@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -17,13 +17,13 @@ import {
17
17
  type HerdrMachineReference,
18
18
  } from "../../shared/types.ts";
19
19
  import type { NestedPathEntry } from "./nested-path.ts";
20
- import type { McpRuntimeSnapshotHost } from "./mcp-direct-tool-allowlist.ts";
20
+ import { extensionOnlyMcpServers, type McpRuntimeSnapshotHost, type ResolvedMcpDirectToolSelection } from "./mcp-direct-tool-allowlist.ts";
21
21
  import type { PermissionRules } from "./permissions.ts";
22
22
  import type { StructuredOutputRuntime } from "./structured-output.ts";
23
23
  import type { ChildToolDiagnostic } from "./tool-availability.ts";
24
24
  import type { RuntimeAcknowledgedChildExtensions } from "../../shared/types.ts";
25
25
  import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV, type ExtensionBindings } from "./extension-bindings.ts";
26
- import type { ResolvedSubagentCapabilityCeiling, SubagentCapabilityAudit } from "./capability-ceiling.ts";
26
+ import { intersectSubagentCapabilityCeilings, type ResolvedSubagentCapabilityCeiling, type SubagentCapabilityAudit } from "./capability-ceiling.ts";
27
27
  import { buildProfileLaunchEnv } from "./profile-launch-env.ts";
