trusty_code/agent_loop/mod.rs
1//! Multi-turn agent loop: drive an LLM through tool calls until it stops.
2//!
3//! Why: A single chat call cannot accomplish a task that requires reading files,
4//! running tools, and reacting to results. The agent loop is the control
5//! structure that repeatedly calls the model, dispatches any requested tool
6//! calls through the gated registry, feeds results back, and iterates until the
7//! model produces a final answer — bounded by a turn cap, a wall-clock timeout,
8//! and token-usage accounting so runs stay cheap and observable.
9//! What: Exposes `AgentLoop`, `AgentLoopConfig`, `AgentLoopError`, and (#2056)
10//! `ToolEventSink`. `run` seeds a `Transcript`, then loops: build a
11//! `ChatRequest` from the running history + registry schemas, call
12//! `LlmClientTrait::chat`, accrue usage into a `PerfCollector`, append the
13//! assistant turn, and — if there are tool calls — dispatch each via
14//! `ToolRegistry::dispatch_gated` (notifying the optional sink around each
15//! dispatch) and append the results. Exits with `AgentOutput` in either of two
16//! ways: the first assistant turn that has NO tool calls (the D3 no-tool-call
17//! finish convention, preserved unchanged as the fallback), or (#2072) an
18//! explicit, successfully-validated `finish_task` tool call, whose structured
19//! `status`/`summary`/`changes`/test-count fields become the final
20//! `AgentOutput` via `build_finish_output`. Aborts with a partial output when
21//! the turn cap, timeout, (#2056) an external cancellation flag, or (#2265
22//! fix #5) an external stop signal fires.
23//! What: The whole `chat → dispatch → iterate` body runs inside a single
24//! `tokio::time::timeout` so a stalled model or hung tool cannot block forever.
25//! Test: `agent_loop::tests` — stubbed two-turn flow, turn-cap abort, recoverable
26//! tool-error continuation, usage accrual, sink notification order, cancellation,
27//! plus an `#[ignore]`-gated live test.
28
29mod compaction;
30mod error;
31mod sink;
32mod transcript;
33
34#[cfg(test)]
35mod tests;
36
37use std::sync::Arc;
38use std::sync::atomic::{AtomicBool, Ordering};
39use std::time::Duration;
40
41use serde_json::Value;
42
43use crate::llm::{
44 CacheControl, ChatMessage, ChatRequest, ChatResponse, LlmClientTrait, RequestUsageConfig,
45 ToolCall, ToolCallExtractError, ToolCallExtractor, ToolDefinition,
46};
47use crate::mode::HarnessMode;
48use crate::perf::PerfCollector;
49use crate::tools::{AgentOutput, FINISH_TASK_TOOL_NAME, FinishTaskArgs, ToolRegistry, ToolResult};
50
51pub use compaction::CompactionConfig;
52// (#2260) Crate-internal re-export so `llm::bedrock::cache` can reuse the
53// same chars/4 token-estimate heuristic for its cachePoint min-size guard
54// instead of duplicating it.
55pub(crate) use compaction::estimate_tokens;
56pub use error::AgentLoopError;
57pub use sink::ToolEventSink;
58pub use transcript::Transcript;
59
60/// Phase name used when accruing token usage into the `PerfCollector`.
61const PERF_PHASE: &str = "agent_loop";
62
63/// Workflow label used to construct the loop's `PerfCollector`.
64const PERF_WORKFLOW: &str = "agent_loop";
65
66/// Tuning knobs for a single agent-loop run.
67///
68/// Why: The three limits (turn cap, wall-clock timeout, model) are the dials a
69/// caller most often needs to vary per task; grouping them keeps the `AgentLoop`
70/// constructor signature stable as more knobs are added later.
71/// What: `max_turns` bounds LLM round-trips; `timeout_secs` bounds total
72/// wall-clock time; `model` is the OpenRouter slug sent on every request.
73/// `mode` (#2059) is the resolved `HarnessMode` for this run — the branch
74/// point `tool_definitions` uses; defaults to `HarnessMode::default()`
75/// (`DailyDriver`) so every pre-#2059 call site that doesn't set it
76/// unchanged.
77/// Test: `agent_loop::tests::config_defaults_are_sane`.
78#[derive(Debug, Clone)]
79pub struct AgentLoopConfig {
80 /// Maximum number of LLM round-trips before aborting with a partial result.
81 pub max_turns: u32,
82
83 /// Wall-clock budget for the entire run, in seconds.
84 pub timeout_secs: u64,
85
86 /// OpenRouter model slug sent on every chat request.
87 pub model: String,
88
89 /// Per-turn completion-token cap sent as `ChatRequest.max_tokens`.
90 ///
91 /// Why: A single hard-coded cap starves any turn that must emit more than
92 /// its value — e.g. `write_file` on a real source file — silently
93 /// truncating output until the loop churns out its turn budget. Callers
94 /// must resolve this from the agent's own `[llm].max_tokens` (via
95 /// `crate::provider::resolve_max_tokens`) rather than relying on the
96 /// default below.
97 /// What: Sent verbatim as `Some(self.max_tokens)` on every `ChatRequest`
98 /// built by `AgentLoop::build_request`.
99 pub max_tokens: u32,
100
101 /// The resolved harness mode for this run (#2059). See
102 /// `Self::tool_definitions`' docs for the branch point this feeds.
103 pub mode: HarnessMode,
104
105 /// Non-destructive context compaction tuning (#2070, §5.4). Only
106 /// consulted when `mode == HarnessMode::DailyDriver` — see
107 /// `Self::maybe_compact_transcript`'s docs for why Parity must never
108 /// compact.
109 pub compaction: CompactionConfig,
110}
111
112impl Default for AgentLoopConfig {
113 /// Sensible defaults for an interactive agent run.
114 ///
115 /// Why: Most callers want a bounded but generous loop; defaults avoid
116 /// boilerplate at every construction site. `max_tokens` defaults to
117 /// `crate::provider::DEFAULT_MAX_TOKENS` — callers that need the agent's
118 /// configured `[llm].max_tokens` must set this field explicitly via
119 /// `crate::provider::resolve_max_tokens`; this default is only the
120 /// generous fallback for when no agent config is consulted.
121 /// What: 8 turns, 120s timeout, `openai/gpt-4o-mini`,
122 /// `DEFAULT_MAX_TOKENS`, `HarnessMode::default()`, `CompactionConfig::default()`.
123 /// Test: `config_defaults_are_sane`.
124 fn default() -> Self {
125 Self {
126 max_turns: 8,
127 timeout_secs: 120,
128 model: "openai/gpt-4o-mini".to_string(),
129 max_tokens: crate::provider::DEFAULT_MAX_TOKENS,
130 mode: HarnessMode::default(),
131 compaction: CompactionConfig::default(),
132 }
133 }
134}
135
136/// Drives an LLM through a bounded multi-turn tool-calling conversation.
137///
138/// Why: Encapsulates the repetitive, error-prone control flow (call → extract
139/// tool calls → dispatch → append → repeat) behind one `run` method so call
140/// sites express intent ("run this task") not mechanics.
141/// What: Holds the config, an `Arc<dyn LlmClientTrait>` (mockable in tests), an
142/// `Arc<ToolRegistry>` whose schemas are advertised and whose `dispatch_gated`
143/// executes tool calls, and three OPTIONAL collaborators set via builder
144/// methods after construction: (#2056) a `sink` notified around every tool
145/// dispatch, (#2056) a `cancel` flag checked once per turn boundary, and
146/// (#2265 fix #5) a `stop_signal` closure checked at that SAME turn boundary.
147/// All three default to `None`, so every existing call site (`run_task`,
148/// `runner::in_process`) is unaffected.
149/// Test: `agent_loop::tests::*`.
150pub struct AgentLoop {
151 config: AgentLoopConfig,
152 llm: Arc<dyn LlmClientTrait>,
153 registry: Arc<ToolRegistry>,
154 sink: Option<Arc<dyn ToolEventSink>>,
155 cancel: Option<Arc<AtomicBool>>,
156 stop_signal: Option<Arc<dyn Fn() -> bool + Send + Sync>>,
157}
158
159impl AgentLoop {
160 /// Construct an agent loop from its three core collaborators.
161 ///
162 /// Why: Constructor injection keeps the loop testable — production passes a
163 /// real `LlmClient`, tests pass a scripted mock, both as
164 /// `Arc<dyn LlmClientTrait>`.
165 /// What: Stores the config, LLM client, and tool registry; `sink`/`cancel`/
166 /// `stop_signal` start `None` — attach them via
167 /// [`Self::with_tool_event_sink`]/[`Self::with_cancel_flag`]/
168 /// [`Self::with_stop_signal`] when the caller needs them (#2056's
169 /// daemon-driven task execution attaches the first two; `run_task`'s PM
170 /// loop attaches `stop_signal` (#2265 fix #5); the delegated engineer's
171 /// own loop attaches none of them).
172 /// Test: `agent_loop::tests::two_turn_flow_completes`.
173 pub fn new(
174 config: AgentLoopConfig,
175 llm: Arc<dyn LlmClientTrait>,
176 registry: Arc<ToolRegistry>,
177 ) -> Self {
178 Self {
179 config,
180 llm,
181 registry,
182 sink: None,
183 cancel: None,
184 stop_signal: None,
185 }
186 }
187
188 /// Attach a [`ToolEventSink`] notified around every tool dispatch (#2056).
189 ///
190 /// Why: Lets a daemon-driven run make its tool activity observable to a
191 /// `session.attach`ed client without forking the dispatch loop.
192 /// What: Builder-style setter; returns `self` for chaining.
193 /// Test: `agent_loop::tests::sink_receives_started_then_finished_in_order`.
194 pub fn with_tool_event_sink(mut self, sink: Arc<dyn ToolEventSink>) -> Self {
195 self.sink = Some(sink);
196 self
197 }
198
199 /// Attach a cancellation flag checked once per turn boundary (#2056).
200 ///
201 /// Why: `session.cancel` on an in-flight daemon-driven run must stop the
202 /// loop cooperatively; sharing one `Arc<AtomicBool>` between the caller and
203 /// every loop it spawns (PM + any delegated sub-agent loops) is the
204 /// cheapest possible cancellation signal.
205 /// What: Builder-style setter; returns `self` for chaining. The flag is
206 /// checked with `Ordering::Relaxed` — only "has it been set at all" matters,
207 /// not fine-grained memory ordering with other state.
208 /// Test: `agent_loop::tests::cancel_flag_aborts_before_next_turn`.
209 pub fn with_cancel_flag(mut self, cancel: Arc<AtomicBool>) -> Self {
210 self.cancel = Some(cancel);
211 self
212 }
213
214 /// Attach an external stop condition checked once per turn boundary
215 /// (#2265 fix #5).
216 ///
217 /// Why: Some callers know, independently of this loop's own turn/timeout
218 /// budget, that a shared external condition has made further turns
219 /// pointless — `run_task`'s PM loop is the motivating case: once its
220 /// shared `redelegation::RedelegationCapSignal` latches (the engineer
221 /// delegation retry decorator has exhausted `MAX_REDELEGATIONS`), every
222 /// subsequent `delegate_to_agent` call is a guaranteed dead end, so the
223 /// PM must stop issuing them rather than silently burning its remaining
224 /// `max_turns` one doomed tool call at a time (the exact bake-off L1
225 /// regression this fix closes). Modelled as a boolean-returning closure,
226 /// not a narrower `RedelegationCapSignal`-specific hook, so `agent_loop`
227 /// stays generic and does not need to depend on `run_task`.
228 /// What: Builder-style setter; returns `self` for chaining. Checked with
229 /// the SAME turn-boundary placement as [`Self::with_cancel_flag`] — once
230 /// per iteration, before the next `chat` call, never mid-tool-call — so a
231 /// tool dispatch already in flight always completes and is answered
232 /// first.
233 /// Test: `agent_loop::tests::stop_signal_aborts_before_next_turn`.
234 pub fn with_stop_signal(mut self, signal: Arc<dyn Fn() -> bool + Send + Sync>) -> Self {
235 self.stop_signal = Some(signal);
236 self
237 }
238
239 /// Run the loop to completion (or to a budget limit) and return the output.
240 ///
241 /// Why: This is the single public entry point; it owns the whole lifecycle
242 /// so callers never reconstruct the loop body incorrectly.
243 /// What: Wraps `run_inner` in a `tokio::time::timeout`. On timeout, returns
244 /// `AgentLoopError::Timeout` carrying whatever partial output `run_inner`
245 /// had accumulated up to the deadline.
246 /// Test: `agent_loop::tests::two_turn_flow_completes`,
247 /// `turn_cap_returns_partial_transcript`, and `timeout_returns_partial`.
248 pub async fn run(&self, system: &str, task: &str) -> Result<AgentOutput, AgentLoopError> {
249 let mut transcript = Transcript::seed(system, task);
250 let mut perf = PerfCollector::new(0, PERF_WORKFLOW, task);
251
252 let timeout = Duration::from_secs(self.config.timeout_secs);
253 let inner = self.run_inner(&mut transcript, &mut perf);
254
255 match tokio::time::timeout(timeout, inner).await {
256 Ok(result) => result,
257 Err(_elapsed) => Err(AgentLoopError::Timeout {
258 timeout_secs: self.config.timeout_secs,
259 partial: Box::new(build_output(&transcript, &perf)),
260 }),
261 }
262 }
263
264 /// The core loop body, separated so the timeout wrapper stays thin.
265 ///
266 /// Why: Keeping the iteration logic out of the timeout match arm makes both
267 /// halves readable and lets the timeout path reuse the same transcript/perf
268 /// state to assemble a partial result.
269 /// What: Iterates up to `max_turns`: check the (#2056) cancellation flag →
270 /// build request → chat → accrue usage → append assistant turn → if tool
271 /// calls are present, dispatch each (notifying the optional sink) and
272 /// append results, then continue — UNLESS one of those calls was a
273 /// successfully-validated `finish_task` (#2072), in which case the loop
274 /// returns immediately with the structured completion output built by
275 /// `build_finish_output`. Otherwise (a no-tool-call turn) return the
276 /// assembled output — the D3 fallback, unchanged. Per D3, `finish_reason`
277 /// never gates termination — pending tool calls always run first.
278 /// Exhausting the turn budget returns `TurnCapExceeded`; an observed
279 /// cancellation returns `Cancelled`; an observed (#2265 fix #5) external
280 /// stop signal returns `StoppedBySignal` — all three with the partial
281 /// transcript.
282 /// Test: Same tests as `run`, plus `cancel_flag_aborts_before_next_turn`,
283 /// `stop_signal_aborts_before_next_turn`,
284 /// `explicit_finish_task_terminates_loop_with_structured_summary`.
285 async fn run_inner(
286 &self,
287 transcript: &mut Transcript,
288 perf: &mut PerfCollector,
289 ) -> Result<AgentOutput, AgentLoopError> {
290 let schemas = self.tool_definitions();
291
292 for _turn in 0..self.config.max_turns {
293 // #2056: checked at the top of every turn boundary — never
294 // mid-tool-call — matching the vision spec's "cancellation is not
295 // instantaneous" semantics (§12, 11.6).
296 if let Some(cancel) = &self.cancel
297 && cancel.load(Ordering::Relaxed)
298 {
299 return Err(AgentLoopError::Cancelled {
300 partial: Box::new(build_output(transcript, perf)),
301 });
302 }
303
304 // #2265 fix #5: the external stop-signal check, same turn
305 // boundary as the cancellation check above — never mid-tool-call.
306 // This is what stops `run_task`'s PM loop from issuing further
307 // `delegate_to_agent` calls once the shared re-delegation cap has
308 // latched, instead of silently spinning through the remaining
309 // `max_turns` on doomed retries.
310 if let Some(stop) = &self.stop_signal
311 && stop()
312 {
313 return Err(AgentLoopError::StoppedBySignal {
314 partial: Box::new(build_output(transcript, perf)),
315 });
316 }
317
318 // #2070: compaction check, same turn boundary as the cancellation
319 // check above — never mid-tool-call.
320 self.maybe_compact_transcript(transcript);
321
322 let request = self.build_request(transcript, &schemas);
323 // TODO(#2265 follow-up): add in-loop retry-with-backoff for
324 // AgentLoopError::Llm before aborting to re-delegation — a single
325 // retryable Bedrock/transport hiccup here currently propagates
326 // straight out via `?` and aborts this whole engineer turn
327 // immediately, forcing a full re-delegation cycle (now bounded by
328 // `run_task::redelegation::MAX_REDELEGATIONS`, #2265) rather than
329 // a cheap in-loop retry of just this one `chat` call. Deferred
330 // (optional fix #5) to keep #2265's required scope (fixes 1-4)
331 // tightly bounded.
332 let response = self.llm.chat(&request).await?;
333
334 accrue_usage(perf, &self.config.model, &response);
335 transcript.push_response(&response);
336
337 let tool_calls = response.first_tool_calls().to_vec();
338
339 // Finish/tool-call precedence (D3, per docs/trusty-code/parity-spec.md §5):
340 // pending tool calls are ALWAYS executed and the loop continues, even
341 // when the same response also carries `finish_reason == "stop"`.
342 // Completion is signalled ONLY by an assistant turn with NO tool calls;
343 // that turn returns the final answer regardless of `finish_reason`.
344 // We must not let a `stop` reason short-circuit pending tool dispatch,
345 // or those calls would be silently dropped and the run would end with
346 // an unanswered tool request.
347 if tool_calls.is_empty() {
348 return Ok(build_output(transcript, perf));
349 }
350
351 // #2072: an explicit, successfully-validated `finish_task` call
352 // terminates the loop immediately with the structured completion
353 // report, rather than waiting for a later no-tool-call turn. Every
354 // tool call in this turn is still dispatched and answered first
355 // (the API requires a result for each), so this check happens
356 // AFTER `dispatch_all`, not instead of it.
357 if let Some(finish_args) = self.dispatch_all(&tool_calls, transcript).await {
358 return Ok(build_finish_output(transcript, perf, &finish_args));
359 }
360 }
361
362 Err(AgentLoopError::TurnCapExceeded {
363 max_turns: self.config.max_turns,
364 partial: Box::new(build_output(transcript, perf)),
365 })
366 }
367
368 /// Dispatch every tool call from one assistant turn, appending each result.
369 ///
370 /// Why: A single assistant turn may request several tools; all must run and
371 /// be answered before the next chat call, or the API rejects the follow-up.
372 /// What: For each call, parse and schema-validate its JSON arguments via
373 /// [`crate::llm::ToolCallExtractor::parse_and_validate`] (#1023) — a parse
374 /// or validation failure is reported through [`Self::report_invalid_arguments`]
375 /// as a recoverable tool result rather than aborting the loop OR (the
376 /// pre-#1023 behaviour) silently dispatching with `{}`. On valid
377 /// arguments, notifies the optional (#2056) sink's `tool_started`,
378 /// dispatches through `dispatch_gated` with no per-agent allowlist,
379 /// notifies `tool_finished` (success) or `tool_error` (a
380 /// fatal/non-recoverable `ToolResult::Error`) based on the result, and
381 /// appends the result as a `tool` message. EVERY call in `tool_calls` is
382 /// dispatched and answered, regardless of whether an earlier one was
383 /// `finish_task` — the API requires a result for each pending call.
384 /// What (#2072): if any call names [`FINISH_TASK_TOOL_NAME`] and its
385 /// dispatch did not return an error (i.e. its arguments passed both the
386 /// generic schema validation above AND `FinishTaskTool::execute`'s own
387 /// deserialisation), returns `Some(args)` with that call's validated
388 /// argument `Value` — the LAST such call wins if the model (unusually)
389 /// emits more than one in a single turn. A malformed/invalid `finish_task`
390 /// call is reported through the same recoverable-error path as any other
391 /// tool and does NOT terminate the loop, letting the model retry.
392 /// Test: `agent_loop::tests::recoverable_tool_error_continues`,
393 /// `agent_loop::tests::malformed_tool_arguments_report_recoverable_error_and_loop_continues`,
394 /// `sink_receives_started_then_finished_in_order`,
395 /// `sink_receives_tool_error_for_fatal_failures`,
396 /// `explicit_finish_task_terminates_loop_with_structured_summary`,
397 /// `malformed_finish_task_repairs_then_terminates`,
398 /// `finish_task_missing_required_field_is_recoverable_not_terminal`,
399 /// `finish_task_invalid_enum_value_is_recoverable_not_terminal`.
400 async fn dispatch_all(
401 &self,
402 tool_calls: &[ToolCall],
403 transcript: &mut Transcript,
404 ) -> Option<Value> {
405 let extractor = ToolCallExtractor::new(|name| self.registry.schema_for(name));
406 let mut finish_args: Option<Value> = None;
407
408 for call in tool_calls {
409 let tool = call.function.name.as_str();
410
411 let args = match extractor.parse_and_validate(tool, &call.function.arguments) {
412 Ok(args) => args,
413 Err(error) => {
414 self.report_invalid_arguments(&call.id, tool, &error, transcript)
415 .await;
416 continue;
417 }
418 };
419
420 if let Some(sink) = &self.sink {
421 sink.tool_started(&call.id, tool, &args.to_string()).await;
422 }
423
424 let result = self.registry.dispatch_gated(tool, args.clone(), None).await;
425
426 if let Some(sink) = &self.sink {
427 notify_result(sink.as_ref(), &call.id, tool, &result).await;
428 }
429
430 transcript.push_tool_result(&call.id, tool, result.content());
431
432 if tool == FINISH_TASK_TOOL_NAME && !result.is_error() {
433 finish_args = Some(args);
434 }
435 }
436
437 finish_args
438 }
439
440 /// Report an invalid or malformed tool call as a recoverable tool result.
441 ///
442 /// Why: #1023 replaces the prior silent `{}` degrade with the extractor's
443 /// precise validation failure. Feeding it back through the SAME
444 /// tool-result channel used for a real execution error lets the model
445 /// see exactly what was wrong and self-correct on its next turn — bounded
446 /// by the loop's existing `max_turns`, with no separate network
447 /// round-trip required for this same-turn dispatch path.
448 /// What: Notifies the optional sink (`tool_started` with a placeholder
449 /// arguments string, then `tool_error` with `error`'s `Display` text),
450 /// then appends a `tool` message carrying that same text.
451 /// Test: `agent_loop::tests::malformed_tool_arguments_report_recoverable_error_and_loop_continues`.
452 async fn report_invalid_arguments(
453 &self,
454 call_id: &str,
455 tool: &str,
456 error: &ToolCallExtractError,
457 transcript: &mut Transcript,
458 ) {
459 let message = error.to_string();
460 if let Some(sink) = &self.sink {
461 sink.tool_started(call_id, tool, "<invalid-arguments>")
462 .await;
463 sink.tool_error(call_id, tool, &message).await;
464 }
465 transcript.push_tool_result(call_id, tool, &message);
466 }
467
468 /// Apply non-destructive context compaction to `transcript`, gated on mode
469 /// (#2070, §5.4; reconciled with §5.9's D2 the same way `tool_definitions`
470 /// is).
471 ///
472 /// Why: The parity-spec (D2) requires `HarnessMode::Parity` runs to stay
473 /// byte-identical / full-history for cross-model benchmark fairness —
474 /// compacting would silently change what a Parity run sends after enough
475 /// turns, breaking that guarantee. `HarnessMode::DailyDriver` is
476 /// production's token-efficiency mode, so it is the only mode this method
477 /// ever calls `Transcript::maybe_compact` for.
478 /// What: No-op under `HarnessMode::Parity`; under `HarnessMode::DailyDriver`,
479 /// delegates to `transcript.maybe_compact(&self.config.compaction)`.
480 /// Test: `agent_loop::tests::daily_driver_mode_compacts_long_running_loop`,
481 /// `agent_loop::tests::parity_mode_never_compacts_even_past_threshold`.
482 fn maybe_compact_transcript(&self, transcript: &mut Transcript) {
483 if self.config.mode == HarnessMode::DailyDriver {
484 transcript.maybe_compact(&self.config.compaction);
485 }
486 }
487
488 /// Build a `ChatRequest` from the running transcript and tool schemas.
489 ///
490 /// Why: Each turn re-sends the full history plus the advertised tools so the
491 /// model has complete context. The completion-token cap must come from
492 /// `self.config.max_tokens` (the caller-resolved agent `[llm].max_tokens`,
493 /// or `DEFAULT_MAX_TOKENS`) — a hard-coded cap here previously truncated
494 /// any turn (e.g. a real `write_file`) needing more than 1024 tokens.
495 /// What: Clones the transcript messages, attaches tools (when any), and sets
496 /// `tool_choice = "auto"` so the model may call tools but isn't forced to.
497 /// (#2156) When [`Self::prompt_cache_enabled`] is `true`, marks the LAST
498 /// tool definition and the system-role message with an ephemeral
499 /// prompt-cache breakpoint — the byte-stable prefix this turn resends
500 /// unchanged from the last — AND (rolling-history follow-up to #2260)
501 /// marks the last two non-system messages via
502 /// [`mark_cache_breakpoint_on_history`], rolling the cached prefix
503 /// forward to cover the growing transcript, the dominant token cost.
504 /// When `false` (Parity mode, or a
505 /// provider/model that hasn't verified the passthrough), the request is
506 /// byte-identical to pre-#2156. This marker is provider-neutral: each
507 /// transport interprets it in its own wire shape — OpenRouter's
508 /// `anthropic/*` passthrough serialises it as Anthropic's `cache_control`
509 /// content-block field (`llm::message::ChatMessage::serialize`); Bedrock's
510 /// Converse transport (#2260) translates it into a native `cachePoint`
511 /// content block (`llm::bedrock::cache`). Independently, when the resolved
512 /// provider's `Provider::wants_detailed_usage()` is `true` (currently
513 /// OpenRouter, unconditionally), attaches
514 /// `usage: Some(RequestUsageConfig::detailed())` so the response carries
515 /// OpenRouter's authoritative `cost` and cache-token breakdown (the
516 /// response-side cache-usage fix).
517 /// Test: Exercised by every loop test; `config_max_tokens_reaches_chat_request`
518 /// pins that a configured cap flows through unchanged;
519 /// `daily_driver_anthropic_model_marks_cache_breakpoints`,
520 /// `daily_driver_bedrock_model_marks_cache_breakpoints`, and
521 /// `parity_mode_never_marks_cache_breakpoints` cover the #2156/#2260 gate;
522 /// `build_request_sets_detailed_usage_for_openrouter` covers the
523 /// detailed-usage gate.
524 fn build_request(&self, transcript: &Transcript, schemas: &[ToolDefinition]) -> ChatRequest {
525 let cache_prefix = self.prompt_cache_enabled();
526 let provider = crate::provider::provider_for(&self.config.model);
527
528 let tools = if schemas.is_empty() {
529 None
530 } else {
531 let mut schemas = schemas.to_vec();
532 if cache_prefix {
533 mark_cache_breakpoint_on_tools(&mut schemas);
534 }
535 Some(schemas)
536 };
537 let tool_choice = tools.as_ref().map(|_| Value::String("auto".to_string()));
538
539 let mut messages = transcript.to_messages();
540 if cache_prefix {
541 mark_cache_breakpoint_on_system(&mut messages);
542 mark_cache_breakpoint_on_history(&mut messages);
543 }
544
545 let usage = provider
546 .wants_detailed_usage()
547 .then(RequestUsageConfig::detailed);
548
549 ChatRequest {
550 model: self.config.model.clone(),
551 messages,
552 temperature: Some(0.0),
553 max_tokens: Some(self.config.max_tokens),
554 tools,
555 tool_choice,
556 usage,
557 }
558 }
559
560 /// Whether this run should mark the static tools+system prefix with a
561 /// prompt-cache breakpoint (#2156).
562 ///
563 /// Why: Caching changes cost/latency only, never model output, so it is
564 /// safe in principle under any mode — but per the #2156 spec this stays
565 /// scoped to `HarnessMode::DailyDriver` (mirroring
566 /// `Self::maybe_compact_transcript`'s existing mode gate) rather than
567 /// silently changing Parity's wire payload. It is further gated on the
568 /// resolved `Provider::supports_prompt_caching` so a model/backend whose
569 /// `cache_control` passthrough hasn't been verified never receives the
570 /// marker.
571 /// What: `true` only when `self.config.mode == HarnessMode::DailyDriver`
572 /// AND `crate::provider::provider_for(&self.config.model)
573 /// .supports_prompt_caching()` is `true`.
574 /// Test: `agent_loop::tests::daily_driver_anthropic_model_marks_cache_breakpoints`,
575 /// `agent_loop::tests::daily_driver_bedrock_model_marks_cache_breakpoints`,
576 /// `agent_loop::tests::parity_mode_never_marks_cache_breakpoints`,
577 /// `agent_loop::tests::non_anthropic_model_never_marks_cache_breakpoints`.
578 fn prompt_cache_enabled(&self) -> bool {
579 self.config.mode == HarnessMode::DailyDriver
580 && crate::provider::provider_for(&self.config.model).supports_prompt_caching()
581 }
582
583 /// Convert the registry's raw JSON schemas into typed `ToolDefinition`s.
584 ///
585 /// Why: The registry emits OpenAI-format `serde_json::Value` schemas, but
586 /// `ChatRequest.tools` is typed as `Vec<ToolDefinition>`; this bridges the
587 /// two without forcing every tool to know about the request type. The
588 /// `self.config.mode` branch (#2059) is the tool-schema CONSUMPTION POINT
589 /// for P1B's token-efficiency work: `HarnessMode::Parity` must forever
590 /// return the registry's full schema set verbatim (parity-spec D2 requires
591 /// byte-identical schemas across models); `HarnessMode::DailyDriver` is
592 /// where a future deferred/metadata-only schema set will be substituted.
593 /// Both arms are identical in M1 — no such set exists yet.
594 /// What: Deserialises each schema value; a schema that fails to parse is
595 /// dropped (a malformed schema must not abort the run) but logged with
596 /// `tracing::warn!` — including the offending tool's name (best-effort from
597 /// the raw schema) and the parse error — so a misconfigured tool that is
598 /// never advertised to the model is diagnosable rather than silent.
599 /// Test: `agent_loop::tests::two_turn_flow_completes` advertises a real tool
600 /// schema through this path; `agent_loop::tests::tool_definitions_identical_across_modes_in_m1`
601 /// pins the #2059 "no behavioural difference yet" contract.
602 fn tool_definitions(&self) -> Vec<ToolDefinition> {
603 let schemas = match self.config.mode {
604 HarnessMode::Parity => self.registry.schemas(),
605 // P1B hooks in here: a deferred/metadata-only schema set. Full
606 // schemas until then (#2059 M1 scope).
607 HarnessMode::DailyDriver => self.registry.schemas(),
608 };
609 schemas
610 .into_iter()
611 .filter_map(
612 |v| match serde_json::from_value::<ToolDefinition>(v.clone()) {
613 Ok(def) => Some(def),
614 Err(e) => {
615 let name = schema_tool_name(&v);
616 tracing::warn!(
617 "dropping unparseable tool schema (tool={name}): {e}; raw schema: {v}"
618 );
619 None
620 }
621 },
622 )
623 .collect()
624 }
625}
626
627/// Mark the LAST tool definition with an ephemeral prompt-cache breakpoint
628/// (#2156).
629///
630/// Why: Anthropic caches everything up to and including a `cache_control`
631/// breakpoint as one prefix; tools render first on the wire, so marking only
632/// the last tool caches the entire (byte-stable) tools array as a unit —
633/// matching `block/goose`'s verified OpenRouter provider.
634/// What: No-op on an empty slice; otherwise sets
635/// `schemas.last_mut().function.cache_control = Some(CacheControl::ephemeral())`.
636/// Test: `agent_loop::tests::daily_driver_anthropic_model_marks_cache_breakpoints`.
637fn mark_cache_breakpoint_on_tools(schemas: &mut [ToolDefinition]) {
638 if let Some(last) = schemas.last_mut() {
639 last.function.cache_control = Some(CacheControl::ephemeral());
640 }
641}
642
643/// Mark the system-role message with an ephemeral prompt-cache breakpoint
644/// (#2156).
645///
646/// Why: The system prompt is the second (and, combined with the tools
647/// breakpoint, final) segment of the byte-stable prefix `build_request`
648/// resends every turn; marking it caches tools+system together as OpenRouter
649/// renders tools before the system message on the wire.
650/// What: Finds the first `role == "system"` entry (there is always exactly
651/// one, from `Transcript::seed`) and sets its `cache_control`; no-op if none
652/// is found.
653/// Test: `agent_loop::tests::daily_driver_anthropic_model_marks_cache_breakpoints`.
654fn mark_cache_breakpoint_on_system(messages: &mut [ChatMessage]) {
655 if let Some(system) = messages.iter_mut().find(|m| m.role == "system") {
656 system.cache_control = Some(CacheControl::ephemeral());
657 }
658}
659
660/// Mark the last two non-system messages with an ephemeral prompt-cache
661/// breakpoint, rolling the cached prefix forward each turn (Bedrock
662/// history-cache follow-up to #2260).
663///
664/// Why: The tools+system prefix `mark_cache_breakpoint_on_tools`/
665/// `mark_cache_breakpoint_on_system` mark is small and static — the growing
666/// transcript is the dominant token cost. A live cost-proof of #2260
667/// as-merged showed cache_read staying 0 and ~452K fresh tokens/run on L1
668/// because nothing ever marked the history: every turn re-sent the full
669/// conversation as fresh input. Marking the LAST TWO non-system messages
670/// (rather than just the last one) mirrors opencode's verified
671/// `final.slice(-2)` pattern and guards against a single turn appending more
672/// content blocks than Bedrock's ~20-block cache lookback window covers — if
673/// only the very last message were marked and it alone exceeded that window,
674/// the previous turn's cache write would fall outside it and never hit.
675/// Uses breakpoint slots 3+4 of Bedrock's 4-per-request cachePoint budget
676/// (slots 1+2 are tools + system).
677/// Caveat: the OpenRouter/Anthropic-passthrough serializer
678/// (`llm::message::ChatMessage::serialize`) drops `cache_control` when a
679/// message has `content: None` (e.g. an assistant turn that is only
680/// `tool_calls`). Marking the last two messages already mitigates this in
681/// practice (at least one of the two usually carries text content); the
682/// Bedrock Converse path (`llm::bedrock::convert`) does not go through that
683/// serializer and is unaffected.
684/// What: Collects the indices of all non-system messages, then sets
685/// `cache_control` on the last (up to) two of them, in original order.
686/// No-op when there are zero or one non-system messages (the loop still
687/// marks whatever is present).
688/// Test: `agent_loop::tests::daily_driver_bedrock_model_marks_cache_breakpoints`.
689fn mark_cache_breakpoint_on_history(messages: &mut [ChatMessage]) {
690 let idxs: Vec<usize> = messages
691 .iter()
692 .enumerate()
693 .filter(|(_, m)| m.role != "system")
694 .map(|(i, _)| i)
695 .collect();
696 for &i in idxs.iter().rev().take(2) {
697 messages[i].cache_control = Some(CacheControl::ephemeral());
698 }
699}
700
701/// Best-effort extraction of a tool's name from its raw OpenAI-format schema.
702///
703/// Why: When a schema fails to deserialise into `ToolDefinition`, the warning is
704/// far more actionable if it names the offending tool; pulling `function.name`
705/// out of the still-valid JSON gives operators a handle even though the full
706/// typed parse failed.
707/// What: Reads `schema["function"]["name"]` as a string, falling back to
708/// `"<unknown>"` when the path is absent or non-string.
709/// Test: `agent_loop::tests::schema_tool_name_extracts_or_falls_back`.
710fn schema_tool_name(schema: &Value) -> &str {
711 schema
712 .get("function")
713 .and_then(|f| f.get("name"))
714 .and_then(Value::as_str)
715 .unwrap_or("<unknown>")
716}
717
718/// Notify a [`ToolEventSink`] of one tool dispatch's outcome (#2056).
719///
720/// Why: Maps `ToolResult`'s three real states onto the sink's two completion
721/// hooks: a non-recoverable (`is_fatal`) error is exceptional — `tool_error` —
722/// while success and a recoverable error are both ordinary completions
723/// distinguished by `success`, matching #2055's `ToolFinished{success}`/
724/// `ToolError` taxonomy split.
725/// What: `is_fatal()` -> `tool_error`; otherwise -> `tool_finished(!is_error())`.
726/// Test: `agent_loop::tests::sink_receives_started_then_finished_in_order`,
727/// `sink_receives_tool_error_for_fatal_failures`.
728async fn notify_result(sink: &dyn ToolEventSink, call_id: &str, tool: &str, result: &ToolResult) {
729 if result.is_fatal() {
730 sink.tool_error(call_id, tool, result.content()).await;
731 } else {
732 sink.tool_finished(call_id, tool, !result.is_error(), result.content())
733 .await;
734 }
735}
736
737/// Accrue one response's token usage into the collector as a phase record.
738///
739/// Why: Cost/usage tracking across the run is a hard requirement; recording each
740/// chat call as a phase keeps per-turn accounting visible in the perf record.
741/// What: Clones the response's usage block into `TokenUsage` and records a phase
742/// keyed by `PERF_PHASE` against the configured model.
743/// Test: `agent_loop::tests::usage_accrues_across_turns`.
744fn accrue_usage(perf: &mut PerfCollector, model: &str, response: &ChatResponse) {
745 let usage = response.clone().token_usage();
746 perf.record_phase(PERF_PHASE, 0, model, &usage);
747}
748
749/// Assemble an `AgentOutput` from the current transcript and perf totals.
750///
751/// Why: Both the success path and the two abort paths need to produce the same
752/// shape of output (final text + accumulated usage); centralising it avoids
753/// drift between them.
754/// What: Uses the transcript's joined assistant text as `content` and the perf
755/// record's totals as `usage`.
756/// Test: Exercised by every loop test via `run`.
757fn build_output(transcript: &Transcript, perf: &PerfCollector) -> AgentOutput {
758 let record = perf.build_record();
759 let totals = &record.totals;
760 let mut output = AgentOutput::from_content(transcript.assistant_text());
761 output.usage = crate::perf::TokenUsage::new(
762 totals.prompt_tokens,
763 totals.completion_tokens,
764 totals.cache_read_tokens,
765 totals.cache_creation_tokens,
766 );
767 output
768}
769
770/// Assemble the final `AgentOutput` from an explicit `finish_task` call (#2072).
771///
772/// Why: An explicit `finish_task` call carries a deterministic, structured
773/// completion report the model built on purpose — reusing that report as the
774/// loop's final output (rather than falling back to whatever prose the
775/// transcript happens to contain) is the entire point of §5.8's "-20 to -30%
776/// per agent output; deterministic, no prose interpretation" impact claim.
777/// What: Starts from the same usage/content baseline as [`build_output`], then
778/// — if `finish_args` deserialises into a `FinishTaskArgs` (it always should,
779/// since `dispatch_all` only calls this after a successful `finish_task`
780/// dispatch, which itself required a successful deserialisation) — overwrites
781/// `content` with [`crate::tools::render_finish_summary`] and sets `summary` to
782/// the model's own one-line `summary` field. On the (should-be-unreachable)
783/// deserialisation failure, falls back to the transcript-derived content
784/// `build_output` already computed, rather than panicking.
785/// Test: `agent_loop::tests::explicit_finish_task_terminates_loop_with_structured_summary`.
786fn build_finish_output(
787 transcript: &Transcript,
788 perf: &PerfCollector,
789 finish_args: &Value,
790) -> AgentOutput {
791 let mut output = build_output(transcript, perf);
792 if let Ok(parsed) = serde_json::from_value::<FinishTaskArgs>(finish_args.clone()) {
793 output.summary = Some(parsed.summary.clone());
794 output.content = crate::tools::render_finish_summary(&parsed);
795 }
796 output
797}