@xzzpig/pi-subagents 0.14.0 → 0.15.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 (198) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +6 -5
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +56 -15
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -19
  9. package/docs/missions.md +10 -2
  10. package/docs/models.md +11 -22
  11. package/docs/observability.md +63 -11
  12. package/docs/standalone-background.md +59 -0
  13. package/docs/tool-reference.md +42 -23
  14. package/docs/watchdog.md +39 -10
  15. package/docs/workflows.md +58 -19
  16. package/index.ts +5 -2
  17. package/inspector-runner.mjs +2 -2
  18. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  20. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  21. package/package.json +9 -4
  22. package/prompts/parallel-review.md +1 -1
  23. package/runner-peer-loader.mjs +24 -0
  24. package/runner-peer-preload.mjs +36 -0
  25. package/skills/pi-subagents/SKILL.md +34 -22
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  27. package/skills/pi-subagents/references/execution-controls.md +27 -8
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  31. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  32. package/src/agents/advertised-agent-prompt.ts +94 -0
  33. package/src/agents/agent-management.ts +71 -59
  34. package/src/agents/agent-serializer.ts +6 -3
  35. package/src/agents/agents.ts +198 -72
  36. package/src/agents/builtin-names.ts +1 -0
  37. package/src/agents/chain-serializer.ts +5 -0
  38. package/src/agents/runtime-agent-registry.ts +7 -6
  39. package/src/api/delegation.ts +4 -0
  40. package/src/api/preflight.ts +110 -71
  41. package/src/api/required-child-extensions.ts +6 -0
  42. package/src/api/shared-types.ts +3 -1
  43. package/src/api/workflow-resources.ts +6 -0
  44. package/src/extension/config.ts +14 -37
  45. package/src/extension/fanout-child.ts +68 -5
  46. package/src/extension/herdr-pi-bridge.ts +164 -0
  47. package/src/extension/index.ts +141 -51
  48. package/src/extension/public-execution.ts +7 -6
  49. package/src/extension/rpc.ts +8 -21
  50. package/src/extension/schemas.ts +86 -84
  51. package/src/extension/tool-description.ts +32 -79
  52. package/src/inspectors/actions.ts +148 -0
  53. package/src/inspectors/ghostty/actions.ts +74 -0
  54. package/src/inspectors/ghostty/plugin.ts +17 -0
  55. package/src/inspectors/herdr/actions.ts +99 -179
  56. package/src/inspectors/herdr/plugin.ts +20 -0
  57. package/src/inspectors/herdr/project-panes.ts +4 -1
  58. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  59. package/src/inspectors/plugins.ts +8 -0
  60. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  61. package/src/inspectors/types.ts +51 -0
  62. package/src/integrations/pi-web-session-liveness.ts +73 -0
  63. package/src/intercom/intercom-bridge.ts +50 -8
  64. package/src/intercom/native-supervisor-channel.ts +142 -115
  65. package/src/intercom/supervisor-ui.ts +3 -2
  66. package/src/missions/workflow-state.ts +37 -16
  67. package/src/policy/authority.ts +4 -0
  68. package/src/profiles/profiles.ts +12 -6
  69. package/src/runs/background/active-async-capacity.ts +22 -18
  70. package/src/runs/background/active-run-index.ts +17 -1
  71. package/src/runs/background/async-execution.ts +359 -176
  72. package/src/runs/background/async-job-tracker.ts +41 -7
  73. package/src/runs/background/async-resume.ts +19 -12
  74. package/src/runs/background/async-retention.ts +20 -0
  75. package/src/runs/background/async-status-snapshot.ts +10 -12
  76. package/src/runs/background/async-status.ts +32 -13
  77. package/src/runs/background/auto-drain.ts +59 -35
  78. package/src/runs/background/binary-bootstrap.ts +38 -0
  79. package/src/runs/background/chain-append.ts +1 -1
  80. package/src/runs/background/chain-root-attachment.ts +22 -33
  81. package/src/runs/background/control-channel.ts +78 -44
  82. package/src/runs/background/fleet-view.ts +30 -2
  83. package/src/runs/background/notify.ts +193 -19
  84. package/src/runs/background/owned-process-tree.ts +35 -8
  85. package/src/runs/background/process-terminal.ts +23 -23
  86. package/src/runs/background/result-files.ts +8 -4
  87. package/src/runs/background/result-watcher.ts +19 -2
  88. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  89. package/src/runs/background/run-child-session.ts +118 -41
  90. package/src/runs/background/run-status.ts +78 -5
  91. package/src/runs/background/runner-aliases.ts +22 -5
  92. package/src/runs/background/runner-child-launch.ts +93 -0
  93. package/src/runs/background/runner-child-sessions.ts +5 -4
  94. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  95. package/src/runs/background/scheduled-runs.ts +51 -18
  96. package/src/runs/background/stale-run-reconciler.ts +38 -12
  97. package/src/runs/background/steering.ts +20 -2
  98. package/src/runs/background/subagent-runner.ts +766 -432
  99. package/src/runs/background/subagent-wait.ts +179 -28
  100. package/src/runs/background/wait-completions.ts +79 -27
  101. package/src/runs/background/wait-subscriptions.ts +9 -3
  102. package/src/runs/background/wait-tool.ts +5 -3
  103. package/src/runs/foreground/async-steering-action.ts +37 -7
  104. package/src/runs/foreground/async-stop-action.ts +93 -3
  105. package/src/runs/foreground/execution.ts +174 -194
  106. package/src/runs/foreground/foreground-history.ts +5 -2
  107. package/src/runs/foreground/prompt-audit.ts +12 -6
  108. package/src/runs/foreground/subagent-executor.ts +896 -397
  109. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  110. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  111. package/src/runs/shared/acceptance.ts +54 -14
  112. package/src/runs/shared/agent-contract.ts +1 -1
  113. package/src/runs/shared/async-status-projection.ts +172 -78
  114. package/src/runs/shared/capability-ceiling.ts +2 -0
  115. package/src/runs/shared/child-hooks.ts +167 -3
  116. package/src/runs/shared/child-launch-plan.ts +15 -3
  117. package/src/runs/shared/child-launch.ts +44 -16
  118. package/src/runs/shared/child-lifecycle.ts +6 -3
  119. package/src/runs/shared/child-runtime-config.ts +8 -1
  120. package/src/runs/shared/child-session.ts +130 -24
  121. package/src/runs/shared/child-tool-plan.ts +145 -14
  122. package/src/runs/shared/completion-evidence.ts +2 -2
  123. package/src/runs/shared/completion-guard.ts +6 -3
  124. package/src/runs/shared/dynamic-fanout.ts +2 -2
  125. package/src/runs/shared/effective-system-prompt.ts +33 -0
  126. package/src/runs/shared/external-cli-contract.ts +11 -1
  127. package/src/runs/shared/external-cli-preflight.ts +6 -2
  128. package/src/runs/shared/external-cli-runner.ts +9 -7
  129. package/src/runs/shared/herdr-connection.ts +134 -0
  130. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  131. package/src/runs/shared/herdr-machine.ts +279 -0
  132. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  133. package/src/runs/shared/herdr-placed-run.ts +263 -0
  134. package/src/runs/shared/host-step-status.ts +11 -11
  135. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  136. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  137. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  138. package/src/runs/shared/model-scope.ts +1 -1
  139. package/src/runs/shared/nested-events.ts +19 -10
  140. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  141. package/src/runs/shared/parallel-handoff.ts +57 -12
  142. package/src/runs/shared/parallel-utils.ts +10 -4
  143. package/src/runs/shared/pi-spawn.ts +10 -0
  144. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  145. package/src/runs/shared/run-fanout-budget.ts +8 -8
  146. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  147. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  148. package/src/runs/shared/task-intent.ts +46 -13
  149. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  150. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  151. package/src/runs/shared/worktree-setup-command.ts +213 -0
  152. package/src/runs/shared/worktree.ts +437 -214
  153. package/src/shared/child-cache-retention.ts +43 -0
  154. package/src/shared/fork-context.ts +15 -72
  155. package/src/shared/launch-contract.ts +70 -8
  156. package/src/shared/model-response-aliases.ts +13 -0
  157. package/src/shared/opencode-session-headers.ts +30 -0
  158. package/src/shared/pruned-fork.ts +1 -1
  159. package/src/shared/required-child-extensions.ts +81 -0
  160. package/src/shared/settings.ts +5 -2
  161. package/src/shared/shortcuts.ts +0 -4
  162. package/src/shared/types.ts +163 -90
  163. package/src/shared/utils.ts +10 -2
  164. package/src/shared/watch-strategy.ts +2 -0
  165. package/src/shared/workflow-child-permit.ts +18 -13
  166. package/src/slash/delegation-adapters.ts +3 -1
  167. package/src/slash/delegation-request.ts +14 -0
  168. package/src/slash/slash-commands.ts +2 -7
  169. package/src/slash/subagents-admin.ts +31 -14
  170. package/src/tui/fleet-status.ts +165 -20
  171. package/src/tui/fleet.ts +30 -19
  172. package/src/tui/render.ts +210 -50
  173. package/src/watchdog/child-status.ts +28 -28
  174. package/src/watchdog/lsp-diagnostics.ts +1 -1
  175. package/src/watchdog/model-selection.ts +21 -1
  176. package/src/watchdog/permission-arbiter.ts +5 -2
  177. package/src/watchdog/register-child.ts +10 -2
  178. package/src/watchdog/register-main.ts +39 -35
  179. package/src/watchdog/render.ts +1 -1
  180. package/src/watchdog/review.ts +122 -74
  181. package/src/watchdog/rules.ts +1 -1
  182. package/src/watchdog/runtime.ts +100 -27
  183. package/src/watchdog/scope.ts +1 -1
  184. package/src/watchdog/settings.ts +3 -0
  185. package/src/watchdog/tool-actions.ts +13 -12
  186. package/src/watchdog/turn-delta.ts +23 -0
  187. package/src/watchdog/types.ts +5 -3
  188. package/src/watchdog/warning-format.ts +1 -1
  189. package/src/workflows/chat-progress.ts +3 -3
  190. package/src/workflows/scripted-workflow.ts +349 -26
  191. package/src/workflows/workflow-checklist.ts +17 -20
  192. package/src/workflows/workflow-child-summary.ts +57 -8
  193. package/src/workflows/workflow-preflight.ts +19 -19
  194. package/src/workflows/workflow-receipt.ts +24 -6
  195. package/src/workflows/workflow-resources.ts +108 -22
  196. package/src/workflows/workflow-settlement.ts +3 -0
  197. package/src/runs/shared/model-exclusions.ts +0 -373
  198. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -1,8 +1,15 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import registerFanoutChildSubagentExtension from "../../extension/fanout-child.ts";
