pal-code 0.0.13 → 0.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/packages/cli/src/components/assistant-body.ts +107 -8
- package/packages/cli/src/components/permission-prompt.ts +35 -19
- package/packages/cli/src/components/sidebar.ts +39 -22
- package/packages/cli/src/index.ts +456 -51
- package/packages/cli/src/overlays/model-picker.ts +6 -6
- package/packages/cli/src/overlays/session-picker.ts +6 -6
- package/packages/cli/src/state.ts +34 -0
- package/packages/cli/src/theme.ts +237 -71
- package/packages/cli/src/themes/github-dark.ts +174 -0
- package/packages/cli/src/themes/index.ts +36 -0
- package/packages/cli/src/themes/types.ts +192 -0
- package/packages/cli/src/themes/vanilla-pi.ts +175 -0
- package/packages/cli/src/tui/paint-panel.ts +20 -0
- package/packages/cli/src/tui/tty-width.ts +973 -0
- package/packages/cli/src/turn.ts +8 -0
- package/packages/cli/src/utils/code-block.ts +90 -13
- package/packages/cli/src/utils/format.ts +11 -7
- package/packages/cli/src/utils/highlight.ts +15 -15
- package/packages/cli/src/utils/osc-canvas.ts +102 -0
- package/packages/cli/src/utils/osc52.ts +32 -3
|
@@ -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 {
|
|
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,10 +46,19 @@ 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';
|
|
41
|
-
import {
|
|
54
|
+
import {
|
|
55
|
+
dequeueMessage,
|
|
56
|
+
enqueueMessage,
|
|
57
|
+
queuedStatusText,
|
|
58
|
+
resetSessionTokenomics,
|
|
59
|
+
setSessionTokenomics,
|
|
60
|
+
state,
|
|
61
|
+
} from './state.js';
|
|
42
62
|
import {Sidebar} from './components/sidebar.js';
|
|
43
63
|
import {cmdHelp, cmdCost} from './commands.js';
|
|
44
64
|
import {
|
|
@@ -49,7 +69,21 @@ import {
|
|
|
49
69
|
} from './commands/update-check.js';
|
|
50
70
|
import {showSessionSelector, cmdResume} from './overlays/session-picker.js';
|
|
51
71
|
import {loadCostManifest, estimateCost, isPricedModel} from './utils/cost.js';
|
|
52
|
-
import {
|
|
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';
|
|
53
87
|
import {openAgentsPanel, closeAgentsPanel} from './agent-panel.js';
|
|
54
88
|
import {
|
|
55
89
|
createOpenRouterProvider,
|
|
@@ -57,6 +91,7 @@ import {
|
|
|
57
91
|
hasAnyKey,
|
|
58
92
|
configPath,
|
|
59
93
|
saveSetting,
|
|
94
|
+
readPalConfig,
|
|
60
95
|
PROVIDERS,
|
|
61
96
|
loadCustomProviders,
|
|
62
97
|
providerForModel,
|
|
@@ -95,7 +130,27 @@ import type {SessionStore as SessionStoreType} from '@pal-code/core';
|
|
|
95
130
|
// (see buildModelOptions). Static curated lists live in @pal-code/core PROVIDERS as fallback.
|
|
96
131
|
|
|
97
132
|
// Version synced from version.json via `node scripts/sync-version.js`.
|
|
98
|
-
const VERSION = '0.0.
|
|
133
|
+
const VERSION = '0.0.15';
|
|
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
|
+
}
|
|
99
154
|
|
|
100
155
|
import {showModelSelector} from './overlays/model-picker.js';
|
|
101
156
|
import {showKeyInput} from './overlays/key-input.js';
|
|
@@ -123,6 +178,15 @@ async function main() {
|
|
|
123
178
|
|
|
124
179
|
const config = loadConfig();
|
|
125
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
|
+
|
|
126
190
|
// Load any user-defined custom providers from ~/.pal/providers.json
|
|
127
191
|
loadCustomProviders();
|
|
128
192
|
|
|
@@ -229,10 +293,9 @@ async function main() {
|
|
|
229
293
|
});
|
|
230
294
|
|
|
231
295
|
// ── Token / cost tracking ──
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
let totalCost = 0;
|
|
296
|
+
// Per-session stats live on `state.sessionTokenomics` (one state-owned
|
|
297
|
+
// object): accumulated per turn, zeroed on /new, restored on both resume
|
|
298
|
+
// paths, and persisted with the session row on every saveSession().
|
|
236
299
|
|
|
237
300
|
// ═══════════════════════════════════════════════════════════════
|
|
238
301
|
// TUI Setup
|
|
@@ -247,12 +310,16 @@ async function main() {
|
|
|
247
310
|
|
|
248
311
|
// ── Components ──
|
|
249
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)
|
|
250
315
|
const editor = new Editor(tui, editorTheme);
|
|
251
316
|
const statusLine = new StatusLine('');
|
|
252
317
|
const permissionPrompt = new PermissionPrompt();
|
|
253
318
|
state.permissionPrompt = permissionPrompt;
|
|
254
319
|
|
|
255
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)
|
|
256
323
|
const resolvedBase = providerForModel(config.model, Object.keys(allKeys));
|
|
257
324
|
const providerName = resolvedBase.provider.name;
|
|
258
325
|
messagesContainer.addChild(new Text(`${c.bold}${c.cyan}pal v${VERSION}${c.reset}`, 1, 0));
|
|
@@ -314,6 +381,10 @@ async function main() {
|
|
|
314
381
|
// The sidebar is a separate overlay and is never part of this column.
|
|
315
382
|
let scrollOffset = 0;
|
|
316
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
|
+
|
|
317
388
|
const pinnedLayout = {
|
|
318
389
|
render(width: number): string[] {
|
|
319
390
|
const inset = sidebarWidthFor(width);
|
|
@@ -392,23 +463,50 @@ async function main() {
|
|
|
392
463
|
return v === '1' || v === 'true';
|
|
393
464
|
})();
|
|
394
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;
|
|
395
475
|
const enableMouse = (): void => {
|
|
396
476
|
if (mouseEnabled || mouseDisabled) return;
|
|
397
477
|
mouseEnabled = true;
|
|
398
|
-
|
|
399
|
-
|
|
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');
|
|
400
482
|
};
|
|
401
483
|
const disableMouse = (): void => {
|
|
402
484
|
if (!mouseEnabled) return;
|
|
403
485
|
mouseEnabled = false;
|
|
404
|
-
|
|
486
|
+
mouseTracked = false;
|
|
487
|
+
clearHover();
|
|
488
|
+
terminal.write('\x1b[?1000l\x1b[?1003l\x1b[?1006l');
|
|
405
489
|
};
|
|
406
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
|
+
|
|
407
496
|
const scrollBy = (delta: number): void => {
|
|
408
497
|
const next = Math.max(0, scrollOffset + delta);
|
|
409
498
|
if (next === scrollOffset) return;
|
|
410
499
|
scrollOffset = next;
|
|
411
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
|
+
}
|
|
412
510
|
};
|
|
413
511
|
|
|
414
512
|
const pageRows = (): number => {
|
|
@@ -416,19 +514,190 @@ async function main() {
|
|
|
416
514
|
return Math.max(1, terminal.rows - editorLines - 2);
|
|
417
515
|
};
|
|
418
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
|
+
|
|
419
666
|
tui.addInputListener((data) => {
|
|
420
667
|
// SGR mouse: ESC [ < b ; x ; y M|m (preferred, enabled via ?1006h)
|
|
421
|
-
const mouse = data.startsWith('\x1b[<')
|
|
668
|
+
const mouse = data.startsWith('\x1b[<')
|
|
669
|
+
? data.slice(3).match(/^(\d+);(\d+);(\d+)([Mm])$/)
|
|
670
|
+
: null;
|
|
422
671
|
if (mouse) {
|
|
423
|
-
const
|
|
424
|
-
|
|
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) {
|
|
425
680
|
scrollBy(3); // wheel up
|
|
426
681
|
return {consume: true};
|
|
427
682
|
}
|
|
428
|
-
if (
|
|
683
|
+
if ((raw & 64) !== 0 && (raw & 3) === 1) {
|
|
429
684
|
scrollBy(-3); // wheel down
|
|
430
685
|
return {consume: true};
|
|
431
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
|
+
}
|
|
432
701
|
return {consume: true}; // swallow other mouse events
|
|
433
702
|
}
|
|
434
703
|
// Legacy X10 mouse: ESC [ M followed by three bytes; button code is the
|
|
@@ -525,6 +794,7 @@ async function main() {
|
|
|
525
794
|
{name: 'resume', description: 'Load a previous session'},
|
|
526
795
|
{name: 'cost', description: 'Show token usage and cost'},
|
|
527
796
|
{name: 'model', description: 'Switch model'},
|
|
797
|
+
{name: 'theme', description: 'Switch color theme (vanilla-pi, github-dark)'},
|
|
528
798
|
{name: 'ext', description: 'Manage extensions'},
|
|
529
799
|
{name: 'export', description: 'Export config to a versionable JSON file'},
|
|
530
800
|
{name: 'import', description: 'Import config from an export file'},
|
|
@@ -553,11 +823,11 @@ async function main() {
|
|
|
553
823
|
// Background sub-agents (ctrl+b opens the panel).
|
|
554
824
|
const running = state.backgroundAgents.filter((a) => a.status === 'running').length;
|
|
555
825
|
const agentStr = state.backgroundAgents.length
|
|
556
|
-
? ` ${
|
|
826
|
+
? ` ${surface.statusLine.warn}⛭ ${running}/${state.backgroundAgents.length} agents${c.reset}`
|
|
557
827
|
: '';
|
|
558
828
|
const sub = getSubagentStatus();
|
|
559
829
|
const subLine = subagentStatusText(sub.active, sub.startedAt);
|
|
560
|
-
const subStr = subLine ? ` ${
|
|
830
|
+
const subStr = subLine ? ` ${surface.statusLine.warn}${subLine}${c.reset}` : '';
|
|
561
831
|
// The status line now only carries identity/nav; token, cost and context
|
|
562
832
|
// usage live in the sidebar's Info block.
|
|
563
833
|
//
|
|
@@ -565,33 +835,49 @@ async function main() {
|
|
|
565
835
|
// while the centered modal (PermissionPrompt) handles the full prompt.
|
|
566
836
|
if (state.overlayMode === 'permission' && state.pendingPermission) {
|
|
567
837
|
statusLine.setText(
|
|
568
|
-
`${
|
|
838
|
+
`${surface.statusLine.warn}🔒 Awaiting permission...${c.reset} ${c.dim}[y/a/n/Esc]${c.reset}`,
|
|
569
839
|
);
|
|
570
840
|
} else if (scrollOffset > 0) {
|
|
571
841
|
// Scrolled back through the transcript — surface the way out so the
|
|
572
842
|
// user isn't stranded in scroll mode.
|
|
573
843
|
statusLine.setText(
|
|
574
|
-
`${
|
|
844
|
+
`${surface.statusLine.info}↕ scrolled${c.reset} ${c.dim}· PgDn/↓ End or Esc to resume${c.reset}`,
|
|
575
845
|
);
|
|
576
846
|
} else {
|
|
577
847
|
// `queued (N)` — messages submitted while a turn runs (drained on
|
|
578
848
|
// settle). Empty at N=0, so the idle status line stays byte-identical.
|
|
579
849
|
const queuedText = queuedStatusText(state.pendingMessages.length);
|
|
580
|
-
const queuedStr = queuedText ? ` ${
|
|
850
|
+
const queuedStr = queuedText ? ` ${surface.statusLine.warn}${queuedText}${c.reset}` : '';
|
|
581
851
|
statusLine.setText(
|
|
582
|
-
`${modelShort} ${
|
|
852
|
+
`${modelShort} ${surface.statusLine.dim}${providerName}${agentStr}${subStr}${queuedStr}${c.reset} ${surface.statusLine.dim}/help${c.reset}`,
|
|
583
853
|
);
|
|
584
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);
|
|
585
858
|
sidebar.setStats({
|
|
586
|
-
inputTokens:
|
|
587
|
-
outputTokens:
|
|
588
|
-
cachedTokens:
|
|
589
|
-
cost:
|
|
859
|
+
inputTokens: state.sessionTokenomics.inputTokens,
|
|
860
|
+
outputTokens: state.sessionTokenomics.outputTokens,
|
|
861
|
+
cachedTokens: state.sessionTokenomics.cachedTokens,
|
|
862
|
+
cost: state.sessionTokenomics.cost,
|
|
590
863
|
contextPct,
|
|
591
864
|
priced: isPricedModel(config.model),
|
|
592
865
|
});
|
|
593
866
|
tui.requestRender();
|
|
594
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
|
+
|
|
595
881
|
// Expose to module-level overlay handlers (model picker, agent panel).
|
|
596
882
|
state.refreshStatusLine = updateStatusLine;
|
|
597
883
|
state.refreshSidebar = () => sidebar.refresh();
|
|
@@ -624,12 +910,7 @@ async function main() {
|
|
|
624
910
|
// ── Session persistence helper ──
|
|
625
911
|
function saveSession() {
|
|
626
912
|
if (messages.length > 0 && store) {
|
|
627
|
-
const tok = {
|
|
628
|
-
inputTokens: totalInputTokens,
|
|
629
|
-
outputTokens: totalOutputTokens,
|
|
630
|
-
cachedTokens: totalCachedTokens,
|
|
631
|
-
cost: totalCost,
|
|
632
|
-
};
|
|
913
|
+
const tok = {...state.sessionTokenomics};
|
|
633
914
|
// Metadata for repaint: tool names/status derived from the messages, plus
|
|
634
915
|
// the agent role recorded for each user turn.
|
|
635
916
|
const meta = deriveMessageMeta(messages).map((m, i) => {
|
|
@@ -710,12 +991,7 @@ async function main() {
|
|
|
710
991
|
const session = s.get(sessionId);
|
|
711
992
|
if (!session) return;
|
|
712
993
|
if (messages.length > 0 && currentSessionId) {
|
|
713
|
-
s.update(currentSessionId, messages, {
|
|
714
|
-
inputTokens: totalInputTokens,
|
|
715
|
-
outputTokens: totalOutputTokens,
|
|
716
|
-
cachedTokens: totalCachedTokens,
|
|
717
|
-
cost: totalCost,
|
|
718
|
-
});
|
|
994
|
+
s.update(currentSessionId, messages, {...state.sessionTokenomics});
|
|
719
995
|
}
|
|
720
996
|
messages.length = 0;
|
|
721
997
|
messages.push(...(session.messages as Message[]));
|
|
@@ -723,11 +999,7 @@ async function main() {
|
|
|
723
999
|
currentSessionId = session.id;
|
|
724
1000
|
state.sessionTitle = session.title ?? null;
|
|
725
1001
|
// Restore tokenomics from the resumed session.
|
|
726
|
-
|
|
727
|
-
totalInputTokens = tok.inputTokens;
|
|
728
|
-
totalOutputTokens = tok.outputTokens;
|
|
729
|
-
totalCachedTokens = tok.cachedTokens;
|
|
730
|
-
totalCost = tok.cost;
|
|
1002
|
+
setSessionTokenomics(session.tokenomics);
|
|
731
1003
|
// The in-memory todo plan belongs to the previous conversation.
|
|
732
1004
|
clearTodos();
|
|
733
1005
|
state.currentTodos = [];
|
|
@@ -1148,7 +1420,9 @@ async function main() {
|
|
|
1148
1420
|
clearTodos();
|
|
1149
1421
|
state.currentTodos = [];
|
|
1150
1422
|
state.permissionWhitelist = [];
|
|
1423
|
+
resetSessionTokenomics();
|
|
1151
1424
|
refreshSidebar();
|
|
1425
|
+
updateStatusLine();
|
|
1152
1426
|
messagesContainer.addChild(new Text(`${c.yellow}New session started.${c.reset}`, 1, 0));
|
|
1153
1427
|
tui.requestRender();
|
|
1154
1428
|
return;
|
|
@@ -1318,10 +1592,61 @@ async function main() {
|
|
|
1318
1592
|
messagesContainer,
|
|
1319
1593
|
tui,
|
|
1320
1594
|
);
|
|
1595
|
+
// cmdResume only swaps in the messages — pull the resumed session's
|
|
1596
|
+
// token stats too (zeros when the lookup failed and nothing resumed).
|
|
1597
|
+
const resumed = currentSessionId ? store.get(currentSessionId) : null;
|
|
1598
|
+
if (resumed) setSessionTokenomics(resumed.tokenomics);
|
|
1599
|
+
else resetSessionTokenomics();
|
|
1600
|
+
updateStatusLine();
|
|
1321
1601
|
return;
|
|
1322
1602
|
}
|
|
1323
1603
|
if (trimmed === '/cost') {
|
|
1324
|
-
|
|
1604
|
+
const tok = state.sessionTokenomics;
|
|
1605
|
+
cmdCost(tok.inputTokens, tok.outputTokens, tok.cost, config.model, messagesContainer, tui);
|
|
1606
|
+
return;
|
|
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();
|
|
1325
1650
|
return;
|
|
1326
1651
|
}
|
|
1327
1652
|
if (trimmed === '/model' || trimmed === '/model ') {
|
|
@@ -1659,16 +1984,17 @@ async function main() {
|
|
|
1659
1984
|
state.lastRun = state.activeRun; // ctrl+o can re-inflate this run
|
|
1660
1985
|
}
|
|
1661
1986
|
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1987
|
+
const tok = state.sessionTokenomics;
|
|
1988
|
+
tok.inputTokens += result.inputTokens;
|
|
1989
|
+
tok.cachedTokens += result.cachedTokens;
|
|
1990
|
+
tok.outputTokens += result.outputTokens;
|
|
1665
1991
|
const turnCost = estimateCost(
|
|
1666
1992
|
result.model,
|
|
1667
1993
|
result.inputTokens,
|
|
1668
1994
|
result.outputTokens,
|
|
1669
1995
|
result.cachedTokens,
|
|
1670
1996
|
);
|
|
1671
|
-
|
|
1997
|
+
tok.cost += turnCost;
|
|
1672
1998
|
|
|
1673
1999
|
updateStatusLine();
|
|
1674
2000
|
saveSession();
|
|
@@ -1716,6 +2042,8 @@ async function main() {
|
|
|
1716
2042
|
// in the same submission instead of stopping and waiting for "go".
|
|
1717
2043
|
// Single-shot: a plan→execute→plan→execute chain within one message is
|
|
1718
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.
|
|
1719
2047
|
if (pendingExecution && !autoExecuted) {
|
|
1720
2048
|
autoExecuted = true;
|
|
1721
2049
|
pendingExecution = false;
|
|
@@ -1725,7 +2053,10 @@ async function main() {
|
|
|
1725
2053
|
tui.requestRender();
|
|
1726
2054
|
await runTurn(
|
|
1727
2055
|
'Your plan above is approved. Implement it now, following that plan. ' +
|
|
1728
|
-
'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.',
|
|
1729
2060
|
);
|
|
1730
2061
|
}
|
|
1731
2062
|
|
|
@@ -1788,7 +2119,77 @@ async function main() {
|
|
|
1788
2119
|
// Restore the terminal: leaving SGR mouse reporting on would make the
|
|
1789
2120
|
// parent shell print raw mouse escape codes.
|
|
1790
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();
|
|
1791
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
|
+
}
|
|
1792
2193
|
}
|
|
1793
2194
|
|
|
1794
2195
|
main().catch((err) => {
|
|
@@ -1796,8 +2197,12 @@ main().catch((err) => {
|
|
|
1796
2197
|
// the terminal in raw mode with SGR mouse reporting on. Restore both so the
|
|
1797
2198
|
// parent shell remains usable.
|
|
1798
2199
|
try {
|
|
1799
|
-
// 1. Disable SGR mouse reporting (?1000
|
|
1800
|
-
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();
|
|
1801
2206
|
// 2. Restore cooked (normal) terminal mode — the inverse of raw mode.
|
|
1802
2207
|
// This is the canonical way to undo process.stdin.setRawMode(true).
|
|
1803
2208
|
if (process.stdin.isTTY) process.stdin.setRawMode(false);
|