@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -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 +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -1,8 +1,16 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { createJiti } from "jiti";
5
+ import * as piCore from "@earendil-works/pi-agent-core";
6
+ import * as piAi from "@earendil-works/pi-ai/compat";
7
+ import * as piTui from "@earendil-works/pi-tui";
3
8
  import * as sdk from "@earendil-works/pi-coding-agent";
9
+ import * as typebox from "typebox";
10
+ import * as typeboxCompile from "typebox/compile";
11
+ import * as typeboxValue from "typebox/value";
4
12
  import { installRunnerHttpDispatcher } from "./runner-http-dispatcher.ts";
5
- import { runConfiguredSubagent, type SubagentRunConfig } from "./subagent-runner.ts";
13
+ import { runConfiguredSubagent, validateSubagentRunConfig } from "./subagent-runner-bootstrap.ts";
6
14
  import { getAgentDir } from "../../shared/utils.ts";
7
15
 
8
16
  /**
@@ -17,10 +25,9 @@ export default async function runBinaryBootstrap(): Promise<never> {
17
25
  delete process.env.PI_SUBAGENT_RUNNER_CONFIG;
18
26
  try {
19
27
  if (!configPath || !path.isAbsolute(configPath)) throw new Error("Missing absolute PI_SUBAGENT_RUNNER_CONFIG path");
20
- const config = JSON.parse(fs.readFileSync(configPath, "utf8")) as SubagentRunConfig;
21
- if (!config || typeof config.id !== "string" || typeof config.asyncDir !== "string" || !Array.isArray(config.steps)) {
22
- throw new Error("Invalid binary runner configuration");
23
- }
28
+ const rawConfig: unknown = JSON.parse(fs.readFileSync(configPath, "utf8"));
29
+ validateSubagentRunConfig(rawConfig);
30
+ const config = rawConfig;
24
31
  try {
25
32
  fs.unlinkSync(configPath);
26
33
  } catch {
@@ -29,7 +36,28 @@ export default async function runBinaryBootstrap(): Promise<never> {
29
36
  // Pi applies httpIdleTimeoutMs to its dispatcher only after extension
30
37
  // factories return; this factory never does, so install the runner's own.
31
38
  installRunnerHttpDispatcher({ agentDir: getAgentDir(), cwd: process.cwd() });
32
- await runConfiguredSubagent(config, { loadPiCodingAgent: async () => sdk });
39
+ await runConfiguredSubagent(config, {
40
+ loadPiCodingAgent: async () => sdk,
41
+ loadExecutionModule: async () => {
42
+ // Native Bun imports bypass Pi's Jiti virtual peers in the compiled host.
43
+ const jiti = createJiti(import.meta.url, {
44
+ tryNative: false,
45
+ moduleCache: false,
46
+ virtualModules: {
47
+ "@earendil-works/pi-agent-core": piCore,
48
+ "@earendil-works/pi-ai": piAi,
49
+ "@earendil-works/pi-ai/compat": piAi,
50
+ "@earendil-works/pi-tui": piTui,
51
+ "@earendil-works/pi-coding-agent": sdk,
52
+ typebox,
53
+ "typebox/compile": typeboxCompile,
54
+ "typebox/value": typeboxValue,
55
+ },
56
+ });
57
+ const runner = `./subagent-runner${path.extname(fileURLToPath(import.meta.url))}`;
58
+ return jiti.import<typeof import("./subagent-runner.ts")>(runner);
59
+ },
60
+ });
33
61
  process.exit(0);
34
62
  } catch (error) {
35
63
  console.error("Subagent binary runner error:", error);
@@ -161,7 +161,7 @@ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus,
161
161
  };
162
162
  }
163
163
 
164
- function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null, message: string): ImportedAsyncRootResult {
164
+ function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null, message: string, stopped = false): ImportedAsyncRootResult {
165
165
  const step = selectedStatusStep(status, root.index);
166
166
  return {
167
167
  agent: step?.agent ?? status?.steps?.[root.index]?.agent ?? "subagent",
@@ -169,7 +169,7 @@ function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null,
169
169
  success: false,
170
170
  exitCode: 1,
171
171
  error: message,
172
- timedOut: true,
172
+ ...(stopped ? { stopped: true } : { timedOut: true }),
173
173
  ...(step?.sessionName ? { sessionName: step.sessionName } : {}),
174
174
  ...(step?.sessionFile ?? status?.sessionFile ? { sessionFile: step?.sessionFile ?? status?.sessionFile } : {}),
175
175
  ...(step?.model ? { model: step.model } : {}),
@@ -228,7 +228,7 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
228
228
 
229
229
  export async function waitForImportedAsyncRoot(
230
230
  root: ImportedAsyncRoot,
231
- options: { pollIntervalMs?: number; terminalResultGraceMs?: number; now?: () => number; shouldAbort?: () => boolean; timeoutMessage?: string } = {},
231
+ options: { pollIntervalMs?: number; terminalResultGraceMs?: number; now?: () => number; shouldAbort?: () => boolean; timeoutMessage?: string; abortedAsStopped?: boolean } = {},
232
232
  ): Promise<ImportedAsyncRootResult> {
233
233
  const pollIntervalMs = options.pollIntervalMs ?? 500;
234
234
  const terminalResultGraceMs = options.terminalResultGraceMs ?? 1_000;
@@ -236,7 +236,7 @@ export async function waitForImportedAsyncRoot(
236
236
  let terminalSince: number | undefined;
237
237
  for (;;) {
238
238
  const status = readStatus(root.asyncDir);
239
- if (options.shouldAbort?.()) return outputFromTimeout(root, status, options.timeoutMessage ?? "Subagent timed out.");
239
+ if (options.shouldAbort?.()) return outputFromTimeout(root, status, options.timeoutMessage ?? "Subagent timed out.", options.abortedAsStopped === true);
240
240
  const result = readImportedResultFile(root, status);
241
241
  if (result) return buildImportedResult(root, status, result);
242
242
  if (isTerminalStatus(status, root.index)) {
@@ -79,6 +79,8 @@ const STOP_REQUESTS_DIR = "stop-requests";
79
79
  const REVIVAL_BRIEFS_DIR = "revival-briefs";
80
80
  export const MAX_STEER_QUEUE_SIZE = 20;
81
81
  const STEER_INBOX_CLOSED_FILE = "steer-inbox-closed.json";
82
+ const STOP_INBOX_CLOSED_FILE = "stop-inbox-closed.json";
83
+ const STOP_INBOX_CLOSED_MESSAGE = "Runner stop inbox is closed. Retry stop after runner shutdown is observed.";
82
84
  const MAX_STEER_MESSAGE_BYTES = 128 * 1024;
83
85
  const MAX_STEER_REQUEST_ID_LENGTH = 256;
84
86
 
@@ -116,6 +118,14 @@ export function steerInboxClosedPath(asyncDir: string): string {
116
118
  return path.join(controlInboxDir(asyncDir), STEER_INBOX_CLOSED_FILE);
117
119
  }
118
120
 
121
+ export function stopInboxClosedPath(asyncDir: string): string {
122
+ return path.join(controlInboxDir(asyncDir), STOP_INBOX_CLOSED_FILE);
123
+ }
124
+
125
+ export function closeStopInbox(asyncDir: string): void {
126
+ writeAtomicJson(stopInboxClosedPath(asyncDir), { version: 1, closedAt: Date.now() });
127
+ }
128
+
119
129
  export function closeSteerInbox(asyncDir: string, state: string, write: (filePath: string, payload: object) => void = writeAtomicJson): void {
120
130
  write(steerInboxClosedPath(asyncDir), { version: 1, closedAt: Date.now(), state });
121
131
  }
@@ -206,15 +216,21 @@ export function requestAsyncTimeout(
206
216
  export function requestAsyncStop(
207
217
  asyncDir: string,
208
218
  payload: Omit<StopRequest, "type"> = {},
209
- deps: { now?: () => number } = {},
219
+ deps: { now?: () => number; write?: typeof writeAtomicJson } = {},
210
220
  ): string {
211
221
  if (payload.targetIndex !== undefined) assertChildIndex(payload.targetIndex);
212
222
  if (payload.childId !== undefined && !validStopChildId(payload.childId)) {
213
223
  throw new Error("stop childId must be a non-empty string without newlines and at most 256 characters.");
214
224
  }
225
+ const closedPath = stopInboxClosedPath(asyncDir);
226
+ if (fs.existsSync(closedPath)) throw new Error(STOP_INBOX_CLOSED_MESSAGE);
215
227
  const request: StopRequest = { ...payload, ts: payload.ts ?? deps.now?.() ?? Date.now(), type: "stop" };
216
228
  const requestPath = path.join(stopRequestsDir(asyncDir), stopRequestFileName(request));
217
- writeAtomicJson(requestPath, request);
229
+ (deps.write ?? writeAtomicJson)(requestPath, request);
230
+ if (fs.existsSync(closedPath)) {
231
+ fs.rmSync(requestPath, { force: true });
232
+ throw new Error(STOP_INBOX_CLOSED_MESSAGE);
233
+ }
218
234
  return requestPath;
219
235
  }
220
236
 
@@ -339,7 +339,16 @@ function formatDetachedForegroundFleetLines(runs: ForegroundRun[]): string[] {
339
339
  return lines;
340
340
  }
341
341
 
342
- function formatAsyncFleetLines(runs: AsyncRunSummary[]): string[] {
342
+ function externalCliStepFacts(step: AsyncRunSummary["steps"][number], now: number): string | undefined {
343
+ if (step.runner?.type !== "external-cli") return undefined;
344
+ const process = step.externalProcess;
345
+ const elapsed = process
346
+ ? process.durationMs ?? Math.max(0, (process.endedAt ?? now) - process.startedAt)
347
+ : undefined;
348
+ return `external-cli${elapsed !== undefined ? ` · ${formatDuration(elapsed)}` : ""}`;
349
+ }
350
+
351
+ function formatAsyncFleetLines(runs: AsyncRunSummary[], now = Date.now()): string[] {
343
352
  if (runs.length === 0) return [];
344
353
  const lines = ["Async runs:"];
345
354
  for (const run of runs) {
@@ -357,7 +366,7 @@ function formatAsyncFleetLines(runs: AsyncRunSummary[]): string[] {
357
366
  const phase = step.phase ? `[${step.phase}] ` : "";
358
367
  const stepActivity = formatActivityFacts(step);
359
368
  const modelThinking = formatModelThinking(step.model, step.thinking);
360
- const parts = [`${step.index}. ${phase}${display}${stepContext ? ` ${stepContext}` : ""}`, step.status, stepActivity, modelThinking].filter(Boolean);
369
+ const parts = [`${step.index}. ${phase}${display}${stepContext ? ` ${stepContext}` : ""}`, step.status, externalCliStepFacts(step, now), stepActivity, modelThinking].filter(Boolean);
361
370
  lines.push(` ${parts.join(" | ")}`);
362
371
  const output = path.join(run.asyncDir, `output-${step.index}.log`);
363
372
  if (fs.existsSync(output)) lines.push(` output: ${shortenPath(output)}`);
@@ -420,7 +429,7 @@ export function inspectSubagentFleet(_params: FleetViewParams, deps: FleetViewDe
420
429
  if (foregroundLines.length) lines.push(...foregroundLines, "");
421
430
  const detachedForegroundLines = formatDetachedForegroundFleetLines(detachedForegroundRuns);
422
431
  if (detachedForegroundLines.length) lines.push(...detachedForegroundLines, "");
423
- const asyncLines = formatAsyncFleetLines(asyncRuns);
432
+ const asyncLines = formatAsyncFleetLines(asyncRuns, deps.now?.() ?? Date.now());
424
433
  if (asyncLines.length) lines.push(...asyncLines, "");
425
434
  lines.push("Commands:");
426
435
  lines.push(" Refresh fleet: subagent({ action: \"status\", view: \"fleet\" })");
@@ -525,14 +534,39 @@ function appendTranscriptBody(lines: string[], sourceLabel: string, sourceLines:
525
534
  lines.push(...body.reverse());
526
535
  }
527
536
 
537
+ function resolveWorkflowTranscriptChild(status: AsyncStatus, asyncDir: string, options: TranscriptOptions): { status: AsyncStatus; asyncDir: string } | undefined {
538
+ if (status.mode !== "workflow" || options.index === undefined) return undefined;
539
+ const step = status.steps?.[options.index];
540
+ if (step?.async !== true || typeof step.runId !== "string" || !/^[A-Za-z0-9_-]+$/.test(step.runId) || step.runId === status.runId) return undefined;
541
+ try {
542
+ const asyncRoot = fs.realpathSync(path.dirname(asyncDir));
543
+ const childDir = path.join(asyncRoot, step.runId);
544
+ if (fs.realpathSync(childDir) !== childDir || fs.lstatSync(path.join(childDir, "status.json")).isSymbolicLink()) return undefined;
545
+ const childStatus = readStatus(childDir);
546
+ return childStatus?.runId === step.runId
547
+ && childStatus.parentWorkflowRunId === status.runId
548
+ && typeof step.workflowKey === "string" && step.workflowKey.length > 0
549
+ && childStatus.workflowKey === step.workflowKey
550
+ && typeof status.sessionId === "string" && status.sessionId.length > 0
551
+ && childStatus.sessionId === status.sessionId
552
+ ? { status: childStatus, asyncDir: childDir }
553
+ : undefined;
554
+ } catch (error) {
555
+ if (isNotFoundError(error)) return undefined;
556
+ throw error;
557
+ }
558
+ }
559
+
528
560
  export function formatAsyncRunTranscript(status: AsyncStatus, asyncDir: string, options: TranscriptOptions = {}): string {
561
+ const workflowChild = resolveWorkflowTranscriptChild(status, asyncDir, options);
562
+ if (workflowChild) return formatAsyncRunTranscript(workflowChild.status, workflowChild.asyncDir, { ...options, index: undefined });
529
563
  const lineLimit = transcriptLineLimit(options.lines);
530
564
  const selected = selectTranscriptStep(status, options);
531
565
  const stepOutputPath = selected.index !== undefined ? path.join(asyncDir, `output-${selected.index}.log`) : undefined;
532
566
  const runOutputPath = resolveMaybeRelative(asyncDir, status.outputFile);
533
567
  const logPath = path.join(asyncDir, `subagent-log-${status.runId}.md`);
534
568
  const outputPaths = selected.index !== undefined
535
- ? uniqueStrings([stepOutputPath, runOutputPath && stepOutputPath && path.resolve(runOutputPath) === path.resolve(stepOutputPath) ? runOutputPath : undefined])
569
+ ? uniqueStrings([selected.step?.externalProcess?.finalOutputPath, stepOutputPath, runOutputPath && stepOutputPath && path.resolve(runOutputPath) === path.resolve(stepOutputPath) ? runOutputPath : undefined])
536
570
  : uniqueStrings([runOutputPath]);
537
571
  const sessionFile = selected.index !== undefined ? selected.step?.sessionFile : status.sessionFile;
538
572
  const eventsPath = path.join(asyncDir, "events.jsonl");
@@ -553,12 +587,22 @@ export function formatAsyncRunTranscript(status: AsyncStatus, asyncDir: string,
553
587
  let transcriptLines: string[] = [];
554
588
  let transcriptSource = "Transcript tail";
555
589
  let truncated = false;
556
- for (const outputPath of outputPaths) {
590
+ const externalProcess = selected.step?.runner?.type === "external-cli" ? selected.step.externalProcess : undefined;
591
+ const externalLogPaths = externalProcess ? [
592
+ { path: externalProcess.stderrPath, label: "External stderr tail" },
593
+ { path: externalProcess.stdoutPath, label: "External stdout tail" },
594
+ ] : [];
595
+ const runningExternal = selected.step?.status === "running" && externalProcess;
596
+ const sources = runningExternal
597
+ ? [...externalLogPaths, ...outputPaths.map((outputPath) => ({ path: outputPath, label: "Transcript tail" }))]
598
+ : [...outputPaths.map((outputPath) => ({ path: outputPath, label: "Transcript tail" })), ...externalLogPaths];
599
+ for (const source of sources) {
600
+ const outputPath = source.path;
557
601
  const tail = readContainedTextTail(outputPath, lineLimit, [asyncDir], "output");
558
602
  if (tail.error) warnings.push(`Output read failed for ${tail.path}: ${tail.error}`);
559
- if (tail.lines.length === 0) continue;
603
+ if (!tail.lines.some((line) => line.trim().length > 0)) continue;
560
604
  transcriptLines = tail.lines;
561
- transcriptSource = `Transcript tail from ${tail.path}`;
605
+ transcriptSource = `${source.label} from ${tail.path}`;
562
606
  truncated = tail.truncated;
563
607
  break;
564
608
  }
@@ -27,6 +27,8 @@ export interface SubagentNotifyChildOutput {
27
27
  runId?: string;
28
28
  agent?: string;
29
29
  status: string;
30
+ /** Latest detached revival of this failed child, e.g. `Revived → <run>: completed`. */
31
+ revival?: string;
30
32
  savedOutputPath?: string;
