@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
@@ -20,7 +20,7 @@ import { applyThinkingSuffix, getHostBuiltinToolNames, projectLaunchResolvedChil
20
20
  import { injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
21
21
  import { applyWatchdogLaunchRules, sendRuleViolationWarning } from "../../watchdog/rules.ts";
22
22
  import { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveExistingReadInstructionPaths, resolveExistingReadPaths, writeInitialProgressFile, type ChainStep, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
23
- import type { RunnerStep } from "../shared/parallel-utils.ts";
23
+ import { isDynamicRunnerGroup, isParallelGroup, type RunnerStep } from "../shared/parallel-utils.ts";
24
24
  import type { ContextMode } from "../shared/context-mode.ts";
25
25
  import { PI_CODING_AGENT_PACKAGE, resolveBunPiExecutable, resolveInstalledPiPackageRoot, resolvePiPackageRoot } from "../shared/pi-spawn.ts";
26
26
  import { JITI_ALIAS_ENV, resolveHostPeerAliases } from "./runner-aliases.ts";
@@ -40,7 +40,6 @@ import { ChainOutputValidationError, validateChainOutputBindings } from "../shar
40
40
  import { createStructuredOutputRuntime } from "../shared/structured-output.ts";
41
41
  import { resolveAcceptanceReportMode, resolveEffectiveAcceptance, validateAcceptanceInput, validateExecutionAcceptance } from "../shared/acceptance.ts";
42
42
  import { createRunFanoutBudget, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
43
- import { validateImplementationToolContract } from "../shared/completion-guard.ts";
44
43
  import {
45
44
  type AcceptanceInput,
46
45
  type AgentContract,
@@ -69,7 +68,7 @@ import {
69
68
  resolveChildMaxSubagentDepth,
70
69
  } from "../../shared/types.ts";
71
70
  import { inheritedNestedParentAddressOf, inheritedNestedRouteOf, nestedResultsPath, nestedSummaryFromAsyncStatus, writeNestedEvent } from "../shared/nested-events.ts";
72
- import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
71
+ import { SUBAGENT_PARENT_SESSION_ENV, type ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
73
72
  import { childSessionFactoryModule } from "../shared/child-session.ts";
74
73
  import { inheritedChildRuntime } from "../shared/child-launch.ts";
75
74
  import { resultFilePath } from "./result-files.ts";
@@ -79,13 +78,16 @@ import { usageBudgetState } from "../shared/usage-budget.ts";
79
78
  import type { ImportedAsyncRoot } from "./chain-root-attachment.ts";
80
79
  import type { SessionLeaseRequest } from "../shared/session-lease.ts";
81
80
  import { finalizeProcessTerminal, initializeProcessTerminal, readProcessTerminal } from "./process-terminal.ts";
81
+ import { persistRunnerStartupFailure } from "./runner-startup-failure.ts";
82
82
  import type { ActiveAsyncCapacityHandle } from "./active-async-capacity.ts";
83
83
  import { statusStepDescription } from "./chain-append.ts";
84
+ import { currentPidNamespaceScope } from "./pid-namespace.ts";
84
85
  import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.ts";
85
86
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
86
87
  import { resolveLaunchBinding } from "../../shared/launch-contract.ts";
87
88
  import { resolvePermissionRules, type PermissionConfig } from "../shared/permissions.ts";
88
89
  import { normalizeExtensionBindings, omitExtensionBindingsEnv, omitInheritedProfileEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
90
+ import { omitGitRoutingEnv } from "../shared/git-environment.ts";
89
91
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
90
92
  import { resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
91
93
 
@@ -159,7 +161,7 @@ function resolveJitiCliPath(): string | undefined {
159
161
  const jitiCliPath = resolveJitiCliPath();
160
162
  const asyncRunnerSourcePath = path.join(
161
163
  path.dirname(fileURLToPath(import.meta.url)),
162
- `subagent-runner${path.extname(fileURLToPath(import.meta.url))}`,
164
+ `subagent-runner-bootstrap${path.extname(fileURLToPath(import.meta.url))}`,
163
165
  );
164
166
  const sourceUnderNodeModules = asyncRunnerSourcePath.split(path.sep).some((segment) => segment.toLowerCase() === "node_modules");
165
167
  function supportsNativeRunner(nodeExecutable: string): boolean {
@@ -179,6 +181,7 @@ interface AsyncExecutionContext {
179
181
  permissions?: PermissionConfig;
180
182
  currentModelProvider?: string;
181
183
  currentModel?: ParentModel;
184
+ scopedModelIds?: string[];
182
185
  /** Optional model-scope enforcement resolved from subagent settings. */
183
186
  modelScope?: ModelScopeConfig;
184
187
  /** Parent-authoritative trust state for profile-aware project config merging. */
@@ -563,6 +566,7 @@ async function terminateRunnerBeforeProceedAsync(proc: ChildProcess, processClos
563
566
  async function completeRunnerStartupHandshake(
564
567
  startupPath: string,
565
568
  startupAckPath: string,
569
+ startupConfirmPath: string,
566
570
  startupProceedPath: string,
567
571
  proc: ChildProcess,
568
572
  processClosed: Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>,
@@ -589,7 +593,7 @@ async function completeRunnerStartupHandshake(
589
593
  const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
590
594
  return { pid: proc.pid, runnerProcessInstanceId, error: acknowledged.error, terminationObserved, startupDidNotProceed: true };
591
595
  }
592
- try { writeRunnerStartupControl(startupAckPath, { action: "confirm", token: ready.token }); } catch (error) {
596
+ try { writeRunnerStartupControl(startupConfirmPath, { action: "confirm", token: ready.token }); } catch (error) {
593
597
  const message = `Failed to confirm async runner startup: ${error instanceof Error ? error.message : String(error)}`;
594
598
  persistStartupFailure(message);
595
599
  const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
@@ -626,37 +630,8 @@ async function completeRunnerStartupHandshake(
626
630
  }
627
631
 
628
632
  function persistPreProceedStartupFailure(asyncDir: string, runId: string, runnerProcessInstanceId: string, sessionId: string | undefined, completionOwnerId: string | undefined, message: string): void {
629
- const now = Date.now();
630
633
  try {
631
- const statusPath = path.join(asyncDir, "status.json");
632
- let status: Partial<AsyncStatus> = {};
633
- try {
634
- status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as Partial<AsyncStatus>;
635
- } catch {}
636
- const existingProcessTerminal = status.processTerminal?.state === "observed" || status.processTerminal?.state === "unknown"
637
- ? status.processTerminal : undefined;
638
- writePrivateAtomicJson(statusPath, {
639
- ...status,
640
- runId,
641
- ...(sessionId ? { sessionId } : {}),
642
- ...(completionOwnerId ? { completionOwnerId } : {}),
643
- state: "failed",
644
- lastUpdate: now,
645
- error: message,
646
- processTerminal: existingProcessTerminal ?? {
647
- version: 1,
648
- state: "not-started",
649
- runId,
650
- runnerProcessInstanceId,
651
- },
652
- });
653
- writePrivateAtomicJson(path.join(asyncDir, "process-terminal-candidate.json"), {
654
- version: 1,
655
- runId,
656
- runnerProcessInstanceId,
657
- writers: {},
658
- expectedWriters: { 0: 0 },
659
- });
634
+ persistRunnerStartupFailure({ asyncDir, runId, runnerProcessInstanceId, sessionId, completionOwnerId, message });
660
635
  } catch {
661
636
  // Startup failures must still return the original launch error.
662
637
  }
@@ -683,19 +658,23 @@ export function emitProcessTerminalEvent(ctx: AsyncExecutionContext, proof: unkn
683
658
  }
684
659
  }
685
660
 
686
- function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Omit<AsyncStatus, "pid" | "processTerminal">, initialStatusPath: string, onProcessTerminal?: (proof: unknown) => void, onBeforeProceed?: (runnerProcessInstanceId: string) => void, requestedCwd = cwd): SpawnRunnerResult | Promise<SpawnRunnerResult> {
661
+ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Omit<AsyncStatus, "pid" | "processTerminal">, initialStatusPath: string, launchParentSessionId: string | undefined, onProcessTerminal?: (proof: unknown) => void, onBeforeProceed?: (runnerProcessInstanceId: string) => void, requestedCwd = cwd): SpawnRunnerResult | Promise<SpawnRunnerResult> {
687
662
  const cwdError = preflightLaunchCwd(requestedCwd, cwd);
688
663
  if (cwdError) return { error: cwdError };
664
+ if (launchParentSessionId !== undefined && (!launchParentSessionId || launchParentSessionId.trim() !== launchParentSessionId)) {
665
+ return { error: "Background runner parent session identity is invalid." };
666
+ }
667
+ const steps = (cfg as { steps?: unknown }).steps;
668
+ if (!Array.isArray(steps)) return { error: "Background runner launch is missing its steps." };
669
+ const inconsistentParent = (steps as RunnerStep[]).some((step) => isParallelGroup(step)
670
+ ? step.parallel.some((child) => child.parentSessionId !== launchParentSessionId)
671
+ : (isDynamicRunnerGroup(step) ? step.parallel.parentSessionId : step.parentSessionId) !== launchParentSessionId);
672
+ if (inconsistentParent) return { error: "Background runner steps have inconsistent parent session identities." };
689
673
 
690
674
  // The compiled host exposes its SDK only through Pi's extension loader.
691
675
  const binaryHost = resolveBunPiExecutable();
692
676
  const nodeExecutable = resolveNodeExecutable();
693
- const configuredExtensions = (cfg as { steps?: Array<{ extensions?: unknown[]; subagentOnlyExtensions?: unknown[]; requiredExtensions?: unknown[] }> }).steps?.some(
694
- (step) => (step.extensions?.length ?? 0) > 0 || (step.subagentOnlyExtensions?.length ?? 0) > 0 || (step.requiredExtensions?.length ?? 0) > 0,
695
- ) ?? false;
696
- // Keep provider/tool extensions in Jiti's host-alias boundary; the native preload
697
- // only certifies the runner's imports, not a separately loaded extension graph.
698
- const nativeRunnerSupported = supportsNativeRunner(nodeExecutable) && !configuredExtensions;
677
+ const nativeRunnerSupported = supportsNativeRunner(nodeExecutable);
699
678
  const runner = asyncRunnerSourcePath;
700
679
  const runnerIsJavaScript = path.extname(runner) === ".js";
701
680
  const bootstrap = path.join(path.dirname(runner), `binary-bootstrap${path.extname(fileURLToPath(import.meta.url))}`);
@@ -730,11 +709,13 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
730
709
  ? path.join(launchAsyncDir, "runner-startup.json")
731
710
  : undefined;
732
711
  const startupAckPath = startupPath ? path.join(path.dirname(startupPath), "runner-startup-ack.json") : undefined;
712
+ const startupConfirmPath = startupPath ? path.join(path.dirname(startupPath), "runner-startup-confirm.json") : undefined;
733
713
  const startupProceedPath = launchAsyncDir && (startupPath || launchBarrierToken)
734
714
  ? path.join(launchAsyncDir, "runner-startup-proceed.json")
735
715
  : undefined;
736
716
  if (startupPath) fs.rmSync(startupPath, { force: true });
737
717
  if (startupAckPath) fs.rmSync(startupAckPath, { force: true });
718
+ if (startupConfirmPath) fs.rmSync(startupConfirmPath, { force: true });
738
719
  if (startupProceedPath) fs.rmSync(startupProceedPath, { force: true });
739
720
 
740
721
  const logPaths = resolveAsyncRunnerLogPaths(launchConfig);
@@ -746,6 +727,7 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
746
727
  stdoutFd = fs.openSync(logPaths.stdoutPath, "a");
747
728
  stderrFd = fs.openSync(logPaths.stderrPath, "a");
748
729
  }
730
+ // Short-circuit native peer aliases so Pi's loader and generated factories preserve filesystem resolution semantics.
749
731
  const preload = Object.keys(hostPeerAliases.aliases).length > 0
750
732
  ? ["--import", new URL("../../../runner-peer-preload.mjs", import.meta.url).href]
751
733
  : [];
@@ -756,22 +738,24 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
756
738
  : nativeRunnerSupported
757
739
  ? [...preload, "--experimental-strip-types", runner, cfgPath]
758
740
  : [...preload, jitiCliPath!, runner, cfgPath];
741
+ const runnerEnv: NodeJS.ProcessEnv = {
742
+ // Fork: profile env inherited from the parent must not leak into children.
743
+ ...omitGitRoutingEnv(omitInheritedProfileEnv(omitExtensionBindingsEnv(process.env))),
744
+ ...childCacheRetentionEnv(),
745
+ [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: binaryHost ? undefined : piPackageRoot,
746
+ // npm must override inherited bundled layouts (#2071); binaries retain release assets.
747
+ PI_PACKAGE_DIR: binaryHost ? process.env.PI_PACKAGE_DIR : piPackageRoot,
748
+ [JITI_ALIAS_ENV]: binaryHost ? undefined : JSON.stringify(hostPeerAliases.aliases),
749
+ PI_ASYNC_NATIVE_RUNNER: !binaryHost && (runnerIsJavaScript || nativeRunnerSupported) ? "1" : "0",
750
+ PI_SUBAGENT_RUNNER_CONFIG: binaryHost ? cfgPath : undefined,
751
+ };
752
+ if (launchParentSessionId === undefined) delete runnerEnv[SUBAGENT_PARENT_SESSION_ENV];
753
+ else runnerEnv[SUBAGENT_PARENT_SESSION_ENV] = launchParentSessionId;
759
754
  const proc = spawn(command, args, {
760
755
  cwd,
761
756
  ...backgroundProcessOptions(),
762
757
  stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
763
- env: {
764
- ...omitInheritedProfileEnv(omitExtensionBindingsEnv(process.env)),
765
- // Unset leaves the inherited parent value in place. See childCacheRetention.
766
- ...childCacheRetentionEnv(),
767
- [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: binaryHost ? undefined : piPackageRoot,
768
- // npm must override inherited bundled layouts (#2071); binaries retain release assets.
769
- PI_PACKAGE_DIR: binaryHost ? process.env.PI_PACKAGE_DIR : piPackageRoot,
770
- [JITI_ALIAS_ENV]: binaryHost ? undefined : JSON.stringify(hostPeerAliases.aliases),
771
- PI_ASYNC_NATIVE_RUNNER: !binaryHost && (runnerIsJavaScript || nativeRunnerSupported) ? "1" : "0",
772
- PI_ASYNC_COMPILED_RUNNER: !binaryHost && runnerIsJavaScript ? "1" : "0",
773
- PI_SUBAGENT_RUNNER_CONFIG: binaryHost ? cfgPath : undefined,
774
- },
758
+ env: runnerEnv,
775
759
  });
776
760
  let observedProcessExit: { exitCode: number | null; signal: NodeJS.Signals | null } | undefined;
777
761
  proc.once("exit", (exitCode, signal) => { observedProcessExit = { exitCode, signal }; });
@@ -847,6 +831,7 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
847
831
  writePrivateAtomicJson(initialStatusPath, {
848
832
  ...initialStatus,
849
833
  pid: proc.pid,
834
+ pidNamespaceScope: currentPidNamespaceScope(),
850
835
  processTerminal: { version: 1, state: "pending", runId: initialStatus.runId, runnerProcessInstanceId },
851
836
  });
852
837
  // Aggregate waits must see the launch before the runner's first status update.
@@ -885,11 +870,11 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
885
870
  }
886
871
  }
887
872
  proc.unref();
888
- if (startupPath && startupAckPath && startupProceedPath) {
873
+ if (startupPath && startupAckPath && startupConfirmPath && startupProceedPath) {
889
874
  const persistStartupFailure = (message: string) => {
890
875
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
891
876
  };
892
- return completeRunnerStartupHandshake(startupPath, startupAckPath, startupProceedPath, proc, processClosed, () => observedProcessExit ?? (proc.exitCode !== null || proc.signalCode !== null ? { exitCode: proc.exitCode, signal: proc.signalCode } : undefined), runnerProcessInstanceId, persistStartupFailure);
877
+ return completeRunnerStartupHandshake(startupPath, startupAckPath, startupConfirmPath, startupProceedPath, proc, processClosed, () => observedProcessExit ?? (proc.exitCode !== null || proc.signalCode !== null ? { exitCode: proc.exitCode, signal: proc.signalCode } : undefined), runnerProcessInstanceId, persistStartupFailure);
893
878
  }
894
879
  return { pid: proc.pid, runnerProcessInstanceId };
895
880
  } catch (error) {
@@ -938,6 +923,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
938
923
  worktreeProvider,
939
924
  asyncDir,
940
925
  } = params;
926
+ const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
941
927
  const outputBaseDir = params.outputBaseDir;
942
928
  const resultMode = params.resultMode ?? "chain";
943
929
  const chainSkills = params.chainSkills ?? [];
@@ -1096,7 +1082,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1096
1082
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
1097
1083
  const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
1098
1084
 
1099
- const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel);
1085
+ const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
1100
1086
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
1101
1087
  const primaryModelFromParent = modelOrigin === "inherited";
1102
1088
  const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(
@@ -1144,8 +1130,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1144
1130
  const launchRuleError = applyWatchdogLaunchRules({ cwd: machine ? runnerCwd : stepCwd, agent: a.name, model: selectedModel, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
1145
1131
  if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
1146
1132
  const fast = s.fast ?? params.fast ?? a.fast;
1147
- const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1148
1133
  const requiredExtensions = externalRunner ? [] : ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1134
+ const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1149
1135
  const toolPlan = resolvePiLaunchToolPlan({
1150
1136
  tools: a.tools,
1151
1137
  excludeTools: a.excludeTools,
@@ -1171,22 +1157,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1171
1157
  if (externalRunner && permissionRules) {
1172
1158
  throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='${externalRunnerType}', which cannot enforce native Pi child permission rules.`);
1173
1159
  }
1174
- if (!externalRunner) {
1175
- const contractTools = toolPlan.explicitToolAllowlist ? toolPlan.effectiveToolAllowlist : undefined;
1176
- const contractError = validateImplementationToolContract({
1177
- agent: a.name,
1178
- task,
1179
- tools: contractTools,
1180
- mcpDirectTools: toolPlan.effectiveMcpTools,
1181
- configuredExtensions: toolPlan.configuredExtensions,
1182
- requestedTools: toolPlan.requestedBuiltinTools,
1183
- acceptanceRole: a.acceptanceRole,
1184
- completionGuard: a.completionGuard,
1185
- });
1186
- if (contractError) throw new AsyncStartValidationError(contractError);
1187
- }
1188
1160
  return {
1189
- parentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,
1161
+ parentSessionId: launchParentSessionId,
1190
1162
  permissionRules,
1191
1163
  ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
1192
1164
  ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
@@ -1218,12 +1190,13 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1218
1190
  tools: a.tools,
1219
1191
  excludeTools: a.excludeTools,
1220
1192
  allowNestedSubagents: a.allowNestedSubagents,
1193
+ allowedAgents: a.allowedAgents,
1221
1194
  extensions: a.extensions,
1222
1195
  subagentOnlyExtensions: a.subagentOnlyExtensions,
1223
1196
  ...(!externalRunner ? { requiredExtensions } : {}),
1224
1197
  mcpDirectTools: a.mcpDirectTools,
1198
+ ...(toolPlan.builtinMcpTools ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
1225
1199
  mutationTools: a.mutationTools,
1226
- completionGuard: a.completionGuard,
1227
1200
  ...(a.sandbox ? { sandbox: a.sandbox } : {}),
1228
1201
  systemPrompt,
1229
1202
  systemPromptMode: a.systemPromptMode,
@@ -1359,6 +1332,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1359
1332
  });
1360
1333
  const steps = params.attachRoot
1361
1334
  ? [{
1335
+ parentSessionId: launchParentSessionId,
1362
1336
  agent: params.attachRoot.agent,
1363
1337
  task: "",
1364
1338
  label: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,
@@ -1529,6 +1503,7 @@ export function executeAsyncChain(
1529
1503
  }
1530
1504
  const initialStatusAt = Date.now();
1531
1505
  const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
1506
+ const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
1532
1507
 
1533
1508
  let spawnResult: SpawnRunnerResult = {};
1534
1509
  try {
@@ -1551,6 +1526,7 @@ export function executeAsyncChain(
1551
1526
  piPackageRoot,
1552
1527
  childSessionFactoryModule: childSessionFactoryModule(),
1553
1528
  inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
1529
+ projectTrusted: ctx.projectTrusted,
1554
1530
  worktreeSetupHook,
1555
1531
  worktreeSetupHookTimeoutMs,
1556
1532
  worktreeBaseDir,
@@ -1568,7 +1544,6 @@ export function executeAsyncChain(
1568
1544
  deadlineAt,
1569
1545
  globalConcurrencyLimit: params.globalConcurrencyLimit,
1570
1546
  runFanoutBudget,
1571
- hostAvailableBuiltins: getHostBuiltinToolNames(ctx.pi),
1572
1547
  workflowGraph,
1573
1548
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1574
1549
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
@@ -1597,6 +1572,7 @@ export function executeAsyncChain(
1597
1572
  steps: initialStatusSteps,
1598
1573
  },
1599
1574
  path.join(asyncDir, "status.json"),
1575
+ launchParentSessionId,
1600
1576
  (proof) => emitProcessTerminalEvent(ctx, proof),
1601
1577
  (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId),
1602
1578
  ) as SpawnRunnerResult;
@@ -1890,7 +1866,7 @@ export function executeAsyncSingle(
1890
1866
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
1891
1867
  : "";
1892
1868
  const taskText = readsInstruction + taskWithOutputInstruction;
1893
- const modelScopes = resolveModelScopesForAgent(ctx.modelScope, agentConfig.name, ctx.currentModel);
1869
+ const modelScopes = resolveModelScopesForAgent(ctx.modelScope, agentConfig.name, ctx.currentModel, ctx.scopedModelIds);
1894
1870
  const modelOrigin = resolveModelOrigin({
1895
1871
  fromParent: params.modelOverrideFromParent,
1896
1872
  storedOrigin: params.modelOrigin,
@@ -1964,8 +1940,8 @@ export function executeAsyncSingle(
1964
1940
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1965
1941
  }
1966
1942
  }
1967
- const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1968
1943
  const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1944
+ const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1969
1945
  const toolPlan = resolvePiLaunchToolPlan({
1970
1946
  tools: agentConfig.tools,
1971
1947
  excludeTools: agentConfig.excludeTools,
@@ -1988,20 +1964,6 @@ export function executeAsyncSingle(
1988
1964
  hostAvailableBuiltins,
1989
1965
  });
1990
1966
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
1991
- if (!externalRunner) {
1992
- const contractTools = toolPlan.explicitToolAllowlist ? toolPlan.effectiveToolAllowlist : undefined;
1993
- const contractError = validateImplementationToolContract({
1994
- agent: agentConfig.name,
1995
- task: taskText,
1996
- tools: contractTools,
1997
- mcpDirectTools: toolPlan.effectiveMcpTools,
1998
- configuredExtensions: toolPlan.configuredExtensions,
1999
- requestedTools: toolPlan.requestedBuiltinTools,
2000
- acceptanceRole: agentConfig.acceptanceRole,
2001
- completionGuard: agentConfig.completionGuard,
2002
- });
2003
- if (contractError) return formatAsyncStartError("single", contractError);
2004
- }
2005
1967
  const fast = params.fast ?? agentConfig.fast;
2006
1968
  const launchThinking = resolveEffectiveThinking(selectedModel, effectiveThinking);
2007
1969
  const { definitionDigest, launchContractDigest } = resolveLaunchBinding({
@@ -2058,6 +2020,7 @@ export function executeAsyncSingle(
2058
2020
  ...(recoveryAgentConfig.tools ? { tools: [...recoveryAgentConfig.tools] } : {}),
2059
2021
  ...(recoveryAgentConfig.excludeTools ? { excludeTools: [...recoveryAgentConfig.excludeTools] } : {}),
2060
2022
  ...(recoveryAgentConfig.allowNestedSubagents !== undefined ? { allowNestedSubagents: recoveryAgentConfig.allowNestedSubagents } : {}),
2023
+ ...(recoveryAgentConfig.allowedAgents !== undefined ? { allowedAgents: [...recoveryAgentConfig.allowedAgents] } : {}),
2061
2024
  ...(recoveryAgentConfig.extensions ? { extensions: [...recoveryAgentConfig.extensions] } : {}),
2062
2025
  ...(recoveryAgentConfig.subagentOnlyExtensions ? { subagentOnlyExtensions: [...recoveryAgentConfig.subagentOnlyExtensions] } : {}),
2063
2026
  ...(recoveryAgentConfig.mcpDirectTools ? { mcpDirectTools: [...recoveryAgentConfig.mcpDirectTools] } : {}),
@@ -2070,7 +2033,6 @@ export function executeAsyncSingle(
2070
2033
  ...(resolvedSkills.length ? { skills: resolvedSkills.map((skill) => skill.name) } : {}),
2071
2034
  ...(recoveryAgentConfig.skillPath ? { skillPath: [...recoveryAgentConfig.skillPath] } : {}),
2072
2035
  ...(recoveryAgentConfig.filePath ? { agentFilePath: recoveryAgentConfig.filePath } : {}),
2073
- ...(recoveryAgentConfig.completionGuard !== undefined ? { completionGuard: recoveryAgentConfig.completionGuard } : {}),
2074
2036
  ...(recoveryAgentConfig.memory ? { memory: { ...recoveryAgentConfig.memory } } : {}),
2075
2037
  ...(outputPath ? { outputPath } : {}),
2076
2038
  outputMode,
@@ -2100,13 +2062,14 @@ export function executeAsyncSingle(
2100
2062
  let spawnResultOrPromise: SpawnRunnerResult | Promise<SpawnRunnerResult> = {};
2101
2063
  const initialStatusAt = Date.now();
2102
2064
  const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
2065
+ const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
2103
2066
  try {
2104
2067
  spawnResultOrPromise = spawnRunner(
2105
2068
  {
2106
2069
  id,
2107
2070
  steps: [
2108
2071
  {
2109
- parentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,
2072
+ parentSessionId: launchParentSessionId,
2110
2073
  permissionRules,
2111
2074
  ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
2112
2075
  ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
@@ -2133,12 +2096,13 @@ export function executeAsyncSingle(
2133
2096
  tools: agentConfig.tools,
2134
2097
  excludeTools: agentConfig.excludeTools,
2135
2098
  allowNestedSubagents: agentConfig.allowNestedSubagents,
2099
+ allowedAgents: agentConfig.allowedAgents,
2136
2100
  extensions: agentConfig.extensions,
2137
2101
  subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
2138
2102
  ...(!externalRunner ? { requiredExtensions } : {}),
2139
2103
  mcpDirectTools: agentConfig.mcpDirectTools,
2104
+ ...(toolPlan.builtinMcpTools ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
2140
2105
  mutationTools: agentConfig.mutationTools,
2141
- completionGuard: agentConfig.completionGuard,
2142
2106
  ...(sandbox ? { sandbox } : {}),
2143
2107
  systemPrompt,
2144
2108
  systemPromptMode: agentConfig.systemPromptMode,
@@ -2184,6 +2148,7 @@ export function executeAsyncSingle(
2184
2148
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
2185
2149
  piPackageRoot,
2186
2150
  childSessionFactoryModule: childSessionFactoryModule(),
2151
+ projectTrusted: ctx.projectTrusted,
2187
2152
  inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
2188
2153
  worktreeSetupHook,
2189
2154
  worktreeSetupHookTimeoutMs,
@@ -2204,7 +2169,6 @@ export function executeAsyncSingle(
2204
2169
  launchContractDigest,
2205
2170
  launchResolvedExtensions,
2206
2171
  runFanoutBudget,
2207
- hostAvailableBuiltins,
2208
2172
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
2209
2173
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
2210
2174
  ...(lane ? { lane } : {}),
@@ -2234,6 +2198,7 @@ export function executeAsyncSingle(
2234
2198
  steps: [{ agent, status: "pending", ...(lane ? { lane } : {}), ...(model ? { model } : {}), ...(contextLimit !== undefined ? { contextLimit } : {}) }],
2235
2199
  },
2236
2200
  path.join(asyncDir, "status.json"),
2201
+ launchParentSessionId,
2237
2202
  (proof) => emitProcessTerminalEvent(ctx, proof),
2238
2203
  (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId),
2239
2204
  params.requestedCwd ?? runnerCwd,