@xzzpig/pi-subagents 0.4.1 → 0.5.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 (128) hide show
  1. package/CHANGELOG.md +175 -0
  2. package/README.md +4 -0
  3. package/agents/oracle.md +3 -1
  4. package/agents/reviewer.md +1 -0
  5. package/agents/scout.md +2 -2
  6. package/agents/worker.md +2 -1
  7. package/async-retention-discovery-worker.mjs +180 -0
  8. package/docs/agents.md +41 -3
  9. package/docs/configuration.md +41 -13
  10. package/docs/extension-api.md +65 -2
  11. package/docs/models.md +2 -0
  12. package/docs/observability.md +41 -5
  13. package/docs/tool-reference.md +38 -39
  14. package/docs/workflows.md +173 -3
  15. package/package.json +14 -10
  16. package/prompts/council.md +48 -0
  17. package/skills/council-mode/SKILL.md +230 -0
  18. package/skills/pi-subagents/SKILL.md +8 -4
  19. package/skills/pi-subagents/references/constraints-and-recipes.md +13 -6
  20. package/skills/pi-subagents/references/execution-controls.md +40 -15
  21. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  22. package/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +4 -2
  24. package/src/agents/agent-management.ts +471 -377
  25. package/src/agents/agent-serializer.ts +2 -0
  26. package/src/agents/agents.ts +186 -44
  27. package/src/agents/builtin-names.ts +9 -0
  28. package/src/agents/runtime-agent-registry.ts +418 -0
  29. package/src/agents/skills.ts +1 -1
  30. package/src/api/agent-management.ts +9 -0
  31. package/src/api/agents.ts +7 -0
  32. package/src/api/external-job-provider.ts +186 -0
  33. package/src/api/preflight.ts +45 -13
  34. package/src/api/shared-types.ts +2 -0
  35. package/src/extension/config.ts +6 -3
  36. package/src/extension/doctor.ts +4 -6
  37. package/src/extension/fanout-child.ts +2 -2
  38. package/src/extension/index.ts +183 -90
  39. package/src/extension/public-execution.ts +31 -2
  40. package/src/extension/rpc.ts +41 -1
  41. package/src/extension/schemas.ts +17 -37
  42. package/src/extension/tool-description.ts +35 -24
  43. package/src/inspectors/herdr/actions.ts +2 -2
  44. package/src/inspectors/herdr/inspector-runner.ts +2 -1
  45. package/src/inspectors/herdr/project-panes.ts +2 -2
  46. package/src/intercom/native-supervisor-channel.ts +32 -10
  47. package/src/missions/lifecycle.ts +6 -1
  48. package/src/missions/store.ts +4 -9
  49. package/src/missions/workflow-state.ts +2 -2
  50. package/src/profiles/profiles.ts +3 -1
  51. package/src/runs/background/active-run-index.ts +31 -8
  52. package/src/runs/background/async-execution.ts +70 -41
  53. package/src/runs/background/async-job-tracker.ts +24 -7
  54. package/src/runs/background/async-resume.ts +49 -16
  55. package/src/runs/background/async-retention.ts +886 -0
  56. package/src/runs/background/async-status-snapshot.ts +14 -5
  57. package/src/runs/background/async-status.ts +39 -53
  58. package/src/runs/background/auto-drain.ts +1 -0
  59. package/src/runs/background/chain-append.ts +3 -33
  60. package/src/runs/background/completion-dedupe.ts +5 -1
  61. package/src/runs/background/completion-replay.ts +22 -12
  62. package/src/runs/background/control-channel.ts +14 -68
  63. package/src/runs/background/fleet-view.ts +68 -19
  64. package/src/runs/background/index-segment.ts +59 -0
  65. package/src/runs/background/inspect-rpc.ts +443 -0
  66. package/src/runs/background/notify.ts +31 -5
  67. package/src/runs/background/result-files.ts +158 -90
  68. package/src/runs/background/result-watcher.ts +124 -20
  69. package/src/runs/background/resume-guidance.ts +8 -5
  70. package/src/runs/background/retained-children.ts +13 -3
  71. package/src/runs/background/run-id-query.ts +7 -0
  72. package/src/runs/background/run-id-resolver.ts +11 -9
  73. package/src/runs/background/run-status.ts +27 -18
  74. package/src/runs/background/scheduled-runs.ts +24 -4
  75. package/src/runs/background/stale-run-reconciler.ts +6 -3
  76. package/src/runs/background/steering.ts +11 -1
  77. package/src/runs/background/subagent-runner.ts +260 -144
  78. package/src/runs/background/subagent-wait.ts +17 -13
  79. package/src/runs/background/terminal-run-index.ts +138 -0
  80. package/src/runs/background/wait-completions.ts +21 -4
  81. package/src/runs/background/wait-subscriptions.ts +81 -2
  82. package/src/runs/background/wait-tool.ts +1 -0
  83. package/src/runs/foreground/async-steering-action.ts +21 -14
  84. package/src/runs/foreground/execution.ts +104 -71
  85. package/src/runs/foreground/subagent-executor.ts +816 -1593
  86. package/src/runs/foreground/workflow-detach-reconcile.ts +262 -0
  87. package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
  88. package/src/runs/shared/acceptance.ts +48 -5
  89. package/src/runs/shared/chain-outputs.ts +1 -3
  90. package/src/runs/shared/external-job-bridge.ts +444 -0
  91. package/src/runs/shared/external-job-runner.ts +286 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
  93. package/src/runs/shared/model-exclusions.ts +242 -0
  94. package/src/runs/shared/model-fallback.ts +153 -40
  95. package/src/runs/shared/orca-progress-tabs.ts +84 -22
  96. package/src/runs/shared/parallel-handoff.ts +46 -4
  97. package/src/runs/shared/parallel-utils.ts +4 -15
  98. package/src/runs/shared/permissions.ts +5 -1
  99. package/src/runs/shared/pi-args.ts +8 -1
  100. package/src/runs/shared/session-lease.ts +0 -6
  101. package/src/runs/shared/subagent-control.ts +51 -7
  102. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  103. package/src/runs/shared/workflow-graph.ts +1 -23
  104. package/src/runs/shared/worktree.ts +14 -2
  105. package/src/shared/atomic-json.ts +22 -2
  106. package/src/shared/capacity-resilient-json.ts +102 -0
  107. package/src/shared/completion-owner.ts +14 -0
  108. package/src/shared/file-system-retry.ts +49 -1
  109. package/src/shared/fork-context.ts +59 -1
  110. package/src/shared/model-info.ts +20 -0
  111. package/src/shared/prompt-resources.ts +0 -40
  112. package/src/shared/settings.ts +5 -29
  113. package/src/shared/types.ts +106 -26
  114. package/src/shared/utils.ts +8 -0
  115. package/src/shared/watch-strategy.ts +10 -0
  116. package/src/slash/slash-bridge.ts +2 -1
  117. package/src/slash/slash-commands.ts +47 -7
  118. package/src/slash/slash-live-state.ts +3 -3
  119. package/src/tui/fleet-status.ts +86 -1
  120. package/src/tui/fleet.ts +117 -16
  121. package/src/tui/render.ts +73 -3
  122. package/src/watchdog/change-signature.ts +1 -1
  123. package/src/watchdog/lsp-diagnostics.ts +1 -0
  124. package/src/workflows/chat-progress.ts +2 -2
  125. package/src/workflows/scripted-workflow.ts +320 -79
  126. package/src/workflows/workflow-receipt.ts +140 -0
  127. package/src/runs/foreground/chain-clarify.ts +0 -1354
  128. package/src/runs/foreground/chain-execution.ts +0 -1581
