agentmux_srv_core/backend/supervisor/
policy.rs1use crate::ambient::digest::TurnEnding;
8use crate::backend::blockcontroller::health::TriggerKind;
9
10use super::{Limits, SupervisorDecision, SupervisorMode, SupervisorState, SupervisorStatus, Verdict};
11
12#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct TurnFacts {
15 pub trigger: Option<TriggerKind>,
18 pub steps: u32,
20 pub ending: TurnEnding,
22 pub background_running: bool,
24 pub reply: String,
26 pub now_ms: u64,
27 pub unavailable: Option<String>,
30}
31
32#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum PreJudge {
35 Ignore,
37 Pause(String),
39 Wait,
41 Judge,
42}
43
44pub fn on_turn_end(state: &mut SupervisorState, mode: SupervisorMode, facts: &TurnFacts) -> PreJudge {
48 if mode == SupervisorMode::Off || facts.trigger == Some(TriggerKind::System) {
49 return PreJudge::Ignore;
50 }
51 if state.mode != mode {
52 *state = SupervisorState { history: std::mem::take(&mut state.history), ..SupervisorState::new(mode, facts.now_ms) };
53 }
54 if let Some(why) = &facts.unavailable {
57 return PreJudge::Pause(format!("{why}."));
58 }
59 match facts.trigger {
60 Some(TriggerKind::User | TriggerKind::Broadcast) => state.reset_run(),
61 Some(TriggerKind::Supervisor) => {
62 if facts.steps <= 1 {
63 state.no_progress += 1;
64 } else {
65 state.no_progress = 0;
66 }
67 }
68 _ => {}
69 }
70 match facts.ending {
71 TurnEnding::AskedUser => PreJudge::Pause("It asked you a question.".to_string()),
72 TurnEnding::UserLast => PreJudge::Ignore,
74 _ if facts.background_running => PreJudge::Wait,
75 _ => PreJudge::Judge,
76 }
77}
78
79#[derive(Clone, Debug, PartialEq, Eq)]
81pub enum Action {
82 Continue { n: u32, reason: String },
84 Pause(String),
86 Done(String),
87 NoVerdict,
89}
90
91pub fn decide(state: &SupervisorState, mode: SupervisorMode, verdict: Option<(Verdict, &str)>, facts: &TurnFacts) -> Action {
93 let Some((verdict, reason)) = verdict else {
94 return Action::NoVerdict;
95 };
96 match verdict {
97 Verdict::Done => Action::Done(reason.to_string()),
98 Verdict::NeedsUser => Action::Pause(reason.to_string()),
99 Verdict::Blocked => Action::Pause(format!("Blocked: {reason}")),
100 Verdict::Continue => match limit_reached(state, mode, facts) {
101 Some(why) => Action::Pause(why),
102 None => Action::Continue { n: state.continuations + 1, reason: reason.to_string() },
103 },
104 }
105}
106
107pub fn limit_reached(state: &SupervisorState, mode: SupervisorMode, facts: &TurnFacts) -> Option<String> {
109 limit_reached_in(&mode.limits(), state, facts)
110}
111
112pub fn limit_reached_in(limits: &Limits, state: &SupervisorState, facts: &TurnFacts) -> Option<String> {
114 if state.continuations >= limits.continuations {
115 return Some(format!("{} continuations in a row; over to you.", state.continuations));
116 }
117 if let Some(run_ms) = limits.run_ms {
118 if state.run_started_at_ms > 0 && facts.now_ms.saturating_sub(state.run_started_at_ms) >= run_ms {
119 return Some(format!("Kept going for {}; over to you.", duration_text(run_ms)));
120 }
121 }
122 if state.no_progress >= limits.no_progress {
123 return Some(format!("No progress: {} continued turns without using a tool.", state.no_progress));
124 }
125 let continued = facts.trigger == Some(TriggerKind::Supervisor);
126 if continued && !facts.reply.is_empty() && facts.reply == state.last_reply {
127 return Some("It gave the same reply twice.".to_string());
128 }
129 None
130}
131
132fn duration_text(ms: u64) -> String {
134 let minutes = ms / 60_000;
135 let plural = |n: u64, unit: &str| format!("{n} {unit}{}", if n == 1 { "" } else { "s" });
136 if minutes >= 60 && minutes % 60 == 0 {
137 plural(minutes / 60, "hour")
138 } else {
139 plural(minutes, "minute")
140 }
141}
142
143pub fn apply(state: &mut SupervisorState, action: &Action, verdict: Option<Verdict>, facts: &TurnFacts) {
145 use super::SupervisorAction as A;
146 let (status, history_action, reason) = match action {
147 Action::Continue { n, reason } => {
148 state.continuations = *n;
149 if state.run_started_at_ms == 0 {
150 state.run_started_at_ms = facts.now_ms;
151 }
152 (SupervisorStatus::Continued, A::Continued, reason.clone())
153 }
154 Action::Pause(why) => (SupervisorStatus::Paused, A::Paused, why.clone()),
155 Action::Done(why) => (SupervisorStatus::Done, A::Done, why.clone()),
156 Action::NoVerdict => (
157 SupervisorStatus::Watching,
158 A::NoVerdict,
159 "Couldn't judge this turn, so it stopped as usual.".to_string(),
160 ),
161 };
162 state.last_reply = facts.reply.clone();
163 state.status = status;
164 state.reason = reason.clone();
165 state.limit = state.mode.limits().continuations;
166 state.record(SupervisorDecision { at_ms: facts.now_ms, action: history_action, verdict, reason });
167}
168
169pub fn apply_pause(state: &mut SupervisorState, why: &str, facts: &TurnFacts) {
171 apply(state, &Action::Pause(why.to_string()), None, facts);
172}
173
174pub fn apply_wait(state: &mut SupervisorState, facts: &TurnFacts) {
176 let reason = "Waiting for its background work to finish.".to_string();
177 state.status = SupervisorStatus::Waiting;
178 state.reason = reason.clone();
179 state.last_reply = facts.reply.clone();
180 state.record(SupervisorDecision { at_ms: facts.now_ms, action: super::SupervisorAction::Waited, verdict: None, reason });
181}