pi-subagent-manager 0.11.1 → 0.12.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
@@ -72,10 +72,12 @@ They inherit your current model until you set preferences. Details: [docs/defaul
72
72
  | `/agents import` | Import agents from other subagent extensions |
73
73
  | `/agents reload` | Reload definitions and settings |
74
74
 
75
- A live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** opens an agent's live view. Type in the bottom **Steer** input and press **Enter** to send it a steering message, including nested agents. **Tab** switches between input and transcript controls, **Escape** returns, and **i** in the tree opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Once the main turn ends and all subagents are idle, the preview collapses to a single status-count line; `/agents tree` still opens the full tree. Press **Left** at the start of the main draft to open it; normal cursor movement is unchanged. See [live navigation](docs/tools-and-ui.md#live-agent-navigation) for controls and compatibility.
75
+ A live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** opens an agent's live view. Type in the bottom **Steer** input and press **Enter** to send it a steering message, including nested agents. **Tab** switches between input and transcript controls, **Escape** returns, and **i** in the tree opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Once the main turn ends and all subagents are idle, the preview collapses to a single status-count line; `/agents tree` still opens the full tree. While subagents are starting or running, press **Left** at the start of the main draft to open it; otherwise Left stays native. `/agents tree` remains available regardless of agent activity. See [live navigation](docs/tools-and-ui.md#live-agent-navigation) for controls and compatibility.
76
76
 
77
77
  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). 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).
78
78
 
