pal-code 0.0.21 → 0.0.23

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.
@@ -38,6 +38,17 @@ import {MessageBox} from './components/message-box.js';
38
38
  import {renderHistory} from './components/render-history.js';
39
39
  import {AssistantBody} from './components/assistant-body.js';
40
40
  import type {AssistantBlockHit} from './components/assistant-body.js';
41
+ import {
42
+ type SelectionPoint,
43
+ type SelectionRange,
44
+ clampRowIntoWindow,
45
+ dragEdgeFor,
46
+ extractSelection,
47
+ highlightSpan,
48
+ isEmptySelection,
49
+ normalizeSelection,
50
+ wordRangeAt,
51
+ } from './tui/selection.js';
41
52
  import {loadConfig} from './config.js';
42
53
  import {StatusLine} from './components/status-line.js';
43
54
  import {PermissionPrompt} from './components/permission-prompt.js';
@@ -45,12 +56,22 @@ import {
45
56
  dequeueMessage,
46
57
  enqueueMessage,
47
58
  nextEscAction,
59
+ nextExitAction,
48
60
  queuedStatusText,
49
61
  resetSessionTokenomics,
50
62
  setSessionTokenomics,
51
63
  state,
52
64
  } from './state.js';
53
65
  import {Sidebar} from './components/sidebar.js';
66
+ import {
67
+ APPROVAL_PROMPT,
68
+ approvalKeyDecision,
69
+ approvalPromptText,
70
+ resolveApprovalTimeoutSeconds,
71
+ shouldAutoApprove,
72
+ shouldFireOnSettle,
73
+ tickApproval,
74
+ } from './approval-gate.js';
54
75
  import {cmdHelp, cmdCost} from './commands.js';
55
76
  import {autocompleteItems} from './slash-commands.js';
