@notrico/pi-fold 0.0.0-stage → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +136 -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-inspection.mjs +9 -0
- package/scripts/preview-work-strip.mjs +101 -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 +66 -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 +103 -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 +258 -0
- package/src/modern-tool-content.ts +28 -0
- package/src/modern-tool-images.ts +63 -0
- package/src/modern-tool-pane.ts +219 -0
- package/src/modern-tools.ts +509 -0
- package/src/modern-workflows.ts +212 -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 +112 -0
- package/src/work-strip.ts +443 -0
- package/tests/action-intent.test.mjs +44 -0
- package/tests/codemode.test.mjs +388 -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-wheel.test.mjs +73 -0
- package/tests/inspection.test.mjs +50 -0
- package/tests/mixed-thinking.test.mjs +371 -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 +961 -0
- package/tests/modern-workflows.test.mjs +189 -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 +321 -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,68 @@
|
|
|
1
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
2
|
+
|
|
3
|
+
/** A raw recorded-text viewport. It only visits the rows requested so far.
|
|
4
|
+
* Strings stay unchanged; unsafe terminal controls get visible representations. */
|
|
5
|
+
export class RecordedTextPane {
|
|
6
|
+
open = false;
|
|
7
|
+
top = 0;
|
|
8
|
+
private width = 0;
|
|
9
|
+
private sources: readonly string[] = [];
|
|
10
|
+
private rows: string[] = [];
|
|
11
|
+
private source = 0;
|
|
12
|
+
private offset = 0;
|
|
13
|
+
private finished = false;
|
|
14
|
+
visitedCharacters = 0;
|
|
15
|
+
setSources(sources: readonly string[]) {
|
|
16
|
+
if (sources.length === this.sources.length && sources.every((s, i) => s === this.sources[i])) return;
|
|
17
|
+
this.sources = sources;
|
|
18
|
+
this.top = 0;
|
|
19
|
+
this.reset();
|
|
20
|
+
}
|
|
21
|
+
private reset() { this.rows = []; this.source = 0; this.offset = 0; this.finished = false; }
|
|
22
|
+
private nextRow(width: number): string | undefined {
|
|
23
|
+
if (this.finished) return;
|
|
24
|
+
if (this.source >= this.sources.length) { this.finished = true; return; }
|
|
25
|
+
const text = this.sources[this.source];
|
|
26
|
+
let row = "", cells = 0;
|
|
27
|
+
// Also bound invisible combining-character input, which has zero cell width.
|
|
28
|
+
let budget = Math.max(64, width * 8);
|
|
29
|
+
while (this.offset < text.length && budget-- > 0) {
|
|
30
|
+
const point = text.codePointAt(this.offset)!;
|
|
31
|
+
const char = String.fromCodePoint(point);
|
|
32
|
+
if (char === "\n") { this.offset++; this.visitedCharacters++; break; }
|
|
33
|
+
if (char === "\r" && text[this.offset + 1] === "\n") { this.offset += 2; this.visitedCharacters += 2; break; }
|
|
34
|
+
const safe = char === "\t" ? " " : /[\p{Cc}\p{Cf}]/u.test(char) ? `\\u${point.toString(16).padStart(4, "0")}` : char;
|
|
35
|
+
const length = visibleWidth(safe);
|
|
36
|
+
if (cells && cells + length > width) break;
|
|
37
|
+
row += length > width ? truncateToWidth(safe, width, "") : safe;
|
|
38
|
+
cells += Math.min(length, width);
|
|
39
|
+
this.offset += char.length;
|
|
40
|
+
this.visitedCharacters += char.length;
|
|
41
|
+
if (cells >= width) break;
|
|
42
|
+
}
|
|
43
|
+
if (this.offset >= text.length) { this.source++; this.offset = 0; }
|
|
44
|
+
return row;
|
|
45
|
+
}
|
|
46
|
+
render(width: number, height: number): string[] {
|
|
47
|
+
width = Math.max(1, Math.floor(width)); height = Math.max(1, Math.floor(height));
|
|
48
|
+
if (width !== this.width) { this.width = width; this.top = 0; this.reset(); }
|
|
49
|
+
const end = this.top + height;
|
|
50
|
+
while (!this.finished && this.rows.length <= end) {
|
|
51
|
+
const row = this.nextRow(width);
|
|
52
|
+
if (row !== undefined) this.rows.push(row);
|
|
53
|
+
}
|
|
54
|
+
this.top = Math.min(this.top, Math.max(0, this.rows.length - height));
|
|
55
|
+
return this.rows.slice(this.top, this.top + height);
|
|
56
|
+
}
|
|
57
|
+
move(direction: string, height: number) {
|
|
58
|
+
if (direction === "home") this.top = 0;
|
|
59
|
+
else if (direction === "up") this.top = Math.max(0, this.top - 1);
|
|
60
|
+
else if (direction === "down") this.top++;
|
|
61
|
+
else if (direction === "pageUp") this.top = Math.max(0, this.top - height);
|
|
62
|
+
else if (direction === "pageDown") this.top += height;
|
|
63
|
+
}
|
|
64
|
+
get more() { return !this.finished || this.top + this.heightHint < this.rows.length; }
|
|
65
|
+
private heightHint = 0;
|
|
66
|
+
view(width: number, height: number) { this.heightHint = height; return this.render(width, height); }
|
|
67
|
+
}
|
|
68
|
+
export const recordedPaneHeight = (rows = process.stdout.rows) => Math.max(1, Math.min(12, Math.floor((Number.isFinite(rows) && rows > 0 ? rows : 24) * .4)));
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { Markdown, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
2
|
+
import { getMarkdownTheme, highlightCode } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
|
|
4
|
+
export type TextFormat = { format?: "code" | "markdown"; language?: string };
|
|
5
|
+
const safeText = (text: string) => text.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]|\p{Cf}/gu, c => {
|
|
6
|
+
const code = c.codePointAt(0)!;
|
|
7
|
+
return code > 0xffff ? `\\u{${code.toString(16)}}` : `\\u${code.toString(16).padStart(4, "0")}`;
|
|
8
|
+
}).replace(/\t/g, " ");
|
|
9
|
+
|
|
10
|
+
/** Format only the next bounded source block. Fenced code state survives blocks;
|
|
11
|
+
* native syntax/Markdown formatting never receives the full unbounded payload. */
|
|
12
|
+
export function* richTextRows(text: string, width: number, options: TextFormat = {}): Generator<string> {
|
|
13
|
+
let offset = 0, fence = "", language = "", heredoc = "", heredocLanguage = "";
|
|
14
|
+
while (offset < text.length) {
|
|
15
|
+
let end = Math.min(text.length, offset + 2048);
|
|
16
|
+
const sample = text.slice(offset, end);
|
|
17
|
+
const newline = sample.indexOf("\n");
|
|
18
|
+
// Markdown is read one source line at a time so fences remain balanced across viewports.
|
|
19
|
+
if ((options.format === "markdown" || options.language === "bash") && newline >= 0) end = offset + newline;
|
|
20
|
+
else if (options.format !== "markdown" && end < text.length) {
|
|
21
|
+
const last = sample.lastIndexOf("\n");
|
|
22
|
+
if (last >= 0) end = offset + last;
|
|
23
|
+
}
|
|
24
|
+
if (end < text.length && end > offset && /[\uD800-\uDBFF]/.test(text[end - 1])) end--;
|
|
25
|
+
const source = safeText(text.slice(offset, end));
|
|
26
|
+
const marker = options.format === "markdown" && source.match(/^ {0,3}(`{3,}|~{3,})([\w+-]*)\s*$/);
|
|
27
|
+
const shellFence = options.language === "bash" && !heredoc && source.match(/^(?:\s*)(node(?:js)?|python[\d.]*|ruby|perl|bun|deno)\b[^\n]*?<<-?\s*['"]?([A-Za-z_]\w*)['"]?\s*$/);
|
|
28
|
+
let rows: string[];
|
|
29
|
+
if (heredoc && source === heredoc) { heredoc = ""; heredocLanguage = ""; rows = highlightCode(source, "bash"); }
|
|
30
|
+
else if (heredoc) rows = highlightCode(source, heredocLanguage);
|
|
31
|
+
else if (shellFence) {
|
|
32
|
+
heredoc = shellFence[2];
|
|
33
|
+
heredocLanguage = /^node|bun|deno/.test(shellFence[1]) ? "javascript" : /^python/.test(shellFence[1]) ? "python" : shellFence[1];
|
|
34
|
+
rows = highlightCode(source, "bash");
|
|
35
|
+
}
|
|
36
|
+
else if (marker && (!fence || marker[1][0] === fence[0] && marker[1].length >= fence.length)) {
|
|
37
|
+
if (fence) { fence = ""; language = ""; }
|
|
38
|
+
else { fence = marker[1]; language = marker[2]; }
|
|
39
|
+
rows = [getMarkdownTheme().codeBlockBorder(source)];
|
|
40
|
+
} else if (options.format === "code" || fence) rows = highlightCode(source, fence ? language || undefined : options.language);
|
|
41
|
+
else if (options.format === "markdown" && /(?:^ {0,3}(?:#{1,6} |>|[-*+] |\d+[.)] )|\*\*|__|`|\[[^\]]+\]\()/u.test(source)) {
|
|
42
|
+
rows = new Markdown(source, 0, 0, getMarkdownTheme()).render(Math.max(1, width));
|
|
43
|
+
} else rows = [source];
|
|
44
|
+
for (const row of rows) yield* wrapTextWithAnsi(row, Math.max(1, width));
|
|
45
|
+
offset = end + (text[end] === "\n" ? 1 : 0);
|
|
46
|
+
}
|
|
47
|
+
if (!text.length) yield "(empty)";
|
|
48
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import type { DisplayMode } from './display-mode.ts';
|
|
2
|
+
import { InteractiveMode, SkillInvocationMessageComponent, UserMessageComponent, VERSION, type ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import { Container, Markdown, MouseRegion, Spacer, Text, matchesKey, stripTerminalSequences, visibleWidth } from '@earendil-works/pi-tui';
|
|
4
|
+
import { fillBackground } from './display-card.ts';
|
|
5
|
+
import { chainNativeMethod } from './native-method-chain.ts';
|
|
6
|
+
import { projectedChildren } from './work-strip-view.ts';
|
|
7
|
+
|
|
8
|
+
type Card = { skill: any; user?: any; gap?: any; detachGap?: () => void; headerEnd?: number; userStart?: number; userHeight?: number; body?: Markdown; bodyKey?: string; bodyTheme?: any };
|
|
9
|
+
const startZone = '\x1b]133;A\x07', endZone = '\x1b]133;B\x07\x1b]133;C\x07';
|
|
10
|
+
|
|
11
|
+
/** Pi 1.3 creates a native skill and optional user row from one user envelope.
|
|
12
|
+
* Keep those identities and inputs; combine only their rendered presentation. */
|
|
13
|
+
export function registerModernSkillPrompts(pi: ExtensionAPI, mode: DisplayMode, version = VERSION): () => void {
|
|
14
|
+
const owner = Symbol.for('compact-renderer:skill-prompts:v1'), shared = globalThis as any;
|
|
15
|
+
shared[owner]?.();
|
|
16
|
+
const proto = InteractiveMode.prototype as any;
|
|
17
|
+
if (version !== '1.3.0' || typeof proto.addMessageToChat !== 'function' || typeof SkillInvocationMessageComponent.prototype.setExpanded !== 'function') return () => {};
|
|
18
|
+
const cards = new Map<any, Card>(), users = new WeakMap<any, Card>();
|
|
19
|
+
let active = false, disposed = false, ctx: any, host: any, input: (() => void) | undefined, selected: Card | undefined, rendering: Card | undefined;
|
|
20
|
+
const redraw = () => host?.ui?.requestRender?.();
|
|
21
|
+
const release = () => { selected = undefined; };
|
|
22
|
+
const compatible = (card: Card) => cards.get(card.skill) === card &&
|
|
23
|
+
typeof card.skill.skillBlock?.name === 'string' && typeof card.skill.skillBlock?.content === 'string' &&
|
|
24
|
+
card.skill.children.length === 1 && card.skill.children[0] instanceof MouseRegion && card.skill.children[0].child instanceof Container &&
|
|
25
|
+
(card.skill.expanded ? card.skill.children[0].child.children.length === 2 && card.skill.children[0].child.children[0] instanceof Text && card.skill.children[0].child.children[1] instanceof Markdown :
|
|
26
|
+
card.skill.children[0].child.children.length === 1 && card.skill.children[0].child.children[0] instanceof Text) &&
|
|
27
|
+
(!card.user || card.user.children.length === 1 && card.user.children[0] instanceof Markdown && card.user.children[0].paddingY === 1 && card.user.text === card.skill.skillBlock.userMessage);
|
|
28
|
+
const enabled = (card: Card) => !disposed && active && mode.isEnabled() &&
|
|
29
|
+
typeof ctx?.ui?.theme?.fg === 'function' && typeof ctx?.ui?.theme?.bg === 'function' && compatible(card);
|
|
30
|
+
const publish = (card: Card) => {
|
|
31
|
+
// Inspection must find the native long-user-prompt target inside the visible
|
|
32
|
+
// skill anchor. Canonical native children and prompt-jump identity stay intact.
|
|
33
|
+
if (enabled(card) && card.user) card.skill[projectedChildren] = [card.user];
|
|
34
|
+
else delete card.skill[projectedChildren];
|
|
35
|
+
};
|
|
36
|
+
const focus = (card: Card) => {
|
|
37
|
+
if (!enabled(card)) return;
|
|
38
|
+
selected = card; card.skill.setExpanded(true); redraw();
|
|
39
|
+
pi.events.emit('compact-renderer:focus:v1', { owner: 'skills', target: (row: any) => row === card.skill });
|
|
40
|
+
};
|
|
41
|
+
const renderCard = (card: Card, width: number) => {
|
|
42
|
+
const theme = ctx.ui.theme, skill = card.skill, block = skill.skillBlock, pad = skill.paddingX;
|
|
43
|
+
const fill = (line: string) => line.includes('\x1b_G') || line.includes('\x1b]1337;File=') ? line : fillBackground(line, Math.max(width, visibleWidth(line)), theme, 'userMessageBg');
|
|
44
|
+
let userLines: string[] = [];
|
|
45
|
+
if (card.user) {
|
|
46
|
+
const previous = rendering; rendering = card;
|
|
47
|
+
try { userLines = card.user.render(width); } finally { rendering = previous; }
|
|
48
|
+
}
|
|
49
|
+
const name = stripTerminalSequences(block.name).replace(/[\p{Cc}\p{Cf}]/gu, '');
|
|
50
|
+
const hint = selected === card ? ' · Enter toggles · Esc returns' : '';
|
|
51
|
+
const heading = new Text(theme.fg('muted', `${skill.expanded ? '▾' : '▸'} /skill:${name}${hint}`), pad, 0).render(width).map(fill);
|
|
52
|
+
const blank = fill('');
|
|
53
|
+
const lines = [userLines[0] ?? startZone + blank, ...heading];
|
|
54
|
+
card.headerEnd = lines.length;
|
|
55
|
+
if (skill.expanded) {
|
|
56
|
+
const bodyPad = pad + (width >= 8 ? 2 : 0);
|
|
57
|
+
const bodyKey = [block.content, bodyPad, theme.bg('userMessageBg', ''), theme.fg('userMessageText', '')].join('\u0000');
|
|
58
|
+
if (!card.body || card.bodyKey !== bodyKey || card.bodyTheme !== skill.markdownTheme) {
|
|
59
|
+
card.body = new Markdown(block.content, bodyPad, 0, skill.markdownTheme, { color: (text: string) => theme.fg('userMessageText', text) });
|
|
60
|
+
card.bodyKey = bodyKey; card.bodyTheme = skill.markdownTheme;
|
|
61
|
+
}
|
|
62
|
+
lines.push(blank, ...card.body.render(width).map(fill));
|
|
63
|
+
}
|
|
64
|
+
card.userStart = undefined; card.userHeight = userLines.length;
|
|
65
|
+
if (card.user) {
|
|
66
|
+
lines.push(blank); card.userStart = lines.length;
|
|
67
|
+
lines.push(...userLines.slice(1, -1));
|
|
68
|
+
}
|
|
69
|
+
lines.push(userLines.at(-1) ?? endZone + blank);
|
|
70
|
+
return lines;
|
|
71
|
+
};
|
|
72
|
+
const detachAdd = chainNativeMethod(proto, 'addMessageToChat', function(native, message, ...args) {
|
|
73
|
+
host = this;
|
|
74
|
+
const before = this.chatContainer?.children.length ?? 0;
|
|
75
|
+
const result = native.call(this, message, ...args);
|
|
76
|
+
if (message.role !== 'user') return result;
|
|
77
|
+
const added = this.chatContainer.children.slice(before);
|
|
78
|
+
while (added[0] instanceof Spacer) added.shift();
|
|
79
|
+
const [skill, gap, user] = added;
|
|
80
|
+
if (!(skill instanceof SkillInvocationMessageComponent) ||
|
|
81
|
+
!(added.length === 1 && !skill.skillBlock.userMessage || added.length === 3 && gap instanceof Spacer && user instanceof UserMessageComponent)) return result;
|
|
82
|
+
const card: Card = { skill, user, gap };
|
|
83
|
+
cards.set(skill, card);
|
|
84
|
+
if (user) users.set(user, card);
|
|
85
|
+
if (gap) card.detachGap = chainNativeMethod(gap, 'render', function(native, width) { return enabled(card) ? [] : native.call(this, width); });
|
|
86
|
+
publish(card);
|
|
87
|
+
return result;
|
|
88
|
+
});
|
|
89
|
+
const detachUser = chainNativeMethod(UserMessageComponent.prototype, 'render', function(native, width) {
|
|
90
|
+
const card = users.get(this);
|
|
91
|
+
return card && rendering !== card && enabled(card) ? [] : native.call(this, width);
|
|
92
|
+
});
|
|
93
|
+
const detachSkill = chainNativeMethod(SkillInvocationMessageComponent.prototype, 'render', function(native, width) {
|
|
94
|
+
const card = cards.get(this);
|
|
95
|
+
if (!card) return native.call(this, width);
|
|
96
|
+
publish(card);
|
|
97
|
+
return enabled(card) ? renderCard(card, width) : native.call(this, width);
|
|
98
|
+
});
|
|
99
|
+
const detachMouse = chainNativeMethod(SkillInvocationMessageComponent.prototype, 'handleMouse', function(native, event) {
|
|
100
|
+
const card = cards.get(this);
|
|
101
|
+
if (!card || !enabled(card)) return native?.call(this, event);
|
|
102
|
+
if (event.type === 'click' && event.button === 'left' && !event.ctrl && !event.alt && !event.shift && event.y >= 1 && event.y < card.headerEnd!) {
|
|
103
|
+
release(); this.setExpanded(!this.expanded);
|
|
104
|
+
pi.events.emit('compact-renderer:focus:v1', { owner: 'editor' }); redraw();
|
|
105
|
+
return { handled: true, render: true };
|
|
106
|
+
}
|
|
107
|
+
if (card.user && card.userStart !== undefined && event.y >= card.userStart && event.y < card.userStart + card.userHeight! - 2) {
|
|
108
|
+
return card.user.handleMouse({ ...event, y: event.y - card.userStart + 1, height: card.userHeight });
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
const prune = () => {
|
|
112
|
+
const mounted = new Set(host?.chatContainer?.children || []);
|
|
113
|
+
for (const [skill, card] of cards) if (!mounted.has(skill)) { card.detachGap?.(); delete skill[projectedChildren]; cards.delete(skill); }
|
|
114
|
+
};
|
|
115
|
+
const reset = (_event: any, context: any) => {
|
|
116
|
+
input?.(); input = undefined; release(); prune();
|
|
117
|
+
ctx = context; active = context.mode === 'tui';
|
|
118
|
+
for (const card of cards.values()) publish(card);
|
|
119
|
+
if (active) input = ctx.ui.onTerminalInput?.((data: string) => {
|
|
120
|
+
if (!selected || !enabled(selected)) return;
|
|
121
|
+
if (matchesKey(data, 'enter')) { selected.skill.setExpanded(!selected.skill.expanded); redraw(); return { consume: true }; }
|
|
122
|
+
const escape = matchesKey(data, 'escape'); release();
|
|
123
|
+
pi.events.emit('compact-renderer:inspection-ended:v1', {}); redraw();
|
|
124
|
+
if (escape) return { consume: true };
|
|
125
|
+
});
|
|
126
|
+
redraw();
|
|
127
|
+
};
|
|
128
|
+
const clear = () => {
|
|
129
|
+
active = false; input?.(); input = undefined; release();
|
|
130
|
+
for (const card of cards.values()) { card.detachGap?.(); delete card.skill[projectedChildren]; }
|
|
131
|
+
cards.clear(); ctx = undefined;
|
|
132
|
+
};
|
|
133
|
+
const subscriptions = [
|
|
134
|
+
pi.on('session_start', reset), pi.on('session_tree', reset), pi.on('session_compact', reset), pi.on('session_before_switch', clear),
|
|
135
|
+
pi.on('ui_prompt_start', release),
|
|
136
|
+
pi.events.on('compact-renderer:focus:v1', (event: any) => { if (event?.owner !== 'skills') release(); }),
|
|
137
|
+
pi.events.on('compact-renderer:inspect:v1', (request: any) => {
|
|
138
|
+
if (!active || !mode.isEnabled()) return;
|
|
139
|
+
prune();
|
|
140
|
+
for (const [index, card] of [...cards.values()].entries()) if (enabled(card)) request?.add?.({ id: `skill-${index}`, kind: 'Skill', label: `/skill:${card.skill.skillBlock.name}`, focus: () => focus(card) });
|
|
141
|
+
}),
|
|
142
|
+
mode.onChange(() => { release(); for (const card of cards.values()) publish(card); redraw(); }),
|
|
143
|
+
];
|
|
144
|
+
const dispose = () => {
|
|
145
|
+
if (disposed) return; disposed = true; clear(); subscriptions.forEach(off => off?.());
|
|
146
|
+
detachMouse(); detachSkill(); detachUser(); detachAdd(); redraw();
|
|
147
|
+
if (shared[owner] === dispose) delete shared[owner];
|
|
148
|
+
};
|
|
149
|
+
subscriptions.push(pi.on('session_shutdown', dispose));
|
|
150
|
+
shared[owner] = dispose;
|
|
151
|
+
return dispose;
|
|
152
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { ToolPane, type PaneAction, type PaneContent } from './modern-tool-pane.ts';
|
|
3
|
+
import { recordedPaneHeight } from './modern-recorded-pane.ts';
|
|
4
|
+
import { recordedValues } from './modern-tool-content.ts';
|
|
5
|
+
import { compactSubagent, subagentDecision, subagentTitle } from './modern-subagents.ts';
|
|
6
|
+
|
|
7
|
+
const short = (name: string) => name.split('__').at(-1) || name;
|
|
8
|
+
const clean = (value: unknown) => typeof value === 'string' ? value.slice(0, 72).replace(/[\p{Cc}\p{Cf}]/gu, ' ') : '';
|
|
9
|
+
export const hiddenSubagent = Symbol.for('compact-renderer:subagent-hidden:v1');
|
|
10
|
+
type Row = { key: string; kind: 'tool' | 'message' | 'entry'; source: any; name?: string; args?: any; result?: any; failed?: boolean; pending?: boolean; revision?: number; raw?: any; group?: ProjectionGroup };
|
|
11
|
+
export type ProjectionGroup = { members: Row[]; pane: ToolPane; answered: boolean; signature: string };
|
|
12
|
+
export type SubagentView = { pane: ToolPane; hidden: boolean; answered: boolean };
|
|
13
|
+
const stamp = (value: any) => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? Date.parse(value) : value;
|
|
14
|
+
const requestId = (d: any) => typeof d?.requestId === 'string' && d.requestId && (!d.id || d.id === d.requestId) ? d.requestId : undefined;
|
|
15
|
+
const textContent = (source: any) => typeof source.content === 'string' || Array.isArray(source.content) && source.content.every((b: any) => b.type === 'text' && typeof b.text === 'string');
|
|
16
|
+
const request = (r: Row) => textContent(r.source || {}) && typeof r.source?.details?.agent === 'string' && r.kind === 'message' && r.source.customType === 'subagent_supervisor_request' && ['need_decision', 'interview_request'].includes(r.source.details?.reason) ? requestId(r.source.details) : undefined;
|
|
17
|
+
const reply = (r: Row) => textContent(r.result || {}) && r.kind === 'tool' && short(r.name || '') === 'subagent_supervisor' && r.args?.action === 'reply' && !r.failed && !r.pending && (!r.result?.details?.status || ['success', 'ok', 'completed'].includes(r.result.details.status)) && typeof r.result?.details?.replyTo === 'string' && (!r.args.replyTo || r.args.replyTo === r.result.details.replyTo) && (!r.args.requestId || r.args.requestId === r.result.details.replyTo) ? r.result.details.replyTo : undefined;
|
|
18
|
+
const answer = (r: Row) => r.kind === 'entry' && r.source.customType === 'subagent_supervisor_reply' && typeof r.source.data?.message === 'string' && typeof r.source.data?.agent === 'string' ? requestId(r.source.data) : undefined;
|
|
19
|
+
const agents = (r: Row): string[] => r.kind === 'tool' ? [r.result?.details?.agent ?? r.args?.agent].filter(x => typeof x === 'string') : r.kind === 'entry' ? [r.source.data?.agent].filter(x => typeof x === 'string') : r.source.details?.runs?.map((x: any) => x.agent) || [r.source.details?.agent].filter(x => typeof x === 'string');
|
|
20
|
+
const guide = (r: Row) => r.kind === 'tool' && ['subagent', 'subagents'].includes(short(r.name || '')) && r.args?.action === 'guide';
|
|
21
|
+
const routine = (r: Row) => {
|
|
22
|
+
const results = r.result?.details?.results;
|
|
23
|
+
if (Array.isArray(results) && results.some((x: any) => !x || x.error || typeof x.exitCode === 'number' && x.exitCode !== 0 || x.detached || x.interrupted || x.timedOut || x.stopped || x.outputPartial || x.turnBudgetExceeded || x.toolBudgetBlocked || x.structuredOutputFailed || x.execution && x.execution.status !== 'completed')) return false;
|
|
24
|
+
if (r.kind === 'tool') return ['subagent', 'subagents'].includes(short(r.name || '')) && ['launch', 'resume', 'status', 'pending', 'list', 'steer', 'guide'].includes(r.args?.action || 'launch') && compactSubagent(r.name || '') && !r.pending && !r.failed && !subagentDecision(r.name || '', r.args) && short(r.name || '') !== 'contact_supervisor' && short(r.name || '') !== 'subagent_supervisor' && !['partial', 'failed'].includes(r.result?.details?.steering?.state) && (!r.result?.details?.status || ['success', 'ok', 'completed'].includes(r.result.details.status)) && !r.result?.content?.some((b: any) => b.type !== 'text');
|
|
25
|
+
const d = r.source.details;
|
|
26
|
+
return r.kind === 'message' && (r.source.customType === 'subagent-notify' && Array.isArray(d?.runs) && d.runs.length > 0 && d.runs.every((x: any) => typeof x.agent === 'string' && x.status === 'completed') || r.source.customType === 'subagent_supervisor_request' && d?.reason === 'progress_update' && typeof d.agent === 'string') && (typeof r.source.content === 'string' || Array.isArray(r.source.content) && r.source.content.every((b: any) => b.type === 'text' && typeof b.text === 'string'));
|
|
27
|
+
};
|
|
28
|
+
function* primary(r: Row): Generator<PaneContent> {
|
|
29
|
+
const content = r.kind === 'tool' ? r.result?.content : r.kind === 'entry' ? r.source.data?.message : r.source.content;
|
|
30
|
+
if (typeof content === 'string') yield { text: content, format: 'markdown' };
|
|
31
|
+
else for (const block of content || []) if (block.type === 'text' && typeof block.text === 'string') yield { text: block.text, format: 'markdown' };
|
|
32
|
+
}
|
|
33
|
+
function* exact(r: Row): Generator<PaneContent> {
|
|
34
|
+
if (r.kind === 'tool') { yield { text: 'Arguments', kind: 'section' }; yield* recordedValues(r.args); yield { text: 'Result', kind: 'section' }; yield* recordedValues(r.result); }
|
|
35
|
+
else yield* recordedValues(r.raw || r.source);
|
|
36
|
+
}
|
|
37
|
+
const action = (r: Row): PaneAction => ({ id: r.key, label: r.kind === 'tool' ? subagentTitle(r.name || '', r.args, r.result, r.failed ? 'failed' : r.pending ? 'pending' : 'success') : r.source.customType === 'subagent-notify' ? `${agents(r).map(clean).join(', ')} · completed` : `${clean(r.source.details?.agent)} · progress update`, sections: () => primary(r), details: () => exact(r) });
|
|
38
|
+
|
|
39
|
+
/** Presentation projection. Only persisted entry order and public event order create rows.
|
|
40
|
+
* Render callbacks resolve recorded identities; they never append or reorder rows. */
|
|
41
|
+
export class SubagentProjection {
|
|
42
|
+
private rows: (Row | null)[] = [];
|
|
43
|
+
private tools = new Map<string, Row>();
|
|
44
|
+
private sources = new WeakMap<object, Row>();
|
|
45
|
+
private details = new WeakMap<object, Row | null>();
|
|
46
|
+
private groups = new Map<string, ProjectionGroup>();
|
|
47
|
+
private serial = 0;
|
|
48
|
+
private boundaries = new WeakSet<object>();
|
|
49
|
+
private dirty = true;
|
|
50
|
+
clear() { this.rows = []; this.tools.clear(); this.sources = new WeakMap(); this.details = new WeakMap(); this.groups.clear(); this.serial = 0; this.boundaries = new WeakSet(); this.dirty = true; }
|
|
51
|
+
private custom(source: any, kind: 'message' | 'entry', key?: string, raw?: any) {
|
|
52
|
+
if (!source || typeof source !== 'object' || this.sources.has(source)) return;
|
|
53
|
+
const existing = kind === 'message' && source.details && this.details.get(source.details);
|
|
54
|
+
if (existing && (!key || key === existing.key) && existing.source.customType === source.customType && stamp(existing.source.timestamp) === stamp(source.timestamp)) { this.sources.set(source, existing); return; }
|
|
55
|
+
const row: Row = { key: key || `live:${++this.serial}`, kind, source, raw };
|
|
56
|
+
this.sources.set(source, row);
|
|
57
|
+
const d = source.details;
|
|
58
|
+
if (kind === 'message' && d && typeof d === 'object') this.details.set(d, this.details.has(d) ? null : row);
|
|
59
|
+
this.rows.push(row); this.dirty = true;
|
|
60
|
+
}
|
|
61
|
+
rebuild(entries: readonly any[]) {
|
|
62
|
+
const previous = this.groups; this.clear(); this.groups = previous;
|
|
63
|
+
for (const entry of entries) {
|
|
64
|
+
if (entry.type === 'message') this.observe(entry.message);
|
|
65
|
+
else if (entry.type === 'custom_message' && entry.display !== false) this.custom({ role: 'custom', customType: entry.customType, content: entry.content, details: entry.details, timestamp: entry.timestamp }, 'message', entry.id, entry);
|
|
66
|
+
else if (entry.type === 'custom' && entry.customType === 'subagent_supervisor_reply') this.custom(entry, 'entry', entry.id);
|
|
67
|
+
else if (['compaction', 'branch_summary', 'custom', 'custom_message'].includes(entry.type) && entry.display !== false) { this.rows.push(null); this.dirty = true; }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
observe(message: any) {
|
|
71
|
+
if (!message || typeof message !== 'object' || message.role === 'custom' && message.display === false) return;
|
|
72
|
+
if (message.role === 'assistant') {
|
|
73
|
+
if (!this.boundaries.has(message) && (message.errorMessage || ['error', 'aborted', 'length'].includes(message.stopReason) || message.content?.some((b: any) => b.type === 'text' && b.text?.trim()))) { this.boundaries.add(message); this.rows.push(null); this.dirty = true; }
|
|
74
|
+
for (const call of message.content || []) if (call.type === 'toolCall') this.start(call.id, call.name, call.arguments);
|
|
75
|
+
} else if (message.role === 'toolResult') this.end(message.toolCallId, message.toolName, message, message.isError);
|
|
76
|
+
else if (message.role === 'custom' && message.display !== false) this.custom(message, 'message');
|
|
77
|
+
else if (message.role !== 'system' && !this.boundaries.has(message)) { this.boundaries.add(message); this.rows.push(null); this.dirty = true; }
|
|
78
|
+
}
|
|
79
|
+
start(id: string, name: string, args?: any) {
|
|
80
|
+
if (!id || !name) return;
|
|
81
|
+
let row = this.tools.get(id);
|
|
82
|
+
if (!row) { row = { key: `tool:${id}`, kind: 'tool', source: undefined, name, args, pending: true }; this.tools.set(id, row); this.rows.push(row); }
|
|
83
|
+
else if (args !== undefined && row.args !== args) { row.args = args; row.revision = (row.revision || 0) + 1; }
|
|
84
|
+
this.dirty = true;
|
|
85
|
+
}
|
|
86
|
+
end(id: string, name: string, result: any, error = false) {
|
|
87
|
+
this.start(id, name); const row = this.tools.get(id); if (!row) return;
|
|
88
|
+
if (row.result !== result || row.failed !== (!!error || !!result?.isError)) row.revision = (row.revision || 0) + 1;
|
|
89
|
+
row.result = result; row.pending = false; row.failed = !!error || !!result?.isError || ['failed', 'partial'].includes(result?.details?.steering?.state); this.dirty = true;
|
|
90
|
+
}
|
|
91
|
+
private regroup() {
|
|
92
|
+
if (!this.dirty) return; this.dirty = false;
|
|
93
|
+
const previous = this.groups; this.groups = new Map();
|
|
94
|
+
for (const row of this.rows) if (row) row.group = undefined;
|
|
95
|
+
const counts = new Map<string, number>(), receipts = new Map<string, number>(), answers = new Map<string, number>();
|
|
96
|
+
for (const row of this.rows) if (row) for (const [id, map] of [[request(row), counts], [reply(row), receipts], [answer(row), answers]] as const) if (id) map.set(id, (map.get(id) || 0) + 1);
|
|
97
|
+
const group = (members: Row[], answered: boolean) => {
|
|
98
|
+
if (members.length < 2) return;
|
|
99
|
+
const key = members[0].key, signature = members.map(r => `${r.key}@${r.revision || 0}`).join('|') + `:${answered}`;
|
|
100
|
+
const g = previous.get(key) || { members, pane: new ToolPane([], '', recordedPaneHeight), answered, signature: '' };
|
|
101
|
+
if (g.signature !== signature || members.some((row, index) => row !== g.members[index] || row.result !== g.members[index]?.result)) {
|
|
102
|
+
if (answered) g.pane.actions = [{ id: key, label: 'Decision answered', sections: function* () { const d = members[0].source.details; if (typeof d.requestBody === 'string') yield { text: d.requestBody, format: 'markdown' }; else yield* primary(members[0]); yield { text: 'Supervisor reply', kind: 'section' }; yield { text: members[2].source.data.message, kind: 'answer', format: 'markdown' }; }, details: function* () { for (const row of members) { yield { text: row.kind === 'tool' ? 'Reply delivery' : row.kind === 'entry' ? 'Recorded supervisor reply' : 'Recorded request', kind: 'section' }; yield* exact(row); } } }];
|
|
103
|
+
else g.pane.actions = members.map(action);
|
|
104
|
+
g.pane.reset(); g.signature = signature;
|
|
105
|
+
}
|
|
106
|
+
g.members = members; g.answered = answered;
|
|
107
|
+
const names = [...new Set(members.flatMap(agents).map(clean).filter(Boolean))];
|
|
108
|
+
g.pane.title = answered ? `${clean(members[0].source.details.agent)} · Decision answered` : `Subagents · ${members.length} ${guide(members[0]) ? "guide lookups" : "updates"}${names.length ? ` · ${names.slice(0, 3).join(', ')}${names.length > 3 ? ', …' : ''}` : ''}`;
|
|
109
|
+
g.pane.headingTone = answered ? 'customMessageLabel' : 'mdLink';
|
|
110
|
+
for (const row of members) row.group = g;
|
|
111
|
+
this.groups.set(key, g);
|
|
112
|
+
};
|
|
113
|
+
let run: Row[] = [];
|
|
114
|
+
const flush = () => { group(run, false); run = []; };
|
|
115
|
+
for (let i = 0; i < this.rows.length; i++) {
|
|
116
|
+
const row = this.rows[i], id = row && request(row), ack = this.rows[i + 1], recorded = this.rows[i + 2];
|
|
117
|
+
if (row && id && counts.get(id) === 1 && receipts.get(id) === 1 && answers.get(id) === 1 && ack && recorded && reply(ack) === id && answer(recorded) === id && row.source.details.agent === recorded.source.data.agent && (!row.source.details.runId || row.source.details.runId === recorded.source.data.runId) && [ack.args, ack.result?.details].every(d => (!d?.agent || d.agent === row.source.details.agent) && (!d?.runId || d.runId === row.source.details.runId))) { flush(); group([row, ack, recorded], true); i += 2; }
|
|
118
|
+
else if (row && routine(row)) {
|
|
119
|
+
if (run.length && guide(run[0]) !== guide(row)) flush();
|
|
120
|
+
run.push(row);
|
|
121
|
+
}
|
|
122
|
+
else flush();
|
|
123
|
+
}
|
|
124
|
+
flush();
|
|
125
|
+
}
|
|
126
|
+
viewTool(id: string): SubagentView | undefined { return this.view(this.tools.get(id)); }
|
|
127
|
+
viewSource(source: any): SubagentView | undefined {
|
|
128
|
+
let row = this.sources.get(source);
|
|
129
|
+
const candidate = source?.details && this.details.get(source.details);
|
|
130
|
+
if (!row && candidate && candidate.source.customType === source.customType && stamp(candidate.source.timestamp) === stamp(source.timestamp)) row = candidate;
|
|
131
|
+
return this.view(row);
|
|
132
|
+
}
|
|
133
|
+
private view(row?: Row): SubagentView | undefined { this.regroup(); return row?.group ? { pane: row.group.pane, hidden: row.group.members[0] !== row, answered: row.group.answered } : undefined; }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
type Shared = { projection: SubagentProjection; sync(): void; release(): void };
|
|
137
|
+
const owners = new WeakMap<object, { shared: Shared; count: number }>();
|
|
138
|
+
export function acquireSubagentProjection(pi: ExtensionAPI): Shared {
|
|
139
|
+
const found = owners.get(pi); if (found) { found.count++; return found.shared; }
|
|
140
|
+
const projection = new SubagentProjection(); let manager: any, last: any, length = -1, leaf: any = Symbol();
|
|
141
|
+
const sync = () => {
|
|
142
|
+
const nextLeaf = manager?.getLeafId?.();
|
|
143
|
+
if (typeof manager?.getLeafId === 'function' && nextLeaf === leaf) return;
|
|
144
|
+
leaf = nextLeaf;
|
|
145
|
+
const entries = manager?.buildContextEntries?.() ?? manager?.getBranch?.();
|
|
146
|
+
if (!entries || entries.length === length && entries.at(-1) === last) return;
|
|
147
|
+
length = entries.length; last = entries.at(-1); projection.rebuild(entries);
|
|
148
|
+
};
|
|
149
|
+
const subscriptions: (() => void)[] = [];
|
|
150
|
+
const reset = (_event: any, ctx: any) => { manager = ctx.sessionManager; last = undefined; length = -1; leaf = Symbol(); projection.clear(); sync(); };
|
|
151
|
+
for (const event of ['session_start', 'session_tree', 'session_compact']) subscriptions.push((pi.on as any)(event, reset));
|
|
152
|
+
for (const event of ['session_before_switch', 'session_shutdown']) subscriptions.push((pi.on as any)(event, () => { manager = undefined; projection.clear(); length = -1; }));
|
|
153
|
+
for (const event of ['message_start', 'message_update', 'message_end']) subscriptions.push((pi.on as any)(event, (event: any) => { sync(); projection.observe(event.message); }));
|
|
154
|
+
subscriptions.push(pi.on('tool_execution_start', (event: any) => { if (!event.parentToolCallId) { sync(); projection.start(event.toolCallId, event.toolName, event.args); } }));
|
|
155
|
+
subscriptions.push(pi.on('tool_execution_end', (event: any) => { if (!event.parentToolCallId) { sync(); projection.end(event.toolCallId, event.toolName, event.result, event.isError); } }));
|
|
156
|
+
const shared = { projection, sync, release() { const owner = owners.get(pi); if (!owner || --owner.count) return; subscriptions.forEach(off => off?.()); projection.clear(); owners.delete(pi); } };
|
|
157
|
+
owners.set(pi, { shared, count: 1 }); return shared;
|
|
158
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import type { DisplayMode } from './display-mode.ts';
|
|
2
|
+
import { ExtensionRunner, VERSION, type ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import { matchesKey, truncateToWidth } from '@earendil-works/pi-tui';
|
|
4
|
+
import { ToolPane, type PaneContent } from './modern-tool-pane.ts';
|
|
5
|
+
import { recordedPaneHeight } from './modern-recorded-pane.ts';
|
|
6
|
+
import { acquireSubagentProjection, hiddenSubagent } from './modern-subagent-groups.ts';
|
|
7
|
+
import { installSubagentSpacingAdapter } from './modern-subagent-spacing.ts';
|
|
8
|
+
import { recordedValues } from './modern-tool-content.ts';
|
|
9
|
+
import { activityHeading } from './display-card.ts';
|
|
10
|
+
|
|
11
|
+
type Summary = { title: string; tone: string };
|
|
12
|
+
const record = (value: any) => value && typeof value === 'object' && !Array.isArray(value);
|
|
13
|
+
const text = (value: unknown) => typeof value === 'string' ? truncateToWidth(value.slice(0, 512).replace(/[\p{Cc}\p{Cf}]/gu, ' '), 90, '…') : '';
|
|
14
|
+
const statuses = new Set(['completed', 'failed', 'paused', 'stopped']);
|
|
15
|
+
const messageTypes = new Set(['subagent_supervisor_request', 'subagent-notify', 'subagent_steering_notice', 'subagent_control_notice', 'subagent-supervisor-unanswered', 'subagent-supervisor-blocked', 'subagent-completion-unanswered', 'subagent-completion-unhandled', 'subagent-workflow-result-write-failed', 'subagent-incremental-child-notify', 'subagent-wait-subscription', 'subagent_watchdog_clarification']);
|
|
16
|
+
|
|
17
|
+
/** Headlines use recorded metadata. Queue acceptance never implies delivery. */
|
|
18
|
+
export function subagentMessageSummary(source: any, entry = false): Summary | undefined {
|
|
19
|
+
const d = entry ? source?.data : source?.details;
|
|
20
|
+
const named = (title: string, tone = 'mdLink') => ({ title: `Subagent · ${title}`, tone });
|
|
21
|
+
if (entry) {
|
|
22
|
+
if (source?.customType === 'subagent_supervisor_reply' && record(d) && typeof d.message === 'string' && typeof d.agent === 'string' && typeof d.requestId === 'string') return named(`reply sent to ${text(d.agent)}`);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
switch (source?.customType) {
|
|
26
|
+
case 'subagent_supervisor_request':
|
|
27
|
+
if (!record(d) || typeof d.agent !== 'string' || !['need_decision', 'interview_request', 'progress_update'].includes(d.reason)) return;
|
|
28
|
+
return named(`${text(d.agent)} · ${d.reason === 'need_decision' ? 'needs a decision' : d.reason === 'interview_request' ? 'asks for structured answers' : 'progress update'}`, d.reason === 'progress_update' ? 'mdLink' : 'customMessageLabel');
|
|
29
|
+
case 'subagent-notify': {
|
|
30
|
+
if (!record(d) || !Array.isArray(d.runs) || !d.runs.length || !d.runs.every((r: any) => record(r) && typeof r.agent === 'string' && statuses.has(r.status))) return;
|
|
31
|
+
const failed = d.runs.some((r: any) => r.status === 'failed');
|
|
32
|
+
return named(d.runs.length === 1 ? `${text(d.runs[0].agent)} · ${d.runs[0].status}` : `${d.runs.length} runs · ${['completed', 'failed', 'paused', 'stopped'].map(s => [s, d.runs.filter((r: any) => r.status === s).length]).filter(([, n]) => n).map(([s, n]) => `${n} ${s}`).join(' · ')}`, failed ? 'error' : 'mdLink');
|
|
33
|
+
}
|
|
34
|
+
case 'subagent_steering_notice':
|
|
35
|
+
if (!record(d) || typeof d.runId !== 'string' || !['failed', 'partial', 'recovered'].includes(d.state)) return;
|
|
36
|
+
return named(`steering ${d.state} · ${text(d.runId)}`, d.state === 'recovered' ? 'mdLink' : 'error');
|
|
37
|
+
case 'subagent_control_notice':
|
|
38
|
+
if (!record(d?.event) || typeof d.event.agent !== 'string' || d.event.type !== 'needs_attention') return;
|
|
39
|
+
return named(`${text(d.event.agent)} · needs attention`, 'customMessageLabel');
|
|
40
|
+
case 'subagent-supervisor-unanswered': return named('supervisor requests unanswered', 'customMessageLabel');
|
|
41
|
+
case 'subagent-supervisor-blocked': return named('supervisor requests blocked', 'error');
|
|
42
|
+
case 'subagent-completion-unanswered': return named('completion results unanswered');
|
|
43
|
+
case 'subagent-completion-unhandled': return named('completion results unhandled', 'error');
|
|
44
|
+
case 'subagent-workflow-result-write-failed': return named('workflow result save failed', 'error');
|
|
45
|
+
case 'subagent-incremental-child-notify':
|
|
46
|
+
if (!record(d) || typeof d.childKey !== 'string' || !statuses.has(d.outcome)) return;
|
|
47
|
+
return named(`workflow child ${text(d.childKey)} · ${d.outcome}`, d.outcome === 'failed' ? 'error' : 'mdLink');
|
|
48
|
+
case 'subagent-wait-subscription':
|
|
49
|
+
if (!record(d) || typeof d.runId !== 'string' || typeof d.outcome !== 'string') return;
|
|
50
|
+
return named(`wait · ${text(d.runId)} · ${text(d.outcome)}`, ['failed', 'error'].includes(d.outcome) ? 'error' : 'mdLink');
|
|
51
|
+
case 'subagent_watchdog_clarification': return named('watchdog needs clarification', 'customMessageLabel');
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Pi 1.3 resolver seam. Keep each extension's original renderer as the fallback.
|
|
56
|
+
* Registering another message renderer cannot delegate through Pi's first-match registry. */
|
|
57
|
+
export function installSubagentMessageAdapter(wrap: (native: any, entry: boolean) => any, version = VERSION): (() => void) | undefined {
|
|
58
|
+
const proto = ExtensionRunner.prototype as any;
|
|
59
|
+
if (version !== '1.3.0' || !['getMessageRenderer', 'getEntryRenderer'].every(k => typeof proto[k] === 'function')) return;
|
|
60
|
+
const owner = Symbol.for('compact-renderer:subagent-message-adapter:v1');
|
|
61
|
+
proto[owner]?.();
|
|
62
|
+
const message = proto.getMessageRenderer, entry = proto.getEntryRenderer;
|
|
63
|
+
let disposed = false;
|
|
64
|
+
const messages = function(this: any, ...args: any[]) { const native = message.apply(this, args); return !disposed && native && messageTypes.has(args[0]) ? wrap(native, false) : native; };
|
|
65
|
+
const entries = function(this: any, ...args: any[]) { const native = entry.apply(this, args); return !disposed && native && args[0] === 'subagent_supervisor_reply' ? wrap(native, true) : native; };
|
|
66
|
+
const dispose = () => {
|
|
67
|
+
if (disposed) return; disposed = true;
|
|
68
|
+
if (proto.getMessageRenderer === messages) proto.getMessageRenderer = message;
|
|
69
|
+
if (proto.getEntryRenderer === entries) proto.getEntryRenderer = entry;
|
|
70
|
+
if (proto[owner] === dispose) delete proto[owner];
|
|
71
|
+
};
|
|
72
|
+
proto.getMessageRenderer = messages; proto.getEntryRenderer = entries; proto[owner] = dispose;
|
|
73
|
+
return dispose;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
type Card = { source: any; entry: boolean; pane: ToolPane; component?: any; expanded: boolean; summary: Summary };
|
|
77
|
+
function* content(source: any, entry: boolean): Generator<PaneContent> {
|
|
78
|
+
if (entry) { yield { text: source.data.message, format: 'markdown' }; return; }
|
|
79
|
+
if (typeof source.content === 'string') yield { text: source.content, format: 'markdown' };
|
|
80
|
+
else for (const part of source.content || []) if (part?.type === 'text' && typeof part.text === 'string') yield { text: part.text, format: 'markdown' };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Display only. Native execution, Fleet, messages, entries and wake routing stay authoritative. */
|
|
84
|
+
export function registerModernSubagentMessages(pi: ExtensionAPI, mode: DisplayMode): () => void {
|
|
85
|
+
const owner = Symbol.for('compact-renderer:subagent-message-registration:v1'), shared = globalThis as any;
|
|
86
|
+
shared[owner]?.();
|
|
87
|
+
const subagents = acquireSubagentProjection(pi), spacing = installSubagentSpacingAdapter();
|
|
88
|
+
let cards = new Map<any, Card>(), selected: Card | undefined, focused = false, active = false, disposed = false;
|
|
89
|
+
let input: (() => void) | undefined, redraw: (() => void) | undefined;
|
|
90
|
+
const release = (preserveAnchor = false) => { if (focused && selected) { (view(selected.source)?.pane || selected.pane).focused = false; if (!preserveAnchor) (view(selected.source)?.pane || selected.pane).releaseInspection(); } focused = false; };
|
|
91
|
+
const view = (source: any) => { subagents.sync(); return subagents.projection.viewSource(source); };
|
|
92
|
+
const adapter = installSubagentMessageAdapter((native, entry) => {
|
|
93
|
+
return (source: any, options: any, theme: any) => {
|
|
94
|
+
const summary = subagentMessageSummary(source, entry);
|
|
95
|
+
const supportedContent = entry || typeof source.content === 'string' || Array.isArray(source.content) && source.content.every((part: any) => part?.type === 'text' && typeof part.text === 'string');
|
|
96
|
+
if (disposed || !active || !mode.isEnabled() || !summary || !supportedContent) return native(source, options, theme);
|
|
97
|
+
let card = cards.get(source);
|
|
98
|
+
if (!card) {
|
|
99
|
+
const pane = new ToolPane([{ id: 'notice', label: summary.title, sections: () => content(source, entry), details: () => recordedValues(entry ? source.data : source.details) }], summary.title, recordedPaneHeight);
|
|
100
|
+
card = { source, entry, pane, expanded: options.expanded, summary }; pane.open = options.expanded;
|
|
101
|
+
cards.set(source, card); if (options.expanded && view(source)) view(source)!.pane.open = true;
|
|
102
|
+
}
|
|
103
|
+
if (card.expanded !== options.expanded) { card.expanded = options.expanded; card.pane.open = options.expanded; card.pane.reset(); const projected = view(source); if (projected) { projected.pane.open = options.expanded; projected.pane.reset(); } }
|
|
104
|
+
card.summary = summary;
|
|
105
|
+
let fallback: any;
|
|
106
|
+
const current = card;
|
|
107
|
+
const projectedPane = () => view(source)?.pane || current.pane;
|
|
108
|
+
const component = {
|
|
109
|
+
[hiddenSubagent]: () => !disposed && active && mode.isEnabled() && !!view(source)?.hidden,
|
|
110
|
+
render(width: number) {
|
|
111
|
+
if (disposed || !active || !mode.isEnabled() || cards.get(source) !== current) { fallback ??= native(source, options, theme); return fallback?.render(width) || []; }
|
|
112
|
+
const projected = view(source);
|
|
113
|
+
if (projected?.hidden) return [];
|
|
114
|
+
const pane = projectedPane();
|
|
115
|
+
if (!projected) { pane.title = current.summary.title; pane.headingTone = current.summary.tone; }
|
|
116
|
+
pane.theme = theme; pane.styleHeader = line => activityHeading(line, theme, pane.headingTone);
|
|
117
|
+
pane.focused = focused && selected === current;
|
|
118
|
+
if (pane.focused) pane.open = true;
|
|
119
|
+
return pane.render(width);
|
|
120
|
+
},
|
|
121
|
+
handleMouse(event: any) {
|
|
122
|
+
if (disposed || !active || !mode.isEnabled() || cards.get(source) !== current) { fallback ??= native(source, options, theme); return fallback?.handleMouse?.(event); }
|
|
123
|
+
if (view(source)?.hidden) return;
|
|
124
|
+
const handled = projectedPane().handleMouse(event);
|
|
125
|
+
if (handled?.handled && handled.render !== false) { release(true); pi.events.emit('compact-renderer:focus:v1', { owner: 'editor' }); redraw?.(); }
|
|
126
|
+
return handled;
|
|
127
|
+
},
|
|
128
|
+
invalidate() { projectedPane().invalidate(); fallback?.invalidate?.(); },
|
|
129
|
+
};
|
|
130
|
+
card.component = component;
|
|
131
|
+
return component;
|
|
132
|
+
};
|
|
133
|
+
});
|
|
134
|
+
const stop = () => { active = false; release(); input?.(); input = undefined; cards.clear(); selected = undefined; redraw = undefined; };
|
|
135
|
+
const reset = (_event: unknown, ctx: any) => {
|
|
136
|
+
stop();
|
|
137
|
+
if (disposed || !adapter || ctx.mode !== 'tui') return;
|
|
138
|
+
active = true;
|
|
139
|
+
redraw = typeof ctx.ui.setHiddenThinkingLabel === 'function' ? () => ctx.ui.setHiddenThinkingLabel() : undefined;
|
|
140
|
+
input = ctx.ui.onTerminalInput?.((data: string) => {
|
|
141
|
+
if (!active || !mode.isEnabled() || !focused || !selected || cards.get(selected.source) !== selected) return;
|
|
142
|
+
if (matchesKey(data, 'escape')) { release(); pi.events.emit('compact-renderer:inspection-ended:v1', { owner: 'subagents' }); redraw?.(); return { consume: true }; }
|
|
143
|
+
if ((view(selected.source)?.pane || selected.pane).handle(data)) { redraw?.(); return { consume: true }; }
|
|
144
|
+
release(); pi.events.emit('compact-renderer:inspection-ended:v1', { owner: 'subagents' }); redraw?.();
|
|
145
|
+
});
|
|
146
|
+
};
|
|
147
|
+
const subscriptions: (() => void)[] = [];
|
|
148
|
+
for (const event of ['session_start', 'session_tree', 'session_compact'] as const) subscriptions.push(pi.on(event, reset));
|
|
149
|
+
subscriptions.push(pi.on('session_before_switch', stop), pi.on('session_shutdown', stop), pi.on('ui_prompt_start', () => release()));
|
|
150
|
+
subscriptions.push(pi.events.on('compact-renderer:focus:v1', (event: any) => { if (event?.owner !== 'subagents') release(); }));
|
|
151
|
+
subscriptions.push(pi.events.on('compact-renderer:disclosures:v1', (request: any) => {
|
|
152
|
+
if (disposed || !active || !mode.isEnabled()) return;
|
|
153
|
+
for (const card of cards.values()) {
|
|
154
|
+
const projected = view(card.source);
|
|
155
|
+
if (projected?.hidden) continue;
|
|
156
|
+
const pane = projected?.pane || card.pane;
|
|
157
|
+
request?.add?.((component: any) => component === card.component, pane.open, () => {
|
|
158
|
+
if (selected === card) { release(); selected = undefined; }
|
|
159
|
+
pane.collapse();
|
|
160
|
+
if (pane !== card.pane) card.pane.collapse();
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}));
|
|
164
|
+
subscriptions.push(pi.events.on('compact-renderer:inspect:v1', (request: any) => {
|
|
165
|
+
if (disposed || !active || !mode.isEnabled()) return;
|
|
166
|
+
[...cards.values()].filter(card => !view(card.source)?.hidden).forEach((card, index) => request?.add?.({ id: `subagent-${index}`, kind: 'Subagent', label: view(card.source)?.pane.title || card.summary.title, focus() {
|
|
167
|
+
if (disposed || !active || !mode.isEnabled() || cards.get(card.source) !== card) return;
|
|
168
|
+
release(); selected = card; focused = true; (view(card.source)?.pane || card.pane).open = true; redraw?.();
|
|
169
|
+
pi.events.emit('compact-renderer:focus:v1', { owner: 'subagents', label: card.summary.title, target: (component: any) => component === card.component });
|
|
170
|
+
} }));
|
|
171
|
+
}));
|
|
172
|
+
subscriptions.push(mode.onChange(() => { release(); redraw?.(); }));
|
|
173
|
+
const dispose = () => { if (disposed) return; disposed = true; subscriptions.forEach(off => off?.()); const repaint = redraw; stop(); adapter?.(); spacing?.(); subagents.release(); if (shared[owner] === dispose) delete shared[owner]; repaint?.(); };
|
|
174
|
+
shared[owner] = dispose;
|
|
175
|
+
return dispose;
|
|
176
|
+
}
|