@xzzpig/pi-subagents 0.13.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 (202) hide show
  1. package/CHANGELOG.md +243 -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 +93 -15
  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 +67 -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/CHANGELOG.md +19 -0
  19. package/node_modules/@xzzpig/pi-components/README.md +28 -0
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +46 -4
  21. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +65 -17
  22. package/node_modules/@xzzpig/pi-components/package.json +1 -1
  23. package/node_modules/@xzzpig/pi-components/src/transcript.ts +107 -14
  24. package/package.json +10 -5
  25. package/prompts/parallel-review.md +1 -1
  26. package/runner-peer-loader.mjs +24 -0
  27. package/runner-peer-preload.mjs +36 -0
  28. package/skills/pi-subagents/SKILL.md +34 -22
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  30. package/skills/pi-subagents/references/execution-controls.md +27 -8
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  33. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  34. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  35. package/src/agents/advertised-agent-prompt.ts +94 -0
  36. package/src/agents/agent-management.ts +71 -59
  37. package/src/agents/agent-serializer.ts +6 -3
  38. package/src/agents/agents.ts +198 -72
  39. package/src/agents/builtin-names.ts +1 -0
  40. package/src/agents/chain-serializer.ts +5 -0
  41. package/src/agents/runtime-agent-registry.ts +7 -6
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +110 -71
  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 +32 -13
  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 +766 -432
  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 +896 -397
  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 +44 -16
  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 +145 -14
  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 +19 -10
  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/readonly-drain-observation.ts +42 -0
  148. package/src/runs/shared/run-fanout-budget.ts +8 -8
  149. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  150. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  151. package/src/runs/shared/task-intent.ts +46 -13
  152. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  153. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  154. package/src/runs/shared/worktree-setup-command.ts +213 -0
  155. package/src/runs/shared/worktree.ts +437 -214
  156. package/src/shared/child-cache-retention.ts +43 -0
  157. package/src/shared/fork-context.ts +15 -72
  158. package/src/shared/launch-contract.ts +70 -8
  159. package/src/shared/model-response-aliases.ts +13 -0
  160. package/src/shared/opencode-session-headers.ts +30 -0
  161. package/src/shared/pruned-fork.ts +1 -1
  162. package/src/shared/required-child-extensions.ts +81 -0
  163. package/src/shared/settings.ts +5 -2
  164. package/src/shared/shortcuts.ts +0 -4
  165. package/src/shared/types.ts +164 -90
  166. package/src/shared/utils.ts +10 -2
  167. package/src/shared/watch-strategy.ts +2 -0
  168. package/src/shared/workflow-child-permit.ts +18 -13
  169. package/src/slash/delegation-adapters.ts +3 -1
  170. package/src/slash/delegation-request.ts +14 -0
  171. package/src/slash/slash-commands.ts +2 -7
  172. package/src/slash/subagents-admin.ts +31 -14
  173. package/src/tui/fleet-native-transcript.ts +50 -6
  174. package/src/tui/fleet-status.ts +165 -20
  175. package/src/tui/fleet.ts +52 -21
  176. package/src/tui/render.ts +210 -50
  177. package/src/watchdog/child-status.ts +28 -28
  178. package/src/watchdog/lsp-diagnostics.ts +1 -1
  179. package/src/watchdog/model-selection.ts +21 -1
  180. package/src/watchdog/permission-arbiter.ts +5 -2
  181. package/src/watchdog/register-child.ts +10 -2
  182. package/src/watchdog/register-main.ts +39 -35
  183. package/src/watchdog/render.ts +1 -1
  184. package/src/watchdog/review.ts +122 -74
  185. package/src/watchdog/rules.ts +1 -1
  186. package/src/watchdog/runtime.ts +100 -27
  187. package/src/watchdog/scope.ts +1 -1
  188. package/src/watchdog/settings.ts +3 -0
  189. package/src/watchdog/tool-actions.ts +13 -12
  190. package/src/watchdog/turn-delta.ts +23 -0
  191. package/src/watchdog/types.ts +5 -3
  192. package/src/watchdog/warning-format.ts +1 -1
  193. package/src/workflows/chat-progress.ts +3 -3
  194. package/src/workflows/scripted-workflow.ts +349 -26
  195. package/src/workflows/workflow-checklist.ts +17 -20
  196. package/src/workflows/workflow-child-summary.ts +57 -8
  197. package/src/workflows/workflow-preflight.ts +19 -19
  198. package/src/workflows/workflow-receipt.ts +24 -6
  199. package/src/workflows/workflow-resources.ts +108 -22
  200. package/src/workflows/workflow-settlement.ts +3 -0
  201. package/src/runs/shared/model-exclusions.ts +0 -373
  202. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -0,0 +1,263 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as net from "node:net";
