@xzzpig/pi-subagents 0.16.0 → 0.18.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.
Files changed (133) hide show
  1. package/CHANGELOG.md +164 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +17 -10
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/models.md +5 -3
  12. package/docs/observability.md +23 -13
  13. package/docs/standalone-background.md +4 -4
  14. package/docs/tool-reference.md +40 -19
  15. package/docs/watchdog.md +2 -0
  16. package/docs/workflows.md +57 -3
  17. package/inspector-runner.mjs +1 -1
  18. package/package.json +14 -8
  19. package/prompts/council.md +6 -3
  20. package/runner-peer-loader.mjs +4 -7
  21. package/runner-peer-preload.mjs +5 -7
  22. package/skills/pi-subagents/SKILL.md +1 -0
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  24. package/skills/pi-subagents/references/execution-controls.md +6 -4
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  26. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  27. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  28. package/src/agents/agent-eject.ts +3 -3
  29. package/src/agents/agent-management.ts +61 -52
  30. package/src/agents/agent-memory.ts +90 -3
  31. package/src/agents/agent-serializer.ts +4 -4
  32. package/src/agents/agents.ts +125 -51
  33. package/src/agents/global-npm-root.ts +58 -0
  34. package/src/agents/proactive-skills.ts +4 -1
  35. package/src/agents/runtime-agent-registry.ts +14 -11
  36. package/src/agents/skills.ts +42 -9
  37. package/src/api/delegation.ts +15 -0
  38. package/src/api/inspectors.ts +27 -0
  39. package/src/api/preflight.ts +60 -60
  40. package/src/extension/doctor.ts +9 -4
  41. package/src/extension/fanout-child.ts +8 -0
  42. package/src/extension/index.ts +101 -48
  43. package/src/extension/rpc.ts +10 -1
  44. package/src/extension/schemas.ts +12 -6
  45. package/src/extension/subagent-guide.ts +12 -4
  46. package/src/extension/tool-activation.ts +197 -0
  47. package/src/extension/tool-description.ts +1 -1
  48. package/src/inspectors/ghostty/plugin.ts +13 -1
  49. package/src/inspectors/plugins.ts +70 -3
  50. package/src/intercom/intercom-bridge.ts +2 -0
  51. package/src/intercom/native-supervisor-channel.ts +22 -15
  52. package/src/intercom/result-intercom.ts +4 -0
  53. package/src/runs/background/active-async-capacity.ts +3 -25
  54. package/src/runs/background/async-execution.ts +100 -140
  55. package/src/runs/background/async-job-tracker.ts +28 -34
  56. package/src/runs/background/async-resume.ts +16 -8
  57. package/src/runs/background/async-status.ts +2 -0
  58. package/src/runs/background/binary-bootstrap.ts +34 -6
  59. package/src/runs/background/fleet-view.ts +51 -7
  60. package/src/runs/background/notify.ts +93 -7
  61. package/src/runs/background/pid-namespace.ts +18 -0
  62. package/src/runs/background/process-terminal-candidate.ts +98 -0
  63. package/src/runs/background/process-terminal.ts +17 -96
  64. package/src/runs/background/result-watcher.ts +1 -1
  65. package/src/runs/background/retained-children.ts +3 -2
  66. package/src/runs/background/run-child-session.ts +16 -5
  67. package/src/runs/background/run-id-resolver.ts +10 -5
  68. package/src/runs/background/run-status.ts +10 -4
  69. package/src/runs/background/runner-aliases.ts +25 -15
  70. package/src/runs/background/runner-child-launch.ts +1 -2
  71. package/src/runs/background/runner-startup-failure.ts +56 -0
  72. package/src/runs/background/stale-run-reconciler.ts +19 -3
  73. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  74. package/src/runs/background/subagent-runner.ts +96 -287
  75. package/src/runs/background/wait-tool.ts +2 -0
  76. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  77. package/src/runs/foreground/execution.ts +217 -250
  78. package/src/runs/foreground/prompt-audit.ts +3 -9
  79. package/src/runs/foreground/subagent-executor.ts +377 -119
  80. package/src/runs/shared/acceptance.ts +167 -68
  81. package/src/runs/shared/capability-ceiling.ts +4 -1
  82. package/src/runs/shared/child-hooks.ts +1 -16
  83. package/src/runs/shared/child-launch.ts +22 -14
  84. package/src/runs/shared/child-runtime-config.ts +3 -0
  85. package/src/runs/shared/child-session.ts +52 -2
  86. package/src/runs/shared/child-tool-plan.ts +23 -113
  87. package/src/runs/shared/dynamic-fanout.ts +1 -1
  88. package/src/runs/shared/external-cli-runner.ts +3 -1
  89. package/src/runs/shared/external-job-bridge.ts +54 -0
  90. package/src/runs/shared/git-environment.ts +29 -0
  91. package/src/runs/shared/mcp-config-sources.ts +3 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  93. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  94. package/src/runs/shared/model-resolution.ts +6 -1
  95. package/src/runs/shared/nested-events.ts +67 -55
  96. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  97. package/src/runs/shared/parallel-utils.ts +2 -1
  98. package/src/runs/shared/pi-spawn.ts +92 -6
  99. package/src/runs/shared/single-output.ts +11 -2
  100. package/src/runs/shared/structured-output.ts +227 -7
  101. package/src/runs/shared/subagent-control.ts +2 -16
  102. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  103. package/src/runs/shared/tool-availability.ts +2 -2
  104. package/src/runs/shared/tool-budget.ts +21 -0
  105. package/src/runs/shared/usage-reconciliation.ts +73 -0
  106. package/src/runs/shared/worktree.ts +35 -8
  107. package/src/shared/child-session-name.ts +4 -2
  108. package/src/shared/fork-context.ts +11 -4
  109. package/src/shared/launch-contract.ts +1 -1
  110. package/src/shared/pruned-fork.ts +69 -56
  111. package/src/shared/types.ts +52 -16
  112. package/src/slash/delegation-adapters.ts +25 -1
  113. package/src/slash/prompt-template-bridge.ts +16 -1
  114. package/src/slash/prompt-workflows.ts +12 -1
  115. package/src/slash/slash-commands.ts +7 -241
  116. package/src/slash/subagent-cost.ts +313 -0
  117. package/src/slash/subagents-admin.ts +28 -29
  118. package/src/tui/fleet-status.ts +24 -2
  119. package/src/tui/fleet.ts +7 -4
  120. package/src/tui/render.ts +53 -19
  121. package/src/watchdog/diff-tool.ts +24 -3
  122. package/src/watchdog/permission-arbiter.ts +13 -15
  123. package/src/watchdog/register-child.ts +10 -2
  124. package/src/watchdog/review.ts +14 -14
  125. package/src/watchdog/runtime.ts +2 -1
  126. package/src/watchdog/turn-delta.ts +11 -5
  127. package/src/workflows/scripted-workflow.ts +109 -23
  128. package/src/workflows/workflow-child-summary.ts +4 -2
  129. package/src/workflows/workflow-settlement.ts +4 -1
  130. package/src/runs/shared/completion-evidence.ts +0 -89
  131. package/src/runs/shared/completion-guard.ts +0 -255
  132. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  133. package/src/runs/shared/task-intent.ts +0 -244