2
+ import { listBackgroundWorkProviders } from "../../api/background-work.ts";
3
+ import { ReadonlyDrainObservation } from "./readonly-drain-observation.ts";
4
+ import registerFanoutChildSubagentExtension, { createChildSafeState } from "../../extension/fanout-child.ts";
3
5
  import registerSubagentFastModeExtension from "./fast-mode-extension.ts";
4
6
  import registerSubagentPromptRuntime from "./subagent-prompt-runtime.ts";
5
7
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
8
+ import type { ChildToolDiagnostic } from "./tool-availability.ts";
9
+ import type { ChildSessionLaunch } from "./child-session.ts";
10
+ import type { ArbiterModelContext } from "./llm-intent-arbiter.ts";
11
+ import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
12
+ import { projectRuntimeAcknowledgedExtensions } from "./runtime-acknowledged-extensions.ts";
6
13
 
7
14
  /** Inline extension shape accepted by pi's resource loader (`extensionFactories`). */
8
15
  export interface ChildHookExtension {
@@ -10,16 +17,173 @@ export interface ChildHookExtension {
10
17
  factory: (pi: ExtensionAPI) => void;
11
18
  }
12
19
 
20
+ type OwnedCapture = Required<Pick<ChildRuntimeConfig, "toolDiagnostic" | "runtimeAcknowledgements">>;
21
+ type PromptProof = { config: ChildRuntimeConfig; snapshot: string; factories?: ChildHookExtension["factory"][]; observeNext?: ReadonlyDrainObservation; observation?: ReadonlyDrainObservation; capture?: OwnedCapture; reporting?: { launch: ChildSessionLaunch; callback: ChildSessionLaunch["onExtensionError"] } };
22
+ const promptProofs = new WeakMap<ChildHookExtension["factory"], PromptProof>();
23
+
24
+ function ownedProof(hooks: ChildHookExtension[]): PromptProof | undefined {
25
+ const proof = hooks[0] && promptProofs.get(hooks[0].factory);
26
+ return proof?.factories?.length === hooks.length && proof.factories.every((factory, index) => hooks[index]?.factory === factory) ? proof : undefined;
27
+ }
28
+
29
+ /** The host's mandatory transcript reporting, owned by the existing hook certificate. */
30
+ export function withChildSessionErrorReporting(session: Omit<ChildSessionLaunch, "onExtensionError">, transcriptWriter: ChildTranscriptWriter | undefined): ChildSessionLaunch {
31
+ const launch: ChildSessionLaunch = { ...session, onExtensionError: (error) => {
32
+ transcriptWriter?.writeStderrLine(`Extension error (${error.extensionPath}, ${error.event}): ${error.error instanceof Error ? error.error.message : String(error.error)}`);
33
+ } };
34
+ const proof = ownedProof(launch.hooks);
35
+ if (proof?.capture && proof.config === launch.runtime) proof.reporting = { launch, callback: launch.onExtensionError };
36
+ return launch;
37
+ }
38
+
39
+ export function isReadonlyChildSessionReporting(launch: ChildSessionLaunch): boolean {
40
+ const proof = ownedProof(launch.hooks);
41
+ const descriptor = Object.getOwnPropertyDescriptor(launch, "onExtensionError");
42
+ if (descriptor && (!descriptor.enumerable || !("value" in descriptor))) return false;
43
+ return proof?.reporting ? proof.reporting.launch === launch && proof.reporting.callback === descriptor?.value : !descriptor && !("onExtensionError" in launch);
44
+ }
45
+
46
+ /** Admit only own enumerable data: inspecting descriptors must not invoke getters. */
47
+ function dataKeys(value: unknown): string[] | undefined {
48
+ if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) return undefined;
49
+ const keys = Reflect.ownKeys(value);
50
+ for (const key of keys) {
51
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
52
+ if (typeof key !== "string" || !descriptor.enumerable || !("value" in descriptor)) return undefined;
53
+ }
54
+ return keys as string[];
55
+ }
56
+
57
+ /** Only reviewed data and the capture callbacks constructed below; no caller callback opt-in. */
58
+ function readonlyConfig(config: ChildRuntimeConfig, capture?: OwnedCapture): string | undefined {
59
+ const strings = ["runId", "agent", "sessionName", "forkCacheKey", "parentSessionId", "orchestratorSessionId"];
60
+ const numbers = ["childIndex", "depth", "maxDepth"];
61
+ const booleans = ["inheritProjectContext", "inheritGlobalContext", "inheritSkills"];
62
+ const keys = dataKeys(config);
63
+ if (!keys) return undefined;
64
+ if (capture && (config.toolDiagnostic !== capture.toolDiagnostic || config.runtimeAcknowledgements !== capture.runtimeAcknowledgements)) return undefined;
65
+ const waitKeys = dataKeys(config.waitTool);
66
+ if (!waitKeys || waitKeys.some((key) => key !== "enabled")) return undefined;
67
+ if (config.fast !== false || config.fanoutChild !== false || config.waitTool.enabled !== false) return undefined;
68
+ for (const key of keys) {
69
+ const value = Object.getOwnPropertyDescriptor(config, key)!.value;
70
+ if (["fast", "fanoutChild", "waitTool"].includes(key)) continue;
71
+ if (capture && (key === "toolDiagnostic" || key === "runtimeAcknowledgements")) continue;
72
+ if (capture && key === "requiredTools" && Array.isArray(value) && Object.getPrototypeOf(value) === Array.prototype) {
73
+ const descriptors = Object.getOwnPropertyDescriptors(value);
74
+ if (Reflect.ownKeys(descriptors).length !== value.length + 1) return undefined;
75
+ for (let i = 0; i < value.length; i++) {
76
+ const descriptor = descriptors[String(i)];
77
+ if (!descriptor?.enumerable || !("value" in descriptor) || !["read", "ls"].includes(descriptor.value)) return undefined;
78
+ }
79
+ continue;
80
+ }
81
+ if (strings.includes(key) && (value === undefined || typeof value === "string")) continue;
82
+ if (numbers.includes(key) && (value === undefined || (typeof value === "number" && Number.isInteger(value) && value >= 0))) continue;
83
+ if (booleans.includes(key) && (value === undefined || typeof value === "boolean")) continue;
84
+ return undefined;
85
+ }
86
+ return JSON.stringify(config);
87
+ }
88
+
89
+ function noBackgroundProviders(): boolean {
90
+ try {
91
+ return listBackgroundWorkProviders().length === 0;
92
+ } catch { return false; }
93
+ }
94
+
95
+ /** Internal proof of the captured closure/config, not its caller-controlled display name. */
96
+ export function isReadonlyChildHookProfile(hooks: ChildHookExtension[], config: ChildRuntimeConfig): boolean {
97
+ const proof = ownedProof(hooks);
98
+ if (!proof) return false;
99
+ const valid = proof.config === config && readonlyConfig(config, proof.capture) === proof.snapshot && noBackgroundProviders();
100
+ if (!valid) proof.observation?.deny();
101
+ return valid && (proof.observation?.check() ?? true);
102
+ }
103
+
104
+ /** Arm just the next installation; ordinary installations retain the original API/handlers. */
105
+ export function observeReadonlyChildHookDrain(hooks: ChildHookExtension[], enabled: boolean, sessionFile: string): void {
106
+ const proof = ownedProof(hooks);
107
+ if (!proof) return;
108
+ if (enabled) {
109
+ proof.observation?.deny();
110
+ proof.observation = undefined;
111
+ }
112
+ proof.observeNext = enabled ? new ReadonlyDrainObservation(sessionFile, () => readonlyConfig(proof.config, proof.capture) === proof.snapshot && noBackgroundProviders()) : undefined;
113
+ }
114
+
115
+ export function captureReadonlyChildDrain(hooks: ChildHookExtension[]): (() => boolean) {
116
+ const proof = ownedProof(hooks);
117
+ const observation = proof?.observation;
118
+ return () => !!observation && proof?.observation === observation && observation.settled();
119
+ }
120
+
13
121
  /**
14
122
  * The child-side hooks pi-subagents installs in every child, keyed off the
15
123
  * launch config. The registrations live in `subagent-prompt-runtime.ts`,
16
124
  * `fast-mode-extension.ts`, and `fanout-child.ts`.
17
125
  */
