pi-agent-swarm 0.0.0 → 0.2.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.
@@ -0,0 +1,766 @@
1
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { TextDecoder } from "node:util";
3
+
4
+ export const SWARM_PROTOCOL_VERSION = 3;
5
+ export const INVITE_PREFIX = "piagentswarm:v1:";
6
+ export const MAX_FRAME_BYTES = 32 * 1024;
7
+ export const MAX_MESSAGE_BYTES = 16 * 1024;
8
+ export const DEFAULT_CLOCK_SKEW_MS = 60_000;
9
+ export const DEFAULT_MESSAGE_TTL_MS = 2 * 60_000;
10
+ export const MAX_MESSAGE_LIFETIME_MS = 5 * 60_000;
11
+
12
+ const GROUP_DOMAIN = "pi-agent-swarm/group/v1\0";
13
+ const FRAME_MAC_DOMAIN = "pi-agent-swarm/frame/v2\0";
14
+ const MANIFEST_MAC_DOMAIN = "pi-agent-swarm/manifest/v2\0";
15
+ const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
16
+ const GROUP_ID = /^[a-f0-9]{32}$/u;
17
+ const ENDPOINT_ID = /^[a-f0-9]{24}$/u;
18
+ const BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{43}$/u;
19
+ const BASE64URL_MAC = /^[A-Za-z0-9_-]{43}$/u;
20
+ const ACK_CODES = new Set<SwarmAckCode>([
21
+ "delivery_failed",
22
+ "kickoff_consumed",
23
+ "launch_mismatch",
24
+ "rate_limited",
25
+ "requests_disabled",
26
+ "shutdown_unauthorized",
27
+ "target_busy",
28
+ ]);
29
+
30
+ export interface SwarmGroup {
31
+ id: string;
32
+ secret: Buffer;
33
+ }
34
+
35
+ export type SwarmMessageMode = "notify" | "request" | "reply" | "kickoff";
36
+
37
+ /**
38
+ * Routes a message: `undefined` or `"steer"` enter the model context, while
39
+ * `"lead"` and `"shutdown"` stay on the control plane and never reach the model.
40
+ */
41
+ export type SwarmMessageKind = "lead" | "steer" | "shutdown";
42
+
43
+ export interface SwarmMessage {
44
+ id: string;
45
+ fromSessionId: string;
46
+ fromName?: string;
47
+ fromCwd?: string;
48
+ toSessionId: string;
49
+ mode: SwarmMessageMode;
50
+ text: string;
51
+ issuedAt: number;
52
+ expiresAt: number;
53
+ replyTo?: string;
54
+ launchId?: string;
55
+ kind?: SwarmMessageKind;
56
+ }
57
+
58
+ export interface SwarmPeerDescription {
59
+ protocolVersion: number;
60
+ sessionId: string;
61
+ endpointId: string;
62
+ name?: string;
63
+ color?: string;
64
+ cwd: string;
65
+ pid: number;
66
+ launchId?: string;
67
+ acceptsRequests: boolean;
68
+ }
69
+
70
+ export type SwarmLocalPeerDescription = Omit<SwarmPeerDescription, "endpointId">;
71
+
72
+ export type SwarmAckStatus = "accepted" | "duplicate" | "rejected" | "busy";
73
+
74
+ export type SwarmAckCode =
75
+ | "delivery_failed"
76
+ | "kickoff_consumed"
77
+ | "launch_mismatch"
78
+ | "rate_limited"
79
+ | "requests_disabled"
80
+ | "shutdown_unauthorized"
81
+ | "target_busy";
82
+
83
+ export interface SwarmAckPayload {
84
+ kind: "ack";
85
+ status: SwarmAckStatus;
86
+ code?: SwarmAckCode;
87
+ error?: string;
88
+ retryAfterMs?: number;
89
+ }
90
+
91
+ export type SwarmPayload =
92
+ | { kind: "describe" }
93
+ | { kind: "description"; peer: SwarmPeerDescription }
94
+ | { kind: "message"; message: SwarmMessage; kickoffCapability?: string }
95
+ | SwarmAckPayload;
96
+
97
+ export interface UnsignedSwarmFrame {
98
+ groupId: string;
99
+ requestId: string;
100
+ targetSessionId: string;
101
+ targetEndpointId: string;
102
+ senderSessionId: string;
103
+ senderEndpointId: string;
104
+ issuedAt: number;
105
+ nonce: string;
106
+ payload: SwarmPayload;
107
+ }
108
+
109
+ export interface SignedSwarmFrame extends UnsignedSwarmFrame {
110
+ version: typeof SWARM_PROTOCOL_VERSION;
111
+ mac: string;
112
+ }
113
+
114
+ export interface UnsignedEndpointManifest {
115
+ groupId: string;
116
+ endpointId: string;
117
+ sessionId: string;
118
+ socketName: string;
119
+ pid: number;
120
+ publishedAt: number;
121
+ }
122
+
123
+ export interface SignedEndpointManifest extends UnsignedEndpointManifest {
124
+ version: typeof SWARM_PROTOCOL_VERSION;
125
+ mac: string;
126
+ }
127
+
128
+ export interface VerifyFrameOptions {
129
+ expectedGroupId: string;
130
+ expectedTargetSessionId: string;
131
+ expectedTargetEndpointId: string;
132
+ now?: number;
133
+ maxClockSkewMs?: number;
134
+ replay?: ReplayWindow;
135
+ }
136
+
137
+ export function createGroup(secret: Uint8Array = randomBytes(32)): SwarmGroup {
138
+ const copied = Buffer.from(secret);
139
+ if (copied.length !== 32) throw new Error("Pi Agent Swarm group secret must be exactly 32 bytes");
140
+ const id = createHash("sha256").update(GROUP_DOMAIN).update(copied).digest("hex").slice(0, 32);
141
+ return { id, secret: copied };
142
+ }
143
+
144
+ export function formatInvite(secret: Uint8Array): string {
145
+ return `${INVITE_PREFIX}${createGroup(secret).secret.toString("base64url")}`;
146
+ }
147
+
148
+ export function parseInvite(value: string): SwarmGroup {
149
+ if (value !== value.trim() || !value.startsWith(INVITE_PREFIX)) {
150
+ throw new Error("Pi Agent Swarm invite is invalid");
151
+ }
152
+ const encoded = value.slice(INVITE_PREFIX.length);
153
+ if (!BASE64URL_32_BYTES.test(encoded)) throw new Error("Pi Agent Swarm invite is invalid");
154
+ let secret: Buffer;
155
+ try {
156
+ secret = Buffer.from(encoded, "base64url");
157
+ } catch {
158
+ throw new Error("Pi Agent Swarm invite is invalid");
159
+ }
160
+ if (secret.length !== 32 || secret.toString("base64url") !== encoded) {
161
+ throw new Error("Pi Agent Swarm invite is invalid");
162
+ }
163
+ return createGroup(secret);
164
+ }
165
+
166
+ export function createSignedFrame(input: UnsignedSwarmFrame, secret: Uint8Array): SignedSwarmFrame {
167
+ const frameWithoutMac = {
168
+ version: SWARM_PROTOCOL_VERSION as typeof SWARM_PROTOCOL_VERSION,
169
+ ...normalizeUnsignedFrame(input),
170
+ };
171
+ return {
172
+ ...frameWithoutMac,
173
+ mac: keyedMac(FRAME_MAC_DOMAIN, frameWithoutMac, secret),
174
+ };
175
+ }
176
+
177
+ export function verifySignedFrame(value: unknown, secret: Uint8Array, options: VerifyFrameOptions): SignedSwarmFrame {
178
+ const frame = normalizeSignedFrame(value);
179
+ if (frame.groupId !== options.expectedGroupId) {
180
+ throw new Error("Pi Agent Swarm frame belongs to the wrong group");
181
+ }
182
+ if (frame.targetSessionId !== options.expectedTargetSessionId) {
183
+ throw new Error("Pi Agent Swarm frame targets another session");
184
+ }
185
+ if (frame.targetEndpointId !== options.expectedTargetEndpointId) {
186
+ throw new Error("Pi Agent Swarm frame targets another endpoint instance");
187
+ }
188
+ const now = options.now ?? Date.now();
189
+ const maxClockSkewMs = options.maxClockSkewMs ?? DEFAULT_CLOCK_SKEW_MS;
190
+ if (Math.abs(now - frame.issuedAt) > maxClockSkewMs) {
191
+ throw new Error("Pi Agent Swarm frame expired outside the accepted clock window");
192
+ }
193
+ const { mac, ...unsigned } = frame;
194
+ const expected = keyedMac(FRAME_MAC_DOMAIN, unsigned, secret);
195
+ if (!safeMacEqual(mac, expected)) throw new Error("Pi Agent Swarm frame authentication failed");
196
+ const replayKey = [frame.senderSessionId, frame.senderEndpointId, frame.requestId, frame.nonce].join(":");
197
+ if (options.replay && !options.replay.accept(replayKey, now)) {
198
+ throw new Error("Pi Agent Swarm frame was replayed");
199
+ }
200
+ return frame;
201
+ }
202
+
203
+ export function createSignedEndpointManifest(
204
+ input: UnsignedEndpointManifest,
205
+ secret: Uint8Array,
206
+ ): SignedEndpointManifest {
207
+ const manifestWithoutMac = {
208
+ version: SWARM_PROTOCOL_VERSION as typeof SWARM_PROTOCOL_VERSION,
209
+ ...normalizeUnsignedEndpointManifest(input),
210
+ };
211
+ return {
212
+ ...manifestWithoutMac,
213
+ mac: keyedMac(MANIFEST_MAC_DOMAIN, manifestWithoutMac, secret),
214
+ };
215
+ }
216
+
217
+ export function verifySignedEndpointManifest(
218
+ value: unknown,
219
+ secret: Uint8Array,
220
+ options: { expectedGroupId: string; expectedEndpointId: string },
221
+ ): SignedEndpointManifest {
222
+ const manifest = normalizeSignedEndpointManifest(value);
223
+ if (manifest.groupId !== options.expectedGroupId) {
224
+ throw new Error("Pi Agent Swarm endpoint manifest belongs to the wrong group");
225
+ }
226
+ if (manifest.endpointId !== options.expectedEndpointId) {
227
+ throw new Error("Pi Agent Swarm endpoint manifest identity does not match its filename");
228
+ }
229
+ if (manifest.socketName !== `${manifest.endpointId}.sock`) {
230
+ throw new Error("Pi Agent Swarm endpoint manifest socket does not match its identity");
231
+ }
232
+ const { mac, ...unsigned } = manifest;
233
+ const expected = keyedMac(MANIFEST_MAC_DOMAIN, unsigned, secret);
234
+ if (!safeMacEqual(mac, expected)) {
235
+ throw new Error("Pi Agent Swarm endpoint manifest authentication failed");
236
+ }
237
+ return manifest;
238
+ }
239
+
240
+ export function validateMessage(value: unknown): SwarmMessage {
241
+ if (!isRecord(value)) throw new Error("Pi Agent Swarm message must be an object");
242
+ assertExactKeys(
243
+ value,
244
+ [
245
+ "expiresAt",
246
+ "fromCwd",
247
+ "fromName",
248
+ "fromSessionId",
249
+ "id",
250
+ "issuedAt",
251
+ "kind",
252
+ "launchId",
253
+ "mode",
254
+ "replyTo",
255
+ "text",
256
+ "toSessionId",
257
+ ],
258
+ "message",
259
+ );
260
+ const id = requiredId(value.id, "message id");
261
+ const fromSessionId = requiredId(value.fromSessionId, "sender session id");
262
+ const fromName = optionalBoundedString(value.fromName, "sender name", 200);
263
+ const fromCwd = optionalBoundedString(value.fromCwd, "sender cwd", 4_096);
264
+ const toSessionId = requiredId(value.toSessionId, "target session id");
265
+ const mode = value.mode;
266
+ if (mode !== "notify" && mode !== "request" && mode !== "reply" && mode !== "kickoff") {
267
+ throw new Error("Pi Agent Swarm message mode is invalid");
268
+ }
269
+ if (typeof value.text !== "string") throw new Error("Pi Agent Swarm message text must be a string");
270
+ if (Buffer.byteLength(value.text, "utf8") > MAX_MESSAGE_BYTES) {
271
+ throw new Error("Pi Agent Swarm message is too large");
272
+ }
273
+ const issuedAt = finiteInteger(value.issuedAt, "message issued time");
274
+ const expiresAt = finiteInteger(value.expiresAt, "message expiry time");
275
+ if (expiresAt <= issuedAt || expiresAt - issuedAt > MAX_MESSAGE_LIFETIME_MS) {
276
+ throw new Error("Pi Agent Swarm message lifetime is invalid");
277
+ }
278
+ const replyTo = optionalId(value.replyTo, "reply message id");
279
+ const launchId = optionalId(value.launchId, "launch id");
280
+ if (value.kind !== undefined && value.kind !== "lead" && value.kind !== "steer" && value.kind !== "shutdown") {
281
+ throw new Error("Pi Agent Swarm message kind is invalid");
282
+ }
283
+ if (mode === "reply" && !replyTo) throw new Error("Pi Agent Swarm reply requires a reply message id");
284
+ if (mode === "kickoff" && !launchId) throw new Error("Pi Agent Swarm kickoff requires a launch id");
285
+ return {
286
+ id,
287
+ fromSessionId,
288
+ ...(fromName ? { fromName } : {}),
289
+ ...(fromCwd ? { fromCwd } : {}),
290
+ toSessionId,
291
+ mode,
292
+ text: value.text,
293
+ issuedAt,
294
+ expiresAt,
295
+ ...(replyTo ? { replyTo } : {}),
296
+ ...(launchId ? { launchId } : {}),
297
+ ...(value.kind !== undefined ? { kind: value.kind as SwarmMessageKind } : {}),
298
+ };
299
+ }
300
+
301
+ export function validateMessageTiming(message: SwarmMessage, now: number): void {
302
+ if (message.issuedAt > now + DEFAULT_CLOCK_SKEW_MS) {
303
+ throw new Error("Pi Agent Swarm message was issued too far in the future");
304
+ }
305
+ if (message.expiresAt < now) throw new Error("Pi Agent Swarm message has expired");
306
+ }
307
+
308
+ export class ReplayWindow {
309
+ private readonly entries = new Map<string, number>();
310
+
311
+ constructor(
312
+ private readonly capacity: number,
313
+ private readonly ttlMs: number,
314
+ ) {
315
+ if (!Number.isInteger(capacity) || capacity < 1) throw new Error("Replay capacity is invalid");
316
+ if (!Number.isFinite(ttlMs) || ttlMs < 1) throw new Error("Replay TTL is invalid");
317
+ }
318
+
319
+ accept(key: string, now: number): boolean {
320
+ if (this.has(key, now)) return false;
321
+ this.record(key, now);
322
+ return true;
323
+ }
324
+
325
+ has(key: string, now: number): boolean {
326
+ this.prune(now);
327
+ return this.entries.has(key);
328
+ }
329
+
330
+ record(key: string, now: number): void {
331
+ this.prune(now);
332
+ this.entries.delete(key);
333
+ this.entries.set(key, now + this.ttlMs);
334
+ while (this.entries.size > this.capacity) {
335
+ const oldest = this.entries.keys().next().value as string | undefined;
336
+ if (oldest === undefined) break;
337
+ this.entries.delete(oldest);
338
+ }
339
+ }
340
+
341
+ get size(): number {
342
+ return this.entries.size;
343
+ }
344
+
345
+ private prune(now: number): void {
346
+ for (const [key, expiresAt] of this.entries) {
347
+ if (expiresAt > now) continue;
348
+ this.entries.delete(key);
349
+ }
350
+ }
351
+ }
352
+
353
+ export class FixedWindowRateLimiter {
354
+ private readonly entries = new Map<string, { start: number; count: number }>();
355
+
356
+ constructor(
357
+ private readonly limit: number,
358
+ private readonly windowMs: number,
359
+ private readonly maxKeys = 128,
360
+ ) {
361
+ if (!Number.isInteger(limit) || limit < 1) throw new Error("Rate limit is invalid");
362
+ if (!Number.isFinite(windowMs) || windowMs < 1) throw new Error("Rate window is invalid");
363
+ if (!Number.isInteger(maxKeys) || maxKeys < 1) throw new Error("Rate key limit is invalid");
364
+ }
365
+
366
+ accept(key: string, now: number): boolean {
367
+ const current = this.entries.get(key);
368
+ if (!current || now - current.start >= this.windowMs || now < current.start) {
369
+ this.entries.delete(key);
370
+ this.entries.set(key, { start: now, count: 1 });
371
+ this.trim();
372
+ return true;
373
+ }
374
+ if (current.count >= this.limit) return false;
375
+ current.count += 1;
376
+ this.entries.delete(key);
377
+ this.entries.set(key, current);
378
+ return true;
379
+ }
380
+
381
+ retryAfterMs(key: string, now: number): number {
382
+ const current = this.entries.get(key);
383
+ if (!current || now < current.start || now - current.start >= this.windowMs) return 0;
384
+ return Math.max(1, current.start + this.windowMs - now);
385
+ }
386
+
387
+ private trim(): void {
388
+ while (this.entries.size > this.maxKeys) {
389
+ const oldest = this.entries.keys().next().value as string | undefined;
390
+ if (oldest === undefined) break;
391
+ this.entries.delete(oldest);
392
+ }
393
+ }
394
+ }
395
+
396
+ export interface JsonLineDecoderOptions {
397
+ onValue(value: unknown): void;
398
+ onError(error: Error): void;
399
+ maxBytes?: number;
400
+ }
401
+
402
+ export class JsonLineDecoder {
403
+ private buffer = Buffer.alloc(0);
404
+ private discarding = false;
405
+ private readonly maxBytes: number;
406
+
407
+ constructor(private readonly options: JsonLineDecoderOptions) {
408
+ this.maxBytes = options.maxBytes ?? MAX_FRAME_BYTES;
409
+ }
410
+
411
+ push(chunk: Buffer | Uint8Array): void {
412
+ let incoming = Buffer.from(chunk);
413
+ if (this.discarding) {
414
+ const newline = incoming.indexOf(0x0a);
415
+ if (newline < 0) return;
416
+ incoming = incoming.subarray(newline + 1);
417
+ this.discarding = false;
418
+ }
419
+ if (incoming.length === 0) return;
420
+ this.buffer = Buffer.concat([this.buffer, incoming]);
421
+ while (true) {
422
+ const newline = this.buffer.indexOf(0x0a);
423
+ if (newline < 0) break;
424
+ const line = this.buffer.subarray(0, newline);
425
+ this.buffer = this.buffer.subarray(newline + 1);
426
+ if (line.length > this.maxBytes) {
427
+ this.options.onError(new Error("Pi Agent Swarm JSONL record is too large"));
428
+ continue;
429
+ }
430
+ this.decodeLine(line);
431
+ }
432
+ if (this.buffer.length > this.maxBytes) {
433
+ this.buffer = Buffer.alloc(0);
434
+ this.discarding = true;
435
+ this.options.onError(new Error("Pi Agent Swarm JSONL record is too large"));
436
+ }
437
+ }
438
+
439
+ finish(): void {
440
+ if (this.discarding) {
441
+ this.discarding = false;
442
+ return;
443
+ }
444
+ if (this.buffer.length === 0) return;
445
+ const line = this.buffer;
446
+ this.buffer = Buffer.alloc(0);
447
+ this.decodeLine(line);
448
+ }
449
+
450
+ private decodeLine(value: Buffer): void {
451
+ const line = value.at(-1) === 0x0d ? value.subarray(0, -1) : value;
452
+ if (line.length === 0) return;
453
+ let text: string;
454
+ try {
455
+ text = new TextDecoder("utf-8", { fatal: true }).decode(line);
456
+ } catch {
457
+ this.options.onError(new Error("Pi Agent Swarm JSONL record contains invalid UTF-8"));
458
+ return;
459
+ }
460
+ try {
461
+ this.options.onValue(JSON.parse(text));
462
+ } catch {
463
+ this.options.onError(new Error("Pi Agent Swarm JSONL record is malformed JSON"));
464
+ }
465
+ }
466
+ }
467
+
468
+ export function validatePeerDescription(value: unknown): SwarmPeerDescription {
469
+ if (!isRecord(value)) throw new Error("Pi Agent Swarm peer description is invalid");
470
+ assertExactKeys(
471
+ value,
472
+ ["acceptsRequests", "color", "cwd", "endpointId", "launchId", "name", "pid", "protocolVersion", "sessionId"],
473
+ "peer description",
474
+ );
475
+ if (value.protocolVersion !== SWARM_PROTOCOL_VERSION) {
476
+ throw new Error("Pi Agent Swarm peer protocol version is unsupported");
477
+ }
478
+ const sessionId = requiredId(value.sessionId, "peer session id");
479
+ const endpointId = requiredEndpointId(value.endpointId, "peer endpoint id");
480
+ const name = optionalBoundedString(value.name, "peer name", 200);
481
+ const cwd = optionalBoundedString(value.cwd, "peer cwd", 4_096);
482
+ if (cwd === undefined) throw new Error("Pi Agent Swarm peer cwd is invalid");
483
+ const pid = finiteInteger(value.pid, "peer process id");
484
+ if (pid < 1) throw new Error("Pi Agent Swarm peer process id is invalid");
485
+ const launchId = optionalId(value.launchId, "peer launch id");
486
+ if (typeof value.acceptsRequests !== "boolean") {
487
+ throw new Error("Pi Agent Swarm peer request policy is invalid");
488
+ }
489
+ let color: string | undefined;
490
+ if (value.color !== undefined) {
491
+ if (typeof value.color !== "string" || !/^#[0-9a-f]{6}$/u.test(value.color.toLowerCase())) {
492
+ throw new Error("Pi Agent Swarm peer color is invalid");
493
+ }
494
+ color = value.color.toLowerCase();
495
+ }
496
+ return {
497
+ protocolVersion: SWARM_PROTOCOL_VERSION,
498
+ sessionId,
499
+ endpointId,
500
+ ...(name ? { name } : {}),
501
+ ...(color ? { color } : {}),
502
+ cwd,
503
+ pid,
504
+ ...(launchId ? { launchId } : {}),
505
+ acceptsRequests: value.acceptsRequests,
506
+ };
507
+ }
508
+
509
+ function normalizeUnsignedFrame(value: UnsignedSwarmFrame): UnsignedSwarmFrame {
510
+ if (!isRecord(value)) throw new Error("Pi Agent Swarm frame must be an object");
511
+ assertExactKeys(
512
+ value,
513
+ [
514
+ "groupId",
515
+ "issuedAt",
516
+ "nonce",
517
+ "payload",
518
+ "requestId",
519
+ "senderEndpointId",
520
+ "senderSessionId",
521
+ "targetEndpointId",
522
+ "targetSessionId",
523
+ ],
524
+ "frame",
525
+ );
526
+ return normalizeUnsignedFrameFields(value);
527
+ }
528
+
529
+ function normalizeUnsignedFrameFields(value: Record<string, unknown>): UnsignedSwarmFrame {
530
+ const groupId = value.groupId;
531
+ if (typeof groupId !== "string" || !GROUP_ID.test(groupId)) {
532
+ throw new Error("Pi Agent Swarm frame group id is invalid");
533
+ }
534
+ return {
535
+ groupId,
536
+ requestId: requiredId(value.requestId, "request id"),
537
+ targetSessionId: requiredId(value.targetSessionId, "target session id"),
538
+ targetEndpointId: requiredEndpointId(value.targetEndpointId, "target endpoint id"),
539
+ senderSessionId: requiredId(value.senderSessionId, "sender session id"),
540
+ senderEndpointId: requiredEndpointId(value.senderEndpointId, "sender endpoint id"),
541
+ issuedAt: finiteInteger(value.issuedAt, "frame issued time"),
542
+ nonce: requiredId(value.nonce, "frame nonce"),
543
+ payload: validatePayload(value.payload),
544
+ };
545
+ }
546
+
547
+ function normalizeSignedFrame(value: unknown): SignedSwarmFrame {
548
+ if (!isRecord(value)) throw new Error("Pi Agent Swarm frame must be an object");
549
+ assertExactKeys(
550
+ value,
551
+ [
552
+ "groupId",
553
+ "issuedAt",
554
+ "mac",
555
+ "nonce",
556
+ "payload",
557
+ "requestId",
558
+ "senderEndpointId",
559
+ "senderSessionId",
560
+ "targetEndpointId",
561
+ "targetSessionId",
562
+ "version",
563
+ ],
564
+ "signed frame",
565
+ );
566
+ if (value.version !== SWARM_PROTOCOL_VERSION) {
567
+ throw new Error("Pi Agent Swarm frame protocol version is unsupported");
568
+ }
569
+ const normalized = normalizeUnsignedFrameFields(value);
570
+ if (typeof value.mac !== "string" || !BASE64URL_MAC.test(value.mac)) {
571
+ throw new Error("Pi Agent Swarm frame authentication tag is invalid");
572
+ }
573
+ return { version: SWARM_PROTOCOL_VERSION, ...normalized, mac: value.mac };
574
+ }
575
+
576
+ function validatePayload(value: unknown): SwarmPayload {
577
+ if (!isRecord(value) || typeof value.kind !== "string") {
578
+ throw new Error("Pi Agent Swarm frame payload is invalid");
579
+ }
580
+ if (value.kind === "describe") {
581
+ assertExactKeys(value, ["kind"], "describe payload");
582
+ return { kind: "describe" };
583
+ }
584
+ if (value.kind === "description") {
585
+ assertExactKeys(value, ["kind", "peer"], "description payload");
586
+ return { kind: "description", peer: validatePeerDescription(value.peer) };
587
+ }
588
+ if (value.kind === "message") {
589
+ assertExactKeys(value, ["kickoffCapability", "kind", "message"], "message payload");
590
+ const kickoffCapability = optionalId(value.kickoffCapability, "kickoff capability");
591
+ const message = validateMessage(value.message);
592
+ if (kickoffCapability && message.mode !== "kickoff") {
593
+ throw new Error("Pi Agent Swarm kickoff capability is invalid for this message mode");
594
+ }
595
+ return {
596
+ kind: "message",
597
+ message,
598
+ ...(kickoffCapability ? { kickoffCapability } : {}),
599
+ };
600
+ }
601
+ if (value.kind === "ack") {
602
+ assertExactKeys(value, ["code", "error", "kind", "retryAfterMs", "status"], "ack payload");
603
+ const status = value.status;
604
+ if (status !== "accepted" && status !== "duplicate" && status !== "rejected" && status !== "busy") {
605
+ throw new Error("Pi Agent Swarm ack status is invalid");
606
+ }
607
+ const code = optionalAckCode(value.code);
608
+ const error = optionalBoundedString(value.error, "ack error", 1_000);
609
+ const retryAfterMs = optionalPositiveInteger(value.retryAfterMs, "ack retry delay", 86_400_000);
610
+ if (status === "accepted" || status === "duplicate") {
611
+ if (code || error || retryAfterMs !== undefined) {
612
+ throw new Error("Pi Agent Swarm successful ack contains rejection details");
613
+ }
614
+ } else if (!code) {
615
+ throw new Error("Pi Agent Swarm rejected ack requires an error code");
616
+ }
617
+ return {
618
+ kind: "ack",
619
+ status,
620
+ ...(code ? { code } : {}),
621
+ ...(error ? { error } : {}),
622
+ ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
623
+ };
624
+ }
625
+ throw new Error("Pi Agent Swarm frame payload kind is invalid");
626
+ }
627
+
628
+ function normalizeUnsignedEndpointManifest(value: UnsignedEndpointManifest): UnsignedEndpointManifest {
629
+ if (!isRecord(value)) throw new Error("Pi Agent Swarm endpoint manifest must be an object");
630
+ assertExactKeys(
631
+ value,
632
+ ["endpointId", "groupId", "pid", "publishedAt", "sessionId", "socketName"],
633
+ "endpoint manifest",
634
+ );
635
+ return normalizeUnsignedEndpointManifestFields(value);
636
+ }
637
+
638
+ function normalizeUnsignedEndpointManifestFields(value: Record<string, unknown>): UnsignedEndpointManifest {
639
+ const groupId = value.groupId;
640
+ if (typeof groupId !== "string" || !GROUP_ID.test(groupId)) {
641
+ throw new Error("Pi Agent Swarm endpoint manifest group id is invalid");
642
+ }
643
+ const endpointId = requiredEndpointId(value.endpointId, "endpoint manifest id");
644
+ const socketName = value.socketName;
645
+ if (typeof socketName !== "string" || socketName !== `${endpointId}.sock`) {
646
+ throw new Error("Pi Agent Swarm endpoint manifest socket name is invalid");
647
+ }
648
+ const pid = finiteInteger(value.pid, "endpoint manifest process id");
649
+ if (pid < 1) throw new Error("Pi Agent Swarm endpoint manifest process id is invalid");
650
+ return {
651
+ groupId,
652
+ endpointId,
653
+ sessionId: requiredId(value.sessionId, "endpoint manifest session id"),
654
+ socketName,
655
+ pid,
656
+ publishedAt: finiteInteger(value.publishedAt, "endpoint manifest publication time"),
657
+ };
658
+ }
659
+
660
+ function normalizeSignedEndpointManifest(value: unknown): SignedEndpointManifest {
661
+ if (!isRecord(value)) throw new Error("Pi Agent Swarm endpoint manifest must be an object");
662
+ assertExactKeys(
663
+ value,
664
+ ["endpointId", "groupId", "mac", "pid", "publishedAt", "sessionId", "socketName", "version"],
665
+ "signed endpoint manifest",
666
+ );
667
+ if (value.version !== SWARM_PROTOCOL_VERSION) {
668
+ throw new Error("Pi Agent Swarm endpoint manifest protocol version is unsupported");
669
+ }
670
+ const normalized = normalizeUnsignedEndpointManifestFields(value);
671
+ if (typeof value.mac !== "string" || !BASE64URL_MAC.test(value.mac)) {
672
+ throw new Error("Pi Agent Swarm endpoint manifest authentication tag is invalid");
673
+ }
674
+ return { version: SWARM_PROTOCOL_VERSION, ...normalized, mac: value.mac };
675
+ }
676
+
677
+ function keyedMac(domain: string, value: object, secret: Uint8Array): string {
678
+ const key = Buffer.from(secret);
679
+ if (key.length !== 32) throw new Error("Pi Agent Swarm group secret must be exactly 32 bytes");
680
+ return createHmac("sha256", key).update(domain).update(canonicalJson(value)).digest("base64url");
681
+ }
682
+
683
+ function safeMacEqual(actual: string, expected: string): boolean {
684
+ const actualBytes = Buffer.from(actual);
685
+ const expectedBytes = Buffer.from(expected);
686
+ return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
687
+ }
688
+
689
+ function canonicalJson(value: unknown): string {
690
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
691
+ return JSON.stringify(value);
692
+ }
693
+ if (typeof value === "number") {
694
+ if (!Number.isFinite(value)) throw new Error("Pi Agent Swarm frame contains a non-finite number");
695
+ return JSON.stringify(value);
696
+ }
697
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
698
+ if (isRecord(value)) {
699
+ return `{${Object.keys(value)
700
+ .filter((key) => value[key] !== undefined)
701
+ .sort()
702
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
703
+ .join(",")}}`;
704
+ }
705
+ throw new Error("Pi Agent Swarm frame contains unsupported data");
706
+ }
707
+
708
+ function requiredId(value: unknown, label: string): string {
709
+ if (typeof value !== "string" || !SAFE_ID.test(value)) {
710
+ throw new Error(`Pi Agent Swarm ${label} is invalid`);
711
+ }
712
+ return value;
713
+ }
714
+
715
+ function requiredEndpointId(value: unknown, label: string): string {
716
+ if (typeof value !== "string" || !ENDPOINT_ID.test(value)) {
717
+ throw new Error(`Pi Agent Swarm ${label} is invalid`);
718
+ }
719
+ return value;
720
+ }
721
+
722
+ function optionalId(value: unknown, label: string): string | undefined {
723
+ if (value === undefined) return undefined;
724
+ return requiredId(value, label);
725
+ }
726
+
727
+ function optionalAckCode(value: unknown): SwarmAckCode | undefined {
728
+ if (value === undefined) return undefined;
729
+ if (typeof value !== "string" || !ACK_CODES.has(value as SwarmAckCode)) {
730
+ throw new Error("Pi Agent Swarm ack error code is invalid");
731
+ }
732
+ return value as SwarmAckCode;
733
+ }
734
+
735
+ function optionalBoundedString(value: unknown, label: string, maxBytes: number): string | undefined {
736
+ if (value === undefined) return undefined;
737
+ if (typeof value !== "string" || Buffer.byteLength(value, "utf8") > maxBytes) {
738
+ throw new Error(`Pi Agent Swarm ${label} is invalid`);
739
+ }
740
+ return value;
741
+ }
742
+
743
+ function optionalPositiveInteger(value: unknown, label: string, maximum: number): number | undefined {
744
+ if (value === undefined) return undefined;
745
+ const normalized = finiteInteger(value, label);
746
+ if (normalized < 1 || normalized > maximum) throw new Error(`Pi Agent Swarm ${label} is invalid`);
747
+ return normalized;
748
+ }
749
+
750
+ function finiteInteger(value: unknown, label: string): number {
751
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
752
+ throw new Error(`Pi Agent Swarm ${label} is invalid`);
753
+ }
754
+ return value;
755
+ }
756
+
757
+ function assertExactKeys(value: Record<string, unknown>, allowed: readonly string[], label: string): void {
758
+ const allowedKeys = new Set(allowed);
759
+ for (const key of Object.keys(value)) {
760
+ if (!allowedKeys.has(key)) throw new Error(`Pi Agent Swarm ${label} contains an unknown field`);
761
+ }
762
+ }
763
+
764
+ function isRecord(value: unknown): value is Record<string, unknown> {
765
+ return typeof value === "object" && value !== null && !Array.isArray(value);
766
+ }