@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,808 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import {
7
+ encodeNestedPathEnv,
8
+ parseNestedPathEnv,
9
+ type NestedPathEntry,
10
+ } from "./nested-path.ts";
11
+ import {
12
+ resolveMcpDirectToolSelections,
13
+ type ResolvedMcpDirectToolSelection,
14
+ } from "./mcp-direct-tool-allowlist.ts";
15
+ import { resolvePiPackageRoot } from "./pi-spawn.ts";
16
+ import { RUNTIME_EXTENSION_ACK_PATH_ENV } from "./runtime-acknowledged-extensions.ts";
17
+ import {
18
+ STRUCTURED_OUTPUT_CAPTURE_ENV,
19
+ STRUCTURED_OUTPUT_SCHEMA_ENV,
20
+ } from "./structured-output.ts";
21
+ import {
22
+ TEMP_ROOT_DIR,
23
+ type JsonSchemaObject,
24
+ type LaunchResolvedChildExtensionsV1,
25
+ type ResolvedToolBudget,
26
+ } from "../../shared/types.ts";
27
+ import { THINKING_LEVELS } from "../../shared/model-info.ts";
28
+ import {
29
+ TOOL_BUDGET_ENV,
30
+ TOOL_BUDGET_ZERO_AUTH_ENV,
31
+ encodeToolBudgetEnv,
32
+ } from "./tool-budget.ts";
33
+ import {
34
+ CHILD_TOOL_DIAGNOSTIC_PATH_ENV,
35
+ MCP_DIRECT_CHILD_TOOLS_ENV,
36
+ REQUIRED_CHILD_TOOLS_ENV,
37
+ } from "./tool-availability.ts";
38
+ import {
39
+ CHILD_WATCHDOG_CONFIG_ENV,
40
+ encodeChildWatchdogConfig,
41
+ type ChildWatchdogConfig,
42
+ } from "../../watchdog/child-status.ts";
43
+ import { WAIT_TOOL_ENABLED_ENV } from "../background/wait-config.ts";
44
+ import {
45
+ PI_CODING_AGENT_PACKAGE_ROOT_ENV,
46
+ getAgentDir,
47
+ } from "../../shared/utils.ts";
48
+ import {
49
+ encodePermissionRules,
50
+ PERMISSION_AUDIT_PATH_ENV,
51
+ PERMISSION_POLICY_ENV,
52
+ type PermissionRules,
53
+ } from "./permissions.ts";
54
+ import {
55
+ SUBAGENT_CAPABILITY_CEILING_ENV,
56
+ capabilityCeilingAgentRestrictionSources,
57
+ decodeSubagentCapabilityCeiling,
58
+ encodeSubagentCapabilityCeiling,
59
+ intersectSubagentCapabilityCeilings,
60
+ isAgentAllowedByCapabilityCeiling,
61
+ type ResolvedSubagentCapabilityCeiling,
62
+ type SubagentCapabilityAudit,
63
+ } from "./capability-ceiling.ts";
64
+
65
+ const TASK_ARG_LIMIT = 8000;
66
+ const MAX_LAUNCH_RESOLVED_EXTENSION_IDS = 32;
67
+ const PROMPT_RUNTIME_EXTENSION_PATH = path.join(
68
+ path.dirname(fileURLToPath(import.meta.url)),
69
+ "subagent-prompt-runtime.ts",
70
+ );
71
+ const FANOUT_CHILD_EXTENSION_PATH = path.join(
72
+ path.dirname(fileURLToPath(import.meta.url)),
73
+ "..",
74
+ "..",
75
+ "extension",
76
+ "fanout-child.ts",
77
+ );
78
+ export const SUBAGENT_CHILD_ENV = "PI_SUBAGENT_CHILD";
79
+ export const SUBAGENT_ORCHESTRATOR_TARGET_ENV =
80
+ "PI_SUBAGENT_ORCHESTRATOR_TARGET";
81
+ export const SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV =
82
+ "PI_SUBAGENT_ORCHESTRATOR_SESSION_ID";
83
+ export const SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV =
84
+ "PI_SUBAGENT_SUPERVISOR_CHANNEL_DIR";
85
+ export const SUBAGENT_RUN_ID_ENV = "PI_SUBAGENT_RUN_ID";
86
+ export const SUBAGENT_CHILD_AGENT_ENV = "PI_SUBAGENT_CHILD_AGENT";
87
+ export const SUBAGENT_CHILD_INDEX_ENV = "PI_SUBAGENT_CHILD_INDEX";
88
+ export const SUBAGENT_FANOUT_CHILD_ENV = "PI_SUBAGENT_FANOUT_CHILD";
89
+ export const SUBAGENT_PARENT_EVENT_SINK_ENV = "PI_SUBAGENT_PARENT_EVENT_SINK";
90
+ export const SUBAGENT_PARENT_CONTROL_INBOX_ENV =
91
+ "PI_SUBAGENT_PARENT_CONTROL_INBOX";
92
+ export const SUBAGENT_PARENT_ROOT_RUN_ID_ENV = "PI_SUBAGENT_PARENT_ROOT_RUN_ID";
93
+ export const SUBAGENT_PARENT_RUN_ID_ENV = "PI_SUBAGENT_PARENT_RUN_ID";
94
+ export const SUBAGENT_PARENT_CHILD_INDEX_ENV = "PI_SUBAGENT_PARENT_CHILD_INDEX";
95
+ export const SUBAGENT_PARENT_DEPTH_ENV = "PI_SUBAGENT_PARENT_DEPTH";
96
+ export const SUBAGENT_PARENT_PATH_ENV = "PI_SUBAGENT_PARENT_PATH";
97
+ export const SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV =
98
+ "PI_SUBAGENT_PARENT_CAPABILITY_TOKEN";
99
+ export const SUBAGENT_PARENT_SESSION_ENV = "PI_SUBAGENT_PARENT_SESSION";
100
+ export const SUBAGENT_STEER_INBOX_ENV = "PI_SUBAGENT_STEER_INBOX";
101
+ export const SUBAGENT_STEER_CAPABILITY_ENV = "PI_SUBAGENT_STEER_CAPABILITY";
102
+ export const SUBAGENT_STEER_ACK_DIR_ENV = "PI_SUBAGENT_STEER_ACK_DIR";
103
+ export const PI_INTERCOM_STABLE_ID_ENV = "PI_INTERCOM_STABLE_ID";
104
+ export const PI_INTERCOM_SESSION_ID_ENV = "PI_INTERCOM_SESSION_ID";
105
+
106
+ export interface BuildPiArgsInput {
107
+ parentSessionId?: string;
108
+ baseArgs: string[];
109
+ task: string;
110
+ sessionEnabled: boolean;
111
+ sessionDir?: string;
112
+ sessionFile?: string;
113
+ model?: string;
114
+ thinking?: string | false;
115
+ systemPromptMode?: "append" | "replace";
116
+ inheritProjectContext: boolean;
117
+ inheritSkills: boolean;
118
+ requireReadTool?: boolean;
119
+ tools?: string[];
120
+ extensions?: string[];
121
+ subagentOnlyExtensions?: string[];
122
+ systemPrompt?: string | null;
123
+ mcpDirectTools?: string[];
124
+ cwd?: string;
125
+ promptFileStem?: string;
126
+ intercomSessionName?: string;
127
+ orchestratorIntercomTarget?: string;
128
+ runId?: string;
129
+ childAgentName?: string;
130
+ childIndex?: number;
131
+ parentEventSink?: string;
132
+ parentControlInbox?: string;
133
+ parentRootRunId?: string;
134
+ parentRunId?: string;
135
+ parentChildIndex?: number;
136
+ parentDepth?: number;
137
+ parentPath?: NestedPathEntry[];
138
+ parentCapabilityToken?: string;
139
+ steerInboxDir?: string;
140
+ steerCapabilityPath?: string;
141
+ steerAckDir?: string;
142
+ structuredOutput?: {
143
+ schema: JsonSchemaObject;
144
+ schemaPath: string;
145
+ outputPath: string;
146
+ };
147
+ toolBudget?: ResolvedToolBudget;
148
+ allowZeroToolBudget?: boolean;
149
+ permissionRules?: PermissionRules;
150
+ permissionAuditPath?: string;
151
+ childWatchdog?: ChildWatchdogConfig;
152
+ waitToolEnabled?: boolean;
153
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
154
+ }
155
+
156
+ export interface BuildPiArgsResult {
157
+ args: string[];
158
+ env: Record<string, string | undefined>;
159
+ tempDir?: string;
160
+ toolDiagnosticPath?: string;
161
+ runtimeAcknowledgedExtensionsPath?: string;
162
+ capabilityAudit?: SubagentCapabilityAudit;
163
+ }
164
+
165
+ function sanitizeSupervisorChannelSegment(value: string): string {
166
+ return (
167
+ value
168
+ .trim()
169
+ .replace(/[^A-Za-z0-9._-]+/g, "-")
170
+ .replace(/^-+|-+$/g, "") || "unknown"
171
+ );
172
+ }
173
+
174
+ function supervisorChannelDir(
175
+ runId: string,
176
+ agent: string,
177
+ childIndex: number,
178
+ ): string {
179
+ return path.join(
180
+ TEMP_ROOT_DIR,
181
+ "supervisor-channels",
182
+ `${sanitizeSupervisorChannelSegment(runId)}-${sanitizeSupervisorChannelSegment(agent)}-${childIndex}`,
183
+ );
184
+ }
185
+
186
+ export function applyThinkingSuffix(
187
+ model: string | undefined,
188
+ thinking: string | false | undefined,
189
+ replaceExisting = false,
190
+ ): string | undefined {
191
+ if (!model || !thinking) return model;
192
+ const colonIdx = model.lastIndexOf(":");
193
+ if (
194
+ colonIdx !== -1 &&
195
+ THINKING_LEVELS.some((level) => level === model.substring(colonIdx + 1))
196
+ ) {
197
+ return replaceExisting ? `${model.slice(0, colonIdx)}:${thinking}` : model;
198
+ }
199
+ return `${model}:${thinking}`;
200
+ }
201
+
202
+ export interface ResolvePiLaunchToolPlanInput {
203
+ tools?: string[];
204
+ extensions?: string[];
205
+ subagentOnlyExtensions?: string[];
206
+ mcpDirectTools?: string[];
207
+ cwd?: string;
208
+ requireReadTool?: boolean;
209
+ structuredOutput?:
210
+ | boolean
211
+ | {
212
+ schema: JsonSchemaObject;
213
+ schemaPath: string;
214
+ outputPath: string;
215
+ };
216
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
217
+ inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
218
+ agentName?: string;
219
+ }
220
+
221
+ export interface PiLaunchToolPlan {
222
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
223
+ requestedBuiltinTools: string[];
224
+ declaredBuiltinTools: string[];
225
+ toolExtensionPaths: string[];
226
+ resolvedMcpSelections: ResolvedMcpDirectToolSelection[];
227
+ effectiveMcpSelections: ResolvedMcpDirectToolSelection[];
228
+ effectiveMcpTools: string[];
229
+ explicitToolAllowlist: boolean;
230
+ internalTools: string[];
231
+ effectiveToolAllowlist: string[];
232
+ requiredChildTools: string[];
233
+ fanoutAuthorized: boolean;
234
+ runtimeExtensions: string[];
235
+ configuredExtensions: string[];
236
+ extensionArgs: string[];
237
+ disableAmbientExtensions: boolean;
238
+ capabilityAudit?: SubagentCapabilityAudit;
239
+ }
240
+
241
+ function extensionIdentifier(value: string): string {
242
+ return `sha256:${createHash("sha256").update(path.normalize(value.trim())).digest("hex").slice(0, 16)}`;
243
+ }
244
+
245
+ function boundedExtensionIdentifiers(values: string[]): {
246
+ ids: string[];
247
+ omitted: number;
248
+ } {
249
+ const ids = [...new Set(values.map(extensionIdentifier))];
250
+ return {
251
+ ids: ids.slice(0, MAX_LAUNCH_RESOLVED_EXTENSION_IDS),
252
+ omitted: Math.max(0, ids.length - MAX_LAUNCH_RESOLVED_EXTENSION_IDS),
253
+ };
254
+ }
255
+
256
+ export function projectLaunchResolvedChildExtensions(
257
+ toolPlan: Pick<
258
+ PiLaunchToolPlan,
259
+ | "runtimeExtensions"
260
+ | "configuredExtensions"
261
+ | "extensionArgs"
262
+ | "disableAmbientExtensions"
263
+ >,
264
+ ): LaunchResolvedChildExtensionsV1 {
265
+ const runtime = boundedExtensionIdentifiers(toolPlan.runtimeExtensions);
266
+ const configured = boundedExtensionIdentifiers(toolPlan.configuredExtensions);
267
+ const effective = boundedExtensionIdentifiers(toolPlan.extensionArgs);
268
+ return {
269
+ version: 1,
270
+ source: "launch-resolved",
271
+ disableAmbientExtensions: toolPlan.disableAmbientExtensions,
272
+ runtime: runtime.ids,
273
+ configured: configured.ids,
274
+ effective: effective.ids,
275
+ omitted: {
276
+ runtime: runtime.omitted,
277
+ configured: configured.omitted,
278
+ effective: effective.omitted,
279
+ },
280
+ };
281
+ }
282
+
283
+ /**
284
+ * Resolve the permission-system extension entry point when installed.
285
+ * Returns the absolute path to the extension's main module, or undefined
286
+ * when the package is not installed. Callers can check `autoInject` config
287
+ * to decide whether to include it in child processes.
288
+ */
289
+ export function resolvePermissionSystemExtension(): string | undefined {
290
+ const agentDir = getAgentDir();
291
+ const candidates = [
292
+ // @xzzpig fork takes priority so child processes inherit the same
293
+ // permission system the parent session loads from settings.json.
294
+ // When only the upstream package is installed, behavior is unchanged.
295
+ path.join(
296
+ agentDir,
297
+ "npm",
298
+ "node_modules",
299
+ "@xzzpig",
300
+ "pi-permission-system",
301
+ ),
302
+ // npm-scoped package (most common)
303
+ path.join(
304
+ agentDir,
305
+ "npm",
306
+ "node_modules",
307
+ "@gotgenes",
308
+ "pi-permission-system",
309
+ ),
310
+ // direct extension directory (some layouts)
311
+ path.join(agentDir, "extensions", "pi-permission-system"),
312
+ ];
313
+ const errors: Error[] = [];
314
+ for (const extDir of candidates) {
315
+ if (!fs.existsSync(extDir)) continue;
316
+ const pkgPath = path.join(extDir, "package.json");
317
+ if (!fs.existsSync(pkgPath)) {
318
+ errors.push(new Error(`Permission-system package manifest is missing at ${pkgPath}.`));
319
+ continue;
320
+ }
321
+ try {
322
+ let pkg: { pi?: { extensions?: string[] } };
323
+ const parsed: unknown = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
324
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
325
+ throw new Error("manifest root must be an object");
326
+ }
327
+ pkg = parsed as typeof pkg;
328
+ const extensions = pkg.pi?.extensions;
329
+ const entry = Array.isArray(extensions) ? extensions[0] : undefined;
330
+ if (typeof entry !== "string" || !entry.trim()) {
331
+ throw new Error(
332
+ `Permission-system package manifest at ${pkgPath} must declare pi.extensions[0] as a non-empty string.`,
333
+ );
334
+ }
335
+ const resolved = path.resolve(extDir, entry);
336
+ if (fs.existsSync(resolved)) return resolved;
337
+ throw new Error(
338
+ `Permission-system extension entry ${JSON.stringify(entry)} in ${pkgPath} does not exist at ${resolved}.`,
339
+ );
340
+ } catch (error) {
341
+ const message = error instanceof Error ? error.message : String(error);
342
+ errors.push(message.startsWith("Permission-system") ? new Error(message) : new Error(`Cannot read permission-system package manifest at ${pkgPath}: ${message}`));
343
+ }
344
+ }
345
+ if (errors.length > 0) throw errors[0]!;
346
+ return undefined;
347
+ }
348
+
349
+ export function resolvePiLaunchToolPlan(
350
+ input: ResolvePiLaunchToolPlanInput,
351
+ ): PiLaunchToolPlan {
352
+ const capabilityCeiling = intersectSubagentCapabilityCeilings(
353
+ input.capabilityCeiling,
354
+ input.inheritedCapabilityCeiling,
355
+ );
356
+ const allowedToolSet =
357
+ capabilityCeiling?.allowedTools === undefined
358
+ ? undefined
359
+ : new Set(capabilityCeiling.allowedTools);
360
+ const requestedBuiltinTools =
361
+ input.tools?.filter(
362
+ (tool) =>
363
+ !(tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")),
364
+ ) ?? [];
365
+ if (input.requireReadTool && allowedToolSet && !allowedToolSet.has("read")) {
366
+ throw new Error(
367
+ `Capability ceiling from ${capabilityCeiling?.sources.join(", ") || "unknown source"} excludes required tool 'read' for lazy skill loading.`,
368
+ );
369
+ }
370
+ const declaredBuiltinTools =
371
+ input.tools === undefined
372
+ ? allowedToolSet
373
+ ? [...allowedToolSet]
374
+ : []
375
+ : (input.requireReadTool &&
376
+ requestedBuiltinTools.length > 0 &&
377
+ !requestedBuiltinTools.includes("read") &&
378
+ !allowedToolSet
379
+ ? ["read", ...requestedBuiltinTools]
380
+ : requestedBuiltinTools
381
+ ).filter((tool) => !allowedToolSet || allowedToolSet.has(tool));
382
+ const fanoutAuthorized = declaredBuiltinTools.includes("subagent");
383
+ const toolExtensionPaths: string[] = capabilityCeiling?.denyExtensions
384
+ ? []
385
+ : (input.tools ?? []).filter(
386
+ (tool) =>
387
+ !requestedBuiltinTools.includes(tool) &&
388
+ (tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")),
389
+ );
390
+ const resolvedMcpSelections = capabilityCeiling?.denyExtensions
391
+ ? []
392
+ : resolveMcpDirectToolSelections(input.mcpDirectTools, input.cwd);
393
+ const effectiveMcpSelections = resolvedMcpSelections.filter(
394
+ (selection) => !allowedToolSet || allowedToolSet.has(selection.name),
395
+ );
396
+ const effectiveMcpTools = effectiveMcpSelections.map(
397
+ (selection) => selection.name,
398
+ );
399
+ const explicitToolAllowlist =
400
+ input.tools !== undefined ||
401
+ (input.mcpDirectTools?.length ?? 0) > 0 ||
402
+ allowedToolSet !== undefined;
403
+ const internalTools = input.structuredOutput ? ["structured_output"] : [];
404
+ const effectiveToolAllowlist = [
405
+ ...new Set([
406
+ ...declaredBuiltinTools,
407
+ ...effectiveMcpTools,
408
+ ...internalTools,
409
+ ]),
410
+ ];
411
+ const requiredChildTools = explicitToolAllowlist
412
+ ? [
413
+ ...new Set([
414
+ ...(input.tools !== undefined ? declaredBuiltinTools : []),
415
+ ...(input.mcpDirectTools?.length ? effectiveMcpTools : []),
416
+ ...internalTools,
417
+ ]),
418
+ ]
419
+ : [];
420
+ const permSystemExt = capabilityCeiling?.denyExtensions
421
+ ? undefined
422
+ : resolvePermissionSystemExtension();
423
+ const runtimeExtensions = [
424
+ PROMPT_RUNTIME_EXTENSION_PATH,
425
+ ...(fanoutAuthorized ? [FANOUT_CHILD_EXTENSION_PATH] : []),
426
+ ...(permSystemExt ? [permSystemExt] : []),
427
+ ];
428
+ const disableAmbientExtensions =
429
+ capabilityCeiling?.denyExtensions === true ||
430
+ input.extensions !== undefined;
431
+ const configuredExtensions = capabilityCeiling?.denyExtensions
432
+ ? []
433
+ : [
434
+ ...toolExtensionPaths,
435
+ ...(input.extensions ?? []),
436
+ ...(input.subagentOnlyExtensions ?? []),
437
+ ];
438
+ const extensionArgs = disableAmbientExtensions
439
+ ? [...new Set([...runtimeExtensions, ...configuredExtensions])]
440
+ : [
441
+ ...new Set([
442
+ ...runtimeExtensions,
443
+ ...toolExtensionPaths,
444
+ ...(input.subagentOnlyExtensions ?? []),
445
+ ]),
446
+ ];
447
+ const requestedToolNames =
448
+ input.tools !== undefined
449
+ ? [
450
+ ...new Set([
451
+ ...requestedBuiltinTools,
452
+ ...resolvedMcpSelections.map((selection) => selection.name),
453
+ ]),
454
+ ]
455
+ : undefined;
456
+ const capabilityAudit = capabilityCeiling
457
+ ? ({
458
+ ceiling: capabilityCeiling,
459
+ ...(requestedToolNames ? { requestedTools: requestedToolNames } : {}),
460
+ effectiveTools: effectiveToolAllowlist,
461
+ removedTools:
462
+ requestedToolNames?.filter(
463
+ (tool) => !effectiveToolAllowlist.includes(tool),
464
+ ) ?? [],
465
+ internalTools,
466
+ extensionsDenied: capabilityCeiling.denyExtensions,
467
+ removedExtensionCount: capabilityCeiling.denyExtensions
468
+ ? (input.extensions?.length ?? 0) +
469
+ (input.subagentOnlyExtensions?.length ?? 0) +
470
+ (input.tools ?? []).filter(
471
+ (tool) =>
472
+ tool.includes("/") ||
473
+ tool.endsWith(".ts") ||
474
+ tool.endsWith(".js"),
475
+ ).length
476
+ : 0,
477
+ requestedMcpToolCount: input.mcpDirectTools?.length ?? 0,
478
+ effectiveMcpTools,
479
+ agentAllowed:
480
+ input.agentName === undefined
481
+ ? true
482
+ : isAgentAllowedByCapabilityCeiling(
483
+ input.agentName,
484
+ capabilityCeiling,
485
+ ),
486
+ ...(capabilityCeilingAgentRestrictionSources(capabilityCeiling)
487
+ ? {
488
+ agentRestrictionSources:
489
+ capabilityCeilingAgentRestrictionSources(capabilityCeiling),
490
+ }
491
+ : {}),
492
+ } satisfies SubagentCapabilityAudit)
493
+ : undefined;
494
+ return {
495
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
496
+ requestedBuiltinTools,
497
+ declaredBuiltinTools,
498
+ toolExtensionPaths,
499
+ resolvedMcpSelections,
500
+ effectiveMcpSelections,
501
+ effectiveMcpTools,
502
+ explicitToolAllowlist,
503
+ internalTools,
504
+ effectiveToolAllowlist,
505
+ requiredChildTools,
506
+ fanoutAuthorized,
507
+ runtimeExtensions,
508
+ configuredExtensions,
509
+ extensionArgs,
510
+ disableAmbientExtensions,
511
+ ...(capabilityAudit ? { capabilityAudit } : {}),
512
+ };
513
+ }
514
+
515
+ /** Escape XML-significant characters in a string for safe attribute interpolation. */
516
+ function escapeXmlAttr(value: string): string {
517
+ return value
518
+ .replace(/&/g, "&amp;")
519
+ .replace(/"/g, "&quot;")
520
+ .replace(/</g, "&lt;")
521
+ .replace(/>/g, "&gt;");
522
+ }
523
+
524
+ export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
525
+ const args = [...input.baseArgs];
526
+
527
+ if (input.sessionFile) {
528
+ fs.mkdirSync(path.dirname(input.sessionFile), { recursive: true });
529
+ args.push("--session", input.sessionFile);
530
+ } else {
531
+ if (!input.sessionEnabled) {
532
+ args.push("--no-session");
533
+ }
534
+ if (input.sessionDir) {
535
+ fs.mkdirSync(input.sessionDir, { recursive: true });
536
+ args.push("--session-dir", input.sessionDir);
537
+ }
538
+ }
539
+
540
+ const modelArg = applyThinkingSuffix(input.model, input.thinking);
541
+ if (modelArg) {
542
+ args.push("--model", modelArg);
543
+ }
544
+
545
+ const toolPlan = resolvePiLaunchToolPlan({
546
+ tools: input.tools,
547
+ extensions: input.extensions,
548
+ subagentOnlyExtensions: input.subagentOnlyExtensions,
549
+ mcpDirectTools: input.mcpDirectTools,
550
+ cwd: input.cwd,
551
+ requireReadTool: input.requireReadTool,
552
+ structuredOutput: input.structuredOutput,
553
+ capabilityCeiling: input.capabilityCeiling,
554
+ inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(
555
+ process.env[SUBAGENT_CAPABILITY_CEILING_ENV],
556
+ ),
557
+ agentName: input.childAgentName,
558
+ });
559
+ if (toolPlan.explicitToolAllowlist) {
560
+ args.push(
561
+ toolPlan.effectiveToolAllowlist.length > 0 ? "--tools" : "--no-tools",
562
+ );
563
+ if (toolPlan.effectiveToolAllowlist.length > 0)
564
+ args.push(toolPlan.effectiveToolAllowlist.join(","));
565
+ }
566
+ if (toolPlan.disableAmbientExtensions) {
567
+ args.push("--no-extensions");
568
+ }
569
+ for (const extPath of toolPlan.extensionArgs)
570
+ args.push("--extension", extPath);
571
+
572
+ if (!input.inheritProjectContext) {
573
+ args.push("--no-context-files");
574
+ }
575
+ if (!input.inheritSkills) {
576
+ args.push("--no-skills");
577
+ }
578
+
579
+ let tempDir: string | undefined;
580
+ if (input.systemPrompt !== undefined && input.systemPrompt !== null) {
581
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
582
+ const stem = (input.promptFileStem ?? "prompt").replace(/[^\w.-]/g, "_");
583
+ const promptPath = path.join(tempDir, `${stem}.md`);
584
+ // Inject <active_agent> tag so the permission-system extension can
585
+ // resolve per-agent policy inside the child session.
586
+ const taggedPrompt = input.childAgentName
587
+ ? `<active_agent name="${escapeXmlAttr(input.childAgentName)}"/>\n\n${input.systemPrompt}`
588
+ : input.systemPrompt;
589
+ fs.writeFileSync(promptPath, taggedPrompt, { mode: 0o600 });
590
+ args.push(
591
+ input.systemPromptMode === "replace"
592
+ ? "--system-prompt"
593
+ : "--append-system-prompt",
594
+ promptPath,
595
+ );
596
+ }
597
+
598
+ if (input.task.length > TASK_ARG_LIMIT) {
599
+ if (!tempDir) {
600
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
601
+ }
602
+ const taskFilePath = path.join(tempDir, "task.md");
603
+ fs.writeFileSync(taskFilePath, `Task: ${input.task}`, { mode: 0o600 });
604
+ args.push(`@${taskFilePath}`);
605
+ } else {
606
+ args.push(`Task: ${input.task}`);
607
+ }
608
+
609
+ const env: Record<string, string | undefined> = {};
610
+ const piPackageRoot =
611
+ process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV] ?? resolvePiPackageRoot();
612
+ if (piPackageRoot) env[PI_CODING_AGENT_PACKAGE_ROOT_ENV] = piPackageRoot;
613
+ if (!tempDir)
614
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
615
+ const runtimeAcknowledgedExtensionsPath = path.join(
616
+ tempDir,
617
+ "runtime-acknowledged-extensions.json",
618
+ );
619
+ env[RUNTIME_EXTENSION_ACK_PATH_ENV] = runtimeAcknowledgedExtensionsPath;
620
+ let toolDiagnosticPath: string | undefined;
621
+ if (toolPlan.requiredChildTools.length > 0) {
622
+ if (!tempDir)
623
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
624
+ toolDiagnosticPath = path.join(tempDir, "tool-diagnostic.json");
625
+ env[REQUIRED_CHILD_TOOLS_ENV] = JSON.stringify(toolPlan.requiredChildTools);
626
+ env[CHILD_TOOL_DIAGNOSTIC_PATH_ENV] = toolDiagnosticPath;
627
+ }
628
+ env[MCP_DIRECT_CHILD_TOOLS_ENV] =
629
+ toolPlan.effectiveMcpTools.length > 0
630
+ ? JSON.stringify(toolPlan.effectiveMcpTools)
631
+ : undefined;
632
+ env[SUBAGENT_CHILD_ENV] = "1";
633
+ env[SUBAGENT_FANOUT_CHILD_ENV] = toolPlan.fanoutAuthorized ? "1" : "0";
634
+ if (input.waitToolEnabled !== undefined) {
635
+ env[WAIT_TOOL_ENABLED_ENV] = input.waitToolEnabled ? "true" : "false";
636
+ }
637
+ const inheritedNestedRoute = Boolean(
638
+ process.env[SUBAGENT_PARENT_EVENT_SINK_ENV] &&
639
+ process.env[SUBAGENT_PARENT_ROOT_RUN_ID_ENV] &&
640
+ process.env[SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV],
641
+ );
642
+ const parentRunId =
643
+ input.parentRunId ??
644
+ input.runId ??
645
+ (inheritedNestedRoute ? process.env[SUBAGENT_RUN_ID_ENV] : undefined) ??
646
+ process.env[SUBAGENT_PARENT_RUN_ID_ENV] ??
647
+ "";
648
+ const parentChildIndex =
649
+ input.parentChildIndex !== undefined
650
+ ? String(input.parentChildIndex)
651
+ : input.childIndex !== undefined
652
+ ? String(input.childIndex)
653
+ : (process.env[SUBAGENT_PARENT_CHILD_INDEX_ENV] ?? "");
654
+ const inheritedDepth = Number(process.env[SUBAGENT_PARENT_DEPTH_ENV]);
655
+ const parentDepth =
656
+ input.parentDepth ??
657
+ (inheritedNestedRoute && Number.isFinite(inheritedDepth)
658
+ ? inheritedDepth + 1
659
+ : 1);
660
+ const parentPath = input.parentPath ?? [
661
+ ...parseNestedPathEnv(process.env[SUBAGENT_PARENT_PATH_ENV]),
662
+ ...(parentRunId
663
+ ? [
664
+ {
665
+ runId: parentRunId,
666
+ ...(parentChildIndex && /^\d+$/.test(parentChildIndex)
667
+ ? { stepIndex: Number(parentChildIndex) }
668
+ : {}),
669
+ ...(input.childAgentName ? { agent: input.childAgentName } : {}),
670
+ },
671
+ ]
672
+ : []),
673
+ ];
674
+ env[SUBAGENT_PARENT_EVENT_SINK_ENV] = toolPlan.fanoutAuthorized
675
+ ? (input.parentEventSink ??
676
+ process.env[SUBAGENT_PARENT_EVENT_SINK_ENV] ??
677
+ "")
678
+ : "";
679
+ env[SUBAGENT_PARENT_CONTROL_INBOX_ENV] = toolPlan.fanoutAuthorized
680
+ ? (input.parentControlInbox ??
681
+ process.env[SUBAGENT_PARENT_CONTROL_INBOX_ENV] ??
682
+ "")
683
+ : "";
684
+ env[SUBAGENT_PARENT_ROOT_RUN_ID_ENV] = toolPlan.fanoutAuthorized
685
+ ? (input.parentRootRunId ??
686
+ process.env[SUBAGENT_PARENT_ROOT_RUN_ID_ENV] ??
687
+ input.runId ??
688
+ "")
689
+ : "";
690
+ env[SUBAGENT_PARENT_RUN_ID_ENV] = toolPlan.fanoutAuthorized
691
+ ? parentRunId
692
+ : "";
693
+ env[SUBAGENT_PARENT_CHILD_INDEX_ENV] = toolPlan.fanoutAuthorized
694
+ ? parentChildIndex
695
+ : "";
696
+ env[SUBAGENT_PARENT_DEPTH_ENV] = toolPlan.fanoutAuthorized
697
+ ? String(parentDepth)
698
+ : "";
699
+ env[SUBAGENT_PARENT_PATH_ENV] = toolPlan.fanoutAuthorized
700
+ ? encodeNestedPathEnv(parentPath)
701
+ : "";
702
+ env[SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV] = toolPlan.fanoutAuthorized
703
+ ? (input.parentCapabilityToken ??
704
+ process.env[SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV] ??
705
+ "")
706
+ : "";
707
+ env.PI_SUBAGENT_INHERIT_PROJECT_CONTEXT = input.inheritProjectContext
708
+ ? "1"
709
+ : "0";
710
+ env.PI_SUBAGENT_INHERIT_SKILLS = input.inheritSkills ? "1" : "0";
711
+ env[PI_INTERCOM_STABLE_ID_ENV] = input.intercomSessionName || undefined;
712
+ env[PI_INTERCOM_SESSION_ID_ENV] = undefined;
713
+ if (input.intercomSessionName) {
714
+ env.PI_SUBAGENT_INTERCOM_SESSION_NAME = input.intercomSessionName;
715
+ }
716
+ if (input.orchestratorIntercomTarget) {
717
+ env[SUBAGENT_ORCHESTRATOR_TARGET_ENV] = input.orchestratorIntercomTarget;
718
+ }
719
+ if (input.parentSessionId) {
720
+ env[SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV] = input.parentSessionId;
721
+ }
722
+ const encodedPermissionRules = encodePermissionRules(input.permissionRules);
723
+ if (
724
+ input.orchestratorIntercomTarget &&
725
+ input.parentSessionId &&
726
+ input.runId &&
727
+ input.childAgentName
728
+ ) {
729
+ const childIndex = input.childIndex ?? 0;
730
+ const channelDir = supervisorChannelDir(
731
+ input.runId,
732
+ input.childAgentName,
733
+ childIndex,
734
+ );
735
+ fs.mkdirSync(path.join(channelDir, "requests"), { recursive: true });
736
+ fs.mkdirSync(path.join(channelDir, "replies"), { recursive: true });
737
+ env[SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV] = channelDir;
738
+ }
739
+ if (encodedPermissionRules)
740
+ env[PERMISSION_AUDIT_PATH_ENV] =
741
+ input.permissionAuditPath ?? path.join(tempDir, "permission-audit.jsonl");
742
+ if (input.runId) {
743
+ env[SUBAGENT_RUN_ID_ENV] = input.runId;
744
+ }
745
+ if (input.childAgentName) {
746
+ env[SUBAGENT_CHILD_AGENT_ENV] = input.childAgentName;
747
+ }
748
+ if (input.childIndex !== undefined) {
749
+ env[SUBAGENT_CHILD_INDEX_ENV] = String(input.childIndex);
750
+ }
751
+ if (!toolPlan.capabilityCeiling && input.mcpDirectTools?.length)
752
+ env.MCP_DIRECT_TOOLS = input.mcpDirectTools.join(",");
753
+ else if (
754
+ toolPlan.capabilityCeiling &&
755
+ toolPlan.effectiveMcpSelections.length &&
756
+ !toolPlan.capabilityCeiling.denyExtensions
757
+ )
758
+ env.MCP_DIRECT_TOOLS = toolPlan.effectiveMcpSelections
759
+ .map((selection) => selection.selector)
760
+ .join(",");
761
+ else env.MCP_DIRECT_TOOLS = "__none__";
762
+ const encodedCapabilityCeiling = encodeSubagentCapabilityCeiling(
763
+ toolPlan.capabilityCeiling,
764
+ );
765
+ if (encodedCapabilityCeiling)
766
+ env[SUBAGENT_CAPABILITY_CEILING_ENV] = encodedCapabilityCeiling;
767
+ if (encodedPermissionRules)
768
+ env[PERMISSION_POLICY_ENV] = encodedPermissionRules;
769
+ if (input.structuredOutput) {
770
+ env[STRUCTURED_OUTPUT_CAPTURE_ENV] = input.structuredOutput.outputPath;
771
+ env[STRUCTURED_OUTPUT_SCHEMA_ENV] = input.structuredOutput.schemaPath;
772
+ }
773
+ if (input.steerInboxDir) {
774
+ env[SUBAGENT_STEER_INBOX_ENV] = input.steerInboxDir;
775
+ }
776
+ if (input.steerCapabilityPath)
777
+ env[SUBAGENT_STEER_CAPABILITY_ENV] = input.steerCapabilityPath;
778
+ if (input.steerAckDir) env[SUBAGENT_STEER_ACK_DIR_ENV] = input.steerAckDir;
779
+ const encodedToolBudget = encodeToolBudgetEnv(input.toolBudget);
780
+ if (encodedToolBudget) env[TOOL_BUDGET_ENV] = encodedToolBudget;
781
+ env[TOOL_BUDGET_ZERO_AUTH_ENV] = input.allowZeroToolBudget ? "1" : undefined;
782
+ const encodedChildWatchdog = encodeChildWatchdogConfig(input.childWatchdog);
783
+ if (encodedChildWatchdog)
784
+ env[CHILD_WATCHDOG_CONFIG_ENV] = encodedChildWatchdog;
785
+
786
+ env[SUBAGENT_PARENT_SESSION_ENV] =
787
+ input.parentSessionId ?? process.env[SUBAGENT_PARENT_SESSION_ENV] ?? "";
788
+
789
+ return {
790
+ args,
791
+ env,
792
+ tempDir,
793
+ toolDiagnosticPath,
794
+ runtimeAcknowledgedExtensionsPath,
795
+ capabilityAudit: toolPlan.capabilityAudit,
796
+ };
797
+ }
798
+
799
+ export const parseParentPathEnv = parseNestedPathEnv;
800
+
801
+ export function cleanupTempDir(tempDir: string | null | undefined): void {
802
+ if (!tempDir) return;
803
+ try {
804
+ fs.rmSync(tempDir, { recursive: true, force: true });
805
+ } catch {
806
+ // Temp cleanup is best effort.
807
+ }
808
+ }