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