31
33
  outputArtifactPath?: string;
32
34
  structuredOutputPath?: string;
@@ -93,6 +95,7 @@ export interface CompletionNotification {
93
95
  agent?: string;
94
96
  status?: string;
95
97
  state?: string;
98
+ revival?: string;
96
99
  success?: boolean;
97
100
  output?: string;
98
101
  structuredOutput?: unknown;
@@ -141,6 +144,7 @@ export interface RegisterSubagentNotifyOptions {
141
144
  timers?: NotifyTimerApi;
142
145
  now?: () => number;
143
146
  ownership?: Pick<ResultDeliveryOwnership, "owns">;
147
+ sendRegistry?: CompletionSendRegistry;
144
148
  }
145
149
 
146
150
  export interface CompletionNotifier {
@@ -152,6 +156,8 @@ export interface CompletionNotifier {
152
156
  const CHILD_OUTPUT_PREVIEW_MAX_BYTES = 4 * 1024;
153
157
  const CHILD_OUTPUT_PREVIEW_COUNT = 8;
154
158
  const PREVIEW_TRUNCATION_MARKER = "...[preview truncated]";
159
+ const COMPLETION_SEND_TTL_MS = 10 * 60 * 1000;
160
+ const COMPLETION_SEND_REGISTRY_CAP = 4_096;
155
161
  type CompletionChild = NonNullable<CompletionNotification["results"]>[number];
156
162
  interface RetainedPathError { path: string; code?: string; message: string }
157
163
  type RetainedPathProjection =
@@ -210,7 +216,7 @@ function formatRetainedPathError(label: string, error: RetainedPathError): strin
210
216
  function childStatus(child: CompletionChild, workflowState?: string): string {
211
217
  const knownStatus = child.status === "complete"
212
218
  ? "completed"
213
- : child.status === "completed" || child.status === "failed" || child.status === "paused" || child.status === "stopped" || child.status === "detached"
219
+ : child.status === "running" || child.status === "completed" || child.status === "failed" || child.status === "paused" || child.status === "stopped" || child.status === "detached"
214
220
  ? child.status
215
221
  : undefined;
216
222
  if (knownStatus) return knownStatus;
@@ -266,6 +272,7 @@ function formatChildOutputBlock(children: SubagentNotifyChildOutput[] | undefine
266
272
  const runId = child.runId ? boundedSafeText(child.runId) : "unavailable";
267
273
  const status = boundedSafeText(child.status) || "unavailable";
268
274
  lines.push(`- key=${key} run=${runId} status=${status}`);
275
+ if (child.revival) lines.push(` ${boundedSafeText(child.revival)}`);
269
276
  lines.push(` Saved output: ${child.savedOutputPath ? boundedSafeText(child.savedOutputPath) : "unavailable"}`);
270
277
  if (child.outputArtifactPath) lines.push(` Output artifact (retention-managed): ${boundedSafeText(child.outputArtifactPath)}`);
271
278
  if (child.structuredOutputPath) lines.push(` Structured output (retention-managed): ${boundedSafeText(child.structuredOutputPath)}`);
@@ -492,7 +499,7 @@ const notificationDebug = debuglog("pi-subagents-notify");
492
499
  type TraceIdentity = Pick<CompletionNotification, "id" | "runId" | "source">;
493
500
  type NotificationReason = "disposed" | "missing_session" | "foreground_session_mismatch" | "not_owned"
494
501
  | "intercom_delivered" | "deduped_ttl" | "deduped_pending" | "batch_deferred"
495
- | "emit_foreground_session_mismatch" | "emit_not_owned" | "send_accepted" | "send_failed" | "dispose_pending";
502
+ | "emit_foreground_session_mismatch" | "emit_not_owned" | "send_joined" | "send_accepted" | "send_failed" | "dispose_pending";
496
503
 
497
504
  // Slice before sanitizing: diagnostic work and each identity are bounded even for
498
505
  // malformed result metadata. Never include task/output, paths, or error bodies.
@@ -521,6 +528,72 @@ interface PendingCompletion {
521
528
  resolve(accepted: boolean): void;
522
529
  }
523
530
 
531
+ export interface CompletionSendClaim {
532
+ owned: boolean;
533
+ outcome: Promise<boolean>;
534
+ settle?(accepted: boolean): void;
535
+ }
536
+
537
+ export interface CompletionSendRegistry {
538
+ claim(key: string, now: number): CompletionSendClaim;
539
+ }
540
+
541
+ interface CompletionSendEntry {
542
+ outcome: Promise<boolean>;
543
+ resolve(accepted: boolean): void;
544
+ deliveredAt?: number;
545
+ }
546
+
547
+ /** A fresh registry is injectable so tests and separately scoped runtimes stay isolated. */
548
+ export function createCompletionSendRegistry(
549
+ ttlMs = COMPLETION_SEND_TTL_MS,
550
+ cap = COMPLETION_SEND_REGISTRY_CAP,
551
+ ): CompletionSendRegistry {
552
+ const entries = new Map<string, CompletionSendEntry>();
553
+ const prune = (now: number) => {
554
+ for (const [key, entry] of entries) {
555
+ if (entry.deliveredAt !== undefined && now - entry.deliveredAt > ttlMs) entries.delete(key);
556
+ }
557
+ if (entries.size <= cap) return;
558
+ for (const [key, entry] of entries) {
559
+ if (entries.size <= cap) break;
560
+ if (entry.deliveredAt !== undefined) entries.delete(key);
561
+ }
562
+ };
563
+ return {
564
+ claim(key, now) {
565
+ prune(now);
566
+ const existing = entries.get(key);
567
+ if (existing) return { owned: false, outcome: existing.outcome };
568
+ let resolve!: (accepted: boolean) => void;
569
+ const entry: CompletionSendEntry = {
570
+ outcome: new Promise<boolean>((settle) => { resolve = settle; }),
571
+ resolve: (accepted) => resolve(accepted),
572
+ };
573
+ entries.set(key, entry);
574
+ return {
575
+ owned: true,
576
+ outcome: entry.outcome,
577
+ settle(accepted) {
578
+ if (entries.get(key) !== entry) return;
579
+ if (accepted) {
580
+ entry.deliveredAt = now;
581
+ prune(now);
582
+ } else {
583
+ entries.delete(key);
584
+ }
585
+ entry.resolve(accepted);
586
+ },
587
+ };
588
+ },
589
+ };
590
+ }
591
+
592
+ const completionSendRegistrySymbol = Symbol.for("pi-subagents.completion-send-registry.v1");
593
+ const processGlobal = globalThis as typeof globalThis & { [completionSendRegistrySymbol]?: CompletionSendRegistry };
594
+ const processCompletionSendRegistry = processGlobal[completionSendRegistrySymbol]
595
+ ?? (processGlobal[completionSendRegistrySymbol] = createCompletionSendRegistry());
596
+
524
597
  function sendCompletion(pi: Pick<ExtensionAPI, "sendMessage">, items: PendingCompletion[]): boolean {
525
598
  if (items.length === 0) return true;
526
599
  const details = items.map((item) => item.details);
@@ -564,8 +637,11 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
564
637
  || summary.startsWith("Paused after interrupt.")
565
638
  );
566
639
  const status = stopped ? "stopped" : paused ? "paused" : result.success ? "completed" : "failed";
567
- const taskInfo =
568
- result.taskIndex !== undefined && result.totalTasks !== undefined
640
+ const runningChildren = (result.mode === "workflow" || agent === "workflow")
641
+ ? result.results?.filter((child) => childStatus(child) === "running").length ?? 0 : 0;
642
+ const taskInfo = runningChildren > 0
643
+ ? ` (${status === "completed" ? "dispatch complete; " : ""}${runningChildren} ${runningChildren === 1 ? "child" : "children"} running or uncollected)`
644
+ : result.taskIndex !== undefined && result.totalTasks !== undefined
569
645
  ? ` (${result.taskIndex + 1}/${result.totalTasks})`
570
646
  : undefined;
571
647
 
@@ -624,6 +700,7 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
624
700
  ...(runId ? { runId } : {}),
625
701
  ...(typeof child.agent === "string" ? { agent: child.agent } : {}),
626
702
  status: childStatus(child, result.state),
703
+ ...(typeof child.revival === "string" && child.revival ? { revival: child.revival } : {}),
627
704
  ...(savedOutputPath ? { savedOutputPath } : {}),
628
705
  ...(outputArtifact.status === "verified" ? { outputArtifactPath: outputArtifact.path } : {}),
629
706
  ...(structuredOutput.status === "verified" ? { structuredOutputPath: structuredOutput.path } : {}),
@@ -687,8 +764,9 @@ export default function registerSubagentNotify(
687
764
  ): CompletionNotifier {
688
765
  const seen = new Map<string, number>();
689
766
  const pending = new Map<string, Promise<boolean>>();
690
- const ttlMs = 10 * 60 * 1000;
767
+ const ttlMs = COMPLETION_SEND_TTL_MS;
691
768
  const now = options.now ?? Date.now;
769
+ const sendRegistry = options.sendRegistry ?? processCompletionSendRegistry;
692
770
  const batchConfig = resolveCompletionBatchConfig(options.batchConfig);
693
771
  const batchers = new Map<string, CompletionBatcher<PendingCompletion>>();
694
772
  let disposed = false;
@@ -716,8 +794,20 @@ export default function registerSubagentNotify(
716
794
  (owned ? accepted : rejected).push(item);
717
795
  }
718
796
  settle(rejected, false);
719
- const sent = sendCompletion(pi, accepted);
720
- settle(accepted, sent, sent ? "send_accepted" : "send_failed");
797
+ const claimed: Array<{ item: PendingCompletion; claim: CompletionSendClaim }> = [];
798
+ for (const item of accepted) {
799
+ const claim = sendRegistry.claim(item.key, now());
800
+ if (claim.owned) {
801
+ claimed.push({ item, claim });
802
+ continue;
803
+ }
804
+ traceNotification("send_joined", item.trace);
805
+ void claim.outcome.then((outcome) => settle([item], outcome, outcome ? undefined : "send_failed"));
806
+ }
807
+ const claimedItems = claimed.map(({ item }) => item);
808
+ const sent = sendCompletion(pi, claimedItems);
809
+ for (const { claim } of claimed) claim.settle?.(sent);
810
+ settle(claimedItems, sent, sent ? "send_accepted" : "send_failed");
721
811
  };
722
812
  const getBatcher = (result: CompletionNotification) => {
723
813
  const key = completionBatchKey(result);
@@ -793,6 +883,7 @@ export default function registerSubagentNotify(
793
883
  };
794
884
 
795
885
  const unsubscribeAsync = pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, (data) => {
886
+ if ((data as CompletionNotification).awaitedByWorkflow === true) return;
796
887
  void deliver(data as CompletionNotification);
797
888
  });
798
889
  const unsubscribeForeground = pi.events.on(SUBAGENT_FOREGROUND_COMPLETE_EVENT, (data) => {
@@ -0,0 +1,18 @@
1
+ import * as fs from "node:fs";
2
+
3
+ let resolved = false;
4
+ let cachedScope: string | undefined;
5
+
6
+ /** Linux PID namespace identity, cached because reconciliation is a polling path. */
7
+ export function currentPidNamespaceScope(): string | undefined {
8
+ if (resolved) return cachedScope;
9
+ resolved = true;
10
+ if (process.platform !== "linux") return undefined;
11
+ try {
12
+ const scope = fs.readlinkSync("/proc/self/ns/pid", "utf-8").trim();
13
+ cachedScope = scope || undefined;
14
+ } catch {
15
+ cachedScope = undefined;
16
+ }
17
+ return cachedScope;
18
+ }
@@ -0,0 +1,98 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
4
+ import type { ProcessInstanceExit } from "../../shared/types.ts";
5
+
6
+ export interface ProcessTerminalCandidate {
7
+ version: 1;
8
+ runId: string;
9
+ runnerProcessInstanceId: string;
10
+ writers: Record<string, ProcessInstanceExit[]>;
11
+ expectedWriters?: Record<string, number>;
12
+ sessionFile?: string;
13
+ revivalLeaseToken?: string;
14
+ revivalLeaseReleaseAcknowledged?: boolean;
15
+ }
16
+
17
+ export function isRecord(value: unknown): value is Record<string, unknown> {
18
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
19
+ }
20
+
21
+ export function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): value is ProcessInstanceExit {
22
+ if (!isRecord(value)) return false;
23
+ if (typeof value.processInstanceId !== "string" || value.processInstanceId.length === 0) return false;
24
+ if (kind ? value.kind !== kind : (value.kind !== "runner" && value.kind !== "pi-writer")) return false;
25
+ if (typeof value.closeObservedAt !== "number" || !Number.isFinite(value.closeObservedAt)) return false;
26
+ if (typeof value.exitCode !== "number" && value.exitCode !== null) return false;
27
+ if (typeof value.signal !== "string" && value.signal !== null) return false;
28
+ if (value.kind === "runner") return value.attempt === undefined;
29
+ if (typeof value.attempt !== "number" || !Number.isInteger(value.attempt) || value.attempt < 0 || !isRecord(value.processTree)) return false;
30
+ if (value.processTree.state === "observed") {
31
+ return value.processTree.mechanism === "posix-process-group"
32
+ && typeof value.processTree.processGroupId === "number"
33
+ && Number.isInteger(value.processTree.processGroupId)
34
+ && value.processTree.processGroupId > 0
35
+ && typeof value.processTree.verifiedAt === "number"
36
+ && Number.isFinite(value.processTree.verifiedAt);
37
+ }
38
+ return value.processTree.state === "unknown"
39
+ && ["unsupported-platform", "signal-failed", "verification-failed"].includes(String(value.processTree.reason))
40
+ && (value.processTree.diagnostic === undefined || typeof value.processTree.diagnostic === "string");
41
+ }
42
+
43
+ function validInstance(value: unknown): value is ProcessInstanceExit {
44
+ return validProcessInstance(value, "pi-writer");
45
+ }
46
+
47
+ export function processTerminalCandidatePath(asyncDir: string): string {
48
+ return path.join(asyncDir, "process-terminal-candidate.json");
49
+ }
50
+
51
+ export function readProcessTerminalCandidate(asyncDir: string): ProcessTerminalCandidate | undefined {
52
+ try {
53
+ const raw = JSON.parse(fs.readFileSync(processTerminalCandidatePath(asyncDir), "utf-8")) as unknown;
54
+ if (!isRecord(raw) || raw.version !== 1 || typeof raw.runId !== "string" || typeof raw.runnerProcessInstanceId !== "string" || !isRecord(raw.writers)) {
55
+ throw new Error(`Invalid process-terminal candidate in '${asyncDir}'.`);
56
+ }
57
+ const writers: Record<string, ProcessInstanceExit[]> = {};
58
+ for (const [index, entries] of Object.entries(raw.writers)) {
59
+ if (!Array.isArray(entries) || !entries.every(validInstance)) throw new Error(`Invalid writer process records for child '${index}'.`);
60
+ writers[index] = entries;
61
+ }
62
+ let expectedWriters: Record<string, number> | undefined;
63
+ if (raw.expectedWriters !== undefined) {
64
+ if (!isRecord(raw.expectedWriters)) throw new Error("Invalid expected writer process records.");
65
+ expectedWriters = {};
66
+ for (const [index, count] of Object.entries(raw.expectedWriters)) {
67
+ if (typeof count !== "number" || !Number.isInteger(count) || count < 0) throw new Error(`Invalid expected writer count for child '${index}'.`);
68
+ expectedWriters[index] = count;
69
+ }
70
+ }
71
+ if (raw.sessionFile !== undefined && typeof raw.sessionFile !== "string") throw new Error("Invalid process-terminal candidate sessionFile.");
72
+ if (raw.revivalLeaseToken !== undefined && typeof raw.revivalLeaseToken !== "string") throw new Error("Invalid process-terminal candidate lease token.");
73
+ if (raw.revivalLeaseReleaseAcknowledged !== undefined && typeof raw.revivalLeaseReleaseAcknowledged !== "boolean") throw new Error("Invalid process-terminal lease release acknowledgement.");
74
+ return {
75
+ version: 1,
76
+ runId: raw.runId,
77
+ runnerProcessInstanceId: raw.runnerProcessInstanceId,
78
+ writers,
79
+ ...(expectedWriters ? { expectedWriters } : {}),
80
+ ...(typeof raw.sessionFile === "string" && raw.sessionFile ? { sessionFile: raw.sessionFile } : {}),
81
+ ...(typeof raw.revivalLeaseToken === "string" && raw.revivalLeaseToken ? { revivalLeaseToken: raw.revivalLeaseToken } : {}),
82
+ ...(typeof raw.revivalLeaseReleaseAcknowledged === "boolean" ? { revivalLeaseReleaseAcknowledged: raw.revivalLeaseReleaseAcknowledged } : {}),
83
+ };
84
+ } catch (error) {
85
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
86
+ throw error;
87
+ }
88
+ }
89
+
90
+ export function writeProcessTerminalCandidate(asyncDir: string, candidate: ProcessTerminalCandidate): void {
91
+ writePrivateAtomicJson(processTerminalCandidatePath(asyncDir), candidate);
92
+ }
93
+
94
+ export function markProcessTerminalCandidateLeaseRelease(asyncDir: string, token: string, acknowledged: boolean): void {
95
+ const candidate = readProcessTerminalCandidate(asyncDir);
96
+ if (!candidate || candidate.revivalLeaseToken !== token) return;
97
+ writeProcessTerminalCandidate(asyncDir, { ...candidate, revivalLeaseReleaseAcknowledged: acknowledged });
98
+ }