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 --- CHANGELOG.md | 20 ++ Cargo.lock | 228 ++++++++++++++++++++++- Cargo.toml | 4 +- README.md | 10 +- docs/adr/0003-compact-is-a-sanctioned-rewrite.md | 37 ++++ 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 +++ tests/config.rs | 28 +++ tests/git.rs | 50 +++++ tests/loop.rs | 14 ++ tests/mock.rs | 2 + tests/sessions.rs | 23 +++ 17 files changed, 710 insertions(+), 48 deletions(-) create mode 100644 docs/adr/0003-compact-is-a-sanctioned-rewrite.md create mode 100644 src/git.rs create mode 100644 tests/config.rs create mode 100644 tests/git.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index dc0cc9e..6d1a673 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,26 @@ break the interface, **PATCH** for bug fixes. file, and the tool schemas the model sees. Anything a script or a resumed session could depend on counts as API. +## 0.11.0 + +### Added +- `/undo` restores the working tree to the state before the last turn, via a git + checkpoint commit taken at each turn start (dirty trees only). +- `/compact` summarises the conversation and rewrites the session to + `header + system + summary`, in the same session id. This is the single + sanctioned transcript rewrite, documented in ADR 0003; it breaks the prompt + cache and has no rollback. +- Provider presets: `--provider opencode-go|openai|openrouter|ollama|llamacpp|vllm` + (or `AGENT686_PROVIDER`). Local gateways default to lenient streaming. +- `--lenient` tolerates providers that end a stream with text but no + `[DONE]`/`finish_reason`. +- `--system-ca` verifies TLS against the OS trust store (via + `rustls-platform-verifier`) instead of bundled roots. + +### Changed +- HTTP proxies (`HTTPS_PROXY`/`HTTP_PROXY`/`ALL_PROXY`/`NO_PROXY`) are honoured — + documented, not implemented: ureq already read them. + ## 0.10.0 ### Added diff --git a/Cargo.lock b/Cargo.lock index ecfdfd2..eae9425 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "agent686" -version = "0.9.2" +version = "0.10.0" dependencies = [ "crossterm", "libc", @@ -64,6 +64,16 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "convert_case" version = "0.10.0" @@ -73,6 +83,22 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "crc32fast" version = "1.5.5" @@ -200,6 +226,55 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "libc" version = "0.2.191" @@ -267,6 +342,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "parking_lot" version = "0.12.5" @@ -403,6 +484,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" version = "1.16.0" @@ -412,6 +505,33 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + [[package]] name = "rustls-webpki" version = "0.103.17" @@ -423,12 +543,53 @@ dependencies = [ "untrusted", ] +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "semver" version = "1.0.28" @@ -521,6 +682,22 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "smallvec" version = "1.16.5" @@ -555,6 +732,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "unicode-ident" version = "1.0.27" @@ -591,6 +788,7 @@ dependencies = [ "percent-encoding", "rustls", "rustls-pki-types", + "rustls-platform-verifier", "ureq-proto", "utf8-zero", "webpki-roots", @@ -614,12 +812,31 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webpki-roots" version = "1.0.12" @@ -645,6 +862,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.52.0", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index e4a6ecb..44d2fee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.10.0" +version = "0.11.0" edition = "2021" description = "A small coding agent for Debian-class Linux" publish = false @@ -8,7 +8,7 @@ publish = false [dependencies] serde = { version = "1", features = ["derive"] } serde_json = "1" -ureq = { version = "3", features = ["rustls"] } +ureq = { version = "3", features = ["rustls", "platform-verifier"] } libc = "0.2" crossterm = "0.29.0" regex = "1.13.1" diff --git a/README.md b/README.md index 6f5260a..6990701 100644 --- a/README.md +++ b/README.md @@ -56,11 +56,15 @@ export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key ``` Provider is OpenCode Go, `chat/completions`, model `deepseek-v4.1-flash` by -default. Every request carries a stable `x-opencode-session` header, which the -service uses for routing and prompt caching. +default; `--provider ollama|openai|openrouter|vllm|llamacpp` switches to another +OpenAI-compatible endpoint, with `--lenient` for servers that omit `[DONE]`. +`HTTPS_PROXY`/`NO_PROXY` are honoured. Every request carries a stable +`x-opencode-session` header, which the service uses for routing and prompt caching. In a terminal: up/down walks history, bracketed paste arrives as one block -(multi-line is fine), ctrl-c abandons the line, ctrl-d exits. +(multi-line is fine), ctrl-c abandons the line, ctrl-d exits. `/undo` reverts the +working tree to before the last turn, `/compact` summarises a long conversation, +`/models` and `/model ` manage the model, `/forget ` prunes sessions. Rate limits and transient failures retry with backoff (four attempts, `Retry-After` honoured); a 429 that survives them explains itself instead of dumping JSON. diff --git a/docs/adr/0003-compact-is-a-sanctioned-rewrite.md b/docs/adr/0003-compact-is-a-sanctioned-rewrite.md new file mode 100644 index 0000000..19a42dc --- /dev/null +++ b/docs/adr/0003-compact-is-a-sanctioned-rewrite.md @@ -0,0 +1,37 @@ +# 0003 — `/compact` is the single sanctioned rewrite of a transcript + +**Status:** accepted + +## Context + +ADR 0002 made sessions append-only and forbade rewriting history, because the +provider's prompt cache depends on a byte-identical prefix and any edit to +earlier messages invalidates it. The cost of that decision was a hard context +ceiling: a long conversation could not be shortened, only abandoned. + +The default model accepts ~500k tokens, so the ceiling is rarely reached, but +when it is, "start a new session" loses everything in the conversation. + +## Decision + +`/compact` is an explicit, user-initiated command that: + +1. asks the model for a one-paragraph summary of the conversation (a single + non-streaming completion), +2. rewrites the session file to `header + system + one user message` carrying + that summary, under the same session id, +3. continues in place. + +It is the **only** code path that truncates a transcript, and it deliberately +breaks the prompt cache — an accepted cost, because the user asked for it and it +happens once, not on every step. + +## Consequences + +- A long session can now be continued instead of abandoned, at the price of the + detail the summary omits. +- The cache is cold after `/compact`; the next turn re-bills the whole prefix. +- There is no rollback: the pre-compact messages are gone. The summary is the + only record, so a bad summary loses real context. +- ADR 0002 still governs everything else: no summarisation, truncation, or + sliding window happens automatically. 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> { diff --git a/tests/config.rs b/tests/config.rs new file mode 100644 index 0000000..05361d3 --- /dev/null +++ b/tests/config.rs @@ -0,0 +1,28 @@ +use agent686::config::Config; + +#[test] +fn presets_fill_base_url_model_and_leniency() { + let ollama = Config::resolve_lenient(None, None, false, Some("ollama".into()), false, false); + assert_eq!(ollama.base_url, "http://localhost:11434/v1"); + assert!(ollama.lenient, "local gateways default to lenient"); + + let opencode = + Config::resolve_lenient(None, None, false, Some("opencode-go".into()), false, false); + assert!(!opencode.lenient); + assert!(opencode.base_url.contains("opencode.ai")); + + // An explicit --base-url beats the preset. + let explicit = Config::resolve_lenient( + None, + Some("http://127.0.0.1:9/v1".into()), + false, + Some("ollama".into()), + false, + false, + ); + assert_eq!(explicit.base_url, "http://127.0.0.1:9/v1"); + + // Unknown preset falls back to the default endpoint. + let unknown = Config::resolve_lenient(None, None, false, Some("nope".into()), false, false); + assert!(unknown.base_url.contains("opencode.ai")); +} diff --git a/tests/git.rs b/tests/git.rs new file mode 100644 index 0000000..19eced1 --- /dev/null +++ b/tests/git.rs @@ -0,0 +1,50 @@ +use std::fs; +use std::path::PathBuf; +use std::process::Command; + +use agent686::git; + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("agent686-git-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +fn repo(tag: &str) -> PathBuf { + let dir = temp_dir(tag); + for args in [ + &["init", "-q"][..], + &["config", "user.email", "agent686@test"][..], + &["config", "user.name", "agent686"][..], + ] { + assert!( + Command::new("git").arg("-C").arg(&dir).args(args).status().unwrap().success() + ); + } + dir +} + +#[test] +fn checkpoint_then_undo_restores_the_tree() { + let dir = repo("roundtrip"); + fs::write(dir.join("a.txt"), "original\n").unwrap(); + + let sha = git::checkpoint(&dir).expect("in a repo"); + assert!(!sha.is_empty()); + + // The turn mutates the tree. + fs::write(dir.join("a.txt"), "changed\n").unwrap(); + fs::write(dir.join("b.txt"), "untracked\n").unwrap(); + + git::undo(&dir, &sha); + + assert_eq!(fs::read_to_string(dir.join("a.txt")).unwrap(), "original\n"); + assert!(!dir.join("b.txt").exists(), "untracked files must be removed"); +} + +#[test] +fn checkpoint_is_none_outside_a_repo() { + let dir = temp_dir("norepo"); + assert!(git::checkpoint(&dir).is_none()); +} diff --git a/tests/loop.rs b/tests/loop.rs index e913302..8c913cd 100644 --- a/tests/loop.rs +++ b/tests/loop.rs @@ -99,6 +99,8 @@ fn runs_a_tool_call_then_finishes_and_records_every_message() { model: "test-model".into(), session: session.id.clone(), yolo: true, + lenient: false, + system_ca: false, }; let mut history = agent::new_history(system); let mut approver = Approver::new(true); @@ -170,6 +172,8 @@ fn a_denied_tool_call_is_returned_as_data() { model: "test-model".into(), session: session.id.clone(), yolo: false, + lenient: false, + system_ca: false, }; let mut history = agent::new_history(system); // Not a terminal, so the approver must deny rather than block. @@ -238,6 +242,8 @@ fn aborting_between_tool_calls_answers_every_call() { model: "test-model".into(), session: session.id.clone(), yolo: true, + lenient: false, + system_ca: false, }; let mut history = agent::new_history(system); let mut approver = Approver::new(true); @@ -313,6 +319,8 @@ fn opening_a_session_with_unanswered_calls_repairs_it() { model: "test-model".into(), session: session.id.clone(), yolo: true, + lenient: false, + system_ca: false, }; let mut approver = Approver::new(true); agent::run_turn( @@ -367,6 +375,8 @@ fn an_empty_bash_call_is_never_approved() { model: "test-model".into(), session: session.id.clone(), yolo: false, + lenient: false, + system_ca: false, }; let mut history = agent::new_history(system); // Not a terminal: if this reaches the approval path it is denied, which the @@ -421,6 +431,8 @@ fn a_tool_call_with_no_arguments_is_reported_to_the_model() { model: "test-model".into(), session: session.id.clone(), yolo: false, + lenient: false, + system_ca: false, }; let mut history = agent::new_history(system); let mut approver = Approver::new(false); @@ -475,6 +487,8 @@ fn a_wrong_argument_key_names_both_keys() { model: "test-model".into(), session: session.id.clone(), yolo: false, + lenient: false, + system_ca: false, }; let mut history = agent::new_history(system); let mut approver = Approver::new(false); diff --git a/tests/mock.rs b/tests/mock.rs index 7e076e3..fdbaca4 100644 --- a/tests/mock.rs +++ b/tests/mock.rs @@ -74,6 +74,8 @@ fn config(base_url: String) -> Config { model: "test-model".into(), session: "testsession".into(), yolo: true, + lenient: false, + system_ca: false, } } diff --git a/tests/sessions.rs b/tests/sessions.rs index b381888..4f8ebd5 100644 --- a/tests/sessions.rs +++ b/tests/sessions.rs @@ -176,3 +176,26 @@ fn last_reply_prefers_content_and_falls_back_to_reasoning() { assert!(reply.content.is_empty()); assert_eq!(reply.reasoning, "thoughts"); } + +#[test] +fn rewrite_replaces_messages_but_keeps_the_header() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = temp_dir("rewrite"); + std::env::set_var("AGENT686_DATA", &dir); + + let system = json!({ "role": "system", "content": "sys" }); + let mut session = Session::create_as("rw".into(), "m", &system).unwrap(); + session + .append(&json!({ "role": "user", "content": "old turn" }), None) + .unwrap(); + + let summary = json!({ "role": "user", "content": "the summary" }); + session.rewrite(&system, &[summary]).unwrap(); + drop(session); + + let (opened, system_back, messages) = Session::open("rw").unwrap(); + assert_eq!(opened.id, "rw", "id preserved"); + assert_eq!(system_back["content"], "sys", "system preserved"); + assert_eq!(messages.len(), 1, "old messages gone: {messages:#?}"); + assert_eq!(messages[0]["content"], "the summary"); +} -- cgit v1.2.3