pal-code 0.0.16 → 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/package.json +2 -2
  2. package/packages/cli/src/agent-panel.ts +1 -1
  3. package/packages/cli/src/commands.ts +1 -1
  4. package/packages/cli/src/components/assistant-body.ts +2 -2
  5. package/packages/cli/src/components/message-box.ts +1 -1
  6. package/packages/cli/src/components/permission-prompt.ts +3 -3
  7. package/packages/cli/src/components/render-history.ts +13 -12
  8. package/packages/cli/src/components/run-view.ts +109 -33
  9. package/packages/cli/src/components/sidebar.ts +73 -12
  10. package/packages/cli/src/components/status-line.ts +3 -3
  11. package/packages/cli/src/config.ts +1 -1
  12. package/packages/cli/src/index.ts +65 -27
  13. package/packages/cli/src/overlays/key-input.ts +2 -1
  14. package/packages/cli/src/overlays/model-picker.ts +2 -1
  15. package/packages/cli/src/overlays/session-picker.ts +3 -2
  16. package/packages/cli/src/state.ts +12 -0
  17. package/packages/cli/src/theme.ts +13 -1
  18. package/packages/cli/src/themes/github-dark.ts +14 -3
  19. package/packages/cli/src/themes/types.ts +26 -2
  20. package/packages/cli/src/themes/vanilla-pi.ts +23 -9
  21. package/packages/cli/src/tui/components/text.ts +102 -0
  22. package/packages/cli/src/tui/render/code-block.ts +325 -0
  23. package/packages/cli/src/{utils → tui/render}/format.ts +31 -24
  24. package/packages/cli/src/{utils → tui/render}/highlight.ts +94 -2
  25. package/packages/cli/src/tui/surface/index.ts +9 -0
  26. package/packages/cli/src/tui/{paint-panel.ts → surface/paint-panel.ts} +1 -1
  27. package/packages/cli/src/tui/theme-types.ts +59 -0
  28. package/packages/cli/src/tui/tty-width.ts +20 -0
  29. package/packages/cli/src/tui/types.ts +53 -0
  30. package/packages/cli/src/turn.ts +13 -7
  31. package/packages/cli/src/utils/code-block.ts +0 -200
@@ -0,0 +1,53 @@
1
+ /**
2
+ * pi-tui-free rendering contracts.
3
+ *
4
+ * The interfaces a renderer needs in order to be driven by a terminal UI
5
+ * engine. These are structural, not nominal: anything with `render(width)`
6
+ * and optionally `invalidate()` satisfies them, so components written against
7
+ * pi-tui keep working unchanged while the engine underneath can be replaced.
8
+ *
9
+ * Adapted from @earendil-works/pi-tui's `dist/tui.d.ts` (MIT,
10
+ * © Mario Zechner, https://github.com/earendil-works/pi).
11
+ */
12
+
13
+ /** Mouse event kinds delivered to components that opt in. */
14
+ export type TuiMouseEventType = 'down' | 'up' | 'move' | 'drag' | 'wheel-up' | 'wheel-down';
15
+
16
+ /** Normalized mouse event, independent of the terminal's reporting format. */
17
+ export interface TuiMouseEvent {
18
+ type: TuiMouseEventType;
19
+ /** Zero-based cell column. */
20
+ x: number;
21
+ /** Zero-based cell row. */
22
+ y: number;
23
+ button?: number;
24
+ }
25
+
26
+ /** What a component did with a mouse event. */
27
+ export type TuiMouseEventResult = {
28
+ handled: boolean;
29
+ /** Stop dispatching this event to components below. */
30
+ consume?: boolean;
31
+ };
32
+
33
+ /**
34
+ * A renderable unit.
35
+ *
36
+ * `render` returns one string per terminal row, each already padded to (or at
37
+ * least valid at) `width` visible columns. Returning `[]` makes the component
38
+ * invisible without removing it from the tree.
39
+ */
40
+ export interface Component {
41
+ render(width: number): string[];
42
+ /** Optional handler for keyboard input while this component has focus. */
43
+ handleInput?(data: string): void;
44
+ /** Optional normalized mouse handler. */
45
+ handleMouse?(event: TuiMouseEvent): TuiMouseEventResult | undefined;
46
+ /**
47
+ * If true, the component receives key release events (Kitty protocol).
48
+ * Default is false — release events are filtered out.
49
+ */
50
+ wantsKeyRelease?: boolean;
51
+ /** Drop any cached rendering. */
52
+ invalidate?(): void;
53
+ }
@@ -40,8 +40,8 @@ export interface TurnResult {
40
40
  cachedTokens: number;
41
41
  /** The model that actually served this turn (may differ from config.model after a fallback). */
42
42
  model: string;
43
- /** Set when this turn compacted older history into a checkpoint. */
44
- compaction?: {boundary: number; summary: string};
43
+ /** Checkpoints this turn produced (auto-compaction can fire more than once). */
44
+ compactions: Array<{boundary: number; summarized: number; summary: string}>;
45
45
  }
