aboutsummaryrefslogtreecommitdiffstats
path: root/docs
diff options
context:
space:
mode:
Diffstat (limited to 'docs')
-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
3 files changed, 237 insertions, 0 deletions
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.