pi-subagent-manager 0.18.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
@@ -77,9 +77,9 @@ A live **Agents** widget sits above the input box. Choose **Full** (the existing
77
77
 
78
78
  **Cost accounting:** Agent rows show estimated USD cost (including cache reads/writes) when reported. Completed, paused, stopped, and failed agents roll up only newly incurred cost. Accounting survives resume, reload, branch navigation, and reaping; nested agents' own costs are counted once. Running-agent costs remain in their rows until settlement. This changes the footer display, not Pi's native session statistics.
79
79
 
80
- - **Default footer:** when no extension provides `/footer`, a default-style footer shows the combined main-agent + settled subagent cost in place of the usual cost.
81
- - **`npm:pi-footer`:** its footer/layout is left untouched. Add a **Pi Event Value** widget through `/footer`, set **Widget ID** to `subagent_cost`, and enable **Raw value only**. This shows the settled **subagent-only** USD subtotal, e.g. `$0.0123`; its existing Session Cost widget still shows main-session cost. The subtotal includes a currency Nerd Font icon when **[labs] Nerd Font icons** is on in `/agents settings`. Values republish on session start/reload and after settlement/settings changes.
82
- - Other extensions registering `/footer` also keep ownership; the fallback cannot safely compose with unrelated custom-footer extensions that expose no `/footer` command.
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
+ - **`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) 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
@@ -17,6 +17,7 @@ All keys are optional. Defaults:
17
17
  "widgetMode": "full",
18
18
  "nerdFontIcons": false,
19
19
  "loaderStyle": "circle",
20
+ "costDisplay": "pi-footer-status",
20
21
  "finalRecap": false,
21
22
  "modelSelection": "pick-first-scoped",
22
23
  "toolFiltering": "allowed",
@@ -70,6 +71,20 @@ Choose **Circle** (default), **Braille**, or **Hourglass** in `/agents` settings
70
71
 
71
72
  The Labs preview shows every family's running animation frames and completed, paused, failed, and stopped icons, so you can compare all states before choosing. Starting uses the running animation. State indicators always precede the unchanged role icon; the selected family also applies to the minimal widget's counts. In non-animated output, active agents use the family's first frame.
72
73
 
74
+ ## [labs] Cost display (`costDisplay`)
75
+
76
+ Choose the cost output in `/agents settings` and save. The stable ID/key is **`subagent_cost`**.
77
+
78
+ | Value | Output |
79
+ | --- | --- |
80
+ | `pi-footer-status` (default) | Publishes `$0.0000` via Pi’s `setStatus` API. In `/footer`, add **Extension Status** and pick **`subagent_cost`** from the status-key selector. |
81
+ | `pi-footer-event` | Emits `pi-footer:update-widget` with `widgetId: "subagent_cost"`. Add **Pi Event Value**, enter **Widget ID** manually, and enable **Raw value only**. Event IDs do not appear in the status selector. Without an extension providing `/footer`, preserves the combined-cost fallback footer. |
82
+ | `pi-status` | Sets Pi’s status to `Total: $0.0000` — main session + all settled subagents; no pi-footer events or custom footer. |
83
+
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
+
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
+
73
88
  ## [labs] Final Recap (`finalRecap`)
74
89
 
75
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.18.0",
3
+ "version": "0.20.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
package/src/index.ts CHANGED
@@ -50,6 +50,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
50
50
  pi,
51
51
  () => costLedger.totalUsd,
52
52
  () => limits.nerdFontIcons,
53
+ () => limits.costDisplay,
53
54
  );
54
55
  const refreshCostFooter = (ctx: ExtensionContext) => costFooter.refresh(ctx);
55
56
  const rollupCost = (thread: ThreadView) => {
@@ -272,7 +273,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
272
273
  customType: ROOT_WAKE_MESSAGE,
273
274
  content:
274
275
  "Asynchronous subagent event(s) arrived (see the preceding subagent notifications). " +
275
- "React: collect results with agent_output, and for a timeout event decide to wait, steer, stop or re-arm with agent_steer timeoutMs.",
276
+ "React: collect results with agent_output, and for a timeout event decide to wait, steer, stop or re-arm with agent_steer using path and timeoutMs only (omit message; resets the reporting timer from now without interrupting the running agent).",
276
277
  display: false,
277
278
  details: {},
278
279
  },
@@ -506,6 +507,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
506
507
  pi.on("agent_end", async (_event, ctx) => {
507
508
  rootTurnEnded = true;
508
509
  if (manager) refreshWidget(ctx);
510
+ refreshCostFooter(ctx);
509
511
  // A migration can span clarification turns. Reload after each root turn, without converting files.
510
512
  if (limits.subagentMode === "off" || !migrationRequested) return;
511
513
  store.reload();
@@ -572,6 +574,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
572
574
  refreshWidget(requireContext());
573
575
  if (event.kind !== "metrics") persist();
574
576
  if (event.kind === "settled") rollupCost(event.thread);
577
+ else refreshCostFooter(requireContext());
575
578
  delivery(event);
576
579
  },
577
580
  });
@@ -633,10 +636,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
633
636
  pi.on("session_before_fork", stopWorkingThreads);
634
637
  pi.on("session_shutdown", async () => {
635
638
  cancelSummary();
636
- costFooter.clear();
637
639
  generation++;
638
640
  closeNavigation(true);
639
641
  await manager?.shutdown();
642
+ costFooter.clear();
640
643
  persist();
641
644
  if (context?.hasUI) context.ui.setWidget("pi-subagent", undefined);
642
645
  manager = undefined;
@@ -17,7 +17,7 @@ export function subagentPrompt(settings: ManagerSettings): string | undefined {
17
17
  policy,
18
18
  "Call agent_types before choosing a type. Use task-based kebab-case paths, not type names. Choose context via agent_spawn path: /root/task forks the lexical parent's conversation; /task starts fresh with no inherited history. Use fresh agents for adversarial review or clean-slate research; give them a self-contained task without the current thread's conclusions.",
19
19
  waitingPolicy,
20
- "Use agent_status to inspect and agent_output for full results. Completion, failure or stop of a wait:false agent is delivered to you as a message event that starts a new turn when you are idle (with Final Recap on, once after all outstanding async agents have finished). Pass timeoutMs to agent_spawn to get a status event if a child runs long; the child is not killed. Valid range 30000–300000 ms; omit for no timeout. When a timeout event shows a child still progressing, call agent_steer with only timeoutMs (no message; re-arms without steering) to re-arm it, or agent_wait/agent_steer/agent_stop.",
20
+ 'Use agent_status to inspect and agent_output for full results. Completion, failure or stop of a wait:false agent is delivered to you as a message event that starts a new turn when you are idle (with Final Recap on, once after all outstanding async agents have finished). Pass timeoutMs to agent_spawn to get a status event if a child runs long; the child is not killed. Valid range 30000–300000 ms; omit for no timeout. To extend a running background agent\'s reporting timer, before or after a timeout event, call agent_steer({path: "/root/task", timeoutMs: 120000}) with message omitted entirely. This resets the timer from now (replacing any pending timer), without sending input, interrupting or resuming the agent; it requires the agent to still be running. After re-arming, end your turn to remain available while it works. For other timeout responses, follow the waiting policy above, send steering input or stop the agent.',
21
21
  "Use agent_steer to send input or resume retained sessions. Paused agents have no final answer; completed agents hand back results. Both retain their session.",
22
22
  `Maximum depth: ${settings.maxLevels} levels including L1. Shared concurrency: ${settings.maxConcurrent} active threads; waiting parents count.`,
23
23
  ].join("\n");
package/src/orch/tools.ts CHANGED
@@ -113,11 +113,23 @@ export function agentTools(
113
113
  ),
114
114
  make(
115
115
  "agent_steer",
116
- "Send input to a descendant and/or re-arm its report-only timeout. With message: working threads receive queued steering; completed, stopped and paused threads resume the SAME session with its previous context. With timeoutMs (30000–300000): the timeout fires that many ms from now, replacing any pending timer. timeoutMs WITHOUT message only re-arms the timeout of a running child (error if not running) and does not steer or resume it; with both, steer and re-arm. At least one is required. Returns immediately; use agent_wait for the result.",
116
+ 'Send input to a descendant and/or re-arm its report-only timeout. With message: working threads receive queued steering; completed, stopped and paused threads resume the SAME session with its previous context. With timeoutMs (30000–300000): the timeout fires that many ms from now, replacing any pending timer. To extend a running background agent\'s reporting timer without sending input, call agent_steer({path: "/root/task", timeoutMs: 120000}) and omit message entirely. This resets the timer to 120000 ms from now, not an addition to the old deadline. timeoutMs WITHOUT message only re-arms the timeout of a running child (error if not running) and does not steer, interrupt or resume it; with both, steer and re-arm. At least one is required. Returns immediately; use agent_wait for the result.',
117
117
  Type.Object({
118
118
  path,
119
- message: Type.Optional(text),
120
- timeoutMs: Type.Optional(Type.Integer({ minimum: 30000, maximum: 300000 })),
119
+ message: Type.Optional(
120
+ Type.String({
121
+ minLength: 1,
122
+ description: "Input to send or resume with. Omit entirely for a timer-only re-arm.",
123
+ }),
124
+ ),
125
+ timeoutMs: Type.Optional(
126
+ Type.Integer({
127
+ minimum: 30000,
128
+ maximum: 300000,
129
+ description:
130
+ "Reset the report-only timer to this many ms from now, replacing any pending timer. With no message, only re-arms a running agent; does not send input, interrupt or resume it.",
131
+ }),
132
+ ),
121
133
  }),
122
134
  async (params) =>
123
135
  result(compact(await threads().steer(params.path, params.message, params.timeoutMs))),
@@ -19,6 +19,9 @@ export type SubagentMode = (typeof SUBAGENT_MODES)[number];
19
19
  export const WIDGET_MODES = ["full", "minimal"] as const;
20
20
  export type WidgetMode = (typeof WIDGET_MODES)[number];
21
21
 
22
+ export const COST_DISPLAY_MODES = ["pi-footer-event", "pi-footer-status", "pi-status"] as const;
23
+ export type CostDisplayMode = (typeof COST_DISPLAY_MODES)[number];
24
+
22
25
  export const LOADER_STYLES = ["circle", "braille", "hourglass"] as const;
23
26
  export type LoaderStyle = (typeof LOADER_STYLES)[number];
24
27
 
@@ -36,6 +39,7 @@ export interface ManagerSettings {
36
39
  subagentMode: SubagentMode;
37
40
  toolFiltering: ToolFilteringMode;
38
41
  widgetMode: WidgetMode;
42
+ costDisplay: CostDisplayMode;
39
43
  nerdFontIcons: boolean;
40
44
  loaderStyle: LoaderStyle;
41
45
  finalRecap: boolean;
@@ -53,13 +57,14 @@ export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
53
57
  subagentMode: "opportunistic",
54
58
  toolFiltering: "allowed",
55
59
  widgetMode: "full",
60
+ costDisplay: "pi-footer-status",
56
61
  nerdFontIcons: false,
57
62
  loaderStyle: "circle",
58
63
  finalRecap: false,
59
64
  };
60
65
 
61
66
  const KEYS = [
62
- "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering", "widgetMode", "nerdFontIcons", "loaderStyle", "finalRecap",
67
+ "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering", "widgetMode", "costDisplay", "nerdFontIcons", "loaderStyle", "finalRecap",
63
68
  ] as const;
64
69
  const MAX_LEVELS = 32;
65
70
 
@@ -100,6 +105,7 @@ function requirement(key: (typeof KEYS)[number]): string {
100
105
  if (key === "nerdFontIcons" || key === "finalRecap") return `${key} must be a boolean`;
101
106
  if (key === "subagentMode") return "subagentMode must be off, opportunistic or orchestration";
102
107
  if (key === "widgetMode") return "widgetMode must be full or minimal";
108
+ if (key === "costDisplay") return "costDisplay must be pi-footer-event, pi-footer-status or pi-status";
103
109
  if (key === "loaderStyle") return "loaderStyle must be circle, braille or hourglass";
104
110
  if (key === "toolFiltering") return "toolFiltering must be allowed, all-except-blocked or all";
105
111
  if (key === "modelSelection")
@@ -154,6 +160,11 @@ function parseSettings(content: string): Partial<ManagerSettings> {
154
160
  layer.widgetMode = value as WidgetMode;
155
161
  continue;
156
162
  }
163
+ if (key === "costDisplay") {
164
+ if (!COST_DISPLAY_MODES.includes(value as CostDisplayMode)) throw new Error(requirement(key));
165
+ layer.costDisplay = value as CostDisplayMode;
166
+ continue;
167
+ }
157
168
  if (key === "loaderStyle") {
158
169
  if (!LOADER_STYLES.includes(value as LoaderStyle)) throw new Error(requirement(key));
159
170
  layer.loaderStyle = value as LoaderStyle;
@@ -2,6 +2,7 @@ import { homedir } from "node:os";
2
2
  import type { Usage } from "@earendil-works/pi-ai";
3
3
  import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
4
4
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
+ import type { CostDisplayMode } from "../prefs/settings.ts";
5
6
 
6
7
  export function footerUsage(entries: readonly SessionEntry[]) {
7
8
  const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
@@ -46,18 +47,39 @@ export class CostFooterController {
46
47
  private installed = false;
47
48
  private requestRender: (() => void) | undefined;
48
49
 
50
+ private publishedMode: CostDisplayMode | undefined;
51
+ private statusContext: ExtensionContext | undefined;
49
52
  constructor(
50
53
  private readonly pi: Pick<ExtensionAPI, "getCommands" | "events">,
51
54
  private readonly subagentCost: () => number,
52
55
  private readonly nerdFontIcons: () => boolean,
56
+ private readonly displayMode: () => CostDisplayMode = () => "pi-footer-status",
53
57
  ) {}
54
58
 
55
59
  refresh(ctx: ExtensionContext): void {
56
- // Publishing is independent of which footer owns the screen, including headless sessions.
57
- this.pi.events.emit(COST_WIDGET_EVENT, {
58
- widgetId: COST_WIDGET_ID,
59
- value: formatSubagentCost(this.subagentCost(), this.nerdFontIcons()),
60
- });
60
+ const mode = this.displayMode();
61
+ const value = formatSubagentCost(this.subagentCost(), this.nerdFontIcons());
62
+ if (this.publishedMode !== undefined && this.publishedMode !== mode) {
63
+ this.clear();
64
+ this.reset(ctx);
65
+ }
66
+ this.publishedMode = mode;
67
+ if (mode !== "pi-footer-event") {
68
+ if (ctx.hasUI) {
69
+ this.statusContext = ctx;
70
+ const statusValue =
71
+ mode === "pi-status"
72
+ ? `Total: ${formatSubagentCost(
73
+ footerUsage(ctx.sessionManager.getEntries()).cost + this.subagentCost(),
74
+ this.nerdFontIcons(),
75
+ )}`
76
+ : value;
77
+ ctx.ui.setStatus(COST_WIDGET_ID, statusValue);
78
+ }
79
+ return;
80
+ }
81
+ // Event mode also works in headless sessions; status modes need a UI consumer.
82
+ this.pi.events.emit(COST_WIDGET_EVENT, { widgetId: COST_WIDGET_ID, value });
61
83
  if (hasExternalFooter(this.pi)) {
62
84
  // Do not clear setFooter here: it could already belong to pi-footer.
63
85
  this.installed = false;
@@ -80,7 +102,11 @@ export class CostFooterController {
80
102
  }
81
103
 
82
104
  clear(): void {
83
- this.pi.events.emit(COST_WIDGET_EVENT, { widgetId: COST_WIDGET_ID, value: null });
105
+ if (this.publishedMode === "pi-footer-event")
106
+ this.pi.events.emit(COST_WIDGET_EVENT, { widgetId: COST_WIDGET_ID, value: null });
107
+ this.statusContext?.ui.setStatus(COST_WIDGET_ID, undefined);
108
+ this.statusContext = undefined;
109
+ this.publishedMode = undefined;
84
110
  }
85
111
  }
86
112
 
@@ -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",
@@ -8,6 +8,7 @@ import {
8
8
  } from "./dialog.ts";
9
9
  import {
10
10
  DEFAULT_MANAGER_SETTINGS,
11
+ type CostDisplayMode,
11
12
  LOADER_STYLES,
12
13
  type LoaderStyle,
13
14
  loadManagerSaveScope,
@@ -117,6 +118,24 @@ const WIDGET_MODE_OPTIONS = [
117
118
  const WIDGET_MODE_HELP =
118
119
  "Full: detailed agent status rows above the input box.\nMinimal: one-line status counts and cumulative input/output tokens for active (starting/running) agents.\nSave and apply to update the widget immediately.";
119
120
 
121
+ const COST_DISPLAY_OPTIONS = [
122
+ {
123
+ id: "pi-footer-event",
124
+ label: "pi-footer event",
125
+ help: "Publish settled subagent-only USD via pi-footer:update-widget with Widget ID subagent_cost. Add a Pi Event Value widget manually and enable Raw value only. Without an external /footer, retain the combined-cost fallback.",
126
+ },
127
+ {
128
+ id: "pi-footer-status",
129
+ label: "pi-footer status key",
130
+ help: "Publish settled subagent-only USD under status key subagent_cost for pi-footer’s Extension Status selector, including $0.0000 before any cost settles. Does not replace your footer.",
131
+ },
132
+ {
133
+ id: "pi-status",
134
+ label: "Pi status only",
135
+ help: "Only update Pi’s status with total USD cost: main session + all settled subagents. pi-footer modes show subagent-only cost. No pi-footer events or custom footer. Third-party footers may also consume this status key.",
136
+ },
137
+ ] as const;
138
+
120
139
  const MODEL_SELECTION_OPTIONS = [
121
140
  {
122
141
  id: "pick-first-available",
@@ -207,6 +226,12 @@ async function configureAgentsDialog(
207
226
  value: WIDGET_MODE_OPTIONS.find((mode) => mode.id === draft.widgetMode)!.label,
208
227
  help: WIDGET_MODE_HELP,
209
228
  },
229
+ {
230
+ id: "costDisplay",
231
+ label: "[labs] Cost display",
232
+ value: COST_DISPLAY_OPTIONS.find((mode) => mode.id === draft.costDisplay)!.label,
233
+ help: "Choose pi-footer event, pi-footer status key (default), or Pi status only. ID: subagent_cost. pi-footer modes: settled subagent-only USD. Pi status: main session + all settled subagents; publishes on session start and as soon as a subagent starts. Save to apply immediately.",
234
+ },
210
235
  {
211
236
  id: "nerdFontIcons",
212
237
  label: "[labs] Nerd Font icons",
@@ -306,6 +331,12 @@ async function configureAgentsDialog(
306
331
  });
307
332
  if (WIDGET_MODE_OPTIONS.some((option) => option.id === mode))
308
333
  draft.widgetMode = mode as WidgetMode;
334
+ } else if (action === "costDisplay") {
335
+ const mode = await dialogMenu(ctx, "[labs] Cost display", [...COST_DISPLAY_OPTIONS], {
336
+ selectedId: draft.costDisplay,
337
+ });
338
+ if (COST_DISPLAY_OPTIONS.some((option) => option.id === mode))
339
+ draft.costDisplay = mode as CostDisplayMode;
309
340
  } else if (action === "nerdFontIcons") {
310
341
  draft.nerdFontIcons = !draft.nerdFontIcons;
311
342
  } else if (action === "loaderStyle") {
@@ -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
+ }