@xzzpig/pi-subagents 0.14.0 → 0.15.1

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 (206) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +7 -6
  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 +55 -136
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -74
  9. package/docs/fork-extensions.md +184 -0
  10. package/docs/missions.md +10 -2
  11. package/docs/models.md +11 -22
  12. package/docs/observability.md +63 -11
  13. package/docs/standalone-background.md +59 -0
  14. package/docs/tool-reference.md +42 -23
  15. package/docs/watchdog.md +39 -10
  16. package/docs/workflows.md +58 -19
  17. package/index.ts +5 -2
  18. package/inspector-runner.mjs +2 -2
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  21. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  22. package/package.json +9 -4
  23. package/prompts/parallel-review.md +1 -1
  24. package/runner-peer-loader.mjs +24 -0
  25. package/runner-peer-preload.mjs +36 -0
  26. package/skills/pi-subagents/SKILL.md +34 -22
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  28. package/skills/pi-subagents/references/execution-controls.md +27 -8
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  32. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  33. package/src/agents/advertised-agent-prompt.ts +94 -0
  34. package/src/agents/agent-eject.ts +339 -0
  35. package/src/agents/agent-management.ts +79 -387
  36. package/src/agents/agent-serializer.ts +6 -3
  37. package/src/agents/agents.ts +198 -72
  38. package/src/agents/builtin-names.ts +1 -0
  39. package/src/agents/chain-serializer.ts +5 -0
  40. package/src/agents/runtime-agent-registry.ts +7 -6
  41. package/src/api/agent-management.ts +2 -2
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +131 -86
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +38 -35
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +770 -444
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +915 -411
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +49 -85
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +149 -112
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +27 -34
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/profile-extensions.ts +134 -0
  148. package/src/runs/shared/profile-launch-env.ts +113 -0
  149. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  150. package/src/runs/shared/run-fanout-budget.ts +8 -8
  151. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  152. package/src/runs/shared/sandbox-profile-guard.ts +34 -0
  153. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  154. package/src/runs/shared/task-intent.ts +46 -13
  155. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  156. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  157. package/src/runs/shared/worktree-setup-command.ts +213 -0
  158. package/src/runs/shared/worktree.ts +437 -214
  159. package/src/shared/child-cache-retention.ts +43 -0
  160. package/src/shared/fork-context.ts +15 -72
  161. package/src/shared/launch-contract.ts +70 -8
  162. package/src/shared/model-response-aliases.ts +13 -0
  163. package/src/shared/opencode-session-headers.ts +30 -0
  164. package/src/shared/permission-profile.ts +14 -0
  165. package/src/shared/pruned-fork.ts +1 -1
  166. package/src/shared/required-child-extensions.ts +81 -0
  167. package/src/shared/sandbox-profile.ts +14 -0
  168. package/src/shared/settings.ts +5 -2
  169. package/src/shared/shortcuts.ts +0 -4
  170. package/src/shared/types.ts +163 -90
  171. package/src/shared/utils.ts +10 -2
  172. package/src/shared/watch-strategy.ts +2 -0
  173. package/src/shared/workflow-child-permit.ts +18 -13
  174. package/src/slash/delegation-adapters.ts +3 -1
  175. package/src/slash/delegation-request.ts +14 -0
  176. package/src/slash/slash-commands.ts +2 -7
  177. package/src/slash/subagents-admin.ts +31 -14
  178. package/src/tui/fleet-status.ts +165 -20
  179. package/src/tui/fleet.ts +30 -19
  180. package/src/tui/render.ts +210 -50
  181. package/src/watchdog/child-status.ts +28 -28
  182. package/src/watchdog/lsp-diagnostics.ts +1 -1
  183. package/src/watchdog/model-selection.ts +21 -1
  184. package/src/watchdog/permission-arbiter.ts +5 -2
  185. package/src/watchdog/register-child.ts +10 -2
  186. package/src/watchdog/register-main.ts +39 -35
  187. package/src/watchdog/render.ts +1 -1
  188. package/src/watchdog/review.ts +122 -74
  189. package/src/watchdog/rules.ts +1 -1
  190. package/src/watchdog/runtime.ts +100 -27
  191. package/src/watchdog/scope.ts +1 -1
  192. package/src/watchdog/settings.ts +3 -0
  193. package/src/watchdog/tool-actions.ts +13 -12
  194. package/src/watchdog/turn-delta.ts +23 -0
  195. package/src/watchdog/types.ts +5 -3
  196. package/src/watchdog/warning-format.ts +1 -1
  197. package/src/workflows/chat-progress.ts +3 -3
  198. package/src/workflows/scripted-workflow.ts +349 -26
  199. package/src/workflows/workflow-checklist.ts +17 -20
  200. package/src/workflows/workflow-child-summary.ts +57 -8
  201. package/src/workflows/workflow-preflight.ts +19 -19
  202. package/src/workflows/workflow-receipt.ts +24 -6
  203. package/src/workflows/workflow-resources.ts +108 -22
  204. package/src/workflows/workflow-settlement.ts +3 -0
  205. package/src/runs/shared/model-exclusions.ts +0 -373
  206. /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.