From f192c40b2a3643a9ab97303310db8dbc7547ee35 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 14:59:31 +0100 Subject: Robustness: retry with backoff, explained errors, --list, --session creates - four attempts on 408/425/429/500/502/503/504 and transport errors, honouring Retry-After - backoff is interruptible so Ctrl-C is not held for up to 8s - context overflow, auth failure and rate limit messages say what to do - --list shows id/model/messages/age without needing a key - --session creates the session when the id does not exist - probes recorded: session header is mandatory, consecutive user messages allowed --- src/provider.rs | 163 +++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 138 insertions(+), 25 deletions(-) (limited to 'src/provider.rs') diff --git a/src/provider.rs b/src/provider.rs index bc1bd99..ba36b70 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -117,6 +117,68 @@ impl SseDecoder { } } +const MAX_ATTEMPTS: usize = 4; +const BACKOFF_BASE_MS: u64 = 1000; +const BACKOFF_MAX_MS: u64 = 8000; + +fn retryable_status(code: u16) -> bool { + matches!(code, 408 | 425 | 429 | 500 | 502 | 503 | 504) +} + +fn backoff(attempt: usize) -> Duration { + let factor = 1u64 << (attempt.saturating_sub(1).min(4) as u32); + Duration::from_millis((BACKOFF_BASE_MS * factor).min(BACKOFF_MAX_MS)) +} + +/// Sleeps in slices so a Ctrl-C during backoff is noticed promptly. +fn sleep_cancellable(total: Duration, cancel: &AtomicBool) -> bool { + let step = Duration::from_millis(100); + let mut left = total; + while left > Duration::ZERO { + if cancel.load(Ordering::Relaxed) { + return false; + } + let slice = left.min(step); + std::thread::sleep(slice); + left -= slice; + } + true +} + +/// Adds the thing the raw provider message does not say: what to do about it. +fn explain(status: u16, message: &str) -> String { + let lower = message.to_lowercase(); + if (status == 400 || status == 413) + && (lower.contains("context") + || lower.contains("too many tokens") + || lower.contains("maximum") + || lower.contains("too long")) + { + return format!( + "{message}\n\nthis session is longer than the model's context window. The \ + transcript is append-only and cannot be shortened, so start a new session." + ); + } + if status == 400 && lower.contains("session") { + return format!( + "{message}\n\nthe x-opencode-session header was not accepted; that is a bug in \ + this harness, not in your setup." + ); + } + if status == 401 || status == 403 { + return format!( + "{message}\n\ncheck the key: OPENCODE_API_KEY or ~/.config/agent686/key" + ); + } + if status == 429 { + return format!( + "{message}\n\nusage limit. Wait for the window to reset, or pick a cheaper \ + model with --model." + ); + } + message.to_string() +} + pub fn chat( cfg: &Config, messages: &[Value], @@ -147,31 +209,82 @@ pub fn chat( .into(); let started = Instant::now(); - let mut resp = agent - .post(&cfg.endpoint()) - .header("Content-Type", "application/json") - .header("Accept", "text/event-stream") - .header("Authorization", format!("Bearer {}", cfg.api_key)) - .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) - // Required by OpenCode Go: stable per conversation, used for routing and - // prompt caching. - .header("x-opencode-session", &cfg.session) - .send(bytes) - .map_err(|e| Error::Transport(e.to_string()))?; - - let status = resp.status().as_u16(); - if !(200..300).contains(&status) { - let text = resp - .body_mut() - .with_config() - .limit(256 * 1024) - .read_to_string() - .unwrap_or_default(); - return Err(Error::Status { - code: status, - message: error_message(&text), - }); - } + let mut resp = { + let mut attempt = 0usize; + loop { + attempt += 1; + if cancel.load(Ordering::Relaxed) { + return Err(Error::Aborted); + } + + let sent = agent + .post(&cfg.endpoint()) + .header("Content-Type", "application/json") + .header("Accept", "text/event-stream") + .header("Authorization", format!("Bearer {}", cfg.api_key)) + .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) + // Required by OpenCode Go: stable per conversation, used for + // routing and prompt caching. Without it the gateway answers + // 400 MissingSessionID. + .header("x-opencode-session", &cfg.session) + .send(bytes.clone()); + + let mut response = match sent { + Ok(response) => response, + Err(error) => { + if attempt < MAX_ATTEMPTS { + let wait = backoff(attempt); + eprintln!( + "agent686: {error}; retrying in {:.1}s ({attempt}/{MAX_ATTEMPTS})", + wait.as_secs_f32() + ); + if !sleep_cancellable(wait, cancel) { + return Err(Error::Aborted); + } + continue; + } + return Err(Error::Transport(error.to_string())); + } + }; + + let status = response.status().as_u16(); + if (200..300).contains(&status) { + break response; + } + + let retry_after = response + .headers() + .get("retry-after") + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.trim().parse::().ok()) + .map(Duration::from_secs); + + let text = response + .body_mut() + .with_config() + .limit(256 * 1024) + .read_to_string() + .unwrap_or_default(); + let message = error_message(&text); + + if retryable_status(status) && attempt < MAX_ATTEMPTS { + let wait = retry_after.unwrap_or_else(|| backoff(attempt)); + eprintln!( + "agent686: HTTP {status}: {message}; retrying in {:.1}s ({attempt}/{MAX_ATTEMPTS})", + wait.as_secs_f32() + ); + if !sleep_cancellable(wait, cancel) { + return Err(Error::Aborted); + } + continue; + } + + return Err(Error::Status { + code: status, + message: explain(status, &message), + }); + } + }; let mut outcome = Outcome::default(); let mut decoder = SseDecoder::new(); -- cgit v1.2.3