@giladbarnea/pi-pretty-codemode 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gilad Barnea
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ ---
2
+ last_updated: 2026-11-27T19-45
3
+ ---
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ # Pretty Codemode
6
+
7
+ Intent summaries and syntax-highlighted nested tool results for Pi Code Mode.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ pi install npm:@giladbarnea/pi-pretty-codemode
13
+ ```
14
+
15
+ For development, install the local checkout instead. Enable one source, then run `/reload` in existing Pi sessions.
16
+
17
+ Requires Node 24+ and supports Pi 1.5.x and 1.6.x.
18
+
19
+ ## One Code Mode display
20
+
21
+ Start a script with an intent comment, immediately after `// @options:` when present:
22
+
23
+ ```js
24
+ // intent: Inspect configuration and check service health
25
+ await Promise.allSettled([
26
+ tools.read({ path: "settings.ts" }),
27
+ tools.bash({ command: "npm test" }),
28
+ ]);
29
+ text({ checked: true });
30
+ ```
31
+
32
+ The extension adds this convention to the agent's tool guidelines. A completed opening comment appears during input streaming. With an intent, a collapsed call shows its purpose, child-status counts and timing. Expand with Pi's tool-output shortcut, normally Ctrl+O, to see the JavaScript, captured child results and script output. Failed scripts keep their error output visible. Scripts without an opening intent retain their previews.
33
+
34
+ Child results come from Pi's real nested execution events and IDs. Reads get source colors, Bash gets command/result boxes, and mutations show captured diff details when available. The script's printed output stays separate. Recognized JSON gets colors, but output text is never matched to a tool by order, filenames or content.
35
+
36
+ Source-provided terminal formatting and control characters are removed for display; the renderer applies its own syntax and diff colors. This does not alter captured or programmatic data.
37
+
38
+ This extension does not replace tool definitions, execution or model-visible results. Write diffs use details supplied by an installed mutation renderer, such as Kendex. Without those details, the actual write result remains visible. Nested Bash commands use pi-pretty-bash's shared tree-sitter highlighter with Pi theme colors, the same as direct Bash: quoted heredocs labelled with a language get that language's colors, and commands over its size budget stay plain and complete.
39
+
40
+ ## Current limits
41
+
42
+ - Captures live in memory for the latest 32 Code Mode runs, up to 256 child calls per run. These limits count records, not payload bytes.
43
+ - Reload, session changes and tree navigation clear captures. Older calls use their original result view rather than invented child output.
44
+ - Nested images show a placeholder. Images printed by the script remain Pi-owned.
45
+ - Expansion applies to the Code Mode call, not independently to each child.
46
+ - Expanded views format JavaScript only for the newest 256 live Code Mode calls; older calls, and saved calls after reload or resume, show the JavaScript as written. Formatting is display-only.
47
+
48
+ The accepted prototype is now a first-class package. Visual hierarchy and repeated-input feedback remain to be addressed. Persistence, payload-byte budgets and additional interaction behavior are separate decisions.
49
+
50
+ ## Development
51
+
52
+ ```sh
53
+ npm ci --ignore-scripts
54
+ npm run check
55
+ ```
56
+
57
+ Tests require Bun. Unit/rendering fixtures are self-contained. The suite exercises actual SDK execution, structured child results, partial output, cancellation, expansion, padding and intent comments.
58
+
59
+ - `index.ts`: registers the guideline, capture invalidation and Code Mode renderer.
60
+ - `src/capture.ts`: observes nested execution events.
61
+ - `src/render.ts`: owns the Code Mode display.
62
+ - `src/intent.ts`: reads the opening comment.
63
+ - `src/renderers/`: child and layout helpers.
64
+
65
+ ## License
66
+
67
+ MIT.
package/index.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { highlightCode, type ExtensionAPI, type ExtensionContext, type ToolRenderers } from "@earendil-works/pi-coding-agent";
2
+ import { createBashHighlighter } from "@giladbarnea/pi-pretty-bash/highlighting.js";
3
+ import { installCapture } from "./src/capture.ts";
4
+ import { createCodemodeRenderers } from "./src/render.ts";
5
+ import { INTENT_GUIDELINE } from "./src/intent.ts";
6
+ import { codemodeCallIds, createPreviewWindow } from "./src/previews.ts";
7
+
8
+ type RenderContext = Parameters<NonNullable<ToolRenderers["renderCall"]>>[2];
9
+
10
+ export default async function (pi: ExtensionAPI): Promise<void> {
11
+ const highlighter = await createBashHighlighter(highlightCode);
12
+ pi.on("session_shutdown", highlighter.dispose);
13
+ pi.on("before_agent_start", event => {
14
+ (event.systemPromptOptions.toolGuidelines.codemode ??= []).push(INTENT_GUIDELINE);
15
+ });
16
+ const invalidations = new Map<string, () => void>();
17
+ const store = installCapture(pi, rootToolCallId => invalidations.get(rootToolCallId)?.());
18
+ const remember = (context: RenderContext): void => {
19
+ if (context.isPartial) invalidations.set(context.toolCallId, context.invalidate);
20
+ else invalidations.delete(context.toolCallId);
21
+ };
22
+ const clear = (): void => invalidations.clear();
23
+ pi.on("session_start", clear);
24
+ pi.on("session_tree", clear);
25
+ pi.on("session_shutdown", clear);
26
+ const previews = createPreviewWindow();
27
+ const syncPreviews = (_event: unknown, context: ExtensionContext): void => previews.sync(codemodeCallIds(context.sessionManager.buildContextEntries()));
28
+ pi.on("session_start", syncPreviews);
29
+ pi.on("session_tree", syncPreviews);
30
+ pi.on("session_compact", syncPreviews);
31
+ pi.on("tool_execution_start", event => {
32
+ if (!event.parentToolCallId && event.toolName === "codemode") previews.add(event.toolCallId);
33
+ });
34
+ pi.registerToolRenderer((name, next) => {
35
+ const original = next();
36
+ if (name !== "codemode" || !original) return original;
37
+ const renderers = createCodemodeRenderers(rootToolCallId => store.get(rootToolCallId), original, highlighter.highlight, previews);
38
+ return {
39
+ ...renderers,
40
+ renderCall(args, theme, context) {
41
+ remember(context);
42
+ return renderers.renderCall!(args, theme, context);
43
+ },
44
+ renderResult(result, options, theme, context) {
45
+ remember(context);
46
+ return renderers.renderResult!(result, options, theme, context);
47
+ },
48
+ };
49
+ });
50
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-pretty-codemode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Intent summaries and syntax-highlighted nested tool results for Pi Code Mode.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": ["pi-package"],
8
+ "repository": { "type": "git", "url": "git+https://github.com/giladbarnea/pi-pretty-codemode.git" },
9
+ "homepage": "https://github.com/giladbarnea/pi-pretty-codemode#readme",
10
+ "bugs": { "url": "https://github.com/giladbarnea/pi-pretty-codemode/issues" },
11
+ "engines": { "node": ">=24" },
12
+ "files": ["index.ts", "src/", "README.md", "LICENSE"],
13
+ "publishConfig": { "access": "public" },
14
+ "pi": { "extensions": ["./index.ts"] },
15
+ "scripts": {
16
+ "test": "for file in tests/*.test.ts; do bun test --timeout 30000 \"$file\" || exit; done",
17
+ "typecheck": "tsc --project tsconfig.json",
18
+ "check": "npm test && npm run typecheck"
19
+ },
20
+ "dependencies": {
21
+ "@dprint/formatter": "0.6.0",
22
+ "@dprint/shfmt": "0.2.0",
23
+ "@dprint/typescript": "0.101.0",
24
+ "@giladbarnea/pi-pretty-bash": "1.0.15"
25
+ },
26
+ "peerDependencies": { "@earendil-works/pi-coding-agent": "1.5.* || 1.6.*", "@earendil-works/pi-tui": "1.5.* || 1.6.*" },
27
+ "devDependencies": {
28
+ "@earendil-works/pi-coding-agent": "1.5.2",
29
+ "@earendil-works/pi-tui": "1.5.2",
30
+ "@earendil-works/pi-ai": "1.5.2",
31
+ "@vanillagreen/pi-tool-renderer": "2.0.13",
32
+ "@types/node": "^24.0.0",
33
+ "typescript": "^5.9.3"
34
+ }
35
+ }
package/src/capture.ts ADDED
@@ -0,0 +1,84 @@
1
+ import type { CodemodeToolDetails } from "@earendil-works/pi-coding-agent";
2
+ import type { CapturedCall, CapturedRun, InstallCapture } from "./contract.ts";
3
+
4
+ type StoredRun = Omit<CapturedRun, "calls"> & { calls: CapturedCall[] };
5
+ const MAX_CALLS_PER_RUN = 256;
6
+ const MAX_RUNS = 32;
7
+
8
+ export const installCapture: InstallCapture = (pi, invalidate) => {
9
+ const runs = new Map<string, StoredRun>();
10
+ const roots = new Map<string, string>();
11
+ const clear = (): void => {
12
+ runs.clear();
13
+ roots.clear();
14
+ };
15
+ pi.on("session_start", clear);
16
+ pi.on("session_shutdown", clear);
17
+ pi.on("session_tree", clear);
18
+
19
+ const releaseOldestRun = (): void => {
20
+ const oldest = runs.keys().next().value!;
21
+ for (const call of runs.get(oldest)!.calls) roots.delete(call.toolCallId);
22
+ roots.delete(oldest);
23
+ runs.delete(oldest);
24
+ invalidate(oldest);
25
+ };
26
+
27
+ pi.on("tool_execution_start", event => {
28
+ if (!event.parentToolCallId && event.toolName === "codemode") {
29
+ while (runs.size >= MAX_RUNS) releaseOldestRun();
30
+ runs.set(event.toolCallId, { calls: [], incomplete: false });
31
+ roots.set(event.toolCallId, event.toolCallId);
32
+ return;
33
+ }
34
+ const root = roots.get(event.parentToolCallId ?? "");
35
+ if (!root) return;
36
+ const run = runs.get(root)!;
37
+ if (run.calls.length === MAX_CALLS_PER_RUN) {
38
+ run.incomplete = true;
39
+ invalidate(root);
40
+ return;
41
+ }
42
+ run.calls.push({
43
+ toolCallId: event.toolCallId,
44
+ parentToolCallId: event.parentToolCallId!,
45
+ toolName: event.toolName,
46
+ args: event.args,
47
+ status: "running",
48
+ });
49
+ roots.set(event.toolCallId, root);
50
+ invalidate(root);
51
+ });
52
+
53
+ pi.on("tool_execution_update", event => {
54
+ const root = roots.get(event.toolCallId);
55
+ if (!root) return;
56
+ const call = runs.get(root)!.calls.find(candidate => candidate.toolCallId === event.toolCallId);
57
+ if (!call) return;
58
+ call.result = event.partialResult;
59
+ invalidate(root);
60
+ });
61
+
62
+ pi.on("tool_execution_end", event => {
63
+ const root = roots.get(event.toolCallId);
64
+ if (!root) return;
65
+ const run = runs.get(root)!;
66
+ if (event.toolCallId === root) {
67
+ const details = event.result.details as CodemodeToolDetails | undefined;
68
+ const statuses = new Map(details?.calls.map(call => [call.id, call.status]));
69
+ for (const call of run.calls) {
70
+ call.status = statuses.get(call.toolCallId) ?? (call.status === "running" ? "cancelled" : call.status);
71
+ }
72
+ invalidate(root);
73
+ return;
74
+ }
75
+ const call = run.calls.find(candidate => candidate.toolCallId === event.toolCallId);
76
+ if (!call) return;
77
+ call.result = event.result;
78
+ call.durationMs = event.durationMs;
79
+ if (call.status !== "cancelled") call.status = event.isError ? "error" : "ok";
80
+ invalidate(root);
81
+ });
82
+
83
+ return { get: root => runs.get(root), clear };
84
+ };
@@ -0,0 +1,35 @@
1
+ import type { AgentToolResult, ExtensionAPI, ToolRenderers } from "@earendil-works/pi-coding-agent";
2
+ import type { BashHighlighter } from "@giladbarnea/pi-pretty-bash/highlighting.js";
3
+ import type { PreviewWindow } from "./previews.ts";
4
+
5
+ export type CapturedCall = {
6
+ toolCallId: string;
7
+ parentToolCallId: string;
8
+ toolName: string;
9
+ args: Record<string, unknown>;
10
+ status: "running" | "ok" | "error" | "cancelled";
11
+ result?: AgentToolResult<unknown>;
12
+ durationMs?: number;
13
+ };
14
+
15
+ export type CapturedRun = {
16
+ calls: readonly CapturedCall[];
17
+ incomplete: boolean;
18
+ };
19
+
20
+ export type CaptureStore = {
21
+ get(rootToolCallId: string): CapturedRun | undefined;
22
+ clear(): void;
23
+ };
24
+
25
+ export type InstallCapture = (
26
+ pi: ExtensionAPI,
27
+ invalidate: (rootToolCallId: string) => void,
28
+ ) => CaptureStore;
29
+
30
+ export type CreateCodemodeRenderers = (
31
+ getRun: CaptureStore["get"],
32
+ original: ToolRenderers,
33
+ highlightBash: BashHighlighter["highlight"],
34
+ previews: PreviewWindow,
35
+ ) => ToolRenderers;
package/src/intent.ts ADDED
@@ -0,0 +1,12 @@
1
+ export const INTENT_GUIDELINE = "Start every codemode script with a // intent: ... comment (after //@options:, if present). State the overall purpose in ~10 words.";
2
+
3
+ const INTENT_LINE = /^(?:[ \t]*\/\/ @options:[^\r\n]*\r?\n)?[ \t]*\/\/ intent:[ \t]*([^\r\n]+)(?:\r?\n|$)/;
4
+
5
+ /** Extract the opening intent once its streamed comment is complete.
6
+ * @example intentFromCode('// intent: Inspect settings\ntext(1);', false) === 'Inspect settings'
7
+ */
8
+ export function intentFromCode(code: string, complete: boolean): string | undefined {
9
+ const match = INTENT_LINE.exec(code);
10
+ if (!match || (!complete && !match[0].endsWith("\n"))) return undefined;
11
+ return match[1].trim() || undefined;
12
+ }
@@ -0,0 +1,62 @@
1
+ /** How many of the newest Code Mode calls in the chat show a formatted JavaScript preview (Gilad, Nov 27). */
2
+ export const PREVIEW_CALLS = 256;
3
+
4
+ type SavedEntry = { type: string; message?: { role?: string; content?: unknown } };
5
+ type ToolCallBlock = { type?: unknown; name?: unknown; id?: unknown };
6
+
7
+ /** The newest Code Mode calls in the chat, in the order Pi draws them: its rebuilt history, then live calls.
8
+ * Only Pi's chat events change the order; rendering only asks. Pi also renders calls outside the chat (export, a replay
9
+ * before session_start), so a call the window has not seen is never a preview and never moves another call. */
10
+ export type PreviewWindow = {
11
+ /** Replace the order with a rebuilt chat's Code Mode call IDs, oldest first. Pi redraws the chat afterwards. */
12
+ sync(toolCallIds: Iterable<string>): void;
13
+ /** Append a live call as the newest; invalidate the preview it pushes past the cutoff. */
14
+ add(toolCallId: string): void;
15
+ /** Whether a call is among the newest. The latest invalidation per drawn row (`owner`, Pi's per-row renderer state)
16
+ * is kept, so each row showing the call is redrawn when it leaves. */
17
+ includes(toolCallId: string, owner: object, invalidate: () => void): boolean;
18
+ };
19
+
20
+ /** Code Mode call IDs in the entries Pi rebuilds the chat from, oldest first.
21
+ * @example codemodeCallIds([{ type: "message", message: { role: "assistant", content: [{ type: "toolCall", name: "codemode", id: "a" }] } }]) // ["a"]
22
+ */
23
+ export function codemodeCallIds(entries: Iterable<SavedEntry>): string[] {
24
+ const ids: string[] = [];
25
+ for (const entry of entries) {
26
+ if (entry.type !== "message" || entry.message?.role !== "assistant" || !Array.isArray(entry.message.content)) continue;
27
+ for (const block of entry.message.content as ToolCallBlock[]) {
28
+ if (block.type === "toolCall" && block.name === "codemode" && typeof block.id === "string") ids.push(block.id);
29
+ }
30
+ }
31
+ return ids;
32
+ }
33
+
34
+ /** Track the newest `limit` Code Mode calls and invalidate a preview once newer calls push it out.
35
+ * @example (w => (w.add("a"), w.includes("a", {}, () => {})))(createPreviewWindow(1)) === true
36
+ */
37
+ export function createPreviewWindow(limit = PREVIEW_CALLS): PreviewWindow {
38
+ let positions = new Map<string, number>();
39
+ const previews = new Map<string, Map<object, () => void>>();
40
+ const outside = (toolCallId: string): boolean => !positions.has(toolCallId) || positions.size - positions.get(toolCallId)! > limit;
41
+ return {
42
+ sync(toolCallIds) {
43
+ positions = new Map();
44
+ previews.clear();
45
+ for (const toolCallId of toolCallIds) positions.set(toolCallId, positions.size);
46
+ },
47
+ add(toolCallId) {
48
+ if (positions.has(toolCallId)) return;
49
+ positions.set(toolCallId, positions.size);
50
+ for (const [shown, invalidations] of previews) {
51
+ if (!outside(shown)) continue;
52
+ previews.delete(shown);
53
+ for (const invalidate of invalidations.values()) invalidate();
54
+ }
55
+ },
56
+ includes(toolCallId, owner, invalidate) {
57
+ if (outside(toolCallId)) return false;
58
+ previews.set(toolCallId, (previews.get(toolCallId) ?? new Map()).set(owner, invalidate));
59
+ return true;
60
+ },
61
+ };
62
+ }
package/src/render.ts ADDED
@@ -0,0 +1,137 @@
1
+ import { highlightCode, type CodemodeToolDetails, type ToolRenderers } from "@earendil-works/pi-coding-agent";
2
+ import { Box, Text, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
3
+ import type { CreateCodemodeRenderers } from "./contract.ts";
4
+ import { renderChild } from "./renderers/children.ts";
5
+ import { commandMemo, displayColors, type CommandMemo } from "./renderers/bash.ts";
6
+ import { intentFromCode } from "./intent.ts";
7
+ import { box, displayText, KeptLines, Lines, styledOutput, textOutput, type RowMemo } from "./renderers/layout.ts";
8
+ import { javascriptPreview } from "./renderers/code-preview.ts";
9
+ import { jsonPreview, memoizedPreview } from "./renderers/preview.ts";
10
+
11
+ const SCRIPT_HEADER = /^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;
12
+ type RenderState = {
13
+ nativeResult?: ReturnType<NonNullable<ToolRenderers["renderResult"]>>;
14
+ startedAt?: number;
15
+ commands?: CommandMemo["entries"];
16
+ scriptOutput?: typeof jsonPreview;
17
+ javascript?: typeof javascriptPreview;
18
+ javascriptRows?: RowMemo;
19
+ javascriptColors?: { source: string; colors: string; lines: readonly string[] };
20
+ };
21
+
22
+ /** The JavaScript preview as displayed: formatted, then sanitized like the original source.
23
+ * @example displayedJavascript("text({a:1})") === 'text({ a: 1 });'
24
+ */
25
+ function displayedJavascript(source: string): string {
26
+ return displayText(javascriptPreview(source).replace(/\r/g, "")).trimEnd();
27
+ }
28
+
29
+ /** Apply the public self-renderer padding contract to both root surfaces.
30
+ * @example padded(component, 1) // One terminal column on each side.
31
+ */
32
+ function padded(component: Component, outputPad: number): Component {
33
+ const container = new Box(outputPad, 0);
34
+ container.addChild(component);
35
+ return container;
36
+ }
37
+
38
+ export const createCodemodeRenderers: CreateCodemodeRenderers = (getRun, original, highlightBash, previews) => ({
39
+ ...original,
40
+ renderShell: "self",
41
+ renderCall(args, theme, context) {
42
+ const source = (args as { code?: unknown } | undefined)?.code;
43
+ const code = typeof source === "string" ? displayText(source.replace(/\r/g, "")).trimEnd() : "";
44
+ const state = context.state as RenderState;
45
+ if (context.executionStarted) state.startedAt ??= Date.now();
46
+ const intent = intentFromCode(code, context.argsComplete);
47
+ if (!context.expanded && intent) {
48
+ return padded(new Text(`${theme.fg("toolTitle", theme.bold("Code Mode"))} ${theme.fg("accent", intent)}`, 0, 0), context.outputPad);
49
+ }
50
+ // Asked last, so only a row that shows a preview is kept for a redraw when its call leaves the newest 256.
51
+ const formatted = typeof source === "string" && context.expanded && context.argsComplete && !context.isPartial && !context.isError
52
+ && previews.includes(context.toolCallId, state, context.invalidate)
53
+ ? (state.javascript ??= memoizedPreview(displayedJavascript))(source)
54
+ : code;
55
+ const caption = formatted === code ? "JavaScript" : "JavaScript preview";
56
+ const sourceBox = (highlighted: readonly string[]): Component => padded(new Lines(width => {
57
+ const rows = highlighted.flatMap(line => wrapTextWithAnsi(line || " ", Math.max(1, width - 4)));
58
+ const shown = context.expanded ? rows : rows.slice(0, 8);
59
+ const remaining = rows.length - shown.length;
60
+ const hint = remaining ? wrapTextWithAnsi(theme.fg("muted", `… ${remaining} more source rows · expand to view`), Math.max(1, width - 4)) : [];
61
+ return [theme.fg("toolTitle", theme.bold("Code Mode")), ...box([...shown, ...hint], width, theme, theme.fg("muted", caption))];
62
+ }), context.outputPad);
63
+ if (formatted === code) return sourceBox(highlightCode(formatted, "javascript"));
64
+ // Pi redraws every past call on each invalidation; a finished preview only changes with colors, padding or width.
65
+ // Highlighting is kept separately, so a resize only wraps the preview again.
66
+ const colors = displayColors(theme);
67
+ const highlighted = (): readonly string[] => {
68
+ const kept = state.javascriptColors;
69
+ if (kept?.source === formatted && kept.colors === colors) return kept.lines;
70
+ state.javascriptColors = { source: formatted, colors, lines: highlightCode(formatted, "javascript") };
71
+ return state.javascriptColors.lines;
72
+ };
73
+ return new KeptLines(state.javascriptRows ??= {}, [formatted, context.outputPad, colors], width => [...sourceBox(highlighted()).render(width)]);
74
+ },
75
+ renderResult(result, options, theme, context) {
76
+ const run = getRun(context.toolCallId);
77
+ const source = (context.args as { code?: unknown } | undefined)?.code;
78
+ const intent = intentFromCode(typeof source === "string" ? source : "", context.argsComplete);
79
+ if (!options.expanded && !context.isError && intent) {
80
+ const details = result.details as CodemodeToolDetails | undefined;
81
+ const calls = details?.calls ?? run?.calls ?? [];
82
+ const counts = new Map<string, number>();
83
+ for (const call of calls) counts.set(call.status, (counts.get(call.status) ?? 0) + 1);
84
+ const startedAt = (context.state as RenderState).startedAt;
85
+ const timing = options.isPartial
86
+ ? startedAt === undefined ? "running" : `running ${Math.round((Date.now() - startedAt) / 1000)}s`
87
+ : context.durationMs === undefined ? "done" : `took ${(context.durationMs / 1000).toFixed(1)}s`;
88
+ const summary = [`${calls.length} tool calls`, ...Array.from(counts, ([status, count]) => `${count} ${status}`), timing].join(" · ");
89
+ const text = details?.fullOutputPath ? `${summary}\nFull output: ${details.fullOutputPath}` : summary;
90
+ return padded(new Text(theme.fg("muted", displayText(text)), 0, 0), context.outputPad);
91
+ }
92
+ if (!run && original.renderResult) {
93
+ const state = context.state as RenderState;
94
+ state.commands = undefined;
95
+ state.scriptOutput = undefined;
96
+ const component = original.renderResult(result, options, theme, { ...context, lastComponent: state.nativeResult });
97
+ state.nativeResult = component;
98
+ return padded(component, context.outputPad);
99
+ }
100
+ const calls = run?.calls ?? [];
101
+ const completed = options.expanded && !options.isPartial && !context.isError;
102
+ const state = context.state as RenderState;
103
+ const commands = commandMemo(state.commands ??= new Map(), theme, highlightBash, completed);
104
+ const children = calls.map(call => renderChild(call, theme, options.expanded, commands));
105
+ const [first, ...rest] = result.content;
106
+ const content = first?.type === "text" && SCRIPT_HEADER.test(first.text) ? rest : result.content;
107
+ const sourceOutput = textOutput({ ...result, content });
108
+ const output = displayText(sourceOutput.replace(/\r/g, "")).trimEnd();
109
+ const fullOutputPath = (result.details as CodemodeToolDetails | undefined)?.fullOutputPath;
110
+ const preview = completed && !fullOutputPath
111
+ ? (state.scriptOutput ??= memoizedPreview(jsonPreview))(sourceOutput)
112
+ : undefined;
113
+ const styled = preview
114
+ ? preview.map((part, index) => {
115
+ const text = displayText(part.text.replace(/\r/g, ""));
116
+ return part.json ? highlightCode(text, "json").join("\n") : styledOutput(index === preview.length - 1 ? text.trimEnd() : text, theme);
117
+ }).join("\n")
118
+ : styledOutput(output, theme, context.isError);
119
+ const failures = calls.filter(call => call.status === "error").length;
120
+ const summary = `${calls.length} call${calls.length === 1 ? "" : "s"}${failures ? ` · ${failures} failed` : ""}`;
121
+ return padded(new Lines(width => {
122
+ const rows: string[] = ["", theme.fg("muted", theme.bold(`Nested tools · ${summary}`))];
123
+ for (const child of children) rows.push("", ...child.render(width));
124
+ if (run?.incomplete) rows.push(...wrapTextWithAnsi(theme.fg("warning", "Nested call capture is incomplete or truncated"), width));
125
+ rows.push("", theme.fg("muted", theme.bold("Script output")));
126
+ const innerWidth = Math.max(1, width - 4);
127
+ const outputRows = styled.split("\n").flatMap(line => wrapTextWithAnsi(line || " ", innerWidth));
128
+ const shown = options.expanded ? outputRows : outputRows.slice(0, 10);
129
+ const remaining = outputRows.length - shown.length;
130
+ const hint = remaining ? wrapTextWithAnsi(theme.fg("muted", `… ${remaining} more rows · expand to view`), innerWidth) : [];
131
+ rows.push(...(output ? box([...shown, ...hint], width, theme) : [theme.fg("muted", options.isPartial ? "waiting for script output" : "no text output")]));
132
+ if (fullOutputPath) rows.push(...wrapTextWithAnsi(theme.fg("muted", `Full output: ${displayText(fullOutputPath)}`), width));
133
+ if (context.durationMs !== undefined) rows.push(theme.fg("muted", `Took ${(context.durationMs / 1000).toFixed(1)}s`));
134
+ return rows;
135
+ }), context.outputPad);
136
+ },
137
+ });
@@ -0,0 +1,125 @@
1
+ import { highlightCode, keyHint, truncateToVisualLines, type BashToolDetails, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import { visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
3
+ import type { BashHighlighter } from "@giladbarnea/pi-pretty-bash/highlighting.js";
4
+ import type { CapturedCall } from "../contract.ts";
5
+ import { box, displayText, expandTabs, isJson, Lines, sanitizedText, textOutput } from "./layout.ts";
6
+ import { bashPreview } from "./code-preview.ts";
7
+ import { memoizedPreview } from "./preview.ts";
8
+
9
+ // Adapted from Gilad's MIT-licensed pi-pretty-bash; the POC has no independent timers.
10
+
11
+ // Every theme color highlighted code can contain: the shared highlighter's syntax tokens, plus Pi's highlightCode
12
+ // colors (including its diff grammar's), plus the borders and titles drawn around code.
13
+ const DISPLAY_COLORS = [
14
+ "syntaxFunction", "syntaxKeyword", "syntaxType", "syntaxString", "syntaxVariable", "syntaxOperator",
15
+ "syntaxComment", "syntaxNumber", "syntaxPunctuation", "text", "muted", "mdCodeBlock", "toolDiffAdded", "toolDiffRemoved",
16
+ "borderMuted", "toolTitle",
17
+ ] as const;
18
+ // Pi registers its eager grammars at startup and all the others in one later step (loadAllHighlightLanguages),
19
+ // so whether one deferred grammar, diff, colors this probe tells which grammar set highlighted the code.
20
+ const GRAMMAR_PROBE = "-a\n+b";
21
+
22
+ /** Fingerprint the current colors and grammar set, since renderers cannot tell a theme change from any other redraw.
23
+ * @example displayColors(theme) === displayColors(theme)
24
+ */
25
+ export function displayColors(theme: Theme): string {
26
+ return DISPLAY_COLORS.map(color => theme.fg(color, "")).join("") + highlightCode(GRAMMAR_PROBE, "diff").join("\n");
27
+ }
28
+
29
+ type PreparedCommand = { source: string; colors: string; highlight: BashHighlighter["highlight"]; sourceLines: string[]; highlighted: string[]; firstLineColored: string };
30
+ type CommandEntry = { preview?: typeof bashPreview; visual?: PreparedCommand };
31
+ /** One Code Mode call's prepared nested command displays, keyed by child tool call ID. */
32
+ export type CommandMemo = { entries: Map<string, CommandEntry>; colors: string; highlight: BashHighlighter["highlight"]; showPreviews: boolean };
33
+
34
+ /** Describe the current colors and grammar set, and reuse a call's entries while they and the highlighter stay the same.
35
+ * @example commandMemo(new Map(), theme, highlighter.highlight, false).colors // A theme and grammar fingerprint.
36
+ */
37
+ export function commandMemo(entries: CommandMemo["entries"], theme: Theme, highlight: BashHighlighter["highlight"], showPreviews: boolean): CommandMemo {
38
+ return { entries, colors: displayColors(theme), highlight, showPreviews };
39
+ }
40
+
41
+ /** Highlight a child's command once per input, colors and highlighter, since Pi redraws every past call on each frame.
42
+ * @example preparedCommand(memo, {}, "echo hi", theme).firstLineColored // A syntax-colored "echo hi".
43
+ */
44
+ function preparedCommand(memo: CommandMemo, entry: CommandEntry, source: string, theme: Theme): PreparedCommand {
45
+ const cached = entry.visual;
46
+ if (cached?.source === source && cached.colors === memo.colors && cached.highlight === memo.highlight) return cached;
47
+ const sourceLines = expandTabs(source).split("\n");
48
+ const prepared: PreparedCommand = {
49
+ source, colors: memo.colors, highlight: memo.highlight, sourceLines,
50
+ // The highlighter sees tabs, because only leading tabs may precede a <<- terminator.
51
+ highlighted: expandTabs(memo.highlight(source, theme)).split("\n"),
52
+ firstLineColored: memo.highlight(sourceLines[0].trim() || "…", theme),
53
+ };
54
+ entry.visual = prepared;
55
+ return prepared;
56
+ }
57
+
58
+ /** Draw a complete command, using numbered boxes for multiline input.
59
+ * @example commandRows(command, 80, theme, false, false) // A syntax-colored short command header.
60
+ */
61
+ function commandRows(command: PreparedCommand, width: number, theme: Theme, running: boolean, preview: boolean): string[] {
62
+ const { sourceLines } = command;
63
+ const prefix = `${theme.fg(running ? "warning" : "accent", "● ")}${theme.bold(preview ? "Bash preview " : "Bash ")}`;
64
+ const header = `${prefix}${command.firstLineColored}`;
65
+ if (sourceLines.length === 1 && visibleWidth(header) <= width) return [header];
66
+ const numberWidth = sourceLines.length > 1 ? Math.max(2, String(sourceLines.length).length) : 0;
67
+ const codeWidth = Math.max(1, width - 4 - (numberWidth ? numberWidth + 1 : 0));
68
+ const rows = command.highlighted.flatMap((line, index) => wrapTextWithAnsi(line || " ", codeWidth).map((segment, segmentIndex) => {
69
+ const number = segmentIndex === 0 ? theme.fg("muted", String(index + 1).padStart(numberWidth)) : " ".repeat(numberWidth);
70
+ return numberWidth ? `${number} ${segment}` : segment;
71
+ }));
72
+ return [prefix.trimEnd(), ...box(rows, width, theme)];
73
+ }
74
+
75
+ /** Interpret a producer exit footer only for failed calls.
76
+ * @example parseOutput('Command exited with code 99', 'ok').body === 'Command exited with code 99'
77
+ */
78
+ function parseOutput(output: string, status: CapturedCall["status"]): { body: string; caption: string } {
79
+ const body = displayText(output).trimEnd();
80
+ if (status === "running") return { body, caption: "running" };
81
+ if (status === "cancelled") return { body, caption: "⊘ cancelled" };
82
+ if (status === "ok") return { body, caption: "✓" };
83
+ const match = /(?:^|\n)(Command exited with code (\d+)|Command aborted|Command timed out after (\d+) seconds(?:\. [^\n]*)?)\s*$/.exec(body);
84
+ if (!match) return { body, caption: "✗ failed" };
85
+ const caption = match[2] ? `✗ exit ${match[2]}` : match[3] ? `✗ timeout ${match[3]}s` : "✗ aborted";
86
+ return { body: body.slice(0, match.index).trimEnd(), caption };
87
+ }
88
+
89
+ export function renderBash(call: CapturedCall, theme: Theme, expanded: boolean, commands: CommandMemo): Component {
90
+ const source = call.args.command;
91
+ const raw = sanitizedText(String(source ?? ""));
92
+ let entry = commands.entries.get(call.toolCallId);
93
+ if (!entry) commands.entries.set(call.toolCallId, entry = {});
94
+ const formatted = commands.showPreviews && call.status === "ok" && typeof source === "string"
95
+ ? (entry.preview ??= memoizedPreview(bashPreview))(source)
96
+ : source;
97
+ const displayed = formatted !== source && typeof formatted === "string"
98
+ ? sanitizedText(formatted).replace(/\n$/, "")
99
+ : raw;
100
+ const command = preparedCommand(commands, entry, displayed === raw.replace(/\n$/, "") ? raw : displayed, theme);
101
+ const details = call.result?.details as BashToolDetails | undefined;
102
+ const parsed = parseOutput(textOutput(call.result), call.status);
103
+ if (details?.truncation?.truncated) parsed.body = parsed.body.replace(/\n*\[Showing [^\]]*\]\s*$/, "");
104
+ const running = call.status === "running";
105
+ const color = running ? "warning" : call.status === "error" ? "error" : call.status === "cancelled" ? "muted" : "success";
106
+ const count = parsed.body ? parsed.body.split("\n").length : 0;
107
+ const caption = [
108
+ theme.fg(color, parsed.caption),
109
+ ...(call.durationMs === undefined ? [] : [theme.fg("muted", `${(call.durationMs / 1000).toFixed(1)}s`)]),
110
+ ...(count ? [theme.fg("muted", `${count} line${count === 1 ? "" : "s"}`)] : []),
111
+ ...(details?.truncation?.truncated ? [theme.fg("warning", "truncated")] : []),
112
+ ].join(theme.fg("dim", " · "));
113
+ const styled = !running && !details?.truncation?.truncated && isJson(parsed.body)
114
+ ? highlightCode(parsed.body, "json").join("\n")
115
+ : parsed.body.split("\n").map(line => theme.fg("toolOutput", line)).join("\n");
116
+ return new Lines(width => {
117
+ const header = commandRows(command, width, theme, running, command.source !== raw);
118
+ if (!parsed.body.trim()) return [...header, `${caption}${theme.fg("muted", running ? " · waiting for output" : " · no output")}`];
119
+ const innerWidth = Math.max(1, width - 4);
120
+ const { skippedCount, visualLines } = truncateToVisualLines(styled, expanded ? Infinity : 10, innerWidth);
121
+ const hint = skippedCount ? wrapTextWithAnsi(`${theme.fg("muted", `… ${skippedCount} earlier lines · `)}${keyHint("app.tools.expand", "to expand")}`, innerWidth) : [];
122
+ const fullPath = details?.fullOutputPath ? wrapTextWithAnsi(theme.fg("muted", `Full output: ${displayText(details.fullOutputPath)}`), width) : [];
123
+ return [...header, ...box([...hint, ...visualLines], width, theme, caption), ...fullPath];
124
+ });
125
+ }
@@ -0,0 +1,62 @@
1
+ import { getLanguageFromPath, highlightCode, renderDiff, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import { wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
3
+ import type { CapturedCall } from "../contract.ts";
4
+ import { renderBash, type CommandMemo } from "./bash.ts";
5
+ import { box, displayText, Lines, numberedRows, styledOutput, textOutput } from "./layout.ts";
6
+
7
+ type MutationDetails = {
8
+ diff?: string;
9
+ kendexDiff?: { lines: { type: string; content: string; oldNum: number | null; newNum: number | null }[] };
10
+ };
11
+ const STATUS = { running: ["…", "warning"], ok: ["✓", "success"], error: ["✗", "error"], cancelled: ["⊘", "muted"] } as const;
12
+ const LABELS: Readonly<Record<string, string>> = { read: "Read", edit: "Edit", write: "Write" };
13
+
14
+ /** Use only authoritative diff details, never the current file on disk.
15
+ * @example mutationDiff({diff: '-1 old\n+1 new'}) === '-1 old\n+1 new'
16
+ */
17
+ function mutationDiff(details: MutationDetails | undefined): string | undefined {
18
+ if (typeof details?.diff === "string") return details.diff;
19
+ return details?.kendexDiff?.lines.map(line => {
20
+ const prefix = line.type === "del" ? "-" : line.type === "add" ? "+" : " ";
21
+ return `${prefix}${line.type === "del" ? line.oldNum ?? "" : line.newNum ?? line.oldNum ?? ""} ${line.content}`;
22
+ }).join("\n");
23
+ }
24
+
25
+ /** Draw a child from its recorded arguments, status and actual result.
26
+ * @example renderChild(recordedRead, theme, true) // No file reads or tool execution.
27
+ */
28
+ export function renderChild(call: CapturedCall, theme: Theme, expanded: boolean, commands: CommandMemo): Component {
29
+ if (call.toolName === "bash") return renderBash(call, theme, expanded, commands);
30
+ const [icon, color] = STATUS[call.status];
31
+ const path = displayText(typeof call.args.path === "string" ? call.args.path : "");
32
+ const label = displayText(LABELS[call.toolName] ?? call.toolName);
33
+ const args = path || displayText(JSON.stringify(call.args));
34
+ const timing = call.durationMs === undefined ? "" : theme.fg("dim", ` · ${(call.durationMs / 1000).toFixed(1)}s`);
35
+ const header = `${theme.fg(color, icon)} ${theme.fg("toolTitle", theme.bold(label))} ${theme.fg("accent", args)}${timing}`;
36
+ const output = displayText(textOutput(call.result)).trimEnd();
37
+ const error = call.status === "error";
38
+ const diff = !error && ["edit", "write"].includes(call.toolName) ? mutationDiff(call.result?.details as MutationDetails | undefined) : undefined;
39
+ const isRead = call.toolName === "read" && !error;
40
+ const language = getLanguageFromPath(path);
41
+ const lines = isRead && Buffer.byteLength(output, "utf8") <= 200 * 1024
42
+ ? highlightCode(output, language).join("\n")
43
+ : styledOutput(output, theme, error);
44
+ const rendered = diff === undefined ? lines : renderDiff(displayText(diff));
45
+ const firstLine = typeof call.args.offset === "number" ? call.args.offset : 1;
46
+ const media = call.result?.content.filter(block => block.type === "image").length ?? 0;
47
+ return new Lines(width => {
48
+ const headings = wrapTextWithAnsi(header, width);
49
+ const innerWidth = Math.max(1, width - 4);
50
+ const rows = isRead && output ? numberedRows(rendered.split("\n"), firstLine, innerWidth, theme)
51
+ : rendered ? rendered.split("\n").flatMap(line => wrapTextWithAnsi(line || " ", innerWidth)) : [];
52
+ const shown = expanded ? rows : rows.slice(0, 10);
53
+ const caption = diff === undefined ? theme.fg("muted", `${output ? output.split("\n").length : 0} lines`)
54
+ : [theme.fg("success", `+${diff.split("\n").filter(line => line.startsWith("+")).length}`), theme.fg("error", `-${diff.split("\n").filter(line => line.startsWith("-")).length}`)].join(" ");
55
+ const remaining = rows.length - shown.length;
56
+ const hint = remaining ? wrapTextWithAnsi(theme.fg("muted", `… ${remaining} more rows · expand to view`), innerWidth) : [];
57
+ const empty = call.status === "running" ? "waiting for output" : call.status === "cancelled" ? "cancelled" : "no text output";
58
+ const body = rows.length ? box([...shown, ...hint], width, theme, caption) : [theme.fg("muted", empty)];
59
+ const imageNote = media ? wrapTextWithAnsi(theme.fg("muted", `${media} image result${media === 1 ? "" : "s"} · nested image preview unavailable`), width) : [];
60
+ return [...headings, ...body, ...imageNote];
61
+ });
62
+ }
@@ -0,0 +1,30 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { createFromBuffer, type Formatter } from "@dprint/formatter";
3
+ import { getBuffer as bashPlugin } from "@dprint/shfmt";
4
+ import { getPath as javascriptPluginPath } from "@dprint/typescript";
5
+ import { canFormatPreview } from "./preview.ts";
6
+
7
+ /** Lazily create one formatter for each language, and decline invalid or oversized source.
8
+ * @example codePreview("preview.js", loadJavascript)("const =") === "const ="
9
+ */
10
+ function codePreview(filePath: string, load: () => Formatter): (source: string) => string {
11
+ let formatter: Formatter | undefined;
12
+ return source => {
13
+ if (!canFormatPreview(source)) return source;
14
+ formatter ??= load();
15
+ try { return formatter.formatText({ filePath, fileText: source }); }
16
+ catch { return source; }
17
+ };
18
+ }
19
+
20
+ export const javascriptPreview = codePreview("preview.js", () => {
21
+ const formatter = createFromBuffer(readFileSync(javascriptPluginPath()));
22
+ formatter.setConfig({ indentWidth: 2, lineWidth: 76 }, { quoteStyle: "preferDouble", quoteProps: "preserve" });
23
+ return formatter;
24
+ });
25
+
26
+ export const bashPreview = codePreview("preview.bash", () => {
27
+ const formatter = createFromBuffer(bashPlugin());
28
+ formatter.setConfig({}, { dialect: "bash", useTabs: false, indentWidth: 2, binaryNextLine: true, switchCaseIndent: true, spaceRedirects: true });
29
+ return formatter;
30
+ });
@@ -0,0 +1,114 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import { highlightCode, type AgentToolResult, type Theme } from "@earendil-works/pi-coding-agent";
3
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
4
+
5
+ export class Lines implements Component {
6
+ private width?: number;
7
+ private rows?: string[];
8
+
9
+ constructor(private draw: (width: number) => string[]) {}
10
+
11
+ invalidate(): void { this.rows = undefined; }
12
+
13
+ render(width: number): string[] {
14
+ if (this.rows && this.width === width) return this.rows;
15
+ this.width = width;
16
+ this.rows = this.draw(Math.max(1, width)).map(row => truncateToWidth(row, Math.max(1, width)));
17
+ return this.rows;
18
+ }
19
+ }
20
+
21
+ /** The last rows a renderer drew for one surface, kept in Pi's per-row renderer state. */
22
+ export type RowMemo = { keys?: readonly unknown[]; width?: number; rows?: string[] };
23
+
24
+ /** Reuse drawn rows across Pi's transcript invalidation while their keys and the width stay the same.
25
+ * Pi invalidates every past tool row on theme changes and full redraws; the keys must name everything the rows show.
26
+ * @example new KeptLines(state.rows ??= {}, [source, colors], width => [source]).render(80)
27
+ */
28
+ export class KeptLines implements Component {
29
+ constructor(private memo: RowMemo, private keys: readonly unknown[], private draw: (width: number) => string[]) {}
30
+
31
+ invalidate(): void {}
32
+
33
+ render(width: number): string[] {
34
+ const memo = this.memo;
35
+ const same = memo.rows && memo.width === width && memo.keys!.length === this.keys.length && memo.keys!.every((key, index) => key === this.keys[index]);
36
+ if (same) return memo.rows!;
37
+ Object.assign(memo, { keys: this.keys, width, rows: this.draw(width) });
38
+ return memo.rows!;
39
+ }
40
+ }
41
+
42
+ /** Remove untrusted terminal instructions before applying renderer-owned styling.
43
+ * @example displayText('\x1b[31mhello\x1b[0m\x07') // "hello"
44
+ */
45
+ export function displayText(text: string): string {
46
+ return expandTabs(sanitizedText(text));
47
+ }
48
+
49
+ /** Remove untrusted terminal instructions, keeping tabs.
50
+ * @example sanitizedText('\x1b[31m\tok\x07') // "\tok"
51
+ */
52
+ export function sanitizedText(text: string): string {
53
+ return stripVTControlCharacters(text).replace(/\r\n|\r/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "");
54
+ }
55
+
56
+ /** @example expandTabs('\tok') // " ok" */
57
+ export function expandTabs(text: string): string {
58
+ return text.replace(/\t/g, " ");
59
+ }
60
+
61
+ /** Return text blocks without changing their contents.
62
+ * @example textOutput({content: [{type: "text", text: "hello"}], details: undefined}) === "hello"
63
+ */
64
+ export function textOutput(result: AgentToolResult<unknown> | undefined): string {
65
+ return result?.content.filter(block => block.type === "text").map(block => block.text).join("\n") ?? "";
66
+ }
67
+
68
+ /** Draw the same compact bordered surface used by rich Bash.
69
+ * @example box(["hello"], 20, theme).length === 3
70
+ */
71
+ export function box(rows: string[], width: number, theme: Theme, caption = ""): string[] {
72
+ const border = (text: string): string => theme.fg("borderMuted", text);
73
+ const innerWidth = Math.max(1, width - 4);
74
+ const title = truncateToWidth(caption, Math.max(1, width - 6));
75
+ const top = title
76
+ ? `${border("┌─")} ${title} ${border("─".repeat(Math.max(1, width - 5 - visibleWidth(title))) + "┐")}`
77
+ : border(`┌${"─".repeat(Math.max(1, width - 2))}┐`);
78
+ return [
79
+ top,
80
+ ...rows.map(row => `${border("│")} ${row}${" ".repeat(Math.max(0, innerWidth - visibleWidth(row)))}\x1b[0m ${border("│")}`),
81
+ border(`└${"─".repeat(Math.max(1, width - 2))}┘`),
82
+ ];
83
+ }
84
+
85
+ /** Recognize complete JSON within the existing Bash highlighting budget.
86
+ * @example isJson('{"ok":true}') === true
87
+ */
88
+ export function isJson(text: string): boolean {
89
+ if (Buffer.byteLength(text, "utf8") > 200 * 1024) return false;
90
+ try { JSON.parse(text); return true; } catch { return false; }
91
+ }
92
+
93
+ /** Highlight JSON without attributing it to any tool or reformatting it.
94
+ * @example styledOutput('{"ok":true}', theme) // Theme-colored JSON with unchanged visible text.
95
+ */
96
+ export function styledOutput(text: string, theme: Theme, error = false): string {
97
+ if (!error && isJson(text)) return highlightCode(text, "json").join("\n");
98
+ const withinBudget = !error && Buffer.byteLength(text, "utf8") <= 200 * 1024;
99
+ return text.split("\n").map(line => withinBudget && isJson(line)
100
+ ? highlightCode(line, "json").join("\n")
101
+ : theme.fg(error ? "error" : "toolOutput", line)).join("\n");
102
+ }
103
+
104
+ /** Wrap numbered source while retaining continuation indentation.
105
+ * @example numberedRows(["abc"], 1, 20, theme).length === 1
106
+ */
107
+ export function numberedRows(lines: string[], start: number, width: number, theme: Theme): string[] {
108
+ const gutterWidth = String(start + lines.length - 1).length;
109
+ const codeWidth = Math.max(1, width - gutterWidth - 3);
110
+ return lines.flatMap((line, index) => wrapTextWithAnsi(line || " ", codeWidth).map((segment, segmentIndex) => {
111
+ const number = segmentIndex === 0 ? String(start + index).padStart(gutterWidth) : " ".repeat(gutterWidth);
112
+ return `${theme.fg("muted", number)} ${theme.fg("borderMuted", "│")} ${segment}`;
113
+ }));
114
+ }
@@ -0,0 +1,85 @@
1
+ const MAX_PREVIEW_BYTES = 16 * 1024;
2
+ const MAX_JSON_DEPTH = 32;
3
+ const TEXT_ITEM = /^==> text ([1-9]\d*)\/([1-9]\d*) <==\n/gm;
4
+
5
+ /** Cache the current display transform, including declined inputs, independently of width and theme.
6
+ * @example memoizedPreview((source) => source.toUpperCase())("hello") === "HELLO"
7
+ */
8
+ export function memoizedPreview<Preview>(format: (source: string) => Preview): (source: string) => Preview {
9
+ let cached: { source: string; preview: Preview } | undefined;
10
+ return source => {
11
+ if (cached?.source !== source) cached = { source, preview: format(source) };
12
+ return cached.preview;
13
+ };
14
+ }
15
+
16
+ /** Decline oversized input and source containing terminal controls other than line breaks and tabs.
17
+ * @example canFormatPreview("echo \x1b[2J") === false
18
+ */
19
+ export function canFormatPreview(source: string): boolean {
20
+ return Buffer.byteLength(source) <= MAX_PREVIEW_BYTES && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/.test(source);
21
+ }
22
+
23
+ /** Indent original JSON tokens, without round-tripping through JavaScript values.
24
+ * @example indentJson('[9e+2,-0]') === '[\n 9e+2,\n -0\n]'
25
+ */
26
+ function indentJson(source: string): string | undefined {
27
+ if (!/^[ \t\r\n]*[\[{]/.test(source)) return undefined;
28
+ try { JSON.parse(source); } catch { return undefined; }
29
+ const tokens = source.match(/"(?:\\[\s\S]|[^"\\])*"|[{}\[\],:]|[^{}\[\],:" \t\r\n]+/g)!;
30
+ const pieces: string[] = [];
31
+ let depth = 0;
32
+ const newline = (): void => { pieces.push("\n", " ".repeat(depth)); };
33
+ for (let index = 0; index < tokens.length; index++) {
34
+ const token = tokens[index];
35
+ switch (token) {
36
+ case "{": case "[":
37
+ pieces.push(token);
38
+ if (tokens[index + 1] === (token === "{" ? "}" : "]")) {
39
+ pieces.push(tokens[++index]);
40
+ break;
41
+ }
42
+ if (++depth > MAX_JSON_DEPTH) return undefined;
43
+ newline();
44
+ break;
45
+ case "}": case "]":
46
+ depth--;
47
+ newline();
48
+ pieces.push(token);
49
+ break;
50
+ case ",":
51
+ pieces.push(token);
52
+ newline();
53
+ break;
54
+ case ":":
55
+ pieces.push(": ");
56
+ break;
57
+ default:
58
+ pieces.push(token);
59
+ }
60
+ }
61
+ return pieces.join("");
62
+ }
63
+
64
+ type OutputPart = { text: string; json?: true };
65
+
66
+ /** Keep complete JSON items as separate syntax-highlighting units inside mixed Script output.
67
+ * @example jsonPreview('[1,2]')?.[0].text === '[\n 1,\n 2\n]'
68
+ */
69
+ export function jsonPreview(source: string): OutputPart[] | undefined {
70
+ if (!canFormatPreview(source)) return undefined;
71
+ if (!source.startsWith("==> text ")) {
72
+ const json = indentJson(source);
73
+ return json === undefined ? undefined : [{ text: json, json: true }];
74
+ }
75
+ const markers = Array.from(source.matchAll(TEXT_ITEM));
76
+ if (markers.length < 2 || markers[0].index !== 0 || markers.some((marker, index) =>
77
+ marker[1] !== String(index + 1) || marker[2] !== String(markers.length))) return undefined;
78
+ const parts = markers.flatMap((marker, index): OutputPart[] => {
79
+ const next = markers[index + 1];
80
+ const body = source.slice(marker.index + marker[0].length, next ? next.index - 1 : source.length);
81
+ const json = indentJson(body);
82
+ return [{ text: marker[0].slice(0, -1) }, json === undefined ? { text: body } : { text: json, json: true }];
83
+ });
84
+ return parts.some(part => part.json) ? parts : undefined;
85
+ }