@aeondave/pi-theme-1337 0.5.1 → 0.6.0

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.
@@ -1,491 +1,491 @@
1
- import type { ToolRenderers } from "@earendil-works/pi-coding-agent";
2
- import type { Box, Component, Container, Text } from "@earendil-works/pi-tui";
3
- import { sanitizeArtLine, sanitizeInlineText } from "./format.ts";
4
- import type { GroupControl, GroupDecision } from "./tool-groups.ts";
5
- import { createRunSummaryView, flatInnerWidth, flatRow, resultRole, statusRole, type FlatRow } from "./tool-view.ts";
6
- import { clipTextRows, isImageProtocolLine, visibleWidth } from "./width.ts";
7
-
8
- export interface ToolAdapterDependencies {
9
- Box: typeof Box;
10
- Container: typeof Container;
11
- Text: typeof Text;
12
- toolName: string;
13
- expandHint?: () => string;
14
- imagesSupported?: () => boolean;
15
- /**
16
- * Folded exploration runs (presentation of the transcript itself). Only the
17
- * polished lane's call slot consults it: the baseline lane always renders the host rows.
18
- */
19
- groups?: GroupControl;
20
- }
21
-
22
- type Call = NonNullable<ToolRenderers["renderCall"]>;
23
- type Context = Parameters<Call>[2];
24
- type Theme = Parameters<Call>[1];
25
- type Result = Parameters<NonNullable<ToolRenderers["renderResult"]>>[0];
26
- type MouseEvent = Parameters<NonNullable<Component["handleMouse"]>>[0];
27
- type Lane = {
28
- renderers: ToolRenderers;
29
- state: Record<string, unknown>;
30
- call?: Component;
31
- result?: Component;
32
- lastCall?: Component;
33
- lastResult?: Component;
34
- callArgs?: unknown;
35
- callFallback?: Component;
36
- callFallbackTheme?: Theme;
37
- resultValue?: Result;
38
- resultFallback?: Component;
39
- resultFallbackKey?: { result: Result; expanded: boolean; showImages: boolean; imagesSupported: boolean; theme: Theme };
40
- };
41
- /**
42
- * One slot's shell, kept across frames so pi-tui's Box cache can hit, and the last
43
- * clip. The shell still renders every frame (children may change their own lines
44
- * silently); only an identical row of identical lines at the same width reuses the clip.
45
- */
46
- type Slot = {
47
- shell?: Box | Container;
48
- lane?: Lane;
49
- children?: Component[];
50
- pad?: number;
51
- clip?: { width: number; input: string[]; output: string[] };
52
- flat?: FlatMemo;
53
- };
54
- /**
55
- * The flat shell's last frame: what it was composed from and the composed row.
56
- * The renderer's lines are copied, not kept by reference — a component may
57
- * rewrite its own array in place, and a memo holding that array would match
58
- * itself. The components are kept only to route a click to the one under it.
59
- */
60
- type FlatMemo = {
61
- width: number;
62
- pad: unknown;
63
- theme: Theme;
64
- dot: string;
65
- connector: string;
66
- call: string[];
67
- result: string[];
68
- callChild: Component;
69
- resultChild: Component;
70
- row: FlatRow;
71
- };
72
- const empty: Component = { render: () => [], invalidate() {} };
73
- const normal: GroupDecision = { kind: "normal" };
74
- const noLines: string[] = [];
75
- function sameLines(last: string[], lines: string[]): boolean {
76
- if (last.length !== lines.length) return false;
77
- for (let i = 0; i < lines.length; i++) if (last[i] !== lines[i]) return false;
78
- return true;
79
- }
80
-
81
- function allFit(lines: string[], width: number): boolean {
82
- for (const line of lines) if (!isImageProtocolLine(line) && visibleWidth(line) > width) return false;
83
- return true;
84
- }
85
-
86
- /**
87
- * A renderer's `render()` is typed `string[]`, but the lines are a third party's:
88
- * one that is not a string (`[undefined, "x"]`) must never reach a string method here.
89
- */
90
- const isText = (line: unknown): line is string => typeof line === "string";
91
- /** A line the flat shell can neither prefix nor clip: an image-protocol payload, or not text at all. */
92
- const isUnframeable = (line: unknown): boolean => !isText(line) || isImageProtocolLine(line);
93
-
94
- function clipOnce(slot: Slot, lines: string[], width: number): string[] {
95
- const last = slot.clip;
96
- if (last && last.width === width && sameLines(last.input, lines)) return last.output;
97
- // Measuring a styled line is the host ruler's fast path, truncating one is not:
98
- // rows that all fit (every row a well-behaved shell returns) are passed on as they are.
99
- // So is a self-framed row holding a line that is not text: the host hands those on
100
- // untouched too, and there is nothing here to measure (the host's Box turns them into text).
101
- const output = !lines.every(isText) || allFit(lines, width) ? lines : clipTextRows(lines, width);
102
- // Kept by reference: Box reuses an array only for identical lines, Container never does.
103
- slot.clip = { width, input: lines, output };
104
- return output;
105
- }
106
-
107
- /**
108
- * Pi fixes the shell when a row is constructed. Keep it self-owned forever and
109
- * switch the *contents*, not the descriptor, when /theme-1337 changes state.
110
- *
111
- * Both lanes receive every host callback, even when hidden: native renderers may
112
- * need their final callback to stop a partial-result timer. Each lane has its own
113
- * state and lastComponent slots, owned solely by the host's per-row state. No
114
- * execution data is changed and images remain entirely ToolExecutionComponent's.
115
- *
116
- * Call with next() as baseline. Wiring must gate isActive on hasUI + mode=tui,
117
- * and invalidate the TUI before requestRender(true) on either toggle. Exports
118
- * made from that active TUI inherit these renderers: Pi supplies no render-mode
119
- * discriminator. Missing/throwing hooks get safe generic text, not a clone of
120
- * Pi's private fallback formatter. Custom baseline self shells stay self-owned.
121
- */
122
- export function createSwitchableToolView(
123
- polished: ToolRenderers,
124
- baseline: ToolRenderers | undefined,
125
- isActive: () => boolean,
126
- dependencies: ToolAdapterDependencies,
127
- stateKey: symbol = Symbol("pi1337-tool-row"),
128
- ): ToolRenderers {
129
- return createAdapter(polished, baseline, isActive, dependencies, stateKey);
130
- }
131
-
132
- /**
133
- * A third-party renderer in this package's flat shell. The content stays the
134
- * renderer's: there is ONE lane, so its hooks run once per host update with
135
- * the host's own `context.state` (never a copy, never reset by a toggle) and
136
- * its own `lastComponent`. Only the frame switches — while active, its call
137
- * lines follow one status dot and its result lines hang under `└`, with no
138
- * background fill and no padding rows; inactive, the same components sit in
139
- * the host's Box, recomposed exactly as for any baseline lane.
140
- *
141
- * The host box is kept, active or not, for what cannot be framed safely: a
142
- * renderer that declares `renderShell: "self"`, a result carrying image
143
- * content (the host paints those outside our shell) and a row whose renderer
144
- * emitted a terminal image-protocol line or a line that is not a string (for
145
- * the rest of that row's life).
146
- * Such rows never fold: `dependencies.groups` is ignored here.
147
- *
148
- * A row whose slots render no line takes none, in either state. Active, that
149
- * also covers slots holding only blank lines (the flat row drops them as
150
- * padding). Inactive it is the one case that cannot equal the host: the host's
151
- * default shell still prints its separator row above an empty box, and a
152
- * `renderShell: "self"` row is given that separator only together with at
153
- * least one line of its own — one blank row alone is not reachable from here.
154
- * Blank-only slots and a slot beside an empty one do match the host exactly.
155
- */
156
- export function createFlatToolView(
157
- foreign: ToolRenderers,
158
- isActive: () => boolean,
159
- dependencies: ToolAdapterDependencies,
160
- stateKey: symbol = Symbol("pi1337-tool-row"),
161
- ): ToolRenderers {
162
- return createAdapter(undefined, foreign, isActive, dependencies, stateKey);
163
- }
164
-
165
- /** `polished === undefined`: one lane (the baseline's renderers) whose frame alone switches. */
166
- function createAdapter(
167
- polished: ToolRenderers | undefined,
168
- baseline: ToolRenderers | undefined,
169
- isActive: () => boolean,
170
- dependencies: ToolAdapterDependencies,
171
- stateKey: symbol,
172
- ): ToolRenderers {
173
- const { Box, Container, Text } = dependencies;
174
- const groups = polished ? dependencies.groups : undefined;
175
-
176
- function fallbackCall(args: unknown, theme: Theme): Component {
177
- let json = "";
178
- try { json = JSON.stringify(args, null, 2) ?? ""; } catch { json = "[unavailable arguments]"; }
179
- return new Text(theme.fg("toolTitle", sanitizeInlineText(dependencies.toolName)) +
180
- (json ? `\n${json.split("\n").map(sanitizeArtLine).join("\n")}` : ""), 0, 0);
181
- }
182
- function fallbackResult(result: Result, context: Context, theme: Theme): Component {
183
- const lines: string[] = [];
184
- let lineCount = 0;
185
- const expanded = context.expanded;
186
- const append = (line: string) => {
187
- lineCount++;
188
- if (expanded || lines.length < 10) lines.push(sanitizeArtLine(line));
189
- };
190
- for (const block of result.content) {
191
- if (block.type === "text") {
192
- const text = block.text;
193
- let start = 0;
194
- for (let end = text.indexOf("\n"); end !== -1; end = text.indexOf("\n", start)) {
195
- lineCount++;
196
- if (expanded || lines.length < 10) lines.push(sanitizeArtLine(text.slice(start, end)));
197
- start = end + 1;
198
- }
199
- lineCount++;
200
- if (expanded || lines.length < 10) lines.push(sanitizeArtLine(text.slice(start)));
201
- } else if (block.type === "image" && !(context.showImages && dependencies.imagesSupported?.())) {
202
- append(`[image: ${sanitizeInlineText(block.mimeType)}]`);
203
- }
204
- }
205
- if (!expanded && lineCount > lines.length) lines.push(`… (${lineCount - lines.length} more lines; ${sanitizeInlineText(dependencies.expandHint?.() ?? "expand")})`);
206
- return lines.length ? new Text(theme.fg("toolOutput", lines.join("\n")), 0, 0) : empty;
207
- }
208
-
209
- function createRow(context: Context, theme: Theme) {
210
- // Two lanes keep a private state each. A framed third-party row has one lane, and
211
- // that lane owns the host's state object itself: no toggle can fork or reset it.
212
- const lanes: Lane[] = polished
213
- ? [polished, baseline ?? {}].map(renderers => ({ renderers, state: {} }))
214
- : [{ renderers: baseline ?? {}, state: context.state }];
215
- const laneFor = (active: boolean): Lane => lanes[active ? 0 : lanes.length - 1]!;
216
- // The flat shell is only ever an option for a third-party row that leaves its frame to the host.
217
- const frames = !polished && baseline?.renderShell !== "self";
218
- let unframed = false; // this row's renderer emitted an image-protocol or non-string line: host box from then on
219
- let resultImages = false; // the host paints the current result's images outside our shell
220
- let flatShown = false; // the last frame of the call slot was the flat shell (mouse routing)
221
- let shell: Box | Container | undefined;
222
- let resultConsumedByCall = false;
223
- let summary: { view: Component; sentence: string; detailed: string; theme: Theme; context: Context } | undefined;
224
- const callSlot: Slot = {};
225
- const resultSlot: Slot = {};
226
- const resetSlots = () => {
227
- for (const slot of [callSlot, resultSlot]) {
228
- slot.shell = undefined;
229
- slot.lane = undefined;
230
- slot.children = undefined;
231
- slot.pad = undefined;
232
- slot.clip = undefined;
233
- slot.flat = undefined;
234
- }
235
- };
236
- // Read at paint time: Box samples its bgFn, so a state or theme change
237
- // repaints without a new shell (and a same-colored change stays cached).
238
- const background = (text: string) => {
239
- const ctx = row.context;
240
- return row.theme.bg(ctx.isPartial ? "toolPendingBg" : ctx.isError ? "toolErrorBg" : "toolSuccessBg", text);
241
- };
242
- // Rebuilt only for another lane, shell kind or child; addChild/setPaddingX
243
- // would drop Box's cache, so neither runs on an unchanged frame.
244
- // The children are compared in place: nothing is allocated on an unchanged frame.
245
- const renderSlot = (slot: Slot, lane: Lane, first: Component, second: Component | undefined, width: number): string[] => {
246
- const self = lane.renderers.renderShell === "self";
247
- const kept = slot.children;
248
- if (!slot.shell || slot.lane !== lane || (slot.shell instanceof Box) === self ||
249
- !kept || kept.length !== (second ? 2 : 1) || kept[0] !== first || kept[1] !== second) {
250
- const children = second ? [first, second] : [first];
251
- slot.shell = self ? new Container() : new Box(0, 1, background);
252
- for (const child of children) slot.shell.addChild(child);
253
- slot.lane = lane;
254
- slot.children = children;
255
- slot.pad = 0;
256
- slot.clip = undefined;
257
- }
258
- if (slot.shell instanceof Box) {
259
- // At impossibly narrow widths sacrifice padding, never the terminal's row boundary.
260
- const pad = Math.min(Math.max(0, Math.floor(row.context.outputPad)), Math.floor((width - 1) / 2));
261
- if (slot.pad !== pad) slot.shell.setPaddingX(slot.pad = pad);
262
- }
263
- return clipOnce(slot, slot.shell.render(width), width);
264
- };
265
- // The flat shell has no component of its own to keep: its children render at
266
- // the inner width every frame (they may change their lines silently) and the
267
- // composed row is reused while the width, the padding, the theme, both mark
268
- // roles and every line are last frame's. The marks are painted only when the
269
- // row is composed: like the renderer's own lines, they bake their colors, and
270
- // the host invalidates every row when the palette changes. Undefined when a
271
- // line carries an image-protocol payload or is not a string at all — that
272
- // row cannot be prefixed or clipped, so the host box takes it (its Box
273
- // paints a non-string line as the text it coerces to; nothing here throws).
274
- const renderFlat = (slot: Slot, call: Component, result: Component, width: number, resultOnly: boolean): string[] | undefined => {
275
- const ctx = row.context;
276
- const inner = flatInnerWidth(width, ctx.outputPad);
277
- const callLines = call === empty ? noLines : call.render(inner);
278
- const resultLines = result === empty ? noLines : result.render(inner);
279
- const dot = statusRole(ctx);
280
- const connector = resultRole(ctx);
281
- const last = slot.flat;
282
- if (last && last.width === width && last.pad === ctx.outputPad && last.theme === row.theme && last.dot === dot &&
283
- last.connector === connector && sameLines(last.call, callLines) && sameLines(last.result, resultLines)) {
284
- last.callChild = call;
285
- last.resultChild = result;
286
- return last.row.lines;
287
- }
288
- if (callLines.some(isUnframeable) || resultLines.some(isUnframeable)) {
289
- slot.flat = undefined;
290
- return undefined;
291
- }
292
- slot.flat = { width, pad: ctx.outputPad, theme: row.theme, dot, connector, call: callLines.slice(), result: resultLines.slice(),
293
- callChild: call, resultChild: result,
294
- row: flatRow(callLines, resultLines, width, ctx.outputPad, row.theme.fg(dot, "●"), row.theme.fg(connector, "└"), resultOnly) };
295
- return slot.flat.row.lines;
296
- };
297
- // A click lands on the renderer's own component, in that component's
298
- // coordinates; one on the lead or the side padding is the host's (it expands the row).
299
- const routeFlat = (event: MouseEvent): ReturnType<NonNullable<Component["handleMouse"]>> => {
300
- const memo = callSlot.flat;
301
- if (!memo) return undefined;
302
- const { left, inner, call, result } = memo.row;
303
- const x = event.x - left;
304
- if (x < 0 || x >= inner || event.y < 0) return undefined;
305
- if (event.y < call.count) {
306
- return memo.callChild.handleMouse?.({ ...event, x, y: event.y + call.skipped, width: inner, height: call.total });
307
- }
308
- const y = event.y - call.count;
309
- if (y >= result.count) return undefined;
310
- return memo.resultChild.handleMouse?.({ ...event, x, y: y + result.skipped, width: inner, height: result.total });
311
- };
312
- // Folding is a polished-lane presentation of the live TUI. The HTML exporter
313
- // renders the call slot as partial, so an export never folds.
314
- const decision = (): GroupDecision => {
315
- const ctx = row.context;
316
- return groups && isActive() && !ctx.expanded && !ctx.isPartial
317
- ? groups.decisionFor(ctx.toolCallId) : normal;
318
- };
319
- const getCall = (lane: Lane): Component => {
320
- if (lane.call) return lane.call;
321
- const currentTheme = row.theme;
322
- if (!lane.callFallback || lane.callFallbackTheme !== currentTheme) {
323
- lane.callFallback = fallbackCall(lane.callArgs, currentTheme);
324
- lane.callFallbackTheme = currentTheme;
325
- }
326
- return lane.callFallback;
327
- };
328
- const getResult = (lane: Lane): Component => {
329
- if (lane.result) return lane.result;
330
- if (!lane.resultValue) return empty;
331
- const ctx = row.context;
332
- const currentTheme = row.theme;
333
- const imagesSupported = !!(ctx.showImages && dependencies.imagesSupported?.());
334
- const key = lane.resultFallbackKey;
335
- if (!lane.resultFallback || !key || key.result !== lane.resultValue ||
336
- key.expanded !== ctx.expanded || key.showImages !== ctx.showImages ||
337
- key.imagesSupported !== imagesSupported || key.theme !== currentTheme) {
338
- lane.resultFallback = fallbackResult(lane.resultValue, ctx, currentTheme);
339
- lane.resultFallbackKey = { result: lane.resultValue, expanded: ctx.expanded,
340
- showImages: ctx.showImages, imagesSupported, theme: currentTheme };
341
- }
342
- return lane.resultFallback;
343
- };
344
- const row = {
345
- context, theme, lanes,
346
- resetResultConsumed() { resultConsumedByCall = false; },
347
- setResultImages(images: boolean) { resultImages = images; },
348
- resultComponent: {
349
- invalidate() {
350
- resetSlots();
351
- for (const lane of lanes) {
352
- lane.result?.invalidate();
353
- lane.resultFallback = undefined;
354
- lane.resultFallbackKey = undefined;
355
- }
356
- },
357
- render(width: number): string[] {
358
- if (width <= 0) return [];
359
- const active = isActive();
360
- const lane = laneFor(active);
361
- // In the TUI the call slot owns both; the HTML export never folds, so
362
- // this slot needs no run decision of its own.
363
- if (resultConsumedByCall) return [];
364
- const result = getResult(lane);
365
- if (result === empty) return [];
366
- if (frames && active && !unframed && !resultImages) {
367
- const lines = renderFlat(resultSlot, empty, result, width, true);
368
- if (lines) return lines;
369
- unframed = true;
370
- }
371
- if (lane.renderers.renderShell === "self") return result.render(width);
372
- return renderSlot(resultSlot, lane, result, undefined, width);
373
- },
374
- },
375
- component: {
376
- invalidate() {
377
- summary = undefined;
378
- resetSlots();
379
- for (const lane of lanes) {
380
- lane.call?.invalidate();
381
- lane.result?.invalidate();
382
- lane.callFallback?.invalidate();
383
- lane.callFallback = undefined;
384
- lane.resultFallback = undefined;
385
- lane.resultFallbackKey = undefined;
386
- }
387
- },
388
- render(width: number): string[] {
389
- if (width <= 0) return [];
390
- const active = isActive();
391
- const lane = laneFor(active);
392
- // Taken fresh each frame — the host re-renders every pass, so transitions are free.
393
- const fold = decision();
394
- flatShown = false;
395
- if (fold.kind !== "normal") {
396
- // The whole row is folded; the result slot must not resurrect it.
397
- resultConsumedByCall = true;
398
- shell = undefined;
399
- if (fold.kind === "hidden") return [];
400
- if (summary?.sentence !== fold.sentence || summary.detailed !== fold.detailed || summary.theme !== row.theme || summary.context !== row.context) {
401
- summary = { sentence: fold.sentence, detailed: fold.detailed, theme: row.theme, context: row.context,
402
- view: createRunSummaryView(fold.sentence, row.theme, row.context, dependencies.expandHint ?? (() => "expand"), fold.detailed) };
403
- }
404
- return summary.view.render(width);
405
- }
406
- if (frames && active && !unframed && !resultImages) {
407
- const flat = renderFlat(callSlot, getCall(lane), getResult(lane), width, false);
408
- if (flat) {
409
- shell = undefined;
410
- flatShown = true;
411
- if (lane.result || lane.resultValue) resultConsumedByCall = true;
412
- return flat;
413
- }
414
- unframed = true;
415
- }
416
- // Never clip terminal-image protocol bytes from a custom renderer.
417
- const result = getResult(lane);
418
- const lines = renderSlot(callSlot, lane, getCall(lane), result === empty ? undefined : result, width);
419
- shell = callSlot.shell;
420
- if (lane.result || lane.resultValue) resultConsumedByCall = true;
421
- return lines;
422
- },
423
- handleMouse(event) {
424
- if (groups && isActive() && event?.type === "click" && event.button === "left") {
425
- // A hidden row has no lines to click: it is only reached through the
426
- // last frame's layout, where it was the tally the user saw.
427
- const onTally = decision().kind !== "normal";
428
- // Any click on a run's row unfolds that run for good. On the tally it
429
- // brings the rows back; on a member row the host is about to expand
430
- // that row alone, and a row the user opened must never leave its
431
- // siblings hidden behind a tally nothing renders.
432
- groups.expand(row.context.toolCallId);
433
- if (onTally) return { handled: true };
434
- }
435
- if (flatShown) return routeFlat(event);
436
- return shell?.handleMouse(event);
437
- },
438
- } satisfies Component,
439
- };
440
- return row;
441
- }
442
- type Row = ReturnType<typeof createRow>;
443
- function getRow(context: Context, theme: Theme): Row {
444
- return context.state[stateKey] ??= createRow(context, theme);
445
- }
446
- return {
447
- renderShell: "self",
448
- renderCall(args, theme, context) {
449
- const row = getRow(context, theme);
450
- row.context = context;
451
- row.theme = theme;
452
- for (const lane of row.lanes) {
453
- lane.callArgs = args;
454
- lane.callFallback = undefined;
455
- lane.callFallbackTheme = undefined;
456
- try {
457
- lane.lastCall = lane.renderers.renderCall?.(args, theme, { ...context, state: lane.state, lastComponent: lane.lastCall });
458
- } catch { lane.lastCall = undefined; }
459
- lane.call = lane.lastCall;
460
- }
461
- return row.component;
462
- },
463
- renderResult(result, options, theme, context) {
464
- const row = getRow(context, theme);
465
- row.context = context;
466
- row.theme = theme;
467
- row.resetResultConsumed();
468
- if (groups) {
469
- // The host renders image payloads outside our shell: a call carrying one
470
- // must never fold, or the images would orphan under an empty row.
471
- if (result.content.some(block => block.type === "image")) groups.markImages(context.toolCallId);
472
- // This row now shows its final result, so it may fold or carry a tally.
473
- if (!options.isPartial) groups.settle(context.toolCallId, context.isError);
474
- }
475
- // ...and for the same reason a third-party row carrying one keeps the host box.
476
- if (!polished) row.setResultImages(result.content.some(block => block.type === "image"));
477
- for (const lane of row.lanes) {
478
- lane.resultValue = result;
479
- lane.resultFallback = undefined;
480
- lane.resultFallbackKey = undefined;
481
- try {
482
- lane.lastResult = lane.renderers.renderResult?.(result, options, theme, { ...context, state: lane.state, lastComponent: lane.lastResult });
483
- } catch { lane.lastResult = undefined; }
484
- lane.result = lane.lastResult;
485
- }
486
- // TUI consumes both slots through the call component's one native Box; HTML
487
- // export renders call and result independently, so expose a result-only shell too.
488
- return row.resultComponent;
489
- },
490
- };
491
- }
1
+ import type { ToolRenderers } from "@earendil-works/pi-coding-agent";
2
+ import type { Box, Component, Container, Text } from "@earendil-works/pi-tui";
3
+ import { sanitizeArtLine, sanitizeInlineText } from "./format.ts";
4
+ import type { GroupControl, GroupDecision } from "./tool-groups.ts";
5
+ import { createRunSummaryView, flatInnerWidth, flatRow, resultRole, statusRole, type FlatRow } from "./tool-view.ts";
6
+ import { clipTextRows, isImageProtocolLine, visibleWidth } from "./width.ts";
7
+
8
+ export interface ToolAdapterDependencies {
9
+ Box: typeof Box;
10
+ Container: typeof Container;
11
+ Text: typeof Text;
12
+ toolName: string;
13
+ expandHint?: () => string;
14
+ imagesSupported?: () => boolean;
15
+ /**
16
+ * Folded exploration runs (presentation of the transcript itself). Only the
17
+ * polished lane's call slot consults it: the baseline lane always renders the host rows.
18
+ */
19
+ groups?: GroupControl;
20
+ }
21
+
22
+ type Call = NonNullable<ToolRenderers["renderCall"]>;
23
+ type Context = Parameters<Call>[2];
24
+ type Theme = Parameters<Call>[1];
25
+ type Result = Parameters<NonNullable<ToolRenderers["renderResult"]>>[0];
26
+ type MouseEvent = Parameters<NonNullable<Component["handleMouse"]>>[0];
27
+ type Lane = {
28
+ renderers: ToolRenderers;
29
+ state: Record<string, unknown>;
30
+ call?: Component;
31
+ result?: Component;
32
+ lastCall?: Component;
33
+ lastResult?: Component;
34
+ callArgs?: unknown;
35
+ callFallback?: Component;
36
+ callFallbackTheme?: Theme;
37
+ resultValue?: Result;
38
+ resultFallback?: Component;
39
+ resultFallbackKey?: { result: Result; expanded: boolean; showImages: boolean; imagesSupported: boolean; theme: Theme };
40
+ };
41
+ /**
42
+ * One slot's shell, kept across frames so pi-tui's Box cache can hit, and the last
43
+ * clip. The shell still renders every frame (children may change their own lines
44
+ * silently); only an identical row of identical lines at the same width reuses the clip.
45
+ */
46
+ type Slot = {
47
+ shell?: Box | Container;
48
+ lane?: Lane;
49
+ children?: Component[];
50
+ pad?: number;
51
+ clip?: { width: number; input: readonly string[]; output: readonly string[] };
52
+ flat?: FlatMemo;
53
+ };
54
+ /**
55
+ * The flat shell's last frame: what it was composed from and the composed row.
56
+ * The renderer's lines are copied, not kept by reference — a component may
57
+ * rewrite its own array in place, and a memo holding that array would match
58
+ * itself. The components are kept only to route a click to the one under it.
59
+ */
60
+ type FlatMemo = {
61
+ width: number;
62
+ pad: unknown;
63
+ theme: Theme;
64
+ dot: string;
65
+ connector: string;
66
+ call: readonly string[];
67
+ result: readonly string[];
68
+ callChild: Component;
69
+ resultChild: Component;
70
+ row: FlatRow;
71
+ };
72
+ const empty: Component = { render: () => [], invalidate() {} };
73
+ const normal: GroupDecision = { kind: "normal" };
74
+ const noLines: readonly string[] = [];
75
+ function sameLines(last: readonly string[], lines: readonly string[]): boolean {
76
+ if (last.length !== lines.length) return false;
77
+ for (let i = 0; i < lines.length; i++) if (last[i] !== lines[i]) return false;
78
+ return true;
79
+ }
80
+
81
+ function allFit(lines: readonly string[], width: number): boolean {
82
+ for (const line of lines) if (!isImageProtocolLine(line) && visibleWidth(line) > width) return false;
83
+ return true;
84
+ }
85
+
86
+ /**
87
+ * A renderer's `render()` is typed `string[]`, but the lines are a third party's:
88
+ * one that is not a string (`[undefined, "x"]`) must never reach a string method here.
89
+ */
90
+ const isText = (line: unknown): line is string => typeof line === "string";
91
+ /** A line the flat shell can neither prefix nor clip: an image-protocol payload, or not text at all. */
92
+ const isUnframeable = (line: unknown): boolean => !isText(line) || isImageProtocolLine(line);
93
+
94
+ function clipOnce(slot: Slot, lines: readonly string[], width: number): readonly string[] {
95
+ const last = slot.clip;
96
+ if (last && last.width === width && sameLines(last.input, lines)) return last.output;
97
+ // Measuring a styled line is the host ruler's fast path, truncating one is not:
98
+ // rows that all fit (every row a well-behaved shell returns) are passed on as they are.
99
+ // So is a self-framed row holding a line that is not text: the host hands those on
100
+ // untouched too, and there is nothing here to measure (the host's Box turns them into text).
101
+ const output = !lines.every(isText) || allFit(lines, width) ? lines : clipTextRows(lines, width);
102
+ // Kept by reference: Box reuses an array only for identical lines, Container never does.
103
+ slot.clip = { width, input: lines, output };
104
+ return output;
105
+ }
106
+
107
+ /**
108
+ * Pi fixes the shell when a row is constructed. Keep it self-owned forever and
109
+ * switch the *contents*, not the descriptor, when /theme-1337 changes state.
110
+ *
111
+ * Both lanes receive every host callback, even when hidden: native renderers may
112
+ * need their final callback to stop a partial-result timer. Each lane has its own
113
+ * state and lastComponent slots, owned solely by the host's per-row state. No
114
+ * execution data is changed and images remain entirely ToolExecutionComponent's.
115
+ *
116
+ * Call with next() as baseline. Wiring must gate isActive on hasUI + mode=tui,
117
+ * and invalidate the TUI before requestRender(true) on either toggle. Exports
118
+ * made from that active TUI inherit these renderers: Pi supplies no render-mode
119
+ * discriminator. Missing/throwing hooks get safe generic text, not a clone of
120
+ * Pi's private fallback formatter. Custom baseline self shells stay self-owned.
121
+ */
122
+ export function createSwitchableToolView(
123
+ polished: ToolRenderers,
124
+ baseline: ToolRenderers | undefined,
125
+ isActive: () => boolean,
126
+ dependencies: ToolAdapterDependencies,
127
+ stateKey: symbol = Symbol("pi1337-tool-row"),
128
+ ): ToolRenderers {
129
+ return createAdapter(polished, baseline, isActive, dependencies, stateKey);
130
+ }
131
+
132
+ /**
133
+ * A third-party renderer in this package's flat shell. The content stays the
134
+ * renderer's: there is ONE lane, so its hooks run once per host update with
135
+ * the host's own `context.state` (never a copy, never reset by a toggle) and
136
+ * its own `lastComponent`. Only the frame switches — while active, its call
137
+ * lines follow one status dot and its result lines hang under `└`, with no
138
+ * background fill and no padding rows; inactive, the same components sit in
139
+ * the host's Box, recomposed exactly as for any baseline lane.
140
+ *
141
+ * The host box is kept, active or not, for what cannot be framed safely: a
142
+ * renderer that declares `renderShell: "self"`, a result carrying image
143
+ * content (the host paints those outside our shell) and a row whose renderer
144
+ * emitted a terminal image-protocol line or a line that is not a string (for
145
+ * the rest of that row's life).
146
+ * Such rows never fold: `dependencies.groups` is ignored here.
147
+ *
148
+ * A row whose slots render no line takes none, in either state. Active, that
149
+ * also covers slots holding only blank lines (the flat row drops them as
150
+ * padding). Inactive it is the one case that cannot equal the host: the host's
151
+ * default shell still prints its separator row above an empty box, and a
152
+ * `renderShell: "self"` row is given that separator only together with at
153
+ * least one line of its own — one blank row alone is not reachable from here.
154
+ * Blank-only slots and a slot beside an empty one do match the host exactly.
155
+ */
156
+ export function createFlatToolView(
157
+ foreign: ToolRenderers,
158
+ isActive: () => boolean,
159
+ dependencies: ToolAdapterDependencies,
160
+ stateKey: symbol = Symbol("pi1337-tool-row"),
161
+ ): ToolRenderers {
162
+ return createAdapter(undefined, foreign, isActive, dependencies, stateKey);
163
+ }
164
+
165
+ /** `polished === undefined`: one lane (the baseline's renderers) whose frame alone switches. */
166
+ function createAdapter(
167
+ polished: ToolRenderers | undefined,
168
+ baseline: ToolRenderers | undefined,
169
+ isActive: () => boolean,
170
+ dependencies: ToolAdapterDependencies,
171
+ stateKey: symbol,
172
+ ): ToolRenderers {
173
+ const { Box, Container, Text } = dependencies;
174
+ const groups = polished ? dependencies.groups : undefined;
175
+
176
+ function fallbackCall(args: unknown, theme: Theme): Component {
177
+ let json = "";
178
+ try { json = JSON.stringify(args, null, 2) ?? ""; } catch { json = "[unavailable arguments]"; }
179
+ return new Text(theme.fg("toolTitle", sanitizeInlineText(dependencies.toolName)) +
180
+ (json ? `\n${json.split("\n").map(sanitizeArtLine).join("\n")}` : ""), 0, 0);
181
+ }
182
+ function fallbackResult(result: Result, context: Context, theme: Theme): Component {
183
+ const lines: string[] = [];
184
+ let lineCount = 0;
185
+ const expanded = context.expanded;
186
+ const append = (line: string) => {
187
+ lineCount++;
188
+ if (expanded || lines.length < 10) lines.push(sanitizeArtLine(line));
189
+ };
190
+ for (const block of result.content) {
191
+ if (block.type === "text") {
192
+ const text = block.text;
193
+ let start = 0;
194
+ for (let end = text.indexOf("\n"); end !== -1; end = text.indexOf("\n", start)) {
195
+ lineCount++;
196
+ if (expanded || lines.length < 10) lines.push(sanitizeArtLine(text.slice(start, end)));
197
+ start = end + 1;
198
+ }
199
+ lineCount++;
200
+ if (expanded || lines.length < 10) lines.push(sanitizeArtLine(text.slice(start)));
201
+ } else if (block.type === "image" && !(context.showImages && dependencies.imagesSupported?.())) {
202
+ append(`[image: ${sanitizeInlineText(block.mimeType)}]`);
203
+ }
204
+ }
205
+ if (!expanded && lineCount > lines.length) lines.push(`… (${lineCount - lines.length} more lines; ${sanitizeInlineText(dependencies.expandHint?.() ?? "expand")})`);
206
+ return lines.length ? new Text(theme.fg("toolOutput", lines.join("\n")), 0, 0) : empty;
207
+ }
208
+
209
+ function createRow(context: Context, theme: Theme) {
210
+ // Two lanes keep a private state each. A framed third-party row has one lane, and
211
+ // that lane owns the host's state object itself: no toggle can fork or reset it.
212
+ const lanes: Lane[] = polished
213
+ ? [polished, baseline ?? {}].map(renderers => ({ renderers, state: {} }))
214
+ : [{ renderers: baseline ?? {}, state: context.state }];
215
+ const laneFor = (active: boolean): Lane => lanes[active ? 0 : lanes.length - 1]!;
216
+ // The flat shell is only ever an option for a third-party row that leaves its frame to the host.
217
+ const frames = !polished && baseline?.renderShell !== "self";
218
+ let unframed = false; // this row's renderer emitted an image-protocol or non-string line: host box from then on
219
+ let resultImages = false; // the host paints the current result's images outside our shell
220
+ let flatShown = false; // the last frame of the call slot was the flat shell (mouse routing)
221
+ let shell: Box | Container | undefined;
222
+ let resultConsumedByCall = false;
223
+ let summary: { view: Component; sentence: string; detailed: string; theme: Theme; context: Context } | undefined;
224
+ const callSlot: Slot = {};
225
+ const resultSlot: Slot = {};
226
+ const resetSlots = () => {
227
+ for (const slot of [callSlot, resultSlot]) {
228
+ slot.shell = undefined;
229
+ slot.lane = undefined;
230
+ slot.children = undefined;
231
+ slot.pad = undefined;
232
+ slot.clip = undefined;
233
+ slot.flat = undefined;
234
+ }
235
+ };
236
+ // Read at paint time: Box samples its bgFn, so a state or theme change
237
+ // repaints without a new shell (and a same-colored change stays cached).
238
+ const background = (text: string) => {
239
+ const ctx = row.context;
240
+ return row.theme.bg(ctx.isPartial ? "toolPendingBg" : ctx.isError ? "toolErrorBg" : "toolSuccessBg", text);
241
+ };
242
+ // Rebuilt only for another lane, shell kind or child; addChild/setPaddingX
243
+ // would drop Box's cache, so neither runs on an unchanged frame.
244
+ // The children are compared in place: nothing is allocated on an unchanged frame.
245
+ const renderSlot = (slot: Slot, lane: Lane, first: Component, second: Component | undefined, width: number): readonly string[] => {
246
+ const self = lane.renderers.renderShell === "self";
247
+ const kept = slot.children;
248
+ if (!slot.shell || slot.lane !== lane || (slot.shell instanceof Box) === self ||
249
+ !kept || kept.length !== (second ? 2 : 1) || kept[0] !== first || kept[1] !== second) {
250
+ const children = second ? [first, second] : [first];
251
+ slot.shell = self ? new Container() : new Box(0, 1, background);
252
+ for (const child of children) slot.shell.addChild(child);
253
+ slot.lane = lane;
254
+ slot.children = children;
255
+ slot.pad = 0;
256
+ slot.clip = undefined;
257
+ }
258
+ if (slot.shell instanceof Box) {
259
+ // At impossibly narrow widths sacrifice padding, never the terminal's row boundary.
260
+ const pad = Math.min(Math.max(0, Math.floor(row.context.outputPad)), Math.floor((width - 1) / 2));
261
+ if (slot.pad !== pad) slot.shell.setPaddingX(slot.pad = pad);
262
+ }
263
+ return clipOnce(slot, slot.shell.render(width), width);
264
+ };
265
+ // The flat shell has no component of its own to keep: its children render at
266
+ // the inner width every frame (they may change their lines silently) and the
267
+ // composed row is reused while the width, the padding, the theme, both mark
268
+ // roles and every line are last frame's. The marks are painted only when the
269
+ // row is composed: like the renderer's own lines, they bake their colors, and
270
+ // the host invalidates every row when the palette changes. Undefined when a
271
+ // line carries an image-protocol payload or is not a string at all — that
272
+ // row cannot be prefixed or clipped, so the host box takes it (its Box
273
+ // paints a non-string line as the text it coerces to; nothing here throws).
274
+ const renderFlat = (slot: Slot, call: Component, result: Component, width: number, resultOnly: boolean): readonly string[] | undefined => {
275
+ const ctx = row.context;
276
+ const inner = flatInnerWidth(width, ctx.outputPad);
277
+ const callLines = call === empty ? noLines : call.render(inner);
278
+ const resultLines = result === empty ? noLines : result.render(inner);
279
+ const dot = statusRole(ctx);
280
+ const connector = resultRole(ctx);
281
+ const last = slot.flat;
282
+ if (last && last.width === width && last.pad === ctx.outputPad && last.theme === row.theme && last.dot === dot &&
283
+ last.connector === connector && sameLines(last.call, callLines) && sameLines(last.result, resultLines)) {
284
+ last.callChild = call;
285
+ last.resultChild = result;
286
+ return last.row.lines;
287
+ }
288
+ if (callLines.some(isUnframeable) || resultLines.some(isUnframeable)) {
289
+ slot.flat = undefined;
290
+ return undefined;
291
+ }
292
+ slot.flat = { width, pad: ctx.outputPad, theme: row.theme, dot, connector, call: callLines.slice(), result: resultLines.slice(),
293
+ callChild: call, resultChild: result,
294
+ row: flatRow(callLines, resultLines, width, ctx.outputPad, row.theme.fg(dot, "●"), row.theme.fg(connector, "└"), resultOnly) };
295
+ return slot.flat.row.lines;
296
+ };
297
+ // A click lands on the renderer's own component, in that component's
298
+ // coordinates; one on the lead or the side padding is the host's (it expands the row).
299
+ const routeFlat = (event: MouseEvent): ReturnType<NonNullable<Component["handleMouse"]>> => {
300
+ const memo = callSlot.flat;
301
+ if (!memo) return undefined;
302
+ const { left, inner, call, result } = memo.row;
303
+ const x = event.x - left;
304
+ if (x < 0 || x >= inner || event.y < 0) return undefined;
305
+ if (event.y < call.count) {
306
+ return memo.callChild.handleMouse?.({ ...event, x, y: event.y + call.skipped, width: inner, height: call.total });
307
+ }
308
+ const y = event.y - call.count;
309
+ if (y >= result.count) return undefined;
310
+ return memo.resultChild.handleMouse?.({ ...event, x, y: y + result.skipped, width: inner, height: result.total });
311
+ };
312
+ // Folding is a polished-lane presentation of the live TUI. The HTML exporter
313
+ // renders the call slot as partial, so an export never folds.
314
+ const decision = (): GroupDecision => {
315
+ const ctx = row.context;
316
+ return groups && isActive() && !ctx.expanded && !ctx.isPartial
317
+ ? groups.decisionFor(ctx.toolCallId) : normal;
318
+ };
319
+ const getCall = (lane: Lane): Component => {
320
+ if (lane.call) return lane.call;
321
+ const currentTheme = row.theme;
322
+ if (!lane.callFallback || lane.callFallbackTheme !== currentTheme) {
323
+ lane.callFallback = fallbackCall(lane.callArgs, currentTheme);
324
+ lane.callFallbackTheme = currentTheme;
325
+ }
326
+ return lane.callFallback;
327
+ };
328
+ const getResult = (lane: Lane): Component => {
329
+ if (lane.result) return lane.result;
330
+ if (!lane.resultValue) return empty;
331
+ const ctx = row.context;
332
+ const currentTheme = row.theme;
333
+ const imagesSupported = !!(ctx.showImages && dependencies.imagesSupported?.());
334
+ const key = lane.resultFallbackKey;
335
+ if (!lane.resultFallback || !key || key.result !== lane.resultValue ||
336
+ key.expanded !== ctx.expanded || key.showImages !== ctx.showImages ||
337
+ key.imagesSupported !== imagesSupported || key.theme !== currentTheme) {
338
+ lane.resultFallback = fallbackResult(lane.resultValue, ctx, currentTheme);
339
+ lane.resultFallbackKey = { result: lane.resultValue, expanded: ctx.expanded,
340
+ showImages: ctx.showImages, imagesSupported, theme: currentTheme };
341
+ }
342
+ return lane.resultFallback;
343
+ };
344
+ const row = {
345
+ context, theme, lanes,
346
+ resetResultConsumed() { resultConsumedByCall = false; },
347
+ setResultImages(images: boolean) { resultImages = images; },
348
+ resultComponent: {
349
+ invalidate() {
350
+ resetSlots();
351
+ for (const lane of lanes) {
352
+ lane.result?.invalidate();
353
+ lane.resultFallback = undefined;
354
+ lane.resultFallbackKey = undefined;
355
+ }
356
+ },
357
+ render(width: number): readonly string[] {
358
+ if (width <= 0) return [];
359
+ const active = isActive();
360
+ const lane = laneFor(active);
361
+ // In the TUI the call slot owns both; the HTML export never folds, so
362
+ // this slot needs no run decision of its own.
363
+ if (resultConsumedByCall) return [];
364
+ const result = getResult(lane);
365
+ if (result === empty) return [];
366
+ if (frames && active && !unframed && !resultImages) {
367
+ const lines = renderFlat(resultSlot, empty, result, width, true);
368
+ if (lines) return lines;
369
+ unframed = true;
370
+ }
371
+ if (lane.renderers.renderShell === "self") return result.render(width);
372
+ return renderSlot(resultSlot, lane, result, undefined, width);
373
+ },
374
+ },
375
+ component: {
376
+ invalidate() {
377
+ summary = undefined;
378
+ resetSlots();
379
+ for (const lane of lanes) {
380
+ lane.call?.invalidate();
381
+ lane.result?.invalidate();
382
+ lane.callFallback?.invalidate();
383
+ lane.callFallback = undefined;
384
+ lane.resultFallback = undefined;
385
+ lane.resultFallbackKey = undefined;
386
+ }
387
+ },
388
+ render(width: number): readonly string[] {
389
+ if (width <= 0) return [];
390
+ const active = isActive();
391
+ const lane = laneFor(active);
392
+ // Taken fresh each frame — the host re-renders every pass, so transitions are free.
393
+ const fold = decision();
394
+ flatShown = false;
395
+ if (fold.kind !== "normal") {
396
+ // The whole row is folded; the result slot must not resurrect it.
397
+ resultConsumedByCall = true;
398
+ shell = undefined;
399
+ if (fold.kind === "hidden") return [];
400
+ if (summary?.sentence !== fold.sentence || summary.detailed !== fold.detailed || summary.theme !== row.theme || summary.context !== row.context) {
401
+ summary = { sentence: fold.sentence, detailed: fold.detailed, theme: row.theme, context: row.context,
402
+ view: createRunSummaryView(fold.sentence, row.theme, row.context, dependencies.expandHint ?? (() => "expand"), fold.detailed) };
403
+ }
404
+ return summary.view.render(width);
405
+ }
406
+ if (frames && active && !unframed && !resultImages) {
407
+ const flat = renderFlat(callSlot, getCall(lane), getResult(lane), width, false);
408
+ if (flat) {
409
+ shell = undefined;
410
+ flatShown = true;
411
+ if (lane.result || lane.resultValue) resultConsumedByCall = true;
412
+ return flat;
413
+ }
414
+ unframed = true;
415
+ }
416
+ // Never clip terminal-image protocol bytes from a custom renderer.
417
+ const result = getResult(lane);
418
+ const lines = renderSlot(callSlot, lane, getCall(lane), result === empty ? undefined : result, width);
419
+ shell = callSlot.shell;
420
+ if (lane.result || lane.resultValue) resultConsumedByCall = true;
421
+ return lines;
422
+ },
423
+ handleMouse(event) {
424
+ if (groups && isActive() && event?.type === "click" && event.button === "left") {
425
+ // A hidden row has no lines to click: it is only reached through the
426
+ // last frame's layout, where it was the tally the user saw.
427
+ const onTally = decision().kind !== "normal";
428
+ // Any click on a run's row unfolds that run for good. On the tally it
429
+ // brings the rows back; on a member row the host is about to expand
430
+ // that row alone, and a row the user opened must never leave its
431
+ // siblings hidden behind a tally nothing renders.
432
+ groups.expand(row.context.toolCallId);
433
+ if (onTally) return { handled: true };
434
+ }
435
+ if (flatShown) return routeFlat(event);
436
+ return shell?.handleMouse(event);
437
+ },
438
+ } satisfies Component,
439
+ };
440
+ return row;
441
+ }
442
+ type Row = ReturnType<typeof createRow>;
443
+ function getRow(context: Context, theme: Theme): Row {
444
+ return context.state[stateKey] ??= createRow(context, theme);
445
+ }
446
+ return {
447
+ renderShell: "self",
448
+ renderCall(args, theme, context) {
449
+ const row = getRow(context, theme);
450
+ row.context = context;
451
+ row.theme = theme;
452
+ for (const lane of row.lanes) {
453
+ lane.callArgs = args;
454
+ lane.callFallback = undefined;
455
+ lane.callFallbackTheme = undefined;
456
+ try {
457
+ lane.lastCall = lane.renderers.renderCall?.(args, theme, { ...context, state: lane.state, lastComponent: lane.lastCall });
458
+ } catch { lane.lastCall = undefined; }
459
+ lane.call = lane.lastCall;
460
+ }
461
+ return row.component;
462
+ },
463
+ renderResult(result, options, theme, context) {
464
+ const row = getRow(context, theme);
465
+ row.context = context;
466
+ row.theme = theme;
467
+ row.resetResultConsumed();
468
+ if (groups) {
469
+ // The host renders image payloads outside our shell: a call carrying one
470
+ // must never fold, or the images would orphan under an empty row.
471
+ if (result.content.some(block => block.type === "image")) groups.markImages(context.toolCallId);
472
+ // This row now shows its final result, so it may fold or carry a tally.
473
+ if (!options.isPartial) groups.settle(context.toolCallId, context.isError);
474
+ }
475
+ // ...and for the same reason a third-party row carrying one keeps the host box.
476
+ if (!polished) row.setResultImages(result.content.some(block => block.type === "image"));
477
+ for (const lane of row.lanes) {
478
+ lane.resultValue = result;
479
+ lane.resultFallback = undefined;
480
+ lane.resultFallbackKey = undefined;
481
+ try {
482
+ lane.lastResult = lane.renderers.renderResult?.(result, options, theme, { ...context, state: lane.state, lastComponent: lane.lastResult });
483
+ } catch { lane.lastResult = undefined; }
484
+ lane.result = lane.lastResult;
485
+ }
486
+ // TUI consumes both slots through the call component's one native Box; HTML
487
+ // export renders call and result independently, so expose a result-only shell too.
488
+ return row.resultComponent;
489
+ },
490
+ };
491
+ }