Skip to main content

agentmux_srv/server/app_api/
app_update.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `app.update-status`: what srv knows about newer AgentMux releases
5//! (`backend::update::check`), for a window that opens after the last
6//! `app:updatestatus` event. Downloading the release it found
7//! (`backend::update::download`), restarting into it once agents are idle and
8//! stopping that wait (`backend::update::restart`) are the user's clicks only:
9//! they come through the host (`POST /api/v1/host/app_update`), which agents,
10//! holding the instance auth key, can't impersonate.
11//! `app.upgrade-requests`: agents' requests waiting for the user
12//! (`backend::upgrade_request`); the user's answer comes only through the
13//! host (`POST /api/v1/host/upgrade_request`), which agents can't impersonate.
14//! And the agent's side over HTTP: the `App` tool's `version`
15//! (`GET /api/v1/app/update-status`) and `upgrade`
16//! (`POST /api/v1/agent/self/upgrade`).
17
18use super::*;
19
20pub fn register(engine: &Arc<WshRpcEngine>, _state: &AppState) {
21    engine.register_typed(COMMAND_APP_UPDATE_STATUS, move |_req: Option<NoArgsReq>, _ctx| async move {
22        Ok::<_, String>(crate::backend::update::check::current_status())
23    });
24    // Read-only, and rate-limited inside: anyone may ask.
25    engine.register_typed(COMMAND_APP_UPDATE_CHECK, move |_req: Option<NoArgsReq>, _ctx| async move {
26        crate::backend::update::check::check_now().await
27    });
28    engine.register_typed(COMMAND_APP_UPGRADE_REQUESTS, move |_req: Option<NoArgsReq>, _ctx| async move {
29        Ok::<_, String>(crate::backend::upgrade_request::UpgradeRequestsEvent {
30            requests: crate::backend::upgrade_request::list(),
31        })
32    });
33}
34
35/// The user's click in the version panel, relayed by the host.
36#[derive(Debug, serde::Deserialize)]
37pub(crate) struct HostAppUpdateAction {
38    /// `download`, `restart` or `cancel`.
39    action: String,
40    /// `restart`: without waiting for agents to finish their turn.
41    #[serde(default)]
42    now: bool,
43}
44
45/// `POST /api/v1/host/app_update`: Download, Upgrade & restart (or Restart
46/// now) and Cancel in the version panel, relayed by the CEF host with its own
47/// token. Answers the status after the action, as `data`.
48pub(crate) async fn handle_host_app_update(
49    axum::extract::State(state): axum::extract::State<AppState>,
50    headers: axum::http::HeaderMap,
51    axum::Json(body): axum::Json<HostAppUpdateAction>,
52) -> axum::response::Response {
53    use axum::http::StatusCode;
54    use axum::response::IntoResponse;
55    use axum::Json;
56    if !crate::server::ui_handlers::from_host(&state, &headers).await {
57        return (StatusCode::FORBIDDEN, Json(json!({ "ok": false, "error": "only the AgentMux host can do that" })))
58            .into_response();
59    }
60    let result = match body.action.as_str() {
61        "download" => crate::backend::update::download::start(),
62        "restart" => crate::backend::update::restart::start(body.now, Vec::new()),
63        "cancel" => crate::backend::update::restart::cancel(),
64        other => Err(format!("unknown action {other:?}")),
65    };
66    match result {
67        Ok(status) => Json(json!({ "ok": true, "data": status })).into_response(),
68        Err(e) => (StatusCode::CONFLICT, Json(json!({ "ok": false, "error": e }))).into_response(),
69    }
70}
71
72/// `POST /api/v1/host/upgrade_request`: the user's Upgrade now / Later on an
73/// agent's upgrade request, relayed by the CEF host with its own token. The
74/// instance auth key, which every agent has, isn't enough.
75pub(crate) async fn handle_host_upgrade_request(
76    axum::extract::State(state): axum::extract::State<AppState>,
77    headers: axum::http::HeaderMap,
78    axum::Json(body): axum::Json<crate::backend::upgrade_request::UpgradeRequestAnswer>,
79) -> axum::response::Response {
80    use axum::http::StatusCode;
81    use axum::response::IntoResponse;
82    use axum::Json;
83    if !crate::server::ui_handlers::from_host(&state, &headers).await {
84        return (StatusCode::FORBIDDEN, Json(json!({ "ok": false, "error": "only the AgentMux host can answer an upgrade request" })))
85            .into_response();
86    }
87    match crate::backend::upgrade_request::answer(&state.broker, &state.mstore, &body.id, &body.version, body.accept) {
88        Ok(()) => Json(json!({ "ok": true })).into_response(),
89        Err(e) => (StatusCode::CONFLICT, Json(json!({ "ok": false, "error": e }))).into_response(),
90    }
91}
92
93/// Query of `GET /api/v1/app/update-status`.
94#[derive(Debug, Default, serde::Deserialize)]
95pub(crate) struct UpdateStatusQuery {
96    /// Ask GitHub now (`update::check::check_now`) rather than answer what the
97    /// last check found.
98    #[serde(default)]
99    check: Option<String>,
100}
101
102/// `GET /api/v1/app/update-status`: the `App` tool's `version`, which asks
103/// with `check=1`. A check that can't reach GitHub answers what srv knew.
104pub(crate) async fn handle_update_status(
105    axum::extract::Query(q): axum::extract::Query<UpdateStatusQuery>,
106) -> axum::Json<crate::backend::update::check::AppUpdateStatus> {
107    if matches!(q.check.as_deref(), Some("1" | "true")) {
108        if let Ok(status) = crate::backend::update::check::check_now().await {
109            return axum::Json(status);
110        }
111    }
112    axum::Json(crate::backend::update::check::current_status())
113}
114
115/// `POST /api/v1/agent/self/upgrade`: the `App` tool's `upgrade`. Starts the
116/// upgrade when the user's own turn asked for it (`self_quit::gate_upgrade`: as
117/// for `QuitSelf`, but not a Swarm broadcast), otherwise files a sensitive
118/// request: the super agent decides and the person can veto the countdown.
119pub(crate) async fn handle_request_upgrade(
120    axum::extract::State(state): axum::extract::State<AppState>,
121    caller: Option<axum::Extension<crate::server::caller::Caller>>,
122    axum::Json(req): axum::Json<agentmux_common::api_types::RequestUpgradeRequest>,
123) -> axum::response::Response {
124    use crate::backend::upgrade_request::{self, Outcome};
125    use axum::http::StatusCode;
126    use axum::response::IntoResponse;
127    use axum::Json;
128
129    let block_id = match crate::server::ui_handlers::verified_block_id(&state, caller.as_deref(), &req.auth) {
130        Ok(b) => b,
131        Err(e) => return (StatusCode::UNAUTHORIZED, Json(json!({ "error": e }))).into_response(),
132    };
133    let reason = req.reason.trim();
134    if reason.is_empty() {
135        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "a reason is required" }))).into_response();
136    }
137    // Ask GitHub first: nothing checks on its own.
138    let status = crate::backend::update::check::check_now()
139        .await
140        .unwrap_or_else(|_| crate::backend::update::check::current_status());
141    let version = match upgrade_request::installable(&status, req.version.as_deref()) {
142        Ok(v) => v,
143        Err(outcome) => return Json(outcome).into_response(),
144    };
145    let agent = req.auth.agent_id.as_str();
146    let provenance = crate::backend::blockcontroller::get_controller(&block_id).and_then(|c| c.turn_provenance());
147    let outcome = match crate::sagas::self_quit::gate_upgrade(provenance.as_ref(), &req.user_instruction) {
148        Ok(()) => {
149            tracing::info!(agent, version = %version, reason, "upgrade: the user's own turn asked; starting");
150            // Prompts other agents raised for this release are answered by it;
151            // they and this agent hear if the upgrade stops short.
152            let mut askers = upgrade_request::resolve_started(&state.broker, &state.mstore, &version);
153            crate::sagas::sensitive_window::answered_by_another(&state, "upgrade", "version", &version, "The person's own request started this upgrade");
154            askers.push(block_id.clone());
155            upgrade_request::start_upgrade(version.clone(), askers);
156            Outcome::Started { version, stopping: crate::backend::update::restart::stopping_now().await }
157        }
158        Err(refusal) => {
159            tracing::info!(agent, version = %version, reason, why = refusal.as_str(), "upgrade: asking as a sensitive request");
160            // The agent acting on its own word: the super agent decides, and the person can veto
161            // the countdown (`SPEC_SUPER_AGENT_2026_10_25.md`).
162            let uid = caller
163                .as_deref()
164                .and_then(crate::server::caller::Caller::uid)
165                .map(str::to_string)
166                .or_else(|| crate::backend::reactive::get_global_handler().get_agent(agent).and_then(|r| r.uid))
167                .unwrap_or_default();
168            if uid.is_empty() {
169                return (StatusCode::FORBIDDEN, Json(json!({ "error": "FORBIDDEN: this acts for an agent, so the request must carry that agent's token" }))).into_response();
170            }
171            let facts = std::collections::BTreeMap::from([("version".to_string(), version.clone())]);
172            match crate::server::sensitive_handlers::file_request(&state, &uid, agent, "upgrade", &facts, reason).await {
173                Ok(filed) => Outcome::Requested {
174                    version,
175                    id: filed["id"].as_str().unwrap_or_default().to_string(),
176                    review: filed["review"].as_str().unwrap_or_default().to_string(),
177                },
178                Err(e) => return (StatusCode::CONFLICT, Json(json!({ "error": e }))).into_response(),
179            }
180        }
181    };
182    Json(outcome).into_response()
183}
184
185#[cfg(test)]
186mod tests {
187    use axum::body::Body;
188    use axum::http::{Request, StatusCode};
189    use serde_json::json;
190    use tower::ServiceExt;
191
192    async fn post(app: &axum::Router, host_token: Option<&str>, body: serde_json::Value) -> (StatusCode, serde_json::Value) {
193        let mut b = Request::builder()
194            .uri("/api/v1/host/app_update")
195            .method("POST")
196            .header("X-AuthKey", "test-secret-key")
197            .header("Content-Type", "application/json");
198        if let Some(token) = host_token {
199            b = b.header("X-Host-Token", token);
200        }
201        let resp = app.clone().oneshot(b.body(Body::from(body.to_string())).unwrap()).await.unwrap();
202        let status = resp.status();
203        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
204        (status, serde_json::from_slice(&body).unwrap_or_default())
205    }
206
207    // ยง4.1: the version panel's clicks come only through the host. The
208    // instance auth key, which every agent has, isn't enough.
209    #[tokio::test]
210    async fn only_the_host_can_click_in_the_version_panel() {
211        let state = crate::server::tests::test_state();
212        *state.host_ipc.lock().await = Some(crate::server::state::HostIpc { port: 1, token: "host-ipc-token".into() });
213        let app = crate::server::build_router(state);
214        for action in ["download", "restart", "cancel"] {
215            let (s, body) = post(&app, None, json!({ "action": action })).await;
216            assert_eq!(s, StatusCode::FORBIDDEN, "{action}: {body}");
217            let (s, _) = post(&app, Some("not-the-token"), json!({ "action": action, "now": true })).await;
218            assert_eq!(s, StatusCode::FORBIDDEN, "{action}");
219        }
220        // The host gets through to the action itself.
221        let (s, body) = post(&app, Some("host-ipc-token"), json!({ "action": "launch" })).await;
222        assert_eq!(s, StatusCode::CONFLICT, "{body}");
223        assert!(body["error"].as_str().unwrap_or_default().contains("unknown action"), "{body}");
224    }
225}