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/main.rs | 57 +++++++++++++++++++- src/provider.rs | 163 +++++++++++++++++++++++++++++++++++++++++++++++--------- src/session.rs | 78 ++++++++++++++++++++++++++- 3 files changed, 271 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index c53ebb6..4bc3550 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,8 +21,9 @@ stdin, one per line. Commands: /paste, /exit, /help. OPTIONS: -m, --model model id (default: deepseek-v4.1-flash) --base-url provider base URL - --session resume a specific session + --session resume a session, creating it if the id is new -c, --continue resume the most recent session + --list list sessions and exit --yolo approve every tool call without asking -h, --help this text @@ -39,6 +40,7 @@ fn main() { let mut base_url = None; let mut resume = None; let mut continue_last = false; + let mut list = false; let mut yolo = false; let mut args = std::env::args().skip(1); @@ -48,6 +50,7 @@ fn main() { "--base-url" => base_url = args.next(), "--session" | "--resume" => resume = args.next(), "-c" | "--continue" => continue_last = true, + "--list" => list = true, "--yolo" => yolo = true, "-h" | "--help" => { print!("{HELP}"); @@ -64,6 +67,11 @@ fn main() { signal::install(); + if list { + print_sessions(); + return; + } + let mut cfg = match Config::resolve(model, base_url, yolo) { Ok(cfg) => cfg, Err(message) => { @@ -189,6 +197,16 @@ fn open_session( }; match id { + Some(id) if !session::exists(&id) => { + let system = agent::system_prompt(); + let session = Session::create_as(id, &cfg.model, &system)?; + eprintln!( + "agent686: new session {} ({})", + session.id, + session.path().display() + ); + Ok((session, agent::new_history(system))) + } Some(id) => { let (session, system, messages) = Session::open(&id)?; if !session.model.is_empty() && session.model != cfg.model { @@ -241,3 +259,40 @@ fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) { } } } + +fn print_sessions() { + let sessions = match session::list() { + Ok(sessions) => sessions, + Err(error) => { + eprintln!("agent686: {error}"); + return; + } + }; + if sessions.is_empty() { + println!("no sessions"); + return; + } + println!("{:<34} {:<22} {:>5} {:>4}", "SESSION", "MODEL", "MSGS", "AGE"); + for info in sessions { + println!( + "{:<34} {:<22} {:>5} {:>4}", + info.id, + info.model, + info.messages, + ago(info.modified) + ); + } +} + +fn ago(modified: SystemTime) -> String { + let seconds = SystemTime::now() + .duration_since(modified) + .map(|d| d.as_secs()) + .unwrap_or(0); + match seconds { + 0..=59 => format!("{seconds}s"), + 60..=3599 => format!("{}m", seconds / 60), + 3600..=86_399 => format!("{}h", seconds / 3600), + _ => format!("{}d", seconds / 86_400), + } +} 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(); diff --git a/src/session.rs b/src/session.rs index 7090dcf..9f2b699 100644 --- a/src/session.rs +++ b/src/session.rs @@ -48,9 +48,22 @@ pub struct Session { file: File, } +pub struct SessionInfo { + pub id: String, + pub model: String, + pub messages: usize, + pub modified: SystemTime, + pub path: PathBuf, +} + impl Session { pub fn create(model: &str, system: &Value) -> Result { - let id = new_id(); + Self::create_as(new_id(), model, system) + } + + /// Creates a session with a caller-chosen id, for `--session ` on a + /// conversation that does not exist yet. + pub fn create_as(id: String, model: &str, system: &Value) -> Result { let dir = sessions_dir(); std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; let path = dir.join(format!("{id}.jsonl")); @@ -163,6 +176,69 @@ impl Session { } } +pub fn exists(id: &str) -> bool { + sessions_dir().join(format!("{id}.jsonl")).is_file() +} + +/// Every session, most recently used first. Reads each file once; fine for the +/// handful of conversations a person accumulates. +pub fn list() -> Result, String> { + let dir = sessions_dir(); + let entries = match std::fs::read_dir(&dir) { + Ok(entries) => entries, + Err(_) => return Ok(Vec::new()), + }; + + let mut sessions = Vec::new(); + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("jsonl") { + continue; + } + let id = match path.file_stem().and_then(|s| s.to_str()) { + Some(id) => id.to_string(), + None => continue, + }; + let modified = entry + .metadata() + .and_then(|m| m.modified()) + .unwrap_or(UNIX_EPOCH); + let (model, messages) = scan(&path); + sessions.push(SessionInfo { + id, + model, + messages, + modified, + path, + }); + } + sessions.sort_by(|a, b| b.modified.cmp(&a.modified)); + Ok(sessions) +} + +fn scan(path: &PathBuf) -> (String, usize) { + let mut model = String::from("?"); + let mut messages = 0usize; + if let Ok(file) = File::open(path) { + for line in BufReader::new(file).lines().map_while(Result::ok) { + let value: Value = match serde_json::from_str(&line) { + Ok(value) => value, + Err(_) => continue, + }; + match value.get("t").and_then(|t| t.as_str()) { + Some("header") => { + if let Some(name) = value.get("model").and_then(|m| m.as_str()) { + model = name.to_string(); + } + } + Some("msg") => messages += 1, + _ => {} + } + } + } + (model, messages) +} + /// Most recently written session, for --continue. pub fn latest() -> Result, String> { let dir = sessions_dir(); -- cgit v1.2.3