Skip to main content

agentmux_srv/server/
http_app_api.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! HTTP adapters over app_api: memory, global memory, fleet stop and stop forwarding.
5//! Split out of server/mod.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.1).
6
7use super::*;
8
9// ---------------------------------------------------------------------------
10// MuxAPI REST handlers (identity / preset / memory).
11//
12// `agent_id` is the agent slug, supplied by agentmux-mcp from its trusted
13// AGENTMUX_AGENT_ID env. Each handler answers a 4xx for caller/validation errors
14// and a 5xx otherwise, by the error's kind (`api_error::ApiError`), then delegates
15// to the shared `app_api::*_impl`.
16// ---------------------------------------------------------------------------
17
18/// A MuxAPI result as its HTTP answer: the value, or the error under the status of its kind
19/// (`api_error::ApiError`). An error that is still a plain `String` gets its kind from its text.
20pub(super) fn app_api_response<T: serde::Serialize>(result: Result<T, impl Into<ApiError>>) -> axum::response::Response {
21    match result {
22        Ok(v) => (StatusCode::OK, Json(v)).into_response(),
23        Err(e) => e.into().into_response(),
24    }
25}
26
27#[derive(serde::Deserialize)]
28pub(super) struct AgentMemoryListQuery {
29    pub(super) agent_id: String,
30}
31
32/// `GET /api/v1/agent/memory/list?agent_id=<slug>` — list the agent's own
33/// native-memory markdown files. Backs the `MemoryList` MCP tool.
34pub(super) async fn handle_agent_memory_list(
35    State(state): State<AppState>,
36    caller: Option<Extension<caller::Caller>>,
37    Query(q): Query<AgentMemoryListQuery>,
38) -> impl IntoResponse {
39    if let Err(e) = actor::require_token(&state, caller.as_deref(), actor::ActorSite::MemoryList, &q.agent_id) {
40        return app_api_response::<()>(Err(e));
41    }
42    app_api_response(app_api::memory_list_impl(&state, app_api::SelfOwner::of(caller.as_deref(), &q.agent_id, "m4c.memory_owner_by_name")))
43}
44
45#[derive(serde::Deserialize)]
46pub(super) struct AgentMemoryReadQuery {
47    pub(super) agent_id: String,
48    pub(super) filename: String,
49}
50
51/// `GET /api/v1/agent/memory/read?agent_id=<slug>&filename=<f>` — read one of
52/// the agent's own memory files. Backs the `MemoryRead` MCP tool.
53pub(super) async fn handle_agent_memory_read(
54    State(state): State<AppState>,
55    caller: Option<Extension<caller::Caller>>,
56    Query(q): Query<AgentMemoryReadQuery>,
57) -> impl IntoResponse {
58    if let Err(e) = actor::require_token(&state, caller.as_deref(), actor::ActorSite::MemoryRead, &q.agent_id) {
59        return app_api_response::<()>(Err(e));
60    }
61    app_api_response(app_api::memory_read_impl(&state, app_api::SelfOwner::of(caller.as_deref(), &q.agent_id, "m4c.memory_owner_by_name"), &q.filename))
62}
63
64#[derive(serde::Deserialize)]
65pub(super) struct AgentMemoryWriteRequest {
66    pub(super) agent_id: String,
67    pub(super) filename: String,
68    pub(super) content: String,
69    /// Same wire shape as the WebSocket RPC's provenance, including a missing
70    /// `detail` defaulting to `{}` rather than `null`.
71    #[serde(default)]
72    pub(super) provenance: Option<crate::backend::rpc_types::NativeMemoryWriteProvenance>,
73}
74
75/// `POST /api/v1/agent/memory/write` — create/overwrite one of the agent's own
76/// memory files (atomic tmp→rename). Backs the `MemoryWrite` MCP tool — the
77/// primary write path an agent actually uses, so `provenance` (optional,
78/// see docs/specs/SPEC_MEMORY_VERSION_CONTROL_AND_ARMORY_AUDIT_2026_08_19.md
79/// §4.1) threads through to the version history here, not just on the
80/// WebSocket RPC's `agent:memory:write_file`.
81pub(super) async fn handle_agent_memory_write(
82    State(state): State<AppState>,
83    caller: Option<Extension<caller::Caller>>,
84    Json(req): Json<AgentMemoryWriteRequest>,
85) -> impl IntoResponse {
86    if let Err(e) = actor::require_token(&state, caller.as_deref(), actor::ActorSite::MemoryWrite, &req.agent_id) {
87        return app_api_response::<()>(Err(e));
88    }
89    let detail_str;
90    let provenance = if let Some(p) = req.provenance.as_ref() {
91        detail_str = p.detail.to_string();
92        Some(app_api::MemoryWriteProvenance { source: &p.source, detail: &detail_str })
93    } else {
94        None
95    };
96    match app_api::memory_write_impl(&state, app_api::SelfOwner::of(caller.as_deref(), &req.agent_id, "m4c.memory_owner_by_name"), &req.filename, &req.content, provenance) {
97        Ok(()) => (StatusCode::OK, Json(json!({ "ok": true }))).into_response(),
98        Err(e) => e.into_response(),
99    }
100}
101
102/// `POST /api/v1/fleet/bulk-stop` — `Stop agents`: close each named agent's tab
103/// (docs/specs/SPEC_STOP_AN_AGENT_ONE_WAY_AND_SHUTDOWN_TOAST_2026_10_23.md).
104/// Backs the `Stop` tool's `agents` action. Infallible per target (never a
105/// single bool): `{ succeeded, failed }`.
106///
107/// Every running agent waits for its user's override (§6.5 of
108/// SPEC_AGENT_SELF_QUIT_2026_09_24.md): 202 with a request per target, or 200
109/// when nothing had to wait (everything refused or already gone). The request
110/// must carry the asking agent's token, which names that agent on the banner
111/// and in the audit log; the optional signed `auth` only identifies the
112/// caller's own block, so that it is refused.
113pub(super) async fn handle_fleet_bulk_stop(
114    State(state): State<AppState>,
115    caller: Option<axum::Extension<crate::server::caller::Caller>>,
116    Json(body): Json<serde_json::Value>,
117) -> impl IntoResponse {
118    let req: crate::backend::rpc_types::CommandFleetBulkStopData = match serde_json::from_value(body.clone()) {
119        Ok(r) => r,
120        Err(e) => return (StatusCode::UNPROCESSABLE_ENTITY, Json(json!({ "error": e.to_string() }))).into_response(),
121    };
122    // An agent stops agents, and is named as the one who did: the window stops them over its own socket.
123    let Some(uid) = caller.as_deref().and_then(crate::server::caller::Caller::uid).map(str::to_string) else {
124        let error = "FORBIDDEN: Stop agents is an agent's tool, so the request must carry that agent's token (AGENTMUX_AGENT_TOKEN)";
125        return (StatusCode::FORBIDDEN, Json(json!({ "error": error }))).into_response();
126    };
127    let by = {
128        let mstore = state.mstore.clone();
129        tokio::task::spawn_blocking(move || mstore.agent_names_by_id(&uid).ok().flatten().map(|row| row.slug)).await.ok().flatten()
130    };
131    let Some(by) = by.filter(|slug| !slug.is_empty()) else {
132        return (StatusCode::FORBIDDEN, Json(json!({ "error": "FORBIDDEN: the token's agent is unknown" }))).into_response();
133    };
134    let caller_block = body
135        .get("auth")
136        .and_then(|a| serde_json::from_value::<agentmux_common::api_types::UiAutomationAuth>(a.clone()).ok())
137        .and_then(|a| ui_handlers::verified_block_id(&state, caller.as_deref(), &a).ok());
138    // `signal` and `staged` no longer mean anything: a close ends the agent
139    // gracefully and force-kills at its own deadline.
140    let mut notes: Vec<String> = Vec::new();
141    if req.signal.is_some() || req.staged.is_some() {
142        notes.push("signal and staged no longer apply: Stop agents closes the agent's tab".to_string());
143    }
144    let (result, pending, left_open) =
145        app_api::fleet::fleet_close_agents_with_override(&state, &by, caller_block.as_deref(), req.targets).await;
146    // An older AgentMux on this machine that predates the override only stopped
147    // these at once. Said here for those; the MCP layer says it for a target
148    // whose window an older instance opened (`effect: stop`).
149    if !left_open.is_empty() {
150        notes.push(format!(
151            "{} run on an older AgentMux on this machine: stopped, but the pane was left open; the user has to close it",
152            left_open.join(", ")
153        ));
154    }
155    let mut out = json!({ "succeeded": result.succeeded, "failed": result.failed });
156    if !notes.is_empty() {
157        out["note"] = json!(notes.join("; "));
158    }
159    if pending.is_empty() {
160        return (StatusCode::OK, Json(out)).into_response();
161    }
162    out["status"] = json!("pending_user_override");
163    out["deadline_ms"] = json!(pending.iter().map(|p| p.deadline_ms).max());
164    out["wait_at_least_ms"] = json!(crate::sagas::pending_shutdown::wait_at_least_ms(pending.iter().map(|p| p.deadline_ms).max().unwrap_or(0)));
165    out["pending"] = json!(pending
166        .iter()
167        .map(|p| json!({ "block_id": p.block_id, "request_id": p.request_id, "effect": p.effect, "deadline_ms": p.deadline_ms }))
168        .collect::<Vec<_>>());
169    (StatusCode::ACCEPTED, Json(out)).into_response()
170}
171
172#[derive(serde::Deserialize)]
173pub(super) struct AgentStopForwardRequest {
174    pub(super) block_id: String,
175    pub(super) signal: Option<String>,
176    /// The asker's name, when the forwarding instance sends one; shown on the banner as a claim.
177    #[serde(default)]
178    pub(super) by: String,
179}
180
181#[derive(serde::Deserialize)]
182pub(super) struct AgentBroadcastForwardRequest {
183    pub(super) block_id: String,
184    pub(super) body: String,
185    pub(super) msg_id: String,
186    pub(super) recipients: usize,
187}
188
189/// A forwarded broadcast as a confirmation names it: the body by its SHA-256, never the words.
190#[derive(serde::Deserialize)]
191pub(super) struct AgentBroadcastConfirmRequest {
192    pub(super) block_id: String,
193    pub(super) body_sha256: String,
194    pub(super) msg_id: String,
195    pub(super) recipients: usize,
196}
197
198/// `POST /agentmux/agent/broadcast`: another channel on this machine asks this
199/// one to deliver a Swarm broadcast to one of its agent panes (same trust model
200/// as the stop forward above: loopback, this instance's own auth key). The
201/// header is built here; the caller supplies only the body.
202pub(super) async fn handle_agent_broadcast_forward(
203    State(state): State<AppState>,
204    caller: Option<axum::Extension<super::caller::Caller>>,
205    Json(req): Json<AgentBroadcastForwardRequest>,
206) -> impl IntoResponse {
207    // The forwarding instance is a server, not an agent: a request that carries an agent's token is that agent asking.
208    if caller.as_deref().and_then(super::caller::Caller::uid).is_some() {
209        return (StatusCode::FORBIDDEN, Json(serde_json::json!({ "success": false, "error": "FORBIDDEN: a Swarm broadcast arrives as the operator's own words and comes from the AgentMux window; an agent broadcasts as itself with the Message tool" }))).into_response();
210    }
211    match app_api::fleet::deliver_forwarded_broadcast(&state, &req.block_id, &req.body, &req.msg_id, req.recipients).await {
212        Ok(()) => (StatusCode::OK, Json(serde_json::json!({ "success": true }))).into_response(),
213        Err(e) => (StatusCode::OK, Json(serde_json::json!({ "success": false, "error": e }))).into_response(),
214    }
215}
216
217/// `POST /agentmux/agent/broadcast/confirm`: another instance on this machine asks whether this
218/// one sent that forward from the operator's window. Answers yes once, and only for a forward this
219/// instance sent; a request that carries an agent's token is refused.
220pub(super) async fn handle_agent_broadcast_confirm(
221    caller: Option<axum::Extension<super::caller::Caller>>,
222    Json(req): Json<AgentBroadcastConfirmRequest>,
223) -> impl IntoResponse {
224    if caller.as_deref().and_then(super::caller::Caller::uid).is_some() {
225        return (StatusCode::FORBIDDEN, Json(serde_json::json!({ "confirmed": false, "error": "FORBIDDEN: only an AgentMux instance confirms a forwarded broadcast" }))).into_response();
226    }
227    let confirmed = app_api::fleet::confirm_forward(&req.msg_id, &req.block_id, &req.body_sha256, req.recipients);
228    (StatusCode::OK, Json(serde_json::json!({ "confirmed": confirmed }))).into_response()
229}
230
231#[derive(serde::Deserialize)]
232pub(super) struct AgentStopPendingForwardRequest {
233    pub(super) block_id: String,
234    pub(super) signal: Option<String>,
235    /// The asking agent, as the forwarding instance verified it. Shown on the
236    /// banner; this instance takes it as claimed.
237    #[serde(default)]
238    pub(super) by: String,
239    /// `close`: close its tab, as `Stop agents` does. Absent (an instance that
240    /// predates it) or `stop`: stop it and keep its pane.
241    #[serde(default)]
242    pub(super) mode: String,
243}
244
245/// `POST /agentmux/agent/stop-pending` — another instance on this machine
246/// forwards an agent's `FleetBulkStop` for a block running HERE: open this
247/// instance's own override window (banner, chime, Keep running) rather than
248/// stopping at once. The caller polls `/api/v1/agent/shutdown/{request_id}`
249/// here. Same trust model and gate as `/agentmux/agent/stop`.
250pub(super) async fn handle_agent_stop_pending_forward(
251    State(state): State<AppState>,
252    caller: Option<axum::Extension<super::caller::Caller>>,
253    Json(req): Json<AgentStopPendingForwardRequest>,
254) -> impl IntoResponse {
255    let close = req.mode == "close";
256    let by = forwarded_asker(&state, caller.as_deref(), &req.by).await;
257    let by = by.as_str();
258    if close {
259        // A close needs the block and an agent in it, not a running controller:
260        // a stopped agent's pane is closed too.
261        let here = state.srv_state.lock().await.blocks.contains_key(&req.block_id);
262        if !here {
263            let error = format!("block not found: {}", req.block_id);
264            return (StatusCode::OK, Json(json!({ "success": false, "error": error }))).into_response();
265        }
266        if !crate::sagas::orphan_reaper::is_agent_block(&state, &req.block_id) {
267            let error = "not an agent pane: close it with Stop with action \"pane\"".to_string();
268            return (StatusCode::OK, Json(json!({ "success": false, "error": error }))).into_response();
269        }
270    } else if crate::backend::blockcontroller::get_controller(&req.block_id).is_none() {
271        let error = format!("NOT_RUNNING: no controller for block {}", req.block_id);
272        return (StatusCode::OK, Json(json!({ "success": false, "error": error }))).into_response();
273    }
274    open_forwarded_window(&state, &req.block_id, req.signal, close, by)
275}
276
277/// Who a request from another instance says is asking: the token's agent when it carries one, else the name the
278/// forwarding instance sent, shown as a claim.
279async fn forwarded_asker(state: &AppState, caller: Option<&super::caller::Caller>, claimed_by: &str) -> String {
280    let token_agent = match caller.and_then(super::caller::Caller::uid).map(str::to_string) {
281        Some(uid) => {
282            let mstore = state.mstore.clone();
283            tokio::task::spawn_blocking(move || mstore.agent_names_by_id(&uid).ok().flatten().map(|row| row.slug))
284                .await
285                .ok()
286                .flatten()
287                .filter(|slug| !slug.is_empty())
288        }
289        None => None,
290    };
291    match (token_agent, claimed_by.trim().is_empty()) {
292        (Some(slug), _) => slug,
293        (None, true) => "an agent on another AgentMux".to_string(),
294        (None, false) => format!("{} (as claimed by another AgentMux)", claimed_by.trim()),
295    }
296}
297
298/// Opens this instance's own override window for a stop or close another instance asked for, and answers with it.
299fn open_forwarded_window(state: &AppState, block_id: &str, signal: Option<String>, close: bool, by: &str) -> axum::response::Response {
300    let action = if close {
301        crate::sagas::pending_shutdown::Action::CloseTab { detail: format!("asked by {by} (Stop agents, from another AgentMux)") }
302    } else {
303        crate::sagas::pending_shutdown::Action::Stop { signal, stop_background: None }
304    };
305    let v = crate::sagas::pending_shutdown::request(state, block_id, by, "FleetBulkStop", "", action);
306    state.reactive_handler.log_fleet_action_audit(
307        Some(by),
308        &v.target,
309        block_id,
310        "fleet.bulk-stop",
311        true,
312        None,
313        &v.request_id,
314        Some(&format!("{} (forwarded from another channel)", crate::sagas::pending_shutdown::audit_note(state, &v, by, "FleetBulkStop"))),
315    );
316    let mut pending = serde_json::to_value(&v).unwrap_or_default();
317    pending["joined"] = json!(v.joined);
318    (StatusCode::OK, Json(json!({ "success": true, "pending": pending }))).into_response()
319}
320
321/// `POST /agentmux/agent/stop` — the cross-channel bulk-stop forward
322/// target. See `fleet_bulk_stop_impl`'s doc comment for the caller side. The
323/// request names its asker itself and cannot be checked, so it goes through this
324/// instance's own override window (banner, chime, Keep running) like
325/// `/agentmux/agent/stop-pending`: the stop happens after 30 s unless the user
326/// keeps the agent running.
327pub(super) async fn handle_agent_stop_forward(
328    State(state): State<AppState>,
329    caller: Option<axum::Extension<super::caller::Caller>>,
330    Json(req): Json<AgentStopForwardRequest>,
331) -> impl IntoResponse {
332    // The forwarding instance is a server acting for its window: an agent that stops another goes through the override window.
333    if caller.as_deref().and_then(super::caller::Caller::uid).is_some() {
334        let error = "FORBIDDEN: an agent stops agents with the Stop tool, which asks the user first";
335        return (StatusCode::FORBIDDEN, Json(serde_json::json!({ "success": false, "error": error }))).into_response();
336    }
337    if crate::backend::blockcontroller::get_controller(&req.block_id).is_none() {
338        let error = format!("NOT_RUNNING: no controller for block {}", req.block_id);
339        return (StatusCode::OK, Json(json!({ "success": false, "error": error }))).into_response();
340    }
341    let by = forwarded_asker(&state, None, &req.by).await;
342    open_forwarded_window(&state, &req.block_id, req.signal, false, &by)
343}
344
345#[derive(serde::Deserialize)]
346pub(super) struct AgentMemoryHistoryQuery {
347    pub(super) agent_id: String,
348    pub(super) filename: String,
349}
350
351/// `GET /api/v1/agent/memory/history?agent_id=<slug>&filename=<f>` — list
352/// every recorded version of one memory file, newest first. Backs the
353/// `MemoryHistory` MCP tool.
354pub(super) async fn handle_agent_memory_history(
355    State(state): State<AppState>,
356    caller: Option<Extension<caller::Caller>>,
357    Query(q): Query<AgentMemoryHistoryQuery>,
358) -> impl IntoResponse {
359    if let Err(e) = actor::require_token(&state, caller.as_deref(), actor::ActorSite::MemoryHistory, &q.agent_id) {
360        return app_api_response::<()>(Err(e));
361    }
362    app_api_response(app_api::memory_history_impl(&state, app_api::SelfOwner::of(caller.as_deref(), &q.agent_id, "m4c.memory_owner_by_name"), &q.filename))
363}
364
365#[derive(serde::Deserialize)]
366pub(super) struct AgentMemoryDiffQuery {
367    pub(super) agent_id: String,
368    pub(super) from_version_id: String,
369    pub(super) to_version_id: String,
370}
371
372/// `GET /api/v1/agent/memory/diff?agent_id=<slug>&from_version_id=&to_version_id=`
373/// — a line-based diff between two recorded versions, both of which must
374/// belong to `agent_id` (reagent P1 — see `memory_diff_impl`'s own doc for
375/// why). Backs the `MemoryDiff` MCP tool.
376pub(super) async fn handle_agent_memory_diff(
377    State(state): State<AppState>,
378    caller: Option<Extension<caller::Caller>>,
379    Query(q): Query<AgentMemoryDiffQuery>,
380) -> impl IntoResponse {
381    if let Err(e) = actor::require_token(&state, caller.as_deref(), actor::ActorSite::MemoryDiff, &q.agent_id) {
382        return app_api_response::<()>(Err(e));
383    }
384    app_api_response(app_api::memory_diff_impl(&state, app_api::SelfOwner::of(caller.as_deref(), &q.agent_id, "m4c.memory_owner_by_name"), &q.from_version_id, &q.to_version_id))
385}
386
387#[derive(serde::Deserialize)]
388pub(super) struct AgentMemoryRevertRequest {
389    pub(super) agent_id: String,
390    pub(super) filename: String,
391    pub(super) target_version_id: String,
392}
393
394/// `POST /api/v1/agent/memory/revert` — restore a memory file's live
395/// content to a prior version, recorded as a NEW version (`source:
396/// "revert"`) — never rewrites or deletes history. Backs the
397/// `MemoryRevert` MCP tool.
398pub(super) async fn handle_agent_memory_revert(
399    State(state): State<AppState>,
400    caller: Option<Extension<caller::Caller>>,
401    Json(req): Json<AgentMemoryRevertRequest>,
402) -> impl IntoResponse {
403    if let Err(e) = actor::require_token(&state, caller.as_deref(), actor::ActorSite::MemoryRevert, &req.agent_id) {
404        return app_api_response::<()>(Err(e));
405    }
406    app_api_response(app_api::memory_revert_impl(&state, app_api::SelfOwner::of(caller.as_deref(), &req.agent_id, "m4c.memory_owner_by_name"), &req.filename, &req.target_version_id))
407}
408
409#[derive(serde::Deserialize)]
410pub(super) struct AgentGlobalMemoryWriteProvenanceReq {
411    /// A short label for where the write came from; `agent_inferred` when the object does not say.
412    #[serde(default = "default_agent_globalmemory_write_source")]
413    pub(super) source: String,
414    // Same "default() on a bare Value yields Null, not {}" trap as
415    // NativeMemoryWriteProvenance in rpc_types — see `detail` there.
416    #[serde(default = "default_agent_globalmemory_write_detail")]
417    pub(super) detail: serde_json::Value,
418    /// Any other key the caller put in the object (the tool's description names none): kept with `detail`.
419    #[serde(flatten)]
420    pub(super) extra: serde_json::Map<String, serde_json::Value>,
421}
422
423impl AgentGlobalMemoryWriteProvenanceReq {
424    /// What is recorded as the version's detail: `detail`, with any other key of the object beside it.
425    pub(super) fn detail_json(&self) -> String {
426        if self.extra.is_empty() {
427            return self.detail.to_string();
428        }
429        let mut merged = match &self.detail {
430            serde_json::Value::Object(map) => map.clone(),
431            serde_json::Value::Null => serde_json::Map::new(),
432            other => serde_json::Map::from_iter([("detail".to_string(), other.clone())]),
433        };
434        for (key, value) in &self.extra {
435            merged.entry(key.clone()).or_insert_with(|| value.clone());
436        }
437        serde_json::Value::Object(merged).to_string()
438    }
439}
440
441pub(super) fn default_agent_globalmemory_write_source() -> String {
442    "agent_inferred".to_string()
443}
444
445#[cfg(test)]
446mod global_memory_provenance_tests {
447    use super::*;
448
449    fn parse(value: serde_json::Value) -> AgentGlobalMemoryWriteProvenanceReq {
450        serde_json::from_value(value).expect("any object is accepted")
451    }
452
453    #[test]
454    fn an_object_without_source_is_taken_as_agent_inferred_and_its_keys_are_kept() {
455        let p = parse(serde_json::json!({ "reason": "slimming", "task": 47935 }));
456        assert_eq!(p.source, "agent_inferred");
457        let detail: serde_json::Value = serde_json::from_str(&p.detail_json()).unwrap();
458        assert_eq!(detail, serde_json::json!({ "reason": "slimming", "task": 47935 }));
459    }
460
461    #[test]
462    fn source_and_detail_are_read_as_before_and_an_empty_object_is_fine() {
463        let p = parse(serde_json::json!({ "source": "human", "detail": { "why": "x" } }));
464        assert_eq!((p.source.as_str(), p.detail_json().as_str()), ("human", r#"{"why":"x"}"#));
465        let empty = parse(serde_json::json!({}));
466        assert_eq!((empty.source.as_str(), empty.detail_json().as_str()), ("agent_inferred", "{}"));
467        // a detail that is not an object keeps its place beside the other keys; detail wins a clash
468        let mixed = parse(serde_json::json!({ "detail": "text", "note": 1 }));
469        let merged: serde_json::Value = serde_json::from_str(&mixed.detail_json()).unwrap();
470        assert_eq!(merged, serde_json::json!({ "detail": "text", "note": 1 }));
471    }
472}
473
474pub(super) fn default_agent_globalmemory_write_detail() -> serde_json::Value {
475    serde_json::json!({})
476}
477
478#[derive(serde::Deserialize)]
479pub(super) struct AgentGlobalMemoryWriteRequest {
480    pub(super) agent_id: String,
481    #[serde(default)]
482    pub(super) id: Option<String>,
483    pub(super) name: String,
484    pub(super) content: String,
485    #[serde(default)]
486    pub(super) provenance: Option<AgentGlobalMemoryWriteProvenanceReq>,
487    /// `fleet` or `machine`: where the entry goes. Absent leaves it as it is (a new entry follows the fleet).
488    #[serde(default)]
489    pub(super) reach: Option<String>,
490}
491
492/// `POST /api/v1/agent/globalmemory/write` — create a new ordinary Global
493/// Memory entry, or update an existing one by `id`. Never reaches a
494/// system-tier row either way — see `global_memory_write_impl`'s own doc
495/// comment for the full invariant. Backs the `GlobalMemoryWrite` MCP tool.
496pub(super) async fn handle_agent_globalmemory_write(
497    State(state): State<AppState>,
498    caller: Option<Extension<caller::Caller>>,
499    Json(req): Json<AgentGlobalMemoryWriteRequest>,
500) -> impl IntoResponse {
501    // The writer is the agent the request's token proves, never a name in the body; a request with no token is refused.
502    let (agent_id, written_by_uid) = match actor::require_token_actor(&state, caller.as_deref(), actor::ActorSite::GlobalMemoryWrite, &req.agent_id).await {
503        Ok(who) => who,
504        Err(e) => return app_api_response::<()>(Err(e)),
505    };
506    let detail_str;
507    let provenance = if let Some(p) = req.provenance.as_ref() {
508        detail_str = p.detail_json();
509        Some(app_api::GlobalMemoryWriteProvenance { source: &p.source, detail: &detail_str })
510    } else {
511        None
512    };
513    app_api_response(app_api::global_memory_write_with_reach_impl(
514        &state,
515        &agent_id,
516        &written_by_uid,
517        req.id.as_deref(),
518        &req.name,
519        &req.content,
520        provenance,
521        req.reach.as_deref(),
522    ))
523}
524
525#[derive(serde::Deserialize)]
526pub(super) struct AgentGlobalMemoryReachRequest {
527    pub(super) id: String,
528    pub(super) reach: String,
529    /// The name the caller gives for itself; the token decides who is recorded.
530    #[serde(default)]
531    pub(super) agent_id: String,
532}
533
534/// `POST /api/v1/agent/globalmemory/reach` — set where an existing Global Memory entry goes:
535/// `fleet` (every proven machine) or `machine` (this one only). Backs the `reach` action of the
536/// Memory tool.
537pub(super) async fn handle_agent_globalmemory_reach(
538    State(state): State<AppState>,
539    caller: Option<Extension<caller::Caller>>,
540    Json(req): Json<AgentGlobalMemoryReachRequest>,
541) -> impl IntoResponse {
542    let (agent_id, _) = match actor::require_token_actor(&state, caller.as_deref(), actor::ActorSite::GlobalMemoryWrite, &req.agent_id).await {
543        Ok(who) => who,
544        Err(e) => return app_api_response::<()>(Err(e)),
545    };
546    app_api_response(app_api::global_memory_reach_impl(&state, &agent_id, &req.id, &req.reach))
547}
548
549/// `GET /api/v1/agent/globalmemory/list` — every Global Memory entry, system
550/// rows first and flagged `system`, summary only (id/name/updated_at/system, no
551/// content). Read, write and remove still refuse a system id. Backs the
552/// `GlobalMemoryList` MCP tool. See
553/// `docs/specs/SPEC_GLOBAL_MEMORY_LIST_SYSTEM_ROWS_2026_10_02.md`.
554pub(super) async fn handle_agent_globalmemory_list(State(state): State<AppState>) -> impl IntoResponse {
555    app_api_response(app_api::global_memory_list_impl(&state))
556}
557
558#[derive(serde::Deserialize)]
559pub(super) struct AgentGlobalMemoryReadQuery {
560    pub(super) id: String,
561}
562
563/// `GET /api/v1/agent/globalmemory/read?id=<id>` — full content of one
564/// ordinary Global Memory entry. Backs the `GlobalMemoryRead` MCP tool.
565pub(super) async fn handle_agent_globalmemory_read(
566    State(state): State<AppState>,
567    Query(q): Query<AgentGlobalMemoryReadQuery>,
568) -> impl IntoResponse {
569    app_api_response(app_api::global_memory_read_impl(&state, &q.id))
570}
571
572#[derive(serde::Deserialize)]
573pub(super) struct AgentGlobalMemoryRemoveRequest {
574    pub(super) id: String,
575    /// The name the caller gives for itself; the token decides who is recorded.
576    #[serde(default)]
577    pub(super) agent_id: String,
578}
579
580/// `POST /api/v1/agent/globalmemory/remove` — demote a Global Memory entry
581/// (clears `is_global`; the bundle row itself survives, same as Memory →
582/// Global's own "Remove" button), recorded as a `remove` version under the
583/// agent the request's token names so the removal can be seen and undone. A
584/// request without that token is refused. Backs the `GlobalMemoryRemove` MCP
585/// tool.
586pub(super) async fn handle_agent_globalmemory_remove(
587    State(state): State<AppState>,
588    caller: Option<Extension<caller::Caller>>,
589    Json(req): Json<AgentGlobalMemoryRemoveRequest>,
590) -> impl IntoResponse {
591    let (agent_id, written_by_uid) =
592        match actor::require_token_actor(&state, caller.as_deref(), actor::ActorSite::GlobalMemoryRemove, &req.agent_id).await {
593            Ok(who) => who,
594            Err(e) => return app_api_response::<()>(Err(e)),
595        };
596    app_api_response(app_api::global_memory_remove_impl(&state, &agent_id, &written_by_uid, &req.id))
597}
598
599#[derive(serde::Deserialize)]
600pub(super) struct AgentGlobalMemoryHistoryQuery {
601    pub(super) id: String,
602}
603
604/// `GET /api/v1/agent/globalmemory/history?id=<id>` — list every recorded
605/// version of one Global Memory entry, newest first. Refuses a system-tier,
606/// blank, or non-global id the same way `read`/`remove` already do — see
607/// `global_memory_history_impl`'s own doc comment. Backs the
608/// `GlobalMemoryHistory` MCP tool.
609pub(super) async fn handle_agent_globalmemory_history(
610    State(state): State<AppState>,
611    Query(q): Query<AgentGlobalMemoryHistoryQuery>,
612) -> impl IntoResponse {
613    app_api_response(app_api::global_memory_history_impl(&state, &q.id))
614}
615
616#[derive(serde::Deserialize)]
617pub(super) struct AgentGlobalMemoryDiffQuery {
618    pub(super) id: String,
619    pub(super) from_version_id: String,
620    pub(super) to_version_id: String,
621}
622
623/// `GET /api/v1/agent/globalmemory/diff?id=<id>&from_version_id=&to_version_id=`
624/// — a line-based diff between two recorded versions, both of which must
625/// belong to `id` (same ownership check as `/api/v1/agent/memory/diff`'s
626/// `agent_id` scoping — see `global_memory_diff_impl`'s own doc comment for
627/// why). Backs the `GlobalMemoryDiff` MCP tool.
628pub(super) async fn handle_agent_globalmemory_diff(
629    State(state): State<AppState>,
630    Query(q): Query<AgentGlobalMemoryDiffQuery>,
631) -> impl IntoResponse {
632    app_api_response(app_api::global_memory_diff_impl(&state, &q.id, &q.from_version_id, &q.to_version_id))
633}
634
635#[derive(serde::Deserialize)]
636pub(super) struct AgentGlobalMemoryRevertRequest {
637    pub(super) agent_id: String,
638    pub(super) id: String,
639    pub(super) version_id: String,
640}
641
642/// `POST /api/v1/agent/globalmemory/revert` — restore a Global Memory
643/// entry's live content to a prior recorded version, recorded as a NEW
644/// version (`source: "revert"`) — never rewrites or deletes history, same
645/// as `/api/v1/agent/memory/revert`. Never reaches a system-tier row — see
646/// `global_memory_revert_impl`'s own doc comment. Backs the
647/// `GlobalMemoryRevert` MCP tool.
648pub(super) async fn handle_agent_globalmemory_revert(
649    State(state): State<AppState>,
650    caller: Option<Extension<caller::Caller>>,
651    Json(req): Json<AgentGlobalMemoryRevertRequest>,
652) -> impl IntoResponse {
653    // As for write: the agent the token proves, and no request without one.
654    let (agent_id, written_by_uid) = match actor::require_token_actor(&state, caller.as_deref(), actor::ActorSite::GlobalMemoryRevert, &req.agent_id).await {
655        Ok(who) => who,
656        Err(e) => return app_api_response::<()>(Err(e)),
657    };
658    app_api_response(app_api::global_memory_revert_impl(
659        &state,
660        &agent_id,
661        &written_by_uid,
662        &req.id,
663        &req.version_id,
664    ))
665}
666
667#[cfg(test)]
668mod tests {
669    use super::*;
670
671    /// One classification for MuxAPI and naming routes: a missing
672    /// resource is a 404 on both, where MuxAPI used to answer 400.
673    #[test]
674    fn an_error_that_is_a_plain_string_gets_its_status_from_its_text() {
675        let status_of = |e: &str| ApiError::from(e.to_string()).status();
676        assert_eq!(status_of("FORBIDDEN: not your memory"), StatusCode::FORBIDDEN);
677        assert_eq!(status_of("globalmemory.read: not found id=x"), StatusCode::NOT_FOUND);
678        assert_eq!(status_of("tab not found: tab-1"), StatusCode::NOT_FOUND);
679        for bad in ["provide id or name", "not a regular file", "file too large", "invalid filename"] {
680            assert_eq!(status_of(bad), StatusCode::BAD_REQUEST, "{bad}");
681        }
682        assert_eq!(status_of("database is locked"), StatusCode::INTERNAL_SERVER_ERROR);
683    }
684}