pi-better-subagents 0.26.2 → 0.27.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,1226 @@
1
+ /**
2
+ * Trusted parent-hosted local transport for worker operations.
3
+ *
4
+ * The host runs in the parent Pi process (or a supervisor process the parent
5
+ * owns). A child receives only an endpoint and a per-run bearer token through
6
+ * its environment. The host binds every request to the run registered for that
7
+ * token and conversation, validates shape, size, cwd and task ownership, and
8
+ * invokes injectable handlers.
9
+ *
10
+ * This module does NOT decide permissions. The handlers are the seam where the
11
+ * coordinator intersects the worker's captured task authority with the current
12
+ * Background profile. Passing a token proves only that this is the registered
13
+ * child; it does not grant the right to launch or observe anything.
14
+ */
15
+ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, unlinkSync } from "node:fs";
16
+ import { createServer, type Server, type Socket } from "node:net";
17
+ import { tmpdir } from "node:os";
18
+ import { join, resolve } from "node:path";
19
+ import { createHash, timingSafeEqual } from "node:crypto";
20
+ import {
21
+ OPERATION_BRIDGE_ENV_KEYS,
22
+ OPERATION_BRIDGE_VERSION,
23
+ OperationBridgeError,
24
+ type JsonRecord,
25
+ type OperationBridgeCapabilities,
26
+ type OperationBridgeDescriptor,
27
+ type OperationBridgeErrorBody,
28
+ type OperationBridgeLimits,
29
+ type OperationBridgeRequestEnvelope,
30
+ type OperationBridgeResponse,
31
+ type OperationToolDescriptor,
32
+ canonicalJson,
33
+ cloneJson,
34
+ createBridgeDescriptor,
35
+ descriptorsForCapabilities,
36
+ extractResultTaskIds,
37
+ extractTaskIds,
38
+ findAuthorityField,
39
+ findBridgeEnvironmentKey,
40
+ findSecretField,
41
+ generateOperationBridgeToken,
42
+ hashOperationBridgeToken,
43
+ isInsideWorkspace,
44
+ isLaunchTool,
45
+ isValidTaskId,
46
+ normalizeToolDescriptors,
47
+ normalizeWaitForOperationsResult,
48
+ operationBridgeErrorBody,
49
+ redactSecret,
50
+ validateCheckpointParams,
51
+ validateHandshakeParams,
52
+ validateJsonSchema,
53
+ validateJsonSchemaSupport,
54
+ validateParkFailedParams,
55
+ validateRequestEnvelope,
56
+ } from "./operation-bridge-types.ts";
57
+
58
+ export interface OperationBridgeLogEvent {
59
+ event: "listen" | "close" | "request" | "reject" | "register" | "rotate" | "revoke" | "checkpoint" | "park-failed";
60
+ runId?: string;
61
+ method?: string;
62
+ requestId?: string;
63
+ code?: string;
64
+ ok?: boolean;
65
+ bytes?: number;
66
+ }
67
+
68
+ /** Diagnostics must never receive a request body or a token. */
69
+ export type OperationBridgeLogger = (event: OperationBridgeLogEvent) => void;
70
+
71
+ export interface OperationRequestContext {
72
+ runId: string;
73
+ conversationId: string;
74
+ /** Registered workspace root. A handler must use this, not a caller-supplied authority field. */
75
+ cwd: string;
76
+ /** Permission/authority snapshot reference owned by the parent. Never credential material. */
77
+ authorityReference: string;
78
+ requestId: string;
79
+ tool: string;
80
+ tokenGeneration: number;
81
+ receivedAt: number;
82
+ /** Aborted when the host's handler timeout elapses. Handlers should stop externally visible work. */
83
+ signal: AbortSignal;
84
+ /** Environment names the parent must strip before spawning any background task. */
85
+ bridgeEnvironmentKeys: readonly string[];
86
+ }
87
+
88
+ export type OperationToolHandler = (
89
+ params: JsonRecord,
90
+ context: OperationRequestContext,
91
+ ) => unknown | Promise<unknown>;
92
+
93
+ export type OperationCheckpointHandler = (
94
+ params: JsonRecord,
95
+ context: OperationRequestContext,
96
+ ) => unknown | Promise<unknown>;
97
+
98
+ export type OperationOwnershipCheck = (
99
+ taskId: string,
100
+ context: OperationRequestContext,
101
+ ) => boolean | Promise<boolean>;
102
+
103
+ /** Parent policy seam for the persisted checkpoint path, prefix and identity. */
104
+ export type OperationCheckpointEvidenceCheck = (
105
+ evidence: JsonRecord,
106
+ context: OperationRequestContext,
107
+ ) => boolean | Promise<boolean>;
108
+
109
+ export interface OperationRunHandlers {
110
+ bg_task_spawn?: OperationToolHandler;
111
+ bg_task_watch?: OperationToolHandler;
112
+ bg_task_status?: OperationToolHandler;
113
+ bg_task_log?: OperationToolHandler;
114
+ wait_for_operations?: OperationToolHandler;
115
+ acknowledge_operation_result?: OperationToolHandler;
116
+ /** Required when capabilities.parking is true. */
117
+ checkpoint?: OperationCheckpointHandler;
118
+ /** Required when capabilities.parking is true. */
119
+ park_failed?: OperationCheckpointHandler;
120
+ }
121
+
122
+ export interface OperationRunRegistration {
123
+ runId: string;
124
+ conversationId: string;
125
+ /** Canonical local workspace. Explicit request cwd values must stay inside it. */
126
+ workspace: string;
127
+ /** Reference to the parent-owned worker + Background authority snapshot. */
128
+ authorityReference: string;
129
+ capabilities: OperationBridgeCapabilities;
130
+ /** Parent-supplied production schemas. Missing entries get the canonical bridge schema. */
131
+ tools?: readonly OperationToolDescriptor[];
132
+ /** Must return false for any task id the run does not own. */
133
+ ownership: OperationOwnershipCheck;
134
+ /**
135
+ * Optional parent-owned check of the claimed checkpoint evidence. Use this
136
+ * to require the trusted native session path and validate the saved prefix
137
+ * against the parent's own records before the checkpoint handler runs.
138
+ */
139
+ checkpointEvidenceValidator?: OperationCheckpointEvidenceCheck;
140
+ handlers: OperationRunHandlers;
141
+ /** Test-only or pre-provisioned token. Production should omit this and use the generated value. */
142
+ token?: string;
143
+ }
144
+
145
+ export interface OperationRunHandle {
146
+ runId: string;
147
+ token: string;
148
+ descriptor: OperationBridgeDescriptor;
149
+ }
150
+
151
+ export interface OperationRunInfo {
152
+ runId: string;
153
+ conversationId: string;
154
+ workspace: string;
155
+ authorityReference: string;
156
+ capabilities: OperationBridgeCapabilities;
157
+ descriptor: OperationBridgeDescriptor;
158
+ tokenGeneration: number;
159
+ revoked: boolean;
160
+ revokedReason?: string;
161
+ inFlight: number;
162
+ issuedWaitIds: readonly string[];
163
+ }
164
+
165
+ export interface CreateOperationBridgeHostOptions {
166
+ /** `unix` is the default on macOS/Linux; `tcp` is loopback-only on Windows or on explicit request. */
167
+ transport?: "unix" | "tcp";
168
+ /** Directory that owns the Unix socket. The host removes it only when it created it. */
169
+ socketDir?: string;
170
+ /** Explicit Unix socket path. Defaults to `<socketDir>/operations.sock`. */
171
+ socketPath?: string;
172
+ maxRequestBytes?: number;
173
+ maxResponseBytes?: number;
174
+ requestTimeoutMs?: number;
175
+ handshakeTimeoutMs?: number;
176
+ idleTimeoutMs?: number;
177
+ maxInflightPerRun?: number;
178
+ maxIdempotencyEntriesPerRun?: number;
179
+ logger?: OperationBridgeLogger;
180
+ now?: () => number;
181
+ tokenFactory?: () => string;
182
+ }
183
+
184
+ export interface OperationBridgeHost {
185
+ readonly endpoint: string;
186
+ readonly transport: "unix" | "tcp";
187
+ readonly limits: OperationBridgeLimits;
188
+ registerRun(registration: OperationRunRegistration): OperationRunHandle;
189
+ /**
190
+ * Trusted parent-only reconciliation seam. After a host reload, the parent
191
+ * can seed a wait generation that a still-running child may checkpoint.
192
+ */
193
+ markWaitIssued(runId: string, waitId: string, generation: number): void;
194
+ rotateRunToken(runId: string): string;
195
+ revokeRun(runId: string, reason?: string): void;
196
+ unregisterRun(runId: string): void;
197
+ getRun(runId: string): OperationRunInfo | undefined;
198
+ close(): Promise<void>;
199
+ }
200
+
201
+ interface FrozenRegistration {
202
+ runId: string;
203
+ conversationId: string;
204
+ workspace: string;
205
+ authorityReference: string;
206
+ capabilities: OperationBridgeCapabilities;
207
+ tools: readonly OperationToolDescriptor[];
208
+ ownership: OperationOwnershipCheck;
209
+ checkpointEvidenceValidator?: OperationCheckpointEvidenceCheck;
210
+ handlers: OperationRunHandlers;
211
+ descriptor: OperationBridgeDescriptor;
212
+ }
213
+
214
+ interface IssuedWait {
215
+ generation: number;
216
+ requestId: string;
217
+ checkpointed: boolean;
218
+ }
219
+
220
+ interface CachedLaunch {
221
+ fingerprint: string;
222
+ result: unknown;
223
+ }
224
+
225
+ interface LaunchClaim {
226
+ fingerprint: string;
227
+ /** `unknown` means the handler timed out after it may have started work; do not replay it here. */
228
+ state: "running" | "unknown";
229
+ }
230
+
231
+ interface RunState {
232
+ registration: FrozenRegistration;
233
+ tokenHash: Buffer;
234
+ tokenGeneration: number;
235
+ staleTokenHashes: Set<string>;
236
+ revoked: boolean;
237
+ revokedReason?: string;
238
+ inFlight: number;
239
+ idempotency: Map<string, CachedLaunch>;
240
+ /** Compact tombstone: a consumed launch key is never cleared by cache eviction. */
241
+ consumedLaunchKeys: Map<string, string>;
242
+ launchClaims: Map<string, LaunchClaim>;
243
+ issuedWaits: Map<string, IssuedWait>;
244
+ sockets: Set<Socket>;
245
+ }
246
+
247
+ interface ConnectionState {
248
+ buffer: Buffer;
249
+ handshake?: { runId: string; conversationId: string; tokenGeneration: number };
250
+ authFailures: number;
251
+ closed: boolean;
252
+ }
253
+
254
+ const DEFAULT_MAX_REQUEST_BYTES = 256 * 1024;
255
+ const DEFAULT_MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
256
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
257
+ const DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000;
258
+ const DEFAULT_IDLE_TIMEOUT_MS = 5 * 60_000;
259
+ const DEFAULT_MAX_INFLIGHT_PER_RUN = 8;
260
+ const DEFAULT_MAX_IDEMPOTENCY_ENTRIES = 512;
261
+ const UNIX_PATH_LIMIT = 100;
262
+
263
+ export async function createOperationBridgeHost(
264
+ options: CreateOperationBridgeHostOptions = {},
265
+ ): Promise<OperationBridgeHost> {
266
+ const transport = options.transport ?? (process.platform === "win32" ? "tcp" : "unix");
267
+ const limits: OperationBridgeLimits = Object.freeze({
268
+ maxRequestBytes: positiveInteger(options.maxRequestBytes, DEFAULT_MAX_REQUEST_BYTES, "maxRequestBytes"),
269
+ maxResponseBytes: positiveInteger(options.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES, "maxResponseBytes"),
270
+ requestTimeoutMs: positiveInteger(options.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS, "requestTimeoutMs"),
271
+ });
272
+ const handshakeTimeoutMs = positiveInteger(options.handshakeTimeoutMs, DEFAULT_HANDSHAKE_TIMEOUT_MS, "handshakeTimeoutMs");
273
+ const idleTimeoutMs = positiveInteger(options.idleTimeoutMs, DEFAULT_IDLE_TIMEOUT_MS, "idleTimeoutMs");
274
+ const maxInflightPerRun = positiveInteger(options.maxInflightPerRun, DEFAULT_MAX_INFLIGHT_PER_RUN, "maxInflightPerRun");
275
+ const maxIdempotencyEntriesPerRun = positiveInteger(
276
+ options.maxIdempotencyEntriesPerRun, DEFAULT_MAX_IDEMPOTENCY_ENTRIES, "maxIdempotencyEntriesPerRun",
277
+ );
278
+ const now = options.now ?? Date.now;
279
+ const tokenFactory = options.tokenFactory ?? generateOperationBridgeToken;
280
+ const logger = options.logger ?? (() => {});
281
+ const runs = new Map<string, RunState>();
282
+ const connectionRuns = new Map<Socket, string>();
283
+ const sockets = new Set<Socket>();
284
+ let closing = false;
285
+ let closePromise: Promise<void> | undefined;
286
+
287
+ let socketDir: string | undefined;
288
+ let ownsSocketDir = false;
289
+ let socketPath: string | undefined;
290
+ let endpoint: string;
291
+ if (transport === "unix") {
292
+ if (options.socketPath) {
293
+ socketPath = options.socketPath;
294
+ } else if (options.socketDir) {
295
+ socketDir = options.socketDir;
296
+ socketPath = join(socketDir, "operations.sock");
297
+ } else {
298
+ socketDir = createDefaultSocketDir();
299
+ ownsSocketDir = true;
300
+ socketPath = join(socketDir, "operations.sock");
301
+ }
302
+ if (socketDir) mkdirSync(socketDir, { recursive: true, mode: 0o700 });
303
+ if (socketDir) {
304
+ try { chmodSync(socketDir, 0o700); } catch { /* best effort on platforms without POSIX modes */ }
305
+ }
306
+ if (Buffer.byteLength(socketPath) > UNIX_PATH_LIMIT) {
307
+ throw new Error(`Unix socket path is too long (${Buffer.byteLength(socketPath)} bytes): ${socketPath}`);
308
+ }
309
+ removeStaleSocket(socketPath);
310
+ endpoint = `unix://${socketPath}`;
311
+ } else {
312
+ endpoint = "tcp://127.0.0.1:0";
313
+ }
314
+
315
+ const server = createServer();
316
+ server.on("connection", (socket) => {
317
+ connectionRuns.delete(socket);
318
+ sockets.add(socket);
319
+ // Accepted sockets are transport for an active session, never a reason
320
+ // for an otherwise finished foreground SDK/CLI process to stay alive.
321
+ socket.unref?.();
322
+ handleConnection(socket);
323
+ });
324
+
325
+ try {
326
+ await listen(server, transport, socketPath);
327
+ } catch (error) {
328
+ if (ownsSocketDir && socketDir) {
329
+ try { rmSync(socketDir, { recursive: true, force: true }); } catch { /* best effort */ }
330
+ }
331
+ throw error;
332
+ }
333
+ if (transport === "unix" && socketPath) {
334
+ try { chmodSync(socketPath, 0o600); } catch { /* best effort */ }
335
+ } else {
336
+ const address = server.address();
337
+ if (address && typeof address === "object") endpoint = `tcp://127.0.0.1:${address.port}`;
338
+ }
339
+ // Unref only after the listen promise has resolved. The bridge still serves
340
+ // while the foreground session has work; it must not hold a finished
341
+ // process open, and v1 has no unattended model daemon.
342
+ server.unref?.();
343
+ logger({ event: "listen", ok: true });
344
+ const frozenLimits = Object.freeze(limits);
345
+
346
+ function registerRun(registration: OperationRunRegistration): OperationRunHandle {
347
+ assertOpen();
348
+ if (!registration || typeof registration !== "object") throw new Error("registration is required");
349
+ if (runs.has(registration.runId)) throw new Error(`Run ${registration.runId} is already registered`);
350
+ if (!registration.runId || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(registration.runId)) {
351
+ throw new Error("runId is invalid");
352
+ }
353
+ if (!registration.conversationId || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(registration.conversationId)) {
354
+ throw new Error("conversationId is invalid");
355
+ }
356
+ if (!registration.workspace || typeof registration.workspace !== "string") throw new Error("workspace is required");
357
+ const requestedWorkspace = resolve(registration.workspace);
358
+ if (!existsSync(requestedWorkspace) || !statSync(requestedWorkspace).isDirectory()) {
359
+ throw new Error(`workspace does not exist or is not a directory: ${requestedWorkspace}`);
360
+ }
361
+ const workspace = realpathSync.native(requestedWorkspace);
362
+ if (!registration.authorityReference || typeof registration.authorityReference !== "string") {
363
+ throw new Error("authorityReference is required");
364
+ }
365
+ if (typeof registration.ownership !== "function") throw new Error("ownership callback is required");
366
+ const capabilities = normalizeCapabilities(registration.capabilities);
367
+ const sourceTools = registration.tools && registration.tools.length
368
+ ? registration.tools
369
+ : descriptorsForCapabilities(capabilities);
370
+ const tools = normalizeToolDescriptors(sourceTools, capabilities);
371
+ for (const tool of tools) {
372
+ const support = validateJsonSchemaSupport(tool.parameters);
373
+ if (!support.ok) {
374
+ throw new OperationBridgeError(
375
+ "invalid-request",
376
+ `${tool.name} schema: ${support.path}: ${support.message}`,
377
+ );
378
+ }
379
+ }
380
+ validateHandlers(registration.handlers, tools, capabilities);
381
+ const initialToken = registration.token ?? tokenFactory();
382
+ validateToken(initialToken);
383
+ const descriptor = createBridgeDescriptor(
384
+ registration.runId,
385
+ registration.conversationId,
386
+ tools,
387
+ capabilities,
388
+ frozenLimits,
389
+ );
390
+ const frozen: FrozenRegistration = Object.freeze({
391
+ runId: registration.runId,
392
+ conversationId: registration.conversationId,
393
+ workspace,
394
+ authorityReference: registration.authorityReference,
395
+ capabilities,
396
+ tools,
397
+ ownership: registration.ownership,
398
+ ...(registration.checkpointEvidenceValidator
399
+ ? { checkpointEvidenceValidator: registration.checkpointEvidenceValidator }
400
+ : {}),
401
+ handlers: Object.freeze({ ...registration.handlers }),
402
+ descriptor,
403
+ });
404
+ runs.set(registration.runId, {
405
+ registration: frozen,
406
+ tokenHash: hashOperationBridgeToken(initialToken),
407
+ tokenGeneration: 1,
408
+ staleTokenHashes: new Set(),
409
+ revoked: false,
410
+ inFlight: 0,
411
+ idempotency: new Map(),
412
+ consumedLaunchKeys: new Map(),
413
+ launchClaims: new Map(),
414
+ issuedWaits: new Map(),
415
+ sockets: new Set(),
416
+ });
417
+ logger({ event: "register", runId: registration.runId, ok: true });
418
+ return Object.freeze({ runId: registration.runId, token: initialToken, descriptor });
419
+ }
420
+
421
+ function markWaitIssued(runId: string, waitId: string, generation: number): void {
422
+ assertOpen();
423
+ const run = requireRun(runId);
424
+ if (run.revoked) throw new Error(`Run ${runId} is revoked`);
425
+ if (!waitId || typeof waitId !== "string" || !Number.isSafeInteger(generation) || generation < 1) {
426
+ throw new Error("waitId and a positive generation are required");
427
+ }
428
+ const existing = run.issuedWaits.get(waitId);
429
+ if (existing && existing.generation !== generation) {
430
+ throw new Error(`wait ${waitId} is already issued at generation ${existing.generation}`);
431
+ }
432
+ run.issuedWaits.set(waitId, {
433
+ generation,
434
+ requestId: existing?.requestId ?? "parent-reconciled",
435
+ checkpointed: existing?.checkpointed ?? false,
436
+ });
437
+ }
438
+
439
+ function rotateRunToken(runId: string): string {
440
+ assertOpen();
441
+ const run = requireRun(runId);
442
+ if (run.revoked) throw new Error(`Run ${runId} is revoked`);
443
+ const next = tokenFactory();
444
+ validateToken(next);
445
+ run.staleTokenHashes.add(tokenHashKey(run.tokenHash));
446
+ run.tokenHash = hashOperationBridgeToken(next);
447
+ run.tokenGeneration += 1;
448
+ logger({ event: "rotate", runId, ok: true });
449
+ return next;
450
+ }
451
+
452
+ function revokeRun(runId: string, reason = "run revoked by the parent"): void {
453
+ const run = runs.get(runId);
454
+ if (!run) return;
455
+ if (run.revoked) return;
456
+ run.revoked = true;
457
+ run.revokedReason = reason;
458
+ run.staleTokenHashes.add(tokenHashKey(run.tokenHash));
459
+ run.tokenHash = Buffer.alloc(0);
460
+ run.idempotency.clear();
461
+ run.consumedLaunchKeys.clear();
462
+ run.launchClaims.clear();
463
+ run.issuedWaits.clear();
464
+ logger({ event: "revoke", runId, ok: true });
465
+ // Keep live connections so the next request can receive a structured
466
+ // `run-revoked` refusal. No handler is reachable after this point.
467
+ }
468
+
469
+ function unregisterRun(runId: string): void {
470
+ revokeRun(runId, "run unregistered");
471
+ runs.delete(runId);
472
+ }
473
+
474
+ function getRun(runId: string): OperationRunInfo | undefined {
475
+ const run = runs.get(runId);
476
+ if (!run) return undefined;
477
+ return Object.freeze({
478
+ runId: run.registration.runId,
479
+ conversationId: run.registration.conversationId,
480
+ workspace: run.registration.workspace,
481
+ authorityReference: run.registration.authorityReference,
482
+ capabilities: run.registration.capabilities,
483
+ descriptor: run.registration.descriptor,
484
+ tokenGeneration: run.tokenGeneration,
485
+ revoked: run.revoked,
486
+ ...(run.revokedReason ? { revokedReason: run.revokedReason } : {}),
487
+ inFlight: run.inFlight,
488
+ issuedWaitIds: Object.freeze([...run.issuedWaits.keys()]),
489
+ });
490
+ }
491
+
492
+ function assertOpen(): void {
493
+ if (closing) throw new OperationBridgeError("closed", "operation bridge is closed");
494
+ }
495
+
496
+ function requireRun(runId: string): RunState {
497
+ const run = runs.get(runId);
498
+ if (!run) throw new OperationBridgeError("run-unknown", "run is not registered");
499
+ return run;
500
+ }
501
+
502
+ function handleConnection(socket: Socket): void {
503
+ connectionRuns.set(socket, "");
504
+ const state: ConnectionState = { buffer: Buffer.alloc(0), authFailures: 0, closed: false };
505
+ let idleTimer: NodeJS.Timeout | undefined;
506
+ let queue = Promise.resolve();
507
+ const resetIdle = () => {
508
+ if (idleTimer) clearTimeout(idleTimer);
509
+ idleTimer = setTimeout(() => socket.destroy(), state.handshake ? idleTimeoutMs : handshakeTimeoutMs);
510
+ idleTimer.unref?.();
511
+ };
512
+ resetIdle();
513
+ socket.setNoDelay?.(true);
514
+ socket.on("data", (chunk: Buffer) => {
515
+ if (state.closed) return;
516
+ resetIdle();
517
+ state.buffer = Buffer.concat([state.buffer, chunk]);
518
+ if (state.buffer.length > limits.maxRequestBytes && state.buffer.indexOf(10) < 0) {
519
+ queue = queue.then(() => {
520
+ sendError(socket, "", {
521
+ code: "request-too-large",
522
+ message: `request exceeds ${limits.maxRequestBytes} bytes`,
523
+ });
524
+ socket.end();
525
+ });
526
+ return;
527
+ }
528
+ let newline = state.buffer.indexOf(10);
529
+ while (newline >= 0) {
530
+ const line = state.buffer.subarray(0, newline);
531
+ state.buffer = state.buffer.subarray(newline + 1);
532
+ if (line.length > limits.maxRequestBytes) {
533
+ queue = queue.then(() => {
534
+ sendError(socket, "", {
535
+ code: "request-too-large",
536
+ message: `request exceeds ${limits.maxRequestBytes} bytes`,
537
+ });
538
+ socket.end();
539
+ });
540
+ } else if (line.length > 0) {
541
+ const text = line.toString("utf8");
542
+ queue = queue.then(() => handleLine(text, socket, state));
543
+ }
544
+ newline = state.buffer.indexOf(10);
545
+ }
546
+ });
547
+ socket.on("error", () => { state.closed = true; if (idleTimer) clearTimeout(idleTimer); });
548
+ socket.on("close", () => {
549
+ state.closed = true;
550
+ if (idleTimer) clearTimeout(idleTimer);
551
+ const runId = connectionRuns.get(socket);
552
+ connectionRuns.delete(socket);
553
+ sockets.delete(socket);
554
+ if (runId) runs.get(runId)?.sockets.delete(socket);
555
+ });
556
+ }
557
+
558
+ async function handleLine(text: string, socket: Socket, state: ConnectionState): Promise<void> {
559
+ if (state.closed) return;
560
+ let parsed: unknown;
561
+ try {
562
+ parsed = JSON.parse(text);
563
+ } catch {
564
+ sendError(socket, "", { code: "invalid-json", message: "request is not valid JSON" });
565
+ return;
566
+ }
567
+ const envelopeResult = validateRequestEnvelope(parsed);
568
+ if (!envelopeResult.ok) {
569
+ sendError(socket, envelopeResult.id, {
570
+ code: envelopeResult.message === "invalid token shape" ? "invalid-token" : "invalid-request",
571
+ message: envelopeResult.message,
572
+ });
573
+ logger({ event: "reject", requestId: envelopeResult.id || undefined, code: "invalid-request" });
574
+ return;
575
+ }
576
+ const envelope = envelopeResult.envelope;
577
+ let run: RunState;
578
+ try {
579
+ run = authenticate(envelope);
580
+ } catch (error) {
581
+ state.authFailures += 1;
582
+ const body = operationBridgeErrorBody(error, envelope.token);
583
+ sendError(socket, envelope.id, body);
584
+ logger({ event: "reject", runId: envelope.runId, method: envelope.method, requestId: envelope.id, code: body.code });
585
+ if (state.authFailures >= 5) socket.destroy();
586
+ return;
587
+ }
588
+ const runId = run.registration.runId;
589
+ connectionRuns.set(socket, runId);
590
+ run.sockets.add(socket);
591
+
592
+ if (envelope.conversationId !== run.registration.conversationId) {
593
+ sendError(socket, envelope.id, {
594
+ code: "conversation-mismatch",
595
+ message: "request conversation does not match the registered run",
596
+ });
597
+ logger({ event: "reject", runId, method: envelope.method, requestId: envelope.id, code: "conversation-mismatch" });
598
+ return;
599
+ }
600
+
601
+ if (envelope.method === "handshake") {
602
+ const params = validateHandshakeParams(envelope.params);
603
+ if (!params.ok) {
604
+ sendError(socket, envelope.id, { code: "invalid-request", message: params.message });
605
+ return;
606
+ }
607
+ state.handshake = { runId, conversationId: run.registration.conversationId, tokenGeneration: run.tokenGeneration };
608
+ sendResult(socket, envelope.id, run.registration.descriptor);
609
+ logger({ event: "request", runId, method: envelope.method, requestId: envelope.id, ok: true });
610
+ return;
611
+ }
612
+
613
+ if (envelope.method === "ping") {
614
+ sendResult(socket, envelope.id, {
615
+ bridgeVersion: OPERATION_BRIDGE_VERSION,
616
+ runId,
617
+ conversationId: run.registration.conversationId,
618
+ tokenGeneration: run.tokenGeneration,
619
+ });
620
+ logger({ event: "request", runId, method: envelope.method, requestId: envelope.id, ok: true });
621
+ return;
622
+ }
623
+
624
+ if (!state.handshake || state.handshake.runId !== runId ||
625
+ state.handshake.conversationId !== run.registration.conversationId) {
626
+ sendError(socket, envelope.id, {
627
+ code: "handshake-required",
628
+ message: "a compatible handshake is required before this method",
629
+ });
630
+ logger({ event: "reject", runId, method: envelope.method, requestId: envelope.id, code: "handshake-required" });
631
+ return;
632
+ }
633
+
634
+ if (envelope.method === "close") {
635
+ sendResult(socket, envelope.id, { closed: true });
636
+ socket.end();
637
+ return;
638
+ }
639
+
640
+ const contextBase = makeContext(run, envelope, new AbortController().signal);
641
+ try {
642
+ if (envelope.method === "checkpoint") {
643
+ await handleCheckpoint(run, envelope, contextBase, socket);
644
+ return;
645
+ }
646
+ if (envelope.method === "park_failed") {
647
+ await handleParkFailed(run, envelope, contextBase, socket);
648
+ return;
649
+ }
650
+ await handleTool(run, envelope, socket);
651
+ } catch (error) {
652
+ const body = operationBridgeErrorBody(error, envelope.token);
653
+ sendError(socket, envelope.id, body);
654
+ logger({ event: "reject", runId, method: envelope.method, requestId: envelope.id, code: body.code });
655
+ }
656
+ }
657
+
658
+ function authenticate(envelope: OperationBridgeRequestEnvelope): RunState {
659
+ const run = runs.get(envelope.runId);
660
+ if (!run) throw new OperationBridgeError("run-unknown", "run is not registered");
661
+ if (run.revoked) throw new OperationBridgeError("run-revoked", "run has been revoked");
662
+ const presented = hashOperationBridgeToken(envelope.token);
663
+ if (run.tokenHash.length === presented.length && timingSafeEqual(run.tokenHash, presented)) return run;
664
+ if (run.staleTokenHashes.has(tokenHashKey(presented))) {
665
+ throw new OperationBridgeError("stale-token", "token was rotated or revoked", false);
666
+ }
667
+ throw new OperationBridgeError("invalid-token", "invalid bearer token", false);
668
+ }
669
+
670
+ function makeContext(run: RunState, envelope: OperationBridgeRequestEnvelope, signal: AbortSignal): OperationRequestContext {
671
+ return {
672
+ runId: run.registration.runId,
673
+ conversationId: run.registration.conversationId,
674
+ cwd: run.registration.workspace,
675
+ authorityReference: run.registration.authorityReference,
676
+ requestId: envelope.id,
677
+ tool: envelope.method,
678
+ tokenGeneration: run.tokenGeneration,
679
+ receivedAt: now(),
680
+ signal,
681
+ bridgeEnvironmentKeys: OPERATION_BRIDGE_ENV_KEYS,
682
+ };
683
+ }
684
+
685
+ async function handleTool(run: RunState, envelope: OperationBridgeRequestEnvelope, socket: Socket): Promise<void> {
686
+ const tool = envelope.method;
687
+ const descriptor = run.registration.tools.find((entry) => entry.name === tool);
688
+ if (!descriptor) {
689
+ sendError(socket, envelope.id, { code: "unsupported-tool", message: `${tool} is not enabled for this run` });
690
+ logger({ event: "reject", runId: run.registration.runId, method: tool, requestId: envelope.id, code: "unsupported-tool" });
691
+ return;
692
+ }
693
+ const handler = run.registration.handlers[tool as keyof OperationRunHandlers];
694
+ if (typeof handler !== "function") {
695
+ sendError(socket, envelope.id, { code: "unsupported-tool", message: `${tool} has no handler` });
696
+ return;
697
+ }
698
+ const params = (envelope.params ?? {}) as JsonRecord;
699
+ if (findSecretField(params)) {
700
+ sendError(socket, envelope.id, { code: "authority-field", message: "request contains a credential-shaped field" });
701
+ return;
702
+ }
703
+ const bridgeEnvironmentField = findBridgeEnvironmentKey(params);
704
+ if (bridgeEnvironmentField) {
705
+ sendError(socket, envelope.id, {
706
+ code: "bridge-env-leak",
707
+ message: `${bridgeEnvironmentField} is a parent bridge credential and cannot be passed to a launched task`,
708
+ });
709
+ logger({ event: "reject", runId: run.registration.runId, method: tool, requestId: envelope.id, code: "bridge-env-leak" });
710
+ return;
711
+ }
712
+ const authorityField = findAuthorityField(params);
713
+ if (authorityField) {
714
+ sendError(socket, envelope.id, {
715
+ code: "authority-field",
716
+ message: `caller field ${authorityField} would override parent authority`,
717
+ });
718
+ logger({ event: "reject", runId: run.registration.runId, method: tool, requestId: envelope.id, code: "authority-field" });
719
+ return;
720
+ }
721
+ const schema = validateJsonSchema(descriptor.parameters, params);
722
+ if (!schema.ok) {
723
+ sendError(socket, envelope.id, {
724
+ code: "schema-invalid",
725
+ message: `${schema.path}: ${schema.message}`,
726
+ });
727
+ return;
728
+ }
729
+ if (params.cwd !== undefined) {
730
+ if (typeof params.cwd !== "string" || !params.cwd) {
731
+ sendError(socket, envelope.id, { code: "cwd-invalid", message: "cwd must be a non-empty string" });
732
+ return;
733
+ }
734
+ const candidate = resolve(run.registration.workspace, params.cwd);
735
+ let resolvedCwd: string;
736
+ try {
737
+ resolvedCwd = realpathSync.native(candidate);
738
+ if (!statSync(resolvedCwd).isDirectory()) throw new Error("not a directory");
739
+ } catch {
740
+ sendError(socket, envelope.id, {
741
+ code: "cwd-invalid",
742
+ message: "cwd does not resolve to an existing directory",
743
+ });
744
+ return;
745
+ }
746
+ if (!isInsideWorkspace(run.registration.workspace, resolvedCwd)) {
747
+ sendError(socket, envelope.id, {
748
+ code: "cwd-outside",
749
+ message: "cwd is outside the registered worker workspace",
750
+ });
751
+ logger({ event: "reject", runId: run.registration.runId, method: tool, requestId: envelope.id, code: "cwd-outside" });
752
+ return;
753
+ }
754
+ }
755
+
756
+ const launch = isLaunchTool(tool, params);
757
+ const idempotencyKey = launch ? envelope.key : undefined;
758
+ if (launch && !idempotencyKey) {
759
+ sendError(socket, envelope.id, {
760
+ code: "idempotency-key-required",
761
+ message: "launch requests require an idempotency key",
762
+ });
763
+ return;
764
+ }
765
+ const fingerprint = launch ? createHash("sha256")
766
+ .update(canonicalJson({ tool, params }), "utf8")
767
+ .digest("hex") : undefined;
768
+ if (idempotencyKey && fingerprint) {
769
+ const cached = run.idempotency.get(idempotencyKey);
770
+ if (cached) {
771
+ if (cached.fingerprint !== fingerprint) {
772
+ sendError(socket, envelope.id, {
773
+ code: "idempotency-conflict",
774
+ message: "idempotency key was already used with different launch parameters",
775
+ });
776
+ return;
777
+ }
778
+ sendResult(socket, envelope.id, cloneJson(cached.result));
779
+ logger({ event: "request", runId: run.registration.runId, method: tool, requestId: envelope.id, ok: true });
780
+ return;
781
+ }
782
+ const consumed = run.consumedLaunchKeys.get(idempotencyKey);
783
+ if (consumed) {
784
+ if (consumed !== fingerprint) {
785
+ sendError(socket, envelope.id, {
786
+ code: "idempotency-conflict",
787
+ message: "idempotency key was already consumed with different launch parameters",
788
+ });
789
+ return;
790
+ }
791
+ // The launch completed, but its result was evicted. Never run it
792
+ // again; the caller must reconcile the existing operation.
793
+ sendError(socket, envelope.id, {
794
+ code: "idempotency-evicted",
795
+ message: "this launch already completed and its cached result was evicted; reconcile instead of retrying",
796
+ });
797
+ logger({ event: "reject", runId: run.registration.runId, method: tool, requestId: envelope.id, code: "idempotency-evicted" });
798
+ return;
799
+ }
800
+ }
801
+
802
+ let launchClaim: LaunchClaim | undefined;
803
+ if (idempotencyKey && fingerprint) {
804
+ const existing = run.launchClaims.get(idempotencyKey);
805
+ if (existing) {
806
+ if (existing.fingerprint !== fingerprint) {
807
+ sendError(socket, envelope.id, {
808
+ code: "idempotency-conflict",
809
+ message: "idempotency key was already used with different launch parameters",
810
+ });
811
+ return;
812
+ }
813
+ sendError(socket, envelope.id, existing.state === "unknown" ? {
814
+ code: "launch-outcome-unknown",
815
+ message: "the earlier launch may have started but its outcome is unknown; reconcile before retrying",
816
+ } : {
817
+ code: "launch-in-progress",
818
+ message: "the same launch is already in progress; reuse its result instead of starting another",
819
+ retryable: true,
820
+ });
821
+ return;
822
+ }
823
+ launchClaim = { fingerprint, state: "running" };
824
+ run.launchClaims.set(idempotencyKey, launchClaim);
825
+ }
826
+
827
+ if (run.inFlight >= maxInflightPerRun) {
828
+ if (idempotencyKey) run.launchClaims.delete(idempotencyKey);
829
+ sendError(socket, envelope.id, {
830
+ code: "too-many-requests",
831
+ message: "too many in-flight requests for this run",
832
+ retryable: true,
833
+ });
834
+ return;
835
+ }
836
+
837
+ const controller = new AbortController();
838
+ const context = makeContext(run, envelope, controller.signal);
839
+ run.inFlight += 1;
840
+ let timeout: NodeJS.Timeout | undefined;
841
+ try {
842
+ const taskIds = extractTaskIds(tool, params);
843
+ for (const taskId of taskIds) {
844
+ if (!isValidTaskId(taskId)) {
845
+ sendError(socket, envelope.id, { code: "task-invalid", message: "invalid task id" });
846
+ return;
847
+ }
848
+ if (!(await ownedTask(run, taskId, context))) {
849
+ sendError(socket, envelope.id, {
850
+ code: "foreign-task",
851
+ message: `task ${taskId} is not owned by this conversation`,
852
+ });
853
+ logger({ event: "reject", runId: run.registration.runId, method: tool, requestId: envelope.id, code: "foreign-task" });
854
+ return;
855
+ }
856
+ }
857
+ const timed = new Promise<never>((_, reject) => {
858
+ timeout = setTimeout(() => {
859
+ controller.abort();
860
+ reject(new OperationBridgeError(
861
+ "handler-timeout",
862
+ `handler did not complete within ${limits.requestTimeoutMs} ms`,
863
+ true,
864
+ ));
865
+ }, limits.requestTimeoutMs);
866
+ timeout.unref?.();
867
+ });
868
+ const result = await Promise.race([Promise.resolve(handler(params, context)), timed]);
869
+ if (findSecretField(result)) {
870
+ throw new OperationBridgeError("secret-in-result", "handler result contains a credential-shaped field");
871
+ }
872
+ const resultEnvironmentField = findBridgeEnvironmentKey(result);
873
+ if (resultEnvironmentField) {
874
+ throw new OperationBridgeError("bridge-env-leak", `handler result contains bridge credential ${resultEnvironmentField}`);
875
+ }
876
+ const cloned = cloneJson(result);
877
+ // Every tool result is checked before any side effect (wait
878
+ // registration, idempotency cache, or send). A read or wait handler
879
+ // must not be able to return a foreign task the requested id did not
880
+ // authorize.
881
+ const resultTaskIds = extractResultTaskIds(cloned);
882
+ for (const taskId of resultTaskIds) {
883
+ if (!isValidTaskId(taskId)) {
884
+ throw new OperationBridgeError("foreign-result-task", "handler returned an invalid task id");
885
+ }
886
+ if (!(await ownedTask(run, taskId, context))) {
887
+ throw new OperationBridgeError("foreign-result-task", `handler returned foreign task ${taskId}`);
888
+ }
889
+ }
890
+ if (tool === "wait_for_operations") {
891
+ const wait = normalizeWaitForOperationsResult(cloned);
892
+ if (!wait.ok) throw new OperationBridgeError("response-invalid", wait.message);
893
+ if (wait.result.park && !wait.result.settled) {
894
+ run.issuedWaits.set(wait.result.waitId, {
895
+ generation: wait.result.generation,
896
+ requestId: envelope.id,
897
+ checkpointed: false,
898
+ });
899
+ }
900
+ }
901
+ if (idempotencyKey && fingerprint) {
902
+ if (run.idempotency.size >= maxIdempotencyEntriesPerRun) {
903
+ const oldest = run.idempotency.keys().next();
904
+ if (!oldest.done) run.idempotency.delete(oldest.value);
905
+ }
906
+ run.idempotency.set(idempotencyKey, { fingerprint, result: cloneJson(cloned) });
907
+ run.consumedLaunchKeys.set(idempotencyKey, fingerprint);
908
+ run.launchClaims.delete(idempotencyKey);
909
+ }
910
+ sendResult(socket, envelope.id, cloned);
911
+ logger({ event: "request", runId: run.registration.runId, method: tool, requestId: envelope.id, ok: true });
912
+ } catch (error) {
913
+ const body = operationBridgeErrorBody(error, envelope.token);
914
+ if (idempotencyKey && launchClaim) {
915
+ // A timeout is ambiguous: the handler may already have launched.
916
+ // Keep the claim so a transport replay cannot start a second one.
917
+ if (body.code === "handler-timeout") launchClaim.state = "unknown";
918
+ else run.launchClaims.delete(idempotencyKey);
919
+ }
920
+ sendError(socket, envelope.id, body);
921
+ logger({ event: "reject", runId: run.registration.runId, method: tool, requestId: envelope.id, code: body.code });
922
+ } finally {
923
+ if (timeout) clearTimeout(timeout);
924
+ if (idempotencyKey && launchClaim?.state === "running") run.launchClaims.delete(idempotencyKey);
925
+ run.inFlight = Math.max(0, run.inFlight - 1);
926
+ }
927
+ }
928
+
929
+ async function handleCheckpoint(
930
+ run: RunState,
931
+ envelope: OperationBridgeRequestEnvelope,
932
+ context: OperationRequestContext,
933
+ socket: Socket,
934
+ ): Promise<void> {
935
+ const params = validateCheckpointParams(envelope.params);
936
+ if (!params.ok) {
937
+ sendError(socket, envelope.id, { code: "checkpoint-invalid", message: params.message });
938
+ return;
939
+ }
940
+ const waitId = params.value.wait_id;
941
+ const generation = params.value.generation;
942
+ const issued = typeof waitId === "string" ? run.issuedWaits.get(waitId) : undefined;
943
+ if (!issued || issued.generation !== generation) {
944
+ sendError(socket, envelope.id, {
945
+ code: "unknown-wait",
946
+ message: "checkpoint does not name a wait generation issued to this run",
947
+ });
948
+ return;
949
+ }
950
+ const evidence = params.value.evidence as JsonRecord;
951
+ if (evidence.waitId !== waitId || evidence.generation !== generation ||
952
+ evidence.toolCallId !== params.value.tool_call_id) {
953
+ sendError(socket, envelope.id, {
954
+ code: "checkpoint-invalid",
955
+ message: "checkpoint evidence does not match the wait identity",
956
+ });
957
+ return;
958
+ }
959
+ if (run.registration.checkpointEvidenceValidator) {
960
+ let accepted = false;
961
+ try {
962
+ accepted = (await run.registration.checkpointEvidenceValidator(evidence, context)) === true;
963
+ } catch {
964
+ accepted = false;
965
+ }
966
+ if (!accepted) {
967
+ sendError(socket, envelope.id, {
968
+ code: "checkpoint-invalid",
969
+ message: "the parent rejected the checkpoint evidence",
970
+ });
971
+ return;
972
+ }
973
+ }
974
+ const handler = run.registration.handlers.checkpoint;
975
+ if (typeof handler !== "function") {
976
+ sendError(socket, envelope.id, { code: "unsupported", message: "this run cannot record checkpoints" });
977
+ return;
978
+ }
979
+ try {
980
+ const result = cloneJson(await invokeCheckpointHandler(handler, params.value, context));
981
+ if (findSecretField(result)) {
982
+ throw new OperationBridgeError("secret-in-result", "checkpoint result contains a credential-shaped field");
983
+ }
984
+ issued.checkpointed = true;
985
+ sendResult(socket, envelope.id, result);
986
+ logger({ event: "checkpoint", runId: run.registration.runId, requestId: envelope.id, ok: true });
987
+ } catch (error) {
988
+ const body = operationBridgeErrorBody(error, envelope.token);
989
+ sendError(socket, envelope.id, body);
990
+ logger({ event: "reject", runId: run.registration.runId, method: "checkpoint", requestId: envelope.id, code: body.code });
991
+ }
992
+ }
993
+
994
+ async function handleParkFailed(
995
+ run: RunState,
996
+ envelope: OperationBridgeRequestEnvelope,
997
+ context: OperationRequestContext,
998
+ socket: Socket,
999
+ ): Promise<void> {
1000
+ const params = validateParkFailedParams(envelope.params);
1001
+ if (!params.ok) {
1002
+ sendError(socket, envelope.id, { code: "checkpoint-invalid", message: params.message });
1003
+ return;
1004
+ }
1005
+ const waitId = params.value.wait_id;
1006
+ const generation = params.value.generation;
1007
+ const issued = typeof waitId === "string" ? run.issuedWaits.get(waitId) : undefined;
1008
+ if (!issued || issued.generation !== generation) {
1009
+ sendError(socket, envelope.id, {
1010
+ code: "unknown-wait",
1011
+ message: "park failure does not name a wait generation issued to this run",
1012
+ });
1013
+ return;
1014
+ }
1015
+ const handler = run.registration.handlers.park_failed;
1016
+ if (typeof handler !== "function") {
1017
+ // A failed park is still explicit: the child has been told it may not
1018
+ // shut down. The parent log is the fallback when no handler is wired.
1019
+ sendError(socket, envelope.id, { code: "unsupported", message: "this run cannot record park failures" });
1020
+ return;
1021
+ }
1022
+ try {
1023
+ const result = cloneJson(await invokeCheckpointHandler(handler, params.value, context));
1024
+ sendResult(socket, envelope.id, result);
1025
+ logger({ event: "park-failed", runId: run.registration.runId, requestId: envelope.id, ok: true });
1026
+ } catch (error) {
1027
+ const body = operationBridgeErrorBody(error, envelope.token);
1028
+ sendError(socket, envelope.id, body);
1029
+ logger({ event: "reject", runId: run.registration.runId, method: "park_failed", requestId: envelope.id, code: body.code });
1030
+ }
1031
+ }
1032
+
1033
+ async function invokeCheckpointHandler(
1034
+ handler: OperationCheckpointHandler,
1035
+ params: JsonRecord,
1036
+ context: OperationRequestContext,
1037
+ ): Promise<unknown> {
1038
+ let timeout: NodeJS.Timeout | undefined;
1039
+ try {
1040
+ return await Promise.race([
1041
+ Promise.resolve(handler(params, context)),
1042
+ new Promise<never>((_, reject) => {
1043
+ timeout = setTimeout(() => {
1044
+ reject(new OperationBridgeError("handler-timeout", "checkpoint handler timed out", true));
1045
+ }, limits.requestTimeoutMs);
1046
+ timeout.unref?.();
1047
+ }),
1048
+ ]);
1049
+ } finally {
1050
+ if (timeout) clearTimeout(timeout);
1051
+ }
1052
+ }
1053
+
1054
+ async function ownedTask(run: RunState, taskId: string, context: OperationRequestContext): Promise<boolean> {
1055
+ try {
1056
+ return (await run.registration.ownership(taskId, context)) === true;
1057
+ } catch (error) {
1058
+ throw new OperationBridgeError(
1059
+ "ownership-error",
1060
+ `ownership check failed: ${redactSecret(error instanceof Error ? error.message : String(error))}`,
1061
+ );
1062
+ }
1063
+ }
1064
+
1065
+ function sendResult(socket: Socket, id: string, result: unknown): void {
1066
+ send(socket, { v: OPERATION_BRIDGE_VERSION, id, ok: true, result });
1067
+ }
1068
+
1069
+ function sendError(socket: Socket, id: string, error: OperationBridgeErrorBody): void {
1070
+ send(socket, { v: OPERATION_BRIDGE_VERSION, id, ok: false, error });
1071
+ }
1072
+
1073
+ function send(socket: Socket, response: OperationBridgeResponse): void {
1074
+ if (socket.destroyed || !socket.writable) return;
1075
+ let encoded = JSON.stringify(response);
1076
+ if (Buffer.byteLength(encoded) > limits.maxResponseBytes) {
1077
+ encoded = JSON.stringify({
1078
+ v: OPERATION_BRIDGE_VERSION,
1079
+ id: response.id,
1080
+ ok: false,
1081
+ error: {
1082
+ code: "response-too-large",
1083
+ message: `response exceeds ${limits.maxResponseBytes} bytes`,
1084
+ },
1085
+ } satisfies OperationBridgeResponse);
1086
+ }
1087
+ socket.write(`${encoded}\n`);
1088
+ }
1089
+
1090
+ function close(): Promise<void> {
1091
+ if (closePromise) return closePromise;
1092
+ closing = true;
1093
+ for (const socket of sockets) socket.destroy();
1094
+ sockets.clear();
1095
+ for (const run of runs.values()) {
1096
+ run.sockets.clear();
1097
+ }
1098
+ closePromise = new Promise<void>((resolveClose) => {
1099
+ server.close(() => resolveClose());
1100
+ }).then(() => {
1101
+ if (socketPath) {
1102
+ try { if (existsSync(socketPath)) unlinkSync(socketPath); } catch { /* best effort */ }
1103
+ }
1104
+ if (ownsSocketDir && socketDir) {
1105
+ try { rmSync(socketDir, { recursive: true, force: true }); } catch { /* best effort */ }
1106
+ }
1107
+ logger({ event: "close", ok: true });
1108
+ });
1109
+ return closePromise;
1110
+ }
1111
+
1112
+ return Object.freeze({
1113
+ endpoint,
1114
+ transport,
1115
+ limits: frozenLimits,
1116
+ registerRun,
1117
+ markWaitIssued,
1118
+ rotateRunToken,
1119
+ revokeRun,
1120
+ unregisterRun,
1121
+ getRun,
1122
+ close,
1123
+ });
1124
+ }
1125
+
1126
+ function positiveInteger(value: number | undefined, fallback: number, name: string): number {
1127
+ if (value === undefined) return fallback;
1128
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`);
1129
+ return value;
1130
+ }
1131
+
1132
+ function normalizeCapabilities(value: OperationBridgeCapabilities): OperationBridgeCapabilities {
1133
+ if (!value || typeof value !== "object") throw new Error("capabilities are required");
1134
+ const background = value.background;
1135
+ if (!background || typeof background !== "object") throw new Error("capabilities.background is required");
1136
+ const booleans = ["spawn", "watch", "status", "log"] as const;
1137
+ for (const key of booleans) {
1138
+ if (typeof background[key] !== "boolean") throw new Error(`capabilities.background.${key} must be boolean`);
1139
+ }
1140
+ for (const key of ["wait", "acknowledge", "parking"] as const) {
1141
+ if (typeof value[key] !== "boolean") throw new Error(`capabilities.${key} must be boolean`);
1142
+ }
1143
+ return Object.freeze({
1144
+ background: Object.freeze({
1145
+ spawn: background.spawn,
1146
+ watch: background.watch,
1147
+ status: background.status,
1148
+ log: background.log,
1149
+ }),
1150
+ wait: value.wait,
1151
+ acknowledge: value.acknowledge,
1152
+ parking: value.parking,
1153
+ });
1154
+ }
1155
+
1156
+ function validateHandlers(
1157
+ handlers: OperationRunHandlers,
1158
+ tools: readonly OperationToolDescriptor[],
1159
+ capabilities: OperationBridgeCapabilities,
1160
+ ): void {
1161
+ if (!handlers || typeof handlers !== "object") throw new Error("handlers are required");
1162
+ for (const tool of tools) {
1163
+ if (typeof handlers[tool.name as keyof OperationRunHandlers] !== "function") {
1164
+ throw new Error(`${tool.name} requires a handler`);
1165
+ }
1166
+ }
1167
+ if (capabilities.parking) {
1168
+ if (typeof handlers.checkpoint !== "function") throw new Error("parking requires a checkpoint handler");
1169
+ if (typeof handlers.park_failed !== "function") throw new Error("parking requires a park_failed handler");
1170
+ }
1171
+ }
1172
+
1173
+ function validateToken(token: string): void {
1174
+ if (typeof token !== "string" || token.length < 32 || token.length > 512 || /[\r\n]/.test(token)) {
1175
+ throw new Error("operation bridge token must be 32-512 characters without newlines");
1176
+ }
1177
+ }
1178
+
1179
+ function tokenHashKey(hash: Buffer): string {
1180
+ return hash.toString("hex");
1181
+ }
1182
+
1183
+ /** Keeps the Unix socket under the platform path limit even when TMPDIR is deeply nested. */
1184
+ function createDefaultSocketDir(): string {
1185
+ const candidates = [tmpdir(), "/tmp", "/var/tmp"];
1186
+ let lastError: unknown;
1187
+ for (const base of candidates) {
1188
+ try {
1189
+ const dir = mkdtempSync(join(base, "pi-op-bridge-"));
1190
+ if (Buffer.byteLength(join(dir, "operations.sock")) <= UNIX_PATH_LIMIT) return dir;
1191
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
1192
+ } catch (error) {
1193
+ lastError = error;
1194
+ }
1195
+ }
1196
+ throw new Error(`cannot create a short Unix socket directory: ${lastError instanceof Error ? lastError.message : "no candidate"}`);
1197
+ }
1198
+
1199
+ function removeStaleSocket(path: string): void {
1200
+ if (!existsSync(path)) return;
1201
+ try {
1202
+ const stat = lstatSync(path);
1203
+ if (stat.isSocket()) unlinkSync(path);
1204
+ else throw new Error(`refusing to replace a non-socket path: ${path}`);
1205
+ } catch (error) {
1206
+ if (error instanceof Error && error.message.startsWith("refusing")) throw error;
1207
+ throw new Error(`cannot prepare Unix socket path ${path}`);
1208
+ }
1209
+ }
1210
+
1211
+ function listen(server: Server, transport: "unix" | "tcp", socketPath: string | undefined): Promise<void> {
1212
+ return new Promise((resolveListen, rejectListen) => {
1213
+ const onError = (error: Error) => {
1214
+ server.off("listening", onListening);
1215
+ rejectListen(error);
1216
+ };
1217
+ const onListening = () => {
1218
+ server.off("error", onError);
1219
+ resolveListen();
1220
+ };
1221
+ server.once("error", onError);
1222
+ server.once("listening", onListening);
1223
+ if (transport === "unix") server.listen(socketPath);
1224
+ else server.listen(0, "127.0.0.1");
1225
+ });
1226
+ }