@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -115,6 +115,22 @@ export function writeProcessTerminalCandidate(asyncDir: string, candidate: Proce
115
115
  writePrivateAtomicJson(processTerminalCandidatePath(asyncDir), candidate);
116
116
  }
117
117
 
118
+ /** Establish ownership before authorizing a runner to start any child session. */
119
+ export function initializeProcessTerminal(asyncDir: string, runId: string, runnerProcessInstanceId: string): void {
120
+ writeProcessTerminalCandidate(asyncDir, {
121
+ version: 1,
122
+ runId,
123
+ runnerProcessInstanceId,
124
+ writers: {},
125
+ });
126
+ writeAtomicJson(processTerminalPath(asyncDir), {
127
+ version: 1,
128
+ state: "pending",
129
+ runId,
130
+ runnerProcessInstanceId,
131
+ });
132
+ }
133
+
118
134
  export function markProcessTerminalCandidateLeaseRelease(asyncDir: string, token: string, acknowledged: boolean): void {
119
135
  const candidate = readProcessTerminalCandidate(asyncDir);
120
136
  if (!candidate || candidate.revivalLeaseToken !== token) return;
@@ -0,0 +1,45 @@
1
+ import type { SubagentState } from "../../shared/types.ts";
2
+
3
+ const MAX_CLAIMED_PREDECESSOR_SESSIONS = 8;
4
+
5
+ type ResultDeliveryState = Pick<SubagentState, "currentSessionId" | "completionOwnerId">;
6
+
7
+ export interface ResultDeliveryOwnership {
8
+ owns(sessionId: string, completionOwnerId: unknown): boolean;
9
+ claimedSessionIds(): readonly string[];
10
+ claimPredecessor(previousSessionFile: string | undefined, previousRuntimeSessionId: string | null): boolean;
11
+ clear(): void;
12
+ }
13
+
14
+ export function createResultDeliveryOwnership(state: ResultDeliveryState): ResultDeliveryOwnership {
15
+ const claimed = new Map<string, string>();
16
+
17
+ const currentOwner = (): string | undefined => typeof state.completionOwnerId === "string" && state.completionOwnerId
18
+ ? state.completionOwnerId
19
+ : undefined;
20
+
21
+ return {
22
+ owns(sessionId, completionOwnerId) {
23
+ const owner = currentOwner();
24
+ if (!owner || completionOwnerId !== owner) return false;
25
+ return sessionId === state.currentSessionId || claimed.get(sessionId) === owner;
26
+ },
27
+ claimedSessionIds() {
28
+ const owner = currentOwner();
29
+ if (!owner) return [];
30
+ return [...claimed].flatMap(([sessionId, claimedOwner]) => claimedOwner === owner ? [sessionId] : []);
31
+ },
32
+ claimPredecessor(previousSessionFile, previousRuntimeSessionId) {
33
+ const owner = currentOwner();
34
+ if (!owner || !previousSessionFile || !previousRuntimeSessionId) return false;
35
+ if (previousSessionFile !== previousRuntimeSessionId || state.currentSessionId !== previousRuntimeSessionId) return false;
36
+ claimed.delete(previousRuntimeSessionId);
37
+ claimed.set(previousRuntimeSessionId, owner);
38
+ while (claimed.size > MAX_CLAIMED_PREDECESSOR_SESSIONS) claimed.delete(claimed.keys().next().value!);
39
+ return true;
40
+ },
41
+ clear() {
42
+ claimed.clear();
43
+ },
44
+ };
45
+ }
@@ -40,6 +40,11 @@ function nonEmptyString(value: unknown): string | undefined {
40
40
  return typeof value === "string" && value.length > 0 ? value : undefined;
41
41
  }
42
42
 
43
+ /** A legacy alias can be valid metadata while still being unaddressable on the current filesystem. */
44
+ function isUnaddressableResultCandidate(error: unknown): boolean {
45
+ return (error as NodeJS.ErrnoException)?.code === "ENAMETOOLONG";
46
+ }
47
+
43
48
  export function resultFileName(runId: string): string {
44
49
  return `${runId}${JSON_EXTENSION}`;
45
50
  }
@@ -227,7 +232,7 @@ function existingResultFile(resultPath: string): boolean {
227
232
  try {
228
233
  return fs.statSync(resultPath).isFile();
229
234
  } catch (error) {
230
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to inspect async result payload '${resultPath}':`, error);
235
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Failed to inspect async result payload '${resultPath}':`, error);
231
236
  return false;
232
237
  }
233
238
  }
