Skip to main content

trusty_code/agent_loop/
error.rs

1//! Error type for the multi-turn agent loop.
2//!
3//! Why: The loop has five distinct failure modes that callers handle
4//! differently — an LLM transport/API failure (usually fatal), exhausting the
5//! turn budget (recoverable: a partial transcript is still useful), the
6//! wall-clock timeout firing (also carries partial work), (#2056)
7//! cooperative cancellation via `AgentLoop::with_cancel_flag` (a
8//! `session.cancel` on an in-flight daemon-driven run), and (#2265 fix #5)
9//! an external stop signal firing via `AgentLoop::with_stop_signal` (e.g. the
10//! `run_task` PM loop refusing to issue another `delegate_to_agent` call once
11//! `run_task::redelegation::RedelegationCapSignal` has latched). A structured
12//! enum lets callers branch without string-matching, and every abort variant
13//! carries the partial `AgentOutput` so no work is lost.
14//! What: Defines `AgentLoopError` with `Llm`, `TurnCapExceeded`, `Timeout`,
15//! `Cancelled`, and `StoppedBySignal` variants, deriving `thiserror::Error`.
16//! Test: `agent_loop::tests::turn_cap_returns_partial_transcript` asserts the
17//! `TurnCapExceeded` variant carries the accumulated transcript;
18//! `cancel_flag_aborts_before_next_turn` covers `Cancelled`;
19//! `stop_signal_aborts_before_next_turn` covers `StoppedBySignal`.
20
21use thiserror::Error;
22
23use crate::llm::InferenceError;
24use crate::tools::AgentOutput;
25
26/// Failure modes of `AgentLoop::run`.
27///
28/// Why: Distinguishes a hard LLM failure from the two budget-exhaustion paths
29/// so callers can decide whether to retry, surface partial output, or abort.
30/// What: `Llm` wraps the underlying `InferenceError`; `TurnCapExceeded` and `Timeout`
31/// each carry the partial `AgentOutput` accumulated up to the point the limit
32/// fired.
33/// Test: Constructed and matched in `agent_loop::tests`.
34#[derive(Debug, Error)]
35pub enum AgentLoopError {
36    /// An LLM chat call failed (transport, API, or deserialisation error).
37    ///
38    /// Why: Network/API failures are typically not recoverable within the loop;
39    /// the caller decides whether to retry the whole run.
40    /// What: Wraps the source `InferenceError`.
41    #[error("LLM call failed: {0}")]
42    Llm(#[from] InferenceError),
43
44    /// The configured `max_turns` budget was exhausted before the model stopped.
45    ///
46    /// Why: Long tool-call chains can loop without converging; capping turns
47    /// bounds cost. The partial transcript is still returned so the caller sees
48    /// how far the run got.
49    /// What: Carries the `AgentOutput` assembled from the turns that completed.
50    ///
51    /// Note: the `partial` output is for INSPECTION / diagnostics ONLY. The cap
52    /// can fire mid-turn — e.g. on an assistant turn that requested tool calls
53    /// whose results were never appended — so the transcript may be internally
54    /// inconsistent (dangling tool calls, no final answer). It is NOT safe to
55    /// replay against an LLM or to resume from; treat it as a snapshot.
56    #[error("turn cap of {max_turns} exceeded; returning partial transcript")]
57    TurnCapExceeded {
58        /// The configured turn limit that was hit.
59        max_turns: u32,
60        /// Partial output accumulated before the cap fired.
61        ///
62        /// Inspection/diagnostics only — see the variant note. May reflect an
63        /// incomplete turn (e.g. tool calls without matching results); do NOT
64        /// replay or resume from it.
65        partial: Box<AgentOutput>,
66    },
67
68    /// The wall-clock timeout elapsed before the loop finished.
69    ///
70    /// Why: A model that stalls or a tool that hangs must not block the caller
71    /// indefinitely; the timeout bounds total latency.
72    /// What: Carries the configured `timeout_secs` and the partial `AgentOutput`
73    /// assembled before the deadline.
74    ///
75    /// Note: the `partial` output is for INSPECTION / diagnostics ONLY. The
76    /// deadline can elapse at any point — including between an assistant turn's
77    /// tool calls and their results — so the transcript may be internally
78    /// inconsistent (dangling tool calls, no final answer). It is NOT safe to
79    /// replay against an LLM or to resume from; treat it as a snapshot.
80    #[error("wall-clock timeout of {timeout_secs}s elapsed; returning partial transcript")]
81    Timeout {
82        /// The configured timeout in seconds that elapsed.
83        timeout_secs: u64,
84        /// Partial output accumulated before the deadline.
85        ///
86        /// Inspection/diagnostics only — see the variant note. May reflect an
87        /// incomplete turn (e.g. tool calls without matching results); do NOT
88        /// replay or resume from it.
89        partial: Box<AgentOutput>,
90    },
91
92    /// The loop's `with_cancel_flag` cancellation flag was observed set
93    /// (#2056: `session.cancel` on an in-flight daemon-driven run).
94    ///
95    /// Why: `session.cancel` must stop an in-flight task cooperatively rather
96    /// than aborting the process or leaking the background task. The flag is
97    /// checked once per turn boundary (before the next LLM call) — per the
98    /// vision spec §12 (11.6), cancellation is NOT instantaneous: a tool call
99    /// already in flight always completes first.
100    /// What: Carries the partial `AgentOutput` assembled before cancellation
101    /// was observed, for the same inspection-only purpose as the other two
102    /// abort variants.
103    #[error("cancelled; returning partial transcript")]
104    Cancelled {
105        /// Partial output accumulated before cancellation was observed.
106        ///
107        /// Inspection/diagnostics only — see the variant note on the other
108        /// abort arms. Do NOT replay or resume from it.
109        partial: Box<AgentOutput>,
110    },
111
112    /// The loop's `with_stop_signal` external stop condition was observed
113    /// `true` at a turn boundary (#2265 fix #5).
114    ///
115    /// Why: A caller may know, independently of this loop's own turn/timeout
116    /// budget, that continuing is pointless — e.g. `run_task`'s PM loop shares
117    /// a `RedelegationCapSignal` with the engineer-delegation retry decorator;
118    /// once that cap latches, every further `delegate_to_agent` call is a
119    /// guaranteed dead end, so burning the PM's remaining turns issuing them
120    /// (previously bounded only by `AgentLoopConfig::max_turns`) wasted up to
121    /// 7 turns per run in the bake-off L1 evidence for zero additional
122    /// engineer work. Checking the signal at the SAME turn boundary as the
123    /// (#2056) cancellation flag — before the next `chat` call, never
124    /// mid-tool-call — stops the loop the turn AFTER the condition becomes
125    /// true, without dropping any in-flight tool dispatch.
126    /// What: Carries the partial `AgentOutput` assembled before the signal
127    /// was observed, for the same inspection-only purpose as the other abort
128    /// variants.
129    #[error("external stop signal observed; returning partial transcript")]
130    StoppedBySignal {
131        /// Partial output accumulated before the stop signal was observed.
132        ///
133        /// Inspection/diagnostics only — see the variant note on the other
134        /// abort arms. Do NOT replay or resume from it.
135        partial: Box<AgentOutput>,
136    },
137}
138
139impl AgentLoopError {
140    /// Mutable access to the partial `AgentOutput` carried by every abort
141    /// variant (#2344).
142    ///
143    /// Why: `AgentLoop::run_with_transcript` needs to rewrite `content` on
144    /// whichever `AgentOutput` a run produced — success or any partial-abort
145    /// variant — so a persistent-session run's reported output is scoped to
146    /// just its own new turns (see `Transcript::assistant_text_since`'s
147    /// docs), without duplicating that match arm-by-arm at the call site.
148    /// What: `Some(&mut partial)` for every abort variant; `None` for `Llm`,
149    /// which carries no partial output at all.
150    /// Test: `agent_loop::tests::run_with_transcript_scopes_partial_output_on_turn_cap`.
151    pub(crate) fn partial_output_mut(&mut self) -> Option<&mut AgentOutput> {
152        match self {
153            AgentLoopError::TurnCapExceeded { partial, .. }
154            | AgentLoopError::Timeout { partial, .. }
155            | AgentLoopError::Cancelled { partial }
156            | AgentLoopError::StoppedBySignal { partial } => Some(partial),
157            AgentLoopError::Llm(_) => None,
158        }
159    }
160}