1use 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
39pub const COMMAND_AGENT_NOTICE_DECIDE: &str = "agent.notice.decide";
41pub const COMMAND_AGENT_NOTICE_SET_GRANT: &str = "agent.notice.setgrant";
43pub const COMMAND_AGENT_NOTICE_GRANTS: &str = "agent.notice.grants";
45pub const COUNTDOWN: Duration = Duration::from_secs(30);
47const WATCH_EVERY: Duration = Duration::from_millis(500);
49const KEEP_FINISHED_MS: i64 = 60_000;
51const REPLAY_EVENTS: usize = 32;
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Kind {
57 Spawn,
59 SshAccess,
61 Google,
63 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum Waiver {
90 UserTurn,
92 Setting,
94}
95
96#[derive(Debug, Clone)]
98pub struct Notice {
99 pub kind: Kind,
100 pub block_id: String,
102 pub agent_id: String,
104 pub agent: String,
106 pub connection: String,
108 pub headline: String,
110 pub body: String,
112 pub quote: String,
114 pub always_label: String,
116 pub waived: Option<Waiver>,
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum Go {
122 Waived(Waiver),
123 Granted,
125 Headless,
127 Deadline,
129 Now,
131 Always,
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum Outcome {
137 Go(Go),
138 Stopped,
140 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#[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#[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#[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 pub agent_id: String,
185 pub allowed: bool,
186}
187
188#[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
223pub 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
245fn 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
256pub async fn announce(state: &AppState, notice: Notice, alive: impl Fn() -> bool) -> Outcome {
259 announce_for(state, notice, alive, COUNTDOWN).await
260}
261
262pub 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, ¬ice);
266 return Outcome::Go(Go::Waived(why));
267 }
268 if granted(¬ice) {
269 if notice.kind == Kind::Spawn {
272 line(state, ¬ice);
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
283fn 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, ¬ice, "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 let _asking = crate::backend::user_attention::Asking::start(&state.broker, &state.mstore, ¬ice.block_id, "consent", ¬ice.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
326struct 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
362fn 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
379pub 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 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
406fn 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
446pub 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;