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, pub opencode: Option, } 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 } } pub fn chat( cfg: &Config, messages: &[Value], cancel: &AtomicBool, sink: &mut dyn Sink, ) -> Result { // serde_json::Value is ordered by key, not by insertion, so the serialised // bytes are stable for the same input. That is what keeps the cache warm; // do not switch this to a struct with fields in a different order, and do // not add anything session-varying to the system message. let body = serde_json::json!({ "model": cfg.model, "messages": messages, "stream": true, "stream_options": { "include_usage": true }, }); let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; 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(180))) .timeout_per_read(Some(Duration::from_secs(180))) .build() .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 outcome = Outcome::default(); let mut decoder = SseDecoder::new(); let mut buf = [0u8; 8192]; let mut reader = resp.body_mut().as_reader(); let mut done = false; while !done { // 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 data.is_empty() { continue; } if data.trim() == "[DONE]" { done = true; break; } let chunk: Chunk = match serde_json::from_str(&data) { Ok(c) => c, // A malformed frame is dropped rather than killing the turn; the // stream is the only recovery path and it is still valid SSE. Err(_) => continue, }; apply_chunk(&chunk, &mut outcome, sink); } } if let Some(usage) = &outcome.usage { if usage.is_null() { outcome.usage = None; } } if let Some(opencode) = &outcome.opencode { if opencode.is_null() { outcome.opencode = None; } } sink.done(&outcome, started.elapsed()); Ok(outcome) } fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { if let Some(usage) = &chunk.usage { outcome.usage = Some(usage.clone()); } if let Some(opencode) = &chunk.opencode { outcome.opencode = Some(opencode.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(calls) = &choice.delta.tool_calls { for call in calls { accumulate_tool_call(&mut outcome.tool_calls, call); } } 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. fn accumulate_tool_call(calls: &mut Vec, delta: &ToolCallDelta) { while calls.len() <= delta.index { let index = calls.len(); calls.push(ToolCall { index, id: String::new(), name: String::new(), arguments: String::new(), }); } let call = &mut calls[delta.index]; 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 { 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) } 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, #[serde(default)] opencode: 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 { index: usize, #[serde(default)] id: Option, #[serde(default)] function: Option, } #[derive(Debug, Deserialize)] struct FunctionDelta { #[serde(default)] name: Option, #[serde(default)] arguments: Option, }