@xzzpig/pi-subagents 0.14.0 → 0.15.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 (198) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +6 -5
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +56 -15
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -19
  9. package/docs/missions.md +10 -2
  10. package/docs/models.md +11 -22
  11. package/docs/observability.md +63 -11
  12. package/docs/standalone-background.md +59 -0
  13. package/docs/tool-reference.md +42 -23
  14. package/docs/watchdog.md +39 -10
  15. package/docs/workflows.md +58 -19
  16. package/index.ts +5 -2
  17. package/inspector-runner.mjs +2 -2
  18. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  20. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  21. package/package.json +9 -4
  22. package/prompts/parallel-review.md +1 -1
  23. package/runner-peer-loader.mjs +24 -0
  24. package/runner-peer-preload.mjs +36 -0
  25. package/skills/pi-subagents/SKILL.md +34 -22
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  27. package/skills/pi-subagents/references/execution-controls.md +27 -8
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  31. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  32. package/src/agents/advertised-agent-prompt.ts +94 -0
  33. package/src/agents/agent-management.ts +71 -59
  34. package/src/agents/agent-serializer.ts +6 -3
  35. package/src/agents/agents.ts +198 -72
  36. package/src/agents/builtin-names.ts +1 -0
  37. package/src/agents/chain-serializer.ts +5 -0
  38. package/src/agents/runtime-agent-registry.ts +7 -6
  39. package/src/api/delegation.ts +4 -0
  40. package/src/api/preflight.ts +110 -71
  41. package/src/api/required-child-extensions.ts +6 -0
  42. package/src/api/shared-types.ts +3 -1
  43. package/src/api/workflow-resources.ts +6 -0
  44. package/src/extension/config.ts +14 -37
  45. package/src/extension/fanout-child.ts +68 -5
  46. package/src/extension/herdr-pi-bridge.ts +164 -0
  47. package/src/extension/index.ts +141 -51
  48. package/src/extension/public-execution.ts +7 -6
  49. package/src/extension/rpc.ts +8 -21
  50. package/src/extension/schemas.ts +86 -84
  51. package/src/extension/tool-description.ts +32 -79
  52. package/src/inspectors/actions.ts +148 -0
  53. package/src/inspectors/ghostty/actions.ts +74 -0
  54. package/src/inspectors/ghostty/plugin.ts +17 -0
  55. package/src/inspectors/herdr/actions.ts +99 -179
  56. package/src/inspectors/herdr/plugin.ts +20 -0
  57. package/src/inspectors/herdr/project-panes.ts +4 -1
  58. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  59. package/src/inspectors/plugins.ts +8 -0
  60. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  61. package/src/inspectors/types.ts +51 -0
  62. package/src/integrations/pi-web-session-liveness.ts +73 -0
  63. package/src/intercom/intercom-bridge.ts +50 -8
  64. package/src/intercom/native-supervisor-channel.ts +142 -115
  65. package/src/intercom/supervisor-ui.ts +3 -2
  66. package/src/missions/workflow-state.ts +37 -16
  67. package/src/policy/authority.ts +4 -0
  68. package/src/profiles/profiles.ts +12 -6
  69. package/src/runs/background/active-async-capacity.ts +22 -18
  70. package/src/runs/background/active-run-index.ts +17 -1
  71. package/src/runs/background/async-execution.ts +359 -176
  72. package/src/runs/background/async-job-tracker.ts +41 -7
  73. package/src/runs/background/async-resume.ts +19 -12
  74. package/src/runs/background/async-retention.ts +20 -0
  75. package/src/runs/background/async-status-snapshot.ts +10 -12
  76. package/src/runs/background/async-status.ts +32 -13
  77. package/src/runs/background/auto-drain.ts +59 -35
  78. package/src/runs/background/binary-bootstrap.ts +38 -0
  79. package/src/runs/background/chain-append.ts +1 -1
  80. package/src/runs/background/chain-root-attachment.ts +22 -33
  81. package/src/runs/background/control-channel.ts +78 -44
  82. package/src/runs/background/fleet-view.ts +30 -2
  83. package/src/runs/background/notify.ts +193 -19
  84. package/src/runs/background/owned-process-tree.ts +35 -8
  85. package/src/runs/background/process-terminal.ts +23 -23
  86. package/src/runs/background/result-files.ts +8 -4
  87. package/src/runs/background/result-watcher.ts +19 -2
  88. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  89. package/src/runs/background/run-child-session.ts +118 -41
  90. package/src/runs/background/run-status.ts +78 -5
  91. package/src/runs/background/runner-aliases.ts +22 -5
  92. package/src/runs/background/runner-child-launch.ts +93 -0
  93. package/src/runs/background/runner-child-sessions.ts +5 -4
  94. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  95. package/src/runs/background/scheduled-runs.ts +51 -18
  96. package/src/runs/background/stale-run-reconciler.ts +38 -12
  97. package/src/runs/background/steering.ts +20 -2
  98. package/src/runs/background/subagent-runner.ts +766 -432
  99. package/src/runs/background/subagent-wait.ts +179 -28
  100. package/src/runs/background/wait-completions.ts +79 -27
  101. package/src/runs/background/wait-subscriptions.ts +9 -3
  102. package/src/runs/background/wait-tool.ts +5 -3
  103. package/src/runs/foreground/async-steering-action.ts +37 -7
  104. package/src/runs/foreground/async-stop-action.ts +93 -3
  105. package/src/runs/foreground/execution.ts +174 -194
  106. package/src/runs/foreground/foreground-history.ts +5 -2
  107. package/src/runs/foreground/prompt-audit.ts +12 -6
  108. package/src/runs/foreground/subagent-executor.ts +896 -397
  109. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  110. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  111. package/src/runs/shared/acceptance.ts +54 -14
  112. package/src/runs/shared/agent-contract.ts +1 -1
  113. package/src/runs/shared/async-status-projection.ts +172 -78
  114. package/src/runs/shared/capability-ceiling.ts +2 -0
  115. package/src/runs/shared/child-hooks.ts +167 -3
  116. package/src/runs/shared/child-launch-plan.ts +15 -3
  117. package/src/runs/shared/child-launch.ts +44 -16
  118. package/src/runs/shared/child-lifecycle.ts +6 -3
  119. package/src/runs/shared/child-runtime-config.ts +8 -1
  120. package/src/runs/shared/child-session.ts +130 -24
  121. package/src/runs/shared/child-tool-plan.ts +145 -14
  122. package/src/runs/shared/completion-evidence.ts +2 -2
  123. package/src/runs/shared/completion-guard.ts +6 -3
  124. package/src/runs/shared/dynamic-fanout.ts +2 -2
  125. package/src/runs/shared/effective-system-prompt.ts +33 -0
  126. package/src/runs/shared/external-cli-contract.ts +11 -1
  127. package/src/runs/shared/external-cli-preflight.ts +6 -2
  128. package/src/runs/shared/external-cli-runner.ts +9 -7
  129. package/src/runs/shared/herdr-connection.ts +134 -0
  130. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  131. package/src/runs/shared/herdr-machine.ts +279 -0
  132. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  133. package/src/runs/shared/herdr-placed-run.ts +263 -0
  134. package/src/runs/shared/host-step-status.ts +11 -11
  135. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  136. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  137. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  138. package/src/runs/shared/model-scope.ts +1 -1
  139. package/src/runs/shared/nested-events.ts +19 -10
  140. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  141. package/src/runs/shared/parallel-handoff.ts +57 -12
  142. package/src/runs/shared/parallel-utils.ts +10 -4
  143. package/src/runs/shared/pi-spawn.ts +10 -0
  144. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  145. package/src/runs/shared/run-fanout-budget.ts +8 -8
  146. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  147. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  148. package/src/runs/shared/task-intent.ts +46 -13
  149. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  150. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  151. package/src/runs/shared/worktree-setup-command.ts +213 -0
  152. package/src/runs/shared/worktree.ts +437 -214
  153. package/src/shared/child-cache-retention.ts +43 -0
  154. package/src/shared/fork-context.ts +15 -72
  155. package/src/shared/launch-contract.ts +70 -8
  156. package/src/shared/model-response-aliases.ts +13 -0
  157. package/src/shared/opencode-session-headers.ts +30 -0
  158. package/src/shared/pruned-fork.ts +1 -1
  159. package/src/shared/required-child-extensions.ts +81 -0
  160. package/src/shared/settings.ts +5 -2
  161. package/src/shared/shortcuts.ts +0 -4
  162. package/src/shared/types.ts +163 -90
  163. package/src/shared/utils.ts +10 -2
  164. package/src/shared/watch-strategy.ts +2 -0
  165. package/src/shared/workflow-child-permit.ts +18 -13
  166. package/src/slash/delegation-adapters.ts +3 -1
  167. package/src/slash/delegation-request.ts +14 -0
  168. package/src/slash/slash-commands.ts +2 -7
  169. package/src/slash/subagents-admin.ts +31 -14
  170. package/src/tui/fleet-status.ts +165 -20
  171. package/src/tui/fleet.ts +30 -19
  172. package/src/tui/render.ts +210 -50
  173. package/src/watchdog/child-status.ts +28 -28
  174. package/src/watchdog/lsp-diagnostics.ts +1 -1
  175. package/src/watchdog/model-selection.ts +21 -1
  176. package/src/watchdog/permission-arbiter.ts +5 -2
  177. package/src/watchdog/register-child.ts +10 -2
  178. package/src/watchdog/register-main.ts +39 -35
  179. package/src/watchdog/render.ts +1 -1
  180. package/src/watchdog/review.ts +122 -74
  181. package/src/watchdog/rules.ts +1 -1
  182. package/src/watchdog/runtime.ts +100 -27
  183. package/src/watchdog/scope.ts +1 -1
  184. package/src/watchdog/settings.ts +3 -0
  185. package/src/watchdog/tool-actions.ts +13 -12
  186. package/src/watchdog/turn-delta.ts +23 -0
  187. package/src/watchdog/types.ts +5 -3
  188. package/src/watchdog/warning-format.ts +1 -1
  189. package/src/workflows/chat-progress.ts +3 -3
  190. package/src/workflows/scripted-workflow.ts +349 -26
  191. package/src/workflows/workflow-checklist.ts +17 -20
  192. package/src/workflows/workflow-child-summary.ts +57 -8
  193. package/src/workflows/workflow-preflight.ts +19 -19
  194. package/src/workflows/workflow-receipt.ts +24 -6
  195. package/src/workflows/workflow-resources.ts +108 -22
  196. package/src/workflows/workflow-settlement.ts +3 -0
  197. package/src/runs/shared/model-exclusions.ts +0 -373
  198. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -26,6 +26,7 @@ import { EXTERNAL_JOB_BRIDGE_REQUEST_DIR, serviceExternalJobBridgeRequests } fro
