pal-code 0.0.5

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 (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +169 -0
  3. package/SYSTEM.md +146 -0
  4. package/bin/pal-code.js +131 -0
  5. package/package.json +68 -0
  6. package/packages/cli/README.md +77 -0
  7. package/packages/cli/src/agent-panel.ts +94 -0
  8. package/packages/cli/src/commands/ext.ts +79 -0
  9. package/packages/cli/src/commands/mcp-registry.ts +136 -0
  10. package/packages/cli/src/commands/mcp.ts +186 -0
  11. package/packages/cli/src/commands.ts +153 -0
  12. package/packages/cli/src/components/message-box.ts +35 -0
  13. package/packages/cli/src/components/permission-prompt.ts +185 -0
  14. package/packages/cli/src/components/render-history.ts +143 -0
  15. package/packages/cli/src/components/run-view.ts +256 -0
  16. package/packages/cli/src/components/sidebar.ts +120 -0
  17. package/packages/cli/src/components/status-line.ts +26 -0
  18. package/packages/cli/src/config.ts +107 -0
  19. package/packages/cli/src/index.ts +1606 -0
  20. package/packages/cli/src/overlays/key-input.ts +167 -0
  21. package/packages/cli/src/overlays/model-picker.ts +106 -0
  22. package/packages/cli/src/overlays/session-picker.ts +168 -0
  23. package/packages/cli/src/overlays/wizard.ts +145 -0
  24. package/packages/cli/src/state.ts +133 -0
  25. package/packages/cli/src/theme.ts +88 -0
  26. package/packages/cli/src/turn.ts +266 -0
  27. package/packages/cli/src/utils/cost.ts +111 -0
  28. package/packages/cli/src/utils/format.test.ts +167 -0
  29. package/packages/cli/src/utils/format.ts +248 -0
  30. package/packages/cli/src/utils/highlight.ts +358 -0
  31. package/packages/cli/src/utils/permissions.ts +196 -0
  32. package/packages/core/src/agent/events.ts +36 -0
  33. package/packages/core/src/agent/fallback.test.ts +99 -0
  34. package/packages/core/src/agent/fallback.ts +344 -0
  35. package/packages/core/src/agent/index.ts +35 -0
  36. package/packages/core/src/agent/protocol.test.ts +136 -0
  37. package/packages/core/src/agent/resume-compaction.test.ts +116 -0
  38. package/packages/core/src/agent/roles.ts +188 -0
  39. package/packages/core/src/agent/run.test.ts +207 -0
  40. package/packages/core/src/agent/run.ts +713 -0
  41. package/packages/core/src/agent/scope.ts +34 -0
  42. package/packages/core/src/agent/todos.ts +66 -0
  43. package/packages/core/src/compaction.protocol.test.ts +90 -0
  44. package/packages/core/src/compaction.test.ts +101 -0
  45. package/packages/core/src/compaction.ts +243 -0
  46. package/packages/core/src/config.test.ts +40 -0
  47. package/packages/core/src/config.ts +387 -0
  48. package/packages/core/src/extensions.ts +178 -0
  49. package/packages/core/src/index.ts +157 -0
  50. package/packages/core/src/logger.ts +54 -0
  51. package/packages/core/src/provider/auth.ts +153 -0
  52. package/packages/core/src/provider/complete.ts +63 -0
  53. package/packages/core/src/provider/index.ts +6 -0
  54. package/packages/core/src/provider/openrouter.test.ts +59 -0
  55. package/packages/core/src/provider/openrouter.ts +304 -0
  56. package/packages/core/src/provider/pick-model.ts +43 -0
  57. package/packages/core/src/provider/registry.ts +222 -0
  58. package/packages/core/src/provider/types.ts +61 -0
  59. package/packages/core/src/repo-map.ts +177 -0
  60. package/packages/core/src/session/index.ts +2 -0
  61. package/packages/core/src/session/migration.test.ts +104 -0
  62. package/packages/core/src/session/store-v2-repair.test.ts +209 -0
  63. package/packages/core/src/session/store.test.ts +235 -0
  64. package/packages/core/src/session/store.ts +677 -0
  65. package/packages/core/src/session/types.ts +72 -0
  66. package/packages/core/src/snapshots.ts +107 -0
  67. package/packages/core/src/tools/definitions.ts +365 -0
  68. package/packages/core/src/tools/executor.test.ts +122 -0
  69. package/packages/core/src/tools/executor.ts +1363 -0
  70. package/packages/core/src/tools/index.ts +5 -0
  71. package/packages/core/src/tools/search.ts +201 -0
  72. package/scripts/postinstall.js +121 -0
  73. package/scripts/preinstall.js +51 -0
@@ -0,0 +1,1606 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * pal — Terminal AI coding agent with tool use (TUI edition).
4
+ * Uses @earendil-works/pi-tui for differential rendering and streaming display.
5
+ *
6
+ * Architecture: agent loop (tool_calls -> execute -> feedback -> repeat) + provider + pi-tui.
7
+ */
8
+
9
+ // ═══════════════════════════════════════════════════════════════════════════════
10
+ // Imports
11
+ // ═══════════════════════════════════════════════════════════════════════════════
12
+
13
+ import {
14
+ ProcessTerminal,
15
+ TuiMainScreen,
16
+ Editor,
17
+ Text,
18
+ Container,
19
+ Spacer,
20
+ matchesKey,
21
+ Key,
22
+ CombinedAutocompleteProvider,
23
+ setKeybindings,
24
+ KeybindingsManager,
25
+ TUI_KEYBINDINGS,
26
+ detectCapabilities,
27
+ } from '@earendil-works/pi-tui';
28
+ import type {TUI} from '@earendil-works/pi-tui';
29
+ import pkg from '../package.json';
30
+
31
+ import {c, editorTheme, agentColors, agentLabels, colorByName} from './theme.js';
32
+ import {generateTitle, sanitizeTitle, formatMessageTimestamp} from './utils/format.js';
33
+ import {MessageBox} from './components/message-box.js';
34
+ import {renderHistory} from './components/render-history.js';
35
+ import {loadConfig} from './config.js';
36
+ import {StatusLine} from './components/status-line.js';
37
+ import {PermissionPrompt} from './components/permission-prompt.js';
38
+ import {state} from './state.js';
39
+ import {Sidebar} from './components/sidebar.js';
40
+ import {cmdHelp, cmdCost} from './commands.js';
41
+ import {showSessionSelector, cmdResume} from './overlays/session-picker.js';
42
+ import {loadCostManifest, estimateCost, isPricedModel} from './utils/cost.js';
43
+ import {openAgentsPanel, closeAgentsPanel} from './agent-panel.js';
44
+ import {
45
+ createOpenRouterProvider,
46
+ resolveAllKeys,
47
+ hasAnyKey,
48
+ configPath,
49
+ saveSetting,
50
+ PROVIDERS,
51
+ loadCustomProviders,
52
+ providerForModel,
53
+ clearTodos,
54
+ resetShell,
55
+ compactionBoundary,
56
+ summarizeRange,
57
+ complete,
58
+ pickCheapModel,
59
+ deriveMessageMeta,
60
+ estimateMessagesTokens,
61
+ restoreSnapshot,
62
+ listSnapshots,
63
+ onAgentEvent,
64
+ providerAccessible,
65
+ rollbackTurn,
66
+ seqToCount,
67
+ registerHistoryProvider,
68
+ isDebugEnabled,
69
+ listPrimaries,
70
+ resolvePrimary,
71
+ defaultPrimaryName,
72
+ resolveProjectRoot,
73
+ } from '@pal/core';
74
+ import type {Provider, ConversationMessage as Message} from '@pal/core';
75
+ // SessionStore deferred — bun:sqlite import may break pi-tui stdin
76
+ import type {SessionStore as SessionStoreType} from '@pal/core';
77
+
78
+ // ═══════════════════════════════════════════════════════════════════════════════
79
+ // Config
80
+ // ═══════════════════════════════════════════════════════════════════════════════
81
+
82
+ // Model lists are now resolved dynamically from each provider's /models endpoint
83
+ // (see buildModelOptions). Static curated lists live in @pal/core PROVIDERS as fallback.
84
+
85
+ // Single source of truth — no more drift from package.json.
86
+ const VERSION = pkg.version;
87
+
88
+ import {showModelSelector} from './overlays/model-picker.js';
89
+ import {showKeyInput} from './overlays/key-input.js';
90
+ import {runSetupWizard} from './overlays/wizard.js';
91
+ import {agentLoop, ensureExtensionsLoaded, isReadOnlyPrimary} from './turn.js';
92
+
93
+ // ═══════════════════════════════════════════════════════════════════════════════
94
+ // Main
95
+ // ═══════════════════════════════════════════════════════════════════════════════
96
+
97
+ async function main() {
98
+ // Fast exit for version flags (no config/project root needed)
99
+ const flag = process.argv[2];
100
+ if (flag === '--version' || flag === '--v' || flag === '-v' || flag === '-version') {
101
+ console.log(`pal-code v${pkg.version}`);
102
+ process.exit(0);
103
+ }
104
+
105
+ // Anchor to the project root (where .pal.json lives) so that process.cwd()
106
+ // reflects the user's project, not wherever the CLI package happens to be.
107
+ const root = resolveProjectRoot();
108
+ if (root && root !== process.cwd()) {
109
+ process.chdir(root);
110
+ }
111
+
112
+ const config = loadConfig();
113
+
114
+ // Load any user-defined custom providers from ~/.pal/providers.json
115
+ loadCustomProviders();
116
+
117
+ // Handle CLI extension commands (no TUI needed)
118
+ if (process.argv[2] === 'add' && process.argv[3]) {
119
+ const {extAdd} = await import('./commands/ext.js');
120
+ const result = extAdd(process.argv[3]);
121
+ console.log(result.message);
122
+ process.exit(result.ok ? 0 : 1);
123
+ }
124
+ if (process.argv[2] === 'remove' && process.argv[3]) {
125
+ const {extRemove} = await import('./commands/ext.js');
126
+ const result = extRemove(process.argv[3]);
127
+ console.log(result.message);
128
+ process.exit(result.ok ? 0 : 1);
129
+ }
130
+ // ── BYOK gate: force setup when no key is configured ──
131
+ let allKeys = resolveAllKeys();
132
+ const forceSetup = process.argv.includes('--setup') || process.argv.includes('--login');
133
+ if (forceSetup || !hasAnyKey(allKeys)) {
134
+ const ok = await runSetupWizard();
135
+ process.stdin.removeAllListeners('data');
136
+ process.stdin.pause();
137
+ if (!ok && !hasAnyKey(allKeys)) process.exit(1);
138
+ allKeys = resolveAllKeys();
139
+ Object.assign(config, loadConfig());
140
+ }
141
+
142
+ // If the selected model’s provider has no key, fall back to one that does.
143
+ {
144
+ const {provider: modelProvider} = providerForModel(config.model, Object.keys(allKeys));
145
+ if (!providerAccessible(modelProvider, allKeys)) {
146
+ const firstConfigured = PROVIDERS.find((p) => providerAccessible(p, allKeys));
147
+ if (firstConfigured) {
148
+ config.model = `${firstConfigured.id}/${firstConfigured.defaultModel}`;
149
+ }
150
+ }
151
+ }
152
+
153
+ // Cost manifest is fetched in the background; the hardcoded table is the fallback.
154
+ loadCostManifest().catch(() => {
155
+ // keep the hardcoded fallback
156
+ });
157
+
158
+ // Provider routing — resolved from the registry by `provider/model` spec.
159
+ function createProvider(modelSpec: string): Provider {
160
+ const {provider: def} = providerForModel(modelSpec, Object.keys(allKeys));
161
+ const envOverride = process.env[`${def.id.toUpperCase()}_BASE_URL`];
162
+ return createOpenRouterProvider({
163
+ id: def.id,
164
+ baseUrl: envOverride ?? def.baseUrl,
165
+ apiKey: allKeys[def.id] ?? (def.keyOptional ? 'public' : ''),
166
+ headers: def.headers,
167
+ modelPrefix: def.modelPrefix,
168
+ });
169
+ }
170
+
171
+ const providerRef = {current: createProvider(config.model)};
172
+ await providerRef.current.init();
173
+
174
+ // ── Session store (deferred — bun:sqlite breaks pi-tui stdin) ──
175
+ let store: SessionStoreType | null = null;
176
+ let currentSessionId: string | null = null;
177
+ // Agent role per user-message index, so persisted user turns repaint with the
178
+ // right box colour. Cleared whenever the conversation is swapped.
179
+ let userRoles = new Map<number, string>();
180
+
181
+ // `recall_history` reads through these closures rather than a captured store,
182
+ // so it keeps working after a session switch or a deferred-store init.
183
+ registerHistoryProvider({
184
+ read: () =>
185
+ store && currentSessionId
186
+ ? store.getMessages(currentSessionId).map((m) => ({
187
+ seq: m.seq,
188
+ role: m.role,
189
+ content: m.content ?? '',
190
+ toolCalls: m.toolCalls?.map((c) => ({name: c.name})),
191
+ }))
192
+ : [],
193
+ mark: () => (store && currentSessionId ? store.getCompactedUpto(currentSessionId) : 0),
194
+ });
195
+
196
+ // ── Token / cost tracking ──
197
+ let totalInputTokens = 0;
198
+ let totalOutputTokens = 0;
199
+ let totalCachedTokens = 0;
200
+ let totalCost = 0;
201
+
202
+ // ═══════════════════════════════════════════════════════════════
203
+ // TUI Setup
204
+ // ═══════════════════════════════════════════════════════════════
205
+
206
+ // Initialize pi-tui keybindings and terminal capabilities (like PI does)
207
+ setKeybindings(new KeybindingsManager(TUI_KEYBINDINGS));
208
+ detectCapabilities();
209
+
210
+ const terminal = new ProcessTerminal();
211
+ const tui: TUI = new TuiMainScreen(terminal);
212
+
213
+ // ── Components ──
214
+ const messagesContainer = new Container();
215
+ const editor = new Editor(tui, editorTheme);
216
+ const statusLine = new StatusLine('');
217
+ const permissionPrompt = new PermissionPrompt();
218
+ state.permissionPrompt = permissionPrompt;
219
+
220
+ // ── Banner ──
221
+ const resolvedBase = providerForModel(config.model, Object.keys(allKeys));
222
+ const providerName = resolvedBase.provider.name;
223
+ messagesContainer.addChild(new Text(`${c.bold}${c.cyan}pal v${VERSION}${c.reset}`, 1, 0));
224
+ messagesContainer.addChild(
225
+ new Text(`${c.dim}Model: ${config.model} (${providerName})${c.reset}`, 1, 0),
226
+ );
227
+ if (!hasAnyKey(allKeys)) {
228
+ messagesContainer.addChild(
229
+ new Text(`${c.yellow} No API key configured. Type /keys to see status.${c.reset}`, 1, 0),
230
+ );
231
+ }
232
+ messagesContainer.addChild(new Text(`${c.dim}Type /help for available commands${c.reset}`, 1, 0));
233
+ messagesContainer.addChild(new Spacer(1));
234
+
235
+ // ── Layout: main column (messages → gap → editor → status) + right sidebar ──
236
+ // Role indicator sits above the editor inside editorRow.
237
+ const roleIndicator = new Text('', 1, 0);
238
+
239
+ const editorRow = new Container();
240
+ editorRow.addChild(roleIndicator); // hidden initially (empty text)
241
+ editorRow.addChild(editor);
242
+
243
+ const sidebar = new Sidebar();
244
+ // Fixed sidebar width used by both the overlay compositor and the transcript
245
+ // layout. Both must agree — if the layout reserves N columns but the overlay
246
+ // paints at M ≠ N, the sidebar overpaints transcript content.
247
+ const SIDEBAR_WIDTH = 30;
248
+ const sidebarWidthFor = (w: number): number => {
249
+ if (w < 70) return 0; // too narrow — hide the sidebar
250
+ return SIDEBAR_WIDTH;
251
+ };
252
+
253
+ // ── Layout: pinned editor/status + scrolling transcript ──
254
+ //
255
+ // TuiMainScreen (pal's renderer) has no layout engine — grow/shrink and
256
+ // ScrollView are only honoured by TuiAltScreen. So the pinning is done here,
257
+ // in a plain component: render the transcript windowed to the rows left over
258
+ // after the editor and status line, then append those two so they never move.
259
+ //
260
+ // `scrollOffset` is rows scrolled up from the bottom (0 = follow the tail).
261
+ // The sidebar is a separate overlay and is never part of this column.
262
+ let scrollOffset = 0;
263
+
264
+ const pinnedLayout = {
265
+ render(width: number): string[] {
266
+ const inset = sidebarWidthFor(width);
267
+ const contentW = Math.max(1, width - inset);
268
+
269
+ const transcript = messagesContainer.render(contentW);
270
+ const editorLines = editorRow.render(contentW);
271
+ const statusLines = statusLine.render(contentW);
272
+
273
+ // Rows available to the transcript so the pinned rows always fit.
274
+ const total = Math.max(1, terminal.rows);
275
+ const viewport = Math.max(1, total - editorLines.length - statusLines.length);
276
+
277
+ // Clamp the scroll window against the current transcript height.
278
+ const maxOffset = Math.max(0, transcript.length - viewport);
279
+ scrollOffset = Math.min(scrollOffset, maxOffset);
280
+
281
+ const end = transcript.length - scrollOffset;
282
+ const start = Math.max(0, end - viewport);
283
+ const window = transcript.slice(start, end);
284
+
285
+ // Pad above when the transcript is shorter than the viewport so the
286
+ // editor stays anchored to the bottom of the frame.
287
+ const padTop = Math.max(0, viewport - window.length);
288
+ const out: string[] = [];
289
+ for (let i = 0; i < padTop; i++) out.push('');
290
+ out.push(...window);
291
+ out.push(...editorLines, ...statusLines);
292
+ return out;
293
+ },
294
+ invalidate(): void {
295
+ messagesContainer.invalidate();
296
+ editorRow.invalidate();
297
+ statusLine.invalidate();
298
+ },
299
+ };
300
+
301
+ // Rows scrolled up from the tail (0 = pinned to the newest output).
302
+ tui.addChild(pinnedLayout);
303
+
304
+ // Sticky sidebar: pi-tui's overlay system composites it at screen-relative
305
+ // positions so it stays pinned to the top-right while the transcript scrolls.
306
+ tui.showOverlay(sidebar, {
307
+ anchor: 'top-right',
308
+ width: SIDEBAR_WIDTH,
309
+ nonCapturing: true,
310
+ visible: () => sidebarWidthFor(tui.terminal.columns) > 0,
311
+ });
312
+
313
+ // ── Transcript scrolling ──
314
+ //
315
+ // Dispatch order in pi-tui: input listeners run BEFORE the focused editor.
316
+ // So we must not blindly consume Up/Down/Home/End — those belong to the
317
+ // editor for cursor movement. Instead there are two tiers:
318
+ //
319
+ // • Always-on keys (editor never needs them): PageUp/PageDown, Ctrl+Home,
320
+ // Ctrl+End, and the mouse wheel.
321
+ // • Scroll-mode keys: plain ↑/↓/Home/End (and Shift/Alt variants) only
322
+ // apply once the user is scrolled away from the tail. Exiting scroll mode
323
+ // (Esc, End, or simply typing) hands the keys back to the editor.
324
+ //
325
+ // This mirrors how `less`/`git log` pagers behave, so typing is never
326
+ // hijacked and the broken-wheel user can drive everything from the keyboard.
327
+
328
+ // Mouse wheel. pi-tui has no mouse layer, so enable SGR mouse reporting and
329
+ // decode the wheel events here. 64 = wheel up, 65 = wheel down.
330
+ //
331
+ // Enabling mouse reporting takes drag-selection away from the terminal: the
332
+ // terminal stops building a native selection and forwards clicks to us
333
+ // instead, and the handler below swallows everything but the wheel. That is
334
+ // why text can't be highlighted with a plain drag. Terminals restore native
335
+ // selection while Shift is held, so `Shift+drag` still works; users who would
336
+ // rather have plain drag-to-copy than wheel scrolling can set PAL_NO_MOUSE=1.
337
+ const mouseDisabled = ((): boolean => {
338
+ const v = process.env.PAL_NO_MOUSE;
339
+ return v === '1' || v === 'true';
340
+ })();
341
+ let mouseEnabled = false;
342
+ const enableMouse = (): void => {
343
+ if (mouseEnabled || mouseDisabled) return;
344
+ mouseEnabled = true;
345
+ // ?1000h button events, ?1006h SGR extended coordinates.
346
+ terminal.write('\x1b[?1000h\x1b[?1006h');
347
+ };
348
+ const disableMouse = (): void => {
349
+ if (!mouseEnabled) return;
350
+ mouseEnabled = false;
351
+ terminal.write('\x1b[?1000l\x1b[?1006l');
352
+ };
353
+
354
+ const scrollBy = (delta: number): void => {
355
+ const next = Math.max(0, scrollOffset + delta);
356
+ if (next === scrollOffset) return;
357
+ scrollOffset = next;
358
+ updateStatusLine();
359
+ };
360
+
361
+ const pageRows = (): number => {
362
+ const editorLines = editorRow.render(Math.max(1, terminal.columns)).length;
363
+ return Math.max(1, terminal.rows - editorLines - 2);
364
+ };
365
+
366
+ tui.addInputListener((data) => {
367
+ // SGR mouse: ESC [ < b ; x ; y M|m (preferred, enabled via ?1006h)
368
+ const mouse = data.match(/^\x1b\[<(\d+);\d+;\d+[Mm]$/);
369
+ if (mouse) {
370
+ const btn = Number(mouse[1]) & 0xff;
371
+ if (btn === 64) {
372
+ scrollBy(3); // wheel up
373
+ return {consume: true};
374
+ }
375
+ if (btn === 65) {
376
+ scrollBy(-3); // wheel down
377
+ return {consume: true};
378
+ }
379
+ return {consume: true}; // swallow other mouse events
380
+ }
381
+ // Legacy X10 mouse: ESC [ M followed by three bytes; button code is the
382
+ // first payload byte minus 32.
383
+ if (data.length === 6 && data.startsWith('\x1b[M')) {
384
+ const btn = data.charCodeAt(3) - 32;
385
+ if (btn === 64) {
386
+ scrollBy(3);
387
+ return {consume: true};
388
+ }
389
+ if (btn === 65) {
390
+ scrollBy(-3);
391
+ return {consume: true};
392
+ }
393
+ return {consume: true};
394
+ }
395
+
396
+ // Always-on navigation.
397
+ if (matchesKey(data, Key.pageUp)) {
398
+ scrollBy(pageRows());
399
+ return {consume: true};
400
+ }
401
+ if (matchesKey(data, Key.pageDown)) {
402
+ scrollBy(-pageRows());
403
+ return {consume: true};
404
+ }
405
+ if (matchesKey(data, 'ctrl+home')) {
406
+ revealEarlierHistory();
407
+ scrollOffset = Number.MAX_SAFE_INTEGER;
408
+ updateStatusLine();
409
+ return {consume: true};
410
+ }
411
+ if (matchesKey(data, 'ctrl+end')) {
412
+ scrollBy(-Number.MAX_SAFE_INTEGER);
413
+ return {consume: true};
414
+ }
415
+
416
+ // Scroll-mode keys — only while scrolled away from the tail.
417
+ const scrolled = scrollOffset > 0;
418
+ if (scrolled) {
419
+ if (matchesKey(data, Key.escape)) {
420
+ scrollBy(-Number.MAX_SAFE_INTEGER);
421
+ return {consume: true};
422
+ }
423
+ if (matchesKey(data, Key.up) || matchesKey(data, Key.shift('up'))) {
424
+ scrollBy(1);
425
+ return {consume: true};
426
+ }
427
+ if (matchesKey(data, Key.down) || matchesKey(data, Key.shift('down'))) {
428
+ scrollBy(-1);
429
+ return {consume: true};
430
+ }
431
+ if (matchesKey(data, Key.home)) {
432
+ scrollOffset = Number.MAX_SAFE_INTEGER;
433
+ updateStatusLine();
434
+ return {consume: true};
435
+ }
436
+ if (matchesKey(data, Key.end)) {
437
+ scrollBy(-Number.MAX_SAFE_INTEGER);
438
+ return {consume: true};
439
+ }
440
+ // Any printable character means the user is typing again — drop out of
441
+ // scroll mode and let the editor receive the key.
442
+ if (data.length === 1 && data >= ' ' && data !== '\x7f') {
443
+ scrollOffset = 0;
444
+ updateStatusLine();
445
+ return undefined;
446
+ }
447
+ }
448
+
449
+ return undefined;
450
+ });
451
+
452
+ // Turn mouse reporting on for the session; clean it up on exit so the shell
453
+ // doesn't inherit a terminal stuck in mouse mode.
454
+ enableMouse();
455
+
456
+ // Live todo checklist, rendered inside the right-hand sidebar.
457
+ function refreshSidebar(): void {
458
+ sidebar.refresh();
459
+ tui.requestRender();
460
+ }
461
+
462
+ // ── Autocomplete ──
463
+ // ── Autocomplete ──
464
+ editor.setAutocompleteProvider(
465
+ new CombinedAutocompleteProvider(
466
+ [
467
+ {name: 'help', description: 'Show available commands'},
468
+ {name: 'exit', description: 'Save session and quit'},
469
+ {name: 'clear', description: 'Reset conversation'},
470
+ {name: 'new', description: 'Start a new session'},
471
+ {name: 'sessions', description: 'List recent sessions'},
472
+ {name: 'resume', description: 'Load a previous session'},
473
+ {name: 'cost', description: 'Show token usage and cost'},
474
+ {name: 'model', description: 'Switch model'},
475
+ {name: 'ext', description: 'Manage extensions'},
476
+ ],
477
+ process.cwd(),
478
+ ),
479
+ );
480
+
481
+ // ── Focus editor ──
482
+ tui.setFocus(editor);
483
+
484
+ // ── Status line updater ──
485
+ // ── Messages array (agent context) ──
486
+ // Declared before updateStatusLine() so the context-fill calculation can read
487
+ // it without hitting the temporal dead zone.
488
+ const messages: Message[] = [];
489
+
490
+ function updateStatusLine() {
491
+ const modelShort = config.model.split('/').pop()?.split(':')[0] ?? config.model;
492
+ const providerName = providerForModel(config.model, Object.keys(allKeys)).provider.name;
493
+ // Context fill = the CURRENT conversation vs the configured window — not
494
+ // lifetime tokens (which never drop after /compact or /new).
495
+ const ctxTokens = estimateMessagesTokens(messages) + Math.ceil(config.systemPrompt.length / 4);
496
+ const contextPct = Math.min(100, Math.round((ctxTokens / config.contextLimit) * 100));
497
+ // Background sub-agents (ctrl+b opens the panel).
498
+ const running = state.backgroundAgents.filter((a) => a.status === 'running').length;
499
+ const agentStr = state.backgroundAgents.length
500
+ ? ` ${c.yellow}⛭ ${running}/${state.backgroundAgents.length} agents${c.reset}`
501
+ : '';
502
+ // The status line now only carries identity/nav; token, cost and context
503
+ // usage live in the sidebar's Info block.
504
+ //
505
+ // When the permission overlay is active, show a small status indicator
506
+ // while the centered modal (PermissionPrompt) handles the full prompt.
507
+ if (state.overlayMode === 'permission' && state.pendingPermission) {
508
+ statusLine.setText(
509
+ `${c.yellow}🔒 Awaiting permission...${c.reset} ${c.dim}[y/a/n/Esc]${c.reset}`,
510
+ );
511
+ } else if (scrollOffset > 0) {
512
+ // Scrolled back through the transcript — surface the way out so the
513
+ // user isn't stranded in scroll mode.
514
+ statusLine.setText(
515
+ `${c.cyan}↕ scrolled${c.reset} ${c.dim}· PgDn/↓ End or Esc to resume${c.reset}`,
516
+ );
517
+ } else {
518
+ statusLine.setText(
519
+ `${modelShort} ${c.dim}${providerName}${agentStr}${c.reset} ${c.dim}/help${c.reset}`,
520
+ );
521
+ }
522
+ sidebar.setStats({
523
+ inputTokens: totalInputTokens,
524
+ outputTokens: totalOutputTokens,
525
+ cachedTokens: totalCachedTokens,
526
+ cost: totalCost,
527
+ contextPct,
528
+ priced: isPricedModel(config.model),
529
+ });
530
+ tui.requestRender();
531
+ }
532
+ // Expose to module-level overlay handlers (model picker, agent panel).
533
+ state.refreshStatusLine = updateStatusLine;
534
+ state.refreshSidebar = () => sidebar.refresh();
535
+
536
+ // Show the centered permission modal: remove editor, add prompt to messages.
537
+ state.showPermissionModal = (): void => {
538
+ // Remove editor from view
539
+ editorRow.removeChild(editor);
540
+ // Add the centered prompt to the message area
541
+ messagesContainer.addChild(permissionPrompt);
542
+ tui.requestRender();
543
+ };
544
+
545
+ updateStatusLine();
546
+
547
+ // Re-read keys + rebuild the live provider after `/key` saves one, so it
548
+ // takes effect without a restart.
549
+ state.reloadKeys = () => {
550
+ allKeys = resolveAllKeys();
551
+ const {provider: modelDef} = providerForModel(config.model, Object.keys(allKeys));
552
+ if (!providerAccessible(modelDef, allKeys)) {
553
+ const firstConfigured = PROVIDERS.find((p) => providerAccessible(p, allKeys));
554
+ if (firstConfigured) config.model = `${firstConfigured.id}/${firstConfigured.defaultModel}`;
555
+ }
556
+ providerRef.current = createProvider(config.model);
557
+ providerRef.current.init();
558
+ updateStatusLine();
559
+ };
560
+
561
+ // ── Session persistence helper ──
562
+ function saveSession() {
563
+ if (messages.length > 0 && store) {
564
+ const tok = {
565
+ inputTokens: totalInputTokens,
566
+ outputTokens: totalOutputTokens,
567
+ cachedTokens: totalCachedTokens,
568
+ cost: totalCost,
569
+ };
570
+ // Metadata for repaint: tool names/status derived from the messages, plus
571
+ // the agent role recorded for each user turn.
572
+ const meta = deriveMessageMeta(messages).map((m, i) => {
573
+ const role = userRoles.get(i);
574
+ return role ? {...m, agentRole: role} : m;
575
+ });
576
+ if (currentSessionId) {
577
+ store.update(currentSessionId, messages, tok, meta);
578
+ } else {
579
+ const firstUserMsg = messages.find((m) => m.role === 'user');
580
+ const title = firstUserMsg ? generateTitle(firstUserMsg.content) : undefined;
581
+ const session = store.create(messages, title, tok, meta);
582
+ currentSessionId = session.id;
583
+ state.sessionTitle = title ?? null;
584
+
585
+ // Upgrade the provisional truncated title with an LLM-generated one.
586
+ // Fire-and-forget: it must never block or fail the turn.
587
+ void maybeGenerateTitle(session.id, firstUserMsg?.content ?? '');
588
+ }
589
+ }
590
+ }
591
+
592
+ /**
593
+ * Generate a better session title with a small/fast model and persist it.
594
+ *
595
+ * Uses the cheapest model the current provider exposes (utility call — quality
596
+ * barely matters, cost/latency do). Tokens are deliberately NOT folded into
597
+ * the session's displayed cost. Any failure leaves the provisional title.
598
+ */
599
+ async function maybeGenerateTitle(sessionId: string, prompt: string): Promise<void> {
600
+ try {
601
+ const provider = providerRef.current;
602
+ let model = config.model.split('/').pop() ?? config.model;
603
+ try {
604
+ const cheapest = pickCheapModel(await provider.models());
605
+ if (cheapest) model = cheapest;
606
+ } catch {
607
+ // model list unavailable — fall back to the session model
608
+ }
609
+
610
+ const result = await complete(provider, {
611
+ model,
612
+ messages: [
613
+ {
614
+ role: 'user',
615
+ content:
616
+ 'Write a concise title (max 6 words, no quotes, no trailing period) ' +
617
+ `for a coding session that begins with this request:\n\n${prompt}`,
618
+ },
619
+ ],
620
+ });
621
+
622
+ const title = sanitizeTitle(result.text);
623
+ if (!title || !store) return;
624
+ store.updateTitle(sessionId, title);
625
+ // Only reflect it if the user hasn't since moved to another session.
626
+ if (currentSessionId === sessionId) {
627
+ state.sessionTitle = title;
628
+ refreshSidebar();
629
+ }
630
+ } catch {
631
+ // keep the provisional title
632
+ }
633
+ }
634
+
635
+ /**
636
+ * Open the session picker and, on selection, swap the conversation in place.
637
+ * Returns the resumed session id (or the current one if nothing was picked).
638
+ *
639
+ * This is the single implementation behind both `/sessions` and bare
640
+ * `/resume`. It must live inside `main()` so the assignment to
641
+ * `currentSessionId` targets main()'s variable rather than a parameter copy.
642
+ */
643
+ function openSessionPicker(): string | null {
644
+ if (!store) return currentSessionId;
645
+ const s = store;
646
+ showSessionSelector(s, messagesContainer, editor, editorRow, tui, (sessionId) => {
647
+ const session = s.get(sessionId);
648
+ if (!session) return;
649
+ if (messages.length > 0 && currentSessionId) {
650
+ s.update(currentSessionId, messages, {
651
+ inputTokens: totalInputTokens,
652
+ outputTokens: totalOutputTokens,
653
+ cachedTokens: totalCachedTokens,
654
+ cost: totalCost,
655
+ });
656
+ }
657
+ messages.length = 0;
658
+ messages.push(...(session.messages as Message[]));
659
+ userRoles = new Map();
660
+ currentSessionId = session.id;
661
+ state.sessionTitle = session.title ?? null;
662
+ // Restore tokenomics from the resumed session.
663
+ const tok = session.tokenomics;
664
+ totalInputTokens = tok.inputTokens;
665
+ totalOutputTokens = tok.outputTokens;
666
+ totalCachedTokens = tok.cachedTokens;
667
+ totalCost = tok.cost;
668
+ // The in-memory todo plan belongs to the previous conversation.
669
+ clearTodos();
670
+ state.currentTodos = [];
671
+ refreshSidebar();
672
+ updateStatusLine();
673
+
674
+ // Repaint the full transcript so the user sees what they left off doing.
675
+ messagesContainer.clear();
676
+ messagesContainer.addChild(
677
+ new Text(
678
+ `${c.green} Resumed session ${session.id.substring(0, 8)}${c.reset} ${c.dim}(${messages.length} messages)${c.reset}`,
679
+ 1,
680
+ 0,
681
+ ),
682
+ );
683
+ if (session.title) {
684
+ messagesContainer.addChild(new Text(`${c.dim} Title: ${session.title}${c.reset}`, 1, 0));
685
+ }
686
+ const stored = s.getMessages(session.id);
687
+ renderHistory(messagesContainer, tui, stored, {
688
+ compactions: s.getCompactions(session.id),
689
+ });
690
+ tui.requestRender();
691
+ });
692
+ return currentSessionId;
693
+ }
694
+
695
+ /**
696
+ * Reveal the transcript prefix hidden by `renderHistory`'s window, if any.
697
+ * Bound to a key so a long resumed session isn't stuck showing only its tail.
698
+ */
699
+ function revealEarlierHistory(): boolean {
700
+ const hook = (messagesContainer as unknown as {revealEarlier?: () => void}).revealEarlier;
701
+ if (typeof hook === 'function') {
702
+ hook();
703
+ return true;
704
+ }
705
+ return false;
706
+ }
707
+
708
+ // ── Exit handler: intercept raw Ctrl+C and Ctrl+D via input listener ──
709
+ // pi-tui maps ctrl+c to "copy selection" and ctrl+d to "delete", so we
710
+ // listen at the raw TUI level. On empty editor, these become exit signals.
711
+ tui.addInputListener((data: string) => {
712
+ if (matchesKey(data, 'ctrl+c') || matchesKey(data, 'ctrl+d')) {
713
+ if (editor.getText().trim().length === 0) {
714
+ saveSession();
715
+ tui.stop();
716
+ process.exit(0);
717
+ }
718
+ }
719
+ return {consume: false};
720
+ });
721
+
722
+ // ═══════════════════════════════════════════════════════════════════════════
723
+ // Background agents — hidden from the transcript, opened with ctrl+b
724
+ // ═══════════════════════════════════════════════════════════════════════════
725
+
726
+ let agentsPanel: ReturnType<typeof openAgentsPanel> | null = null;
727
+
728
+ function openPanel(): void {
729
+ if (agentsPanel) return;
730
+ agentsPanel = openAgentsPanel(tui, messagesContainer, editorRow, editor);
731
+ }
732
+
733
+ function closePanel(): void {
734
+ if (!agentsPanel) return;
735
+ closeAgentsPanel(tui, agentsPanel, messagesContainer, editorRow, editor);
736
+ agentsPanel = null;
737
+ }
738
+
739
+ /**
740
+ * Render the input role indicator.
741
+ *
742
+ * Cycles only **primary agents** (Tab) — the agent that owns the turn. The
743
+ * delegation roles (`explore`, `build`, …) are not shown here: the primary
744
+ * agent fans work out to them on its own.
745
+ */
746
+ function updateRoleIndicator(): void {
747
+ const primaries = listPrimaries();
748
+ if (primaries.length <= 1) {
749
+ // Nothing to cycle — keep the editor clean.
750
+ roleIndicator.setText('');
751
+ tui.requestRender();
752
+ return;
753
+ }
754
+
755
+ const spec = resolvePrimary(state.currentAgentRole) ?? primaries[0];
756
+ const color = colorByName(spec.color, agentColors[spec.name] ?? c.cyan);
757
+ const label = spec.label ?? agentLabels[spec.name] ?? spec.name;
758
+ roleIndicator.setText(` ${color}▸ ${label}${c.reset} ${c.dim}(Tab to cycle)${c.reset}`);
759
+ tui.requestRender();
760
+ }
761
+
762
+ /** Advance to the next primary agent (wraps). No-op when fewer than two. */
763
+ function cycleAgentRole(): void {
764
+ const primaries = listPrimaries();
765
+ if (primaries.length <= 1) return;
766
+ const idx = primaries.findIndex((p) => p.name === state.currentAgentRole);
767
+ const next = primaries[(idx + 1) % primaries.length];
768
+ state.currentAgentRole = next.name;
769
+ updateRoleIndicator();
770
+ }
771
+
772
+ /** Switch directly to a primary agent. Returns false if it isn't registered. */
773
+ function switchPrimary(name: string): boolean {
774
+ if (!resolvePrimary(name)) return false;
775
+ state.currentAgentRole = name;
776
+ updateRoleIndicator();
777
+ return true;
778
+ }
779
+
780
+ /**
781
+ * Whether a primary is the read-only planning agent.
782
+ *
783
+ * Prefers the explicit `role` tag; falls back to the tool list, which is what
784
+ * actually gets enforced either way.
785
+ */
786
+ function isReadOnlyRole(name: string): boolean {
787
+ const primary = resolvePrimary(name);
788
+ if (primary?.role) return primary.role === 'plan';
789
+ return isReadOnlyPrimary(name);
790
+ }
791
+
792
+ // Let extension loading refresh the indicator once primaries are registered.
793
+ state.refreshRoleIndicator = updateRoleIndicator;
794
+
795
+ tui.addInputListener((data: string) => {
796
+ // ── Permission overlay — y/n/a/Esc while a permission prompt is active ──
797
+ if (state.overlayMode === 'permission' && state.permissionResolver) {
798
+ /** Tear down the permission modal UI and restore the editor. */
799
+ const teardownPermission = (): void => {
800
+ // Remove the centered prompt from the message area
801
+ if (state.permissionPrompt) {
802
+ try { messagesContainer.removeChild(state.permissionPrompt); } catch {}
803
+ }
804
+ // Restore the editor
805
+ editorRow.addChild(editor);
806
+ tui.setFocus(editor);
807
+ tui.requestRender();
808
+ };
809
+
810
+ if (matchesKey(data, 'y') || matchesKey(data, Key.shift('y'))) {
811
+ // Allow once
812
+ state.permissionResolver(true);
813
+ // Only tear down if no queued permissions remain (resolver may have
814
+ // already set up the next modal via showNextQueuedPermission)
815
+ if (!state.permissionResolver) teardownPermission();
816
+ return {consume: true};
817
+ }
818
+ if (matchesKey(data, 'a') || matchesKey(data, Key.shift('a'))) {
819
+ // Always allow — add to session whitelist, then allow
820
+ const perm = state.pendingPermission;
821
+ if (perm) {
822
+ state.permissionWhitelist.push({tool: perm.toolName, pattern: perm.target});
823
+ }
824
+ state.permissionResolver(true);
825
+ if (!state.permissionResolver) teardownPermission();
826
+ return {consume: true};
827
+ }
828
+ if (matchesKey(data, 'n') || matchesKey(data, Key.shift('n')) || matchesKey(data, 'escape')) {
829
+ // Deny
830
+ state.permissionResolver(false);
831
+ if (!state.permissionResolver) teardownPermission();
832
+ return {consume: true};
833
+ }
834
+ // Ignore all other keys while permission overlay is active
835
+ return {consume: true};
836
+ }
837
+
838
+ // Tab cycles *primary* agents (OMO/OpenCode style) — only when the editor
839
+ // is empty, so file-path autocomplete keeps working.
840
+ if (matchesKey(data, 'tab') && editor.getText().trim().length === 0) {
841
+ cycleAgentRole();
842
+ return {consume: true};
843
+ }
844
+ // Esc aborts a running turn (keeps the session). Only active mid-turn —
845
+ // otherwise Esc falls through to the editor (autocomplete dismissal).
846
+ if (matchesKey(data, 'escape') && state.activeAbort) {
847
+ state.activeAbort.abort();
848
+ return {consume: true};
849
+ }
850
+ if (matchesKey(data, 'ctrl+b')) {
851
+ if (state.overlayMode === 'agents') closePanel();
852
+ else openPanel();
853
+ return {consume: true};
854
+ }
855
+ if (matchesKey(data, 'ctrl+o')) {
856
+ // Re-inflate the most recent collapsed run.
857
+ if (state.lastRun) {
858
+ state.lastRun.expand();
859
+ state.lastRun = null;
860
+ }
861
+ return {consume: true};
862
+ }
863
+ if (state.overlayMode === 'agents' && matchesKey(data, 'escape')) {
864
+ closePanel();
865
+ return {consume: true};
866
+ }
867
+ return {consume: false};
868
+ });
869
+
870
+ // Sub-agent lifecycle → status bar counter only (no transcript spam).
871
+ onAgentEvent((ev) => {
872
+ if (ev.type === 'delegate-start') {
873
+ if (!state.backgroundAgents.some((a) => a.id === ev.id)) {
874
+ state.backgroundAgents.push({
875
+ id: ev.id,
876
+ task: ev.task,
877
+ status: 'running',
878
+ startedAt: Date.now(),
879
+ });
880
+ }
881
+ state.refreshStatusLine();
882
+ } else if (ev.type === 'delegate-done') {
883
+ const agent = state.backgroundAgents.find((a) => a.id === ev.id);
884
+ if (agent) {
885
+ agent.status = ev.error ? 'error' : 'done';
886
+ agent.finishedAt = Date.now();
887
+ agent.result = ev.summary;
888
+ }
889
+ state.refreshStatusLine();
890
+ } else if (ev.type === 'todos-updated') {
891
+ state.currentTodos = ev.todos;
892
+ refreshSidebar();
893
+ } else if (ev.type === 'primary-request') {
894
+ // The agent asked to change mode (e.g. enter/exit plan mode).
895
+ const wasReadOnly = isReadOnlyRole(state.currentAgentRole);
896
+ if (switchPrimary(ev.name)) {
897
+ const nowReadOnly = isReadOnlyRole(ev.name);
898
+ // Leaving a read-only agent (plan → pal) means a plan is ready. Flag it
899
+ // so the turn is followed by an implementation turn, rather than
900
+ // stopping and making the user type "go".
901
+ if (wasReadOnly && !nowReadOnly && !autoExecuted) pendingExecution = true;
902
+
903
+ const why = ev.reason ? ` ${c.dim}— ${ev.reason}${c.reset}` : '';
904
+ messagesContainer.addChild(
905
+ new Text(`${c.dim} → switched to ${c.reset}${c.bold}${ev.name}${c.reset}${why}`, 1, 0),
906
+ );
907
+ tui.requestRender();
908
+ }
909
+ }
910
+ });
911
+
912
+ // ═══════════════════════════════════════════════════════════════════════════
913
+ // Editor submit handler
914
+ // ═══════════════════════════════════════════════════════════════════════════
915
+
916
+ let isProcessing = false;
917
+
918
+ // Set by the `primary-request` listener when a planning agent hands control
919
+ // back: the turn that follows should implement the plan automatically.
920
+ let pendingExecution = false;
921
+ // Guards against a plan → execute → plan → execute chain in one user message.
922
+ let autoExecuted = false;
923
+
924
+ editor.onSubmit = async (text) => {
925
+ if (isProcessing) return;
926
+ // `let` so `/plan <task>` and `/execute <task>` can rewrite the input and
927
+ // fall through to the normal turn dispatch below.
928
+ let trimmed = text.trim();
929
+ if (!trimmed) return;
930
+
931
+ editor.setText('');
932
+
933
+ // ── Slash commands ──
934
+ if (trimmed === '/help' || trimmed === '/h') {
935
+ cmdHelp(messagesContainer, tui);
936
+ return;
937
+ }
938
+ if (trimmed === 'exit' || trimmed === 'quit' || trimmed === '/exit' || trimmed === '/quit') {
939
+ saveSession();
940
+ tui.stop();
941
+ process.exit(0);
942
+ }
943
+ if (trimmed === '/roles') {
944
+ const mod = await import('@pal/agents').catch(() => null);
945
+ if (!mod) {
946
+ messagesContainer.addChild(
947
+ new Text(`${c.dim} @pal/agents is not installed${c.reset}`, 1, 0),
948
+ );
949
+ } else {
950
+ const lines = mod.formatRoles().split('\n');
951
+ for (const line of lines) {
952
+ messagesContainer.addChild(new Text(`${c.dim}${line}${c.reset}`, 0, 0));
953
+ }
954
+ }
955
+ tui.requestRender();
956
+ return;
957
+ }
958
+ // ── Plan mode ──
959
+ // The read-only `plan` primary can be reached two ways: Tab (manual) or
960
+ // `/plan` (automatic — one step, no cycling). `/plan <task>` enters plan
961
+ // mode AND runs that task in the same go; `/execute` returns to the
962
+ // orchestrator to implement what was planned.
963
+ if (trimmed === '/plan' || trimmed.startsWith('/plan ')) {
964
+ await ensureExtensionsLoaded(config.extensions);
965
+ const arg = trimmed.slice('/plan'.length).trim();
966
+
967
+ if (arg === 'off') {
968
+ switchPrimary(defaultPrimaryName());
969
+ messagesContainer.addChild(
970
+ new Text(`${c.dim} plan mode off — back to ${defaultPrimaryName()}${c.reset}`, 1, 0),
971
+ );
972
+ tui.requestRender();
973
+ return;
974
+ }
975
+ if (!switchPrimary('plan')) {
976
+ messagesContainer.addChild(
977
+ new Text(`${c.dim} no "plan" primary is configured${c.reset}`, 1, 0),
978
+ );
979
+ tui.requestRender();
980
+ return;
981
+ }
982
+ if (arg) {
983
+ trimmed = arg; // fall through — run the task in plan mode
984
+ } else {
985
+ messagesContainer.addChild(
986
+ new Text(
987
+ `${c.red}▸ plan${c.reset}${c.dim} — read-only. Describe what to plan, or ${c.reset}/execute${c.dim} to implement.${c.reset}`,
988
+ 1,
989
+ 0,
990
+ ),
991
+ );
992
+ tui.requestRender();
993
+ return;
994
+ }
995
+ }
996
+ if (trimmed === '/execute' || trimmed.startsWith('/execute ')) {
997
+ await ensureExtensionsLoaded(config.extensions);
998
+ const arg = trimmed.slice('/execute'.length).trim();
999
+ switchPrimary(defaultPrimaryName());
1000
+ if (arg) {
1001
+ trimmed = arg; // fall through — implement in the orchestrator
1002
+ } else {
1003
+ messagesContainer.addChild(
1004
+ new Text(
1005
+ `${c.green}▸ ${defaultPrimaryName()}${c.reset}${c.dim} — plan mode off, ready to implement.${c.reset}`,
1006
+ 1,
1007
+ 0,
1008
+ ),
1009
+ );
1010
+ tui.requestRender();
1011
+ return;
1012
+ }
1013
+ }
1014
+ if (trimmed === '/reload' || trimmed === '/restart') {
1015
+ if (!isDebugEnabled()) {
1016
+ messagesContainer.addChild(
1017
+ new Text(
1018
+ `${c.dim} ${trimmed} is only available in debug mode (PAL_DEBUG=1)${c.reset}`,
1019
+ 1,
1020
+ 0,
1021
+ ),
1022
+ );
1023
+ tui.requestRender();
1024
+ return;
1025
+ }
1026
+ if (trimmed === '/reload') {
1027
+ // Re-import extensions (cache-bust via timestamp query param).
1028
+ // Useful during extension development — no full restart needed.
1029
+ const turnModule = await import('./turn.js');
1030
+ const toolCount = await turnModule.reloadExtensions(config.extensions);
1031
+ messagesContainer.addChild(
1032
+ new Text(`${c.green} Extensions reloaded (${toolCount} tools)${c.reset}`, 1, 0),
1033
+ );
1034
+ } else {
1035
+ // Save session, then spawn a fresh process and exit.
1036
+ saveSession();
1037
+ tui.stop();
1038
+ const args = process.argv.slice(2);
1039
+ Bun.spawn(['bun', 'run', 'start', ...args], {
1040
+ stdio: ['inherit', 'inherit', 'inherit'],
1041
+ cwd: process.cwd(),
1042
+ });
1043
+ process.exit(0);
1044
+ }
1045
+ tui.requestRender();
1046
+ return;
1047
+ }
1048
+ if (trimmed === '/new') {
1049
+ saveSession();
1050
+ messages.length = 0;
1051
+ userRoles = new Map();
1052
+ currentSessionId = null;
1053
+ state.sessionTitle = null;
1054
+ messagesContainer.clear();
1055
+ resetShell();
1056
+ clearTodos();
1057
+ state.currentTodos = [];
1058
+ state.permissionWhitelist = [];
1059
+ refreshSidebar();
1060
+ messagesContainer.addChild(
1061
+ new Text(`${c.yellow}New session started.${c.reset}`, 1, 0),
1062
+ );
1063
+ tui.requestRender();
1064
+ return;
1065
+ }
1066
+ if (trimmed === '/clear') {
1067
+ // /clear was removed in favour of /new: history is append-only now, so
1068
+ // "erase this session" has no clean representation. Point users at /new.
1069
+ messagesContainer.addChild(
1070
+ new Text(`${c.dim} /clear was removed — use /new to start a fresh session.${c.reset}`, 1, 0),
1071
+ );
1072
+ tui.requestRender();
1073
+ return;
1074
+ }
1075
+ if (trimmed === '/undo' || trimmed.startsWith('/undo ')) {
1076
+ const snapshotId = trimmed.slice('/undo'.length).trim() || undefined;
1077
+ const result = restoreSnapshot(snapshotId);
1078
+ messagesContainer.addChild(
1079
+ new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1080
+ );
1081
+ tui.requestRender();
1082
+ return;
1083
+ }
1084
+ if (trimmed === '/snapshots') {
1085
+ const snaps = listSnapshots(15);
1086
+ if (snaps.length === 0) {
1087
+ messagesContainer.addChild(
1088
+ new Text(
1089
+ `${c.dim} No snapshots. Snapshots are taken automatically before edits.${c.reset}`,
1090
+ 1,
1091
+ 0,
1092
+ ),
1093
+ );
1094
+ } else {
1095
+ const lines = snaps.map((s) => {
1096
+ const time = new Date(s.ts).toLocaleTimeString();
1097
+ const name = s.originalPath.split(/[/\\]/).pop() ?? s.originalPath;
1098
+ return ` ${c.dim}${time}${c.reset} ${s.tool.padEnd(11)} ${name} ${c.dim}${s.id}${c.reset}`;
1099
+ });
1100
+ messagesContainer.addChild(
1101
+ new Text(
1102
+ `${c.bold}Snapshots${c.reset} ${c.dim}(/undo [id] to restore)${c.reset}\n${lines.join('\n')}`,
1103
+ 1,
1104
+ 0,
1105
+ ),
1106
+ );
1107
+ }
1108
+ tui.requestRender();
1109
+ return;
1110
+ }
1111
+ if (trimmed === '/compact') {
1112
+ // Manual compaction mirrors the agent's own: summarize the oldest messages
1113
+ // into a checkpoint, raise the high-water mark, and keep every message.
1114
+ // Starting from the existing mark means a second `/compact` (or one after
1115
+ // an automatic compaction) extends the checkpoint instead of redoing it.
1116
+ const alreadyUpto = store && currentSessionId ? store.getCompactedUpto(currentSessionId) : 0;
1117
+ const remaining = messages.slice(alreadyUpto);
1118
+ const boundary = compactionBoundary(remaining, 5);
1119
+ if (boundary <= 0) {
1120
+ messagesContainer.addChild(
1121
+ new Text(`${c.dim}Context is within limits — nothing to compact.${c.reset}`, 1, 0),
1122
+ );
1123
+ tui.requestRender();
1124
+ return;
1125
+ }
1126
+ const provider = providerRef.current;
1127
+ const summary = await summarizeRange(remaining.slice(0, boundary), (prompt) =>
1128
+ complete(provider, {model: config.model, messages: [{role: 'user', content: prompt}]}).then(
1129
+ (r) => r.text,
1130
+ ),
1131
+ );
1132
+ const newMark = alreadyUpto + boundary;
1133
+ if (store && currentSessionId) {
1134
+ store.recordCompaction(currentSessionId, alreadyUpto, newMark, summary);
1135
+ }
1136
+ messagesContainer.addChild(
1137
+ new Text(
1138
+ `${c.green}Compacted ${boundary} messages into a checkpoint.${c.reset}`,
1139
+ 1,
1140
+ 0,
1141
+ ),
1142
+ );
1143
+ tui.requestRender();
1144
+ return;
1145
+ }
1146
+ if (trimmed.startsWith('/effort')) {
1147
+ const level = trimmed.split(' ')[1]?.trim() as 'low' | 'medium' | 'high' | undefined;
1148
+ if (!level || !['low', 'medium', 'high'].includes(level)) {
1149
+ messagesContainer.addChild(
1150
+ new Text(
1151
+ `${c.dim}Current reasoning effort: ${c.reset}${c.bold}${config.reasoningEffort}${c.reset}${c.dim}\nUsage: /effort low|medium|high${c.reset}`,
1152
+ 1,
1153
+ 0,
1154
+ ),
1155
+ );
1156
+ } else {
1157
+ config.reasoningEffort = level;
1158
+ saveSetting('reasoningEffort', level);
1159
+ messagesContainer.addChild(
1160
+ new Text(`${c.green}Reasoning effort set to: ${level}${c.reset}`, 1, 0),
1161
+ );
1162
+ updateStatusLine();
1163
+ }
1164
+ tui.requestRender();
1165
+ return;
1166
+ }
1167
+ if (trimmed === '/permission' || trimmed === '/perm') {
1168
+ const {loadPermissions} = await import('./config.js');
1169
+ const perm = loadPermissions();
1170
+ const lines: string[] = [];
1171
+ lines.push(`${c.bold}Permission rules:${c.reset}`);
1172
+ lines.push('');
1173
+ lines.push(`${c.dim}Defaults:${c.reset}`);
1174
+ for (const [tool, action] of Object.entries(perm.defaults)) {
1175
+ const color = action === 'allow' ? c.green : action === 'deny' ? c.red : c.yellow;
1176
+ lines.push(` ${tool.padEnd(20)} ${color}${action}${c.reset}`);
1177
+ }
1178
+ lines.push('');
1179
+ lines.push(`${c.dim}Rules (first match wins):${c.reset}`);
1180
+ if (perm.rules.length === 0) {
1181
+ lines.push(' (none)');
1182
+ } else {
1183
+ for (const rule of perm.rules) {
1184
+ const tools = Array.isArray(rule.tool) ? rule.tool.join(',') : rule.tool;
1185
+ const color = rule.action === 'allow' ? c.green : rule.action === 'deny' ? c.red : c.yellow;
1186
+ lines.push(` ${tools.padEnd(20)} ${rule.match.padEnd(20)} ${color}${rule.action}${c.reset}`);
1187
+ }
1188
+ }
1189
+ if (state.permissionWhitelist.length > 0) {
1190
+ lines.push('');
1191
+ lines.push(`${c.dim}Session whitelist (cleared on /new):${c.reset}`);
1192
+ for (const entry of state.permissionWhitelist) {
1193
+ lines.push(` ${entry.tool.padEnd(20)} ${c.green}${entry.pattern}${c.reset}`);
1194
+ }
1195
+ }
1196
+ lines.push('');
1197
+ lines.push(`${c.dim}Edit permissions.json in your project root or ~/.pal/ to customize.${c.reset}`);
1198
+ for (const line of lines) {
1199
+ messagesContainer.addChild(new Text(line, 1, 0));
1200
+ }
1201
+ tui.requestRender();
1202
+ return;
1203
+ }
1204
+ if (trimmed === '/sessions') {
1205
+ currentSessionId = openSessionPicker();
1206
+ return;
1207
+ }
1208
+ // Bare `/resume` behaves exactly like `/sessions` — one implementation.
1209
+ // (`cmdResume`'s interactive path used to mutate a parameter, so the
1210
+ // resumed id never reached main()'s variable and the next save created a
1211
+ // brand-new session instead of updating the resumed one.)
1212
+ if (trimmed === '/resume') {
1213
+ currentSessionId = openSessionPicker();
1214
+ return;
1215
+ }
1216
+ if (trimmed.startsWith('/resume ')) {
1217
+ if (!store) return;
1218
+ currentSessionId = cmdResume(
1219
+ trimmed,
1220
+ messages,
1221
+ store,
1222
+ currentSessionId,
1223
+ messagesContainer,
1224
+ tui,
1225
+ );
1226
+ return;
1227
+ }
1228
+ if (trimmed === '/cost') {
1229
+ cmdCost(totalInputTokens, totalOutputTokens, totalCost, config.model, messagesContainer, tui);
1230
+ return;
1231
+ }
1232
+ if (trimmed === '/model' || trimmed === '/model ') {
1233
+ void showModelSelector(
1234
+ config,
1235
+ messagesContainer,
1236
+ editor,
1237
+ editorRow,
1238
+ tui,
1239
+ providerRef,
1240
+ createProvider,
1241
+ allKeys,
1242
+ );
1243
+ return;
1244
+ }
1245
+ if (trimmed.startsWith('/model ')) {
1246
+ // Direct model set: /model provider/model-name
1247
+ const newName = trimmed.slice(7).trim();
1248
+ config.model = newName;
1249
+ saveSetting('model', newName);
1250
+ providerRef.current = createProvider(newName);
1251
+ providerRef.current.init();
1252
+ messagesContainer.addChild(
1253
+ new Text(`${c.green} Model set to: ${config.model}${c.reset}`, 1, 0),
1254
+ );
1255
+ state.refreshStatusLine();
1256
+ tui.requestRender();
1257
+ return;
1258
+ }
1259
+ if (trimmed === '/keys') {
1260
+ const keys = resolveAllKeys();
1261
+ const lines = PROVIDERS.map((p) => {
1262
+ const has = keys[p.id] ? `${c.green}set${c.reset}` : `${c.dim}—${c.reset}`;
1263
+ return ` ${p.name.padEnd(16)} ${has}${p.keyOptional && !keys[p.id] ? ` ${c.dim}(keyless available)${c.reset}` : ''}`;
1264
+ });
1265
+ messagesContainer.addChild(
1266
+ new Text(
1267
+ `${c.bold}Configured keys${c.reset} ${c.dim}(${configPath()})${c.reset}\n${lines.join('\n')}\n${c.dim}Add or change a key with /key <value> — it takes effect immediately.${c.reset}`,
1268
+ 1,
1269
+ 0,
1270
+ ),
1271
+ );
1272
+ tui.requestRender();
1273
+ return;
1274
+ }
1275
+ if (trimmed === '/key' || trimmed === '/config') {
1276
+ showKeyInput(config, messagesContainer, editor, editorRow, tui);
1277
+ return;
1278
+ }
1279
+ if (trimmed === '/ext' || trimmed.startsWith('/ext ')) {
1280
+ const args = trimmed.slice('/ext'.length).trim();
1281
+ const parts = args.split(/\s+/);
1282
+ const sub = parts[0];
1283
+ const pkg = parts[1];
1284
+
1285
+ if (sub === 'add' && pkg) {
1286
+ const {extAdd} = await import('./commands/ext.js');
1287
+ const result = extAdd(pkg);
1288
+ messagesContainer.addChild(
1289
+ new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1290
+ );
1291
+ } else if (sub === 'remove' && pkg) {
1292
+ const {extRemove} = await import('./commands/ext.js');
1293
+ const result = extRemove(pkg);
1294
+ messagesContainer.addChild(
1295
+ new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1296
+ );
1297
+ } else if (sub === 'list') {
1298
+ const extensions = state.extensions;
1299
+ const lines = extensions.map((ext) => {
1300
+ const status = ext.active ? `${c.green}active${c.reset}` : `${c.red}failed${c.reset}`;
1301
+ return ` ${ext.name.padEnd(24)} ${status}`;
1302
+ });
1303
+ if (lines.length === 0) {
1304
+ messagesContainer.addChild(new Text(`${c.dim} No extensions loaded.${c.reset}`, 1, 0));
1305
+ } else {
1306
+ messagesContainer.addChild(
1307
+ new Text(`${c.bold}Loaded extensions${c.reset}\n${lines.join('\n')}`, 1, 0),
1308
+ );
1309
+ }
1310
+ } else {
1311
+ messagesContainer.addChild(
1312
+ new Text(
1313
+ `${c.dim} Usage: /ext add <name> | /ext remove <name> | /ext list${c.reset}`,
1314
+ 1,
1315
+ 0,
1316
+ ),
1317
+ );
1318
+ }
1319
+ tui.requestRender();
1320
+ return;
1321
+ }
1322
+
1323
+ if (trimmed === '/mcp' || trimmed.startsWith('/mcp ')) {
1324
+ const args = trimmed.slice('/mcp'.length).trim();
1325
+ const parts = args.split(/\s+/);
1326
+ const sub = parts[0];
1327
+
1328
+ if (sub === 'add' && parts.length >= 3) {
1329
+ const name = parts[1];
1330
+ const command = parts[2];
1331
+ const cmdArgs = parts.slice(3);
1332
+ const {mcpAdd} = await import('./commands/mcp.js');
1333
+ const result = mcpAdd(name, command, cmdArgs);
1334
+ messagesContainer.addChild(
1335
+ new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1336
+ );
1337
+ } else if (sub === 'add-remote' && parts.length >= 3) {
1338
+ const name = parts[1];
1339
+ const url = parts[2];
1340
+ const headers: Record<string, string> = {};
1341
+ // Parse --header "Key: Value" pairs
1342
+ for (let i = 3; i < parts.length; i++) {
1343
+ if (parts[i] === '--header' && parts[i + 1]) {
1344
+ const [key, ...valueParts] = parts[i + 1].split(':');
1345
+ if (key && valueParts.length > 0) {
1346
+ headers[key.trim()] = valueParts.join(':').trim();
1347
+ }
1348
+ i++; // skip the header value
1349
+ }
1350
+ }
1351
+ const {mcpAddRemote} = await import('./commands/mcp.js');
1352
+ const result = mcpAddRemote(name, url, Object.keys(headers).length > 0 ? headers : undefined);
1353
+ messagesContainer.addChild(
1354
+ new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1355
+ );
1356
+ } else if (sub === 'remove' && parts[1]) {
1357
+ const {mcpRemove} = await import('./commands/mcp.js');
1358
+ const result = mcpRemove(parts[1]);
1359
+ messagesContainer.addChild(
1360
+ new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1361
+ );
1362
+ } else if (sub === 'list') {
1363
+ const {mcpList} = await import('./commands/mcp.js');
1364
+ const lines = mcpList();
1365
+ messagesContainer.addChild(
1366
+ new Text(`${c.bold}${lines.join('\n')}${c.reset}`, 1, 0),
1367
+ );
1368
+ } else if (sub === 'browse') {
1369
+ const {REGISTRY} = await import('./commands/mcp-registry.js');
1370
+ const lines: string[] = [`${c.bold}Curated MCP Servers${c.reset}`, ''];
1371
+ for (const entry of REGISTRY) {
1372
+ lines.push(` ${c.cyan}${entry.name}${c.reset}`);
1373
+ lines.push(` ${c.dim}${entry.description}${c.reset}`);
1374
+ if (entry.url) {
1375
+ // Remote server
1376
+ lines.push(` ${c.green}/mcp add-remote ${entry.name.toLowerCase()} ${entry.url}${c.reset}`);
1377
+ } else if (entry.package) {
1378
+ // Local server
1379
+ lines.push(` ${c.green}/mcp add ${entry.name.toLowerCase()} npx -y ${entry.package}${c.reset}`);
1380
+ }
1381
+ lines.push('');
1382
+ }
1383
+ messagesContainer.addChild(new Text(lines.join('\n'), 1, 0));
1384
+ } else if (sub === 'search' && parts[1]) {
1385
+ const query = parts.slice(1).join(' ');
1386
+ const {searchRegistry} = await import('./commands/mcp-registry.js');
1387
+ const results = searchRegistry(query);
1388
+ if (results.length === 0) {
1389
+ messagesContainer.addChild(
1390
+ new Text(`${c.dim} No MCP servers found for "${query}".${c.reset}`, 1, 0),
1391
+ );
1392
+ } else {
1393
+ const lines: string[] = [
1394
+ `${c.bold}Search results for "${query}"${c.reset}`,
1395
+ '',
1396
+ ];
1397
+ for (const entry of results) {
1398
+ lines.push(` ${c.cyan}${entry.name}${c.reset} — ${entry.description}`);
1399
+ if (entry.url) {
1400
+ lines.push(` ${c.green}/mcp add-remote ${entry.name.toLowerCase()} ${entry.url}${c.reset}`);
1401
+ } else if (entry.package) {
1402
+ lines.push(` ${c.green}/mcp add ${entry.name.toLowerCase()} npx -y ${entry.package}${c.reset}`);
1403
+ }
1404
+ lines.push('');
1405
+ }
1406
+ messagesContainer.addChild(new Text(lines.join('\n'), 1, 0));
1407
+ }
1408
+ } else {
1409
+ messagesContainer.addChild(
1410
+ new Text(
1411
+ `${c.dim} Usage: /mcp add <name> <cmd> [args] | /mcp add-remote <name> <url> [--header "Key: Value"] | /mcp remove <name> | /mcp list | /mcp browse | /mcp search <query>${c.reset}`,
1412
+ 1,
1413
+ 0,
1414
+ ),
1415
+ );
1416
+ }
1417
+ tui.requestRender();
1418
+ return;
1419
+ }
1420
+
1421
+ // ── Clear finished todos when user moves on to something new ──
1422
+ if (state.currentTodos.length > 0) {
1423
+ const allTerminal = state.currentTodos.every(
1424
+ (t) => t.status === 'completed' || t.status === 'cancelled',
1425
+ );
1426
+ if (allTerminal) {
1427
+ state.currentTodos = [];
1428
+ refreshSidebar();
1429
+ }
1430
+ }
1431
+
1432
+ // ── Show user message in a box ──
1433
+ // Spacing lives outside the box (between messages), never inside it.
1434
+ const activeRole = state.currentAgentRole;
1435
+ // Record the role for this user turn so repaint can colour it correctly.
1436
+ userRoles.set(messages.length, activeRole);
1437
+ messagesContainer.addChild(new Spacer(1));
1438
+ messagesContainer.addChild(new MessageBox(trimmed, activeRole, formatMessageTimestamp(Date.now())));
1439
+ messagesContainer.addChild(new Spacer(1));
1440
+ tui.requestRender();
1441
+
1442
+ // ── Agent turn ──
1443
+ // The selected primary agent shapes the turn itself (system prompt + tool
1444
+ // set) rather than being described in the message — see agentLoop.
1445
+ isProcessing = true;
1446
+ editor.disableSubmit = true;
1447
+ autoExecuted = false;
1448
+
1449
+ /**
1450
+ * Run one turn and fold its usage into the session totals.
1451
+ *
1452
+ * Reads `state.currentAgentRole` at call time (not a captured variable) so a
1453
+ * mode the agent switched to mid-conversation is honoured by the next turn.
1454
+ */
1455
+ const runTurn = async (message: string): Promise<void> => {
1456
+ pendingExecution = false;
1457
+ state.activeAbort = new AbortController();
1458
+
1459
+ let answered = false;
1460
+ try {
1461
+ // Build the compaction note from all stored checkpoints so the resumed
1462
+ // session re-enters runAgent with the full summary context. Without this,
1463
+ // compactionNote starts empty and the model never sees its own earlier
1464
+ // summaries — a silent loss of context on every resume.
1465
+ let resumedNote = '';
1466
+ if (store && currentSessionId) {
1467
+ const records = store.getCompactions(currentSessionId);
1468
+ resumedNote = records
1469
+ .map((r) => `[messages ${r.fromSeq}-${r.toSeq}]\n${r.summary}`)
1470
+ .join('\n\n');
1471
+ }
1472
+ const result = await agentLoop(
1473
+ message,
1474
+ messages,
1475
+ config,
1476
+ tui,
1477
+ messagesContainer,
1478
+ allKeys,
1479
+ createProvider,
1480
+ state.currentAgentRole,
1481
+ // Resume from the persisted high-water mark so an already-summarized
1482
+ // prefix is neither re-sent nor re-summarized.
1483
+ store && currentSessionId ? store.getCompactedUpto(currentSessionId) : 0,
1484
+ resumedNote,
1485
+ );
1486
+ answered = true;
1487
+ if (state.activeRun) {
1488
+ state.activeRun.finish(true);
1489
+ state.lastRun = state.activeRun; // ctrl+o can re-inflate this run
1490
+ }
1491
+
1492
+ totalInputTokens += result.inputTokens;
1493
+ totalCachedTokens += result.cachedTokens;
1494
+ totalOutputTokens += result.outputTokens;
1495
+ const turnCost = estimateCost(
1496
+ result.model,
1497
+ result.inputTokens,
1498
+ result.outputTokens,
1499
+ result.cachedTokens,
1500
+ );
1501
+ totalCost += turnCost;
1502
+
1503
+ updateStatusLine();
1504
+ saveSession();
1505
+
1506
+ // Record the checkpoint the agent produced, if any. The messages it
1507
+ // summarized are still stored — this only raises the high-water mark so
1508
+ // the model view (and next request) skips the summarized prefix.
1509
+ //
1510
+ // `boundary` is a whole-history COUNT; the store speaks in 1-based seqs,
1511
+ // and a rolled-back earlier turn can shift them apart, so convert through
1512
+ // the same helper the agent uses instead of assuming they're equal.
1513
+ if (result.compaction && store && currentSessionId) {
1514
+ const from = store.getCompactedUpto(currentSessionId);
1515
+ const to = seqToCount(result.compaction.boundary, messages.length);
1516
+ if (to > from) {
1517
+ store.recordCompaction(currentSessionId, from, to, result.compaction.summary);
1518
+ }
1519
+ }
1520
+ } catch (err) {
1521
+ const msg = err instanceof Error ? err.message : String(err);
1522
+ messagesContainer.addChild(new Text(`${c.red} Error: ${msg}${c.reset}`, 1, 0));
1523
+ tui.requestRender();
1524
+ // Roll the transcript back to the start of this turn (core owns the rule).
1525
+ const rolledBackTo = rollbackTurn(messages);
1526
+ // Keep the append-only store consistent: drop any rows this failed turn
1527
+ // managed to persist (seq is 1-based, so the message at index N is seq N+1).
1528
+ if (store && currentSessionId) {
1529
+ store.deleteMessagesFrom(currentSessionId, rolledBackTo + 1);
1530
+ }
1531
+ } finally {
1532
+ state.activeAbort = null;
1533
+ if (!answered && state.activeRun) {
1534
+ state.activeRun.finish(false);
1535
+ state.lastRun = state.activeRun;
1536
+ }
1537
+ state.activeRun = null;
1538
+ tui.requestRender();
1539
+ }
1540
+ };
1541
+
1542
+ await runTurn(trimmed);
1543
+
1544
+ // ── Auto-execute a finished plan ──
1545
+ // The planning agent called exit_plan_mode, so a plan is ready. Implement it
1546
+ // in the same submission instead of stopping and waiting for "go".
1547
+ // Single-shot: a plan→execute→plan→execute chain within one message is
1548
+ // refused by the `autoExecuted` guard above.
1549
+ if (pendingExecution && !autoExecuted) {
1550
+ autoExecuted = true;
1551
+ pendingExecution = false;
1552
+ messagesContainer.addChild(
1553
+ new Text(`${c.green} ▸ ${c.reset}${c.dim}plan approved — implementing…${c.reset}`, 1, 0),
1554
+ );
1555
+ tui.requestRender();
1556
+ await runTurn(
1557
+ 'Your plan above is approved. Implement it now, following that plan. ' +
1558
+ 'Do not enter plan mode again for this task — carry it through to completion.',
1559
+ );
1560
+ }
1561
+
1562
+ isProcessing = false;
1563
+ editor.disableSubmit = false;
1564
+ tui.requestRender();
1565
+ };
1566
+
1567
+ // ═══════════════════════════════════════════════════════════════════════════
1568
+ // Start TUI
1569
+ // ═══════════════════════════════════════════════════════════════════════════
1570
+
1571
+ tui.start();
1572
+
1573
+ // Load extensions in the background — fast startup, ready before first message.
1574
+ ensureExtensionsLoaded(config.extensions).catch(() => {});
1575
+
1576
+ // Initialize session store AFTER tui starts (bun:sqlite import must not run before pi-tui stdin setup)
1577
+ const {SessionStore} = await import('@pal/core');
1578
+ store = new SessionStore();
1579
+ store.init();
1580
+
1581
+ // Keep process alive — bun exits when async completes even with stdin in raw mode.
1582
+ // The noop interval forces bun to keep the event loop running.
1583
+ const _keepAlive = setInterval(() => {}, 60_000);
1584
+ process.on('exit', () => {
1585
+ clearInterval(_keepAlive);
1586
+ // Restore the terminal: leaving SGR mouse reporting on would make the
1587
+ // parent shell print raw mouse escape codes.
1588
+ disableMouse();
1589
+ });}
1590
+
1591
+ main().catch((err) => {
1592
+ // A startup failure (e.g. locked DB, broken import) after tui.start() leaves
1593
+ // the terminal in raw mode with SGR mouse reporting on. Restore both so the
1594
+ // parent shell remains usable.
1595
+ try {
1596
+ // 1. Disable SGR mouse reporting (?1000 and ?1006).
1597
+ process.stdout.write('\x1b[?1000l\x1b[?1006l');
1598
+ // 2. Restore cooked (normal) terminal mode — the inverse of raw mode.
1599
+ // This is the canonical way to undo process.stdin.setRawMode(true).
1600
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
1601
+ // 3. Show the cursor in case it was hidden.
1602
+ process.stdout.write('\x1b[?25h');
1603
+ } catch { /* best-effort — may crash again if stdin/stdout are gone */ }
1604
+ console.error(err);
1605
+ process.exit(1);
1606
+ });