@bismawy/pi-arnative 0.16.1 → 0.18.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/README.md +25 -16
- package/extensions/index.ts +41 -0
- package/lib/active-clock.ts +91 -0
- package/lib/ansi.ts +40 -78
- package/lib/box.ts +49 -68
- package/lib/chatbox.ts +371 -0
- package/lib/color.ts +3 -31
- package/lib/compat.ts +0 -60
- package/lib/edit-diff.ts +199 -0
- package/{extensions → lib/features}/arnative.ts +96 -423
- package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -327
- package/{extensions → lib/features}/budget.ts +17 -242
- package/lib/features/footer.ts +2232 -0
- package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
- package/{extensions → lib/features}/model-heal.ts +5 -28
- package/lib/features/progress-group.ts +1557 -0
- package/{extensions → lib/features}/render-cache.ts +113 -161
- package/{extensions → lib/features}/timestamps.ts +18 -94
- package/{extensions → lib/features}/todos.ts +44 -158
- package/lib/features/tools.ts +1202 -0
- package/lib/features/ui-render-tweaks.ts +606 -0
- package/lib/features/usage.ts +786 -0
- package/lib/format.ts +22 -4
- package/lib/git-status.ts +164 -0
- package/lib/list-picker.ts +1 -127
- package/lib/model-heal.ts +70 -162
- package/lib/patch.ts +0 -63
- package/lib/preset-store.ts +17 -133
- package/lib/provider-store.ts +573 -0
- package/lib/provider.ts +52 -851
- package/lib/runtime.ts +209 -0
- package/lib/shortcuts.ts +8 -58
- package/lib/spinner.ts +88 -162
- package/lib/status-widget.ts +4 -30
- package/lib/todos.ts +20 -143
- package/lib/usage-pricing.ts +143 -0
- package/lib/usage-store.ts +44 -378
- package/package.json +5 -6
- package/themes/arnative-blossom.json +0 -0
- package/themes/arnative-crimson.json +0 -0
- package/themes/arnative-cyberpunk.json +0 -0
- package/themes/arnative-dracula.json +0 -0
- package/themes/arnative-earthy.json +0 -0
- package/themes/arnative-garden.json +0 -0
- package/themes/arnative-gruvbox.json +0 -0
- package/themes/arnative-lemonade.json +0 -0
- package/themes/arnative-magical.json +0 -0
- package/themes/arnative-matrix.json +0 -0
- package/themes/arnative-neutral.json +0 -0
- package/themes/arnative-nord.json +0 -0
- package/themes/arnative-zinc.json +0 -0
- package/themes/arnative.json +0 -0
- package/CHANGELOG.md +0 -683
- package/extensions/animations.ts +0 -242
- package/extensions/footer.ts +0 -2617
- package/extensions/tools.ts +0 -2231
- package/extensions/ui-render-tweaks.ts +0 -1005
- package/extensions/usage-export.ts +0 -283
- package/extensions/usage.ts +0 -1406
- package/lib/check.ts +0 -21
- package/themes/gen-themes.mjs +0 -715
package/extensions/tools.ts
DELETED
|
@@ -1,2231 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Codex/Claude-Code style tool boxes: every tool call in its own box.
|
|
3
|
-
* ╭────────────────────────────╮
|
|
4
|
-
* │ $ cmd smart… │ running (spinner, gone once finished)
|
|
5
|
-
* ╰────────────────────────────╯
|
|
6
|
-
* ╭────────────────────────────╮
|
|
7
|
-
* │ ✓ $ cmd smart… 0.1s │ final, collapsed; duration right-aligned
|
|
8
|
-
* │ first output line │
|
|
9
|
-
* ╰────────────────────────────╯
|
|
10
|
-
* Click `[show]` / `[hide]` or press the `app.tools.expand` key (ctrl+o by default) = full title + detail
|
|
11
|
-
* (output dim; edit = toolDiff*).
|
|
12
|
-
* Collapsed summary: bash/write ` first line`; grep/find/read numeric
|
|
13
|
-
* (→ N matches / → N files / N lines); edit ` +N / -M`. Expanded plain output
|
|
14
|
-
* gets no summary line (no duplicated first line).
|
|
15
|
-
* Colors: tool name accent, paths/links soft, box lines + dim. Execution is a
|
|
16
|
-
* pure delegate (spread of the built-in tools).
|
|
17
|
-
* "has a result" lives in context.state, read at render() -> restore/reload safe,
|
|
18
|
-
* no stale box. Third-party tools with no renderer of their own (memory_write,
|
|
19
|
-
* scratchpad, MCP…) get the same box: shell "self", one-line summary,
|
|
20
|
-
* `[show]` for the full detail.
|
|
21
|
-
*/
|
|
22
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
23
|
-
import {
|
|
24
|
-
createBashTool,
|
|
25
|
-
createEditTool,
|
|
26
|
-
createFindTool,
|
|
27
|
-
createGrepTool,
|
|
28
|
-
createLsTool,
|
|
29
|
-
createLsToolDefinition,
|
|
30
|
-
createPowerShellTool,
|
|
31
|
-
createPowerShellToolDefinition,
|
|
32
|
-
createReadTool,
|
|
33
|
-
createWriteTool,
|
|
34
|
-
getMarkdownTheme,
|
|
35
|
-
highlightCode,
|
|
36
|
-
initTheme,
|
|
37
|
-
ToolExecutionComponent,
|
|
38
|
-
} from "@earendil-works/pi-coding-agent";
|
|
39
|
-
import { Markdown, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
40
|
-
import { mkdtempSync, rmSync } from "node:fs";
|
|
41
|
-
import { homedir, tmpdir } from "node:os";
|
|
42
|
-
import { join } from "node:path";
|
|
43
|
-
import { inSpans, renderBoxLines as box, type TextSpan, textSpans } from "../lib/box.ts";
|
|
44
|
-
import { getActiveTheme, stripAnsi, softSecondaryOf } from "../lib/ansi.ts";
|
|
45
|
-
import { actionWord } from "../lib/todos.ts";
|
|
46
|
-
import { EDIT_DIFF_KEY, choiceSetting, resetPresetCache } from "../lib/preset-store.ts";
|
|
47
|
-
import { clearRenderCache } from "./render-cache.ts";
|
|
48
|
-
import { assert, isMain } from "../lib/check.ts";
|
|
49
|
-
import { markPatched, originalOf } from "../lib/patch.ts";
|
|
50
|
-
|
|
51
|
-
type Theme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; inverse?(text: string): string };
|
|
52
|
-
type TResult = { content: Array<{ type: string; text?: string }>; isError?: boolean; details?: any };
|
|
53
|
-
type TCtx = { isError?: boolean; toolCallId?: string; args?: any; state?: Record<string, unknown>; durationMs?: number };
|
|
54
|
-
type Res = (r: TResult, th: Theme, soft: (s: string) => string, isErr: boolean, expanded: boolean) => string;
|
|
55
|
-
|
|
56
|
-
const cwd = process.cwd();
|
|
57
|
-
const MAX_TIMINGS = 200;
|
|
58
|
-
const TIMINGS = new Map<string, number>();
|
|
59
|
-
|
|
60
|
-
/** Runtime of one call: pi's own figure first (it survives a restore and covers tools this
|
|
61
|
-
* module does not wrap), then the wall time recorded by the execute wrapper. */
|
|
62
|
-
const durationOf = (ctx: TCtx): string =>
|
|
63
|
-
fmtMs(ctx.durationMs ?? (ctx.toolCallId ? TIMINGS.get(ctx.toolCallId) : undefined));
|
|
64
|
-
|
|
65
|
-
export function recordTiming(toolCallId: string, durationMs: number): void {
|
|
66
|
-
if (TIMINGS.size >= MAX_TIMINGS) {
|
|
67
|
-
const oldest = TIMINGS.keys().next().value;
|
|
68
|
-
if (oldest !== undefined) TIMINGS.delete(oldest);
|
|
69
|
-
}
|
|
70
|
-
TIMINGS.set(toolCallId, durationMs);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// Running icon : 500ms spin frames from a ticker that only runs while
|
|
74
|
-
// a tool is active (idle = no wasteful re-renders).
|
|
75
|
-
const FRAMES = ["", "", ""];
|
|
76
|
-
let ACTIVE = 0;
|
|
77
|
-
let TICK: ReturnType<typeof setInterval> | null = null;
|
|
78
|
-
let requestRenderFn: (() => void) | null = null;
|
|
79
|
-
|
|
80
|
-
function syncTicker(): void {
|
|
81
|
-
if (ACTIVE > 0 && !TICK) {
|
|
82
|
-
TICK = setInterval(() => requestRenderFn?.(), 500);
|
|
83
|
-
} else if (ACTIVE <= 0 && TICK) {
|
|
84
|
-
clearInterval(TICK);
|
|
85
|
-
TICK = null;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export function spinIcon(): string {
|
|
90
|
-
return FRAMES[Math.floor(Date.now() / 500) % FRAMES.length];
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** Tool duration: `2ms` under a second, `1.4s` above — the wording pi itself uses. */
|
|
94
|
-
function fmtMs(ms: number | undefined): string {
|
|
95
|
-
if (ms === undefined || !Number.isFinite(ms)) return "";
|
|
96
|
-
return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export class Lines {
|
|
100
|
-
private get: (width: number) => string[];
|
|
101
|
-
constructor(get: (width: number) => string[]) {
|
|
102
|
-
this.get = get;
|
|
103
|
-
}
|
|
104
|
-
render(width: number): string[] {
|
|
105
|
-
return this.get(width);
|
|
106
|
-
}
|
|
107
|
-
invalidate(): void {}
|
|
108
|
-
}
|
|
109
|
-
const EMPTY = new Lines(() => []);
|
|
110
|
-
|
|
111
|
-
const shortPath = (p: string): string => {
|
|
112
|
-
const home = homedir();
|
|
113
|
-
return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
|
|
114
|
-
};
|
|
115
|
-
|
|
116
|
-
const textOf = (r: TResult): string =>
|
|
117
|
-
r.content.filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n").trim();
|
|
118
|
-
|
|
119
|
-
const firstLine = (s: string): string => s.split("\n").find((l) => l.trim()) ?? "";
|
|
120
|
-
|
|
121
|
-
// Summary = first line with content. Punctuation-only lines (e.g. a lone `{` from
|
|
122
|
-
// pretty-printed MCP JSON) explain nothing -> take the next one.
|
|
123
|
-
const firstMeaningful = (s: string): string => {
|
|
124
|
-
const lines = s.split("\n").filter((l) => l.trim());
|
|
125
|
-
return lines.find((l) => !/^[\s{}\[\],;:]+$/.test(l)) ?? lines[0] ?? "";
|
|
126
|
-
};
|
|
127
|
-
|
|
128
|
-
const countLines = (s: string): number => (s ? s.split("\n").filter(Boolean).length : 0);
|
|
129
|
-
|
|
130
|
-
// Tint folder paths / URLs; everything else default.
|
|
131
|
-
export const LINK_RE = /(?:https?:\/\/[^\s"'`)}\]]+|(?:~|\.{1,2})?\/[\w.+@~%/-]+|[\w.+@~-]+(?:\/[\w.+@~%/-]+)+)/g;
|
|
132
|
-
export function paintLinks(text: string, soft: (s: string) => string): string {
|
|
133
|
-
return text.replace(LINK_RE, (m) => soft(m));
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// Word-limited smart title: `maxWords` words + ellipsis; full text when expanded.
|
|
137
|
-
export function smartTitle(cmd: string, maxWords = 6): string {
|
|
138
|
-
const words = cmd.replace(/\r?\n/g, " ").trim().split(/\s+/).filter(Boolean);
|
|
139
|
-
if (words.length <= maxWords) return words.join(" ");
|
|
140
|
-
return `${words.slice(0, maxWords).join(" ")}…`;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// Result line prefix: dim (duration lives at the right end of the title).
|
|
144
|
-
export function resHead(theme: Theme): string {
|
|
145
|
-
return theme.fg("dim", "");
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/** Rows a block of text takes once painted at `width`, blank lines dropped: one long JSON
|
|
149
|
-
* string is a single newline but twenty-five rows on screen. */
|
|
150
|
-
const drawnRows = (text: string, width: number): number =>
|
|
151
|
-
text
|
|
152
|
-
.split("\n")
|
|
153
|
-
.filter((l) => l.trim())
|
|
154
|
-
.reduce((n, l) => n + Math.max(1, Math.ceil(visibleWidth(l) / Math.max(1, width))), 0);
|
|
155
|
-
|
|
156
|
-
/** A summary is one row by definition: a single-line JSON payload of 40k chars would
|
|
157
|
-
* otherwise wrap into a full screen and the box would look expanded while folded. */
|
|
158
|
-
const oneRow = (text: string, inner: number): string => truncateToWidth(text, inner, "…");
|
|
159
|
-
|
|
160
|
-
// Title line: duration right-aligned and space-aware (title truncated when it
|
|
161
|
-
// doesn't fit); expanded = full title wrapped. All lines stay <= inner (overflow bug).
|
|
162
|
-
export function titleRow(
|
|
163
|
-
theme: Theme,
|
|
164
|
-
icon: string,
|
|
165
|
-
name: string,
|
|
166
|
-
argPart: string,
|
|
167
|
-
inner: number,
|
|
168
|
-
dur: string,
|
|
169
|
-
expanded: boolean,
|
|
170
|
-
hint = "",
|
|
171
|
-
): string[] {
|
|
172
|
-
const head = `${icon} ${name} ${argPart}`.trim();
|
|
173
|
-
// Runtime first, label last: the figure is what you read, the label is the button.
|
|
174
|
-
const right = [dur, hint].filter(Boolean).join(" · ");
|
|
175
|
-
const durStr = right ? theme.fg("dim", right) : "";
|
|
176
|
-
if (!durStr) {
|
|
177
|
-
return expanded ? wrapTextWithAnsi(head, inner) : [truncateToWidth(head, inner, "…")];
|
|
178
|
-
}
|
|
179
|
-
const durW = visibleWidth(durStr);
|
|
180
|
-
const avail = Math.max(8, inner - durW);
|
|
181
|
-
const wrapW = Math.max(4, avail - 1); // keep at least 1 space before the duration
|
|
182
|
-
const lines = expanded ? wrapTextWithAnsi(head, wrapW) : [truncateToWidth(head, wrapW, "…")];
|
|
183
|
-
const pad = Math.max(1, avail - visibleWidth(lines[0]));
|
|
184
|
-
lines[0] = `${lines[0]}${" ".repeat(pad)}${durStr}`;
|
|
185
|
-
return lines;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// Default summary: collapsed ` first output line`, empty when expanded (the
|
|
189
|
-
// full output is right below — no duplicate first line).
|
|
190
|
-
export const resText: Res = (r, th, soft, isErr, expanded) => {
|
|
191
|
-
if (expanded && !isErr) return "";
|
|
192
|
-
const f = firstLine(textOf(r));
|
|
193
|
-
return f ? `${resHead(th)} ${paintLinks(f, soft)}` : resHead(th);
|
|
194
|
-
};
|
|
195
|
-
|
|
196
|
-
// Numeric summary ` → N matches`; errors fall back to the first line (most important).
|
|
197
|
-
export const numRes =
|
|
198
|
-
(fmt: (n: number) => string): Res =>
|
|
199
|
-
(r, th, soft, isErr, expanded) => {
|
|
200
|
-
if (isErr) return resText(r, th, soft, isErr, false);
|
|
201
|
-
if (expanded) return "";
|
|
202
|
-
return `${resHead(th)} ${fmt(countLines(textOf(r)))}`;
|
|
203
|
-
};
|
|
204
|
-
|
|
205
|
-
// First markdown heading in the text (e.g. `## omaga-sync workflow (2026-08-23)`).
|
|
206
|
-
const firstHeading = (s: unknown): string =>
|
|
207
|
-
typeof s === "string" ? (s.split("\n").find((l) => /^#{1,6}\s/.test(l.trim()))?.trim() ?? "") : "";
|
|
208
|
-
|
|
209
|
-
// One-line summary for tools without their own renderer. memory_write appends the
|
|
210
|
-
// heading it just wrote (from args.content) so the line names WHAT was written
|
|
211
|
-
// instead of just "Appended to MEMORY.md".
|
|
212
|
-
export function toolSummary(name: string, text: string, args?: any): string {
|
|
213
|
-
const head = firstMeaningful(text).trim();
|
|
214
|
-
const title = name === "memory_write" ? firstHeading(args?.content) : "";
|
|
215
|
-
return title ? `${head}. ${title}` : head;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
// The box says whether it is open with a word: [show] folded, [hide] open. The label is
|
|
219
|
-
// also the click target (see HINT_SPANS) and sits on the title row, so the affordance a
|
|
220
|
-
// click just used stays visible instead of vanishing with the summary line.
|
|
221
|
-
export const HINT_EXPAND = "[show]";
|
|
222
|
-
export const HINT_COLLAPSE = "[hide]";
|
|
223
|
-
|
|
224
|
-
// Expanded detail: themed markdown (same layout as a normal pi message — code
|
|
225
|
-
// blocks, lists, colors) instead of a plain dim dump.
|
|
226
|
-
export const fullText = (r: TResult, _th: Theme, width = 0): string[] => {
|
|
227
|
-
const text = textOf(r);
|
|
228
|
-
if (!text) return [];
|
|
229
|
-
if (!width) return text.split("\n").map((l) => _th.fg("dim", l));
|
|
230
|
-
try {
|
|
231
|
-
return new Markdown(text, 0, 0, getMarkdownTheme()).render(Math.max(8, width));
|
|
232
|
-
} catch {
|
|
233
|
-
return text.split("\n").map((l) => _th.fg("dim", l));
|
|
234
|
-
}
|
|
235
|
-
};
|
|
236
|
-
|
|
237
|
-
const isBlankLine = (l: string): boolean => stripAnsi(l).trim() === "";
|
|
238
|
-
|
|
239
|
-
// Drop blank lines at both edges (the built-in Spacer) — that's the gap between boxes.
|
|
240
|
-
export function stripBlankEdges(lines: string[]): string[] {
|
|
241
|
-
let s = 0;
|
|
242
|
-
let e = lines.length;
|
|
243
|
-
while (s < e && isBlankLine(lines[s])) s++;
|
|
244
|
-
while (e > s && isBlankLine(lines[e - 1])) e--;
|
|
245
|
-
return lines.slice(s, e);
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
// The inter-box gap is the built-in Spacer(1) of ToolExecutionComponent, stripped
|
|
249
|
-
// with a prototype render patch (same pattern as the footer patch). Own boxes (our
|
|
250
|
-
// minimal() tools + codemode) and every box forced by the generic predicate below
|
|
251
|
-
// are stripped; a box-owning third party left untouched is not.
|
|
252
|
-
const OWN_BOX = new Set<string>();
|
|
253
|
-
const hasOwnRendererDef = (self: { toolDefinition?: { renderCall?: unknown; renderResult?: unknown } }): boolean =>
|
|
254
|
-
Boolean(self?.toolDefinition?.renderCall || self?.toolDefinition?.renderResult);
|
|
255
|
-
|
|
256
|
-
// Inline image line: kitty (\x1b_G) or iTerm2 (\x1b]1337;File=) graphics payload.
|
|
257
|
-
// pi renders a tool's image preview as an extra child BELOW the box, padding it with
|
|
258
|
-
// `result.rows - 1` blank rows; the last row carries a cursor-up prefix before the
|
|
259
|
-
// sequence. Not exported by pi-tui, so match both prefixes.
|
|
260
|
-
export const isImageLine = (line: string): boolean => line.includes("\x1b_G") || line.includes("\x1b]1337;File=");
|
|
261
|
-
|
|
262
|
-
/** Drop the leading Spacer and the gap between box and image preview:
|
|
263
|
-
* its blank tail rows are kept as the image's vertical space so the
|
|
264
|
-
* terminal draws the image with balanced spacing above and below. */
|
|
265
|
-
export function stripEdgesKeepingImages(lines: string[]): string[] {
|
|
266
|
-
const firstImage = lines.findIndex(isImageLine);
|
|
267
|
-
if (firstImage < 0) return stripBlankEdges(lines);
|
|
268
|
-
let s = 0;
|
|
269
|
-
while (s < firstImage && isBlankLine(lines[s])) s++;
|
|
270
|
-
const head = lines.slice(s, firstImage);
|
|
271
|
-
while (head.length > 0 && isBlankLine(head[head.length - 1]!)) head.pop();
|
|
272
|
-
return [...head, ...lines.slice(firstImage)];
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
// Per box: did this module strip the blank rows above it? Those rows shift every mouse
|
|
276
|
-
// row index, so a press on the border and the title row is found at 0 and 1 only for a
|
|
277
|
-
// stripped box. `Symbol.for` keeps the state across the re-import a `/reload` performs.
|
|
278
|
-
// Cells of the expand hint in this box's own drawn lines. The hint is the whole click
|
|
279
|
-
// target: every other cell of the box keeps pi's text selection, so the output stays
|
|
280
|
-
// copyable. Recomputed on every render, because the label moves with the width and the key.
|
|
281
|
-
const HINT_SPANS = Symbol.for("pi-arnative.toolBoxHintSpans");
|
|
282
|
-
const SCROLL_OFFSET = Symbol.for("pi-arnative.toolBoxScrollOffset");
|
|
283
|
-
const SCROLL_HOLD = Symbol.for("pi-arnative.toolBoxScrollHold");
|
|
284
|
-
const HOLD_DELAY_MS = 250;
|
|
285
|
-
const HOLD_REPEAT_MS = 90;
|
|
286
|
-
|
|
287
|
-
type HoldTimers = { delay?: ReturnType<typeof setTimeout>; repeat?: ReturnType<typeof setInterval> };
|
|
288
|
-
|
|
289
|
-
function stopScrollHold(comp: Record<symbol, unknown>): void {
|
|
290
|
-
const timers = comp[SCROLL_HOLD] as HoldTimers | undefined;
|
|
291
|
-
if (!timers) return;
|
|
292
|
-
if (timers.delay) clearTimeout(timers.delay);
|
|
293
|
-
if (timers.repeat) clearInterval(timers.repeat);
|
|
294
|
-
comp[SCROLL_HOLD] = undefined;
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
function startScrollHold(
|
|
298
|
-
comp: Record<symbol, unknown> & { expanded?: boolean; ui?: { requestRender?: () => void } },
|
|
299
|
-
dir: -1 | 1,
|
|
300
|
-
): void {
|
|
301
|
-
stopScrollHold(comp);
|
|
302
|
-
const timers: HoldTimers = {};
|
|
303
|
-
comp[SCROLL_HOLD] = timers;
|
|
304
|
-
const stepOnce = (): boolean => {
|
|
305
|
-
if (!comp.expanded) {
|
|
306
|
-
stopScrollHold(comp);
|
|
307
|
-
return false;
|
|
308
|
-
}
|
|
309
|
-
const meta = (comp[SCROLL_META] as { maxOffset: number; step: number } | undefined) ?? { maxOffset: 0, step: 6 };
|
|
310
|
-
const cur = Number(comp[SCROLL_OFFSET] ?? 0);
|
|
311
|
-
const next = Math.max(0, Math.min(meta.maxOffset, cur + dir * meta.step));
|
|
312
|
-
if (next === cur) {
|
|
313
|
-
stopScrollHold(comp);
|
|
314
|
-
return false;
|
|
315
|
-
}
|
|
316
|
-
comp[SCROLL_OFFSET] = next;
|
|
317
|
-
comp.ui?.requestRender?.();
|
|
318
|
-
return true;
|
|
319
|
-
};
|
|
320
|
-
timers.delay = setTimeout(() => {
|
|
321
|
-
timers.delay = undefined;
|
|
322
|
-
if (!stepOnce()) return;
|
|
323
|
-
if (comp[SCROLL_HOLD] === timers && timers.repeat === undefined) {
|
|
324
|
-
timers.repeat = setInterval(stepOnce, HOLD_REPEAT_MS);
|
|
325
|
-
}
|
|
326
|
-
}, HOLD_DELAY_MS);
|
|
327
|
-
}
|
|
328
|
-
const SCROLL_UP_SPANS = Symbol.for("pi-arnative.toolBoxScrollUpSpans");
|
|
329
|
-
const SCROLL_DOWN_SPANS = Symbol.for("pi-arnative.toolBoxScrollDownSpans");
|
|
330
|
-
const SCROLL_META = Symbol.for("pi-arnative.toolBoxScrollMeta");
|
|
331
|
-
// A press already toggled this box; the release and the synthesized click that follow it
|
|
332
|
-
// must not toggle it a second time.
|
|
333
|
-
const PRESS_TOGGLED = Symbol.for("pi-arnative.toolBoxPressToggled");
|
|
334
|
-
const STRIPPED_BOX = Symbol.for("pi-arnative.toolBoxStripped");
|
|
335
|
-
|
|
336
|
-
export function expandedBoxBodyLimit(rows = process.stdout.rows || 28): number {
|
|
337
|
-
return Math.min(12, Math.max(6, Math.floor(rows * 0.35)));
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
function boxTokenPaint(tokens: readonly string[]): (text: string) => string {
|
|
341
|
-
const th = getActiveTheme<{ fg?(c: string, t: string): string }>();
|
|
342
|
-
if (!th?.fg) return (s) => s;
|
|
343
|
-
for (const token of tokens) {
|
|
344
|
-
try {
|
|
345
|
-
const probe = th.fg(token, "x");
|
|
346
|
-
if (typeof probe === "string" && probe.includes("x")) return (s) => th.fg!(token, s);
|
|
347
|
-
} catch {
|
|
348
|
-
// try next token
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
return (s) => s;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
export function paintScrollEdge(
|
|
355
|
-
edgeLine: string,
|
|
356
|
-
leftCorner: string,
|
|
357
|
-
rightCorner: string,
|
|
358
|
-
label: string,
|
|
359
|
-
width: number,
|
|
360
|
-
borderPaint: (text: string) => string,
|
|
361
|
-
primaryPaint: (text: string) => string,
|
|
362
|
-
): string {
|
|
363
|
-
const inner = width - 2;
|
|
364
|
-
const labelW = visibleWidth(label);
|
|
365
|
-
if (inner < labelW + 4) return edgeLine;
|
|
366
|
-
const bgOpen = edgeLine.match(/^(\x1b\[48;[0-9;]*m)+/)?.[0] ?? "";
|
|
367
|
-
const bgClose = bgOpen ? "\x1b[49m" : "";
|
|
368
|
-
const totalDashes = inner - (labelW + 2);
|
|
369
|
-
const leftDashes = Math.floor(totalDashes / 2);
|
|
370
|
-
const rightDashes = totalDashes - leftDashes;
|
|
371
|
-
const content = `${borderPaint(`${leftCorner}${"\u2500".repeat(leftDashes)} `)}${primaryPaint(label)}${borderPaint(` ${"\u2500".repeat(rightDashes)}${rightCorner}`)}`;
|
|
372
|
-
return `${bgOpen}${content}${bgClose}`;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
export function capExpandedToolBox(
|
|
376
|
-
drawn: string[],
|
|
377
|
-
scrollOffset: number,
|
|
378
|
-
maxBody: number,
|
|
379
|
-
width: number,
|
|
380
|
-
borderPaint: (text: string) => string,
|
|
381
|
-
primaryPaint: (text: string) => string,
|
|
382
|
-
): { lines: string[]; maxOffset: number; aboveLabel: string; belowLabel: string; botRow: number } {
|
|
383
|
-
if (drawn.length < 4 || !stripAnsi(drawn[0] ?? "").trimStart().startsWith("\u256d")) {
|
|
384
|
-
return { lines: drawn, maxOffset: 0, aboveLabel: "", belowLabel: "", botRow: -1 };
|
|
385
|
-
}
|
|
386
|
-
let botIdx = -1;
|
|
387
|
-
for (let i = drawn.length - 1; i >= 2; i--) {
|
|
388
|
-
const p = stripAnsi(drawn[i]!).trim();
|
|
389
|
-
if (p.startsWith("\u2570") && p.endsWith("\u256f")) {
|
|
390
|
-
botIdx = i;
|
|
391
|
-
break;
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
if (botIdx < 3) return { lines: drawn, maxOffset: 0, aboveLabel: "", belowLabel: "", botRow: -1 };
|
|
395
|
-
const body = drawn.slice(2, botIdx);
|
|
396
|
-
if (body.length <= maxBody) return { lines: drawn, maxOffset: 0, aboveLabel: "", belowLabel: "", botRow: botIdx };
|
|
397
|
-
|
|
398
|
-
const maxOffset = body.length - maxBody;
|
|
399
|
-
const offset = Math.max(0, Math.min(scrollOffset, maxOffset));
|
|
400
|
-
const visible = body.slice(offset, offset + maxBody);
|
|
401
|
-
const above = offset;
|
|
402
|
-
const below = body.length - (offset + visible.length);
|
|
403
|
-
const aboveLabel = above > 0 ? `\u2191 ${above} more` : "";
|
|
404
|
-
const belowLabel = below > 0 ? `\u2193 ${below} more` : "";
|
|
405
|
-
const top = aboveLabel ? paintScrollEdge(drawn[0]!, "\u256d", "\u256e", aboveLabel, width, borderPaint, primaryPaint) : drawn[0]!;
|
|
406
|
-
const bot = belowLabel ? paintScrollEdge(drawn[botIdx]!, "\u2570", "\u256f", belowLabel, width, borderPaint, primaryPaint) : drawn[botIdx]!;
|
|
407
|
-
const lines = [top, drawn[1]!, ...visible, bot, ...drawn.slice(botIdx + 1)];
|
|
408
|
-
return { lines, maxOffset, aboveLabel, belowLabel, botRow: 2 + visible.length };
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
// The patches below reinstall on every module load (pi's /reload re-evaluates the
|
|
412
|
-
// extension in the same process), so a UI fix applies without restarting pi; see
|
|
413
|
-
// lib/patch.ts for the originals/mark bookkeeping that makes that safe.
|
|
414
|
-
if (ToolExecutionComponent?.prototype?.render) {
|
|
415
|
-
const proto = ToolExecutionComponent.prototype as any;
|
|
416
|
-
const origRender = originalOf<(this: any, width: number) => string[]>(proto, "render");
|
|
417
|
-
proto.render = markPatched(function (this: any, width: number): string[] {
|
|
418
|
-
const lines = origRender.call(this, width);
|
|
419
|
-
const stripped = OWN_BOX.has(this.toolName) || boxTheirRenderers(this) || !hasOwnRendererDef(this);
|
|
420
|
-
this[STRIPPED_BOX] = stripped;
|
|
421
|
-
let drawn = stripped ? stripEdgesKeepingImages(lines) : lines;
|
|
422
|
-
if (stripped && this.expanded) {
|
|
423
|
-
const maxBody = expandedBoxBodyLimit();
|
|
424
|
-
const capped = capExpandedToolBox(
|
|
425
|
-
drawn,
|
|
426
|
-
Number(this[SCROLL_OFFSET] ?? 0),
|
|
427
|
-
maxBody,
|
|
428
|
-
width,
|
|
429
|
-
boxTokenPaint(["dim"]),
|
|
430
|
-
boxTokenPaint(["dim"]),
|
|
431
|
-
);
|
|
432
|
-
drawn = capped.lines;
|
|
433
|
-
this[SCROLL_OFFSET] = Math.max(0, Math.min(Number(this[SCROLL_OFFSET] ?? 0), capped.maxOffset));
|
|
434
|
-
this[SCROLL_META] = { maxOffset: capped.maxOffset, step: Math.max(1, Math.floor(maxBody / 2)) };
|
|
435
|
-
this[SCROLL_UP_SPANS] = capped.aboveLabel ? textSpans([drawn[0]!], capped.aboveLabel) : [];
|
|
436
|
-
this[SCROLL_DOWN_SPANS] =
|
|
437
|
-
capped.belowLabel && capped.botRow >= 0
|
|
438
|
-
? textSpans([drawn[capped.botRow]!], capped.belowLabel).map((s) => ({ ...s, row: capped.botRow }))
|
|
439
|
-
: [];
|
|
440
|
-
} else {
|
|
441
|
-
stopScrollHold(this);
|
|
442
|
-
this[SCROLL_OFFSET] = 0;
|
|
443
|
-
this[SCROLL_UP_SPANS] = [];
|
|
444
|
-
this[SCROLL_DOWN_SPANS] = [];
|
|
445
|
-
this[SCROLL_META] = undefined;
|
|
446
|
-
}
|
|
447
|
-
// Only a box this module laid out is measured here; a renderer pi owns keeps pi's
|
|
448
|
-
// own mouse path, since its row offsets come from a layout it did not show us.
|
|
449
|
-
// Title rows only (frame + title): a [show] inside the output must not become a button.
|
|
450
|
-
this[HINT_SPANS] = stripped
|
|
451
|
-
? [...textSpans(drawn, HINT_EXPAND), ...textSpans(drawn, HINT_COLLAPSE)].filter((span) => span.row <= 1)
|
|
452
|
-
: [];
|
|
453
|
-
return drawn;
|
|
454
|
-
});
|
|
455
|
-
|
|
456
|
-
// Click to expand/collapse or scroll, on the hint/more text alone. pi toggles on the
|
|
457
|
-
// "click" it synthesizes from a press and a release at the same cell, so a one-cell
|
|
458
|
-
// drift made the hint look inert, and the stripped row above the box left its top
|
|
459
|
-
// border dead. A left press on the button acts at once and the release plus the click
|
|
460
|
-
// that follow are swallowed; the click clears the flag, not the release, or that click
|
|
461
|
-
// would trigger twice. Any other cell is left to pi: a press there starts a selection,
|
|
462
|
-
// so the output can be copied.
|
|
463
|
-
const origMouse = originalOf<(this: any, event: any) => any>(proto, "handleMouse");
|
|
464
|
-
proto.handleMouse = markPatched(function (this: any, event: any): any {
|
|
465
|
-
const onHint = (this[HINT_SPANS] as TextSpan[] | undefined)?.length
|
|
466
|
-
? inSpans(this[HINT_SPANS] as TextSpan[], event.y, event.x)
|
|
467
|
-
: false;
|
|
468
|
-
const onUp = (this[SCROLL_UP_SPANS] as TextSpan[] | undefined)?.length
|
|
469
|
-
? inSpans(this[SCROLL_UP_SPANS] as TextSpan[], event.y, event.x)
|
|
470
|
-
: false;
|
|
471
|
-
const onDown = (this[SCROLL_DOWN_SPANS] as TextSpan[] | undefined)?.length
|
|
472
|
-
? inSpans(this[SCROLL_DOWN_SPANS] as TextSpan[], event.y, event.x)
|
|
473
|
-
: false;
|
|
474
|
-
if ((onHint || onUp || onDown) && event.type === "press" && event.button === "left") {
|
|
475
|
-
stopScrollHold(this);
|
|
476
|
-
// A child of the box (an image preview) keeps its own press.
|
|
477
|
-
const childHit = origMouse.call(this, event);
|
|
478
|
-
if (childHit) return childHit;
|
|
479
|
-
if (onHint) {
|
|
480
|
-
if (!this.result) return undefined;
|
|
481
|
-
this.setExpanded(!this.expanded);
|
|
482
|
-
this[PRESS_TOGGLED] = true;
|
|
483
|
-
return { handled: true, render: true };
|
|
484
|
-
}
|
|
485
|
-
const meta = (this[SCROLL_META] as { maxOffset: number; step: number } | undefined) ?? { maxOffset: 0, step: 6 };
|
|
486
|
-
const cur = Number(this[SCROLL_OFFSET] ?? 0);
|
|
487
|
-
const dir: -1 | 1 = onUp ? -1 : 1;
|
|
488
|
-
const next = Math.max(0, Math.min(meta.maxOffset, cur + dir * meta.step));
|
|
489
|
-
this[SCROLL_OFFSET] = next;
|
|
490
|
-
this[PRESS_TOGGLED] = true;
|
|
491
|
-
startScrollHold(this, dir);
|
|
492
|
-
this.ui?.requestRender?.();
|
|
493
|
-
return { handled: true, render: true };
|
|
494
|
-
}
|
|
495
|
-
if (this[PRESS_TOGGLED] && (event.type === "release" || event.type === "click")) {
|
|
496
|
-
stopScrollHold(this);
|
|
497
|
-
if (event.type === "click") this[PRESS_TOGGLED] = false;
|
|
498
|
-
return { handled: true, render: false };
|
|
499
|
-
}
|
|
500
|
-
if (
|
|
501
|
-
this[STRIPPED_BOX] &&
|
|
502
|
-
this.result &&
|
|
503
|
-
event.type === "click" &&
|
|
504
|
-
event.button === "left"
|
|
505
|
-
) {
|
|
506
|
-
if ((event.clickCount ?? 1) !== 1) return undefined;
|
|
507
|
-
const origHit = origMouse.call(this, event);
|
|
508
|
-
if (origHit) return origHit;
|
|
509
|
-
this.setExpanded(!this.expanded);
|
|
510
|
-
return { handled: true, render: true };
|
|
511
|
-
}
|
|
512
|
-
return origMouse.call(this, event);
|
|
513
|
-
});
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
// --- Tools without their own renderer: same box, one-line summary ---
|
|
517
|
-
// Without this pi renders them as a plain bg block (name + 10 output lines). Our
|
|
518
|
-
// renderer is installed through the prototype (same pattern as the gap patch) only
|
|
519
|
-
// for tools that define no renderCall/renderResult of their own; third-party
|
|
520
|
-
// renderers are handled by the generic predicate below.
|
|
521
|
-
//
|
|
522
|
-
// BOXED_TOOLS is now a display-name map (plus the cdp special render path);
|
|
523
|
-
// boxing itself is generic (see boxTheirRenderers). The pi-web-access tools get a
|
|
524
|
-
// friendlier title ("search "/"fetch "/"get_content ") and their renderer content is
|
|
525
|
-
// reused inside our box.
|
|
526
|
-
//
|
|
527
|
-
// MCP tools (pi-mcp-adapter) declare `renderShell: "default"`, so the generic
|
|
528
|
-
// predicate boxes them, but their result renderer prints the WHOLE output on error
|
|
529
|
-
// (unbounded) and their call args can run to dozens of lines: a 1-line summary +
|
|
530
|
-
// [show] is tighter while the invoked tool stays visible.
|
|
531
|
-
const BOXED_TOOLS = new Map([
|
|
532
|
-
["web_search", "search"],
|
|
533
|
-
["fetch_content", "fetch"],
|
|
534
|
-
["get_search_content", "get_content"],
|
|
535
|
-
]);
|
|
536
|
-
|
|
537
|
-
// @narumitw/pi-chrome-devtools ships bare-text renderers ("Chrome DevTools: navigate",
|
|
538
|
-
// collapsed output is empty) so they are ignored and these tools take our default box
|
|
539
|
-
// path. CDP_ICON marks them in the call box (no hook for the generic tool icon).
|
|
540
|
-
const CDP_ICON = "\uf268";
|
|
541
|
-
const CDP_TOOLS: [string, string][] = [
|
|
542
|
-
["chrome_devtools_load", "load"],
|
|
543
|
-
["chrome_devtools_list_pages", "list pages"],
|
|
544
|
-
["chrome_devtools_select_page", "select page"],
|
|
545
|
-
["chrome_devtools_navigate", "navigate"],
|
|
546
|
-
["chrome_devtools_evaluate", "evaluate"],
|
|
547
|
-
["chrome_devtools_screenshot", "screenshot"],
|
|
548
|
-
["chrome_devtools_webmcp_list_tools", "list WebMCP tools"],
|
|
549
|
-
["chrome_devtools_webmcp_call_tool", "call WebMCP tool"],
|
|
550
|
-
];
|
|
551
|
-
const CDP_NAME = new Map(CDP_TOOLS);
|
|
552
|
-
for (const [n] of CDP_TOOLS) BOXED_TOOLS.set(n, n);
|
|
553
|
-
|
|
554
|
-
const displayName = (name: string): string =>
|
|
555
|
-
CDP_NAME.has(name) ? `Chrome DevTools: ${CDP_NAME.get(name)}` : (BOXED_TOOLS.get(name) ?? name);
|
|
556
|
-
for (const n of BOXED_TOOLS.keys()) OWN_BOX.add(n);
|
|
557
|
-
|
|
558
|
-
const MCP_TOOL = (name: string): boolean => name === "mcp" || name === "mcpScript" || name.startsWith("mcp__");
|
|
559
|
-
|
|
560
|
-
// Generic, not a name list: any tool that ships its own renderers is boxed, unless
|
|
561
|
-
// it declares `renderShell: "self"` (our own `minimal()`/codemode boxes) or sits in
|
|
562
|
-
// NOT_BOXED. That covers every third-party extension without a registration step:
|
|
563
|
-
// pi-fff (`ffgrep`/`fffind`, and `find`/`grep` in its override mode), pi core's
|
|
564
|
-
// `powershell`/`ls` (their definitions spread `renderCall`/`renderResult` onto the
|
|
565
|
-
// tool object) and pi-mcp-adapter (`renderShell: "default"`) all fall in by shape.
|
|
566
|
-
//
|
|
567
|
-
// MCP is boxed even when pi-mcp-adapter declares `renderShell: "self"`: since 2.3x
|
|
568
|
-
// its default `toolResultRendering: "compact"` paints flat text (`mcp call x @ y`,
|
|
569
|
-
// no border), so a `self` shell there means "no box", not "my own box".
|
|
570
|
-
//
|
|
571
|
-
// `source_check` is the single exception: its partial phase (curator URLs + approval
|
|
572
|
-
// state) would disappear because our partial path returns nothing.
|
|
573
|
-
const NOT_BOXED = new Set(["source_check"]);
|
|
574
|
-
const boxTheirRenderers = (self: any): boolean =>
|
|
575
|
-
Boolean(self.toolDefinition) &&
|
|
576
|
-
(self.toolDefinition.renderShell !== "self" || MCP_TOOL(self.toolName)) &&
|
|
577
|
-
!NOT_BOXED.has(self.toolName);
|
|
578
|
-
|
|
579
|
-
// The MCP box title names the invoked tool (full args when expanded).
|
|
580
|
-
const mcpInfo = (name: string, args: any, th: Theme): string => {
|
|
581
|
-
if (!MCP_TOOL(name)) return "";
|
|
582
|
-
const tool = String(args?.tool ?? "");
|
|
583
|
-
const server = String(args?.server ?? "");
|
|
584
|
-
return tool ? th.fg("dim", `${tool}${server ? ` @ ${server}` : ""}`) : "";
|
|
585
|
-
};
|
|
586
|
-
|
|
587
|
-
// Cap third-party lines in the call box; the rest goes behind [show].
|
|
588
|
-
const CALL_ROWS = 2;
|
|
589
|
-
const capped = (th: Theme, rows: string[], expanded: boolean): string[] =>
|
|
590
|
-
expanded || rows.length <= CALL_ROWS ? rows : [...rows.slice(0, CALL_ROWS), th.fg("dim", HINT_EXPAND)];
|
|
591
|
-
|
|
592
|
-
// Third-party renderers run unguarded here (at render time, unlike pi's own
|
|
593
|
-
// updateDisplay which wraps them in try/catch + fallback): a throw becomes an
|
|
594
|
-
// uncaughtException that exits pi. e.g. pi-web-access' get_content renderCall
|
|
595
|
-
// slices args.responseId — undefined on a partial/malformed tool call.
|
|
596
|
-
const safeCall = <T>(fn: () => T): T | null => {
|
|
597
|
-
try {
|
|
598
|
-
return fn();
|
|
599
|
-
} catch {
|
|
600
|
-
return null;
|
|
601
|
-
}
|
|
602
|
-
};
|
|
603
|
-
|
|
604
|
-
// Lines from a third-party renderer component (right padding trimmed, ANSI kept).
|
|
605
|
-
const componentLines = (component: any, width: number): string[] => {
|
|
606
|
-
try {
|
|
607
|
-
const lines = component?.render(Math.max(8, width));
|
|
608
|
-
return Array.isArray(lines) ? lines.map((l: string) => String(l).trimEnd()) : [];
|
|
609
|
-
} catch {
|
|
610
|
-
return [];
|
|
611
|
-
}
|
|
612
|
-
};
|
|
613
|
-
|
|
614
|
-
/** Right-align a label on the first row of `rows`, for a row pi did not build: the fold
|
|
615
|
-
* hint and the runtime still land where every other box puts them. */
|
|
616
|
-
const rightAlign = (th: Theme, rows: string[], inner: number, right: string): string[] => {
|
|
617
|
-
if (!right || rows.length === 0) return rows;
|
|
618
|
-
const label = th.fg("dim", right);
|
|
619
|
-
const avail = Math.max(4, inner - visibleWidth(label) - 1);
|
|
620
|
-
const head = truncateToWidth(rows[0]!, avail, "…");
|
|
621
|
-
const pad = Math.max(1, avail - visibleWidth(head));
|
|
622
|
-
return [`${head}${" ".repeat(pad)}${label}`, ...rows.slice(1)];
|
|
623
|
-
};
|
|
624
|
-
|
|
625
|
-
// Status icon + third-party lines -> our box content lines.
|
|
626
|
-
const boxedRows = (icon: string, lines: string[]): string[] => {
|
|
627
|
-
const body = lines.filter((l) => !isBlankLine(l));
|
|
628
|
-
return body.length ? [`${icon} ${body[0]}`, ...body.slice(1)] : [icon];
|
|
629
|
-
};
|
|
630
|
-
|
|
631
|
-
/**
|
|
632
|
-
* Subtle per-tool bg (see also toolPendingBg/toolSuccessBg for `todo`).
|
|
633
|
-
* `memory_write` uses customMessageBg: thin, violet-ish = "note", just distinct
|
|
634
|
-
* from the plain progress boxes. Use `name.startsWith("memory_")` to cover all
|
|
635
|
-
* memory tools.
|
|
636
|
-
*/
|
|
637
|
-
export const boxBgOf = (name: string): string | undefined => (name === "memory_write" ? "customMessageBg" : undefined);
|
|
638
|
-
|
|
639
|
-
if (ToolExecutionComponent?.prototype?.render) {
|
|
640
|
-
const proto = ToolExecutionComponent.prototype as any;
|
|
641
|
-
const origCall = originalOf<(this: any) => any>(proto, "getCallRenderer");
|
|
642
|
-
const origResult = originalOf<(this: any) => any>(proto, "getResultRenderer");
|
|
643
|
-
const origShell = originalOf<(this: any) => string>(proto, "getRenderShell");
|
|
644
|
-
const hasOwnRenderer = (self: any): boolean =>
|
|
645
|
-
!boxTheirRenderers(self) && Boolean(origCall.call(self) || origResult.call(self));
|
|
646
|
-
// pi-fff splits title (renderCall) and result (renderResult) — both merge into one box.
|
|
647
|
-
// Its two naming modes are covered: `find`/`grep` (override) and `ffgrep`/`fffind` (default).
|
|
648
|
-
const FFF_TOOLS = ["find", "grep", "ffgrep", "fffind"];
|
|
649
|
-
|
|
650
|
-
// A tool call with no registered definition (e.g. an unknown tool name that
|
|
651
|
-
// errored with "Tool X not found") makes hasRendererDefinition() false, so the
|
|
652
|
-
// constructor adds the plain contentText fallback and updateDisplay() never calls
|
|
653
|
-
// getCallRenderer/getResultRenderer — our patch is bypassed and the call renders
|
|
654
|
-
// as bare name + pretty-printed args. Claim those calls as defined so they take
|
|
655
|
-
// the same box path as any other renderer-less tool.
|
|
656
|
-
const origHasRendererDefinition = originalOf<(this: any) => boolean>(proto, "hasRendererDefinition");
|
|
657
|
-
proto.hasRendererDefinition = markPatched(function (this: any): boolean {
|
|
658
|
-
return origHasRendererDefinition.call(this) || this.toolDefinition === undefined;
|
|
659
|
-
});
|
|
660
|
-
|
|
661
|
-
proto.getRenderShell = markPatched(function (this: any): string {
|
|
662
|
-
if (boxTheirRenderers(this)) return "self";
|
|
663
|
-
return hasOwnRenderer(this) ? origShell.call(this) : "self";
|
|
664
|
-
});
|
|
665
|
-
|
|
666
|
-
proto.getCallRenderer = markPatched(function (this: any) {
|
|
667
|
-
const name: string = this.toolName;
|
|
668
|
-
const mine = boxTheirRenderers(this);
|
|
669
|
-
const own = origCall.call(this);
|
|
670
|
-
// Chrome DevTools' own renderCall is a bare line and pi-mcp-adapter's compact one
|
|
671
|
-
// is the same flat text; ours replaces both (icon + name + invoked MCP tool).
|
|
672
|
-
if (own && !mine && !CDP_NAME.has(name)) return own;
|
|
673
|
-
return (args: any, th: Theme, ctx: TCtx) =>
|
|
674
|
-
new Lines((width) => {
|
|
675
|
-
if ((ctx.state as Record<string, unknown> | undefined)?.hasResult) return [];
|
|
676
|
-
const icon = CDP_NAME.has(name) ? th.fg("accent", CDP_ICON) : th.fg("warning", spinIcon());
|
|
677
|
-
const theirs =
|
|
678
|
-
own && !CDP_NAME.has(name) && !MCP_TOOL(name)
|
|
679
|
-
? componentLines(safeCall(() => own.call(this, args, th, ctx)), width - 6)
|
|
680
|
-
: [];
|
|
681
|
-
if (mine && theirs.length)
|
|
682
|
-
return box(th, width, boxedRows(icon, capped(th, theirs, Boolean(this.expanded))));
|
|
683
|
-
const inner = Math.max(8, width - 4);
|
|
684
|
-
const rows = titleRow(
|
|
685
|
-
th,
|
|
686
|
-
icon,
|
|
687
|
-
th.fg("accent", displayName(name)),
|
|
688
|
-
name === "todo" ? todoTitleDetail(th, softSecondaryOf(th), actionWord(args?.action, args?.status)) : mcpInfo(name, args, th),
|
|
689
|
-
inner,
|
|
690
|
-
"",
|
|
691
|
-
false,
|
|
692
|
-
);
|
|
693
|
-
return box(th, width, rows, boxBgOf(name));
|
|
694
|
-
});
|
|
695
|
-
});
|
|
696
|
-
|
|
697
|
-
proto.getResultRenderer = markPatched(function (this: any) {
|
|
698
|
-
const name: string = this.toolName;
|
|
699
|
-
const own = origResult.call(this);
|
|
700
|
-
// pi-fff splits title (renderCall) and result (renderResult); both go in one box.
|
|
701
|
-
const fff = FFF_TOOLS.includes(name) && this.toolDefinition?.renderShell !== "self";
|
|
702
|
-
// MCP: their result renderer is deliberately skipped (unbounded error dump).
|
|
703
|
-
if (own && !boxTheirRenderers(this)) return own;
|
|
704
|
-
// Chrome DevTools are in BOXED_TOOLS for the title/icon only: their renderResult
|
|
705
|
-
// (raw text, empty when collapsed) would drop our title row, so it is ignored.
|
|
706
|
-
const cdp = CDP_NAME.has(name);
|
|
707
|
-
return (result: TResult, opts: { expanded: boolean; isPartial?: boolean }, th: Theme, ctx: TCtx) => {
|
|
708
|
-
if (opts.isPartial) return EMPTY;
|
|
709
|
-
((ctx.state ??= {}) as Record<string, unknown>).hasResult = true;
|
|
710
|
-
const text = textOf(result);
|
|
711
|
-
// pi-web-access reports failure via `details.error` without throwing, so
|
|
712
|
-
// ctx.isError alone is not enough: without this the error box shows ✓.
|
|
713
|
-
const isErr = Boolean(ctx.isError || result.isError || (result.details as { error?: unknown } | undefined)?.error);
|
|
714
|
-
// Their renderer content is reused inside our box unless it is unusable:
|
|
715
|
-
// MCP dumps the whole output on error (1-line summary instead), Chrome
|
|
716
|
-
// DevTools is a bare line, and errors take our own path (pi-web-access'
|
|
717
|
-
// own error box would nest a box inside a box).
|
|
718
|
-
return new Lines((width) => {
|
|
719
|
-
const soft = softSecondaryOf(th);
|
|
720
|
-
const inner = Math.max(8, width - 4);
|
|
721
|
-
const icon = isErr ? th.fg("error", "x") : th.fg("success", "✓");
|
|
722
|
-
// Their renderer already answers `expanded`, so both states are measured: the fold
|
|
723
|
-
// label appears only when the other state really shows a different number of rows.
|
|
724
|
-
const theirsAt = (exp: boolean) =>
|
|
725
|
-
own && !isErr && !cdp && !MCP_TOOL(name)
|
|
726
|
-
? componentLines(
|
|
727
|
-
safeCall(() =>
|
|
728
|
-
own.call(this, { content: result.content, details: result.details }, { ...opts, expanded: exp }, th, ctx),
|
|
729
|
-
),
|
|
730
|
-
width - 6,
|
|
731
|
-
)
|
|
732
|
-
: [];
|
|
733
|
-
const boxed2 = theirsAt(opts.expanded);
|
|
734
|
-
// Only rows on screen decide: a renderer that answers `expanded` with the same visible
|
|
735
|
-
// height (a trailing newline, a blank row) has nothing to fold.
|
|
736
|
-
const rowsShown = (rows: string[]) => rows.filter((l) => !isBlankLine(l)).length;
|
|
737
|
-
const foldHint = rowsShown(theirsAt(!opts.expanded)) === rowsShown(boxed2) ? "" : opts.expanded ? HINT_COLLAPSE : HINT_EXPAND;
|
|
738
|
-
if (fff && boxed2.length) {
|
|
739
|
-
const callLines = componentLines(safeCall(() => origCall.call(this)?.call(this, ctx.args, th, ctx)), width - 6);
|
|
740
|
-
const head = `${icon} ${callLines[0]?.trim() || th.fg("accent", displayName(name))}`;
|
|
741
|
-
const right = [durationOf(ctx), foldHint].filter(Boolean).join(" · ");
|
|
742
|
-
return box(th, width, rightAlign(th, [head, ...boxed2], inner, right));
|
|
743
|
-
}
|
|
744
|
-
// Third-party content keeps its own template but not its own chrome: without this the
|
|
745
|
-
// box had no title row, so the tool name, the runtime and the fold label were all lost.
|
|
746
|
-
if (boxed2.length && !cdp) {
|
|
747
|
-
const rows = titleRow(
|
|
748
|
-
th,
|
|
749
|
-
icon,
|
|
750
|
-
th.fg("accent", displayName(name)),
|
|
751
|
-
mcpInfo(name, ctx.args, th),
|
|
752
|
-
inner,
|
|
753
|
-
durationOf(ctx),
|
|
754
|
-
opts.expanded,
|
|
755
|
-
foldHint,
|
|
756
|
-
);
|
|
757
|
-
return box(th, width, [...rows, ...boxed2]);
|
|
758
|
-
}
|
|
759
|
-
// A payload with no newline can still be a full screen of wrapped text, so the row
|
|
760
|
-
// count is measured at this width: a 40k-char JSON line folds like any other box.
|
|
761
|
-
const more = drawnRows(text, inner) > 1;
|
|
762
|
-
const rows = titleRow(
|
|
763
|
-
th,
|
|
764
|
-
icon,
|
|
765
|
-
th.fg("accent", displayName(name)),
|
|
766
|
-
name === "todo"
|
|
767
|
-
? todoTitleDetail(th, soft, (result.details as { detail?: unknown } | undefined)?.detail)
|
|
768
|
-
: mcpInfo(name, ctx.args, th),
|
|
769
|
-
inner,
|
|
770
|
-
durationOf(ctx),
|
|
771
|
-
opts.expanded,
|
|
772
|
-
more ? (opts.expanded ? HINT_COLLAPSE : HINT_EXPAND) : "",
|
|
773
|
-
);
|
|
774
|
-
const summary = toolSummary(name, text, ctx.args);
|
|
775
|
-
const summaryRow = oneRow(
|
|
776
|
-
`${resHead(th)}${summary ? ` ${paintLinks(summary, soft)}` : ""}`,
|
|
777
|
-
inner,
|
|
778
|
-
);
|
|
779
|
-
rows.push(summaryRow);
|
|
780
|
-
if (opts.expanded && more) {
|
|
781
|
-
// MCP args are gone once the call box is replaced by the result.
|
|
782
|
-
if (MCP_TOOL(name)) rows.push(th.fg("dim", `args ${JSON.stringify(ctx.args ?? {})}`));
|
|
783
|
-
rows.push(...fullText(result, th, inner));
|
|
784
|
-
}
|
|
785
|
-
return box(th, width, rows, boxBgOf(name));
|
|
786
|
-
});
|
|
787
|
-
};
|
|
788
|
-
});
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
/** `todo · completed`: the status the call left behind (or its action word), so the title says
|
|
792
|
-
* what happened and not just which tool ran. The word takes the soft accent tier, the dot stays
|
|
793
|
-
* dim. */
|
|
794
|
-
function todoTitleDetail(th: Theme, soft: (s: string) => string, word: unknown): string {
|
|
795
|
-
const text = typeof word === "string" ? word.trim() : "";
|
|
796
|
-
return text ? `${th.fg("dim", "·")} ${soft(text)}` : "";
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
// codemode: the script is highlighted, the calls and output come from pi's own details.
|
|
800
|
-
function codeLines(code: string): string[] {
|
|
801
|
-
const js = code.replace(/\r/g, "").trimEnd().replace(/\t/g, " ");
|
|
802
|
-
if (!js) return [];
|
|
803
|
-
try {
|
|
804
|
-
return highlightCode(js, "javascript");
|
|
805
|
-
} catch {
|
|
806
|
-
return js.split("\n");
|
|
807
|
-
}
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
/** `✓ todo {"action":"list"} 2ms` — status icon, tool name, muted args, dim duration. */
|
|
811
|
-
function formatCodemodeCall(call: any, th: Theme): string {
|
|
812
|
-
const [color, glyph] = STATUS_ICON[String(call?.status ?? "ok")] ?? ["error", "x"];
|
|
813
|
-
const dur = fmtMs(Number(call?.durationMs));
|
|
814
|
-
let line = ` ${th.fg(color, glyph)} ${th.fg("accent", String(call?.name ?? ""))}`;
|
|
815
|
-
if (call?.args) line += ` ${th.fg("muted", String(call.args))}`;
|
|
816
|
-
if (dur) line += ` ${th.fg("dim", dur)}`;
|
|
817
|
-
return line;
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
// codemode call status -> [theme colour, glyph], same mapping pi's own renderer uses.
|
|
821
|
-
const STATUS_ICON: Record<string, [string, string]> = {
|
|
822
|
-
running: ["warning", "…"],
|
|
823
|
-
ok: ["success", "✓"],
|
|
824
|
-
cancelled: ["muted", "⊘"],
|
|
825
|
-
error: ["error", "x"],
|
|
826
|
-
};
|
|
827
|
-
|
|
828
|
-
/** Drop pi's "Script completed\nWall time …\nOutput:" header (a rejected input has none). */
|
|
829
|
-
function codemodeOutput(content: unknown): string {
|
|
830
|
-
const blocks = (Array.isArray(content) ? content : []).filter((c: any) => c?.type === "text") as Array<{ text?: string }>;
|
|
831
|
-
const header = /^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n/;
|
|
832
|
-
return blocks
|
|
833
|
-
.map((c, i) => (i === 0 ? String(c.text ?? "").replace(header, "") : String(c.text ?? "")))
|
|
834
|
-
.join("\n")
|
|
835
|
-
.trim();
|
|
836
|
-
}
|
|
837
|
-
|
|
838
|
-
/** Script lines; collapsed keeps only the first, like the other tools' one-line call. */
|
|
839
|
-
function codemodeScript(code: string, expanded: boolean): { lines: string[]; hidden: number } {
|
|
840
|
-
const lines = codeLines(code);
|
|
841
|
-
if (expanded || lines.length <= 1) return { lines, hidden: 0 };
|
|
842
|
-
return { lines: lines.slice(0, 1), hidden: lines.length - 1 };
|
|
843
|
-
}
|
|
844
|
-
|
|
845
|
-
/** Every box row: title, script, nested calls, output. Collapsed is the title plus the
|
|
846
|
-
* script's first line, with the rest behind the expand hint. Expanding — or failing —
|
|
847
|
-
* shows everything: a truncated error would read as a short, successful run. */
|
|
848
|
-
function codemodeBoxRows(
|
|
849
|
-
args: any,
|
|
850
|
-
result: { content?: unknown; details?: any } | undefined,
|
|
851
|
-
th: Theme,
|
|
852
|
-
expanded: boolean,
|
|
853
|
-
isErr: boolean,
|
|
854
|
-
icon: string,
|
|
855
|
-
inner: number,
|
|
856
|
-
dur = "",
|
|
857
|
-
): string[] {
|
|
858
|
-
const code = typeof args?.code === "string" ? args.code : "";
|
|
859
|
-
const script = codemodeScript(code, expanded);
|
|
860
|
-
const calls = (result?.details?.calls as any[] | undefined) ?? [];
|
|
861
|
-
const output = codemodeOutput(result?.content);
|
|
862
|
-
const outLines = output ? output.split("\n") : [];
|
|
863
|
-
const shown = expanded || isErr;
|
|
864
|
-
// A failing run shows its calls and output even when collapsed, so only a multi-line
|
|
865
|
-
// script gives it anything to fold; a passing run folds multi-line scripts, calls and output.
|
|
866
|
-
const foldable = countLines(code) > 1 || (!isErr && (calls.length > 0 || outLines.length > 0));
|
|
867
|
-
const label = foldable ? (expanded ? HINT_COLLAPSE : HINT_EXPAND) : "";
|
|
868
|
-
const rows = titleRow(th, icon, th.fg("accent", "codemode"), "", inner, dur, expanded, label);
|
|
869
|
-
script.lines.forEach((line, i) => rows.push(i === 0 ? `${resHead(th)} ${line}` : ` ${line}`));
|
|
870
|
-
if (shown) {
|
|
871
|
-
if (calls.length || outLines.length) rows.push("");
|
|
872
|
-
rows.push(...calls.map((c) => formatCodemodeCall(c, th)), ...outLines.map((l) => th.fg("toolOutput", ` ${l}`)));
|
|
873
|
-
}
|
|
874
|
-
return rows;
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
// One render path for all tools (no per-tool duplication).
|
|
878
|
-
// renderCall = running box (); renderResult = final box (✓/x + right-aligned
|
|
879
|
-
// duration + summary); state.hasResult is written by renderResult and read at
|
|
880
|
-
// render() -> exactly one box, also after reload/restore. res & full are optional
|
|
881
|
-
// (default: first output line / dim detail).
|
|
882
|
-
function minimal(
|
|
883
|
-
pi: ExtensionAPI,
|
|
884
|
-
tool: { execute: (...a: any[]) => Promise<any> } & Record<string, unknown>,
|
|
885
|
-
name: (th: Theme, soft: (s: string) => string) => string,
|
|
886
|
-
call: (a: any, th: Theme, soft: (s: string) => string, expanded: boolean) => string,
|
|
887
|
-
res: Res = resText,
|
|
888
|
-
full: (r: TResult, th: Theme, inner: number) => string[] = fullText,
|
|
889
|
-
): void {
|
|
890
|
-
OWN_BOX.add(String(tool.name ?? ""));
|
|
891
|
-
pi.registerTool({
|
|
892
|
-
...tool,
|
|
893
|
-
renderShell: "self",
|
|
894
|
-
async execute(toolCallId: string, params: any, signal: any, onUpdate: any, ctx: any) {
|
|
895
|
-
const start = performance.now();
|
|
896
|
-
ACTIVE++;
|
|
897
|
-
syncTicker();
|
|
898
|
-
try {
|
|
899
|
-
return await tool.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
900
|
-
} finally {
|
|
901
|
-
recordTiming(toolCallId, Math.round(performance.now() - start));
|
|
902
|
-
ACTIVE--;
|
|
903
|
-
syncTicker();
|
|
904
|
-
}
|
|
905
|
-
},
|
|
906
|
-
renderCall(args: any, theme: Theme, context: TCtx) {
|
|
907
|
-
return new Lines((width) => {
|
|
908
|
-
// Read context.state live (never capture): renderResult may create it after renderCall.
|
|
909
|
-
if (context.state?.hasResult) return [];
|
|
910
|
-
const soft = softSecondaryOf(theme);
|
|
911
|
-
const inner = Math.max(8, width - 4);
|
|
912
|
-
const rows = titleRow(
|
|
913
|
-
theme,
|
|
914
|
-
theme.fg("warning", spinIcon()),
|
|
915
|
-
name(theme, soft),
|
|
916
|
-
call(args, theme, soft, false),
|
|
917
|
-
inner,
|
|
918
|
-
"",
|
|
919
|
-
false,
|
|
920
|
-
);
|
|
921
|
-
return box(theme, width, rows);
|
|
922
|
-
});
|
|
923
|
-
},
|
|
924
|
-
renderResult(
|
|
925
|
-
result: TResult,
|
|
926
|
-
{ expanded, isPartial }: { expanded: boolean; isPartial: boolean },
|
|
927
|
-
theme: Theme,
|
|
928
|
-
context: TCtx,
|
|
929
|
-
) {
|
|
930
|
-
if (isPartial) return EMPTY;
|
|
931
|
-
((context.state ??= {}) as Record<string, unknown>).hasResult = true;
|
|
932
|
-
const text = textOf(result);
|
|
933
|
-
// `ctx.isError`/`result.isError` are the only honest sources: output text starting with
|
|
934
|
-
// "Error" is normal content (a file whose first line says "Error handling...").
|
|
935
|
-
const isErr = Boolean(context.isError || result.isError);
|
|
936
|
-
const dur = durationOf(context as TCtx);
|
|
937
|
-
const icon = isErr ? theme.fg("error", "x") : theme.fg("success", "✓");
|
|
938
|
-
return new Lines((width) => {
|
|
939
|
-
const soft = softSecondaryOf(theme);
|
|
940
|
-
const inner = Math.max(8, width - 4);
|
|
941
|
-
// Anything the collapsed summary hides gets the standard hint; without it a
|
|
942
|
-
// two-line box (edit: `+1 / -1`) looks complete while the diff sits behind it.
|
|
943
|
-
const hasDetail =
|
|
944
|
-
drawnRows(text, inner) > 1 || Boolean((result.details as { diff?: string } | undefined)?.diff);
|
|
945
|
-
const label = hasDetail ? (expanded ? HINT_COLLAPSE : HINT_EXPAND) : "";
|
|
946
|
-
const rows = titleRow(
|
|
947
|
-
theme,
|
|
948
|
-
icon,
|
|
949
|
-
name(theme, soft),
|
|
950
|
-
call(context.args ?? {}, theme, soft, expanded),
|
|
951
|
-
inner,
|
|
952
|
-
dur,
|
|
953
|
-
expanded,
|
|
954
|
-
label,
|
|
955
|
-
);
|
|
956
|
-
const resLine = res(result, theme, soft, isErr, expanded);
|
|
957
|
-
if (expanded) rows.push(...full(result, theme, inner));
|
|
958
|
-
else if (resLine) rows.push(oneRow(resLine, inner));
|
|
959
|
-
return box(theme, width, rows);
|
|
960
|
-
});
|
|
961
|
-
},
|
|
962
|
-
} as any);
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
function arnativeTools(pi: ExtensionAPI) {
|
|
966
|
-
// codemode keeps pi's own data (script + nested calls + output) wrapped in the arnative
|
|
967
|
-
// box, bg like every other tool. A resolver runs first and returns our renderers for
|
|
968
|
-
// that name; `next()` would give pi's unboxed ones.
|
|
969
|
-
OWN_BOX.add("codemode");
|
|
970
|
-
pi.registerToolRenderer((toolName, next) => (toolName === "codemode" ? codemodeRenderers : next()));
|
|
971
|
-
|
|
972
|
-
// Re-render source for the spinner + ticker cleanup when the session closes
|
|
973
|
-
pi.on("session_start", async (_event, ctx) => {
|
|
974
|
-
TIMINGS.clear();
|
|
975
|
-
requestRenderFn = () => {
|
|
976
|
-
try {
|
|
977
|
-
(ctx.ui as { requestRender?: () => void }).requestRender?.();
|
|
978
|
-
} catch {
|
|
979
|
-
// ignore
|
|
980
|
-
}
|
|
981
|
-
};
|
|
982
|
-
});
|
|
983
|
-
pi.on("session_shutdown", async () => {
|
|
984
|
-
TIMINGS.clear();
|
|
985
|
-
ACTIVE = 0;
|
|
986
|
-
if (TICK) {
|
|
987
|
-
clearInterval(TICK);
|
|
988
|
-
TICK = null;
|
|
989
|
-
}
|
|
990
|
-
requestRenderFn = null;
|
|
991
|
-
});
|
|
992
|
-
|
|
993
|
-
// Gap is only stripped for our own boxes (see OWN_BOX above).
|
|
994
|
-
|
|
995
|
-
const shellCall = (a: { command?: string }, _th: Theme, soft: (s: string) => string, expanded: boolean): string => {
|
|
996
|
-
const cmd = (a.command ?? "").replace(/\r?\n/g, " ").trim();
|
|
997
|
-
return paintLinks(expanded ? cmd : smartTitle(cmd), soft);
|
|
998
|
-
};
|
|
999
|
-
|
|
1000
|
-
// powershell: pi core registers it as a separate builtin (only on Windows); without
|
|
1001
|
-
// our own registration it keeps pi's "default" shell and renders as a bg block, not a
|
|
1002
|
-
// box (the same reason `bash` is re-registered below). Windows only: on any other
|
|
1003
|
-
// platform `getPowerShellConfig()` throws, and an unregistered tool would stay off
|
|
1004
|
-
// while our registration is active on load.
|
|
1005
|
-
if (process.platform === "win32")
|
|
1006
|
-
minimal(pi, createPowerShellTool(cwd), (th) => th.fg("accent", "PS>"), shellCall);
|
|
1007
|
-
|
|
1008
|
-
// ls: no renderShell of its own, so pi's default shell turns it into a bg block.
|
|
1009
|
-
minimal(
|
|
1010
|
-
pi,
|
|
1011
|
-
createLsTool(cwd),
|
|
1012
|
-
(th) => th.fg("accent", "ls"),
|
|
1013
|
-
(a, _th, soft) => soft(shortPath(a.path ?? ".")),
|
|
1014
|
-
numRes((n) => `${n} entries`),
|
|
1015
|
-
);
|
|
1016
|
-
|
|
1017
|
-
// bash: ` $ <6 words>…` / `✓ $ <full title when expanded> 0.1s`
|
|
1018
|
-
minimal(pi, createBashTool(cwd), (th) => th.fg("accent", "$"), shellCall);
|
|
1019
|
-
|
|
1020
|
-
// read: `read path[:range]` → ` N lines`
|
|
1021
|
-
minimal(
|
|
1022
|
-
pi,
|
|
1023
|
-
createReadTool(cwd),
|
|
1024
|
-
(th) => th.fg("accent", "read"),
|
|
1025
|
-
(a, _th, soft) => {
|
|
1026
|
-
const range =
|
|
1027
|
-
a.offset || a.limit ? `:${a.offset ?? 1}${a.limit ? `-${(a.offset ?? 1) + a.limit - 1}` : ""}` : "";
|
|
1028
|
-
return `${soft(shortPath(a.path ?? ""))}${range}`;
|
|
1029
|
-
},
|
|
1030
|
-
numRes((n) => `${n} lines`),
|
|
1031
|
-
);
|
|
1032
|
-
|
|
1033
|
-
// grep: `grep /pattern/ in path (glob)` → ` → N matches`
|
|
1034
|
-
minimal(
|
|
1035
|
-
pi,
|
|
1036
|
-
createGrepTool(cwd),
|
|
1037
|
-
(th) => th.fg("accent", "grep"),
|
|
1038
|
-
(a, _th, soft) =>
|
|
1039
|
-
`/${a.pattern ?? ""}/ in ${soft(shortPath(a.path ?? "."))}${a.glob ? ` (${a.glob})` : ""}`,
|
|
1040
|
-
numRes((n) => `→ ${n} matches`),
|
|
1041
|
-
);
|
|
1042
|
-
|
|
1043
|
-
// find: `find pattern in path` → ` → N files`
|
|
1044
|
-
minimal(
|
|
1045
|
-
pi,
|
|
1046
|
-
createFindTool(cwd),
|
|
1047
|
-
(th) => th.fg("accent", "find"),
|
|
1048
|
-
(a, _th, soft) => `${a.pattern ?? ""} in ${soft(shortPath(a.path ?? "."))}`,
|
|
1049
|
-
numRes((n) => `→ ${n} files`),
|
|
1050
|
-
);
|
|
1051
|
-
|
|
1052
|
-
// write: `write path`, default res (first output line)
|
|
1053
|
-
minimal(
|
|
1054
|
-
pi,
|
|
1055
|
-
createWriteTool(cwd),
|
|
1056
|
-
(th) => th.fg("accent", "write"),
|
|
1057
|
-
(a, _th, soft) => soft(shortPath(a.path ?? "")),
|
|
1058
|
-
);
|
|
1059
|
-
|
|
1060
|
-
// edit: `edit path`, ` +N / -M`, expand = diff toolDiff*
|
|
1061
|
-
minimal(
|
|
1062
|
-
pi,
|
|
1063
|
-
createEditTool(cwd),
|
|
1064
|
-
(th) => th.fg("accent", "edit"),
|
|
1065
|
-
(a, _th, soft) => soft(shortPath(a.path ?? "")),
|
|
1066
|
-
(r, th, _soft, isErr, expanded) => {
|
|
1067
|
-
if (isErr) return resText(r, th, (s) => s, isErr, false);
|
|
1068
|
-
const diff: string = r.details?.diff ?? "";
|
|
1069
|
-
let add = 0;
|
|
1070
|
-
let del = 0;
|
|
1071
|
-
for (const l of diff.split("\n")) {
|
|
1072
|
-
if (l.startsWith("+") && !l.startsWith("+++")) add++;
|
|
1073
|
-
else if (l.startsWith("-") && !l.startsWith("---")) del++;
|
|
1074
|
-
}
|
|
1075
|
-
return `${resHead(th)} ${th.fg("toolDiffAdded", `+${add}`)} / ${th.fg("toolDiffRemoved", `-${del}`)}`;
|
|
1076
|
-
},
|
|
1077
|
-
(r, th, inner) => formatEditDiff(r, th, inner),
|
|
1078
|
-
);
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
const SPLIT_DIFF_MIN_WIDTH = 50;
|
|
1082
|
-
const INTRA_LINE_MAX_TOKENS = 200;
|
|
1083
|
-
|
|
1084
|
-
export type EditDiffMode = "Split" | "Unified";
|
|
1085
|
-
export const EDIT_DIFF_CHOICES: readonly EditDiffMode[] = ["Split", "Unified"];
|
|
1086
|
-
const editDiffSetting = choiceSetting(EDIT_DIFF_KEY, EDIT_DIFF_CHOICES, "Split");
|
|
1087
|
-
const EDIT_DIFF_CONFIG_KEY = editDiffSetting.slot;
|
|
1088
|
-
|
|
1089
|
-
export const activeEditDiff = (): EditDiffMode => editDiffSetting.get();
|
|
1090
|
-
|
|
1091
|
-
export function setEditDiff(mode: EditDiffMode): void {
|
|
1092
|
-
editDiffSetting.set(mode);
|
|
1093
|
-
clearRenderCache();
|
|
1094
|
-
}
|
|
1095
|
-
|
|
1096
|
-
type DiffSide = { styled: string } | null;
|
|
1097
|
-
|
|
1098
|
-
function unifiedDiffLines(diff: string, th: Theme): string[] {
|
|
1099
|
-
return diff.split("\n").map((l) =>
|
|
1100
|
-
l.startsWith("+") && !l.startsWith("+++")
|
|
1101
|
-
? th.fg("toolDiffAdded", l)
|
|
1102
|
-
: l.startsWith("-") && !l.startsWith("---")
|
|
1103
|
-
? th.fg("toolDiffRemoved", l)
|
|
1104
|
-
: th.fg("toolDiffContext", l),
|
|
1105
|
-
);
|
|
1106
|
-
}
|
|
1107
|
-
|
|
1108
|
-
function tokenizeDiffLine(s: string): string[] {
|
|
1109
|
-
return s.match(/[A-Za-z0-9_]+|\s+|[^\sA-Za-z0-9_]/g) ?? [];
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
/**
|
|
1113
|
-
* Highlights changed tokens between paired old/new lines using `inverse`,
|
|
1114
|
-
* keeping leading indentation un-highlighted.
|
|
1115
|
-
*/
|
|
1116
|
-
function highlightLinePair(oldText: string, newText: string, th: Theme): { left: string; right: string } {
|
|
1117
|
-
const a = tokenizeDiffLine(oldText);
|
|
1118
|
-
const b = tokenizeDiffLine(newText);
|
|
1119
|
-
if (a.length === 0 || b.length === 0 || a.length > INTRA_LINE_MAX_TOKENS || b.length > INTRA_LINE_MAX_TOKENS) {
|
|
1120
|
-
return { left: th.fg("toolDiffRemoved", oldText), right: th.fg("toolDiffAdded", newText) };
|
|
1121
|
-
}
|
|
1122
|
-
|
|
1123
|
-
const m = a.length;
|
|
1124
|
-
const n = b.length;
|
|
1125
|
-
const dp: Uint16Array[] = Array.from({ length: m + 1 }, () => new Uint16Array(n + 1));
|
|
1126
|
-
for (let i = m - 1; i >= 0; i--) {
|
|
1127
|
-
for (let j = n - 1; j >= 0; j--) {
|
|
1128
|
-
dp[i]![j] = a[i] === b[j] ? dp[i + 1]![j + 1]! + 1 : Math.max(dp[i + 1]![j]!, dp[i]![j + 1]!);
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
|
|
1132
|
-
const inv = (s: string) => (th.inverse ? th.inverse(s) : `\x1b[7m${s}\x1b[27m`);
|
|
1133
|
-
let left = "";
|
|
1134
|
-
let right = "";
|
|
1135
|
-
let i = 0;
|
|
1136
|
-
let j = 0;
|
|
1137
|
-
let seenNonWsLeft = false;
|
|
1138
|
-
let seenNonWsRight = false;
|
|
1139
|
-
|
|
1140
|
-
const emitChanged = (tok: string, color: string, seenNonWs: boolean): [string, boolean] => {
|
|
1141
|
-
if (!seenNonWs && /^\s+$/.test(tok)) return [th.fg(color, tok), false];
|
|
1142
|
-
return [th.fg(color, inv(tok)), true];
|
|
1143
|
-
};
|
|
1144
|
-
|
|
1145
|
-
while (i < m && j < n) {
|
|
1146
|
-
if (a[i] === b[j]) {
|
|
1147
|
-
const tok = a[i]!;
|
|
1148
|
-
if (tok.trim()) {
|
|
1149
|
-
seenNonWsLeft = true;
|
|
1150
|
-
seenNonWsRight = true;
|
|
1151
|
-
}
|
|
1152
|
-
left += th.fg("toolDiffRemoved", tok);
|
|
1153
|
-
right += th.fg("toolDiffAdded", tok);
|
|
1154
|
-
i++;
|
|
1155
|
-
j++;
|
|
1156
|
-
} else if (dp[i + 1]![j]! >= dp[i]![j + 1]!) {
|
|
1157
|
-
const [chunk, seen] = emitChanged(a[i]!, "toolDiffRemoved", seenNonWsLeft);
|
|
1158
|
-
left += chunk;
|
|
1159
|
-
seenNonWsLeft = seen;
|
|
1160
|
-
i++;
|
|
1161
|
-
} else {
|
|
1162
|
-
const [chunk, seen] = emitChanged(b[j]!, "toolDiffAdded", seenNonWsRight);
|
|
1163
|
-
right += chunk;
|
|
1164
|
-
seenNonWsRight = seen;
|
|
1165
|
-
j++;
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
while (i < m) {
|
|
1169
|
-
const [chunk, seen] = emitChanged(a[i]!, "toolDiffRemoved", seenNonWsLeft);
|
|
1170
|
-
left += chunk;
|
|
1171
|
-
seenNonWsLeft = seen;
|
|
1172
|
-
i++;
|
|
1173
|
-
}
|
|
1174
|
-
while (j < n) {
|
|
1175
|
-
const [chunk, seen] = emitChanged(b[j]!, "toolDiffAdded", seenNonWsRight);
|
|
1176
|
-
right += chunk;
|
|
1177
|
-
seenNonWsRight = seen;
|
|
1178
|
-
j++;
|
|
1179
|
-
}
|
|
1180
|
-
return { left, right };
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
function wrapDiffCell(side: DiffSide, width: number): string[] {
|
|
1184
|
-
if (!side) return [""];
|
|
1185
|
-
const clean = side.styled.replace(/\t/g, " ");
|
|
1186
|
-
return clean === "" ? [""] : wrapTextWithAnsi(clean, width);
|
|
1187
|
-
}
|
|
1188
|
-
|
|
1189
|
-
function renderSplitPair(left: DiffSide, right: DiffSide, leftW: number, rightW: number, sep: string): string[] {
|
|
1190
|
-
const leftLines = wrapDiffCell(left, leftW);
|
|
1191
|
-
const rightLines = wrapDiffCell(right, rightW);
|
|
1192
|
-
const count = Math.max(leftLines.length, rightLines.length);
|
|
1193
|
-
const rows: string[] = [];
|
|
1194
|
-
for (let i = 0; i < count; i++) {
|
|
1195
|
-
const l = leftLines[i] ?? "";
|
|
1196
|
-
const r = rightLines[i] ?? "";
|
|
1197
|
-
const pad = " ".repeat(Math.max(0, leftW - visibleWidth(l)));
|
|
1198
|
-
rows.push(`${l}${pad}${sep}${r}`);
|
|
1199
|
-
}
|
|
1200
|
-
return rows;
|
|
1201
|
-
}
|
|
1202
|
-
|
|
1203
|
-
/**
|
|
1204
|
-
* Formats an `edit` diff side-by-side (Before | After) when the box inner width
|
|
1205
|
-
* is at least {@link SPLIT_DIFF_MIN_WIDTH}, falling back to unified diff on
|
|
1206
|
-
* narrow terminals or when `details.diff` is absent.
|
|
1207
|
-
*/
|
|
1208
|
-
export function formatEditDiff(r: TResult, th: Theme, inner: number, mode: EditDiffMode = activeEditDiff()): string[] {
|
|
1209
|
-
const diff: string = r.details?.diff ?? "";
|
|
1210
|
-
if (!diff) return fullText(r, th);
|
|
1211
|
-
if (mode === "Unified" || inner < SPLIT_DIFF_MIN_WIDTH) return unifiedDiffLines(diff, th);
|
|
1212
|
-
|
|
1213
|
-
const sep = th.fg("dim", " │ ");
|
|
1214
|
-
const leftW = Math.floor((inner - 3) / 2);
|
|
1215
|
-
const rightW = inner - 3 - leftW;
|
|
1216
|
-
const out: string[] = [
|
|
1217
|
-
`${th.fg("dim", "Before")}${" ".repeat(Math.max(0, leftW - 6))}${sep}${th.fg("dim", "After")}`,
|
|
1218
|
-
th.fg("dim", `${"─".repeat(leftW)}─┼─${"─".repeat(rightW)}`),
|
|
1219
|
-
];
|
|
1220
|
-
|
|
1221
|
-
let dels: string[] = [];
|
|
1222
|
-
let adds: string[] = [];
|
|
1223
|
-
const flushChanges = () => {
|
|
1224
|
-
const count = Math.max(dels.length, adds.length);
|
|
1225
|
-
for (let i = 0; i < count; i++) {
|
|
1226
|
-
const d = dels[i];
|
|
1227
|
-
const a = adds[i];
|
|
1228
|
-
if (d !== undefined && a !== undefined) {
|
|
1229
|
-
const { left, right } = highlightLinePair(d, a, th);
|
|
1230
|
-
out.push(...renderSplitPair({ styled: left }, { styled: right }, leftW, rightW, sep));
|
|
1231
|
-
} else {
|
|
1232
|
-
const left: DiffSide = d !== undefined ? { styled: th.fg("toolDiffRemoved", d) } : null;
|
|
1233
|
-
const right: DiffSide = a !== undefined ? { styled: th.fg("toolDiffAdded", a) } : null;
|
|
1234
|
-
out.push(...renderSplitPair(left, right, leftW, rightW, sep));
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
dels = [];
|
|
1238
|
-
adds = [];
|
|
1239
|
-
};
|
|
1240
|
-
|
|
1241
|
-
for (const line of diff.split("\n")) {
|
|
1242
|
-
if (line.startsWith("-") && !line.startsWith("---")) {
|
|
1243
|
-
dels.push(line.slice(1));
|
|
1244
|
-
} else if (line.startsWith("+") && !line.startsWith("+++")) {
|
|
1245
|
-
adds.push(line.slice(1));
|
|
1246
|
-
} else if (line.startsWith(" ")) {
|
|
1247
|
-
flushChanges();
|
|
1248
|
-
const side: DiffSide = { styled: th.fg("toolDiffContext", line.slice(1)) };
|
|
1249
|
-
out.push(...renderSplitPair(side, side, leftW, rightW, sep));
|
|
1250
|
-
} else {
|
|
1251
|
-
flushChanges();
|
|
1252
|
-
out.push(th.fg("toolDiffContext", line));
|
|
1253
|
-
}
|
|
1254
|
-
}
|
|
1255
|
-
flushChanges();
|
|
1256
|
-
return out;
|
|
1257
|
-
}
|
|
1258
|
-
|
|
1259
|
-
// codemode: pi's renderer wrapped in our box. renderShell "self" keeps the
|
|
1260
|
-
// execution defaults; renderCall/renderResult draw the box. state.hasResult
|
|
1261
|
-
// guarantees one box per call, also after reload/restore.
|
|
1262
|
-
const codemodeRenderers = {
|
|
1263
|
-
renderShell: "self" as const,
|
|
1264
|
-
renderCall(args: any, th: Theme, ctx: TCtx) {
|
|
1265
|
-
return new Lines((width) => {
|
|
1266
|
-
if (ctx.state?.hasResult) return [];
|
|
1267
|
-
const isErr = Boolean(ctx.isError);
|
|
1268
|
-
const bg = isErr ? "toolErrorBg" : "toolPendingBg";
|
|
1269
|
-
// Same spinner as every other box while the tool runs; the codemode glyph
|
|
1270
|
-
// only appears once the result is in (renderResult).
|
|
1271
|
-
const icon = th.fg("warning", spinIcon());
|
|
1272
|
-
return box(th, width, codemodeBoxRows(args, undefined, th, Boolean(ctx.expanded), isErr, icon, Math.max(8, width - 4)), bg);
|
|
1273
|
-
});
|
|
1274
|
-
},
|
|
1275
|
-
renderResult(result: TResult & { details?: any }, opts: { expanded: boolean; isPartial?: boolean }, th: Theme, ctx: TCtx) {
|
|
1276
|
-
if (opts.isPartial) return EMPTY;
|
|
1277
|
-
((ctx.state ??= {}) as Record<string, unknown>).hasResult = true;
|
|
1278
|
-
const isErr = Boolean(ctx.isError || result.isError);
|
|
1279
|
-
const icon = isErr ? th.fg("error", "x") : th.fg("success", "\uf489");
|
|
1280
|
-
const dur = durationOf(ctx);
|
|
1281
|
-
return new Lines((width) =>
|
|
1282
|
-
box(th, width, codemodeBoxRows(ctx.args, result, th, Boolean(opts.expanded), isErr, icon, Math.max(8, width - 4), dur), isErr ? "toolErrorBg" : "toolSuccessBg"),
|
|
1283
|
-
);
|
|
1284
|
-
},
|
|
1285
|
-
};
|
|
1286
|
-
|
|
1287
|
-
export default arnativeTools;
|
|
1288
|
-
|
|
1289
|
-
// Self-check: `node extensions/tools.ts`.
|
|
1290
|
-
if (isMain(import.meta.url)) {
|
|
1291
|
-
const mark = (s: string) => `<${s}>`;
|
|
1292
|
-
const th: Theme = { fg: (_c, s) => s };
|
|
1293
|
-
const R = { content: [{ type: "text", text: "path:1:match a\npath:2:match b\npath:3:match c" }] };
|
|
1294
|
-
|
|
1295
|
-
assert(smartTitle("echo hi") === "echo hi", "short text kept intact");
|
|
1296
|
-
assert(smartTitle("ls a b c d e f g h") === "ls a b c d e…", "cut at the 6-word limit");
|
|
1297
|
-
assert(smartTitle("a b c d e f g") === "a b c d e f…", "7 words -> 6 words + ellipsis");
|
|
1298
|
-
assert(smartTitle("a b c d e f") === "a b c d e f", "6 words kept intact");
|
|
1299
|
-
|
|
1300
|
-
assert(paintLinks("cd /run/media/x && echo hi", mark) === "cd </run/media/x> && echo hi", "filter path absolut");
|
|
1301
|
-
assert(paintLinks("git clone https://github.com/a/b", mark) === "git clone <https://github.com/a/b>", "filter link URL");
|
|
1302
|
-
assert(paintLinks("ls extensions/tools.ts", mark) === "ls <extensions/tools.ts>", "relative path filter");
|
|
1303
|
-
assert(paintLinks("echo plain 2>&1", mark) === "echo plain 2>&1", "plain text untouched");
|
|
1304
|
-
|
|
1305
|
-
// right-aligned duration, space-aware (overflow bug regression)
|
|
1306
|
-
const t1 = titleRow(th, "✓", "$", "echo hi", 30, "0.1s", false);
|
|
1307
|
-
assert(t1.length === 1 && visibleWidth(t1[0]) === 30, "duration right-aligned within the inner width");
|
|
1308
|
-
assert(t1[0].endsWith("0.1s"), "duration at the right end of the title");
|
|
1309
|
-
const t2 = titleRow(th, "✓", "$", "word ".repeat(40), 30, "0.1s", false);
|
|
1310
|
-
assert(t2.length === 1 && visibleWidth(t2[0]) === 30, "collapsed: long title stays 1 line, within width");
|
|
1311
|
-
const t3 = titleRow(th, "✓", "$", "word ".repeat(40), 30, "0.1s", true);
|
|
1312
|
-
assert(t3.every((l) => visibleWidth(l) <= 30), "expanded: every line <= inner");
|
|
1313
|
-
const t4 = titleRow(th, "✓", "$", "echo hi", 30, "", false);
|
|
1314
|
-
assert(!t4[0].includes("0.1s"), "no duration: empty (restored session)");
|
|
1315
|
-
|
|
1316
|
-
// crash regression: third-party renderCall throwing at build time (pi-web-access
|
|
1317
|
-
// get_content: responseId.slice on undefined) must be contained, not crash pi
|
|
1318
|
-
assert(
|
|
1319
|
-
safeCall(() => {
|
|
1320
|
-
const args: { responseId?: string } = {};
|
|
1321
|
-
return args.responseId!.slice(0, 8);
|
|
1322
|
-
}) === null,
|
|
1323
|
-
"renderCall throws -> null (not a crash)",
|
|
1324
|
-
);
|
|
1325
|
-
assert(
|
|
1326
|
-
componentLines(
|
|
1327
|
-
safeCall(() => {
|
|
1328
|
-
throw new Error("renderer crash");
|
|
1329
|
-
}),
|
|
1330
|
-
10,
|
|
1331
|
-
).length === 0,
|
|
1332
|
-
"renderer crash -> 0 lines",
|
|
1333
|
-
);
|
|
1334
|
-
|
|
1335
|
-
// no duplicate summary
|
|
1336
|
-
assert(resText(R, th, (s) => s, false, true) === "", "expand: empty summary");
|
|
1337
|
-
assert(resText(R, th, (s) => s, false, false) === " path:1:match a", "collapsed: first line shown");
|
|
1338
|
-
assert(numRes((n) => `→ ${n} matches`)(R, th, (s) => s, false, false) === " → 3 matches", "grep: N matches");
|
|
1339
|
-
assert(
|
|
1340
|
-
numRes((n) => `→ ${n} matches`)({ content: [{ type: "text", text: "Error: bad" }] }, th, (s) => s, true, false) ===
|
|
1341
|
-
" Error: bad",
|
|
1342
|
-
"error: falls back to the first line",
|
|
1343
|
-
);
|
|
1344
|
-
|
|
1345
|
-
// inter-box gap stripped
|
|
1346
|
-
assert(stripBlankEdges(["", "a", "", "b", " ", ""]).join() === "a,,b", "blank edge lines dropped");
|
|
1347
|
-
assert(stripBlankEdges(["", "\x1b[2m\x1b[22m", "x"]).join() === "x", "blank ANSI line counts as blank");
|
|
1348
|
-
assert(stripBlankEdges(["a"]).join() === "a", "no blanks: kept intact");
|
|
1349
|
-
|
|
1350
|
-
// Image preview: pi pads the image with blank rows (`result.rows - 1`), and the last
|
|
1351
|
-
// one carries a cursor-up prefix before the sequence. Those rows are the image's
|
|
1352
|
-
// vertical space — deleting them made the terminal paint the image over whatever
|
|
1353
|
-
// sits below (chat text, editor, footer). Regression: preview destroyed the layout.
|
|
1354
|
-
const kittySeq = "\x1b[5A\x1b_Ga=T,f=100,i=7,q=2,C=1,m=0;AAAA\x1b\\";
|
|
1355
|
-
const itermSeq = "\x1b]1337;File=inline=1:AAAA\x07";
|
|
1356
|
-
const withImage = ["", "╭─╮", "│ ✓ read form_crop.png │", "╰─╯", "", kittySeq, "", ""];
|
|
1357
|
-
const kept = stripEdgesKeepingImages(withImage);
|
|
1358
|
-
assert(kept.length === 6, "image: leading gap and box-image spacer dropped, blank tail kept");
|
|
1359
|
-
assert(kept[0] === "╭─╮", "image: leading Spacer removed");
|
|
1360
|
-
assert(kept.indexOf(kittySeq) === 3 && kept.length - 4 === 2, "image: rows after the sequence intact");
|
|
1361
|
-
assert(
|
|
1362
|
-
stripEdgesKeepingImages(["", "a", "", "b", " ", ""]).join() === "a,,b",
|
|
1363
|
-
"no image: falls back to plain edge stripping",
|
|
1364
|
-
);
|
|
1365
|
-
assert(isImageLine(itermSeq) && !isImageLine("│ plain text │"), "image line detection: kitty + iTerm2 only");
|
|
1366
|
-
|
|
1367
|
-
// tools without their own renderer -> same box (memory_write etc.)
|
|
1368
|
-
const noRenderer = { toolName: "memory_write", toolDefinition: {} };
|
|
1369
|
-
// tool with no definition (e.g. "Tool glob not found") -> still a box, not plain text
|
|
1370
|
-
const noDefinition = { toolName: "glob", toolDefinition: undefined, expanded: false };
|
|
1371
|
-
assert(
|
|
1372
|
-
ToolExecutionComponent.prototype.hasRendererDefinition.call(noDefinition) === true &&
|
|
1373
|
-
ToolExecutionComponent.prototype.getRenderShell.call(noDefinition) === "self",
|
|
1374
|
-
"tool without a definition: self shell (our box, not the plain fallback)",
|
|
1375
|
-
);
|
|
1376
|
-
assert(
|
|
1377
|
-
ToolExecutionComponent.prototype.hasRendererDefinition.call({ toolName: "x", toolDefinition: {} }) === true,
|
|
1378
|
-
"tool with a definition still has its renderer",
|
|
1379
|
-
);
|
|
1380
|
-
const noDefOut = (ToolExecutionComponent.prototype.getResultRenderer.call(noDefinition) as any)(
|
|
1381
|
-
{ content: [{ type: "text", text: '{\n "pattern": "**/*.ts"\n}\nTool glob not found' }] },
|
|
1382
|
-
{ expanded: false, isPartial: false },
|
|
1383
|
-
th,
|
|
1384
|
-
{ args: { pattern: "**/*.ts" }, state: {} },
|
|
1385
|
-
).render(60);
|
|
1386
|
-
assert(noDefOut[0].startsWith("\u256d") && noDefOut[noDefOut.length - 1].startsWith("\u2570"), "tool without a definition: result wrapped in a box");
|
|
1387
|
-
assert(
|
|
1388
|
-
noDefOut.some((l: string) => l.includes("\u2713 glob")) &&
|
|
1389
|
-
noDefOut.some((l: string) => l.includes('[show]')),
|
|
1390
|
-
"tool without a definition: title + summary + expand hint",
|
|
1391
|
-
);
|
|
1392
|
-
// todo (this package's own tool, no renderers): the title says what the call left behind.
|
|
1393
|
-
const todoNoRenderer = { toolName: "todo", toolDefinition: {} };
|
|
1394
|
-
const todoBox = (ToolExecutionComponent.prototype.getResultRenderer.call(todoNoRenderer) as any)(
|
|
1395
|
-
{ content: [{ type: "text", text: "Updated #1" }], details: { detail: "completed" } },
|
|
1396
|
-
{ expanded: false, isPartial: false },
|
|
1397
|
-
th,
|
|
1398
|
-
{ args: { action: "update", id: 1, status: "completed" }, state: {} },
|
|
1399
|
-
).render(60);
|
|
1400
|
-
assert(
|
|
1401
|
-
todoBox.some((l: string) => l.includes("todo · completed")),
|
|
1402
|
-
`todo result: the title names the status, got ${todoBox.find((l: string) => l.includes("todo"))}`,
|
|
1403
|
-
);
|
|
1404
|
-
assert(todoBox.some((l: string) => l.includes("Updated #1")), "todo result: the status line keeps the result text");
|
|
1405
|
-
const todoPending = (ToolExecutionComponent.prototype.getCallRenderer.call(todoNoRenderer) as any)(
|
|
1406
|
-
{ action: "create", subject: "Tulis widget" },
|
|
1407
|
-
th,
|
|
1408
|
-
{ state: {}, args: {} },
|
|
1409
|
-
).render(60);
|
|
1410
|
-
assert(todoPending.some((l: string) => l.includes("todo · created")), "todo call: the title names the action");
|
|
1411
|
-
assert(
|
|
1412
|
-
!todoBox.some((l: string) => l.includes("·") && l.includes("Tulis widget")),
|
|
1413
|
-
"todo: the task name stays on the status line, not in the title",
|
|
1414
|
-
);
|
|
1415
|
-
// Generic predicate: any tool that ships its own renderers and no `renderShell: "self"`
|
|
1416
|
-
// is boxed — no name list to maintain for new extensions.
|
|
1417
|
-
const withRenderer = { toolName: "bash", toolDefinition: { renderResult: () => undefined } };
|
|
1418
|
-
assert(ToolExecutionComponent.prototype.getRenderShell.call(noRenderer) === "self", "plain tool -> self shell");
|
|
1419
|
-
assert(
|
|
1420
|
-
ToolExecutionComponent.prototype.getRenderShell.call(withRenderer) === "self",
|
|
1421
|
-
"tool with its own renderer -> boxed too (generic predicate, no name list)",
|
|
1422
|
-
);
|
|
1423
|
-
const extTool = { toolName: "some_ext_tool", toolDefinition: { renderCall: () => undefined } };
|
|
1424
|
-
assert(
|
|
1425
|
-
ToolExecutionComponent.prototype.getRenderShell.call(extTool) === "self",
|
|
1426
|
-
"unknown third-party tool with its own renderer -> boxed",
|
|
1427
|
-
);
|
|
1428
|
-
assert(
|
|
1429
|
-
toolSummary("memory_write", "Appended to MEMORY.md\n\nExisting MEMORY.md preview (1 lines)", {
|
|
1430
|
-
content: "## omaga-sync workflow (2026-08-23)\n- Repo: /x",
|
|
1431
|
-
}) === "Appended to MEMORY.md. ## omaga-sync workflow (2026-08-23)",
|
|
1432
|
-
"memory_write: summary + the heading just written",
|
|
1433
|
-
);
|
|
1434
|
-
assert(
|
|
1435
|
-
toolSummary("memory_write", "Appended to daily log: /x/y.md", { content: "- note without a heading" }) ===
|
|
1436
|
-
"Appended to daily log: /x/y.md",
|
|
1437
|
-
"memory_write daily: no heading -> first line",
|
|
1438
|
-
);
|
|
1439
|
-
assert(toolSummary("todo", "line1\nline2") === "line1", "other tools: first line only");
|
|
1440
|
-
assert(
|
|
1441
|
-
toolSummary("mcp", '{\n "url": "https://example.com",\n "ok": true\n}') === '"url": "https://example.com",',
|
|
1442
|
-
"first line is just '{' -> next line becomes the summary (MCP JSON)",
|
|
1443
|
-
);
|
|
1444
|
-
assert(
|
|
1445
|
-
toolSummary("mcp", '{\n "url": "https://example.com",\n "ok": true\n}', {}) === '"url": "https://example.com",' &&
|
|
1446
|
-
toolSummary("mcp", "{") === "{",
|
|
1447
|
-
"JSON summary: use the content line, fall back to the first",
|
|
1448
|
-
);
|
|
1449
|
-
assert(toolSummary("memory_write", "Appended to MEMORY.md") === "Appended to MEMORY.md", "ballast: plain summary kept intact");
|
|
1450
|
-
|
|
1451
|
-
// distinct subtle bg: memory_write only
|
|
1452
|
-
assert(boxBgOf("memory_write") === "customMessageBg", "memory_write -> bg customMessageBg");
|
|
1453
|
-
assert(boxBgOf("bash") === undefined && boxBgOf("todo") === undefined, "other tools get no extra bg");
|
|
1454
|
-
const bgSeen: string[] = [];
|
|
1455
|
-
const thBgMem: Theme = { fg: (_c, s) => s, bg: (c, s) => (bgSeen.push(c), `<${s}>`) };
|
|
1456
|
-
const bgLines = box(thBgMem, 20, ["memory_write 0.1s", " Appended to MEMORY.md"], boxBgOf("memory_write"));
|
|
1457
|
-
assert(bgSeen.length === bgLines.length && bgSeen.every((c) => c === "customMessageBg"), "bg used on every box line");
|
|
1458
|
-
assert(bgLines.every((l) => visibleWidth(l.replace(/[<>]/g, "")) === 20), "bg does not break the box line width");
|
|
1459
|
-
assert(bgLines[0]!.replace(/[<>]/g, "").startsWith("╭"), "top line stays intact");
|
|
1460
|
-
|
|
1461
|
-
// pi-web-access: their renderer content, our box
|
|
1462
|
-
const paResult: any = { render: () => ["\x1b[32mPi Coding Agent\x1b[39m (77 matches, 77 shown)"] };
|
|
1463
|
-
const paCall: any = { render: () => ["\x1b[1mget_content \x1b[22m\x1b[36mfind 4\x1b[39m"] };
|
|
1464
|
-
const boxedRes = {
|
|
1465
|
-
toolName: "get_search_content",
|
|
1466
|
-
toolDefinition: { renderCall: () => paCall, renderResult: () => paResult },
|
|
1467
|
-
};
|
|
1468
|
-
assert(
|
|
1469
|
-
ToolExecutionComponent.prototype.getRenderShell.call(boxedRes) === "self",
|
|
1470
|
-
"pi-web-access: shell forced to self (joins our box, not a bg block)",
|
|
1471
|
-
);
|
|
1472
|
-
const searchRes = {
|
|
1473
|
-
toolName: "web_search",
|
|
1474
|
-
toolDefinition: { renderCall: () => ({ render: () => ["\x1b[1msearch \x1b[22m\x1b[36m\"site:pi.dev\"\x1b[39m"] }), renderResult: () => ({ render: () => ["\x1b[32m5 sources\x1b[39m"] }) },
|
|
1475
|
-
};
|
|
1476
|
-
assert(
|
|
1477
|
-
ToolExecutionComponent.prototype.getRenderShell.call(searchRes) === "self",
|
|
1478
|
-
"web_search: shell forced to self (joins our box)",
|
|
1479
|
-
);
|
|
1480
|
-
const bRes = ToolExecutionComponent.prototype.getResultRenderer.call(boxedRes) as any;
|
|
1481
|
-
const bOut = bRes(
|
|
1482
|
-
{ content: [{ type: "text", text: "raw text that must not be rendered" }], details: { matchCount: 77 } },
|
|
1483
|
-
{ expanded: false, isPartial: false },
|
|
1484
|
-
th,
|
|
1485
|
-
{ args: {} },
|
|
1486
|
-
).render(60);
|
|
1487
|
-
assert(bOut[0].startsWith("╭") && bOut[bOut.length - 1].startsWith("╰"), "pi-web-access: result wrapped in our box");
|
|
1488
|
-
assert(bOut.some((l: string) => l.includes("(77 matches, 77 shown)")), "pi-web-access: their renderer info kept");
|
|
1489
|
-
assert(!bOut.some((l: string) => l.includes("raw text")), "pi-web-access: raw text not used when a renderer exists");
|
|
1490
|
-
assert(
|
|
1491
|
-
bRes(
|
|
1492
|
-
{
|
|
1493
|
-
content: [{ type: "text", text: "No URL specified. Provide url, urlIndex, or query." }],
|
|
1494
|
-
details: { error: "No URL specified" },
|
|
1495
|
-
},
|
|
1496
|
-
{ expanded: false, isPartial: false },
|
|
1497
|
-
th,
|
|
1498
|
-
{ args: {} },
|
|
1499
|
-
)
|
|
1500
|
-
.render(60)
|
|
1501
|
-
.some((l: string) => l.includes("x get_content")),
|
|
1502
|
-
"pi-web-access: details.error -> x icon (not ✓)",
|
|
1503
|
-
);
|
|
1504
|
-
const bErr = bRes(
|
|
1505
|
-
{ content: [{ type: "text", text: "No URL specified. Provide url, urlIndex, or query." }] },
|
|
1506
|
-
{ expanded: false, isPartial: false },
|
|
1507
|
-
th,
|
|
1508
|
-
{ args: {}, isError: true },
|
|
1509
|
-
).render(60);
|
|
1510
|
-
assert(
|
|
1511
|
-
bErr.some((l: string) => l.includes("No URL specified")) &&
|
|
1512
|
-
bErr.filter((l: string) => l.includes("╭")).length === 1,
|
|
1513
|
-
"error: a single box (no nested box)",
|
|
1514
|
-
);
|
|
1515
|
-
assert(
|
|
1516
|
-
bRes({ content: [{ type: "text", text: "x" }] }, { expanded: false, isPartial: true }, th, { args: {} }).render(60)
|
|
1517
|
-
.length === 0,
|
|
1518
|
-
"pi-web-access: empty partial phase (no double box)",
|
|
1519
|
-
);
|
|
1520
|
-
const bCall = ToolExecutionComponent.prototype.getCallRenderer.call(boxedRes) as any;
|
|
1521
|
-
const bCallOut = bCall({}, th, { args: {}, state: {} }).render(60);
|
|
1522
|
-
assert(
|
|
1523
|
-
bCallOut[0].startsWith("╭") && bCallOut.some((l: string) => l.includes("find 4")),
|
|
1524
|
-
"pi-web-access: their renderer arg lines go in the box",
|
|
1525
|
-
);
|
|
1526
|
-
|
|
1527
|
-
// pi-fff override mode: find/grep re-registered with own renderers, no renderShell
|
|
1528
|
-
const fffCall = { render: () => ["\x1b[1mfind \x1b[22m\x1b[36m*.ts in /tmp/work\x1b[39m"] };
|
|
1529
|
-
const fffRes = { render: () => ["src/a.ts \x1b[2m... (6 more lines)\x1b[22m"] };
|
|
1530
|
-
const fffFind = { toolName: "find", toolDefinition: { renderCall: () => fffCall, renderResult: () => fffRes } };
|
|
1531
|
-
assert(
|
|
1532
|
-
ToolExecutionComponent.prototype.getRenderShell.call(fffFind) === "self",
|
|
1533
|
-
"pi-fff find: shell forced to self (joins our box)",
|
|
1534
|
-
);
|
|
1535
|
-
const fffOut = (ToolExecutionComponent.prototype.getResultRenderer.call(fffFind) as any)(
|
|
1536
|
-
{ content: [{ type: "text", text: "src/a.ts\nsrc/b.ts" }] },
|
|
1537
|
-
{ expanded: false, isPartial: false },
|
|
1538
|
-
th,
|
|
1539
|
-
{ args: { pattern: "*.ts", path: "/tmp/work" }, state: {} },
|
|
1540
|
-
).render(60);
|
|
1541
|
-
assert(fffOut[0].startsWith("╭") && fffOut[fffOut.length - 1].startsWith("╰"), "pi-fff find: result wrapped in a box");
|
|
1542
|
-
assert(fffOut.some((l: string) => l.includes("*.ts in /tmp/work")), "pi-fff find: renderCall title goes in the box");
|
|
1543
|
-
assert(fffOut.some((l: string) => l.includes("6 more lines")), "pi-fff find: renderResult summary goes in the box");
|
|
1544
|
-
|
|
1545
|
-
// pi-fff default mode (`ffgrep`/`fffind`): same renderer shape, different names.
|
|
1546
|
-
for (const n of ["ffgrep", "fffind"]) {
|
|
1547
|
-
const t = { toolName: n, toolDefinition: { renderCall: () => fffCall, renderResult: () => fffRes } };
|
|
1548
|
-
assert(
|
|
1549
|
-
ToolExecutionComponent.prototype.getRenderShell.call(t) === "self",
|
|
1550
|
-
`pi-fff ${n}: shell forced to self (default mode is boxed too)`,
|
|
1551
|
-
);
|
|
1552
|
-
const out = (ToolExecutionComponent.prototype.getResultRenderer.call(t) as any)(
|
|
1553
|
-
{ content: [{ type: "text", text: "src/a.ts\nsrc/b.ts" }] },
|
|
1554
|
-
{ expanded: false, isPartial: false },
|
|
1555
|
-
th,
|
|
1556
|
-
{ args: { pattern: "*.ts" }, state: {} },
|
|
1557
|
-
).render(60);
|
|
1558
|
-
assert(
|
|
1559
|
-
out[0].startsWith("╭") && out.some((l: string) => l.includes("6 more lines")),
|
|
1560
|
-
`pi-fff ${n}: result + summary merged into one box`,
|
|
1561
|
-
);
|
|
1562
|
-
}
|
|
1563
|
-
|
|
1564
|
-
// pi core `powershell` / `ls` spread their renderers into the tool object and set no
|
|
1565
|
-
// renderShell, so pi's "default" shell used to render them as a bare bg block (see the
|
|
1566
|
-
// OWN_BOX block below for the registration half of this fix).
|
|
1567
|
-
for (const [n, t] of [
|
|
1568
|
-
["powershell", createPowerShellToolDefinition(cwd)],
|
|
1569
|
-
["ls", createLsToolDefinition(cwd)],
|
|
1570
|
-
] as const) {
|
|
1571
|
-
assert(
|
|
1572
|
-
ToolExecutionComponent.prototype.getRenderShell.call({ toolName: n, toolDefinition: t }) === "self",
|
|
1573
|
-
`pi core ${n}: shell forced to self (joins our box, not a bg block)`,
|
|
1574
|
-
);
|
|
1575
|
-
}
|
|
1576
|
-
|
|
1577
|
-
const oursFind = { toolName: "find", toolDefinition: { renderShell: "self", renderCall: () => fffCall, renderResult: () => fffRes } };
|
|
1578
|
-
assert(
|
|
1579
|
-
(ToolExecutionComponent.prototype.getCallRenderer.call(oursFind) as any)() === fffCall &&
|
|
1580
|
-
(ToolExecutionComponent.prototype.getResultRenderer.call(oursFind) as any)() === fffRes,
|
|
1581
|
-
"our find (renderShell self): its own renderer as-is, not boxed again",
|
|
1582
|
-
);
|
|
1583
|
-
|
|
1584
|
-
// Guard: source_check is deliberately NOT boxed — its curator partial carries
|
|
1585
|
-
// URLs + approval state, while our partial path returns nothing. Without this
|
|
1586
|
-
// assert a later edit of BOXED_TOOLS would swallow it silently.
|
|
1587
|
-
for (const n of ["source_check"]) {
|
|
1588
|
-
const theirs = () => "their-renderer";
|
|
1589
|
-
assert(
|
|
1590
|
-
ToolExecutionComponent.prototype.getResultRenderer.call({ toolName: n, toolDefinition: { renderResult: theirs } })() ===
|
|
1591
|
-
"their-renderer",
|
|
1592
|
-
`${n}: deliberately not boxed (the curator partial needs URLs)`,
|
|
1593
|
-
);
|
|
1594
|
-
}
|
|
1595
|
-
|
|
1596
|
-
// pi-mcp-adapter: result does NOT use their renderer (unbounded error dump)
|
|
1597
|
-
// -> 1-line summary + [show]; the invoked tool stays visible.
|
|
1598
|
-
const mcpTheirs = () => "renderer-mcp";
|
|
1599
|
-
const mcpTool = { toolName: "mcp", toolDefinition: { renderCall: mcpTheirs, renderResult: mcpTheirs } };
|
|
1600
|
-
assert(
|
|
1601
|
-
(ToolExecutionComponent.prototype.getResultRenderer.call(mcpTool) as any) !== mcpTheirs,
|
|
1602
|
-
"mcp: third-party result renderer skipped (error dump capped)",
|
|
1603
|
-
);
|
|
1604
|
-
assert(
|
|
1605
|
-
(ToolExecutionComponent.prototype.getResultRenderer.call({ toolName: "mcp__tinyfish", toolDefinition: { renderResult: mcpTheirs } }) as any) !==
|
|
1606
|
-
mcpTheirs,
|
|
1607
|
-
"mcp__<server>: their renderer skipped (our box path)",
|
|
1608
|
-
);
|
|
1609
|
-
const mcpPayload = {
|
|
1610
|
-
content: [{ type: "text", text: "x Failed to call tool\nu Expected parameters:\n{\n \"required\": []\n}" }],
|
|
1611
|
-
details: { error: "failed" },
|
|
1612
|
-
};
|
|
1613
|
-
const mcpOut = (ToolExecutionComponent.prototype.getResultRenderer.call(mcpTool) as any)(
|
|
1614
|
-
mcpPayload,
|
|
1615
|
-
{ expanded: false, isPartial: false },
|
|
1616
|
-
th,
|
|
1617
|
-
{ args: { tool: "fetch_content", server: "tinyfish" }, state: {} },
|
|
1618
|
-
).render(96);
|
|
1619
|
-
assert(mcpOut.length <= 6, `mcp error collapsed stays short (${mcpOut.length} lines)`);
|
|
1620
|
-
assert(
|
|
1621
|
-
mcpOut.some((l: string) => l.includes("fetch_content @ tinyfish")),
|
|
1622
|
-
"mcp: title names the invoked MCP tool",
|
|
1623
|
-
);
|
|
1624
|
-
assert(mcpOut.some((l: string) => l.includes("[show]")), "mcp: expand hint present");
|
|
1625
|
-
// Nothing hidden (a single output line), so the label goes away in both states.
|
|
1626
|
-
const mcpTiny = { content: [{ type: "text", text: "ok" }], details: {} };
|
|
1627
|
-
for (const expanded of [false, true]) {
|
|
1628
|
-
const rows = (ToolExecutionComponent.prototype.getResultRenderer.call(mcpTool) as any)(
|
|
1629
|
-
mcpTiny,
|
|
1630
|
-
{ expanded, isPartial: false },
|
|
1631
|
-
th,
|
|
1632
|
-
{ args: { tool: "fetch_content", server: "tinyfish" }, state: {} },
|
|
1633
|
-
).render(96);
|
|
1634
|
-
assert(rows.every((l: string) => !l.includes("[show]") && !l.includes("[hide]")), `mcp: nothing hidden, so no label (expanded=${expanded})`);
|
|
1635
|
-
}
|
|
1636
|
-
// A box whose content comes from a third-party renderer still shows its runtime, the
|
|
1637
|
-
// way pi's own box did before this module replaced it.
|
|
1638
|
-
recordTiming("mcp-dur", 2400);
|
|
1639
|
-
const mcpTimed = (ToolExecutionComponent.prototype.getResultRenderer.call(mcpTool) as any)(
|
|
1640
|
-
mcpPayload,
|
|
1641
|
-
{ expanded: false, isPartial: false },
|
|
1642
|
-
th,
|
|
1643
|
-
{ args: { tool: "fetch_content", server: "tinyfish" }, state: {}, toolCallId: "mcp-dur" },
|
|
1644
|
-
).render(96);
|
|
1645
|
-
assert(mcpTimed[1]!.includes("2.4s"), "mcp: the title row carries the runtime");
|
|
1646
|
-
const mcpFull = (ToolExecutionComponent.prototype.getResultRenderer.call(mcpTool) as any)(
|
|
1647
|
-
mcpPayload,
|
|
1648
|
-
{ expanded: true, isPartial: false },
|
|
1649
|
-
th,
|
|
1650
|
-
{ args: { tool: "fetch_content", server: "tinyfish" }, state: {} },
|
|
1651
|
-
).render(96);
|
|
1652
|
-
assert(mcpFull.length > mcpOut.length, "mcp: expand shows the full dump + args");
|
|
1653
|
-
|
|
1654
|
-
// pi-mcp-adapter >= 2.3x defaults to `toolResultRendering: "compact"`, which sets
|
|
1655
|
-
// `renderShell: "self"` and paints flat text (`mcp call x @ y`, no border). That
|
|
1656
|
-
// `self` means "no box", not "my own box", so the MCP names must still be boxed.
|
|
1657
|
-
const mcpCompact = { toolName: "mcp", toolDefinition: { renderShell: "self", renderCall: mcpTheirs, renderResult: mcpTheirs } };
|
|
1658
|
-
assert(
|
|
1659
|
-
ToolExecutionComponent.prototype.getRenderShell.call(mcpCompact) === "self" &&
|
|
1660
|
-
(ToolExecutionComponent.prototype.getResultRenderer.call(mcpCompact) as any) !== mcpTheirs,
|
|
1661
|
-
"mcp compact (renderShell self): still boxed, their flat renderer skipped",
|
|
1662
|
-
);
|
|
1663
|
-
const mcpCompactOut = (ToolExecutionComponent.prototype.getResultRenderer.call(mcpCompact) as any)(
|
|
1664
|
-
{ content: [{ type: "text", text: "ok" }], details: {} },
|
|
1665
|
-
{ expanded: false, isPartial: false },
|
|
1666
|
-
th,
|
|
1667
|
-
{ args: { tool: "cloudflare_execute", server: "cloudflare" }, state: {} },
|
|
1668
|
-
).render(96);
|
|
1669
|
-
assert(
|
|
1670
|
-
mcpCompactOut[0].startsWith("\u256d") && mcpCompactOut.some((l: string) => l.includes("cloudflare_execute @ cloudflare")),
|
|
1671
|
-
"mcp compact: bordered box naming the invoked tool",
|
|
1672
|
-
);
|
|
1673
|
-
const mcpCompactCall = (ToolExecutionComponent.prototype.getCallRenderer.call(mcpCompact) as any)(
|
|
1674
|
-
{ tool: "cloudflare_execute", server: "cloudflare" },
|
|
1675
|
-
th,
|
|
1676
|
-
{ args: {}, state: {} },
|
|
1677
|
-
).render(96);
|
|
1678
|
-
assert(
|
|
1679
|
-
mcpCompactCall[0].startsWith("\u256d") && mcpCompactCall.some((l: string) => l.includes("cloudflare_execute @ cloudflare")),
|
|
1680
|
-
"mcp compact: the running box is ours too (no flat `mcp call ...` line)",
|
|
1681
|
-
);
|
|
1682
|
-
// A non-MCP fourth-party `renderShell: "self"` still draws its own box: untouched.
|
|
1683
|
-
assert(
|
|
1684
|
-
ToolExecutionComponent.prototype.getResultRenderer.call({ toolName: "other_ext", toolDefinition: { renderShell: "self", renderResult: mcpTheirs } })() === "renderer-mcp",
|
|
1685
|
-
"renderShell self outside MCP keeps its own renderer",
|
|
1686
|
-
);
|
|
1687
|
-
|
|
1688
|
-
// Gap is only stripped for our own box lines.
|
|
1689
|
-
// The default export registers the tools (filling OWN_BOX); a pi stub suffices.
|
|
1690
|
-
arnativeTools({
|
|
1691
|
-
registerTool: () => {},
|
|
1692
|
-
registerToolRenderer: () => {},
|
|
1693
|
-
on: () => {},
|
|
1694
|
-
registerShortcut: () => {},
|
|
1695
|
-
registerMessageRenderer: () => {},
|
|
1696
|
-
} as never);
|
|
1697
|
-
assert(
|
|
1698
|
-
OWN_BOX.has("bash") && OWN_BOX.has("read") && OWN_BOX.has("edit") && OWN_BOX.has("fetch_content") && OWN_BOX.has("web_search"),
|
|
1699
|
-
"OWN_BOX: our own tools + boxed tools registered",
|
|
1700
|
-
);
|
|
1701
|
-
assert(!OWN_BOX.has("mcp") && !OWN_BOX.has("source_check"), "OWN_BOX: third-party renderers not tightened");
|
|
1702
|
-
// pi core `powershell`/`ls` spread their renderer functions onto the tool object and
|
|
1703
|
-
// set no renderShell; that is exactly the shape that used to fall into pi's "default"
|
|
1704
|
-
// shell and render as a bare bg block. Registering them through minimal() boxes them.
|
|
1705
|
-
const coreReg: Record<string, any> = {};
|
|
1706
|
-
arnativeTools({ registerTool: (t: any) => { coreReg[t.name] = t; }, registerToolRenderer: () => {}, on: () => {} } as never);
|
|
1707
|
-
for (const [n, t] of [
|
|
1708
|
-
["powershell", createPowerShellToolDefinition(cwd)],
|
|
1709
|
-
["ls", createLsToolDefinition(cwd)],
|
|
1710
|
-
] as const) {
|
|
1711
|
-
const def = t as any;
|
|
1712
|
-
assert(
|
|
1713
|
-
Boolean(def.renderCall) && Boolean(def.renderResult),
|
|
1714
|
-
`pi core ${n}: the definition pi runs spreads its renderers onto the object`,
|
|
1715
|
-
);
|
|
1716
|
-
assert(
|
|
1717
|
-
ToolExecutionComponent.prototype.getRenderShell.call({ toolName: n, toolDefinition: def }) === "self",
|
|
1718
|
-
`pi core ${n}: shell forced to self (joins our box, not a bg block)`,
|
|
1719
|
-
);
|
|
1720
|
-
}
|
|
1721
|
-
// The guard is load-bearing: `getPowerShellConfig()` throws off Windows, and our
|
|
1722
|
-
// registration activates a tool the builtin deliberately leaves off.
|
|
1723
|
-
assert(
|
|
1724
|
-
coreReg.ls?.renderShell === "self",
|
|
1725
|
-
"pi core ls: registered through minimal() (boxing is live)",
|
|
1726
|
-
);
|
|
1727
|
-
assert(
|
|
1728
|
-
process.platform === "win32" ? coreReg.powershell?.renderShell === "self" : coreReg.powershell === undefined,
|
|
1729
|
-
"pi core powershell: registered on Windows only (getPowerShellConfig throws elsewhere)",
|
|
1730
|
-
); assert(hasOwnRendererDef(mcpTool) && !hasOwnRendererDef(noRenderer), "tightened benchmark: tool renderer definition");
|
|
1731
|
-
assert(
|
|
1732
|
-
capped(th, ["a", "b", "c"], false).length === CALL_ROWS + 1 &&
|
|
1733
|
-
capped(th, ["a", "b", "c"], true).length === 3 &&
|
|
1734
|
-
capped(th, ["a"], false).length === 1,
|
|
1735
|
-
"third-party call lines capped only when collapsed",
|
|
1736
|
-
);
|
|
1737
|
-
assert(
|
|
1738
|
-
mcpInfo("bash", { tool: "x" }, th) === "" && mcpInfo("mcp", { tool: "x", server: "s" }, th).includes("x @ s"),
|
|
1739
|
-
"mcpInfo only for MCP tools",
|
|
1740
|
-
);
|
|
1741
|
-
|
|
1742
|
-
const ctxState: TCtx = { args: { content: "## Heading\n- x" }, state: {} };
|
|
1743
|
-
const resRenderer = ToolExecutionComponent.prototype.getResultRenderer.call(noRenderer) as any;
|
|
1744
|
-
const out = resRenderer(
|
|
1745
|
-
{ content: [{ type: "text", text: "Appended to MEMORY.md\n\nExisting MEMORY.md preview" }] },
|
|
1746
|
-
{ expanded: false, isPartial: false },
|
|
1747
|
-
th,
|
|
1748
|
-
ctxState,
|
|
1749
|
-
).render(60);
|
|
1750
|
-
assert(out[0].startsWith("╭") && out[out.length - 1].startsWith("╰"), "plain tool result wrapped in a box");
|
|
1751
|
-
assert(
|
|
1752
|
-
out.some((l: string) => l.includes("Appended to MEMORY.md. ## Heading")),
|
|
1753
|
-
"box carries the summary + heading",
|
|
1754
|
-
);
|
|
1755
|
-
assert(out.some((l: string) => l.includes("[show]")), "collapsed: expand hint present");
|
|
1756
|
-
assert(
|
|
1757
|
-
resRenderer(
|
|
1758
|
-
{ content: [{ type: "text", text: "Appended to MEMORY.md\n\nExisting preview" }] },
|
|
1759
|
-
{ expanded: true, isPartial: false },
|
|
1760
|
-
th,
|
|
1761
|
-
ctxState,
|
|
1762
|
-
).render(60).length > out.length,
|
|
1763
|
-
"expand: full detail shown too",
|
|
1764
|
-
);
|
|
1765
|
-
|
|
1766
|
-
// stale box regression (restore-safe)
|
|
1767
|
-
const st: Record<string, unknown> = {};
|
|
1768
|
-
const comp = new Lines(() => (st.hasResult ? [] : ["row"]));
|
|
1769
|
-
assert(comp.render(10).length === 1, "running: box shown");
|
|
1770
|
-
st.hasResult = true;
|
|
1771
|
-
assert(comp.render(10).length === 0, "final: running box gone (restore-safe)");
|
|
1772
|
-
assert(FRAMES.includes(spinIcon()), "animation icon is always a valid frame");
|
|
1773
|
-
ACTIVE = 3;
|
|
1774
|
-
syncTicker();
|
|
1775
|
-
assert(TICK !== null, "ticker alive while a tool is running");
|
|
1776
|
-
ACTIVE = 0;
|
|
1777
|
-
syncTicker();
|
|
1778
|
-
assert(TICK === null, "ticker stops when idle (no timer leak)");
|
|
1779
|
-
|
|
1780
|
-
// Expanded detail: themed markdown, error text intact and no longer plain dim.
|
|
1781
|
-
const errDetail = fullText(
|
|
1782
|
-
{ content: [{ type: "text", text: '{\n "pattern": "**/*.ts"\n}\nTool glob not found' }], isError: true },
|
|
1783
|
-
th,
|
|
1784
|
-
40,
|
|
1785
|
-
);
|
|
1786
|
-
const plain = stripAnsi(errDetail.join("\n"));
|
|
1787
|
-
assert(plain.includes("Tool glob not found") && plain.includes('"pattern"'), "error detail: content intact");
|
|
1788
|
-
assert(
|
|
1789
|
-
errDetail.every((l: string) => visibleWidth(l) === 40),
|
|
1790
|
-
"error detail: rendered as markdown (wrapped + padded to width), not a plain line split",
|
|
1791
|
-
);
|
|
1792
|
-
assert(
|
|
1793
|
-
fullText({ content: [{ type: "text", text: "a\nb" }] }, th, 0).join("|") === th.fg("dim", "a") + "|" + th.fg("dim", "b"),
|
|
1794
|
-
"no width (self-check) still dumps dim",
|
|
1795
|
-
);
|
|
1796
|
-
|
|
1797
|
-
// codemode: one box per call, driven through the real component (what pi uses).
|
|
1798
|
-
const cmArgs = { code: 'const l = await tools.todo({ action: "list" });\nconsole.log(l);' };
|
|
1799
|
-
const cmRes = {
|
|
1800
|
-
content: [
|
|
1801
|
-
{ type: "text", text: "Script completed\nWall time 0.01 seconds\nOutput:\n" },
|
|
1802
|
-
{ type: "text", text: "alpha: ok" },
|
|
1803
|
-
],
|
|
1804
|
-
details: { calls: [{ status: "ok", name: "todo", args: '{"action":"list"}', durationMs: 2 }] },
|
|
1805
|
-
};
|
|
1806
|
-
initTheme(); // ToolExecutionComponent resolves a real theme, not the fg-passthrough stub
|
|
1807
|
-
const cmRender = (args: any, result: any, expanded = false) => {
|
|
1808
|
-
const c: any = new ToolExecutionComponent("codemode", "1", args, {}, codemodeRenderers as any, { requestRender() {} }, cwd);
|
|
1809
|
-
if (result) c.updateResult(result, false);
|
|
1810
|
-
c.setExpanded(expanded);
|
|
1811
|
-
// pi prefixes the box with a spacer blank line; drop blanks so the rows are predictable.
|
|
1812
|
-
return (c.render(100) as string[]).map(stripAnsi).filter((l) => l !== "");
|
|
1813
|
-
};
|
|
1814
|
-
recordTiming("1", 10);
|
|
1815
|
-
const cmCollapsed = cmRender(cmArgs, cmRes);
|
|
1816
|
-
assert(cmCollapsed.length === 4 && cmCollapsed[0]!.startsWith("╭") && cmCollapsed[3]!.startsWith("╰"), "codemode: collapsed box is title + one script line inside the border");
|
|
1817
|
-
assert(cmCollapsed[1]!.endsWith("10ms · [show] │"), "codemode: the title row right-aligns the runtime and expand hint");
|
|
1818
|
-
assert(cmCollapsed[2]!.includes("const l = await tools.todo"), "codemode: collapsed shows the first script line");
|
|
1819
|
-
const cmExpanded = cmRender(cmArgs, cmRes, true);
|
|
1820
|
-
assert(cmExpanded[1]!.endsWith("10ms · [hide] │"), "codemode: the expanded title row right-aligns the runtime and fold hint");
|
|
1821
|
-
assert(cmExpanded.some((l) => l.includes("✓ todo") && l.includes("2ms")) && cmExpanded.some((l) => l.includes("alpha: ok")), "codemode: expanded shows the nested calls and the output");
|
|
1822
|
-
// A failing run is never truncated: the whole output is shown without a hint in either state.
|
|
1823
|
-
const longErr = { content: [{ type: "text", text: "Script failed\nWall time 0.1 seconds\nOutput:\n" + Array.from({ length: 12 }, (_, i) => `line ${i + 1}`).join("\n") }], isError: true };
|
|
1824
|
-
const cmErr = cmRender({ code: "boom()" }, longErr);
|
|
1825
|
-
assert(cmErr.some((l) => l.includes("line 12")) && !cmErr.some((l) => l.includes("[show]")), "codemode: a failed run shows all its output, no hint");
|
|
1826
|
-
assert(!cmRender({ code: "boom()" }, longErr, true).some((l) => l.includes("[hide]")), "codemode: a failed single-line run has nothing to fold when expanded");
|
|
1827
|
-
// Running: the shared spinner, not the codemode glyph, and no hint while nothing is hidden.
|
|
1828
|
-
const cmRunning = cmRender({ code: "console.log(1);" }, undefined);
|
|
1829
|
-
assert(FRAMES.some((f) => cmRunning.join("\n").includes(f)) && !cmRunning.join("\n").includes("\uf489"), "codemode: running box uses the shared spinner, not the codemode glyph");
|
|
1830
|
-
assert(!cmRunning.some((l) => l.includes("[show]")), "codemode: nothing hidden on a single-line script");
|
|
1831
|
-
assert([...cmCollapsed, ...cmExpanded, ...cmErr].every((l) => visibleWidth(l) === 100), "codemode: box fills the given width");
|
|
1832
|
-
assert(fmtMs(2) === "2ms" && fmtMs(1400) === "1.4s" && fmtMs(undefined) === "", "duration wording: ms under a second, s above");
|
|
1833
|
-
assert(codemodeOutput(cmRes.content) === "alpha: ok", "codemode: Script completed header dropped (own block)");
|
|
1834
|
-
assert(codemodeOutput([{ type: "text", text: "Script completed\nWall time 0.01 seconds\nOutput:\n2" }]) === "2", "codemode: header dropped when joined with the output");
|
|
1835
|
-
// minimal(): a collapsed summary hides more than it shows -> hint; expanded shows all.
|
|
1836
|
-
{
|
|
1837
|
-
const reg2: Record<string, any> = {};
|
|
1838
|
-
const fakePi: any = { registerTool: (t: any) => { reg2[t.name] = t; }, registerToolRenderer: () => {}, on: () => {} };
|
|
1839
|
-
arnativeTools(fakePi);
|
|
1840
|
-
const minRender = (name: string, args: any, result: any, expanded = false) => {
|
|
1841
|
-
const c: any = new ToolExecutionComponent(name, "1", args, {}, reg2[name], { requestRender() {} }, cwd);
|
|
1842
|
-
c.updateResult(result, false);
|
|
1843
|
-
c.setExpanded(expanded);
|
|
1844
|
-
return (c.render(74) as string[]).map(stripAnsi).filter((l) => l !== "");
|
|
1845
|
-
};
|
|
1846
|
-
const diffRes = { content: [{ type: "text", text: "ok" }], details: { diff: "@@\n-old\n+new" } };
|
|
1847
|
-
// The runtime comes from pi's own duration first (a restored session, a tool this
|
|
1848
|
-
// module does not wrap), then from the wall clock this module records. The pinned
|
|
1849
|
-
// devDependency predates `durationMs`, so only the fallback is reachable here; the
|
|
1850
|
-
// pi-supplied path is checked against the installed 1.4.0 in the release audit.
|
|
1851
|
-
const withDur = (id: string, expanded: boolean) => {
|
|
1852
|
-
const c: any = new ToolExecutionComponent("bash", id, { command: "true" }, {}, reg2.bash, { requestRender() {} }, cwd);
|
|
1853
|
-
c.updateResult(diffRes, false);
|
|
1854
|
-
c.setExpanded(expanded);
|
|
1855
|
-
return (c.render(74) as string[]).map(stripAnsi).filter((l) => l !== "");
|
|
1856
|
-
};
|
|
1857
|
-
recordTiming("dur-collapsed", 1400);
|
|
1858
|
-
const durRow = withDur("dur-collapsed", false)[1]!;
|
|
1859
|
-
assert(durRow.includes("1.4s"), "duration: the collapsed title row keeps the runtime");
|
|
1860
|
-
assert(
|
|
1861
|
-
durRow.indexOf("1.4s") < durRow.indexOf("[show]") && durRow.includes("1.4s · [show]"),
|
|
1862
|
-
"duration: the runtime comes first, the label keeps the right edge",
|
|
1863
|
-
);
|
|
1864
|
-
recordTiming("dur-open", 400);
|
|
1865
|
-
const durOpen = withDur("dur-open", true);
|
|
1866
|
-
assert(
|
|
1867
|
-
durOpen[1]!.includes("400ms · [hide]"),
|
|
1868
|
-
"duration: the expanded title row carries the runtime before the fold label",
|
|
1869
|
-
);
|
|
1870
|
-
const bare = withDur("dur-none", false)[1]!;
|
|
1871
|
-
assert(!/dms|d.ds/.test(bare), "duration: a call with no figure leaves the row clean");
|
|
1872
|
-
const ed = minRender("edit", { path: "README.md" }, diffRes);
|
|
1873
|
-
assert(ed[1]!.includes("[show]"), "minimal(): the title row carries the expand hint");
|
|
1874
|
-
assert(ed.some((l) => l.includes("+1 / -1")), "minimal(): the summary stays on its own row");
|
|
1875
|
-
assert(!ed.some((l) => l.includes("+1 / -1") && l.includes("[show]")), "minimal(): the summary no longer shares its row with the hint");
|
|
1876
|
-
assert(!minRender("edit", { path: "README.md" }, diffRes, true).some((l) => l.includes("[show]")), "minimal(): expanded edit drops the hint");
|
|
1877
|
-
// Expanded, the affordance stays: the same key folds the box back, on the title row.
|
|
1878
|
-
const opened = minRender("edit", { path: "README.md" }, diffRes, true);
|
|
1879
|
-
assert(opened[1]!.includes("[hide]"), "minimal(): the expanded title row offers the fold hint");
|
|
1880
|
-
assert(!opened.some((l) => l.includes("[show]")), "minimal(): the folded box offers no expand hint");
|
|
1881
|
-
assert(opened.every((l) => visibleWidth(l) === 74), "minimal(): the fold hint keeps every row the box width");
|
|
1882
|
-
assert(
|
|
1883
|
-
minRender("edit", { path: "README.md" }, { content: [{ type: "text", text: "done" }], details: {} }, true).every((l) => !l.includes("[hide]")),
|
|
1884
|
-
"minimal(): nothing hidden, so an expanded box offers no fold hint",
|
|
1885
|
-
);
|
|
1886
|
-
assert(
|
|
1887
|
-
minRender("bash", { command: "true" }, { content: [{ type: "text", text: "done" }], details: {} }).every((l) => !l.includes("[show]")),
|
|
1888
|
-
"minimal(): a single-line output has nothing hidden, so no hint",
|
|
1889
|
-
);
|
|
1890
|
-
// Output that merely STARTS with "Error" is content, not a failure: the box keeps its ✓.
|
|
1891
|
-
assert(
|
|
1892
|
-
minRender("bash", { command: "true" }, { content: [{ type: "text", text: "Error handling notes" }], details: {} }).some((l) => l.includes("✓")),
|
|
1893
|
-
"minimal(): text starting with 'Error' is not treated as a failed call",
|
|
1894
|
-
);
|
|
1895
|
-
assert(
|
|
1896
|
-
minRender("edit", { path: "README.md" }, diffRes).every((l) => visibleWidth(l) === 74),
|
|
1897
|
-
"minimal(): hint row still fills the box width",
|
|
1898
|
-
);
|
|
1899
|
-
// Side-by-side edit diff: Before | After at wide widths, unified fallback when narrow
|
|
1900
|
-
const diffTmp = mkdtempSync(join(tmpdir(), "arnative-editdiff-"));
|
|
1901
|
-
const prevAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
1902
|
-
process.env.PI_CODING_AGENT_DIR = diffTmp;
|
|
1903
|
-
delete (globalThis as Record<symbol, unknown>)[EDIT_DIFF_CONFIG_KEY];
|
|
1904
|
-
resetPresetCache();
|
|
1905
|
-
try {
|
|
1906
|
-
const openedIsolated = minRender("edit", { path: "README.md" }, diffRes, true);
|
|
1907
|
-
assert(openedIsolated.some((l) => l.includes("Before") && l.includes("│") && l.includes("After")), "edit: expanded view shows Before | After header");
|
|
1908
|
-
assert(openedIsolated.some((l) => l.includes("─┼─")), "edit: expanded view shows header separator");
|
|
1909
|
-
assert(openedIsolated.some((l) => l.includes("old") && !l.includes("-old") && l.includes("│") && l.includes("new") && !l.includes("+new")), "edit: expanded view pairs old and new without +/- prefix");
|
|
1910
|
-
const intraRes = { content: [{ type: "text", text: "ok" }], details: { diff: "-const x = 1;\n+const x = 2;" } };
|
|
1911
|
-
const intraLines = formatEditDiff(intraRes, th, 70);
|
|
1912
|
-
assert(intraLines.some((l) => l.includes("const x = \x1b[7m1\x1b[27m;") && l.includes("const x = \x1b[7m2\x1b[27m;")), "edit: intra-line diff highlights only changed tokens");
|
|
1913
|
-
const pureAdd = minRender("edit", { path: "README.md" }, { content: [{ type: "text", text: "ok" }], details: { diff: "+ 10 added\n 11 ctx" } }, true);
|
|
1914
|
-
assert(pureAdd.some((l) => /^\│\s+\│\s+10 added/.test(l)), "edit: pure addition leaves Before column blank and strips +");
|
|
1915
|
-
assert(pureAdd.some((l) => l.includes("11 ctx") && l.indexOf("11 ctx") !== l.lastIndexOf("11 ctx")), "edit: context line appears in both columns");
|
|
1916
|
-
assert(pureAdd.every((l) => visibleWidth(l) === 74), "edit: side-by-side rows keep exact box width");
|
|
1917
|
-
const narrow = formatEditDiff(diffRes, th, 40);
|
|
1918
|
-
assert(!narrow.some((l) => l.includes("Before") && l.includes("After")), "edit: narrow width falls back to unified diff");
|
|
1919
|
-
setEditDiff("Unified");
|
|
1920
|
-
const liveUnified = minRender("edit", { path: "README.md" }, diffRes, true);
|
|
1921
|
-
assert(!liveUnified.some((l) => l.includes("Before") && l.includes("After")), "edit: setEditDiff('Unified') switches immediately");
|
|
1922
|
-
assert(liveUnified.some((l) => l.includes("-old")) && liveUnified.some((l) => l.includes("+new")), "edit: Unified mode keeps +/- lines");
|
|
1923
|
-
setEditDiff("Split");
|
|
1924
|
-
const liveSplit = minRender("edit", { path: "README.md" }, diffRes, true);
|
|
1925
|
-
assert(liveSplit.some((l) => l.includes("Before") && l.includes("After")), "edit: setEditDiff('Split') switches back immediately");
|
|
1926
|
-
} finally {
|
|
1927
|
-
if (prevAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
1928
|
-
else process.env.PI_CODING_AGENT_DIR = prevAgentDir;
|
|
1929
|
-
delete (globalThis as Record<symbol, unknown>)[EDIT_DIFF_CONFIG_KEY];
|
|
1930
|
-
resetPresetCache();
|
|
1931
|
-
rmSync(diffTmp, { recursive: true, force: true });
|
|
1932
|
-
}
|
|
1933
|
-
}
|
|
1934
|
-
|
|
1935
|
-
// Chrome DevTools: their bare renderers are replaced by our box (title + summary).
|
|
1936
|
-
const textComp = (text: string, color?: string) => ({
|
|
1937
|
-
render: (w: number) => (text ? text.split("\n").map((l) => (color ? th.fg(color, l) : l).slice(0, Math.max(0, w))) : []),
|
|
1938
|
-
invalidate() {},
|
|
1939
|
-
});
|
|
1940
|
-
const cdpRes = {
|
|
1941
|
-
toolName: "chrome_devtools_navigate",
|
|
1942
|
-
toolDefinition: {
|
|
1943
|
-
renderCall: () => textComp("Chrome DevTools: navigate"),
|
|
1944
|
-
renderResult: () => textComp(""),
|
|
1945
|
-
},
|
|
1946
|
-
};
|
|
1947
|
-
// The call renderer is not theirs (their bare line would swallow our icon/title).
|
|
1948
|
-
assert(
|
|
1949
|
-
ToolExecutionComponent.prototype.getCallRenderer.call(cdpRes) !== (cdpRes.toolDefinition.renderCall as any)(),
|
|
1950
|
-
"chrome-devtools: their bare call renderer is replaced by our box",
|
|
1951
|
-
);
|
|
1952
|
-
const cdpResult = { content: [{ type: "text", text: 'navigated\n{\n "pageId": "p1",\n "url": "https://example.com"\n}' }], details: {} };
|
|
1953
|
-
const cdpComp = (result: any, expanded = false) => {
|
|
1954
|
-
const c: any = new ToolExecutionComponent("chrome_devtools_navigate", "1", { url: "https://example.com" }, {}, cdpRes.toolDefinition as any, { requestRender() {} }, cwd);
|
|
1955
|
-
if (result) c.updateResult(result, false);
|
|
1956
|
-
c.setExpanded(expanded);
|
|
1957
|
-
return (c.render(74) as string[]).map(stripAnsi).filter((l) => l !== "");
|
|
1958
|
-
};
|
|
1959
|
-
const cdpCollapsed = cdpComp(cdpResult);
|
|
1960
|
-
assert(
|
|
1961
|
-
cdpCollapsed[0]!.startsWith("╭") && cdpCollapsed[cdpCollapsed.length - 1]!.startsWith("╰") && cdpCollapsed.some((l) => l.includes("navigate")),
|
|
1962
|
-
"chrome-devtools: result renders in our box with the tool name",
|
|
1963
|
-
);
|
|
1964
|
-
const cdpCall = ToolExecutionComponent.prototype.getCallRenderer.call(cdpRes) as any;
|
|
1965
|
-
const cdpCallOut: string[] = cdpCall({ url: "https://example.com" }, th, { args: {}, state: {} }).render(74);
|
|
1966
|
-
assert(
|
|
1967
|
-
cdpCallOut[0]!.startsWith("╭") && cdpCallOut.some((l) => stripAnsi(l).includes("Chrome DevTools: navigate")),
|
|
1968
|
-
"chrome-devtools: call box keeps the tool title and the CDP glyph",
|
|
1969
|
-
);
|
|
1970
|
-
assert(stripAnsi(cdpCallOut[1]!).includes(CDP_ICON), "chrome-devtools: call box uses the Chrome glyph, not the spinner");
|
|
1971
|
-
const cdpExpanded = cdpComp(cdpResult, true);
|
|
1972
|
-
assert(cdpExpanded.some((l) => l.includes('"pageId": "p1"')), "chrome-devtools: expanded shows the full tool output");
|
|
1973
|
-
assert(cdpCollapsed.some((l) => l.includes("navigated")), "chrome-devtools: collapsed shows the first line");
|
|
1974
|
-
assert(cdpCollapsed[1]!.includes("[show]"), "chrome-devtools: the title row carries the expand hint");
|
|
1975
|
-
assert([...cdpCollapsed, ...cdpExpanded].every((l) => visibleWidth(l) === 74), "chrome-devtools: box fills the given width");
|
|
1976
|
-
// Mouse on a tool box: the strip patch removes the blank rows above the box AFTER
|
|
1977
|
-
// pi laid out its mouse regions, so a click used to land one row high and the top
|
|
1978
|
-
// border was dead. pi also drops the click when the pointer drifts one cell.
|
|
1979
|
-
const mouseBox = () => {
|
|
1980
|
-
const c: any = new ToolExecutionComponent("mouse_probe", "1", {}, {}, {}, { requestRender: () => undefined }, cwd);
|
|
1981
|
-
c.updateResult({ content: [{ type: "text", text: "one\ntwo\nthree" }] }, false);
|
|
1982
|
-
// Render before any event: pi only hit-tests a click against a box it has measured.
|
|
1983
|
-
c.render(60);
|
|
1984
|
-
return c;
|
|
1985
|
-
};
|
|
1986
|
-
// Height comes from the box as drawn, the same number pi puts in the event.
|
|
1987
|
-
const mouse = (c: any, type: string, y: number, x = 5): any =>
|
|
1988
|
-
c.handleMouse({
|
|
1989
|
-
type,
|
|
1990
|
-
button: "left",
|
|
1991
|
-
x,
|
|
1992
|
-
y,
|
|
1993
|
-
screenX: x,
|
|
1994
|
-
screenY: y,
|
|
1995
|
-
width: 60,
|
|
1996
|
-
height: (c.render(60) as string[]).length,
|
|
1997
|
-
shift: false,
|
|
1998
|
-
alt: false,
|
|
1999
|
-
ctrl: false,
|
|
2000
|
-
});
|
|
2001
|
-
const click = (c: any, y: number, x = 5) => {
|
|
2002
|
-
mouse(c, "press", y, x);
|
|
2003
|
-
mouse(c, "release", y, x);
|
|
2004
|
-
mouse(c, "click", y, x);
|
|
2005
|
-
};
|
|
2006
|
-
const spans = (c: any) => textSpans(c.render(60) as string[], "[show]");
|
|
2007
|
-
const probeLines = mouseBox().render(60) as string[];
|
|
2008
|
-
assert(
|
|
2009
|
-
probeLines.length === 4 && stripAnsi(probeLines[0]!).startsWith("╭"),
|
|
2010
|
-
"mouse probe: 4 rows, blank edges stripped",
|
|
2011
|
-
);
|
|
2012
|
-
{
|
|
2013
|
-
const box = mouseBox();
|
|
2014
|
-
const [hint] = spans(box);
|
|
2015
|
-
assert(hint !== undefined, "mouse: the drawn box carries the hint span");
|
|
2016
|
-
const x = hint!.start;
|
|
2017
|
-
click(box, hint!.row, x);
|
|
2018
|
-
assert(box.expanded === true, "mouse: a click on the hint expands");
|
|
2019
|
-
click(box, hint!.row, x);
|
|
2020
|
-
assert(box.expanded === false, "mouse: the next click on the hint collapses");
|
|
2021
|
-
}
|
|
2022
|
-
{
|
|
2023
|
-
// A one-cell drift used to swallow the click: the press toggles, so it cannot.
|
|
2024
|
-
const box = mouseBox();
|
|
2025
|
-
const [hint] = spans(box);
|
|
2026
|
-
const x = hint!.start;
|
|
2027
|
-
mouse(box, "press", hint!.row, x);
|
|
2028
|
-
mouse(box, "move", hint!.row, x + 1);
|
|
2029
|
-
mouse(box, "release", hint!.row, x + 1);
|
|
2030
|
-
assert(box.expanded === true, "mouse: a one-cell drift on the hint still expands");
|
|
2031
|
-
mouse(box, "click", hint!.row, x + 1);
|
|
2032
|
-
assert(box.expanded === true, "mouse: the swallowed click does not toggle twice");
|
|
2033
|
-
}
|
|
2034
|
-
{
|
|
2035
|
-
// A label inside the output is content, not a button: only the title rows are matched.
|
|
2036
|
-
const outLabel: any = new ToolExecutionComponent("bash", "8", { command: "printf" }, {}, {}, { requestRender() {} }, cwd);
|
|
2037
|
-
outLabel.updateResult({ content: [{ type: "text", text: "line\n[show] in the output\nmore" }], details: {} }, false);
|
|
2038
|
-
outLabel.setExpanded(true);
|
|
2039
|
-
const outLines = (outLabel.render(60) as string[]).map(stripAnsi);
|
|
2040
|
-
const labelRow = outLines.findIndex((l) => l.includes("in the output"));
|
|
2041
|
-
assert(labelRow > 1, "mouse: the output label sits below the title rows");
|
|
2042
|
-
const labelX = outLines[labelRow]!.indexOf("[show]");
|
|
2043
|
-
const labelTaken = outLabel.handleMouse({ type: "press", button: "left", x: labelX, y: labelRow, screenX: labelX, screenY: labelRow, width: 60, height: outLines.length, shift: false, alt: false, ctrl: false });
|
|
2044
|
-
assert(labelTaken === undefined && outLabel.expanded === true, "mouse: a [show] inside the output is not a button");
|
|
2045
|
-
}
|
|
2046
|
-
{
|
|
2047
|
-
// Expanded, the fold hint is a click target too: the same cells, the other label.
|
|
2048
|
-
const box = mouseBox();
|
|
2049
|
-
const [open] = textSpans(box.render(60) as string[], "[show]");
|
|
2050
|
-
click(box, open!.row, open!.start);
|
|
2051
|
-
assert(box.expanded === true, "mouse: the expand hint opens the box");
|
|
2052
|
-
const [fold] = textSpans(box.render(60) as string[], "[hide]");
|
|
2053
|
-
assert(fold !== undefined, "mouse: the expanded box draws the fold hint");
|
|
2054
|
-
// One cell of drift: pi would drop the click, so only the hint cells can fold it.
|
|
2055
|
-
const fx = fold!.start;
|
|
2056
|
-
mouse(box, "press", fold!.row, fx);
|
|
2057
|
-
mouse(box, "move", fold!.row, fx + 1);
|
|
2058
|
-
mouse(box, "release", fold!.row, fx + 1);
|
|
2059
|
-
assert(box.expanded === false, "mouse: a drifting press on the fold hint closes the box");
|
|
2060
|
-
mouse(box, "click", fold!.row, fx + 1);
|
|
2061
|
-
assert(box.expanded === false, "mouse: the swallowed click does not reopen it");
|
|
2062
|
-
}
|
|
2063
|
-
{
|
|
2064
|
-
// Every cell off the hint keeps press uncaptured for text selection, while a plain
|
|
2065
|
-
// single click anywhere on the box still toggles expand/collapse.
|
|
2066
|
-
const box = mouseBox();
|
|
2067
|
-
const taken = mouse(box, "press", 2, 6);
|
|
2068
|
-
assert(taken === undefined && box.expanded === false, "mouse: a press off the hint is left to pi (text selection)");
|
|
2069
|
-
mouse(box, "move", 2, 14);
|
|
2070
|
-
mouse(box, "release", 2, 14);
|
|
2071
|
-
assert(box.expanded === false, "mouse: a drag over the output does not expand the box");
|
|
2072
|
-
click(box, 1, 6);
|
|
2073
|
-
assert(box.expanded === true, "mouse: single click on box title text expands without blocking drag select");
|
|
2074
|
-
click(box, 0, 6);
|
|
2075
|
-
assert(box.expanded === false, "mouse: single click on top border collapses without blocking drag select");
|
|
2076
|
-
box.handleMouse({
|
|
2077
|
-
type: "click",
|
|
2078
|
-
button: "left",
|
|
2079
|
-
x: 6,
|
|
2080
|
-
y: 2,
|
|
2081
|
-
screenX: 6,
|
|
2082
|
-
screenY: 2,
|
|
2083
|
-
width: 60,
|
|
2084
|
-
height: (box.render(60) as string[]).length,
|
|
2085
|
-
clickCount: 2,
|
|
2086
|
-
shift: false,
|
|
2087
|
-
alt: false,
|
|
2088
|
-
ctrl: false,
|
|
2089
|
-
});
|
|
2090
|
-
assert(box.expanded === false, "mouse: double-click selection does not toggle box");
|
|
2091
|
-
}
|
|
2092
|
-
{
|
|
2093
|
-
// Expanded long output caps body height and offers clickable primary ↑/↓ N more borders.
|
|
2094
|
-
const prevRows = process.stdout.rows;
|
|
2095
|
-
Object.defineProperty(process.stdout, "rows", { value: 28, configurable: true });
|
|
2096
|
-
try {
|
|
2097
|
-
const maxBody = expandedBoxBodyLimit(28);
|
|
2098
|
-
assert(maxBody === 9, "expanded body viewport adapts cleanly (9 rows at 28-line terminal)");
|
|
2099
|
-
const longText = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`).join("\n");
|
|
2100
|
-
const longBox: any = new ToolExecutionComponent("bash", "9", { command: "seq 20" }, {}, {}, { requestRender() {} }, cwd);
|
|
2101
|
-
longBox.updateResult({ content: [{ type: "text", text: longText }], details: {} }, false);
|
|
2102
|
-
longBox.setExpanded(true);
|
|
2103
|
-
const topView = (longBox.render(60) as string[]).map(stripAnsi);
|
|
2104
|
-
assert(topView.length === maxBody + 3, `expanded long box caps height to ${maxBody + 3} lines`);
|
|
2105
|
-
assert(!topView[0]!.includes("↑") && topView[topView.length - 1]!.includes("↓ 12 more"), "top of expanded box shows only ↓ N more");
|
|
2106
|
-
const [downBtn] = textSpans(longBox.render(60) as string[], "↓ 12 more");
|
|
2107
|
-
assert(downBtn !== undefined, "↓ N more is clickable on bottom border");
|
|
2108
|
-
click(longBox, downBtn!.row, downBtn!.start);
|
|
2109
|
-
const midView = (longBox.render(60) as string[]).map(stripAnsi);
|
|
2110
|
-
assert(midView[0]!.includes("↑ 4 more") && midView[midView.length - 1]!.includes("↓ 8 more"), "clicking ↓ N more scrolls body down");
|
|
2111
|
-
assert(midView.some((l) => l.includes("line 4")) && !midView.some((l) => l.includes(" line 1")), "scrolled viewport hides scrolled-past rows");
|
|
2112
|
-
const [upBtn] = textSpans(longBox.render(60) as string[], "↑ 4 more");
|
|
2113
|
-
assert(upBtn !== undefined, "↑ N more is clickable on top border");
|
|
2114
|
-
click(longBox, upBtn!.row, upBtn!.start);
|
|
2115
|
-
const backView = (longBox.render(60) as string[]).map(stripAnsi);
|
|
2116
|
-
assert(!backView[0]!.includes("↑") && backView.some((l) => l.includes("line 1")), "clicking ↑ N more scrolls back to top");
|
|
2117
|
-
const edge = paintScrollEdge("\x1b[48;2;10;20;30m\x1b[2m╭──────────╮\x1b[39m\x1b[49m", "\u256d", "\u256e", "\u2191 1 more", 24, (t) => `<bdr>${t}</bdr>`, (t) => `<pri>${t}</pri>`);
|
|
2118
|
-
assert(edge.startsWith("\x1b[48;2;10;20;30m") && edge.endsWith("\x1b[49m") && edge.includes("<pri>↑ 1 more</pri>"), "scroll edge preserves background and paints N more in primary");
|
|
2119
|
-
} finally {
|
|
2120
|
-
Object.defineProperty(process.stdout, "rows", { value: prevRows, configurable: true });
|
|
2121
|
-
}
|
|
2122
|
-
}
|
|
2123
|
-
|
|
2124
|
-
// Capped timings map self-check
|
|
2125
|
-
for (let i = 0; i < 250; i++) recordTiming(`call_${i}`, i);
|
|
2126
|
-
assert(TIMINGS.size === MAX_TIMINGS, `TIMINGS size is bounded to ${MAX_TIMINGS}`);
|
|
2127
|
-
assert(!TIMINGS.has("call_0") && TIMINGS.has("call_249"), "TIMINGS evicts oldest entries");
|
|
2128
|
-
TIMINGS.clear();
|
|
2129
|
-
|
|
2130
|
-
// /reload re-evaluates this module inside the same pi process. The prototype patches
|
|
2131
|
-
// must reinstall with the new closures; a globalThis guard bailed out on the second
|
|
2132
|
-
// load and kept the old ones, so a UI fix never appeared until pi restarted.
|
|
2133
|
-
{
|
|
2134
|
-
const before = ToolExecutionComponent.prototype.getResultRenderer;
|
|
2135
|
-
await import(`${import.meta.url}?reload=1`);
|
|
2136
|
-
const after = ToolExecutionComponent.prototype.getResultRenderer;
|
|
2137
|
-
assert(after !== before, "/reload: the prototype patch reinstalls on re-evaluation");
|
|
2138
|
-
// The stored original must stay pi's own method: capturing our previous patch
|
|
2139
|
-
// wrapped every box in a second one (double border + double ✓).
|
|
2140
|
-
const stored = (ToolExecutionComponent.prototype as any)[Symbol.for("pi-arnative.protoOriginals")];
|
|
2141
|
-
const patchedMark = Symbol.for("pi-arnative.patchedMethod");
|
|
2142
|
-
assert(
|
|
2143
|
-
!stored.render[patchedMark] && !stored.getResultRenderer[patchedMark],
|
|
2144
|
-
"/reload: originals stay pi's own methods, never a previous patch",
|
|
2145
|
-
);
|
|
2146
|
-
const plainAfter = (ToolExecutionComponent.prototype.getResultRenderer.call(noRenderer) as any)(
|
|
2147
|
-
{ content: [{ type: "text", text: "Appended to MEMORY.md" }] },
|
|
2148
|
-
{ expanded: false, isPartial: false },
|
|
2149
|
-
th,
|
|
2150
|
-
{ args: {}, state: {} },
|
|
2151
|
-
).render(60);
|
|
2152
|
-
assert(
|
|
2153
|
-
plainAfter.filter((l: string) => l.startsWith("\u256d")).length === 1,
|
|
2154
|
-
"/reload: a plain tool draws one box, not a box inside a box",
|
|
2155
|
-
);
|
|
2156
|
-
const mcpAfter = (after as any).call(mcpCompact);
|
|
2157
|
-
assert(mcpAfter !== mcpTheirs, "/reload: MCP stays boxed after re-evaluation");
|
|
2158
|
-
const out2 = mcpAfter(
|
|
2159
|
-
{ content: [{ type: "text", text: "ok" }], details: {} },
|
|
2160
|
-
{ expanded: false, isPartial: false },
|
|
2161
|
-
th,
|
|
2162
|
-
{ args: { tool: "cloudflare_execute", server: "cloudflare" }, state: {} },
|
|
2163
|
-
).render(96);
|
|
2164
|
-
assert(
|
|
2165
|
-
out2[0].startsWith("\u256d") && out2.some((l: string) => l.includes("cloudflare_execute @ cloudflare")),
|
|
2166
|
-
"/reload: the box still renders (no double-patch loop, originals kept once)",
|
|
2167
|
-
);
|
|
2168
|
-
}
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
// --- Third-party boxes carry a title row, so they can be folded like any other ----
|
|
2172
|
-
// pi-web-access paints its own template; without our title row the box lost the tool
|
|
2173
|
-
// name, the runtime and the [show] label, so the only way to expand it was ctrl+o.
|
|
2174
|
-
const paFolding = {
|
|
2175
|
-
toolName: "web_search",
|
|
2176
|
-
toolDefinition: {
|
|
2177
|
-
renderResult: (_r: unknown, o: { expanded?: boolean }) => ({
|
|
2178
|
-
render: () => (o.expanded ? ["a", "b", "c", "d"] : ["a"]),
|
|
2179
|
-
}),
|
|
2180
|
-
},
|
|
2181
|
-
};
|
|
2182
|
-
const paFold = (expanded: boolean) =>
|
|
2183
|
-
(ToolExecutionComponent.prototype.getResultRenderer.call(paFolding) as any)(
|
|
2184
|
-
{ content: [{ type: "text", text: "raw" }], details: {} },
|
|
2185
|
-
{ expanded, isPartial: false },
|
|
2186
|
-
th,
|
|
2187
|
-
{ args: {}, state: {} },
|
|
2188
|
-
).render(80) as string[];
|
|
2189
|
-
const paFolded = paFold(false).map(stripAnsi);
|
|
2190
|
-
const paOpen = paFold(true).map(stripAnsi);
|
|
2191
|
-
assert(paFolded[1]!.includes("search"), "third-party box: the title row names the tool");
|
|
2192
|
-
assert(paFolded[1]!.includes("[show]"), "third-party box: collapsed offers [show]");
|
|
2193
|
-
assert(paOpen[1]!.includes("[hide]"), "third-party box: expanded offers [hide]");
|
|
2194
|
-
assert(paOpen.length > paFolded.length, "third-party box: expanding really shows more rows");
|
|
2195
|
-
// A renderer that ignores `expanded` has nothing to fold, so it gets no label.
|
|
2196
|
-
const flat = { toolName: "web_search", toolDefinition: { renderResult: () => ({ render: () => ["only line"] }) } };
|
|
2197
|
-
for (const expanded of [false, true]) {
|
|
2198
|
-
const rows = (ToolExecutionComponent.prototype.getResultRenderer.call(flat) as any)(
|
|
2199
|
-
{ content: [{ type: "text", text: "raw" }], details: {} },
|
|
2200
|
-
{ expanded, isPartial: false },
|
|
2201
|
-
th,
|
|
2202
|
-
{ args: {}, state: {} },
|
|
2203
|
-
).render(80) as string[];
|
|
2204
|
-
assert(rows.every((l: string) => !l.includes("[show]") && !l.includes("[hide]")), `third-party box: nothing to fold, no label (expanded=${expanded})`);
|
|
2205
|
-
}
|
|
2206
|
-
|
|
2207
|
-
// --- A one-line payload that fills the screen still folds ---------------------
|
|
2208
|
-
// A JSON reply has no newline, so it used to count as one row: no [show], and the
|
|
2209
|
-
// summary row wrapped into 30 rows because nothing clipped it.
|
|
2210
|
-
const longJson = JSON.stringify({ results: [{ url: "https://example.com", text: "x".repeat(4000) }] });
|
|
2211
|
-
const longBox = resRenderer(
|
|
2212
|
-
{ content: [{ type: "text", text: longJson }] },
|
|
2213
|
-
{ expanded: false, isPartial: false },
|
|
2214
|
-
th,
|
|
2215
|
-
{ args: {}, state: {} },
|
|
2216
|
-
).render(80) as string[];
|
|
2217
|
-
assert(longBox.some((l: string) => l.includes("[show]")), "a wrapped one-line payload offers [show]");
|
|
2218
|
-
assert(longBox.length <= 6, `a folded box stays short whatever the payload (${longBox.length} rows)`);
|
|
2219
|
-
assert(
|
|
2220
|
-
longBox.every((l: string) => !l.includes("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")),
|
|
2221
|
-
"the summary row is one row: the payload is clipped, not wrapped",
|
|
2222
|
-
);
|
|
2223
|
-
const shortBox = resRenderer(
|
|
2224
|
-
{ content: [{ type: "text", text: "done" }] },
|
|
2225
|
-
{ expanded: false, isPartial: false },
|
|
2226
|
-
th,
|
|
2227
|
-
{ args: {}, state: {} },
|
|
2228
|
-
).render(80) as string[];
|
|
2229
|
-
assert(shortBox.every((l: string) => !l.includes("[show]")), "a one-row answer has nothing to fold, so no label");
|
|
2230
|
-
console.log("OK");
|
|
2231
|
-
}
|