summaryrefslogtreecommitdiffstats
path: root/docs/PLAN.md
blob: f22b2300815ad1a74cadf442f782b52f4d1f74e6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# 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/<version>`, 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 number printed on every tool line, the allowance in 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, one environment
  line (cwd, platform, arch, git branch), and `AGENTS.md` from cwd up to the git
  root — never above it, and only the working directory outside a repository.
  Frozen for the session; the session records the starting directory and warns if
  resumed elsewhere; an mtime change prints a notice only.
- **UI.** Line-mode. ANSI only when stdout is a TTY, and disabled by `NO_COLOR`
  or `TERM=dumb`. A small raw-mode line editor: arrow-key history persisted to
  disk, bracketed paste as one block, ctrl-a/e/u/k/w editing, ctrl-c abandons the
  line, ctrl-d exits. Raw mode is on only while a prompt is being read, so Ctrl-C
  during a turn stays a signal. No alt-screen, 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.** ✅ Done.

JSONL append/load, session id, `--continue`, `--session <id>`, status line,
SIGINT handling (first Ctrl-C aborts the turn, second exits). Verified: a
9-step turn writes 19 lines (header + 18 messages, reasoning stored under
`_reasoning`), `--continue` replays all 18 messages and answers from history
without reading files.

**M2 — Read-side tools and edits.** ✅ Done.

`read`, `write`, `edit`, `grep`, `glob`, the agent loop, tool-call accumulation,
diff preview plus approval. Verified by `tests/tools.rs` (uniqueness, ambiguity
with line numbers, no implicit `mkdir`, truncation, glob `**`, grep case) and
`tests/loop.rs` (tool call executed and recorded; a denial returned as data).
The approval prompt was also driven through a real pty.

**M3 — `bash`.** ✅ Done.

Fresh shell per call, 120 s timeout that kills the process, capped output
(64 KiB head, 16 KiB tail), exit code or signal reported. Verified: exit codes,
timeout, missing `cwd`, and real `gcc` invocations.

**M4 — Prompt and input.** ✅ Done.

System prompt with cwd/platform/arch/branch, `AGENTS.md` snapshot frozen at
session start with a change warning, `/paste`, TTY-aware colour. Verified
against the live API: streaming, tool calls, `reasoning_content`, usage and
`opencode.allowance` in the final chunk, and a 401 surfaced as
`api_key_expired`.

**M5 — Target gate.** ✅ Done.

`scripts/check-glibc.sh` (required symbols ≤ 2.36; weak symbols such as glibc
2.39's `pidfd_spawnp` are reported but ignored, since they resolve to NULL).
2.0 MB stripped i686 binary, `GLIBC_2.34` required. Verified by running the
whole acceptance test inside `--platform linux/386 debian:12`.

**M6 — Robustness.** ✅ Done.

- Retries on 408/425/429/500/502/503/504 and on transport errors: four attempts,
  1 s / 2 s / 4 s backoff, `Retry-After` honoured, and the backoff is
  interruptible so Ctrl-C does not wait it out.
- Provider errors explain themselves: context overflow says to start a new
  session, 401/403 says where the key lives, 429 points at the plan limit and
  `--model`.
- `--list` shows id, model, message count and age; `--session <id>` creates the
  session when the id is new instead of erroring.

Probed against the live gateway: `x-opencode-session` is mandatory (400
`MissingSessionID` without it); two consecutive user messages are accepted, so a
turn that failed after writing its prompt can be resumed without editing the
transcript; and `deepseek-v4.1-flash` accepted a 500k-token prompt, so the
context ceiling is far higher than the 128k the plan assumed.

**M7 — Input editor.** ✅ Done.

Replaces plain `read_line` behind the same seam. `crossterm` raw mode is enabled
only while a prompt is being read, so Ctrl-C during a turn is still a signal and
the double-Ctrl-C exit keeps working.

- Up/down history, persisted to `~/.local/share/agent686/history`, capped at 200
  entries, with prompt-mode commands excluded and newlines escaped per record.
- Bracketed paste arrives as one block, including newlines: pasting a stack trace
  is one prompt, not thirty.
- Editing: left/right/home/end, backspace/delete, ctrl-a/e/u/k/w. Ctrl-C abandons
  the line, Ctrl-D exits. Ctrl-J submits too, so pipes and test harnesses work.
- Redraw moves up by the number of rows the previous buffer occupied, which
  needed a correct terminal width: a pty that reports 0 columns is treated as 80,
  not as 1 (treating it as 1 made every character wrap onto its own line).
- Non-TTY stdin still falls back to plain line reading.

## 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.

Two runs, both with `--yolo`:

| Where | Steps | Wall | Allowance | Result |
|---|---|---|---|---|
| x86-64 dev host | 9 | 55.7 s | $0.000214 | `calc.c` (115 lines), clean `-Wall -Wextra` build, 18 cases tested |
| `linux/386 debian:12` | 8 | 32.1 s | $0.000182 | `calc.c` + `Makefile`, `3 + 4 = 7`, `7 / 2 = 3.5`, `5 / 0` → error, exit 1 |

Independently rebuilt and re-run outside the agent both times.

## Layout

```
src/main.rs        args, mode selection, exit codes, /paste
src/config.rs      precedence CLI > env > file; key source
src/provider.rs    request construction, retry, SSE parsing, model list
src/session.rs     id, JSONL append/load/replay, listing, permissions
src/agent.rs       turn/step loop, tool dispatch, approval hooks, prompt
src/line.rs        raw-mode line editor, history
src/signal.rs      SIGINT -> cancel flag
src/doctor.rs      --doctor checks
src/tools/         read, write, edit, bash, grep, glob
src/ui.rs          streaming render, diffs, approval prompt, status line
tests/mock.rs      provider over std TcpListener (SSE, retry, truncation)
tests/loop.rs      agent loop, abort and repair invariants
tests/tools.rs     tool semantics and edge cases
tests/sessions.rs  session round-trip, listing, permissions
tests/cli.rs       argument validation and exit codes
tests/doctor.rs    --doctor against a mock provider
tests/sse.rs       decoder at every byte boundary
tests/prompt.rs    instruction scope
scripts/check-glibc.sh, scripts/mock-provider.py
```

## Settled against the live API

1. `stream_options: {"include_usage": true}` is honoured; usage arrives in the
   chunk that carries `finish_reason`. ✅
2. Accounting is nested: `usage.opencode.allowance` and `.list_cost`. ✅
3. `reasoning_content` is the delta field. ✅
4. `x-opencode-session` is mandatory: without it the gateway answers 400
   `MissingSessionID`. Any opaque stable id works. ✅
5. Two consecutive user messages are accepted, so a turn that failed after
   writing its prompt can be resumed without editing the transcript. ✅
6. The default model accepted a 500k-token prompt, so overflow is rarer than
   assumed. The exact limit is unknown and deliberately not modelled. ✅
7. `reasoning_effort`: not sent; unverified.