pal-code 0.0.16 → 0.0.18

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.
Files changed (40) hide show
  1. package/README.md +9 -6
  2. package/SYSTEM.md +17 -2
  3. package/package.json +10 -5
  4. package/packages/cli/src/agent-panel.ts +1 -1
  5. package/packages/cli/src/agent-ui.ts +66 -0
  6. package/packages/cli/src/commands/ext-registry.ts +7 -0
  7. package/packages/cli/src/commands.ts +32 -102
  8. package/packages/cli/src/components/assistant-body.ts +4 -3
  9. package/packages/cli/src/components/message-box.ts +2 -2
  10. package/packages/cli/src/components/permission-prompt.ts +3 -3
  11. package/packages/cli/src/components/render-history.ts +13 -12
  12. package/packages/cli/src/components/run-view.ts +109 -33
  13. package/packages/cli/src/components/sidebar.ts +81 -14
  14. package/packages/cli/src/components/status-line.ts +3 -3
  15. package/packages/cli/src/config.ts +6 -129
  16. package/packages/cli/src/index.ts +194 -69
  17. package/packages/cli/src/overlays/key-input.ts +142 -121
  18. package/packages/cli/src/overlays/model-picker.ts +19 -56
  19. package/packages/cli/src/overlays/select.ts +102 -0
  20. package/packages/cli/src/overlays/session-picker.ts +14 -40
  21. package/packages/cli/src/overlays/wizard.ts +107 -42
  22. package/packages/cli/src/prompt/select.ts +181 -0
  23. package/packages/cli/src/slash-commands.ts +105 -0
  24. package/packages/cli/src/state.ts +32 -74
  25. package/packages/cli/src/theme.ts +13 -1
  26. package/packages/cli/src/themes/github-dark.ts +14 -3
  27. package/packages/cli/src/themes/types.ts +26 -2
  28. package/packages/cli/src/themes/vanilla-pi.ts +23 -9
  29. package/packages/cli/src/tui/components/text.ts +102 -0
  30. package/packages/cli/src/tui/render/code-block.ts +325 -0
  31. package/packages/cli/src/{utils → tui/render}/format.ts +31 -24
  32. package/packages/cli/src/{utils → tui/render}/highlight.ts +94 -2
  33. package/packages/cli/src/tui/render/markdown.ts +529 -0
  34. package/packages/cli/src/tui/surface/index.ts +9 -0
  35. package/packages/cli/src/tui/{paint-panel.ts → surface/paint-panel.ts} +1 -1
  36. package/packages/cli/src/tui/theme-types.ts +59 -0
  37. package/packages/cli/src/tui/tty-width.ts +20 -0
  38. package/packages/cli/src/tui/types.ts +53 -0
  39. package/packages/cli/src/turn.ts +0 -292
  40. package/packages/cli/src/utils/code-block.ts +0 -200
@@ -1,14 +1,28 @@
1
1
  /**
2
2
  * First-run BYOK setup — runs BEFORE the TUI takes over stdin.
3
3
  *
4
- * It needs its own line reader because bun's `readline/promises` never
5
- * resolves on piped stdin, and the raw `data`-event reader below is also what
6
- * lets the wizard run without entering raw mode.
4
+ * Provider selection uses the standalone raw-mode picker in `prompt/select.ts`
5
+ * (no pi-tui); key entry uses the line reader below because bun's
6
+ * `readline/promises` never resolves on piped stdin.
7
7
  */
8
8
 
9
- import {PROVIDERS, detectProvider, saveKey, saveSetting, configPath} from '@pal-code/core';
9
+ import {
10
+ PROVIDERS,
11
+ detectProvider,
12
+ resolveAllKeys,
13
+ saveKey,
14
+ saveSetting,
15
+ configPath,
16
+ } from '@pal-code/core';
17
+ import type {ProviderKeys} from '@pal-code/core';
10
18
 
11
19
  import {c} from '../theme.js';
20
+ import {canPromptInteractively, promptSelect} from '../prompt/select.js';
21
+ import type {PromptItem} from '../prompt/select.js';
22
+
23
+ type Provider = (typeof PROVIDERS)[number];
24
+
25
+ const PASTE_KEY = '__paste__';
12
26
 
