@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -1,935 +0,0 @@
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 { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV, type ExtensionBindings } from "./extension-bindings.ts";
17
- import { RUNTIME_EXTENSION_ACK_PATH_ENV } from "./runtime-acknowledged-extensions.ts";
18
- import {
19
- STRUCTURED_OUTPUT_ACCEPTANCE_CAPTURE_ENV,
20
- STRUCTURED_OUTPUT_CAPTURE_ENV,
21
- STRUCTURED_OUTPUT_SCHEMA_ENV,
22
- } from "./structured-output.ts";
23
- import {
24
- TEMP_ROOT_DIR,
25
- type JsonSchemaObject,
26
- type LaunchResolvedChildExtensionsV1,
27
- type ResolvedToolBudget,
28
- type RunFanoutBudgetDescriptor,
29
- } from "../../shared/types.ts";
30
- import { THINKING_LEVELS } from "../../shared/model-info.ts";
31
- import { decodeThinkingCeiling, intersectThinkingCeilings, SUBAGENT_THINKING_CEILING_ENV } from "../../shared/thinking-ceiling.ts";
32
- import { encodeRunFanoutBudgetDescriptor, RUN_FANOUT_BUDGET_ENV } from "./run-fanout-budget.ts";
33
- import {
34
- TOOL_BUDGET_ENV,
35
- TOOL_BUDGET_ZERO_AUTH_ENV,
36
- encodeToolBudgetEnv,
37
- } from "./tool-budget.ts";
38
- import {
39
- CHILD_TOOL_DIAGNOSTIC_PATH_ENV,
40
- MCP_DIRECT_CHILD_TOOLS_ENV,
41
- REQUIRED_CHILD_TOOLS_ENV,
42
- } from "./tool-availability.ts";
43
- import {
44
- CHILD_WATCHDOG_CONFIG_ENV,
45
- encodeChildWatchdogConfig,
46
- type ChildWatchdogConfig,
47
- } from "../../watchdog/child-status.ts";
48
- import { WAIT_TOOL_ENABLED_ENV } from "../background/wait-config.ts";
49
- import {
50
- PI_CODING_AGENT_PACKAGE_ROOT_ENV,
51
- getAgentDir,
52
- } from "../../shared/utils.ts";
53
- import {
54
- encodePermissionRules,
55
- PERMISSION_AUDIT_PATH_ENV,
56
- PERMISSION_POLICY_ENV,
57
- type PermissionRules,
58
- } from "./permissions.ts";
59
- import {
60
- SUBAGENT_CAPABILITY_CEILING_ENV,
61
- capabilityCeilingAgentRestrictionSources,
62
- decodeSubagentCapabilityCeiling,
63
- encodeSubagentCapabilityCeiling,
64
- intersectSubagentCapabilityCeilings,
65
- isAgentAllowedByCapabilityCeiling,
66
- type ResolvedSubagentCapabilityCeiling,
67
- type SubagentCapabilityAudit,
68
- } from "./capability-ceiling.ts";
69
-
70
- const TASK_ARG_LIMIT = 8000;
71
-
72
- /**
73
- * Env override for how the task text reaches the child process. Endpoint
74
- * protection (EDR) pre-execution command-line scanning may deny exec of
75
- * children whose argv embeds a long natural-language task, which surfaces
76
- * as an immediate zero-activity SIGKILL. File delivery keeps the task out
77
- * of argv entirely.
78
- */
79
- export const SUBAGENT_TASK_DELIVERY_ENV = "PI_SUBAGENT_TASK_DELIVERY";
80
-
81
- export type SubagentTaskDelivery = "auto" | "file";
82
-
83
- export function resolveSubagentTaskDelivery(
84
- env: NodeJS.ProcessEnv = process.env,
85
- ): SubagentTaskDelivery {
86
- return env[SUBAGENT_TASK_DELIVERY_ENV]?.trim().toLowerCase() === "file"
87
- ? "file"
88
- : "auto";
89
- }
90
-
91
- function shouldDeliverTaskViaFile(
92
- task: string,
93
- delivery: SubagentTaskDelivery,
94
- ): boolean {
95
- return delivery === "file" || task.length > TASK_ARG_LIMIT;
96
- }
97
- const MAX_LAUNCH_RESOLVED_EXTENSION_IDS = 32;
98
- const PROMPT_RUNTIME_EXTENSION_PATH = path.join(
99
- path.dirname(fileURLToPath(import.meta.url)),
100
- "subagent-prompt-runtime.ts",
101
- );
102
- const FANOUT_CHILD_EXTENSION_PATH = path.join(
103
- path.dirname(fileURLToPath(import.meta.url)),
104
- "..",
105
- "..",
106
- "extension",
107
- "fanout-child.ts",
108
- );
109
- const FAST_MODE_EXTENSION_PATH = path.join(
110
- path.dirname(fileURLToPath(import.meta.url)),
111
- "fast-mode-extension.ts",
112
- );
113
- const FAST_MODE_ALLOWED_MODELS = new Set([
114
- "openai-codex/gpt-5.6-luna",
115
- "openai-codex/gpt-5.6-sol",
116
- ]);
117
- export const SUBAGENT_CHILD_ENV = "PI_SUBAGENT_CHILD";
118
- export const SUBAGENT_ORCHESTRATOR_TARGET_ENV =
119
- "PI_SUBAGENT_ORCHESTRATOR_TARGET";
120
- export const SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV =
121
- "PI_SUBAGENT_ORCHESTRATOR_SESSION_ID";
122
- export const SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV =
123
- "PI_SUBAGENT_SUPERVISOR_CHANNEL_DIR";
124
- export const SUBAGENT_RUN_ID_ENV = "PI_SUBAGENT_RUN_ID";
125
- export const SUBAGENT_CHILD_AGENT_ENV = "PI_SUBAGENT_CHILD_AGENT";
126
- export const SUBAGENT_CHILD_INDEX_ENV = "PI_SUBAGENT_CHILD_INDEX";
127
- export const SUBAGENT_FANOUT_CHILD_ENV = "PI_SUBAGENT_FANOUT_CHILD";
128
- export const SUBAGENT_PARENT_EVENT_SINK_ENV = "PI_SUBAGENT_PARENT_EVENT_SINK";
129
- export const SUBAGENT_PARENT_CONTROL_INBOX_ENV =
130
- "PI_SUBAGENT_PARENT_CONTROL_INBOX";
131
- export const SUBAGENT_PARENT_ROOT_RUN_ID_ENV = "PI_SUBAGENT_PARENT_ROOT_RUN_ID";
132
- export const SUBAGENT_PARENT_RUN_ID_ENV = "PI_SUBAGENT_PARENT_RUN_ID";
133
- export const SUBAGENT_PARENT_CHILD_INDEX_ENV = "PI_SUBAGENT_PARENT_CHILD_INDEX";
134
- export const SUBAGENT_PARENT_DEPTH_ENV = "PI_SUBAGENT_PARENT_DEPTH";
135
- export const SUBAGENT_PARENT_PATH_ENV = "PI_SUBAGENT_PARENT_PATH";
136
- export const SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV =
137
- "PI_SUBAGENT_PARENT_CAPABILITY_TOKEN";
138
- export const SUBAGENT_PARENT_SESSION_ENV = "PI_SUBAGENT_PARENT_SESSION";
139
- export const SUBAGENT_STEER_INBOX_ENV = "PI_SUBAGENT_STEER_INBOX";
140
- export const SUBAGENT_STEER_CAPABILITY_ENV = "PI_SUBAGENT_STEER_CAPABILITY";
141
- export const SUBAGENT_STEER_ACK_DIR_ENV = "PI_SUBAGENT_STEER_ACK_DIR";
142
- export const PI_INTERCOM_STABLE_ID_ENV = "PI_INTERCOM_STABLE_ID";
143
- export const PI_INTERCOM_SESSION_ID_ENV = "PI_INTERCOM_SESSION_ID";
144
-
145
- export interface BuildPiArgsInput {
146
- parentSessionId?: string;
147
- baseArgs: string[];
148
- task: string;
149
- sessionEnabled: boolean;
150
- sessionDir?: string;
151
- sessionFile?: string;
152
- model?: string;
153
- thinking?: string | false;
154
- systemPromptMode?: "append" | "replace";
155
- inheritProjectContext: boolean;
156
- inheritSkills: boolean;
157
- requireReadTool?: boolean;
158
- tools?: string[];
159
- extensions?: string[];
160
- subagentOnlyExtensions?: string[];
161
- systemPrompt?: string | null;
162
- mcpDirectTools?: string[];
163
- cwd?: string;
164
- promptFileStem?: string;
165
- intercomSessionName?: string;
166
- orchestratorIntercomTarget?: string;
167
- runId?: string;
168
- childAgentName?: string;
169
- childIndex?: number;
170
- parentEventSink?: string;
171
- parentControlInbox?: string;
172
- parentRootRunId?: string;
173
- parentRunId?: string;
174
- parentChildIndex?: number;
175
- parentDepth?: number;
176
- parentPath?: NestedPathEntry[];
177
- parentCapabilityToken?: string;
178
- runFanoutBudget?: RunFanoutBudgetDescriptor;
179
- steerInboxDir?: string;
180
- steerCapabilityPath?: string;
181
- steerAckDir?: string;
182
- structuredOutput?: {
183
- schema: JsonSchemaObject;
184
- schemaPath: string;
185
- outputPath: string;
186
- acceptanceReportPath?: string;
187
- };
188
- fast?: boolean;
189
- modelCandidates?: readonly string[];
190
- toolBudget?: ResolvedToolBudget;
191
- allowZeroToolBudget?: boolean;
192
- permissionRules?: PermissionRules;
193
- permissionAuditPath?: string;
194
- childWatchdog?: ChildWatchdogConfig;
195
- /**
196
- * Per-launch override of the task delivery mode. Startup-retry paths set
197
- * this to "file" after an unexplained zero-activity SIGKILL so the retry
198
- * keeps the task text out of the child's argv.
199
- */
200
- taskDelivery?: SubagentTaskDelivery;
201
- waitToolEnabled?: boolean;
202
- capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
203
- thinkingCeiling?: import("../../shared/model-info.ts").ThinkingLevel;
204
- extensionBindings?: ExtensionBindings;
205
- }
206
-
207
- export interface BuildPiArgsResult {
208
- args: string[];
209
- env: Record<string, string | undefined>;
210
- warnings: string[];
211
- tempDir?: string;
212
- toolDiagnosticPath?: string;
213
- runtimeAcknowledgedExtensionsPath?: string;
214
- capabilityAudit?: SubagentCapabilityAudit;
215
- }
216
-
217
- function sanitizeSupervisorChannelSegment(value: string): string {
218
- return (
219
- value
220
- .trim()
221
- .replace(/[^A-Za-z0-9._-]+/g, "-")
222
- .replace(/^-+|-+$/g, "") || "unknown"
223
- );
224
- }
225
-
226
- function supervisorChannelDir(
227
- runId: string,
228
- agent: string,
229
- childIndex: number,
230
- ): string {
231
- return path.join(
232
- TEMP_ROOT_DIR,
233
- "supervisor-channels",
234
- `${sanitizeSupervisorChannelSegment(runId)}-${sanitizeSupervisorChannelSegment(agent)}-${childIndex}`,
235
- );
236
- }
237
-
238
- export function applyThinkingSuffix(
239
- model: string | undefined,
240
- thinking: string | false | undefined,
241
- replaceExisting = false,
242
- ): string | undefined {
243
- if (!model || !thinking) return model;
244
- const colonIdx = model.lastIndexOf(":");
245
- if (
246
- colonIdx !== -1 &&
247
- THINKING_LEVELS.some((level) => level === model.substring(colonIdx + 1))
248
- ) {
249
- return replaceExisting ? `${model.slice(0, colonIdx)}:${thinking}` : model;
250
- }
251
- return `${model}:${thinking}`;
252
- }
253
-
254
- function stripThinkingSuffix(model: string): string {
255
- const colonIdx = model.lastIndexOf(":");
256
- if (colonIdx === -1) return model;
257
- return THINKING_LEVELS.some((level) => level === model.substring(colonIdx + 1))
258
- ? model.slice(0, colonIdx)
259
- : model;
260
- }
261
-
262
- function resolveFastModeExtension(input: Pick<ResolvePiLaunchToolPlanInput, "fast" | "model" | "modelCandidates" | "agentName">): string[] {
263
- if (!input.fast) return [];
264
- const candidates = (input.modelCandidates?.length ? input.modelCandidates : input.model ? [input.model] : [])
265
- .map(stripThinkingSuffix);
266
- if (candidates.length === 0) {
267
- throw new Error(`fast mode requires an explicit supported native OpenAI-Codex model${input.agentName ? ` for agent '${input.agentName}'` : ""}.`);
268
- }
269
- const unsupported = candidates.filter((model) => !FAST_MODE_ALLOWED_MODELS.has(model));
270
- if (unsupported.length > 0) {
271
- throw new Error(`fast mode supports only ${[...FAST_MODE_ALLOWED_MODELS].join(", ")}; unsupported model${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.`);
272
- }
273
- return [FAST_MODE_EXTENSION_PATH];
274
- }
275
-
276
- export interface ResolvePiLaunchToolPlanInput {
277
- tools?: string[];
278
- extensions?: string[];
279
- subagentOnlyExtensions?: string[];
280
- mcpDirectTools?: string[];
281
- cwd?: string;
282
- requireReadTool?: boolean;
283
- structuredOutput?:
284
- | boolean
285
- | {
286
- schema: JsonSchemaObject;
287
- schemaPath: string;
288
- outputPath: string;
289
- };
290
- fast?: boolean;
291
- model?: string;
292
- modelCandidates?: readonly string[];
293
- capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
294
- inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
295
- agentName?: string;
296
- permissionRules?: PermissionRules;
297
- }
298
-
299
- export interface PiLaunchToolPlan {
300
- capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
301
- requestedBuiltinTools: string[];
302
- declaredBuiltinTools: string[];
303
- toolExtensionPaths: string[];
304
- resolvedMcpSelections: ResolvedMcpDirectToolSelection[];
305
- effectiveMcpSelections: ResolvedMcpDirectToolSelection[];
306
- effectiveMcpTools: string[];
307
- explicitToolAllowlist: boolean;
308
- internalTools: string[];
309
- effectiveToolAllowlist: string[];
310
- requiredChildTools: string[];
311
- fanoutAuthorized: boolean;
312
- runtimeExtensions: string[];
313
- configuredExtensions: string[];
314
- extensionArgs: string[];
315
- disableAmbientExtensions: boolean;
316
- capabilityAudit?: SubagentCapabilityAudit;
317
- /** Non-fatal launch warnings; they do not change behavior. */
318
- warnings: string[];
319
- }
320
-
321
- function extensionIdentifier(value: string): string {
322
- return `sha256:${createHash("sha256").update(path.normalize(value.trim())).digest("hex").slice(0, 16)}`;
323
- }
324
-
325
- function boundedExtensionIdentifiers(values: string[]): {
326
- ids: string[];
327
- omitted: number;
328
- } {
329
- const ids = [...new Set(values.map(extensionIdentifier))];
330
- return {
331
- ids: ids.slice(0, MAX_LAUNCH_RESOLVED_EXTENSION_IDS),
332
- omitted: Math.max(0, ids.length - MAX_LAUNCH_RESOLVED_EXTENSION_IDS),
333
- };
334
- }
335
-
336
- function hasPermissionRules(rules: PermissionRules | undefined): boolean {
337
- return rules !== undefined && Object.keys(rules).length > 0;
338
- }
339
-
340
- export function projectLaunchResolvedChildExtensions(
341
- toolPlan: Pick<
342
- PiLaunchToolPlan,
343
- | "runtimeExtensions"
344
- | "configuredExtensions"
345
- | "extensionArgs"
346
- | "disableAmbientExtensions"
347
- >,
348
- ): LaunchResolvedChildExtensionsV1 {
349
- const runtime = boundedExtensionIdentifiers(toolPlan.runtimeExtensions);
350
- const configured = boundedExtensionIdentifiers(toolPlan.configuredExtensions);
351
- const effective = boundedExtensionIdentifiers(toolPlan.extensionArgs);
352
- return {
353
- version: 1,
354
- source: "launch-resolved",
355
- disableAmbientExtensions: toolPlan.disableAmbientExtensions,
356
- runtime: runtime.ids,
357
- configured: configured.ids,
358
- effective: effective.ids,
359
- omitted: {
360
- runtime: runtime.omitted,
361
- configured: configured.omitted,
362
- effective: effective.omitted,
363
- },
364
- };
365
- }
366
-
367
- /**
368
- * Resolve the permission-system extension entry point when installed.
369
- * Returns the absolute path to the extension's main module, or undefined
370
- * when the package is not installed. Callers can check `autoInject` config
371
- * to decide whether to include it in child processes.
372
- */
373
- export function resolvePermissionSystemExtension(): string | undefined {
374
- const agentDir = getAgentDir();
375
- const candidates = [
376
- // @xzzpig fork takes priority so child processes inherit the same
377
- // permission system the parent session loads from settings.json.
378
- // When only the upstream package is installed, behavior is unchanged.
379
- path.join(
380
- agentDir,
381
- "npm",
382
- "node_modules",
383
- "@xzzpig",
384
- "pi-permission-system",
385
- ),
386
- // npm-scoped package (most common)
387
- path.join(
388
- agentDir,
389
- "npm",
390
- "node_modules",
391
- "@gotgenes",
392
- "pi-permission-system",
393
- ),
394
- // direct extension directory (some layouts)
395
- path.join(agentDir, "extensions", "pi-permission-system"),
396
- ];
397
- const errors: Error[] = [];
398
- for (const extDir of candidates) {
399
- if (!fs.existsSync(extDir)) continue;
400
- const pkgPath = path.join(extDir, "package.json");
401
- if (!fs.existsSync(pkgPath)) {
402
- errors.push(new Error(`Permission-system package manifest is missing at ${pkgPath}.`));
403
- continue;
404
- }
405
- try {
406
- let pkg: { pi?: { extensions?: string[] } };
407
- const parsed: unknown = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
408
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
409
- throw new Error("manifest root must be an object");
410
- }
411
- pkg = parsed as typeof pkg;
412
- const extensions = pkg.pi?.extensions;
413
- const entry = Array.isArray(extensions) ? extensions[0] : undefined;
414
- if (typeof entry !== "string" || !entry.trim()) {
415
- throw new Error(
416
- `Permission-system package manifest at ${pkgPath} must declare pi.extensions[0] as a non-empty string.`,
417
- );
418
- }
419
- const resolved = path.resolve(extDir, entry);
420
- if (fs.existsSync(resolved)) return resolved;
421
- throw new Error(
422
- `Permission-system extension entry ${JSON.stringify(entry)} in ${pkgPath} does not exist at ${resolved}.`,
423
- );
424
- } catch (error) {
425
- const message = error instanceof Error ? error.message : String(error);
426
- errors.push(message.startsWith("Permission-system") ? new Error(message) : new Error(`Cannot read permission-system package manifest at ${pkgPath}: ${message}`));
427
- }
428
- }
429
- if (errors.length > 0) throw errors[0]!;
430
- return undefined;
431
- }
432
-
433
- export function resolvePiLaunchToolPlan(
434
- input: ResolvePiLaunchToolPlanInput,
435
- ): PiLaunchToolPlan {
436
- const capabilityCeiling = intersectSubagentCapabilityCeilings(
437
- input.capabilityCeiling,
438
- input.inheritedCapabilityCeiling,
439
- );
440
- const allowedToolSet =
441
- capabilityCeiling?.allowedTools === undefined
442
- ? undefined
443
- : new Set(capabilityCeiling.allowedTools);
444
- const requestedBuiltinTools =
445
- input.tools?.filter(
446
- (tool) =>
447
- !(tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")),
448
- ) ?? [];
449
- if (input.requireReadTool && allowedToolSet && !allowedToolSet.has("read")) {
450
- throw new Error(
451
- `Capability ceiling from ${capabilityCeiling?.sources.join(", ") || "unknown source"} excludes required tool 'read' for lazy skill loading.`,
452
- );
453
- }
454
- const declaredBuiltinTools =
455
- input.tools === undefined
456
- ? allowedToolSet
457
- ? [...allowedToolSet]
458
- : []
459
- : (input.requireReadTool &&
460
- requestedBuiltinTools.length > 0 &&
461
- !requestedBuiltinTools.includes("read") &&
462
- !allowedToolSet
463
- ? ["read", ...requestedBuiltinTools]
464
- : requestedBuiltinTools
465
- ).filter((tool) => !allowedToolSet || allowedToolSet.has(tool));
466
- const fanoutAuthorized = declaredBuiltinTools.includes("subagent");
467
- const toolExtensionPaths: string[] = capabilityCeiling?.denyExtensions
468
- ? []
469
- : (input.tools ?? []).filter(
470
- (tool) =>
471
- !requestedBuiltinTools.includes(tool) &&
472
- (tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")),
473
- );
474
- const resolvedMcpSelections = capabilityCeiling?.denyExtensions
475
- ? []
476
- : resolveMcpDirectToolSelections(input.mcpDirectTools, input.cwd);
477
- const effectiveMcpSelections = resolvedMcpSelections.filter(
478
- (selection) => !allowedToolSet || allowedToolSet.has(selection.name),
479
- );
480
- const effectiveMcpTools = effectiveMcpSelections.map(
481
- (selection) => selection.name,
482
- );
483
- const explicitToolAllowlist =
484
- input.tools !== undefined ||
485
- (input.mcpDirectTools?.length ?? 0) > 0 ||
486
- allowedToolSet !== undefined;
487
- const internalTools = input.structuredOutput ? ["structured_output"] : [];
488
- const effectiveToolAllowlist = [
489
- ...new Set([
490
- ...declaredBuiltinTools,
491
- ...effectiveMcpTools,
492
- ...internalTools,
493
- ]),
494
- ];
495
- // Supervisor-coordination names stay in the --tools allowlist but are never
496
- // strict requirements: children register contact_supervisor at runtime through
497
- // the native supervisor channel (or pi-intercom). The pre-0.50 bridge always
498
- // appended intercom alongside contact_supervisor, so that exact pairing is
499
- // legacy plumbing, not a user demand for an external intercom provider;
500
- // a lone intercom entry stays strictly required (#1207).
501
- const legacySupervisorPairing = declaredBuiltinTools.includes("contact_supervisor");
502
- const requiredChildTools = explicitToolAllowlist
503
- ? [
504
- ...new Set([
505
- ...(input.tools !== undefined ? declaredBuiltinTools : []),
506
- ...(input.mcpDirectTools?.length ? effectiveMcpTools : []),
507
- ...internalTools,
508
- ].filter((tool) => tool !== "contact_supervisor" && (!legacySupervisorPairing || tool !== "intercom"))),
509
- ]
510
- : [];
511
- const permSystemExt = capabilityCeiling?.denyExtensions
512
- ? undefined
513
- : hasPermissionRules(input.permissionRules)
514
- ? resolvePermissionSystemExtension()
515
- : undefined;
516
- if (input.fast && capabilityCeiling?.denyExtensions) throw new Error("fast mode requires a child runtime extension, but this launch denies extensions.");
517
- const fastModeExtensions = resolveFastModeExtension({ fast: input.fast, model: input.model, modelCandidates: input.modelCandidates, agentName: input.agentName });
518
- const runtimeExtensions = [
519
- PROMPT_RUNTIME_EXTENSION_PATH,
520
- ...fastModeExtensions,
521
- ...(fanoutAuthorized ? [FANOUT_CHILD_EXTENSION_PATH] : []),
522
- ...(permSystemExt ? [permSystemExt] : []),
523
- ];
524
- const disableAmbientExtensions =
525
- capabilityCeiling?.denyExtensions === true ||
526
- input.extensions !== undefined;
527
- const warnings: string[] = [];
528
- // An explicit empty list disables ambient extensions, including model providers.
529
- if (capabilityCeiling?.denyExtensions !== true && Array.isArray(input.extensions) && input.extensions.length === 0) {
530
- const agentLabel = input.agentName ? ` for agent '${input.agentName}'` : "";
531
- warnings.push(
532
- `extensions: [] override${agentLabel} disables ALL ambient extensions for this child (not just "adds nothing"), `
533
- + "including any model-provider extension needed to resolve a provider-qualified model. "
534
- + "List the extensions this child actually needs instead of an empty array.",
535
- );
536
- }
537
- const configuredExtensions = capabilityCeiling?.denyExtensions
538
- ? []
539
- : [
540
- ...toolExtensionPaths,
541
- ...(input.extensions ?? []),
542
- ...(input.subagentOnlyExtensions ?? []),
543
- ];
544
- const extensionArgs = disableAmbientExtensions
545
- ? [...new Set([...runtimeExtensions, ...configuredExtensions])]
546
- : [
547
- ...new Set([
548
- ...runtimeExtensions,
549
- ...toolExtensionPaths,
550
- ...(input.subagentOnlyExtensions ?? []),
551
- ]),
552
- ];
553
- const requestedToolNames =
554
- input.tools !== undefined
555
- ? [
556
- ...new Set([
557
- ...requestedBuiltinTools,
558
- ...resolvedMcpSelections.map((selection) => selection.name),
559
- ]),
560
- ]
561
- : undefined;
562
- const capabilityAudit = capabilityCeiling
563
- ? ({
564
- ceiling: capabilityCeiling,
565
- ...(requestedToolNames ? { requestedTools: requestedToolNames } : {}),
566
- effectiveTools: effectiveToolAllowlist,
567
- removedTools:
568
- requestedToolNames?.filter(
569
- (tool) => !effectiveToolAllowlist.includes(tool),
570
- ) ?? [],
571
- internalTools,
572
- extensionsDenied: capabilityCeiling.denyExtensions,
573
- removedExtensionCount: capabilityCeiling.denyExtensions
574
- ? (input.extensions?.length ?? 0) +
575
- (input.subagentOnlyExtensions?.length ?? 0) +
576
- (input.tools ?? []).filter(
577
- (tool) =>
578
- tool.includes("/") ||
579
- tool.endsWith(".ts") ||
580
- tool.endsWith(".js"),
581
- ).length
582
- : 0,
583
- requestedMcpToolCount: input.mcpDirectTools?.length ?? 0,
584
- effectiveMcpTools,
585
- agentAllowed:
586
- input.agentName === undefined
587
- ? true
588
- : isAgentAllowedByCapabilityCeiling(
589
- input.agentName,
590
- capabilityCeiling,
591
- ),
592
- ...(capabilityCeilingAgentRestrictionSources(capabilityCeiling)
593
- ? {
594
- agentRestrictionSources:
595
- capabilityCeilingAgentRestrictionSources(capabilityCeiling),
596
- }
597
- : {}),
598
- } satisfies SubagentCapabilityAudit)
599
- : undefined;
600
- return {
601
- ...(capabilityCeiling ? { capabilityCeiling } : {}),
602
- requestedBuiltinTools,
603
- declaredBuiltinTools,
604
- toolExtensionPaths,
605
- resolvedMcpSelections,
606
- effectiveMcpSelections,
607
- effectiveMcpTools,
608
- explicitToolAllowlist,
609
- internalTools,
610
- effectiveToolAllowlist,
611
- requiredChildTools,
612
- fanoutAuthorized,
613
- runtimeExtensions,
614
- configuredExtensions,
615
- extensionArgs,
616
- disableAmbientExtensions,
617
- warnings,
618
- ...(capabilityAudit ? { capabilityAudit } : {}),
619
- };
620
- }
621
-
622
- /** Escape XML-significant characters in a string for safe attribute interpolation. */
623
- function escapeXmlAttr(value: string): string {
624
- return value
625
- .replace(/&/g, "&amp;")
626
- .replace(/"/g, "&quot;")
627
- .replace(/</g, "&lt;")
628
- .replace(/>/g, "&gt;");
629
- }
630
-
631
- export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
632
- const args = [...input.baseArgs];
633
-
634
- if (input.sessionFile) {
635
- fs.mkdirSync(path.dirname(input.sessionFile), { recursive: true });
636
- args.push("--session", input.sessionFile);
637
- } else {
638
- if (!input.sessionEnabled) {
639
- args.push("--no-session");
640
- }
641
- if (input.sessionDir) {
642
- fs.mkdirSync(input.sessionDir, { recursive: true });
643
- args.push("--session-dir", input.sessionDir);
644
- }
645
- }
646
-
647
- const modelArg = applyThinkingSuffix(input.model, input.thinking);
648
- if (modelArg) {
649
- args.push("--model", modelArg);
650
- }
651
-
652
- const toolPlan = resolvePiLaunchToolPlan({
653
- tools: input.tools,
654
- extensions: input.extensions,
655
- subagentOnlyExtensions: input.subagentOnlyExtensions,
656
- mcpDirectTools: input.mcpDirectTools,
657
- cwd: input.cwd,
658
- requireReadTool: input.requireReadTool,
659
- structuredOutput: input.structuredOutput,
660
- fast: input.fast,
661
- model: modelArg,
662
- modelCandidates: input.modelCandidates,
663
- capabilityCeiling: input.capabilityCeiling,
664
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(
665
- process.env[SUBAGENT_CAPABILITY_CEILING_ENV],
666
- ),
667
- agentName: input.childAgentName,
668
- permissionRules: input.permissionRules,
669
- });
670
- if (toolPlan.explicitToolAllowlist) {
671
- args.push(
672
- toolPlan.effectiveToolAllowlist.length > 0 ? "--tools" : "--no-tools",
673
- );
674
- if (toolPlan.effectiveToolAllowlist.length > 0)
675
- args.push(toolPlan.effectiveToolAllowlist.join(","));
676
- }
677
- if (toolPlan.disableAmbientExtensions) {
678
- args.push("--no-extensions");
679
- }
680
- for (const extPath of toolPlan.extensionArgs)
681
- args.push("--extension", extPath);
682
-
683
- if (!input.inheritProjectContext) {
684
- args.push("--no-context-files");
685
- }
686
- if (!input.inheritSkills) {
687
- args.push("--no-skills");
688
- }
689
-
690
- let tempDir: string | undefined;
691
- if (input.systemPrompt !== undefined && input.systemPrompt !== null) {
692
- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
693
- const stem = (input.promptFileStem ?? "prompt").replace(/[^\w.-]/g, "_");
694
- const promptPath = path.join(tempDir, `${stem}.md`);
695
- // Inject <active_agent> tag so the permission-system extension can
696
- // resolve per-agent policy inside the child session.
697
- const taggedPrompt = input.childAgentName
698
- ? `<active_agent name="${escapeXmlAttr(input.childAgentName)}"/>\n\n${input.systemPrompt}`
699
- : input.systemPrompt;
700
- fs.writeFileSync(promptPath, taggedPrompt, { mode: 0o600 });
701
- args.push(
702
- input.systemPromptMode === "replace"
703
- ? "--system-prompt"
704
- : "--append-system-prompt",
705
- promptPath,
706
- );
707
- }
708
-
709
- if (
710
- shouldDeliverTaskViaFile(
711
- input.task,
712
- input.taskDelivery ?? resolveSubagentTaskDelivery(),
713
- )
714
- ) {
715
- if (!tempDir) {
716
- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
717
- }
718
- const taskFilePath = path.join(tempDir, "task.md");
719
- fs.writeFileSync(taskFilePath, `Task: ${input.task}`, { mode: 0o600 });
720
- args.push(`@${taskFilePath}`);
721
- } else {
722
- args.push(`Task: ${input.task}`);
723
- }
724
-
725
- const env: Record<string, string | undefined> = {};
726
- env[PI_SUBAGENT_EXTENSION_BINDINGS_ENV] = encodeExtensionBindings(input.extensionBindings);
727
- const piPackageRoot =
728
- process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV] ?? resolvePiPackageRoot();
729
- if (piPackageRoot) env[PI_CODING_AGENT_PACKAGE_ROOT_ENV] = piPackageRoot;
730
- if (!tempDir)
731
- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
732
- const runtimeAcknowledgedExtensionsPath = path.join(
733
- tempDir,
734
- "runtime-acknowledged-extensions.json",
735
- );
736
- env[RUNTIME_EXTENSION_ACK_PATH_ENV] = runtimeAcknowledgedExtensionsPath;
737
- let toolDiagnosticPath: string | undefined;
738
- if (toolPlan.requiredChildTools.length > 0) {
739
- if (!tempDir)
740
- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
741
- toolDiagnosticPath = path.join(tempDir, "tool-diagnostic.json");
742
- env[REQUIRED_CHILD_TOOLS_ENV] = JSON.stringify(toolPlan.requiredChildTools);
743
- env[CHILD_TOOL_DIAGNOSTIC_PATH_ENV] = toolDiagnosticPath;
744
- }
745
- env[MCP_DIRECT_CHILD_TOOLS_ENV] =
746
- toolPlan.effectiveMcpTools.length > 0
747
- ? JSON.stringify(toolPlan.effectiveMcpTools)
748
- : undefined;
749
- env[SUBAGENT_CHILD_ENV] = "1";
750
- env[SUBAGENT_FANOUT_CHILD_ENV] = toolPlan.fanoutAuthorized ? "1" : "0";
751
- if (input.waitToolEnabled !== undefined) {
752
- env[WAIT_TOOL_ENABLED_ENV] = input.waitToolEnabled ? "true" : "false";
753
- }
754
- const inheritedNestedRoute = Boolean(
755
- process.env[SUBAGENT_PARENT_EVENT_SINK_ENV] &&
756
- process.env[SUBAGENT_PARENT_ROOT_RUN_ID_ENV] &&
757
- process.env[SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV],
758
- );
759
- const parentRunId =
760
- input.parentRunId ??
761
- input.runId ??
762
- (inheritedNestedRoute ? process.env[SUBAGENT_RUN_ID_ENV] : undefined) ??
763
- process.env[SUBAGENT_PARENT_RUN_ID_ENV] ??
764
- "";
765
- const parentChildIndex =
766
- input.parentChildIndex !== undefined
767
- ? String(input.parentChildIndex)
768
- : input.childIndex !== undefined
769
- ? String(input.childIndex)
770
- : (process.env[SUBAGENT_PARENT_CHILD_INDEX_ENV] ?? "");
771
- const inheritedDepth = Number(process.env[SUBAGENT_PARENT_DEPTH_ENV]);
772
- const parentDepth =
773
- input.parentDepth ??
774
- (inheritedNestedRoute && Number.isFinite(inheritedDepth)
775
- ? inheritedDepth + 1
776
- : 1);
777
- const parentPath = input.parentPath ?? [
778
- ...parseNestedPathEnv(process.env[SUBAGENT_PARENT_PATH_ENV]),
779
- ...(parentRunId
780
- ? [
781
- {
782
- runId: parentRunId,
783
- ...(parentChildIndex && /^\d+$/.test(parentChildIndex)
784
- ? { stepIndex: Number(parentChildIndex) }
785
- : {}),
786
- ...(input.childAgentName ? { agent: input.childAgentName } : {}),
787
- },
788
- ]
789
- : []),
790
- ];
791
- env[SUBAGENT_PARENT_EVENT_SINK_ENV] = toolPlan.fanoutAuthorized
792
- ? (input.parentEventSink ??
793
- process.env[SUBAGENT_PARENT_EVENT_SINK_ENV] ??
794
- "")
795
- : "";
796
- env[SUBAGENT_PARENT_CONTROL_INBOX_ENV] = toolPlan.fanoutAuthorized
797
- ? (input.parentControlInbox ??
798
- process.env[SUBAGENT_PARENT_CONTROL_INBOX_ENV] ??
799
- "")
800
- : "";
801
- env[SUBAGENT_PARENT_ROOT_RUN_ID_ENV] = toolPlan.fanoutAuthorized
802
- ? (input.parentRootRunId ??
803
- process.env[SUBAGENT_PARENT_ROOT_RUN_ID_ENV] ??
804
- input.runId ??
805
- "")
806
- : "";
807
- env[SUBAGENT_PARENT_RUN_ID_ENV] = toolPlan.fanoutAuthorized
808
- ? parentRunId
809
- : "";
810
- env[SUBAGENT_PARENT_CHILD_INDEX_ENV] = toolPlan.fanoutAuthorized
811
- ? parentChildIndex
812
- : "";
813
- env[SUBAGENT_PARENT_DEPTH_ENV] = toolPlan.fanoutAuthorized
814
- ? String(parentDepth)
815
- : "";
816
- env[SUBAGENT_PARENT_PATH_ENV] = toolPlan.fanoutAuthorized
817
- ? encodeNestedPathEnv(parentPath)
818
- : "";
819
- env[SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV] = toolPlan.fanoutAuthorized
820
- ? (input.parentCapabilityToken ??
821
- process.env[SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV] ??
822
- "")
823
- : "";
824
- env[RUN_FANOUT_BUDGET_ENV] = toolPlan.fanoutAuthorized
825
- ? (input.runFanoutBudget ? encodeRunFanoutBudgetDescriptor(input.runFanoutBudget) : process.env[RUN_FANOUT_BUDGET_ENV])
826
- : undefined;
827
- env.PI_SUBAGENT_INHERIT_PROJECT_CONTEXT = input.inheritProjectContext
828
- ? "1"
829
- : "0";
830
- env.PI_SUBAGENT_INHERIT_SKILLS = input.inheritSkills ? "1" : "0";
831
- env[PI_INTERCOM_STABLE_ID_ENV] = input.intercomSessionName || undefined;
832
- env[PI_INTERCOM_SESSION_ID_ENV] = undefined;
833
- if (input.intercomSessionName) {
834
- env.PI_SUBAGENT_INTERCOM_SESSION_NAME = input.intercomSessionName;
835
- }
836
- if (input.orchestratorIntercomTarget) {
837
- env[SUBAGENT_ORCHESTRATOR_TARGET_ENV] = input.orchestratorIntercomTarget;
838
- }
839
- if (input.parentSessionId) {
840
- env[SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV] = input.parentSessionId;
841
- }
842
- const encodedPermissionRules = encodePermissionRules(input.permissionRules);
843
- if (
844
- input.orchestratorIntercomTarget &&
845
- input.parentSessionId &&
846
- input.runId &&
847
- input.childAgentName
848
- ) {
849
- const childIndex = input.childIndex ?? 0;
850
- const channelDir = supervisorChannelDir(
851
- input.runId,
852
- input.childAgentName,
853
- childIndex,
854
- );
855
- fs.mkdirSync(path.join(channelDir, "requests"), { recursive: true });
856
- fs.mkdirSync(path.join(channelDir, "replies"), { recursive: true });
857
- env[SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV] = channelDir;
858
- }
859
- if (encodedPermissionRules)
860
- env[PERMISSION_AUDIT_PATH_ENV] =
861
- input.permissionAuditPath ?? path.join(tempDir, "permission-audit.jsonl");
862
- if (input.runId) {
863
- env[SUBAGENT_RUN_ID_ENV] = input.runId;
864
- }
865
- if (input.childAgentName) {
866
- env[SUBAGENT_CHILD_AGENT_ENV] = input.childAgentName;
867
- }
868
- if (input.childIndex !== undefined) {
869
- env[SUBAGENT_CHILD_INDEX_ENV] = String(input.childIndex);
870
- }
871
- if (!toolPlan.capabilityCeiling && input.mcpDirectTools?.length)
872
- env.MCP_DIRECT_TOOLS = input.mcpDirectTools.join(",");
873
- else if (
874
- toolPlan.capabilityCeiling &&
875
- toolPlan.effectiveMcpSelections.length &&
876
- !toolPlan.capabilityCeiling.denyExtensions
877
- )
878
- env.MCP_DIRECT_TOOLS = toolPlan.effectiveMcpSelections
879
- .map((selection) => selection.selector)
880
- .join(",");
881
- else env.MCP_DIRECT_TOOLS = "__none__";
882
- const encodedCapabilityCeiling = encodeSubagentCapabilityCeiling(
883
- toolPlan.capabilityCeiling,
884
- );
885
- const thinkingCeiling = intersectThinkingCeilings(
886
- input.thinkingCeiling,
887
- decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]),
888
- );
889
- if (thinkingCeiling) env[SUBAGENT_THINKING_CEILING_ENV] = thinkingCeiling;
890
- if (encodedCapabilityCeiling)
891
- env[SUBAGENT_CAPABILITY_CEILING_ENV] = encodedCapabilityCeiling;
892
- if (encodedPermissionRules)
893
- env[PERMISSION_POLICY_ENV] = encodedPermissionRules;
894
- if (input.structuredOutput) {
895
- env[STRUCTURED_OUTPUT_CAPTURE_ENV] = input.structuredOutput.outputPath;
896
- env[STRUCTURED_OUTPUT_SCHEMA_ENV] = input.structuredOutput.schemaPath;
897
- if (input.structuredOutput.acceptanceReportPath) env[STRUCTURED_OUTPUT_ACCEPTANCE_CAPTURE_ENV] = input.structuredOutput.acceptanceReportPath;
898
- }
899
- if (input.steerInboxDir) {
900
- env[SUBAGENT_STEER_INBOX_ENV] = input.steerInboxDir;
901
- }
902
- if (input.steerCapabilityPath)
903
- env[SUBAGENT_STEER_CAPABILITY_ENV] = input.steerCapabilityPath;
904
- if (input.steerAckDir) env[SUBAGENT_STEER_ACK_DIR_ENV] = input.steerAckDir;
905
- const encodedToolBudget = encodeToolBudgetEnv(input.toolBudget);
906
- if (encodedToolBudget) env[TOOL_BUDGET_ENV] = encodedToolBudget;
907
- env[TOOL_BUDGET_ZERO_AUTH_ENV] = input.allowZeroToolBudget ? "1" : undefined;
908
- const encodedChildWatchdog = encodeChildWatchdogConfig(input.childWatchdog);
909
- if (encodedChildWatchdog)
910
- env[CHILD_WATCHDOG_CONFIG_ENV] = encodedChildWatchdog;
911
-
912
- env[SUBAGENT_PARENT_SESSION_ENV] =
913
- input.parentSessionId ?? process.env[SUBAGENT_PARENT_SESSION_ENV] ?? "";
914
-
915
- return {
916
- args,
917
- env,
918
- warnings: toolPlan.warnings,
919
- tempDir,
920
- toolDiagnosticPath,
921
- runtimeAcknowledgedExtensionsPath,
922
- capabilityAudit: toolPlan.capabilityAudit,
923
- };
924
- }
925
-
926
- export const parseParentPathEnv = parseNestedPathEnv;
927
-
928
- export function cleanupTempDir(tempDir: string | null | undefined): void {
929
- if (!tempDir) return;
930
- try {
931
- fs.rmSync(tempDir, { recursive: true, force: true });
932
- } catch {
933
- // Temp cleanup is best effort.
934
- }
935
- }