@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
@@ -5,13 +5,15 @@
5
5
  * parent pi process for foreground children, the detached runner process for
6
6
  * background children. The factory is injectable so tests can script a child
7
7
  * without the real runtime; the default implementation wraps
8
- * `createAgentSession` from a pi package module and shares one `ModelRuntime`
9
- * across every child it creates.
8
+ * `createAgentSession` from a pi package module.
10
9
  */
11
10
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
12
11
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
+ import { pinChildCacheRetention } from "../../shared/child-cache-retention.ts";
13
13
  import { getAgentDir } from "../../shared/utils.ts";
14
14
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
15
+ import type { RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
16
+ import type { HerdrMachineReference, HerdrRemoteGitStatus } from "../../shared/types.ts";
15
17
 
16
18
  export interface ChildSessionEvent {
17
19
  type: string;
@@ -46,6 +48,12 @@ export type ChildSessionStorage =
46
48
 
47
49
  export interface ChildSessionLaunch {
48
50
  cwd: string;
51
+ /** Resolved pane-native placement. Local launches omit this field. */
52
+ machine?: HerdrMachineReference;
53
+ /** Process-local provider source owned by the invoking foreground parent. */
54
+ parentProviderRegistry?: ParentProviderRegistry;
55
+ /** Logical names resolved only by the remote ambient package. */
56
+ remoteResources?: { agent: string; skills?: string[]; toolCeiling?: string[]; reads?: string[] | false };
49
57
  storage: ChildSessionStorage;
50
58
  /** Model reference as the agent config names it (`provider/id`, optionally `:thinking`). */
51
59
  model?: string;
@@ -54,6 +62,8 @@ export interface ChildSessionLaunch {
54
62
  excludeTools?: string[];
55
63
  /** Extension files loaded for this child in addition to the inline hooks. */
56
64
  extensionPaths: string[];
65
+ /** Canonical required paths and safe evidence identities for fail-closed loading. */
66
+ requiredExtensions?: RequiredChildExtensionSnapshot;
57
67
  /**
58
68
  * Discover the ambient extensions (agent dir, project, settings) the way a
59
69
  * `pi` process would. False loads only `extensionPaths` and `hooks`.
@@ -92,16 +102,29 @@ export interface ChildSession {
92
102
  abort(): Promise<void>;
93
103
  /** Emits `session_shutdown` to the child's extensions and disposes the session; resolves once that shutdown work is done. */
94
104
  dispose(): Promise<void>;
105
+ /** True while Pi still has steering or follow-up input that has not started a turn. */
106
+ hasQueuedMessages?(): boolean;
95
107
  readonly messages: readonly AgentMessage[];
96
108
  readonly sessionFile: string | undefined;
97
109
  readonly sessionId: string;
98
110
  readonly modelId: string | undefined;
111
+ readonly machineEvidence?: { machineId: string; initial?: HerdrRemoteGitStatus; final?: HerdrRemoteGitStatus };
112
+ /** Event-updated pane-native status; reading it performs no network work. */
113
+ readonly placementSnapshot?: unknown;
99
114
  /** Set by the foreground host once the run detached; `factory.dispose()` leaves such children running. */
100
115
  detached?: boolean;
101
116
  /** Set by `factory.dispose()` before it aborts the child, so the host can report the stop truthfully. */
102
117
  shutDown?: boolean;
103
118
  }
104
119
 
120
+ export function childSessionHasQueuedMessages(session: ChildSession | undefined): boolean {
121
+ try {
122
+ return session?.hasQueuedMessages?.() === true;
123
+ } catch {
124
+ return false;
125
+ }
126
+ }
127
+
105
128
  export interface ChildSessionFactory {
106
129
  create(launch: ChildSessionLaunch): Promise<ChildSession>;
107
130
  /** Abort and dispose every live attached child; detached children keep running and hold the shared runtime. */
@@ -122,16 +145,48 @@ export interface DefaultChildSessionFactoryOptions {
122
145
  }
123
146
 
124
147
  type ModelRuntimeInstance = Awaited<ReturnType<PiCodingAgentModule["ModelRuntime"]["create"]>>;
125
- type QueuedProviderRegistration = { name: string; config: Parameters<ModelRuntimeInstance["registerProvider"]>[1]; extensionPath: string };
126
- type QueuedNativeProviderRegistration = { provider: Parameters<ModelRuntimeInstance["registerNativeProvider"]>[0]; extensionPath: string };
127
148
 
128
- interface LoaderWithExtensions {
129
- getExtensions(): {
130
- runtime: {
131
- pendingProviderRegistrations: QueuedProviderRegistration[];
132
- pendingNativeProviderRegistrations: QueuedNativeProviderRegistration[];
133
- };
134
- };
149
+ export type ParentProviderRegistry = Pick<ModelRuntimeInstance, "getRegisteredProviderIds" | "getRegisteredProviderConfig" | "getRegisteredNativeProvider">;
150
+
151
+ function inheritParentProviders(modelRuntime: ModelRuntimeInstance, parentProviders: ParentProviderRegistry, claimedProviderIds: ReadonlySet<string>, onError: ((error: ChildSessionExtensionError) => void) | undefined): boolean {
152
+ let providerIds: readonly string[];
153
+ try {
154
+ providerIds = parentProviders.getRegisteredProviderIds();
155
+ } catch (error) {
156
+ onError?.({ extensionPath: "<parent-providers>", event: "inherit_provider", error });
157
+ throw new Error(`Failed to enumerate parent providers: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
158
+ }
159
+ let registered = false;
160
+ for (const providerId of new Set(providerIds)) {
161
+ if (claimedProviderIds.has(providerId)) continue;
162
+ try {
163
+ const native = parentProviders.getRegisteredNativeProvider(providerId);
164
+ const config = native ? undefined : parentProviders.getRegisteredProviderConfig(providerId);
165
+ if (native) modelRuntime.registerNativeProvider(native);
166
+ else if (config) modelRuntime.registerProvider(providerId, config);
167
+ else throw new Error(`Parent provider '${providerId}' has no registered native provider or config.`);
168
+ registered = true;
169
+ } catch (error) {
170
+ onError?.({ extensionPath: `<parent-provider:${providerId}>`, event: "inherit_provider", error });
171
+ throw new Error(`Failed to inherit parent provider '${providerId}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
172
+ }
173
+ }
174
+ return registered;
175
+ }
176
+
177
+ const CHILD_PROMPT_RUNTIME_EXTENSION_PATH = "<inline:pi-subagents:prompt-runtime>";
178
+
179
+ /** The prompt runtime filters parent-only context before ambient extensions inspect
180
+ * the child prompt. Other inline hooks keep their normal position after ambient
181
+ * extensions, and ambient extension order stays unchanged. */
182
+ function prioritizeChildPromptRuntime<T extends { extensions: Array<{ path: string }> }>(result: T): T {
183
+ const index = result.extensions.findIndex(({ path }) => path === CHILD_PROMPT_RUNTIME_EXTENSION_PATH);
184
+ if (index <= 0) return result;
185
+ const extensions = [...result.extensions];
186
+ const [promptRuntime] = extensions.splice(index, 1);
187
+ if (!promptRuntime) return result;
188
+ extensions.unshift(promptRuntime);
189
+ return { ...result, extensions };
135
190
  }
136
191
 
137
192
  /** One launch at a time from env application through `session_start`, so parallel launches never observe each other's `processEnv` while their extensions load and start. */
@@ -170,30 +225,39 @@ function restoreProcessEnv(saved: Array<[string, string | undefined]>): void {
170
225
  }
171
226
  }
172
227
 
173
- function flushQueuedProviderRegistrations(loader: object, modelRuntime: ModelRuntimeInstance, onError: ((error: ChildSessionExtensionError) => void) | undefined): void {
174
- if (!("getExtensions" in loader) || typeof loader.getExtensions !== "function") return;
175
- const { runtime } = (loader as LoaderWithExtensions).getExtensions();
176
- for (const { name, config, extensionPath } of runtime.pendingProviderRegistrations) {
228
+ function flushQueuedProviderRegistrations(loader: InstanceType<PiCodingAgentModule["DefaultResourceLoader"]>, modelRuntime: ModelRuntimeInstance, onError: ((error: ChildSessionExtensionError) => void) | undefined, requiredPaths: ReadonlySet<string>): { claimedProviderIds: Set<string>; registered: boolean } {
229
+ const claimedProviderIds = new Set<string>();
230
+ if (!("getExtensions" in loader) || typeof loader.getExtensions !== "function") return { claimedProviderIds, registered: false };
231
+ const { runtime } = loader.getExtensions();
232
+ let registered = false;
233
+ for (const { name, config, extensionPath } of runtime.pendingProviderRegistrations ?? []) {
234
+ claimedProviderIds.add(name);
177
235
  try {
178
236
  modelRuntime.registerProvider(name, config);
237
+ registered = true;
179
238
  } catch (error) {
180
239
  onError?.({ extensionPath, event: "register_provider", error });
240
+ if (requiredPaths.has(extensionPath)) throw new Error(`Required child extension provider registration failed for '${extensionPath}': ${error instanceof Error ? error.message : String(error)}`);
181
241
  }
182
242
  }
183
- runtime.pendingProviderRegistrations = [];
184
- for (const { provider, extensionPath } of runtime.pendingNativeProviderRegistrations) {
243
+ if (Array.isArray(runtime.pendingProviderRegistrations)) runtime.pendingProviderRegistrations = [];
244
+ for (const { provider, extensionPath } of runtime.pendingNativeProviderRegistrations ?? []) {
245
+ claimedProviderIds.add(provider.id);
185
246
  try {
186
247
  modelRuntime.registerNativeProvider(provider);
248
+ registered = true;
187
249
  } catch (error) {
188
250
  onError?.({ extensionPath, event: "register_provider", error });
251
+ if (requiredPaths.has(extensionPath)) throw new Error(`Required child extension provider registration failed for '${extensionPath}': ${error instanceof Error ? error.message : String(error)}`);
189
252
  }
190
253
  }
191
- runtime.pendingNativeProviderRegistrations = [];
254
+ if (Array.isArray(runtime.pendingNativeProviderRegistrations)) runtime.pendingNativeProviderRegistrations = [];
255
+ return { claimedProviderIds, registered };
192
256
  }
193
257
 
194
258
  /**
195
- * Default factory: real pi sessions sharing one `ModelRuntime`, created lazily
196
- * on the first child launch and dropped on `dispose()`.
259
+ * Default factory: detached/background sessions retain the existing shared
260
+ * runtime; each parent-bound foreground launch gets an isolated runtime.
197
261
  */
198
262
  export function createDefaultChildSessionFactory(options: DefaultChildSessionFactoryOptions = {}): ChildSessionFactory {
199
263
  const loadPiCodingAgent = options.loadPiCodingAgent ?? (() => import("@earendil-works/pi-coding-agent"));
@@ -212,9 +276,17 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
212
276
  return {
213
277
  async create(launch) {
214
278
  const pi = await loadPiCodingAgent();
215
- const modelRuntime = await sharedRuntime(pi);
279
+ const modelRuntime = launch.parentProviderRegistry
280
+ ? await pi.ModelRuntime.create()
281
+ : await sharedRuntime(pi);
216
282
  const agentDir = getAgentDir();
217
283
  const settingsManager = pi.SettingsManager.create(launch.cwd, agentDir);
284
+ // Foreground children share Pi's global theme with the parent, so reinitializing it
285
+ // would overwrite the parent's active light/dark appearance. Detached runners have
286
+ // no initialized theme and must initialize one for headless extension renderers.
287
+ const themeKey = Symbol.for("@earendil-works/pi-coding-agent:theme");
288
+ const themeInitialized = Boolean((globalThis as Record<symbol, unknown>)[themeKey]);
289
+ if (!themeInitialized && typeof pi.initTheme === "function") pi.initTheme(settingsManager.getTheme());
218
290
  const loader = new pi.DefaultResourceLoader({
219
291
  cwd: launch.cwd,
220
292
  agentDir,
@@ -226,15 +298,31 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
226
298
  noContextFiles: launch.noContextFiles,
227
299
  additionalExtensionPaths: launch.extensionPaths,
228
300
  extensionFactories: launch.hooks,
301
+ extensionsOverride: prioritizeChildPromptRuntime,
229
302
  ...(launch.systemPrompt !== undefined ? { systemPrompt: launch.systemPrompt } : {}),
230
303
  ...(launch.appendSystemPrompt !== undefined ? { appendSystemPrompt: [launch.appendSystemPrompt] } : {}),
231
304
  });
232
305
  const open = async () => {
306
+ const requiredPaths = new Set((launch.requiredExtensions ?? []).map(({ path }) => path));
233
307
  const savedTransientEnv = captureProcessEnv(launch.transientProcessEnv);
234
308
  applyProcessEnv(launch.processEnv);
235
309
  if (!resetExtensionCacheOnReload(loader) && (launch.ambientExtensions || launch.extensionPaths.length)) launch.onExtensionError?.({ extensionPath: "<loader>", event: "load", error: new Error("pi's extension cache reset is unavailable; extensions loaded into this child share module state with other sessions in this process.") });
236
310
  await loader.reload();
237
- flushQueuedProviderRegistrations(loader, modelRuntime, launch.onExtensionError);
311
+ const loadErrors = requiredPaths.size > 0
312
+ ? loader.getExtensions().errors.filter(({ path }) => requiredPaths.has(path)) : [];
313
+ if (loadErrors.length > 0) throw new Error(`Required child extension failed to load: ${loadErrors.map(({ path, error }) => `${path}: ${error}`).join("; ")}`);
314
+ const queued = flushQueuedProviderRegistrations(loader, modelRuntime, launch.onExtensionError, requiredPaths);
315
+ const inherited = launch.parentProviderRegistry
316
+ ? inheritParentProviders(modelRuntime, launch.parentProviderRegistry, queued.claimedProviderIds, launch.onExtensionError)
317
+ : false;
318
+ if (queued.registered || inherited) {
319
+ try {
320
+ await modelRuntime.refresh({ allowNetwork: false });
321
+ } catch (error) {
322
+ launch.onExtensionError?.({ extensionPath: "<provider-refresh>", event: "refresh_providers", error });
323
+ throw new Error(`Failed to refresh child providers: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
324
+ }
325
+ }
238
326
  const sessionManager = launch.storage.kind === "file"
239
327
  ? pi.SessionManager.open(launch.storage.sessionFile, undefined, launch.cwd)
240
328
  : launch.storage.kind === "dir"
@@ -259,6 +347,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
259
347
  settingsManager,
260
348
  sessionStartEvent: { type: "session_start", reason: "startup" },
261
349
  });
350
+ pinChildCacheRetention(session.agent);
262
351
  // Extensions captured module state from the launch env window
263
352
  // (registration and session_start); restore transient keys so an
264
353
  // in-process child cannot leak them into the host process.
@@ -284,7 +373,9 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
284
373
  const shutdown = async (): Promise<void> => {
285
374
  try {
286
375
  const runner = session.extensionRunner;
287
- if (runner.hasHandlers("session_shutdown")) await Promise.race([runner.emit({ type: "session_shutdown", reason: "quit" }), new Promise((resolve) => setTimeout(resolve, shutdownTimeoutMs).unref?.())]);
376
+ if (runner.hasHandlers("session_shutdown")) {
377
+ await Promise.race([runner.emit({ type: "session_shutdown", reason: "quit" }), new Promise<void>((resolve) => setTimeout(resolve, shutdownTimeoutMs).unref?.())]);
378
+ }
288
379
  } catch (error) {
289
380
  launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error });
290
381
  } finally {
@@ -297,6 +388,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
297
388
  steer: (text) => session.steer(text),
298
389
  followUp: (text) => session.followUp(text),
299
390
  abort: () => session.abort(),
391
+ hasQueuedMessages: () => session.agent?.hasQueuedMessages?.() === true,
300
392
  dispose: () => {
301
393
  if (!pending) {
302
394
  live.delete(child);
@@ -333,10 +425,24 @@ let activeFactoryModule: string | undefined;
333
425
 
334
426
  /** The process-wide factory foreground runs use unless a run passes its own. */
335
427
  export function childSessionFactory(): ChildSessionFactory {
336
- activeFactory ??= createDefaultChildSessionFactory();
428
+ activeFactory ??= createLazyPlacementFactory(createDefaultChildSessionFactory());
337
429
  return activeFactory;
338
430
  }
339
431
 
432
+ function createLazyPlacementFactory(local: ChildSessionFactory): ChildSessionFactory {
433
+ let placed: ChildSessionFactory | undefined;
434
+ const factory = async () => placed ??= (await import("./herdr-placed-run.ts")).createPlacementAwareChildSessionFactory(local);
435
+ return {
436
+ async create(launch) { return launch.machine ? (await factory()).create(launch) : local.create(launch); },
437
+ async dispose() { if (placed) await placed.dispose(); else await local.dispose(); },
438
+ };
439
+ }
440
+
441
+ /** Default factory including pane-native placement; detached runners use the same boundary. */
442
+ export function createPlacementChildSessionFactory(options: DefaultChildSessionFactoryOptions = {}): ChildSessionFactory {
443
+ return createLazyPlacementFactory(createDefaultChildSessionFactory(options));
444
+ }
445
+
340
446
  /**
341
447
  * Replace the process-wide factory. Tests install a scripted factory; passing
342
448
  * undefined restores the default on next use.
@@ -7,6 +7,7 @@ import { createHash } from "node:crypto";
7
7
  import * as fs from "node:fs";
8
8
  import * as path from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
11
  import {
11
12
  formatUnresolvedMcpDirectToolSelectors,
12
13
  resolveMcpDirectToolResolution,
@@ -16,13 +17,14 @@ import {
16
17
  import {
17
18
  TEMP_ROOT_DIR,
18
19
  type JsonSchemaObject,
19
- type LaunchResolvedChildExtensionsV1,
20
+ type LaunchResolvedChildExtensions,
20
21
  } from "../../shared/types.ts";
21
22
  import { THINKING_LEVELS } from "../../shared/model-info.ts";
22
23
  import { getAgentDir } from "../../shared/utils.ts";
23
24
  import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
24
25
  import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
25
26
  import type { PermissionRules } from "./permissions.ts";
27
+ import { snapshotRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
26
28
  import {
27
29
  capabilityCeilingAgentRestrictionSources,
28
30
  intersectSubagentCapabilityCeilings,
@@ -34,18 +36,18 @@ import {
34
36
  const MAX_LAUNCH_RESOLVED_EXTENSION_IDS = 32;
35
37
  const PROMPT_RUNTIME_EXTENSION_PATH = path.join(
36
38
  path.dirname(fileURLToPath(import.meta.url)),
37
- "subagent-prompt-runtime.ts",
39
+ `subagent-prompt-runtime${path.extname(fileURLToPath(import.meta.url))}`,
38
40
  );
39
41
  const FANOUT_CHILD_EXTENSION_PATH = path.join(
40
42
  path.dirname(fileURLToPath(import.meta.url)),
41
43
  "..",
42
44
  "..",
43
45
  "extension",
44
- "fanout-child.ts",
46
+ `fanout-child${path.extname(fileURLToPath(import.meta.url))}`,
45
47
  );
46
48
  const FAST_MODE_EXTENSION_PATH = path.join(
47
49
  path.dirname(fileURLToPath(import.meta.url)),
48
- "fast-mode-extension.ts",
50
+ `fast-mode-extension${path.extname(fileURLToPath(import.meta.url))}`,
49
51
  );
50
52
  const SANDBOX_PROFILE_GUARD_EXTENSION_PATH = path.join(
51
53
  path.dirname(fileURLToPath(import.meta.url)),
@@ -66,6 +68,39 @@ const FAST_MODE_ALLOWED_MODELS = new Set([
66
68
  "openai-codex/gpt-5.6-sol",
67
69
  ]);
68
70
  const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64;
71
+ const PI_BUILTIN_TOOL_NAMES = new Set(["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"]);
72
+ const REPOSITORY_INSPECTION_TOOLS = new Set(["read", "grep", "find", "ls", "bash", "powershell"]);
73
+ const REVIEW_OR_SCOUT_AGENT_PATTERN = /\b(?:reviewer|scout)\b/i;
74
+
75
+ export function isReviewOrScoutLaneAgent(agentName: string | undefined): boolean {
76
+ return typeof agentName === "string" && REVIEW_OR_SCOUT_AGENT_PATTERN.test(agentName);
77
+ }
78
+
79
+ export function missingPermittedRepositoryInspectionTools(
80
+ unavailableHostBuiltins: readonly string[],
81
+ excludeTools: readonly string[] = [],
82
+ ): string[] {
83
+ const excluded = new Set(excludeTools);
84
+ return unavailableHostBuiltins.filter((tool) => REPOSITORY_INSPECTION_TOOLS.has(tool) && !excluded.has(tool));
85
+ }
86
+
87
+ export function formatReviewLaneToolContractFailure(input: {
88
+ agentName?: string;
89
+ missingTools: readonly string[];
90
+ requestedTools?: readonly string[];
91
+ effectiveTools: readonly string[];
92
+ ceilingSources?: readonly string[];
93
+ excludeTools?: readonly string[];
94
+ }): string {
95
+ const subject = input.agentName ? `Agent '${input.agentName}'` : "Subagent";
96
+ return [
97
+ `${subject}: tool contract could not be satisfied; host runtime does not provide permitted required repository tools [${input.missingTools.join(", ")}].`,
98
+ `Requested tool names: ${input.requestedTools ? `[${input.requestedTools.join(", ")}]` : "not explicitly specified"}; effective tool allowlist: [${input.effectiveTools.join(", ")}].`,
99
+ ...(input.ceilingSources?.length ? [`Active capability ceiling sources: [${input.ceilingSources.join(", ")}].`] : []),
100
+ ...(input.excludeTools?.length ? [`Explicit excludeTools: [${input.excludeTools.join(", ")}].`] : []),
101
+ "This is a lane infrastructure failure, not a completed review/scout result.",
102
+ ].join(" ");
103
+ }
69
104
 
70
105
  export function deriveForkPromptCacheKey(parentSessionId: string | undefined): string | undefined {
71
106
  const parent = parentSessionId?.trim();
@@ -119,9 +154,9 @@ function stripThinkingSuffix(model: string): string {
119
154
  : model;
120
155
  }
121
156
 
122
- function resolveFastModeExtension(input: Pick<ResolvePiLaunchToolPlanInput, "fast" | "model" | "modelCandidates" | "agentName">): string[] {
157
+ function resolveFastModeExtension(input: Pick<ResolvePiLaunchToolPlanInput, "fast" | "model" | "agentName">): string[] {
123
158
  if (!input.fast) return [];
124
- const candidates = (input.modelCandidates?.length ? input.modelCandidates : input.model ? [input.model] : [])
159
+ const candidates = (input.model ? [input.model] : [])
125
160
  .map(stripThinkingSuffix);
126
161
  if (candidates.length === 0) {
127
162
  throw new Error(`fast mode requires an explicit supported native OpenAI-Codex model${input.agentName ? ` for agent '${input.agentName}'` : ""}.`);
@@ -139,6 +174,7 @@ export interface ResolvePiLaunchToolPlanInput {
139
174
  allowNestedSubagents?: boolean;
140
175
  extensions?: string[];
141
176
  subagentOnlyExtensions?: string[];
177
+ requiredExtensions?: RequiredChildExtensionSnapshot;
142
178
  mcpDirectTools?: string[];
143
179
  cwd?: string;
144
180
  requireReadTool?: boolean;
@@ -151,7 +187,6 @@ export interface ResolvePiLaunchToolPlanInput {
151
187
  };
152
188
  fast?: boolean;
153
189
  model?: string;
154
- modelCandidates?: readonly string[];
155
190
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
156
191
  inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
157
192
  agentName?: string;
@@ -161,7 +196,17 @@ export interface ResolvePiLaunchToolPlanInput {
161
196
  sandbox?: string;
162
197
  /** A validated global pi-permission-system profile selected by the agent definition. */
163
198
  permissionProfile?: string;
164
- }
199
+
200
+ /**
201
+ * When provided, child tool plans intersect known Pi core tool slots with
202
+ * this set. Core tools the agent declares but the host does not provide are
203
+ * omitted with a non-fatal warning (tracked in `unavailableHostBuiltins`).
204
+ * Review/scout lanes fail closed when a requested, still-permitted
205
+ * repository inspection tool is among those host omissions. Intentionally
206
+ * empty or ceiling-restricted allowlists are not a minimum-tool contract.
207
+ * Non-core names remain allowed and are validated in the child's registry.
208
+ */
209
+ hostAvailableBuiltins?: readonly string[];}
165
210
 
166
211
  export interface PiLaunchToolPlan {
167
212
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
@@ -181,11 +226,14 @@ export interface PiLaunchToolPlan {
181
226
  sandboxExtension?: string;
182
227
  runtimeExtensions: string[];
183
228
  configuredExtensions: string[];
229
+ requiredExtensions: RequiredChildExtensionSnapshot;
184
230
  extensionArgs: string[];
185
231
  disableAmbientExtensions: boolean;
186
232
  capabilityAudit?: SubagentCapabilityAudit;
187
233
  /** Non-fatal launch warnings; they do not change behavior. */
188
234
  warnings: string[];
235
+ /** Builtin tools the agent declared but the host runtime does not provide. */
236
+ unavailableHostBuiltins: string[];
189
237
  }
190
238
 
191
239
  function extensionIdentifier(value: string): string {
@@ -223,10 +271,11 @@ export function projectLaunchResolvedChildExtensions(
223
271
  PiLaunchToolPlan,
224
272
  | "runtimeExtensions"
225
273
  | "configuredExtensions"
274
+ | "requiredExtensions"
226
275
  | "extensionArgs"
227
276
  | "disableAmbientExtensions"
228
277
  >,
229
- ): LaunchResolvedChildExtensionsV1 {
278
+ ): LaunchResolvedChildExtensions {
230
279
  const runtime = boundedExtensionIdentifiers(toolPlan.runtimeExtensions);
231
280
  const configured = boundedExtensionIdentifiers(toolPlan.configuredExtensions);
232
281
  const effective = boundedExtensionIdentifiers(toolPlan.extensionArgs);
@@ -236,10 +285,12 @@ export function projectLaunchResolvedChildExtensions(
236
285
  disableAmbientExtensions: toolPlan.disableAmbientExtensions,
237
286
  runtime: runtime.ids,
238
287
  configured: configured.ids,
288
+ required: toolPlan.requiredExtensions.map(({ id }) => id),
239
289
  effective: effective.ids,
240
290
  omitted: {
241
291
  runtime: runtime.omitted,
242
292
  configured: configured.omitted,
293
+ required: 0,
243
294
  effective: effective.omitted,
244
295
  },
245
296
  };
@@ -377,6 +428,32 @@ function resolveSandboxExtension(): string {
377
428
  throw new Error(`No usable pi-sandbox extension manifest was found under '${agentDir}'.`);
378
429
  }
379
430
 
431
+ /**
432
+ * Extract the names of builtin tools the host provides. Use this to pass
433
+ * `hostAvailableBuiltins` to `resolvePiLaunchToolPlan` so child tool plans
434
+ * intersect known core slots with what the host actually supports. Wrapped
435
+ * core slots count regardless of source; host-specific builtins count too.
436
+ *
437
+ * Returns `undefined` when builtin tool discovery fails or yields nothing,
438
+ * so callers skip the intersection (fail-safe to allowing all declared tools).
439
+ * This handles test mocks without proper tool registration and hosts whose
440
+ * getAllTools() throws before extensions load.
441
+ */
442
+ export function getHostBuiltinToolNames(pi: Pick<ExtensionAPI, "getAllTools">): string[] | undefined {
443
+ try {
444
+ const builtins = pi
445
+ .getAllTools()
446
+ .filter((tool) => {
447
+ const source = (tool.sourceInfo as { source?: string } | undefined)?.source;
448
+ return source === "builtin" || PI_BUILTIN_TOOL_NAMES.has(tool.name);
449
+ })
450
+ .map((tool) => tool.name);
451
+ return builtins.length > 0 ? builtins : undefined;
452
+ } catch {
453
+ return undefined;
454
+ }
455
+ }
456
+
380
457
  export function resolvePiLaunchToolPlan(
381
458
  input: ResolvePiLaunchToolPlanInput,
382
459
  ): PiLaunchToolPlan {
@@ -384,21 +461,35 @@ export function resolvePiLaunchToolPlan(
384
461
  input.capabilityCeiling,
385
462
  input.inheritedCapabilityCeiling,
386
463
  );
464
+ const requiredExtensions = snapshotRequiredChildExtensions(input.requiredExtensions ?? []);
465
+ if (requiredExtensions.length > 0 && capabilityCeiling?.denyExtensions) {
466
+ throw new Error(`Capability ceiling from ${capabilityCeiling.sources.join(", ") || "unknown source"} denies extensions but this host requires: ${requiredExtensions.map(({ id }) => id).join(", ")}.`);
467
+ }
387
468
  const allowedToolSet =
388
469
  capabilityCeiling?.allowedTools === undefined
389
470
  ? undefined
390
471
  : new Set(capabilityCeiling.allowedTools);
472
+ const hostAvailableSet =
473
+ input.hostAvailableBuiltins === undefined
474
+ ? undefined
475
+ : new Set(input.hostAvailableBuiltins);
391
476
  const requestedBuiltinTools =
392
477
  input.tools?.filter(
393
478
  (tool) =>
394
479
  !(tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")),
395
480
  ) ?? [];
481
+ if (input.requireReadTool && hostAvailableSet && !hostAvailableSet.has("read")) {
482
+ const agentLabel = input.agentName ? ` for agent '${input.agentName}'` : "";
483
+ throw new Error(
484
+ `Host runtime does not provide required tool 'read'${agentLabel} for lazy skill loading.`,
485
+ );
486
+ }
396
487
  if (input.requireReadTool && allowedToolSet && !allowedToolSet.has("read")) {
397
488
  throw new Error(
398
489
  `Capability ceiling from ${capabilityCeiling?.sources.join(", ") || "unknown source"} excludes required tool 'read' for lazy skill loading.`,
399
490
  );
400
491
  }
401
- const declaredBuiltinTools =
492
+ const ceilingFilteredBuiltinTools =
402
493
  input.tools === undefined
403
494
  ? allowedToolSet
404
495
  ? [...allowedToolSet]
@@ -410,6 +501,12 @@ export function resolvePiLaunchToolPlan(
410
501
  ? ["read", ...requestedBuiltinTools]
411
502
  : requestedBuiltinTools
412
503
  ).filter((tool) => !allowedToolSet || allowedToolSet.has(tool));
504
+ const declaredBuiltinTools = hostAvailableSet
505
+ ? ceilingFilteredBuiltinTools.filter((tool) => !PI_BUILTIN_TOOL_NAMES.has(tool) || hostAvailableSet.has(tool))
506
+ : ceilingFilteredBuiltinTools;
507
+ const unavailableHostBuiltins = hostAvailableSet
508
+ ? ceilingFilteredBuiltinTools.filter((tool) => PI_BUILTIN_TOOL_NAMES.has(tool) && !hostAvailableSet.has(tool))
509
+ : [];
413
510
  const excludeTools = [...new Set((input.excludeTools ?? []).map((tool) => tool.trim()).filter(Boolean))];
414
511
  const excludedToolSet = new Set(excludeTools);
415
512
  const effectiveDeclaredBuiltinTools = declaredBuiltinTools.filter((tool) => !excludedToolSet.has(tool));
@@ -418,6 +515,9 @@ export function resolvePiLaunchToolPlan(
418
515
  !excludedToolSet.has("subagent") &&
419
516
  (!allowedToolSet || allowedToolSet.has("subagent"))
420
517
  );
518
+ if (effectiveDeclaredBuiltinTools.includes("subagent_supervisor") && !fanoutAuthorized) {
519
+ throw new Error("Tool 'subagent_supervisor' requires fanout authorization: include 'subagent' in the effective tools allowlist or enable allowNestedSubagents.");
520
+ }
421
521
  const toolExtensionPaths: string[] = capabilityCeiling?.denyExtensions
422
522
  ? []
423
523
  : (input.tools ?? []).filter(
@@ -458,8 +558,8 @@ export function resolvePiLaunchToolPlan(
458
558
  ...internalTools,
459
559
  ]),
460
560
  ];
461
- // Supervisor-coordination names stay in the --tools allowlist but are never
462
- // strict requirements: children register contact_supervisor at runtime through
561
+ // Upward contact stays in the --tools allowlist but is not a strict
562
+ // requirement: children register contact_supervisor at runtime through
463
563
  // the native supervisor channel (or pi-intercom). The pre-0.50 bridge always
464
564
  // appended intercom alongside contact_supervisor, so that exact pairing is
465
565
  // legacy plumbing, not a user demand for an external intercom provider;
@@ -513,7 +613,7 @@ export function resolvePiLaunchToolPlan(
513
613
  }
514
614
  }
515
615
  if (input.fast && capabilityCeiling?.denyExtensions) throw new Error("fast mode requires a child runtime extension, but this launch denies extensions.");
516
- const fastModeExtensions = resolveFastModeExtension({ fast: input.fast, model: input.model, modelCandidates: input.modelCandidates, agentName: input.agentName });
616
+ const fastModeExtensions = resolveFastModeExtension({ fast: input.fast, model: input.model, agentName: input.agentName });
517
617
  const runtimeExtensions = [
518
618
  PROMPT_RUNTIME_EXTENSION_PATH,
519
619
  ...fastModeExtensions,
@@ -541,7 +641,7 @@ export function resolvePiLaunchToolPlan(
541
641
  ...(input.extensions ?? []),
542
642
  ...(input.subagentOnlyExtensions ?? []),
543
643
  ];
544
- const extensionArgs = disableAmbientExtensions
644
+ const ordinaryExtensionArgs = disableAmbientExtensions
545
645
  ? [...new Set([...runtimeExtensions, ...configuredExtensions])]
546
646
  : [
547
647
  ...new Set([
@@ -550,6 +650,8 @@ export function resolvePiLaunchToolPlan(
550
650
  ...(input.subagentOnlyExtensions ?? []),
551
651
  ]),
552
652
  ];
653
+ // Host-required paths have final precedence and cannot be removed by agent defaults or overrides.
654
+ const extensionArgs = [...new Set([...ordinaryExtensionArgs, ...requiredExtensions.map(({ path }) => path)])];
553
655
  const requestedToolNames =
554
656
  input.tools !== undefined
555
657
  ? [
@@ -559,6 +661,32 @@ export function resolvePiLaunchToolPlan(
559
661
  ]),
560
662
  ]
561
663
  : undefined;
664
+ const missingPermittedRepositoryTools = input.tools !== undefined
665
+ ? missingPermittedRepositoryInspectionTools(unavailableHostBuiltins, excludeTools)
666
+ : [];
667
+ if (missingPermittedRepositoryTools.length > 0 && isReviewOrScoutLaneAgent(input.agentName)) {
668
+ throw new Error(formatReviewLaneToolContractFailure({
669
+ agentName: input.agentName,
670
+ missingTools: missingPermittedRepositoryTools,
671
+ requestedTools: requestedToolNames,
672
+ effectiveTools: effectiveToolAllowlist,
673
+ ceilingSources: capabilityCeiling?.sources,
674
+ excludeTools,
675
+ }));
676
+ }
677
+ // Host pruning also happens without a ceiling (and therefore without an
678
+ // audit). Use the existing non-fatal launch warnings rather than inventing
679
+ // a ceiling or treating the requested allowlist as a minimum requirement.
680
+ if (unavailableHostBuiltins.length > 0) {
681
+ const subject = input.agentName ? `Agent '${input.agentName}'` : "Subagent";
682
+ warnings.push(
683
+ `${subject}: host runtime tool availability omitted [${unavailableHostBuiltins.join(", ")}]. `
684
+ + `Requested tool names: ${requestedToolNames ? `[${requestedToolNames.join(", ")}]` : "not explicitly specified"}; effective tool allowlist: [${effectiveToolAllowlist.join(", ")}]. `
685
+ + (capabilityCeiling ? `Active capability ceiling sources: [${capabilityCeiling.sources.join(", ") || "unknown source"}]. ` : "")
686
+ + (excludeTools.length > 0 ? `Explicit excludeTools: [${excludeTools.join(", ")}]. ` : "")
687
+ + "This is a non-fatal tool-plan diagnostic, not verification of the child's runtime tool menu.",
688
+ );
689
+ }
562
690
  const capabilityAudit = capabilityCeiling
563
691
  ? ({
564
692
  ceiling: capabilityCeiling,
@@ -596,6 +724,7 @@ export function resolvePiLaunchToolPlan(
596
724
  capabilityCeilingAgentRestrictionSources(capabilityCeiling),
597
725
  }
598
726
  : {}),
727
+ ...(unavailableHostBuiltins.length > 0 ? { unavailableHostBuiltins } : {}),
599
728
  } satisfies SubagentCapabilityAudit)
600
729
  : undefined;
601
730
  return {
@@ -615,9 +744,11 @@ export function resolvePiLaunchToolPlan(
615
744
  ...(sandboxExtension ? { sandboxExtension } : {}),
616
745
  runtimeExtensions,
617
746
  configuredExtensions,
747
+ requiredExtensions,
618
748
  extensionArgs,
619
749
  disableAmbientExtensions,
620
750
  warnings,
751
+ unavailableHostBuiltins,
621
752
  ...(capabilityAudit ? { capabilityAudit } : {}),
622
753
  };
623
754
  }
@@ -26,7 +26,7 @@ export function planCompletionEvidence(input: {
26
26
  mutationAttemptObserved: boolean;
27
27
  mutationEvidence?: TrackedMutationEvidence;
28
28
  arbiterRescued?: boolean;
29
- agentContractV1: boolean;
29
+ agentContractEnabled: boolean;
30
30
  }): CompletionEvidencePlan {
31
31
  const guardBlocked = input.guard?.blocked === true;
32
32
  const guardTriggered = input.guardTriggered
@@ -59,7 +59,7 @@ export function planCompletionEvidence(input: {
59
59
  mutationExpected,
60
60
  mutationAttempted,
61
61
  fileMutation,
62
- legacyFailureError: guardTriggered && !input.agentContractV1
62
+ legacyFailureError: guardTriggered && !input.agentContractEnabled
63
63
  ? MISSING_IMPLEMENTATION_MUTATION_ERROR
64
64
  : undefined,
65
65
  };