@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
@@ -1,5 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
+ import { createHash } from "node:crypto";
3
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
5
  import { writePrivateAtomicJson } from "../shared/atomic-json.ts";
5
6
  import { PROMPT_REDACTED } from "../shared/utils.ts";
@@ -294,13 +295,17 @@ export function syncMissionFromAsyncCompletion(value: unknown): MissionRecord |
294
295
  current = readMission(binding.location, binding.missionId);
295
296
  } catch (error) {
296
297
  if (!(error instanceof MissionNotFoundError)) throw error;
298
+ const reason = "mission-record-missing";
299
+ const markerId = createHash("sha256").update(JSON.stringify([runId, binding.missionId, reason])).digest("hex");
300
+ const markerPath = path.join(event.asyncDir, `.mission-sync-skipped-${markerId}.json`);
297
301
  try {
302
+ fs.writeFileSync(markerPath, `${JSON.stringify({ runId, missionId: binding.missionId, reason })}\n`, { encoding: "utf-8", mode: 0o600, flag: "wx" });
298
303
  fs.appendFileSync(path.join(event.asyncDir, "events.jsonl"), `${JSON.stringify({
299
304
  type: "subagent.mission.sync.skipped",
300
305
  ts: Date.now(),
301
306
  runId,
302
307
  missionId: binding.missionId,
303
- reason: "mission-record-missing",
308
+ reason,
304
309
  missionPath: missionRecordPath(binding.location, binding.missionId),
305
310
  })}\n`, "utf-8");
306
311
  } catch {
@@ -77,11 +77,6 @@ function nonNegativeTokenCount(value: unknown, label: string): number {
77
77
  return value as number;
78
78
  }
79
79
 
80
- function parseStoredGoal(value: unknown, label: string): { goal?: MissionGoal; legacyObjective?: string } {
81
- if (typeof value === "string") return { legacyObjective: requiredString(value, label).trim() };
82
- return { goal: parseGoal(value, label) };
83
- }
84
-
85
80
  function parseGoal(value: unknown, label: string): MissionGoal {
86
81
  const input = asObject(value, label);
87
82
  if (input.status !== "active" && input.status !== "paused" && input.status !== "budget-exhausted") throw new Error(`${label}.status is invalid`);
@@ -223,18 +218,18 @@ export function parseMissionRecord(value: unknown, source = "mission record"): M
223
218
  const decisions = input.decisions as unknown[];
224
219
  const artifacts = input.artifacts as unknown[];
225
220
  const receipts = (input.receipts ?? []) as unknown[];
226
- const parsedGoal = input.goal !== undefined ? parseStoredGoal(input.goal, `${source}.goal`) : {};
221
+ const goal = input.goal !== undefined ? parseGoal(input.goal, `${source}.goal`) : undefined;
227
222
  const budget = input.budget !== undefined ? parseBudget(input.budget, `${source}.budget`) : undefined;
228
223
  const usage = input.usage !== undefined ? parseUsage(input.usage, `${source}.usage`) : undefined;
229
- const objective = optionalString(input.objective, `${source}.objective`)?.trim() ?? parsedGoal.legacyObjective;
224
+ const objective = optionalString(input.objective, `${source}.objective`)?.trim();
230
225
  if (!objective) throw new Error(`${source}.objective must be a non-empty string`);
231
- if (parsedGoal.goal && !budget) throw new Error(`${source}.budget is required for a goal mission`);
226
+ if (goal && !budget) throw new Error(`${source}.budget is required for a goal mission`);
232
227
  return {
233
228
  schemaVersion: 1,
234
229
  id: validateMissionId(input.id, `${source}.id`),
235
230
  title: requiredString(input.title, `${source}.title`),
236
231
  objective,
237
- ...(parsedGoal.goal ? { goal: parsedGoal.goal } : {}),
232
+ ...(goal ? { goal } : {}),
238
233
  ...(budget ? { budget } : {}),
239
234
  ...(usage ? { usage } : {}),
240
235
  status: missionStatus(input.status, `${source}.status`),
@@ -59,7 +59,7 @@ function psProcessStartKey(pid: number): string | undefined {
59
59
 
60
60
  function windowsProcessStartKey(pid: number): string | undefined {
61
61
  try {
62
- const raw = execFileSync("powershell.exe", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter \"ProcessId=${pid}\").CreationDate`], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1000 }).trim();
62
+ const raw = execFileSync("powershell.exe", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter \"ProcessId=${pid}\").CreationDate`], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1000, windowsHide: true }).trim();
63
63
  return raw ? `win:${raw}` : undefined;
64
64
  } catch {
65
65
  return undefined;
@@ -69,7 +69,7 @@ function windowsProcessStartKey(pid: number): string | undefined {
69
69
  function processStartKey(pid: number): string | undefined {
70
70
  if (process.platform === "linux") return linuxProcessStartKey(pid) ?? psProcessStartKey(pid);
71
71
  if (process.platform === "win32") return windowsProcessStartKey(pid);
72
- return psProcessStartKey(pid);
72
+ return undefined;
73
73
  }
74
74
 
75
75
  const CURRENT_PROCESS_KEY = processStartKey(process.pid);
@@ -3,6 +3,7 @@ import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
5
  import { BUILTIN_AGENT_NAMES } from "../agents/agents.ts";
6
+ import { getPiSpawnCommand } from "../runs/shared/pi-spawn.ts";
6
7
  import { findModelInfo, getSupportedThinkingLevels, splitKnownThinkingSuffix, toModelInfo } from "../shared/model-info.ts";
7
8
  import { getAgentDir } from "../shared/utils.ts";
8
9
 
@@ -340,7 +341,8 @@ async function probeModel(
340
341
  if (typeof pi.exec !== "function") {
341
342
  return { status: "skipped", message: "pi.exec is unavailable in this runtime." };
342
343
  }
343
- const result = await pi.exec("pi", ["-p", "--model", fullId, "--no-tools", 'Reply with exactly "OK".'], {
344
+ const spawnSpec = getPiSpawnCommand(["-p", "--model", fullId, "--no-tools", 'Reply with exactly "OK".']);
345
+ const result = await pi.exec(spawnSpec.command, spawnSpec.args, {
344
346
  cwd: os.tmpdir(),
345
347
  timeout: 45_000,
346
348
  } as Record<string, unknown>);
@@ -1,6 +1,10 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { AsyncStatus } from "../../shared/types.ts";
4
+ import { readStatus } from "../../shared/utils.ts";
5
+ import { encodeIndexSegment } from "./index-segment.ts";
6
+ import { updateTerminalRunIndex } from "./terminal-run-index.ts";
7
+ import { isStorageCapacityError } from "../../shared/file-system-retry.ts";
4
8
 
5
9
  export const ACTIVE_RUN_INDEX_DIR = ".active-runs";
6
10
  export const DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS = 24 * 60 * 60 * 1000;
@@ -12,7 +16,7 @@ function indexDir(asyncDirRoot: string): string {
12
16
  }
13
17
 
14
18
  function toolCallIndexDir(asyncDirRoot: string, toolCallId: string): string {
15
- return path.join(indexDir(asyncDirRoot), TOOL_CALL_INDEX_DIR, encodeURIComponent(toolCallId));
19
+ return path.join(indexDir(asyncDirRoot), TOOL_CALL_INDEX_DIR, encodeIndexSegment(toolCallId));
16
20
  }
17
21
 
18
22
  function toolCallIndexPath(asyncDir: string, toolCallId: string): string {
@@ -45,8 +49,11 @@ function releaseToolCallAliases(asyncDir: string): void {
45
49
  try {
46
50
  entries = fs.readdirSync(root, { withFileTypes: true });
47
51
  } catch (error) {
48
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
49
- throw error;
52
+ const code = (error as NodeJS.ErrnoException).code;
53
+ if (code !== "ENOENT" && code !== "ENOTDIR") {
54
+ console.error(`Failed to inspect async active-run tool-call index root '${root}':`, error);
55
+ }
56
+ return;
50
57
  }
51
58
  for (const entry of entries) {
52
59
  if (!entry.isDirectory()) continue;
@@ -69,19 +76,34 @@ export function releaseActiveRunIndex(asyncDir: string): void {
69
76
  releaseToolCallAliases(asyncDir);
70
77
  }
71
78
 
72
- export function updateActiveRunIndex(asyncDir: string, state: AsyncStatus["state"], toolCallId?: string): void {
79
+ export function updateActiveRunIndex(asyncDir: string, state: AsyncStatus["state"], toolCallId?: string, options: { retryCapacityErrors?: boolean } = {}): void {
73
80
  const marker = markerPath(asyncDir);
74
81
  if (isActiveAsyncState(state)) {
75
82
  fs.mkdirSync(path.dirname(marker), { recursive: true });
76
83
  fs.writeFileSync(marker, "", { flag: "a" });
77
84
  if (toolCallId) {
78
- const toolCallMarker = toolCallIndexPath(asyncDir, toolCallId);
79
- fs.mkdirSync(path.dirname(toolCallMarker), { recursive: true });
80
- fs.writeFileSync(toolCallMarker, "", { flag: "a" });
85
+ try {
86
+ const toolCallMarker = toolCallIndexPath(asyncDir, toolCallId);
87
+ fs.mkdirSync(path.dirname(toolCallMarker), { recursive: true });
88
+ fs.writeFileSync(toolCallMarker, "", { flag: "a" });
89
+ } catch (error) {
90
+ // Tool-call aliases are optional. The authoritative active-run marker
91
+ // must keep the launch discoverable even when alias indexing fails.
92
+ console.error(`Failed to write async active-run tool-call index for '${asyncDir}':`, error);
93
+ }
81
94
  }
82
95
  return;
83
96
  }
84
97
  releaseActiveRunIndex(asyncDir);
98
+ const status = readStatus(asyncDir);
99
+ if (status && status.state === state) {
100
+ try {
101
+ updateTerminalRunIndex(asyncDir, status);
102
+ } catch (error) {
103
+ if (options.retryCapacityErrors && isStorageCapacityError(error)) throw error;
104
+ console.error(`Failed to write async terminal-run index for '${asyncDir}':`, error);
105
+ }
106
+ }
85
107
  }
86
108
 
87
109
  export function activeRunMarkerAgeMs(asyncDir: string, now = Date.now()): number | undefined {
@@ -110,7 +132,8 @@ export function readActiveRunToolCallIndex(asyncDirRoot: string, toolCallId: str
110
132
  .filter((entry) => entry.isFile())
111
133
  .map((entry) => entry.name);
112
134
  } catch (error) {
113
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
135
+ const code = (error as NodeJS.ErrnoException).code;
136
+ if (code === "ENOENT" || code === "ENOTDIR") return [];
114
137
  throw error;
115
138
  }
116
139
  }
@@ -13,9 +13,10 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
13
  import type { AgentConfig } from "../../agents/agents.ts";
14
14
  import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts";
15
15
  import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
16
+ import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
16
17
  import { applyThinkingSuffix, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/pi-args.ts";
17
18
  import { injectOutputPathSystemPrompt, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
18
- import { buildChainInstructions, isCheckpointStep, isDynamicParallelStep, isParallelStep, resolveChainPath, resolveExistingReadPaths, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile, type ChainStep, type ResolvedStepBehavior, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
19
+ import { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveChainPath, resolveExistingReadPaths, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile, type ChainStep, type ResolvedStepBehavior, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
19
20
  import type { RunnerStep } from "../shared/parallel-utils.ts";
20
21
  import type { ContextMode } from "../shared/context-mode.ts";
21
22
  import { resolvePiPackageRoot } from "../shared/pi-spawn.ts";
@@ -23,7 +24,7 @@ import { resolveNodeExecutable } from "../../shared/node-executable.ts";
23
24
  import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.ts";
24
25
  import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
25
26
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, PROMPT_REDACTED, resolveChildCwd } from "../../shared/utils.ts";
26
- import { buildModelCandidates, resolveEffectiveSubagentModel, resolveModelCandidate, resolveSubagentModelOverride, type AvailableModelInfo, type ParentModel } from "../shared/model-fallback.ts";
27
+ import { buildModelCandidates, inheritsParentModel, resolveEffectiveSubagentModel, resolveModelCandidate, resolveSubagentModelOverride, type AvailableModelInfo, type ParentModel } from "../shared/model-fallback.ts";
27
28
  import { resolveToolTimeoutMs, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
28
29
  import type { ModelScopeConfig } from "../shared/model-scope.ts";
29
30
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
@@ -125,6 +126,7 @@ interface AsyncExecutionContext {
125
126
  pi: ExtensionAPI;
126
127
  cwd: string;
127
128
  currentSessionId: string;
129
+ completionOwnerId?: string;
128
130
  /** Parent session id used by permission-system ask forwarding. */
129
131
  parentSessionId?: string;
130
132
  permissions?: PermissionConfig;
@@ -144,7 +146,7 @@ interface AsyncChainParams {
144
146
  /** Raw caller-facing goal used only by the started event. */
145
147
  goal?: string;
146
148
  attachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };
147
- resultMode?: Exclude<SubagentRunMode, "single">;
149
+ resultMode?: SubagentRunMode;
148
150
  agents: AgentConfig[];
149
151
  ctx: AsyncExecutionContext;
150
152
  availableModels?: AvailableModelInfo[];
@@ -218,6 +220,7 @@ interface AsyncSingleParams {
218
220
  agentContract?: AgentContract;
219
221
  structuredOutputSchema?: JsonSchemaObject;
220
222
  modelOverride?: string;
223
+ modelOverrideFromParent?: boolean;
221
224
  thinkingOverride?: AgentConfig["thinking"];
222
225
  availableModels?: AvailableModelInfo[];
223
226
  maxSubagentDepth: number;
@@ -225,6 +228,7 @@ interface AsyncSingleParams {
225
228
  worktreeSetupHook?: string;
226
229
  worktreeSetupHookTimeoutMs?: number;
227
230
  worktreeBaseDir?: string;
231
+ worktree?: boolean;
228
232
  controlConfig?: ResolvedControlConfig;
229
233
  intercomBridge?: IntercomBridgeConfig;
230
234
  controlIntercomTarget?: string;
@@ -428,7 +432,7 @@ function terminateRunnerBeforeProceed(pid: number): boolean {
428
432
  return !runnerIsAlive(pid);
429
433
  }
430
434
 
431
- function persistPreProceedStartupFailure(asyncDir: string, runId: string, runnerProcessInstanceId: string, sessionId: string | undefined, message: string): void {
435
+ function persistPreProceedStartupFailure(asyncDir: string, runId: string, runnerProcessInstanceId: string, sessionId: string | undefined, completionOwnerId: string | undefined, message: string): void {
432
436
  const now = Date.now();
433
437
  try {
434
438
  const statusPath = path.join(asyncDir, "status.json");
@@ -440,6 +444,7 @@ function persistPreProceedStartupFailure(asyncDir: string, runId: string, runner
440
444
  ...status,
441
445
  runId,
442
446
  ...(sessionId ? { sessionId } : {}),
447
+ ...(completionOwnerId ? { completionOwnerId } : {}),
443
448
  state: "failed",
444
449
  lastUpdate: now,
445
450
  error: message,
@@ -491,10 +496,11 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
491
496
  fs.writeFileSync(cfgPath, JSON.stringify(launchConfig));
492
497
  const runner = path.join(path.dirname(fileURLToPath(import.meta.url)), "subagent-runner.ts");
493
498
  const nodeCommand = resolveNodeExecutable();
494
- const launchForStartup = launchConfig as typeof launchConfig & { asyncDir?: unknown; id?: unknown; sessionId?: unknown; revivalLease?: unknown };
499
+ const launchForStartup = launchConfig as typeof launchConfig & { asyncDir?: unknown; id?: unknown; sessionId?: unknown; completionOwnerId?: unknown; revivalLease?: unknown };
495
500
  const launchAsyncDir = typeof launchForStartup.asyncDir === "string" ? launchForStartup.asyncDir : undefined;
496
501
  const launchRunId = typeof launchForStartup.id === "string" ? launchForStartup.id : suffix;
497
502
  const launchSessionId = typeof launchForStartup.sessionId === "string" ? launchForStartup.sessionId : undefined;
503
+ const launchCompletionOwnerId = typeof launchForStartup.completionOwnerId === "string" ? launchForStartup.completionOwnerId : undefined;
498
504
  const startupPath = typeof launchForStartup.revivalLease === "object" && launchAsyncDir
499
505
  ? path.join(launchAsyncDir, "runner-startup.json")
500
506
  : undefined;
@@ -584,7 +590,7 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
584
590
  proc.unref();
585
591
  if (startupPath && startupAckPath && startupProceedPath) {
586
592
  const persistStartupFailure = (message: string) => {
587
- if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, message);
593
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
588
594
  };
589
595
  const ready = waitForRunnerStartup(startupPath, "ready", RUNNER_STARTUP_TIMEOUT_MS);
590
596
  if (ready.ok === false) {
@@ -669,13 +675,11 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
669
675
  : chain;
670
676
  const firstStep = chain[0];
671
677
  const originalTask = params.task ?? (firstStep
672
- ? (isCheckpointStep(firstStep)
673
- ? undefined
674
- : isParallelStep(firstStep)
675
- ? firstStep.parallel[0]?.task
676
- : isDynamicParallelStep(firstStep)
677
- ? firstStep.parallel.task
678
- : (firstStep as SequentialStep).task)
678
+ ? (isParallelStep(firstStep)
679
+ ? firstStep.parallel[0]?.task
680
+ : isDynamicParallelStep(firstStep)
681
+ ? firstStep.parallel.task
682
+ : (firstStep as SequentialStep).task)
679
683
  : undefined);
680
684
  try {
681
685
  if (params.validateOutputBindings !== false) {
@@ -688,13 +692,11 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
688
692
  const workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: graphChain });
689
693
 
690
694
  for (const s of chain) {
691
- const stepAgents = isCheckpointStep(s)
692
- ? []
693
- : isParallelStep(s)
694
- ? s.parallel.map((t) => t.agent)
695
- : isDynamicParallelStep(s)
696
- ? [s.parallel.agent]
697
- : [(s as SequentialStep).agent];
695
+ const stepAgents = isParallelStep(s)
696
+ ? s.parallel.map((t) => t.agent)
697
+ : isDynamicParallelStep(s)
698
+ ? [s.parallel.agent]
699
+ : [(s as SequentialStep).agent];
698
700
  for (const agentName of stepAgents) {
699
701
  if (!agents.find((x) => x.name === agentName)) {
700
702
  return { error: `Unknown agent: ${agentName}` };
@@ -716,7 +718,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
716
718
  };
717
719
  const buildSeqStep = (s: SequentialStep, sessionFile?: string, behaviorCwd?: string, progressPrecreated = false, resolvedBehavior?: ResolvedStepBehavior, flatIndex?: number, parallelOutputNamespace?: { stepIndex: number; taskIndex?: number }, runFanoutPath?: string) => {
718
720
  const a = agents.find((x) => x.name === s.agent)!;
719
- const externalRunner = a.runner?.type === "external-cli";
721
+ const externalRunner = a.runner?.type === "external-cli" || a.runner?.type === "external-job";
722
+ const externalRunnerType = a.runner?.type;
720
723
  if (externalRunner) {
721
724
  const unsupported: string[] = [];
722
725
  if (s.model !== undefined) unsupported.push("model override");
@@ -724,7 +727,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
724
727
  if (s.acceptance !== undefined || params.agentContract !== undefined || s.agentContract !== undefined) unsupported.push("acceptance/agent contract");
725
728
  if (s.toolBudget !== undefined || params.toolBudget !== undefined || a.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
726
729
  if (params.contextForAgent?.(s.agent) === "fork") unsupported.push("fork context");
727
- if (unsupported.length > 0) throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='external-cli' and does not support: ${unsupported.join(", ")}.`);
730
+ if (unsupported.length > 0) throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
728
731
  }
729
732
  try {
730
733
  assertAgentAllowedByCapabilityCeiling(a.name, intersectSubagentCapabilityCeilings(params.capabilityCeiling, decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV])));
@@ -815,7 +818,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
815
818
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
816
819
  const permissionRules = resolvePermissionRules(ctx.permissions, a.permissions);
817
820
  if (externalRunner && permissionRules) {
818
- throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='external-cli', which cannot enforce native Pi child permission rules.`);
821
+ throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='${externalRunnerType}', which cannot enforce native Pi child permission rules.`);
819
822
  }
820
823
  return {
821
824
  parentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,
@@ -835,7 +838,10 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
835
838
  model,
836
839
  thinking: resolveEffectiveThinking(model, effectiveThinking),
837
840
  launchResolvedExtensions,
838
- modelCandidates: externalRunner ? undefined : buildModelCandidates(primaryModel, a.fallbackModels, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope }).map((candidate) =>
841
+ modelCandidates: externalRunner ? undefined : buildModelCandidates(primaryModel, a.fallbackModels, availableModels, ctx.currentModelProvider, {
842
+ scope: ctx.modelScope,
843
+ primaryModelFromParent: inheritsParentModel(s.model, a.model, ctx.currentModel),
844
+ }).map((candidate) =>
839
845
  applyThinkingSuffix(candidate, effectiveThinking, thinkingOverride !== undefined),
840
846
  ),
841
847
  tools: a.tools,
@@ -872,6 +878,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
872
878
  ...(s.outputSchema ? { structuredOutputSchema: s.outputSchema } : {}),
873
879
  ...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, "structured-output")) } : {}),
874
880
  ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
881
+ ...(s.worktree ? { worktree: true } : {}),
875
882
  };
876
883
  };
877
884
 
@@ -890,9 +897,6 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
890
897
 
891
898
  try {
892
899
  const builtSteps = chain.map((s, stepIndex) => {
893
- if (isCheckpointStep(s)) {
894
- return { checkpoint: s.checkpoint, ...(s.message ? { message: s.message } : {}), phase: s.phase, label: s.label };
895
- }
896
900
  if (isParallelStep(s)) {
897
901
  const parallelBehaviors = s.parallel.map((task) => {
898
902
  const agent = agents.find((candidate) => candidate.name === task.agent)!;
@@ -958,8 +962,17 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
958
962
  ...(s.gateOn ? { gateOn: s.gateOn } : {}),
959
963
  };
960
964
  }
965
+ const sequential = s as SequentialStep;
966
+ let behaviorCwd: string | undefined;
967
+ if (sequential.worktree) {
968
+ try {
969
+ behaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, 0, worktreeBaseDir);
970
+ } catch {
971
+ behaviorCwd = undefined;
972
+ }
973
+ }
961
974
  const staticStep = nextFlatStep();
962
- return buildSeqStep(s as SequentialStep, staticStep.sessionFile, undefined, false, undefined, staticStep.index, undefined, `chain[${stepIndex}]`);
975
+ return buildSeqStep(sequential, staticStep.sessionFile, behaviorCwd, false, undefined, staticStep.index, undefined, `chain[${stepIndex}]`);
963
976
  });
964
977
  const steps = params.attachRoot
965
978
  ? [{
@@ -1028,7 +1041,6 @@ export function executeAsyncChain(
1028
1041
  const resultMode = params.resultMode ?? "chain";
1029
1042
  const acceptanceErrors = validateExecutionAcceptance({
1030
1043
  chain: chain.map((step) => {
1031
- if (isCheckpointStep(step)) return {};
1032
1044
  if (isParallelStep(step)) return { parallel: step.parallel };
1033
1045
  if (isDynamicParallelStep(step)) return { acceptance: step.acceptance, parallel: step.parallel };
1034
1046
  return { acceptance: step.acceptance };
@@ -1127,6 +1139,7 @@ export function executeAsyncChain(
1127
1139
  sessionDir: sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined,
1128
1140
  asyncDir,
1129
1141
  sessionId: ctx.currentSessionId,
1142
+ completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1130
1143
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1131
1144
  piPackageRoot,
1132
1145
  piArgv1: process.argv[1],
@@ -1253,6 +1266,7 @@ export function executeAsyncChain(
1253
1266
  id,
1254
1267
  pid: spawnResult.pid,
1255
1268
  sessionId: ctx.currentSessionId,
1269
+ completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1256
1270
  mode: resultMode,
1257
1271
  agent: firstAgents[0],
1258
1272
  agents: flatAgents,
@@ -1323,7 +1337,8 @@ export function executeAsyncSingle(
1323
1337
  const task = params.task ?? "";
1324
1338
  const acceptanceErrors = validateAcceptanceInput(params.acceptance);
1325
1339
  if (acceptanceErrors.length > 0) return formatAsyncStartError("single", acceptanceErrors.join(" "));
1326
- const externalRunner = agentConfig.runner?.type === "external-cli";
1340
+ const externalRunner = agentConfig.runner?.type === "external-cli" || agentConfig.runner?.type === "external-job";
1341
+ const externalRunnerType = agentConfig.runner?.type;
1327
1342
  const permissionRules = resolvePermissionRules(ctx.permissions, agentConfig.permissions);
1328
1343
  if (externalRunner) {
1329
1344
  const unsupported: string[] = [];
@@ -1335,7 +1350,7 @@ export function executeAsyncSingle(
1335
1350
  if (params.context === "fork") unsupported.push("fork context");
1336
1351
  if ((params.skills?.length ?? 0) > 0) unsupported.push("skills");
1337
1352
  if (permissionRules) unsupported.push("native Pi child permissions");
1338
- if (unsupported.length > 0) return formatAsyncStartError("single", `Agent '${agentConfig.name}' uses runner.type='external-cli' and does not support: ${unsupported.join(", ")}.`);
1353
+ if (unsupported.length > 0) return formatAsyncStartError("single", `Agent '${agentConfig.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
1339
1354
  }
1340
1355
  const capabilityCeiling = intersectSubagentCapabilityCeilings(params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId), decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]));
1341
1356
  try {
@@ -1344,6 +1359,10 @@ export function executeAsyncSingle(
1344
1359
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1345
1360
  }
1346
1361
  const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
1362
+ const instructionCwd = params.worktree === true
1363
+ ? resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s0`, 0, worktreeBaseDir)
1364
+ : runnerCwd;
1365
+ const readExistenceCwd = params.worktree === true ? runnerCwd : instructionCwd;
1347
1366
  const skillNames = params.skills ?? agentConfig.skills ?? [];
1348
1367
  const availableModels = params.availableModels;
1349
1368
  const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
@@ -1385,26 +1404,28 @@ export function executeAsyncSingle(
1385
1404
  }
1386
1405
 
1387
1406
  const effectiveOutput = normalizeSingleOutputOverride(params.output, agentConfig.output);
1388
- const outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, runnerCwd, params.outputBaseDir ?? (artifactsDir ? path.join(artifactsDir, "outputs", id) : undefined));
1407
+ const outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, instructionCwd, params.outputBaseDir ?? (artifactsDir ? path.join(artifactsDir, "outputs", id) : undefined));
1389
1408
  systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, agentConfig);
1390
- const outputMode = params.outputMode ?? "inline";
1409
+ const outputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
1391
1410
  const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
1392
1411
  if (validationError) return formatAsyncStartError("single", validationError);
1393
1412
  const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig);
1394
1413
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
1395
1414
  // absolute paths pass through; relative paths resolve against the child cwd.
1396
1415
  const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
1397
- const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, runnerCwd) : [];
1416
+ const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, readExistenceCwd) : [];
1398
1417
  const readsInstruction = readPaths.length > 0
1399
1418
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
1400
1419
  : "";
1401
1420
  const taskText = readsInstruction + taskWithOutputInstruction;
1402
- const primaryModel = externalRunner ? undefined : resolveSubagentModelOverride(
1403
- params.modelOverride ?? agentConfig.model,
1404
- ctx.currentModel,
1405
- availableModels,
1406
- ctx.currentModelProvider,
1407
- );
1421
+ const primaryModel = externalRunner ? undefined : params.modelOverrideFromParent
1422
+ ? params.modelOverride
1423
+ : resolveSubagentModelOverride(
1424
+ params.modelOverride ?? agentConfig.model,
1425
+ ctx.currentModel,
1426
+ availableModels,
1427
+ ctx.currentModelProvider,
1428
+ );
1408
1429
  const effectiveThinking = externalRunner ? undefined : params.thinkingOverride ?? agentConfig.thinking;
1409
1430
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);
1410
1431
  const toolBudgetInput = params.toolBudget ?? agentConfig.toolBudget ?? params.configToolBudget;
@@ -1431,7 +1452,10 @@ export function executeAsyncSingle(
1431
1452
  : undefined;
1432
1453
  const modelCandidates = externalRunner
1433
1454
  ? []
1434
- : buildModelCandidates(primaryModel, agentConfig.fallbackModels, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope })
1455
+ : buildModelCandidates(primaryModel, agentConfig.fallbackModels, availableModels, ctx.currentModelProvider, {
1456
+ scope: ctx.modelScope,
1457
+ primaryModelFromParent: params.modelOverrideFromParent,
1458
+ })
1435
1459
  .flatMap((candidate) => {
1436
1460
  const resolved = applyThinkingSuffix(candidate, effectiveThinking, params.thinkingOverride !== undefined);
1437
1461
  return resolved ? [resolved] : [];
@@ -1489,6 +1513,7 @@ export function executeAsyncSingle(
1489
1513
  ...(sessionFile ? { sessionFile } : {}),
1490
1514
  cwd: runnerCwd,
1491
1515
  ...(model ? { model } : {}),
1516
+ ...(params.modelOverrideFromParent ? { modelOverrideFromParent: true } : {}),
1492
1517
  ...(recoveryAgentConfig.fallbackModels ? { fallbackModels: [...recoveryAgentConfig.fallbackModels] } : {}),
1493
1518
  ...(effectiveThinking ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1494
1519
  ...(recoveryAgentConfig.tools ? { tools: [...recoveryAgentConfig.tools] } : {}),
@@ -1509,6 +1534,7 @@ export function executeAsyncSingle(
1509
1534
  ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
1510
1535
  ...(params.acceptance !== undefined ? { acceptance: params.acceptance } : {}),
1511
1536
  ...(controlConfig ? { controlConfig } : {}),
1537
+ ...(params.context ? { context: params.context } : {}),
1512
1538
  ...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
1513
1539
  ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
1514
1540
  ...(initialTurnBudget ? { initialTurnBudget: { maxTurns: initialTurnBudget.maxTurns, graceTurns: initialTurnBudget.graceTurns } } : {}),
@@ -1570,6 +1596,7 @@ export function executeAsyncSingle(
1570
1596
  ...(structuredOutput ? { structuredOutput } : {}),
1571
1597
  ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
1572
1598
  ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
1599
+ ...(params.worktree === true ? { worktree: true } : {}),
1573
1600
  },
1574
1601
  ],
1575
1602
  resultPath: params.parentWorkflowRunId !== undefined && params.revivalLease !== undefined
@@ -1584,6 +1611,7 @@ export function executeAsyncSingle(
1584
1611
  sessionDir: resolvedSessionDir,
1585
1612
  asyncDir,
1586
1613
  sessionId: ctx.currentSessionId,
1614
+ completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1587
1615
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1588
1616
  piPackageRoot,
1589
1617
  piArgv1: process.argv[1],
@@ -1677,6 +1705,7 @@ export function executeAsyncSingle(
1677
1705
  id,
1678
1706
  pid: spawnResult.pid,
1679
1707
  sessionId: ctx.currentSessionId,
1708
+ completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1680
1709
  mode: "single",
1681
1710
  agent,
1682
1711
  task: task?.trim() ? PROMPT_REDACTED : undefined,