From 226c44dc770dd0ea42e322af4d0edd6c14ce14db Mon Sep 17 00:00:00 2001 From: salmonik Date: Wed, 18 Nov 2026 12:45:05 +0100 Subject: 0.11.0: /undo via git checkpoints, /compact, provider presets, leniency, system CA - /undo resets to a git checkpoint taken before each turn - /compact summarises and rewrites the transcript (ADR 0003, the one sanctioned rewrite) - --provider presets for six OpenAI-compatible gateways, local ones lenient by default - --lenient and --system-ca - proxies already honoured via ureq; documented --- src/agent.rs | 2 +- src/config.rs | 61 ++++++++++++++++++++++++++---- src/git.rs | 57 ++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 115 ++++++++++++++++++++++++++++++++++++++++++++++++++------ src/provider.rs | 81 ++++++++++++++++++++++++++++----------- src/session.rs | 25 ++++++++++++ 7 files changed, 300 insertions(+), 42 deletions(-) create mode 100644 src/git.rs (limited to 'src') diff --git a/src/agent.rs b/src/agent.rs index afd662c..c3d77c1 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -185,7 +185,7 @@ pub fn run_turn( push(session, history, user, None); let schemas = tools::schemas(); - let client = provider::agent(); + let client = provider::agent(cfg.system_ca); let mut steps = 0usize; let mut last: Option = None; let mut aborted = false; diff --git a/src/config.rs b/src/config.rs index 77bdc52..1d259c7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,6 +3,17 @@ 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"; +/// (name, base_url, default_model, lenient). Local gateways that omit `[DONE]` +/// or `usage` are marked lenient so a truncated-looking stream is not an error. +const PRESETS: &[(&str, &str, &str, bool)] = &[ + ("opencode-go", DEFAULT_BASE_URL, DEFAULT_MODEL, false), + ("openai", "https://api.openai.com/v1", "gpt-4o-mini", false), + ("openrouter", "https://openrouter.ai/api/v1", "", false), + ("ollama", "http://localhost:11434/v1", "", true), + ("llamacpp", "http://localhost:8080/v1", "", true), + ("vllm", "http://localhost:8000/v1", "", true), +]; + #[derive(Debug, Clone, PartialEq, Eq)] pub enum KeySource { Env, @@ -19,16 +30,24 @@ pub struct Config { /// the session exists. pub session: String, pub yolo: bool, + /// Tolerate providers that omit `[DONE]`/`usage`/`finish_reason`. + pub lenient: bool, + /// Verify TLS against the system trust store instead of bundled roots. + pub system_ca: bool, } impl Config { /// CLI flags win over environment variables, which win over defaults. + #[allow(clippy::too_many_arguments)] pub fn resolve( model: Option, base_url: Option, yolo: bool, + provider: Option, + lenient: bool, + system_ca: bool, ) -> Result { - let config = Self::resolve_lenient(model, base_url, yolo); + let config = Self::resolve_lenient(model, base_url, yolo, provider, lenient, system_ca); if config.api_key.is_empty() { return Err(format!( "no API key: set OPENCODE_API_KEY or write one to {}", @@ -42,17 +61,39 @@ impl Config { /// Same as `resolve`, but tolerates a missing key so `--doctor` can report /// the missing key instead of failing to start. - pub fn resolve_lenient(model: Option, base_url: Option, yolo: bool) -> Config { + pub fn resolve_lenient( + model: Option, + base_url: Option, + yolo: bool, + provider: Option, + lenient: bool, + system_ca: bool, + ) -> Config { + // Presets fill the base URL and a default model; explicit values win. + let provider = provider.or_else(|| env_nonempty("AGENT686_PROVIDER")); + let (preset_url, preset_model, preset_lenient) = provider + .as_deref() + .and_then(|name| PRESETS.iter().find(|(n, ..)| *n == name)) + .map(|(_, url, model, lenient)| (*url, *model, *lenient)) + .unwrap_or((DEFAULT_BASE_URL, "", false)); + + let base_url = base_url + .or_else(|| env_nonempty("AGENT686_BASE_URL")) + .unwrap_or_else(|| preset_url.to_string()); + + let model = model + .or_else(|| env_nonempty("AGENT686_MODEL")) + .or_else(|| (!preset_model.is_empty()).then(|| preset_model.to_string())) + .unwrap_or_else(|| DEFAULT_MODEL.to_string()); + Config { api_key: api_key().unwrap_or_default(), - 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()), + base_url, + model, session: String::new(), yolo, + lenient: lenient || preset_lenient, + system_ca: system_ca || env_nonempty("AGENT686_SYSTEM_CA").is_some(), } } @@ -61,6 +102,10 @@ impl Config { } } +pub fn provider_names() -> Vec<&'static str> { + PRESETS.iter().map(|(name, ..)| *name).collect() +} + fn env_nonempty(key: &str) -> Option { std::env::var(key).ok().filter(|v| !v.trim().is_empty()) } diff --git a/src/git.rs b/src/git.rs new file mode 100644 index 0000000..78348af --- /dev/null +++ b/src/git.rs @@ -0,0 +1,57 @@ +//! Git helpers for the checkpoint/undo feature. In a separate module so they +//! are unit-testable without driving the whole CLI. + +use std::path::Path; +use std::process::Command; + +/// Runs `git -C `, returning trimmed stdout on success. +pub fn run(dir: &Path, args: &[&str]) -> Option { + Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .ok() + .and_then(|output| { + output + .status + .success() + .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string()) + }) +} + +/// True when `dir` is inside a work tree (a `.git` dir or file up the tree). +pub fn in_repo(dir: &Path) -> bool { + let mut current = dir.to_path_buf(); + loop { + if current.join(".git").exists() { + return true; + } + if !current.pop() { + return false; + } + } +} + +/// Snapshots the tree as a commit when it is dirty, and returns HEAD. Returns +/// `None` outside a repository. +pub fn checkpoint(dir: &Path) -> Option { + if !in_repo(dir) { + return None; + } + run(dir, &["add", "-A"]); + let dirty = run(dir, &["status", "--porcelain"]) + .map(|status| !status.is_empty()) + .unwrap_or(false); + if dirty { + run(dir, &["commit", "-m", "agent686: checkpoint"]); + } + run(dir, &["rev-parse", "HEAD"]) +} + +/// Resets to the checkpoint commit and drops untracked files, undoing a turn's +/// changes. +pub fn undo(dir: &Path, sha: &str) { + run(dir, &["reset", "--hard", sha]); + run(dir, &["clean", "-fd"]); +} diff --git a/src/lib.rs b/src/lib.rs index c5c02b1..b1e0592 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ pub mod agent; pub mod config; pub mod doctor; +pub mod git; pub mod line; pub mod provider; pub mod session; diff --git a/src/main.rs b/src/main.rs index a425d71..8f53d9e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ use std::io::{BufRead, IsTerminal, Write}; +use std::path::Path; use serde_json::json; use std::time::UNIX_EPOCH; use std::path::PathBuf; @@ -37,6 +38,10 @@ OPTIONS: --show [ID] print a transcript (most recent if no ID) and exit --doctor check key, directories, provider and model, then exit --yolo approve every tool call without asking + --provider preset: opencode-go, openai, openrouter, ollama, + llamacpp, vllm + --lenient tolerate providers that omit [DONE]/usage + --system-ca verify TLS with the system trust store -V, --version print the version and exit -h, --help this text @@ -63,6 +68,9 @@ struct Args { doctor: bool, yolo: bool, json: bool, + provider: Option, + lenient: bool, + system_ca: bool, } fn main() { @@ -88,6 +96,9 @@ fn parse_args() -> Result { doctor: false, yolo: false, json: false, + provider: None, + lenient: false, + system_ca: false, }; let mut words: Vec = Vec::new(); let mut iter = std::env::args().skip(1).peekable(); @@ -118,6 +129,10 @@ fn parse_args() -> Result { args.show = Some(Some(value.to_string())); continue; } + "--provider" => { + args.provider = Some(value.to_string()); + continue; + } _ => return Err(format!("unknown flag {flag}\n\n{HELP}")), } } @@ -142,6 +157,9 @@ fn parse_args() -> Result { "--doctor" => args.doctor = true, "--yolo" => args.yolo = true, "--json" => args.json = true, + "--provider" => args.provider = Some(take_value(&mut iter, "--provider")?), + "--lenient" => args.lenient = true, + "--system-ca" => args.system_ca = true, "-V" | "--version" => { println!("agent686 {}", env!("CARGO_PKG_VERSION")); std::process::exit(0); @@ -216,13 +234,27 @@ fn run(args: Args) { } if args.doctor { - let mut config = Config::resolve_lenient(args.model, args.base_url, args.yolo); + let mut config = Config::resolve_lenient( + args.model, + args.base_url, + args.yolo, + args.provider, + args.lenient, + args.system_ca, + ); // `/models` needs the session header too, even though this is not a turn. config.session = session::new_id(); std::process::exit(doctor::run(&config, args.json)); } - let mut cfg = match Config::resolve(args.model, args.base_url, args.yolo) { + let mut cfg = match Config::resolve( + args.model, + args.base_url, + args.yolo, + args.provider, + args.lenient, + args.system_ca, + ) { Ok(cfg) => cfg, Err(message) => { eprintln!("agent686: {message}"); @@ -287,6 +319,7 @@ fn run(args: Args) { let mut editor = Editor::new(); let interactive = editor.is_interactive(); + let mut checkpoint: Option = None; if !interactive && !cfg.yolo { eprintln!( "agent686: stdin is not a terminal, so write/edit/bash will be denied; \ @@ -330,6 +363,14 @@ fn run(args: Args) { forget_sessions(&text, &session); continue; } + if text == "/undo" { + undo(checkpoint.as_deref()); + continue; + } + if text == "/compact" { + compact(&cfg, &mut session, &mut history); + continue; + } match text.as_str() { "/exit" | "/quit" => break, @@ -364,6 +405,7 @@ fn run(args: Args) { } warn_if_changed(&watched, &mut warned); + checkpoint = git_checkpoint(); if let Err(error) = agent::run_turn( &cfg, &mut session, @@ -439,6 +481,63 @@ fn open_session( /// The system prompt is frozen with the directory the session started in. If the /// user resumes from somewhere else, tools and prompt disagree. +/// Git is the documented undo, so before a turn we snapshot the tree with a +/// commit when it is dirty. `/undo` resets back to this. +fn git_checkpoint() -> Option { + let Ok(cwd) = std::env::current_dir() else { + return None; + }; + agent686::git::checkpoint(&cwd) +} + +fn undo(checkpoint: Option<&str>) { + let Some(sha) = checkpoint else { + eprintln!("agent686: /undo needs a git repository"); + return; + }; + let Ok(cwd) = std::env::current_dir() else { + return; + }; + agent686::git::undo(&cwd, sha); + eprintln!("agent686: restored to {sha}"); +} + +/// `/compact`: summarise the conversation and start again from the summary, in +/// the same session id. The only sanctioned rewrite of the transcript (ADR 0003). +fn compact(cfg: &Config, session: &mut Session, history: &mut Vec) { + let system = history.first().cloned().unwrap_or_else(|| agent::system_prompt()); + let mut messages = history.clone(); + messages.push(json!({ + "role": "user", + "content": "Summarize the conversation so far into one concise paragraph that \ + preserves the goal, decisions made, files changed, and the current \ + state. Omit pleasantries." + })); + let summary = match agent686::provider::summarize(cfg, &messages) { + Ok(summary) if !summary.trim().is_empty() => summary, + Ok(_) => { + eprintln!("agent686: /compact produced an empty summary; aborting"); + return; + } + Err(error) => { + eprintln!("agent686: /compact failed: {error}"); + return; + } + }; + + let user = json!({ + "role": "user", + "content": format!("[earlier conversation, summarized]\n{summary}"), + }); + let new_history = vec![system.clone(), user]; + if let Err(error) = session.rewrite(&system, &new_history[1..]) { + eprintln!("agent686: /compact could not rewrite the session: {error}"); + return; + } + *history = new_history; + eprintln!("agent686: compacted into a {}-character summary", summary.len()); +} + fn list_models(cfg: &Config) { match agent686::provider::models(cfg) { Ok(models) => { @@ -640,16 +739,8 @@ fn refuse_yolo(cfg: &Config) { } } -fn in_git_repo(dir: &std::path::Path) -> bool { - let mut current = dir.to_path_buf(); - loop { - if current.join(".git").exists() { - return true; - } - if !current.pop() { - return false; - } - } +fn in_git_repo(dir: &Path) -> bool { + agent686::git::in_repo(dir) } fn style(code: &str, text: &str, color: bool) -> String { diff --git a/src/provider.rs b/src/provider.rs index b08d1f2..c03dea2 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -197,15 +197,22 @@ fn explain(status: u16, message: &str) -> String { } /// One client per turn: rebuilding it per step pays a TLS handshake on every -/// request, which is noticeable on an i686 core. -pub fn agent() -> ureq::Agent { - ureq::Agent::config_builder() +/// request, which is noticeable on an i686 core. `system_ca` verifies against +/// the OS trust store instead of bundled roots. +pub fn agent(system_ca: bool) -> ureq::Agent { + let mut builder = 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() + .timeout_per_read(Some(Duration::from_secs(180))); + if system_ca { + builder = builder.tls_config( + ureq::tls::TlsConfig::builder() + .root_certs(ureq::tls::RootCerts::PlatformVerifier) + .build(), + ); + } + builder.build().into() } pub fn chat( @@ -215,7 +222,7 @@ pub fn chat( cancel: &AtomicBool, sink: &mut dyn Sink, ) -> Result { - chat_with(&agent(), cfg, messages, tools, cancel, sink) + chat_with(&agent(cfg.system_ca), cfg, messages, tools, cancel, sink) } pub fn chat_with( @@ -378,14 +385,18 @@ pub fn chat_with( } // A connection that closes early, or a 200 that is not SSE at all, must not - // be recorded as a complete answer. + // be recorded as a complete answer. Lenient mode tolerates local servers + // that finish with text but no [DONE]/finish_reason. if !completed { - return Err(Error::Transport(format!( - "stream ended before completion ({} bytes of text, {} tool call(s)); \ - the turn was not recorded as answered", - outcome.content.len(), - outcome.tool_calls.len() - ))); + let lenient_ok = cfg.lenient && outcome.tool_calls.is_empty() && !outcome.content.is_empty(); + if !lenient_ok { + return Err(Error::Transport(format!( + "stream ended before completion ({} bytes of text, {} tool call(s)); \ + the turn was not recorded as answered", + outcome.content.len(), + outcome.tool_calls.len() + ))); + } } sink.done(&outcome, started.elapsed()); @@ -555,15 +566,43 @@ struct FunctionDelta { arguments: Option, } +/// A single non-streaming completion, used by `/compact` to summarise history. +pub fn summarize(cfg: &Config, messages: &[Value]) -> Result { + let body = serde_json::json!({ "model": cfg.model, "messages": messages, "stream": false }); + let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; + let mut response = agent(cfg.system_ca) + .post(&cfg.endpoint()) + .header("Content-Type", "application/json") + .header("Authorization", format!("Bearer {}", cfg.api_key)) + .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) + .header("x-opencode-session", &cfg.session) + .send(bytes) + .map_err(|e| Error::Transport(e.to_string()))?; + + let status = response.status().as_u16(); + let text = response + .body_mut() + .with_config() + .limit(2 * 1024 * 1024) + .read_to_string() + .unwrap_or_default(); + if !(200..300).contains(&status) { + return Err(Error::Status { + code: status, + message: error_message(&text), + }); + } + let value: Value = serde_json::from_str(&text) + .map_err(|e| Error::Transport(format!("could not parse the completion: {e}")))?; + Ok(value["choices"][0]["message"]["content"] + .as_str() + .unwrap_or("") + .to_string()) +} + /// Lists the models the provider offers for this key, for `--doctor`. pub fn models(cfg: &Config) -> Result, Error> { - let agent: ureq::Agent = ureq::Agent::config_builder() - .http_status_as_error(false) - .timeout_connect(Some(Duration::from_secs(10))) - .timeout_recv_response(Some(Duration::from_secs(20))) - .timeout_per_read(Some(Duration::from_secs(20))) - .build() - .into(); + let agent = agent(cfg.system_ca); let url = format!("{}/models", cfg.base_url.trim_end_matches('/')); let mut response = agent diff --git a/src/session.rs b/src/session.rs index 881b1ed..8fc6d29 100644 --- a/src/session.rs +++ b/src/session.rs @@ -252,6 +252,31 @@ impl Session { &self.path } + /// Rewrites the transcript from scratch: a fresh header plus the given + /// messages. This is the one sanctioned rewrite, called only by `/compact` + /// (see ADR 0003); everything else appends. + pub fn rewrite(&mut self, system: &Value, messages: &[Value]) -> Result<(), String> { + use std::io::{Seek, SeekFrom, Write}; + self.file.set_len(0).map_err(|e| e.to_string())?; + self.file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; + let header = json!({ + "t": "header", + "session": self.id, + "model": self.model, + "cwd": self.cwd, + "version": self.version, + "created": now_ms(), + "system": system, + }); + writeln!(self.file, "{header}").map_err(|e| e.to_string())?; + for message in messages { + let mut line = message.as_object().cloned().unwrap_or_default(); + line.insert("t".into(), json!("msg")); + writeln!(self.file, "{}", Value::Object(line)).map_err(|e| e.to_string())?; + } + self.file.flush().map_err(|e| e.to_string()) + } + /// Records a model switch so `--list` shows what the last turn used. Appending /// is legal; the header itself is never rewritten. pub fn record_model(&mut self, model: &str) -> Result<(), String> { -- cgit v1.2.3