@bismawy/pi-arnative 0.16.1 → 0.18.1
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 +1691 -0
- package/{extensions → lib/features}/render-cache.ts +391 -218
- 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 +48 -49
- 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
|
@@ -0,0 +1,1202 @@
|
|
|
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 { createBashTool, createEditTool, createFindTool, createGrepTool, createLsTool, createPowerShellTool, createReadTool, createWriteTool, getMarkdownTheme, highlightCode, ToolExecutionComponent, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
23
|
+
import { Markdown, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
24
|
+
import { homedir } from "node:os";
|
|
25
|
+
import { join } from "node:path";
|
|
26
|
+
import { createHoldRepeat, inSpans, renderBoxLines as box, type HoldRepeat, type TextSpan, textSpans } from "../box.ts";
|
|
27
|
+
import { getActiveTheme, stripAnsi, softSecondaryOf } from "../ansi.ts";
|
|
28
|
+
import { actionWord } from "../todos.ts";
|
|
29
|
+
import {
|
|
30
|
+
EDIT_DIFF_CHOICES,
|
|
31
|
+
EDIT_DIFF_CONFIG_KEY,
|
|
32
|
+
activeEditDiff,
|
|
33
|
+
formatEditDiff,
|
|
34
|
+
setEditDiff,
|
|
35
|
+
type EditDiffMode,
|
|
36
|
+
} from "../edit-diff.ts";
|
|
37
|
+
import { markPatched, originalOf } from "../patch.ts";
|
|
38
|
+
import {
|
|
39
|
+
TOOL_BOX_SCROLL_HOLD_KEY as SCROLL_HOLD,
|
|
40
|
+
TOOL_BOX_SCROLL_OFFSET_KEY as SCROLL_OFFSET,
|
|
41
|
+
} from "../runtime.ts";
|
|
42
|
+
|
|
43
|
+
export { EDIT_DIFF_CHOICES, activeEditDiff, formatEditDiff, setEditDiff, type EditDiffMode };
|
|
44
|
+
|
|
45
|
+
export type Theme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; inverse?(text: string): string };
|
|
46
|
+
type ToolArgs = Record<string, unknown>;
|
|
47
|
+
type ToolDetails = { diff?: string; calls?: CodemodeCall[] } & Record<string, unknown>;
|
|
48
|
+
type TResult = { content: Array<{ type: string; text?: string }>; isError?: boolean; details?: ToolDetails };
|
|
49
|
+
export type TCtx = { isError?: boolean; toolCallId?: string; args?: ToolArgs; state?: Record<string, unknown>; durationMs?: number; expanded?: boolean };
|
|
50
|
+
type Res = (r: TResult, th: Theme, soft: (s: string) => string, isErr: boolean, expanded: boolean) => string;
|
|
51
|
+
|
|
52
|
+
interface CodemodeCall {
|
|
53
|
+
status?: string;
|
|
54
|
+
durationMs?: number;
|
|
55
|
+
name?: string;
|
|
56
|
+
args?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface RenderableComponent {
|
|
60
|
+
render?(width: number): string[];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface ToolMouseEventLike {
|
|
64
|
+
type: string;
|
|
65
|
+
button?: string;
|
|
66
|
+
x: number;
|
|
67
|
+
y: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
type ToolRendererFn = (args: ToolArgs, th: Theme, ctx: TCtx) => RenderableComponent;
|
|
71
|
+
type ToolResultRendererFn = (
|
|
72
|
+
result: TResult,
|
|
73
|
+
opts: { expanded: boolean; isPartial?: boolean },
|
|
74
|
+
th: Theme,
|
|
75
|
+
ctx: TCtx,
|
|
76
|
+
) => RenderableComponent;
|
|
77
|
+
|
|
78
|
+
interface PatchedToolComponent extends Record<symbol, unknown> {
|
|
79
|
+
toolName: string;
|
|
80
|
+
expanded?: boolean;
|
|
81
|
+
toolDefinition?: { renderShell?: string; renderCall?: ToolRendererFn; renderResult?: ToolResultRendererFn };
|
|
82
|
+
render(width: number): string[];
|
|
83
|
+
handleMouse?(event: ToolMouseEventLike): unknown;
|
|
84
|
+
hasRendererDefinition(): boolean;
|
|
85
|
+
getRenderShell(): string;
|
|
86
|
+
getCallRenderer(): ToolRendererFn | undefined;
|
|
87
|
+
getResultRenderer(): ToolResultRendererFn | undefined;
|
|
88
|
+
invalidate?: () => void;
|
|
89
|
+
ui?: { requestRender?: () => void };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const cwd = process.cwd();
|
|
93
|
+
const MAX_TIMINGS = 200;
|
|
94
|
+
const TIMINGS = new Map<string, number>();
|
|
95
|
+
|
|
96
|
+
/** Runtime of one call: pi's own figure first (it survives a restore and covers tools this
|
|
97
|
+
* module does not wrap), then the wall time recorded by the execute wrapper. */
|
|
98
|
+
const durationOf = (ctx: TCtx): string =>
|
|
99
|
+
fmtMs(ctx.durationMs ?? (ctx.toolCallId ? TIMINGS.get(ctx.toolCallId) : undefined));
|
|
100
|
+
|
|
101
|
+
export function recordTiming(toolCallId: string, durationMs: number): void {
|
|
102
|
+
if (TIMINGS.size >= MAX_TIMINGS) {
|
|
103
|
+
const oldest = TIMINGS.keys().next().value;
|
|
104
|
+
if (oldest !== undefined) TIMINGS.delete(oldest);
|
|
105
|
+
}
|
|
106
|
+
TIMINGS.set(toolCallId, durationMs);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function getToolTiming(toolCallId: string | undefined): number | undefined {
|
|
110
|
+
return toolCallId ? TIMINGS.get(toolCallId) : undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Running icon : 500ms spin frames from a ticker that only runs while
|
|
114
|
+
// a tool is active (idle = no wasteful re-renders).
|
|
115
|
+
const FRAMES = ["", "", ""];
|
|
116
|
+
let ACTIVE = 0;
|
|
117
|
+
let TICK: ReturnType<typeof setInterval> | null = null;
|
|
118
|
+
let requestRenderFn: (() => void) | null = null;
|
|
119
|
+
|
|
120
|
+
function syncTicker(): void {
|
|
121
|
+
if (ACTIVE > 0 && !TICK) {
|
|
122
|
+
TICK = setInterval(() => requestRenderFn?.(), 500);
|
|
123
|
+
} else if (ACTIVE <= 0 && TICK) {
|
|
124
|
+
clearInterval(TICK);
|
|
125
|
+
TICK = null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function spinIcon(): string {
|
|
130
|
+
return FRAMES[Math.floor(Date.now() / 500) % FRAMES.length];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Tool duration: `2ms` under a second, `1.4s` above — the wording pi itself uses. */
|
|
134
|
+
export function fmtMs(ms: number | undefined): string {
|
|
135
|
+
if (ms === undefined || !Number.isFinite(ms)) return "";
|
|
136
|
+
return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export class Lines {
|
|
140
|
+
private get: (width: number) => string[];
|
|
141
|
+
constructor(get: (width: number) => string[]) {
|
|
142
|
+
this.get = get;
|
|
143
|
+
}
|
|
144
|
+
render(width: number): string[] {
|
|
145
|
+
return this.get(width);
|
|
146
|
+
}
|
|
147
|
+
invalidate(): void {}
|
|
148
|
+
}
|
|
149
|
+
const EMPTY = new Lines(() => []);
|
|
150
|
+
|
|
151
|
+
export const shortPath = (p: string): string => {
|
|
152
|
+
const home = homedir();
|
|
153
|
+
return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const textOf = (r: TResult): string =>
|
|
157
|
+
r.content.filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n").trim();
|
|
158
|
+
|
|
159
|
+
const firstLine = (s: string): string => s.split("\n").find((l) => l.trim()) ?? "";
|
|
160
|
+
|
|
161
|
+
// Summary = first line with content. Punctuation-only lines (e.g. a lone `{` from
|
|
162
|
+
// pretty-printed MCP JSON) explain nothing -> take the next one.
|
|
163
|
+
const firstMeaningful = (s: string): string => {
|
|
164
|
+
const lines = s.split("\n").filter((l) => l.trim());
|
|
165
|
+
return lines.find((l) => !/^[\s{}\[\],;:]+$/.test(l)) ?? lines[0] ?? "";
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const countLines = (s: string): number => (s ? s.split("\n").filter(Boolean).length : 0);
|
|
169
|
+
|
|
170
|
+
// Tint folder paths / URLs; everything else default.
|
|
171
|
+
const LINK_RE = /(?:https?:\/\/[^\s"'`)}\]]+|(?:~|\.{1,2})?\/[\w.+@~%/-]+|[\w.+@~-]+(?:\/[\w.+@~%/-]+)+)/g;
|
|
172
|
+
export function paintLinks(text: string, soft: (s: string) => string): string {
|
|
173
|
+
return text.replace(LINK_RE, (m) => soft(m));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Word-limited smart title: `maxWords` words + ellipsis; full text when expanded.
|
|
177
|
+
export function smartTitle(cmd: string, maxWords = 6): string {
|
|
178
|
+
const words = cmd.replace(/\r?\n/g, " ").trim().split(/\s+/).filter(Boolean);
|
|
179
|
+
if (words.length <= maxWords) return words.join(" ");
|
|
180
|
+
return `${words.slice(0, maxWords).join(" ")}…`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Result line prefix: dim (duration lives at the right end of the title).
|
|
184
|
+
function resHead(theme: Theme): string {
|
|
185
|
+
return theme.fg("dim", "");
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Rows a block of text takes once painted at `width`, blank lines dropped: one long JSON
|
|
189
|
+
* string is a single newline but twenty-five rows on screen. Early-exits when `limit` is hit. */
|
|
190
|
+
const drawnRows = (text: string, width: number, limit = Number.POSITIVE_INFINITY): number => {
|
|
191
|
+
const w = Math.max(1, width);
|
|
192
|
+
let n = 0;
|
|
193
|
+
for (const l of text.split("\n")) {
|
|
194
|
+
if (!l.trim()) continue;
|
|
195
|
+
// Fast path: if raw length already exceeds limit * w (ASCII), avoid visibleWidth on huge blobs.
|
|
196
|
+
if (l.length > w * 2 && limit <= 2) return limit;
|
|
197
|
+
n += Math.max(1, Math.ceil(visibleWidth(l) / w));
|
|
198
|
+
if (n >= limit) return n;
|
|
199
|
+
}
|
|
200
|
+
return n;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
/** A summary is one row by definition: a single-line JSON payload of 40k chars would
|
|
204
|
+
* otherwise wrap into a full screen and the box would look expanded while folded. */
|
|
205
|
+
const oneRow = (text: string, inner: number): string => truncateToWidth(text, inner, "…");
|
|
206
|
+
|
|
207
|
+
// Title line: duration right-aligned and space-aware (title truncated when it
|
|
208
|
+
// doesn't fit); expanded = full title wrapped. All lines stay <= inner (overflow bug).
|
|
209
|
+
export function titleRow(
|
|
210
|
+
theme: Theme,
|
|
211
|
+
icon: string,
|
|
212
|
+
name: string,
|
|
213
|
+
argPart: string,
|
|
214
|
+
inner: number,
|
|
215
|
+
dur: string,
|
|
216
|
+
expanded: boolean,
|
|
217
|
+
hint = "",
|
|
218
|
+
): string[] {
|
|
219
|
+
const head = `${icon} ${name} ${argPart}`.trim();
|
|
220
|
+
// Runtime first, label last: the figure is what you read, the label is the button.
|
|
221
|
+
const right = [dur, hint].filter(Boolean).join(" · ");
|
|
222
|
+
const durStr = right ? theme.fg("dim", right) : "";
|
|
223
|
+
if (!durStr) {
|
|
224
|
+
return expanded ? wrapTextWithAnsi(head, inner) : [truncateToWidth(head, inner, "…")];
|
|
225
|
+
}
|
|
226
|
+
const durW = visibleWidth(durStr);
|
|
227
|
+
const avail = Math.max(8, inner - durW);
|
|
228
|
+
const wrapW = Math.max(4, avail - 1); // keep at least 1 space before the duration
|
|
229
|
+
const lines = expanded ? wrapTextWithAnsi(head, wrapW) : [truncateToWidth(head, wrapW, "…")];
|
|
230
|
+
const pad = Math.max(1, avail - visibleWidth(lines[0]));
|
|
231
|
+
lines[0] = `${lines[0]}${" ".repeat(pad)}${durStr}`;
|
|
232
|
+
return lines;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Default summary: collapsed ` first output line`, empty when expanded (the
|
|
236
|
+
// full output is right below — no duplicate first line).
|
|
237
|
+
export const resText: Res = (r, th, soft, isErr, expanded) => {
|
|
238
|
+
if (expanded && !isErr) return "";
|
|
239
|
+
const f = firstLine(textOf(r));
|
|
240
|
+
return f ? `${resHead(th)} ${paintLinks(f, soft)}` : resHead(th);
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
// Numeric summary ` → N matches`; errors fall back to the first line (most important).
|
|
244
|
+
export const numRes =
|
|
245
|
+
(fmt: (n: number) => string): Res =>
|
|
246
|
+
(r, th, soft, isErr, expanded) => {
|
|
247
|
+
if (isErr) return resText(r, th, soft, isErr, false);
|
|
248
|
+
if (expanded) return "";
|
|
249
|
+
return `${resHead(th)} ${fmt(countLines(textOf(r)))}`;
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
// First markdown heading in the text (e.g. `## omaga-sync workflow (2026-08-23)`).
|
|
253
|
+
const firstHeading = (s: unknown): string =>
|
|
254
|
+
typeof s === "string" ? (s.split("\n").find((l) => /^#{1,6}\s/.test(l.trim()))?.trim() ?? "") : "";
|
|
255
|
+
|
|
256
|
+
// One-line summary for tools without their own renderer. memory_write appends the
|
|
257
|
+
// heading it just wrote (from args.content) so the line names WHAT was written
|
|
258
|
+
// instead of just "Appended to MEMORY.md".
|
|
259
|
+
export function toolSummary(name: string, text: string, args?: ToolArgs): string {
|
|
260
|
+
const head = firstMeaningful(text).trim();
|
|
261
|
+
const title = name === "memory_write" ? firstHeading(args?.content) : "";
|
|
262
|
+
return title ? `${head}. ${title}` : head;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// The box says whether it is open with a word: [show] folded, [hide] open. The label is
|
|
266
|
+
// also the click target (see HINT_SPANS) and sits on the title row, so the affordance a
|
|
267
|
+
// click just used stays visible instead of vanishing with the summary line.
|
|
268
|
+
export const HINT_EXPAND = "[show]";
|
|
269
|
+
export const HINT_COLLAPSE = "[hide]";
|
|
270
|
+
|
|
271
|
+
const FULL_TEXT_MARKDOWN_MAX_BYTES = 32_768;
|
|
272
|
+
const FULL_TEXT_MARKDOWN_MAX_LINE = 4_096;
|
|
273
|
+
|
|
274
|
+
function exceedsMarkdownBudget(text: string): boolean {
|
|
275
|
+
if (text.length > FULL_TEXT_MARKDOWN_MAX_BYTES) return true;
|
|
276
|
+
let start = 0;
|
|
277
|
+
while (start < text.length) {
|
|
278
|
+
const nl = text.indexOf("\n", start);
|
|
279
|
+
const end = nl === -1 ? text.length : nl;
|
|
280
|
+
if (end - start > FULL_TEXT_MARKDOWN_MAX_LINE) return true;
|
|
281
|
+
if (nl === -1) break;
|
|
282
|
+
start = nl + 1;
|
|
283
|
+
}
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Expanded detail: themed markdown (same layout as a normal pi message — code
|
|
288
|
+
// blocks, lists, colors) instead of a plain dim dump. Oversized blobs (e.g. 200 KB
|
|
289
|
+
// single-line JSON) bypass the full Markdown parser to avoid 500ms+ main-thread stalls.
|
|
290
|
+
export const fullText = (r: TResult, _th: Theme, width = 0): string[] => {
|
|
291
|
+
const text = textOf(r);
|
|
292
|
+
if (!text) return [];
|
|
293
|
+
if (!width) return text.split("\n").map((l) => _th.fg("dim", l));
|
|
294
|
+
const w = Math.max(8, width);
|
|
295
|
+
if (exceedsMarkdownBudget(text)) {
|
|
296
|
+
const out: string[] = [];
|
|
297
|
+
for (const line of text.split("\n")) {
|
|
298
|
+
if (line.length <= w) {
|
|
299
|
+
out.push(_th.fg("dim", line));
|
|
300
|
+
} else {
|
|
301
|
+
for (let i = 0; i < line.length; i += w) {
|
|
302
|
+
out.push(_th.fg("dim", line.slice(i, i + w)));
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return out;
|
|
307
|
+
}
|
|
308
|
+
try {
|
|
309
|
+
return new Markdown(text, 0, 0, getMarkdownTheme()).render(w);
|
|
310
|
+
} catch {
|
|
311
|
+
return text.split("\n").map((l) => _th.fg("dim", l));
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
const isBlankLine = (l: string): boolean => stripAnsi(l).trim() === "";
|
|
316
|
+
|
|
317
|
+
// Drop blank lines at both edges (the built-in Spacer) — that's the gap between boxes.
|
|
318
|
+
export function stripBlankEdges(lines: string[]): string[] {
|
|
319
|
+
let s = 0;
|
|
320
|
+
let e = lines.length;
|
|
321
|
+
while (s < e && isBlankLine(lines[s])) s++;
|
|
322
|
+
while (e > s && isBlankLine(lines[e - 1])) e--;
|
|
323
|
+
return lines.slice(s, e);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// The inter-box gap is the built-in Spacer(1) of ToolExecutionComponent, stripped
|
|
327
|
+
// with a prototype render patch (same pattern as the footer patch). Own boxes (our
|
|
328
|
+
// minimal() tools + codemode) and every box forced by the generic predicate below
|
|
329
|
+
// are stripped; a box-owning third party left untouched is not.
|
|
330
|
+
const OWN_BOX = new Set<string>();
|
|
331
|
+
const hasOwnRendererDef = (self: { toolDefinition?: { renderCall?: unknown; renderResult?: unknown } }): boolean =>
|
|
332
|
+
Boolean(self?.toolDefinition?.renderCall || self?.toolDefinition?.renderResult);
|
|
333
|
+
|
|
334
|
+
// Inline image line: kitty (\x1b_G) or iTerm2 (\x1b]1337;File=) graphics payload.
|
|
335
|
+
// pi renders a tool's image preview as an extra child BELOW the box, padding it with
|
|
336
|
+
// `result.rows - 1` blank rows; the last row carries a cursor-up prefix before the
|
|
337
|
+
// sequence. Not exported by pi-tui, so match both prefixes.
|
|
338
|
+
export const isImageLine = (line: string): boolean => line.includes("\x1b_G") || line.includes("\x1b]1337;File=");
|
|
339
|
+
|
|
340
|
+
/** Drop the leading Spacer and the gap between box and image preview:
|
|
341
|
+
* its blank tail rows are kept as the image's vertical space so the
|
|
342
|
+
* terminal draws the image with balanced spacing above and below. */
|
|
343
|
+
export function stripEdgesKeepingImages(lines: string[]): string[] {
|
|
344
|
+
const firstImage = lines.findIndex(isImageLine);
|
|
345
|
+
if (firstImage < 0) return stripBlankEdges(lines);
|
|
346
|
+
let s = 0;
|
|
347
|
+
while (s < firstImage && isBlankLine(lines[s])) s++;
|
|
348
|
+
const head = lines.slice(s, firstImage);
|
|
349
|
+
while (head.length > 0 && isBlankLine(head[head.length - 1]!)) head.pop();
|
|
350
|
+
return [...head, ...lines.slice(firstImage)];
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Per box: did this module strip the blank rows above it? Those rows shift every mouse
|
|
354
|
+
// row index, so a press on the border and the title row is found at 0 and 1 only for a
|
|
355
|
+
// stripped box. `Symbol.for` keeps the state across the re-import a `/reload` performs.
|
|
356
|
+
// Cells of the expand hint in this box's own drawn lines. The hint is the whole click
|
|
357
|
+
// target: every other cell of the box keeps pi's text selection, so the output stays
|
|
358
|
+
// copyable. Recomputed on every render, because the label moves with the width and the key.
|
|
359
|
+
const HINT_SPANS = Symbol.for("pi-arnative.toolBoxHintSpans");
|
|
360
|
+
|
|
361
|
+
function stopScrollHold(comp: Record<symbol, unknown>): void {
|
|
362
|
+
const hold = comp[SCROLL_HOLD] as HoldRepeat | undefined;
|
|
363
|
+
if (hold && typeof hold.stop === "function") hold.stop();
|
|
364
|
+
comp[SCROLL_HOLD] = undefined;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function startScrollHold(
|
|
368
|
+
comp: Record<symbol, unknown> & { expanded?: boolean; ui?: { requestRender?: () => void } },
|
|
369
|
+
dir: -1 | 1,
|
|
370
|
+
): void {
|
|
371
|
+
stopScrollHold(comp);
|
|
372
|
+
const hold = createHoldRepeat();
|
|
373
|
+
comp[SCROLL_HOLD] = hold;
|
|
374
|
+
hold.start(() => {
|
|
375
|
+
if (!comp.expanded) return false;
|
|
376
|
+
const meta = (comp[SCROLL_META] as { maxOffset: number; step: number } | undefined) ?? { maxOffset: 0, step: 6 };
|
|
377
|
+
const cur = Number(comp[SCROLL_OFFSET] ?? 0);
|
|
378
|
+
const next = Math.max(0, Math.min(meta.maxOffset, cur + dir * meta.step));
|
|
379
|
+
if (next === cur) return false;
|
|
380
|
+
comp[SCROLL_OFFSET] = next;
|
|
381
|
+
comp.ui?.requestRender?.();
|
|
382
|
+
return true;
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
const SCROLL_UP_SPANS = Symbol.for("pi-arnative.toolBoxScrollUpSpans");
|
|
386
|
+
const SCROLL_DOWN_SPANS = Symbol.for("pi-arnative.toolBoxScrollDownSpans");
|
|
387
|
+
const SCROLL_META = Symbol.for("pi-arnative.toolBoxScrollMeta");
|
|
388
|
+
// A press already toggled this box; the release and the synthesized click that follow it
|
|
389
|
+
// must not toggle it a second time.
|
|
390
|
+
const PRESS_TOGGLED = Symbol.for("pi-arnative.toolBoxPressToggled");
|
|
391
|
+
const STRIPPED_BOX = Symbol.for("pi-arnative.toolBoxStripped");
|
|
392
|
+
|
|
393
|
+
export function expandedBoxBodyLimit(rows = process.stdout.rows || 28): number {
|
|
394
|
+
return Math.min(12, Math.max(6, Math.floor(rows * 0.35)));
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function boxTokenPaint(tokens: readonly string[]): (text: string) => string {
|
|
398
|
+
const th = getActiveTheme<{ fg?(c: string, t: string): string }>();
|
|
399
|
+
if (!th?.fg) return (s) => s;
|
|
400
|
+
for (const token of tokens) {
|
|
401
|
+
try {
|
|
402
|
+
const probe = th.fg(token, "x");
|
|
403
|
+
if (typeof probe === "string" && probe.includes("x")) return (s) => th.fg!(token, s);
|
|
404
|
+
} catch {
|
|
405
|
+
// try next token
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return (s) => s;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export function paintScrollEdge(
|
|
412
|
+
edgeLine: string,
|
|
413
|
+
leftCorner: string,
|
|
414
|
+
rightCorner: string,
|
|
415
|
+
label: string,
|
|
416
|
+
width: number,
|
|
417
|
+
borderPaint: (text: string) => string,
|
|
418
|
+
primaryPaint: (text: string) => string,
|
|
419
|
+
): string {
|
|
420
|
+
const inner = width - 2;
|
|
421
|
+
const labelW = visibleWidth(label);
|
|
422
|
+
if (inner < labelW + 4) return edgeLine;
|
|
423
|
+
const bgOpen = edgeLine.match(/^(\x1b\[48;[0-9;]*m)+/)?.[0] ?? "";
|
|
424
|
+
const bgClose = bgOpen ? "\x1b[49m" : "";
|
|
425
|
+
const totalDashes = inner - (labelW + 2);
|
|
426
|
+
const leftDashes = Math.floor(totalDashes / 2);
|
|
427
|
+
const rightDashes = totalDashes - leftDashes;
|
|
428
|
+
const content = `${borderPaint(`${leftCorner}${"\u2500".repeat(leftDashes)} `)}${primaryPaint(label)}${borderPaint(` ${"\u2500".repeat(rightDashes)}${rightCorner}`)}`;
|
|
429
|
+
return `${bgOpen}${content}${bgClose}`;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function capExpandedToolBox(
|
|
433
|
+
drawn: string[],
|
|
434
|
+
scrollOffset: number,
|
|
435
|
+
maxBody: number,
|
|
436
|
+
width: number,
|
|
437
|
+
borderPaint: (text: string) => string,
|
|
438
|
+
primaryPaint: (text: string) => string,
|
|
439
|
+
): { lines: string[]; maxOffset: number; aboveLabel: string; belowLabel: string; botRow: number } {
|
|
440
|
+
if (drawn.length < 4 || !stripAnsi(drawn[0] ?? "").trimStart().startsWith("\u256d")) {
|
|
441
|
+
return { lines: drawn, maxOffset: 0, aboveLabel: "", belowLabel: "", botRow: -1 };
|
|
442
|
+
}
|
|
443
|
+
let botIdx = -1;
|
|
444
|
+
for (let i = drawn.length - 1; i >= 2; i--) {
|
|
445
|
+
const p = stripAnsi(drawn[i]!).trim();
|
|
446
|
+
if (p.startsWith("\u2570") && p.endsWith("\u256f")) {
|
|
447
|
+
botIdx = i;
|
|
448
|
+
break;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
if (botIdx < 3) return { lines: drawn, maxOffset: 0, aboveLabel: "", belowLabel: "", botRow: -1 };
|
|
452
|
+
const body = drawn.slice(2, botIdx);
|
|
453
|
+
if (body.length <= maxBody) return { lines: drawn, maxOffset: 0, aboveLabel: "", belowLabel: "", botRow: botIdx };
|
|
454
|
+
|
|
455
|
+
const maxOffset = body.length - maxBody;
|
|
456
|
+
const offset = Math.max(0, Math.min(scrollOffset, maxOffset));
|
|
457
|
+
const visible = body.slice(offset, offset + maxBody);
|
|
458
|
+
const above = offset;
|
|
459
|
+
const below = body.length - (offset + visible.length);
|
|
460
|
+
const aboveLabel = above > 0 ? `\u2191 ${above} more` : "";
|
|
461
|
+
const belowLabel = below > 0 ? `\u2193 ${below} more` : "";
|
|
462
|
+
const top = aboveLabel ? paintScrollEdge(drawn[0]!, "\u256d", "\u256e", aboveLabel, width, borderPaint, primaryPaint) : drawn[0]!;
|
|
463
|
+
const bot = belowLabel ? paintScrollEdge(drawn[botIdx]!, "\u2570", "\u256f", belowLabel, width, borderPaint, primaryPaint) : drawn[botIdx]!;
|
|
464
|
+
const lines = [top, drawn[1]!, ...visible, bot, ...drawn.slice(botIdx + 1)];
|
|
465
|
+
return { lines, maxOffset, aboveLabel, belowLabel, botRow: 2 + visible.length };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// The patches below reinstall on every module load (pi's /reload re-evaluates the
|
|
469
|
+
// extension in the same process), so a UI fix applies without restarting pi; see
|
|
470
|
+
// lib/patch.ts for the originals/mark bookkeeping that makes that safe.
|
|
471
|
+
if (ToolExecutionComponent?.prototype?.render) {
|
|
472
|
+
const proto = ToolExecutionComponent.prototype as unknown as PatchedToolComponent;
|
|
473
|
+
const origRender = originalOf<(this: PatchedToolComponent, width: number) => string[]>(proto, "render");
|
|
474
|
+
proto.render = markPatched(function (this: PatchedToolComponent, width: number): string[] {
|
|
475
|
+
const lines = origRender.call(this, width);
|
|
476
|
+
const stripped = OWN_BOX.has(this.toolName) || boxTheirRenderers(this) || !hasOwnRendererDef(this);
|
|
477
|
+
this[STRIPPED_BOX] = stripped;
|
|
478
|
+
let drawn = stripped ? stripEdgesKeepingImages(lines) : lines;
|
|
479
|
+
if (stripped && this.expanded) {
|
|
480
|
+
const maxBody = expandedBoxBodyLimit();
|
|
481
|
+
const capped = capExpandedToolBox(
|
|
482
|
+
drawn,
|
|
483
|
+
Number(this[SCROLL_OFFSET] ?? 0),
|
|
484
|
+
maxBody,
|
|
485
|
+
width,
|
|
486
|
+
boxTokenPaint(["dim"]),
|
|
487
|
+
boxTokenPaint(["dim"]),
|
|
488
|
+
);
|
|
489
|
+
drawn = capped.lines;
|
|
490
|
+
this[SCROLL_OFFSET] = Math.max(0, Math.min(Number(this[SCROLL_OFFSET] ?? 0), capped.maxOffset));
|
|
491
|
+
this[SCROLL_META] = { maxOffset: capped.maxOffset, step: Math.max(1, Math.floor(maxBody / 2)) };
|
|
492
|
+
this[SCROLL_UP_SPANS] = capped.aboveLabel ? textSpans([drawn[0]!], capped.aboveLabel) : [];
|
|
493
|
+
this[SCROLL_DOWN_SPANS] =
|
|
494
|
+
capped.belowLabel && capped.botRow >= 0
|
|
495
|
+
? textSpans([drawn[capped.botRow]!], capped.belowLabel).map((s) => ({ ...s, row: capped.botRow }))
|
|
496
|
+
: [];
|
|
497
|
+
} else {
|
|
498
|
+
stopScrollHold(this);
|
|
499
|
+
this[SCROLL_OFFSET] = 0;
|
|
500
|
+
this[SCROLL_UP_SPANS] = [];
|
|
501
|
+
this[SCROLL_DOWN_SPANS] = [];
|
|
502
|
+
this[SCROLL_META] = undefined;
|
|
503
|
+
}
|
|
504
|
+
// Only a box this module laid out is measured here; a renderer pi owns keeps pi's
|
|
505
|
+
// own mouse path, since its row offsets come from a layout it did not show us.
|
|
506
|
+
// Title rows only (frame + title): a [show] inside the output must not become a button.
|
|
507
|
+
this[HINT_SPANS] = stripped
|
|
508
|
+
? [...textSpans(drawn, HINT_EXPAND), ...textSpans(drawn, HINT_COLLAPSE)].filter((span) => span.row <= 1)
|
|
509
|
+
: [];
|
|
510
|
+
return drawn;
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
// Click to expand/collapse or scroll, on the hint/more text alone. pi toggles on the
|
|
514
|
+
// "click" it synthesizes from a press and a release at the same cell, so a one-cell
|
|
515
|
+
// drift made the hint look inert, and the stripped row above the box left its top
|
|
516
|
+
// border dead. A left press on the button acts at once and the release plus the click
|
|
517
|
+
// that follow are swallowed; the click clears the flag, not the release, or that click
|
|
518
|
+
// would trigger twice. Any other cell is left to pi: a press there starts a selection,
|
|
519
|
+
// so the output can be copied.
|
|
520
|
+
const origMouse = originalOf<(this: PatchedToolComponent, event: ToolMouseEventLike) => unknown>(proto, "handleMouse");
|
|
521
|
+
proto.handleMouse = markPatched(function (this: PatchedToolComponent, event: ToolMouseEventLike): unknown {
|
|
522
|
+
const onHint = (this[HINT_SPANS] as TextSpan[] | undefined)?.length
|
|
523
|
+
? inSpans(this[HINT_SPANS] as TextSpan[], event.y, event.x)
|
|
524
|
+
: false;
|
|
525
|
+
const onUp = (this[SCROLL_UP_SPANS] as TextSpan[] | undefined)?.length
|
|
526
|
+
? inSpans(this[SCROLL_UP_SPANS] as TextSpan[], event.y, event.x)
|
|
527
|
+
: false;
|
|
528
|
+
const onDown = (this[SCROLL_DOWN_SPANS] as TextSpan[] | undefined)?.length
|
|
529
|
+
? inSpans(this[SCROLL_DOWN_SPANS] as TextSpan[], event.y, event.x)
|
|
530
|
+
: false;
|
|
531
|
+
if ((onHint || onUp || onDown) && event.type === "press" && event.button === "left") {
|
|
532
|
+
stopScrollHold(this);
|
|
533
|
+
// A child of the box (an image preview) keeps its own press.
|
|
534
|
+
const childHit = origMouse.call(this, event);
|
|
535
|
+
if (childHit) return childHit;
|
|
536
|
+
if (onHint) {
|
|
537
|
+
if (!this.result) return undefined;
|
|
538
|
+
this.setExpanded(!this.expanded);
|
|
539
|
+
this[PRESS_TOGGLED] = true;
|
|
540
|
+
return { handled: true, render: true };
|
|
541
|
+
}
|
|
542
|
+
const meta = (this[SCROLL_META] as { maxOffset: number; step: number } | undefined) ?? { maxOffset: 0, step: 6 };
|
|
543
|
+
const cur = Number(this[SCROLL_OFFSET] ?? 0);
|
|
544
|
+
const dir: -1 | 1 = onUp ? -1 : 1;
|
|
545
|
+
const next = Math.max(0, Math.min(meta.maxOffset, cur + dir * meta.step));
|
|
546
|
+
this[SCROLL_OFFSET] = next;
|
|
547
|
+
this[PRESS_TOGGLED] = true;
|
|
548
|
+
startScrollHold(this, dir);
|
|
549
|
+
this.ui?.requestRender?.();
|
|
550
|
+
return { handled: true, render: true };
|
|
551
|
+
}
|
|
552
|
+
if (this[PRESS_TOGGLED] && (event.type === "release" || event.type === "click")) {
|
|
553
|
+
stopScrollHold(this);
|
|
554
|
+
if (event.type === "click") this[PRESS_TOGGLED] = false;
|
|
555
|
+
return { handled: true, render: false };
|
|
556
|
+
}
|
|
557
|
+
if (
|
|
558
|
+
this[STRIPPED_BOX] &&
|
|
559
|
+
this.result &&
|
|
560
|
+
event.type === "click" &&
|
|
561
|
+
event.button === "left"
|
|
562
|
+
) {
|
|
563
|
+
if ((event.clickCount ?? 1) !== 1) return undefined;
|
|
564
|
+
const origHit = origMouse.call(this, event);
|
|
565
|
+
if (origHit) return origHit;
|
|
566
|
+
this.setExpanded(!this.expanded);
|
|
567
|
+
return { handled: true, render: true };
|
|
568
|
+
}
|
|
569
|
+
return origMouse.call(this, event);
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// --- Tools without their own renderer: same box, one-line summary ---
|
|
574
|
+
// Without this pi renders them as a plain bg block (name + 10 output lines). Our
|
|
575
|
+
// renderer is installed through the prototype (same pattern as the gap patch) only
|
|
576
|
+
// for tools that define no renderCall/renderResult of their own; third-party
|
|
577
|
+
// renderers are handled by the generic predicate below.
|
|
578
|
+
//
|
|
579
|
+
// BOXED_TOOLS is now a display-name map (plus the cdp special render path);
|
|
580
|
+
// boxing itself is generic (see boxTheirRenderers). The pi-web-access tools get a
|
|
581
|
+
// friendlier title ("search "/"fetch "/"get_content ") and their renderer content is
|
|
582
|
+
// reused inside our box.
|
|
583
|
+
//
|
|
584
|
+
// MCP tools (pi-mcp-adapter) declare `renderShell: "default"`, so the generic
|
|
585
|
+
// predicate boxes them, but their result renderer prints the WHOLE output on error
|
|
586
|
+
// (unbounded) and their call args can run to dozens of lines: a 1-line summary +
|
|
587
|
+
// [show] is tighter while the invoked tool stays visible.
|
|
588
|
+
const BOXED_TOOLS = new Map([
|
|
589
|
+
["web_search", "search"],
|
|
590
|
+
["fetch_content", "fetch"],
|
|
591
|
+
["get_search_content", "get_content"],
|
|
592
|
+
]);
|
|
593
|
+
|
|
594
|
+
// @narumitw/pi-chrome-devtools ships bare-text renderers ("Chrome DevTools: navigate",
|
|
595
|
+
// collapsed output is empty) so they are ignored and these tools take our default box
|
|
596
|
+
// path. CDP_ICON marks them in the call box (no hook for the generic tool icon).
|
|
597
|
+
const CDP_ICON = "\uf268";
|
|
598
|
+
const CDP_TOOLS: [string, string][] = [
|
|
599
|
+
["chrome_devtools_load", "load"],
|
|
600
|
+
["chrome_devtools_list_pages", "list pages"],
|
|
601
|
+
["chrome_devtools_select_page", "select page"],
|
|
602
|
+
["chrome_devtools_navigate", "navigate"],
|
|
603
|
+
["chrome_devtools_evaluate", "evaluate"],
|
|
604
|
+
["chrome_devtools_screenshot", "screenshot"],
|
|
605
|
+
["chrome_devtools_webmcp_list_tools", "list WebMCP tools"],
|
|
606
|
+
["chrome_devtools_webmcp_call_tool", "call WebMCP tool"],
|
|
607
|
+
];
|
|
608
|
+
const CDP_NAME = new Map(CDP_TOOLS);
|
|
609
|
+
for (const [n] of CDP_TOOLS) BOXED_TOOLS.set(n, n);
|
|
610
|
+
|
|
611
|
+
const displayName = (name: string): string =>
|
|
612
|
+
CDP_NAME.has(name) ? `Chrome DevTools: ${CDP_NAME.get(name)}` : (BOXED_TOOLS.get(name) ?? name);
|
|
613
|
+
for (const n of BOXED_TOOLS.keys()) OWN_BOX.add(n);
|
|
614
|
+
|
|
615
|
+
const MCP_TOOL = (name: string): boolean => name === "mcp" || name === "mcpScript" || name.startsWith("mcp__");
|
|
616
|
+
|
|
617
|
+
// Generic, not a name list: any tool that ships its own renderers is boxed, unless
|
|
618
|
+
// it declares `renderShell: "self"` (our own `minimal()`/codemode boxes) or sits in
|
|
619
|
+
// NOT_BOXED. That covers every third-party extension without a registration step:
|
|
620
|
+
// pi-fff (`ffgrep`/`fffind`, and `find`/`grep` in its override mode), pi core's
|
|
621
|
+
// `powershell`/`ls` (their definitions spread `renderCall`/`renderResult` onto the
|
|
622
|
+
// tool object) and pi-mcp-adapter (`renderShell: "default"`) all fall in by shape.
|
|
623
|
+
//
|
|
624
|
+
// MCP is boxed even when pi-mcp-adapter declares `renderShell: "self"`: since 2.3x
|
|
625
|
+
// its default `toolResultRendering: "compact"` paints flat text (`mcp call x @ y`,
|
|
626
|
+
// no border), so a `self` shell there means "no box", not "my own box".
|
|
627
|
+
//
|
|
628
|
+
// `source_check` is the single exception: its partial phase (curator URLs + approval
|
|
629
|
+
// state) would disappear because our partial path returns nothing.
|
|
630
|
+
const NOT_BOXED = new Set(["source_check"]);
|
|
631
|
+
const boxTheirRenderers = (self: Pick<PatchedToolComponent, "toolName" | "toolDefinition">): boolean =>
|
|
632
|
+
Boolean(self.toolDefinition) &&
|
|
633
|
+
(self.toolDefinition?.renderShell !== "self" || MCP_TOOL(self.toolName)) &&
|
|
634
|
+
!NOT_BOXED.has(self.toolName);
|
|
635
|
+
|
|
636
|
+
// The MCP box title names the invoked tool (full args when expanded).
|
|
637
|
+
const mcpInfo = (name: string, args: ToolArgs | undefined, th: Theme): string => {
|
|
638
|
+
if (!MCP_TOOL(name)) return "";
|
|
639
|
+
const tool = String(args?.tool ?? "");
|
|
640
|
+
const server = String(args?.server ?? "");
|
|
641
|
+
return tool ? th.fg("dim", `${tool}${server ? ` @ ${server}` : ""}`) : "";
|
|
642
|
+
};
|
|
643
|
+
|
|
644
|
+
// Cap third-party lines in the call box; the rest goes behind [show].
|
|
645
|
+
const CALL_ROWS = 2;
|
|
646
|
+
const capped = (th: Theme, rows: string[], expanded: boolean): string[] =>
|
|
647
|
+
expanded || rows.length <= CALL_ROWS ? rows : [...rows.slice(0, CALL_ROWS), th.fg("dim", HINT_EXPAND)];
|
|
648
|
+
|
|
649
|
+
// Third-party renderers run unguarded here (at render time, unlike pi's own
|
|
650
|
+
// updateDisplay which wraps them in try/catch + fallback): a throw becomes an
|
|
651
|
+
// uncaughtException that exits pi. e.g. pi-web-access' get_content renderCall
|
|
652
|
+
// slices args.responseId — undefined on a partial/malformed tool call.
|
|
653
|
+
const safeCall = <T>(fn: () => T): T | null => {
|
|
654
|
+
try {
|
|
655
|
+
return fn();
|
|
656
|
+
} catch {
|
|
657
|
+
return null;
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
|
|
661
|
+
// Lines from a third-party renderer component (right padding trimmed, ANSI kept).
|
|
662
|
+
const componentLines = (component: RenderableComponent | null | undefined, width: number): string[] => {
|
|
663
|
+
try {
|
|
664
|
+
const lines = component?.render(Math.max(8, width));
|
|
665
|
+
return Array.isArray(lines) ? lines.map((l: string) => String(l).trimEnd()) : [];
|
|
666
|
+
} catch {
|
|
667
|
+
return [];
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
/** Right-align a label on the first row of `rows`, for a row pi did not build: the fold
|
|
672
|
+
* hint and the runtime still land where every other box puts them. */
|
|
673
|
+
const rightAlign = (th: Theme, rows: string[], inner: number, right: string): string[] => {
|
|
674
|
+
if (!right || rows.length === 0) return rows;
|
|
675
|
+
const label = th.fg("dim", right);
|
|
676
|
+
const avail = Math.max(4, inner - visibleWidth(label) - 1);
|
|
677
|
+
const head = truncateToWidth(rows[0]!, avail, "…");
|
|
678
|
+
const pad = Math.max(1, avail - visibleWidth(head));
|
|
679
|
+
return [`${head}${" ".repeat(pad)}${label}`, ...rows.slice(1)];
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
// Status icon + third-party lines -> our box content lines.
|
|
683
|
+
const boxedRows = (icon: string, lines: string[]): string[] => {
|
|
684
|
+
const body = lines.filter((l) => !isBlankLine(l));
|
|
685
|
+
return body.length ? [`${icon} ${body[0]}`, ...body.slice(1)] : [icon];
|
|
686
|
+
};
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* Subtle per-tool bg (see also toolPendingBg/toolSuccessBg for `todo`).
|
|
690
|
+
* `memory_write` uses customMessageBg: thin, violet-ish = "note", just distinct
|
|
691
|
+
* from the plain progress boxes. Use `name.startsWith("memory_")` to cover all
|
|
692
|
+
* memory tools.
|
|
693
|
+
*/
|
|
694
|
+
export const boxBgOf = (name: string): string | undefined => (name === "memory_write" ? "customMessageBg" : undefined);
|
|
695
|
+
|
|
696
|
+
if (ToolExecutionComponent?.prototype?.render) {
|
|
697
|
+
const proto = ToolExecutionComponent.prototype as unknown as PatchedToolComponent;
|
|
698
|
+
const origCall = originalOf<(this: PatchedToolComponent) => ToolRendererFn | undefined>(proto, "getCallRenderer");
|
|
699
|
+
const origResult = originalOf<(this: PatchedToolComponent) => ToolResultRendererFn | undefined>(proto, "getResultRenderer");
|
|
700
|
+
const origShell = originalOf<(this: PatchedToolComponent) => string>(proto, "getRenderShell");
|
|
701
|
+
const hasOwnRenderer = (self: PatchedToolComponent): boolean =>
|
|
702
|
+
!boxTheirRenderers(self) && Boolean(origCall.call(self) || origResult.call(self));
|
|
703
|
+
// pi-fff splits title (renderCall) and result (renderResult) — both merge into one box.
|
|
704
|
+
// Its two naming modes are covered: `find`/`grep` (override) and `ffgrep`/`fffind` (default).
|
|
705
|
+
const FFF_TOOLS = ["find", "grep", "ffgrep", "fffind"];
|
|
706
|
+
|
|
707
|
+
// A tool call with no registered definition (e.g. an unknown tool name that
|
|
708
|
+
// errored with "Tool X not found") makes hasRendererDefinition() false, so the
|
|
709
|
+
// constructor adds the plain contentText fallback and updateDisplay() never calls
|
|
710
|
+
// getCallRenderer/getResultRenderer — our patch is bypassed and the call renders
|
|
711
|
+
// as bare name + pretty-printed args. Claim those calls as defined so they take
|
|
712
|
+
// the same box path as any other renderer-less tool.
|
|
713
|
+
const origHasRendererDefinition = originalOf<(this: PatchedToolComponent) => boolean>(proto, "hasRendererDefinition");
|
|
714
|
+
proto.hasRendererDefinition = markPatched(function (this: PatchedToolComponent): boolean {
|
|
715
|
+
return origHasRendererDefinition.call(this) || this.toolDefinition === undefined;
|
|
716
|
+
});
|
|
717
|
+
|
|
718
|
+
proto.getRenderShell = markPatched(function (this: PatchedToolComponent): string {
|
|
719
|
+
if (boxTheirRenderers(this)) return "self";
|
|
720
|
+
return hasOwnRenderer(this) ? origShell.call(this) : "self";
|
|
721
|
+
});
|
|
722
|
+
|
|
723
|
+
proto.getCallRenderer = markPatched(function (this: PatchedToolComponent) {
|
|
724
|
+
const name: string = this.toolName;
|
|
725
|
+
const mine = boxTheirRenderers(this);
|
|
726
|
+
const own = origCall.call(this);
|
|
727
|
+
// Chrome DevTools' own renderCall is a bare line and pi-mcp-adapter's compact one
|
|
728
|
+
// is the same flat text; ours replaces both (icon + name + invoked MCP tool).
|
|
729
|
+
if (own && !mine && !CDP_NAME.has(name)) return own;
|
|
730
|
+
return (args: ToolArgs, th: Theme, ctx: TCtx) =>
|
|
731
|
+
new Lines((width) => {
|
|
732
|
+
if ((ctx.state as Record<string, unknown> | undefined)?.hasResult) return [];
|
|
733
|
+
const icon = CDP_NAME.has(name) ? th.fg("accent", CDP_ICON) : th.fg("warning", spinIcon());
|
|
734
|
+
const theirs =
|
|
735
|
+
own && !CDP_NAME.has(name) && !MCP_TOOL(name)
|
|
736
|
+
? componentLines(safeCall(() => own.call(this, args, th, ctx)), width - 6)
|
|
737
|
+
: [];
|
|
738
|
+
if (mine && theirs.length)
|
|
739
|
+
return box(th, width, boxedRows(icon, capped(th, theirs, Boolean(this.expanded))));
|
|
740
|
+
const inner = Math.max(8, width - 4);
|
|
741
|
+
const rows = titleRow(
|
|
742
|
+
th,
|
|
743
|
+
icon,
|
|
744
|
+
th.fg("accent", displayName(name)),
|
|
745
|
+
name === "todo" ? todoTitleDetail(th, softSecondaryOf(th), actionWord(args?.action, args?.status)) : mcpInfo(name, args, th),
|
|
746
|
+
inner,
|
|
747
|
+
"",
|
|
748
|
+
false,
|
|
749
|
+
);
|
|
750
|
+
return box(th, width, rows, boxBgOf(name));
|
|
751
|
+
});
|
|
752
|
+
});
|
|
753
|
+
|
|
754
|
+
proto.getResultRenderer = markPatched(function (this: PatchedToolComponent) {
|
|
755
|
+
const name: string = this.toolName;
|
|
756
|
+
const own = origResult.call(this);
|
|
757
|
+
// pi-fff splits title (renderCall) and result (renderResult); both go in one box.
|
|
758
|
+
const fff = FFF_TOOLS.includes(name) && this.toolDefinition?.renderShell !== "self";
|
|
759
|
+
// MCP: their result renderer is deliberately skipped (unbounded error dump).
|
|
760
|
+
if (own && !boxTheirRenderers(this)) return own;
|
|
761
|
+
// Chrome DevTools are in BOXED_TOOLS for the title/icon only: their renderResult
|
|
762
|
+
// (raw text, empty when collapsed) would drop our title row, so it is ignored.
|
|
763
|
+
const cdp = CDP_NAME.has(name);
|
|
764
|
+
return (result: TResult, opts: { expanded: boolean; isPartial?: boolean }, th: Theme, ctx: TCtx) => {
|
|
765
|
+
if (opts.isPartial) return EMPTY;
|
|
766
|
+
((ctx.state ??= {}) as Record<string, unknown>).hasResult = true;
|
|
767
|
+
const text = textOf(result);
|
|
768
|
+
// pi-web-access reports failure via `details.error` without throwing, so
|
|
769
|
+
// ctx.isError alone is not enough: without this the error box shows ✓.
|
|
770
|
+
const isErr = Boolean(ctx.isError || result.isError || (result.details as { error?: unknown } | undefined)?.error);
|
|
771
|
+
// Their renderer content is reused inside our box unless it is unusable:
|
|
772
|
+
// MCP dumps the whole output on error (1-line summary instead), Chrome
|
|
773
|
+
// DevTools is a bare line, and errors take our own path (pi-web-access'
|
|
774
|
+
// own error box would nest a box inside a box).
|
|
775
|
+
return new Lines((width) => {
|
|
776
|
+
const soft = softSecondaryOf(th);
|
|
777
|
+
const inner = Math.max(8, width - 4);
|
|
778
|
+
const icon = isErr ? th.fg("error", "x") : th.fg("success", "✓");
|
|
779
|
+
// Their renderer already answers `expanded`, so both states are measured: the fold
|
|
780
|
+
// label appears only when the other state really shows a different number of rows.
|
|
781
|
+
const theirsAt = (exp: boolean) =>
|
|
782
|
+
own && !isErr && !cdp && !MCP_TOOL(name)
|
|
783
|
+
? componentLines(
|
|
784
|
+
safeCall(() =>
|
|
785
|
+
own.call(this, { content: result.content, details: result.details }, { ...opts, expanded: exp }, th, ctx),
|
|
786
|
+
),
|
|
787
|
+
width - 6,
|
|
788
|
+
)
|
|
789
|
+
: [];
|
|
790
|
+
const boxed2 = theirsAt(opts.expanded);
|
|
791
|
+
// Only rows on screen decide: a renderer that answers `expanded` with the same visible
|
|
792
|
+
// height (a trailing newline, a blank row) has nothing to fold.
|
|
793
|
+
const rowsShown = (rows: string[]) => rows.filter((l) => !isBlankLine(l)).length;
|
|
794
|
+
const foldHint = rowsShown(theirsAt(!opts.expanded)) === rowsShown(boxed2) ? "" : opts.expanded ? HINT_COLLAPSE : HINT_EXPAND;
|
|
795
|
+
if (fff && boxed2.length) {
|
|
796
|
+
const callLines = componentLines(safeCall(() => origCall.call(this)?.call(this, ctx.args, th, ctx)), width - 6);
|
|
797
|
+
const head = `${icon} ${callLines[0]?.trim() || th.fg("accent", displayName(name))}`;
|
|
798
|
+
const right = [durationOf(ctx), foldHint].filter(Boolean).join(" · ");
|
|
799
|
+
return box(th, width, rightAlign(th, [head, ...boxed2], inner, right));
|
|
800
|
+
}
|
|
801
|
+
// Third-party content keeps its own template but not its own chrome: without this the
|
|
802
|
+
// box had no title row, so the tool name, the runtime and the fold label were all lost.
|
|
803
|
+
if (boxed2.length && !cdp) {
|
|
804
|
+
const rows = titleRow(
|
|
805
|
+
th,
|
|
806
|
+
icon,
|
|
807
|
+
th.fg("accent", displayName(name)),
|
|
808
|
+
mcpInfo(name, ctx.args, th),
|
|
809
|
+
inner,
|
|
810
|
+
durationOf(ctx),
|
|
811
|
+
opts.expanded,
|
|
812
|
+
foldHint,
|
|
813
|
+
);
|
|
814
|
+
return box(th, width, [...rows, ...boxed2]);
|
|
815
|
+
}
|
|
816
|
+
// A payload with no newline can still be a full screen of wrapped text, so the row
|
|
817
|
+
// count is measured at this width: a 40k-char JSON line folds like any other box.
|
|
818
|
+
const more = drawnRows(text, inner) > 1;
|
|
819
|
+
const rows = titleRow(
|
|
820
|
+
th,
|
|
821
|
+
icon,
|
|
822
|
+
th.fg("accent", displayName(name)),
|
|
823
|
+
name === "todo"
|
|
824
|
+
? todoTitleDetail(th, soft, (result.details as { detail?: unknown } | undefined)?.detail)
|
|
825
|
+
: mcpInfo(name, ctx.args, th),
|
|
826
|
+
inner,
|
|
827
|
+
durationOf(ctx),
|
|
828
|
+
opts.expanded,
|
|
829
|
+
more ? (opts.expanded ? HINT_COLLAPSE : HINT_EXPAND) : "",
|
|
830
|
+
);
|
|
831
|
+
const summary = toolSummary(name, text, ctx.args);
|
|
832
|
+
const summaryRow = oneRow(
|
|
833
|
+
`${resHead(th)}${summary ? ` ${paintLinks(summary, soft)}` : ""}`,
|
|
834
|
+
inner,
|
|
835
|
+
);
|
|
836
|
+
rows.push(summaryRow);
|
|
837
|
+
if (opts.expanded && more) {
|
|
838
|
+
// MCP args are gone once the call box is replaced by the result.
|
|
839
|
+
if (MCP_TOOL(name)) rows.push(th.fg("dim", `args ${JSON.stringify(ctx.args ?? {})}`));
|
|
840
|
+
rows.push(...fullText(result, th, inner));
|
|
841
|
+
}
|
|
842
|
+
return box(th, width, rows, boxBgOf(name));
|
|
843
|
+
});
|
|
844
|
+
};
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/** `todo · completed`: the status the call left behind (or its action word), so the title says
|
|
849
|
+
* what happened and not just which tool ran. The word takes the soft accent tier, the dot stays
|
|
850
|
+
* dim. */
|
|
851
|
+
function todoTitleDetail(th: Theme, soft: (s: string) => string, word: unknown): string {
|
|
852
|
+
const text = typeof word === "string" ? word.trim() : "";
|
|
853
|
+
return text ? `${th.fg("dim", "·")} ${soft(text)}` : "";
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// codemode: the script is highlighted, the calls and output come from pi's own details.
|
|
857
|
+
function codeLines(code: string): string[] {
|
|
858
|
+
const js = code.replace(/\r/g, "").trimEnd().replace(/\t/g, " ");
|
|
859
|
+
if (!js) return [];
|
|
860
|
+
try {
|
|
861
|
+
return highlightCode(js, "javascript");
|
|
862
|
+
} catch {
|
|
863
|
+
return js.split("\n");
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/** `✓ todo {"action":"list"} 2ms` — status icon, tool name, muted args, dim duration. */
|
|
868
|
+
function formatCodemodeCall(call: CodemodeCall, th: Theme): string {
|
|
869
|
+
const [color, glyph] = STATUS_ICON[String(call?.status ?? "ok")] ?? ["error", "x"];
|
|
870
|
+
const dur = fmtMs(Number(call?.durationMs));
|
|
871
|
+
let line = ` ${th.fg(color, glyph)} ${th.fg("accent", String(call?.name ?? ""))}`;
|
|
872
|
+
if (call?.args) line += ` ${th.fg("muted", String(call.args))}`;
|
|
873
|
+
if (dur) line += ` ${th.fg("dim", dur)}`;
|
|
874
|
+
return line;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
// codemode call status -> [theme colour, glyph], same mapping pi's own renderer uses.
|
|
878
|
+
const STATUS_ICON: Record<string, [string, string]> = {
|
|
879
|
+
running: ["warning", "…"],
|
|
880
|
+
ok: ["success", "✓"],
|
|
881
|
+
cancelled: ["muted", "⊘"],
|
|
882
|
+
error: ["error", "x"],
|
|
883
|
+
};
|
|
884
|
+
|
|
885
|
+
/** Drop pi's "Script completed\nWall time …\nOutput:" header (a rejected input has none). */
|
|
886
|
+
function codemodeOutput(content: unknown): string {
|
|
887
|
+
const blocks = (Array.isArray(content) ? content : []).filter(
|
|
888
|
+
(c): c is { type: string; text?: string } => Boolean(c && typeof c === "object" && (c as { type?: unknown }).type === "text"),
|
|
889
|
+
);
|
|
890
|
+
const header = /^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n/;
|
|
891
|
+
return blocks
|
|
892
|
+
.map((c, i) => (i === 0 ? String(c.text ?? "").replace(header, "") : String(c.text ?? "")))
|
|
893
|
+
.join("\n")
|
|
894
|
+
.trim();
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/** Script lines; collapsed keeps only the first, like the other tools' one-line call. */
|
|
898
|
+
function codemodeScript(code: string, expanded: boolean): { lines: string[]; hidden: number } {
|
|
899
|
+
const lines = codeLines(code);
|
|
900
|
+
if (expanded || lines.length <= 1) return { lines, hidden: 0 };
|
|
901
|
+
return { lines: lines.slice(0, 1), hidden: lines.length - 1 };
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/** Every box row: title, script, nested calls, output. Collapsed is the title plus the
|
|
905
|
+
* script's first line, with the rest behind the expand hint. Expanding — or failing —
|
|
906
|
+
* shows everything: a truncated error would read as a short, successful run. */
|
|
907
|
+
function codemodeBoxRows(
|
|
908
|
+
args: ToolArgs | undefined,
|
|
909
|
+
result: { content?: unknown; details?: ToolDetails } | undefined,
|
|
910
|
+
th: Theme,
|
|
911
|
+
expanded: boolean,
|
|
912
|
+
isErr: boolean,
|
|
913
|
+
icon: string,
|
|
914
|
+
inner: number,
|
|
915
|
+
dur = "",
|
|
916
|
+
): string[] {
|
|
917
|
+
const code = typeof args?.code === "string" ? args.code : "";
|
|
918
|
+
const script = codemodeScript(code, expanded);
|
|
919
|
+
const calls: CodemodeCall[] = Array.isArray(result?.details?.calls) ? result.details.calls : [];
|
|
920
|
+
const output = codemodeOutput(result?.content);
|
|
921
|
+
const outLines = output ? output.split("\n") : [];
|
|
922
|
+
const shown = expanded || isErr;
|
|
923
|
+
// A failing run shows its calls and output even when collapsed, so only a multi-line
|
|
924
|
+
// script gives it anything to fold; a passing run folds multi-line scripts, calls and output.
|
|
925
|
+
const foldable = countLines(code) > 1 || (!isErr && (calls.length > 0 || outLines.length > 0));
|
|
926
|
+
const label = foldable ? (expanded ? HINT_COLLAPSE : HINT_EXPAND) : "";
|
|
927
|
+
const rows = titleRow(th, icon, th.fg("accent", "codemode"), "", inner, dur, expanded, label);
|
|
928
|
+
script.lines.forEach((line, i) => rows.push(i === 0 ? `${resHead(th)} ${line}` : ` ${line}`));
|
|
929
|
+
if (shown) {
|
|
930
|
+
if (calls.length || outLines.length) rows.push("");
|
|
931
|
+
rows.push(...calls.map((c) => formatCodemodeCall(c, th)), ...outLines.map((l) => th.fg("toolOutput", ` ${l}`)));
|
|
932
|
+
}
|
|
933
|
+
return rows;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
// One render path for all tools (no per-tool duplication).
|
|
937
|
+
// renderCall = running box (); renderResult = final box (✓/x + right-aligned
|
|
938
|
+
// duration + summary); state.hasResult is written by renderResult and read at
|
|
939
|
+
// render() -> exactly one box, also after reload/restore. res & full are optional
|
|
940
|
+
// (default: first output line / dim detail).
|
|
941
|
+
function minimal(
|
|
942
|
+
pi: ExtensionAPI,
|
|
943
|
+
tool: { execute: (...a: unknown[]) => Promise<unknown> } & Record<string, unknown>,
|
|
944
|
+
name: (th: Theme, soft: (s: string) => string) => string,
|
|
945
|
+
call: (a: ToolArgs, th: Theme, soft: (s: string) => string, expanded: boolean) => string,
|
|
946
|
+
res: Res = resText,
|
|
947
|
+
full: (r: TResult, th: Theme, inner: number) => string[] = fullText,
|
|
948
|
+
): void {
|
|
949
|
+
OWN_BOX.add(String(tool.name ?? ""));
|
|
950
|
+
pi.registerTool({
|
|
951
|
+
...tool,
|
|
952
|
+
renderShell: "self",
|
|
953
|
+
async execute(toolCallId: string, params: unknown, signal: unknown, onUpdate: unknown, ctx: unknown) {
|
|
954
|
+
const start = performance.now();
|
|
955
|
+
ACTIVE++;
|
|
956
|
+
syncTicker();
|
|
957
|
+
try {
|
|
958
|
+
return await tool.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
959
|
+
} finally {
|
|
960
|
+
recordTiming(toolCallId, Math.round(performance.now() - start));
|
|
961
|
+
ACTIVE--;
|
|
962
|
+
syncTicker();
|
|
963
|
+
}
|
|
964
|
+
},
|
|
965
|
+
renderCall(args: ToolArgs, theme: Theme, context: TCtx) {
|
|
966
|
+
return new Lines((width) => {
|
|
967
|
+
// Read context.state live (never capture): renderResult may create it after renderCall.
|
|
968
|
+
if (context.state?.hasResult) return [];
|
|
969
|
+
const soft = softSecondaryOf(theme);
|
|
970
|
+
const inner = Math.max(8, width - 4);
|
|
971
|
+
const rows = titleRow(
|
|
972
|
+
theme,
|
|
973
|
+
theme.fg("warning", spinIcon()),
|
|
974
|
+
name(theme, soft),
|
|
975
|
+
call(args, theme, soft, false),
|
|
976
|
+
inner,
|
|
977
|
+
"",
|
|
978
|
+
false,
|
|
979
|
+
);
|
|
980
|
+
return box(theme, width, rows);
|
|
981
|
+
});
|
|
982
|
+
},
|
|
983
|
+
renderResult(
|
|
984
|
+
result: TResult,
|
|
985
|
+
{ expanded, isPartial }: { expanded: boolean; isPartial: boolean },
|
|
986
|
+
theme: Theme,
|
|
987
|
+
context: TCtx,
|
|
988
|
+
) {
|
|
989
|
+
if (isPartial) return EMPTY;
|
|
990
|
+
((context.state ??= {}) as Record<string, unknown>).hasResult = true;
|
|
991
|
+
const text = textOf(result);
|
|
992
|
+
// `ctx.isError`/`result.isError` are the only honest sources: output text starting with
|
|
993
|
+
// "Error" is normal content (a file whose first line says "Error handling...").
|
|
994
|
+
const isErr = Boolean(context.isError || result.isError);
|
|
995
|
+
const dur = durationOf(context as TCtx);
|
|
996
|
+
const icon = isErr ? theme.fg("error", "x") : theme.fg("success", "✓");
|
|
997
|
+
return new Lines((width) => {
|
|
998
|
+
const soft = softSecondaryOf(theme);
|
|
999
|
+
const inner = Math.max(8, width - 4);
|
|
1000
|
+
// Anything the collapsed summary hides gets the standard hint; without it a
|
|
1001
|
+
// two-line box (edit: `+1 / -1`) looks complete while the diff sits behind it.
|
|
1002
|
+
const hasDetail =
|
|
1003
|
+
drawnRows(text, inner, 2) > 1 || Boolean((result.details as { diff?: string } | undefined)?.diff);
|
|
1004
|
+
const label = hasDetail ? (expanded ? HINT_COLLAPSE : HINT_EXPAND) : "";
|
|
1005
|
+
const rows = titleRow(
|
|
1006
|
+
theme,
|
|
1007
|
+
icon,
|
|
1008
|
+
name(theme, soft),
|
|
1009
|
+
call(context.args ?? {}, theme, soft, expanded),
|
|
1010
|
+
inner,
|
|
1011
|
+
dur,
|
|
1012
|
+
expanded,
|
|
1013
|
+
label,
|
|
1014
|
+
);
|
|
1015
|
+
const resLine = res(result, theme, soft, isErr, expanded);
|
|
1016
|
+
if (expanded) rows.push(...full(result, theme, inner));
|
|
1017
|
+
else if (resLine) rows.push(oneRow(resLine, inner));
|
|
1018
|
+
return box(theme, width, rows);
|
|
1019
|
+
});
|
|
1020
|
+
},
|
|
1021
|
+
} as unknown as Parameters<ExtensionAPI["registerTool"]>[0]);
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
function arnativeTools(pi: ExtensionAPI) {
|
|
1025
|
+
// codemode keeps pi's own data (script + nested calls + output) wrapped in the arnative
|
|
1026
|
+
// box, bg like every other tool. A resolver runs first and returns our renderers for
|
|
1027
|
+
// that name; `next()` would give pi's unboxed ones.
|
|
1028
|
+
OWN_BOX.add("codemode");
|
|
1029
|
+
pi.registerToolRenderer((toolName, next) => (toolName === "codemode" ? codemodeRenderers : next()));
|
|
1030
|
+
|
|
1031
|
+
// Re-render source for the spinner + ticker cleanup when the session closes
|
|
1032
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1033
|
+
TIMINGS.clear();
|
|
1034
|
+
requestRenderFn = () => {
|
|
1035
|
+
try {
|
|
1036
|
+
(ctx.ui as { requestRender?: () => void }).requestRender?.();
|
|
1037
|
+
} catch {
|
|
1038
|
+
// ignore
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
});
|
|
1042
|
+
pi.on("session_shutdown", async () => {
|
|
1043
|
+
TIMINGS.clear();
|
|
1044
|
+
ACTIVE = 0;
|
|
1045
|
+
if (TICK) {
|
|
1046
|
+
clearInterval(TICK);
|
|
1047
|
+
TICK = null;
|
|
1048
|
+
}
|
|
1049
|
+
requestRenderFn = null;
|
|
1050
|
+
});
|
|
1051
|
+
|
|
1052
|
+
// Gap is only stripped for our own boxes (see OWN_BOX above).
|
|
1053
|
+
|
|
1054
|
+
const shellCall = (a: { command?: string }, _th: Theme, soft: (s: string) => string, expanded: boolean): string => {
|
|
1055
|
+
const cmd = (a.command ?? "").replace(/\r?\n/g, " ").trim();
|
|
1056
|
+
return paintLinks(expanded ? cmd : smartTitle(cmd), soft);
|
|
1057
|
+
};
|
|
1058
|
+
|
|
1059
|
+
// powershell: pi core registers it as a separate builtin (only on Windows); without
|
|
1060
|
+
// our own registration it keeps pi's "default" shell and renders as a bg block, not a
|
|
1061
|
+
// box (the same reason `bash` is re-registered below). Windows only: on any other
|
|
1062
|
+
// platform `getPowerShellConfig()` throws, and an unregistered tool would stay off
|
|
1063
|
+
// while our registration is active on load.
|
|
1064
|
+
if (process.platform === "win32")
|
|
1065
|
+
minimal(pi, createPowerShellTool(cwd), (th) => th.fg("accent", "PS>"), shellCall);
|
|
1066
|
+
|
|
1067
|
+
// ls: no renderShell of its own, so pi's default shell turns it into a bg block.
|
|
1068
|
+
minimal(
|
|
1069
|
+
pi,
|
|
1070
|
+
createLsTool(cwd),
|
|
1071
|
+
(th) => th.fg("accent", "ls"),
|
|
1072
|
+
(a, _th, soft) => soft(shortPath(a.path ?? ".")),
|
|
1073
|
+
numRes((n) => `${n} entries`),
|
|
1074
|
+
);
|
|
1075
|
+
|
|
1076
|
+
// bash: ` $ <6 words>…` / `✓ $ <full title when expanded> 0.1s`
|
|
1077
|
+
minimal(pi, createBashTool(cwd), (th) => th.fg("accent", "$"), shellCall);
|
|
1078
|
+
|
|
1079
|
+
// read: `read path[:range]` → ` N lines`
|
|
1080
|
+
minimal(
|
|
1081
|
+
pi,
|
|
1082
|
+
createReadTool(cwd),
|
|
1083
|
+
(th) => th.fg("accent", "read"),
|
|
1084
|
+
(a, _th, soft) => {
|
|
1085
|
+
const range =
|
|
1086
|
+
a.offset || a.limit ? `:${a.offset ?? 1}${a.limit ? `-${(a.offset ?? 1) + a.limit - 1}` : ""}` : "";
|
|
1087
|
+
return `${soft(shortPath(a.path ?? ""))}${range}`;
|
|
1088
|
+
},
|
|
1089
|
+
numRes((n) => `${n} lines`),
|
|
1090
|
+
);
|
|
1091
|
+
|
|
1092
|
+
// grep: `grep /pattern/ in path (glob)` → ` → N matches`
|
|
1093
|
+
minimal(
|
|
1094
|
+
pi,
|
|
1095
|
+
createGrepTool(cwd),
|
|
1096
|
+
(th) => th.fg("accent", "grep"),
|
|
1097
|
+
(a, _th, soft) =>
|
|
1098
|
+
`/${a.pattern ?? ""}/ in ${soft(shortPath(a.path ?? "."))}${a.glob ? ` (${a.glob})` : ""}`,
|
|
1099
|
+
numRes((n) => `→ ${n} matches`),
|
|
1100
|
+
);
|
|
1101
|
+
|
|
1102
|
+
// find: `find pattern in path` → ` → N files`
|
|
1103
|
+
minimal(
|
|
1104
|
+
pi,
|
|
1105
|
+
createFindTool(cwd),
|
|
1106
|
+
(th) => th.fg("accent", "find"),
|
|
1107
|
+
(a, _th, soft) => `${a.pattern ?? ""} in ${soft(shortPath(a.path ?? "."))}`,
|
|
1108
|
+
numRes((n) => `→ ${n} files`),
|
|
1109
|
+
);
|
|
1110
|
+
|
|
1111
|
+
// write: `write path`, default res (first output line)
|
|
1112
|
+
minimal(
|
|
1113
|
+
pi,
|
|
1114
|
+
createWriteTool(cwd),
|
|
1115
|
+
(th) => th.fg("accent", "write"),
|
|
1116
|
+
(a, _th, soft) => soft(shortPath(a.path ?? "")),
|
|
1117
|
+
);
|
|
1118
|
+
|
|
1119
|
+
// edit: `edit path`, ` +N / -M`, expand = diff toolDiff*
|
|
1120
|
+
minimal(
|
|
1121
|
+
pi,
|
|
1122
|
+
createEditTool(cwd),
|
|
1123
|
+
(th) => th.fg("accent", "edit"),
|
|
1124
|
+
(a, _th, soft) => soft(shortPath(a.path ?? "")),
|
|
1125
|
+
(r, th, _soft, isErr, expanded) => {
|
|
1126
|
+
if (isErr) return resText(r, th, (s) => s, isErr, false);
|
|
1127
|
+
const diff: string = r.details?.diff ?? "";
|
|
1128
|
+
let add = 0;
|
|
1129
|
+
let del = 0;
|
|
1130
|
+
for (const l of diff.split("\n")) {
|
|
1131
|
+
if (l.startsWith("+") && !l.startsWith("+++")) add++;
|
|
1132
|
+
else if (l.startsWith("-") && !l.startsWith("---")) del++;
|
|
1133
|
+
}
|
|
1134
|
+
return `${resHead(th)} ${th.fg("toolDiffAdded", `+${add}`)} / ${th.fg("toolDiffRemoved", `-${del}`)}`;
|
|
1135
|
+
},
|
|
1136
|
+
(r, th, inner) => formatEditDiff(r, th, inner),
|
|
1137
|
+
);
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
// codemode: pi's renderer wrapped in our box. renderShell "self" keeps the
|
|
1141
|
+
// execution defaults; renderCall/renderResult draw the box. state.hasResult
|
|
1142
|
+
// guarantees one box per call, also after reload/restore.
|
|
1143
|
+
const codemodeRenderers = {
|
|
1144
|
+
renderShell: "self" as const,
|
|
1145
|
+
renderCall(args: ToolArgs, th: Theme, ctx: TCtx) {
|
|
1146
|
+
return new Lines((width) => {
|
|
1147
|
+
if (ctx.state?.hasResult) return [];
|
|
1148
|
+
const isErr = Boolean(ctx.isError);
|
|
1149
|
+
const bg = isErr ? "toolErrorBg" : "toolPendingBg";
|
|
1150
|
+
// Same spinner as every other box while the tool runs; the codemode glyph
|
|
1151
|
+
// only appears once the result is in (renderResult).
|
|
1152
|
+
const icon = th.fg("warning", spinIcon());
|
|
1153
|
+
return box(th, width, codemodeBoxRows(args, undefined, th, Boolean(ctx.expanded), isErr, icon, Math.max(8, width - 4)), bg);
|
|
1154
|
+
});
|
|
1155
|
+
},
|
|
1156
|
+
renderResult(result: TResult, opts: { expanded: boolean; isPartial?: boolean }, th: Theme, ctx: TCtx) {
|
|
1157
|
+
if (opts.isPartial) return EMPTY;
|
|
1158
|
+
((ctx.state ??= {}) as Record<string, unknown>).hasResult = true;
|
|
1159
|
+
const isErr = Boolean(ctx.isError || result.isError);
|
|
1160
|
+
const icon = isErr ? th.fg("error", "x") : th.fg("success", "\uf489");
|
|
1161
|
+
const dur = durationOf(ctx);
|
|
1162
|
+
return new Lines((width) =>
|
|
1163
|
+
box(th, width, codemodeBoxRows(ctx.args, result, th, Boolean(opts.expanded), isErr, icon, Math.max(8, width - 4), dur), isErr ? "toolErrorBg" : "toolSuccessBg"),
|
|
1164
|
+
);
|
|
1165
|
+
},
|
|
1166
|
+
};
|
|
1167
|
+
|
|
1168
|
+
export default arnativeTools;
|
|
1169
|
+
|
|
1170
|
+
export const __test = {
|
|
1171
|
+
cwd,
|
|
1172
|
+
MAX_TIMINGS,
|
|
1173
|
+
TIMINGS,
|
|
1174
|
+
FRAMES,
|
|
1175
|
+
get ACTIVE() {
|
|
1176
|
+
return ACTIVE;
|
|
1177
|
+
},
|
|
1178
|
+
set ACTIVE(v) {
|
|
1179
|
+
ACTIVE = v;
|
|
1180
|
+
},
|
|
1181
|
+
get TICK() {
|
|
1182
|
+
return TICK;
|
|
1183
|
+
},
|
|
1184
|
+
set TICK(v) {
|
|
1185
|
+
TICK = v;
|
|
1186
|
+
},
|
|
1187
|
+
syncTicker,
|
|
1188
|
+
fmtMs,
|
|
1189
|
+
OWN_BOX,
|
|
1190
|
+
hasOwnRendererDef,
|
|
1191
|
+
BOXED_TOOLS,
|
|
1192
|
+
CDP_ICON,
|
|
1193
|
+
mcpInfo,
|
|
1194
|
+
CALL_ROWS,
|
|
1195
|
+
capped,
|
|
1196
|
+
safeCall,
|
|
1197
|
+
componentLines,
|
|
1198
|
+
codemodeOutput,
|
|
1199
|
+
minimal,
|
|
1200
|
+
EDIT_DIFF_CONFIG_KEY,
|
|
1201
|
+
codemodeRenderers,
|
|
1202
|
+
};
|