@aeondave/pi-theme-1337 0.0.0-stage → 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.
- package/CHANGELOG.md +263 -0
- package/LICENSE +21 -0
- package/README.md +166 -2
- package/assets/banner.png +0 -0
- package/assets/palettes.gif +0 -0
- package/docs/architecture.md +172 -0
- package/docs/configuration.md +103 -0
- package/docs/palette-design.md +51 -0
- package/docs/theme-motion.md +88 -0
- package/package.json +68 -4
- package/src/avatar.ts +174 -0
- package/src/background.ts +82 -0
- package/src/config.ts +400 -0
- package/src/diff-spans.ts +77 -0
- package/src/draft.ts +10 -0
- package/src/editor.ts +545 -0
- package/src/format.ts +464 -0
- package/src/frame.ts +380 -0
- package/src/git-status-cache.ts +198 -0
- package/src/git-status-reader.ts +28 -0
- package/src/git-status.ts +72 -0
- package/src/header-controller.ts +58 -0
- package/src/header.ts +151 -0
- package/src/index.ts +1264 -0
- package/src/quota.ts +581 -0
- package/src/redraw-guard.ts +79 -0
- package/src/run-summary.ts +623 -0
- package/src/spinner.ts +72 -0
- package/src/status-style.ts +26 -0
- package/src/terminal-title.ts +67 -0
- package/src/tool-activity.ts +216 -0
- package/src/tool-adapter.ts +491 -0
- package/src/tool-groups.ts +192 -0
- package/src/tool-lexicon.ts +200 -0
- package/src/tool-view.ts +788 -0
- package/src/width.ts +246 -0
- package/themes/1337-amber.json +94 -0
- package/themes/1337-amber.pi1337 +3 -0
- package/themes/1337-cosmos.json +94 -0
- package/themes/1337-cosmos.pi1337 +3 -0
- package/themes/1337-cyber.json +94 -0
- package/themes/1337-cyber.pi1337 +3 -0
- package/themes/1337-cyberpunk-2077-edgerunner.json +94 -0
- package/themes/1337-cyberpunk-2077-edgerunner.pi1337 +7 -0
- package/themes/1337-cyberpunk-2077.json +94 -0
- package/themes/1337-cyberpunk-2077.pi1337 +7 -0
- package/themes/1337-fallout.json +94 -0
- package/themes/1337-fallout.pi1337 +4 -0
- package/themes/1337-ice.json +94 -0
- package/themes/1337-ice.pi1337 +3 -0
- package/themes/1337-magma.json +94 -0
- package/themes/1337-magma.pi1337 +1 -0
- package/themes/1337-neon.json +94 -0
- package/themes/1337-neon.pi1337 +3 -0
- package/themes/1337-poison.json +94 -0
- package/themes/1337-poison.pi1337 +3 -0
- package/themes/1337-skynet-dark.json +94 -0
- package/themes/1337-skynet-dark.pi1337 +4 -0
- package/themes/1337-skynet.json +94 -0
- package/themes/1337-skynet.pi1337 +4 -0
- package/themes/1337.json +95 -0
- package/themes/1337.pi1337 +3 -0
|
@@ -0,0 +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: 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
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure registry that folds runs of consecutive exploration calls.
|
|
3
|
+
*
|
|
4
|
+
* The host fixes one `ToolExecutionComponent` per call into a transcript container
|
|
5
|
+
* no extension can see, but a `renderShell: "self"` renderer can render zero lines
|
|
6
|
+
* (the row disappears) or one summary line instead of its view. This module owns
|
|
7
|
+
* the ONLY state that decides which, derived from the same documented
|
|
8
|
+
* `tool_execution_*` events the host builds rows from and closed by any message
|
|
9
|
+
* that paints a transcript row. No host prototypes are patched; the adapter asks
|
|
10
|
+
* `decisionFor` at render time and the host's per-frame re-render applies
|
|
11
|
+
* transitions for free.
|
|
12
|
+
*
|
|
13
|
+
* Folding is presentation of the transcript itself — it suppresses neither
|
|
14
|
+
* `notify()`, status indicators, widgets, nor any other Pi channel. A run folds
|
|
15
|
+
* as soon as it holds MIN_FOLD settled calls, and keeps folding while it is
|
|
16
|
+
* open: hidden rows take no lines, so the tally stays where it is and counts up
|
|
17
|
+
* as each later call settles into it. A row is never hidden unless another row
|
|
18
|
+
* of its run renders the tally. Calls still running, failed calls and
|
|
19
|
+
* image-bearing calls keep their own rows (the host paints images outside our
|
|
20
|
+
* shell), and Ctrl+O still expands every row.
|
|
21
|
+
*/
|
|
22
|
+
import { isFoldableTool, tallyDetails, tallyName, tallySentence, tallySubject } from "./tool-lexicon.ts";
|
|
23
|
+
|
|
24
|
+
export type GroupDecision =
|
|
25
|
+
| { readonly kind: "normal" }
|
|
26
|
+
| { readonly kind: "hidden" }
|
|
27
|
+
/** `sentence` counts ("Read 3 files"); `detailed` names the files when the row has room for it. */
|
|
28
|
+
| { readonly kind: "summary"; readonly sentence: string; readonly detailed: string };
|
|
29
|
+
|
|
30
|
+
/** What a row adapter consumes. Row-local state (expanded, partial) is the adapter's business, not the registry's. */
|
|
31
|
+
export interface GroupControl {
|
|
32
|
+
decisionFor(callId: string): GroupDecision;
|
|
33
|
+
/** A click on the summary or on any member row: the run's rows return for good (one-way; Ctrl+O still expands everything). */
|
|
34
|
+
expand(callId: string): void;
|
|
35
|
+
/** The host paints a result's images outside our shell, so a call carrying one never folds. */
|
|
36
|
+
markImages(callId: string): void;
|
|
37
|
+
/**
|
|
38
|
+
* The call's row has its final result. Rows settle their own calls: Pi tells
|
|
39
|
+
* extensions a tool ended before it updates the row, so an event-fed registry
|
|
40
|
+
* would hide a run's rows while the row meant to carry the tally still
|
|
41
|
+
* rendered as running.
|
|
42
|
+
*/
|
|
43
|
+
settle(callId: string, failed: boolean): void;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface ToolStartDetails {
|
|
47
|
+
/** With `cwd`, name what the call is about, so the tally counts distinct files and patterns. */
|
|
48
|
+
readonly args?: unknown;
|
|
49
|
+
readonly cwd?: string;
|
|
50
|
+
/** This package's adapter renders that tool's rows (default true). */
|
|
51
|
+
readonly rendersHere?: boolean;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ToolRunRegistry extends GroupControl {
|
|
55
|
+
onToolStart(callId: string, toolName: string, details?: ToolStartDetails): void;
|
|
56
|
+
/** Closes the open run when the message paints transcript rows. */
|
|
57
|
+
onMessage(message: unknown): void;
|
|
58
|
+
closeAll(): void;
|
|
59
|
+
reset(): void;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Fewer calls than this read fine as rows; a tally only pays for itself on longer runs. */
|
|
63
|
+
export const MIN_FOLD = 3;
|
|
64
|
+
|
|
65
|
+
// Singletons: decisionFor runs for every row on every frame and must not allocate.
|
|
66
|
+
const NORMAL: GroupDecision = Object.freeze({ kind: "normal" });
|
|
67
|
+
const HIDDEN: GroupDecision = Object.freeze({ kind: "hidden" });
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Whether the host paints a transcript row for this message — and so whether it
|
|
71
|
+
* sits between two tool rows and must break their run. Tool results belong to
|
|
72
|
+
* the rows themselves. An assistant message paints text, a "∴ thinking" row (this
|
|
73
|
+
* extension always sets a hidden-thinking label) and, when the turn ended badly,
|
|
74
|
+
* an error line; a toolCall-only message paints nothing. Other roles paint unless
|
|
75
|
+
* they opt out with `display: false`.
|
|
76
|
+
*/
|
|
77
|
+
export function messagePaintsRows(message: unknown): boolean {
|
|
78
|
+
if (typeof message !== "object" || message === null) return false;
|
|
79
|
+
const m = message as { role?: unknown; content?: unknown; stopReason?: unknown; display?: unknown };
|
|
80
|
+
if (m.role === "toolResult") return false;
|
|
81
|
+
if (m.role !== "assistant") return m.display !== false;
|
|
82
|
+
if (m.stopReason === "length" || m.stopReason === "error" || m.stopReason === "aborted") return true;
|
|
83
|
+
if (typeof m.content === "string") return m.content.trim().length > 0;
|
|
84
|
+
if (!Array.isArray(m.content)) return false;
|
|
85
|
+
return m.content.some(block => {
|
|
86
|
+
if (typeof block !== "object" || block === null) return false;
|
|
87
|
+
const b = block as { type?: unknown; text?: unknown; thinking?: unknown };
|
|
88
|
+
const text = b.type === "text" ? b.text : b.type === "thinking" ? b.thinking : undefined;
|
|
89
|
+
return typeof text === "string" && text.trim().length > 0;
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface RunCall {
|
|
94
|
+
readonly id: string;
|
|
95
|
+
readonly name: string;
|
|
96
|
+
readonly subject: string;
|
|
97
|
+
readonly display: string;
|
|
98
|
+
ended: boolean;
|
|
99
|
+
failed: boolean;
|
|
100
|
+
images: boolean;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
interface Run {
|
|
104
|
+
readonly calls: RunCall[];
|
|
105
|
+
expanded: boolean;
|
|
106
|
+
/** The fold, computed once per mutation; undefined = stale. */
|
|
107
|
+
fold?: Map<RunCall, GroupDecision>;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const foldable = (call: RunCall): boolean => call.ended && !call.failed && !call.images;
|
|
111
|
+
|
|
112
|
+
function computeFold(run: Run): Map<RunCall, GroupDecision> {
|
|
113
|
+
const fold = new Map<RunCall, GroupDecision>();
|
|
114
|
+
if (run.expanded) return fold;
|
|
115
|
+
const members = run.calls.filter(foldable);
|
|
116
|
+
if (members.length < MIN_FOLD) return fold;
|
|
117
|
+
const sentence = tallySentence(members);
|
|
118
|
+
const detailed = tallyDetails(members);
|
|
119
|
+
// The carrier is the last foldable call: the rows before it take no lines, so
|
|
120
|
+
// as an open run grows the tally stays put and the newest settled call takes
|
|
121
|
+
// it over in place — and it sits where the run ended even when a failed call
|
|
122
|
+
// trails it.
|
|
123
|
+
for (const call of members) fold.set(call, HIDDEN);
|
|
124
|
+
fold.set(members[members.length - 1]!, { kind: "summary", sentence, detailed });
|
|
125
|
+
return fold;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function createToolRunRegistry(): ToolRunRegistry {
|
|
129
|
+
let openRun: Run | undefined;
|
|
130
|
+
const byCall = new Map<string, { run: Run; call: RunCall }>();
|
|
131
|
+
|
|
132
|
+
const close = (): void => {
|
|
133
|
+
const run = openRun;
|
|
134
|
+
if (!run) return;
|
|
135
|
+
openRun = undefined;
|
|
136
|
+
// A run that can never fold needs no memory: keep only runs that matter.
|
|
137
|
+
if (run.calls.length < MIN_FOLD) for (const call of run.calls) byCall.delete(call.id);
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
onToolStart(callId, toolName, { args, cwd, rendersHere = true } = {}) {
|
|
142
|
+
if (!callId || byCall.has(callId)) return;
|
|
143
|
+
// bash (side effects), edit, write, delegate, custom tools and rows another
|
|
144
|
+
// renderer owns all break the run and stay untracked themselves.
|
|
145
|
+
if (!rendersHere || !isFoldableTool(toolName)) {
|
|
146
|
+
close();
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
openRun ??= { calls: [], expanded: false };
|
|
150
|
+
const call: RunCall = { id: callId, name: toolName, subject: tallySubject(toolName, args, cwd),
|
|
151
|
+
display: tallyName(toolName, args, cwd), ended: false, failed: false, images: false };
|
|
152
|
+
openRun.calls.push(call);
|
|
153
|
+
openRun.fold = undefined;
|
|
154
|
+
byCall.set(callId, { run: openRun, call });
|
|
155
|
+
},
|
|
156
|
+
settle(callId, failed) {
|
|
157
|
+
const entry = byCall.get(callId);
|
|
158
|
+
if (!entry || entry.call.ended) return;
|
|
159
|
+
entry.call.ended = true;
|
|
160
|
+
entry.call.failed = failed;
|
|
161
|
+
entry.run.fold = undefined;
|
|
162
|
+
},
|
|
163
|
+
onMessage(message) {
|
|
164
|
+
// Called on every streaming delta: bail before inspecting the message.
|
|
165
|
+
if (openRun && messagePaintsRows(message)) close();
|
|
166
|
+
},
|
|
167
|
+
closeAll: close,
|
|
168
|
+
reset() {
|
|
169
|
+
openRun = undefined;
|
|
170
|
+
byCall.clear();
|
|
171
|
+
},
|
|
172
|
+
expand(callId) {
|
|
173
|
+
const entry = byCall.get(callId);
|
|
174
|
+
if (!entry || entry.run.expanded) return;
|
|
175
|
+
entry.run.expanded = true;
|
|
176
|
+
entry.run.fold = undefined;
|
|
177
|
+
},
|
|
178
|
+
markImages(callId) {
|
|
179
|
+
const entry = byCall.get(callId);
|
|
180
|
+
if (!entry || entry.call.images) return;
|
|
181
|
+
entry.call.images = true;
|
|
182
|
+
entry.run.fold = undefined;
|
|
183
|
+
},
|
|
184
|
+
decisionFor(callId) {
|
|
185
|
+
const entry = byCall.get(callId);
|
|
186
|
+
if (!entry) return NORMAL;
|
|
187
|
+
const run = entry.run;
|
|
188
|
+
run.fold ??= computeFold(run);
|
|
189
|
+
return run.fold.get(entry.call) ?? NORMAL;
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|