@@ -2,354 +2,89 @@
22
33 A fast, transparent, config-first terminal coding agent for one user at a time.
44
5-This document records the intent and the decisions behind the code. The code is
6-the source of truth for behavior; this is the contract for anyone changing it.
5+This file holds intent, direction, and guardrails — not a description of the
6+code. The source is the source of truth for behavior. If a fact can be learned
7+by reading the code, it does not belong here; keep this file short.
78
89 ## Intent
910
10-- A small, auditable agent core with no hidden machinery.
11+- A small, auditable core with no hidden machinery.
1112 - A minimal system prompt with no injected meta-guidance.
1213 - Provider work delegated entirely to `pi-ai`.
1314 - Durable, user-owned, readable session logs.
14-- An append-only TUI with a small bounded live region and no full-screen buffer.
15-- First-class local (Ollama / llama.cpp / vLLM) and hosted models on equal footing.
15+- An append-only TUI with a bounded live region and no full-screen buffer.
16+- Local models (Ollama / llama.cpp / vLLM) and hosted models treated as equals.
1617
17-Prior art is reference, not template. `x.x.x-archive` holds the previous
18-implementation; `../awl/` (append-only live-region TUI, config-driven design),
19-`../bough/` (layer boundaries), and `../agent-ide/` (session durability, streaming)
20-are references. Extract ideas, do not port code.
18+Prior art is reference, not template: `x.x.x-archive` (previous implementation),
19+`../awl/` (append-only live-region TUI), `../bough/` (layer boundaries), and
20+`../agent-ide/` (session durability, streaming). Extract ideas, do not port code.
2121
22-## Hard constraints
23-
24-- **Node.js directly.** No Bun, no Deno, no `Bun.*`, no Bun package scripts.
25- Everything must work with `node`/`npm`.
26-- **No TUI library or framework.** No `cel-tui`, `OpenTUI`, `blessed`, `Ink`, or
27- React. Render with direct `process.stdout` ANSI writes and plain strings.
28-- **`pi-ai` owns the provider layer.** All model requests, provider adapters,
29- wire formats, streaming, auth resolution, and usage accounting go through
30- `@earendil-works/pi-ai`. Never re-implement a provider protocol or fork it.
31-- **Do not copy other coding agents' source code.** Pi and `pi-ai` are behavioral references; write original code.
32-- **No sandboxing, no permission layer.** Tools run with the user's permissions.
33- Isolation is an environment concern (`nono`), not the agent's. No jail,
34- approval gate, or supervisor.
35-- **No loop limits.** No max turns, tool calls, token budgets, or agent-imposed
36- timeouts. The user's ability to interrupt is the limit.
37-- **Config-first.** Every user-facing behavior that can vary comes from config
38- with a sane default.
39-- **Minimal context.** The model sees only the configured system prompt plus
40- explicitly opted-in resource files. No doom-loop reminders, hidden
41- `<system-reminder>` blocks, internal-behavior text, or harness meta-text.
42-
43-## Runtime and repo shape
44-
45-- TypeScript, ESM, `"type": "module"`, `strict`, `erasableSyntaxOnly`,
46- `verbatimModuleSyntax`.
47-- TypeScript runs directly through Node's native type stripping (`node src/cli.ts`).
48- Use relative imports with explicit `.ts` extensions. Avoid non-erasable syntax
49- (`enum`, `namespace`, parameter properties, legacy decorators).
50-- `bin/mini-coder.ts` is a thin shebang shim importing `src/cli.ts`.
51-- Module boundaries (names may change, boundaries may not move):
52- - `cli` — argument parsing, mode selection, process wiring.
53- - `config` — load, validate, merge, resolve config; build `pi-ai` models.
54- - `session` — append-only JSONL store of `pi-ai` `Message`s.
55- - `agent` — streaming loop, tool dispatch, pause/cancel state. No UI, no
56- provider-specific code.
57- - `tools` — `edit`, `bash` runners. No UI.
58- - `prompt` — system-prompt assembly (config, skills, `AGENTS.md`).
59- - `tui` — terminal live region and input editor; a projection of agent events.
60-- The agent must not import `tui`. The TUI must not own agent or provider
61- semantics. Headless and TUI are two projections of the same agent events.
62-
63-## Configuration
64-
65-Global config only, at `$XDG_CONFIG_HOME/mini-coder/config.json`
66-(default `~/.config/mini-coder/config.json`). No project-local config, no
67-config-override flags. A missing file is valid and uses defaults, except for
68-`provider` and `model`, which are required.
69-
70-Because `pi-ai` owns the provider catalog, auth env vars, base URLs, wire APIs,
71-and compat detection, model config stays thin. A built-in provider needs only
72-`provider` + `model`; `customProviders` exists only for endpoints `pi-ai` does
73-not ship.
74-
75-Fields and defaults:
76-
77-- `sessionsDir` — root for per-session directories. Default `<cwd>/sessions`.
78-- `systemPrompt` — base system prompt. Default `""`.
79-- `discoverAgentFiles` — include discovered `AGENTS.md`/`CLAUDE.md`. Default `true`.
80-- `skillsDirs` — directories scanned for `SKILL.md`. Default `[]` (no skills).
81-- `tools` — enabled tool names. Default `["edit", "bash"]`.
82-- `provider` — **required.** Built-in `pi-ai` provider id or a
83- `customProviders[].id`. No default; a config without it is an error.
84-- `model` — **required.** Model id within that provider. No default; mini-coder
85- never picks a model.
86-- `thinkingEffort` — one of `minimal`, `low`, `medium`, `high`, `xhigh`, `max`.
87- Default `"medium"`.
88-- `customProviders` — array; default `[]`. Each entry:
89- - `id` (matches the active `provider`),
90- - `name` (display; defaults to `id`),
91- - `baseUrl`,
92- - `api` — explicit `pi-ai` wire id: `openai-completions`,
93- `openai-responses`, `anthropic-messages`, or `google-generative-ai`. Never
94- inferred from a name or URL,
95- - `models` — model ids served there,
96- - `envKeys` — optional credential env vars; omit for keyless local servers,
97- - `headers` — optional extra request headers.
98-
99-Decisions:
100-
101-- Built-in models are looked up in `pi-ai`'s catalog. Do not duplicate catalog
102- data or env vars in mini-coder.
103-- Omitted custom-model metadata uses safe defaults (`reasoning: false`,
104- `input: ["text"]`, zero cost, 200k context, 32k max tokens). `pi-ai`
105- auto-detects `compat` from `baseUrl`; add overrides only when a concrete
106- endpoint misbehaves.
107-- `headers` merge into requests and are kept out of session records.
108-- Unknown `tools` names and unknown config keys are config errors. Validate at
109- load and name the failing field.
110-
111-## Provider integration
112-
113-Use `pi-ai` entrypoints: `builtinModels()` / `createModels()`,
114-`createProvider({ id, name, baseUrl, auth, models, api })`,
115-`envApiKeyAuth(displayName, envVars)`,
116-`models.streamSimple(model, context, { reasoning, signal, sessionId })`, and the
117-`Type` re-export. Import API implementations only from
118-`@earendil-works/pi-ai/api/<api>.lazy` so unused provider SDKs are not bundled.
119-
120-Decisions:
121-
122-- Register built-ins with `builtinModels()` and custom entries with
123- `createProvider`. Keyless custom providers get a stub auth that resolves a
124- placeholder key rather than an env lookup.
125-- Auth is entirely `pi-ai`'s. Credentials resolve from env vars only; stored
126- credentials, login flows, and a persistent `CredentialStore` are deferred.
127-- Keep the adapter thin. Consume `pi-ai` message/stream types directly; do not
128- translate them into a parallel model. Keep provider-specific continuation data
129- (opaque blocks, signatures) intact in the session.
130-
131-## Session persistence
132-
133-`pi-ai` ships no session store. The session layer is a thin append-only JSONL
134-wrapper around `pi-ai`'s own `Message` type. Never invent a parallel message
135-model.
136-
137-One JSON object per line; never rewrite or delete committed lines. Records:
138-
139-- `{ type: "session", version: 1, id, cwd, createdAt, title }` — first line,
140- written once.
141-- `{ type: "request", at, provider, model, api, thinkingEffort, systemPrompt,
142- tools }` — written before each model request, capturing resolved inputs.
143-- `{ type: "message", at, message }` — each conversation message, stored as a
144- `pi-ai` `Message` verbatim.
145-
146-Directory and file layout:
147-
148-```
149-<sessionsDir>/<YYYYMMDD>-<HHmmss>-<slug>-<shortid>/session.jsonl
150-```
151-
152-- The directory name is the session `id` and the canonical key. Never rename it.
153-- `YYYYMMDD-HHmmss` is UTC creation time, keeping `ls` chronological.
154-- `slug` comes from the first user message: lowercased, non-alphanumerics
155- collapsed to `-`, trimmed, truncated to ~40 chars, falling back to `session`.
156- The same function produces the `title`.
157-- `shortid` is 6 random base36 chars, disambiguating same-second, same-title
158- sessions.
159-- Ensure `sessionsDir` recursively; create the session directory with exclusive
160- `mkdirSync` and regenerate `shortid` on `EEXIST` (bounded attempts). No locks.
161-- Create lazily on the first user message so the slug is meaningful; the session
162- is in-memory before that.
163-- One writer per session directory.
164-- Append with `writeSync` + `fsyncSync` so committed lines survive a crash. A
165- persistence failure stops the turn; never continue with unrecorded side
166- effects.
167-- Preserve message order and tool-call ↔ tool-result relationships.
168-- Reading sessions back is deferred; when it is added, tolerate a truncated
169- final line, reject corruption in committed history, and use `pi-ai`'s
170- `AssistantMessageFrameEncoder` / `reduceAssistantMessageFrames` rather than a
171- custom frame format.
172-
173-## Agent loop
174-
175-One loop, no limits. Per turn: assemble `{ systemPrompt, tools, messages }`,
176-`for await` over `streamSimple`, surface text/reasoning/tool-call events, append
177-the final assistant message, then execute any tool calls in order, appending
178-each result, and repeat. Stop when the assistant produces no tool calls, on
179-cancel, or on a surfaced error.
180-
181-Phases: `preparing`, `waitingModel`, `streaming`, `runningTool`, `pausing`,
182-`idle`; a turn may be cancelled from any active phase. Events: `phase`, `text`,
183-`reasoning`, `toolCall`, `toolOutput`, `toolResult`, `message`, `error`,
184-`cancelled`, `complete`.
185-
186-Decisions:
187-
188-- No compaction, summarization, or context rewriting.
189-- No automatic retries. Provider errors are surfaced, not hidden.
190-- No reminders or meta-messages between steps.
191-- The loop is driven by an `AbortSignal` and checks pause state at step
192- boundaries (top of each iteration and before each tool call).
193-
194-## Tools
195-
196-`edit` and `bash` only. Stateless; recoverable failures return tool-result text,
197-not thrown errors. There is no `read` tool — the model reads files with Unix
198-tooling through `bash`. Tool arguments are untrusted input and are validated at
199-the boundary with Typebox (`Value.Parse`); application logic uses plain types.
200-
201-- **`edit`** — `{ path, oldText, newText }`. Exact find-and-replace. Fails when
202- `oldText` is missing or matches more than once. Empty `oldText` creates a new
203- file and fails if it exists. Returns a unified diff via `createTwoFilesPatch`
204- from the `diff` package. Checks the abort signal before writing.
205-- **`bash`** — `{ command }`. Runs `bash -c` in `process.cwd()` in its own
206- process group (`detached: true`) so cancellation can kill the whole tree.
207- Streams stdout/stderr through `onOutput`, then returns combined output plus
208- exit code. On abort, SIGTERM the group, then SIGKILL after a short grace.
209- Output is bounded (10k head + 6k tail) and truncation is reported in
210- `details` (`truncated`, `omittedChars`, `totalChars`) rather than silently
211- dropped. No default timeout.
212-
213-Only tools named in config `tools` are exposed and may execute. No approval
214-prompts, sandboxing, or per-tool budgets.
215-
216-## System prompt assembly
217-
218-In order: config `systemPrompt`, then skills (when `skillsDirs` is non-empty),
219-then agent files (when `discoverAgentFiles`).
220-
221-- Agent files: load `AGENTS.md` and `CLAUDE.md` from `~/.agents/` and the project
222- root (`process.cwd()`), trimmed, each under a heading naming its path.
223-- Skills: scan each `skillsDirs` entry for `<dir>/<name>/SKILL.md`, read its
224- frontmatter (`name`, `description`), and advertise the absolute path so the
225- model can read it with `bash` on demand. Progressive disclosure only — never
226- inline skill bodies. No directories means no skills; there is no implicit
227- global or project-local discovery.
228-- No other injected instructions, reminders, or environment blobs.
229-
230-## TUI
231-
232-Normal terminal screen. No alternate screen, no full-screen buffer, no
233-persistent cursor modes. Styling is unconstrained: SGR attributes and colour,
234-live or committed, are the renderer's choice, and `src/tui/` owns it. No flicker:
235-coalesce writes (16ms frame cadence) and never redraw committed output.
236-
237-Two regions:
238-
239-- **Committed history** — printed once to terminal scrollback and never
240- redrawn. User turns, assistant text, tool calls, and tool results go here. The
241- terminal owns scrollback, selection, and scrolling.
242-- **Live region** — at most the height of the terminal minus one row, holding
243- a one-row context-usage readout, the in-flight line (the current incomplete
244- line of whichever stream is active), a one-row phase status, and the editor,
245- in that order. Only this region is redrawn. When idle it holds the context
246- readout and the editor: no in-flight line, no status row.
247-
248-The context readout is always present, including idle, and is display-only: it
249-estimates the tokens the next request would send against `model.contextWindow`
250-and is never persisted. Anchor on the last `AssistantMessage.usage` — the prompt
251-that was sent is `totalTokens - output` — and estimate the anchor message and
252-everything after it; fall back to a ~1 token per 4 characters estimate of the
253-whole context. Emphasize as it approaches the window, and mark it full when
254-`used + model.maxTokens` would exceed it.
255-
256-Scrollback is append-only and written before the live region is redrawn, never
257-after. Blocks — a user turn, a tool call with its result body, a terminal-state
258-line — are separated by exactly one blank line, never two, and never as the
259-first line. Each tool block is committed as a unit when its result arrives, so a
260-call and its body stay contiguous even when one assistant message announces
261-several calls before any of them runs.
262-
263-Redraw: move to the top of the live region, erase to end of screen, rewrite.
264-Track the region's height exactly: it changes when the status row appears or
265-disappears and when the in-flight line wraps, so erasing it means erasing every
266-occupied row, not one. When content is committed, print it above the live region
267-and shrink the region before the next frame. On `SIGWINCH`, drop the cursor
268-anchor and re-anchor rather than guessing; never erase committed history. Handle
269-wrapping, Unicode width, and tiny terminals without corrupting scrollback.
270-
271-Input editor (notepad-level, not Vim/readline parity): multiline
272-insertion/deletion, cursor movement across lines, reliable typing, backspace,
273-newline, and large bracketed paste. `Enter` submits; `Ctrl+J` inserts a newline
274-(`Shift+Enter` also maps to newline where the terminal sends it). The draft
275-survives redraws, cancellation, and errors. No undo/redo, history search, or
276-path completion.
277-
278-Terminal lifecycle: raw mode only in interactive mode; bracketed paste enabled;
279-restore prior mode, cursor visibility, and modified state on exit, cancel, and
280-`SIGINT`/`SIGTERM`. Re-read size on resize. Use `process.stdout.columns`/`rows`
281-with fallbacks for `0`/undefined. Escape sequences are parsed by a small state
282-machine with a short timeout to distinguish a lone ESC from a sequence.
283-
284-## Interruption and lifecycle
285-
286-- **ESC = polite pause request.** It never interrupts the current step: the
287- in-flight model request completes and the running tool runs to completion. The
288- loop then pauses at the next boundary for a steering message, which is
289- appended before the turn continues.
290-- **CTRL+C = cancel the turn completely.** Abort the model request via
291- `AbortSignal` and terminate the running tool's process group. Persist the
292- aborted assistant message (`stopReason: "aborted"`). Return to idle; do not
293- undo completed side effects. When idle, it clears a non-empty draft instead.
294-- **CTRL+D = exit**, only when the input is empty. Flush the session, restore the
295- terminal, exit cleanly.
296-- No max turns, tool-call budget, or automatic stop.
297-
298-## Headless mode
299-
300-`-p` / `--print` is the only CLI interface and the only flag. It runs one prompt
301-to completion non-interactively and prints the final assistant answer to stdout.
302-Accepted spellings: `-p <prompt>`, `--print <prompt>`, `-p=<prompt>`,
303-`--print=<prompt>`; unknown arguments are errors.
304-
305-- Persists the session under `sessionsDir` exactly like interactive mode; the
306- JSONL log is the durable record. No other machine-readable stdout mode.
307-- Diagnostics, tool progress, and errors go to stderr.
308-- Never emit ANSI escapes or terminal controls when not a TTY; never wait for
309- prompts.
310-- Exit `0` on success, non-zero on failure/cancel.
311-
312-## Reliability and diagnostics
313-
314-- Persistence failure stops the turn.
315-- Surface provider errors with their message; do not mask, summarize, or retry.
316-- Local diagnostics only. No remote telemetry. Any debug output would go to
317- stderr behind an explicit flag; redact secrets and prompt/tool content by
318- default.
319-- No hidden stalls: every wait (model request, tool, pause) has a visible state
320- in the TUI; in headless mode tool calls, tool output, errors, and
321- cancellation are written to stderr.
322-
323-## Scope boundaries
22+## Direction
32423
32524 Deferred, not rejected. Do not build unless explicitly promoted:
32625
32726 - context compaction / summarization / masking;
32827 - reading or resuming sessions (the JSONL log is write-only today);
329-- prompt templates;
330-- custom agents / subagents / delegation;
331-- an extension or plugin system;
332-- a settings TUI or overlay editors;
333-- custom OAuth or auth implementations (use `pi-ai`'s provider auth);
28+- prompt templates; custom agents / subagents / delegation;
29+- an extension or plugin system; a settings TUI; overlay editors;
30+- custom OAuth or auth flows (use `pi-ai`'s provider auth);
33431 - MCP, image generation, multi-agent orchestration;
33532 - sandboxing, approval prompts, permission policies;
33633 - tests and CI (standing rule: no tests unless asked);
337-- macOS/Windows behavior and cross-platform abstractions. Target Linux first.
34+- macOS/Windows support and cross-platform abstractions. Target Linux first.
35+
36+## Guardrails
37+
38+Hard constraints. Do not cross these without explicit direction:
39+
40+- **Node.js directly.** No Bun, no Deno, no `Bun.*`, no Bun package scripts.
41+- **No TUI library or framework.** Render with direct `process.stdout` ANSI
42+ writes and plain strings.
43+- **`pi-ai` owns the provider layer.** All model requests, adapters, wire
44+ formats, streaming, auth, and usage go through `@earendil-works/pi-ai`. Never
45+ re-implement a provider protocol, and keep provider-specific continuation data
46+ intact.
47+- **Write original code.** Other coding agents are behavioral references only.
48+- **No sandbox or permission layer.** Tools run with the user's permissions;
49+ isolation is an environment concern (`nono`), not the agent's.
50+- **No loop limits.** No max turns, tool calls, token budgets, or agent-imposed
51+ timeouts. The user's ability to interrupt is the limit.
52+- **Config-first.** Every user-facing behavior that can vary comes from config
53+ with a sane default. Global config only — no project-local config, no
54+ config-override flags — and never duplicate `pi-ai`'s catalog or env vars.
55+- **Minimal context.** The model sees the configured system prompt plus
56+ explicitly opted-in resource files — never reminders, hidden blocks, or
57+ harness meta-text.
58+- **Never invent a parallel model.** Consume `pi-ai`'s `Message` and stream
59+ types directly.
60+- **The agent never imports the TUI.** Headless and TUI are two projections of
61+ the same agent events; the TUI owns no agent or provider semantics.
62+
63+## Invariants
64+
65+- Sessions are append-only JSONL, one `pi-ai` message per line, fsynced on
66+ write. Never rewrite or delete committed lines. A persistence failure stops
67+ the turn.
68+- The loop has no compaction, no retries, and no meta-messages between steps.
69+ Provider errors surface as-is, never masked or summarized.
70+- `edit` and `bash` only. No `read` tool — the model reads files through `bash`.
71+ Tool arguments are untrusted and validated once at the boundary.
72+- Interruption: ESC politely pauses at the next step boundary; Ctrl+C cancels the
73+ turn (abort the request, kill the tool's process group, persist the aborted
74+ message); Ctrl+D exits on an empty draft. Completed side effects are never
75+ undone.
76+- Diagnostics are local only. No telemetry, no hidden stalls.
33877
33978 ## Working agreement
34079
341-- Read `pi-ai`'s README and the reference projects before designing. Trace the
342- real data flow; apply guards at the narrowest boundary.
343-- Keep the diff small. Do not opportunistically refactor or harden adjacent
344- code.
345-- Prefer plain functions and objects over classes; keep exports minimal; define
346- helpers near their use.
347-- Validate untrusted input once at the boundary (config, tool args) with
348- Typebox, then keep internal code plain-typed. Do not spread schema-derived
349- types everywhere.
350-- Ask before adding a dependency. `diff` and `typebox` are approved;
351- supply-chain risk is a real constraint.
352-- Do not add tests unless explicitly asked. Verify manually.
353-- Before finishing, review the diff against the hard constraints and the scope
354- boundaries, remove anything that added scope, and report any requirement that
355- could not be satisfied.
80+- Trace the real data flow before designing; apply guards at the narrowest
81+ boundary.
82+- Keep the diff small. Do not opportunistically refactor or harden adjacent code.
83+- Prefer plain functions and objects; keep exports minimal; define helpers near
84+ their use.
85+- Validate untrusted input once at the boundary with Typebox, then keep internal
86+ code plain-typed.
87+- Ask before adding a dependency. `diff` and `typebox` are approved.
88+- Do not add tests unless explicitly asked; verify manually.
89+- Before finishing, review the diff against the direction and guardrails, remove
90+ anything that added scope, and report any requirement you could not satisfy.