@xzzpig/pi-subagents 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/docs/agents.md +15 -5
  3. package/docs/configuration.md +10 -0
  4. package/docs/extension-api.md +1 -1
  5. package/docs/missions.md +15 -1
  6. package/docs/models.md +6 -2
  7. package/docs/observability.md +8 -3
  8. package/docs/tool-reference.md +28 -3
  9. package/docs/workflows.md +2 -2
  10. package/package.json +1 -1
  11. package/src/agents/agents.ts +59 -3
  12. package/src/api/preflight.ts +42 -1
  13. package/src/extension/config.ts +4 -1
  14. package/src/extension/index.ts +23 -16
  15. package/src/extension/public-execution.ts +3 -0
  16. package/src/extension/reply-workflow-script.ts +1 -1
  17. package/src/extension/rpc.ts +1 -1
  18. package/src/extension/schemas.ts +5 -3
  19. package/src/extension/tool-description.ts +1 -1
  20. package/src/missions/goal-driver.ts +44 -31
  21. package/src/missions/store.ts +10 -1
  22. package/src/profiles/profiles.ts +5 -2
  23. package/src/runs/background/async-execution.ts +88 -6
  24. package/src/runs/background/async-job-tracker.ts +3 -2
  25. package/src/runs/background/await-async-run.ts +4 -2
  26. package/src/runs/background/control-channel.ts +43 -0
  27. package/src/runs/background/run-child-session.ts +13 -6
  28. package/src/runs/background/runner-aliases.ts +7 -4
  29. package/src/runs/background/scheduled-runs.ts +28 -13
  30. package/src/runs/background/stale-run-reconciler.ts +13 -2
  31. package/src/runs/background/subagent-runner.ts +43 -4
  32. package/src/runs/foreground/command-action.ts +41 -0
  33. package/src/runs/foreground/execution.ts +16 -7
  34. package/src/runs/foreground/subagent-executor.ts +63 -12
  35. package/src/runs/shared/child-commands.ts +228 -0
  36. package/src/runs/shared/child-session.ts +93 -19
  37. package/src/runs/shared/child-tool-plan.ts +1 -1
  38. package/src/runs/shared/claude-code-adapter.ts +157 -2
  39. package/src/runs/shared/dynamic-fanout.ts +1 -1
  40. package/src/runs/shared/external-cli-preflight.ts +54 -6
  41. package/src/runs/shared/external-cli-runner.ts +5 -1
  42. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -4
  43. package/src/runs/shared/model-resolution.ts +9 -1
  44. package/src/runs/shared/parallel-utils.ts +2 -0
  45. package/src/runs/shared/run-history.ts +87 -0
  46. package/src/runs/shared/subagent-control.ts +32 -17
  47. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  48. package/src/shared/required-child-extensions.ts +39 -5
  49. package/src/shared/types.ts +6 -1
  50. package/src/slash/subagent-cost.ts +9 -5
  51. package/src/tui/render.ts +4 -4
  52. package/src/workflows/workflow-receipt.ts +2 -2
  53. package/src/workflows/workflow-resources.ts +7 -4
@@ -133,6 +133,93 @@ function appendPrivateHistoryLine(historyPath: string, line: string): void {
133
133
  }
134
134
  }
135
135
 