26
26
  import { shouldUseNativeFsWatch } from "../../shared/watch-strategy.ts";
27
27
  import { parseWorkflowChildSummary } from "../../workflows/workflow-child-summary.ts";
28
28
  import { validHostStepNodes } from "../shared/host-step-status.ts";
29
+ import { readProcessTerminal } from "./process-terminal.ts";
29
30
  import { withCachedUiContext } from "../../shared/extension-context.ts";
30
31
 
31
32
  interface AsyncJobTrackerOptions {
@@ -51,11 +52,14 @@ const DEFAULT_LIVENESS_INTERVAL_MS = 5000;
51
52
  const EVENT_REFRESH_DEBOUNCE_MS = 25;
52
53
  const WATCH_ATTACHMENT_RETRY_MS = 100;
53
54
 
55
+ const isTerminalJobStatus = (status: AsyncJobState["status"]): boolean =>
56
+ status === "complete" || status === "failed" || status === "partial" || status === "paused" || status === "rejected" || status === "stopped";
57
+
54
58
  function rememberFleetJob(state: SubagentState, job: AsyncJobState): void {
55
59
  state.fleetJobs ??= new Map();
56
60
  state.fleetJobs.set(job.asyncId, job);
57
61
  const terminal = [...state.fleetJobs.values()]
58
- .filter((candidate) => candidate.status === "complete" || candidate.status === "failed" || candidate.status === "paused" || candidate.status === "stopped")
62
+ .filter((candidate) => isTerminalJobStatus(candidate.status))
59
63
  .sort((left, right) => (right.updatedAt ?? right.startedAt ?? 0) - (left.updatedAt ?? left.startedAt ?? 0));
60
64
  for (const stale of terminal.slice(MAX_RECENT_FLEET_JOBS)) state.fleetJobs.delete(stale.asyncId);
61
65
  }
@@ -78,6 +82,9 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
78
82
  let widgetRerenderTimer: ReturnType<typeof setTimeout> | undefined;
79
83
  const runningJobIds = new Set<string>();
80
84
  const externalJobBridgeRuns = new Set<string>();
85
+ // Early native failure is visible before its publisher finishes. Retain only
86
+ // that scoped observation, using the existing liveness sweep to renew delivery.
87
+ const terminalPublications = new Map<string, { instanceId: string; pending: true } | { pending: false }>();
81
88
  const externalJobBridgeEligibility = (steps: AsyncJobState["steps"]): "required" | "not-required" | "unknown" => {
82
89
  if (!Array.isArray(steps)) return "unknown";
83
90
  for (const step of steps) {
@@ -96,7 +103,6 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
96
103
  let nextWidgetAnimationAt = Date.now() + WIDGET_ANIMATION_INTERVAL_MS;
97
104
  const watch = options.watch ?? fs.watch;
98
105
  const useNativeWatcher = () => shouldUseNativeFsWatch("async-job-tracker", options.platform);
99
- const terminalStatus = (status: string) => status === "complete" || status === "failed" || status === "paused" || status === "stopped";
100
106
  const withLastUiContext = <T>(run: (ctx: ExtensionContext) => T): T | undefined => {
101
107
  const cached = state.lastUiContext;
102
108
  return withCachedUiContext(cached, () => {
@@ -380,6 +386,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
380
386
  refreshTimers.delete(asyncId);
381
387
  runningJobIds.delete(asyncId);
382
388
  externalJobBridgeRuns.delete(asyncId);
389
+ terminalPublications.delete(asyncId);
383
390
  };
384
391
 
385
392
  const refreshJob = (job: AsyncJobState): boolean => {
@@ -440,9 +447,10 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
440
447
  if (status) {
441
448
  const previousStatus = job.status;
442
449
  job.status = status.state;
450
+ if (!isTerminalJobStatus(job.status)) terminalPublications.delete(job.asyncId);
443
451
  if (job.status === "running") runningJobIds.add(job.asyncId);
444
452
  else runningJobIds.delete(job.asyncId);
445
- if (job.status !== "complete" && job.status !== "failed" && job.status !== "paused" && job.status !== "stopped") cancelCleanup(job.asyncId);
453
+ if (!isTerminalJobStatus(job.status)) cancelCleanup(job.asyncId);
446
454
  job.sessionId = status.sessionId ?? job.sessionId;
447
455
  job.activityState = status.activityState;
448
456
  job.lastActivityAt = status.lastActivityAt ?? job.lastActivityAt;
@@ -496,10 +504,31 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
496
504
  job.turnBudgetExceeded = status.turnBudgetExceeded ?? job.turnBudgetExceeded;
497
505
  job.wrapUpRequested = status.wrapUpRequested ?? job.wrapUpRequested;
498
506
  job.sessionFile = status.sessionFile ?? job.sessionFile;
499
- if (terminalStatus(job.status)) {
500
- if (!terminalStatus(previousStatus)) options.onJobTerminal?.();
507
+ if (isTerminalJobStatus(job.status)) {
508
+ let publication = terminalPublications.get(job.asyncId);
509
+ if (!publication && status.mode !== "workflow" && status.processTerminal?.state === "pending"
510
+ && status.runId === job.asyncId && status.sessionId === state.currentSessionId
511
+ && status.completionOwnerId && status.completionOwnerId === state.completionOwnerId) {
512
+ publication = { instanceId: status.processTerminal.runnerProcessInstanceId, pending: true };
513
+ terminalPublications.set(job.asyncId, publication);
514
+ }
515
+ const wasPending = publication?.pending;
516
+ if (publication?.pending) {
517
+ // Reconciliation resolves pending as well as public payloads. The
518
+ // watcher already discovers exact tracked run IDs without promotion.
519
+ const published = reconciliation.resultPath && fs.existsSync(reconciliation.resultPath);
520
+ const closed = !published && readProcessTerminal(job.asyncDir, {
521
+ runId: job.asyncId, runnerProcessInstanceId: publication.instanceId,
522
+ })?.state === "observed";
523
+ if (published || closed) {
524
+ publication = { pending: false };
525
+ terminalPublications.set(job.asyncId, publication);
526
+ } else cancelCleanup(job.asyncId);
527
+ }
528
+ // Scan on close too: publication may have raced the payload check.
529
+ if (!isTerminalJobStatus(previousStatus) || (wasPending && !publication?.pending)) options.onJobTerminal?.();
501
530
  rememberFleetJob(state, job);
502
- if (!nestedRefreshFailed && !hasLiveNestedDescendants(job.nestedChildren) && (previousStatus !== job.status || !state.cleanupTimers.has(job.asyncId))) {
531
+ if (!publication?.pending && !nestedRefreshFailed && !hasLiveNestedDescendants(job.nestedChildren) && (previousStatus !== job.status || !state.cleanupTimers.has(job.asyncId))) {
503
532
  scheduleCleanup(job.asyncId);
504
533
  }
505
534
  }
@@ -526,7 +555,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
526
555
  }
527
556
  runningJobIds.delete(job.asyncId);
528
557
  rememberFleetJob(state, job);
529
- if (!hasLiveNestedDescendants(job.nestedChildren) && !state.cleanupTimers.has(job.asyncId)) scheduleCleanup(job.asyncId);
558
+ if (!terminalPublications.get(job.asyncId)?.pending && !hasLiveNestedDescendants(job.nestedChildren) && !state.cleanupTimers.has(job.asyncId)) scheduleCleanup(job.asyncId);
530
559
  }
531
560
  return widgetRenderKey(job, widgetExpanded) !== widgetStateBefore;
532
561
  };
@@ -668,6 +697,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
668
697
  const sessionRoot = state.liveAsyncSessionRoots?.get(info.id);
669
698
  state.liveAsyncSessionRoots?.delete(info.id);
670
699
  externalJobBridgeRuns.delete(info.id);
700
+ terminalPublications.delete(info.id);
671
701
  state.asyncJobs.set(info.id, {
672
702
  asyncId: info.id,
673
703
  asyncDir,
@@ -721,6 +751,9 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
721
751
  job.asyncDir = result.asyncDir;
722
752
  watchJob(job);
723
753
  }
754
+ // Delivery can precede the first terminal status refresh. Remember its
755
+ // settlement even when no pending publication has been observed yet.
756
+ terminalPublications.set(asyncId, { pending: false });
724
757
  try {
725
758
  updateAsyncJobNestedProjection(job);
726
759
  } catch (error) {
@@ -745,6 +778,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
745
778
  widgetRerenderTimer = undefined;
746
779
  runningJobIds.clear();
747
780
  externalJobBridgeRuns.clear();
781
+ terminalPublications.clear();
748
782
  };
749
783
 
750
784
  const resetJobs = (ctx?: ExtensionContext) => {
@@ -3,6 +3,7 @@ import * as path from "node:path";
3
3
  import { DIRS, type AcceptanceInput, type AsyncStatus, type SteeringRecoveryDescriptor, type SubagentRunMode } from "../../shared/types.ts";
4
4
  import type { AgentConfig } from "../../agents/agents.ts";
5
5
  import { normalizeExtensionBindings } from "../shared/extension-bindings.ts";
6
+ import { snapshotRequiredChildExtensions } from "../../shared/required-child-extensions.ts";
6
7
  import { normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
7
8
  import { validateAcceptanceInput } from "../shared/acceptance.ts";
8
9
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
@@ -17,6 +18,8 @@ import { intersectThinkingCeilings, parseThinkingLevel, type ThinkingLevel } fro
17
18
  import { assertWorkflowGraphHostSteps } from "../shared/host-step-status.ts";
18
19
  import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
19
20
  import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
21
+ import { validateIntercomBridgeConfig } from "../../intercom/intercom-bridge.ts";
22
+ import { validateModelResponseAliases } from "../../shared/model-response-aliases.ts";
20
23
 
21
24
  export interface AsyncResumeParams {
22
25
  id?: string;
@@ -333,12 +336,13 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
333
336
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': expected an object.`);
334
337
  const parsed = value as Record<string, unknown>;
335
338
  const allowedFields = new Set([
336
- "version", "launchContractDigest", "sourceRunId", "agentContract", "agent", "sandbox", "permissionProfile", "sessionFile", "cwd", "model", "modelProvider", "modelOverrideFromParent", "modelOrigin", "fallbackModels", "thinking", "thinkingCeiling", "tools", "allowNestedSubagents", "extensions",
339
+ "modelResponseAliases", "version", "launchContractDigest", "sourceRunId", "agentContract", "agent", "sandbox", "permissionProfile", "sessionFile", "cwd", "model", "modelProvider", "modelOverrideFromParent", "modelOrigin", "fast", "thinking", "thinkingCeiling", "tools", "allowNestedSubagents", "extensions",
337
340
  "subagentOnlyExtensions", "mcpDirectTools", "excludeTools", "mutationTools", "systemPrompt", "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills",
338
341
  "skillPath", "agentFilePath", "completionGuard", "memory", "outputPath", "outputMode", "structuredOutputSchema", "acceptance", "sessionDir", "artifactConfig",
339
342
  "artifactsDir", "maxOutput", "controlConfig", "context", "intercomBridge", "absoluteDeadlineAt", "initialTurnBudget", "initialToolBudget", "maxSubagentDepth", "share", "capabilityCeiling",
340
343
  "launchResolvedExtensions", "runFanoutBudget", "lane", "baseRef",
341
344
  "extensionBindings",
345
+ "requiredExtensions",
342
346
  ]);
343
347
  for (const field of Object.keys(parsed)) {
344
348
  if (!allowedFields.has(field)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': unknown field '${field}'.`);
@@ -353,9 +357,14 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
353
357
  } catch (error) {
354
358
  throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${error instanceof Error ? error.message : String(error)}`);
355
359
  }
360
+ validateModelResponseAliases(parsed.modelResponseAliases, `async recovery descriptor '${descriptorPath}' modelResponseAliases`);
356
361
  if (parsed.capabilityCeiling !== undefined) parsed.capabilityCeiling = parseSubagentCapabilityCeiling(parsed.capabilityCeiling, `async recovery descriptor '${descriptorPath}' capabilityCeiling`);
357
362
  if (parsed.thinkingCeiling !== undefined) parsed.thinkingCeiling = parseThinkingLevel(parsed.thinkingCeiling, `async recovery descriptor '${descriptorPath}' thinkingCeiling`);
358
363
  if (parsed.extensionBindings !== undefined) parsed.extensionBindings = normalizeExtensionBindings(parsed.extensionBindings)!.value;
364
+ if (parsed.requiredExtensions !== undefined) {
365
+ try { parsed.requiredExtensions = snapshotRequiredChildExtensions(parsed.requiredExtensions, "requiredExtensions"); }
366
+ catch (error) { throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${error instanceof Error ? error.message : String(error)}`); }
367
+ }
359
368
  if (parsed.lane !== undefined) parsed.lane = normalizeWorkflowLaneMetadata(parsed.lane, `Invalid async recovery descriptor '${descriptorPath}': lane`);
360
369
  if (parsed.agentContract !== undefined) {
361
370
  if (!parsed.agentContract || typeof parsed.agentContract !== "object" || Array.isArray(parsed.agentContract)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': agentContract must be an object.`);
@@ -366,6 +375,7 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
366
375
  if (parsed.outputMode !== "inline" && parsed.outputMode !== "file-only") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': outputMode is invalid.`);
367
376
  if (parsed.context !== undefined && parsed.context !== "fresh" && parsed.context !== "fork") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': context is invalid.`);
368
377
  if (parsed.modelOverrideFromParent !== undefined && typeof parsed.modelOverrideFromParent !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': modelOverrideFromParent must be a boolean.`);
378
+ if (parsed.fast !== undefined && typeof parsed.fast !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': fast must be a boolean.`);
369
379
  if (parsed.modelOrigin !== undefined && parsed.modelOrigin !== "explicit" && parsed.modelOrigin !== "inherited" && parsed.modelOrigin !== "configured") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': modelOrigin must be 'explicit', 'inherited', or 'configured'.`);
370
380
  if (parsed.modelOrigin === undefined && parsed.model !== undefined) parsed.modelOrigin = parsed.modelOverrideFromParent ? "inherited" : "configured";
371
381
  for (const field of ["inheritProjectContext", "inheritSkills", "share"] as const) {
@@ -375,7 +385,7 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
375
385
  else if (typeof parsed.inheritGlobalContext !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': inheritGlobalContext must be a boolean.`);
376
386
  if (parsed.allowNestedSubagents !== undefined && typeof parsed.allowNestedSubagents !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': allowNestedSubagents must be a boolean.`);
377
387
  if (!Number.isInteger(parsed.maxSubagentDepth) || (parsed.maxSubagentDepth as number) < 0) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': maxSubagentDepth must be a non-negative integer.`);
378
- for (const field of ["fallbackModels", "tools", "excludeTools", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "mutationTools", "skills", "skillPath"] as const) {
388
+ for (const field of ["tools", "excludeTools", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "mutationTools", "skills", "skillPath"] as const) {
379
389
  const item = parsed[field];
380
390
  if (item !== undefined && (!Array.isArray(item) || item.some((entry) => typeof entry !== "string" || !entry.trim()))) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${field} must contain non-empty strings.`);
381
391
  }
@@ -427,14 +437,8 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
427
437
  if (!Number.isInteger(artifact.cleanupDays) || (artifact.cleanupDays as number) < 0) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': artifactConfig.cleanupDays must be a non-negative integer.`);
428
438
  }
429
439
  if (parsed.intercomBridge !== undefined) {
430
- if (!parsed.intercomBridge || typeof parsed.intercomBridge !== "object" || Array.isArray(parsed.intercomBridge)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': intercomBridge must be an object.`);
431
- const bridge = parsed.intercomBridge as Record<string, unknown>;
432
- for (const field of Object.keys(bridge)) {
433
- if (field !== "mode" && field !== "instructionFile" && field !== "resultDelivery") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': intercomBridge.${field} is not supported.`);
434
- }
435
- if (bridge.mode !== undefined && bridge.mode !== "off" && bridge.mode !== "fork-only" && bridge.mode !== "always") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': intercomBridge.mode is invalid.`);
436
- if (bridge.instructionFile !== undefined && typeof bridge.instructionFile !== "string") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': intercomBridge.instructionFile must be a string.`);
437
- if (bridge.resultDelivery !== undefined && typeof bridge.resultDelivery !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': intercomBridge.resultDelivery must be a boolean.`);
440
+ const bridge = validateIntercomBridgeConfig({ value: parsed.intercomBridge, label: "intercomBridge" });
441
+ if (!bridge.ok) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${bridge.error}`);
438
442
  }
439
443
  if (parsed.controlConfig !== undefined) {
440
444
  if (!parsed.controlConfig || typeof parsed.controlConfig !== "object" || Array.isArray(parsed.controlConfig)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': controlConfig must be an object.`);
@@ -577,7 +581,11 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
577
581
  const index = requestedIndex ?? 0;
578
582
  if (!Number.isInteger(index)) throw new Error(`Async run '${runId}' index must be an integer.`);
579
583
  if (index < 0 || index >= stepCount) throw new Error(`Async run '${runId}' has ${stepCount} children. Index ${index} is out of range.`);
580
- const agent = statusSteps[index]?.agent ?? resultSteps[index]?.agent ?? result?.agent;
584
+ const selectedStatusStep = statusSteps[index];
585
+ if (selectedStatusStep?.status === "stopped" || selectedStatusStep?.stopped === true) {
586
+ throw new Error(`Async run '${runId}' child ${index} was stopped and cannot be resumed. Start a new run instead.`);
587
+ }
588
+ const agent = selectedStatusStep?.agent ?? resultSteps[index]?.agent ?? result?.agent;
581
589
  if (!agent) throw new Error(`Could not determine child agent for async run '${runId}'.`);
582
590
  if (recoveryDescriptor && recoveryDescriptor.agent !== agent) throw new Error(`Async run '${runId}' has a recovery descriptor for '${recoveryDescriptor.agent}', not '${agent}'.`);
583
591
  const sessionFile = statusSteps[index]?.sessionFile
@@ -624,7 +632,6 @@ export function applySteeringRecoveryAgentConfig(agentConfig: AgentConfig, descr
624
632
  ...agentConfig,
625
633
  model: descriptor.model,
626
634
  modelProvider: descriptor.modelProvider,
627
- fallbackModels: descriptor.fallbackModels ? [...descriptor.fallbackModels] : undefined,
628
635
  thinking: descriptor.thinking,
629
636
  maxThinking: intersectThinkingCeilings(descriptor.thinkingCeiling, agentConfig.maxThinking),
630
637
  tools: descriptor.tools ? [...descriptor.tools] : undefined,
@@ -154,6 +154,8 @@ function readStatus(runDir: string): AsyncStatus | undefined {
154
154
  || !RUN_MODES.has(value.mode as AsyncStatus["mode"])
155
155
  || typeof value.startedAt !== "number"
156
156
  || !Number.isFinite(value.startedAt)) return undefined;
157
+ // SAFETY: readStatus validates every field of the raw JSON record above; the
158
+ // cast only re-narrows the validated record to its domain type.
157
159
  return value as unknown as AsyncStatus;
158
160
  }
159
161
 
@@ -317,10 +319,21 @@ function parseWaitRunIds(dir: string): { runIds: Set<string>; safe: boolean } {
317
319
 
318
320
  function readCursor(root: string): RetentionCursor {
319
321
  const value = readJson(path.join(root, CURSOR_NAME));
322
+ // SAFETY: readCursor checks version === 1 and the cursor shape is the only
323
+ // v1 record this store writes; the cast re-narrows the validated payload.
320
324
  return value?.version === 1 ? value as unknown as RetentionCursor : { version: 1 };
321
325
  }
322
326
 
327
+ let currentProcessStartIdentity: string | undefined | null = null;
328
+
323
329
  function processStartIdentity(pid: number): string | undefined {
330
+ // Foreign PIDs can be reused while this process lives, so resolve them afresh.
331
+ if (pid !== process.pid) return computeProcessStartIdentity(pid);
332
+ if (currentProcessStartIdentity === null) currentProcessStartIdentity = computeProcessStartIdentity(pid);
333
+ return currentProcessStartIdentity;
334
+ }
335
+
336
+ function computeProcessStartIdentity(pid: number): string | undefined {
324
337
  if (process.platform === "linux") {
325
338
  try {
326
339
  const stat = fs.readFileSync(`/proc/${pid}/stat`).toString("utf8");
@@ -363,6 +376,8 @@ function parseLockOwner(lockDir: string): RetentionLockOwner | undefined {
363
376
  || typeof owner.startedAt !== "number"
364
377
  || !Number.isFinite(owner.startedAt)) return undefined;
365
378
  if (owner.processStartIdentity !== undefined && typeof owner.processStartIdentity !== "string") return undefined;
379
+ // SAFETY: parseLockOwner validates every owner field above; the cast only
380
+ // re-narrows the validated JSON record to RetentionLockOwner.
366
381
  return owner as unknown as RetentionLockOwner;
367
382
  }
368
383
 
@@ -465,6 +480,9 @@ function hasUnresolvedResultHandoff(data: Record<string, unknown>): boolean {
465
480
  return typeof manifestPath !== "string" || !manifestPath || unresolvedHandoff(manifestPath);
466
481
  }
467
482
 
483
+ // The completion mode is an opaque JSON leaf read from the result record; callers
484
+ // narrow it with typeof before use.
485
+ // pi-lens-ignore: no-unknown-returns
468
486
  function completionMode(data: Record<string, unknown>): unknown {
469
487
  return data.completion && typeof data.completion === "object" && !Array.isArray(data.completion)
470
488
  ? (data.completion as Record<string, unknown>).mode
@@ -572,6 +590,8 @@ function parseDiscoveryResult(message: unknown, passId: string, runBudget: numbe
572
590
  if (typeof operation.session !== "string" || !validRunId(operation.session) || (operation.type === "set-pending" && (typeof operation.value !== "string" || !safeRelative(operation.value)))) throw new Error("Retention discovery worker returned an invalid pending cursor operation.");
573
591
  } else throw new Error("Retention discovery worker returned an unknown cursor operation.");
574
592
  }
593
+ // SAFETY: parseDiscoveryResult validates every candidate, cursor, and scalar
594
+ // operation above; the cast re-narrows the worker message to its domain type.
575
595
  return message as unknown as RetentionDiscovery;
576
596
  }
577
597
 
@@ -1,8 +1,8 @@
1
1
  import type { AsyncJobState, SubagentState } from "../../shared/types.ts";
2
2
  import {
3
- projectAsyncStatusSnapshot,
3
+ projectAsyncStatusSnapshot as buildAsyncStatusSnapshot,
4
4
  type AsyncStatusSnapshotOptions,
5
- type AsyncStatusSnapshotV1,
5
+ type AsyncStatusSnapshot,
6
6
  } from "../shared/async-status-projection.ts";
7
7
 
8
8
  export {
@@ -10,22 +10,20 @@ export {
10
10
  ASYNC_STATUS_SNAPSHOT_VERSION,
11
11
  } from "../shared/async-status-projection.ts";
12
12
  export type {
13
- AsyncStatusSnapshotActivityV1,
14
- AsyncStatusSnapshotCapsV1,
15
- AsyncStatusSnapshotHostStepV1,
13
+ AsyncStatusSnapshotActivity,
14
+ AsyncStatusSnapshotCaps,
15
+ AsyncStatusSnapshotHostStep,
16
16
  AsyncStatusSnapshotKind,
17
- AsyncStatusSnapshotNodeV1,
18
- AsyncStatusSnapshotOmittedV1,
17
+ AsyncStatusSnapshotNode,
18
+ AsyncStatusSnapshotOmitted,
19
19
  AsyncStatusSnapshotOptions,
20
20
  AsyncStatusSnapshotState,
21
- AsyncStatusSnapshotV1,
21
+ AsyncStatusSnapshot,
22
22
  } from "../shared/async-status-projection.ts";
23
23
 
24
24
  export const ASYNC_STATUS_SNAPSHOT_WIDGET_PREFIX = "PI_SUBAGENT_ASYNC_JSON:";
25
25
 
26
- export function buildAsyncStatusSnapshot(jobs: Iterable<AsyncJobState>, options: AsyncStatusSnapshotOptions = {}): AsyncStatusSnapshotV1 {
27
- return projectAsyncStatusSnapshot(jobs, options);
28
- }
26
+ export { buildAsyncStatusSnapshot };
29
27
 
30
28
  export function asyncStatusSnapshotJobsForState(state: SubagentState | undefined, sessionId: string | null | undefined): AsyncJobState[] {
31
29
  if (!state || !sessionId || state.currentSessionId !== sessionId) return [];
@@ -39,7 +37,7 @@ export function asyncStatusSnapshotJobsForState(state: SubagentState | undefined
39
37
  return [...jobs.values()];
40
38
  }
41
39
 
42
- export function buildAsyncStatusSnapshotForState(state: SubagentState | undefined, sessionId: string | null | undefined, options: AsyncStatusSnapshotOptions = {}): AsyncStatusSnapshotV1 {
40
+ export function buildAsyncStatusSnapshotForState(state: SubagentState | undefined, sessionId: string | null | undefined, options: AsyncStatusSnapshotOptions = {}): AsyncStatusSnapshot {
43
41
  return buildAsyncStatusSnapshot(asyncStatusSnapshotJobsForState(state, sessionId), options);
44
42
  }
45
43
 
@@ -3,7 +3,7 @@ import * as path from "node:path";
3
3
  import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../../shared/formatters.ts";
4
4
  import { previewDisplayText } from "../../shared/display-text.ts";
5
5
  import { formatActivityLabel, formatParallelOutcome } from "../../shared/status-format.ts";
6
- import { type ActivityState, type AsyncJobStep, type AsyncParallelGroupStatus, type AsyncStatus, type CostSummary, type Details, type HostStepNodeV1, type HostStepState, type LaunchResolvedChildExtensionsV1, type RuntimeAcknowledgedChildExtensionsV1, type NestedRunSummary, type SteeringStatus, type SubagentRunMode, type TimeoutRecoveryProjection, type TokenUsage, type TurnBudgetState, type UsageBudgetState, type WorktreeNaming, type WorkflowPreflightV1, type WorkflowGraphSnapshot } from "../../shared/types.ts";
6
+ import { type ActivityState, type AsyncJobStep, type AsyncParallelGroupStatus, type AsyncStatus, type CostSummary, type Details, type HostStepNode, type HostStepState, type LaunchResolvedChildExtensions, type RuntimeAcknowledgedChildExtensions, type NestedRunSummary, type SteeringStatus, type SubagentRunMode, type TimeoutRecoveryProjection, type TokenUsage, type TurnBudgetState, type UsageBudgetState, type WorktreeNaming, type WorkflowPreflight, type WorkflowGraphSnapshot } from "../../shared/types.ts";
7
7
  import type { ResolvedSubagentCapabilityCeiling, SubagentCapabilityAudit } from "../shared/capability-ceiling.ts";
8
8
  import { readStatus } from "../../shared/utils.ts";
9
9
  import { attachRootChildrenToSteps, buildNestedRouteIndex, findNestedRouteForRootId, type NestedRoute, projectNestedEvents } from "../shared/nested-events.ts";
@@ -27,6 +27,8 @@ import { formatTimeoutRecoveryLines, projectTimeoutRecovery } from "../shared/mu
27
27
  import { formatWorkflowChecklistText, projectWorkflowChecklist } from "../../workflows/workflow-checklist.ts";
28
28
  import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
29
29
  import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
30
+ import type { RawDrainStatusObserver } from "../shared/readonly-drain-observation.ts";
31
+ import { childWatchdogProgressForModel } from "../../watchdog/child-status.ts";
30
32
 
31
33
  interface AsyncRunStepSummary {
32
34
  index: number;
@@ -69,7 +71,7 @@ interface AsyncRunStepSummary {
69
71
  thinking?: string;
70
72
  sandbox?: string;
71
73
  permissionProfile?: string;
72
- attemptedModels?: string[];
74
+ requestedModel?: string;
73
75
  sessionFile?: string;
74
76
  transcriptPath?: string;
75
77
  error?: string;
@@ -86,8 +88,8 @@ interface AsyncRunStepSummary {
86
88
  effects?: AsyncJobStep["effects"];
87
89
  processTerminal?: AsyncJobStep["processTerminal"];
88
90
  timeoutRecovery?: TimeoutRecoveryProjection;
89
- launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
90
- runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
91
+ launchResolvedExtensions?: LaunchResolvedChildExtensions;
92
+ runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensions;
91
93
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
92
94
  capabilityAudit?: SubagentCapabilityAudit;
93
95
  children?: NestedRunSummary[];
@@ -128,7 +130,7 @@ export interface AsyncRunSummary {
128
130
  chainStepCount?: number;
129
131
  pendingAppends?: number;
130
132
  parallelGroups?: AsyncParallelGroupStatus[];
131
- hostSteps?: HostStepNodeV1[];
133
+ hostSteps?: HostStepNode[];
132
134
  workflowGraph?: AsyncStatus["workflowGraph"];
133
135
  steps: AsyncRunStepSummary[];
134
136
  sessionDir?: string;
@@ -141,8 +143,8 @@ export interface AsyncRunSummary {
141
143
  nestedWarnings?: string[];
142
144
  processTerminal?: AsyncStatus["processTerminal"];
143
145
  runFanoutBudget?: AsyncStatus["runFanoutBudget"];
144
- launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
145
- runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
146
+ launchResolvedExtensions?: LaunchResolvedChildExtensions;
147
+ runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensions;
146
148
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
147
149
  capabilityAudit?: SubagentCapabilityAudit;
148
150
  parentWorkflowRunId?: string;
@@ -150,7 +152,7 @@ export interface AsyncRunSummary {
150
152
  lane?: AsyncStatus["lane"];
151
153
  workflow?: Details["workflow"];
152
154
  workflowChildren?: Details["workflowChildren"];
153
- preflight?: WorkflowPreflightV1;
155
+ preflight?: WorkflowPreflight;
154
156
  }
155
157
 
156
158
  interface AsyncRunListOptions {
@@ -392,7 +394,7 @@ function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string
392
394
  ...(sandbox ? { sandbox } : {}),
393
395
  ...(permissionProfile ? { permissionProfile } : {}),
394
396
  ...(step.thinkingCeiling ? { thinkingCeiling: step.thinkingCeiling } : {}),
395
- ...(step.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
397
+ ...(step.requestedModel ? { requestedModel: step.requestedModel } : {}),
396
398
  ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
397
399
  ...(step.transcriptPath ? { transcriptPath: step.transcriptPath } : {}),
398
400
  ...(step.error ? { error: step.error } : {}),
@@ -412,7 +414,7 @@ function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string
412
414
  ...(step.execution ? { execution: step.execution } : {}),
413
415
  ...(step.review ? { review: step.review } : {}),
414
416
  ...(step.effects ? { effects: step.effects } : {}),
415
- ...(step.watchdog ? { watchdog: step.watchdog } : {}),
417
+ ...(step.watchdog ? { watchdog: childWatchdogProgressForModel(step.watchdog) } : {}),
416
418
  ...(step.processTerminal ? { processTerminal: sanitizeProcessTerminal(step.processTerminal, { runId: status.runId, runnerProcessInstanceId: step.processTerminal.runnerProcessInstanceId }, `${path.join(asyncDir, "status.json")} step ${index}`) } : {}),
417
419
  ...(timeoutRecovery ? { timeoutRecovery } : {}),
418
420
  ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
@@ -511,7 +513,7 @@ function sortRuns(runs: AsyncRunSummary[]): AsyncRunSummary[] {
511
513
  });
512
514
  }
513
515
 
514
- export function listAsyncRuns(asyncDirRoot: string, options: AsyncRunListOptions = {}): AsyncRunSummary[] {
516
+ export function listAsyncRuns(asyncDirRoot: string, options: AsyncRunListOptions = {}, observeStatus?: RawDrainStatusObserver): AsyncRunSummary[] {
515
517
  let entries: string[];
516
518
  const activeEntries = new Set<string>();
517
519
  const wantsActive = options.states === undefined || options.states.some(isActiveAsyncState);
@@ -538,6 +540,7 @@ export function listAsyncRuns(asyncDirRoot: string, options: AsyncRunListOptions
538
540
  indexed.add(entry);
539
541
  activeEntries.add(entry);
540
542
  } else {
543
+ observeStatus?.(null);
541
544
  updateActiveRunIndex(path.join(asyncDirRoot, entry), "failed");
542
545
  }
543
546
  }
@@ -549,6 +552,7 @@ export function listAsyncRuns(asyncDirRoot: string, options: AsyncRunListOptions
549
552
  }
550
553
  } catch (error) {
551
554
  if (isNotFoundError(error)) return [];
555
+ observeStatus?.(null);
552
556
  throw new Error(`Failed to list async runs in '${asyncDirRoot}': ${getErrorMessage(error)}`, {
553
557
  cause: error instanceof Error ? error : undefined,
554
558
  });
@@ -572,22 +576,35 @@ export function listAsyncRuns(asyncDirRoot: string, options: AsyncRunListOptions
572
576
  const asyncDir = path.join(asyncDirRoot, entry);
573
577
  let status: (AsyncStatus & { cwd?: string }) | null;
574
578
  try {
579
+ // Reconciliation can rewrite state; session-scoped discovery does not own foreign runs.
580
+ if (options.sessionId !== undefined) {
581
+ const stored = readStatus(asyncDir);
582
+ if (stored && stored.sessionId !== options.sessionId) {
583
+ observeStatus?.(stored);
584
+ continue;
585
+ }
586
+ }
575
587
  const reconciliation = options.reconcile === false
576
588
  ? undefined
577
- : reconcileAsyncRun(asyncDir, { resultsDir: options.resultsDir, kill: options.kill, now: options.now });
589
+ : reconcileAsyncRun(asyncDir, { resultsDir: options.resultsDir, kill: options.kill, now: options.now }, observeStatus);
578
590
  status = (reconciliation?.status ?? readStatus(asyncDir)) as (AsyncStatus & { cwd?: string }) | null;
591
+ if (options.reconcile === false) observeStatus?.(status);
579
592
  } catch (error) {
593
+ observeStatus?.(null);
580
594
  if (!activeEntries.has(entry) || !isAsyncStatusIsolationError(asyncDir, error)) throw error;
581
595
  isolateCorruptActiveRun(asyncDir, entry, error, options.now);
582
596
  continue;
583
597
  }
584
598
  if (!status) {
599
+ observeStatus?.(null);
585
600
  if (activeEntries.has(entry)) updateActiveRunIndex(asyncDir, "failed");
586
601
  continue;
587
602
  }
588
603
  if (activeEntries.has(entry) && !isActiveAsyncState(status.state)) {
589
604
  const processTerminal = readProcessTerminal(asyncDir, { runId: status.runId, runnerProcessInstanceId: status.processTerminal?.runnerProcessInstanceId });
590
- if (processTerminal?.state === "observed" || (activeRunMarkerAgeMs(asyncDir, options.now?.()) ?? 0) > DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS) releaseActiveRunIndex(asyncDir);
605
+ if (processTerminal?.state === "observed" || (activeRunMarkerAgeMs(asyncDir, options.now?.()) ?? 0) > DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS) {
606
+ updateActiveRunIndex(asyncDir, status.state, status.toolCallId, { terminalIndexBeforeRelease: true });
607
+ }
591
608
  }
592
609
  if (status.displayDismissedAt !== undefined) continue;
593
610
  // Filter before the nested-route lookup: the lookup builds an index over
@@ -603,6 +620,7 @@ export function listAsyncRuns(asyncDirRoot: string, options: AsyncRunListOptions
603
620
  nestedRoute = resolveNestedRoute(status.runId || path.basename(asyncDir));
604
621
  if (nestedRoute) reconcileNestedAsyncDescendants(nestedRoute, { resultsDir: options.resultsDir, kill: options.kill, now: options.now });
605
622
  } catch (error) {
623
+ observeStatus?.(null);
606
624
  nestedWarnings.push(`Nested status unavailable: ${getErrorMessage(error)}`);
607
625
  }
608
626
  }
@@ -610,6 +628,7 @@ export function listAsyncRuns(asyncDirRoot: string, options: AsyncRunListOptions
610
628
  try {
611
629
  summary = statusToSummary(asyncDir, status, nestedWarnings, nestedRoute);
612
630
  } catch (error) {
631
+ observeStatus?.(null);
613
632
  if (!activeEntries.has(entry) || !isAsyncStatusIsolationError(asyncDir, error)) throw error;
614
633
  isolateCorruptActiveRun(asyncDir, entry, error, options.now);
615
634
  continue;
@@ -1,12 +1,13 @@
1
1
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
2
  import { snapshotBackgroundWork } from "../../api/background-work.ts";
3
- import { DIRS, type Details, type SubagentState } from "../../shared/types.ts";
3
+ import type { Details, SubagentState } from "../../shared/types.ts";
4
4
  import { listAsyncRuns } from "./async-status.ts";
5
- import { waitForSubagents, type SubagentWaitDeps, type SubagentWaitParams, type WaitEventBus } from "./subagent-wait.ts";
5
+ import type { ReadonlyDrainObservation } from "../shared/readonly-drain-observation.ts";
6
+ import { waitForSubagents, waitRunScopes, type SubagentWaitDeps, type SubagentWaitParams, type WaitEventBus } from "./subagent-wait.ts";
6
7
 
7
8
  export const DEFAULT_AUTO_DRAIN_TIMEOUT_MS = 30 * 60 * 1000;
8
9
 
9
- export interface AutoDrainDeps {
10
+ export interface AutoDrainDeps extends Pick<SubagentWaitDeps, "asyncDirRoot" | "resultsDir" | "nestedRootRunId"> {
10
11
  state: SubagentState;
11
12
  events?: WaitEventBus;
12
13
  timeoutMs?: number;
@@ -17,52 +18,75 @@ export interface AutoDrainDeps {
17
18
  deps: SubagentWaitDeps,
18
19
  ) => Promise<AgentToolResult<Details>>;
19
20
  hasWork?: (sessionId: string, nowMs: number) => boolean;
21
+ hasPendingSupervisorRequest?: () => boolean;
20
22
  }
21
23
 
22
24
  function resultText(value: AgentToolResult<Details>): string {
23
25
  return value.content.map((part) => part.type === "text" ? part.text : "").join(" ").trim();
24
26
  }
25
27
 
26
- function hasOutstandingWork(sessionId: string, nowMs: number): boolean {
27
- const asyncRuns = listAsyncRuns(DIRS.async, {
28
+ function hasOutstandingWork(deps: AutoDrainDeps, sessionId: string, nowMs: number, observation?: ReadonlyDrainObservation): boolean {
29
+ const asyncRuns = waitRunScopes(deps).flatMap(({ asyncDirRoot, resultsDir }) => listAsyncRuns(asyncDirRoot, {
28
30
  states: ["queued", "running"],
29
31
  sessionId,
30
- resultsDir: DIRS.results,
32
+ resultsDir,
31
33
  now: () => nowMs,
32
- });
33
- return asyncRuns.length > 0 || snapshotBackgroundWork(sessionId, nowMs).items.length > 0;
34
+ includeNested: false,
35
+ }, observation?.status));
36
+ const detachedForeground = [...(deps.state.foregroundRuns?.values() ?? [])].some((run) =>
37
+ run.sessionId === sessionId && run.children.some((child) => child.status === "detached")
38
+ );
39
+ return asyncRuns.length > 0 || snapshotBackgroundWork(sessionId, nowMs).items.length > 0 || detachedForeground;
34
40
  }
35
41
 
36
42
  /** Drain all work owned by the current headless session, including work added while draining. */
37
- export async function drainOutstandingWork(deps: AutoDrainDeps): Promise<void> {
43
+ export async function drainOutstandingWork(deps: AutoDrainDeps, observation?: ReadonlyDrainObservation): Promise<void> {
38
44
  const sessionId = deps.state.currentSessionId;
39
- if (!sessionId) throw new Error("Cannot auto-drain background work without an active session identity.");
40
- const now = deps.now ?? Date.now;
41
- const timeoutMs = deps.timeoutMs ?? DEFAULT_AUTO_DRAIN_TIMEOUT_MS;
42
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Auto-drain timeoutMs must be a positive finite number.");
43
- const deadlineAt = now() + timeoutMs;
44
- const hasWork = deps.hasWork ?? hasOutstandingWork;
45
- const wait = deps.wait ?? waitForSubagents;
45
+ observation?.begin(sessionId, !deps.hasWork && !deps.wait && !deps.now && !deps.hasPendingSupervisorRequest);
46
+ try {
47
+ if (!sessionId) throw new Error("Cannot auto-drain background work without an active session identity.");
48
+ const now = deps.now ?? Date.now;
49
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_AUTO_DRAIN_TIMEOUT_MS;
50
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Auto-drain timeoutMs must be a positive finite number.");
51
+ const deadlineAt = now() + timeoutMs;
52
+ const hasWork = deps.hasWork ?? ((id: string, time: number) => hasOutstandingWork(deps, id, time, observation));
53
+ const wait = deps.wait ?? waitForSubagents;
46
54
 
47
- while (hasWork(sessionId, now())) {
48
- const remainingMs = deadlineAt - now();
49
- if (remainingMs <= 0) {
50
- throw new Error(`Auto-drain timed out after ${timeoutMs}ms with background work still active in session '${sessionId}'.`);
51
- }
52
- const waitResult = await wait(
53
- { all: true, timeoutMs: remainingMs },
54
- undefined,
55
- {
56
- state: deps.state,
57
- events: deps.events,
58
- now,
59
- stopOnAttention: false,
60
- failOnFailedRuns: true,
61
- failOnAttention: true,
62
- },
63
- );
64
- if (waitResult.isError) {
65
- throw new Error(`Auto-drain failed for session '${sessionId}': ${resultText(waitResult) || "bg_wait returned an error without details"}.`);
55
+ while (true) {
56
+ if (deps.state.currentSessionId !== sessionId) throw new Error("Auto-drain stopped because the active session changed.");
57
+ if (deps.hasPendingSupervisorRequest?.()) break;
58
+ const work = hasWork(sessionId, now());
59
+ observation?.predicate(work);
60
+ if (!work) break;
61
+ const remainingMs = deadlineAt - now();
62
+ if (remainingMs <= 0) {
63
+ throw new Error(`Auto-drain timed out after ${timeoutMs}ms with background work still active in session '${sessionId}'.`);
64
+ }
65
+ const waitResult = await wait(
66
+ { all: true, timeoutMs: remainingMs },
67
+ undefined,
68
+ {
69
+ state: deps.state,
70
+ asyncDirRoot: deps.asyncDirRoot,
71
+ resultsDir: deps.resultsDir,
72
+ nestedRootRunId: deps.nestedRootRunId,
73
+ events: deps.events,
74
+ now,
75
+ stopOnAttention: false,
76
+ failOnFailedRuns: true,
77
+ failOnAttention: true,
78
+ hasPendingSupervisorRequest: deps.hasPendingSupervisorRequest,
79
+ },
80
+ );
81
+ if (waitResult.isError) {
82
+ throw new Error(`Auto-drain failed for session '${sessionId}': ${resultText(waitResult) || "bg_wait returned an error without details"}.`);
83
+ }
84
+ if (waitResult.details.wait?.reason === "supervisor_request") break;
85
+ if (deps.hasPendingSupervisorRequest?.()) break;
66
86
  }
87
+ observation?.complete();
88
+ } catch (error) {
89
+ observation?.deny();
90
+ throw error;
67
91
  }
68
92
  }