18
126
  export function createChildHooks(config: ChildRuntimeConfig): ChildHookExtension[] {
127
+ return childHooks(config);
128
+ }
129
+
130
+ /** Launch-owned bookkeeping, paired with the same private hook certificate (no callback registration API). */
131
+ export function createCapturedChildHooks(config: ChildRuntimeConfig, runner = false) {
132
+ let diagnostic: ChildToolDiagnostic | undefined;
133
+ let acknowledgedIds: string[] | undefined;
134
+ let completionIntentContext: ArbiterModelContext | undefined;
135
+ let finalDrainHeld = false;
136
+ const capture: OwnedCapture = {
137
+ toolDiagnostic: (value) => { diagnostic = value; },
138
+ runtimeAcknowledgements: (ids) => { acknowledgedIds = ids; },
139
+ };
140
+ Object.assign(config, capture);
141
+ const hooks = childHooks(config, capture, (held) => { finalDrainHeld = held; });
142
+ if (runner) {
143
+ hooks.push({ name: "pi-subagents:completion-intent", factory: (pi) => pi.on("session_start", (_event, childCtx) => {
144
+ // Retain only attempt model services and the session id string, not the live child session.
145
+ completionIntentContext = {
146
+ model: childCtx.model,
147
+ modelRegistry: childCtx.modelRegistry,
148
+ sessionId: childCtx.sessionManager.getSessionId(),
149
+ };
150
+ }) });
151
+ const proof = promptProofs.get(hooks[0]!.factory);
152
+ if (proof) proof.factories = hooks.map((hook) => hook.factory);
153
+ }
154
+ return {
155
+ hooks,
156
+ completionIntentContext: () => completionIntentContext,
157
+ toolDiagnostic: () => diagnostic,
158
+ runtimeAcknowledgedExtensions: () => acknowledgedIds ? projectRuntimeAcknowledgedExtensions(acknowledgedIds) : undefined,
159
+ finalDrainHeld: () => finalDrainHeld,
160
+ };
161
+ }
162
+
163
+ function childHooks(config: ChildRuntimeConfig, capture?: OwnedCapture, holdFinalDrain?: (held: boolean) => void): ChildHookExtension[] {
164
+ const snapshot = readonlyConfig(config, capture);
165
+ const proof: PromptProof | undefined = snapshot === undefined ? undefined : { config, snapshot, capture };
166
+ const runtime = Object.create(config) as ChildRuntimeConfig;
167
+ const ownedState = Object.getOwnPropertyDescriptor(config, "runtimeState");
168
+ if (!ownedState || !("value" in ownedState) || ownedState.value == null) {
169
+ Object.defineProperty(runtime, "runtimeState", { configurable: true, enumerable: true, writable: true, value: createChildSafeState() });
170
+ }
171
+ if (holdFinalDrain) {
172
+ Object.defineProperty(runtime, "holdFinalDrain", { configurable: true, enumerable: true, writable: true, value: holdFinalDrain });
173
+ }
19
174
  const hooks: ChildHookExtension[] = [
20
- { name: "pi-subagents:prompt-runtime", factory: (pi) => registerSubagentPromptRuntime(pi, config) },
175
+ { name: "pi-subagents:prompt-runtime", factory: function promptRuntime(pi) {
176
+ if (!proof?.observeNext) return registerSubagentPromptRuntime(pi, runtime);
177
+ proof.observation = proof.observeNext;
178
+ proof.observeNext = undefined;
179
+ registerSubagentPromptRuntime(pi, runtime, proof.observation);
180
+ } },
21
181
  ];
182
+ if (proof) {
183
+ proof.factories = hooks.map((hook) => hook.factory);
184
+ promptProofs.set(hooks[0]!.factory, proof);
185
+ }
22
186
  if (config.fast) hooks.push({ name: "pi-subagents:fast-mode", factory: (pi) => registerSubagentFastModeExtension(pi) });
23
- if (config.fanoutChild) hooks.push({ name: "pi-subagents:fanout-child", factory: (pi) => registerFanoutChildSubagentExtension(pi, config) });
187
+ if (config.fanoutChild) hooks.push({ name: "pi-subagents:fanout-child", factory: (pi) => registerFanoutChildSubagentExtension(pi, runtime) });
24
188
  return hooks;
25
189
  }