4
+ import * as path from "node:path";
5
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
6
+ import packageJson from "../../../package.json" with { type: "json" };
7
+ import type { HerdrMachineReference, HerdrRemoteGitStatus } from "../../shared/types.ts";
8
+ import type { ChildSession, ChildSessionEvent, ChildSessionFactory, ChildSessionLaunch } from "./child-session.ts";
9
+ import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
10
+ import { connectHerdrMachine, remoteShellCommand, runHerdrRemoteCommand, runHerdrRemoteCommandAsync, type HerdrForwardedConnection, type HerdrRpcClient } from "./herdr-connection.ts";
11
+ import { encodeHerdrPiFrame, HERDR_PI_MODE_ENV, HERDR_PI_PROTOCOL, HERDR_PI_RUN_ENV, HERDR_PI_RUNTIME_DIR_ENV, HerdrPiFrameDecoder, validateHerdrPiRunId, type HerdrPiFrame } from "./herdr-pi-protocol.ts";
12
+ import { getAgentDir } from "../../shared/utils.ts";
13
+
14
+ export interface HerdrRunIdentity { runId: string; machineId: string; target: string; session: string | null; workspaceId: string; tabId: string; paneId: string; terminalId: string; agentName: string; nativeSessionId: string; cwd: string; runtimeDir: string }
15
+ export interface HerdrRunSnapshot { connection: "connected" | "unknown" | "closed"; state: "ready" | "working" | "blocked" | "settled" | "unknown"; identity?: HerdrRunIdentity; revision: number }
16
+ export interface HerdrReconnectCandidate { endpoint: { session: string | null; protocol: number; version: string }; agents: Array<{ terminal_id?: string; pane_id?: string; agent_status?: string }>; bridge: { runId?: string; nativeSessionId?: string; packageVersion?: string; protocol?: number; evidenceCursor?: number; evidenceFloor?: number } }
17
+
18
+ function herdrRunState(status: unknown, fallback: HerdrRunSnapshot["state"] = "unknown"): HerdrRunSnapshot["state"] {
19
+ return status === "working" ? "working" : status === "blocked" ? "blocked" : status === "idle" || status === "done" ? "settled" : status === "unknown" ? "unknown" : fallback;
20
+ }
21
+
22
+ export function herdrStatusSubscriptions(paneId: string): unknown[] {
23
+ return [{ type: "pane.agent_status_changed", pane_id: paneId }, { type: "pane.closed" }, { type: "pane.moved" }];
24
+ }
25
+
26
+ export function reconcileHerdrPlacedRun(identity: HerdrRunIdentity, candidate: HerdrReconnectCandidate, proveEvidence: () => { ok: true; cursor: number } | { ok: false; reason: string }): { ok: true; state: HerdrRunSnapshot["state"]; paneId: string; cursor: number } | { ok: false; reason: string } {
27
+ if (candidate.endpoint.session !== identity.session) return { ok: false, reason: "Herdr session changed during reconnect." }; const matches = candidate.agents.filter((agent) => agent.terminal_id === identity.terminalId); if (matches.length !== 1 || typeof matches[0]!.pane_id !== "string") return { ok: false, reason: matches.length ? "Terminal identity is ambiguous." : "Owned terminal is missing." }; const proof = proveEvidence(); if (!proof.ok) return proof; return { ok: true, state: herdrRunState(matches[0]!.agent_status), paneId: matches[0]!.pane_id!, cursor: proof.cursor };
28
+ }
29
+
30
+ export function reconcileHerdrReconnect(identity: HerdrRunIdentity, candidate: HerdrReconnectCandidate, lastEvidenceCursor: number): { ok: true; state: HerdrRunSnapshot["state"]; paneId: string; cursor: number } | { ok: false; reason: string } {
31
+ return reconcileHerdrPlacedRun(identity, candidate, () => { const bridge = candidate.bridge; if (bridge.runId !== identity.runId || bridge.nativeSessionId !== identity.nativeSessionId || bridge.packageVersion !== packageJson.version || bridge.protocol !== HERDR_PI_PROTOCOL) return { ok: false, reason: "Bridge run, package, protocol, or native session identity changed." }; if (typeof bridge.evidenceCursor !== "number" || typeof bridge.evidenceFloor !== "number" || bridge.evidenceCursor < lastEvidenceCursor || bridge.evidenceFloor > lastEvidenceCursor + 1) return { ok: false, reason: "Bridge evidence has a gap after reconnect." }; return { ok: true, cursor: bridge.evidenceCursor }; });
32
+ }
33
+
34
+ export async function boundedHerdrReconnect(identity: HerdrRunIdentity, lastEvidenceCursor: number, attempt: (number: number) => Promise<HerdrReconnectCandidate>, options: { attempts?: number; deadlineMs?: number; disposed?: () => boolean } = {}) {
35
+ const deadline = Date.now() + (options.deadlineMs ?? 15_000); let last = "Reconnect did not run.";
36
+ for (let number = 1; number <= (options.attempts ?? 3) && Date.now() < deadline; number++) {
37
+ if (options.disposed?.()) return { ok: false as const, reason: "Reconnect was disposed." };
38
+ try { const result = reconcileHerdrReconnect(identity, await attempt(number), lastEvidenceCursor); if (result.ok) return result; last = result.reason; } catch (error) { last = error instanceof Error ? error.message : String(error); }
39
+ await new Promise((resolve) => setTimeout(resolve, Math.min(number * 100, Math.max(0, deadline - Date.now()))));
40
+ }
41
+ return { ok: false as const, reason: last };
42
+ }
43
+
44
+ function safeRunId(value: string | undefined): string { const prefix = value?.replace(/[^A-Za-z0-9_-]/gu, "_").slice(0, 48) ?? "run"; return validateHerdrPiRunId(`${prefix}_${randomBytes(8).toString("hex")}`); }
45
+ function idOf(value: unknown, key: string): string { const found = value && typeof value === "object" ? (value as Record<string, unknown>)[key] : undefined; if (typeof found !== "string" || !found) throw new Error(`Herdr did not return ${key}.`); return found; }
46
+ function list(value: unknown, key: string): unknown[] { if (Array.isArray(value)) return value; const found = value && typeof value === "object" ? (value as Record<string, unknown>)[key] : undefined; return Array.isArray(found) ? found : []; }
47
+ function tagged(value: unknown, type: string, key: string): Record<string, unknown> { if (!value || typeof value !== "object" || (value as Record<string, unknown>).type !== type || !(key in (value as Record<string, unknown>)) || typeof (value as Record<string, unknown>)[key] !== "object") throw new Error(`Herdr returned an invalid ${type} envelope.`); return (value as Record<string, Record<string, unknown>>)[key]!; }
48
+ export function parseHerdrCreated(value: unknown, type: "workspace_created" | "tab_created"): { workspaceId?: string; tabId: string; paneId: string } { const envelope = value as Record<string, unknown>; if (envelope?.type !== type) throw new Error(`Herdr returned an invalid ${type} envelope.`); const tab = envelope.tab as Record<string, unknown>; const pane = envelope.root_pane as Record<string, unknown>; return { ...(type === "workspace_created" ? { workspaceId: idOf(envelope.workspace, "workspace_id") } : {}), tabId: idOf(tab, "tab_id"), paneId: idOf(pane, "pane_id") }; }
49
+ export function parseHerdrAgent(value: unknown, type: "agent_started" | "agent_info" | "agent_prompted") { return tagged(value, type, "agent"); }
50
+ export function parseHerdrSessionSnapshot(value: unknown): Record<string, unknown> { return tagged(value, "session_snapshot", "snapshot"); }
51
+ export function ownsHerdrPane(agent: Record<string, unknown>, terminalId: string, paneId: string): boolean { return agent.terminal_id === terminalId && agent.pane_id === paneId; }
52
+ function snapshotAgents(snapshot: Record<string, unknown>): Array<{ terminal_id?: string; pane_id?: string; agent_status?: string }> { return list(snapshot, "agents").filter((agent): agent is Record<string, unknown> => Boolean(agent && typeof agent === "object")).map((agent) => ({ terminal_id: typeof agent.terminal_id === "string" ? agent.terminal_id : undefined, pane_id: typeof agent.pane_id === "string" ? agent.pane_id : undefined, agent_status: typeof agent.agent_status === "string" ? agent.agent_status : undefined })); }
53
+
54
+ export const HERDR_MAX_OWNED_PANES = 20;
55
+ const HERDR_ALLOCATION_LOCK_TIMEOUT_MS = 10_000, HERDR_ALLOCATION_LOCK_POLL_MS = 25;
56
+ export function herdrPaneAllocationKey(target: string, session: string | null, cwd: string): string { return JSON.stringify([target, session, cwd]); }
57
+ function assertPrivateDir(directory: string): void { const stat = fs.lstatSync(directory); if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o777) !== 0o700 || (typeof process.getuid === "function" && stat.uid !== process.getuid())) throw new Error("Herdr allocation path is not a mode-0700 agent-private owned directory."); }
58
+ function ensurePrivateChild(parent: string, name: string): string { const directory = path.join(parent, name); try { fs.mkdirSync(directory, { mode: 0o700 }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; } assertPrivateDir(directory); return directory; }
59
+ function allocationLockRoot(): string { const agentDir = getAgentDir(); fs.mkdirSync(agentDir, { recursive: true, mode: 0o700 }); assertPrivateDir(agentDir); const packageDir = ensurePrivateChild(agentDir, "pi-subagents"); return ensurePrivateChild(packageDir, "herdr-allocation-locks"); }
60
+ function livePid(pid: number): boolean { try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; } }
61
+ interface AllocationOwner { pid: number; token: string; dev: number; ino: number }
62
+ function readAllocationOwner(ownerPath: string): AllocationOwner { const descriptor = fs.openSync(ownerPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0)); try { const stat = fs.fstatSync(descriptor); if (!stat.isFile() || (stat.mode & 0o777) !== 0o600 || (typeof process.getuid === "function" && stat.uid !== process.getuid())) throw new Error("Herdr allocation lock owner record is unsafe."); const value = JSON.parse(fs.readFileSync(descriptor, "utf8")) as { pid?: unknown; token?: unknown }; if (typeof value.pid !== "number" || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.token !== "string" || !/^[a-f0-9]{32}$/u.test(value.token)) throw new Error("Herdr allocation lock owner record is malformed."); return { pid: value.pid, token: value.token, dev: stat.dev, ino: stat.ino }; } finally { fs.closeSync(descriptor); } }
63
+ function sameOwner(left: AllocationOwner, right: AllocationOwner): boolean { return left.token === right.token && left.dev === right.dev && left.ino === right.ino; }
64
+ export async function withHerdrPaneAllocationLock<T>(key: string, action: () => Promise<T>, options: { timeoutMs?: number; pollMs?: number } = {}): Promise<T> {
65
+ const root = allocationLockRoot(), digest = createHash("sha256").update(key).digest("hex"), lockPath = path.join(root, `${digest}.lock`), recoveryPath = path.join(root, `${digest}.recovery`), token = randomBytes(16).toString("hex"), tempPath = path.join(root, `.${digest}.${token}.tmp`), deadline = Date.now() + (options.timeoutMs ?? HERDR_ALLOCATION_LOCK_TIMEOUT_MS); let published: AllocationOwner | undefined;
66
+ try {
67
+ fs.writeFileSync(tempPath, JSON.stringify({ pid: process.pid, token, createdAt: Date.now() }), { mode: 0o600, flag: "wx" }); const tempOwner = readAllocationOwner(tempPath);
68
+ for (;;) {
69
+ let recovering = false; try { readAllocationOwner(recoveryPath); recovering = true; } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
70
+ if (!recovering) {
71
+ let linked = false;
72
+ try {
73
+ fs.linkSync(tempPath, lockPath); linked = true;
74
+ try { readAllocationOwner(recoveryPath); const current = readAllocationOwner(lockPath); if (!sameOwner(current, tempOwner)) throw new Error("Herdr allocation lock changed during publication."); fs.unlinkSync(lockPath); }
75
+ catch (recoveryError) { if ((recoveryError as NodeJS.ErrnoException).code !== "ENOENT") throw recoveryError; published = readAllocationOwner(lockPath); if (!sameOwner(published, tempOwner)) throw new Error("Herdr allocation lock publication identity changed."); break; }
76
+ } catch (publishError) { if (linked) { try { const current = readAllocationOwner(lockPath); if (sameOwner(current, tempOwner)) fs.unlinkSync(lockPath); } catch {} } if ((publishError as NodeJS.ErrnoException).code !== "EEXIST" && (publishError as NodeJS.ErrnoException).code !== "ENOENT") throw publishError; }
77
+ }
78
+ if (published) break;
79
+ try { const current = readAllocationOwner(lockPath); if (!livePid(current.pid)) { let claimed = false; try { fs.linkSync(lockPath, recoveryPath); claimed = true; const recovery = readAllocationOwner(recoveryPath), latest = readAllocationOwner(lockPath); if (!sameOwner(recovery, current) || !sameOwner(latest, current)) throw new Error("Herdr stale lock identity changed during recovery."); fs.unlinkSync(lockPath); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST" && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } finally { if (claimed) fs.unlinkSync(recoveryPath); } if (claimed) continue; } } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
80
+ if (Date.now() >= deadline) throw new Error("Timed out waiting for the Herdr pane allocation lock."); await new Promise((resolve) => setTimeout(resolve, options.pollMs ?? HERDR_ALLOCATION_LOCK_POLL_MS));
81
+ }
82
+ fs.unlinkSync(tempPath);
83
+ let value: T | undefined, actionError: unknown, releaseError: unknown, actionFailed = false, releaseFailed = false; try { value = await action(); } catch (error) { actionFailed = true; actionError = error; }
84
+ try { const current = readAllocationOwner(lockPath); if (!published || !sameOwner(current, published)) throw new Error("Herdr pane allocation lock ownership changed before release."); fs.unlinkSync(lockPath); } catch (error) { releaseFailed = true; releaseError = error; }
85
+ if (actionFailed && releaseFailed) throw new AggregateError([actionError, releaseError], "Herdr pane allocation action and release both failed.", { cause: actionError }); if (actionFailed) throw actionError; if (releaseFailed) throw releaseError; return value as T;
86
+ } finally { try { fs.unlinkSync(tempPath); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } }
87
+ }
88
+
89
+ export function serializeHerdrPiLaunch(launch: ChildSessionLaunch): { args: string[]; resources: { agent: string; skills?: string[]; toolCeiling?: string[]; reads?: string[] | false } } {
90
+ if (launch.storage.kind === "file") throw new Error("Pane-native remote Pi does not support fork, resume, or revival; use fresh context.");
91
+ if (launch.extensionPaths.length || launch.requiredExtensions?.length) throw new Error("Pane-native remote Pi cannot transfer local extension paths; install/configure pi-subagents on the remote machine.");
92
+ if (launch.processEnv && Object.values(launch.processEnv).some((value) => value !== undefined && value !== "__none__")) throw new Error("Pane-native remote Pi cannot transfer local bindings, MCP selections, or process environment.");
93
+ if (launch.runtime.nestedRoute || launch.runtime.fanoutChild || launch.runtime.depth > 1) throw new Error("Nested delegation from a pane-native remote Pi is not supported.");
94
+ if (launch.excludeTools?.length || launch.runtime.permissions || launch.runtime.toolBudget || launch.runtime.requiredExtensions || launch.runtime.requiredTools?.length || launch.runtime.mcpDirectTools?.length) throw new Error("Pane-native remote Pi cannot yet represent exclusions, permission rules, tool budgets, MCP direct tools, or required-tool/extension contracts; remove machine placement.");
95
+ const resources = launch.remoteResources;
96
+ if (!resources || !/^[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 && resources.reads.some((read) => typeof read !== "string" || Buffer.byteLength(read) > 4096))) throw new Error("Pane-native remote resources require bounded logical agent, skill, tool, and read names.");
97
+ const args: string[] = [];
98
+ if (launch.noSkills) args.push("--no-skills", "--no-prompt-templates");
99
+ if (launch.noContextFiles) args.push("--no-context-files");
100
+ if (launch.model) args.push("--model", launch.model);
101
+ return { args, resources: { agent: resources.agent, ...(resources.skills ? { skills: [...resources.skills] } : {}), ...(resources.toolCeiling ? { toolCeiling: [...resources.toolCeiling] } : {}), ...(resources.reads !== undefined ? { reads: resources.reads === false ? false : [...resources.reads] } : {}) } };
102
+ }
103
+
104
+ export async function provisionHerdrPane(client: HerdrRpcClient, cwd: string, runId: string, runtimeDir: string, environment?: Record<string, string>, allocationKey = cwd): Promise<{ workspaceId: string; tabId: string; paneId: string }> {
105
+ return withHerdrPaneAllocationLock(allocationKey, async () => {
106
+ const snapshot = parseHerdrSessionSnapshot(await client.call("session.snapshot")); const panes = list(snapshot, "panes").filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")), workspaces = list(snapshot, "workspaces").filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"));
107
+ const ownedLabel = `pi-subagents-${createHash("sha256").update(cwd).digest("hex").slice(0, 10)}`, owned = workspaces.filter((item) => item.label === ownedLabel); if (owned.length > 1) throw new Error("Herdr deterministic owned workspace identity is ambiguous.");
108
+ const cwdWorkspaceIds = new Set(panes.filter((item) => item.cwd === cwd || item.foreground_cwd === cwd).map((item) => item.workspace_id).filter((id): id is string => typeof id === "string")), cwdWorkspaces = workspaces.filter((item) => typeof item.workspace_id === "string" && cwdWorkspaceIds.has(item.workspace_id));
109
+ const selected = owned[0] ?? (cwdWorkspaces.length === 1 ? cwdWorkspaces[0] : undefined), selectedId = selected ? idOf(selected, "workspace_id") : undefined, actual = selectedId ? panes.filter((pane) => pane.workspace_id === selectedId).length : 0;
110
+ if (actual >= HERDR_MAX_OWNED_PANES) throw new Error(`Herdr workspace pane limit of ${HERDR_MAX_OWNED_PANES} is reached; close an existing pane before launching another placed run.`);
111
+ const env = environment ?? { [HERDR_PI_MODE_ENV]: "1", [HERDR_PI_RUN_ENV]: runId, [HERDR_PI_RUNTIME_DIR_ENV]: runtimeDir };
112
+ if (selectedId) { const tab = parseHerdrCreated(await client.call("tab.create", { workspace_id: selectedId, cwd, label: `subagent-${runId.slice(-8)}`, env, focus: false }), "tab_created"); return { workspaceId: selectedId, tabId: tab.tabId, paneId: tab.paneId }; }
113
+ const workspace = parseHerdrCreated(await client.call("workspace.create", { cwd, label: ownedLabel, env, focus: false }), "workspace_created"); return { workspaceId: workspace.workspaceId!, tabId: workspace.tabId, paneId: workspace.paneId };
114
+ });
115
+ }
116
+
117
+
118
+ export async function discoverBridgeManifest(machine: HerdrMachineReference, runId: string, runtimeDir: string, options: { sshBin?: string; env?: NodeJS.ProcessEnv } = {}): Promise<{ socketPath: string; nativeSessionId: string; packageVersion: string; protocol: number }> {
119
+ const script = `p="$1/manifest.json"; test -f "$p" && test ! -L "$p" && cat "$p"`;
120
+ for (let attempt = 0; attempt < 100; attempt++) {
121
+ const result = await runHerdrRemoteCommandAsync(machine, remoteShellCommand(script, [runtimeDir]), { ...options, timeout: 5_000, maxBuffer: 64 * 1024 });
122
+ if (result.error) throw new Error(`Remote bridge manifest discovery failed: ${result.error.message}`, { cause: result.error });
123
+ if (result.status === 0 && result.stdout.trim()) {
124
+ let value: unknown; try { value = JSON.parse(result.stdout) as unknown; } catch { throw new Error("Remote bridge manifest is malformed."); }
125
+ const p = value as Record<string, unknown>;
126
+ if (p.runId !== runId || typeof p.socketPath !== "string" || path.posix.dirname(p.socketPath) !== runtimeDir || typeof p.nativeSessionId !== "string" || typeof p.packageVersion !== "string" || typeof p.protocol !== "number") throw new Error("Remote bridge manifest identity is incomplete or outside its owned runtime directory.");
127
+ return p as unknown as { socketPath: string; nativeSessionId: string; packageVersion: string; protocol: number };
128
+ }
129
+ await new Promise((resolve) => setTimeout(resolve, 50));
130
+ }
131
+ throw new Error("The remote Pi did not expose the packaged pi-subagents bridge. Install/configure the same package version as an ambient Pi extension on the saved machine.");
132
+ }
133
+
134
+ export async function createRemoteRuntimeDir(machine: HerdrMachineReference, runId: string, options: { sshBin?: string; env?: NodeJS.ProcessEnv } = {}): Promise<string> { const result = await runHerdrRemoteCommandAsync(machine, remoteShellCommand("umask 077; mktemp -d \"${TMPDIR:-/tmp}/pi-subagents-herdr-$1-XXXXXXXX\"", [runId]), { ...options, timeout: 10_000, maxBuffer: 4096 }); if (result.error) throw new Error(`Could not provision a run-private remote bridge runtime directory: ${result.error.message}`, { cause: result.error }); const value = result.stdout.trim(); if (result.status !== 0 || !path.posix.isAbsolute(value) || value.includes("\n")) throw new Error("Could not provision a run-private remote bridge runtime directory."); return value; }
135
+ export function removeRemoteRuntimeDir(machine: HerdrMachineReference, runtimeDir: string, options: { sshBin?: string; env?: NodeJS.ProcessEnv } = {}): void { const result = runHerdrRemoteCommand(machine, remoteShellCommand("p=$1; case \"${p##*/}\" in pi-subagents-herdr-*) test -d \"$p\" && test ! -L \"$p\" && rm -rf -- \"$p\";; *) exit 64;; esac", [runtimeDir]), { ...options, timeout: 10_000, maxBuffer: 4096 }); if (result.status !== 0 || result.stdout) throw new Error(`Could not remove the exact owned remote runtime directory: ${String(result.stderr).slice(0, 512)}`); }
136
+
137
+ /** The single private owner for allocation shared by every pane-native backend projection. */
138
+ export class HerdrPlacedRunOwner {
139
+ readonly machine: HerdrMachineReference; readonly runId: string; readonly runtimeDir: string; connection: HerdrForwardedConnection;
140
+ owned?: { workspaceId: string; tabId: string; paneId: string }; terminalId?: string; agentName?: string; startedArgv?: string[]; identity?: HerdrRunIdentity; #unsubscribe = () => {}; #snapshot: HerdrRunSnapshot = { connection: "connected", state: "ready", revision: 0 }; #cleanupPromise?: Promise<void>; readonly #removeRuntime: () => void;
141
+ private constructor(machine: HerdrMachineReference, runId: string, runtimeDir: string, connection: HerdrForwardedConnection, removeRuntime: () => void = () => removeRemoteRuntimeDir(machine, runtimeDir)) { this.machine = machine; this.runId = runId; this.runtimeDir = runtimeDir; this.connection = connection; this.#removeRuntime = removeRuntime; }
142
+ static async create(machine: HerdrMachineReference, runId: string, beforePane?: (owner: HerdrPlacedRunOwner) => void | Promise<void>): Promise<HerdrPlacedRunOwner> { const runtimeDir = await createRemoteRuntimeDir(machine, runId); let connection: HerdrForwardedConnection | undefined; try { connection = await connectHerdrMachine(machine); const owner = new HerdrPlacedRunOwner(machine, runId, runtimeDir, connection); await beforePane?.(owner); return owner; } catch (error) { const cleanupErrors: unknown[] = []; try { await connection?.close(); } catch (cleanupError) { cleanupErrors.push(cleanupError); } try { removeRemoteRuntimeDir(machine, runtimeDir); } catch (cleanupError) { cleanupErrors.push(cleanupError); } if (cleanupErrors.length) throw new AggregateError([error, ...cleanupErrors], "Herdr owner creation failed and cleanup also failed.", { cause: error }); throw error; } }
143
+ observeEvent(event: unknown): void { const data = event && typeof event === "object" ? (event as { data?: Record<string, unknown> }).data : undefined; if (data && (!this.terminalId || data.terminal_id === this.terminalId || data.pane_id === this.owned?.paneId)) this.#snapshot = { ...this.#snapshot, revision: this.#snapshot.revision + 1, state: herdrRunState(data.agent_status, this.#snapshot.state) }; }
144
+ markConnectionUnknown(observed: HerdrForwardedConnection): boolean { if (this.connection !== observed) return false; this.#snapshot = { ...this.#snapshot, connection: "unknown", state: "unknown", revision: this.#snapshot.revision + 1 }; return true; }
145
+ statusSubscriptions(paneId = this.owned?.paneId): unknown[] { if (!paneId) throw new Error("Herdr status subscription requires a provisioned pane."); return herdrStatusSubscriptions(paneId); }
146
+ async subscribe(listener: (event: unknown) => void, disconnected: (error: Error) => void): Promise<void> { const observed = this.connection; let adopted = false, candidateLost: Error | undefined; const unsubscribe = await observed.client.subscribe(this.statusSubscriptions(), (event) => { this.observeEvent(event); listener(event); }, (error) => { if (!adopted) { candidateLost ??= error; return; } if (!this.markConnectionUnknown(observed)) return; disconnected(error); }); if (candidateLost) { unsubscribe(); throw candidateLost; } this.#unsubscribe = unsubscribe; adopted = true; }
147
+ async provision(environment?: Record<string, string>): Promise<{ workspaceId: string; tabId: string; paneId: string }> { this.owned = await provisionHerdrPane(this.connection.client, this.machine.cwd, this.runId, this.runtimeDir, environment, herdrPaneAllocationKey(this.machine.target, this.connection.endpoint.session, this.machine.cwd)); return this.owned; }
148
+ async start(kind: "pi" | "claude" | "cursor" | "codex", name: string, args: string[], options: { timeoutMs?: number; pollMs?: number; clock?: { now(): number; wait(ms: number): Promise<void> } } = {}): Promise<{ terminalId: string; paneId: string; argv: string[] }> {
149
+ if (!this.owned) throw new Error("Herdr placement owner has not provisioned its pane."); const clock = options.clock ?? { now: () => Date.now(), wait: (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)) }, deadline = clock.now() + (options.timeoutMs ?? 5_000), pollMs = options.pollMs ?? 50;
150
+ let response: unknown;
151
+ for (;;) {
152
+ try { response = await this.connection.client.call("agent.start", { name, kind, pane_id: this.owned.paneId, args, timeout_ms: 45_000 }, 60_000); break; }
153
+ catch (error) {
154
+ if (!(error instanceof Error) || !error.message.includes("is not an available shell")) throw error;
155
+ const pane = tagged(await this.connection.client.call("pane.get", { pane_id: this.owned.paneId }), "pane_info", "pane"); if (pane.pane_id !== this.owned.paneId || pane.workspace_id !== this.owned.workspaceId || pane.tab_id !== this.owned.tabId) throw new Error("Herdr startup pane identity changed after a transient start rejection.", { cause: error }); if (pane.agent != null || pane.agent_session != null) throw new Error("Herdr startup pane became occupied after a transient start rejection.", { cause: error }); if (clock.now() >= deadline) throw new Error("Herdr owned pane remained unavailable until the startup deadline.", { cause: error }); await clock.wait(Math.min(pollMs, deadline - clock.now()));
156
+ }
157
+ }
158
+ const started = parseHerdrAgent(response, "agent_started"), argv = [kind, ...args], terminalId = idOf(started, "terminal_id"), paneId = idOf(started, "pane_id"); if (paneId !== this.owned.paneId) throw new Error("Herdr started the native agent in an unexpected pane."); this.agentName = name; this.terminalId = terminalId; this.startedArgv = argv; return { terminalId, paneId, argv };
159
+ }
160
+ journal(identity: HerdrRunIdentity): void { this.identity = identity; this.#snapshot = { ...this.#snapshot, identity }; const journalDir = path.join(getAgentDir(), "pi-subagents", "herdr-run-journal"); fs.mkdirSync(journalDir, { recursive: true, mode: 0o700 }); fs.writeFileSync(path.join(journalDir, `${this.runId}.json`), JSON.stringify({ version: 1, identity, state: "ready", updatedAt: Date.now() }), { mode: 0o600, flag: "wx" }); }
161
+ get snapshot(): HerdrRunSnapshot { return this.#snapshot; }
162
+ runRemote(command: string, options: { timeout?: number; maxBuffer?: number } = {}) { return runHerdrRemoteCommand(this.machine, command, options); }
163
+ async replaceConnection(input: { connection: HerdrForwardedConnection; unsubscribe: () => void; paneId: string; state: HerdrRunSnapshot["state"] }): Promise<void> { const oldConnection = this.connection, oldUnsubscribe = this.#unsubscribe; this.connection = input.connection; this.#unsubscribe = input.unsubscribe; if (this.identity) this.identity = { ...this.identity, paneId: input.paneId }; this.#snapshot = { connection: "connected", state: input.state, identity: this.identity, revision: this.#snapshot.revision + 1 }; oldUnsubscribe(); await oldConnection.close(); }
164
+ cleanup(closeStartedPane = true): Promise<void> { return this.#cleanupPromise ??= this.#performCleanup(closeStartedPane); }
165
+ async #performCleanup(closeStartedPane: boolean): Promise<void> { let failure: unknown; try { if (closeStartedPane && this.owned) { let closed = false; if (this.terminalId && this.agentName) { const current = parseHerdrAgent(await this.connection.client.call<Record<string, unknown>>("agent.get", { target: this.agentName }), "agent_info"); if (ownsHerdrPane(current, this.terminalId, this.owned.paneId)) { await this.connection.client.call("pane.close", { pane_id: this.owned.paneId }); closed = true; } } if (!closed) { const snapshot = parseHerdrSessionSnapshot(await this.connection.client.call<Record<string, unknown>>("session.snapshot")); const occupants = snapshotAgents(snapshot).filter((agent) => agent.pane_id === this.owned!.paneId); if (occupants.length !== 0) throw new Error("Refusing cleanup because startup pane ownership is uncertain."); await this.connection.client.call("pane.close", { pane_id: this.owned.paneId }); } } } catch (error) { failure = error; } try { this.#unsubscribe(); await this.connection.close(); this.#removeRuntime(); } catch (error) { failure ??= error; } this.#snapshot = { ...this.#snapshot, connection: "closed", revision: this.#snapshot.revision + 1 }; if (failure) throw failure; }
166
+ }
167
+
168
+ export class BridgeChannel {
169
+ readonly socket: net.Socket; readonly decoder = new HerdrPiFrameDecoder(); readonly listeners = new Set<(frame: HerdrPiFrame) => void>(); readonly waiters = new Map<string, { resolve(frame: HerdrPiFrame): void; reject(error: Error): void }>(); readonly runId: string; readonly frames: HerdrPiFrame[] = [];
170
+ readonly failure: Promise<never>; #rejectFailure!: (error: Error) => void; #failed = false;
171
+ constructor(socketPath: string, runId: string) { this.runId = runId; this.failure = new Promise<never>((_resolve, reject) => { this.#rejectFailure = reject; }); this.failure.catch(() => {}); this.socket = net.createConnection(socketPath); this.socket.on("data", (chunk: Buffer) => { try { for (const frame of this.decoder.push(chunk)) { if (frame.runId !== runId) throw new Error("Bridge run identity mismatch."); this.frames.push(frame); if (this.frames.length > 1024) throw new Error("Bridge replay queue exceeded its bound."); const key = typeof frame.requestId === "string" ? `${frame.type}:${frame.requestId}` : ""; const waiter = this.waiters.get(key); if (waiter) { this.waiters.delete(key); waiter.resolve(frame); } for (const listener of this.listeners) listener(frame); } } catch (error) { this.fail(error as Error); } }); this.socket.on("error", (error) => this.fail(error)); this.socket.on("close", () => { if (!this.#failed) this.fail(new Error("Remote Pi bridge connection was lost; task state is unknown.")); }); }
172
+ fail(error: Error) { if (this.#failed) return; this.#failed = true; this.#rejectFailure(error); for (const waiter of this.waiters.values()) waiter.reject(error); this.waiters.clear(); }
173
+ get failed() { return this.#failed; }
174
+ wait(type: string, requestId: string): Promise<HerdrPiFrame> { return new Promise((resolve, reject) => this.waiters.set(`${type}:${requestId}`, { resolve, reject })); }
175
+ configure(resources: { agent: string; skills?: string[]; toolCeiling?: string[]; reads?: string[] | false }) { const requestId = `cfg_${randomBytes(6).toString("hex")}`; const waiting = this.wait("configured", requestId); this.socket.write(encodeHerdrPiFrame({ protocol: HERDR_PI_PROTOCOL, runId: this.runId, type: "configure", requestId, resources })); return waiting; }
176
+ supervisorDelivered(requestId: string) { this.socket.write(encodeHerdrPiFrame({ protocol: HERDR_PI_PROTOCOL, runId: this.runId, type: "supervisor-delivered", requestId })); }
177
+ prepare(requestId: string, operation: string, text?: string, supervisorId?: string) { const waiting = this.wait("prepared", requestId); this.socket.write(encodeHerdrPiFrame({ protocol: HERDR_PI_PROTOCOL, runId: this.runId, type: "prepare", requestId, operation, ...(text !== undefined ? { text } : {}), ...(supervisorId ? { supervisorId } : {}) })); return waiting; }
178
+ close() { this.socket.destroy(); }
179
+ }
180
+
181
+ function waitForReadyBridgeFrame(bridge: BridgeChannel, timeoutMs: number, timeoutMessage: string, configured = false): Promise<HerdrPiFrame> {
182
+ return new Promise((resolve, reject) => {
183
+ const timer = setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs);
184
+ const listener = (frame: HerdrPiFrame) => {
185
+ if (frame.type !== "ready" || configured && frame.configured !== true) return;
186
+ clearTimeout(timer);
187
+ bridge.listeners.delete(listener);
188
+ resolve(frame);
189
+ };
190
+ bridge.listeners.add(listener);
191
+ });
192
+ }
193
+
194
+ export class HerdrPiSession implements ChildSession {
195
+ readonly #listeners = new Set<(event: ChildSessionEvent) => void>(); #messages: AgentMessage[] = []; #sequence = 0; #disposed = false; #aborted = false; #initialGit?: HerdrRemoteGitStatus; #finalGit?: HerdrRemoteGitStatus;
196
+ readonly #operations = new Map<string, { resolve(): void; reject(error: Error): void; accepted: boolean; settled: boolean }>();
197
+ #snapshot: HerdrRunSnapshot; bridgeForward: { close(): Promise<void> }; bridge: BridgeChannel; readonly requestedTools: string[] | undefined; readonly model: string | undefined; #evidenceCursor = 0; #reconnecting?: Promise<void>; #reconnectFactory?: () => Promise<void>; #reconnectFailure?: Error;
198
+ #replyTimer?: NodeJS.Timeout; readonly supervisorDir: string | undefined; readonly runtime: ChildRuntimeConfig; readonly owner: HerdrPlacedRunOwner;
199
+ constructor(owner: HerdrPlacedRunOwner, bridgeForward: { close(): Promise<void> }, bridge: BridgeChannel, requestedTools: string[] | undefined, model: string | undefined, runtime: ChildRuntimeConfig, initialGit?: HerdrRemoteGitStatus) { this.owner = owner; this.bridgeForward = bridgeForward; this.bridge = bridge; this.requestedTools = requestedTools; this.model = model; this.runtime = runtime; this.supervisorDir = runtime.supervisorChannelDir; this.#snapshot = { connection: "connected", state: "ready", identity: owner.identity, revision: 0 }; this.#initialGit = initialGit; bridge.listeners.add((frame) => this.#frame(frame)); if (this.supervisorDir) { this.#replyTimer = setInterval(() => { const replies = path.join(this.supervisorDir!, "replies"); for (const name of fs.existsSync(replies) ? fs.readdirSync(replies) : []) { const file = path.join(replies, name); try { const value = JSON.parse(fs.readFileSync(file, "utf8")) as { message?: unknown; requestId?: unknown }; if (typeof value.message === "string" && typeof value.requestId === "string") void this.#operation("supervisor-reply", value.message, value.requestId).then(() => fs.rmSync(file, { force: true })); } catch {} } }, 50); this.#replyTimer.unref?.(); } }
200
+ get identity(): HerdrRunIdentity { return this.owner.identity!; } set identity(value: HerdrRunIdentity) { this.owner.identity = value; }
201
+ get connection(): HerdrForwardedConnection { return this.owner.connection; } set connection(value: HerdrForwardedConnection) { this.owner.connection = value; }
202
+ armReconnect(factory: () => Promise<void>) { this.#reconnectFactory = factory; const observed = this.bridge; observed.failure.catch(() => { if (this.bridge === observed) void this.reconnect(); }); }
203
+ get evidenceCursor() { return this.#evidenceCursor; }
204
+ async reconnect() { if (this.#disposed || !this.#reconnectFactory || this.#reconnectFailure) return; this.#snapshot = { ...this.#snapshot, connection: "unknown", state: "unknown", revision: this.#snapshot.revision + 1 }; this.#reconnecting ??= this.#reconnectFactory().catch((error) => { const unknown = this.#reconnectFailure = new Error(`Remote Pi reconciliation failed; task state is unknown: ${error instanceof Error ? error.message : String(error)}`); for (const operation of this.#operations.values()) if (!operation.settled) { operation.settled = true; operation.reject(unknown); } }).finally(() => { this.#reconnecting = undefined; }); await this.#reconnecting; }
205
+ async replaceTransport(input: { connection: HerdrForwardedConnection; bridgeForward: { close(): Promise<void> }; bridge: BridgeChannel; unsubscribe: () => void; paneId: string; cursor: number; state: HerdrRunSnapshot["state"] }) { if (this.#disposed) { input.unsubscribe(); input.bridge.close(); await input.bridgeForward.close(); await input.connection.close(); return; } const old = { bridgeForward: this.bridgeForward, bridge: this.bridge }; this.bridgeForward = input.bridgeForward; this.bridge = input.bridge; this.identity = { ...this.identity, paneId: input.paneId }; this.#reconnectFailure = undefined; for (const frame of input.bridge.frames) if (typeof frame.cursor === "number" && frame.cursor > this.#evidenceCursor) this.#frame(frame); input.bridge.listeners.add((frame) => this.#frame(frame)); for (const operation of this.#operations.values()) if (!operation.accepted && !operation.settled) { operation.settled = true; operation.reject(new Error("Remote operation was not accepted before transport loss; task state is unknown.")); } this.#evidenceCursor = Math.max(this.#evidenceCursor, input.cursor); this.#snapshot = { connection: "connected", state: input.state, identity: this.identity, revision: this.#snapshot.revision + 1 }; const ownerReplacement = this.owner.replaceConnection({ connection: input.connection, unsubscribe: input.unsubscribe, paneId: input.paneId, state: input.state }); old.bridge.close(); await old.bridgeForward.close(); await ownerReplacement; if (this.#disposed) { await this.owner.cleanup(this.#aborted); return; } this.armReconnect(this.#reconnectFactory!); }
206
+ observeHerdr(value: unknown) { const data = value && typeof value === "object" ? (value as { data?: Record<string, unknown> }).data : undefined; if (!data || (data.terminal_id !== this.identity.terminalId && data.pane_id !== this.identity.paneId)) return; this.#snapshot = { ...this.#snapshot, revision: this.#snapshot.revision + 1, state: herdrRunState(data.agent_status, this.#snapshot.state) }; }
207
+ #frame(frame: HerdrPiFrame) { if (typeof frame.cursor === "number") { if (frame.cursor <= this.#evidenceCursor) return; this.#evidenceCursor = frame.cursor; } if (frame.nativeSessionId !== this.identity.nativeSessionId) { this.bridge.fail(new Error("Remote Pi native session identity changed.")); void this.connection.close(); return; } if (frame.type === "accepted" && typeof frame.requestId === "string") { const operation = this.#operations.get(frame.requestId); if (operation) operation.accepted = true; } if (frame.type === "supervisor-request" && this.supervisorDir && typeof frame.requestId === "string") this.#relaySupervisor(frame); if (frame.type === "event" && frame.event && typeof frame.event === "object") { const event = frame.event as ChildSessionEvent; const message = event.message as AgentMessage | undefined; if (event.type === "message_end" && message) this.#messages.push(message); for (const listener of this.#listeners) listener(event); } if (frame.type === "settled" && typeof frame.requestId === "string") { if (frame.finalAssistant && typeof frame.finalAssistant === "object") { const message = frame.finalAssistant as AgentMessage; if (!this.#messages.includes(message)) this.#messages.push(message); } if (frame.finalGit && typeof frame.finalGit === "object") this.#finalGit = frame.finalGit as HerdrRemoteGitStatus; const operation = this.#operations.get(frame.requestId); if (operation && !operation.settled) { operation.accepted = true; operation.settled = true; frame.idle === true && frame.pending === false ? operation.resolve() : operation.reject(new Error("Remote Pi did not settle with an empty native queue.")); } for (const listener of this.#listeners) listener({ type: "agent_settled" }); } }
208
+ #relaySupervisor(frame: HerdrPiFrame) { if (!this.supervisorDir || typeof frame.requestId !== "string") return; const reason = frame.reason; if (reason !== "need_decision" && reason !== "interview_request" && reason !== "progress_update") return; const createdAt = Date.now(); const file = path.join(this.supervisorDir, "requests", `${path.basename(frame.requestId)}.json`); const request = { type: "subagent.supervisor.request", id: frame.requestId, createdAt, ...(reason !== "progress_update" ? { expiresAt: createdAt + 10 * 60_000 } : {}), reason, message: typeof frame.message === "string" ? frame.message : "", ...(frame.interview && typeof frame.interview === "object" ? { interview: frame.interview } : {}), expectsReply: reason !== "progress_update", runId: this.runtime.runId ?? this.identity.runId, agent: this.runtime.agent ?? "remote", childIndex: this.runtime.childIndex ?? 0, orchestratorSessionId: this.runtime.orchestratorSessionId }; try { fs.writeFileSync(file, JSON.stringify(request), { mode: 0o600, flag: "wx" }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; const existing = JSON.parse(fs.readFileSync(file, "utf8")) as { id?: unknown; reason?: unknown }; if (existing.id !== frame.requestId || existing.reason !== reason) throw new Error("Supervisor relay identity changed during replay."); } if (reason === "progress_update") this.bridge.supervisorDelivered(frame.requestId); }
209
+ async #operation(operation: string, text?: string, supervisorId?: string): Promise<void> { const requestId = `${++this.#sequence}_${randomBytes(5).toString("hex")}`; let completion: Promise<void> = Promise.resolve(); if (operation === "prompt") completion = new Promise<void>((resolve, reject) => this.#operations.set(requestId, { resolve, reject, accepted: false, settled: false })); try { await Promise.race([this.bridge.prepare(requestId, operation, text, supervisorId), this.bridge.failure]); await this.connection.client.call("agent.prompt", { target: this.identity.agentName, text: `/pi-subagents-bridge ${requestId}` }); await completion; } catch (error) { if (operation === "prompt" && this.bridge.failed) { await this.reconnect(); await completion; return; } const pending = this.#operations.get(requestId); if (pending) pending.settled = true; throw error; } finally { if (operation === "prompt") this.#operations.delete(requestId); } }
210
+ subscribe(listener: (event: ChildSessionEvent) => void) { this.#listeners.add(listener); return () => this.#listeners.delete(listener); }
211
+ prompt(text: string) { return this.#operation("prompt", text); } steer(text: string) { return this.#operation("steer", text); } followUp(text: string) { return this.#operation("follow-up", text); } async abort() { this.#aborted = true; await this.#operation("abort"); }
212
+ async dispose() { if (this.#disposed) return; this.#disposed = true; if (this.#replyTimer) clearInterval(this.#replyTimer); this.bridge.close(); await this.bridgeForward.close(); await this.owner.cleanup(this.#aborted); this.#snapshot = { ...this.#snapshot, connection: "closed" }; }
213
+ get messages() { return this.#messages; } get sessionFile() { return undefined; } get sessionId() { return this.identity.nativeSessionId; } get modelId() { return this.model; }
214
+ get machineEvidence() { return { machineId: this.identity.machineId, ...(this.#initialGit ? { initial: this.#initialGit } : {}), ...(this.#finalGit ? { final: this.#finalGit } : {}) }; }
215
+ get placementSnapshot() { return this.owner.snapshot; }
216
+ }
217
+
218
+ export async function reconnectHerdrPiSession(session: HerdrPiSession, launch: ChildSessionLaunch, dependencies: { connect?: typeof connectHerdrMachine; discoverManifest?: typeof discoverBridgeManifest; createBridge?: (socketPath: string, runId: string) => BridgeChannel } = {}): Promise<void> {
219
+ const connect = dependencies.connect ?? connectHerdrMachine, discoverManifest = dependencies.discoverManifest ?? discoverBridgeManifest, createBridge = dependencies.createBridge ?? ((socketPath: string, runId: string) => new BridgeChannel(socketPath, runId));
220
+ let validated: { connection: HerdrForwardedConnection; unsubscribe: () => void; bridgeForward: { socketPath: string; close(): Promise<void> }; bridge: BridgeChannel; candidate: { adopted: boolean; lost?: Error } } | undefined;
221
+ const result = await boundedHerdrReconnect(session.identity, session.evidenceCursor, async () => {
222
+ const connection = await connect(launch.machine!); let unsubscribe = () => {}; let bridgeForward: { socketPath: string; close(): Promise<void> } | undefined; let bridge: BridgeChannel | undefined; const generation: { adopted: boolean; lost?: Error } = { adopted: false };
223
+ try {
224
+ const snapshot = parseHerdrSessionSnapshot(await connection.client.call<Record<string, unknown>>("session.snapshot"));
225
+ const agents = snapshotAgents(snapshot);
226
+ const manifest = await discoverManifest(launch.machine!, session.identity.runId, session.identity.runtimeDir); bridgeForward = await connection.forwardRemoteSocket(manifest.socketPath, "bridge-reconnect"); bridge = createBridge(bridgeForward.socketPath, session.identity.runId);
227
+ const ready = await waitForReadyBridgeFrame(bridge, 8_000, "Reconnected bridge handshake timed out.", true);
228
+ const candidate: HerdrReconnectCandidate = { endpoint: connection.endpoint, agents, bridge: { runId: ready.runId, nativeSessionId: ready.nativeSessionId as string | undefined, packageVersion: ready.packageVersion as string | undefined, protocol: ready.protocol, evidenceCursor: ready.evidenceCursor as number | undefined, evidenceFloor: ready.evidenceFloor as number | undefined } };
229
+ const check = reconcileHerdrReconnect(session.identity, candidate, session.evidenceCursor); if (!check.ok) throw new Error(check.reason);
230
+ unsubscribe = await connection.client.subscribe(herdrStatusSubscriptions(check.paneId), (event) => { session.owner.observeEvent(event); session.observeHerdr(event); }, (error) => { if (!generation.adopted) { generation.lost ??= error; return; } session.owner.markConnectionUnknown(connection); void session.reconnect(); });
231
+ if (generation.lost) throw generation.lost; validated = { connection, unsubscribe, bridgeForward, bridge, candidate: generation }; return candidate;
232
+ } catch (error) { unsubscribe(); bridge?.close(); await bridgeForward?.close(); await connection.close(); throw error; }
233
+ }, { attempts: 3, deadlineMs: 15_000, disposed: () => (session.placementSnapshot as HerdrRunSnapshot).connection === "closed" });
234
+ if (!result.ok) throw new Error(`Pane-native reconnect remains unknown: ${result.reason}`);
235
+ if (!validated) throw new Error("Pane-native reconnect produced no validated transport.");
236
+ if (validated.candidate.lost) { validated.unsubscribe(); validated.bridge.close(); await validated.bridgeForward.close(); await validated.connection.close(); throw validated.candidate.lost; }
237
+ validated.candidate.adopted = true;
238
+ await session.replaceTransport({ ...validated, paneId: result.paneId, cursor: result.cursor, state: result.state });
239
+ }
240
+
241
+ export async function createHerdrPiSession(launch: ChildSessionLaunch): Promise<ChildSession> {
242
+ if (!launch.machine) throw new Error("Pane-native Pi launch requires a saved machine.");
243
+ const policy = serializeHerdrPiLaunch(launch); const runId = safeRunId(launch.runtime.runId); const owner = await HerdrPlacedRunOwner.create(launch.machine, runId); const runtimeDir = owner.runtimeDir, connection = owner.connection; let owned: { workspaceId: string; tabId: string; paneId: string } | undefined; let agentName: string | undefined; let observeHerdr: ((event: unknown) => void) | undefined;
244
+ try {
245
+ let reconnectSession: HerdrPiSession | undefined; owned = await owner.provision(); await owner.subscribe((event) => observeHerdr?.(event), () => void reconnectSession?.reconnect());
246
+ agentName = `pi-${runId.slice(-20)}`; const { terminalId } = await owner.start("pi", agentName, policy.args);
247
+ const manifest = await discoverBridgeManifest(launch.machine, runId, runtimeDir); if (manifest.protocol !== HERDR_PI_PROTOCOL || manifest.packageVersion !== packageJson.version) throw new Error(`Remote pi-subagents bridge version mismatch (remote ${manifest.packageVersion}, local ${packageJson.version}).`);
248
+ const bridgeForward = await connection.forwardRemoteSocket(manifest.socketPath, "bridge"); const bridge = new BridgeChannel(bridgeForward.socketPath, runId);
249
+ const ready = await waitForReadyBridgeFrame(bridge, 15_000, "Remote Pi bridge handshake timed out.");
250
+ if (ready.packageVersion !== packageJson.version || ready.nativeSessionId !== manifest.nativeSessionId || ready.cwd !== launch.machine.cwd) throw new Error("Remote Pi bridge handshake identity mismatch.");
251
+ const configured = await Promise.race([bridge.configure(policy.resources), bridge.failure]);
252
+ if (configured.nativeSessionId !== manifest.nativeSessionId || configured.agent !== policy.resources.agent) throw new Error("Remote Pi resource resolution identity mismatch.");
253
+ if (!Array.isArray(configured.tools) || (policy.resources.toolCeiling && (configured.tools as unknown[]).some((tool) => !policy.resources.toolCeiling!.includes(String(tool))))) throw new Error("Remote Pi active-tool ceiling acknowledgement mismatch.");
254
+ if (launch.model && configured.model !== launch.model.split(":")[0]) throw new Error(`Remote Pi model '${launch.model}' did not resolve to the requested provider/model.`);
255
+ const identity: HerdrRunIdentity = { runId, machineId: launch.machine.id, target: launch.machine.target, session: connection.endpoint.session, workspaceId: owned.workspaceId, tabId: owned.tabId, paneId: owned.paneId, terminalId, agentName, nativeSessionId: manifest.nativeSessionId, cwd: launch.machine.cwd, runtimeDir };
256
+ owner.journal(identity);
257
+ const session = new HerdrPiSession(owner, bridgeForward, bridge, (configured.tools as string[] | undefined), typeof ready.model === "string" ? ready.model : undefined, launch.runtime, ready.initialGit as HerdrRemoteGitStatus | undefined); reconnectSession = session; observeHerdr = (event) => session.observeHerdr(event); session.armReconnect(() => reconnectHerdrPiSession(session, launch)); return session;
258
+ } catch (error) { await owner.cleanup(); throw error; }
259
+ }
260
+
261
+ export function createPlacementAwareChildSessionFactory(local: ChildSessionFactory, createRemote: (launch: ChildSessionLaunch) => Promise<ChildSession> = createHerdrPiSession): ChildSessionFactory {
262
+ const remote = new Set<ChildSession>(); return { async create(launch) { if (!launch.machine) return local.create(launch); serializeHerdrPiLaunch(launch); const child = await createRemote(launch); remote.add(child); return child; }, async dispose() { await Promise.allSettled([...remote].map((child) => child.dispose())); remote.clear(); await local.dispose(); } };
263
+ }
@@ -1,6 +1,6 @@
1
1
  import type {
2
2
  AsyncStatus,
3
- HostStepNodeV1,
3
+ HostStepNode,
4
4
  HostStepState,
5
5
  HostStepVerdict,
6
6
  WorkflowGraphNode,
@@ -57,7 +57,7 @@ function assertTimestamp(value: unknown, field: string, source: string, required
57
57
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`Invalid host step '${source}': ${field} must be a non-negative safe integer.`);
58
58
  }
59
59
 
60
- function assertFreshness(value: unknown, source: string): asserts value is HostStepNodeV1["freshness"] {
60
+ function assertFreshness(value: unknown, source: string): asserts value is HostStepNode["freshness"] {
61
61
  if (!isRecord(value)) throw new Error(`Invalid host step '${source}': freshness must be an object.`);
62
62
  const unknownFields = Object.keys(value).filter((field) => !FRESHNESS_FIELDS.has(field));
63
63
  if (unknownFields.length > 0) throw new Error(`Invalid host step '${source}': freshness has unsupported fields: ${unknownFields.join(", ")}.`);
@@ -70,7 +70,7 @@ function assertFreshness(value: unknown, source: string): asserts value is HostS
70
70
  * Validate the persisted host-step contract. This deliberately rejects unknown
71
71
  * fields and unbounded values so status and receipt loaders fail closed.
72
72
  */
73
- export function assertHostStepNode(value: unknown, source = "status"): asserts value is HostStepNodeV1 {
73
+ export function assertHostStepNode(value: unknown, source = "status"): asserts value is HostStepNode {
74
74
  if (!isRecord(value)) throw new Error(`Invalid host step '${source}': expected an object.`);
75
75
  const unknownFields = Object.keys(value).filter((field) => !HOST_STEP_FIELDS.has(field));
76
76
  if (unknownFields.length > 0) throw new Error(`Invalid host step '${source}': unsupported fields: ${unknownFields.join(", ")}.`);
@@ -105,7 +105,7 @@ export function assertHostStepNode(value: unknown, source = "status"): asserts v
105
105
  assertTimestamp(value.deadlineAt, "deadlineAt", source);
106
106
  }
107
107
 
108
- export function parseHostStepNode(value: unknown, source = "status"): HostStepNodeV1 {
108
+ export function parseHostStepNode(value: unknown, source = "status"): HostStepNode {
109
109
  assertHostStepNode(value, source);
110
110
  return {
111
111
  ...value,
@@ -113,7 +113,7 @@ export function parseHostStepNode(value: unknown, source = "status"): HostStepNo
113
113
  };
114
114
  }
115
115
 
116
- export function assertUniqueHostStepIds(hostSteps: readonly HostStepNodeV1[], source = "status"): void {
116
+ export function assertUniqueHostStepIds(hostSteps: readonly HostStepNode[], source = "status"): void {
117
117
  const ids = new Set<string>();
118
118
  for (const hostStep of hostSteps) {
119
119
  if (ids.has(hostStep.id)) throw new Error(`Invalid host step '${source}': duplicate host step id '${hostStep.id}'.`);
@@ -122,11 +122,11 @@ export function assertUniqueHostStepIds(hostSteps: readonly HostStepNodeV1[], so
122
122
  }
123
123
 
124
124
  /** Return only valid host nodes so an untrusted in-memory projection fails closed. */
125
- export function validHostStepNodes(graph: WorkflowGraphSnapshot | undefined): HostStepNodeV1[] {
125
+ export function validHostStepNodes(graph: WorkflowGraphSnapshot | undefined): HostStepNode[] {
126
126
  const nodes = graph?.nodes ?? [];
127
127
  const nodeIdCounts = new Map<string, number>();
128
128
  for (const node of nodes) nodeIdCounts.set(node.id, (nodeIdCounts.get(node.id) ?? 0) + 1);
129
- const hostSteps: HostStepNodeV1[] = [];
129
+ const hostSteps: HostStepNode[] = [];
130
130
  for (const [index, node] of nodes.entries()) {
131
131
  if (node.kind !== "host-step") continue;
132
132
  try {
@@ -147,7 +147,7 @@ export function assertWorkflowGraphHostSteps(graph: WorkflowGraphSnapshot | unde
147
147
  if (!Array.isArray(graph.nodes)) throw new Error(`Invalid host step '${source}.workflowGraph': nodes must be an array.`);
148
148
  const hostStepCount = graph.nodes.filter((node) => node.kind === "host-step").length;
149
149
  if (hostStepCount > HOST_STEP_MAX_COUNT) throw new Error(`Invalid host step '${source}': workflowGraph contains more than ${HOST_STEP_MAX_COUNT} host steps.`);
150
- const hostSteps: HostStepNodeV1[] = [];
150
+ const hostSteps: HostStepNode[] = [];
151
151
  for (const [index, node] of graph.nodes.entries()) {
152
152
  if (node.kind !== "host-step") continue;
153
153
  const hostStep = parseHostStepNode(node.hostStep, `${source}.workflowGraph.nodes[${index}].hostStep`);
@@ -161,7 +161,7 @@ export function assertWorkflowGraphHostSteps(graph: WorkflowGraphSnapshot | unde
161
161
  }
162
162
  }
163
163
 
164
- export function hostStepWorkflowNode(hostStep: HostStepNodeV1): WorkflowGraphNode {
164
+ export function hostStepWorkflowNode(hostStep: HostStepNode): WorkflowGraphNode {
165
165
  assertHostStepNode(hostStep, hostStep.id);
166
166
  return {
167
167
  id: hostStep.id,
@@ -172,7 +172,7 @@ export function hostStepWorkflowNode(hostStep: HostStepNodeV1): WorkflowGraphNod
172
172
  };
173
173
  }
174
174
 
175
- function workflowNodeStatus(hostStep: HostStepNodeV1): WorkflowNodeStatus {
175
+ function workflowNodeStatus(hostStep: HostStepNode): WorkflowNodeStatus {
176
176
  if (hostStep.state === "pending") return "pending";
177
177
  if (hostStep.state === "running") return "running";
178
178
  if (hostStep.state === "cancelled") return "stopped";
@@ -187,7 +187,7 @@ function workflowNodeStatus(hostStep: HostStepNodeV1): WorkflowNodeStatus {
187
187
  */
188
188
  export function upsertHostStep(input: {
189
189
  status: AsyncStatus;
190
- hostStep: HostStepNodeV1;
190
+ hostStep: HostStepNode;
191
191
  persist: (status: AsyncStatus) => void;
192
192
  }): AsyncStatus {
193
193
  const hostStep = parseHostStepNode(input.hostStep, input.hostStep.id);
@@ -1,10 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
- import { Agent, type AgentTool, type StreamFn } from "@earendil-works/pi-agent-core";
3
- import { convertToLlm, type ExtensionContext } from "@earendil-works/pi-coding-agent";
4
- import { streamSimple } from "@earendil-works/pi-ai/compat";
2
+ import type { Agent, AgentTool, StreamFn } from "@earendil-works/pi-agent-core";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
4
  import type { ProviderHeaders } from "@earendil-works/pi-ai";
6
5
  import { Type, type Static } from "typebox";
7
6
  import { agentStreamOptions } from "../../shared/agent-stream-options.ts";
7
+ import { opencodeSessionHeaders } from "../../shared/opencode-session-headers.ts";
8
8
 
9
9
  /**
10
10
  * LLM intent arbiter for the completion mutation guard.
@@ -52,7 +52,13 @@ export function mapArbiterDecision(
52
52
 
53
53
  interface ArbiterRuntime {
54
54
  model: NonNullable<RegistryModel>;
55
- baseStreamFn: StreamFn;
55
+ /** Explicit override; it always wins over a registered provider stream. */
56
+ explicitStreamFn?: StreamFn;
57
+ /** Registered provider stream, usable only when its api matches the model. */
58
+ registeredStreamFn?: StreamFn;
59
+ registeredApi?: string;
60
+ /** Session id for OpenCode session-routing headers, when the caller has one. */
61
+ sessionId?: string;
56
62
  timeoutMs: number;
57
63
  }
58
64
 
@@ -73,9 +79,14 @@ export interface TaskMutationArbiterOptions {
73
79
  const DEFAULT_ARBITER_TIMEOUT_MS = 10_000;
74
80
 
75
81
  type RegistryModel = ReturnType<NonNullable<ExtensionContext["modelRegistry"]["find"]>>;
82
+ /** Model services the arbiter needs, plus the caller's session id for OpenCode session-routing headers. */
83
+ export type ArbiterModelContext = Pick<ExtensionContext, "model" | "modelRegistry"> & {
84
+ /** Session id the headers attach to (the child's, captured by detached runners; the parent's, passed by foreground callers). */
85
+ sessionId?: string;
86
+ };
76
87
 
77
88
  function resolveArbiterModel(
78
- ctx: ExtensionContext,
89
+ ctx: ArbiterModelContext,
79
90
  options?: TaskMutationArbiterOptions,
80
91
  ): NonNullable<RegistryModel> | null {
81
92
  const registry = ctx.modelRegistry as {
@@ -95,7 +106,7 @@ function resolveArbiterModel(
95
106
  }
96
107
 
97
108
  function resolveArbiterRuntime(
98
- ctx: ExtensionContext,
109
+ ctx: ArbiterModelContext,
99
110
  options?: TaskMutationArbiterOptions,
100
111
  ): ArbiterRuntime | null {
101
112
  const model = resolveArbiterModel(ctx, options);
@@ -103,23 +114,21 @@ function resolveArbiterRuntime(
103
114
  const registry = ctx.modelRegistry as {
104
115
  getRegisteredProviderConfig?: (provider: string) => { api?: string; streamSimple?: StreamFn } | undefined;
105
116
  };
106
- const modelApi = (model as { api?: string }).api;
107
117
  const registered = registry.getRegisteredProviderConfig?.(model.provider);
108
- const baseStreamFn = options?.streamFn
109
- ?? (registered?.streamSimple && registered.api === modelApi
110
- ? registered.streamSimple
111
- : streamSimple);
112
118
  return {
113
119
  model,
114
- baseStreamFn,
120
+ explicitStreamFn: options?.streamFn,
121
+ registeredStreamFn: registered?.streamSimple,
122
+ registeredApi: registered?.api,
123
+ sessionId: ctx.sessionId,
115
124
  timeoutMs: options?.timeoutMs ?? DEFAULT_ARBITER_TIMEOUT_MS,
116
125
  };
117
126
  }
118
127
 
119
128
  async function resolveArbiterAuth(
120
- ctx: ExtensionContext,
129
+ ctx: ArbiterModelContext,
121
130
  model: RegistryModel,
122
- ): Promise<ArbiterAuth> {
131
+ ): Promise<ArbiterAuth | undefined> {
123
132
  const registry = ctx.modelRegistry as {
124
133
  getApiKeyAndHeaders?: (m: RegistryModel) => Promise<{
125
134
  ok: boolean;
@@ -135,14 +144,14 @@ async function resolveArbiterAuth(
135
144
  if (!registry.getApiKeyAndHeaders) return {};
136
145
  try {
137
146
  const auth = await registry.getApiKeyAndHeaders(model);
138
- if (auth.ok === false) return {};
147
+ if (auth.ok === false) return undefined;
139
148
  return {
140
149
  ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
141
150
  ...(auth.headers ? { headers: auth.headers } : {}),
142
151
  ...(auth.env ? { env: auth.env } : {}),
143
152
  };
144
153
  } catch {
145
- return {};
154
+ return undefined;
146
155
  }
147
156
  }
148
157
 
@@ -150,12 +159,13 @@ async function resolveArbiterAuth(
150
159
  function authWrappedStreamFn(
151
160
  base: StreamFn,
152
161
  auth: ArbiterAuth,
162
+ sessionId: string | undefined,
153
163
  ): StreamFn {
154
164
  return (model, context, streamOptions) => base(model, context, {
155
165
  ...(streamOptions ?? {}),
156
166
  ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
157
167
  ...(auth.env || streamOptions?.env ? { env: { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } } : {}),
158
- headers: { ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
168
+ headers: { ...opencodeSessionHeaders(model, sessionId), ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
159
169
  });
160
170
  }
161
171
 
@@ -164,6 +174,15 @@ async function runArbitration(
164
174
  auth: ArbiterAuth,
165
175
  task: string,
166
176
  ): Promise<TaskMutationVerdict> {
177
+ // Keep optional Pi peers out of the detached runner's static import graph.
178
+ const [{ Agent }, { convertToLlm }, { streamSimple }] = await Promise.all([
179
+ import("@earendil-works/pi-agent-core"),
180
+ import("@earendil-works/pi-coding-agent"),
181
+ import("@earendil-works/pi-ai/compat"),
182
+ ]);
183
+ const streamFn: StreamFn = runtime.explicitStreamFn
184
+ ?? (runtime.registeredApi !== undefined && runtime.registeredApi === runtime.model.api ? runtime.registeredStreamFn : undefined)
185
+ ?? streamSimple;
167
186
  let decision: DecisionParams | undefined;
168
187
  const tool: AgentTool<typeof DecisionParams, { recorded: boolean }> = {
169
188
  name: "task_mutation_decision",
@@ -190,7 +209,7 @@ async function runArbitration(
190
209
  tools: [tool],
191
210
  },
192
211
  convertToLlm,
193
- ...agentStreamOptions(authWrappedStreamFn(runtime.baseStreamFn, auth)),
212
+ ...agentStreamOptions(authWrappedStreamFn(streamFn, auth, runtime.sessionId)),
194
213
  getApiKey: (providerName) =>
195
214
  providerName === runtime.model.provider ? auth.apiKey : undefined,
196
215
  beforeToolCall: async ({ toolCall }) =>
@@ -221,9 +240,9 @@ async function runArbitration(
221
240
  }
222
241
  }
223
242
 
224
- /** Create a memoized arbiter bound to the parent session's model, or undefined when disabled/unavailable. */
243
+ /** Create a memoized arbiter bound to the supplied model services, or undefined when disabled/unavailable. */
225
244
  export function createTaskMutationArbiter(
226
- ctx: ExtensionContext,
245
+ ctx: ArbiterModelContext,
227
246
  options?: TaskMutationArbiterOptions,
228
247
  ): TaskMutationArbiter | undefined {
229
248
  if (process.env.PI_SUBAGENTS_LLM_INTENT_ARBITER === "0") return undefined;
@@ -235,7 +254,7 @@ export function createTaskMutationArbiter(
235
254
  const cached = cache.get(key);
236
255
  if (cached) return cached;
237
256
  const auth = await resolveArbiterAuth(ctx, runtime.model);
238
- const verdict = await runArbitration(runtime, auth, task);
257
+ const verdict = auth ? await runArbitration(runtime, auth, task) : "unavailable";
239
258
  if (cache.size > 200) cache.clear();
240
259
  cache.set(key, verdict);
241
260
  return verdict;