Skip to main content

agentmux_srv/server/
http_self.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Presets, identity accounts and self.
5//! Split out of server/mod.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.1).
6
7use super::*;
8
9/// `GET /api/v1/agent/preset/list` — list all presets (shared catalog, summary
10/// fields only). Backs the `PresetList` MCP tool.
11pub(super) async fn handle_agent_preset_list(State(state): State<AppState>) -> impl IntoResponse {
12    app_api_response(app_api::bundle_list_impl(&state).await)
13}
14
15#[derive(serde::Deserialize)]
16pub(super) struct AgentPresetGetQuery {
17    #[serde(default)]
18    pub(super) agent_id: String,
19    #[serde(default)]
20    pub(super) id: String,
21    #[serde(default)]
22    pub(super) name: String,
23}
24
25/// `GET /api/v1/agent/preset/get?agent_id=<slug>&id=&name=` — fetch a preset by
26/// id or name; with neither, return the agent's own bound preset (self).
27/// Backs the `PresetGet` MCP tool.
28pub(super) async fn handle_agent_preset_get(
29    State(state): State<AppState>,
30    caller: Option<Extension<caller::Caller>>,
31    Query(q): Query<AgentPresetGetQuery>,
32) -> impl IntoResponse {
33    if q.id.is_empty() && q.name.is_empty() {
34        // Self mode: `agent_id` is the actor (owner = actor). By id or name
35        // it is only an optional hint, so it is not checked there.
36        if let Err(e) = actor::require_token(&state, caller.as_deref(), actor::ActorSite::PresetGet, &q.agent_id) {
37            return app_api_response::<()>(Err(e));
38        }
39        if q.agent_id.is_empty() {
40            return ApiError::bad_request("preset.get: provide id, name, or agent_id (for self)").into_response();
41        }
42        return app_api_response(
43            app_api::bundle_self_get_impl(
44                &state,
45                app_api::SelfOwner::of(caller.as_deref(), &q.agent_id, "m4c.preset_owner_by_name"),
46            )
47            .await,
48        );
49    }
50    app_api_response(app_api::bundle_get_impl(&state, &q.id, &q.name).await)
51}
52
53#[derive(serde::Deserialize)]
54pub(super) struct AgentIdentityAccountsQuery {
55    pub(super) agent_id: String,
56    /// `mine` (default): the agent's own linked accounts. `machine`: every signed-in account here,
57    /// with its stable id and quota (`identity.accounts`).
58    #[serde(default)]
59    pub(super) scope: String,
60}
61
62/// `GET /api/v1/agent/identity/accounts?agent_id=<slug>` — list the agent's own
63/// linked credential accounts (masked tails only, never secrets). Backs the
64/// `IdentityAccounts` MCP tool.
65pub(super) async fn handle_agent_identity_accounts(
66    State(state): State<AppState>,
67    caller: Option<Extension<caller::Caller>>,
68    Query(q): Query<AgentIdentityAccountsQuery>,
69) -> impl IntoResponse {
70    if let Err(e) = actor::require_token(&state, caller.as_deref(), actor::ActorSite::IdentityAccounts, &q.agent_id) {
71        return app_api_response::<()>(Err(e));
72    }
73    if q.scope.eq_ignore_ascii_case("machine") {
74        return app_api_response(crate::server::account_episodes::identity_accounts(state).await);
75    }
76    app_api_response(
77        app_api::identity_self_accounts_impl(
78            &state,
79            app_api::SelfOwner::of(caller.as_deref(), &q.agent_id, "m4c.identity_owner_by_name"),
80        )
81        .await,
82    )
83}
84
85#[derive(serde::Deserialize)]
86pub(super) struct AgentIdentitySwitchRequest {
87    /// The calling agent's name (S1: must be one only the token's own agent answers to).
88    pub(super) agent_id: String,
89    /// The agent to move; the caller itself when absent.
90    #[serde(default)]
91    pub(super) target: Option<String>,
92    pub(super) account: String,
93    #[serde(default)]
94    pub(super) when: crate::server::account_episodes::AccountSwitchWhen,
95}
96
97/// `POST /api/v1/agent/identity/switch` — move an agent (the caller by default) to another signed-in
98/// account of its provider, now or when its turn ends. Backs `Identity` with action `switch`; the
99/// audit row names the caller (SPEC_ACCOUNT_SWITCH_FROM_THE_COMPOSER_NO_BIND_2026_10_26.md §3.4).
100pub(super) async fn handle_agent_identity_switch(
101    State(state): State<AppState>,
102    caller: Option<Extension<caller::Caller>>,
103    Json(req): Json<AgentIdentitySwitchRequest>,
104) -> impl IntoResponse {
105    // The audit row names who switched, so the caller is the agent the token proves, never the body's word.
106    let (slug, _) = match actor::require_token_actor(&state, caller.as_deref(), actor::ActorSite::IdentitySwitch, &req.agent_id).await {
107        Ok(who) => who,
108        Err(e) => return app_api_response::<()>(Err(e)),
109    };
110    if req.target.as_deref().is_some_and(crate::server::account_episodes::is_all_limited) {
111        let switch = crate::server::account_episodes::AgentAccountSwitchReq { agent_id: None, account: req.account, when: req.when };
112        return app_api_response(crate::server::account_episodes::switch_all_limited(state, slug, switch).await);
113    }
114    let switch = crate::server::account_episodes::AgentAccountSwitchReq {
115        agent_id: Some(req.target.unwrap_or_else(|| slug.clone())),
116        account: req.account,
117        when: req.when,
118    };
119    app_api_response(crate::server::account_episodes::switch_account(state, slug, switch).await)
120}
121
122#[derive(serde::Deserialize)]
123pub(super) struct AgentIdentityValidateRequest {
124    pub(super) agent_id: String,
125    pub(super) account_id: String,
126}
127
128/// `POST /api/v1/agent/identity/validate` — live-probe one of the agent's own
129/// linked accounts using its stored keychain secret (the agent never supplies a
130/// secret). Backs the `IdentityValidate` MCP tool.
131pub(super) async fn handle_agent_identity_validate(
132    State(state): State<AppState>,
133    caller: Option<Extension<caller::Caller>>,
134    Json(req): Json<AgentIdentityValidateRequest>,
135) -> impl IntoResponse {
136    if let Err(e) = actor::require_token(&state, caller.as_deref(), actor::ActorSite::IdentityValidate, &req.agent_id) {
137        return app_api_response::<()>(Err(e));
138    }
139    app_api_response(
140        app_api::identity_account_validate_stored_impl(
141            &state,
142            app_api::SelfOwner::of(caller.as_deref(), &req.agent_id, "m4c.identity_owner_by_name"),
143            &req.account_id,
144        )
145        .await,
146    )
147}
148
149#[derive(serde::Deserialize)]
150pub(super) struct AgentIdentityCheckLimitsRequest {
151    pub(super) agent_id: String,
152    /// The account (id, label or email) whose limited agents are looked at; every limited agent when absent.
153    #[serde(default)]
154    pub(super) account: Option<String>,
155}
156
157/// `POST /api/v1/agent/identity/check-limits`: look again, now, at the agents marked out of quota. Backs
158/// `Identity` with action `check_limits` (task #2648): a small turn on each, and one that works clears the limit.
159pub(super) async fn handle_agent_identity_check_limits(
160    State(state): State<AppState>,
161    caller: Option<Extension<caller::Caller>>,
162    Json(req): Json<AgentIdentityCheckLimitsRequest>,
163) -> impl IntoResponse {
164    if let Err(e) = actor::require_token(&state, caller.as_deref(), actor::ActorSite::IdentityCheckLimits, &req.agent_id) {
165        return app_api_response::<()>(Err(e));
166    }
167    app_api_response(crate::server::limit_check_api::check_account_limits(state, req.account).await)
168}
169
170#[derive(serde::Deserialize)]
171pub(super) struct SelfQuery {
172    /// Block UUID of the calling agent pane (its `AGENTMUX_BLOCKID`).
173    pub(super) block_id: Option<String>,
174}
175
176/// `GET /api/v1/self?block_id=<id>` — resolve the calling agent's place in the
177/// object tree (block → tab → window → workspace, with their names). The
178/// sidecar serves many agents, so the caller identifies itself by its block id
179/// (the MCP `WhoAmI` tool passes `AGENTMUX_BLOCKID`). Naming verbs reuse the
180/// same resolver to default their target to the agent's own context.
181pub(super) async fn handle_self(
182    State(state): State<AppState>,
183    Query(q): Query<SelfQuery>,
184) -> impl IntoResponse {
185    let block_id = q.block_id.unwrap_or_default();
186    if block_id.is_empty() {
187        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "missing block_id" }))).into_response();
188    }
189    match service::resolve_agent_context(&state.mstore, &block_id) {
190        Ok(ctx) => Json(serde_json::to_value(&ctx).unwrap_or_default()).into_response(),
191        Err(e) => (StatusCode::NOT_FOUND, Json(json!({ "error": e }))).into_response(),
192    }
193}