causa_runtime/driver.rs
1//! The execution stack here — retry scheduling, tool batch dispatch, artifact
2//! spill, control plumbing, and trace construction. The canonical consumer
3//! of the kernel's contracts lives here, one layer up.
4use crate::budget::FramePolicy;
5use crate::config::TurnRunOptions;
6use crate::config::UnknownOutcomePolicy;
7use crate::control::RunControl;
8use crate::conversation::{ConversationError, ConversationState, SealedResult};
9use crate::executor::ToolExecutor;
10use crate::hook::UnknownDecision;
11use crate::interaction::BatchDecision;
12use causa_kernel::AttemptNumber;
13use causa_kernel::ModelGateway;
14use causa_kernel::ModelRequest;
15use causa_kernel::ModelStopReason;
16use causa_kernel::TextPayload;
17use causa_kernel::ToolCallPayload;
18use causa_kernel::ToolResultPayload;
19use causa_kernel::{ArtifactRef, ToolCallId, ToolResultStatus, Truncation};
20use causa_kernel::{AttemptControl, ModelUsage, StreamDelta};
21use causa_kernel::{BlockContent, merged_frame};
22use causa_kernel::{BlockId, ConversationId, FrameScope, InvocationId, RoundId};
23use causa_kernel::{ModelInvokeError, ModelInvokeErrorKind, ModelOutput};
24use causa_kernel::{TurnContext, TurnSnapshot};
25use std::collections::{HashMap, HashSet};
26use std::sync::Arc;
27use std::time::{Duration, Instant};
28
29use tracing::Instrument;
30
31use crate::hook::{HookCtx, HookOutcome, PassthroughHook, ToolUseHook};
32use futures_util::StreamExt;
33
34fn millis_since(t: Instant) -> u64 {
35 t.elapsed().as_millis() as u64
36}
37
38/// The turn's committed-but-unanswered tool calls, in block order — the
39/// model-emitted draft order results pair into. Shared by the resume
40/// validation and the approval-resume prologue.
41pub(crate) fn unanswered_tool_calls(active: &TurnContext) -> Vec<ToolCallPayload> {
42 let mut pending: Vec<ToolCallPayload> = Vec::new();
43 for b in active.blocks() {
44 match &b.content {
45 BlockContent::ToolCall(c) => pending.push(c.clone()),
46 BlockContent::ToolResult(r) => pending.retain(|p| p.call_id != r.call_id),
47 _ => {}
48 }
49 }
50 pending
51}
52
53// Tool-use filtering lives behind `crate::hook::ToolUseHook`.
54// `TurnRunner` defaults to `PassthroughHook` (no opinion); concrete
55// filter policies live in `crate::filter` or the host layer.
56
57/// Why a turn terminated in `TurnResult::Interrupted`. The serde shape
58/// (`kind` / `detail`) is part of the event wire contract; see the
59/// wire-contract note on [`TurnOutcome`].
60#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
61#[serde(tag = "kind", content = "detail")]
62pub enum TurnInterruption {
63 /// The host cancelled the turn through the shared `RunControl` token
64 /// (including cancellation observed mid-call, mid-stream, or during
65 /// retry backoff).
66 ExplicitCancellation,
67 /// The turn deadline carried by `RunControl` passed (checked at every
68 /// loop top; retry backoff caps its wait at the remaining deadline and
69 /// re-checks before each attempt, and a retry loop that gives up after
70 /// the deadline has passed ends here rather than with the last
71 /// attempt's error kind).
72 TurnDeadlineExceeded,
73 /// Uniform carrier for terminal model-call failures: retry exhaustion
74 /// and non-retryable kinds (Permanent / InvalidRequest / UnknownOutcome)
75 /// all land here, discriminated by `last_kind`; a parent-caused
76 /// `Cancelled` maps to `ExplicitCancellation` instead.
77 RetryExhausted {
78 /// Error kind of the final failed attempt — retry exhaustion and
79 /// non-retryable kinds alike.
80 last_kind: ModelInvokeErrorKind,
81 /// Error message of the final failed attempt.
82 last_error: String,
83 },
84 /// The kernel refused the model response —
85 /// `TurnContext::append_model_output` rejected it.
86 InvalidModelOutput {
87 /// The kernel's rejection message.
88 reason: String,
89 },
90 /// The loop reached `TurnLimits::max_model_rounds` before the model
91 /// ended the turn.
92 MaxModelRounds {
93 /// The configured limit that was reached.
94 limit: u32,
95 },
96 /// The turn emitted more than `TurnLimits::max_tool_calls` tool calls
97 /// (counted at dispatch time, including a batch paused pending
98 /// approval).
99 MaxToolCalls {
100 /// The configured limit that was exceeded.
101 limit: u32,
102 },
103 /// A tool call ended `UnknownOutcome` while its trusted declaration
104 /// demands `Stop` — the call's result is unknowable, so continuing
105 /// is unsafe.
106 UnsafeUnknownOutcome {
107 /// The offending call.
108 call_id: ToolCallId,
109 },
110 /// Turn-scope frame materialization failed — `FramePolicy::materialize`
111 /// returned an error.
112 CompactionFailed {
113 /// The materialization error message.
114 reason: String,
115 },
116 /// A driver invariant broke (e.g. the fact machine refused an append)
117 /// — a caller bug, not a model or tool failure.
118 RunnerInvariantViolation {
119 /// The invariant failure message.
120 reason: String,
121 },
122 /// The model stopped on the token ceiling; the driver dispatches this
123 /// before applying, so no blocks persist.
124 ModelMaxTokens,
125 /// The model refused; the driver dispatches this before applying, so
126 /// no blocks persist.
127 ModelRefusal,
128}
129
130/// One model attempt inside a round — an entry of the retry ledger.
131#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
132pub struct AttemptTrace {
133 /// 1-based attempt number within the round's invocation.
134 pub attempt: AttemptNumber,
135 /// `None` = successful attempt; `Some(kind)` = the failure classification.
136 pub kind: Option<ModelInvokeErrorKind>,
137 /// Whether the failure was classified retryable (it may still not have
138 /// been retried once `RetryPolicy::max_retries` was spent).
139 pub is_retryable: bool,
140 /// Wall-clock duration of the attempt, in milliseconds.
141 pub duration_ms: u64,
142}
143/// Summary of the model output that closed a round, recorded before any
144/// tool dispatch.
145#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
146pub struct OutputSummary {
147 /// The model's stop reason (`EndTurn`, `ToolUse`, `MaxTokens`, `Refusal`).
148 pub stop_reason: ModelStopReason,
149 /// Token usage reported by the gateway, when the provider supplied it.
150 pub usage: Option<causa_kernel::ModelUsage>,
151 /// Number of tool calls in the model's response payload.
152 pub tool_call_count: usize,
153 /// Byte length of the response text.
154 pub response_text_bytes: usize,
155}
156/// One dispatched tool call, as observed by the executor.
157#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
158pub struct ToolCallTrace {
159 /// Id pairing this entry with the committed tool-call block.
160 pub call_id: ToolCallId,
161 /// Tool name from the draft payload (resolved by `call_id`).
162 pub tool_name: String,
163 /// The call's index in the model-emitted draft order.
164 pub position: usize,
165 /// Final result status of the call.
166 pub status: ToolResultStatus,
167 /// Output truncation marker (`Truncation::None` unless truncated).
168 pub truncation: Truncation,
169 /// Reference to the spilled full output, when truncation used an
170 /// `ArtifactStore`.
171 pub artifact: Option<ArtifactRef>,
172 /// Executor-measured wall-clock duration in milliseconds (`0` for
173 /// host-precomputed outcomes).
174 pub duration_ms: u64,
175}
176/// One dispatched tool batch, as observed by the executor.
177#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
178pub struct ToolBatchTrace {
179 /// Per-call traces in canonical (model draft) order — executor
180 /// results, hook rejections, and host-precomputed outcomes alike.
181 pub calls: Vec<ToolCallTrace>,
182 /// Actual completion order (recorded as the executor returns), not submission order.
183 pub completion_order: Vec<ToolCallId>,
184}
185/// One model round: framing, attempts, output, applied blocks, and its
186/// tool batch (when any).
187#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
188pub struct ModelRoundTrace {
189 /// 0-based round index within the turn.
190 pub round_id: RoundId,
191 /// Turn + round identity every attempt of the round shares (a retry
192 /// bumps only the attempt number).
193 pub invocation_id: InvocationId,
194 /// The `source_version` at frame materialization (the version before apply).
195 pub frame_version: causa_kernel::ContextVersion,
196 /// One entry per model attempt, in order.
197 pub attempts: Vec<AttemptTrace>,
198 /// `None` when no output was produced (every attempt failed).
199 pub output_summary: Option<OutputSummary>,
200 /// Ids of the blocks the model door committed this round (optional
201 /// text first, then one tool call per draft).
202 pub applied_block_ids: Vec<BlockId>,
203 /// The dispatched batch, when the round dispatched tools.
204 pub tool_batch: Option<ToolBatchTrace>,
205}
206/// The turn's trace: one record per model round plus totals.
207#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
208pub struct TurnTrace {
209 /// Rounds in execution order — including rounds whose invocation
210 /// never produced output.
211 pub rounds: Vec<ModelRoundTrace>,
212 /// Total tool calls emitted, counted at dispatch time (a paused batch
213 /// counts once, at emission — the resume does not re-count).
214 pub tool_calls_total: usize,
215 /// Wall-clock duration of this run in milliseconds (a resumed
216 /// continuation measures only the continuation).
217 pub total_duration_ms: u64,
218}
219impl TurnTrace {
220 /// An empty trace — no rounds, zero totals; the fresh-drive starting
221 /// point.
222 pub fn new() -> Self {
223 Self {
224 rounds: vec![],
225 tool_calls_total: 0,
226 total_duration_ms: 0,
227 }
228 }
229}
230impl Default for TurnTrace {
231 fn default() -> Self {
232 Self::new()
233 }
234}
235
236/// How a turn ended: completed, interrupted, or paused mid-turn. The
237/// serde shapes are a load-bearing wire contract (embedded in
238/// `ContextEvent`); `tests/serialization.rs` pins them.
239#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
240pub enum TurnResult {
241 /// The model ended the turn (`EndTurn`) — no pending work remains.
242 Completed {
243 /// The final model output.
244 final_output: ModelOutput,
245 },
246 /// The turn stopped early; `cause` discriminates why.
247 Interrupted {
248 /// Why the turn was interrupted.
249 cause: TurnInterruption,
250 },
251 /// Resumable suspension — not a terminal state: the turn's facts stay
252 /// open in the outcome's `context` / `state` (the single fact source),
253 /// the prepared batch is neither executed nor rejected, and
254 /// `resume_turn` / `TurnRunner::resume` continue the same turn from
255 /// the [`Continuation`].
256 Paused {
257 /// The single continuation: pause position, control counts,
258 /// prepared work, and queued inputs.
259 continuation: Continuation,
260 },
261}
262
263/// The hook-prepared work an approval pause checkpoints: the hook has
264/// already filtered / rejected / rewritten the model-emitted batch, and
265/// those decisions cannot be re-derived on resume — they are saved, not
266/// re-run. The original payloads remain derivable from the committed
267/// tool-call blocks (fact identity); the independent rewrite and rejections
268/// live here as serializable data.
269///
270/// The checkpoint stores recorded results plus the unknown-outcome actions
271/// fixed at pause time, not result envelopes: a tool's recorded result is
272/// a fact, and what an `UnknownOutcome` result does next is harness
273/// configuration. [`unknown_decisions`](Self::unknown_decisions)
274/// must exactly cover the saved results whose status is `UnknownOutcome`
275/// — no extra, missing, or duplicate entries — and a resume may never
276/// recompute them through new configuration.
277///
278/// # Wire compatibility
279///
280/// `rejected` is written as `[{result, policy}]` through a private runtime
281/// DTO — the policy is the fixed decision for `UnknownOutcome` entries and
282/// the canonical `Stop` for every other status (whose policy never
283/// participated in execution). Deserialization reads the same shape (both
284/// fields required), drops the policy of non-unknown entries, and rejects
285/// any decision set that does not exactly cover the saved `UnknownOutcome`
286/// results; earlier formats without prepared work still fail loudly.
287pub struct PreparedApproval {
288 /// Calls the hook admitted — arguments possibly rewritten — in model
289 /// draft order. These are what still await the host's decision at
290 /// resume; the resume decision must cover them exactly once.
291 pub awaiting: Vec<ToolCallPayload>,
292 /// Calls the hook rejected. The stored results commit verbatim at
293 /// resume (with their original call ids) and can never be re-decided —
294 /// a resume decision touching them is rejected before anything
295 /// executes.
296 pub rejected: Vec<ToolResultPayload>,
297 /// The unknown-outcome actions fixed when the turn paused: exactly one
298 /// entry per saved `UnknownOutcome` result, no more, no fewer. New
299 /// configuration never overrides these on resume.
300 pub unknown_decisions: Vec<UnknownDecision>,
301}
302impl std::fmt::Debug for PreparedApproval {
303 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304 f.debug_struct("PreparedApproval")
305 .field("awaiting", &self.awaiting.len())
306 .field("rejected", &self.rejected.len())
307 .field("unknown_decisions", &self.unknown_decisions.len())
308 .finish()
309 }
310}
311impl Clone for PreparedApproval {
312 fn clone(&self) -> Self {
313 Self {
314 awaiting: self.awaiting.clone(),
315 rejected: self.rejected.clone(),
316 unknown_decisions: self.unknown_decisions.clone(),
317 }
318 }
319}
320
321/// Private wire shape for one checkpointed rejection: the `{result, policy}`
322/// envelope. Not part of the public API — the public in-memory structure
323/// separates the recorded result from the saved action.
324#[derive(serde::Serialize, serde::Deserialize)]
325struct RejectedWire {
326 result: ToolResultPayload,
327 policy: UnknownOutcomePolicy,
328}
329
330impl serde::Serialize for PreparedApproval {
331 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
332 let rejected: Vec<RejectedWire> = self
333 .rejected
334 .iter()
335 .map(|result| RejectedWire {
336 result: result.clone(),
337 policy: if result.status == ToolResultStatus::UnknownOutcome {
338 // Exact cover is an invariant; fall back to the default
339 // action only to keep serialization total.
340 self.unknown_decisions
341 .iter()
342 .find(|d| d.call_id == result.call_id)
343 .map(|d| d.policy)
344 .unwrap_or_default()
345 } else {
346 // The policy of a decided result never participated in
347 // execution; the canonical Stop keeps the old shape.
348 UnknownOutcomePolicy::Stop
349 },
350 })
351 .collect();
352 #[derive(serde::Serialize)]
353 struct Wire<'a> {
354 awaiting: &'a Vec<ToolCallPayload>,
355 rejected: Vec<RejectedWire>,
356 }
357 Wire {
358 awaiting: &self.awaiting,
359 rejected,
360 }
361 .serialize(serializer)
362 }
363}
364
365impl<'de> serde::Deserialize<'de> for PreparedApproval {
366 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
367 #[derive(serde::Deserialize)]
368 struct Wire {
369 awaiting: Vec<ToolCallPayload>,
370 rejected: Vec<RejectedWire>,
371 }
372 let wire = Wire::deserialize(deserializer)?;
373 let mut rejected = Vec::with_capacity(wire.rejected.len());
374 let mut unknown_decisions: Vec<UnknownDecision> = Vec::new();
375 for entry in wire.rejected {
376 if entry.result.status == ToolResultStatus::UnknownOutcome {
377 // The saved action rides the old policy field; a missing
378 // one is a hard deserialize error, never a silent Stop.
379 unknown_decisions.push(UnknownDecision {
380 call_id: entry.result.call_id.clone(),
381 policy: entry.policy,
382 });
383 }
384 // Non-unknown entries' policy was never consumed by the
385 // execution stack; it is dropped on load and re-canonicalized
386 // to Stop on write.
387 rejected.push(entry.result);
388 }
389 // Exact cover: every saved UnknownOutcome has exactly one decision,
390 // and no decision points at a decided (non-unknown) result.
391 let unknown_ids: std::collections::HashSet<&ToolCallId> = rejected
392 .iter()
393 .filter(|r| r.status == ToolResultStatus::UnknownOutcome)
394 .map(|r| &r.call_id)
395 .collect();
396 let mut seen = std::collections::HashSet::new();
397 for d in &unknown_decisions {
398 if !unknown_ids.contains(&d.call_id) {
399 return Err(serde::de::Error::custom(format!(
400 "checkpoint decision for call {:?} does not match a saved UnknownOutcome result",
401 d.call_id.0
402 )));
403 }
404 if !seen.insert(&d.call_id) {
405 return Err(serde::de::Error::custom(format!(
406 "checkpoint has conflicting decisions for call {:?}",
407 d.call_id.0
408 )));
409 }
410 }
411 if seen.len() != unknown_ids.len() {
412 return Err(serde::de::Error::custom(
413 "checkpoint is missing the unknown-outcome decision for a saved result",
414 ));
415 }
416 // A call id appearing twice among the results would already be a
417 // fact-pairing error downstream; reject it here where the wire is
418 // at fault.
419 let mut ids = std::collections::HashSet::new();
420 for r in &rejected {
421 if !ids.insert(&r.call_id) {
422 return Err(serde::de::Error::custom(format!(
423 "checkpoint saves call {:?} twice",
424 r.call_id.0
425 )));
426 }
427 }
428 Ok(Self {
429 awaiting: wire.awaiting,
430 rejected,
431 unknown_decisions,
432 })
433 }
434}
435
436/// Where a turn paused. The execution stack currently emits only the
437/// approval position; the steering position exists so hosts that suspend
438/// before a model round produce a continuation the same resume machinery
439/// consumes (the pause point and the round together define the next step —
440/// never free-floating `Option`s).
441#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
442#[serde(tag = "kind", content = "detail", rename_all = "snake_case")]
443pub enum PausePoint {
444 /// The approval gate paused behind a hook-prepared batch.
445 AwaitingApproval {
446 /// The hook's prepared work awaiting the host's decision.
447 prepared: PreparedApproval,
448 /// Advisory decision budget the host granted itself, as *remaining*
449 /// time so the variant stays serde-friendly (a host anchors
450 /// `Instant::now() + d`). Carried for information only — the resume
451 /// never derives a deadline from it.
452 deadline: Option<Duration>,
453 },
454 /// Paused before a model round so the host can steer; no batch awaits
455 /// (a steering continuation over a turn with unanswered tool calls is
456 /// rejected at resume — the batch could never be answered).
457 PausedForSteering,
458}
459
460/// The single continuation of a paused turn: everything
461/// resuming needs beyond the paused outcome's fact state, the runner, the
462/// new options, and the new control. Rounds and quotas are read from here
463/// — never from the trace, which is observational and may be trimmed
464/// freely without changing where a resume continues or what it may spend.
465#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
466pub struct Continuation {
467 /// Where and why the turn paused.
468 pub pause_point: PausePoint,
469 /// The round the continuation sits at: for an approval pause, the
470 /// paused round whose batch executes first at resume (the loop then
471 /// continues at round+1); for a steering pause, the first round whose
472 /// model phase has not run yet.
473 pub round: u32,
474 /// Tool calls already counted against the turn's quota at emission
475 /// time (a paused batch was counted once, at emission — the resume
476 /// never re-counts it). The authoritative control count across
477 /// resumes.
478 pub accounted_tool_calls: usize,
479 /// Inputs received but not yet committed. A resume commits them first
480 /// (`user.steering` label), before the resume request's own inject —
481 /// "queued → injected → pulled" order; identical texts are independent
482 /// inputs and are never deduped.
483 #[serde(default, skip_serializing_if = "Vec::is_empty")]
484 pub queued_inputs: Vec<TextPayload>,
485}
486
487/// A bare-turn entry's result: the turn context (sealed unless the turn
488/// paused), the outcome, and the trace.
489#[derive(Debug, serde::Serialize, serde::Deserialize)]
490pub struct TurnOutcome {
491 /// The sealed active turn at handoff. Serialized through the
492 /// `turn_context_as_snapshot` adapter (see `causa_kernel::turn_context_as_snapshot`):
493 /// the in-memory `TurnContext` is the mutable fact machine, but
494 /// once sealed its snapshot projection is the canonical wire shape.
495 /// On reload we rebuild a sealed `TurnContext` via
496 /// `from_validated_blocks` + `seal()`.
497 #[serde(with = "causa_kernel::turn_context_as_snapshot")]
498 pub context: TurnContext,
499 /// Terminal result or pause — see [`TurnResult`].
500 pub result: TurnResult,
501 /// What happened during the run — see [`TurnTrace`].
502 pub trace: TurnTrace,
503}
504
505// Wire-contract note: `TurnResult`, `TurnOutcome`, `ConversationOutcome`
506// and the `TurnTrace` family are embedded in `causa_runtime::event::ContextEvent`
507// and delivered over IPC. Their Rust item paths live in this crate and may
508// move between layers without notice — but their serde shapes are a
509// load-bearing external contract and must not change without a breaking
510// migration of the event wire format. `tests/serialization.rs` pins the
511// shapes.
512
513/// The conversation entry's counterpart to [`TurnOutcome`]: consume/return —
514/// the state comes back with the active turn sealed inside and its outcome
515/// stamped; the host then calls `commit` (Completed) or `abort_turn`
516/// (Interrupted).
517#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
518pub struct ConversationOutcome {
519 /// The state back from the run, its active turn sealed and
520 /// outcome-stamped; the host then calls `commit` (Completed),
521 /// `abort_turn` (Interrupted), or `resume_turn` (Paused).
522 pub state: ConversationState,
523 /// The active turn's outcome.
524 pub result: TurnResult,
525 /// The active turn's trace (a resumed continuation appends to the
526 /// paused phase's trace).
527 pub trace: TurnTrace,
528}
529
530/// The frame source — the single fork point between the two runner entries.
531#[derive(Clone, Copy)]
532enum FrameSource<'a> {
533 /// Policy-shaped materialization over the active turn (Turn scope).
534 Turn(&'a FramePolicy),
535 /// Lossless merged view (Conversation scope) — the frame policy is
536 /// deliberately inert here.
537 Conversation {
538 conversation_id: &'a ConversationId,
539 history: &'a [TurnSnapshot],
540 },
541}
542
543/// The model-phase fork point: a batch `invoke`, or a delta `stream` whose
544/// items are forwarded to the interaction seam. Everything downstream of
545/// the assembled `ModelOutput` is shared state machine.
546#[derive(Clone, Copy)]
547pub(crate) enum ModelPhase {
548 Batch,
549 Stream,
550}
551
552/// Continuation payload for a resumed turn: the validated continuation plus
553/// the new decision, consumed once by `drive_from`'s prologue. Built by the
554/// public resume entries after validation; rounds, counts, prepared work,
555/// and queued inputs all come from the [`Continuation`] — the trace rides
556/// along as observation only.
557pub(crate) struct ResumeState {
558 /// The paused turn's continuation (pause position, round, counts,
559 /// prepared work, queued inputs).
560 pub(crate) continuation: Continuation,
561 /// The resume request's new decision for the prepared batch. `Some`
562 /// iff the pause point is `AwaitingApproval` (enforced by validation).
563 pub(crate) decision: Option<HookOutcome>,
564 /// The resume request's new inputs, appended before the next model
565 /// round — after the continuation's queued inputs.
566 pub(crate) inject: Vec<TextPayload>,
567 /// The paused phase's trace — rounds append to it, totals re-derive
568 /// from the continuation's count. A trimmed trace changes nothing.
569 pub(crate) trace: TurnTrace,
570}
571
572/// What a batch dispatch feeds the executor: live payloads, or
573/// pre-computed results (hook rejections and the host's
574/// `BatchDecision::Reject` copy).
575enum BatchWork {
576 Execute(Vec<ToolCallPayload>),
577 Precomputed(Vec<PrecomputedResult>),
578}
579
580/// One pre-computed tool result with its unknown-outcome action when that
581/// action is already fixed — a checkpoint entry, an explicit host
582/// decision, or an executed `UnknownOutcome` (resolved by the executed
583/// name at dispatch time). `None` resolves through the turn's
584/// unknown-outcome configuration by the batch's tool name;
585/// results with any other status never consume an action.
586#[derive(Debug, Clone)]
587struct PrecomputedResult {
588 result: ToolResultPayload,
589 fixed_policy: Option<UnknownOutcomePolicy>,
590}
591
592/// Attach explicit host decisions to precomputed results: an
593/// `UnknownOutcome` entry picks up its explicit decision if one is given,
594/// else stays unfixed (resolved by the batch name later). Entries for
595/// non-unknown results are ignored here and rejected by validation.
596fn attach_decisions(
597 results: Vec<ToolResultPayload>,
598 decisions: &[UnknownDecision],
599) -> Vec<PrecomputedResult> {
600 results
601 .into_iter()
602 .map(|result| PrecomputedResult {
603 fixed_policy: if result.status == ToolResultStatus::UnknownOutcome {
604 decisions
605 .iter()
606 .find(|d| d.call_id == result.call_id)
607 .map(|d| d.policy)
608 } else {
609 None
610 },
611 result,
612 })
613 .collect()
614}
615
616/// The execution stack over the kernel's ports: frame materialization,
617/// bounded model retry, tool batch dispatch through the hook and
618/// interaction seams, run control plumbing, and trace construction.
619pub struct TurnRunner {
620 gateway: Arc<dyn ModelGateway>,
621 executor: Arc<ToolExecutor>,
622 /// Seam for tool-use filtering. `TurnRunner::new()` defaults to
623 /// `PassthroughHook` (no filter applied — the driver carries no
624 /// opinion). Custom hooks (e.g. `FilterChain`, which implements
625 /// `ToolUseHook`) plug in via `TurnRunner::with_hook`.
626 hook: Arc<dyn ToolUseHook>,
627}
628impl TurnRunner {
629 /// A runner with the default [`PassthroughHook`] — no tool-use
630 /// filtering (the driver carries no opinion; opt in via
631 /// [`TurnRunner::with_hook`]).
632 pub fn new(gateway: Arc<dyn ModelGateway>, executor: Arc<ToolExecutor>) -> Self {
633 Self {
634 gateway,
635 executor,
636 hook: Arc::new(PassthroughHook),
637 }
638 }
639
640 /// A runner with a custom [`ToolUseHook`] applied between model
641 /// output and tool dispatch (e.g. a
642 /// [`FilterChain`](crate::filter::FilterChain)).
643 pub fn with_hook(
644 gateway: Arc<dyn ModelGateway>,
645 executor: Arc<ToolExecutor>,
646 hook: Arc<dyn ToolUseHook>,
647 ) -> Self {
648 Self {
649 gateway,
650 executor,
651 hook,
652 }
653 }
654 /// Frames materialize from the active turn alone (Turn scope,
655 /// policy-shaped).
656 pub async fn run(
657 &self,
658 context: TurnContext,
659 options: TurnRunOptions,
660 ctrl: RunControl,
661 ) -> TurnOutcome {
662 let span = tracing::info_span!(
663 "agent.turn",
664 turn_id = %context.turn_id().0,
665 scope = "turn"
666 );
667 self.run_inner(context, options, ctrl, ModelPhase::Batch)
668 .instrument(span)
669 .await
670 }
671
672 async fn run_inner(
673 &self,
674 mut context: TurnContext,
675 options: TurnRunOptions,
676 ctrl: RunControl,
677 phase: ModelPhase,
678 ) -> TurnOutcome {
679 let start = Instant::now();
680 let (result, mut trace, tool_calls_total) = self
681 .drive(
682 &mut context,
683 FrameSource::Turn(&options.frame),
684 &options,
685 &ctrl,
686 phase,
687 )
688 .await;
689 // Every drive exit is terminal or paused; the entry owns all
690 // bookkeeping (totals, duration, sealing — withheld on pause).
691 trace.tool_calls_total = tool_calls_total;
692 trace.total_duration_ms = millis_since(start);
693 if !matches!(result, TurnResult::Paused { .. }) {
694 context.seal();
695 }
696 TurnOutcome {
697 context,
698 result,
699 trace,
700 }
701 }
702
703 /// The streaming twin of [`TurnRunner::run`]. The model
704 /// phase consumes provider deltas — each one forwarded to
705 /// `options.interaction.on_delta` — instead of a single batch result;
706 /// retry bookkeeping, tool dispatch, traces, and sealing are the same
707 /// shared state machine. A retried attempt re-streams the same frame;
708 /// deltas already observed are advisory history, and the host decides
709 /// how to present the partial-then-reset flow.
710 pub async fn run_streaming(
711 &self,
712 context: TurnContext,
713 options: TurnRunOptions,
714 ctrl: RunControl,
715 ) -> TurnOutcome {
716 let span = tracing::info_span!(
717 "agent.turn",
718 turn_id = %context.turn_id().0,
719 scope = "turn.streaming"
720 );
721 self.run_inner(context, options, ctrl, ModelPhase::Stream)
722 .instrument(span)
723 .await
724 }
725
726 /// Frames materialize as the lossless merged view over committed history
727 /// plus the active turn (Conversation scope — the `options.frame` policy
728 /// is deliberately inert here). Consume/return: the state comes back
729 /// with the active turn sealed and outcome-stamped; the host then calls
730 /// `commit` (Completed) or `abort_turn` (Interrupted).
731 pub async fn run_in_conversation(
732 &self,
733 state: ConversationState,
734 options: TurnRunOptions,
735 ctrl: RunControl,
736 ) -> Result<ConversationOutcome, ConversationError> {
737 self.drive_conversation(state, options, ctrl, ModelPhase::Batch, None)
738 .await
739 }
740
741 /// The streaming twin of [`TurnRunner::run_in_conversation`]
742 /// — same consume/return contract and entry gates, delta-driven model
743 /// phase. `options.frame` stays deliberately inert here.
744 pub async fn run_in_conversation_streaming(
745 &self,
746 state: ConversationState,
747 options: TurnRunOptions,
748 ctrl: RunControl,
749 ) -> Result<ConversationOutcome, ConversationError> {
750 self.drive_conversation(state, options, ctrl, ModelPhase::Stream, None)
751 .await
752 }
753
754 /// Continue a paused conversation turn. The continuation half of
755 /// `run_in_conversation` — same
756 /// consume/return contract; the free function
757 /// `crate::resume::resume_turn` is the public face: it validates the
758 /// complete paused outcome (stamp, open turn, continuation-vs-facts,
759 /// decision coverage) and builds the [`ResumeState`] from the
760 /// outcome's [`Continuation`].
761 pub(crate) async fn resume_conversation(
762 &self,
763 state: ConversationState,
764 options: TurnRunOptions,
765 ctrl: RunControl,
766 resume: ResumeState,
767 ) -> Result<ConversationOutcome, ConversationError> {
768 // Resumes continue in batch phase: the facts are complete, and a
769 // streaming continuation is future work.
770 self.drive_conversation(state, options, ctrl, ModelPhase::Batch, Some(resume))
771 .await
772 }
773
774 /// Continue a paused bare turn — the
775 /// continuation half of [`TurnRunner::run`]/[`TurnRunner::run_streaming`].
776 /// Consumes the **complete paused outcome** plus the new
777 /// [`ResumeRequest`](crate::resume::ResumeRequest) (decision + inject);
778 /// the host no longer assembles reason/trace by hand. Validation runs
779 /// before anything executes or any fact changes — a rejected request
780 /// returns the untouched paused material in the
781 /// [`ResumeRejection`](crate::resume::ResumeRejection). Rounds, quota
782 /// counts, prepared hook work, and queued inputs all come from the
783 /// outcome's [`Continuation`]: a trimmed or empty trace changes
784 /// nothing, and lower limits stop the turn before external execution.
785 // Rejection returns the complete paused material by value, matching
786 // resume_turn and the Session construction contract.
787 #[allow(clippy::result_large_err)]
788 pub async fn resume(
789 &self,
790 outcome: TurnOutcome,
791 request: crate::resume::ResumeRequest,
792 options: TurnRunOptions,
793 ctrl: RunControl,
794 ) -> Result<TurnOutcome, crate::resume::ResumeRejection<TurnOutcome>> {
795 if let Err(reason) =
796 crate::resume::validate_resume(&outcome.result, &outcome.context, &request)
797 {
798 return Err(crate::resume::ResumeRejection { reason, outcome });
799 }
800 let TurnResult::Paused { continuation } = outcome.result else {
801 unreachable!("validated above");
802 };
803 let TurnOutcome {
804 mut context, trace, ..
805 } = outcome;
806 let start = Instant::now();
807 let (result, mut trace, tool_calls_total) = self
808 .drive_from(
809 &mut context,
810 FrameSource::Turn(&options.frame),
811 &options,
812 &ctrl,
813 ModelPhase::Batch,
814 Some(ResumeState {
815 continuation,
816 decision: request.decision,
817 inject: request.inject,
818 trace,
819 }),
820 )
821 .await;
822 trace.tool_calls_total = tool_calls_total;
823 trace.total_duration_ms = millis_since(start);
824 if !matches!(result, TurnResult::Paused { .. }) {
825 context.seal();
826 }
827 Ok(TurnOutcome {
828 context,
829 result,
830 trace,
831 })
832 }
833
834 /// The conversation entry body — entry gates, merged-frame source,
835 /// terminal bookkeeping, and outcome-stamped sealing shared by both
836 /// conversation entries and the resume path.
837 async fn drive_conversation(
838 &self,
839 state: ConversationState,
840 options: TurnRunOptions,
841 ctrl: RunControl,
842 phase: ModelPhase,
843 resume: Option<ResumeState>,
844 ) -> Result<ConversationOutcome, ConversationError> {
845 // One `agent.turn` span per entry, ids and scope only — never
846 // message content. The span is entered per poll via `Instrument`,
847 // so the future stays `Send`.
848 let scope = if resume.is_some() {
849 "conversation.resume"
850 } else if matches!(phase, ModelPhase::Stream) {
851 "conversation.streaming"
852 } else {
853 "conversation"
854 };
855 let turn_id = state
856 .active_turn()
857 .map(|t| t.turn_id().0)
858 .unwrap_or_default();
859 let span = tracing::info_span!(
860 "agent.turn",
861 turn_id = %turn_id,
862 conversation_id = %state.conversation_id().0,
863 scope = scope,
864 );
865 self.drive_conversation_inner(state, options, ctrl, phase, resume)
866 .instrument(span)
867 .await
868 }
869
870 /// The conversation entry body — entry gates, merged-frame source,
871 /// terminal bookkeeping, and outcome-stamped sealing shared by both
872 /// conversation entries and the resume path.
873 async fn drive_conversation_inner(
874 &self,
875 mut state: ConversationState,
876 options: TurnRunOptions,
877 ctrl: RunControl,
878 phase: ModelPhase,
879 resume: Option<ResumeState>,
880 ) -> Result<ConversationOutcome, ConversationError> {
881 // Entry gates — caller bugs fail fast, before the state machine.
882 let active_id = match state.active_turn() {
883 Some(t) => t.turn_id(),
884 None => return Err(ConversationError::NoActiveTurn),
885 };
886 if state.active_turn().expect("checked above").is_sealed() {
887 return Err(ConversationError::TurnAlreadySealed);
888 }
889 // A paused turn occupies the slot; fresh-driving it would run the
890 // same turn twice. Resume (resume_turn) or abort instead.
891 if resume.is_none() && state.sealed_result() == Some(SealedResult::Paused) {
892 return Err(ConversationError::TurnAlreadyActive);
893 }
894 // Field-split borrow: read conversation id and history while driving
895 // the active turn mutably; stamping happens after the loop through
896 // the public `seal_turn`, so no second &mut seam is exposed.
897 let (conversation_id, history, active) = state.runner_parts();
898 let active = active.expect("NoActiveTurn checked above");
899 let start = Instant::now();
900 let (result, mut trace, tool_calls_total) = self
901 .drive_from(
902 active,
903 FrameSource::Conversation {
904 conversation_id,
905 history: &history,
906 },
907 &options,
908 &ctrl,
909 phase,
910 resume,
911 )
912 .await;
913 trace.tool_calls_total = tool_calls_total;
914 trace.total_duration_ms = millis_since(start);
915 let stamp = match &result {
916 TurnResult::Completed { .. } => SealedResult::Completed,
917 TurnResult::Interrupted { .. } => SealedResult::Interrupted,
918 TurnResult::Paused { .. } => SealedResult::Paused,
919 };
920 state
921 .seal_turn(active_id, stamp)
922 .expect("active turn still present");
923 Ok(ConversationOutcome {
924 state,
925 result,
926 trace,
927 })
928 }
929
930 /// One streaming model attempt: forward every delta to the interaction
931 /// seam, then return the `Done` output (falling back to a stream-phase
932 /// `Usage` delta when `Done` carries none). An `Error` delta maps to the
933 /// same error shape the `invoke` path produces, so the shared retry
934 /// loop and trace machinery apply unchanged; a stream that ends
935 /// without `Done` is `UnknownOutcome`.
936 async fn stream_attempt(
937 &self,
938 req: &ModelRequest,
939 attempt_ctrl: &AttemptControl,
940 options: &TurnRunOptions,
941 round_id: RoundId,
942 ) -> Result<ModelOutput, ModelInvokeError> {
943 use futures_util::StreamExt;
944 let mut stream = self.gateway.stream(req, attempt_ctrl).await?;
945 let mut usage_seen: Option<ModelUsage> = None;
946 loop {
947 let item = tokio::select! {
948 biased;
949 _ = attempt_ctrl.cancellation_token().cancelled() => {
950 return Err(ModelInvokeError::new(
951 ModelInvokeErrorKind::Cancelled,
952 "cancelled during stream",
953 ));
954 }
955 next = stream.next() => match next {
956 Some(item) => item,
957 None => {
958 return Err(ModelInvokeError::new(
959 ModelInvokeErrorKind::UnknownOutcome,
960 "stream ended without Done",
961 ));
962 }
963 },
964 };
965 options.interaction.on_delta(round_id, &item).await;
966 match item {
967 StreamDelta::Done { final_output, .. } => {
968 let mut out = final_output;
969 if out.usage.is_none() {
970 out.usage = usage_seen;
971 }
972 return Ok(out);
973 }
974 StreamDelta::Usage(u) => usage_seen = Some(u),
975 StreamDelta::Error { kind, message } => {
976 return Err(ModelInvokeError::new(kind, message));
977 }
978 StreamDelta::TextDelta { .. }
979 | StreamDelta::ReasoningDelta { .. }
980 | StreamDelta::ToolCallDelta { .. } => {}
981 }
982 }
983 }
984
985 /// The shared state machine — every entry runs this loop; the frame
986 /// source, the model phase, and the resume prologue are the only
987 /// forks. Every exit is terminal or paused; the entries own
988 /// sealing/stamping.
989 async fn drive(
990 &self,
991 active: &mut TurnContext,
992 frames: FrameSource<'_>,
993 options: &TurnRunOptions,
994 ctrl: &RunControl,
995 phase: ModelPhase,
996 ) -> (TurnResult, TurnTrace, usize) {
997 self.drive_from(active, frames, options, ctrl, phase, None)
998 .await
999 }
1000
1001 async fn drive_from(
1002 &self,
1003 active: &mut TurnContext,
1004 frames: FrameSource<'_>,
1005 options: &TurnRunOptions,
1006 ctrl: &RunControl,
1007 phase: ModelPhase,
1008 resume: Option<ResumeState>,
1009 ) -> (TurnResult, TurnTrace, usize) {
1010 let mut round: u32;
1011 let mut tool_calls_total: usize;
1012 let mut trace: TurnTrace;
1013 let mut pending_inject: Vec<TextPayload>;
1014 match resume {
1015 None => {
1016 round = 0;
1017 tool_calls_total = 0;
1018 trace = TurnTrace::new();
1019 pending_inject = Vec::new();
1020 }
1021 Some(r) => {
1022 let ResumeState {
1023 continuation,
1024 decision,
1025 inject,
1026 trace: resumed_trace,
1027 } = r;
1028 let Continuation {
1029 pause_point,
1030 round: paused_round,
1031 accounted_tool_calls,
1032 queued_inputs,
1033 } = continuation;
1034 round = paused_round;
1035 tool_calls_total = accounted_tool_calls;
1036 trace = resumed_trace;
1037 // Queued inputs land before the request's inject ("queued
1038 // → injected → pulled"); both commit at the loop top with
1039 // the `user.steering` label.
1040 pending_inject = queued_inputs;
1041 pending_inject.extend(inject);
1042 // A resumed turn whose control is already spent exits
1043 // before touching facts.
1044 if ctrl.should_stop() {
1045 let cause = if ctrl.is_cancelled() {
1046 TurnInterruption::ExplicitCancellation
1047 } else {
1048 TurnInterruption::TurnDeadlineExceeded
1049 };
1050 return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
1051 }
1052 // Exhausted limits stop the turn BEFORE external
1053 // execution: a lowered `max_tool_calls` refuses the
1054 // withheld batch itself, a lowered `max_model_rounds`
1055 // refuses the paused round's batch (its results would
1056 // never reach a model call). Steering pauses re-enter the
1057 // loop instead, where the boundary checks apply before any
1058 // model call.
1059 if tool_calls_total as u64 > options.policy.limits.max_tool_calls as u64 {
1060 return (
1061 TurnResult::Interrupted {
1062 cause: TurnInterruption::MaxToolCalls {
1063 limit: options.policy.limits.max_tool_calls,
1064 },
1065 },
1066 trace,
1067 tool_calls_total,
1068 );
1069 }
1070 if matches!(pause_point, PausePoint::AwaitingApproval { .. })
1071 && round >= options.policy.limits.max_model_rounds
1072 {
1073 return (
1074 TurnResult::Interrupted {
1075 cause: TurnInterruption::MaxModelRounds {
1076 limit: options.policy.limits.max_model_rounds,
1077 },
1078 },
1079 trace,
1080 tool_calls_total,
1081 );
1082 }
1083 // Approval-resume prologue: execute the paused round's
1084 // batch. The saved hook rejections stay rejected; the new
1085 // decision covers the remaining awaiting calls exactly
1086 // once (validated at the entry, re-checked by `run_batch`).
1087 // The batch was already counted into `accounted_tool_calls`
1088 // at emission, so the prologue never re-counts it.
1089 if let Some(decision) = decision {
1090 let PausePoint::AwaitingApproval {
1091 prepared,
1092 deadline: _,
1093 } = pause_point
1094 else {
1095 unreachable!("entry validation pairs a decision with an approval pause");
1096 };
1097 // The paused batch is exactly the committed-but-
1098 // unanswered tool calls of this turn, in block order —
1099 // the model-emitted draft order the results pair into.
1100 let draft = unanswered_tool_calls(active);
1101 // Checkpoint entries commit verbatim with their fixed
1102 // actions; only the awaiting calls are
1103 // newly decided. New precomputed rejections use the
1104 // host's explicit entries, else resolve through the
1105 // current configuration by the batch name.
1106 let PreparedApproval {
1107 rejected: saved_rejected,
1108 unknown_decisions: saved_decisions,
1109 ..
1110 } = prepared;
1111 let mut rejected: Vec<PrecomputedResult> = saved_rejected
1112 .into_iter()
1113 .map(|result| PrecomputedResult {
1114 fixed_policy: saved_decisions
1115 .iter()
1116 .find(|d| d.call_id == result.call_id)
1117 .map(|d| d.policy),
1118 result,
1119 })
1120 .collect();
1121 rejected.extend(attach_decisions(
1122 decision.rejected,
1123 &decision.unknown_decisions,
1124 ));
1125 if let Err(cause) = self
1126 .run_batch(
1127 active,
1128 &draft,
1129 BatchWork::Execute(decision.to_execute),
1130 rejected,
1131 options,
1132 ctrl,
1133 round,
1134 &mut trace,
1135 )
1136 .await
1137 {
1138 return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
1139 }
1140 round += 1;
1141 }
1142 }
1143 }
1144
1145 // The first model phase of this drive advertises the host-declared
1146 // surface (the `TurnInvocation` baseline); every later round
1147 // boundary re-snapshots the runner's executor, so catalog changes
1148 // — including ones this turn's own tool calls triggered — reach the
1149 // next request. Retries within one round reuse that round's
1150 // snapshot.
1151 let first_model_round = round;
1152
1153 loop {
1154 // Steering: resume-time injections first, then the
1155 // round-boundary pull. Both append with the `user.steering`
1156 // source label; the next model round sees them.
1157 if !pending_inject.is_empty() {
1158 for text in std::mem::take(&mut pending_inject) {
1159 if let Err(e) = active.append_input(text, "user.steering") {
1160 return (
1161 TurnResult::Interrupted {
1162 cause: TurnInterruption::RunnerInvariantViolation {
1163 reason: e.to_string(),
1164 },
1165 },
1166 trace,
1167 tool_calls_total,
1168 );
1169 }
1170 }
1171 }
1172 for text in options.interaction.pending_inputs().await {
1173 if let Err(e) = active.append_input(text, "user.steering") {
1174 return (
1175 TurnResult::Interrupted {
1176 cause: TurnInterruption::RunnerInvariantViolation {
1177 reason: e.to_string(),
1178 },
1179 },
1180 trace,
1181 tool_calls_total,
1182 );
1183 }
1184 }
1185 // boundary checks
1186 if ctrl.should_stop() {
1187 let cause = if ctrl.is_cancelled() {
1188 TurnInterruption::ExplicitCancellation
1189 } else {
1190 TurnInterruption::TurnDeadlineExceeded
1191 };
1192 return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
1193 }
1194 if round >= options.policy.limits.max_model_rounds {
1195 return (
1196 TurnResult::Interrupted {
1197 cause: TurnInterruption::MaxModelRounds {
1198 limit: options.policy.limits.max_model_rounds,
1199 },
1200 },
1201 trace,
1202 tool_calls_total,
1203 );
1204 }
1205 // materialize the round's frame — the single fork point between
1206 // the entries; the fact machine only ever offers the lossless
1207 // projection, the policy orchestrates anything beyond it
1208 let frame = match frames {
1209 FrameSource::Turn(policy) => {
1210 match policy.materialize(active, RoundId(round)).await {
1211 Ok(f) => f,
1212 Err(e) => {
1213 return (
1214 TurnResult::Interrupted {
1215 cause: TurnInterruption::CompactionFailed {
1216 reason: e.to_string(),
1217 },
1218 },
1219 trace,
1220 tool_calls_total,
1221 );
1222 }
1223 }
1224 }
1225 FrameSource::Conversation {
1226 conversation_id,
1227 history,
1228 } => merged_frame(conversation_id, history, active, RoundId(round)),
1229 };
1230 let frame_version = match &frame.scope {
1231 FrameScope::Turn { source_version, .. }
1232 | FrameScope::Conversation { source_version, .. } => *source_version,
1233 };
1234 let invocation = InvocationId {
1235 turn_id: active.turn_id(),
1236 round_id: RoundId(round),
1237 };
1238 // Per-round tool surface (see `first_model_round` above): the
1239 // host baseline for the first model phase, a fresh executor
1240 // snapshot at every later round boundary. Retries inside the
1241 // attempt loop below reuse the same snapshot, so advertising
1242 // and dispatch routing stay one decision per round.
1243 let round_surface = if round == first_model_round {
1244 options.invocation.tool_surface.clone()
1245 } else {
1246 self.executor.tool_surface().await
1247 };
1248 // The round span covers the bounded retry loop; spans are
1249 // entered per poll via `Instrument`, so the future stays `Send`.
1250 // Fields carry ids and names only — never frame content or
1251 // arguments.
1252 let round_span = tracing::debug_span!(
1253 "agent.round",
1254 turn_id = %invocation.turn_id.0,
1255 round_id = round
1256 );
1257 let (attempts, output) = async {
1258 // bounded logical retry: same InvocationId / ContextFrame, attempt+1
1259 let mut attempt: u32 = 1;
1260 let mut attempts: Vec<AttemptTrace> = Vec::new();
1261 let output: Result<ModelOutput, ModelInvokeError> = loop {
1262 let attempt_started = Instant::now();
1263 let attempt_ctrl = ctrl.for_attempt(options.policy.attempt_timeout);
1264 let req = ModelRequest {
1265 invocation_id: invocation.clone(),
1266 attempt: AttemptNumber(attempt),
1267 frame: frame.clone(),
1268 model: options.invocation.model.clone(),
1269 tool_surface: round_surface.clone(),
1270 generation: options.invocation.generation.clone(),
1271 cache: options.invocation.cache,
1272 };
1273 let attempt_span = tracing::debug_span!(
1274 "agent.attempt",
1275 attempt = attempt,
1276 model = %options.invocation.model.0
1277 );
1278 let result = match phase {
1279 ModelPhase::Batch => {
1280 self.gateway
1281 .invoke(&req, &attempt_ctrl)
1282 .instrument(attempt_span)
1283 .await
1284 }
1285 ModelPhase::Stream => {
1286 self.stream_attempt(&req, &attempt_ctrl, options, RoundId(round))
1287 .instrument(attempt_span)
1288 .await
1289 }
1290 };
1291 match result {
1292 Ok(out) => {
1293 attempts.push(AttemptTrace {
1294 attempt: AttemptNumber(attempt),
1295 kind: None,
1296 is_retryable: false,
1297 duration_ms: millis_since(attempt_started),
1298 });
1299 break Ok(out);
1300 }
1301 Err(e) => {
1302 let retryable = options.policy.retry.allows(&e.kind);
1303 attempts.push(AttemptTrace {
1304 attempt: AttemptNumber(attempt),
1305 kind: Some(e.kind.clone()),
1306 is_retryable: retryable,
1307 duration_ms: millis_since(attempt_started),
1308 });
1309 if retryable && attempt <= options.policy.retry.max_retries {
1310 // Cancellation- and deadline-aware backoff:
1311 // sleep between attempts, racing the shared
1312 // token so a cancel lands immediately instead
1313 // of after the wait, and capping the wait at
1314 // the remaining turn deadline so the driver
1315 // never holds the turn hostage in its own
1316 // backoff.
1317 let delay = options.policy.retry.backoff_delay(attempt + 1);
1318 let capped = ctrl
1319 .remaining_turn_time()
1320 .map_or(delay, |remaining| delay.min(remaining));
1321 if !capped.is_zero() {
1322 tokio::select! {
1323 biased;
1324 _ = attempt_ctrl.cancellation_token().cancelled() => {
1325 break Err(ModelInvokeError::new(
1326 ModelInvokeErrorKind::Cancelled,
1327 "cancelled during retry backoff",
1328 ));
1329 }
1330 _ = tokio::time::sleep(capped) => {}
1331 }
1332 }
1333 // Stop guard before spending another attempt:
1334 // a cancel or a deadline that landed during the
1335 // backoff (or the previous attempt) ends the
1336 // loop here. The outer mapping attributes the
1337 // turn's end to `TurnDeadlineExceeded` whenever
1338 // the deadline has passed, so the terminal
1339 // reason matches the round-boundary check.
1340 if ctrl.should_stop() {
1341 if ctrl.is_cancelled() {
1342 break Err(ModelInvokeError::new(
1343 ModelInvokeErrorKind::Cancelled,
1344 "cancelled during retry backoff",
1345 ));
1346 }
1347 break Err(ModelInvokeError::new(
1348 ModelInvokeErrorKind::TimedOut,
1349 "turn deadline passed during retry backoff",
1350 ));
1351 }
1352 attempt += 1;
1353 continue;
1354 }
1355 break Err(e);
1356 }
1357 }
1358 };
1359 (attempts, output)
1360 }
1361 .instrument(round_span)
1362 .await;
1363 let output = match output {
1364 Ok(o) => o,
1365 Err(e) => {
1366 let cause = if matches!(e.kind, ModelInvokeErrorKind::Cancelled)
1367 && ctrl.is_cancelled()
1368 {
1369 TurnInterruption::ExplicitCancellation
1370 } else if ctrl.should_stop() && !ctrl.is_cancelled() {
1371 // The turn deadline passed while the retry loop was
1372 // still working — mid-attempt or during backoff — so
1373 // the turn ends with the same verdict the
1374 // round-boundary check would produce, not with the
1375 // last attempt's error kind.
1376 TurnInterruption::TurnDeadlineExceeded
1377 } else {
1378 TurnInterruption::RetryExhausted {
1379 last_kind: e.kind.clone(),
1380 last_error: e.message.clone(),
1381 }
1382 };
1383 trace.rounds.push(ModelRoundTrace {
1384 round_id: RoundId(round),
1385 invocation_id: invocation,
1386 frame_version,
1387 attempts,
1388 output_summary: None,
1389 applied_block_ids: vec![],
1390 tool_batch: None,
1391 });
1392 return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
1393 }
1394 };
1395 let output_summary = Some(OutputSummary {
1396 stop_reason: output.stop_reason,
1397 usage: output.usage.clone(),
1398 tool_call_count: output.response.tool_calls.len(),
1399 response_text_bytes: output.response.text.0.len(),
1400 });
1401 // Every round lands in the trace exactly once, right after the
1402 // output is summarized — including the paths that never apply a
1403 // block. Later stages fill their fields through `last_mut`.
1404 trace.rounds.push(ModelRoundTrace {
1405 round_id: RoundId(round),
1406 invocation_id: invocation.clone(),
1407 frame_version,
1408 attempts,
1409 output_summary,
1410 applied_block_ids: vec![],
1411 tool_batch: None,
1412 });
1413 // MaxTokens / Refusal never persist blocks; they carry their
1414 // own dedicated interruption causes, so dispatch before apply.
1415 // This is driver policy: the canonical append_model_output would
1416 // happily record them as facts.
1417 if matches!(
1418 output.stop_reason,
1419 ModelStopReason::MaxTokens | ModelStopReason::Refusal
1420 ) {
1421 let cause = if matches!(output.stop_reason, ModelStopReason::MaxTokens) {
1422 TurnInterruption::ModelMaxTokens
1423 } else {
1424 TurnInterruption::ModelRefusal
1425 };
1426 return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
1427 }
1428 let applied = match active.append_model_output(
1429 invocation.clone(),
1430 &output.response,
1431 output.stop_reason,
1432 ) {
1433 Ok(a) => a,
1434 Err(e) => {
1435 return (
1436 TurnResult::Interrupted {
1437 cause: TurnInterruption::InvalidModelOutput {
1438 reason: e.to_string(),
1439 },
1440 },
1441 trace,
1442 tool_calls_total,
1443 );
1444 }
1445 };
1446 // The receipt carries the prepared tool calls in model draft
1447 // order — the same payloads the kernel committed, with ids
1448 // generated exactly once. No re-reading of blocks.
1449 let call_payloads: Vec<ToolCallPayload> = applied.tool_calls;
1450 trace
1451 .rounds
1452 .last_mut()
1453 .expect("round trace just pushed")
1454 .applied_block_ids = applied.block_ids.clone();
1455 match output.stop_reason {
1456 ModelStopReason::EndTurn => {
1457 // append_model_output guarantees EndTurn has empty tool_calls
1458 return (
1459 TurnResult::Completed {
1460 final_output: output,
1461 },
1462 trace,
1463 tool_calls_total,
1464 );
1465 }
1466 ModelStopReason::ToolUse => {
1467 // Emitted calls count at dispatch time — including the
1468 // batch still pending behind a pause (the resume
1469 // therefore must not re-count it).
1470 tool_calls_total += call_payloads.len();
1471 if tool_calls_total as u32 > options.policy.limits.max_tool_calls {
1472 return (
1473 TurnResult::Interrupted {
1474 cause: TurnInterruption::MaxToolCalls {
1475 limit: options.policy.limits.max_tool_calls,
1476 },
1477 },
1478 trace,
1479 tool_calls_total,
1480 );
1481 }
1482 // ToolUse hook: the tool-use filter seam. `TurnRunner::new()`
1483 // defaults to `PassthroughHook` (no filter applied — opt in
1484 // via `with_hook`). `FilterChain` plugs in via `with_hook`,
1485 // implementing `ToolUseHook` directly.
1486 let (hook_to_exec, hook_rejected, hook_decisions): (
1487 Vec<ToolCallPayload>,
1488 Vec<ToolResultPayload>,
1489 Vec<UnknownDecision>,
1490 ) = {
1491 let call_control = ctrl
1492 .for_attempt(options.policy.attempt_timeout)
1493 .for_call(options.execution.call_timeout);
1494 let conversation_id = match &frames {
1495 FrameSource::Conversation {
1496 conversation_id, ..
1497 } => Some(*conversation_id),
1498 FrameSource::Turn(_) => None,
1499 };
1500 let hook_ctx = HookCtx {
1501 turn_id: &active.turn_id(),
1502 conversation_id,
1503 round_id: RoundId(round),
1504 control: &call_control,
1505 };
1506 let outcome = self.hook.apply(call_payloads.clone(), &hook_ctx).await;
1507 (
1508 outcome.to_execute,
1509 outcome.rejected,
1510 outcome.unknown_decisions,
1511 )
1512 };
1513 // The second gate — the host's batch decision.
1514 // Default `Proceed`; `Pause` suspends the turn with the
1515 // model-emitted batch as `pending_calls`, before any
1516 // execution or rejection lands in the facts.
1517 let decision = options.interaction.decide_batch(&hook_to_exec).await;
1518 match decision {
1519 BatchDecision::Pause { deadline } => {
1520 // The checkpoint saves the hook's prepared work
1521 // (admitted-with-rewrites + rejections) so the
1522 // resume never re-runs the hook and never
1523 // re-admits a rejected call. The outcome's
1524 // context is the single fact source — no
1525 // duplicated snapshot rides on the variant.
1526 // The checkpoint fixes the
1527 // actual action for every prepared
1528 // UnknownOutcome — the explicit hook entry if
1529 // given, else the turn's current configuration
1530 // resolved by the batch's tool name. A resume
1531 // can never recompute these.
1532 let draft_names: HashMap<ToolCallId, String> = call_payloads
1533 .iter()
1534 .map(|p| (p.call_id.clone(), p.tool_name.clone()))
1535 .collect();
1536 let unknown_decisions = hook_rejected
1537 .iter()
1538 .filter(|r| r.status == ToolResultStatus::UnknownOutcome)
1539 .map(|r| UnknownDecision {
1540 call_id: r.call_id.clone(),
1541 policy: hook_decisions
1542 .iter()
1543 .find(|d| d.call_id == r.call_id)
1544 .map(|d| d.policy)
1545 .unwrap_or_else(|| {
1546 options.policy.unknown_outcome.resolve(
1547 draft_names
1548 .get(&r.call_id)
1549 .map(String::as_str)
1550 .unwrap_or(""),
1551 )
1552 }),
1553 })
1554 .collect();
1555 return (
1556 TurnResult::Paused {
1557 continuation: Continuation {
1558 pause_point: PausePoint::AwaitingApproval {
1559 prepared: PreparedApproval {
1560 awaiting: hook_to_exec,
1561 rejected: hook_rejected,
1562 unknown_decisions,
1563 },
1564 deadline,
1565 },
1566 round,
1567 accounted_tool_calls: tool_calls_total,
1568 queued_inputs: Vec::new(),
1569 },
1570 },
1571 trace,
1572 tool_calls_total,
1573 );
1574 }
1575 BatchDecision::Proceed => {
1576 if let Err(cause) = self
1577 .run_batch(
1578 active,
1579 &call_payloads,
1580 BatchWork::Execute(hook_to_exec),
1581 attach_decisions(hook_rejected, &hook_decisions),
1582 options,
1583 ctrl,
1584 round,
1585 &mut trace,
1586 )
1587 .await
1588 {
1589 return (
1590 TurnResult::Interrupted { cause },
1591 trace,
1592 tool_calls_total,
1593 );
1594 }
1595 }
1596 BatchDecision::Rewrite(rewritten) => {
1597 if let Err(cause) = self
1598 .run_batch(
1599 active,
1600 &call_payloads,
1601 BatchWork::Execute(rewritten),
1602 attach_decisions(hook_rejected, &hook_decisions),
1603 options,
1604 ctrl,
1605 round,
1606 &mut trace,
1607 )
1608 .await
1609 {
1610 return (
1611 TurnResult::Interrupted { cause },
1612 trace,
1613 tool_calls_total,
1614 );
1615 }
1616 }
1617 BatchDecision::Reject {
1618 results,
1619 unknown_decisions,
1620 } => {
1621 if let Err(cause) = self
1622 .run_batch(
1623 active,
1624 &call_payloads,
1625 BatchWork::Precomputed(attach_decisions(
1626 results,
1627 &unknown_decisions,
1628 )),
1629 attach_decisions(hook_rejected, &hook_decisions),
1630 options,
1631 ctrl,
1632 round,
1633 &mut trace,
1634 )
1635 .await
1636 {
1637 return (
1638 TurnResult::Interrupted { cause },
1639 trace,
1640 tool_calls_total,
1641 );
1642 }
1643 }
1644 }
1645 round += 1;
1646 }
1647 ModelStopReason::MaxTokens | ModelStopReason::Refusal => {
1648 unreachable!("handled before append_model_output")
1649 }
1650 }
1651 }
1652 }
1653
1654 /// Execute a tool batch and commit its results — the shared core of
1655 /// the normal ToolUse dispatch and the approval-resume prologue.
1656 // Private shared core; every parameter is a distinct axis (facts,
1657 // order, work, policy, control, round, trace) — grouping would only
1658 // obscure it.
1659 #[allow(clippy::too_many_arguments)]
1660 /// `draft_order` is the model-emitted payload order; the canonical
1661 /// result order follows it (host rewrites and pre-computed rejects
1662 /// still pair by `call_id`). The batch trace attaches to the round's
1663 /// trace entry before committing, so even a
1664 /// `RunnerInvariantViolation` keeps the observations.
1665 async fn run_batch(
1666 &self,
1667 active: &mut TurnContext,
1668 draft_order: &[ToolCallPayload],
1669 work: BatchWork,
1670 mut rejected: Vec<PrecomputedResult>,
1671 options: &TurnRunOptions,
1672 ctrl: &RunControl,
1673 round: u32,
1674 trace: &mut TurnTrace,
1675 ) -> Result<(), TurnInterruption> {
1676 // Batch completeness is runner policy (the kernel's tool door
1677 // intentionally accepts partial commits): every model-emitted call
1678 // must be covered exactly once by the work + rejected decision —
1679 // no silent drops, no duplicates, no foreign ids. Validated BEFORE
1680 // dispatch so a broken decision cannot spend side effects on calls
1681 // the facts can never pair.
1682 let expected: HashSet<ToolCallId> = draft_order.iter().map(|p| p.call_id.clone()).collect();
1683 let mut covered: HashSet<ToolCallId> = HashSet::new();
1684 let work_ids: Vec<&ToolCallId> = match &work {
1685 BatchWork::Execute(payloads) => payloads.iter().map(|p| &p.call_id).collect(),
1686 BatchWork::Precomputed(pre) => pre.iter().map(|o| &o.result.call_id).collect(),
1687 };
1688 for call_id in work_ids
1689 .into_iter()
1690 .chain(rejected.iter().map(|o| &o.result.call_id))
1691 {
1692 if !expected.contains(call_id) {
1693 return Err(TurnInterruption::RunnerInvariantViolation {
1694 reason: format!(
1695 "batch decision covers call {:?} which the model did not emit",
1696 call_id.0
1697 ),
1698 });
1699 }
1700 if !covered.insert(call_id.clone()) {
1701 return Err(TurnInterruption::RunnerInvariantViolation {
1702 reason: format!("batch decision covers call {:?} more than once", call_id.0),
1703 });
1704 }
1705 }
1706 if covered.len() != expected.len() {
1707 let missing: Vec<String> = expected
1708 .difference(&covered)
1709 .map(|id| id.0.clone())
1710 .collect();
1711 return Err(TurnInterruption::RunnerInvariantViolation {
1712 reason: format!(
1713 "batch decision does not cover every emitted call: missing {missing:?}"
1714 ),
1715 });
1716 }
1717 // parallel dispatch; completion order comes from the
1718 // stream (each future is yielded as it finishes), so no
1719 // shared log is needed
1720 let (mut results, completion_order, call_durations): (
1721 Vec<PrecomputedResult>,
1722 Vec<ToolCallId>,
1723 HashMap<ToolCallId, u64>,
1724 ) = match work {
1725 BatchWork::Execute(to_exec) => {
1726 let futs = to_exec.into_iter().map(|payload| {
1727 let unknown_outcome = options.policy.unknown_outcome.clone();
1728 let cc = ctrl
1729 .for_attempt(options.policy.attempt_timeout)
1730 .for_call(options.execution.call_timeout);
1731 let store = options.execution.artifact_store.clone();
1732 let tc = options.execution.token_counter.clone();
1733 // The effective per-call output limit is
1734 // resolved by the ACTUAL executed name (post hook /
1735 // rewrite / resume decision) before dispatch; the
1736 // executor never consults the tool object.
1737 let limits = options
1738 .execution
1739 .tool_output_limits_overrides
1740 .get(&payload.tool_name)
1741 .copied()
1742 .unwrap_or(options.execution.tool_output_limits);
1743 // An executed UnknownOutcome's action
1744 // resolves by the executed name, not the draft's.
1745 let name = payload.tool_name.clone();
1746 let exec = self.executor.clone();
1747 async move {
1748 let t0 = Instant::now();
1749 let result = exec
1750 .execute_with_limits(payload, cc, store, tc, limits)
1751 .await;
1752 let fixed_policy = if result.status == ToolResultStatus::UnknownOutcome {
1753 Some(unknown_outcome.resolve(&name))
1754 } else {
1755 None
1756 };
1757 (
1758 PrecomputedResult {
1759 result,
1760 fixed_policy,
1761 },
1762 millis_since(t0),
1763 )
1764 }
1765 });
1766 let mut stream = futures_util::stream::FuturesUnordered::from_iter(futs);
1767 let mut results = Vec::with_capacity(stream.len());
1768 let mut completion_order = Vec::with_capacity(stream.len());
1769 let mut call_durations: HashMap<ToolCallId, u64> = HashMap::new();
1770 while let Some((pre, duration_ms)) = stream.next().await {
1771 completion_order.push(pre.result.call_id.clone());
1772 call_durations.insert(pre.result.call_id.clone(), duration_ms);
1773 results.push(pre);
1774 }
1775 (results, completion_order, call_durations)
1776 }
1777 BatchWork::Precomputed(precomputed) => (
1778 precomputed,
1779 Vec::new(), // host-supplied: no executor completion order
1780 HashMap::new(),
1781 ),
1782 };
1783 results.append(&mut rejected);
1784 // Post-execution identity: every returned outcome must answer one
1785 // of the batch's own calls — a tool fabricating a foreign id fails
1786 // loudly here instead of as a kernel pairing error after the fact.
1787 if let Some(foreign) = results
1788 .iter()
1789 .find(|r| !expected.contains(&r.result.call_id))
1790 {
1791 return Err(TurnInterruption::RunnerInvariantViolation {
1792 reason: format!(
1793 "tool outcome answers foreign call {:?}",
1794 foreign.result.call_id.0
1795 ),
1796 });
1797 }
1798 // Canonical order = model draft order, taken from the
1799 // receipt's position — not from ToolCallId encoding. The
1800 // kernel re-derives the same order from call block
1801 // sequences when committing.
1802 let order_index: HashMap<ToolCallId, usize> = draft_order
1803 .iter()
1804 .enumerate()
1805 .map(|(i, p)| (p.call_id.clone(), i))
1806 .collect();
1807 results.sort_by_key(|r| order_index.get(&r.result.call_id).copied());
1808 let tool_names: HashMap<ToolCallId, String> = draft_order
1809 .iter()
1810 .map(|p| (p.call_id.clone(), p.tool_name.clone()))
1811 .collect();
1812 // Resolve every remaining unknown-outcome action through
1813 // the turn policy, keyed by the batch's tool name for the call
1814 // (precomputed entries were never executed, so the batch name is
1815 // their actual name). Explicit / checkpoint-fixed actions win.
1816 for pre in &mut results {
1817 if pre.result.status == ToolResultStatus::UnknownOutcome && pre.fixed_policy.is_none() {
1818 pre.fixed_policy = Some(
1819 options.policy.unknown_outcome.resolve(
1820 tool_names
1821 .get(&pre.result.call_id)
1822 .map(String::as_str)
1823 .unwrap_or(""),
1824 ),
1825 );
1826 }
1827 }
1828 // Every UnknownOutcome now carries exactly one resolved action.
1829 debug_assert!(results.iter().all(|pre| {
1830 pre.result.status != ToolResultStatus::UnknownOutcome || pre.fixed_policy.is_some()
1831 }));
1832 // attach batch trace before committing so even a
1833 // RunnerInvariantViolation keeps the observations
1834 if let Some(rt) = trace
1835 .rounds
1836 .last_mut()
1837 .filter(|rt| rt.round_id == RoundId(round))
1838 {
1839 rt.tool_batch = Some(ToolBatchTrace {
1840 calls: results
1841 .iter()
1842 .map(|pre| ToolCallTrace {
1843 call_id: pre.result.call_id.clone(),
1844 tool_name: tool_names
1845 .get(&pre.result.call_id)
1846 .cloned()
1847 .unwrap_or_default(),
1848 position: order_index
1849 .get(&pre.result.call_id)
1850 .copied()
1851 .unwrap_or_default(),
1852 status: pre.result.status.clone(),
1853 truncation: pre.result.output.truncation,
1854 artifact: pre.result.output.artifact.clone(),
1855 duration_ms: call_durations
1856 .get(&pre.result.call_id)
1857 .copied()
1858 .unwrap_or(0),
1859 })
1860 .collect(),
1861 completion_order,
1862 });
1863 }
1864 if let Err(e) =
1865 active.append_tool_results(results.iter().map(|pre| pre.result.clone()).collect())
1866 {
1867 return Err(TurnInterruption::RunnerInvariantViolation {
1868 reason: e.to_string(),
1869 });
1870 }
1871 // UnknownOutcome action: Stop interrupts after the real
1872 // result is committed, Continue proceeds to the next round — it
1873 // never re-runs the call, rewrites the result into a success, or
1874 // cancels sibling calls; parent should_stop is checked at the next
1875 // loop top.
1876 if let Some(uu) = results.iter().find(|pre| {
1877 pre.result.status == ToolResultStatus::UnknownOutcome
1878 && pre.fixed_policy == Some(UnknownOutcomePolicy::Stop)
1879 }) {
1880 return Err(TurnInterruption::UnsafeUnknownOutcome {
1881 call_id: uu.result.call_id.clone(),
1882 });
1883 }
1884 Ok(())
1885 }
1886}