@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
@@ -0,0 +1,632 @@
1
+ /**
2
+ * Child tool plan: which builtin tools, MCP tools, runtime hooks, and extension
3
+ * files a child launch gets, and how that resolution is reported. Both the
4
+ * foreground path and the async runner build their session launch from this.
5
+ */
6
+ import { createHash } from "node:crypto";
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import {
11
+ formatUnresolvedMcpDirectToolSelectors,
12
+ resolveMcpDirectToolResolution,
13
+ type McpRuntimeSnapshotHost,
14
+ type ResolvedMcpDirectToolSelection,
15
+ } from "./mcp-direct-tool-allowlist.ts";
16
+ import {
17
+ TEMP_ROOT_DIR,
18
+ type JsonSchemaObject,
19
+ type LaunchResolvedChildExtensionsV1,
20
+ } from "../../shared/types.ts";
21
+ import { THINKING_LEVELS } from "../../shared/model-info.ts";
22
+ import { getAgentDir } from "../../shared/utils.ts";
23
+ import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
24
+ import type { PermissionRules } from "./permissions.ts";
25
+ import {
26
+ capabilityCeilingAgentRestrictionSources,
27
+ intersectSubagentCapabilityCeilings,
28
+ isAgentAllowedByCapabilityCeiling,
29
+ type ResolvedSubagentCapabilityCeiling,
30
+ type SubagentCapabilityAudit,
31
+ } from "./capability-ceiling.ts";
32
+
33
+ const MAX_LAUNCH_RESOLVED_EXTENSION_IDS = 32;
34
+ const PROMPT_RUNTIME_EXTENSION_PATH = path.join(
35
+ path.dirname(fileURLToPath(import.meta.url)),
36
+ "subagent-prompt-runtime.ts",
37
+ );
38
+ const FANOUT_CHILD_EXTENSION_PATH = path.join(
39
+ path.dirname(fileURLToPath(import.meta.url)),
40
+ "..",
41
+ "..",
42
+ "extension",
43
+ "fanout-child.ts",
44
+ );
45
+ const FAST_MODE_EXTENSION_PATH = path.join(
46
+ path.dirname(fileURLToPath(import.meta.url)),
47
+ "fast-mode-extension.ts",
48
+ );
49
+ const SANDBOX_PROFILE_GUARD_EXTENSION_PATH = path.join(
50
+ path.dirname(fileURLToPath(import.meta.url)),
51
+ "sandbox-profile-guard.ts",
52
+ );
53
+ const SUBAGENT_RUNTIME_EXTENSION_PATHS = new Set([
54
+ PROMPT_RUNTIME_EXTENSION_PATH,
55
+ FANOUT_CHILD_EXTENSION_PATH,
56
+ FAST_MODE_EXTENSION_PATH,
57
+ ].map((extensionPath) => path.normalize(extensionPath)));
58
+
59
+ /** True for the extension files pi-subagents itself installs in child sessions. */
60
+ export function isSubagentRuntimeExtensionPath(extensionPath: string): boolean {
61
+ return SUBAGENT_RUNTIME_EXTENSION_PATHS.has(path.normalize(extensionPath));
62
+ }
63
+ const FAST_MODE_ALLOWED_MODELS = new Set([
64
+ "openai-codex/gpt-5.6-luna",
65
+ "openai-codex/gpt-5.6-sol",
66
+ ]);
67
+ const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64;
68
+
69
+ export function deriveForkPromptCacheKey(parentSessionId: string | undefined): string | undefined {
70
+ const parent = parentSessionId?.trim();
71
+ if (!parent) return undefined;
72
+ const digest = createHash("sha256").update(parent).digest("hex").slice(0, OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH - "pi-fork:".length);
73
+ return `pi-fork:${digest}`;
74
+ }
75
+
76
+ function sanitizeSupervisorChannelSegment(value: string): string {
77
+ return (
78
+ value
79
+ .trim()
80
+ .replace(/[^A-Za-z0-9._-]+/g, "-")
81
+ .replace(/^-+|-+$/g, "") || "unknown"
82
+ );
83
+ }
84
+
85
+ export function supervisorChannelDir(
86
+ runId: string,
87
+ agent: string,
88
+ childIndex: number,
89
+ ): string {
90
+ return path.join(
91
+ TEMP_ROOT_DIR,
92
+ "supervisor-channels",
93
+ `${sanitizeSupervisorChannelSegment(runId)}-${sanitizeSupervisorChannelSegment(agent)}-${childIndex}`,
94
+ );
95
+ }
96
+
97
+ export function applyThinkingSuffix(
98
+ model: string | undefined,
99
+ thinking: string | false | undefined,
100
+ replaceExisting = false,
101
+ ): string | undefined {
102
+ if (!model || !thinking) return model;
103
+ const colonIdx = model.lastIndexOf(":");
104
+ if (
105
+ colonIdx !== -1 &&
106
+ THINKING_LEVELS.some((level) => level === model.substring(colonIdx + 1))
107
+ ) {
108
+ return replaceExisting ? `${model.slice(0, colonIdx)}:${thinking}` : model;
109
+ }
110
+ return `${model}:${thinking}`;
111
+ }
112
+
113
+ function stripThinkingSuffix(model: string): string {
114
+ const colonIdx = model.lastIndexOf(":");
115
+ if (colonIdx === -1) return model;
116
+ return THINKING_LEVELS.some((level) => level === model.substring(colonIdx + 1))
117
+ ? model.slice(0, colonIdx)
118
+ : model;
119
+ }
120
+
121
+ function resolveFastModeExtension(input: Pick<ResolvePiLaunchToolPlanInput, "fast" | "model" | "modelCandidates" | "agentName">): string[] {
122
+ if (!input.fast) return [];
123
+ const candidates = (input.modelCandidates?.length ? input.modelCandidates : input.model ? [input.model] : [])
124
+ .map(stripThinkingSuffix);
125
+ if (candidates.length === 0) {
126
+ throw new Error(`fast mode requires an explicit supported native OpenAI-Codex model${input.agentName ? ` for agent '${input.agentName}'` : ""}.`);
127
+ }
128
+ const unsupported = candidates.filter((model) => !FAST_MODE_ALLOWED_MODELS.has(model));
129
+ if (unsupported.length > 0) {
130
+ throw new Error(`fast mode supports only ${[...FAST_MODE_ALLOWED_MODELS].join(", ")}; unsupported model${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.`);
131
+ }
132
+ return [FAST_MODE_EXTENSION_PATH];
133
+ }
134
+
135
+ export interface ResolvePiLaunchToolPlanInput {
136
+ tools?: string[];
137
+ excludeTools?: string[];
138
+ allowNestedSubagents?: boolean;
139
+ extensions?: string[];
140
+ subagentOnlyExtensions?: string[];
141
+ mcpDirectTools?: string[];
142
+ cwd?: string;
143
+ requireReadTool?: boolean;
144
+ structuredOutput?:
145
+ | boolean
146
+ | {
147
+ schema: JsonSchemaObject;
148
+ schemaPath: string;
149
+ outputPath: string;
150
+ };
151
+ fast?: boolean;
152
+ model?: string;
153
+ modelCandidates?: readonly string[];
154
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
155
+ inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
156
+ agentName?: string;
157
+ permissionRules?: PermissionRules;
158
+ runtimeSnapshotHost?: McpRuntimeSnapshotHost;
159
+ /** A validated global pi-sandbox profile selected by the agent definition. */
160
+ sandbox?: string;
161
+ }
162
+
163
+ export interface PiLaunchToolPlan {
164
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
165
+ requestedBuiltinTools: string[];
166
+ declaredBuiltinTools: string[];
167
+ excludeTools: string[];
168
+ toolExtensionPaths: string[];
169
+ resolvedMcpSelections: ResolvedMcpDirectToolSelection[];
170
+ effectiveMcpSelections: ResolvedMcpDirectToolSelection[];
171
+ effectiveMcpTools: string[];
172
+ explicitToolAllowlist: boolean;
173
+ internalTools: string[];
174
+ effectiveToolAllowlist: string[];
175
+ requiredChildTools: string[];
176
+ fanoutAuthorized: boolean;
177
+ /** Absolute path of the resolved pi-sandbox child extension when a sandbox profile is selected. */
178
+ sandboxExtension?: string;
179
+ runtimeExtensions: string[];
180
+ configuredExtensions: string[];
181
+ extensionArgs: string[];
182
+ disableAmbientExtensions: boolean;
183
+ capabilityAudit?: SubagentCapabilityAudit;
184
+ /** Non-fatal launch warnings; they do not change behavior. */
185
+ warnings: string[];
186
+ }
187
+
188
+ function extensionIdentifier(value: string): string {
189
+ return `sha256:${createHash("sha256").update(path.normalize(value.trim())).digest("hex").slice(0, 16)}`;
190
+ }
191
+
192
+ function boundedExtensionIdentifiers(values: string[]): {
193
+ ids: string[];
194
+ omitted: number;
195
+ } {
196
+ const ids = [...new Set(values.map(extensionIdentifier))];
197
+ return {
198
+ ids: ids.slice(0, MAX_LAUNCH_RESOLVED_EXTENSION_IDS),
199
+ omitted: Math.max(0, ids.length - MAX_LAUNCH_RESOLVED_EXTENSION_IDS),
200
+ };
201
+ }
202
+
203
+ function hasPermissionRules(rules: PermissionRules | undefined): boolean {
204
+ return rules !== undefined && Object.keys(rules).length > 0;
205
+ }
206
+
207
+ /**
208
+ * Children are pi sessions inside the parent or the runner process; a spawned
209
+ * `pi` received extra MCP server definitions as a CLI argument, but a session
210
+ * has no such input. Selecting a server that exists only in pi-mcp-adapter's
211
+ * runtime snapshot therefore cannot work and fails the launch.
212
+ */
213
+ export function formatRuntimeSnapshotMcpServersError(agentName: string | undefined, serverNames: readonly string[]): string {
214
+ const subject = agentName ? `Agent '${agentName}'` : "Subagent";
215
+ return `${subject} selects MCP tools from servers that exist only in pi-mcp-adapter's runtime snapshot (${serverNames.join(", ")}). MCP servers from the runtime snapshot cannot be provided to in-process children; MCP tools must come from an ambient adapter extension in a background child (\`async: true\`), so add the server to the adapter's configuration file instead.`;
216
+ }
217
+
218
+ export function projectLaunchResolvedChildExtensions(
219
+ toolPlan: Pick<
220
+ PiLaunchToolPlan,
221
+ | "runtimeExtensions"
222
+ | "configuredExtensions"
223
+ | "extensionArgs"
224
+ | "disableAmbientExtensions"
225
+ >,
226
+ ): LaunchResolvedChildExtensionsV1 {
227
+ const runtime = boundedExtensionIdentifiers(toolPlan.runtimeExtensions);
228
+ const configured = boundedExtensionIdentifiers(toolPlan.configuredExtensions);
229
+ const effective = boundedExtensionIdentifiers(toolPlan.extensionArgs);
230
+ return {
231
+ version: 1,
232
+ source: "launch-resolved",
233
+ disableAmbientExtensions: toolPlan.disableAmbientExtensions,
234
+ runtime: runtime.ids,
235
+ configured: configured.ids,
236
+ effective: effective.ids,
237
+ omitted: {
238
+ runtime: runtime.omitted,
239
+ configured: configured.omitted,
240
+ effective: effective.omitted,
241
+ },
242
+ };
243
+ }
244
+
245
+ /**
246
+ * Resolve the permission-system extension entry point when installed.
247
+ * Returns the absolute path to the extension's main module, or undefined
248
+ * when the package is not installed. Callers can check `autoInject` config
249
+ * to decide whether to include it in child sessions.
250
+ */
251
+ export function resolvePermissionSystemExtension(): string | undefined {
252
+ const agentDir = getAgentDir();
253
+ const candidates = [
254
+ // Fork: the @xzzpig fork takes priority so child processes inherit the
255
+ // same permission system the parent session loads from settings.json.
256
+ // When only the upstream package is installed, behavior is unchanged.
257
+ path.join(
258
+ agentDir,
259
+ "npm",
260
+ "node_modules",
261
+ "@xzzpig",
262
+ "pi-permission-system",
263
+ ),
264
+ // npm-scoped package (most common)
265
+ path.join(
266
+ agentDir,
267
+ "npm",
268
+ "node_modules",
269
+ "@gotgenes",
270
+ "pi-permission-system",
271
+ ),
272
+ // direct extension directory (some layouts)
273
+ path.join(agentDir, "extensions", "pi-permission-system"),
274
+ ];
275
+ const errors: Error[] = [];
276
+ for (const extDir of candidates) {
277
+ if (!fs.existsSync(extDir)) continue;
278
+ const pkgPath = path.join(extDir, "package.json");
279
+ if (!fs.existsSync(pkgPath)) {
280
+ errors.push(new Error(`Permission-system package manifest is missing at ${pkgPath}.`));
281
+ continue;
282
+ }
283
+ try {
284
+ let pkg: { pi?: { extensions?: string[] } };
285
+ const parsed: unknown = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
286
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
287
+ throw new Error("manifest root must be an object");
288
+ }
289
+ pkg = parsed as typeof pkg;
290
+ const extensions = pkg.pi?.extensions;
291
+ const entry = Array.isArray(extensions) ? extensions[0] : undefined;
292
+ if (typeof entry !== "string" || !entry.trim()) {
293
+ throw new Error(
294
+ `Permission-system package manifest at ${pkgPath} must declare pi.extensions[0] as a non-empty string.`,
295
+ );
296
+ }
297
+ const resolved = path.resolve(extDir, entry);
298
+ if (fs.existsSync(resolved)) return resolved;
299
+ throw new Error(
300
+ `Permission-system extension entry ${JSON.stringify(entry)} in ${pkgPath} does not exist at ${resolved}.`,
301
+ );
302
+ } catch (error) {
303
+ const message = error instanceof Error ? error.message : String(error);
304
+ errors.push(message.startsWith("Permission-system") ? new Error(message) : new Error(`Cannot read permission-system package manifest at ${pkgPath}: ${message}`));
305
+ }
306
+ }
307
+ if (errors.length > 0) throw errors[0]!;
308
+ return undefined;
309
+ }
310
+
311
+ export function resolveSandboxExtensionForProfile(profileName: string): string {
312
+ validateSandboxProfileName(profileName, "sandbox profile");
313
+ return resolveSandboxExtension();
314
+ }
315
+
316
+ function resolveSandboxExtension(): string {
317
+ const agentDir = getAgentDir();
318
+ const candidates = [
319
+ path.join(agentDir, "npm", "node_modules", "@xzzpig", "pi-sandbox"),
320
+ path.join(agentDir, "npm", "node_modules", "pi-sandbox"),
321
+ path.join(agentDir, "extensions", "pi-sandbox"),
322
+ ];
323
+ const errors: Error[] = [];
324
+ let foundPackage = false;
325
+ for (const extDir of candidates) {
326
+ if (!fs.existsSync(extDir)) continue;
327
+ foundPackage = true;
328
+ const pkgPath = path.join(extDir, "package.json");
329
+ if (!fs.existsSync(pkgPath)) {
330
+ errors.push(new Error(`Sandbox package manifest is missing at ${pkgPath}.`));
331
+ continue;
332
+ }
333
+ try {
334
+ const parsed: unknown = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
335
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
336
+ throw new Error("manifest root must be an object");
337
+ }
338
+ const manifest = parsed as { name?: unknown; pi?: { extensions?: unknown } };
339
+ if (manifest.name !== "@xzzpig/pi-sandbox" && manifest.name !== "pi-sandbox") {
340
+ throw new Error(`Sandbox package manifest at ${pkgPath} must declare name '@xzzpig/pi-sandbox' or 'pi-sandbox'.`);
341
+ }
342
+ const extensions = manifest.pi?.extensions;
343
+ const entry = Array.isArray(extensions) ? extensions[0] : undefined;
344
+ if (typeof entry !== "string" || !entry.trim()) {
345
+ throw new Error(`Sandbox package manifest at ${pkgPath} must declare pi.extensions[0] as a non-empty string.`);
346
+ }
347
+ if (path.isAbsolute(entry)) {
348
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} must be relative to the package directory.`);
349
+ }
350
+ const resolved = path.resolve(extDir, entry);
351
+ const relative = path.relative(extDir, resolved);
352
+ if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
353
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} must remain inside ${extDir}.`);
354
+ }
355
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
356
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} does not resolve to a file at ${resolved}.`);
357
+ }
358
+ const realPackageRoot = fs.realpathSync(extDir);
359
+ const realEntry = fs.realpathSync(resolved);
360
+ const realRelative = path.relative(realPackageRoot, realEntry);
361
+ if (!realRelative || realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
362
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} resolves outside ${extDir}.`);
363
+ }
364
+ return resolved;
365
+ } catch (error) {
366
+ const message = error instanceof Error ? error.message : String(error);
367
+ errors.push(message.startsWith("Sandbox") ? new Error(message) : new Error(`Cannot read sandbox package manifest at ${pkgPath}: ${message}`));
368
+ }
369
+ }
370
+ if (errors.length > 0) throw errors[0]!;
371
+ if (!foundPackage) {
372
+ throw new Error(`pi-sandbox is not installed; cannot launch a child with sandbox profile.`);
373
+ }
374
+ throw new Error(`No usable pi-sandbox extension manifest was found under '${agentDir}'.`);
375
+ }
376
+
377
+ export function resolvePiLaunchToolPlan(
378
+ input: ResolvePiLaunchToolPlanInput,
379
+ ): PiLaunchToolPlan {
380
+ const capabilityCeiling = intersectSubagentCapabilityCeilings(
381
+ input.capabilityCeiling,
382
+ input.inheritedCapabilityCeiling,
383
+ );
384
+ const allowedToolSet =
385
+ capabilityCeiling?.allowedTools === undefined
386
+ ? undefined
387
+ : new Set(capabilityCeiling.allowedTools);
388
+ const requestedBuiltinTools =
389
+ input.tools?.filter(
390
+ (tool) =>
391
+ !(tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")),
392
+ ) ?? [];
393
+ if (input.requireReadTool && allowedToolSet && !allowedToolSet.has("read")) {
394
+ throw new Error(
395
+ `Capability ceiling from ${capabilityCeiling?.sources.join(", ") || "unknown source"} excludes required tool 'read' for lazy skill loading.`,
396
+ );
397
+ }
398
+ const declaredBuiltinTools =
399
+ input.tools === undefined
400
+ ? allowedToolSet
401
+ ? [...allowedToolSet]
402
+ : []
403
+ : (input.requireReadTool &&
404
+ requestedBuiltinTools.length > 0 &&
405
+ !requestedBuiltinTools.includes("read") &&
406
+ !allowedToolSet
407
+ ? ["read", ...requestedBuiltinTools]
408
+ : requestedBuiltinTools
409
+ ).filter((tool) => !allowedToolSet || allowedToolSet.has(tool));
410
+ const excludeTools = [...new Set((input.excludeTools ?? []).map((tool) => tool.trim()).filter(Boolean))];
411
+ const excludedToolSet = new Set(excludeTools);
412
+ const effectiveDeclaredBuiltinTools = declaredBuiltinTools.filter((tool) => !excludedToolSet.has(tool));
413
+ const fanoutAuthorized = effectiveDeclaredBuiltinTools.includes("subagent") || (
414
+ input.allowNestedSubagents === true &&
415
+ !excludedToolSet.has("subagent") &&
416
+ (!allowedToolSet || allowedToolSet.has("subagent"))
417
+ );
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 mcpResolution = capabilityCeiling?.denyExtensions
426
+ ? { selections: [], unresolvedSelectors: [] }
427
+ : resolveMcpDirectToolResolution(input.mcpDirectTools, input.cwd, input.runtimeSnapshotHost);
428
+ if (mcpResolution.runtimeServerNames?.length) {
429
+ throw new Error(formatRuntimeSnapshotMcpServersError(input.agentName, mcpResolution.runtimeServerNames));
430
+ }
431
+ if (mcpResolution.unresolvedSelectors.length > 0) {
432
+ throw new Error(formatUnresolvedMcpDirectToolSelectors(mcpResolution.unresolvedSelectors));
433
+ }
434
+ const resolvedMcpSelections = mcpResolution.selections;
435
+ const resolvedMcpNames = new Set(resolvedMcpSelections.map((selection) => selection.name));
436
+ const legacyMcpNameCounts = countLegacyUnderscoreMcpToolNames(resolvedMcpSelections);
437
+ const effectiveMcpSelections = resolvedMcpSelections.filter(
438
+ (selection) =>
439
+ !allowedToolSet ||
440
+ allowedToolSet.has(selection.name) ||
441
+ isLegacyUnderscoreMcpToolAllowed(selection, allowedToolSet, resolvedMcpNames, legacyMcpNameCounts),
442
+ ).filter((selection) => !excludedToolSet.has(selection.name));
443
+ const effectiveMcpTools = effectiveMcpSelections.map(
444
+ (selection) => selection.name,
445
+ );
446
+ const explicitToolAllowlist =
447
+ input.tools !== undefined ||
448
+ (input.mcpDirectTools?.length ?? 0) > 0 ||
449
+ allowedToolSet !== undefined;
450
+ const internalTools = (input.structuredOutput ? ["structured_output"] : []).filter((tool) => !excludedToolSet.has(tool));
451
+ const effectiveToolAllowlist = [
452
+ ...new Set([
453
+ ...effectiveDeclaredBuiltinTools,
454
+ ...effectiveMcpTools,
455
+ ...internalTools,
456
+ ]),
457
+ ];
458
+ // Supervisor-coordination names stay in the --tools allowlist but are never
459
+ // strict requirements: children register contact_supervisor at runtime through
460
+ // the native supervisor channel (or pi-intercom). The pre-0.50 bridge always
461
+ // appended intercom alongside contact_supervisor, so that exact pairing is
462
+ // legacy plumbing, not a user demand for an external intercom provider;
463
+ // a lone intercom entry stays strictly required (#1207).
464
+ const legacySupervisorPairing = effectiveDeclaredBuiltinTools.includes("contact_supervisor");
465
+ const requiredChildTools = explicitToolAllowlist
466
+ ? [
467
+ ...new Set([
468
+ ...(input.tools !== undefined ? effectiveDeclaredBuiltinTools : []),
469
+ ...(input.mcpDirectTools?.length ? effectiveMcpTools : []),
470
+ ...internalTools,
471
+ ].filter((tool) => tool !== "contact_supervisor" && (!legacySupervisorPairing || tool !== "intercom"))),
472
+ ]
473
+ : [];
474
+ const permSystemExt = capabilityCeiling?.denyExtensions
475
+ ? undefined
476
+ : hasPermissionRules(input.permissionRules)
477
+ ? resolvePermissionSystemExtension()
478
+ : undefined;
479
+ const sandboxProfile = input.sandbox === undefined
480
+ ? undefined
481
+ : validateSandboxProfileName(input.sandbox, "sandbox profile");
482
+ if (sandboxProfile && capabilityCeiling?.denyExtensions) {
483
+ throw new Error(`Sandbox profile '${sandboxProfile}' requires the pi-sandbox child extension, but this launch denies child extensions.`);
484
+ }
485
+ let sandboxExtension: string | undefined;
486
+ if (sandboxProfile) {
487
+ try {
488
+ sandboxExtension = resolveSandboxExtensionForProfile(sandboxProfile);
489
+ } catch (error) {
490
+ const message = error instanceof Error ? error.message : String(error);
491
+ throw new Error(`Sandbox profile '${sandboxProfile}' cannot be enabled: ${message}`);
492
+ }
493
+ }
494
+ if (input.fast && capabilityCeiling?.denyExtensions) throw new Error("fast mode requires a child runtime extension, but this launch denies extensions.");
495
+ const fastModeExtensions = resolveFastModeExtension({ fast: input.fast, model: input.model, modelCandidates: input.modelCandidates, agentName: input.agentName });
496
+ const runtimeExtensions = [
497
+ PROMPT_RUNTIME_EXTENSION_PATH,
498
+ ...fastModeExtensions,
499
+ ...(fanoutAuthorized ? [FANOUT_CHILD_EXTENSION_PATH] : []),
500
+ ...(permSystemExt ? [permSystemExt] : []),
501
+ ...(sandboxExtension ? [sandboxExtension, SANDBOX_PROFILE_GUARD_EXTENSION_PATH] : []),
502
+ ];
503
+ const disableAmbientExtensions =
504
+ capabilityCeiling?.denyExtensions === true ||
505
+ input.extensions !== undefined;
506
+ const warnings: string[] = [];
507
+ // An explicit empty list disables ambient extensions, including model providers.
508
+ if (capabilityCeiling?.denyExtensions !== true && Array.isArray(input.extensions) && input.extensions.length === 0) {
509
+ const agentLabel = input.agentName ? ` for agent '${input.agentName}'` : "";
510
+ warnings.push(
511
+ `extensions: [] override${agentLabel} disables ALL ambient extensions for this child (not just "adds nothing"), `
512
+ + "including any model-provider extension needed to resolve a provider-qualified model. "
513
+ + "List the extensions this child actually needs instead of an empty array.",
514
+ );
515
+ }
516
+ const configuredExtensions = capabilityCeiling?.denyExtensions
517
+ ? []
518
+ : [
519
+ ...toolExtensionPaths,
520
+ ...(input.extensions ?? []),
521
+ ...(input.subagentOnlyExtensions ?? []),
522
+ ];
523
+ const extensionArgs = disableAmbientExtensions
524
+ ? [...new Set([...runtimeExtensions, ...configuredExtensions])]
525
+ : [
526
+ ...new Set([
527
+ ...runtimeExtensions,
528
+ ...toolExtensionPaths,
529
+ ...(input.subagentOnlyExtensions ?? []),
530
+ ]),
531
+ ];
532
+ const requestedToolNames =
533
+ input.tools !== undefined
534
+ ? [
535
+ ...new Set([
536
+ ...requestedBuiltinTools,
537
+ ...resolvedMcpSelections.map((selection) => selection.name),
538
+ ]),
539
+ ]
540
+ : undefined;
541
+ const capabilityAudit = capabilityCeiling
542
+ ? ({
543
+ ceiling: capabilityCeiling,
544
+ ...(requestedToolNames ? { requestedTools: requestedToolNames } : {}),
545
+ effectiveTools: effectiveToolAllowlist,
546
+ ...(excludeTools.length > 0 ? { excludeTools } : {}),
547
+ removedTools:
548
+ requestedToolNames?.filter(
549
+ (tool) => !effectiveToolAllowlist.includes(tool),
550
+ ) ?? [],
551
+ internalTools,
552
+ extensionsDenied: capabilityCeiling.denyExtensions,
553
+ removedExtensionCount: capabilityCeiling.denyExtensions
554
+ ? (input.extensions?.length ?? 0) +
555
+ (input.subagentOnlyExtensions?.length ?? 0) +
556
+ (input.tools ?? []).filter(
557
+ (tool) =>
558
+ tool.includes("/") ||
559
+ tool.endsWith(".ts") ||
560
+ tool.endsWith(".js"),
561
+ ).length
562
+ : 0,
563
+ requestedMcpToolCount: input.mcpDirectTools?.length ?? 0,
564
+ effectiveMcpTools,
565
+ agentAllowed:
566
+ input.agentName === undefined
567
+ ? true
568
+ : isAgentAllowedByCapabilityCeiling(
569
+ input.agentName,
570
+ capabilityCeiling,
571
+ ),
572
+ ...(capabilityCeilingAgentRestrictionSources(capabilityCeiling)
573
+ ? {
574
+ agentRestrictionSources:
575
+ capabilityCeilingAgentRestrictionSources(capabilityCeiling),
576
+ }
577
+ : {}),
578
+ } satisfies SubagentCapabilityAudit)
579
+ : undefined;
580
+ return {
581
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
582
+ requestedBuiltinTools,
583
+ declaredBuiltinTools,
584
+ excludeTools,
585
+ toolExtensionPaths,
586
+ resolvedMcpSelections,
587
+ effectiveMcpSelections,
588
+ effectiveMcpTools,
589
+ explicitToolAllowlist,
590
+ internalTools,
591
+ effectiveToolAllowlist,
592
+ requiredChildTools,
593
+ fanoutAuthorized,
594
+ ...(sandboxExtension ? { sandboxExtension } : {}),
595
+ runtimeExtensions,
596
+ configuredExtensions,
597
+ extensionArgs,
598
+ disableAmbientExtensions,
599
+ warnings,
600
+ ...(capabilityAudit ? { capabilityAudit } : {}),
601
+ };
602
+ }
603
+
604
+ // Capability ceilings persisted before #1685 may still name hyphenated MCP server prefixes with underscores.
605
+ function countLegacyUnderscoreMcpToolNames(selections: readonly ResolvedMcpDirectToolSelection[]): Map<string, number> {
606
+ const counts = new Map<string, number>();
607
+ for (const selection of selections) {
608
+ const legacyName = legacyUnderscoreMcpToolName(selection);
609
+ if (legacyName !== selection.name) counts.set(legacyName, (counts.get(legacyName) ?? 0) + 1);
610
+ }
611
+ return counts;
612
+ }
613
+
614
+ function isLegacyUnderscoreMcpToolAllowed(
615
+ selection: ResolvedMcpDirectToolSelection,
616
+ allowedToolSet: ReadonlySet<string>,
617
+ resolvedMcpNames: ReadonlySet<string>,
618
+ legacyMcpNameCounts: ReadonlyMap<string, number>,
619
+ ): boolean {
620
+ const legacyName = legacyUnderscoreMcpToolName(selection);
621
+ return legacyMcpNameCounts.get(legacyName) === 1 && !resolvedMcpNames.has(legacyName) && allowedToolSet.has(legacyName);
622
+ }
623
+
624
+ function legacyUnderscoreMcpToolName(selection: ResolvedMcpDirectToolSelection): string {
625
+ const slash = selection.selector.indexOf("/");
626
+ if (slash < 1) return selection.name;
627
+ const toolName = selection.selector.slice(slash + 1);
628
+ const suffix = `_${toolName}`;
629
+ if (!selection.name.endsWith(suffix)) return selection.name;
630
+ const prefix = selection.name.slice(0, -suffix.length);
631
+ return `${prefix.replace(/-/g, "_")}${suffix}`;
632
+ }