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 --- docs/PLAN.md | 137 ++++++++++++++++++++++++++++++++++ docs/adr/0001-dynamic-glibc-i686.md | 49 ++++++++++++ docs/adr/0002-append-only-sessions.md | 51 +++++++++++++ 3 files changed, 237 insertions(+) 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 (limited to 'docs') 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. -- cgit v1.2.3