Skip to main content

agentmux_srv/server/
routes.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The HTTP route table and frontend fallback.
5//! Split out of server/mod.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.1).
6
7use super::*;
8use super::agent_only;
9use super::route_table::declared_routes;
10use agentmux_common::AUTH_KEY_HEADER;
11
12/// The two routers srv serves. `full` is every route and is bound on
13/// loopback only. `lan` is what `backend::lan::listeners` binds on LAN
14/// interfaces when LAN discovery is on: the routes a LAN peer calls (all
15/// behind `lan_or_full_auth_middleware`), plus health and the WhatsApp
16/// webhook, which authenticate themselves. Nothing that requires the full
17/// `auth_key` is served off-host, so a LAN listener has no full-key surface.
18pub struct SrvRouters {
19    pub full: Router,
20    pub lan: Router,
21    /// What the Linux container listener serves (`backend::container::listener`): the full
22    /// router behind a guard that admits only container tokens, on container routes, from the
23    /// agents subnet.
24    pub container: Router,
25}
26
27/// Build the full router (see [`build_routers`]).
28#[cfg(test)]
29pub fn build_router(state: AppState) -> Router {
30    build_routers(state).full
31}
32
33/// Build both routers with all routes, auth middleware, and CORS.
34pub fn build_routers(state: AppState) -> SrvRouters {
35    build_routers_with(state, crate::headless::frontend_dir())
36}
37
38/// [`build_routers`], with the frontend directory passed in (headless
39/// `--frontend-dir`, or `None`).
40pub(crate) fn build_routers_with(state: AppState, frontend_dir: Option<&std::path::Path>) -> SrvRouters {
41    let cors = cors_layer();
42
43    super::remote_ops::receive::mark_started();
44    let lan_forward_routes = lan_forward_routes(&state);
45    let authed_routes = authed_routes(&state);
46
47    // Health endpoint (no auth). `/health` always; `/` too, except on the
48    // full router when headless `--frontend-dir` serves the frontend there
49    // (`with_frontend`). The LAN router's health never changes.
50    let health = root_health_route().merge(health_route());
51    let full_health = if frontend_dir.is_some() { health_route() } else { health.clone() };
52
53    // WhatsApp Cloud API webhook receiver (no auth). Meta's servers call
54    // these directly and cannot supply the X-AuthKey header auth_middleware
55    // requires, so — like `health` — these must be merged at the top level,
56    // outside `authed_routes`'s `route_layer(auth_middleware)`, not added to
57    // that router. The GET handshake and POST delivery are authenticated by
58    // a different mechanism suited to a third party AgentMux doesn't
59    // control the request format of: hub.verify_token comparison on GET,
60    // and HMAC-SHA256(app_secret, raw_body) signature validation on every
61    // POST (see messaging/whatsapp/webhook.rs). See
62    // docs/specs/SPEC_MESSAGING_INTEGRATION_WHATSAPP_2026_07_07.md §8.2.
63    let whatsapp_webhooks = whatsapp_webhooks();
64
65    // Ext 5 of docs/reports/REPORT_MUXSPECT_MUXLOG_CROSS_CHANNEL_INSPECTION_2026_08_22.md:
66    // stamp every response with this instance's own version, so a stale-
67    // build 404 (this session hit exactly this: `muxspect conversations`
68    // 404ing because the running srv predated that route, with nothing
69    // saying so) is self-diagnosing instead of a bare, unexplained 404.
70    // Captured by value (not via AppState extraction) so this applies to
71    // EVERY route uniformly, including the unauthenticated health/webhook
72    // ones, without needing `AppState: Clone`.
73    let version_for_header = state.version.clone();
74    let version_header = axum::middleware::from_fn(move |req: axum::extract::Request, next: axum::middleware::Next| {
75        let version = version_for_header.clone();
76        async move {
77            let mut response = next.run(req).await;
78            if let Ok(value) = axum::http::HeaderValue::from_str(&version) {
79                response.headers_mut().insert("x-agentmux-srv-version", value);
80            }
81            response
82        }
83    });
84
85    let lan = Router::new()
86        .merge(health.clone())
87        .merge(whatsapp_webhooks.clone())
88        .merge(lan_forward_routes.clone())
89        .layer(version_header.clone())
90        .layer(cors.clone())
91        .with_state(state.clone());
92
93    // An approved widget's files (SPEC_USER_WIDGETS_AND_WIDGET_API_2026_10_09.md
94    // §5.2). No auth key: a widget's iframe loads them, and the URL's key
95    // segment is what keeps other pages out. Full router only, never the LAN.
96    let widget_files = widget_files_routes();
97
98    // The model gateway: an agent's harness calls it with its gateway token, which the handler checks
99    // itself. Full router only; a container reaches it through the container listener.
100    let model_gateway = model_gateway_route();
101
102    // A headless srv serving its own UI also serves the browser sign-in (`local_session_routes`).
103    let sign_in = if super::local_session_routes::enabled() { super::local_session_routes::routes() } else { Router::new() };
104
105    // A script on this computer starts an event job's run (`server::hook_handlers`): full router only, never the
106    // LAN, and the job's own secret is its key.
107    let local_hook = local_hook_route();
108
109    let full = Router::new()
110        .merge(full_health)
111        .merge(local_hook)
112        .merge(sign_in)
113        .merge(widget_files)
114        .merge(model_gateway)
115        .merge(whatsapp_webhooks)
116        .merge(lan_forward_routes)
117        .merge(authed_routes);
118    // Before the layers: `Router::layer` wraps only the routes and fallback
119    // that exist when it's called, so a fallback added afterwards would skip
120    // CORS and the version header (ReAgent P1 on #3900).
121    let full = match frontend_dir {
122        Some(dir) => with_frontend(full, dir),
123        None => full,
124    };
125    let full = full.layer(version_header).layer(cors).with_state(state.clone());
126    let container = crate::backend::container::listener::layer_reporting(
127        full.clone(),
128        crate::backend::container::listener::current_subnet,
129        super::model_gateway_key::foreign_use_reporter(state),
130        super::route_table::serves,
131    );
132
133    SrvRouters { full, lan, container }
134}
135
136declared_routes! {
137    /// The health check at `/`, where no frontend is served there.
138    fn root_health_route, ROOT_HEALTH_ROUTE;
139    GET "/" => health_handler;
140}
141
142declared_routes! {
143    /// The health check (no auth), on both routers.
144    fn health_route, HEALTH_ROUTE;
145    GET "/health" => health_handler;
146}
147
148declared_routes! {
149    /// The model gateway: every method goes on to the provider, and the handler checks the caller's gateway token.
150    fn model_gateway_route, MODEL_GATEWAY_ROUTE;
151    ANY "/api/v1/model/:route/*tail" => super::model_gateway_handlers::handle_model_gateway;
152}
153
154declared_routes! {
155    /// A job's local hook, with the body limit of a hook call.
156    fn local_hook_route, LOCAL_HOOK_ROUTE;
157    POST "/agentmux/hook/:job", Always => super::hook_handlers::handle_hook, layer(axum::extract::DefaultBodyLimit::max(crate::backend::jobs::webhook_local::MAX_BODY));
158}
159
160/// CORS for both routers: loopback origins only (plus any headless `--allowed-origin`).
161fn cors_layer() -> CorsLayer {
162    // CORS: reflect only loopback origins, plus any headless `--allowed-origin`.
163    //
164    // Before the 2026-05-11 security audit (C3) this allowed any origin
165    // (matching the historical Go pkg/web/web.go). That made every web
166    // page the user happened to have open a potential CSRF source —
167    // localhost is not a trust boundary on a developer machine.
168    //
169    // The legitimate cross-origin callers are:
170    //   - The CEF frontend served from `http://127.0.0.1:<host-port>`
171    //   - Vite dev server at `http://localhost:5173` (and similar)
172    //
173    // Both are loopback. The predicate accepts http://127.0.0.1:* and
174    // http://localhost:* (any port, http only; https is irrelevant for
175    // loopback). External origins are denied, which means a malicious
176    // page in the user's browser can't drive the sidecar even if it
177    // discovers the port.
178    use tower_http::cors::AllowOrigin;
179    CorsLayer::new()
180        .allow_origin(AllowOrigin::predicate(|origin, _req| {
181            origin.to_str().is_ok_and(is_allowed_origin)
182        }))
183        .allow_methods(Any)
184        .allow_headers(vec![
185            header::CONTENT_TYPE,
186            header::AUTHORIZATION,
187            header::ACCEPT,
188            "X-Session-Id".parse().unwrap(),
189            AUTH_KEY_HEADER.parse().unwrap(),
190            "X-Requested-With".parse().unwrap(),
191            "x-vercel-ai-ui-message-stream".parse().unwrap(),
192            // A video poster reads a file's first bytes (stream-local-file,
193            // SPEC_AGENT_PANE_RICH_OUTPUT_2026_09_27.md §5). The request also
194            // carries X-AuthKey, so it's preflighted and Range must be listed.
195            header::RANGE,
196        ])
197        // Custom response headers are invisible to cross-origin `fetch()`
198        // callers (Response.headers.get(...) silently returns null) unless
199        // explicitly exposed here — a browser CORS default, not an
200        // allow_headers concern (that list governs REQUEST headers only).
201        // `X-ZoneFileInfo` (files.rs's handle_mux_file) is read by
202        // `fetchMuxFile` on every blockfile GET; without this, any 200
203        // response is indistinguishable from a malformed one to the
204        // frontend ("missing zone file info for ..." — the exact failure
205        // mode `TermWrap.loadInitialTerminalData()` hit once terminal
206        // scrollback write-through started actually producing real 200s
207        // instead of always-404, see
208        // SPEC_TERMINAL_SCROLLBACK_PERSISTENCE_2026_07_23.md §2.1's
209        // follow-up). Not dev-only — the CEF frontend's own origin is
210        // cross-origin from this server in production too (see the
211        // allow_origin comment above).
212        // `Content-Range` carries a ranged stream-local-file response's
213        // total size, which inline video/audio read before play (Codex P2 on
214        // #4073).
215        // `X-ZoneFileOffset` says where that response's body starts in the
216        // file (later than asked once a terminal's output was trimmed);
217        // `fetchMuxFile` reads it to resume at the file's absolute end.
218        .expose_headers(vec!["X-ZoneFileInfo".parse().unwrap(), "X-ZoneFileOffset".parse().unwrap(), header::CONTENT_RANGE])
219}
220
221declared_routes! {
222    /// The routes of `lan_forward_routes`, each with what is decided about it.
223    fn lan_forward_routes_declared, LAN_FORWARD_ROUTES;
224    POST "/agentmux/reactive/inject", Handler => reactive::handle_reactive_inject;
225    // A typed request from an agent on another machine, which this srv carries out itself
226    // (SPEC_AGENTS_OPERATE_OTHER_MACHINES_2026_10_30.md). The signature authorizes it, never the key.
227    POST "/agentmux/remote/op", Always => super::remote_ops::receive::handle_remote_op;
228    // A jekt with its files after it, from another instance or a LAN peer
229    // (SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §4). Streamed, never buffered.
230    POST "/agentmux/reactive/inject-files", Handler => super::jekt_files::handle_reactive_inject_files;
231    GET "/agentmux/reactive/agent" => reactive::handle_reactive_agent;
232    // Names, kinds and status only — see `handle_reactive_agent_names`' doc comment for why
233    // this is deliberately not `/agentmux/reactive/agents` (which stays
234    // behind full auth because it serializes internal routing fields).
235    GET "/agentmux/reactive/agent-names" => reactive::handle_reactive_agent_names;
236    // One live instance per agent, LAN tier (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 §4.4).
237    GET "/agentmux/agent/holding" => agent_takeover::handle_agent_holding;
238    // The same names, as a versioned snapshot and an SSE stream, so a phone
239    // follows changes without polling (SPEC_LAN_FLEET_FEED_2026_10_03.md).
240    GET "/agentmux/fleet" => handle_fleet;
241    GET "/agentmux/fleet/events" => handle_fleet_events;
242}
243
244/// The routes an LAN peer actually calls when forwarding a jekt or
245/// looking up which agents this instance hosts
246/// (`LanDiscoveryController::find_agent`, `server/reactive.rs`'s Tier-3
247/// forward). Kept OUT of `reactive_routes`/`authed_routes` deliberately
248/// — merged at the top level with their own `lan_or_full_auth_middleware`
249/// instead, so a LAN peer's scoped `lan_key` (see `Config::lan_key`) is
250/// accepted here without also being accepted by `authed_routes`'s much
251/// broader surface (the general `auth_middleware` there requires the
252/// full `auth_key` only). See `lan_or_full_auth_middleware`'s doc
253/// comment for why this can't just be nested inside `authed_routes`.
254fn lan_forward_routes(state: &AppState) -> Router<AppState> {
255    lan_forward_routes_declared()
256        // Who did what (`http_action`): inner to the caller layer, which names the caller.
257        .route_layer(middleware::from_fn_with_state(state.clone(), super::http_action::record_action))
258        // Identity M4a: inner to the auth layer (route_layer order: the
259        // last one added runs first), so it sees which key authenticated.
260        .route_layer(middleware::from_fn_with_state(state.clone(), caller::caller_middleware))
261        .route_layer(middleware::from_fn_with_state(state.clone(), lan_or_full_auth_middleware))
262        // Outermost, so a refusal by the layers above is seen too: a line for a request to a
263        // route a peer posts to that is refused, hangs or times out (`lan_watch`).
264        .route_layer(middleware::from_fn_with_state(state.clone(), super::lan_watch::watch))
265}
266
267declared_routes! {
268    /// Reactive routes. Previously registered without auth on the
269    /// assumption that localhost is a trust boundary; the 2026-05-11
270    /// security audit (C1 + C2) showed that any local process — or a
271    /// web page driving 127.0.0.1 via the permissive CORS layer — could
272    /// drive `/agentmux/reactive/inject` and reconfigure the cloud
273    /// muxbus poller. These routes are now merged into `authed_routes`
274    /// below and gated by `auth_middleware`. (`/inject` and `/agent` are
275    /// NOT here — see `lan_forward_routes` above.)
276    fn reactive_routes, REACTIVE_ROUTES;
277    GET "/agentmux/reactive/agents" => reactive::handle_reactive_agents;
278    GET "/agentmux/reactive/audit" => reactive::handle_reactive_audit;
279    // What this channel keeps in its own audit file, for another channel on this computer listing every channel
280    // (SPEC_AUDIT_LIVE_LOG_OF_EVERY_AGENT_ACTION_2026_11_03.md §3.6 point 5).
281    // Not recorded: the Audit's read of another channel's own rows, every ten seconds while it is listed. A record of
282    // each would be rows in the Audit it reads.
283    POST "/agentmux/audit/own", Never => app_api::audit_query::handle_audit_own;
284    POST "/agentmux/reactive/register", Always => reactive::handle_reactive_register;
285    // Holder side of a takeover — full auth only, never LAN (spec §4.6).
286    POST "/agentmux/agent/release", Always => agent_takeover::handle_agent_release;
287    POST "/agentmux/reactive/unregister", Always => pane_binding::handle_unregister;
288    // Identity M3 (spec §5): the one place a typed agent name is
289    // interpreted. Called by agentmux-mcp before WorkEnqueue/CronCreate.
290    POST "/agentmux/agents/resolve", Never => name_resolution::handle_resolve_agent_name;
291    POST "/agentmux/reactive/ensure-signing-key", Always => reactive::handle_reactive_ensure_signing_key;
292    GET "/agentmux/reactive/poller/stats" => reactive::handle_reactive_poller_stats;
293    POST "/agentmux/reactive/poller/config", Always => reactive::handle_reactive_poller_config;
294    GET "/agentmux/reactive/poller/status" => reactive::handle_reactive_poller_status;
295    GET "/agentmux/reactive/transcript" => reactive::handle_reactive_transcript;
296    // SPEC_AGENT_HISTORY_SEARCH_2026_09_17.md — search an agent's own past
297    // conversations on disk. Distinct from `/transcript`, which is the LIVE
298    // session's tail only. Full-auth route (not in the LAN-scoped set):
299    // this reads conversation content, which is exactly what the LAN key
300    // must not reach.
301    GET "/agentmux/reactive/history/search" => reactive::handle_reactive_history_search;
302}
303
304declared_routes! {
305    /// The routes of `agent_routes`, each with what is decided about it.
306    fn agent_routes_declared, AGENT_ROUTES;
307    POST "/agentmux/jobs", Always => cron::handle_cron_create;
308    DELETE "/agentmux/jobs/:id", Always => cron::handle_cron_delete;
309    PATCH "/agentmux/jobs/:id", Always => cron::handle_cron_patch;
310    POST "/agentmux/jobs/:id/run", Always => cron::handle_cron_run_now;
311    POST "/agentmux/jobs/runs/:run_id/report", Always => cron::handle_cron_report;
312    POST "/agentmux/cron", Always => cron::handle_cron_create;
313    DELETE "/agentmux/cron/:id", Always => cron::handle_cron_delete;
314    PATCH "/agentmux/cron/:id", Always => cron::handle_cron_patch;
315    POST "/agentmux/cron/:id/run", Always => cron::handle_cron_run_now;
316    POST "/agentmux/cron/runs/:run_id/report", Always => cron::handle_cron_report;
317    POST "/agentmux/work", Always => work_queue::handle_work_enqueue;
318    POST "/agentmux/work/claim", Always => bulletin_handlers::handle_work_claim_with_bulletins;
319    POST "/agentmux/work/boards", Always => work_boards::handle_boards_act;
320    POST "/agentmux/work/:id/heartbeat", Always => work_queue::handle_work_heartbeat;
321    POST "/agentmux/work/:id/complete", Always => work_queue::handle_work_complete;
322    POST "/agentmux/work/:id/release", Always => work_queue::handle_work_release;
323    POST "/agentmux/work/:id/update", Always => work_tasks::handle_work_update;
324    POST "/agentmux/work/:id/ask", Always => work_tasks::handle_work_ask;
325    POST "/agentmux/work/:id/submit", Always => work_tasks::handle_work_submit;
326    POST "/agentmux/work/:id/hold", Always => work_tasks::handle_work_hold;
327    POST "/agentmux/work/:id/unhold", Always => work_tasks::handle_work_unhold;
328    POST "/agentmux/work/act", Always => work_act::handle_work_act;
329    // A sensitive operation: the agent asks, the super agent decides, the person can veto
330    // (SPEC_SUPER_AGENT_2026_10_25.md).
331    POST "/api/v1/sensitive/:action", Always => sensitive_handlers::handle_sensitive;
332    // The Drone tool: an agent lists and reads the drones here, fires one with a payload and reads its
333    // runs; a fire is recorded as that agent (SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md §6.5).
334    POST "/api/v1/drone/:action", Always => drone_agent::handle_drone;
335    // The Zoom tool: an agent reads and sets zoom in its own tab and window (SPEC_MUXAPI_ZOOM_2026_11_24.md).
336    POST "/api/v1/ui/zoom/:action", Always => zoom::handle_zoom;
337    // Presence claims and posts to a repository's coordination channel
338    // (SPEC_AGENT_COORDINATION_CHANNEL_2026_10_15.md); reading is open.
339    POST "/api/v1/work-claims", Always => work_claims_handlers::handle_claim_work;
340    POST "/api/v1/work-claims/release", Always => work_claims_handlers::handle_release_work;
341    // Presence status: the agent's own one-line account of what it is doing now.
342    POST "/api/v1/agent/status", Always => agent_status_handlers::handle_agent_status;
343    // An agent asks for a pending workspace stop to be put back (recorded as that agent).
344    POST "/api/v1/agent/keep-running", Always => app_api::workspace_stop::handle_keep_running;
345    POST "/api/v1/coord/posts", Always => coord_channel_handlers::handle_post_to_channel;
346    POST "/api/v1/bulletin", Always => bulletin_handlers::handle_post_bulletin;
347    GET "/api/v1/bulletin" => bulletin_handlers::handle_read_bulletin;
348    POST "/api/v1/quota-mode", Always => quota_mode_handler::handle_set_quota_mode;
349    GET "/api/v1/quota-mode" => quota_mode_handler::handle_get_quota_mode;
350}
351
352/// Routes that act for an agent: each needs the agent's token (`agent_only`).
353/// Jobs (SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.1) and the cron scheduler
354/// under them (`/agentmux/cron` is kept as an alias for one release), and
355/// Muxqueue, the universal agent work queue
356/// (docs/reports/REPORT_UNIVERSAL_AGENT_WORK_QUEUE_2026_09_01.md), with the
357/// Kanban's holder routes (SPEC_WARDEN_KANBAN_2026_10_20.md) and an agent's
358/// hold and unhold (SPEC_KANBAN_AGENTS_HOLD_AND_UNHOLD_2026_10_22.md).
359fn agent_routes(state: &AppState) -> Router<AppState> {
360    agent_routes_declared()
361        .route_layer(middleware::from_fn_with_state(state.clone(), agent_only::require_agent_token))
362}
363
364declared_routes! {
365    /// MessageBus routes (authed, localhost-only).
366    fn bus_routes, BUS_ROUTES;
367    POST "/api/bus/register", Always => messagebus::handle_register;
368    POST "/api/bus/send", Always => messagebus::handle_send;
369    POST "/api/bus/inject", Always => messagebus::handle_inject;
370    POST "/api/bus/broadcast", Always => messagebus::handle_broadcast;
371    GET "/api/bus/messages" => messagebus::handle_read_messages;
372    POST "/api/bus/messages/delete", Always => messagebus::handle_delete_messages;
373    GET "/api/bus/agents" => messagebus::handle_list_agents;
374}
375
376declared_routes! {
377    /// A deep link another program handed to AgentMux, sent by the host and proven by its token: the operating system's
378    /// rules (G4e).
379    fn os_link_routes, OS_LINK_ROUTES;
380    // Records itself, with the link's source (`deeplink_os::record`).
381    POST "/api/v1/host/deeplink_open", Handler => super::deeplink_os::handle_os_open_link;
382}
383
384/// Everything behind the full key: the groups below, then the layers that attribute and authenticate.
385fn authed_routes(state: &AppState) -> Router<AppState> {
386    Router::new()
387        .merge(service_shell_and_vault_routes())
388        .merge(streamed_browser_routes())
389        .merge(agent_api_routes())
390        .merge(muxspect_routes())
391        .merge(memory_and_identity_routes())
392        .merge(ui_and_host_routes())
393        .merge(agent_self_and_fleet_routes())
394        .merge(forward_messaging_and_work_routes())
395        .merge(bus_routes())
396        .merge(os_link_routes())
397        .merge(agent_routes(state))
398        .merge(reactive_routes())
399        .route_layer(middleware::from_fn_with_state(state.clone(), super::http_action::record_action))
400        // Identity M4a: attribute the (already authenticated) request.
401        .route_layer(middleware::from_fn_with_state(
402            state.clone(),
403            caller::caller_middleware,
404        ))
405        .route_layer(middleware::from_fn_with_state(
406            state.clone(),
407            auth_middleware,
408        ))
409}
410
411declared_routes! {
412    /// The streamed Browser pane of a headless server's web UI; 404 unless switched on.
413    fn streamed_browser_routes, STREAMED_BROWSER_ROUTES;
414    GET "/agentmux/streamed-browser" => super::streamed_browser::handle, route_layer(middleware::from_fn(ws_origin_guard));
415}
416
417declared_routes! {
418    /// The routes of `service_shell_and_vault_routes`, each with what is decided about it.
419    fn service_shell_and_vault_routes_declared, SERVICE_SHELL_AND_VAULT_ROUTES;
420    GET "/ws" => websocket::handle_ws, route_layer(middleware::from_fn(ws_origin_guard));
421    POST "/agentmux/service", Plumbing => service::handle_service;
422    GET "/agentmux/file" => files::handle_mux_file;
423    GET "/agentmux/stream-file" => stub_501;
424    GET "/agentmux/stream-file/*path" => stub_501;
425    GET "/agentmux/stream-local-file" => files::handle_stream_local_file;
426    GET "/agentmux/file-icon" => super::file_icons::handle_file_icon;
427    GET "/api/post-chat-message" => stub_501;
428    POST "/api/post-chat-message", Never => stub_501;
429    GET "/docsite/*path" => files::handle_docsite;
430    GET "/schema/*path" => files::handle_schema;
431    GET "/api/lan-instances" => handle_lan_instances;
432    GET "/agentmux/discovery" => super::live_facts::handler::handle;
433    GET "/agentmux/old-versions" => super::old_versions_handlers::handle_get;
434    POST "/agentmux/old-versions", Always => super::old_versions_handlers::handle_post;
435    GET "/agentmux/reactive/availability" => super::availability_view::handle_availability;
436    GET "/agentmux/diag/sagas" => handle_diag_sagas;
437    // Streaming-bash wrapper publish endpoint
438    // (SPEC_STREAMING_BASH_RUNNER_2026_05_11.md §4.3). agentmux-bashwrap
439    // POSTs `{event, scopes, data}` here while a PreToolUse-rewritten
440    // Bash command is running; we forward to the in-process MPS broker.
441    // Auth-gated like the other reactive routes (PR #801 pattern).
442    POST "/agentmux/wps/publish", Never => handle_wps_publish;
443    // A container agent's bashwrap: its own pane's `tool_chunk` only (the generic relay above
444    // is refused to a container token).
445    POST "/api/v1/agent/tool-chunk", Never => container_tool_chunk::handle_container_tool_chunk, layer(axum::extract::DefaultBodyLimit::max(container_tool_chunk::MAX_BODY_BYTES));
446    // A container agent's PreCompact hook: its own pane's `compaction_started` only.
447    POST "/api/v1/agent/compaction-started", Never => container_compaction_started::handle_container_compaction_started, layer(axum::extract::DefaultBodyLimit::max(container_compaction_started::MAX_BODY_BYTES));
448    // Persistent shell launch endpoint
449    // (SPEC_PERSISTENT_SHELL_NODE_2026_06_11.md §5.3). agentmux-mcp's
450    // Shell tool POSTs here; we publish shell_node_create + spawn a
451    // ShellNodeRunner that streams shell_chunk events to the frontend.
452    POST "/api/v1/shell/create", Always => handle_shell_create;
453    // Stop a persistent shell (Phase 3). agentmux-mcp's `ShellStop` tool
454    // POSTs here; tree-kills the shell's process group.
455    POST "/api/v1/shell/stop", Always => handle_shell_stop;
456    // Phase 3b — write to a running shell's stdin (for interactive prompts).
457    POST "/api/v1/shell/input", Always => handle_shell_input;
458    // Phase 3b — query running state, exit code, and line count.
459    POST "/api/v1/shell/status", Never => handle_shell_status;
460    POST "/api/v1/shell/output", Never => handle_shell_output;
461    // Real PTY-backed shell, for genuinely interactive programs the
462    // piped /api/v1/shell/* family above can't drive (see
463    // docs/specs/SPEC_AGENT_INTERACTIVE_PTY_SHELL_API_2026_09_10.md).
464    // agentmux-mcp's `PtyShell*` tools POST here.
465    POST "/api/v1/ptyshell/create", Always => handle_pty_shell_create;
466    POST "/api/v1/ptyshell/input", Always => handle_pty_shell_input;
467    POST "/api/v1/ptyshell/resize", Always => handle_pty_shell_resize;
468    POST "/api/v1/ptyshell/read", Never => handle_pty_shell_read;
469    POST "/api/v1/ptyshell/status", Never => handle_pty_shell_status;
470    POST "/api/v1/ptyshell/stop", Always => handle_pty_shell_stop;
471    // Open a pane (editor/term/browser/…) from an agent tool call.
472    // agentmux-mcp's OpenEditor tool POSTs `{view:"editor", file, …}` here;
473    // shares the exact pane.open logic with the WebSocket RPC handler
474    // (app_api::open_pane). See ANALYSIS_AGENT_APP_API_OPEN_IN_EDITOR_2026_05_30.
475    POST "/api/v1/pane/open", Always => handle_pane_open;
476    // A deep link an agent opens (`Pane` open with `link`): srv's guard, then the window's executor.
477    // Records itself: every open it decides, refused and queued ones too, with the link and the reason
478    // (`deeplink_guard::record`, G9).
479    // For container agents too: srv's guard refuses a path a container agent's snapshot rule would not open.
480    POST "/api/v1/pane/open_link", Handler => super::deeplink_guard::handle_pane_open_link;
481    // Widgets for agents (WidgetList, WidgetInstall): an install waits
482    // for the user's answer, which only the host can carry.
483    GET "/api/v1/widgets" => super::widget_agent_handlers::handle_widgets_list;
484    POST "/api/v1/widgets/install", Always => super::widget_agent_handlers::handle_widgets_install;
485    // An agent's `Browser` `fill` with `vault`: the person says where it may go.
486    POST "/api/v1/ui/browser/vault_fill", Always => super::browser_vault_fill::handle_vault_fill;
487    // An agent's `Browser` `signin`: the person says yes, or a grant and a notice.
488    POST "/api/v1/ui/browser/signin", Always => super::browser_signin::handle_signin;
489    // An agent's `Browser` `generate_password`: the person says yes, then a countdown with Stop.
490    POST "/api/v1/ui/browser/generate_password", Always => super::browser_account::handle_generate_password;
491    POST "/api/v1/ui/browser/capture", Always => super::browser_capture::handle_capture;
492}
493
494/// The websocket and service calls, files, shells, widgets, the Vault and Google.
495fn service_shell_and_vault_routes() -> Router<AppState> {
496    service_shell_and_vault_routes_declared()
497        // The Vault for agents, declared with its policies in `vault_routes.rs`.
498        .merge(super::vault_routes::vault_routes())
499        .merge(google_agent_routes())
500}
501
502declared_routes! {
503    /// Open, spawn, start, stop and name agents; windows, tabs and layout.
504    fn agent_api_routes, AGENT_API_ROUTES;
505    // Open (launch) an agent into a pane from an agent tool call —
506    // agentmux-mcp's OpenAgent tool POSTs `{agent_id, tab_id?, …}` here.
507    // Shares the exact agent.open logic (incl. its AGENT_OPEN_LOCKS
508    // TOCTOU serialization) with the WebSocket RPC handler via
509    // app_api::open_agent_impl. Until this route existed, automation
510    // could STOP an agent (/api/v1/fleet/bulk-stop, cross-channel) but
511    // could not START one anywhere — see
512    // REPORT_AGENT_OPEN_API_GAP_2026_09_06.md.
513    POST "/api/v1/agent/open", Always => handle_agent_open;
514    // Agents open with host and view: a watching pane over a paired computer's agent, on the caller's window.
515    POST "/api/v1/agent/open_view", Always => app_api::remote_pane_view::handle_agent_open_view;
516    // An agent launches a worker, a new agent built from its own
517    // definition (not a fork), in a pane next to its own
518    // (SPEC_AGENT_WORKERS_2026_10_15.md §3.1).
519    POST "/api/v1/agent/spawn", Always => app_api::agent_spawn::handle_agent_spawn;
520    POST "/api/v1/agent/spawn_many", Always => app_api::agent_spawn::handle_agent_spawn_many;
521    POST "/api/v1/agent/create", Always => app_api::agent_spawn::handle_agent_create;
522    POST "/api/v1/agent/import", Handler => app_api::agent_spawn::handle_agent_import;
523    POST "/api/v1/agent/open_many", Always => app_api::agent_open_many::handle_agent_open_many;
524    // Remove a container agent's container so its next message starts it from the current
525    // agent image (`Agents update_container`); only between turns.
526    POST "/api/v1/agent/container/update", Always => app_api::container_update::handle_update_container;
527    // A container agent's CPU and memory limits (`Agents set_container_limits`).
528    POST "/api/v1/agent/container/limits", Always => app_api::container_limits::handle_container_limits;
529    // A container agent's cache volumes: their sizes, and clearing them (`Agents container_caches`).
530    POST "/api/v1/agent/container/caches", Always => app_api::container_caches::handle_container_caches;
531    // A leader's own workers and how each is doing (§3.4).
532    POST "/api/v1/agent/workers", Never => app_api::agent_spawn::handle_agent_workers;
533    POST "/api/v1/agent/routes", Never => app_api::agent_routes::handle_agent_routes;
534    // Start, stop or detach an agent (`Agents start`, `stop`, `detach`); a stop of another agent waits for the person's override window.
535    POST "/api/v1/agent/start", Always => app_api::agent_lifecycle::handle_agent_start;
536    POST "/api/v1/agent/stop", Always => app_api::agent_lifecycle::handle_agent_stop;
537    // A leader mutes one of its agents' quiet watch for a stated time.
538    POST "/api/v1/agent/mute-quiet", Always => app_api::agent_mute_quiet::handle_agent_mute_quiet;
539    POST "/api/v1/agent/detach", Always => app_api::agent_lifecycle::handle_agent_detach;
540    POST "/api/v1/agent/rotate-token", Always => app_api::agent_rotate_token::handle_agent_rotate_token;
541    // Delete an agent the caller made, once it is stopped (`Agents delete`).
542    POST "/api/v1/agent/delete", Always => app_api::agent_lifecycle::handle_agent_delete;
543    // Replay an agent's recent transcript, then tail it (`Agents watch`).
544    POST "/api/v1/agent/watch", Never => app_api::agent_watch::handle_agent_watch;
545    // One live instance per agent, Phase 2 (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 §4.6).
546    POST "/api/v1/agent/takeover", Always => pane_binding::handle_takeover;
547    // Voice speech-to-text: the renderer POSTs mic audio (one
548    // silence-bounded utterance per request); we forward to a Whisper
549    // backend and return the transcript. Key stays server-side.
550    // See SPEC_VOICE_STT_ENGINE_2026_06_20.md and #1591.
551    POST "/api/v1/voice/transcribe", Plumbing => voice::handle_voice_transcribe;
552    GET "/api/v1/voice/status" => voice::handle_voice_status;
553    // Image attachments in the agent composer: serve stored files and
554    // accept the paste fallback's streamed upload.
555    // SPEC_AGENT_PANE_IMAGE_ATTACHMENTS_2026_09_26.md §6.2, §6.5.
556    POST "/api/v1/attachments/upload", Plumbing => attachments::handle_attachment_upload;
557    GET "/api/v1/attachments/:id/:kind" => attachments::handle_attachment_file;
558    // A screenshot or recording for a Kanban task: streamed and hashed like the attachments upload (the agent-token
559    // layer above buffers whole bodies, so it is not behind it); the task call that names the file is.
560    // SPEC_KANBAN_TASK_MEDIA_2026_10_25.md §3.1.
561    POST "/agentmux/work/media", Always => work_media::handle_work_media_upload;
562    // First-class agent API (SPEC_AGENT_API_FIRST_CLASS_SURFACE_2026_06_17.md).
563    // `GET /api/v1/self?block_id=` resolves the caller's place in the tree;
564    // `POST /api/v1/window/name` sets the window display name (taskbar title).
565    // agentmux-mcp's `WhoAmI` / `SetWindowName` tools call these.
566    GET "/api/v1/self" => handle_self;
567    // The connections an agent's Shell/PtyShell may name (`ConnList` tool,
568    // SPEC_REMOTE_TERMINALS_AND_DURABLE_SESSIONS_2026_10_02.md §8.1).
569    GET "/api/v1/conn/list" => app_api::connections::handle_conn_list;
570    // ssh's askpass, through agentmux-bashwrap: answered only for a live
571    // per-ssh secret (backend::remote::askpass).
572    POST "/api/v1/askpass", Never => app_api::connections::handle_askpass;
573    POST "/api/v1/window/name", Always => handle_window_name;
574    // Naming verbs (SPEC §4.3): rename the caller's own tab / pane / workspace
575    // (or an explicit target). agentmux-mcp's SetTabName / SetPaneTitle /
576    // SetWorkspaceName tools POST here.
577    POST "/api/v1/tab/name", Always => handle_tab_name;
578    POST "/api/v1/pane/title", Always => handle_pane_title;
579    POST "/api/v1/workspace/name", Always => handle_workspace_name;
580    // A file or folder renamed in its folder, so Editor tabs open on it follow
581    // (agentmux-mcp's Pane rename with target "file").
582    POST "/api/v1/file/rename", Always => handle_file_rename;
583    // Introspection verbs (SPEC §4.6): read-only views of the UI tree so an
584    // agent can see what's around it. agentmux-mcp's GetLayout / ListWindows
585    // / ListWorkspaces / ListTabs tools GET these.
586    GET "/api/v1/layout" => handle_layout;
587    GET "/api/v1/windows" => handle_list_windows;
588    GET "/api/v1/workspaces" => handle_list_workspaces;
589    GET "/api/v1/tabs" => handle_list_tabs;
590    // Layout / navigation verbs (SPEC §4.5): switch the active tab, open a
591    // new tab, focus a window. agentmux-mcp's SetActiveTab / NewTab /
592    // FocusWindow tools POST here.
593    POST "/api/v1/tab/activate", Always => handle_tab_activate;
594    POST "/api/v1/tab/new", Always => handle_tab_new;
595    POST "/api/v1/window/focus", Always => handle_window_focus;
596    // An agent places a floating pane it opened (`Pane` resize, move, place): srv checks the opener, the pane's window answers.
597    // For container agents too: a window call, with no host execution by the agent.
598    POST "/api/v1/pane/place", Always => super::pane_place::handle_pane_place;
599}
600
601declared_routes! {
602    /// The routes of `muxspect_routes`, each with what is decided about it.
603    fn muxspect_routes_declared, MUXSPECT_ROUTES;
604    // The live AgentMux instances on this machine, for `muxspect instances` and `--channel`
605    // (SPEC_MUXSPECT_CROSS_TIER_INSTANCE_INSPECTION_2026_09_02.md, Phase 2a). Read-only.
606    GET "/api/v1/muxspect/instances" => muxspect_instances::handle_muxspect_instances;
607    // Cross-instance lookup — Ext 4 of
608    // docs/reports/REPORT_MUXSPECT_MUXLOG_CROSS_CHANNEL_INSPECTION_2026_08_22.md.
609    // Checks this instance first, then every other channel via the shared
610    // reactive registry (same mechanism `conversations` below already
611    // uses) — see the handler's own doc comment.
612    GET "/api/v1/muxspect/find" => muxspect_handlers::handle_muxspect_find;
613    // `dock/clear` is this module's one mutating route (narrowly scoped; see the handler's own
614    // doc comment) and is deliberately not behind the `?channel=` forward.
615    POST "/api/v1/muxspect/dock/clear", Always => muxspect_handlers::handle_muxspect_dock_clear;
616    // Migration doctor — `migrate --verify`'s report from inside a live
617    // instance (SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03.md Phase 1c).
618    // Read-only; see the handler's own doc comment.
619    GET "/api/v1/muxspect/migrations" => muxspect_handlers::handle_muxspect_migrations;
620    // srv's own memory and what holds it (`backend::mem_census`). Read-only, and about this
621    // process, so it is not behind the `?channel=` forward.
622    GET "/api/v1/muxspect/memory" => super::muxspect_memory::handle_muxspect_memory;
623    // All-tier conversation glance (host/cross-channel previews, LAN/WAN
624    // liveness) — see the handler's own doc comment
625    // (SPEC_MUXSPECT_CROSS_TIER_CONVERSATION_VISIBILITY_2026_08_21.md Phase A).
626    GET "/api/v1/muxspect/conversations" => muxspect_handlers::handle_muxspect_conversations;
627    // Agents' work facts, and WhoIsWorkingOn over them
628    // (SPEC_AGENT_OVERLAP_AWARENESS_2026_10_10.md §3.1, §3.2). Read-only.
629    GET "/api/v1/work-facts" => work_facts_handlers::handle_work_facts;
630    GET "/api/v1/work-facts/who" => work_facts_handlers::handle_who_is_working_on;
631    // What messages cost per agent per day (SPEC_CHEAPER_FLEET_MESSAGING_2026_10_30.md section 7). Read-only.
632    GET "/api/v1/message-stats" => message_stats_handler::handle_message_stats;
633    // The recent messages between agents, ids and times only, for the Atlas map on open (`backend::message_flow`). Read-only.
634    GET "/api/v1/message-flow" => message_flow_handler::handle_message_flow;
635    // This machine's agent containers and the container runtime's state, names and states only (`backend::container_status`). Read-only.
636    GET "/api/v1/containers" => containers_handler::handle_containers;
637    // The recent task filings and hand-overs on the boards the caller sees, names and numbers only (`backend::task_flow`). Read-only.
638    GET "/api/v1/task-flow" => task_flow_handler::handle_task_flow;
639    // The recent reviews, check results and merges of agents' PRs, ids, states and times only, for the Atlas map's review bot and
640    // CI nodes on open (`backend::pr_flow`). Read-only.
641    GET "/api/v1/pr-flow" => pr_flow_handler::handle_pr_flow;
642    // Every PR a task names, with its review, checks and merge state and what it waits on (`backend::reviews`). Read-only.
643    GET "/api/v1/reviews" => reviews_handler::handle_reviews;
644    // ClaimWork / ReleaseWork (same spec, §3.4): informational claims,
645    // never a lock.
646    // PostToChannel / ReadChannel: a repository's coordination channel
647    // (SPEC_AGENT_COORDINATION_CHANNEL_2026_10_15.md).
648    GET "/api/v1/coord/posts" => coord_channel_handlers::handle_read_channel;
649}
650
651/// `muxspect`, work facts and the coordination channel.
652fn muxspect_routes() -> Router<AppState> {
653    muxspect_routes_declared()
654        .merge(forwardable_muxspect_routes())
655}
656
657declared_routes! {
658    /// The routes of `forwardable_muxspect_routes`, each with what is decided about it.
659    fn forwardable_muxspect_routes_declared, FORWARDABLE_MUXSPECT_ROUTES;
660    // Live-state introspection for the `muxspect` CLI (Phase 1 of
661    // docs/specs/SPEC_MUXSPECT_LIVE_INTROSPECTION_TOOL_2026_08_01.md): read-only, diagnostic-only,
662    // reached like every other /api/v1/* route (X-AuthKey from the caller's own environment).
663    GET "/api/v1/muxspect/list" => muxspect_handlers::handle_muxspect_list;
664    GET "/api/v1/muxspect/layout" => muxspect_handlers::handle_muxspect_layout;
665    GET "/api/v1/muxspect/describe" => muxspect_handlers::handle_muxspect_describe;
666    // Which page each renderer draws, with CPU and what the page is doing (SPEC_RELEASE_BUILD_BROWSER_PAGE_DIAGNOSTIC_2026_11_13.md).
667    GET "/api/v1/muxspect/browsers" => muxspect_browsers::handle_muxspect_browsers;
668    // Dock: the cached ToolNode status snapshot (2026-08-06 dock diagnosis spec).
669    GET "/api/v1/muxspect/dock" => muxspect_handlers::handle_muxspect_dock;
670    // Durable declared-background task registry (see the handler for why it is not the dock).
671    GET "/api/v1/muxspect/background-tasks" => muxspect_handlers::handle_muxspect_background_tasks;
672    // Sender-liveness verdict for a jekt's claimed FROM (SPEC_MUXSPECT_VERIFY_SENDER_2026_08_21.md).
673    GET "/api/v1/muxspect/verify-sender" => muxspect_handlers::handle_muxspect_verify_sender;
674}
675
676/// The muxspect reads that can be asked of another instance on this machine with `?channel=<name>`
677/// (Phase 2a of SPEC_MUXSPECT_CROSS_TIER_INSTANCE_INSPECTION_2026_09_02.md §2.4). Every route here
678/// is a read; `dock/clear`, the one write, is deliberately not, and `find` and `conversations`
679/// already look across channels themselves.
680fn forwardable_muxspect_routes() -> Router<AppState> {
681    forwardable_muxspect_routes_declared()
682        .route_layer(axum::middleware::from_fn(muxspect_instances::forward_to_channel))
683}
684
685declared_routes! {
686    /// MuxAPI memory, Global Memory, presets, identity and skills.
687    fn memory_and_identity_routes, MEMORY_AND_IDENTITY_ROUTES;
688    // MuxAPI — identity / preset / memory namespaces, the MCP-facing
689    // slice of the app-API RPC surface (SPEC_AGENT_APP_API_MCP_BINDINGS_2026_06_28).
690    // The agent identity (`agent_id`) is supplied by agentmux-mcp from its
691    // AGENTMUX_AGENT_ID env. Host agents do hold the instance key, so the
692    // owner comes from the caller's token where there is one
693    // (`SelfOwner::of`); a container token is always pinned to its own
694    // agent (backend::container::credential). Each handler calls the
695    // same `app_api::*_impl` the WebSocket RPC handlers use.
696    GET "/api/v1/agent/memory/list" => handle_agent_memory_list;
697    GET "/api/v1/agent/memory/read" => handle_agent_memory_read;
698    POST "/api/v1/agent/memory/write", Always => handle_agent_memory_write;
699    GET "/api/v1/agent/memory/history" => handle_agent_memory_history;
700    GET "/api/v1/agent/memory/diff" => handle_agent_memory_diff;
701    POST "/api/v1/agent/memory/revert", Always => handle_agent_memory_revert;
702    // Global Memory (agent-facing) — SPEC_AGENT_FACING_GLOBAL_MEMORY_
703    // API_2026_09_15.md. Unlike the agent/memory/* routes above (each
704    // agent's own private native memory), these touch a single,
705    // shared, workspace-wide list every agent inherits at launch. Same
706    // trust model as every other route in this block: `agent_id` comes
707    // from agentmux-mcp's trusted env, never forgeable from an agent's
708    // own PTY. Never exposes or accepts a system-tier (`is_system`)
709    // entry — see `global_memory_write_impl`'s own doc comment.
710    POST "/api/v1/agent/globalmemory/write", Always => handle_agent_globalmemory_write;
711    GET "/api/v1/agent/globalmemory/list" => handle_agent_globalmemory_list;
712    GET "/api/v1/agent/globalmemory/read" => handle_agent_globalmemory_read;
713    POST "/api/v1/agent/globalmemory/remove", Always => handle_agent_globalmemory_remove;
714    POST "/api/v1/agent/globalmemory/reach", Always => handle_agent_globalmemory_reach;
715    // Global Memory audit trail (read side) — SPEC_AGENT_FACING_GLOBAL_
716    // MEMORY_API_2026_09_15.md Phase 3 follow-up: `bundle_version_list`/
717    // `bundle_version_get` (`bundle_versions.rs`) already existed and were
718    // tested, but nothing exposed them via MCP/REST until now. Same trust
719    // model and same system-tier exclusion as the four routes above.
720    GET "/api/v1/agent/globalmemory/history" => handle_agent_globalmemory_history;
721    GET "/api/v1/agent/globalmemory/diff" => handle_agent_globalmemory_diff;
722    POST "/api/v1/agent/globalmemory/revert", Always => handle_agent_globalmemory_revert;
723    // An agent's memory delivered through Claude Code's `SessionStart`
724    // hook, one part per hook command, then an acknowledgement per part —
725    // SPEC_GLOBAL_MEMORY_DELIVERY_2026_09_27.md §7 P2. Called by
726    // `agentmux-bashwrap sessionstart`, whose `X-Agent-Token` names the
727    // agent whose Personal Memory is delivered.
728    POST "/api/v1/agent/memory/session-start/part", Never => memory_delivery_handlers::handle_session_start_part;
729    POST "/api/v1/agent/memory/session-start/ack", Never => memory_delivery_handlers::handle_session_start_ack;
730    GET "/api/v1/agent/preset/list" => handle_agent_preset_list;
731    GET "/api/v1/agent/preset/get" => handle_agent_preset_get;
732    GET "/api/v1/agent/identity/accounts" => handle_agent_identity_accounts;
733    POST "/api/v1/agent/identity/validate", Always => handle_agent_identity_validate;
734    POST "/api/v1/agent/identity/switch", Always => handle_agent_identity_switch;
735    POST "/api/v1/agent/identity/check-limits", Always => handle_agent_identity_check_limits;
736    POST "/api/v1/agent/identity/signin/notice", Always => signin_notice::handle_agent_signin_notice;
737    POST "/api/v1/agent/skill", Always => handle_agent_skill;
738}
739
740declared_routes! {
741    /// A headless server's registered external host: it vouches for a connection, and asks what the workspace is doing,
742    /// for a graceful shutdown and for a stop notice. Every one answers 404 unless a host is registered.
743    fn external_host_routes, EXTERNAL_HOST_ROUTES;
744    POST "/api/v1/host/external_nonce", Plumbing => super::external_host::handle_nonce;
745    POST "/api/v1/host/external_attest", Plumbing => super::external_host::handle_attest;
746    POST "/api/v1/host/external_revoke", Plumbing => super::external_host::handle_revoke;
747    POST "/api/v1/host/activity", Plumbing => super::host_control::handle_activity;
748    POST "/api/v1/host/shutdown", Plumbing => super::host_control::handle_shutdown;
749    POST "/api/v1/host/notice", Plumbing => super::host_control::handle_notice;
750}
751
752declared_routes! {
753    /// The routes of `ui_and_host_routes`, each with what is decided about it.
754    fn ui_and_host_routes_declared, UI_AND_HOST_ROUTES;
755    // Agent UI automation (SPEC_AGENT_UI_AUTOMATION_CLICK_SCREENSHOT_2026_08_18.md)
756    // — proxies to the paired CEF host's browser_api CDP routes. `block_id`
757    // is stamped by agentmux-mcp from AGENTMUX_BLOCKID, same trust model as
758    // the agent/memory/preset/identity routes just above.
759    POST "/api/v1/ui/screenshot", Never => ui_handlers::handle_ui_screenshot;
760    // A `UI` window capture reads what each window blacks out, just before and just after its frame.
761    // Not recorded: it asks the windows what a window capture blacks out; the capture itself is recorded by the
762    // agent's MCP.
763    // For container agents too: the route itself tells a container agent what to use instead.
764    POST "/api/v1/ui/capture_mask", Never => super::capture_mask_route::handle_capture_mask;
765    POST "/api/v1/ui/record", Never => ui_record::handle_ui_record;
766    POST "/api/v1/ui/click", Always => ui_handlers::handle_ui_click;
767    POST "/api/v1/ui/query", Never => ui_handlers::handle_ui_query;
768    // Shortcuts (PLAN_SHORTCUTS_VERIFIED_AND_APP_API_2026_10_10.md §4) —
769    // in the window that holds the caller's own pane.
770    POST "/api/v1/ui/shortcuts/list", Never => ui_shortcuts::handle_ui_shortcuts_list;
771    POST "/api/v1/ui/shortcuts/run", Always => ui_shortcuts::handle_ui_run_command;
772    POST "/api/v1/ui/shortcuts/press", Always => ui_shortcuts::handle_ui_press_keys;
773    POST "/api/v1/ui/shortcuts/set", Always => ui_shortcuts::handle_ui_set_shortcut;
774    POST "/api/v1/ui/shortcuts/reset", Always => ui_shortcuts::handle_ui_reset_shortcuts;
775    // Browser-pane deep control (SPEC_AGENT_BROWSER_PANE_DEEP_CONTROL_2026_09_20.md)
776    // — own-pane-only, same identity model as the ui/* routes above.
777    // navigate/back/forward/reload/eval additionally require the
778    // caller's own pane to be a dedicated browser pane (checked
779    // host-side in browser_api::routes::reject_if_shared_target).
780    POST "/api/v1/ui/browser/open", Always => ui_handlers::handle_ui_browser_open;
781    POST "/api/v1/ui/browser/snapshot", Never => ui_handlers::handle_ui_browser_snapshot;
782    POST "/api/v1/ui/browser/find", Never => crate::server::browser_find::handle_ui_browser_find;
783    POST "/api/v1/ui/browser/locate", Never => crate::server::browser_locate::handle_ui_browser_locate;
784    POST "/api/v1/ui/browser/act", Always => ui_handlers::handle_ui_browser_act;
785    POST "/api/v1/ui/browser/set_files", Always => ui_handlers::handle_ui_browser_set_files;
786    POST "/api/v1/ui/browser/wait_for", Never => ui_handlers::handle_ui_browser_wait_for;
787    POST "/api/v1/host/browser_attention", Plumbing => ui_handlers::handle_host_browser_attention;
788    POST "/api/v1/ui/browser/request_bypass", Always => crate::server::browser_bypass_routes::handle_ui_browser_request_bypass;
789    POST "/api/v1/ui/browser/end_bypass", Always => crate::server::browser_bypass_routes::handle_ui_browser_end_bypass;
790    POST "/api/v1/ui/browser/close", Always => crate::server::browser_close_route::handle_ui_browser_close;
791    POST "/api/v1/ui/browser/terminal", Always => crate::server::browser_terminal::handle_ui_browser_terminal;
792    POST "/api/v1/host/browser_bypass", Plumbing => crate::server::browser_bypass_routes::handle_host_browser_bypass;
793    // The pane's action log (Browser's log) and the person's Pause / Resume.
794    POST "/api/v1/ui/browser/actions", Never => crate::server::browser_actions::handle_ui_browser_actions;
795    POST "/api/v1/host/browser_pause", Plumbing => crate::server::browser_actions::handle_host_browser_pause;
796    POST "/api/v1/host/widget_approval", Plumbing => super::widget_handlers::handle_host_widget_approval;
797    POST "/api/v1/host/job_templates", Plumbing => super::job_template_handlers::handle_host_job_templates;
798    POST "/api/v1/host/jobs", Plumbing => super::cron::handle_host_jobs;
799    // Everything the Vault pane does, relayed by the host.
800    POST "/api/v1/host/vault", Plumbing => super::vault_handlers::handle_host_vault;
801    // The Google account panel (who may use which service), relayed by the host.
802    POST "/api/v1/host/google", Plumbing => super::google_handlers::handle_host_google;
803    // The user's clicks in the version panel (Download, Upgrade & restart,
804    // Cancel), and their answer to an agent's upgrade request, relayed by the host.
805    POST "/api/v1/host/app_update", Plumbing => app_api::app_update::handle_host_app_update;
806    POST "/api/v1/host/upgrade_request", Plumbing => app_api::app_update::handle_host_upgrade_request;
807    // The user's answer to an agent's request to drive a native app, and
808    // their Stop (SPEC_DESKTOP_DRIVING_2026_10_20.md §5.4, §5.6).
809    POST "/api/v1/host/desktop_request", Plumbing => app_api::desktop::handle_host_request;
810    POST "/api/v1/host/desktop_stop", Plumbing => app_api::desktop::handle_host_stop;
811    // The host vouches for the AgentMux window's websocket connection.
812    POST "/api/v1/host/operator_attest", Plumbing => super::operator_proof::handle_host_attest;
813    POST "/api/v1/host/browser_navigation", Plumbing => crate::server::browser_allowlist::handle_host_browser_navigation;
814    POST "/api/v1/host/browser_dialog", Plumbing => crate::server::browser_dialog::handle_host_browser_dialog;
815    POST "/api/v1/host/browser_permission", Plumbing => crate::server::browser_permission::handle_host_browser_permission;
816    POST "/api/v1/ui/browser/dialogs", Never => crate::server::browser_dialog::handle_ui_browser_dialogs;
817    POST "/api/v1/ui/browser/zoom", Always => crate::server::browser_zoom::handle_ui_browser_zoom;
818    POST "/api/v1/ui/browser/scroll", Always => crate::server::browser_scroll::handle_ui_browser_scroll;
819    POST "/api/v1/ui/browser/list", Never => crate::server::browser_sessions::handle_ui_browser_list;
820    POST "/api/v1/ui/browser/show", Always => crate::server::browser_sessions::handle_ui_browser_show;
821    POST "/api/v1/ui/browser/hide", Always => crate::server::browser_sessions::handle_ui_browser_hide;
822    POST "/api/v1/host/browser_popup", Plumbing => ui_handlers::handle_host_browser_popup;
823    POST "/api/v1/host/browser_popup_window", Plumbing => ui_handlers::handle_host_browser_popup_window;
824    POST "/api/v1/ui/browser/navigate", Always => ui_handlers::handle_ui_browser_navigate;
825    POST "/api/v1/ui/browser/back", Always => ui_handlers::handle_ui_browser_back;
826    POST "/api/v1/ui/browser/forward", Always => ui_handlers::handle_ui_browser_forward;
827    POST "/api/v1/ui/browser/reload", Always => ui_handlers::handle_ui_browser_reload;
828    POST "/api/v1/ui/browser/eval", Always => ui_handlers::handle_ui_browser_eval;
829    POST "/api/v1/ui/browser/dispatch_key", Always => ui_handlers::handle_ui_browser_dispatch_key;
830    POST "/api/v1/ui/browser/focus_element", Always => ui_handlers::handle_ui_browser_focus_element;
831    POST "/api/v1/ui/browser/focus_info", Never => ui_handlers::handle_ui_browser_focus_info;
832    // Pane lifecycle (SPEC_AGENT_PANE_LIFECYCLE_CONTROL_2026_09_10.md) —
833    // `ClosePane`. Own-pane identity is verified the same way as the
834    // ui/* routes above (`verified_block_id`); the target pane, when
835    // acting on another agent's pane, is fleet-tier (see the
836    // fleet/bulk-stop comment below) — no ownership check on the
837    // target, but the caller is never anonymous in the audit log the
838    // way `FleetBulkStop`'s calls are today.
839    POST "/api/v1/agent/pane/close", Always => app_api::pane::handle_close_pane;
840    POST "/api/v1/agent/self/quit", Always => app_api::pane::handle_quit_self;
841    // The App tool: what AgentMux runs and whether a newer release is out,
842    // and asking to upgrade (SPEC_UPGRADE_FOR_USERS_AND_AGENTS §5.1).
843    GET "/api/v1/app/update-status" => app_api::app_update::handle_update_status;
844    // An agent asks this srv to run an operation on another machine (the `host` argument).
845    POST "/api/v1/agent/remote/op", Always => super::remote_ops::send::handle_agent_remote_op;
846    GET "/api/v1/app/connectivity" => app_api::connectivity::handle_status;
847    GET "/api/v1/app/health" => super::remote_ops::app_ops::handle_health;
848    // This workspace's pending stop, for any agent to read.
849    GET "/api/v1/app/workspace" => app_api::workspace_stop::handle_workspace;
850    GET "/api/v1/app/logs" => super::remote_ops::log_ops::handle_local_logs;
851    // The record of AgentMux's own size over weeks (SPEC_LONG_RUNNING_ZERO_DEGRADATION §6).
852    GET "/api/v1/app/record" => app_api::record_read::handle_record;
853    POST "/api/v1/agent/self/upgrade", Always => app_api::app_update::handle_request_upgrade;
854}
855
856/// UI automation, the browser pane and the host relays.
857fn ui_and_host_routes() -> Router<AppState> {
858    ui_and_host_routes_declared()
859        .merge(browser_control_routes())
860        .merge(external_host_routes())
861}
862
863declared_routes! {
864    /// The routes of `agent_self_and_fleet_routes`, each with what is decided about it.
865    fn agent_self_and_fleet_routes_declared, AGENT_SELF_AND_FLEET_ROUTES;
866    // The Desktop tool: the gate in front of looking at and controlling a
867    // native app (SPEC_DESKTOP_DRIVING_2026_10_20.md §6).
868    POST "/api/v1/agent/desktop/policy", Always => app_api::desktop::handle_policy;
869    POST "/api/v1/agent/desktop/authorize", Always => app_api::desktop::handle_authorize;
870    POST "/api/v1/agent/desktop/record", Always => app_api::desktop::handle_record;
871    POST "/api/v1/agent/desktop/release", Always => app_api::desktop::handle_release;
872    // `agentmux-mcp doctor`, from the agent's shell: its own pane by token.
873    POST "/api/v1/agent/self/mcp-health", Never => app_api::mcp_health::handle_mcp_health;
874    POST "/api/v1/agent/self/mcp-heal", Always => app_api::mcp_health::handle_mcp_heal;
875    POST "/api/v1/agent/self/mcp-beat", Never => app_api::mcp_health::handle_mcp_beat;
876    // An agent's own context, and compacting itself (SPEC_AGENT_SELF_COMPACTION §3.3).
877    POST "/api/v1/agent/self/context", Never => app_api::agent_context::handle_context_self;
878    POST "/api/v1/agent/self/compact", Always => app_api::agent_context::handle_compact_self;
879    POST "/api/v1/agent/self/fresh", Always => app_api::agent_context::handle_fresh_self;
880    // An agent answering the window a user action gave it to prepare (SPEC_AGENT_PREP_BEFORE_SESSION_RESTART).
881    POST "/api/v1/agent/self/ready", Always => crate::server::prep::handle_ready_self;
882    // An agent reading and editing a definition's extra environment variables.
883    POST "/api/v1/agent/env", Handler => app_api::agent_env::handle_agent_env;
884    // The GitHub App's installation token for an agent's git and gh, through
885    // agentmux-bashwrap (identity::github_tokens).
886    POST "/api/v1/github/token", Always => app_api::github_token::handle_github_token;
887    // A container agent's push, judged as data by the host's publish guard (a container's pre-push hook).
888    POST "/api/v1/github/push-scan", Always => app_api::push_scan::handle_push_scan, layer(axum::extract::DefaultBodyLimit::max(app_api::push_scan::MAX_BODY_BYTES));
889    // A container agent's `gh pr merge`, run by the host's gh-agent: the container's own token cannot write contents.
890    POST "/api/v1/github/pr-merge", Always => app_api::pr_merge::handle_pr_merge;
891    // Records itself (`app_api::aws_credentials`): a fresh session and every refusal, but not a cache hit, which the
892    // AWS CLI asks for on every command and the layer would record each time.
893    POST "/api/v1/aws/credentials", Never => app_api::aws_credentials::handle_aws_credentials;
894    // The grants a host shares with its container agents: which are in force, and the answer to a new or wider one.
895    GET "/api/v1/aws/grants" => app_api::aws_grants::handle_aws_grants;
896    POST "/api/v1/aws/grants/decide", Always => app_api::aws_grants::handle_aws_grant_decide;
897    // An agent asks for the shared pane-history store's free space to be given back at the next
898    // start, withdraws that, or reads where it stands (`App history_reclaim`).
899    POST "/api/v1/agent/history/reclaim", Always => app_api::agent_history_reclaim::handle_history_reclaim;
900    GET "/api/v1/agent/history/reclaim" => app_api::agent_history_reclaim::handle_history_reclaim_status;
901    // The outcome of a shutdown waiting on the user's override (§6.5):
902    // the MCP tools poll it after their 202.
903    // axum 0.7: a path parameter is `:name`; `{name}` would be a literal.
904    GET "/api/v1/agent/shutdown/:request_id" => app_api::pane::handle_shutdown_status;
905    // Native dev-proxy registration (SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md)
906    // — `RegisterDevServer`. Same `verified_block_id` identity model as
907    // the ui/* and pane/close routes above; the backend address it
908    // actually stores is resolved server-side from the CALLER's own
909    // container, never taken from the request body.
910    POST "/api/v1/agent/dev_server/register", Always => app_api::dev_server::handle_register_dev_server;
911    // Fleet control (SPEC_MULTI_AGENT_FLEET_CONTROL_2026_08_20.md) —
912    // bulk-stop is the one fleet action exposed to agentmux-mcp (see
913    // `FleetBulkStop`): stopping a controller involves no jekt signing,
914    // unlike broadcast (which an agent instead sends by looping the
915    // existing single-target signed SendMessage path client-side —
916    // see `server/app_api/fleet.rs`'s module doc comment for why no
917    // `/api/v1/fleet/broadcast` route exists). Same MCP-facing App-API
918    // trust model as the routes above: gated by the general X-AuthKey
919    // middleware wrapping this whole router, no additional per-agent
920    // scoping — fleet actions target OTHER agents' panes by design, so
921    // "own pane only" doesn't apply here the way it does to `ui/*`.
922    POST "/api/v1/fleet/bulk-stop", Always => handle_fleet_bulk_stop;
923    // Cross-channel bulk-stop forward target
924    // (SPEC_FLEET_BULK_STOP_CROSS_CHANNEL_2026_08_22.md): when
925    // `fleet_bulk_stop_impl` can't find a target block_id in ITS OWN
926    // in-process controller registry, it checks the shared
927    // cross-channel registry and forwards here — same trust model as
928    // `/agentmux/reactive/inject`'s own cross-channel forward (same
929    // host, same user, the target channel's own auth_key from the
930    // shared registry). Loopback-only by construction: the caller only
931    // ever forwards to a `local_url` it already verified is loopback.
932    POST "/agentmux/agent/stop", Always => handle_agent_stop_forward;
933}
934
935/// An agent acting on itself, and fleet control.
936fn agent_self_and_fleet_routes() -> Router<AppState> {
937    agent_self_and_fleet_routes_declared()
938        // An agent sets or clears seats, several at once; recorded under its name.
939        .merge(agent_definition_routes())
940}
941
942declared_routes! {
943    /// The forwards other instances call, messaging, job reads and the Kanban.
944    fn forward_messaging_and_work_routes, FORWARD_MESSAGING_AND_WORK_ROUTES;
945    // A Job run's timeout or cancel, forwarded to the AgentMux that follows it
946    // (same trust model as the stop forward above).
947    POST super::jobs_remote_stop::STOP_RUN_PATH, Always => super::jobs_remote_stop::handle_jobs_stop_run;
948    // A Swarm broadcast's cross-channel forward target
949    // (SPEC_SWARM_REMOTE_AGENTS_PLATFORM_TAG_AND_SELECTION_2026_10_03.md §5.2):
950    // same trust model as the stop forward above. The caller sends only the
951    // body; this instance writes the header.
952    POST "/agentmux/agent/broadcast", Always => handle_agent_broadcast_forward;
953    // The receiving instance asks the sending one whether it sent the forward from the operator's window. Not
954    // refused to a container agent by its audience: the handler refuses any request that carries an agent's token.
955    // Not recorded: an instance asking another whether it sent a forwarded broadcast; the forward itself is recorded.
956    POST "/agentmux/agent/broadcast/confirm", Never => handle_agent_broadcast_confirm;
957    // The same forward, for an agent's FleetBulkStop: this instance's
958    // user gets the 30 s override window (SPEC_AGENT_SELF_QUIT §6.5).
959    POST "/agentmux/agent/stop-pending", Always => handle_agent_stop_pending_forward;
960    GET "/api/messaging/status" => messaging_handlers::handle_status;
961    POST "/api/messaging/discord/send", Always => messaging_handlers::handle_discord_send;
962    POST "/api/messaging/telegram/send", Always => messaging_handlers::handle_telegram_send;
963    POST "/api/messaging/slack/send", Always => messaging_handlers::handle_slack_send;
964    POST "/api/messaging/whatsapp/send", Always => messaging_handlers::handle_whatsapp_send;
965    // Reading jobs; changing them is in `agent_routes`. Auth-gated like reactive routes.
966    GET "/agentmux/jobs" => cron::handle_cron_list;
967    GET "/agentmux/jobs/:id/runs" => cron::handle_cron_runs;
968    GET "/agentmux/cron" => cron::handle_cron_list;
969    GET "/agentmux/cron/:id/runs" => cron::handle_cron_runs;
970    GET "/agentmux/identity/fallbacks" => caller::handle_identity_fallbacks;
971    GET "/agentmux/agents/self/keys" => agent_self_keys::handle_agent_self_keys;
972    // What the launcher asks before the tray's Quit.
973    GET "/agentmux/quit-question" => super::quit_question::handle_quit_question;
974    GET "/agentmux/work" => work_queue::handle_work_list;
975    GET "/agentmux/work/boards" => work_boards::handle_boards_list;
976    GET "/agentmux/work/:id" => work_tasks::handle_work_get;
977    GET "/agentmux/work/:id/tokens" => work_tasks::handle_work_tokens;
978    // Kanban: an agent's decision on a task in review (signed, not a token).
979    POST "/agentmux/work/:id/accept", Always => work_delegate::handle_work_accept;
980    POST "/agentmux/work/:id/send_back", Always => work_delegate::handle_work_send_back;
981}
982
983declared_routes! {
984    /// WhatsApp Cloud API webhook receiver (no auth). Meta's servers call it directly and cannot supply the
985    /// X-AuthKey header `auth_middleware` requires, so it is merged outside `authed_routes`.
986    fn whatsapp_webhooks, WHATSAPP_WEBHOOKS;
987    GET "/webhook/whatsapp" => crate::messaging::whatsapp::handle_verify;
988    POST "/webhook/whatsapp", Never => crate::messaging::whatsapp::handle_inbound;
989}
990
991declared_routes! {
992    /// An approved widget's files and the SDK. Full router only, never the LAN.
993    fn widget_files_routes, WIDGET_FILES_ROUTES;
994    GET "/agentmux/widget-files/:id/:hash/:key/*path" => super::widget_handlers::handle_widget_file;
995    GET "/agentmux/widget-sdk/:file" => super::widget_handlers::handle_widget_sdk;
996}
997
998declared_routes! {
999    /// Who drives a browser pane: the hand-off to the person, what became of it, and taking back a pane the person took over.
1000    fn browser_control_routes, BROWSER_CONTROL_ROUTES;
1001    POST "/api/v1/ui/browser/handoff", Always => ui_handlers::handle_ui_browser_handoff;
1002    POST "/api/v1/ui/browser/handoff_status", Never => crate::server::browser_retake::handle_ui_browser_handoff_status;
1003    POST "/api/v1/ui/browser/request", Never => crate::server::browser_waiting::handle_ui_browser_request;
1004    POST "/api/v1/ui/browser/retake", Always => crate::server::browser_retake::handle_ui_browser_retake;
1005    POST "/api/v1/ui/browser/take_control", Always => crate::server::browser_control::handle_ui_browser_take_control;
1006    POST "/api/v1/ui/browser/release", Always => crate::server::browser_control::handle_ui_browser_release;
1007}
1008
1009declared_routes! {
1010    /// What an agent changes about the agents themselves: their seats and names. Each acts as the agent its token
1011    /// names and is recorded under it.
1012    fn agent_definition_routes, AGENT_DEFINITION_ROUTES;
1013    POST "/api/v1/agent/seats", Handler => app_api::agent_seats::handle_agent_seats;
1014    POST "/api/v1/agent/folder-overlap-ask", Handler => app_api::folder_overlap_ask::handle_folder_overlap_ask;
1015    POST "/api/v1/agent/pin-ask", Handler => app_api::pin_ask::handle_pin_ask;
1016    POST "/api/v1/agent/migrate-ids", Handler => app_api::agent_migrate_ids::handle_agent_migrate_ids;
1017    POST "/api/v1/agent/rename", Handler => app_api::agent_rename::handle_agent_rename;
1018    POST "/api/v1/agent/export", Handler => app_api::agent_export::handle_agent_export;
1019    POST "/api/v1/agent/bring_back", Handler => app_api::agent_handover::handle_agent_bring_back;
1020    POST "/api/v1/agent/move", Handler => app_api::agent_move::handle_agent_move;
1021    POST "/api/v1/agent/move_status", Handler => app_api::agent_handover::handle_agent_move_status;
1022    POST "/api/v1/agent/update", Handler => app_api::agent_definition::handle_agent_update;
1023    POST "/api/v1/agent/bundles", Handler => app_api::agent_definition::handle_agent_bundles;
1024    POST "/api/v1/agent/hide", Handler => app_api::agent_definition::handle_agent_hide;
1025    POST "/api/v1/agent/unhide", Handler => app_api::agent_definition::handle_agent_unhide;
1026}
1027
1028declared_routes! {
1029    /// Google connectors for agents: srv makes the call with the account's token, for an agent with a
1030    /// grant (Calendar, Drive and Gmail), and agents turn services on and off themselves.
1031    fn google_agent_routes, GOOGLE_AGENT_ROUTES;
1032    GET "/api/v1/google/self/services" => super::google_handlers::handle_google_self_services;
1033    GET "/api/v1/google/status" => super::google_handlers::handle_google_status;
1034    POST "/api/v1/google/grant", Always => super::google_handlers::handle_google_grant;
1035    POST "/api/v1/google/disconnect", Always => super::google_handlers::handle_google_disconnect;
1036    POST "/api/v1/google/connect", Always => super::google_handlers::connect::handle_google_connect;
1037    POST "/api/v1/google/connect/status", Always => super::google_handlers::connect::handle_google_connect_status;
1038    POST "/api/v1/google/connect/cancel", Always => super::google_handlers::connect::handle_google_connect_cancel;
1039    POST "/api/v1/google/calendar", Always => super::google_handlers::handle_google_calendar;
1040    POST "/api/v1/google/drive", Always => super::google_handlers::handle_google_drive;
1041    POST "/api/v1/google/gmail", Always => super::google_handlers::handle_google_gmail;
1042}
1043
1044/// Serve the built frontend in `dir` for every path no route claims, `/`
1045/// included. Unauthenticated, like the CEF host's static server: the bundle
1046/// holds no secrets, and srv's key still guards every API route. Unknown
1047/// paths get `index.html`. Full router only; the LAN router never serves it.
1048pub(super) fn with_frontend(router: Router<AppState>, dir: &std::path::Path) -> Router<AppState> {
1049    use tower_http::services::{ServeDir, ServeFile};
1050    let index = ServeFile::new(dir.join("index.html"));
1051    // The UI's files carry the sign-in's policy (CSP, framing) when srv signs a browser in.
1052    let files = Router::new()
1053        .fallback_service(ServeDir::new(dir).fallback(index))
1054        // How a browser caches them: the page and the files without a hash are revalidated (ui_cache.rs).
1055        .layer(middleware::from_fn(super::ui_cache::ui_cache))
1056        .layer(middleware::from_fn(super::local_session_routes::ui_headers));
1057    router.fallback_service(files)
1058}
1059
1060#[cfg(test)]
1061#[path = "tests/routes_shape_tests.rs"]
1062mod routes_shape_tests;