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.
@@ -1,3 +1,6 @@
1
+ import { type ContextRecyclingLaunch, normalizeContextRecyclingPolicy } from "./context-recycling.js";
2
+ import type { WorkerRole } from "./profiles.js";
3
+
1
4
  type SwarmThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
2
5
 
3
6
  export const SWARM_LAUNCH_ENV_KEYS = [
@@ -11,6 +14,12 @@ export const SWARM_LAUNCH_ENV_KEYS = [
11
14
  "PI_SWARM_MODEL_PROVIDER",
12
15
  "PI_SWARM_MODEL_ID",
13
16
  "PI_SWARM_THINKING",
17
+ "PI_SWARM_CONTEXT_RECYCLING",
18
+ "PI_SWARM_ROLE",
19
+ "PI_SWARM_PROFILE",
20
+ "PI_SWARM_RUNTIME",
21
+ "PI_SWARM_RUNTIME_MODEL",
22
+ "PI_SWARM_READABLE_DIRS",
14
23
  ] as const;
15
24
 
16
25
  export interface SwarmLaunchEnvelope {
@@ -21,10 +30,18 @@ export interface SwarmLaunchEnvelope {
21
30
  childName?: string;
22
31
  childColor?: string;
23
32
  acceptsRequests: boolean;
33
+ contextRecycling?: ContextRecyclingLaunch;
24
34
  model?: { provider: string; id: string; thinkingLevel?: SwarmThinkingLevel };
35
+ role?: WorkerRole;
36
+ profile?: string;
37
+ runtime?: "pi" | "agy";
38
+ runtimeModel?: string;
39
+ readableDirs?: string[];
25
40
  }
26
41
 
27
42
  const THINKING_LEVELS = new Set<SwarmThinkingLevel>(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
43
+ const VALID_ROLES = new Set<WorkerRole>(["implementer", "researcher", "reviewer"]);
44
+ const VALID_RUNTIMES = new Set<"pi" | "agy">(["pi", "agy"]);
28
45
  const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
29
46
 
30
47
  export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.env): SwarmLaunchEnvelope | undefined {
@@ -43,6 +60,7 @@ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.e
43
60
  const childName = optionalBounded(values.PI_SWARM_CHILD_NAME, "child name", 200);
44
61
  const childColor = optionalHexColor(values.PI_SWARM_COLOR);
45
62
  const acceptsRequests = parseBoolean(values.PI_SWARM_ACCEPT_REQUESTS);
63
+ const contextRecycling = parseContextRecycling(values.PI_SWARM_CONTEXT_RECYCLING);
46
64
  const provider = optionalBounded(values.PI_SWARM_MODEL_PROVIDER, "model provider", 200);
47
65
  const id = optionalBounded(values.PI_SWARM_MODEL_ID, "model id", 500);
48
66
  if ((provider === undefined) !== (id === undefined)) {
@@ -55,6 +73,14 @@ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.e
55
73
  if (thinking !== undefined && !THINKING_LEVELS.has(thinking as SwarmThinkingLevel)) {
56
74
  throw new Error("Pi Agent Swarm launch thinking level is invalid");
57
75
  }
76
+ const role = parseRole(values.PI_SWARM_ROLE);
77
+ const profile = optionalBounded(values.PI_SWARM_PROFILE, "profile", 64);
78
+ const runtime = parseRuntime(values.PI_SWARM_RUNTIME);
79
+ const runtimeModel = optionalBounded(values.PI_SWARM_RUNTIME_MODEL, "runtime model", 200);
80
+ if (runtime === "agy" && !runtimeModel) {
81
+ throw new Error("Pi Agent Swarm launch runtime model is required for agy runtime");
82
+ }
83
+ const readableDirs = parseReadableDirs(values.PI_SWARM_READABLE_DIRS);
58
84
  return {
59
85
  invite,
60
86
  parentSessionId,
@@ -63,6 +89,7 @@ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.e
63
89
  ...(childName ? { childName } : {}),
64
90
  ...(childColor ? { childColor } : {}),
65
91
  acceptsRequests,
92
+ ...(contextRecycling ? { contextRecycling } : {}),
66
93
  ...(provider && id
67
94
  ? {
68
95
  model: {
@@ -72,6 +99,11 @@ export function consumeLaunchEnvelope(environment: NodeJS.ProcessEnv = process.e
72
99
  },
73
100
  }
74
101
  : {}),
102
+ ...(role ? { role } : {}),
103
+ ...(profile ? { profile } : {}),
104
+ ...(runtime ? { runtime } : {}),
105
+ ...(runtimeModel ? { runtimeModel } : {}),
106
+ ...(readableDirs ? { readableDirs } : {}),
75
107
  };
76
108
  }
77
109
 
@@ -82,6 +114,7 @@ export function launchEnvelopeEnvironment(envelope: SwarmLaunchEnvelope): Record
82
114
  PI_SWARM_LAUNCH_ID: envelope.launchId,
83
115
  PI_SWARM_KICKOFF_CAPABILITY: envelope.kickoffCapability,
84
116
  PI_SWARM_ACCEPT_REQUESTS: envelope.acceptsRequests ? "1" : "0",
117
+ ...(envelope.contextRecycling ? { PI_SWARM_CONTEXT_RECYCLING: JSON.stringify(envelope.contextRecycling) } : {}),
85
118
  ...(envelope.childName ? { PI_SWARM_CHILD_NAME: envelope.childName } : {}),
86
119
  ...(envelope.childColor ? { PI_SWARM_COLOR: envelope.childColor } : {}),
87
120
  ...(envelope.model
@@ -91,6 +124,55 @@ export function launchEnvelopeEnvironment(envelope: SwarmLaunchEnvelope): Record
91
124
  ...(envelope.model.thinkingLevel ? { PI_SWARM_THINKING: envelope.model.thinkingLevel } : {}),
92
125
  }
93
126
  : {}),
127
+ ...(envelope.role ? { PI_SWARM_ROLE: envelope.role } : {}),
128
+ ...(envelope.profile ? { PI_SWARM_PROFILE: envelope.profile } : {}),
129
+ ...(envelope.runtime ? { PI_SWARM_RUNTIME: envelope.runtime } : {}),
130
+ ...(envelope.runtimeModel ? { PI_SWARM_RUNTIME_MODEL: envelope.runtimeModel } : {}),
131
+ ...(envelope.readableDirs?.length ? { PI_SWARM_READABLE_DIRS: JSON.stringify(envelope.readableDirs) } : {}),
132
+ };
133
+ }
134
+
135
+ function parseContextRecycling(value: string | undefined): ContextRecyclingLaunch | undefined {
136
+ if (value === undefined) return undefined;
137
+ const boundedValue = bounded(value, "context recycling policy", 4096);
138
+ let parsed: unknown;
139
+ try {
140
+ parsed = JSON.parse(boundedValue);
141
+ } catch {
142
+ throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
143
+ }
144
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
145
+ throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
146
+ }
147
+ const candidate = parsed as Record<string, unknown>;
148
+ const allowed = ["lineageId", "generation", "replacementCount", "policy", "handoffPath"];
149
+ if (Object.keys(candidate).some((key) => !allowed.includes(key))) {
150
+ throw new Error("Pi Agent Swarm launch context recycling policy is invalid");
151
+ }
152
+ const lineageId = safeId(candidate.lineageId as string | undefined, "lineage id");
153
+ if (!Number.isInteger(candidate.generation) || (candidate.generation as number) < 1) {
154
+ throw new Error("Pi Agent Swarm launch context recycling generation is invalid");
155
+ }
156
+ if (!Number.isInteger(candidate.replacementCount) || (candidate.replacementCount as number) < 0) {
157
+ throw new Error("Pi Agent Swarm launch context recycling replacement count is invalid");
158
+ }
159
+ const handoffPath = optionalBounded(candidate.handoffPath as string | undefined, "context handoff path", 4096);
160
+ if ((candidate.generation === 1) !== (handoffPath === undefined)) {
161
+ throw new Error("Pi Agent Swarm launch context handoff path is inconsistent");
162
+ }
163
+ const policy = normalizeContextRecyclingPolicy(candidate.policy);
164
+ if (
165
+ candidate.generation !== (candidate.replacementCount as number) + 1 ||
166
+ (candidate.replacementCount as number) > policy.maxReplacements
167
+ ) {
168
+ throw new Error("Pi Agent Swarm launch context recycling generation is inconsistent");
169
+ }
170
+ return {
171
+ lineageId,
172
+ generation: candidate.generation as number,
173
+ replacementCount: candidate.replacementCount as number,
174
+ policy,
175
+ ...(handoffPath ? { handoffPath } : {}),
94
176
  };
95
177
  }
