@rwjblue/pi-durable-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Robert Jackson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,184 @@
1
- # Temporary Holding Version
1
+ # Pi Durable UI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A reusable Node.js terminal UI for attaching to a Durable conversation. Bring
4
+ your own adapter for history, progress, and explicit user actions. The library
5
+ requires no Pi Projects install, registry, Rex session, or particular host
6
+ transport. It uses Pi 1.8.0's public editor, message and tool components. The
7
+ library does not construct an `AgentSession` or run a model turn itself.
8
+
9
+ ## Run the self-test
10
+
11
+ Requires Node.js 22.19 or later. [Watch the offline demo](https://github.com/rwjblue/pi-durable-ui/blob/main/docs/demo.gif).
12
+ Try the released package without using your Pi profile or calling a model provider:
13
+
14
+ ```sh
15
+ npm exec --package=@rwjblue/pi-durable-ui -- pi-durable-ui-self-test --offline
16
+ ```
17
+
18
+ The `--` separates npm's options from the demo command. Omit the trailing
19
+ `--offline` to use your normal Pi connection. The demo also accepts `--help`
20
+ and `--model <provider/model[:thinking]>`.
21
+
22
+ To run from a checkout, use these commands from the repository root:
23
+
24
+ ```sh
25
+ npm ci --ignore-scripts
26
+ node self-test.mjs --offline
27
+ npm test
28
+ ```
29
+
30
+ **Connected mode** reads Pi's normal profile (or `PI_CODING_AGENT_DIR`). It
31
+ uses Pi's provider and auth runtime, including `models.json`, saved logins,
32
+ and environment credentials. It starts with the first available match in
33
+ `enabledModels` or the saved default, including its thinking level. If neither
34
+ is set, it uses an available model. It also loads Pi's context files and some
35
+ settings, including the named theme and built-in tool selection. It does not
36
+ load Pi extensions, MCP servers, skills, or prompt templates; a provider
37
+ registered only by an extension is not available here. Log in or change the
38
+ saved default in stock Pi.
39
+
40
+ Ask a question, ask it to read a file, or ask it to call `preview_card` once
41
+ with a title. **Connected mode consumes real tokens and sends prompts and tool
42
+ results to your provider.** The native Durable `read`, `write`, `edit`, and
43
+ `bash` tools run in the launch directory with your local permissions and no
44
+ approval prompt. Use a scratch checkout to try writes or shell commands.
45
+ Only `preview_card` runs through the fixture approval.
46
+
47
+ **Offline mode** reads no Pi profile or credentials and calls no external
48
+ provider. Type anything to get a streaming Markdown echo that reports the
49
+ model and thinking level used, or `preview` for a scripted `preview_card`
50
+ call. In either mode, press **y** to approve the exact preview or **n** to
51
+ deny, and **Ctrl+O** to expand tool output.
52
+
53
+ In both modes, type `/help` for the available commands and keys. Tab completes
54
+ slash commands. Use `/model [provider/id]` or **Ctrl+L** to pick a model, and
55
+ `/thinking [level]` or **Shift+Tab** to change its thinking level. **Ctrl+P**
56
+ and **Alt+P** cycle the same-provider models in `enabledModels` (the offline
57
+ fixture has its own scope). A cross-provider switch requires a review because
58
+ a later request can send this conversation's context to that provider. These
59
+ commands don't change Pi's defaults. `/session` shows recorded token usage,
60
+ not context occupancy. `/copy` copies the latest complete assistant answer
61
+ that this pane received, excluding thinking and tool results.
62
+
63
+ **Enter** steers at the next Durable input boundary; **Alt+Enter** sends a
64
+ follow-up, which waits for a final boundary if a run is active. If both are
65
+ admitted at the same boundary, Durable uses submission order. `/compact
66
+ [instructions]` asks the current model to summarize older context. It can
67
+ consume tokens and requires an idle scratch conversation. Escape dismisses
68
+ completion, a picker, or a review; it doesn't interrupt host work.
69
+
70
+ Both modes use a real Durable Harness and temporary SQLite, separate from
71
+ Pi's session history. They are not background hosts: **Ctrl+D** on an empty
72
+ editor exits and removes the scratch database. It does not undo tool actions.
73
+ Use [`self-test.mjs`](self-test.mjs) to try a Durable tool or plugin in an
74
+ isolated registry. Run `npm test` in this package for the offline command,
75
+ settings, review, admission, and compaction tests.
76
+
77
+ ## Install or embed the package
78
+
79
+ Install it as a Node.js library, not a Pi extension:
80
+
81
+ ```sh
82
+ npm install @rwjblue/pi-durable-ui
83
+ ```
84
+
85
+ If you're only embedding the UI, you can add `--omit=optional` to skip the
86
+ demo's dependencies. Run your adapter in a terminal:
87
+
88
+ ```js
89
+ import { runDurableChat } from "@rwjblue/pi-durable-ui";
90
+
91
+ runDurableChat({
92
+ title: "Attached worker",
93
+ cwd: workerCwd,
94
+ access: "read-only tools",
95
+ model: { provider: "fixture", id: "test", thinkingLevel: "off" },
96
+ read: after => host.readChat(workerId, after),
97
+ submit: value => host.submitChatInput(workerId, value),
98
+ close: () => host.detachClient(workerId),
99
+ });
100
+ ```
101
+
102
+ `host` above is your adapter, not an API supplied by Pi or this package.
103
+ `read` can project local state or call your own RPC service, and `submit`
104
+ forwards explicit user input to the host. The UI uses one foreground terminal per process. The optional second
105
+ argument is `{ theme: "dark" | "light" }` (default `dark`). `title` and `cwd` set
106
+ the pane title and workdir display. The optional `access` label and
107
+ `model: { provider, id, thinkingLevel? }` are display-only metadata.
108
+
109
+ - `read(after)` is polled and starts with cursor `0`. Return
110
+ `{ cursor, messages, partial, tools, label, program, notice?, approval?, controls? }`.
111
+ `messages` contains only newly finalized Pi messages, in order. `partial` is
112
+ the current assistant message or `null`. `tools` is an array of live slots
113
+ `{ callId, status, output? }` keyed to finalized assistant tool calls.
114
+ `label` and optional `notice` are status lines; `program` is pi-tui's
115
+ `ProgramStatus` (for example `{ state: "blocked", kind: "permission" }`).
116
+ Reads must never start, resume, stop, or acknowledge work.
117
+ - `submit(value)` handles explicit editor submission and returns a status
118
+ string or a review `{ title, lines, submit }`. `approval` uses the same
119
+ review shape plus a stable `id` and a `key` that changes whenever the reviewed
120
+ intent or its authority changes. Set `deny: true` to enable both y and n;
121
+ the review's `submit(allow)` runs only after the whole preview was displayed
122
+ in the current layout. Dismissing an approval hides only that ID and key.
123
+ A replacement opens at the first page and must be reviewed from scratch.
124
+ For single-action reviews, use `confirm` to label y.
125
+ The adapter supplies exact, losslessly escaped display lines and binds its
126
+ callback to that exact intent, not the latest decision. The host still must
127
+ check identity, revision, deadline, and receipt on admission.
128
+ - `close()` releases only client-side resources. `runDurableChat` also returns
129
+ the detach function. Detach is not stop; no execution is tied to the TUI.
130
+
131
+ ### Optional conversation controls
132
+
133
+ Omit `controls` to keep the original input and `/detach` behavior. Supply it,
134
+ even as `{}`, to enable local help, copy, quit, completion, and rejection of
135
+ unsupported single-line slash commands. Each read can also advertise:
136
+
137
+ | Field | Meaning |
138
+ | --- | --- |
139
+ | `model` | Committed `{ provider, id, thinkingLevel? }`; replaces the launch-time footer model. |
140
+ | `models` | Selectable `{ provider, id, label? }` entries. Requires `model`. |
141
+ | `cycleModels` | Explicit ordered `{ provider, id }` scope. The pane cycles only entries from the current provider. |
142
+ | `thinkingLevels` | Ordered levels supported by `model`, including `off` when applicable. |
143
+ | `session` | `{ id, state?, queued?, tokens? }`; `tokens` is recorded cumulative usage, if available. |
144
+ | `followUp` | `true` to expose Alt+Enter. Ordinary Enter still calls the top-level `submit(value)`. |
145
+ | `compact` | `true` to expose `/compact [instructions]`. Use `label`/`program` for progress. |
146
+
147
+ When advertising write capabilities, return a `controls.submit(action)` bound
148
+ to the conversation and relevant revisions from that read. Actions are
149
+ `{ type: "model", provider, id }`, `{ type: "thinking", thinkingLevel }`,
150
+ `{ type: "followUp", content }`, or `{ type: "compact", instructions }`.
151
+ Return a status string or the same exact-review shape as ordinary `submit`;
152
+ throw on rejection. Offer a review for changes that could send context to a
153
+ new provider. The host must recheck authority, target availability, expected
154
+ settings and required idle state, including at confirmation. Never change
155
+ profile defaults or silently fall back to another model or admission mode.
156
+ The client refreshes after success or failure and never guesses the new model.
157
+ Live approvals take priority over client pickers. See
158
+ [`self-test-controls.mjs`](self-test-controls.mjs) for an in-process example.
159
+
160
+ ## Scope and findings
161
+
162
+ Pi 1.8.0 exports `InteractiveMode`, but its constructor takes the concrete
163
+ native `AgentSessionRuntime`; the SDK runtime factory must return a native
164
+ `AgentSession` and cwd-bound services. `InteractiveMode` binds to those services
165
+ and session replacement; there is no public Durable transport injection.
166
+ `pi-durable` exposes `Harness` and conversation state, not an
167
+ `AgentSessionRuntime` adapter. Pi RPC starts a native session in another
168
+ process; it isn't a plug-in transport for stock interactive mode.
169
+
170
+ This UI feels close for Markdown, composing, and toggling tool details. It
171
+ uses Pi's native `read` renderer for path colors and syntax highlights, generic
172
+ cards for other tools, and a small footer for the workdir and model. It polls
173
+ snapshots and uses a keyboard-scrolled transcript. It doesn't inherit Pi's
174
+ context gauge, custom keybindings, history navigation, mouse/search, images,
175
+ or extension UI. The connected fixture borrows Pi's launch settings, not its
176
+ settings screens or interactive extension hooks. The pane cannot withdraw
177
+ queued messages or interrupt a run. If full stock Pi behavior is required,
178
+ use native workers rather than assuming Durable can reproduce it.
179
+
180
+ For maintainer release instructions, see the [release checklist](https://github.com/rwjblue/pi-durable-ui/blob/main/RELEASE.md).
181
+
182
+ ## License
183
+
184
+ [MIT](LICENSE)
package/commands.mjs ADDED
@@ -0,0 +1,207 @@
1
+ import { copyToClipboard } from "@earendil-works/pi-coding-agent";
2
+ import { CombinedAutocompleteProvider, fuzzyFilter, Input, SelectList, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+ import { clean } from "./transcript.mjs";
4
+
5
+ export const modelName = ({ provider, id }) => `${provider}/${id}`;
6
+ const sameModel = (a, b) => a.provider === b.provider && a.id === b.id;
7
+ const singleLine = value => clean(value).replaceAll("\n", " ");
8
+
9
+ const bindings = {
10
+ selectModel: { defaultKeys: "ctrl+l", description: "Select model" },
11
+ cycleModel: { defaultKeys: "ctrl+p", description: "Next model in scope" },
12
+ previousModel: { defaultKeys: "alt+p", description: "Previous model in scope" },
13
+ cycleThinking: { defaultKeys: "shift+tab", description: "Cycle thinking level" },
14
+ followUp: { defaultKeys: "alt+enter", description: "Send or queue follow-up" },
15
+ };
16
+ const bindingName = name => `durable.${name}`;
17
+ export const COMMAND_KEYS = Object.fromEntries(Object.entries(bindings).map(([name, binding]) => [bindingName(name), binding]));
18
+
19
+ export function parseCommand(text) {
20
+ const match = /^\/([a-z][a-z-]*)(?:[ \t]+([^\n\r]*))?$/i.exec(text.trim());
21
+ return match ? { name: match[1].toLowerCase(), argument: match[2]?.trim() ?? "" } : undefined;
22
+ }
23
+
24
+ export function scopedModels(controls) {
25
+ return (controls.cycleModels ?? []).filter(model => model.provider === controls.model?.provider);
26
+ }
27
+
28
+ export function nextScopedModel(controls, direction) {
29
+ const options = scopedModels(controls);
30
+ if (options.length < 2) return undefined;
31
+ const current = options.findIndex(option => sameModel(option, controls.model));
32
+ if (current < 0) return direction > 0 ? options[0] : options.at(-1);
33
+ return options[(current + direction + options.length) % options.length];
34
+ }
35
+
36
+ function picker(title, items, { current, query = "", keys, theme, onSelect, cancel }) {
37
+ const search = new Input({ prompt: "Search: " });
38
+ if (query) search.setValue(query);
39
+ let list, rows = 0;
40
+ function rebuild(preferred) {
41
+ const matches = fuzzyFilter(items, search.getValue().trim(), item => `${item.label} ${item.description ?? ""}`);
42
+ list = new SelectList(matches, rows, { ...theme, noMatch: () => theme.noMatch(" No matches") }, { maxPrimaryColumnWidth: 68 });
43
+ const index = matches.findIndex(item => item.value === preferred);
44
+ if (index >= 0) list.setSelectedIndex(index);
45
+ list.onSelect = onSelect;
46
+ }
47
+ const nav = ["up", "down", "pageUp", "pageDown", "confirm"].map(key => `tui.select.${key}`);
48
+ return {
49
+ handleInput(data) {
50
+ if (keys.matches(data, "tui.select.cancel")) cancel();
51
+ else if (!rows) return;
52
+ else if (nav.some(key => keys.matches(data, key))) list.handleInput(data);
53
+ else {
54
+ const before = search.getValue();
55
+ search.handleInput(data);
56
+ if (search.getValue() !== before) rebuild(current);
57
+ }
58
+ },
59
+ render(width, room, focused) {
60
+ const visibleRows = width >= 24 ? Math.min(8, Math.max(0, room - 4)) : 0;
61
+ const label = value => theme.selectedText(truncateToWidth(value, width));
62
+ if (visibleRows !== rows) {
63
+ rows = visibleRows;
64
+ rebuild(list?.getSelectedItem()?.value ?? current);
65
+ }
66
+ if (!rows) return [label("Resize · Esc closes selector")];
67
+ search.focused = focused;
68
+ return [label(title), ...search.render(width), ...list.render(width), label("Enter select · Esc cancel")];
69
+ },
70
+ };
71
+ }
72
+
73
+ export function createCommands({ cwd, access, editor, keys, theme, controls, apply, perform, status, lastAnswer, quit }) {
74
+ let panel;
75
+ function cancel() { panel = undefined; }
76
+ function choose(snapshot, action) { cancel(); apply(snapshot, action); }
77
+ function chooseModel(snapshot, model) {
78
+ choose(snapshot, { type: "model", provider: model.provider, id: model.id });
79
+ }
80
+ function selectModel(snapshot, query) {
81
+ const models = snapshot.models;
82
+ const exact = query && models.find(model => modelName(model) === query);
83
+ if (exact) { chooseModel(snapshot, exact); return; }
84
+ const items = models.map((model, index) => ({ value: String(index), label: singleLine(modelName(model)),
85
+ description: model.label && singleLine(model.label) }));
86
+ panel = picker("Select model", items, { current: String(models.findIndex(model => sameModel(model, snapshot.model))),
87
+ query, keys, theme, cancel, onSelect: item => chooseModel(snapshot, models[Number(item.value)]) });
88
+ }
89
+ function selectThinking(snapshot, level) {
90
+ const select = thinkingLevel => choose(snapshot, { type: "thinking", thinkingLevel });
91
+ if (level) {
92
+ const match = snapshot.thinkingLevels.find(candidate => candidate === level.toLowerCase());
93
+ if (match) select(match);
94
+ else status(`Available thinking levels: ${snapshot.thinkingLevels.join(", ")}.`);
95
+ return;
96
+ }
97
+ panel = picker("Thinking level", snapshot.thinkingLevels.map(level => ({ value: level, label: singleLine(level) })),
98
+ { current: snapshot.model.thinkingLevel, keys, theme, cancel, onSelect: item => select(item.value) });
99
+ }
100
+ function info(title, lines) {
101
+ let start = 0, page = 1;
102
+ panel = {
103
+ handleInput(key) {
104
+ if (keys.matches(key, "tui.select.cancel")) cancel();
105
+ else if (keys.matches(key, "tui.select.up")) start--;
106
+ else if (keys.matches(key, "tui.select.down")) start++;
107
+ else if (keys.matches(key, "tui.select.pageUp")) start -= page;
108
+ else if (keys.matches(key, "tui.select.pageDown")) start += page;
109
+ },
110
+ render(width, room) {
111
+ if (room < 3) return [theme.selectedText(truncateToWidth("Resize · Esc close", width))];
112
+ const rows = lines.flatMap(line => wrapTextWithAnsi(singleLine(line), width));
113
+ page = room - 2;
114
+ start = Math.max(0, Math.min(start, rows.length - page));
115
+ return [theme.selectedText(truncateToWidth(title, width)), ...rows.slice(start, start + page),
116
+ theme.description(truncateToWidth(rows.length > page ? "↑/↓ scroll · Esc close" : "Esc close", width))];
117
+ },
118
+ };
119
+ }
120
+ function session({ session, model }) {
121
+ info("Durable conversation", [
122
+ `ID: ${session.id}`, `Directory: ${cwd}`, ...(access ? [`Access: ${access}`] : []),
123
+ ...(model ? [`Model: ${modelName(model)}`, `Thinking: ${model.thinkingLevel ?? "unknown"}`] : []),
124
+ ...(session.state ? [`State: ${session.state}`] : []),
125
+ ...(session.queued !== undefined ? [`Queued inputs: ${session.queued}`] : []),
126
+ ...(session.tokens !== undefined ? [`Recorded model tokens: ${session.tokens.toLocaleString()}`] : []),
127
+ ]);
128
+ }
129
+ function help(snapshot) {
130
+ info("Available commands and keys", [
131
+ ...available(snapshot).map(({ name, description, argumentHint }) => `/${name}${argumentHint ? ` ${argumentHint}` : ""} · ${description}`),
132
+ "Tab · Complete commands", "Shift+Enter or Ctrl+J · Insert newline", "Ctrl+O · Toggle tool output",
133
+ "PgUp/PgDn · Scroll transcript", "Ctrl+D on empty editor · Detach",
134
+ ...shortcuts.filter(({ enabled }) => enabled(snapshot)).map(({ key }) => `${bindings[key].defaultKeys} · ${bindings[key].description}`),
135
+ ]);
136
+ }
137
+ const enabled = {
138
+ model: snapshot => snapshot.model && snapshot.models?.length,
139
+ thinking: snapshot => snapshot.model && snapshot.thinkingLevels?.length,
140
+ cycle: snapshot => snapshot.model && scopedModels(snapshot).length > 1,
141
+ };
142
+ const commands = [
143
+ { name: "model", description: "Select conversation model", argumentHint: "[provider/id]", enabled: enabled.model, run: selectModel },
144
+ { name: "thinking", description: "Select thinking level", argumentHint: "[level]", enabled: enabled.thinking, run: selectThinking },
145
+ { name: "compact", description: "Summarize earlier context (model request)", argumentHint: "[instructions]",
146
+ enabled: snapshot => snapshot.compact, run: (snapshot, instructions) => apply(snapshot, { type: "compact", instructions }) },
147
+ { name: "session", description: "Show conversation information", enabled: snapshot => snapshot.session !== undefined, run: session },
148
+ { name: "copy", description: "Copy last completed answer", run: () => {
149
+ const text = lastAnswer();
150
+ if (!text) status("No completed assistant answer to copy.");
151
+ else perform(async () => { await copyToClipboard(text); return "Copied assistant answer."; });
152
+ } },
153
+ { name: "help", description: "Show available commands and keys", run: help },
154
+ { name: "hotkeys", description: "Show available commands and keys", run: help },
155
+ { name: "quit", description: "Detach this terminal client", run: quit },
156
+ { name: "detach", description: "Detach this terminal client", run: quit },
157
+ ];
158
+ const shortcuts = [
159
+ { key: "selectModel", enabled: enabled.model, run: snapshot => selectModel(snapshot, "") },
160
+ { key: "cycleModel", enabled: enabled.cycle, run: snapshot => chooseModel(snapshot, nextScopedModel(snapshot, 1)) },
161
+ { key: "previousModel", enabled: enabled.cycle, run: snapshot => chooseModel(snapshot, nextScopedModel(snapshot, -1)) },
162
+ { key: "cycleThinking", enabled: enabled.thinking, run: snapshot => {
163
+ const levels = snapshot.thinkingLevels;
164
+ if (levels.length === 1) status(`Only ${levels[0]} is available for this model.`);
165
+ else choose(snapshot, { type: "thinking", thinkingLevel: levels[(levels.indexOf(snapshot.model.thinkingLevel) + 1) % levels.length] });
166
+ } },
167
+ { key: "followUp", enabled: snapshot => snapshot.followUp, run: snapshot => {
168
+ const draft = editor.getExpandedText();
169
+ const content = draft.trim();
170
+ if (parseCommand(content)) status("Use Enter to run a command.");
171
+ else if (content) apply(snapshot, { type: "followUp", content }, draft);
172
+ } },
173
+ ];
174
+ const available = snapshot => commands.filter(command => !command.enabled || command.enabled(snapshot));
175
+ const completion = new CombinedAutocompleteProvider([], cwd);
176
+ editor.setAutocompleteProvider({
177
+ getSuggestions(lines, row, col, options) {
178
+ const snapshot = controls();
179
+ // Restrict Pi completion to slash commands; never enumerate the client's filesystem for a host's cwd.
180
+ if (!snapshot || lines.length !== 1 || !/^\s*\/[a-z-]*$/i.test(lines[row].slice(0, col))) return null;
181
+ return new CombinedAutocompleteProvider(available(snapshot), cwd).getSuggestions(lines, row, col, { ...options, force: false });
182
+ },
183
+ applyCompletion: (...args) => completion.applyCompletion(...args),
184
+ });
185
+ return {
186
+ get active() { return Boolean(panel); }, cancel,
187
+ render: (...args) => panel?.render(...args),
188
+ input(key) {
189
+ if (panel) { panel.handleInput(key); return true; }
190
+ const snapshot = controls();
191
+ const shortcut = snapshot && shortcuts.find(binding => binding.enabled(snapshot) && keys.matches(key, bindingName(binding.key)));
192
+ if (!shortcut) return false;
193
+ shortcut.run(snapshot);
194
+ return true;
195
+ },
196
+ submit(text) {
197
+ const snapshot = controls();
198
+ const parsed = snapshot && parseCommand(text);
199
+ if (!parsed) return false;
200
+ const command = available(snapshot).find(({ name }) => name === parsed.name);
201
+ if (!command) status(`/${parsed.name} is not available here. See /help.`);
202
+ else if (parsed.argument && !command.argumentHint) status(`Usage: /${parsed.name}`);
203
+ else command.run(snapshot, parsed.argument);
204
+ return true;
205
+ },
206
+ };
207
+ }
package/index.mjs ADDED
@@ -0,0 +1,251 @@
1
+ import { homedir } from "node:os";
2
+ import { basename, isAbsolute, relative, sep } from "node:path";
3
+ import { getSelectListTheme, getSettingsListTheme, initTheme } from "@earendil-works/pi-coding-agent";
4
+ import { Editor, KeybindingsManager, matchesKey, ProcessTerminal, setKeybindings, truncateToWidth,
5
+ TuiMainScreen, TUI_KEYBINDINGS, visibleWidth } from "@earendil-works/pi-tui";
6
+ import { COMMAND_KEYS, createCommands, modelName } from "./commands.mjs";
7
+ import { clean, createTranscript } from "./transcript.mjs";
8
+
9
+ // Approval text must not use word wrapping that drops spaces at line breaks.
10
+ const segmenter = new Intl.Segmenter();
11
+ function exactRows(lines, width) {
12
+ return lines.join("\n").split("\n").flatMap(line => {
13
+ const rows = [];
14
+ let row = "", used = 0;
15
+ for (const { segment } of segmenter.segment(line)) {
16
+ const size = visibleWidth(segment);
17
+ if (used + size > width) { rows.push(row); row = ""; used = 0; }
18
+ row += segment;
19
+ used += size;
20
+ }
21
+ return [...rows, row];
22
+ });
23
+ }
24
+
25
+ const oneLine = value => clean(value).replaceAll("\n", " ");
26
+ const isApproval = review => review?.id !== undefined;
27
+ const sameApproval = (a, b) => isApproval(a) && a.id === b?.id && a.key === b.key;
28
+ function displayCwd(cwd) {
29
+ const home = homedir();
30
+ if (!home) return cwd;
31
+ const path = relative(home, cwd);
32
+ if (path === ".." || path.startsWith(`..${sep}`) || isAbsolute(path)) return cwd;
33
+ return path ? `~${sep}${path}` : "~";
34
+ }
35
+
36
+ // Foreground UI only. The adapter owns persisted history, execution and authorization.
37
+ export function runDurableChat({ title, cwd, access, model, read, submit, close }, { theme = "dark" } = {}) {
38
+ if (!process.stdin.isTTY) throw new Error("Run the Durable chat in a terminal.");
39
+ initTheme(theme);
40
+ const selectList = getSelectListTheme();
41
+ const { selectedText: accent, description: muted } = selectList;
42
+ const { description: dim } = getSettingsListTheme();
43
+ const pwd = oneLine(displayCwd(cwd));
44
+ function metadata(width) {
45
+ const current = view?.controls?.model ?? model;
46
+ if (!current) return dim(truncateToWidth(pwd, width));
47
+ const modelText = oneLine(`${modelName(current)}${current.thinkingLevel ? ` · thinking ${current.thinkingLevel}` : ""}`);
48
+ const right = truncateToWidth(modelText, width);
49
+ const space = width - visibleWidth(right);
50
+ const left = space > 2 ? truncateToWidth(pwd, space - 2) : "";
51
+ return dim(left) + " ".repeat(space - visibleWidth(left)) + muted(right);
52
+ }
53
+ const keys = new KeybindingsManager({ ...TUI_KEYBINDINGS, ...COMMAND_KEYS,
54
+ "app.tools.expand": { defaultKeys: "ctrl+o", description: "Toggle tool output" },
55
+ });
56
+ setKeybindings(keys);
57
+ const terminal = new ProcessTerminal();
58
+ const tui = new TuiMainScreen(terminal);
59
+ const editor = new Editor(tui, { borderColor: muted, selectList }, { paddingX: 1 });
60
+ const transcript = createTranscript(tui, cwd, editor);
61
+ let cursor = 0, view, status = "Connecting…", scroll = 0, review, dismissed, connected = false, closed = false;
62
+ let lastProgramStatus, reading, sending = false;
63
+ const commands = createCommands({ cwd, access, editor, keys, theme: selectList,
64
+ controls: () => connected ? view.controls : undefined,
65
+ apply(snapshot, action, draft) {
66
+ if (!connected || sending) { status = "Another action is in flight."; return; }
67
+ if (draft !== undefined) { editor.setText(""); scroll = 0; }
68
+ status = action.type === "compact" ? "Requesting compaction…" : "Sending…";
69
+ void act(() => snapshot.submit(action), draft);
70
+ },
71
+ perform: action => { if (!sending) void act(action); },
72
+ status: value => { status = value; }, lastAnswer: transcript.lastAnswer, quit,
73
+ });
74
+ function repaint() { if (!closed) tui.requestRender(); }
75
+ function resetReviewLayout() { if (review) review.layout = undefined; }
76
+ const signals = ["SIGHUP", "SIGINT", "SIGTERM"];
77
+ function quit() {
78
+ if (closed) return;
79
+ closed = true;
80
+ clearInterval(watch);
81
+ for (const signal of signals) process.off(signal, quit);
82
+ process.off("SIGWINCH", resetReviewLayout);
83
+ terminal.setProgramStatus({ state: "clear" });
84
+ tui.stop();
85
+ close?.();
86
+ }
87
+ async function act(action, draft) {
88
+ sending = true;
89
+ try {
90
+ const next = await action();
91
+ if (typeof next === "string") status = next;
92
+ else if (next && !closed && !review) { commands.cancel(); review = { ...next }; }
93
+ } catch (err) {
94
+ status = err.message;
95
+ if (draft !== undefined && !editor.getText()) editor.setText(draft);
96
+ } finally {
97
+ // A read already in flight may predate this action. Refresh even after a rejection.
98
+ await reading;
99
+ await refresh();
100
+ sending = false;
101
+ repaint();
102
+ }
103
+ }
104
+ function closeReview() {
105
+ const choice = review;
106
+ if (isApproval(choice)) dismissed = { id: choice.id, key: choice.key };
107
+ review = undefined;
108
+ return choice;
109
+ }
110
+ function handleReview(key) {
111
+ if (matchesKey(key, "escape") || matchesKey(key, "ctrl+c")) {
112
+ closeReview();
113
+ status = "Review closed. Nothing sent.";
114
+ return;
115
+ }
116
+ const frame = review.layout;
117
+ if (!connected || sending || !frame?.shown || frame.width !== terminal.columns || frame.height !== terminal.rows) return;
118
+ if (matchesKey(key, "pageUp") || matchesKey(key, "pageDown")) {
119
+ frame.scroll = Math.max(0, frame.start + frame.page * (matchesKey(key, "pageUp") ? -1 : 1));
120
+ frame.shown = false;
121
+ return;
122
+ }
123
+ const yes = matchesKey(key, "y"), no = matchesKey(key, "n");
124
+ if (!frame.complete || !(yes || (no && review.deny))) return;
125
+ const choice = closeReview();
126
+ status = "Sending…";
127
+ void act(() => choice.submit(yes));
128
+ }
129
+ function renderReview(width, height, page) {
130
+ const line = (style, value) => style(truncateToWidth(value, width));
131
+ if (width < 24 || page < 1) {
132
+ resetReviewLayout();
133
+ return [line(accent, "Resize · Esc closes review")];
134
+ }
135
+ if (review.layout?.width !== width || review.layout?.height !== height || review.layout?.page !== page) {
136
+ // Adapter review lines must already escape invisible characters without losing information.
137
+ review.layout = { width, height, page, scroll: 0, reviewed: 0, rows: exactRows(review.lines.map(clean), width - 2) };
138
+ }
139
+ const frame = review.layout;
140
+ const { rows } = frame;
141
+ const start = Math.min(frame.scroll, Math.max(0, rows.length - page));
142
+ const end = Math.min(rows.length, start + page);
143
+ if (start <= frame.reviewed) frame.reviewed = Math.max(frame.reviewed, end);
144
+ const complete = end === rows.length && frame.reviewed === end;
145
+ Object.assign(frame, { start, complete, shown: true });
146
+ const confirm = review.deny ? "y approve · n deny" : `y ${review.confirm ?? "confirm"}`;
147
+ return [line(accent, `${clean(review.title)} · ${start + 1}–${end}/${rows.length}`),
148
+ ...rows.slice(start, end).map(row => `${muted("│ ")}${row}`),
149
+ line(accent, `${complete ? confirm : "PgDn review"} · Esc close`)];
150
+ }
151
+
152
+ const root = {
153
+ focused: false,
154
+ invalidate() { editor.invalidate(); transcript.invalidate(); },
155
+ handleInput(key) {
156
+ if (matchesKey(key, "ctrl+d") && (review || (!commands.active && !editor.getText()))) { quit(); return; }
157
+ if (review) handleReview(key);
158
+ else if (commands.input(key)) { repaint(); return; }
159
+ else if (keys.matches(key, "app.tools.expand")) status = `Tool output ${transcript.toggleTools() ? "expanded" : "collapsed"}.`;
160
+ else if (!editor.isShowingAutocomplete() && matchesKey(key, "pageUp")) scroll += 12;
161
+ else if (!editor.isShowingAutocomplete() && matchesKey(key, "pageDown")) scroll = Math.max(0, scroll - 12);
162
+ else if (matchesKey(key, "ctrl+c")) editor.setText("");
163
+ else editor.handleInput(key);
164
+ repaint();
165
+ },
166
+ render(width) {
167
+ const height = terminal.rows;
168
+ const line = (style, value) => style(truncateToWidth(oneLine(value), width));
169
+ if (height < 6 || width < 3) { resetReviewLayout(); commands.cancel(); return [line(accent, "Resize · Ctrl+D detach")]; }
170
+ const rows = transcript.render(width);
171
+ const top = [line(accent, access ? `${title} · ${access}` : title)];
172
+ const footer = [metadata(width), line(dim, view?.controls ? "/help · Ctrl+O tools · Ctrl+D detach" :
173
+ "Ctrl+O tools · PgUp/PgDn scroll · Ctrl+D detach (empty editor)")];
174
+ const waiting = connected && view.program.state === "blocked";
175
+ const info = [line(waiting ? accent : muted, connected ? view.label : "Disconnected; reconnect only reads history."), line(muted, status)];
176
+ let bottom;
177
+ if (review) {
178
+ // Pin the exact review above the key hints, leaving a few transcript lines visible.
179
+ const available = height - top.length - info.length - footer.length - 2; // Review title and confirmation.
180
+ bottom = renderReview(width, height, available - Math.min(3, Math.max(0, available - 1)));
181
+ } else if (commands.active) {
182
+ bottom = commands.render(width, height - top.length - info.length - footer.length, root.focused);
183
+ } else {
184
+ editor.focused = root.focused;
185
+ bottom = editor.render(width);
186
+ if (view?.notice && height > top.length + info.length + bottom.length + footer.length + 2) info.push(line(muted, view.notice));
187
+ }
188
+ const room = Math.max(0, height - top.length - info.length - bottom.length - footer.length);
189
+ scroll = Math.min(scroll, Math.max(0, rows.length - room));
190
+ const end = rows.length - scroll;
191
+ return [...top, ...rows.slice(Math.max(0, end - room), end), ...info, ...bottom, ...footer].slice(-height);
192
+ },
193
+ };
194
+ editor.onSubmit = value => {
195
+ if (!value || closed) return;
196
+ if (value === "/detach") { quit(); return; }
197
+ if (!connected || sending) {
198
+ editor.setText(value);
199
+ status = connected ? "A command is in flight." : "Reconnect before issuing commands.";
200
+ repaint();
201
+ return;
202
+ }
203
+ if (commands.submit(value)) { repaint(); return; }
204
+ scroll = 0;
205
+ void act(() => submit(value));
206
+ };
207
+
208
+ function refresh() {
209
+ if (!closed) return reading ??= poll().finally(() => { reading = undefined; });
210
+ }
211
+ async function poll() {
212
+ try {
213
+ view = await read(cursor);
214
+ if (closed) return;
215
+ for (const message of view.messages) transcript.append(message);
216
+ cursor = view.cursor;
217
+ transcript.update(view);
218
+ if (!connected) status = "Connected · read-only catch-up";
219
+ connected = true;
220
+ if (isApproval(review) && !sameApproval(review, view.approval)) {
221
+ // Discard the old layout without dismissing its replacement.
222
+ review = undefined;
223
+ status = "Approval changed or expired; nothing sent.";
224
+ }
225
+ if (!isApproval(review) && view.approval && !sameApproval(dismissed, view.approval)) {
226
+ commands.cancel();
227
+ review = { ...view.approval, layout: undefined };
228
+ }
229
+ } catch { connected = false; commands.cancel(); resetReviewLayout(); }
230
+ finally {
231
+ if (!closed) {
232
+ const next = connected ? view.program : { state: "error", message: "Disconnected" };
233
+ const signature = JSON.stringify(next);
234
+ if (signature !== lastProgramStatus) {
235
+ lastProgramStatus = signature;
236
+ terminal.setProgramStatus({ app: "pi-durable", ...next });
237
+ }
238
+ }
239
+ repaint();
240
+ }
241
+ }
242
+ const watch = setInterval(() => void refresh(), 180);
243
+ for (const signal of signals) process.once(signal, quit);
244
+ process.on("SIGWINCH", resetReviewLayout);
245
+ tui.addChild(root);
246
+ tui.setFocus(root);
247
+ tui.start();
248
+ terminal.setTitle(oneLine(`Pi Durable - ${title} - ${basename(cwd) || cwd}`));
249
+ void refresh();
250
+ return quit;
251
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@rwjblue/pi-durable-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Attach-only terminal UI for Pi Durable conversations",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/rwjblue/pi-durable-ui.git"
9
+ },
10
+ "publishConfig": { "access": "public" },
11
+ "type": "module",
12
+ "exports": "./index.mjs",
13
+ "bin": { "pi-durable-ui-self-test": "./self-test.mjs" },
14
+ "files": ["index.mjs", "commands.mjs", "transcript.mjs", "self-test.mjs", "self-test-controls.mjs", "README.md"],
15
+ "scripts": { "test": "node --test *.test.mjs" },
16
+ "engines": { "node": ">=22.19.0" },
17
+ "dependencies": {
18
+ "@earendil-works/pi-coding-agent": "1.8.0",
19
+ "@earendil-works/pi-tui": "1.8.0"
20
+ },
21
+ "optionalDependencies": {
22
+ "@earendil-works/chord": "1.8.0",
23
+ "@earendil-works/pi-ai": "1.8.0",
24
+ "@earendil-works/pi-durable": "1.8.0",
25
+ "@earendil-works/pi-schema": "1.8.0"
26
+ }
27
+ }
@@ -0,0 +1,125 @@
1
+ import { clampThinkingLevel, getSupportedThinkingLevels } from "@earendil-works/pi-ai/models";
2
+ import { AgentDoc, configure, defineDoc, InboxDoc, LiveDoc, UsageDoc } from "@earendil-works/pi-durable";
3
+
4
+ // This revision belongs to the disposable host. It is committed alongside settings changes
5
+ // so a delayed approval can't be used twice or after switching away and back to the same model.
6
+ const ControlsDoc = defineDoc({ kind: "self-test.controls", version: 1, scope: "conversation", history: "latest", fork: "initial",
7
+ initial: () => ({ revision: 0 }), checkpointWhen: () => true,
8
+ });
9
+ const ref = ({ provider, id }) => ({ provider, id });
10
+ const name = ({ provider, id }) => `${provider}/${id}`;
11
+ export function exactJson(value) {
12
+ return JSON.stringify(value, null, 2).replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, char =>
13
+ char === "\n" ? char : char.split("").map(unit => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`).join(""));
14
+ }
15
+ function idle(live, inbox) {
16
+ return !live?.run && !live?.compactions?.length && !inbox?.items.length;
17
+ }
18
+
19
+ // A single-operator, in-process adapter. The UI serializes explicit submissions to this fixture.
20
+ export function fixtureControls({ harness, root, context, models, available, cycleModels, defaultThinking, now = Date.now }) {
21
+ async function checkIdle(tx) {
22
+ const live = await tx.doc(LiveDoc, root.id);
23
+ const inbox = await tx.doc(InboxDoc, root.id);
24
+ if (!idle(live, inbox)) throw new Error("Wait until the conversation and its queue are idle.");
25
+ }
26
+ function allowed(target) {
27
+ const match = available().find(option => option.provider === target.provider && option.id === target.id);
28
+ const model = match && models.getModel(target.provider, target.id);
29
+ if (!model) throw new Error("That model is not available. Choose again.");
30
+ return model;
31
+ }
32
+ function apply(expected, change, approval) {
33
+ return root.commit(async tx => {
34
+ await checkIdle(tx);
35
+ const state = await tx.doc(AgentDoc, root.id);
36
+ const settings = await tx.doc(ControlsDoc, root.id);
37
+ if (settings.revision !== expected.revision || state.model?.provider !== expected.model.provider ||
38
+ state.model?.modelId !== expected.model.id || state.thinkingLevel !== expected.model.thinkingLevel) {
39
+ throw new Error("Conversation settings changed. Choose again.");
40
+ }
41
+ const requested = change.model ?? expected.model;
42
+ if (!await models.checkAuth(requested.provider)) throw new Error("That provider is not available. Choose again.");
43
+ const target = allowed(requested);
44
+ if (approval && (((await tx.latestEntryId(root.id)) ?? 0) !== approval.after || now() >= approval.until)) {
45
+ throw new Error("The review expired or the conversation changed. Choose again.");
46
+ }
47
+ if (!getSupportedThinkingLevels(target).includes(change.thinkingLevel)) throw new Error("That thinking level is not available.");
48
+ if (change.thinkingLevel === expected.model.thinkingLevel && name(target) === name(expected.model)) {
49
+ return change.model ? `Model: ${name(target)}` : `Thinking level: ${change.thinkingLevel}`;
50
+ }
51
+ if (change.model) {
52
+ await configure(tx, root.id, { model: { provider: target.provider, modelId: target.id }, thinkingLevel: change.thinkingLevel });
53
+ } else {
54
+ await configure(tx, root.id, { thinkingLevel: change.thinkingLevel });
55
+ }
56
+ settings.revision++;
57
+ return change.model ? `Model: ${name(target)}` : `Thinking level: ${change.thinkingLevel}`;
58
+ }, context);
59
+ }
60
+ async function input(content, whenBusy) {
61
+ const submission = await root.submit({ type: "input", content, whenBusy }, context);
62
+ const record = await submission.status(context);
63
+ if (record.status === "unanswered") return `Input not answered: ${record.reason}.`;
64
+ if (record.status === "queued") return whenBusy === "followUp" ? "Follow-up queued." : "Steering input queued.";
65
+ return "Input accepted.";
66
+ }
67
+ async function compact(instructions) {
68
+ // The fixture is the only submitter. If there's no run, queue, or compaction at this
69
+ // check, nothing can enqueue work between it and the explicit compact() admission.
70
+ await root.commit(checkIdle, context);
71
+ const id = await root.compact(instructions || undefined, context);
72
+ const { state: { outcome } } = await harness.waitForTask(id, context);
73
+ if (outcome.status !== "completed") return `Compaction ${outcome.status}: ${outcome.error?.message ?? outcome.reason ?? "no summary saved"}.`;
74
+ if (!outcome.result.submissionId) return "Nothing to compact yet.";
75
+ const summary = await harness.submission(outcome.result.submissionId, context);
76
+ const receipt = await summary?.status(context);
77
+ return receipt?.status === "done" ? "Context compacted." : "Compaction did not save a summary.";
78
+ }
79
+ return {
80
+ input,
81
+ async read(after, live) {
82
+ const [agent, settings, inbox, usage] = await Promise.all([
83
+ harness.snapshot(AgentDoc, root.id, context), harness.snapshot(ControlsDoc, root.id, context),
84
+ harness.snapshot(InboxDoc, root.id, context), harness.snapshot(UsageDoc, root.id, context),
85
+ ]);
86
+ const model = { provider: agent.model.provider, id: agent.model.modelId, thinkingLevel: agent.thinkingLevel };
87
+ const expected = { model, revision: settings?.revision ?? 0 };
88
+ const current = models.getModel(model.provider, model.id);
89
+ const catalog = available();
90
+ return {
91
+ model, models: catalog.map(option => ({ ...ref(option), label: option.name })),
92
+ cycleModels: cycleModels.filter(option => catalog.some(candidate => name(option) === name(candidate))).map(ref),
93
+ thinkingLevels: current ? getSupportedThinkingLevels(current) : [],
94
+ session: {
95
+ id: root.id, state: live?.tools?.some(slot => slot.status === "sleeping") ? "Waiting" :
96
+ live?.compactions?.length ? "Compacting" : live?.run ? "Working" : "Idle",
97
+ queued: (inbox?.items ?? []).filter(item => item.mode !== "write").length,
98
+ tokens: Object.values(usage?.models ?? {}).reduce((total, value) => total + value.totalTokens, 0),
99
+ },
100
+ followUp: true, compact: true,
101
+ async submit(action) {
102
+ switch (action.type) {
103
+ case "followUp": return input(action.content, "followUp");
104
+ case "compact": return compact(action.instructions);
105
+ case "thinking": return apply(expected, { thinkingLevel: action.thinkingLevel });
106
+ case "model": {
107
+ const target = allowed(action);
108
+ const level = name(target) === name(model) ? model.thinkingLevel : defaultThinking(target, model.thinkingLevel);
109
+ const change = { model: ref(target), thinkingLevel: clampThinkingLevel(target, level) };
110
+ if (target.provider === model.provider) return apply(expected, change);
111
+ if (!idle(live, inbox)) throw new Error("Wait until the conversation and its queue are idle.");
112
+ const review = { until: now() + 5 * 60_000, after };
113
+ return { title: "Switch provider", confirm: "switch", lines: [
114
+ exactJson({ conversation: root.id, from: model, to: { ...change.model, thinkingLevel: change.thinkingLevel } }),
115
+ "The next turn can send this conversation’s context to the new provider.",
116
+ `Expires ${new Date(review.until).toISOString()}`,
117
+ ], submit: allow => allow ? apply(expected, change, review) : "Provider unchanged." };
118
+ }
119
+ default: throw new Error("Unsupported fixture action.");
120
+ }
121
+ },
122
+ };
123
+ },
124
+ };
125
+ }
package/self-test.mjs ADDED
@@ -0,0 +1,227 @@
1
+ #!/usr/bin/env node
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { parseArgs } from "node:util";
7
+ import { BACKGROUND_CONTEXT as context } from "@earendil-works/chord/context";
8
+ import { clampThinkingLevel, createModels } from "@earendil-works/pi-ai/models";
9
+ import { fauxAssistantMessage as say, fauxProvider, fauxText, fauxToolCall } from "@earendil-works/pi-ai/providers/faux";
10
+ import { getAgentDir, hasTrustRequiringProjectResources, loadProjectContextFiles, ModelRuntime,
11
+ ProjectTrustStore, resolveCliModel, resolveModelScopeWithDiagnostics, SettingsManager } from "@earendil-works/pi-coding-agent";
12
+ import { CompactionEntry, createRegistry, defineExtension, defineSignal, defineTool, Harness, LiveDoc } from "@earendil-works/pi-durable";
13
+ import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
14
+ import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
15
+ import { CodingTools } from "@earendil-works/pi-durable/tools";
16
+ import { bool, obj, str } from "@earendil-works/pi-schema";
17
+ import { runDurableChat } from "./index.mjs";
18
+ import { exactJson, fixtureControls } from "./self-test-controls.mjs";
19
+
20
+ const usage = `Usage: pi-durable-ui-self-test [--model <pattern> | --offline]
21
+
22
+ Run a scratch Durable conversation using your Pi profile and local coding tools.
23
+ --model <pattern> Override the saved model (Pi's provider/model[:thinking] syntax).
24
+ --offline Use scripted faux models, with no Pi profile or network.
25
+ --help Show this help.
26
+
27
+ Connected mode sends prompts and tool results to the selected provider. Its
28
+ read, write, edit and bash tools run with your local permissions, like Pi.
29
+ Ctrl+D on an empty editor exits and deletes the scratch conversation.`;
30
+ let flags;
31
+ try {
32
+ ({ values: flags } = parseArgs({ options: { model: { type: "string" }, offline: { type: "boolean" }, help: { type: "boolean" } } }));
33
+ if (flags.help) { console.log(usage); process.exit(0); }
34
+ if (flags.offline && flags.model !== undefined) throw new Error("--offline cannot be combined with --model.");
35
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("Run the self-test in a terminal.");
36
+ } catch (err) {
37
+ console.error(`${err.message}\n\n${usage}`);
38
+ process.exit(1);
39
+ }
40
+
41
+ // This is a disposable fixture, not a daemon or a host for arbitrary sessions.
42
+ const registry = createRegistry();
43
+ const decision = defineSignal({ name: "self-test.preview", version: 1, schema: obj({ allow: bool() }) });
44
+ let pending;
45
+ const previewTool = defineTool({
46
+ name: "preview_card", description: "Show a harmless fixture card in the terminal.",
47
+ parameters: obj({ title: str() }), callers: ["model"], replay: "safe",
48
+ async execute(args, api, ctx) {
49
+ const answer = await api.readSignal(decision, "preview", ctx);
50
+ if (!answer) {
51
+ const until = api.now() + 5 * 60_000;
52
+ pending = { id: api.taskId, args, until };
53
+ return { kind: "sleep", signals: [decision.key("preview")], until };
54
+ }
55
+ pending = undefined;
56
+ if (answer.kind !== "value" || !answer.value.allow) {
57
+ return { output: [{ type: "text", text: "Fixture preview not approved." }], isError: true };
58
+ }
59
+ for (let i = 1; i <= 14; i++) {
60
+ api.output(`${args.title} · line ${i}\n`);
61
+ await delay(85, undefined, { signal: ctx.abortSignal });
62
+ }
63
+ return {};
64
+ },
65
+ });
66
+ registry.install(defineExtension({ name: "self-test", tools: [previewTool] }));
67
+
68
+ function offlineProfile() {
69
+ const speed = { tokensPerSecond: 18, tokenSize: { min: 2, max: 2 } };
70
+ const faux = fauxProvider({ ...speed, models: [
71
+ { id: "faux-1", name: "Faux model" }, { id: "faux-1-reasoning", name: "Faux reasoning", reasoning: true },
72
+ ] });
73
+ const other = fauxProvider({ ...speed, provider: "faux-other", models: [{ id: "faux-1", name: "Second faux provider" }] });
74
+ const catalog = [...faux.models, ...other.models];
75
+ const model = faux.getModel();
76
+ const models = createModels();
77
+ for (const fixture of [faux, other]) {
78
+ models.setProvider(fixture.provider);
79
+ function respond(ctx, options, _state, model) {
80
+ fixture.appendResponses([respond]);
81
+ return respondTo(ctx.messages, options, model);
82
+ }
83
+ fixture.setResponses([respond]);
84
+ }
85
+ function respondTo(messages, options, model) {
86
+ const last = messages.at(-1);
87
+ if (last?.role === "toolResult") return say(last.isError ? "The preview was not shown." : "The preview finished. Ctrl+O expands its output.");
88
+ const prompt = last?.role !== "user" ? "" : typeof last.content === "string" ? last.content :
89
+ last.content.filter(part => part.type === "text").map(part => part.text).join("\n");
90
+ if (prompt.trim().toLowerCase() === "preview") {
91
+ return say([fauxText("I'll show a **fixture card** after you review its exact arguments."),
92
+ fauxToolCall("preview_card", { title: "Sample card" })], { stopReason: "toolUse" });
93
+ }
94
+ return say(`## Durable self-test\n\nRequest: ${model.provider}/${model.id} · thinking ${options?.reasoning ?? "off"}\n\nYou said:\n\n${String(prompt || "(no text)").split("\n").map(line => `> ${line}`).join("\n")}\n\nType \`preview\` to try the harmless approval and tool output.`);
95
+ }
96
+ return { models, model, thinkingLevel: "off", available: () => catalog, cycleModels: faux.models,
97
+ defaultThinking: (_target, current) => current, settings: { compaction: { enabled: false, keepRecentTokens: 200 } } };
98
+ }
99
+
100
+ async function connectedProfile(cwd, models) {
101
+ const agentDir = getAgentDir();
102
+ const settings = SettingsManager.create(cwd, agentDir, { projectTrusted: false });
103
+ const trusted = new ProjectTrustStore(agentDir).get(cwd) ??
104
+ (settings.getDefaultProjectTrust() === "always" || !hasTrustRequiringProjectResources(cwd));
105
+ settings.setProjectTrusted(trusted);
106
+
107
+ const modelError = models.getError();
108
+ if (modelError) console.error(`Pi model configuration: ${modelError}`);
109
+ let model, thinking;
110
+ const patterns = settings.getEnabledModels();
111
+ const { scopedModels, diagnostics } = patterns?.length ? await resolveModelScopeWithDiagnostics(patterns, models) :
112
+ { scopedModels: [], diagnostics: [] };
113
+ for (const { message } of diagnostics) console.error(message);
114
+ if (flags.model !== undefined) {
115
+ const resolved = resolveCliModel({ cliModel: flags.model, modelRuntime: models });
116
+ if (!resolved.model || !models.getModel(resolved.model.provider, resolved.model.id)) {
117
+ throw new Error(resolved.error ?? "Choose a model registered in Pi's catalog or models.json.");
118
+ }
119
+ ({ model, thinkingLevel: thinking } = resolved);
120
+ } else {
121
+ if (scopedModels.length) ({ model, thinkingLevel: thinking } = scopedModels[0]);
122
+ const provider = settings.getDefaultProvider(), id = settings.getDefaultModel();
123
+ if (!model && provider && id) {
124
+ model = models.getModel(provider, id);
125
+ if (!model || !models.hasConfiguredAuth(provider)) {
126
+ throw new Error(`Pi's saved model ${provider}/${id} is unavailable. Check Pi's connection or select --model; use --offline for the fixture.`);
127
+ }
128
+ }
129
+ model ??= models.getAvailableSnapshot()[0];
130
+ }
131
+ if (!model || !models.hasConfiguredAuth(model.provider)) {
132
+ throw new Error("No usable Pi connection for the selected model. Configure one in Pi, or use --offline.");
133
+ }
134
+ const thinkingLevel = clampThinkingLevel(model, thinking ?? settings.getModelThinkingLevel(model.provider, model.id)
135
+ ?? settings.getDefaultThinkingLevel() ?? "medium");
136
+
137
+ registry.install(CodingTools);
138
+ const toolNames = settings.getDefaultTools();
139
+ const codingTools = toolNames ? toolNames.flatMap(name => CodingTools.tools.filter(tool => tool.name === name)) : CodingTools.tools;
140
+ const tools = [...codingTools, previewTool];
141
+ const thinkingBudgets = settings.getThinkingBudgets();
142
+ const instructions = [
143
+ `You are a coding assistant working in ${cwd}. Only call preview_card when asked to try the approval fixture.`,
144
+ ...loadProjectContextFiles({ cwd, agentDir }).map(({ path, content }) => `## ${path}\n\n${content}`),
145
+ ].join("\n\n");
146
+ return { models, model, thinkingLevel, tools, instructions, theme: settings.getTheme(),
147
+ available: () => models.getAvailableSnapshot(), cycleModels: scopedModels.map(({ model }) => model),
148
+ defaultThinking: (target, current) => scopedModels.find(({ model }) => model.provider === target.provider && model.id === target.id)?.thinkingLevel
149
+ ?? settings.getModelThinkingLevel(target.provider, target.id) ?? current,
150
+ env: () => new NodeExecutionEnv({ cwd, shellPath: settings.getShellPath() }),
151
+ settings: {
152
+ stream: { transport: settings.getTransport(), ...(thinkingBudgets ? { thinkingBudgets } : {}) },
153
+ retry: settings.getRetrySettings(), compaction: settings.getCompactionSettings(model),
154
+ steeringMode: settings.getSteeringMode(), followUpMode: settings.getFollowUpMode(),
155
+ },
156
+ };
157
+ }
158
+
159
+ const offline = flags.offline === true;
160
+ const scratch = await mkdtemp(join(tmpdir(), "pi-durable-ui-"));
161
+ let harness, modelRuntime;
162
+ try {
163
+ const cwd = offline ? scratch : process.cwd();
164
+ if (!offline) {
165
+ // Share Pi's connection logic without creating a native session or loading its extension runtime.
166
+ modelRuntime = await ModelRuntime.create({ allowModelNetwork: false });
167
+ }
168
+ const { models, model: { provider, id }, thinkingLevel, env, settings, instructions, tools, theme, available, cycleModels, defaultThinking } =
169
+ offline ? offlineProfile() : await connectedProfile(cwd, modelRuntime);
170
+ harness = await Harness.open(await openNodeSqliteStorage(join(scratch, "session.sqlite")), {
171
+ models, registry, env, settings: { ...settings, toolExecution: "sequential" },
172
+ }, context);
173
+ const root = await harness.root(context, { agent: { cwd, model: { provider, modelId: id }, thinkingLevel, instructions, tools } });
174
+ const controls = fixtureControls({ harness, root, context, models, available, cycleModels, defaultThinking });
175
+ const done = Promise.withResolvers();
176
+ const idle = offline ? "Offline fixture · type anything, or preview to try a tool" : "Pi connection · ask a question or try a coding task";
177
+ runDurableChat({ title: "Durable UI self-test", cwd, access: offline ? undefined : "local coding tools", model: { provider, id, thinkingLevel },
178
+ async read(after) {
179
+ const messages = [];
180
+ for (;;) {
181
+ const { items } = await root.entries({ order: "ascending", minEntryId: after + 1 }, 30, undefined, context);
182
+ for (const entry of items) {
183
+ after = entry.id;
184
+ if (entry.model && entry.kind !== CompactionEntry.kind) messages.push(...entry.model);
185
+ }
186
+ if (items.length < 30) break;
187
+ }
188
+ const live = await harness.snapshot(LiveDoc, root.id, context);
189
+ const gate = pending;
190
+ const approval = gate && gate.until > Date.now() && live?.tools?.some(slot => slot.taskId === gate.id && slot.status === "sleeping") ? {
191
+ id: gate.id, key: gate.id, title: "Exact arguments · preview_card", deny: true,
192
+ // Preserve invisible characters in model-supplied arguments as visible JSON escapes.
193
+ lines: [
194
+ exactJson(gate.args),
195
+ `Fixture only · expires ${new Date(gate.until).toISOString()}`,
196
+ ],
197
+ submit: allow => root.commit(async tx => {
198
+ const task = await tx.task(gate.id);
199
+ if (task?.state.status !== "sleeping" || gate.until <= Date.now() ||
200
+ await tx.signal(gate.id, decision, "preview", { allow }) !== "delivered") {
201
+ throw new Error("Fixture decision changed or expired; nothing sent.");
202
+ }
203
+ return allow ? "Preview approved." : "Preview denied.";
204
+ }, context),
205
+ } : undefined;
206
+ const failure = !live?.run && live?.runFailure;
207
+ const compacting = live?.compactions?.length;
208
+ return { cursor: after, messages, partial: live?.generation?.message ?? null, tools: live?.tools ?? [], approval,
209
+ label: approval ? "Waiting for approval: preview_card" : compacting ? "Compacting context…" :
210
+ live?.run ? "Working" : failure ? `Run failed: ${failure.reason}` : idle,
211
+ notice: failure?.detail, controls: await controls.read(after, live),
212
+ program: approval ? { state: "blocked", kind: "permission" } : { state: live?.run || compacting ? "working" : failure ? "error" : "idle" } };
213
+ },
214
+ submit: content => controls.input(content, "steer"),
215
+ close: done.resolve,
216
+ }, { theme });
217
+ await done.promise;
218
+ } catch (err) {
219
+ console.error(`Durable UI self-test: ${err.message}`);
220
+ process.exitCode = 1;
221
+ } finally {
222
+ try { await harness?.close(context); }
223
+ finally {
224
+ await rm(scratch, { recursive: true, force: true });
225
+ await modelRuntime?.settleCredentialWrites();
226
+ }
227
+ }
package/transcript.mjs ADDED
@@ -0,0 +1,74 @@
1
+ import { AssistantMessageComponent, createReadToolDefinition, ToolExecutionComponent, UserMessageComponent } from "@earendil-works/pi-coding-agent";
2
+ import { Container } from "@earendil-works/pi-tui";
3
+
4
+ // Only render text; never pass model/tool output through as terminal escapes.
5
+ export const clean = value => String(value ?? "").replace(/[\p{Cc}\p{Cf}]/gu, char =>
6
+ char === "\n" ? "\n" : char === "\t" ? " " : "�");
7
+ const parts = content => typeof content === "string" ? [{ type: "text", text: clean(content) }] :
8
+ (content ?? []).flatMap(part => part.type === "text" ? [{ type: "text", text: clean(part.text) }] : []);
9
+ const assistant = message => ({ ...message, errorMessage: clean(message.errorMessage), content: message.content.flatMap(part => {
10
+ if (part.type === "thinking") return [{ type: "thinking", thinking: clean(part.thinking) }];
11
+ if (part.type === "toolCall") return [part]; // AssistantMessageComponent does not render arguments.
12
+ return parts([part]);
13
+ }) });
14
+ const safeArgs = value => typeof value === "string" ? clean(value) : Array.isArray(value) ? value.map(safeArgs) :
15
+ value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([k, v]) => [clean(k), safeArgs(v)])) : value;
16
+
17
+ export function createTranscript(tui, cwd, editor) {
18
+ const rows = new Container(), partial = new AssistantMessageComponent();
19
+ const tools = new Map();
20
+ // Use Pi's path colors and syntax highlighting for read. Never retain or invoke the tool's execute function.
21
+ const { renderCall, renderResult } = createReadToolDefinition(cwd);
22
+ const readRenderers = { renderCall, renderResult };
23
+ let expanded = false, lastPartial = "", lastAnswer = "";
24
+ function newTool(id, name, args) {
25
+ const renderers = name === "read" ? readRenderers : {}; // Other tools use Pi's compact generic card.
26
+ const component = new ToolExecutionComponent(clean(name), id, safeArgs(args), { showImages: false }, renderers, tui, cwd);
27
+ component.setArgsComplete();
28
+ component.setExpanded(expanded);
29
+ tools.set(id, { component });
30
+ rows.addChild(component);
31
+ return tools.get(id);
32
+ }
33
+ return {
34
+ append(message) {
35
+ if (message.role === "user") {
36
+ const text = parts(message.content).map(part => part.text).join("\n");
37
+ rows.addChild(new UserMessageComponent(text));
38
+ editor.addToHistory(text);
39
+ } else if (message.role === "assistant") {
40
+ if (message.stopReason === "stop") {
41
+ const answer = parts(message.content).map(part => part.text).join("\n");
42
+ if (answer.trim()) lastAnswer = answer;
43
+ }
44
+ rows.addChild(new AssistantMessageComponent(assistant(message)));
45
+ for (const call of message.content.filter(part => part.type === "toolCall")) newTool(call.id, call.name, call.arguments);
46
+ } else if (message.role === "toolResult") {
47
+ const row = tools.get(message.toolCallId) ?? newTool(message.toolCallId, message.toolName);
48
+ row.component.updateResult({ content: parts(message.content), isError: message.isError });
49
+ row.done = true;
50
+ }
51
+ },
52
+ update(view) {
53
+ const next = JSON.stringify(view.partial);
54
+ if (next !== lastPartial) {
55
+ lastPartial = next;
56
+ partial.updateContent(view.partial ? assistant(view.partial) : { content: [] }, Boolean(view.partial));
57
+ }
58
+ for (const { callId, status, output } of view.tools) {
59
+ const row = tools.get(callId);
60
+ if (!row || row.done || status !== "running" || row.output === output) continue;
61
+ row.output = output;
62
+ row.component.updateResult({ content: parts(output), isError: false }, true);
63
+ }
64
+ },
65
+ lastAnswer: () => lastAnswer,
66
+ toggleTools() {
67
+ expanded = !expanded;
68
+ for (const { component } of tools.values()) component.setExpanded(expanded);
69
+ return expanded;
70
+ },
71
+ invalidate() { rows.invalidate(); partial.invalidate(); },
72
+ render(width) { return [...rows.render(width), ...partial.render(width)]; },
73
+ };
74
+ }