@xzzpig/pi-subagents 0.21.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.
- package/CHANGELOG.md +10 -0
- package/docs/fork-supervisor-routing.md +77 -0
- package/package.json +2 -1
- package/src/api/supervisor-routing.ts +196 -0
- package/src/extension/index.ts +29 -2
- package/src/intercom/fork-supervisor-routing.ts +533 -0
- package/src/intercom/native-supervisor-channel.ts +75 -9
- package/src/runs/foreground/subagent-executor.ts +25 -0
- package/src/slash/prompt-template-bridge.ts +21 -20
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.22.0]
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- 新增 `@xzzpig/pi-subagents/supervisor-routing` 导出:版本化的父会话内 supervisor 响应器注册
|
|
8
|
+
(`registerSupervisorResponderViaEvents`),作用域为 sessionId + delegation requestId + ownerRunId + nodeId + agent。
|
|
9
|
+
- 结构化委派执行器新增内部 launch hooks:在真实 foreground runId 分配、canonical agent 解析之后、
|
|
10
|
+
任何 child prompt 之前触发 `beforeNativeChildLaunch`,不改变模型可见的 request schema 或子进程环境。
|
|
11
|
+
- 原生 supervisor 通道支持独占接管:被接管的提问不再唤醒主模型、不再触发 detach,回复仍走文件权威写入。
|
|
12
|
+
|
|
3
13
|
## [Unreleased]
|
|
4
14
|
|
|
5
15
|
## [0.21.0] - 2026-10-10 (fork)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Fork:监督请求路由(supervisor responder routing)
|
|
2
|
+
|
|
3
|
+
本文说明 pi-subagents 在本仓库中新增的 **fork-only** 接入:让父扩展按「精确的一次委派尝试」登记一个只读 responder,从而在该尝试的 supervisor 提问到来时**独占接管**,不唤醒主模型、不触发 detach。
|
|
4
|
+
|
|
5
|
+
上游(upstream)语义保持不变:普通 subagent / workflow 的监督行为、终态枚举、detach 状态转换与模型可见的工具 schema 都没有改动。
|
|
6
|
+
|
|
7
|
+
## 新增文件
|
|
8
|
+
|
|
9
|
+
| 文件 | 作用 |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| `src/api/supervisor-routing.ts` | 版本化父扩展 API:事件常量、类型、scope 校验、客户端调用 |
|
|
12
|
+
| `src/intercom/fork-supervisor-routing.ts` | 按 owner 分域的登记表、启动前绑定、接管 dispatcher、回复与清理 |
|
|
13
|
+
|
|
14
|
+
`package.json` 增加 `./supervisor-routing` 导出;**不提升版本**,不新增依赖。
|
|
15
|
+
|
|
16
|
+
## API
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import {
|
|
20
|
+
SUPERVISOR_RESPONDER_REGISTER_EVENT, // pi-subagents:supervisor-responder-register:v1
|
|
21
|
+
registerSupervisorResponderViaEvents, // ({ pi, scope, respond, onFailure }) => { dispose() }
|
|
22
|
+
type SupervisorResponderScope, // sessionId + requestId + ownerRunId + nodeId + agent
|
|
23
|
+
type SupervisorResponderRequest, // requestId(提问 id) + reason + message + interview? + runId + agent + childIndex + deadlineAt + signal
|
|
24
|
+
type SupervisorResponderOutcome, // { kind:"reply", message } | { kind:"error", code, message }
|
|
25
|
+
} from "@xzzpig/pi-subagents/supervisor-routing";
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
契约要点:
|
|
29
|
+
|
|
30
|
+
* 复用 `runtime-agent-events.ts` 的**同步回执**模式:发出请求后立刻读回 `request.result`。owner 缺失、版本不支持、`ok:false` 或回执畸形都会抛出可执行的 Error;`dispose()` 幂等。
|
|
31
|
+
* **只接受完整 scope**:五个字段都必须是去空白后非空、长度 ≤ 256 且不含 CR/LF 的字符串;`agent === "*"` 被明确拒绝(禁止「仅按 agent 名接管」)。
|
|
32
|
+
* 同一 scope 重复登记被拒绝;旧 handle 的 `dispose()` 只移除自己。
|
|
33
|
+
|
|
34
|
+
## 启动前绑定(唯一的身份来源)
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
runGoalCompletionAuditor
|
|
38
|
+
→ 生成身份三元组并登记(scope = sessionId + requestId + ownerRunId + nodeId + agent)
|
|
39
|
+
prompt-template-bridge.ts
|
|
40
|
+
→ executeStructured 增加内部可选第 6 参数 request(仅当完整请求解析通过时传入)
|
|
41
|
+
extension/index.ts
|
|
42
|
+
→ 由完整 scope 得到 launch hooks,作为可选第 6 参数传给 executeDelegated
|
|
43
|
+
subagent-executor.ts
|
|
44
|
+
→ createSubagentExecutor 用 WeakMap 存 hooks;在真实 runId 分配、canonical agent 解析之后、
|
|
45
|
+
任何 child prompt 或工具启动之前调用 beforeNativeChildLaunch(runId, agent, childIndex=0,
|
|
46
|
+
parentSessionId, bridgeActive)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
绑定规则:
|
|
50
|
+
|
|
51
|
+
* 必须使用执行器**已解析的 canonical agent**,请求里的别名不能作为路由;不得从 child 自报字段推断;
|
|
52
|
+
* scope 只绑定一次;路由冲突、身份变化、已释放的登记、非法的 childIndex、空的 runId/agent 都在**任何模型调用之前**失败;
|
|
53
|
+
* `bridgeActive` 为 false 时不绑定,保持原行为。
|
|
54
|
+
|
|
55
|
+
## 独占接管
|
|
56
|
+
|
|
57
|
+
native supervisor channel 的 poll 在完成 owner / lifecycle 校验并写入 pending 之后、`parentWake.sendMessage` 与 detach 事件之前调用 dispatcher:
|
|
58
|
+
|
|
59
|
+
* claim 返回同步布尔值;命中时跳过默认唤醒与 detach,**不 await 模型**,因此不会阻塞其他通道扫描;
|
|
60
|
+
* 同一提问 id 的重复观察复用现有处理,不重复提问也不重复写回复;
|
|
61
|
+
* `progress_update` 保持原有快速路径;
|
|
62
|
+
* 其他路由保持原有的 pending + 唤醒 + detach 行为;
|
|
63
|
+
* 被接管的提问**不会**产生主模型提醒;通用 `subagent_supervisor` 的 reply 动作对被接管的提问返回明确错误(`responder-managed`)。
|
|
64
|
+
|
|
65
|
+
回复写入复用通道自身的 `writeReply` + `appendSupervisorReplyEntry`,并且在写之前重新确认:pending 请求仍存在、尚无回复文件、路由 owner 与 generation 仍有效、时间未过期。文件写入成功即为投递依据;journal 失败仍遵循既有「文件为准、最佳努力」策略,不撤回已写入的回复。
|
|
66
|
+
|
|
67
|
+
## 失败与清理
|
|
68
|
+
|
|
69
|
+
* claim 后启动、回答、投递或过期任一环节出错:先锁定 failed,再对同一 scope **至多一次**调用 `onFailure`,由父侧取消该次审计;绝不回退到默认通知或 detach,也绝不把错误当成「无人接管」;
|
|
70
|
+
* native 通道清理已不在 pending 的请求时会通知 dispatcher:已解决的保持 delivered,过期/不活跃/缺失则使未完成的模型请求失效并取消;
|
|
71
|
+
* owner session 重置、shutdown、reload 或登记 `dispose()` 都会释放绑定;普通(未登记)的调用保持原有行为。
|
|
72
|
+
|
|
73
|
+
## 与上游的关系(fork-divergence)
|
|
74
|
+
|
|
75
|
+
* 新增逻辑都在 fork-only 文件里;上游文件只保留**最小 seam**:结构化委派的第六参数、执行器内部的启动钩子、native 通道的 dispatcher 挂点,以及 `package.json` 的一个导出条目;
|
|
76
|
+
* 上游文件保持字节稳定,不做格式化,不手改 lockfile;
|
|
77
|
+
* 具体 seam 与 replay 记录见 `subtrees/pi-subagents.json` 的 `reapplyOnSync`;不为此新增 fork-only 模块填写维护债务。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xzzpig/pi-subagents",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.0",
|
|
4
4
|
"description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
|
|
5
5
|
"author": "Nico Bailon",
|
|
6
6
|
"license": "MIT",
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
"./external-job-provider": "./src/api/external-job-provider.ts",
|
|
12
12
|
"./external-runs": "./src/api/external-runs.ts",
|
|
13
13
|
"./agents": "./src/api/agents.ts",
|
|
14
|
+
"./supervisor-routing": "./src/api/supervisor-routing.ts",
|
|
14
15
|
"./inspectors": "./src/api/inspectors.ts",
|
|
15
16
|
"./delegation": "./src/api/delegation.ts",
|
|
16
17
|
"./capability-ceiling": "./src/api/capability-ceiling.ts",
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Versioned cross-extension supervisor-responder routing API (fork-only).
|
|
3
|
+
*
|
|
4
|
+
* A consumer extension (pi-goal-x's completion audit) registers one responder
|
|
5
|
+
* for ONE exact delegation attempt before the request is emitted. The
|
|
6
|
+
* pi-subagents owner binds that registration to the real child route (runId +
|
|
7
|
+
* canonical agent + childIndex) before the child's first prompt, and then
|
|
8
|
+
* hands that attempt's `need_decision` / `interview_request` asks to the
|
|
9
|
+
* responder instead of waking the parent model or detaching the child.
|
|
10
|
+
*
|
|
11
|
+
* The registration travels through the same synchronous, in-process event
|
|
12
|
+
* contract as `runtime-agent-events.ts`: the client emits a request object and
|
|
13
|
+
* reads the owner's result back out of that same object, so an owner that is
|
|
14
|
+
* missing, not ready, or older than this API fails closed with an actionable
|
|
15
|
+
* error instead of silently degrading to native wake/detach.
|
|
16
|
+
*
|
|
17
|
+
* This module is deliberately types + constants + the client call only. The
|
|
18
|
+
* owner-side registry, launch binding and ask dispatcher live in
|
|
19
|
+
* `../intercom/fork-supervisor-routing.ts` so the model-facing surface stays
|
|
20
|
+
* unchanged.
|
|
21
|
+
*/
|
|
22
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
23
|
+
|
|
24
|
+
export const SUPERVISOR_RESPONDER_REGISTER_EVENT = "pi-subagents:supervisor-responder-register:v1";
|
|
25
|
+
export const SUPERVISOR_RESPONDER_REGISTER_VERSION = 1;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Identity of the one delegation attempt a responder owns.
|
|
29
|
+
*
|
|
30
|
+
* `requestId` is the DELEGATION attempt id (the id the structured delegation
|
|
31
|
+
* request was emitted with), never the supervisor ask id. `agent` is the agent
|
|
32
|
+
* name the request asked for; the owner binds the canonical resolved agent
|
|
33
|
+
* separately, so an alias can never be used to take over another agent's asks.
|
|
34
|
+
*/
|
|
35
|
+
export interface SupervisorResponderScope {
|
|
36
|
+
sessionId: string;
|
|
37
|
+
requestId: string;
|
|
38
|
+
ownerRunId: string;
|
|
39
|
+
nodeId: string;
|
|
40
|
+
agent: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type SupervisorResponderReason = "need_decision" | "interview_request" | "progress_update";
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* One supervisor ask routed to a responder.
|
|
47
|
+
*
|
|
48
|
+
* `requestId` here is the ASK id (the native supervisor request id); consumers
|
|
49
|
+
* that keep a coordination record rename it to `supervisorRequestId` to keep it
|
|
50
|
+
* distinct from `SupervisorResponderScope.requestId`.
|
|
51
|
+
*/
|
|
52
|
+
export interface SupervisorResponderRequest {
|
|
53
|
+
requestId: string;
|
|
54
|
+
reason: SupervisorResponderReason;
|
|
55
|
+
message: string;
|
|
56
|
+
interview?: unknown;
|
|
57
|
+
runId: string;
|
|
58
|
+
agent: string;
|
|
59
|
+
childIndex: number;
|
|
60
|
+
/** Absolute deadline for this ask; absent means only the audit deadline applies. */
|
|
61
|
+
deadlineAt?: number;
|
|
62
|
+
signal: AbortSignal;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export type SupervisorResponderOutcome =
|
|
66
|
+
| { kind: "reply"; message: string }
|
|
67
|
+
| { kind: "error"; code: string; message: string };
|
|
68
|
+
|
|
69
|
+
export type SupervisorResponder = (
|
|
70
|
+
request: SupervisorResponderRequest,
|
|
71
|
+
) => SupervisorResponderOutcome | Promise<SupervisorResponderOutcome>;
|
|
72
|
+
|
|
73
|
+
/** Owner-side handle returned through the registration event. */
|
|
74
|
+
export interface SupervisorResponderRegistration {
|
|
75
|
+
/** Idempotent; removes only this registration. */
|
|
76
|
+
dispose(): void;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type SupervisorResponderRegistrationResult =
|
|
80
|
+
| { ok: true; registration: SupervisorResponderRegistration }
|
|
81
|
+
| { ok: false; error: Error };
|
|
82
|
+
|
|
83
|
+
export interface SupervisorResponderRegistrationRequest {
|
|
84
|
+
version: 1;
|
|
85
|
+
scope: SupervisorResponderScope;
|
|
86
|
+
respond: SupervisorResponder;
|
|
87
|
+
/** Called at most once per scope when a claimed ask cannot be answered or delivered. */
|
|
88
|
+
onFailure?: (error: Error) => void;
|
|
89
|
+
result?: SupervisorResponderRegistrationResult;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface RegisterSupervisorResponderViaEventsInput {
|
|
93
|
+
pi: Pick<ExtensionAPI, "events">;
|
|
94
|
+
scope: SupervisorResponderScope;
|
|
95
|
+
respond: SupervisorResponder;
|
|
96
|
+
onFailure?: (error: Error) => void;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const MAX_IDENTITY_LENGTH = 256;
|
|
100
|
+
const IDENTITY_FIELDS = ["sessionId", "requestId", "ownerRunId", "nodeId", "agent"] as const;
|
|
101
|
+
|
|
102
|
+
function identityError(field: string, reason: string): string {
|
|
103
|
+
return `Supervisor responder scope.${field} ${reason}.`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Validate a scope strictly: every identity field must be present, non-empty,
|
|
108
|
+
* CR/LF-free and within the delegation identity byte budget. A scope that only
|
|
109
|
+
* names an agent (the "take over every ask of this agent" shape) is refused.
|
|
110
|
+
*/
|
|
111
|
+
export function validateSupervisorResponderScope(
|
|
112
|
+
scope: unknown,
|
|
113
|
+
): { scope: SupervisorResponderScope } | { error: string } {
|
|
114
|
+
if (!scope || typeof scope !== "object" || Array.isArray(scope)) {
|
|
115
|
+
return { error: "Supervisor responder scope must be an object." };
|
|
116
|
+
}
|
|
117
|
+
const candidate = scope as Record<string, unknown>;
|
|
118
|
+
for (const field of IDENTITY_FIELDS) {
|
|
119
|
+
const value = candidate[field];
|
|
120
|
+
if (typeof value !== "string") return { error: identityError(field, "must be a string") };
|
|
121
|
+
if (!value.trim()) return { error: identityError(field, "must not be empty") };
|
|
122
|
+
if (value.length > MAX_IDENTITY_LENGTH) {
|
|
123
|
+
return { error: identityError(field, `must be at most ${MAX_IDENTITY_LENGTH} characters`) };
|
|
124
|
+
}
|
|
125
|
+
if (/[\r\n]/.test(value)) return { error: identityError(field, "must not contain CR or LF") };
|
|
126
|
+
}
|
|
127
|
+
if (candidate.agent === "*") {
|
|
128
|
+
return { error: "Supervisor responder scope.agent must name one agent; wildcard takeover is not supported." };
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
scope: {
|
|
132
|
+
sessionId: candidate.sessionId as string,
|
|
133
|
+
requestId: candidate.requestId as string,
|
|
134
|
+
ownerRunId: candidate.ownerRunId as string,
|
|
135
|
+
nodeId: candidate.nodeId as string,
|
|
136
|
+
agent: candidate.agent as string,
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function errorFrom(value: unknown): Error {
|
|
142
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Register a responder for one exact delegation attempt through the installed
|
|
147
|
+
* pi-subagents owner in this Pi process. Throws an actionable error when the
|
|
148
|
+
* owner is missing, older than this API, or refuses the registration.
|
|
149
|
+
*/
|
|
150
|
+
export function registerSupervisorResponderViaEvents(
|
|
151
|
+
input: RegisterSupervisorResponderViaEventsInput,
|
|
152
|
+
): SupervisorResponderRegistration {
|
|
153
|
+
const validated = validateSupervisorResponderScope(input.scope);
|
|
154
|
+
if ("error" in validated) throw new Error(validated.error);
|
|
155
|
+
if (typeof input.respond !== "function") {
|
|
156
|
+
throw new Error("Supervisor responder must be a function: (request) => outcome.");
|
|
157
|
+
}
|
|
158
|
+
if (input.onFailure !== undefined && typeof input.onFailure !== "function") {
|
|
159
|
+
throw new Error("Supervisor responder onFailure must be a function when provided.");
|
|
160
|
+
}
|
|
161
|
+
const request: SupervisorResponderRegistrationRequest = {
|
|
162
|
+
version: SUPERVISOR_RESPONDER_REGISTER_VERSION,
|
|
163
|
+
scope: validated.scope,
|
|
164
|
+
respond: input.respond,
|
|
165
|
+
...(input.onFailure ? { onFailure: input.onFailure } : {}),
|
|
166
|
+
};
|
|
167
|
+
input.pi.events.emit(SUPERVISOR_RESPONDER_REGISTER_EVENT, request);
|
|
168
|
+
const result = request.result as unknown;
|
|
169
|
+
if (result === undefined) {
|
|
170
|
+
throw new Error(
|
|
171
|
+
"pi-subagents is not installed, not ready, or does not support supervisor responder event registration.",
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
if (result && typeof result === "object" && !Array.isArray(result)) {
|
|
175
|
+
const candidate = result as Record<string, unknown>;
|
|
176
|
+
if (
|
|
177
|
+
candidate.ok === true &&
|
|
178
|
+
candidate.registration &&
|
|
179
|
+
typeof candidate.registration === "object" &&
|
|
180
|
+
typeof (candidate.registration as { dispose?: unknown }).dispose === "function"
|
|
181
|
+
) {
|
|
182
|
+
const registration = candidate.registration as SupervisorResponderRegistration;
|
|
183
|
+
let disposed = false;
|
|
184
|
+
return {
|
|
185
|
+
dispose: () => {
|
|
186
|
+
if (disposed) return;
|
|
187
|
+
disposed = true;
|
|
188
|
+
registration.dispose();
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
if (candidate.ok === false && candidate.error instanceof Error) throw candidate.error;
|
|
193
|
+
if (candidate.ok === false) throw errorFrom(candidate.error);
|
|
194
|
+
}
|
|
195
|
+
throw new Error("pi-subagents returned a malformed supervisor responder registration result.");
|
|
196
|
+
}
|
package/src/extension/index.ts
CHANGED
|
@@ -26,6 +26,13 @@ import { mergeAgentsForScope } from "../agents/agent-selection.ts";
|
|
|
26
26
|
import { clearRuntimeAgentsForPi, listRuntimeAgentConfigs, mergeRuntimeAgents } from "../agents/runtime-agent-registry.ts";
|
|
27
27
|
import { discoverAgentsWithRuntime } from "../agents/runtime-discovery.ts";
|
|
28
28
|
import { registerRuntimeAgentEventListener } from "../agents/runtime-agent-events.ts";
|
|
29
|
+
import {
|
|
30
|
+
createSupervisorDispatcher,
|
|
31
|
+
createSupervisorLaunchHooks,
|
|
32
|
+
disposeSupervisorRouting,
|
|
33
|
+
disposeSupervisorRoutingForOwner,
|
|
34
|
+
registerSupervisorResponderEventListener,
|
|
35
|
+
} from "../intercom/fork-supervisor-routing.ts";
|
|
29
36
|
import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
|
|
30
37
|
import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.ts";
|
|
31
38
|
import { resolveCurrentSessionId } from "../shared/session-identity.ts";
|
|
@@ -354,6 +361,9 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
354
361
|
// Owner states are created only by scheduled execution, which loads the executor first.
|
|
355
362
|
getCurrentOwnerStates: () => executor?.getCurrentSupervisorOwnerStates() ?? [],
|
|
356
363
|
parentWake,
|
|
364
|
+
// Exclusive takeover for registered responder routes; unregistered routes
|
|
365
|
+
// keep the native wake/detach path untouched.
|
|
366
|
+
supervisorDispatcher: createSupervisorDispatcher(pi, () => state.supervisorOwnerSessionId ?? null),
|
|
357
367
|
});
|
|
358
368
|
const waitSubscriptionManager = createWaitSubscriptionManager(wakingPi, state);
|
|
359
369
|
const mainWatchdog = registerMainWatchdog(pi);
|
|
@@ -647,10 +657,22 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
647
657
|
getContext: () => state.lastUiContext,
|
|
648
658
|
execute: (requestId, params, signal, ctx, onUpdate) =>
|
|
649
659
|
executeSubagentCollapsed(requestId, params, signal, onUpdate, ctx),
|
|
650
|
-
executeStructured: async (requestId, params, signal, ctx, onUpdate) => {
|
|
660
|
+
executeStructured: async (requestId, params, signal, ctx, onUpdate, request) => {
|
|
651
661
|
if (ctx.hasUI) ctx.ui.setToolsExpanded(false);
|
|
652
662
|
await waitForAdvertisement();
|
|
653
|
-
|
|
663
|
+
// The responder is bound to the REAL child route (runId + canonical
|
|
664
|
+
// agent + index) inside the executor, before the first prompt. Passing
|
|
665
|
+
// it here keeps callbacks out of model parameters, artifacts and child
|
|
666
|
+
// env; an unregistered attempt gets no hooks and keeps default behaviour.
|
|
667
|
+
const supervisorLaunchHooks = request
|
|
668
|
+
? createSupervisorLaunchHooks(pi, {
|
|
669
|
+
requestId: request.requestId,
|
|
670
|
+
ownerRunId: request.ownerRunId,
|
|
671
|
+
nodeId: request.nodeId,
|
|
672
|
+
agent: request.agent,
|
|
673
|
+
}, () => state.supervisorOwnerSessionId ?? null)
|
|
674
|
+
: undefined;
|
|
675
|
+
return (await getExecutor()).executeDelegated(requestId, params, signal, onUpdate, ctx, supervisorLaunchHooks);
|
|
654
676
|
},
|
|
655
677
|
});
|
|
656
678
|
|
|
@@ -819,6 +841,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
819
841
|
};
|
|
820
842
|
const eventUnsubscribes = [
|
|
821
843
|
registerRuntimeAgentEventListener(pi),
|
|
844
|
+
registerSupervisorResponderEventListener(pi, () => state.supervisorOwnerSessionId ?? null),
|
|
822
845
|
registerInspectorEventListener(pi),
|
|
823
846
|
pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, asyncStartedHandler),
|
|
824
847
|
pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, asyncCompleteHandler),
|
|
@@ -891,6 +914,9 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
891
914
|
resultDeliveryOwnership.claimPredecessor(previousSessionFile, previousRuntimeSessionId);
|
|
892
915
|
state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
|
|
893
916
|
state.supervisorOwnerSessionId = ctx.sessionManager.getSessionId() || null;
|
|
917
|
+
// A responder binding belongs to one exact runtime session; a reset or
|
|
918
|
+
// tree switch must release every registration that is no longer live.
|
|
919
|
+
disposeSupervisorRoutingForOwner(pi, state.supervisorOwnerSessionId);
|
|
894
920
|
transitionResultDelivery();
|
|
895
921
|
owedResultRunIds.clear();
|
|
896
922
|
deliveredRunIds.clear();
|
|
@@ -1048,6 +1074,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
1048
1074
|
state.widgetsSuspended = false;
|
|
1049
1075
|
state.currentSessionId = null;
|
|
1050
1076
|
state.supervisorOwnerSessionId = null;
|
|
1077
|
+
disposeSupervisorRouting(pi);
|
|
1051
1078
|
state.statusProjectionSessionId = null;
|
|
1052
1079
|
state.parentSessionFile = null;
|
|
1053
1080
|
if (runtimeEntry.sessionManager && runtimeRegistry.bySessionManager.get(runtimeEntry.sessionManager) === runtimeEntry) {
|
|
@@ -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
|
+
}
|
|
@@ -6,6 +6,7 @@ import type { AgentBeforeSettleEvent, AgentBeforeSettleEventResult, ExtensionAPI
|
|
|
6
6
|
import { Type } from "typebox";
|
|
7
7
|
import type { ChildSupervisorMetadata } from "../runs/shared/child-runtime-config.ts";
|
|
8
8
|
import { INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, TEMP_ROOT_DIR, type ControlEvent, type IntercomEventBus, type SubagentState } from "../shared/types.ts";
|
|
9
|
+
import type { SupervisorDispatcher } from "./fork-supervisor-routing.ts";
|
|
9
10
|
import { writeAtomicJson } from "../shared/atomic-json.ts";
|
|
10
11
|
import { shouldUseNativeFsWatch } from "../shared/watch-strategy.ts";
|
|
11
12
|
import { MODEL_ONLY_TOOL } from "../shared/extension-context.ts";
|
|
@@ -89,6 +90,12 @@ interface NativeSupervisorChannelDeps {
|
|
|
89
90
|
/** Retained scheduled states for the current runtime owner, never foreign owners. */
|
|
90
91
|
getCurrentOwnerStates?: () => Iterable<SubagentState>;
|
|
91
92
|
parentWake?: Pick<ExtensionAPI, "sendMessage">;
|
|
93
|
+
/**
|
|
94
|
+
* Owner-side responder dispatcher. When a registered responder claims an ask,
|
|
95
|
+
* this channel skips the parent wake and detach emission for that ask and
|
|
96
|
+
* never lets a generic reply overwrite it. Unset means default behaviour.
|
|
97
|
+
*/
|
|
98
|
+
supervisorDispatcher?: SupervisorDispatcher;
|
|
92
99
|
platform?: NodeJS.Platform;
|
|
93
100
|
watch?: SupervisorWatch;
|
|
94
101
|
timers?: Pick<typeof globalThis, "setInterval" | "clearInterval" | "setImmediate" | "clearImmediate">;
|
|
@@ -177,8 +184,15 @@ async function waitForReply(channelDir: string, requestId: string, deadline: num
|
|
|
177
184
|
while (Date.now() <= deadline) {
|
|
178
185
|
if (signal?.aborted) throw new Error("Supervisor request cancelled.");
|
|
179
186
|
if (fs.existsSync(file)) {
|
|
180
|
-
|
|
181
|
-
|
|
187
|
+
let parsed: Partial<SupervisorReply> | undefined;
|
|
188
|
+
try {
|
|
189
|
+
parsed = JSON.parse(fs.readFileSync(file, "utf-8")) as Partial<SupervisorReply>;
|
|
190
|
+
} catch {
|
|
191
|
+
// A partially written or corrupt reply file must not crash the child;
|
|
192
|
+
// keep polling until the deadline instead.
|
|
193
|
+
parsed = undefined;
|
|
194
|
+
}
|
|
195
|
+
if (parsed && parsed.type === "subagent.supervisor.reply" && parsed.requestId === requestId && typeof parsed.message === "string") {
|
|
182
196
|
return parsed as SupervisorReply;
|
|
183
197
|
}
|
|
184
198
|
}
|
|
@@ -529,7 +543,11 @@ function writeReply(request: PendingSupervisorRequest, message: string): Supervi
|
|
|
529
543
|
return reply;
|
|
530
544
|
}
|
|
531
545
|
|
|
532
|
-
|
|
546
|
+
/** Internal: exported so the journal-failure content oracle can exercise the real boundary. */
|
|
547
|
+
export function appendSupervisorReplyEntry(pi: ExtensionAPI, request: PendingSupervisorRequest, reply: SupervisorReply): void {
|
|
548
|
+
// SAFETY: newer hosts expose appendEntry on ExtensionAPI while older SDK
|
|
549
|
+
// typings omit it. The narrowed shape is optional and every use below is
|
|
550
|
+
// guarded by a typeof check, so no unchecked property is read.
|
|
533
551
|
const appendEntry = (pi as unknown as {
|
|
534
552
|
appendEntry?: (customType: string, data?: SupervisorReplyEntryData) => void;
|
|
535
553
|
}).appendEntry;
|
|
@@ -545,9 +563,10 @@ function appendSupervisorReplyEntry(pi: ExtensionAPI, request: PendingSupervisor
|
|
|
545
563
|
message: reply.message,
|
|
546
564
|
createdAt: reply.createdAt,
|
|
547
565
|
});
|
|
548
|
-
} catch
|
|
566
|
+
} catch {
|
|
549
567
|
// The reply file is authoritative; a UI journal failure must not undo a delivered reply.
|
|
550
|
-
|
|
568
|
+
// Fixed text only: an external exception body/stack must never reach diagnostics.
|
|
569
|
+
console.error("Failed to journal native supervisor reply: error details omitted");
|
|
551
570
|
}
|
|
552
571
|
}
|
|
553
572
|
|
|
@@ -585,7 +604,7 @@ function publicPendingRequests(pending: Map<string, PendingSupervisorRequest>):
|
|
|
585
604
|
}));
|
|
586
605
|
}
|
|
587
606
|
|
|
588
|
-
function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, PendingSupervisorRequest>, state: SubagentState, onLifecycle: SupervisorRequestLifecycleObserver, discover: () => void, runState: (request: SupervisorRequest) => SubagentState): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
|
|
607
|
+
function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, PendingSupervisorRequest>, state: SubagentState, onLifecycle: SupervisorRequestLifecycleObserver, discover: () => void, runState: (request: SupervisorRequest) => SubagentState, isClaimed: (requestId: string) => boolean = () => false): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
|
|
589
608
|
return {
|
|
590
609
|
name: NATIVE_SUPERVISOR_TOOL_NAME,
|
|
591
610
|
...MODEL_ONLY_TOOL,
|
|
@@ -601,11 +620,16 @@ function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, Pendin
|
|
|
601
620
|
return { content: [{ type: "text", text: `Native supervisor channel active. Pending replies: ${pending.size}.` }], details: { active: true, pending: pending.size, root: SUPERVISOR_CHANNEL_ROOT } };
|
|
602
621
|
}
|
|
603
622
|
if (input.action === "pending" || input.action === "list") {
|
|
604
|
-
|
|
605
|
-
|
|
623
|
+
// Responder-managed asks are not the parent model's to answer.
|
|
624
|
+
const answerable = [...pending.values()].filter((request) => request.expectsReply && !isClaimed(request.id));
|
|
625
|
+
const lines = answerable.map(formatPendingLine);
|
|
626
|
+
return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No pending supervisor requests." }], details: { pending: publicPendingRequests(new Map(answerable.map((request) => [request.id, request]))) } };
|
|
606
627
|
}
|
|
607
628
|
if (input.action === "reply") {
|
|
608
629
|
const request = resolvePendingRequest(pending, input);
|
|
630
|
+
if (isClaimed(request.id)) {
|
|
631
|
+
throw new Error(`Supervisor request ${request.id} is responder-managed; it can only be answered by its registered responder.`);
|
|
632
|
+
}
|
|
609
633
|
const reply = writeReply(request, input.message ?? "");
|
|
610
634
|
appendSupervisorReplyEntry(pi, request, reply);
|
|
611
635
|
pending.delete(request.id);
|
|
@@ -637,6 +661,9 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
637
661
|
return state;
|
|
638
662
|
};
|
|
639
663
|
const pending = new Map<string, PendingSupervisorRequest>();
|
|
664
|
+
// Asks claimed by a registered responder: never woken, never detached, never
|
|
665
|
+
// answered through the generic parent tool.
|
|
666
|
+
const claimedAsks = new Set<string>();
|
|
640
667
|
// One continuation and one warning per request; never auto-answer or loop.
|
|
641
668
|
const settleNotices = new Map<string, "reminded" | "warned" | "handled">();
|
|
642
669
|
let unsubscribeSettle: (() => void) | undefined;
|
|
@@ -670,6 +697,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
670
697
|
const observeRequestLifecycle: SupervisorRequestLifecycleObserver = (request, lifecycle) => {
|
|
671
698
|
settleNotices.delete(request.id);
|
|
672
699
|
if (lifecycle !== "wrong-session") rememberResolvedRequest(request);
|
|
700
|
+
if (lifecycle !== "pending") deps.supervisorDispatcher?.observe(request.id, lifecycle);
|
|
673
701
|
updateSettleSubscription();
|
|
674
702
|
};
|
|
675
703
|
const getSupervisorRequestState = (event: ControlEvent): SupervisorRequestState => {
|
|
@@ -716,7 +744,25 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
716
744
|
};
|
|
717
745
|
|
|
718
746
|
const registerParentTools = (): void => {
|
|
719
|
-
if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => poll(), runState));
|
|
747
|
+
if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => poll(), runState, (requestId) => claimedAsks.has(requestId)));
|
|
748
|
+
};
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Write a responder's answer through the same file-authoritative path the
|
|
752
|
+
* native reply uses, after re-confirming the ask is still answerable.
|
|
753
|
+
*/
|
|
754
|
+
const deliverClaimedReply = (request: PendingSupervisorRequest, message: string): void => {
|
|
755
|
+
if (!pending.has(request.id)) throw new Error(`Supervisor ask ${request.id} is no longer pending.`);
|
|
756
|
+
if (!requestMatchesOwner(request, state)) throw new Error(`Supervisor ask ${request.id} no longer belongs to the live owner session.`);
|
|
757
|
+
if (fs.existsSync(replyPath(request.channelDir, request.id))) throw new Error(`Supervisor ask ${request.id} already has a reply.`);
|
|
758
|
+
const now = Date.now();
|
|
759
|
+
if (request.expectsReply && now > requestExpiresAt(request, now)) throw new Error(`Supervisor ask ${request.id} has expired.`);
|
|
760
|
+
const reply = writeReply(request, message);
|
|
761
|
+
appendSupervisorReplyEntry(pi, request, reply);
|
|
762
|
+
pending.delete(request.id);
|
|
763
|
+
claimedAsks.delete(request.id);
|
|
764
|
+
observeRequestLifecycle(request, "resolved");
|
|
765
|
+
clearForegroundSupervisorAttention(request, pending, state);
|
|
720
766
|
};
|
|
721
767
|
|
|
722
768
|
const cleanupStaleChannelsIfDue = (): void => {
|
|
@@ -759,6 +805,24 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
759
805
|
pending.set(request.id, request);
|
|
760
806
|
updateSettleSubscription();
|
|
761
807
|
markForegroundSupervisorAttention(request, state);
|
|
808
|
+
// Exclusive takeover: a registered responder claims this exact bound
|
|
809
|
+
// route before any parent wake or detach is emitted. A claim is final
|
|
810
|
+
// for this ask; failures inside the responder fail the audit closed
|
|
811
|
+
// instead of falling back to the default notification path.
|
|
812
|
+
const claimed = deps.supervisorDispatcher?.claim({
|
|
813
|
+
askId: request.id,
|
|
814
|
+
runId: request.runId,
|
|
815
|
+
agent: request.agent,
|
|
816
|
+
childIndex: request.childIndex,
|
|
817
|
+
reason: request.reason,
|
|
818
|
+
message: request.message,
|
|
819
|
+
...(request.interview !== undefined ? { interview: request.interview } : {}),
|
|
820
|
+
...(request.expiresAt !== undefined ? { deadlineAt: request.expiresAt } : {}),
|
|
821
|
+
}, (message) => deliverClaimedReply(request, message)) === true;
|
|
822
|
+
if (claimed) {
|
|
823
|
+
claimedAsks.add(request.id);
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
762
826
|
// The ask is already queued above. A sendMessage failure (no UI, stale context) must not
|
|
763
827
|
// lose it, and must not abort the loop before the remaining asks register.
|
|
764
828
|
try {
|
|
@@ -803,6 +867,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
803
867
|
return;
|
|
804
868
|
const messages = event.context.contextMessages;
|
|
805
869
|
const requests = [...pending.values()].filter(request => {
|
|
870
|
+
if (claimedAsks.has(request.id)) return false;
|
|
806
871
|
if (!request.expectsReply || settleNotices.get(request.id) === "warned" || settleNotices.get(request.id) === "handled") return false;
|
|
807
872
|
const index = messages.findLastIndex(message => message.role === "custom"
|
|
808
873
|
&& message.customType === SUPERVISOR_REQUEST_MESSAGE_TYPE
|
|
@@ -990,6 +1055,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
990
1055
|
if (deferredWatcherRefresh) timers.clearImmediate(deferredWatcherRefresh);
|
|
991
1056
|
deferredWatcherRefresh = undefined;
|
|
992
1057
|
pending.clear();
|
|
1058
|
+
claimedAsks.clear();
|
|
993
1059
|
settleNotices.clear();
|
|
994
1060
|
requestCorrelations.clear();
|
|
995
1061
|
seenFiles.clear();
|
|
@@ -3,6 +3,7 @@ import * as fs from "node:fs";
|
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
5
5
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import type { SupervisorLaunchHooks } from "../../intercom/fork-supervisor-routing.ts";
|
|
6
7
|
import { discoverAgents, discoverAgentsAll, findBlockingAgentDiagnostic, formatAvailableAgentLines, formatUnknownAgentError, resolveAgentName, suggestAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
|
|
7
8
|
import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
|
|
8
9
|
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
@@ -507,6 +508,8 @@ interface ExecutionContextData {
|
|
|
507
508
|
controlConfig: ResolvedControlConfig;
|
|
508
509
|
/** Structured delegation consumers do not need duration-only heartbeat snapshots. */
|
|
509
510
|
suppressUnchangedDelegationUpdates?: boolean;
|
|
511
|
+
/** Internal delegated-launch binding hooks (never a model-facing parameter). */
|
|
512
|
+
supervisorLaunchHooks?: SupervisorLaunchHooks;
|
|
510
513
|
intercomBridge: IntercomBridgeState;
|
|
511
514
|
nestedRoute?: NestedRouteInfo;
|
|
512
515
|
timeoutMs?: number;
|
|
@@ -4164,6 +4167,22 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
|
|
|
4164
4167
|
details: { mode: "single", results: [] },
|
|
4165
4168
|
};
|
|
4166
4169
|
}
|
|
4170
|
+
// Internal delegated-launch binding: the real runId and canonical agent now
|
|
4171
|
+
// exist and no child prompt has been sent yet. A binding conflict or an
|
|
4172
|
+
// identity change must fail here, before any model call.
|
|
4173
|
+
if (data.supervisorLaunchHooks) {
|
|
4174
|
+
try {
|
|
4175
|
+
data.supervisorLaunchHooks.beforeNativeChildLaunch({
|
|
4176
|
+
runId,
|
|
4177
|
+
agent: agentConfig.name,
|
|
4178
|
+
childIndex: 0,
|
|
4179
|
+
...(data.parentPiSessionId ? { parentSessionId: data.parentPiSessionId } : {}),
|
|
4180
|
+
bridgeActive: childBridgeActive,
|
|
4181
|
+
});
|
|
4182
|
+
} catch (error) {
|
|
4183
|
+
return toExecutionErrorResult(params, error instanceof Error ? error : new Error(String(error)), contextPolicy.contextSummary);
|
|
4184
|
+
}
|
|
4185
|
+
}
|
|
4167
4186
|
let foregroundMachine: import("../../shared/types.ts").HerdrMachineReference | undefined;
|
|
4168
4187
|
const requestedMachine = params.machine ?? agentConfig.machine;
|
|
4169
4188
|
const requiredExtensions = data.requiredExtensions ?? deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(data.parentPiSessionId);
|
|
@@ -5412,6 +5431,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5412
5431
|
signal: AbortSignal,
|
|
5413
5432
|
onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
|
|
5414
5433
|
ctx: ExtensionContext,
|
|
5434
|
+
supervisorLaunchHooks?: SupervisorLaunchHooks,
|
|
5415
5435
|
) => Promise<AgentToolResult<Details>>;
|
|
5416
5436
|
/** Scheduled launches retain their owning context without replacing the live active session. */
|
|
5417
5437
|
executeScheduled: (
|
|
@@ -5425,6 +5445,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5425
5445
|
} {
|
|
5426
5446
|
const executorDeps = deps;
|
|
5427
5447
|
const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
|
|
5448
|
+
const delegatedSupervisorLaunchHooks = new WeakMap<object, SupervisorLaunchHooks>();
|
|
5428
5449
|
const delegatedZeroToolBudgets = new WeakSet<object>();
|
|
5429
5450
|
const delegatedExecutions = new WeakSet<object>();
|
|
5430
5451
|
const publicExecutions = new WeakSet<object>();
|
|
@@ -5460,6 +5481,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5460
5481
|
const inheritedUsageBudget = workflowOwnedUsageBudgets.get(params);
|
|
5461
5482
|
const retainedRequiredExtensions = workflowRetainedRequiredExtensions.get(params);
|
|
5462
5483
|
const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
|
|
5484
|
+
const supervisorLaunchHooks = delegatedSupervisorLaunchHooks.get(params);
|
|
5463
5485
|
const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
|
|
5464
5486
|
const delegatedExecution = delegatedExecutions.has(params);
|
|
5465
5487
|
const publicExecution = publicExecutions.has(params);
|
|
@@ -7857,6 +7879,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
7857
7879
|
toolCallId: _id,
|
|
7858
7880
|
controlConfig,
|
|
7859
7881
|
...(delegatedExecution ? { suppressUnchangedDelegationUpdates: true } : {}),
|
|
7882
|
+
...(supervisorLaunchHooks ? { supervisorLaunchHooks } : {}),
|
|
7860
7883
|
intercomBridge,
|
|
7861
7884
|
nestedRoute,
|
|
7862
7885
|
timeoutMs: foregroundTimeout.timeoutMs,
|
|
@@ -8172,6 +8195,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
8172
8195
|
signal: AbortSignal,
|
|
8173
8196
|
onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
|
|
8174
8197
|
ctx: ExtensionContext,
|
|
8198
|
+
supervisorLaunchHooks?: SupervisorLaunchHooks,
|
|
8175
8199
|
): Promise<AgentToolResult<Details>> => {
|
|
8176
8200
|
const disabledFeatureError = disabledFeatureResult(params);
|
|
8177
8201
|
if (disabledFeatureError) return disabledFeatureError;
|
|
@@ -8188,6 +8212,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
8188
8212
|
delete privateParams.delegatedAllowZeroToolBudget;
|
|
8189
8213
|
delete privateParams.delegatedWorkflowPermit;
|
|
8190
8214
|
if (thinkingOverride !== undefined) delegatedThinkingOverrides.set(delegatedParams, thinkingOverride);
|
|
8215
|
+
if (supervisorLaunchHooks) delegatedSupervisorLaunchHooks.set(delegatedParams, supervisorLaunchHooks);
|
|
8191
8216
|
if (allowZeroToolBudget) delegatedZeroToolBudgets.add(delegatedParams);
|
|
8192
8217
|
if (workflowPermit) workflowPermitContexts.set(delegatedParams, { root: workflowPermit });
|
|
8193
8218
|
delegatedExecutions.add(delegatedParams);
|
|
@@ -51,6 +51,8 @@ interface PromptTemplateBridgeOptions<Ctx extends { cwd?: string }> {
|
|
|
51
51
|
signal: AbortSignal,
|
|
52
52
|
ctx: Ctx,
|
|
53
53
|
onUpdate: (result: PromptTemplateBridgeResult) => void,
|
|
54
|
+
/** Internal: the validated original request. Never a model-visible parameter. */
|
|
55
|
+
request?: SubagentDelegationRequest,
|
|
54
56
|
) => Promise<PromptTemplateBridgeResult>;
|
|
55
57
|
}
|
|
56
58
|
|
|
@@ -342,29 +344,28 @@ export function registerPromptTemplateDelegationBridge<Ctx extends { cwd?: strin
|
|
|
342
344
|
);
|
|
343
345
|
|
|
344
346
|
try {
|
|
345
|
-
const
|
|
347
|
+
const executeStructured = structuredRequest && options.executeStructured
|
|
346
348
|
? options.executeStructured
|
|
347
|
-
:
|
|
349
|
+
: undefined;
|
|
348
350
|
let lastStructuredUpdate: SubagentDelegationUpdate | undefined;
|
|
349
|
-
const
|
|
350
|
-
requestId,
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
if (structuredRequest) {
|
|
357
|
-
const payload = toSubagentDelegationUpdate(structuredRequest, update);
|
|
358
|
-
if (payload && (!lastStructuredUpdate || !sameStructuredDelegationUpdateProgress(lastStructuredUpdate, payload))) {
|
|
359
|
-
lastStructuredUpdate = payload;
|
|
360
|
-
options.events.emit(SUBAGENT_DELEGATION_UPDATE_EVENT, payload);
|
|
361
|
-
}
|
|
362
|
-
return;
|
|
351
|
+
const onExecutionUpdate = (update: PromptTemplateBridgeResult): void => {
|
|
352
|
+
if (key ? !ownsAttempt(key, controller) : !ownsLegacyRequest(requestId, controller)) return;
|
|
353
|
+
if (structuredRequest) {
|
|
354
|
+
const payload = toSubagentDelegationUpdate(structuredRequest, update);
|
|
355
|
+
if (payload && (!lastStructuredUpdate || !sameStructuredDelegationUpdateProgress(lastStructuredUpdate, payload))) {
|
|
356
|
+
lastStructuredUpdate = payload;
|
|
357
|
+
options.events.emit(SUBAGENT_DELEGATION_UPDATE_EVENT, payload);
|
|
363
358
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
const payload = toDelegationUpdate(requestId, update);
|
|
362
|
+
if (payload) options.events.emit(PROMPT_TEMPLATE_SUBAGENT_UPDATE_EVENT, payload);
|
|
363
|
+
};
|
|
364
|
+
// The structured path receives the validated original request as an
|
|
365
|
+
// internal sixth argument; the legacy five-parameter path is unchanged.
|
|
366
|
+
const result = executeStructured && structuredRequest
|
|
367
|
+
? await executeStructured(requestId, params, controller.signal, ctx, onExecutionUpdate, structuredRequest)
|
|
368
|
+
: await options.execute(requestId, params, controller.signal, ctx, onExecutionUpdate);
|
|
368
369
|
if (key ? !ownsAttempt(key, controller) : !ownsLegacyRequest(requestId, controller)) return;
|
|
369
370
|
if (structuredRequest && key) {
|
|
370
371
|
emitTerminal(key, toSubagentDelegationResponse(structuredRequest, result, controller.signal.aborted));
|