@each1024/pi-mini-mode 1.3.1 → 1.3.2

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