1use std::collections::{HashMap, HashSet};
9use std::hash::{Hash, Hasher};
10use std::sync::{Arc, Mutex, OnceLock};
11
12use serde::Deserialize;
13
14use crate::ambient::digest;
15use crate::backend::blockcontroller::core::broadcast_block_update;
16use crate::backend::blockcontroller::health::{TriggerKind, TurnEnd, TurnInput, TurnTrigger};
17use crate::backend::eventbus::EventBus;
18use crate::backend::mps::{Broker, MuxEvent, EVENT_AGENT_TURN};
19use crate::backend::notify::policy::NotifyKind;
20use crate::backend::obj::Block;
21use crate::backend::storage::background_tasks::BackgroundTaskStatus;
22use crate::backend::storage::filestore::FileStore;
23use crate::backend::storage::store::Store;
24
25use super::judge::{self, Judgement};
26use super::pacing::{self, WaitOver};
27use super::settings::{self, NoticeGroup};
28use super::policy::{self, Action, PreJudge, TurnFacts};
29use super::{
30 message, supports, SupervisorAction, SupervisorDecision, SupervisorMode, SupervisorState, SupervisorStatus,
31 Verdict, META_MODE, META_STATE,
32};
33
34#[derive(Deserialize)]
36struct PublishedTurn {
37 block_id: String,
38 turn_id: u64,
39 #[serde(default)]
40 ended_at_ms: Option<u64>,
41 #[serde(default)]
42 end: Option<TurnEnd>,
43 #[serde(default)]
44 trigger: Option<TurnTrigger>,
45 #[serde(default)]
47 absorbed: Vec<TurnTrigger>,
48 #[serde(default)]
49 steps: u32,
50}
51
52impl PublishedTurn {
53 fn effective_trigger(&self) -> Option<TriggerKind> {
57 let first = self.trigger.as_ref().map(|t| t.kind);
58 if first != Some(TriggerKind::System) {
59 return first;
60 }
61 self.absorbed.iter().map(|t| t.kind).find(|k| *k != TriggerKind::System).or(first)
62 }
63}
64
65#[derive(Clone, Debug, PartialEq, Eq)]
67struct TurnEnded {
68 block_id: String,
69 turn_id: u64,
70 ended_at_ms: u64,
71 trigger: Option<TriggerKind>,
72 steps: u32,
73}
74
75fn parse_turn_ended(data: &serde_json::Value) -> Option<TurnEnded> {
78 let t = PublishedTurn::deserialize(data).ok()?;
79 if t.end != Some(TurnEnd::Completed) {
80 return None;
81 }
82 let trigger = t.effective_trigger();
83 Some(TurnEnded {
84 block_id: t.block_id,
85 turn_id: t.turn_id,
86 ended_at_ms: t.ended_at_ms.unwrap_or(0),
87 trigger,
88 steps: t.steps,
89 })
90}
91
92const SEEN_MAX: usize = 1024;
94
95pub struct Supervisor {
96 mstore: Arc<Store>,
97 filestore: Arc<FileStore>,
98 event_bus: Arc<EventBus>,
99 broker: Arc<Broker>,
100 runs: Mutex<HashMap<String, SupervisorState>>,
102 generations: Mutex<HashMap<String, u64>>,
104 locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
106 seen: Mutex<HashSet<(String, u64, u64)>>,
108 budget: Mutex<pacing::Budget>,
110 budget_noticed: std::sync::atomic::AtomicBool,
112}
113
114static INSTANCE: OnceLock<Arc<Supervisor>> = OnceLock::new();
115
116pub fn instance() -> Option<Arc<Supervisor>> {
118 INSTANCE.get().cloned()
119}
120
121pub fn start(mstore: Arc<Store>, filestore: Arc<FileStore>, event_bus: Arc<EventBus>, broker: Arc<Broker>) {
123 let sup = Arc::new(Supervisor {
124 mstore,
125 filestore,
126 event_bus,
127 broker: broker.clone(),
128 runs: Mutex::default(),
129 generations: Mutex::default(),
130 locks: Mutex::default(),
131 seen: Mutex::default(),
132 budget: Mutex::default(),
133 budget_noticed: Default::default(),
134 });
135 if INSTANCE.set(sup.clone()).is_err() {
136 return;
137 }
138 sup.drop_restarted_waits();
140 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<TurnEnded>();
141 broker.add_observer(Arc::new(move |ev: &MuxEvent| {
143 if ev.event != EVENT_AGENT_TURN {
144 return;
145 }
146 if let Some(end) = ev.data.as_ref().and_then(parse_turn_ended) {
147 let _ = tx.send(end);
148 }
149 }));
150 tokio::spawn(async move {
151 while let Some(end) = rx.recv().await {
152 if !sup.first_sighting(&end) {
153 continue;
154 }
155 let sup = sup.clone();
156 tokio::spawn(async move {
157 sup.evaluate(&end.block_id, end.trigger, end.steps, true).await;
158 });
159 }
160 });
161}
162
163impl Supervisor {
164 fn drop_restarted_waits(&self) {
168 let blocks = match self.mstore.get_all::<Block>() {
169 Ok(b) => b,
170 Err(e) => {
171 tracing::warn!(error = %e, "supervisor: could not read panes to clear interrupted waits");
172 return;
173 }
174 };
175 for block in blocks {
176 let Some(mut state) = SupervisorState::from_meta(&block.meta) else { continue };
177 if !pacing::drop_restarted_wait(&mut state) {
178 continue;
179 }
180 let Ok(value) = serde_json::to_value(&state) else { continue };
181 let id = block.oid.clone();
182 let written = self.mstore.with_tx(|tx| {
183 let mut b = tx.must_get::<Block>(&id)?;
184 b.meta.insert(META_STATE.to_string(), value);
185 tx.update(&mut b)?;
186 Ok(())
187 });
188 match written {
189 Ok(()) => broadcast_block_update(&self.mstore, &self.event_bus, &id),
190 Err(e) => tracing::warn!(block_id = %id, error = %e, "supervisor: could not clear an interrupted wait"),
191 }
192 }
193 }
194
195 fn first_sighting(&self, end: &TurnEnded) -> bool {
196 let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
197 if seen.len() > SEEN_MAX {
198 seen.clear();
199 }
200 seen.insert((end.block_id.clone(), end.turn_id, end.ended_at_ms))
201 }
202
203 fn next_generation(&self, block_id: &str) -> u64 {
204 let mut g = self.generations.lock().unwrap_or_else(|e| e.into_inner());
205 let n = g.entry(block_id.to_string()).or_insert(0);
206 *n += 1;
207 *n
208 }
209
210 fn is_current(&self, block_id: &str, generation: u64) -> bool {
211 self.generations.lock().unwrap_or_else(|e| e.into_inner()).get(block_id) == Some(&generation)
212 }
213
214 fn lock_for(&self, block_id: &str) -> Arc<tokio::sync::Mutex<()>> {
215 let mut locks = self.locks.lock().unwrap_or_else(|e| e.into_inner());
216 locks.entry(block_id.to_string()).or_default().clone()
217 }
218
219 fn block(&self, block_id: &str) -> Option<Block> {
220 self.mstore.get::<Block>(block_id).ok().flatten()
221 }
222
223 fn state_for(&self, block_id: &str, block: &Block, mode: SupervisorMode, now_ms: u64) -> SupervisorState {
224 let runs = self.runs.lock().unwrap_or_else(|e| e.into_inner());
225 runs.get(block_id)
226 .cloned()
227 .or_else(|| SupervisorState::from_meta(&block.meta))
228 .unwrap_or_else(|| SupervisorState::new(mode, now_ms))
229 }
230
231 fn save(&self, block_id: &str, generation: u64, state: &SupervisorState) {
235 if !self.is_current(block_id, generation) {
236 return;
237 }
238 self.runs.lock().unwrap_or_else(|e| e.into_inner()).insert(block_id.to_string(), state.clone());
239 let Ok(value) = serde_json::to_value(state) else { return };
240 let written = self.mstore.with_tx(|tx| {
241 let mut block = tx.must_get::<Block>(block_id)?;
242 block.meta.insert(META_STATE.to_string(), value);
243 tx.update(&mut block)?;
244 Ok(())
245 });
246 match written {
247 Ok(()) => broadcast_block_update(&self.mstore, &self.event_bus, block_id),
248 Err(e) => tracing::warn!(block_id = %block_id, error = %e, "supervisor: could not store its state"),
249 }
250 }
251
252 fn notify_group(&self, block_id: &str, group: NoticeGroup, text: String) {
255 if settings::SupervisorSettings::current().notifies(group) {
256 self.notify(block_id, NotifyKind::InputWaiting, Some(text));
257 }
258 }
259
260 fn notify(&self, block_id: &str, kind: NotifyKind, text: Option<String>) {
261 let Some(router) = crate::backend::notify::router::get(&self.broker) else { return };
262 let block_id = block_id.to_string();
263 tokio::task::spawn_blocking(move || router.emit(kind, &block_id, text.as_deref(), 0));
265 }
266
267 fn notify_finished(&self, block_id: &str, trigger: Option<TriggerKind>) {
272 if !settings::SupervisorSettings::current().notifies(NoticeGroup::Done) {
273 return;
274 }
275 if is_external_start(trigger)
276 && !crate::backend::notify::router::get(&self.broker).is_some_and(|r| r.external_turns_notified())
277 {
278 return;
279 }
280 self.notify(block_id, NotifyKind::TurnCompleted, None);
281 }
282
283 pub async fn evaluate(self: &Arc<Self>, block_id: &str, trigger: Option<TriggerKind>, steps: u32, notify: bool) {
286 let mut generation = self.next_generation(block_id);
287 let lock = self.lock_for(block_id);
288 let _held = lock.lock().await;
289 if !self.is_current(block_id, generation) {
290 return;
291 }
292 let Some(block) = self.block(block_id) else { return };
293 let mode = SupervisorMode::from_meta(&block.meta);
294 if !settings::enabled() || mode == SupervisorMode::Off || !supports(&block.meta) {
295 return;
296 }
297 let now_ms = agentmux_common::time::now_ms_u64();
298 if super::stopped_by_user(block_id) {
301 self.stand_down_for_stop(block_id, generation, &block, mode, now_ms);
302 return;
303 }
304 let Some(activity) = digest::read_recent_activity(&self.filestore, &self.mstore, block_id) else {
307 if notify && trigger != Some(TriggerKind::System) {
308 self.notify_finished(block_id, trigger);
309 }
310 return;
311 };
312 let facts = TurnFacts {
313 trigger,
314 steps,
315 ending: activity.ending,
316 background_running: self.background_running(block_id),
317 reply: fingerprint(&activity.text),
318 now_ms,
319 unavailable: crate::backend::agent_state::unavailable_of_block(&self.mstore, None, block_id, now_ms).map(|u| u.reason()),
320 };
321 let mut state = self.state_for(block_id, &block, mode, now_ms);
322 match policy::on_turn_end(&mut state, mode, &facts) {
323 PreJudge::Ignore => {
324 self.save(block_id, generation, &state);
325 if notify && trigger != Some(TriggerKind::System) {
328 self.notify_finished(block_id, trigger);
329 }
330 return;
331 }
332 PreJudge::Wait => {
333 policy::apply_wait(&mut state, &facts);
334 self.save(block_id, generation, &state);
335 return;
336 }
337 PreJudge::Pause(why) => {
338 policy::apply_pause(&mut state, &why, &facts);
339 self.save(block_id, generation, &state);
340 if notify {
341 let group = if facts.unavailable.is_some() { NoticeGroup::Failed } else { NoticeGroup::NeedsYou };
343 self.notify_group(block_id, group, format!("Supervisor paused: {why}"));
344 }
345 return;
346 }
347 PreJudge::Judge => {}
348 }
349
350 state.status = SupervisorStatus::Judging;
351 state.reason.clear();
352 self.save(block_id, generation, &state);
353
354 let mut outcome = judge::judge(&self.mstore, block_id, generation, mode, &activity.text, state.continuations).await;
355 if matches!(outcome, judge::Outcome::Failed)
358 && settings::enabled()
359 && self.is_current(block_id, generation)
360 && !turn_active(block_id)
361 {
362 let retry = self.next_generation(block_id);
363 outcome = judge::judge(&self.mstore, block_id, retry, mode, &activity.text, state.continuations).await;
364 generation = retry;
365 }
366 let judged: Option<Judgement> = match outcome {
367 judge::Outcome::Superseded => return,
368 judge::Outcome::Failed | judge::Outcome::NoVerdict => None,
369 judge::Outcome::Judged(j) => Some(j),
370 };
371 if !self.is_current(block_id, generation) {
374 return;
375 }
376 if self.block(block_id).map(|b| SupervisorMode::from_meta(&b.meta)) != Some(mode) {
377 return;
378 }
379 if !settings::enabled() {
382 state.status = SupervisorStatus::Watching;
383 self.save(block_id, generation, &state);
384 if notify && trigger != Some(TriggerKind::System) {
385 self.notify_finished(block_id, trigger);
386 }
387 return;
388 }
389 if turn_active(block_id) {
390 state.status = SupervisorStatus::Watching;
391 self.save(block_id, generation, &state);
392 return;
393 }
394
395 if super::stopped_by_user(block_id) {
397 self.stand_down_for_stop(block_id, generation, &block, mode, now_ms);
398 return;
399 }
400
401 let verdict = judged.as_ref().map(|j| (j.verdict, j.reason.as_str()));
402 let action = policy::decide(&state, mode, verdict, &facts);
403 let judged_verdict = judged.as_ref().map(|j| j.verdict);
404 let next = judged.as_ref().map(|j| j.next.clone()).unwrap_or_default();
405 let wait = settings::SupervisorSettings::current().cooldown_secs;
409 if let (Action::Continue { reason, .. }, true) = (&action, wait > 0) {
410 state.status = SupervisorStatus::Waiting;
411 state.reason = format!("{}{wait} s wait: {reason}", pacing::WAIT_PREFIX);
412 self.save(block_id, generation, &state);
413 let sup = self.clone();
414 let block_id = block_id.to_string();
415 tokio::spawn(async move {
416 tokio::time::sleep(std::time::Duration::from_secs(u64::from(wait))).await;
417 sup.continue_after_wait(&block_id, generation, mode, action, judged_verdict, next, facts, notify, trigger)
418 .await;
419 });
420 return;
421 }
422 self.conclude(block_id, generation, &mut state, action, judged_verdict, &next, &facts, mode, notify, trigger);
423 }
424
425 #[allow(clippy::too_many_arguments)]
427 async fn continue_after_wait(
428 &self,
429 block_id: &str,
430 generation: u64,
431 mode: SupervisorMode,
432 action: Action,
433 verdict: Option<Verdict>,
434 next: String,
435 mut facts: TurnFacts,
436 notify: bool,
437 trigger: Option<TriggerKind>,
438 ) {
439 let lock = self.lock_for(block_id);
440 let _held = lock.lock().await;
441 let block = self.block(block_id);
442 let over = WaitOver {
443 superseded: !self.is_current(block_id, generation),
444 switched_off: !settings::enabled(),
445 mode_changed: block.as_ref().map(|b| SupervisorMode::from_meta(&b.meta)) != Some(mode),
446 turn_running: turn_active(block_id),
447 stopped: super::stopped_by_user(block_id) || super::stopped_since(block_id, facts.now_ms),
449 };
450 let now_ms = agentmux_common::time::now_ms_u64();
451 if let Some(why) = over.drop_reason() {
452 if over.superseded || over.mode_changed {
455 return;
456 }
457 let Some(block) = block else { return };
458 if over.stopped {
459 self.stand_down_for_stop(block_id, generation, &block, mode, now_ms);
460 return;
461 }
462 let mut state = self.state_for(block_id, &block, mode, now_ms);
463 state.status = SupervisorStatus::Watching;
464 state.reason = format!("Not continued: {why}.");
465 self.save(block_id, generation, &state);
466 return;
467 }
468 let Some(block) = block else { return };
469 facts.now_ms = now_ms;
470 let mut state = self.state_for(block_id, &block, mode, now_ms);
471 let action = match action {
473 Action::Continue { .. } => match policy::limit_reached(&state, mode, &facts) {
474 Some(why) => Action::Pause(why),
475 None => action,
476 },
477 other => other,
478 };
479 self.conclude(block_id, generation, &mut state, action, verdict, &next, &facts, mode, notify, trigger);
480 }
481
482 #[allow(clippy::too_many_arguments)]
485 fn conclude(
486 &self,
487 block_id: &str,
488 generation: u64,
489 state: &mut SupervisorState,
490 mut action: Action,
491 verdict: Option<Verdict>,
492 next: &str,
493 facts: &TurnFacts,
494 mode: SupervisorMode,
495 notify: bool,
496 trigger: Option<TriggerKind>,
497 ) {
498 let mut undeliverable = false;
499 let mut repeat_budget_notice = false;
500 if let Action::Continue { n, reason } = &action {
501 let hourly = settings::SupervisorSettings::current().hourly;
502 let spent = self.budget.lock().unwrap_or_else(|e| e.into_inner()).spend(facts.now_ms, hourly);
503 match spent {
504 Err(wait_ms) => {
505 repeat_budget_notice = self.budget_noticed.swap(true, std::sync::atomic::Ordering::Relaxed);
506 let sent = self.budget.lock().unwrap_or_else(|e| e.into_inner()).sent_in_hour(facts.now_ms);
507 action = Action::Pause(pacing::budget_reached(sent, hourly, wait_ms));
508 }
509 Ok(ticket) => {
510 self.budget_noticed.store(false, std::sync::atomic::Ordering::Relaxed);
511 let text = message::continuation(mode, *n, mode.limits().continuations, reason, next);
512 if let Err(e) = deliver(block_id, &text) {
513 self.budget.lock().unwrap_or_else(|e| e.into_inner()).refund(ticket);
514 undeliverable = true;
515 action = Action::Pause(format!("Couldn't continue it: {e}"));
516 }
517 }
518 }
519 }
520 policy::apply(state, &action, verdict, facts);
521 self.save(block_id, generation, state);
522 if !notify {
523 return;
524 }
525 match &action {
526 Action::Continue { .. } => {}
527 Action::Pause(why) => {
528 if !repeat_budget_notice {
529 let group = pacing::pause_group(&action, verdict, undeliverable);
530 self.notify_group(block_id, group, format!("Supervisor paused: {why}"));
531 }
532 }
533 Action::Done(_) | Action::NoVerdict => self.notify_finished(block_id, trigger),
534 }
535 }
536
537 fn stand_down_for_stop(&self, block_id: &str, generation: u64, block: &Block, mode: SupervisorMode, now_ms: u64) {
540 let mut state = self.state_for(block_id, block, mode, now_ms);
541 state.status = SupervisorStatus::Watching;
542 state.reason = STOPPED_BY_USER.to_string();
543 state.record(SupervisorDecision {
544 at_ms: now_ms,
545 action: SupervisorAction::Stopped,
546 verdict: None,
547 reason: STOPPED_BY_USER.to_string(),
548 });
549 self.save(block_id, generation, &state);
550 }
551
552 fn background_running(&self, block_id: &str) -> bool {
553 self.mstore
554 .background_task_list_for_block(block_id)
555 .map(|tasks| tasks.iter().any(|t| t.status == BackgroundTaskStatus::Running))
556 .unwrap_or(false)
557 }
558
559 pub async fn set_mode(self: &Arc<Self>, block_id: &str, mode: SupervisorMode) -> Result<(), String> {
562 let block = self.block(block_id).ok_or_else(|| "no such pane".to_string())?;
563 if mode != SupervisorMode::Off && !settings::enabled() {
564 return Err(settings::SWITCHED_OFF.to_string());
565 }
566 if mode != SupervisorMode::Off && !supports(&block.meta) {
567 return Err("the Supervisor works with Claude agents only for now".to_string());
568 }
569 let now_ms = agentmux_common::time::now_ms_u64();
570 self.next_generation(block_id);
573
574 let history = self.state_for(block_id, &block, mode, now_ms).history;
575 let mut state = SupervisorState { history, ..SupervisorState::new(mode, now_ms) };
576 let label = match mode {
577 SupervisorMode::Off => "Turned off.",
578 SupervisorMode::Steady => "Set to Steady.",
579 SupervisorMode::Drive => "Set to Drive.",
580 };
581 state.record(SupervisorDecision {
582 at_ms: now_ms,
583 action: SupervisorAction::ModeSet,
584 verdict: None,
585 reason: label.to_string(),
586 });
587 let value = serde_json::to_value(&state).map_err(|e| e.to_string())?;
588 self.mstore
589 .with_tx(|tx| {
590 let mut block = tx.must_get::<Block>(block_id)?;
591 if mode == SupervisorMode::Off {
592 block.meta.remove(META_MODE);
593 } else {
594 block.meta.insert(META_MODE.to_string(), serde_json::Value::String(mode.as_str().to_string()));
595 }
596 block.meta.insert(META_STATE.to_string(), value);
597 tx.update(&mut block)?;
598 Ok(())
599 })
600 .map_err(|e| e.to_string())?;
601 self.runs.lock().unwrap_or_else(|e| e.into_inner()).insert(block_id.to_string(), state);
602 broadcast_block_update(&self.mstore, &self.event_bus, block_id);
603
604 if mode != SupervisorMode::Off && !turn_active(block_id) {
605 let sup = self.clone();
606 let block_id = block_id.to_string();
607 tokio::spawn(async move { sup.evaluate(&block_id, None, 0, false).await });
608 }
609 Ok(())
610 }
611}
612
613const STOPPED_BY_USER: &str = "You stopped it; it waits for your next message.";
614
615fn is_external_start(trigger: Option<TriggerKind>) -> bool {
620 matches!(trigger, Some(TriggerKind::Agent | TriggerKind::Service | TriggerKind::Schedule | TriggerKind::Task))
621}
622
623fn turn_active(block_id: &str) -> bool {
624 crate::backend::blockcontroller::get_block_controller_status(block_id).is_some_and(|s| s.turn_active)
625}
626
627fn deliver(block_id: &str, text: &str) -> Result<(), String> {
630 use crate::backend::reactive::SenderDelivery;
631 use crate::backend::agent_route::AgentRoute;
632 let input = TurnInput { from: crate::backend::message_origin::MessageOrigin::supervisor(), text: text.to_string(), joins_turn: None };
633 match crate::backend::agent_route::route_agent_message_from(block_id, text, Some(input), crate::backend::message_origin::MessageOrigin::supervisor(), &[], None) {
634 Ok(AgentRoute::Sent(SenderDelivery::Delivered | SenderDelivery::Deferred)) => Ok(()),
635 Ok(AgentRoute::Sent(SenderDelivery::Pty)) => Err("the pane is not an agent session".to_string()),
636 Ok(AgentRoute::StartTurn { .. }) => Err("the agent isn't running".to_string()),
637 Err(e) => Err(e),
638 }
639}
640
641pub(super) fn fingerprint(digest_text: &str) -> String {
643 let Some(at) = digest_text.rfind("[assistant] ") else { return String::new() };
644 let mut h = std::collections::hash_map::DefaultHasher::new();
645 digest_text[at..].trim().hash(&mut h);
646 format!("{:016x}", h.finish())
647}
648
649#[cfg(test)]
650pub(super) fn parse_turn_ended_for_test(data: &serde_json::Value) -> Option<(String, Option<TriggerKind>, u32)> {
651 parse_turn_ended(data).map(|t| (t.block_id, t.trigger, t.steps))
652}
653
654#[cfg(test)]
655pub(super) fn is_external_start_for_test(trigger: Option<TriggerKind>) -> bool {
656 is_external_start(trigger)
657}
658
659#[cfg(test)]
660pub(super) fn for_test(mstore: Arc<Store>) -> Arc<Supervisor> {
661 Arc::new(Supervisor {
662 mstore,
663 filestore: Arc::new(FileStore::open_in_memory().unwrap()),
664 event_bus: Arc::new(EventBus::new()),
665 broker: Arc::new(Broker::new()),
666 runs: Mutex::default(),
667 generations: Mutex::default(),
668 locks: Mutex::default(),
669 seen: Mutex::default(),
670 budget: Mutex::default(),
671 budget_noticed: Default::default(),
672 })
673}