@xzzpig/pi-subagents 0.20.0 → 0.22.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 (144) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/fork-supervisor-routing.md +77 -0
  13. package/docs/missions.md +34 -17
  14. package/docs/models.md +1 -1
  15. package/docs/observability.md +10 -5
  16. package/docs/tool-reference.md +117 -84
  17. package/docs/watchdog.md +8 -6
  18. package/docs/workflows.md +16 -7
  19. package/index.ts +5 -0
  20. package/package.json +6 -3
  21. package/prompts/council.md +1 -1
  22. package/skills/pi-subagents/SKILL.md +1 -1
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  24. package/skills/pi-subagents/references/execution-controls.md +16 -16
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  26. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  27. package/src/agents/advertised-agent-prompt.ts +9 -1
  28. package/src/agents/agent-management.ts +4 -0
  29. package/src/agents/agent-memory.ts +3 -3
  30. package/src/agents/agent-scope.ts +4 -0
  31. package/src/agents/agent-serializer.ts +8 -1
  32. package/src/agents/agents.ts +191 -145
  33. package/src/api/preflight.ts +8 -4
  34. package/src/api/supervisor-routing.ts +196 -0
  35. package/src/extension/config.ts +21 -2
  36. package/src/extension/context-injection.ts +6 -1
  37. package/src/extension/control-notices.ts +1 -9
  38. package/src/extension/declaration-pinning.ts +164 -0
  39. package/src/extension/doctor.ts +7 -10
  40. package/src/extension/fanout-child.ts +7 -8
  41. package/src/extension/index.ts +143 -134
  42. package/src/extension/reply-workflow-script.ts +20 -11
  43. package/src/extension/rpc.ts +11 -6
  44. package/src/extension/schemas.ts +34 -30
  45. package/src/extension/subagent-guide.ts +86 -6
  46. package/src/extension/subagent-options.ts +47 -0
  47. package/src/extension/tool-activation.ts +3 -2
  48. package/src/extension/tool-description.ts +51 -68
  49. package/src/inspectors/actions.ts +37 -11
  50. package/src/inspectors/plugins.ts +3 -2
  51. package/src/inspectors/tmux/actions.ts +204 -0
  52. package/src/inspectors/tmux/client.ts +85 -0
  53. package/src/inspectors/tmux/plugin.ts +21 -0
  54. package/src/integrations/herdr-status.ts +18 -49
  55. package/src/integrations/program-status.ts +215 -0
  56. package/src/intercom/fork-supervisor-routing.ts +533 -0
  57. package/src/intercom/native-supervisor-channel.ts +152 -13
  58. package/src/intercom/result-intercom.ts +3 -2
  59. package/src/intercom/supervisor-ui.ts +2 -174
  60. package/src/missions/store.ts +25 -5
  61. package/src/profiles/profiles.ts +24 -21
  62. package/src/runs/background/active-async-capacity.ts +58 -8
  63. package/src/runs/background/async-execution.ts +143 -38
  64. package/src/runs/background/async-job-tracker.ts +11 -4
  65. package/src/runs/background/async-resume.ts +5 -2
  66. package/src/runs/background/await-async-run.ts +14 -9
  67. package/src/runs/background/binary-bootstrap.ts +2 -1
  68. package/src/runs/background/calendar-schedule.ts +90 -0
  69. package/src/runs/background/chain-root-attachment.ts +9 -5
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +16 -2
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-child-launch.ts +1 -0
  79. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  80. package/src/runs/background/scheduled-runs.ts +256 -61
  81. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  82. package/src/runs/background/subagent-runner.ts +32 -12
  83. package/src/runs/background/subagent-wait.ts +38 -19
  84. package/src/runs/background/terminal-run-index.ts +46 -1
  85. package/src/runs/background/wait-completions.ts +1 -0
  86. package/src/runs/background/wait-tool.ts +33 -23
  87. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  88. package/src/runs/foreground/async-stop-action.ts +48 -22
  89. package/src/runs/foreground/execution.ts +94 -52
  90. package/src/runs/foreground/foreground-history.ts +1 -0
  91. package/src/runs/foreground/subagent-executor.ts +232 -77
  92. package/src/runs/shared/child-commands.ts +2 -1
  93. package/src/runs/shared/child-hooks.ts +4 -3
  94. package/src/runs/shared/child-launch.ts +3 -0
  95. package/src/runs/shared/child-session.ts +41 -24
  96. package/src/runs/shared/child-tool-plan.ts +13 -26
  97. package/src/runs/shared/dynamic-fanout.ts +1 -1
  98. package/src/runs/shared/fork-command-result.ts +10 -0
  99. package/src/runs/shared/herdr-placed-run.ts +5 -4
  100. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  101. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  102. package/src/runs/shared/model-resolution.ts +30 -1
  103. package/src/runs/shared/nested-events.ts +5 -0
  104. package/src/runs/shared/parallel-handoff.ts +56 -8
  105. package/src/runs/shared/parallel-utils.ts +2 -0
  106. package/src/runs/shared/partial-output.ts +48 -0
  107. package/src/runs/shared/runner-launcher.ts +25 -0
  108. package/src/runs/shared/single-output.ts +53 -0
  109. package/src/runs/shared/structured-output.ts +14 -7
  110. package/src/runs/shared/subagent-control.ts +3 -3
  111. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  112. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  113. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  114. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  115. package/src/runs/shared/worktree-lock.ts +29 -0
  116. package/src/runs/shared/worktree.ts +12 -1
  117. package/src/shared/atomic-json.ts +4 -2
  118. package/src/shared/edit-distance.ts +33 -0
  119. package/src/shared/file-lease.ts +74 -0
  120. package/src/shared/formatters.ts +1 -5
  121. package/src/shared/model-info.ts +22 -0
  122. package/src/shared/package-version.ts +17 -0
  123. package/src/shared/parent-wake.ts +79 -0
  124. package/src/shared/pruned-fork.ts +7 -1
  125. package/src/shared/runtime-module-path.ts +19 -0
  126. package/src/shared/settings-file-lease.ts +36 -0
  127. package/src/shared/types.ts +36 -2
  128. package/src/shared/utils.ts +8 -6
  129. package/src/slash/prompt-template-bridge.ts +21 -20
  130. package/src/slash/slash-commands.ts +3 -3
  131. package/src/slash/subagents-admin.ts +2 -1
  132. package/src/tui/fleet-native-transcript.ts +2 -0
  133. package/src/tui/fleet-transcript.ts +12 -3
  134. package/src/tui/fleet.ts +11 -8
  135. package/src/tui/render.ts +27 -19
  136. package/src/tui/subagent-messages.ts +305 -0
  137. package/src/watchdog/diff-tool.ts +2 -2
  138. package/src/watchdog/register-main.ts +2 -22
  139. package/src/watchdog/render.ts +2 -24
  140. package/src/watchdog/runtime.ts +6 -4
  141. package/src/watchdog/settings.ts +18 -13
  142. package/src/watchdog/tool-actions.ts +2 -2
  143. package/src/workflows/scripted-workflow.ts +20 -6
  144. package/src/workflows/workflow-resources.ts +11 -0
