@each1024/pi-mini-mode 2.0.8 → 2.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -6
- package/README.zh-CN.md +6 -8
- package/extensions/footer-status.ts +46 -1185
- package/lib/agent-render.ts +203 -0
- package/lib/agent-state.ts +199 -0
- package/lib/agent-view.ts +5 -519
- package/lib/agent-widgets.ts +129 -0
- package/lib/footer-line.ts +206 -0
- package/lib/input-editor-paths.ts +79 -0
- package/lib/input-editor.ts +184 -0
- package/lib/input-enhancements-types.ts +49 -0
- package/lib/input-enhancements.ts +15 -797
- package/lib/input-hover-preview.ts +122 -0
- package/lib/input-image-graphics.ts +34 -0
- package/lib/input-image-paths.ts +120 -0
- package/lib/input-inline-images.ts +114 -0
- package/lib/input-skill-completion.ts +132 -0
- package/lib/minimal-output.ts +379 -0
- package/lib/minimal-turns.ts +203 -0
- package/lib/settings-web.ts +9 -2
- package/lib/settings.html +5 -4
- package/lib/settings.ts +153 -0
- package/lib/thinking-preview.ts +30 -19
- package/lib/thinking-stream.ts +89 -0
- package/lib/transcript-adapter.ts +15 -501
- package/lib/transcript-cards.ts +67 -0
- package/lib/transcript-notice-render.ts +211 -0
- package/lib/transcript-notices.ts +238 -0
- package/lib/usage.ts +137 -0
- package/package.json +4 -2
package/lib/agent-view.ts
CHANGED
|
@@ -1,520 +1,6 @@
|
|
|
1
|
-
import { diagramMarkdown, isMarkdownProse, renderMinimalMarkdown } from "./minimal-markdown.ts";
|
|
2
|
-
import { extractNoticeBody, supervisorNoticeBody } from "./transcript-adapter.ts";
|
|
3
|
-
import { paintExpandedHeading } from "./minimal-theme.ts";
|
|
4
|
-
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
5
|
-
import { join, resolve } from "node:path";
|
|
6
|
-
import { tmpdir } from "node:os";
|
|
7
|
-
import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
-
import { Markdown, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
|
|
9
1
|
|
|
10
|
-
|
|
11
|
-
export
|
|
12
|
-
export
|
|
13
|
-
export
|
|
14
|
-
|
|
15
|
-
name: string;
|
|
16
|
-
task: string;
|
|
17
|
-
tool?: string;
|
|
18
|
-
action?: string;
|
|
19
|
-
state: "running" | "done" | "error";
|
|
20
|
-
output?: string;
|
|
21
|
-
startedAt?: number;
|
|
22
|
-
endedAt?: number;
|
|
23
|
-
}
|
|
24
|
-
export function agentCallDisplay(call: AgentCall): { summary: string; detail: string } {
|
|
25
|
-
if (isAgentTool(call.tool ?? call.name)) return {
|
|
26
|
-
summary: `${call.tool ?? call.name} · ${call.action || "dispatch"} · ${call.state === "running" ? "waiting for receipt" : call.state === "error" ? "failed" : "returned"}`,
|
|
27
|
-
detail: call.output ?? call.task,
|
|
28
|
-
};
|
|
29
|
-
const receipt = call.output?.match(/\bAsync workflow \[([^\]\n]+)\]/);
|
|
30
|
-
if (receipt) return { summary: `Workflow ${receipt[1]} · dispatched`, detail: "" };
|
|
31
|
-
return {
|
|
32
|
-
summary: call.state !== "error" && /^(read|write|edit|bash|grep|find|ls)$/.test(call.name) ? call.task || call.output || "" : call.output ?? call.task,
|
|
33
|
-
detail: call.state === "error" ? call.output ?? "" : "",
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
export const isAgentTool = (name: string) => /^(subagent(?:_supervisor)?|agents?|get_subagent_result|steer_subagent|bg_wait)$/i.test(name);
|
|
37
|
-
export function agentCall(id: string, tool: string, args: unknown): AgentCall {
|
|
38
|
-
const data = (args && typeof args === "object" ? args : {}) as Record<string, unknown>;
|
|
39
|
-
const name = String(data.agent ?? data.subagent_type ?? data.agent_type ?? tool);
|
|
40
|
-
return { id, name, tool, action: typeof data.action === "string" ? data.action : undefined, task: String(data.task ?? data.prompt ?? data.description ?? data.action ?? data.command ?? data.path ?? ""), state: "running" };
|
|
41
|
-
}
|
|
42
|
-
export function agentCallRows(calls: AgentCall[], theme: Theme, width: number, expanded: boolean,
|
|
43
|
-
markdown: (text: string, width: number) => string[]): string[] {
|
|
44
|
-
if (!calls.length || width < 1) return [];
|
|
45
|
-
const running = calls.filter(call => call.state === "running").length;
|
|
46
|
-
const errors = calls.filter(call => call.state === "error").length;
|
|
47
|
-
const done = calls.length - running - errors;
|
|
48
|
-
const header = `${expanded ? "⌄" : "›"} Agent calls · ${calls.length} total · ${running} running · ${done} returned${errors ? ` · ${errors} failed` : ""} · Ctrl+O`;
|
|
49
|
-
const rows = [truncateToWidth(theme.fg(errors ? "error" : running ? "accent" : "muted", header), width)];
|
|
50
|
-
if (expanded) calls.forEach((call, index) => {
|
|
51
|
-
const color = call.state === "error" ? "error" : call.state === "done" ? "success" : "accent";
|
|
52
|
-
const glyph = call.state === "error" ? "✗" : call.state === "done" ? "✓" : "●";
|
|
53
|
-
rows.push(truncateToWidth(theme.fg(color, `${index === calls.length - 1 ? "└─" : "├─"} ${glyph} ${call.name}`), width));
|
|
54
|
-
for (const text of [call.task, call.output]) {
|
|
55
|
-
if (text) rows.push(...markdown(text, Math.max(1, width - 3)).map(row => truncateToWidth(` ${row}`, width, "")));
|
|
56
|
-
}
|
|
57
|
-
});
|
|
58
|
-
return rows;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
const plain = (text: string) => text.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").trim();
|
|
62
|
-
|
|
63
|
-
/** Child gate JSON is for the runtime, not the transcript. */
|
|
64
|
-
export function stripAcceptanceReport(output: string): string {
|
|
65
|
-
return output
|
|
66
|
-
.replace(/\n?```acceptance[-_]report\s*\n[\s\S]*?```\s*$/i, "")
|
|
67
|
-
.replace(/\n?ACCEPTANCE_REPORT\s*:\s*\{[\s\S]*\}\s*$/i, "")
|
|
68
|
-
.trimEnd();
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** Recover the child's own prose and raw tool inputs from its session, never from activity previews. */
|
|
72
|
-
const childSessionCache = new Map<string, { stamp: string; thinking: string; finalOutput: string; latestText: string; inputs: Array<{ name: string; value: string }> }>();
|
|
73
|
-
const singleLine = (value: string) => plain(value).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ");
|
|
74
|
-
function childSessionData(sessionFile: unknown) {
|
|
75
|
-
if (typeof sessionFile !== "string") return undefined;
|
|
76
|
-
try {
|
|
77
|
-
const stat = statSync(sessionFile);
|
|
78
|
-
const stamp = `${stat.mtimeMs}:${stat.size}`;
|
|
79
|
-
let cached = childSessionCache.get(sessionFile);
|
|
80
|
-
if (!cached || cached.stamp !== stamp) {
|
|
81
|
-
const inputs: Array<{ name: string; value: string }> = [];
|
|
82
|
-
let thinking = "";
|
|
83
|
-
let finalOutput = "";
|
|
84
|
-
let latestText = "";
|
|
85
|
-
for (const line of readFileSync(sessionFile, "utf8").split(/\r?\n/)) {
|
|
86
|
-
try {
|
|
87
|
-
const entry = JSON.parse(line) as { type?: string; thinkingLevel?: string; message?: { role?: string; stopReason?: string; channel?: string; content?: Array<{ type?: string; text?: string; name?: string; input?: Record<string, unknown>; arguments?: Record<string, unknown> } | null> } };
|
|
88
|
-
if (entry.type === "thinking_level_change" && /^(off|minimal|low|medium|high|xhigh|max)$/.test(entry.thinkingLevel ?? "")) thinking = entry.thinkingLevel!;
|
|
89
|
-
if (entry.message?.role !== "assistant") continue;
|
|
90
|
-
const message = entry.message;
|
|
91
|
-
const content = Array.isArray(message.content) ? message.content : [];
|
|
92
|
-
const text = content.filter(block => block?.type === "text" && typeof block.text === "string").map(block => block!.text).join("\n\n").trim();
|
|
93
|
-
// Pi persists no channel: only a stopped assistant text reply is a final answer.
|
|
94
|
-
finalOutput = entry.type === "message" && message.stopReason === "stop"
|
|
95
|
-
&& (message.channel === undefined || message.channel === "final")
|
|
96
|
-
&& !content.some(block => block?.type === "toolCall")
|
|
97
|
-
? text : "";
|
|
98
|
-
// Narration attached to a tool call is still the child's own prose; it
|
|
99
|
-
// is the only body a running or tool-ended child has.
|
|
100
|
-
if (entry.type === "message" && text) latestText = text;
|
|
101
|
-
for (const call of content) {
|
|
102
|
-
if (!call) continue;
|
|
103
|
-
if (call.type !== "toolCall" || typeof call.name !== "string") continue;
|
|
104
|
-
const input = call.arguments ?? call.input ?? {};
|
|
105
|
-
const value = [input.path, input.command, input.pattern, input.query, input.task, input.prompt]
|
|
106
|
-
.find((candidate): candidate is string => typeof candidate === "string") ?? "";
|
|
107
|
-
if (value) inputs.push({ name: call.name, value: singleLine(value) });
|
|
108
|
-
}
|
|
109
|
-
} catch { /* A concurrently written session can end with a partial line. */ }
|
|
110
|
-
}
|
|
111
|
-
cached = { stamp, thinking, finalOutput, latestText, inputs };
|
|
112
|
-
childSessionCache.set(sessionFile, cached);
|
|
113
|
-
}
|
|
114
|
-
return cached;
|
|
115
|
-
} catch { return undefined; }
|
|
116
|
-
}
|
|
117
|
-
function rawToolInput(sessionFile: unknown, tool: unknown, preview: string): string {
|
|
118
|
-
if (typeof tool !== "string" || !preview.endsWith("...")) return preview;
|
|
119
|
-
const prefix = singleLine(preview.slice(0, -3));
|
|
120
|
-
return [...(childSessionData(sessionFile)?.inputs ?? [])].reverse().find(input => input.name === tool && input.value.startsWith(prefix))?.value ?? preview;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
const isAgentWidget = (source: string) => /^(?:[●○◉✓✗×\u2800-\u28ff]\s*)?(?:async subagent|Async agents|subagents\b|[│├└─\s]*async workflow)/i.test(source);
|
|
124
|
-
/** Presentation adapter for pi-subagents' independently updated widget.
|
|
125
|
-
* Unknown widget formats pass through unchanged; no task state is inferred.
|
|
126
|
-
*/
|
|
127
|
-
export function restyleAgentWidget(lines: string[], theme: Theme, width: number, expanded: boolean): string[] {
|
|
128
|
-
const content = lines.map(plain).filter(Boolean);
|
|
129
|
-
if (!content.length || !isAgentWidget(content[0])) return lines;
|
|
130
|
-
const details = content.slice(1).map(line => line
|
|
131
|
-
.replace(/^[│├└─\s]+/, "")
|
|
132
|
-
.replace(/(?:[·•]\s*)?Press\s+ctrl\+.*$/i, "")
|
|
133
|
-
.replace(/(?:[·•]\s*)?Ctrl\+Alt\+F\s+Fleet.*$/i, "").trim())
|
|
134
|
-
.filter(line => line && !/^async workflow\b|^[…+] .*lines hidden\b/i.test(line));
|
|
135
|
-
const isHeading = (line: string) => /^(?:[└├]─\s*)?[●○◉✓✗×◦■\u2800-\u28ff]\s/.test(line)
|
|
136
|
-
&& !/^[│⎿]/.test(line);
|
|
137
|
-
const blocks: string[][] = [];
|
|
138
|
-
for (const line of details) {
|
|
139
|
-
if (!blocks.length || isHeading(line)) blocks.push([line]);
|
|
140
|
-
else blocks[blocks.length - 1].push(line);
|
|
141
|
-
}
|
|
142
|
-
const isDone = (block: string[]) => /\b(complete|completed|done|success|succeeded)\b/i.test(block[0]) || /^✓/.test(block[0]);
|
|
143
|
-
const isFailed = (block: string[]) => /\b(failed|error|rejected|stopped|cancelled|canceled|aborted)\b/i.test(block[0]) || /^[✗×]/.test(block[0]);
|
|
144
|
-
const done = blocks.filter(block => isDone(block) && !isFailed(block)).length;
|
|
145
|
-
const errors = blocks.filter(isFailed).length;
|
|
146
|
-
const visible = blocks.filter(block => expanded || isFailed(block) || !isDone(block));
|
|
147
|
-
const rows = [agentSummary(theme, width, blocks.length - done - errors, done, errors, expanded)];
|
|
148
|
-
if (!blocks.length) rows.push(truncateToWidth(theme.fg("text", content[0]), width));
|
|
149
|
-
const markdown = (text: string, available: number) => renderMinimalMarkdown(text, Math.max(1, available), getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
|
|
150
|
-
{ color: value => theme.fg("text", value) }, diagramMarkdown);
|
|
151
|
-
// ponytail: native widget exposes bounded live previews, not the full child transcript.
|
|
152
|
-
visible.forEach((block, index) => {
|
|
153
|
-
const heading = block[0].replace(/^(?:[└├]─\s*)?[●○◉✓✗×◦■\u2800-\u28ff]\s*/, "");
|
|
154
|
-
const badge = heading.match(/\(([^()]+?)(?:\s*·\s*thinking\s+|[ :]+)(off|minimal|low|medium|high|xhigh|max)\)/)
|
|
155
|
-
?? heading.match(/\(([^()]+)\)(?=\s*(?:·|$))/);
|
|
156
|
-
const title = heading.split(" · ")[0].replace(/\s*\([^()]*\)\s*$/, "");
|
|
157
|
-
const identity = badge ? theme.fg("accent", theme.bold(title)) + theme.fg("muted", " · ") + theme.fg("accent", theme.bold(badge[1])) + (badge[2] ? theme.fg("muted", ` ${badge[2]}`) : "")
|
|
158
|
-
: theme.fg("accent", theme.bold(heading.split(" · ")[0]));
|
|
159
|
-
const activity = block.slice(1).filter(line => !/^(?:task|output)\s*:/i.test(line));
|
|
160
|
-
const latest = activity.at(-1)?.replace(/^[⎿│]\s*/, "") || block.slice(1).find(line => /^task\s*:/i.test(line)) || heading;
|
|
161
|
-
const glyph = /\b(failed|error|rejected)\b/i.test(heading) || /^[✗×]/.test(block[0]) ? "×"
|
|
162
|
-
: /\b(running|active|starting|queued|pending)\b/i.test(heading) || /^[\u2800-\u28ff]/.test(block[0]) ? runningGlyph() : "●";
|
|
163
|
-
const prefix = theme.fg("accent", index === visible.length - 1 ? "└─ " : "├─ ")
|
|
164
|
-
+ theme.fg(glyph === "×" ? "error" : "accent", glyph + " ") + identity + theme.fg("text", " : ");
|
|
165
|
-
const summary = /\b(failed|error)\b/i.test(heading + " " + latest)
|
|
166
|
-
? theme.fg("error", latest)
|
|
167
|
-
: markdown(latest, Math.max(1, visibleWidth(latest) + 1)).join(" ");
|
|
168
|
-
rows.push(truncateToWidth(prefix + summary, width));
|
|
169
|
-
});
|
|
170
|
-
return rows;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
function agentSummary(theme: Theme, width: number, running: number, done: number, errors: number, expanded: boolean): string {
|
|
174
|
-
const label = `Sub Agent · running ${running}${done ? ` · done ${done}` : ""}${errors ? ` · failed ${errors}` : ""}${done ? ` · Ctrl+S ${expanded ? "collapse" : "expand"}` : ""}`;
|
|
175
|
-
const summary = truncateToWidth(theme.fg(errors ? "error" : "muted", label), width);
|
|
176
|
-
return " ".repeat(Math.max(0, width - visibleWidth(summary))) + summary;
|
|
177
|
-
}
|
|
178
|
-
const finishedAgent = (state: unknown) => /^(complete|completed|done|success|succeeded)$/.test(String(state));
|
|
179
|
-
const failedAgent = (node: Record<string, unknown>) => !!node.error || /^(failed|error|stopped|rejected|cancelled|canceled|aborted)$/.test(String(node.status ?? node.state));
|
|
180
|
-
const timestamp = (value: unknown): number | undefined => typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
181
|
-
function formatAgentElapsed(startedAt: number, endedAt: number): string {
|
|
182
|
-
const seconds = Math.max(0, Math.floor((endedAt - startedAt) / 1_000));
|
|
183
|
-
const minutes = Math.floor(seconds / 60);
|
|
184
|
-
const remainder = String(seconds % 60).padStart(2, "0");
|
|
185
|
-
return minutes >= 60 ? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${remainder}` : `${minutes}:${remainder}`;
|
|
186
|
-
}
|
|
187
|
-
// Only hide the passive native agent summary, preserving the interactive fleet and external jobs/panes.
|
|
188
|
-
const isAgentFleetSummary = (lines: string[]) => {
|
|
189
|
-
const content = lines.map(plain).filter(Boolean);
|
|
190
|
-
return content.length === 1 && /^\d+ active agents?\b/.test(content[0])
|
|
191
|
-
&& !/\b(?:jobs?|panes?)\b/.test(content[0]);
|
|
192
|
-
};
|
|
193
|
-
|
|
194
|
-
export const AGENT_STATUS_ENTRY = "pi-mini-mode-agent-status";
|
|
195
|
-
|
|
196
|
-
export function savedAgentStatuses(entries: unknown[]): Record<string, unknown>[] {
|
|
197
|
-
const saved = new Map<string, Record<string, unknown>>();
|
|
198
|
-
for (const value of entries) {
|
|
199
|
-
const entry = value as { type?: string; customType?: string; data?: Record<string, unknown> } | null;
|
|
200
|
-
if (entry?.type === "custom" && entry.customType === AGENT_STATUS_ENTRY
|
|
201
|
-
&& entry.data && typeof entry.data.runId === "string") saved.set(entry.data.runId, entry.data);
|
|
202
|
-
}
|
|
203
|
-
return [...saved.values()];
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
/** Keep observed snapshots even after the producer cleans its temporary directory. */
|
|
207
|
-
export function retainAgentStatuses(previous: Record<string, unknown>[], current: Record<string, unknown>[]): Record<string, unknown>[] {
|
|
208
|
-
const retained = new Map(previous.map(status => [String(status.runId), status]));
|
|
209
|
-
for (const status of new Map([...previous, ...current].map(status => [String(status.runId), status])).values()) {
|
|
210
|
-
const saved = retained.get(String(status.runId));
|
|
211
|
-
const children = agentChildren([status]).map(child => {
|
|
212
|
-
const previous = saved && agentChildren([saved]).find(item => item.displayId === child.displayId);
|
|
213
|
-
const sameAttempt = previous?.sessionFile === child.sessionFile && previous?.startedAt === child.startedAt;
|
|
214
|
-
const finalOutput = childSessionData(child.sessionFile)?.finalOutput ?? child.finalOutput ?? (sameAttempt ? previous?.finalOutput : undefined);
|
|
215
|
-
return { ...child, finalOutput, notice: child.notice ?? previous?.notice, noticeMessages: child.noticeMessages ?? previous?.noticeMessages };
|
|
216
|
-
});
|
|
217
|
-
retained.set(String(status.runId), children.length
|
|
218
|
-
? { ...status, steps: children, workflowChildren: undefined, children: undefined } : status);
|
|
219
|
-
}
|
|
220
|
-
return [...retained.values()];
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// ponytail: pi-subagents status.json adapter; replace with an uncapped public snapshot API when available.
|
|
224
|
-
export function readAgentStatuses(sessionId: string, root = process.env.PI_SUBAGENTS_TEMP_ROOT?.trim()
|
|
225
|
-
? resolve(process.env.PI_SUBAGENTS_TEMP_ROOT) : join(tmpdir(), `pi-subagents-uid-${process.getuid?.()}`), previous: Record<string, unknown>[] = []): Record<string, unknown>[] {
|
|
226
|
-
if (!sessionId) return [];
|
|
227
|
-
const directory = join(root, "async-subagent-runs");
|
|
228
|
-
try {
|
|
229
|
-
return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
|
|
230
|
-
if (!entry.isDirectory()) return [];
|
|
231
|
-
try {
|
|
232
|
-
const status = JSON.parse(readFileSync(join(directory, entry.name, "status.json"), "utf8"));
|
|
233
|
-
return status && status.sessionId === sessionId ? [status] : [];
|
|
234
|
-
} catch {
|
|
235
|
-
// Retain the last valid snapshot during replacement; never flash an empty panel.
|
|
236
|
-
return previous.filter(status => status.sessionId === sessionId && status.runId === entry.name);
|
|
237
|
-
}
|
|
238
|
-
});
|
|
239
|
-
} catch { return previous.filter(status => status.sessionId === sessionId); }
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
export function currentAgentStatuses(statuses: Record<string, unknown>[], callsOrIds: unknown[]): Record<string, unknown>[] {
|
|
243
|
-
const callIds = new Set<string>();
|
|
244
|
-
const runIds = new Set<string>();
|
|
245
|
-
for (const item of callsOrIds) {
|
|
246
|
-
if (typeof item === "string") {
|
|
247
|
-
callIds.add(item);
|
|
248
|
-
const match = item.match(/\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/i);
|
|
249
|
-
if (match) runIds.add(match[1]);
|
|
250
|
-
} else if (item && typeof item === "object") {
|
|
251
|
-
const call = item as Record<string, unknown>;
|
|
252
|
-
if (typeof call.id === "string") callIds.add(call.id);
|
|
253
|
-
const text = `${call.output ?? ""} ${call.task ?? ""} ${call.action ?? ""}`;
|
|
254
|
-
const matches = text.matchAll(/\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/gi);
|
|
255
|
-
for (const m of matches) runIds.add(m[1]);
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
const selected = new Set<string>();
|
|
259
|
-
for (const status of statuses) {
|
|
260
|
-
const runId = String(status.runId ?? "");
|
|
261
|
-
const toolCallId = String(status.toolCallId ?? "");
|
|
262
|
-
if ((toolCallId && callIds.has(toolCallId)) || (runId && runIds.has(runId))) {
|
|
263
|
-
if (runId) selected.add(runId);
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
for (let size = -1; size !== selected.size;) {
|
|
267
|
-
size = selected.size;
|
|
268
|
-
for (const status of statuses) {
|
|
269
|
-
const parentId = String(status.parentWorkflowRunId ?? "");
|
|
270
|
-
if (parentId && selected.has(parentId)) selected.add(String(status.runId));
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
return statuses.filter(status => selected.has(String(status.runId)));
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
/** Associate each status only with the user turn that dispatched its tool call.
|
|
277
|
-
* Status snapshots are session-wide and can update after later turns begin.
|
|
278
|
-
*/
|
|
279
|
-
export function agentStatusesByTurn(statuses: Record<string, unknown>[], turns: Array<{ agentCalls?: unknown[] }>): Map<number, Record<string, unknown>[]> {
|
|
280
|
-
const assigned = new Map<number, Record<string, unknown>[]>();
|
|
281
|
-
const claimed = new Set<string>();
|
|
282
|
-
for (const [index, turn] of turns.entries()) {
|
|
283
|
-
const matched = currentAgentStatuses(statuses, turn.agentCalls ?? []).filter(status => {
|
|
284
|
-
const runId = String(status.runId ?? "");
|
|
285
|
-
return !runId || !claimed.has(runId);
|
|
286
|
-
});
|
|
287
|
-
assigned.set(index, matched);
|
|
288
|
-
for (const status of matched) {
|
|
289
|
-
const runId = String(status.runId ?? "");
|
|
290
|
-
if (runId) claimed.add(runId);
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
return assigned;
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
export function agentChildren(statuses: Record<string, unknown>[]): Record<string, unknown>[] {
|
|
297
|
-
const children = new Map<string, Record<string, unknown>>();
|
|
298
|
-
const visit = (value: unknown, key: string) => {
|
|
299
|
-
if (!value || typeof value !== "object") return;
|
|
300
|
-
const node = value as Record<string, unknown>;
|
|
301
|
-
if (typeof node.agent === "string") {
|
|
302
|
-
const id = String(node.runId ?? (node.childId ? `${key}:${node.childId}` : key));
|
|
303
|
-
const previous = children.get(id);
|
|
304
|
-
children.set(id, { ...previous, ...node, displayId: id, model: node.model || previous?.model, thinking: node.thinking || previous?.thinking });
|
|
305
|
-
}
|
|
306
|
-
const inventory = node.workflowChildren as { children?: unknown[] } | undefined;
|
|
307
|
-
if (Array.isArray(inventory?.children)) inventory.children.forEach((child, i) => visit(child, `${key}/steps/${i}`));
|
|
308
|
-
if (Array.isArray(node.steps)) node.steps.forEach((child, i) => visit(child, `${key}/steps/${i}`));
|
|
309
|
-
if (Array.isArray(node.children)) node.children.forEach((child, i) => visit(child, `${key}/children/${i}`));
|
|
310
|
-
};
|
|
311
|
-
// Workflow snapshots can lag behind the child. Merge their metadata first,
|
|
312
|
-
// then apply the child's own snapshot regardless of directory iteration order.
|
|
313
|
-
for (const status of [...statuses.filter(status => status.mode !== "single"), ...statuses.filter(status => status.mode === "single")]) {
|
|
314
|
-
if (status.mode === "single" && Array.isArray(status.steps) && status.steps.length === 1) {
|
|
315
|
-
const terminal = finishedAgent(status.state) || failedAgent(status);
|
|
316
|
-
visit({ ...status.steps[0], runId: status.runId, startedAt: status.steps[0].startedAt ?? status.startedAt,
|
|
317
|
-
notice: status.notice ?? status.steps[0].notice, noticeMessages: status.noticeMessages ?? status.steps[0].noticeMessages,
|
|
318
|
-
...(terminal ? { status: status.state, endedAt: status.steps[0].endedAt ?? status.endedAt, error: status.error ?? status.steps[0].error } : {}),
|
|
319
|
-
}, String(status.runId));
|
|
320
|
-
} else visit({ ...status, notice: status.notice, noticeMessages: status.noticeMessages }, String(status.runId));
|
|
321
|
-
}
|
|
322
|
-
return [...children.values()];
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
/** Retained for callers that share a render-state map across the current session. */
|
|
326
|
-
export type AgentDeadlines = Map<string, number>;
|
|
327
|
-
|
|
328
|
-
/** One snapshot drives both the inline count and its uncapped child rows. */
|
|
329
|
-
export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme, width: number, expanded = false, _activeOnly = false,
|
|
330
|
-
deadlines: AgentDeadlines = new Map(), now = Date.now(), expandedIds?: Set<string>,
|
|
331
|
-
subagentControls?: Array<{ runId: string; y: number; width: number; line: string }>) {
|
|
332
|
-
// Live and session-persisted snapshots share the same lifecycle and details.
|
|
333
|
-
const all = agentChildren(statuses);
|
|
334
|
-
const errors = all.filter(failedAgent).length;
|
|
335
|
-
const done = all.filter(child => !failedAgent(child) && finishedAgent(child.status ?? child.state)).length;
|
|
336
|
-
const rows: string[] = [];
|
|
337
|
-
const text = (value: unknown) => typeof value === "string" ? plain(value).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ") : "";
|
|
338
|
-
const bodyText = (value: unknown) => typeof value === "string"
|
|
339
|
-
? stripAcceptanceReport(plain(value).replace(/[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/g, " ")).trim() : "";
|
|
340
|
-
const renderBody = (source: string, available: number) => {
|
|
341
|
-
const width = Math.max(1, available);
|
|
342
|
-
if (isMarkdownProse(source)) return renderMinimalMarkdown(source, width, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
|
|
343
|
-
{ color: value => theme.fg("muted", value) }, diagramMarkdown);
|
|
344
|
-
// Wrap by visible columns. Do not re-slice truncateToWidth: it appends a
|
|
345
|
-
// reset, so slice(row.length) would drop source characters on every wrap.
|
|
346
|
-
return wrapTextWithAnsi(source, width).map(row => theme.fg("muted", row));
|
|
347
|
-
};
|
|
348
|
-
if (width > 0) all.forEach((child, index) => {
|
|
349
|
-
const runKey = String(child.runId ?? child.displayId);
|
|
350
|
-
const isChildExpanded = expanded || (expandedIds?.has(runKey) ?? false);
|
|
351
|
-
const notice = child.notice as { summary?: string; state?: string; color?: "error" | "warning" | "muted"; alert?: boolean; internal?: boolean } | undefined;
|
|
352
|
-
const model = text(child.model).split("/").at(-1) || "";
|
|
353
|
-
const suffix = model.match(/:(off|minimal|low|medium|high|xhigh|max)$/);
|
|
354
|
-
const level = text(child.thinking) || suffix?.[1] || childSessionData(child.sessionFile)?.thinking || "?";
|
|
355
|
-
const tools = Array.isArray(child.recentTools) ? child.recentTools.filter(tool => tool && typeof tool === "object") : [];
|
|
356
|
-
const latest = tools.at(-1);
|
|
357
|
-
const latestArgs = rawToolInput(child.sessionFile, latest?.tool, text(latest?.args));
|
|
358
|
-
const activity = notice?.summary
|
|
359
|
-
|| text(child.error)
|
|
360
|
-
|| [text(child.currentTool), text(child.currentPath || child.currentToolArgs)].filter(Boolean).join(" ")
|
|
361
|
-
|| [text(latest?.tool), latestArgs].filter(Boolean).join(" ")
|
|
362
|
-
|| text(child.description) || text(child.status ?? child.state) || "waiting";
|
|
363
|
-
// Tool inputs are literal code, not Markdown (heredocs can contain HTML-like text).
|
|
364
|
-
const body = latest || child.currentTool ? text(activity) : text(renderMinimalMarkdown(activity, Math.max(1, visibleWidth(activity) + 1), getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "", undefined, diagramMarkdown).join(" "));
|
|
365
|
-
const state = text(child.status ?? child.state) || "waiting";
|
|
366
|
-
const terminal = failedAgent(child) || finishedAgent(state);
|
|
367
|
-
const isRunning = /^(running|active|starting|queued|pending)$/.test(state);
|
|
368
|
-
const glyph = failedAgent(child) || notice?.color === "error" ? "×"
|
|
369
|
-
: notice?.color === "warning" ? "⚠"
|
|
370
|
-
: finishedAgent(state) ? "✓"
|
|
371
|
-
: isRunning ? runningGlyph(now) : "●";
|
|
372
|
-
const color = "text";
|
|
373
|
-
// Status snapshots, not the dispatch tool receipt, define a child run's lifecycle.
|
|
374
|
-
// Preserve a terminal observation when an older pi-subagents status omits endedAt.
|
|
375
|
-
const elapsedKey = `elapsed:${runKey}`;
|
|
376
|
-
const startedAt = timestamp(child.startedAt) ?? deadlines.get(elapsedKey) ?? now;
|
|
377
|
-
if (!timestamp(child.startedAt)) deadlines.set(elapsedKey, startedAt);
|
|
378
|
-
const endedAt = terminal ? timestamp(child.endedAt) ?? deadlines.get(`${elapsedKey}:ended`) ?? now : now;
|
|
379
|
-
if (terminal) deadlines.set(`${elapsedKey}:ended`, endedAt);
|
|
380
|
-
const elapsed = formatAgentElapsed(startedAt, endedAt);
|
|
381
|
-
const identity = isChildExpanded ? "accent" : color;
|
|
382
|
-
const heading = truncateToWidth(theme.fg(isChildExpanded ? "accent" : "dim", `${index === all.length - 1 ? "└─" : "├─"} `)
|
|
383
|
-
+ theme.fg(failedAgent(child) || notice?.color === "error" ? "error" : notice?.color === "warning" ? "warning" : isRunning && !terminal ? "accent" : "muted", `${glyph} `)
|
|
384
|
-
+ theme.fg(identity, theme.bold("SubAgent"))
|
|
385
|
-
+ theme.fg(identity, ` • ${suffix ? model.slice(0, -suffix[0].length) : model}`)
|
|
386
|
-
+ (level ? theme.fg("muted", ` ${level}`) : "") + theme.fg(terminal ? "muted" : "success", ` ${elapsed}`) + theme.fg(identity, " : "), width, "…");
|
|
387
|
-
const bodyBudget = Math.max(0, width - visibleWidth(heading));
|
|
388
|
-
const progress = !bodyBudget ? "" : truncateToWidth(body, bodyBudget, "…");
|
|
389
|
-
const row = heading + theme.fg(isChildExpanded ? "accent" : "muted", progress);
|
|
390
|
-
const padded = row + " ".repeat(Math.max(0, width - visibleWidth(row)));
|
|
391
|
-
const line = isChildExpanded ? paintExpandedHeading(theme, padded) : padded;
|
|
392
|
-
subagentControls?.push({ runId: runKey, y: rows.length, width, line });
|
|
393
|
-
rows.push(line);
|
|
394
|
-
if (isChildExpanded) {
|
|
395
|
-
const rail = theme.fg("accent", "│") + " ";
|
|
396
|
-
let processShown = false;
|
|
397
|
-
if (!terminal) {
|
|
398
|
-
const process: Array<{ name: string; args: string }> = tools.slice(-6).map(tool => ({
|
|
399
|
-
name: text(tool.tool) || "tool",
|
|
400
|
-
args: rawToolInput(child.sessionFile, tool.tool, text(tool.args)),
|
|
401
|
-
}));
|
|
402
|
-
if (!process.length && child.currentTool) {
|
|
403
|
-
process.push({ name: text(child.currentTool), args: text(child.currentPath || child.currentToolArgs) });
|
|
404
|
-
}
|
|
405
|
-
for (const item of process) {
|
|
406
|
-
const prefix = `${rail}${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(item.name))}${item.args ? " " : ""}`;
|
|
407
|
-
rows.push(truncateToWidth(prefix + (item.args ? theme.fg("muted", item.args) : ""), width, "…"));
|
|
408
|
-
processShown = true;
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
const messages = Array.isArray(child.noticeMessages) ? child.noticeMessages : [];
|
|
412
|
-
const bodies: string[] = [];
|
|
413
|
-
let latestProgress = "";
|
|
414
|
-
for (const msg of messages) {
|
|
415
|
-
const item = msg && typeof msg === "object" ? msg as Record<string, unknown> : undefined;
|
|
416
|
-
const details = item?.details && typeof item.details === "object" ? item.details as Record<string, unknown> : undefined;
|
|
417
|
-
if (item?.customType === "subagent_supervisor_request" && details?.reason === "progress_update") {
|
|
418
|
-
const progress = extractNoticeBody(msg);
|
|
419
|
-
if (progress) latestProgress = progress;
|
|
420
|
-
continue;
|
|
421
|
-
}
|
|
422
|
-
const b = supervisorNoticeBody(msg);
|
|
423
|
-
if (b && !bodies.includes(b)) bodies.push(b);
|
|
424
|
-
}
|
|
425
|
-
const session = childSessionData(child.sessionFile);
|
|
426
|
-
if (!bodies.length && latestProgress) bodies.push(latestProgress);
|
|
427
|
-
const latestText = bodyText(session?.latestText);
|
|
428
|
-
if (!terminal && latestText && !bodies.length) bodies.push(latestText);
|
|
429
|
-
// A stopped answer outranks the running narration; the narration still
|
|
430
|
-
// covers a child that ended between turns or without a stopped reply.
|
|
431
|
-
const finalOutput = terminal ? bodyText(session?.finalOutput || latestText || child.finalOutput) : "";
|
|
432
|
-
if (finalOutput && !bodies.includes(finalOutput)) bodies.push(finalOutput);
|
|
433
|
-
const error = bodyText(child.error);
|
|
434
|
-
if (error && !bodies.includes(error)) bodies.push(error);
|
|
435
|
-
if (!terminal && !processShown && !bodies.length) {
|
|
436
|
-
rows.push(truncateToWidth(`${rail}${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(text(state)))}`, width, "…"));
|
|
437
|
-
processShown = true;
|
|
438
|
-
}
|
|
439
|
-
for (const [index, textBody] of bodies.entries()) {
|
|
440
|
-
// Child/supervisor bodies are Markdown prose; tool logs and JSON are
|
|
441
|
-
// not placed in this semantic body channel.
|
|
442
|
-
if (processShown || index > 0) rows.push(truncateToWidth(rail, width, ""));
|
|
443
|
-
for (const line of renderBody(textBody, Math.max(1, width - 3))) {
|
|
444
|
-
rows.push(truncateToWidth(`${rail}${line}`, width));
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
});
|
|
449
|
-
return { rows, total: all.length, done, errors, running: all.length - done - errors };
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
export function liveAgentRows(statuses: Record<string, unknown>[], theme: Theme, width: number, expanded = false, deadlines: AgentDeadlines = new Map()): string[] {
|
|
453
|
-
const view = liveAgentView(statuses, theme, width, expanded, false, deadlines);
|
|
454
|
-
return width > 0 && view.total ? [agentSummary(theme, width, view.running, view.done, view.errors, expanded), ...view.rows] : [];
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
/** Pi 0.85 widget containers: preserve unrelated widgets and their lifecycle. */
|
|
458
|
-
export function attachAgentWidgets(tui: unknown, theme: Theme, expanded: () => boolean, statuses?: () => Record<string, unknown>[], inline = false): () => void {
|
|
459
|
-
const host = tui as { children?: Array<Component & { children?: Component[] }> };
|
|
460
|
-
if (host.children?.length !== 7) return () => {};
|
|
461
|
-
const restores: Array<() => void> = [];
|
|
462
|
-
const deadlines: AgentDeadlines = new Map();
|
|
463
|
-
for (const index of [3, 5]) {
|
|
464
|
-
const container = host.children[index];
|
|
465
|
-
if (!Array.isArray(container?.children)) continue;
|
|
466
|
-
const descriptor = Object.getOwnPropertyDescriptor(container, "render");
|
|
467
|
-
const mouseDescriptor = Object.getOwnPropertyDescriptor(container, "handleMouse");
|
|
468
|
-
const render = (width: number) => {
|
|
469
|
-
const live = !inline && statuses ? liveAgentRows(statuses(), theme, width, expanded(), deadlines) : [];
|
|
470
|
-
let inserted = false;
|
|
471
|
-
const rows = container.children!.flatMap(child => {
|
|
472
|
-
const original = child.render(width);
|
|
473
|
-
if (inline && (isAgentWidget(original.map(plain).find(Boolean) ?? "") || isAgentFleetSummary(original))) return [];
|
|
474
|
-
if (statuses && live.length && isAgentFleetSummary(original)) return [];
|
|
475
|
-
const source = original.map(plain).find(Boolean) ?? "";
|
|
476
|
-
const agentWidget = isAgentWidget(source);
|
|
477
|
-
if (statuses && agentWidget) {
|
|
478
|
-
if (inserted || index !== 3) return [];
|
|
479
|
-
inserted = true;
|
|
480
|
-
return live;
|
|
481
|
-
}
|
|
482
|
-
return restyleAgentWidget(original, theme, width, expanded());
|
|
483
|
-
});
|
|
484
|
-
if (index === 3 && !inserted) rows.push(...live);
|
|
485
|
-
return rows;
|
|
486
|
-
};
|
|
487
|
-
const mouse: NonNullable<Component["handleMouse"]> = (event) => {
|
|
488
|
-
let y = 0;
|
|
489
|
-
let inserted = false;
|
|
490
|
-
const live = !inline && statuses ? liveAgentRows(statuses(), theme, event.width, expanded(), deadlines) : [];
|
|
491
|
-
|
|
492
|
-
for (const child of container.children!) {
|
|
493
|
-
const original = child.render(event.width);
|
|
494
|
-
if (inline && (isAgentWidget(original.map(plain).find(Boolean) ?? "") || isAgentFleetSummary(original))) continue;
|
|
495
|
-
if (statuses && live.length && isAgentFleetSummary(original)) continue;
|
|
496
|
-
const agentWidget = isAgentWidget(original.map(plain).find(Boolean) ?? "");
|
|
497
|
-
const shown = statuses && agentWidget ? (index === 3 && !inserted ? live : [])
|
|
498
|
-
: restyleAgentWidget(original, theme, event.width, expanded());
|
|
499
|
-
if (agentWidget) inserted = true;
|
|
500
|
-
if (event.y >= y && event.y < y + shown.length) {
|
|
501
|
-
// Do not route clicks into native controls hidden by the compact view.
|
|
502
|
-
return shown === original ? child.handleMouse?.({ ...event, y: event.y - y, height: shown.length }) : undefined;
|
|
503
|
-
}
|
|
504
|
-
y += shown.length;
|
|
505
|
-
}
|
|
506
|
-
};
|
|
507
|
-
container.render = render;
|
|
508
|
-
container.handleMouse = mouse;
|
|
509
|
-
restores.push(() => {
|
|
510
|
-
if (container.handleMouse === mouse) {
|
|
511
|
-
if (mouseDescriptor) Object.defineProperty(container, "handleMouse", mouseDescriptor);
|
|
512
|
-
else delete container.handleMouse;
|
|
513
|
-
}
|
|
514
|
-
if (container.render !== render) return;
|
|
515
|
-
if (descriptor) Object.defineProperty(container, "render", descriptor);
|
|
516
|
-
else delete (container as Partial<Component>).render;
|
|
517
|
-
});
|
|
518
|
-
}
|
|
519
|
-
return () => { deadlines.clear(); restores.forEach(restore => restore()); };
|
|
520
|
-
}
|
|
2
|
+
/** Public agent view API; persistence and terminal rendering have separate lifecycles. */
|
|
3
|
+
export { AGENT_STATUS_ENTRY, stripAcceptanceReport, savedAgentStatuses, retainAgentStatuses, readAgentStatuses, currentAgentStatuses, agentStatusesByTurn, agentChildren } from "./agent-state.ts";
|
|
4
|
+
export { RUNNING_FRAMES, runningGlyph, agentCallDisplay, isAgentTool, agentCall, agentCallRows, liveAgentView, liveAgentRows } from "./agent-render.ts";
|
|
5
|
+
export type { AgentCall, AgentDeadlines } from "./agent-render.ts";
|
|
6
|
+
export { restyleAgentWidget, attachAgentWidgets } from "./agent-widgets.ts";
|