@each1024/pi-mini-mode 2.0.18 → 2.0.20

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.
@@ -2,6 +2,8 @@ import { diagramMarkdown, isMarkdownProse, renderMinimalMarkdown } from "./minim
2
2
  import { extractNoticeBody, supervisorNoticeBody } from "./transcript-notices.ts";
3
3
  import { paintExpandedHeading } from "./minimal-theme.ts";
4
4
  import { agentChildren, childSessionData, failedAgent, finishedAgent, plain, rawToolInput, stripAcceptanceReport } from "./agent-state.ts";
5
+ import type { UiLanguage } from "./settings.ts";
6
+ import { addUsage, EMPTY_USAGE, formatUsd, type UsageLike } from "./usage.ts";
5
7
  import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
6
8
  import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
7
9
 
@@ -13,6 +15,7 @@ export interface AgentCall {
13
15
  id: string;
14
16
  name: string;
15
17
  task: string;
18
+ command?: string;
16
19
  tool?: string;
17
20
  action?: string;
18
21
  state: "running" | "done" | "error";
@@ -36,7 +39,8 @@ export const isAgentTool = (name: string) => /^(subagent(?:_supervisor)?|agents?
36
39
  export function agentCall(id: string, tool: string, args: unknown): AgentCall {
37
40
  const data = (args && typeof args === "object" ? args : {}) as Record<string, unknown>;
38
41
  const name = String(data.agent ?? data.subagent_type ?? data.agent_type ?? tool);
39
- 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" };
42
+ const command = typeof data.command === "string" ? data.command : undefined;
43
+ return { id, name, tool, command, action: typeof data.action === "string" ? data.action : undefined, task: String(data.task ?? data.prompt ?? data.description ?? data.action ?? data.command ?? data.path ?? ""), state: "running" };
40
44
  }
41
45
  export function agentCallRows(calls: AgentCall[], theme: Theme, width: number, expanded: boolean,
42
46
  markdown: (text: string, width: number) => string[]): string[] {
@@ -70,17 +74,78 @@ function formatAgentElapsed(startedAt: number, endedAt: number): string {
70
74
  return minutes >= 60 ? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${remainder}` : `${minutes}:${remainder}`;
71
75
  }
72
76
 
77
+ function formatCompactTokens(value: number): string {
78
+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
79
+ if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`;
80
+ return String(Math.round(value));
81
+ }
82
+
83
+ function padRightVisible(str: string, targetWidth: number): string {
84
+ if (targetWidth <= 0) return "";
85
+ const fitted = truncateToWidth(str, targetWidth, "…");
86
+ return fitted + " ".repeat(Math.max(0, targetWidth - visibleWidth(fitted)));
87
+ }
88
+
89
+ function padLeftVisible(str: string, targetWidth: number): string {
90
+ if (targetWidth <= 0) return "";
91
+ const fitted = truncateToWidth(str, targetWidth, "…");
92
+ return " ".repeat(Math.max(0, targetWidth - visibleWidth(fitted))) + fitted;
93
+ }
94
+
95
+ const TABLE_COPY = {
96
+ zh: {
97
+ source: "来源",
98
+ task: "任务",
99
+ time: "用时",
100
+ steps: "步骤",
101
+ input: "输入",
102
+ output: "输出",
103
+ cache: "缓存",
104
+ total: "合计",
105
+ expand: "展开",
106
+ collapse: "收起",
107
+ running: "运行",
108
+ done: "完成",
109
+ failed: "失败",
110
+ count: (n: number) => `${n} 个`,
111
+ session: "会话",
112
+ turns: (n: number) => `${n} 轮`,
113
+ cacheDetail: (r: string, w: string, m: string) => `缓存读 ${r} · 缓存写 ${w} · 未命中 ${m}`,
114
+ },
115
+ en: {
116
+ source: "Source",
117
+ task: "Task",
118
+ time: "Time",
119
+ steps: "Steps",
120
+ input: "In",
121
+ output: "Out",
122
+ cache: "Cache",
123
+ total: "Total",
124
+ expand: "expand",
125
+ collapse: "collapse",
126
+ running: "running",
127
+ done: "done",
128
+ failed: "failed",
129
+ count: (n: number) => `${n}`,
130
+ session: "session",
131
+ turns: (n: number) => n === 1 ? "1 turn" : `${n} turns`,
132
+ cacheDetail: (r: string, w: string, m: string) => `cache read ${r} · cache write ${w} · miss ${m}`,
133
+ },
134
+ } as const;
135
+
73
136
  /** Retained for callers that share a render-state map across the current session. */
74
137
  export type AgentDeadlines = Map<string, number>;
75
138
 
76
139
  /** One snapshot drives both the inline count and its uncapped child rows. */
77
140
  export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme, width: number, expanded = false, _activeOnly = false,
78
141
  deadlines: AgentDeadlines = new Map(), now = Date.now(), expandedIds?: Set<string>,
79
- subagentControls?: Array<{ runId: string; y: number; width: number; line: string }>) {
142
+ subagentControls?: Array<{ runId: string; y: number; width: number; line: string }>,
143
+ lang: UiLanguage = "zh") {
80
144
  // Live and session-persisted snapshots share the same lifecycle and details.
81
145
  const all = agentChildren(statuses);
82
146
  const errors = all.filter(failedAgent).length;
83
147
  const done = all.filter(child => !failedAgent(child) && finishedAgent(child.status ?? child.state)).length;
148
+ const running = all.length - done - errors;
84
149
  const rows: string[] = [];
85
150
  const text = (value: unknown) => typeof value === "string" ? plain(value).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ") : "";
86
151
  const bodyText = (value: unknown) => typeof value === "string"
@@ -93,13 +158,285 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
93
158
  // reset, so slice(row.length) would drop source characters on every wrap.
94
159
  return wrapTextWithAnsi(source, width).map(row => theme.fg("muted", row));
95
160
  };
161
+
162
+ const hasTableData = all.some(child => {
163
+ if (child.source === "pi -p" || child.agent === "pi -p" || child.usage) return true;
164
+ const session = childSessionData(child.sessionFile);
165
+ return Boolean(session?.sessionId || (session?.usage.totalTokens ?? 0) > 0);
166
+ });
167
+
168
+ const copy = TABLE_COPY[lang] ?? TABLE_COPY.zh;
169
+ const gap = " ";
170
+ const prefixWidth = 3;
171
+ const sourceWidth = Math.max(
172
+ visibleWidth(copy.source),
173
+ visibleWidth(copy.total),
174
+ ...all.map(child => (child.source === "pi -p" || child.agent === "pi -p" ? 5 : 8)),
175
+ );
176
+ const timeWidth = 5;
177
+ const stepsWidth = 5;
178
+ const inputWidth = 7;
179
+ const outputWidth = 7;
180
+ const cacheWidth = 5;
181
+ const baseFixed = prefixWidth + 2 + sourceWidth + 2 + timeWidth + 2;
182
+ const minTaskForOptional = 18;
183
+ const minTaskFallback = 12;
184
+ const useTable = width > 0 && all.length > 0 && hasTableData && width >= baseFixed + minTaskFallback;
185
+
186
+ const fullWidth = width;
187
+ if (useTable) {
188
+ // Rows sit on the Agent tree rail, like process records above them.
189
+ const railPrefix = theme.fg("dim", "│ ");
190
+ const width = Math.max(1, fullWidth - visibleWidth(railPrefix));
191
+ // Hide optional columns in order: Cache -> Out -> Steps -> In
192
+ let showInput = false;
193
+ let showSteps = false;
194
+ let showOutput = false;
195
+ let showCache = false;
196
+ if (width >= baseFixed + (2 + stepsWidth) + (2 + inputWidth) + (2 + outputWidth) + (2 + cacheWidth) + minTaskForOptional) {
197
+ showInput = true; showSteps = true; showOutput = true; showCache = true;
198
+ } else if (width >= baseFixed + (2 + stepsWidth) + (2 + inputWidth) + (2 + outputWidth) + minTaskForOptional) {
199
+ showInput = true; showSteps = true; showOutput = true;
200
+ } else if (width >= baseFixed + (2 + stepsWidth) + (2 + inputWidth) + minTaskForOptional) {
201
+ showInput = true; showSteps = true;
202
+ } else if (width >= baseFixed + (2 + inputWidth) + minTaskForOptional) {
203
+ showInput = true;
204
+ }
205
+ const optionalWidth = (showSteps ? 2 + stepsWidth : 0)
206
+ + (showInput ? 2 + inputWidth : 0)
207
+ + (showOutput ? 2 + outputWidth : 0)
208
+ + (showCache ? 2 + cacheWidth : 0);
209
+ // Keep numbers next to the task instead of pinning them to the far edge.
210
+ const taskWidth = Math.max(minTaskFallback, Math.min(56, width - baseFixed - optionalWidth));
211
+ const leftWidth = prefixWidth + 2 + sourceWidth + 2 + taskWidth;
212
+
213
+ const anyExpanded = expanded || all.some(child => expandedIds?.has(String(child.runId ?? child.displayId)));
214
+ const statusParts = [
215
+ running ? `${copy.running} ${running}` : "",
216
+ done ? `${copy.done} ${done}` : "",
217
+ errors ? `${copy.failed} ${errors}` : "",
218
+ ].filter(Boolean);
219
+ const titleLabel = `Sub Agent · ${copy.count(all.length)}${statusParts.length ? ` · ${statusParts.join(" · ")}` : ""} · Ctrl+S ${anyExpanded ? copy.collapse : copy.expand}`;
220
+ const titleFits = visibleWidth(titleLabel) <= leftWidth;
221
+ if (!titleFits) rows.push(theme.fg(errors ? "error" : "muted", truncateToWidth(titleLabel, width, "…")));
222
+ const headerCells = [
223
+ titleFits ? theme.fg(errors ? "error" : "muted", padRightVisible(titleLabel, leftWidth)) : " ".repeat(leftWidth),
224
+ padLeftVisible(copy.time, timeWidth),
225
+ ...(showSteps ? [padLeftVisible(copy.steps, stepsWidth)] : []),
226
+ ...(showInput ? [padLeftVisible(copy.input, inputWidth)] : []),
227
+ ...(showOutput ? [padLeftVisible(copy.output, outputWidth)] : []),
228
+ ...(showCache ? [padLeftVisible(copy.cache, cacheWidth)] : []),
229
+ ];
230
+ const headerRow = headerCells[0] + gap + theme.fg("dim", headerCells.slice(1).join(gap));
231
+ rows.push(headerRow + " ".repeat(Math.max(0, width - visibleWidth(headerRow))));
232
+
233
+ let totalSteps = 0;
234
+ let totalInput = 0;
235
+ let totalOutput = 0;
236
+ let totalCacheRead = 0;
237
+ let anyUsage = false;
238
+ const rawSids = all.map(child => {
239
+ const s = childSessionData(child.sessionFile);
240
+ return s?.sessionId || text(child.sessionId) || String(child.runId ?? child.displayId);
241
+ });
242
+ const sidPrefixCounts = new Map<string, number>();
243
+ for (const id of rawSids) {
244
+ const p = id.slice(0, 8);
245
+ sidPrefixCounts.set(p, (sidPrefixCounts.get(p) ?? 0) + 1);
246
+ }
247
+
248
+ all.forEach((child, childIndex) => {
249
+ const runKey = String(child.runId ?? child.displayId);
250
+ const isChildExpanded = expanded || (expandedIds?.has(runKey) ?? false);
251
+ const notice = child.notice as { summary?: string; state?: string; color?: "error" | "warning" | "muted"; alert?: boolean; internal?: boolean } | undefined;
252
+ const session = childSessionData(child.sessionFile);
253
+ const rawModel = text(child.model) || session?.model || "";
254
+ const modelShort = rawModel.split("/").at(-1) || "";
255
+ const suffix = modelShort.match(/:(off|minimal|low|medium|high|xhigh|max)$/);
256
+ const cleanModel = (suffix ? modelShort.slice(0, -suffix[0].length) : modelShort) || "?";
257
+ const level = text(child.thinking) || suffix?.[1] || session?.thinking || "off";
258
+ const tools = Array.isArray(child.recentTools) ? child.recentTools.filter(tool => tool && typeof tool === "object") : [];
259
+ const latest = tools.at(-1);
260
+ const latestArgs = rawToolInput(child.sessionFile, latest?.tool, text(latest?.args));
261
+ const currentAction = [text(child.currentTool), text(child.currentPath || child.currentToolArgs)].filter(Boolean).join(" ")
262
+ || [text(latest?.tool), latestArgs].filter(Boolean).join(" ");
263
+ const taskPrompt = text(child.task || child.description);
264
+ const state = text(child.status ?? child.state) || "waiting";
265
+ const terminal = failedAgent(child) || finishedAgent(state);
266
+ const isRunning = /^(running|active|starting|queued|pending)$/.test(state);
267
+ const rawTaskText = failedAgent(child)
268
+ ? (notice?.summary || text(child.error) || taskPrompt || currentAction || state)
269
+ : terminal
270
+ ? (taskPrompt || notice?.summary || currentAction || state)
271
+ : (notice?.summary || currentAction || taskPrompt || state);
272
+ const taskDisplay = (!terminal && (latest || child.currentTool))
273
+ ? text(rawTaskText)
274
+ : text(renderMinimalMarkdown(rawTaskText, Math.max(1, visibleWidth(rawTaskText) + 1), getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "", undefined, diagramMarkdown).join(" "));
275
+
276
+ const glyph = failedAgent(child) || notice?.color === "error" ? "×"
277
+ : notice?.color === "warning" ? "⚠"
278
+ : finishedAgent(state) ? "✓"
279
+ : isRunning ? runningGlyph(now) : "●";
280
+ const glyphColor = failedAgent(child) || notice?.color === "error" ? "error"
281
+ : notice?.color === "warning" ? "warning"
282
+ : isRunning && !terminal ? "accent" : "muted";
283
+
284
+ const elapsedKey = `elapsed:${runKey}`;
285
+ const startedAt = timestamp(child.startedAt) ?? session?.startedAt ?? deadlines.get(elapsedKey) ?? now;
286
+ if (!timestamp(child.startedAt) && !session?.startedAt) deadlines.set(elapsedKey, startedAt);
287
+ const endedAt = terminal ? timestamp(child.endedAt) ?? session?.endedAt ?? deadlines.get(`${elapsedKey}:ended`) ?? now : now;
288
+ if (terminal) deadlines.set(`${elapsedKey}:ended`, endedAt);
289
+ const elapsed = formatAgentElapsed(startedAt, endedAt);
290
+
291
+ const fallbackToolCount = typeof child.toolCount === "number" && Number.isFinite(child.toolCount) ? child.toolCount : 0;
292
+ const stepCount = session?.steps.length ? session.steps.length : Math.max(tools.length, fallbackToolCount);
293
+ const usage = session && (session.usage.totalTokens > 0 || !child.usage)
294
+ ? session.usage
295
+ : (child.usage ? addUsage(EMPTY_USAGE, child.usage as UsageLike) : EMPTY_USAGE);
296
+ const inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;
297
+ const outputTokens = usage.output;
298
+ const hasUsage = inputTokens > 0 || outputTokens > 0;
299
+ totalSteps += stepCount;
300
+ totalInput += inputTokens;
301
+ totalOutput += outputTokens;
302
+ totalCacheRead += usage.cacheRead;
303
+ anyUsage ||= hasUsage;
304
+
305
+ const inputStr = hasUsage ? formatCompactTokens(inputTokens) : "–";
306
+ const outputStr = hasUsage ? formatCompactTokens(outputTokens) : "–";
307
+ const cacheStr = inputTokens > 0 ? `${Math.round((100 * usage.cacheRead) / inputTokens)}%` : "–";
308
+
309
+ const isPrint = child.source === "pi -p" || child.agent === "pi -p";
310
+ const sourceLabel = isPrint ? "pi -p" : "SubAgent";
311
+ const fgMain = isChildExpanded ? "accent" : "text";
312
+ const fgTask = failedAgent(child) ? "error" : isChildExpanded ? "accent" : "muted";
313
+ const fgTime = isChildExpanded ? "accent" : terminal ? "muted" : "success";
314
+
315
+ const prefixCell = isChildExpanded
316
+ ? theme.fg("accent", padRightVisible(`⌄ ${glyph}`, prefixWidth))
317
+ : theme.fg(isRunning && !terminal ? "accent" : "muted", "› ") + theme.fg(glyphColor, glyph);
318
+ const cells = [
319
+ prefixCell,
320
+ theme.fg(fgMain, theme.bold(padRightVisible(sourceLabel, sourceWidth))),
321
+ theme.fg(fgTask, padRightVisible(taskDisplay, taskWidth)),
322
+ theme.fg(fgTime, padLeftVisible(elapsed, timeWidth)),
323
+ ...(showSteps ? [theme.fg(fgMain, padLeftVisible(String(stepCount), stepsWidth))] : []),
324
+ ...(showInput ? [theme.fg(fgMain, padLeftVisible(inputStr, inputWidth))] : []),
325
+ ...(showOutput ? [theme.fg(fgMain, padLeftVisible(outputStr, outputWidth))] : []),
326
+ ...(showCache ? [theme.fg(fgMain, padLeftVisible(cacheStr, cacheWidth))] : []),
327
+ ];
328
+ const joined = cells.join(gap);
329
+ const padded = joined + " ".repeat(Math.max(0, width - visibleWidth(joined)));
330
+ const line = isChildExpanded ? paintExpandedHeading(theme, padded) : padded;
331
+ subagentControls?.push({ runId: runKey, y: rows.length, width: fullWidth, line: railPrefix + line });
332
+ rows.push(line);
333
+
334
+ if (isChildExpanded) {
335
+ const rail = theme.fg("accent", "│") + " ";
336
+ const tableWidth = leftWidth + 2 + timeWidth + optionalWidth;
337
+ const innerWidth = Math.max(1, Math.min(width, tableWidth) - visibleWidth(rail));
338
+ const rawSid = rawSids[childIndex] ?? runKey;
339
+ const sid = (sidPrefixCounts.get(rawSid.slice(0, 8)) ?? 0) > 1 && rawSid.length >= 13
340
+ ? rawSid.slice(0, 13)
341
+ : rawSid.slice(0, 8);
342
+ const turnsCount = session?.turns ?? 0;
343
+ const metaLine = `${cleanModel} · ${level} · ${copy.session} ${sid} · ${copy.turns(turnsCount)} · ${formatUsd(usage.cost)}`;
344
+ const metaRow = rail + theme.fg("dim", truncateToWidth(metaLine, innerWidth, "…"));
345
+ rows.push(metaRow + " ".repeat(Math.max(0, width - visibleWidth(metaRow))));
346
+
347
+ const stepItems = (session?.steps.length
348
+ ? session.steps
349
+ : tools.map(tool => ({
350
+ at: timestamp(tool.endMs) ?? startedAt,
351
+ name: text(tool.tool) || "tool",
352
+ value: rawToolInput(child.sessionFile, tool.tool, text(tool.args)),
353
+ input: 0,
354
+ }))).slice(-8);
355
+ const stepBase = session?.startedAt ?? startedAt;
356
+ const stepToolWidth = Math.max(6, ...stepItems.map(s => Math.min(12, visibleWidth(s.name))));
357
+ for (const step of stepItems) {
358
+ const relTime = padRightVisible(formatAgentElapsed(stepBase, step.at >= stepBase ? step.at : stepBase), 5);
359
+ const toolCol = padRightVisible(step.name, stepToolWidth);
360
+ const inText = step.input > 0 ? padLeftVisible(`↑${formatCompactTokens(step.input)}`, 8) : "";
361
+ const argWidth = Math.max(1, innerWidth - 5 - 2 - stepToolWidth - 2 - (inText ? 10 : 0));
362
+ const argCol = padRightVisible(step.value, argWidth);
363
+ const stepRow = rail
364
+ + theme.fg("dim", relTime) + " "
365
+ + theme.fg("text", theme.bold(toolCol)) + " "
366
+ + theme.fg("muted", argCol)
367
+ + (inText ? " " + theme.fg("dim", inText) : "");
368
+ rows.push(stepRow + " ".repeat(Math.max(0, width - visibleWidth(stepRow))));
369
+ }
370
+
371
+ const messages = Array.isArray(child.noticeMessages) ? child.noticeMessages : [];
372
+ const bodies: string[] = [];
373
+ let latestProgress = "";
374
+ for (const msg of messages) {
375
+ const item = msg && typeof msg === "object" ? msg as Record<string, unknown> : undefined;
376
+ const details = item?.details && typeof item.details === "object" ? item.details as Record<string, unknown> : undefined;
377
+ if (item?.customType === "subagent_supervisor_request" && details?.reason === "progress_update") {
378
+ const progress = extractNoticeBody(msg, lang);
379
+ if (progress) latestProgress = progress;
380
+ continue;
381
+ }
382
+ const b = supervisorNoticeBody(msg, lang);
383
+ if (b && !bodies.includes(b)) bodies.push(b);
384
+ }
385
+ if (!bodies.length && latestProgress) bodies.push(latestProgress);
386
+ const latestText = bodyText(session?.latestText);
387
+ if (!terminal && latestText && !bodies.length) bodies.push(latestText);
388
+ const finalOutput = terminal ? bodyText(session?.finalOutput || latestText || child.finalOutput) : "";
389
+ if (finalOutput && !bodies.includes(finalOutput)) bodies.push(finalOutput);
390
+ const error = bodyText(child.error);
391
+ if (error && !bodies.includes(error)) bodies.push(error);
392
+
393
+ for (const [bodyIdx, textBody] of bodies.entries()) {
394
+ if (stepItems.length > 0 || bodyIdx > 0) {
395
+ rows.push(rail + " ".repeat(Math.max(0, width - visibleWidth(rail))));
396
+ }
397
+ for (const mdLine of renderBody(textBody, innerWidth)) {
398
+ const fullMd = truncateToWidth(`${rail}${mdLine}`, width);
399
+ rows.push(fullMd + " ".repeat(Math.max(0, width - visibleWidth(fullMd))));
400
+ }
401
+ }
402
+
403
+ const cacheFooter = copy.cacheDetail(
404
+ formatCompactTokens(usage.cacheRead),
405
+ formatCompactTokens(usage.cacheWrite),
406
+ formatCompactTokens(usage.input),
407
+ );
408
+ const cacheRow = rail + theme.fg("dim", truncateToWidth(cacheFooter, innerWidth, "…"));
409
+ rows.push(cacheRow + " ".repeat(Math.max(0, width - visibleWidth(cacheRow))));
410
+ }
411
+ });
412
+
413
+ const totalInputStr = anyUsage ? formatCompactTokens(totalInput) : "–";
414
+ const totalOutputStr = anyUsage ? formatCompactTokens(totalOutput) : "–";
415
+ const totalCacheStr = totalInput > 0 ? `${Math.round((100 * totalCacheRead) / totalInput)}%` : "–";
416
+ const totalCells = [
417
+ " ".repeat(prefixWidth),
418
+ padRightVisible(copy.total, sourceWidth),
419
+ " ".repeat(taskWidth),
420
+ " ".repeat(timeWidth),
421
+ ...(showSteps ? [padLeftVisible(String(totalSteps), stepsWidth)] : []),
422
+ ...(showInput ? [padLeftVisible(totalInputStr, inputWidth)] : []),
423
+ ...(showOutput ? [padLeftVisible(totalOutputStr, outputWidth)] : []),
424
+ ...(showCache ? [padLeftVisible(totalCacheStr, cacheWidth)] : []),
425
+ ];
426
+ const totalRow = theme.fg("muted", totalCells.join(gap));
427
+ if (all.length > 1) rows.push(totalRow + " ".repeat(Math.max(0, width - visibleWidth(totalRow))));
428
+
429
+ return { rows: rows.map(row => railPrefix + row), total: all.length, done, errors, running, table: true };
430
+ }
431
+
96
432
  if (width > 0) all.forEach((child, index) => {
97
433
  const runKey = String(child.runId ?? child.displayId);
98
434
  const isChildExpanded = expanded || (expandedIds?.has(runKey) ?? false);
99
435
  const notice = child.notice as { summary?: string; state?: string; color?: "error" | "warning" | "muted"; alert?: boolean; internal?: boolean } | undefined;
100
- const model = text(child.model).split("/").at(-1) || "";
436
+ const session = childSessionData(child.sessionFile);
437
+ const model = (text(child.model) || session?.model || "").split("/").at(-1) || "";
101
438
  const suffix = model.match(/:(off|minimal|low|medium|high|xhigh|max)$/);
102
- const level = text(child.thinking) || suffix?.[1] || childSessionData(child.sessionFile)?.thinking || "?";
439
+ const level = text(child.thinking) || suffix?.[1] || session?.thinking || "?";
103
440
  const tools = Array.isArray(child.recentTools) ? child.recentTools.filter(tool => tool && typeof tool === "object") : [];
104
441
  const latest = tools.at(-1);
105
442
  const latestArgs = rawToolInput(child.sessionFile, latest?.tool, text(latest?.args));
@@ -107,7 +444,7 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
107
444
  || text(child.error)
108
445
  || [text(child.currentTool), text(child.currentPath || child.currentToolArgs)].filter(Boolean).join(" ")
109
446
  || [text(latest?.tool), latestArgs].filter(Boolean).join(" ")
110
- || text(child.description) || text(child.status ?? child.state) || "waiting";
447
+ || text(child.task || child.description) || text(child.status ?? child.state) || "waiting";
111
448
  // Tool inputs are literal code, not Markdown (heredocs can contain HTML-like text).
112
449
  const body = latest || child.currentTool ? text(activity) : text(renderMinimalMarkdown(activity, Math.max(1, visibleWidth(activity) + 1), getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "", undefined, diagramMarkdown).join(" "));
113
450
  const state = text(child.status ?? child.state) || "waiting";
@@ -121,15 +458,16 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
121
458
  // Status snapshots, not the dispatch tool receipt, define a child run's lifecycle.
122
459
  // Preserve a terminal observation when an older pi-subagents status omits endedAt.
123
460
  const elapsedKey = `elapsed:${runKey}`;
124
- const startedAt = timestamp(child.startedAt) ?? deadlines.get(elapsedKey) ?? now;
125
- if (!timestamp(child.startedAt)) deadlines.set(elapsedKey, startedAt);
126
- const endedAt = terminal ? timestamp(child.endedAt) ?? deadlines.get(`${elapsedKey}:ended`) ?? now : now;
461
+ const startedAt = timestamp(child.startedAt) ?? session?.startedAt ?? deadlines.get(elapsedKey) ?? now;
462
+ if (!timestamp(child.startedAt) && !session?.startedAt) deadlines.set(elapsedKey, startedAt);
463
+ const endedAt = terminal ? timestamp(child.endedAt) ?? session?.endedAt ?? deadlines.get(`${elapsedKey}:ended`) ?? now : now;
127
464
  if (terminal) deadlines.set(`${elapsedKey}:ended`, endedAt);
128
465
  const elapsed = formatAgentElapsed(startedAt, endedAt);
129
466
  const identity = isChildExpanded ? "accent" : color;
467
+ const labelName = child.source === "pi -p" || child.agent === "pi -p" ? "pi -p" : "SubAgent";
130
468
  const heading = truncateToWidth(theme.fg(isChildExpanded ? "accent" : "dim", `${index === all.length - 1 ? "└─" : "├─"} `)
131
469
  + theme.fg(failedAgent(child) || notice?.color === "error" ? "error" : notice?.color === "warning" ? "warning" : isRunning && !terminal ? "accent" : "muted", `${glyph} `)
132
- + theme.fg(identity, theme.bold("SubAgent"))
470
+ + theme.fg(identity, theme.bold(labelName))
133
471
  + theme.fg(identity, ` • ${suffix ? model.slice(0, -suffix[0].length) : model}`)
134
472
  + (level ? theme.fg("muted", ` ${level}`) : "") + theme.fg(terminal ? "muted" : "success", ` ${elapsed}`) + theme.fg(identity, " : "), width, "…");
135
473
  const bodyBudget = Math.max(0, width - visibleWidth(heading));
@@ -163,14 +501,13 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
163
501
  const item = msg && typeof msg === "object" ? msg as Record<string, unknown> : undefined;
164
502
  const details = item?.details && typeof item.details === "object" ? item.details as Record<string, unknown> : undefined;
165
503
  if (item?.customType === "subagent_supervisor_request" && details?.reason === "progress_update") {
166
- const progress = extractNoticeBody(msg);
504
+ const progress = extractNoticeBody(msg, lang);
167
505
  if (progress) latestProgress = progress;
168
506
  continue;
169
507
  }
170
- const b = supervisorNoticeBody(msg);
508
+ const b = supervisorNoticeBody(msg, lang);
171
509
  if (b && !bodies.includes(b)) bodies.push(b);
172
510
  }
173
- const session = childSessionData(child.sessionFile);
174
511
  if (!bodies.length && latestProgress) bodies.push(latestProgress);
175
512
  const latestText = bodyText(session?.latestText);
176
513
  if (!terminal && latestText && !bodies.length) bodies.push(latestText);
@@ -194,10 +531,11 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
194
531
  }
195
532
  }
196
533
  });
197
- return { rows, total: all.length, done, errors, running: all.length - done - errors };
534
+ return { rows, total: all.length, done, errors, running };
198
535
  }
199
536
 
200
- export function liveAgentRows(statuses: Record<string, unknown>[], theme: Theme, width: number, expanded = false, deadlines: AgentDeadlines = new Map()): string[] {
201
- const view = liveAgentView(statuses, theme, width, expanded, false, deadlines);
202
- return width > 0 && view.total ? [agentSummary(theme, width, view.running, view.done, view.errors, expanded), ...view.rows] : [];
537
+ export function liveAgentRows(statuses: Record<string, unknown>[], theme: Theme, width: number, expanded = false, deadlines: AgentDeadlines = new Map(), lang: UiLanguage = "zh"): string[] {
538
+ const view = liveAgentView(statuses, theme, width, expanded, false, deadlines, Date.now(), undefined, undefined, lang);
539
+ if (!width || !view.total) return [];
540
+ return view.table ? view.rows : [agentSummary(theme, width, view.running, view.done, view.errors, expanded), ...view.rows];
203
541
  }