96
178
 
@@ -116,6 +198,39 @@ function optionalBounded(value: string | undefined, label: string, maxBytes: num
116
198
  return value === undefined ? undefined : bounded(value, label, maxBytes);
117
199
  }
118
200
 
201
+ function parseRole(value: string | undefined): WorkerRole | undefined {
202
+ if (value === undefined) return undefined;
203
+ if (!VALID_ROLES.has(value as WorkerRole)) throw new Error("Pi Agent Swarm launch role is invalid");
204
+ return value as WorkerRole;
205
+ }
206
+
207
+ function parseRuntime(value: string | undefined): "pi" | "agy" | undefined {
208
+ if (value === undefined) return undefined;
209
+ if (!VALID_RUNTIMES.has(value as "pi" | "agy")) throw new Error("Pi Agent Swarm launch runtime is invalid");
210
+ return value as "pi" | "agy";
211
+ }
212
+
213
+ function parseReadableDirs(value: string | undefined): string[] | undefined {
214
+ if (value === undefined) return undefined;
215
+ const boundedValue = bounded(value, "readable dirs", 16_384);
216
+ let parsed: unknown;
217
+ try {
218
+ parsed = JSON.parse(boundedValue);
219
+ } catch {
220
+ throw new Error("Pi Agent Swarm launch readable dirs is invalid");
221
+ }
222
+ if (
223
+ !Array.isArray(parsed) ||
224
+ parsed.length > 32 ||
225
+ parsed.some(
226
+ (item) => typeof item !== "string" || item.length === 0 || item.includes("\0") || Buffer.byteLength(item) > 4_096,
227
+ )
228
+ ) {
229
+ throw new Error("Pi Agent Swarm launch readable dirs is invalid");
230
+ }
231
+ return parsed as string[];
232
+ }
233
+
119
234
  function optionalHexColor(value: string | undefined): string | undefined {
120
235
  if (value === undefined) return undefined;
121
236
  const lower = value.toLowerCase();
@@ -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
+ }