Skip to main content

agentmux_srv/server/app_api/
pin_ask.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents ask_pin_change` (`POST /api/v1/agent/pin-ask`): an agent asks the person to move or forget one pin, and the
5//! person answers with one click on a card in that agent's own pane (`backend::pin_asks`).
6//!
7//! An agent that acts on its own can only accept a key the hosting install vouches for (`pins::agent_adopt`); every other
8//! change is the person's. This is how the person's decision reaches an agent that was given the work: nothing about the
9//! change comes from the agent's words but its reason. srv reads the pin and what was refused for it, builds the card from
10//! them, and keeps it. The answer is `pins.ask.answer`, which only the AgentMux window can send; it names the ask by id and
11//! carries nothing else, so what changes is what the card showed. srv checks it all again when the person allows: the pin
12//! must still be the one that was shown, and the key or install refused for the name the one that was shown. A no, a
13//! timeout and a closed window all leave the pin as it is. `forget` without a card stays the window's alone.
14//!
15//! The pin log (`logs/pin-changes.log`) names the agent that asked and says the person confirmed it; the audit log has the
16//! ask under the agent and the answer under the person.
17
18use axum::extract::State;
19use axum::http::StatusCode;
20use axum::response::{IntoResponse, Response};
21use axum::{Extension, Json};
22use serde::Deserialize;
23use serde_json::{json, Value};
24
25use super::folder_overlap_ask::{asker_named, refuse, Asker, Refusal};
26use super::pins::{change, confirm_shown, label, Change};
27use super::*;
28use crate::backend::pin_asks::{asks, Asked, Outcome, PinAsk, OPEN_MS};
29use crate::backend::rpc_types::{CommandPinsAskAnswerData, CommandPinsChangeData, PinsAskAnswerResult, PinsAsksResult, COMMAND_PINS_ASKS, COMMAND_PINS_ASK_ANSWER};
30use crate::server::caller::Caller;
31use crate::server::reactive::lan_continuity::fingerprint;
32use crate::server::reactive::lan_refusals;
33
34/// The audit entry's action for an ask, and for the person's two answers.
35pub(crate) const AUDIT_ASK: &str = "pins.ask";
36const AUDIT_ALLOW: &str = "pins.ask.allow";
37const AUDIT_DECLINE: &str = "pins.ask.decline";
38
39/// The longest reason an agent may give, in characters.
40const MAX_REASON: usize = 300;
41
42/// What a caller is told when it is not the window.
43const ONLY_THE_PERSON_ANSWERS: &str = "only the person answers an agent's ask to change a pin, from the AgentMux window";
44
45#[derive(Debug, Deserialize)]
46pub(crate) struct AskRequest {
47    /// `move` (accept the key or install refused for the name) or `forget`.
48    pub change: String,
49    /// `lan` or `wan`.
50    pub kind: String,
51    /// The name the pin is for.
52    pub agent_id: String,
53    /// The channel of a `wan` pin.
54    #[serde(default)]
55    pub channel: Option<String>,
56    /// What the agent saw: for `move` the refused key (its fingerprint) or install (its label), for `forget` the pinned one. The
57    /// ask is refused if it is no longer that.
58    #[serde(default)]
59    pub expect: Option<String>,
60    /// Why, in the agent's words; the card shows it as the agent's.
61    #[serde(default)]
62    pub reason: String,
63}
64
65/// The pin and what is refused for it, as srv holds them now, in the words of the card.
66struct Shown {
67    from: String,
68    from_install: String,
69    to: String,
70    to_install: String,
71}
72
73fn internal(e: impl std::fmt::Display) -> Refusal {
74    refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("pins: {e}"))
75}
76
77/// A reason on one line, with no control characters; refused when empty or long.
78fn clean_reason(reason: &str) -> Result<String, Refusal> {
79    let one_line = reason.split_whitespace().collect::<Vec<_>>().join(" ");
80    let one_line: String = one_line.chars().filter(|c| !c.is_control()).collect();
81    if one_line.is_empty() {
82        return Err(refuse(StatusCode::BAD_REQUEST, "Agents ask_pin_change needs a reason: say in a sentence why the pin should change; the person reads it"));
83    }
84    if one_line.chars().count() > MAX_REASON {
85        return Err(refuse(StatusCode::BAD_REQUEST, format!("Agents ask_pin_change: the reason is at most {MAX_REASON} characters")));
86    }
87    Ok(one_line)
88}
89
90fn stale(what: String) -> Refusal {
91    refuse(StatusCode::CONFLICT, what)
92}
93
94/// The pin now (a key's fingerprint, or an install's label), and the install it is bound to.
95fn pin_now(state: &AppState, kind: &str, agent: &str, channel: &str) -> Result<Option<(String, String)>, Refusal> {
96    match kind {
97        "lan" => {
98            let Some((key, _since)) = state.mstore.lan_peer_pubkey_pin_since(agent).map_err(internal)? else { return Ok(None) };
99            let bound = state.mstore.lan_pin_installed(agent).ok().flatten().map(|i| label(&i.host_hint, &i.instance_id)).unwrap_or_default();
100            Ok(Some((fingerprint(&key), bound)))
101        }
102        _ => {
103            let Some(wan) = crate::backend::storage::wan_identity::global() else { return Ok(None) };
104            let pin = wan.agent_instance_pin_get(agent, channel).map_err(internal)?;
105            Ok(pin.map(|p| (label(&p.host_hint, &p.instance_id), String::new())))
106        }
107    }
108}
109
110/// What the person would be shown for this request, from srv's own record; refused when the pin or the refused key is not what the
111/// agent saw.
112fn describe(state: &AppState, req: &AskRequest, how: Change, agent: &str, channel: &str) -> Result<Shown, Refusal> {
113    let (from, from_install) = pin_now(state, &req.kind, agent, channel)?.ok_or_else(|| {
114        stale(format!("no {} pin for {agent}: there is nothing to move or forget (a name with no pin takes its first key with pins adopt)", req.kind))
115    })?;
116    let expect = req.expect.as_deref();
117    if how == Change::Forget {
118        if expect != Some(from.as_str()) {
119            return Err(stale(format!("the pin for {agent} is not the one named: expect the fingerprint or install now pinned, {from}")));
120        }
121        return Ok(Shown { from, from_install, to: String::new(), to_install: String::new() });
122    }
123    let (to, to_install) = if req.kind == "lan" {
124        let refused = lan_refusals::get(agent)
125            .filter(|r| fingerprint(&r.key_b64) != from)
126            .ok_or_else(|| stale(format!("no other key has been shown for {agent} since AgentMux started")))?;
127        let install = refused.cert.as_ref().map(|c| label(&c.host_hint, &c.instance_id)).unwrap_or_default();
128        (fingerprint(&refused.key_b64), install)
129    } else {
130        let wan = crate::backend::storage::wan_identity::global().ok_or_else(|| stale("this install has no WAN identity".to_string()))?;
131        let pin = wan.agent_instance_pin_get(agent, channel).map_err(internal)?.ok_or_else(|| stale(format!("no WAN pin for {agent} on {channel}")))?;
132        let conflict = pin.conflict.ok_or_else(|| stale(format!("no other install has spoken for {agent} on {channel}")))?;
133        (label(&conflict.host_hint, &conflict.instance_id), String::new())
134    };
135    confirm_shown(expect, &to, agent).map_err(stale)?;
136    Ok(Shown { from, from_install, to, to_install })
137}
138
139fn how_of(change: &str) -> Option<Change> {
140    match change {
141        "move" => Some(Change::Adopt),
142        "forget" => Some(Change::Forget),
143        _ => None,
144    }
145}
146
147/// Where an ask for the change stands, asking the person when they have not been asked.
148pub(crate) fn ask(state: &AppState, asker: &Asker, req: &AskRequest, now_ms: u64) -> Result<Value, Refusal> {
149    let change = req.change.trim();
150    let how = how_of(change).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, "Agents ask_pin_change: change is move or forget"))?;
151    let agent = req.agent_id.trim().to_lowercase();
152    if agent.is_empty() {
153        return Err(refuse(StatusCode::BAD_REQUEST, "Agents ask_pin_change: no agent named"));
154    }
155    let channel = req.channel.as_deref().map(str::trim).unwrap_or_default();
156    match (req.kind.as_str(), channel.is_empty()) {
157        ("lan", true) | ("wan", false) => {}
158        ("lan", false) => return Err(refuse(StatusCode::BAD_REQUEST, "Agents ask_pin_change: a LAN pin has no channel")),
159        ("wan", true) => return Err(refuse(StatusCode::BAD_REQUEST, "Agents ask_pin_change: a WAN pin needs its channel")),
160        (other, _) => return Err(refuse(StatusCode::BAD_REQUEST, format!("Agents ask_pin_change: unknown kind {other:?} (lan or wan)"))),
161    }
162    let reason = clean_reason(&req.reason)?;
163    let shown = match describe(state, req, how, &agent, channel) {
164        Ok(shown) => shown,
165        // This agent's own ask for exactly this was allowed a moment ago: the pin has moved, so there is nothing left to describe.
166        Err(why) => {
167            return match asks().allowed_ago_ms(change, &req.kind, &agent, channel, &asker.slug, req.expect.as_deref().unwrap_or_default(), now_ms) {
168                Some(ago) => Ok(json!({ "status": "allowed", "seconds_ago": ago / 1000, "note": "the person allowed this change; it is done" })),
169                None => Err(why),
170            }
171        }
172    };
173    if asker.block_id.is_empty() {
174        return Err(refuse(StatusCode::CONFLICT, "Agents ask_pin_change shows its card in the asking agent's pane, and this agent has no open pane to show it in"));
175    }
176    let card = PinAsk {
177        id: uuid::Uuid::new_v4().to_string(),
178        change: change.to_string(),
179        kind: req.kind.clone(),
180        agent_id: agent.clone(),
181        channel: channel.to_string(),
182        from: shown.from,
183        from_install: shown.from_install,
184        to: shown.to,
185        to_install: shown.to_install,
186        reason,
187        agent: asker.name.clone(),
188        asker_id: asker.slug.clone(),
189        block_id: asker.block_id.clone(),
190        requested_ms: now_ms,
191    };
192    match asks().ask(card, now_ms) {
193        Asked::Waiting { ask: kept, new } => {
194            publish_asks(state);
195            if new {
196                audit(state, Some(&asker.slug), AUDIT_ASK, &kept);
197            }
198            Ok(json!({
199                "status": "asked",
200                "expires_in_seconds": (OPEN_MS.saturating_sub(now_ms.saturating_sub(kept.requested_ms))).div_ceil(1000),
201                "note": "the person is asked in your pane; ask_pin_change again with the same arguments for their answer. No answer in time counts as a no",
202            }))
203        }
204        Asked::Settled { outcome: Outcome::Allowed, .. } => Ok(json!({ "status": "allowed", "note": "the person allowed this change; it is done" })),
205        Asked::Settled { outcome: Outcome::Declined, retry_after_ms } => Ok(json!({
206            "status": "declined",
207            "retry_after_seconds": retry_after_ms.div_ceil(1000),
208            "note": "the person said no to this change; it is not asked again for a while",
209        })),
210        Asked::Settled { outcome: Outcome::Expired, .. } => Ok(json!({
211            "status": "expired",
212            "note": "nobody answered in time, which is a no; ask again if the change is still needed",
213        })),
214    }
215}
216
217/// Tells every window the asks now waiting.
218pub(crate) fn publish_asks(state: &AppState) {
219    let event = crate::backend::mps_events::PinAsksEvent { asks: asks().list(agentmux_common::time::now_ms_u64()) };
220    state.broker.publish_event::<crate::backend::mps_events::PinAsks>(&event, vec![], 0);
221}
222
223/// Ends the asks for a pin that just changed, whichever way it did.
224pub(crate) fn pin_changed(state: &AppState, kind: &str, agent: &str, channel: &str) {
225    asks().forget_pin(kind, agent, channel, agentmux_common::time::now_ms_u64());
226    publish_asks(state);
227}
228
229/// Records an ask under the agent that made it, or an answer under the person (`by` is `None`).
230fn audit(state: &AppState, by: Option<&str>, action: &str, ask: &PinAsk) {
231    let note = match ask.change.as_str() {
232        "forget" => format!("{} asked to forget the {} pin for {} ({}): {}", ask.agent, ask.kind, ask.agent_id, ask.from, ask.reason),
233        _ => format!("{} asked to move the {} pin for {} from {} to {}: {}", ask.agent, ask.kind, ask.agent_id, ask.from, ask.to, ask.reason),
234    };
235    tracing::info!(action, "{note}");
236    let request_id = uuid::Uuid::new_v4().to_string();
237    state.reactive_handler.log_fleet_action_audit(by, &ask.agent_id, &ask.block_id, action, true, None, &request_id, Some(&note));
238}
239
240/// What the person allowed, applied as srv holds the pin now: refused if it is not what the card showed.
241fn apply(state: &AppState, ask: &PinAsk) -> Result<(), String> {
242    let how = how_of(&ask.change).ok_or_else(|| "pins: unknown change".to_string())?;
243    let now = pin_now(state, &ask.kind, &ask.agent_id, &ask.channel).map_err(|r| r.message)?;
244    if now.map(|(from, _)| from).as_deref() != Some(ask.from.as_str()) {
245        return Err(format!("pins: the pin for {} is not the one the card showed, so nothing was changed; ask again", ask.agent_id));
246    }
247    let req = CommandPinsChangeData {
248        kind: ask.kind.clone(),
249        agent_id: ask.agent_id.clone(),
250        channel: (!ask.channel.is_empty()).then(|| ask.channel.clone()),
251        // The key or install the card showed: the change is refused if what was refused for the name is another.
252        expect: (how == Change::Adopt).then(|| ask.to.clone()),
253    };
254    change(state, &req, how, Some(&ask.asker_id))
255}
256
257/// The person's answer to one ask: taken once, by its id, and applied exactly as the card showed it.
258fn answer(state: &AppState, cmd: CommandPinsAskAnswerData) -> Result<PinsAskAnswerResult, String> {
259    let now = agentmux_common::time::now_ms_u64();
260    let Some(ask) = asks().take(&cmd.id, now) else {
261        publish_asks(state);
262        return Ok(PinsAskAnswerResult { outcome: "gone".to_string() });
263    };
264    if !cmd.allow {
265        asks().settle(&ask, Outcome::Declined, now);
266        publish_asks(state);
267        audit(state, None, AUDIT_DECLINE, &ask);
268        return Ok(PinsAskAnswerResult { outcome: "declined".to_string() });
269    }
270    // The ask is gone either way; a change that no longer fits is not remembered as a no, so the agent can ask again.
271    let applied = apply(state, &ask);
272    if applied.is_ok() {
273        asks().settle(&ask, Outcome::Allowed, now);
274        audit(state, None, AUDIT_ALLOW, &ask);
275    }
276    publish_asks(state);
277    applied.map(|()| PinsAskAnswerResult { outcome: "changed".to_string() })
278}
279
280pub(crate) async fn handle_pin_ask(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<AskRequest>) -> Response {
281    let caller = caller.map(|Extension(c)| c);
282    let run = || -> Result<Value, Refusal> {
283        let asker = asker_named(&state, caller.as_ref(), "no agent token: Agents ask_pin_change is an agent's ask; the person changes a pin from the AgentMux window")?;
284        ask(&state, &asker, &req, agentmux_common::time::now_ms_u64())
285    };
286    match run() {
287        Ok(body) => Json(body).into_response(),
288        Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
289    }
290}
291
292pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
293    let st = state.clone();
294    engine.register_typed(COMMAND_PINS_ASK_ANSWER, move |cmd: CommandPinsAskAnswerData, ctx| {
295        let state = st.clone();
296        async move {
297            ctx.operator_only(ONLY_THE_PERSON_ANSWERS)?;
298            answer(&state, cmd)
299        }
300    });
301    engine.register_typed(COMMAND_PINS_ASKS, |_req: Value, ctx| async move {
302        ctx.operator_only(ONLY_THE_PERSON_ANSWERS)?;
303        Ok(PinsAsksResult { asks: asks().list(agentmux_common::time::now_ms_u64()) })
304    });
305}
306
307#[cfg(test)]
308#[path = "pin_ask_tests.rs"]
309mod tests;