Skip to main content

agentmux_srv_core/agents/
failure_rules.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The rules `classify` tries, in order, to name a failure. A rule answers `Some` failure when the
5//! evidence is its cause, `None` when it is not.
6
7use super::*;
8
9/// What a classification rests on: the run's exit evidence and the text it left.
10pub(super) struct Evidence<'a> {
11    pub(super) exit_code: Option<i32>,
12    pub(super) signal: Option<i32>,
13    pub(super) result_frame: Option<&'a Value>,
14    pub(super) frame_reported_error: bool,
15    /// The stderr, and the terminal frame's error text after it.
16    pub(super) combined: String,
17    /// `combined`, lower-cased once for the keyword matches.
18    pub(super) hay: String,
19    /// The last lines of `combined`, kept as the failure's evidence.
20    pub(super) tail: String,
21}
22
23impl Evidence<'_> {
24    /// A failure of this class, carrying the exit evidence and the stderr tail.
25    fn failure(&self, code: FailureClass, title: &str, detail: &str, retryable: bool) -> AgentFailure {
26        build(code, title, detail, retryable, self.exit_code, self.signal, &self.tail)
27    }
28}
29
30type Rule = fn(&Evidence<'_>) -> Option<AgentFailure>;
31
32/// The rules, most specific first. Order matters: rate-limit and overload are checked
33/// before usage-limit because the server-side rate-limit message
34/// literally contains "not your usage limit".
35pub(super) const RULES: [Rule; 16] = [
36    turn_cap_frame,
37    killed,
38    rate_limited,
39    overloaded,
40    missing_account,
41    open_in_other_pane,
42    live_elsewhere,
43    agent_deleted,
44    ambient_home,
45    unprotected_config,
46    not_authenticated,
47    route_credits,
48    context_exceeded,
49    turn_cap_text,
50    usage_limit,
51    network,
52];
53
54/// The terminal frame says the turn cap was reached.
55fn turn_cap_frame(ev: &Evidence<'_>) -> Option<AgentFailure> {
56    // Explicit terminal-frame subtype: turn cap reached.
57    if ev.result_frame
58        .and_then(|f| f.get("subtype"))
59        .and_then(|v| v.as_str())
60        .is_some_and(|s| s.contains("max_turns"))
61    {
62        return Some(ev.failure(
63            FailureClass::MaxTurns,
64            "Hit the turn limit",
65            "The agent reached its configured `--max-turns` cap before finishing. Raise the cap or split the task.",
66            false,
67        ));
68    }
69    None
70}
71
72/// Killed by a signal (the OOM killer or an external stop).
73fn killed(ev: &Evidence<'_>) -> Option<AgentFailure> {
74    // Killed by a signal (OOM killer or external stop). 137 == 128 + SIGKILL(9).
75    if ev.signal.is_some() || ev.exit_code == Some(137) {
76        return Some(ev.failure(
77            FailureClass::Killed,
78            "Agent process was killed",
79            "Terminated by a signal — most often the OS out-of-memory killer or an external stop. Reduce concurrent load / memory pressure and retry.",
80            false,
81        ));
82    }
83    None
84}
85
86/// Server-side rate limit: transient, and not the account quota. A 429 that names the plan's own limit ("HTTP 429
87/// You've hit your 5-hour limit") is the quota, whatever the status says: it stays for `usage_limit`.
88fn rate_limited(ev: &Evidence<'_>) -> Option<AgentFailure> {
89    if names_plan_limit(&ev.hay) && !names_server_throttle(&ev.hay) {
90        return None;
91    }
92    if ev.hay.contains("rate limited")
93        || ev.hay.contains("temporarily limiting requests")
94        || ev.hay.contains("rate limit exceeded")
95        || ev.hay.contains("too many requests")
96        || ev.hay.contains("rate_limit")
97        || mentions_http_status(&ev.hay, "429")
98    {
99        return Some(ev.failure(
100            FailureClass::RateLimited,
101            "Rate-limited by the API",
102            "Server-side rate limit — transient, and not your account quota. Retry shortly; consider lowering parallelism.",
103            true,
104        ));
105    }
106    None
107}
108
109/// The API is overloaded (HTTP 529).
110fn overloaded(ev: &Evidence<'_>) -> Option<AgentFailure> {
111    if ev.hay.contains("overloaded") || mentions_http_status(&ev.hay, "529") {
112        return Some(ev.failure(
113            FailureClass::Overloaded,
114            "API temporarily overloaded",
115            "The API reported it is overloaded (HTTP 529). Transient — retry with backoff.",
116            true,
117        ));
118    }
119    None
120}
121
122/// The identity spawn gate refused: no account is bound.
123fn missing_account(ev: &Evidence<'_>) -> Option<AgentFailure> {
124    // The identity spawn gate's own refusal (identity/resolver/errors.rs's
125    // `SpawnGateError::MissingCredentials` Display impl — a deliberate,
126    // spec-owned wording per SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4_2026_07_14.md
127    // §2.2, not third-party CLI/API output, so matching on it is as stable
128    // as matching our own code). This never reaches the API at all — the
129    // spawn was refused before any CLI process existed to report a 401 —
130    // so it's checked separately from the `not_authenticated` rule with its own
131    // wording, but classifies the same way: no account bound is exactly as
132    // actionable as a rejected credential, and needs the same relogin UI.
133    // Before this, the message had no recognized keyword and fell through
134    // to `UnknownNonZero`, which offers only "Retry" — a retry can never
135    // succeed against a gate that blocks every respawn identically, so the
136    // agent pane got stuck showing a dead-end error with no way out.
137    // "in the armory" is the wording before the Armory became Connectors
138    // (SPEC_RETIRE_ARMORY_CONNECTORS_AND_KNOWLEDGE_PANES_2026_10_05.md §4.4);
139    // a failure recorded then still has to classify.
140    if ev.hay.contains("bind an account for this provider in connectors")
141        || ev.hay.contains("bind an account for this provider in the armory")
142    {
143        // codex P2 on PR #2413: this branch matches EVERY oauth-class
144        // provider's MissingCredentials refusal (Codex, Gemini, OpenClaw,
145        // Copilot — not just Claude), but a prior version of this message
146        // hardcoded "No Claude account is bound". Extract the provider id
147        // from the gate's own wording ("no credentials for {provider}: …")
148        // instead of assuming — falls back to generic phrasing if the
149        // extraction ever misses (wording drift in errors.rs), rather than
150        // asserting a specific, possibly wrong, provider name.
151        let provider_phrase = extract_spawn_gate_provider(&ev.combined)
152            .map(|p| format!("No {} account", capitalize_provider(&p)))
153            .unwrap_or_else(|| "No account".to_string());
154        return Some(ev.failure(
155            FailureClass::Auth,
156            "No account linked",
157            &format!(
158                "{provider_phrase} is bound to this agent — the spawn was refused before it could run. \
159                 Sign in to link one."
160            ),
161            false,
162        ));
163    }
164    None
165}
166
167/// Another pane of this AgentMux holds the agent.
168fn open_in_other_pane(ev: &Evidence<'_>) -> Option<AgentFailure> {
169    // Another pane of this AgentMux holds the agent (`held_elsewhere_error`).
170    // Checked before the instance refusal: both can name "another" holder.
171    if let Some(holder) = open_in_other_pane_holder(&ev.combined) {
172        let mut f = ev.failure(
173            FailureClass::OpenInOtherPane,
174            "Open in another pane",
175            "This agent is already open in another pane. Go there to keep working in it, or move it here: the other pane stops and this one resumes the same conversation.",
176            false,
177        );
178        f.holder_block_id = Some(holder);
179        return Some(f);
180    }
181    None
182}
183
184/// Another AgentMux instance holds the agent.
185fn live_elsewhere(ev: &Evidence<'_>) -> Option<AgentFailure> {
186    // A single-live-instance refusal (backend::agent_admission — our own
187    // wording, recognised by the same markers that module uses). Checked
188    // before the generic classes: its text is not provider output, and a
189    // Retry cannot succeed while the other instance holds the agent.
190    if crate::backend::agent_admission::is_admission_refusal(&ev.combined) {
191        let taken_over = ev.hay.contains("was taken over by another agentmux instance");
192        return Some(ev.failure(
193            FailureClass::LiveElsewhere,
194            if taken_over { "Taken over by another AgentMux instance" } else { "Running in another AgentMux instance" },
195            frame_or_stderr_line(&ev.combined),
196            false,
197        ));
198    }
199    None
200}
201
202/// The identity spawn gate refused: the pane's agent was deleted.
203fn agent_deleted(ev: &Evidence<'_>) -> Option<AgentFailure> {
204    // The identity spawn gate's deleted-agent refusal (identity/resolver/
205    // errors.rs's `SpawnGateError::AgentDeleted` Display — our own wording).
206    // Its own class, never Retry: the gate refuses every respawn the same
207    // way, so a Retry would be the same dead end as the `missing_account` rule.
208    if ev.hay.contains("was deleted, so this pane cannot start") {
209        return Some(ev.failure(
210            FailureClass::AgentDeleted,
211            "Agent was deleted",
212            "This pane's agent was deleted, so it cannot start. Close the pane, \
213             or go back to the picker and launch another agent in it.",
214            false,
215        ));
216    }
217    None
218}
219
220/// The identity spawn gate refused: the identity points at the personal login directory.
221fn ambient_home(ev: &Evidence<'_>) -> Option<AgentFailure> {
222    // The identity spawn gate's ambient-home-dir refusal (identity/resolver/
223    // errors.rs's `SpawnGateError::AmbientHomeDirNotAllowed` Display impl —
224    // same reasoning as the `missing_account` rule: this never
225    // reaches the API, and a bare "Retry" would be a dead end since the
226    // gate blocks every respawn identically until the identity is rebound.
227    if ev.hay.contains("instead of an isolated agentmux account") {
228        let provider_phrase = extract_ambient_home_provider(&ev.combined)
229            .map(|p| format!("This agent's {} identity", capitalize_provider(&p)))
230            .unwrap_or_else(|| "This agent's identity".to_string());
231        return Some(ev.failure(
232            FailureClass::Auth,
233            "Identity points at your personal login",
234            &format!(
235                "{provider_phrase} is bound directly to your personal CLI login \
236                 directory, which AgentMux no longer allows. Re-bind it to an \
237                 isolated account in Connectors \u{2192} Accounts, then retry."
238            ),
239            false,
240        ));
241    }
242    None
243}
244
245/// The identity spawn gate refused: the config directory could not be isolated.
246fn unprotected_config(ev: &Evidence<'_>) -> Option<AgentFailure> {
247    // The identity spawn gate's CLAUDE.md isolation-seed refusal
248    // (identity/resolver/errors.rs's `SpawnGateError::ClaudeMdSeedFailed`
249    // Display impl — same reasoning as the `missing_account` and `ambient_home` rules: this never
250    // reaches the API, so it needs its own title/detail instead of falling
251    // through to the generic UnknownNonZero fallback. ReAgent P2 on PR
252    // #2854 — added alongside the `ambient_home` rule but
253    // initially missed for this newer variant.
254    if ev.hay.contains("refusing to spawn with an unprotected config dir") {
255        let provider_phrase = extract_claude_md_seed_provider(&ev.combined)
256            .map(|p| format!("This agent's {} config directory", capitalize_provider(&p)))
257            .unwrap_or_else(|| "This agent's config directory".to_string());
258        return Some(ev.failure(
259            FailureClass::Auth,
260            "Could not isolate this agent's config",
261            &format!(
262                "{provider_phrase} could not be prepared for isolated use — the spawn was \
263                 refused rather than risk it silently reading your personal CLI config. \
264                 Retry, and check the directory's permissions if it persists."
265            ),
266            false,
267        ));
268    }
269    None
270}
271
272/// The API rejected the credentials.
273fn not_authenticated(ev: &Evidence<'_>) -> Option<AgentFailure> {
274    if ev.hay.contains("authentication_error")
275        || ev.hay.contains("authentication_failed")
276        || ev.hay.contains("invalid authentication")
277        || ev.hay.contains("invalid api key")
278        || ev.hay.contains("invalid x-api-key")
279        || ev.hay.contains("unauthorized")
280        || ev.hay.contains("please run /login")
281        // A login whose session ended: "Failed to authenticate: OAuth session expired and could not be
282        // refreshed", also as the cause of "Prompt is too long · automatic compaction failed: …".
283        || ev.hay.contains("failed to authenticate")
284        || ev.hay.contains("oauth session expired")
285        || mentions_http_status(&ev.hay, "401")
286    {
287        return Some(ev.failure(
288            FailureClass::Auth,
289            "Not authenticated",
290            "The API rejected the credentials (HTTP 401). Re-authenticate via the Identity tab or `claude /login`.",
291            false,
292        ));
293    }
294    None
295}
296
297/// The model route's key has no credits left (HTTP 402). Every agent on the route fails the same way until
298/// someone adds credits, so this is a `UsageLimit` with a title of its own (`ROUTE_CREDITS_TITLE`).
299fn route_credits(ev: &Evidence<'_>) -> Option<AgentFailure> {
300    if names_route_credits(&ev.hay) {
301        return Some(ev.failure(
302            FailureClass::UsageLimit,
303            ROUTE_CREDITS_TITLE,
304            "The model route this agent uses answered HTTP 402: its key has no credits left. Every agent on the route is stopped by it. Add credits to the route's key in the provider's account; messages wait and a turn tries again in a few minutes.",
305            false,
306        ));
307    }
308    None
309}
310
311/// The conversation outgrew the context window.
312fn context_exceeded(ev: &Evidence<'_>) -> Option<AgentFailure> {
313    // "Prompt is too long · automatic compaction failed: You've hit your weekly limit": the CLI
314    // couldn't compact because the account is out of quota, so the limit is the cause, and
315    // a move to an account with quota (failover) is what fixes it. It falls through to the `usage_limit` rule.
316    if !names_plan_limit(&ev.hay)
317        && (ev.hay.contains("model_context_window_exceeded")
318            || ev.hay.contains("prompt is too long")
319            || (ev.hay.contains("context") && (ev.hay.contains("exceed") || ev.hay.contains("window") || ev.hay.contains("too long"))))
320    {
321        return Some(ev.failure(
322            FailureClass::ContextExceeded,
323            "Context window exceeded",
324            "The conversation exceeded the model's context window. Clear or compact the agent's history and retry.",
325            false,
326        ));
327    }
328    None
329}
330
331/// The turn cap, named in the text.
332fn turn_cap_text(ev: &Evidence<'_>) -> Option<AgentFailure> {
333    if ev.hay.contains("max turns") || ev.hay.contains("max-turns") || ev.hay.contains("maximum number of turns") {
334        return Some(ev.failure(
335            FailureClass::MaxTurns,
336            "Hit the turn limit",
337            "The agent reached its configured `--max-turns` cap before finishing. Raise the cap or split the task.",
338            false,
339        ));
340    }
341    None
342}
343
344/// The plan or usage limit is reached.
345fn usage_limit(ev: &Evidence<'_>) -> Option<AgentFailure> {
346    // Claude's plan limits read "You've hit your weekly limit · resets …" (or
347    // "session limit", or "monthly spend limit · raise it at …"), with no
348    // "usage" in them.
349    if names_plan_limit(&ev.hay)
350        || ev.hay.contains("quota")
351        || ev.hay.contains("billing")
352        || ev.hay.contains("insufficient")
353    {
354        return Some(ev.failure(
355            FailureClass::UsageLimit,
356            "Usage limit reached",
357            "Your plan or usage limit appears to be reached. Check plan / billing — retrying won't help until it resets.",
358            false,
359        ));
360    }
361    None
362}
363
364/// A network error reached the API.
365fn network(ev: &Evidence<'_>) -> Option<AgentFailure> {
366    // Claude Code ends a turn whose retries ran out with "API Error:
367    // Connection refused — … (ECONNREFUSED)" when the network is down,
368    // or "Unable to connect to API (ConnectionRefused)" when nothing listens.
369    if ev.hay.contains("apiconnectionerror")
370        || ev.hay.contains("unable to connect to api")
371        || ev.hay.contains("connection error")
372        || ev.hay.contains("connection refused")
373        || ev.hay.contains("could not resolve")
374        || ev.hay.contains("econnreset")
375        || ev.hay.contains("econnrefused")
376        || ev.hay.contains("enotfound")
377        || ev.hay.contains("enetunreach")
378        || ev.hay.contains("ehostunreach")
379        || ev.hay.contains("etimedout")
380        || ev.hay.contains("network")
381        || ev.hay.contains("timed out")
382        || ev.hay.contains("timeout")
383        || ev.hay.contains("dns")
384    {
385        return Some(ev.failure(
386            FailureClass::Network,
387            "Network error reaching the API",
388            "A network/connection error occurred talking to the API. Check connectivity and retry.",
389            true,
390        ));
391    }
392    None
393}
394
395/// No rule named a cause: say what is known.
396pub(super) fn fallback(ev: &Evidence<'_>) -> AgentFailure {
397    // Fallbacks.
398    if ev.frame_reported_error {
399        return ev.failure(
400            FailureClass::UnknownNonZero,
401            "Agent reported an error",
402            "The agent reported a terminal error with no recognized cause. The raw output tail is included below.",
403            false,
404        );
405    }
406    if ev.exit_code == Some(0) {
407        return ev.failure(
408            FailureClass::NoOutput,
409            "Agent produced no output",
410            "The agent exited cleanly (code 0) but never produced a final result. Inspect the transcript / sidecar log.",
411            false,
412        );
413    }
414    ev.failure(
415        FailureClass::UnknownNonZero,
416        "Agent failed",
417        "The agent exited with a non-zero status and no recognized error. The raw stderr tail is included below.",
418        false,
419    )
420}