79
+ Enable **[labs] Final Recap** in `/agents` to automatically ask the idle main agent to summarize detached-agent results, keeping the final response in the main thread. It is off by default and suppressed by Subagent Mode Off. **Enabling it may cause extra model turns and uses more tokens and context.** See [Final Recap](docs/settings.md#labs-final-recap-finalrecap).
80
+
79
81
  ## Docs
80
82
 
81
83
  - [Your own agent](docs/custom-agents.md) — walkthrough for writing an agent type
package/docs/settings.md CHANGED
@@ -16,6 +16,7 @@ All keys are optional. Defaults:
16
16
  "subagentMode": "opportunistic",
17
17
  "widgetMode": "full",
18
18
  "nerdFontIcons": false,
19
+ "finalRecap": false,
19
20
  "modelSelection": "pick-first-scoped",
20
21
  "toolFiltering": "allowed",
21
22
  "maxLevels": 3,
@@ -62,6 +63,14 @@ When enabled, an agent type’s optional `icon` appears before its readable name
62
63
 
63
64
  All six bundled agents have [role-specific icons](default-agents.md#nerd-font-icons). Add or change an icon with **[labs] Icon** in `/agents types`, or the optional `icon` frontmatter field in [your own agent](custom-agents.md#icons-labs). Retained threads keep the icon from their saved agent definition.
64
65
 
66
+ ## [labs] Final Recap (`finalRecap`)
67
+
68
+ **[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.
69
+
70
+ When detached agents finish or fail and the main agent is idle, their results are sent back to the main agent for an automatic summary. The summary is a main-thread response, so child notifications do not become the final visible message. Progress updates do not trigger summaries, and active main-agent work is not interrupted. **Subagent Mode Off** suppresses automatic summaries even if this setting is enabled.
71
+
72
+ **Enabling Final Recap may cause extra model turns and uses more tokens and context.** Leave it off if you prefer to inspect results manually in `/agents tree` or request a summary yourself.
73
+
65
74
  ## Model Picking (`modelSelection`)
66
75
 
67
76
  Which model an agent gets when its session starts.
@@ -25,6 +25,8 @@
25
25
 
26
26
  Then `agent_wait` or `agent_status` on `/root/controller-security-research`.
27
27
 
28
+ Child progress and completion notifications are retained in the main agent's context without adding visible chat messages. By default they do not start another turn, keeping the main agent's final response last in the conversation even when detached children finish later. The opt-in **[labs] Final Recap** setting asks an idle main agent to summarize newly completed or failed asynchronous agents; results arriving during a summary are handled after that summary finishes. Progress updates and foreground results do not trigger summaries. Enabling it uses more tokens and context. Use the Agents widget, `/agents tree`, or `agent_output` to inspect child status and answers.
29
+
28
30
  ## Parallel and nested work
29
31
 
30
32
  - Launch **all independent siblings with `wait: false`, then wait**. Spawning one foreground child and waiting before the next is sequential.
@@ -58,7 +60,7 @@ Refreshes every second and keeps your selection, collapse state and scroll posit
58
60
 
59
61
  ### Live agent navigation
60
62
 
61
- The fullscreen watcher shows steer and agent messages in full, including the in-progress assistant reply. Tool calls, results, and other metadata show their name/status and only the first three wrapped lines of each arguments/output preview, followed by `...` when more is hidden. Use **i → Transcript** from the tree for retained tool details. Thinking is initially hidden (**t** toggles it with transcript controls focused). 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.
63
+ 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.
62
64
 
63
65
  - 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.
64
66
  - **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.
@@ -68,13 +70,13 @@ The fullscreen watcher shows steer and agent messages in full, including the in-
68
70
 
69
71
  #### Left-arrow entry
70
72
 
71
- Press physical **Left (←)** at the beginning of the main draft (or in an empty input) to open the subagent browser. Elsewhere, Left retains normal cursor movement. Down is always native editing/history navigation. Autocomplete, jumps, paste and configured shortcuts take precedence. Navigating preserves the main draft/cursor and does not require the root to be idle.
73
+ While any subagent is **starting or running**, press physical **Left (←)** at the beginning of the main draft (or in an empty input) to open the subagent browser. With no active subagents, or elsewhere in the draft, Left retains normal cursor movement. `/agents tree` remains available regardless of agent activity. Down is always native editing/history navigation. Autocomplete, jumps, paste and configured shortcuts take precedence. Navigating preserves the main draft/cursor and does not require the root to be idle.
72
74
 
73
75
  Left-arrow entry is enabled by default in the TUI; `/agents tree` remains available everywhere. Pi has one custom-editor slot: installation is skipped if another factory owns it or an existing draft is nonempty, since the host cannot transfer cursor/undo/expanded-paste state. Load order can still let a later editor replace ours. Initial startup uses Pi's history hydration; replacement installations seed history once. Session-tree rebuilds keep the existing editor instance.
74
76
 
75
77
  While navigation is open, the host fullscreen search shortcut is temporarily disabled through public keybindings to avoid stacking a second host overlay. The prior binding owner is restored only if no other extension replaced it. **Known host limitation:** if an unrelated extension stacks another overlay above navigation, Pi's custom-UI completion can close the newer overlay instead. Avoid concurrent extension-owned overlays; a host identity-targeted completion API is needed to remove this limitation. No private host access or unsupported overlay-lifecycle workaround is used.
76
78
 
77
- Run `python3 scripts/live-agent-navigation-smoke.py` after `npm install` for credential-free, offline POSIX PTY checks in regular/fullscreen mode (entry, root return, draft restoration, resize and host-search suppression). No model prompts are submitted. Broader manual acceptance covers concurrent live turns, autocomplete/paste/undo interactions, remapped shortcuts and rich custom content.
79
+ Run `python3 scripts/live-agent-navigation-smoke.py` after `npm install` for credential-free, offline POSIX PTY checks in regular/fullscreen mode (idle Left gating, explicit command entry, root return, resize and host-search suppression). No model prompts are submitted. Broader manual acceptance covers concurrent live turns, autocomplete/paste/undo interactions, remapped shortcuts and rich custom content.
78
80
 
79
81
  ## Agents widget
80
82
 
@@ -83,7 +85,7 @@ The widget above the input editor has two display modes, selected with **Status
83
85
  - **Full** (default): the existing compact tree, at most twelve lines.
84
86
  - **Minimal**: a summary line such as `3 running, 2 stopped, 1 failed, 1 paused ↑12k ↓3k`, with semantic theme colors. Starting agents count as running; completed agents are counted when present. Token totals include only currently starting/running agents, not the main conversation or settled threads. Use `/agents tree` for details.
85
87
 
86
- Once the main turn has ended and no subagents are starting or running, either mode collapses to a single status-count line without the browser hint. The full tree remains available via `/agents tree` or **Left** at the start of the draft. A new main turn or active subagent restores the configured display mode.
88
+ Once the main turn has ended and no subagents are starting or running, either mode collapses to a single status-count line without the browser hint. The full tree remains available via `/agents tree`; **Left** at the start of the draft opens it only while subagents are starting or running. A new main turn or active subagent restores the configured display mode.
87
89
 
88
90
  In full mode:
89
91
 
@@ -91,7 +93,7 @@ In full mode:
91
93
  - A second, indented line shows latest activity.
92
94
  - Active branches are shown first; the most recent agents within each state are preferred when previews overflow. Overflow is counted, not listed.
93
95
  - Time freezes while paused and resumes on continue.
94
- - A small status strip below the previews shows the running count (including starting agents) and **Press ← to open subagent browser**, including when agents overflow. Minimal mode also shows the hint. RPC output omits the keyboard hint.
96
+ - A small status strip below the previews shows the running count (including starting agents) and **Press ← to open subagent browser**, including when agents overflow. Full and minimal modes show the hint only while subagents are starting or running. RPC output omits the keyboard hint.
95
97
 
96
98
  ### Interrupts and stopping agents
97
99
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.11.1",
3
+ "version": "0.12.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
package/src/index.ts CHANGED
@@ -18,9 +18,11 @@ import type { SavedThread, ThreadEvent } from "./types.ts";
18
18
 
19
19
  const REGISTRY_ENTRY = "pi-subagent:registry:v1";
20
20
  const ROOT_MAILBOX_ENTRY = "pi-subagent:root-mailbox:v1";
21
+ const ROOT_SUMMARY_MESSAGE = "pi-subagent:final-recap";
21
22
  type RootNotification = {
22
23
  rootSessionId: string;
23
24
  content: string;
25
+ finalRecap?: boolean;
24
26
  details: { mailboxId: string; path: string; state: string };
25
27
  };
26
28
 
@@ -49,6 +51,14 @@ export default function piSubagent(pi: ExtensionAPI): void {
49
51
  };
50
52
  let generation = 0;
51
53
  let rootTurnEnded = false;
54
+ let summaryRunning = false;
55
+ let suspendingSummaries = false;
56
+ let summaryTimer: ReturnType<typeof setTimeout> | undefined;
57
+ const cancelSummary = () => {
58
+ if (summaryTimer !== undefined) clearTimeout(summaryTimer);
59
+ summaryTimer = undefined;
60
+ summaryRunning = false;
61
+ };
52
62
  let navigation = new AgentNavigationController();
53
63
  let navigationEditor: AgentNavigationEditor | undefined;
54
64
  let navigationEditorFactory: Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0];
@@ -80,7 +90,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
80
90
  initialHistory: seedHistory ? history : undefined,
81
91
  generation: () => navigationGeneration,
82
92
  canOpen: () => manager !== undefined && context?.mode === "tui" &&
83
- limits.subagentMode !== "off" && !navigation.isOpen,
93
+ limits.subagentMode !== "off" && !navigation.isOpen &&
94
+ manager.list().some((thread) => thread.path !== "/root" &&
95
+ (thread.state === "starting" || thread.state === "running")),
84
96
  openTree: () => manager && context
85
97
  ? navigation.open(context, manager.scope("/root"), undefined, limits.nerdFontIcons) : undefined,
86
98
  onError: (error) => context?.ui.notify(
@@ -147,12 +159,62 @@ export default function piSubagent(pi: ExtensionAPI): void {
147
159
  {
148
160
  customType: "pi-subagent:update",
149
161
  content: notification.content,
150
- display: true,
162
+ // Keep asynchronous child updates in model context, not the main chat.
163
+ // Idle/settlement delivery can follow the root's final answer; rendering it
164
+ // would leave a child's output as the last visible message. The widget and
165
+ // agent browser provide status/output without displacing the root response.
166
+ display: false,
151
167
  details: notification.details,
152
168
  },
153
169
  { triggerTurn: false },
154
170
  );
155
171
  };
172
+ const pendingSummaries = (ctx: ExtensionContext) => {
173
+ const entries = ctx.sessionManager.getBranch();
174
+ const summarized = new Set(entries.flatMap((entry) => {
175
+ if (entry.type !== "custom_message" || entry.customType !== ROOT_SUMMARY_MESSAGE) return [];
176
+ const ids = (entry.details as { mailboxIds?: unknown } | undefined)?.mailboxIds;
177
+ return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : [];
178
+ }));
179
+ return entries.flatMap((entry) => {
180
+ if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) return [];
181
+ const notification = entry.data as RootNotification | undefined;
182
+ return notification?.rootSessionId === ctx.sessionManager.getSessionId() &&
183
+ notification.finalRecap === true && typeof notification.content === "string" &&
184
+ typeof notification.details?.mailboxId === "string" &&
185
+ !summarized.has(notification.details.mailboxId) ? [notification] : [];
186
+ });
187
+ };
188
+ const scheduleSummary = (ctx: ExtensionContext) => {
189
+ if (!limits.finalRecap || limits.subagentMode === "off" || summaryRunning || suspendingSummaries ||
190
+ summaryTimer !== undefined || ctx.isIdle() === false || !pendingSummaries(ctx).length) return;
191
+ const currentGeneration = generation;
192
+ // Coalesce siblings finishing together and leave the settlement boundary before
193
+ // starting a new turn. Recheck settings/session/idle state after the deferral.
194
+ summaryTimer = setTimeout(() => {
195
+ summaryTimer = undefined;
196
+ if (currentGeneration !== generation || context?.sessionManager !== ctx.sessionManager ||
197
+ !limits.finalRecap || limits.subagentMode === "off" || suspendingSummaries || ctx.isIdle() === false) return;
198
+ const notifications = pendingSummaries(ctx);
199
+ if (!notifications.length) return;
200
+ summaryRunning = true;
201
+ try {
202
+ pi.sendMessage({
203
+ customType: ROOT_SUMMARY_MESSAGE,
204
+ content: "Summarize the newly finished asynchronous subagent results for the user. " +
205
+ "Their results are in the preceding subagent notifications; use agent_output if more detail is needed. " +
206
+ "Give a concise main-thread answer covering results and any failures. " +
207
+ "Do not spawn or resume agents solely to summarize.\nAgents: " +
208
+ [...new Set(notifications.map((notification) => notification.details.path))].join(", "),
209
+ display: false,
210
+ details: { mailboxIds: notifications.map((notification) => notification.details.mailboxId) },
211
+ }, { triggerTurn: true });
212
+ } catch (error) {
213
+ summaryRunning = false;
214
+ warnDelivery(error);
215
+ }
216
+ }, 0);
217
+ };
156
218
  const restoreRootMailbox = (ctx: ExtensionContext) => {
157
219
  if (limits.subagentMode === "off" || ctx.isIdle?.() === false) return;
158
220
  const entries = ctx.sessionManager.getBranch();
@@ -176,9 +238,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
176
238
  delivered.add(notification.details.mailboxId);
177
239
  }
178
240
  }
