@xzzpig/pi-subagents 0.1.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 (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,1574 @@
1
+ /**
2
+ * Async execution logic for subagent tool
3
+ */
4
+
5
+ import { spawn } from "node:child_process";
6
+ import { randomUUID } from "node:crypto";
7
+ import * as fs from "node:fs";
8
+ import * as os from "node:os";
9
+ import * as path from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { createRequire } from "node:module";
12
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
+ import type { AgentConfig } from "../../agents/agents.ts";
14
+ import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts";
15
+ import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
16
+ import { applyThinkingSuffix, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/pi-args.ts";
17
+ import { injectOutputPathSystemPrompt, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
18
+ import { buildChainInstructions, isCheckpointStep, isDynamicParallelStep, isParallelStep, resolveChainPath, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile, type ChainStep, type ResolvedStepBehavior, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
19
+ import type { RunnerStep } from "../shared/parallel-utils.ts";
20
+ import type { ContextMode } from "../shared/context-mode.ts";
21
+ import { resolvePiPackageRoot } from "../shared/pi-spawn.ts";
22
+ import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.ts";
23
+ import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
24
+ import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, resolveChildCwd } from "../../shared/utils.ts";
25
+ import { buildModelCandidates, resolveEffectiveSubagentModel, resolveModelCandidate, resolveSubagentModelOverride, type AvailableModelInfo, type ParentModel } from "../shared/model-fallback.ts";
26
+ import type { ModelScopeConfig } from "../shared/model-scope.ts";
27
+ import { resolveEffectiveThinking } from "../../shared/model-info.ts";
28
+ import { resolveExpectedWorktreeAgentCwd } from "../shared/worktree.ts";
29
+ import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.ts";
30
+ import { ChainOutputValidationError, validateChainOutputBindings } from "../shared/chain-outputs.ts";
31
+ import { createStructuredOutputRuntime } from "../shared/structured-output.ts";
32
+ import { resolveEffectiveAcceptance, validateAcceptanceInput, validateExecutionAcceptance } from "../shared/acceptance.ts";
33
+ import {
34
+ type AcceptanceInput,
35
+ type AgentContract,
36
+ type ArtifactConfig,
37
+ type Details,
38
+ type JsonSchemaObject,
39
+ type MaxOutputConfig,
40
+ type NestedRouteInfo,
41
+ type ResolvedControlConfig,
42
+ type ResolvedTurnBudget,
43
+ type ResolvedToolBudget,
44
+ type ToolBudgetConfig,
45
+ type SubagentRunMode,
46
+ type SteeringRecoveryDescriptor,
47
+ type UsageBudgetConfig,
48
+ DIRS,
49
+ SUBAGENT_ASYNC_STARTED_EVENT,
50
+ SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
51
+ TEMP_ROOT_DIR,
52
+ getAsyncConfigPath,
53
+ resolveChildMaxSubagentDepth,
54
+ } from "../../shared/types.ts";
55
+ import { nestedResultsPath, nestedSummaryFromAsyncStatus, resolveInheritedNestedRouteFromEnv, resolveNestedParentAddressFromEnv, writeNestedEvent } from "../shared/nested-events.ts";
56
+ import { appendTurnBudgetSystemPrompt, initialTurnBudgetState } from "../shared/turn-budget.ts";
57
+ import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
58
+ import { usageBudgetState } from "../shared/usage-budget.ts";
59
+ import type { ImportedAsyncRoot } from "./chain-root-attachment.ts";
60
+ import type { SessionLeaseRequest } from "../shared/session-lease.ts";
61
+ import { finalizeProcessTerminal, readProcessTerminal } from "./process-terminal.ts";
62
+ import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.ts";
63
+ import { assertAgentAllowedByCapabilityCeiling, decodeSubagentCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
64
+ import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
65
+ import { resolvePermissionRules, type PermissionConfig } from "../shared/permissions.ts";
66
+
67
+ const require = createRequire(import.meta.url);
68
+ const piPackageRoot = resolvePiPackageRoot();
69
+
70
+ function resolveJitiCliFromPackageJson(packageJsonPath: string): string | undefined {
71
+ if (!fs.existsSync(packageJsonPath)) return undefined;
72
+ const packageRoot = path.dirname(packageJsonPath);
73
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as {
74
+ bin?: string | Record<string, string>;
75
+ };
76
+ const binField = pkg.bin;
77
+ const binPath = typeof binField === "string"
78
+ ? binField
79
+ : binField?.jiti ?? Object.values(binField ?? {})[0];
80
+ const candidates = [binPath, "lib/jiti-cli.mjs"].filter((candidate): candidate is string => Boolean(candidate));
81
+ for (const candidate of candidates) {
82
+ const cliPath = path.resolve(packageRoot, candidate);
83
+ if (fs.existsSync(cliPath)) return cliPath;
84
+ }
85
+ return undefined;
86
+ }
87
+
88
+ function resolveJitiCliPath(): string | undefined {
89
+ const candidates: Array<() => string | undefined> = [
90
+ () => require.resolve("jiti/package.json"),
91
+ () => piPackageRoot
92
+ ? createRequire(path.join(piPackageRoot, "package.json")).resolve("jiti/package.json")
93
+ : undefined,
94
+ () => {
95
+ if (!process.argv[1]) return undefined;
96
+ const piEntry = fs.realpathSync(process.argv[1]);
97
+ return createRequire(piEntry).resolve("jiti/package.json");
98
+ },
99
+ () => piPackageRoot ? path.join(piPackageRoot, "node_modules", "jiti", "package.json") : undefined,
100
+ ];
101
+ for (const candidate of candidates) {
102
+ try {
103
+ const packageJsonPath = candidate();
104
+ if (!packageJsonPath) continue;
105
+ const cliPath = resolveJitiCliFromPackageJson(packageJsonPath);
106
+ if (cliPath) return cliPath;
107
+ } catch {
108
+ // Candidate not available in this install, continue probing.
109
+ }
110
+ }
111
+ return undefined;
112
+ }
113
+
114
+ const jitiCliPath = resolveJitiCliPath();
115
+
116
+ interface AsyncExecutionContext {
117
+ pi: ExtensionAPI;
118
+ cwd: string;
119
+ currentSessionId: string;
120
+ /** Parent session id used by permission-system ask forwarding. */
121
+ parentSessionId?: string;
122
+ permissions?: PermissionConfig;
123
+ currentModelProvider?: string;
124
+ currentModel?: ParentModel;
125
+ /** Optional model-scope enforcement resolved from subagent settings. */
126
+ modelScope?: ModelScopeConfig;
127
+ /** Whether the parent session has an interactive UI. */
128
+ interactive?: boolean;
129
+ }
130
+
131
+ interface AsyncChainParams {
132
+ chain: ChainStep[];
133
+ task?: string;
134
+ /** Raw caller-facing goal used only by the started event. */
135
+ goal?: string;
136
+ attachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };
137
+ resultMode?: Exclude<SubagentRunMode, "single">;
138
+ agents: AgentConfig[];
139
+ ctx: AsyncExecutionContext;
140
+ availableModels?: AvailableModelInfo[];
141
+ cwd?: string;
142
+ maxOutput?: MaxOutputConfig;
143
+ artifactsDir?: string;
144
+ artifactConfig: ArtifactConfig;
145
+ shareEnabled: boolean;
146
+ sessionRoot?: string;
147
+ agentContract?: AgentContract;
148
+ chainSkills?: string[];
149
+ sessionFilesByFlatIndex?: (string | undefined)[];
150
+ thinkingOverridesByFlatIndex?: (AgentConfig["thinking"] | undefined)[];
151
+ contextForAgent?: (agentName: string) => ContextMode;
152
+ progressDir?: string;
153
+ dynamicFanoutMaxItems?: number;
154
+ maxSubagentDepth: number;
155
+ waitToolEnabled?: boolean;
156
+ worktreeSetupHook?: string;
157
+ worktreeSetupHookTimeoutMs?: number;
158
+ worktreeBaseDir?: string;
159
+ controlConfig?: ResolvedControlConfig;
160
+ controlIntercomTarget?: string;
161
+ childIntercomTarget?: (agent: string, index: number) => string | undefined;
162
+ nestedRoute?: NestedRouteInfo;
163
+ acceptance?: AcceptanceInput;
164
+ timeoutMs?: number;
165
+ turnBudget?: ResolvedTurnBudget;
166
+ toolBudget?: ResolvedToolBudget;
167
+ usageBudget?: UsageBudgetConfig;
168
+ configToolBudget?: ResolvedToolBudget;
169
+ /** Global cap on simultaneously-running subagent tasks within the async run. */
170
+ globalConcurrencyLimit?: number;
171
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
172
+ parentWorkflowRunId?: string;
173
+ workflowKey?: string;
174
+ }
175
+
176
+ interface AsyncSingleParams {
177
+ agent: string;
178
+ task?: string;
179
+ /** Raw caller-facing goal used only by the started event. */
180
+ goal?: string;
181
+ agentConfig: AgentConfig;
182
+ ctx: AsyncExecutionContext;
183
+ cwd?: string;
184
+ maxOutput?: MaxOutputConfig;
185
+ artifactsDir?: string;
186
+ artifactConfig: ArtifactConfig;
187
+ shareEnabled: boolean;
188
+ sessionRoot?: string;
189
+ sessionDir?: string;
190
+ sessionFile?: string;
191
+ revivalLease?: SessionLeaseRequest;
192
+ context?: ContextMode;
193
+ skills?: string[];
194
+ output?: string | boolean;
195
+ reads?: string[] | false;
196
+ outputMode?: "inline" | "file-only";
197
+ outputBaseDir?: string;
198
+ agentContract?: AgentContract;
199
+ structuredOutputSchema?: JsonSchemaObject;
200
+ modelOverride?: string;
201
+ thinkingOverride?: AgentConfig["thinking"];
202
+ availableModels?: AvailableModelInfo[];
203
+ maxSubagentDepth: number;
204
+ waitToolEnabled?: boolean;
205
+ worktreeSetupHook?: string;
206
+ worktreeSetupHookTimeoutMs?: number;
207
+ worktreeBaseDir?: string;
208
+ controlConfig?: ResolvedControlConfig;
209
+ controlIntercomTarget?: string;
210
+ childIntercomTarget?: (agent: string, index: number) => string | undefined;
211
+ nestedRoute?: NestedRouteInfo;
212
+ acceptance?: AcceptanceInput;
213
+ timeoutMs?: number;
214
+ absoluteDeadlineAt?: number;
215
+ turnBudget?: { maxTurns: number; graceTurns?: number };
216
+ toolBudget?: ResolvedToolBudget | ToolBudgetConfig;
217
+ usageBudget?: UsageBudgetConfig;
218
+ configToolBudget?: ResolvedToolBudget;
219
+ allowZeroToolBudget?: boolean;
220
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
221
+ parentWorkflowRunId?: string;
222
+ workflowKey?: string;
223
+ }
224
+
225
+ interface AsyncExecutionResult {
226
+ content: Array<{ type: "text"; text: string }>;
227
+ details: Details;
228
+ isError?: boolean;
229
+ }
230
+
231
+ export interface AsyncRunnerStepBuildParams {
232
+ chain: ChainStep[];
233
+ task?: string;
234
+ attachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };
235
+ resultMode?: SubagentRunMode;
236
+ agents: AgentConfig[];
237
+ ctx: AsyncExecutionContext;
238
+ availableModels?: AvailableModelInfo[];
239
+ cwd?: string;
240
+ chainSkills?: string[];
241
+ sessionFilesByFlatIndex?: (string | undefined)[];
242
+ thinkingOverridesByFlatIndex?: (AgentConfig["thinking"] | undefined)[];
243
+ contextForAgent?: (agentName: string) => ContextMode;
244
+ progressDir?: string;
245
+ agentContract?: AgentContract;
246
+ dynamicFanoutMaxItems?: number;
247
+ maxSubagentDepth: number;
248
+ waitToolEnabled?: boolean;
249
+ worktreeBaseDir?: string;
250
+ asyncDir: string;
251
+ outputBaseDir?: string;
252
+ validateOutputBindings?: boolean;
253
+ toolBudget?: ResolvedToolBudget;
254
+ configToolBudget?: ResolvedToolBudget;
255
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
256
+ }
257
+
258
+ export type AsyncRunnerStepBuildResult =
259
+ | {
260
+ steps: RunnerStep[];
261
+ runnerCwd: string;
262
+ workflowGraph: ReturnType<typeof buildWorkflowGraphSnapshot>;
263
+ eventChain: ChainStep[];
264
+ originalTask?: string;
265
+ }
266
+ | { error: string };
267
+
268
+ export function formatAsyncStartedMessage(headline: string, interactive: boolean): string {
269
+ const guidance = interactive
270
+ ? [
271
+ "The async run is detached and running in the background.",
272
+ "You are in an interactive session. By default, return control to the user now; Pi will wake you on completion when the run finishes or needs attention. Do NOT call subagent_wait() merely to wait, and do not run sleep/polling loops to wait for it.",
273
+ "When you need an explicit wake for one known run but do not need same-turn results, call subagent_wait({ id: \"...\", nonBlocking: true }) to arm a subscription and return immediately.",
274
+ "Override the default and call blocking subagent_wait() before ending the turn only when the current request is run-to-completion — for example, the user asked you to report results back here before continuing, or a skill must finish in one turn. In that case, call subagent_wait() to block until the run completes so its results are delivered in this turn instead of deferred.",
275
+ "Otherwise, continue any independent work or return control to the user. Use subagent({ action: \"status\", id: \"...\" }) for a one-shot status/result or to inspect a blocked/stale run, never as a wait loop.",
276
+ ]
277
+ : [
278
+ "The async run is detached. Do not run sleep timers or polling loops just to wait for it.",
279
+ "This is a non-interactive run: Pi auto-drains current-session background work at agent_end so detached children are not abandoned; call subagent_wait() when this turn must receive the run's results before it ends, otherwise let the headless auto-drain finish the work.",
280
+ "Use subagent({ action: \"status\", id: \"...\" }) when you need a one-shot status/result or to inspect a blocked/stale run. To block until completion, use subagent_wait() — do not poll in a loop.",
281
+ ];
282
+ return [headline, "", ...guidance].join("\n");
283
+ }
284
+
285
+ /**
286
+ * Check if jiti is available for async execution
287
+ */
288
+ export function isAsyncAvailable(): boolean {
289
+ return jitiCliPath !== undefined;
290
+ }
291
+
292
+ function isNodeExecutableName(execPath: string): boolean {
293
+ const basename = path.basename(execPath).toLowerCase();
294
+ return basename === "node" || basename === "node.exe" || basename === "nodejs" || basename === "nodejs.exe";
295
+ }
296
+
297
+ function canUseCurrentNodeExecutable(execPath: string): boolean {
298
+ try {
299
+ fs.accessSync(execPath, process.platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
300
+ return true;
301
+ } catch {
302
+ return false;
303
+ }
304
+ }
305
+
306
+ function resolveAsyncRunnerNodeCommand(): string {
307
+ if (isNodeExecutableName(process.execPath) && canUseCurrentNodeExecutable(process.execPath)) {
308
+ return process.execPath;
309
+ }
310
+ return process.platform === "win32" ? "node.exe" : "node";
311
+ }
312
+
313
+ export function resolveAsyncRunnerLogPaths(cfg: object): { stdoutPath: string; stderrPath: string } | undefined {
314
+ const asyncDir = typeof (cfg as { asyncDir?: unknown }).asyncDir === "string"
315
+ ? (cfg as { asyncDir: string }).asyncDir
316
+ : undefined;
317
+ if (!asyncDir) return undefined;
318
+ return {
319
+ stdoutPath: path.join(asyncDir, "runner.stdout.log"),
320
+ stderrPath: path.join(asyncDir, "runner.stderr.log"),
321
+ };
322
+ }
323
+
324
+ function closeFd(fd: number | undefined): void {
325
+ if (fd === undefined) return;
326
+ try {
327
+ fs.closeSync(fd);
328
+ } catch {
329
+ // Best-effort cleanup; child process already owns its duplicated stdio fd.
330
+ }
331
+ }
332
+
333
+ /**
334
+ * Spawn the async runner process
335
+ */
336
+ const RUNNER_STARTUP_TIMEOUT_MS = 10_000;
337
+ const RUNNER_STARTUP_WAIT_BUFFER = typeof SharedArrayBuffer !== "undefined" ? new SharedArrayBuffer(4) : undefined;
338
+ const RUNNER_STARTUP_WAIT_VIEW = RUNNER_STARTUP_WAIT_BUFFER ? new Int32Array(RUNNER_STARTUP_WAIT_BUFFER) : undefined;
339
+
340
+ type RunnerStartupState = "ready" | "acknowledged";
341
+
342
+ type RunnerStartupWaitResult =
343
+ | { ok: true; token: string }
344
+ | { ok: false; error: string };
345
+
346
+ function waitForStartupInterval(delayMs = 20): void {
347
+ if (RUNNER_STARTUP_WAIT_VIEW) {
348
+ Atomics.wait(RUNNER_STARTUP_WAIT_VIEW, 0, 0, delayMs);
349
+ return;
350
+ }
351
+ const waitUntil = Date.now() + delayMs;
352
+ while (Date.now() < waitUntil) {
353
+ // Startup handshakes are synchronous so resume rejects before reporting a run as started.
354
+ }
355
+ }
356
+
357
+ function readRunnerStartup(startupPath: string, expectedState: RunnerStartupState, expectedToken?: string): RunnerStartupWaitResult | undefined {
358
+ if (!fs.existsSync(startupPath)) return undefined;
359
+ try {
360
+ const payload = JSON.parse(fs.readFileSync(startupPath, "utf-8")) as { state?: unknown; token?: unknown; error?: unknown };
361
+ if (payload.state === "error" && typeof payload.error === "string") return { ok: false, error: payload.error };
362
+ if (payload.state !== expectedState) return undefined;
363
+ if (typeof payload.token !== "string" || (expectedToken !== undefined && payload.token !== expectedToken)) {
364
+ return { ok: false, error: `Async runner wrote an invalid ${expectedState} startup handshake: ${startupPath}` };
365
+ }
366
+ return { ok: true, token: payload.token };
367
+ } catch (error) {
368
+ return { ok: false, error: `Failed to read async runner startup handshake '${startupPath}': ${error instanceof Error ? error.message : String(error)}` };
369
+ }
370
+ }
371
+
372
+ function waitForRunnerStartup(startupPath: string, expectedState: RunnerStartupState, timeoutMs: number, expectedToken?: string): RunnerStartupWaitResult {
373
+ const deadline = Date.now() + timeoutMs;
374
+ for (;;) {
375
+ const result = readRunnerStartup(startupPath, expectedState, expectedToken);
376
+ if (result) return result;
377
+ if (Date.now() >= deadline) break;
378
+ waitForStartupInterval(Math.min(20, Math.max(1, deadline - Date.now())));
379
+ }
380
+ const finalResult = readRunnerStartup(startupPath, expectedState, expectedToken);
381
+ if (finalResult) return finalResult;
382
+ return { ok: false, error: `Timed out after ${timeoutMs}ms waiting for the async runner startup state '${expectedState}'.` };
383
+ }
384
+
385
+ function writeRunnerStartupControl(filePath: string, payload: { action: "ack" | "proceed"; token: string }): void {
386
+ // Delegate to the shared atomic JSON writer (temp file + rename, retrying
387
+ // transient Windows EPERM/EBUSY/EACCES locks and cleaning up the temp file
388
+ // on failure), so the startup handshake gets the same locking resilience as
389
+ // every other async control/result file. This is exercised by
390
+ // test/unit/atomic-json.test.ts.
391
+ writePrivateAtomicJson(filePath, payload);
392
+ }
393
+
394
+ function runnerIsAlive(pid: number): boolean {
395
+ try {
396
+ process.kill(pid, 0);
397
+ return true;
398
+ } catch (error) {
399
+ return (error as NodeJS.ErrnoException).code === "EPERM";
400
+ }
401
+ }
402
+
403
+ function terminateRunnerBeforeProceed(pid: number): void {
404
+ for (const signal of ["SIGTERM", "SIGKILL"] as const) {
405
+ if (!runnerIsAlive(pid)) return;
406
+ try {
407
+ process.kill(pid, signal);
408
+ } catch {
409
+ if (!runnerIsAlive(pid)) return;
410
+ }
411
+ const deadline = Date.now() + 1000;
412
+ while (runnerIsAlive(pid) && Date.now() < deadline) waitForStartupInterval();
413
+ }
414
+ }
415
+
416
+ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal?: (proof: unknown) => void): { pid?: number; error?: string } {
417
+ if (!jitiCliPath) {
418
+ return { error: "upstream jiti for TypeScript execution could not be found; ensure package dependencies are installed" };
419
+ }
420
+
421
+ try {
422
+ const cwdStats = fs.statSync(cwd);
423
+ if (!cwdStats.isDirectory()) {
424
+ return { error: `cwd is not a directory: ${cwd}` };
425
+ }
426
+ } catch {
427
+ return { error: `cwd does not exist: ${cwd}` };
428
+ }
429
+
430
+ fs.mkdirSync(TEMP_ROOT_DIR, { recursive: true });
431
+ const cfgPath = getAsyncConfigPath(suffix);
432
+ const runnerProcessInstanceId = randomUUID();
433
+ const launchConfig = { ...cfg, runnerProcessInstanceId };
434
+ fs.writeFileSync(cfgPath, JSON.stringify(launchConfig));
435
+ const runner = path.join(path.dirname(fileURLToPath(import.meta.url)), "subagent-runner.ts");
436
+ const nodeCommand = resolveAsyncRunnerNodeCommand();
437
+ const launchForStartup = launchConfig as typeof launchConfig & { asyncDir?: unknown; revivalLease?: unknown };
438
+ const launchAsyncDir = typeof launchForStartup.asyncDir === "string" ? launchForStartup.asyncDir : undefined;
439
+ const startupPath = typeof launchForStartup.revivalLease === "object" && launchAsyncDir
440
+ ? path.join(launchAsyncDir, "runner-startup.json")
441
+ : undefined;
442
+ const startupAckPath = startupPath ? path.join(path.dirname(startupPath), "runner-startup-ack.json") : undefined;
443
+ const startupProceedPath = startupPath ? path.join(path.dirname(startupPath), "runner-startup-proceed.json") : undefined;
444
+ if (startupPath) fs.rmSync(startupPath, { force: true });
445
+ if (startupAckPath) fs.rmSync(startupAckPath, { force: true });
446
+ if (startupProceedPath) fs.rmSync(startupProceedPath, { force: true });
447
+
448
+ const logPaths = resolveAsyncRunnerLogPaths(launchConfig);
449
+ let stdoutFd: number | undefined;
450
+ let stderrFd: number | undefined;
451
+ try {
452
+ if (logPaths) {
453
+ fs.mkdirSync(path.dirname(logPaths.stdoutPath), { recursive: true });
454
+ stdoutFd = fs.openSync(logPaths.stdoutPath, "a");
455
+ stderrFd = fs.openSync(logPaths.stderrPath, "a");
456
+ }
457
+ const proc = spawn(nodeCommand, [jitiCliPath, runner, cfgPath], {
458
+ cwd,
459
+ detached: true,
460
+ stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
461
+ windowsHide: true,
462
+ env: {
463
+ ...process.env,
464
+ ...(piPackageRoot ? { [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot } : {}),
465
+ },
466
+ });
467
+ closeFd(stdoutFd);
468
+ closeFd(stderrFd);
469
+ proc.on("error", (error) => {
470
+ console.error(`[pi-subagents] async spawn failed: ${error.message}`);
471
+ });
472
+ proc.once("close", (exitCode, signal) => {
473
+ const launch = launchConfig as { asyncDir?: unknown; id?: unknown; nestedRoute?: NestedRouteInfo; nestedSelf?: { parentRunId: string; parentStepIndex?: number; depth: number; path?: Array<{ runId: string; stepIndex?: number; agent?: string }> } };
474
+ const asyncDir = launch.asyncDir;
475
+ const runId = launch.id;
476
+ if (typeof asyncDir !== "string" || typeof runId !== "string") return;
477
+ finalizeProcessTerminal(asyncDir, runId, {
478
+ processInstanceId: runnerProcessInstanceId,
479
+ closeObservedAt: Date.now(),
480
+ exitCode,
481
+ signal,
482
+ });
483
+ const persisted = readProcessTerminal(asyncDir, { runId, runnerProcessInstanceId });
484
+ if (!persisted) return;
485
+ if (launch.nestedRoute && launch.nestedSelf) {
486
+ try {
487
+ let status: import("../../shared/types.ts").AsyncStatus;
488
+ try {
489
+ status = JSON.parse(fs.readFileSync(path.join(asyncDir, "status.json"), "utf-8")) as import("../../shared/types.ts").AsyncStatus;
490
+ status.processTerminal = persisted;
491
+ } catch {
492
+ status = {
493
+ runId,
494
+ mode: "single",
495
+ state: persisted.state === "observed" ? "complete" : "failed",
496
+ startedAt: persisted.observedAt ?? Date.now(),
497
+ lastUpdate: Date.now(),
498
+ processTerminal: persisted,
499
+ };
500
+ }
501
+ writeNestedEvent(launch.nestedRoute, {
502
+ type: "subagent.nested.completed",
503
+ ts: Date.now(),
504
+ parentRunId: launch.nestedSelf.parentRunId,
505
+ parentStepIndex: launch.nestedSelf.parentStepIndex,
506
+ child: nestedSummaryFromAsyncStatus(status, asyncDir, {
507
+ id: runId,
508
+ parentRunId: launch.nestedSelf.parentRunId,
509
+ parentStepIndex: launch.nestedSelf.parentStepIndex,
510
+ depth: launch.nestedSelf.depth,
511
+ path: launch.nestedSelf.path,
512
+ mode: status.mode,
513
+ ts: Date.now(),
514
+ }),
515
+ });
516
+ } catch (error) {
517
+ console.error("Failed to emit final nested process-terminal status:", error);
518
+ }
519
+ }
520
+ onProcessTerminal?.(persisted);
521
+ });
522
+ if (typeof proc.pid !== "number") {
523
+ return { error: `async runner did not produce a pid for cwd: ${cwd}` };
524
+ }
525
+ proc.unref();
526
+ if (startupPath && startupAckPath && startupProceedPath) {
527
+ const ready = waitForRunnerStartup(startupPath, "ready", RUNNER_STARTUP_TIMEOUT_MS);
528
+ if (ready.ok === false) {
529
+ terminateRunnerBeforeProceed(proc.pid);
530
+ return { error: ready.error };
531
+ }
532
+ try {
533
+ writeRunnerStartupControl(startupAckPath, { action: "ack", token: ready.token });
534
+ } catch (error) {
535
+ terminateRunnerBeforeProceed(proc.pid);
536
+ return { error: `Failed to acknowledge async runner startup: ${error instanceof Error ? error.message : String(error)}` };
537
+ }
538
+ const acknowledged = waitForRunnerStartup(startupPath, "acknowledged", RUNNER_STARTUP_TIMEOUT_MS, ready.token);
539
+ if (acknowledged.ok === false) {
540
+ terminateRunnerBeforeProceed(proc.pid);
541
+ return { error: acknowledged.error };
542
+ }
543
+ try {
544
+ writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: ready.token });
545
+ } catch (error) {
546
+ terminateRunnerBeforeProceed(proc.pid);
547
+ return { error: `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}` };
548
+ }
549
+ try {
550
+ fs.rmSync(startupPath, { force: true });
551
+ } catch {
552
+ // Proceed is the commit point; handshake cleanup cannot turn a running revival into a start error.
553
+ }
554
+ }
555
+ return { pid: proc.pid };
556
+ } catch (error) {
557
+ closeFd(stdoutFd);
558
+ closeFd(stderrFd);
559
+ return { error: error instanceof Error ? error.message : String(error) };
560
+ }
561
+ }
562
+
563
+ function formatAsyncStartError(mode: SubagentRunMode, message: string): AsyncExecutionResult {
564
+ return {
565
+ content: [{ type: "text", text: message }],
566
+ isError: true,
567
+ details: { mode, results: [] },
568
+ };
569
+ }
570
+
571
+ const UNAVAILABLE_SUBAGENT_SKILL_ERROR = "Skills not found: pi-subagents";
572
+
573
+ class UnavailableSubagentSkillError extends Error {}
574
+ class AsyncStartValidationError extends Error {}
575
+
576
+ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildParams): AsyncRunnerStepBuildResult {
577
+ const {
578
+ chain,
579
+ agents,
580
+ ctx,
581
+ cwd,
582
+ sessionFilesByFlatIndex,
583
+ thinkingOverridesByFlatIndex,
584
+ maxSubagentDepth,
585
+ worktreeBaseDir,
586
+ asyncDir,
587
+ } = params;
588
+ const outputBaseDir = params.outputBaseDir;
589
+ const resultMode = params.resultMode ?? "chain";
590
+ const chainSkills = params.chainSkills ?? [];
591
+ const availableModels = params.availableModels;
592
+ const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
593
+ const progressDir = params.progressDir ?? runnerCwd;
594
+ const graphChain: ChainStep[] = params.attachRoot
595
+ ? [{
596
+ agent: params.attachRoot.agent,
597
+ task: `Attach async root ${params.attachRoot.runId}`,
598
+ label: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,
599
+ ...(params.attachRoot.outputName ? { as: params.attachRoot.outputName } : {}),
600
+ }, ...chain]
601
+ : chain;
602
+ const firstStep = chain[0];
603
+ const originalTask = params.task ?? (firstStep
604
+ ? (isCheckpointStep(firstStep)
605
+ ? undefined
606
+ : isParallelStep(firstStep)
607
+ ? firstStep.parallel[0]?.task
608
+ : isDynamicParallelStep(firstStep)
609
+ ? firstStep.parallel.task
610
+ : (firstStep as SequentialStep).task)
611
+ : undefined);
612
+ try {
613
+ if (params.validateOutputBindings !== false) {
614
+ validateChainOutputBindings(chain, { maxItems: params.dynamicFanoutMaxItems });
615
+ }
616
+ } catch (error) {
617
+ if (error instanceof ChainOutputValidationError) return { error: error.message };
618
+ throw error;
619
+ }
620
+ const workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: graphChain });
621
+
622
+ for (const s of chain) {
623
+ const stepAgents = isCheckpointStep(s)
624
+ ? []
625
+ : isParallelStep(s)
626
+ ? s.parallel.map((t) => t.agent)
627
+ : isDynamicParallelStep(s)
628
+ ? [s.parallel.agent]
629
+ : [(s as SequentialStep).agent];
630
+ for (const agentName of stepAgents) {
631
+ if (!agents.find((x) => x.name === agentName)) {
632
+ return { error: `Unknown agent: ${agentName}` };
633
+ }
634
+ }
635
+ }
636
+
637
+ let progressInstructionCreated = false;
638
+ const buildStepOverrides = (s: SequentialStep): StepOverrides => {
639
+ const stepSkillInput = normalizeSkillInput(s.skill);
640
+ return {
641
+ ...(s.output !== undefined ? { output: s.output } : {}),
642
+ ...(s.outputMode !== undefined ? { outputMode: s.outputMode } : {}),
643
+ ...(s.reads !== undefined ? { reads: s.reads } : {}),
644
+ ...(s.progress !== undefined ? { progress: s.progress } : {}),
645
+ ...(stepSkillInput !== undefined ? { skills: stepSkillInput } : {}),
646
+ ...(s.model !== undefined ? { model: s.model } : {}),
647
+ };
648
+ };
649
+ const buildSeqStep = (s: SequentialStep, sessionFile?: string, behaviorCwd?: string, progressPrecreated = false, resolvedBehavior?: ResolvedStepBehavior, flatIndex?: number, parallelOutputNamespace?: { stepIndex: number; taskIndex?: number }) => {
650
+ const a = agents.find((x) => x.name === s.agent)!;
651
+ const externalRunner = a.runner?.type === "external-cli";
652
+ if (externalRunner) {
653
+ const unsupported: string[] = [];
654
+ if (s.model !== undefined) unsupported.push("model override");
655
+ if (s.outputSchema !== undefined) unsupported.push("structured output");
656
+ if (s.acceptance !== undefined || params.agentContract !== undefined || s.agentContract !== undefined) unsupported.push("acceptance/agent contract");
657
+ if (s.toolBudget !== undefined || params.toolBudget !== undefined || a.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
658
+ if (params.contextForAgent?.(s.agent) === "fork") unsupported.push("fork context");
659
+ if (unsupported.length > 0) throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='external-cli' and does not support: ${unsupported.join(", ")}.`);
660
+ }
661
+ try {
662
+ assertAgentAllowedByCapabilityCeiling(a.name, intersectSubagentCapabilityCeilings(params.capabilityCeiling, decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV])));
663
+ } catch (error) {
664
+ throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
665
+ }
666
+ const toolBudgetInput = s.toolBudget ?? params.toolBudget ?? a.toolBudget ?? params.configToolBudget;
667
+ const resolvedToolBudget = validateToolBudgetConfig(toolBudgetInput, s.toolBudget ? "toolBudget" : a.toolBudget ? "agent.toolBudget" : "config.toolBudget");
668
+ if (resolvedToolBudget.error) throw new AsyncStartValidationError(resolvedToolBudget.error);
669
+ const stepCwd = resolveChildCwd(runnerCwd, s.cwd);
670
+ const instructionCwd = behaviorCwd ?? stepCwd;
671
+ let behavior = suppressProgressForReadOnlyTask(resolvedBehavior ?? resolveStepBehavior(a, buildStepOverrides(s), chainSkills), s.task, originalTask);
672
+ const inheritedRelativeParallelOutput = parallelOutputNamespace && s.output === undefined && typeof behavior.output === "string" && !path.isAbsolute(behavior.output);
673
+ if (inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex !== undefined) {
674
+ behavior = {
675
+ ...behavior,
676
+ output: path.join(`parallel-${parallelOutputNamespace.stepIndex}`, `${parallelOutputNamespace.taskIndex}-${s.agent}`, behavior.output as string),
677
+ };
678
+ }
679
+ const namespaceOutputPath = Boolean(inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex === undefined);
680
+ const skillNames = behavior.skills === false ? [] : behavior.skills;
681
+ const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
682
+ skillNames,
683
+ stepCwd,
684
+ ctx.cwd,
685
+ a.skillPath,
686
+ a.filePath ? path.dirname(a.filePath) : stepCwd,
687
+ );
688
+ if (missingSkills.includes("pi-subagents")) throw new UnavailableSubagentSkillError(UNAVAILABLE_SUBAGENT_SKILL_ERROR);
689
+
690
+ let systemPrompt = a.systemPrompt?.trim() ?? "";
691
+ if (resolvedSkills.length > 0) {
692
+ const injection = buildSkillInjection(resolvedSkills);
693
+ systemPrompt = systemPrompt ? `${systemPrompt}\n\n${injection}` : injection;
694
+ }
695
+ const memoryInjection = buildAgentMemoryInjection(a, stepCwd);
696
+ if (memoryInjection) {
697
+ systemPrompt = systemPrompt ? `${systemPrompt}\n\n${memoryInjection}` : memoryInjection;
698
+ }
699
+ systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: stepCwd, agentName: a.name });
700
+
701
+ const readInstructions = buildChainInstructions({ ...behavior, output: false, progress: false }, instructionCwd, false);
702
+ const isFirstProgressAgent = behavior.progress && !progressPrecreated && !progressInstructionCreated;
703
+ if (behavior.progress) progressInstructionCreated = true;
704
+ const progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, progressDir, isFirstProgressAgent);
705
+ const outputPath = resolveSingleOutputPath(behavior.output, ctx.cwd, instructionCwd, outputBaseDir);
706
+ if (!namespaceOutputPath) systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, a);
707
+ const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Async step (${s.agent})`);
708
+ if (validationError) throw new AsyncStartValidationError(validationError);
709
+ let taskTemplate = s.task ?? "{previous}";
710
+ taskTemplate = taskTemplate.replace(/\{task\}/g, originalTask ?? "");
711
+ taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, runnerCwd);
712
+ const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
713
+ const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
714
+
715
+ const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(
716
+ s.model,
717
+ a.model,
718
+ ctx.currentModel,
719
+ availableModels,
720
+ ctx.currentModelProvider,
721
+ { scope: ctx.modelScope },
722
+ );
723
+ const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
724
+ const effectiveThinking = externalRunner ? undefined : thinkingOverride ?? a.thinking;
725
+ const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);
726
+ const agentContract = s.agentContract ?? params.agentContract;
727
+ const toolPlan = resolvePiLaunchToolPlan({
728
+ tools: a.tools,
729
+ extensions: a.extensions,
730
+ subagentOnlyExtensions: a.subagentOnlyExtensions,
731
+ mcpDirectTools: a.mcpDirectTools,
732
+ cwd: stepCwd,
733
+ requireReadTool: Boolean(resolvedSkills.length),
734
+ structuredOutput: Boolean(s.outputSchema),
735
+ capabilityCeiling: params.capabilityCeiling,
736
+ inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
737
+ agentName: a.name,
738
+ });
739
+ const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
740
+ const permissionRules = resolvePermissionRules(ctx.permissions, a.permissions);
741
+ if (externalRunner && permissionRules) {
742
+ throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='external-cli', which cannot enforce native Pi child permission rules.`);
743
+ }
744
+ return {
745
+ parentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,
746
+ permissionRules,
747
+ ...(params.capabilityCeiling ? { capabilityCeiling: params.capabilityCeiling } : {}),
748
+ agent: s.agent,
749
+ task,
750
+ ...(a.runner ? { runner: a.runner } : {}),
751
+ ...(params.contextForAgent ? { context: params.contextForAgent(s.agent) } : {}),
752
+ ...(agentContract ? { agentContract } : {}),
753
+ phase: s.phase,
754
+ label: s.label,
755
+ outputName: s.as,
756
+ structured: Boolean(s.outputSchema),
757
+ cwd: stepCwd,
758
+ model,
759
+ thinking: resolveEffectiveThinking(model, effectiveThinking),
760
+ launchResolvedExtensions,
761
+ modelCandidates: externalRunner ? undefined : buildModelCandidates(primaryModel, a.fallbackModels, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope }).map((candidate) =>
762
+ applyThinkingSuffix(candidate, effectiveThinking, thinkingOverride !== undefined),
763
+ ),
764
+ tools: a.tools,
765
+ extensions: a.extensions,
766
+ subagentOnlyExtensions: a.subagentOnlyExtensions,
767
+ mcpDirectTools: a.mcpDirectTools,
768
+ completionGuard: a.completionGuard,
769
+ systemPrompt,
770
+ systemPromptMode: a.systemPromptMode,
771
+ inheritProjectContext: a.inheritProjectContext,
772
+ inheritSkills: a.inheritSkills,
773
+ skills: resolvedSkills.map((r) => r.name),
774
+ outputPath,
775
+ ...(namespaceOutputPath ? { namespaceOutputPath: true } : {}),
776
+ outputMode: behavior.outputMode,
777
+ sessionFile,
778
+ maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, a.maxSubagentDepth),
779
+ waitToolEnabled: params.waitToolEnabled,
780
+ effectiveAcceptance: resolveEffectiveAcceptance({
781
+ explicit: s.acceptance,
782
+ agentName: s.agent,
783
+ acceptanceRole: a.acceptanceRole,
784
+ task,
785
+ mode: resultMode,
786
+ async: true,
787
+ dynamic: false,
788
+ agentContract,
789
+ }),
790
+ acceptanceInput: s.acceptance,
791
+ acceptanceRole: a.acceptanceRole,
792
+ ...(s.gateOn ? { gateOn: s.gateOn } : {}),
793
+ ...(s.outputSchema ? { structuredOutputSchema: s.outputSchema } : {}),
794
+ ...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, "structured-output")) } : {}),
795
+ ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
796
+ };
797
+ };
798
+
799
+ let flatStepIndex = 0;
800
+ const nextFlatStep = (): { index: number; sessionFile?: string; thinkingOverride?: AgentConfig["thinking"] } => {
801
+ const index = flatStepIndex;
802
+ const sessionFile = sessionFilesByFlatIndex?.[flatStepIndex];
803
+ const thinkingOverride = thinkingOverridesByFlatIndex?.[flatStepIndex];
804
+ flatStepIndex++;
805
+ return {
806
+ index,
807
+ ...(sessionFile ? { sessionFile } : {}),
808
+ ...(thinkingOverride ? { thinkingOverride } : {}),
809
+ };
810
+ };
811
+
812
+ try {
813
+ const builtSteps = chain.map((s, stepIndex) => {
814
+ if (isCheckpointStep(s)) {
815
+ return { checkpoint: s.checkpoint, ...(s.message ? { message: s.message } : {}), phase: s.phase, label: s.label };
816
+ }
817
+ if (isParallelStep(s)) {
818
+ const parallelBehaviors = s.parallel.map((task) => {
819
+ const agent = agents.find((candidate) => candidate.name === task.agent)!;
820
+ return suppressProgressForReadOnlyTask(resolveStepBehavior(agent, buildStepOverrides(task), chainSkills), task.task, originalTask);
821
+ });
822
+ const progressPrecreated = parallelBehaviors.some((behavior) => behavior.progress);
823
+ if (progressPrecreated) {
824
+ if (!s.worktree || params.progressDir) writeInitialProgressFile(progressDir);
825
+ progressInstructionCreated = true;
826
+ }
827
+ return {
828
+ parallel: s.parallel.map((t, taskIndex) => {
829
+ let behaviorCwd: string | undefined;
830
+ if (s.worktree) {
831
+ try {
832
+ behaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, taskIndex, worktreeBaseDir);
833
+ } catch {
834
+ behaviorCwd = undefined;
835
+ }
836
+ }
837
+ const staticStep = nextFlatStep();
838
+ return buildSeqStep({ ...t, agentContract: t.agentContract ?? s.agentContract, gateOn: t.gateOn ?? s.gateOn }, staticStep.sessionFile, behaviorCwd, progressPrecreated, parallelBehaviors[taskIndex], staticStep.index, { stepIndex, taskIndex });
839
+ }),
840
+ concurrency: s.concurrency,
841
+ failFast: s.failFast,
842
+ worktree: s.worktree,
843
+ };
844
+ }
845
+ if (isDynamicParallelStep(s)) {
846
+ const agent = agents.find((candidate) => candidate.name === s.parallel.agent)!;
847
+ const behavior = suppressProgressForReadOnlyTask(resolveStepBehavior(agent, buildStepOverrides(s.parallel), chainSkills), s.parallel.task, originalTask);
848
+ const progressPrecreated = behavior.progress;
849
+ if (progressPrecreated) {
850
+ writeInitialProgressFile(progressDir);
851
+ progressInstructionCreated = true;
852
+ }
853
+ const maxItems = s.expand.maxItems ?? params.dynamicFanoutMaxItems ?? 0;
854
+ const dynamicFlatSteps = Array.from({ length: maxItems }, () => nextFlatStep());
855
+ const parallel = buildSeqStep({ ...(s.parallel as SequentialStep), agentContract: s.parallel.agentContract ?? s.agentContract, gateOn: s.parallel.gateOn ?? s.gateOn }, undefined, undefined, progressPrecreated, behavior, undefined, { stepIndex });
856
+ return {
857
+ expand: s.expand,
858
+ parallel,
859
+ collect: s.collect,
860
+ concurrency: s.concurrency,
861
+ failFast: s.failFast,
862
+ phase: s.phase,
863
+ label: s.label,
864
+ sessionFiles: dynamicFlatSteps.map((step) => step.sessionFile),
865
+ thinkingOverrides: dynamicFlatSteps.map((step) => step.thinkingOverride),
866
+ effectiveAcceptance: resolveEffectiveAcceptance({
867
+ explicit: s.acceptance,
868
+ agentName: s.parallel.agent,
869
+ acceptanceRole: agent.acceptanceRole,
870
+ task: parallel.task,
871
+ mode: resultMode,
872
+ async: true,
873
+ dynamicGroup: true,
874
+ agentContract: s.agentContract ?? params.agentContract,
875
+ }),
876
+ acceptanceInput: s.acceptance,
877
+ acceptanceRole: agent.acceptanceRole,
878
+ ...(s.agentContract ?? params.agentContract ? { agentContract: s.agentContract ?? params.agentContract } : {}),
879
+ ...(s.gateOn ? { gateOn: s.gateOn } : {}),
880
+ };
881
+ }
882
+ const staticStep = nextFlatStep();
883
+ return buildSeqStep(s as SequentialStep, staticStep.sessionFile, undefined, false, undefined, staticStep.index);
884
+ });
885
+ const steps = params.attachRoot
886
+ ? [{
887
+ agent: params.attachRoot.agent,
888
+ task: "",
889
+ label: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,
890
+ outputName: params.attachRoot.outputName,
891
+ importAsyncRoot: {
892
+ runId: params.attachRoot.runId,
893
+ asyncDir: params.attachRoot.asyncDir,
894
+ resultPath: params.attachRoot.resultPath,
895
+ index: params.attachRoot.index,
896
+ },
897
+ inheritProjectContext: false,
898
+ inheritSkills: false,
899
+ }, ...builtSteps]
900
+ : builtSteps;
901
+ for (const step of steps) {
902
+ if (!("parallel" in step) || !Array.isArray(step.parallel)) continue;
903
+ const seen = new Map<string, { index: number; agent: string }>();
904
+ for (let index = 0; index < step.parallel.length; index++) {
905
+ const task = step.parallel[index]!;
906
+ if (!task.outputPath) continue;
907
+ const previous = seen.get(task.outputPath);
908
+ if (previous) {
909
+ throw new AsyncStartValidationError(`Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${task.agent}) resolve output to the same path: ${task.outputPath}. Use distinct output paths.`);
910
+ }
911
+ seen.set(task.outputPath, { index, agent: task.agent });
912
+ }
913
+ }
914
+ return { steps: steps as RunnerStep[], runnerCwd, workflowGraph, eventChain: graphChain, ...(originalTask !== undefined ? { originalTask } : {}) };
915
+ } catch (error) {
916
+ if (error instanceof UnavailableSubagentSkillError || error instanceof AsyncStartValidationError) return { error: error.message };
917
+ throw error;
918
+ }
919
+ }
920
+
921
+ /**
922
+ * Execute a chain asynchronously
923
+ */
924
+ export function executeAsyncChain(
925
+ id: string,
926
+ params: AsyncChainParams,
927
+ ): AsyncExecutionResult {
928
+ const {
929
+ chain,
930
+ agents,
931
+ ctx,
932
+ cwd,
933
+ maxOutput,
934
+ artifactsDir,
935
+ artifactConfig,
936
+ shareEnabled,
937
+ sessionRoot,
938
+ sessionFilesByFlatIndex,
939
+ thinkingOverridesByFlatIndex,
940
+ maxSubagentDepth,
941
+ worktreeSetupHook,
942
+ worktreeSetupHookTimeoutMs,
943
+ worktreeBaseDir,
944
+ controlConfig,
945
+ controlIntercomTarget,
946
+ childIntercomTarget,
947
+ nestedRoute,
948
+ } = params;
949
+ const resultMode = params.resultMode ?? "chain";
950
+ const acceptanceErrors = validateExecutionAcceptance({
951
+ chain: chain.map((step) => {
952
+ if (isCheckpointStep(step)) return {};
953
+ if (isParallelStep(step)) return { parallel: step.parallel };
954
+ if (isDynamicParallelStep(step)) return { acceptance: step.acceptance, parallel: step.parallel };
955
+ return { acceptance: step.acceptance };
956
+ }),
957
+ });
958
+ if (acceptanceErrors.length > 0) return formatAsyncStartError(resultMode, acceptanceErrors.join(" "));
959
+ const capabilityCeiling = params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId);
960
+ const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
961
+ const nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
962
+ const asyncDir = inheritedNestedRoute
963
+ ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
964
+ : path.join(DIRS.async, id);
965
+ try {
966
+ fs.mkdirSync(asyncDir, { recursive: true });
967
+ } catch (error) {
968
+ const message = error instanceof Error ? error.message : String(error);
969
+ return {
970
+ content: [{ type: "text", text: `Failed to create async run directory '${asyncDir}': ${message}` }],
971
+ isError: true,
972
+ details: { mode: resultMode, results: [] },
973
+ };
974
+ }
975
+
976
+ const built = buildAsyncRunnerSteps(id, {
977
+ chain,
978
+ task: params.task,
979
+ attachRoot: params.attachRoot,
980
+ resultMode,
981
+ agents,
982
+ ctx,
983
+ availableModels: params.availableModels,
984
+ cwd,
985
+ chainSkills: params.chainSkills,
986
+ sessionFilesByFlatIndex,
987
+ thinkingOverridesByFlatIndex,
988
+ contextForAgent: params.contextForAgent,
989
+ progressDir: params.progressDir ?? (artifactsDir ? path.join(artifactsDir, "progress", id) : resultMode === "parallel" ? path.join(asyncDir, "progress") : undefined),
990
+ agentContract: params.agentContract,
991
+ outputBaseDir: artifactsDir ? path.join(artifactsDir, "outputs", id) : undefined,
992
+ dynamicFanoutMaxItems: params.dynamicFanoutMaxItems,
993
+ maxSubagentDepth,
994
+ waitToolEnabled: params.waitToolEnabled,
995
+ worktreeBaseDir,
996
+ asyncDir,
997
+ toolBudget: params.toolBudget,
998
+ configToolBudget: params.configToolBudget,
999
+ capabilityCeiling,
1000
+ });
1001
+ if ("error" in built) {
1002
+ try {
1003
+ fs.rmSync(asyncDir, { recursive: true, force: true });
1004
+ } catch {
1005
+ // Best-effort cleanup for validation failures before the runner is spawned.
1006
+ }
1007
+ return formatAsyncStartError(resultMode, built.error);
1008
+ }
1009
+ const { steps, runnerCwd, workflowGraph, eventChain } = built;
1010
+ const deadlineAt = params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined;
1011
+ const initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;
1012
+ const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
1013
+ let childTargetIndex = 0;
1014
+ const childIntercomTargets = childIntercomTarget ? steps.flatMap((step) => {
1015
+ if (!("parallel" in step) && "importAsyncRoot" in step && step.importAsyncRoot) {
1016
+ childTargetIndex++;
1017
+ return [undefined];
1018
+ }
1019
+ if ("parallel" in step) {
1020
+ if (!Array.isArray(step.parallel)) {
1021
+ childTargetIndex++;
1022
+ return [undefined];
1023
+ }
1024
+ return step.parallel.map((task) => childIntercomTarget(task.agent, childTargetIndex++));
1025
+ }
1026
+ return "agent" in step ? [childIntercomTarget(step.agent, childTargetIndex++)] : [undefined];
1027
+ }) : undefined;
1028
+
1029
+ let spawnResult: { pid?: number; error?: string } = {};
1030
+ try {
1031
+ spawnResult = spawnRunner(
1032
+ {
1033
+ id,
1034
+ steps,
1035
+ resultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(DIRS.results, `${id}.json`),
1036
+ cwd: runnerCwd,
1037
+ placeholder: "{previous}",
1038
+ maxOutput,
1039
+ artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
1040
+ artifactConfig,
1041
+ share: shareEnabled,
1042
+ sessionDir: sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined,
1043
+ asyncDir,
1044
+ sessionId: ctx.currentSessionId,
1045
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
1046
+ piPackageRoot,
1047
+ piArgv1: process.argv[1],
1048
+ worktreeSetupHook,
1049
+ worktreeSetupHookTimeoutMs,
1050
+ worktreeBaseDir,
1051
+ controlConfig,
1052
+ turnBudget: params.turnBudget,
1053
+ toolBudget: params.toolBudget,
1054
+ usageBudget: params.usageBudget,
1055
+ controlIntercomTarget,
1056
+ childIntercomTargets,
1057
+ resultMode,
1058
+ dynamicFanoutMaxItems: params.dynamicFanoutMaxItems,
1059
+ timeoutMs: params.timeoutMs,
1060
+ deadlineAt,
1061
+ globalConcurrencyLimit: params.globalConcurrencyLimit,
1062
+ workflowGraph,
1063
+ ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1064
+ ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
1065
+ nestedRoute: nestedRoute ?? inheritedNestedRoute,
1066
+ nestedSelf: inheritedNestedRoute && nestedAddress ? {
1067
+ parentRunId: nestedAddress.parentRunId,
1068
+ parentStepIndex: nestedAddress.parentStepIndex,
1069
+ depth: nestedAddress.depth,
1070
+ path: nestedAddress.path,
1071
+ } : undefined,
1072
+ },
1073
+ id,
1074
+ runnerCwd,
1075
+ (proof) => ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof),
1076
+ );
1077
+ } catch (error) {
1078
+ const message = error instanceof Error ? error.message : String(error);
1079
+ return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${message}`);
1080
+ }
1081
+
1082
+ if (spawnResult.error) {
1083
+ return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${spawnResult.error}`);
1084
+ }
1085
+
1086
+ if (spawnResult.pid) {
1087
+ const eventFirstStep = eventChain[0];
1088
+ if (!eventFirstStep) {
1089
+ return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': event chain has no steps`);
1090
+ }
1091
+ const firstAgents = isParallelStep(eventFirstStep)
1092
+ ? eventFirstStep.parallel.map((t) => t.agent)
1093
+ : isDynamicParallelStep(eventFirstStep)
1094
+ ? [eventFirstStep.parallel.agent]
1095
+ : [(eventFirstStep as SequentialStep).agent];
1096
+ const firstTask = isParallelStep(eventFirstStep)
1097
+ ? eventFirstStep.parallel[0]?.task
1098
+ : isDynamicParallelStep(eventFirstStep)
1099
+ ? eventFirstStep.parallel.task
1100
+ : (eventFirstStep as SequentialStep).task;
1101
+ const workflowGoal = params.goal ?? (params.task?.trim() || firstTask);
1102
+ const parallelGroups: Array<{ start: number; count: number; stepIndex: number }> = [];
1103
+ const flatAgents: string[] = [];
1104
+ let flatStepStart = 0;
1105
+ for (let stepIndex = 0; stepIndex < eventChain.length; stepIndex++) {
1106
+ const step = eventChain[stepIndex]!;
1107
+ if (isParallelStep(step)) {
1108
+ parallelGroups.push({ start: flatStepStart, count: step.parallel.length, stepIndex });
1109
+ flatAgents.push(...step.parallel.map((task) => task.agent));
1110
+ flatStepStart += step.parallel.length;
1111
+ } else if (isDynamicParallelStep(step)) {
1112
+ parallelGroups.push({ start: flatStepStart, count: 1, stepIndex });
1113
+ flatAgents.push(step.parallel.agent);
1114
+ flatStepStart++;
1115
+ } else {
1116
+ flatAgents.push((step as SequentialStep).agent);
1117
+ flatStepStart++;
1118
+ }
1119
+ }
1120
+ if (inheritedNestedRoute && nestedAddress) {
1121
+ const now = Date.now();
1122
+ try {
1123
+ writeNestedEvent(inheritedNestedRoute, {
1124
+ type: "subagent.nested.started",
1125
+ ts: now,
1126
+ parentRunId: nestedAddress.parentRunId,
1127
+ parentStepIndex: nestedAddress.parentStepIndex,
1128
+ child: {
1129
+ id,
1130
+ parentRunId: nestedAddress.parentRunId,
1131
+ parentStepIndex: nestedAddress.parentStepIndex,
1132
+ depth: nestedAddress.depth,
1133
+ path: nestedAddress.path,
1134
+ asyncDir,
1135
+ pid: spawnResult.pid,
1136
+ ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
1137
+ leafIntercomTarget: childIntercomTargets?.[0],
1138
+ intercomTarget: childIntercomTargets?.[0],
1139
+ ownerState: "live",
1140
+ mode: resultMode,
1141
+ state: "running",
1142
+ agent: firstAgents[0],
1143
+ agents: flatAgents,
1144
+ chainStepCount: eventChain.length,
1145
+ parallelGroups,
1146
+ ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
1147
+ ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1148
+ startedAt: now,
1149
+ lastUpdate: now,
1150
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
1151
+ },
1152
+ });
1153
+ } catch (error) {
1154
+ console.error("Failed to emit nested async start event:", error);
1155
+ }
1156
+ }
1157
+ ctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {
1158
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
1159
+ id,
1160
+ pid: spawnResult.pid,
1161
+ sessionId: ctx.currentSessionId,
1162
+ mode: resultMode,
1163
+ agent: firstAgents[0],
1164
+ agents: flatAgents,
1165
+ task: firstTask?.slice(0, 50),
1166
+ goal: workflowGoal?.slice(0, 120),
1167
+ chain: eventChain.map((s) =>
1168
+ isParallelStep(s) ? `[${s.parallel.map((t) => t.agent).join("+")}]` : isDynamicParallelStep(s) ? `expand:${s.parallel.agent}` : (s as SequentialStep).agent,
1169
+ ),
1170
+ chainStepCount: eventChain.length,
1171
+ parallelGroups,
1172
+ workflowGraph,
1173
+ cwd: runnerCwd,
1174
+ asyncDir,
1175
+ ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
1176
+ ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1177
+ ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
1178
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
1179
+ ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1180
+ ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
1181
+ nestedRoute,
1182
+ });
1183
+ }
1184
+
1185
+ const chainDesc = chain
1186
+ .map((s) =>
1187
+ isParallelStep(s) ? `[${s.parallel.map((t) => t.agent).join("+")}]` : isDynamicParallelStep(s) ? `expand:${s.parallel.agent}` : (s as SequentialStep).agent,
1188
+ )
1189
+ .join(" -> ");
1190
+
1191
+ return {
1192
+ content: [{ type: "text", text: formatAsyncStartedMessage(`Async ${resultMode}: ${chainDesc} [${id}]`, ctx.interactive === true) }],
1193
+ details: { mode: resultMode, runId: id, results: [], asyncId: id, asyncDir, workflowGraph, ...(capabilityCeiling ? { capabilityCeiling } : {}), ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}), ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}), ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}), ...(params.turnBudget ? { turnBudget: params.turnBudget } : {}), ...(params.toolBudget ? { toolBudget: params.toolBudget } : {}), ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}) },
1194
+ };
1195
+ }
1196
+
1197
+ /**
1198
+ * Execute a single agent asynchronously
1199
+ */
1200
+ export function executeAsyncSingle(
1201
+ id: string,
1202
+ params: AsyncSingleParams,
1203
+ ): AsyncExecutionResult {
1204
+ const {
1205
+ agent,
1206
+ agentConfig,
1207
+ ctx,
1208
+ cwd,
1209
+ maxOutput,
1210
+ artifactsDir,
1211
+ artifactConfig,
1212
+ shareEnabled,
1213
+ sessionRoot,
1214
+ sessionFile,
1215
+ maxSubagentDepth,
1216
+ worktreeSetupHook,
1217
+ worktreeSetupHookTimeoutMs,
1218
+ worktreeBaseDir,
1219
+ controlConfig,
1220
+ controlIntercomTarget,
1221
+ childIntercomTarget,
1222
+ nestedRoute,
1223
+ } = params;
1224
+ const task = params.task ?? "";
1225
+ const acceptanceErrors = validateAcceptanceInput(params.acceptance);
1226
+ if (acceptanceErrors.length > 0) return formatAsyncStartError("single", acceptanceErrors.join(" "));
1227
+ const externalRunner = agentConfig.runner?.type === "external-cli";
1228
+ const permissionRules = resolvePermissionRules(ctx.permissions, agentConfig.permissions);
1229
+ if (externalRunner) {
1230
+ const unsupported: string[] = [];
1231
+ if (params.modelOverride !== undefined) unsupported.push("model override");
1232
+ if (params.thinkingOverride !== undefined) unsupported.push("thinking override");
1233
+ if (params.structuredOutputSchema !== undefined) unsupported.push("structured output");
1234
+ if (params.acceptance !== undefined || params.agentContract !== undefined) unsupported.push("acceptance/agent contract");
1235
+ if (params.toolBudget !== undefined || agentConfig.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
1236
+ if (params.context === "fork") unsupported.push("fork context");
1237
+ if ((params.skills?.length ?? 0) > 0) unsupported.push("skills");
1238
+ if (permissionRules) unsupported.push("native Pi child permissions");
1239
+ if (unsupported.length > 0) return formatAsyncStartError("single", `Agent '${agentConfig.name}' uses runner.type='external-cli' and does not support: ${unsupported.join(", ")}.`);
1240
+ }
1241
+ const capabilityCeiling = intersectSubagentCapabilityCeilings(params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId), decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]));
1242
+ try {
1243
+ assertAgentAllowedByCapabilityCeiling(agentConfig.name, capabilityCeiling);
1244
+ } catch (error) {
1245
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1246
+ }
1247
+ const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
1248
+ const skillNames = params.skills ?? agentConfig.skills ?? [];
1249
+ const availableModels = params.availableModels;
1250
+ const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
1251
+ skillNames,
1252
+ runnerCwd,
1253
+ ctx.cwd,
1254
+ agentConfig.skillPath,
1255
+ agentConfig.filePath ? path.dirname(agentConfig.filePath) : runnerCwd,
1256
+ );
1257
+ if (missingSkills.includes("pi-subagents")) return formatAsyncStartError("single", UNAVAILABLE_SUBAGENT_SKILL_ERROR);
1258
+ let systemPrompt = agentConfig.systemPrompt?.trim() ?? "";
1259
+ if (resolvedSkills.length > 0) {
1260
+ const injection = buildSkillInjection(resolvedSkills);
1261
+ systemPrompt = systemPrompt ? `${systemPrompt}\n\n${injection}` : injection;
1262
+ }
1263
+ const memoryInjection = buildAgentMemoryInjection(agentConfig, runnerCwd);
1264
+ if (memoryInjection) {
1265
+ systemPrompt = systemPrompt ? `${systemPrompt}\n\n${memoryInjection}` : memoryInjection;
1266
+ }
1267
+ systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: runnerCwd, agentName: agentConfig.name });
1268
+
1269
+ const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
1270
+ const nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
1271
+ const asyncDir = inheritedNestedRoute
1272
+ ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
1273
+ : path.join(DIRS.async, id);
1274
+ try {
1275
+ fs.mkdirSync(asyncDir, { recursive: true });
1276
+ } catch (error) {
1277
+ const message = error instanceof Error ? error.message : String(error);
1278
+ return {
1279
+ content: [{ type: "text", text: `Failed to create async run directory '${asyncDir}': ${message}` }],
1280
+ isError: true,
1281
+ details: { mode: "single" as const, results: [] },
1282
+ };
1283
+ }
1284
+
1285
+ const effectiveOutput = normalizeSingleOutputOverride(params.output, agentConfig.output);
1286
+ const outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, runnerCwd, params.outputBaseDir ?? (artifactsDir ? path.join(artifactsDir, "outputs", id) : undefined));
1287
+ systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, agentConfig);
1288
+ const outputMode = params.outputMode ?? "inline";
1289
+ const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
1290
+ if (validationError) return formatAsyncStartError("single", validationError);
1291
+ const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig);
1292
+ // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
1293
+ // absolute paths pass through; relative paths resolve against the child cwd.
1294
+ const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
1295
+ const readsInstruction = Array.isArray(reads) && reads.length > 0
1296
+ ? `[Read from: ${reads.map((f) => resolveChainPath(f, runnerCwd)).join(", ")}]\n\n`
1297
+ : "";
1298
+ const taskText = readsInstruction + taskWithOutputInstruction;
1299
+ const primaryModel = externalRunner ? undefined : resolveSubagentModelOverride(
1300
+ params.modelOverride ?? agentConfig.model,
1301
+ ctx.currentModel,
1302
+ availableModels,
1303
+ ctx.currentModelProvider,
1304
+ );
1305
+ const effectiveThinking = externalRunner ? undefined : params.thinkingOverride ?? agentConfig.thinking;
1306
+ const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);
1307
+ const toolBudgetInput = params.toolBudget ?? agentConfig.toolBudget ?? params.configToolBudget;
1308
+ const resolvedToolBudget = validateToolBudgetConfig(toolBudgetInput, params.toolBudget ? "toolBudget" : agentConfig.toolBudget ? "agent.toolBudget" : "config.toolBudget");
1309
+ if (resolvedToolBudget.error) return formatAsyncStartError("single", resolvedToolBudget.error);
1310
+ const deadlineAt = params.absoluteDeadlineAt ?? (params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined);
1311
+ const timeoutMs = params.absoluteDeadlineAt !== undefined && deadlineAt !== undefined
1312
+ ? deadlineAt - Date.now()
1313
+ : params.timeoutMs;
1314
+ if (timeoutMs !== undefined && timeoutMs <= 0) return formatAsyncStartError("single", "The source run's absolute deadline expired before recovery could launch.");
1315
+ const initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;
1316
+ const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
1317
+ const resolvedSessionDir = params.sessionDir ?? (sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined);
1318
+ const structuredOutput = params.structuredOutputSchema
1319
+ ? createStructuredOutputRuntime(params.structuredOutputSchema, path.join(asyncDir, "structured-output"))
1320
+ : undefined;
1321
+ const modelCandidates = buildModelCandidates(primaryModel, agentConfig.fallbackModels, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope })
1322
+ .flatMap((candidate) => {
1323
+ const resolved = applyThinkingSuffix(candidate, effectiveThinking, params.thinkingOverride !== undefined);
1324
+ return resolved ? [resolved] : [];
1325
+ });
1326
+ const effectiveSystemPrompt = appendTurnBudgetSystemPrompt(systemPrompt, params.turnBudget);
1327
+ const toolPlan = resolvePiLaunchToolPlan({
1328
+ tools: agentConfig.tools,
1329
+ extensions: agentConfig.extensions,
1330
+ subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
1331
+ mcpDirectTools: agentConfig.mcpDirectTools,
1332
+ cwd: runnerCwd,
1333
+ requireReadTool: Boolean(resolvedSkills.length),
1334
+ structuredOutput: Boolean(params.structuredOutputSchema),
1335
+ capabilityCeiling,
1336
+ inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
1337
+ agentName: agentConfig.name,
1338
+ });
1339
+ const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
1340
+ const launchContractDigest = launchBindingDigest({
1341
+ definitionDigest: agentDefinitionDigest(agentConfig),
1342
+ task,
1343
+ ...(model ? { model } : {}),
1344
+ modelCandidates,
1345
+ ...(resolveEffectiveThinking(model, effectiveThinking) ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1346
+ systemPrompt: effectiveSystemPrompt,
1347
+ systemPromptMode: agentConfig.systemPromptMode,
1348
+ inheritProjectContext: agentConfig.inheritProjectContext,
1349
+ inheritSkills: agentConfig.inheritSkills,
1350
+ skills: resolvedSkills.map((skill) => skill.name),
1351
+ tools: toolPlan.effectiveToolAllowlist,
1352
+ extensions: toolPlan.extensionArgs,
1353
+ mcpDirectTools: toolPlan.effectiveMcpTools,
1354
+ ...(outputPath ? { outputPath } : {}),
1355
+ outputMode,
1356
+ ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
1357
+ });
1358
+ const resolvedAcceptance = resolveEffectiveAcceptance({
1359
+ explicit: params.acceptance,
1360
+ agentName: agent,
1361
+ acceptanceRole: agentConfig.acceptanceRole,
1362
+ task,
1363
+ mode: "single",
1364
+ async: true,
1365
+ agentContract: params.agentContract,
1366
+ });
1367
+ const recoveryDescriptor: SteeringRecoveryDescriptor = {
1368
+ version: 1,
1369
+ launchContractDigest,
1370
+ sourceRunId: id,
1371
+ ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1372
+ agent,
1373
+ launchResolvedExtensions,
1374
+ ...(sessionFile ? { sessionFile } : {}),
1375
+ cwd: runnerCwd,
1376
+ ...(model ? { model } : {}),
1377
+ ...(agentConfig.fallbackModels ? { fallbackModels: [...agentConfig.fallbackModels] } : {}),
1378
+ ...(effectiveThinking ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1379
+ ...(agentConfig.tools ? { tools: [...agentConfig.tools] } : {}),
1380
+ ...(agentConfig.extensions ? { extensions: [...agentConfig.extensions] } : {}),
1381
+ ...(agentConfig.subagentOnlyExtensions ? { subagentOnlyExtensions: [...agentConfig.subagentOnlyExtensions] } : {}),
1382
+ ...(agentConfig.mcpDirectTools ? { mcpDirectTools: [...agentConfig.mcpDirectTools] } : {}),
1383
+ ...(agentConfig.systemPrompt ? { systemPrompt: agentConfig.systemPrompt } : {}),
1384
+ systemPromptMode: agentConfig.systemPromptMode,
1385
+ inheritProjectContext: agentConfig.inheritProjectContext,
1386
+ inheritSkills: agentConfig.inheritSkills,
1387
+ ...(resolvedSkills.length ? { skills: resolvedSkills.map((skill) => skill.name) } : {}),
1388
+ ...(agentConfig.skillPath ? { skillPath: [...agentConfig.skillPath] } : {}),
1389
+ ...(agentConfig.filePath ? { agentFilePath: agentConfig.filePath } : {}),
1390
+ ...(agentConfig.completionGuard !== undefined ? { completionGuard: agentConfig.completionGuard } : {}),
1391
+ ...(agentConfig.memory ? { memory: { ...agentConfig.memory } } : {}),
1392
+ ...(outputPath ? { outputPath } : {}),
1393
+ outputMode,
1394
+ ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
1395
+ ...(params.acceptance !== undefined ? { acceptance: params.acceptance } : {}),
1396
+ ...(controlConfig ? { controlConfig } : {}),
1397
+ ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
1398
+ ...(initialTurnBudget ? { initialTurnBudget } : {}),
1399
+ ...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
1400
+ maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, agentConfig.maxSubagentDepth),
1401
+ ...(maxOutput ? { maxOutput } : {}),
1402
+ share: shareEnabled,
1403
+ ...(resolvedSessionDir ? { sessionDir: resolvedSessionDir } : {}),
1404
+ ...(artifactsDir ? { artifactsDir } : {}),
1405
+ artifactConfig,
1406
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
1407
+ };
1408
+ if (!externalRunner) {
1409
+ try {
1410
+ writePrivateAtomicJson(path.join(asyncDir, "recovery-descriptor.json"), recoveryDescriptor);
1411
+ } catch (error) {
1412
+ return formatAsyncStartError("single", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);
1413
+ }
1414
+ }
1415
+ let spawnResult: { pid?: number; error?: string } = {};
1416
+ try {
1417
+ spawnResult = spawnRunner(
1418
+ {
1419
+ id,
1420
+ steps: [
1421
+ {
1422
+ parentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,
1423
+ permissionRules,
1424
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
1425
+ agent,
1426
+ task: taskText,
1427
+ ...(agentConfig.runner ? { runner: agentConfig.runner } : {}),
1428
+ ...(params.context ? { context: params.context } : {}),
1429
+ cwd: runnerCwd,
1430
+ model,
1431
+ thinking: resolveEffectiveThinking(model, effectiveThinking),
1432
+ modelCandidates,
1433
+ tools: agentConfig.tools,
1434
+ extensions: agentConfig.extensions,
1435
+ subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
1436
+ mcpDirectTools: agentConfig.mcpDirectTools,
1437
+ completionGuard: agentConfig.completionGuard,
1438
+ systemPrompt,
1439
+ systemPromptMode: agentConfig.systemPromptMode,
1440
+ inheritProjectContext: agentConfig.inheritProjectContext,
1441
+ inheritSkills: agentConfig.inheritSkills,
1442
+ skills: resolvedSkills.map((r) => r.name),
1443
+ outputPath,
1444
+ outputMode,
1445
+ ...(!externalRunner && sessionFile ? { sessionFile } : {}),
1446
+ maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, agentConfig.maxSubagentDepth),
1447
+ waitToolEnabled: params.waitToolEnabled,
1448
+ ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1449
+ definitionDigest: agentDefinitionDigest(agentConfig),
1450
+ launchBindingTask: task,
1451
+ launchContractDigest,
1452
+ launchResolvedExtensions,
1453
+ effectiveAcceptance: resolvedAcceptance,
1454
+ ...(structuredOutput ? { structuredOutput } : {}),
1455
+ ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
1456
+ ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
1457
+ },
1458
+ ],
1459
+ resultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(DIRS.results, `${id}.json`),
1460
+ cwd: runnerCwd,
1461
+ placeholder: "{previous}",
1462
+ maxOutput,
1463
+ artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
1464
+ artifactConfig,
1465
+ share: shareEnabled,
1466
+ sessionDir: resolvedSessionDir,
1467
+ asyncDir,
1468
+ sessionId: ctx.currentSessionId,
1469
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
1470
+ piPackageRoot,
1471
+ piArgv1: process.argv[1],
1472
+ worktreeSetupHook,
1473
+ worktreeSetupHookTimeoutMs,
1474
+ worktreeBaseDir,
1475
+ controlConfig,
1476
+ timeoutMs,
1477
+ deadlineAt,
1478
+ turnBudget: params.turnBudget,
1479
+ toolBudget: params.toolBudget,
1480
+ usageBudget: params.usageBudget,
1481
+ controlIntercomTarget,
1482
+ childIntercomTargets: childIntercomTarget ? [childIntercomTarget(agent, 0)] : undefined,
1483
+ resultMode: "single",
1484
+ launchContractDigest,
1485
+ launchResolvedExtensions,
1486
+ ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1487
+ ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
1488
+ ...(params.revivalLease ? { revivalLease: params.revivalLease } : {}),
1489
+ nestedRoute: nestedRoute ?? inheritedNestedRoute,
1490
+ nestedSelf: inheritedNestedRoute && nestedAddress ? {
1491
+ parentRunId: nestedAddress.parentRunId,
1492
+ parentStepIndex: nestedAddress.parentStepIndex,
1493
+ depth: nestedAddress.depth,
1494
+ path: nestedAddress.path,
1495
+ } : undefined,
1496
+ },
1497
+ id,
1498
+ runnerCwd,
1499
+ (proof) => ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof),
1500
+ );
1501
+ } catch (error) {
1502
+ const message = error instanceof Error ? error.message : String(error);
1503
+ return formatAsyncStartError("single", `Failed to start async run '${id}': ${message}`);
1504
+ }
1505
+
1506
+ if (spawnResult.error) {
1507
+ return formatAsyncStartError("single", `Failed to start async run '${id}': ${spawnResult.error}`);
1508
+ }
1509
+
1510
+ if (spawnResult.pid) {
1511
+ if (inheritedNestedRoute && nestedAddress) {
1512
+ const now = Date.now();
1513
+ try {
1514
+ writeNestedEvent(inheritedNestedRoute, {
1515
+ type: "subagent.nested.started",
1516
+ ts: now,
1517
+ parentRunId: nestedAddress.parentRunId,
1518
+ parentStepIndex: nestedAddress.parentStepIndex,
1519
+ child: {
1520
+ id,
1521
+ parentRunId: nestedAddress.parentRunId,
1522
+ parentStepIndex: nestedAddress.parentStepIndex,
1523
+ depth: nestedAddress.depth,
1524
+ path: nestedAddress.path,
1525
+ asyncDir,
1526
+ pid: spawnResult.pid,
1527
+ ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
1528
+ leafIntercomTarget: childIntercomTarget?.(agent, 0),
1529
+ intercomTarget: childIntercomTarget?.(agent, 0),
1530
+ ownerState: "live",
1531
+ mode: "single",
1532
+ state: "running",
1533
+ agent,
1534
+ agents: [agent],
1535
+ chainStepCount: 1,
1536
+ ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
1537
+ ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1538
+ startedAt: now,
1539
+ lastUpdate: now,
1540
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
1541
+ },
1542
+ });
1543
+ } catch (error) {
1544
+ console.error("Failed to emit nested async start event:", error);
1545
+ }
1546
+ }
1547
+ ctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {
1548
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
1549
+ id,
1550
+ pid: spawnResult.pid,
1551
+ sessionId: ctx.currentSessionId,
1552
+ mode: "single",
1553
+ agent,
1554
+ task: task?.slice(0, 50),
1555
+ goal: (params.goal ?? task).slice(0, 120),
1556
+ cwd: runnerCwd,
1557
+ asyncDir,
1558
+ launchContractDigest,
1559
+ launchResolvedExtensions,
1560
+ ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1561
+ ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
1562
+ ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
1563
+ ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1564
+ ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
1565
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
1566
+ nestedRoute,
1567
+ });
1568
+ }
1569
+
1570
+ return {
1571
+ content: [{ type: "text", text: formatAsyncStartedMessage(`Async: ${agent} [${id}]`, ctx.interactive === true) }],
1572
+ details: { mode: "single", runId: id, results: [], asyncId: id, asyncDir, launchContractDigest, launchResolvedExtensions, ...(capabilityCeiling ? { capabilityCeiling } : {}), ...(params.context ? { context: params.context } : {}), ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}), ...(params.turnBudget ? { turnBudget: params.turnBudget } : {}), ...(params.toolBudget ? { toolBudget: resolvedToolBudget.budget ?? params.toolBudget } : {}), ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}) } as Details,
1573
+ };
1574
+ }