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.
- package/LICENSE +21 -0
- package/README.md +240 -2
- package/dist/chunks/chunk-77JHO3GV.ts +144 -0
- package/dist/chunks/chunk-77JHO3GV.ts.map +7 -0
- package/dist/chunks/menu-RH6GY6U4.ts +119 -0
- package/dist/chunks/menu-RH6GY6U4.ts.map +7 -0
- package/dist/index.ts +4092 -0
- package/dist/index.ts.map +7 -0
- package/package.json +54 -2
- package/src/color.ts +129 -0
- package/src/external.ts +150 -0
- package/src/footer.ts +63 -0
- package/src/i3-workspace.ts +281 -0
- package/src/index.ts +1 -0
- package/src/launch-envelope.ts +124 -0
- package/src/launcher.ts +93 -0
- package/src/menu.ts +131 -0
- package/src/pi-agent-swarm.ts +173 -0
- package/src/pi-invocation.ts +144 -0
- package/src/protocol.ts +766 -0
- package/src/reload-handoff.ts +33 -0
- package/src/renderer.ts +30 -0
- package/src/runtime-directory.ts +249 -0
- package/src/settings.ts +369 -0
- package/src/swarm-controller.ts +1353 -0
- package/src/terminal.ts +54 -0
- package/src/text.ts +42 -0
- package/src/tools.ts +275 -0
- package/src/transport-io.ts +155 -0
- package/src/transport.ts +939 -0
package/src/transport.ts
ADDED
|
@@ -0,0 +1,939 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { chmod, lstat, open, opendir, rm } from "node:fs/promises";
|
|
4
|
+
import { createServer, type Server, type Socket } from "node:net";
|
|
5
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
6
|
+
import {
|
|
7
|
+
createSignedEndpointManifest,
|
|
8
|
+
createSignedFrame,
|
|
9
|
+
FixedWindowRateLimiter,
|
|
10
|
+
JsonLineDecoder,
|
|
11
|
+
ReplayWindow,
|
|
12
|
+
type SignedEndpointManifest,
|
|
13
|
+
type SignedSwarmFrame,
|
|
14
|
+
SWARM_PROTOCOL_VERSION,
|
|
15
|
+
type SwarmAckCode,
|
|
16
|
+
type SwarmAckPayload,
|
|
17
|
+
type SwarmGroup,
|
|
18
|
+
type SwarmLocalPeerDescription,
|
|
19
|
+
type SwarmMessage,
|
|
20
|
+
type SwarmPeerDescription,
|
|
21
|
+
validateMessage,
|
|
22
|
+
validateMessageTiming,
|
|
23
|
+
validatePeerDescription,
|
|
24
|
+
verifySignedEndpointManifest,
|
|
25
|
+
verifySignedFrame,
|
|
26
|
+
} from "./protocol.js";
|
|
27
|
+
import {
|
|
28
|
+
assertOwnedPath,
|
|
29
|
+
cleanupStaleRuntimeEntries,
|
|
30
|
+
createEndpointPaths,
|
|
31
|
+
type EndpointPaths,
|
|
32
|
+
endpointIdFromManifestName,
|
|
33
|
+
ensureGroupRuntimeDirectory,
|
|
34
|
+
MAX_MANIFEST_BYTES,
|
|
35
|
+
MAX_RUNTIME_SCAN_ENTRIES,
|
|
36
|
+
publishManifest,
|
|
37
|
+
randomEndpointId,
|
|
38
|
+
removeOwnedEndpoint,
|
|
39
|
+
} from "./runtime-directory.js";
|
|
40
|
+
import {
|
|
41
|
+
closeSocketServer,
|
|
42
|
+
isDeadEndpointError,
|
|
43
|
+
listenSocketServer,
|
|
44
|
+
readBoundedHandleUtf8,
|
|
45
|
+
readBoundedUtf8,
|
|
46
|
+
requestFrame,
|
|
47
|
+
writeFrame,
|
|
48
|
+
} from "./transport-io.js";
|
|
49
|
+
|
|
50
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 2_000;
|
|
51
|
+
const DEFAULT_DISCOVERY_DEADLINE_MS = 2_000;
|
|
52
|
+
const DEFAULT_DISCOVERY_PROBE_TIMEOUT_MS = 500;
|
|
53
|
+
const MAX_DISCOVERY_MANIFESTS = 64;
|
|
54
|
+
const MAX_DISCOVERY_CONCURRENCY = 16;
|
|
55
|
+
const MAX_DISCOVERY_ISSUES = 32;
|
|
56
|
+
const MAX_PENDING_CONNECTIONS = 32;
|
|
57
|
+
const MAX_INFLIGHT_DELIVERIES = 8;
|
|
58
|
+
const MESSAGE_DEDUP_CAPACITY = 1_024;
|
|
59
|
+
const MESSAGE_DEDUP_TTL_MS = 10 * 60_000;
|
|
60
|
+
const FRAME_REPLAY_CAPACITY = 2_048;
|
|
61
|
+
const FRAME_REPLAY_TTL_MS = 2 * 60_000;
|
|
62
|
+
const MAX_REQUESTS_PER_MINUTE = 60;
|
|
63
|
+
const MAX_TOTAL_REQUESTS_PER_MINUTE = 240;
|
|
64
|
+
const RATE_WINDOW_MS = 60_000;
|
|
65
|
+
const SAFE_SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
66
|
+
|
|
67
|
+
export interface SwarmTransportOptions {
|
|
68
|
+
group: SwarmGroup;
|
|
69
|
+
peer: SwarmLocalPeerDescription;
|
|
70
|
+
baseDirectory?: string;
|
|
71
|
+
endpointId?: string;
|
|
72
|
+
requestTimeoutMs?: number;
|
|
73
|
+
discoveryDeadlineMs?: number;
|
|
74
|
+
discoveryProbeTimeoutMs?: number;
|
|
75
|
+
kickoffCapability?: string;
|
|
76
|
+
onMessage(message: SwarmMessage, signal: AbortSignal): Promise<void> | void;
|
|
77
|
+
/** Resolve whether a shutdown control message from the given sender is authorized. */
|
|
78
|
+
authorizeShutdown?: (message: SwarmMessage) => boolean;
|
|
79
|
+
seenMessageIds?: readonly string[];
|
|
80
|
+
kickoffConsumed?: boolean;
|
|
81
|
+
now?: () => number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface SwarmSendAuthorization {
|
|
85
|
+
kickoffCapability: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface SwarmDeliveryAck {
|
|
89
|
+
accepted: boolean;
|
|
90
|
+
duplicate: boolean;
|
|
91
|
+
code?: SwarmAckCode;
|
|
92
|
+
error?: string;
|
|
93
|
+
retryAfterMs?: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export type SwarmDiscoveryIssueCode =
|
|
97
|
+
| "deadline_exceeded"
|
|
98
|
+
| "identity_conflict"
|
|
99
|
+
| "invalid_manifest"
|
|
100
|
+
| "peer_unreachable"
|
|
101
|
+
| "protocol_error"
|
|
102
|
+
| "scan_saturated";
|
|
103
|
+
|
|
104
|
+
export interface SwarmDiscoveryIssue {
|
|
105
|
+
code: SwarmDiscoveryIssueCode;
|
|
106
|
+
sessionId?: string;
|
|
107
|
+
endpointId?: string;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface SwarmDiscoveryResult {
|
|
111
|
+
peers: SwarmPeerDescription[];
|
|
112
|
+
issues: SwarmDiscoveryIssue[];
|
|
113
|
+
scannedEntries: number;
|
|
114
|
+
saturated: boolean;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface ManifestRecord {
|
|
118
|
+
manifest: SignedEndpointManifest;
|
|
119
|
+
manifestPath: string;
|
|
120
|
+
socketPath: string;
|
|
121
|
+
raw: string;
|
|
122
|
+
socketIdentity?: { dev: bigint; ino: bigint };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
interface ManifestReadResult {
|
|
126
|
+
records: ManifestRecord[];
|
|
127
|
+
issues: SwarmDiscoveryIssue[];
|
|
128
|
+
scannedEntries: number;
|
|
129
|
+
saturated: boolean;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export class SwarmTransport {
|
|
133
|
+
private server?: Server;
|
|
134
|
+
private paths?: EndpointPaths;
|
|
135
|
+
private startPromise?: Promise<void>;
|
|
136
|
+
private stopPromise?: Promise<void>;
|
|
137
|
+
private stopped = false;
|
|
138
|
+
private ownsEndpointFiles = false;
|
|
139
|
+
private readonly lifecycle = new AbortController();
|
|
140
|
+
private readonly sockets = new Set<Socket>();
|
|
141
|
+
private readonly pendingTasks = new Set<Promise<void>>();
|
|
142
|
+
private readonly frameReplay = new ReplayWindow(FRAME_REPLAY_CAPACITY, FRAME_REPLAY_TTL_MS);
|
|
143
|
+
private readonly responseReplay = new ReplayWindow(FRAME_REPLAY_CAPACITY, FRAME_REPLAY_TTL_MS);
|
|
144
|
+
private readonly messageDedup = new ReplayWindow(MESSAGE_DEDUP_CAPACITY, MESSAGE_DEDUP_TTL_MS);
|
|
145
|
+
private readonly senderRateLimiter = new FixedWindowRateLimiter(
|
|
146
|
+
MAX_REQUESTS_PER_MINUTE,
|
|
147
|
+
RATE_WINDOW_MS,
|
|
148
|
+
MAX_DISCOVERY_MANIFESTS,
|
|
149
|
+
);
|
|
150
|
+
private readonly totalRateLimiter = new FixedWindowRateLimiter(MAX_TOTAL_REQUESTS_PER_MINUTE, RATE_WINDOW_MS, 1);
|
|
151
|
+
private readonly peer: SwarmPeerDescription;
|
|
152
|
+
private kickoffConsumed = false;
|
|
153
|
+
private kickoffPending = false;
|
|
154
|
+
private inflightDeliveries = 0;
|
|
155
|
+
private readonly pendingMessageIds = new Set<string>();
|
|
156
|
+
private readonly now: () => number;
|
|
157
|
+
|
|
158
|
+
constructor(private readonly options: SwarmTransportOptions) {
|
|
159
|
+
if (process.platform === "win32") {
|
|
160
|
+
throw new Error("Pi Agent Swarm local transport requires a POSIX platform");
|
|
161
|
+
}
|
|
162
|
+
if (options.group.secret.length !== 32) throw new Error("Pi Agent Swarm group secret is invalid");
|
|
163
|
+
if (options.requestTimeoutMs !== undefined) {
|
|
164
|
+
assertPositiveDuration(options.requestTimeoutMs, "Pi Agent Swarm request timeout");
|
|
165
|
+
}
|
|
166
|
+
if (options.discoveryDeadlineMs !== undefined) {
|
|
167
|
+
assertPositiveDuration(options.discoveryDeadlineMs, "Pi Agent Swarm discovery deadline");
|
|
168
|
+
}
|
|
169
|
+
if (options.discoveryProbeTimeoutMs !== undefined) {
|
|
170
|
+
assertPositiveDuration(options.discoveryProbeTimeoutMs, "Pi Agent Swarm discovery probe timeout");
|
|
171
|
+
}
|
|
172
|
+
if (!SAFE_SESSION_ID.test(options.peer.sessionId)) {
|
|
173
|
+
throw new Error("Pi Agent Swarm local session id is invalid");
|
|
174
|
+
}
|
|
175
|
+
if (options.peer.protocolVersion !== SWARM_PROTOCOL_VERSION) {
|
|
176
|
+
throw new Error("Pi Agent Swarm local protocol version is invalid");
|
|
177
|
+
}
|
|
178
|
+
const endpointId = options.endpointId ?? randomEndpointId();
|
|
179
|
+
this.peer = validatePeerDescription({ ...options.peer, endpointId });
|
|
180
|
+
if (
|
|
181
|
+
(options.kickoffCapability !== undefined && !SAFE_SESSION_ID.test(options.kickoffCapability)) ||
|
|
182
|
+
Boolean(this.peer.launchId) !== Boolean(options.kickoffCapability)
|
|
183
|
+
) {
|
|
184
|
+
throw new Error("Pi Agent Swarm local kickoff capability is invalid");
|
|
185
|
+
}
|
|
186
|
+
this.now = options.now ?? Date.now;
|
|
187
|
+
this.kickoffConsumed = options.kickoffConsumed === true;
|
|
188
|
+
for (const id of options.seenMessageIds ?? []) {
|
|
189
|
+
if (SAFE_SESSION_ID.test(id)) this.messageDedup.accept(id, this.now());
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
setAcceptsRequests(value: boolean): void {
|
|
194
|
+
this.peer.acceptsRequests = value;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
setColor(color: string): void {
|
|
198
|
+
this.peer.color = color;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
setName(name: string): void {
|
|
202
|
+
this.peer.name = name;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
get peerDescription(): SwarmPeerDescription {
|
|
206
|
+
return { ...this.peer };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
get endpointManifest(): (EndpointPaths & { peer: SwarmPeerDescription }) | undefined {
|
|
210
|
+
return this.paths ? { ...this.paths, peer: { ...this.peer } } : undefined;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async start(signal?: AbortSignal): Promise<void> {
|
|
214
|
+
if (this.stopped) throw new Error("Pi Agent Swarm transport has already stopped");
|
|
215
|
+
if (this.startPromise) return this.startPromise;
|
|
216
|
+
throwIfAborted(signal, "Pi Agent Swarm transport start aborted");
|
|
217
|
+
const operationSignal = combineSignals(signal, this.lifecycle.signal);
|
|
218
|
+
this.startPromise = this.startOwned(operationSignal).catch(async (error) => {
|
|
219
|
+
await this.cleanup();
|
|
220
|
+
this.startPromise = undefined;
|
|
221
|
+
throw error;
|
|
222
|
+
});
|
|
223
|
+
return this.startPromise;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async discover(
|
|
227
|
+
signal?: AbortSignal,
|
|
228
|
+
deadlineMs = this.options.discoveryDeadlineMs ?? DEFAULT_DISCOVERY_DEADLINE_MS,
|
|
229
|
+
): Promise<SwarmDiscoveryResult> {
|
|
230
|
+
this.assertStarted();
|
|
231
|
+
throwIfAborted(signal, "Pi Agent Swarm peer discovery aborted");
|
|
232
|
+
assertPositiveDuration(deadlineMs, "Pi Agent Swarm discovery deadline");
|
|
233
|
+
const deadline = deadlineSignal(deadlineMs, "Pi Agent Swarm peer discovery deadline exceeded");
|
|
234
|
+
const operationSignal = combineSignals(signal, this.lifecycle.signal, deadline.signal);
|
|
235
|
+
try {
|
|
236
|
+
const manifestResult = await this.readManifests(operationSignal);
|
|
237
|
+
const issues = [...manifestResult.issues];
|
|
238
|
+
const discovered: Array<{ peer: SwarmPeerDescription; record: ManifestRecord }> = [];
|
|
239
|
+
let cursor = 0;
|
|
240
|
+
const worker = async () => {
|
|
241
|
+
while (cursor < manifestResult.records.length && !operationSignal.aborted) {
|
|
242
|
+
const index = cursor;
|
|
243
|
+
cursor += 1;
|
|
244
|
+
const record = manifestResult.records[index];
|
|
245
|
+
if (!record || record.manifest.endpointId === this.peer.endpointId) continue;
|
|
246
|
+
try {
|
|
247
|
+
const response = await this.request(
|
|
248
|
+
record,
|
|
249
|
+
{ kind: "describe" },
|
|
250
|
+
operationSignal,
|
|
251
|
+
this.options.discoveryProbeTimeoutMs ?? DEFAULT_DISCOVERY_PROBE_TIMEOUT_MS,
|
|
252
|
+
);
|
|
253
|
+
if (response.payload.kind !== "description") {
|
|
254
|
+
throw new Error("Pi Agent Swarm peer returned an invalid description response");
|
|
255
|
+
}
|
|
256
|
+
assertDescriptionMatchesManifest(response.payload.peer, record);
|
|
257
|
+
if (response.payload.peer.sessionId === this.peer.sessionId) {
|
|
258
|
+
addIssue(issues, {
|
|
259
|
+
code: "identity_conflict",
|
|
260
|
+
sessionId: this.peer.sessionId,
|
|
261
|
+
endpointId: response.payload.peer.endpointId,
|
|
262
|
+
});
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
discovered.push({ peer: response.payload.peer, record });
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (signal?.aborted || this.lifecycle.signal.aborted) throw error;
|
|
268
|
+
if (deadline.signal.aborted) break;
|
|
269
|
+
if (isDeadEndpointError(error)) {
|
|
270
|
+
addIssue(issues, {
|
|
271
|
+
code: "peer_unreachable",
|
|
272
|
+
sessionId: record.manifest.sessionId,
|
|
273
|
+
endpointId: record.manifest.endpointId,
|
|
274
|
+
});
|
|
275
|
+
await this.removeStaleRecord(record);
|
|
276
|
+
} else if (!isAbortError(error)) {
|
|
277
|
+
addIssue(issues, {
|
|
278
|
+
code: "protocol_error",
|
|
279
|
+
sessionId: record.manifest.sessionId,
|
|
280
|
+
endpointId: record.manifest.endpointId,
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
await Promise.all(
|
|
287
|
+
Array.from(
|
|
288
|
+
{
|
|
289
|
+
length: Math.min(MAX_DISCOVERY_CONCURRENCY, manifestResult.records.length),
|
|
290
|
+
},
|
|
291
|
+
() => worker(),
|
|
292
|
+
),
|
|
293
|
+
);
|
|
294
|
+
if (signal?.aborted || this.lifecycle.signal.aborted) {
|
|
295
|
+
throw abortError("Pi Agent Swarm peer discovery aborted");
|
|
296
|
+
}
|
|
297
|
+
if (deadline.signal.aborted) addIssue(issues, { code: "deadline_exceeded" });
|
|
298
|
+
const peers: SwarmPeerDescription[] = [];
|
|
299
|
+
const bySession = new Map<string, Array<{ peer: SwarmPeerDescription; record: ManifestRecord }>>();
|
|
300
|
+
for (const item of discovered) {
|
|
301
|
+
const matches = bySession.get(item.peer.sessionId) ?? [];
|
|
302
|
+
matches.push(item);
|
|
303
|
+
bySession.set(item.peer.sessionId, matches);
|
|
304
|
+
}
|
|
305
|
+
for (const [sessionId, matches] of bySession) {
|
|
306
|
+
if (matches.length === 1 && matches[0]) {
|
|
307
|
+
peers.push(matches[0].peer);
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
addIssue(issues, { code: "identity_conflict", sessionId });
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
peers: peers.sort((left, right) => left.sessionId.localeCompare(right.sessionId)),
|
|
314
|
+
issues,
|
|
315
|
+
scannedEntries: manifestResult.scannedEntries,
|
|
316
|
+
saturated: manifestResult.saturated,
|
|
317
|
+
};
|
|
318
|
+
} finally {
|
|
319
|
+
deadline.dispose();
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async listPeers(signal?: AbortSignal, deadlineMs?: number): Promise<SwarmPeerDescription[]> {
|
|
324
|
+
return (await this.discover(signal, deadlineMs)).peers;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async send(
|
|
328
|
+
targetSessionId: string,
|
|
329
|
+
value: SwarmMessage,
|
|
330
|
+
signal?: AbortSignal,
|
|
331
|
+
authorization?: SwarmSendAuthorization,
|
|
332
|
+
): Promise<SwarmDeliveryAck> {
|
|
333
|
+
this.assertStarted();
|
|
334
|
+
throwIfAborted(signal, "Pi Agent Swarm message send aborted");
|
|
335
|
+
if (!SAFE_SESSION_ID.test(targetSessionId)) {
|
|
336
|
+
throw new Error("Pi Agent Swarm target session id is invalid");
|
|
337
|
+
}
|
|
338
|
+
const message = validateMessage(value);
|
|
339
|
+
validateMessageTiming(message, this.now());
|
|
340
|
+
if (message.fromSessionId !== this.peer.sessionId) {
|
|
341
|
+
throw new Error("Pi Agent Swarm message sender does not match the local session");
|
|
342
|
+
}
|
|
343
|
+
if (message.toSessionId !== targetSessionId) {
|
|
344
|
+
throw new Error("Pi Agent Swarm message target does not match the selected session");
|
|
345
|
+
}
|
|
346
|
+
if (authorization && message.mode !== "kickoff") {
|
|
347
|
+
throw new Error("Pi Agent Swarm kickoff authorization is invalid for this message mode");
|
|
348
|
+
}
|
|
349
|
+
if (authorization && !SAFE_SESSION_ID.test(authorization.kickoffCapability)) {
|
|
350
|
+
throw new Error("Pi Agent Swarm kickoff authorization is invalid");
|
|
351
|
+
}
|
|
352
|
+
const manifestResult = await this.readManifests(signal);
|
|
353
|
+
throwIfAborted(signal, "Pi Agent Swarm message send aborted");
|
|
354
|
+
const candidates = manifestResult.records.filter(({ manifest }) => manifest.sessionId === targetSessionId);
|
|
355
|
+
if (candidates.length === 0) {
|
|
356
|
+
throw new Error(`Pi Agent Swarm session ${targetSessionId} is unavailable`);
|
|
357
|
+
}
|
|
358
|
+
const record =
|
|
359
|
+
candidates.length === 1 ? candidates[0] : await this.resolveUniqueTarget(targetSessionId, candidates, signal);
|
|
360
|
+
if (!record) throw new Error(`Pi Agent Swarm session ${targetSessionId} is unavailable`);
|
|
361
|
+
let response: SignedSwarmFrame;
|
|
362
|
+
try {
|
|
363
|
+
response = await this.request(
|
|
364
|
+
record,
|
|
365
|
+
{
|
|
366
|
+
kind: "message",
|
|
367
|
+
message,
|
|
368
|
+
...(authorization ? { kickoffCapability: authorization.kickoffCapability } : {}),
|
|
369
|
+
},
|
|
370
|
+
signal,
|
|
371
|
+
);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (isDeadEndpointError(error)) await this.removeStaleRecord(record);
|
|
374
|
+
throw error;
|
|
375
|
+
}
|
|
376
|
+
if (response.payload.kind !== "ack") {
|
|
377
|
+
throw new Error("Pi Agent Swarm peer returned an invalid delivery acknowledgement");
|
|
378
|
+
}
|
|
379
|
+
return deliveryAck(response.payload);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async stop(): Promise<void> {
|
|
383
|
+
if (this.stopPromise) return this.stopPromise;
|
|
384
|
+
this.stopped = true;
|
|
385
|
+
this.lifecycle.abort();
|
|
386
|
+
const start = this.startPromise;
|
|
387
|
+
this.stopPromise = (async () => {
|
|
388
|
+
await start?.catch(() => undefined);
|
|
389
|
+
await this.cleanup();
|
|
390
|
+
})();
|
|
391
|
+
return this.stopPromise;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
private async startOwned(signal?: AbortSignal): Promise<void> {
|
|
395
|
+
const directory = await ensureGroupRuntimeDirectory(this.options.group.id, {
|
|
396
|
+
...(this.options.baseDirectory ? { baseDirectory: this.options.baseDirectory } : {}),
|
|
397
|
+
});
|
|
398
|
+
await cleanupStaleRuntimeEntries(directory, this.now());
|
|
399
|
+
throwIfAborted(signal, "Pi Agent Swarm transport start aborted");
|
|
400
|
+
const paths = createEndpointPaths(directory, this.peer.endpointId);
|
|
401
|
+
await assertEndpointPathsAvailable(paths);
|
|
402
|
+
const server = createServer((socket) => this.acceptSocket(socket));
|
|
403
|
+
this.server = server;
|
|
404
|
+
this.paths = paths;
|
|
405
|
+
await listenSocketServer(server, paths.socketPath, signal);
|
|
406
|
+
this.ownsEndpointFiles = true;
|
|
407
|
+
await chmod(paths.socketPath, 0o600);
|
|
408
|
+
throwIfAborted(signal, "Pi Agent Swarm transport start aborted");
|
|
409
|
+
await publishManifest(
|
|
410
|
+
paths.manifestPath,
|
|
411
|
+
createSignedEndpointManifest(
|
|
412
|
+
{
|
|
413
|
+
groupId: this.options.group.id,
|
|
414
|
+
endpointId: this.peer.endpointId,
|
|
415
|
+
sessionId: this.peer.sessionId,
|
|
416
|
+
socketName: basename(paths.socketPath),
|
|
417
|
+
pid: this.peer.pid,
|
|
418
|
+
publishedAt: this.now(),
|
|
419
|
+
},
|
|
420
|
+
this.options.group.secret,
|
|
421
|
+
),
|
|
422
|
+
);
|
|
423
|
+
throwIfAborted(signal, "Pi Agent Swarm transport start aborted");
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
private acceptSocket(socket: Socket): void {
|
|
427
|
+
if (
|
|
428
|
+
this.stopped ||
|
|
429
|
+
this.sockets.size >= MAX_PENDING_CONNECTIONS ||
|
|
430
|
+
this.pendingTasks.size >= MAX_PENDING_CONNECTIONS
|
|
431
|
+
) {
|
|
432
|
+
socket.destroy();
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
this.sockets.add(socket);
|
|
436
|
+
const connection = new AbortController();
|
|
437
|
+
const timer = setTimeout(() => {
|
|
438
|
+
connection.abort();
|
|
439
|
+
socket.destroy();
|
|
440
|
+
}, this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);
|
|
441
|
+
timer.unref();
|
|
442
|
+
let handled = false;
|
|
443
|
+
const decoder = new JsonLineDecoder({
|
|
444
|
+
onValue: (value) => {
|
|
445
|
+
if (handled) {
|
|
446
|
+
socket.destroy();
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
handled = true;
|
|
450
|
+
const task = this.handleIncoming(socket, value, connection.signal);
|
|
451
|
+
this.pendingTasks.add(task);
|
|
452
|
+
void task.then(
|
|
453
|
+
() => this.pendingTasks.delete(task),
|
|
454
|
+
() => this.pendingTasks.delete(task),
|
|
455
|
+
);
|
|
456
|
+
},
|
|
457
|
+
onError: () => socket.destroy(),
|
|
458
|
+
});
|
|
459
|
+
socket.on("data", (chunk) => decoder.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk));
|
|
460
|
+
socket.on("end", () => decoder.finish());
|
|
461
|
+
socket.on("error", () => undefined);
|
|
462
|
+
socket.on("close", () => {
|
|
463
|
+
clearTimeout(timer);
|
|
464
|
+
connection.abort();
|
|
465
|
+
this.sockets.delete(socket);
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
private async handleIncoming(socket: Socket, value: unknown, signal: AbortSignal): Promise<void> {
|
|
470
|
+
try {
|
|
471
|
+
const now = this.now();
|
|
472
|
+
const frame = verifySignedFrame(value, this.options.group.secret, {
|
|
473
|
+
expectedGroupId: this.options.group.id,
|
|
474
|
+
expectedTargetSessionId: this.peer.sessionId,
|
|
475
|
+
expectedTargetEndpointId: this.peer.endpointId,
|
|
476
|
+
now,
|
|
477
|
+
replay: this.frameReplay,
|
|
478
|
+
});
|
|
479
|
+
const totalAccepted = this.totalRateLimiter.accept("all", now);
|
|
480
|
+
const senderAccepted = this.senderRateLimiter.accept(frame.senderSessionId, now);
|
|
481
|
+
if (!totalAccepted || !senderAccepted) {
|
|
482
|
+
const retryAfterMs = Math.max(
|
|
483
|
+
totalAccepted ? 0 : this.totalRateLimiter.retryAfterMs("all", now),
|
|
484
|
+
senderAccepted ? 0 : this.senderRateLimiter.retryAfterMs(frame.senderSessionId, now),
|
|
485
|
+
);
|
|
486
|
+
await this.respond(socket, frame, {
|
|
487
|
+
kind: "ack",
|
|
488
|
+
status: "busy",
|
|
489
|
+
code: "rate_limited",
|
|
490
|
+
error: "Target session rate limit exceeded",
|
|
491
|
+
retryAfterMs,
|
|
492
|
+
});
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
if (frame.payload.kind === "describe") {
|
|
496
|
+
await this.respond(socket, frame, { kind: "description", peer: this.peer });
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
if (frame.payload.kind !== "message") throw new Error("Unsupported Pi Agent Swarm request payload");
|
|
500
|
+
const message = frame.payload.message;
|
|
501
|
+
validateMessageTiming(message, now);
|
|
502
|
+
if (message.fromSessionId !== frame.senderSessionId || message.toSessionId !== this.peer.sessionId) {
|
|
503
|
+
throw new Error("Pi Agent Swarm message identity does not match its authenticated frame");
|
|
504
|
+
}
|
|
505
|
+
if (this.messageDedup.has(message.id, now)) {
|
|
506
|
+
await this.respond(socket, frame, { kind: "ack", status: "duplicate" });
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
const policyError = this.messagePolicyError(message, frame.payload.kickoffCapability);
|
|
510
|
+
if (policyError) {
|
|
511
|
+
await this.respond(socket, frame, policyError);
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
if (this.pendingMessageIds.has(message.id) || this.inflightDeliveries >= MAX_INFLIGHT_DELIVERIES) {
|
|
515
|
+
await this.respond(socket, frame, {
|
|
516
|
+
kind: "ack",
|
|
517
|
+
status: "busy",
|
|
518
|
+
code: "target_busy",
|
|
519
|
+
error: this.pendingMessageIds.has(message.id)
|
|
520
|
+
? "Target session is still delivering this message"
|
|
521
|
+
: "Target session has too many in-flight deliveries",
|
|
522
|
+
});
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
this.pendingMessageIds.add(message.id);
|
|
526
|
+
this.inflightDeliveries += 1;
|
|
527
|
+
if (message.mode === "kickoff") this.kickoffPending = true;
|
|
528
|
+
try {
|
|
529
|
+
const deliverySignal = combineSignals(signal, this.lifecycle.signal);
|
|
530
|
+
await raceWithSignal(
|
|
531
|
+
Promise.resolve(this.options.onMessage(message, deliverySignal)),
|
|
532
|
+
deliverySignal,
|
|
533
|
+
"Pi Agent Swarm message delivery aborted",
|
|
534
|
+
);
|
|
535
|
+
this.messageDedup.record(message.id, this.now());
|
|
536
|
+
if (message.mode === "kickoff") this.kickoffConsumed = true;
|
|
537
|
+
} catch {
|
|
538
|
+
if (signal.aborted || this.lifecycle.signal.aborted) throw abortError("Delivery aborted");
|
|
539
|
+
await this.respond(socket, frame, {
|
|
540
|
+
kind: "ack",
|
|
541
|
+
status: "rejected",
|
|
542
|
+
code: "delivery_failed",
|
|
543
|
+
error: "Target session rejected the message",
|
|
544
|
+
});
|
|
545
|
+
return;
|
|
546
|
+
} finally {
|
|
547
|
+
this.pendingMessageIds.delete(message.id);
|
|
548
|
+
this.inflightDeliveries -= 1;
|
|
549
|
+
if (message.mode === "kickoff") this.kickoffPending = false;
|
|
550
|
+
}
|
|
551
|
+
await this.respond(socket, frame, { kind: "ack", status: "accepted" });
|
|
552
|
+
} catch {
|
|
553
|
+
socket.destroy();
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
private messagePolicyError(message: SwarmMessage, kickoffCapability?: string): SwarmAckPayload | undefined {
|
|
558
|
+
if (message.kind === "shutdown" && !(this.options.authorizeShutdown?.(message) ?? false)) {
|
|
559
|
+
return {
|
|
560
|
+
kind: "ack",
|
|
561
|
+
status: "rejected",
|
|
562
|
+
code: "shutdown_unauthorized",
|
|
563
|
+
error: "Sender is not authorized to shut down this session",
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
if (message.mode === "request" && !this.peer.acceptsRequests) {
|
|
567
|
+
return {
|
|
568
|
+
kind: "ack",
|
|
569
|
+
status: "rejected",
|
|
570
|
+
code: "requests_disabled",
|
|
571
|
+
error: "Target session does not allow agent requests",
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
if (message.mode === "kickoff") {
|
|
575
|
+
if (
|
|
576
|
+
!this.peer.launchId ||
|
|
577
|
+
message.launchId !== this.peer.launchId ||
|
|
578
|
+
!secretEqual(kickoffCapability, this.options.kickoffCapability)
|
|
579
|
+
) {
|
|
580
|
+
return {
|
|
581
|
+
kind: "ack",
|
|
582
|
+
status: "rejected",
|
|
583
|
+
code: "launch_mismatch",
|
|
584
|
+
error: "Launch kickoff does not match the target session",
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
if (this.kickoffConsumed || this.kickoffPending) {
|
|
588
|
+
return {
|
|
589
|
+
kind: "ack",
|
|
590
|
+
status: "rejected",
|
|
591
|
+
code: "kickoff_consumed",
|
|
592
|
+
error: "Launch kickoff has already been consumed",
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return undefined;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
private async respond(
|
|
600
|
+
socket: Socket,
|
|
601
|
+
request: SignedSwarmFrame,
|
|
602
|
+
payload: SignedSwarmFrame["payload"],
|
|
603
|
+
): Promise<void> {
|
|
604
|
+
const response = createSignedFrame(
|
|
605
|
+
{
|
|
606
|
+
groupId: this.options.group.id,
|
|
607
|
+
requestId: request.requestId,
|
|
608
|
+
targetSessionId: request.senderSessionId,
|
|
609
|
+
targetEndpointId: request.senderEndpointId,
|
|
610
|
+
senderSessionId: this.peer.sessionId,
|
|
611
|
+
senderEndpointId: this.peer.endpointId,
|
|
612
|
+
issuedAt: this.now(),
|
|
613
|
+
nonce: randomId("nonce"),
|
|
614
|
+
payload,
|
|
615
|
+
},
|
|
616
|
+
this.options.group.secret,
|
|
617
|
+
);
|
|
618
|
+
await writeFrame(socket, response);
|
|
619
|
+
socket.end();
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
private async readManifests(signal?: AbortSignal): Promise<ManifestReadResult> {
|
|
623
|
+
const paths = this.paths;
|
|
624
|
+
if (!paths) throw new Error("Pi Agent Swarm transport is not started");
|
|
625
|
+
throwIfAborted(signal, "Pi Agent Swarm peer discovery aborted");
|
|
626
|
+
const records: ManifestRecord[] = [];
|
|
627
|
+
const issues: SwarmDiscoveryIssue[] = [];
|
|
628
|
+
let scannedEntries = 0;
|
|
629
|
+
let saturated = false;
|
|
630
|
+
const directory = await opendir(paths.directory);
|
|
631
|
+
try {
|
|
632
|
+
for await (const entry of directory) {
|
|
633
|
+
throwIfAborted(signal, "Pi Agent Swarm peer discovery aborted");
|
|
634
|
+
if (scannedEntries >= MAX_RUNTIME_SCAN_ENTRIES) {
|
|
635
|
+
saturated = true;
|
|
636
|
+
addIssue(issues, { code: "scan_saturated" });
|
|
637
|
+
break;
|
|
638
|
+
}
|
|
639
|
+
scannedEntries += 1;
|
|
640
|
+
if (!entry.isFile()) continue;
|
|
641
|
+
const endpointId = endpointIdFromManifestName(entry.name);
|
|
642
|
+
if (!endpointId) {
|
|
643
|
+
if (entry.name.endsWith(".json")) addIssue(issues, { code: "invalid_manifest" });
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
if (records.length >= MAX_DISCOVERY_MANIFESTS) {
|
|
647
|
+
saturated = true;
|
|
648
|
+
addIssue(issues, { code: "scan_saturated" });
|
|
649
|
+
continue;
|
|
650
|
+
}
|
|
651
|
+
try {
|
|
652
|
+
records.push(
|
|
653
|
+
await readManifest(paths.directory, resolve(paths.directory, entry.name), endpointId, this.options.group),
|
|
654
|
+
);
|
|
655
|
+
} catch {
|
|
656
|
+
addIssue(issues, { code: "invalid_manifest", endpointId });
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
} finally {
|
|
660
|
+
await directory.close().catch(() => undefined);
|
|
661
|
+
}
|
|
662
|
+
throwIfAborted(signal, "Pi Agent Swarm peer discovery aborted");
|
|
663
|
+
records.sort((left, right) => left.manifest.endpointId.localeCompare(right.manifest.endpointId));
|
|
664
|
+
return { records, issues, scannedEntries, saturated };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
private async request(
|
|
668
|
+
record: ManifestRecord,
|
|
669
|
+
payload: SignedSwarmFrame["payload"],
|
|
670
|
+
signal?: AbortSignal,
|
|
671
|
+
timeoutMs = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
672
|
+
): Promise<SignedSwarmFrame> {
|
|
673
|
+
throwIfAborted(signal, "Pi Agent Swarm request aborted");
|
|
674
|
+
const requestId = randomId("req");
|
|
675
|
+
const frame = createSignedFrame(
|
|
676
|
+
{
|
|
677
|
+
groupId: this.options.group.id,
|
|
678
|
+
requestId,
|
|
679
|
+
targetSessionId: record.manifest.sessionId,
|
|
680
|
+
targetEndpointId: record.manifest.endpointId,
|
|
681
|
+
senderSessionId: this.peer.sessionId,
|
|
682
|
+
senderEndpointId: this.peer.endpointId,
|
|
683
|
+
issuedAt: this.now(),
|
|
684
|
+
nonce: randomId("nonce"),
|
|
685
|
+
payload,
|
|
686
|
+
},
|
|
687
|
+
this.options.group.secret,
|
|
688
|
+
);
|
|
689
|
+
const value = await requestFrame(record.socketPath, frame, signal, timeoutMs);
|
|
690
|
+
throwIfAborted(signal, "Pi Agent Swarm request aborted");
|
|
691
|
+
const response = verifySignedFrame(value, this.options.group.secret, {
|
|
692
|
+
expectedGroupId: this.options.group.id,
|
|
693
|
+
expectedTargetSessionId: this.peer.sessionId,
|
|
694
|
+
expectedTargetEndpointId: this.peer.endpointId,
|
|
695
|
+
now: this.now(),
|
|
696
|
+
replay: this.responseReplay,
|
|
697
|
+
});
|
|
698
|
+
if (
|
|
699
|
+
response.requestId !== requestId ||
|
|
700
|
+
response.senderSessionId !== record.manifest.sessionId ||
|
|
701
|
+
response.senderEndpointId !== record.manifest.endpointId
|
|
702
|
+
) {
|
|
703
|
+
throw new Error("Pi Agent Swarm response identity does not match its request");
|
|
704
|
+
}
|
|
705
|
+
return response;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
private async resolveUniqueTarget(
|
|
709
|
+
targetSessionId: string,
|
|
710
|
+
candidates: ManifestRecord[],
|
|
711
|
+
signal?: AbortSignal,
|
|
712
|
+
): Promise<ManifestRecord | undefined> {
|
|
713
|
+
const live: ManifestRecord[] = [];
|
|
714
|
+
await Promise.all(
|
|
715
|
+
candidates.map(async (record) => {
|
|
716
|
+
try {
|
|
717
|
+
const response = await this.request(
|
|
718
|
+
record,
|
|
719
|
+
{ kind: "describe" },
|
|
720
|
+
signal,
|
|
721
|
+
this.options.discoveryProbeTimeoutMs ?? DEFAULT_DISCOVERY_PROBE_TIMEOUT_MS,
|
|
722
|
+
);
|
|
723
|
+
if (response.payload.kind !== "description") return;
|
|
724
|
+
assertDescriptionMatchesManifest(response.payload.peer, record);
|
|
725
|
+
live.push(record);
|
|
726
|
+
} catch (error) {
|
|
727
|
+
if (isAbortError(error)) throw error;
|
|
728
|
+
if (isDeadEndpointError(error)) await this.removeStaleRecord(record);
|
|
729
|
+
}
|
|
730
|
+
}),
|
|
731
|
+
);
|
|
732
|
+
if (live.length > 1) {
|
|
733
|
+
throw new Error(`Pi Agent Swarm session ${targetSessionId} has conflicting live endpoints`);
|
|
734
|
+
}
|
|
735
|
+
return live[0];
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
private async removeStaleRecord(record: ManifestRecord): Promise<void> {
|
|
739
|
+
try {
|
|
740
|
+
const current = await readBoundedUtf8(record.manifestPath, MAX_MANIFEST_BYTES);
|
|
741
|
+
if (current !== record.raw) return;
|
|
742
|
+
await rm(record.manifestPath, { force: true });
|
|
743
|
+
if (record.socketIdentity) {
|
|
744
|
+
const info = await lstat(record.socketPath, { bigint: true }).catch(() => undefined);
|
|
745
|
+
if (info?.isSocket() && info.dev === record.socketIdentity.dev && info.ino === record.socketIdentity.ino) {
|
|
746
|
+
await rm(record.socketPath, { force: true });
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
} catch {
|
|
750
|
+
// A concurrent owner change wins over stale cleanup.
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
private assertStarted(): void {
|
|
755
|
+
if (!this.startPromise || !this.paths || this.stopped) {
|
|
756
|
+
throw new Error("Pi Agent Swarm transport is not started");
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
private async cleanup(): Promise<void> {
|
|
761
|
+
const server = this.server;
|
|
762
|
+
this.server = undefined;
|
|
763
|
+
for (const socket of this.sockets) socket.destroy();
|
|
764
|
+
this.sockets.clear();
|
|
765
|
+
if (server) await closeSocketServer(server);
|
|
766
|
+
await Promise.allSettled([...this.pendingTasks]);
|
|
767
|
+
this.pendingTasks.clear();
|
|
768
|
+
this.pendingMessageIds.clear();
|
|
769
|
+
this.kickoffPending = false;
|
|
770
|
+
this.inflightDeliveries = 0;
|
|
771
|
+
const paths = this.paths;
|
|
772
|
+
if (paths && this.ownsEndpointFiles) await removeOwnedEndpoint(paths);
|
|
773
|
+
this.ownsEndpointFiles = false;
|
|
774
|
+
this.paths = undefined;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
async function assertEndpointPathsAvailable(paths: EndpointPaths): Promise<void> {
|
|
779
|
+
for (const path of [paths.manifestPath, paths.socketPath]) {
|
|
780
|
+
try {
|
|
781
|
+
await lstat(path);
|
|
782
|
+
throw new Error("Pi Agent Swarm endpoint identity is already in use");
|
|
783
|
+
} catch (error) {
|
|
784
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
throw error;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
async function readManifest(
|
|
793
|
+
directory: string,
|
|
794
|
+
manifestPath: string,
|
|
795
|
+
endpointId: string,
|
|
796
|
+
group: SwarmGroup,
|
|
797
|
+
): Promise<ManifestRecord> {
|
|
798
|
+
assertOwnedPath(directory, manifestPath, ".json");
|
|
799
|
+
const handle = await open(manifestPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
800
|
+
try {
|
|
801
|
+
const info = await handle.stat({ bigint: true });
|
|
802
|
+
if (!info.isFile() || info.size > BigInt(MAX_MANIFEST_BYTES)) {
|
|
803
|
+
throw new Error("Pi Agent Swarm endpoint manifest is invalid");
|
|
804
|
+
}
|
|
805
|
+
if (typeof process.getuid === "function" && Number(info.uid) !== process.getuid()) {
|
|
806
|
+
throw new Error("Pi Agent Swarm endpoint manifest has another owner");
|
|
807
|
+
}
|
|
808
|
+
if ((Number(info.mode) & 0o777) !== 0o600) {
|
|
809
|
+
throw new Error("Pi Agent Swarm endpoint manifest permissions are not private");
|
|
810
|
+
}
|
|
811
|
+
const raw = await readBoundedHandleUtf8(handle, MAX_MANIFEST_BYTES);
|
|
812
|
+
const manifest = verifySignedEndpointManifest(JSON.parse(raw) as unknown, group.secret, {
|
|
813
|
+
expectedGroupId: group.id,
|
|
814
|
+
expectedEndpointId: endpointId,
|
|
815
|
+
});
|
|
816
|
+
const socketPath = join(directory, manifest.socketName);
|
|
817
|
+
if (dirname(resolve(socketPath)) !== resolve(directory)) {
|
|
818
|
+
throw new Error("Pi Agent Swarm endpoint socket path is invalid");
|
|
819
|
+
}
|
|
820
|
+
const socketInfo = await lstat(socketPath, { bigint: true }).catch(() => undefined);
|
|
821
|
+
if (socketInfo) {
|
|
822
|
+
if (!socketInfo.isSocket()) throw new Error("Pi Agent Swarm endpoint path is not a Unix socket");
|
|
823
|
+
if (typeof process.getuid === "function" && Number(socketInfo.uid) !== process.getuid()) {
|
|
824
|
+
throw new Error("Pi Agent Swarm endpoint socket has another owner");
|
|
825
|
+
}
|
|
826
|
+
if ((Number(socketInfo.mode) & 0o777) !== 0o600) {
|
|
827
|
+
throw new Error("Pi Agent Swarm endpoint socket permissions are not private");
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
return {
|
|
831
|
+
manifest,
|
|
832
|
+
manifestPath,
|
|
833
|
+
socketPath,
|
|
834
|
+
raw,
|
|
835
|
+
...(socketInfo ? { socketIdentity: { dev: socketInfo.dev, ino: socketInfo.ino } } : {}),
|
|
836
|
+
};
|
|
837
|
+
} finally {
|
|
838
|
+
await handle.close();
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
function assertDescriptionMatchesManifest(peer: SwarmPeerDescription, record: ManifestRecord): void {
|
|
843
|
+
if (
|
|
844
|
+
peer.sessionId !== record.manifest.sessionId ||
|
|
845
|
+
peer.endpointId !== record.manifest.endpointId ||
|
|
846
|
+
peer.pid !== record.manifest.pid
|
|
847
|
+
) {
|
|
848
|
+
throw new Error("Pi Agent Swarm peer identity does not match its endpoint manifest");
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
function deliveryAck(payload: SwarmAckPayload): SwarmDeliveryAck {
|
|
853
|
+
return {
|
|
854
|
+
accepted: payload.status === "accepted" || payload.status === "duplicate",
|
|
855
|
+
duplicate: payload.status === "duplicate",
|
|
856
|
+
...(payload.code ? { code: payload.code } : {}),
|
|
857
|
+
...(payload.error ? { error: payload.error } : {}),
|
|
858
|
+
...(payload.retryAfterMs !== undefined ? { retryAfterMs: payload.retryAfterMs } : {}),
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
function addIssue(issues: SwarmDiscoveryIssue[], issue: SwarmDiscoveryIssue): void {
|
|
863
|
+
if (issues.length >= MAX_DISCOVERY_ISSUES) return;
|
|
864
|
+
if (
|
|
865
|
+
issues.some(
|
|
866
|
+
(existing) =>
|
|
867
|
+
existing.code === issue.code &&
|
|
868
|
+
existing.sessionId === issue.sessionId &&
|
|
869
|
+
existing.endpointId === issue.endpointId,
|
|
870
|
+
)
|
|
871
|
+
) {
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
issues.push(issue);
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
function randomId(prefix: string): string {
|
|
878
|
+
return `${prefix}_${randomBytes(12).toString("hex")}`;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
function combineSignals(...signals: Array<AbortSignal | undefined>): AbortSignal {
|
|
882
|
+
const concrete = signals.filter((signal): signal is AbortSignal => signal !== undefined);
|
|
883
|
+
return concrete.length === 0
|
|
884
|
+
? new AbortController().signal
|
|
885
|
+
: concrete.length === 1
|
|
886
|
+
? concrete[0]
|
|
887
|
+
: AbortSignal.any(concrete);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
function deadlineSignal(milliseconds: number, message: string): { signal: AbortSignal; dispose(): void } {
|
|
891
|
+
const controller = new AbortController();
|
|
892
|
+
const timer = setTimeout(() => controller.abort(abortError(message)), milliseconds);
|
|
893
|
+
timer.unref();
|
|
894
|
+
return { signal: controller.signal, dispose: () => clearTimeout(timer) };
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
function secretEqual(actual: string | undefined, expected: string | undefined): boolean {
|
|
898
|
+
if (!actual || !expected) return false;
|
|
899
|
+
const actualBytes = Buffer.from(actual);
|
|
900
|
+
const expectedBytes = Buffer.from(expected);
|
|
901
|
+
return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
function raceWithSignal<T>(task: Promise<T>, signal: AbortSignal, message: string): Promise<T> {
|
|
905
|
+
if (signal.aborted) return Promise.reject(abortError(message));
|
|
906
|
+
return new Promise<T>((resolvePromise, rejectPromise) => {
|
|
907
|
+
let settled = false;
|
|
908
|
+
const settle = (operation: () => void) => {
|
|
909
|
+
if (settled) return;
|
|
910
|
+
settled = true;
|
|
911
|
+
signal.removeEventListener("abort", onAbort);
|
|
912
|
+
operation();
|
|
913
|
+
};
|
|
914
|
+
const onAbort = () => settle(() => rejectPromise(abortError(message)));
|
|
915
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
916
|
+
void task.then(
|
|
917
|
+
(value) => settle(() => resolvePromise(value)),
|
|
918
|
+
(error) => settle(() => rejectPromise(error instanceof Error ? error : new Error(String(error)))),
|
|
919
|
+
);
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
function throwIfAborted(signal: AbortSignal | undefined, message: string): void {
|
|
924
|
+
if (signal?.aborted) throw abortError(message);
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
function abortError(message: string): Error {
|
|
928
|
+
const error = new Error(message);
|
|
929
|
+
error.name = "AbortError";
|
|
930
|
+
return error;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
function isAbortError(error: unknown): boolean {
|
|
934
|
+
return error instanceof Error && error.name === "AbortError";
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
function assertPositiveDuration(value: number, label: string): void {
|
|
938
|
+
if (!Number.isFinite(value) || value < 1) throw new Error(`${label} is invalid`);
|
|
939
|
+
}
|