241
+ scheduleSummary(ctx);
179
242
  };
180
243
  pi.on("agent_settled", async (_event, ctx) => {
181
- if (context?.sessionManager === ctx.sessionManager) restoreRootMailbox(ctx);
244
+ if (context?.sessionManager === ctx.sessionManager) {
245
+ summaryRunning = false;
246
+ restoreRootMailbox(ctx);
247
+ }
182
248
  });
183
249
  const delivery = (event: ThreadEvent) => {
184
250
  if (event.kind === "change" || event.kind === "metrics") return;
@@ -194,6 +260,11 @@ export default function piSubagent(pi: ExtensionAPI): void {
194
260
  const notification: RootNotification = {
195
261
  rootSessionId: requireContext().sessionManager.getSessionId(),
196
262
  content: message,
263
+ // Foreground results already handled by a busy main thread do not need
264
+ // another turn. Completions during a summary do need a follow-up summary.
265
+ finalRecap: limits.finalRecap && !suspendingSummaries && event.kind === "settled" &&
266
+ (thread.state === "completed" || thread.state === "failed") &&
267
+ (requireContext().isIdle() || summaryRunning),
197
268
  details: {
198
269
  mailboxId: randomUUID(),
199
270
  path: thread.path,
@@ -203,7 +274,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
203
274
  // Persist first; defer delivery until the root is idle and the plugin is enabled.
204
275
  // The eventual transcript message carries its ID for branch-local recovery.
205
276
  pi.appendEntry(ROOT_MAILBOX_ENTRY, notification);
206
- sendRootNotification(notification);
277
+ restoreRootMailbox(requireContext());
207
278
  } else void requireManager().deliver(event.recipient, message).catch(warnDelivery);
208
279
  } catch (error) {
209
280
  warnDelivery(error);
@@ -264,6 +335,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
264
335
  });
265
336
 
266
337
  const attachSession = async (ctx: ExtensionContext, installEditor = false, seedHistory = true) => {
338
+ cancelSummary();
267
339
  const token = ++generation;
268
340
  closeNavigation(installEditor);
269
341
  navigation = new AgentNavigationController();
@@ -334,11 +406,18 @@ export default function piSubagent(pi: ExtensionAPI): void {
334
406
  });
335
407
  pi.on("session_tree", async (_event, ctx) => attachSession(ctx));
336
408
  const stopWorkingThreads = async () => {
409
+ cancelSummary();
337
410
  closeNavigation();
338
- if (!manager) return;
339
- for (const thread of manager.list()) {
340
- const state = manager.get(thread.path).state;
341
- if (state === "starting" || state === "running") await manager.stop("/root", thread.path);
411
+ suspendingSummaries = true;
412
+ try {
413
+ if (!manager) return;
414
+ for (const thread of manager.list()) {
415
+ const state = manager.get(thread.path).state;
416
+ if (state === "starting" || state === "running") await manager.stop("/root", thread.path);
417
+ }
418
+ } finally {
419
+ cancelSummary();
420
+ suspendingSummaries = false;
342
421
  }
343
422
  };
344
423
  // Finish old-thread cancellation while appendEntry still points to the old branch/session.
@@ -346,6 +425,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
346
425
  pi.on("session_before_switch", stopWorkingThreads);
347
426
  pi.on("session_before_fork", stopWorkingThreads);
348
427
  pi.on("session_shutdown", async () => {
428
+ cancelSummary();
349
429
  generation++;
350
430
  closeNavigation(true);
351
431
  await manager?.shutdown();
@@ -34,6 +34,7 @@ export interface ManagerSettings {
34
34
  toolFiltering: ToolFilteringMode;
35
35
  widgetMode: WidgetMode;
36
36
  nerdFontIcons: boolean;
37
+ finalRecap: boolean;
37
38
  maxLevels: number;
38
39
  maxConcurrent: number;
39
40
  maxThreads: number;
@@ -49,10 +50,11 @@ export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
49
50
  toolFiltering: "allowed",
50
51
  widgetMode: "full",
51
52
  nerdFontIcons: false,
53
+ finalRecap: false,
52
54
  };
53
55
 
54
56
  const KEYS = [
55
- "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering", "widgetMode", "nerdFontIcons",
57
+ "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering", "widgetMode", "nerdFontIcons", "finalRecap",
56
58
  ] as const;
57
59
  const MAX_LEVELS = 32;
58
60
 
@@ -90,7 +92,7 @@ function positiveSafeInteger(value: unknown): value is number {
90
92
  }
91
93
 
92
94
  function requirement(key: (typeof KEYS)[number]): string {
93
- if (key === "nerdFontIcons") return "nerdFontIcons must be a boolean";
95
+ if (key === "nerdFontIcons" || key === "finalRecap") return `${key} must be a boolean`;
94
96
  if (key === "subagentMode") return "subagentMode must be off, opportunistic or orchestration";
95
97
  if (key === "widgetMode") return "widgetMode must be full or minimal";
96
98
  if (key === "toolFiltering") return "toolFiltering must be allowed, all-except-blocked or all";
@@ -125,9 +127,9 @@ function parseSettings(content: string): Partial<ManagerSettings> {
125
127
  for (const key of KEYS) {
126
128
  if (!Object.hasOwn(record, key)) continue;
127
129
  const value = record[key];
128
- if (key === "nerdFontIcons") {
130
+ if (key === "nerdFontIcons" || key === "finalRecap") {
129
131
  if (typeof value !== "boolean") throw new Error(requirement(key));
130
- layer.nerdFontIcons = value;
132
+ layer[key] = value;
131
133
  continue;
132
134
  }
133
135
  if (key === "subagentMode") {
@@ -15,11 +15,15 @@ import type { ThreadService, TranscriptSnapshot } from "../types.ts";
15
15
  import { dialogText, type DialogHost } from "./dialog.ts";
16
16
  import { agentTypeLabel } from "./ui.ts";
17
17
 
18
+ /** Transcript detail level cycled by the t key: full → preview → compact. */
19
+ export type TranscriptDetail = "full" | "preview" | "compact";
20
+ const DETAIL_CYCLE: TranscriptDetail[] = ["full", "preview", "compact"];
21
+
18
22
  export interface AgentViewportState {
19
23
  scrollTop: number;
20
24
  follow: boolean;
21
25
  showInherited?: boolean;
22
- showThinking?: boolean;
26
+ detail?: TranscriptDetail;
23
27
  }
24
28
 
25
29
  /** Fully cover main, including at very small sizes; only trusted renderers emit terminal sequences. */
@@ -60,7 +64,7 @@ export class LiveAgentView {
60
64
  private attachment = 0;
61
65
  private unsubscribe: (() => void) | undefined;
62
66
  private renderTimer: ReturnType<typeof setTimeout> | undefined;
63
- private cache = new WeakMap<object, { width: number; thinking: boolean; lines: string[] }>();
67
+ private cache = new WeakMap<object, { width: number; detail: TranscriptDetail; lines: string[] }>();
64
68
  private scroll: ScrollView;
65
69
  private content: string[] = [];
66
70
  private restoreViewport = true;
@@ -235,7 +239,8 @@ export class LiveAgentView {
235
239
  this.viewport.showInherited = !this.viewport.showInherited;
236
240
  this.invalidate();
237
241
  } else if (data === "t") {
238
- this.viewport.showThinking = !this.viewport.showThinking;
242
+ this.viewport.detail =
243
+ DETAIL_CYCLE[(DETAIL_CYCLE.indexOf(this.detail) + 1) % DETAIL_CYCLE.length];
239
244
  this.invalidate();
240
245
  } else if (matchesKey(data, Key.home)) this.scroll.scrollTo(0, { disableFollow: true });
241
246
  else if (matchesKey(data, Key.end) || data === "l") this.scroll.scrollToEnd();
@@ -249,6 +254,10 @@ export class LiveAgentView {
249
254
  this.viewport.follow = this.scroll.isFollowingEnd;
250
255
  }
251
256
 
257
+ private get detail(): TranscriptDetail {
258
+ return this.viewport.detail ?? "preview";
259
+ }
260
+
252
261
  private wrap(value: string, width: number): string[] {
253
262
  return text(value)
254
263
  .split("\n")
@@ -302,26 +311,23 @@ export class LiveAgentView {
302
311
  if (!block) return this.wrap(json(value), width);
303
312
  if (block.type === "text") return this.markdown(String(block.text ?? ""), width);
304
313
  if (block.type === "image") return ["[Image — text-only observer]"];
305
- if (block.type === "thinking")
306
- return this.viewport.showThinking
307
- ? this.markdown(String(block.thinking ?? "[redacted thinking]"), width, true)
308
- : [this.theme.fg("dim", "[Thinking hidden · t show]")];
314
+ if (block.type === "thinking") {
315
+ if (this.detail === "compact")
316
+ return [this.theme.fg("dim", "[Thinking hidden · t cycles view]")];
317
+ // Thinking is model-authored Markdown; preview truncates the rendered lines, not the source.
318
+ const rendered = this.markdown(String(block.thinking ?? "[redacted thinking]"), width, true);
319
+ if (this.detail === "full" || rendered.length <= 3) return rendered;
320
+ return [...rendered.slice(0, 3), this.theme.fg("dim", "...")];
321
+ }
309
322
  if (block.type === "toolCall")
310
- return [
311
- this.theme.fg(
312
- "accent",
313
- dialogText(`Tool call: ${String(block.name)} (${String(block.id)})`),
314
- ),
315
- ...this.preview(json(block.arguments), width),
316
- ];
323
+ return this.toolCall(String(block.name), block.arguments, width);
317
324
  return this.preview(json(block), width);
318
325
  });
319
326
  }
320
327
 
321
328
  private message(message: AgentMessage, width: number): string[] {
322
329
  const cached = this.cache.get(message);
323
- if (cached && cached.width === width && cached.thinking === !!this.viewport.showThinking)
324
- return cached.lines;
330
+ if (cached && cached.width === width && cached.detail === this.detail) return cached.lines;
325
331
  const data = message as unknown as Record<string, unknown>;
326
332
  const label =
327
333
  message.role === "toolResult"
@@ -340,10 +346,112 @@ export class LiveAgentView {
340
346
  : []),
341
347
  "",
342
348
  ];
343
- this.cache.set(message, { width, thinking: !!this.viewport.showThinking, lines });
349
+ this.cache.set(message, { width, detail: this.detail, lines });
344
350
  return lines;
345
351
  }
346
352
 
353
+ /**
354
+ * Pi-style tool call lines, mirroring the main session's built-in renderers (`$ command`,
355
+ * `read path:range`, `grep /pattern/ in path`, …) instead of bare JSON. All interpolated values
356
+ * are sanitized; unknown tools fall back to pretty-printed JSON. Shaped by the detail mode:
357
+ * compact keeps one truncated line, preview keeps three wrapped rows, full keeps everything
358
+ * (bounded by the preview byte cap for pathological payloads).
359
+ */
360
+ private toolCall(name: string, args: unknown, width: number): string[] {
361
+ const data = object(args);
362
+ const str = (key: string): string | undefined => {
363
+ const value = data?.[key];
364
+ return typeof value === "string" ? text(value) : undefined;
365
+ };
366
+ const num = (key: string): number | undefined => {
367
+ const value = data?.[key];
368
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
369
+ };
370
+ const title = (value: string) => this.theme.fg("accent", value);
371
+ const detail = (value: string) => this.theme.fg("muted", value);
372
+ const path = str("file_path") ?? str("path");
373
+ let lines: string[];
374
+ switch (name) {
375
+ case "bash":
376
+ case "powershell": {
377
+ const prompt = name === "bash" ? "$" : ">";
378
+ const command = (str("command") ?? "...").split("\n");
379
+ const timeout = num("timeout");
380
+ lines = [
381
+ `${title(`${prompt} ${command[0]}`)}${timeout ? detail(` (timeout ${timeout}s)`) : ""}`,
382
+ ...command.slice(1),
383
+ ];
384
+ break;
385
+ }
386
+ case "read": {
387
+ const offset = num("offset");
388
+ const limit = num("limit");
389
+ const range =
390
+ offset == null && limit == null
391
+ ? ""
392
+ : this.theme.fg(
393
+ "warning",
394
+ `:${offset ?? 1}${limit != null ? `-${(offset ?? 1) + limit - 1}` : ""}`,
395
+ );
396
+ lines = [`${title("read")} ${path ?? "?"}${range}`];
397
+ break;
398
+ }
399
+ case "edit":
400
+ lines = [`${title("edit")} ${path ?? "?"}`];
401
+ break;
402
+ case "write": {
403
+ lines = [`${title("write")} ${path ?? "?"}`];
404
+ const content = str("content");
405
+ if (content) {
406
+ const contentLines = content.split("\n");
407
+ while (contentLines.length && contentLines.at(-1) === "") contentLines.pop();
408
+ lines.push(...contentLines);
409
+ }
410
+ break;
411
+ }
412
+ case "grep": {
413
+ const pattern = str("pattern");
414
+ const glob = str("glob");
415
+ const limit = num("limit");
416
+ lines = [
417
+ `${title("grep")} ${this.theme.fg("accent", `/${pattern ?? ""}/`)}` +
418
+ `${path ? detail(` in ${path}`) : ""}${glob ? detail(` (${glob})`) : ""}` +
419
+ `${limit != null ? detail(` limit ${limit}`) : ""}`,
420
+ ];
421
+ break;
422
+ }
423
+ case "find": {
424
+ const pattern = str("pattern");
425
+ const limit = num("limit");
426
+ lines = [
427
+ `${title("find")} ${this.theme.fg("accent", pattern ?? "")}` +
428
+ `${path ? detail(` in ${path}`) : ""}${limit != null ? detail(` (limit ${limit})`) : ""}`,
429
+ ];
430
+ break;
431
+ }
432
+ case "ls": {
433
+ const limit = num("limit");
434
+ lines = [`${title("ls")} ${path ?? "."}${limit != null ? detail(` (limit ${limit})`) : ""}`];
435
+ break;
436
+ }
437
+ default:
438
+ lines = [title(dialogText(name)), ...json(args).split("\n")];
439
+ }
440
+ if (this.detail === "compact")
441
+ return [truncateToWidth(lines[0] ?? "", Math.max(1, width), "…", true)];
442
+ const wrapped = lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
443
+ if (this.detail === "preview" && wrapped.length > 3)
444
+ return [...wrapped.slice(0, 3), this.theme.fg("dim", "...")];
445
+ const bounded: string[] = [];
446
+ let chars = 0;
447
+ for (const line of wrapped) {
448
+ if (chars > 32768) return [...bounded, this.theme.fg("dim", "...")];
449
+ bounded.push(line);
450
+ chars += line.length;
451
+ }
452
+ return bounded;
453
+ }
454
+
347
455
  render(width: number): string[] {
348
456
  const height = Math.max(1, this.host.terminal?.rows ?? 24);
349
457
  const columns = Math.max(1, width);
@@ -386,16 +494,15 @@ export class LiveAgentView {
386
494
  );
387
495
  for (const tool of snapshot.tools) {
388
496
  if (committedResults.has(tool.toolCallId)) continue;
389
- body.push(
390
- this.theme.fg(
391
- tool.isError ? "error" : "warning",
392
- dialogText(
393
- `Tool ${tool.toolName} — ${tool.state}${tool.isError ? " (error)" : ""}${tool.parentToolCallId ? " (nested)" : ""}`,
394
- ),
497
+ const call = this.toolCall(tool.toolName, tool.args, columns);
498
+ call[0] = `${call[0]} ${this.theme.fg(
499
+ tool.isError ? "error" : "warning",
500
+ dialogText(
501
+ `— ${tool.state}${tool.isError ? " (error)" : ""}${tool.parentToolCallId ? " (nested)" : ""}`,
395
502
  ),
396
- ...this.preview(json(tool.args), columns),
397
- );
398
- if (tool.result !== undefined)
503
+ )}`;
504
+ body.push(...call);
505
+ if (tool.result !== undefined && this.detail !== "compact")
399
506
  body.push(...this.preview(object(tool.result)?.content ?? tool.result, columns));
400
507
  body.push("");
401
508
  }
@@ -421,7 +528,7 @@ export class LiveAgentView {
421
528
  this.saveViewport();
422
529
  const footer = this.error
423
530
  ? "Ctrl+R Retry · Tab input/transcript · Esc tree · Ctrl+Q main"
424
- : `${this.editing ? "Enter steer · Tab browse" : "Tab steer · Home/End scroll · c context · t thinking"} · Esc tree · Ctrl+Q main · ↑↓/PgUp/PgDn scroll · ${this.viewport.follow ? "following" : "scrolled"}`;
531
+ : `${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"}`;
425
532
  const input = this.input.render(columns)[0]!;
426
533
  const status = this.theme.fg(
427
534
  this.steerStatus ? (this.steerFailed ? "error" : "muted") : this.error ? "error" : "muted",
@@ -197,6 +197,12 @@ async function configureAgentsDialog(
197
197
  value: draft.nerdFontIcons ? "On" : "Off",
198
198
  help: "Experimental: display each agent type’s optional icon.\nRequires a Nerd Font configured in your terminal; otherwise glyphs may appear as boxes.\nOff by default. Save and apply to update the widget immediately.",
199
199
  },
200
+ {
201
+ id: "finalRecap",
202
+ label: "[labs] Final Recap",
203
+ value: draft.finalRecap ? "On" : "Off",
204
+ help: "Experimental: when detached agents finish or fail and the main agent is idle, automatically ask the main agent to summarize their results.\nEnabling this may cause extra model turns and uses more tokens and context.\nOff by default. Subagent Mode Off suppresses automatic summaries.",
205
+ },
200
206
  {
201
207
  id: "scope",
202
208
  label: "Save scope",
@@ -280,6 +286,8 @@ async function configureAgentsDialog(
280
286
  draft.widgetMode = mode as WidgetMode;
281
287
  } else if (action === "nerdFontIcons") {
282
288
  draft.nerdFontIcons = !draft.nerdFontIcons;
289
+ } else if (action === "finalRecap") {
290
+ draft.finalRecap = !draft.finalRecap;
283
291
  } else if (action === "scope") {
284
292
  if (!ctx.isProjectTrusted())
285
293
  ctx.ui.notify(
package/src/ui/ui.ts CHANGED
@@ -473,7 +473,7 @@ export function renderAgentTree(
473
473
  lines.push(agentLine(row, columns, theme, nerdFontIcons));
474
474
  lines.push(activityLine(row, columns, theme));
475
475
  }
476
- lines.push(agentWidgetStatus(live, omitted, columns, theme, showBrowserHint));
476
+ lines.push(agentWidgetStatus(live, omitted, columns, theme, showBrowserHint && live > 0));
477
477
  return lines;
478
478
  }
479
479
 
@@ -521,7 +521,7 @@ export function renderAgentSummary(
521
521
  const right = theme.fg("muted", `↑${formatCount(input)} ↓${formatCount(output)}`);
522
522
  const columns = Math.max(0, width);
523
523
  const lines = [fitLine(left, right, columns)];
524
- if (showBrowserHint)
524
+ if (showBrowserHint && counts.running > 0)
525
525
  lines.push(truncateToWidth(theme.fg("muted", AGENT_BROWSER_HINT), columns, ""));
526
526
  return lines;
527
527
  }