@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
@@ -6,10 +6,10 @@ import { FLEET_KEYBINDING_ACTIONS, type ArtifactDirPreference, type ExtensionCon
6
6
  import { validateMissionStoreConfig } from "../missions/store.ts";
7
7
  import { validateAuthorityPolicy } from "../policy/authority.ts";
8
8
  import { getAgentDir } from "../shared/utils.ts";
9
- import { DEFAULT_MODEL_EXCLUSION_TTL_MS, MAX_MODEL_EXCLUSION_TTL_MS, setDefaultTTL } from "../runs/shared/model-exclusions.ts";
10
9
  import { validatePermissionConfig } from "../runs/shared/permissions.ts";
11
10
  import { MAX_ABANDONED_SLOT_RELEASE_AFTER_MS, MIN_ABANDONED_SLOT_RELEASE_AFTER_MS } from "../runs/background/active-async-capacity.ts";
12
11
  import { normalizeWorktreeBranchPrefix } from "../runs/shared/worktree.ts";
12
+ import { validateModelResponseAliases } from "../shared/model-response-aliases.ts";
13
13
 
14
14
  const ARTIFACT_DIR_PREFERENCES = new Set<ArtifactDirPreference>(["project", "session", "temp"]);
15
15
  const FLEET_KEYBINDING_ACTION_SET = new Set<string>(FLEET_KEYBINDING_ACTIONS);
@@ -96,17 +96,6 @@ function validateCapacityConfig(value: unknown): void {
96
96
  }
97
97
  }
98
98
 
