agentmux_srv/server/app_api/
folder_overlap_ask.rs1use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::{Extension, Json};
17use serde::Deserialize;
18use serde_json::{json, Value};
19
20use crate::backend::folder_overlap as overlap;
21use crate::backend::folder_overlap_asks::{asks, Asked, FolderAsk};
22use crate::backend::storage::agents::AgentDefinition;
23use crate::server::caller::Caller;
24use crate::server::state::AppState;
25
26pub(crate) const AUDIT_ASK: &str = "folder-overlap.ask";
28
29#[derive(Debug, Deserialize)]
30pub(crate) struct AskRequest {
31 pub(crate) host: String,
33 pub(crate) container: String,
35}
36
37#[derive(Debug)]
38pub(crate) struct Refusal {
39 pub status: StatusCode,
40 pub message: String,
41}
42
43pub(crate) fn refuse(status: StatusCode, message: impl Into<String>) -> Refusal {
44 Refusal { status, message: message.into() }
45}
46
47pub(crate) struct Asker {
49 pub slug: String,
50 pub name: String,
51 pub block_id: String,
52}
53
54fn asker_of(state: &AppState, caller: Option<&Caller>) -> Result<Asker, Refusal> {
55 asker_named(state, caller, "no agent token: Agents ask_go_ahead is an agent's ask; the person goes ahead from the AgentMux window")
56}
57
58pub(crate) fn asker_named(state: &AppState, caller: Option<&Caller>, no_token: &str) -> Result<Asker, Refusal> {
60 let Some(uid) = caller.and_then(Caller::uid) else {
61 return Err(refuse(StatusCode::UNAUTHORIZED, no_token));
62 };
63 let def = state
64 .mstore
65 .agent_def_get(uid)
66 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("ask_go_ahead: {e}")))?
67 .ok_or_else(|| refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"))?;
68 let block_id = crate::backend::reactive::handler::get_global_handler().block_for_uid(uid).unwrap_or_default();
69 Ok(Asker { slug: def.slug, name: def.name, block_id })
70}
71
72fn agent_named(state: &AppState, named: &str, what: &str) -> Result<AgentDefinition, Refusal> {
73 let named = named.trim();
74 crate::backend::agent_resolve::resolve_agent_id(&state.mstore, named)
75 .ok()
76 .and_then(|id| state.mstore.agent_def_get(&id).ok().flatten())
77 .ok_or_else(|| refuse(StatusCode::NOT_FOUND, format!("no agent '{named}' on this machine ({what})")))
78}
79
80pub(crate) fn ask(state: &AppState, asker: &Asker, req: &AskRequest, now_ms: u64) -> Result<Value, Refusal> {
82 let host = agent_named(state, &req.host, "host")?;
83 let container = agent_named(state, &req.container, "container")?;
84 if !overlap::is_a_pair(&state.mstore, &host.id, &container.id) {
85 return Err(refuse(StatusCode::BAD_REQUEST, "Agents ask_go_ahead needs host: a host agent and container: a container agent"));
86 }
87 if overlap::accepted(&host.id, &container.id) {
88 return Ok(json!({ "status": "chosen", "note": "the person has gone ahead with these two agents: retry what was refused" }));
89 }
90 let shared = overlap::of(&state.mstore, &host, Some(&overlap::open_folder(&host))).iter().any(|o| o.container_id == container.id);
91 if !shared {
92 return Ok(json!({ "status": "not_needed", "note": "these two agents share no folder, so there is nothing to go ahead with" }));
93 }
94 if asker.block_id.is_empty() {
95 return Err(refuse(StatusCode::CONFLICT, "Agents ask_go_ahead shows its card in the asking agent's pane, and this agent has no open pane to show it in"));
96 }
97 let ask = FolderAsk {
98 host_id: host.id.clone(),
99 host_name: host.name.clone(),
100 container_id: container.id.clone(),
101 container_name: container.name.clone(),
102 agent: asker.name.clone(),
103 block_id: asker.block_id.clone(),
104 requested_ms: now_ms,
105 };
106 match asks().ask(ask, now_ms) {
107 Asked::Waiting { new, .. } => {
108 super::folder_overlap::publish_asks(state);
109 if new {
110 super::folder_overlap::audit(state, Some(&asker.slug), AUDIT_ASK, &host.id, &container.id, &asker.block_id);
111 }
112 Ok(json!({
113 "status": "asked",
114 "note": "the person is asked in your pane; ask_go_ahead again for their answer, then retry what was refused",
115 }))
116 }
117 Asked::Declined { retry_after_ms } => Ok(json!({
118 "status": "declined",
119 "retry_after_seconds": retry_after_ms.div_ceil(1000),
120 "note": "the person said no to these two agents; give them separate workspaces, or bind the shared folder read-only into the container agent (a volume ending in :ro)",
121 })),
122 }
123}
124
125pub(crate) async fn handle_folder_overlap_ask(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<AskRequest>) -> Response {
126 let caller = caller.map(|Extension(c)| c);
127 let run = || -> Result<Value, Refusal> {
128 let asker = asker_of(&state, caller.as_ref())?;
129 ask(&state, &asker, &req, agentmux_common::time::now_ms_u64())
130 };
131 match run() {
132 Ok(body) => Json(body).into_response(),
133 Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
134 }
135}