pal-code 0.0.14 → 0.0.16

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.
@@ -25,8 +25,19 @@ import {
25
25
  TUI_KEYBINDINGS,
26
26
  detectCapabilities,
27
27
  } from '@earendil-works/pi-tui';
28
- import type {TUI} from '@earendil-works/pi-tui';
29
- import {c, editorTheme, agentColors, agentLabels, colorByName} from './theme.js';
28
+ import type {Component, TUI} from '@earendil-works/pi-tui';
29
+ import {
30
+ c,
31
+ surface,
32
+ editorTheme,
33
+ agentColors,
34
+ agentLabels,
35
+ colorByName,
36
+ setTheme,
37
+ activeTheme,
38
+ listThemes,
39
+ resolveTheme,
40
+ } from './theme.js';
30
41
  import {
31
42
  generateTitle,
32
43
  sanitizeTitle,
@@ -35,6 +46,8 @@ import {
35
46
  } from './utils/format.js';
36
47
  import {MessageBox} from './components/message-box.js';
37
48
  import {renderHistory} from './components/render-history.js';
49
+ import {AssistantBody} from './components/assistant-body.js';
50
+ import type {AssistantBlockHit} from './components/assistant-body.js';
38
51
  import {loadConfig} from './config.js';
39
52
  import {StatusLine} from './components/status-line.js';
40
53
  import {PermissionPrompt} from './components/permission-prompt.js';
@@ -56,7 +69,21 @@ import {
56
69
  } from './commands/update-check.js';
57
70
  import {showSessionSelector, cmdResume} from './overlays/session-picker.js';
58
71
  import {loadCostManifest, estimateCost, isPricedModel} from './utils/cost.js';
59
- import {buildOsc52Sequence, lastAssistantText, lastCodeBlock} from './utils/osc52.js';
72
+ import {
73
+ buildOsc22Pointer,
74
+ buildOsc52Sequence,
75
+ lastAssistantText,
76
+ lastCodeBlock,
77
+ } from './utils/osc52.js';
78
+ import {
79
+ buildCanvasQuery,
80
+ buildCanvasRestore,
81
+ buildOsc10Set,
82
+ buildOsc11Set,
83
+ parseCanvasReplies,
84
+ planCanvasSync,
85
+ } from './utils/osc-canvas.js';
86
+ import type {CanvasSync} from './utils/osc-canvas.js';
60
87
  import {openAgentsPanel, closeAgentsPanel} from './agent-panel.js';
61
88
  import {
62
89
  createOpenRouterProvider,
@@ -64,6 +91,7 @@ import {
64
91
  hasAnyKey,
65
92
  configPath,
66
93
  saveSetting,
94
+ readPalConfig,
67
95
  PROVIDERS,
68
96
  loadCustomProviders,
69
97
  providerForModel,
@@ -102,7 +130,27 @@ import type {SessionStore as SessionStoreType} from '@pal-code/core';
102
130
  // (see buildModelOptions). Static curated lists live in @pal-code/core PROVIDERS as fallback.
103
131
 
104
132
  // Version synced from version.json via `node scripts/sync-version.js`.
105
- const VERSION = '0.0.14';
133
+ const VERSION = '0.0.16';
134
+
135
+ // ── Canvas sync (OSC 10/11) ──
136
+ // Raw reply payloads captured after a successful startup query + set, or null
137
+ // when nothing was set (vanilla theme → empty plan, no reply → discarded).
138
+ // Module-level because both `main()`'s exit handler and `main().catch` below
139
+ // need it. restoreCanvas() is registered on those paths ONLY after a set —
140
+ // an empty plan never reaches it, so vanilla writes zero bytes end-to-end.
141
+ let savedCanvas: CanvasSync | null = null;
142
+
143
+ /**
144
+ * Re-emit the terminal's original default fg/bg, verbatim from the startup
145
+ * query replies. Idempotent (clears first) so the exit handler and the
146
+ * crash path can both call it; no-op when no set was ever performed.
147
+ */
148
+ function restoreCanvas(): void {
149
+ if (savedCanvas === null) return;
150
+ const restore = buildCanvasRestore(savedCanvas);
151
+ savedCanvas = null; // clear before writing so a throw can't double-emit
152
+ if (restore !== '') process.stdout.write(restore);
153
+ }
106
154
 
107
155
  import {showModelSelector} from './overlays/model-picker.js';
108
156
  import {showKeyInput} from './overlays/key-input.js';
@@ -130,6 +178,15 @@ async function main() {
130
178
 
131
179
  const config = loadConfig();
132
180
 
181
+ // Resolve the theme before any component or banner is constructed, so every
182
+ // palette read below uses it (PAL_THEME env wins over ~/.pal/config.json).
183
+ setTheme(resolveTheme(readPalConfig(), process.env.PAL_THEME));
184
+
185
+ // Canvas plan is pure and computed here, but the query itself runs at the
186
+ // end of main(): raw stdin only exists after tui.start(). An empty plan
187
+ // (vanilla-pi: window bg/fg '') skips the whole block — zero bytes.
188
+ const canvasPlan = planCanvasSync(activeTheme().surface.window);
189
+
133
190
  // Load any user-defined custom providers from ~/.pal/providers.json
134
191
  loadCustomProviders();
135
192
 
@@ -253,12 +310,16 @@ async function main() {
253
310
 
254
311
  // ── Components ──
255
312
  const messagesContainer = new Container();
313
+ // theme-captured at construction — applies on restart (Editor reads
314
+ // theme.borderColor once in its ctor; /theme mid-session won't repaint it)
256
315
  const editor = new Editor(tui, editorTheme);
257
316
  const statusLine = new StatusLine('');
258
317
  const permissionPrompt = new PermissionPrompt();
259
318
  state.permissionPrompt = permissionPrompt;
260
319
 
261
320
  // ── Banner ──
321
+ // theme-captured at construction — applies on restart (Text embeds the
322
+ // palette bytes; /theme mid-session leaves pre-existing transcript rows as-is)
262
323
  const resolvedBase = providerForModel(config.model, Object.keys(allKeys));
263
324
  const providerName = resolvedBase.provider.name;
264
325
  messagesContainer.addChild(new Text(`${c.bold}${c.cyan}pal v${VERSION}${c.reset}`, 1, 0));
@@ -320,6 +381,10 @@ async function main() {
320
381
  // The sidebar is a separate overlay and is never part of this column.
321
382
  let scrollOffset = 0;
322
383
 
384
+ // Status-line confirmation after a header copy click; cleared after 1500ms.
385
+ let copiedFlash = '';
386
+ let copiedFlashTimer: ReturnType<typeof setTimeout> | null = null;
387
+
323
388
  const pinnedLayout = {
324
389
  render(width: number): string[] {
325
390
  const inset = sidebarWidthFor(width);
@@ -398,23 +463,50 @@ async function main() {
398
463
  return v === '1' || v === 'true';
399
464
  })();
400
465
  let mouseEnabled = false;
466
+ // ── Hover state (Phase B) ──
467
+ // `mouseTracked` gates every hover path so PAL_NO_MOUSE never evaluates one;
468
+ // the (x, y) pair dedupes the full-transcript hit-test to cell changes.
469
+ type HoverTarget = {body: AssistantBody; segIndex: number};
470
+ let hoverTarget: HoverTarget | null = null;
471
+ let hoverPointer = false;
472
+ let lastMouseX = -1;
473
+ let lastMouseY = -1;
474
+ let mouseTracked = false;
401
475
  const enableMouse = (): void => {
402
476
  if (mouseEnabled || mouseDisabled) return;
403
477
  mouseEnabled = true;
404
- // ?1000h button events, ?1006h SGR extended coordinates.
405
- terminal.write('\x1b[?1000h\x1b[?1006h');
478
+ mouseTracked = true;
479
+ // ?1000h button events, ?1003h any-motion tracking (hover), ?1006h SGR
480
+ // extended coordinates.
481
+ terminal.write('\x1b[?1000h\x1b[?1003h\x1b[?1006h');
406
482
  };
407
483
  const disableMouse = (): void => {
408
484
  if (!mouseEnabled) return;
409
485
  mouseEnabled = false;
410
- terminal.write('\x1b[?1000l\x1b[?1006l');
486
+ mouseTracked = false;
487
+ clearHover();
488
+ terminal.write('\x1b[?1000l\x1b[?1003l\x1b[?1006l');
411
489
  };
412
490
 
491
+ // Success chip on the copied segment after a header click; cleared after 1500ms.
492
+ let successTimer: ReturnType<typeof setTimeout> | null = null;
493
+ // The body+segment currently showing the success chip (one owner at a time).
494
+ let successOwner: HoverTarget | null = null;
495
+
413
496
  const scrollBy = (delta: number): void => {
414
497
  const next = Math.max(0, scrollOffset + delta);
415
498
  if (next === scrollOffset) return;
416
499
  scrollOffset = next;
417
500
  updateStatusLine();
501
+ // The rows under a stationary pointer change when the window moves —
502
+ // re-run hover at the same cell (coords reset to defeat the dedupe).
503
+ if (mouseTracked && lastMouseX >= 0) {
504
+ const keepX = lastMouseX;
505
+ const keepY = lastMouseY;
506
+ lastMouseX = -1;
507
+ lastMouseY = -1;
508
+ evaluateHover(keepX, keepY);
509
+ }
418
510
  };
419
511
 
420
512
  const pageRows = (): number => {
@@ -422,19 +514,190 @@ async function main() {
422
514
  return Math.max(1, terminal.rows - editorLines - 2);
423
515
  };
424
516
 
517
+ // ── Code-block header copy (left-click on `⧉ copy`) ──
518
+ //
519
+ // Recompute the exact transcript window the renderer painted (same formula
520
+ // as pinnedLayout above), map the SGR click cell to a transcript row, then
521
+ // walk the render tree to the AssistantBody owning that row and hit-test
522
+ // its header copy zone. Every other click stays a no-op.
523
+ const sidebarBail = (): boolean =>
524
+ sidebarWidthFor(terminal.columns) > 0 &&
525
+ sidebar.render(SIDEBAR_WIDTH).length > Math.max(1, terminal.rows);
526
+
527
+ type CodeBlockHit = {
528
+ body: AssistantBody;
529
+ segIndex: number | null;
530
+ zone: {startCol: number; width: number} | null;
531
+ block: AssistantBlockHit;
532
+ };
533
+
534
+ const findAssistantBlock = (
535
+ node: Component,
536
+ width: number,
537
+ row: number,
538
+ ): {body: AssistantBody; localRow: number; block: AssistantBlockHit} | null => {
539
+ if (node instanceof AssistantBody) {
540
+ const block = node.blockAt(width, row);
541
+ return block ? {body: node, localRow: row, block} : null;
542
+ }
543
+ if (node instanceof Container) {
544
+ let acc = 0;
545
+ for (const child of node.children) {
546
+ const h = child.render(width).length;
547
+ if (row >= acc && row < acc + h) return findAssistantBlock(child, width, row - acc);
548
+ acc += h;
549
+ }
550
+ }
551
+ return null;
552
+ };
553
+
554
+ // Pure layout math + tree walk: maps a 1-based SGR cell to the code block
555
+ // under it. Callers flush the frame first so the y → row mapping matches
556
+ // what is painted — this must not repaint itself (hover runs it per motion).
557
+ const findCodeBlockAt = (_x: number, y: number): CodeBlockHit | null => {
558
+ const contentW = Math.max(1, terminal.columns - sidebarWidthFor(terminal.columns));
559
+ const transcript = messagesContainer.render(contentW);
560
+ const editorH = editorRow.render(contentW).length;
561
+ const statusH = statusLine.render(contentW).length;
562
+ const total = Math.max(1, terminal.rows);
563
+ const viewport = Math.max(1, total - editorH - statusH);
564
+ const off = Math.min(scrollOffset, Math.max(0, transcript.length - viewport));
565
+ const end = transcript.length - off;
566
+ const start = Math.max(0, end - viewport);
567
+ const winLen = end - start;
568
+ const padTop = Math.max(0, viewport - winLen);
569
+
570
+ // SGR coordinates are 1-based; the layout pads the window above.
571
+ const windowIdx = y - 1 - padTop;
572
+ if (windowIdx < 0 || windowIdx >= winLen) return null;
573
+ const found = findAssistantBlock(messagesContainer, contentW, start + windowIdx);
574
+ if (!found) return null;
575
+ return {
576
+ body: found.body,
577
+ segIndex: found.body.blockIndexAt(contentW, found.localRow),
578
+ zone: found.block.zone,
579
+ block: found.block,
580
+ };
581
+ };
582
+
583
+ const handleCopyClick = (x: number, y: number): void => {
584
+ // Flush any pending frame so the row mapping matches what is painted.
585
+ tui.renderNow();
586
+ // A sidebar taller than the viewport overlays transcript rows and breaks
587
+ // the y → row mapping — bail rather than copy the wrong block.
588
+ if (sidebarBail()) return;
589
+
590
+ const hit = findCodeBlockAt(x, y);
591
+ if (!hit?.zone || hit.segIndex === null) return;
592
+ const col = x - 1;
593
+ if (col < hit.zone.startCol || col >= hit.zone.startCol + hit.zone.width) return;
594
+
595
+ // Same mechanism as /copy: OSC 52 through pi-tui's writer.
596
+ tui.terminal.write(buildOsc52Sequence(hit.block.code));
597
+ flashCopied(hit.block.code.length);
598
+
599
+ // Success chip on the owning segment (Phase B). Only one body shows it:
600
+ // clear the previous owner before arming this one.
601
+ const prevOwner = successOwner;
602
+ successOwner = {body: hit.body, segIndex: hit.segIndex};
603
+ if (prevOwner && prevOwner.body !== hit.body && prevOwner.body.setSuccess(null)) {
604
+ tui.renderNow();
605
+ }
606
+ if (hit.body.setSuccess(hit.segIndex)) tui.renderNow();
607
+ if (successTimer !== null) clearTimeout(successTimer);
608
+ successTimer = setTimeout(() => {
609
+ successTimer = null;
610
+ if (successOwner?.body === hit.body && successOwner.segIndex === hit.segIndex) {
611
+ successOwner = null;
612
+ }
613
+ if (hit.body.setSuccess(null)) tui.renderNow();
614
+ }, 1500);
615
+ };
616
+
617
+ // ── Hover: pointer over a copy zone → highlight + finger cursor ──
618
+ // Deduped to cell changes — findCodeBlockAt is a full-transcript render.
619
+ function evaluateHover(x: number, y: number): void {
620
+ if (!mouseTracked) return;
621
+ if (sidebarBail()) return;
622
+ if (x === lastMouseX && y === lastMouseY) return;
623
+ lastMouseX = x;
624
+ lastMouseY = y;
625
+ tui.renderNow();
626
+ const hit = findCodeBlockAt(x, y);
627
+ let newTarget: HoverTarget | null = null;
628
+ if (hit?.zone && hit.segIndex !== null) {
629
+ const col = x - 1;
630
+ if (col >= hit.zone.startCol && col < hit.zone.startCol + hit.zone.width) {
631
+ newTarget = {body: hit.body, segIndex: hit.segIndex};
632
+ }
633
+ }
634
+ const prev = hoverTarget;
635
+ const sameTarget =
636
+ prev !== null &&
637
+ newTarget !== null &&
638
+ prev.body === newTarget.body &&
639
+ prev.segIndex === newTarget.segIndex;
640
+ if (sameTarget) return;
641
+ const oldChanged = prev ? prev.body.setHovered(null) : false;
642
+ const newChanged = newTarget ? newTarget.body.setHovered(newTarget.segIndex) : false;
643
+ hoverTarget = newTarget;
644
+ const pointerOn = newTarget !== null;
645
+ if (pointerOn !== hoverPointer) {
646
+ hoverPointer = pointerOn;
647
+ tui.terminal.write(buildOsc22Pointer(pointerOn));
648
+ }
649
+ if (oldChanged || newChanged) tui.renderNow();
650
+ }
651
+
652
+ // Mouse disable/shutdown: drop the highlight and restore the default cursor.
653
+ function clearHover(): void {
654
+ const prev = hoverTarget;
655
+ hoverTarget = null;
656
+ const changed = prev ? prev.body.setHovered(null) : false;
657
+ if (hoverPointer) {
658
+ hoverPointer = false;
659
+ tui.terminal.write(buildOsc22Pointer(false));
660
+ }
661
+ lastMouseX = -1;
662
+ lastMouseY = -1;
663
+ if (changed) tui.renderNow();
664
+ }
665
+
425
666
  tui.addInputListener((data) => {
426
667
  // SGR mouse: ESC [ < b ; x ; y M|m (preferred, enabled via ?1006h)
427
- const mouse = data.startsWith('\x1b[<') ? data.slice(3).match(/^(\d+);\d+;\d+[Mm]$/) : null;
668
+ const mouse = data.startsWith('\x1b[<')
669
+ ? data.slice(3).match(/^(\d+);(\d+);(\d+)([Mm])$/)
670
+ : null;
428
671
  if (mouse) {
429
- const btn = Number(mouse[1]) & 0xff;
430
- if (btn === 64) {
672
+ const raw = Number(mouse[1]);
673
+ const x = Number(mouse[2]);
674
+ const y = Number(mouse[3]);
675
+ const isRelease = mouse[4] === 'm';
676
+ // Wheel: bit 6 set; low 2 bits pick the direction (0 up, 1 down).
677
+ // Bit-mask decode keeps modifier+wheel working (Shift+wheel arrives as
678
+ // 64|4 / 65|4 and would miss an exact `btn === 64/65` comparison).
679
+ if ((raw & 64) !== 0 && (raw & 3) === 0) {
431
680
  scrollBy(3); // wheel up
432
681
  return {consume: true};
433
682
  }
434
- if (btn === 65) {
683
+ if ((raw & 64) !== 0 && (raw & 3) === 1) {
435
684
  scrollBy(-3); // wheel down
436
685
  return {consume: true};
437
686
  }
687
+ // Pointer-motion reports (?1003h): motion bit set, wheel clear — track
688
+ // hover. The release char is ignored: motion arrives as M or m
689
+ // depending on whether a button is held during the move.
690
+ if ((raw & 32) !== 0 && (raw & 64) === 0) {
691
+ evaluateHover(x, y);
692
+ return {consume: true};
693
+ }
694
+ // Left-button press without drag/wheel bits → header copy-zone test;
695
+ // the handler itself is a no-op outside a zone. Drag bit (32) excluded
696
+ // so a future drag-select never fires a copy.
697
+ if (!isRelease && (raw & 64) === 0 && (raw & 32) === 0 && (raw & 3) === 0) {
698
+ handleCopyClick(x, y);
699
+ return {consume: true};
700
+ }
438
701
  return {consume: true}; // swallow other mouse events
439
702
  }
440
703
  // Legacy X10 mouse: ESC [ M followed by three bytes; button code is the
@@ -531,6 +794,7 @@ async function main() {
531
794
  {name: 'resume', description: 'Load a previous session'},
532
795
  {name: 'cost', description: 'Show token usage and cost'},
533
796
  {name: 'model', description: 'Switch model'},
797
+ {name: 'theme', description: 'Switch color theme (vanilla-pi, github-dark)'},
534
798
  {name: 'ext', description: 'Manage extensions'},
535
799
  {name: 'export', description: 'Export config to a versionable JSON file'},
536
800
  {name: 'import', description: 'Import config from an export file'},
@@ -559,11 +823,11 @@ async function main() {
559
823
  // Background sub-agents (ctrl+b opens the panel).
560
824
  const running = state.backgroundAgents.filter((a) => a.status === 'running').length;
561
825
  const agentStr = state.backgroundAgents.length
562
- ? ` ${c.yellow}⛭ ${running}/${state.backgroundAgents.length} agents${c.reset}`
826
+ ? ` ${surface.statusLine.warn}⛭ ${running}/${state.backgroundAgents.length} agents${c.reset}`
563
827
  : '';
564
828
  const sub = getSubagentStatus();
565
829
  const subLine = subagentStatusText(sub.active, sub.startedAt);
566
- const subStr = subLine ? ` ${c.yellow}${subLine}${c.reset}` : '';
830
+ const subStr = subLine ? ` ${surface.statusLine.warn}${subLine}${c.reset}` : '';
567
831
  // The status line now only carries identity/nav; token, cost and context
568
832
  // usage live in the sidebar's Info block.
569
833
  //
@@ -571,23 +835,26 @@ async function main() {
571
835
  // while the centered modal (PermissionPrompt) handles the full prompt.
572
836
  if (state.overlayMode === 'permission' && state.pendingPermission) {
573
837
  statusLine.setText(
574
- `${c.yellow}🔒 Awaiting permission...${c.reset} ${c.dim}[y/a/n/Esc]${c.reset}`,
838
+ `${surface.statusLine.warn}🔒 Awaiting permission...${c.reset} ${c.dim}[y/a/n/Esc]${c.reset}`,
575
839
  );
576
840
  } else if (scrollOffset > 0) {
577
841
  // Scrolled back through the transcript — surface the way out so the
578
842
  // user isn't stranded in scroll mode.
579
843
  statusLine.setText(
580
- `${c.cyan}↕ scrolled${c.reset} ${c.dim}· PgDn/↓ End or Esc to resume${c.reset}`,
844
+ `${surface.statusLine.info}↕ scrolled${c.reset} ${c.dim}· PgDn/↓ End or Esc to resume${c.reset}`,
581
845
  );
582
846
  } else {
583
847
  // `queued (N)` — messages submitted while a turn runs (drained on
584
848
  // settle). Empty at N=0, so the idle status line stays byte-identical.
585
849
  const queuedText = queuedStatusText(state.pendingMessages.length);
586
- const queuedStr = queuedText ? ` ${c.yellow}${queuedText}${c.reset}` : '';
850
+ const queuedStr = queuedText ? ` ${surface.statusLine.warn}${queuedText}${c.reset}` : '';
587
851
  statusLine.setText(
588
- `${modelShort} ${c.dim}${providerName}${agentStr}${subStr}${queuedStr}${c.reset} ${c.dim}/help${c.reset}`,
852
+ `${modelShort} ${surface.statusLine.dim}${providerName}${agentStr}${subStr}${queuedStr}${c.reset} ${surface.statusLine.dim}/help${c.reset}`,
589
853
  );
590
854
  }
855
+ // A copy flash outranks every other status for its 1500ms window, so a
856
+ // streaming repaint (which re-runs this function) can't clobber it.
857
+ if (copiedFlash) statusLine.setText(copiedFlash);
591
858
  sidebar.setStats({
592
859
  inputTokens: state.sessionTokenomics.inputTokens,
593
860
  outputTokens: state.sessionTokenomics.outputTokens,
@@ -598,6 +865,19 @@ async function main() {
598
865
  });
599
866
  tui.requestRender();
600
867
  }
868
+
869
+ /** Green status-line confirmation after a header copy click (1500ms). */
870
+ function flashCopied(count: number): void {
871
+ copiedFlash = `${surface.statusLine.flash} ✓ copied ${count} chars${c.reset}`;
872
+ updateStatusLine();
873
+ if (copiedFlashTimer !== null) clearTimeout(copiedFlashTimer);
874
+ copiedFlashTimer = setTimeout(() => {
875
+ copiedFlash = '';
876
+ copiedFlashTimer = null;
877
+ updateStatusLine();
878
+ }, 1500);
879
+ }
880
+
601
881
  // Expose to module-level overlay handlers (model picker, agent panel).
602
882
  state.refreshStatusLine = updateStatusLine;
603
883
  state.refreshSidebar = () => sidebar.refresh();
@@ -1325,6 +1605,50 @@ async function main() {
1325
1605
  cmdCost(tok.inputTokens, tok.outputTokens, tok.cost, config.model, messagesContainer, tui);
1326
1606
  return;
1327
1607
  }
1608
+ if (trimmed === '/theme') {
1609
+ const active = activeTheme();
1610
+ const lines = listThemes().map((name) =>
1611
+ name === active.name
1612
+ ? `${c.green} ● ${name}${c.reset} ${c.dim}(active)${c.reset}`
1613
+ : ` ${c.dim}○ ${name}${c.reset}`,
1614
+ );
1615
+ messagesContainer.addChild(
1616
+ new Text(
1617
+ `${c.bold}Theme:${c.reset} ${active.displayName} ${c.dim}(${active.name})${c.reset}\n` +
1618
+ `${lines.join('\n')}\n${c.dim}Switch with /theme <name>.${c.reset}`,
1619
+ 1,
1620
+ 0,
1621
+ ),
1622
+ );
1623
+ tui.requestRender();
1624
+ return;
1625
+ }
1626
+ if (trimmed.startsWith('/theme ')) {
1627
+ const name = trimmed.slice('/theme '.length).trim();
1628
+ if (!setTheme(name)) {
1629
+ messagesContainer.addChild(
1630
+ new Text(
1631
+ `${c.red} Unknown theme: ${name}${c.reset} ` +
1632
+ `${c.dim}(${listThemes().join(', ')})${c.reset}`,
1633
+ 1,
1634
+ 0,
1635
+ ),
1636
+ );
1637
+ tui.requestRender();
1638
+ return;
1639
+ }
1640
+ saveSetting('theme', name);
1641
+ messagesContainer.addChild(new Text(`${c.green} ✓ theme: ${name} (saved)${c.reset}`, 1, 0));
1642
+ // Same repaint path as /model NAME (refresh status + requestRender),
1643
+ // plus container invalidation so render-time components (markdown,
1644
+ // sidebar) repaint from source with the new palette.
1645
+ messagesContainer.invalidate();
1646
+ editorRow.invalidate();
1647
+ state.refreshStatusLine();
1648
+ refreshSidebar();
1649
+ tui.requestRender();
1650
+ return;
1651
+ }
1328
1652
  if (trimmed === '/model' || trimmed === '/model ') {
1329
1653
  void showModelSelector(
1330
1654
  config,
@@ -1718,6 +2042,8 @@ async function main() {
1718
2042
  // in the same submission instead of stopping and waiting for "go".
1719
2043
  // Single-shot: a plan→execute→plan→execute chain within one message is
1720
2044
  // refused by the `autoExecuted` guard above.
2045
+ // The execution-mode re-assertion exists because the plan-mode switch's
2046
+ // stop notice was the last turn-ending guidance the model saw.
1721
2047
  if (pendingExecution && !autoExecuted) {
1722
2048
  autoExecuted = true;
1723
2049
  pendingExecution = false;
@@ -1727,7 +2053,10 @@ async function main() {
1727
2053
  tui.requestRender();
1728
2054
  await runTurn(
1729
2055
  'Your plan above is approved. Implement it now, following that plan. ' +
1730
- 'Do not enter plan mode again for this task — carry it through to completion.',
2056
+ 'Do not enter plan mode again for this task — carry it through to completion. ' +
2057
+ 'You are now in execution mode. Work through the plan by calling tools until it is ' +
2058
+ 'fully implemented — never end a turn with prose describing what you will do next; ' +
2059
+ 'a turn may only end in prose when everything is done or a genuine question for the user.',
1731
2060
  );
1732
2061
  }
1733
2062
 
@@ -1790,7 +2119,77 @@ async function main() {
1790
2119
  // Restore the terminal: leaving SGR mouse reporting on would make the
1791
2120
  // parent shell print raw mouse escape codes.
1792
2121
  disableMouse();
2122
+ // Restore the terminal's own default fg/bg if startup canvas sync set
2123
+ // them (no-op when savedCanvas is null — vanilla / no-reply paths).
2124
+ restoreCanvas();
1793
2125
  });
2126
+
2127
+ // ── Canvas sync (OSC 10/11) ──
2128
+ // Runs after tui.start() (raw stdin only exists now) and after the exit
2129
+ // handler registration above, so every set has a restore path from the
2130
+ // moment it is written. Replies are harvested by a temporary input listener
2131
+ // on pi-tui's normal pipeline (StdinBuffer emits whole escape sequences) —
2132
+ // stdin is never intercepted, so keystrokes during the window flow to the
2133
+ // regular listeners untouched and no drain buffer is needed.
2134
+ if (canvasPlan.fg !== undefined || canvasPlan.bg !== undefined) {
2135
+ let replyBytes = '';
2136
+ let settled = false;
2137
+ let timer: ReturnType<typeof setTimeout> | undefined;
2138
+ let finish: (() => void) | undefined;
2139
+
2140
+ const unsubscribe = tui.addInputListener((data: string) => {
2141
+ // A reply event starts with OSC 10/11; a continuation event completes a
2142
+ // reply StdinBuffer flushed mid-sequence (endsWith checks the tail only,
2143
+ // so an already-terminated capture stops matching).
2144
+ const pending =
2145
+ replyBytes !== '' && !replyBytes.endsWith('\x07') && !replyBytes.endsWith('\x1b\\');
2146
+ if (!pending && !data.startsWith('\x1b]10;') && !data.startsWith('\x1b]11;')) {
2147
+ return undefined;
2148
+ }
2149
+ replyBytes += data;
2150
+ const replies = parseCanvasReplies(replyBytes);
2151
+ const fgDone = canvasPlan.fg === undefined || replies.fg !== undefined;
2152
+ const bgDone = canvasPlan.bg === undefined || replies.bg !== undefined;
2153
+ if (fgDone && bgDone) finish?.(); // both planned channels answered — skip the rest of the timeout
2154
+ return {consume: true}; // replies never reach the editor
2155
+ });
2156
+
2157
+ await new Promise<void>((resolve) => {
2158
+ finish = () => {
2159
+ if (settled) return;
2160
+ settled = true;
2161
+ if (timer !== undefined) clearTimeout(timer);
2162
+ resolve();
2163
+ };
2164
+ timer = setTimeout(() => {
2165
+ // No usable reply within the single 300ms budget (both channels share
2166
+ // it): replyBytes is discarded below — no set, no restore.
2167
+ finish?.();
2168
+ }, 300);
2169
+ tui.terminal.write(buildCanvasQuery());
2170
+ });
2171
+ unsubscribe();
2172
+ finish = undefined;
2173
+
2174
+ // Set only channels present in BOTH the plan and the reply; the raw reply
2175
+ // payload is what we restore verbatim on exit.
2176
+ const replies = parseCanvasReplies(replyBytes);
2177
+ replyBytes = ''; // explicit discard — the parse above is the only consumer
2178
+ const sets: string[] = [];
2179
+ const saved: CanvasSync = {};
2180
+ if (canvasPlan.fg !== undefined && replies.fg !== undefined) {
2181
+ sets.push(buildOsc10Set(canvasPlan.fg));
2182
+ saved.fg = replies.fg;
2183
+ }
2184
+ if (canvasPlan.bg !== undefined && replies.bg !== undefined) {
2185
+ sets.push(buildOsc11Set(canvasPlan.bg));
2186
+ saved.bg = replies.bg;
2187
+ }
2188
+ if (sets.length > 0) {
2189
+ savedCanvas = saved;
2190
+ tui.terminal.write(sets.join(''));
2191
+ }
2192
+ }
1794
2193
  }
1795
2194
 
1796
2195
  main().catch((err) => {
@@ -1798,8 +2197,12 @@ main().catch((err) => {
1798
2197
  // the terminal in raw mode with SGR mouse reporting on. Restore both so the
1799
2198
  // parent shell remains usable.
1800
2199
  try {
1801
- // 1. Disable SGR mouse reporting (?1000 and ?1006).
1802
- process.stdout.write('\x1b[?1000l\x1b[?1006l');
2200
+ // 1. Disable SGR mouse reporting (?1000, ?1003 motion, ?1006).
2201
+ process.stdout.write('\x1b[?1000l\x1b[?1003l\x1b[?1006l');
2202
+ // 2. Restore the default cursor if a hover left the finger pointer on.
2203
+ process.stdout.write(buildOsc22Pointer(false));
2204
+ // Restore the terminal's original default fg/bg if canvas sync set them.
2205
+ restoreCanvas();
1803
2206
  // 2. Restore cooked (normal) terminal mode — the inverse of raw mode.
1804
2207
  // This is the canonical way to undo process.stdin.setRawMode(true).
1805
2208
  if (process.stdin.isTTY) process.stdin.setRawMode(false);
@@ -5,7 +5,7 @@ import type {TUI, Container, Editor, SelectItem} from '@earendil-works/pi-tui';
5
5
  import {PROVIDERS, resolveModelIds, saveSetting} from '@pal-code/core';
6
6
  import type {Provider, ProviderKeys} from '@pal-code/core';
7
7
 
8
- import {c} from '../theme.js';
8
+ import {c, surface} from '../theme.js';
9
9
  import {state} from '../state.js';
10
10
 
11
11
  /**
@@ -63,11 +63,11 @@ export async function showModelSelector(
63
63
  const options = await buildModelOptions(allKeys);
64
64
 
65
65
  const selectList = new SelectList(options, 14, {
66
- selectedPrefix: (_text: string) => `${c.cyan}> ${c.reset}`,
67
- selectedText: (text: string) => `${c.bold}${text}${c.reset}`,
68
- description: (text: string) => `${c.dim}${text}${c.reset}`,
69
- scrollInfo: (text: string) => `${c.dim}${text}${c.reset}`,
70
- noMatch: (text: string) => `${c.dim}${text}${c.reset}`,
66
+ selectedPrefix: (_text: string) => `${surface.overlay.selectedPrefix}> ${c.reset}`,
67
+ selectedText: (text: string) => `${surface.overlay.selectedText}${text}${c.reset}`,
68
+ description: (text: string) => `${surface.overlay.description}${text}${c.reset}`,
69
+ scrollInfo: (text: string) => `${surface.overlay.scrollInfo}${text}${c.reset}`,
70
+ noMatch: (text: string) => `${surface.overlay.noMatch}${text}${c.reset}`,
71
71
  });
72
72
 
73
73
  // Highlight the current model
@@ -8,7 +8,7 @@
8
8
  import {Text, SelectList} from '@earendil-works/pi-tui';
9
9
  import type {TUI, Container, Editor, SelectItem} from '@earendil-works/pi-tui';
10
10
 
11
- import {c} from '../theme.js';
11
+ import {c, surface} from '../theme.js';
12
12
  import {truncate} from '../utils/format.js';
13
13
  import type {ConversationMessage as Message, Session, SessionStore} from '@pal-code/core';
14
14
 
@@ -72,11 +72,11 @@ export function showSessionSelector(
72
72
  }
73
73
 
74
74
  const selectList = new SelectList(items, 12, {
75
- selectedPrefix: (_text: string) => `${c.cyan}> ${c.reset}`,
76
- selectedText: (text: string) => `${c.bold}${text}${c.reset}`,
77
- description: (text: string) => ` ${c.dim}${text}${c.reset}`,
78
- scrollInfo: (text: string) => `${c.dim}${text}${c.reset}`,
79
- noMatch: (_text: string) => `${c.dim} No matching sessions.${c.reset}`,
75
+ selectedPrefix: (_text: string) => `${surface.overlay.selectedPrefix}> ${c.reset}`,
76
+ selectedText: (text: string) => `${surface.overlay.selectedText}${text}${c.reset}`,
77
+ description: (text: string) => ` ${surface.overlay.description}${text}${c.reset}`,
78
+ scrollInfo: (text: string) => `${surface.overlay.scrollInfo}${text}${c.reset}`,
79
+ noMatch: (_text: string) => `${surface.overlay.noMatch} No matching sessions.${c.reset}`,
80
80
  });
81
81
 
82
82
  const label = new Text(