@@ -1,7 +1,7 @@
1
1
  import * as path from "node:path";
2
2
  import type { AgentConfig } from "../../agents/agents.ts";
3
3
  import { resolveChildCwd } from "../../shared/utils.ts";
4
- import type { OutputMode } from "../../shared/types.ts";
4
+ import type { JsonSchemaObject, OutputMode } from "../../shared/types.ts";
5
5
  import { resolveSingleOutputPath } from "./single-output.ts";
6
6
 
7
7
  export interface ResolvedStepBehavior {
@@ -12,6 +12,7 @@ export interface ResolvedStepBehavior {
12
12
  skills: string[] | false;
13
13
  model?: string;
14
14
  fast?: boolean;
15
+ outputSchema?: JsonSchemaObject;
15
16
  }
16
17
 
17
18
  export type OutputOverrideInput = string | boolean;
@@ -24,6 +25,7 @@ export interface StepOverrides {
24
25
  skills?: string[] | false;
25
26
  model?: string;
26
27
  fast?: boolean;
28
+ outputSchema?: JsonSchemaObject | false;
27
29
  }
28
30
 
29
31
  export interface ChildLaunchPlanInput {
@@ -35,6 +37,7 @@ export interface ChildLaunchPlanInput {
35
37
  runtimeCwd: string;
36
38
  stepCwdInput?: string;
37
39
  behaviorCwd?: string;
40
+ machineCwd?: string;
38
41
  chainSkills?: string[];
39
42
  outputBaseDir?: string;
40
43
  parallelOutputNamespace?: { stepIndex: number; taskIndex?: number };
@@ -58,6 +61,14 @@ export function normalizeOutputOverride(output: unknown): string | false | undef
58
61
  return typeof output === "string" && output.length > 0 ? output : undefined;
59
62
  }
60
63
 
64
+ export const resolveEffectiveOutputSchema = (agentConfig: AgentConfig, override?: JsonSchemaObject | false): JsonSchemaObject | undefined => override === false ? undefined : override !== undefined ? override : agentConfig.outputSchema;
65
+
66
+ type OutputSchemaStep = { agent: string; outputSchema?: JsonSchemaObject | false };
67
+ export function projectChainOutputSchemas<S extends OutputSchemaStep, R = S, G = { parallel: R[] | R }>(chain: readonly (S | { parallel: S[] | S })[], agents: AgentConfig[], projectStep?: (step: S, outputSchema: JsonSchemaObject | undefined) => R, projectGroup?: (step: { parallel: S[] | S }, parallel: R[] | R) => G): Array<R | G> {
68
+ const project = (step: S): R => { const agent = agents.find((candidate) => candidate.name === step.agent); if (!agent && !projectStep) return step as unknown as R; const outputSchema = agent && resolveEffectiveOutputSchema(agent, step.outputSchema); return projectStep ? projectStep(step, outputSchema) : { ...step, outputSchema } as unknown as R; };
69
+ return chain.map((step) => { if (!("parallel" in step)) return project(step as S); const parallel = Array.isArray(step.parallel) ? step.parallel.map(project) : project(step.parallel as S); return projectGroup ? projectGroup(step, parallel) : { ...step, parallel } as unknown as G; });
70
+ }
71
+
61
72
  export function resolveStepBehavior(
62
73
  agentConfig: AgentConfig,
63
74
  stepOverrides: StepOverrides,
@@ -94,7 +105,8 @@ export function resolveStepBehavior(
94
105
  const outputMode = stepOverrides.outputMode ?? agentConfig.outputMode ?? "inline";
95
106
  const model = stepOverrides.model ?? agentConfig.model;
96
107
  const fast = stepOverrides.fast ?? agentConfig.fast;
97
- return { output, outputMode, reads, progress, skills, model, fast };
108
+ const outputSchema = resolveEffectiveOutputSchema(agentConfig, stepOverrides.outputSchema);
109
+ return { output, outputMode, reads, progress, skills, model, fast, ...(outputSchema !== undefined ? { outputSchema } : {}) };
98
110
  }
99
111
 
100
112
  export function resolveTaskTextForFileUpdatePolicy(task: string | undefined, originalTask?: string): string | undefined {
@@ -117,7 +129,7 @@ export function suppressProgressForReadOnlyTask(behavior: ResolvedStepBehavior,
117
129
  }
118
130
 
119
131
  export function planChildLaunch(input: ChildLaunchPlanInput): ChildLaunchPlan {
120
- const stepCwd = resolveChildCwd(input.runnerCwd, input.stepCwdInput);
132
+ const stepCwd = input.machineCwd ?? resolveChildCwd(input.runnerCwd, input.stepCwdInput);
121
133
  const instructionCwd = input.behaviorCwd ?? stepCwd;
122
134
  const readExistenceCwd = input.behaviorCwd ? stepCwd : instructionCwd;
123
135
  let behavior = suppressProgressForReadOnlyTask(
@@ -13,9 +13,10 @@ import { intersectThinkingCeilings } from "../../shared/thinking-ceiling.ts";
13
13
  import {
14
14
  TEMP_ROOT_DIR,
15
15
  resolveChildDepth,
16
- type LaunchResolvedChildExtensionsV1,
16
+ type LaunchResolvedChildExtensions,
17
17
  type ResolvedToolBudget,
18
18
  type RunFanoutBudgetDescriptor,
19
+ type HerdrMachineReference,
19
20
  } from "../../shared/types.ts";
20
21
  import { SUBAGENT_SANDBOX_PROFILE_ENV, SUBAGENT_SANDBOX_PROJECT_TRUST_ENV } from "../../shared/sandbox-profile.ts";
21
22
  import { SUBAGENT_PERMISSION_PROFILE_ENV, SUBAGENT_PERMISSION_PROFILE_PINNED_ENV } from "../../shared/permission-profile.ts";
@@ -24,8 +25,7 @@ import type { McpRuntimeSnapshotHost } from "./mcp-direct-tool-allowlist.ts";
24
25
  import type { PermissionRules } from "./permissions.ts";
25
26
  import type { StructuredOutputRuntime } from "./structured-output.ts";
26
27
  import type { ChildToolDiagnostic } from "./tool-availability.ts";
27
- import type { RuntimeAcknowledgedChildExtensionsV1 } from "../../shared/types.ts";
28
- import { projectRuntimeAcknowledgedExtensions } from "./runtime-acknowledged-extensions.ts";
28
+ import type { RuntimeAcknowledgedChildExtensions } from "../../shared/types.ts";
29
29
  import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV, type ExtensionBindings } from "./extension-bindings.ts";
30
30
  import { SANDBOX_DIAGNOSTICS_PATH_ENV } from "./sandbox-startup-diagnostics.ts";
31
31
  import type { ResolvedSubagentCapabilityCeiling, SubagentCapabilityAudit } from "./capability-ceiling.ts";
@@ -37,8 +37,11 @@ import {
37
37
  type PiLaunchToolPlan,
38
38
  } from "./child-tool-plan.ts";
39
39
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
40
- import { createChildHooks } from "./child-hooks.ts";
40
+ import { createCapturedChildHooks, withChildSessionErrorReporting } from "./child-hooks.ts";
41
+ import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
41
42
  import type { ChildSessionLaunch, ChildSessionStorage } from "./child-session.ts";
43
+ import type { ArbiterModelContext } from "./llm-intent-arbiter.ts";
44
+ import { resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
42
45
 
43
46
  /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
44
47
  export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
@@ -60,7 +63,7 @@ function hasTrustedProfileProjectCwd(input: Pick<BuildInProcessChildLaunchInput,
60
63
  * launches inherits. Serialized into the background runner config; the
61
64
  * foreground path passes the executor's full `ChildRuntimeConfig`.
62
65
  */
63
- export type InheritedChildRuntime = Pick<ChildRuntimeConfig, "depth" | "maxDepth" | "nestedRoute" | "nestedParent" | "capabilityCeiling" | "thinkingCeiling" | "runFanoutBudget">;
66
+ export type InheritedChildRuntime = Pick<ChildRuntimeConfig, "depth" | "maxDepth" | "nestedRoute" | "nestedParent" | "capabilityCeiling" | "thinkingCeiling" | "runFanoutBudget" | "requiredExtensions">;
64
67
 
65
68
  export function inheritedChildRuntime(config: ChildRuntimeConfig | undefined): InheritedChildRuntime | undefined {
66
69
  if (!config) return undefined;
@@ -72,10 +75,14 @@ export function inheritedChildRuntime(config: ChildRuntimeConfig | undefined): I
72
75
  ...(config.capabilityCeiling ? { capabilityCeiling: config.capabilityCeiling } : {}),
73
76
  ...(config.thinkingCeiling ? { thinkingCeiling: config.thinkingCeiling } : {}),
74
77
  ...(config.runFanoutBudget ? { runFanoutBudget: config.runFanoutBudget } : {}),
78
+ ...(config.requiredExtensions ? { requiredExtensions: config.requiredExtensions } : {}),
75
79
  };
76
80
  }
77
81
 
78
82
  export interface BuildInProcessChildLaunchInput {
83
+ machine?: HerdrMachineReference;
84
+ remoteSkillNames?: string[];
85
+ remoteReads?: string[] | false;
79
86
  parentSessionId?: string;
80
87
  forkCacheKey?: string;
81
88
  sessionEnabled: boolean;
@@ -92,6 +99,8 @@ export interface BuildInProcessChildLaunchInput {
92
99
  excludeTools?: string[];
93
100
  extensions?: string[];
94
101
  subagentOnlyExtensions?: string[];
102
+ /** Serialized launch snapshot; omitted only for a top-level parent-process lookup. */
103
+ requiredExtensions?: RequiredChildExtensionSnapshot;
95
104
  systemPrompt?: string | null;
96
105
  mcpDirectTools?: string[];
97
106
  extensionBindings?: ExtensionBindings;
@@ -106,7 +115,6 @@ export interface BuildInProcessChildLaunchInput {
106
115
  runFanoutBudget?: RunFanoutBudgetDescriptor;
107
116
  structuredOutput?: StructuredOutputRuntime;
108
117
  fast?: boolean;
109
- modelCandidates?: readonly string[];
110
118
  toolBudget?: ResolvedToolBudget;
111
119
  permissionRules?: PermissionRules;
112
120
  permissionAuditPath?: string;
@@ -136,12 +144,21 @@ export interface BuildInProcessChildLaunchInput {
136
144
  * them and exposes the child environment external extensions read.
137
145
  */
138
146
  host: "parent" | "runner";
147
+ /**
148
+ * Pi core tool names the host runtime provides. When set, child tool plans
149
+ * intersect known core slots with this set; declared non-core names remain
150
+ * for child startup validation. Review/scout lanes fail closed when a requested,
151
+ * still-permitted repository inspection tool is missing from that set.
152
+ */
153
+ hostAvailableBuiltins?: readonly string[];
139
154
  }
140
155
 
141
156
  export interface InProcessChildCapture {
157
+ completionIntentContext?(): ArbiterModelContext | undefined;
142
158
  structuredOutput(): { called: boolean; value?: unknown; acceptanceReport?: unknown; acceptanceReportProvided: boolean };
143
159
  toolDiagnostic(): ChildToolDiagnostic | undefined;
144
- runtimeAcknowledgedExtensions(): RuntimeAcknowledgedChildExtensionsV1 | undefined;
160
+ runtimeAcknowledgedExtensions(): RuntimeAcknowledgedChildExtensions | undefined;
161
+ finalDrainHeld(): boolean;
145
162
  }
146
163
 
147
164
  export interface InProcessChildLaunch {
@@ -149,7 +166,7 @@ export interface InProcessChildLaunch {
149
166
  config: ChildRuntimeConfig;
150
167
  session: Omit<ChildSessionLaunch, "onExtensionError">;
151
168
  capture: InProcessChildCapture;
152
- launchResolvedExtensions: LaunchResolvedChildExtensionsV1;
169
+ launchResolvedExtensions: LaunchResolvedChildExtensions;
153
170
  warnings: string[];
154
171
  capabilityAudit?: SubagentCapabilityAudit;
155
172
  /** Path a blocked child extension writes its startup failure to; see
@@ -157,6 +174,11 @@ export interface InProcessChildLaunch {
157
174
  sandboxDiagnosticsPath?: string;
158
175
  }
159
176
 
177
+ /** Actual host create-input boundary. Evidence remains explicitly opt-in and dormant in production. */
178
+ export function createReportedChildSessionInput(launch: InProcessChildLaunch, transcriptWriter?: ChildTranscriptWriter): ChildSessionLaunch {
179
+ return withChildSessionErrorReporting(launch.session, transcriptWriter);
180
+ }
181
+
160
182
  /** Escape XML-significant characters in a string for safe attribute interpolation. */
161
183
  function escapeXmlAttr(value: string): string {
162
184
  return value
@@ -195,19 +217,20 @@ function childStorage(input: BuildInProcessChildLaunchInput): ChildSessionStorag
195
217
  }
196
218
 
197
219
  export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput): InProcessChildLaunch {
220
+ const requiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
198
221
  const toolPlan = resolvePiLaunchToolPlan({
199
222
  tools: input.tools,
200
223
  excludeTools: input.excludeTools,
201
224
  allowNestedSubagents: input.allowNestedSubagents,
202
225
  extensions: input.extensions,
203
226
  subagentOnlyExtensions: input.subagentOnlyExtensions,
227
+ requiredExtensions,
204
228
  mcpDirectTools: input.mcpDirectTools,
205
229
  cwd: input.cwd,
206
230
  requireReadTool: input.requireReadTool,
207
231
  structuredOutput: Boolean(input.structuredOutput),
208
232
  fast: input.fast,
209
233
  model: input.model,
210
- modelCandidates: input.modelCandidates,
211
234
  capabilityCeiling: input.capabilityCeiling,
212
235
  inheritedCapabilityCeiling: inheritedCapabilityCeiling(input.inherited),
213
236
  agentName: input.childAgentName,
@@ -215,6 +238,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
215
238
  runtimeSnapshotHost: input.runtimeSnapshotHost,
216
239
  sandbox: input.sandbox,
217
240
  permissionProfile: input.permissionProfile,
241
+ hostAvailableBuiltins: input.hostAvailableBuiltins,
218
242
  });
219
243
 
220
244
  // A selected profile is validated by resolvePiLaunchToolPlan; the child
@@ -297,8 +321,6 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
297
321
  let structuredAcceptanceReport: unknown;
298
322
  let structuredCalled = false;
299
323
  let structuredAcceptanceProvided = false;
300
- let toolDiagnostic: ChildToolDiagnostic | undefined;
301
- let acknowledgedIds: string[] | undefined;
302
324
 
303
325
  const config: ChildRuntimeConfig = {
304
326
  ...(input.runId ? { runId: input.runId } : {}),
@@ -317,6 +339,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
317
339
  maxDepth: childDepth.maxDepth,
318
340
  ...(toolPlan.capabilityCeiling ? { capabilityCeiling: toolPlan.capabilityCeiling } : {}),
319
341
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
342
+ ...(toolPlan.requiredExtensions.length > 0 ? { requiredExtensions: toolPlan.requiredExtensions } : {}),
320
343
  inheritProjectContext: input.inheritProjectContext,
321
344
  inheritGlobalContext: input.inheritGlobalContext,
322
345
  inheritSkills: input.inheritSkills,
@@ -347,10 +370,9 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
347
370
  : {}),
348
371
  ...(toolPlan.requiredChildTools.length > 0 ? { requiredTools: toolPlan.requiredChildTools } : {}),
349
372
  ...(toolPlan.effectiveMcpTools.length > 0 ? { mcpDirectTools: toolPlan.effectiveMcpTools } : {}),
350
- toolDiagnostic: (diagnostic) => { toolDiagnostic = diagnostic; },
351
- runtimeAcknowledgements: (ids) => { acknowledgedIds = ids; },
352
373
  fast: input.fast === true,
353
374
  };
375
+ const capturedHooks = createCapturedChildHooks(config, input.host === "runner");
354
376
 
355
377
  const extensionPaths = toolPlan.extensionArgs.filter((extensionPath) => !isSubagentRuntimeExtensionPath(extensionPath));
356
378
  const ambientExtensions = input.host === "runner" && !toolPlan.disableAmbientExtensions;
@@ -359,19 +381,23 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
359
381
  configuredExtensions: toolPlan.configuredExtensions,
360
382
  extensionArgs: toolPlan.extensionArgs,
361
383
  disableAmbientExtensions: !ambientExtensions,
384
+ requiredExtensions: toolPlan.requiredExtensions,
362
385
  });
363
386
  const taggedPrompt = input.systemPrompt !== undefined && input.systemPrompt !== null
364
387
  ? `<active_agent name="${escapeXmlAttr(input.childAgentName)}"/>\n\n${input.systemPrompt}`
365
388
  : undefined;
366
389
  const session: Omit<ChildSessionLaunch, "onExtensionError"> = {
367
390
  cwd: input.cwd,
391
+ ...(input.machine ? { machine: input.machine } : {}),
392
+ ...(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] } : {}) } } : {}),
368
393
  storage: childStorage(input),
369
394
  ...(input.model ? { model: input.model } : {}),
370
395
  ...(toolPlan.explicitToolAllowlist ? { tools: toolPlan.effectiveToolAllowlist } : {}),
371
396
  ...(!toolPlan.explicitToolAllowlist && toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
372
397
  extensionPaths,
398
+ requiredExtensions: toolPlan.requiredExtensions,
373
399
  ambientExtensions,
374
- hooks: createChildHooks(config),
400
+ hooks: capturedHooks.hooks,
375
401
  ...(input.host === "runner" || childEnv
376
402
  ? { processEnv: { ...childProcessEnv(input, toolPlan, childEnv), ...profilePin } }
377
403
  : { processEnv: profilePin }),
@@ -389,9 +415,11 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
389
415
  config,
390
416
  session,
391
417
  capture: {
418
+ completionIntentContext: capturedHooks.completionIntentContext,
392
419
  structuredOutput: () => ({ called: structuredCalled, value: structuredValue, acceptanceReport: structuredAcceptanceReport, acceptanceReportProvided: structuredAcceptanceProvided }),
393
- toolDiagnostic: () => toolDiagnostic,
394
- runtimeAcknowledgedExtensions: () => (acknowledgedIds ? projectRuntimeAcknowledgedExtensions(acknowledgedIds) : undefined),
420
+ toolDiagnostic: capturedHooks.toolDiagnostic,
421
+ runtimeAcknowledgedExtensions: capturedHooks.runtimeAcknowledgedExtensions,
422
+ finalDrainHeld: capturedHooks.finalDrainHeld,
395
423
  },
396
424
  launchResolvedExtensions,
397
425
  warnings: toolPlan.warnings,
@@ -14,11 +14,14 @@ export function projectChildLifecycle(event: { type?: string; willRetry?: unknow
14
14
  if (state) state.compactionRetryActive = event.willRetry === true;
15
15
  return event.willRetry === true ? "cancel-drain" : "none";
16
16
  }
17
- if (event.type === "agent_start" || event.type === "auto_retry_start") {
17
+ if (event.type === "agent_start" || event.type === "auto_retry_start" || event.type === "turn_start") {
18
18
  if (state) state.compactionRetryActive = false;
19
+ return "cancel-drain";
20
+ }
21
+ if (event.type === "agent_end") {
22
+ if (event.willRetry !== true && state) state.compactionRetryActive = false;
23
+ return "cancel-drain";
19
24
  }
20
- if (event.type === "agent_end" && event.willRetry === true) return "cancel-drain";
21
- if (event.type === "agent_end" && state) state.compactionRetryActive = false;
22
25
  if (event.type === "agent_settled") return state?.compactionRetryActive ? "none" : "start-drain";
23
26
  if (terminalAssistantStop) return "start-drain";
24
27
  return "none";
@@ -1,4 +1,4 @@
1
- import type { JsonSchemaObject, ResolvedToolBudget, RunFanoutBudgetDescriptor } from "../../shared/types.ts";
1
+ import type { JsonSchemaObject, ResolvedToolBudget, RunFanoutBudgetDescriptor, SubagentState } from "../../shared/types.ts";
2
2
  import type { ThinkingLevel } from "../../shared/model-info.ts";
3
3
  import type { NestedPathEntry } from "./nested-path.ts";
4
4
  import type { PermissionRules } from "./permissions.ts";
@@ -6,6 +6,7 @@ import type { ChildWatchdogConfig, ChildWatchdogStatusEvent } from "../../watchd
6
6
  import type { ResolvedWaitToolConfig } from "../background/wait-config.ts";
7
7
  import type { ChildToolDiagnostic } from "./tool-availability.ts";
8
8
  import type { ResolvedSubagentCapabilityCeiling } from "./capability-ceiling.ts";
9
+ import type { RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
9
10
 
10
11
  /**
11
12
  * Set in processes that host child sessions (the async runner). The extension
@@ -75,6 +76,8 @@ export interface ChildRuntimeConfig {
75
76
  depth: number;
76
77
  maxDepth?: number;
77
78
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
79
+ /** Immutable root-parent host policy propagated to nested native launches. */
80
+ requiredExtensions?: RequiredChildExtensionSnapshot;
78
81
  thinkingCeiling?: ThinkingLevel;
79
82
  inheritProjectContext?: boolean;
80
83
  inheritGlobalContext?: boolean;
@@ -86,6 +89,10 @@ export interface ChildRuntimeConfig {
86
89
  /** Receives child watchdog status events. */
87
90
  watchdogStatus?: (event: ChildWatchdogStatusEvent) => void;
88
91
  waitTool: ResolvedWaitToolConfig;
92
+ runtimeState?: SubagentState;
93
+ holdFinalDrain?: (held: boolean) => void;
94
+ /** Installation-local downward owner-channel barrier; never inherited or serialized into descendants. */
95
+ hasPendingSupervisorRequest?: () => boolean;
89
96
  structuredOutput?: ChildStructuredOutput;
90
97
  requiredTools?: string[];
91
98
  mcpDirectTools?: string[];