From 7175543e00caa9ce35487fa7f8b1b479c1ba00a2 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 02:54:21 +0100 Subject: M0: streaming provider, SSE decoder, mock provider, i686 build gate --- src/agent.rs | 67 ++++++++++++ src/config.rs | 67 ++++++++++++ src/lib.rs | 5 + src/main.rs | 136 ++++++++++++++++++++++++ src/provider.rs | 319 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/session.rs | 39 +++++++ src/ui.rs | 75 +++++++++++++ 7 files changed, 708 insertions(+) create mode 100644 src/agent.rs create mode 100644 src/config.rs create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 src/provider.rs create mode 100644 src/session.rs create mode 100644 src/ui.rs (limited to 'src') diff --git a/src/agent.rs b/src/agent.rs new file mode 100644 index 0000000..2d84566 --- /dev/null +++ b/src/agent.rs @@ -0,0 +1,67 @@ +use std::sync::atomic::AtomicBool; + +use serde_json::{json, Value}; + +use crate::config::Config; +use crate::provider::{self, Error, Outcome, Sink}; + +/// Frozen for the life of the process. Anything session-varying added here +/// invalidates the provider's prompt cache, so keep it boring. +pub fn system_message() -> Value { + json!({ + "role": "system", + "content": "You are agent686, a coding agent working in a Unix terminal. \ + You edit files and run commands. Be terse and do not explain \ + what you are about to do before doing it." + }) +} + +/// Appends the user message, runs one provider round trip, and appends the +/// assistant message to the history whether or not it asked for tools. +pub fn run_turn( + cfg: &Config, + history: &mut Vec, + prompt: &str, + cancel: &AtomicBool, + sink: &mut dyn Sink, +) -> Result { + history.push(json!({ "role": "user", "content": prompt })); + + let outcome = provider::chat(cfg, history, cancel, sink)?; + + let mut message = serde_json::Map::new(); + message.insert("role".into(), json!("assistant")); + message.insert( + "content".into(), + if outcome.content.is_empty() { + Value::Null + } else { + json!(outcome.content) + }, + ); + if !outcome.tool_calls.is_empty() { + let calls: Vec = outcome + .tool_calls + .iter() + .map(|call| { + json!({ + "id": call.id, + "type": "function", + "function": { + "name": call.name, + // Byte-for-byte what the model sent. + "arguments": call.arguments, + } + }) + }) + .collect(); + message.insert("tool_calls".into(), Value::Array(calls)); + } + history.push(Value::Object(message)); + + Ok(outcome) +} + +pub fn new_history() -> Vec { + vec![system_message()] +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..b781637 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,67 @@ +use std::path::PathBuf; + +pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; +pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash"; + +#[derive(Debug, Clone)] +pub struct Config { + pub base_url: String, + pub api_key: String, + pub model: String, + pub session: String, +} + +impl Config { + /// CLI flags win over environment variables, which win over defaults. + pub fn resolve( + model: Option, + base_url: Option, + session: Option, + ) -> Result { + Ok(Config { + api_key: api_key()?, + base_url: base_url + .or_else(|| env_nonempty("AGENT686_BASE_URL")) + .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()), + model: model + .or_else(|| env_nonempty("AGENT686_MODEL")) + .unwrap_or_else(|| DEFAULT_MODEL.to_string()), + session: session.unwrap_or_else(crate::session::new_id), + }) + } + + pub fn endpoint(&self) -> String { + format!("{}/chat/completions", self.base_url.trim_end_matches('/')) + } +} + +fn env_nonempty(key: &str) -> Option { + std::env::var(key).ok().filter(|v| !v.trim().is_empty()) +} + +/// The key comes from the environment first, then from a file, so a key never +/// has to live in shell history or in a process listing. +fn api_key() -> Result { + if let Some(k) = env_nonempty("OPENCODE_API_KEY") { + return Ok(k.trim().to_string()); + } + if let Some(path) = key_file() { + if let Ok(k) = std::fs::read_to_string(&path) { + let k = k.trim().to_string(); + if !k.is_empty() { + return Ok(k); + } + } + } + Err(format!( + "no API key: set OPENCODE_API_KEY or write one to {}", + key_file() + .map(|p| p.display().to_string()) + .unwrap_or_else(|| "~/.config/agent686/key".into()) + )) +} + +fn key_file() -> Option { + let home = std::env::var_os("HOME")?; + Some(PathBuf::from(home).join(".config/agent686/key")) +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..20913b2 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,5 @@ +pub mod agent; +pub mod config; +pub mod provider; +pub mod session; +pub mod ui; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..8c9a58c --- /dev/null +++ b/src/main.rs @@ -0,0 +1,136 @@ +use std::io::{BufRead, IsTerminal, Write}; +use std::sync::atomic::AtomicBool; + +use agent686::{agent, config::Config, ui}; + +const HELP: &str = "\ +agent686 — a small coding agent + +USAGE: + agent686 [OPTIONS] [PROMPT...] + +With a prompt it runs one turn and exits; without one it reads prompts from +stdin, one per line. /exit quits. + +OPTIONS: + -m, --model model id (default: deepseek-v4.1-flash) + --base-url provider base URL, e.g. http://127.0.0.1:8080/v1 + --session reuse a session id, including for the provider header + -h, --help this text + +ENVIRONMENT: + OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) + AGENT686_MODEL default model id + AGENT686_BASE_URL default provider base URL +"; + +fn main() { + let mut prompt: Option = None; + let mut model = None; + let mut base_url = None; + let mut session = None; + + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + match arg.as_str() { + "-m" | "--model" => model = args.next(), + "--base-url" => base_url = args.next(), + "--session" => session = args.next(), + "-h" | "--help" => { + print!("{HELP}"); + return; + } + flag if flag.starts_with('-') && flag.len() > 1 => { + eprintln!("agent686: unknown flag {flag}\n"); + print!("{HELP}"); + std::process::exit(2); + } + word => { + prompt = Some(match prompt.take() { + Some(existing) => format!("{existing} {word}"), + None => word.to_string(), + }) + } + } + } + + let cfg = match Config::resolve(model, base_url, session) { + Ok(cfg) => cfg, + Err(message) => { + eprintln!("agent686: {message}"); + std::process::exit(2); + } + }; + + let cancel = AtomicBool::new(false); + let mut history = agent::new_history(); + + // One-shot mode: a prompt on the command line means one turn, then exit. + if let Some(prompt) = prompt { + let mut sink = ui::Renderer::new(ui::stdout_is_tty()); + match agent::run_turn(&cfg, &mut history, &prompt, &cancel, &mut sink) { + Ok(outcome) => note_tool_calls(&outcome), + Err(error) => { + eprintln!("agent686: {error}"); + std::process::exit(1); + } + } + return; + } + + let interactive = std::io::stdin().is_terminal(); + if interactive { + eprintln!( + "agent686 · {} · session {}{}", + cfg.model, + cfg.session, + if is_local(&cfg.base_url) { " · local" } else { "" } + ); + eprintln!("one prompt per line · /exit to quit"); + } + + let stdin = std::io::stdin(); + let mut line = String::new(); + loop { + if interactive { + print!("> "); + let _ = std::io::stdout().flush(); + } + line.clear(); + if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { + break; + } + let text = line.trim_end(); + if text.is_empty() { + continue; + } + if text == "/exit" || text == "/quit" { + break; + } + let mut sink = ui::Renderer::new(ui::stdout_is_tty()); + match agent::run_turn(&cfg, &mut history, text, &cancel, &mut sink) { + Ok(outcome) => note_tool_calls(&outcome), + Err(error) => eprintln!("agent686: {error}"), + } + } +} + +fn note_tool_calls(outcome: &agent686::provider::Outcome) { + if outcome.tool_calls.is_empty() { + return; + } + let names: Vec<&str> = outcome + .tool_calls + .iter() + .map(|call| call.name.as_str()) + .collect(); + eprintln!( + "agent686: model asked for {} tool call(s) [{}]; tools arrive in milestone 2", + names.len(), + names.join(", ") + ); +} + +fn is_local(base_url: &str) -> bool { + base_url.contains("127.0.0.1") || base_url.contains("localhost") +} diff --git a/src/provider.rs b/src/provider.rs new file mode 100644 index 0000000..a2aed64 --- /dev/null +++ b/src/provider.rs @@ -0,0 +1,319 @@ +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, +} diff --git a/src/session.rs b/src/session.rs new file mode 100644 index 0000000..aef4835 --- /dev/null +++ b/src/session.rs @@ -0,0 +1,39 @@ +use std::hash::{Hash, Hasher}; +use std::io::Read; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// A session id is opaque to the provider: it only has to be stable for the life +/// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps +/// it usable as a file name. +pub fn new_id() -> String { + let mut bytes = random_bytes(); + // Put the creation time in the first bytes so ids sort roughly by age. + let ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + bytes[..8].copy_from_slice(&ms.to_be_bytes()); + + let mut out = String::with_capacity(32); + for b in bytes { + out.push_str(&format!("{b:02x}")); + } + out +} + +fn random_bytes() -> [u8; 16] { + let mut bytes = [0u8; 16]; + if let Ok(mut f) = std::fs::File::open("/dev/urandom") { + if f.read_exact(&mut bytes).is_ok() { + return bytes; + } + } + // Fallback: not cryptographic, but an id only has to not collide. + let mut h = std::collections::hash_map::DefaultHasher::new(); + SystemTime::now().hash(&mut h); + std::process::id().hash(&mut h); + let v = h.finish(); + bytes[..8].copy_from_slice(&v.to_be_bytes()); + bytes[8..].copy_from_slice(&(v ^ 0x9e37_79b9_7f4a_7c15).to_be_bytes()); + bytes +} diff --git a/src/ui.rs b/src/ui.rs new file mode 100644 index 0000000..13440b2 --- /dev/null +++ b/src/ui.rs @@ -0,0 +1,75 @@ +use std::io::{IsTerminal, Write}; +use std::time::Duration; + +use crate::provider::{Outcome, Sink}; + +pub fn stdout_is_tty() -> bool { + std::io::stdout().is_terminal() +} + +/// Streams to stdout. Colour is used only when stdout is a terminal, so piping +/// the output somewhere gives clean text. +pub struct Renderer { + color: bool, + dimmed: bool, + wrote_text: bool, +} + +impl Renderer { + pub fn new(color: bool) -> Self { + Self { + color, + dimmed: false, + wrote_text: false, + } + } + + fn undim(&mut self) { + if self.dimmed { + print!("\x1b[0m"); + self.dimmed = false; + } + } +} + +impl Sink for Renderer { + fn text(&mut self, s: &str) { + self.undim(); + print!("{s}"); + let _ = std::io::stdout().flush(); + self.wrote_text = true; + } + + fn reasoning(&mut self, s: &str) { + if !self.color { + return; + } + if !self.dimmed { + print!("\x1b[2m"); + self.dimmed = true; + } + print!("{s}"); + let _ = std::io::stdout().flush(); + } + + fn done(&mut self, outcome: &Outcome, elapsed: Duration) { + self.undim(); + if self.wrote_text { + println!(); + } + let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())]; + if let Some(usage) = &outcome.usage { + let input = usage.get("prompt_tokens").and_then(|v| v.as_u64()); + let output = usage.get("completion_tokens").and_then(|v| v.as_u64()); + if let (Some(i), Some(o)) = (input, output) { + parts.push(format!("{i} in · {o} out")); + } + } + let line = format!("─ {}", parts.join(" · ")); + if self.color { + println!("\x1b[2m{line}\x1b[0m"); + } else { + println!("{line}"); + } + } +} -- cgit v1.2.3