Skip to main content

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` — UNLESS (#2279) an attached
21//! `FinishGate` rejects it first, downgrading it to a recoverable retry so
22//! the model gets another turn instead of finishing prematurely. Aborts with
23//! a partial output when the turn cap, timeout, (#2056) an external
24//! cancellation flag, or (#2265 fix #5) an external stop signal fires.
25//! What: The whole `chat → dispatch → iterate` body runs inside a single
26//! `tokio::time::timeout` so a stalled model or hung tool cannot block forever.
27//! (#2344) `run` is now a thin wrapper over [`AgentLoop::run_with_transcript`],
28//! which drives the SAME loop body against an already-prepared `Transcript`
29//! instead of always seeding fresh — the entry point
30//! `task::executor::run_and_record` uses so a session's PM conversation
31//! persists and grows across repeated `task.run` calls instead of restarting
32//! from scratch each time.
33//! Test: `agent_loop::tests` — stubbed two-turn flow, turn-cap abort, recoverable
34//! tool-error continuation, usage accrual, sink notification order, cancellation,
35//! plus an `#[ignore]`-gated live test.
36
37mod cadence;
38mod compaction;
39mod error;
40mod goals;
41mod sink;
42mod transcript;
43
44#[cfg(test)]
45mod cadence_env_helper;
46#[cfg(test)]
47pub(crate) use cadence_env_helper::with_cadence_env;
48#[cfg(test)]
49mod tests;
50
51use std::sync::Arc;
52use std::sync::atomic::{AtomicBool, Ordering};
53use std::time::Duration;
54
55use serde_json::Value;
56
57use crate::llm::{
58    CacheControl, ChatMessage, ChatRequest, ChatResponse, LlmClientTrait, RequestUsageConfig,
59    ToolCall, ToolCallExtractError, ToolCallExtractor, ToolDefinition,
60};
61use crate::mode::HarnessMode;
62use crate::perf::PerfCollector;
63use crate::tools::{AgentOutput, FINISH_TASK_TOOL_NAME, FinishTaskArgs, ToolRegistry, ToolResult};
64
65pub use cadence::{CadenceConfig, resolve_cadence_config};
66pub use compaction::CompactionConfig;
67// (#2260) Crate-internal re-export so `llm::bedrock::cache` can reuse the
68// same chars/4 token-estimate heuristic for its cachePoint min-size guard
69// instead of duplicating it.
70pub(crate) use compaction::estimate_tokens;
71pub use error::AgentLoopError;
72pub use goals::{GOAL_SLOT_COUNT, GoalSlot, GoalSlotError, GoalSlots, GoalSource};
73pub use sink::ToolEventSink;
74pub use transcript::Transcript;
75
76/// Verify-before-finish gate hook (#2279): inspects the run's own
77/// `Transcript` at the exact moment a successful `finish_task` call would
78/// otherwise terminate the loop, and may reject it with a human-readable
79/// reason instead.
80///
81/// Why: A closure (rather than a trait) lets two very different verification
82/// strategies share one turn-boundary hook without `agent_loop` knowing
83/// about either concrete strategy: a delegated engineer's own loop needs
84/// only its own `Transcript` (its `bash` calls land there directly — see
85/// `crate::verify_gate::default_finish_gate`); the delegating PM's loop
86/// never calls `bash` itself, so its gate closure instead captures an
87/// external `run_task::SharedTranscript` and consults that instead (see
88/// `crate::verify_gate::pm_finish_gate`). This is the SAME decoupling
89/// `Self::stop_signal` (#2265 fix #5) already established for "some external
90/// condition the loop must consult at a turn boundary" — reused here rather
91/// than adding a bespoke third turn-boundary check.
92/// What: Returns `None` when the gate is satisfied (or inert — nothing
93/// requires verification for this run); `Some(reason)` when it trips,
94/// carrying the message fed back to the model as the rejected `finish_task`
95/// call's recoverable tool result.
96/// Test: `agent_loop::tests::finish_gate_*`.
97pub type FinishGate = Arc<dyn Fn(&Transcript) -> Option<String> + Send + Sync>;
98
99/// Phase name used when accruing token usage into the `PerfCollector`.
100const PERF_PHASE: &str = "agent_loop";
101
102/// Workflow label used to construct the loop's `PerfCollector`.
103const PERF_WORKFLOW: &str = "agent_loop";
104
105/// Tuning knobs for a single agent-loop run.
106///
107/// Why: The three limits (turn cap, wall-clock timeout, model) are the dials a
108/// caller most often needs to vary per task; grouping them keeps the `AgentLoop`
109/// constructor signature stable as more knobs are added later.
110/// What: `max_turns` bounds LLM round-trips; `timeout_secs` bounds total
111/// wall-clock time; `model` is the OpenRouter slug sent on every request.
112/// `mode` (#2059) is the resolved `HarnessMode` for this run — the branch
113/// point `tool_definitions` uses; defaults to `HarnessMode::default()`
114/// (`DailyDriver`) so every pre-#2059 call site that doesn't set it
115/// unchanged.
116/// Test: `agent_loop::tests::config_defaults_are_sane`.
117#[derive(Debug, Clone)]
118pub struct AgentLoopConfig {
119    /// Maximum number of LLM round-trips before aborting with a partial result.
120    pub max_turns: u32,
121
122    /// Wall-clock budget for the entire run, in seconds.
123    pub timeout_secs: u64,
124
125    /// OpenRouter model slug sent on every chat request.
126    pub model: String,
127
128    /// Per-turn completion-token cap sent as `ChatRequest.max_tokens`.
129    ///
130    /// Why: A single hard-coded cap starves any turn that must emit more than
131    /// its value — e.g. `write_file` on a real source file — silently
132    /// truncating output until the loop churns out its turn budget. Callers
133    /// must resolve this from the agent's own `[llm].max_tokens` (via
134    /// `crate::provider::resolve_max_tokens`) rather than relying on the
135    /// default below.
136    /// What: Sent verbatim as `Some(self.max_tokens)` on every `ChatRequest`
137    /// built by `AgentLoop::build_request`.
138    pub max_tokens: u32,
139
140    /// The resolved harness mode for this run (#2059). See
141    /// `Self::tool_definitions`' docs for the branch point this feeds.
142    pub mode: HarnessMode,
143
144    /// Non-destructive context compaction tuning (#2070, §5.4). Only
145    /// consulted when `mode == HarnessMode::DailyDriver` — see
146    /// `Self::maybe_compact_transcript`'s docs for why Parity must never
147    /// compact.
148    pub compaction: CompactionConfig,
149
150    /// Cadence-compressor tuning (#2346, epic #2343). `None` (the default)
151    /// disables cadence entirely — the delegated engineer's own loop and
152    /// `run_task`'s legacy one-shot/bake-off path both rely on this default
153    /// to stay byte-identical to pre-#2346 behaviour; only
154    /// `task::executor::run_and_record`'s persistent-session PM loop sets
155    /// `Some(_)`. Consulted only under `HarnessMode::DailyDriver` — see
156    /// `Self::maybe_cadence_compress`'s docs.
157    pub cadence: Option<CadenceConfig>,
158}
159
160impl Default for AgentLoopConfig {
161    /// Sensible defaults for an interactive agent run.
162    ///
163    /// Why: Most callers want a bounded but generous loop; defaults avoid
164    /// boilerplate at every construction site. `max_tokens` defaults to
165    /// `crate::provider::DEFAULT_MAX_TOKENS` — callers that need the agent's
166    /// configured `[llm].max_tokens` must set this field explicitly via
167    /// `crate::provider::resolve_max_tokens`; this default is only the
168    /// generous fallback for when no agent config is consulted.
169    /// What: 8 turns, 120s timeout, `openai/gpt-4o-mini`,
170    /// `DEFAULT_MAX_TOKENS`, `HarnessMode::default()`, `CompactionConfig::default()`,
171    /// `cadence: None` (#2346 — disabled unless a caller opts in).
172    /// Test: `config_defaults_are_sane`.
173    fn default() -> Self {
174        Self {
175            max_turns: 8,
176            timeout_secs: 120,
177            model: "openai/gpt-4o-mini".to_string(),
178            max_tokens: crate::provider::DEFAULT_MAX_TOKENS,
179            mode: HarnessMode::default(),
180            compaction: CompactionConfig::default(),
181            cadence: None,
182        }
183    }
184}
185
186/// Drives an LLM through a bounded multi-turn tool-calling conversation.
187///
188/// Why: Encapsulates the repetitive, error-prone control flow (call → extract
189/// tool calls → dispatch → append → repeat) behind one `run` method so call
190/// sites express intent ("run this task") not mechanics.
191/// What: Holds the config, an `Arc<dyn LlmClientTrait>` (mockable in tests), an
192/// `Arc<ToolRegistry>` whose schemas are advertised and whose `dispatch_gated`
193/// executes tool calls, and three OPTIONAL collaborators set via builder
194/// methods after construction: (#2056) a `sink` notified around every tool
195/// dispatch, (#2056) a `cancel` flag checked once per turn boundary, and
196/// (#2265 fix #5) a `stop_signal` closure checked at that SAME turn boundary.
197/// All three default to `None`, so every existing call site (`run_task`,
198/// `runner::in_process`) is unaffected. A fourth optional collaborator,
199/// (#2279) `finish_gate`, is set via [`Self::with_finish_gate`] — see
200/// [`FinishGate`]'s docs.
201/// Test: `agent_loop::tests::*`.
202pub struct AgentLoop {
203    config: AgentLoopConfig,
204    llm: Arc<dyn LlmClientTrait>,
205    registry: Arc<ToolRegistry>,
206    sink: Option<Arc<dyn ToolEventSink>>,
207    cancel: Option<Arc<AtomicBool>>,
208    stop_signal: Option<Arc<dyn Fn() -> bool + Send + Sync>>,
209    finish_gate: Option<FinishGate>,
210    /// (#2682) When `true`, a `bash` test invocation that
211    /// `crate::redundant_run::is_redundant_test_rerun` judges redundant (an
212    /// identical suite already passed and nothing changed since) is
213    /// short-circuited with `crate::redundant_run::REDUNDANT_RERUN_MESSAGE`
214    /// instead of being spawned. Default `false` (a pure no-op for every call
215    /// site that never opts in); attached at the delegated-engineer
216    /// construction site via [`Self::with_redundant_run_suppression`].
217    suppress_redundant_reruns: bool,
218}
219
220impl AgentLoop {
221    /// Construct an agent loop from its three core collaborators.
222    ///
223    /// Why: Constructor injection keeps the loop testable — production passes a
224    /// real `LlmClient`, tests pass a scripted mock, both as
225    /// `Arc<dyn LlmClientTrait>`.
226    /// What: Stores the config, LLM client, and tool registry; `sink`/`cancel`/
227    /// `stop_signal` start `None` — attach them via
228    /// [`Self::with_tool_event_sink`]/[`Self::with_cancel_flag`]/
229    /// [`Self::with_stop_signal`] when the caller needs them (#2056's
230    /// daemon-driven task execution attaches the first two; `run_task`'s PM
231    /// loop attaches `stop_signal` (#2265 fix #5); the delegated engineer's
232    /// own loop attaches none of them).
233    /// Test: `agent_loop::tests::two_turn_flow_completes`.
234    pub fn new(
235        config: AgentLoopConfig,
236        llm: Arc<dyn LlmClientTrait>,
237        registry: Arc<ToolRegistry>,
238    ) -> Self {
239        Self {
240            config,
241            llm,
242            registry,
243            sink: None,
244            cancel: None,
245            stop_signal: None,
246            finish_gate: None,
247            suppress_redundant_reruns: false,
248        }
249    }
250
251    /// Attach a [`ToolEventSink`] notified around every tool dispatch (#2056).
252    ///
253    /// Why: Lets a daemon-driven run make its tool activity observable to a
254    /// `session.attach`ed client without forking the dispatch loop.
255    /// What: Builder-style setter; returns `self` for chaining.
256    /// Test: `agent_loop::tests::sink_receives_started_then_finished_in_order`.
257    pub fn with_tool_event_sink(mut self, sink: Arc<dyn ToolEventSink>) -> Self {
258        self.sink = Some(sink);
259        self
260    }
261
262    /// Attach a cancellation flag checked once per turn boundary (#2056).
263    ///
264    /// Why: `session.cancel` on an in-flight daemon-driven run must stop the
265    /// loop cooperatively; sharing one `Arc<AtomicBool>` between the caller and
266    /// every loop it spawns (PM + any delegated sub-agent loops) is the
267    /// cheapest possible cancellation signal.
268    /// What: Builder-style setter; returns `self` for chaining. The flag is
269    /// checked with `Ordering::Relaxed` — only "has it been set at all" matters,
270    /// not fine-grained memory ordering with other state.
271    /// Test: `agent_loop::tests::cancel_flag_aborts_before_next_turn`.
272    pub fn with_cancel_flag(mut self, cancel: Arc<AtomicBool>) -> Self {
273        self.cancel = Some(cancel);
274        self
275    }
276
277    /// Attach an external stop condition checked once per turn boundary
278    /// (#2265 fix #5).
279    ///
280    /// Why: Some callers know, independently of this loop's own turn/timeout
281    /// budget, that a shared external condition has made further turns
282    /// pointless — `run_task`'s PM loop is the motivating case: once its
283    /// shared `redelegation::RedelegationCapSignal` latches (the engineer
284    /// delegation retry decorator has exhausted `MAX_REDELEGATIONS`), every
285    /// subsequent `delegate_to_agent` call is a guaranteed dead end, so the
286    /// PM must stop issuing them rather than silently burning its remaining
287    /// `max_turns` one doomed tool call at a time (the exact bake-off L1
288    /// regression this fix closes). Modelled as a boolean-returning closure,
289    /// not a narrower `RedelegationCapSignal`-specific hook, so `agent_loop`
290    /// stays generic and does not need to depend on `run_task`.
291    /// What: Builder-style setter; returns `self` for chaining. Checked with
292    /// the SAME turn-boundary placement as [`Self::with_cancel_flag`] — once
293    /// per iteration, before the next `chat` call, never mid-tool-call — so a
294    /// tool dispatch already in flight always completes and is answered
295    /// first.
296    /// Test: `agent_loop::tests::stop_signal_aborts_before_next_turn`.
297    pub fn with_stop_signal(mut self, signal: Arc<dyn Fn() -> bool + Send + Sync>) -> Self {
298        self.stop_signal = Some(signal);
299        self
300    }
301
302    /// Attach a [`FinishGate`] consulted the moment a successful
303    /// `finish_task` call would otherwise terminate the loop (#2279).
304    ///
305    /// Why: Gives a caller a hook to reject a premature `finish_task` with a
306    /// recoverable retry instead of letting the loop terminate — see
307    /// [`FinishGate`]'s docs for how the delegated-engineer and delegating-PM
308    /// cases differ. `None` (the default) is a pure no-op; every existing
309    /// call site that never attaches a gate is unaffected.
310    /// What: Builder-style setter; returns `self` for chaining.
311    /// Test: `agent_loop::tests::finish_gate_trips_and_recovers`,
312    /// `agent_loop::tests::finish_gate_inert_without_named_test_command`.
313    pub fn with_finish_gate(mut self, gate: FinishGate) -> Self {
314        self.finish_gate = Some(gate);
315        self
316    }
317
318    /// Enable redundant full-suite test re-run suppression (#2682).
319    ///
320    /// Why: The complement to [`Self::with_finish_gate`]'s verify gate — where
321    /// that guarantees the suite runs at least once, this stops it running more
322    /// than needed. Opt-in (default `false`) and attached at the same single
323    /// delegated-engineer construction site (`runner::in_process`) so both
324    /// gates bracket the same loop; call sites that never opt in are a pure
325    /// no-op.
326    /// What: Builder-style setter; returns `self` for chaining. When set,
327    /// [`Self::dispatch_all`] consults
328    /// [`crate::redundant_run::is_redundant_test_rerun`] before spawning a
329    /// `bash` test command and short-circuits a redundant one.
330    /// Test: `agent_loop::tests::redundant_test_rerun_is_suppressed`,
331    /// `agent_loop::tests::test_rerun_after_edit_is_not_suppressed`.
332    pub fn with_redundant_run_suppression(mut self) -> Self {
333        self.suppress_redundant_reruns = true;
334        self
335    }
336
337    /// Run the loop to completion (or to a budget limit) and return the output.
338    ///
339    /// Why: This is the single public entry point for a fresh, one-shot run —
340    /// `run_task` and the delegated engineer's own loop, neither of which
341    /// participate in cross-run persistence, always start from a clean slate.
342    /// What: Seeds a brand-new `Transcript` (`system` + `task`), then
343    /// delegates to [`Self::run_with_transcript`]. Because a fresh seed's
344    /// `assistant_text_mark()` is always `0`, the returned output's `content`
345    /// is identical to the pre-#2344 behaviour (the whole run's joined
346    /// assistant text) — this method's observable contract is unchanged.
347    /// Test: `agent_loop::tests::two_turn_flow_completes`,
348    /// `turn_cap_returns_partial_transcript`, and `timeout_returns_partial`.
349    pub async fn run(&self, system: &str, task: &str) -> Result<AgentOutput, AgentLoopError> {
350        let mut transcript = Transcript::seed(system, task);
351        self.run_with_transcript(&mut transcript, task).await
352    }
353
354    /// Run the loop against an ALREADY-PREPARED transcript instead of
355    /// seeding a fresh one (#2344 — the persistent-session entry point).
356    ///
357    /// Why: `task::executor::run_and_record` needs the PM's conversation to
358    /// survive across repeated `task.run` calls on the same session:
359    /// `session::SessionRegistry::begin_pm_transcript` either seeds fresh (a
360    /// session's first run) or appends the new request as a `user` turn onto
361    /// the session's existing, growing history (every run after that) —
362    /// either way, `transcript` arrives here already holding exactly the
363    /// messages this run should send. [`Self::run`] is just this method
364    /// called with a freshly seeded transcript, so both entry points share
365    /// one loop implementation.
366    /// What: Records `transcript.assistant_text_mark()` BEFORE driving the
367    /// loop, runs the SAME timeout-wrapped `run_inner` body `run` used to,
368    /// then rewrites `content` on the resulting `AgentOutput` (success or any
369    /// partial-abort variant, via `AgentLoopError::partial_output_mut`) to
370    /// `transcript.assistant_text_since(mark)` — scoping THIS call's reported
371    /// answer to only the turns it produced, even though the transcript
372    /// itself keeps the full cumulative history for the model and for
373    /// `session.get_transcript`. Skips the rewrite when `summary.is_some()`:
374    /// an explicit `finish_task` completion (#2072) already carries a
375    /// deliberate, structured summary via `build_finish_output`, which must
376    /// not be clobbered by the plain assistant-text join.
377    /// Test: `agent_loop::tests::run_with_transcript_does_not_reseed_system_message`,
378    /// `agent_loop::tests::run_with_transcript_scopes_output_to_new_turns`,
379    /// `agent_loop::tests::run_with_transcript_scopes_partial_output_on_turn_cap`,
380    /// `agent_loop::tests::run_with_transcript_does_not_clobber_finish_task_summary`.
381    pub async fn run_with_transcript(
382        &self,
383        transcript: &mut Transcript,
384        task: &str,
385    ) -> Result<AgentOutput, AgentLoopError> {
386        let mark = transcript.assistant_text_mark();
387        let mut perf = PerfCollector::new(0, PERF_WORKFLOW, task);
388
389        let timeout = Duration::from_secs(self.config.timeout_secs);
390        let inner = self.run_inner(transcript, &mut perf);
391
392        let mut result = match tokio::time::timeout(timeout, inner).await {
393            Ok(result) => result,
394            Err(_elapsed) => Err(AgentLoopError::Timeout {
395                timeout_secs: self.config.timeout_secs,
396                partial: Box::new(build_output(transcript, &perf)),
397            }),
398        };
399
400        match &mut result {
401            Ok(output) => scope_output_to_new_turns(output, transcript, mark),
402            Err(e) => {
403                if let Some(partial) = e.partial_output_mut() {
404                    scope_output_to_new_turns(partial, transcript, mark);
405                }
406            }
407        }
408        result
409    }
410
411    /// The core loop body, separated so the timeout wrapper stays thin.
412    ///
413    /// Why: Keeping the iteration logic out of the timeout match arm makes both
414    /// halves readable and lets the timeout path reuse the same transcript/perf
415    /// state to assemble a partial result.
416    /// What: Iterates up to `max_turns`: check the (#2056) cancellation flag →
417    /// build request → chat → accrue usage → append assistant turn → if tool
418    /// calls are present, dispatch each (notifying the optional sink) and
419    /// append results, then continue — UNLESS one of those calls was a
420    /// successfully-validated `finish_task` (#2072), in which case the loop
421    /// returns immediately with the structured completion output built by
422    /// `build_finish_output`. Otherwise (a no-tool-call turn) return the
423    /// assembled output — the D3 fallback, unchanged. Per D3, `finish_reason`
424    /// never gates termination — pending tool calls always run first.
425    /// Exhausting the turn budget returns `TurnCapExceeded`; an observed
426    /// cancellation returns `Cancelled`; an observed (#2265 fix #5) external
427    /// stop signal returns `StoppedBySignal` — all three with the partial
428    /// transcript.
429    /// Test: Same tests as `run`, plus `cancel_flag_aborts_before_next_turn`,
430    /// `stop_signal_aborts_before_next_turn`,
431    /// `explicit_finish_task_terminates_loop_with_structured_summary`.
432    async fn run_inner(
433        &self,
434        transcript: &mut Transcript,
435        perf: &mut PerfCollector,
436    ) -> Result<AgentOutput, AgentLoopError> {
437        let schemas = self.tool_definitions();
438
439        for _turn in 0..self.config.max_turns {
440            // #2056: checked at the top of every turn boundary — never
441            // mid-tool-call — matching the vision spec's "cancellation is not
442            // instantaneous" semantics (§12, 11.6).
443            if let Some(cancel) = &self.cancel
444                && cancel.load(Ordering::Relaxed)
445            {
446                return Err(AgentLoopError::Cancelled {
447                    partial: Box::new(build_output(transcript, perf)),
448                });
449            }
450
451            // #2265 fix #5: the external stop-signal check, same turn
452            // boundary as the cancellation check above — never mid-tool-call.
453            // This is what stops `run_task`'s PM loop from issuing further
454            // `delegate_to_agent` calls once the shared re-delegation cap has
455            // latched, instead of silently spinning through the remaining
456            // `max_turns` on doomed retries.
457            if let Some(stop) = &self.stop_signal
458                && stop()
459            {
460                return Err(AgentLoopError::StoppedBySignal {
461                    partial: Box::new(build_output(transcript, perf)),
462                });
463            }
464
465            // #2346: cadence compression runs FIRST, same turn boundary as
466            // the checks above — the continuous, turn-count-driven mechanism
467            // that keeps working context under budget so #2070's threshold
468            // compactor below becomes a backstop rather than the primary
469            // token-efficiency path.
470            self.maybe_cadence_compress(transcript);
471
472            // #2070: compaction check, same turn boundary as the cancellation
473            // check above — never mid-tool-call. Runs AFTER cadence so it
474            // only ever sees a transcript cadence already kept under budget.
475            self.maybe_compact_transcript(transcript);
476
477            let request = self.build_request(transcript, &schemas);
478            // TODO(#2265 follow-up): add in-loop retry-with-backoff for
479            // AgentLoopError::Llm before aborting to re-delegation — a single
480            // retryable Bedrock/transport hiccup here currently propagates
481            // straight out via `?` and aborts this whole engineer turn
482            // immediately, forcing a full re-delegation cycle (now bounded by
483            // `run_task::redelegation::MAX_REDELEGATIONS`, #2265) rather than
484            // a cheap in-loop retry of just this one `chat` call. Deferred
485            // (optional fix #5) to keep #2265's required scope (fixes 1-4)
486            // tightly bounded.
487            let response = self.llm.chat(&request).await?;
488
489            accrue_usage(perf, &self.config.model, &response);
490            transcript.push_response(&response);
491
492            let tool_calls = response.first_tool_calls().to_vec();
493
494            // Finish/tool-call precedence (D3, per docs/trusty-code/parity-spec.md §5):
495            // pending tool calls are ALWAYS executed and the loop continues, even
496            // when the same response also carries `finish_reason == "stop"`.
497            // Completion is signalled ONLY by an assistant turn with NO tool calls;
498            // that turn returns the final answer regardless of `finish_reason`.
499            // We must not let a `stop` reason short-circuit pending tool dispatch,
500            // or those calls would be silently dropped and the run would end with
501            // an unanswered tool request.
502            if tool_calls.is_empty() {
503                return Ok(build_output(transcript, perf));
504            }
505
506            // #2072: an explicit, successfully-validated `finish_task` call
507            // terminates the loop immediately with the structured completion
508            // report, rather than waiting for a later no-tool-call turn. Every
509            // tool call in this turn is still dispatched and answered first
510            // (the API requires a result for each), so this check happens
511            // AFTER `dispatch_all`, not instead of it.
512            if let Some(finish_args) = self.dispatch_all(&tool_calls, transcript).await {
513                return Ok(build_finish_output(transcript, perf, &finish_args));
514            }
515        }
516
517        Err(AgentLoopError::TurnCapExceeded {
518            max_turns: self.config.max_turns,
519            partial: Box::new(build_output(transcript, perf)),
520        })
521    }
522
523    /// Dispatch every tool call from one assistant turn, appending each result.
524    ///
525    /// Why: A single assistant turn may request several tools; all must run and
526    /// be answered before the next chat call, or the API rejects the follow-up.
527    /// What: For each call, parse and schema-validate its JSON arguments via
528    /// [`crate::llm::ToolCallExtractor::parse_and_validate`] (#1023) — a parse
529    /// or validation failure is reported through [`Self::report_invalid_arguments`]
530    /// as a recoverable tool result rather than aborting the loop OR (the
531    /// pre-#1023 behaviour) silently dispatching with `{}`. On valid
532    /// arguments, notifies the optional (#2056) sink's `tool_started`,
533    /// dispatches through `dispatch_gated` with no per-agent allowlist,
534    /// notifies `tool_finished` (success) or `tool_error` (a
535    /// fatal/non-recoverable `ToolResult::Error`) based on the result, and
536    /// appends the result as a `tool` message. EVERY call in `tool_calls` is
537    /// dispatched and answered, regardless of whether an earlier one was
538    /// `finish_task` — the API requires a result for each pending call.
539    /// What (#2072): if any call names [`FINISH_TASK_TOOL_NAME`] and its
540    /// dispatch did not return an error (i.e. its arguments passed both the
541    /// generic schema validation above AND `FinishTaskTool::execute`'s own
542    /// deserialisation), returns `Some(args)` with that call's validated
543    /// argument `Value` — the LAST such call wins if the model (unusually)
544    /// emits more than one in a single turn. A malformed/invalid `finish_task`
545    /// call is reported through the same recoverable-error path as any other
546    /// tool and does NOT terminate the loop, letting the model retry.
547    /// (#2279) A `finish_task` call that DID succeed is still subject to the
548    /// optional [`Self::finish_gate`] — see [`FinishGate`]'s docs. When
549    /// attached and it trips, the result is downgraded in place to
550    /// `ToolResult::err(reason)` — the SAME recoverable-error shape used
551    /// throughout this method — BEFORE the sink notification and transcript
552    /// push below, so both see the rejection, not the original success; this
553    /// also means the `finish_args` assignment below never fires for a
554    /// gate-rejected call, so the loop simply continues to the next turn.
555    /// Test: `agent_loop::tests::recoverable_tool_error_continues`,
556    /// `agent_loop::tests::malformed_tool_arguments_report_recoverable_error_and_loop_continues`,
557    /// `sink_receives_started_then_finished_in_order`,
558    /// `sink_receives_tool_error_for_fatal_failures`,
559    /// `explicit_finish_task_terminates_loop_with_structured_summary`,
560    /// `malformed_finish_task_repairs_then_terminates`,
561    /// `finish_task_missing_required_field_is_recoverable_not_terminal`,
562    /// `finish_task_invalid_enum_value_is_recoverable_not_terminal`,
563    /// `finish_gate_trips_and_recovers`,
564    /// `finish_gate_inert_without_named_test_command`.
565    async fn dispatch_all(
566        &self,
567        tool_calls: &[ToolCall],
568        transcript: &mut Transcript,
569    ) -> Option<Value> {
570        let extractor = ToolCallExtractor::new(|name| self.registry.schema_for(name));
571        let mut finish_args: Option<Value> = None;
572
573        for call in tool_calls {
574            let tool = call.function.name.as_str();
575
576            let args = match extractor.parse_and_validate(tool, &call.function.arguments) {
577                Ok(args) => args,
578                Err(error) => {
579                    self.report_invalid_arguments(&call.id, tool, &error, transcript)
580                        .await;
581                    continue;
582                }
583            };
584
585            if let Some(sink) = &self.sink {
586                sink.tool_started(&call.id, tool, &args.to_string()).await;
587            }
588
589            // #2682: short-circuit a redundant full-suite re-run BEFORE
590            // spawning it — an identical test command already passed earlier
591            // and nothing has changed since (see `redundant_run`). The prior
592            // pass still stands, so re-running only burns a turn's wall-clock;
593            // returning a normal (non-error) sentinel result keeps the loop
594            // calm and nudges the model to finish rather than re-confirm. Only
595            // ever fires when explicitly enabled via
596            // `with_redundant_run_suppression`, so no other call site is
597            // affected.
598            let mut result = if self.suppress_redundant_reruns
599                && crate::redundant_run::is_test_bash_call(call)
600                && crate::redundant_run::is_redundant_test_rerun(&transcript.messages(), &call.id)
601            {
602                ToolResult::ok(crate::redundant_run::REDUNDANT_RERUN_MESSAGE.to_string())
603            } else {
604                self.registry.dispatch_gated(tool, args.clone(), None).await
605            };
606
607            // #2279: a `finish_task` call that otherwise SUCCEEDED is still
608            // subject to the verify-before-finish gate, if one is attached.
609            // Tripping it downgrades the result to the same recoverable-error
610            // shape every other tool failure uses, so the model sees WHY
611            // finish was rejected and gets another turn to fix it, rather
612            // than the loop silently declining to terminate.
613            if tool == FINISH_TASK_TOOL_NAME
614                && !result.is_error()
615                && let Some(reason) = self.finish_gate.as_ref().and_then(|gate| gate(transcript))
616            {
617                result = ToolResult::err(reason);
618            }
619
620            if let Some(sink) = &self.sink {
621                notify_result(sink.as_ref(), &call.id, tool, &result).await;
622            }
623
624            transcript.push_tool_result(&call.id, tool, result.content());
625
626            if tool == FINISH_TASK_TOOL_NAME && !result.is_error() {
627                finish_args = Some(args);
628            }
629        }
630
631        finish_args
632    }
633
634    /// Report an invalid or malformed tool call as a recoverable tool result.
635    ///
636    /// Why: #1023 replaces the prior silent `{}` degrade with the extractor's
637    /// precise validation failure. Feeding it back through the SAME
638    /// tool-result channel used for a real execution error lets the model
639    /// see exactly what was wrong and self-correct on its next turn — bounded
640    /// by the loop's existing `max_turns`, with no separate network
641    /// round-trip required for this same-turn dispatch path.
642    /// What: Notifies the optional sink (`tool_started` with a placeholder
643    /// arguments string, then `tool_error` with `error`'s `Display` text),
644    /// then appends a `tool` message carrying that same text.
645    /// Test: `agent_loop::tests::malformed_tool_arguments_report_recoverable_error_and_loop_continues`.
646    async fn report_invalid_arguments(
647        &self,
648        call_id: &str,
649        tool: &str,
650        error: &ToolCallExtractError,
651        transcript: &mut Transcript,
652    ) {
653        let message = error.to_string();
654        if let Some(sink) = &self.sink {
655            sink.tool_started(call_id, tool, "<invalid-arguments>")
656                .await;
657            sink.tool_error(call_id, tool, &message).await;
658        }
659        transcript.push_tool_result(call_id, tool, &message);
660    }
661
662    /// Apply non-destructive context compaction to `transcript`, gated on mode
663    /// (#2070, §5.4; reconciled with §5.9's D2 the same way `tool_definitions`
664    /// is).
665    ///
666    /// Why: The parity-spec (D2) requires `HarnessMode::Parity` runs to stay
667    /// byte-identical / full-history for cross-model benchmark fairness —
668    /// compacting would silently change what a Parity run sends after enough
669    /// turns, breaking that guarantee. `HarnessMode::DailyDriver` is
670    /// production's token-efficiency mode, so it is the only mode this method
671    /// ever calls `Transcript::maybe_compact` for. (#2349, epic #2343) Under
672    /// the #2346 cadence system a threshold fire is no longer expected in
673    /// steady state — it means cadence sizing / daemon-availability /
674    /// turn-size assumptions were violated — so this is also where that
675    /// regression signal is raised. Cadence-DISABLED contexts (`run_task`
676    /// one-shot, `Parity`, delegated sub-agent engineer loops — all
677    /// `cadence: None`) still use threshold compaction as their PRIMARY,
678    /// EXPECTED mechanism, so the error-level framing below must never apply
679    /// to them.
680    /// What: No-op under `HarnessMode::Parity`; under `HarnessMode::DailyDriver`,
681    /// delegates to `transcript.maybe_compact(&self.config.compaction)`. When
682    /// that returns `true` (a fire actually happened), unconditionally calls
683    /// `transcript.record_threshold_compaction()` (#2349's fact counter,
684    /// exposed via `session::TranscriptRecord.compaction_events` —
685    /// increments regardless of cadence), then — ONLY when
686    /// `self.config.cadence.is_some()` — emits `tracing::error!` with the
687    /// current estimated token count, the configured `token_threshold`, and
688    /// `cadence_enabled = true` for context. `cadence: None` keeps today's
689    /// existing behaviour exactly as it was before this ticket: no log at
690    /// this call site at all.
691    /// Test: `agent_loop::tests::daily_driver_mode_compacts_long_running_loop`,
692    /// `agent_loop::tests::parity_mode_never_compacts_even_past_threshold`,
693    /// `agent_loop::tests::forced_degradation_increments_counter_and_logs_error`,
694    /// `agent_loop::tests::cadence_none_threshold_fire_does_not_log_error`.
695    fn maybe_compact_transcript(&self, transcript: &mut Transcript) {
696        if self.config.mode != HarnessMode::DailyDriver {
697            return;
698        }
699        if !transcript.maybe_compact(&self.config.compaction) {
700            return;
701        }
702        transcript.record_threshold_compaction();
703
704        if self.config.cadence.is_some() {
705            let estimated_tokens = compaction::estimate_total_tokens(&transcript.to_messages());
706            tracing::error!(
707                estimated_tokens,
708                token_threshold = self.config.compaction.token_threshold,
709                cadence_enabled = true,
710                "threshold compaction fired unexpectedly under cadence — this is a regression \
711                 signal: cadence sizing, daemon availability, or turn-size assumptions were \
712                 likely violated (epic #2343 expects compaction_events == 0 in steady state)"
713            );
714        }
715    }
716
717    /// Apply the #2346 cadence compressor to `transcript`, gated on mode the
718    /// SAME way [`Self::maybe_compact_transcript`] is, plus an explicit
719    /// per-run opt-in.
720    ///
721    /// Why: Cadence must respect the identical `HarnessMode::Parity` carve-out
722    /// as threshold compaction (byte-identical benchmark runs), AND must stay
723    /// off by default (`self.config.cadence == None`) so every call site that
724    /// doesn't explicitly opt in — the delegated engineer's own loop,
725    /// `run_task`'s legacy one-shot/bake-off path — sees zero behavioural
726    /// change from before this ticket. Only
727    /// `task::executor::run_and_record`'s persistent-session PM loop sets
728    /// `AgentLoopConfig.cadence = Some(_)`.
729    /// What: No-op unless `mode == HarnessMode::DailyDriver` AND
730    /// `self.config.cadence` is `Some`; otherwise resolves the model's real
731    /// context window (`crate::provider::resolve_context_window`, mirroring
732    /// `Self::maybe_compact_transcript`'s own model-aware sibling) and
733    /// delegates to `cadence::maybe_cadence_compress`, reusing
734    /// `self.config.compaction.keep_last_messages` as the shared active-zone
735    /// size rather than introducing a second, possibly-inconsistent knob.
736    /// Test: `agent_loop::tests::cadence_disabled_by_default`,
737    /// `agent_loop::tests::cadence_never_fires_in_parity_mode`,
738    /// `agent_loop::tests::cadence_fires_in_daily_driver_when_configured`.
739    fn maybe_cadence_compress(&self, transcript: &mut Transcript) {
740        if self.config.mode != HarnessMode::DailyDriver {
741            return;
742        }
743        let Some(cadence_cfg) = &self.config.cadence else {
744            return;
745        };
746        let context_window = crate::provider::resolve_context_window(&self.config.model);
747        cadence::maybe_cadence_compress(
748            transcript,
749            cadence_cfg,
750            self.config.compaction.keep_last_messages,
751            context_window,
752        );
753    }
754
755    /// Build a `ChatRequest` from the running transcript and tool schemas.
756    ///
757    /// Why: Each turn re-sends the full history plus the advertised tools so the
758    /// model has complete context. The completion-token cap must come from
759    /// `self.config.max_tokens` (the caller-resolved agent `[llm].max_tokens`,
760    /// or `DEFAULT_MAX_TOKENS`) — a hard-coded cap here previously truncated
761    /// any turn (e.g. a real `write_file`) needing more than 1024 tokens.
762    /// What: Clones the transcript messages, attaches tools (when any), and sets
763    /// `tool_choice = "auto"` so the model may call tools but isn't forced to.
764    /// (#2156) When [`Self::prompt_cache_enabled`] is `true`, marks the LAST
765    /// tool definition and the system-role message with an ephemeral
766    /// prompt-cache breakpoint — the byte-stable prefix this turn resends
767    /// unchanged from the last — AND (rolling-history follow-up to #2260)
768    /// marks the last two non-system messages via
769    /// [`mark_cache_breakpoint_on_history`], rolling the cached prefix
770    /// forward to cover the growing transcript, the dominant token cost.
771    /// When `false` (Parity mode, or a
772    /// provider/model that hasn't verified the passthrough), the request is
773    /// byte-identical to pre-#2156. This marker is provider-neutral: each
774    /// transport interprets it in its own wire shape — OpenRouter's
775    /// `anthropic/*` passthrough serialises it as Anthropic's `cache_control`
776    /// content-block field (`llm::message::ChatMessage::serialize`); Bedrock's
777    /// Converse transport (#2260) translates it into a native `cachePoint`
778    /// content block (`llm::bedrock::cache`). Independently, when the resolved
779    /// provider's `Provider::wants_detailed_usage()` is `true` (currently
780    /// OpenRouter, unconditionally), attaches
781    /// `usage: Some(RequestUsageConfig::detailed())` so the response carries
782    /// OpenRouter's authoritative `cost` and cache-token breakdown (the
783    /// response-side cache-usage fix).
784    /// Test: Exercised by every loop test; `config_max_tokens_reaches_chat_request`
785    /// pins that a configured cap flows through unchanged;
786    /// `daily_driver_anthropic_model_marks_cache_breakpoints`,
787    /// `daily_driver_bedrock_model_marks_cache_breakpoints`, and
788    /// `parity_mode_never_marks_cache_breakpoints` cover the #2156/#2260 gate;
789    /// `build_request_sets_detailed_usage_for_openrouter` covers the
790    /// detailed-usage gate.
791    fn build_request(&self, transcript: &Transcript, schemas: &[ToolDefinition]) -> ChatRequest {
792        let cache_prefix = self.prompt_cache_enabled();
793        let provider = crate::provider::provider_for(&self.config.model);
794
795        let tools = if schemas.is_empty() {
796            None
797        } else {
798            let mut schemas = schemas.to_vec();
799            if cache_prefix {
800                mark_cache_breakpoint_on_tools(&mut schemas);
801            }
802            Some(schemas)
803        };
804        let tool_choice = tools.as_ref().map(|_| Value::String("auto".to_string()));
805
806        let mut messages = transcript.to_messages();
807        if cache_prefix {
808            mark_cache_breakpoint_on_system(&mut messages);
809            mark_cache_breakpoint_on_history(&mut messages);
810        }
811
812        let usage = provider
813            .wants_detailed_usage()
814            .then(RequestUsageConfig::detailed);
815
816        ChatRequest {
817            model: self.config.model.clone(),
818            messages,
819            temperature: Some(0.0),
820            max_tokens: Some(self.config.max_tokens),
821            tools,
822            tool_choice,
823            usage,
824        }
825    }
826
827    /// Whether this run should mark the static tools+system prefix with a
828    /// prompt-cache breakpoint (#2156).
829    ///
830    /// Why: Caching changes cost/latency only, never model output, so it is
831    /// safe in principle under any mode — but per the #2156 spec this stays
832    /// scoped to `HarnessMode::DailyDriver` (mirroring
833    /// `Self::maybe_compact_transcript`'s existing mode gate) rather than
834    /// silently changing Parity's wire payload. It is further gated on the
835    /// resolved `Provider::supports_prompt_caching` so a model/backend whose
836    /// `cache_control` passthrough hasn't been verified never receives the
837    /// marker.
838    /// What: `true` only when `self.config.mode == HarnessMode::DailyDriver`
839    /// AND `crate::provider::provider_for(&self.config.model)
840    /// .supports_prompt_caching()` is `true`.
841    /// Test: `agent_loop::tests::daily_driver_anthropic_model_marks_cache_breakpoints`,
842    /// `agent_loop::tests::daily_driver_bedrock_model_marks_cache_breakpoints`,
843    /// `agent_loop::tests::parity_mode_never_marks_cache_breakpoints`,
844    /// `agent_loop::tests::non_anthropic_model_never_marks_cache_breakpoints`.
845    fn prompt_cache_enabled(&self) -> bool {
846        self.config.mode == HarnessMode::DailyDriver
847            && crate::provider::provider_for(&self.config.model).supports_prompt_caching()
848    }
849
850    /// Convert the registry's raw JSON schemas into typed `ToolDefinition`s.
851    ///
852    /// Why: The registry emits OpenAI-format `serde_json::Value` schemas, but
853    /// `ChatRequest.tools` is typed as `Vec<ToolDefinition>`; this bridges the
854    /// two without forcing every tool to know about the request type. The
855    /// `self.config.mode` branch (#2059) is the tool-schema CONSUMPTION POINT
856    /// for P1B's token-efficiency work: `HarnessMode::Parity` must forever
857    /// return the registry's full schema set verbatim (parity-spec D2 requires
858    /// byte-identical schemas across models); `HarnessMode::DailyDriver` is
859    /// where a future deferred/metadata-only schema set will be substituted.
860    /// Both arms are identical in M1 — no such set exists yet.
861    /// What: Deserialises each schema value; a schema that fails to parse is
862    /// dropped (a malformed schema must not abort the run) but logged with
863    /// `tracing::warn!` — including the offending tool's name (best-effort from
864    /// the raw schema) and the parse error — so a misconfigured tool that is
865    /// never advertised to the model is diagnosable rather than silent.
866    /// Test: `agent_loop::tests::two_turn_flow_completes` advertises a real tool
867    /// schema through this path; `agent_loop::tests::tool_definitions_identical_across_modes_in_m1`
868    /// pins the #2059 "no behavioural difference yet" contract.
869    fn tool_definitions(&self) -> Vec<ToolDefinition> {
870        let schemas = match self.config.mode {
871            HarnessMode::Parity => self.registry.schemas(),
872            // P1B hooks in here: a deferred/metadata-only schema set. Full
873            // schemas until then (#2059 M1 scope).
874            HarnessMode::DailyDriver => self.registry.schemas(),
875        };
876        schemas
877            .into_iter()
878            .filter_map(
879                |v| match serde_json::from_value::<ToolDefinition>(v.clone()) {
880                    Ok(def) => Some(def),
881                    Err(e) => {
882                        let name = schema_tool_name(&v);
883                        tracing::warn!(
884                            "dropping unparseable tool schema (tool={name}): {e}; raw schema: {v}"
885                        );
886                        None
887                    }
888                },
889            )
890            .collect()
891    }
892}
893
894/// Mark the LAST tool definition with an ephemeral prompt-cache breakpoint
895/// (#2156).
896///
897/// Why: Anthropic caches everything up to and including a `cache_control`
898/// breakpoint as one prefix; tools render first on the wire, so marking only
899/// the last tool caches the entire (byte-stable) tools array as a unit —
900/// matching `block/goose`'s verified OpenRouter provider.
901/// What: No-op on an empty slice; otherwise sets
902/// `schemas.last_mut().function.cache_control = Some(CacheControl::ephemeral())`.
903/// Test: `agent_loop::tests::daily_driver_anthropic_model_marks_cache_breakpoints`.
904fn mark_cache_breakpoint_on_tools(schemas: &mut [ToolDefinition]) {
905    if let Some(last) = schemas.last_mut() {
906        last.function.cache_control = Some(CacheControl::ephemeral());
907    }
908}
909
910/// Mark the system-role message with an ephemeral prompt-cache breakpoint
911/// (#2156).
912///
913/// Why: The system prompt is the second (and, combined with the tools
914/// breakpoint, final) segment of the byte-stable prefix `build_request`
915/// resends every turn; marking it caches tools+system together as OpenRouter
916/// renders tools before the system message on the wire.
917/// What: Finds the first `role == "system"` entry (there is always exactly
918/// one, from `Transcript::seed`) and sets its `cache_control`; no-op if none
919/// is found.
920/// Test: `agent_loop::tests::daily_driver_anthropic_model_marks_cache_breakpoints`.
921fn mark_cache_breakpoint_on_system(messages: &mut [ChatMessage]) {
922    if let Some(system) = messages.iter_mut().find(|m| m.role == "system") {
923        system.cache_control = Some(CacheControl::ephemeral());
924    }
925}
926
927/// Mark the last two non-system messages with an ephemeral prompt-cache
928/// breakpoint, rolling the cached prefix forward each turn (Bedrock
929/// history-cache follow-up to #2260).
930///
931/// Why: The tools+system prefix `mark_cache_breakpoint_on_tools`/
932/// `mark_cache_breakpoint_on_system` mark is small and static — the growing
933/// transcript is the dominant token cost. A live cost-proof of #2260
934/// as-merged showed cache_read staying 0 and ~452K fresh tokens/run on L1
935/// because nothing ever marked the history: every turn re-sent the full
936/// conversation as fresh input. Marking the LAST TWO non-system messages
937/// (rather than just the last one) mirrors opencode's verified
938/// `final.slice(-2)` pattern and guards against a single turn appending more
939/// content blocks than Bedrock's ~20-block cache lookback window covers — if
940/// only the very last message were marked and it alone exceeded that window,
941/// the previous turn's cache write would fall outside it and never hit.
942/// Uses breakpoint slots 3+4 of Bedrock's 4-per-request cachePoint budget
943/// (slots 1+2 are tools + system).
944/// Caveat: the OpenRouter/Anthropic-passthrough serializer
945/// (`llm::message::ChatMessage::serialize`) drops `cache_control` when a
946/// message has `content: None` (e.g. an assistant turn that is only
947/// `tool_calls`). Marking the last two messages already mitigates this in
948/// practice (at least one of the two usually carries text content); the
949/// Bedrock Converse path (`llm::bedrock::convert`) does not go through that
950/// serializer and is unaffected.
951/// What: Collects the indices of all non-system messages, then sets
952/// `cache_control` on the last (up to) two of them, in original order.
953/// No-op when there are zero or one non-system messages (the loop still
954/// marks whatever is present).
955/// Test: `agent_loop::tests::daily_driver_bedrock_model_marks_cache_breakpoints`.
956fn mark_cache_breakpoint_on_history(messages: &mut [ChatMessage]) {
957    let idxs: Vec<usize> = messages
958        .iter()
959        .enumerate()
960        .filter(|(_, m)| m.role != "system")
961        .map(|(i, _)| i)
962        .collect();
963    for &i in idxs.iter().rev().take(2) {
964        messages[i].cache_control = Some(CacheControl::ephemeral());
965    }
966}
967
968/// Best-effort extraction of a tool's name from its raw OpenAI-format schema.
969///
970/// Why: When a schema fails to deserialise into `ToolDefinition`, the warning is
971/// far more actionable if it names the offending tool; pulling `function.name`
972/// out of the still-valid JSON gives operators a handle even though the full
973/// typed parse failed.
974/// What: Reads `schema["function"]["name"]` as a string, falling back to
975/// `"<unknown>"` when the path is absent or non-string.
976/// Test: `agent_loop::tests::schema_tool_name_extracts_or_falls_back`.
977fn schema_tool_name(schema: &Value) -> &str {
978    schema
979        .get("function")
980        .and_then(|f| f.get("name"))
981        .and_then(Value::as_str)
982        .unwrap_or("<unknown>")
983}
984
985/// Notify a [`ToolEventSink`] of one tool dispatch's outcome (#2056).
986///
987/// Why: Maps `ToolResult`'s three real states onto the sink's two completion
988/// hooks: a non-recoverable (`is_fatal`) error is exceptional — `tool_error` —
989/// while success and a recoverable error are both ordinary completions
990/// distinguished by `success`, matching #2055's `ToolFinished{success}`/
991/// `ToolError` taxonomy split.
992/// What: `is_fatal()` -> `tool_error`; otherwise -> `tool_finished(!is_error())`.
993/// Test: `agent_loop::tests::sink_receives_started_then_finished_in_order`,
994/// `sink_receives_tool_error_for_fatal_failures`.
995async fn notify_result(sink: &dyn ToolEventSink, call_id: &str, tool: &str, result: &ToolResult) {
996    if result.is_fatal() {
997        sink.tool_error(call_id, tool, result.content()).await;
998    } else {
999        sink.tool_finished(call_id, tool, !result.is_error(), result.content())
1000            .await;
1001    }
1002}
1003
1004/// Accrue one response's token usage into the collector as a phase record.
1005///
1006/// Why: Cost/usage tracking across the run is a hard requirement; recording each
1007/// chat call as a phase keeps per-turn accounting visible in the perf record.
1008/// What: Clones the response's usage block into `TokenUsage` and records a phase
1009/// keyed by `PERF_PHASE` against the configured model.
1010/// Test: `agent_loop::tests::usage_accrues_across_turns`.
1011fn accrue_usage(perf: &mut PerfCollector, model: &str, response: &ChatResponse) {
1012    let usage = response.clone().token_usage();
1013    perf.record_phase(PERF_PHASE, 0, model, &usage);
1014}
1015
1016/// Rewrite `output.content` to only the assistant text produced SINCE `mark`
1017/// (#2344).
1018///
1019/// Why: `AgentLoop::run_with_transcript` scopes a persistent-session run's
1020/// reported output to just its own new turns — see that method's docs.
1021/// What: No-op when `output.summary` is `Some` (an explicit `finish_task`
1022/// completion's structured summary must never be overwritten by the plain
1023/// assistant-text join). Otherwise sets `output.content =
1024/// transcript.assistant_text_since(mark)`.
1025/// Test: `agent_loop::tests::run_with_transcript_scopes_output_to_new_turns`,
1026/// `agent_loop::tests::run_with_transcript_does_not_clobber_finish_task_summary`.
1027fn scope_output_to_new_turns(output: &mut AgentOutput, transcript: &Transcript, mark: usize) {
1028    if output.summary.is_none() {
1029        output.content = transcript.assistant_text_since(mark);
1030    }
1031}
1032
1033/// Assemble an `AgentOutput` from the current transcript and perf totals.
1034///
1035/// Why: Both the success path and the two abort paths need to produce the same
1036/// shape of output (final text + accumulated usage); centralising it avoids
1037/// drift between them.
1038/// What: Uses the transcript's joined assistant text as `content` and the perf
1039/// record's totals as `usage`.
1040/// Test: Exercised by every loop test via `run`.
1041fn build_output(transcript: &Transcript, perf: &PerfCollector) -> AgentOutput {
1042    let record = perf.build_record();
1043    let totals = &record.totals;
1044    let mut output = AgentOutput::from_content(transcript.assistant_text());
1045    output.usage = crate::perf::TokenUsage::new(
1046        totals.prompt_tokens,
1047        totals.completion_tokens,
1048        totals.cache_read_tokens,
1049        totals.cache_creation_tokens,
1050    );
1051    output
1052}
1053
1054/// Assemble the final `AgentOutput` from an explicit `finish_task` call (#2072).
1055///
1056/// Why: An explicit `finish_task` call carries a deterministic, structured
1057/// completion report the model built on purpose — reusing that report as the
1058/// loop's final output (rather than falling back to whatever prose the
1059/// transcript happens to contain) is the entire point of §5.8's "-20 to -30%
1060/// per agent output; deterministic, no prose interpretation" impact claim.
1061/// What: Starts from the same usage/content baseline as [`build_output`], then
1062/// — if `finish_args` deserialises into a `FinishTaskArgs` (it always should,
1063/// since `dispatch_all` only calls this after a successful `finish_task`
1064/// dispatch, which itself required a successful deserialisation) — overwrites
1065/// `content` with [`crate::tools::render_finish_summary`], sets `summary` to
1066/// the model's own one-line `summary` field, and (#2683) records the reported
1067/// `status` in `finish_status` so a delegating caller can distinguish an
1068/// explicit successful completion from any other termination. On the
1069/// (should-be-unreachable) deserialisation failure, falls back to the
1070/// transcript-derived content `build_output` already computed, rather than
1071/// panicking.
1072/// Test: `agent_loop::tests::explicit_finish_task_terminates_loop_with_structured_summary`.
1073fn build_finish_output(
1074    transcript: &Transcript,
1075    perf: &PerfCollector,
1076    finish_args: &Value,
1077) -> AgentOutput {
1078    let mut output = build_output(transcript, perf);
1079    if let Ok(parsed) = serde_json::from_value::<FinishTaskArgs>(finish_args.clone()) {
1080        output.summary = Some(parsed.summary.clone());
1081        output.content = crate::tools::render_finish_summary(&parsed);
1082        output.finish_status = Some(parsed.status);
1083    }
1084    output
1085}