diff options
Diffstat (limited to '')
| -rw-r--r-- | Cargo.lock | 1 | ||||
| -rw-r--r-- | Cargo.toml | 1 | ||||
| -rw-r--r-- | README.md | 71 | ||||
| -rw-r--r-- | docs/PLAN.md | 71 | ||||
| -rwxr-xr-x | scripts/check-glibc.sh | 24 | ||||
| -rwxr-xr-x | scripts/mock-provider.py | 18 | ||||
| -rw-r--r-- | src/agent.rs | 218 | ||||
| -rw-r--r-- | src/config.rs | 10 | ||||
| -rw-r--r-- | src/lib.rs | 2 | ||||
| -rw-r--r-- | src/main.rs | 217 | ||||
| -rw-r--r-- | src/provider.rs | 64 | ||||
| -rw-r--r-- | src/session.rs | 182 | ||||
| -rw-r--r-- | src/signal.rs | 23 | ||||
| -rw-r--r-- | src/tools/fs.rs | 527 | ||||
| -rw-r--r-- | src/tools/mod.rs | 148 | ||||
| -rw-r--r-- | src/tools/shell.rs | 129 | ||||
| -rw-r--r-- | src/ui.rs | 171 | ||||
| -rw-r--r-- | tests/loop.rs | 192 | ||||
| -rw-r--r-- | tests/mock.rs | 5 | ||||
| -rw-r--r-- | tests/tools.rs | 142 |
20 files changed, 2061 insertions, 155 deletions
| @@ -12,6 +12,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | |||
| 12 | name = "agent686" | 12 | name = "agent686" |
| 13 | version = "0.1.0" | 13 | version = "0.1.0" |
| 14 | dependencies = [ | 14 | dependencies = [ |
| 15 | "libc", | ||
| 15 | "serde", | 16 | "serde", |
| 16 | "serde_json", | 17 | "serde_json", |
| 17 | "ureq", | 18 | "ureq", |
| @@ -9,6 +9,7 @@ publish = false | |||
| 9 | serde = { version = "1", features = ["derive"] } | 9 | serde = { version = "1", features = ["derive"] } |
| 10 | serde_json = "1" | 10 | serde_json = "1" |
| 11 | ureq = { version = "3", features = ["rustls"] } | 11 | ureq = { version = "3", features = ["rustls"] } |
| 12 | libc = "0.2" | ||
| 12 | 13 | ||
| 13 | [profile.release] | 14 | [profile.release] |
| 14 | strip = true | 15 | 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 @@ | |||
| 1 | # agent686 | ||
| 2 | |||
| 3 | A small coding agent for a 32-bit Debian box: one binary, six tools, line mode. | ||
| 4 | |||
| 5 | Built because the existing harnesses are TypeScript bundles that need a modern | ||
| 6 | CPU, and the target here is a Debian 12 i386 machine with 2 cores and 4 GB. | ||
| 7 | |||
| 8 | ``` | ||
| 9 | 2.0 MB ELF 32-bit LSB pie, Intel i386 | ||
| 10 | GLIBC_2.34 required (target has 2.36) | ||
| 11 | ``` | ||
| 12 | |||
| 13 | ## Build | ||
| 14 | |||
| 15 | ```sh | ||
| 16 | cargo build --release --target i686-unknown-linux-gnu | ||
| 17 | ./scripts/check-glibc.sh target/i686-unknown-linux-gnu/release/agent686 | ||
| 18 | ``` | ||
| 19 | |||
| 20 | The gate matters: the dev host's 32-bit glibc is newer than the target's, so a | ||
| 21 | dependency can silently raise the required symbol version. | ||
| 22 | |||
| 23 | ## Run | ||
| 24 | |||
| 25 | ```sh | ||
| 26 | export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key | ||
| 27 | ./agent686 "make a calculator in C" # one turn, then exit | ||
| 28 | ./agent686 # interactive, one prompt per line | ||
| 29 | ./agent686 -c # continue the most recent session | ||
| 30 | ./agent686 --session <id> # resume a specific one | ||
| 31 | ./agent686 --yolo "..." # approve every tool call | ||
| 32 | ``` | ||
| 33 | |||
| 34 | Provider is OpenCode Go, `chat/completions`, model `deepseek-v4.1-flash` by | ||
| 35 | default. Every request carries a stable `x-opencode-session` header, which the | ||
| 36 | service uses for routing and prompt caching. | ||
| 37 | |||
| 38 | ## Tools | ||
| 39 | |||
| 40 | `read` (numbered lines), `write` (never creates directories), `edit` (exact | ||
| 41 | match, must be unique), `bash` (fresh shell per call, 120 s timeout, capped | ||
| 42 | output), `grep` (literal, recursive), `glob` (`*`, `?`, `**`). | ||
| 43 | |||
| 44 | Reads never prompt. The first `write`/`edit` of a session shows a diff and asks; | ||
| 45 | answering `a` allows the rest of the session. Every `bash` call asks, because | ||
| 46 | that is where `rm -rf` lives. | ||
| 47 | |||
| 48 | ## Tests | ||
| 49 | |||
| 50 | ```sh | ||
| 51 | cargo test # 19 tests, no network | ||
| 52 | python3 scripts/mock-provider.py & # canned SSE provider | ||
| 53 | docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gate | ||
| 54 | ``` | ||
| 55 | |||
| 56 | `tests/sse.rs` feeds the stream one byte at a time, so splits inside lines and | ||
| 57 | inside UTF-8 characters are covered. `tests/loop.rs` proves a tool call is | ||
| 58 | executed, recorded, and that a denial is returned to the model as data. | ||
| 59 | |||
| 60 | ## Design notes | ||
| 61 | |||
| 62 | - [CONTEXT.md](CONTEXT.md) — what the words mean (session, turn, step, approval). | ||
| 63 | - [docs/PLAN.md](docs/PLAN.md) — decisions, non-goals, milestones, acceptance test. | ||
| 64 | - [docs/adr/0001](docs/adr/0001-dynamic-glibc-i686.md) — why dynamic glibc, not | ||
| 65 | a static binary: static glibc plus NSS modules segfaults on DNS. | ||
| 66 | - [docs/adr/0002](docs/adr/0002-append-only-sessions.md) — why history is never | ||
| 67 | rewritten: cached prompt reads are ~50× cheaper, and they require a | ||
| 68 | byte-identical prefix. | ||
| 69 | |||
| 70 | No async runtime, no TUI, no MCP, no subagents, no compaction. Those are | ||
| 71 | 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 | |||
| 73 | streams correctly; `scripts/check-glibc.sh` passes and fails as expected; | 73 | streams correctly; `scripts/check-glibc.sh` passes and fails as expected; |
| 74 | `scripts/mock-provider.py` gives a no-key provider for manual work. | 74 | `scripts/mock-provider.py` gives a no-key provider for manual work. |
| 75 | 75 | ||
| 76 | **M1 — Sessions, status line, abort.** JSONL append/load, session id, `--continue`, | 76 | **M1 — Sessions, status line, abort.** ✅ Done. |
| 77 | `--resume <id>`, status line, SIGINT handling. | 77 | |
| 78 | *Done when:* a turn survives `kill -9` between steps, `--continue` resumes it, and | 78 | JSONL append/load, session id, `--continue`, `--session <id>`, status line, |
| 79 | Ctrl-C returns the prompt without losing the transcript. | 79 | SIGINT handling (first Ctrl-C aborts the turn, second exits). Verified: a |
| 80 | 80 | 9-step turn writes 19 lines (header + 18 messages, reasoning stored under | |
| 81 | **M2 — Read-side tools and edits.** `read`, `write`, `edit`, `grep`, `glob`, the | 81 | `_reasoning`), `--continue` replays all 18 messages and answers from history |
| 82 | agent loop, tool-call accumulation, the approval prompt with diff. | 82 | without reading files. |
| 83 | *Done when:* a canned mock session writes a C file, greps it, edits it, and the | 83 | |
| 84 | transcript replays byte-identically. | 84 | **M2 — Read-side tools and edits.** ✅ Done. |
| 85 | 85 | ||
| 86 | **M3 — `bash`.** Command execution, timeout, output capping, per-call approval, | 86 | `read`, `write`, `edit`, `grep`, `glob`, the agent loop, tool-call accumulation, |
| 87 | head/tail rendering. | 87 | diff preview plus approval. Verified by `tests/tools.rs` (uniqueness, ambiguity |
| 88 | *Done when:* the mock session compiles the C file and handles a non-zero exit as | 88 | with line numbers, no implicit `mkdir`, truncation, glob `**`, grep case) and |
| 89 | data rather than an error. | 89 | `tests/loop.rs` (tool call executed and recorded; a denial returned as data). |
| 90 | 90 | The approval prompt was also driven through a real pty. | |
| 91 | **M4 — Prompt and input.** System prompt, environment block, `AGENTS.md` | 91 | |
| 92 | snapshot, `/paste`, TTY detection, real-API smoke test. | 92 | **M3 — `bash`.** ✅ Done. |
| 93 | *Done when:* one real turn against OpenCode Go works end to end. | 93 | |
| 94 | 94 | Fresh shell per call, 120 s timeout that kills the process, capped output | |
| 95 | **M5 — Target gate.** `scripts/check-glibc.sh` (max symbol version ≤ 2.36), | 95 | (64 KiB head, 16 KiB tail), exit code or signal reported. Verified: exit codes, |
| 96 | `cargo check --target i686` clean, release run inside | 96 | timeout, missing `cwd`, and real `gcc` invocations. |
| 97 | `docker run --platform linux/386 debian:12`, binary copied to the i386 box. | 97 | |
| 98 | *Done when:* the acceptance test runs there. | 98 | **M4 — Prompt and input.** ✅ Done. |
| 99 | |||
| 100 | System prompt with cwd/platform/arch/branch, `AGENTS.md` snapshot frozen at | ||
| 101 | session start with a change warning, `/paste`, TTY-aware colour. Verified | ||
| 102 | against the live API: streaming, tool calls, `reasoning_content`, usage and | ||
| 103 | `opencode.allowance` in the final chunk, and a 401 surfaced as | ||
| 104 | `api_key_expired`. | ||
| 105 | |||
| 106 | **M5 — Target gate.** ✅ Done. | ||
| 107 | |||
| 108 | `scripts/check-glibc.sh` (required symbols ≤ 2.36; weak symbols such as glibc | ||
| 109 | 2.39's `pidfd_spawnp` are reported but ignored, since they resolve to NULL). | ||
| 110 | 2.0 MB stripped i686 binary, `GLIBC_2.34` required. Verified by running the | ||
| 111 | whole acceptance test inside `--platform linux/386 debian:12`. | ||
| 99 | 112 | ||
| 100 | ## Acceptance test (v1) | 113 | ## Acceptance test (v1) |
| 101 | 114 | ||
| 102 | > "Make a simple calculator in C" — run on the i386 box, from an empty directory. | 115 | > "Make a simple calculator in C" — run on the i386 box, from an empty directory. |
| 103 | 116 | ||
| 104 | Exercises `write` (create files), `bash` (compile, run), `read` (inspect what it | 117 | Exercises `write` (create files), `bash` (compile, run), `read` (inspect what it |
| 105 | wrote), and terminates on its own. Success is: it compiles, it runs, it does | 118 | wrote), and terminates on its own. |
| 106 | addition and division, and it did not need more than a handful of files. | 119 | |
| 120 | Two runs, both with `--yolo`: | ||
| 121 | |||
| 122 | | Where | Steps | Wall | Allowance | Result | | ||
| 123 | |---|---|---|---|---| | ||
| 124 | | x86-64 dev host | 9 | 55.7 s | $0.000214 | `calc.c` (115 lines), clean `-Wall -Wextra` build, 18 cases tested | | ||
| 125 | | `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 | | ||
| 126 | |||
| 127 | Independently rebuilt and re-run outside the agent both times. | ||
| 107 | 128 | ||
| 108 | ## Layout | 129 | ## Layout |
| 109 | 130 | ||
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 @@ | |||
| 4 | # The dev host's 32-bit glibc is newer than Debian 12's, so a dependency can | 4 | # The dev host's 32-bit glibc is newer than Debian 12's, so a dependency can |
| 5 | # silently raise the required symbol version. Without this check the failure | 5 | # silently raise the required symbol version. Without this check the failure |
| 6 | # only shows up as "version `GLIBC_2.38' not found" on the target machine. | 6 | # only shows up as "version `GLIBC_2.38' not found" on the target machine. |
| 7 | # | ||
| 8 | # Weak undefined symbols are ignored: they resolve to NULL on older libc and the | ||
| 9 | # code paths using them fall back. Rust's std does this for glibc 2.39's | ||
| 10 | # pidfd_spawnp/pidfd_getpid, for example. | ||
| 7 | set -euo pipefail | 11 | set -euo pipefail |
| 8 | 12 | ||
| 9 | binary=${1:?usage: check-glibc.sh <binary> [ceiling, default 2.36]} | 13 | binary=${1:?usage: check-glibc.sh <binary> [ceiling, default 2.36]} |
| @@ -14,21 +18,31 @@ if [ ! -f "$binary" ]; then | |||
| 14 | exit 2 | 18 | exit 2 |
| 15 | fi | 19 | fi |
| 16 | 20 | ||
| 17 | max=$(readelf -V "$binary" 2>/dev/null \ | 21 | required=$(readelf --dyn-syms --wide "$binary" 2>/dev/null \ |
| 22 | | awk '$5 != "WEAK" { print }' \ | ||
| 23 | | grep -oE 'GLIBC_[0-9]+\.[0-9]+' \ | ||
| 24 | | sed 's/^GLIBC_//' \ | ||
| 25 | | sort -Vu \ | ||
| 26 | | tail -1 || true) | ||
| 27 | weak=$(readelf --dyn-syms --wide "$binary" 2>/dev/null \ | ||
| 28 | | awk '$5 == "WEAK" { print }' \ | ||
| 18 | | grep -oE 'GLIBC_[0-9]+\.[0-9]+' \ | 29 | | grep -oE 'GLIBC_[0-9]+\.[0-9]+' \ |
| 19 | | sed 's/^GLIBC_//' \ | 30 | | sed 's/^GLIBC_//' \ |
| 20 | | sort -Vu \ | 31 | | sort -Vu \ |
| 21 | | tail -1 || true) | 32 | | tail -1 || true) |
| 22 | 33 | ||
| 23 | if [ -z "${max:-}" ]; then | 34 | if [ -z "${required:-}" ]; then |
| 24 | echo "check-glibc: no versioned symbols (statically linked?) — nothing to check" | 35 | echo "check-glibc: no versioned symbols (statically linked?) — nothing to check" |
| 25 | exit 0 | 36 | exit 0 |
| 26 | fi | 37 | fi |
| 27 | 38 | ||
| 28 | echo "check-glibc: max symbol version GLIBC_$max, ceiling GLIBC_$ceiling" | 39 | echo "check-glibc: required GLIBC_$required, ceiling GLIBC_$ceiling" |
| 40 | if [ -n "${weak:-}" ] && [ "$weak" != "$required" ]; then | ||
| 41 | echo "check-glibc: weak GLIBC_$weak (optional, resolves to NULL on older libc)" | ||
| 42 | fi | ||
| 29 | 43 | ||
| 30 | if [ "$(printf '%s\n%s\n' "$ceiling" "$max" | sort -V | tail -1)" != "$ceiling" ]; then | 44 | if [ "$(printf '%s\n%s\n' "$ceiling" "$required" | sort -V | tail -1)" != "$ceiling" ]; then |
| 31 | echo "check-glibc: FAIL — binary needs GLIBC_$max, target has GLIBC_$ceiling" >&2 | 45 | echo "check-glibc: FAIL — binary needs GLIBC_$required, target has GLIBC_$ceiling" >&2 |
| 32 | exit 1 | 46 | exit 1 |
| 33 | fi | 47 | fi |
| 34 | 48 | ||
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 | |||
| 14 | from http.server import BaseHTTPRequestHandler, HTTPServer | 14 | from http.server import BaseHTTPRequestHandler, HTTPServer |
| 15 | 15 | ||
| 16 | 16 | ||
| 17 | def tool_frames(path, content): | ||
| 18 | yield {"choices": [{"delta": {"tool_calls": [{ | ||
| 19 | "index": 0, | ||
| 20 | "id": "call_mock_1", | ||
| 21 | "function": {"name": "write", "arguments": json.dumps({"path": path, "content": content})}, | ||
| 22 | }]}, "finish_reason": "tool_calls"}]} | ||
| 23 | |||
| 24 | |||
| 17 | def frames(answer: str): | 25 | def frames(answer: str): |
| 18 | yield {"choices": [{"delta": {"reasoning_content": "The user said hi. "}}]} | 26 | yield {"choices": [{"delta": {"reasoning_content": "The user said hi. "}}]} |
| 19 | yield {"choices": [{"delta": {"reasoning_content": "A short greeting is enough."}}]} | 27 | yield {"choices": [{"delta": {"reasoning_content": "A short greeting is enough."}}]} |
| @@ -46,12 +54,17 @@ class Handler(BaseHTTPRequestHandler): | |||
| 46 | self.wfile.write(body) | 54 | self.wfile.write(body) |
| 47 | return | 55 | return |
| 48 | 56 | ||
| 57 | self.server.requests += 1 | ||
| 49 | self.send_response(200) | 58 | self.send_response(200) |
| 50 | self.send_header("Content-Type", "text/event-stream") | 59 | self.send_header("Content-Type", "text/event-stream") |
| 51 | self.send_header("Cache-Control", "no-cache") | 60 | self.send_header("Cache-Control", "no-cache") |
| 52 | self.end_headers() | 61 | self.end_headers() |
| 53 | 62 | ||
| 54 | for frame in frames(self.server.answer): | 63 | if self.server.tool_write and self.server.requests == 1: |
| 64 | stream = tool_frames(self.server.tool_write, "written by the mock\n") | ||
| 65 | else: | ||
| 66 | stream = frames(self.server.answer) | ||
| 67 | for frame in stream: | ||
| 55 | if self.server.delay: | 68 | if self.server.delay: |
| 56 | time.sleep(self.server.delay) | 69 | time.sleep(self.server.delay) |
| 57 | self.wfile.write(f"data: {json.dumps(frame)}\n\n".encode()) | 70 | self.wfile.write(f"data: {json.dumps(frame)}\n\n".encode()) |
| @@ -70,6 +83,7 @@ def main(): | |||
| 70 | parser.add_argument("--delay", type=float, default=0.05, help="seconds between frames") | 83 | parser.add_argument("--delay", type=float, default=0.05, help="seconds between frames") |
| 71 | parser.add_argument("--status", type=int, default=200, help="return this HTTP status") | 84 | parser.add_argument("--status", type=int, default=200, help="return this HTTP status") |
| 72 | parser.add_argument("--answer", default="Hello from the mock provider.") | 85 | parser.add_argument("--answer", default="Hello from the mock provider.") |
| 86 | parser.add_argument("--tool-write", metavar="PATH", help="first response asks to write PATH") | ||
| 73 | parser.add_argument("--quiet", action="store_true") | 87 | parser.add_argument("--quiet", action="store_true") |
| 74 | args = parser.parse_args() | 88 | args = parser.parse_args() |
| 75 | 89 | ||
| @@ -78,6 +92,8 @@ def main(): | |||
| 78 | server.delay = args.delay | 92 | server.delay = args.delay |
| 79 | server.status = args.status | 93 | server.status = args.status |
| 80 | server.quiet = args.quiet | 94 | server.quiet = args.quiet |
| 95 | server.tool_write = args.tool_write | ||
| 96 | server.requests = 0 | ||
| 81 | print(f"mock provider on http://127.0.0.1:{args.port}/v1", flush=True) | 97 | print(f"mock provider on http://127.0.0.1:{args.port}/v1", flush=True) |
| 82 | server.serve_forever() | 98 | server.serve_forever() |
| 83 | 99 | ||
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 @@ | |||
| 1 | use std::path::PathBuf; | ||
| 2 | use std::process::Command; | ||
| 1 | use std::sync::atomic::AtomicBool; | 3 | use std::sync::atomic::AtomicBool; |
| 4 | use std::time::{Instant, SystemTime}; | ||
| 2 | 5 | ||
| 3 | use serde_json::{json, Value}; | 6 | use serde_json::{json, Value}; |
| 4 | 7 | ||
| 5 | use crate::config::Config; | 8 | use crate::config::Config; |
| 6 | use crate::provider::{self, Error, Outcome, Sink}; | 9 | use crate::provider::{self, Error, Outcome}; |
| 10 | use crate::session::Session; | ||
| 11 | use crate::tools::{self, Approval}; | ||
| 12 | use crate::ui::{self, Approver, Renderer}; | ||
| 7 | 13 | ||
| 8 | /// Frozen for the life of the process. Anything session-varying added here | 14 | /// Frozen for the life of the session. Anything session-varying added here |
| 9 | /// invalidates the provider's prompt cache, so keep it boring. | 15 | /// invalidates the provider's prompt cache, so keep it boring. |
| 10 | pub fn system_message() -> Value { | 16 | pub fn system_prompt() -> Value { |
| 11 | json!({ | 17 | let mut text = String::from( |
| 12 | "role": "system", | 18 | "You are agent686, a coding agent in a Unix terminal.\n\n\ |
| 13 | "content": "You are agent686, a coding agent working in a Unix terminal. \ | 19 | Tools: read, write, edit, bash, grep, glob. Paths are relative to the working \ |
| 14 | You edit files and run commands. Be terse and do not explain \ | 20 | directory.\n\ |
| 15 | what you are about to do before doing it." | 21 | - read before you edit; files are shown with line numbers.\n\ |
| 16 | }) | 22 | - edit replaces one exact occurrence of the old text and fails if it is missing \ |
| 23 | or ambiguous, so include enough context.\n\ | ||
| 24 | - write replaces a whole file and does not create directories.\n\ | ||
| 25 | - bash starts a fresh shell in the working directory every call; cd does not \ | ||
| 26 | persist, pass cwd instead.\n\ | ||
| 27 | - Do not explain what you are about to do. Act, then report briefly.\n\n", | ||
| 28 | ); | ||
| 29 | |||
| 30 | let cwd = std::env::current_dir() | ||
| 31 | .map(|p| p.display().to_string()) | ||
| 32 | .unwrap_or_default(); | ||
| 33 | text.push_str(&format!( | ||
| 34 | "Environment: cwd={cwd} · {} · {}", | ||
| 35 | std::env::consts::OS, | ||
| 36 | std::env::consts::ARCH | ||
| 37 | )); | ||
| 38 | if let Some(branch) = git_branch(&cwd) { | ||
| 39 | text.push_str(&format!(" · branch={branch}")); | ||
| 40 | } | ||
| 41 | text.push('\n'); | ||
| 42 | |||
| 43 | if let Some((path, content)) = project_instructions() { | ||
| 44 | if !content.trim().is_empty() { | ||
| 45 | text.push_str(&format!( | ||
| 46 | "\n<project-instructions source=\"{}\">\n{}\n</project-instructions>\n", | ||
| 47 | path.display(), | ||
| 48 | content.trim() | ||
| 49 | )); | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | json!({ "role": "system", "content": text }) | ||
| 54 | } | ||
| 55 | |||
| 56 | pub fn agents_md() -> Option<(PathBuf, SystemTime)> { | ||
| 57 | let path = project_instructions().map(|(path, _)| path)?; | ||
| 58 | let modified = std::fs::metadata(&path).ok()?.modified().ok()?; | ||
| 59 | Some((path, modified)) | ||
| 60 | } | ||
| 61 | |||
| 62 | fn project_instructions() -> Option<(PathBuf, String)> { | ||
| 63 | let mut dir = std::env::current_dir().ok()?; | ||
| 64 | loop { | ||
| 65 | let candidate = dir.join("AGENTS.md"); | ||
| 66 | if candidate.is_file() { | ||
| 67 | let content = std::fs::read_to_string(&candidate).ok()?; | ||
| 68 | return Some((candidate, content)); | ||
| 69 | } | ||
| 70 | if !dir.pop() { | ||
| 71 | return None; | ||
| 72 | } | ||
| 73 | } | ||
| 17 | } | 74 | } |
| 18 | 75 | ||
| 19 | /// Appends the user message, runs one provider round trip, and appends the | 76 | fn git_branch(cwd: &str) -> Option<String> { |
| 20 | /// assistant message to the history whether or not it asked for tools. | 77 | let output = Command::new("git") |
| 78 | .arg("-C") | ||
| 79 | .arg(cwd) | ||
| 80 | .args(["rev-parse", "--abbrev-ref", "HEAD"]) | ||
| 81 | .output() | ||
| 82 | .ok()?; | ||
| 83 | if !output.status.success() { | ||
| 84 | return None; | ||
| 85 | } | ||
| 86 | let branch = String::from_utf8_lossy(&output.stdout).trim().to_string(); | ||
| 87 | if branch.is_empty() { | ||
| 88 | None | ||
| 89 | } else { | ||
| 90 | Some(branch) | ||
| 91 | } | ||
| 92 | } | ||
| 93 | |||
| 94 | pub fn new_history(system: Value) -> Vec<Value> { | ||
| 95 | vec![system] | ||
| 96 | } | ||
| 97 | |||
| 98 | /// Runs one turn to completion: model, tools, model, ... until the model answers | ||
| 99 | /// without asking for a tool. Every message that is sent is also appended to the | ||
| 100 | /// session file, in order, before the next request. | ||
| 21 | pub fn run_turn( | 101 | pub fn run_turn( |
| 22 | cfg: &Config, | 102 | cfg: &Config, |
| 103 | session: &mut Session, | ||
| 23 | history: &mut Vec<Value>, | 104 | history: &mut Vec<Value>, |
| 24 | prompt: &str, | 105 | prompt: &str, |
| 25 | cancel: &AtomicBool, | 106 | cancel: &AtomicBool, |
| 26 | sink: &mut dyn Sink, | 107 | approver: &mut Approver, |
| 27 | ) -> Result<Outcome, Error> { | 108 | ) -> Result<(), Error> { |
| 28 | history.push(json!({ "role": "user", "content": prompt })); | 109 | let started = Instant::now(); |
| 110 | |||
| 111 | let user = json!({ "role": "user", "content": prompt }); | ||
| 112 | push(session, history, user, None); | ||
| 29 | 113 | ||
| 30 | let outcome = provider::chat(cfg, history, cancel, sink)?; | 114 | let schemas = tools::schemas(); |
| 115 | let mut steps = 0usize; | ||
| 116 | let mut last: Option<Outcome> = None; | ||
| 31 | 117 | ||
| 118 | loop { | ||
| 119 | if cancel.load(std::sync::atomic::Ordering::Relaxed) { | ||
| 120 | crate::signal::reset(); | ||
| 121 | eprintln!("aborted"); | ||
| 122 | break; | ||
| 123 | } | ||
| 124 | |||
| 125 | steps += 1; | ||
| 126 | let mut renderer = Renderer::new(); | ||
| 127 | let mut outcome = match provider::chat(cfg, history, &schemas, cancel, &mut renderer) { | ||
| 128 | Ok(outcome) => outcome, | ||
| 129 | Err(Error::Aborted) => { | ||
| 130 | crate::signal::reset(); | ||
| 131 | eprintln!("aborted"); | ||
| 132 | break; | ||
| 133 | } | ||
| 134 | Err(error) => return Err(error), | ||
| 135 | }; | ||
| 136 | |||
| 137 | // A missing id would make the tool result unattachable. | ||
| 138 | for (index, call) in outcome.tool_calls.iter_mut().enumerate() { | ||
| 139 | if call.id.is_empty() { | ||
| 140 | call.id = format!("call_{steps}_{index}"); | ||
| 141 | } | ||
| 142 | } | ||
| 143 | |||
| 144 | let assistant = assistant_message(&outcome); | ||
| 145 | push(session, history, assistant, Some(outcome.reasoning.as_str())); | ||
| 146 | |||
| 147 | if outcome.tool_calls.is_empty() { | ||
| 148 | last = Some(outcome); | ||
| 149 | break; | ||
| 150 | } | ||
| 151 | let calls = outcome.tool_calls.clone(); | ||
| 152 | last = Some(outcome); | ||
| 153 | |||
| 154 | for call in calls { | ||
| 155 | if cancel.load(std::sync::atomic::Ordering::Relaxed) { | ||
| 156 | crate::signal::reset(); | ||
| 157 | eprintln!("aborted"); | ||
| 158 | break; | ||
| 159 | } | ||
| 160 | let result = execute(&call, approver); | ||
| 161 | ui::tool_result(&result); | ||
| 162 | let content = match result { | ||
| 163 | Ok(output) => output, | ||
| 164 | Err(error) => format!("error: {error}"), | ||
| 165 | }; | ||
| 166 | let message = json!({ | ||
| 167 | "role": "tool", | ||
| 168 | "tool_call_id": call.id, | ||
| 169 | "content": content, | ||
| 170 | }); | ||
| 171 | push(session, history, message, None); | ||
| 172 | } | ||
| 173 | } | ||
| 174 | |||
| 175 | if let Some(outcome) = last { | ||
| 176 | ui::status(steps, started.elapsed(), &outcome); | ||
| 177 | } | ||
| 178 | Ok(()) | ||
| 179 | } | ||
| 180 | |||
| 181 | fn execute(call: &provider::ToolCall, approver: &mut Approver) -> Result<String, String> { | ||
| 182 | let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); | ||
| 183 | ui::tool_line(&call.name, &args); | ||
| 184 | |||
| 185 | match tools::approval(&call.name) { | ||
| 186 | Approval::Never => tools::run(&call.name, &args), | ||
| 187 | Approval::Once => match tools::plan(&call.name, &args) { | ||
| 188 | Ok(change) => { | ||
| 189 | if approver.allow_edit(change.path(), &change.preview()) { | ||
| 190 | change.apply() | ||
| 191 | } else { | ||
| 192 | Err("denied by the user".into()) | ||
| 193 | } | ||
| 194 | } | ||
| 195 | Err(error) => Err(error), | ||
| 196 | }, | ||
| 197 | Approval::EveryCall => { | ||
| 198 | let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""); | ||
| 199 | if approver.allow_bash(cmd) { | ||
| 200 | tools::run(&call.name, &args) | ||
| 201 | } else { | ||
| 202 | Err("denied by the user".into()) | ||
| 203 | } | ||
| 204 | } | ||
| 205 | } | ||
| 206 | } | ||
| 207 | |||
| 208 | fn assistant_message(outcome: &Outcome) -> Value { | ||
| 32 | let mut message = serde_json::Map::new(); | 209 | let mut message = serde_json::Map::new(); |
| 33 | message.insert("role".into(), json!("assistant")); | 210 | message.insert("role".into(), json!("assistant")); |
| 34 | message.insert( | 211 | message.insert( |
| @@ -57,11 +234,12 @@ pub fn run_turn( | |||
| 57 | .collect(); | 234 | .collect(); |
| 58 | message.insert("tool_calls".into(), Value::Array(calls)); | 235 | message.insert("tool_calls".into(), Value::Array(calls)); |
| 59 | } | 236 | } |
| 60 | history.push(Value::Object(message)); | 237 | Value::Object(message) |
| 61 | |||
| 62 | Ok(outcome) | ||
| 63 | } | 238 | } |
| 64 | 239 | ||
| 65 | pub fn new_history() -> Vec<Value> { | 240 | fn push(session: &mut Session, history: &mut Vec<Value>, message: Value, reasoning: Option<&str>) { |
| 66 | vec![system_message()] | 241 | if let Err(error) = session.append(&message, reasoning) { |
| 242 | eprintln!("agent686: could not write session: {error}"); | ||
| 243 | } | ||
| 244 | history.push(message); | ||
| 67 | } | 245 | } |
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 { | |||
| 8 | pub base_url: String, | 8 | pub base_url: String, |
| 9 | pub api_key: String, | 9 | pub api_key: String, |
| 10 | pub model: String, | 10 | pub model: String, |
| 11 | /// Session id, sent to the provider as `x-opencode-session`. Filled in once | ||
| 12 | /// the session exists. | ||
| 11 | pub session: String, | 13 | pub session: String, |
| 14 | pub yolo: bool, | ||
| 12 | } | 15 | } |
| 13 | 16 | ||
| 14 | impl Config { | 17 | impl Config { |
| @@ -16,7 +19,7 @@ impl Config { | |||
| 16 | pub fn resolve( | 19 | pub fn resolve( |
| 17 | model: Option<String>, | 20 | model: Option<String>, |
| 18 | base_url: Option<String>, | 21 | base_url: Option<String>, |
| 19 | session: Option<String>, | 22 | yolo: bool, |
| 20 | ) -> Result<Config, String> { | 23 | ) -> Result<Config, String> { |
| 21 | Ok(Config { | 24 | Ok(Config { |
| 22 | api_key: api_key()?, | 25 | api_key: api_key()?, |
| @@ -26,7 +29,8 @@ impl Config { | |||
| 26 | model: model | 29 | model: model |
| 27 | .or_else(|| env_nonempty("AGENT686_MODEL")) | 30 | .or_else(|| env_nonempty("AGENT686_MODEL")) |
| 28 | .unwrap_or_else(|| DEFAULT_MODEL.to_string()), | 31 | .unwrap_or_else(|| DEFAULT_MODEL.to_string()), |
| 29 | session: session.unwrap_or_else(crate::session::new_id), | 32 | session: String::new(), |
| 33 | yolo, | ||
| 30 | }) | 34 | }) |
| 31 | } | 35 | } |
| 32 | 36 | ||
| @@ -40,7 +44,7 @@ fn env_nonempty(key: &str) -> Option<String> { | |||
| 40 | } | 44 | } |
| 41 | 45 | ||
| 42 | /// The key comes from the environment first, then from a file, so a key never | 46 | /// The key comes from the environment first, then from a file, so a key never |
| 43 | /// has to live in shell history or in a process listing. | 47 | /// has to live in shell history. |
| 44 | fn api_key() -> Result<String, String> { | 48 | fn api_key() -> Result<String, String> { |
| 45 | if let Some(k) = env_nonempty("OPENCODE_API_KEY") { | 49 | if let Some(k) = env_nonempty("OPENCODE_API_KEY") { |
| 46 | return Ok(k.trim().to_string()); | 50 | return Ok(k.trim().to_string()); |
| @@ -2,4 +2,6 @@ pub mod agent; | |||
| 2 | pub mod config; | 2 | pub mod config; |
| 3 | pub mod provider; | 3 | pub mod provider; |
| 4 | pub mod session; | 4 | pub mod session; |
| 5 | pub mod signal; | ||
| 6 | pub mod tools; | ||
| 5 | pub mod ui; | 7 | 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 @@ | |||
| 1 | use std::io::{BufRead, IsTerminal, Write}; | 1 | use std::io::{BufRead, IsTerminal, Write}; |
| 2 | use std::sync::atomic::AtomicBool; | 2 | use std::path::PathBuf; |
| 3 | use std::time::SystemTime; | ||
| 3 | 4 | ||
| 4 | use agent686::{agent, config::Config, ui}; | 5 | use serde_json::Value; |
| 6 | |||
| 7 | use agent686::config::Config; | ||
| 8 | use agent686::session::{self, Session}; | ||
| 9 | use agent686::ui::Approver; | ||
| 10 | use agent686::{agent, signal}; | ||
| 5 | 11 | ||
| 6 | const HELP: &str = "\ | 12 | const HELP: &str = "\ |
| 7 | agent686 — a small coding agent | 13 | agent686 — a small coding agent |
| @@ -9,33 +15,40 @@ agent686 — a small coding agent | |||
| 9 | USAGE: | 15 | USAGE: |
| 10 | agent686 [OPTIONS] [PROMPT...] | 16 | agent686 [OPTIONS] [PROMPT...] |
| 11 | 17 | ||
| 12 | With a prompt it runs one turn and exits; without one it reads prompts from | 18 | With a prompt it runs one turn and exits. Without one it reads prompts from |
| 13 | stdin, one per line. /exit quits. | 19 | stdin, one per line. Commands: /paste, /exit, /help. |
| 14 | 20 | ||
| 15 | OPTIONS: | 21 | OPTIONS: |
| 16 | -m, --model <ID> model id (default: deepseek-v4.1-flash) | 22 | -m, --model <ID> model id (default: deepseek-v4.1-flash) |
| 17 | --base-url <URL> provider base URL, e.g. http://127.0.0.1:8080/v1 | 23 | --base-url <URL> provider base URL |
| 18 | --session <ID> reuse a session id, including for the provider header | 24 | --session <ID> resume a specific session |
| 25 | -c, --continue resume the most recent session | ||
| 26 | --yolo approve every tool call without asking | ||
| 19 | -h, --help this text | 27 | -h, --help this text |
| 20 | 28 | ||
| 21 | ENVIRONMENT: | 29 | ENVIRONMENT: |
| 22 | OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) | 30 | OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) |
| 23 | AGENT686_MODEL default model id | 31 | AGENT686_MODEL default model id |
| 24 | AGENT686_BASE_URL default provider base URL | 32 | AGENT686_BASE_URL default provider base URL |
| 33 | AGENT686_DATA where sessions live (default ~/.local/share/agent686) | ||
| 25 | "; | 34 | "; |
| 26 | 35 | ||
| 27 | fn main() { | 36 | fn main() { |
| 28 | let mut prompt: Option<String> = None; | 37 | let mut prompt_words: Vec<String> = Vec::new(); |
| 29 | let mut model = None; | 38 | let mut model = None; |
| 30 | let mut base_url = None; | 39 | let mut base_url = None; |
| 31 | let mut session = None; | 40 | let mut resume = None; |
| 41 | let mut continue_last = false; | ||
| 42 | let mut yolo = false; | ||
| 32 | 43 | ||
| 33 | let mut args = std::env::args().skip(1); | 44 | let mut args = std::env::args().skip(1); |
| 34 | while let Some(arg) = args.next() { | 45 | while let Some(arg) = args.next() { |
| 35 | match arg.as_str() { | 46 | match arg.as_str() { |
| 36 | "-m" | "--model" => model = args.next(), | 47 | "-m" | "--model" => model = args.next(), |
| 37 | "--base-url" => base_url = args.next(), | 48 | "--base-url" => base_url = args.next(), |
| 38 | "--session" => session = args.next(), | 49 | "--session" | "--resume" => resume = args.next(), |
| 50 | "-c" | "--continue" => continue_last = true, | ||
| 51 | "--yolo" => yolo = true, | ||
| 39 | "-h" | "--help" => { | 52 | "-h" | "--help" => { |
| 40 | print!("{HELP}"); | 53 | print!("{HELP}"); |
| 41 | return; | 54 | return; |
| @@ -45,16 +58,13 @@ fn main() { | |||
| 45 | print!("{HELP}"); | 58 | print!("{HELP}"); |
| 46 | std::process::exit(2); | 59 | std::process::exit(2); |
| 47 | } | 60 | } |
| 48 | word => { | 61 | word => prompt_words.push(word.to_string()), |
| 49 | prompt = Some(match prompt.take() { | ||
| 50 | Some(existing) => format!("{existing} {word}"), | ||
| 51 | None => word.to_string(), | ||
| 52 | }) | ||
| 53 | } | ||
| 54 | } | 62 | } |
| 55 | } | 63 | } |
| 56 | 64 | ||
| 57 | let cfg = match Config::resolve(model, base_url, session) { | 65 | signal::install(); |
| 66 | |||
| 67 | let mut cfg = match Config::resolve(model, base_url, yolo) { | ||
| 58 | Ok(cfg) => cfg, | 68 | Ok(cfg) => cfg, |
| 59 | Err(message) => { | 69 | Err(message) => { |
| 60 | eprintln!("agent686: {message}"); | 70 | eprintln!("agent686: {message}"); |
| @@ -62,18 +72,31 @@ fn main() { | |||
| 62 | } | 72 | } |
| 63 | }; | 73 | }; |
| 64 | 74 | ||
| 65 | let cancel = AtomicBool::new(false); | 75 | let (mut session, mut history) = match open_session(&cfg, resume, continue_last) { |
| 66 | let mut history = agent::new_history(); | 76 | Ok(pair) => pair, |
| 67 | 77 | Err(message) => { | |
| 68 | // One-shot mode: a prompt on the command line means one turn, then exit. | 78 | eprintln!("agent686: {message}"); |
| 69 | if let Some(prompt) = prompt { | 79 | std::process::exit(1); |
| 70 | let mut sink = ui::Renderer::new(ui::stdout_is_tty()); | 80 | } |
| 71 | match agent::run_turn(&cfg, &mut history, &prompt, &cancel, &mut sink) { | 81 | }; |
| 72 | Ok(outcome) => note_tool_calls(&outcome), | 82 | cfg.session = session.id.clone(); |
| 73 | Err(error) => { | 83 | |
| 74 | eprintln!("agent686: {error}"); | 84 | let mut approver = Approver::new(cfg.yolo); |
| 75 | std::process::exit(1); | 85 | let watched = agent::agents_md(); |
| 76 | } | 86 | let mut warned = false; |
| 87 | |||
| 88 | if !prompt_words.is_empty() { | ||
| 89 | let prompt = prompt_words.join(" "); | ||
| 90 | if let Err(error) = agent::run_turn( | ||
| 91 | &cfg, | ||
| 92 | &mut session, | ||
| 93 | &mut history, | ||
| 94 | &prompt, | ||
| 95 | &signal::CANCEL, | ||
| 96 | &mut approver, | ||
| 97 | ) { | ||
| 98 | eprintln!("agent686: {error}"); | ||
| 99 | std::process::exit(1); | ||
| 77 | } | 100 | } |
| 78 | return; | 101 | return; |
| 79 | } | 102 | } |
| @@ -84,9 +107,9 @@ fn main() { | |||
| 84 | "agent686 · {} · session {}{}", | 107 | "agent686 · {} · session {}{}", |
| 85 | cfg.model, | 108 | cfg.model, |
| 86 | cfg.session, | 109 | cfg.session, |
| 87 | if is_local(&cfg.base_url) { " · local" } else { "" } | 110 | if cfg.yolo { " · yolo" } else { "" } |
| 88 | ); | 111 | ); |
| 89 | eprintln!("one prompt per line · /exit to quit"); | 112 | eprintln!("one prompt per line · /paste · /exit"); |
| 90 | } | 113 | } |
| 91 | 114 | ||
| 92 | let stdin = std::io::stdin(); | 115 | let stdin = std::io::stdin(); |
| @@ -100,37 +123,121 @@ fn main() { | |||
| 100 | if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { | 123 | if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { |
| 101 | break; | 124 | break; |
| 102 | } | 125 | } |
| 103 | let text = line.trim_end(); | 126 | let mut text = line.trim_end().to_string(); |
| 104 | if text.is_empty() { | 127 | if text.is_empty() { |
| 105 | continue; | 128 | continue; |
| 106 | } | 129 | } |
| 107 | if text == "/exit" || text == "/quit" { | 130 | |
| 108 | break; | 131 | match text.as_str() { |
| 132 | "/exit" | "/quit" => break, | ||
| 133 | "/help" => { | ||
| 134 | print!("{HELP}"); | ||
| 135 | continue; | ||
| 136 | } | ||
| 137 | "/paste" => { | ||
| 138 | let mut buffer = String::new(); | ||
| 139 | loop { | ||
| 140 | if interactive { | ||
| 141 | print!("… "); | ||
| 142 | let _ = std::io::stdout().flush(); | ||
| 143 | } | ||
| 144 | line.clear(); | ||
| 145 | if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { | ||
| 146 | break; | ||
| 147 | } | ||
| 148 | let piece = line.trim_end_matches(['\n', '\r']); | ||
| 149 | if piece == "." { | ||
| 150 | break; | ||
| 151 | } | ||
| 152 | buffer.push_str(piece); | ||
| 153 | buffer.push('\n'); | ||
| 154 | } | ||
| 155 | text = buffer.trim_end().to_string(); | ||
| 156 | if text.is_empty() { | ||
| 157 | continue; | ||
| 158 | } | ||
| 159 | } | ||
| 160 | _ => {} | ||
| 109 | } | 161 | } |
| 110 | let mut sink = ui::Renderer::new(ui::stdout_is_tty()); | 162 | |
| 111 | match agent::run_turn(&cfg, &mut history, text, &cancel, &mut sink) { | 163 | warn_if_changed(&watched, &mut warned); |
| 112 | Ok(outcome) => note_tool_calls(&outcome), | 164 | if let Err(error) = agent::run_turn( |
| 113 | Err(error) => eprintln!("agent686: {error}"), | 165 | &cfg, |
| 166 | &mut session, | ||
| 167 | &mut history, | ||
| 168 | &text, | ||
| 169 | &signal::CANCEL, | ||
| 170 | &mut approver, | ||
| 171 | ) { | ||
| 172 | eprintln!("agent686: {error}"); | ||
| 114 | } | 173 | } |
| 115 | } | 174 | } |
| 116 | } | 175 | } |
| 117 | 176 | ||
| 118 | fn note_tool_calls(outcome: &agent686::provider::Outcome) { | 177 | fn open_session( |
| 119 | if outcome.tool_calls.is_empty() { | 178 | cfg: &Config, |
| 120 | return; | 179 | resume: Option<String>, |
| 180 | continue_last: bool, | ||
| 181 | ) -> Result<(Session, Vec<Value>), String> { | ||
| 182 | let id = match resume { | ||
| 183 | Some(id) => Some(id), | ||
| 184 | None if continue_last => Some( | ||
| 185 | session::latest()? | ||
| 186 | .ok_or_else(|| "no sessions to continue; run without --continue".to_string())?, | ||
| 187 | ), | ||
| 188 | None => None, | ||
| 189 | }; | ||
| 190 | |||
| 191 | match id { | ||
| 192 | Some(id) => { | ||
| 193 | let (session, system, messages) = Session::open(&id)?; | ||
| 194 | if !session.model.is_empty() && session.model != cfg.model { | ||
| 195 | eprintln!( | ||
| 196 | "agent686: session used {}; continuing with {}", | ||
| 197 | session.model, cfg.model | ||
| 198 | ); | ||
| 199 | } | ||
| 200 | // The system message frozen at session start is reused verbatim, so | ||
| 201 | // the request prefix stays byte-identical across restarts. | ||
| 202 | let system = if system.is_null() { | ||
| 203 | agent::system_prompt() | ||
| 204 | } else { | ||
| 205 | system | ||
| 206 | }; | ||
| 207 | let mut history = agent::new_history(system); | ||
| 208 | let count = messages.len(); | ||
| 209 | history.extend(messages); | ||
| 210 | eprintln!("agent686: resumed {} ({count} messages)", session.id); | ||
| 211 | Ok((session, history)) | ||
| 212 | } | ||
| 213 | None => { | ||
| 214 | let system = agent::system_prompt(); | ||
| 215 | let session = Session::create(&cfg.model, &system)?; | ||
| 216 | eprintln!( | ||
| 217 | "agent686: new session {} ({})", | ||
| 218 | session.id, | ||
| 219 | session.path().display() | ||
| 220 | ); | ||
| 221 | Ok((session, agent::new_history(system))) | ||
| 222 | } | ||
| 121 | } | 223 | } |
| 122 | let names: Vec<&str> = outcome | ||
| 123 | .tool_calls | ||
| 124 | .iter() | ||
| 125 | .map(|call| call.name.as_str()) | ||
| 126 | .collect(); | ||
| 127 | eprintln!( | ||
| 128 | "agent686: model asked for {} tool call(s) [{}]; tools arrive in milestone 2", | ||
| 129 | names.len(), | ||
| 130 | names.join(", ") | ||
| 131 | ); | ||
| 132 | } | 224 | } |
| 133 | 225 | ||
| 134 | fn is_local(base_url: &str) -> bool { | 226 | fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) { |
| 135 | base_url.contains("127.0.0.1") || base_url.contains("localhost") | 227 | let (path, seen) = match watched { |
| 228 | Some(watched) => watched, | ||
| 229 | None => return, | ||
| 230 | }; | ||
| 231 | if *warned { | ||
| 232 | return; | ||
| 233 | } | ||
| 234 | if let Ok(modified) = std::fs::metadata(path).and_then(|m| m.modified()) { | ||
| 235 | if modified != *seen { | ||
| 236 | eprintln!( | ||
| 237 | "agent686: {} changed; start a new session to pick it up", | ||
| 238 | path.display() | ||
| 239 | ); | ||
| 240 | *warned = true; | ||
| 241 | } | ||
| 242 | } | ||
| 136 | } | 243 | } |
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 { | |||
| 44 | pub tool_calls: Vec<ToolCall>, | 44 | pub tool_calls: Vec<ToolCall>, |
| 45 | pub finish: Option<String>, | 45 | pub finish: Option<String>, |
| 46 | pub usage: Option<Value>, | 46 | pub usage: Option<Value>, |
| 47 | pub opencode: Option<Value>, | 47 | } |
| 48 | |||
| 49 | impl Outcome { | ||
| 50 | pub fn allowance(&self) -> Option<f64> { | ||
| 51 | self.usage | ||
| 52 | .as_ref()? | ||
| 53 | .get("opencode")? | ||
| 54 | .get("allowance")? | ||
| 55 | .as_f64() | ||
| 56 | } | ||
| 57 | |||
| 58 | pub fn list_cost(&self) -> Option<f64> { | ||
| 59 | self.usage | ||
| 60 | .as_ref()? | ||
| 61 | .get("opencode")? | ||
| 62 | .get("list_cost")? | ||
| 63 | .as_f64() | ||
| 64 | } | ||
| 65 | |||
| 66 | pub fn tokens(&self) -> (Option<u64>, Option<u64>) { | ||
| 67 | let usage = match &self.usage { | ||
| 68 | Some(u) => u, | ||
| 69 | None => return (None, None), | ||
| 70 | }; | ||
| 71 | ( | ||
| 72 | usage.get("prompt_tokens").and_then(|v| v.as_u64()), | ||
| 73 | usage.get("completion_tokens").and_then(|v| v.as_u64()), | ||
| 74 | ) | ||
| 75 | } | ||
| 48 | } | 76 | } |
| 49 | 77 | ||
| 50 | pub trait Sink { | 78 | pub trait Sink { |
| @@ -92,19 +120,22 @@ impl SseDecoder { | |||
| 92 | pub fn chat( | 120 | pub fn chat( |
| 93 | cfg: &Config, | 121 | cfg: &Config, |
| 94 | messages: &[Value], | 122 | messages: &[Value], |
| 123 | tools: &[Value], | ||
| 95 | cancel: &AtomicBool, | 124 | cancel: &AtomicBool, |
| 96 | sink: &mut dyn Sink, | 125 | sink: &mut dyn Sink, |
| 97 | ) -> Result<Outcome, Error> { | 126 | ) -> Result<Outcome, Error> { |
| 98 | // serde_json::Value is ordered by key, not by insertion, so the serialised | 127 | // serde_json::Value orders objects by key, so the serialised bytes are |
| 99 | // bytes are stable for the same input. That is what keeps the cache warm; | 128 | // stable for the same input. That is what keeps the provider's prompt cache |
| 100 | // do not switch this to a struct with fields in a different order, and do | 129 | // warm. Do not add anything session-varying here. |
| 101 | // not add anything session-varying to the system message. | 130 | let mut body = serde_json::json!({ |
| 102 | let body = serde_json::json!({ | ||
| 103 | "model": cfg.model, | 131 | "model": cfg.model, |
| 104 | "messages": messages, | 132 | "messages": messages, |
| 105 | "stream": true, | 133 | "stream": true, |
| 106 | "stream_options": { "include_usage": true }, | 134 | "stream_options": { "include_usage": true }, |
| 107 | }); | 135 | }); |
| 136 | if !tools.is_empty() { | ||
| 137 | body["tools"] = Value::Array(tools.to_vec()); | ||
| 138 | } | ||
| 108 | let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; | 139 | let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; |
| 109 | 140 | ||
| 110 | let agent: ureq::Agent = ureq::Agent::config_builder() | 141 | let agent: ureq::Agent = ureq::Agent::config_builder() |
| @@ -169,23 +200,15 @@ pub fn chat( | |||
| 169 | } | 200 | } |
| 170 | let chunk: Chunk = match serde_json::from_str(&data) { | 201 | let chunk: Chunk = match serde_json::from_str(&data) { |
| 171 | Ok(c) => c, | 202 | Ok(c) => c, |
| 172 | // A malformed frame is dropped rather than killing the turn; the | 203 | // A malformed frame is dropped rather than killing the turn. |
| 173 | // stream is the only recovery path and it is still valid SSE. | ||
| 174 | Err(_) => continue, | 204 | Err(_) => continue, |
| 175 | }; | 205 | }; |
| 176 | apply_chunk(&chunk, &mut outcome, sink); | 206 | apply_chunk(&chunk, &mut outcome, sink); |
| 177 | } | 207 | } |
| 178 | } | 208 | } |
| 179 | 209 | ||
| 180 | if let Some(usage) = &outcome.usage { | 210 | if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { |
| 181 | if usage.is_null() { | 211 | outcome.usage = None; |
| 182 | outcome.usage = None; | ||
| 183 | } | ||
| 184 | } | ||
| 185 | if let Some(opencode) = &outcome.opencode { | ||
| 186 | if opencode.is_null() { | ||
| 187 | outcome.opencode = None; | ||
| 188 | } | ||
| 189 | } | 212 | } |
| 190 | 213 | ||
| 191 | sink.done(&outcome, started.elapsed()); | 214 | sink.done(&outcome, started.elapsed()); |
| @@ -196,9 +219,6 @@ fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { | |||
| 196 | if let Some(usage) = &chunk.usage { | 219 | if let Some(usage) = &chunk.usage { |
| 197 | outcome.usage = Some(usage.clone()); | 220 | outcome.usage = Some(usage.clone()); |
| 198 | } | 221 | } |
| 199 | if let Some(opencode) = &chunk.opencode { | ||
| 200 | outcome.opencode = Some(opencode.clone()); | ||
| 201 | } | ||
| 202 | for choice in &chunk.choices { | 222 | for choice in &chunk.choices { |
| 203 | if let Some(r) = &choice.delta.reasoning_content { | 223 | if let Some(r) = &choice.delta.reasoning_content { |
| 204 | if !r.is_empty() { | 224 | if !r.is_empty() { |
| @@ -266,7 +286,7 @@ fn error_message(body: &str) -> String { | |||
| 266 | truncate(body.trim(), 500) | 286 | truncate(body.trim(), 500) |
| 267 | } | 287 | } |
| 268 | 288 | ||
| 269 | fn truncate(s: &str, max: usize) -> String { | 289 | pub fn truncate(s: &str, max: usize) -> String { |
| 270 | match s.char_indices().nth(max) { | 290 | match s.char_indices().nth(max) { |
| 271 | Some((i, _)) => format!("{}…", &s[..i]), | 291 | Some((i, _)) => format!("{}…", &s[..i]), |
| 272 | None => s.to_string(), | 292 | None => s.to_string(), |
| @@ -279,8 +299,6 @@ struct Chunk { | |||
| 279 | choices: Vec<Choice>, | 299 | choices: Vec<Choice>, |
| 280 | #[serde(default)] | 300 | #[serde(default)] |
| 281 | usage: Option<Value>, | 301 | usage: Option<Value>, |
| 282 | #[serde(default)] | ||
| 283 | opencode: Option<Value>, | ||
| 284 | } | 302 | } |
| 285 | 303 | ||
| 286 | #[derive(Debug, Deserialize)] | 304 | #[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 @@ | |||
| 1 | use std::fs::{File, OpenOptions}; | ||
| 1 | use std::hash::{Hash, Hasher}; | 2 | use std::hash::{Hash, Hasher}; |
| 2 | use std::io::Read; | 3 | use std::io::{BufRead, BufReader, Read, Write}; |
| 4 | use std::path::PathBuf; | ||
| 3 | use std::time::{SystemTime, UNIX_EPOCH}; | 5 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 4 | 6 | ||
| 7 | use serde_json::{json, Map, Value}; | ||
| 8 | |||
| 5 | /// A session id is opaque to the provider: it only has to be stable for the life | 9 | /// A session id is opaque to the provider: it only has to be stable for the life |
| 6 | /// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps | 10 | /// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps |
| 7 | /// it usable as a file name. | 11 | /// it usable as a file name. |
| 8 | pub fn new_id() -> String { | 12 | pub fn new_id() -> String { |
| 9 | let mut bytes = random_bytes(); | 13 | let mut bytes = random_bytes(); |
| 10 | // Put the creation time in the first bytes so ids sort roughly by age. | 14 | // Creation time first, so ids sort roughly by age. |
| 11 | let ms = SystemTime::now() | 15 | let ms = now_ms(); |
| 12 | .duration_since(UNIX_EPOCH) | ||
| 13 | .map(|d| d.as_millis() as u64) | ||
| 14 | .unwrap_or(0); | ||
| 15 | bytes[..8].copy_from_slice(&ms.to_be_bytes()); | 16 | bytes[..8].copy_from_slice(&ms.to_be_bytes()); |
| 16 | 17 | ||
| 17 | let mut out = String::with_capacity(32); | 18 | let mut out = String::with_capacity(32); |
| @@ -21,9 +22,176 @@ pub fn new_id() -> String { | |||
| 21 | out | 22 | out |
| 22 | } | 23 | } |
| 23 | 24 | ||
| 25 | pub fn now_ms() -> u64 { | ||
| 26 | SystemTime::now() | ||
| 27 | .duration_since(UNIX_EPOCH) | ||
| 28 | .map(|d| d.as_millis() as u64) | ||
| 29 | .unwrap_or(0) | ||
| 30 | } | ||
| 31 | |||
| 32 | pub fn data_root() -> PathBuf { | ||
| 33 | if let Some(dir) = std::env::var_os("AGENT686_DATA") { | ||
| 34 | return PathBuf::from(dir); | ||
| 35 | } | ||
| 36 | let home = std::env::var_os("HOME").unwrap_or_default(); | ||
| 37 | PathBuf::from(home).join(".local/share/agent686") | ||
| 38 | } | ||
| 39 | |||
| 40 | pub fn sessions_dir() -> PathBuf { | ||
| 41 | data_root().join("sessions") | ||
| 42 | } | ||
| 43 | |||
| 44 | pub struct Session { | ||
| 45 | pub id: String, | ||
| 46 | pub model: String, | ||
| 47 | path: PathBuf, | ||
| 48 | file: File, | ||
| 49 | } | ||
| 50 | |||
| 51 | impl Session { | ||
| 52 | pub fn create(model: &str, system: &Value) -> Result<Session, String> { | ||
| 53 | let id = new_id(); | ||
| 54 | let dir = sessions_dir(); | ||
| 55 | std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; | ||
| 56 | let path = dir.join(format!("{id}.jsonl")); | ||
| 57 | let mut file = OpenOptions::new() | ||
| 58 | .create_new(true) | ||
| 59 | .append(true) | ||
| 60 | .open(&path) | ||
| 61 | .map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 62 | |||
| 63 | let header = json!({ | ||
| 64 | "t": "header", | ||
| 65 | "session": id, | ||
| 66 | "model": model, | ||
| 67 | "created": now_ms(), | ||
| 68 | "system": system, | ||
| 69 | }); | ||
| 70 | writeln!(file, "{header}").map_err(|e| e.to_string())?; | ||
| 71 | file.flush().map_err(|e| e.to_string())?; | ||
| 72 | |||
| 73 | Ok(Session { | ||
| 74 | id, | ||
| 75 | model: model.to_string(), | ||
| 76 | path, | ||
| 77 | file, | ||
| 78 | }) | ||
| 79 | } | ||
| 80 | |||
| 81 | /// Rebuilds the wire history exactly as it was sent, plus the system message | ||
| 82 | /// that was frozen when the session started. | ||
| 83 | pub fn open(id: &str) -> Result<(Session, Value, Vec<Value>), String> { | ||
| 84 | let path = sessions_dir().join(format!("{id}.jsonl")); | ||
| 85 | let file = File::open(&path).map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 86 | let reader = BufReader::new(file.try_clone().map_err(|e| e.to_string())?); | ||
| 87 | |||
| 88 | let mut model = String::new(); | ||
| 89 | let mut system = Value::Null; | ||
| 90 | let mut session_id = id.to_string(); | ||
| 91 | let mut messages = Vec::new(); | ||
| 92 | |||
| 93 | for line in reader.lines() { | ||
| 94 | let line = line.map_err(|e| e.to_string())?; | ||
| 95 | if line.trim().is_empty() { | ||
| 96 | continue; | ||
| 97 | } | ||
| 98 | let value: Value = match serde_json::from_str(&line) { | ||
| 99 | Ok(v) => v, | ||
| 100 | // A torn last line is expected after kill -9; ignore it. | ||
| 101 | Err(_) => continue, | ||
| 102 | }; | ||
| 103 | match value.get("t").and_then(|t| t.as_str()) { | ||
| 104 | Some("header") => { | ||
| 105 | model = value | ||
| 106 | .get("model") | ||
| 107 | .and_then(|m| m.as_str()) | ||
| 108 | .unwrap_or_default() | ||
| 109 | .to_string(); | ||
| 110 | system = value.get("system").cloned().unwrap_or(Value::Null); | ||
| 111 | if let Some(s) = value.get("session").and_then(|s| s.as_str()) { | ||
| 112 | session_id = s.to_string(); | ||
| 113 | } | ||
| 114 | } | ||
| 115 | Some("msg") => { | ||
| 116 | let mut message = value.clone(); | ||
| 117 | if let Some(object) = message.as_object_mut() { | ||
| 118 | object.remove("t"); | ||
| 119 | object.remove("_reasoning"); | ||
| 120 | } | ||
| 121 | messages.push(message); | ||
| 122 | } | ||
| 123 | _ => {} | ||
| 124 | } | ||
| 125 | } | ||
| 126 | |||
| 127 | let file = OpenOptions::new() | ||
| 128 | .append(true) | ||
| 129 | .open(&path) | ||
| 130 | .map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 131 | |||
| 132 | Ok(( | ||
| 133 | Session { | ||
| 134 | id: session_id, | ||
| 135 | model, | ||
| 136 | path, | ||
| 137 | file, | ||
| 138 | }, | ||
| 139 | system, | ||
| 140 | messages, | ||
| 141 | )) | ||
| 142 | } | ||
| 143 | |||
| 144 | /// Append one wire message. `reasoning` is stored beside it for humans and | ||
| 145 | /// stripped on replay: sending it back is wasted tokens at best. | ||
| 146 | pub fn append(&mut self, message: &Value, reasoning: Option<&str>) -> Result<(), String> { | ||
| 147 | let mut line = match message.as_object() { | ||
| 148 | Some(object) => object.clone(), | ||
| 149 | None => Map::new(), | ||
| 150 | }; | ||
| 151 | line.insert("t".into(), json!("msg")); | ||
| 152 | if let Some(reasoning) = reasoning { | ||
| 153 | if !reasoning.is_empty() { | ||
| 154 | line.insert("_reasoning".into(), json!(reasoning)); | ||
| 155 | } | ||
| 156 | } | ||
| 157 | writeln!(self.file, "{}", Value::Object(line)).map_err(|e| e.to_string())?; | ||
| 158 | self.file.flush().map_err(|e| e.to_string()) | ||
| 159 | } | ||
| 160 | |||
| 161 | pub fn path(&self) -> &PathBuf { | ||
| 162 | &self.path | ||
| 163 | } | ||
| 164 | } | ||
| 165 | |||
| 166 | /// Most recently written session, for --continue. | ||
| 167 | pub fn latest() -> Result<Option<String>, String> { | ||
| 168 | let dir = sessions_dir(); | ||
| 169 | let entries = match std::fs::read_dir(&dir) { | ||
| 170 | Ok(entries) => entries, | ||
| 171 | Err(_) => return Ok(None), | ||
| 172 | }; | ||
| 173 | let mut newest: Option<(SystemTime, String)> = None; | ||
| 174 | for entry in entries.flatten() { | ||
| 175 | let path = entry.path(); | ||
| 176 | if path.extension().and_then(|e| e.to_str()) != Some("jsonl") { | ||
| 177 | continue; | ||
| 178 | } | ||
| 179 | let modified = entry | ||
| 180 | .metadata() | ||
| 181 | .and_then(|m| m.modified()) | ||
| 182 | .unwrap_or(UNIX_EPOCH); | ||
| 183 | if newest.as_ref().is_none_or(|(t, _)| modified > *t) { | ||
| 184 | if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { | ||
| 185 | newest = Some((modified, stem.to_string())); | ||
| 186 | } | ||
| 187 | } | ||
| 188 | } | ||
| 189 | Ok(newest.map(|(_, id)| id)) | ||
| 190 | } | ||
| 191 | |||
| 24 | fn random_bytes() -> [u8; 16] { | 192 | fn random_bytes() -> [u8; 16] { |
| 25 | let mut bytes = [0u8; 16]; | 193 | let mut bytes = [0u8; 16]; |
| 26 | if let Ok(mut f) = std::fs::File::open("/dev/urandom") { | 194 | if let Ok(mut f) = File::open("/dev/urandom") { |
| 27 | if f.read_exact(&mut bytes).is_ok() { | 195 | if f.read_exact(&mut bytes).is_ok() { |
| 28 | return bytes; | 196 | return bytes; |
| 29 | } | 197 | } |
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 @@ | |||
| 1 | use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 2 | |||
| 3 | /// Set by the first Ctrl-C. Cleared between turns. | ||
| 4 | pub static CANCEL: AtomicBool = AtomicBool::new(false); | ||
| 5 | |||
| 6 | extern "C" fn handler(_: libc::c_int) { | ||
| 7 | // First Ctrl-C aborts the turn. A second one is taken to mean "I really mean | ||
| 8 | // it" and leaves immediately; `_exit` is async-signal-safe, `exit` is not. | ||
| 9 | if CANCEL.swap(true, Ordering::SeqCst) { | ||
| 10 | unsafe { libc::_exit(130) } | ||
| 11 | } | ||
| 12 | } | ||
| 13 | |||
| 14 | pub fn install() { | ||
| 15 | let handler: extern "C" fn(libc::c_int) = handler; | ||
| 16 | unsafe { | ||
| 17 | libc::signal(libc::SIGINT, handler as libc::sighandler_t); | ||
| 18 | } | ||
| 19 | } | ||
| 20 | |||
| 21 | pub fn reset() { | ||
| 22 | CANCEL.store(false, Ordering::SeqCst); | ||
| 23 | } | ||
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 @@ | |||
| 1 | use std::fs; | ||
| 2 | use std::path::{Path, PathBuf}; | ||
| 3 | |||
| 4 | use serde_json::Value; | ||
| 5 | |||
| 6 | const MAX_LINE_CHARS: usize = 400; | ||
| 7 | const MAX_READ_LINES: usize = 2000; | ||
| 8 | const MAX_MATCHES: usize = 200; | ||
| 9 | const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; | ||
| 10 | const PREVIEW_BUDGET: usize = 60; | ||
| 11 | |||
| 12 | const SKIP_DIRS: &[&str] = &[ | ||
| 13 | ".git", | ||
| 14 | "target", | ||
| 15 | "node_modules", | ||
| 16 | "dist", | ||
| 17 | "build", | ||
| 18 | ".venv", | ||
| 19 | "vendor", | ||
| 20 | ".cache", | ||
| 21 | ]; | ||
| 22 | |||
| 23 | /// A pending file change. Built and previewed first, applied only after the | ||
| 24 | /// human agrees. | ||
| 25 | pub enum Change { | ||
| 26 | Write { path: String, content: String }, | ||
| 27 | Edit { path: String, old: String, new: String, text: String }, | ||
| 28 | } | ||
| 29 | |||
| 30 | impl Change { | ||
| 31 | pub fn path(&self) -> &str { | ||
| 32 | match self { | ||
| 33 | Change::Write { path, .. } | Change::Edit { path, .. } => path, | ||
| 34 | } | ||
| 35 | } | ||
| 36 | |||
| 37 | pub fn preview(&self) -> String { | ||
| 38 | match self { | ||
| 39 | Change::Write { path, content } => match fs::read_to_string(path) { | ||
| 40 | Ok(old) if old == *content => format!("{path}: unchanged"), | ||
| 41 | Ok(old) => diff_preview(&old, content), | ||
| 42 | Err(_) => new_file_preview(path, content), | ||
| 43 | }, | ||
| 44 | Change::Edit { | ||
| 45 | path, | ||
| 46 | old, | ||
| 47 | new, | ||
| 48 | text, | ||
| 49 | } => { | ||
| 50 | let at = text.find(old.as_str()).unwrap_or(0); | ||
| 51 | edit_preview(path, text, old, new, at) | ||
| 52 | } | ||
| 53 | } | ||
| 54 | } | ||
| 55 | |||
| 56 | pub fn apply(self) -> Result<String, String> { | ||
| 57 | match self { | ||
| 58 | Change::Write { path, content } => { | ||
| 59 | let parent = Path::new(&path).parent(); | ||
| 60 | if let Some(parent) = parent { | ||
| 61 | if !parent.as_os_str().is_empty() && !parent.is_dir() { | ||
| 62 | return Err(format!( | ||
| 63 | "parent directory does not exist: {} (create it with bash first)", | ||
| 64 | parent.display() | ||
| 65 | )); | ||
| 66 | } | ||
| 67 | } | ||
| 68 | fs::write(&path, &content).map_err(|e| format!("{path}: {e}"))?; | ||
| 69 | Ok(format!( | ||
| 70 | "wrote {} bytes ({} lines) to {path}", | ||
| 71 | content.len(), | ||
| 72 | content.lines().count() | ||
| 73 | )) | ||
| 74 | } | ||
| 75 | Change::Edit { | ||
| 76 | path, | ||
| 77 | old, | ||
| 78 | new, | ||
| 79 | mut text, | ||
| 80 | } => { | ||
| 81 | let at = text | ||
| 82 | .find(old.as_str()) | ||
| 83 | .ok_or_else(|| format!("{path}: text to replace disappeared"))?; | ||
| 84 | let line = text[..at].matches('\n').count() + 1; | ||
| 85 | text.replace_range(at..at + old.len(), &new); | ||
| 86 | fs::write(&path, &text).map_err(|e| format!("{path}: {e}"))?; | ||
| 87 | Ok(format!("edited {path}: 1 replacement at line {line}")) | ||
| 88 | } | ||
| 89 | } | ||
| 90 | } | ||
| 91 | } | ||
| 92 | |||
| 93 | pub fn plan_write(args: &Value) -> Result<Change, String> { | ||
| 94 | Ok(Change::Write { | ||
| 95 | path: req(args, "path")?, | ||
| 96 | content: req(args, "content")?, | ||
| 97 | }) | ||
| 98 | } | ||
| 99 | |||
| 100 | pub fn plan_edit(args: &Value) -> Result<Change, String> { | ||
| 101 | let path = req(args, "path")?; | ||
| 102 | let old = req(args, "old")?; | ||
| 103 | let new = req(args, "new")?; | ||
| 104 | if old.is_empty() { | ||
| 105 | return Err("`old` must not be empty; use write to create a file".into()); | ||
| 106 | } | ||
| 107 | let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; | ||
| 108 | let hits: Vec<usize> = text.match_indices(&old).map(|(i, _)| i).collect(); | ||
| 109 | match hits.len() { | ||
| 110 | 0 => Err(format!( | ||
| 111 | "text to replace was not found in {path}. Read the file and copy the exact \ | ||
| 112 | text, including indentation." | ||
| 113 | )), | ||
| 114 | 1 => Ok(Change::Edit { | ||
| 115 | path, | ||
| 116 | old, | ||
| 117 | new, | ||
| 118 | text, | ||
| 119 | }), | ||
| 120 | n => Err(format!( | ||
| 121 | "text to replace appears {n} times in {path} (lines {}); include more \ | ||
| 122 | surrounding context so it is unique.", | ||
| 123 | line_list(&text, &hits) | ||
| 124 | )), | ||
| 125 | } | ||
| 126 | } | ||
| 127 | |||
| 128 | pub fn read(args: &Value) -> Result<String, String> { | ||
| 129 | let path = req(args, "path")?; | ||
| 130 | let offset = args | ||
| 131 | .get("offset") | ||
| 132 | .and_then(|v| v.as_u64()) | ||
| 133 | .unwrap_or(1) | ||
| 134 | .max(1) as usize; | ||
| 135 | let limit = args | ||
| 136 | .get("limit") | ||
| 137 | .and_then(|v| v.as_u64()) | ||
| 138 | .unwrap_or(MAX_READ_LINES as u64) | ||
| 139 | .clamp(1, MAX_READ_LINES as u64) as usize; | ||
| 140 | |||
| 141 | let bytes = fs::read(&path).map_err(|e| format!("{path}: {e}"))?; | ||
| 142 | if bytes.iter().take(8192).any(|&b| b == 0) { | ||
| 143 | return Err(format!( | ||
| 144 | "{path}: looks like a binary file and will not be shown" | ||
| 145 | )); | ||
| 146 | } | ||
| 147 | let text = String::from_utf8_lossy(&bytes); | ||
| 148 | let lines: Vec<&str> = text.lines().collect(); | ||
| 149 | if lines.is_empty() { | ||
| 150 | return Ok(format!("{path}: empty file")); | ||
| 151 | } | ||
| 152 | if offset > lines.len() { | ||
| 153 | return Ok(format!( | ||
| 154 | "{path} has {} lines; offset {offset} is past the end", | ||
| 155 | lines.len() | ||
| 156 | )); | ||
| 157 | } | ||
| 158 | |||
| 159 | let end = (offset + limit - 1).min(lines.len()); | ||
| 160 | let mut out = String::with_capacity((end - offset + 2) * 40); | ||
| 161 | for number in offset..=end { | ||
| 162 | out.push_str(&format!( | ||
| 163 | "{number:>6}\t{}\n", | ||
| 164 | clip(lines[number - 1], MAX_LINE_CHARS) | ||
| 165 | )); | ||
| 166 | } | ||
| 167 | if end < lines.len() { | ||
| 168 | out.push_str(&format!( | ||
| 169 | "… {} more line(s); continue with offset={}\n", | ||
| 170 | lines.len() - end, | ||
| 171 | end + 1 | ||
| 172 | )); | ||
| 173 | } | ||
| 174 | Ok(out) | ||
| 175 | } | ||
| 176 | |||
| 177 | pub fn grep(args: &Value) -> Result<String, String> { | ||
| 178 | let pattern = req(args, "pattern")?; | ||
| 179 | if pattern.is_empty() { | ||
| 180 | return Err("pattern must not be empty".into()); | ||
| 181 | } | ||
| 182 | let base = args | ||
| 183 | .get("path") | ||
| 184 | .and_then(|v| v.as_str()) | ||
| 185 | .unwrap_or(".") | ||
| 186 | .to_string(); | ||
| 187 | let ignore_case = args | ||
| 188 | .get("ignore_case") | ||
| 189 | .and_then(|v| v.as_bool()) | ||
| 190 | .unwrap_or(false); | ||
| 191 | let needle = if ignore_case { | ||
| 192 | pattern.to_lowercase() | ||
| 193 | } else { | ||
| 194 | pattern.clone() | ||
| 195 | }; | ||
| 196 | |||
| 197 | let root = Path::new(&base); | ||
| 198 | let files = if root.is_file() { | ||
| 199 | vec![root.to_path_buf()] | ||
| 200 | } else { | ||
| 201 | let mut files = Vec::new(); | ||
| 202 | walk(root, &mut files); | ||
| 203 | files | ||
| 204 | }; | ||
| 205 | |||
| 206 | let mut out = String::new(); | ||
| 207 | let mut matches = 0usize; | ||
| 208 | for file in files { | ||
| 209 | if matches >= MAX_MATCHES { | ||
| 210 | break; | ||
| 211 | } | ||
| 212 | grep_file(&file, &needle, ignore_case, &mut matches, &mut out); | ||
| 213 | } | ||
| 214 | |||
| 215 | if matches == 0 { | ||
| 216 | return Ok(format!("no matches for `{pattern}` under {base}")); | ||
| 217 | } | ||
| 218 | if matches >= MAX_MATCHES { | ||
| 219 | out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n")); | ||
| 220 | } | ||
| 221 | Ok(out) | ||
| 222 | } | ||
| 223 | |||
| 224 | pub fn glob(args: &Value) -> Result<String, String> { | ||
| 225 | let pattern = req(args, "pattern")?; | ||
| 226 | let base = args | ||
| 227 | .get("path") | ||
| 228 | .and_then(|v| v.as_str()) | ||
| 229 | .unwrap_or(".") | ||
| 230 | .to_string(); | ||
| 231 | let root = Path::new(&base); | ||
| 232 | if !root.is_dir() { | ||
| 233 | return Err(format!("not a directory: {base}")); | ||
| 234 | } | ||
| 235 | |||
| 236 | let mut files = Vec::new(); | ||
| 237 | walk(root, &mut files); | ||
| 238 | |||
| 239 | // A pattern without a slash is matched against the file name at any depth. | ||
| 240 | let bare = !pattern.contains('/'); | ||
| 241 | let mut hits = Vec::new(); | ||
| 242 | for file in files { | ||
| 243 | let name = file.file_name().and_then(|n| n.to_str()).unwrap_or(""); | ||
| 244 | let hit = if bare { | ||
| 245 | wildcard_match(pattern.as_bytes(), name.as_bytes()) | ||
| 246 | } else { | ||
| 247 | let relative = file | ||
| 248 | .strip_prefix(root) | ||
| 249 | .unwrap_or(&file) | ||
| 250 | .to_string_lossy() | ||
| 251 | .to_string(); | ||
| 252 | glob_match(&pattern, &relative) | ||
| 253 | }; | ||
| 254 | if hit { | ||
| 255 | hits.push(file); | ||
| 256 | if hits.len() >= MAX_MATCHES { | ||
| 257 | break; | ||
| 258 | } | ||
| 259 | } | ||
| 260 | } | ||
| 261 | |||
| 262 | if hits.is_empty() { | ||
| 263 | return Ok(format!("no files match `{pattern}` under {base}")); | ||
| 264 | } | ||
| 265 | |||
| 266 | let mut out = String::new(); | ||
| 267 | for hit in &hits { | ||
| 268 | out.push_str(&hit.display().to_string()); | ||
| 269 | out.push('\n'); | ||
| 270 | } | ||
| 271 | if hits.len() >= MAX_MATCHES { | ||
| 272 | out.push_str(&format!("… stopped after {MAX_MATCHES} files\n")); | ||
| 273 | } | ||
| 274 | Ok(out) | ||
| 275 | } | ||
| 276 | |||
| 277 | fn grep_file(path: &Path, needle_lower: &str, ignore_case: bool, count: &mut usize, out: &mut String) { | ||
| 278 | let meta = match fs::metadata(path) { | ||
| 279 | Ok(m) => m, | ||
| 280 | Err(_) => return, | ||
| 281 | }; | ||
| 282 | if meta.len() > MAX_SCAN_BYTES { | ||
| 283 | return; | ||
| 284 | } | ||
| 285 | let bytes = match fs::read(path) { | ||
| 286 | Ok(b) => b, | ||
| 287 | Err(_) => return, | ||
| 288 | }; | ||
| 289 | if bytes.iter().take(8192).any(|&b| b == 0) { | ||
| 290 | return; | ||
| 291 | } | ||
| 292 | let text = String::from_utf8_lossy(&bytes); | ||
| 293 | let mut needle = needle_lower.to_string(); | ||
| 294 | if !ignore_case { | ||
| 295 | needle = needle.to_string(); | ||
| 296 | } | ||
| 297 | |||
| 298 | for (index, line) in text.lines().enumerate() { | ||
| 299 | if *count >= MAX_MATCHES { | ||
| 300 | return; | ||
| 301 | } | ||
| 302 | let hit = if ignore_case { | ||
| 303 | line.to_lowercase().contains(&needle) | ||
| 304 | } else { | ||
| 305 | line.contains(&needle) | ||
| 306 | }; | ||
| 307 | if hit { | ||
| 308 | *count += 1; | ||
| 309 | out.push_str(&format!( | ||
| 310 | "{}:{}: {}\n", | ||
| 311 | path.display(), | ||
| 312 | index + 1, | ||
| 313 | clip(line.trim_end(), 200) | ||
| 314 | )); | ||
| 315 | } | ||
| 316 | } | ||
| 317 | } | ||
| 318 | |||
| 319 | fn walk(dir: &Path, out: &mut Vec<PathBuf>) { | ||
| 320 | let entries = match fs::read_dir(dir) { | ||
| 321 | Ok(entries) => entries, | ||
| 322 | Err(_) => return, | ||
| 323 | }; | ||
| 324 | for entry in entries.flatten() { | ||
| 325 | let file_type = match entry.file_type() { | ||
| 326 | Ok(t) => t, | ||
| 327 | Err(_) => continue, | ||
| 328 | }; | ||
| 329 | let path = entry.path(); | ||
| 330 | if file_type.is_dir() { | ||
| 331 | let name = entry.file_name(); | ||
| 332 | if SKIP_DIRS.iter().any(|skip| name == *skip) { | ||
| 333 | continue; | ||
| 334 | } | ||
| 335 | walk(&path, out); | ||
| 336 | } else if file_type.is_file() { | ||
| 337 | out.push(path); | ||
| 338 | } | ||
| 339 | } | ||
| 340 | } | ||
| 341 | |||
| 342 | fn glob_match(pattern: &str, path: &str) -> bool { | ||
| 343 | let p: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect(); | ||
| 344 | let s: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); | ||
| 345 | match_segments(&p, &s) | ||
| 346 | } | ||
| 347 | |||
| 348 | fn match_segments(pattern: &[&str], path: &[&str]) -> bool { | ||
| 349 | match pattern.split_first() { | ||
| 350 | None => path.is_empty(), | ||
| 351 | Some((&"**", rest)) => { | ||
| 352 | if match_segments(rest, path) { | ||
| 353 | return true; | ||
| 354 | } | ||
| 355 | for skip in 0..path.len() { | ||
| 356 | if match_segments(rest, &path[skip + 1..]) { | ||
| 357 | return true; | ||
| 358 | } | ||
| 359 | } | ||
| 360 | false | ||
| 361 | } | ||
| 362 | Some((segment, rest)) => match path.split_first() { | ||
| 363 | None => false, | ||
| 364 | Some((name, tail)) => { | ||
| 365 | wildcard_match(segment.as_bytes(), name.as_bytes()) && match_segments(rest, tail) | ||
| 366 | } | ||
| 367 | }, | ||
| 368 | } | ||
| 369 | } | ||
| 370 | |||
| 371 | fn wildcard_match(pattern: &[u8], text: &[u8]) -> bool { | ||
| 372 | match pattern.split_first() { | ||
| 373 | None => text.is_empty(), | ||
| 374 | Some((&b'*', rest)) => (0..=text.len()).any(|skip| wildcard_match(rest, &text[skip..])), | ||
| 375 | Some((&b'?', rest)) => !text.is_empty() && wildcard_match(rest, &text[1..]), | ||
| 376 | Some((byte, rest)) => match text.split_first() { | ||
| 377 | Some((first, tail)) => first == byte && wildcard_match(rest, tail), | ||
| 378 | None => false, | ||
| 379 | }, | ||
| 380 | } | ||
| 381 | } | ||
| 382 | |||
| 383 | fn new_file_preview(path: &str, content: &str) -> String { | ||
| 384 | let lines: Vec<&str> = content.lines().collect(); | ||
| 385 | let mut out = format!("@@ new file {path} ({} lines) @@\n", lines.len()); | ||
| 386 | for line in lines.iter().take(PREVIEW_BUDGET) { | ||
| 387 | out.push_str(&format!("+ {}\n", clip(line, 200))); | ||
| 388 | } | ||
| 389 | if lines.len() > PREVIEW_BUDGET { | ||
| 390 | out.push_str(&format!("… {} more line(s)\n", lines.len() - PREVIEW_BUDGET)); | ||
| 391 | } | ||
| 392 | out | ||
| 393 | } | ||
| 394 | |||
| 395 | fn diff_preview(old: &str, new: &str) -> String { | ||
| 396 | let a: Vec<&str> = old.lines().collect(); | ||
| 397 | let b: Vec<&str> = new.lines().collect(); | ||
| 398 | |||
| 399 | let mut prefix = 0; | ||
| 400 | while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] { | ||
| 401 | prefix += 1; | ||
| 402 | } | ||
| 403 | let mut suffix = 0; | ||
| 404 | while suffix < a.len().saturating_sub(prefix) | ||
| 405 | && suffix < b.len().saturating_sub(prefix) | ||
| 406 | && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix] | ||
| 407 | { | ||
| 408 | suffix += 1; | ||
| 409 | } | ||
| 410 | |||
| 411 | let start = prefix.saturating_sub(2); | ||
| 412 | let a_end = a.len() - suffix; | ||
| 413 | let b_end = b.len() - suffix; | ||
| 414 | |||
| 415 | let mut out = format!( | ||
| 416 | "@@ -{},{} +{},{} @@\n", | ||
| 417 | start + 1, | ||
| 418 | a_end.saturating_sub(start), | ||
| 419 | start + 1, | ||
| 420 | b_end.saturating_sub(start) | ||
| 421 | ); | ||
| 422 | let mut budget = PREVIEW_BUDGET; | ||
| 423 | |||
| 424 | for line in &a[start..prefix] { | ||
| 425 | if budget == 0 { | ||
| 426 | break; | ||
| 427 | } | ||
| 428 | budget -= 1; | ||
| 429 | out.push_str(&format!(" {}\n", clip(line, 200))); | ||
| 430 | } | ||
| 431 | for line in &a[prefix..a_end] { | ||
| 432 | if budget == 0 { | ||
| 433 | break; | ||
| 434 | } | ||
| 435 | budget -= 1; | ||
| 436 | out.push_str(&format!("- {}\n", clip(line, 200))); | ||
| 437 | } | ||
| 438 | for line in &b[prefix..b_end] { | ||
| 439 | if budget == 0 { | ||
| 440 | break; | ||
| 441 | } | ||
| 442 | budget -= 1; | ||
| 443 | out.push_str(&format!("+ {}\n", clip(line, 200))); | ||
| 444 | } | ||
| 445 | for line in a[a_end..(a_end + 2).min(a.len())].iter() { | ||
| 446 | if budget == 0 { | ||
| 447 | break; | ||
| 448 | } | ||
| 449 | budget -= 1; | ||
| 450 | out.push_str(&format!(" {}\n", clip(line, 200))); | ||
| 451 | } | ||
| 452 | if budget == 0 { | ||
| 453 | out.push_str("… diff truncated\n"); | ||
| 454 | } | ||
| 455 | out | ||
| 456 | } | ||
| 457 | |||
| 458 | fn edit_preview(path: &str, text: &str, old: &str, new: &str, at: usize) -> String { | ||
| 459 | let lines: Vec<&str> = text.lines().collect(); | ||
| 460 | let line_no = text[..at].matches('\n').count() + 1; | ||
| 461 | let old_lines = old.lines().count().max(1); | ||
| 462 | |||
| 463 | let mut out = format!("@@ {path}:{line_no} @@\n"); | ||
| 464 | let mut budget = PREVIEW_BUDGET; | ||
| 465 | |||
| 466 | let before_start = (line_no - 1).saturating_sub(2); | ||
| 467 | for line in &lines[before_start..line_no.saturating_sub(1)] { | ||
| 468 | if budget == 0 { | ||
| 469 | break; | ||
| 470 | } | ||
| 471 | budget -= 1; | ||
| 472 | out.push_str(&format!(" {}\n", clip(line, 200))); | ||
| 473 | } | ||
| 474 | for line in old.lines() { | ||
| 475 | if budget == 0 { | ||
| 476 | break; | ||
| 477 | } | ||
| 478 | budget -= 1; | ||
| 479 | out.push_str(&format!("- {}\n", clip(line, 200))); | ||
| 480 | } | ||
| 481 | for line in new.lines() { | ||
| 482 | if budget == 0 { | ||
| 483 | break; | ||
| 484 | } | ||
| 485 | budget -= 1; | ||
| 486 | out.push_str(&format!("+ {}\n", clip(line, 200))); | ||
| 487 | } | ||
| 488 | let after_start = (line_no - 1 + old_lines).min(lines.len()); | ||
| 489 | for line in &lines[after_start..(after_start + 2).min(lines.len())] { | ||
| 490 | if budget == 0 { | ||
| 491 | break; | ||
| 492 | } | ||
| 493 | budget -= 1; | ||
| 494 | out.push_str(&format!(" {}\n", clip(line, 200))); | ||
| 495 | } | ||
| 496 | if budget == 0 { | ||
| 497 | out.push_str("… diff truncated\n"); | ||
| 498 | } | ||
| 499 | out | ||
| 500 | } | ||
| 501 | |||
| 502 | fn line_list(text: &str, offsets: &[usize]) -> String { | ||
| 503 | let mut numbers: Vec<String> = offsets | ||
| 504 | .iter() | ||
| 505 | .take(10) | ||
| 506 | .map(|&at| (text[..at].matches('\n').count() + 1).to_string()) | ||
| 507 | .collect(); | ||
| 508 | if offsets.len() > 10 { | ||
| 509 | numbers.push("…".into()); | ||
| 510 | } | ||
| 511 | numbers.join(", ") | ||
| 512 | } | ||
| 513 | |||
| 514 | fn req(args: &Value, key: &str) -> Result<String, String> { | ||
| 515 | match args.get(key).and_then(|v| v.as_str()) { | ||
| 516 | Some(value) => Ok(value.to_string()), | ||
| 517 | None => Err(format!("missing required argument `{key}`")), | ||
| 518 | } | ||
| 519 | } | ||
| 520 | |||
| 521 | fn clip(s: &str, max: usize) -> String { | ||
| 522 | if s.chars().count() <= max { | ||
| 523 | return s.to_string(); | ||
| 524 | } | ||
| 525 | let cut: String = s.chars().take(max).collect(); | ||
| 526 | format!("{cut}…") | ||
| 527 | } | ||
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 @@ | |||
| 1 | pub mod fs; | ||
| 2 | pub mod shell; | ||
| 3 | |||
| 4 | use serde_json::{json, Value}; | ||
| 5 | |||
| 6 | use fs::Change; | ||
| 7 | |||
| 8 | /// When a tool needs a human before it runs. | ||
| 9 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 10 | pub enum Approval { | ||
| 11 | /// Read-only or harmless. | ||
| 12 | Never, | ||
| 13 | /// Prompts on first use per session, then remembers. | ||
| 14 | Once, | ||
| 15 | /// Prompts on every call, no memory. | ||
| 16 | EveryCall, | ||
| 17 | } | ||
| 18 | |||
| 19 | pub fn approval(name: &str) -> Approval { | ||
| 20 | match name { | ||
| 21 | "write" | "edit" => Approval::Once, | ||
| 22 | "bash" => Approval::EveryCall, | ||
| 23 | _ => Approval::Never, | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | /// Tools that execute immediately. | ||
| 28 | pub fn run(name: &str, args: &Value) -> Result<String, String> { | ||
| 29 | match name { | ||
| 30 | "read" => fs::read(args), | ||
| 31 | "grep" => fs::grep(args), | ||
| 32 | "glob" => fs::glob(args), | ||
| 33 | "bash" => shell::bash(args, std::time::Duration::from_secs(120)), | ||
| 34 | other => Err(unknown(other)), | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | /// Tools that produce a change needing approval before it is applied. | ||
| 39 | pub fn plan(name: &str, args: &Value) -> Result<Change, String> { | ||
| 40 | match name { | ||
| 41 | "write" => fs::plan_write(args), | ||
| 42 | "edit" => fs::plan_edit(args), | ||
| 43 | other => Err(unknown(other)), | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | fn unknown(name: &str) -> String { | ||
| 48 | format!("unknown tool `{name}`; available: read, write, edit, bash, grep, glob") | ||
| 49 | } | ||
| 50 | |||
| 51 | /// Static and in a fixed order, so the serialised prefix never changes. | ||
| 52 | pub fn schemas() -> Vec<Value> { | ||
| 53 | vec![ | ||
| 54 | json!({ | ||
| 55 | "type": "function", | ||
| 56 | "function": { | ||
| 57 | "name": "read", | ||
| 58 | "description": "Read a text file. Returns numbered lines. Read before editing.", | ||
| 59 | "parameters": { | ||
| 60 | "type": "object", | ||
| 61 | "properties": { | ||
| 62 | "path": { "type": "string", "description": "file path" }, | ||
| 63 | "offset": { "type": "integer", "description": "first line, 1-based (default 1)" }, | ||
| 64 | "limit": { "type": "integer", "description": "maximum lines (default and cap 2000)" } | ||
| 65 | }, | ||
| 66 | "required": ["path"] | ||
| 67 | } | ||
| 68 | } | ||
| 69 | }), | ||
| 70 | json!({ | ||
| 71 | "type": "function", | ||
| 72 | "function": { | ||
| 73 | "name": "write", | ||
| 74 | "description": "Create or replace a whole file. The parent directory must already exist.", | ||
| 75 | "parameters": { | ||
| 76 | "type": "object", | ||
| 77 | "properties": { | ||
| 78 | "path": { "type": "string" }, | ||
| 79 | "content": { "type": "string" } | ||
| 80 | }, | ||
| 81 | "required": ["path", "content"] | ||
| 82 | } | ||
| 83 | } | ||
| 84 | }), | ||
| 85 | json!({ | ||
| 86 | "type": "function", | ||
| 87 | "function": { | ||
| 88 | "name": "edit", | ||
| 89 | "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.", | ||
| 90 | "parameters": { | ||
| 91 | "type": "object", | ||
| 92 | "properties": { | ||
| 93 | "path": { "type": "string" }, | ||
| 94 | "old": { "type": "string", "description": "exact existing text, including indentation" }, | ||
| 95 | "new": { "type": "string", "description": "replacement text" } | ||
| 96 | }, | ||
| 97 | "required": ["path", "old", "new"] | ||
| 98 | } | ||
| 99 | } | ||
| 100 | }), | ||
| 101 | json!({ | ||
| 102 | "type": "function", | ||
| 103 | "function": { | ||
| 104 | "name": "bash", | ||
| 105 | "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.", | ||
| 106 | "parameters": { | ||
| 107 | "type": "object", | ||
| 108 | "properties": { | ||
| 109 | "cmd": { "type": "string" }, | ||
| 110 | "cwd": { "type": "string", "description": "working directory (default: project root)" } | ||
| 111 | }, | ||
| 112 | "required": ["cmd"] | ||
| 113 | } | ||
| 114 | } | ||
| 115 | }), | ||
| 116 | json!({ | ||
| 117 | "type": "function", | ||
| 118 | "function": { | ||
| 119 | "name": "grep", | ||
| 120 | "description": "Search file contents for a literal string, recursively. Skips .git, target, node_modules and similar.", | ||
| 121 | "parameters": { | ||
| 122 | "type": "object", | ||
| 123 | "properties": { | ||
| 124 | "pattern": { "type": "string" }, | ||
| 125 | "path": { "type": "string", "description": "file or directory (default .)" }, | ||
| 126 | "ignore_case": { "type": "boolean" } | ||
| 127 | }, | ||
| 128 | "required": ["pattern"] | ||
| 129 | } | ||
| 130 | } | ||
| 131 | }), | ||
| 132 | json!({ | ||
| 133 | "type": "function", | ||
| 134 | "function": { | ||
| 135 | "name": "glob", | ||
| 136 | "description": "List files matching a glob. Supports *, ? and ** across path segments, e.g. **/*.rs.", | ||
| 137 | "parameters": { | ||
| 138 | "type": "object", | ||
| 139 | "properties": { | ||
| 140 | "pattern": { "type": "string" }, | ||
| 141 | "path": { "type": "string", "description": "directory to search (default .)" } | ||
| 142 | }, | ||
| 143 | "required": ["pattern"] | ||
| 144 | } | ||
| 145 | } | ||
| 146 | }), | ||
| 147 | ] | ||
| 148 | } | ||
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 @@ | |||
| 1 | use std::fs::File; | ||
| 2 | use std::io::{Read, Seek, SeekFrom}; | ||
| 3 | use std::path::PathBuf; | ||
| 4 | use std::process::{Command, Stdio}; | ||
| 5 | use std::sync::atomic::{AtomicU64, Ordering}; | ||
| 6 | use std::time::{Duration, Instant}; | ||
| 7 | |||
| 8 | use serde_json::Value; | ||
| 9 | |||
| 10 | const HEAD_BYTES: usize = 64 * 1024; | ||
| 11 | const TAIL_BYTES: i64 = 16 * 1024; | ||
| 12 | static COUNTER: AtomicU64 = AtomicU64::new(0); | ||
| 13 | |||
| 14 | pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> { | ||
| 15 | let cmd = match args.get("cmd").and_then(|v| v.as_str()) { | ||
| 16 | Some(cmd) => cmd.to_string(), | ||
| 17 | None => return Err("missing required argument `cmd`".into()), | ||
| 18 | }; | ||
| 19 | |||
| 20 | let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?; | ||
| 21 | if !cwd.is_dir() { | ||
| 22 | return Err(format!("cwd is not a directory: {}", cwd.display())); | ||
| 23 | } | ||
| 24 | |||
| 25 | let path = std::env::temp_dir().join(format!( | ||
| 26 | "agent686-{}-{}.out", | ||
| 27 | std::process::id(), | ||
| 28 | COUNTER.fetch_add(1, Ordering::Relaxed) | ||
| 29 | )); | ||
| 30 | let mut file = std::fs::OpenOptions::new() | ||
| 31 | .read(true) | ||
| 32 | .write(true) | ||
| 33 | .create(true) | ||
| 34 | .truncate(true) | ||
| 35 | .open(&path) | ||
| 36 | .map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 37 | let stdout = file.try_clone().map_err(|e| e.to_string())?; | ||
| 38 | let stderr = file.try_clone().map_err(|e| e.to_string())?; | ||
| 39 | |||
| 40 | let mut child = Command::new("sh") | ||
| 41 | .arg("-c") | ||
| 42 | .arg(&cmd) | ||
| 43 | .current_dir(&cwd) | ||
| 44 | .stdin(Stdio::null()) | ||
| 45 | .stdout(Stdio::from(stdout)) | ||
| 46 | .stderr(Stdio::from(stderr)) | ||
| 47 | .spawn() | ||
| 48 | .map_err(|e| format!("failed to start sh: {e}"))?; | ||
| 49 | |||
| 50 | let deadline = Instant::now() + timeout; | ||
| 51 | let mut timed_out = false; | ||
| 52 | let status = loop { | ||
| 53 | match child.try_wait().map_err(|e| e.to_string())? { | ||
| 54 | Some(status) => break status, | ||
| 55 | None => { | ||
| 56 | if Instant::now() >= deadline { | ||
| 57 | let _ = child.kill(); | ||
| 58 | timed_out = true; | ||
| 59 | break child.wait().map_err(|e| e.to_string())?; | ||
| 60 | } | ||
| 61 | std::thread::sleep(Duration::from_millis(20)); | ||
| 62 | } | ||
| 63 | } | ||
| 64 | }; | ||
| 65 | |||
| 66 | let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; | ||
| 67 | drop(file); | ||
| 68 | let _ = std::fs::remove_file(&path); | ||
| 69 | |||
| 70 | let mut out = output; | ||
| 71 | if !out.is_empty() && !out.ends_with('\n') { | ||
| 72 | out.push('\n'); | ||
| 73 | } | ||
| 74 | if timed_out { | ||
| 75 | out.push_str(&format!( | ||
| 76 | "[timed out after {:.1}s; process killed]", | ||
| 77 | timeout.as_secs_f64() | ||
| 78 | )); | ||
| 79 | } else { | ||
| 80 | match status.code() { | ||
| 81 | Some(code) => out.push_str(&format!("[exit {code}]")), | ||
| 82 | None => { | ||
| 83 | use std::os::unix::process::ExitStatusExt; | ||
| 84 | out.push_str(&format!( | ||
| 85 | "[killed by signal {}]", | ||
| 86 | status.signal().unwrap_or_default() | ||
| 87 | )); | ||
| 88 | } | ||
| 89 | } | ||
| 90 | } | ||
| 91 | Ok(out) | ||
| 92 | } | ||
| 93 | |||
| 94 | fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> { | ||
| 95 | let current = std::env::current_dir().map_err(|e| e.to_string())?; | ||
| 96 | Ok(match cwd { | ||
| 97 | Some(dir) => { | ||
| 98 | let path = PathBuf::from(dir); | ||
| 99 | if path.is_absolute() { | ||
| 100 | path | ||
| 101 | } else { | ||
| 102 | current.join(path) | ||
| 103 | } | ||
| 104 | } | ||
| 105 | None => current, | ||
| 106 | }) | ||
| 107 | } | ||
| 108 | |||
| 109 | fn read_capped(file: &mut File) -> Result<String, String> { | ||
| 110 | let len = file.metadata().map(|m| m.len()).unwrap_or(0); | ||
| 111 | file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; | ||
| 112 | |||
| 113 | let mut out = Vec::new(); | ||
| 114 | if len <= HEAD_BYTES as u64 { | ||
| 115 | file.read_to_end(&mut out).map_err(|e| e.to_string())?; | ||
| 116 | } else { | ||
| 117 | file.take(HEAD_BYTES as u64) | ||
| 118 | .read_to_end(&mut out) | ||
| 119 | .map_err(|e| e.to_string())?; | ||
| 120 | let omitted = len.saturating_sub(HEAD_BYTES as u64 + TAIL_BYTES as u64); | ||
| 121 | out.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); | ||
| 122 | file.seek(SeekFrom::End(-TAIL_BYTES)) | ||
| 123 | .map_err(|e| e.to_string())?; | ||
| 124 | let mut tail = Vec::new(); | ||
| 125 | file.read_to_end(&mut tail).map_err(|e| e.to_string())?; | ||
| 126 | out.extend_from_slice(&tail); | ||
| 127 | } | ||
| 128 | Ok(String::from_utf8_lossy(&out).into_owned()) | ||
| 129 | } | ||
| @@ -1,4 +1,5 @@ | |||
| 1 | use std::io::{IsTerminal, Write}; | 1 | use std::io::{IsTerminal, Write}; |
| 2 | use std::sync::OnceLock; | ||
| 2 | use std::time::Duration; | 3 | use std::time::Duration; |
| 3 | 4 | ||
| 4 | use crate::provider::{Outcome, Sink}; | 5 | use crate::provider::{Outcome, Sink}; |
| @@ -7,18 +8,33 @@ pub fn stdout_is_tty() -> bool { | |||
| 7 | std::io::stdout().is_terminal() | 8 | std::io::stdout().is_terminal() |
| 8 | } | 9 | } |
| 9 | 10 | ||
| 11 | pub fn stdin_is_tty() -> bool { | ||
| 12 | std::io::stdin().is_terminal() | ||
| 13 | } | ||
| 14 | |||
| 15 | fn color() -> bool { | ||
| 16 | static COLOR: OnceLock<bool> = OnceLock::new(); | ||
| 17 | *COLOR.get_or_init(stdout_is_tty) | ||
| 18 | } | ||
| 19 | |||
| 20 | fn paint(code: &str, text: &str) -> String { | ||
| 21 | if color() { | ||
| 22 | format!("\x1b[{code}m{text}\x1b[0m") | ||
| 23 | } else { | ||
| 24 | text.to_string() | ||
| 25 | } | ||
| 26 | } | ||
| 27 | |||
| 10 | /// Streams to stdout. Colour is used only when stdout is a terminal, so piping | 28 | /// Streams to stdout. Colour is used only when stdout is a terminal, so piping |
| 11 | /// the output somewhere gives clean text. | 29 | /// the output somewhere gives clean text. |
| 12 | pub struct Renderer { | 30 | pub struct Renderer { |
| 13 | color: bool, | ||
| 14 | dimmed: bool, | 31 | dimmed: bool, |
| 15 | wrote_text: bool, | 32 | wrote_text: bool, |
| 16 | } | 33 | } |
| 17 | 34 | ||
| 18 | impl Renderer { | 35 | impl Renderer { |
| 19 | pub fn new(color: bool) -> Self { | 36 | pub fn new() -> Self { |
| 20 | Self { | 37 | Self { |
| 21 | color, | ||
| 22 | dimmed: false, | 38 | dimmed: false, |
| 23 | wrote_text: false, | 39 | wrote_text: false, |
| 24 | } | 40 | } |
| @@ -41,7 +57,7 @@ impl Sink for Renderer { | |||
| 41 | } | 57 | } |
| 42 | 58 | ||
| 43 | fn reasoning(&mut self, s: &str) { | 59 | fn reasoning(&mut self, s: &str) { |
| 44 | if !self.color { | 60 | if !color() { |
| 45 | return; | 61 | return; |
| 46 | } | 62 | } |
| 47 | if !self.dimmed { | 63 | if !self.dimmed { |
| @@ -52,24 +68,147 @@ impl Sink for Renderer { | |||
| 52 | let _ = std::io::stdout().flush(); | 68 | let _ = std::io::stdout().flush(); |
| 53 | } | 69 | } |
| 54 | 70 | ||
| 55 | fn done(&mut self, outcome: &Outcome, elapsed: Duration) { | 71 | fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) { |
| 56 | self.undim(); | 72 | self.undim(); |
| 57 | if self.wrote_text { | 73 | if self.wrote_text { |
| 58 | println!(); | 74 | println!(); |
| 75 | self.wrote_text = false; | ||
| 76 | } | ||
| 77 | } | ||
| 78 | } | ||
| 79 | |||
| 80 | pub fn tool_line(name: &str, args: &serde_json::Value) { | ||
| 81 | let detail = match name { | ||
| 82 | "bash" => args | ||
| 83 | .get("cmd") | ||
| 84 | .and_then(|v| v.as_str()) | ||
| 85 | .unwrap_or("") | ||
| 86 | .to_string(), | ||
| 87 | "grep" => format!( | ||
| 88 | "{} in {}", | ||
| 89 | args.get("pattern").and_then(|v| v.as_str()).unwrap_or(""), | ||
| 90 | args.get("path").and_then(|v| v.as_str()).unwrap_or(".") | ||
| 91 | ), | ||
| 92 | "glob" => args | ||
| 93 | .get("pattern") | ||
| 94 | .and_then(|v| v.as_str()) | ||
| 95 | .unwrap_or("") | ||
| 96 | .to_string(), | ||
| 97 | _ => args | ||
| 98 | .get("path") | ||
| 99 | .and_then(|v| v.as_str()) | ||
| 100 | .unwrap_or("") | ||
| 101 | .to_string(), | ||
| 102 | }; | ||
| 103 | println!("{} {}", paint("1;36", &format!("● {name}")), detail); | ||
| 104 | let _ = std::io::stdout().flush(); | ||
| 105 | } | ||
| 106 | |||
| 107 | pub fn tool_result(result: &Result<String, String>) { | ||
| 108 | let text = match result { | ||
| 109 | Ok(output) => output, | ||
| 110 | Err(error) => error, | ||
| 111 | }; | ||
| 112 | let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or(""); | ||
| 113 | let summary = crate::provider::truncate(first.trim(), 100); | ||
| 114 | println!(" {} {}", paint("2", "└"), paint("2", &summary)); | ||
| 115 | let _ = std::io::stdout().flush(); | ||
| 116 | } | ||
| 117 | |||
| 118 | pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome) { | ||
| 119 | let mut parts = vec![ | ||
| 120 | if steps == 1 { | ||
| 121 | "1 step".to_string() | ||
| 122 | } else { | ||
| 123 | format!("{steps} steps") | ||
| 124 | }, | ||
| 125 | format!("{:.1}s", elapsed.as_secs_f64()), | ||
| 126 | ]; | ||
| 127 | let (input, output) = outcome.tokens(); | ||
| 128 | if let (Some(i), Some(o)) = (input, output) { | ||
| 129 | parts.push(format!("{i} in · {o} out")); | ||
| 130 | } | ||
| 131 | if let Some(allowance) = outcome.allowance() { | ||
| 132 | if allowance > 0.0 { | ||
| 133 | parts.push(format!("${allowance:.6}")); | ||
| 134 | } | ||
| 135 | } | ||
| 136 | println!("{}", paint("2", &format!("─ {}", parts.join(" · ")))); | ||
| 137 | let _ = std::io::stdout().flush(); | ||
| 138 | } | ||
| 139 | |||
| 140 | #[derive(Debug, PartialEq, Eq, Clone, Copy)] | ||
| 141 | pub enum Answer { | ||
| 142 | No, | ||
| 143 | Yes, | ||
| 144 | Always, | ||
| 145 | } | ||
| 146 | |||
| 147 | pub struct Approver { | ||
| 148 | yolo: bool, | ||
| 149 | interactive: bool, | ||
| 150 | edits_allowed: bool, | ||
| 151 | } | ||
| 152 | |||
| 153 | impl Approver { | ||
| 154 | pub fn new(yolo: bool) -> Self { | ||
| 155 | Self { | ||
| 156 | yolo, | ||
| 157 | interactive: stdin_is_tty(), | ||
| 158 | edits_allowed: false, | ||
| 159 | } | ||
| 160 | } | ||
| 161 | |||
| 162 | pub fn yolo(&self) -> bool { | ||
| 163 | self.yolo | ||
| 164 | } | ||
| 165 | |||
| 166 | fn ask(&self, question: &str) -> Answer { | ||
| 167 | if self.yolo { | ||
| 168 | return Answer::Yes; | ||
| 169 | } | ||
| 170 | if !self.interactive { | ||
| 171 | println!( | ||
| 172 | "{}", | ||
| 173 | paint("33", " no terminal to ask; denied (use --yolo to allow)") | ||
| 174 | ); | ||
| 175 | return Answer::No; | ||
| 59 | } | 176 | } |
| 60 | let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())]; | 177 | print!("\n{} {} ", question, paint("2", "[y/N/a]")); |
| 61 | if let Some(usage) = &outcome.usage { | 178 | let _ = std::io::stdout().flush(); |
| 62 | let input = usage.get("prompt_tokens").and_then(|v| v.as_u64()); | 179 | |
| 63 | let output = usage.get("completion_tokens").and_then(|v| v.as_u64()); | 180 | let mut line = String::new(); |
| 64 | if let (Some(i), Some(o)) = (input, output) { | 181 | if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 { |
| 65 | parts.push(format!("{i} in · {o} out")); | 182 | return Answer::No; |
| 183 | } | ||
| 184 | match line.trim().to_ascii_lowercase().as_str() { | ||
| 185 | "y" | "yes" => Answer::Yes, | ||
| 186 | "a" | "always" => Answer::Always, | ||
| 187 | _ => Answer::No, | ||
| 188 | } | ||
| 189 | } | ||
| 190 | |||
| 191 | /// One prompt for the first edit of a session, then silent. | ||
| 192 | pub fn allow_edit(&mut self, path: &str, preview: &str) -> bool { | ||
| 193 | if self.yolo || self.edits_allowed { | ||
| 194 | return true; | ||
| 195 | } | ||
| 196 | println!("{preview}"); | ||
| 197 | match self.ask(&format!("apply this change to {path}?")) { | ||
| 198 | Answer::Yes => true, | ||
| 199 | Answer::Always => { | ||
| 200 | self.edits_allowed = true; | ||
| 201 | true | ||
| 66 | } | 202 | } |
| 203 | Answer::No => false, | ||
| 67 | } | 204 | } |
| 68 | let line = format!("─ {}", parts.join(" · ")); | 205 | } |
| 69 | if self.color { | 206 | |
| 70 | println!("\x1b[2m{line}\x1b[0m"); | 207 | /// Every call, no memory: the point is seeing the command. |
| 71 | } else { | 208 | pub fn allow_bash(&mut self, cmd: &str) -> bool { |
| 72 | println!("{line}"); | 209 | if self.yolo { |
| 210 | return true; | ||
| 73 | } | 211 | } |
| 212 | self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200))) == Answer::Yes | ||
| 74 | } | 213 | } |
| 75 | } | 214 | } |
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 @@ | |||
| 1 | use std::fs; | ||
| 2 | use std::io::{BufRead, BufReader, Read, Write}; | ||
| 3 | use std::net::TcpListener; | ||
| 4 | use std::path::PathBuf; | ||
| 5 | use std::sync::atomic::AtomicBool; | ||
| 6 | use std::thread; | ||
| 7 | |||
| 8 | use serde_json::json; | ||
| 9 | |||
| 10 | use agent686::agent; | ||
| 11 | use agent686::config::Config; | ||
| 12 | use agent686::session::Session; | ||
| 13 | use agent686::ui::Approver; | ||
| 14 | |||
| 15 | fn sse(body: &str) -> String { | ||
| 16 | format!( | ||
| 17 | "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{body}" | ||
| 18 | ) | ||
| 19 | } | ||
| 20 | |||
| 21 | /// Serves one canned SSE response per connection, in order. | ||
| 22 | fn serve_sequence(responses: Vec<String>) -> String { | ||
| 23 | let listener = TcpListener::bind("127.0.0.1:0").unwrap(); | ||
| 24 | let addr = listener.local_addr().unwrap(); | ||
| 25 | thread::spawn(move || { | ||
| 26 | for response in responses { | ||
| 27 | let (mut stream, _) = listener.accept().unwrap(); | ||
| 28 | let mut reader = BufReader::new(stream.try_clone().unwrap()); | ||
| 29 | let mut length = 0usize; | ||
| 30 | loop { | ||
| 31 | let mut line = String::new(); | ||
| 32 | if reader.read_line(&mut line).unwrap_or(0) == 0 { | ||
| 33 | break; | ||
| 34 | } | ||
| 35 | if line == "\r\n" || line == "\n" { | ||
| 36 | break; | ||
| 37 | } | ||
| 38 | if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { | ||
| 39 | length = value.trim().parse().unwrap_or(0); | ||
| 40 | } | ||
| 41 | } | ||
| 42 | let mut body = vec![0u8; length]; | ||
| 43 | let _ = reader.read_exact(&mut body); | ||
| 44 | let _ = stream.write_all(response.as_bytes()); | ||
| 45 | let _ = stream.flush(); | ||
| 46 | } | ||
| 47 | }); | ||
| 48 | format!("http://{addr}") | ||
| 49 | } | ||
| 50 | |||
| 51 | fn temp_dir(tag: &str) -> PathBuf { | ||
| 52 | let dir = std::env::temp_dir().join(format!("agent686-loop-{tag}-{}", std::process::id())); | ||
| 53 | let _ = fs::remove_dir_all(&dir); | ||
| 54 | fs::create_dir_all(&dir).unwrap(); | ||
| 55 | dir | ||
| 56 | } | ||
| 57 | |||
| 58 | #[test] | ||
| 59 | fn runs_a_tool_call_then_finishes_and_records_every_message() { | ||
| 60 | let dir = temp_dir("write"); | ||
| 61 | let target = dir.join("hello.txt"); | ||
| 62 | let arguments = json!({ | ||
| 63 | "path": target.display().to_string(), | ||
| 64 | "content": "hello from the mock\n" | ||
| 65 | }) | ||
| 66 | .to_string(); | ||
| 67 | |||
| 68 | let tool_round = sse(&format!( | ||
| 69 | "data: {}\n\ndata: [DONE]\n\n", | ||
| 70 | json!({ | ||
| 71 | "choices": [{ | ||
| 72 | "delta": { "tool_calls": [{ | ||
| 73 | "index": 0, | ||
| 74 | "id": "call_1", | ||
| 75 | "function": { "name": "write", "arguments": arguments } | ||
| 76 | }]}, | ||
| 77 | "finish_reason": "tool_calls" | ||
| 78 | }] | ||
| 79 | }) | ||
| 80 | )); | ||
| 81 | let final_round = sse( | ||
| 82 | "data: {\"choices\":[{\"delta\":{\"content\":\"done\"},\"finish_reason\":\"stop\"}]}\n\n\ | ||
| 83 | data: [DONE]\n\n", | ||
| 84 | ); | ||
| 85 | |||
| 86 | let base = serve_sequence(vec![tool_round, final_round]); | ||
| 87 | |||
| 88 | std::env::set_var("AGENT686_DATA", dir.join("data")); | ||
| 89 | |||
| 90 | let system = agent::system_prompt(); | ||
| 91 | let mut session = Session::create("test-model", &system).unwrap(); | ||
| 92 | let cfg = Config { | ||
| 93 | base_url: base, | ||
| 94 | api_key: "test-key".into(), | ||
| 95 | model: "test-model".into(), | ||
| 96 | session: session.id.clone(), | ||
| 97 | yolo: true, | ||
| 98 | }; | ||
| 99 | let mut history = agent::new_history(system); | ||
| 100 | let mut approver = Approver::new(true); | ||
| 101 | |||
| 102 | agent::run_turn( | ||
| 103 | &cfg, | ||
| 104 | &mut session, | ||
| 105 | &mut history, | ||
| 106 | "write a file", | ||
| 107 | &AtomicBool::new(false), | ||
| 108 | &mut approver, | ||
| 109 | ) | ||
| 110 | .expect("turn should complete"); | ||
| 111 | |||
| 112 | assert_eq!( | ||
| 113 | fs::read_to_string(&target).unwrap(), | ||
| 114 | "hello from the mock\n" | ||
| 115 | ); | ||
| 116 | |||
| 117 | // system, user, assistant(tool_calls), tool result, assistant(final) | ||
| 118 | assert_eq!(history.len(), 5); | ||
| 119 | assert_eq!(history[3]["role"], "tool"); | ||
| 120 | assert_eq!(history[3]["tool_call_id"], "call_1"); | ||
| 121 | |||
| 122 | let log = fs::read_to_string(session.path()).unwrap(); | ||
| 123 | let lines: Vec<&str> = log.lines().collect(); | ||
| 124 | assert_eq!(lines.len(), 5, "header plus four messages: {log}"); | ||
| 125 | assert!(lines[0].contains("\"t\":\"header\"")); | ||
| 126 | assert_eq!(lines[3].contains("\"role\":\"tool\""), true); | ||
| 127 | } | ||
| 128 | |||
| 129 | #[test] | ||
| 130 | fn a_denied_tool_call_is_returned_as_data() { | ||
| 131 | let dir = temp_dir("denied"); | ||
| 132 | let target = dir.join("never.txt"); | ||
| 133 | let arguments = json!({ | ||
| 134 | "path": target.display().to_string(), | ||
| 135 | "content": "should not exist" | ||
| 136 | }) | ||
| 137 | .to_string(); | ||
| 138 | |||
| 139 | let tool_round = sse(&format!( | ||
| 140 | "data: {}\n\ndata: [DONE]\n\n", | ||
| 141 | json!({ | ||
| 142 | "choices": [{ | ||
| 143 | "delta": { "tool_calls": [{ | ||
| 144 | "index": 0, | ||
| 145 | "id": "call_1", | ||
| 146 | "function": { "name": "write", "arguments": arguments } | ||
| 147 | }]}, | ||
| 148 | "finish_reason": "tool_calls" | ||
| 149 | }] | ||
| 150 | }) | ||
| 151 | )); | ||
| 152 | let final_round = sse( | ||
| 153 | "data: {\"choices\":[{\"delta\":{\"content\":\"understood\"},\"finish_reason\":\"stop\"}]}\n\n\ | ||
| 154 | data: [DONE]\n\n", | ||
| 155 | ); | ||
| 156 | |||
| 157 | let base = serve_sequence(vec![tool_round, final_round]); | ||
| 158 | std::env::set_var("AGENT686_DATA", dir.join("data")); | ||
| 159 | |||
| 160 | let system = agent::system_prompt(); | ||
| 161 | let mut session = Session::create("test-model", &system).unwrap(); | ||
| 162 | let cfg = Config { | ||
| 163 | base_url: base, | ||
| 164 | api_key: "test-key".into(), | ||
| 165 | model: "test-model".into(), | ||
| 166 | session: session.id.clone(), | ||
| 167 | yolo: false, | ||
| 168 | }; | ||
| 169 | let mut history = agent::new_history(system); | ||
| 170 | // Not a terminal, so the approver must deny rather than block. | ||
| 171 | let mut approver = Approver::new(false); | ||
| 172 | |||
| 173 | agent::run_turn( | ||
| 174 | &cfg, | ||
| 175 | &mut session, | ||
| 176 | &mut history, | ||
| 177 | "write a file", | ||
| 178 | &AtomicBool::new(false), | ||
| 179 | &mut approver, | ||
| 180 | ) | ||
| 181 | .expect("a denial is not a failed turn"); | ||
| 182 | |||
| 183 | assert!(!target.exists()); | ||
| 184 | assert_eq!(history[3]["role"], "tool"); | ||
| 185 | assert!( | ||
| 186 | history[3]["content"] | ||
| 187 | .as_str() | ||
| 188 | .unwrap() | ||
| 189 | .contains("denied by the user") | ||
| 190 | ); | ||
| 191 | assert_eq!(history[4]["content"], "understood"); | ||
| 192 | } | ||
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 { | |||
| 73 | api_key: "test-key".into(), | 73 | api_key: "test-key".into(), |
| 74 | model: "test-model".into(), | 74 | model: "test-model".into(), |
| 75 | session: "testsession".into(), | 75 | session: "testsession".into(), |
| 76 | yolo: true, | ||
| 76 | } | 77 | } |
| 77 | } | 78 | } |
| 78 | 79 | ||
| @@ -94,6 +95,7 @@ fn streams_text_reasoning_and_usage() { | |||
| 94 | let outcome = provider::chat( | 95 | let outcome = provider::chat( |
| 95 | &config(base), | 96 | &config(base), |
| 96 | &[json!({ "role": "user", "content": "hi" })], | 97 | &[json!({ "role": "user", "content": "hi" })], |
| 98 | &[], | ||
| 97 | &AtomicBool::new(false), | 99 | &AtomicBool::new(false), |
| 98 | &mut sink, | 100 | &mut sink, |
| 99 | ) | 101 | ) |
| @@ -133,6 +135,7 @@ fn assembles_tool_call_arguments_byte_for_byte() { | |||
| 133 | let outcome = provider::chat( | 135 | let outcome = provider::chat( |
| 134 | &config(base), | 136 | &config(base), |
| 135 | &[json!({ "role": "user", "content": "read a.txt" })], | 137 | &[json!({ "role": "user", "content": "read a.txt" })], |
| 138 | &[], | ||
| 136 | &AtomicBool::new(false), | 139 | &AtomicBool::new(false), |
| 137 | &mut sink, | 140 | &mut sink, |
| 138 | ) | 141 | ) |
| @@ -161,6 +164,7 @@ fn surfaces_provider_error_text() { | |||
| 161 | let error = provider::chat( | 164 | let error = provider::chat( |
| 162 | &config(base), | 165 | &config(base), |
| 163 | &[json!({ "role": "user", "content": "hi" })], | 166 | &[json!({ "role": "user", "content": "hi" })], |
| 167 | &[], | ||
| 164 | &AtomicBool::new(false), | 168 | &AtomicBool::new(false), |
| 165 | &mut sink, | 169 | &mut sink, |
| 166 | ) | 170 | ) |
| @@ -184,6 +188,7 @@ fn honours_a_cancelled_turn() { | |||
| 184 | let error = provider::chat( | 188 | let error = provider::chat( |
| 185 | &config(base), | 189 | &config(base), |
| 186 | &[json!({ "role": "user", "content": "hi" })], | 190 | &[json!({ "role": "user", "content": "hi" })], |
| 191 | &[], | ||
| 187 | &AtomicBool::new(true), | 192 | &AtomicBool::new(true), |
| 188 | &mut sink, | 193 | &mut sink, |
| 189 | ) | 194 | ) |
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 @@ | |||
| 1 | use std::fs; | ||
| 2 | use std::path::PathBuf; | ||
| 3 | use std::time::Duration; | ||
| 4 | |||
| 5 | use serde_json::json; | ||
| 6 | |||
| 7 | use agent686::tools::{self, shell}; | ||
| 8 | |||
| 9 | fn temp_dir(tag: &str) -> PathBuf { | ||
| 10 | let dir = std::env::temp_dir().join(format!("agent686-test-{tag}-{}", std::process::id())); | ||
| 11 | let _ = fs::remove_dir_all(&dir); | ||
| 12 | fs::create_dir_all(&dir).unwrap(); | ||
| 13 | dir | ||
| 14 | } | ||
| 15 | |||
| 16 | #[test] | ||
| 17 | fn edit_refuses_ambiguous_and_missing_text() { | ||
| 18 | let dir = temp_dir("edit-ambiguous"); | ||
| 19 | let path = dir.join("a.txt"); | ||
| 20 | fs::write(&path, "alpha\nbeta\nalpha\n").unwrap(); | ||
| 21 | |||
| 22 | let error = tools::plan("edit", &json!({ "path": path, "old": "alpha", "new": "gamma" })) | ||
| 23 | .err() | ||
| 24 | .expect("ambiguous edit must fail"); | ||
| 25 | assert!(error.contains("appears 2 times"), "{error}"); | ||
| 26 | assert!(error.contains("lines 1, 3"), "{error}"); | ||
| 27 | |||
| 28 | let error = tools::plan("edit", &json!({ "path": path, "old": "nope", "new": "x" })) | ||
| 29 | .err() | ||
| 30 | .expect("missing text must fail"); | ||
| 31 | assert!(error.contains("was not found"), "{error}"); | ||
| 32 | |||
| 33 | // The file is untouched by a refused plan. | ||
| 34 | assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta\nalpha\n"); | ||
| 35 | } | ||
| 36 | |||
| 37 | #[test] | ||
| 38 | fn edit_applies_exactly_one_replacement() { | ||
| 39 | let dir = temp_dir("edit-apply"); | ||
| 40 | let path = dir.join("main.c"); | ||
| 41 | fs::write(&path, "int main(void) {\n return 0;\n}\n").unwrap(); | ||
| 42 | |||
| 43 | let change = tools::plan( | ||
| 44 | "edit", | ||
| 45 | &json!({ "path": path, "old": " return 0;", "new": " return 1;" }), | ||
| 46 | ) | ||
| 47 | .expect("unique edit should plan"); | ||
| 48 | |||
| 49 | let preview = change.preview(); | ||
| 50 | assert!(preview.contains("- return 0;"), "{preview}"); | ||
| 51 | assert!(preview.contains("+ return 1;"), "{preview}"); | ||
| 52 | |||
| 53 | let outcome = change.apply().expect("apply should succeed"); | ||
| 54 | assert!(outcome.contains("1 replacement at line 2"), "{outcome}"); | ||
| 55 | assert_eq!( | ||
| 56 | fs::read_to_string(&path).unwrap(), | ||
| 57 | "int main(void) {\n return 1;\n}\n" | ||
| 58 | ); | ||
| 59 | } | ||
| 60 | |||
| 61 | #[test] | ||
| 62 | fn write_does_not_create_parent_directories() { | ||
| 63 | let dir = temp_dir("write-parent"); | ||
| 64 | let path = dir.join("missing").join("file.txt"); | ||
| 65 | let change = tools::plan("write", &json!({ "path": path, "content": "hi" })).unwrap(); | ||
| 66 | let error = change.apply().err().expect("apply must fail"); | ||
| 67 | assert!(error.contains("parent directory does not exist"), "{error}"); | ||
| 68 | } | ||
| 69 | |||
| 70 | #[test] | ||
| 71 | fn read_numbers_lines_and_reports_truncation() { | ||
| 72 | let dir = temp_dir("read"); | ||
| 73 | let path = dir.join("f.txt"); | ||
| 74 | fs::write(&path, "one\ntwo\nthree\nfour\n").unwrap(); | ||
| 75 | |||
| 76 | let text = tools::run("read", &json!({ "path": path, "limit": 2 })).unwrap(); | ||
| 77 | assert!(text.contains(" 1\tone"), "{text}"); | ||
| 78 | assert!(text.contains(" 2\ttwo"), "{text}"); | ||
| 79 | assert!(text.contains("2 more line(s); continue with offset=3"), "{text}"); | ||
| 80 | assert!(!text.contains("three"), "{text}"); | ||
| 81 | } | ||
| 82 | |||
| 83 | #[test] | ||
| 84 | fn grep_finds_lines_and_honours_case() { | ||
| 85 | let dir = temp_dir("grep"); | ||
| 86 | let path = dir.join("f.txt"); | ||
| 87 | fs::write(&path, "alpha\nbeta\nALPHA\n").unwrap(); | ||
| 88 | |||
| 89 | let text = tools::run("grep", &json!({ "pattern": "alpha", "path": dir })).unwrap(); | ||
| 90 | assert_eq!(text.lines().count(), 1, "{text}"); | ||
| 91 | |||
| 92 | let text = tools::run( | ||
| 93 | "grep", | ||
| 94 | &json!({ "pattern": "alpha", "path": dir, "ignore_case": true }), | ||
| 95 | ) | ||
| 96 | .unwrap(); | ||
| 97 | assert_eq!(text.lines().count(), 2, "{text}"); | ||
| 98 | } | ||
| 99 | |||
| 100 | #[test] | ||
| 101 | fn glob_supports_double_star_and_bare_names() { | ||
| 102 | let dir = temp_dir("glob"); | ||
| 103 | fs::create_dir_all(dir.join("sub/deep")).unwrap(); | ||
| 104 | fs::write(dir.join("a.rs"), "").unwrap(); | ||
| 105 | fs::write(dir.join("sub/b.rs"), "").unwrap(); | ||
| 106 | fs::write(dir.join("sub/deep/c.rs"), "").unwrap(); | ||
| 107 | fs::write(dir.join("sub/note.txt"), "").unwrap(); | ||
| 108 | |||
| 109 | let text = tools::run("glob", &json!({ "pattern": "**/*.rs", "path": dir })).unwrap(); | ||
| 110 | assert_eq!(text.lines().count(), 3, "{text}"); | ||
| 111 | |||
| 112 | let text = tools::run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap(); | ||
| 113 | assert_eq!(text.lines().count(), 3, "{text}"); | ||
| 114 | |||
| 115 | let text = tools::run("glob", &json!({ "pattern": "sub/*.rs", "path": dir })).unwrap(); | ||
| 116 | assert_eq!(text.lines().count(), 1, "{text}"); | ||
| 117 | assert!(text.contains("b.rs"), "{text}"); | ||
| 118 | } | ||
| 119 | |||
| 120 | #[test] | ||
| 121 | fn bash_reports_exit_code_and_times_out() { | ||
| 122 | let text = tools::run("bash", &json!({ "cmd": "echo hi; exit 3" })).unwrap(); | ||
| 123 | assert!(text.contains("hi"), "{text}"); | ||
| 124 | assert!(text.contains("[exit 3]"), "{text}"); | ||
| 125 | |||
| 126 | let text = shell::bash(&json!({ "cmd": "sleep 5" }), Duration::from_millis(150)).unwrap(); | ||
| 127 | assert!(text.contains("timed out after"), "{text}"); | ||
| 128 | } | ||
| 129 | |||
| 130 | #[test] | ||
| 131 | fn bash_rejects_a_missing_cwd() { | ||
| 132 | let error = tools::run("bash", &json!({ "cmd": "true", "cwd": "/nonexistent-dir-xyz" })) | ||
| 133 | .err() | ||
| 134 | .expect("missing cwd must fail"); | ||
| 135 | assert!(error.contains("cwd is not a directory"), "{error}"); | ||
| 136 | } | ||
| 137 | |||
| 138 | #[test] | ||
| 139 | fn unknown_tool_is_an_error_not_a_panic() { | ||
| 140 | let error = tools::run("teleport", &json!({})).err().unwrap(); | ||
| 141 | assert!(error.contains("unknown tool"), "{error}"); | ||
| 142 | } | ||
