use std::io::Read; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use serde::Deserialize; use serde_json::Value; use crate::config::Config; #[derive(Debug)] pub enum Error { Transport(String), Status { code: u16, message: String }, Aborted, } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::Transport(m) => write!(f, "{m}"), Error::Status { code, message } => write!(f, "HTTP {code}: {message}"), Error::Aborted => write!(f, "aborted"), } } } impl std::error::Error for Error {} /// One completed tool call, assembled from streamed deltas. #[derive(Debug, Default, Clone)] pub struct ToolCall { pub index: usize, pub id: String, pub name: String, /// The argument JSON exactly as the model emitted it. Never re-serialised: /// re-encoding can change key order and invalidate the provider's cache. pub arguments: String, } #[derive(Debug, Default)] pub struct Outcome { pub content: String, pub reasoning: String, pub tool_calls: Vec, pub finish: Option, pub usage: Option, } impl Outcome { pub fn allowance(&self) -> Option { self.usage .as_ref()? .get("opencode")? .get("allowance")? .as_f64() } pub fn list_cost(&self) -> Option { self.usage .as_ref()? .get("opencode")? .get("list_cost")? .as_f64() } pub fn tokens(&self) -> (Option, Option) { let usage = match &self.usage { Some(u) => u, None => return (None, None), }; ( usage.get("prompt_tokens").and_then(|v| v.as_u64()), usage.get("completion_tokens").and_then(|v| v.as_u64()), ) } } pub trait Sink { fn text(&mut self, s: &str); fn reasoning(&mut self, s: &str); fn done(&mut self, outcome: &Outcome, elapsed: Duration); } /// Decodes an SSE byte stream into `data:` payloads. /// /// Kept as a state machine so that chunk boundaries can fall anywhere: inside a /// line, or inside a multi-byte UTF-8 character. Only complete lines are ever /// converted to text. #[derive(Default)] pub struct SseDecoder { buf: Vec, } impl SseDecoder { pub fn new() -> Self { Self::default() } pub fn feed(&mut self, chunk: &[u8]) -> Vec { self.buf.extend_from_slice(chunk); let mut out = Vec::new(); let mut start = 0; while let Some(rel) = self.buf[start..].iter().position(|&b| b == b'\n') { let end = start + rel; let mut line = &self.buf[start..end]; if line.last() == Some(&b'\r') { line = &line[..line.len() - 1]; } start = end + 1; if let Some(payload) = line.strip_prefix(b"data:") { let payload = payload.strip_prefix(b" ").unwrap_or(payload); out.push(String::from_utf8_lossy(payload).into_owned()); } } self.buf.drain(..start); out } /// Anything left when the connection closes without a final newline. pub fn finish(&mut self) -> Vec { let mut out = Vec::new(); if !self.buf.is_empty() { let mut line = &self.buf[..]; if line.last() == Some(&b'\r') { line = &line[..line.len() - 1]; } if let Some(payload) = line.strip_prefix(b"data:") { let payload = payload.strip_prefix(b" ").unwrap_or(payload); out.push(String::from_utf8_lossy(payload).into_owned()); } self.buf.clear(); } out } } 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() } /// One client per turn: rebuilding it per step pays a TLS handshake on every /// request, which is noticeable on an i686 core. pub fn agent() -> ureq::Agent { ureq::Agent::config_builder() .http_status_as_error(false) .timeout_connect(Some(Duration::from_secs(10))) .timeout_recv_response(Some(Duration::from_secs(180))) .timeout_per_read(Some(Duration::from_secs(180))) .build() .into() } pub fn chat( cfg: &Config, messages: &[Value], tools: &[Value], cancel: &AtomicBool, sink: &mut dyn Sink, ) -> Result { chat_with(&agent(), cfg, messages, tools, cancel, sink) } pub fn chat_with( agent: &ureq::Agent, cfg: &Config, messages: &[Value], tools: &[Value], cancel: &AtomicBool, sink: &mut dyn Sink, ) -> Result { // serde_json::Value orders objects by key, so the serialised bytes are // stable for the same input. That is what keeps the provider's prompt cache // warm. Do not add anything session-varying here. let mut body = serde_json::json!({ "model": cfg.model, "messages": messages, "stream": true, "stream_options": { "include_usage": true }, }); if !tools.is_empty() { body["tools"] = Value::Array(tools.to_vec()); } let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; let started = Instant::now(); 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(); let mut buf = [0u8; 8192]; let mut reader = resp.body_mut().as_reader(); let mut calls: std::collections::BTreeMap = std::collections::BTreeMap::new(); let mut completed = false; let mut done = false; let mut dropped = 0usize; loop { // Blocking reads mean an abort is only noticed when bytes arrive or the // per-read timeout fires. Good enough: the model streams constantly. if cancel.load(Ordering::Relaxed) { return Err(Error::Aborted); } let n = match reader.read(&mut buf) { Ok(0) => break, Ok(n) => n, Err(e) => return Err(Error::Transport(e.to_string())), }; for data in decoder.feed(&buf[..n]) { if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { done = true; break; } } if done { break; } } // A final `data:` frame with no trailing newline is legitimate. if !done { for data in decoder.finish() { if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { break; } } } let before = calls.len(); outcome.tool_calls = calls .into_values() // Some backends emit an empty placeholder alongside a real call; asking // a human to approve a blank command is worse than dropping it. .filter(|call| !(call.name.is_empty() && call.arguments.trim().is_empty())) .collect(); let dropped_calls = before - outcome.tool_calls.len(); if dropped_calls > 0 { eprintln!("agent686: ignored {dropped_calls} empty tool call(s)"); } if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { outcome.usage = None; } if dropped > 0 { eprintln!("agent686: ignored {dropped} malformed stream frame(s)"); } // A connection that closes early, or a 200 that is not SSE at all, must not // be recorded as a complete answer. if !completed { return Err(Error::Transport(format!( "stream ended before completion ({} bytes of text, {} tool call(s)); \ the turn was not recorded as answered", outcome.content.len(), outcome.tool_calls.len() ))); } sink.done(&outcome, started.elapsed()); Ok(outcome) } fn handle_event( data: &str, outcome: &mut Outcome, calls: &mut std::collections::BTreeMap, completed: &mut bool, dropped: &mut usize, sink: &mut dyn Sink, ) -> bool { if data.is_empty() { return false; } if std::env::var_os("AGENT686_DEBUG_STREAM").is_some() { eprintln!("sse: {}", truncate(data, 400)); } if data.trim() == "[DONE]" { *completed = true; return true; } match serde_json::from_str::(data) { Ok(chunk) => { if chunk.choices.iter().any(|choice| choice.finish_reason.is_some()) { *completed = true; } apply_chunk(&chunk, outcome, calls, sink); } // Counted and reported rather than silently swallowed. Err(_) => *dropped += 1, } false } fn apply_chunk( chunk: &Chunk, outcome: &mut Outcome, calls: &mut std::collections::BTreeMap, sink: &mut dyn Sink, ) { if let Some(usage) = &chunk.usage { outcome.usage = Some(usage.clone()); } for choice in &chunk.choices { if let Some(r) = &choice.delta.reasoning_content { if !r.is_empty() { outcome.reasoning.push_str(r); sink.reasoning(r); } } if let Some(t) = &choice.delta.content { if !t.is_empty() { outcome.content.push_str(t); sink.text(t); } } if let Some(deltas) = &choice.delta.tool_calls { for delta in deltas { accumulate_tool_call(calls, delta); } } if let Some(finish) = &choice.finish_reason { outcome.finish = Some(finish.clone()); } } } /// Tool call deltas arrive split across chunks and are keyed by `index`: the /// name and id usually come once, the arguments a fragment at a time. A map /// keyed by index means a missing or non-contiguous index cannot invent an /// empty call or shift the others. fn accumulate_tool_call( calls: &mut std::collections::BTreeMap, delta: &ToolCallDelta, ) { let call = calls.entry(delta.index).or_insert_with(|| ToolCall { index: delta.index, id: String::new(), name: String::new(), arguments: String::new(), }); if let Some(id) = &delta.id { call.id.push_str(id); } if let Some(function) = &delta.function { if let Some(name) = &function.name { call.name.push_str(name); } if let Some(args) = &function.arguments { call.arguments.push_str(args); } } } fn error_message(body: &str) -> String { let trimmed = body.trim_start(); if trimmed.starts_with('<') { return "the provider returned an HTML error page rather than JSON".to_string(); } if let Ok(v) = serde_json::from_str::(body) { if let Some(err) = v.get("error") { if let Some(message) = err.get("message").and_then(|m| m.as_str()) { return match err.get("code").and_then(|c| c.as_str()) { Some(code) if !code.is_empty() => format!("{message} ({code})"), _ => message.to_string(), }; } } if let Some(message) = v.get("message").and_then(|m| m.as_str()) { return message.to_string(); } } truncate(body.trim(), 500) } pub fn truncate(s: &str, max: usize) -> String { match s.char_indices().nth(max) { Some((i, _)) => format!("{}…", &s[..i]), None => s.to_string(), } } #[derive(Debug, Deserialize)] struct Chunk { #[serde(default)] choices: Vec, #[serde(default)] usage: Option, } #[derive(Debug, Deserialize)] struct Choice { #[serde(default)] delta: Delta, #[serde(default)] finish_reason: Option, } #[derive(Debug, Default, Deserialize)] struct Delta { #[serde(default)] content: Option, #[serde(default)] reasoning_content: Option, #[serde(default)] tool_calls: Option>, } #[derive(Debug, Deserialize)] struct ToolCallDelta { #[serde(default)] index: usize, #[serde(default)] id: Option, #[serde(default)] function: Option, } #[derive(Debug, Deserialize)] struct FunctionDelta { #[serde(default)] name: Option, #[serde(default)] arguments: Option, } /// Lists the models the provider offers for this key, for `--doctor`. pub fn models(cfg: &Config) -> Result, Error> { let agent: ureq::Agent = ureq::Agent::config_builder() .http_status_as_error(false) .timeout_connect(Some(Duration::from_secs(10))) .timeout_recv_response(Some(Duration::from_secs(20))) .timeout_per_read(Some(Duration::from_secs(20))) .build() .into(); let url = format!("{}/models", cfg.base_url.trim_end_matches('/')); let mut response = agent .get(&url) .header("Authorization", format!("Bearer {}", cfg.api_key)) .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) .header("x-opencode-session", &cfg.session) .call() .map_err(|e| Error::Transport(e.to_string()))?; let status = response.status().as_u16(); let body = response .body_mut() .with_config() .limit(8 * 1024 * 1024) .read_to_string() .unwrap_or_default(); if !(200..300).contains(&status) { return Err(Error::Status { code: status, message: explain(status, &error_message(&body)), }); } let value: Value = serde_json::from_str(&body) .map_err(|e| Error::Transport(format!("could not parse the model list: {e}")))?; Ok(value .get("data") .and_then(|data| data.as_array()) .map(|models| { models .iter() .filter_map(|model| model.get("id").and_then(|id| id.as_str())) .map(|id| id.to_string()) .collect() }) .unwrap_or_default()) }