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