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 --- Cargo.lock | 1 + Cargo.toml | 1 + README.md | 71 +++++++ docs/PLAN.md | 71 ++++--- scripts/check-glibc.sh | 24 ++- scripts/mock-provider.py | 18 +- 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 +++++++++++++-- tests/loop.rs | 192 +++++++++++++++++ tests/mock.rs | 5 + tests/tools.rs | 142 +++++++++++++ 20 files changed, 2061 insertions(+), 155 deletions(-) create mode 100644 README.md 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 create mode 100644 tests/loop.rs create mode 100644 tests/tools.rs diff --git a/Cargo.lock b/Cargo.lock index 2af945a..c2f3482 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12,6 +12,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" name = "agent686" version = "0.1.0" dependencies = [ + "libc", "serde", "serde_json", "ureq", diff --git a/Cargo.toml b/Cargo.toml index 4806119..22e8cf6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ publish = false serde = { version = "1", features = ["derive"] } serde_json = "1" ureq = { version = "3", features = ["rustls"] } +libc = "0.2" [profile.release] strip = true diff --git a/README.md b/README.md new file mode 100644 index 0000000..562058a --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# agent686 + +A small coding agent for a 32-bit Debian box: one binary, six tools, line mode. + +Built because the existing harnesses are TypeScript bundles that need a modern +CPU, and the target here is a Debian 12 i386 machine with 2 cores and 4 GB. + +``` +2.0 MB ELF 32-bit LSB pie, Intel i386 +GLIBC_2.34 required (target has 2.36) +``` + +## Build + +```sh +cargo build --release --target i686-unknown-linux-gnu +./scripts/check-glibc.sh target/i686-unknown-linux-gnu/release/agent686 +``` + +The gate matters: the dev host's 32-bit glibc is newer than the target's, so a +dependency can silently raise the required symbol version. + +## Run + +```sh +export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key +./agent686 "make a calculator in C" # one turn, then exit +./agent686 # interactive, one prompt per line +./agent686 -c # continue the most recent session +./agent686 --session # resume a specific one +./agent686 --yolo "..." # approve every tool call +``` + +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. + +## Tools + +`read` (numbered lines), `write` (never creates directories), `edit` (exact +match, must be unique), `bash` (fresh shell per call, 120 s timeout, capped +output), `grep` (literal, recursive), `glob` (`*`, `?`, `**`). + +Reads never prompt. The first `write`/`edit` of a session shows a diff and asks; +answering `a` allows the rest of the session. Every `bash` call asks, because +that is where `rm -rf` lives. + +## Tests + +```sh +cargo test # 19 tests, no network +python3 scripts/mock-provider.py & # canned SSE provider +docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gate +``` + +`tests/sse.rs` feeds the stream one byte at a time, so splits inside lines and +inside UTF-8 characters are covered. `tests/loop.rs` proves a tool call is +executed, recorded, and that a denial is returned to the model as data. + +## Design notes + +- [CONTEXT.md](CONTEXT.md) — what the words mean (session, turn, step, approval). +- [docs/PLAN.md](docs/PLAN.md) — decisions, non-goals, milestones, acceptance test. +- [docs/adr/0001](docs/adr/0001-dynamic-glibc-i686.md) — why dynamic glibc, not + a static binary: static glibc plus NSS modules segfaults on DNS. +- [docs/adr/0002](docs/adr/0002-append-only-sessions.md) — why history is never + rewritten: cached prompt reads are ~50× cheaper, and they require a + byte-identical prefix. + +No async runtime, no TUI, no MCP, no subagents, no compaction. Those are +choices, not gaps: see the non-goals. diff --git a/docs/PLAN.md b/docs/PLAN.md index 2766664..b1273b1 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -73,37 +73,58 @@ Verified: `cargo test` 8/8; 2.0 MB stripped i686 binary, max symbol streams correctly; `scripts/check-glibc.sh` passes and fails as expected; `scripts/mock-provider.py` gives a no-key provider for manual work. -**M1 — Sessions, status line, abort.** JSONL append/load, session id, `--continue`, -`--resume `, status line, SIGINT handling. -*Done when:* a turn survives `kill -9` between steps, `--continue` resumes it, and -Ctrl-C returns the prompt without losing the transcript. - -**M2 — Read-side tools and edits.** `read`, `write`, `edit`, `grep`, `glob`, the -agent loop, tool-call accumulation, the approval prompt with diff. -*Done when:* a canned mock session writes a C file, greps it, edits it, and the -transcript replays byte-identically. - -**M3 — `bash`.** Command execution, timeout, output capping, per-call approval, -head/tail rendering. -*Done when:* the mock session compiles the C file and handles a non-zero exit as -data rather than an error. - -**M4 — Prompt and input.** System prompt, environment block, `AGENTS.md` -snapshot, `/paste`, TTY detection, real-API smoke test. -*Done when:* one real turn against OpenCode Go works end to end. - -**M5 — Target gate.** `scripts/check-glibc.sh` (max symbol version ≤ 2.36), -`cargo check --target i686` clean, release run inside -`docker run --platform linux/386 debian:12`, binary copied to the i386 box. -*Done when:* the acceptance test runs there. +**M1 — Sessions, status line, abort.** ✅ Done. + +JSONL append/load, session id, `--continue`, `--session `, status line, +SIGINT handling (first Ctrl-C aborts the turn, second exits). Verified: a +9-step turn writes 19 lines (header + 18 messages, reasoning stored under +`_reasoning`), `--continue` replays all 18 messages and answers from history +without reading files. + +**M2 — Read-side tools and edits.** ✅ Done. + +`read`, `write`, `edit`, `grep`, `glob`, the agent loop, tool-call accumulation, +diff preview plus approval. Verified by `tests/tools.rs` (uniqueness, ambiguity +with line numbers, no implicit `mkdir`, truncation, glob `**`, grep case) and +`tests/loop.rs` (tool call executed and recorded; a denial returned as data). +The approval prompt was also driven through a real pty. + +**M3 — `bash`.** ✅ Done. + +Fresh shell per call, 120 s timeout that kills the process, capped output +(64 KiB head, 16 KiB tail), exit code or signal reported. Verified: exit codes, +timeout, missing `cwd`, and real `gcc` invocations. + +**M4 — Prompt and input.** ✅ Done. + +System prompt with cwd/platform/arch/branch, `AGENTS.md` snapshot frozen at +session start with a change warning, `/paste`, TTY-aware colour. Verified +against the live API: streaming, tool calls, `reasoning_content`, usage and +`opencode.allowance` in the final chunk, and a 401 surfaced as +`api_key_expired`. + +**M5 — Target gate.** ✅ Done. + +`scripts/check-glibc.sh` (required symbols ≤ 2.36; weak symbols such as glibc +2.39's `pidfd_spawnp` are reported but ignored, since they resolve to NULL). +2.0 MB stripped i686 binary, `GLIBC_2.34` required. Verified by running the +whole acceptance test inside `--platform linux/386 debian:12`. ## Acceptance test (v1) > "Make a simple calculator in C" — run on the i386 box, from an empty directory. Exercises `write` (create files), `bash` (compile, run), `read` (inspect what it -wrote), and terminates on its own. Success is: it compiles, it runs, it does -addition and division, and it did not need more than a handful of files. +wrote), and terminates on its own. + +Two runs, both with `--yolo`: + +| Where | Steps | Wall | Allowance | Result | +|---|---|---|---|---| +| x86-64 dev host | 9 | 55.7 s | $0.000214 | `calc.c` (115 lines), clean `-Wall -Wextra` build, 18 cases tested | +| `linux/386 debian:12` | 8 | 32.1 s | $0.000182 | `calc.c` + `Makefile`, `3 + 4 = 7`, `7 / 2 = 3.5`, `5 / 0` → error, exit 1 | + +Independently rebuilt and re-run outside the agent both times. ## Layout diff --git a/scripts/check-glibc.sh b/scripts/check-glibc.sh index bb9052f..b02cd75 100755 --- a/scripts/check-glibc.sh +++ b/scripts/check-glibc.sh @@ -4,6 +4,10 @@ # The dev host's 32-bit glibc is newer than Debian 12's, so a dependency can # silently raise the required symbol version. Without this check the failure # only shows up as "version `GLIBC_2.38' not found" on the target machine. +# +# Weak undefined symbols are ignored: they resolve to NULL on older libc and the +# code paths using them fall back. Rust's std does this for glibc 2.39's +# pidfd_spawnp/pidfd_getpid, for example. set -euo pipefail binary=${1:?usage: check-glibc.sh [ceiling, default 2.36]} @@ -14,21 +18,31 @@ if [ ! -f "$binary" ]; then exit 2 fi -max=$(readelf -V "$binary" 2>/dev/null \ +required=$(readelf --dyn-syms --wide "$binary" 2>/dev/null \ + | awk '$5 != "WEAK" { print }' \ + | grep -oE 'GLIBC_[0-9]+\.[0-9]+' \ + | sed 's/^GLIBC_//' \ + | sort -Vu \ + | tail -1 || true) +weak=$(readelf --dyn-syms --wide "$binary" 2>/dev/null \ + | awk '$5 == "WEAK" { print }' \ | grep -oE 'GLIBC_[0-9]+\.[0-9]+' \ | sed 's/^GLIBC_//' \ | sort -Vu \ | tail -1 || true) -if [ -z "${max:-}" ]; then +if [ -z "${required:-}" ]; then echo "check-glibc: no versioned symbols (statically linked?) — nothing to check" exit 0 fi -echo "check-glibc: max symbol version GLIBC_$max, ceiling GLIBC_$ceiling" +echo "check-glibc: required GLIBC_$required, ceiling GLIBC_$ceiling" +if [ -n "${weak:-}" ] && [ "$weak" != "$required" ]; then + echo "check-glibc: weak GLIBC_$weak (optional, resolves to NULL on older libc)" +fi -if [ "$(printf '%s\n%s\n' "$ceiling" "$max" | sort -V | tail -1)" != "$ceiling" ]; then - echo "check-glibc: FAIL — binary needs GLIBC_$max, target has GLIBC_$ceiling" >&2 +if [ "$(printf '%s\n%s\n' "$ceiling" "$required" | sort -V | tail -1)" != "$ceiling" ]; then + echo "check-glibc: FAIL — binary needs GLIBC_$required, target has GLIBC_$ceiling" >&2 exit 1 fi diff --git a/scripts/mock-provider.py b/scripts/mock-provider.py index 4d11349..fb15662 100755 --- a/scripts/mock-provider.py +++ b/scripts/mock-provider.py @@ -14,6 +14,14 @@ import time from http.server import BaseHTTPRequestHandler, HTTPServer +def tool_frames(path, content): + yield {"choices": [{"delta": {"tool_calls": [{ + "index": 0, + "id": "call_mock_1", + "function": {"name": "write", "arguments": json.dumps({"path": path, "content": content})}, + }]}, "finish_reason": "tool_calls"}]} + + def frames(answer: str): yield {"choices": [{"delta": {"reasoning_content": "The user said hi. "}}]} yield {"choices": [{"delta": {"reasoning_content": "A short greeting is enough."}}]} @@ -46,12 +54,17 @@ class Handler(BaseHTTPRequestHandler): self.wfile.write(body) return + self.server.requests += 1 self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Cache-Control", "no-cache") self.end_headers() - for frame in frames(self.server.answer): + if self.server.tool_write and self.server.requests == 1: + stream = tool_frames(self.server.tool_write, "written by the mock\n") + else: + stream = frames(self.server.answer) + for frame in stream: if self.server.delay: time.sleep(self.server.delay) self.wfile.write(f"data: {json.dumps(frame)}\n\n".encode()) @@ -70,6 +83,7 @@ def main(): parser.add_argument("--delay", type=float, default=0.05, help="seconds between frames") parser.add_argument("--status", type=int, default=200, help="return this HTTP status") parser.add_argument("--answer", default="Hello from the mock provider.") + parser.add_argument("--tool-write", metavar="PATH", help="first response asks to write PATH") parser.add_argument("--quiet", action="store_true") args = parser.parse_args() @@ -78,6 +92,8 @@ def main(): server.delay = args.delay server.status = args.status server.quiet = args.quiet + server.tool_write = args.tool_write + server.requests = 0 print(f"mock provider on http://127.0.0.1:{args.port}/v1", flush=True) server.serve_forever() 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 } } diff --git a/tests/loop.rs b/tests/loop.rs new file mode 100644 index 0000000..d77d890 --- /dev/null +++ b/tests/loop.rs @@ -0,0 +1,192 @@ +use std::fs; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpListener; +use std::path::PathBuf; +use std::sync::atomic::AtomicBool; +use std::thread; + +use serde_json::json; + +use agent686::agent; +use agent686::config::Config; +use agent686::session::Session; +use agent686::ui::Approver; + +fn sse(body: &str) -> String { + format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{body}" + ) +} + +/// Serves one canned SSE response per connection, in order. +fn serve_sequence(responses: Vec) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + thread::spawn(move || { + for response in responses { + let (mut stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { + break; + } + if line == "\r\n" || line == "\n" { + break; + } + if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap_or(0); + } + } + let mut body = vec![0u8; length]; + let _ = reader.read_exact(&mut body); + let _ = stream.write_all(response.as_bytes()); + let _ = stream.flush(); + } + }); + format!("http://{addr}") +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("agent686-loop-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn runs_a_tool_call_then_finishes_and_records_every_message() { + let dir = temp_dir("write"); + let target = dir.join("hello.txt"); + let arguments = json!({ + "path": target.display().to_string(), + "content": "hello from the mock\n" + }) + .to_string(); + + let tool_round = sse(&format!( + "data: {}\n\ndata: [DONE]\n\n", + json!({ + "choices": [{ + "delta": { "tool_calls": [{ + "index": 0, + "id": "call_1", + "function": { "name": "write", "arguments": arguments } + }]}, + "finish_reason": "tool_calls" + }] + }) + )); + let final_round = sse( + "data: {\"choices\":[{\"delta\":{\"content\":\"done\"},\"finish_reason\":\"stop\"}]}\n\n\ + data: [DONE]\n\n", + ); + + let base = serve_sequence(vec![tool_round, final_round]); + + std::env::set_var("AGENT686_DATA", dir.join("data")); + + let system = agent::system_prompt(); + let mut session = Session::create("test-model", &system).unwrap(); + let cfg = Config { + base_url: base, + api_key: "test-key".into(), + model: "test-model".into(), + session: session.id.clone(), + yolo: true, + }; + let mut history = agent::new_history(system); + let mut approver = Approver::new(true); + + agent::run_turn( + &cfg, + &mut session, + &mut history, + "write a file", + &AtomicBool::new(false), + &mut approver, + ) + .expect("turn should complete"); + + assert_eq!( + fs::read_to_string(&target).unwrap(), + "hello from the mock\n" + ); + + // system, user, assistant(tool_calls), tool result, assistant(final) + assert_eq!(history.len(), 5); + assert_eq!(history[3]["role"], "tool"); + assert_eq!(history[3]["tool_call_id"], "call_1"); + + let log = fs::read_to_string(session.path()).unwrap(); + let lines: Vec<&str> = log.lines().collect(); + assert_eq!(lines.len(), 5, "header plus four messages: {log}"); + assert!(lines[0].contains("\"t\":\"header\"")); + assert_eq!(lines[3].contains("\"role\":\"tool\""), true); +} + +#[test] +fn a_denied_tool_call_is_returned_as_data() { + let dir = temp_dir("denied"); + let target = dir.join("never.txt"); + let arguments = json!({ + "path": target.display().to_string(), + "content": "should not exist" + }) + .to_string(); + + let tool_round = sse(&format!( + "data: {}\n\ndata: [DONE]\n\n", + json!({ + "choices": [{ + "delta": { "tool_calls": [{ + "index": 0, + "id": "call_1", + "function": { "name": "write", "arguments": arguments } + }]}, + "finish_reason": "tool_calls" + }] + }) + )); + let final_round = sse( + "data: {\"choices\":[{\"delta\":{\"content\":\"understood\"},\"finish_reason\":\"stop\"}]}\n\n\ + data: [DONE]\n\n", + ); + + let base = serve_sequence(vec![tool_round, final_round]); + std::env::set_var("AGENT686_DATA", dir.join("data")); + + let system = agent::system_prompt(); + let mut session = Session::create("test-model", &system).unwrap(); + let cfg = Config { + base_url: base, + api_key: "test-key".into(), + model: "test-model".into(), + session: session.id.clone(), + yolo: false, + }; + let mut history = agent::new_history(system); + // Not a terminal, so the approver must deny rather than block. + let mut approver = Approver::new(false); + + agent::run_turn( + &cfg, + &mut session, + &mut history, + "write a file", + &AtomicBool::new(false), + &mut approver, + ) + .expect("a denial is not a failed turn"); + + assert!(!target.exists()); + assert_eq!(history[3]["role"], "tool"); + assert!( + history[3]["content"] + .as_str() + .unwrap() + .contains("denied by the user") + ); + assert_eq!(history[4]["content"], "understood"); +} diff --git a/tests/mock.rs b/tests/mock.rs index 80d965b..52dec7c 100644 --- a/tests/mock.rs +++ b/tests/mock.rs @@ -73,6 +73,7 @@ fn config(base_url: String) -> Config { api_key: "test-key".into(), model: "test-model".into(), session: "testsession".into(), + yolo: true, } } @@ -94,6 +95,7 @@ fn streams_text_reasoning_and_usage() { let outcome = provider::chat( &config(base), &[json!({ "role": "user", "content": "hi" })], + &[], &AtomicBool::new(false), &mut sink, ) @@ -133,6 +135,7 @@ fn assembles_tool_call_arguments_byte_for_byte() { let outcome = provider::chat( &config(base), &[json!({ "role": "user", "content": "read a.txt" })], + &[], &AtomicBool::new(false), &mut sink, ) @@ -161,6 +164,7 @@ fn surfaces_provider_error_text() { let error = provider::chat( &config(base), &[json!({ "role": "user", "content": "hi" })], + &[], &AtomicBool::new(false), &mut sink, ) @@ -184,6 +188,7 @@ fn honours_a_cancelled_turn() { let error = provider::chat( &config(base), &[json!({ "role": "user", "content": "hi" })], + &[], &AtomicBool::new(true), &mut sink, ) diff --git a/tests/tools.rs b/tests/tools.rs new file mode 100644 index 0000000..0189af8 --- /dev/null +++ b/tests/tools.rs @@ -0,0 +1,142 @@ +use std::fs; +use std::path::PathBuf; +use std::time::Duration; + +use serde_json::json; + +use agent686::tools::{self, shell}; + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("agent686-test-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn edit_refuses_ambiguous_and_missing_text() { + let dir = temp_dir("edit-ambiguous"); + let path = dir.join("a.txt"); + fs::write(&path, "alpha\nbeta\nalpha\n").unwrap(); + + let error = tools::plan("edit", &json!({ "path": path, "old": "alpha", "new": "gamma" })) + .err() + .expect("ambiguous edit must fail"); + assert!(error.contains("appears 2 times"), "{error}"); + assert!(error.contains("lines 1, 3"), "{error}"); + + let error = tools::plan("edit", &json!({ "path": path, "old": "nope", "new": "x" })) + .err() + .expect("missing text must fail"); + assert!(error.contains("was not found"), "{error}"); + + // The file is untouched by a refused plan. + assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta\nalpha\n"); +} + +#[test] +fn edit_applies_exactly_one_replacement() { + let dir = temp_dir("edit-apply"); + let path = dir.join("main.c"); + fs::write(&path, "int main(void) {\n return 0;\n}\n").unwrap(); + + let change = tools::plan( + "edit", + &json!({ "path": path, "old": " return 0;", "new": " return 1;" }), + ) + .expect("unique edit should plan"); + + let preview = change.preview(); + assert!(preview.contains("- return 0;"), "{preview}"); + assert!(preview.contains("+ return 1;"), "{preview}"); + + let outcome = change.apply().expect("apply should succeed"); + assert!(outcome.contains("1 replacement at line 2"), "{outcome}"); + assert_eq!( + fs::read_to_string(&path).unwrap(), + "int main(void) {\n return 1;\n}\n" + ); +} + +#[test] +fn write_does_not_create_parent_directories() { + let dir = temp_dir("write-parent"); + let path = dir.join("missing").join("file.txt"); + let change = tools::plan("write", &json!({ "path": path, "content": "hi" })).unwrap(); + let error = change.apply().err().expect("apply must fail"); + assert!(error.contains("parent directory does not exist"), "{error}"); +} + +#[test] +fn read_numbers_lines_and_reports_truncation() { + let dir = temp_dir("read"); + let path = dir.join("f.txt"); + fs::write(&path, "one\ntwo\nthree\nfour\n").unwrap(); + + let text = tools::run("read", &json!({ "path": path, "limit": 2 })).unwrap(); + assert!(text.contains(" 1\tone"), "{text}"); + assert!(text.contains(" 2\ttwo"), "{text}"); + assert!(text.contains("2 more line(s); continue with offset=3"), "{text}"); + assert!(!text.contains("three"), "{text}"); +} + +#[test] +fn grep_finds_lines_and_honours_case() { + let dir = temp_dir("grep"); + let path = dir.join("f.txt"); + fs::write(&path, "alpha\nbeta\nALPHA\n").unwrap(); + + let text = tools::run("grep", &json!({ "pattern": "alpha", "path": dir })).unwrap(); + assert_eq!(text.lines().count(), 1, "{text}"); + + let text = tools::run( + "grep", + &json!({ "pattern": "alpha", "path": dir, "ignore_case": true }), + ) + .unwrap(); + assert_eq!(text.lines().count(), 2, "{text}"); +} + +#[test] +fn glob_supports_double_star_and_bare_names() { + let dir = temp_dir("glob"); + fs::create_dir_all(dir.join("sub/deep")).unwrap(); + fs::write(dir.join("a.rs"), "").unwrap(); + fs::write(dir.join("sub/b.rs"), "").unwrap(); + fs::write(dir.join("sub/deep/c.rs"), "").unwrap(); + fs::write(dir.join("sub/note.txt"), "").unwrap(); + + let text = tools::run("glob", &json!({ "pattern": "**/*.rs", "path": dir })).unwrap(); + assert_eq!(text.lines().count(), 3, "{text}"); + + let text = tools::run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap(); + assert_eq!(text.lines().count(), 3, "{text}"); + + let text = tools::run("glob", &json!({ "pattern": "sub/*.rs", "path": dir })).unwrap(); + assert_eq!(text.lines().count(), 1, "{text}"); + assert!(text.contains("b.rs"), "{text}"); +} + +#[test] +fn bash_reports_exit_code_and_times_out() { + let text = tools::run("bash", &json!({ "cmd": "echo hi; exit 3" })).unwrap(); + assert!(text.contains("hi"), "{text}"); + assert!(text.contains("[exit 3]"), "{text}"); + + let text = shell::bash(&json!({ "cmd": "sleep 5" }), Duration::from_millis(150)).unwrap(); + assert!(text.contains("timed out after"), "{text}"); +} + +#[test] +fn bash_rejects_a_missing_cwd() { + let error = tools::run("bash", &json!({ "cmd": "true", "cwd": "/nonexistent-dir-xyz" })) + .err() + .expect("missing cwd must fail"); + assert!(error.contains("cwd is not a directory"), "{error}"); +} + +#[test] +fn unknown_tool_is_an_error_not_a_panic() { + let error = tools::run("teleport", &json!({})).err().unwrap(); + assert!(error.contains("unknown tool"), "{error}"); +} -- cgit v1.2.3