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