pi-agent-swarm 0.4.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 +21 -4
- package/dist/index.ts +7047 -1209
- package/dist/index.ts.map +4 -4
- package/package.json +1 -1
- package/src/auto-name.ts +137 -28
- package/src/budget.ts +268 -0
- package/src/context-recycling.ts +257 -52
- package/src/external-runtime.ts +374 -0
- package/src/fanout.ts +219 -0
- package/src/launch-envelope.ts +64 -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/model-catalog.ts +213 -0
- package/src/org.ts +242 -0
- package/src/pi-agent-swarm.ts +28 -7
- package/src/profile-probe.ts +143 -0
- package/src/profiles.ts +621 -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 +1671 -95
- package/src/tools.ts +144 -5
- package/src/worktree.ts +86 -0
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { chmod, lstat, mkdir, readdir, rm } from "node:fs/promises";
|
|
3
|
+
import { createConnection, createServer, type Server, type Socket } from "node:net";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import type { WorkerHandoffContent, WorkerTaskStatus } from "./context-recycling.js";
|
|
7
|
+
import type { LeaderHandoffContent } from "./leader-recycling.js";
|
|
8
|
+
import type { SwarmRole } from "./profiles.js";
|
|
9
|
+
import { defaultRuntimeBaseDirectory } from "./runtime-directory.js";
|
|
10
|
+
import type { SpawnSessionInput, SpawnSessionResult, SwarmCatalogResult, SwarmSnapshot } from "./swarm-controller.js";
|
|
11
|
+
|
|
12
|
+
export const LEAD_MCP_SERVER_NAME = "swarm-lead";
|
|
13
|
+
const LEAD_MCP_SOCKET_RE = /^lmcp-[a-f0-9]{16}\.sock$/u;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Safely prune stale `lmcp-*.sock` files whose owning Pi process has exited
|
|
17
|
+
* (`ECONNREFUSED` / `ENOENT`), while leaving active sockets and unrelated files untouched.
|
|
18
|
+
*/
|
|
19
|
+
export async function cleanupStaleLeadMcpSockets(baseDir: string): Promise<number> {
|
|
20
|
+
const entries = await readdir(baseDir).catch(() => [] as string[]);
|
|
21
|
+
let removed = 0;
|
|
22
|
+
for (const name of entries) {
|
|
23
|
+
if (!LEAD_MCP_SOCKET_RE.test(name)) continue;
|
|
24
|
+
const candidate = join(baseDir, name);
|
|
25
|
+
const info = await lstat(candidate).catch(() => undefined);
|
|
26
|
+
if (!info?.isSocket()) continue;
|
|
27
|
+
const alive = await probeUnixSocketAlive(candidate);
|
|
28
|
+
if (!alive) {
|
|
29
|
+
await rm(candidate, { force: true }).catch(() => undefined);
|
|
30
|
+
removed += 1;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return removed;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function probeUnixSocketAlive(socketPath: string): Promise<boolean> {
|
|
37
|
+
return new Promise((resolvePromise) => {
|
|
38
|
+
let settled = false;
|
|
39
|
+
const sock = createConnection(socketPath);
|
|
40
|
+
const finish = (alive: boolean) => {
|
|
41
|
+
if (settled) return;
|
|
42
|
+
settled = true;
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
sock.destroy();
|
|
45
|
+
resolvePromise(alive);
|
|
46
|
+
};
|
|
47
|
+
const timer = setTimeout(() => finish(true), 250);
|
|
48
|
+
sock.once("connect", () => finish(true));
|
|
49
|
+
sock.once("error", (err: NodeJS.ErrnoException) => {
|
|
50
|
+
if (err.code === "ECONNREFUSED" || err.code === "ENOENT") {
|
|
51
|
+
finish(false);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
// Conservative on unexpected errors: do not delete.
|
|
55
|
+
finish(true);
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface LeadMcpBridgeActions {
|
|
61
|
+
getContext: () => ExtensionContext | undefined;
|
|
62
|
+
getRole: () => SwarmRole;
|
|
63
|
+
catalog: (ctx: ExtensionContext) => SwarmCatalogResult;
|
|
64
|
+
spawn: (ctx: ExtensionContext, input: SpawnSessionInput) => Promise<SpawnSessionResult>;
|
|
65
|
+
snapshot: () => Promise<SwarmSnapshot>;
|
|
66
|
+
send: (
|
|
67
|
+
ctx: ExtensionContext,
|
|
68
|
+
options: {
|
|
69
|
+
targetSessionId: string;
|
|
70
|
+
text: string;
|
|
71
|
+
mode: "notify" | "request" | "reply";
|
|
72
|
+
replyTo?: string;
|
|
73
|
+
taskStatus?: WorkerTaskStatus;
|
|
74
|
+
handoff?: WorkerHandoffContent;
|
|
75
|
+
},
|
|
76
|
+
) => Promise<unknown>;
|
|
77
|
+
shutdownPeer: (ctx: ExtensionContext, targetSessionId: string) => Promise<unknown>;
|
|
78
|
+
publishLeaderHandoff: (ctx: ExtensionContext, handoff: LeaderHandoffContent) => Promise<unknown>;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface JsonRpcRequest {
|
|
82
|
+
jsonrpc?: string;
|
|
83
|
+
id?: string | number | null;
|
|
84
|
+
method?: string;
|
|
85
|
+
params?: Record<string, unknown>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const LEAD_MCP_TOOLS = [
|
|
89
|
+
{
|
|
90
|
+
name: "swarm_catalog",
|
|
91
|
+
description:
|
|
92
|
+
"Inspect live vertical capability profiles (default, write, pcb, 3d, design, re, game), project hints, and concrete models across Pi and agy pools (including recent sawQuota flags).",
|
|
93
|
+
inputSchema: {
|
|
94
|
+
type: "object",
|
|
95
|
+
properties: {},
|
|
96
|
+
additionalProperties: false,
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
name: "swarm_spawn",
|
|
101
|
+
description:
|
|
102
|
+
"Spawn a collaborating worker session in an external window with explicit Role x Profile x concrete ModelRef (pi:provider/id or agy:<modelId>), validated contextFiles/readableDirs, and launch confirmation.",
|
|
103
|
+
inputSchema: {
|
|
104
|
+
type: "object",
|
|
105
|
+
properties: {
|
|
106
|
+
role: { type: "string", enum: ["implementer", "researcher", "reviewer"] },
|
|
107
|
+
profile: { type: "string" },
|
|
108
|
+
model: { type: "string" },
|
|
109
|
+
task: { type: "string" },
|
|
110
|
+
name: { type: "string" },
|
|
111
|
+
color: { type: "string" },
|
|
112
|
+
cwd: { type: "string" },
|
|
113
|
+
direction: { type: "string", enum: ["right", "down", "left", "up"] },
|
|
114
|
+
allowRequests: { type: "boolean" },
|
|
115
|
+
contextFiles: { type: "array", items: { type: "string" } },
|
|
116
|
+
readableDirs: { type: "array", items: { type: "string" } },
|
|
117
|
+
contextRecycling: {
|
|
118
|
+
type: "object",
|
|
119
|
+
properties: {
|
|
120
|
+
taskProfile: { type: "string", enum: ["short", "long", "auto"] },
|
|
121
|
+
maxContextPercent: { type: "number" },
|
|
122
|
+
maxReplacements: { type: "integer" },
|
|
123
|
+
},
|
|
124
|
+
required: ["taskProfile"],
|
|
125
|
+
additionalProperties: false,
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
additionalProperties: false,
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
name: "swarm_bus",
|
|
133
|
+
description: "List live swarm sessions, send a notify/request/reply message, or request graceful peer shutdown.",
|
|
134
|
+
inputSchema: {
|
|
135
|
+
type: "object",
|
|
136
|
+
properties: {
|
|
137
|
+
action: { type: "string", enum: ["list", "send", "reply", "shutdown", "catalog"] },
|
|
138
|
+
targetSessionId: { type: "string" },
|
|
139
|
+
message: { type: "string" },
|
|
140
|
+
mode: { type: "string", enum: ["notify", "request"] },
|
|
141
|
+
replyTo: { type: "string" },
|
|
142
|
+
taskStatus: { type: "string", enum: ["working", "completed"] },
|
|
143
|
+
},
|
|
144
|
+
required: ["action"],
|
|
145
|
+
additionalProperties: false,
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
name: "swarm_leader_handoff",
|
|
150
|
+
description: "Publish a structured 10-section leader handoff for same-window replacement.",
|
|
151
|
+
inputSchema: {
|
|
152
|
+
type: "object",
|
|
153
|
+
properties: {
|
|
154
|
+
originalObjective: { type: "string" },
|
|
155
|
+
currentState: { type: "string" },
|
|
156
|
+
completedWork: { type: "string" },
|
|
157
|
+
remainingWork: { type: "string" },
|
|
158
|
+
modifiedFiles: { type: "string" },
|
|
159
|
+
verification: { type: "string" },
|
|
160
|
+
decisions: { type: "string" },
|
|
161
|
+
blocker: { type: "string" },
|
|
162
|
+
nextAction: { type: "string" },
|
|
163
|
+
artifacts: { type: "array", items: { type: "string" } },
|
|
164
|
+
},
|
|
165
|
+
required: [
|
|
166
|
+
"originalObjective",
|
|
167
|
+
"currentState",
|
|
168
|
+
"completedWork",
|
|
169
|
+
"remainingWork",
|
|
170
|
+
"modifiedFiles",
|
|
171
|
+
"verification",
|
|
172
|
+
"decisions",
|
|
173
|
+
"blocker",
|
|
174
|
+
"nextAction",
|
|
175
|
+
"artifacts",
|
|
176
|
+
],
|
|
177
|
+
additionalProperties: false,
|
|
178
|
+
},
|
|
179
|
+
},
|
|
180
|
+
] as const;
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Self-contained stdio-to-Unix-socket MCP proxy executed by `node -e`.
|
|
184
|
+
* Keeps `dist/index.ts` single-bundle clean with zero relative script-file fragility.
|
|
185
|
+
*/
|
|
186
|
+
const STDIO_PROXY_SCRIPT = `
|
|
187
|
+
const net = require("node:net");
|
|
188
|
+
const sockPath = process.argv[1];
|
|
189
|
+
const token = process.env.PI_SWARM_MCP_TOKEN || "";
|
|
190
|
+
const client = net.createConnection(sockPath);
|
|
191
|
+
let connected = false;
|
|
192
|
+
let stdinEnded = false;
|
|
193
|
+
const queuedLines = [];
|
|
194
|
+
client.on("connect", () => {
|
|
195
|
+
client.write(JSON.stringify({ authToken: token }) + "\\n");
|
|
196
|
+
connected = true;
|
|
197
|
+
while (queuedLines.length > 0) {
|
|
198
|
+
client.write(queuedLines.shift() + "\\n");
|
|
199
|
+
}
|
|
200
|
+
if (stdinEnded) client.end();
|
|
201
|
+
});
|
|
202
|
+
let stdinBuf = "";
|
|
203
|
+
process.stdin.setEncoding("utf8");
|
|
204
|
+
process.stdin.on("data", (chunk) => {
|
|
205
|
+
stdinBuf += chunk;
|
|
206
|
+
let nl;
|
|
207
|
+
while ((nl = stdinBuf.indexOf("\\n")) >= 0) {
|
|
208
|
+
const line = stdinBuf.slice(0, nl).trim();
|
|
209
|
+
stdinBuf = stdinBuf.slice(nl + 1);
|
|
210
|
+
if (!line) continue;
|
|
211
|
+
if (connected) client.write(line + "\\n");
|
|
212
|
+
else queuedLines.push(line);
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
let sockBuf = "";
|
|
216
|
+
client.setEncoding("utf8");
|
|
217
|
+
client.on("data", (chunk) => {
|
|
218
|
+
sockBuf += chunk;
|
|
219
|
+
let nl;
|
|
220
|
+
while ((nl = sockBuf.indexOf("\\n")) >= 0) {
|
|
221
|
+
const line = sockBuf.slice(0, nl);
|
|
222
|
+
sockBuf = sockBuf.slice(nl + 1);
|
|
223
|
+
if (line.trim()) process.stdout.write(line + "\\n");
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
client.on("error", (err) => {
|
|
227
|
+
process.stderr.write("swarm-lead-mcp proxy error: " + err.message + "\\n");
|
|
228
|
+
process.exit(1);
|
|
229
|
+
});
|
|
230
|
+
client.on("close", () => process.exit(0));
|
|
231
|
+
process.stdin.on("end", () => {
|
|
232
|
+
stdinEnded = true;
|
|
233
|
+
if (connected) client.end();
|
|
234
|
+
});
|
|
235
|
+
`.trim();
|
|
236
|
+
|
|
237
|
+
export class LeadMcpBridge {
|
|
238
|
+
private server: Server | undefined;
|
|
239
|
+
private socketPath: string | undefined;
|
|
240
|
+
private token: string | undefined;
|
|
241
|
+
private readonly sockets = new Set<Socket>();
|
|
242
|
+
private registered = false;
|
|
243
|
+
|
|
244
|
+
constructor(
|
|
245
|
+
private readonly pi: ExtensionAPI,
|
|
246
|
+
private readonly actions: LeadMcpBridgeActions,
|
|
247
|
+
private readonly runtimeBaseDirectory?: string,
|
|
248
|
+
) {}
|
|
249
|
+
|
|
250
|
+
get active(): boolean {
|
|
251
|
+
return this.server !== undefined && this.socketPath !== undefined;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
getSocketPath(): string | undefined {
|
|
255
|
+
return this.socketPath;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
getToken(): string | undefined {
|
|
259
|
+
return this.token;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async start(): Promise<void> {
|
|
263
|
+
// Hard security boundary: NEVER expose lead MCP tools to worker sessions.
|
|
264
|
+
if (this.actions.getRole() !== "lead") {
|
|
265
|
+
throw new Error("Refusing to start swarm-lead MCP bridge in a non-lead worker session");
|
|
266
|
+
}
|
|
267
|
+
if (this.server) return;
|
|
268
|
+
|
|
269
|
+
const baseDir = join(this.runtimeBaseDirectory ?? defaultRuntimeBaseDirectory(), "lead-mcp");
|
|
270
|
+
await mkdir(baseDir, { recursive: true, mode: 0o700 });
|
|
271
|
+
await chmod(baseDir, 0o700).catch(() => undefined);
|
|
272
|
+
await cleanupStaleLeadMcpSockets(baseDir).catch(() => undefined);
|
|
273
|
+
|
|
274
|
+
const token = randomBytes(32).toString("hex");
|
|
275
|
+
const socketPath = join(baseDir, `lmcp-${randomBytes(8).toString("hex")}.sock`);
|
|
276
|
+
const server = createServer((socket) => {
|
|
277
|
+
this.handleConnection(socket, token);
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
await new Promise<void>((resolvePromise, rejectPromise) => {
|
|
281
|
+
const onError = (err: Error) => rejectPromise(err);
|
|
282
|
+
server.once("error", onError);
|
|
283
|
+
server.listen(socketPath, () => {
|
|
284
|
+
server.off("error", onError);
|
|
285
|
+
resolvePromise();
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
await chmod(socketPath, 0o600).catch(() => undefined);
|
|
289
|
+
|
|
290
|
+
this.server = server;
|
|
291
|
+
this.socketPath = socketPath;
|
|
292
|
+
this.token = token;
|
|
293
|
+
|
|
294
|
+
const registerMcp = (this.pi as unknown as { registerMcpServer?: (name: string, config: unknown) => void })
|
|
295
|
+
.registerMcpServer;
|
|
296
|
+
if (typeof registerMcp === "function") {
|
|
297
|
+
registerMcp.call(this.pi, LEAD_MCP_SERVER_NAME, {
|
|
298
|
+
command: process.execPath,
|
|
299
|
+
args: ["-e", STDIO_PROXY_SCRIPT, socketPath],
|
|
300
|
+
env: { PI_SWARM_MCP_TOKEN: token },
|
|
301
|
+
description:
|
|
302
|
+
"Session-private Swarm Lead orchestration bridge (swarm_catalog, swarm_spawn, swarm_bus, swarm_leader_handoff). Exposed only to role=lead sessions.",
|
|
303
|
+
});
|
|
304
|
+
this.registered = true;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async stop(): Promise<void> {
|
|
309
|
+
const server = this.server;
|
|
310
|
+
const socketPath = this.socketPath;
|
|
311
|
+
this.server = undefined;
|
|
312
|
+
this.socketPath = undefined;
|
|
313
|
+
this.token = undefined;
|
|
314
|
+
|
|
315
|
+
for (const socket of this.sockets) {
|
|
316
|
+
socket.destroy();
|
|
317
|
+
}
|
|
318
|
+
this.sockets.clear();
|
|
319
|
+
|
|
320
|
+
if (server) {
|
|
321
|
+
await new Promise<void>((resolvePromise) => {
|
|
322
|
+
server.close(() => resolvePromise());
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
if (socketPath) {
|
|
326
|
+
await rm(socketPath, { force: true }).catch(() => undefined);
|
|
327
|
+
}
|
|
328
|
+
if (this.registered) {
|
|
329
|
+
const unregisterMcp = (this.pi as unknown as { unregisterMcpServer?: (name: string) => void })
|
|
330
|
+
.unregisterMcpServer;
|
|
331
|
+
if (typeof unregisterMcp === "function") {
|
|
332
|
+
try {
|
|
333
|
+
unregisterMcp.call(this.pi, LEAD_MCP_SERVER_NAME);
|
|
334
|
+
} catch {
|
|
335
|
+
// Best-effort unregister.
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
this.registered = false;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
private handleConnection(socket: Socket, expectedToken: string): void {
|
|
343
|
+
this.sockets.add(socket);
|
|
344
|
+
socket.setEncoding("utf8");
|
|
345
|
+
let authenticated = false;
|
|
346
|
+
let buffer = "";
|
|
347
|
+
|
|
348
|
+
socket.on("data", (chunk: string) => {
|
|
349
|
+
buffer += chunk;
|
|
350
|
+
let newlineIdx = buffer.indexOf("\n");
|
|
351
|
+
while (newlineIdx >= 0) {
|
|
352
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
353
|
+
buffer = buffer.slice(newlineIdx + 1);
|
|
354
|
+
newlineIdx = buffer.indexOf("\n");
|
|
355
|
+
if (!line) continue;
|
|
356
|
+
|
|
357
|
+
let parsed: Record<string, unknown>;
|
|
358
|
+
try {
|
|
359
|
+
parsed = JSON.parse(line) as Record<string, unknown>;
|
|
360
|
+
} catch {
|
|
361
|
+
socket.destroy();
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
if (!authenticated) {
|
|
366
|
+
const candidate = typeof parsed.authToken === "string" ? parsed.authToken : "";
|
|
367
|
+
const expectedBuf = Buffer.from(expectedToken, "utf8");
|
|
368
|
+
const actualBuf = Buffer.from(candidate, "utf8");
|
|
369
|
+
if (expectedBuf.length !== actualBuf.length || !timingSafeEqual(expectedBuf, actualBuf)) {
|
|
370
|
+
socket.destroy();
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
authenticated = true;
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
void this.dispatchRpc(parsed as JsonRpcRequest).then((response) => {
|
|
378
|
+
if (response && !socket.destroyed) {
|
|
379
|
+
socket.write(`${JSON.stringify(response)}\n`);
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
socket.on("close", () => {
|
|
386
|
+
this.sockets.delete(socket);
|
|
387
|
+
});
|
|
388
|
+
socket.on("error", () => {
|
|
389
|
+
this.sockets.delete(socket);
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private async dispatchRpc(request: JsonRpcRequest): Promise<Record<string, unknown> | undefined> {
|
|
394
|
+
const hasId = Object.hasOwn(request, "id") && request.id !== undefined;
|
|
395
|
+
const id = request.id;
|
|
396
|
+
const method = request.method;
|
|
397
|
+
if (!method) return undefined;
|
|
398
|
+
|
|
399
|
+
// JSON-RPC 2.0 notifications omit `id` and MUST NOT receive a response
|
|
400
|
+
// (e.g., `notifications/initialized`, `notifications/roots/list_changed`, `notifications/cancelled`).
|
|
401
|
+
if (!hasId || method.startsWith("notifications/")) {
|
|
402
|
+
return undefined;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
if (method === "ping") {
|
|
406
|
+
return {
|
|
407
|
+
jsonrpc: "2.0",
|
|
408
|
+
id: id ?? null,
|
|
409
|
+
result: {},
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
if (method === "initialize") {
|
|
414
|
+
return {
|
|
415
|
+
jsonrpc: "2.0",
|
|
416
|
+
id: id ?? null,
|
|
417
|
+
result: {
|
|
418
|
+
protocolVersion: "2024-11-05",
|
|
419
|
+
capabilities: { tools: {} },
|
|
420
|
+
serverInfo: { name: LEAD_MCP_SERVER_NAME, version: "1.0.0" },
|
|
421
|
+
},
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
if (method === "tools/list") {
|
|
426
|
+
return {
|
|
427
|
+
jsonrpc: "2.0",
|
|
428
|
+
id: id ?? null,
|
|
429
|
+
result: { tools: LEAD_MCP_TOOLS },
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
if (method === "tools/call") {
|
|
434
|
+
const params = request.params ?? {};
|
|
435
|
+
const toolName = typeof params.name === "string" ? params.name : "";
|
|
436
|
+
const args =
|
|
437
|
+
params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments)
|
|
438
|
+
? (params.arguments as Record<string, unknown>)
|
|
439
|
+
: {};
|
|
440
|
+
try {
|
|
441
|
+
const result = await this.executeTool(toolName, args);
|
|
442
|
+
return {
|
|
443
|
+
jsonrpc: "2.0",
|
|
444
|
+
id: id ?? null,
|
|
445
|
+
result: {
|
|
446
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
447
|
+
},
|
|
448
|
+
};
|
|
449
|
+
} catch (error) {
|
|
450
|
+
return {
|
|
451
|
+
jsonrpc: "2.0",
|
|
452
|
+
id: id ?? null,
|
|
453
|
+
result: {
|
|
454
|
+
isError: true,
|
|
455
|
+
content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
|
|
456
|
+
},
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
return {
|
|
462
|
+
jsonrpc: "2.0",
|
|
463
|
+
id: id ?? null,
|
|
464
|
+
error: { code: -32601, message: `Method not found: ${method}` },
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
private async executeTool(name: string, args: Record<string, unknown>): Promise<unknown> {
|
|
469
|
+
if (this.actions.getRole() !== "lead") {
|
|
470
|
+
throw new Error("swarm-lead MCP tools are restricted to lead sessions");
|
|
471
|
+
}
|
|
472
|
+
const ctx = this.actions.getContext();
|
|
473
|
+
if (!ctx) throw new Error("Swarm lead session context is not active");
|
|
474
|
+
|
|
475
|
+
switch (name) {
|
|
476
|
+
case "swarm_catalog":
|
|
477
|
+
return this.actions.catalog(ctx);
|
|
478
|
+
case "swarm_spawn":
|
|
479
|
+
return this.actions.spawn(ctx, args as unknown as SpawnSessionInput);
|
|
480
|
+
case "swarm_bus": {
|
|
481
|
+
const action = typeof args.action === "string" ? args.action : "";
|
|
482
|
+
if (action === "catalog") return this.actions.catalog(ctx);
|
|
483
|
+
if (action === "list") return this.actions.snapshot();
|
|
484
|
+
if (action === "shutdown") {
|
|
485
|
+
if (typeof args.targetSessionId !== "string" || !args.targetSessionId) {
|
|
486
|
+
throw new Error("swarm_bus shutdown requires targetSessionId");
|
|
487
|
+
}
|
|
488
|
+
return this.actions.shutdownPeer(ctx, args.targetSessionId);
|
|
489
|
+
}
|
|
490
|
+
if (action === "send" || action === "reply") {
|
|
491
|
+
if (typeof args.targetSessionId !== "string" || !args.targetSessionId) {
|
|
492
|
+
throw new Error(`swarm_bus ${action} requires targetSessionId`);
|
|
493
|
+
}
|
|
494
|
+
if (typeof args.message !== "string" || !args.message) {
|
|
495
|
+
throw new Error(`swarm_bus ${action} requires message`);
|
|
496
|
+
}
|
|
497
|
+
const mode = action === "reply" ? "reply" : args.mode === "request" ? "request" : "notify";
|
|
498
|
+
return this.actions.send(ctx, {
|
|
499
|
+
targetSessionId: args.targetSessionId,
|
|
500
|
+
text: args.message,
|
|
501
|
+
mode,
|
|
502
|
+
...(typeof args.replyTo === "string" ? { replyTo: args.replyTo } : {}),
|
|
503
|
+
...(args.taskStatus === "working" || args.taskStatus === "completed"
|
|
504
|
+
? { taskStatus: args.taskStatus }
|
|
505
|
+
: {}),
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
throw new Error(`Unsupported swarm_bus action "${action}"`);
|
|
509
|
+
}
|
|
510
|
+
case "swarm_leader_handoff":
|
|
511
|
+
return this.actions.publishLeaderHandoff(ctx, args as unknown as LeaderHandoffContent);
|
|
512
|
+
default:
|
|
513
|
+
throw new Error(`Unknown swarm-lead MCP tool "${name}"`);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import type { LeaderRecyclingPolicy } from "./leader-recycling.js";
|
|
3
|
+
import type { SwarmMessage } from "./protocol.js";
|
|
4
|
+
|
|
5
|
+
export const LEADER_HANDOFF_BRIDGE_TTL_MS = 30_000;
|
|
6
|
+
export const LEADER_HANDOFF_BRIDGE_FALLBACK_TTL_MS = 30 * 60_000;
|
|
7
|
+
export const LEADER_HANDOFF_BRIDGE_APPLY_TTL_MS = 10 * 60_000;
|
|
8
|
+
export const LEADER_HANDOFF_BRIDGE_SYMBOL = Symbol.for("pi-agent-swarm/leader-handoff-bridge");
|
|
9
|
+
|
|
10
|
+
export interface LeaderHandoffBridgeInput {
|
|
11
|
+
lineageId: string;
|
|
12
|
+
generation: number;
|
|
13
|
+
replacementCount: number;
|
|
14
|
+
policy: LeaderRecyclingPolicy;
|
|
15
|
+
handoffPath: string;
|
|
16
|
+
previousSessionFile: string;
|
|
17
|
+
previousSessionId: string;
|
|
18
|
+
name?: string;
|
|
19
|
+
color?: string;
|
|
20
|
+
model?: string;
|
|
21
|
+
thinkingLevel?: string;
|
|
22
|
+
invite?: string;
|
|
23
|
+
groupDirectory?: string;
|
|
24
|
+
acceptsRequests: boolean;
|
|
25
|
+
nextAction: string;
|
|
26
|
+
/** Distinguishes automatic failures from an explicit /swarm handoff across newSession. */
|
|
27
|
+
automatic?: boolean;
|
|
28
|
+
editorDraft?: string;
|
|
29
|
+
deferredFollowUps?: SwarmMessage[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface LeaderHandoffBridgeEntry extends LeaderHandoffBridgeInput {
|
|
33
|
+
token: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface LeaderHandoffBridge {
|
|
37
|
+
put(value: LeaderHandoffBridgeInput, now?: number): LeaderHandoffBridgeEntry;
|
|
38
|
+
take(token: string, previousSessionFile: string, now?: number): LeaderHandoffBridgeEntry | undefined;
|
|
39
|
+
peek(token: string, previousSessionFile: string, now?: number): LeaderHandoffBridgeEntry | undefined;
|
|
40
|
+
arm(token: string, previousSessionFile: string, now?: number, ttlMs?: number): LeaderHandoffBridgeEntry | undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
type StoredLeaderHandoff = {
|
|
44
|
+
entry: LeaderHandoffBridgeEntry;
|
|
45
|
+
expiresAt: number;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
type LeaderHandoffBridgeGlobal = typeof globalThis & {
|
|
49
|
+
[LEADER_HANDOFF_BRIDGE_SYMBOL]?: LeaderHandoffBridge;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
function bridgeKey(token: string, previousSessionFile: string): string {
|
|
53
|
+
return `${token}\u0000${previousSessionFile}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function createLeaderHandoffBridge(): LeaderHandoffBridge {
|
|
57
|
+
const entries = new Map<string, StoredLeaderHandoff>();
|
|
58
|
+
const purge = (now: number): void => {
|
|
59
|
+
for (const [key, value] of entries) {
|
|
60
|
+
if (now >= value.expiresAt) entries.delete(key);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const peek: LeaderHandoffBridge["peek"] = (token, previousSessionFile, now = Date.now()) => {
|
|
64
|
+
purge(now);
|
|
65
|
+
return entries.get(bridgeKey(token, previousSessionFile))?.entry;
|
|
66
|
+
};
|
|
67
|
+
return {
|
|
68
|
+
put(value, now = Date.now()) {
|
|
69
|
+
purge(now);
|
|
70
|
+
// JSON serialization rejects cycles/BigInt and ensures no SessionManager or runtime object is retained.
|
|
71
|
+
const data = JSON.parse(JSON.stringify(value)) as LeaderHandoffBridgeInput;
|
|
72
|
+
const entry: LeaderHandoffBridgeEntry = {
|
|
73
|
+
...data,
|
|
74
|
+
token: randomBytes(24).toString("base64url"),
|
|
75
|
+
};
|
|
76
|
+
entries.set(bridgeKey(entry.token, entry.previousSessionFile), {
|
|
77
|
+
entry,
|
|
78
|
+
// Reset normally removes staged entries; this finite fallback bounds secrets after an interrupted lifecycle.
|
|
79
|
+
expiresAt: now + LEADER_HANDOFF_BRIDGE_FALLBACK_TTL_MS,
|
|
80
|
+
});
|
|
81
|
+
return entry;
|
|
82
|
+
},
|
|
83
|
+
peek,
|
|
84
|
+
arm(token, previousSessionFile, now = Date.now(), ttlMs = LEADER_HANDOFF_BRIDGE_TTL_MS) {
|
|
85
|
+
const entry = peek(token, previousSessionFile, now);
|
|
86
|
+
if (!entry) return undefined;
|
|
87
|
+
const stored = entries.get(bridgeKey(token, previousSessionFile));
|
|
88
|
+
if (stored) stored.expiresAt = now + ttlMs;
|
|
89
|
+
return entry;
|
|
90
|
+
},
|
|
91
|
+
take(token, previousSessionFile, now = Date.now()) {
|
|
92
|
+
const key = bridgeKey(token, previousSessionFile);
|
|
93
|
+
const entry = peek(token, previousSessionFile, now);
|
|
94
|
+
entries.delete(key);
|
|
95
|
+
return entry;
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const bridgeGlobal = globalThis as LeaderHandoffBridgeGlobal;
|
|
101
|
+
bridgeGlobal[LEADER_HANDOFF_BRIDGE_SYMBOL] ??= createLeaderHandoffBridge();
|
|
102
|
+
|
|
103
|
+
/** Process-local only: invites and editor drafts are never persisted by this bridge. */
|
|
104
|
+
export const leaderHandoffBridge = bridgeGlobal[LEADER_HANDOFF_BRIDGE_SYMBOL];
|
|
105
|
+
|
|
106
|
+
export type LeaderHandoffSuccessorRegistration = {
|
|
107
|
+
token: string;
|
|
108
|
+
previousSessionFile: string;
|
|
109
|
+
lineageId: string;
|
|
110
|
+
generation: number;
|
|
111
|
+
previousSessionId?: string;
|
|
112
|
+
groupDirectory?: string;
|
|
113
|
+
/** The handoff that produced this successor came from an automatic advisory. */
|
|
114
|
+
automatic?: boolean;
|
|
115
|
+
};
|
|
116
|
+
const SUCCESSOR_REGISTRATIONS_SYMBOL = Symbol.for("pi-agent-swarm/leader-successor-registrations");
|
|
117
|
+
type SuccessorRegistrationGlobal = typeof globalThis & {
|
|
118
|
+
[SUCCESSOR_REGISTRATIONS_SYMBOL]?: WeakMap<object, LeaderHandoffSuccessorRegistration>;
|
|
119
|
+
};
|
|
120
|
+
const successorGlobal = globalThis as SuccessorRegistrationGlobal;
|
|
121
|
+
successorGlobal[SUCCESSOR_REGISTRATIONS_SYMBOL] ??= new WeakMap<object, LeaderHandoffSuccessorRegistration>();
|
|
122
|
+
const successorRegistrations = successorGlobal[SUCCESSOR_REGISTRATIONS_SYMBOL];
|
|
123
|
+
|
|
124
|
+
/** setup() runs before session_start; key only by the successor's new SessionManager. */
|
|
125
|
+
export function registerLeaderHandoffSuccessor(
|
|
126
|
+
sessionManager: object,
|
|
127
|
+
token: string,
|
|
128
|
+
previousSessionFile: string,
|
|
129
|
+
lineageId: string,
|
|
130
|
+
generation: number,
|
|
131
|
+
previousSessionId?: string,
|
|
132
|
+
groupDirectory?: string,
|
|
133
|
+
automatic?: boolean,
|
|
134
|
+
): void {
|
|
135
|
+
successorRegistrations.set(sessionManager, {
|
|
136
|
+
token,
|
|
137
|
+
previousSessionFile,
|
|
138
|
+
lineageId,
|
|
139
|
+
generation,
|
|
140
|
+
previousSessionId,
|
|
141
|
+
groupDirectory,
|
|
142
|
+
automatic,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function takeLeaderHandoffSuccessor(
|
|
147
|
+
sessionManager: object,
|
|
148
|
+
previousSessionFile?: string,
|
|
149
|
+
): LeaderHandoffSuccessorRegistration | undefined {
|
|
150
|
+
const registration = successorRegistrations.get(sessionManager);
|
|
151
|
+
if (!registration || (previousSessionFile && registration.previousSessionFile !== previousSessionFile))
|
|
152
|
+
return undefined;
|
|
153
|
+
successorRegistrations.delete(sessionManager);
|
|
154
|
+
return registration;
|
|
155
|
+
}
|