13
27
  const _lineQueue: string[] = [];
14
28
  let _pendingLine: ((line: string) => void) | null = null;
@@ -69,8 +83,8 @@ export async function ask(prompt: string): Promise<string> {
69
83
  }
70
84
 
71
85
  /**
72
- * Interactive first-run setup. Plain stdin/stdout (not the TUI) so it works
73
- * before raw mode. Saves the key + default model into ~/.pal/config.json.
86
+ * Interactive first-run setup. Saves the key + default model into
87
+ * ~/.pal/config.json.
74
88
  */
75
89
  export async function runSetupWizard(): Promise<boolean> {
76
90
  console.log('');
@@ -79,47 +93,18 @@ export async function runSetupWizard(): Promise<boolean> {
79
93
  `${c.dim} pal is BYOK (bring your own key). Pick a provider, paste your key.${c.reset}`,
80
94
  );
81
95
  console.log('');
82
- PROVIDERS.forEach((p, i) => {
83
- const tag = p.keyOptional ? `${c.green}free-ok${c.reset}` : '';
84
- console.log(
85
- ` ${c.bold}${String(i + 1).padStart(2)}${c.reset}. ${p.name.padEnd(16)} ${c.dim}${providerHint(p)}${c.reset} ${tag}`,
86
- );
87
- });
88
- console.log('');
96
+ const configured = resolveAllKeys();
89
97
 
90
- const first = await ask(` ${c.bold}Provider number or paste an API key:${c.reset} `);
91
- if (!first) {
98
+ const picked = canPromptInteractively()
99
+ ? await pickProviderInteractive(configured)
100
+ : await pickProviderNumeric(configured);
101
+ if (!picked) {
92
102
  console.log(`${c.red} Setup cancelled. Run pal again to retry.${c.reset}`);
93
103
  return false;
94
104
  }
95
105
 
96
- let provider = null as (typeof PROVIDERS)[number] | null;
97
- let key = '';
98
-
99
- const asNum = Number(first);
100
- if (Number.isInteger(asNum) && asNum >= 1 && asNum <= PROVIDERS.length) {
101
- provider = PROVIDERS[asNum - 1];
102
- key = await ask(
103
- provider.keyOptional
104
- ? ` ${c.bold}Paste your ${provider.name} API key (Enter for keyless):${c.reset} `
105
- : ` ${c.bold}Paste your ${provider.name} API key:${c.reset} `,
106
- );
107
- } else {
108
- key = first;
109
- provider = detectProvider(key);
110
- if (!provider) {
111
- console.log(`${c.yellow} Could not detect the provider from that key shape.${c.reset}`);
112
- const pick = await ask(` ${c.bold}Provider number:${c.reset} `);
113
- const n = Number(pick);
114
- provider = Number.isInteger(n) && n >= 1 && n <= PROVIDERS.length ? PROVIDERS[n - 1] : null;
115
- }
116
- }
117
-
118
- if (!provider) {
119
- console.log(`${c.red} Setup cancelled — no provider selected.${c.reset}`);
120
- return false;
121
- }
122
- if (!key && !provider.keyOptional) {
106
+ const {provider, key} = picked;
107
+ if (!key && !(provider.keyOptional && !configured[provider.id])) {
123
108
  console.log(`${c.red} Setup cancelled — no key saved.${c.reset}`);
124
109
  return false;
125
110
  }
@@ -143,3 +128,83 @@ export async function runSetupWizard(): Promise<boolean> {
143
128
  console.log('');
144
129
  return true;
145
130
  }
131
+
132
+ async function pickProviderInteractive(
133
+ configured: ProviderKeys,
134
+ ): Promise<{provider: Provider; key: string} | null> {
135
+ const items: PromptItem[] = [
136
+ ...PROVIDERS.map((p) => ({
137
+ value: p.id,
138
+ label: p.name,
139
+ description: [providerHint(p), p.keyOptional && !configured[p.id] ? 'free-ok' : '']
140
+ .filter(Boolean)
141
+ .join(' · '),
142
+ })),
143
+ {value: PASTE_KEY, label: 'Paste an API key…', description: 'Auto-detect the provider'},
144
+ ];
145
+ const selectedValue =
146
+ PROVIDERS.find((p) => configured[p.id])?.id ?? PROVIDERS.find((p) => p.keyOptional)?.id;
147
+
148
+ for (;;) {
149
+ const picked = await promptSelect({title: 'Select provider', items, selectedValue});
150
+ if (!picked) return null;
151
+
152
+ if (picked.value === PASTE_KEY) {
153
+ const pasted = await ask(` ${c.bold}Paste your API key:${c.reset} `);
154
+ if (!pasted) continue;
155
+ const detected = detectProvider(pasted);
156
+ if (!detected) {
157
+ console.log(`${c.yellow} Could not detect the provider from that key shape.${c.reset}`);
158
+ continue;
159
+ }
160
+ return {provider: detected, key: pasted};
161
+ }
162
+
163
+ const provider = PROVIDERS.find((p) => p.id === picked.value);
164
+ if (!provider) continue;
165
+ const key = await ask(
166
+ provider.keyOptional && !configured[provider.id]
167
+ ? ` ${c.bold}Paste your ${provider.name} API key (Enter for keyless):${c.reset} `
168
+ : ` ${c.bold}Paste your ${provider.name} API key:${c.reset} `,
169
+ );
170
+ return {provider, key};
171
+ }
172
+ }
173
+
174
+ async function pickProviderNumeric(
175
+ configured: ProviderKeys,
176
+ ): Promise<{provider: Provider; key: string} | null> {
177
+ PROVIDERS.forEach((p, i) => {
178
+ const tag = p.keyOptional && !configured[p.id] ? `${c.green}free-ok${c.reset}` : '';
179
+ console.log(
180
+ ` ${c.bold}${String(i + 1).padStart(2)}${c.reset}. ${p.name.padEnd(16)} ${c.dim}${providerHint(p)}${c.reset} ${tag}`,
181
+ );
182
+ });
183
+ console.log('');
184
+
185
+ const first = await ask(` ${c.bold}Provider number or paste an API key:${c.reset} `);
186
+ if (!first) return null;
187
+
188
+ const asNum = Number(first);
189
+ if (Number.isInteger(asNum) && asNum >= 1 && asNum <= PROVIDERS.length) {
190
+ const provider = PROVIDERS[asNum - 1];
191
+ const key = await ask(
192
+ provider.keyOptional && !configured[provider.id]
193
+ ? ` ${c.bold}Paste your ${provider.name} API key (Enter for keyless):${c.reset} `
194
+ : ` ${c.bold}Paste your ${provider.name} API key:${c.reset} `,
195
+ );
196
+ return {provider, key};
197
+ }
198
+
199
+ const detected = detectProvider(first);
200
+ if (detected) return {provider: detected, key: first};
201
+
202
+ console.log(`${c.yellow} Could not detect the provider from that key shape.${c.reset}`);
203
+ const pick = await ask(` ${c.bold}Provider number:${c.reset} `);
204
+ const n = Number(pick);
205
+ const provider = Number.isInteger(n) && n >= 1 && n <= PROVIDERS.length ? PROVIDERS[n - 1] : null;
206
+ if (!provider) return null;
207
+
208
+ const key = await ask(` ${c.bold}Paste your ${provider.name} API key:${c.reset} `);
209
+ return {provider, key};
210
+ }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Minimal interactive picker for flows that run before the pi-tui app owns
3
+ * stdin. Self-contained: raw stdin + ANSI, no TUI dependency.
4
+ */
5
+
6
+ import {emitKeypressEvents} from 'node:readline';
7
+ import type {Key} from 'node:readline';
8
+
9
+ import {c} from '../theme.js';
10
+ import {truncate} from '../tui/render/format.js';
11
+
12
+ export interface PromptItem {
13
+ value: string;
14
+ label: string;
15
+ description?: string;
16
+ }
17
+
18
+ export interface PromptSelectOptions {
19
+ title: string;
20
+ items: PromptItem[];
21
+ selectedValue?: string;
22
+ height?: number;
23
+ hint?: string;
24
+ }
25
+
26
+ const DEFAULT_HINT = 'type to filter, ↑↓ navigate, Enter select, Esc cancel';
27
+
28
+ export function canPromptInteractively(): boolean {
29
+ return Boolean(
30
+ process.stdin.isTTY && process.stdout.isTTY && typeof process.stdin.setRawMode === 'function',
31
+ );
32
+ }
33
+
34
+ export function filterItems(items: PromptItem[], query: string): PromptItem[] {
35
+ const needle = query.trim().toLowerCase();
36
+ if (!needle) return items;
37
+ return items.filter((item) =>
38
+ `${item.label} ${item.description ?? ''}`.toLowerCase().includes(needle),
39
+ );
40
+ }
41
+
42
+ export function moveSelection(index: number, delta: number, length: number): number {
43
+ if (length === 0) return 0;
44
+ return (index + delta + length) % length;
45
+ }
46
+
47
+ export function promptSelect(opts: PromptSelectOptions): Promise<PromptItem | null> {
48
+ if (!canPromptInteractively()) return Promise.resolve(null);
49
+
50
+ return new Promise((resolve) => {
51
+ const stdin = process.stdin;
52
+ const height = Math.max(3, opts.height ?? 12);
53
+ let query = '';
54
+ let index = Math.max(
55
+ 0,
56
+ opts.items.findIndex((item) => item.value === opts.selectedValue),
57
+ );
58
+ let rendered = 0;
59
+ let done = false;
60
+
61
+ const visible = (): PromptItem[] => filterItems(opts.items, query);
62
+
63
+ const render = (): void => {
64
+ const items = visible();
65
+ if (index >= items.length) index = Math.max(0, items.length - 1);
66
+ const start = Math.max(0, Math.min(index - Math.floor(height / 2), items.length - height));
67
+ const width = Math.max(24, (process.stdout.columns ?? 80) - 5);
68
+ const hint = query
69
+ ? `filter: ${truncate(query, Math.min(24, width - 10))}`
70
+ : (opts.hint ?? DEFAULT_HINT);
71
+
72
+ const lines = [
73
+ ` ${c.bold}${truncate(opts.title, width)}${c.reset}`,
74
+ ` ${c.dim}${hint}${c.reset}`,
75
+ ];
76
+ for (let i = start; i < Math.min(items.length, start + height); i += 1) {
77
+ const item = items[i];
78
+ const active = i === index;
79
+ const label = truncate(item.label, 30);
80
+ const room = width - label.length - 2;
81
+ const description =
82
+ item.description && room > 8
83
+ ? ` ${c.dim}${truncate(item.description, room)}${c.reset}`
84
+ : '';
85
+ lines.push(
86
+ ` ${active ? `${c.cyan}>${c.reset}` : ' '} ${active ? `${c.cyan}${label}${c.reset}` : label}${description}`,
87
+ );
88
+ }
89
+ if (items.length === 0) lines.push(` ${c.dim}No matches.${c.reset}`);
90
+ if (items.length > height) lines.push(` ${c.dim}${index + 1}/${items.length}${c.reset}`);
91
+
92
+ if (rendered > 0) process.stdout.write(`\x1b[${rendered}A`);
93
+ process.stdout.write(`\x1b[0J${lines.join('\n')}\n`);
94
+ rendered = lines.length;
95
+ };
96
+
97
+ const cleanup = (): void => {
98
+ if (done) return;
99
+ done = true;
100
+ stdin.off('keypress', onKey);
101
+ stdin.off('end', onEnd);
102
+ process.off('SIGINT', onSigint);
103
+ if (typeof stdin.setRawMode === 'function') stdin.setRawMode(false);
104
+ stdin.pause();
105
+ process.stdout.write('\x1b[?25h');
106
+ };
107
+
108
+ const finish = (item: PromptItem | null): void => {
109
+ if (done) return;
110
+ if (rendered > 0) process.stdout.write(`\x1b[${rendered}A\x1b[0J`);
111
+ cleanup();
112
+ if (item) process.stdout.write(` ${c.green}✓${c.reset} ${item.label}\n`);
113
+ resolve(item);
114
+ };
115
+
116
+ const onKey = (str: string | undefined, key: Key): void => {
117
+ if (done) return;
118
+ if (key.name === 'up') {
119
+ index = moveSelection(index, -1, visible().length);
120
+ render();
121
+ return;
122
+ }
123
+ if (key.name === 'down') {
124
+ index = moveSelection(index, 1, visible().length);
125
+ render();
126
+ return;
127
+ }
128
+ if (key.name === 'return' || key.name === 'enter') {
129
+ const item = visible()[index];
130
+ if (item) finish(item);
131
+ return;
132
+ }
133
+ if (key.name === 'escape') {
134
+ if (query) {
135
+ query = '';
136
+ index = 0;
137
+ render();
138
+ } else {
139
+ finish(null);
140
+ }
141
+ return;
142
+ }
143
+ if (key.ctrl && key.name === 'c') {
144
+ finish(null);
145
+ return;
146
+ }
147
+ if (key.ctrl && key.name === 'u') {
148
+ query = '';
149
+ index = 0;
150
+ render();
151
+ return;
152
+ }
153
+ if (key.name === 'backspace') {
154
+ query = query.slice(0, -1);
155
+ index = 0;
156
+ render();
157
+ return;
158
+ }
159
+ if (str && !key.ctrl && !key.meta) {
160
+ const printable = str.replace(/[^\x20-\x7e]/g, '');
161
+ if (printable) {
162
+ query += printable;
163
+ index = 0;
164
+ render();
165
+ }
166
+ }
167
+ };
168
+
169
+ const onEnd = (): void => finish(null);
170
+ const onSigint = (): void => finish(null);
171
+
172
+ process.stdout.write('\x1b[?25l');
173
+ emitKeypressEvents(stdin);
174
+ if (typeof stdin.setRawMode === 'function') stdin.setRawMode(true);
175
+ stdin.resume();
176
+ stdin.on('keypress', onKey);
177
+ stdin.on('end', onEnd);
178
+ process.once('SIGINT', onSigint);
179
+ render();
180
+ });
181
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Single source of truth for slash commands.
3
+ *
4
+ * Both `/help` and the editor's autocomplete read from this list. Keep it in
5
+ * sync with the dispatch chain in `index.ts` — `slash-commands.test.ts` scans
6
+ * that file and fails when a handler exists without a registry entry (or the
7
+ * other way around).
8
+ */
9
+
10
+ export interface SlashCommandDetail {
11
+ /** Text after the command name, e.g. `add <pkg>`. */
12
+ usage: string;
13
+ description: string;
14
+ }
15
+
16
+ export interface SlashCommand {
17
+ name: string;
18
+ description: string;
19
+ /** Argument hint shown after the name, e.g. `[provider] [key]`. */
20
+ usage?: string;
21
+ aliases?: string[];
22
+ /** Only shown when debug mode is enabled. */
23
+ debugOnly?: boolean;
24
+ /** Subcommands rendered as indented rows under the command. */
25
+ details?: SlashCommandDetail[];
26
+ }
27
+
28
+ export const SLASH_COMMANDS: SlashCommand[] = [
29
+ {name: 'help', description: 'Show this help message', aliases: ['h']},
30
+ {name: 'exit', description: 'Save session and quit', aliases: ['quit']},
31
+ {name: 'new', description: 'Start a new session'},
32
+ {name: 'clear', description: 'Reset conversation'},
33
+ {name: 'sessions', description: 'List recent sessions'},
34
+ {name: 'resume', description: 'Load a previous session', usage: 'ID'},
35
+ {name: 'cost', description: 'Show token usage and estimated cost'},
36
+ {name: 'model', description: 'Switch model (picker, or pass provider/name)', usage: '[name]'},
37
+ {
38
+ name: 'key',
39
+ description: 'Set an API key (interactive, or provider + key)',
40
+ usage: '[provider] [key]',
41
+ aliases: ['config'],
42
+ },
43
+ {
44
+ name: 'rotation',
45
+ description: 'Toggle automatic model switching on failure',
46
+ usage: '[on|off]',
47
+ },
48
+ {name: 'keys', description: 'Show configured API keys'},
49
+ {name: 'theme', description: 'Switch color theme (picker, or pass name)', usage: '[name]'},
50
+ {name: 'compact', description: 'Compress context when nearing the limit'},
51
+ {name: 'effort', description: 'Set reasoning effort', usage: 'low|medium|high'},
52
+ {name: 'plan', description: 'Enter read-only plan mode', usage: '[task]'},
53
+ {name: 'execute', description: 'Leave plan mode and implement'},
54
+ {name: 'undo', description: 'Restore the file from your last edit'},
55
+ {name: 'snapshots', description: 'List recent file snapshots'},
56
+ {
57
+ name: 'permission',
58
+ description: 'Show permission rules and whitelist',
59
+ aliases: ['perm'],
60
+ },
61
+ {name: 'copy', description: 'Copy last reply (or code block) to clipboard', usage: '[code]'},
62
+ {
63
+ name: 'ext',
64
+ description: 'Manage extensions',
65
+ details: [
66
+ {usage: 'add <pkg>', description: 'Install an extension from npm'},
67
+ {usage: 'remove <pkg>', description: 'Remove an extension'},
68
+ {usage: 'list', description: 'List loaded extensions'},
69
+ {usage: 'search <q>', description: 'Search the npm registry'},
70
+ {usage: 'browse', description: 'Browse curated extensions'},
71
+ ],
72
+ },
73
+ {
74
+ name: 'mcp',
75
+ description: 'Manage MCP servers',
76
+ details: [
77
+ {usage: 'add <name> <cmd> [args]', description: 'Add a local MCP server'},
78
+ {usage: 'add-remote <name> <url>', description: 'Add a remote MCP server'},
79
+ {usage: 'remove <name>', description: 'Remove an MCP server'},
80
+ {usage: 'list', description: 'List MCP servers'},
81
+ {usage: 'browse', description: 'Browse curated MCP servers'},
82
+ {usage: 'search <q>', description: 'Search curated MCP servers'},
83
+ ],
84
+ },
85
+ {name: 'export', description: 'Export config to JSON (secrets excluded)', usage: '[file]'},
86
+ {name: 'import', description: 'Merge an export (local API keys kept)', usage: '<file>'},
87
+ {name: 'roles', description: 'List agent roles (agents extension)'},
88
+ {name: 'reload', description: 'Hot-reload extensions (dev)', debugOnly: true},
89
+ {name: 'restart', description: 'Restart pal (saves session first)', debugOnly: true},
90
+ ];
91
+
92
+ /** Registry entries that should be visible in the current mode. */
93
+ export function visibleCommands(debug = false): SlashCommand[] {
94
+ return SLASH_COMMANDS.filter((cmd) => debug || !cmd.debugOnly);
95
+ }
96
+
97
+ /** Items for the editor's `/` autocomplete. */
98
+ export function autocompleteItems(debug = false): Array<{name: string; description: string}> {
99
+ return visibleCommands(debug).map(({name, description}) => ({name, description}));
100
+ }
101
+
102
+ /** Resolve a name or alias (without the leading slash). */
103
+ export function findCommand(name: string): SlashCommand | null {
104
+ return SLASH_COMMANDS.find((cmd) => cmd.name === name || cmd.aliases?.includes(name)) ?? null;
105
+ }
@@ -1,66 +1,42 @@
1
1
  /**
2
2
  * Session-scoped mutable UI state.
3
3
  *
4
- * This is the CLI's single "app state" object. It exists so the pickers, the
5
- * agents panel, and `main()` can share a few mutable references without every
6
- * one of them living in the same file — the previous arrangement had these
7
- * scattered as module-level `let`s in `index.ts`, which made the extraction of
8
- * any one overlay impossible.
4
+ * The shared, frontend-agnostic part lives in `@pal-code/core`
5
+ * (`SharedState` / `createSharedState`). This object adds only the state the
6
+ * terminal frontend owns: overlays, focus, the active run block and the
7
+ * permission modal plumbing.
9
8
  *
10
9
  * Deliberately a plain object rather than exported `let` bindings: importers
11
10
  * mutate `state.x` directly, and reads always see the current value (a plain
12
11
  * object export is a live reference; a `let` export would be a snapshot at the
13
12
  * import site).
14
- *
15
- * Only *presentation* state lives here. Anything that decides what the agent
16
- * does belongs in `@pal-code/core` (see SYSTEM.md).
17
13
  */
18
14
 
19
- import type {SessionTokenomics} from '@pal-code/core';
20
- import type {RunView} from './components/run-view.js';
15
+ import type {
16
+ ExtensionStatus,
17
+ McpServerStatus,
18
+ SharedState,
19
+ SessionTokenomics,
20
+ } from '@pal-code/core';
21
+ import {createSharedState} from '@pal-code/core';
21
22
  import type {PermissionPrompt} from './components/permission-prompt.js';
23
+ import type {RunView} from './components/run-view.js';
22
24
 
23
- export type OverlayMode = 'none' | 'model-select' | 'key-input' | 'agents' | 'permission';
25
+ export type {BackgroundAgent, TodoItem} from '@pal-code/core';
26
+ export type ExtensionInfo = ExtensionStatus;
27
+ export type McpServerInfo = McpServerStatus;
28
+
29
+ export type OverlayMode = 'none' | 'select' | 'key-input' | 'agents' | 'permission';
24
30
 
25
31
  /**
26
32
  * Name of the active **primary agent** (the one the user talks to, cycled with
27
- * Tab). Populated from the orchestration extension at load time; defaults to
28
- * 'pal' (the orchestrator) when no extension provides primaries.
33
+ * Tab). Populated from the orchestration extension at load time.
29
34
  *
30
35
  * Not to be confused with a delegation role — see `@pal-code/core`'s `PrimarySpec`.
31
36
  */
32
37
  export type AgentRole = string;
33
38
 
34
- export interface BackgroundAgent {
35
- id: string;
36
- task: string;
37
- status: 'running' | 'done' | 'error';
38
- startedAt: number;
39
- finishedAt?: number;
40
- result?: string;
41
- }
42
-
43
- export interface TodoItem {
44
- content: string;
45
- status: string;
46
- }
47
-
48
- export interface ExtensionInfo {
49
- /** Extension package name (e.g. '@pal-code/web-search'). */
50
- name: string;
51
- /** Whether the extension loaded successfully and its tools are available. */
52
- active: boolean;
53
- /** Why loading failed, when `active` is false. */
54
- reason?: string;
55
- }
56
-
57
- export interface McpServerInfo {
58
- name: string;
59
- status: 'connected' | 'error' | 'starting';
60
- toolCount: number;
61
- }
62
-
63
- export interface AppState {
39
+ export interface AppState extends SharedState {
64
40
  /** Which overlay (if any) currently owns the editor area. */
65
41
  overlayMode: OverlayMode;
66
42
  /** Bound by `main()`; re-renders the status line. */
@@ -69,34 +45,22 @@ export interface AppState {
69
45
  refreshSidebar: () => void;
70
46
  /** Bound by `main()`; re-reads keys and rebuilds the provider after `/key`. */
71
47
  reloadKeys: (() => void) | null;
72
- /** Title of the current session, shown at the top of the sidebar. */
73
- sessionTitle: string | null;
74
- /** Latest todo list from the `todos-updated` event. */
75
- currentTodos: readonly TodoItem[];
76
- /** Sub-agents spawned by `delegate`, shown in the ctrl+b panel. */
77
- backgroundAgents: BackgroundAgent[];
78
48
  /** The run block for the in-flight turn. */
79
49
  activeRun: RunView | null;
80
50
  /** Cancels the in-flight turn (Esc). */
81
51
  activeAbort: AbortController | null;
52
+ /** First Esc armed a stop; a second one inside the window aborts the turn. */
53
+ abortArmed: boolean;
82
54
  /** The most recently collapsed run, for ctrl+o. */
83
55
  lastRun: RunView | null;
84
56
  /** Messages submitted while a turn was running; drained one per settled turn. */
85
57
  pendingMessages: string[];
86
- /** Loaded extensions and their status. */
87
- extensions: ExtensionInfo[];
88
- /** MCP servers discovered during startup. */
89
- mcpServers: McpServerInfo[];
90
- /** Currently selected primary agent (see AgentRole). */
91
- currentAgentRole: AgentRole;
92
58
  /** Bound by `main()`; re-renders the input role indicator after extensions load. */
93
59
  refreshRoleIndicator: () => void;
94
60
  /** Bound by `main()`; shows the centered permission modal overlay. */
95
61
  showPermissionModal: () => void;
96
62
 
97
63
  // ── Permission system ──
98
- /** Session-scoped "always allow" entries. Cleared on /new. */
99
- permissionWhitelist: Array<{tool: string; pattern: string}>;
100
64
  /** Resolves an async permission prompt (set by main()). Returns 'allow' | 'deny'. */
101
65
  permissionResolver: ((allow: boolean) => void) | null;
102
66
  /** Context for the current permission overlay (shown in the prompt). */
@@ -110,40 +74,25 @@ export interface AppState {
110
74
  target: string;
111
75
  summary: string;
112
76
  }>;
113
-
114
- // ── Session-scoped tokenomics ──
115
- /**
116
- * Accumulated token usage and cost for the *current* session only — the
117
- * sidebar stats, `/cost`, and `saveSession` all read this single object.
118
- * Zeroed on `/new`, restored when a session is resumed, and persisted with
119
- * the session row on every save.
120
- */
121
- sessionTokenomics: SessionTokenomics;
122
77
  }
123
78
 
124
79
  export const state: AppState = {
80
+ ...createSharedState(),
125
81
  overlayMode: 'none',
126
82
  refreshStatusLine: () => {},
127
83
  refreshSidebar: () => {},
128
84
  reloadKeys: null,
129
- sessionTitle: null,
130
- currentTodos: [],
131
- backgroundAgents: [],
132
85
  activeRun: null,
133
86
  activeAbort: null,
87
+ abortArmed: false,
134
88
  lastRun: null,
135
89
  pendingMessages: [],
136
- extensions: [],
137
- mcpServers: [],
138
- currentAgentRole: 'pal',
139
90
  refreshRoleIndicator: () => {},
140
91
  showPermissionModal: () => {},
141
- permissionWhitelist: [],
142
92
  permissionResolver: null,
143
93
  pendingPermission: null,
144
94
  permissionPrompt: null,
145
95
  permissionQueue: [],
146
- sessionTokenomics: {inputTokens: 0, outputTokens: 0, cachedTokens: 0, cost: 0},
147
96
  };
148
97
 
149
98
  /**
@@ -156,6 +105,15 @@ export function enqueueMessage(queue: string[], message: string): number {
156
105
  return queue.length;
157
106
  }
158
107
 
108
+ /**
109
+ * Resolve one Esc press against the two-press stop contract: the first press
110
+ * only arms (so a stray Esc never kills work in flight), the second one inside
111
+ * the arm window aborts. Pure — the caller owns the timer and the controller.
112
+ */
113
+ export function nextEscAction(armed: boolean): {armed: boolean; abort: boolean} {
114
+ return armed ? {armed: false, abort: true} : {armed: true, abort: false};
115
+ }
116
+
159
117
  /**
160
118
  * Take the next message to run when a turn settles — completed, errored, or
161
119
  * aborted alike. Returns null when nothing is queued.
@@ -11,7 +11,7 @@
11
11
  * the pure `resolveTheme()` in themes/index.ts.
12
12
  */
13
13
 
14
- import type {EditorTheme, MarkdownTheme} from '@earendil-works/pi-tui';
14
+ import type {EditorTheme, MarkdownTheme} from './tui/theme-types.js';
15
15
  import type {CColors, CodeboxTokens, SurfaceTokens, SyntaxTokens, Theme} from './themes/types.js';
16
16
  import {themes} from './themes/index.js';
17
17
  import {vanillaPi} from './themes/vanilla-pi.js';
@@ -116,6 +116,15 @@ export const codebox: CodeboxTokens = {
116
116
  get successFg() {
117
117
  return current.codebox.successFg;
118
118
  },
119
+ get gutterFg() {
120
+ return current.codebox.gutterFg;
121
+ },
122
+ get diffDelBg() {
123
+ return current.codebox.diffDelBg;
124
+ },
125
+ get diffAddBg() {
126
+ return current.codebox.diffAddBg;
127
+ },
119
128
  };
120
129
 
121
130
  export const markdownTheme: MarkdownTheme = {
@@ -251,4 +260,7 @@ export const surface: SurfaceTokens = {
251
260
  get messageBox() {
252
261
  return current.surface.messageBox;
253
262
  },
263
+ get runView() {
264
+ return current.surface.runView;
265
+ },
254
266
  };