From 7175543e00caa9ce35487fa7f8b1b479c1ba00a2 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 02:54:21 +0100 Subject: M0: streaming provider, SSE decoder, mock provider, i686 build gate --- .gitignore | 1 + CONTEXT.md | 30 +++ Cargo.lock | 437 ++++++++++++++++++++++++++++++++++ Cargo.toml | 16 ++ docs/PLAN.md | 137 +++++++++++ docs/adr/0001-dynamic-glibc-i686.md | 49 ++++ docs/adr/0002-append-only-sessions.md | 51 ++++ scripts/check-glibc.sh | 35 +++ scripts/mock-provider.py | 86 +++++++ src/agent.rs | 67 ++++++ src/config.rs | 67 ++++++ src/lib.rs | 5 + src/main.rs | 136 +++++++++++ src/provider.rs | 319 +++++++++++++++++++++++++ src/session.rs | 39 +++ src/ui.rs | 75 ++++++ tests/mock.rs | 192 +++++++++++++++ tests/sse.rs | 40 ++++ 18 files changed, 1782 insertions(+) create mode 100644 .gitignore create mode 100644 CONTEXT.md create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 docs/PLAN.md create mode 100644 docs/adr/0001-dynamic-glibc-i686.md create mode 100644 docs/adr/0002-append-only-sessions.md create mode 100755 scripts/check-glibc.sh create mode 100755 scripts/mock-provider.py create mode 100644 src/agent.rs create mode 100644 src/config.rs create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 src/provider.rs create mode 100644 src/session.rs create mode 100644 src/ui.rs create mode 100644 tests/mock.rs create mode 100644 tests/sse.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000..e48cb1a --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,30 @@ +# Context + +## Language + +**Provider** — a service that serves models over HTTP, with its own credential and +request/response shape. v1 supports exactly one: **OpenCode Go** (called +`opencode-go` in OpenCode's vocabulary), an OpenAI-compatible gateway. + +**Model** — a model id served by a provider, e.g. `deepseek-v4.1-flash`. A model +is not a provider, and not a config profile. The same model may be reachable +through more than one wire protocol. + +**Session** — one conversation, identified by an id that is stable for the life of +that conversation and survives the process exiting. Continuing a session reuses +its id; starting a new conversation gets a new one. A session is not a run, not a +process, and not a file. + +**Turn** — one user message plus every step the agent takes until the model +answers without tool calls. A turn is the unit of interruption: aborting a turn +leaves the session and its history intact. + +**Step** — one request/response cycle with the model within a turn. A turn is one +or more steps. + +**Tool call** — the model asking the harness to run one tool with arguments. A +tool call that fails, is denied, or produces no output is still a completed tool +call; its outcome is returned to the model as a result, not raised as an error. + +**Approval** — the human's permission for a tool call to run. An approval is +scoped to a session, not to a turn: once granted, it holds until the session ends. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..2af945a --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,437 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "agent686" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "ureq", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4806119 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "agent686" +version = "0.1.0" +edition = "2021" +description = "A small coding agent for a 32-bit Debian box" +publish = false + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +ureq = { version = "3", features = ["rustls"] } + +[profile.release] +strip = true +lto = true +codegen-units = 1 diff --git a/docs/PLAN.md b/docs/PLAN.md new file mode 100644 index 0000000..2766664 --- /dev/null +++ b/docs/PLAN.md @@ -0,0 +1,137 @@ +# agent686 — v1 plan + +A small coding agent for a Debian 12 i386 box (2 cores, 4 GB). Single binary, +line-mode, six tools. Built for understanding, not parity with anything. + +## Fixed constraints + +| | | +|---|---| +| Target | Debian 12 i386, glibc 2.36, 2 cores, 4 GB | +| Build | `i686-unknown-linux-gnu`, dynamic glibc (see ADR 0001) | +| Dev host | x86-64, `gcc-multilib`, `i686` + `i686-unknown-linux-musl` targets | +| Provider | OpenCode Go — `https://opencode.ai/inference/go/openai/v1`, `chat/completions` | +| Auth | `OPENCODE_API_KEY`, else `~/.config/agent686/key` (600 perms) | +| Concurrency | blocking, single-threaded; `ureq` + `rustls`/ring; no async runtime | + +## Decisions + +- **One provider, one wire protocol.** `chat/completions` only. Console translates, + so Claude/Gemini/GPT models are reachable through it. No `/responses`, no + `/anthropic/v1/messages`, no provider abstraction. +- **Client identity.** `User-Agent: agent686/`, and a stable + `x-opencode-session` header carrying the session id on every request. +- **Six tools.** `read` (numbered lines, offset/limit, 2000-line cap), `write` + (no implicit `mkdir`), `edit` (exact match, must be unique, else fail with match + count and line numbers), `bash` (fresh shell each call, `cwd` param, 120 s + timeout, capped output, exit code), `grep`, `glob`. All native — no dependence + on `rg` being installed. +- **Approval.** Reads free. First `write`/`edit` of a session prompts with a + unified diff and offers "always" (session-scoped). Every `bash` call prompts + unless `--yolo`. Prompts happen after the stream ends, never mid-token. +- **Turn/step.** A turn ends when the model answers with no tool calls, on user + abort, or on a non-retryable provider error. **No step cap** — the brake is the + step counter on the status line and Ctrl-C. +- **Tool errors are data.** Failures, non-zero exits, and denials are returned to + the model as results. Only transport/auth/process failures end a turn. +- **Sessions.** Append-only JSONL of wire messages (see ADR 0002). No compaction, + no truncation, no summarisation. Overflow is the provider's 400. +- **Prompt.** Snapshot at session start: fixed system prompt, a 3-line + environment block (cwd, platform, git branch), and `AGENTS.md` from cwd up to + the git root. Frozen for the session; mtime change prints a notice only. +- **UI.** Line-mode. ANSI only when stdout is a TTY. Plain `read_line` plus + `/paste` (reads until a lone `.` or EOF). No alt-screen, no raw mode, no + history, no markdown rendering, no syntax highlighting. +- **Ctrl-C.** SIGINT handler sets a flag; the stream loop closes the socket and + ends the turn. Second Ctrl-C exits. +- **No model metadata.** No cost display, no pre-flight context check. Token + counts shown only if the gateway returns usage; `opencode.allowance` shown if + present. +- **Dependencies.** `serde`, `serde_json`, `ureq` (rustls). Nothing else unless + justified. Tests use `std` only. + +## Non-goals for v1 + +Subagents, MCP, LSP, plugins/hooks, multiple providers, Anthropic-native wire +format, image input, RAG, worktrees, session sharing, syntax highlighting, +full-screen TUI, undo/snapshots (git is the undo), config knobs for step limits. + +## Milestones + +Each milestone is done when it runs, not when it compiles. + +**M0 — Skeleton and mock provider.** ✅ Done 2026-11-15. + +Crate, config load, request builder, SSE parser, one turn printed to stdout, no +tools. Mock provider over `std::net::TcpListener` in `tests/mock.rs` (no HTTP +crate) replaying canned SSE: text deltas, a split tool call, a 401. Parser tests +feed the stream one byte at a time, so splits inside SSE lines and inside +multi-byte UTF-8 are covered. + +Verified: `cargo test` 8/8; 2.0 MB stripped i686 binary, max symbol +`GLIBC_2.34`, runs inside `debian:12` for `linux/386` against the mock and +streams correctly; `scripts/check-glibc.sh` passes and fails as expected; +`scripts/mock-provider.py` gives a no-key provider for manual work. + +**M1 — Sessions, status line, abort.** JSONL append/load, session id, `--continue`, +`--resume `, status line, SIGINT handling. +*Done when:* a turn survives `kill -9` between steps, `--continue` resumes it, and +Ctrl-C returns the prompt without losing the transcript. + +**M2 — Read-side tools and edits.** `read`, `write`, `edit`, `grep`, `glob`, the +agent loop, tool-call accumulation, the approval prompt with diff. +*Done when:* a canned mock session writes a C file, greps it, edits it, and the +transcript replays byte-identically. + +**M3 — `bash`.** Command execution, timeout, output capping, per-call approval, +head/tail rendering. +*Done when:* the mock session compiles the C file and handles a non-zero exit as +data rather than an error. + +**M4 — Prompt and input.** System prompt, environment block, `AGENTS.md` +snapshot, `/paste`, TTY detection, real-API smoke test. +*Done when:* one real turn against OpenCode Go works end to end. + +**M5 — Target gate.** `scripts/check-glibc.sh` (max symbol version ≤ 2.36), +`cargo check --target i686` clean, release run inside +`docker run --platform linux/386 debian:12`, binary copied to the i386 box. +*Done when:* the acceptance test runs there. + +## Acceptance test (v1) + +> "Make a simple calculator in C" — run on the i386 box, from an empty directory. + +Exercises `write` (create files), `bash` (compile, run), `read` (inspect what it +wrote), and terminates on its own. Success is: it compiles, it runs, it does +addition and division, and it did not need more than a handful of files. + +## Layout + +``` +src/main.rs args, mode selection, exit codes +src/config.rs TOML-free config if possible; env precedence CLI > env > file +src/provider.rs request construction, ureq call, SSE parsing +src/session.rs id, JSONL append/load, replay +src/agent.rs turn/step loop, tool dispatch, approval hooks +src/tools/ read, write, edit, bash, grep, glob +src/ui.rs streaming render, diffs, approval prompt, status line, /paste +tests/mock.rs mock provider over std TcpListener +scripts/check-glibc.sh +``` + +Input is kept behind a single `read_input() -> Option` function so a +raw-mode editor with history can replace it later without touching the loop. + +## Open questions to settle against the live API + +Blocked on a fresh `OPENCODE_API_KEY` (the stored one returns `api_key_expired`). + +1. Is `stream_options: {"include_usage": true}` honoured, and does usage arrive in + the final chunk? +2. Exact shape and location of `opencode.allowance`; which unit it is in. +3. Is `reasoning_content` the delta field name across all reasoning models, or + only DeepSeek-derived ones? +4. Does the gateway accept `reasoning_effort`, or is reasoning configured + elsewhere? +5. Error body shape for context overflow, to map it to "start a new session". +6. Whether `x-opencode-session` has format constraints (opaque vs UUID). diff --git a/docs/adr/0001-dynamic-glibc-i686.md b/docs/adr/0001-dynamic-glibc-i686.md new file mode 100644 index 0000000..df791e0 --- /dev/null +++ b/docs/adr/0001-dynamic-glibc-i686.md @@ -0,0 +1,49 @@ +# 0001 — Ship a dynamically linked glibc i686 binary, not a static one + +**Status:** accepted + +## Context + +The target is a Debian 12 i386 machine: glibc 2.36, 2 cores, 4 GB RAM. The +development machine is x86-64 with `gcc-multilib` and the `i686-unknown-linux-gnu` +Rust target installed. + +"Single static binary" was the original plan, on the assumption that it removes +all runtime dependencies. Two measurements on the development machine contradict +that: + +1. **Static glibc cannot use NSS modules, and crashes trying.** An i686 binary + built with `+crt-static` segfaults inside `libnss_resolve.so.2` at + `getaddrinfo()`, because the host's `nsswitch.conf` lists `resolve` before + `files`. Static glibc is documented as unable to load NSS modules; on any + systemd-resolved machine, DNS from a static glibc binary is a SIGSEGV. The + failure mode is invisible at build time and appears on the first network call. +2. **Static musl requires a C-free dependency tree, which we do not have.** + `ring` (pulled in by `rustls`/`ureq`) compiles C and assembly; cc-rs invokes + `musl-gcc -m32` and fails because no 32-bit musl sysroot exists here. Making + musl work means adding an `i686-linux-musl` cross toolchain, or swapping the + TLS stack for a pre-1.0 pure-Rust provider. + +The dynamic i686 build works unchanged: TLS handshake, DNS, JSON parse, exit 0. +Its highest required symbol version is `GLIBC_2.34`, and it runs correctly inside +`docker run --platform linux/386 debian:12` (glibc 2.36). + +## Decision + +Build `i686-unknown-linux-gnu` **dynamically linked against glibc**, using the +host's 32-bit toolchain. Do not use `+crt-static`. Gate every release on a check +that the maximum required symbol version is `<= GLIBC_2.36`, and verify releases +by running them inside the `linux/386 debian:12` container before copying to the +target machine. + +## Consequences + +- The binary is ~3 MB stripped and needs the target's glibc to be at least 2.34. + Debian 12 provides 2.36, so there is headroom, but a future dependency can pull + in newer symbol versions. The `readelf` ceiling check is mandatory, not + advisory — without it the failure appears only on the i686 machine. +- Distribution is a binary plus its glibc, not a single file to `scp` anywhere. + Accepted: the target is a known Debian 12 box, not an unknown fleet. +- `ring`/`rustls` stay available, so the dependency tree is unconstrained. +- If the target later turns out to be older than glibc 2.34, or a second target + appears with an older libc, this decision reopens and musl becomes the path. diff --git a/docs/adr/0002-append-only-sessions.md b/docs/adr/0002-append-only-sessions.md new file mode 100644 index 0000000..2acfbd4 --- /dev/null +++ b/docs/adr/0002-append-only-sessions.md @@ -0,0 +1,51 @@ +# 0002 — Sessions are append-only wire transcripts; history is never rewritten + +**Status:** accepted + +## Context + +Two forces meet in the session format. + +The first is cost. The provider bills cached prompt reads at roughly 1/50th of +input price (DeepSeek V4.1 Flash: $0.003/M cached vs $0.15/M input). Cache hits +depend on the request prefix being byte-identical to the previous request. The +prefix is the system prompt, the tool schemas, and the message history — so any +edit to an earlier message invalidates the cache for everything after it and +re-bills the whole context. + +The second is fidelity. The model's next step depends on what it actually said +and what the tools actually returned, so the stored history has to reproduce the +wire messages exactly: `reasoning_content` from a reasoning model must not be +sent back (wasted tokens at best, a 400 at worst on DeepSeek-style backends), +and tool-call arguments must round-trip as the original JSON string rather than +being parsed and re-serialised, which can reorder keys and change whitespace. + +Summarising old turns, truncating old tool output, and dropping old messages all +solve context exhaustion, and all of them rewrite the prefix. They are +incompatible with cache stability. + +## Decision + +Store each session as **append-only JSONL of wire-level messages**, replayed +verbatim. No compaction, no truncation, no summarisation, no sliding window. + +- `reasoning_content` is stored (for the human to read) and stripped on replay. +- Tool-call arguments are stored and replayed as the original JSON string. +- The system prompt, environment block, and tool schemas are frozen at session + start and built from fixed-order structs — never a `HashMap`, never containing + session-varying values. +- When the conversation exceeds the model's context window, the provider returns + an error, the turn ends, and the user is told to start a new session. + +## Consequences + +- Prompt caching stays warm for the life of a session, which is the dominant cost + factor on a $10/month plan. +- Resuming a session is exact: replay the file and continue. No reconstruction + logic, no "the summary forgot the decision from ten turns ago". +- Long sessions have a hard ceiling and cannot be extended. The only remedy is a + new session, which loses the conversation. Accepted: with 128k-class windows + this is a rare event, and the failure is loud rather than silent. +- Session files grow without bound and are never garbage-collected. Accepted. +- Any future feature that wants to show a compacted view of history must render + it separately from what is sent to the provider. The transcript is the truth. diff --git a/scripts/check-glibc.sh b/scripts/check-glibc.sh new file mode 100755 index 0000000..bb9052f --- /dev/null +++ b/scripts/check-glibc.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Gate a release on the glibc the target actually has. +# +# The dev host's 32-bit glibc is newer than Debian 12's, so a dependency can +# silently raise the required symbol version. Without this check the failure +# only shows up as "version `GLIBC_2.38' not found" on the target machine. +set -euo pipefail + +binary=${1:?usage: check-glibc.sh [ceiling, default 2.36]} +ceiling=${2:-2.36} + +if [ ! -f "$binary" ]; then + echo "check-glibc: no such file: $binary" >&2 + exit 2 +fi + +max=$(readelf -V "$binary" 2>/dev/null \ + | grep -oE 'GLIBC_[0-9]+\.[0-9]+' \ + | sed 's/^GLIBC_//' \ + | sort -Vu \ + | tail -1 || true) + +if [ -z "${max:-}" ]; then + echo "check-glibc: no versioned symbols (statically linked?) — nothing to check" + exit 0 +fi + +echo "check-glibc: max symbol version GLIBC_$max, ceiling GLIBC_$ceiling" + +if [ "$(printf '%s\n%s\n' "$ceiling" "$max" | sort -V | tail -1)" != "$ceiling" ]; then + echo "check-glibc: FAIL — binary needs GLIBC_$max, target has GLIBC_$ceiling" >&2 + exit 1 +fi + +echo "check-glibc: ok" diff --git a/scripts/mock-provider.py b/scripts/mock-provider.py new file mode 100755 index 0000000..4d11349 --- /dev/null +++ b/scripts/mock-provider.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""A canned OpenAI-compatible SSE provider for manual testing. + +No API key, no network, no quota. Streams a reasoning delta, a text answer and +a usage frame, with a small pause between them so the renderer can be seen +working incrementally. + + scripts/mock-provider.py --port 8765 + OPENCODE_API_KEY=test ./agent686 --base-url http://127.0.0.1:8765/v1 "hi" +""" +import argparse +import json +import time +from http.server import BaseHTTPRequestHandler, HTTPServer + + +def frames(answer: str): + yield {"choices": [{"delta": {"reasoning_content": "The user said hi. "}}]} + yield {"choices": [{"delta": {"reasoning_content": "A short greeting is enough."}}]} + for word in answer.split(" "): + yield {"choices": [{"delta": {"content": word + " "}}]} + yield {"choices": [{"delta": {}, "finish_reason": "stop"}]} + yield {"choices": [], "usage": {"prompt_tokens": 24, "completion_tokens": 9}} + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.0" + + def do_POST(self): + length = int(self.headers.get("content-length") or 0) + self.rfile.read(length) + + if self.server.status != 200: + body = json.dumps( + { + "error": { + "type": "authentication_error", + "code": "api_key_expired", + "message": "This API key has expired.", + } + } + ).encode() + self.send_response(self.server.status) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(body) + return + + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-cache") + self.end_headers() + + for frame in frames(self.server.answer): + if self.server.delay: + time.sleep(self.server.delay) + self.wfile.write(f"data: {json.dumps(frame)}\n\n".encode()) + self.wfile.flush() + self.wfile.write(b"data: [DONE]\n\n") + self.wfile.flush() + + def log_message(self, fmt, *args): + if not self.server.quiet: + super().log_message(fmt, *args) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--port", type=int, default=8765) + parser.add_argument("--delay", type=float, default=0.05, help="seconds between frames") + parser.add_argument("--status", type=int, default=200, help="return this HTTP status") + parser.add_argument("--answer", default="Hello from the mock provider.") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args() + + server = HTTPServer(("127.0.0.1", args.port), Handler) + server.answer = args.answer + server.delay = args.delay + server.status = args.status + server.quiet = args.quiet + print(f"mock provider on http://127.0.0.1:{args.port}/v1", flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/src/agent.rs b/src/agent.rs new file mode 100644 index 0000000..2d84566 --- /dev/null +++ b/src/agent.rs @@ -0,0 +1,67 @@ +use std::sync::atomic::AtomicBool; + +use serde_json::{json, Value}; + +use crate::config::Config; +use crate::provider::{self, Error, Outcome, Sink}; + +/// Frozen for the life of the process. Anything session-varying added here +/// invalidates the provider's prompt cache, so keep it boring. +pub fn system_message() -> Value { + json!({ + "role": "system", + "content": "You are agent686, a coding agent working in a Unix terminal. \ + You edit files and run commands. Be terse and do not explain \ + what you are about to do before doing it." + }) +} + +/// Appends the user message, runs one provider round trip, and appends the +/// assistant message to the history whether or not it asked for tools. +pub fn run_turn( + cfg: &Config, + history: &mut Vec, + prompt: &str, + cancel: &AtomicBool, + sink: &mut dyn Sink, +) -> Result { + history.push(json!({ "role": "user", "content": prompt })); + + let outcome = provider::chat(cfg, history, cancel, sink)?; + + let mut message = serde_json::Map::new(); + message.insert("role".into(), json!("assistant")); + message.insert( + "content".into(), + if outcome.content.is_empty() { + Value::Null + } else { + json!(outcome.content) + }, + ); + if !outcome.tool_calls.is_empty() { + let calls: Vec = outcome + .tool_calls + .iter() + .map(|call| { + json!({ + "id": call.id, + "type": "function", + "function": { + "name": call.name, + // Byte-for-byte what the model sent. + "arguments": call.arguments, + } + }) + }) + .collect(); + message.insert("tool_calls".into(), Value::Array(calls)); + } + history.push(Value::Object(message)); + + Ok(outcome) +} + +pub fn new_history() -> Vec { + vec![system_message()] +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..b781637 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,67 @@ +use std::path::PathBuf; + +pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; +pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash"; + +#[derive(Debug, Clone)] +pub struct Config { + pub base_url: String, + pub api_key: String, + pub model: String, + pub session: String, +} + +impl Config { + /// CLI flags win over environment variables, which win over defaults. + pub fn resolve( + model: Option, + base_url: Option, + session: Option, + ) -> Result { + Ok(Config { + api_key: api_key()?, + base_url: base_url + .or_else(|| env_nonempty("AGENT686_BASE_URL")) + .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()), + model: model + .or_else(|| env_nonempty("AGENT686_MODEL")) + .unwrap_or_else(|| DEFAULT_MODEL.to_string()), + session: session.unwrap_or_else(crate::session::new_id), + }) + } + + pub fn endpoint(&self) -> String { + format!("{}/chat/completions", self.base_url.trim_end_matches('/')) + } +} + +fn env_nonempty(key: &str) -> Option { + std::env::var(key).ok().filter(|v| !v.trim().is_empty()) +} + +/// The key comes from the environment first, then from a file, so a key never +/// has to live in shell history or in a process listing. +fn api_key() -> Result { + if let Some(k) = env_nonempty("OPENCODE_API_KEY") { + return Ok(k.trim().to_string()); + } + if let Some(path) = key_file() { + if let Ok(k) = std::fs::read_to_string(&path) { + let k = k.trim().to_string(); + if !k.is_empty() { + return Ok(k); + } + } + } + Err(format!( + "no API key: set OPENCODE_API_KEY or write one to {}", + key_file() + .map(|p| p.display().to_string()) + .unwrap_or_else(|| "~/.config/agent686/key".into()) + )) +} + +fn key_file() -> Option { + let home = std::env::var_os("HOME")?; + Some(PathBuf::from(home).join(".config/agent686/key")) +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..20913b2 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,5 @@ +pub mod agent; +pub mod config; +pub mod provider; +pub mod session; +pub mod ui; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..8c9a58c --- /dev/null +++ b/src/main.rs @@ -0,0 +1,136 @@ +use std::io::{BufRead, IsTerminal, Write}; +use std::sync::atomic::AtomicBool; + +use agent686::{agent, config::Config, ui}; + +const HELP: &str = "\ +agent686 — a small coding agent + +USAGE: + agent686 [OPTIONS] [PROMPT...] + +With a prompt it runs one turn and exits; without one it reads prompts from +stdin, one per line. /exit quits. + +OPTIONS: + -m, --model model id (default: deepseek-v4.1-flash) + --base-url provider base URL, e.g. http://127.0.0.1:8080/v1 + --session reuse a session id, including for the provider header + -h, --help this text + +ENVIRONMENT: + OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) + AGENT686_MODEL default model id + AGENT686_BASE_URL default provider base URL +"; + +fn main() { + let mut prompt: Option = None; + let mut model = None; + let mut base_url = None; + let mut session = None; + + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + match arg.as_str() { + "-m" | "--model" => model = args.next(), + "--base-url" => base_url = args.next(), + "--session" => session = args.next(), + "-h" | "--help" => { + print!("{HELP}"); + return; + } + flag if flag.starts_with('-') && flag.len() > 1 => { + eprintln!("agent686: unknown flag {flag}\n"); + print!("{HELP}"); + std::process::exit(2); + } + word => { + prompt = Some(match prompt.take() { + Some(existing) => format!("{existing} {word}"), + None => word.to_string(), + }) + } + } + } + + let cfg = match Config::resolve(model, base_url, session) { + Ok(cfg) => cfg, + Err(message) => { + eprintln!("agent686: {message}"); + std::process::exit(2); + } + }; + + let cancel = AtomicBool::new(false); + let mut history = agent::new_history(); + + // One-shot mode: a prompt on the command line means one turn, then exit. + if let Some(prompt) = prompt { + let mut sink = ui::Renderer::new(ui::stdout_is_tty()); + match agent::run_turn(&cfg, &mut history, &prompt, &cancel, &mut sink) { + Ok(outcome) => note_tool_calls(&outcome), + Err(error) => { + eprintln!("agent686: {error}"); + std::process::exit(1); + } + } + return; + } + + let interactive = std::io::stdin().is_terminal(); + if interactive { + eprintln!( + "agent686 · {} · session {}{}", + cfg.model, + cfg.session, + if is_local(&cfg.base_url) { " · local" } else { "" } + ); + eprintln!("one prompt per line · /exit to quit"); + } + + let stdin = std::io::stdin(); + let mut line = String::new(); + loop { + if interactive { + print!("> "); + let _ = std::io::stdout().flush(); + } + line.clear(); + if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { + break; + } + let text = line.trim_end(); + if text.is_empty() { + continue; + } + if text == "/exit" || text == "/quit" { + break; + } + let mut sink = ui::Renderer::new(ui::stdout_is_tty()); + match agent::run_turn(&cfg, &mut history, text, &cancel, &mut sink) { + Ok(outcome) => note_tool_calls(&outcome), + Err(error) => eprintln!("agent686: {error}"), + } + } +} + +fn note_tool_calls(outcome: &agent686::provider::Outcome) { + if outcome.tool_calls.is_empty() { + return; + } + let names: Vec<&str> = outcome + .tool_calls + .iter() + .map(|call| call.name.as_str()) + .collect(); + eprintln!( + "agent686: model asked for {} tool call(s) [{}]; tools arrive in milestone 2", + names.len(), + names.join(", ") + ); +} + +fn is_local(base_url: &str) -> bool { + base_url.contains("127.0.0.1") || base_url.contains("localhost") +} diff --git a/src/provider.rs b/src/provider.rs new file mode 100644 index 0000000..a2aed64 --- /dev/null +++ b/src/provider.rs @@ -0,0 +1,319 @@ +use std::io::Read; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use serde::Deserialize; +use serde_json::Value; + +use crate::config::Config; + +#[derive(Debug)] +pub enum Error { + Transport(String), + Status { code: u16, message: String }, + Aborted, +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Transport(m) => write!(f, "{m}"), + Error::Status { code, message } => write!(f, "HTTP {code}: {message}"), + Error::Aborted => write!(f, "aborted"), + } + } +} + +impl std::error::Error for Error {} + +/// One completed tool call, assembled from streamed deltas. +#[derive(Debug, Default, Clone)] +pub struct ToolCall { + pub index: usize, + pub id: String, + pub name: String, + /// The argument JSON exactly as the model emitted it. Never re-serialised: + /// re-encoding can change key order and invalidate the provider's cache. + pub arguments: String, +} + +#[derive(Debug, Default)] +pub struct Outcome { + pub content: String, + pub reasoning: String, + pub tool_calls: Vec, + pub finish: Option, + pub usage: Option, + pub opencode: Option, +} + +pub trait Sink { + fn text(&mut self, s: &str); + fn reasoning(&mut self, s: &str); + fn done(&mut self, outcome: &Outcome, elapsed: Duration); +} + +/// Decodes an SSE byte stream into `data:` payloads. +/// +/// Kept as a state machine so that chunk boundaries can fall anywhere: inside a +/// line, or inside a multi-byte UTF-8 character. Only complete lines are ever +/// converted to text. +#[derive(Default)] +pub struct SseDecoder { + buf: Vec, +} + +impl SseDecoder { + pub fn new() -> Self { + Self::default() + } + + pub fn feed(&mut self, chunk: &[u8]) -> Vec { + self.buf.extend_from_slice(chunk); + let mut out = Vec::new(); + let mut start = 0; + while let Some(rel) = self.buf[start..].iter().position(|&b| b == b'\n') { + let end = start + rel; + let mut line = &self.buf[start..end]; + if line.last() == Some(&b'\r') { + line = &line[..line.len() - 1]; + } + start = end + 1; + if let Some(payload) = line.strip_prefix(b"data:") { + let payload = payload.strip_prefix(b" ").unwrap_or(payload); + out.push(String::from_utf8_lossy(payload).into_owned()); + } + } + self.buf.drain(..start); + out + } +} + +pub fn chat( + cfg: &Config, + messages: &[Value], + cancel: &AtomicBool, + sink: &mut dyn Sink, +) -> Result { + // serde_json::Value is ordered by key, not by insertion, so the serialised + // bytes are stable for the same input. That is what keeps the cache warm; + // do not switch this to a struct with fields in a different order, and do + // not add anything session-varying to the system message. + let body = serde_json::json!({ + "model": cfg.model, + "messages": messages, + "stream": true, + "stream_options": { "include_usage": true }, + }); + let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; + + let agent: ureq::Agent = ureq::Agent::config_builder() + .http_status_as_error(false) + .timeout_connect(Some(Duration::from_secs(10))) + .timeout_recv_response(Some(Duration::from_secs(180))) + .timeout_per_read(Some(Duration::from_secs(180))) + .build() + .into(); + + let started = Instant::now(); + let mut resp = agent + .post(&cfg.endpoint()) + .header("Content-Type", "application/json") + .header("Accept", "text/event-stream") + .header("Authorization", format!("Bearer {}", cfg.api_key)) + .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) + // Required by OpenCode Go: stable per conversation, used for routing and + // prompt caching. + .header("x-opencode-session", &cfg.session) + .send(bytes) + .map_err(|e| Error::Transport(e.to_string()))?; + + let status = resp.status().as_u16(); + if !(200..300).contains(&status) { + let text = resp + .body_mut() + .with_config() + .limit(256 * 1024) + .read_to_string() + .unwrap_or_default(); + return Err(Error::Status { + code: status, + message: error_message(&text), + }); + } + + let mut outcome = Outcome::default(); + let mut decoder = SseDecoder::new(); + let mut buf = [0u8; 8192]; + let mut reader = resp.body_mut().as_reader(); + let mut done = false; + + while !done { + // Blocking reads mean an abort is only noticed when bytes arrive or the + // per-read timeout fires. Good enough: the model streams constantly. + if cancel.load(Ordering::Relaxed) { + return Err(Error::Aborted); + } + let n = match reader.read(&mut buf) { + Ok(0) => break, + Ok(n) => n, + Err(e) => return Err(Error::Transport(e.to_string())), + }; + for data in decoder.feed(&buf[..n]) { + if data.is_empty() { + continue; + } + if data.trim() == "[DONE]" { + done = true; + break; + } + let chunk: Chunk = match serde_json::from_str(&data) { + Ok(c) => c, + // A malformed frame is dropped rather than killing the turn; the + // stream is the only recovery path and it is still valid SSE. + Err(_) => continue, + }; + apply_chunk(&chunk, &mut outcome, sink); + } + } + + if let Some(usage) = &outcome.usage { + if usage.is_null() { + outcome.usage = None; + } + } + if let Some(opencode) = &outcome.opencode { + if opencode.is_null() { + outcome.opencode = None; + } + } + + sink.done(&outcome, started.elapsed()); + Ok(outcome) +} + +fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { + if let Some(usage) = &chunk.usage { + outcome.usage = Some(usage.clone()); + } + if let Some(opencode) = &chunk.opencode { + outcome.opencode = Some(opencode.clone()); + } + for choice in &chunk.choices { + if let Some(r) = &choice.delta.reasoning_content { + if !r.is_empty() { + outcome.reasoning.push_str(r); + sink.reasoning(r); + } + } + if let Some(t) = &choice.delta.content { + if !t.is_empty() { + outcome.content.push_str(t); + sink.text(t); + } + } + if let Some(calls) = &choice.delta.tool_calls { + for call in calls { + accumulate_tool_call(&mut outcome.tool_calls, call); + } + } + if let Some(finish) = &choice.finish_reason { + outcome.finish = Some(finish.clone()); + } + } +} + +/// Tool call deltas arrive split across chunks and are keyed by `index`: the +/// name and id usually come once, the arguments a fragment at a time. +fn accumulate_tool_call(calls: &mut Vec, delta: &ToolCallDelta) { + while calls.len() <= delta.index { + let index = calls.len(); + calls.push(ToolCall { + index, + id: String::new(), + name: String::new(), + arguments: String::new(), + }); + } + let call = &mut calls[delta.index]; + if let Some(id) = &delta.id { + call.id.push_str(id); + } + if let Some(function) = &delta.function { + if let Some(name) = &function.name { + call.name.push_str(name); + } + if let Some(args) = &function.arguments { + call.arguments.push_str(args); + } + } +} + +fn error_message(body: &str) -> String { + if let Ok(v) = serde_json::from_str::(body) { + if let Some(err) = v.get("error") { + if let Some(message) = err.get("message").and_then(|m| m.as_str()) { + return match err.get("code").and_then(|c| c.as_str()) { + Some(code) if !code.is_empty() => format!("{message} ({code})"), + _ => message.to_string(), + }; + } + } + if let Some(message) = v.get("message").and_then(|m| m.as_str()) { + return message.to_string(); + } + } + truncate(body.trim(), 500) +} + +fn truncate(s: &str, max: usize) -> String { + match s.char_indices().nth(max) { + Some((i, _)) => format!("{}…", &s[..i]), + None => s.to_string(), + } +} + +#[derive(Debug, Deserialize)] +struct Chunk { + #[serde(default)] + choices: Vec, + #[serde(default)] + usage: Option, + #[serde(default)] + opencode: Option, +} + +#[derive(Debug, Deserialize)] +struct Choice { + #[serde(default)] + delta: Delta, + #[serde(default)] + finish_reason: Option, +} + +#[derive(Debug, Default, Deserialize)] +struct Delta { + #[serde(default)] + content: Option, + #[serde(default)] + reasoning_content: Option, + #[serde(default)] + tool_calls: Option>, +} + +#[derive(Debug, Deserialize)] +struct ToolCallDelta { + index: usize, + #[serde(default)] + id: Option, + #[serde(default)] + function: Option, +} + +#[derive(Debug, Deserialize)] +struct FunctionDelta { + #[serde(default)] + name: Option, + #[serde(default)] + arguments: Option, +} diff --git a/src/session.rs b/src/session.rs new file mode 100644 index 0000000..aef4835 --- /dev/null +++ b/src/session.rs @@ -0,0 +1,39 @@ +use std::hash::{Hash, Hasher}; +use std::io::Read; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// A session id is opaque to the provider: it only has to be stable for the life +/// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps +/// it usable as a file name. +pub fn new_id() -> String { + let mut bytes = random_bytes(); + // Put the creation time in the first bytes so ids sort roughly by age. + let ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + bytes[..8].copy_from_slice(&ms.to_be_bytes()); + + let mut out = String::with_capacity(32); + for b in bytes { + out.push_str(&format!("{b:02x}")); + } + out +} + +fn random_bytes() -> [u8; 16] { + let mut bytes = [0u8; 16]; + if let Ok(mut f) = std::fs::File::open("/dev/urandom") { + if f.read_exact(&mut bytes).is_ok() { + return bytes; + } + } + // Fallback: not cryptographic, but an id only has to not collide. + let mut h = std::collections::hash_map::DefaultHasher::new(); + SystemTime::now().hash(&mut h); + std::process::id().hash(&mut h); + let v = h.finish(); + bytes[..8].copy_from_slice(&v.to_be_bytes()); + bytes[8..].copy_from_slice(&(v ^ 0x9e37_79b9_7f4a_7c15).to_be_bytes()); + bytes +} diff --git a/src/ui.rs b/src/ui.rs new file mode 100644 index 0000000..13440b2 --- /dev/null +++ b/src/ui.rs @@ -0,0 +1,75 @@ +use std::io::{IsTerminal, Write}; +use std::time::Duration; + +use crate::provider::{Outcome, Sink}; + +pub fn stdout_is_tty() -> bool { + std::io::stdout().is_terminal() +} + +/// Streams to stdout. Colour is used only when stdout is a terminal, so piping +/// the output somewhere gives clean text. +pub struct Renderer { + color: bool, + dimmed: bool, + wrote_text: bool, +} + +impl Renderer { + pub fn new(color: bool) -> Self { + Self { + color, + dimmed: false, + wrote_text: false, + } + } + + fn undim(&mut self) { + if self.dimmed { + print!("\x1b[0m"); + self.dimmed = false; + } + } +} + +impl Sink for Renderer { + fn text(&mut self, s: &str) { + self.undim(); + print!("{s}"); + let _ = std::io::stdout().flush(); + self.wrote_text = true; + } + + fn reasoning(&mut self, s: &str) { + if !self.color { + return; + } + if !self.dimmed { + print!("\x1b[2m"); + self.dimmed = true; + } + print!("{s}"); + let _ = std::io::stdout().flush(); + } + + fn done(&mut self, outcome: &Outcome, elapsed: Duration) { + self.undim(); + if self.wrote_text { + println!(); + } + let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())]; + if let Some(usage) = &outcome.usage { + let input = usage.get("prompt_tokens").and_then(|v| v.as_u64()); + let output = usage.get("completion_tokens").and_then(|v| v.as_u64()); + if let (Some(i), Some(o)) = (input, output) { + parts.push(format!("{i} in · {o} out")); + } + } + let line = format!("─ {}", parts.join(" · ")); + if self.color { + println!("\x1b[2m{line}\x1b[0m"); + } else { + println!("{line}"); + } + } +} diff --git a/tests/mock.rs b/tests/mock.rs new file mode 100644 index 0000000..80d965b --- /dev/null +++ b/tests/mock.rs @@ -0,0 +1,192 @@ +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpListener; +use std::sync::atomic::AtomicBool; +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +use serde_json::json; + +use agent686::config::Config; +use agent686::provider::{self, Error, Outcome, Sink}; + +#[derive(Default)] +struct Collector { + text: String, + reasoning: String, + finished: bool, +} + +impl Sink for Collector { + fn text(&mut self, s: &str) { + self.text.push_str(s); + } + fn reasoning(&mut self, s: &str) { + self.reasoning.push_str(s); + } + fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) { + self.finished = true; + } +} + +/// Serves exactly one request on a random port, then closes. Returns the base +/// URL and a receiver for the request as the client sent it. +fn serve_once(response: &'static str) -> (String, mpsc::Receiver) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + + let mut request = String::new(); + let mut content_length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { + break; + } + if line == "\r\n" || line == "\n" { + break; + } + if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { + content_length = value.trim().parse().unwrap_or(0); + } + request.push_str(&line); + } + let mut body = vec![0u8; content_length]; + let _ = reader.read_exact(&mut body); + request.push_str(&String::from_utf8_lossy(&body)); + let _ = tx.send(request); + + let _ = stream.write_all(response.as_bytes()); + let _ = stream.flush(); + }); + + (format!("http://{addr}"), rx) +} + +fn config(base_url: String) -> Config { + Config { + base_url, + api_key: "test-key".into(), + model: "test-model".into(), + session: "testsession".into(), + } +} + +#[test] +fn streams_text_reasoning_and_usage() { + const SSE: &str = concat!( + "HTTP/1.1 200 OK\r\n", + "Content-Type: text/event-stream\r\n", + "Connection: close\r\n", + "\r\n", + "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}\n\n", + "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n", + "data: {\"choices\":[{\"delta\":{\"content\":\" from mock\"},\"finish_reason\":\"stop\"}]}\n\n", + "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2}}\n\n", + "data: [DONE]\n\n", + ); + let (base, rx) = serve_once(SSE); + let mut sink = Collector::default(); + let outcome = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &AtomicBool::new(false), + &mut sink, + ) + .expect("chat should succeed"); + + assert_eq!(outcome.content, "Hello from mock"); + assert_eq!(outcome.reasoning, "thinking"); + assert_eq!(sink.text, "Hello from mock"); + assert_eq!(sink.reasoning, "thinking"); + assert!(sink.finished); + assert_eq!(outcome.usage.unwrap()["completion_tokens"], 2); + + let request = rx.recv().unwrap().to_ascii_lowercase(); + assert!( + request.contains("x-opencode-session: testsession"), + "session header missing from request:\n{request}" + ); + assert!(request.contains("user-agent: agent686/")); + assert!(request.contains("\"stream\":true")); + assert!(request.contains("\"include_usage\":true")); +} + +#[test] +fn assembles_tool_call_arguments_byte_for_byte() { + const SSE: &str = concat!( + "HTTP/1.1 200 OK\r\n", + "Content-Type: text/event-stream\r\n", + "Connection: close\r\n", + "\r\n", + "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\"}}]}}]}\n\n", + "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\"a.txt\\\"}\"}}]}}]}\n\n", + "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n", + "data: [DONE]\n\n", + ); + let (base, _rx) = serve_once(SSE); + let mut sink = Collector::default(); + let outcome = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "read a.txt" })], + &AtomicBool::new(false), + &mut sink, + ) + .expect("chat should succeed"); + + assert_eq!(outcome.tool_calls.len(), 1); + let call = &outcome.tool_calls[0]; + assert_eq!(call.id, "call_1"); + assert_eq!(call.name, "read"); + assert_eq!(call.arguments, r#"{"path":"a.txt"}"#); + assert_eq!(outcome.finish.as_deref(), Some("tool_calls")); +} + +#[test] +fn surfaces_provider_error_text() { + const RESPONSE: &str = concat!( + "HTTP/1.1 401 Unauthorized\r\n", + "Content-Type: application/json\r\n", + "Connection: close\r\n", + "\r\n", + "{\"error\":{\"type\":\"authentication_error\",\"code\":\"api_key_expired\",", + "\"message\":\"This API key has expired.\"}}", + ); + let (base, _rx) = serve_once(RESPONSE); + let mut sink = Collector::default(); + let error = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &AtomicBool::new(false), + &mut sink, + ) + .expect_err("should fail"); + + match error { + Error::Status { code, message } => { + assert_eq!(code, 401); + assert!(message.contains("This API key has expired."), "{message}"); + assert!(message.contains("api_key_expired"), "{message}"); + } + other => panic!("unexpected error: {other:?}"), + } +} + +#[test] +fn honours_a_cancelled_turn() { + const SSE: &str = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\ndata: {\"choices\":[{\"delta\":{\"content\":\"x\"}}]}\n\n"; + let (base, _rx) = serve_once(SSE); + let mut sink = Collector::default(); + let error = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &AtomicBool::new(true), + &mut sink, + ) + .expect_err("cancelled turn should abort"); + assert!(matches!(error, Error::Aborted)); +} diff --git a/tests/sse.rs b/tests/sse.rs new file mode 100644 index 0000000..7994a0a --- /dev/null +++ b/tests/sse.rs @@ -0,0 +1,40 @@ +use agent686::provider::SseDecoder; + +#[test] +fn reassembles_lines_split_at_every_byte() { + // Fed one byte at a time, so the decoder sees a split after every character, + // including in the middle of the multi-byte ones. + let wire = "data: {\"a\":\"café ✓\"}\n\ndata: [DONE]\n\n"; + let mut decoder = SseDecoder::new(); + let mut got = Vec::new(); + for byte in wire.as_bytes() { + got.extend(decoder.feed(std::slice::from_ref(byte))); + } + assert_eq!(got, vec!["{\"a\":\"café ✓\"}".to_string(), "[DONE]".to_string()]); +} + +#[test] +fn handles_crlf_comments_and_event_lines() { + let wire = ": keep-alive\r\nevent: message\r\ndata:{\"x\":1}\r\n\r\n"; + let mut decoder = SseDecoder::new(); + let got = decoder.feed(wire.as_bytes()); + assert_eq!(got, vec!["{\"x\":1}".to_string()]); +} + +#[test] +fn keeps_incomplete_line_until_finished() { + let mut decoder = SseDecoder::new(); + assert!(decoder.feed(b"data: {\"x\"").is_empty()); + assert!(decoder.feed(b":1}").is_empty()); + assert_eq!( + decoder.feed(b"\n"), + vec!["{\"x\":1}".to_string()] + ); +} + +#[test] +fn ignores_non_data_lines() { + let mut decoder = SseDecoder::new(); + let got = decoder.feed(b"id: 1\nretry: 2000\n\n"); + assert!(got.is_empty()); +} -- cgit v1.2.3