pi-agent-swarm 0.3.0 → 0.5.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/README.md +44 -6
- package/dist/chunks/{menu-RH6GY6U4.ts → menu-NLK5I2DA.ts} +15 -2
- package/dist/chunks/menu-NLK5I2DA.ts.map +7 -0
- package/dist/index.ts +7755 -924
- package/dist/index.ts.map +4 -4
- package/package.json +4 -4
- package/src/auto-name.ts +137 -28
- package/src/budget.ts +268 -0
- package/src/context-recycling.ts +712 -0
- package/src/external-runtime.ts +374 -0
- package/src/fanout.ts +219 -0
- package/src/launch-envelope.ts +115 -0
- package/src/lead-mcp-bridge.ts +516 -0
- package/src/leader-handoff-bridge.ts +155 -0
- package/src/leader-recycling.ts +752 -0
- package/src/leader-runtime.ts +1098 -0
- package/src/leader-session-runtime.ts +71 -0
- package/src/ledger.ts +351 -0
- package/src/menu.ts +16 -2
- package/src/model-catalog.ts +213 -0
- package/src/org.ts +242 -0
- package/src/pi-agent-swarm.ts +55 -2
- package/src/profile-probe.ts +143 -0
- package/src/profiles.ts +621 -0
- package/src/protocol.ts +14 -3
- package/src/reload-handoff.ts +3 -0
- package/src/resource-lease.ts +250 -0
- package/src/reviewer.ts +191 -0
- package/src/settings.ts +335 -10
- package/src/swarm-controller.ts +2207 -89
- package/src/tools.ts +244 -7
- package/src/transport.ts +17 -0
- package/src/worktree.ts +86 -0
- package/dist/chunks/menu-RH6GY6U4.ts.map +0 -7
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { SwarmLedgerUsage } from "./ledger.js";
|
|
3
|
+
import type { ExternalRuntimeModelEntry, ExternalRuntimeSnapshot } from "./model-catalog.js";
|
|
4
|
+
import type { WorkerRole } from "./profiles.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Extension-neutral, versioned event bus contract between `pi-agent-swarm` and any
|
|
8
|
+
* external ACP/CLI runtime extension (such as `pi-agy-acp`).
|
|
9
|
+
*
|
|
10
|
+
* Neither extension imports the other; both speak only this versioned event protocol.
|
|
11
|
+
*/
|
|
12
|
+
export const EXTERNAL_RUNTIME_EVENT = "pi-agent-swarm:external-runtime:v1";
|
|
13
|
+
|
|
14
|
+
export type ExternalRuntimeEventPayload =
|
|
15
|
+
| {
|
|
16
|
+
type: "discover";
|
|
17
|
+
requesterId: string;
|
|
18
|
+
}
|
|
19
|
+
| {
|
|
20
|
+
type: "register" | "models_snapshot";
|
|
21
|
+
runtimeId: string;
|
|
22
|
+
available: boolean;
|
|
23
|
+
models: ExternalRuntimeModelEntry[];
|
|
24
|
+
}
|
|
25
|
+
| {
|
|
26
|
+
type: "configure";
|
|
27
|
+
requestId: string;
|
|
28
|
+
runtimeId: string;
|
|
29
|
+
sessionId: string;
|
|
30
|
+
cwd: string;
|
|
31
|
+
role: WorkerRole;
|
|
32
|
+
profile: string;
|
|
33
|
+
modelId: string;
|
|
34
|
+
readableDirs: string[];
|
|
35
|
+
}
|
|
36
|
+
| {
|
|
37
|
+
type: "ready";
|
|
38
|
+
requestId: string;
|
|
39
|
+
runtimeId: string;
|
|
40
|
+
sessionId: string;
|
|
41
|
+
ok: boolean;
|
|
42
|
+
actualModel?: string;
|
|
43
|
+
error?: string;
|
|
44
|
+
}
|
|
45
|
+
| {
|
|
46
|
+
type: "run_turn";
|
|
47
|
+
requestId: string;
|
|
48
|
+
runtimeId: string;
|
|
49
|
+
sessionId: string;
|
|
50
|
+
prompt: string;
|
|
51
|
+
messageId: string;
|
|
52
|
+
fromSessionId: string;
|
|
53
|
+
}
|
|
54
|
+
| {
|
|
55
|
+
type: "turn_completed";
|
|
56
|
+
requestId: string;
|
|
57
|
+
runtimeId: string;
|
|
58
|
+
sessionId: string;
|
|
59
|
+
ok: boolean;
|
|
60
|
+
text: string;
|
|
61
|
+
stopReason: string;
|
|
62
|
+
error?: string;
|
|
63
|
+
sawQuota?: boolean;
|
|
64
|
+
usage?: SwarmLedgerUsage & {
|
|
65
|
+
cachedReadTokens?: number;
|
|
66
|
+
cachedWriteTokens?: number;
|
|
67
|
+
thoughtTokens?: number;
|
|
68
|
+
};
|
|
69
|
+
toolCalls?: Array<{ id?: string; label: string; status: string }>;
|
|
70
|
+
}
|
|
71
|
+
| {
|
|
72
|
+
type: "cancel";
|
|
73
|
+
runtimeId: string;
|
|
74
|
+
sessionId: string;
|
|
75
|
+
requestId?: string;
|
|
76
|
+
}
|
|
77
|
+
| {
|
|
78
|
+
type: "shutdown";
|
|
79
|
+
runtimeId: string;
|
|
80
|
+
sessionId: string;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export interface ExternalTurnResult {
|
|
84
|
+
ok: boolean;
|
|
85
|
+
text: string;
|
|
86
|
+
stopReason: string;
|
|
87
|
+
error?: string;
|
|
88
|
+
sawQuota: boolean;
|
|
89
|
+
usage?: SwarmLedgerUsage;
|
|
90
|
+
toolCalls: Array<{ id?: string; label: string; status: string }>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface PendingWaiter<T> {
|
|
94
|
+
resolve: (value: T) => void;
|
|
95
|
+
reject: (error: Error) => void;
|
|
96
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
97
|
+
cleanupAbort?: () => void;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export class ExternalRuntimeHost {
|
|
101
|
+
private unsubscribe: (() => void) | undefined;
|
|
102
|
+
private readonly readyWaiters = new Map<string, PendingWaiter<{ actualModel?: string }>>();
|
|
103
|
+
private readonly turnWaiters = new Map<string, PendingWaiter<ExternalTurnResult>>();
|
|
104
|
+
|
|
105
|
+
constructor(
|
|
106
|
+
private readonly pi: ExtensionAPI,
|
|
107
|
+
private readonly handlers: {
|
|
108
|
+
onSnapshot: (snapshot: ExternalRuntimeSnapshot) => void;
|
|
109
|
+
now: () => number;
|
|
110
|
+
randomId: (prefix: string) => string;
|
|
111
|
+
},
|
|
112
|
+
) {}
|
|
113
|
+
|
|
114
|
+
start(requesterId: string): void {
|
|
115
|
+
this.stop();
|
|
116
|
+
const events = this.pi.events;
|
|
117
|
+
if (!events || typeof events.on !== "function") return;
|
|
118
|
+
const unsub = events.on(EXTERNAL_RUNTIME_EVENT, (raw: unknown) => {
|
|
119
|
+
this.handleEvent(raw);
|
|
120
|
+
});
|
|
121
|
+
this.unsubscribe = typeof unsub === "function" ? unsub : undefined;
|
|
122
|
+
this.emit({ type: "discover", requesterId });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
stop(): void {
|
|
126
|
+
try {
|
|
127
|
+
this.unsubscribe?.();
|
|
128
|
+
} catch {
|
|
129
|
+
// Best-effort unsubscribe.
|
|
130
|
+
}
|
|
131
|
+
this.unsubscribe = undefined;
|
|
132
|
+
for (const [id, waiter] of this.readyWaiters) {
|
|
133
|
+
this.clearWaiter(waiter);
|
|
134
|
+
waiter.reject(new Error(`External runtime configure request ${id} cancelled during stop`));
|
|
135
|
+
}
|
|
136
|
+
this.readyWaiters.clear();
|
|
137
|
+
for (const [id, waiter] of this.turnWaiters) {
|
|
138
|
+
this.clearWaiter(waiter);
|
|
139
|
+
waiter.reject(new Error(`External runtime turn ${id} cancelled during stop`));
|
|
140
|
+
}
|
|
141
|
+
this.turnWaiters.clear();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
discover(requesterId: string): void {
|
|
145
|
+
this.emit({ type: "discover", requesterId });
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
configure(
|
|
149
|
+
params: {
|
|
150
|
+
runtimeId: string;
|
|
151
|
+
sessionId: string;
|
|
152
|
+
cwd: string;
|
|
153
|
+
role: WorkerRole;
|
|
154
|
+
profile: string;
|
|
155
|
+
modelId: string;
|
|
156
|
+
readableDirs: string[];
|
|
157
|
+
timeoutMs?: number;
|
|
158
|
+
},
|
|
159
|
+
signal?: AbortSignal,
|
|
160
|
+
): Promise<{ actualModel?: string }> {
|
|
161
|
+
const requestId = this.handlers.randomId("extcfg");
|
|
162
|
+
const timeoutMs = params.timeoutMs ?? 60_000;
|
|
163
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
164
|
+
if (signal?.aborted) {
|
|
165
|
+
rejectPromise(new Error("External runtime configure aborted"));
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const waiter: PendingWaiter<{ actualModel?: string }> = {
|
|
169
|
+
resolve: resolvePromise,
|
|
170
|
+
reject: rejectPromise,
|
|
171
|
+
};
|
|
172
|
+
waiter.timer = setTimeout(() => {
|
|
173
|
+
if (!this.readyWaiters.delete(requestId)) return;
|
|
174
|
+
this.clearWaiter(waiter);
|
|
175
|
+
rejectPromise(
|
|
176
|
+
new Error(
|
|
177
|
+
`External runtime "${params.runtimeId}" did not become ready within ${timeoutMs}ms (is pi-agy-acp loaded?)`,
|
|
178
|
+
),
|
|
179
|
+
);
|
|
180
|
+
}, timeoutMs);
|
|
181
|
+
if (signal) {
|
|
182
|
+
const onAbort = () => {
|
|
183
|
+
if (!this.readyWaiters.delete(requestId)) return;
|
|
184
|
+
this.clearWaiter(waiter);
|
|
185
|
+
rejectPromise(new Error("External runtime configure aborted"));
|
|
186
|
+
};
|
|
187
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
188
|
+
waiter.cleanupAbort = () => signal.removeEventListener("abort", onAbort);
|
|
189
|
+
}
|
|
190
|
+
this.readyWaiters.set(requestId, waiter);
|
|
191
|
+
this.emit({
|
|
192
|
+
type: "configure",
|
|
193
|
+
requestId,
|
|
194
|
+
runtimeId: params.runtimeId,
|
|
195
|
+
sessionId: params.sessionId,
|
|
196
|
+
cwd: params.cwd,
|
|
197
|
+
role: params.role,
|
|
198
|
+
profile: params.profile,
|
|
199
|
+
modelId: params.modelId,
|
|
200
|
+
readableDirs: params.readableDirs,
|
|
201
|
+
});
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
runTurn(
|
|
206
|
+
params: {
|
|
207
|
+
runtimeId: string;
|
|
208
|
+
sessionId: string;
|
|
209
|
+
prompt: string;
|
|
210
|
+
messageId: string;
|
|
211
|
+
fromSessionId: string;
|
|
212
|
+
timeoutMs?: number;
|
|
213
|
+
},
|
|
214
|
+
signal?: AbortSignal,
|
|
215
|
+
): Promise<ExternalTurnResult> {
|
|
216
|
+
const requestId = this.handlers.randomId("extturn");
|
|
217
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
218
|
+
if (signal?.aborted) {
|
|
219
|
+
rejectPromise(new Error("External runtime turn aborted"));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const waiter: PendingWaiter<ExternalTurnResult> = {
|
|
223
|
+
resolve: resolvePromise,
|
|
224
|
+
reject: rejectPromise,
|
|
225
|
+
};
|
|
226
|
+
if (params.timeoutMs && params.timeoutMs > 0) {
|
|
227
|
+
waiter.timer = setTimeout(() => {
|
|
228
|
+
if (!this.turnWaiters.delete(requestId)) return;
|
|
229
|
+
this.clearWaiter(waiter);
|
|
230
|
+
this.cancel(params.runtimeId, params.sessionId, requestId);
|
|
231
|
+
rejectPromise(new Error(`External runtime turn timed out after ${params.timeoutMs}ms`));
|
|
232
|
+
}, params.timeoutMs);
|
|
233
|
+
}
|
|
234
|
+
if (signal) {
|
|
235
|
+
const onAbort = () => {
|
|
236
|
+
if (!this.turnWaiters.delete(requestId)) return;
|
|
237
|
+
this.clearWaiter(waiter);
|
|
238
|
+
this.cancel(params.runtimeId, params.sessionId, requestId);
|
|
239
|
+
rejectPromise(new Error("External runtime turn aborted"));
|
|
240
|
+
};
|
|
241
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
242
|
+
waiter.cleanupAbort = () => signal.removeEventListener("abort", onAbort);
|
|
243
|
+
}
|
|
244
|
+
this.turnWaiters.set(requestId, waiter);
|
|
245
|
+
this.emit({
|
|
246
|
+
type: "run_turn",
|
|
247
|
+
requestId,
|
|
248
|
+
runtimeId: params.runtimeId,
|
|
249
|
+
sessionId: params.sessionId,
|
|
250
|
+
prompt: params.prompt,
|
|
251
|
+
messageId: params.messageId,
|
|
252
|
+
fromSessionId: params.fromSessionId,
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
cancel(runtimeId: string, sessionId: string, requestId?: string): void {
|
|
258
|
+
this.emit({
|
|
259
|
+
type: "cancel",
|
|
260
|
+
runtimeId,
|
|
261
|
+
sessionId,
|
|
262
|
+
...(requestId ? { requestId } : {}),
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
shutdown(runtimeId: string, sessionId: string): void {
|
|
267
|
+
this.emit({
|
|
268
|
+
type: "shutdown",
|
|
269
|
+
runtimeId,
|
|
270
|
+
sessionId,
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private emit(payload: ExternalRuntimeEventPayload): void {
|
|
275
|
+
if (typeof this.pi.events?.emit === "function") {
|
|
276
|
+
this.pi.events.emit(EXTERNAL_RUNTIME_EVENT, payload);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
private handleEvent(raw: unknown): void {
|
|
281
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
|
|
282
|
+
const msg = raw as Record<string, unknown>;
|
|
283
|
+
const type = msg.type;
|
|
284
|
+
if ((type === "register" || type === "models_snapshot") && typeof msg.runtimeId === "string") {
|
|
285
|
+
const models: ExternalRuntimeModelEntry[] = Array.isArray(msg.models)
|
|
286
|
+
? msg.models
|
|
287
|
+
.filter(
|
|
288
|
+
(item): item is ExternalRuntimeModelEntry =>
|
|
289
|
+
Boolean(item) &&
|
|
290
|
+
typeof item === "object" &&
|
|
291
|
+
typeof (item as Record<string, unknown>).modelId === "string",
|
|
292
|
+
)
|
|
293
|
+
.map((item) => ({
|
|
294
|
+
modelId: item.modelId,
|
|
295
|
+
...(typeof item.label === "string" ? { label: item.label } : {}),
|
|
296
|
+
...(typeof item.contextWindow === "number" ? { contextWindow: item.contextWindow } : {}),
|
|
297
|
+
...(typeof item.costHint === "string" ? { costHint: item.costHint } : {}),
|
|
298
|
+
...(item.sawQuota === true ? { sawQuota: true } : {}),
|
|
299
|
+
...(typeof item.quotaSeenAt === "number" ? { quotaSeenAt: item.quotaSeenAt } : {}),
|
|
300
|
+
}))
|
|
301
|
+
: [];
|
|
302
|
+
this.handlers.onSnapshot({
|
|
303
|
+
runtimeId: msg.runtimeId,
|
|
304
|
+
available: msg.available !== false,
|
|
305
|
+
models,
|
|
306
|
+
updatedAt: this.handlers.now(),
|
|
307
|
+
});
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (type === "ready" && typeof msg.requestId === "string") {
|
|
312
|
+
const waiter = this.readyWaiters.get(msg.requestId);
|
|
313
|
+
if (!waiter) return;
|
|
314
|
+
this.readyWaiters.delete(msg.requestId);
|
|
315
|
+
this.clearWaiter(waiter);
|
|
316
|
+
if (msg.ok === true) {
|
|
317
|
+
waiter.resolve({
|
|
318
|
+
...(typeof msg.actualModel === "string" ? { actualModel: msg.actualModel } : {}),
|
|
319
|
+
});
|
|
320
|
+
} else {
|
|
321
|
+
waiter.reject(new Error(typeof msg.error === "string" ? msg.error : "External runtime failed to configure"));
|
|
322
|
+
}
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (type === "turn_completed" && typeof msg.requestId === "string") {
|
|
327
|
+
const waiter = this.turnWaiters.get(msg.requestId);
|
|
328
|
+
if (!waiter) return;
|
|
329
|
+
this.turnWaiters.delete(msg.requestId);
|
|
330
|
+
this.clearWaiter(waiter);
|
|
331
|
+
const rawUsage =
|
|
332
|
+
msg.usage && typeof msg.usage === "object" && !Array.isArray(msg.usage)
|
|
333
|
+
? (msg.usage as Record<string, unknown>)
|
|
334
|
+
: undefined;
|
|
335
|
+
const usage: SwarmLedgerUsage | undefined = rawUsage
|
|
336
|
+
? {
|
|
337
|
+
...(typeof rawUsage.inputTokens === "number" ? { inputTokens: rawUsage.inputTokens } : {}),
|
|
338
|
+
...(typeof rawUsage.outputTokens === "number" ? { outputTokens: rawUsage.outputTokens } : {}),
|
|
339
|
+
...(typeof rawUsage.totalTokens === "number" ? { totalTokens: rawUsage.totalTokens } : {}),
|
|
340
|
+
...(typeof rawUsage.costUsd === "number" ? { costUsd: rawUsage.costUsd } : {}),
|
|
341
|
+
}
|
|
342
|
+
: undefined;
|
|
343
|
+
const toolCalls = Array.isArray(msg.toolCalls)
|
|
344
|
+
? msg.toolCalls
|
|
345
|
+
.filter((item): item is { id?: string; label: string; status: string } =>
|
|
346
|
+
Boolean(item && typeof item === "object" && typeof (item as Record<string, unknown>).label === "string"),
|
|
347
|
+
)
|
|
348
|
+
.map((item) => ({
|
|
349
|
+
...(typeof item.id === "string" ? { id: item.id } : {}),
|
|
350
|
+
label: item.label,
|
|
351
|
+
status: typeof item.status === "string" ? item.status : "done",
|
|
352
|
+
}))
|
|
353
|
+
: [];
|
|
354
|
+
waiter.resolve({
|
|
355
|
+
ok: msg.ok === true,
|
|
356
|
+
text: typeof msg.text === "string" ? msg.text : "",
|
|
357
|
+
stopReason: typeof msg.stopReason === "string" ? msg.stopReason : "end_turn",
|
|
358
|
+
...(typeof msg.error === "string" ? { error: msg.error } : {}),
|
|
359
|
+
sawQuota: msg.sawQuota === true,
|
|
360
|
+
...(usage ? { usage } : {}),
|
|
361
|
+
toolCalls,
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private clearWaiter<T>(waiter: PendingWaiter<T>): void {
|
|
367
|
+
if (waiter.timer) {
|
|
368
|
+
clearTimeout(waiter.timer);
|
|
369
|
+
waiter.timer = undefined;
|
|
370
|
+
}
|
|
371
|
+
waiter.cleanupAbort?.();
|
|
372
|
+
waiter.cleanupAbort = undefined;
|
|
373
|
+
}
|
|
374
|
+
}
|
package/src/fanout.ts
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import type { ResolvedWorkerProfile, WorkerRole } from "./profiles.js";
|
|
3
|
+
import type { SwarmIsolationMode } from "./worktree.js";
|
|
4
|
+
|
|
5
|
+
export interface FanoutBranchSpec {
|
|
6
|
+
id: string;
|
|
7
|
+
role: WorkerRole;
|
|
8
|
+
profile: ResolvedWorkerProfile;
|
|
9
|
+
cwd: string;
|
|
10
|
+
model?: string;
|
|
11
|
+
task: string;
|
|
12
|
+
name?: string;
|
|
13
|
+
color?: string;
|
|
14
|
+
contextFiles?: string[];
|
|
15
|
+
readableDirs?: string[];
|
|
16
|
+
allowRequests?: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface FanoutPrecheckOptions {
|
|
20
|
+
maxChildren: number;
|
|
21
|
+
isolation: SwarmIsolationMode;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class FanoutConcurrencyError extends Error {
|
|
25
|
+
constructor(
|
|
26
|
+
public readonly code:
|
|
27
|
+
| "empty_branches"
|
|
28
|
+
| "max_children_exceeded"
|
|
29
|
+
| "macro_opaque_forbidden"
|
|
30
|
+
| "resource_lock_conflict"
|
|
31
|
+
| "shared_workspace_write_conflict",
|
|
32
|
+
message: string,
|
|
33
|
+
) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = "FanoutConcurrencyError";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Deterministic pre-flight concurrency law for `session_fanout`:
|
|
41
|
+
* 1. Total branches <= maxChildren;
|
|
42
|
+
* 2. No branch with `orchestration === "macro-opaque"` (e.g. `game`) may be fanned out;
|
|
43
|
+
* 3. Total demand for any profile resource cannot exceed its `concurrency` (e.g. two `pcb` writers wanting `gui:lceda`);
|
|
44
|
+
* 4. Multiple writable branches (`role === "implementer"`) cannot target the same cwd unless `isolation === "worktree"`.
|
|
45
|
+
*
|
|
46
|
+
* Every violation rejects the entire batch BEFORE opening any terminal window or spending any tokens.
|
|
47
|
+
*/
|
|
48
|
+
export function precheckFanoutBatch(branches: readonly FanoutBranchSpec[], options: FanoutPrecheckOptions): void {
|
|
49
|
+
if (branches.length === 0) {
|
|
50
|
+
throw new FanoutConcurrencyError("empty_branches", "session_fanout requires at least one branch");
|
|
51
|
+
}
|
|
52
|
+
if (branches.length > options.maxChildren) {
|
|
53
|
+
throw new FanoutConcurrencyError(
|
|
54
|
+
"max_children_exceeded",
|
|
55
|
+
`session_fanout requested ${branches.length} branches, exceeding maxChildren=${options.maxChildren}`,
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const resourceDemand = new Map<string, { concurrency: number; claimants: string[] }>();
|
|
60
|
+
const writableByCwd = new Map<string, string[]>();
|
|
61
|
+
|
|
62
|
+
for (const branch of branches) {
|
|
63
|
+
if (branch.profile.orchestration === "macro-opaque") {
|
|
64
|
+
throw new FanoutConcurrencyError(
|
|
65
|
+
"macro_opaque_forbidden",
|
|
66
|
+
`session_fanout refuses branch "${branch.id}" with macro-opaque profile "${branch.profile.id}" (nested multi-agent replication is prohibited).`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
for (const res of branch.profile.resources) {
|
|
71
|
+
const existing = resourceDemand.get(res.id);
|
|
72
|
+
if (existing) {
|
|
73
|
+
existing.concurrency = Math.min(existing.concurrency, res.concurrency);
|
|
74
|
+
existing.claimants.push(branch.id);
|
|
75
|
+
} else {
|
|
76
|
+
resourceDemand.set(res.id, { concurrency: res.concurrency, claimants: [branch.id] });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (branch.profile.writable) {
|
|
81
|
+
const normalizedCwd = resolve(branch.cwd);
|
|
82
|
+
const list = writableByCwd.get(normalizedCwd) ?? [];
|
|
83
|
+
list.push(branch.id);
|
|
84
|
+
writableByCwd.set(normalizedCwd, list);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
for (const [resourceId, demand] of resourceDemand) {
|
|
89
|
+
if (demand.claimants.length > demand.concurrency) {
|
|
90
|
+
throw new FanoutConcurrencyError(
|
|
91
|
+
"resource_lock_conflict",
|
|
92
|
+
`session_fanout rejected before launch: branches [${demand.claimants.join(", ")}] contend for singleton/bounded resource "${resourceId}" (concurrency=${demand.concurrency}). Run them sequentially or use read-only reviewer branches.`,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (options.isolation !== "worktree") {
|
|
98
|
+
for (const [cwd, claimants] of writableByCwd) {
|
|
99
|
+
if (claimants.length > 1) {
|
|
100
|
+
throw new FanoutConcurrencyError(
|
|
101
|
+
"shared_workspace_write_conflict",
|
|
102
|
+
`session_fanout rejected before launch: writable branches [${claimants.join(", ")}] share cwd "${cwd}" without worktree isolation. Enable isolation="worktree", give distinct cwds, or use read-only researcher/reviewer roles.`,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface FanoutBranchResult<T = unknown> {
|
|
110
|
+
branchId: string;
|
|
111
|
+
status: "completed" | "failed" | "timed_out";
|
|
112
|
+
sessionId?: string;
|
|
113
|
+
value?: T;
|
|
114
|
+
error?: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface FanoutJoinSummary<T = unknown> {
|
|
118
|
+
expected: number;
|
|
119
|
+
received: number;
|
|
120
|
+
timedOut: number;
|
|
121
|
+
failed: number;
|
|
122
|
+
allowPartial: boolean;
|
|
123
|
+
results: FanoutBranchResult<T>[];
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Join helper for parallel fan-out executions with bounded deadline and optional partial acceptance.
|
|
128
|
+
*/
|
|
129
|
+
export async function joinFanoutBranches<T>(
|
|
130
|
+
branches: readonly { branchId: string; run: (signal: AbortSignal) => Promise<{ sessionId?: string; value: T }> }[],
|
|
131
|
+
options: { deadlineMs?: number; allowPartial?: boolean; signal?: AbortSignal } = {},
|
|
132
|
+
): Promise<FanoutJoinSummary<T>> {
|
|
133
|
+
const allowPartial = options.allowPartial ?? true;
|
|
134
|
+
const deadlineMs = options.deadlineMs ?? 120_000;
|
|
135
|
+
const deadlineController = new AbortController();
|
|
136
|
+
|
|
137
|
+
const onOuterAbort = () => deadlineController.abort(options.signal?.reason);
|
|
138
|
+
if (options.signal) {
|
|
139
|
+
if (options.signal.aborted) {
|
|
140
|
+
deadlineController.abort(options.signal.reason);
|
|
141
|
+
} else {
|
|
142
|
+
options.signal.addEventListener("abort", onOuterAbort, { once: true });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
let timedOutFlag = false;
|
|
147
|
+
const timer =
|
|
148
|
+
deadlineMs > 0
|
|
149
|
+
? setTimeout(() => {
|
|
150
|
+
timedOutFlag = true;
|
|
151
|
+
deadlineController.abort(new Error(`Fan-out join deadline (${deadlineMs}ms) reached`));
|
|
152
|
+
}, deadlineMs)
|
|
153
|
+
: undefined;
|
|
154
|
+
|
|
155
|
+
try {
|
|
156
|
+
const settled = await Promise.all(
|
|
157
|
+
branches.map(async (branch): Promise<FanoutBranchResult<T>> => {
|
|
158
|
+
try {
|
|
159
|
+
const outcome = await raceWithAbort(branch.run(deadlineController.signal), deadlineController.signal);
|
|
160
|
+
return {
|
|
161
|
+
branchId: branch.branchId,
|
|
162
|
+
status: "completed",
|
|
163
|
+
...(outcome.sessionId ? { sessionId: outcome.sessionId } : {}),
|
|
164
|
+
value: outcome.value,
|
|
165
|
+
};
|
|
166
|
+
} catch (error) {
|
|
167
|
+
const isTimeout = timedOutFlag && deadlineController.signal.aborted;
|
|
168
|
+
return {
|
|
169
|
+
branchId: branch.branchId,
|
|
170
|
+
status: isTimeout ? "timed_out" : "failed",
|
|
171
|
+
error: error instanceof Error ? error.message : String(error),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
}),
|
|
175
|
+
);
|
|
176
|
+
|
|
177
|
+
const received = settled.filter((r) => r.status === "completed").length;
|
|
178
|
+
const timedOut = settled.filter((r) => r.status === "timed_out").length;
|
|
179
|
+
const failed = settled.filter((r) => r.status === "failed").length;
|
|
180
|
+
|
|
181
|
+
if (!allowPartial && received < branches.length) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
`Fan-out join failed with allowPartial=false: ${received}/${branches.length} completed (${timedOut} timed out, ${failed} failed)`,
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
expected: branches.length,
|
|
189
|
+
received,
|
|
190
|
+
timedOut,
|
|
191
|
+
failed,
|
|
192
|
+
allowPartial,
|
|
193
|
+
results: settled,
|
|
194
|
+
};
|
|
195
|
+
} finally {
|
|
196
|
+
if (timer) clearTimeout(timer);
|
|
197
|
+
options.signal?.removeEventListener("abort", onOuterAbort);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function raceWithAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
202
|
+
if (signal.aborted) {
|
|
203
|
+
return Promise.reject(signal.reason ?? new Error("Aborted"));
|
|
204
|
+
}
|
|
205
|
+
return new Promise<T>((resolvePromise, rejectPromise) => {
|
|
206
|
+
const onAbort = () => rejectPromise(signal.reason ?? new Error("Aborted"));
|
|
207
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
208
|
+
promise.then(
|
|
209
|
+
(value) => {
|
|
210
|
+
signal.removeEventListener("abort", onAbort);
|
|
211
|
+
resolvePromise(value);
|
|
212
|
+
},
|
|
213
|
+
(error) => {
|
|
214
|
+
signal.removeEventListener("abort", onAbort);
|
|
215
|
+
rejectPromise(error);
|
|
216
|
+
},
|
|
217
|
+
);
|
|
218
|
+
});
|
|
219
|
+
}
|