agent_abstraction/error.rs
1//! The one error type every fallible call in this crate returns.
2//!
3//! Each variant is a case a caller has to branch on differently. A GUI shows
4//! [`Error::NotInstalled`] as an install prompt, [`Error::RateLimited`] as
5//! "wait", and [`Error::Unsupported`] as a programming mistake. Failures that
6//! need no branch collapse into [`Error::Spawn`] / [`Error::Store`].
7
8use std::time::Duration;
9
10use crate::agent::Agent;
11
12/// Result alias for this crate.
13pub type Result<T> = std::result::Result<T, Error>;
14
15/// Everything that can go wrong driving an agent CLI.
16#[derive(Debug, thiserror::Error)]
17#[non_exhaustive]
18pub enum Error {
19 /// The agent's binary is not on `PATH`. Carries the install command so a UI
20 /// can offer it directly instead of making the user go find it.
21 #[error("`{bin}` not found on PATH; install it: {hint}")]
22 NotInstalled {
23 /// The agent whose binary is missing.
24 agent: Agent,
25 /// The binary name that was looked up.
26 bin: String,
27 /// The documented install command.
28 hint: &'static str,
29 },
30
31 /// The child process could not be started, or its stdio could not be read.
32 #[error("failed to spawn `{bin}`: {source}")]
33 Spawn {
34 /// The binary that failed to start.
35 bin: String,
36 /// The underlying OS error.
37 #[source]
38 source: std::io::Error,
39 },
40
41 /// The run exceeded its deadline and the child was killed. Any output
42 /// captured before the kill is preserved so a caller can still show it.
43 #[error("`{bin}` exceeded its {} s timeout and was killed", timeout.as_secs())]
44 Timeout {
45 /// The binary that overran.
46 bin: String,
47 /// The deadline that was hit.
48 timeout: Duration,
49 /// Whatever the agent had printed before it was killed.
50 partial: String,
51 },
52
53 /// An interactive transport accepted a control request locally but never
54 /// acknowledged it. The agent process may still be alive, but the caller
55 /// must stop that run before retrying the input on a resumed session.
56 #[error(
57 "`{bin}` did not acknowledge interactive input within {} s; its transport may be stalled",
58 timeout.as_secs()
59 )]
60 ControlTimeout {
61 /// The agent binary whose transport stopped responding.
62 bin: String,
63 /// How long the delivery receipt was allowed to take.
64 timeout: Duration,
65 },
66
67 /// The agent ran to completion but exited non-zero.
68 #[error("`{bin}` exited with status {code}: {stderr}")]
69 Failed {
70 /// The binary that failed.
71 bin: String,
72 /// Its exit code, or `-1` when it died to a signal.
73 code: i32,
74 /// Its stderr, trimmed, for the message.
75 stderr: String,
76 },
77
78 /// The provider refused the request for quota reasons: a usage limit, a
79 /// rate limit, or an exhausted budget.
80 ///
81 /// This is deliberately its own variant and this crate never retries it
82 /// automatically. Backing off is the caller's decision and burying a
83 /// retry loop in here would turn a limit the provider set into something
84 /// the library quietly works around. See `docs/operating-limits.md`.
85 #[error("`{bin}` was rate limited or hit a usage limit: {message}")]
86 RateLimited {
87 /// The binary that was limited.
88 bin: String,
89 /// The provider's own wording, passed through unedited.
90 message: String,
91 },
92
93 /// The request asked an agent for something it cannot do headlessly:
94 /// forking on Codex, a named session on Copilot, an event stream on an
95 /// agent that only prints text.
96 ///
97 /// Always an error, never a silent downgrade: a caller that asked to fork
98 /// and got a linear resume would corrupt the conversation it meant to
99 /// branch.
100 #[error("{agent} does not support {what}")]
101 Unsupported {
102 /// The agent that was asked.
103 agent: Agent,
104 /// The capability it lacks.
105 what: &'static str,
106 },
107
108 /// A named session already belongs to a different agent. Sessions cannot
109 /// migrate: the stored handle is only meaningful to the CLI that minted it.
110 #[error("session `{name}` belongs to {bound}, cannot resume it on {requested}")]
111 SessionConflict {
112 /// The caller's session name.
113 name: String,
114 /// The agent that created the session.
115 bound: Agent,
116 /// The agent the caller tried to use.
117 requested: Agent,
118 },
119
120 /// The session store could not be read or written.
121 #[error("session store I/O failed at {path}: {source}")]
122 Store {
123 /// The file or directory involved.
124 path: String,
125 /// The underlying OS error.
126 #[source]
127 source: std::io::Error,
128 },
129
130 /// The agent produced output this crate could not interpret: a missing
131 /// session id under a format that promises one, or unparseable JSON where
132 /// the contract requires it.
133 #[error("could not parse {agent} output: {detail}")]
134 Parse {
135 /// The agent whose output was unreadable.
136 agent: Agent,
137 /// What specifically was wrong.
138 detail: String,
139 },
140
141 /// The agent has no usable credentials.
142 ///
143 /// Its own category because the remedy is a specific human action rather
144 /// than anything about the request, and because it is easy to reach by
145 /// accident: [`crate::EnvPolicy::Minimal`] withholds the environment by
146 /// default, so a credential this crate does not know to pass through
147 /// presents as a login failure rather than a configuration one.
148 #[error("`{bin}` is not authenticated: {message}. To fix: {hint}")]
149 NotAuthenticated {
150 /// The agent that refused.
151 agent: Agent,
152 /// The binary that refused.
153 bin: String,
154 /// The provider's own wording, unedited.
155 message: String,
156 /// The command that resolves it.
157 hint: &'static str,
158 },
159
160 /// The agent ran, exited cleanly, and reported that the turn itself failed.
161 ///
162 /// Its own variant because the process succeeding says nothing about the
163 /// turn succeeding. An unknown model, a schema the provider rejects or an
164 /// upstream outage all arrive this way: exit code 0, with the failure
165 /// described in the output. Reporting that as `Ok` hands back an
166 /// [`crate::Outcome`] whose `text` is an error message, which a caller
167 /// checking only `Result::is_ok` will render as the answer.
168 ///
169 /// The same reasoning already applied to [`Error::NotAuthenticated`] and
170 /// [`Error::RateLimited`], which are also reported with a zero exit; this
171 /// covers everything else in that family.
172 #[error("{agent} reported a failed turn{}: {message}", status.map(|s| format!(" (status {s})")).unwrap_or_default())]
173 AgentError {
174 /// The agent that failed.
175 agent: Agent,
176 /// The binary that ran.
177 bin: String,
178 /// The provider's status code, where the agent reported one. A 404 is
179 /// typically an unknown model, a 400 a rejected request.
180 status: Option<u16>,
181 /// The agent's own description, unedited.
182 message: String,
183 },
184
185 /// The CLI rejected an argument this crate passed it.
186 ///
187 /// Almost always a version mismatch: the flag was verified against the
188 /// release named in [`crate::Agent::verified_version`] and the installed
189 /// one differs. Separated from [`Error::Failed`] because the remedy is
190 /// different: nothing about the request is wrong, the wrapper and the CLI
191 /// disagree. Run [`crate::Probe`] to confirm.
192 #[error(
193 "`{bin}` rejected an argument, which usually means its version differs from the one these flags were verified against: {detail}"
194 )]
195 FlagRejected {
196 /// The binary that refused.
197 bin: String,
198 /// Its own complaint, unedited.
199 detail: String,
200 },
201
202 /// The run was stopped by [`crate::Run::cancel`] or by dropping its handle.
203 ///
204 /// Not a fault: the caller asked for this. Distinguished from
205 /// [`Error::Interrupted`], which means the driver died unexpectedly, and
206 /// from [`Error::Timeout`], which is a deadline rather than a request.
207 #[error("the run of `{bin}` was cancelled")]
208 Cancelled {
209 /// The binary that was stopped.
210 bin: String,
211 },
212
213 /// A prompt, system prompt or raw argument too large for the command line,
214 /// on an agent with no way to deliver it off the argv.
215 ///
216 /// Returned rather than letting the OS reject the spawn with a bare
217 /// `E2BIG`, which says nothing about which input was the problem.
218 #[error(
219 "{what} is {size} bytes, over the {limit} byte command-line budget for {agent}, \
220 and it has no way to take it off the command line"
221 )]
222 CommandLineTooLarge {
223 /// The agent the request targeted.
224 agent: Agent,
225 /// Which input overflowed.
226 what: &'static str,
227 /// Its size in bytes.
228 size: usize,
229 /// The budget it exceeded.
230 limit: usize,
231 },
232
233 /// [`crate::stream`] was called outside a Tokio runtime.
234 ///
235 /// Spawning the driver task needs a runtime context. Reporting this rather
236 /// than letting `tokio::spawn` panic keeps the fallible signature honest.
237 #[error("no Tokio runtime is running; call this from within one")]
238 NoRuntime,
239
240 /// The task driving the run panicked or was cancelled, so there is no
241 /// outcome to report.
242 ///
243 /// Distinct from [`Error::Spawn`] on purpose: the process started fine, and
244 /// reporting this as a spawn failure would name the wrong cause. It is also
245 /// why this is not squeezed into an [`std::io::Error`], which a dropped
246 /// runtime task is not.
247 #[error("the run of `{bin}` was interrupted: {detail}")]
248 Interrupted {
249 /// The binary that was running.
250 bin: String,
251 /// Whether the task panicked or was cancelled.
252 detail: String,
253 },
254}
255
256impl Error {
257 /// Whether retrying this exact request later could plausibly succeed.
258 ///
259 /// True for quota and timeout failures; false for a missing binary, an
260 /// unsupported capability, or a session conflict, which need the caller to
261 /// change something first. This classifies; it does not retry. A caller
262 /// must stop the old run before retrying [`Error::ControlTimeout`].
263 #[must_use]
264 pub fn is_transient(&self) -> bool {
265 matches!(
266 self,
267 Error::RateLimited { .. } | Error::Timeout { .. } | Error::ControlTimeout { .. }
268 )
269 }
270
271 /// Whether this run was stopped because the caller asked, rather than
272 /// because anything went wrong. A UI should not show it as a failure.
273 #[must_use]
274 pub fn is_cancelled(&self) -> bool {
275 matches!(self, Error::Cancelled { .. })
276 }
277
278 /// Whether this failed because the agent has no usable credentials.
279 ///
280 /// Worth branching on in a UI: unlike most failures, the user can fix it,
281 /// and [`Error::NotAuthenticated`] carries the command that does.
282 #[must_use]
283 pub fn is_auth_failure(&self) -> bool {
284 matches!(self, Error::NotAuthenticated { .. })
285 }
286}