From 343f2a8a6148b8004d6f4d74fb779b4f30c9686a Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 03:11:22 +0100 Subject: M1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate - append-only JSONL sessions with --continue/--session; reasoning stored, stripped on replay - read/write/edit/grep/glob + bash with timeout and capped output - diff-preview approval for the first edit of a session, per-call approval for bash - system prompt frozen per session with AGENTS.md snapshot and change warning - SIGINT aborts the turn, second Ctrl-C exits - glibc gate ignores weak symbols; verified in linux/386 debian:12 - acceptance test (calculator in C) passes on both x86-64 and i386 --- src/agent.rs | 218 ++++++++++++++++++++-- src/config.rs | 10 +- src/lib.rs | 2 + src/main.rs | 217 ++++++++++++++++------ src/provider.rs | 64 ++++--- src/session.rs | 182 +++++++++++++++++- src/signal.rs | 23 +++ src/tools/fs.rs | 527 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/tools/mod.rs | 148 +++++++++++++++ src/tools/shell.rs | 129 +++++++++++++ src/ui.rs | 171 +++++++++++++++-- 11 files changed, 1567 insertions(+), 124 deletions(-) create mode 100644 src/signal.rs create mode 100644 src/tools/fs.rs create mode 100644 src/tools/mod.rs create mode 100644 src/tools/shell.rs (limited to 'src') diff --git a/src/agent.rs b/src/agent.rs index 2d84566..7e652ed 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1,34 +1,211 @@ +use std::path::PathBuf; +use std::process::Command; use std::sync::atomic::AtomicBool; +use std::time::{Instant, SystemTime}; use serde_json::{json, Value}; use crate::config::Config; -use crate::provider::{self, Error, Outcome, Sink}; +use crate::provider::{self, Error, Outcome}; +use crate::session::Session; +use crate::tools::{self, Approval}; +use crate::ui::{self, Approver, Renderer}; -/// Frozen for the life of the process. Anything session-varying added here +/// Frozen for the life of the session. 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." - }) +pub fn system_prompt() -> Value { + let mut text = String::from( + "You are agent686, a coding agent in a Unix terminal.\n\n\ + Tools: read, write, edit, bash, grep, glob. Paths are relative to the working \ + directory.\n\ + - read before you edit; files are shown with line numbers.\n\ + - edit replaces one exact occurrence of the old text and fails if it is missing \ + or ambiguous, so include enough context.\n\ + - write replaces a whole file and does not create directories.\n\ + - bash starts a fresh shell in the working directory every call; cd does not \ + persist, pass cwd instead.\n\ + - Do not explain what you are about to do. Act, then report briefly.\n\n", + ); + + let cwd = std::env::current_dir() + .map(|p| p.display().to_string()) + .unwrap_or_default(); + text.push_str(&format!( + "Environment: cwd={cwd} · {} · {}", + std::env::consts::OS, + std::env::consts::ARCH + )); + if let Some(branch) = git_branch(&cwd) { + text.push_str(&format!(" · branch={branch}")); + } + text.push('\n'); + + if let Some((path, content)) = project_instructions() { + if !content.trim().is_empty() { + text.push_str(&format!( + "\n\n{}\n\n", + path.display(), + content.trim() + )); + } + } + + json!({ "role": "system", "content": text }) +} + +pub fn agents_md() -> Option<(PathBuf, SystemTime)> { + let path = project_instructions().map(|(path, _)| path)?; + let modified = std::fs::metadata(&path).ok()?.modified().ok()?; + Some((path, modified)) +} + +fn project_instructions() -> Option<(PathBuf, String)> { + let mut dir = std::env::current_dir().ok()?; + loop { + let candidate = dir.join("AGENTS.md"); + if candidate.is_file() { + let content = std::fs::read_to_string(&candidate).ok()?; + return Some((candidate, content)); + } + if !dir.pop() { + return None; + } + } } -/// Appends the user message, runs one provider round trip, and appends the -/// assistant message to the history whether or not it asked for tools. +fn git_branch(cwd: &str) -> Option { + let output = Command::new("git") + .arg("-C") + .arg(cwd) + .args(["rev-parse", "--abbrev-ref", "HEAD"]) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let branch = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if branch.is_empty() { + None + } else { + Some(branch) + } +} + +pub fn new_history(system: Value) -> Vec { + vec![system] +} + +/// Runs one turn to completion: model, tools, model, ... until the model answers +/// without asking for a tool. Every message that is sent is also appended to the +/// session file, in order, before the next request. pub fn run_turn( cfg: &Config, + session: &mut Session, history: &mut Vec, prompt: &str, cancel: &AtomicBool, - sink: &mut dyn Sink, -) -> Result { - history.push(json!({ "role": "user", "content": prompt })); + approver: &mut Approver, +) -> Result<(), Error> { + let started = Instant::now(); + + let user = json!({ "role": "user", "content": prompt }); + push(session, history, user, None); - let outcome = provider::chat(cfg, history, cancel, sink)?; + let schemas = tools::schemas(); + let mut steps = 0usize; + let mut last: Option = None; + loop { + if cancel.load(std::sync::atomic::Ordering::Relaxed) { + crate::signal::reset(); + eprintln!("aborted"); + break; + } + + steps += 1; + let mut renderer = Renderer::new(); + let mut outcome = match provider::chat(cfg, history, &schemas, cancel, &mut renderer) { + Ok(outcome) => outcome, + Err(Error::Aborted) => { + crate::signal::reset(); + eprintln!("aborted"); + break; + } + Err(error) => return Err(error), + }; + + // A missing id would make the tool result unattachable. + for (index, call) in outcome.tool_calls.iter_mut().enumerate() { + if call.id.is_empty() { + call.id = format!("call_{steps}_{index}"); + } + } + + let assistant = assistant_message(&outcome); + push(session, history, assistant, Some(outcome.reasoning.as_str())); + + if outcome.tool_calls.is_empty() { + last = Some(outcome); + break; + } + let calls = outcome.tool_calls.clone(); + last = Some(outcome); + + for call in calls { + if cancel.load(std::sync::atomic::Ordering::Relaxed) { + crate::signal::reset(); + eprintln!("aborted"); + break; + } + let result = execute(&call, approver); + ui::tool_result(&result); + let content = match result { + Ok(output) => output, + Err(error) => format!("error: {error}"), + }; + let message = json!({ + "role": "tool", + "tool_call_id": call.id, + "content": content, + }); + push(session, history, message, None); + } + } + + if let Some(outcome) = last { + ui::status(steps, started.elapsed(), &outcome); + } + Ok(()) +} + +fn execute(call: &provider::ToolCall, approver: &mut Approver) -> Result { + let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); + ui::tool_line(&call.name, &args); + + match tools::approval(&call.name) { + Approval::Never => tools::run(&call.name, &args), + Approval::Once => match tools::plan(&call.name, &args) { + Ok(change) => { + if approver.allow_edit(change.path(), &change.preview()) { + change.apply() + } else { + Err("denied by the user".into()) + } + } + Err(error) => Err(error), + }, + Approval::EveryCall => { + let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""); + if approver.allow_bash(cmd) { + tools::run(&call.name, &args) + } else { + Err("denied by the user".into()) + } + } + } +} + +fn assistant_message(outcome: &Outcome) -> Value { let mut message = serde_json::Map::new(); message.insert("role".into(), json!("assistant")); message.insert( @@ -57,11 +234,12 @@ pub fn run_turn( .collect(); message.insert("tool_calls".into(), Value::Array(calls)); } - history.push(Value::Object(message)); - - Ok(outcome) + Value::Object(message) } -pub fn new_history() -> Vec { - vec![system_message()] +fn push(session: &mut Session, history: &mut Vec, message: Value, reasoning: Option<&str>) { + if let Err(error) = session.append(&message, reasoning) { + eprintln!("agent686: could not write session: {error}"); + } + history.push(message); } diff --git a/src/config.rs b/src/config.rs index b781637..a1d7c42 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,7 +8,10 @@ pub struct Config { pub base_url: String, pub api_key: String, pub model: String, + /// Session id, sent to the provider as `x-opencode-session`. Filled in once + /// the session exists. pub session: String, + pub yolo: bool, } impl Config { @@ -16,7 +19,7 @@ impl Config { pub fn resolve( model: Option, base_url: Option, - session: Option, + yolo: bool, ) -> Result { Ok(Config { api_key: api_key()?, @@ -26,7 +29,8 @@ impl Config { model: model .or_else(|| env_nonempty("AGENT686_MODEL")) .unwrap_or_else(|| DEFAULT_MODEL.to_string()), - session: session.unwrap_or_else(crate::session::new_id), + session: String::new(), + yolo, }) } @@ -40,7 +44,7 @@ fn env_nonempty(key: &str) -> Option { } /// 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. +/// has to live in shell history. fn api_key() -> Result { if let Some(k) = env_nonempty("OPENCODE_API_KEY") { return Ok(k.trim().to_string()); diff --git a/src/lib.rs b/src/lib.rs index 20913b2..18fe336 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,4 +2,6 @@ pub mod agent; pub mod config; pub mod provider; pub mod session; +pub mod signal; +pub mod tools; pub mod ui; diff --git a/src/main.rs b/src/main.rs index 8c9a58c..c53ebb6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,13 @@ use std::io::{BufRead, IsTerminal, Write}; -use std::sync::atomic::AtomicBool; +use std::path::PathBuf; +use std::time::SystemTime; -use agent686::{agent, config::Config, ui}; +use serde_json::Value; + +use agent686::config::Config; +use agent686::session::{self, Session}; +use agent686::ui::Approver; +use agent686::{agent, signal}; const HELP: &str = "\ agent686 — a small coding agent @@ -9,33 +15,40 @@ 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. +With a prompt it runs one turn and exits. Without one it reads prompts from +stdin, one per line. Commands: /paste, /exit, /help. 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 + --base-url provider base URL + --session resume a specific session + -c, --continue resume the most recent session + --yolo approve every tool call without asking -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 + OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) + AGENT686_MODEL default model id + AGENT686_BASE_URL default provider base URL + AGENT686_DATA where sessions live (default ~/.local/share/agent686) "; fn main() { - let mut prompt: Option = None; + let mut prompt_words: Vec = Vec::new(); let mut model = None; let mut base_url = None; - let mut session = None; + let mut resume = None; + let mut continue_last = false; + let mut yolo = false; 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(), + "--session" | "--resume" => resume = args.next(), + "-c" | "--continue" => continue_last = true, + "--yolo" => yolo = true, "-h" | "--help" => { print!("{HELP}"); return; @@ -45,16 +58,13 @@ fn main() { print!("{HELP}"); std::process::exit(2); } - word => { - prompt = Some(match prompt.take() { - Some(existing) => format!("{existing} {word}"), - None => word.to_string(), - }) - } + word => prompt_words.push(word.to_string()), } } - let cfg = match Config::resolve(model, base_url, session) { + signal::install(); + + let mut cfg = match Config::resolve(model, base_url, yolo) { Ok(cfg) => cfg, Err(message) => { eprintln!("agent686: {message}"); @@ -62,18 +72,31 @@ fn main() { } }; - 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); - } + let (mut session, mut history) = match open_session(&cfg, resume, continue_last) { + Ok(pair) => pair, + Err(message) => { + eprintln!("agent686: {message}"); + std::process::exit(1); + } + }; + cfg.session = session.id.clone(); + + let mut approver = Approver::new(cfg.yolo); + let watched = agent::agents_md(); + let mut warned = false; + + if !prompt_words.is_empty() { + let prompt = prompt_words.join(" "); + if let Err(error) = agent::run_turn( + &cfg, + &mut session, + &mut history, + &prompt, + &signal::CANCEL, + &mut approver, + ) { + eprintln!("agent686: {error}"); + std::process::exit(1); } return; } @@ -84,9 +107,9 @@ fn main() { "agent686 · {} · session {}{}", cfg.model, cfg.session, - if is_local(&cfg.base_url) { " · local" } else { "" } + if cfg.yolo { " · yolo" } else { "" } ); - eprintln!("one prompt per line · /exit to quit"); + eprintln!("one prompt per line · /paste · /exit"); } let stdin = std::io::stdin(); @@ -100,37 +123,121 @@ fn main() { if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { break; } - let text = line.trim_end(); + let mut text = line.trim_end().to_string(); if text.is_empty() { continue; } - if text == "/exit" || text == "/quit" { - break; + + match text.as_str() { + "/exit" | "/quit" => break, + "/help" => { + print!("{HELP}"); + continue; + } + "/paste" => { + let mut buffer = 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 piece = line.trim_end_matches(['\n', '\r']); + if piece == "." { + break; + } + buffer.push_str(piece); + buffer.push('\n'); + } + text = buffer.trim_end().to_string(); + if text.is_empty() { + continue; + } + } + _ => {} } - 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}"), + + warn_if_changed(&watched, &mut warned); + if let Err(error) = agent::run_turn( + &cfg, + &mut session, + &mut history, + &text, + &signal::CANCEL, + &mut approver, + ) { + eprintln!("agent686: {error}"); } } } -fn note_tool_calls(outcome: &agent686::provider::Outcome) { - if outcome.tool_calls.is_empty() { - return; +fn open_session( + cfg: &Config, + resume: Option, + continue_last: bool, +) -> Result<(Session, Vec), String> { + let id = match resume { + Some(id) => Some(id), + None if continue_last => Some( + session::latest()? + .ok_or_else(|| "no sessions to continue; run without --continue".to_string())?, + ), + None => None, + }; + + match id { + Some(id) => { + let (session, system, messages) = Session::open(&id)?; + if !session.model.is_empty() && session.model != cfg.model { + eprintln!( + "agent686: session used {}; continuing with {}", + session.model, cfg.model + ); + } + // The system message frozen at session start is reused verbatim, so + // the request prefix stays byte-identical across restarts. + let system = if system.is_null() { + agent::system_prompt() + } else { + system + }; + let mut history = agent::new_history(system); + let count = messages.len(); + history.extend(messages); + eprintln!("agent686: resumed {} ({count} messages)", session.id); + Ok((session, history)) + } + None => { + let system = agent::system_prompt(); + let session = Session::create(&cfg.model, &system)?; + eprintln!( + "agent686: new session {} ({})", + session.id, + session.path().display() + ); + Ok((session, agent::new_history(system))) + } } - 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") +fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) { + let (path, seen) = match watched { + Some(watched) => watched, + None => return, + }; + if *warned { + return; + } + if let Ok(modified) = std::fs::metadata(path).and_then(|m| m.modified()) { + if modified != *seen { + eprintln!( + "agent686: {} changed; start a new session to pick it up", + path.display() + ); + *warned = true; + } + } } diff --git a/src/provider.rs b/src/provider.rs index a2aed64..bc1bd99 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -44,7 +44,35 @@ pub struct Outcome { pub tool_calls: Vec, pub finish: Option, pub usage: Option, - pub opencode: 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 { @@ -92,19 +120,22 @@ impl SseDecoder { pub fn chat( cfg: &Config, messages: &[Value], + tools: &[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!({ + // 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 agent: ureq::Agent = ureq::Agent::config_builder() @@ -169,23 +200,15 @@ pub fn chat( } 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. + // A malformed frame is dropped rather than killing the turn. 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; - } + if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { + outcome.usage = None; } sink.done(&outcome, started.elapsed()); @@ -196,9 +219,6 @@ 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() { @@ -266,7 +286,7 @@ fn error_message(body: &str) -> String { truncate(body.trim(), 500) } -fn truncate(s: &str, max: usize) -> String { +pub fn truncate(s: &str, max: usize) -> String { match s.char_indices().nth(max) { Some((i, _)) => format!("{}…", &s[..i]), None => s.to_string(), @@ -279,8 +299,6 @@ struct Chunk { choices: Vec, #[serde(default)] usage: Option, - #[serde(default)] - opencode: Option, } #[derive(Debug, Deserialize)] diff --git a/src/session.rs b/src/session.rs index aef4835..7090dcf 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1,17 +1,18 @@ +use std::fs::{File, OpenOptions}; use std::hash::{Hash, Hasher}; -use std::io::Read; +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; +use serde_json::{json, Map, Value}; + /// 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); + // Creation time first, so ids sort roughly by age. + let ms = now_ms(); bytes[..8].copy_from_slice(&ms.to_be_bytes()); let mut out = String::with_capacity(32); @@ -21,9 +22,176 @@ pub fn new_id() -> String { out } +pub fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +pub fn data_root() -> PathBuf { + if let Some(dir) = std::env::var_os("AGENT686_DATA") { + return PathBuf::from(dir); + } + let home = std::env::var_os("HOME").unwrap_or_default(); + PathBuf::from(home).join(".local/share/agent686") +} + +pub fn sessions_dir() -> PathBuf { + data_root().join("sessions") +} + +pub struct Session { + pub id: String, + pub model: String, + path: PathBuf, + file: File, +} + +impl Session { + pub fn create(model: &str, system: &Value) -> Result { + let id = new_id(); + let dir = sessions_dir(); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let path = dir.join(format!("{id}.jsonl")); + let mut file = OpenOptions::new() + .create_new(true) + .append(true) + .open(&path) + .map_err(|e| format!("{}: {e}", path.display()))?; + + let header = json!({ + "t": "header", + "session": id, + "model": model, + "created": now_ms(), + "system": system, + }); + writeln!(file, "{header}").map_err(|e| e.to_string())?; + file.flush().map_err(|e| e.to_string())?; + + Ok(Session { + id, + model: model.to_string(), + path, + file, + }) + } + + /// Rebuilds the wire history exactly as it was sent, plus the system message + /// that was frozen when the session started. + pub fn open(id: &str) -> Result<(Session, Value, Vec), String> { + let path = sessions_dir().join(format!("{id}.jsonl")); + let file = File::open(&path).map_err(|e| format!("{}: {e}", path.display()))?; + let reader = BufReader::new(file.try_clone().map_err(|e| e.to_string())?); + + let mut model = String::new(); + let mut system = Value::Null; + let mut session_id = id.to_string(); + let mut messages = Vec::new(); + + for line in reader.lines() { + let line = line.map_err(|e| e.to_string())?; + if line.trim().is_empty() { + continue; + } + let value: Value = match serde_json::from_str(&line) { + Ok(v) => v, + // A torn last line is expected after kill -9; ignore it. + Err(_) => continue, + }; + match value.get("t").and_then(|t| t.as_str()) { + Some("header") => { + model = value + .get("model") + .and_then(|m| m.as_str()) + .unwrap_or_default() + .to_string(); + system = value.get("system").cloned().unwrap_or(Value::Null); + if let Some(s) = value.get("session").and_then(|s| s.as_str()) { + session_id = s.to_string(); + } + } + Some("msg") => { + let mut message = value.clone(); + if let Some(object) = message.as_object_mut() { + object.remove("t"); + object.remove("_reasoning"); + } + messages.push(message); + } + _ => {} + } + } + + let file = OpenOptions::new() + .append(true) + .open(&path) + .map_err(|e| format!("{}: {e}", path.display()))?; + + Ok(( + Session { + id: session_id, + model, + path, + file, + }, + system, + messages, + )) + } + + /// Append one wire message. `reasoning` is stored beside it for humans and + /// stripped on replay: sending it back is wasted tokens at best. + pub fn append(&mut self, message: &Value, reasoning: Option<&str>) -> Result<(), String> { + let mut line = match message.as_object() { + Some(object) => object.clone(), + None => Map::new(), + }; + line.insert("t".into(), json!("msg")); + if let Some(reasoning) = reasoning { + if !reasoning.is_empty() { + line.insert("_reasoning".into(), json!(reasoning)); + } + } + writeln!(self.file, "{}", Value::Object(line)).map_err(|e| e.to_string())?; + self.file.flush().map_err(|e| e.to_string()) + } + + pub fn path(&self) -> &PathBuf { + &self.path + } +} + +/// Most recently written session, for --continue. +pub fn latest() -> Result, String> { + let dir = sessions_dir(); + let entries = match std::fs::read_dir(&dir) { + Ok(entries) => entries, + Err(_) => return Ok(None), + }; + let mut newest: Option<(SystemTime, String)> = None; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("jsonl") { + continue; + } + let modified = entry + .metadata() + .and_then(|m| m.modified()) + .unwrap_or(UNIX_EPOCH); + if newest.as_ref().is_none_or(|(t, _)| modified > *t) { + if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { + newest = Some((modified, stem.to_string())); + } + } + } + Ok(newest.map(|(_, id)| id)) +} + fn random_bytes() -> [u8; 16] { let mut bytes = [0u8; 16]; - if let Ok(mut f) = std::fs::File::open("/dev/urandom") { + if let Ok(mut f) = File::open("/dev/urandom") { if f.read_exact(&mut bytes).is_ok() { return bytes; } diff --git a/src/signal.rs b/src/signal.rs new file mode 100644 index 0000000..8705660 --- /dev/null +++ b/src/signal.rs @@ -0,0 +1,23 @@ +use std::sync::atomic::{AtomicBool, Ordering}; + +/// Set by the first Ctrl-C. Cleared between turns. +pub static CANCEL: AtomicBool = AtomicBool::new(false); + +extern "C" fn handler(_: libc::c_int) { + // First Ctrl-C aborts the turn. A second one is taken to mean "I really mean + // it" and leaves immediately; `_exit` is async-signal-safe, `exit` is not. + if CANCEL.swap(true, Ordering::SeqCst) { + unsafe { libc::_exit(130) } + } +} + +pub fn install() { + let handler: extern "C" fn(libc::c_int) = handler; + unsafe { + libc::signal(libc::SIGINT, handler as libc::sighandler_t); + } +} + +pub fn reset() { + CANCEL.store(false, Ordering::SeqCst); +} diff --git a/src/tools/fs.rs b/src/tools/fs.rs new file mode 100644 index 0000000..6addf8d --- /dev/null +++ b/src/tools/fs.rs @@ -0,0 +1,527 @@ +use std::fs; +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +const MAX_LINE_CHARS: usize = 400; +const MAX_READ_LINES: usize = 2000; +const MAX_MATCHES: usize = 200; +const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; +const PREVIEW_BUDGET: usize = 60; + +const SKIP_DIRS: &[&str] = &[ + ".git", + "target", + "node_modules", + "dist", + "build", + ".venv", + "vendor", + ".cache", +]; + +/// A pending file change. Built and previewed first, applied only after the +/// human agrees. +pub enum Change { + Write { path: String, content: String }, + Edit { path: String, old: String, new: String, text: String }, +} + +impl Change { + pub fn path(&self) -> &str { + match self { + Change::Write { path, .. } | Change::Edit { path, .. } => path, + } + } + + pub fn preview(&self) -> String { + match self { + Change::Write { path, content } => match fs::read_to_string(path) { + Ok(old) if old == *content => format!("{path}: unchanged"), + Ok(old) => diff_preview(&old, content), + Err(_) => new_file_preview(path, content), + }, + Change::Edit { + path, + old, + new, + text, + } => { + let at = text.find(old.as_str()).unwrap_or(0); + edit_preview(path, text, old, new, at) + } + } + } + + pub fn apply(self) -> Result { + match self { + Change::Write { path, content } => { + let parent = Path::new(&path).parent(); + if let Some(parent) = parent { + if !parent.as_os_str().is_empty() && !parent.is_dir() { + return Err(format!( + "parent directory does not exist: {} (create it with bash first)", + parent.display() + )); + } + } + fs::write(&path, &content).map_err(|e| format!("{path}: {e}"))?; + Ok(format!( + "wrote {} bytes ({} lines) to {path}", + content.len(), + content.lines().count() + )) + } + Change::Edit { + path, + old, + new, + mut text, + } => { + let at = text + .find(old.as_str()) + .ok_or_else(|| format!("{path}: text to replace disappeared"))?; + let line = text[..at].matches('\n').count() + 1; + text.replace_range(at..at + old.len(), &new); + fs::write(&path, &text).map_err(|e| format!("{path}: {e}"))?; + Ok(format!("edited {path}: 1 replacement at line {line}")) + } + } + } +} + +pub fn plan_write(args: &Value) -> Result { + Ok(Change::Write { + path: req(args, "path")?, + content: req(args, "content")?, + }) +} + +pub fn plan_edit(args: &Value) -> Result { + let path = req(args, "path")?; + let old = req(args, "old")?; + let new = req(args, "new")?; + if old.is_empty() { + return Err("`old` must not be empty; use write to create a file".into()); + } + let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; + let hits: Vec = text.match_indices(&old).map(|(i, _)| i).collect(); + match hits.len() { + 0 => Err(format!( + "text to replace was not found in {path}. Read the file and copy the exact \ + text, including indentation." + )), + 1 => Ok(Change::Edit { + path, + old, + new, + text, + }), + n => Err(format!( + "text to replace appears {n} times in {path} (lines {}); include more \ + surrounding context so it is unique.", + line_list(&text, &hits) + )), + } +} + +pub fn read(args: &Value) -> Result { + let path = req(args, "path")?; + let offset = args + .get("offset") + .and_then(|v| v.as_u64()) + .unwrap_or(1) + .max(1) as usize; + let limit = args + .get("limit") + .and_then(|v| v.as_u64()) + .unwrap_or(MAX_READ_LINES as u64) + .clamp(1, MAX_READ_LINES as u64) as usize; + + let bytes = fs::read(&path).map_err(|e| format!("{path}: {e}"))?; + if bytes.iter().take(8192).any(|&b| b == 0) { + return Err(format!( + "{path}: looks like a binary file and will not be shown" + )); + } + let text = String::from_utf8_lossy(&bytes); + let lines: Vec<&str> = text.lines().collect(); + if lines.is_empty() { + return Ok(format!("{path}: empty file")); + } + if offset > lines.len() { + return Ok(format!( + "{path} has {} lines; offset {offset} is past the end", + lines.len() + )); + } + + let end = (offset + limit - 1).min(lines.len()); + let mut out = String::with_capacity((end - offset + 2) * 40); + for number in offset..=end { + out.push_str(&format!( + "{number:>6}\t{}\n", + clip(lines[number - 1], MAX_LINE_CHARS) + )); + } + if end < lines.len() { + out.push_str(&format!( + "… {} more line(s); continue with offset={}\n", + lines.len() - end, + end + 1 + )); + } + Ok(out) +} + +pub fn grep(args: &Value) -> Result { + let pattern = req(args, "pattern")?; + if pattern.is_empty() { + return Err("pattern must not be empty".into()); + } + let base = args + .get("path") + .and_then(|v| v.as_str()) + .unwrap_or(".") + .to_string(); + let ignore_case = args + .get("ignore_case") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let needle = if ignore_case { + pattern.to_lowercase() + } else { + pattern.clone() + }; + + let root = Path::new(&base); + let files = if root.is_file() { + vec![root.to_path_buf()] + } else { + let mut files = Vec::new(); + walk(root, &mut files); + files + }; + + let mut out = String::new(); + let mut matches = 0usize; + for file in files { + if matches >= MAX_MATCHES { + break; + } + grep_file(&file, &needle, ignore_case, &mut matches, &mut out); + } + + if matches == 0 { + return Ok(format!("no matches for `{pattern}` under {base}")); + } + if matches >= MAX_MATCHES { + out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n")); + } + Ok(out) +} + +pub fn glob(args: &Value) -> Result { + let pattern = req(args, "pattern")?; + let base = args + .get("path") + .and_then(|v| v.as_str()) + .unwrap_or(".") + .to_string(); + let root = Path::new(&base); + if !root.is_dir() { + return Err(format!("not a directory: {base}")); + } + + let mut files = Vec::new(); + walk(root, &mut files); + + // A pattern without a slash is matched against the file name at any depth. + let bare = !pattern.contains('/'); + let mut hits = Vec::new(); + for file in files { + let name = file.file_name().and_then(|n| n.to_str()).unwrap_or(""); + let hit = if bare { + wildcard_match(pattern.as_bytes(), name.as_bytes()) + } else { + let relative = file + .strip_prefix(root) + .unwrap_or(&file) + .to_string_lossy() + .to_string(); + glob_match(&pattern, &relative) + }; + if hit { + hits.push(file); + if hits.len() >= MAX_MATCHES { + break; + } + } + } + + if hits.is_empty() { + return Ok(format!("no files match `{pattern}` under {base}")); + } + + let mut out = String::new(); + for hit in &hits { + out.push_str(&hit.display().to_string()); + out.push('\n'); + } + if hits.len() >= MAX_MATCHES { + out.push_str(&format!("… stopped after {MAX_MATCHES} files\n")); + } + Ok(out) +} + +fn grep_file(path: &Path, needle_lower: &str, ignore_case: bool, count: &mut usize, out: &mut String) { + let meta = match fs::metadata(path) { + Ok(m) => m, + Err(_) => return, + }; + if meta.len() > MAX_SCAN_BYTES { + return; + } + let bytes = match fs::read(path) { + Ok(b) => b, + Err(_) => return, + }; + if bytes.iter().take(8192).any(|&b| b == 0) { + return; + } + let text = String::from_utf8_lossy(&bytes); + let mut needle = needle_lower.to_string(); + if !ignore_case { + needle = needle.to_string(); + } + + for (index, line) in text.lines().enumerate() { + if *count >= MAX_MATCHES { + return; + } + let hit = if ignore_case { + line.to_lowercase().contains(&needle) + } else { + line.contains(&needle) + }; + if hit { + *count += 1; + out.push_str(&format!( + "{}:{}: {}\n", + path.display(), + index + 1, + clip(line.trim_end(), 200) + )); + } + } +} + +fn walk(dir: &Path, out: &mut Vec) { + let entries = match fs::read_dir(dir) { + Ok(entries) => entries, + Err(_) => return, + }; + for entry in entries.flatten() { + let file_type = match entry.file_type() { + Ok(t) => t, + Err(_) => continue, + }; + let path = entry.path(); + if file_type.is_dir() { + let name = entry.file_name(); + if SKIP_DIRS.iter().any(|skip| name == *skip) { + continue; + } + walk(&path, out); + } else if file_type.is_file() { + out.push(path); + } + } +} + +fn glob_match(pattern: &str, path: &str) -> bool { + let p: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect(); + let s: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); + match_segments(&p, &s) +} + +fn match_segments(pattern: &[&str], path: &[&str]) -> bool { + match pattern.split_first() { + None => path.is_empty(), + Some((&"**", rest)) => { + if match_segments(rest, path) { + return true; + } + for skip in 0..path.len() { + if match_segments(rest, &path[skip + 1..]) { + return true; + } + } + false + } + Some((segment, rest)) => match path.split_first() { + None => false, + Some((name, tail)) => { + wildcard_match(segment.as_bytes(), name.as_bytes()) && match_segments(rest, tail) + } + }, + } +} + +fn wildcard_match(pattern: &[u8], text: &[u8]) -> bool { + match pattern.split_first() { + None => text.is_empty(), + Some((&b'*', rest)) => (0..=text.len()).any(|skip| wildcard_match(rest, &text[skip..])), + Some((&b'?', rest)) => !text.is_empty() && wildcard_match(rest, &text[1..]), + Some((byte, rest)) => match text.split_first() { + Some((first, tail)) => first == byte && wildcard_match(rest, tail), + None => false, + }, + } +} + +fn new_file_preview(path: &str, content: &str) -> String { + let lines: Vec<&str> = content.lines().collect(); + let mut out = format!("@@ new file {path} ({} lines) @@\n", lines.len()); + for line in lines.iter().take(PREVIEW_BUDGET) { + out.push_str(&format!("+ {}\n", clip(line, 200))); + } + if lines.len() > PREVIEW_BUDGET { + out.push_str(&format!("… {} more line(s)\n", lines.len() - PREVIEW_BUDGET)); + } + out +} + +fn diff_preview(old: &str, new: &str) -> String { + let a: Vec<&str> = old.lines().collect(); + let b: Vec<&str> = new.lines().collect(); + + let mut prefix = 0; + while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] { + prefix += 1; + } + let mut suffix = 0; + while suffix < a.len().saturating_sub(prefix) + && suffix < b.len().saturating_sub(prefix) + && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix] + { + suffix += 1; + } + + let start = prefix.saturating_sub(2); + let a_end = a.len() - suffix; + let b_end = b.len() - suffix; + + let mut out = format!( + "@@ -{},{} +{},{} @@\n", + start + 1, + a_end.saturating_sub(start), + start + 1, + b_end.saturating_sub(start) + ); + let mut budget = PREVIEW_BUDGET; + + for line in &a[start..prefix] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + for line in &a[prefix..a_end] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("- {}\n", clip(line, 200))); + } + for line in &b[prefix..b_end] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("+ {}\n", clip(line, 200))); + } + for line in a[a_end..(a_end + 2).min(a.len())].iter() { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + if budget == 0 { + out.push_str("… diff truncated\n"); + } + out +} + +fn edit_preview(path: &str, text: &str, old: &str, new: &str, at: usize) -> String { + let lines: Vec<&str> = text.lines().collect(); + let line_no = text[..at].matches('\n').count() + 1; + let old_lines = old.lines().count().max(1); + + let mut out = format!("@@ {path}:{line_no} @@\n"); + let mut budget = PREVIEW_BUDGET; + + let before_start = (line_no - 1).saturating_sub(2); + for line in &lines[before_start..line_no.saturating_sub(1)] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + for line in old.lines() { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("- {}\n", clip(line, 200))); + } + for line in new.lines() { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("+ {}\n", clip(line, 200))); + } + let after_start = (line_no - 1 + old_lines).min(lines.len()); + for line in &lines[after_start..(after_start + 2).min(lines.len())] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + if budget == 0 { + out.push_str("… diff truncated\n"); + } + out +} + +fn line_list(text: &str, offsets: &[usize]) -> String { + let mut numbers: Vec = offsets + .iter() + .take(10) + .map(|&at| (text[..at].matches('\n').count() + 1).to_string()) + .collect(); + if offsets.len() > 10 { + numbers.push("…".into()); + } + numbers.join(", ") +} + +fn req(args: &Value, key: &str) -> Result { + match args.get(key).and_then(|v| v.as_str()) { + Some(value) => Ok(value.to_string()), + None => Err(format!("missing required argument `{key}`")), + } +} + +fn clip(s: &str, max: usize) -> String { + if s.chars().count() <= max { + return s.to_string(); + } + let cut: String = s.chars().take(max).collect(); + format!("{cut}…") +} diff --git a/src/tools/mod.rs b/src/tools/mod.rs new file mode 100644 index 0000000..503de08 --- /dev/null +++ b/src/tools/mod.rs @@ -0,0 +1,148 @@ +pub mod fs; +pub mod shell; + +use serde_json::{json, Value}; + +use fs::Change; + +/// When a tool needs a human before it runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Approval { + /// Read-only or harmless. + Never, + /// Prompts on first use per session, then remembers. + Once, + /// Prompts on every call, no memory. + EveryCall, +} + +pub fn approval(name: &str) -> Approval { + match name { + "write" | "edit" => Approval::Once, + "bash" => Approval::EveryCall, + _ => Approval::Never, + } +} + +/// Tools that execute immediately. +pub fn run(name: &str, args: &Value) -> Result { + match name { + "read" => fs::read(args), + "grep" => fs::grep(args), + "glob" => fs::glob(args), + "bash" => shell::bash(args, std::time::Duration::from_secs(120)), + other => Err(unknown(other)), + } +} + +/// Tools that produce a change needing approval before it is applied. +pub fn plan(name: &str, args: &Value) -> Result { + match name { + "write" => fs::plan_write(args), + "edit" => fs::plan_edit(args), + other => Err(unknown(other)), + } +} + +fn unknown(name: &str) -> String { + format!("unknown tool `{name}`; available: read, write, edit, bash, grep, glob") +} + +/// Static and in a fixed order, so the serialised prefix never changes. +pub fn schemas() -> Vec { + vec![ + json!({ + "type": "function", + "function": { + "name": "read", + "description": "Read a text file. Returns numbered lines. Read before editing.", + "parameters": { + "type": "object", + "properties": { + "path": { "type": "string", "description": "file path" }, + "offset": { "type": "integer", "description": "first line, 1-based (default 1)" }, + "limit": { "type": "integer", "description": "maximum lines (default and cap 2000)" } + }, + "required": ["path"] + } + } + }), + json!({ + "type": "function", + "function": { + "name": "write", + "description": "Create or replace a whole file. The parent directory must already exist.", + "parameters": { + "type": "object", + "properties": { + "path": { "type": "string" }, + "content": { "type": "string" } + }, + "required": ["path", "content"] + } + } + }), + json!({ + "type": "function", + "function": { + "name": "edit", + "description": "Replace one exact occurrence of `old` with `new`. Fails if `old` is missing or appears more than once, so include enough context to be unique.", + "parameters": { + "type": "object", + "properties": { + "path": { "type": "string" }, + "old": { "type": "string", "description": "exact existing text, including indentation" }, + "new": { "type": "string", "description": "replacement text" } + }, + "required": ["path", "old", "new"] + } + } + }), + json!({ + "type": "function", + "function": { + "name": "bash", + "description": "Run a shell command. Each call is a fresh shell at the working directory, so `cd` does not persist; pass cwd instead. Times out after 120s. Returns combined output and the exit code.", + "parameters": { + "type": "object", + "properties": { + "cmd": { "type": "string" }, + "cwd": { "type": "string", "description": "working directory (default: project root)" } + }, + "required": ["cmd"] + } + } + }), + json!({ + "type": "function", + "function": { + "name": "grep", + "description": "Search file contents for a literal string, recursively. Skips .git, target, node_modules and similar.", + "parameters": { + "type": "object", + "properties": { + "pattern": { "type": "string" }, + "path": { "type": "string", "description": "file or directory (default .)" }, + "ignore_case": { "type": "boolean" } + }, + "required": ["pattern"] + } + } + }), + json!({ + "type": "function", + "function": { + "name": "glob", + "description": "List files matching a glob. Supports *, ? and ** across path segments, e.g. **/*.rs.", + "parameters": { + "type": "object", + "properties": { + "pattern": { "type": "string" }, + "path": { "type": "string", "description": "directory to search (default .)" } + }, + "required": ["pattern"] + } + } + }), + ] +} diff --git a/src/tools/shell.rs b/src/tools/shell.rs new file mode 100644 index 0000000..9c214fb --- /dev/null +++ b/src/tools/shell.rs @@ -0,0 +1,129 @@ +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +const HEAD_BYTES: usize = 64 * 1024; +const TAIL_BYTES: i64 = 16 * 1024; +static COUNTER: AtomicU64 = AtomicU64::new(0); + +pub fn bash(args: &Value, timeout: Duration) -> Result { + let cmd = match args.get("cmd").and_then(|v| v.as_str()) { + Some(cmd) => cmd.to_string(), + None => return Err("missing required argument `cmd`".into()), + }; + + let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?; + if !cwd.is_dir() { + return Err(format!("cwd is not a directory: {}", cwd.display())); + } + + let path = std::env::temp_dir().join(format!( + "agent686-{}-{}.out", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + )); + let mut file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(&path) + .map_err(|e| format!("{}: {e}", path.display()))?; + let stdout = file.try_clone().map_err(|e| e.to_string())?; + let stderr = file.try_clone().map_err(|e| e.to_string())?; + + let mut child = Command::new("sh") + .arg("-c") + .arg(&cmd) + .current_dir(&cwd) + .stdin(Stdio::null()) + .stdout(Stdio::from(stdout)) + .stderr(Stdio::from(stderr)) + .spawn() + .map_err(|e| format!("failed to start sh: {e}"))?; + + let deadline = Instant::now() + timeout; + let mut timed_out = false; + let status = loop { + match child.try_wait().map_err(|e| e.to_string())? { + Some(status) => break status, + None => { + if Instant::now() >= deadline { + let _ = child.kill(); + timed_out = true; + break child.wait().map_err(|e| e.to_string())?; + } + std::thread::sleep(Duration::from_millis(20)); + } + } + }; + + let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; + drop(file); + let _ = std::fs::remove_file(&path); + + let mut out = output; + if !out.is_empty() && !out.ends_with('\n') { + out.push('\n'); + } + if timed_out { + out.push_str(&format!( + "[timed out after {:.1}s; process killed]", + timeout.as_secs_f64() + )); + } else { + match status.code() { + Some(code) => out.push_str(&format!("[exit {code}]")), + None => { + use std::os::unix::process::ExitStatusExt; + out.push_str(&format!( + "[killed by signal {}]", + status.signal().unwrap_or_default() + )); + } + } + } + Ok(out) +} + +fn resolve_cwd(cwd: Option<&str>) -> Result { + let current = std::env::current_dir().map_err(|e| e.to_string())?; + Ok(match cwd { + Some(dir) => { + let path = PathBuf::from(dir); + if path.is_absolute() { + path + } else { + current.join(path) + } + } + None => current, + }) +} + +fn read_capped(file: &mut File) -> Result { + let len = file.metadata().map(|m| m.len()).unwrap_or(0); + file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; + + let mut out = Vec::new(); + if len <= HEAD_BYTES as u64 { + file.read_to_end(&mut out).map_err(|e| e.to_string())?; + } else { + file.take(HEAD_BYTES as u64) + .read_to_end(&mut out) + .map_err(|e| e.to_string())?; + let omitted = len.saturating_sub(HEAD_BYTES as u64 + TAIL_BYTES as u64); + out.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); + file.seek(SeekFrom::End(-TAIL_BYTES)) + .map_err(|e| e.to_string())?; + let mut tail = Vec::new(); + file.read_to_end(&mut tail).map_err(|e| e.to_string())?; + out.extend_from_slice(&tail); + } + Ok(String::from_utf8_lossy(&out).into_owned()) +} diff --git a/src/ui.rs b/src/ui.rs index 13440b2..2ec0821 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1,4 +1,5 @@ use std::io::{IsTerminal, Write}; +use std::sync::OnceLock; use std::time::Duration; use crate::provider::{Outcome, Sink}; @@ -7,18 +8,33 @@ pub fn stdout_is_tty() -> bool { std::io::stdout().is_terminal() } +pub fn stdin_is_tty() -> bool { + std::io::stdin().is_terminal() +} + +fn color() -> bool { + static COLOR: OnceLock = OnceLock::new(); + *COLOR.get_or_init(stdout_is_tty) +} + +fn paint(code: &str, text: &str) -> String { + if color() { + format!("\x1b[{code}m{text}\x1b[0m") + } else { + text.to_string() + } +} + /// 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 { + pub fn new() -> Self { Self { - color, dimmed: false, wrote_text: false, } @@ -41,7 +57,7 @@ impl Sink for Renderer { } fn reasoning(&mut self, s: &str) { - if !self.color { + if !color() { return; } if !self.dimmed { @@ -52,24 +68,147 @@ impl Sink for Renderer { let _ = std::io::stdout().flush(); } - fn done(&mut self, outcome: &Outcome, elapsed: Duration) { + fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) { self.undim(); if self.wrote_text { println!(); + self.wrote_text = false; + } + } +} + +pub fn tool_line(name: &str, args: &serde_json::Value) { + let detail = match name { + "bash" => args + .get("cmd") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(), + "grep" => format!( + "{} in {}", + args.get("pattern").and_then(|v| v.as_str()).unwrap_or(""), + args.get("path").and_then(|v| v.as_str()).unwrap_or(".") + ), + "glob" => args + .get("pattern") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(), + _ => args + .get("path") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(), + }; + println!("{} {}", paint("1;36", &format!("● {name}")), detail); + let _ = std::io::stdout().flush(); +} + +pub fn tool_result(result: &Result) { + let text = match result { + Ok(output) => output, + Err(error) => error, + }; + let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or(""); + let summary = crate::provider::truncate(first.trim(), 100); + println!(" {} {}", paint("2", "└"), paint("2", &summary)); + let _ = std::io::stdout().flush(); +} + +pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome) { + let mut parts = vec![ + if steps == 1 { + "1 step".to_string() + } else { + format!("{steps} steps") + }, + format!("{:.1}s", elapsed.as_secs_f64()), + ]; + let (input, output) = outcome.tokens(); + if let (Some(i), Some(o)) = (input, output) { + parts.push(format!("{i} in · {o} out")); + } + if let Some(allowance) = outcome.allowance() { + if allowance > 0.0 { + parts.push(format!("${allowance:.6}")); + } + } + println!("{}", paint("2", &format!("─ {}", parts.join(" · ")))); + let _ = std::io::stdout().flush(); +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum Answer { + No, + Yes, + Always, +} + +pub struct Approver { + yolo: bool, + interactive: bool, + edits_allowed: bool, +} + +impl Approver { + pub fn new(yolo: bool) -> Self { + Self { + yolo, + interactive: stdin_is_tty(), + edits_allowed: false, + } + } + + pub fn yolo(&self) -> bool { + self.yolo + } + + fn ask(&self, question: &str) -> Answer { + if self.yolo { + return Answer::Yes; + } + if !self.interactive { + println!( + "{}", + paint("33", " no terminal to ask; denied (use --yolo to allow)") + ); + return Answer::No; } - 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")); + print!("\n{} {} ", question, paint("2", "[y/N/a]")); + let _ = std::io::stdout().flush(); + + let mut line = String::new(); + if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 { + return Answer::No; + } + match line.trim().to_ascii_lowercase().as_str() { + "y" | "yes" => Answer::Yes, + "a" | "always" => Answer::Always, + _ => Answer::No, + } + } + + /// One prompt for the first edit of a session, then silent. + pub fn allow_edit(&mut self, path: &str, preview: &str) -> bool { + if self.yolo || self.edits_allowed { + return true; + } + println!("{preview}"); + match self.ask(&format!("apply this change to {path}?")) { + Answer::Yes => true, + Answer::Always => { + self.edits_allowed = true; + true } + Answer::No => false, } - let line = format!("─ {}", parts.join(" · ")); - if self.color { - println!("\x1b[2m{line}\x1b[0m"); - } else { - println!("{line}"); + } + + /// Every call, no memory: the point is seeing the command. + pub fn allow_bash(&mut self, cmd: &str) -> bool { + if self.yolo { + return true; } + self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200))) == Answer::Yes } } -- cgit v1.2.3