base/interface/turn_policy.rs
1//! `TurnPolicy` — when a turn has gone on long enough.
2//!
3//! A turn is a loop: call the model, run what it asked for, call it again. Two
4//! judgements decide when that loop ends, and both were constants compiled
5//! into the middle of a twelve-hundred-line function — a ceiling on model
6//! calls, and a ceiling on structured-output retries. Neither is a fact about
7//! how an agent works; both are opinions about how long is too long, and
8//! different deployments hold different ones.
9//!
10//! # What is a judgement here, and what is not
11//!
12//! Only judgements about *progress* belong behind this contract. Three other
13//! things end a turn and none of them is one:
14//!
15//! * **Cancellation** — the session was stopped. That is an instruction, and
16//! interruption is kernel-only for a reason: a policy that could decline to
17//! stop is a policy that could refuse to be stopped.
18//! * **A hook said stop** — `PostToolUse` discontinuing, or a `Stop` hook.
19//! Those are already an extension point's output. Letting a policy overrule
20//! one would invert the trust order: the operator configured the hook, and
21//! the policy might have arrived with a plugin.
22//! * **The model asked for tools, so there is more to do.** That is the loop's
23//! definition rather than an opinion about it — the skeleton, which stays
24//! closed.
25//!
26//! # Asked where the judgements already happen
27//!
28//! Two methods rather than one, because the two ceilings are checked at
29//! different points today and consolidating them would reorder the loop. The
30//! call ceiling is checked before spending a call; the retry ceiling after one
31//! comes back. Moving either would be a behavior change wearing a refactor's
32//! clothes.
33
34use std::sync::Arc;
35
36/// How far into a turn we are.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct TurnProgress<'a> {
39 /// Model calls made in this turn so far.
40 pub api_calls: u32,
41 /// Tool calls dispatched in this turn so far.
42 pub tool_calls: u32,
43 /// How many structured-output retries the model has spent.
44 pub structured_output_calls: u32,
45 /// The stop reason the model itself gave for the last call. Empty before
46 /// the first call.
47 pub stop_reason: &'a str,
48}
49
50/// What to do next.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum TurnStep {
53 /// Keep going.
54 Continue,
55 /// End the turn, reporting `reason`.
56 ///
57 /// The reason reaches the host as `TurnComplete.stop_reason` and is part
58 /// of the observable contract — a policy inventing a new one is telling
59 /// every consumer something they have no case for, so prefer the existing
60 /// vocabulary (`max_turns`, `max_structured_output_retries`) unless the
61 /// situation genuinely is new.
62 Stop { reason: String },
63}
64
65impl TurnStep {
66 pub fn stop(reason: impl Into<String>) -> Self {
67 Self::Stop {
68 reason: reason.into(),
69 }
70 }
71
72 pub fn is_stop(&self) -> bool {
73 matches!(self, Self::Stop { .. })
74 }
75}
76
77/// When a turn has gone on long enough.
78pub trait TurnPolicy: Send + Sync {
79 /// Before spending another model call.
80 fn before_model_call(&self, _progress: &TurnProgress<'_>) -> TurnStep {
81 TurnStep::Continue
82 }
83
84 /// After a model call came back, before acting on what it asked for.
85 ///
86 /// Asked first, whatever the stop reason: a `Stop` here ends a reply cut
87 /// off at `max_tokens` before [`RecoveryPolicy::on_early_stop`] or
88 /// [`BudgetPolicy::on_output_target`] see it.
89 ///
90 /// [`RecoveryPolicy::on_early_stop`]: crate::interface::recovery_policy::RecoveryPolicy::on_early_stop
91 /// [`BudgetPolicy::on_output_target`]: crate::interface::budget_policy::BudgetPolicy::on_output_target
92 fn after_model_call(&self, _progress: &TurnProgress<'_>) -> TurnStep {
93 TurnStep::Continue
94 }
95}
96
97/// The engine's own ceilings.
98///
99/// `max_api_calls` in particular is the *lower* of what settings allow and
100/// what the scene allows, so a scene declaring a tighter ceiling is honoured.
101/// Constructing the policy is the one place that rule lives.
102pub struct LimitsPolicy {
103 pub max_api_calls: u32,
104 pub max_structured_output_retries: u32,
105}
106
107impl LimitsPolicy {
108 /// `max_api_calls` is the lower of the two ceilings.
109 pub fn new(settings_max_api_calls: u32, scene_max_api_calls: u32, max_retries: u32) -> Self {
110 Self {
111 max_api_calls: settings_max_api_calls.min(scene_max_api_calls),
112 max_structured_output_retries: max_retries,
113 }
114 }
115}
116
117impl TurnPolicy for LimitsPolicy {
118 fn before_model_call(&self, progress: &TurnProgress<'_>) -> TurnStep {
119 if progress.api_calls >= self.max_api_calls {
120 return TurnStep::stop("max_turns");
121 }
122 TurnStep::Continue
123 }
124
125 fn after_model_call(&self, progress: &TurnProgress<'_>) -> TurnStep {
126 if progress.structured_output_calls >= self.max_structured_output_retries {
127 return TurnStep::stop("max_structured_output_retries");
128 }
129 TurnStep::Continue
130 }
131}
132
133/// Every policy in turn; the first one that says stop wins.
134///
135/// The second implementation, and the shape a host actually wants: adding a
136/// ceiling of your own should not mean reimplementing the engine's. A stop is
137/// never overridden by a later policy — a policy that could veto another's
138/// stop would make "add a limit" mean "hope nobody added a looser one".
139pub struct FirstOf(pub Vec<Arc<dyn TurnPolicy>>);
140
141impl TurnPolicy for FirstOf {
142 fn before_model_call(&self, progress: &TurnProgress<'_>) -> TurnStep {
143 for p in &self.0 {
144 let step = p.before_model_call(progress);
145 if step.is_stop() {
146 return step;
147 }
148 }
149 TurnStep::Continue
150 }
151
152 fn after_model_call(&self, progress: &TurnProgress<'_>) -> TurnStep {
153 for p in &self.0 {
154 let step = p.after_model_call(progress);
155 if step.is_stop() {
156 return step;
157 }
158 }
159 TurnStep::Continue
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166
167 fn at(api_calls: u32, structured: u32) -> TurnProgress<'static> {
168 TurnProgress {
169 api_calls,
170 tool_calls: 0,
171 structured_output_calls: structured,
172 stop_reason: "",
173 }
174 }
175
176 fn limits() -> LimitsPolicy {
177 LimitsPolicy::new(25, u32::MAX, 5)
178 }
179
180 #[test]
181 fn the_call_ceiling_stops_at_it_not_after_it() {
182 assert_eq!(limits().before_model_call(&at(24, 0)), TurnStep::Continue);
183 assert_eq!(
184 limits().before_model_call(&at(25, 0)),
185 TurnStep::stop("max_turns"),
186 "the check is `>=`; an off-by-one here is 26 calls billed instead of 25"
187 );
188 }
189
190 #[test]
191 fn the_tighter_of_the_two_ceilings_wins() {
192 let scene_is_tighter = LimitsPolicy::new(25, 3, 5);
193 assert_eq!(scene_is_tighter.max_api_calls, 3);
194 let settings_are_tighter = LimitsPolicy::new(2, 10, 5);
195 assert_eq!(settings_are_tighter.max_api_calls, 2);
196 }
197
198 #[test]
199 fn the_retry_ceiling_is_checked_after_the_call_not_before() {
200 assert_eq!(
201 limits().before_model_call(&at(0, 99)),
202 TurnStep::Continue,
203 "a retry count must not end a turn before the call that would raise it"
204 );
205 assert_eq!(
206 limits().after_model_call(&at(0, 5)),
207 TurnStep::stop("max_structured_output_retries")
208 );
209 }
210
211 #[test]
212 fn a_host_ceiling_composes_with_the_engines_rather_than_replacing_it() {
213 struct StopAtThree;
214 impl TurnPolicy for StopAtThree {
215 fn before_model_call(&self, progress: &TurnProgress<'_>) -> TurnStep {
216 if progress.api_calls >= 3 {
217 return TurnStep::stop("host_ceiling");
218 }
219 TurnStep::Continue
220 }
221 }
222
223 let composed = FirstOf(vec![Arc::new(limits()), Arc::new(StopAtThree)]);
224 assert_eq!(composed.before_model_call(&at(2, 0)), TurnStep::Continue);
225 assert_eq!(
226 composed.before_model_call(&at(3, 0)),
227 TurnStep::stop("host_ceiling"),
228 "the tighter one wins even though the engine's would still allow it"
229 );
230 assert_eq!(
231 composed.after_model_call(&at(0, 5)),
232 TurnStep::stop("max_structured_output_retries"),
233 "and the engine's still applies where the host's says nothing"
234 );
235 }
236
237 /// A later policy cannot un-stop an earlier one. Otherwise "add a limit"
238 /// would mean "hope nobody registered a looser one after you".
239 #[test]
240 fn a_stop_is_never_overridden() {
241 struct NeverStops;
242 impl TurnPolicy for NeverStops {}
243
244 let composed = FirstOf(vec![Arc::new(limits()), Arc::new(NeverStops)]);
245 assert_eq!(
246 composed.before_model_call(&at(25, 0)),
247 TurnStep::stop("max_turns")
248 );
249 }
250}