Skip to main content

agentmux_srv_core/backend/supervisor/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Swarm Supervisor: when a supervised agent ends a turn, a cheap judge
5//! model reads its recent conversation and either sends it a continuation or
6//! stops and tells the user why.
7//!
8//! - `policy`: the rules, pure: when a turn is judged, the limits, and what a
9//!   verdict leads to.
10//! - `judge`: the prompt and the one reader of its reply.
11//! - `message`: the continuation the agent receives.
12//! - `watcher`: listens for completed turns and carries a decision out.
13//!
14//! docs/specs/SPEC_SWARM_SUPERVISOR_2026_10_16.md.
15
16pub mod judge;
17pub mod message;
18pub mod pacing;
19pub mod policy;
20pub mod settings;
21pub mod watcher;
22
23#[cfg(test)]
24mod tests;
25
26use serde::{Deserialize, Serialize};
27
28use crate::backend::obj::{self, MetaMapType};
29
30/// Block meta: the pane's mode, `"steady"` or `"drive"`; absent is Off.
31pub const META_MODE: &str = "supervisor:mode";
32/// Block meta: the run state and recent decisions (`SupervisorState`), written
33/// by srv only, read by Swarm.
34pub const META_STATE: &str = "supervisor:state";
35
36/// How far the Supervisor keeps an agent going (spec §2).
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
38#[ts(export, export_to = "../../../frontend/types/rpc/")]
39#[serde(rename_all = "snake_case")]
40pub enum SupervisorMode {
41    #[default]
42    Off,
43    /// Continue an agent that stopped only to check in; stop on real questions.
44    Steady,
45    /// Also continue through open questions the agent can research and decide.
46    Drive,
47}
48
49impl SupervisorMode {
50    pub fn as_str(self) -> &'static str {
51        match self {
52            SupervisorMode::Off => "off",
53            SupervisorMode::Steady => "steady",
54            SupervisorMode::Drive => "drive",
55        }
56    }
57
58    /// The mode a wire or meta value names; anything else is Off.
59    pub fn parse(s: &str) -> Self {
60        match s.trim().to_ascii_lowercase().as_str() {
61            "steady" => SupervisorMode::Steady,
62            "drive" => SupervisorMode::Drive,
63            _ => SupervisorMode::Off,
64        }
65    }
66
67    pub fn from_meta(meta: &MetaMapType) -> Self {
68        Self::parse(&obj::meta_get_string(meta, META_MODE, ""))
69    }
70
71    /// This mode's limits under the settings as they are now.
72    pub fn limits(self) -> Limits {
73        settings::SupervisorSettings::current().limits(self)
74    }
75}
76
77/// When a run stops for the user (spec §3.4).
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub struct Limits {
80    /// Continuations in a row since the user last spoke.
81    pub continuations: u32,
82    /// Time since the run's first continuation.
83    pub run_ms: Option<u64>,
84    /// Continued turns in a row with no tool use.
85    pub no_progress: u32,
86}
87
88/// What the judge said about a turn.
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
90#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "SupervisorVerdict")]
91#[serde(rename_all = "snake_case")]
92pub enum Verdict {
93    Continue,
94    Done,
95    NeedsUser,
96    Blocked,
97}
98
99impl Verdict {
100    pub fn parse(s: &str) -> Option<Self> {
101        match s.trim().to_ascii_lowercase().replace([' ', '-'], "_").as_str() {
102            "continue" => Some(Verdict::Continue),
103            "done" => Some(Verdict::Done),
104            "needs_user" | "needs_you" => Some(Verdict::NeedsUser),
105            "blocked" => Some(Verdict::Blocked),
106            _ => None,
107        }
108    }
109}
110
111/// Where a supervised pane stands, as Swarm shows it.
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
113#[ts(export, export_to = "../../../frontend/types/rpc/")]
114#[serde(rename_all = "snake_case")]
115pub enum SupervisorStatus {
116    /// Supervising; nothing to say yet.
117    #[default]
118    Watching,
119    /// Asking the judge about the turn that just ended.
120    Judging,
121    /// Background work is running; the turn it wakes is judged instead.
122    Waiting,
123    /// Sent a continuation.
124    Continued,
125    /// Stopped: the user is needed (`reason` says why).
126    Paused,
127    /// The judge found the work done.
128    Done,
129}
130
131/// What the Supervisor did after a turn, for the history.
132#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
133#[ts(export, export_to = "../../../frontend/types/rpc/")]
134#[serde(rename_all = "snake_case")]
135pub enum SupervisorAction {
136    Continued,
137    Paused,
138    Done,
139    Waited,
140    /// No verdict (the judge failed, timed out or answered out of format):
141    /// nothing was sent, and the user got the ordinary "finished" notice.
142    NoVerdict,
143    /// The mode was set (a new run).
144    ModeSet,
145    /// The user's Stop ended the turn: nothing was judged or sent.
146    Stopped,
147}
148
149/// One decision, newest last in `SupervisorState::history`.
150#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
151#[ts(export, export_to = "../../../frontend/types/rpc/")]
152pub struct SupervisorDecision {
153    #[ts(type = "number")]
154    pub at_ms: u64,
155    pub action: SupervisorAction,
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    #[ts(optional)]
158    pub verdict: Option<Verdict>,
159    #[serde(default, skip_serializing_if = "String::is_empty")]
160    #[ts(optional, as = "Option<String>")]
161    pub reason: String,
162}
163
164/// How many decisions the history keeps.
165pub const HISTORY_MAX: usize = 10;
166
167/// A supervised pane's run state, mirrored to block meta `supervisor:state`
168/// after every decision (spec §3.6).
169#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
170#[ts(export, export_to = "../../../frontend/types/rpc/")]
171pub struct SupervisorState {
172    pub mode: SupervisorMode,
173    pub status: SupervisorStatus,
174    /// Why it stopped, or what it last decided, in a sentence.
175    #[serde(default, skip_serializing_if = "String::is_empty")]
176    #[ts(optional, as = "Option<String>")]
177    pub reason: String,
178    /// Continuations in a row since the user last spoke.
179    #[serde(default)]
180    pub continuations: u32,
181    /// The mode's continuation limit, for "3 of 15".
182    #[serde(default)]
183    pub limit: u32,
184    /// When this run's first continuation was sent; 0 before one.
185    #[serde(default)]
186    #[ts(type = "number")]
187    pub run_started_at_ms: u64,
188    /// Continued turns in a row with no tool use.
189    #[serde(default)]
190    pub no_progress: u32,
191    /// A fingerprint of the agent's last final message, to see it repeat.
192    #[serde(default, skip_serializing_if = "String::is_empty")]
193    #[ts(optional, as = "Option<String>")]
194    pub last_reply: String,
195    #[serde(default)]
196    #[ts(type = "number")]
197    pub updated_at_ms: u64,
198    #[serde(default)]
199    pub history: Vec<SupervisorDecision>,
200}
201
202impl SupervisorState {
203    /// A fresh run in `mode`.
204    pub fn new(mode: SupervisorMode, now_ms: u64) -> Self {
205        SupervisorState { mode, limit: mode.limits().continuations, updated_at_ms: now_ms, ..Default::default() }
206    }
207
208    /// The state stored in `meta`, if any and readable.
209    pub fn from_meta(meta: &MetaMapType) -> Option<Self> {
210        serde_json::from_value(meta.get(META_STATE)?.clone()).ok()
211    }
212
213    /// Start a new run: the user spoke, or the mode changed. History is kept.
214    pub fn reset_run(&mut self) {
215        self.continuations = 0;
216        self.run_started_at_ms = 0;
217        self.no_progress = 0;
218        self.last_reply.clear();
219    }
220
221    pub fn record(&mut self, decision: SupervisorDecision) {
222        self.updated_at_ms = decision.at_ms;
223        self.history.push(decision);
224        if self.history.len() > HISTORY_MAX {
225            let excess = self.history.len() - HISTORY_MAX;
226            self.history.drain(..excess);
227        }
228    }
229}
230
231/// Whether the user stopped this pane's turn within the grace window
232/// (`backend::user_stop`). The turn end it causes is never judged or
233/// continued: the user's override wins (spec §3.4).
234pub fn stopped_by_user(block_id: &str) -> bool {
235    crate::backend::user_stop::stopped_recently(block_id)
236}
237
238/// Whether the user stopped the pane at or after `since_ms`: what a continuation
239/// that waited checks, since the grace window is shorter than the wait.
240pub fn stopped_since(block_id: &str, since_ms: u64) -> bool {
241    crate::backend::user_stop::stopped_since(block_id, since_ms as i64)
242}
243
244/// Whether the Supervisor can work on this pane at all: a Claude agent, whose
245/// conversation srv can read and whose CLI runs the judge (spec §2.1).
246pub fn supports(meta: &MetaMapType) -> bool {
247    obj::meta_get_string(meta, "agentProvider", "") == "claude"
248        && crate::ambient::digest::reads_output_format(&obj::meta_get_string(meta, "agentOutputFormat", ""))
249}
250
251/// Whether a pane is supervised now: a mode is set and the pane supports it.
252/// The notification router skips its generic "finished" notice for these, as
253/// the Supervisor sends its own (spec §3.7). Never while the master switch is
254/// off: a stored mode is not read then.
255pub fn is_supervised(meta: &MetaMapType) -> bool {
256    settings::enabled() && SupervisorMode::from_meta(meta) != SupervisorMode::Off && supports(meta)
257}