diff options
| author | salmonik <salmonik@tuta.io> | 2026-11-15 14:59:31 +0100 |
|---|---|---|
| committer | salmonik <salmonik@tuta.io> | 2026-11-15 14:59:31 +0100 |
| commit | f192c40b2a3643a9ab97303310db8dbc7547ee35 (patch) | |
| tree | 1b2133afa1b3318f8c0da032a7da278691e577ca /src | |
| parent | M1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate (diff) | |
| download | agent686-f192c40b2a3643a9ab97303310db8dbc7547ee35.tar.gz agent686-f192c40b2a3643a9ab97303310db8dbc7547ee35.zip | |
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 <id> creates the session when the id does not exist
- probes recorded: session header is mandatory, consecutive user messages allowed
Diffstat (limited to '')
| -rw-r--r-- | src/main.rs | 57 | ||||
| -rw-r--r-- | src/provider.rs | 163 | ||||
| -rw-r--r-- | src/session.rs | 78 |
3 files changed, 271 insertions, 27 deletions
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. | |||
| 21 | OPTIONS: | 21 | OPTIONS: |
| 22 | -m, --model <ID> model id (default: deepseek-v4.1-flash) | 22 | -m, --model <ID> model id (default: deepseek-v4.1-flash) |
| 23 | --base-url <URL> provider base URL | 23 | --base-url <URL> provider base URL |
| 24 | --session <ID> resume a specific session | 24 | --session <ID> resume a session, creating it if the id is new |
| 25 | -c, --continue resume the most recent session | 25 | -c, --continue resume the most recent session |
| 26 | --list list sessions and exit | ||
| 26 | --yolo approve every tool call without asking | 27 | --yolo approve every tool call without asking |
| 27 | -h, --help this text | 28 | -h, --help this text |
| 28 | 29 | ||
| @@ -39,6 +40,7 @@ fn main() { | |||
| 39 | let mut base_url = None; | 40 | let mut base_url = None; |
| 40 | let mut resume = None; | 41 | let mut resume = None; |
| 41 | let mut continue_last = false; | 42 | let mut continue_last = false; |
| 43 | let mut list = false; | ||
| 42 | let mut yolo = false; | 44 | let mut yolo = false; |
| 43 | 45 | ||
| 44 | let mut args = std::env::args().skip(1); | 46 | let mut args = std::env::args().skip(1); |
| @@ -48,6 +50,7 @@ fn main() { | |||
| 48 | "--base-url" => base_url = args.next(), | 50 | "--base-url" => base_url = args.next(), |
| 49 | "--session" | "--resume" => resume = args.next(), | 51 | "--session" | "--resume" => resume = args.next(), |
| 50 | "-c" | "--continue" => continue_last = true, | 52 | "-c" | "--continue" => continue_last = true, |
| 53 | "--list" => list = true, | ||
| 51 | "--yolo" => yolo = true, | 54 | "--yolo" => yolo = true, |
| 52 | "-h" | "--help" => { | 55 | "-h" | "--help" => { |
| 53 | print!("{HELP}"); | 56 | print!("{HELP}"); |
| @@ -64,6 +67,11 @@ fn main() { | |||
| 64 | 67 | ||
| 65 | signal::install(); | 68 | signal::install(); |
| 66 | 69 | ||
| 70 | if list { | ||
| 71 | print_sessions(); | ||
| 72 | return; | ||
| 73 | } | ||
| 74 | |||
| 67 | let mut cfg = match Config::resolve(model, base_url, yolo) { | 75 | let mut cfg = match Config::resolve(model, base_url, yolo) { |
| 68 | Ok(cfg) => cfg, | 76 | Ok(cfg) => cfg, |
| 69 | Err(message) => { | 77 | Err(message) => { |
| @@ -189,6 +197,16 @@ fn open_session( | |||
| 189 | }; | 197 | }; |
| 190 | 198 | ||
| 191 | match id { | 199 | match id { |
| 200 | Some(id) if !session::exists(&id) => { | ||
| 201 | let system = agent::system_prompt(); | ||
| 202 | let session = Session::create_as(id, &cfg.model, &system)?; | ||
| 203 | eprintln!( | ||
| 204 | "agent686: new session {} ({})", | ||
| 205 | session.id, | ||
| 206 | session.path().display() | ||
| 207 | ); | ||
| 208 | Ok((session, agent::new_history(system))) | ||
| 209 | } | ||
| 192 | Some(id) => { | 210 | Some(id) => { |
| 193 | let (session, system, messages) = Session::open(&id)?; | 211 | let (session, system, messages) = Session::open(&id)?; |
| 194 | if !session.model.is_empty() && session.model != cfg.model { | 212 | if !session.model.is_empty() && session.model != cfg.model { |
| @@ -241,3 +259,40 @@ fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) { | |||
| 241 | } | 259 | } |
| 242 | } | 260 | } |
| 243 | } | 261 | } |
| 262 | |||
| 263 | fn print_sessions() { | ||
| 264 | let sessions = match session::list() { | ||
| 265 | Ok(sessions) => sessions, | ||
| 266 | Err(error) => { | ||
| 267 | eprintln!("agent686: {error}"); | ||
| 268 | return; | ||
| 269 | } | ||
| 270 | }; | ||
| 271 | if sessions.is_empty() { | ||
| 272 | println!("no sessions"); | ||
| 273 | return; | ||
| 274 | } | ||
| 275 | println!("{:<34} {:<22} {:>5} {:>4}", "SESSION", "MODEL", "MSGS", "AGE"); | ||
| 276 | for info in sessions { | ||
| 277 | println!( | ||
| 278 | "{:<34} {:<22} {:>5} {:>4}", | ||
| 279 | info.id, | ||
| 280 | info.model, | ||
| 281 | info.messages, | ||
| 282 | ago(info.modified) | ||
| 283 | ); | ||
| 284 | } | ||
| 285 | } | ||
| 286 | |||
| 287 | fn ago(modified: SystemTime) -> String { | ||
| 288 | let seconds = SystemTime::now() | ||
| 289 | .duration_since(modified) | ||
| 290 | .map(|d| d.as_secs()) | ||
| 291 | .unwrap_or(0); | ||
| 292 | match seconds { | ||
| 293 | 0..=59 => format!("{seconds}s"), | ||
| 294 | 60..=3599 => format!("{}m", seconds / 60), | ||
| 295 | 3600..=86_399 => format!("{}h", seconds / 3600), | ||
| 296 | _ => format!("{}d", seconds / 86_400), | ||
| 297 | } | ||
| 298 | } | ||
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 { | |||
| 117 | } | 117 | } |
| 118 | } | 118 | } |
| 119 | 119 | ||
| 120 | const MAX_ATTEMPTS: usize = 4; | ||
| 121 | const BACKOFF_BASE_MS: u64 = 1000; | ||
| 122 | const BACKOFF_MAX_MS: u64 = 8000; | ||
| 123 | |||
| 124 | fn retryable_status(code: u16) -> bool { | ||
| 125 | matches!(code, 408 | 425 | 429 | 500 | 502 | 503 | 504) | ||
| 126 | } | ||
| 127 | |||
| 128 | fn backoff(attempt: usize) -> Duration { | ||
| 129 | let factor = 1u64 << (attempt.saturating_sub(1).min(4) as u32); | ||
| 130 | Duration::from_millis((BACKOFF_BASE_MS * factor).min(BACKOFF_MAX_MS)) | ||
| 131 | } | ||
| 132 | |||
| 133 | /// Sleeps in slices so a Ctrl-C during backoff is noticed promptly. | ||
| 134 | fn sleep_cancellable(total: Duration, cancel: &AtomicBool) -> bool { | ||
| 135 | let step = Duration::from_millis(100); | ||
| 136 | let mut left = total; | ||
| 137 | while left > Duration::ZERO { | ||
| 138 | if cancel.load(Ordering::Relaxed) { | ||
| 139 | return false; | ||
| 140 | } | ||
| 141 | let slice = left.min(step); | ||
| 142 | std::thread::sleep(slice); | ||
| 143 | left -= slice; | ||
| 144 | } | ||
| 145 | true | ||
| 146 | } | ||
| 147 | |||
| 148 | /// Adds the thing the raw provider message does not say: what to do about it. | ||
| 149 | fn explain(status: u16, message: &str) -> String { | ||
| 150 | let lower = message.to_lowercase(); | ||
| 151 | if (status == 400 || status == 413) | ||
| 152 | && (lower.contains("context") | ||
| 153 | || lower.contains("too many tokens") | ||
| 154 | || lower.contains("maximum") | ||
| 155 | || lower.contains("too long")) | ||
| 156 | { | ||
| 157 | return format!( | ||
| 158 | "{message}\n\nthis session is longer than the model's context window. The \ | ||
| 159 | transcript is append-only and cannot be shortened, so start a new session." | ||
| 160 | ); | ||
| 161 | } | ||
| 162 | if status == 400 && lower.contains("session") { | ||
| 163 | return format!( | ||
| 164 | "{message}\n\nthe x-opencode-session header was not accepted; that is a bug in \ | ||
| 165 | this harness, not in your setup." | ||
| 166 | ); | ||
| 167 | } | ||
| 168 | if status == 401 || status == 403 { | ||
| 169 | return format!( | ||
| 170 | "{message}\n\ncheck the key: OPENCODE_API_KEY or ~/.config/agent686/key" | ||
| 171 | ); | ||
| 172 | } | ||
| 173 | if status == 429 { | ||
| 174 | return format!( | ||
| 175 | "{message}\n\nusage limit. Wait for the window to reset, or pick a cheaper \ | ||
| 176 | model with --model." | ||
| 177 | ); | ||
| 178 | } | ||
| 179 | message.to_string() | ||
| 180 | } | ||
| 181 | |||
| 120 | pub fn chat( | 182 | pub fn chat( |
| 121 | cfg: &Config, | 183 | cfg: &Config, |
| 122 | messages: &[Value], | 184 | messages: &[Value], |
| @@ -147,31 +209,82 @@ pub fn chat( | |||
| 147 | .into(); | 209 | .into(); |
| 148 | 210 | ||
| 149 | let started = Instant::now(); | 211 | let started = Instant::now(); |
| 150 | let mut resp = agent | 212 | let mut resp = { |
| 151 | .post(&cfg.endpoint()) | 213 | let mut attempt = 0usize; |
| 152 | .header("Content-Type", "application/json") | 214 | loop { |
| 153 | .header("Accept", "text/event-stream") | 215 | attempt += 1; |
| 154 | .header("Authorization", format!("Bearer {}", cfg.api_key)) | 216 | if cancel.load(Ordering::Relaxed) { |
| 155 | .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) | 217 | return Err(Error::Aborted); |
| 156 | // Required by OpenCode Go: stable per conversation, used for routing and | 218 | } |
| 157 | // prompt caching. | 219 | |
| 158 | .header("x-opencode-session", &cfg.session) | 220 | let sent = agent |
| 159 | .send(bytes) | 221 | .post(&cfg.endpoint()) |
| 160 | .map_err(|e| Error::Transport(e.to_string()))?; | 222 | .header("Content-Type", "application/json") |
| 161 | 223 | .header("Accept", "text/event-stream") | |
| 162 | let status = resp.status().as_u16(); | 224 | .header("Authorization", format!("Bearer {}", cfg.api_key)) |
| 163 | if !(200..300).contains(&status) { | 225 | .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) |
| 164 | let text = resp | 226 | // Required by OpenCode Go: stable per conversation, used for |
| 165 | .body_mut() | 227 | // routing and prompt caching. Without it the gateway answers |
| 166 | .with_config() | 228 | // 400 MissingSessionID. |
| 167 | .limit(256 * 1024) | 229 | .header("x-opencode-session", &cfg.session) |
| 168 | .read_to_string() | 230 | .send(bytes.clone()); |
| 169 | .unwrap_or_default(); | 231 | |
| 170 | return Err(Error::Status { | 232 | let mut response = match sent { |
| 171 | code: status, | 233 | Ok(response) => response, |
| 172 | message: error_message(&text), | 234 | Err(error) => { |
| 173 | }); | 235 | if attempt < MAX_ATTEMPTS { |
| 174 | } | 236 | let wait = backoff(attempt); |
| 237 | eprintln!( | ||
| 238 | "agent686: {error}; retrying in {:.1}s ({attempt}/{MAX_ATTEMPTS})", | ||
| 239 | wait.as_secs_f32() | ||
| 240 | ); | ||
| 241 | if !sleep_cancellable(wait, cancel) { | ||
| 242 | return Err(Error::Aborted); | ||
| 243 | } | ||
| 244 | continue; | ||
| 245 | } | ||
| 246 | return Err(Error::Transport(error.to_string())); | ||
| 247 | } | ||
| 248 | }; | ||
| 249 | |||
| 250 | let status = response.status().as_u16(); | ||
| 251 | if (200..300).contains(&status) { | ||
| 252 | break response; | ||
| 253 | } | ||
| 254 | |||
| 255 | let retry_after = response | ||
| 256 | .headers() | ||
| 257 | .get("retry-after") | ||
| 258 | .and_then(|value| value.to_str().ok()) | ||
| 259 | .and_then(|value| value.trim().parse::<u64>().ok()) | ||
| 260 | .map(Duration::from_secs); | ||
| 261 | |||
| 262 | let text = response | ||
| 263 | .body_mut() | ||
| 264 | .with_config() | ||
| 265 | .limit(256 * 1024) | ||
| 266 | .read_to_string() | ||
| 267 | .unwrap_or_default(); | ||
| 268 | let message = error_message(&text); | ||
| 269 | |||
| 270 | if retryable_status(status) && attempt < MAX_ATTEMPTS { | ||
| 271 | let wait = retry_after.unwrap_or_else(|| backoff(attempt)); | ||
| 272 | eprintln!( | ||
| 273 | "agent686: HTTP {status}: {message}; retrying in {:.1}s ({attempt}/{MAX_ATTEMPTS})", | ||
| 274 | wait.as_secs_f32() | ||
| 275 | ); | ||
| 276 | if !sleep_cancellable(wait, cancel) { | ||
| 277 | return Err(Error::Aborted); | ||
| 278 | } | ||
| 279 | continue; | ||
| 280 | } | ||
| 281 | |||
| 282 | return Err(Error::Status { | ||
| 283 | code: status, | ||
| 284 | message: explain(status, &message), | ||
| 285 | }); | ||
| 286 | } | ||
| 287 | }; | ||
| 175 | 288 | ||
| 176 | let mut outcome = Outcome::default(); | 289 | let mut outcome = Outcome::default(); |
| 177 | let mut decoder = SseDecoder::new(); | 290 | 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 { | |||
| 48 | file: File, | 48 | file: File, |
| 49 | } | 49 | } |
| 50 | 50 | ||
| 51 | pub struct SessionInfo { | ||
| 52 | pub id: String, | ||
| 53 | pub model: String, | ||
| 54 | pub messages: usize, | ||
| 55 | pub modified: SystemTime, | ||
| 56 | pub path: PathBuf, | ||
| 57 | } | ||
| 58 | |||
| 51 | impl Session { | 59 | impl Session { |
| 52 | pub fn create(model: &str, system: &Value) -> Result<Session, String> { | 60 | pub fn create(model: &str, system: &Value) -> Result<Session, String> { |
| 53 | let id = new_id(); | 61 | Self::create_as(new_id(), model, system) |
| 62 | } | ||
| 63 | |||
| 64 | /// Creates a session with a caller-chosen id, for `--session <id>` on a | ||
| 65 | /// conversation that does not exist yet. | ||
| 66 | pub fn create_as(id: String, model: &str, system: &Value) -> Result<Session, String> { | ||
| 54 | let dir = sessions_dir(); | 67 | let dir = sessions_dir(); |
| 55 | std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; | 68 | std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; |
| 56 | let path = dir.join(format!("{id}.jsonl")); | 69 | let path = dir.join(format!("{id}.jsonl")); |
| @@ -163,6 +176,69 @@ impl Session { | |||
| 163 | } | 176 | } |
| 164 | } | 177 | } |
| 165 | 178 | ||
| 179 | pub fn exists(id: &str) -> bool { | ||
| 180 | sessions_dir().join(format!("{id}.jsonl")).is_file() | ||
| 181 | } | ||
| 182 | |||
| 183 | /// Every session, most recently used first. Reads each file once; fine for the | ||
| 184 | /// handful of conversations a person accumulates. | ||
| 185 | pub fn list() -> Result<Vec<SessionInfo>, String> { | ||
| 186 | let dir = sessions_dir(); | ||
| 187 | let entries = match std::fs::read_dir(&dir) { | ||
| 188 | Ok(entries) => entries, | ||
| 189 | Err(_) => return Ok(Vec::new()), | ||
| 190 | }; | ||
| 191 | |||
| 192 | let mut sessions = Vec::new(); | ||
| 193 | for entry in entries.flatten() { | ||
| 194 | let path = entry.path(); | ||
| 195 | if path.extension().and_then(|e| e.to_str()) != Some("jsonl") { | ||
| 196 | continue; | ||
| 197 | } | ||
| 198 | let id = match path.file_stem().and_then(|s| s.to_str()) { | ||
| 199 | Some(id) => id.to_string(), | ||
| 200 | None => continue, | ||
| 201 | }; | ||
| 202 | let modified = entry | ||
| 203 | .metadata() | ||
| 204 | .and_then(|m| m.modified()) | ||
| 205 | .unwrap_or(UNIX_EPOCH); | ||
| 206 | let (model, messages) = scan(&path); | ||
| 207 | sessions.push(SessionInfo { | ||
| 208 | id, | ||
| 209 | model, | ||
| 210 | messages, | ||
| 211 | modified, | ||
| 212 | path, | ||
| 213 | }); | ||
| 214 | } | ||
| 215 | sessions.sort_by(|a, b| b.modified.cmp(&a.modified)); | ||
| 216 | Ok(sessions) | ||
| 217 | } | ||
| 218 | |||
| 219 | fn scan(path: &PathBuf) -> (String, usize) { | ||
| 220 | let mut model = String::from("?"); | ||
| 221 | let mut messages = 0usize; | ||
| 222 | if let Ok(file) = File::open(path) { | ||
| 223 | for line in BufReader::new(file).lines().map_while(Result::ok) { | ||
| 224 | let value: Value = match serde_json::from_str(&line) { | ||
| 225 | Ok(value) => value, | ||
| 226 | Err(_) => continue, | ||
| 227 | }; | ||
| 228 | match value.get("t").and_then(|t| t.as_str()) { | ||
| 229 | Some("header") => { | ||
| 230 | if let Some(name) = value.get("model").and_then(|m| m.as_str()) { | ||
| 231 | model = name.to_string(); | ||
| 232 | } | ||
| 233 | } | ||
| 234 | Some("msg") => messages += 1, | ||
| 235 | _ => {} | ||
| 236 | } | ||
| 237 | } | ||
| 238 | } | ||
| 239 | (model, messages) | ||
| 240 | } | ||
| 241 | |||
| 166 | /// Most recently written session, for --continue. | 242 | /// Most recently written session, for --continue. |
| 167 | pub fn latest() -> Result<Option<String>, String> { | 243 | pub fn latest() -> Result<Option<String>, String> { |
| 168 | let dir = sessions_dir(); | 244 | let dir = sessions_dir(); |