@@ -0,0 +1,313 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { getArtifactPaths, getArtifactsDir } from "../shared/artifacts.ts";
5
+ import { formatTokens } from "../shared/formatters.ts";
6
+ import { DIRS, SLASH_RESULT_TYPE, type Details, type SingleResult, type SubagentState, type Usage } from "../shared/types.ts";
7
+ import { readStatus } from "../shared/utils.ts";
8
+ import { readWorkflowReceipt } from "../workflows/workflow-receipt.ts";
9
+ import { resolveSlashMessageDetails } from "./slash-live-state.ts";
10
+
11
+ /** Structured parent-plus-child accounting for one session; the source of `/subagent-cost` and the RPC `cost` method. */
12
+ export interface SubagentCostReport {
13
+ version: 1;
14
+ parent: Usage;
15
+ children: SubagentCostChild[];
16
+ childTotal: Usage;
17
+ total: Usage;
18
+ /** Async children whose usage metadata could not be resolved; the child total is a lower bound when this is non-zero. */
19
+ unresolvedAsyncChildren: number;
20
+ }
21
+
22
+ export interface SubagentCostChild {
23
+ label: string;
24
+ agent?: string;
25
+ runId?: string;
26
+ usage: Usage;
27
+ sessionFile?: string;
28
+ }
29
+
30
+ export const SUBAGENT_COST_REPORT_VERSION = 1 as const;
31
+
32
+ function emptyUsage(): Usage {
33
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
34
+ }
35
+
36
+ function addUsage(target: Usage, source: Usage): void {
37
+ target.input += source.input;
38
+ target.output += source.output;
39
+ target.cacheRead += source.cacheRead;
40
+ target.cacheWrite += source.cacheWrite;
41
+ target.cost += source.cost;
42
+ target.turns += source.turns;
43
+ }
44
+
45
+ function usageHasValue(usage: Usage): boolean {
46
+ return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0;
47
+ }
48
+
49
+ function nonNegativeNumber(value: unknown): number | undefined {
50
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
51
+ }
52
+
53
+ function usageFromValue(value: unknown, turnsOverride?: number): Usage | undefined {
54
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
55
+ const record = value as Record<string, unknown>;
56
+ const costValue = typeof record.cost === "object" && record.cost !== null && !Array.isArray(record.cost)
57
+ ? (record.cost as Record<string, unknown>).total
58
+ : record.cost;
59
+ const turnsValue = turnsOverride ?? record.turns;
60
+ const usage = {
61
+ input: nonNegativeNumber(record.input) ?? 0,
62
+ output: nonNegativeNumber(record.output) ?? 0,
63
+ cacheRead: nonNegativeNumber(record.cacheRead) ?? 0,
64
+ cacheWrite: nonNegativeNumber(record.cacheWrite) ?? 0,
65
+ cost: nonNegativeNumber(costValue) ?? 0,
66
+ turns: nonNegativeNumber(turnsValue) ?? 0,
67
+ };
68
+ return Number.isSafeInteger(usage.turns) ? usage : undefined;
69
+ }
70
+
71
+ function assistantUsageFromMessage(message: unknown): Usage | undefined {
72
+ if (!message || typeof message !== "object") return undefined;
73
+ const msg = message as { role?: unknown; usage?: unknown };
74
+ return msg.role === "assistant" ? usageFromValue(msg.usage, 1) : undefined;
75
+ }
76
+
77
+ function compactionUsageFromEntry(entry: unknown): Usage | undefined {
78
+ if (!entry || typeof entry !== "object") return undefined;
79
+ const record = entry as { type?: unknown; usage?: unknown };
80
+ return record.type === "compaction" ? usageFromValue(record.usage, 0) : undefined;
81
+ }
82
+
83
+ const MAX_USAGE_METADATA_BYTES = 2 * 1024 * 1024;
84
+
85
+ function readUsageMetadata(metadataPath: string): Record<string, unknown> | undefined {
86
+ let fd: number | undefined;
87
+ try {
88
+ fd = fs.openSync(metadataPath, "r");
89
+ const stat = fs.fstatSync(fd);
90
+ if (!stat.isFile() || stat.size > MAX_USAGE_METADATA_BYTES) return undefined;
91
+ const buffer = Buffer.allocUnsafe(stat.size);
92
+ let offset = 0;
93
+ while (offset < buffer.length) {
94
+ const bytesRead = fs.readSync(fd, buffer, offset, buffer.length - offset, null);
95
+ if (bytesRead <= 0) return undefined;
96
+ offset += bytesRead;
97
+ }
98
+ const value: unknown = JSON.parse(buffer.toString("utf-8"));
99
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
100
+ } finally {
101
+ if (fd !== undefined) fs.closeSync(fd);
102
+ }
103
+ }
104
+
105
+ function isSubagentDetails(value: unknown): value is Details {
106
+ if (!value || typeof value !== "object") return false;
107
+ const details = value as { mode?: unknown; results?: unknown };
108
+ return typeof details.mode === "string" && Array.isArray(details.results);
109
+ }
110
+
111
+ function detailsFromSessionEntry(entry: unknown): Details | undefined {
112
+ if (!entry || typeof entry !== "object") return undefined;
113
+ const record = entry as { type?: unknown; customType?: unknown; details?: unknown; message?: unknown };
114
+ if (record.type === "custom_message" && record.customType === SLASH_RESULT_TYPE) {
115
+ const details = resolveSlashMessageDetails(record.details)?.result.details;
116
+ return isSubagentDetails(details) ? details : undefined;
117
+ }
118
+ if (record.type !== "message" || !record.message || typeof record.message !== "object") return undefined;
119
+ const message = record.message as { role?: unknown; toolName?: unknown; details?: unknown };
120
+ if (message.role !== "toolResult" || (message.toolName !== "subagent" && message.toolName !== "bg_wait")) return undefined;
121
+ return isSubagentDetails(message.details) ? message.details : undefined;
122
+ }
123
+
124
+ function metadataUsage(
125
+ artifactsDirs: string[],
126
+ input: { runId: string; agent: string },
127
+ indexes: ReadonlyArray<number | undefined> = [0, undefined],
128
+ ): Usage | undefined {
129
+ if (!/^[A-Za-z0-9._-]+$/.test(input.runId)) return undefined;
130
+ for (const artifactsDir of artifactsDirs) {
131
+ for (const index of indexes) {
132
+ const metadataPath = getArtifactPaths(artifactsDir, input.runId, input.agent, index).metadataPath;
133
+ try {
134
+ const metadata = readUsageMetadata(metadataPath);
135
+ if (!metadata) continue;
136
+ if (metadata.runId !== input.runId || metadata.agent !== input.agent) continue;
137
+ const usage = usageFromValue(metadata.usage);
138
+ if (usage && usageHasValue(usage)) return usage;
139
+ } catch (error) {
140
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to read subagent usage metadata '${metadataPath}':`, error);
141
+ }
142
+ }
143
+ }
144
+ return undefined;
145
+ }
146
+
147
+ /**
148
+ * Collect parent and child usage for the current session branch. Foreground
149
+ * children come from persisted `subagent`/`bg_wait` tool-result details; async
150
+ * workflow children are resolved through receipts, and other async runs through
151
+ * their status steps, then artifact metadata.
152
+ */
153
+ export function collectSubagentCost(
154
+ ctx: ExtensionContext,
155
+ state: Pick<SubagentState, "baseCwd" | "artifactDirPreference">,
156
+ ): SubagentCostReport {
157
+ const parent = emptyUsage();
158
+ const childTotal = emptyUsage();
159
+ const total = emptyUsage();
160
+ const children: SubagentCostChild[] = [];
161
+ const seenChildren = new Set<string>();
162
+ const workflowRunIds = new Set<string>();
163
+ const asyncRunIds = new Set<string>();
164
+ const completedRunIds = new Set<string>();
165
+ let unresolvedAsyncChildren = 0;
166
+
167
+ const addChild = (input: { agent?: string; runId?: string; identity?: string; usage?: Usage; sessionFile?: string }): boolean => {
168
+ if (!input.usage || !usageHasValue(input.usage)) return false;
169
+ const identity = input.identity ?? (input.runId ? `run:${input.runId}` : input.sessionFile ? `session:${input.sessionFile}` : undefined);
170
+ if (identity && seenChildren.has(identity)) return true;
171
+ if (identity) seenChildren.add(identity);
172
+ const usage = { ...input.usage };
173
+ children.push({
174
+ label: `Child ${children.length + 1} (${input.agent ?? "unknown"})`,
175
+ ...(input.agent ? { agent: input.agent } : {}),
176
+ ...(input.runId ? { runId: input.runId } : {}),
177
+ usage,
178
+ ...(input.sessionFile ? { sessionFile: input.sessionFile } : {}),
179
+ });
180
+ addUsage(childTotal, usage);
181
+ return true;
182
+ };
183
+
184
+ for (const entry of ctx.sessionManager.getBranch()) {
185
+ const message = entry.type === "message" ? (entry as { message?: unknown }).message : undefined;
186
+ const parentUsage = assistantUsageFromMessage(message) ?? compactionUsageFromEntry(entry);
187
+ if (parentUsage) addUsage(parent, parentUsage);
188
+ const details = detailsFromSessionEntry(entry);
189
+ if (!details) continue;
190
+ if (details.mode === "workflow" && details.runId) workflowRunIds.add(details.runId);
191
+ // An async launch result has no child results; its usage lands in run artifacts.
192
+ else if (details.asyncId && details.results.length === 0) asyncRunIds.add(details.asyncId);
193
+ for (const result of details.results) {
194
+ const resultRunId = (result as SingleResult & { runId?: unknown }).runId;
195
+ addChild({ agent: result.agent, runId: typeof resultRunId === "string" ? resultRunId : undefined, usage: usageFromValue(result.usage), sessionFile: result.sessionFile });
196
+ }
197
+ for (const completion of details.completions ?? []) {
198
+ if (completion.mode === "workflow") workflowRunIds.add(completion.runId);
199
+ completedRunIds.add(completion.runId);
200
+ for (const result of completion.results ?? []) {
201
+ addChild({ agent: result.agent, runId: result.runId, usage: usageFromValue(result.usage), sessionFile: result.sessionFile });
202
+ }
203
+ }
204
+ }
205
+
206
+ let sessionFile: string | null = null;
207
+ try {
208
+ sessionFile = ctx.sessionManager.getSessionFile() ?? null;
209
+ } catch { /* an unpersisted session can still report direct child usage */ }
210
+ const artifactsDirs = new Set<string>();
211
+ const addArtifactsDir = (cwd: string | undefined): void => {
212
+ try {
213
+ artifactsDirs.add(getArtifactsDir(sessionFile, cwd, state.artifactDirPreference));
214
+ } catch { /* invalid or unavailable project roots are ignored */ }
215
+ };
216
+ addArtifactsDir(ctx.cwd);
217
+ addArtifactsDir(state.baseCwd);
218
+
219
+ for (const workflowRunId of workflowRunIds) {
220
+ try {
221
+ const status = readStatus(path.join(DIRS.async, workflowRunId));
222
+ addArtifactsDir(status?.cwd);
223
+ const receipt = readWorkflowReceipt(DIRS.async, workflowRunId);
224
+ const summaryChildren = new Map((receipt.workflowChildren?.children ?? []).map((child) => [child.childId, child]));
225
+ const refsByRunId = new Map<string, { runId: string; agent?: string }>();
226
+ const addRef = (runId: string | undefined, agent: string | undefined): void => {
227
+ if (!runId) return;
228
+ const existing = refsByRunId.get(runId);
229
+ if (!existing || (!existing.agent && agent)) refsByRunId.set(runId, { runId, ...(agent ? { agent } : {}) });
230
+ };
231
+ for (const [key, entry] of Object.entries(receipt.entries)) {
232
+ const summaryChild = summaryChildren.get(key);
233
+ const runIds = entry.continuation?.runIds?.length
234
+ ? entry.continuation.runIds
235
+ : entry.latestRunId ? [entry.latestRunId] : summaryChild?.runId ? [summaryChild.runId] : [];
236
+ for (const runId of runIds) addRef(runId, entry.agent ?? summaryChild?.agent);
237
+ }
238
+ for (const child of receipt.workflowChildren?.children ?? []) {
239
+ if (!Object.hasOwn(receipt.entries, child.childId)) addRef(child.runId, child.agent);
240
+ }
241
+ for (const ref of refsByRunId.values()) {
242
+ if (seenChildren.has(`run:${ref.runId}`)) continue;
243
+ if (!ref.agent) {
244
+ unresolvedAsyncChildren += 1;
245
+ continue;
246
+ }
247
+ const usage = metadataUsage([...artifactsDirs], { runId: ref.runId, agent: ref.agent });
248
+ if (!usage || !addChild({ ...ref, usage })) unresolvedAsyncChildren += 1;
249
+ }
250
+ } catch (error) {
251
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to resolve async subagent usage for '${workflowRunId}':`, error);
252
+ }
253
+ }
254
+
255
+ for (const asyncRunId of asyncRunIds) {
256
+ // A bg_wait completion already reported this run's results; its children carry no child runId.
257
+ if (completedRunIds.has(asyncRunId)) continue;
258
+ try {
259
+ const status = readStatus(path.join(DIRS.async, asyncRunId));
260
+ if (!status?.steps?.length) {
261
+ unresolvedAsyncChildren += 1;
262
+ continue;
263
+ }
264
+ addArtifactsDir(status.cwd);
265
+ const steps = status.steps;
266
+ // The runner suffixes artifact names with the flat step index only for multi-step runs.
267
+ steps.forEach((step, index) => {
268
+ const flatIndex = steps.length > 1 ? index : undefined;
269
+ const usage = metadataUsage([...artifactsDirs], { runId: asyncRunId, agent: step.agent }, flatIndex === undefined ? [undefined, 0] : [flatIndex]);
270
+ const identity = flatIndex === undefined ? `run:${asyncRunId}` : `run:${asyncRunId}:${flatIndex}`;
271
+ // Pending and running steps have not finalized their metadata yet.
272
+ const settled = step.status !== "pending" && step.status !== "running";
273
+ if (!addChild({ agent: step.agent, runId: asyncRunId, identity, usage }) && settled) unresolvedAsyncChildren += 1;
274
+ });
275
+ } catch (error) {
276
+ unresolvedAsyncChildren += 1;
277
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to resolve async subagent usage for '${asyncRunId}':`, error);
278
+ }
279
+ }
280
+
281
+ addUsage(total, parent);
282
+ addUsage(total, childTotal);
283
+ return { version: SUBAGENT_COST_REPORT_VERSION, parent, children, childTotal, total, unresolvedAsyncChildren };
284
+ }
285
+
286
+ function formatCostUsage(label: string, usage: Usage): string {
287
+ const extras = [
288
+ usage.cacheRead ? `cache read ${formatTokens(usage.cacheRead)}` : "",
289
+ usage.cacheWrite ? `cache write ${formatTokens(usage.cacheWrite)}` : "",
290
+ usage.turns ? `${usage.turns} turn${usage.turns === 1 ? "" : "s"}` : "",
291
+ ].filter(Boolean);
292
+ return `${label}: ↑${formatTokens(usage.input)} ↓${formatTokens(usage.output)} $${usage.cost.toFixed(4)}${extras.length ? ` (${extras.join(", ")})` : ""}`;
293
+ }
294
+
295
+ /** The `/subagent-cost` text rendering of a collected report. */
296
+ export function formatSubagentCostReport(report: SubagentCostReport): string {
297
+ const lines = [
298
+ "Subagent cost",
299
+ "",
300
+ formatCostUsage("Parent", report.parent),
301
+ ];
302
+ if (report.children.length === 0) {
303
+ lines.push("No subagent child usage found in this session.");
304
+ } else {
305
+ for (const child of report.children) {
306
+ lines.push(formatCostUsage(child.label, child.usage));
307
+ if (child.sessionFile) lines.push(` Session: ${child.sessionFile}`);
308
+ }
309
+ }
310
+ if (report.unresolvedAsyncChildren > 0) lines.push(`Async child usage unavailable: ${report.unresolvedAsyncChildren}.`);
311
+ lines.push("────────────────────────────", formatCostUsage("Children", report.childTotal), formatCostUsage("Total", report.total));
312
+ return lines.join("\n");
313
+ }
@@ -19,7 +19,7 @@ let adminDialogEvents: UiSpanSilentEvents | undefined;
19
19
 
20
20
  /** Claims the next dialog span as silent (pi-notify protocol). */
21
21
  function markAdminDialogSilent(): void {
22
- emitUiSpanSilent(adminDialogEvents, "admin");
22
+ emitUiSpanSilent(adminDialogEvents, "admin");
23
23
  }
24
24
  import { editableAgentConfig, preservedAgentFrontmatterFields } from "../agents/agent-management.ts";
25
25
  import { findModelInfo, getSupportedThinkingLevels, toModelInfo } from "../shared/model-info.ts";
@@ -38,12 +38,12 @@ function sourceRank(source: AgentConfig["source"]): number {
38
38
  return 3;
39
39
  }
40
40
 
41
- function allVisibleAgents(pi: RuntimeAgentOwner, cwd: string): AgentConfig[] {
42
- const d = discoverAgentsAll(cwd);
41
+ function allVisibleAgents(pi: RuntimeAgentOwner, cwd: string, preferredModelProvider?: string): AgentConfig[] {
42
+ const d = discoverAgentsAll(cwd, preferredModelProvider);
43
43
  const allConfigured = [...d.project, ...d.user, ...d.package, ...d.builtin];
44
44
  const visibleConfigured = allConfigured.filter((agent) => !agent.disabled);
45
45
  // Disabled definitions remain in collision checks even though the panel hides them.
46
- const agents = mergeRuntimeAgents(pi, { agents: visibleConfigured }, allConfigured).agents;
46
+ const agents = mergeRuntimeAgents(pi, { agents: visibleConfigured }, allConfigured, { cwd, scope: "both", preferredModelProvider }).agents;
47
47
  return agents.sort((a, b) => a.name.localeCompare(b.name) || sourceRank(a.source) - sourceRank(b.source));
48
48
  }
49
49
 
@@ -86,20 +86,20 @@ function modelFullId(model: ModelInfo): string {
86
86
  async function liveAvailableModels(ctx: ExtensionContext) {
87
87
  try {
88
88
  // Reload local configuration and cached catalogs without network discovery on picker open.
89
- // Host SDK versions differ on the refresh result shape: newer hosts return a result
90
- // object with per-provider errors and an abort flag, older hosts resolve void.
91
- const refresh = ctx.modelRegistry.refresh as ((options?: unknown) => Promise<unknown>) | undefined;
92
- const result = await refresh?.({ allowNetwork: false, signal: AbortSignal.timeout(5_000) });
93
- if (result && typeof result === "object") {
94
- const errors = (result as { errors?: Map<string, Error> }).errors;
95
- const aborted = (result as { aborted?: boolean }).aborted;
96
- const firstError = errors?.entries().next().value;
97
- if (firstError) {
98
- ctx.ui.notify(`Could not refresh ${firstError[0]}; using the currently loaded choices. ${firstError[1].message}`, "warning");
99
- } else if (aborted) {
100
- ctx.ui.notify("Model registry refresh timed out; using the currently loaded choices.", "warning");
101
- }
89
+ // Host SDK versions differ on the refresh result shape: newer hosts return a result
90
+ // object with per-provider errors and an abort flag, older hosts resolve void.
91
+ const refresh = ctx.modelRegistry.refresh as ((options?: unknown) => Promise<unknown>) | undefined;
92
+ const result = await refresh?.({ allowNetwork: false, signal: AbortSignal.timeout(5_000) });
93
+ if (result && typeof result === "object") {
94
+ const errors = (result as { errors?: Map<string, Error> }).errors;
95
+ const aborted = (result as { aborted?: boolean }).aborted;
96
+ const firstError = errors?.entries().next().value;
97
+ if (firstError) {
98
+ ctx.ui.notify(`Could not refresh ${firstError[0]}; using the currently loaded choices. ${firstError[1].message}`, "warning");
99
+ } else if (aborted) {
100
+ ctx.ui.notify("Model registry refresh timed out; using the currently loaded choices.", "warning");
102
101
  }
102
+ }
103
103
  } catch (error) {
104
104
  const message = error instanceof Error ? error.message : String(error);
105
105
  ctx.ui.notify(`Could not refresh the model registry; using the last loaded choices. ${message}`, "warning");
@@ -125,7 +125,6 @@ function buildBuiltinBase(agent: AgentConfig): BuiltinAgentOverrideBase {
125
125
  ...(agent.mcpDirectTools !== undefined ? { mcpDirectTools: [...agent.mcpDirectTools] } : {}),
126
126
  ...(agent.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: [...agent.subagentOnlyExtensions] } : {}),
127
127
  ...(agent.mutationTools !== undefined ? { mutationTools: [...agent.mutationTools] } : {}),
128
- ...(agent.completionGuard !== undefined ? { completionGuard: agent.completionGuard } : {}),
129
128
  ...(agent.toolBudget !== undefined ? { toolBudget: agent.toolBudget } : {}),
130
129
  };
131
130
  }
@@ -176,7 +175,7 @@ function readOnlyAgentMessage(agent: AgentConfig, field: EditableOverrideField):
176
175
  }
177
176
 
178
177
  async function selectAgent(pi: RuntimeAgentOwner, ctx: ExtensionContext, args: string): Promise<AgentSelection> {
179
- const agents = allVisibleAgents(pi, ctx.cwd);
178
+ const agents = allVisibleAgents(pi, ctx.cwd, ctx.model?.provider);
180
179
  const requestedName = args.trim().split(/\s+/)[0] ?? "";
181
180
  if (agents.length === 0) return { kind: "not-found", agents, requestedName: requestedName || undefined };
182
181
 
@@ -230,7 +229,7 @@ function metadataFor(agent: AgentConfig): string {
230
229
  }
231
230
 
232
231
  async function selectFromList(ctx: ExtensionContext, title: string, subtitle: string | undefined, items: SelectorItem[]): Promise<string | undefined> {
233
- markAdminDialogSilent();
232
+ markAdminDialogSilent();
234
233
  if (typeof ctx.ui.custom === "function") {
235
234
  const result = await ctx.ui.custom<SelectorResult>(
236
235
  (tui, theme, kb, done) => new SelectorComponent(tui, theme, kb, { title, subtitle, items, done }),
@@ -285,7 +284,7 @@ async function chooseOverrideScope(ctx: ExtensionContext, agent: AgentConfig): P
285
284
  return agent.source === "project" && agent.override.scope === "user" && d.projectSettingsPath ? "project" : agent.override.scope;
286
285
  }
287
286
  if (!d.projectSettingsPath || !ctx.hasUI) return "user";
288
- markAdminDialogSilent();
287
+ markAdminDialogSilent();
289
288
  const choice = await ctx.ui.select(`Save subagent override for ${agent.name}`, ["user", "project"]);
290
289
  return choice === "user" || choice === "project" ? choice : undefined;
291
290
  }
@@ -402,7 +401,7 @@ async function editSystemPrompt(ctx: ExtensionContext, agent: AgentConfig): Prom
402
401
  const readOnlyMessage = readOnlyAgentMessage(agent, "systemPrompt");
403
402
  if (readOnlyMessage) return readOnlyMessage;
404
403
  }
405
- markAdminDialogSilent();
404
+ markAdminDialogSilent();
406
405
  const edited = await ctx.ui.editor(`Edit '${agent.name}' system prompt`, agent.systemPrompt ?? "");
407
406
  if (edited === undefined) return null;
408
407
  const projectOwnsLowerScopeOverride = agent.source === "project" && agent.override?.scope === "user" && discoverAgentsAll(ctx.cwd).projectSettingsPath;
@@ -413,12 +412,12 @@ async function editSystemPrompt(ctx: ExtensionContext, agent: AgentConfig): Prom
413
412
  }
414
413
 
415
414
  export async function openSubagentsAdmin(pi: ExtensionAPI, ctx: ExtensionContext, args = ""): Promise<void> {
416
- adminDialogEvents = pi.events;
417
- try {
418
- return await runAdminFlow(pi, ctx, args);
419
- } finally {
420
- adminDialogEvents = undefined;
421
- }
415
+ adminDialogEvents = pi.events;
416
+ try {
417
+ return await runAdminFlow(pi, ctx, args);
418
+ } finally {
419
+ adminDialogEvents = undefined;
420
+ }
422
421
  }
423
422
 
424
423
  async function runAdminFlow(pi: ExtensionAPI, ctx: ExtensionContext, args = ""): Promise<void> {
@@ -450,7 +449,7 @@ async function runAdminFlow(pi: ExtensionAPI, ctx: ExtensionContext, args = ""):
450
449
  else if (requestedAction === "prompt" || requestedAction === "system-prompt" || requestedAction === "edit") action = "Edit system prompt";
451
450
  else if (requestedAction === "details" || requestedAction === "info") action = "Show details";
452
451
  if (!action) {
453
- markAdminDialogSilent();
452
+ markAdminDialogSilent();
454
453
  action = await ctx.ui.select(
455
454
  `Administer ${agent.name}\n${metadataSummary(agent)}`,
456
455
  ["Change model", "Change thinking level", "Edit system prompt", "Show details", "Done"],
@@ -538,6 +538,8 @@ export class SubagentFleetStatus {
538
538
  private selectedKey = "main";
539
539
  private inspectorOpen = false;
540
540
  private lastRenderKey = "";
541
+ private lastPaint: { width: number; theme: Theme } | undefined;
542
+ private prepaint: { key: string; width: number; theme: Theme; lines: string[] } | undefined;
541
543
  private entries: FleetStatusEntry[] = [];
542
544
  private workflowSnapshots = new Map<string, { snapshot: string; childRows: Set<string> }>();
543
545
  private readonly onWorkflowCoverageChange: FleetStatusOptions["onWorkflowCoverageChange"];
@@ -594,6 +596,7 @@ export class SubagentFleetStatus {
594
596
  }
595
597
 
596
598
  refresh(): void {
599
+ this.prepaint = undefined;
597
600
  const ctx = this.getActiveUiContext();
598
601
  if (!ctx) return;
599
602
  if (this.state.widgetsSuspended) {
@@ -662,17 +665,34 @@ export class SubagentFleetStatus {
662
665
  }
663
666
 
664
667
  const renderKey = this.getRenderKey();
665
- if (!this.active || renderKey !== this.lastRenderKey) this.clearWorkflowCoverage();
668
+ if (!this.active) this.clearWorkflowCoverage();
669
+ // The async widget paints above the roster, so recompute coverage (structure and row fit) now.
670
+ // Clearing it instead would flash the full workflow tree on every live-stat tick.
671
+ else if (renderKey !== this.lastRenderKey && this.lastPaint) {
672
+ const { width, theme } = this.lastPaint;
673
+ this.prepaint = { key: renderKey, width, theme, lines: this.render(width, theme) };
674
+ }
666
675
  if (!this.widgetRegistered) {
667
676
  ctx.ui.setWidget(FLEET_STATUS_WIDGET_KEY, (tui, theme) => {
668
677
  this.tui = tui;
669
678
  return {
670
- render: (width: number) => this.render(width, theme),
679
+ render: (width: number) => {
680
+ this.lastPaint = { width, theme };
681
+ const prepaint = this.prepaint;
682
+ this.prepaint = undefined;
683
+ if (prepaint && prepaint.key === this.lastRenderKey && prepaint.key === this.getRenderKey()
684
+ && prepaint.width === width && prepaint.theme === theme && !this.state.widgetsSuspended
685
+ && !this.inspectorOpen && !this.state.fleetInspectorOpen) return prepaint.lines;
686
+ return this.render(width, theme);
687
+ },
671
688
  invalidate: () => {
672
689
  this.lastRenderKey = "";
690
+ this.prepaint = undefined;
673
691
  },
674
692
  dispose: () => {
675
693
  if (this.tui !== tui) return;
694
+ this.prepaint = undefined;
695
+ this.lastPaint = undefined;
676
696
  this.clearWorkflowCoverage();
677
697
  this.widgetRegistered = false;
678
698
  this.tui = undefined;
@@ -1057,6 +1077,7 @@ export class SubagentFleetStatus {
1057
1077
  }
1058
1078
 
1059
1079
  private clearWidget(): void {
1080
+ this.prepaint = undefined;
1060
1081
  this.clearWorkflowCoverage();
1061
1082
  if (!this.widgetRegistered) return;
1062
1083
  try {
@@ -1071,6 +1092,7 @@ export class SubagentFleetStatus {
1071
1092
  }
1072
1093
 
1073
1094
  private clearUiRegistration(): void {
1095
+ this.prepaint = undefined;
1074
1096
  this.clearWorkflowCoverage();
1075
1097
  if (this.timer) clearInterval(this.timer);
1076
1098
  this.timer = undefined;
package/src/tui/fleet.ts CHANGED
@@ -120,7 +120,7 @@ export interface FleetViewOptions {
120
120
  fleetKeybindings?: FleetKeybindingsConfig;
121
121
  actions?: FleetActionHandlers;
122
122
  copyText?: (text: string) => Promise<void> | void;
123
- inspectorPlugins?: readonly InspectorPlugin[];
123
+ inspectorPlugins?: () => readonly InspectorPlugin[];
124
124
  inspectorEnv?: NodeJS.ProcessEnv;
125
125
  /** Event bus used to claim the fleet dialog as a silent span. */
126
126
  events?: UiSpanSilentEvents;
@@ -679,6 +679,9 @@ function transcriptTarget(item: FleetItem, state: SubagentState): { path: string
679
679
  };
680
680
  }
681
681
  const step = item.step ?? (item.run.steps.length === 1 ? item.run.steps[0] : undefined);
682
+ // External CLI logs are plain text, not structured session JSONL. Let the
683
+ // bounded async detail formatter select final output/stderr/stdout instead.
684
+ if (step?.runner?.type === "external-cli") return undefined;
682
685
  const recordedSessionFile = step?.sessionFile ?? item.run.sessionFile;
683
686
  const recordedPath = step?.transcriptPath ?? recordedSessionFile;
684
687
  if (!recordedPath) return undefined;
@@ -1544,7 +1547,7 @@ export async function openSubagentFleet(ctx: ExtensionContext, state: SubagentSt
1544
1547
  cwd: state.baseCwd,
1545
1548
  ...(state.authorityPolicy ? { authorityPolicy: state.authorityPolicy } : {}),
1546
1549
  ...(state.missionStoreConfig ? { missions: state.missionStoreConfig } : {}),
1547
- ...(options.inspectorPlugins ? { plugins: options.inspectorPlugins } : {}),
1550
+ plugins: options.inspectorPlugins?.(),
1548
1551
  ...(options.inspectorEnv ? { env: options.inspectorEnv } : {}),
1549
1552
  }), `Failed to open inspector for async run ${input.runId}.`),
1550
1553
  redoPrompt: async (input: { runId: string; index: number; guidance: string; control?: ForegroundRunControl }) => {
@@ -1574,8 +1577,8 @@ export interface OpenFleetFromStatusOptions {
1574
1577
  asyncDirRoot: string;
1575
1578
  resultsDir: string;
1576
1579
  fleetKeybindings?: FleetKeybindingsConfig;
1577
- /** Built-in inspector plugins, when the caller hosts inspector integration. */
1578
- inspectorPlugins?: readonly InspectorPlugin[];
1580
+ /** Lazy inspector plugins, when the caller hosts inspector integration. */
1581
+ inspectorPlugins?: () => readonly InspectorPlugin[];
1579
1582
  }
1580
1583
 
1581
1584
  /**