136
+ function backgroundRunHistoryTask(steps: readonly unknown[], resultMode: string): string {
137
+ const step = steps.length === 1 && typeof steps[0] === "object" && steps[0] !== null
138
+ ? (steps[0] as { task?: unknown; launchBindingTask?: unknown })
139
+ : undefined;
140
+ if (step) {
141
+ const task = typeof step.launchBindingTask === "string" && step.launchBindingTask ? step.launchBindingTask : step.task;
142
+ if (typeof task === "string" && task) return task;
143
+ }
144
+ return resultMode || "run";
145
+ }
146
+
147
+ export interface BackgroundRunHistoryEntry {
148
+ agent: string;
149
+ task: string;
150
+ exitCode: number;
151
+ durationMs: number;
152
+ terminal: Pick<NonNullable<Parameters<typeof recordRun>[4]>, "stopped" | "interrupted" | "timedOut" | "processSignal">;
153
+ }
154
+
155
+ const TERMINAL_STEP_STATUSES = new Set(["complete", "completed"]);
156
+ /** Steps that reached THEIR OWN terminal state — run-wide flags must not relabel them. */
157
+ const SELF_TERMINAL_STEP_STATUSES = new Set(["complete", "completed", "failed", "rejected"]);
158
+
159
+ /**
160
+ * Census rows for one finished background run. Single-step runs keep the exact
161
+ * foreground shape (agent + task text). Multi-step runs record ONE ROW PER CHILD
162
+ * STEP so `loadRunsForAgent(agent)` sees every child — a composite-only row would
163
+ * stay invisible to per-agent lookups. Per-step prompts are never hashed:
164
+ * multi-step rows hash the mode label only.
165
+ *
166
+ * Fidelity rules:
167
+ * - a row is recorded only for children that actually LAUNCHED (a child
168
+ * session was dispatched). Status alone cannot decide this: `stopRunner()`,
169
+ * `timeoutRunner()`, fail-fast skips, and usage-budget skips all relabel
170
+ * never-launched steps to terminal statuses (`stopped`, `failed`+`timedOut,
171
+ * `failed`+`skipped) before the run ends — the runner therefore threads an
172
+ * explicit `launched` fact per step. `pending` and `launched: false` steps
173
+ * get no row — unrun agents must not accumulate attempts or failures;
174
+ * - run-level terminal flags (stopped/interrupted/timedOut) apply only to steps
175
+ * that did not reach a terminal state of their own — a child that completed
176
+ * or failed BEFORE a sibling was interrupted keeps its own outcome, because
177
+ * recordRun() lets those flags override the exit code;
178
+ * - self-terminal steps carry their own timedOut/stopped flags instead.
179
+ */
180
+ export function planBackgroundRunHistory(input: {
181
+ steps: readonly unknown[];
182
+ resultMode: string;
183
+ statusSteps: ReadonlyArray<{ agent?: unknown; status?: unknown; durationMs?: number; timedOut?: boolean; stopped?: boolean; launched?: boolean }>;
184
+ stepResults?: ReadonlyArray<{ processSignal?: unknown } | undefined>;
185
+ runDurationMs: number;
186
+ stopped?: boolean;
187
+ interrupted?: boolean;
188
+ timedOut?: boolean;
189
+ }): BackgroundRunHistoryEntry[] {
190
+ const runTerminal: BackgroundRunHistoryEntry["terminal"] = {
191
+ ...(input.stopped ? { stopped: true } : {}),
192
+ ...(input.interrupted ? { interrupted: true } : {}),
193
+ ...(input.timedOut ? { timedOut: true } : {}),
194
+ };
195
+ const task = backgroundRunHistoryTask(input.steps, input.resultMode);
196
+ const rows: BackgroundRunHistoryEntry[] = [];
197
+ for (const [index, step] of input.statusSteps.entries()) {
198
+ if (typeof step.agent !== "string" || !step.agent) continue;
199
+ // `launched === false` marks steps the runner never dispatched a child
200
+ // session for, regardless of the status they were later relabeled to.
201
+ if (step.status === "pending" || step.launched === false) continue;
202
+ const succeeded = typeof step.status === "string" && TERMINAL_STEP_STATUSES.has(step.status);
203
+ const ownTerminal: BackgroundRunHistoryEntry["terminal"] = {
204
+ ...(step.timedOut === true ? { timedOut: true } : {}),
205
+ ...(step.stopped === true ? { stopped: true } : {}),
206
+ };
207
+ // A step that reached its own terminal state (completed, or failed/rejected
208
+ // before a sibling was interrupted) keeps its own outcome; run-wide flags
209
+ // would relabel it in recordRun().
210
+ const terminal = typeof step.status === "string" && SELF_TERMINAL_STEP_STATUSES.has(step.status) ? ownTerminal : { ...runTerminal, ...ownTerminal };
211
+ const processSignal = input.stepResults?.[index]?.processSignal;
212
+ rows.push({
213
+ agent: step.agent,
214
+ task,
215
+ exitCode: succeeded ? 0 : 1,
216
+ durationMs: typeof step.durationMs === "number" ? step.durationMs : input.runDurationMs,
217
+ terminal: processSignal === undefined ? terminal : { ...terminal, processSignal: typeof processSignal === "string" ? processSignal : null },
218
+ });
219
+ }
220
+ return rows;
221
+ }
222
+
136
223
  export function recordRun(
137
224
  agent: string,
138
225
  task: string,
@@ -190,7 +190,8 @@ export function shouldNotifyControlEvent(config: ResolvedControlConfig, event: C
190
190
  export function controlNotificationKey(event: ControlEvent, childIntercomTarget?: string): string {
191
191
  const childKey = childIntercomTarget ?? (event.index !== undefined ? `${event.runId}:${event.index}` : event.runId);
192
192
  const contextHash = createHash("sha256").update(formatControlNudge(event)).digest("hex").slice(0, 8);
193
- return `${childKey}:${event.type}:${event.reason ?? "idle"}:${contextHash}`;
193
+ const callKey = event.reason === "tool_open_threshold" && event.toolCallId ? `:${event.toolCallId}` : "";
194
+ return `${childKey}:${event.type}:${event.reason ?? "idle"}${callKey}:${contextHash}`;
194
195
  }
195
196
 
196
197
  export function claimControlNotification(config: ResolvedControlConfig, event: ControlEvent, seenKeys: Set<string>, childIntercomTarget?: string): boolean {
@@ -228,42 +229,56 @@ export function formatControlNoticeMessage(event: ControlEvent, childIntercomTar
228
229
  const nudgeMessage = formatControlNudge(event);
229
230
  const steerCommand = `subagent({ action: "steer", id: "${runTarget}", ${event.index !== undefined ? `index: ${event.index}, ` : ""}message: ${JSON.stringify(nudgeMessage)} })`;
230
231
  const nestedResumeCommand = `subagent({ action: "resume", id: "${runTarget}", message: ${JSON.stringify(nudgeMessage)} })`;
232
+ const facts = formatLongRunningFacts(event);
233
+ const head = (title: string) => [
234
+ `${title}: ${event.agent}`,
235
+ `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
236
+ `Signal: ${event.message}`,
237
+ facts ? `Facts: ${facts}` : undefined,
238
+ ];
239
+ const status = `Status: subagent({ action: "status", id: "${runTarget}" })`;
240
+ const lines = (items: Array<string | undefined>) => items.filter((line): line is string => Boolean(line)).join("\n");
231
241
  if (event.type === "active_long_running") {
232
- const facts = formatLongRunningFacts(event);
233
- return [
234
- `Subagent active but long-running: ${event.agent}`,
235
- `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
236
- `Signal: ${event.message}`,
237
- facts ? `Facts: ${facts}` : undefined,
242
+ return lines([
243
+ ...head("Subagent active but long-running"),
238
244
  "Hint: Inspect status first. Use steer for a top-level live async child, routed resume for a live nested child, or resume to revive a paused/completed/failed child.",
239
245
  `Top-level live async nudge: ${steerCommand}`,
240
246
  `Routed live nested nudge: ${nestedResumeCommand}`,
241
247
  childIntercomTarget ? `Direct intercom target: ${childIntercomTarget}` : undefined,
242
- `Status: subagent({ action: "status", id: "${runTarget}" })`,
248
+ status,
243
249
  `Interrupt: subagent({ action: "interrupt", id: "${runTarget}" })`,
244
- ].filter((line): line is string => Boolean(line)).join("\n");
250
+ ]);
251
+ }
252
+
253
+ if (event.reason === "tool_open_threshold" && event.currentTool === "bash") {
254
+ const command = (label: string, action: string) => `${label}: subagent(${JSON.stringify({ action, id: runTarget, ...(event.index !== undefined ? { index: event.index } : {}), toolCallId: event.toolCallId })})`;
255
+ return lines([
256
+ ...head("Subagent needs attention"),
257
+ "Hint: Inspect the running command and recent output before nudging. A queued steer does not cancel an in-flight bash call. A dev server or watch command may intentionally never return. Elapsed time alone does not prove the command is stuck.",
258
+ "Recovery: For a local Pi child explicitly granted subagent_command, yield a needed persistent command or cancel the exact incorrect command, then steer the child. Query command.status to confirm the result. If command controls are unavailable, inspect partial changes and interruption scope before interrupt/resume; interrupt is run-scoped and may affect siblings.",
259
+ ...(event.toolCallId ? [command("Command", "command.status"), command("Yield", "command.yield"), command("Cancel", "command.cancel")] : []),
260
+ status,
261
+ `Transcript: subagent({ action: "status", id: "${runTarget}", view: "transcript"${event.index !== undefined ? `, index: ${event.index}` : ""} })`,
262
+ ]);
245
263
  }
246
264
 
247
265
  const supervisorHint = event.reason === "supervisor_request"
248
266
  ? "Supervisor request: reply to the pending request. If subagent_supervisor pending is empty, check intercom pending because an external intercom tool may own the request."
249
267
  : undefined;
250
- const facts = formatLongRunningFacts(event);
251
- return [
252
- `Subagent needs attention: ${event.agent}`,
253
- `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
254
- `Signal: ${event.message}`,
255
- facts ? `Facts: ${facts}` : undefined,
268
+ return lines([
269
+ ...head("Subagent needs attention"),
256
270
  event.recentFailureSummary ? `Recent failures: ${event.recentFailureSummary}` : undefined,
257
271
  supervisorHint,
258
272
  "Hint: Inspect status first unless the run is clearly blocked. Use steer for a top-level live async child, routed resume for a live nested child, or resume to revive a paused/completed/failed child.",
259
273
  `Top-level live async nudge: ${steerCommand}`,
260
274
  `Routed live nested nudge: ${nestedResumeCommand}`,
261
275
  childIntercomTarget ? `Direct intercom target: ${childIntercomTarget}` : undefined,
262
- `Status: subagent({ action: "status", id: "${runTarget}" })`,
276
+ status,
263
277
  `Interrupt: subagent({ action: "interrupt", id: "${runTarget}" })`,
264
- ].filter((line): line is string => Boolean(line)).join("\n");
278
+ ]);
265
279
  }
266
280
 
281
+
267
282
  export function formatControlIntercomMessage(event: ControlEvent, childIntercomTarget?: string): string {
268
283
  const statusLabel = event.type === "active_long_running"
269
284
  ? "subagent active but long-running"
@@ -267,17 +267,22 @@ export function rewriteForkCacheProviderRequest(event: BeforeProviderRequestEven
267
267
  return { ...payload, prompt_cache_key: key };
268
268
  }
269
269
 
270
- function portableToolId(id: string): string {
270
+ function portableToolId(id: string, preserveBoundedCompositeToolIds = false): string {
271
271
  if (PORTABLE_TOOL_ID_PATTERN.test(id) && id.length <= MAX_PORTABLE_TOOL_ID_LENGTH) return id;
272
+ // Codex splits call_id|item_id on replay; each wire ID must remain portable and bounded.
273
+ if (preserveBoundedCompositeToolIds) {
274
+ const parts = id.split("|");
275
+ if (parts.length === 2 && parts.every((part) => PORTABLE_TOOL_ID_PATTERN.test(part) && part.length <= MAX_PORTABLE_TOOL_ID_LENGTH)) return id;
276
+ }
272
277
  const encoded = `tool_${Buffer.from(id).toString("base64url") || "empty"}`;
273
278
  if (encoded.length <= MAX_PORTABLE_TOOL_ID_LENGTH) return encoded;
274
279
  return `tool_${createHash("sha256").update(id).digest("base64url")}`;
275
280
  }
276
281
 
277
- function sanitizeToolHistoryMessage(message: unknown): unknown {
282
+ function sanitizeToolHistoryMessage(message: unknown, preserveBoundedCompositeToolIds = false): unknown {
278
283
  const m = message as { role?: string; content?: unknown; toolCallId?: unknown };
279
284
  if (m?.role === "toolResult" && typeof m.toolCallId === "string") {
280
- const toolCallId = portableToolId(m.toolCallId);
285
+ const toolCallId = portableToolId(m.toolCallId, preserveBoundedCompositeToolIds);
281
286
  return toolCallId === m.toolCallId ? message : { ...m, toolCallId };
282
287
  }
283
288
  if (m?.role !== "assistant" || !Array.isArray(m.content)) return message;
@@ -285,7 +290,7 @@ function sanitizeToolHistoryMessage(message: unknown): unknown {
285
290
  const content = m.content.map((block) => {
286
291
  const b = block as { type?: string; id?: unknown };
287
292
  if (b?.type !== "toolCall" || typeof b.id !== "string") return block;
288
- const id = portableToolId(b.id);
293
+ const id = portableToolId(b.id, preserveBoundedCompositeToolIds);
289
294
  if (id === b.id) return block;
290
295
  changed = true;
291
296
  return { ...b, id };
@@ -302,7 +307,7 @@ function stripAssistantSubagentToolCallBlocks(message: unknown): unknown | undef
302
307
  return { ...m, content: filteredContent };
303
308
  }
304
309
 
305
- export function stripParentOnlySubagentMessages(messages: unknown[], options: { sanitizeToolIds?: boolean; preserveFanoutToolHistory?: boolean } = {}): unknown[] {
310
+ export function stripParentOnlySubagentMessages(messages: unknown[], options: { sanitizeToolIds?: boolean; preserveBoundedCompositeToolIds?: boolean; preserveFanoutToolHistory?: boolean } = {}): unknown[] {
306
311
  const preserveCurrentFanoutToolHistory = options.preserveFanoutToolHistory === true;
307
312
  const sanitizeToolIds = options.sanitizeToolIds ?? true;
308
313
  let changed = false;
@@ -317,7 +322,7 @@ export function stripParentOnlySubagentMessages(messages: unknown[], options: {
317
322
  changed = true;
318
323
  continue;
319
324
  }
320
- const sanitized = sanitizeToolIds ? sanitizeToolHistoryMessage(stripped) : stripped;
325
+ const sanitized = sanitizeToolIds ? sanitizeToolHistoryMessage(stripped, options.preserveBoundedCompositeToolIds === true) : stripped;
321
326
  if (stripped !== message || sanitized !== stripped) changed = true;
322
327
  filtered.push(sanitized);
323
328
  }
@@ -524,6 +529,7 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config?:
524
529
  if (!event || typeof event !== "object" || !("messages" in event) || !Array.isArray(event.messages)) return undefined;
525
530
  const messages = stripParentOnlySubagentMessages(event.messages, {
526
531
  sanitizeToolIds: !COMPOSITE_TOOL_ID_APIS.has(ctx?.model?.api ?? ""),
532
+ preserveBoundedCompositeToolIds: ctx?.model?.api === "openai-codex-responses",
527
533
  preserveFanoutToolHistory: config.fanoutChild,
528
534
  });
529
535
  if (messages === event.messages) return undefined;
@@ -16,10 +16,13 @@ export interface RequiredChildExtension {
16
16
  export interface RegisterRequiredChildExtensionsInput {
17
17
  sessionId: string;
18
18
  extensions: readonly RequiredChildExtension[];
19
+ /** Reject launches whose runner or machine placement cannot load these extensions, instead of dropping them. */
20
+ requireForAllRunners?: boolean;
19
21
  }
20
22
 
21
23
  export interface RequiredChildExtensionRegistration { dispose(): void }
22
- export type RequiredChildExtensionSnapshot = ReadonlyArray<Readonly<RequiredChildExtension>>;
24
+ /** Registration stamps `requireForAllRunners` on each entry so every carrier of the snapshot retains it. */
25
+ export type RequiredChildExtensionSnapshot = ReadonlyArray<Readonly<RequiredChildExtension & { requireForAllRunners?: true }>>;
23
26
 
24
27
  /** Validate and freeze a snapshot; registration canonicalizes once, while retained launches preserve that identity. */
25
28
  export function snapshotRequiredChildExtensions(value: unknown, label = "Required child extensions", canonicalizeFiles = false): RequiredChildExtensionSnapshot {
@@ -27,11 +30,14 @@ export function snapshotRequiredChildExtensions(value: unknown, label = "Require
27
30
  const ids = new Set<string>();
28
31
  const paths = new Set<string>();
29
32
  return Object.freeze(value.map((entry, index) => {
30
- if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).some((key) => key !== "id" && key !== "path")) throw new Error(`${label} entry ${index} requires only id and path.`);
33
+ // The flag comes from registration, so only serialized snapshots (not registration input) may carry it.
34
+ if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).some((key) => key !== "id" && key !== "path" && (canonicalizeFiles || key !== "requireForAllRunners"))) throw new Error(`${label} entry ${index} requires only id and path.`);
31
35
  const id = "id" in entry ? entry.id : undefined;
32
36
  const rawPath = "path" in entry ? entry.path : undefined;
37
+ const requireForAllRunners = "requireForAllRunners" in entry ? entry.requireForAllRunners : undefined;
33
38
  if (typeof id !== "string" || !ID_PATTERN.test(id)) throw new Error(`${label} entry ${index} requires a safe id of at most 128 characters.`);
34
39
  if (ids.has(id)) throw new Error(`${label} id '${id}' is duplicated.`);
40
+ if (requireForAllRunners !== undefined && requireForAllRunners !== true) throw new Error(`${label} '${id}' requireForAllRunners must be true when present.`);
35
41
  if (typeof rawPath !== "string" || !rawPath.trim() || rawPath.includes("\0") || Buffer.byteLength(rawPath, "utf8") > MAX_PATH_BYTES || (!canonicalizeFiles && !path.isAbsolute(rawPath))) throw new Error(`${label} '${id}' requires ${canonicalizeFiles ? "a" : "an absolute"} non-empty path of at most ${MAX_PATH_BYTES} bytes without NUL.`);
36
42
  let extensionPath = rawPath;
37
43
  if (canonicalizeFiles) {
@@ -45,7 +51,7 @@ export function snapshotRequiredChildExtensions(value: unknown, label = "Require
45
51
  if (paths.has(extensionPath)) throw new Error(`${label} path '${extensionPath}' is duplicated.`);
46
52
  ids.add(id);
47
53
  paths.add(extensionPath);
48
- return Object.freeze({ id, path: extensionPath });
54
+ return Object.freeze(requireForAllRunners ? { id, path: extensionPath, requireForAllRunners } : { id, path: extensionPath });
49
55
  }));
50
56
  }
51
57
 
@@ -66,9 +72,11 @@ function registry(): Registry {
66
72
 
67
73
  /** Register one immutable host-required extension snapshot for a parent session. */
68
74
  export function registerRequiredChildExtensions(input: RegisterRequiredChildExtensionsInput): RequiredChildExtensionRegistration {
69
- if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => key !== "sessionId" && key !== "extensions")) throw new Error("Required child extension registration requires only sessionId and extensions.");
75
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => key !== "sessionId" && key !== "extensions" && key !== "requireForAllRunners")) throw new Error("Required child extension registration accepts only sessionId, extensions, and requireForAllRunners.");
70
76
  if (typeof input.sessionId !== "string" || !input.sessionId || input.sessionId.trim() !== input.sessionId || input.sessionId.length > 256 || input.sessionId.includes("\0")) throw new Error("Required child extension registration requires a non-empty trimmed sessionId of at most 256 characters without NUL.");
71
- const frozen = snapshotRequiredChildExtensions(input.extensions, "Required child extensions", true);
77
+ if (input.requireForAllRunners !== undefined && typeof input.requireForAllRunners !== "boolean") throw new Error("Required child extension registration requireForAllRunners must be a boolean.");
78
+ const canonical = snapshotRequiredChildExtensions(input.extensions, "Required child extensions", true);
79
+ const frozen = input.requireForAllRunners ? Object.freeze(canonical.map((entry) => Object.freeze({ ...entry, requireForAllRunners: true as const }))) : canonical;
72
80
  const store = registry();
73
81
  if (store.bySession.has(input.sessionId)) throw new Error(`Required child extensions are already registered for session '${input.sessionId}'; dispose them first.`);
74
82
  store.bySession.set(input.sessionId, frozen);
@@ -79,3 +87,29 @@ export function resolveRequiredChildExtensions(sessionId: string | undefined): R
79
87
  if (!sessionId) return EMPTY_SNAPSHOT;
80
88
  return registry().bySession.get(sessionId) ?? EMPTY_SNAPSHOT;
81
89
  }
90
+
91
+ /** Reject a non-native runner or machine placement when any given snapshot has a `requireForAllRunners` entry. */
92
+ export function assertRequiredChildExtensionsAdmitted(snapshots: ReadonlyArray<RequiredChildExtensionSnapshot | undefined>, launch: { agent: string; runnerType?: string; machine?: string }): void {
93
+ const ids = [...new Set(snapshots.flatMap((snapshot) => snapshot ?? []).filter((entry) => entry.requireForAllRunners).map((entry) => entry.id))];
94
+ if (ids.length === 0) return;
95
+ const route = launch.machine ? `machine '${launch.machine}'` : launch.runnerType !== undefined && launch.runnerType !== "pi" ? `runner.type='${launch.runnerType}'` : undefined;
96
+ if (route) throw new Error(`Agent '${launch.agent}' cannot run on ${route}: the host requires child extensions (${ids.join(", ")}) for every runner, and only local native Pi children load them.`);
97
+ }
98
+
99
+ export function hasMandatoryRequiredChildExtensions(snapshot: RequiredChildExtensionSnapshot | undefined): snapshot is RequiredChildExtensionSnapshot {
100
+ return snapshot?.some((entry) => entry.requireForAllRunners) === true;
101
+ }
102
+
103
+ const RETAINED_FILE = "required-child-extensions.json";
104
+
105
+ /** Persist a run's mandatory snapshot so append-step admits against it; writes nothing without a mandatory entry. */
106
+ export function writeRetainedRequiredChildExtensions(asyncDir: string, snapshot: RequiredChildExtensionSnapshot): void {
107
+ if (!hasMandatoryRequiredChildExtensions(snapshot)) return;
108
+ fs.writeFileSync(path.join(asyncDir, RETAINED_FILE), `${JSON.stringify(snapshot)}\n`, { mode: 0o600 });
109
+ }
110
+
111
+ export function readRetainedRequiredChildExtensions(asyncDir: string): RequiredChildExtensionSnapshot | undefined {
112
+ const filePath = path.join(asyncDir, RETAINED_FILE);
113
+ if (!fs.existsSync(filePath)) return undefined;
114
+ return snapshotRequiredChildExtensions(JSON.parse(fs.readFileSync(filePath, "utf-8")), "Retained required child extensions");
115
+ }
@@ -1277,6 +1277,8 @@ export interface SingleResult {
1277
1277
  index: number;
1278
1278
  /** Workflow child key that owns this result when returned from workflow details. */
1279
1279
  workflowKey?: string;
1280
+ /** Workflow child run id that produced this result; resumed rounds share a session file but not a run id. */
1281
+ runId?: string;
1280
1282
  agent: string;
1281
1283
  task: string;
1282
1284
  /** Human-readable display name for the child's own session (agent + task
@@ -1439,6 +1441,7 @@ export interface AgentCapabilityRow {
1439
1441
  }
1440
1442
 
1441
1443
  export interface Details {
1444
+ commands?: import("../runs/shared/child-commands.ts").ChildCommandSnapshot[];
1442
1445
  mode: SubagentResultMode | "management";
1443
1446
  workflowReceiptPath?: string;
1444
1447
  runId?: string;
@@ -2699,6 +2702,8 @@ export interface ExtensionConfig {
2699
2702
  fleetKeybindings?: FleetKeybindingsConfig;
2700
2703
  /** Show the under-editor async runs widget. Defaults to true, including when FleetView is enabled. */
2701
2704
  asyncWidget?: boolean;
2705
+ /** Start the under-editor async runs widget folded. Defaults to false. */
2706
+ asyncWidgetCollapsed?: boolean;
2702
2707
  /** Exact provider/model candidates mapped to operator-declared equivalent response IDs. Empty arrays add no accepted IDs. */
2703
2708
  modelResponseAliases?: Record<string, string[]>;
2704
2709
  /** Tool description variant registered for the parent-facing subagent tool. Defaults to split metadata. */
@@ -2892,7 +2897,7 @@ export const POLL_INTERVAL_MS = 250;
2892
2897
  export const WIDGET_ANIMATION_INTERVAL_MS = 1000;
2893
2898
  export const MAX_WIDGET_JOBS = 4;
2894
2899
  export const DEFAULT_SUBAGENT_MAX_DEPTH = 2;
2895
- export const SUBAGENT_ACTIONS = ["list", "get", "models", "children.list", "guide", "validate", "create", "update", "delete", "eject", "disable", "enable", "reset", "mission.create", "mission.list", "mission.show", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "worktree.discard", "worktree.cleanup", "lane.status", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.show", "refine.rollback", "inspector.open", "inspector.command", "inspector.status", "inspector.close", "project.open", "project.status", "project.close", "status", "debug.run", "grant-spawn-budget", "interrupt", "resume", "steer", "stop", "dismiss", "doctor", "watchdog.status", "watchdog.check", "watchdog.configure", "watchdog.recommend-model", "schedule.create", "schedule.list", "schedule.show", "schedule.history", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"] as const;
2900
+ export const SUBAGENT_ACTIONS = ["list", "get", "models", "children.list", "guide", "validate", "create", "update", "delete", "eject", "disable", "enable", "reset", "mission.create", "mission.list", "mission.show", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "worktree.discard", "worktree.cleanup", "lane.status", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.show", "refine.rollback", "inspector.open", "inspector.command", "inspector.status", "inspector.close", "project.open", "project.status", "project.close", "status", "debug.run", "grant-spawn-budget", "interrupt", "resume", "steer", "stop", "command.status", "command.yield", "command.cancel", "dismiss", "doctor", "watchdog.status", "watchdog.check", "watchdog.configure", "watchdog.recommend-model", "schedule.create", "schedule.list", "schedule.show", "schedule.history", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"] as const;
2896
2901
 
2897
2902
  export const DEFAULT_FORK_PREAMBLE =
2898
2903
  "You are a delegated subagent running from a fork of the parent session. " +
@@ -3,7 +3,7 @@ import * as path from "node:path";
3
3
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
4
  import { getArtifactPaths, getArtifactsDir } from "../shared/artifacts.ts";
5
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";
6
+ import { DIRS, SLASH_RESULT_TYPE, type Details, type SubagentState, type Usage } from "../shared/types.ts";
7
7
  import { readStatus } from "../shared/utils.ts";
8
8
  import { readWorkflowReceipt } from "../workflows/workflow-receipt.ts";
9
9
  import { resolveSlashMessageDetails } from "./slash-live-state.ts";
@@ -187,12 +187,12 @@ export function collectSubagentCost(
187
187
  if (parentUsage) addUsage(parent, parentUsage);
188
188
  const details = detailsFromSessionEntry(entry);
189
189
  if (!details) continue;
190
- if (details.mode === "workflow" && details.runId) workflowRunIds.add(details.runId);
190
+ // Only async workflows persist a receipt file; foreground workflow child usage is already in results.
191
+ if (details.mode === "workflow" && details.runId && details.asyncId) workflowRunIds.add(details.runId);
191
192
  // An async launch result has no child results; its usage lands in run artifacts.
192
193
  else if (details.asyncId && details.results.length === 0) asyncRunIds.add(details.asyncId);
193
194
  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 });
195
+ addChild({ agent: result.agent, runId: typeof result.runId === "string" ? result.runId : undefined, usage: usageFromValue(result.usage), sessionFile: result.sessionFile });
196
196
  }
197
197
  for (const completion of details.completions ?? []) {
198
198
  if (completion.mode === "workflow") workflowRunIds.add(completion.runId);
@@ -248,7 +248,11 @@ export function collectSubagentCost(
248
248
  if (!usage || !addChild({ ...ref, usage })) unresolvedAsyncChildren += 1;
249
249
  }
250
250
  } catch (error) {
251
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to resolve async subagent usage for '${workflowRunId}':`, error);
251
+ // Without a receipt, a bg_wait completion cannot prove it reported every child (a stopped workflow may omit one).
252
+ unresolvedAsyncChildren += 1;
253
+ // A running workflow has no receipt yet; readWorkflowReceipt keeps the ENOENT as its cause.
254
+ const missing = (error as NodeJS.ErrnoException).code === "ENOENT" || ((error as Error).cause as NodeJS.ErrnoException | undefined)?.code === "ENOENT";
255
+ if (!missing) console.error(`Failed to resolve async subagent usage for '${workflowRunId}':`, error);
252
256
  }
253
257
  }
254
258
 
package/src/tui/render.ts CHANGED
@@ -2900,7 +2900,7 @@ function materializedWidgetChildLines(job: AsyncJobState, theme: Theme, width: n
2900
2900
  return lines;
2901
2901
  }
2902
2902
 
2903
- function buildWidgetComponent(jobs: AsyncJobState[], ui: ExtensionContext["ui"]): (tui: { requestRender(): void }, theme: Theme) => Component {
2903
+ function buildWidgetComponent(jobs: AsyncJobState[], ui: ExtensionContext["ui"], initiallyCollapsed = false): (tui: { requestRender(): void }, theme: Theme) => Component {
2904
2904
  return (tui, theme) => {
2905
2905
  const container = new Container();
2906
2906
  let cachedRenderWidth: number | undefined;
@@ -2908,7 +2908,7 @@ function buildWidgetComponent(jobs: AsyncJobState[], ui: ExtensionContext["ui"])
2908
2908
  let cachedExpanded: boolean | undefined;
2909
2909
  let cachedLines: string[] | undefined;
2910
2910
  let cachedCoverage = "[]";
2911
- let collapsed = false;
2911
+ let collapsed = initiallyCollapsed;
2912
2912
  const invalidate = (): void => {
2913
2913
  cachedLines = undefined;
2914
2914
  resetWidgetLayoutSession();
@@ -3080,7 +3080,7 @@ export function buildWidgetLines(jobs: AsyncJobState[], theme: Theme, width = ge
3080
3080
  /**
3081
3081
  * Render the async jobs widget
3082
3082
  */
3083
- export function renderWidget(ctx: ExtensionContext, jobs: AsyncJobState[]): void {
3083
+ export function renderWidget(ctx: ExtensionContext, jobs: AsyncJobState[], initiallyCollapsed = false): void {
3084
3084
  if (jobs.length === 0) {
3085
3085
  resetWidgetLayoutSession();
3086
3086
  asyncWidgetUpdates.delete(ctx.ui);
@@ -3096,7 +3096,7 @@ export function renderWidget(ctx: ExtensionContext, jobs: AsyncJobState[]): void
3096
3096
  // component instead so progress cannot move it past other extensions' widgets.
3097
3097
  const update = asyncWidgetUpdates.get(ctx.ui);
3098
3098
  if (update) update(jobs);
3099
- else ctx.ui.setWidget(WIDGET_KEY, buildWidgetComponent(jobs, ctx.ui));
3099
+ else ctx.ui.setWidget(WIDGET_KEY, buildWidgetComponent(jobs, ctx.ui, initiallyCollapsed));
3100
3100
  }
3101
3101
 
3102
3102
  function renderSingleCompact(
@@ -321,9 +321,9 @@ export function readWorkflowReceipt(asyncDirRoot: string, workflowRunId: string)
321
321
  if ((error as NodeJS.ErrnoException).code === "ENOENT") {
322
322
  const workflowDir = path.dirname(receiptPath);
323
323
  if (fs.existsSync(path.join(workflowDir, "status.json")) || fs.existsSync(path.join(workflowDir, "events.jsonl"))) {
324
- throw new Error(`Workflow receipt '${workflowRunId}' is not available because the workflow may still be active or terminal receipt writing failed. Use direct child run IDs from status/events for direct resume after the normal retained-child checks.`);
324
+ throw new Error(`Workflow receipt '${workflowRunId}' is not available because the workflow may still be active or terminal receipt writing failed. Use direct child run IDs from status/events for direct resume after the normal retained-child checks.`, { cause: error });
325
325
  }
326
- throw new Error(`Workflow receipt '${workflowRunId}' was not found.`);
326
+ throw new Error(`Workflow receipt '${workflowRunId}' was not found.`, { cause: error });
327
327
  }
328
328
  throw new Error(`Workflow receipt '${workflowRunId}' could not be read: ${error instanceof Error ? error.message : String(error)}`, { cause: error instanceof Error ? error : undefined });
329
329
  }
@@ -9,7 +9,10 @@ import type { WorkflowResourceProvenance } from "../shared/types.ts";
9
9
  import { buildStructuredWorkflowScript, isPlainRecord } from "./structured-workflow-scripts.ts";
10
10
 
11
11
  const RESOURCE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
12
- const MAX_ARGS_BYTES = 16 * 1024;
12
+ export const MAX_ARGS_BYTES = 16 * 1024;
13
+ export const MAX_ARGS_FIELDS = 16;
14
+ export const MAX_ARGS_ITEMS = 64;
15
+ export const MAX_ARGS_DEPTH = 8;
13
16
  const MAX_STRING_BYTES = 16 * 1024;
14
17
 
15
18
  export interface ResolvedWorkflowResource {
@@ -96,7 +99,7 @@ function jsonByteLength(value: unknown): number {
96
99
  }
97
100
 
98
101
  function validatePlainJson(value: unknown, path: string, depth = 0): void {
99
- if (depth > 8) throw new Error(`${path} is too deeply nested.`);
102
+ if (depth > MAX_ARGS_DEPTH) throw new Error(`${path} is too deeply nested.`);
100
103
  if (value === null || typeof value === "boolean") return;
101
104
  if (typeof value === "string") {
102
105
  if (!value.trim()) throw new Error(`${path} must not be empty.`);
@@ -108,12 +111,12 @@ function validatePlainJson(value: unknown, path: string, depth = 0): void {
108
111
  return;
109
112
  }
110
113
  if (Array.isArray(value)) {
111
- if (value.length > 64) throw new Error(`${path} contains too many items.`);
114
+ if (value.length > MAX_ARGS_ITEMS) throw new Error(`${path} contains too many items.`);
112
115
  for (const [index, entry] of value.entries()) validatePlainJson(entry, `${path}[${index}]`, depth + 1);
113
116
  return;
114
117
  }
115
118
  if (!isPlainRecord(value)) throw new Error(`${path} must contain plain JSON data.`);
116
- if (Object.keys(value).length > 16) throw new Error(`${path} contains too many fields.`);
119
+ if (Object.keys(value).length > MAX_ARGS_FIELDS) throw new Error(`${path} contains too many fields.`);
117
120
  for (const [key, entry] of Object.entries(value)) {
118
121
  if (!key.trim()) throw new Error(`${path} contains an empty field name.`);
119
122
  validatePlainJson(entry, `${path}.${key}`, depth + 1);