1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
//! Turn-based state machine for agent control flow.
//!
//! Replaces flat loop `break`/`continue`/`return` with explicit
//! [`TurnState`] → [`TurnOutcome`] → [`TurnAction`] transitions
//! driven by a pure [`TurnTransition::resolve`] function.
//!
//! This makes the agent loop's control flow auditable, testable, and
//! extensible without touching the core executor.
use crate::provider::FinishReason;
use super::run::RunStatus;
use serde::{Deserialize, Serialize};
/// States in the agent turn cycle.
///
/// Each iteration of the agent loop moves through a subset of these states.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TurnState {
/// Validating iteration count and token budget before any work.
CheckingPolicy,
/// Running proactive compaction then building the chat context.
BuildingContext,
/// Calling the model provider (streaming or complete).
CallingModel,
/// Running reactive compaction after a context overflow.
Compacting,
/// Parsing the model response and deciding whether to call tools.
ProcessingResponse,
/// Executing tool calls returned by the model.
ExecutingTools,
/// Persisting tool results and preparing for the next turn.
Persisting,
}
/// Outcome of a turn — what the state produced.
///
/// Drives the transition to the next state.
#[derive(Debug, Clone)]
pub enum TurnOutcome {
/// State executed successfully.
Success,
/// Policy limit reached (iteration or token).
PolicyExceeded {
/// Human-readable reason.
reason: String,
},
/// Provider returned a context overflow error.
ContextOverflow,
/// Provider returned a non-retryable error.
ProviderError {
/// Error message.
message: String,
},
/// Context or storage error.
PipelineError {
/// Error message.
message: String,
},
/// Model response has no tool calls — agent is done.
NoToolCalls,
/// Model finish reason is not ToolCalls — agent is done.
NotToolCalls {
/// The finish reason that stopped the loop.
finish_reason: FinishReason,
},
/// Tool execution failed and policy does not allow continuation.
ToolFailure {
/// Error message.
message: String,
},
/// Model output was truncated (FinishReason::Length). Recovery may be attempted.
OutputTruncated,
}
/// Action the loop executor should take after a transition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TurnAction {
/// Proceed to the next state in the normal flow.
Continue {
/// Next state to enter.
next: TurnState,
},
/// Break the loop and complete the run successfully.
BreakLoop,
/// Run compaction then retry CallingModel.
CompactAndRetry,
/// Terminate the run with an error.
Fail {
/// Error message.
reason: String,
},
}
/// Pure resolver mapping `(TurnState, TurnOutcome)` → `TurnAction`.
///
/// This function encodes the complete control-flow logic. It is
/// stateless and can be tested exhaustively without the runtime.
pub struct TurnTransition;
impl TurnTransition {
/// Resolves the next action given the current state and outcome.
#[must_use]
pub fn resolve(state: TurnState, outcome: &TurnOutcome) -> TurnAction {
match (state, outcome) {
// ── CheckingPolicy ──────────────────────────────────────
(TurnState::CheckingPolicy, TurnOutcome::PolicyExceeded { reason }) => {
TurnAction::Fail {
reason: reason.clone(),
}
}
(TurnState::CheckingPolicy, TurnOutcome::Success) => TurnAction::Continue {
next: TurnState::BuildingContext,
},
// ── BuildingContext / Compacting ────────────────────────
(TurnState::BuildingContext | TurnState::Compacting, TurnOutcome::Success)
| (TurnState::ProcessingResponse, TurnOutcome::OutputTruncated) => {
TurnAction::Continue {
next: TurnState::CallingModel,
}
}
(
TurnState::BuildingContext | TurnState::Compacting,
TurnOutcome::PipelineError { .. },
) => TurnAction::Fail {
reason: "context build failed".to_string(),
},
// ── CallingModel ────────────────────────────────────────
(TurnState::CallingModel, TurnOutcome::Success) => TurnAction::Continue {
next: TurnState::ProcessingResponse,
},
(TurnState::CallingModel, TurnOutcome::ContextOverflow) => TurnAction::CompactAndRetry,
(TurnState::CallingModel, TurnOutcome::ProviderError { .. }) => TurnAction::Fail {
reason: "provider error".to_string(),
},
// ── ProcessingResponse ──────────────────────────────────
(
TurnState::ProcessingResponse,
TurnOutcome::NoToolCalls | TurnOutcome::NotToolCalls { .. },
) => TurnAction::BreakLoop,
(TurnState::ProcessingResponse, TurnOutcome::Success) => TurnAction::Continue {
next: TurnState::ExecutingTools,
},
// ── ExecutingTools ──────────────────────────────────────
(TurnState::ExecutingTools, TurnOutcome::Success) => TurnAction::Continue {
next: TurnState::Persisting,
},
(TurnState::ExecutingTools, TurnOutcome::ToolFailure { .. }) => TurnAction::Fail {
reason: "tool execution failed".to_string(),
},
// ── Persisting ──────────────────────────────────────────
(TurnState::Persisting, TurnOutcome::Success) => TurnAction::Continue {
next: TurnState::CheckingPolicy,
},
(TurnState::Persisting, TurnOutcome::PipelineError { .. }) => TurnAction::Fail {
reason: "persistence failed".to_string(),
},
// ── Fallback: unexpected combinations ────────────────────
(_, outcome) => TurnAction::Fail {
reason: format!("unexpected outcome {outcome:?} in state {state:?}"),
},
}
}
/// Derives the [`RunStatus`] implied by a given turn state.
#[must_use]
pub fn status_for(state: TurnState) -> RunStatus {
match state {
TurnState::CheckingPolicy | TurnState::Compacting | TurnState::BuildingContext => {
RunStatus::BuildingContext
}
TurnState::CallingModel | TurnState::ProcessingResponse => RunStatus::CallingModel,
TurnState::ExecutingTools => RunStatus::WaitingForTools,
TurnState::Persisting => RunStatus::Persisting,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// ── CheckingPolicy ──────────────────────────────────────────────
#[test]
fn policy_exceeded_fails() {
let action = TurnTransition::resolve(
TurnState::CheckingPolicy,
&TurnOutcome::PolicyExceeded {
reason: "iteration".into(),
},
);
assert_eq!(
action,
TurnAction::Fail {
reason: "iteration".into()
}
);
}
#[test]
fn policy_ok_proceeds_to_context() {
let action = TurnTransition::resolve(TurnState::CheckingPolicy, &TurnOutcome::Success);
assert_eq!(
action,
TurnAction::Continue {
next: TurnState::BuildingContext
}
);
}
// ── CallingModel ────────────────────────────────────────────────
#[test]
fn context_overflow_compacts_and_retries() {
let action =
TurnTransition::resolve(TurnState::CallingModel, &TurnOutcome::ContextOverflow);
assert_eq!(action, TurnAction::CompactAndRetry);
}
#[test]
fn model_success_moves_to_processing() {
let action = TurnTransition::resolve(TurnState::CallingModel, &TurnOutcome::Success);
assert_eq!(
action,
TurnAction::Continue {
next: TurnState::ProcessingResponse
}
);
}
#[test]
fn provider_error_fails() {
let action = TurnTransition::resolve(
TurnState::CallingModel,
&TurnOutcome::ProviderError {
message: "boom".into(),
},
);
assert_eq!(
action,
TurnAction::Fail {
reason: "provider error".into()
}
);
}
// ── Compacting ──────────────────────────────────────────────────
#[test]
fn compaction_success_returns_to_model() {
let action = TurnTransition::resolve(TurnState::Compacting, &TurnOutcome::Success);
assert_eq!(
action,
TurnAction::Continue {
next: TurnState::CallingModel
}
);
}
// ── ProcessingResponse ──────────────────────────────────────────
#[test]
fn no_tool_calls_breaks_loop() {
let action =
TurnTransition::resolve(TurnState::ProcessingResponse, &TurnOutcome::NoToolCalls);
assert_eq!(action, TurnAction::BreakLoop);
}
#[test]
fn not_tool_calls_finish_breaks() {
let action = TurnTransition::resolve(
TurnState::ProcessingResponse,
&TurnOutcome::NotToolCalls {
finish_reason: FinishReason::Stop,
},
);
assert_eq!(action, TurnAction::BreakLoop);
}
#[test]
fn tool_calls_moves_to_execution() {
let action = TurnTransition::resolve(TurnState::ProcessingResponse, &TurnOutcome::Success);
assert_eq!(
action,
TurnAction::Continue {
next: TurnState::ExecutingTools
}
);
}
#[test]
fn output_truncated_continues_to_model() {
let action =
TurnTransition::resolve(TurnState::ProcessingResponse, &TurnOutcome::OutputTruncated);
assert_eq!(
action,
TurnAction::Continue {
next: TurnState::CallingModel
}
);
}
// ── Persisting to loop ──────────────────────────────────────────
#[test]
fn persisting_success_returns_to_check() {
let action = TurnTransition::resolve(TurnState::Persisting, &TurnOutcome::Success);
assert_eq!(
action,
TurnAction::Continue {
next: TurnState::CheckingPolicy
}
);
}
// ── Status mapping ──────────────────────────────────────────────
#[test]
fn status_maps_correctly() {
assert_eq!(
TurnTransition::status_for(TurnState::BuildingContext),
RunStatus::BuildingContext
);
assert_eq!(
TurnTransition::status_for(TurnState::CallingModel),
RunStatus::CallingModel
);
assert_eq!(
TurnTransition::status_for(TurnState::ExecutingTools),
RunStatus::WaitingForTools
);
assert_eq!(
TurnTransition::status_for(TurnState::Persisting),
RunStatus::Persisting
);
}
}