use crate::budget::FramePolicy;
use crate::config::TurnRunOptions;
use crate::config::UnknownOutcomePolicy;
use crate::control::RunControl;
use crate::conversation::{ConversationError, ConversationState, SealedResult};
use crate::executor::ToolExecutor;
use crate::hook::UnknownDecision;
use crate::interaction::BatchDecision;
use causa_kernel::AttemptNumber;
use causa_kernel::ModelGateway;
use causa_kernel::ModelRequest;
use causa_kernel::ModelStopReason;
use causa_kernel::TextPayload;
use causa_kernel::ToolCallPayload;
use causa_kernel::ToolResultPayload;
use causa_kernel::{ArtifactRef, ToolCallId, ToolResultStatus, Truncation};
use causa_kernel::{AttemptControl, ModelUsage, StreamDelta};
use causa_kernel::{BlockContent, merged_frame};
use causa_kernel::{BlockId, ConversationId, FrameScope, InvocationId, RoundId};
use causa_kernel::{ModelInvokeError, ModelInvokeErrorKind, ModelOutput};
use causa_kernel::{TurnContext, TurnSnapshot};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::Instrument;
use crate::hook::{HookCtx, HookOutcome, PassthroughHook, ToolUseHook};
use futures_util::StreamExt;
fn millis_since(t: Instant) -> u64 {
t.elapsed().as_millis() as u64
}
pub(crate) fn unanswered_tool_calls(active: &TurnContext) -> Vec<ToolCallPayload> {
let mut pending: Vec<ToolCallPayload> = Vec::new();
for b in active.blocks() {
match &b.content {
BlockContent::ToolCall(c) => pending.push(c.clone()),
BlockContent::ToolResult(r) => pending.retain(|p| p.call_id != r.call_id),
_ => {}
}
}
pending
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", content = "detail")]
pub enum TurnInterruption {
ExplicitCancellation,
TurnDeadlineExceeded,
RetryExhausted {
last_kind: ModelInvokeErrorKind,
last_error: String,
},
InvalidModelOutput {
reason: String,
},
MaxModelRounds {
limit: u32,
},
MaxToolCalls {
limit: u32,
},
UnsafeUnknownOutcome {
call_id: ToolCallId,
},
CompactionFailed {
reason: String,
},
RunnerInvariantViolation {
reason: String,
},
ModelMaxTokens,
ModelRefusal,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AttemptTrace {
pub attempt: AttemptNumber,
pub kind: Option<ModelInvokeErrorKind>,
pub is_retryable: bool,
pub duration_ms: u64,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OutputSummary {
pub stop_reason: ModelStopReason,
pub usage: Option<causa_kernel::ModelUsage>,
pub tool_call_count: usize,
pub response_text_bytes: usize,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ToolCallTrace {
pub call_id: ToolCallId,
pub tool_name: String,
pub position: usize,
pub status: ToolResultStatus,
pub truncation: Truncation,
pub artifact: Option<ArtifactRef>,
pub duration_ms: u64,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ToolBatchTrace {
pub calls: Vec<ToolCallTrace>,
pub completion_order: Vec<ToolCallId>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ModelRoundTrace {
pub round_id: RoundId,
pub invocation_id: InvocationId,
pub frame_version: causa_kernel::ContextVersion,
pub attempts: Vec<AttemptTrace>,
pub output_summary: Option<OutputSummary>,
pub applied_block_ids: Vec<BlockId>,
pub tool_batch: Option<ToolBatchTrace>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TurnTrace {
pub rounds: Vec<ModelRoundTrace>,
pub tool_calls_total: usize,
pub total_duration_ms: u64,
}
impl TurnTrace {
pub fn new() -> Self {
Self {
rounds: vec![],
tool_calls_total: 0,
total_duration_ms: 0,
}
}
}
impl Default for TurnTrace {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum TurnResult {
Completed {
final_output: ModelOutput,
},
Interrupted {
cause: TurnInterruption,
},
Paused {
continuation: Continuation,
},
}
pub struct PreparedApproval {
pub awaiting: Vec<ToolCallPayload>,
pub rejected: Vec<ToolResultPayload>,
pub unknown_decisions: Vec<UnknownDecision>,
}
impl std::fmt::Debug for PreparedApproval {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PreparedApproval")
.field("awaiting", &self.awaiting.len())
.field("rejected", &self.rejected.len())
.field("unknown_decisions", &self.unknown_decisions.len())
.finish()
}
}
impl Clone for PreparedApproval {
fn clone(&self) -> Self {
Self {
awaiting: self.awaiting.clone(),
rejected: self.rejected.clone(),
unknown_decisions: self.unknown_decisions.clone(),
}
}
}
#[derive(serde::Serialize, serde::Deserialize)]
struct RejectedWire {
result: ToolResultPayload,
policy: UnknownOutcomePolicy,
}
impl serde::Serialize for PreparedApproval {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let rejected: Vec<RejectedWire> = self
.rejected
.iter()
.map(|result| RejectedWire {
result: result.clone(),
policy: if result.status == ToolResultStatus::UnknownOutcome {
self.unknown_decisions
.iter()
.find(|d| d.call_id == result.call_id)
.map(|d| d.policy)
.unwrap_or_default()
} else {
UnknownOutcomePolicy::Stop
},
})
.collect();
#[derive(serde::Serialize)]
struct Wire<'a> {
awaiting: &'a Vec<ToolCallPayload>,
rejected: Vec<RejectedWire>,
}
Wire {
awaiting: &self.awaiting,
rejected,
}
.serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for PreparedApproval {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(serde::Deserialize)]
struct Wire {
awaiting: Vec<ToolCallPayload>,
rejected: Vec<RejectedWire>,
}
let wire = Wire::deserialize(deserializer)?;
let mut rejected = Vec::with_capacity(wire.rejected.len());
let mut unknown_decisions: Vec<UnknownDecision> = Vec::new();
for entry in wire.rejected {
if entry.result.status == ToolResultStatus::UnknownOutcome {
unknown_decisions.push(UnknownDecision {
call_id: entry.result.call_id.clone(),
policy: entry.policy,
});
}
rejected.push(entry.result);
}
let unknown_ids: std::collections::HashSet<&ToolCallId> = rejected
.iter()
.filter(|r| r.status == ToolResultStatus::UnknownOutcome)
.map(|r| &r.call_id)
.collect();
let mut seen = std::collections::HashSet::new();
for d in &unknown_decisions {
if !unknown_ids.contains(&d.call_id) {
return Err(serde::de::Error::custom(format!(
"checkpoint decision for call {:?} does not match a saved UnknownOutcome result",
d.call_id.0
)));
}
if !seen.insert(&d.call_id) {
return Err(serde::de::Error::custom(format!(
"checkpoint has conflicting decisions for call {:?}",
d.call_id.0
)));
}
}
if seen.len() != unknown_ids.len() {
return Err(serde::de::Error::custom(
"checkpoint is missing the unknown-outcome decision for a saved result",
));
}
let mut ids = std::collections::HashSet::new();
for r in &rejected {
if !ids.insert(&r.call_id) {
return Err(serde::de::Error::custom(format!(
"checkpoint saves call {:?} twice",
r.call_id.0
)));
}
}
Ok(Self {
awaiting: wire.awaiting,
rejected,
unknown_decisions,
})
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", content = "detail", rename_all = "snake_case")]
pub enum PausePoint {
AwaitingApproval {
prepared: PreparedApproval,
deadline: Option<Duration>,
},
PausedForSteering,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Continuation {
pub pause_point: PausePoint,
pub round: u32,
pub accounted_tool_calls: usize,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub queued_inputs: Vec<TextPayload>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TurnOutcome {
#[serde(with = "causa_kernel::turn_context_as_snapshot")]
pub context: TurnContext,
pub result: TurnResult,
pub trace: TurnTrace,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConversationOutcome {
pub state: ConversationState,
pub result: TurnResult,
pub trace: TurnTrace,
}
#[derive(Clone, Copy)]
enum FrameSource<'a> {
Turn(&'a FramePolicy),
Conversation {
conversation_id: &'a ConversationId,
history: &'a [TurnSnapshot],
},
}
#[derive(Clone, Copy)]
pub(crate) enum ModelPhase {
Batch,
Stream,
}
pub(crate) struct ResumeState {
pub(crate) continuation: Continuation,
pub(crate) decision: Option<HookOutcome>,
pub(crate) inject: Vec<TextPayload>,
pub(crate) trace: TurnTrace,
}
enum BatchWork {
Execute(Vec<ToolCallPayload>),
Precomputed(Vec<PrecomputedResult>),
}
#[derive(Debug, Clone)]
struct PrecomputedResult {
result: ToolResultPayload,
fixed_policy: Option<UnknownOutcomePolicy>,
}
fn attach_decisions(
results: Vec<ToolResultPayload>,
decisions: &[UnknownDecision],
) -> Vec<PrecomputedResult> {
results
.into_iter()
.map(|result| PrecomputedResult {
fixed_policy: if result.status == ToolResultStatus::UnknownOutcome {
decisions
.iter()
.find(|d| d.call_id == result.call_id)
.map(|d| d.policy)
} else {
None
},
result,
})
.collect()
}
pub struct TurnRunner {
gateway: Arc<dyn ModelGateway>,
executor: Arc<ToolExecutor>,
hook: Arc<dyn ToolUseHook>,
}
impl TurnRunner {
pub fn new(gateway: Arc<dyn ModelGateway>, executor: Arc<ToolExecutor>) -> Self {
Self {
gateway,
executor,
hook: Arc::new(PassthroughHook),
}
}
pub fn with_hook(
gateway: Arc<dyn ModelGateway>,
executor: Arc<ToolExecutor>,
hook: Arc<dyn ToolUseHook>,
) -> Self {
Self {
gateway,
executor,
hook,
}
}
pub async fn run(
&self,
context: TurnContext,
options: TurnRunOptions,
ctrl: RunControl,
) -> TurnOutcome {
let span = tracing::info_span!(
"agent.turn",
turn_id = %context.turn_id().0,
scope = "turn"
);
self.run_inner(context, options, ctrl, ModelPhase::Batch)
.instrument(span)
.await
}
async fn run_inner(
&self,
mut context: TurnContext,
options: TurnRunOptions,
ctrl: RunControl,
phase: ModelPhase,
) -> TurnOutcome {
let start = Instant::now();
let (result, mut trace, tool_calls_total) = self
.drive(
&mut context,
FrameSource::Turn(&options.frame),
&options,
&ctrl,
phase,
)
.await;
trace.tool_calls_total = tool_calls_total;
trace.total_duration_ms = millis_since(start);
if !matches!(result, TurnResult::Paused { .. }) {
context.seal();
}
TurnOutcome {
context,
result,
trace,
}
}
pub async fn run_streaming(
&self,
context: TurnContext,
options: TurnRunOptions,
ctrl: RunControl,
) -> TurnOutcome {
let span = tracing::info_span!(
"agent.turn",
turn_id = %context.turn_id().0,
scope = "turn.streaming"
);
self.run_inner(context, options, ctrl, ModelPhase::Stream)
.instrument(span)
.await
}
pub async fn run_in_conversation(
&self,
state: ConversationState,
options: TurnRunOptions,
ctrl: RunControl,
) -> Result<ConversationOutcome, ConversationError> {
self.drive_conversation(state, options, ctrl, ModelPhase::Batch, None)
.await
}
pub async fn run_in_conversation_streaming(
&self,
state: ConversationState,
options: TurnRunOptions,
ctrl: RunControl,
) -> Result<ConversationOutcome, ConversationError> {
self.drive_conversation(state, options, ctrl, ModelPhase::Stream, None)
.await
}
pub(crate) async fn resume_conversation(
&self,
state: ConversationState,
options: TurnRunOptions,
ctrl: RunControl,
resume: ResumeState,
) -> Result<ConversationOutcome, ConversationError> {
self.drive_conversation(state, options, ctrl, ModelPhase::Batch, Some(resume))
.await
}
#[allow(clippy::result_large_err)]
pub async fn resume(
&self,
outcome: TurnOutcome,
request: crate::resume::ResumeRequest,
options: TurnRunOptions,
ctrl: RunControl,
) -> Result<TurnOutcome, crate::resume::ResumeRejection<TurnOutcome>> {
if let Err(reason) =
crate::resume::validate_resume(&outcome.result, &outcome.context, &request)
{
return Err(crate::resume::ResumeRejection { reason, outcome });
}
let TurnResult::Paused { continuation } = outcome.result else {
unreachable!("validated above");
};
let TurnOutcome {
mut context, trace, ..
} = outcome;
let start = Instant::now();
let (result, mut trace, tool_calls_total) = self
.drive_from(
&mut context,
FrameSource::Turn(&options.frame),
&options,
&ctrl,
ModelPhase::Batch,
Some(ResumeState {
continuation,
decision: request.decision,
inject: request.inject,
trace,
}),
)
.await;
trace.tool_calls_total = tool_calls_total;
trace.total_duration_ms = millis_since(start);
if !matches!(result, TurnResult::Paused { .. }) {
context.seal();
}
Ok(TurnOutcome {
context,
result,
trace,
})
}
async fn drive_conversation(
&self,
state: ConversationState,
options: TurnRunOptions,
ctrl: RunControl,
phase: ModelPhase,
resume: Option<ResumeState>,
) -> Result<ConversationOutcome, ConversationError> {
let scope = if resume.is_some() {
"conversation.resume"
} else if matches!(phase, ModelPhase::Stream) {
"conversation.streaming"
} else {
"conversation"
};
let turn_id = state
.active_turn()
.map(|t| t.turn_id().0)
.unwrap_or_default();
let span = tracing::info_span!(
"agent.turn",
turn_id = %turn_id,
conversation_id = %state.conversation_id().0,
scope = scope,
);
self.drive_conversation_inner(state, options, ctrl, phase, resume)
.instrument(span)
.await
}
async fn drive_conversation_inner(
&self,
mut state: ConversationState,
options: TurnRunOptions,
ctrl: RunControl,
phase: ModelPhase,
resume: Option<ResumeState>,
) -> Result<ConversationOutcome, ConversationError> {
let active_id = match state.active_turn() {
Some(t) => t.turn_id(),
None => return Err(ConversationError::NoActiveTurn),
};
if state.active_turn().expect("checked above").is_sealed() {
return Err(ConversationError::TurnAlreadySealed);
}
if resume.is_none() && state.sealed_result() == Some(SealedResult::Paused) {
return Err(ConversationError::TurnAlreadyActive);
}
let (conversation_id, history, active) = state.runner_parts();
let active = active.expect("NoActiveTurn checked above");
let start = Instant::now();
let (result, mut trace, tool_calls_total) = self
.drive_from(
active,
FrameSource::Conversation {
conversation_id,
history: &history,
},
&options,
&ctrl,
phase,
resume,
)
.await;
trace.tool_calls_total = tool_calls_total;
trace.total_duration_ms = millis_since(start);
let stamp = match &result {
TurnResult::Completed { .. } => SealedResult::Completed,
TurnResult::Interrupted { .. } => SealedResult::Interrupted,
TurnResult::Paused { .. } => SealedResult::Paused,
};
state
.seal_turn(active_id, stamp)
.expect("active turn still present");
Ok(ConversationOutcome {
state,
result,
trace,
})
}
async fn stream_attempt(
&self,
req: &ModelRequest,
attempt_ctrl: &AttemptControl,
options: &TurnRunOptions,
round_id: RoundId,
) -> Result<ModelOutput, ModelInvokeError> {
use futures_util::StreamExt;
let mut stream = self.gateway.stream(req, attempt_ctrl).await?;
let mut usage_seen: Option<ModelUsage> = None;
loop {
let item = tokio::select! {
biased;
_ = attempt_ctrl.cancellation_token().cancelled() => {
return Err(ModelInvokeError::new(
ModelInvokeErrorKind::Cancelled,
"cancelled during stream",
));
}
next = stream.next() => match next {
Some(item) => item,
None => {
return Err(ModelInvokeError::new(
ModelInvokeErrorKind::UnknownOutcome,
"stream ended without Done",
));
}
},
};
options.interaction.on_delta(round_id, &item).await;
match item {
StreamDelta::Done { final_output, .. } => {
let mut out = final_output;
if out.usage.is_none() {
out.usage = usage_seen;
}
return Ok(out);
}
StreamDelta::Usage(u) => usage_seen = Some(u),
StreamDelta::Error { kind, message } => {
return Err(ModelInvokeError::new(kind, message));
}
StreamDelta::TextDelta { .. }
| StreamDelta::ReasoningDelta { .. }
| StreamDelta::ToolCallDelta { .. } => {}
}
}
}
async fn drive(
&self,
active: &mut TurnContext,
frames: FrameSource<'_>,
options: &TurnRunOptions,
ctrl: &RunControl,
phase: ModelPhase,
) -> (TurnResult, TurnTrace, usize) {
self.drive_from(active, frames, options, ctrl, phase, None)
.await
}
async fn drive_from(
&self,
active: &mut TurnContext,
frames: FrameSource<'_>,
options: &TurnRunOptions,
ctrl: &RunControl,
phase: ModelPhase,
resume: Option<ResumeState>,
) -> (TurnResult, TurnTrace, usize) {
let mut round: u32;
let mut tool_calls_total: usize;
let mut trace: TurnTrace;
let mut pending_inject: Vec<TextPayload>;
match resume {
None => {
round = 0;
tool_calls_total = 0;
trace = TurnTrace::new();
pending_inject = Vec::new();
}
Some(r) => {
let ResumeState {
continuation,
decision,
inject,
trace: resumed_trace,
} = r;
let Continuation {
pause_point,
round: paused_round,
accounted_tool_calls,
queued_inputs,
} = continuation;
round = paused_round;
tool_calls_total = accounted_tool_calls;
trace = resumed_trace;
pending_inject = queued_inputs;
pending_inject.extend(inject);
if ctrl.should_stop() {
let cause = if ctrl.is_cancelled() {
TurnInterruption::ExplicitCancellation
} else {
TurnInterruption::TurnDeadlineExceeded
};
return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
}
if tool_calls_total as u64 > options.policy.limits.max_tool_calls as u64 {
return (
TurnResult::Interrupted {
cause: TurnInterruption::MaxToolCalls {
limit: options.policy.limits.max_tool_calls,
},
},
trace,
tool_calls_total,
);
}
if matches!(pause_point, PausePoint::AwaitingApproval { .. })
&& round >= options.policy.limits.max_model_rounds
{
return (
TurnResult::Interrupted {
cause: TurnInterruption::MaxModelRounds {
limit: options.policy.limits.max_model_rounds,
},
},
trace,
tool_calls_total,
);
}
if let Some(decision) = decision {
let PausePoint::AwaitingApproval {
prepared,
deadline: _,
} = pause_point
else {
unreachable!("entry validation pairs a decision with an approval pause");
};
let draft = unanswered_tool_calls(active);
let PreparedApproval {
rejected: saved_rejected,
unknown_decisions: saved_decisions,
..
} = prepared;
let mut rejected: Vec<PrecomputedResult> = saved_rejected
.into_iter()
.map(|result| PrecomputedResult {
fixed_policy: saved_decisions
.iter()
.find(|d| d.call_id == result.call_id)
.map(|d| d.policy),
result,
})
.collect();
rejected.extend(attach_decisions(
decision.rejected,
&decision.unknown_decisions,
));
if let Err(cause) = self
.run_batch(
active,
&draft,
BatchWork::Execute(decision.to_execute),
rejected,
options,
ctrl,
round,
&mut trace,
)
.await
{
return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
}
round += 1;
}
}
}
let first_model_round = round;
loop {
if !pending_inject.is_empty() {
for text in std::mem::take(&mut pending_inject) {
if let Err(e) = active.append_input(text, "user.steering") {
return (
TurnResult::Interrupted {
cause: TurnInterruption::RunnerInvariantViolation {
reason: e.to_string(),
},
},
trace,
tool_calls_total,
);
}
}
}
for text in options.interaction.pending_inputs().await {
if let Err(e) = active.append_input(text, "user.steering") {
return (
TurnResult::Interrupted {
cause: TurnInterruption::RunnerInvariantViolation {
reason: e.to_string(),
},
},
trace,
tool_calls_total,
);
}
}
if ctrl.should_stop() {
let cause = if ctrl.is_cancelled() {
TurnInterruption::ExplicitCancellation
} else {
TurnInterruption::TurnDeadlineExceeded
};
return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
}
if round >= options.policy.limits.max_model_rounds {
return (
TurnResult::Interrupted {
cause: TurnInterruption::MaxModelRounds {
limit: options.policy.limits.max_model_rounds,
},
},
trace,
tool_calls_total,
);
}
let frame = match frames {
FrameSource::Turn(policy) => {
match policy.materialize(active, RoundId(round)).await {
Ok(f) => f,
Err(e) => {
return (
TurnResult::Interrupted {
cause: TurnInterruption::CompactionFailed {
reason: e.to_string(),
},
},
trace,
tool_calls_total,
);
}
}
}
FrameSource::Conversation {
conversation_id,
history,
} => merged_frame(conversation_id, history, active, RoundId(round)),
};
let frame_version = match &frame.scope {
FrameScope::Turn { source_version, .. }
| FrameScope::Conversation { source_version, .. } => *source_version,
};
let invocation = InvocationId {
turn_id: active.turn_id(),
round_id: RoundId(round),
};
let round_surface = if round == first_model_round {
options.invocation.tool_surface.clone()
} else {
self.executor.tool_surface().await
};
let round_span = tracing::debug_span!(
"agent.round",
turn_id = %invocation.turn_id.0,
round_id = round
);
let (attempts, output) = async {
let mut attempt: u32 = 1;
let mut attempts: Vec<AttemptTrace> = Vec::new();
let output: Result<ModelOutput, ModelInvokeError> = loop {
let attempt_started = Instant::now();
let attempt_ctrl = ctrl.for_attempt(options.policy.attempt_timeout);
let req = ModelRequest {
invocation_id: invocation.clone(),
attempt: AttemptNumber(attempt),
frame: frame.clone(),
model: options.invocation.model.clone(),
tool_surface: round_surface.clone(),
generation: options.invocation.generation.clone(),
cache: options.invocation.cache,
};
let attempt_span = tracing::debug_span!(
"agent.attempt",
attempt = attempt,
model = %options.invocation.model.0
);
let result = match phase {
ModelPhase::Batch => {
self.gateway
.invoke(&req, &attempt_ctrl)
.instrument(attempt_span)
.await
}
ModelPhase::Stream => {
self.stream_attempt(&req, &attempt_ctrl, options, RoundId(round))
.instrument(attempt_span)
.await
}
};
match result {
Ok(out) => {
attempts.push(AttemptTrace {
attempt: AttemptNumber(attempt),
kind: None,
is_retryable: false,
duration_ms: millis_since(attempt_started),
});
break Ok(out);
}
Err(e) => {
let retryable = options.policy.retry.allows(&e.kind);
attempts.push(AttemptTrace {
attempt: AttemptNumber(attempt),
kind: Some(e.kind.clone()),
is_retryable: retryable,
duration_ms: millis_since(attempt_started),
});
if retryable && attempt <= options.policy.retry.max_retries {
let delay = options.policy.retry.backoff_delay(attempt + 1);
let capped = ctrl
.remaining_turn_time()
.map_or(delay, |remaining| delay.min(remaining));
if !capped.is_zero() {
tokio::select! {
biased;
_ = attempt_ctrl.cancellation_token().cancelled() => {
break Err(ModelInvokeError::new(
ModelInvokeErrorKind::Cancelled,
"cancelled during retry backoff",
));
}
_ = tokio::time::sleep(capped) => {}
}
}
if ctrl.should_stop() {
if ctrl.is_cancelled() {
break Err(ModelInvokeError::new(
ModelInvokeErrorKind::Cancelled,
"cancelled during retry backoff",
));
}
break Err(ModelInvokeError::new(
ModelInvokeErrorKind::TimedOut,
"turn deadline passed during retry backoff",
));
}
attempt += 1;
continue;
}
break Err(e);
}
}
};
(attempts, output)
}
.instrument(round_span)
.await;
let output = match output {
Ok(o) => o,
Err(e) => {
let cause = if matches!(e.kind, ModelInvokeErrorKind::Cancelled)
&& ctrl.is_cancelled()
{
TurnInterruption::ExplicitCancellation
} else if ctrl.should_stop() && !ctrl.is_cancelled() {
TurnInterruption::TurnDeadlineExceeded
} else {
TurnInterruption::RetryExhausted {
last_kind: e.kind.clone(),
last_error: e.message.clone(),
}
};
trace.rounds.push(ModelRoundTrace {
round_id: RoundId(round),
invocation_id: invocation,
frame_version,
attempts,
output_summary: None,
applied_block_ids: vec![],
tool_batch: None,
});
return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
}
};
let output_summary = Some(OutputSummary {
stop_reason: output.stop_reason,
usage: output.usage.clone(),
tool_call_count: output.response.tool_calls.len(),
response_text_bytes: output.response.text.0.len(),
});
trace.rounds.push(ModelRoundTrace {
round_id: RoundId(round),
invocation_id: invocation.clone(),
frame_version,
attempts,
output_summary,
applied_block_ids: vec![],
tool_batch: None,
});
if matches!(
output.stop_reason,
ModelStopReason::MaxTokens | ModelStopReason::Refusal
) {
let cause = if matches!(output.stop_reason, ModelStopReason::MaxTokens) {
TurnInterruption::ModelMaxTokens
} else {
TurnInterruption::ModelRefusal
};
return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
}
let applied = match active.append_model_output(
invocation.clone(),
&output.response,
output.stop_reason,
) {
Ok(a) => a,
Err(e) => {
return (
TurnResult::Interrupted {
cause: TurnInterruption::InvalidModelOutput {
reason: e.to_string(),
},
},
trace,
tool_calls_total,
);
}
};
let call_payloads: Vec<ToolCallPayload> = applied.tool_calls;
trace
.rounds
.last_mut()
.expect("round trace just pushed")
.applied_block_ids = applied.block_ids.clone();
match output.stop_reason {
ModelStopReason::EndTurn => {
return (
TurnResult::Completed {
final_output: output,
},
trace,
tool_calls_total,
);
}
ModelStopReason::ToolUse => {
tool_calls_total += call_payloads.len();
if tool_calls_total as u32 > options.policy.limits.max_tool_calls {
return (
TurnResult::Interrupted {
cause: TurnInterruption::MaxToolCalls {
limit: options.policy.limits.max_tool_calls,
},
},
trace,
tool_calls_total,
);
}
let (hook_to_exec, hook_rejected, hook_decisions): (
Vec<ToolCallPayload>,
Vec<ToolResultPayload>,
Vec<UnknownDecision>,
) = {
let call_control = ctrl
.for_attempt(options.policy.attempt_timeout)
.for_call(options.execution.call_timeout);
let conversation_id = match &frames {
FrameSource::Conversation {
conversation_id, ..
} => Some(*conversation_id),
FrameSource::Turn(_) => None,
};
let hook_ctx = HookCtx {
turn_id: &active.turn_id(),
conversation_id,
round_id: RoundId(round),
control: &call_control,
};
let outcome = self.hook.apply(call_payloads.clone(), &hook_ctx).await;
(
outcome.to_execute,
outcome.rejected,
outcome.unknown_decisions,
)
};
let decision = options.interaction.decide_batch(&hook_to_exec).await;
match decision {
BatchDecision::Pause { deadline } => {
let draft_names: HashMap<ToolCallId, String> = call_payloads
.iter()
.map(|p| (p.call_id.clone(), p.tool_name.clone()))
.collect();
let unknown_decisions = hook_rejected
.iter()
.filter(|r| r.status == ToolResultStatus::UnknownOutcome)
.map(|r| UnknownDecision {
call_id: r.call_id.clone(),
policy: hook_decisions
.iter()
.find(|d| d.call_id == r.call_id)
.map(|d| d.policy)
.unwrap_or_else(|| {
options.policy.unknown_outcome.resolve(
draft_names
.get(&r.call_id)
.map(String::as_str)
.unwrap_or(""),
)
}),
})
.collect();
return (
TurnResult::Paused {
continuation: Continuation {
pause_point: PausePoint::AwaitingApproval {
prepared: PreparedApproval {
awaiting: hook_to_exec,
rejected: hook_rejected,
unknown_decisions,
},
deadline,
},
round,
accounted_tool_calls: tool_calls_total,
queued_inputs: Vec::new(),
},
},
trace,
tool_calls_total,
);
}
BatchDecision::Proceed => {
if let Err(cause) = self
.run_batch(
active,
&call_payloads,
BatchWork::Execute(hook_to_exec),
attach_decisions(hook_rejected, &hook_decisions),
options,
ctrl,
round,
&mut trace,
)
.await
{
return (
TurnResult::Interrupted { cause },
trace,
tool_calls_total,
);
}
}
BatchDecision::Rewrite(rewritten) => {
if let Err(cause) = self
.run_batch(
active,
&call_payloads,
BatchWork::Execute(rewritten),
attach_decisions(hook_rejected, &hook_decisions),
options,
ctrl,
round,
&mut trace,
)
.await
{
return (
TurnResult::Interrupted { cause },
trace,
tool_calls_total,
);
}
}
BatchDecision::Reject {
results,
unknown_decisions,
} => {
if let Err(cause) = self
.run_batch(
active,
&call_payloads,
BatchWork::Precomputed(attach_decisions(
results,
&unknown_decisions,
)),
attach_decisions(hook_rejected, &hook_decisions),
options,
ctrl,
round,
&mut trace,
)
.await
{
return (
TurnResult::Interrupted { cause },
trace,
tool_calls_total,
);
}
}
}
round += 1;
}
ModelStopReason::MaxTokens | ModelStopReason::Refusal => {
unreachable!("handled before append_model_output")
}
}
}
}
#[allow(clippy::too_many_arguments)]
async fn run_batch(
&self,
active: &mut TurnContext,
draft_order: &[ToolCallPayload],
work: BatchWork,
mut rejected: Vec<PrecomputedResult>,
options: &TurnRunOptions,
ctrl: &RunControl,
round: u32,
trace: &mut TurnTrace,
) -> Result<(), TurnInterruption> {
let expected: HashSet<ToolCallId> = draft_order.iter().map(|p| p.call_id.clone()).collect();
let mut covered: HashSet<ToolCallId> = HashSet::new();
let work_ids: Vec<&ToolCallId> = match &work {
BatchWork::Execute(payloads) => payloads.iter().map(|p| &p.call_id).collect(),
BatchWork::Precomputed(pre) => pre.iter().map(|o| &o.result.call_id).collect(),
};
for call_id in work_ids
.into_iter()
.chain(rejected.iter().map(|o| &o.result.call_id))
{
if !expected.contains(call_id) {
return Err(TurnInterruption::RunnerInvariantViolation {
reason: format!(
"batch decision covers call {:?} which the model did not emit",
call_id.0
),
});
}
if !covered.insert(call_id.clone()) {
return Err(TurnInterruption::RunnerInvariantViolation {
reason: format!("batch decision covers call {:?} more than once", call_id.0),
});
}
}
if covered.len() != expected.len() {
let missing: Vec<String> = expected
.difference(&covered)
.map(|id| id.0.clone())
.collect();
return Err(TurnInterruption::RunnerInvariantViolation {
reason: format!(
"batch decision does not cover every emitted call: missing {missing:?}"
),
});
}
let (mut results, completion_order, call_durations): (
Vec<PrecomputedResult>,
Vec<ToolCallId>,
HashMap<ToolCallId, u64>,
) = match work {
BatchWork::Execute(to_exec) => {
let futs = to_exec.into_iter().map(|payload| {
let unknown_outcome = options.policy.unknown_outcome.clone();
let cc = ctrl
.for_attempt(options.policy.attempt_timeout)
.for_call(options.execution.call_timeout);
let store = options.execution.artifact_store.clone();
let tc = options.execution.token_counter.clone();
let limits = options
.execution
.tool_output_limits_overrides
.get(&payload.tool_name)
.copied()
.unwrap_or(options.execution.tool_output_limits);
let name = payload.tool_name.clone();
let exec = self.executor.clone();
async move {
let t0 = Instant::now();
let result = exec
.execute_with_limits(payload, cc, store, tc, limits)
.await;
let fixed_policy = if result.status == ToolResultStatus::UnknownOutcome {
Some(unknown_outcome.resolve(&name))
} else {
None
};
(
PrecomputedResult {
result,
fixed_policy,
},
millis_since(t0),
)
}
});
let mut stream = futures_util::stream::FuturesUnordered::from_iter(futs);
let mut results = Vec::with_capacity(stream.len());
let mut completion_order = Vec::with_capacity(stream.len());
let mut call_durations: HashMap<ToolCallId, u64> = HashMap::new();
while let Some((pre, duration_ms)) = stream.next().await {
completion_order.push(pre.result.call_id.clone());
call_durations.insert(pre.result.call_id.clone(), duration_ms);
results.push(pre);
}
(results, completion_order, call_durations)
}
BatchWork::Precomputed(precomputed) => (
precomputed,
Vec::new(), HashMap::new(),
),
};
results.append(&mut rejected);
if let Some(foreign) = results
.iter()
.find(|r| !expected.contains(&r.result.call_id))
{
return Err(TurnInterruption::RunnerInvariantViolation {
reason: format!(
"tool outcome answers foreign call {:?}",
foreign.result.call_id.0
),
});
}
let order_index: HashMap<ToolCallId, usize> = draft_order
.iter()
.enumerate()
.map(|(i, p)| (p.call_id.clone(), i))
.collect();
results.sort_by_key(|r| order_index.get(&r.result.call_id).copied());
let tool_names: HashMap<ToolCallId, String> = draft_order
.iter()
.map(|p| (p.call_id.clone(), p.tool_name.clone()))
.collect();
for pre in &mut results {
if pre.result.status == ToolResultStatus::UnknownOutcome && pre.fixed_policy.is_none() {
pre.fixed_policy = Some(
options.policy.unknown_outcome.resolve(
tool_names
.get(&pre.result.call_id)
.map(String::as_str)
.unwrap_or(""),
),
);
}
}
debug_assert!(results.iter().all(|pre| {
pre.result.status != ToolResultStatus::UnknownOutcome || pre.fixed_policy.is_some()
}));
if let Some(rt) = trace
.rounds
.last_mut()
.filter(|rt| rt.round_id == RoundId(round))
{
rt.tool_batch = Some(ToolBatchTrace {
calls: results
.iter()
.map(|pre| ToolCallTrace {
call_id: pre.result.call_id.clone(),
tool_name: tool_names
.get(&pre.result.call_id)
.cloned()
.unwrap_or_default(),
position: order_index
.get(&pre.result.call_id)
.copied()
.unwrap_or_default(),
status: pre.result.status.clone(),
truncation: pre.result.output.truncation,
artifact: pre.result.output.artifact.clone(),
duration_ms: call_durations
.get(&pre.result.call_id)
.copied()
.unwrap_or(0),
})
.collect(),
completion_order,
});
}
if let Err(e) =
active.append_tool_results(results.iter().map(|pre| pre.result.clone()).collect())
{
return Err(TurnInterruption::RunnerInvariantViolation {
reason: e.to_string(),
});
}
if let Some(uu) = results.iter().find(|pre| {
pre.result.status == ToolResultStatus::UnknownOutcome
&& pre.fixed_policy == Some(UnknownOutcomePolicy::Stop)
}) {
return Err(TurnInterruption::UnsafeUnknownOutcome {
call_id: uu.result.call_id.clone(),
});
}
Ok(())
}
}