@notrico/pi-fold 0.0.0-stage → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +129 -0
- package/LICENSE +21 -0
- package/README.md +71 -2
- package/docs/implementation.md +47 -0
- package/docs/performance.md +118 -0
- package/docs/renderer-reference.md +110 -0
- package/index.ts +53 -0
- package/package.json +55 -4
- package/scripts/performance-review.mjs +273 -0
- package/scripts/preview-work-strip.mjs +84 -0
- package/scripts/preview.mjs +232 -0
- package/scripts/retained-memory-review.mjs +46 -0
- package/scripts/test.mjs +21 -0
- package/src/action-intent.ts +93 -0
- package/src/display-card.ts +64 -0
- package/src/display-line-cache.ts +26 -0
- package/src/display-mode.ts +33 -0
- package/src/fold-command.ts +61 -0
- package/src/inspection.ts +87 -0
- package/src/modern-code-content.ts +131 -0
- package/src/modern-code-pane.ts +101 -0
- package/src/modern-native-tools.ts +79 -0
- package/src/modern-prompts-adapter.ts +41 -0
- package/src/modern-prompts.ts +185 -0
- package/src/modern-recorded-pane.ts +68 -0
- package/src/modern-rich-text.ts +48 -0
- package/src/modern-skill-prompts.ts +152 -0
- package/src/modern-subagent-groups.ts +158 -0
- package/src/modern-subagent-messages.ts +176 -0
- package/src/modern-subagent-spacing.ts +35 -0
- package/src/modern-subagents.ts +52 -0
- package/src/modern-thinking-adapter.ts +85 -0
- package/src/modern-thinking.ts +236 -0
- package/src/modern-tool-content.ts +28 -0
- package/src/modern-tool-images.ts +63 -0
- package/src/modern-tool-pane.ts +208 -0
- package/src/modern-tools.ts +509 -0
- package/src/modern-workflows.ts +209 -0
- package/src/native-method-chain.ts +31 -0
- package/src/permission-presentation.ts +280 -0
- package/src/recorded-summary.ts +13 -0
- package/src/work-strip-subagents.ts +221 -0
- package/src/work-strip-view.ts +104 -0
- package/src/work-strip.ts +443 -0
- package/tests/action-intent.test.mjs +44 -0
- package/tests/codemode.test.mjs +365 -0
- package/tests/display-cache-lifecycle.test.mjs +55 -0
- package/tests/display-line-cache.test.mjs +48 -0
- package/tests/display-mode.test.mjs +25 -0
- package/tests/fixtures/preview-fixture.ts +81 -0
- package/tests/fold-command.test.mjs +150 -0
- package/tests/fold-shortcut.test.mjs +143 -0
- package/tests/input-focus.test.mjs +95 -0
- package/tests/inspection.test.mjs +50 -0
- package/tests/mixed-thinking.test.mjs +319 -0
- package/tests/modern-prompts.test.mjs +84 -0
- package/tests/modern-skill-prompts.test.mjs +174 -0
- package/tests/modern-subagent-groups.test.mjs +132 -0
- package/tests/modern-subagent-messages.test.mjs +137 -0
- package/tests/modern-thinking.test.mjs +202 -0
- package/tests/modern-tools.test.mjs +908 -0
- package/tests/modern-workflows.test.mjs +147 -0
- package/tests/ordinary-prompts.test.mjs +167 -0
- package/tests/permission-presentation.test.mjs +257 -0
- package/tests/preview-example.test.mjs +171 -0
- package/tests/reload-lifecycle.test.mjs +161 -0
- package/tests/subagent-spacing.test.mjs +34 -0
- package/tests/test-runtime.mjs +58 -0
- package/tests/work-strip-final-surface.test.mjs +271 -0
- package/tests/work-strip-hierarchy.test.mjs +258 -0
- package/tests/work-strip-preview.test.mjs +120 -0
- package/tests/work-strip-spacing.test.mjs +208 -0
- package/tests/work-strip-subagents.test.mjs +236 -0
- package/tests/work-strip.test.mjs +148 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { DisplayMode } from './display-mode.ts';
|
|
2
|
+
import { VERSION, type ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import { Container, ScrollView, isViewportTUI, type Component } from '@earendil-works/pi-tui';
|
|
4
|
+
import { projectedChildren } from './work-strip-view.ts';
|
|
5
|
+
|
|
6
|
+
type Choice = { id: string; kind: string; label: string; focus(): void };
|
|
7
|
+
type Target = (component: Component) => boolean;
|
|
8
|
+
const children = (component: any): Component[] => [...(Array.isArray(component?.[projectedChildren]) ? component[projectedChildren] : Array.isArray(component?.children) ? component.children : []), ...(component?.child && typeof component.child.render === 'function' ? [component.child] : [])];
|
|
9
|
+
|
|
10
|
+
/** Pi 1.3 viewport seam. Read the mounted tree; never replace its layout/root. */
|
|
11
|
+
export function revealInspection(tui: any, target: Target, version = VERSION): boolean {
|
|
12
|
+
if (version !== '1.3.0' || !tui || !isViewportTUI(tui) || typeof tui.getMountedRoots !== 'function') return false;
|
|
13
|
+
const scrolls: ScrollView[] = [], seen = new Set<Component>();
|
|
14
|
+
const find = (component: Component) => {
|
|
15
|
+
if (seen.has(component)) return; seen.add(component);
|
|
16
|
+
if (component instanceof ScrollView && component.primary) { scrolls.push(component); return; }
|
|
17
|
+
children(component).forEach(find);
|
|
18
|
+
};
|
|
19
|
+
for (const root of tui.getMountedRoots()) find(root);
|
|
20
|
+
if (scrolls.length !== 1) return false;
|
|
21
|
+
const scroll = scrolls[0], document = scroll.children[0];
|
|
22
|
+
if (!document) return false;
|
|
23
|
+
const width = scroll.getContentWidth(Math.max(1, tui.terminal.columns));
|
|
24
|
+
// Opening a work strip changes its projected child list. Measure before the
|
|
25
|
+
// traversal so nested inspection uses the same tree as native mouse layout.
|
|
26
|
+
document.render(width);
|
|
27
|
+
const contains = (component: Component, visited = new Set<Component>()): boolean => {
|
|
28
|
+
if (visited.has(component)) return false; visited.add(component);
|
|
29
|
+
return target(component) || children(component).some(child => contains(child, visited));
|
|
30
|
+
};
|
|
31
|
+
let row = 0, found: number | undefined;
|
|
32
|
+
const visit = (component: Component) => {
|
|
33
|
+
if (found !== undefined) return;
|
|
34
|
+
// Plain Containers add no own spacing. Subclasses own their final rendered height.
|
|
35
|
+
if (component.constructor === Container) { for (const child of children(component)) visit(child); return; }
|
|
36
|
+
const height = component.render(width).length;
|
|
37
|
+
if (height && contains(component)) { found = row; return; }
|
|
38
|
+
row += height;
|
|
39
|
+
};
|
|
40
|
+
visit(document);
|
|
41
|
+
if (found === undefined) return false;
|
|
42
|
+
scroll.scrollTo(found, { disableFollow: true }); tui.requestRender();
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Native picker plus visible focus status. No model tools, transcript or editor mutation. */
|
|
47
|
+
export function registerInspection(pi: ExtensionAPI, mode: DisplayMode): () => void {
|
|
48
|
+
let ui: any, tui: any, disposed = false;
|
|
49
|
+
let revealTimer: ReturnType<typeof setTimeout> | undefined;
|
|
50
|
+
const clearStatus = () => { if (revealTimer) clearTimeout(revealTimer); revealTimer = undefined; ui?.setStatus?.('compact-inspection', undefined); };
|
|
51
|
+
const clear = () => { clearStatus(); ui?.setWidget?.('compact-inspection-host', undefined); ui = undefined; tui = undefined; };
|
|
52
|
+
const subscriptions = [
|
|
53
|
+
pi.on('session_start', (_event, ctx) => {
|
|
54
|
+
clear(); if (disposed || !ctx.hasUI) return; ui = ctx.ui;
|
|
55
|
+
// This zero-row widget only obtains the supported TUI handle. It owns no root.
|
|
56
|
+
ui.setWidget?.('compact-inspection-host', (host: any) => { tui = host; return { render: () => [], invalidate() {} }; });
|
|
57
|
+
}),
|
|
58
|
+
pi.on('session_before_switch', clear), pi.on('session_shutdown', clear),
|
|
59
|
+
pi.on('ui_prompt_start', clearStatus), pi.on('session_tree', clearStatus), pi.on('session_compact', clearStatus), mode.onChange(clearStatus),
|
|
60
|
+
pi.events.on('compact-renderer:inspection-ended:v1', clearStatus),
|
|
61
|
+
pi.events.on('compact-renderer:focus:v1', (event: any) => {
|
|
62
|
+
if (event?.owner === 'editor') { clearStatus(); return; }
|
|
63
|
+
if (!event?.target || disposed || !mode.isEnabled()) return;
|
|
64
|
+
clearStatus();
|
|
65
|
+
revealInspection(tui, event.target);
|
|
66
|
+
// Opening a pane changes the layout height. Reapply once after the native
|
|
67
|
+
// render frame has measured it; do not poll or replace the layout root.
|
|
68
|
+
revealTimer = setTimeout(() => { revealTimer = undefined; if (!disposed) revealInspection(tui, event.target); }, 30);
|
|
69
|
+
ui?.setStatus?.('compact-inspection', `Inspecting ${event.owner === 'work' ? 'work' : event.owner === 'tools' ? 'tools' : event.owner === 'thinking' ? 'thinking' : event.owner === 'subagents' ? 'subagents' : 'prompt'} · Esc or type to return`);
|
|
70
|
+
}),
|
|
71
|
+
];
|
|
72
|
+
pi.registerCommand('inspect', {
|
|
73
|
+
description: 'Select tools, subagent activity, thinking, or a prompt to inspect',
|
|
74
|
+
async handler(_args, ctx) {
|
|
75
|
+
if (!ctx.hasUI || disposed) return;
|
|
76
|
+
if (!mode.isEnabled()) { ctx.ui.notify('Use /fold on to inspect grouped blocks.', 'info'); return; }
|
|
77
|
+
const choices: Choice[] = [];
|
|
78
|
+
pi.events.emit('compact-renderer:inspect:v1', { add(choice: Choice) { if (choice && typeof choice.focus === 'function') choices.push(choice); } });
|
|
79
|
+
if (!choices.length) { ctx.ui.notify('No Pi Fold blocks to inspect yet.', 'info'); return; }
|
|
80
|
+
const labels = choices.map((choice, index) => `${index + 1}. ${choice.kind} — ${choice.label.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ').slice(0, 160)}`);
|
|
81
|
+
const selected = await ctx.ui.select('Inspect a block', labels);
|
|
82
|
+
const index = selected === undefined ? -1 : labels.indexOf(selected);
|
|
83
|
+
if (index >= 0 && !disposed && mode.isEnabled()) choices[index].focus();
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
return () => { if (disposed) return; disposed = true; clear(); subscriptions.forEach(off => off()); };
|
|
87
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
2
|
+
import { richTextRows } from "./modern-rich-text.ts";
|
|
3
|
+
import { codeIntent } from "./action-intent.ts";
|
|
4
|
+
|
|
5
|
+
const missing = Symbol("unsupported accessor");
|
|
6
|
+
const data = (object: any, key: string): any => {
|
|
7
|
+
if (!object || typeof object !== "object") return undefined;
|
|
8
|
+
const descriptor = Object.getOwnPropertyDescriptor(object, key);
|
|
9
|
+
return descriptor && !("value" in descriptor) ? missing : descriptor?.value;
|
|
10
|
+
};
|
|
11
|
+
export const codeDuration = (ms: number) => ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;
|
|
12
|
+
export const codeCost = (cost: number) => `$${cost >= .01 ? cost.toFixed(2) : cost.toPrecision(2)}`;
|
|
13
|
+
const scriptHeader = /^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;
|
|
14
|
+
|
|
15
|
+
function* metadataValues(value: any, ancestors = new Set<object>()): Generator<string> {
|
|
16
|
+
if (typeof value === "string") { yield value || '""'; return; }
|
|
17
|
+
if (value === null || typeof value !== "object") { yield String(value); return; }
|
|
18
|
+
if (ancestors.has(value)) { yield "[circular reference]"; return; }
|
|
19
|
+
ancestors.add(value); let fields = 0;
|
|
20
|
+
for (const key in value) if (Object.prototype.hasOwnProperty.call(value, key)) {
|
|
21
|
+
fields++; yield key; yield ":";
|
|
22
|
+
const field = data(value, key);
|
|
23
|
+
if (field === missing) yield "[Recorded accessor; not evaluated]";
|
|
24
|
+
else yield* metadataValues(field, ancestors);
|
|
25
|
+
}
|
|
26
|
+
if (!fields) yield Array.isArray(value) ? "[]" : "{}";
|
|
27
|
+
ancestors.delete(value);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Data references only. Aggregate/shape work happens once per explicit update revision;
|
|
31
|
+
* rendering visits bounded chunks and the nested calls reached by the viewport. */
|
|
32
|
+
export class CodeContent {
|
|
33
|
+
supported = true;
|
|
34
|
+
calls: any[] = [];
|
|
35
|
+
content: any[] = [];
|
|
36
|
+
code = "";
|
|
37
|
+
intent = "Run code";
|
|
38
|
+
private details: any;
|
|
39
|
+
errors = 0; cancelled = 0; unresolved = 0; priced = 0; totalCost = 0; images = 0;
|
|
40
|
+
private visibleContent: { block: any; index: number }[] = [];
|
|
41
|
+
aggregateBlocks = 0;
|
|
42
|
+
aggregateEntries = 0; sourceCharacters = 0; paintedCalls = 0;
|
|
43
|
+
private revision = -1;
|
|
44
|
+
update(args: any, result: any, revision: number) {
|
|
45
|
+
if (revision === this.revision) return false;
|
|
46
|
+
this.revision = revision; this.supported = true;
|
|
47
|
+
this.errors = this.cancelled = this.unresolved = this.priced = this.totalCost = this.images = 0;
|
|
48
|
+
const code = data(args, "code"), content = result ? data(result, "content") : [], details = result ? data(result, "details") : undefined;
|
|
49
|
+
const calls = details == null ? [] : data(details, "calls");
|
|
50
|
+
if (typeof code !== "string" || !Array.isArray(content) || details === missing || calls === missing || calls != null && !Array.isArray(calls)) { this.supported = false; return true; }
|
|
51
|
+
this.code = code; this.content = content; this.calls = calls ?? []; this.details = details; this.visibleContent = [];
|
|
52
|
+
for (let i = 0; i < content.length; i++) {
|
|
53
|
+
this.aggregateBlocks++;
|
|
54
|
+
const block = data(content, String(i));
|
|
55
|
+
const type = data(block, "type");
|
|
56
|
+
if (type === "image" && typeof data(block, "mimeType") === "string" && typeof data(block, "data") === "string") {
|
|
57
|
+
this.images++; this.visibleContent.push({ block, index: i });
|
|
58
|
+
} else if (type === "text" && typeof data(block, "text") === "string") {
|
|
59
|
+
if (data(block, "text").length) this.visibleContent.push({ block, index: i });
|
|
60
|
+
} else { this.supported = false; return true; }
|
|
61
|
+
}
|
|
62
|
+
for (let i = 0; i < this.calls.length; i++) {
|
|
63
|
+
this.aggregateEntries++;
|
|
64
|
+
const call = data(this.calls, String(i)), status = data(call, "status"), cost = data(call, "cost"), duration = data(call, "durationMs");
|
|
65
|
+
if (typeof data(call, "name") !== "string" || typeof data(call, "args") !== "string" || !["running", "ok", "error", "cancelled"].includes(status) ||
|
|
66
|
+
cost !== undefined && (typeof cost !== "number" || !Number.isFinite(cost)) || duration !== undefined && (typeof duration !== "number" || !Number.isFinite(duration)) ||
|
|
67
|
+
data(call, "error") !== undefined && typeof data(call, "error") !== "string") { this.supported = false; return true; }
|
|
68
|
+
if (status === "error") this.errors++;
|
|
69
|
+
if (status === "cancelled") this.cancelled++;
|
|
70
|
+
if (status === "running") this.unresolved++;
|
|
71
|
+
if (cost) { this.priced++; this.totalCost += cost; }
|
|
72
|
+
}
|
|
73
|
+
this.intent = codeIntent(args, this.calls);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
private *text(text: string, width: number, theme: any, token?: string, code = false): Generator<string> {
|
|
77
|
+
// A long line, including combining characters, never creates an unlimited formatter call.
|
|
78
|
+
for (let offset = 0; offset < text.length;) {
|
|
79
|
+
let end = Math.min(text.length, offset + 1024);
|
|
80
|
+
if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1])) end--;
|
|
81
|
+
const sample = text.slice(offset, end), newline = sample.lastIndexOf("\n");
|
|
82
|
+
if (newline >= 0 && end < text.length) end = offset + newline + 1;
|
|
83
|
+
const chunk = text.slice(offset, end);
|
|
84
|
+
this.sourceCharacters += chunk.length;
|
|
85
|
+
// The separator newline belongs to the source but not a second artificial blank row.
|
|
86
|
+
const source = chunk.endsWith("\n") ? chunk.slice(0, -1) : chunk;
|
|
87
|
+
for (const row of (source.length ? richTextRows(source, width, code ? { format: "code", language: "javascript" } : {}) : [""])) yield token && theme ? theme.fg(token, row) : row;
|
|
88
|
+
offset = end;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
*rows(width: number, theme: any, isError: boolean, hasDuration = false): Generator<string> {
|
|
92
|
+
const fg = (token: string, text: string) => theme ? theme.fg(token, text) : text;
|
|
93
|
+
yield* this.text(this.code, width, theme, undefined, true);
|
|
94
|
+
if (this.calls.length) yield "";
|
|
95
|
+
for (let i = 0; i < this.calls.length; i++) {
|
|
96
|
+
this.paintedCalls++;
|
|
97
|
+
const call = this.calls[i];
|
|
98
|
+
const status = { running: ["warning", "…"], ok: ["success", "✓"], error: ["error", "✗"], cancelled: ["muted", "⊘"] }[call.status] as string[];
|
|
99
|
+
const duration = call.durationMs !== undefined ? fg("dim", codeDuration(call.durationMs)) : "";
|
|
100
|
+
const cost = call.cost ? fg("dim", codeCost(call.cost)) : "";
|
|
101
|
+
if (call.name.length + call.args.length <= 512 && !/[\r\n]/.test(call.name + call.args)) {
|
|
102
|
+
const safe = (text: string) => [...richTextRows(text, 8192)].join("");
|
|
103
|
+
this.sourceCharacters += call.name.length + call.args.length;
|
|
104
|
+
const line = `${fg(status[0], status[1])} ${fg("toolTitle", safe(call.name))}${call.args ? ` ${fg("muted", safe(call.args))}` : ""}${duration ? ` ${duration}` : ""}${cost ? ` ${cost}` : ""}`;
|
|
105
|
+
// Already-sanitized native ANSI must not pass through the raw text sanitizer again.
|
|
106
|
+
yield* wrapTextWithAnsi(line, width);
|
|
107
|
+
} else {
|
|
108
|
+
yield fg(status[0], status[1]);
|
|
109
|
+
yield* this.text(call.name, width, theme, "toolTitle");
|
|
110
|
+
if (call.args) yield* this.text(call.args, width, theme, "muted");
|
|
111
|
+
if (duration || cost) yield `${duration} ${cost}`.trim();
|
|
112
|
+
}
|
|
113
|
+
if (call.error) for (const row of this.text(call.error, Math.max(1, width - 4), theme, "error")) yield " ".repeat(Math.min(4, Math.max(0, width - 1))) + row;
|
|
114
|
+
}
|
|
115
|
+
if (this.priced > 1) yield fg("muted", `Model calls: ${codeCost(this.totalCost)}`);
|
|
116
|
+
for (const { block, index } of this.visibleContent) {
|
|
117
|
+
// The heading counts images and the image adapter displays them or their
|
|
118
|
+
// fallback. Do not repeat a placeholder for each image in the text pane.
|
|
119
|
+
if (block.type === "image") continue;
|
|
120
|
+
const text = block.text;
|
|
121
|
+
if (hasDuration && index === 0 && text.length < 160 && scriptHeader.test(text)) continue;
|
|
122
|
+
if (text) { yield ""; yield* this.text(text, width, theme, isError ? "error" : "toolOutput"); }
|
|
123
|
+
}
|
|
124
|
+
if (this.details && typeof this.details === "object") for (const key in this.details) if (key !== "calls" && Object.prototype.hasOwnProperty.call(this.details, key)) {
|
|
125
|
+
yield* this.text(key, width, theme, "muted"); yield fg("muted", ":");
|
|
126
|
+
const value = data(this.details, key);
|
|
127
|
+
if (value === missing) { yield fg("warning", "[Recorded accessor; native display required]"); continue; }
|
|
128
|
+
for (const text of metadataValues(value)) yield* this.text(text, width, theme, "muted");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { matchesKey, truncateToWidth, visibleWidth, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
|
|
2
|
+
import { activityHeading, activityRow, cardContentWidth } from "./display-card.ts";
|
|
3
|
+
import { CodeContent } from "./modern-code-content.ts";
|
|
4
|
+
|
|
5
|
+
/** Native-style codemode with lazy bounded text/call formatting. Native-off stays stock. */
|
|
6
|
+
export class CodePane {
|
|
7
|
+
open = false; focused = false; offset = 0;
|
|
8
|
+
heading = "codemode · Preparing";
|
|
9
|
+
title = "codemode · Preparing"; theme?: any; tone = "syntaxVariable";
|
|
10
|
+
content = new CodeContent();
|
|
11
|
+
private rows: string[] = []; private iterator?: Iterator<string>; private done = false; private width = 0;
|
|
12
|
+
private lastWidth = 0; private lastHeight = 0;
|
|
13
|
+
private startedAt?: number; private endedAt?: number; private interval?: ReturnType<typeof setInterval>;
|
|
14
|
+
private themeKey = "";
|
|
15
|
+
private partial = false; private isError = false; private durationMs?: number;
|
|
16
|
+
paintedRows = 0;
|
|
17
|
+
constructor(private height: () => number) {}
|
|
18
|
+
get clock() { return { startedAt: this.startedAt, endedAt: this.endedAt }; }
|
|
19
|
+
adoptClock(clock: { startedAt?: number; endedAt?: number }) { this.startedAt ??= clock.startedAt; this.endedAt ??= clock.endedAt; }
|
|
20
|
+
suspend() { if (this.interval !== undefined) clearInterval(this.interval); this.interval = undefined; }
|
|
21
|
+
dispose() { this.suspend(); this.rows = []; this.iterator = undefined; }
|
|
22
|
+
collapse() { this.open = false; this.focused = false; this.offset = 0; this.reset(); }
|
|
23
|
+
private reset() { this.rows = []; this.iterator = undefined; this.done = false; this.width = 0; }
|
|
24
|
+
setTheme(theme: any) {
|
|
25
|
+
const tokens = ["text", "toolTitle", "toolOutput", "mdCodeBlock", "muted", "dim", "warning", "error", "success", "syntaxKeyword", "syntaxString", "syntaxComment", "syntaxNumber", "syntaxFunction", "syntaxOperator", "syntaxPunctuation", "syntaxType", "syntaxVariable", "toolDiffAdded", "toolDiffRemoved"];
|
|
26
|
+
const key = tokens.map(token => theme?.fg(token, "x") ?? "x").join("") + (theme?.bg("selectedBg", "x") ?? "x") + (theme?.bold("x") ?? "x");
|
|
27
|
+
if (key !== this.themeKey) { this.themeKey = key; this.reset(); }
|
|
28
|
+
this.theme = theme;
|
|
29
|
+
}
|
|
30
|
+
update(args: any, result: any, revision: number, context: any) {
|
|
31
|
+
if (this.content.update(args, result, revision)) this.reset();
|
|
32
|
+
if (context.executionStarted) this.startedAt ??= Date.now();
|
|
33
|
+
if (this.durationMs !== context.durationMs || this.isError !== context.isError) this.reset();
|
|
34
|
+
this.partial = context.isPartial; this.isError = context.isError; this.durationMs = context.durationMs;
|
|
35
|
+
if (result && (!this.partial || this.isError)) { this.endedAt ??= Date.now(); this.suspend(); }
|
|
36
|
+
else if (result && this.partial && this.startedAt !== undefined && !this.interval) this.interval = setInterval(() => context.invalidate(), 1000);
|
|
37
|
+
return this.content.supported;
|
|
38
|
+
}
|
|
39
|
+
handle(data: string): boolean {
|
|
40
|
+
if (matchesKey(data, "enter")) { this.open = !this.open; this.offset = 0; return true; }
|
|
41
|
+
if (matchesKey(data, "home")) { this.open = true; this.offset = 0; return true; }
|
|
42
|
+
if (["up", "down", "pageUp", "pageDown"].some(key => matchesKey(data, key as any))) {
|
|
43
|
+
const down = matchesKey(data, "down") || matchesKey(data, "pageDown");
|
|
44
|
+
const distance = matchesKey(data, "pageUp") || matchesKey(data, "pageDown") ? Math.max(1, this.height() - 2) : 1;
|
|
45
|
+
this.open = true; this.offset = Math.max(0, this.offset + (down ? distance : -distance)); return true;
|
|
46
|
+
}
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
render(width: number): string[] {
|
|
50
|
+
this.lastWidth = width;
|
|
51
|
+
const contentWidth = cardContentWidth(width);
|
|
52
|
+
const title = `${this.open ? "▾" : "▸"} ${this.title}${this.focused ? " · focused" : ""}`;
|
|
53
|
+
// Keep category identity separate from secondary counts/timing. Failures override both.
|
|
54
|
+
const label = `${this.open ? "▾" : "▸"} ${this.heading}`;
|
|
55
|
+
const metadata = title.slice(label.length);
|
|
56
|
+
const styled = this.theme
|
|
57
|
+
? activityHeading(label, this.theme, this.tone === "error" ? "error" : "syntaxVariable") +
|
|
58
|
+
metadata.split(/( · \d+ nested (?:errors?|cancelled|unresolved))/).map(part =>
|
|
59
|
+
this.theme.fg(this.tone === "error" ? "error" : this.tone === "warning" && /^ · \d+ nested (?:errors?|cancelled|unresolved)$/.test(part) ? "warning" : "muted", part)).join("")
|
|
60
|
+
: title;
|
|
61
|
+
const header = activityRow(styled, width, this.theme, this.focused);
|
|
62
|
+
if (!this.open) { this.lastHeight = 1; return [header]; }
|
|
63
|
+
const indent = contentWidth >= 4 ? " " : "";
|
|
64
|
+
const nativeWidth = Math.max(1, contentWidth - indent.length);
|
|
65
|
+
if (this.width !== nativeWidth) { this.reset(); this.width = nativeWidth; this.offset = 0; }
|
|
66
|
+
this.iterator ??= this.content.rows(nativeWidth, this.theme, this.isError, this.durationMs !== undefined || this.startedAt !== undefined);
|
|
67
|
+
const bodyHeight = Math.max(1, Math.min(20, this.height()) - 2);
|
|
68
|
+
this.offset = Math.min(this.offset, this.rows.length);
|
|
69
|
+
while (!this.done && this.rows.length <= this.offset + bodyHeight) {
|
|
70
|
+
const row = this.iterator.next();
|
|
71
|
+
if (row.done) this.done = true;
|
|
72
|
+
else { this.rows.push(truncateToWidth(row.value, nativeWidth, "")); this.paintedRows++; }
|
|
73
|
+
}
|
|
74
|
+
if (this.done) this.offset = Math.min(this.offset, Math.max(0, this.rows.length - bodyHeight));
|
|
75
|
+
const body = this.rows.slice(this.offset, this.offset + bodyHeight).map(row => activityRow(indent + row, width, this.theme));
|
|
76
|
+
const more = !this.done || this.offset + bodyHeight < this.rows.length;
|
|
77
|
+
const duration = (ms: number) => {
|
|
78
|
+
const seconds = ms / 1000;
|
|
79
|
+
if (seconds < 60) return `${seconds.toFixed(1)}s`;
|
|
80
|
+
const total = Math.floor(seconds), minutes = Math.floor(total / 60), remainder = total % 60;
|
|
81
|
+
return minutes < 60 ? `${minutes}m ${remainder}s` : `${Math.floor(minutes / 60)}h ${minutes % 60}m ${remainder}s`;
|
|
82
|
+
};
|
|
83
|
+
let timer = "";
|
|
84
|
+
// Avoid repeating the heading's duration, but retain it below a clipped
|
|
85
|
+
// heading so a narrow terminal does not lose the timing information.
|
|
86
|
+
if (!this.partial && this.durationMs !== undefined && visibleWidth(title) > contentWidth) timer = `Took ${duration(this.durationMs)}`;
|
|
87
|
+
else if (this.durationMs === undefined && this.startedAt !== undefined) timer = `${this.partial ? "Elapsed" : "Took"} ${duration((this.endedAt ?? Date.now()) - this.startedAt)}`;
|
|
88
|
+
const footer = [timer, this.focused ? `Enter collapse · ↑/↓ scroll · Home start · Esc release${more ? " · more ↓" : ""}` : more ? "more ↓" : ""].filter(Boolean).join(" · ");
|
|
89
|
+
const visible = [header, ...body, ...(footer ? [activityRow(this.theme ? this.theme.fg("muted", truncateToWidth(footer, contentWidth)) : truncateToWidth(footer, contentWidth), width, this.theme)] : [])];
|
|
90
|
+
this.lastHeight = visible.length; return visible;
|
|
91
|
+
}
|
|
92
|
+
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
93
|
+
if (event.x < 0 || event.x >= this.lastWidth || event.y < 0 || event.y >= this.lastHeight) return undefined;
|
|
94
|
+
if (event.type === "wheel" && this.open && Number.isFinite(event.wheelDelta) && event.wheelDelta) { this.offset = Math.max(0, this.offset + Math.max(-20, Math.min(20, Math.trunc(event.wheelDelta)))); return { handled: true }; }
|
|
95
|
+
if (event.type !== "click" || event.button !== "left") return undefined;
|
|
96
|
+
if (event.shift || event.alt || event.ctrl) return { handled: true, render: false };
|
|
97
|
+
if (event.y === 0) { this.open = !this.open; this.offset = 0; return { handled: true }; }
|
|
98
|
+
return { handled: true, render: false };
|
|
99
|
+
}
|
|
100
|
+
invalidate() { this.reset(); }
|
|
101
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { VERSION, keyHint, type ToolRenderers } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Box, Container, Text, stripTerminalSequences, type Component } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
type Context = Parameters<NonNullable<ToolRenderers["renderCall"]>>[2];
|
|
5
|
+
/** Native private-state knowledge is confined here. Unsupported Pi versions keep stock rendering. */
|
|
6
|
+
export const nativeToolsSupported = VERSION === "1.3.0";
|
|
7
|
+
export const nativeToolContextSupported = (context: Context) => !!context && typeof context.toolCallId === "string" && typeof context.invalidate === "function" && !!context.state && typeof context.state === "object" && typeof context.cwd === "string" && typeof context.expanded === "boolean" && typeof context.executionStarted === "boolean" && typeof context.isPartial === "boolean";
|
|
8
|
+
export function nativeTextFallback(result: any, theme?: any, options = { expanded: true }): Text {
|
|
9
|
+
const text = (Array.isArray(result?.content) ? result.content : []).filter((block: any) => block?.type === "text").map((block: any) => String(block.text ?? "")).join("\n");
|
|
10
|
+
const output = stripTerminalSequences(text).replace(/\r/g, "");
|
|
11
|
+
if (!theme) return new Text(output, 0, 0);
|
|
12
|
+
const lines = output.split("\n");
|
|
13
|
+
const visible = options.expanded ? lines : lines.slice(0, 10);
|
|
14
|
+
let display = visible.map(line => theme.fg("toolOutput", line)).join("\n");
|
|
15
|
+
const remaining = lines.length - visible.length;
|
|
16
|
+
if (remaining > 0) display += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
|
|
17
|
+
return new Text(display, 0, 0);
|
|
18
|
+
}
|
|
19
|
+
function callFallback(name: string, args: any, theme: any, expanded: boolean) {
|
|
20
|
+
const title = theme.fg("toolTitle", theme.bold(name));
|
|
21
|
+
if (args == null) return new Text(title, 0, 0);
|
|
22
|
+
const entries = typeof args === "object" && !Array.isArray(args) ? Object.entries(args) : [["args", args]];
|
|
23
|
+
if (!entries.length) return new Text(title, 0, 0);
|
|
24
|
+
if (expanded) {
|
|
25
|
+
const lines = entries.map(([key, value]) => ` ${key}: ${(typeof value === "string" ? value : JSON.stringify(value) ?? String(value)).replace(/\t/g, " ").replace(/\r/g, "").split("\n").join("\n ")}`);
|
|
26
|
+
return new Text(`${title}\n${theme.fg("muted", lines.join("\n"))}`, 0, 0);
|
|
27
|
+
}
|
|
28
|
+
const pairs = entries.map(([key, value]) => `${key}=${JSON.stringify(value) ?? String(value)}`).join(" ");
|
|
29
|
+
return new Text(`${title} ${theme.fg("muted", pairs.length > 100 ? `${pairs.slice(0, 97)}...` : pairs)}`, 0, 0);
|
|
30
|
+
}
|
|
31
|
+
export class NativeToolOwner {
|
|
32
|
+
private state: Record<string, any> = {};
|
|
33
|
+
private call?: Component;
|
|
34
|
+
private result?: Component;
|
|
35
|
+
private error?: boolean;
|
|
36
|
+
private shell = new Box(1, 1);
|
|
37
|
+
private empty = new Container();
|
|
38
|
+
constructor(private name: string, private stock?: ToolRenderers) {}
|
|
39
|
+
context(context: Context, slot: "call" | "result") {
|
|
40
|
+
return { ...context, state: this.state, lastComponent: slot === "call" ? this.call : this.result };
|
|
41
|
+
}
|
|
42
|
+
private nativeShell(theme: any, context: Context) {
|
|
43
|
+
const background = context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg";
|
|
44
|
+
this.shell.setBgFn(text => theme.bg(background, text));
|
|
45
|
+
this.shell.setPaddingX(context.outputPad);
|
|
46
|
+
this.shell.clear();
|
|
47
|
+
if (this.call) this.shell.addChild(this.call);
|
|
48
|
+
if (this.result) this.shell.addChild(this.result);
|
|
49
|
+
return this.shell;
|
|
50
|
+
}
|
|
51
|
+
renderCall(args: any, theme: any, context: Context) {
|
|
52
|
+
this.call = this.stock?.renderCall?.(args, theme, this.context(context, "call")) ?? callFallback(this.name, args, theme, context.expanded);
|
|
53
|
+
return this.stock?.renderShell === "self" ? this.call : this.nativeShell(theme, context);
|
|
54
|
+
}
|
|
55
|
+
renderResult(result: any, options: any, theme: any, context: Context) {
|
|
56
|
+
// Some stock result slots switch component class on error; don't reuse across that transition.
|
|
57
|
+
if (this.error !== context.isError) this.result = undefined;
|
|
58
|
+
this.error = context.isError;
|
|
59
|
+
this.result = this.stock?.renderResult?.(result, options, theme, this.context(context, "result")) ?? nativeTextFallback(result, theme, options);
|
|
60
|
+
if (this.stock?.renderShell === "self") return this.result;
|
|
61
|
+
// Both native slots share one public Box. The wrapper's call slot owns its position,
|
|
62
|
+
// and its result slot updates that Box without adding a second shell or padding.
|
|
63
|
+
this.nativeShell(theme, context);
|
|
64
|
+
return this.empty;
|
|
65
|
+
}
|
|
66
|
+
renderCurrent(width: number) { return (this.stock?.renderShell === "self" ? this.call : this.shell)?.render(width) ?? []; }
|
|
67
|
+
get clock() { return { startedAt: this.state.startedAt as number | undefined, endedAt: this.state.endedAt as number | undefined }; }
|
|
68
|
+
adoptClock(clock: { startedAt?: number; endedAt?: number }) { this.state.startedAt ??= clock.startedAt; this.state.endedAt ??= clock.endedAt; }
|
|
69
|
+
suspend() {
|
|
70
|
+
// Pi 1.3.0 render-utils ToolTimerState. Only clear a handle owned by this native state.
|
|
71
|
+
// Never inspect or mutate the host row's rendererState or extension execution timers.
|
|
72
|
+
if (nativeToolsSupported && ["bash", "powershell", "codemode"].includes(this.name) && this.state.interval !== undefined) {
|
|
73
|
+
const interval = this.state.interval;
|
|
74
|
+
if (typeof interval === "number" || (interval && typeof interval === "object" && typeof interval.hasRef === "function")) clearInterval(interval);
|
|
75
|
+
this.state.interval = undefined;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
dispose() { this.suspend(); this.call = undefined; this.result = undefined; this.shell.clear(); this.state = {}; }
|
|
79
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { UserMessageComponent, VERSION } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Markdown } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
export function invalidateModernPrompt(component: any) {
|
|
5
|
+
for (const child of Array.isArray(component?.children) ? component.children : []) if (child instanceof Markdown) child.invalidate();
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** The transformer is public. This isolated Pi 1.3.0 seam supplies per-card
|
|
9
|
+
* identity, cache invalidation, and mouse expansion, which the public hook lacks. */
|
|
10
|
+
export function installModernPromptAdapter(hooks: {
|
|
11
|
+
render(component: any, markdown: string, original: () => string[]): string[];
|
|
12
|
+
mouse(component: any, event: any): any;
|
|
13
|
+
fallback?(component: any): void;
|
|
14
|
+
}, version = VERSION): (() => void) | undefined {
|
|
15
|
+
const proto = UserMessageComponent.prototype as any;
|
|
16
|
+
if (version !== "1.3.0" || typeof proto.render !== "function" || typeof proto.rebuild !== "function") return;
|
|
17
|
+
const owner = Symbol.for("compact-renderer:prompt-adapter:v1");
|
|
18
|
+
proto[owner]?.();
|
|
19
|
+
const render = proto.render, mouse = proto.handleMouse;
|
|
20
|
+
const mouseDescriptor = Object.getOwnPropertyDescriptor(proto, "handleMouse");
|
|
21
|
+
let disposed = false;
|
|
22
|
+
const compatible = (c: any) => typeof c.text === "string" && Array.isArray(c.children) && c.children.length === 1 && c.children[0] instanceof Markdown && typeof c.children[0].invalidate === "function";
|
|
23
|
+
const renderWrapper = function(this: any, width: number) {
|
|
24
|
+
if (!disposed && compatible(this)) return hooks.render(this, this.text, () => render.call(this, width));
|
|
25
|
+
// A previously collapsed instance can become incompatible after a host update.
|
|
26
|
+
// Clear only known native Markdown caches, then let the transformer return raw.
|
|
27
|
+
invalidateModernPrompt(this);
|
|
28
|
+
hooks.fallback?.(this);
|
|
29
|
+
return render.call(this, width);
|
|
30
|
+
};
|
|
31
|
+
const mouseWrapper = function(this: any, event: any) { const handled = !disposed && compatible(this) && hooks.mouse(this, event); return handled || mouse?.call(this, event); };
|
|
32
|
+
const dispose = () => {
|
|
33
|
+
if (disposed) return;
|
|
34
|
+
disposed = true;
|
|
35
|
+
if (proto.render === renderWrapper) proto.render = render;
|
|
36
|
+
if (proto.handleMouse === mouseWrapper) { if (mouseDescriptor) Object.defineProperty(proto, "handleMouse", mouseDescriptor); else delete proto.handleMouse; }
|
|
37
|
+
if (proto[owner] === dispose) delete proto[owner];
|
|
38
|
+
};
|
|
39
|
+
proto.render = renderWrapper; proto.handleMouse = mouseWrapper; proto[owner] = dispose;
|
|
40
|
+
return dispose;
|
|
41
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import type { DisplayMode } from './display-mode.ts';
|
|
2
|
+
import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Markdown, matchesKey, stripTerminalSequences, truncateToWidth } from "@earendil-works/pi-tui";
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { installModernPromptAdapter, invalidateModernPrompt } from "./modern-prompts-adapter.ts";
|
|
6
|
+
|
|
7
|
+
type Template = { name: string; parts: string[]; description?: string };
|
|
8
|
+
type PromptCard = { component: any; original: string; name?: string; open: boolean; eligible: boolean; revision: number; controlStart?: number; controlEnd?: number };
|
|
9
|
+
const promptLabel = (card: PromptCard) => card.name ? `/${card.name}` : "Submitted prompt";
|
|
10
|
+
const blankPromptRow = (row: string) => !stripTerminalSequences(row).trim();
|
|
11
|
+
function promptExcerpts(rows: string[]): { opening: string[]; ending: string[] } {
|
|
12
|
+
let first = 0, last = rows.length;
|
|
13
|
+
while (first < last && blankPromptRow(rows[first])) first++;
|
|
14
|
+
while (last > first && blankPromptRow(rows[last - 1])) last--;
|
|
15
|
+
let openingEnd = first;
|
|
16
|
+
while (openingEnd < Math.min(first + 3, last) && !blankPromptRow(rows[openingEnd])) openingEnd++;
|
|
17
|
+
let paragraphStart = last;
|
|
18
|
+
while (paragraphStart > openingEnd && !blankPromptRow(rows[paragraphStart - 1])) paragraphStart--;
|
|
19
|
+
const endingStart = Math.max(openingEnd, paragraphStart, last - 2);
|
|
20
|
+
return { opening: rows.slice(first, openingEnd), ending: rows.slice(endingStart, last) };
|
|
21
|
+
}
|
|
22
|
+
const placeholders = /\$\{(?:\d+|ARGUMENTS|@):-[^}]*\}|\$\{@:\d+(?::\d+)?\}|\$(?:ARGUMENTS|@|\d+)/g;
|
|
23
|
+
export function modernPromptTemplates(commands: readonly any[]): Template[] {
|
|
24
|
+
const templates: Template[] = [];
|
|
25
|
+
for (const command of commands) {
|
|
26
|
+
if (command.source !== "prompt" || commands.some(c => c.source === "extension" && c.name === command.name)) continue;
|
|
27
|
+
try {
|
|
28
|
+
const raw = readFileSync(command.sourceInfo.path, "utf8");
|
|
29
|
+
if (raw.length > 100000) continue;
|
|
30
|
+
const body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, "").trim();
|
|
31
|
+
const parts = body.split(placeholders);
|
|
32
|
+
if (parts[0].length >= 40 && parts.length <= 33) templates.push({ name: command.name, parts, description: typeof command.description === "string" ? command.description : undefined });
|
|
33
|
+
} catch { /* Missing templates leave their original text visible. */ }
|
|
34
|
+
}
|
|
35
|
+
return templates;
|
|
36
|
+
}
|
|
37
|
+
export function matchingModernPrompt(text: string, templates: readonly Template[]): string | undefined {
|
|
38
|
+
const value = text.trim();
|
|
39
|
+
if (value.length > 200000) return;
|
|
40
|
+
for (const { name, parts } of templates) {
|
|
41
|
+
if (parts.length === 1) { if (value === parts[0]) return name; continue; }
|
|
42
|
+
const first = parts[0].trimStart(), last = parts.at(-1)!.trimEnd();
|
|
43
|
+
if (!value.startsWith(first) || last && !value.endsWith(last)) continue;
|
|
44
|
+
let position = first.length, matches = true;
|
|
45
|
+
for (const part of parts.slice(1, -1)) {
|
|
46
|
+
const next = value.indexOf(part, position);
|
|
47
|
+
if (next < 0) { matches = false; break; }
|
|
48
|
+
position = next + part.length;
|
|
49
|
+
}
|
|
50
|
+
if (matches && (!last || position <= value.length - last.length)) return name;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Bounded display text from existing metadata or the recorded expansion, never a model summary. */
|
|
55
|
+
export function modernPromptSummary(original: string, description?: string): string {
|
|
56
|
+
const sample = (description?.trim() || original).slice(0, 1024).replace(/[\uD800-\uDBFF]$/, "");
|
|
57
|
+
const text = sample.replace(/^[ \t]*#{1,6}[ \t]+/gm, "").replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim();
|
|
58
|
+
const sentence = description?.trim() ? text : text.match(/^.*?[.!?。!?](?:\s|$)/u)?.[0]?.trim() || text;
|
|
59
|
+
return truncateToWidth(sentence, 110, "…").replace(/\x1b\[[0-9;]*m/g, "");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Display only: the public transformer sees the original Markdown. Its output
|
|
63
|
+
* does not replace messages, prompt expansion, transcript entries, or model input. */
|
|
64
|
+
export function registerModernPrompts(pi: ExtensionAPI, mode: DisplayMode): () => void {
|
|
65
|
+
const owner = Symbol.for("compact-renderer:prompt-registration:v1"), shared = globalThis as any;
|
|
66
|
+
shared[owner]?.();
|
|
67
|
+
let templates: Template[] = [], cards = new Map<any, PromptCard>();
|
|
68
|
+
let rendering: PromptCard | undefined, selected: PromptCard | undefined;
|
|
69
|
+
let focused = false, active = false, disposed = false, revision = 0, redraw: (() => void) | undefined, input: (() => void) | undefined, theme: any;
|
|
70
|
+
const invalidate = () => { for (const card of cards.values()) invalidateModernPrompt(card.component); };
|
|
71
|
+
const release = () => { if (focused) { focused = false; revision++; } };
|
|
72
|
+
const select = (card: PromptCard, open = false) => {
|
|
73
|
+
if (!card.eligible) return;
|
|
74
|
+
selected = card; focused = true; if (open) card.open = true;
|
|
75
|
+
revision++; redraw?.();
|
|
76
|
+
pi.events.emit("compact-renderer:focus:v1", { owner: "prompts", label: `Prompt ${promptLabel(card)}`, target: (component: any) => component === card.component });
|
|
77
|
+
};
|
|
78
|
+
const adapter = installModernPromptAdapter({
|
|
79
|
+
render(component, markdown, original) {
|
|
80
|
+
if (disposed || !active || !mode.isEnabled()) return original();
|
|
81
|
+
const name = matchingModernPrompt(markdown, templates);
|
|
82
|
+
let card = cards.get(component);
|
|
83
|
+
if (!name) {
|
|
84
|
+
// Count the native rendered body, excluding its top/bottom padding. The
|
|
85
|
+
// native Markdown cache handles width changes and retains all formatting.
|
|
86
|
+
const lines = original(), native = component.children[0];
|
|
87
|
+
const padding = native.paddingY;
|
|
88
|
+
if (padding !== 1 || !Number.isFinite(native.cachedWidth)) {
|
|
89
|
+
if (card) { cards.delete(component); if (selected === card) { selected = undefined; release(); } }
|
|
90
|
+
return lines;
|
|
91
|
+
}
|
|
92
|
+
if (card && card.original !== markdown) { card.original = markdown; card.open = false; }
|
|
93
|
+
if (lines.length - padding * 2 <= 8) {
|
|
94
|
+
// Width can temporarily make a long prompt short. Retain its chosen
|
|
95
|
+
// expansion state, but remove controls and inspection while it fits.
|
|
96
|
+
if (card) {
|
|
97
|
+
card.eligible = false;
|
|
98
|
+
if (selected === card) { selected = undefined; release(); pi.events.emit("compact-renderer:inspection-ended:v1", {}); }
|
|
99
|
+
}
|
|
100
|
+
return lines;
|
|
101
|
+
}
|
|
102
|
+
if (!card || card.name) { card = { component, original: markdown, open: false, eligible: true, revision: -1 }; cards.set(component, card); }
|
|
103
|
+
card.eligible = true;
|
|
104
|
+
const controlText = `${card.open ? "▴ Show less" : "⋯ Show more"}${focused && selected === card ? " · Enter toggles · Esc returns" : ""}`;
|
|
105
|
+
const control = new Markdown(controlText, native.paddingX, 0, native.theme, {
|
|
106
|
+
...native.defaultTextStyle, bold: false,
|
|
107
|
+
color: (text: string) => theme?.fg("muted", text) ?? native.defaultTextStyle?.color?.(text) ?? text,
|
|
108
|
+
});
|
|
109
|
+
const controlLines = control.render(native.cachedWidth);
|
|
110
|
+
const blank = " ".repeat(native.cachedWidth), gap = native.defaultTextStyle?.bgColor?.(blank) ?? blank;
|
|
111
|
+
const excerpts = card.open ? undefined : promptExcerpts(lines.slice(padding, -padding));
|
|
112
|
+
const before = card.open ? [...lines.slice(0, -padding), gap] : [...lines.slice(0, padding), ...excerpts!.opening, gap];
|
|
113
|
+
card.controlStart = before.length;
|
|
114
|
+
card.controlEnd = before.length + controlLines.length;
|
|
115
|
+
// Keep the native prompt-zone markers on the first/last padding rows.
|
|
116
|
+
// Pi 1.3.0 supplies one padding row at each end of user Markdown.
|
|
117
|
+
return [...before, ...controlLines, ...(excerpts ? [gap, ...excerpts.ending] : []), ...lines.slice(-padding)];
|
|
118
|
+
}
|
|
119
|
+
if (!card) { card = { component, original: markdown, name, open: false, eligible: true, revision: -1 }; cards.set(component, card); }
|
|
120
|
+
card.eligible = true;
|
|
121
|
+
if (card.original !== markdown) { card.original = markdown; card.open = false; card.revision = -1; }
|
|
122
|
+
if (card.revision !== revision || card.name !== name) { invalidateModernPrompt(component); card.revision = revision; card.name = name; }
|
|
123
|
+
const previous = rendering;
|
|
124
|
+
rendering = card;
|
|
125
|
+
try { return original(); } finally { rendering = previous; }
|
|
126
|
+
},
|
|
127
|
+
fallback(component) { cards.delete(component); if (selected?.component === component) { selected = undefined; release(); } },
|
|
128
|
+
mouse(component, event) {
|
|
129
|
+
const card = cards.get(component);
|
|
130
|
+
const onControl = card?.name ? event.y === 1 : card && event.y >= card.controlStart! && event.y < card.controlEnd!;
|
|
131
|
+
if (!disposed && active && mode.isEnabled() && card?.eligible && event.type === "click" && event.button === "left" && onControl) {
|
|
132
|
+
release(); pi.events.emit("compact-renderer:focus:v1", { owner: "editor" });
|
|
133
|
+
card.open = !card.open; revision++; return { handled: true, render: true };
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
// No usable inline adapter means no collapse. Unsupported hosts show originals.
|
|
138
|
+
pi.registerMarkdownTransformer((markdown, context) => {
|
|
139
|
+
if (disposed || !active || !adapter || !mode.isEnabled() || context.messageType !== "user" || !rendering || markdown !== rendering.original) return markdown;
|
|
140
|
+
const label = rendering.name!.replace(/[\\`*_\[\]<>\p{Cc}\p{Cf}]/gu, "");
|
|
141
|
+
const heading = `**${rendering.open ? "▾" : "▸"} prompt · /${label}**${focused && selected === rendering ? ` · Enter ${rendering.open ? "collapses" : "expands"} · Esc returns` : ""}`;
|
|
142
|
+
const summary = modernPromptSummary(markdown, templates.find(template => template.name === rendering.name)?.description);
|
|
143
|
+
return rendering.open ? `${heading}\n\n${markdown}` : `${heading} — ${summary}`;
|
|
144
|
+
});
|
|
145
|
+
const reset = (_event: unknown, ctx: any) => {
|
|
146
|
+
invalidate(); cards.clear(); rendering = undefined; selected = undefined; focused = false; revision++;
|
|
147
|
+
input?.(); input = undefined; redraw = undefined; active = false;
|
|
148
|
+
if (disposed) return;
|
|
149
|
+
templates = modernPromptTemplates(pi.getCommands());
|
|
150
|
+
if (ctx.mode !== "tui" || !adapter) return;
|
|
151
|
+
active = true;
|
|
152
|
+
const ui = ctx.ui;
|
|
153
|
+
theme = ui.theme;
|
|
154
|
+
redraw = typeof ui.setHiddenThinkingLabel === "function" ? () => ui.setHiddenThinkingLabel() : undefined;
|
|
155
|
+
input = ui.onTerminalInput?.((data: string) => {
|
|
156
|
+
if (!mode.isEnabled()) { release(); return; }
|
|
157
|
+
if (matchesKey(data, "alt+i")) {
|
|
158
|
+
const choices = [...cards.values()].filter(card => card.eligible);
|
|
159
|
+
if (!choices.length) return;
|
|
160
|
+
const index = focused ? choices.indexOf(selected!) : -1;
|
|
161
|
+
select(index < 0 ? choices.at(-1)! : choices[(index + choices.length - 1) % choices.length]);
|
|
162
|
+
// Focus appears in the same short label on the next render.
|
|
163
|
+
revision++; redraw?.(); return { consume: true };
|
|
164
|
+
}
|
|
165
|
+
if (!focused || !selected?.eligible || !cards.has(selected.component)) return;
|
|
166
|
+
if (matchesKey(data, "escape")) { release(); pi.events.emit("compact-renderer:inspection-ended:v1", {}); redraw?.(); return { consume: true }; }
|
|
167
|
+
if (matchesKey(data, "enter")) { selected.open = !selected.open; revision++; redraw?.(); return { consume: true }; }
|
|
168
|
+
release(); pi.events.emit("compact-renderer:inspection-ended:v1", {}); redraw?.();
|
|
169
|
+
});
|
|
170
|
+
redraw?.();
|
|
171
|
+
};
|
|
172
|
+
const subscriptions: (() => void)[] = [];
|
|
173
|
+
for (const event of ["session_start", "session_tree", "session_compact"] as const) subscriptions.push(pi.on(event, reset));
|
|
174
|
+
subscriptions.push(pi.events.on("compact-renderer:inspect:v1", (request: any) => {
|
|
175
|
+
if (disposed || !active || !mode.isEnabled()) return;
|
|
176
|
+
[...cards.values()].filter(card => card.eligible).forEach((card, index) => request?.add?.({ id: `prompt-${index}`, kind: "Prompt", label: `${promptLabel(card)} — ${modernPromptSummary(card.original, templates.find(template => template.name === card.name)?.description)}`, focus: () => { if (!disposed && active && mode.isEnabled() && cards.get(card.component) === card) select(card, true); } }));
|
|
177
|
+
}));
|
|
178
|
+
subscriptions.push(pi.on("ui_prompt_start", release));
|
|
179
|
+
subscriptions.push(pi.on("session_shutdown", () => { active = false; invalidate(); input?.(); input = undefined; redraw = undefined; cards.clear(); selected = undefined; rendering = undefined; release(); }));
|
|
180
|
+
subscriptions.push(pi.events.on("compact-renderer:focus:v1", (event: any) => { if (event?.owner !== "prompts") release(); }));
|
|
181
|
+
subscriptions.push(mode.onChange(() => { revision++; release(); invalidate(); redraw?.(); }));
|
|
182
|
+
const dispose = () => { if (disposed) return; disposed = true; active = false; for (const unsub of subscriptions) unsub?.(); input?.(); input = undefined; invalidate(); cards.clear(); adapter?.(); redraw?.(); redraw = undefined; release(); if (shared[owner] === dispose) delete shared[owner]; };
|
|
183
|
+
shared[owner] = dispose;
|
|
184
|
+
return dispose;
|
|
185
|
+
}
|