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