diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/agent.rs | 67 | ||||
| -rw-r--r-- | src/config.rs | 67 | ||||
| -rw-r--r-- | src/lib.rs | 5 | ||||
| -rw-r--r-- | src/main.rs | 136 | ||||
| -rw-r--r-- | src/provider.rs | 319 | ||||
| -rw-r--r-- | src/session.rs | 39 | ||||
| -rw-r--r-- | src/ui.rs | 75 |
7 files changed, 708 insertions, 0 deletions
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 @@ | |||
| 1 | use std::sync::atomic::AtomicBool; | ||
| 2 | |||
| 3 | use serde_json::{json, Value}; | ||
| 4 | |||
| 5 | use crate::config::Config; | ||
| 6 | use crate::provider::{self, Error, Outcome, Sink}; | ||
| 7 | |||
| 8 | /// Frozen for the life of the process. Anything session-varying added here | ||
| 9 | /// invalidates the provider's prompt cache, so keep it boring. | ||
| 10 | pub fn system_message() -> Value { | ||
| 11 | json!({ | ||
| 12 | "role": "system", | ||
| 13 | "content": "You are agent686, a coding agent working in a Unix terminal. \ | ||
| 14 | You edit files and run commands. Be terse and do not explain \ | ||
| 15 | what you are about to do before doing it." | ||
| 16 | }) | ||
| 17 | } | ||
| 18 | |||
| 19 | /// Appends the user message, runs one provider round trip, and appends the | ||
| 20 | /// assistant message to the history whether or not it asked for tools. | ||
| 21 | pub fn run_turn( | ||
| 22 | cfg: &Config, | ||
| 23 | history: &mut Vec<Value>, | ||
| 24 | prompt: &str, | ||
| 25 | cancel: &AtomicBool, | ||
| 26 | sink: &mut dyn Sink, | ||
| 27 | ) -> Result<Outcome, Error> { | ||
| 28 | history.push(json!({ "role": "user", "content": prompt })); | ||
| 29 | |||
| 30 | let outcome = provider::chat(cfg, history, cancel, sink)?; | ||
| 31 | |||
| 32 | let mut message = serde_json::Map::new(); | ||
| 33 | message.insert("role".into(), json!("assistant")); | ||
| 34 | message.insert( | ||
| 35 | "content".into(), | ||
| 36 | if outcome.content.is_empty() { | ||
| 37 | Value::Null | ||
| 38 | } else { | ||
| 39 | json!(outcome.content) | ||
| 40 | }, | ||
| 41 | ); | ||
| 42 | if !outcome.tool_calls.is_empty() { | ||
| 43 | let calls: Vec<Value> = outcome | ||
| 44 | .tool_calls | ||
| 45 | .iter() | ||
| 46 | .map(|call| { | ||
| 47 | json!({ | ||
| 48 | "id": call.id, | ||
| 49 | "type": "function", | ||
| 50 | "function": { | ||
| 51 | "name": call.name, | ||
| 52 | // Byte-for-byte what the model sent. | ||
| 53 | "arguments": call.arguments, | ||
| 54 | } | ||
| 55 | }) | ||
| 56 | }) | ||
| 57 | .collect(); | ||
| 58 | message.insert("tool_calls".into(), Value::Array(calls)); | ||
| 59 | } | ||
| 60 | history.push(Value::Object(message)); | ||
| 61 | |||
| 62 | Ok(outcome) | ||
| 63 | } | ||
| 64 | |||
| 65 | pub fn new_history() -> Vec<Value> { | ||
| 66 | vec![system_message()] | ||
| 67 | } | ||
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 @@ | |||
| 1 | use std::path::PathBuf; | ||
| 2 | |||
| 3 | pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; | ||
| 4 | pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash"; | ||
| 5 | |||
| 6 | #[derive(Debug, Clone)] | ||
| 7 | pub struct Config { | ||
| 8 | pub base_url: String, | ||
| 9 | pub api_key: String, | ||
| 10 | pub model: String, | ||
| 11 | pub session: String, | ||
| 12 | } | ||
| 13 | |||
| 14 | impl Config { | ||
| 15 | /// CLI flags win over environment variables, which win over defaults. | ||
| 16 | pub fn resolve( | ||
| 17 | model: Option<String>, | ||
| 18 | base_url: Option<String>, | ||
| 19 | session: Option<String>, | ||
| 20 | ) -> Result<Config, String> { | ||
| 21 | Ok(Config { | ||
| 22 | api_key: api_key()?, | ||
| 23 | base_url: base_url | ||
| 24 | .or_else(|| env_nonempty("AGENT686_BASE_URL")) | ||
| 25 | .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()), | ||
| 26 | model: model | ||
| 27 | .or_else(|| env_nonempty("AGENT686_MODEL")) | ||
| 28 | .unwrap_or_else(|| DEFAULT_MODEL.to_string()), | ||
| 29 | session: session.unwrap_or_else(crate::session::new_id), | ||
| 30 | }) | ||
| 31 | } | ||
| 32 | |||
| 33 | pub fn endpoint(&self) -> String { | ||
| 34 | format!("{}/chat/completions", self.base_url.trim_end_matches('/')) | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | fn env_nonempty(key: &str) -> Option<String> { | ||
| 39 | std::env::var(key).ok().filter(|v| !v.trim().is_empty()) | ||
| 40 | } | ||
| 41 | |||
| 42 | /// The key comes from the environment first, then from a file, so a key never | ||
| 43 | /// has to live in shell history or in a process listing. | ||
| 44 | fn api_key() -> Result<String, String> { | ||
| 45 | if let Some(k) = env_nonempty("OPENCODE_API_KEY") { | ||
| 46 | return Ok(k.trim().to_string()); | ||
| 47 | } | ||
| 48 | if let Some(path) = key_file() { | ||
| 49 | if let Ok(k) = std::fs::read_to_string(&path) { | ||
| 50 | let k = k.trim().to_string(); | ||
| 51 | if !k.is_empty() { | ||
| 52 | return Ok(k); | ||
| 53 | } | ||
| 54 | } | ||
| 55 | } | ||
| 56 | Err(format!( | ||
| 57 | "no API key: set OPENCODE_API_KEY or write one to {}", | ||
| 58 | key_file() | ||
| 59 | .map(|p| p.display().to_string()) | ||
| 60 | .unwrap_or_else(|| "~/.config/agent686/key".into()) | ||
| 61 | )) | ||
| 62 | } | ||
| 63 | |||
| 64 | fn key_file() -> Option<PathBuf> { | ||
| 65 | let home = std::env::var_os("HOME")?; | ||
| 66 | Some(PathBuf::from(home).join(".config/agent686/key")) | ||
| 67 | } | ||
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 @@ | |||
| 1 | pub mod agent; | ||
| 2 | pub mod config; | ||
| 3 | pub mod provider; | ||
| 4 | pub mod session; | ||
| 5 | 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 @@ | |||
| 1 | use std::io::{BufRead, IsTerminal, Write}; | ||
| 2 | use std::sync::atomic::AtomicBool; | ||
| 3 | |||
| 4 | use agent686::{agent, config::Config, ui}; | ||
| 5 | |||
| 6 | const HELP: &str = "\ | ||
| 7 | agent686 — a small coding agent | ||
| 8 | |||
| 9 | USAGE: | ||
| 10 | agent686 [OPTIONS] [PROMPT...] | ||
| 11 | |||
| 12 | With a prompt it runs one turn and exits; without one it reads prompts from | ||
| 13 | stdin, one per line. /exit quits. | ||
| 14 | |||
| 15 | OPTIONS: | ||
| 16 | -m, --model <ID> model id (default: deepseek-v4.1-flash) | ||
| 17 | --base-url <URL> provider base URL, e.g. http://127.0.0.1:8080/v1 | ||
| 18 | --session <ID> reuse a session id, including for the provider header | ||
| 19 | -h, --help this text | ||
| 20 | |||
| 21 | ENVIRONMENT: | ||
| 22 | OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) | ||
| 23 | AGENT686_MODEL default model id | ||
| 24 | AGENT686_BASE_URL default provider base URL | ||
| 25 | "; | ||
| 26 | |||
| 27 | fn main() { | ||
| 28 | let mut prompt: Option<String> = None; | ||
| 29 | let mut model = None; | ||
| 30 | let mut base_url = None; | ||
| 31 | let mut session = None; | ||
| 32 | |||
| 33 | let mut args = std::env::args().skip(1); | ||
| 34 | while let Some(arg) = args.next() { | ||
| 35 | match arg.as_str() { | ||
| 36 | "-m" | "--model" => model = args.next(), | ||
| 37 | "--base-url" => base_url = args.next(), | ||
| 38 | "--session" => session = args.next(), | ||
| 39 | "-h" | "--help" => { | ||
| 40 | print!("{HELP}"); | ||
| 41 | return; | ||
| 42 | } | ||
| 43 | flag if flag.starts_with('-') && flag.len() > 1 => { | ||
| 44 | eprintln!("agent686: unknown flag {flag}\n"); | ||
| 45 | print!("{HELP}"); | ||
| 46 | std::process::exit(2); | ||
| 47 | } | ||
| 48 | word => { | ||
| 49 | prompt = Some(match prompt.take() { | ||
| 50 | Some(existing) => format!("{existing} {word}"), | ||
| 51 | None => word.to_string(), | ||
| 52 | }) | ||
| 53 | } | ||
| 54 | } | ||
| 55 | } | ||
| 56 | |||
| 57 | let cfg = match Config::resolve(model, base_url, session) { | ||
| 58 | Ok(cfg) => cfg, | ||
| 59 | Err(message) => { | ||
| 60 | eprintln!("agent686: {message}"); | ||
| 61 | std::process::exit(2); | ||
| 62 | } | ||
| 63 | }; | ||
| 64 | |||
| 65 | let cancel = AtomicBool::new(false); | ||
| 66 | let mut history = agent::new_history(); | ||
| 67 | |||
| 68 | // One-shot mode: a prompt on the command line means one turn, then exit. | ||
| 69 | if let Some(prompt) = prompt { | ||
| 70 | let mut sink = ui::Renderer::new(ui::stdout_is_tty()); | ||
| 71 | match agent::run_turn(&cfg, &mut history, &prompt, &cancel, &mut sink) { | ||
| 72 | Ok(outcome) => note_tool_calls(&outcome), | ||
| 73 | Err(error) => { | ||
| 74 | eprintln!("agent686: {error}"); | ||
| 75 | std::process::exit(1); | ||
| 76 | } | ||
| 77 | } | ||
| 78 | return; | ||
| 79 | } | ||
| 80 | |||
| 81 | let interactive = std::io::stdin().is_terminal(); | ||
| 82 | if interactive { | ||
| 83 | eprintln!( | ||
| 84 | "agent686 · {} · session {}{}", | ||
| 85 | cfg.model, | ||
| 86 | cfg.session, | ||
| 87 | if is_local(&cfg.base_url) { " · local" } else { "" } | ||
| 88 | ); | ||
| 89 | eprintln!("one prompt per line · /exit to quit"); | ||
| 90 | } | ||
| 91 | |||
| 92 | let stdin = std::io::stdin(); | ||
| 93 | let mut line = String::new(); | ||
| 94 | loop { | ||
| 95 | if interactive { | ||
| 96 | print!("> "); | ||
| 97 | let _ = std::io::stdout().flush(); | ||
| 98 | } | ||
| 99 | line.clear(); | ||
| 100 | if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { | ||
| 101 | break; | ||
| 102 | } | ||
| 103 | let text = line.trim_end(); | ||
| 104 | if text.is_empty() { | ||
| 105 | continue; | ||
| 106 | } | ||
| 107 | if text == "/exit" || text == "/quit" { | ||
| 108 | break; | ||
| 109 | } | ||
| 110 | let mut sink = ui::Renderer::new(ui::stdout_is_tty()); | ||
| 111 | match agent::run_turn(&cfg, &mut history, text, &cancel, &mut sink) { | ||
| 112 | Ok(outcome) => note_tool_calls(&outcome), | ||
| 113 | Err(error) => eprintln!("agent686: {error}"), | ||
| 114 | } | ||
| 115 | } | ||
| 116 | } | ||
| 117 | |||
| 118 | fn note_tool_calls(outcome: &agent686::provider::Outcome) { | ||
| 119 | if outcome.tool_calls.is_empty() { | ||
| 120 | return; | ||
| 121 | } | ||
| 122 | let names: Vec<&str> = outcome | ||
| 123 | .tool_calls | ||
| 124 | .iter() | ||
| 125 | .map(|call| call.name.as_str()) | ||
| 126 | .collect(); | ||
| 127 | eprintln!( | ||
| 128 | "agent686: model asked for {} tool call(s) [{}]; tools arrive in milestone 2", | ||
| 129 | names.len(), | ||
| 130 | names.join(", ") | ||
| 131 | ); | ||
| 132 | } | ||
| 133 | |||
| 134 | fn is_local(base_url: &str) -> bool { | ||
| 135 | base_url.contains("127.0.0.1") || base_url.contains("localhost") | ||
| 136 | } | ||
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 @@ | |||
| 1 | use std::io::Read; | ||
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 3 | use std::time::{Duration, Instant}; | ||
| 4 | |||
| 5 | use serde::Deserialize; | ||
| 6 | use serde_json::Value; | ||
| 7 | |||
| 8 | use crate::config::Config; | ||
| 9 | |||
| 10 | #[derive(Debug)] | ||
| 11 | pub enum Error { | ||
| 12 | Transport(String), | ||
| 13 | Status { code: u16, message: String }, | ||
| 14 | Aborted, | ||
| 15 | } | ||
| 16 | |||
| 17 | impl std::fmt::Display for Error { | ||
| 18 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 19 | match self { | ||
| 20 | Error::Transport(m) => write!(f, "{m}"), | ||
| 21 | Error::Status { code, message } => write!(f, "HTTP {code}: {message}"), | ||
| 22 | Error::Aborted => write!(f, "aborted"), | ||
| 23 | } | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | impl std::error::Error for Error {} | ||
| 28 | |||
| 29 | /// One completed tool call, assembled from streamed deltas. | ||
| 30 | #[derive(Debug, Default, Clone)] | ||
| 31 | pub struct ToolCall { | ||
| 32 | pub index: usize, | ||
| 33 | pub id: String, | ||
| 34 | pub name: String, | ||
| 35 | /// The argument JSON exactly as the model emitted it. Never re-serialised: | ||
| 36 | /// re-encoding can change key order and invalidate the provider's cache. | ||
| 37 | pub arguments: String, | ||
| 38 | } | ||
| 39 | |||
| 40 | #[derive(Debug, Default)] | ||
| 41 | pub struct Outcome { | ||
| 42 | pub content: String, | ||
| 43 | pub reasoning: String, | ||
| 44 | pub tool_calls: Vec<ToolCall>, | ||
| 45 | pub finish: Option<String>, | ||
| 46 | pub usage: Option<Value>, | ||
| 47 | pub opencode: Option<Value>, | ||
| 48 | } | ||
| 49 | |||
| 50 | pub trait Sink { | ||
| 51 | fn text(&mut self, s: &str); | ||
| 52 | fn reasoning(&mut self, s: &str); | ||
| 53 | fn done(&mut self, outcome: &Outcome, elapsed: Duration); | ||
| 54 | } | ||
| 55 | |||
| 56 | /// Decodes an SSE byte stream into `data:` payloads. | ||
| 57 | /// | ||
| 58 | /// Kept as a state machine so that chunk boundaries can fall anywhere: inside a | ||
| 59 | /// line, or inside a multi-byte UTF-8 character. Only complete lines are ever | ||
| 60 | /// converted to text. | ||
| 61 | #[derive(Default)] | ||
| 62 | pub struct SseDecoder { | ||
| 63 | buf: Vec<u8>, | ||
| 64 | } | ||
| 65 | |||
| 66 | impl SseDecoder { | ||
| 67 | pub fn new() -> Self { | ||
| 68 | Self::default() | ||
| 69 | } | ||
| 70 | |||
| 71 | pub fn feed(&mut self, chunk: &[u8]) -> Vec<String> { | ||
| 72 | self.buf.extend_from_slice(chunk); | ||
| 73 | let mut out = Vec::new(); | ||
| 74 | let mut start = 0; | ||
| 75 | while let Some(rel) = self.buf[start..].iter().position(|&b| b == b'\n') { | ||
| 76 | let end = start + rel; | ||
| 77 | let mut line = &self.buf[start..end]; | ||
| 78 | if line.last() == Some(&b'\r') { | ||
| 79 | line = &line[..line.len() - 1]; | ||
| 80 | } | ||
| 81 | start = end + 1; | ||
| 82 | if let Some(payload) = line.strip_prefix(b"data:") { | ||
| 83 | let payload = payload.strip_prefix(b" ").unwrap_or(payload); | ||
| 84 | out.push(String::from_utf8_lossy(payload).into_owned()); | ||
| 85 | } | ||
| 86 | } | ||
| 87 | self.buf.drain(..start); | ||
| 88 | out | ||
| 89 | } | ||
| 90 | } | ||
| 91 | |||
| 92 | pub fn chat( | ||
| 93 | cfg: &Config, | ||
| 94 | messages: &[Value], | ||
| 95 | cancel: &AtomicBool, | ||
| 96 | sink: &mut dyn Sink, | ||
| 97 | ) -> Result<Outcome, Error> { | ||
| 98 | // serde_json::Value is ordered by key, not by insertion, so the serialised | ||
| 99 | // bytes are stable for the same input. That is what keeps the cache warm; | ||
| 100 | // do not switch this to a struct with fields in a different order, and do | ||
| 101 | // not add anything session-varying to the system message. | ||
| 102 | let body = serde_json::json!({ | ||
| 103 | "model": cfg.model, | ||
| 104 | "messages": messages, | ||
| 105 | "stream": true, | ||
| 106 | "stream_options": { "include_usage": true }, | ||
| 107 | }); | ||
| 108 | let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; | ||
| 109 | |||
| 110 | let agent: ureq::Agent = ureq::Agent::config_builder() | ||
| 111 | .http_status_as_error(false) | ||
| 112 | .timeout_connect(Some(Duration::from_secs(10))) | ||
| 113 | .timeout_recv_response(Some(Duration::from_secs(180))) | ||
| 114 | .timeout_per_read(Some(Duration::from_secs(180))) | ||
| 115 | .build() | ||
| 116 | .into(); | ||
| 117 | |||
| 118 | let started = Instant::now(); | ||
| 119 | let mut resp = agent | ||
| 120 | .post(&cfg.endpoint()) | ||
| 121 | .header("Content-Type", "application/json") | ||
| 122 | .header("Accept", "text/event-stream") | ||
| 123 | .header("Authorization", format!("Bearer {}", cfg.api_key)) | ||
| 124 | .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) | ||
| 125 | // Required by OpenCode Go: stable per conversation, used for routing and | ||
| 126 | // prompt caching. | ||
| 127 | .header("x-opencode-session", &cfg.session) | ||
| 128 | .send(bytes) | ||
| 129 | .map_err(|e| Error::Transport(e.to_string()))?; | ||
| 130 | |||
| 131 | let status = resp.status().as_u16(); | ||
| 132 | if !(200..300).contains(&status) { | ||
| 133 | let text = resp | ||
| 134 | .body_mut() | ||
| 135 | .with_config() | ||
| 136 | .limit(256 * 1024) | ||
| 137 | .read_to_string() | ||
| 138 | .unwrap_or_default(); | ||
| 139 | return Err(Error::Status { | ||
| 140 | code: status, | ||
| 141 | message: error_message(&text), | ||
| 142 | }); | ||
| 143 | } | ||
| 144 | |||
| 145 | let mut outcome = Outcome::default(); | ||
| 146 | let mut decoder = SseDecoder::new(); | ||
| 147 | let mut buf = [0u8; 8192]; | ||
| 148 | let mut reader = resp.body_mut().as_reader(); | ||
| 149 | let mut done = false; | ||
| 150 | |||
| 151 | while !done { | ||
| 152 | // Blocking reads mean an abort is only noticed when bytes arrive or the | ||
| 153 | // per-read timeout fires. Good enough: the model streams constantly. | ||
| 154 | if cancel.load(Ordering::Relaxed) { | ||
| 155 | return Err(Error::Aborted); | ||
| 156 | } | ||
| 157 | let n = match reader.read(&mut buf) { | ||
| 158 | Ok(0) => break, | ||
| 159 | Ok(n) => n, | ||
| 160 | Err(e) => return Err(Error::Transport(e.to_string())), | ||
| 161 | }; | ||
| 162 | for data in decoder.feed(&buf[..n]) { | ||
| 163 | if data.is_empty() { | ||
| 164 | continue; | ||
| 165 | } | ||
| 166 | if data.trim() == "[DONE]" { | ||
| 167 | done = true; | ||
| 168 | break; | ||
| 169 | } | ||
| 170 | let chunk: Chunk = match serde_json::from_str(&data) { | ||
| 171 | Ok(c) => c, | ||
| 172 | // A malformed frame is dropped rather than killing the turn; the | ||
| 173 | // stream is the only recovery path and it is still valid SSE. | ||
| 174 | Err(_) => continue, | ||
| 175 | }; | ||
| 176 | apply_chunk(&chunk, &mut outcome, sink); | ||
| 177 | } | ||
| 178 | } | ||
| 179 | |||
| 180 | if let Some(usage) = &outcome.usage { | ||
| 181 | if usage.is_null() { | ||
| 182 | outcome.usage = None; | ||
| 183 | } | ||
| 184 | } | ||
| 185 | if let Some(opencode) = &outcome.opencode { | ||
| 186 | if opencode.is_null() { | ||
| 187 | outcome.opencode = None; | ||
| 188 | } | ||
| 189 | } | ||
| 190 | |||
| 191 | sink.done(&outcome, started.elapsed()); | ||
| 192 | Ok(outcome) | ||
| 193 | } | ||
| 194 | |||
| 195 | fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { | ||
| 196 | if let Some(usage) = &chunk.usage { | ||
| 197 | outcome.usage = Some(usage.clone()); | ||
| 198 | } | ||
| 199 | if let Some(opencode) = &chunk.opencode { | ||
| 200 | outcome.opencode = Some(opencode.clone()); | ||
| 201 | } | ||
| 202 | for choice in &chunk.choices { | ||
| 203 | if let Some(r) = &choice.delta.reasoning_content { | ||
| 204 | if !r.is_empty() { | ||
| 205 | outcome.reasoning.push_str(r); | ||
| 206 | sink.reasoning(r); | ||
| 207 | } | ||
| 208 | } | ||
| 209 | if let Some(t) = &choice.delta.content { | ||
| 210 | if !t.is_empty() { | ||
| 211 | outcome.content.push_str(t); | ||
| 212 | sink.text(t); | ||
| 213 | } | ||
| 214 | } | ||
| 215 | if let Some(calls) = &choice.delta.tool_calls { | ||
| 216 | for call in calls { | ||
| 217 | accumulate_tool_call(&mut outcome.tool_calls, call); | ||
| 218 | } | ||
| 219 | } | ||
| 220 | if let Some(finish) = &choice.finish_reason { | ||
| 221 | outcome.finish = Some(finish.clone()); | ||
| 222 | } | ||
| 223 | } | ||
| 224 | } | ||
| 225 | |||
| 226 | /// Tool call deltas arrive split across chunks and are keyed by `index`: the | ||
| 227 | /// name and id usually come once, the arguments a fragment at a time. | ||
| 228 | fn accumulate_tool_call(calls: &mut Vec<ToolCall>, delta: &ToolCallDelta) { | ||
| 229 | while calls.len() <= delta.index { | ||
| 230 | let index = calls.len(); | ||
| 231 | calls.push(ToolCall { | ||
| 232 | index, | ||
| 233 | id: String::new(), | ||
| 234 | name: String::new(), | ||
| 235 | arguments: String::new(), | ||
| 236 | }); | ||
| 237 | } | ||
| 238 | let call = &mut calls[delta.index]; | ||
| 239 | if let Some(id) = &delta.id { | ||
| 240 | call.id.push_str(id); | ||
| 241 | } | ||
| 242 | if let Some(function) = &delta.function { | ||
| 243 | if let Some(name) = &function.name { | ||
| 244 | call.name.push_str(name); | ||
| 245 | } | ||
| 246 | if let Some(args) = &function.arguments { | ||
| 247 | call.arguments.push_str(args); | ||
| 248 | } | ||
| 249 | } | ||
| 250 | } | ||
| 251 | |||
| 252 | fn error_message(body: &str) -> String { | ||
| 253 | if let Ok(v) = serde_json::from_str::<Value>(body) { | ||
| 254 | if let Some(err) = v.get("error") { | ||
| 255 | if let Some(message) = err.get("message").and_then(|m| m.as_str()) { | ||
| 256 | return match err.get("code").and_then(|c| c.as_str()) { | ||
| 257 | Some(code) if !code.is_empty() => format!("{message} ({code})"), | ||
| 258 | _ => message.to_string(), | ||
| 259 | }; | ||
| 260 | } | ||
| 261 | } | ||
| 262 | if let Some(message) = v.get("message").and_then(|m| m.as_str()) { | ||
| 263 | return message.to_string(); | ||
| 264 | } | ||
| 265 | } | ||
| 266 | truncate(body.trim(), 500) | ||
| 267 | } | ||
| 268 | |||
| 269 | fn truncate(s: &str, max: usize) -> String { | ||
| 270 | match s.char_indices().nth(max) { | ||
| 271 | Some((i, _)) => format!("{}…", &s[..i]), | ||
| 272 | None => s.to_string(), | ||
| 273 | } | ||
| 274 | } | ||
| 275 | |||
| 276 | #[derive(Debug, Deserialize)] | ||
| 277 | struct Chunk { | ||
| 278 | #[serde(default)] | ||
| 279 | choices: Vec<Choice>, | ||
| 280 | #[serde(default)] | ||
| 281 | usage: Option<Value>, | ||
| 282 | #[serde(default)] | ||
| 283 | opencode: Option<Value>, | ||
| 284 | } | ||
| 285 | |||
| 286 | #[derive(Debug, Deserialize)] | ||
| 287 | struct Choice { | ||
| 288 | #[serde(default)] | ||
| 289 | delta: Delta, | ||
| 290 | #[serde(default)] | ||
| 291 | finish_reason: Option<String>, | ||
| 292 | } | ||
| 293 | |||
| 294 | #[derive(Debug, Default, Deserialize)] | ||
| 295 | struct Delta { | ||
| 296 | #[serde(default)] | ||
| 297 | content: Option<String>, | ||
| 298 | #[serde(default)] | ||
| 299 | reasoning_content: Option<String>, | ||
| 300 | #[serde(default)] | ||
| 301 | tool_calls: Option<Vec<ToolCallDelta>>, | ||
| 302 | } | ||
| 303 | |||
| 304 | #[derive(Debug, Deserialize)] | ||
| 305 | struct ToolCallDelta { | ||
| 306 | index: usize, | ||
| 307 | #[serde(default)] | ||
| 308 | id: Option<String>, | ||
| 309 | #[serde(default)] | ||
| 310 | function: Option<FunctionDelta>, | ||
| 311 | } | ||
| 312 | |||
| 313 | #[derive(Debug, Deserialize)] | ||
| 314 | struct FunctionDelta { | ||
| 315 | #[serde(default)] | ||
| 316 | name: Option<String>, | ||
| 317 | #[serde(default)] | ||
| 318 | arguments: Option<String>, | ||
| 319 | } | ||
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 @@ | |||
| 1 | use std::hash::{Hash, Hasher}; | ||
| 2 | use std::io::Read; | ||
| 3 | use std::time::{SystemTime, UNIX_EPOCH}; | ||
| 4 | |||
| 5 | /// A session id is opaque to the provider: it only has to be stable for the life | ||
| 6 | /// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps | ||
| 7 | /// it usable as a file name. | ||
| 8 | pub fn new_id() -> String { | ||
| 9 | let mut bytes = random_bytes(); | ||
| 10 | // Put the creation time in the first bytes so ids sort roughly by age. | ||
| 11 | let ms = SystemTime::now() | ||
| 12 | .duration_since(UNIX_EPOCH) | ||
| 13 | .map(|d| d.as_millis() as u64) | ||
| 14 | .unwrap_or(0); | ||
| 15 | bytes[..8].copy_from_slice(&ms.to_be_bytes()); | ||
| 16 | |||
| 17 | let mut out = String::with_capacity(32); | ||
| 18 | for b in bytes { | ||
| 19 | out.push_str(&format!("{b:02x}")); | ||
| 20 | } | ||
| 21 | out | ||
| 22 | } | ||
| 23 | |||
| 24 | fn random_bytes() -> [u8; 16] { | ||
| 25 | let mut bytes = [0u8; 16]; | ||
| 26 | if let Ok(mut f) = std::fs::File::open("/dev/urandom") { | ||
| 27 | if f.read_exact(&mut bytes).is_ok() { | ||
| 28 | return bytes; | ||
| 29 | } | ||
| 30 | } | ||
| 31 | // Fallback: not cryptographic, but an id only has to not collide. | ||
| 32 | let mut h = std::collections::hash_map::DefaultHasher::new(); | ||
| 33 | SystemTime::now().hash(&mut h); | ||
| 34 | std::process::id().hash(&mut h); | ||
| 35 | let v = h.finish(); | ||
| 36 | bytes[..8].copy_from_slice(&v.to_be_bytes()); | ||
| 37 | bytes[8..].copy_from_slice(&(v ^ 0x9e37_79b9_7f4a_7c15).to_be_bytes()); | ||
| 38 | bytes | ||
| 39 | } | ||
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 @@ | |||
| 1 | use std::io::{IsTerminal, Write}; | ||
| 2 | use std::time::Duration; | ||
| 3 | |||
| 4 | use crate::provider::{Outcome, Sink}; | ||
| 5 | |||
| 6 | pub fn stdout_is_tty() -> bool { | ||
| 7 | std::io::stdout().is_terminal() | ||
| 8 | } | ||
| 9 | |||
| 10 | /// Streams to stdout. Colour is used only when stdout is a terminal, so piping | ||
| 11 | /// the output somewhere gives clean text. | ||
| 12 | pub struct Renderer { | ||
| 13 | color: bool, | ||
| 14 | dimmed: bool, | ||
| 15 | wrote_text: bool, | ||
| 16 | } | ||
| 17 | |||
| 18 | impl Renderer { | ||
| 19 | pub fn new(color: bool) -> Self { | ||
| 20 | Self { | ||
| 21 | color, | ||
| 22 | dimmed: false, | ||
| 23 | wrote_text: false, | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | fn undim(&mut self) { | ||
| 28 | if self.dimmed { | ||
| 29 | print!("\x1b[0m"); | ||
| 30 | self.dimmed = false; | ||
| 31 | } | ||
| 32 | } | ||
| 33 | } | ||
| 34 | |||
| 35 | impl Sink for Renderer { | ||
| 36 | fn text(&mut self, s: &str) { | ||
| 37 | self.undim(); | ||
| 38 | print!("{s}"); | ||
| 39 | let _ = std::io::stdout().flush(); | ||
| 40 | self.wrote_text = true; | ||
| 41 | } | ||
| 42 | |||
| 43 | fn reasoning(&mut self, s: &str) { | ||
| 44 | if !self.color { | ||
| 45 | return; | ||
| 46 | } | ||
| 47 | if !self.dimmed { | ||
| 48 | print!("\x1b[2m"); | ||
| 49 | self.dimmed = true; | ||
| 50 | } | ||
| 51 | print!("{s}"); | ||
| 52 | let _ = std::io::stdout().flush(); | ||
| 53 | } | ||
| 54 | |||
| 55 | fn done(&mut self, outcome: &Outcome, elapsed: Duration) { | ||
| 56 | self.undim(); | ||
| 57 | if self.wrote_text { | ||
| 58 | println!(); | ||
| 59 | } | ||
| 60 | let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())]; | ||
| 61 | if let Some(usage) = &outcome.usage { | ||
| 62 | let input = usage.get("prompt_tokens").and_then(|v| v.as_u64()); | ||
| 63 | let output = usage.get("completion_tokens").and_then(|v| v.as_u64()); | ||
| 64 | if let (Some(i), Some(o)) = (input, output) { | ||
| 65 | parts.push(format!("{i} in · {o} out")); | ||
| 66 | } | ||
| 67 | } | ||
| 68 | let line = format!("─ {}", parts.join(" · ")); | ||
| 69 | if self.color { | ||
| 70 | println!("\x1b[2m{line}\x1b[0m"); | ||
| 71 | } else { | ||
| 72 | println!("{line}"); | ||
| 73 | } | ||
| 74 | } | ||
| 75 | } | ||