@@ -0,0 +1,533 @@
1
+ /**
2
+ * Owner-side supervisor responder routing (fork-only).
3
+ *
4
+ * Responsibilities:
5
+ * - hold one owner-local registry keyed by the owning ExtensionAPI object;
6
+ * - accept a registration only for a complete delegation identity, validated
7
+ * against the live supervisor owner session id;
8
+ * - bind a registration to the real child route (runId + canonical agent +
9
+ * childIndex) exactly once, before the child's first prompt;
10
+ * - claim that route's asks, answer them through a caller-supplied delivery
11
+ * closure, and fail closed — never fall back to native wake/detach — once a
12
+ * claimed ask cannot be answered or delivered;
13
+ * - release bindings on terminal, owner session reset and shutdown.
14
+ *
15
+ * Nothing here changes ordinary subagent/workflow behaviour: a route with no
16
+ * bound registration is not claimed, so the native channel keeps its existing
17
+ * pending/wake/detach handling byte-for-byte.
18
+ */
19
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
20
+ import {
21
+ SUPERVISOR_RESPONDER_REGISTER_EVENT,
22
+ SUPERVISOR_RESPONDER_REGISTER_VERSION,
23
+ validateSupervisorResponderScope,
24
+ type SupervisorResponder,
25
+ type SupervisorResponderOutcome,
26
+ type SupervisorResponderReason,
27
+ type SupervisorResponderRegistration,
28
+ type SupervisorResponderRegistrationRequest,
29
+ type SupervisorResponderRegistrationResult,
30
+ type SupervisorResponderRequest,
31
+ type SupervisorResponderScope,
32
+ } from "../api/supervisor-routing.ts";
33
+
34
+ /** Per-reply hard bound; matches the coordination-record reply budget (8 KiB). */
35
+ export const MAX_SUPERVISOR_RESPONDER_REPLY_BYTES = 8 * 1024;
36
+
37
+ /** Identity of the delegation attempt a consumer registered for. */
38
+ export interface SupervisorDelegationIdentity {
39
+ requestId: string;
40
+ ownerRunId: string;
41
+ nodeId: string;
42
+ agent: string;
43
+ }
44
+
45
+ /** The real child route, resolved by the executor before the first prompt. */
46
+ export interface SupervisorChildRoute {
47
+ runId: string;
48
+ /** Canonical agent resolved by the executor; never the requested alias. */
49
+ agent: string;
50
+ childIndex: number;
51
+ parentSessionId?: string;
52
+ /** False when the child carries no supervisor capability; no binding is made. */
53
+ bridgeActive: boolean;
54
+ }
55
+
56
+ export interface SupervisorLaunchHooks {
57
+ /** Called once, after the real runId exists and before any child prompt. */
58
+ beforeNativeChildLaunch(route: SupervisorChildRoute): void;
59
+ /** Idempotent; drops the pending (or bound) registration for this launch. */
60
+ release(): void;
61
+ }
62
+
63
+ export type SupervisorAskLifecycle = "resolved" | "expired" | "inactive" | "missing" | "wrong-session";
64
+
65
+ export interface SupervisorAskInput {
66
+ askId: string;
67
+ runId: string;
68
+ agent: string;
69
+ childIndex: number;
70
+ reason: SupervisorResponderReason;
71
+ message: string;
72
+ interview?: unknown;
73
+ deadlineAt?: number;
74
+ }
75
+
76
+ export interface SupervisorDispatcher {
77
+ /**
78
+ * Synchronously claim an ask for a bound responder. True means "this ask is
79
+ * responder-managed": the caller must skip the native parent wake and detach.
80
+ * False means no responder owns this route, so default behaviour applies.
81
+ */
82
+ claim(input: SupervisorAskInput, deliver: (message: string) => void): boolean;
83
+ /** Native lifecycle observation for an ask this dispatcher may own. */
84
+ observe(askId: string, lifecycle: SupervisorAskLifecycle): void;
85
+ }
86
+
87
+ type AskState = "claimed" | "running" | "delivered" | "failed" | "cancelled";
88
+
89
+ interface AskRecord {
90
+ askId: string;
91
+ state: AskState;
92
+ registration: Registration;
93
+ controller: AbortController;
94
+ delivered: boolean;
95
+ }
96
+
97
+ interface Registration {
98
+ scope: SupervisorResponderScope;
99
+ respond: SupervisorResponder;
100
+ onFailure?: (error: Error) => void;
101
+ disposed: boolean;
102
+ failureNotified: boolean;
103
+ bound?: SupervisorChildRoute;
104
+ }
105
+
106
+ interface OwnerRegistry {
107
+ registrations: Map<string, Registration>;
108
+ pendingByIdentity: Map<string, Registration>;
109
+ byRoute: Map<string, Registration>;
110
+ asks: Map<string, AskRecord>;
111
+ disposed: boolean;
112
+ }
113
+
114
+ /** Identity key of the owning extension instance (one registry per owner). */
115
+ type OwnerKey = Pick<ExtensionAPI, "events">;
116
+
117
+ const registries = new WeakMap<OwnerKey, OwnerRegistry>();
118
+
119
+ function registryFor(pi: OwnerKey, create: boolean): OwnerRegistry | undefined {
120
+ const existing = registries.get(pi);
121
+ if (existing || !create) return existing;
122
+ const created: OwnerRegistry = {
123
+ registrations: new Map(),
124
+ pendingByIdentity: new Map(),
125
+ byRoute: new Map(),
126
+ asks: new Map(),
127
+ disposed: false,
128
+ };
129
+ registries.set(pi, created);
130
+ return created;
131
+ }
132
+
133
+ function identityKey(scope: SupervisorResponderScope): string {
134
+ return [scope.sessionId, scope.requestId, scope.ownerRunId, scope.nodeId, scope.agent].join("\u0000");
135
+ }
136
+
137
+ function delegationKey(sessionId: string, identity: SupervisorDelegationIdentity): string {
138
+ return [sessionId, identity.requestId, identity.ownerRunId, identity.nodeId, identity.agent].join("\u0000");
139
+ }
140
+
141
+ function routeKey(runId: string, agent: string, childIndex: number): string {
142
+ return `${runId}\u0000${agent}\u0000${childIndex}`;
143
+ }
144
+
145
+ function byteLength(value: string): number {
146
+ return Buffer.byteLength(value, "utf8");
147
+ }
148
+
149
+ function safeMessage(value: unknown, fallback: string): string {
150
+ if (typeof value !== "string") return fallback;
151
+ const trimmed = value.trim();
152
+ if (!trimmed) return fallback;
153
+ return trimmed.length > 1024 ? `${trimmed.slice(0, 1024)}…` : trimmed;
154
+ }
155
+
156
+ /**
157
+ * Install the owner-side registration listener. `getOwnerSessionId` must read
158
+ * the LIVE supervisor owner session id (the SDK runtime session id), never a
159
+ * session file path or a display alias.
160
+ */
161
+ export function registerSupervisorResponderEventListener(
162
+ pi: ExtensionAPI,
163
+ getOwnerSessionId: () => string | null,
164
+ ): () => void {
165
+ return pi.events.on(SUPERVISOR_RESPONDER_REGISTER_EVENT, (rawRequest) => {
166
+ if (!rawRequest || typeof rawRequest !== "object" || Array.isArray(rawRequest)) return;
167
+ const request = rawRequest as Record<string, unknown>;
168
+ if (request.result !== undefined) return;
169
+ try {
170
+ if (request.version !== SUPERVISOR_RESPONDER_REGISTER_VERSION) {
171
+ throw new Error(
172
+ `Unsupported supervisor responder registration event version '${String(request.version)}'.`,
173
+ );
174
+ }
175
+ const validated = validateSupervisorResponderScope(request.scope);
176
+ if ("error" in validated) throw new Error(validated.error);
177
+ const respond = request.respond;
178
+ if (typeof respond !== "function") {
179
+ throw new Error("Supervisor responder must be a function: (request) => outcome.");
180
+ }
181
+ if (request.onFailure !== undefined && typeof request.onFailure !== "function") {
182
+ throw new Error("Supervisor responder onFailure must be a function when provided.");
183
+ }
184
+ const registration = registerSupervisorResponder({
185
+ pi,
186
+ scope: validated.scope,
187
+ respond: respond as SupervisorResponder,
188
+ onFailure: request.onFailure as ((error: Error) => void) | undefined,
189
+ getOwnerSessionId,
190
+ });
191
+ request.result = { ok: true, registration } satisfies SupervisorResponderRegistrationResult;
192
+ } catch (error) {
193
+ request.result = {
194
+ ok: false,
195
+ error: error instanceof Error ? error : new Error(String(error)),
196
+ } satisfies SupervisorResponderRegistrationResult;
197
+ }
198
+ });
199
+ }
200
+
201
+ function registerSupervisorResponder(input: {
202
+ pi: ExtensionAPI;
203
+ scope: SupervisorResponderScope;
204
+ respond: SupervisorResponder;
205
+ onFailure?: (error: Error) => void;
206
+ getOwnerSessionId: () => string | null;
207
+ }): SupervisorResponderRegistration {
208
+ const registry = registryFor(input.pi, true);
209
+ if (!registry || registry.disposed) {
210
+ throw new Error("The pi-subagents supervisor router has already been disposed.");
211
+ }
212
+ const liveSessionId = input.getOwnerSessionId();
213
+ // Fail closed: without a live owner session id there is no way to prove this scope
214
+ // belongs to the current runtime owner, so the registration must be refused rather
215
+ // than accepted (an unbound registration would silently fall back to the default
216
+ // supervisor path at child launch).
217
+ if (!liveSessionId) {
218
+ throw new Error("The supervisor responder cannot be registered without a live owner session id.");
219
+ }
220
+ if (liveSessionId !== input.scope.sessionId) {
221
+ throw new Error(
222
+ `Supervisor responder scope.sessionId '${input.scope.sessionId}' is not the live supervisor owner session '${liveSessionId}'.`,
223
+ );
224
+ }
225
+ const key = identityKey(input.scope);
226
+ if (registry.registrations.has(key)) {
227
+ throw new Error(
228
+ `A supervisor responder is already registered for delegation attempt '${input.scope.requestId}'.`,
229
+ );
230
+ }
231
+ const registration: Registration = {
232
+ scope: { ...input.scope },
233
+ respond: input.respond,
234
+ ...(input.onFailure ? { onFailure: input.onFailure } : {}),
235
+ disposed: false,
236
+ failureNotified: false,
237
+ };
238
+ registry.registrations.set(key, registration);
239
+ registry.pendingByIdentity.set(key, registration);
240
+ return {
241
+ dispose: () => {
242
+ disposeRegistration(registry, key, registration);
243
+ },
244
+ };
245
+ }
246
+
247
+ function disposeRegistration(registry: OwnerRegistry, key: string, registration: Registration): void {
248
+ if (registration.disposed) return;
249
+ registration.disposed = true;
250
+ // Only this registration is removed; a replacement registered on the same
251
+ // scope keeps working because it owns its own map entries.
252
+ if (registry.registrations.get(key) === registration) registry.registrations.delete(key);
253
+ if (registry.pendingByIdentity.get(key) === registration) registry.pendingByIdentity.delete(key);
254
+ if (registration.bound) {
255
+ const boundKey = routeKey(registration.bound.runId, registration.bound.agent, registration.bound.childIndex);
256
+ if (registry.byRoute.get(boundKey) === registration) registry.byRoute.delete(boundKey);
257
+ }
258
+ // Idempotent terminal cleanup: cancel any live ask, then DROP every ask record that
259
+ // referenced this registration so the responder/onFailure closures (and the audit
260
+ // context they hold) do not survive the attempt. Owner shutdown keeps its own sweep.
261
+ for (const [askId, ask] of [...registry.asks.entries()]) {
262
+ if (ask.registration !== registration) continue;
263
+ if (ask.state === "claimed" || ask.state === "running") {
264
+ ask.state = "cancelled";
265
+ ask.controller.abort();
266
+ }
267
+ registry.asks.delete(askId);
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Resolve the pending registration for one delegation attempt and return the
273
+ * pre-launch binding hooks. Undefined when this attempt has no responder, in
274
+ * which case the executor keeps its original launch path.
275
+ */
276
+ export function createSupervisorLaunchHooks(
277
+ pi: ExtensionAPI,
278
+ identity: SupervisorDelegationIdentity,
279
+ getOwnerSessionId: () => string | null,
280
+ ): SupervisorLaunchHooks | undefined {
281
+ const registry = registryFor(pi, false);
282
+ if (!registry || registry.disposed) return undefined;
283
+ const liveSessionId = getOwnerSessionId();
284
+ // A REGISTERED attempt whose owner is gone or changed must fail the launch instead of
285
+ // silently returning undefined (which would start the child on the default path).
286
+ const registered = [...registry.pendingByIdentity.values()].find(
287
+ (candidate) => !candidate.disposed && candidate.scope.requestId === identity.requestId,
288
+ );
289
+ if (registered) {
290
+ if (!liveSessionId) {
291
+ throw new Error(
292
+ `Delegation attempt '${identity.requestId}' has a registered supervisor responder but no live owner session; refusing to start the child without its responder.`,
293
+ );
294
+ }
295
+ if (registered.scope.sessionId !== liveSessionId) {
296
+ throw new Error(
297
+ `Delegation attempt '${identity.requestId}' was registered for owner session '${registered.scope.sessionId}' but the live owner is '${liveSessionId}'; refusing to start the child without its responder.`,
298
+ );
299
+ }
300
+ }
301
+ if (!liveSessionId) return undefined;
302
+ const key = delegationKey(liveSessionId, identity);
303
+ const registration = registry.pendingByIdentity.get(key);
304
+ if (!registration || registration.disposed) return undefined;
305
+
306
+ let consumed = false;
307
+ return {
308
+ beforeNativeChildLaunch: (route) => {
309
+ if (consumed) {
310
+ throw new Error(
311
+ `Supervisor route for delegation attempt '${identity.requestId}' was already bound; a second child launch is not supported.`,
312
+ );
313
+ }
314
+ consumed = true;
315
+ if (registration.disposed) {
316
+ throw new Error(
317
+ `Supervisor responder for delegation attempt '${identity.requestId}' was disposed before the child launched.`,
318
+ );
319
+ }
320
+ const currentSessionId = getOwnerSessionId();
321
+ if (currentSessionId !== registration.scope.sessionId) {
322
+ throw new Error(
323
+ `Supervisor responder for delegation attempt '${identity.requestId}' belongs to session '${registration.scope.sessionId}', not the live owner '${String(currentSessionId)}'.`,
324
+ );
325
+ }
326
+ if (!Number.isInteger(route.childIndex) || route.childIndex < 0) {
327
+ throw new Error(
328
+ `Supervisor route for delegation attempt '${identity.requestId}' has an invalid childIndex '${String(route.childIndex)}'.`,
329
+ );
330
+ }
331
+ if (!route.runId.trim() || !route.agent.trim()) {
332
+ throw new Error(
333
+ `Supervisor route for delegation attempt '${identity.requestId}' is missing the real runId or canonical agent.`,
334
+ );
335
+ }
336
+ // A child without supervisor capability can never ask; leave the
337
+ // registration unbound so no ask is claimed and nothing detaches.
338
+ if (!route.bridgeActive) return;
339
+ const keyForRoute = routeKey(route.runId, route.agent, route.childIndex);
340
+ const existing = registry.byRoute.get(keyForRoute);
341
+ if (existing && existing !== registration) {
342
+ throw new Error(
343
+ `Supervisor route '${route.runId}#${route.childIndex} ${route.agent}' is already bound to another delegation attempt.`,
344
+ );
345
+ }
346
+ registration.bound = { ...route };
347
+ registry.byRoute.set(keyForRoute, registration);
348
+ registry.pendingByIdentity.delete(identityKey(registration.scope));
349
+ },
350
+ release: () => {
351
+ disposeRegistration(registry, identityKey(registration.scope), registration);
352
+ },
353
+ };
354
+ }
355
+
356
+ /**
357
+ * Owner-side ask dispatcher used by the native supervisor channel. A claimed
358
+ * ask never falls back to native wake/detach, even when it fails.
359
+ */
360
+ export function createSupervisorDispatcher(
361
+ pi: ExtensionAPI,
362
+ getOwnerSessionId: () => string | null,
363
+ ): SupervisorDispatcher {
364
+ const fail = (ask: AskRecord, code: string, message: string): void => {
365
+ if (ask.state === "delivered" || ask.state === "failed" || ask.state === "cancelled") return;
366
+ ask.state = "failed";
367
+ ask.controller.abort();
368
+ const registration = ask.registration;
369
+ if (registration.failureNotified) return;
370
+ registration.failureNotified = true;
371
+ // `code` and `message` are already bounded/fixed by the callers above.
372
+ const error = new Error(`${code}: ${safeMessage(message, "supervisor responder failed")}`);
373
+ (error as Error & { code?: string }).code = code;
374
+ try {
375
+ registration.onFailure?.(error);
376
+ } catch {
377
+ // The audit's own cancellation path owns its diagnostics; a throwing
378
+ // callback must not crash the native channel's poll loop.
379
+ }
380
+ };
381
+
382
+ const run = (ask: AskRecord, input: SupervisorAskInput, deliver: (message: string) => void): void => {
383
+ const registration = ask.registration;
384
+ ask.state = "running";
385
+ const request: SupervisorResponderRequest = {
386
+ requestId: input.askId,
387
+ reason: input.reason,
388
+ message: input.message,
389
+ ...(input.interview !== undefined ? { interview: input.interview } : {}),
390
+ runId: input.runId,
391
+ agent: input.agent,
392
+ childIndex: input.childIndex,
393
+ ...(input.deadlineAt !== undefined ? { deadlineAt: input.deadlineAt } : {}),
394
+ signal: ask.controller.signal,
395
+ };
396
+ void Promise.resolve()
397
+ .then(() => registration.respond(request))
398
+ .then((outcome: SupervisorResponderOutcome) => {
399
+ if (ask.state === "cancelled" || ask.state === "failed") return;
400
+ if (!outcome || typeof outcome !== "object") {
401
+ fail(ask, "invalid_outcome", "responder returned no outcome");
402
+ return;
403
+ }
404
+ if (outcome.kind === "error") {
405
+ fail(ask, safeMessage(outcome.code, "responder_error"), outcome.message);
406
+ return;
407
+ }
408
+ if (outcome.kind !== "reply" || typeof outcome.message !== "string") {
409
+ fail(ask, "invalid_outcome", "responder returned an unsupported outcome shape");
410
+ return;
411
+ }
412
+ const message = outcome.message.trim();
413
+ if (!message) {
414
+ fail(ask, "empty_reply", "responder returned an empty reply");
415
+ return;
416
+ }
417
+ if (byteLength(message) > MAX_SUPERVISOR_RESPONDER_REPLY_BYTES) {
418
+ fail(ask, "reply_too_large", `reply exceeds ${MAX_SUPERVISOR_RESPONDER_REPLY_BYTES} bytes`);
419
+ return;
420
+ }
421
+ if (ask.controller.signal.aborted) {
422
+ fail(ask, "cancelled", "ask was cancelled before delivery");
423
+ return;
424
+ }
425
+ try {
426
+ deliver(message);
427
+ } catch (error) {
428
+ // The native write failed; the underlying exception text must not cross
429
+ // this boundary (diagnostics never echo external exception bodies).
430
+ void error;
431
+ fail(ask, "delivery_failed", "the native supervisor reply could not be written");
432
+ return;
433
+ }
434
+ ask.state = "delivered";
435
+ ask.delivered = true;
436
+ })
437
+ .catch((error: unknown) => {
438
+ // Same boundary rule for a responder rejection: fixed text only.
439
+ void error;
440
+ fail(ask, "responder_error", "the supervisor responder failed");
441
+ });
442
+ };
443
+
444
+ return {
445
+ claim: (input, deliver) => {
446
+ const registry = registryFor(pi, false);
447
+ if (!registry || registry.disposed) return false;
448
+ const registration = registry.byRoute.get(routeKey(input.runId, input.agent, input.childIndex));
449
+ if (!registration || registration.disposed) return false;
450
+ const liveSessionId = getOwnerSessionId();
451
+ if (liveSessionId !== registration.scope.sessionId) {
452
+ // A bound route whose owner session is gone must fail closed: the
453
+ // audit is already orphaned and must never be answered by a stale
454
+ // responder or handed back to the native wake/detach path.
455
+ const orphan: AskRecord = {
456
+ askId: input.askId,
457
+ state: "claimed",
458
+ registration,
459
+ controller: new AbortController(),
460
+ delivered: false,
461
+ };
462
+ registry.asks.set(input.askId, orphan);
463
+ fail(orphan, "owner_session_changed", "supervisor owner session changed during the audit");
464
+ return true;
465
+ }
466
+ const existing = registry.asks.get(input.askId);
467
+ if (existing) {
468
+ // Duplicate observation of the same ask: reuse in-flight handling and
469
+ // never re-prompt the responder or rewrite the reply.
470
+ return true;
471
+ }
472
+ const ask: AskRecord = {
473
+ askId: input.askId,
474
+ state: "claimed",
475
+ registration,
476
+ controller: new AbortController(),
477
+ delivered: false,
478
+ };
479
+ registry.asks.set(input.askId, ask);
480
+ run(ask, input, deliver);
481
+ return true;
482
+ },
483
+ observe: (askId, lifecycle) => {
484
+ const registry = registryFor(pi, false);
485
+ if (!registry) return;
486
+ const ask = registry.asks.get(askId);
487
+ if (!ask) return;
488
+ if (ask.state === "delivered") {
489
+ // A delivered reply removes the request file, so "missing" here is the
490
+ // expected post-delivery observation and must not fail the audit.
491
+ return;
492
+ }
493
+ if (lifecycle === "resolved") {
494
+ ask.state = "delivered";
495
+ ask.delivered = true;
496
+ ask.controller.abort();
497
+ return;
498
+ }
499
+ fail(ask, `ask_${lifecycle.replace("-", "_")}`, `supervisor ask became ${lifecycle}`);
500
+ },
501
+ };
502
+ }
503
+
504
+ /**
505
+ * Release every registration owned by this ExtensionAPI whose session is no
506
+ * longer live (owner session reset, session tree switch, shutdown).
507
+ */
508
+ export function disposeSupervisorRoutingForOwner(pi: ExtensionAPI, liveSessionId: string | null): void {
509
+ const registry = registryFor(pi, false);
510
+ if (!registry) return;
511
+ for (const [key, registration] of [...registry.registrations]) {
512
+ if (liveSessionId && registration.scope.sessionId === liveSessionId) continue;
513
+ disposeRegistration(registry, key, registration);
514
+ }
515
+ }
516
+
517
+ /** Full teardown used by the owning extension on shutdown. */
518
+ export function disposeSupervisorRouting(pi: ExtensionAPI): void {
519
+ const registry = registryFor(pi, false);
520
+ if (!registry) return;
521
+ registry.disposed = true;
522
+ for (const [key, registration] of [...registry.registrations]) {
523
+ disposeRegistration(registry, key, registration);
524
+ }
525
+ for (const ask of registry.asks.values()) {
526
+ if (ask.state === "claimed" || ask.state === "running") {
527
+ ask.state = "cancelled";
528
+ ask.controller.abort();
529
+ }
530
+ }
531
+ registry.asks.clear();
532
+ registries.delete(pi);
533
+ }