pi-agent-swarm 0.4.0 → 0.6.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 +8318 -1148
- 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/cache-warming.ts +147 -0
- package/src/context-recycling.ts +257 -52
- package/src/external-runtime.ts +590 -0
- package/src/fanout.ts +219 -0
- package/src/launch-envelope.ts +64 -0
- package/src/lead-mcp-bridge.ts +557 -0
- package/src/leader-handoff-bridge.ts +161 -0
- package/src/leader-recycling.ts +765 -0
- package/src/leader-runtime.ts +1220 -0
- package/src/leader-session-runtime.ts +94 -0
- package/src/ledger.ts +378 -0
- package/src/mission.ts +293 -0
- package/src/model-catalog.ts +213 -0
- package/src/org.ts +252 -0
- package/src/pi-agent-swarm.ts +31 -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 +279 -0
- package/src/settings.ts +537 -10
- package/src/swarm-controller.ts +2359 -102
- package/src/tools.ts +246 -5
- package/src/worktree.ts +86 -0
|
@@ -0,0 +1,557 @@
|
|
|
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
|
+
mission?: (
|
|
79
|
+
ctx: ExtensionContext,
|
|
80
|
+
input: {
|
|
81
|
+
missionAction: "start" | "complete" | "status";
|
|
82
|
+
firstPrinciples?: string;
|
|
83
|
+
acceptanceCriteria?: string;
|
|
84
|
+
constraints?: string;
|
|
85
|
+
estimatedMinutes?: number;
|
|
86
|
+
summary?: string;
|
|
87
|
+
outcome?: "achieved" | "with_residuals";
|
|
88
|
+
residuals?: string[];
|
|
89
|
+
},
|
|
90
|
+
) => Promise<unknown>;
|
|
91
|
+
publishLeaderHandoff: (ctx: ExtensionContext, handoff: LeaderHandoffContent) => Promise<unknown>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
interface JsonRpcRequest {
|
|
95
|
+
jsonrpc?: string;
|
|
96
|
+
id?: string | number | null;
|
|
97
|
+
method?: string;
|
|
98
|
+
params?: Record<string, unknown>;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const LEAD_MCP_TOOLS = [
|
|
102
|
+
{
|
|
103
|
+
name: "swarm_catalog",
|
|
104
|
+
description:
|
|
105
|
+
"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).",
|
|
106
|
+
inputSchema: {
|
|
107
|
+
type: "object",
|
|
108
|
+
properties: {},
|
|
109
|
+
additionalProperties: false,
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
name: "swarm_spawn",
|
|
114
|
+
description:
|
|
115
|
+
"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.",
|
|
116
|
+
inputSchema: {
|
|
117
|
+
type: "object",
|
|
118
|
+
properties: {
|
|
119
|
+
role: { type: "string", enum: ["implementer", "researcher", "reviewer"] },
|
|
120
|
+
profile: { type: "string" },
|
|
121
|
+
model: { type: "string" },
|
|
122
|
+
task: { type: "string" },
|
|
123
|
+
name: { type: "string" },
|
|
124
|
+
color: { type: "string" },
|
|
125
|
+
cwd: { type: "string" },
|
|
126
|
+
direction: { type: "string", enum: ["right", "down", "left", "up"] },
|
|
127
|
+
allowRequests: { type: "boolean" },
|
|
128
|
+
contextFiles: { type: "array", items: { type: "string" } },
|
|
129
|
+
readableDirs: { type: "array", items: { type: "string" } },
|
|
130
|
+
contextRecycling: {
|
|
131
|
+
type: "object",
|
|
132
|
+
properties: {
|
|
133
|
+
taskProfile: { type: "string", enum: ["short", "long", "auto"] },
|
|
134
|
+
maxContextPercent: { type: "number" },
|
|
135
|
+
maxReplacements: { type: "integer" },
|
|
136
|
+
},
|
|
137
|
+
required: ["taskProfile"],
|
|
138
|
+
additionalProperties: false,
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
additionalProperties: false,
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
name: "swarm_bus",
|
|
146
|
+
description:
|
|
147
|
+
'List live swarm sessions, manage the mandatory first-principles mission countdown (action="mission"), send a notify/request/reply message, or request graceful peer shutdown.',
|
|
148
|
+
inputSchema: {
|
|
149
|
+
type: "object",
|
|
150
|
+
properties: {
|
|
151
|
+
action: { type: "string", enum: ["list", "send", "reply", "shutdown", "catalog", "mission"] },
|
|
152
|
+
targetSessionId: { type: "string" },
|
|
153
|
+
message: { type: "string" },
|
|
154
|
+
mode: { type: "string", enum: ["notify", "request"] },
|
|
155
|
+
replyTo: { type: "string" },
|
|
156
|
+
taskStatus: { type: "string", enum: ["working", "completed"] },
|
|
157
|
+
missionAction: { type: "string", enum: ["start", "complete", "status"] },
|
|
158
|
+
firstPrinciples: { type: "string" },
|
|
159
|
+
acceptanceCriteria: { type: "string" },
|
|
160
|
+
constraints: { type: "string" },
|
|
161
|
+
estimatedMinutes: { type: "number" },
|
|
162
|
+
summary: { type: "string" },
|
|
163
|
+
outcome: { type: "string", enum: ["achieved", "with_residuals"] },
|
|
164
|
+
residuals: { type: "array", items: { type: "string" } },
|
|
165
|
+
},
|
|
166
|
+
required: ["action"],
|
|
167
|
+
additionalProperties: false,
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
name: "swarm_leader_handoff",
|
|
172
|
+
description: "Publish a structured 10-section leader handoff for same-window replacement.",
|
|
173
|
+
inputSchema: {
|
|
174
|
+
type: "object",
|
|
175
|
+
properties: {
|
|
176
|
+
originalObjective: { type: "string" },
|
|
177
|
+
currentState: { type: "string" },
|
|
178
|
+
completedWork: { type: "string" },
|
|
179
|
+
remainingWork: { type: "string" },
|
|
180
|
+
modifiedFiles: { type: "string" },
|
|
181
|
+
verification: { type: "string" },
|
|
182
|
+
decisions: { type: "string" },
|
|
183
|
+
blocker: { type: "string" },
|
|
184
|
+
nextAction: { type: "string" },
|
|
185
|
+
artifacts: { type: "array", items: { type: "string" } },
|
|
186
|
+
},
|
|
187
|
+
required: [
|
|
188
|
+
"originalObjective",
|
|
189
|
+
"currentState",
|
|
190
|
+
"completedWork",
|
|
191
|
+
"remainingWork",
|
|
192
|
+
"modifiedFiles",
|
|
193
|
+
"verification",
|
|
194
|
+
"decisions",
|
|
195
|
+
"blocker",
|
|
196
|
+
"nextAction",
|
|
197
|
+
"artifacts",
|
|
198
|
+
],
|
|
199
|
+
additionalProperties: false,
|
|
200
|
+
},
|
|
201
|
+
},
|
|
202
|
+
] as const;
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Self-contained stdio-to-Unix-socket MCP proxy executed by `node -e`.
|
|
206
|
+
* Keeps `dist/index.ts` single-bundle clean with zero relative script-file fragility.
|
|
207
|
+
*/
|
|
208
|
+
const STDIO_PROXY_SCRIPT = `
|
|
209
|
+
const net = require("node:net");
|
|
210
|
+
const sockPath = process.argv[1];
|
|
211
|
+
const token = process.env.PI_SWARM_MCP_TOKEN || "";
|
|
212
|
+
const client = net.createConnection(sockPath);
|
|
213
|
+
let connected = false;
|
|
214
|
+
let stdinEnded = false;
|
|
215
|
+
const queuedLines = [];
|
|
216
|
+
client.on("connect", () => {
|
|
217
|
+
client.write(JSON.stringify({ authToken: token }) + "\\n");
|
|
218
|
+
connected = true;
|
|
219
|
+
while (queuedLines.length > 0) {
|
|
220
|
+
client.write(queuedLines.shift() + "\\n");
|
|
221
|
+
}
|
|
222
|
+
if (stdinEnded) client.end();
|
|
223
|
+
});
|
|
224
|
+
let stdinBuf = "";
|
|
225
|
+
process.stdin.setEncoding("utf8");
|
|
226
|
+
process.stdin.on("data", (chunk) => {
|
|
227
|
+
stdinBuf += chunk;
|
|
228
|
+
let nl;
|
|
229
|
+
while ((nl = stdinBuf.indexOf("\\n")) >= 0) {
|
|
230
|
+
const line = stdinBuf.slice(0, nl).trim();
|
|
231
|
+
stdinBuf = stdinBuf.slice(nl + 1);
|
|
232
|
+
if (!line) continue;
|
|
233
|
+
if (connected) client.write(line + "\\n");
|
|
234
|
+
else queuedLines.push(line);
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
let sockBuf = "";
|
|
238
|
+
client.setEncoding("utf8");
|
|
239
|
+
client.on("data", (chunk) => {
|
|
240
|
+
sockBuf += chunk;
|
|
241
|
+
let nl;
|
|
242
|
+
while ((nl = sockBuf.indexOf("\\n")) >= 0) {
|
|
243
|
+
const line = sockBuf.slice(0, nl);
|
|
244
|
+
sockBuf = sockBuf.slice(nl + 1);
|
|
245
|
+
if (line.trim()) process.stdout.write(line + "\\n");
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
client.on("error", (err) => {
|
|
249
|
+
process.stderr.write("swarm-lead-mcp proxy error: " + err.message + "\\n");
|
|
250
|
+
process.exit(1);
|
|
251
|
+
});
|
|
252
|
+
client.on("close", () => process.exit(0));
|
|
253
|
+
process.stdin.on("end", () => {
|
|
254
|
+
stdinEnded = true;
|
|
255
|
+
if (connected) client.end();
|
|
256
|
+
});
|
|
257
|
+
`.trim();
|
|
258
|
+
|
|
259
|
+
export class LeadMcpBridge {
|
|
260
|
+
private server: Server | undefined;
|
|
261
|
+
private socketPath: string | undefined;
|
|
262
|
+
private token: string | undefined;
|
|
263
|
+
private readonly sockets = new Set<Socket>();
|
|
264
|
+
private registered = false;
|
|
265
|
+
|
|
266
|
+
constructor(
|
|
267
|
+
private readonly pi: ExtensionAPI,
|
|
268
|
+
private readonly actions: LeadMcpBridgeActions,
|
|
269
|
+
private readonly runtimeBaseDirectory?: string,
|
|
270
|
+
) {}
|
|
271
|
+
|
|
272
|
+
get active(): boolean {
|
|
273
|
+
return this.server !== undefined && this.socketPath !== undefined;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
getSocketPath(): string | undefined {
|
|
277
|
+
return this.socketPath;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
getToken(): string | undefined {
|
|
281
|
+
return this.token;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async start(): Promise<void> {
|
|
285
|
+
// Hard security boundary: NEVER expose lead MCP tools to worker sessions.
|
|
286
|
+
if (this.actions.getRole() !== "lead") {
|
|
287
|
+
throw new Error("Refusing to start swarm-lead MCP bridge in a non-lead worker session");
|
|
288
|
+
}
|
|
289
|
+
if (this.server) return;
|
|
290
|
+
|
|
291
|
+
const baseDir = join(this.runtimeBaseDirectory ?? defaultRuntimeBaseDirectory(), "lead-mcp");
|
|
292
|
+
await mkdir(baseDir, { recursive: true, mode: 0o700 });
|
|
293
|
+
await chmod(baseDir, 0o700).catch(() => undefined);
|
|
294
|
+
await cleanupStaleLeadMcpSockets(baseDir).catch(() => undefined);
|
|
295
|
+
|
|
296
|
+
const token = randomBytes(32).toString("hex");
|
|
297
|
+
const socketPath = join(baseDir, `lmcp-${randomBytes(8).toString("hex")}.sock`);
|
|
298
|
+
const server = createServer((socket) => {
|
|
299
|
+
this.handleConnection(socket, token);
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
await new Promise<void>((resolvePromise, rejectPromise) => {
|
|
303
|
+
const onError = (err: Error) => rejectPromise(err);
|
|
304
|
+
server.once("error", onError);
|
|
305
|
+
server.listen(socketPath, () => {
|
|
306
|
+
server.off("error", onError);
|
|
307
|
+
resolvePromise();
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
await chmod(socketPath, 0o600).catch(() => undefined);
|
|
311
|
+
|
|
312
|
+
this.server = server;
|
|
313
|
+
this.socketPath = socketPath;
|
|
314
|
+
this.token = token;
|
|
315
|
+
|
|
316
|
+
const registerMcp = (this.pi as unknown as { registerMcpServer?: (name: string, config: unknown) => void })
|
|
317
|
+
.registerMcpServer;
|
|
318
|
+
if (typeof registerMcp === "function") {
|
|
319
|
+
registerMcp.call(this.pi, LEAD_MCP_SERVER_NAME, {
|
|
320
|
+
command: process.execPath,
|
|
321
|
+
args: ["-e", STDIO_PROXY_SCRIPT, socketPath],
|
|
322
|
+
env: { PI_SWARM_MCP_TOKEN: token },
|
|
323
|
+
description:
|
|
324
|
+
"Session-private Swarm Lead orchestration bridge (swarm_catalog, swarm_spawn, swarm_bus, swarm_leader_handoff). Exposed only to role=lead sessions.",
|
|
325
|
+
});
|
|
326
|
+
this.registered = true;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async stop(): Promise<void> {
|
|
331
|
+
const server = this.server;
|
|
332
|
+
const socketPath = this.socketPath;
|
|
333
|
+
this.server = undefined;
|
|
334
|
+
this.socketPath = undefined;
|
|
335
|
+
this.token = undefined;
|
|
336
|
+
|
|
337
|
+
for (const socket of this.sockets) {
|
|
338
|
+
socket.destroy();
|
|
339
|
+
}
|
|
340
|
+
this.sockets.clear();
|
|
341
|
+
|
|
342
|
+
if (server) {
|
|
343
|
+
await new Promise<void>((resolvePromise) => {
|
|
344
|
+
server.close(() => resolvePromise());
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
if (socketPath) {
|
|
348
|
+
await rm(socketPath, { force: true }).catch(() => undefined);
|
|
349
|
+
}
|
|
350
|
+
if (this.registered) {
|
|
351
|
+
const unregisterMcp = (this.pi as unknown as { unregisterMcpServer?: (name: string) => void })
|
|
352
|
+
.unregisterMcpServer;
|
|
353
|
+
if (typeof unregisterMcp === "function") {
|
|
354
|
+
try {
|
|
355
|
+
unregisterMcp.call(this.pi, LEAD_MCP_SERVER_NAME);
|
|
356
|
+
} catch {
|
|
357
|
+
// Best-effort unregister.
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
this.registered = false;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
private handleConnection(socket: Socket, expectedToken: string): void {
|
|
365
|
+
this.sockets.add(socket);
|
|
366
|
+
socket.setEncoding("utf8");
|
|
367
|
+
let authenticated = false;
|
|
368
|
+
let buffer = "";
|
|
369
|
+
|
|
370
|
+
socket.on("data", (chunk: string) => {
|
|
371
|
+
buffer += chunk;
|
|
372
|
+
let newlineIdx = buffer.indexOf("\n");
|
|
373
|
+
while (newlineIdx >= 0) {
|
|
374
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
375
|
+
buffer = buffer.slice(newlineIdx + 1);
|
|
376
|
+
newlineIdx = buffer.indexOf("\n");
|
|
377
|
+
if (!line) continue;
|
|
378
|
+
|
|
379
|
+
let parsed: Record<string, unknown>;
|
|
380
|
+
try {
|
|
381
|
+
parsed = JSON.parse(line) as Record<string, unknown>;
|
|
382
|
+
} catch {
|
|
383
|
+
socket.destroy();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
if (!authenticated) {
|
|
388
|
+
const candidate = typeof parsed.authToken === "string" ? parsed.authToken : "";
|
|
389
|
+
const expectedBuf = Buffer.from(expectedToken, "utf8");
|
|
390
|
+
const actualBuf = Buffer.from(candidate, "utf8");
|
|
391
|
+
if (expectedBuf.length !== actualBuf.length || !timingSafeEqual(expectedBuf, actualBuf)) {
|
|
392
|
+
socket.destroy();
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
authenticated = true;
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
void this.dispatchRpc(parsed as JsonRpcRequest).then((response) => {
|
|
400
|
+
if (response && !socket.destroyed) {
|
|
401
|
+
socket.write(`${JSON.stringify(response)}\n`);
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
socket.on("close", () => {
|
|
408
|
+
this.sockets.delete(socket);
|
|
409
|
+
});
|
|
410
|
+
socket.on("error", () => {
|
|
411
|
+
this.sockets.delete(socket);
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
private async dispatchRpc(request: JsonRpcRequest): Promise<Record<string, unknown> | undefined> {
|
|
416
|
+
const hasId = Object.hasOwn(request, "id") && request.id !== undefined;
|
|
417
|
+
const id = request.id;
|
|
418
|
+
const method = request.method;
|
|
419
|
+
if (!method) return undefined;
|
|
420
|
+
|
|
421
|
+
// JSON-RPC 2.0 notifications omit `id` and MUST NOT receive a response
|
|
422
|
+
// (e.g., `notifications/initialized`, `notifications/roots/list_changed`, `notifications/cancelled`).
|
|
423
|
+
if (!hasId || method.startsWith("notifications/")) {
|
|
424
|
+
return undefined;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
if (method === "ping") {
|
|
428
|
+
return {
|
|
429
|
+
jsonrpc: "2.0",
|
|
430
|
+
id: id ?? null,
|
|
431
|
+
result: {},
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
if (method === "initialize") {
|
|
436
|
+
return {
|
|
437
|
+
jsonrpc: "2.0",
|
|
438
|
+
id: id ?? null,
|
|
439
|
+
result: {
|
|
440
|
+
protocolVersion: "2024-11-05",
|
|
441
|
+
capabilities: { tools: {} },
|
|
442
|
+
serverInfo: { name: LEAD_MCP_SERVER_NAME, version: "1.0.0" },
|
|
443
|
+
},
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (method === "tools/list") {
|
|
448
|
+
return {
|
|
449
|
+
jsonrpc: "2.0",
|
|
450
|
+
id: id ?? null,
|
|
451
|
+
result: { tools: LEAD_MCP_TOOLS },
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
if (method === "tools/call") {
|
|
456
|
+
const params = request.params ?? {};
|
|
457
|
+
const toolName = typeof params.name === "string" ? params.name : "";
|
|
458
|
+
const args =
|
|
459
|
+
params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments)
|
|
460
|
+
? (params.arguments as Record<string, unknown>)
|
|
461
|
+
: {};
|
|
462
|
+
try {
|
|
463
|
+
const result = await this.executeTool(toolName, args);
|
|
464
|
+
return {
|
|
465
|
+
jsonrpc: "2.0",
|
|
466
|
+
id: id ?? null,
|
|
467
|
+
result: {
|
|
468
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
469
|
+
},
|
|
470
|
+
};
|
|
471
|
+
} catch (error) {
|
|
472
|
+
return {
|
|
473
|
+
jsonrpc: "2.0",
|
|
474
|
+
id: id ?? null,
|
|
475
|
+
result: {
|
|
476
|
+
isError: true,
|
|
477
|
+
content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
|
|
478
|
+
},
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
return {
|
|
484
|
+
jsonrpc: "2.0",
|
|
485
|
+
id: id ?? null,
|
|
486
|
+
error: { code: -32601, message: `Method not found: ${method}` },
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
private async executeTool(name: string, args: Record<string, unknown>): Promise<unknown> {
|
|
491
|
+
if (this.actions.getRole() !== "lead") {
|
|
492
|
+
throw new Error("swarm-lead MCP tools are restricted to lead sessions");
|
|
493
|
+
}
|
|
494
|
+
const ctx = this.actions.getContext();
|
|
495
|
+
if (!ctx) throw new Error("Swarm lead session context is not active");
|
|
496
|
+
|
|
497
|
+
switch (name) {
|
|
498
|
+
case "swarm_catalog":
|
|
499
|
+
return this.actions.catalog(ctx);
|
|
500
|
+
case "swarm_spawn":
|
|
501
|
+
return this.actions.spawn(ctx, args as unknown as SpawnSessionInput);
|
|
502
|
+
case "swarm_bus": {
|
|
503
|
+
const action = typeof args.action === "string" ? args.action : "";
|
|
504
|
+
if (action === "catalog") return this.actions.catalog(ctx);
|
|
505
|
+
if (action === "list") return this.actions.snapshot();
|
|
506
|
+
if (action === "mission") {
|
|
507
|
+
if (!this.actions.mission) throw new Error("swarm_bus mission is unavailable");
|
|
508
|
+
const missionAction = args.missionAction;
|
|
509
|
+
if (missionAction !== "start" && missionAction !== "complete" && missionAction !== "status") {
|
|
510
|
+
throw new Error('swarm_bus mission requires missionAction ("start" | "complete" | "status")');
|
|
511
|
+
}
|
|
512
|
+
return this.actions.mission(ctx, {
|
|
513
|
+
missionAction,
|
|
514
|
+
...(typeof args.firstPrinciples === "string" ? { firstPrinciples: args.firstPrinciples } : {}),
|
|
515
|
+
...(typeof args.acceptanceCriteria === "string" ? { acceptanceCriteria: args.acceptanceCriteria } : {}),
|
|
516
|
+
...(typeof args.constraints === "string" ? { constraints: args.constraints } : {}),
|
|
517
|
+
...(typeof args.estimatedMinutes === "number" ? { estimatedMinutes: args.estimatedMinutes } : {}),
|
|
518
|
+
...(typeof args.summary === "string" ? { summary: args.summary } : {}),
|
|
519
|
+
...(args.outcome === "achieved" || args.outcome === "with_residuals" ? { outcome: args.outcome } : {}),
|
|
520
|
+
...(Array.isArray(args.residuals)
|
|
521
|
+
? { residuals: args.residuals.filter((r): r is string => typeof r === "string") }
|
|
522
|
+
: {}),
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
if (action === "shutdown") {
|
|
526
|
+
if (typeof args.targetSessionId !== "string" || !args.targetSessionId) {
|
|
527
|
+
throw new Error("swarm_bus shutdown requires targetSessionId");
|
|
528
|
+
}
|
|
529
|
+
return this.actions.shutdownPeer(ctx, args.targetSessionId);
|
|
530
|
+
}
|
|
531
|
+
if (action === "send" || action === "reply") {
|
|
532
|
+
if (typeof args.targetSessionId !== "string" || !args.targetSessionId) {
|
|
533
|
+
throw new Error(`swarm_bus ${action} requires targetSessionId`);
|
|
534
|
+
}
|
|
535
|
+
if (typeof args.message !== "string" || !args.message) {
|
|
536
|
+
throw new Error(`swarm_bus ${action} requires message`);
|
|
537
|
+
}
|
|
538
|
+
const mode = action === "reply" ? "reply" : args.mode === "request" ? "request" : "notify";
|
|
539
|
+
return this.actions.send(ctx, {
|
|
540
|
+
targetSessionId: args.targetSessionId,
|
|
541
|
+
text: args.message,
|
|
542
|
+
mode,
|
|
543
|
+
...(typeof args.replyTo === "string" ? { replyTo: args.replyTo } : {}),
|
|
544
|
+
...(args.taskStatus === "working" || args.taskStatus === "completed"
|
|
545
|
+
? { taskStatus: args.taskStatus }
|
|
546
|
+
: {}),
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
throw new Error(`Unsupported swarm_bus action "${action}"`);
|
|
550
|
+
}
|
|
551
|
+
case "swarm_leader_handoff":
|
|
552
|
+
return this.actions.publishLeaderHandoff(ctx, args as unknown as LeaderHandoffContent);
|
|
553
|
+
default:
|
|
554
|
+
throw new Error(`Unknown swarm-lead MCP tool "${name}"`);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|