Skip to main content

agentmux_srv/sagas/
agent_notice.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent doing something the person may want to stop, told to the person in
5//! the agent's own pane (docs/specs/SPEC_AGENT_SPAWN_NOTICE_IN_THE_PANE_2026_11_08.md):
6//! starting an agent, using the person's SSH keys on a host, using a Google
7//! connector, adopting memory. It replaces the approval window that opened over
8//! the pane and refused when nobody clicked.
9//!
10//! Nothing waits for a click. [`announce`] decides by the requester's state:
11//! - **Waived** (the person's own turn asked for it, or the "Agents may start
12//!   agents" setting is on), or the person said **Always** to this agent
13//!   before: it goes ahead at once, and the pane gets a one-line notice.
14//! - **No window connected** (headless): nobody could stop it, so it goes ahead
15//!   at once, and is logged.
16//! - Otherwise a **card** with a 30 s countdown: **Stop it**, **Start now**, **Always
17//!   allow this agent**. If nobody acts it goes ahead at the deadline. The
18//!   requester closed or deleted (no pane left, or its agent stopped) ends it
19//!   as [`Outcome::Gone`]. A parked agent is still running, so it does not.
20//!
21//! The person's choice comes only through `agent.notice.decide`, accepted only
22//! from the proven AgentMux window (`operator_only`): an agent can't stop,
23//! hurry or grant on the person's behalf, which is the one guard kept. The card
24//! is drawn from srv's own record, with the agent's own words only as the quoted
25//! brief.
26
27use std::collections::HashMap;
28use std::sync::{Arc, LazyLock, Mutex};
29use std::time::Duration;
30
31use serde::{Deserialize, Serialize};
32
33use crate::backend::agent_grants::{self, Topic};
34pub use crate::backend::prompt_events::{GrantsEvent, NoticeView, EVENT_AGENT_GRANTS, EVENT_AGENT_NOTICE};
35use crate::backend::rpc::engine::WshRpcEngine;
36use crate::server::AppState;
37use agentmux_common::time::now_ms;
38
39/// The person's Stop it, Start now or Always for a countdown.
40pub const COMMAND_AGENT_NOTICE_DECIDE: &str = "agent.notice.decide";
41/// The person's switch of one agent's "Always" (the pane menu and Settings).
42pub const COMMAND_AGENT_NOTICE_SET_GRANT: &str = "agent.notice.setgrant";
43/// The agents with an "Always" for a topic.
44pub const COMMAND_AGENT_NOTICE_GRANTS: &str = "agent.notice.grants";
45/// The one place the length of the wait is set.
46pub const COUNTDOWN: Duration = Duration::from_secs(30);
47/// How often a waiting countdown looks for its requester.
48const WATCH_EVERY: Duration = Duration::from_millis(500);
49/// A settled countdown stays answerable (as "too late") this long.
50const KEEP_FINISHED_MS: i64 = 60_000;
51/// How many events are kept for a window that opens mid-countdown.
52const REPLAY_EVENTS: usize = 32;
53
54/// What the notice is about.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Kind {
57    /// Starting a worker, creating an agent, or starting workers.
58    Spawn,
59    /// Running a command on an SSH host with the person's keys.
60    SshAccess,
61    /// A Google connector action the agent's definition asks to confirm.
62    Google,
63    /// Adopting memory from the agent's earlier accounts.
64    Memory,
65}
66
67impl Kind {
68    fn wire(self) -> &'static str {
69        match self {
70            Kind::Spawn => "spawn",
71            Kind::SshAccess => "ssh",
72            Kind::Google => "google",
73            Kind::Memory => "memory",
74        }
75    }
76
77    fn topic(self) -> Option<Topic> {
78        match self {
79            Kind::Spawn => Some(Topic::Spawn),
80            Kind::Google => Some(Topic::Google),
81            Kind::Memory => Some(Topic::Memory),
82            Kind::SshAccess => None,
83        }
84    }
85}
86
87/// Why no card was needed.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum Waiver {
90    /// The person's own turn asked for it.
91    UserTurn,
92    /// The person turned on "Agents may start agents".
93    Setting,
94}
95
96/// What the person is told, and what a grant is keyed by. Built by srv from its own record.
97#[derive(Debug, Clone)]
98pub struct Notice {
99    pub kind: Kind,
100    /// The requester's pane.
101    pub block_id: String,
102    /// The requester's definition id: what "Always" belongs to. Empty: no "Always".
103    pub agent_id: String,
104    /// The requester's name.
105    pub agent: String,
106    /// The SSH host, for [`Kind::SshAccess`].
107    pub connection: String,
108    /// "Posa is starting Korp-2": one line.
109    pub headline: String,
110    /// The facts: model, route, who pays.
111    pub body: String,
112    /// The agent's own words (its brief), shown quoted and clipped; empty for none.
113    pub quote: String,
114    /// The Always button's words; empty offers none.
115    pub always_label: String,
116    pub waived: Option<Waiver>,
117}
118
119/// Why it goes ahead.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum Go {
122    Waived(Waiver),
123    /// The person said Always earlier.
124    Granted,
125    /// No window is connected to stop it in.
126    Headless,
127    /// Nobody acted before the deadline.
128    Deadline,
129    /// The person pressed Start now.
130    Now,
131    /// The person pressed Always.
132    Always,
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum Outcome {
137    Go(Go),
138    /// The person pressed Stop it.
139    Stopped,
140    /// The requester is gone: nothing is left to start it for.
141    Gone,
142}
143
144impl Outcome {
145    pub fn goes(self) -> bool {
146        matches!(self, Outcome::Go(_))
147    }
148
149    fn wire(self) -> &'static str {
150        match self {
151            Outcome::Go(Go::Now) => "now",
152            Outcome::Go(Go::Always) => "always",
153            Outcome::Go(_) => "deadline",
154            Outcome::Stopped => "stopped",
155            Outcome::Gone => "gone",
156        }
157    }
158}
159
160/// Data for `agent.notice.decide`: the card's `id` (from `agent:notice`).
161#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
162#[ts(export, export_to = "../../../frontend/types/rpc/")]
163pub struct CommandAgentNoticeDecideData {
164    pub request_id: String,
165    #[ts(type = r#""veto" | "now" | "always""#)]
166    pub choice: String,
167}
168
169/// How the person's choice came out: `too_late` when the countdown had ended.
170#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
171#[ts(export, export_to = "../../../frontend/types/rpc/")]
172pub struct AgentNoticeDecideResult {
173    #[ts(type = r#""stopped" | "started" | "always" | "too_late""#)]
174    pub outcome: String,
175}
176
177/// Data for `agent.notice.setgrant`.
178#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
179#[ts(export, export_to = "../../../frontend/types/rpc/")]
180pub struct CommandAgentNoticeSetGrantData {
181    #[ts(type = r#""spawn" | "google" | "memory""#)]
182    pub topic: String,
183    /// The agent's definition id.
184    pub agent_id: String,
185    pub allowed: bool,
186}
187
188/// Data for `agent.notice.grants`.
189#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
190#[ts(export, export_to = "../../../frontend/types/rpc/")]
191pub struct CommandAgentNoticeGrantsData {
192    #[ts(type = r#""spawn" | "google" | "memory""#)]
193    pub topic: String,
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
197#[ts(export, export_to = "../../../frontend/types/rpc/")]
198pub struct AgentNoticeGrantsResult {
199    pub agents: Vec<String>,
200}
201
202#[derive(Clone, Copy, PartialEq, Eq)]
203enum Choice {
204    Veto,
205    Now,
206    Always,
207}
208
209struct Entry {
210    view: NoticeView,
211    notice: Notice,
212    choice: Option<Choice>,
213    wake: Arc<tokio::sync::Notify>,
214    finished_at_ms: Option<i64>,
215}
216
217static ENTRIES: LazyLock<Mutex<HashMap<String, Entry>>> = LazyLock::new(Default::default);
218
219fn entries() -> std::sync::MutexGuard<'static, HashMap<String, Entry>> {
220    ENTRIES.lock().unwrap_or_else(|e| e.into_inner())
221}
222
223/// The countdowns still running.
224pub fn pending() -> Vec<NoticeView> {
225    entries().values().filter(|e| e.view.status == "pending").map(|e| e.view.clone()).collect()
226}
227
228fn view_of(id: &str, n: &Notice, status: &'static str, opened_ms: i64, deadline_ms: i64) -> NoticeView {
229    NoticeView {
230        id: id.to_string(),
231        kind: n.kind.wire(),
232        block_id: n.block_id.clone(),
233        agent: n.agent.clone(),
234        headline: n.headline.clone(),
235        body: n.body.clone(),
236        quote: n.quote.clone(),
237        always_label: if n.agent_id.is_empty() { String::new() } else { n.always_label.clone() },
238        deadline_ms,
239        opened_ms,
240        status,
241        outcome: String::new(),
242    }
243}
244
245/// Whether the person already said Always to this requester.
246fn granted(n: &Notice) -> bool {
247    if n.agent_id.is_empty() {
248        return false;
249    }
250    match n.kind.topic() {
251        Some(topic) => agent_grants::allowed(topic, &n.agent_id),
252        None => crate::backend::remote::agent_access::always_allowed(&n.agent_id, &n.connection),
253    }
254}
255
256/// Tell the person, then say whether the thing goes ahead. `alive` says whether the requester is
257/// still there (its pane exists and its agent runs), asked while the countdown runs.
258pub async fn announce(state: &AppState, notice: Notice, alive: impl Fn() -> bool) -> Outcome {
259    announce_for(state, notice, alive, COUNTDOWN).await
260}
261
262/// [`announce`] with a countdown of `window`.
263pub async fn announce_for(state: &AppState, notice: Notice, alive: impl Fn() -> bool, window: Duration) -> Outcome {
264    if let Some(why) = notice.waived {
265        line(state, &notice);
266        return Outcome::Go(Go::Waived(why));
267    }
268    if granted(&notice) {
269        // Only a start is worth a line each time: an SSH command or a connector call is frequent, and
270        // its host row (Remotes) or its agent's settings already show the grant.
271        if notice.kind == Kind::Spawn {
272            line(state, &notice);
273        }
274        return Outcome::Go(Go::Granted);
275    }
276    if state.host_ipc.lock().await.is_none() {
277        tracing::info!(kind = notice.kind.wire(), agent = %notice.agent, "agent notice: no window is connected to stop it in, so it goes ahead");
278        return Outcome::Go(Go::Headless);
279    }
280    countdown(state, notice, alive, window).await
281}
282
283/// The one-line notice, for a start nobody needs to answer.
284fn line(state: &AppState, n: &Notice) {
285    let now = now_ms();
286    let view = view_of(&uuid::Uuid::new_v4().to_string(), n, "line", now, 0);
287    state.broker.publish_event::<crate::backend::mps_events::AgentNotice>(&view, vec![], 0);
288}
289
290async fn countdown(state: &AppState, notice: Notice, alive: impl Fn() -> bool, window: Duration) -> Outcome {
291    let id = uuid::Uuid::new_v4().to_string();
292    let opened = now_ms();
293    let deadline = tokio::time::Instant::now() + window;
294    let view = view_of(&id, &notice, "pending", opened, opened + window.as_millis() as i64);
295    let wake = Arc::new(tokio::sync::Notify::new());
296    {
297        let mut map = entries();
298        map.retain(|_, e| e.finished_at_ms.is_none_or(|t| opened - t < KEEP_FINISHED_MS));
299        map.insert(id.clone(), Entry { view: view.clone(), notice: notice.clone(), choice: None, wake: wake.clone(), finished_at_ms: None });
300    }
301    state.broker.publish_event::<crate::backend::mps_events::AgentNotice>(&view, vec![], REPLAY_EVENTS);
302    // The pane's waiting tone, tab badge and notification, while it counts.
303    let _asking = crate::backend::user_attention::Asking::start(&state.broker, &state.mstore, &notice.block_id, "consent", &notice.headline);
304    tracing::info!(kind = notice.kind.wire(), agent = %notice.agent, request_id = %id, "agent notice: the person has {} s to stop it", window.as_secs());
305
306    let mut ending = Ending { broker: state.broker.clone(), id: id.clone(), view, kind: notice.kind.wire(), agent: notice.agent.clone(), done: false };
307    let fallback = loop {
308        let left = deadline.saturating_duration_since(tokio::time::Instant::now());
309        if left.is_zero() {
310            break Outcome::Go(Go::Deadline);
311        }
312        tokio::select! {
313            _ = tokio::time::sleep(left.min(WATCH_EVERY)) => {}
314            _ = wake.notified() => {}
315        }
316        if choice_of(&id).is_some() {
317            break Outcome::Go(Go::Deadline);
318        }
319        if !alive() {
320            break Outcome::Gone;
321        }
322    };
323    ending.finish(fallback)
324}
325
326/// Ends a countdown however it ends: its caller can be dropped while it waits (the agent's request
327/// closed with the agent), and the card must still go.
328struct Ending {
329    broker: Arc<crate::backend::mps::Broker>,
330    id: String,
331    view: NoticeView,
332    kind: &'static str,
333    agent: String,
334    done: bool,
335}
336
337impl Ending {
338    fn finish(&mut self, fallback: Outcome) -> Outcome {
339        let outcome = settle(&self.id, fallback);
340        self.done = true;
341        let mut done = self.view.clone();
342        done.status = "cleared";
343        done.outcome = outcome.wire().to_string();
344        self.broker.publish_event::<crate::backend::mps_events::AgentNotice>(&done, vec![], REPLAY_EVENTS);
345        tracing::info!(kind = self.kind, agent = %self.agent, request_id = %self.id, outcome = outcome.wire(), "agent notice: ended");
346        outcome
347    }
348}
349
350impl Drop for Ending {
351    fn drop(&mut self) {
352        if !self.done {
353            self.finish(Outcome::Gone);
354        }
355    }
356}
357
358fn choice_of(id: &str) -> Option<Choice> {
359    entries().get(id).and_then(|e| e.choice)
360}
361
362/// End the countdown `id`: the person's choice if they made one (it wins over `fallback`, however
363/// close to the deadline), else `fallback`. After this the countdown answers "too late".
364fn settle(id: &str, fallback: Outcome) -> Outcome {
365    let mut map = entries();
366    let Some(e) = map.get_mut(id) else { return fallback };
367    let outcome = match e.choice {
368        Some(Choice::Veto) => Outcome::Stopped,
369        Some(Choice::Now) => Outcome::Go(Go::Now),
370        Some(Choice::Always) => Outcome::Go(Go::Always),
371        None => fallback,
372    };
373    e.view.status = "cleared";
374    e.view.outcome = outcome.wire().to_string();
375    e.finished_at_ms = Some(now_ms());
376    outcome
377}
378
379/// The person's choice for countdown `id`. `Always` first remembers the grant (and says so if it
380/// could not), then starts the thing.
381pub fn decide(state: &AppState, id: &str, choice: &str) -> Result<&'static str, String> {
382    let choice = match choice {
383        "veto" => Choice::Veto,
384        "now" => Choice::Now,
385        "always" => Choice::Always,
386        other => return Err(format!("INVALID_ARG: choice is 'veto', 'now' or 'always', not '{}'", other.chars().take(20).collect::<String>())),
387    };
388    // One lock from the check to the grant and the choice: a countdown that ends in between
389    // (`settle` takes the same lock) leaves no grant behind for a person who was told "too late".
390    let mut map = entries();
391    let Some(e) = map.get_mut(id).filter(|e| e.view.status == "pending" && e.choice.is_none()) else {
392        return Ok("too_late");
393    };
394    if choice == Choice::Always {
395        remember(state, &e.notice)?;
396    }
397    e.choice = Some(choice);
398    e.wake.notify_one();
399    Ok(match choice {
400        Choice::Veto => "stopped",
401        Choice::Now => "started",
402        Choice::Always => "always",
403    })
404}
405
406/// Write the "Always" the card offered.
407fn remember(state: &AppState, n: &Notice) -> Result<(), String> {
408    if n.agent_id.is_empty() || n.always_label.is_empty() {
409        return Err("INVALID_ARG: this notice offers no Always".to_string());
410    }
411    match n.kind.topic() {
412        Some(topic) => {
413            agent_grants::allow(topic, &n.agent_id).map_err(|e| format!("could not remember Always: {e}"))?;
414            publish_grants(state, topic);
415        }
416        None => {
417            crate::server::app_api::connections::remember_always_in(&state.broker, &crate::backend::base::get_mux_config_dir(), &n.agent_id, &n.connection)
418                .map_err(|e| format!("could not remember Always: {e}"))?;
419        }
420    }
421    Ok(())
422}
423
424fn topic_of(name: &str) -> Result<Topic, String> {
425    match name {
426        "spawn" => Ok(Topic::Spawn),
427        "google" => Ok(Topic::Google),
428        "memory" => Ok(Topic::Memory),
429        other => Err(format!("INVALID_ARG: topic is 'spawn', 'google' or 'memory', not '{}'", other.chars().take(20).collect::<String>())),
430    }
431}
432
433fn topic_wire(t: Topic) -> &'static str {
434    match t {
435        Topic::Spawn => "spawn",
436        Topic::Google => "google",
437        Topic::Memory => "memory",
438    }
439}
440
441fn publish_grants(state: &AppState, topic: Topic) {
442    let event = GrantsEvent { topic: topic_wire(topic), agents: agent_grants::all(topic) };
443    state.broker.publish_event::<crate::backend::mps_events::AgentGrants>(&event, vec![], 1);
444}
445
446/// `agent.notice.decide`, `agent.notice.setgrant` and `agent.notice.grants`. The first two are
447/// accepted only from the proven AgentMux window (`operator_only`), never from an agent: an agent
448/// can't stop, hurry or grant on the person's behalf.
449pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
450    let s = state.clone();
451    engine.register_typed(COMMAND_AGENT_NOTICE_DECIDE, move |cmd: CommandAgentNoticeDecideData, ctx| {
452        let state = s.clone();
453        async move {
454            ctx.operator_only("only the person can stop, hurry or auto-approve what an agent does")?;
455            let outcome = decide(&state, &cmd.request_id, &cmd.choice)?;
456            Ok(AgentNoticeDecideResult { outcome: outcome.to_string() })
457        }
458    });
459    let s = state.clone();
460    engine.register_typed(COMMAND_AGENT_NOTICE_SET_GRANT, move |cmd: CommandAgentNoticeSetGrantData, ctx| {
461        let state = s.clone();
462        async move {
463            ctx.operator_only("only the person can let an agent act without a notice")?;
464            let topic = topic_of(&cmd.topic)?;
465            if cmd.agent_id.trim().is_empty() {
466                return Err("INVALID_ARG: agent_id is required".to_string());
467            }
468            if cmd.allowed {
469                agent_grants::allow(topic, &cmd.agent_id).map_err(|e| e.to_string())?;
470            } else {
471                agent_grants::revoke(topic, &cmd.agent_id).map_err(|e| e.to_string())?;
472            }
473            publish_grants(&state, topic);
474            Ok(AgentNoticeGrantsResult { agents: agent_grants::all(topic) })
475        }
476    });
477    engine.register_typed(COMMAND_AGENT_NOTICE_GRANTS, move |cmd: CommandAgentNoticeGrantsData, _ctx| async move {
478        Ok(AgentNoticeGrantsResult { agents: agent_grants::all(topic_of(&cmd.topic)?) })
479    });
480}
481
482#[cfg(test)]
483#[path = "agent_notice_tests.rs"]
484mod tests;