46
46
 
47
47
  let extensionsLoaded = false;
@@ -246,7 +246,7 @@ export async function agentLoop(
246
246
 
247
247
  let usage = {inputTokens: 0, outputTokens: 0, cachedTokens: 0};
248
248
  let activeModel = config.model;
249
- let compaction: {boundary: number; summary: string} | undefined;
249
+ const compactions: TurnResult['compactions'] = [];
250
250
 
251
251
  for await (const ev of runWithFallback({
252
252
  messages,
@@ -274,11 +274,17 @@ export async function agentLoop(
274
274
  run.setModel(shortModel(ev.model));
275
275
  } else if (ev.type === 'round-start') run.beginRound(ev.round, ev.max);
276
276
  else if (ev.type === 'text-delta') run.streamText(ev.content);
277
+ else if (ev.type === 'thinking-delta') run.streamThinking(ev.content);
277
278
  else if (ev.type === 'tool-start') run.addTool(ev.id, ev.name, ev.argsSummary);
278
279
  else if (ev.type === 'tool-end') run.endTool(ev.id, ev.ok, ev.content);
279
- else if (ev.type === 'notice') run.notice(ev.text);
280
- else if (ev.type === 'compacted') compaction = {boundary: ev.boundary, summary: ev.summary};
281
- else if (ev.type === 'aborted') run.aborted();
280
+ else if (ev.type === 'notice') {
281
+ // The compaction notice is superseded by the green transcript line the
282
+ // caller prints after the turn — this dim inline copy vanished with the
283
+ // run block's collapse, which is why auto-compaction looked silent.
284
+ if (!ev.text.startsWith('Context compacted')) run.notice(ev.text);
285
+ } else if (ev.type === 'compacted') {
286
+ compactions.push({boundary: ev.boundary, summarized: ev.summarized, summary: ev.summary});
287
+ } else if (ev.type === 'aborted') run.aborted();
282
288
  else if (ev.type === 'done') usage = ev.usage;
283
289
  }
284
290
 
@@ -287,6 +293,6 @@ export async function agentLoop(
287
293
  outputTokens: usage.outputTokens,
288
294
  cachedTokens: usage.cachedTokens,
289
295
  model: activeModel,
290
- compaction,
296
+ compactions,
291
297
  };
292
298
  }
@@ -1,200 +0,0 @@
1
- /**
2
- * Fenced code blocks in the transcript: segmentation + boxed rendering.
3
- *
4
- * Both exports are pure and deterministic — same input bytes → same output
5
- * bytes, no clock or randomness. Hover/success paint arrives as explicit
6
- * `opts` parameters, never as ambient state, so the TUI can repaint
7
- * differentially and the components can cache by width without desyncing
8
- * the screen from the cache.
9
- */
10
-
11
- import {truncateToWidth} from '../tui/tty-width.js';
12
-
13
- import {c, codebox} from '../theme.js';
14
- import {buildHeader, displayWidth, wrapText} from './format.js';
15
- import {highlightCode} from './highlight.js';
16
-
17
- /** One piece of an assistant message: prose, or a fenced code block. */
18
- export type CodeSegment =
19
- | {readonly kind: 'text'; readonly text: string}
20
- | {readonly kind: 'code'; readonly lang: string; readonly lines: readonly string[]};
21
-
22
- /** Right-edge copy affordance drawn in rendered code-block headers. */
23
- export const COPY_LABEL = '⧉ copy';
24
-
25
- /** Header label once the copy succeeded — wider than COPY_LABEL, so the
26
- * dash run and copy zone must recompute from it. */
27
- export const SUCCESS_LABEL = '✓ copied';
28
-
29
- /**
30
- * Screen geometry of the header copy zone: the rightmost columns of the
31
- * header row — the label plus the closing corner (`⧉ copy╮`). Returns null
32
- * when disabled or when the box is too narrow for the label plus at least
33
- * one dash. Measured with `displayWidth` (=== `visibleWidth`), so the
34
- * renderer and the click hit-test always agree on the same columns even if
35
- * the label's ambiguous-width glyph is measured differently than expected.
36
- * `label` defaults to COPY_LABEL; pass SUCCESS_LABEL while the success
37
- * chip is painted so the hit-test follows the reflowed zone.
38
- */
39
- export function copyZoneRect(
40
- W: number,
41
- tag: string,
42
- enabled: boolean,
43
- label = COPY_LABEL,
44
- ): {startCol: number; width: number} | null {
45
- const tagW = displayWidth(tag.trim());
46
- const tagged = tag.trim() !== '' && tagW + 6 <= W;
47
- const dashes = tagged ? W - tagW - 5 : W - 2;
48
- const labelW = displayWidth(label);
49
- if (!enabled || dashes - labelW < 1) return null;
50
- return {startCol: W - labelW - 1, width: labelW + 1};
51
- }
52
-
53
- /**
54
- * Re-open the surface fill after every full reset inside a row, so a
55
- * mid-line `\x1b[0m` (highlightCode emits them around every token) never
56
- * leaves a cell on the terminal default background. Callers append the
57
- * row's single final reset after this pass.
58
- */
59
- function keepSurface(s: string): string {
60
- return s.split(c.reset).join(c.reset + codebox.surfaceBg);
61
- }
62
-
63
- // Opening fence: up to 3 leading spaces, 3+ backticks, then an info string
64
- // that must not itself contain backticks (CommonMark) — so a line like
65
- // "```code```" mid-paragraph stays prose.
66
- const OPEN_FENCE = /^ {0,3}(`{3,})([^`]*)$/;
67
- // Closing fence: backticks and whitespace only, and never shorter than the opener.
68
- const CLOSE_FENCE = /^ {0,3}(`{3,})[ \t]*$/;
69
-
70
- function trimBlankEdges(lines: readonly string[]): readonly string[] {
71
- let start = 0;
72
- let end = lines.length;
73
- while (start < end && (lines[start] ?? '').trim() === '') start++;
74
- while (end > start && (lines[end - 1] ?? '').trim() === '') end--;
75
- return lines.slice(start, end);
76
- }
77
-
78
- /**
79
- * Split markdown into prose and fenced code segments.
80
- *
81
- * Handles the edge cases that show up in real model output: an unclosed
82
- * fence at the end of the message (runs to end), no language tag, padded or
83
- * mixed-case tags, fences that interrupt a paragraph, CRLF endings, and
84
- * longer (````) fences whose content contains triple backticks.
85
- */
86
- export function parseCodeSegments(text: string): CodeSegment[] {
87
- const segments: CodeSegment[] = [];
88
- let textLines: string[] = [];
89
- let fence: {ticks: number; lang: string; lines: string[]} | null = null;
90
-
91
- const flushText = (): void => {
92
- const kept = trimBlankEdges(textLines);
93
- textLines = [];
94
- if (kept.length > 0) segments.push({kind: 'text', text: kept.join('\n')});
95
- };
96
-
97
- for (const line of text.split(/\r\n|\r|\n/)) {
98
- if (fence) {
99
- const close = CLOSE_FENCE.exec(line);
100
- if (close && (close[1] ?? '').length >= fence.ticks) {
101
- segments.push({kind: 'code', lang: fence.lang, lines: fence.lines});
102
- fence = null;
103
- } else {
104
- fence.lines.push(line);
105
- }
106
- continue;
107
- }
108
-
109
- const open = OPEN_FENCE.exec(line);
110
- if (open) {
111
- flushText();
112
- const info = (open[2] ?? '').trim();
113
- fence = {
114
- ticks: (open[1] ?? '').length,
115
- lang: info.split(/\s+/)[0] ?? '',
116
- lines: [],
117
- };
118
- continue;
119
- }
120
- textLines.push(line);
121
- }
122
-
123
- if (fence) segments.push({kind: 'code', lang: fence.lang, lines: fence.lines});
124
- flushText();
125
- return segments;
126
- }
127
-
128
- /**
129
- * Render one fenced code segment as a bordered, language-tagged box:
130
- *
131
- * ╭─ typescript ────────╮
132
- * │ const x = 1; │
133
- * ╰─────────────────────╯
134
- *
135
- * Geometry mirrors `userMessageBox` (same W/inner/textWidth clamps, same
136
- * `buildHeader` degradation on narrow widths) so every transcript box lines
137
- * up. Code is syntax-highlighted via the existing `highlightCode` helper,
138
- * then wrapped and hard-truncated to the box — no row ever exceeds `width`.
139
- */
140
- export function codeBlockBox(
141
- code: string,
142
- width: number,
143
- lang = '',
144
- opts?: {copy?: boolean; hover?: boolean; success?: boolean},
145
- ): string {
146
- // One clamp before anything is derived, so header/body/footer agree.
147
- const W = Math.max(6, Math.floor(width));
148
- const inner = W - 4; // columns between "│ " and " │"
149
- const textWidth = Math.max(1, inner - 1); // reserve the last inner column
150
-
151
- const tag = lang.trim();
152
- const hover = opts?.hover === true;
153
- const success = opts?.success === true;
154
- // Every row opens the surface fill once; `paint` switches only the
155
- // foreground role, and `finish` re-opens the fill after any embedded
156
- // reset before closing the row with a single trailing reset.
157
- const bg = codebox.surfaceBg;
158
- const paint = (s: string): string => `${bg}${codebox.borderFg}${s}`;
159
- const finish = (line: string): string => `${keepSurface(line)}${c.reset}`;
160
-
161
- // Copy affordance: pin the label at the right edge of the header (zone
162
- // includes the closing ╮) while the visible width stays exactly W.
163
- // Chip precedence: success > hover > idle — success swaps both the
164
- // label and the fg, and the zone reflows from the wider label.
165
- const labelText = success ? SUCCESS_LABEL : COPY_LABEL;
166
- const zone = copyZoneRect(W, tag, opts?.copy === true, labelText);
167
- const tagW = displayWidth(tag);
168
- const labelW = displayWidth(labelText);
169
- const chipBg = hover && !success ? codebox.chipBgHover : codebox.chipBgIdle;
170
- const chipFg = success ? codebox.successFg : hover ? codebox.chipFgHover : codebox.chipFgIdle;
171
- const chip = `${chipBg}${chipFg}${labelText}`;
172
-
173
- let header: string;
174
- if (!zone) {
175
- header = tag
176
- ? finish(buildHeader(W, tag, tagW, codebox.langFg, paint, ''))
177
- : finish(paint(`╭${'─'.repeat(W - 2)}╮`));
178
- } else if (tag !== '' && tagW + 6 <= W) {
179
- const dashes = W - tagW - 5 - labelW;
180
- header = finish(
181
- `${paint('╭─')} ${codebox.langFg}${tag}${c.reset} ${paint('─'.repeat(dashes))}` +
182
- `${chip}${paint('╮')}`,
183
- );
184
- } else {
185
- const dashes = W - 2 - labelW;
186
- header = finish(`${paint(`╭${'─'.repeat(dashes)}`)}${chip}${paint('╮')}`);
187
- }
188
-
189
- const body = wrapText(highlightCode(code, tag || undefined).join('\n'), textWidth)
190
- .map((line) => {
191
- const safe = truncateToWidth(line.trimEnd(), textWidth, '');
192
- const pad = Math.max(0, inner - displayWidth(safe));
193
- return finish(`${paint('│')} ${safe}${c.reset}${' '.repeat(pad)} ${paint('│')}`);
194
- })
195
- .join('\n');
196
-
197
- const footer = finish(paint(`╰${'─'.repeat(W - 2)}╯`));
198
-
199
- return `${header}\n${body}\n${footer}`;
200
- }