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 --- README.md | 8 ++- docs/PLAN.md | 17 +++++ scripts/mock-provider.py | 18 +++--- src/main.rs | 57 ++++++++++++++++- src/provider.rs | 163 +++++++++++++++++++++++++++++++++++++++-------- src/session.rs | 78 ++++++++++++++++++++++- tests/mock.rs | 131 +++++++++++++++++++++++++++++++++++++ tests/sessions.rs | 69 ++++++++++++++++++++ 8 files changed, 503 insertions(+), 38 deletions(-) create mode 100644 tests/sessions.rs diff --git a/README.md b/README.md index 562058a..4ec5d64 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,8 @@ export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key ./agent686 "make a calculator in C" # one turn, then exit ./agent686 # interactive, one prompt per line ./agent686 -c # continue the most recent session -./agent686 --session # resume a specific one +./agent686 --session # resume it, or create it if the id is new +./agent686 --list # id, model, message count, age ./agent686 --yolo "..." # approve every tool call ``` @@ -35,6 +36,9 @@ Provider is OpenCode Go, `chat/completions`, model `deepseek-v4.1-flash` by default. Every request carries a stable `x-opencode-session` header, which the service uses for routing and prompt caching. +Rate limits and transient failures retry with backoff (four attempts, `Retry-After` +honoured); a 429 that survives them explains itself instead of dumping JSON. + ## Tools `read` (numbered lines), `write` (never creates directories), `edit` (exact @@ -48,7 +52,7 @@ that is where `rm -rf` lives. ## Tests ```sh -cargo test # 19 tests, no network +cargo test # 24 tests, no network python3 scripts/mock-provider.py & # canned SSE provider docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gate ``` diff --git a/docs/PLAN.md b/docs/PLAN.md index b1273b1..75fd25b 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -110,6 +110,23 @@ against the live API: streaming, tool calls, `reasoning_content`, usage and 2.0 MB stripped i686 binary, `GLIBC_2.34` required. Verified by running the whole acceptance test inside `--platform linux/386 debian:12`. +**M6 — Robustness.** ✅ Done. + +- Retries on 408/425/429/500/502/503/504 and on transport errors: four attempts, + 1 s / 2 s / 4 s backoff, `Retry-After` honoured, and the backoff is + interruptible so Ctrl-C does not wait it out. +- Provider errors explain themselves: context overflow says to start a new + session, 401/403 says where the key lives, 429 points at the plan limit and + `--model`. +- `--list` shows id, model, message count and age; `--session ` creates the + session when the id is new instead of erroring. + +Probed against the live gateway: `x-opencode-session` is mandatory (400 +`MissingSessionID` without it); two consecutive user messages are accepted, so a +turn that failed after writing its prompt can be resumed without editing the +transcript; and `deepseek-v4.1-flash` accepted a 500k-token prompt, so the +context ceiling is far higher than the 128k the plan assumed. + ## Acceptance test (v1) > "Make a simple calculator in C" — run on the i386 box, from an empty directory. diff --git a/scripts/mock-provider.py b/scripts/mock-provider.py index fb15662..aa4731e 100755 --- a/scripts/mock-provider.py +++ b/scripts/mock-provider.py @@ -39,16 +39,14 @@ class Handler(BaseHTTPRequestHandler): self.rfile.read(length) if self.server.status != 200: - body = json.dumps( - { - "error": { - "type": "authentication_error", - "code": "api_key_expired", - "message": "This API key has expired.", - } - } - ).encode() + if self.server.status == 429: + error = {"code": "rate_limited", "message": "Too many requests."} + else: + error = {"code": "api_key_expired", "message": "This API key has expired."} + body = json.dumps({"error": error}).encode() self.send_response(self.server.status) + if self.server.retry_after is not None: + self.send_header("Retry-After", str(self.server.retry_after)) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(body) @@ -84,6 +82,7 @@ def main(): parser.add_argument("--status", type=int, default=200, help="return this HTTP status") parser.add_argument("--answer", default="Hello from the mock provider.") parser.add_argument("--tool-write", metavar="PATH", help="first response asks to write PATH") + parser.add_argument("--retry-after", type=int, help="Retry-After header on errors") parser.add_argument("--quiet", action="store_true") args = parser.parse_args() @@ -94,6 +93,7 @@ def main(): server.quiet = args.quiet server.tool_write = args.tool_write server.requests = 0 + server.retry_after = args.retry_after print(f"mock provider on http://127.0.0.1:{args.port}/v1", flush=True) server.serve_forever() 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(); diff --git a/tests/mock.rs b/tests/mock.rs index 52dec7c..9b3cd5a 100644 --- a/tests/mock.rs +++ b/tests/mock.rs @@ -195,3 +195,134 @@ fn honours_a_cancelled_turn() { .expect_err("cancelled turn should abort"); assert!(matches!(error, Error::Aborted)); } + +/// Serves one canned response per connection, in order, and records each +/// request so retries can be asserted. +fn serve_times(responses: Vec<&'static str>) -> (String, mpsc::Receiver) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = mpsc::channel(); + thread::spawn(move || { + for response in responses { + let (mut stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut request = String::new(); + let mut length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { + break; + } + if line == "\r\n" || line == "\n" { + break; + } + if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap_or(0); + } + request.push_str(&line); + } + let mut body = vec![0u8; length]; + let _ = reader.read_exact(&mut body); + request.push_str(&String::from_utf8_lossy(&body)); + let _ = tx.send(request); + let _ = stream.write_all(response.as_bytes()); + let _ = stream.flush(); + } + }); + (format!("http://{addr}"), rx) +} + +#[test] +fn retries_a_rate_limit_and_keeps_the_same_session_header() { + const LIMITED: &str = concat!( + "HTTP/1.1 429 Too Many Requests\r\n", + "Retry-After: 0\r\n", + "Content-Type: application/json\r\n", + "Connection: close\r\n", + "\r\n", + "{\"error\":{\"code\":\"rate_limited\",\"message\":\"slow down\"}}", + ); + const OK: &str = concat!( + "HTTP/1.1 200 OK\r\n", + "Content-Type: text/event-stream\r\n", + "Connection: close\r\n", + "\r\n", + "data: {\"choices\":[{\"delta\":{\"content\":\"second try\"},\"finish_reason\":\"stop\"}]}\n\n", + "data: [DONE]\n\n", + ); + + let (base, rx) = serve_times(vec![LIMITED, OK]); + let mut sink = Collector::default(); + let outcome = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &[], + &AtomicBool::new(false), + &mut sink, + ) + .expect("retry should succeed"); + + assert_eq!(outcome.content, "second try"); + + let first = rx.recv().expect("first request").to_ascii_lowercase(); + let second = rx.recv().expect("second request").to_ascii_lowercase(); + assert!(first.contains("x-opencode-session: testsession"), "{first}"); + assert!(second.contains("x-opencode-session: testsession"), "{second}"); +} + +#[test] +fn does_not_retry_a_permanent_client_error() { + const BAD: &str = concat!( + "HTTP/1.1 400 Bad Request\r\n", + "Content-Type: application/json\r\n", + "Connection: close\r\n", + "\r\n", + "{\"error\":{\"message\":\"maximum context length exceeded\"}}", + ); + let (base, rx) = serve_times(vec![BAD]); + let mut sink = Collector::default(); + let error = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &[], + &AtomicBool::new(false), + &mut sink, + ) + .expect_err("400 should fail"); + + match error { + Error::Status { code, message } => { + assert_eq!(code, 400); + assert!( + message.contains("start a new session"), + "should explain overflow: {message}" + ); + } + other => panic!("unexpected error: {other:?}"), + } + assert!(rx.recv().is_ok(), "exactly one request should be sent"); +} + +#[test] +fn auth_failure_says_where_the_key_lives() { + const UNAUTHORIZED: &str = concat!( + "HTTP/1.1 401 Unauthorized\r\n", + "Content-Type: application/json\r\n", + "Connection: close\r\n", + "\r\n", + "{\"error\":{\"code\":\"api_key_expired\",\"message\":\"This API key has expired.\"}}", + ); + let (base, _rx) = serve_times(vec![UNAUTHORIZED]); + let mut sink = Collector::default(); + let error = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &[], + &AtomicBool::new(false), + &mut sink, + ) + .expect_err("401 should fail"); + + let message = format!("{error}"); + assert!(message.contains("OPENCODE_API_KEY"), "{message}"); +} diff --git a/tests/sessions.rs b/tests/sessions.rs new file mode 100644 index 0000000..8d17fc5 --- /dev/null +++ b/tests/sessions.rs @@ -0,0 +1,69 @@ +use std::fs; +use std::path::PathBuf; +use std::process::Command; + +use serde_json::json; + +use agent686::session::{self, Session}; + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("agent686-sess-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn sessions_create_list_and_replay() { + let dir = temp_dir("roundtrip"); + std::env::set_var("AGENT686_DATA", &dir); + + let system = json!({ "role": "system", "content": "frozen" }); + let mut alpha = Session::create_as("alpha".into(), "model-a", &system).unwrap(); + assert!( + Session::create_as("alpha".into(), "model-a", &system).is_err(), + "duplicate ids must not overwrite a session" + ); + + alpha + .append(&json!({ "role": "user", "content": "hello" }), None) + .unwrap(); + alpha + .append( + &json!({ "role": "assistant", "content": "hi" }), + Some("because"), + ) + .unwrap(); + + assert!(session::exists("alpha")); + assert!(!session::exists("nope")); + + let listed = session::list().unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].id, "alpha"); + assert_eq!(listed[0].model, "model-a"); + assert_eq!(listed[0].messages, 2); + + let (reopened, system_back, messages) = Session::open("alpha").unwrap(); + assert_eq!(reopened.id, "alpha"); + assert_eq!(system_back["content"], "frozen"); + assert_eq!(messages.len(), 2); + assert_eq!(messages[1]["content"], "hi"); + // Reasoning is stored beside the message but must not be replayed. + assert!(messages[1].get("_reasoning").is_none()); +} + +#[test] +fn cli_lists_sessions_without_a_key() { + let dir = temp_dir("cli"); + let output = Command::new(env!("CARGO_BIN_EXE_agent686")) + .env("AGENT686_DATA", &dir) + .env_remove("OPENCODE_API_KEY") + .arg("--list") + .output() + .unwrap(); + + assert!(output.status.success(), "{output:?}"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("no sessions"), "{stdout}"); +} -- cgit v1.2.3