99
- /** Validate the user-controlled TTL policy before it reaches the exclusion store. */
100
- // TEST:test/unit/pi-coding-agent-dir.test.ts[loads and applies model exclusion TTL config]
101
- function validateModelExclusionsConfig(value: unknown): void {
102
- if (value === undefined) return;
103
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.modelExclusions must be a JSON object");
104
- const defaultTtlMs = (value as Record<string, unknown>).defaultTtlMs;
105
- if (defaultTtlMs !== undefined && (typeof defaultTtlMs !== "number" || !Number.isFinite(defaultTtlMs) || defaultTtlMs <= 0 || defaultTtlMs > MAX_MODEL_EXCLUSION_TTL_MS)) {
106
- throw new Error(`config.modelExclusions.defaultTtlMs must be a finite positive number no greater than ${MAX_MODEL_EXCLUSION_TTL_MS}`);
107
- }
108
- }
109
-
110
99
  function validateOrcaProgressTabsConfig(value: unknown): void {
111
100
  if (value === undefined) return;
112
101
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.orcaProgressTabs must be a JSON object");
@@ -153,6 +142,13 @@ function validateConfig(config: Record<string, unknown>): void {
153
142
  throw new Error('config.defaultSubagentContext must be "fresh" or "fork"');
154
143
  }
155
144
  validateForkContextConfig(config.forkContext);
145
+ if (config.checkpointBeforeDeadlineMs !== undefined
146
+ && (typeof config.checkpointBeforeDeadlineMs !== "number"
147
+ || !Number.isInteger(config.checkpointBeforeDeadlineMs)
148
+ || config.checkpointBeforeDeadlineMs <= 0
149
+ || config.checkpointBeforeDeadlineMs > 2_147_483_647)) {
150
+ throw new Error("config.checkpointBeforeDeadlineMs must be a positive integer no larger than 2147483647");
151
+ }
156
152
  if (config.foregroundDetachShortcut !== undefined
157
153
  && (typeof config.foregroundDetachShortcut !== "string" || !isValidKeyId(config.foregroundDetachShortcut))) {
158
154
  throw new Error("config.foregroundDetachShortcut must be a valid keybinding string such as \"ctrl+b\"");
@@ -176,7 +172,8 @@ function validateConfig(config: Record<string, unknown>): void {
176
172
  validateFleetKeybindingsConfig(config.fleetKeybindings);
177
173
  validateArtifactConfig(config.artifactConfig);
178
174
  validateCapacityConfig(config.capacity);
179
- validateModelExclusionsConfig(config.modelExclusions);
175
+ if (config.modelExclusions !== undefined) throw new Error("config.modelExclusions was removed; model failures are no longer persisted or used for automatic switching");
176
+ validateModelResponseAliases(config.modelResponseAliases);
180
177
  validateMainWindowRendererConfig(config.mainWindowRenderer);
181
178
  validateOrcaProgressTabsConfig(config.orcaProgressTabs);
182
179
  }
@@ -187,6 +184,8 @@ export function getConfigPath(): string {
187
184
 
188
185
  function readConfigForUpdate(configPath = getConfigPath()): ExtensionConfig {
189
186
  if (!fs.existsSync(configPath)) return {};
187
+ // Upstream-original: config parse is guarded by the object check below, which throws a domain error.
188
+ // pi-lens-ignore: unchecked-throwing-call-js
190
189
  const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8")) as unknown;
191
190
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
192
191
  throw new Error(`Subagent config at '${configPath}' must be a JSON object`);
@@ -208,28 +207,6 @@ export function updateConfig(updater: (config: ExtensionConfig) => ExtensionConf
208
207
  return next;
209
208
  }
210
209
 
211
- /**
212
- * Resolve the default TTL that the process-wide exclusion store should use.
213
- *
214
- * @param config Extension configuration after validation.
215
- * @returns The configured TTL in milliseconds, or the built-in 24-hour default.
216
- */
217
- // TEST:test/unit/pi-coding-agent-dir.test.ts[loads and applies model exclusion TTL config]
218
- export function resolveModelExclusionTTL(config: Pick<ExtensionConfig, "modelExclusions">): number {
219
- return config.modelExclusions?.defaultTtlMs ?? DEFAULT_MODEL_EXCLUSION_TTL_MS;
220
- }
221
-
222
- /**
223
- * Apply the configured exclusion policy to the process-wide model store.
224
- *
225
- * @param config Extension configuration after validation.
226
- * @returns Nothing.
227
- */
228
- // TEST:test/unit/pi-coding-agent-dir.test.ts[loads and applies model exclusion TTL config]
229
- export function applyModelExclusionsConfig(config: Pick<ExtensionConfig, "modelExclusions">): void {
230
- setDefaultTTL(resolveModelExclusionTTL(config), { shortenExisting: config.modelExclusions?.defaultTtlMs !== undefined });
231
- }
232
-
233
210
  export function resolveAsyncByDefault(config: Pick<ExtensionConfig, "asyncByDefault">): boolean {
234
211
  return config.asyncByDefault !== false;
235
212
  }
@@ -240,12 +217,12 @@ export function loadConfig(): ExtensionConfig {
240
217
  return readConfigForUpdate(configPath);
241
218
  } catch (error) {
242
219
  if (error instanceof PrunedForkConfigError) throw error;
243
- // An explicitly requested worktree provider/prefix must not be silently
220
+ // Explicit route identity, worktree, and checkpoint policies must not be silently
244
221
  // discarded and replaced by the built-in defaults after validation fails.
245
222
  try {
246
223
  const raw = JSON.parse(fs.readFileSync(configPath, "utf-8")) as unknown;
247
224
  if (raw && typeof raw === "object" && !Array.isArray(raw)
248
- && (Object.hasOwn(raw, "worktreeProvider") || Object.hasOwn(raw, "worktreeBranchPrefix"))) throw error;
225
+ && (Object.hasOwn(raw, "worktreeProvider") || Object.hasOwn(raw, "worktreeBranchPrefix") || Object.hasOwn(raw, "modelResponseAliases") || Object.hasOwn(raw, "modelExclusions") || Object.hasOwn(raw, "checkpointBeforeDeadlineMs"))) throw error;
249
226
  } catch (readError) {
250
227
  if (readError === error) throw error;
251
228
  }
@@ -9,11 +9,13 @@ import { resolveWaitToolConfig } from "../runs/background/wait-config.ts";
9
9
  import type { ChildRuntimeConfig } from "../runs/shared/child-runtime-config.ts";
10
10
  import { readNestedControlRequests, resolveInheritedNestedRoute, type NestedRoute, writeNestedControlResult } from "../runs/shared/nested-events.ts";
11
11
  import { deliverSubagentIntercomMessageEvent } from "../intercom/result-intercom.ts";
12
+ import { createNativeSupervisorChannel, NATIVE_SUPERVISOR_TOOL_NAME, resolveSupervisorChannelDir } from "../intercom/native-supervisor-channel.ts";
13
+ import { readStatus } from "../shared/utils.ts";
12
14
  import { resolveSubagentIntercomTarget } from "../intercom/intercom-bridge.ts";
13
15
  import { createSubagentParamsSchema } from "./schemas.ts";
14
16
  import { finalizeToolResult } from "./tool-result.ts";
15
17
  import { loadConfig, resolveAsyncByDefault } from "./config.ts";
16
- import { type Details, type SubagentState } from "../shared/types.ts";
18
+ import { SUBAGENT_ASYNC_STARTED_EVENT, type AsyncStartedEvent, type Details, type SubagentState } from "../shared/types.ts";
17
19
 
18
20
  function getSubagentSessionRoot(parentSessionFile: string | null): string {
19
21
  if (parentSessionFile) {
@@ -28,7 +30,7 @@ function expandTilde(p: string): string {
28
30
  return p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
29
31
  }
30
32
 
31
- function createChildSafeState(): SubagentState {
33
+ export function createChildSafeState(): SubagentState {
32
34
  return {
33
35
  baseCwd: "",
34
36
  currentSessionId: null,
@@ -127,7 +129,8 @@ function startNestedControlInboxListener(pi: ExtensionAPI, state: SubagentState,
127
129
  }
128
130
  inboxState.pendingResults.delete(request.requestId);
129
131
  inboxState.seen.add(request.requestId);
130
- try { fs.unlinkSync(request.filePath); } catch {}
132
+ // Best-effort cleanup of an already-consumed request; the inbox loop tolerates a missing file.
133
+ try { fs.unlinkSync(request.filePath); } catch { /* tolerate a missing inbox file */ }
131
134
  } finally {
132
135
  inboxState.inFlight.delete(request.requestId);
133
136
  }
@@ -141,7 +144,7 @@ function startNestedControlInboxListener(pi: ExtensionAPI, state: SubagentState,
141
144
  return () => clearInterval(timer);
142
145
  }
143
146
 
144
- /** Register the child-side `subagent` tool for fanout-authorized children. */
147
+ /** Register delegation and supervisor replies for fanout-authorized children. */
145
148
  export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, childConfig: ChildRuntimeConfig): void {
146
149
  if (!childConfig.fanoutChild) return;
147
150
 
@@ -156,7 +159,40 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
156
159
 
157
160
  const config = loadConfig();
158
161
  const waitToolConfig = resolveWaitToolConfig(config.waitTool);
159
- const state = createChildSafeState();
162
+ const state = childConfig.runtimeState ?? createChildSafeState();
163
+ const asyncChildren = new Map<string, { dir: string; agents: string[] }>();
164
+ const foregroundChannels = new Set<string>();
165
+ const supervisorChannel = createNativeSupervisorChannel(pi, state, {
166
+ getChannelDirs: () => {
167
+ const dirs = new Set<string>();
168
+ for (const run of state.foregroundControls.values()) {
169
+ for (const child of run.activeChildren?.values() ?? []) dirs.add(resolveSupervisorChannelDir(run.runId, child.agent, child.index));
170
+ }
171
+ for (const run of state.foregroundRuns?.values() ?? []) {
172
+ for (const child of run.children) {
173
+ if (child.status === "detached") dirs.add(resolveSupervisorChannelDir(run.runId, child.agent, child.index));
174
+ }
175
+ }
176
+ const retiringForeground = [...foregroundChannels].filter(dir => !dirs.has(dir));
177
+ for (const dir of dirs) foregroundChannels.add(dir);
178
+ for (const dir of retiringForeground) dirs.add(dir);
179
+ const retiringAsync: string[] = [];
180
+ for (const [id, child] of asyncChildren) {
181
+ const status = readStatus(child.dir);
182
+ if (status && status.state !== "queued" && status.state !== "running") retiringAsync.push(id);
183
+ for (const [index, agent] of child.agents.entries()) dirs.add(resolveSupervisorChannelDir(id, agent, index));
184
+ }
185
+ return {
186
+ dirs: [...dirs],
187
+ retire: () => {
188
+ for (const dir of retiringForeground) foregroundChannels.delete(dir);
189
+ for (const id of retiringAsync) asyncChildren.delete(id);
190
+ },
191
+ };
192
+ },
193
+ });
194
+ const hasPendingSupervisorRequest = supervisorChannel.hasPendingRequests;
195
+ childConfig.hasPendingSupervisorRequest = hasPendingSupervisorRequest;
160
196
  const executor = createSubagentExecutor({
161
197
  pi,
162
198
  state,
@@ -170,6 +206,8 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
170
206
  discoverAgents,
171
207
  allowMutatingManagementActions: false,
172
208
  childRuntime: childConfig,
209
+ activateSupervisorTransport: supervisorChannel.activateTransport,
210
+ findPendingAsks: supervisorChannel.findPendingAsks,
173
211
  });
174
212
 
175
213
  const params = createSubagentParamsSchema();
@@ -188,6 +226,31 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
188
226
  };
189
227
 
190
228
  pi.registerTool(tool);
229
+ let unsubscribeAsyncStarted: (() => void) | undefined;
230
+ pi.on("session_start", (_event, ctx) => {
231
+ supervisorChannel.registerTools();
232
+ // The host applies the explicit allowlist to dynamic registration too.
233
+ if (!pi.getAllTools().some(tool => tool.name === NATIVE_SUPERVISOR_TOOL_NAME)) return;
234
+ // Downward asks belong to this coordinator, not its parent or persisted session file.
235
+ state.supervisorOwnerSessionId = ctx.sessionManager.getSessionId() || null;
236
+ unsubscribeAsyncStarted = pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, (payload: unknown) => {
237
+ const info = payload as AsyncStartedEvent;
238
+ if (!info.id || !info.asyncDir || info.sessionId !== state.currentSessionId) return;
239
+ const agents = info.agents ?? (info.agent ? [info.agent] : []);
240
+ asyncChildren.set(info.id, { dir: info.asyncDir, agents });
241
+ supervisorChannel.activateTransport();
242
+ });
243
+ supervisorChannel.start();
244
+ supervisorChannel.activateTransport();
245
+ });
246
+ pi.on("session_shutdown", () => {
247
+ unsubscribeAsyncStarted?.();
248
+ asyncChildren.clear();
249
+ foregroundChannels.clear();
250
+ supervisorChannel.dispose();
251
+ if (childConfig.hasPendingSupervisorRequest === hasPendingSupervisorRequest) childConfig.hasPendingSupervisorRequest = undefined;
252
+ state.supervisorOwnerSessionId = null;
253
+ });
191
254
  const route = resolveNestedControlRoute(childConfig);
192
255
  if (!route) return;
193
256
  const listenerCleanupKey = "__piSubagentFanoutChildNestedControlInboxCleanups";
@@ -0,0 +1,164 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as net from "node:net";
4
+ import * as path from "node:path";
5
+ import { Type } from "typebox";
6
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
7
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
+ import packageJson from "../../package.json" with { type: "json" };
9
+ import { encodeHerdrPiFrame, HERDR_PI_MAX_FRAME_BYTES, HERDR_PI_PROTOCOL, HERDR_PI_RUN_ENV, HERDR_PI_RUNTIME_DIR_ENV, HerdrPiFrameDecoder, validateHerdrPiRunId, type HerdrPiFrame } from "../runs/shared/herdr-pi-protocol.ts";
10
+ import { discoverAgents } from "../agents/agents.ts";
11
+ import { buildSkillInjection, resolveSkills } from "../agents/skills.ts";
12
+ import { buildAgentMemoryInjection } from "../agents/agent-memory.ts";
13
+ import { appendAgentRefinementOverlay } from "../agents/agent-refinements.ts";
14
+ import { rewriteSubagentPrompt } from "../runs/shared/subagent-prompt-runtime.ts";
15
+ import { resolveExistingReadPaths } from "../shared/settings.ts";
16
+
17
+ interface PendingRequest { operation: "prompt" | "steer" | "follow-up" | "abort" | "supervisor-reply"; text?: string; supervisorId?: string }
18
+ interface BridgeContext {
19
+ isIdle(): boolean;
20
+ hasPendingMessages(): boolean;
21
+ getActiveTools?(): string[];
22
+ sessionManager?: { getSessionId?(): string; getSessionFile?(): string | undefined };
23
+ model?: { provider?: string; id?: string };
24
+ }
25
+
26
+ function gitEvidence(cwd: string): Record<string, unknown> | undefined {
27
+ const run = (args: string[]) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 5_000, maxBuffer: 128 * 1024 });
28
+ const inside = run(["rev-parse", "--is-inside-work-tree"]);
29
+ if (inside.status !== 0) return undefined;
30
+ const head = run(["rev-parse", "HEAD"]); const branch = run(["symbolic-ref", "--quiet", "--short", "HEAD"]); const dirty = run(["status", "--porcelain"]);
31
+ return { ...(head.status === 0 ? { head: head.stdout.trim() } : {}), ...(branch.status === 0 ? { branch: branch.stdout.trim() } : {}), dirty: Boolean(dirty.stdout.trim()) };
32
+ }
33
+
34
+ export function resolveRemoteHerdrResources(cwd: string, resources: { agent: string; skills?: string[]; toolCeiling?: string[]; reads?: string[] | false }, remoteDefaultTools: string[] = []): { agent: string; skills: string[]; tools: string[]; systemPrompt: string; inheritProjectContext: boolean; inheritGlobalContext: boolean; inheritSkills: boolean } {
35
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(resources.agent) || resources.skills?.some((name) => !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(name)) || resources.toolCeiling?.some((name) => !/^[A-Za-z0-9_-]{1,64}$/u.test(name)) || (resources.reads !== undefined && resources.reads !== false && (!Array.isArray(resources.reads) || resources.reads.some((name) => typeof name !== "string")))) throw new Error("Remote logical resource names are invalid.");
36
+ const discovered = discoverAgents(cwd, "both").agents.filter((agent) => agent.name === resources.agent || agent.aliases?.includes(resources.agent));
37
+ if (discovered.length !== 1) throw new Error(`Remote agent '${resources.agent}' was not found unambiguously in ${cwd}.`);
38
+ const agent = discovered[0]!; const names = resources.skills ?? agent.skills ?? [];
39
+ const skills = resolveSkills(names, cwd); if (skills.missing.length) throw new Error(`Remote Pi skills not found: ${skills.missing.join(", ")}. Configure them on the saved machine.`);
40
+ const skillPrompt = buildSkillInjection(skills.resolved);
41
+ const reads = resources.reads === undefined ? agent.defaultReads ?? false : resources.reads; const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, cwd) : [];
42
+ const systemPrompt = appendAgentRefinementOverlay(`${agent.systemPrompt}${buildAgentMemoryInjection(agent, cwd)}${skillPrompt ? `\n\n${skillPrompt}` : ""}${readPaths.length ? `\n\n[Read from: ${readPaths.join(", ")}]` : ""}`, { cwd, agentName: agent.name });
43
+ const denied = new Set(agent.excludeTools ?? []); const tools = (agent.tools === undefined ? remoteDefaultTools : agent.tools).filter((tool) => !denied.has(tool) && (!resources.toolCeiling || resources.toolCeiling.includes(tool))); if (agent.tools === undefined && !tools.length) throw new Error(`Remote agent '${agent.name}' resolved no default active tools within the inherited ceiling.`);
44
+ return { agent: agent.name, skills: names, tools, systemPrompt, inheritProjectContext: agent.inheritProjectContext, inheritGlobalContext: agent.inheritGlobalContext, inheritSkills: agent.inheritSkills };
45
+ }
46
+
47
+ export default function registerHerdrPiBridge(pi: ExtensionAPI): void {
48
+ const runId = validateHerdrPiRunId(process.env[HERDR_PI_RUN_ENV]);
49
+ const runDir = process.env[HERDR_PI_RUNTIME_DIR_ENV];
50
+ if (!runDir || !path.isAbsolute(runDir) || fs.lstatSync(runDir).isSymbolicLink()) throw new Error("Herdr bridge runtime directory was not authoritatively provisioned.");
51
+ fs.chmodSync(runDir, 0o700);
52
+ const socketPath = path.join(runDir, "bridge.sock");
53
+ const manifestPath = path.join(runDir, "manifest.json");
54
+ for (const candidate of [socketPath, manifestPath]) {
55
+ try { const stat = fs.lstatSync(candidate); if (stat.isSymbolicLink()) throw new Error(`Refusing symlink at '${candidate}'.`); fs.rmSync(candidate, { force: true }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
56
+ }
57
+ let client: net.Socket | undefined;
58
+ let context: BridgeContext | undefined;
59
+ let nativeSessionId: string | undefined;
60
+ let finalAssistant: AgentMessage | undefined;
61
+ let activeRequestId: string | undefined;
62
+ let resolvedSystemPrompt: string | undefined;
63
+ let resolvedContextPolicy: { agent: string; inheritProjectContext: boolean; inheritGlobalContext: boolean; inheritSkills: boolean } | undefined;
64
+ let configured = false;
65
+ const pending = new Map<string, PendingRequest>();
66
+ const supervisor = new Map<string, { reason: "need_decision" | "interview_request" | "progress_update"; resolve(answer: string): void }>();
67
+ let evidenceCursor = 0; let journalBytes = 0; const journal: HerdrPiFrame[] = [];
68
+ const send = (frame: { type: string; [key: string]: unknown }) => {
69
+ const record = { protocol: HERDR_PI_PROTOCOL, runId, ...frame, cursor: ++evidenceCursor } as HerdrPiFrame; const size = Buffer.byteLength(JSON.stringify(record)); journal.push(record); journalBytes += size; while (journal.length > 512 || journalBytes > 8 * 1024 * 1024) { const removed = journal.shift(); if (removed) journalBytes -= Buffer.byteLength(JSON.stringify(removed)); }
70
+ if (!client || client.destroyed) return;
71
+ client.write(encodeHerdrPiFrame(record));
72
+ };
73
+ const sessionId = (ctx: BridgeContext) => ctx.sessionManager?.getSessionId?.();
74
+ const activeTools = (ctx: BridgeContext) => ctx.getActiveTools?.() ?? [];
75
+
76
+ pi.registerTool({
77
+ name: "contact_supervisor",
78
+ label: "Contact supervisor",
79
+ description: "Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",
80
+ parameters: Type.Object({ reason: Type.Union([Type.Literal("need_decision"), Type.Literal("interview_request"), Type.Literal("progress_update")]), message: Type.Optional(Type.String({ maxLength: 65_536 })), interview: Type.Optional(Type.Unknown()) }, { additionalProperties: false }),
81
+ execute: async (_toolCallId, input: { reason: "need_decision" | "interview_request" | "progress_update"; message?: string; interview?: unknown }) => {
82
+ if (input.reason !== "interview_request" && !input.message?.trim()) throw new Error("message is required for supervisor decisions and progress updates.");
83
+ const id = `sup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
84
+ send({ type: "supervisor-request", requestId: id, reason: input.reason, message: input.message?.slice(0, 65_536) ?? "", ...(input.interview !== undefined ? { interview: input.interview } : {}), expectsReply: input.reason !== "progress_update", nativeSessionId });
85
+ if (input.reason === "progress_update") { await new Promise<string>((resolve) => supervisor.set(id, { reason: input.reason, resolve })); return { content: [{ type: "text", text: "Supervisor progress update queued." }], details: { delivered: true, requestId: id, reason: input.reason } }; }
86
+ const reason = input.reason as "need_decision" | "interview_request"; const answer = await new Promise<string>((resolve) => supervisor.set(id, { reason, resolve })); const details: Record<string, unknown> = { requestId: id, reason }; if (reason === "interview_request") try { details.structuredReply = JSON.parse(answer.replace(/^```(?:json)?\s*|\s*```$/giu, "")); } catch { details.structuredReplyParseError = "Supervisor interview reply was not valid JSON."; }
87
+ return { content: [{ type: "text", text: `**Reply from supervisor:**\n${answer}` }], details };
88
+ },
89
+ });
90
+
91
+ const execute = async (requestId: string, ctx: BridgeContext) => {
92
+ const request = pending.get(requestId);
93
+ if (!request) throw new Error(`Unknown or already consumed bridge request '${requestId}'.`);
94
+ pending.delete(requestId);
95
+ if (sessionId(ctx) !== nativeSessionId) throw new Error("Native Pi session identity changed.");
96
+ send({ type: "accepted", requestId, operation: request.operation, nativeSessionId });
97
+ // SAFETY: pi exposes sendUserMessage/abort on the live host API; narrowed to the two methods this bridge drives.
98
+ const api = pi as unknown as { sendUserMessage(text: string, options?: { deliverAs?: "steer" | "followUp" }): void; abort(): void };
99
+ if (request.operation === "prompt") { activeRequestId = requestId; finalAssistant = undefined; api.sendUserMessage(request.text ?? ""); }
100
+ else if (request.operation === "steer") api.sendUserMessage(request.text ?? "", { deliverAs: "steer" });
101
+ else if (request.operation === "follow-up") api.sendUserMessage(request.text ?? "", { deliverAs: "followUp" });
102
+ else if (request.operation === "abort") api.abort();
103
+ else {
104
+ const entry = request.supervisorId ? supervisor.get(request.supervisorId) : undefined;
105
+ if (!entry) throw new Error("Unknown supervisor request.");
106
+ supervisor.delete(request.supervisorId!); entry.resolve(request.text ?? "");
107
+ }
108
+ send({ type: "control-ack", requestId, operation: request.operation, nativeSessionId });
109
+ };
110
+ // SAFETY: BridgeContext is the same ctx object pi passes to command handlers; the cast only drops the generic wrapper.
111
+ pi.registerCommand("pi-subagents-bridge", { description: "Internal pane-native request dispatch", handler: (args, ctx) => execute(args.trim(), ctx as unknown as BridgeContext) });
112
+
113
+ // SAFETY: pi.on is a typed event emitter; the cast widens it to the dynamic handler signature this bridge registers.
114
+ const on = pi.on as unknown as (name: string, handler: (event: Record<string, unknown>, ctx: BridgeContext) => unknown) => void;
115
+ on("before_agent_start", (event) => resolvedSystemPrompt && resolvedContextPolicy ? { systemPrompt: `${rewriteSubagentPrompt(typeof event.systemPrompt === "string" ? event.systemPrompt : "", { inheritProjectContext: resolvedContextPolicy.inheritProjectContext, inheritGlobalContext: resolvedContextPolicy.inheritGlobalContext, inheritSkills: resolvedContextPolicy.inheritSkills })}\n\n<active_agent name=${JSON.stringify(resolvedContextPolicy.agent)}/>\n\n${resolvedSystemPrompt}` } : undefined);
116
+ on("session_start", (_event, ctx) => {
117
+ context = ctx; nativeSessionId = sessionId(ctx);
118
+ if (!nativeSessionId) throw new Error("Pane-native Pi bridge requires a persisted native session identity.");
119
+ fs.writeFileSync(manifestPath, JSON.stringify({ protocol: HERDR_PI_PROTOCOL, packageVersion: packageJson.version, runId, socketPath, nativeSessionId, pid: process.pid }), { mode: 0o600, flag: "wx" });
120
+ send({ type: "ready", packageVersion: packageJson.version, nativeSessionId, sessionFile: ctx.sessionManager?.getSessionFile?.(), cwd: process.cwd(), tools: activeTools(ctx), model: ctx.model?.provider && ctx.model.id ? `${ctx.model.provider}/${ctx.model.id}` : undefined, configured, activeRequestId, evidenceCursor, evidenceFloor: journal[0]?.cursor ?? evidenceCursor + 1, initialGit: gitEvidence(process.cwd()) });
121
+ });
122
+ on("message_end", (event) => {
123
+ const message = event.message as AgentMessage | undefined;
124
+ if (message?.role === "assistant") finalAssistant = message;
125
+ send({ type: "event", requestId: activeRequestId, event: { ...event, message }, nativeSessionId });
126
+ });
127
+ on("agent_settled", (_event, ctx) => { const requestId = activeRequestId; send({ type: "settled", requestId, nativeSessionId, idle: ctx.isIdle(), pending: ctx.hasPendingMessages(), finalAssistant, finalGit: gitEvidence(process.cwd()) }); if (ctx.isIdle() && !ctx.hasPendingMessages()) activeRequestId = undefined; });
128
+ on("session_shutdown", () => { server.close(); client?.destroy(); try { fs.rmSync(runDir, { recursive: true, force: true }); } catch { /* Best-effort; the run dir may already be gone. */ } });
129
+
130
+ const server = net.createServer((socket) => {
131
+ if (client && !client.destroyed) { socket.destroy(); return; }
132
+ client = socket; const decoder = new HerdrPiFrameDecoder(); let total = 0;
133
+ for (const record of journal) socket.write(encodeHerdrPiFrame(record));
134
+ socket.on("data", (chunk: Buffer) => {
135
+ total += chunk.byteLength; if (total > HERDR_PI_MAX_FRAME_BYTES * 32) { socket.destroy(new Error("Bridge byte budget exceeded.")); return; }
136
+ try {
137
+ for (const frame of decoder.push(chunk)) {
138
+ if (frame.runId !== runId) throw new Error("Bridge run identity mismatch.");
139
+ if (frame.type === "supervisor-delivered" && typeof frame.requestId === "string") { const entry = supervisor.get(frame.requestId); if (!entry || entry.reason !== "progress_update") throw new Error("Unknown supervisor delivery acknowledgement."); supervisor.delete(frame.requestId); entry.resolve("delivered"); continue; }
140
+ if (frame.type === "configure") {
141
+ if (configured || typeof frame.requestId !== "string" || !frame.resources || typeof frame.resources !== "object") throw new Error("Invalid or duplicate bridge configuration.");
142
+ const resources = frame.resources as { agent?: unknown; skills?: unknown; toolCeiling?: unknown; reads?: unknown };
143
+ const invalidSkills = resources.skills !== undefined && (!Array.isArray(resources.skills) || resources.skills.some((name) => typeof name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(name)));
144
+ const invalidReads = resources.reads !== undefined && resources.reads !== false && (!Array.isArray(resources.reads) || resources.reads.some((name) => typeof name !== "string"));
145
+ if (typeof resources.agent !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(resources.agent) || invalidSkills || invalidReads) throw new Error("Remote logical resource names are invalid.");
146
+ const resolved = resolveRemoteHerdrResources(process.cwd(), { agent: resources.agent, ...(resources.skills ? { skills: resources.skills as string[] } : {}), ...(resources.toolCeiling ? { toolCeiling: resources.toolCeiling as string[] } : {}), ...(resources.reads !== undefined ? { reads: resources.reads as string[] | false } : {}) }, context ? activeTools(context) : []); resolvedSystemPrompt = resolved.systemPrompt; resolvedContextPolicy = resolved;
147
+ // SAFETY: setActiveTools is optional on the host API; presence-checked with ?. before use.
148
+ (pi as unknown as { setActiveTools?(tools: string[]): void }).setActiveTools?.(resolved.tools); const acknowledged = context ? activeTools(context) : []; if (acknowledged.some((tool) => !resolved.tools.includes(tool)) || resolved.tools.some((tool) => !acknowledged.includes(tool))) throw new Error("Remote Pi did not apply the resolved active-tool set exactly.");
149
+ configured = true; send({ type: "configured", requestId: frame.requestId, nativeSessionId, agent: resolved.agent, skills: resolved.skills, model: context?.model?.provider && context.model.id ? `${context.model.provider}/${context.model.id}` : undefined, tools: acknowledged }); continue;
150
+ }
151
+ if (frame.type !== "prepare" || typeof frame.requestId !== "string" || pending.has(frame.requestId) || !configured) throw new Error("Invalid, duplicate, or unconfigured bridge request.");
152
+ const operation = frame.operation;
153
+ if (!(["prompt", "steer", "follow-up", "abort", "supervisor-reply"] as unknown[]).includes(operation)) throw new Error("Unsupported bridge operation.");
154
+ const text = frame.text; if (text !== undefined && (typeof text !== "string" || Buffer.byteLength(text) > 256 * 1024)) throw new Error("Bridge request text is invalid or too large.");
155
+ pending.set(frame.requestId, { operation: operation as PendingRequest["operation"], ...(text !== undefined ? { text } : {}), ...(typeof frame.supervisorId === "string" ? { supervisorId: frame.supervisorId } : {}) });
156
+ send({ type: "prepared", requestId: frame.requestId, nativeSessionId });
157
+ }
158
+ } catch (error) { socket.destroy(error as Error); }
159
+ });
160
+ socket.on("close", () => { if (client === socket) client = undefined; });
161
+ if (context && nativeSessionId) send({ type: "ready", packageVersion: packageJson.version, nativeSessionId, sessionFile: context.sessionManager?.getSessionFile?.(), cwd: process.cwd(), tools: activeTools(context), model: context.model?.provider && context.model.id ? `${context.model.provider}/${context.model.id}` : undefined, configured, activeRequestId, evidenceCursor, evidenceFloor: journal[0]?.cursor ?? evidenceCursor + 1, initialGit: gitEvidence(process.cwd()) });
162
+ });
163
+ server.listen(socketPath, () => { fs.chmodSync(socketPath, 0o600); });
164
+ }