@@ -241,7 +246,7 @@ function pendingResultPayloadMatches(filePath: string, sessionId: string, runId:
241
246
  const data = JSON.parse(fs.readFileSync(filePath, "utf-8")) as Record<string, unknown>;
242
247
  return (nonEmptyString(data.runId) ?? nonEmptyString(data.id)) === runId && nonEmptyString(data.sessionId) === sessionId;
243
248
  } catch (error) {
244
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Ignoring invalid pending async result '${filePath}':`, error);
249
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid pending async result '${filePath}':`, error);
245
250
  return false;
246
251
  }
247
252
  }
@@ -263,11 +268,11 @@ export function promotePendingResultFile(resultsDir: string, sessionId: string,
263
268
  return existingResultFile(resultPath) ? "promoted" : "pending";
264
269
  } catch (error) {
265
270
  const code = (error as NodeJS.ErrnoException).code;
266
- if (code === "ENOENT" || code === "EEXIST" || code === "EPERM" || code === "EACCES") {
271
+ if (code === "ENOENT" || code === "EEXIST" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) {
267
272
  const pendingExists = existingResultFile(pendingPath);
268
273
  const resultExists = existingResultFile(resultPath);
269
274
  if (pendingExists) {
270
- if (!resultExists && options.logFailure !== false) console.error(`Failed to promote pending async result '${pendingPath}' to '${resultPath}':`, error);
275
+ if (!resultExists && options.logFailure !== false && !isUnaddressableResultCandidate(error)) console.error(`Failed to promote pending async result '${pendingPath}' to '${resultPath}':`, error);
271
276
  return "pending";
272
277
  }
273
278
  if (resultExists) return "promoted";
@@ -318,7 +323,7 @@ function readResultIndexForSessionRun(resultsDir: string, sessionId: string, run
318
323
  } catch (error) {
319
324
  const code = (error as NodeJS.ErrnoException).code;
320
325
  if (code === "EPERM" || code === "EACCES") throw error;
321
- if (code !== "ENOENT" && code !== "ENOTDIR") {
326
+ if (code !== "ENOENT" && code !== "ENOTDIR" && !isUnaddressableResultCandidate(error)) {
322
327
  console.error(`Ignoring invalid async result index for '${runId}':`, error);
323
328
  }
324
329
  }
@@ -338,7 +343,8 @@ export function resultPayloadPathForMissionObserverRun(resultsDir: string, runId
338
343
  if (!entry || entry.runId !== runId) return undefined;
339
344
  return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
340
345
  } catch (error) {
341
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Ignoring invalid async result observer index for '${runId}':`, error);
346
+ const code = (error as NodeJS.ErrnoException).code;
347
+ if (code !== "ENOENT" && code !== "ENOTDIR" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid async result observer index for '${runId}':`, error);
342
348
  return undefined;
343
349
  }
344
350
  }
@@ -356,9 +362,12 @@ export function resultPayloadPathForIndexedRun(resultsDir: string, runId: string
356
362
  fs.rmSync(entryPath, { force: true });
357
363
  } catch (error) {
358
364
  const code = (error as NodeJS.ErrnoException).code;
365
+ if (isUnaddressableResultCandidate(error)) return undefined;
359
366
  if (code !== "ENOENT" && code !== "ENOTDIR") {
360
367
  console.error(`Ignoring invalid async result run index '${entryPath}':`, error);
361
- try { fs.rmSync(entryPath, { force: true }); } catch {}
368
+ try { fs.rmSync(entryPath, { force: true }); } catch {
369
+ // Invalid optional run-index cleanup is best-effort.
370
+ }
362
371
  }
363
372
  }
364
373
  return undefined;
@@ -378,7 +387,7 @@ function listIndexFiles(dir: string): string[] {
378
387
  .map((entry) => path.join(dir, entry.name));
379
388
  } catch (error) {
380
389
  const code = (error as NodeJS.ErrnoException).code;
381
- if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES") return [];
390
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return [];
382
391
  throw error;
383
392
  }
384
393
  return files;
@@ -396,7 +405,7 @@ function resultFilesFromIndexDir(resultsDir: string, dir: string, includePending
396
405
  const resultFile = indexedResultFile(resultsDir, entry, includePending);
397
406
  if (resultFile) candidates.add(resultFile);
398
407
  } catch (error) {
399
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Ignoring invalid async result index '${entryPath}':`, error);
408
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid async result index '${entryPath}':`, error);
400
409
  }
401
410
  }
