pi-subagent-manager 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,7 +79,7 @@ A live **Agents** widget sits above the input box. Choose **Full** (the existing
79
79
 
80
80
  - Choose **[labs] Cost display** in `/agents settings`: **pi-footer status key** (default), **pi-footer event**, or **Pi status only**. The stable ID/key is **`subagent_cost`**.
81
81
  - **`npm:pi-footer`:** with the default status-key mode, add **Extension Status** through `/footer` and select **`subagent_cost`**. Event mode instead requires a **Pi Event Value** widget with **Widget ID** entered manually and **Raw value only** enabled; event IDs are not listed in the status selector.
82
- - Values publish at session start and immediately on subagent startup, including `$0.0000`, then after settlement/settings changes. Status modes leave your footer untouched; event mode retains the combined-cost fallback when no extension provides `/footer`. See [Cost display settings](docs/settings.md#labs-cost-display-costdisplay).
82
+ - Values publish at session start and immediately on subagent startup, including `$0.0000`, then after settlement/settings changes. Status modes leave your footer untouched; event mode retains the combined-cost fallback when no extension provides `/footer`. See [Cost display settings](docs/settings.md#labs-cost-display-costdisplay) and the [pi-footer setup guide with exact snippets](docs/pi-footer.md).
83
83
 
84
84
  Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Font icons** in `/agents` to show role-specific icons beside agent names (off by default; requires a Nerd Font in your terminal). Loaders appear **before**, never instead of, the role icon. Choose Circle, Braille, or Hourglass under **[labs] Loader style**, with previews of every animation frame and each family's completed, paused, failed, and stopped icons. Custom agent types can set an optional `icon` or use **[labs] Icon** in `/agents types`. See [icon setup](docs/settings.md#labs-nerd-font-icons-nerdfonticons).
85
85
 
@@ -0,0 +1,126 @@
1
+ # Subagent dollar totals in pi-footer
2
+
3
+ With `npm:pi-footer` loaded, choose one of the two integration paths below. Both
4
+ show the **settled subagent-only USD subtotal**, not the main session's cost.
5
+ Keep pi-footer's native cost widget if you also want the main session cost.
6
+
7
+ The shared status key / event Widget ID is exactly **`subagent_cost`**. It is not
8
+ `pi-subagent-manager`, an extension file path, or an npm package ID.
9
+
10
+ ## Extension Status (recommended; default)
11
+
12
+ 1. Open `/agents settings`, set **[labs] Cost display** to **pi-footer status key**,
13
+ and save with **Ctrl+S**.
14
+ 2. Open `/footer`, choose **Edit lines**, select a row, and add **Extension Status**.
15
+ 3. Set **Status key** to **`subagent_cost`** and enable **Raw value only**.
16
+ 4. Save the footer configuration.
17
+
18
+ The corresponding subagent-manager setting is:
19
+
20
+ ```json
21
+ {
22
+ "costDisplay": "pi-footer-status"
23
+ }
24
+ ```
25
+
26
+ For a file-based footer setup, insert this widget object into an existing row
27
+ array in `lines` in `~/.pi/agent/extensions/pi-footer.json`:
28
+
29
+ ```json
30
+ {
31
+ "id": "subagent-cost-status",
32
+ "type": "external-status",
33
+ "enabled": true,
34
+ "options": {
35
+ "externalStatusKey": "subagent_cost",
36
+ "raw": true,
37
+ "hideWhenEmpty": true,
38
+ "trimValue": 0
39
+ }
40
+ }
41
+ ```
42
+
43
+ Here `id` identifies the footer widget instance; **`externalStatusKey`** is the
44
+ lookup key that must match the publisher. Do not put the package name in it.
45
+ The manager already publishes the value using this API (no extra extension needed):
46
+
47
+ ```typescript
48
+ ctx.ui.setStatus("subagent_cost", "$0.1234");
49
+ ```
50
+
51
+ It clears the status with `ctx.ui.setStatus("subagent_cost", undefined)`.
52
+
53
+ ## Pi Event Value (alternative)
54
+
55
+ 1. Open `/agents settings`, set **[labs] Cost display** to **pi-footer event**,
56
+ and save with **Ctrl+S**.
57
+ 2. In `/footer`, add a **Pi Event Value** widget to the desired row.
58
+ 3. Enter **Widget ID** as **`subagent_cost`** manually, replacing the generated ID,
59
+ and enable **Raw value only**. Event IDs do **not** appear in the status-key selector.
60
+ 4. Save the footer configuration.
61
+
62
+ The corresponding subagent-manager setting is:
63
+
64
+ ```json
65
+ {
66
+ "costDisplay": "pi-footer-event"
67
+ }
68
+ ```
69
+
70
+ Insert this widget object into an existing row array in the footer's `lines`:
71
+
72
+ ```json
73
+ {
74
+ "id": "subagent-cost-event",
75
+ "type": "event",
76
+ "enabled": true,
77
+ "options": {
78
+ "widgetId": "subagent_cost",
79
+ "raw": true,
80
+ "hideWhenEmpty": true
81
+ }
82
+ }
83
+ ```
84
+
85
+ The manager already emits the following event; no custom publisher is required.
86
+ This is the exact event name and payload shape, with an illustrative dollar value:
87
+
88
+ ```typescript
89
+ pi.events.emit("pi-footer:update-widget", {
90
+ widgetId: "subagent_cost",
91
+ value: "$0.1234",
92
+ });
93
+ ```
94
+
95
+ To clear the event value, the manager emits:
96
+
97
+ ```typescript
98
+ pi.events.emit("pi-footer:update-widget", {
99
+ widgetId: "subagent_cost",
100
+ value: null,
101
+ });
102
+ ```
103
+
104
+ ## File locations and refresh behavior
105
+
106
+ - Merge the `costDisplay` setting into
107
+ `~/.pi/agent/subagent-manager/settings.json`, or the trusted-project override
108
+ `.pi/agent/subagent-manager/settings.json`. Preserve your other settings.
109
+ - Footer widget snippets are **objects inside a row**, not complete configuration
110
+ files: the structure is `"lines": [[widgetObject, otherWidgetObject]]`. Preserve
111
+ existing rows and widgets. `PI_FOOTER_CONFIG` can override the footer file path.
112
+ - After manual file edits, use Pi's `/reload` to reload extensions and settings.
113
+ Using the settings dialogs applies changes immediately when saved.
114
+ - Choose only the widget matching your selected mode. Switching modes clears the
115
+ old output; shutdown clears the published value too.
116
+ - `$0.0000` appears at session start/reload and immediately on subagent startup.
117
+ Running costs settle on completion, pause, stop, or failure; they remain in
118
+ agent rows until then. Nested agents are counted once, and accounting survives
119
+ resume and reaping. Nerd Font icons may prefix the dollar value when enabled.
120
+ - If the status key is missing, check that the manager is loaded and the mode is
121
+ **pi-footer status key**, not **pi-footer event** or **Pi status only**.
122
+ **Pi status only** publishes a combined main-session + settled-subagent total,
123
+ so it is not the mode to use for a subagent-only widget.
124
+
125
+ See [Cost display settings](settings.md#labs-cost-display-costdisplay) for all modes
126
+ and fallback behavior when pi-footer is not loaded.
package/docs/settings.md CHANGED
@@ -83,6 +83,8 @@ Choose the cost output in `/agents settings` and save. The stable ID/key is **`s
83
83
 
84
84
  Both status modes use the same public Pi status API: third-party footers may also display Pi status-only output. These modes never replace your footer. The pi-footer modes show the **settled subagent-only** USD subtotal; Pi status shows **main session + all settled subagents**. In all modes, running costs settle on completion, pause, stop, or failure. It publishes on session start/reload, immediately when a subagent starts (even at zero), and after settlement/settings changes. Switching modes clears the previous output; shutdown clears the published value. Nerd Font icons apply when enabled.
85
85
 
86
+ See [Subagent dollar totals in pi-footer](pi-footer.md) for step-by-step setup and copy-paste widget configuration, status-key, and event snippets.
87
+
86
88
  ## [labs] Final Recap (`finalRecap`)
87
89
 
88
90
  **[labs] Final Recap** is an experimental on/off toggle, **off by default**. Enable it in `/agents` and save with **Ctrl+S**, or set `"finalRecap": true` in your settings file.
@@ -72,7 +72,7 @@ Refreshes every second and keeps your selection, collapse state and scroll posit
72
72
 
73
73
  ### Live agent navigation
74
74
 
75
- The fullscreen watcher renders steer and agent messages (including thinking) as Markdown, same as pi's main transcript. Tool calls use pi's built-in call formats (`$ command`, `read path:range`, `grep /pattern/ in path`, …) rather than bare JSON; unknown tools fall back to pretty-printed JSON. Tool results and other metadata show their name/status and only the first three wrapped lines of each output preview, followed by `...` when more is hidden. Use **i → Transcript** from the tree for retained tool details. **t** cycles three detail levels with transcript controls focused: **preview** (default: three rows per call, first three rendered thinking lines), **compact** (one line per call, thinking hidden), **full** (complete calls and thinking). Inherited context is initially collapsed (**c** toggles it with transcript controls focused). Watching alone never starts a turn, switches sessions, or changes model/tool/resource ownership. Unsupported/custom content and images use safe text placeholders rather than native rich rendering. Legacy sessions without reliable inherited-prefix metadata show their whole transcript.
75
+ The fullscreen watcher renders steer and agent messages (including thinking) as Markdown, same as pi's main transcript. Tool calls and their results share pi's native `ToolExecutionComponent`, with built-in renderers for shell commands, reads, highlighted writes, edit diffs and search tools. Pending, successful and failed executions use pi's active theme colors. Unknown tools use pi's safe generic renderer; nested executions appear beneath their parent. **Ctrl+O** toggles full tool output from either input or transcript focus. **t** cycles detail levels with transcript controls focused: **preview** (default: pi's native tool previews, first three rendered thinking lines), **compact** (one line per call, thinking hidden), **full** (complete tool output and thinking). Successful reads are collapsed by default, just like pi; expand them with **Ctrl+O**. Inherited context is initially collapsed (**c** toggles it with transcript controls focused). Watching alone never starts a turn, switches sessions, or changes model/tool/resource ownership. Extension renderers are never invoked, raw terminal controls are stripped, and images use safe text placeholders. Legacy sessions without reliable inherited-prefix metadata show their whole transcript.
76
76
 
77
77
  - The bottom **Steer** input is focused initially. Type and press **Enter** to send to the inspected agent, including nested descendants, through the same service as `agent_steer`: running agents receive queued input; paused/completed/stopped agents resume their retained session. Empty input is ignored. Sending leaves the viewer open; failures are shown and preserve the draft for retry.
78
78
  - **Tab** switches between steering input and transcript controls. While typing, **c/t/l/r** are ordinary text and **Home/End** move the input cursor. Pasting never submits by itself.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
@@ -11,12 +11,11 @@ import {
11
11
  visibleWidth,
12
12
  wrapTextWithAnsi,
13
13
  } from "@earendil-works/pi-tui";
14
- import type { ThreadService, TranscriptSnapshot } from "../types.ts";
14
+ import type { ThreadService, TranscriptSnapshot, TranscriptToolState } from "../types.ts";
15
15
  import { dialogText, type DialogHost } from "./dialog.ts";
16
16
  import { AGENT_PROGRESS_INTERVAL, agentProgressIcon, agentTypeLabel } from "./ui.ts";
17
17
  import type { LoaderStyle } from "../prefs/settings.ts";
18
-
19
- type ThemeBg = Parameters<Theme["bg"]>[0];
18
+ import { renderTranscriptTool } from "./transcript-tool.ts";
20
19
 
21
20
  /** Transcript detail level cycled by the t key: full → preview → compact. */
22
21
  export type TranscriptDetail = "full" | "preview" | "compact";
@@ -59,7 +58,7 @@ function json(value: unknown): string {
59
58
  }
60
59
  }
61
60
 
62
- /** Live transcript and manual steering. Never invoke tools' custom renderers or pass through raw controls. */
61
+ /** Live transcript and manual steering. Reuse trusted pi built-ins; strip untrusted controls. */
63
62
  export class LiveAgentView {
64
63
  private snapshot: TranscriptSnapshot | undefined;
65
64
  private error: string | undefined;
@@ -84,6 +83,22 @@ export class LiveAgentView {
84
83
  private steerStatus: string | undefined;
85
84
  private steerFailed = false;
86
85
 
86
+ private results = new Map<string, AgentMessage>();
87
+ private tools = new Map<string, TranscriptToolState>();
88
+ private renderedTools = new Set<string>();
89
+ private toolCache = new Map<
90
+ string,
91
+ {
92
+ args: unknown;
93
+ result: unknown;
94
+ running: boolean;
95
+ isError: boolean;
96
+ name: string;
97
+ width: number;
98
+ detail: TranscriptDetail;
99
+ lines: string[];
100
+ }
101
+ >();
87
102
  constructor(
88
103
  private host: DialogHost,
89
104
  private theme: Theme,
@@ -186,6 +201,7 @@ export class LiveAgentView {
186
201
  snapshot.revision < this.snapshot.revision))
187
202
  )
188
203
  return;
204
+ if (snapshot.generation !== this.snapshot?.generation) this.toolCache.clear();
189
205
  this.snapshot = snapshot;
190
206
  this.error = snapshot.error;
191
207
  this.syncProgress();
@@ -219,6 +235,7 @@ export class LiveAgentView {
219
235
 
220
236
  invalidate(): void {
221
237
  this.cache = new WeakMap();
238
+ this.toolCache.clear();
222
239
  this.input.invalidate();
223
240
  }
224
241
 
@@ -242,6 +259,12 @@ export class LiveAgentView {
242
259
  if (matchesKey(data, Key.escape)) return this.done("back");
243
260
  if (matchesKey(data, Key.ctrl("q")) || matchesKey(data, Key.ctrl("c")))
244
261
  return this.done("main");
262
+ if (matchesKey(data, Key.ctrl("o"))) {
263
+ this.viewport.detail = this.detail === "full" ? "preview" : "full";
264
+ this.invalidate();
265
+ this.host.requestRender();
266
+ return;
267
+ }
245
268
  if (matchesKey(data, Key.tab)) {
246
269
  this.editing = !this.editing;
247
270
  this.input.focused = this.focused && this.editing;
@@ -290,18 +313,6 @@ export class LiveAgentView {
290
313
  return lines.map((line) => ` ${line}`);
291
314
  }
292
315
 
293
- /** Full-width themed band with one column of padding, like pi's tool boxes. */
294
- private band(lines: string[], token: ThemeBg, width: number): string[] {
295
- const inner = Math.max(1, width - 2);
296
- return lines.map((line) => {
297
- const clipped = truncateToWidth(line, inner, "", true);
298
- return this.theme.bg(
299
- token,
300
- ` ${clipped}${" ".repeat(Math.max(0, inner - visibleWidth(clipped)))} `,
301
- );
302
- });
303
- }
304
-
305
316
  private wrap(value: string, width: number): string[] {
306
317
  return text(value)
307
318
  .split("\n")
@@ -354,11 +365,7 @@ export class LiveAgentView {
354
365
  return content.flatMap((value) => {
355
366
  const block = object(value);
356
367
  if (block?.type === "toolCall")
357
- return this.band(
358
- this.toolCall(String(block.name), block.arguments, inner),
359
- "toolSuccessBg",
360
- width,
361
- );
368
+ return this.tool(String(block.id), String(block.name), block.arguments, width);
362
369
  return this.pad(this.blockLines(value, inner));
363
370
  });
364
371
  }
@@ -381,13 +388,17 @@ export class LiveAgentView {
381
388
  }
382
389
 
383
390
  private message(message: AgentMessage, width: number): string[] {
384
- const cached = this.cache.get(message);
385
- if (cached && cached.width === width && cached.detail === this.detail) return cached.lines;
391
+ if (message.role === "toolResult") {
392
+ const result = message as unknown as Record<string, unknown>;
393
+ return this.tool(String(result.toolCallId), String(result.toolName), {}, width);
394
+ }
386
395
  const data = message as unknown as Record<string, unknown>;
387
- const label =
388
- message.role === "toolResult"
389
- ? `Tool result: ${String(data.toolName)}${data.isError ? " — error" : ""}`
390
- : message.role;
396
+ const hasTools =
397
+ Array.isArray(data.content) &&
398
+ data.content.some((block: unknown) => object(block)?.type === "toolCall");
399
+ const cached = !hasTools && this.cache.get(message);
400
+ if (cached && cached.width === width && cached.detail === this.detail) return cached.lines;
401
+ const label = message.role;
391
402
  const collapsed = !["user", "assistant", "custom"].includes(message.role);
392
403
  const content = data.content ?? data.summary ?? data.output ?? data;
393
404
  const inner = Math.max(1, width - 2);
@@ -398,128 +409,64 @@ export class LiveAgentView {
398
409
  : this.wrap(String(data.errorMessage), inner)
399
410
  ).map((line) => this.theme.fg("error", line))
400
411
  : [];
401
- const lines =
402
- message.role === "toolResult"
403
- ? [
404
- ...this.band(
405
- [heading, ...this.preview(content, inner), ...errors],
406
- data.isError ? "toolErrorBg" : "customMessageBg",
407
- width,
408
- ),
409
- "",
410
- ]
411
- : [
412
- ...this.pad([heading]),
413
- ...(collapsed ? this.pad(this.preview(content, inner)) : this.blocks(content, width)),
414
- ...this.pad(errors),
415
- "",
416
- ];
417
- this.cache.set(message, { width, detail: this.detail, lines });
412
+ const lines = [
413
+ ...this.pad([heading]),
414
+ ...(collapsed ? this.pad(this.preview(content, inner)) : this.blocks(content, width)),
415
+ ...this.pad(errors),
416
+ "",
417
+ ];
418
+ if (!hasTools) this.cache.set(message, { width, detail: this.detail, lines });
418
419
  return lines;
419
420
  }
420
421
 
421
- /**
422
- * Pi-style tool call lines, mirroring the main session's built-in renderers (`$ command`,
423
- * `read path:range`, `grep /pattern/ in path`, …) instead of bare JSON. All interpolated values
424
- * are sanitized; unknown tools fall back to pretty-printed JSON. Shaped by the detail mode:
425
- * compact keeps one truncated line, preview keeps three wrapped rows, full keeps everything
426
- * (bounded by the preview byte cap for pathological payloads).
427
- */
428
- private toolCall(name: string, args: unknown, width: number): string[] {
429
- const data = object(args);
430
- const str = (key: string): string | undefined => {
431
- const value = data?.[key];
432
- return typeof value === "string" ? text(value) : undefined;
433
- };
434
- const num = (key: string): number | undefined => {
435
- const value = data?.[key];
436
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
437
- };
438
- const title = (value: string) => this.theme.fg("accent", value);
439
- const detail = (value: string) => this.theme.fg("muted", value);
440
- const path = str("file_path") ?? str("path");
422
+ /** Pair a call with its committed result or live partial, then render nested executions in place. */
423
+ private tool(id: string, name: string, args: unknown, width: number): string[] {
424
+ if (this.renderedTools.has(id)) return [];
425
+ this.renderedTools.add(id);
426
+ const state = this.tools.get(id);
427
+ const result = this.results.get(id) ?? state?.result;
428
+ const running =
429
+ !this.results.has(id) && (state ? state.state === "running" : result === undefined);
430
+ const isError = Boolean(object(result)?.isError ?? state?.isError);
431
+ // Committed call arguments are authoritative; orphan results use retained live args if available.
432
+ if (state && !Object.keys(object(args) ?? {}).length) args = state.args;
433
+ const cached = this.toolCache.get(id);
441
434
  let lines: string[];
442
- switch (name) {
443
- case "bash":
444
- case "powershell": {
445
- const prompt = name === "bash" ? "$" : ">";
446
- const command = (str("command") ?? "...").split("\n");
447
- const timeout = num("timeout");
448
- lines = [
449
- `${title(`${prompt} ${command[0]}`)}${timeout ? detail(` (timeout ${timeout}s)`) : ""}`,
450
- ...command.slice(1),
451
- ];
452
- break;
453
- }
454
- case "read": {
455
- const offset = num("offset");
456
- const limit = num("limit");
457
- const range =
458
- offset == null && limit == null
459
- ? ""
460
- : this.theme.fg(
461
- "warning",
462
- `:${offset ?? 1}${limit != null ? `-${(offset ?? 1) + limit - 1}` : ""}`,
463
- );
464
- lines = [`${title("read")} ${path ?? "?"}${range}`];
465
- break;
466
- }
467
- case "edit":
468
- lines = [`${title("edit")} ${path ?? "?"}`];
469
- break;
470
- case "write": {
471
- lines = [`${title("write")} ${path ?? "?"}`];
472
- const content = str("content");
473
- if (content) {
474
- const contentLines = content.split("\n");
475
- while (contentLines.length && contentLines.at(-1) === "") contentLines.pop();
476
- lines.push(...contentLines);
477
- }
478
- break;
479
- }
480
- case "grep": {
481
- const pattern = str("pattern");
482
- const glob = str("glob");
483
- const limit = num("limit");
484
- lines = [
485
- `${title("grep")} ${this.theme.fg("accent", `/${pattern ?? ""}/`)}` +
486
- `${path ? detail(` in ${path}`) : ""}${glob ? detail(` (${glob})`) : ""}` +
487
- `${limit != null ? detail(` limit ${limit}`) : ""}`,
488
- ];
489
- break;
490
- }
491
- case "find": {
492
- const pattern = str("pattern");
493
- const limit = num("limit");
494
- lines = [
495
- `${title("find")} ${this.theme.fg("accent", pattern ?? "")}` +
496
- `${path ? detail(` in ${path}`) : ""}${limit != null ? detail(` (limit ${limit})`) : ""}`,
497
- ];
498
- break;
499
- }
500
- case "ls": {
501
- const limit = num("limit");
502
- lines = [
503
- `${title("ls")} ${path ?? "."}${limit != null ? detail(` (limit ${limit})`) : ""}`,
504
- ];
505
- break;
506
- }
507
- default:
508
- lines = [title(dialogText(name)), ...json(args).split("\n")];
435
+ if (
436
+ cached &&
437
+ cached.args === args &&
438
+ cached.result === result &&
439
+ cached.running === running &&
440
+ cached.isError === isError &&
441
+ cached.name === name &&
442
+ cached.width === width &&
443
+ cached.detail === this.detail
444
+ ) {
445
+ lines = cached.lines;
446
+ } else {
447
+ lines = renderTranscriptTool(name, id, args, result, isError, running, this.detail, width);
448
+ this.toolCache.set(id, {
449
+ args,
450
+ result,
451
+ running,
452
+ isError,
453
+ name,
454
+ width,
455
+ detail: this.detail,
456
+ lines,
457
+ });
509
458
  }
510
- if (this.detail === "compact")
511
- return [truncateToWidth(lines[0] ?? "", Math.max(1, width), "…", true)];
512
- const wrapped = lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
513
- if (this.detail === "preview" && wrapped.length > 3)
514
- return [...wrapped.slice(0, 3), this.theme.fg("dim", "...")];
515
- const bounded: string[] = [];
516
- let chars = 0;
517
- for (const line of wrapped) {
518
- if (chars > 32768) return [...bounded, this.theme.fg("dim", "...")];
519
- bounded.push(line);
520
- chars += line.length;
459
+ const nested: string[] = [];
460
+ for (const child of this.tools.values()) {
461
+ if (child.parentToolCallId !== id || this.renderedTools.has(child.toolCallId)) continue;
462
+ nested.push(
463
+ ` ${this.theme.fg("dim", "↳ nested tool")}`,
464
+ ...this.tool(child.toolCallId, child.toolName, child.args, Math.max(3, width - 2)).map(
465
+ (line) => ` ${line}`,
466
+ ),
467
+ );
521
468
  }
522
- return bounded;
469
+ return [...lines, ...nested];
523
470
  }
524
471
 
525
472
  render(width: number): string[] {
@@ -534,6 +481,16 @@ export class LiveAgentView {
534
481
  `${this.path} · ${agentTypeLabel(thread?.type ?? "agent", thread?.icon, this.nerdFontIcons, thread ? agentProgressIcon(thread, this.nerdFontIcons, Date.now(), true, this.loaderStyle) : undefined)} · ${thread?.state ?? "attaching"} — Watching — main continues`,
535
482
  ),
536
483
  );
484
+ this.results = new Map(
485
+ (snapshot?.messages ?? [])
486
+ .filter((message) => message.role === "toolResult")
487
+ .map((message) => [
488
+ String((message as unknown as Record<string, unknown>).toolCallId),
489
+ message,
490
+ ]),
491
+ );
492
+ this.tools = new Map((snapshot?.tools ?? []).map((tool) => [tool.toolCallId, tool]));
493
+ this.renderedTools.clear();
537
494
  const body: string[] = [];
538
495
  if (this.error)
539
496
  body.push(
@@ -559,31 +516,16 @@ export class LiveAgentView {
559
516
  ` ${this.theme.fg("warning", "Assistant streaming…")}`,
560
517
  ...this.message(snapshot.assistant, columns),
561
518
  );
562
- const committedResults = new Set(
563
- snapshot.messages
564
- .filter((message) => message.role === "toolResult")
565
- .map((message) => (message.role === "toolResult" ? message.toolCallId : "")),
566
- );
567
- for (const tool of snapshot.tools) {
568
- if (committedResults.has(tool.toolCallId)) continue;
569
- const call = this.toolCall(tool.toolName, tool.args, inner);
570
- call[0] = `${call[0]} ${this.theme.fg(
571
- tool.isError ? "error" : "warning",
572
- dialogText(
573
- `— ${tool.state}${tool.isError ? " (error)" : ""}${tool.parentToolCallId ? " (nested)" : ""}`,
574
- ),
575
- )}`;
576
- body.push(...this.band(call, "toolSuccessBg", columns));
577
- if (tool.result !== undefined && this.detail !== "compact")
578
- body.push(
579
- ...this.band(
580
- this.preview(object(tool.result)?.content ?? tool.result, inner),
581
- tool.isError ? "toolErrorBg" : "customMessageBg",
582
- columns,
583
- ),
584
- );
585
- body.push("");
586
- }
519
+ // Parents first even when nested notifications arrive before the outer call.
520
+ for (const tool of snapshot.tools)
521
+ if (!tool.parentToolCallId && !this.results.has(tool.toolCallId))
522
+ body.push(...this.tool(tool.toolCallId, tool.toolName, tool.args, columns));
523
+ // An orphan nested execution still needs to be visible if its parent is unavailable.
524
+ for (const tool of snapshot.tools)
525
+ if (!this.renderedTools.has(tool.toolCallId) && !this.results.has(tool.toolCallId))
526
+ body.push(...this.tool(tool.toolCallId, tool.toolName, tool.args, columns));
527
+ for (const id of this.toolCache.keys())
528
+ if (!this.renderedTools.has(id)) this.toolCache.delete(id);
587
529
  if (!body.length)
588
530
  body.push(
589
531
  thread?.state === "starting"
@@ -606,7 +548,7 @@ export class LiveAgentView {
606
548
  this.saveViewport();
607
549
  const footer = this.error
608
550
  ? "Ctrl+R Retry · Tab input/transcript · Esc tree · Ctrl+Q main"
609
- : `${this.editing ? "Enter steer · Tab browse" : `Tab steer · Home/End scroll · c context · t view:${this.detail}`} · Esc tree · Ctrl+Q main · ↑↓/PgUp/PgDn scroll · ${this.viewport.follow ? "following" : "scrolled"}`;
551
+ : `${this.editing ? "Enter steer · Tab browse" : `Tab steer · Home/End scroll · c context · t view:${this.detail}`} · Ctrl+O expand tools · Esc tree · Ctrl+Q main · ↑↓/PgUp/PgDn scroll · ${this.viewport.follow ? "following" : "scrolled"}`;
610
552
  const input = ` ${this.input.render(inner)[0]!}`;
611
553
  const status = this.theme.fg(
612
554
  this.steerStatus ? (this.steerFailed ? "error" : "muted") : this.error ? "error" : "muted",
@@ -294,29 +294,28 @@ export class StatusDialog {
294
294
  ]
295
295
  .map((part) => dialogText(part))
296
296
  .join(" ");
297
- const first = [
297
+ const identityLine = [
298
298
  selected ? this.theme.fg("accent", head) : head,
299
299
  badge,
300
300
  this.theme.fg(inactive ? base : selected ? "accent" : "text", ` ${identity} `),
301
301
  this.theme.fg(inactive ? hint : "muted", dialogText(thread.state)),
302
302
  ].join("");
303
303
  // Continue the tree's vertical guides without repeating the branch or selection marker.
304
- const stem = row.prefix.replace("├─ ", "│ ").replace("└─ ", " ");
304
+ const stem = row.prefix.replace("├ ", "│ ").replace("└ ", " ");
305
305
  const activity = ` ${stem} ${dialogText(thread.status || thread.task)}`;
306
306
  const metrics = this.theme.fg(base, threadMetrics(thread));
307
307
  const metricWidth = visibleWidth(metrics);
308
- const second =
308
+ const first =
309
309
  metricWidth >= width
310
310
  ? truncateToWidth(metrics, width, "")
311
311
  : (() => {
312
- const left = truncateToWidth(
313
- this.theme.fg(inactive ? base : selected ? "accent" : "muted", activity),
314
- width - metricWidth - 1,
315
- );
316
- return (
317
- left + " ".repeat(Math.max(1, width - visibleWidth(left) - metricWidth)) + metrics
318
- );
312
+ const left = truncateToWidth(identityLine, width - metricWidth - 1);
313
+ return left + " ".repeat(Math.max(1, width - visibleWidth(left) - metricWidth)) + metrics;
319
314
  })();
315
+ const second = truncateToWidth(
316
+ this.theme.fg(inactive ? base : selected ? "accent" : "muted", activity),
317
+ width,
318
+ );
320
319
  return [first, second];
321
320
  }
322
321
 
@@ -137,10 +137,10 @@ export function buildStatusTree(
137
137
  for (const [index, node] of ordered.entries()) {
138
138
  visited.add(node.path);
139
139
  const last = index === ordered.length - 1;
140
- const stem = ancestors.map((isLast) => (isLast ? " " : "│ ")).join("");
140
+ const stem = ancestors.map((isLast) => (isLast ? " " : "│ ")).join("");
141
141
  rows.push({
142
142
  path: node.path,
143
- prefix: stem + (top ? "" : last ? "└─ " : "├─ "),
143
+ prefix: stem + (top ? "" : last ? "└ " : "├ "),
144
144
  hasChildren: node.children.length > 0,
145
145
  ...(node.thread ? { thread: node.thread } : {}),
146
146
  });
@@ -0,0 +1,142 @@
1
+ import {
2
+ ToolExecutionComponent,
3
+ type ToolDefinition,
4
+ createBashToolDefinition,
5
+ createPowerShellToolDefinition,
6
+ createReadToolDefinition,
7
+ createEditToolDefinition,
8
+ createWriteToolDefinition,
9
+ createGrepToolDefinition,
10
+ createFindToolDefinition,
11
+ createLsToolDefinition,
12
+ } from "@earendil-works/pi-coding-agent";
13
+ import { Text, stripTerminalSequences, type TUI } from "@earendil-works/pi-tui";
14
+
15
+ /** Only trusted pi built-ins: observing a transcript must never execute extension renderers. */
16
+ type Renderers = Pick<ToolDefinition<any, any>, "renderCall" | "renderResult">;
17
+ const renderers = new Map<string, Renderers>(
18
+ [
19
+ createBashToolDefinition(process.cwd()),
20
+ createPowerShellToolDefinition(process.cwd()),
21
+ createReadToolDefinition(process.cwd()),
22
+ createEditToolDefinition(process.cwd()),
23
+ createWriteToolDefinition(process.cwd()),
24
+ createGrepToolDefinition(process.cwd()),
25
+ createFindToolDefinition(process.cwd()),
26
+ createLsToolDefinition(process.cwd()),
27
+ ].map((tool) => [
28
+ tool.name,
29
+ { renderCall: tool.renderCall, renderResult: tool.renderResult } as Renderers,
30
+ ]),
31
+ );
32
+
33
+ // Native edit call previews otherwise read today's file asynchronously. An observer must
34
+ // use the recorded result.diff, not inspect a possibly different worktree on every paint.
35
+ const edit = renderers.get("edit")!;
36
+ const editCall = edit.renderCall!;
37
+ edit.renderCall = (args, theme, context) =>
38
+ editCall(args, theme, { ...context, argsComplete: false });
39
+
40
+ // Pi's generic fallback is unbounded. Retain the native tool box/title, but bound
41
+ // unknown-tool previews by visual rows (extension tools can return enormous single lines).
42
+ const generic: Renderers = {
43
+ renderResult(result, options, theme) {
44
+ const output = result.content
45
+ .filter((block) => block.type === "text")
46
+ .map((block) => block.text)
47
+ .join("\n");
48
+ const bounded = options.expanded ? output : output.slice(0, 32768);
49
+ const component = new Text(theme.fg("toolOutput", bounded), 0, 0);
50
+ return {
51
+ invalidate() {
52
+ component.invalidate();
53
+ },
54
+ render(width) {
55
+ const rows = component.render(width);
56
+ if (options.expanded || (rows.length <= 5 && bounded.length === output.length)) return rows;
57
+ return [...rows.slice(0, 5), theme.fg("muted", "… more lines (Ctrl+O to expand)")];
58
+ },
59
+ };
60
+ },
61
+ };
62
+ function safeText(value: string): string {
63
+ return stripTerminalSequences(value)
64
+ .replace(/\r\n?/g, "\n")
65
+ .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "");
66
+ }
67
+
68
+ /** Sanitize args, content AND details before trusted renderers interpolate them. */
69
+ function sanitize(value: unknown, seen = new WeakSet<object>(), depth = 0): any {
70
+ if (typeof value === "string") return safeText(value);
71
+ if (!value || typeof value !== "object") return typeof value === "bigint" ? String(value) : value;
72
+ if (seen.has(value)) return "[Circular]";
73
+ if (depth > 64) return "[Nested data omitted]";
74
+ seen.add(value);
75
+ const safe = Array.isArray(value)
76
+ ? value.map((item) => sanitize(item, seen, depth + 1))
77
+ : Object.fromEntries(
78
+ Object.entries(value).map(([key, item]) => [
79
+ safeText(key),
80
+ sanitize(item, seen, depth + 1),
81
+ ]),
82
+ );
83
+ seen.delete(value);
84
+ return safe;
85
+ }
86
+
87
+ export function renderTranscriptTool(
88
+ name: string,
89
+ id: string,
90
+ args: unknown,
91
+ result: unknown,
92
+ isError: boolean,
93
+ running: boolean,
94
+ detail: "full" | "preview" | "compact",
95
+ width: number,
96
+ ): string[] {
97
+ // The native shell renderer owns elapsed-time intervals after markExecutionStarted().
98
+ // An observer has no execution lifecycle to dispose, so intentionally don't start that clock.
99
+ const ui = { requestRender() {} } as TUI;
100
+ const component = new ToolExecutionComponent(
101
+ safeText(name),
102
+ safeText(id),
103
+ sanitize(args),
104
+ { showImages: false },
105
+ renderers.get(name) ?? generic,
106
+ ui,
107
+ process.cwd(),
108
+ );
109
+ const data =
110
+ result && typeof result === "object" ? (result as Record<string, unknown>) : undefined;
111
+ const content = data?.content ?? result;
112
+ component.updateResult(
113
+ {
114
+ content: (Array.isArray(content) ? content : content === undefined ? [] : [content]).map(
115
+ (block) => {
116
+ // Never hand image payloads to pi (even showImages:false can trigger Kitty conversion).
117
+ if (block && typeof block === "object" && (block as { type?: string }).type === "image")
118
+ return { type: "text", text: "[Image — text-only observer]" };
119
+ if (block && typeof block === "object" && (block as { type?: string }).type === "text")
120
+ return {
121
+ type: "text",
122
+ text: safeText(String((block as { text?: unknown }).text ?? "")),
123
+ };
124
+ return {
125
+ type: "text",
126
+ text: safeText(
127
+ typeof block === "string" ? block : (JSON.stringify(sanitize(block)) ?? ""),
128
+ ),
129
+ };
130
+ },
131
+ ),
132
+ details: sanitize(data?.details),
133
+ isError: isError || data?.isError === true,
134
+ },
135
+ running,
136
+ );
137
+ component.setExpanded(detail === "full");
138
+ const lines = component.render(Math.max(3, width));
139
+ if (detail === "compact")
140
+ return lines.filter((line) => stripTerminalSequences(line).trim()).slice(0, 1);
141
+ return lines;
142
+ }