Skip to main content

agentmux_srv/server/prep/
handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The two ways a window is answered from outside: the agent's `Agents ready`
5//! (`POST /api/v1/agent/self/ready`) and the person's "Switch now" (`agent.prep.now`).
6
7use std::sync::Arc;
8
9use axum::extract::State;
10use axum::http::StatusCode;
11use axum::response::{IntoResponse, Response};
12use axum::{Extension, Json};
13use serde::{Deserialize, Serialize};
14use serde_json::json;
15
16use crate::backend::rpc::engine::WshRpcEngine;
17use crate::backend::rpc_types::COMMAND_AGENT_PREP_NOW;
18use crate::server::caller::Caller;
19use crate::server::AppState;
20
21use super::ledger::{self, Answer};
22
23#[derive(Debug, Deserialize)]
24pub struct ReadyRequest {
25    /// The caller's slug, which its token must name.
26    agent: String,
27    #[serde(default)]
28    handoff: Option<String>,
29    #[serde(default)]
30    more_time: bool,
31    #[serde(default)]
32    why: Option<String>,
33}
34
35fn refused(status: StatusCode, why: &str) -> Response {
36    (status, Json(json!({ "error": why }))).into_response()
37}
38
39/// `POST /api/v1/agent/self/ready`: the caller answers the window open for its own agent. Acts only
40/// on the pane its token names, never on a name, so a prep id that leaks is no use to another agent.
41pub async fn handle_ready_self(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<ReadyRequest>) -> Response {
42    let Some(block_id) = crate::server::actor::own_pane_by_token(&state.mstore, caller.as_deref(), req.agent.trim()) else {
43        return refused(StatusCode::UNAUTHORIZED, "no pane for this agent token: Agents ready answers only the calling agent's own change");
44    };
45    let def_id = match state.mstore.get::<crate::backend::obj::Block>(&block_id) {
46        Ok(Some(b)) => crate::backend::obj::meta_get_string(&b.meta, "agentId", ""),
47        _ => String::new(),
48    };
49    if def_id.is_empty() {
50        return refused(StatusCode::BAD_REQUEST, "the pane is not an agent's");
51    }
52    let slug = req.agent.trim().to_string();
53    let answer = Answer { handoff: req.handoff, more_time: req.more_time, why: req.why };
54    let result = tokio::task::spawn_blocking(move || ledger::answer(&state, &def_id, &slug, answer)).await;
55    match result {
56        Ok(Ok(body)) => Json(body).into_response(),
57        Ok(Err(why)) => refused(StatusCode::CONFLICT, &why),
58        Err(e) => refused(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
59    }
60}
61
62/// `agent.prep.now`: end the window the agent is in and let the change run.
63#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
64#[ts(export, export_to = "../../../frontend/types/rpc/")]
65pub struct AgentPrepNowReq {
66    pub agent_id: String,
67}
68
69#[derive(Debug, Clone, Serialize, ts_rs::TS)]
70#[ts(export, export_to = "../../../frontend/types/rpc/")]
71pub struct AgentPrepNowResult {
72    /// Whether a window was open for the agent.
73    pub ended: bool,
74}
75
76/// Registers `agent.prep.now`. Open to agents as well as the window, as every account change is: the
77/// audit row of the change names whoever asked.
78pub fn register(engine: &Arc<WshRpcEngine>, _state: &AppState) {
79    engine.register_typed(COMMAND_AGENT_PREP_NOW, move |req: AgentPrepNowReq, ctx| async move {
80        if ctx.agent_id.is_empty() {
81            ctx.operator_only("only the AgentMux window or an agent ends a change's window")?;
82        }
83        Ok(AgentPrepNowResult { ended: ledger::person_says_now(req.agent_id.trim(), &ctx.agent_id).is_ok() })
84    });
85}