402
411
  return [...candidates];
@@ -418,7 +427,7 @@ function pendingResultFilesForSession(resultsDir: string, sessionId: string): st
418
427
  entries = fs.readdirSync(dir, { withFileTypes: true });
419
428
  } catch (error) {
420
429
  const code = (error as NodeJS.ErrnoException).code;
421
- if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES") continue;
430
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) continue;
422
431
  throw error;
423
432
  }
424
433
  for (const entry of entries) {
@@ -429,7 +438,7 @@ function pendingResultFilesForSession(resultsDir: string, sessionId: string): st
429
438
  const runId = nonEmptyString(data.runId) ?? nonEmptyString(data.id);
430
439
  if (runId && nonEmptyString(data.sessionId) === sessionId) files.add(resultFileName(runId));
431
440
  } catch (error) {
432
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Ignoring invalid pending async result '${pendingPath}':`, error);
441
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid pending async result '${pendingPath}':`, error);
433
442
  }
434
443
  }
435
444
  }
@@ -471,14 +480,16 @@ export function cleanupResultIndexes(resultsDir: string, now = Date.now(), maxAg
471
480
  entries = fs.readdirSync(dir, { withFileTypes: true });
472
481
  } catch (error) {
473
482
  const code = (error as NodeJS.ErrnoException).code;
474
- if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES") return;
483
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return;
475
484
  throw error;
476
485
  }
