Skip to main content

orch/engine/runner/fallback/
mod.rs

1//! Error recovery and fallback strategies.
2//!
3//! Extracted from `runner/mod.rs`. Handles the `Err(agent_err)` arm of the
4//! parse result: error classification, model failover, free-model fallback,
5//! and agent rerouting.
6
7use crate::store;
8use crate::store::TaskStore;
9use std::collections::HashSet;
10use std::sync::Arc;
11
12use super::{agents, response};
13use crate::cmd_cache;
14use crate::engine;
15use crate::engine::cooldown;
16use crate::engine::cooldown::CreditExhaustionReason;
17
18/// Summarizes a rate limit error by extracting key information from Claude's API retry JSON.
19///
20/// Looks for the last `{"type":"system","subtype":"api_retry",...}` line (or a partial
21/// fragment containing `"subtype":"api_retry"`) and extracts `error_status`, `attempt`,
22/// `retry_delay_ms` to return a compact summary.
23/// Returns a compact fallback if no api_retry JSON is found.
24///
25/// Exposed `pub(crate)` so the review pipeline (`engine::review`) reuses the same
26/// summariser as the task runner. Without this, review runs persisted raw
27/// api_retry JSON fragments into `task_runs.error` (issue #3149).
28pub(crate) fn summarize_rate_limit_error(raw_output: &str) -> String {
29    // Byte cap for the first-line fallback summary below
30    const FIRST_LINE_CAP: usize = 120;
31    // Find the last line containing "subtype":"api_retry"
32    // This handles both complete JSON objects and truncated fragments that begin
33    // mid-object (e.g. `,"subtype":"api_retry","attempt":5...`).
34    let last_api_retry_line = raw_output
35        .lines()
36        .rev()
37        .find(|line| line.contains("\"subtype\":\"api_retry\""));
38
39    if let Some(line) = last_api_retry_line {
40        return summarise_api_retry_line(line);
41    }
42
43    // No `"subtype":"api_retry"` marker but the payload may still be a truncated
44    // api_retry NDJSON fragment that lost the `"subtype"` key earlier in the
45    // stream. If any line contains the characteristic numeric fields
46    // (`error_status`, `attempt`, `retry_delay_ms`), summarise from that line
47    // instead of echoing the raw JSON into `task_runs.error` (issue #3149).
48    let api_retry_field_markers = ["\"error_status\":", "\"attempt\":", "\"retry_delay_ms\":"];
49    let field_line = raw_output
50        .lines()
51        .rev()
52        .find(|line| api_retry_field_markers.iter().any(|m| line.contains(m)));
53    if let Some(line) = field_line {
54        return summarise_api_retry_line(line);
55    }
56
57    // No api_retry JSON or field markers found — emit a compact first-line
58    // summary, never raw passthrough. Truncate to a tight byte cap so even
59    // long single-line provider payloads cannot bloat `task_runs.error`.
60    let first_line = raw_output.lines().next().unwrap_or(raw_output);
61    if first_line.len() > FIRST_LINE_CAP {
62        let cutoff = agents::truncate_at_char_boundary(first_line, FIRST_LINE_CAP);
63        let remaining = raw_output.len().saturating_sub(cutoff);
64        format!("{}... (+{} more chars)", &first_line[..cutoff], remaining)
65    } else {
66        first_line.to_string()
67    }
68}
69
70/// Extract `error_status`, `attempt`, and `retry_delay_ms` from a single
71/// `api_retry`-shaped JSON line (or fragment) and return a compact summary
72/// such as `"status=429 after 7 attempts (last delay 35s)"`. Falls back to
73/// `"status=… (api_retry fragment)"` when no numeric field is recoverable.
74fn summarise_api_retry_line(line: &str) -> String {
75    let error_status =
76        extract_json_field(line, "\"error_status\":").unwrap_or_else(|| "unknown".to_string());
77    let attempt = extract_json_field(line, "\"attempt\":").unwrap_or_else(|| "unknown".to_string());
78    let retry_delay_ms =
79        extract_json_field(line, "\"retry_delay_ms\":").unwrap_or_else(|| "0".to_string());
80
81    let has_field = error_status != "unknown"
82        || attempt != "unknown"
83        || (retry_delay_ms != "0" && retry_delay_ms != "unknown");
84
85    if has_field {
86        let retry_delay_s = retry_delay_ms.parse::<f64>().unwrap_or(0.0) / 1000.0;
87        #[expect(
88            clippy::cast_possible_truncation,
89            clippy::cast_sign_loss,
90            reason = "the saturating cast floors the delay to whole seconds"
91        )]
92        let retry_delay_s = retry_delay_s as u64;
93        format!("status={error_status} after {attempt} attempts (last delay {retry_delay_s}s)")
94    } else {
95        let status_hint = extract_json_field(line, "\"status\":")
96            .or_else(|| extract_json_field(line, "\"error\":"))
97            .unwrap_or_else(|| "429".to_string());
98        format!("status={status_hint} (api_retry fragment)")
99    }
100}
101
102/// Extracts a JSON field value as a string, handling both quoted strings and raw numbers.
103fn extract_json_field(json: &str, field: &str) -> Option<String> {
104    json.find(field).and_then(|start| {
105        let value_start = start + field.len();
106        let value_str = &json[value_start..];
107
108        // Handle quoted strings
109        if let Some(rest) = value_str.strip_prefix('"') {
110            let end = rest.find('"')?; // find closing quote
111            Some(rest[..end].to_string())
112        }
113        // Handle raw numbers (integers or floats)
114        else {
115            let end = value_str
116                .find(|c: char| !c.is_ascii_digit() && c != '.')
117                .unwrap_or(value_str.len());
118            let num_str = &value_str[..end];
119            num_str
120                .strip_suffix(',')
121                .map(ToString::to_string)
122                .or_else(|| Some(num_str.to_string()))
123        }
124    })
125}
126
127/// How `run()` should proceed after error handling.
128#[derive(Debug)]
129pub enum ErrorHandleResult {
130    /// Task was rerouted — `run()` should record metrics then return early.
131    EarlyReturn { status: String },
132    /// Normal failover applied (or task marked needs_review) — proceed to cleanup + metrics.
133    ///
134    /// `error` is the current run's attributed error message (e.g. "kimi timed out after 1801s").
135    /// Callers should pass this as `error_override` to `build_run_audit` so that stale
136    /// `last_error` values from a previous agent's run are not mis-attributed.
137    Continue { status: String, error: String },
138}
139
140/// Try to reroute the task to an untried free model.
141///
142/// Returns `Some(EarlyReturn { status: "new" })` if a free model was found and the
143/// task was rerouted, `None` otherwise (caller should fall through to normal failover).
144///
145/// - `exclude_models`: models to skip in addition to already-tried ones
146/// - `check_cooldowns`: whether to skip models currently in cooldown
147/// - `set_agent`: if `Some`, also overwrite the task's `agent` field
148/// - `apply_backoff`: whether to pace the reroute with `wait_for_fallback_backoff`
149/// - `reason_prefix`: prefix for the `last_error` message (free model name is appended)
150#[expect(
151    clippy::too_many_arguments,
152    reason = "each caller picks a different mix of reroute options"
153)]
154#[expect(
155    clippy::ref_option,
156    reason = "the store helpers it calls take the store as &Option"
157)]
158async fn try_free_model_reroute(
159    task_id: &str,
160    agent_name: &str,
161    agent_runner: &dyn agents::AgentRunner,
162    exclude_models: &[&str],
163    check_cooldowns: bool,
164    set_agent: Option<&str>,
165    apply_backoff: bool,
166    reason_prefix: &str,
167    store: &Option<Arc<TaskStore>>,
168    repo: &str,
169) -> Option<ErrorHandleResult> {
170    let free = agent_runner.free_models();
171    if free.is_empty() {
172        return None;
173    }
174    let tried_models: String = store::opt_store_get_task(store, repo, task_id)
175        .await
176        .map(|t| t.model_reroute_chain)
177        .unwrap_or_default();
178    let tried_set: HashSet<&str> = tried_models.split(',').filter(|s| !s.is_empty()).collect();
179    let next_free = free.iter().find(|m| {
180        !exclude_models.contains(&m.as_str())
181            && !tried_set.contains(m.as_str())
182            && (!check_cooldowns
183                || (!cooldown::is_agent_in_cooldown(agent_name)
184                    && !response::is_model_in_cooldown(agent_name, m)))
185    })?;
186    tracing::info!(task_id, model = %next_free, "{}", reason_prefix);
187    let new_tried = if tried_models.is_empty() {
188        next_free.clone()
189    } else {
190        format!("{tried_models},{next_free}")
191    };
192    let msg = format!("{reason_prefix} {next_free}");
193    let mut fields: Vec<(&str, serde_json::Value)> = vec![
194        ("model", serde_json::json!(next_free.clone())),
195        ("model_reroute_chain", serde_json::json!(new_tried)),
196        ("last_error", serde_json::json!(msg)),
197    ];
198    if let Some(agent) = set_agent {
199        fields.push(("agent", serde_json::json!(agent)));
200    }
201    if let Err(e) = store::store_set_result(store, repo, task_id, &fields).await {
202        tracing::warn!(task_id, err = %e, "try_free_model_reroute: failed to persist model update — not rerouting");
203        return None; // let caller fall through to normal failover
204    }
205    if apply_backoff {
206        response::wait_for_fallback_backoff(task_id, store, repo).await;
207    }
208    Some(ErrorHandleResult::EarlyReturn {
209        status: "new".to_string(),
210    })
211}
212
213/// Apply a vendor-provided future reset date as the model cooldown.
214///
215/// Skipped for credit exhaustion reasons other than billing cycle, which keep their agent-wide cooldowns.
216/// Returns true when the cooldown was set.
217async fn apply_vendor_reset_date(
218    agent_name: &str,
219    model_name: Option<&str>,
220    message: &str,
221) -> bool {
222    let Some(model) = model_name else {
223        return false;
224    };
225    match cooldown::detect_credit_exhaustion(message) {
226        None | Some(CreditExhaustionReason::BillingCycleExhausted) => {}
227        Some(_) => return false,
228    }
229    match cooldown::parse_retry_at(message) {
230        Some(until) if until > chrono::Utc::now().timestamp() => {
231            cooldown::set_model_cooldown_until(agent_name, model, until).await;
232            true
233        }
234        _ => false,
235    }
236}
237
238/// Handle an agent error: classify it, attempt recovery strategies, and update store.
239///
240/// Returns `Ok(ErrorHandleResult::EarlyReturn)` when the task was rerouted and
241/// `run()` should record metrics and return immediately (skipping tmux cleanup).
242/// Returns `Ok(ErrorHandleResult::Continue)` when `run()` should proceed to cleanup.
243#[expect(
244    clippy::too_many_arguments,
245    reason = "the error path needs the task, agent, model and store context together"
246)]
247pub async fn handle_error(
248    task_id: &str,
249    agent_err: &agents::AgentError,
250    agent_name: &str,
251    agent_runner: &dyn agents::AgentRunner,
252    model_name: Option<&str>,
253    complexity: Option<&str>,
254    new_attempts: u32,
255    store: &Option<Arc<TaskStore>>,
256    repo: &str,
257) -> anyhow::Result<ErrorHandleResult> {
258    tracing::warn!(
259        task_id,
260        agent = agent_name,
261        error = %agent_err,
262        "agent error, attempting recovery"
263    );
264
265    // Map AgentError to RetryableError for handle_failover(). credit_recorded
266    // skips the generic failure_count bump for already-recorded credit errors
267    let mut credit_recorded = false;
268    let (retryable, error_msg) = match agent_err {
269        agents::AgentError::RateLimit { message, .. } => {
270            let is_provider_returned_error = message
271                .to_ascii_lowercase()
272                .contains("provider returned error");
273            // Check for credit exhaustion - these require longer agent-wide cooldowns.
274            // For all other rate limits, record both the agent-level and model-level
275            // cooldowns immediately so the router can observe them before any concurrent
276            // tasks start their runs. handle_failover() also records the cooldown later,
277            // but setting it here means the in-memory map is updated right away — without
278            // this, concurrent dispatches that check cooldowns between now and
279            // handle_failover() will see no cooldown and waste another run against the
280            // same rate-limited model.
281            //
282            // Setting BOTH cooldowns is critical: the router's model selection
283            // (model_for_complexity) checks is_model_in_cooldown(agent, model) which
284            // uses the agent:model key, so a model-level cooldown is needed to prevent
285            // the same model from being re-selected even when the agent-level cooldown
286            // is set. Without the model-level cooldown, the model continues to be
287            // picked and fails repeatedly (issue #2153).
288            // Track whether the quota is model-scoped (BillingCycleExhausted + known model).
289            // When true we return ModelUnavailable so handle_failover skips the
290            // agent-level failure counter — the agent itself is healthy, only the
291            // specific model's plan quota was exhausted (issue #3382).
292            let mut billing_cycle_model_scoped = false;
293
294            if apply_vendor_reset_date(agent_name, model_name, message).await {
295                let reason = cooldown::detect_credit_exhaustion(message);
296                credit_recorded = reason.is_some();
297                billing_cycle_model_scoped =
298                    reason == Some(CreditExhaustionReason::BillingCycleExhausted);
299            } else if let Some(reason) = cooldown::detect_credit_exhaustion(message) {
300                credit_recorded = true;
301                // For billing cycle exhaustion where we know the specific model, apply
302                // model-level persistent cooldown only. The quota is scoped to that
303                // provider sub-model (e.g. github-copilot/gpt-5-mini), not the entire
304                // agent account, so an agent-wide cooldown would incorrectly block
305                // unrelated models on the same agent.
306                if reason == CreditExhaustionReason::BillingCycleExhausted {
307                    if let Some(model) = model_name {
308                        cooldown::record_persistent_model_failure(agent_name, model).await;
309                        billing_cycle_model_scoped = true;
310                    } else {
311                        cooldown::record_credit_exhaustion(agent_name, reason).await;
312                    }
313                } else {
314                    cooldown::record_credit_exhaustion(agent_name, reason).await;
315                }
316            } else if let (Some(model), Some(window_secs)) =
317                (model_name, cooldown::parse_relative_usage_window(message))
318            {
319                // Vendor-advertised relative usage window (e.g. "weekly (7-day)
320                // usage limit") is authoritative — apply a model-specific cooldown
321                // for that exact duration instead of the generic exponential
322                // backoff. This is the same window-detection the `needs_review`
323                // call site (cooldown::record_rate_limit()) already applies; this
324                // in-task failover path bypassed it entirely, undoing the
325                // #3572/#3574 fix for the most common rate-limit path (issue #3580).
326                cooldown::set_model_cooldown(
327                    agent_name,
328                    model,
329                    window_secs,
330                    "rate_limit_usage_window",
331                )
332                .await;
333                tracing::info!(
334                    task_id,
335                    agent = agent_name,
336                    model,
337                    window_secs,
338                    "relative usage window detected: applying model-specific cooldown"
339                );
340            } else {
341                cooldown::record_agent_failure_with_message(agent_name, message).await;
342                // Also record the model-specific cooldown so model_for_complexity skips it.
343                if let Some(model) = model_name {
344                    if is_provider_returned_error {
345                        cooldown::record_transient_model_failure(agent_name, model).await;
346                    } else {
347                        response::record_model_failure(agent_name, model).await;
348                    }
349                }
350            }
351            // Use ModelUnavailable when billing cycle is exhausted for a known model so
352            // handle_failover does not call record_agent_failure_with_message (which would
353            // set an unwanted agent-level cooldown). The agent's other models remain available.
354            let retryable = if billing_cycle_model_scoped {
355                response::RetryableError::ModelUnavailable
356            } else {
357                response::RetryableError::UsageLimit
358            };
359            (
360                retryable,
361                format!(
362                    "{agent_name} rate limit: {}",
363                    summarize_rate_limit_error(message)
364                ),
365            )
366        }
367        agents::AgentError::Auth { message } => {
368            // Check for credit exhaustion first — those need longer agent-wide cooldowns.
369            // For plain auth failures (expired key, wrong token, etc.) record both the
370            // agent-level and model-level cooldowns so the router can observe them before
371            // concurrent tasks start another run against the same unavailable model.
372            let mut billing_cycle_model_scoped = false;
373
374            if apply_vendor_reset_date(agent_name, model_name, message).await {
375                let reason = cooldown::detect_credit_exhaustion(message);
376                credit_recorded = reason.is_some();
377                billing_cycle_model_scoped =
378                    reason == Some(CreditExhaustionReason::BillingCycleExhausted);
379            } else if let Some(reason) = cooldown::detect_credit_exhaustion(message) {
380                credit_recorded = true;
381                // Billing cycle exhaustion scoped to a known model gets model-level
382                // persistent cooldown only — agent-wide cooldown would block unrelated models.
383                if reason == CreditExhaustionReason::BillingCycleExhausted {
384                    if let Some(model) = model_name {
385                        cooldown::record_persistent_model_failure(agent_name, model).await;
386                        billing_cycle_model_scoped = true;
387                    } else {
388                        cooldown::record_credit_exhaustion(agent_name, reason).await;
389                    }
390                } else {
391                    cooldown::record_credit_exhaustion(agent_name, reason).await;
392                }
393            } else {
394                cooldown::record_agent_failure_with_message(agent_name, message).await;
395                if let Some(model) = model_name {
396                    response::record_model_failure(agent_name, model).await;
397                }
398            }
399            // Use ModelUnavailable for model-scoped billing exhaustion so handle_failover
400            // does not set an agent-level failure cooldown (issue #3382).
401            let retryable = if billing_cycle_model_scoped {
402                response::RetryableError::ModelUnavailable
403            } else {
404                response::RetryableError::AuthError
405            };
406            (retryable, format!("{agent_name} auth error: {message}"))
407        }
408        agents::AgentError::Timeout { elapsed } => {
409            // A task time limit says the work was long, not that the model is
410            // unavailable. Retry without a model cooldown or rate_limits row
411            (
412                response::RetryableError::Timeout,
413                format!("{agent_name} timed out after {}s", elapsed.as_secs()),
414            )
415        }
416        agents::AgentError::Interrupted { message } => (
417            response::RetryableError::Interrupted,
418            format!("{agent_name} interrupted: {message}"),
419        ),
420        agents::AgentError::MissingTool { tool } => (
421            response::RetryableError::MissingTooling,
422            format!("missing tool: {tool}"),
423        ),
424        agents::AgentError::ModelUnavailable { model, message } => {
425            cooldown::record_model_unavailable(agent_name, model, message).await;
426
427            // Try next model before switching agent, unless the agent is cooled
428            // (an agent-wide cooldown must not be defeated by model substitution)
429            let agent_cooled = cooldown::is_agent_in_cooldown(agent_name);
430            let models = agent_runner.available_models();
431            let current_model = model_name.unwrap_or("");
432            let next_model = if agent_cooled {
433                None
434            } else {
435                models.iter().find(|m| {
436                    m.as_str() != current_model
437                        && m.as_str() != model
438                        && !response::is_model_in_cooldown(agent_name, m)
439                })
440            };
441            if let Some(next) = next_model {
442                tracing::info!(task_id, model = %next, "retrying with different model");
443                let msg = format!("model {model} unavailable, trying {next}");
444                if let Err(e) = store::store_set_result(
445                    store,
446                    repo,
447                    task_id,
448                    &[
449                        ("model", serde_json::json!(next.clone())),
450                        ("last_error", serde_json::json!(msg)),
451                    ],
452                )
453                .await
454                {
455                    tracing::warn!(task_id, err = %e, "failed to write model failover to store");
456                }
457                // Skip normal failover — we're retrying same agent with different model.
458                // Use "routed" (not "new") since agent/model are already stored;
459                // this avoids a redundant LLM re-routing cycle.
460                response::wait_for_fallback_backoff(task_id, store, repo).await;
461                return Ok(ErrorHandleResult::EarlyReturn {
462                    status: "routed".to_string(),
463                });
464            }
465
466            // No other standard models available — try free models for simple tasks
467            let is_simple = matches!(complexity, None | Some("simple"));
468            if is_simple
469                && let Some(result) = try_free_model_reroute(
470                    task_id,
471                    agent_name,
472                    agent_runner,
473                    &[current_model, model.as_str()],
474                    true,
475                    None,
476                    true,
477                    &format!("model {model} unavailable, trying free model"),
478                    store,
479                    repo,
480                )
481                .await
482            {
483                return Ok(result);
484            }
485
486            (
487                response::RetryableError::ModelUnavailable,
488                format!("model {model} unavailable"),
489            )
490        }
491        agents::AgentError::ContextOverflow { message } => {
492            // Context overflow is deterministic — the task's prompt/context is too large
493            // for this model's context window. Cycling through other agents would hit the
494            // same limit and waste API calls. Skip failover entirely and escalate
495            // immediately to needs_review so a human can intervene (e.g., split the task,
496            // reduce context, or manually assign a model with a larger context window).
497            let msg = format!("{agent_name} context overflow: {message}");
498            if let Err(e) = store::store_set_result(
499                store,
500                repo,
501                task_id,
502                &[("last_error", serde_json::json!(msg))],
503            )
504            .await
505            {
506                tracing::warn!(task_id, err = %e, "failed to write context_overflow last_error to store");
507            }
508            return Ok(ErrorHandleResult::EarlyReturn {
509                status: "needs_review".to_string(),
510            });
511        }
512        agents::AgentError::WaitingForInput { message } => {
513            // Requires human — skip failover, go straight to needs_review
514            let msg = format!("waiting for input: {message}");
515            if let Err(e) = store::store_set_result(
516                store,
517                repo,
518                task_id,
519                &[("last_error", serde_json::json!(msg))],
520            )
521            .await
522            {
523                tracing::warn!(task_id, err = %e, "failed to write waiting_for_input last_error to store");
524            }
525            return Ok(ErrorHandleResult::EarlyReturn {
526                status: "needs_review".to_string(),
527            });
528        }
529        agents::AgentError::PermissionDenied { message } => (
530            response::RetryableError::Failed,
531            format!("permission denied: {message}"),
532        ),
533        agents::AgentError::InvalidResponse { .. } => {
534            // Record model-specific cooldown so the same model that produced an
535            // unparseable response isn't immediately retried on the next task.
536            if let Some(model) = model_name {
537                response::record_model_failure(agent_name, model).await;
538            }
539            (
540                response::RetryableError::Failed,
541                format!("{agent_name} invalid response"),
542            )
543        }
544        agents::AgentError::AgentFailed { message } => {
545            // "Provider returned error" (opencode) and similar upstream failures.
546            // Record model+agent cooldowns so the router skips this model on retry,
547            // then route through handle_failover() to get proper reroute-chain
548            // tracking, exhaustion checks, and fallback pacing.
549            // Credit-shaped errors that escaped the Auth/RateLimit classifiers still
550            // need the credit cooldown and counter, not the generic 5 min backoff.
551            if let Some(reason) = cooldown::detect_credit_exhaustion(message) {
552                credit_recorded = true;
553                match model_name {
554                    Some(model) if reason == CreditExhaustionReason::BillingCycleExhausted => {
555                        cooldown::record_persistent_model_failure(agent_name, model).await;
556                    }
557                    _ => cooldown::record_credit_exhaustion(agent_name, reason).await,
558                }
559            } else {
560                if let Some(model) = model_name {
561                    response::record_model_failure(agent_name, model).await;
562                }
563                cooldown::record_agent_failure_with_message(agent_name, message).await;
564            }
565            (
566                response::RetryableError::Failed,
567                format!("{agent_name} failed: {message}"),
568            )
569        }
570        agents::AgentError::NetworkError { message } => {
571            // Transient connectivity failure — retry same agent without rerouting,
572            // but grow a dedicated streak counter so backoff keeps increasing.
573            // Use "routed" so it re-dispatches without a full re-routing cycle.
574            // After MAX_NETWORK_RETRIES consecutive network errors, escalate to
575            // needs_review so a human is notified rather than looping forever.
576            const MAX_NETWORK_RETRIES: u64 = 8;
577            let msg = format!("{agent_name} network error: {message}");
578            let retry_count = match store::store_increment(store, repo, task_id, "network_retries")
579                .await
580            {
581                Ok(count) => {
582                    tracing::info!(
583                        task_id,
584                        retry_count = count,
585                        agent = agent_name,
586                        "network retry scheduled"
587                    );
588                    count
589                }
590                Err(e) => {
591                    tracing::warn!(
592                        task_id,
593                        error = %e,
594                        "failed to increment network_retries — escalating to needs_review"
595                    );
596                    return Ok(ErrorHandleResult::Continue {
597                        status: "needs_review".to_string(),
598                        error: format!("{agent_name} network error (store unavailable): {message}"),
599                    });
600                }
601            };
602            if let Err(e) = store::store_set_result(
603                store,
604                repo,
605                task_id,
606                &[("last_error", serde_json::json!(msg))],
607            )
608            .await
609            {
610                tracing::warn!(task_id, err = %e, "failed to write network_error last_error to store");
611            }
612            if retry_count >= MAX_NETWORK_RETRIES {
613                tracing::warn!(
614                    task_id,
615                    retry_count,
616                    agent = agent_name,
617                    "network retries exhausted, escalating to needs_review"
618                );
619                return Ok(ErrorHandleResult::Continue {
620                    status: "needs_review".to_string(),
621                    error: msg,
622                });
623            }
624            // Apply backoff to pace retries
625            response::wait_for_fallback_backoff(task_id, store, repo).await;
626            return Ok(ErrorHandleResult::EarlyReturn {
627                status: "routed".to_string(),
628            });
629        }
630        agents::AgentError::StaleSession { session_id } => {
631            // Stale session errors only occur in the orch chat control session, not
632            // in task runners (tasks don't use --session-id / --resume). Treat as a
633            // generic agent failure so the task is retried from scratch.
634            (
635                response::RetryableError::Failed,
636                format!("{agent_name} stale session: {session_id}"),
637            )
638        }
639        agents::AgentError::ThinkingBlockConflict { message } => {
640            // Transient Anthropic API 400 — thinking blocks modified in multi-turn
641            // tool-use. Not a model capacity or rate-limit problem.
642            // Do NOT record failure counts or model/agent cooldowns.
643            // Pass ModelUnavailable so handle_failover skips agent failure recording
644            // while still updating the reroute chain to avoid re-selecting claude.
645            (
646                response::RetryableError::ModelUnavailable,
647                format!("{agent_name} thinking block conflict: {message}"),
648            )
649        }
650        agents::AgentError::Unknown { exit_code, message } => {
651            // Exit 0 with empty output is a silent failure (common with GitHub
652            // Copilot models in opencode).  Record a model-specific cooldown so
653            // the same model is not retried on every subsequent task.
654            // Also matches when message == "empty-output-exit0" (from classify_from_text
655            // or the direct empty-output branch in mod.rs).
656            if *exit_code == 0
657                && (message.is_empty()
658                    || message == "empty-output-exit0"
659                    || message.starts_with("empty-output-exit0:"))
660            {
661                if let Some(m) = model_name {
662                    // A stopped session also exits 0 with no output, so the backoff stays short
663                    cooldown::record_transient_model_failure(agent_name, m).await;
664                }
665                // Before falling through to handle_failover() (which tries claude/codex),
666                // check whether this agent has any free models that haven't been tried yet.
667                // Silent exit-0 is usually model/provider-specific; retrying other free
668                // models first avoids wasting paid claude/codex failovers.
669                let current = model_name.unwrap_or("");
670                if let Some(result) = try_free_model_reroute(
671                    task_id,
672                    agent_name,
673                    agent_runner,
674                    &[current],
675                    true,
676                    Some("opencode"),
677                    true,
678                    "silent exit 0, retrying with free model",
679                    store,
680                    repo,
681                )
682                .await
683                {
684                    return Ok(result);
685                }
686            }
687
688            // Handle JSON cost telemetry in stdout for non-zero exits
689            // If the message looks like Claude's cost JSON, replace with a generic message
690            let error_message = if *exit_code != 0 && message.contains("\"costUSD\":") {
691                // Extract just the essential info: exit code and that cost telemetry was present
692                format!(
693                    "{agent_name} exited with non-zero status (cost telemetry in stdout, no error message)"
694                )
695            } else {
696                format!("{agent_name} exit {exit_code}: {message}")
697            };
698
699            (response::RetryableError::Failed, error_message)
700        }
701    };
702
703    // Timeouts and interrupts clear the agent and skip the rate_limits row
704    if matches!(
705        retryable,
706        response::RetryableError::Timeout | response::RetryableError::Interrupted
707    ) && let Err(e) = store::store_set_result(
708        store,
709        repo,
710        task_id,
711        &[
712            ("agent", serde_json::json!("")),
713            ("last_error", serde_json::json!(error_msg.clone())),
714        ],
715    )
716    .await
717    {
718        tracing::warn!(task_id, err = %e, "failed to write timeout agent clear to store");
719    }
720
721    // Record rate limit in store (sqlx). Timeouts and interrupted runs are
722    // not usage limits, so they must not write a row
723    {
724        let error_type_str = match retryable {
725            response::RetryableError::UsageLimit => Some("rate"),
726            response::RetryableError::AuthError => Some("auth"),
727            response::RetryableError::Timeout | response::RetryableError::Interrupted => None,
728            _ => Some("error"),
729        };
730        if let Some(limit_type) = error_type_str
731            && let Some(s) = store
732            && let Err(e) = s
733                .record_rate_limit(agent_name, limit_type, Some(task_id))
734                .await
735        {
736            tracing::warn!(task_id, agent = %agent_name, err = %e, "failed to persist rate_limit event — router health check may miss this signal");
737        }
738    }
739
740    // Try free models as last resort before giving up
741    let chain = response::get_reroute_chain(task_id, store, repo).await;
742    let available: Vec<String> = engine::configured_agents()
743        .into_iter()
744        .filter(|a| cmd_cache::command_exists(a))
745        .collect();
746
747    let all_agents_tried = {
748        let chain_set: HashSet<&str> = if chain.is_empty() {
749            HashSet::new()
750        } else {
751            chain.split(',').collect()
752        };
753        !available
754            .iter()
755            .any(|a| a.as_str() != agent_name && !chain_set.contains(a.as_str()))
756    };
757
758    let is_simple = matches!(complexity, None | Some("simple"));
759    if all_agents_tried && is_simple {
760        // All agents exhausted — try free models via opencode (only for simple tasks)
761        if let Some(result) = try_free_model_reroute(
762            task_id,
763            agent_name,
764            agent_runner,
765            &[],
766            true, // fix: check cooldowns (was previously missing, inconsistent with other paths)
767            Some("opencode"),
768            false,
769            "all agents exhausted, trying free model",
770            store,
771            repo,
772        )
773        .await
774        {
775            return Ok(result);
776        }
777    }
778
779    let outcome = response::handle_failover(
780        task_id,
781        agent_name,
782        retryable,
783        &error_msg,
784        credit_recorded,
785        store,
786        repo,
787    )
788    .await;
789    match (outcome.status.as_str(), outcome.next_agent.as_deref()) {
790        ("new", Some(next)) => {
791            tracing::info!(task_id, to = next, "failover: re-routing to fallback agent");
792        }
793        ("new", None) => {
794            tracing::warn!(task_id, "failover exhausted (retryable), task reset to new");
795        }
796        ("blocked", _) => {
797            tracing::warn!(task_id, "failover exhausted (hard failure), task blocked");
798        }
799        _ => {}
800    }
801    let status = outcome.status;
802
803    // Store failure memory for retry learning
804    response::store_failure_memory(
805        task_id,
806        new_attempts,
807        agent_name,
808        model_name,
809        &error_msg,
810        store,
811        repo,
812    )
813    .await;
814
815    Ok(ErrorHandleResult::Continue {
816        status,
817        error: error_msg,
818    })
819}
820
821#[cfg(test)]
822mod tests;