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
//! Round ordering, observation boundaries and terminal-result selection.
use super::model::{control_cause, invoke, notify, stopped};
use super::{TurnInterruption, TurnResult, TurnRunner, commit, request};
use crate::{RunEvent, ToolCatalogError, ToolProcessingError, TurnRunOptions};
use causa_kernel::{
CallControl, Context, InvocationId, ModelStopReason, RoundId, ToolBatch, TurnId,
};
impl TurnRunner {
pub(super) async fn run_loop(
&self,
turn_id: &TurnId,
context: &mut Context,
options: &TurnRunOptions,
control: &CallControl,
streaming: bool,
) -> (TurnResult, Option<ToolBatch>) {
let mut round = 0;
let mut declared_before = 0u32;
loop {
if let Some(cause) = stopped(control, None) {
return interrupted(cause, None);
}
if round >= options.limits.max_model_rounds {
return interrupted(
TurnInterruption::MaxModelRounds {
limit: options.limits.max_model_rounds,
},
None,
);
}
let invocation_id = InvocationId {
turn_id: turn_id.clone(),
round_id: RoundId(round),
};
let bound = match self
.executor
.bind(invocation_id.clone(), control.clone())
.await
{
Ok(bound) => match &options.processor_data {
Some(data) => bound.with_processor_data(data.clone()),
None => bound,
},
Err(ToolCatalogError::Control(error)) => {
return interrupted(control_cause(error, Some(invocation_id)), None);
}
Err(error) => {
return interrupted(
TurnInterruption::ToolCatalogFailed {
invocation_id,
error,
},
None,
);
}
};
if let Some(cause) = stopped(control, Some(&invocation_id)) {
return interrupted(cause, None);
}
// The context records which tools the model is offered: a
// difference from the bound tools is appended before preparation,
// after the user turn or the tool results that end the context.
match commit::tool_change(context, &invocation_id, bound.surface()) {
Ok(Some(start)) => notify(
options,
RunEvent::BlocksCommitted {
invocation_id: &invocation_id,
blocks: &context.blocks()[start..],
},
),
Ok(None) => {}
Err(cause) => return interrupted(cause, None),
}
if let Some(cause) = stopped(control, Some(&invocation_id)) {
return interrupted(cause, None);
}
let request =
match request::prepare(context, &invocation_id, bound.surface(), options, control)
.await
{
Ok(request) => request,
Err(cause) => return interrupted(cause, None),
};
notify(options, RunEvent::ModelRequestReady { request: &request });
if let Some(cause) = stopped(control, Some(&invocation_id)) {
return interrupted(cause, None);
}
let output =
match invoke(self.gateway.as_ref(), &request, options, control, streaming).await {
Ok(output) => output,
Err(cause) => return interrupted(cause, None),
};
notify(
options,
RunEvent::ModelOutput {
invocation_id: &invocation_id,
output: &output,
},
);
// Only EndTurn and ToolUse are committed and continued. Every
// other reason returns the complete uncommitted output, and is
// selected before the stop check so a stop raised by the observer
// cannot replace it. No wildcard arm is needed.
match output.stop_reason {
ModelStopReason::EndTurn | ModelStopReason::ToolUse => {}
ModelStopReason::MaxTokens => {
return interrupted(
TurnInterruption::ModelMaxTokens {
invocation_id,
output,
},
None,
);
}
ModelStopReason::Refusal => {
return interrupted(
TurnInterruption::ModelRefusal {
invocation_id,
output,
},
None,
);
}
ModelStopReason::ContextWindowExceeded => {
return interrupted(
TurnInterruption::ModelContextWindowExceeded {
invocation_id,
output,
},
None,
);
}
ModelStopReason::Unrecognized => {
return interrupted(
TurnInterruption::ModelStopUnrecognized {
invocation_id,
output,
},
None,
);
}
}
if let Some(cause) = stopped(control, Some(&invocation_id)) {
return interrupted(cause, None);
}
let commit::ModelCommit {
output,
mut batch,
start,
} = match commit::model(context, &invocation_id, output) {
Ok(committed) => committed,
Err(cause) => return interrupted(cause, None),
};
notify(
options,
RunEvent::BlocksCommitted {
invocation_id: &invocation_id,
blocks: &context.blocks()[start..],
},
);
if output.stop_reason == ModelStopReason::EndTurn {
return (
TurnResult::Completed {
final_output: output,
},
None,
);
}
let declared_this_round = batch.calls().len();
let total = u32::try_from(declared_this_round)
.ok()
.and_then(|n| declared_before.checked_add(n));
if total.is_none_or(|total| total > options.limits.max_tool_calls) {
return interrupted(
TurnInterruption::MaxToolCalls {
invocation_id,
limit: options.limits.max_tool_calls,
declared_before,
declared_this_round,
},
Some(batch),
);
}
declared_before = total.expect("checked tool declaration total");
if let Some(cause) = stopped(control, Some(&invocation_id)) {
return interrupted(cause, Some(batch));
}
notify(
options,
RunEvent::ToolBatchReady {
invocation_id: &invocation_id,
batch: &batch,
},
);
if let Some(cause) = stopped(control, Some(&invocation_id)) {
return interrupted(cause, Some(batch));
}
// The module must finish controlled collection. Never drop this future
// in an outer cancellation select: it owns the started-call records.
let processed = bound.process(&mut batch).await;
notify(
options,
RunEvent::ToolBatchReturned {
invocation_id: &invocation_id,
batch: &batch,
result: processed.as_ref().map(|_| ()),
},
);
if let Err(error) = processed {
let cause = match error {
ToolProcessingError::Control(error) => {
control_cause(error, Some(invocation_id))
}
error => TurnInterruption::ToolProcessingFailed {
invocation_id,
error,
},
};
return interrupted(cause, Some(batch));
}
// A fully processed batch is committed before any stop is
// honored: the tools ran and the host's processors ran, so the
// results are facts and there is nothing left for the host to
// decide about them.
let commit::ToolCommit { start, unknown } =
match commit::tools(context, &invocation_id, &batch) {
Ok(committed) => committed,
Err(cause) => return interrupted(cause, Some(batch)),
};
notify(
options,
RunEvent::BlocksCommitted {
invocation_id: &invocation_id,
blocks: &context.blocks()[start..],
},
);
// The successful commit consumes the uncommitted tool batch.
// Unknown is a fixed terminal cause and is selected before a stop.
if let Some(call_block_id) = unknown {
return interrupted(
TurnInterruption::UnknownToolOutcome {
invocation_id,
call_block_id,
},
None,
);
}
if let Some(cause) = stopped(control, Some(&invocation_id)) {
return interrupted(cause, None);
}
round += 1;
}
}
}
fn interrupted(
cause: TurnInterruption,
batch: Option<ToolBatch>,
) -> (TurnResult, Option<ToolBatch>) {
(TurnResult::Interrupted { cause }, batch)
}