477
486
  for (const entry of entries) {
478
487
  const fullPath = path.join(dir, entry.name);
479
488
  if (entry.isDirectory()) {
480
489
  visit(fullPath);
481
- try { fs.rmdirSync(fullPath); } catch {}
490
+ try { fs.rmdirSync(fullPath); } catch {
491
+ // Non-empty or concurrently removed index directories are left in place.
492
+ }
482
493
  continue;
483
494
  }
484
495
  if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
@@ -492,11 +503,14 @@ export function cleanupResultIndexes(resultsDir: string, now = Date.now(), maxAg
492
503
  removed += 1;
493
504
  }
494
505
  } catch (error) {
506
+ if (isUnaddressableResultCandidate(error)) continue;
495
507
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Ignoring invalid async result index '${fullPath}':`, error);
496
508
  try {
497
509
  fs.rmSync(fullPath, { force: true });
498
510
  removed += 1;
499
- } catch {}
511
+ } catch {
512
+ // Invalid optional index cleanup is best-effort.
513
+ }
500
514
  }
501
515
  }
502
516
  };
@@ -25,6 +25,7 @@ import { recordWaitCompletion } from "./wait-completions.ts";
25
25
  import { MISSION_BINDING_FILE, syncMissionFromAsyncCompletion } from "../../missions/lifecycle.ts";
26
26
  import { missionObserverResultCandidateFiles, promotePendingResultFile, removeMissionObserverIndex, removeResultIndex, resultCandidateFilesForSession, resultPayloadPathForIndexedRun, resultPayloadPathForMissionObserverRun, resultPayloadPathForSessionRun, writeAsyncResultFile, writeResultIndexForData } from "./result-files.ts";
27
27
  import type { CompletionNotifier, CompletionNotification } from "./notify.ts";
28
+ import type { ResultDeliveryOwnership } from "./result-delivery-ownership.ts";
28
29
 
29
30
  const WATCHER_RESTART_DELAY_MS = 3000;
30
31
  const POLL_INTERVAL_MS = 3000;
@@ -60,10 +61,13 @@ type ResultWatcherDeps = {
60
61
  /** Control how slow result-index scans are logged. Defaults to \"activity\". */
61
62
  resultScanLogging?: "all" | "activity" | "off";
62
63
  platform?: NodeJS.Platform;
64
+ /** Shared current/predecessor session ownership used by the notifier. */
65
+ ownership?: Pick<ResultDeliveryOwnership, "owns" | "claimedSessionIds">;
63
66
  };
64
67
 
65
68
  type ResultFileChild = {
66
69
  agent?: string;
70
+ sessionName?: string;
67
71
  output?: string;
68
72
  structuredOutput?: unknown;
69
73
  outputState?: SubagentOutputState;
@@ -148,6 +152,10 @@ function isNotFound(error: unknown): boolean {
148
152
  return errorCode(error) === "ENOENT";
149
153
  }
150
154
 
155
+ function isAbsentResultCandidate(error: unknown): boolean {
156
+ return isNotFound(error) || errorCode(error) === "ENAMETOOLONG";
157
+ }
158
+
151
159
  function isAccessDenied(error: unknown): boolean {
152
160
  const code = errorCode(error);
153
161
  return code === "EPERM" || code === "EACCES";
@@ -196,6 +204,7 @@ export function createResultWatcher(
196
204
  deps: ResultWatcherDeps = {},
197
205
  ): {
198
206
  startResultWatcher: () => void;
207
+ transitionResultDelivery: () => void;
199
208
  primeExistingResults: (options?: { triggerTurn?: boolean }) => void;
200
209
  refreshResultDelivery: () => void;
201
210
  stopResultWatcher: () => void;
@@ -214,14 +223,16 @@ export function createResultWatcher(
214
223
  // The sole in-memory ownership lease. It is acquired for one active session
215
224
  // and revoked before the watcher, queues, or callbacks are torn down.
216
225
  let activeSessionId: string | null = null;
226
+ const ownsResult = deps.ownership?.owns
227
+ ?? ((sessionId: string, completionOwnerId: unknown) => sessionId === state.currentSessionId
228
+ && typeof completionOwnerId === "string"
229
+ && completionOwnerId === state.completionOwnerId);
230
+ const claimedSessionIds = () => deps.ownership?.claimedSessionIds() ?? [];
217
231
 
218
232
  const ownsCompletion = (sessionId: string, completionOwnerId: unknown, epoch: number) => {
219
233
  if (!deliveryActive || epoch !== deliveryEpoch) return false;
220
234
  if (!activeSessionId && state.currentSessionId) activeSessionId = state.currentSessionId;
221
- return activeSessionId === sessionId
222
- && state.currentSessionId === sessionId
223
- && typeof completionOwnerId === "string"
224
- && completionOwnerId === state.completionOwnerId;
235
+ return activeSessionId === state.currentSessionId && ownsResult(sessionId, completionOwnerId);
225
236
  };
226
237
 
227
238
  const scheduleResult = (file: string, triggerTurn: boolean, delayMs = 0) => {
@@ -235,15 +246,18 @@ export function createResultWatcher(
235
246
  try {
236
247
  return fsApi.statSync(publicResultPath(file)).isFile();
237
248
  } catch (error) {
238
- if (!isNotFound(error)) console.error(`Failed to inspect subagent result file '${publicResultPath(file)}':`, error);
249
+ if (!isAbsentResultCandidate(error)) console.error(`Failed to inspect subagent result file '${publicResultPath(file)}':`, error);
239
250
  return false;
240
251
  }
241
252
  };
242
253
  const resultPayloadPath = (file: string, observed?: ReadonlySet<string>): string | undefined => {
243
254
  if (file !== path.basename(file) || !file.endsWith(".json")) return undefined;
244
255
  const runId = file.replace(/\.json$/i, "");
245
- const sessionResult = state.currentSessionId ? resultPayloadPathForSessionRun(resultsDir, state.currentSessionId, runId) : undefined;
246
- if (sessionResult) return sessionResult;
256
+ for (const sessionId of [state.currentSessionId, ...claimedSessionIds()]) {
257
+ if (!sessionId) continue;
258
+ const sessionResult = resultPayloadPathForSessionRun(resultsDir, sessionId, runId);
259
+ if (sessionResult) return sessionResult;
260
+ }
247
261
  const observerResult = resultPayloadPathForMissionObserverRun(resultsDir, runId);
248
262
  if (observerResult) return observerResult;
249
263
  if (observed?.has(runId)) {
@@ -265,7 +279,7 @@ export function createResultWatcher(
265
279
  } catch (error) {
266
280
  identityCache.delete(file);
267
281
  if (isAccessDenied(error)) throw error;
268
- if (!isNotFound(error)) console.error(`Failed to inspect subagent result file '${resultPath}':`, error);
282
+ if (!isAbsentResultCandidate(error)) console.error(`Failed to inspect subagent result file '${resultPath}':`, error);
269
283
  return undefined;
270
284
  }
271
285
  };
@@ -283,7 +297,7 @@ export function createResultWatcher(
283
297
  } catch (error) {
284
298
  identityCache.delete(file);
285
299
  if (isAccessDenied(error)) throw error;
286
- if (!isNotFound(error)) console.error(`Failed to inspect subagent result file '${resultPath}':`, error);
300
+ if (!isAbsentResultCandidate(error)) console.error(`Failed to inspect subagent result file '${resultPath}':`, error);
287
301
  return undefined;
288
302
  }
289
303
  };
@@ -304,7 +318,7 @@ export function createResultWatcher(
304
318
  // Missing identity stays on the normal parser path so malformed or legacy
305
319
  // files keep their existing diagnostics and compatibility behavior.
306
320
  if (!identity.sessionId) return true;
307
- if (identity.sessionId === state.currentSessionId && identity.completionOwnerId === state.completionOwnerId) return true;
321
+ if (ownsResult(identity.sessionId, identity.completionOwnerId)) return true;
308
322
  if (identity.asyncDir && fsApi.existsSync(path.join(identity.asyncDir, MISSION_BINDING_FILE))) return true;
309
323
  if (identity.runId && (observed ?? observedRunIds()).has(identity.runId)) return true;
310
324
  return Boolean(deps.observeCompletion && !deps.observedCompletionRunIds);
@@ -317,7 +331,7 @@ export function createResultWatcher(
317
331
  removeResultIndex(resultsDir, sessionId, runId, toolCallId);
318
332
  return true;
319
333
  } catch (error) {
320
- if (!isNotFound(error)) {
334
+ if (!isAbsentResultCandidate(error)) {
321
335
  console.error(`Failed to remove delivered subagent result '${publicResultPath(file)}'; will retry:`, error);
322
336
  return false;
323
337
  }
@@ -384,7 +398,7 @@ export function createResultWatcher(
384
398
  if (!resultPayloadWasReplaced(data, readPublicResultIdentity())) return false;
385
399
  } catch (error) {
386
400
  if (isAccessDenied(error)) throw error;
387
- if (isNotFound(error)) return false;
401
+ if (isAbsentResultCandidate(error)) return false;
388
402
  console.error(`Failed to re-read subagent result file '${publicResultPath(file)}':`, error);
389
403
  }
390
404
  identityCache.delete(file);
@@ -412,7 +426,7 @@ export function createResultWatcher(
412
426
  if (observerSucceeded) removeMissionObserverIndex(resultsDir, runId);
413
427
  const epoch = deliveryEpoch;
414
428
  if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
415
- // Recorded before dedupe and before the unlink below so subagent_wait can
429
+ // Recorded before dedupe and before the unlink below so bg_wait can
416
430
  // use the in-memory record or its bounded durable replay after cleanup.
417
431
  recordWaitCompletion(state, runId, data, Date.now(), completionTtlMs, {
418
432
  resultsDir,
@@ -469,6 +483,7 @@ export function createResultWatcher(
469
483
  : undefined;
470
484
  return {
471
485
  agent: result.agent ?? data.agent ?? `step-${index + 1}`,
486
+ ...(result.sessionName ? { sessionName: result.sessionName } : {}),
472
487
  status: resolveSubagentResultStatus({
473
488
  success: result.success,
474
489
  state: childState,
@@ -617,8 +632,9 @@ export function createResultWatcher(
617
632
  };
618
633
  const indexedResultCandidates = (observed: ReadonlySet<string>): string[] => {
619
634
  const files = new Set<string>();
620
- if (state.currentSessionId) {
621
- for (const file of resultCandidateFilesForSession(resultsDir, state.currentSessionId)) files.add(file);
635
+ for (const sessionId of [state.currentSessionId, ...claimedSessionIds()]) {
636
+ if (!sessionId) continue;
637
+ for (const file of resultCandidateFilesForSession(resultsDir, sessionId)) files.add(file);
622
638
  }
623
639
  for (const runId of state.asyncJobs.keys()) files.add(`${runId}.json`);
624
640
  for (const file of missionObserverResultCandidateFiles(resultsDir)) files.add(file);
@@ -751,6 +767,13 @@ export function createResultWatcher(
751
767
  }
752
768
  };
753
769
 
770
+ const transitionResultDelivery = () => {
771
+ deliveryActive = true;
772
+ activeSessionId = state.currentSessionId;
773
+ deliveryEpoch += 1;
774
+ identityCache.clear();
775
+ };
776
+
754
777
  const stopResultWatcher = () => {
755
778
  deliveryActive = false;
756
779
  activeSessionId = null;
@@ -765,5 +788,5 @@ export function createResultWatcher(
765
788
  identityCache.clear();
766
789
  };
767
790
 
768
- return { startResultWatcher, primeExistingResults, stopResultWatcher, refreshResultDelivery: () => { primeExistingResults(); startDemandPolling(); } };
791
+ return { startResultWatcher, transitionResultDelivery, primeExistingResults, stopResultWatcher, refreshResultDelivery: () => { primeExistingResults(); startDemandPolling(); } };
769
792
  }
@@ -12,7 +12,7 @@ function isIntercomDetached(run: AsyncRunSummary): boolean {
12
12
 
13
13
  function formatIntercomDetachGuidance(run: AsyncRunSummary): string | undefined {
14
14
  if (!isIntercomDetached(run)) return undefined;
15
- return `Run "${run.id}" detached for intercom coordination. Reply to the supervisor request first, then wait with subagent_wait({ id: "${run.id}" }). Use subagent({ action: "status", id: "${run.id}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
15
+ return `Run "${run.id}" detached for intercom coordination. Reply to the supervisor request first, then wait with bg_wait({ id: "${run.id}" }). Use subagent({ action: "status", id: "${run.id}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
16
16
  }
17
17
 
18
18
  export function formatAsyncReviveCommand(run: AsyncRunSummary): string | undefined {
@@ -39,7 +39,7 @@ export function formatResumeFirstFailedRunDetail(run: AsyncRunSummary): string |
39
39
  }
40
40
 
41
41
  export function formatResumeFirstFailedRunsNote(runs: AsyncRunSummary[]): string {
42
- const failedRuns = runs.filter((run) => run.state === "failed");
42
+ const failedRuns = runs.filter((run) => run.state === "failed" || run.state === "partial");
43
43
  const detachGuidance = failedRuns
44
44
  .map(formatIntercomDetachGuidance)
45
45
  .filter((guidance): guidance is string => Boolean(guidance));
@@ -27,7 +27,7 @@ export interface RetainedChild {
27
27
  }
28
28
 
29
29
  function isRetainedChildState(state: AsyncRunSummary["state"]): state is RetainedChildState {
30
- return state === "complete" || state === "failed" || state === "paused" || state === "stopped";
30
+ return state === "complete" || state === "failed" || state === "partial" || state === "paused" || state === "stopped";
31
31
  }
32
32
 
33
33
  function isTerminalStepStatus(status: AsyncRunSummary["steps"][number]["status"]): boolean {