aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--.gitignore1
-rw-r--r--CONTEXT.md30
-rw-r--r--Cargo.lock437
-rw-r--r--Cargo.toml16
-rw-r--r--docs/PLAN.md137
-rw-r--r--docs/adr/0001-dynamic-glibc-i686.md49
-rw-r--r--docs/adr/0002-append-only-sessions.md51
-rwxr-xr-xscripts/check-glibc.sh35
-rwxr-xr-xscripts/mock-provider.py86
-rw-r--r--src/agent.rs67
-rw-r--r--src/config.rs67
-rw-r--r--src/lib.rs5
-rw-r--r--src/main.rs136
-rw-r--r--src/provider.rs319
-rw-r--r--src/session.rs39
-rw-r--r--src/ui.rs75
-rw-r--r--tests/mock.rs192
-rw-r--r--tests/sse.rs40
18 files changed, 1782 insertions, 0 deletions
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 @@
1# Context
2
3## Language
4
5**Provider** — a service that serves models over HTTP, with its own credential and
6request/response shape. v1 supports exactly one: **OpenCode Go** (called
7`opencode-go` in OpenCode's vocabulary), an OpenAI-compatible gateway.
8
9**Model** — a model id served by a provider, e.g. `deepseek-v4.1-flash`. A model
10is not a provider, and not a config profile. The same model may be reachable
11through more than one wire protocol.
12
13**Session** — one conversation, identified by an id that is stable for the life of
14that conversation and survives the process exiting. Continuing a session reuses
15its id; starting a new conversation gets a new one. A session is not a run, not a
16process, and not a file.
17
18**Turn** — one user message plus every step the agent takes until the model
19answers without tool calls. A turn is the unit of interruption: aborting a turn
20leaves the session and its history intact.
21
22**Step** — one request/response cycle with the model within a turn. A turn is one
23or more steps.
24
25**Tool call** — the model asking the harness to run one tool with arguments. A
26tool call that fails, is denied, or produces no output is still a completed tool
27call; its outcome is returned to the model as a result, not raised as an error.
28
29**Approval** — the human's permission for a tool call to run. An approval is
30scoped 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 @@
1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "adler2"
7version = "2.0.1"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10
11[[package]]
12name = "agent686"
13version = "0.1.0"
14dependencies = [
15 "serde",
16 "serde_json",
17 "ureq",
18]
19
20[[package]]
21name = "base64"
22version = "0.23.1"
23source = "registry+https://github.com/rust-lang/crates.io-index"
24checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
25
26[[package]]
27name = "bytes"
28version = "1.12.1"
29source = "registry+https://github.com/rust-lang/crates.io-index"
30checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
31
32[[package]]
33name = "cc"
34version = "1.11.2"
35source = "registry+https://github.com/rust-lang/crates.io-index"
36checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"
37dependencies = [
38 "find-msvc-tools",
39 "shlex",
40]
41
42[[package]]
43name = "cfg-if"
44version = "1.0.5"
45source = "registry+https://github.com/rust-lang/crates.io-index"
46checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
47
48[[package]]
49name = "crc32fast"
50version = "1.5.5"
51source = "registry+https://github.com/rust-lang/crates.io-index"
52checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
53dependencies = [
54 "cfg-if",
55]
56
57[[package]]
58name = "find-msvc-tools"
59version = "0.1.15"
60source = "registry+https://github.com/rust-lang/crates.io-index"
61checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
62
63[[package]]
64name = "flate2"
65version = "1.1.11"
66source = "registry+https://github.com/rust-lang/crates.io-index"
67checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
68dependencies = [
69 "crc32fast",
70 "miniz_oxide",
71 "zlib-rs",
72]
73
74[[package]]
75name = "getrandom"
76version = "0.2.17"
77source = "registry+https://github.com/rust-lang/crates.io-index"
78checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
79dependencies = [
80 "cfg-if",
81 "libc",
82 "wasi",
83]
84
85[[package]]
86name = "http"
87version = "1.5.0"
88source = "registry+https://github.com/rust-lang/crates.io-index"
89checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
90dependencies = [
91 "bytes",
92 "itoa",
93]
94
95[[package]]
96name = "httparse"
97version = "1.10.1"
98source = "registry+https://github.com/rust-lang/crates.io-index"
99checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
100
101[[package]]
102name = "itoa"
103version = "1.0.19"
104source = "registry+https://github.com/rust-lang/crates.io-index"
105checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
106
107[[package]]
108name = "libc"
109version = "0.2.191"
110source = "registry+https://github.com/rust-lang/crates.io-index"
111checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
112
113[[package]]
114name = "log"
115version = "0.4.35"
116source = "registry+https://github.com/rust-lang/crates.io-index"
117checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
118
119[[package]]
120name = "memchr"
121version = "2.8.3"
122source = "registry+https://github.com/rust-lang/crates.io-index"
123checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
124
125[[package]]
126name = "miniz_oxide"
127version = "0.9.1"
128source = "registry+https://github.com/rust-lang/crates.io-index"
129checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
130dependencies = [
131 "adler2",
132 "simd-adler32",
133]
134
135[[package]]
136name = "once_cell"
137version = "1.21.4"
138source = "registry+https://github.com/rust-lang/crates.io-index"
139checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
140
141[[package]]
142name = "percent-encoding"
143version = "2.3.2"
144source = "registry+https://github.com/rust-lang/crates.io-index"
145checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
146
147[[package]]
148name = "proc-macro2"
149version = "1.0.107"
150source = "registry+https://github.com/rust-lang/crates.io-index"
151checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
152dependencies = [
153 "unicode-ident",
154]
155
156[[package]]
157name = "quote"
158version = "1.0.47"
159source = "registry+https://github.com/rust-lang/crates.io-index"
160checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
161dependencies = [
162 "proc-macro2",
163]
164
165[[package]]
166name = "ring"
167version = "0.17.14"
168source = "registry+https://github.com/rust-lang/crates.io-index"
169checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
170dependencies = [
171 "cc",
172 "cfg-if",
173 "getrandom",
174 "libc",
175 "untrusted",
176 "windows-sys",
177]
178
179[[package]]
180name = "rustls"
181version = "0.23.46"
182source = "registry+https://github.com/rust-lang/crates.io-index"
183checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
184dependencies = [
185 "log",
186 "once_cell",
187 "ring",
188 "rustls-pki-types",
189 "rustls-webpki",
190 "subtle",
191 "zeroize",
192]
193
194[[package]]
195name = "rustls-pki-types"
196version = "1.16.0"
197source = "registry+https://github.com/rust-lang/crates.io-index"
198checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
199dependencies = [
200 "zeroize",
201]
202
203[[package]]
204name = "rustls-webpki"
205version = "0.103.17"
206source = "registry+https://github.com/rust-lang/crates.io-index"
207checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
208dependencies = [
209 "ring",
210 "rustls-pki-types",
211 "untrusted",
212]
213
214[[package]]
215name = "serde"
216version = "1.0.229"
217source = "registry+https://github.com/rust-lang/crates.io-index"
218checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
219dependencies = [
220 "serde_core",
221 "serde_derive",
222]
223
224[[package]]
225name = "serde_core"
226version = "1.0.229"
227source = "registry+https://github.com/rust-lang/crates.io-index"
228checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
229dependencies = [
230 "serde_derive",
231]
232
233[[package]]
234name = "serde_derive"
235version = "1.0.229"
236source = "registry+https://github.com/rust-lang/crates.io-index"
237checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
238dependencies = [
239 "proc-macro2",
240 "quote",
241 "syn",
242]
243
244[[package]]
245name = "serde_json"
246version = "1.0.154"
247source = "registry+https://github.com/rust-lang/crates.io-index"
248checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
249dependencies = [
250 "itoa",
251 "memchr",
252 "serde",
253 "serde_core",
254 "zmij",
255]
256
257[[package]]
258name = "shlex"
259version = "2.0.1"
260source = "registry+https://github.com/rust-lang/crates.io-index"
261checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
262
263[[package]]
264name = "simd-adler32"
265version = "0.3.10"
266source = "registry+https://github.com/rust-lang/crates.io-index"
267checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
268
269[[package]]
270name = "subtle"
271version = "2.6.1"
272source = "registry+https://github.com/rust-lang/crates.io-index"
273checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
274
275[[package]]
276name = "syn"
277version = "3.0.10"
278source = "registry+https://github.com/rust-lang/crates.io-index"
279checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
280dependencies = [
281 "proc-macro2",
282 "quote",
283 "unicode-ident",
284]
285
286[[package]]
287name = "unicode-ident"
288version = "1.0.27"
289source = "registry+https://github.com/rust-lang/crates.io-index"
290checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
291
292[[package]]
293name = "untrusted"
294version = "0.9.0"
295source = "registry+https://github.com/rust-lang/crates.io-index"
296checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
297
298[[package]]
299name = "ureq"
300version = "3.5.2"
301source = "registry+https://github.com/rust-lang/crates.io-index"
302checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d"
303dependencies = [
304 "base64",
305 "flate2",
306 "log",
307 "percent-encoding",
308 "rustls",
309 "rustls-pki-types",
310 "ureq-proto",
311 "utf8-zero",
312 "webpki-roots",
313]
314
315[[package]]
316name = "ureq-proto"
317version = "0.7.1"
318source = "registry+https://github.com/rust-lang/crates.io-index"
319checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3"
320dependencies = [
321 "base64",
322 "http",
323 "httparse",
324 "log",
325]
326
327[[package]]
328name = "utf8-zero"
329version = "0.8.1"
330source = "registry+https://github.com/rust-lang/crates.io-index"
331checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
332
333[[package]]
334name = "wasi"
335version = "0.11.1+wasi-snapshot-preview1"
336source = "registry+https://github.com/rust-lang/crates.io-index"
337checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
338
339[[package]]
340name = "webpki-roots"
341version = "1.0.12"
342source = "registry+https://github.com/rust-lang/crates.io-index"
343checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"
344dependencies = [
345 "rustls-pki-types",
346]
347
348[[package]]
349name = "windows-sys"
350version = "0.52.0"
351source = "registry+https://github.com/rust-lang/crates.io-index"
352checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
353dependencies = [
354 "windows-targets",
355]
356
357[[package]]
358name = "windows-targets"
359version = "0.52.6"
360source = "registry+https://github.com/rust-lang/crates.io-index"
361checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
362dependencies = [
363 "windows_aarch64_gnullvm",
364 "windows_aarch64_msvc",
365 "windows_i686_gnu",
366 "windows_i686_gnullvm",
367 "windows_i686_msvc",
368 "windows_x86_64_gnu",
369 "windows_x86_64_gnullvm",
370 "windows_x86_64_msvc",
371]
372
373[[package]]
374name = "windows_aarch64_gnullvm"
375version = "0.52.6"
376source = "registry+https://github.com/rust-lang/crates.io-index"
377checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
378
379[[package]]
380name = "windows_aarch64_msvc"
381version = "0.52.6"
382source = "registry+https://github.com/rust-lang/crates.io-index"
383checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
384
385[[package]]
386name = "windows_i686_gnu"
387version = "0.52.6"
388source = "registry+https://github.com/rust-lang/crates.io-index"
389checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
390
391[[package]]
392name = "windows_i686_gnullvm"
393version = "0.52.6"
394source = "registry+https://github.com/rust-lang/crates.io-index"
395checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
396
397[[package]]
398name = "windows_i686_msvc"
399version = "0.52.6"
400source = "registry+https://github.com/rust-lang/crates.io-index"
401checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
402
403[[package]]
404name = "windows_x86_64_gnu"
405version = "0.52.6"
406source = "registry+https://github.com/rust-lang/crates.io-index"
407checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
408
409[[package]]
410name = "windows_x86_64_gnullvm"
411version = "0.52.6"
412source = "registry+https://github.com/rust-lang/crates.io-index"
413checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
414
415[[package]]
416name = "windows_x86_64_msvc"
417version = "0.52.6"
418source = "registry+https://github.com/rust-lang/crates.io-index"
419checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
420
421[[package]]
422name = "zeroize"
423version = "1.9.1"
424source = "registry+https://github.com/rust-lang/crates.io-index"
425checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
426
427[[package]]
428name = "zlib-rs"
429version = "0.6.8"
430source = "registry+https://github.com/rust-lang/crates.io-index"
431checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
432
433[[package]]
434name = "zmij"
435version = "1.0.23"
436source = "registry+https://github.com/rust-lang/crates.io-index"
437checksum = "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 @@
1[package]
2name = "agent686"
3version = "0.1.0"
4edition = "2021"
5description = "A small coding agent for a 32-bit Debian box"
6publish = false
7
8[dependencies]
9serde = { version = "1", features = ["derive"] }
10serde_json = "1"
11ureq = { version = "3", features = ["rustls"] }
12
13[profile.release]
14strip = true
15lto = true
16codegen-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 @@
1# agent686 — v1 plan
2
3A small coding agent for a Debian 12 i386 box (2 cores, 4 GB). Single binary,
4line-mode, six tools. Built for understanding, not parity with anything.
5
6## Fixed constraints
7
8| | |
9|---|---|
10| Target | Debian 12 i386, glibc 2.36, 2 cores, 4 GB |
11| Build | `i686-unknown-linux-gnu`, dynamic glibc (see ADR 0001) |
12| Dev host | x86-64, `gcc-multilib`, `i686` + `i686-unknown-linux-musl` targets |
13| Provider | OpenCode Go — `https://opencode.ai/inference/go/openai/v1`, `chat/completions` |
14| Auth | `OPENCODE_API_KEY`, else `~/.config/agent686/key` (600 perms) |
15| Concurrency | blocking, single-threaded; `ureq` + `rustls`/ring; no async runtime |
16
17## Decisions
18
19- **One provider, one wire protocol.** `chat/completions` only. Console translates,
20 so Claude/Gemini/GPT models are reachable through it. No `/responses`, no
21 `/anthropic/v1/messages`, no provider abstraction.
22- **Client identity.** `User-Agent: agent686/<version>`, and a stable
23 `x-opencode-session` header carrying the session id on every request.
24- **Six tools.** `read` (numbered lines, offset/limit, 2000-line cap), `write`
25 (no implicit `mkdir`), `edit` (exact match, must be unique, else fail with match
26 count and line numbers), `bash` (fresh shell each call, `cwd` param, 120 s
27 timeout, capped output, exit code), `grep`, `glob`. All native — no dependence
28 on `rg` being installed.
29- **Approval.** Reads free. First `write`/`edit` of a session prompts with a
30 unified diff and offers "always" (session-scoped). Every `bash` call prompts
31 unless `--yolo`. Prompts happen after the stream ends, never mid-token.
32- **Turn/step.** A turn ends when the model answers with no tool calls, on user
33 abort, or on a non-retryable provider error. **No step cap** — the brake is the
34 step counter on the status line and Ctrl-C.
35- **Tool errors are data.** Failures, non-zero exits, and denials are returned to
36 the model as results. Only transport/auth/process failures end a turn.
37- **Sessions.** Append-only JSONL of wire messages (see ADR 0002). No compaction,
38 no truncation, no summarisation. Overflow is the provider's 400.
39- **Prompt.** Snapshot at session start: fixed system prompt, a 3-line
40 environment block (cwd, platform, git branch), and `AGENTS.md` from cwd up to
41 the git root. Frozen for the session; mtime change prints a notice only.
42- **UI.** Line-mode. ANSI only when stdout is a TTY. Plain `read_line` plus
43 `/paste` (reads until a lone `.` or EOF). No alt-screen, no raw mode, no
44 history, no markdown rendering, no syntax highlighting.
45- **Ctrl-C.** SIGINT handler sets a flag; the stream loop closes the socket and
46 ends the turn. Second Ctrl-C exits.
47- **No model metadata.** No cost display, no pre-flight context check. Token
48 counts shown only if the gateway returns usage; `opencode.allowance` shown if
49 present.
50- **Dependencies.** `serde`, `serde_json`, `ureq` (rustls). Nothing else unless
51 justified. Tests use `std` only.
52
53## Non-goals for v1
54
55Subagents, MCP, LSP, plugins/hooks, multiple providers, Anthropic-native wire
56format, image input, RAG, worktrees, session sharing, syntax highlighting,
57full-screen TUI, undo/snapshots (git is the undo), config knobs for step limits.
58
59## Milestones
60
61Each milestone is done when it runs, not when it compiles.
62
63**M0 — Skeleton and mock provider.** ✅ Done 2026-11-15.
64
65Crate, config load, request builder, SSE parser, one turn printed to stdout, no
66tools. Mock provider over `std::net::TcpListener` in `tests/mock.rs` (no HTTP
67crate) replaying canned SSE: text deltas, a split tool call, a 401. Parser tests
68feed the stream one byte at a time, so splits inside SSE lines and inside
69multi-byte UTF-8 are covered.
70
71Verified: `cargo test` 8/8; 2.0 MB stripped i686 binary, max symbol
72`GLIBC_2.34`, runs inside `debian:12` for `linux/386` against the mock and
73streams correctly; `scripts/check-glibc.sh` passes and fails as expected;
74`scripts/mock-provider.py` gives a no-key provider for manual work.
75
76**M1 — Sessions, status line, abort.** JSONL append/load, session id, `--continue`,
77`--resume <id>`, status line, SIGINT handling.
78*Done when:* a turn survives `kill -9` between steps, `--continue` resumes it, and
79Ctrl-C returns the prompt without losing the transcript.
80
81**M2 — Read-side tools and edits.** `read`, `write`, `edit`, `grep`, `glob`, the
82agent loop, tool-call accumulation, the approval prompt with diff.
83*Done when:* a canned mock session writes a C file, greps it, edits it, and the
84transcript replays byte-identically.
85
86**M3 — `bash`.** Command execution, timeout, output capping, per-call approval,
87head/tail rendering.
88*Done when:* the mock session compiles the C file and handles a non-zero exit as
89data rather than an error.
90
91**M4 — Prompt and input.** System prompt, environment block, `AGENTS.md`
92snapshot, `/paste`, TTY detection, real-API smoke test.
93*Done when:* one real turn against OpenCode Go works end to end.
94
95**M5 — Target gate.** `scripts/check-glibc.sh` (max symbol version ≤ 2.36),
96`cargo check --target i686` clean, release run inside
97`docker run --platform linux/386 debian:12`, binary copied to the i386 box.
98*Done when:* the acceptance test runs there.
99
100## Acceptance test (v1)
101
102> "Make a simple calculator in C" — run on the i386 box, from an empty directory.
103
104Exercises `write` (create files), `bash` (compile, run), `read` (inspect what it
105wrote), and terminates on its own. Success is: it compiles, it runs, it does
106addition and division, and it did not need more than a handful of files.
107
108## Layout
109
110```
111src/main.rs args, mode selection, exit codes
112src/config.rs TOML-free config if possible; env precedence CLI > env > file
113src/provider.rs request construction, ureq call, SSE parsing
114src/session.rs id, JSONL append/load, replay
115src/agent.rs turn/step loop, tool dispatch, approval hooks
116src/tools/ read, write, edit, bash, grep, glob
117src/ui.rs streaming render, diffs, approval prompt, status line, /paste
118tests/mock.rs mock provider over std TcpListener
119scripts/check-glibc.sh
120```
121
122Input is kept behind a single `read_input() -> Option<String>` function so a
123raw-mode editor with history can replace it later without touching the loop.
124
125## Open questions to settle against the live API
126
127Blocked on a fresh `OPENCODE_API_KEY` (the stored one returns `api_key_expired`).
128
1291. Is `stream_options: {"include_usage": true}` honoured, and does usage arrive in
130 the final chunk?
1312. Exact shape and location of `opencode.allowance`; which unit it is in.
1323. Is `reasoning_content` the delta field name across all reasoning models, or
133 only DeepSeek-derived ones?
1344. Does the gateway accept `reasoning_effort`, or is reasoning configured
135 elsewhere?
1365. Error body shape for context overflow, to map it to "start a new session".
1376. 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 @@
1# 0001 — Ship a dynamically linked glibc i686 binary, not a static one
2
3**Status:** accepted
4
5## Context
6
7The target is a Debian 12 i386 machine: glibc 2.36, 2 cores, 4 GB RAM. The
8development machine is x86-64 with `gcc-multilib` and the `i686-unknown-linux-gnu`
9Rust target installed.
10
11"Single static binary" was the original plan, on the assumption that it removes
12all runtime dependencies. Two measurements on the development machine contradict
13that:
14
151. **Static glibc cannot use NSS modules, and crashes trying.** An i686 binary
16 built with `+crt-static` segfaults inside `libnss_resolve.so.2` at
17 `getaddrinfo()`, because the host's `nsswitch.conf` lists `resolve` before
18 `files`. Static glibc is documented as unable to load NSS modules; on any
19 systemd-resolved machine, DNS from a static glibc binary is a SIGSEGV. The
20 failure mode is invisible at build time and appears on the first network call.
212. **Static musl requires a C-free dependency tree, which we do not have.**
22 `ring` (pulled in by `rustls`/`ureq`) compiles C and assembly; cc-rs invokes
23 `musl-gcc -m32` and fails because no 32-bit musl sysroot exists here. Making
24 musl work means adding an `i686-linux-musl` cross toolchain, or swapping the
25 TLS stack for a pre-1.0 pure-Rust provider.
26
27The dynamic i686 build works unchanged: TLS handshake, DNS, JSON parse, exit 0.
28Its highest required symbol version is `GLIBC_2.34`, and it runs correctly inside
29`docker run --platform linux/386 debian:12` (glibc 2.36).
30
31## Decision
32
33Build `i686-unknown-linux-gnu` **dynamically linked against glibc**, using the
34host's 32-bit toolchain. Do not use `+crt-static`. Gate every release on a check
35that the maximum required symbol version is `<= GLIBC_2.36`, and verify releases
36by running them inside the `linux/386 debian:12` container before copying to the
37target machine.
38
39## Consequences
40
41- The binary is ~3 MB stripped and needs the target's glibc to be at least 2.34.
42 Debian 12 provides 2.36, so there is headroom, but a future dependency can pull
43 in newer symbol versions. The `readelf` ceiling check is mandatory, not
44 advisory — without it the failure appears only on the i686 machine.
45- Distribution is a binary plus its glibc, not a single file to `scp` anywhere.
46 Accepted: the target is a known Debian 12 box, not an unknown fleet.
47- `ring`/`rustls` stay available, so the dependency tree is unconstrained.
48- If the target later turns out to be older than glibc 2.34, or a second target
49 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 @@
1# 0002 — Sessions are append-only wire transcripts; history is never rewritten
2
3**Status:** accepted
4
5## Context
6
7Two forces meet in the session format.
8
9The first is cost. The provider bills cached prompt reads at roughly 1/50th of
10input price (DeepSeek V4.1 Flash: $0.003/M cached vs $0.15/M input). Cache hits
11depend on the request prefix being byte-identical to the previous request. The
12prefix is the system prompt, the tool schemas, and the message history — so any
13edit to an earlier message invalidates the cache for everything after it and
14re-bills the whole context.
15
16The second is fidelity. The model's next step depends on what it actually said
17and what the tools actually returned, so the stored history has to reproduce the
18wire messages exactly: `reasoning_content` from a reasoning model must not be
19sent back (wasted tokens at best, a 400 at worst on DeepSeek-style backends),
20and tool-call arguments must round-trip as the original JSON string rather than
21being parsed and re-serialised, which can reorder keys and change whitespace.
22
23Summarising old turns, truncating old tool output, and dropping old messages all
24solve context exhaustion, and all of them rewrite the prefix. They are
25incompatible with cache stability.
26
27## Decision
28
29Store each session as **append-only JSONL of wire-level messages**, replayed
30verbatim. No compaction, no truncation, no summarisation, no sliding window.
31
32- `reasoning_content` is stored (for the human to read) and stripped on replay.
33- Tool-call arguments are stored and replayed as the original JSON string.
34- The system prompt, environment block, and tool schemas are frozen at session
35 start and built from fixed-order structs — never a `HashMap`, never containing
36 session-varying values.
37- When the conversation exceeds the model's context window, the provider returns
38 an error, the turn ends, and the user is told to start a new session.
39
40## Consequences
41
42- Prompt caching stays warm for the life of a session, which is the dominant cost
43 factor on a $10/month plan.
44- Resuming a session is exact: replay the file and continue. No reconstruction
45 logic, no "the summary forgot the decision from ten turns ago".
46- Long sessions have a hard ceiling and cannot be extended. The only remedy is a
47 new session, which loses the conversation. Accepted: with 128k-class windows
48 this is a rare event, and the failure is loud rather than silent.
49- Session files grow without bound and are never garbage-collected. Accepted.
50- Any future feature that wants to show a compacted view of history must render
51 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 @@
1#!/usr/bin/env bash
2# Gate a release on the glibc the target actually has.
3#
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
6# only shows up as "version `GLIBC_2.38' not found" on the target machine.
7set -euo pipefail
8
9binary=${1:?usage: check-glibc.sh <binary> [ceiling, default 2.36]}
10ceiling=${2:-2.36}
11
12if [ ! -f "$binary" ]; then
13 echo "check-glibc: no such file: $binary" >&2
14 exit 2
15fi
16
17max=$(readelf -V "$binary" 2>/dev/null \
18 | grep -oE 'GLIBC_[0-9]+\.[0-9]+' \
19 | sed 's/^GLIBC_//' \
20 | sort -Vu \
21 | tail -1 || true)
22
23if [ -z "${max:-}" ]; then
24 echo "check-glibc: no versioned symbols (statically linked?) — nothing to check"
25 exit 0
26fi
27
28echo "check-glibc: max symbol version GLIBC_$max, ceiling GLIBC_$ceiling"
29
30if [ "$(printf '%s\n%s\n' "$ceiling" "$max" | sort -V | tail -1)" != "$ceiling" ]; then
31 echo "check-glibc: FAIL — binary needs GLIBC_$max, target has GLIBC_$ceiling" >&2
32 exit 1
33fi
34
35echo "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 @@
1#!/usr/bin/env python3
2"""A canned OpenAI-compatible SSE provider for manual testing.
3
4No API key, no network, no quota. Streams a reasoning delta, a text answer and
5a usage frame, with a small pause between them so the renderer can be seen
6working incrementally.
7
8 scripts/mock-provider.py --port 8765
9 OPENCODE_API_KEY=test ./agent686 --base-url http://127.0.0.1:8765/v1 "hi"
10"""
11import argparse
12import json
13import time
14from http.server import BaseHTTPRequestHandler, HTTPServer
15
16
17def frames(answer: str):
18 yield {"choices": [{"delta": {"reasoning_content": "The user said hi. "}}]}
19 yield {"choices": [{"delta": {"reasoning_content": "A short greeting is enough."}}]}
20 for word in answer.split(" "):
21 yield {"choices": [{"delta": {"content": word + " "}}]}
22 yield {"choices": [{"delta": {}, "finish_reason": "stop"}]}
23 yield {"choices": [], "usage": {"prompt_tokens": 24, "completion_tokens": 9}}
24
25
26class Handler(BaseHTTPRequestHandler):
27 protocol_version = "HTTP/1.0"
28
29 def do_POST(self):
30 length = int(self.headers.get("content-length") or 0)
31 self.rfile.read(length)
32
33 if self.server.status != 200:
34 body = json.dumps(
35 {
36 "error": {
37 "type": "authentication_error",
38 "code": "api_key_expired",
39 "message": "This API key has expired.",
40 }
41 }
42 ).encode()
43 self.send_response(self.server.status)
44 self.send_header("Content-Type", "application/json")
45 self.end_headers()
46 self.wfile.write(body)
47 return
48
49 self.send_response(200)
50 self.send_header("Content-Type", "text/event-stream")
51 self.send_header("Cache-Control", "no-cache")
52 self.end_headers()
53
54 for frame in frames(self.server.answer):
55 if self.server.delay:
56 time.sleep(self.server.delay)
57 self.wfile.write(f"data: {json.dumps(frame)}\n\n".encode())
58 self.wfile.flush()
59 self.wfile.write(b"data: [DONE]\n\n")
60 self.wfile.flush()
61
62 def log_message(self, fmt, *args):
63 if not self.server.quiet:
64 super().log_message(fmt, *args)
65
66
67def main():
68 parser = argparse.ArgumentParser()
69 parser.add_argument("--port", type=int, default=8765)
70 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")
72 parser.add_argument("--answer", default="Hello from the mock provider.")
73 parser.add_argument("--quiet", action="store_true")
74 args = parser.parse_args()
75
76 server = HTTPServer(("127.0.0.1", args.port), Handler)
77 server.answer = args.answer
78 server.delay = args.delay
79 server.status = args.status
80 server.quiet = args.quiet
81 print(f"mock provider on http://127.0.0.1:{args.port}/v1", flush=True)
82 server.serve_forever()
83
84
85if __name__ == "__main__":
86 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 @@
1use std::sync::atomic::AtomicBool;
2
3use serde_json::{json, Value};
4
5use crate::config::Config;
6use crate::provider::{self, Error, Outcome, Sink};
7
8/// Frozen for the life of the process. Anything session-varying added here
9/// invalidates the provider's prompt cache, so keep it boring.
10pub fn system_message() -> Value {
11 json!({
12 "role": "system",
13 "content": "You are agent686, a coding agent working in a Unix terminal. \
14 You edit files and run commands. Be terse and do not explain \
15 what you are about to do before doing it."
16 })
17}
18
19/// Appends the user message, runs one provider round trip, and appends the
20/// assistant message to the history whether or not it asked for tools.
21pub fn run_turn(
22 cfg: &Config,
23 history: &mut Vec<Value>,
24 prompt: &str,
25 cancel: &AtomicBool,
26 sink: &mut dyn Sink,
27) -> Result<Outcome, Error> {
28 history.push(json!({ "role": "user", "content": prompt }));
29
30 let outcome = provider::chat(cfg, history, cancel, sink)?;
31
32 let mut message = serde_json::Map::new();
33 message.insert("role".into(), json!("assistant"));
34 message.insert(
35 "content".into(),
36 if outcome.content.is_empty() {
37 Value::Null
38 } else {
39 json!(outcome.content)
40 },
41 );
42 if !outcome.tool_calls.is_empty() {
43 let calls: Vec<Value> = outcome
44 .tool_calls
45 .iter()
46 .map(|call| {
47 json!({
48 "id": call.id,
49 "type": "function",
50 "function": {
51 "name": call.name,
52 // Byte-for-byte what the model sent.
53 "arguments": call.arguments,
54 }
55 })
56 })
57 .collect();
58 message.insert("tool_calls".into(), Value::Array(calls));
59 }
60 history.push(Value::Object(message));
61
62 Ok(outcome)
63}
64
65pub fn new_history() -> Vec<Value> {
66 vec![system_message()]
67}
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 @@
1use std::path::PathBuf;
2
3pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1";
4pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash";
5
6#[derive(Debug, Clone)]
7pub struct Config {
8 pub base_url: String,
9 pub api_key: String,
10 pub model: String,
11 pub session: String,
12}
13
14impl Config {
15 /// CLI flags win over environment variables, which win over defaults.
16 pub fn resolve(
17 model: Option<String>,
18 base_url: Option<String>,
19 session: Option<String>,
20 ) -> Result<Config, String> {
21 Ok(Config {
22 api_key: api_key()?,
23 base_url: base_url
24 .or_else(|| env_nonempty("AGENT686_BASE_URL"))
25 .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
26 model: model
27 .or_else(|| env_nonempty("AGENT686_MODEL"))
28 .unwrap_or_else(|| DEFAULT_MODEL.to_string()),
29 session: session.unwrap_or_else(crate::session::new_id),
30 })
31 }
32
33 pub fn endpoint(&self) -> String {
34 format!("{}/chat/completions", self.base_url.trim_end_matches('/'))
35 }
36}
37
38fn env_nonempty(key: &str) -> Option<String> {
39 std::env::var(key).ok().filter(|v| !v.trim().is_empty())
40}
41
42/// 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.
44fn api_key() -> Result<String, String> {
45 if let Some(k) = env_nonempty("OPENCODE_API_KEY") {
46 return Ok(k.trim().to_string());
47 }
48 if let Some(path) = key_file() {
49 if let Ok(k) = std::fs::read_to_string(&path) {
50 let k = k.trim().to_string();
51 if !k.is_empty() {
52 return Ok(k);
53 }
54 }
55 }
56 Err(format!(
57 "no API key: set OPENCODE_API_KEY or write one to {}",
58 key_file()
59 .map(|p| p.display().to_string())
60 .unwrap_or_else(|| "~/.config/agent686/key".into())
61 ))
62}
63
64fn key_file() -> Option<PathBuf> {
65 let home = std::env::var_os("HOME")?;
66 Some(PathBuf::from(home).join(".config/agent686/key"))
67}
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 @@
1pub mod agent;
2pub mod config;
3pub mod provider;
4pub mod session;
5pub 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 @@
1use std::io::{BufRead, IsTerminal, Write};
2use std::sync::atomic::AtomicBool;
3
4use agent686::{agent, config::Config, ui};
5
6const HELP: &str = "\
7agent686 — a small coding agent
8
9USAGE:
10 agent686 [OPTIONS] [PROMPT...]
11
12With a prompt it runs one turn and exits; without one it reads prompts from
13stdin, one per line. /exit quits.
14
15OPTIONS:
16 -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
18 --session <ID> reuse a session id, including for the provider header
19 -h, --help this text
20
21ENVIRONMENT:
22 OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key)
23 AGENT686_MODEL default model id
24 AGENT686_BASE_URL default provider base URL
25";
26
27fn main() {
28 let mut prompt: Option<String> = None;
29 let mut model = None;
30 let mut base_url = None;
31 let mut session = None;
32
33 let mut args = std::env::args().skip(1);
34 while let Some(arg) = args.next() {
35 match arg.as_str() {
36 "-m" | "--model" => model = args.next(),
37 "--base-url" => base_url = args.next(),
38 "--session" => session = args.next(),
39 "-h" | "--help" => {
40 print!("{HELP}");
41 return;
42 }
43 flag if flag.starts_with('-') && flag.len() > 1 => {
44 eprintln!("agent686: unknown flag {flag}\n");
45 print!("{HELP}");
46 std::process::exit(2);
47 }
48 word => {
49 prompt = Some(match prompt.take() {
50 Some(existing) => format!("{existing} {word}"),
51 None => word.to_string(),
52 })
53 }
54 }
55 }
56
57 let cfg = match Config::resolve(model, base_url, session) {
58 Ok(cfg) => cfg,
59 Err(message) => {
60 eprintln!("agent686: {message}");
61 std::process::exit(2);
62 }
63 };
64
65 let cancel = AtomicBool::new(false);
66 let mut history = agent::new_history();
67
68 // One-shot mode: a prompt on the command line means one turn, then exit.
69 if let Some(prompt) = prompt {
70 let mut sink = ui::Renderer::new(ui::stdout_is_tty());
71 match agent::run_turn(&cfg, &mut history, &prompt, &cancel, &mut sink) {
72 Ok(outcome) => note_tool_calls(&outcome),
73 Err(error) => {
74 eprintln!("agent686: {error}");
75 std::process::exit(1);
76 }
77 }
78 return;
79 }
80
81 let interactive = std::io::stdin().is_terminal();
82 if interactive {
83 eprintln!(
84 "agent686 · {} · session {}{}",
85 cfg.model,
86 cfg.session,
87 if is_local(&cfg.base_url) { " · local" } else { "" }
88 );
89 eprintln!("one prompt per line · /exit to quit");
90 }
91
92 let stdin = std::io::stdin();
93 let mut line = String::new();
94 loop {
95 if interactive {
96 print!("> ");
97 let _ = std::io::stdout().flush();
98 }
99 line.clear();
100 if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 {
101 break;
102 }
103 let text = line.trim_end();
104 if text.is_empty() {
105 continue;
106 }
107 if text == "/exit" || text == "/quit" {
108 break;
109 }
110 let mut sink = ui::Renderer::new(ui::stdout_is_tty());
111 match agent::run_turn(&cfg, &mut history, text, &cancel, &mut sink) {
112 Ok(outcome) => note_tool_calls(&outcome),
113 Err(error) => eprintln!("agent686: {error}"),
114 }
115 }
116}
117
118fn note_tool_calls(outcome: &agent686::provider::Outcome) {
119 if outcome.tool_calls.is_empty() {
120 return;
121 }
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}
133
134fn is_local(base_url: &str) -> bool {
135 base_url.contains("127.0.0.1") || base_url.contains("localhost")
136}
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 @@
1use std::io::Read;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::{Duration, Instant};
4
5use serde::Deserialize;
6use serde_json::Value;
7
8use crate::config::Config;
9
10#[derive(Debug)]
11pub enum Error {
12 Transport(String),
13 Status { code: u16, message: String },
14 Aborted,
15}
16
17impl std::fmt::Display for Error {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 match self {
20 Error::Transport(m) => write!(f, "{m}"),
21 Error::Status { code, message } => write!(f, "HTTP {code}: {message}"),
22 Error::Aborted => write!(f, "aborted"),
23 }
24 }
25}
26
27impl std::error::Error for Error {}
28
29/// One completed tool call, assembled from streamed deltas.
30#[derive(Debug, Default, Clone)]
31pub struct ToolCall {
32 pub index: usize,
33 pub id: String,
34 pub name: String,
35 /// The argument JSON exactly as the model emitted it. Never re-serialised:
36 /// re-encoding can change key order and invalidate the provider's cache.
37 pub arguments: String,
38}
39
40#[derive(Debug, Default)]
41pub struct Outcome {
42 pub content: String,
43 pub reasoning: String,
44 pub tool_calls: Vec<ToolCall>,
45 pub finish: Option<String>,
46 pub usage: Option<Value>,
47 pub opencode: Option<Value>,
48}
49
50pub trait Sink {
51 fn text(&mut self, s: &str);
52 fn reasoning(&mut self, s: &str);
53 fn done(&mut self, outcome: &Outcome, elapsed: Duration);
54}
55
56/// Decodes an SSE byte stream into `data:` payloads.
57///
58/// Kept as a state machine so that chunk boundaries can fall anywhere: inside a
59/// line, or inside a multi-byte UTF-8 character. Only complete lines are ever
60/// converted to text.
61#[derive(Default)]
62pub struct SseDecoder {
63 buf: Vec<u8>,
64}
65
66impl SseDecoder {
67 pub fn new() -> Self {
68 Self::default()
69 }
70
71 pub fn feed(&mut self, chunk: &[u8]) -> Vec<String> {
72 self.buf.extend_from_slice(chunk);
73 let mut out = Vec::new();
74 let mut start = 0;
75 while let Some(rel) = self.buf[start..].iter().position(|&b| b == b'\n') {
76 let end = start + rel;
77 let mut line = &self.buf[start..end];
78 if line.last() == Some(&b'\r') {
79 line = &line[..line.len() - 1];
80 }
81 start = end + 1;
82 if let Some(payload) = line.strip_prefix(b"data:") {
83 let payload = payload.strip_prefix(b" ").unwrap_or(payload);
84 out.push(String::from_utf8_lossy(payload).into_owned());
85 }
86 }
87 self.buf.drain(..start);
88 out
89 }
90}
91
92pub fn chat(
93 cfg: &Config,
94 messages: &[Value],
95 cancel: &AtomicBool,
96 sink: &mut dyn Sink,
97) -> Result<Outcome, Error> {
98 // serde_json::Value is ordered by key, not by insertion, so the serialised
99 // bytes are stable for the same input. That is what keeps the cache warm;
100 // do not switch this to a struct with fields in a different order, and do
101 // not add anything session-varying to the system message.
102 let body = serde_json::json!({
103 "model": cfg.model,
104 "messages": messages,
105 "stream": true,
106 "stream_options": { "include_usage": true },
107 });
108 let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?;
109
110 let agent: ureq::Agent = ureq::Agent::config_builder()
111 .http_status_as_error(false)
112 .timeout_connect(Some(Duration::from_secs(10)))
113 .timeout_recv_response(Some(Duration::from_secs(180)))
114 .timeout_per_read(Some(Duration::from_secs(180)))
115 .build()
116 .into();
117
118 let started = Instant::now();
119 let mut resp = agent
120 .post(&cfg.endpoint())
121 .header("Content-Type", "application/json")
122 .header("Accept", "text/event-stream")
123 .header("Authorization", format!("Bearer {}", cfg.api_key))
124 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION")))
125 // Required by OpenCode Go: stable per conversation, used for routing and
126 // prompt caching.
127 .header("x-opencode-session", &cfg.session)
128 .send(bytes)
129 .map_err(|e| Error::Transport(e.to_string()))?;
130
131 let status = resp.status().as_u16();
132 if !(200..300).contains(&status) {
133 let text = resp
134 .body_mut()
135 .with_config()
136 .limit(256 * 1024)
137 .read_to_string()
138 .unwrap_or_default();
139 return Err(Error::Status {
140 code: status,
141 message: error_message(&text),
142 });
143 }
144
145 let mut outcome = Outcome::default();
146 let mut decoder = SseDecoder::new();
147 let mut buf = [0u8; 8192];
148 let mut reader = resp.body_mut().as_reader();
149 let mut done = false;
150
151 while !done {
152 // Blocking reads mean an abort is only noticed when bytes arrive or the
153 // per-read timeout fires. Good enough: the model streams constantly.
154 if cancel.load(Ordering::Relaxed) {
155 return Err(Error::Aborted);
156 }
157 let n = match reader.read(&mut buf) {
158 Ok(0) => break,
159 Ok(n) => n,
160 Err(e) => return Err(Error::Transport(e.to_string())),
161 };
162 for data in decoder.feed(&buf[..n]) {
163 if data.is_empty() {
164 continue;
165 }
166 if data.trim() == "[DONE]" {
167 done = true;
168 break;
169 }
170 let chunk: Chunk = match serde_json::from_str(&data) {
171 Ok(c) => c,
172 // A malformed frame is dropped rather than killing the turn; the
173 // stream is the only recovery path and it is still valid SSE.
174 Err(_) => continue,
175 };
176 apply_chunk(&chunk, &mut outcome, sink);
177 }
178 }
179
180 if let Some(usage) = &outcome.usage {
181 if usage.is_null() {
182 outcome.usage = None;
183 }
184 }
185 if let Some(opencode) = &outcome.opencode {
186 if opencode.is_null() {
187 outcome.opencode = None;
188 }
189 }
190
191 sink.done(&outcome, started.elapsed());
192 Ok(outcome)
193}
194
195fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) {
196 if let Some(usage) = &chunk.usage {
197 outcome.usage = Some(usage.clone());
198 }
199 if let Some(opencode) = &chunk.opencode {
200 outcome.opencode = Some(opencode.clone());
201 }
202 for choice in &chunk.choices {
203 if let Some(r) = &choice.delta.reasoning_content {
204 if !r.is_empty() {
205 outcome.reasoning.push_str(r);
206 sink.reasoning(r);
207 }
208 }
209 if let Some(t) = &choice.delta.content {
210 if !t.is_empty() {
211 outcome.content.push_str(t);
212 sink.text(t);
213 }
214 }
215 if let Some(calls) = &choice.delta.tool_calls {
216 for call in calls {
217 accumulate_tool_call(&mut outcome.tool_calls, call);
218 }
219 }
220 if let Some(finish) = &choice.finish_reason {
221 outcome.finish = Some(finish.clone());
222 }
223 }
224}
225
226/// Tool call deltas arrive split across chunks and are keyed by `index`: the
227/// name and id usually come once, the arguments a fragment at a time.
228fn accumulate_tool_call(calls: &mut Vec<ToolCall>, delta: &ToolCallDelta) {
229 while calls.len() <= delta.index {
230 let index = calls.len();
231 calls.push(ToolCall {
232 index,
233 id: String::new(),
234 name: String::new(),
235 arguments: String::new(),
236 });
237 }
238 let call = &mut calls[delta.index];
239 if let Some(id) = &delta.id {
240 call.id.push_str(id);
241 }
242 if let Some(function) = &delta.function {
243 if let Some(name) = &function.name {
244 call.name.push_str(name);
245 }
246 if let Some(args) = &function.arguments {
247 call.arguments.push_str(args);
248 }
249 }
250}
251
252fn error_message(body: &str) -> String {
253 if let Ok(v) = serde_json::from_str::<Value>(body) {
254 if let Some(err) = v.get("error") {
255 if let Some(message) = err.get("message").and_then(|m| m.as_str()) {
256 return match err.get("code").and_then(|c| c.as_str()) {
257 Some(code) if !code.is_empty() => format!("{message} ({code})"),
258 _ => message.to_string(),
259 };
260 }
261 }
262 if let Some(message) = v.get("message").and_then(|m| m.as_str()) {
263 return message.to_string();
264 }
265 }
266 truncate(body.trim(), 500)
267}
268
269fn truncate(s: &str, max: usize) -> String {
270 match s.char_indices().nth(max) {
271 Some((i, _)) => format!("{}…", &s[..i]),
272 None => s.to_string(),
273 }
274}
275
276#[derive(Debug, Deserialize)]
277struct Chunk {
278 #[serde(default)]
279 choices: Vec<Choice>,
280 #[serde(default)]
281 usage: Option<Value>,
282 #[serde(default)]
283 opencode: Option<Value>,
284}
285
286#[derive(Debug, Deserialize)]
287struct Choice {
288 #[serde(default)]
289 delta: Delta,
290 #[serde(default)]
291 finish_reason: Option<String>,
292}
293
294#[derive(Debug, Default, Deserialize)]
295struct Delta {
296 #[serde(default)]
297 content: Option<String>,
298 #[serde(default)]
299 reasoning_content: Option<String>,
300 #[serde(default)]
301 tool_calls: Option<Vec<ToolCallDelta>>,
302}
303
304#[derive(Debug, Deserialize)]
305struct ToolCallDelta {
306 index: usize,
307 #[serde(default)]
308 id: Option<String>,
309 #[serde(default)]
310 function: Option<FunctionDelta>,
311}
312
313#[derive(Debug, Deserialize)]
314struct FunctionDelta {
315 #[serde(default)]
316 name: Option<String>,
317 #[serde(default)]
318 arguments: Option<String>,
319}
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 @@
1use std::hash::{Hash, Hasher};
2use std::io::Read;
3use std::time::{SystemTime, UNIX_EPOCH};
4
5/// 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
7/// it usable as a file name.
8pub fn new_id() -> String {
9 let mut bytes = random_bytes();
10 // Put the creation time in the first bytes so ids sort roughly by age.
11 let ms = SystemTime::now()
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
17 let mut out = String::with_capacity(32);
18 for b in bytes {
19 out.push_str(&format!("{b:02x}"));
20 }
21 out
22}
23
24fn random_bytes() -> [u8; 16] {
25 let mut bytes = [0u8; 16];
26 if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
27 if f.read_exact(&mut bytes).is_ok() {
28 return bytes;
29 }
30 }
31 // Fallback: not cryptographic, but an id only has to not collide.
32 let mut h = std::collections::hash_map::DefaultHasher::new();
33 SystemTime::now().hash(&mut h);
34 std::process::id().hash(&mut h);
35 let v = h.finish();
36 bytes[..8].copy_from_slice(&v.to_be_bytes());
37 bytes[8..].copy_from_slice(&(v ^ 0x9e37_79b9_7f4a_7c15).to_be_bytes());
38 bytes
39}
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 @@
1use std::io::{IsTerminal, Write};
2use std::time::Duration;
3
4use crate::provider::{Outcome, Sink};
5
6pub fn stdout_is_tty() -> bool {
7 std::io::stdout().is_terminal()
8}
9
10/// Streams to stdout. Colour is used only when stdout is a terminal, so piping
11/// the output somewhere gives clean text.
12pub struct Renderer {
13 color: bool,
14 dimmed: bool,
15 wrote_text: bool,
16}
17
18impl Renderer {
19 pub fn new(color: bool) -> Self {
20 Self {
21 color,
22 dimmed: false,
23 wrote_text: false,
24 }
25 }
26
27 fn undim(&mut self) {
28 if self.dimmed {
29 print!("\x1b[0m");
30 self.dimmed = false;
31 }
32 }
33}
34
35impl Sink for Renderer {
36 fn text(&mut self, s: &str) {
37 self.undim();
38 print!("{s}");
39 let _ = std::io::stdout().flush();
40 self.wrote_text = true;
41 }
42
43 fn reasoning(&mut self, s: &str) {
44 if !self.color {
45 return;
46 }
47 if !self.dimmed {
48 print!("\x1b[2m");
49 self.dimmed = true;
50 }
51 print!("{s}");
52 let _ = std::io::stdout().flush();
53 }
54
55 fn done(&mut self, outcome: &Outcome, elapsed: Duration) {
56 self.undim();
57 if self.wrote_text {
58 println!();
59 }
60 let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())];
61 if let Some(usage) = &outcome.usage {
62 let input = usage.get("prompt_tokens").and_then(|v| v.as_u64());
63 let output = usage.get("completion_tokens").and_then(|v| v.as_u64());
64 if let (Some(i), Some(o)) = (input, output) {
65 parts.push(format!("{i} in · {o} out"));
66 }
67 }
68 let line = format!("─ {}", parts.join(" · "));
69 if self.color {
70 println!("\x1b[2m{line}\x1b[0m");
71 } else {
72 println!("{line}");
73 }
74 }
75}
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 @@
1use std::io::{BufRead, BufReader, Read, Write};
2use std::net::TcpListener;
3use std::sync::atomic::AtomicBool;
4use std::sync::mpsc;
5use std::thread;
6use std::time::Duration;
7
8use serde_json::json;
9
10use agent686::config::Config;
11use agent686::provider::{self, Error, Outcome, Sink};
12
13#[derive(Default)]
14struct Collector {
15 text: String,
16 reasoning: String,
17 finished: bool,
18}
19
20impl Sink for Collector {
21 fn text(&mut self, s: &str) {
22 self.text.push_str(s);
23 }
24 fn reasoning(&mut self, s: &str) {
25 self.reasoning.push_str(s);
26 }
27 fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) {
28 self.finished = true;
29 }
30}
31
32/// Serves exactly one request on a random port, then closes. Returns the base
33/// URL and a receiver for the request as the client sent it.
34fn serve_once(response: &'static str) -> (String, mpsc::Receiver<String>) {
35 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
36 let addr = listener.local_addr().unwrap();
37 let (tx, rx) = mpsc::channel();
38
39 thread::spawn(move || {
40 let (mut stream, _) = listener.accept().unwrap();
41 let mut reader = BufReader::new(stream.try_clone().unwrap());
42
43 let mut request = String::new();
44 let mut content_length = 0usize;
45 loop {
46 let mut line = String::new();
47 if reader.read_line(&mut line).unwrap_or(0) == 0 {
48 break;
49 }
50 if line == "\r\n" || line == "\n" {
51 break;
52 }
53 if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") {
54 content_length = value.trim().parse().unwrap_or(0);
55 }
56 request.push_str(&line);
57 }
58 let mut body = vec![0u8; content_length];
59 let _ = reader.read_exact(&mut body);
60 request.push_str(&String::from_utf8_lossy(&body));
61 let _ = tx.send(request);
62
63 let _ = stream.write_all(response.as_bytes());
64 let _ = stream.flush();
65 });
66
67 (format!("http://{addr}"), rx)
68}
69
70fn config(base_url: String) -> Config {
71 Config {
72 base_url,
73 api_key: "test-key".into(),
74 model: "test-model".into(),
75 session: "testsession".into(),
76 }
77}
78
79#[test]
80fn streams_text_reasoning_and_usage() {
81 const SSE: &str = concat!(
82 "HTTP/1.1 200 OK\r\n",
83 "Content-Type: text/event-stream\r\n",
84 "Connection: close\r\n",
85 "\r\n",
86 "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}\n\n",
87 "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n",
88 "data: {\"choices\":[{\"delta\":{\"content\":\" from mock\"},\"finish_reason\":\"stop\"}]}\n\n",
89 "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2}}\n\n",
90 "data: [DONE]\n\n",
91 );
92 let (base, rx) = serve_once(SSE);
93 let mut sink = Collector::default();
94 let outcome = provider::chat(
95 &config(base),
96 &[json!({ "role": "user", "content": "hi" })],
97 &AtomicBool::new(false),
98 &mut sink,
99 )
100 .expect("chat should succeed");
101
102 assert_eq!(outcome.content, "Hello from mock");
103 assert_eq!(outcome.reasoning, "thinking");
104 assert_eq!(sink.text, "Hello from mock");
105 assert_eq!(sink.reasoning, "thinking");
106 assert!(sink.finished);
107 assert_eq!(outcome.usage.unwrap()["completion_tokens"], 2);
108
109 let request = rx.recv().unwrap().to_ascii_lowercase();
110 assert!(
111 request.contains("x-opencode-session: testsession"),
112 "session header missing from request:\n{request}"
113 );
114 assert!(request.contains("user-agent: agent686/"));
115 assert!(request.contains("\"stream\":true"));
116 assert!(request.contains("\"include_usage\":true"));
117}
118
119#[test]
120fn assembles_tool_call_arguments_byte_for_byte() {
121 const SSE: &str = concat!(
122 "HTTP/1.1 200 OK\r\n",
123 "Content-Type: text/event-stream\r\n",
124 "Connection: close\r\n",
125 "\r\n",
126 "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\"}}]}}]}\n\n",
127 "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\"a.txt\\\"}\"}}]}}]}\n\n",
128 "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
129 "data: [DONE]\n\n",
130 );
131 let (base, _rx) = serve_once(SSE);
132 let mut sink = Collector::default();
133 let outcome = provider::chat(
134 &config(base),
135 &[json!({ "role": "user", "content": "read a.txt" })],
136 &AtomicBool::new(false),
137 &mut sink,
138 )
139 .expect("chat should succeed");
140
141 assert_eq!(outcome.tool_calls.len(), 1);
142 let call = &outcome.tool_calls[0];
143 assert_eq!(call.id, "call_1");
144 assert_eq!(call.name, "read");
145 assert_eq!(call.arguments, r#"{"path":"a.txt"}"#);
146 assert_eq!(outcome.finish.as_deref(), Some("tool_calls"));
147}
148
149#[test]
150fn surfaces_provider_error_text() {
151 const RESPONSE: &str = concat!(
152 "HTTP/1.1 401 Unauthorized\r\n",
153 "Content-Type: application/json\r\n",
154 "Connection: close\r\n",
155 "\r\n",
156 "{\"error\":{\"type\":\"authentication_error\",\"code\":\"api_key_expired\",",
157 "\"message\":\"This API key has expired.\"}}",
158 );
159 let (base, _rx) = serve_once(RESPONSE);
160 let mut sink = Collector::default();
161 let error = provider::chat(
162 &config(base),
163 &[json!({ "role": "user", "content": "hi" })],
164 &AtomicBool::new(false),
165 &mut sink,
166 )
167 .expect_err("should fail");
168
169 match error {
170 Error::Status { code, message } => {
171 assert_eq!(code, 401);
172 assert!(message.contains("This API key has expired."), "{message}");
173 assert!(message.contains("api_key_expired"), "{message}");
174 }
175 other => panic!("unexpected error: {other:?}"),
176 }
177}
178
179#[test]
180fn honours_a_cancelled_turn() {
181 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";
182 let (base, _rx) = serve_once(SSE);
183 let mut sink = Collector::default();
184 let error = provider::chat(
185 &config(base),
186 &[json!({ "role": "user", "content": "hi" })],
187 &AtomicBool::new(true),
188 &mut sink,
189 )
190 .expect_err("cancelled turn should abort");
191 assert!(matches!(error, Error::Aborted));
192}
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 @@
1use agent686::provider::SseDecoder;
2
3#[test]
4fn reassembles_lines_split_at_every_byte() {
5 // Fed one byte at a time, so the decoder sees a split after every character,
6 // including in the middle of the multi-byte ones.
7 let wire = "data: {\"a\":\"café ✓\"}\n\ndata: [DONE]\n\n";
8 let mut decoder = SseDecoder::new();
9 let mut got = Vec::new();
10 for byte in wire.as_bytes() {
11 got.extend(decoder.feed(std::slice::from_ref(byte)));
12 }
13 assert_eq!(got, vec!["{\"a\":\"café ✓\"}".to_string(), "[DONE]".to_string()]);
14}
15
16#[test]
17fn handles_crlf_comments_and_event_lines() {
18 let wire = ": keep-alive\r\nevent: message\r\ndata:{\"x\":1}\r\n\r\n";
19 let mut decoder = SseDecoder::new();
20 let got = decoder.feed(wire.as_bytes());
21 assert_eq!(got, vec!["{\"x\":1}".to_string()]);
22}
23
24#[test]
25fn keeps_incomplete_line_until_finished() {
26 let mut decoder = SseDecoder::new();
27 assert!(decoder.feed(b"data: {\"x\"").is_empty());
28 assert!(decoder.feed(b":1}").is_empty());
29 assert_eq!(
30 decoder.feed(b"\n"),
31 vec!["{\"x\":1}".to_string()]
32 );
33}
34
35#[test]
36fn ignores_non_data_lines() {
37 let mut decoder = SseDecoder::new();
38 let got = decoder.feed(b"id: 1\nretry: 2000\n\n");
39 assert!(got.is_empty());
40}