28
28
  import {
29
29
  isSubagentRuntimeExtensionPath,
@@ -36,7 +36,6 @@ import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
36
36
  import { createCapturedChildHooks, withChildSessionErrorReporting } from "./child-hooks.ts";
37
37
  import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
38
38
  import type { ChildSessionLaunch, ChildSessionStorage } from "./child-session.ts";
39
- import type { ArbiterModelContext } from "./llm-intent-arbiter.ts";
40
39
  import { resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
41
40
 
42
41
  /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
@@ -87,6 +86,8 @@ export interface BuildInProcessChildLaunchInput {
87
86
  requiredExtensions?: RequiredChildExtensionSnapshot;
88
87
  systemPrompt?: string | null;
89
88
  mcpDirectTools?: string[];
89
+ /** Selections the parent resolved against Pi's built-in MCP, carried to the runner. */
90
+ builtinMcpTools?: ResolvedMcpDirectToolSelection[];
90
91
  extensionBindings?: ExtensionBindings;
91
92
  cwd: string;
92
93
  intercomSessionName?: string;
@@ -107,6 +108,7 @@ export interface BuildInProcessChildLaunchInput {
107
108
  waitToolEnabled?: boolean;
108
109
  waitToolDefaultTimeoutMs?: number;
109
110
  allowNestedSubagents?: boolean;
111
+ descendantAllowedAgents?: string[];
110
112
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
111
113
  thinkingCeiling?: ThinkingLevel;
112
114
  maxSubagentDepth?: number;
@@ -115,6 +117,8 @@ export interface BuildInProcessChildLaunchInput {
115
117
  sandbox?: string;
116
118
  /** A validated global pi-permission-system profile selected by the agent definition. */
117
119
  permissionProfile?: string;
120
+ /** Builtin tool names the host runtime provides; intersects agent-declared core tools. */
121
+ hostAvailableBuiltins?: readonly string[];
118
122
  /** Parent-authoritative trust state for profile-aware project config merging. */
119
123
  projectTrusted?: boolean;
120
124
  /** Exact trusted parent cwd; profile project config applies only when the child cwd matches it. */
@@ -128,17 +132,9 @@ export interface BuildInProcessChildLaunchInput {
128
132
  * them and exposes the child environment external extensions read.
129
133
  */
130
134
  host: "parent" | "runner";
131
- /**
132
- * Pi core tool names the host runtime provides. When set, child tool plans
133
- * intersect known core slots with this set; declared non-core names remain
134
- * for child startup validation. Review/scout lanes fail closed when a requested,
135
- * still-permitted repository inspection tool is missing from that set.
136
- */
137
- hostAvailableBuiltins?: readonly string[];
138
135
  }
139
136
 
140
137
  export interface InProcessChildCapture {
141
- completionIntentContext?(): ArbiterModelContext | undefined;
142
138
  structuredOutput(): { called: boolean; value?: unknown; acceptanceReport?: unknown; acceptanceReportProvided: boolean };
143
139
  toolDiagnostic(): ChildToolDiagnostic | undefined;
144
140
  runtimeAcknowledgedExtensions(): RuntimeAcknowledgedChildExtensions | undefined;
@@ -180,7 +176,9 @@ function inheritedCapabilityCeiling(inherited: InheritedChildRuntime | undefined
180
176
  function childProcessEnv(input: BuildInProcessChildLaunchInput, toolPlan: PiLaunchToolPlan, sandboxEnv?: Record<string, string | undefined>): Record<string, string | undefined> {
181
177
  const env: Record<string, string | undefined> = {};
182
178
  env[PI_SUBAGENT_EXTENSION_BINDINGS_ENV] = encodeExtensionBindings(input.extensionBindings);
183
- if (!toolPlan.capabilityCeiling && input.mcpDirectTools?.length) env[MCP_DIRECT_TOOLS_ENV] = input.mcpDirectTools.join(",");
179
+ // Selectors resolved against Pi's built-in MCP never reach an adapter.
180
+ if (toolPlan.builtinMcpTools) env[MCP_DIRECT_TOOLS_ENV] = "__none__";
181
+ else if (!toolPlan.capabilityCeiling && input.mcpDirectTools?.length) env[MCP_DIRECT_TOOLS_ENV] = input.mcpDirectTools.join(",");
184
182
  else if (toolPlan.capabilityCeiling && toolPlan.effectiveMcpSelections.length && !toolPlan.capabilityCeiling.denyExtensions) {
185
183
  env[MCP_DIRECT_TOOLS_ENV] = toolPlan.effectiveMcpSelections.map((selection) => selection.selector).join(",");
186
184
  } else env[MCP_DIRECT_TOOLS_ENV] = "__none__";
@@ -202,6 +200,13 @@ function childStorage(input: BuildInProcessChildLaunchInput): ChildSessionStorag
202
200
 
203
201
  export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput): InProcessChildLaunch {
204
202
  const requiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
203
+ const agentCapabilityCeiling: ResolvedSubagentCapabilityCeiling | undefined = input.descendantAllowedAgents === undefined
204
+ ? undefined
205
+ : { version: 1, allowedAgents: [...input.descendantAllowedAgents], denyExtensions: false, sources: [`agent:${input.childAgentName}`] };
206
+ const inheritedCeiling = inheritedCapabilityCeiling(input.inherited);
207
+ const capabilityCeilingForPlanning = agentCapabilityCeiling && !input.capabilityCeiling && !inheritedCeiling
208
+ ? { version: 1 as const, denyExtensions: false, sources: [] }
209
+ : input.capabilityCeiling;
205
210
  const toolPlan = resolvePiLaunchToolPlan({
206
211
  tools: input.tools,
207
212
  excludeTools: input.excludeTools,
@@ -210,13 +215,14 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
210
215
  subagentOnlyExtensions: input.subagentOnlyExtensions,
211
216
  requiredExtensions,
212
217
  mcpDirectTools: input.mcpDirectTools,
218
+ builtinMcpTools: input.builtinMcpTools,
213
219
  cwd: input.cwd,
214
220
  requireReadTool: input.requireReadTool,
215
221
  structuredOutput: Boolean(input.structuredOutput),
216
222
  fast: input.fast,
217
223
  model: input.model,
218
- capabilityCeiling: input.capabilityCeiling,
219
- inheritedCapabilityCeiling: inheritedCapabilityCeiling(input.inherited),
224
+ capabilityCeiling: capabilityCeilingForPlanning,
225
+ inheritedCapabilityCeiling: inheritedCeiling,
220
226
  agentName: input.childAgentName,
221
227
  permissionRules: input.permissionRules,
222
228
  runtimeSnapshotHost: input.runtimeSnapshotHost,
@@ -224,6 +230,16 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
224
230
  permissionProfile: input.permissionProfile,
225
231
  hostAvailableBuiltins: input.hostAvailableBuiltins,
226
232
  });
233
+ // Foreground children load no ambient extensions, so an extension's registerMcpServer() never runs in them.
234
+ if (input.host === "parent" && input.runtimeSnapshotHost && toolPlan.builtinMcpTools?.length) {
235
+ // Pi treats a session without a trust decision as trusted.
236
+ const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false);
237
+ if (servers.length) throw new Error(`Agent '${input.childAgentName}' selects MCP tools from servers that extensions registered (${servers.join(", ")}). Only background children (async: true) load those extensions; run the agent in the background or add the server to the global mcp.json or a trusted project's .pi/mcp.json.`);
238
+ }
239
+ toolPlan.capabilityCeiling = intersectSubagentCapabilityCeilings(toolPlan.capabilityCeiling, agentCapabilityCeiling);
240
+ if (toolPlan.capabilityAudit && toolPlan.capabilityCeiling) {
241
+ toolPlan.capabilityAudit = { ...toolPlan.capabilityAudit, ceiling: toolPlan.capabilityCeiling };
242
+ }
227
243
 
228
244
  // Profile env construction (ack/diagnostics paths, sandbox and permission
229
245
  // profile keys, the pinned profile, and the transient host key list) lives
@@ -257,8 +273,10 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
257
273
  let structuredAcceptanceReport: unknown;
258
274
  let structuredCalled = false;
259
275
  let structuredAcceptanceProvided = false;
276
+ const structuredTerminalState = { captured: false };
260
277
 
261
278
  const config: ChildRuntimeConfig = {
279
+ cwd: input.cwd,
262
280
  ...(input.runId ? { runId: input.runId } : {}),
263
281
  agent: input.childAgentName,
264
282
  childIndex: input.childIndex,
@@ -292,6 +310,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
292
310
  ? {
293
311
  structuredOutput: {
294
312
  schema: input.structuredOutput.schema,
313
+ terminalState: structuredTerminalState,
295
314
  ...(input.structuredOutput.acceptanceReportPath
296
315
  ? { acceptanceReport: input.structuredOutput.acceptanceReportRequired ? "required" as const : "optional" as const }
297
316
  : {}),
@@ -300,6 +319,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
300
319
  structuredValue = value;
301
320
  structuredAcceptanceProvided = acceptanceReport !== undefined;
302
321
  structuredAcceptanceReport = acceptanceReport;
322
+ structuredTerminalState.captured = true;
303
323
  },
304
324
  },
305
325
  }
@@ -308,7 +328,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
308
328
  ...(toolPlan.effectiveMcpTools.length > 0 ? { mcpDirectTools: toolPlan.effectiveMcpTools } : {}),
309
329
  fast: input.fast === true,
310
330
  };
311
- const capturedHooks = createCapturedChildHooks(config, input.host === "runner");
331
+ const capturedHooks = createCapturedChildHooks(config);
312
332
 
313
333
  const extensionPaths = toolPlan.extensionArgs.filter((extensionPath) => !isSubagentRuntimeExtensionPath(extensionPath));
314
334
  const ambientExtensions = input.host === "runner" && !toolPlan.disableAmbientExtensions;
@@ -325,10 +345,12 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
325
345
  const session: Omit<ChildSessionLaunch, "onExtensionError"> = {
326
346
  cwd: input.cwd,
327
347
  ...(input.machine ? { machine: input.machine } : {}),
348
+ ...(input.projectTrusted !== undefined ? { projectTrusted: input.projectTrusted } : {}),
328
349
  ...(input.machine ? { remoteResources: { agent: input.childAgentName, ...(input.remoteSkillNames ? { skills: input.remoteSkillNames } : {}), ...(input.remoteReads !== undefined ? { reads: input.remoteReads } : {}), ...(toolPlan.explicitToolAllowlist ? { toolCeiling: [...toolPlan.effectiveToolAllowlist] } : toolPlan.capabilityCeiling?.allowedTools ? { toolCeiling: [...toolPlan.capabilityCeiling.allowedTools] } : {}) } } : {}),
329
350
  storage: childStorage(input),
330
351
  ...(input.model ? { model: input.model } : {}),
331
352
  ...(toolPlan.explicitToolAllowlist ? { tools: toolPlan.effectiveToolAllowlist } : {}),
353
+ ...(toolPlan.builtinMcpTools?.length ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
332
354
  ...(!toolPlan.explicitToolAllowlist && toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
333
355
  extensionPaths,
334
356
  requiredExtensions: toolPlan.requiredExtensions,
@@ -351,7 +373,6 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
351
373
  config,
352
374
  session,
353
375
  capture: {
354
- completionIntentContext: capturedHooks.completionIntentContext,
355
376
  structuredOutput: () => ({ called: structuredCalled, value: structuredValue, acceptanceReport: structuredAcceptanceReport, acceptanceReportProvided: structuredAcceptanceProvided }),
356
377
  toolDiagnostic: capturedHooks.toolDiagnostic,
357
378
  runtimeAcknowledgedExtensions: capturedHooks.runtimeAcknowledgedExtensions,
@@ -39,6 +39,8 @@ export interface ChildPermissions {
39
39
  export interface ChildStructuredOutput {
40
40
  schema: JsonSchemaObject;
41
41
  acceptanceReport?: "optional" | "required";
42
+ /** Authoritative child-local state set only after validated capture succeeds. */
43
+ terminalState?: { captured: boolean };
42
44
  /** Receives the validated value; `acceptanceReport` is undefined when the child omitted it. */
43
45
  capture: (value: unknown, acceptanceReport: unknown | undefined) => void;
44
46
  }
@@ -58,6 +60,7 @@ export interface ChildSupervisorMetadata {
58
60
  * that hosts the child session builds it and passes it to the hooks directly.
59
61
  */
60
62
  export interface ChildRuntimeConfig {
63
+ cwd?: string;
61
64
  runId?: string;
62
65
  agent?: string;
63
66
  childIndex?: number;
@@ -7,10 +7,15 @@
7
7
  * without the real runtime; the default implementation wraps
8
8
  * `createAgentSession` from a pi package module.
9
9
  */
10
+ import * as fs from "node:fs";
11
+ import * as path from "node:path";
12
+ import { pathToFileURL } from "node:url";
10
13
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
11
14
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
15
  import { pinChildCacheRetention } from "../../shared/child-cache-retention.ts";
13
- import { getAgentDir } from "../../shared/utils.ts";
16
+ import { getAgentDir, PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
17
+ import { resolvePackageSubpath } from "../background/runner-aliases.ts";
18
+ import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot, resolvePiPackageRoot } from "./pi-spawn.ts";
14
19
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
15
20
  import type { RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
16
21
  import type { HerdrMachineReference, HerdrRemoteGitStatus } from "../../shared/types.ts";
@@ -50,6 +55,8 @@ export interface ChildSessionLaunch {
50
55
  cwd: string;
51
56
  /** Resolved pane-native placement. Local launches omit this field. */
52
57
  machine?: HerdrMachineReference;
58
+ /** The launching session's project trust; undefined keeps Pi's default for hosts without trust. */
59
+ projectTrusted?: boolean;
53
60
  /** Process-local provider source owned by the invoking foreground parent. */
54
61
  parentProviderRegistry?: ParentProviderRegistry;
55
62
  /** Logical names resolved only by the remote ambient package. */
@@ -59,6 +66,8 @@ export interface ChildSessionLaunch {
59
66
  model?: string;
60
67
  /** Explicit tool allowlist; undefined keeps pi's defaults. */
61
68
  tools?: string[];
69
+ /** Tools of Pi's built-in MCP extension the child must declare to its model directly, with the `mcp:` selector that granted each; `tools` names them too. */
70
+ builtinMcpTools?: Array<{ name: string; selector: string }>;
62
71
  excludeTools?: string[];
63
72
  /** Extension files loaded for this child in addition to the inline hooks. */
64
73
  extensionPaths: string[];
@@ -108,6 +117,7 @@ export interface ChildSession {
108
117
  readonly sessionFile: string | undefined;
109
118
  readonly sessionId: string;
110
119
  readonly modelId: string | undefined;
120
+ readonly contextWindow?: number;
111
121
  readonly machineEvidence?: { machineId: string; initial?: HerdrRemoteGitStatus; final?: HerdrRemoteGitStatus };
112
122
  /** Event-updated pane-native status; reading it performs no network work. */
113
123
  readonly placementSnapshot?: unknown;
@@ -142,6 +152,8 @@ export interface DefaultChildSessionFactoryOptions {
142
152
  loadPiCodingAgent?: () => Promise<PiCodingAgentModule>;
143
153
  /** Upper bound on a disposed child's `session_shutdown` handlers before the session is dropped anyway. */
144
154
  shutdownTimeoutMs?: number;
155
+ /** Upper bound on the wait for selected built-in MCP tools to register after the session starts. */
156
+ builtinMcpToolWaitMs?: number;
145
157
  }
146
158
 
147
159
  type ModelRuntimeInstance = Awaited<ReturnType<PiCodingAgentModule["ModelRuntime"]["create"]>>;
@@ -225,6 +237,53 @@ function restoreProcessEnv(saved: Array<[string, string | undefined]>): void {
225
237
  }
226
238
  }
227
239
 
240
+ /**
241
+ * Pi's built-in MCP extension registers server tools with the configured exposure, `codemode` by
242
+ * default, which the child's `tools` allowlist cannot declare. Registering the selected names as
243
+ * `direct` makes them model-declared and callable; `hidden` stays hidden. A name counts only when
244
+ * the tool's raw identity, its `<server>/<tool>` label, matches the granting selector: Pi can give
245
+ * the sanitized name of `srv/a.b` to `srv/a_b`. Every other tool the extension registers becomes
246
+ * `hidden`, so neither codemode nor `ctx.executeTool()` can call it, independent of the `tools`
247
+ * allowlist. The `builtin` entry loads
248
+ * through the explicit `builtin:mcp` path even with `noExtensions`, and `replaceable` lets an
249
+ * ambient MCP extension that registers `/mcp` replace it, as in the parent.
250
+ */
251
+ function selectedBuiltinMcpExtension(pi: PiCodingAgentModule, selections: ReadonlyArray<{ name: string; selector: string }>): ChildHookExtension & { builtin: true; replaceable: true } {
252
+ // Pi 0.99 export; the pinned SDK types predate it.
253
+ const createMcpExtension = (pi as { createMcpExtension?: () => (api: ExtensionAPI) => void | Promise<void> }).createMcpExtension;
254
+ if (typeof createMcpExtension !== "function") throw new Error(`Selected built-in MCP tools (${selections.map(({ name }) => name).join(", ")}) need a Pi version with built-in MCP.`);
255
+ const selectors = new Map(selections.map(({ name, selector }) => [name, selector]));
256
+ const granted = (tool: { name: string; label?: string; exposure?: string }) => {
257
+ const selector = selectors.get(tool.name);
258
+ if (selector === undefined || tool.exposure === "hidden" || tool.label === undefined) return false;
259
+ return selector.includes("/") ? tool.label === selector : tool.label.startsWith(`${selector}/`);
260
+ };
261
+ const mcp = createMcpExtension();
262
+ const factory = (api: ExtensionAPI) => mcp(new Proxy(api, {
263
+ get(target, prop) {
264
+ if (prop === "registerTool") {
265
+ return (tool: Parameters<ExtensionAPI["registerTool"]>[0] & { exposure?: string }) =>
266
+ target.registerTool({ ...tool, exposure: granted(tool) ? "direct" : "hidden" } as typeof tool);
267
+ }
268
+ const value = Reflect.get(target, prop, target);
269
+ return typeof value === "function" ? value.bind(target) : value;
270
+ },
271
+ }));
272
+ return { name: "mcp", factory, builtin: true, replaceable: true };
273
+ }
274
+
275
+ /** MCP connects after `session_start`, so the selected tools register some time after the session binds. */
276
+ async function missingBuiltinMcpTools(session: { getAllTools(): Array<{ name: string }>; getActiveToolNames(): string[] }, names: readonly string[], timeoutMs: number, stopped: () => boolean): Promise<string[]> {
277
+ const deadline = Date.now() + timeoutMs;
278
+ for (;;) {
279
+ const active = new Set(session.getActiveToolNames());
280
+ const direct = new Set(session.getAllTools().filter((tool) => (tool as { exposure?: string }).exposure === "direct").map(({ name }) => name));
281
+ const missing = names.filter((name) => !active.has(name) || !direct.has(name));
282
+ if (missing.length === 0 || stopped() || Date.now() >= deadline) return missing;
283
+ await new Promise((resolve) => setTimeout(resolve, 50));
284
+ }
285
+ }
286
+
228
287
  function flushQueuedProviderRegistrations(loader: InstanceType<PiCodingAgentModule["DefaultResourceLoader"]>, modelRuntime: ModelRuntimeInstance, onError: ((error: ChildSessionExtensionError) => void) | undefined, requiredPaths: ReadonlySet<string>): { claimedProviderIds: Set<string>; registered: boolean } {
229
288
  const claimedProviderIds = new Set<string>();
230
289
  if (!("getExtensions" in loader) || typeof loader.getExtensions !== "function") return { claimedProviderIds, registered: false };
@@ -255,17 +314,64 @@ function flushQueuedProviderRegistrations(loader: InstanceType<PiCodingAgentModu
255
314
  return { claimedProviderIds, registered };
256
315
  }
257
316
 
317
+ /**
318
+ * Load the host-owned pi-coding-agent module by absolute package entry so a
319
+ * child cannot resolve an extension-owned copy. Root precedence is the running
320
+ * host, an explicit override, then the install tree. Once any root is selected,
321
+ * its manifest, package identity, entry, and import must all succeed; the bare
322
+ * specifier is used only when no root resolves.
323
+ */
324
+ export async function loadHostPiCodingAgent(): Promise<PiCodingAgentModule> {
325
+ const overrideRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]?.trim() || undefined;
326
+ const runningRoot = resolvePiPackageRoot();
327
+ const selectedOverride = runningRoot === undefined ? overrideRoot : undefined;
328
+ const root = runningRoot ?? selectedOverride ?? resolveInstalledPiPackageRoot();
329
+ if (root) {
330
+ const entry = fs.realpathSync(resolveHostPackageEntry(root, selectedOverride));
331
+ return import(pathToFileURL(entry).href);
332
+ }
333
+ return import(PI_CODING_AGENT_PACKAGE);
334
+ }
335
+
336
+ function resolveHostPackageEntry(root: string, overrideRoot: string | undefined): string {
337
+ const packageJson = path.join(root, "package.json");
338
+ const source = fs.readFileSync(packageJson, "utf8");
339
+ let parsed: unknown;
340
+ try {
341
+ parsed = JSON.parse(source);
342
+ } catch (error) {
343
+ throw new Error(`invalid host SDK manifest at ${packageJson}: malformed JSON`, { cause: error });
344
+ }
345
+ if (!isUnknownRecord(parsed)) throw new Error(`invalid host SDK manifest at ${packageJson}: expected a JSON object`);
346
+ const pkg = parsed;
347
+ if (pkg.name !== PI_CODING_AGENT_PACKAGE) {
348
+ const source = overrideRoot !== undefined ? ` (${PI_CODING_AGENT_PACKAGE_ROOT_ENV} override)` : "";
349
+ throw new Error(`refusing to load the host SDK from ${root}${source}: package.json name is "${String(pkg.name ?? "(none)")}", expected "${PI_CODING_AGENT_PACKAGE}"`);
350
+ }
351
+ const entry = resolvePackageSubpath(root, ".");
352
+ if (!entry) throw new Error(`host SDK manifest at ${packageJson} has no resolvable root export`);
353
+ return entry;
354
+ }
355
+
356
+ function isUnknownRecord(value: unknown): value is Record<string, unknown> {
357
+ return typeof value === "object" && value !== null && !Array.isArray(value);
358
+ }
359
+
258
360
  /**
259
361
  * Default factory: detached/background sessions retain the existing shared
260
362
  * runtime; each parent-bound foreground launch gets an isolated runtime.
261
363
  */
262
364
  export function createDefaultChildSessionFactory(options: DefaultChildSessionFactoryOptions = {}): ChildSessionFactory {
263
- const loadPiCodingAgent = options.loadPiCodingAgent ?? (() => import("@earendil-works/pi-coding-agent"));
365
+ const loadPiCodingAgent = options.loadPiCodingAgent ?? loadHostPiCodingAgent;
264
366
  const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 5_000;
367
+ const builtinMcpToolWaitMs = options.builtinMcpToolWaitMs ?? 10_000;
265
368
  let runtime: ReturnType<PiCodingAgentModule["ModelRuntime"]["create"]> | undefined;
266
369
  const live = new Set<ChildSession>();
267
370
  /** Extension shutdowns still running for disposed children; `dispose()` waits for them. */
268
371
  const shutdowns = new Set<Promise<void>>();
372
+ /** Launches still waiting for their MCP tools; `dispose()` ends the wait and waits for their shutdown. */
373
+ const mcpWaits = new Set<Promise<void>>();
374
+ let disposals = 0;
269
375
  const sharedRuntime = async (pi: PiCodingAgentModule) => {
270
376
  runtime ??= pi.ModelRuntime.create().catch((error: unknown) => {
271
377
  runtime = undefined;
@@ -275,29 +381,44 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
275
381
  };
276
382
  return {
277
383
  async create(launch) {
384
+ const disposalsAtStart = disposals;
278
385
  const pi = await loadPiCodingAgent();
386
+ const builtinMcpTools = launch.builtinMcpTools ?? [];
387
+ const builtinMcp = builtinMcpTools.length ? selectedBuiltinMcpExtension(pi, builtinMcpTools) : undefined;
279
388
  const modelRuntime = launch.parentProviderRegistry
280
389
  ? await pi.ModelRuntime.create()
281
390
  : await sharedRuntime(pi);
282
391
  const agentDir = getAgentDir();
283
- const settingsManager = pi.SettingsManager.create(launch.cwd, agentDir);
392
+ const settingsManager = pi.SettingsManager.create(launch.cwd, agentDir, { projectTrusted: launch.projectTrusted });
284
393
  // Foreground children share Pi's global theme with the parent, so reinitializing it
285
394
  // would overwrite the parent's active light/dark appearance. Detached runners have
286
395
  // no initialized theme and must initialize one for headless extension renderers.
287
396
  const themeKey = Symbol.for("@earendil-works/pi-coding-agent:theme");
288
397
  const themeInitialized = Boolean((globalThis as Record<symbol, unknown>)[themeKey]);
289
398
  if (!themeInitialized && typeof pi.initTheme === "function") pi.initTheme(settingsManager.getTheme());
399
+ // SDK sessions do not install Pi's CLI built-ins. Use the host's own
400
+ // codemode factory only when this child can select it; older Pi hosts
401
+ // without that factory retain the strict missing-tool diagnostic.
402
+ const createCodemodeExtension = (pi as PiCodingAgentModule & { createCodemodeExtension?: () => ChildHookExtension["factory"] }).createCodemodeExtension;
403
+ const codemode = typeof createCodemodeExtension === "function" &&
404
+ !launch.runtime.capabilityCeiling?.denyExtensions &&
405
+ (launch.tools === undefined || launch.tools.includes("codemode")) &&
406
+ !launch.excludeTools?.includes("codemode")
407
+ ? [{ name: "codemode", factory: createCodemodeExtension(), replaceable: true }]
408
+ : [];
290
409
  const loader = new pi.DefaultResourceLoader({
291
410
  cwd: launch.cwd,
292
411
  agentDir,
293
412
  settingsManager,
294
413
  noExtensions: !launch.ambientExtensions,
295
414
  noSkills: launch.noSkills,
415
+ // Pi merges skills from extensions' resources_discover without checking noSkills.
416
+ skillsOverride: launch.noSkills ? (base) => ({ ...base, skills: [] }) : undefined,
296
417
  noPromptTemplates: true,
297
418
  noThemes: true,
298
419
  noContextFiles: launch.noContextFiles,
299
- additionalExtensionPaths: launch.extensionPaths,
300
- extensionFactories: launch.hooks,
420
+ additionalExtensionPaths: builtinMcp ? [...launch.extensionPaths, "builtin:mcp"] : launch.extensionPaths,
421
+ extensionFactories: [...launch.hooks, ...codemode, ...(builtinMcp ? [builtinMcp] : [])],
301
422
  extensionsOverride: prioritizeChildPromptRuntime,
302
423
  ...(launch.systemPrompt !== undefined ? { systemPrompt: launch.systemPrompt } : {}),
303
424
  ...(launch.appendSystemPrompt !== undefined ? { appendSystemPrompt: [launch.appendSystemPrompt] } : {}),
@@ -382,11 +503,24 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
382
503
  session.dispose();
383
504
  }
384
505
  };
506
+ // Outside the launch lock: MCP servers connect after `session_start` without reading the per-launch env.
507
+ if (builtinMcpTools.length) {
508
+ const disposed = () => disposals !== disposalsAtStart;
509
+ const ready = missingBuiltinMcpTools(session, builtinMcpTools.map(({ name }) => name), builtinMcpToolWaitMs, disposed).then(async (missing) => {
510
+ if (!missing.length && !disposed()) return;
511
+ await shutdown();
512
+ throw new Error(disposed()
513
+ ? "The child session factory was disposed while the child waited for its MCP tools."
514
+ : `Selected built-in MCP tools did not register in the child session: ${missing.join(", ")}. The MCP server may have failed to connect, or the name belongs to a different tool than the selector names; check it with /mcp.`);
515
+ });
516
+ mcpWaits.add(ready);
517
+ try { await ready; } finally { mcpWaits.delete(ready); }
518
+ }
385
519
  const child: ChildSession = {
386
520
  subscribe: (listener) => session.subscribe((event) => listener(event as unknown as ChildSessionEvent)),
387
521
  prompt: (text) => session.prompt(text),
388
- steer: (text) => session.steer(text),
389
- followUp: (text) => session.followUp(text),
522
+ steer: (text) => session.steer(text).then(() => undefined),
523
+ followUp: (text) => session.followUp(text).then(() => undefined),
390
524
  abort: () => session.abort(),
391
525
  hasQueuedMessages: () => session.agent?.hasQueuedMessages?.() === true,
392
526
  dispose: () => {
@@ -403,18 +537,20 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
403
537
  get sessionFile() { return session.sessionFile; },
404
538
  get sessionId() { return session.sessionId; },
405
539
  get modelId() { return session.model ? `${session.model.provider}/${session.model.id}` : undefined; },
540
+ get contextWindow() { return session.model?.contextWindow; },
406
541
  };
407
542
  live.add(child);
408
543
  return child;
409
544
  },
410
545
  async dispose() {
546
+ disposals += 1;
411
547
  const children = [...live].filter((child) => !child.detached);
412
548
  for (const child of children) child.shutDown = true;
413
549
  await Promise.allSettled(children.map((child) => child.abort()));
414
550
  for (const child of children) {
415
551
  try { void child.dispose(); } catch { /* best effort */ }
416
552
  }
417
- await Promise.allSettled([...shutdowns]);
553
+ await Promise.allSettled([...shutdowns, ...mcpWaits]);
418
554
  if (live.size === 0) runtime = undefined;
419
555
  },
420
556
  };