Skip to main content

agentmux_srv/server/app_api/
folder_overlap_ask.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents ask_go_ahead` (`POST /api/v1/agent/folder-overlap-ask`): an agent that was refused for a host agent that
5//! shares a folder with a container agent asks the person to go ahead with that pair. srv keeps the ask
6//! (`backend::folder_overlap_asks`), the window shows it as a card in the asking agent's pane, and the person answers
7//! with one click, which only their window can do (`app_api::folder_overlap`). Asking again says where the ask
8//! stands: `asked` while the person has not answered, `chosen` once they went ahead, `declined` after a no.
9//!
10//! The caller is the agent its token names; a request without one is refused, so an ask is never the person's. The
11//! ask is recorded in the audit log under the asking agent, and the person's answer under the person.
12
13use 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
26/// The audit entry's action for an ask.
27pub(crate) const AUDIT_ASK: &str = "folder-overlap.ask";
28
29#[derive(Debug, Deserialize)]
30pub(crate) struct AskRequest {
31    /// The host agent, by id or slug.
32    pub(crate) host: String,
33    /// The container agent, by id or slug.
34    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
47/// The agent asking, and the pane its card shows in (empty when it has none).
48pub(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
58/// The agent a request's token names, with the pane its card shows in. `no_token` is what a request with none is told.
59pub(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
80/// Where an ask for the pair stands, asking the person when they have not been asked.
81pub(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}