@@ -20,6 +20,8 @@ import { normalizeParallelGroups } from "./parallel-groups.ts";
20
20
  import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-reconciler.ts";
21
21
  import { findNestedRouteForRootId, hasLiveNestedDescendants, updateAsyncJobNestedProjection } from "../shared/nested-events.ts";
22
22
  import { listAsyncRuns, type AsyncRunSummary } from "./async-status.ts";
23
+ import { EXTERNAL_JOB_BRIDGE_REQUEST_DIR, serviceExternalJobBridgeRequests } from "../shared/external-job-bridge.ts";
24
+ import { shouldUseNativeFsWatch } from "../../shared/watch-strategy.ts";
23
25
 
24
26
  interface AsyncJobTrackerOptions {
25
27
  completionRetentionMs?: number;
@@ -27,6 +29,9 @@ interface AsyncJobTrackerOptions {
27
29
  pollIntervalMs?: number;
28
30
  resultsDir?: string;
29
31
  widgetEnabled?: boolean;
32
+ platform?: NodeJS.Platform;
33
+ onJobTerminal?: () => void;
34
+ watch?: typeof fs.watch;
30
35
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
31
36
  now?: () => number;
32
37
  }
@@ -66,6 +71,9 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
66
71
  const runningJobIds = new Set<string>();
67
72
  let rootWatcher: fs.FSWatcher | undefined;
68
73
  let nextLivenessAt = Date.now() + livenessIntervalMs;
74
+ const watch = options.watch ?? fs.watch;
75
+ const useNativeWatcher = () => shouldUseNativeFsWatch("async-job-tracker", options.platform);
76
+ const terminalStatus = (status: string) => status === "complete" || status === "failed" || status === "paused" || status === "stopped";
69
77
  const rerenderWidget = (ctx: ExtensionContext, jobs = Array.from(state.asyncJobs.values())) => {
70
78
  if (state.widgetsSuspended) return;
71
79
  renderWidget(ctx, options.widgetEnabled === false ? [] : jobs);
@@ -139,6 +147,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
139
147
  mode: run.mode,
140
148
  context: run.context,
141
149
  cwd: run.cwd,
150
+ sessionRoot: run.sessionRoot,
142
151
  agents: visibleSteps.map((step) => step.agent),
143
152
  currentStep: run.currentStep,
144
153
  chainStepCount: run.chainStepCount,
@@ -315,7 +324,8 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
315
324
  };
316
325
 
317
326
  const refreshJob = (job: AsyncJobState): boolean => {
318
- const widgetStateBefore = widgetRenderKey(job);
327
+ const widgetExpanded = state.lastUiContext?.hasUI ? state.lastUiContext.ui.getToolsExpanded?.() ?? false : false;
328
+ const widgetStateBefore = widgetRenderKey(job, widgetExpanded);
319
329
  let nestedRefreshFailed = false;
320
330
  const refreshNestedProjection = () => {
321
331
  try {
@@ -327,6 +337,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
327
337
  };
328
338
  try {
329
339
  emitNewControlEvents(job);
340
+ serviceExternalJobBridgeRequests(job.asyncDir);
330
341
  try {
331
342
  if (job.nestedRoute) reconcileNestedAsyncDescendants(job.nestedRoute, { resultsDir, kill: options.kill, now: options.now });
332
343
  } catch (error) {
@@ -342,6 +353,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
342
353
  runId: job.asyncId,
343
354
  pid: job.pid,
344
355
  sessionId: job.sessionId,
356
+ completionOwnerId: job.completionOwnerId,
345
357
  mode: job.mode,
346
358
  agents: job.agents,
347
359
  chainStepCount: job.chainStepCount,
@@ -404,13 +416,14 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
404
416
  job.turnBudgetExceeded = status.turnBudgetExceeded ?? job.turnBudgetExceeded;
405
417
  job.wrapUpRequested = status.wrapUpRequested ?? job.wrapUpRequested;
406
418
  job.sessionFile = status.sessionFile ?? job.sessionFile;
407
- if (job.status === "complete" || job.status === "failed" || job.status === "paused" || job.status === "stopped") {
419
+ if (terminalStatus(job.status)) {
420
+ if (!terminalStatus(previousStatus)) options.onJobTerminal?.();
408
421
  rememberFleetJob(state, job);
409
422
  if (!nestedRefreshFailed && !hasLiveNestedDescendants(job.nestedChildren) && (previousStatus !== job.status || !state.cleanupTimers.has(job.asyncId))) {
410
423
  scheduleCleanup(job.asyncId);
411
424
  }
412
425
  }
413
- return widgetRenderKey(job) !== widgetStateBefore;
426
+ return widgetRenderKey(job, widgetExpanded) !== widgetStateBefore;
414
427
  }
415
428
  if (job.status === "queued") {
416
429
  job.status = "running";
@@ -427,7 +440,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
427
440
  rememberFleetJob(state, job);
428
441
  if (!hasLiveNestedDescendants(job.nestedChildren) && !state.cleanupTimers.has(job.asyncId)) scheduleCleanup(job.asyncId);
429
442
  }
430
- return widgetRenderKey(job) !== widgetStateBefore;
443
+ return widgetRenderKey(job, widgetExpanded) !== widgetStateBefore;
431
444
  };
432
445
 
433
446
  const scheduleJobRefresh = (asyncId: string, delayMs = EVENT_REFRESH_DEBOUNCE_MS) => {
@@ -442,6 +455,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
442
455
  };
443
456
 
444
457
  const watchJob = (job: AsyncJobState) => {
458
+ if (!useNativeWatcher()) return;
445
459
  const watched = jobWatchers.get(job.asyncId) ?? { watchers: new Map<string, fs.FSWatcher>() };
446
460
  const active = job.status === "queued" || job.status === "running";
447
461
  const watchPath = (watchPath: string): boolean => {
@@ -449,11 +463,11 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
449
463
  const nestedEventSink = job.nestedRoute?.eventSink === watchPath;
450
464
  let watcher: fs.FSWatcher;
451
465
  try {
452
- watcher = fs.watch(resolveWatchPath(watchPath), (_event, file) => {
466
+ watcher = watch(resolveWatchPath(watchPath), (_event, file) => {
453
467
  const rawFileName = file?.toString();
454
468
  const fileName = rawFileName ?? path.basename(watchPath);
455
469
  const nestedEventFile = nestedEventSink && (!rawFileName || rawFileName.endsWith(".json") || rawFileName.endsWith(".jsonl"));
456
- if (fileName === "status.json" || fileName === "events.jsonl" || nestedEventFile) {
470
+ if (fileName === "status.json" || fileName === "events.jsonl" || fileName === EXTERNAL_JOB_BRIDGE_REQUEST_DIR || fileName.endsWith(".json") || nestedEventFile) {
457
471
  scheduleJobRefresh(job.asyncId);
458
472
  }
459
473
  if (watchPath !== job.asyncDir && !nestedEventSink) {
@@ -480,6 +494,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
480
494
  const statusWatched = watchPath(statusPath);
481
495
  if (statusWatched && !hadStatusWatcher) scheduleJobRefresh(job.asyncId);
482
496
  watchPath(path.join(job.asyncDir, "events.jsonl"));
497
+ watchPath(path.join(job.asyncDir, EXTERNAL_JOB_BRIDGE_REQUEST_DIR));
483
498
  if (job.nestedRoute) watchPath(job.nestedRoute.eventSink);
484
499
  if (!statusWatched && active && !watched.retryTimer) {
485
500
  watched.retryTimer = setTimeout(() => {
@@ -497,9 +512,10 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
497
512
  };
498
513
 
499
514
  const watchAsyncRoot = () => {
515
+ if (!useNativeWatcher()) return;
500
516
  if (rootWatcher) return;
501
517
  try {
502
- rootWatcher = fs.watch(resolveWatchPath(asyncDirRoot), (_event, file) => {
518
+ rootWatcher = watch(resolveWatchPath(asyncDirRoot), (_event, file) => {
503
519
  const runDirName = file?.toString();
504
520
  for (const job of state.asyncJobs.values()) {
505
521
  if (jobWatchers.has(job.asyncId) || (runDirName && path.basename(job.asyncDir) !== runDirName)) continue;
@@ -568,6 +584,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
568
584
  status: "queued",
569
585
  pid: typeof info.pid === "number" ? info.pid : undefined,
570
586
  ...(typeof info.sessionId === "string" ? { sessionId: info.sessionId } : {}),
587
+ ...(typeof info.completionOwnerId === "string" ? { completionOwnerId: info.completionOwnerId } : {}),
571
588
  mode: info.mode ?? (info.chain ? "chain" : "single"),
572
589
  description: info.goal ?? info.task,
573
590
  agents,
@@ -1,6 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { DIRS, type AcceptanceInput, type AsyncStatus, type ResolvedTurnBudget, type SteeringRecoveryDescriptor } from "../../shared/types.ts";
3
+ import { DIRS, type AcceptanceInput, type AsyncStatus, type ResolvedTurnBudget, type SteeringRecoveryDescriptor, type SubagentRunMode } from "../../shared/types.ts";
4
4
  import type { AgentConfig } from "../../agents/agents.ts";
5
5
  import { validateAcceptanceInput } from "../shared/acceptance.ts";
6
6
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
@@ -8,7 +8,9 @@ import { intersectSubagentCapabilityCeilings, parseSubagentCapabilityCeiling, ty
8
8
  import { validateRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
9
9
  import { resolveTurnBudgetConfig } from "../shared/turn-budget.ts";
10
10
  import { reconcileAsyncRun } from "./stale-run-reconciler.ts";
11
- import { resultFilePath } from "./result-files.ts";
11
+ import { resultFilePath, resultPayloadPathForIndexedRun } from "./result-files.ts";
12
+ import { canScanAsyncRunPrefix, MIN_SAFE_ASYNC_RUN_PREFIX_LENGTH } from "./run-id-query.ts";
13
+ import { parallelHandoffPath, resolveRetainedWorktreeCwd } from "../shared/parallel-handoff.ts";
12
14
 
13
15
  export interface AsyncResumeParams {
14
16
  id?: string;
@@ -34,6 +36,7 @@ export type AsyncResumeTarget = {
34
36
  runId: string;
35
37
  asyncDir?: string;
36
38
  state: AsyncStatus["state"];
39
+ mode?: SubagentRunMode;
37
40
  agent: string;
38
41
  index: number;
39
42
  cwd?: string;
@@ -173,6 +176,8 @@ function prefixedRunIds(dir: string, prefix: string, suffix = ""): string[] {
173
176
  }
174
177
 
175
178
  function exactResultPath(resultsDir: string, runId: string): string | null {
179
+ const indexed = resultPayloadPathForIndexedRun(resultsDir, runId);
180
+ if (indexed) return indexed;
176
181
  const resultPath = resultFilePath(resultsDir, runId);
177
182
  assertInsideRoot(resultsDir, resultPath, "Async result file");
178
183
  return fs.existsSync(resultPath) ? resultPath : null;
@@ -181,6 +186,7 @@ function exactResultPath(resultsDir: string, runId: string): string | null {
181
186
  export function findAsyncRunPrefixMatches(prefix: string, asyncDirRoot: string, resultsDir: string): Array<{ id: string; location: AsyncRunLocation }> {
182
187
  const requestedId = assertRunId(prefix, "id");
183
188
  if (!requestedId) return [];
189
+ if (!canScanAsyncRunPrefix(requestedId)) return [];
184
190
  const asyncRoot = path.resolve(asyncDirRoot);
185
191
  const resultRoot = path.resolve(resultsDir);
186
192
  const matchingIds = prefixedRunIds(asyncRoot, requestedId).sort();
@@ -223,6 +229,10 @@ export function resolveAsyncRunLocation(params: AsyncResumeParams, asyncDirRoot:
223
229
  resolvedId: requestedId,
224
230
  };
225
231
  }
232
+ if (requestedId.length < MIN_SAFE_ASYNC_RUN_PREFIX_LENGTH) {
233
+ throw new Error(`Async run id prefix '${requestedId}' is too short. Provide at least ${MIN_SAFE_ASYNC_RUN_PREFIX_LENGTH} characters.`);
234
+ }
235
+ if (!canScanAsyncRunPrefix(requestedId)) return { asyncDir: null, resultPath: null, resolvedId: requestedId };
226
236
 
227
237
  const matching = findAsyncRunPrefixMatches(requestedId, asyncRoot, resultRoot);
228
238
  if (matching.length === 0) return { asyncDir: null, resultPath: null, resolvedId: requestedId };
@@ -261,12 +271,7 @@ function validateStatusForResume(status: AsyncStatus | null, source: string): vo
261
271
  }
262
272
  }
263
273
 
264
- function normalizeRecoveryAcceptance(value: unknown, descriptorPath: string): AcceptanceInput | undefined {
265
- if (value && typeof value === "object" && !Array.isArray(value) && ("explicit" in value || "inferredReason" in value)) {
266
- const { explicit, inferredReason: _inferredReason, ...publicAcceptance } = value as Record<string, unknown>;
267
- if (explicit === false) return undefined;
268
- value = publicAcceptance;
269
- }
274
+ function normalizeRecoveryAcceptance(value: unknown, descriptorPath: string): AcceptanceInput {
270
275
  const errors = validateAcceptanceInput(value, "recoveryDescriptor.acceptance");
271
276
  if (errors.length) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${errors.join(" ")}`);
272
277
  return value as AcceptanceInput;
@@ -289,6 +294,17 @@ function normalizeRecoveryTurnBudget(value: unknown, descriptorPath: string): Re
289
294
  return result.turnBudget;
290
295
  }
291
296
 
297
+ export function asyncReviveRequiresRecoveryDescriptor(target: Pick<AsyncResumeTarget, "recoveryDescriptor" | "mode" | "sessionFile">): boolean {
298
+ if (target.recoveryDescriptor) return false;
299
+ return !(target.mode === "workflow" && Boolean(target.sessionFile));
300
+ }
301
+
302
+ function resumeTargetMode(status: AsyncStatus | null, result: AsyncResultFile | undefined): SubagentRunMode | undefined {
303
+ if (status?.mode) return status.mode;
304
+ if (result?.mode === "single" || result?.mode === "parallel" || result?.mode === "chain" || result?.mode === "workflow") return result.mode;
305
+ return undefined;
306
+ }
307
+
292
308
  export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): SteeringRecoveryDescriptor | undefined {
293
309
  if (!asyncDir) return undefined;
294
310
  const descriptorPath = path.join(asyncDir, "recovery-descriptor.json");
@@ -302,10 +318,10 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
302
318
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': expected an object.`);
303
319
  const parsed = value as Record<string, unknown>;
304
320
  const allowedFields = new Set([
305
- "version", "launchContractDigest", "sourceRunId", "agentContract", "agent", "sessionFile", "cwd", "model", "fallbackModels", "thinking", "tools", "extensions",
321
+ "version", "launchContractDigest", "sourceRunId", "agentContract", "agent", "sessionFile", "cwd", "model", "modelOverrideFromParent", "fallbackModels", "thinking", "tools", "extensions",
306
322
  "subagentOnlyExtensions", "mcpDirectTools", "systemPrompt", "systemPromptMode", "inheritProjectContext", "inheritSkills", "skills",
307
323
  "skillPath", "agentFilePath", "completionGuard", "memory", "outputPath", "outputMode", "structuredOutputSchema", "acceptance", "sessionDir", "artifactConfig",
308
- "artifactsDir", "maxOutput", "controlConfig", "intercomBridge", "absoluteDeadlineAt", "initialTurnBudget", "initialToolBudget", "maxSubagentDepth", "share", "capabilityCeiling",
324
+ "artifactsDir", "maxOutput", "controlConfig", "context", "intercomBridge", "absoluteDeadlineAt", "initialTurnBudget", "initialToolBudget", "maxSubagentDepth", "share", "capabilityCeiling",
309
325
  "launchResolvedExtensions", "runFanoutBudget",
310
326
  ]);
311
327
  for (const field of Object.keys(parsed)) {
@@ -329,6 +345,8 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
329
345
  }
330
346
  if (parsed.systemPromptMode !== "append" && parsed.systemPromptMode !== "replace") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': systemPromptMode is invalid.`);
331
347
  if (parsed.outputMode !== "inline" && parsed.outputMode !== "file-only") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': outputMode is invalid.`);
348
+ if (parsed.context !== undefined && parsed.context !== "fresh" && parsed.context !== "fork") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': context is invalid.`);
349
+ if (parsed.modelOverrideFromParent !== undefined && typeof parsed.modelOverrideFromParent !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': modelOverrideFromParent must be a boolean.`);
332
350
  for (const field of ["inheritProjectContext", "inheritSkills", "share"] as const) {
333
351
  if (typeof parsed[field] !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${field} must be a boolean.`);
334
352
  }
@@ -395,11 +413,7 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
395
413
  if (!Array.isArray(control.notifyOn) || control.notifyOn.some((item) => item !== "active_long_running" && item !== "needs_attention")) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': controlConfig.notifyOn is invalid.`);
396
414
  if (!Array.isArray(control.notifyChannels) || control.notifyChannels.some((item) => item !== "event" && item !== "async" && item !== "intercom")) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': controlConfig.notifyChannels is invalid.`);
397
415
  }
398
- if (parsed.acceptance !== undefined) {
399
- const acceptance = normalizeRecoveryAcceptance(parsed.acceptance, descriptorPath);
400
- if (acceptance === undefined) delete parsed.acceptance;
401
- else parsed.acceptance = acceptance;
402
- }
416
+ if (parsed.acceptance !== undefined) parsed.acceptance = normalizeRecoveryAcceptance(parsed.acceptance, descriptorPath);
403
417
  return parsed as unknown as SteeringRecoveryDescriptor;
404
418
  }
405
419
 
@@ -410,6 +424,17 @@ function validateResumeSessionFile(runId: string, sessionFile: string): string {
410
424
  return resolved;
411
425
  }
412
426
 
427
+ function validateResumeCwd(runId: string, cwd: string | undefined): string | undefined {
428
+ if (!cwd) return undefined;
429
+ const resolved = path.resolve(cwd);
430
+ try {
431
+ if (!fs.statSync(resolved).isDirectory()) throw new Error("path is not a directory");
432
+ } catch (error) {
433
+ throw new Error(`Async run '${runId}' required cwd does not exist: ${cwd}`, { cause: error instanceof Error ? error : undefined });
434
+ }
435
+ return resolved;
436
+ }
437
+
413
438
  export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncResumeDeps = {}, options: AsyncResumeOptions = {}): AsyncResumeTarget {
414
439
  const asyncDirRoot = deps.asyncDirRoot ?? DIRS.async;
415
440
  const resultsDir = deps.resultsDir ?? DIRS.results;
@@ -427,6 +452,7 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
427
452
  const recoveryDescriptor = readAsyncRecoveryDescriptor(location.asyncDir ?? undefined);
428
453
  const result = location.resultPath ? readResultFile(location.resultPath) : undefined;
429
454
  const runId = status?.runId ?? result?.runId ?? result?.id ?? location.resolvedId ?? (location.asyncDir ? path.basename(location.asyncDir) : "unknown");
455
+ const mode = resumeTargetMode(status, result);
430
456
  if (options.sessionId && ((status && status.sessionId !== options.sessionId) || (result && result.sessionId !== options.sessionId))) {
431
457
  throw new Error(`Async run '${runId}' was not found in the active session.`);
432
458
  }
@@ -453,6 +479,7 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
453
479
  runId,
454
480
  asyncDir: location.asyncDir ?? undefined,
455
481
  state,
482
+ ...(mode ? { mode } : {}),
456
483
  agent: selectedStep.agent,
457
484
  index: requestedIndex,
458
485
  cwd: status?.cwd ?? result?.cwd,
@@ -480,6 +507,7 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
480
507
  runId,
481
508
  asyncDir: location.asyncDir ?? undefined,
482
509
  state,
510
+ ...(mode ? { mode } : {}),
483
511
  agent: selected.step.agent,
484
512
  index: selected.index,
485
513
  cwd: status?.cwd ?? result?.cwd,
@@ -510,15 +538,20 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
510
538
  const stepModel = statusSteps[index]?.model ?? resultSteps[index]?.model ?? (stepCount === 1 ? result?.model : undefined);
511
539
  const stepThinking = statusSteps[index]?.thinking ?? resultSteps[index]?.thinking ?? (stepCount === 1 ? result?.thinking : undefined);
512
540
  const capabilityCeiling = intersectSubagentCapabilityCeilings(status?.capabilityCeiling, statusSteps[index]?.capabilityCeiling, result?.capabilityCeiling, resultSteps[index]?.capabilityCeiling);
541
+ const managedWorktreeCwd = location.asyncDir
542
+ ? resolveRetainedWorktreeCwd(parallelHandoffPath(location.asyncDir), runId, index)
543
+ : undefined;
544
+ const resumeCwd = validateResumeCwd(runId, managedWorktreeCwd ?? status?.cwd ?? result?.cwd ?? recoveryDescriptor?.cwd);
513
545
 
514
546
  return {
515
547
  kind: "revive",
516
548
  runId,
517
549
  asyncDir: location.asyncDir ?? undefined,
518
550
  state,
551
+ ...(mode ? { mode } : {}),
519
552
  agent,
520
553
  index,
521
- cwd: status?.cwd ?? result?.cwd,
554
+ ...(resumeCwd ? { cwd: resumeCwd } : {}),
522
555
  ...(resolvedSessionFile ? { sessionFile: resolvedSessionFile } : {}),
523
556
  ...(stepModel ? { model: stepModel } : {}),
524
557
  ...(stepThinking ? { thinking: stepThinking } : {}),