aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorsalmonik <salmonik@tuta.io>2026-11-15 14:59:31 +0100
committersalmonik <salmonik@tuta.io>2026-11-15 14:59:31 +0100
commitf192c40b2a3643a9ab97303310db8dbc7547ee35 (patch)
tree1b2133afa1b3318f8c0da032a7da278691e577ca
parentM1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate (diff)
downloadagent686-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--README.md8
-rw-r--r--docs/PLAN.md17
-rwxr-xr-xscripts/mock-provider.py18
-rw-r--r--src/main.rs57
-rw-r--r--src/provider.rs163
-rw-r--r--src/session.rs78
-rw-r--r--tests/mock.rs131
-rw-r--r--tests/sessions.rs69
8 files changed, 503 insertions, 38 deletions
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
27./agent686 "make a calculator in C" # one turn, then exit 27./agent686 "make a calculator in C" # one turn, then exit
28./agent686 # interactive, one prompt per line 28./agent686 # interactive, one prompt per line
29./agent686 -c # continue the most recent session 29./agent686 -c # continue the most recent session
30./agent686 --session <id> # resume a specific one 30./agent686 --session <id> # resume it, or create it if the id is new
31./agent686 --list # id, model, message count, age
31./agent686 --yolo "..." # approve every tool call 32./agent686 --yolo "..." # approve every tool call
32``` 33```
33 34
@@ -35,6 +36,9 @@ Provider is OpenCode Go, `chat/completions`, model `deepseek-v4.1-flash` by
35default. Every request carries a stable `x-opencode-session` header, which the 36default. Every request carries a stable `x-opencode-session` header, which the
36service uses for routing and prompt caching. 37service uses for routing and prompt caching.
37 38
39Rate limits and transient failures retry with backoff (four attempts, `Retry-After`
40honoured); a 429 that survives them explains itself instead of dumping JSON.
41
38## Tools 42## Tools
39 43
40`read` (numbered lines), `write` (never creates directories), `edit` (exact 44`read` (numbered lines), `write` (never creates directories), `edit` (exact
@@ -48,7 +52,7 @@ that is where `rm -rf` lives.
48## Tests 52## Tests
49 53
50```sh 54```sh
51cargo test # 19 tests, no network 55cargo test # 24 tests, no network
52python3 scripts/mock-provider.py & # canned SSE provider 56python3 scripts/mock-provider.py & # canned SSE provider
53docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gate 57docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gate
54``` 58```
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
1102.0 MB stripped i686 binary, `GLIBC_2.34` required. Verified by running the 1102.0 MB stripped i686 binary, `GLIBC_2.34` required. Verified by running the
111whole acceptance test inside `--platform linux/386 debian:12`. 111whole acceptance test inside `--platform linux/386 debian:12`.
112 112
113**M6 — Robustness.** ✅ Done.
114
115- Retries on 408/425/429/500/502/503/504 and on transport errors: four attempts,
116 1 s / 2 s / 4 s backoff, `Retry-After` honoured, and the backoff is
117 interruptible so Ctrl-C does not wait it out.
118- Provider errors explain themselves: context overflow says to start a new
119 session, 401/403 says where the key lives, 429 points at the plan limit and
120 `--model`.
121- `--list` shows id, model, message count and age; `--session <id>` creates the
122 session when the id is new instead of erroring.
123
124Probed against the live gateway: `x-opencode-session` is mandatory (400
125`MissingSessionID` without it); two consecutive user messages are accepted, so a
126turn that failed after writing its prompt can be resumed without editing the
127transcript; and `deepseek-v4.1-flash` accepted a 500k-token prompt, so the
128context ceiling is far higher than the 128k the plan assumed.
129
113## Acceptance test (v1) 130## Acceptance test (v1)
114 131
115> "Make a simple calculator in C" — run on the i386 box, from an empty directory. 132> "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):
39 self.rfile.read(length) 39 self.rfile.read(length)
40 40
41 if self.server.status != 200: 41 if self.server.status != 200:
42 body = json.dumps( 42 if self.server.status == 429:
43 { 43 error = {"code": "rate_limited", "message": "Too many requests."}
44 "error": { 44 else:
45 "type": "authentication_error", 45 error = {"code": "api_key_expired", "message": "This API key has expired."}
46 "code": "api_key_expired", 46 body = json.dumps({"error": error}).encode()
47 "message": "This API key has expired.",
48 }
49 }
50 ).encode()
51 self.send_response(self.server.status) 47 self.send_response(self.server.status)
48 if self.server.retry_after is not None:
49 self.send_header("Retry-After", str(self.server.retry_after))
52 self.send_header("Content-Type", "application/json") 50 self.send_header("Content-Type", "application/json")
53 self.end_headers() 51 self.end_headers()
54 self.wfile.write(body) 52 self.wfile.write(body)
@@ -84,6 +82,7 @@ def main():
84 parser.add_argument("--status", type=int, default=200, help="return this HTTP status") 82 parser.add_argument("--status", type=int, default=200, help="return this HTTP status")
85 parser.add_argument("--answer", default="Hello from the mock provider.") 83 parser.add_argument("--answer", default="Hello from the mock provider.")
86 parser.add_argument("--tool-write", metavar="PATH", help="first response asks to write PATH") 84 parser.add_argument("--tool-write", metavar="PATH", help="first response asks to write PATH")
85 parser.add_argument("--retry-after", type=int, help="Retry-After header on errors")
87 parser.add_argument("--quiet", action="store_true") 86 parser.add_argument("--quiet", action="store_true")
88 args = parser.parse_args() 87 args = parser.parse_args()
89 88
@@ -94,6 +93,7 @@ def main():
94 server.quiet = args.quiet 93 server.quiet = args.quiet
95 server.tool_write = args.tool_write 94 server.tool_write = args.tool_write
96 server.requests = 0 95 server.requests = 0
96 server.retry_after = args.retry_after
97 print(f"mock provider on http://127.0.0.1:{args.port}/v1", flush=True) 97 print(f"mock provider on http://127.0.0.1:{args.port}/v1", flush=True)
98 server.serve_forever() 98 server.serve_forever()
99 99
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.
21OPTIONS: 21OPTIONS:
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
263fn 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
287fn 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
120const MAX_ATTEMPTS: usize = 4;
121const BACKOFF_BASE_MS: u64 = 1000;
122const BACKOFF_MAX_MS: u64 = 8000;
123
124fn retryable_status(code: u16) -> bool {
125 matches!(code, 408 | 425 | 429 | 500 | 502 | 503 | 504)
126}
127
128fn 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.
134fn 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.
149fn 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
120pub fn chat( 182pub 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
51pub struct SessionInfo {
52 pub id: String,
53 pub model: String,
54 pub messages: usize,
55 pub modified: SystemTime,
56 pub path: PathBuf,
57}
58
51impl Session { 59impl 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
179pub 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.
185pub 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
219fn 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.
167pub fn latest() -> Result<Option<String>, String> { 243pub fn latest() -> Result<Option<String>, String> {
168 let dir = sessions_dir(); 244 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() {
195 .expect_err("cancelled turn should abort"); 195 .expect_err("cancelled turn should abort");
196 assert!(matches!(error, Error::Aborted)); 196 assert!(matches!(error, Error::Aborted));
197} 197}
198
199/// Serves one canned response per connection, in order, and records each
200/// request so retries can be asserted.
201fn serve_times(responses: Vec<&'static str>) -> (String, mpsc::Receiver<String>) {
202 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
203 let addr = listener.local_addr().unwrap();
204 let (tx, rx) = mpsc::channel();
205 thread::spawn(move || {
206 for response in responses {
207 let (mut stream, _) = listener.accept().unwrap();
208 let mut reader = BufReader::new(stream.try_clone().unwrap());
209 let mut request = String::new();
210 let mut length = 0usize;
211 loop {
212 let mut line = String::new();
213 if reader.read_line(&mut line).unwrap_or(0) == 0 {
214 break;
215 }
216 if line == "\r\n" || line == "\n" {
217 break;
218 }
219 if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") {
220 length = value.trim().parse().unwrap_or(0);
221 }
222 request.push_str(&line);
223 }
224 let mut body = vec![0u8; length];
225 let _ = reader.read_exact(&mut body);
226 request.push_str(&String::from_utf8_lossy(&body));
227 let _ = tx.send(request);
228 let _ = stream.write_all(response.as_bytes());
229 let _ = stream.flush();
230 }
231 });
232 (format!("http://{addr}"), rx)
233}
234
235#[test]
236fn retries_a_rate_limit_and_keeps_the_same_session_header() {
237 const LIMITED: &str = concat!(
238 "HTTP/1.1 429 Too Many Requests\r\n",
239 "Retry-After: 0\r\n",
240 "Content-Type: application/json\r\n",
241 "Connection: close\r\n",
242 "\r\n",
243 "{\"error\":{\"code\":\"rate_limited\",\"message\":\"slow down\"}}",
244 );
245 const OK: &str = concat!(
246 "HTTP/1.1 200 OK\r\n",
247 "Content-Type: text/event-stream\r\n",
248 "Connection: close\r\n",
249 "\r\n",
250 "data: {\"choices\":[{\"delta\":{\"content\":\"second try\"},\"finish_reason\":\"stop\"}]}\n\n",
251 "data: [DONE]\n\n",
252 );
253
254 let (base, rx) = serve_times(vec![LIMITED, OK]);
255 let mut sink = Collector::default();
256 let outcome = provider::chat(
257 &config(base),
258 &[json!({ "role": "user", "content": "hi" })],
259 &[],
260 &AtomicBool::new(false),
261 &mut sink,
262 )
263 .expect("retry should succeed");
264
265 assert_eq!(outcome.content, "second try");
266
267 let first = rx.recv().expect("first request").to_ascii_lowercase();
268 let second = rx.recv().expect("second request").to_ascii_lowercase();
269 assert!(first.contains("x-opencode-session: testsession"), "{first}");
270 assert!(second.contains("x-opencode-session: testsession"), "{second}");
271}
272
273#[test]
274fn does_not_retry_a_permanent_client_error() {
275 const BAD: &str = concat!(
276 "HTTP/1.1 400 Bad Request\r\n",
277 "Content-Type: application/json\r\n",
278 "Connection: close\r\n",
279 "\r\n",
280 "{\"error\":{\"message\":\"maximum context length exceeded\"}}",
281 );
282 let (base, rx) = serve_times(vec![BAD]);
283 let mut sink = Collector::default();
284 let error = provider::chat(
285 &config(base),
286 &[json!({ "role": "user", "content": "hi" })],
287 &[],
288 &AtomicBool::new(false),
289 &mut sink,
290 )
291 .expect_err("400 should fail");
292
293 match error {
294 Error::Status { code, message } => {
295 assert_eq!(code, 400);
296 assert!(
297 message.contains("start a new session"),
298 "should explain overflow: {message}"
299 );
300 }
301 other => panic!("unexpected error: {other:?}"),
302 }
303 assert!(rx.recv().is_ok(), "exactly one request should be sent");
304}
305
306#[test]
307fn auth_failure_says_where_the_key_lives() {
308 const UNAUTHORIZED: &str = concat!(
309 "HTTP/1.1 401 Unauthorized\r\n",
310 "Content-Type: application/json\r\n",
311 "Connection: close\r\n",
312 "\r\n",
313 "{\"error\":{\"code\":\"api_key_expired\",\"message\":\"This API key has expired.\"}}",
314 );
315 let (base, _rx) = serve_times(vec![UNAUTHORIZED]);
316 let mut sink = Collector::default();
317 let error = provider::chat(
318 &config(base),
319 &[json!({ "role": "user", "content": "hi" })],
320 &[],
321 &AtomicBool::new(false),
322 &mut sink,
323 )
324 .expect_err("401 should fail");
325
326 let message = format!("{error}");
327 assert!(message.contains("OPENCODE_API_KEY"), "{message}");
328}
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 @@
1use std::fs;
2use std::path::PathBuf;
3use std::process::Command;
4
5use serde_json::json;
6
7use agent686::session::{self, Session};
8
9fn temp_dir(tag: &str) -> PathBuf {
10 let dir = std::env::temp_dir().join(format!("agent686-sess-{tag}-{}", std::process::id()));
11 let _ = fs::remove_dir_all(&dir);
12 fs::create_dir_all(&dir).unwrap();
13 dir
14}
15
16#[test]
17fn sessions_create_list_and_replay() {
18 let dir = temp_dir("roundtrip");
19 std::env::set_var("AGENT686_DATA", &dir);
20
21 let system = json!({ "role": "system", "content": "frozen" });
22 let mut alpha = Session::create_as("alpha".into(), "model-a", &system).unwrap();
23 assert!(
24 Session::create_as("alpha".into(), "model-a", &system).is_err(),
25 "duplicate ids must not overwrite a session"
26 );
27
28 alpha
29 .append(&json!({ "role": "user", "content": "hello" }), None)
30 .unwrap();
31 alpha
32 .append(
33 &json!({ "role": "assistant", "content": "hi" }),
34 Some("because"),
35 )
36 .unwrap();
37
38 assert!(session::exists("alpha"));
39 assert!(!session::exists("nope"));
40
41 let listed = session::list().unwrap();
42 assert_eq!(listed.len(), 1);
43 assert_eq!(listed[0].id, "alpha");
44 assert_eq!(listed[0].model, "model-a");
45 assert_eq!(listed[0].messages, 2);
46
47 let (reopened, system_back, messages) = Session::open("alpha").unwrap();
48 assert_eq!(reopened.id, "alpha");
49 assert_eq!(system_back["content"], "frozen");
50 assert_eq!(messages.len(), 2);
51 assert_eq!(messages[1]["content"], "hi");
52 // Reasoning is stored beside the message but must not be replayed.
53 assert!(messages[1].get("_reasoning").is_none());
54}
55
56#[test]
57fn cli_lists_sessions_without_a_key() {
58 let dir = temp_dir("cli");
59 let output = Command::new(env!("CARGO_BIN_EXE_agent686"))
60 .env("AGENT686_DATA", &dir)
61 .env_remove("OPENCODE_API_KEY")
62 .arg("--list")
63 .output()
64 .unwrap();
65
66 assert!(output.status.success(), "{output:?}");
67 let stdout = String::from_utf8_lossy(&output.stdout);
68 assert!(stdout.contains("no sessions"), "{stdout}");
69}