56
77
  import {
@@ -66,6 +87,7 @@ import {
66
87
  registerModelPricing,
67
88
  resolveTurnCost,
68
89
  } from './utils/cost.js';
90
+ import {resetProviderSession, DEFAULT_REASONING_EFFORT} from '@pal-code/core';
69
91
  import {
70
92
  buildOsc22Pointer,
71
93
  buildOsc52Sequence,
@@ -107,6 +129,8 @@ import {
107
129
  pickCheapModel,
108
130
  deriveMessageMeta,
109
131
  estimateMessagesTokens,
132
+ fixedPromptTokens,
133
+ estimateToolSchemaTokens,
110
134
  restoreSnapshot,
111
135
  listSnapshots,
112
136
  onAgentEvent,
@@ -134,7 +158,7 @@ import type {SessionStore as SessionStoreType} from '@pal-code/core';
134
158
  // (see buildModelOptions). Static curated lists live in @pal-code/core PROVIDERS as fallback.
135
159
 
136
160
  // Version synced from version.json via `node scripts/sync-version.js`.
137
- const VERSION = '0.0.21';
161
+ const VERSION = '0.0.23';
138
162
 
139
163
  // ── Canvas sync (OSC 10/11) ──
140
164
  // Raw reply payloads captured after a successful startup query + set, or null
@@ -167,6 +191,7 @@ import {
167
191
  runTurn as runAgentTurn,
168
192
  } from '@pal-code/core';
169
193
  import {approveTool, createTuiAgentUi} from './agent-ui.js';
194
+ import {linesOf, parseHeadlessArgs, runPrint, runRpc} from './headless.js';
170
195
  import {settledStatus} from './utils/osc-status.js';
171
196
  import {createStatusReporter} from './utils/status-report.js';
172
197
 
@@ -330,10 +355,18 @@ async function main() {
330
355
  console.log(result.message);
331
356
  process.exit(result.ok ? 0 : 1);
332
357
  }
358
+ // ── Headless front-ends ──
359
+ // `-p` and `--mode rpc` are additional adapters over the same core, not a
360
+ // variant of the TUI. Detected here (before the BYOK gate) so the interactive
361
+ // setup wizard is never launched for a non-interactive run; executed further
362
+ // down, once the provider factory exists. Nothing below that point has to
363
+ // know headless mode exists.
364
+ const headless = parseHeadlessArgs(process.argv.slice(2));
365
+
333
366
  // ── BYOK gate: force setup when no key is configured ──
334
367
  let allKeys = resolveAllKeys();
335
368
  const forceSetup = process.argv.includes('--setup') || process.argv.includes('--login');
336
- if (forceSetup || !hasAnyKey(allKeys)) {
369
+ if (headless === null && (forceSetup || !hasAnyKey(allKeys))) {
337
370
  const ok = await runSetupWizard();
338
371
  process.stdin.removeAllListeners('data');
339
372
  process.stdin.pause();
@@ -397,6 +430,48 @@ async function main() {
397
430
  }
398
431
 
399
432
  const providerRef = {current: createProvider(config.model)};
433
+
434
+ // ── Headless execution ──
435
+ // Reached only when `-p` / `--mode rpc` was parsed above. The active model is
436
+ // already validated against configured keys, so a headless run fails with a
437
+ // normal provider error rather than the interactive wizard.
438
+ if (headless !== null) {
439
+ const ctx = {settings: config, keys: allKeys, createProvider};
440
+ const writeOut = (s: string): void => {
441
+ process.stdout.write(s);
442
+ };
443
+ const writeErr = (s: string): void => {
444
+ process.stderr.write(s);
445
+ };
446
+ const onSigint = (): void => {
447
+ process.exit(130);
448
+ };
449
+ process.once('SIGINT', onSigint);
450
+
451
+ if (headless.mode === 'print' && !headless.prompt) {
452
+ writeErr('pal: -p needs a prompt\ntry: pal -p "explain the build script"\n');
453
+ process.exit(1);
454
+ }
455
+
456
+ try {
457
+ const code =
458
+ headless.mode === 'rpc'
459
+ ? await runRpc(ctx, headless, {
460
+ stdout: writeOut,
461
+ stderr: writeErr,
462
+ stdin: linesOf(process.stdin as AsyncIterable<Uint8Array>),
463
+ })
464
+ : await runPrint(headless.prompt, ctx, headless, {
465
+ stdout: writeOut,
466
+ stderr: writeErr,
467
+ });
468
+ process.exit(code);
469
+ } catch (err) {
470
+ writeErr(`pal: ${err instanceof Error ? err.message : String(err)}\n`);
471
+ process.exit(1);
472
+ }
473
+ }
474
+
400
475
  await providerRef.current.init();
401
476
  syncModelPricing(providerRef.current);
402
477
 
@@ -499,6 +574,16 @@ async function main() {
499
574
  const agentUi = createTuiAgentUi(tui, messagesContainer);
500
575
 
501
576
  const sidebar = new Sidebar();
577
+ sidebar.setVersion(VERSION);
578
+ // Row budget for the sticky footer: the overlay owns the right-hand columns
579
+ // for the whole screen height (the main column stops at `columns - width`),
580
+ // so the footer's row is simply the last screen row.
581
+ sidebar.setViewportRows(terminal.rows);
582
+ tui.addInputListener(() => {
583
+ // A terminal resize changes the footer's row. Cheap no-op when unchanged.
584
+ sidebar.setViewportRows(terminal.rows);
585
+ return undefined;
586
+ });
502
587
  // Fixed sidebar width used by both the overlay compositor and the transcript
503
588
  // layout. Both must agree — if the layout reserves N columns but the overlay
504
589
  // paints at M ≠ N, the sidebar overpaints transcript content.
@@ -523,6 +608,43 @@ async function main() {
523
608
  let copiedFlash = '';
524
609
  let copiedFlashTimer: ReturnType<typeof setTimeout> | null = null;
525
610
 
611
+ // ── Drag-selection state ──
612
+ //
613
+ // Points are kept in TRANSCRIPT space (absolute rendered row), not screen
614
+ // space, so the highlight follows the text when the window scrolls instead of
615
+ // sliding over whatever is now under the same screen cell. `selectionCols`
616
+ // clamps columns to the transcript (never the sidebar overlay) — that clamp
617
+ // is the whole point: it is what keeps overlay glyphs and the row padding out
618
+ // of the copy.
619
+ let selectionAnchor: SelectionPoint | null = null;
620
+ let selectionFocus: SelectionPoint | null = null;
621
+ let dragging = false;
622
+
623
+ // Drag-scroll state lives here with the rest of the selection state, not next
624
+ // to the functions that use it: `clearSelection` and `disableMouse` are both
625
+ // declared ABOVE those functions and call `stopDragScroll`, so a `let` further
626
+ // down would be in the temporal dead zone on an early call path.
627
+ const DRAG_SCROLL_INTERVAL_MS = 60;
628
+ let dragScrollTimer: ReturnType<typeof setInterval> | null = null;
629
+ let dragEdge: -1 | 0 | 1 = 0;
630
+
631
+ const selectionRange = (): SelectionRange | null =>
632
+ normalizeSelection(selectionAnchor, selectionFocus);
633
+
634
+ const clearSelection = (repaint = true): void => {
635
+ if (selectionAnchor === null && selectionFocus === null) return;
636
+ selectionAnchor = null;
637
+ selectionFocus = null;
638
+ dragging = false;
639
+ stopDragScroll();
640
+ if (repaint) {
641
+ // The status line carries the "selection pending" hint, so it has to be
642
+ // refreshed whenever the selection goes away — not just repainted.
643
+ updateStatusLine();
644
+ tui.renderNow();
645
+ }
646
+ };
647
+
526
648
  const pinnedLayout = {
527
649
  render(width: number): string[] {
528
650
  const inset = sidebarWidthFor(width);
@@ -549,7 +671,21 @@ async function main() {
549
671
  const padTop = Math.max(0, viewport - window.length);
550
672
  const out: string[] = [];
551
673
  for (let i = 0; i < padTop; i++) out.push('');
552
- out.push(...window);
674
+ // Paint the selection onto the rows it actually covers. `window[i]` is
675
+ // transcript row `start + i`, and only rows inside that window can be
676
+ // highlighted — a selection anchored above the window is simply clipped.
677
+ const range = selectionRange();
678
+ const painted =
679
+ range === null
680
+ ? window
681
+ : window.map((line, i) => {
682
+ const row = start + i;
683
+ if (row < range.first.row || row > range.last.row) return line;
684
+ const from = row === range.first.row ? range.first.col : 0;
685
+ const to = row === range.last.row ? range.last.col : contentW;
686
+ return highlightSpan(line, from, to);
687
+ });
688
+ out.push(...painted);
553
689
  out.push(...editorLines, ...statusLines);
554
690
  return out;
555
691
  },
@@ -576,16 +712,22 @@ async function main() {
576
712
  //
577
713
  // Dispatch order in pi-tui: input listeners run BEFORE the focused editor.
578
714
  // So we must not blindly consume Up/Down/Home/End — those belong to the
579
- // editor for cursor movement. Instead there are two tiers:
715
+ // editor for cursor movement. The split is by MODIFIER instead:
580
716
  //
581
- // • Always-on keys (editor never needs them): PageUp/PageDown, Ctrl+Home,
582
- // Ctrl+End, and the mouse wheel.
583
- // • Scroll-mode keys: plain ↑/↓/Home/End (and Shift/Alt variants) only
584
- // apply once the user is scrolled away from the tail. Exiting scroll mode
585
- // (Esc, End, or simply typing) hands the keys back to the editor.
717
+ // • Shift+↑/↓/Home/End/PgUp/PgDn scroll the transcript, from any position
718
+ // (not only while already scrolled), and are always consumed.
719
+ // • Plain ↑/↓/Home/End always belong to the editor — no mode to exit.
720
+ // • PgUp/PgDn, Ctrl+Home, Ctrl+End and the mouse wheel are editor-neutral,
721
+ // so they scroll unmodified too.
586
722
  //
587
- // This mirrors how `less`/`git log` pagers behave, so typing is never
588
- // hijacked and the broken-wheel user can drive everything from the keyboard.
723
+ // Shift is deliberately the scroll modifier rather than the copy modifier:
724
+ // the terminal keeps Shift+drag for native selection no matter what pal
725
+ // binds, so one modifier cannot mean both. (Copying pal's own text needs
726
+ // pal-side selection — see EXTENSIONS-ROADMAP.md item #5.)
727
+ //
728
+ // Verified against pi-tui's parser: Shift+Up arrives as `\x1b[1;2A` and
729
+ // matches `Key.shift('up')`, while plain `\x1b[A` does not collide with it.
730
+ // pi-tui's Editor binds no Shift+arrow at all.
589
731
 
590
732
  // Mouse wheel. pi-tui has no mouse layer, so enable SGR mouse reporting and
591
733
  // decode the wheel events here. 64 = wheel up, 65 = wheel down.
@@ -623,6 +765,9 @@ async function main() {
623
765
  mouseEnabled = false;
624
766
  mouseTracked = false;
625
767
  clearHover();
768
+ // No more motion events will arrive, so nothing can stop a running
769
+ // autoscroll tick — it would scroll forever with the mouse reporting off.
770
+ stopDragScroll();
626
771
  terminal.write('\x1b[?1000l\x1b[?1003l\x1b[?1006l');
627
772
  };
628
773
 
@@ -652,6 +797,25 @@ async function main() {
652
797
  return Math.max(1, terminal.rows - editorLines - 2);
653
798
  };
654
799
 
800
+ // A selection anchored in transcript space stays valid while the window
801
+ // scrolls (the highlight follows the text, not the screen cell), so scrolling
802
+ // must not clear it — it only needs a repaint.
803
+
804
+ /**
805
+ * Snap the transcript back to the newest row.
806
+ *
807
+ * The old scroll-mode design relied on "typing a printable character" to
808
+ * leave the scrolled window, which is no longer available: plain arrows now
809
+ * belong to the editor, so there is no mode to leave and no keystroke to
810
+ * detect. Submitting has to do it explicitly, otherwise a prompt sent while
811
+ * scrolled up would stream its reply entirely out of view.
812
+ */
813
+ const snapToTail = (): void => {
814
+ if (scrollOffset === 0) return;
815
+ scrollOffset = 0;
816
+ updateStatusLine();
817
+ };
818
+
655
819
  // ── Code-block header copy (left-click on `⧉ copy`) ──
656
820
  //
657
821
  // Recompute the exact transcript window the renderer painted (same formula
@@ -689,10 +853,19 @@ async function main() {
689
853
  return null;
690
854
  };
691
855
 
692
- // Pure layout math + tree walk: maps a 1-based SGR cell to the code block
693
- // under it. Callers flush the frame first so the y → row mapping matches
694
- // what is painted — this must not repaint itself (hover runs it per motion).
695
- const findCodeBlockAt = (_x: number, y: number): CodeBlockHit | null => {
856
+ // Shared layout math: the transcript window in screen space.
857
+ //
858
+ // Every consumer (hit-testing, cell→row mapping, edge auto-scroll) must agree
859
+ // on exactly which rows are painted and where the padding sits, so this lives
860
+ // in one place. `padTop` is the blank padding above a short transcript;
861
+ // `winLen` is how many real transcript rows are visible.
862
+ const transcriptWindow = (): {
863
+ contentW: number;
864
+ start: number;
865
+ end: number;
866
+ winLen: number;
867
+ padTop: number;
868
+ } => {
696
869
  const contentW = Math.max(1, terminal.columns - sidebarWidthFor(terminal.columns));
697
870
  const transcript = messagesContainer.render(contentW);
698
871
  const editorH = editorRow.render(contentW).length;
@@ -704,6 +877,14 @@ async function main() {
704
877
  const start = Math.max(0, end - viewport);
705
878
  const winLen = end - start;
706
879
  const padTop = Math.max(0, viewport - winLen);
880
+ return {contentW, start, end, winLen, padTop};
881
+ };
882
+
883
+ // Pure layout math + tree walk: maps a 1-based SGR cell to the code block
884
+ // under it. Callers flush the frame first so the y → row mapping matches
885
+ // what is painted — this must not repaint itself (hover runs it per motion).
886
+ const findCodeBlockAt = (_x: number, y: number): CodeBlockHit | null => {
887
+ const {contentW, start, winLen, padTop} = transcriptWindow();
707
888
 
708
889
  // SGR coordinates are 1-based; the layout pads the window above.
709
890
  const windowIdx = y - 1 - padTop;
@@ -718,6 +899,148 @@ async function main() {
718
899
  };
719
900
  };
720
901
 
902
+ // Map a 1-based SGR cell to a point in transcript space, or null when the
903
+ // cell is outside the transcript window (padding, editor, status line).
904
+ // Columns are clamped to the transcript width: the sidebar is an overlay
905
+ // painted over the same rows, and letting a drag reach those columns is
906
+ // exactly what copied sidebar glyphs under native selection.
907
+ const screenToTranscript = (x: number, y: number): SelectionPoint | null => {
908
+ const {contentW, start, winLen, padTop} = transcriptWindow();
909
+ const windowIdx = y - 1 - padTop;
910
+ if (windowIdx < 0 || windowIdx >= winLen) return null;
911
+ const col = Math.max(0, Math.min(x - 1, contentW));
912
+ return {row: start + windowIdx, col};
913
+ };
914
+
915
+ /** Copy whatever the current selection covers, then flash the status line. */
916
+ const copySelection = (): void => {
917
+ const range = selectionRange();
918
+ if (range === null || isEmptySelection(range)) return;
919
+ // Recompute the freshly rendered rows: the copied text must be the same
920
+ // bytes the highlight was painted over, not a stale scroll snapshot.
921
+ const contentW = Math.max(1, terminal.columns - sidebarWidthFor(terminal.columns));
922
+ const rows = messagesContainer.render(contentW);
923
+ // Re-base the range onto the slice — extractSelection indexes from lines[0].
924
+ const window = rows.slice(range.first.row, range.last.row + 1);
925
+ const rebased: SelectionRange = {
926
+ first: {row: 0, col: range.first.col},
927
+ last: {row: window.length - 1, col: range.last.col},
928
+ };
929
+ const text = extractSelection(window, rebased);
930
+ if (text.trim() === '') return;
931
+ tui.terminal.write(buildOsc52Sequence(text));
932
+ flashCopied(text.length);
933
+ };
934
+
935
+ // ── Drag edge auto-scroll ──
936
+ //
937
+ // Motion events only arrive while the mouse actually moves. Resting the
938
+ // pointer past the top or bottom edge is a steady state, so a timer has to
939
+ // drive the scroll — otherwise the window stops at the edge and the drag can
940
+ // never reach content that is out of view. Each tick scrolls one row and
941
+ // re-pins the focus to the edge row, so the selection keeps growing.
942
+ //
943
+ // `dragScrollTimer`, `dragEdge` and `DRAG_SCROLL_INTERVAL_MS` are declared up
944
+ // with the selection state (see above) because `clearSelection` and
945
+ // `disableMouse` reference `stopDragScroll` before this point.
946
+ // The last pointer column, so a tick can extend the focus without a motion
947
+ // event to read it from.
948
+ let dragColumn = 0;
949
+ // Last pointer row, in screen coordinates. The top edge is inferred from
950
+ // motion direction because the window starts at screen row 1 — there is no row
951
+ // above it to point at (see `dragEdgeFor`).
952
+ let dragLastY = -1;
953
+ // Double-click detection: the previous press cell and when it happened. SGR
954
+ // has no click-count field, so pal has to infer it from two presses landing on
955
+ // the same cell inside the platform's double-click window.
956
+ let lastPressRow = -1;
957
+ let lastPressCol = -1;
958
+ let lastPressAt = 0;
959
+ const DOUBLE_CLICK_MS = 500;
960
+
961
+ /** Expand the selection to the word under a click. Copy stays on Ctrl/Cmd+C. */
962
+ const selectWordAt = (point: SelectionPoint): void => {
963
+ const {contentW} = transcriptWindow();
964
+ const rows = messagesContainer.render(contentW);
965
+ const line = rows[point.row];
966
+ if (line === undefined) return;
967
+ const span = wordRangeAt(line, point.col);
968
+ if (span === null) return;
969
+ selectionAnchor = {row: point.row, col: span.from};
970
+ selectionFocus = {row: point.row, col: span.to};
971
+ // Repaint the status line too: it is what tells the user the selection is
972
+ // waiting to be copied rather than already copied.
973
+ updateStatusLine();
974
+ tui.renderNow();
975
+ };
976
+
977
+ const stopDragScroll = (): void => {
978
+ if (dragScrollTimer !== null) {
979
+ clearInterval(dragScrollTimer);
980
+ dragScrollTimer = null;
981
+ }
982
+ dragEdge = 0;
983
+ };
984
+
985
+ /** One autoscroll step: scroll, then pull the focus along to the edge row. */
986
+ const dragScrollStep = (): void => {
987
+ if (!dragging || dragEdge === 0) {
988
+ stopDragScroll();
989
+ return;
990
+ }
991
+ // Rows scrolled up increase the offset; the bottom edge reveals later rows.
992
+ const before = scrollOffset;
993
+ scrollBy(dragEdge > 0 ? -1 : 1);
994
+ if (scrollOffset === before) {
995
+ // Hitting either end of the transcript: nothing left to reveal, so the
996
+ // pointer is no longer past anything meaningful. Stop rather than spin.
997
+ stopDragScroll();
998
+ return;
999
+ }
1000
+ const {start, winLen} = transcriptWindow();
1001
+ if (winLen <= 0) return;
1002
+ const edgeRow = dragEdge > 0 ? start + winLen - 1 : start;
1003
+ if (selectionFocus === null || selectionFocus.row !== edgeRow) {
1004
+ selectionFocus = {row: edgeRow, col: dragColumn};
1005
+ }
1006
+ tui.renderNow();
1007
+ };
1008
+
1009
+ /**
1010
+ * Update the autoscroll state from the pointer's position.
1011
+ *
1012
+ * Called on every drag motion. Returns the focus row to use: the real row
1013
+ * when the pointer is over the transcript, or the pinned edge row when it has
1014
+ * gone past one.
1015
+ */
1016
+ const updateDragScroll = (y: number, col: number): number => {
1017
+ const {start, winLen, padTop, contentW} = transcriptWindow();
1018
+ const windowIdx = y - 1 - padTop;
1019
+ const movingUp = dragLastY >= 0 && y < dragLastY;
1020
+ dragLastY = y;
1021
+ // Clamp to the transcript, never the sidebar overlay — a pinned focus column
1022
+ // that reached into the overlay would highlight cells outside pal's text.
1023
+ dragColumn = Math.max(0, Math.min(col, contentW));
1024
+
1025
+ let edge = dragEdgeFor(windowIdx, winLen, movingUp);
1026
+ // Nothing lives above transcript row 0, so a top-edge signal with the window
1027
+ // already at the start would spin the timer for no gain. (When the
1028
+ // transcript is shorter than the viewport, `padTop` pushes it down and a
1029
+ // pointer in that blank band lands here with `start === 0`.)
1030
+ if (edge === -1 && start === 0) edge = 0;
1031
+ dragEdge = edge;
1032
+
1033
+ if (edge !== 0) {
1034
+ if (dragScrollTimer === null) {
1035
+ dragScrollTimer = setInterval(dragScrollStep, DRAG_SCROLL_INTERVAL_MS);
1036
+ }
1037
+ } else {
1038
+ stopDragScroll();
1039
+ }
1040
+ if (winLen <= 0) return start;
1041
+ return clampRowIntoWindow(windowIdx, winLen, start);
1042
+ };
1043
+
721
1044
  const handleCopyClick = (x: number, y: number): void => {
722
1045
  // Flush any pending frame so the row mapping matches what is painted.
723
1046
  tui.renderNow();
@@ -801,7 +1124,40 @@ async function main() {
801
1124
  if (changed) tui.renderNow();
802
1125
  }
803
1126
 
1127
+ /**
1128
+ * True when a selection is currently on screen and there is text to copy.
1129
+ *
1130
+ * Ctrl/Cmd+C has to consult this before it is allowed to mean "exit": on
1131
+ * Windows and Linux a bare Ctrl+C is the quit key, so the only way to make it
1132
+ * also mean "copy" without a modifier that terminals cannot report is to let
1133
+ * an existing selection take priority over quitting.
1134
+ */
1135
+ const hasCopyableSelection = (): boolean => {
1136
+ const range = selectionRange();
1137
+ return range !== null && !isEmptySelection(range);
1138
+ };
1139
+
1140
+ /** Copy the live selection on Ctrl/Cmd+C, clearing it so the next press exits. */
1141
+ const copySelectionFromKey = (): void => {
1142
+ copySelection();
1143
+ clearSelection();
1144
+ };
1145
+
804
1146
  tui.addInputListener((data) => {
1147
+ // ── Copy key, checked before everything that could quit ──
1148
+ //
1149
+ // Placed in this listener (which runs before the exit handler below) because
1150
+ // "copy" must beat "exit". Cmd+C reports as `super+c` only over the Kitty
1151
+ // keyboard protocol; a plain Ctrl+C arrives as a bare \x03 with no modifier
1152
+ // information at all, so pal cannot tell the two apart and treats both as
1153
+ // "copy if something is selected, otherwise quit".
1154
+ if (hasCopyableSelection()) {
1155
+ if (matchesKey(data, 'ctrl+c') || matchesKey(data, 'super+c')) {
1156
+ copySelectionFromKey();
1157
+ return {consume: true};
1158
+ }
1159
+ }
1160
+
805
1161
  // SGR mouse: ESC [ < b ; x ; y M|m (preferred, enabled via ?1006h)
806
1162
  const mouse = data.startsWith('\x1b[<')
807
1163
  ? data.slice(3).match(/^(\d+);(\d+);(\d+)([Mm])$/)
@@ -822,18 +1178,81 @@ async function main() {
822
1178
  scrollBy(-3); // wheel down
823
1179
  return {consume: true};
824
1180
  }
825
- // Pointer-motion reports (?1003h): motion bit set, wheel clear — track
826
- // hover. The release char is ignored: motion arrives as M or m
827
- // depending on whether a button is held during the move.
1181
+ // Pointer motion (?1003h, or ?1002h while a button is held).
828
1182
  if ((raw & 32) !== 0 && (raw & 64) === 0) {
1183
+ // With the left button down this is a drag: extend the selection
1184
+ // instead of tracking hover. `dragging` is only set by a press that
1185
+ // landed inside the transcript, so a drag over the editor or the
1186
+ // sidebar never starts one.
1187
+ if (dragging) {
1188
+ const col = Math.max(0, Math.min(x - 1, terminal.columns));
1189
+ const row = updateDragScroll(y, col);
1190
+ if (
1191
+ selectionFocus === null ||
1192
+ row !== selectionFocus.row ||
1193
+ col !== selectionFocus.col
1194
+ ) {
1195
+ selectionFocus = {row, col};
1196
+ tui.renderNow();
1197
+ }
1198
+ return {consume: true};
1199
+ }
829
1200
  evaluateHover(x, y);
830
1201
  return {consume: true};
831
1202
  }
832
- // Left-button press without drag/wheel bits → header copy-zone test;
833
- // the handler itself is a no-op outside a zone. Drag bit (32) excluded
834
- // so a future drag-select never fires a copy.
1203
+ // Left-button press (no drag/wheel bits): anchor a selection. A press on
1204
+ // the `⧉ copy` header still works — it is resolved on release, when we
1205
+ // know whether the user actually dragged.
835
1206
  if (!isRelease && (raw & 64) === 0 && (raw & 32) === 0 && (raw & 3) === 0) {
836
- handleCopyClick(x, y);
1207
+ const point = screenToTranscript(x, y);
1208
+ // A second press on the same cell inside the threshold is a double-click:
1209
+ // select the word and copy it right away. Tracked per press because SGR
1210
+ // carries no click count.
1211
+ const now = Date.now();
1212
+ const isDouble =
1213
+ point !== null &&
1214
+ point.row === lastPressRow &&
1215
+ point.col === lastPressCol &&
1216
+ now - lastPressAt <= DOUBLE_CLICK_MS;
1217
+ lastPressRow = point?.row ?? -1;
1218
+ lastPressCol = point?.col ?? -1;
1219
+ lastPressAt = now;
1220
+
1221
+ clearSelection();
1222
+ if (point) {
1223
+ if (isDouble) {
1224
+ // Do not arm a drag: a triple-click would otherwise extend the word
1225
+ // selection into a drag on the next motion event.
1226
+ selectWordAt(point);
1227
+ return {consume: true};
1228
+ }
1229
+ selectionAnchor = point;
1230
+ selectionFocus = point;
1231
+ dragging = true;
1232
+ dragColumn = point.col;
1233
+ // Seed the direction tracker: the first motion event compares against
1234
+ // this, so a drag that starts heading upward is detected immediately.
1235
+ dragLastY = y;
1236
+ // A fresh press replaces any previous selection; announce it at once so
1237
+ // the status line hint is not a release behind the highlight.
1238
+ updateStatusLine();
1239
+ }
1240
+ return {consume: true};
1241
+ }
1242
+ // Release: end the drag but KEEP the selection painted. Copying happens
1243
+ // on Ctrl/Cmd+C, so a drag that stopped on the wrong word costs nothing —
1244
+ // the old auto-copy-on-release made every misstop a clipboard overwrite.
1245
+ if (isRelease) {
1246
+ if (dragging) {
1247
+ stopDragScroll();
1248
+ dragging = false;
1249
+ // A press-release with no movement is still a header copy-zone click.
1250
+ if (!hasCopyableSelection()) {
1251
+ clearSelection();
1252
+ handleCopyClick(x, y);
1253
+ }
1254
+ return {consume: true};
1255
+ }
837
1256
  return {consume: true};
838
1257
  }
839
1258
  return {consume: true}; // swallow other mouse events
@@ -853,7 +1272,37 @@ async function main() {
853
1272
  return {consume: true};
854
1273
  }
855
1274
 
856
- // Always-on navigation.
1275
+ // Shift-modified navigation — scrolls the transcript from anywhere, and
1276
+ // always wins over the editor (which binds no Shift+arrow). Checked before
1277
+ // the unmodified keys so a Shift chord can never fall through to them.
1278
+ if (matchesKey(data, Key.shift('up'))) {
1279
+ scrollBy(1);
1280
+ return {consume: true};
1281
+ }
1282
+ if (matchesKey(data, Key.shift('down'))) {
1283
+ scrollBy(-1);
1284
+ return {consume: true};
1285
+ }
1286
+ if (matchesKey(data, Key.shift('pageUp'))) {
1287
+ scrollBy(pageRows());
1288
+ return {consume: true};
1289
+ }
1290
+ if (matchesKey(data, Key.shift('pageDown'))) {
1291
+ scrollBy(-pageRows());
1292
+ return {consume: true};
1293
+ }
1294
+ if (matchesKey(data, Key.shift('home'))) {
1295
+ revealEarlierHistory();
1296
+ scrollOffset = Number.MAX_SAFE_INTEGER;
1297
+ updateStatusLine();
1298
+ return {consume: true};
1299
+ }
1300
+ if (matchesKey(data, Key.shift('end'))) {
1301
+ scrollBy(-Number.MAX_SAFE_INTEGER);
1302
+ return {consume: true};
1303
+ }
1304
+
1305
+ // Unmodified, editor-neutral navigation.
857
1306
  if (matchesKey(data, Key.pageUp)) {
858
1307
  scrollBy(pageRows());
859
1308
  return {consume: true};
@@ -873,37 +1322,24 @@ async function main() {
873
1322
  return {consume: true};
874
1323
  }
875
1324
 
876
- // Scroll-mode keys — only while scrolled away from the tail.
877
- const scrolled = scrollOffset > 0;
878
- if (scrolled) {
879
- if (matchesKey(data, Key.escape)) {
880
- scrollBy(-Number.MAX_SAFE_INTEGER);
881
- return {consume: true};
882
- }
883
- if (matchesKey(data, Key.up) || matchesKey(data, Key.shift('up'))) {
884
- scrollBy(1);
885
- return {consume: true};
886
- }
887
- if (matchesKey(data, Key.down) || matchesKey(data, Key.shift('down'))) {
888
- scrollBy(-1);
889
- return {consume: true};
890
- }
891
- if (matchesKey(data, Key.home)) {
892
- scrollOffset = Number.MAX_SAFE_INTEGER;
893
- updateStatusLine();
894
- return {consume: true};
895
- }
896
- if (matchesKey(data, Key.end)) {
897
- scrollBy(-Number.MAX_SAFE_INTEGER);
898
- return {consume: true};
899
- }
900
- // Any printable character means the user is typing again — drop out of
901
- // scroll mode and let the editor receive the key.
902
- if (data.length === 1 && data >= ' ' && data !== '\x7f') {
903
- scrollOffset = 0;
904
- updateStatusLine();
905
- return undefined;
906
- }
1325
+ // Leaving the scrolled window. Esc is also the abort key, so this must not
1326
+ // eat a live Esc: while a turn is running, Esc belongs to the abort
1327
+ // two-press logic further down and the user returns with Shift+End instead.
1328
+ // Plain ↑/↓ and Home/End belong to the editor readline-style, so they are
1329
+ // no longer intercepted — the old scroll mode swallowing them is exactly
1330
+ // what made arrow-key scrolling depend on invisible state.
1331
+ if (scrollOffset > 0 && !state.activeAbort && matchesKey(data, Key.escape)) {
1332
+ scrollBy(-Number.MAX_SAFE_INTEGER);
1333
+ return {consume: true};
1334
+ }
1335
+ // Escape also drops a selection when nothing else wants the key.
1336
+ if (
1337
+ !state.activeAbort &&
1338
+ (selectionAnchor !== null || selectionFocus !== null) &&
1339
+ matchesKey(data, Key.escape)
1340
+ ) {
1341
+ clearSelection();
1342
+ return {consume: true};
907
1343
  }
908
1344
 
909
1345
  return undefined;
@@ -934,12 +1370,36 @@ async function main() {
934
1370
  // it without hitting the temporal dead zone.
935
1371
  const messages: Message[] = [];
936
1372
 
1373
+ /**
1374
+ * Memoised tool-schema token cost. Null until first measured; cleared when the
1375
+ * tool set can change (extension load/reload), since that is what moves it.
1376
+ */
1377
+ let toolTokensCache: number | null = null;
1378
+
1379
+ /** Invalidate the memoised tool-schema cost after the tool set changes. */
1380
+ function refreshToolTokenEstimate(): void {
1381
+ toolTokensCache = null;
1382
+ }
1383
+
937
1384
  function updateStatusLine() {
938
- const modelShort = config.model.split('/').pop()?.split(':')[0] ?? config.model;
939
- const providerName = providerForModel(config.model, Object.keys(allKeys)).provider.name;
1385
+ const modelShort = config.model.split('/').pop()?.split(':')[0] ?? config.model; const providerName = providerForModel(config.model, Object.keys(allKeys)).provider.name;
1386
+ // Thinking mode sits between the model and the provider: the identity of the
1387
+ // turn is "which model, thinking how hard, on whose endpoint". Shown always
1388
+ // (not only for reasoning models) so the setting is never a guess — that is
1389
+ // the whole point of surfacing it.
1390
+ const effortStr = `${surface.statusLine.dim}·${c.reset}${surface.statusLine.info}${config.reasoningEffort}${c.reset}`;
940
1391
  // Context fill = the CURRENT conversation vs the configured window — not
941
1392
  // lifetime tokens (which never drop after /compact or /new).
942
- const ctxTokens = estimateMessagesTokens(messages) + Math.ceil(config.systemPrompt.length / 4);
1393
+ // Charges the FULL prompt: composeSystemPrompt's roles/skills/extension
1394
+ // blocks plus the tool schemas are re-sent every request but were never
1395
+ // counted here, so this was a material undercount (see fixedPromptTokens).
1396
+ // Tool schemas don't change between extension loads, and this runs on every
1397
+ // streaming repaint — so measure once rather than re-serializing ~2k tokens
1398
+ // of JSON per frame. `refreshToolTokenEstimate()` is the invalidation point.
1399
+ toolTokensCache ??= estimateToolSchemaTokens();
1400
+ const ctxTokens =
1401
+ estimateMessagesTokens(messages) +
1402
+ fixedPromptTokens(config.systemPrompt, toolTokensCache);
943
1403
  const contextPct = Math.min(100, Math.round((ctxTokens / config.contextLimit) * 100));
944
1404
  // Background sub-agents (ctrl+b opens the panel).
945
1405
  const running = state.backgroundAgents.filter((a) => a.status === 'running').length;
@@ -960,9 +1420,17 @@ async function main() {
960
1420
  );
961
1421
  } else if (scrollOffset > 0) {
962
1422
  // Scrolled back through the transcript — surface the way out so the
963
- // user isn't stranded in scroll mode.
1423
+ // user isn't stranded in the scrolled window.
964
1424
  statusLine.setText(
965
- `${surface.statusLine.info}↕ scrolled${c.reset} ${c.dim}· PgDn/↓ End or Esc to resume${c.reset}`,
1425
+ `${surface.statusLine.info}↕ scrolled${c.reset} ${c.dim}· Shift+PgDn/Shift+↓ or Esc to resume${c.reset}`,
1426
+ );
1427
+ } else if (hasCopyableSelection()) {
1428
+ // A finished drag waits here until the user commits it with Ctrl/Cmd+C.
1429
+ // Retained (not auto-copied) so a drag that ended in the wrong place can
1430
+ // be redone without having already clobbered the clipboard — but that only
1431
+ // works if the pending state is visible.
1432
+ statusLine.setText(
1433
+ `${surface.statusLine.info}▍ selection${c.reset} ${c.dim}· Ctrl/Cmd+C to copy · Esc to clear${c.reset}`,
966
1434
  );
967
1435
  } else {
968
1436
  // `queued (N)` — messages submitted while a turn runs (drained on
@@ -975,8 +1443,13 @@ async function main() {
975
1443
  state.abortArmed && state.activeAbort
976
1444
  ? ` ${surface.statusLine.warn}Esc again to stop${c.reset}`
977
1445
  : '';
1446
+ // An armed exit is a committed quit one keystroke away — it must say so,
1447
+ // the same way the Esc-to-stop arm does.
1448
+ const exitStr = state.exitArmed
1449
+ ? ` ${surface.statusLine.warn}Ctrl+C again to quit${c.reset}`
1450
+ : '';
978
1451
  statusLine.setText(
979
- `${modelShort} ${surface.statusLine.dim}${providerName}${agentStr}${subStr}${queuedStr}${abortStr}${c.reset} ${surface.statusLine.dim}/help${c.reset}`,
1452
+ `${modelShort} ${effortStr} ${surface.statusLine.dim}${providerName}${agentStr}${subStr}${queuedStr}${abortStr}${exitStr}${c.reset} ${surface.statusLine.dim}/help${c.reset}`,
980
1453
  );
981
1454
  }
982
1455
  // A copy flash outranks every other status for its 1500ms window, so a
@@ -1198,16 +1671,65 @@ async function main() {
1198
1671
  // ── Exit handler: intercept raw Ctrl+C and Ctrl+D via input listener ──
1199
1672
  // pi-tui maps ctrl+c to "copy selection" and ctrl+d to "delete", so we
1200
1673
  // listen at the raw TUI level. On empty editor, these become exit signals.
1674
+ //
1675
+ // Ctrl+C takes two presses, matching the Esc/turn-stop contract: with nothing
1676
+ // selected the first press only arms (the status line says so), and a second
1677
+ // one inside the window quits. That is what stops the copy key and the quit
1678
+ // key from colliding — without it the *first* Ctrl+C would exit the moment no
1679
+ // text was selected. A live selection outranks both, and the copy listener
1680
+ // above has already consumed the key in that case.
1681
+ let exitArmTimer: ReturnType<typeof setTimeout> | null = null;
1682
+ const disarmExit = (): void => {
1683
+ state.exitArmed = false;
1684
+ if (exitArmTimer) {
1685
+ clearTimeout(exitArmTimer);
1686
+ exitArmTimer = null;
1687
+ }
1688
+ };
1689
+ const armExit = (): void => {
1690
+ disarmExit();
1691
+ state.exitArmed = true;
1692
+ exitArmTimer = setTimeout(() => {
1693
+ state.exitArmed = false;
1694
+ exitArmTimer = null;
1695
+ updateStatusLine();
1696
+ }, 5000);
1697
+ updateStatusLine();
1698
+ };
1699
+
1201
1700
  tui.addInputListener((data: string) => {
1202
1701
  if (state.abortArmed && !matchesKey(data, 'escape')) {
1203
1702
  disarmAbort();
1204
1703
  updateStatusLine();
1205
1704
  }
1206
- if (matchesKey(data, 'ctrl+c') || matchesKey(data, 'ctrl+d')) {
1705
+ // Any key other than the quit keys cancels an armed exit, so a forgotten arm
1706
+ // cannot turn a much later Ctrl+C into an accidental quit.
1707
+ const isQuitKey = matchesKey(data, 'ctrl+c') || matchesKey(data, 'ctrl+d');
1708
+ if (state.exitArmed && !isQuitKey) {
1709
+ disarmExit();
1710
+ updateStatusLine();
1711
+ }
1712
+ if (isQuitKey) {
1713
+ // A selection means this press is a copy, not an arm and not a quit.
1714
+ if (hasCopyableSelection()) return {consume: false};
1715
+ // Ctrl+D has no copy meaning, so it keeps quitting in one press.
1716
+ if (matchesKey(data, 'ctrl+d')) {
1717
+ if (editor.getText().trim().length === 0) {
1718
+ saveSession();
1719
+ tui.stop();
1720
+ process.exit(0);
1721
+ }
1722
+ return {consume: false};
1723
+ }
1207
1724
  if (editor.getText().trim().length === 0) {
1208
- saveSession();
1209
- tui.stop();
1210
- process.exit(0);
1725
+ const action = nextExitAction(state.exitArmed, false);
1726
+ if (action.exit) {
1727
+ disarmExit();
1728
+ saveSession();
1729
+ tui.stop();
1730
+ process.exit(0);
1731
+ }
1732
+ armExit();
1211
1733
  }
1212
1734
  }
1213
1735
  return {consume: false};
@@ -1335,8 +1857,47 @@ async function main() {
1335
1857
  return {consume: true};
1336
1858
  }
1337
1859
 
1860
+ // ── Plan approval prompt: y / n (and Esc = no) ──
1861
+ // Checked before every other binding so a plan waiting on consent cannot be
1862
+ // answered by accident through some unrelated key. Only y/n/Esc are
1863
+ // consumed; anything else falls through to the editor untouched.
1864
+ if (pendingApproval) {
1865
+ const decision = approvalKeyDecision(data);
1866
+ if (decision !== 'ignore') {
1867
+ if (decision === 'approve') {
1868
+ void firePlanApproval();
1869
+ } else {
1870
+ dismissApprovalPrompt();
1871
+ messagesContainer.addChild(
1872
+ new Text(
1873
+ `${c.dim} plan not approved — staying in ${state.currentAgentRole}. ` +
1874
+ `The plan is still in the transcript.${c.reset}`,
1875
+ 1,
1876
+ 0,
1877
+ ),
1878
+ );
1879
+ tui.requestRender();
1880
+ }
1881
+ return {consume: true};
1882
+ }
1883
+ }
1884
+
1885
+ // Shift+Tab cycles *primary* agents mid-draft. Plain Tab cannot be taken:
1886
+ // it belongs to the editor's autocomplete (pi-tui README:432). shift+tab is
1887
+ // unbound there (README:430-439, 698) and reaches this listener whatever
1888
+ // the buffer holds — which is the point: cycling used to require an empty
1889
+ // editor, so it was impossible to switch mode while reviewing a draft.
1890
+ // Returning consume stops the editor from also acting on the key.
1891
+ if (matchesKey(data, Key.shift('tab'))) {
1892
+ // Mid-turn switching is a no-op: the primary decides which tools are
1893
+ // legal, and flipping plan → pal under a live read-only run would grant
1894
+ // write tools to a turn that was authorised read-only.
1895
+ if (!state.activeAbort) cycleAgentRole();
1896
+ return {consume: true};
1897
+ }
1338
1898
  // Tab cycles *primary* agents (OMO/OpenCode style) — only when the editor
1339
- // is empty, so file-path autocomplete keeps working.
1899
+ // is empty, so file-path autocomplete keeps working. Left exactly as-is on
1900
+ // purpose: this work does not touch plain Tab.
1340
1901
  if (matchesKey(data, 'tab') && editor.getText().trim().length === 0) {
1341
1902
  cycleAgentRole();
1342
1903
  return {consume: true};
@@ -1401,10 +1962,12 @@ async function main() {
1401
1962
  const wasReadOnly = isReadOnlyRole(state.currentAgentRole);
1402
1963
  if (switchPrimary(ev.name)) {
1403
1964
  const nowReadOnly = isReadOnlyRole(ev.name);
1404
- // Leaving a read-only agent (plan → pal) means a plan is ready. Flag it
1405
- // so the turn is followed by an implementation turn, rather than
1406
- // stopping and making the user type "go".
1407
- if (wasReadOnly && !nowReadOnly && !autoExecuted) pendingExecution = true;
1965
+ // Leaving a read-only agent (plan → pal) means a plan is ready. It is
1966
+ // NOT approved: the model asked, so the user decides. This listener runs
1967
+ // inside the live planning turn, so it cannot prompt (runTurn is not
1968
+ // re-entrant) — it records intent and the settle path in `onSubmit`
1969
+ // opens the y/n prompt once the turn has finished.
1970
+ if (wasReadOnly && !nowReadOnly && !autoExecuted) pendingPlan = true;
1408
1971
 
1409
1972
  const why = ev.reason ? ` ${c.dim}— ${ev.reason}${c.reset}` : '';
1410
1973
  messagesContainer.addChild(
@@ -1435,11 +1998,148 @@ async function main() {
1435
1998
 
1436
1999
  let isProcessing = false;
1437
2000
 
2001
+ // ── Plan → build approval gate ──
1438
2002
  // Set by the `primary-request` listener when a planning agent hands control
1439
- // back: the turn that follows should implement the plan automatically.
1440
- let pendingExecution = false;
2003
+ // back. The plan is NOT approved at that moment: the model asked, so the user
2004
+ // decides. The old code ran the implementation turn in the same pass, so
2005
+ // `exit_plan_mode` began writing files while the transcript announced "your
2006
+ // plan above is approved" — nothing had been approved.
2007
+ let pendingApproval = false;
2008
+ // Set when a planning agent switched back to an executable role mid-turn.
2009
+ // The prompt cannot be shown from the `primary-request` listener: that fires
2010
+ // inside the live planning turn (`isProcessing` is true), and `runTurn` is
2011
+ // not re-entrant. So the listener only records intent, and the settle path in
2012
+ // `onSubmit` opens the prompt once the turn is over.
2013
+ let pendingPlan = false;
1441
2014
  // Guards against a plan → execute → plan → execute chain in one user message.
1442
2015
  let autoExecuted = false;
2016
+ // The single "implement" path. The `y` keypress and the timeout both route
2017
+ // through it, so the approval prompt text lives in exactly one place and the
2018
+ // post-approval turn can only ever be started from one place.
2019
+ let approvePlan: (() => Promise<void>) | null = null;
2020
+ // Countdown handle. `null` means no prompt is counting down.
2021
+ let approvalTimer: ReturnType<typeof setInterval> | null = null;
2022
+ // The countdown text component, repainted in place each tick. A bare child
2023
+ // added per tick would append a new transcript row every second.
2024
+ let approvalText: Text | null = null;
2025
+ // Seconds left on the visible countdown. Hoisted out of `showApprovalPrompt`'s
2026
+ // closure because the settle path has to read it: a countdown that expired
2027
+ // while a turn was live reached zero with nowhere to fire, and only this value
2028
+ // can tell the settle path that the approval is due.
2029
+ let approvalRemaining = 0;
2030
+
2031
+ /** Stop the countdown. Called on `y`, on `n`, and before any new turn. */
2032
+ const clearApprovalTimer = (): void => {
2033
+ if (approvalTimer !== null) {
2034
+ clearInterval(approvalTimer);
2035
+ approvalTimer = null;
2036
+ }
2037
+ };
2038
+
2039
+ /** Drop the prompt row and stop its countdown. Does not run anything. */
2040
+ const dismissApprovalPrompt = (): void => {
2041
+ clearApprovalTimer();
2042
+ pendingApproval = false;
2043
+ approvePlan = null;
2044
+ if (approvalText) {
2045
+ try {
2046
+ messagesContainer.removeChild(approvalText);
2047
+ } catch {
2048
+ // Already detached — nothing to undo.
2049
+ }
2050
+ approvalText = null;
2051
+ }
2052
+ tui.requestRender();
2053
+ };
2054
+
2055
+ /**
2056
+ * Run the approved implementation turn exactly once.
2057
+ *
2058
+ * Shared by the `y` keypress, the countdown, and the settle-path re-check, and
2059
+ * guarded by `pendingApproval` so no two of those can ever both fire.
2060
+ *
2061
+ * Declared as a `function` (not a `const` arrow) on purpose: `showApprovalPrompt`
2062
+ * schedules it from a timer callback, and with `const` that reference sat in a
2063
+ * temporal dead zone — the compiler could not see it, but the callback resolved
2064
+ * it lazily and would have thrown on the first timeout.
2065
+ */
2066
+ async function firePlanApproval(): Promise<void> {
2067
+ const run = approvePlan;
2068
+ if (!pendingApproval || !run) return;
2069
+ // Clear the flag FIRST: dismissing below is what makes the second caller
2070
+ // (y after timeout, or timeout after y) a no-op.
2071
+ pendingApproval = false;
2072
+ autoExecuted = true;
2073
+ dismissApprovalPrompt();
2074
+ messagesContainer.addChild(
2075
+ new Text(`${c.green} ▸ ${c.reset}${c.dim}plan approved — implementing…${c.reset}`, 1, 0),
2076
+ );
2077
+ tui.requestRender();
2078
+ await run();
2079
+ }
2080
+
2081
+ /**
2082
+ * Show the approval prompt with a live countdown.
2083
+ *
2084
+ * The countdown is part of the contract, not decoration: the prompt
2085
+ * auto-approves, so the user must be able to see that it will. While
2086
+ * `isProcessing` the countdown runs but the timeout is *held* — `runTurn` is
2087
+ * not re-entrant, so firing mid-turn would either run two turns at once or be
2088
+ * silently dropped. The settle path re-checks and fires then.
2089
+ */
2090
+ const showApprovalPrompt = (runApproval: () => Promise<void>): void => {
2091
+ approvePlan = runApproval;
2092
+ pendingApproval = true;
2093
+
2094
+ approvalRemaining = resolveApprovalTimeoutSeconds(readPalConfig().planApprovalTimeoutSeconds);
2095
+ const text = new Text('', 1, 0);
2096
+ const paint = (): void => {
2097
+ text.setText(
2098
+ `${c.green}▸ ${c.reset}${c.yellow}${approvalPromptText(approvalRemaining)}${c.reset}`,
2099
+ );
2100
+ };
2101
+ paint();
2102
+ approvalText = text;
2103
+ messagesContainer.addChild(text);
2104
+ messagesContainer.addChild(new Spacer(1));
2105
+ tui.requestRender();
2106
+
2107
+ clearApprovalTimer();
2108
+ approvalTimer = setInterval(() => {
2109
+ if (!pendingApproval) {
2110
+ clearApprovalTimer();
2111
+ return;
2112
+ }
2113
+ const next = tickApproval(approvalRemaining);
2114
+ approvalRemaining = next.remainingSeconds;
2115
+ paint();
2116
+ tui.requestRender();
2117
+ if (
2118
+ next.done &&
2119
+ shouldAutoApprove({
2120
+ pending: pendingApproval,
2121
+ idle: !isProcessing,
2122
+ remainingSeconds: approvalRemaining,
2123
+ })
2124
+ ) {
2125
+ void firePlanApproval();
2126
+ }
2127
+ }, 1000);
2128
+ };
2129
+
2130
+ /**
2131
+ * Drop any pending approval *without* running it.
2132
+ *
2133
+ * Called at the top of every fresh submission. A prompt that outlived the
2134
+ * message it belonged to would otherwise answer the wrong turn: the user types
2135
+ * something new, the countdown they forgot about expires, and the stale plan
2136
+ * gets implemented instead of what they just asked for.
2137
+ */
2138
+ const resetApprovalGate = (): void => {
2139
+ if (pendingApproval || approvalTimer !== null || approvalText !== null) {
2140
+ dismissApprovalPrompt();
2141
+ }
2142
+ };
1443
2143
 
1444
2144
  editor.onSubmit = async (text) => {
1445
2145
  // `let` so `/plan <task>` and `/execute <task>` can rewrite the input and
@@ -1447,6 +2147,11 @@ async function main() {
1447
2147
  let trimmed = text.trim();
1448
2148
  if (!trimmed) return;
1449
2149
 
2150
+ // Submitting always means "show me the newest output": jump out of a
2151
+ // scrolled-back window before either queueing or starting the turn, so the
2152
+ // reply (or the queued marker) is never painted off-screen.
2153
+ snapToTail();
2154
+
1450
2155
  // A turn is running: the editor stays submittable — park the message on
1451
2156
  // the queue instead of starting a second turn. The settle path below
1452
2157
  // drains one message per settled turn (completion, error, or abort; an
@@ -1461,6 +2166,11 @@ async function main() {
1461
2166
  return;
1462
2167
  }
1463
2168
 
2169
+ // A fresh submission supersedes any approval still waiting on the previous
2170
+ // one — otherwise its countdown expires later and implements a plan the user
2171
+ // has already moved on from.
2172
+ resetApprovalGate();
2173
+
1464
2174
  editor.setText('');
1465
2175
 
1466
2176
  // ── Slash commands ──
@@ -1567,6 +2277,7 @@ async function main() {
1567
2277
  messagesContainer.addChild(
1568
2278
  new Text(`${c.green} Extensions reloaded (${toolCount} tools)${c.reset}`, 1, 0),
1569
2279
  );
2280
+ refreshToolTokenEstimate();
1570
2281
  } else {
1571
2282
  // Save session, then spawn a fresh process and exit.
1572
2283
  saveSession();
@@ -1593,6 +2304,9 @@ async function main() {
1593
2304
  state.currentTodos = [];
1594
2305
  state.permissionWhitelist = [];
1595
2306
  resetSessionTokenomics();
2307
+ // A new conversation gets a new provider session id, so prompt caching
2308
+ // starts from a clean shard instead of extending the previous one.
2309
+ resetProviderSession();
1596
2310
  refreshSidebar();
1597
2311
  updateStatusLine();
1598
2312
  messagesContainer.addChild(new Text(`${c.yellow}New session started.${c.reset}`, 1, 0));
@@ -1684,7 +2398,7 @@ async function main() {
1684
2398
  if (!level || !['low', 'medium', 'high'].includes(level)) {
1685
2399
  messagesContainer.addChild(
1686
2400
  new Text(
1687
- `${c.dim}Current reasoning effort: ${c.reset}${c.bold}${config.reasoningEffort}${c.reset}${c.dim}\nUsage: /effort low|medium|high${c.reset}`,
2401
+ `${c.dim}Current reasoning effort: ${c.reset}${c.bold}${config.reasoningEffort}${c.reset}${c.dim}\nUsage: /effort low|medium|high (default: ${DEFAULT_REASONING_EFFORT})${c.reset}`,
1688
2402
  1,
1689
2403
  0,
1690
2404
  ),
@@ -2211,7 +2925,6 @@ async function main() {
2211
2925
  * mode the agent switched to mid-conversation is honoured by the next turn.
2212
2926
  */
2213
2927
  const runTurn = async (message: string): Promise<void> => {
2214
- pendingExecution = false;
2215
2928
  state.activeAbort = new AbortController();
2216
2929
  state.statusReporter.report('working');
2217
2930
 
@@ -2320,32 +3033,57 @@ async function main() {
2320
3033
 
2321
3034
  await runTurn(trimmed);
2322
3035
 
2323
- // ── Auto-execute a finished plan ──
2324
- // The planning agent called exit_plan_mode, so a plan is ready. Implement it
2325
- // in the same submission instead of stopping and waiting for "go".
2326
- // Single-shot: a plan→execute→plan→execute chain within one message is
2327
- // refused by the `autoExecuted` guard above.
2328
- // The execution-mode re-assertion exists because the plan-mode switch's
2329
- // stop notice was the last turn-ending guidance the model saw.
2330
- if (pendingExecution && !autoExecuted) {
2331
- autoExecuted = true;
2332
- pendingExecution = false;
2333
- messagesContainer.addChild(
2334
- new Text(`${c.green} ▸ ${c.reset}${c.dim}plan approved — implementing…${c.reset}`, 1, 0),
2335
- );
2336
- tui.requestRender();
2337
- await runTurn(
2338
- 'Your plan above is approved. Implement it now, following that plan. ' +
2339
- 'Do not enter plan mode again for this task — carry it through to completion. ' +
2340
- 'You are now in execution mode. Work through the plan by calling tools until it is ' +
2341
- 'fully implemented — never end a turn with prose describing what you will do next; ' +
2342
- 'a turn may only end in prose when everything is done or a genuine question for the user.',
2343
- );
3036
+ // ── Plan approval gate ──
3037
+ // A planning agent that called exit_plan_mode switched back to an
3038
+ // executable role mid-turn (the `primary-request` listener parked that in
3039
+ // `pendingPlan`) but was NOT given consent: the model asked, so the user
3040
+ // decides. Now that the planning turn has settled and `isProcessing` is
3041
+ // false, show the y/n prompt. The implementation turn starts only from
3042
+ // `firePlanApproval` — the user's `y`, or the countdown after a timeout.
3043
+ //
3044
+ // Single-shot: `autoExecuted` blocks a plan → execute → plan → execute
3045
+ // chain within one user message.
3046
+ const planReady = pendingPlan;
3047
+ pendingPlan = false;
3048
+ if (planReady && !autoExecuted) {
3049
+ showApprovalPrompt(async () => {
3050
+ // The approval turn runs outside a submit, so `onSubmit`'s own
3051
+ // isProcessing raise never covered it — do it here, or a keystroke
3052
+ // during implementation could start a second concurrent turn.
3053
+ autoExecuted = true;
3054
+ isProcessing = true;
3055
+ try {
3056
+ await runTurn(APPROVAL_PROMPT);
3057
+ } finally {
3058
+ isProcessing = false;
3059
+ tui.requestRender();
3060
+ }
3061
+ });
2344
3062
  }
2345
3063
 
2346
3064
  isProcessing = false;
2347
3065
  tui.requestRender();
2348
3066
 
3067
+ // ── Settle-path approval re-check ──
3068
+ // The countdown is held while `isProcessing` (see `shouldAutoApprove`), so an
3069
+ // approval that expired during the turn above reached zero with nothing to
3070
+ // act on. Without this, that plan is silently lost: the prompt stays on
3071
+ // screen while implementing nothing, forever. Now that the turn is over the
3072
+ // held timeout resolves here instead of being dropped.
3073
+ //
3074
+ // `isProcessing` must already be false: `runTurn` is not re-entrant.
3075
+ if (shouldFireOnSettle({pending: pendingApproval, remainingSeconds: approvalRemaining})) {
3076
+ messagesContainer.addChild(
3077
+ new Text(
3078
+ `${c.dim} approval timed out — implementing the plan automatically${c.reset}`,
3079
+ 1,
3080
+ 0,
3081
+ ),
3082
+ );
3083
+ tui.requestRender();
3084
+ await firePlanApproval();
3085
+ }
3086
+
2349
3087
  // ── Drain queued messages ──
2350
3088
  // Every settle — completion, error, or abort — hands the next queued
2351
3089
  // message back to the normal submit path (identical to a fresh
@@ -2405,6 +3143,9 @@ async function main() {
2405
3143
  // Restore the terminal: leaving SGR mouse reporting on would make the
2406
3144
  // parent shell print raw mouse escape codes.
2407
3145
  disableMouse();
3146
+ // A selection left painted would keep reverse-video cells in the parent
3147
+ // shell's scrollback after pal exits. No repaint: the terminal is stopping.
3148
+ clearSelection(false);
2408
3149
  // Restore the terminal's own default fg/bg if startup canvas sync set
2409
3150
  // them (no-op when savedCanvas is null — vanilla / no-reply paths).
2410
3151
  restoreCanvas();