xonecas.io
64875
Mc

mini-coder / commit 66c5fd5

feat: better editting experience

xonecas2026-09-22 66c5fd5edd36a5d4324dbd8b506f9b7c30176c0f parent b185a90

4 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

AGENTS.md+67−332
@@ -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.
src/tui/editor.ts+139−33
@@ -1,9 +1,32 @@
11 import { displayWidth, expandTabs, wrapLine, type Key } from "./term.ts";
22
3+const TAB = 4;
4+const DEFAULT_WIDTH = 80;
5+
36 function codePoints(line: string): string[] {
47 return Array.from(line);
58 }
69
10+function isSpace(ch: string): boolean {
11+ return /\s/u.test(ch);
12+}
13+
14+/** First code point index of the word before `col`; shared by all word motion. */
15+function wordStart(cps: string[], col: number): number {
16+ let i = col;
17+ while (i > 0 && isSpace(cps[i - 1])) i--;
18+ while (i > 0 && !isSpace(cps[i - 1])) i--;
19+ return i;
20+}
21+
22+/** Code point index one past the word at or after `col`. */
23+function wordEnd(cps: string[], col: number): number {
24+ let i = col;
25+ while (i < cps.length && isSpace(cps[i])) i++;
26+ while (i < cps.length && !isSpace(cps[i])) i++;
27+ return i;
28+}
29+
730 export interface EditorRender {
831 rows: string[];
932 cursorRow: number;
@@ -14,6 +37,8 @@ export class Editor {
1437 private lines: string[] = [""];
1538 private row = 0;
1639 private col = 0;
40+ private scroll = 0;
41+ private width = DEFAULT_WIDTH;
1742
1843 text(): string {
1944 return this.lines.join("\n");
@@ -23,16 +48,19 @@ export class Editor {
2348 this.lines = [""];
2449 this.row = 0;
2550 this.col = 0;
51+ this.scroll = 0;
2652 }
2753
2854 handle(key: Key): "submit" | "changed" | "none" {
2955 switch (key.type) {
30- case "text":
31- this.insert(key.text);
32- return "changed";
56+ case "submit":
57+ return "submit";
3358 case "newline":
3459 this.insert("\n");
3560 return "changed";
61+ case "text":
62+ this.insert(key.text);
63+ return "changed";
3664 case "tab":
3765 this.insert("\t");
3866 return "changed";
@@ -42,12 +70,21 @@ export class Editor {
4270 case "delete":
4371 this.deleteForward();
4472 return "changed";
73+ case "wordBack":
74+ this.wordBack();
75+ return "changed";
4576 case "left":
4677 this.left();
4778 return "changed";
4879 case "right":
4980 this.right();
5081 return "changed";
82+ case "wordLeft":
83+ this.wordLeft();
84+ return "changed";
85+ case "wordRight":
86+ this.wordRight();
87+ return "changed";
5188 case "up":
5289 this.up();
5390 return "changed";
@@ -60,40 +97,72 @@ export class Editor {
6097 case "end":
6198 this.col = codePoints(this.lines[this.row]).length;
6299 return "changed";
63- case "wordBack":
64- this.wordBack();
100+ case "docStart":
101+ this.row = 0;
102+ this.col = 0;
103+ return "changed";
104+ case "docEnd":
105+ this.row = this.lines.length - 1;
106+ this.col = codePoints(this.lines[this.row]).length;
65107 return "changed";
66- case "enter":
67- return "submit";
68108 default:
69109 return "none";
70110 }
71111 }
72112
73- render(width: number): EditorRender {
113+ /** Clipped to `maxRows`, scrolled only as far as the caret requires. */
114+ render(width: number, maxRows: number): EditorRender {
115+ this.width = Math.max(1, width);
74116 const rows: string[] = [];
75117 let cursorRow = 0;
76118 let cursorCol = 0;
77119 for (let line = 0; line < this.lines.length; line++) {
78- const expanded = expandTabs(this.lines[line]);
79- const chunks = wrapLine(expanded, width);
120+ const chunks = wrapLine(expandTabs(this.lines[line], TAB), this.width);
80121 if (line === this.row) {
81- const prefix = codePoints(expanded)
82- .slice(0, this.col)
83- .join("");
84- const prefixWidth = displayWidth(prefix);
85- let rowInLine = Math.floor(prefixWidth / width);
86- if (rowInLine >= chunks.length) {
87- rowInLine = chunks.length - 1;
88- cursorCol = displayWidth(chunks[rowInLine]);
89- } else {
90- cursorCol = prefixWidth - rowInLine * width;
91- }
92- cursorRow = rows.length + rowInLine;
122+ const caret = this.caret();
123+ cursorRow = rows.length + caret.row;
124+ cursorCol = caret.col;
93125 }
94126 rows.push(...chunks);
95127 }
96- return { rows, cursorRow, cursorCol };
128+ const view = Math.max(1, maxRows);
129+ if (cursorRow < this.scroll) this.scroll = cursorRow;
130+ else if (cursorRow >= this.scroll + view) this.scroll = cursorRow - view + 1;
131+ this.scroll = Math.min(Math.max(this.scroll, 0), Math.max(0, rows.length - view));
132+ return {
133+ rows: rows.slice(this.scroll, this.scroll + view),
134+ cursorRow: cursorRow - this.scroll,
135+ cursorCol,
136+ };
137+ }
138+
139+ /** The caret's display row within its logical line, and its cell column. */
140+ private caret(): { row: number; col: number } {
141+ const line = this.lines[this.row];
142+ const chunks = wrapLine(expandTabs(line, TAB), this.width);
143+ const cell = this.cells(line)[this.col];
144+ const row = Math.floor(cell / this.width);
145+ if (row >= chunks.length) return { row: chunks.length - 1, col: displayWidth(chunks[chunks.length - 1]) };
146+ return { row, col: cell - row * this.width };
147+ }
148+
149+ /** Display column of every code point boundary in `line`, tabs expanded. */
150+ private cells(line: string): number[] {
151+ const out = [0];
152+ let col = 0;
153+ for (const ch of codePoints(line)) {
154+ col += ch === "\t" ? TAB - (col % TAB) : displayWidth(ch);
155+ out.push(col);
156+ }
157+ return out;
158+ }
159+
160+ /** The caret column nearest `cell`, never past the end of the line. */
161+ private colAtCell(line: string, cell: number): number {
162+ const cells = this.cells(line);
163+ let i = cells.length - 1;
164+ while (i > 0 && cells[i] > cell) i--;
165+ return i;
97166 }
98167
99168 private insert(text: string): void {
@@ -157,25 +226,62 @@ export class Editor {
157226 }
158227 }
159228
229+ /** One display row, so the caret crosses the wrapped rows of a long line. */
160230 private up(): void {
161- if (this.row > 0) {
162- this.row--;
163- this.col = Math.min(this.col, codePoints(this.lines[this.row]).length);
231+ const line = this.lines[this.row];
232+ const caret = this.caret();
233+ if (caret.row > 0) {
234+ this.col = this.colAtCell(line, this.cells(line)[this.col] - this.width);
235+ return;
164236 }
237+ if (this.row === 0) return;
238+ this.row--;
239+ const previous = this.lines[this.row];
240+ const lastRow = wrapLine(expandTabs(previous, TAB), this.width).length - 1;
241+ this.col = this.colAtCell(previous, lastRow * this.width + caret.col);
165242 }
166243
167244 private down(): void {
168- if (this.row < this.lines.length - 1) {
169- this.row++;
170- this.col = Math.min(this.col, codePoints(this.lines[this.row]).length);
245+ const line = this.lines[this.row];
246+ const caret = this.caret();
247+ if (caret.row < wrapLine(expandTabs(line, TAB), this.width).length - 1) {
248+ this.col = this.colAtCell(line, this.cells(line)[this.col] + this.width);
249+ return;
250+ }
251+ if (this.row === this.lines.length - 1) return;
252+ this.row++;
253+ this.col = this.colAtCell(this.lines[this.row], caret.col);
254+ }
255+
256+ private wordLeft(): void {
257+ const cps = codePoints(this.lines[this.row]);
258+ const start = wordStart(cps, this.col);
259+ if (start !== this.col) {
260+ this.col = start;
261+ return;
262+ }
263+ if (this.row === 0) return;
264+ this.row--;
265+ const previous = codePoints(this.lines[this.row]);
266+ this.col = wordStart(previous, previous.length);
267+ }
268+
269+ private wordRight(): void {
270+ const cps = codePoints(this.lines[this.row]);
271+ const end = wordEnd(cps, this.col);
272+ if (end !== this.col) {
273+ this.col = end;
274+ return;
171275 }
276+ if (this.row === this.lines.length - 1) return;
277+ this.row++;
278+ this.col = wordEnd(codePoints(this.lines[this.row]), 0);
172279 }
173280
174281 private wordBack(): void {
175282 const current = codePoints(this.lines[this.row]);
176- const start = this.col;
177- while (this.col > 0 && current[this.col - 1] === " ") this.col--;
178- while (this.col > 0 && current[this.col - 1] !== " ") this.col--;
179- this.lines[this.row] = current.slice(0, this.col).join("") + current.slice(start).join("");
283+ const start = wordStart(current, this.col);
284+ this.lines[this.row] = current.slice(0, start).join("") + current.slice(this.col).join("");
285+ this.col = start;
180286 }
181287 }
src/tui/term.ts+184−67
@@ -74,17 +74,21 @@ export function wrapLine(text: string, width: number): string[] {
7474
7575 export type Key =
7676 | { type: "text"; text: string }
77- | { type: "enter" }
77+ | { type: "submit" }
7878 | { type: "newline" }
7979 | { type: "backspace" }
8080 | { type: "delete" }
81+ | { type: "wordBack" }
8182 | { type: "left" }
8283 | { type: "right" }
84+ | { type: "wordLeft" }
85+ | { type: "wordRight" }
8386 | { type: "up" }
8487 | { type: "down" }
8588 | { type: "home" }
8689 | { type: "end" }
87- | { type: "wordBack" }
90+ | { type: "docStart" }
91+ | { type: "docEnd" }
8892 | { type: "tab" }
8993 | { type: "escape" }
9094 | { type: "interrupt" }
@@ -93,51 +97,123 @@ export type Key =
9397 const PASTE_START = "\x1b[200~";
9498 const PASTE_END = "\x1b[201~";
9599
96-function normalizePaste(text: string): string {
97- return text.replace(/\r\n?/g, "\n");
100+const SHIFT = 1;
101+const ALT = 2;
102+const CTRL = 4;
103+/** Only real modifiers are acted on; lock bits and the rest are ignored. */
104+const MODS = SHIFT | ALT | CTRL;
105+
106+/** Codes for keys without a printable form, matching kitty's functional range. */
107+const CODE = {
108+ enter: 13,
109+ escape: 27,
110+ tab: 9,
111+ backspace: 127,
112+ delete: 57349,
113+ left: 57350,
114+ right: 57351,
115+ up: 57352,
116+ down: 57353,
117+ home: 57356,
118+ end: 57357,
119+} as const;
120+
121+/** The one table every input path resolves through: code and modifiers to key. */
122+const KEYS: Record<string, Key | undefined> = {
123+ [`${CODE.enter}:0`]: { type: "submit" },
124+ [`${CODE.enter}:${ALT}`]: { type: "newline" },
125+ [`${CODE.enter}:${SHIFT}`]: { type: "newline" },
126+ [`${CODE.escape}:0`]: { type: "escape" },
127+ [`${CODE.tab}:0`]: { type: "tab" },
128+ [`${CODE.backspace}:0`]: { type: "backspace" },
129+ [`${CODE.backspace}:${CTRL}`]: { type: "wordBack" },
130+ [`${CODE.delete}:0`]: { type: "delete" },
131+ [`${CODE.left}:0`]: { type: "left" },
132+ [`${CODE.left}:${CTRL}`]: { type: "wordLeft" },
133+ [`${CODE.right}:0`]: { type: "right" },
134+ [`${CODE.right}:${CTRL}`]: { type: "wordRight" },
135+ [`${CODE.up}:0`]: { type: "up" },
136+ [`${CODE.down}:0`]: { type: "down" },
137+ [`${CODE.home}:0`]: { type: "home" },
138+ [`${CODE.home}:${CTRL}`]: { type: "docStart" },
139+ [`${CODE.end}:0`]: { type: "end" },
140+ [`${CODE.end}:${CTRL}`]: { type: "docEnd" },
141+ ["97:4"]: { type: "home" }, // Ctrl+A
142+ ["98:2"]: { type: "wordBack" }, // Alt+B
143+ ["99:4"]: { type: "interrupt" }, // Ctrl+C
144+ ["100:4"]: { type: "eof" }, // Ctrl+D
145+ ["101:4"]: { type: "end" }, // Ctrl+E
146+ ["106:4"]: { type: "newline" }, // Ctrl+J
147+ ["119:4"]: { type: "wordBack" }, // Ctrl+W
148+};
149+
150+const CSI_FINALS: Record<string, number | undefined> = {
151+ A: CODE.up,
152+ B: CODE.down,
153+ C: CODE.right,
154+ D: CODE.left,
155+ H: CODE.home,
156+ F: CODE.end,
157+};
158+
159+const CSI_TILDES: Record<number, number | undefined> = {
160+ 1: CODE.home,
161+ 3: CODE.delete,
162+ 4: CODE.end,
163+ 7: CODE.home,
164+ 8: CODE.end,
165+};
166+
167+interface Chord {
168+ code: number;
169+ mods: number;
98170 }
99171
100-function mapChar(ch: string): Key | null {
101- switch (ch) {
102- case "\r":
103- return { type: "enter" };
104- case "\n":
105- return { type: "newline" };
106- case "\x7f":
107- case "\x08":
108- return { type: "backspace" };
109- case "\t":
110- return { type: "tab" };
111- case "\x01":
112- return { type: "home" };
113- case "\x05":
114- return { type: "end" };
115- case "\x17":
116- return { type: "wordBack" };
117- case "\x03":
118- return { type: "interrupt" };
119- case "\x04":
120- return { type: "eof" };
121- default:
122- return null;
123- }
172+function lookup(code: number, mods: number): Key | null {
173+ return KEYS[`${code}:${mods}`] ?? null;
174+}
175+
176+/** A legacy control byte, as the chord the same key arrives as elsewhere. */
177+function controlChord(code: number): Chord {
178+ if (code === 0x08) return { code: CODE.backspace, mods: 0 };
179+ if (code === 0x09) return { code: CODE.tab, mods: 0 };
180+ if (code === 0x0d) return { code: CODE.enter, mods: 0 };
181+ return { code: code + 0x60, mods: CTRL };
124182 }
125183
126-function mapCsi(seq: string): Key | null {
127- const last = seq[seq.length - 1];
128- if (last === "A") return { type: "up" };
129- if (last === "B") return { type: "down" };
130- if (last === "C") return { type: "right" };
131- if (last === "D") return { type: "left" };
132- if (last === "H") return { type: "home" };
133- if (last === "F") return { type: "end" };
134- if (last === "~") {
135- const code = Number.parseInt(seq.slice(2, -1), 10);
136- if (code === 1 || code === 7) return { type: "home" };
137- if (code === 4 || code === 8) return { type: "end" };
138- if (code === 3) return { type: "delete" };
184+/** Control bytes are never text: they resolve through the table or vanish. */
185+function mapPoint(code: number): Key | null {
186+ if (code === 0x7f) return lookup(CODE.backspace, 0);
187+ if (code < 0x20) {
188+ const { code: point, mods } = controlChord(code);
189+ return lookup(point, mods);
139190 }
140- return null;
191+ return { type: "text", text: String.fromCodePoint(code) };
192+}
193+
194+function modsOf(field: string | undefined): number {
195+ const raw = Number.parseInt(field ?? "", 10);
196+ return Number.isFinite(raw) && raw > 0 ? (raw - 1) & MODS : 0;
197+}
198+
199+/** `code[:shifted[:base]];mods[:event];text` */
200+function csiUChord(params: string): Chord | null {
201+ const fields = params.split(";");
202+ const code = Number.parseInt(fields[0].split(":")[0], 10);
203+ if (!Number.isFinite(code)) return null; // probe replies and private forms
204+ if (code >= 57344) return null; // functional keys never arrive as CSI-u
205+ return { code, mods: modsOf(fields[1]?.split(":")[0]) };
206+}
207+
208+/** `params final`: the legacy `CSI 1;5D` form and SS3's bare `A`. */
209+function legacyChord(final: string, params: string): Chord | null {
210+ const fields = params.split(";");
211+ const code = final === "~" ? CSI_TILDES[Number.parseInt(fields[0], 10)] : CSI_FINALS[final];
212+ return code === undefined ? null : { code, mods: modsOf(fields[1]) };
213+}
214+
215+function normalizePaste(text: string): string {
216+ return text.replace(/\r\n?/g, "\n");
141217 }
142218
143219 export class KeyParser {
@@ -154,6 +230,15 @@ export class KeyParser {
154230 return [{ type: "escape" }];
155231 }
156232
233+ /** True while the buffer holds a sequence that may still complete. */
234+ pendingSequence(): boolean {
235+ return !this.pasting && this.buffer.length > 1;
236+ }
237+
238+ flushSequence(): void {
239+ this.buffer = "";
240+ }
241+
157242 feed(chunk: string): Key[] {
158243 this.buffer += chunk;
159244 const keys: Key[] = [];
@@ -189,9 +274,8 @@ export class KeyParser {
189274 const code = this.buffer.codePointAt(0)!;
190275 const ch = String.fromCodePoint(code);
191276 this.buffer = this.buffer.slice(ch.length);
192- const key = mapChar(ch);
277+ const key = mapPoint(code);
193278 if (key) keys.push(key);
194- else if (code >= 0x20 && code !== 0x7f) keys.push({ type: "text", text: ch });
195279 }
196280 return keys;
197281 }
@@ -200,24 +284,44 @@ export class KeyParser {
200284 const buffer = this.buffer;
201285 if (buffer.length < 2) return false;
202286 const next = buffer[1];
203- if (next === "[" || next === "O") {
204- let i = 2;
205- while (i < buffer.length) {
206- const code = buffer.charCodeAt(i);
207- if (code >= 0x40 && code <= 0x7e) break;
208- i++;
209- }
210- if (i >= buffer.length) return false;
211- const seq = buffer.slice(0, i + 1);
212- this.buffer = buffer.slice(i + 1);
213- const key = mapCsi(seq);
287+ if (next === "[" || next === "O") return this.parseCsi(keys);
288+ if (next === "]") return this.skipString(true);
289+ if (next === "P" || next === "X" || next === "^" || next === "_") return this.skipString(false);
290+ this.buffer = buffer.slice(2);
291+ const key = lookup(next.codePointAt(0)!, ALT);
292+ if (key) keys.push(key);
293+ return true;
294+ }
295+
296+ private parseCsi(keys: Key[]): boolean {
297+ const buffer = this.buffer;
298+ let i = 2;
299+ while (i < buffer.length) {
300+ const code = buffer.charCodeAt(i);
301+ if (code >= 0x40 && code <= 0x7e) break;
302+ i++;
303+ }
304+ if (i >= buffer.length) return false;
305+ const final = buffer[i];
306+ const params = buffer.slice(2, i);
307+ this.buffer = buffer.slice(i + 1);
308+ const chord = final === "u" ? csiUChord(params) : legacyChord(final, params);
309+ if (chord !== null) {
310+ const key = lookup(chord.code, chord.mods);
214311 if (key) keys.push(key);
215- return true;
216312 }
217- const ch = buffer[1];
218- this.buffer = buffer.slice(2);
219- if (ch === "\r" || ch === "\n") keys.push({ type: "newline" });
220- else if (ch === "b" || ch === "B") keys.push({ type: "wordBack" });
313+ return true;
314+ }
315+
316+ /** OSC ends at BEL or ST; DCS/APC/PM/SOS end at ST. Skipped whole. */
317+ private skipString(bel: boolean): boolean {
318+ const st = this.buffer.indexOf("\x1b\\", 2);
319+ const bell = bel ? this.buffer.indexOf("\x07", 2) : -1;
320+ let end = -1;
321+ if (bell >= 0 && (st < 0 || bell < st)) end = bell + 1;
322+ else if (st >= 0) end = st + 2;
323+ if (end < 0) return false;
324+ this.buffer = this.buffer.slice(end);
221325 return true;
222326 }
223327 }
@@ -231,6 +335,7 @@ export class Terminal {
231335 private readonly handlers: TerminalHandlers;
232336 private parser = new KeyParser();
233337 private escapeTimer: NodeJS.Timeout | undefined;
338+ private sequenceTimer: NodeJS.Timeout | undefined;
234339 private started = false;
235340
236341 constructor(handlers: TerminalHandlers) {
@@ -253,16 +358,17 @@ export class Terminal {
253358 process.stdin.resume();
254359 process.stdin.on("data", this.onData);
255360 process.stdout.on("resize", this.onResize);
256- process.stdout.write("\x1b[?2004h");
361+ // Bracketed paste, then kitty flag 1 so `Shift+Enter` is distinguishable.
362+ if (process.stdout.isTTY) process.stdout.write("\x1b[?2004h\x1b[>1u\x1b[?u");
257363 }
258364
259365 stop(): void {
260366 if (!this.started) return;
261367 this.started = false;
262- if (this.escapeTimer) clearTimeout(this.escapeTimer);
368+ this.clearTimers();
263369 process.stdin.off("data", this.onData);
264370 process.stdout.off("resize", this.onResize);
265- process.stdout.write("\x1b[?2004l");
371+ if (process.stdout.isTTY) process.stdout.write("\x1b[<u\x1b[?2004l");
266372 if (process.stdin.isTTY) process.stdin.setRawMode(false);
267373 process.stdin.pause();
268374 }
@@ -271,17 +377,28 @@ export class Terminal {
271377 process.stdout.write(text);
272378 }
273379
380+ private clearTimers(): void {
381+ if (this.escapeTimer) clearTimeout(this.escapeTimer);
382+ if (this.sequenceTimer) clearTimeout(this.sequenceTimer);
383+ this.escapeTimer = undefined;
384+ this.sequenceTimer = undefined;
385+ }
386+
274387 private onData = (chunk: string): void => {
275- if (this.escapeTimer) {
276- clearTimeout(this.escapeTimer);
277- this.escapeTimer = undefined;
278- }
388+ // Both timers reset on every chunk, so `Alt`+key stays snappy and an
389+ // incomplete sequence never wedges the buffer.
390+ this.clearTimers();
279391 for (const key of this.parser.feed(chunk)) this.handlers.onKey(key);
Cut short: this commit's diff is over 1000 lines.
src/tui/tui.ts+38−32
Cut short: this commit's diff is over 1000 lines.