pi-better-subagents 0.26.2 → 0.27.1

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,1109 @@
1
+ /**
2
+ * Child-side operation bridge.
3
+ *
4
+ * The child receives an endpoint and a per-run token from the parent through
5
+ * its environment. It exposes only the tools named by the parent's handshake
6
+ * descriptor and forwards each call to the trusted parent host. It loads no
7
+ * background runner, task registry or shell-spawn path of its own, so a worker
8
+ * cannot widen execution by importing this module.
9
+ *
10
+ * Parking is deliberately fail-closed. A `wait_for_operations` result that asks
11
+ * the worker to park is not enough to exit: after the tool result is part of the
12
+ * saved native conversation, `completePendingPark` verifies that durable
13
+ * checkpoint, records it with the host, and only then calls the public SDK's
14
+ * `ctx.shutdown()`. If any step cannot be proven, the child reports a park
15
+ * failure and keeps running; it never simulates a successful park.
16
+ */
17
+ import { randomBytes } from "node:crypto";
18
+ import { readFileSync, realpathSync } from "node:fs";
19
+ import { connect, type Socket } from "node:net";
20
+ import * as piSdk from "@earendil-works/pi-coding-agent";
21
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
22
+ import { captureParkCheckpoint, type ParkCheckpoint } from "./park-checkpoint.ts";
23
+ import {
24
+ ACKNOWLEDGE_OPERATION_TOOL,
25
+ OPERATION_BRIDGE_ENV_KEYS,
26
+ OPERATION_BRIDGE_TOOL_NAMES,
27
+ OPERATION_BRIDGE_VERSION,
28
+ OPERATIONS_ATTEMPT_ID_ENV,
29
+ OPERATIONS_CHILD_ID_ENV,
30
+ OPERATIONS_CONVERSATION_ID_ENV,
31
+ OPERATIONS_ENABLED_ENV,
32
+ OPERATIONS_ENDPOINT_ENV,
33
+ OPERATIONS_RUN_ID_ENV,
34
+ OPERATIONS_TOKEN_ENV,
35
+ OPERATIONS_WRITER_LEASE_ID_ENV,
36
+ WAIT_OPERATIONS_TOOL,
37
+ OperationBridgeError,
38
+ OperationToolError,
39
+ type JsonRecord,
40
+ type NormalizedWaitResult,
41
+ type OperationBridgeCapabilities,
42
+ type OperationBridgeDescriptor,
43
+ type OperationBridgeErrorCode,
44
+ type OperationBridgeLimits,
45
+ type OperationBridgeMethod,
46
+ type OperationToolDescriptor,
47
+ type OperationBridgeToolName,
48
+ cloneJson,
49
+ deepFreeze,
50
+ descriptorFingerprint,
51
+ findBridgeEnvironmentKey,
52
+ isLaunchTool,
53
+ normalizeWaitForOperationsResult,
54
+ parseBridgeEndpoint,
55
+ validateJsonSchemaSupport,
56
+ redactSecret,
57
+ } from "./operation-bridge-types.ts";
58
+
59
+ // ---- configuration ---------------------------------------------------------
60
+
61
+ export interface ChildOperationBridgeConfig {
62
+ endpoint: string;
63
+ token: string;
64
+ runId: string;
65
+ conversationId: string;
66
+ attemptId?: string;
67
+ writerLeaseId?: string;
68
+ childId?: string;
69
+ requestTimeoutMs?: number;
70
+ }
71
+
72
+ export type ChildOperationBridgeConfigResult =
73
+ | { status: "disabled"; reason: string }
74
+ | { status: "invalid"; reason: string }
75
+ | { status: "ready"; config: ChildOperationBridgeConfig };
76
+
77
+ const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/;
78
+
79
+ /** Namespace access keeps an older SDK without a VERSION export from failing at import time. */
80
+ const PI_CODING_AGENT_VERSION = (piSdk as { VERSION?: string }).VERSION;
81
+
82
+ /** First SDK line with the public `terminate` tool-result boundary used for parking. */
83
+ export const MIN_PARKING_SDK_VERSION = "0.82.1";
84
+
85
+ export function supportsParkingBoundary(version: string | undefined = PI_CODING_AGENT_VERSION): boolean {
86
+ if (typeof version !== "string") return false;
87
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version.trim());
88
+ if (!match) return false;
89
+ const [major, minor, patch] = match.slice(1).map(Number);
90
+ const minimum = [0, 82, 1];
91
+ for (let index = 0; index < minimum.length; index += 1) {
92
+ const actual = [major, minor, patch][index]!;
93
+ if (actual > minimum[index]!) return true;
94
+ if (actual < minimum[index]!) return false;
95
+ }
96
+ return true;
97
+ }
98
+
99
+ /** Reads the parent-provided child environment without touching any other session source. */
100
+ export function readChildOperationBridgeConfig(env: NodeJS.ProcessEnv = process.env): ChildOperationBridgeConfigResult {
101
+ const required = [
102
+ OPERATIONS_ENDPOINT_ENV,
103
+ OPERATIONS_TOKEN_ENV,
104
+ OPERATIONS_RUN_ID_ENV,
105
+ OPERATIONS_CONVERSATION_ID_ENV,
106
+ ];
107
+ if (env[OPERATIONS_ENABLED_ENV] === "0" || env[OPERATIONS_ENABLED_ENV] === "false") {
108
+ return { status: "disabled", reason: "parent disabled the operation bridge for this run" };
109
+ }
110
+ const explicitlyEnabled = env[OPERATIONS_ENABLED_ENV] === "1" || env[OPERATIONS_ENABLED_ENV] === "true";
111
+ const present = required.filter((key) => typeof env[key] === "string" && env[key]!.length > 0);
112
+ if (!explicitlyEnabled && present.length === 0) {
113
+ return { status: "disabled", reason: "no parent operation bridge environment" };
114
+ }
115
+ if (present.length !== required.length) {
116
+ return { status: "invalid", reason: "operation bridge environment is incomplete" };
117
+ }
118
+ const endpoint = env[OPERATIONS_ENDPOINT_ENV]!;
119
+ const token = env[OPERATIONS_TOKEN_ENV]!;
120
+ const runId = env[OPERATIONS_RUN_ID_ENV]!;
121
+ const conversationId = env[OPERATIONS_CONVERSATION_ID_ENV]!;
122
+ try {
123
+ parseBridgeEndpoint(endpoint);
124
+ } catch {
125
+ return { status: "invalid", reason: "operation bridge endpoint is not a supported local endpoint" };
126
+ }
127
+ if (token.length < 32 || token.length > 512 || /[\r\n]/.test(token)) {
128
+ return { status: "invalid", reason: "operation bridge token has an invalid shape" };
129
+ }
130
+ if (!ID_PATTERN.test(runId) || !ID_PATTERN.test(conversationId)) {
131
+ return { status: "invalid", reason: "operation bridge run identity is invalid" };
132
+ }
133
+ return {
134
+ status: "ready",
135
+ config: {
136
+ endpoint,
137
+ token,
138
+ runId,
139
+ conversationId,
140
+ ...(env[OPERATIONS_ATTEMPT_ID_ENV] ? { attemptId: env[OPERATIONS_ATTEMPT_ID_ENV]! } : {}),
141
+ ...(env[OPERATIONS_WRITER_LEASE_ID_ENV] ? { writerLeaseId: env[OPERATIONS_WRITER_LEASE_ID_ENV]! } : {}),
142
+ ...(env[OPERATIONS_CHILD_ID_ENV] ? { childId: env[OPERATIONS_CHILD_ID_ENV]! } : {}),
143
+ },
144
+ };
145
+ }
146
+
147
+ // ---- transport client ------------------------------------------------------
148
+
149
+ interface PendingRequest {
150
+ id: string;
151
+ method: OperationBridgeMethod;
152
+ resolve(value: unknown): void;
153
+ reject(error: Error): void;
154
+ timer?: NodeJS.Timeout;
155
+ removeAbort?: () => void;
156
+ }
157
+
158
+ export interface OperationBridgeClientOptions {
159
+ requestTimeoutMs?: number;
160
+ handshakeTimeoutMs?: number;
161
+ maxResponseBytes?: number;
162
+ clientName?: string;
163
+ clientVersion?: string;
164
+ }
165
+
166
+ export interface OperationBridgeClient {
167
+ readonly endpoint: string;
168
+ readonly config: Readonly<ChildOperationBridgeConfig>;
169
+ readonly descriptor: OperationBridgeDescriptor | undefined;
170
+ handshake(): Promise<OperationBridgeDescriptor>;
171
+ request(
172
+ method: OperationBridgeMethod,
173
+ params: JsonRecord,
174
+ options?: { timeoutMs?: number; signal?: AbortSignal; idempotencyKey?: string },
175
+ ): Promise<unknown>;
176
+ close(): Promise<void>;
177
+ }
178
+
179
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
180
+ const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;
181
+ const DEFAULT_MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
182
+
183
+ export function createOperationBridgeClient(
184
+ config: ChildOperationBridgeConfig,
185
+ options: OperationBridgeClientOptions = {},
186
+ ): OperationBridgeClient {
187
+ const endpoint = parseBridgeEndpoint(config.endpoint);
188
+ const requestTimeoutMs = positive(options.requestTimeoutMs ?? config.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);
189
+ const handshakeTimeoutMs = positive(options.handshakeTimeoutMs, DEFAULT_HANDSHAKE_TIMEOUT_MS);
190
+ const maxResponseBytes = positive(options.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES);
191
+ const client = {
192
+ name: options.clientName ?? "pi-better-subagents-child",
193
+ version: options.clientVersion ?? "1",
194
+ };
195
+ let socket: Socket | undefined;
196
+ let buffer = Buffer.alloc(0);
197
+ let connectPromise: Promise<Socket> | undefined;
198
+ let connectionHandshaked = false;
199
+ let closed = false;
200
+ let descriptor: OperationBridgeDescriptor | undefined;
201
+ const pending = new Map<string, PendingRequest>();
202
+
203
+ const clientApi: OperationBridgeClient = {
204
+ endpoint: config.endpoint,
205
+ config: Object.freeze({ ...config }),
206
+ get descriptor() { return descriptor; },
207
+ handshake,
208
+ request,
209
+ close,
210
+ };
211
+ return clientApi;
212
+
213
+ async function handshake(): Promise<OperationBridgeDescriptor> {
214
+ const raw = await sendOnce("handshake", {
215
+ bridge_version: OPERATION_BRIDGE_VERSION,
216
+ client,
217
+ }, undefined, { timeoutMs: handshakeTimeoutMs });
218
+ const verified = verifyDescriptor(raw, config);
219
+ descriptor = verified;
220
+ connectionHandshaked = true;
221
+ return verified;
222
+ }
223
+
224
+ async function request(
225
+ method: OperationBridgeMethod,
226
+ params: JsonRecord,
227
+ requestOptions: { timeoutMs?: number; signal?: AbortSignal; idempotencyKey?: string } = {},
228
+ ): Promise<unknown> {
229
+ if (closed) throw new OperationBridgeError("closed", "operation bridge client is closed");
230
+ if (method === "handshake") return await handshake();
231
+ const launch = isLaunchTool(method, params);
232
+ const idempotencyKey = launch ? (requestOptions.idempotencyKey ?? randomBytes(18).toString("hex")) : undefined;
233
+ let retried = false;
234
+ for (;;) {
235
+ try {
236
+ if (!connectionHandshaked) await handshake();
237
+ return await sendOnce(method, params, idempotencyKey, requestOptions);
238
+ } catch (error) {
239
+ // Only a transport interruption is retried. A handler timeout can
240
+ // mean the parent already started the operation, so retrying it
241
+ // without an authoritative launch claim could duplicate work.
242
+ const retry = !retried && idempotencyKey && error instanceof OperationBridgeError &&
243
+ error.code === "closed";
244
+ if (!retry) throw error;
245
+ retried = true;
246
+ socket?.destroy();
247
+ socket = undefined;
248
+ connectPromise = undefined;
249
+ connectionHandshaked = false;
250
+ buffer = Buffer.alloc(0);
251
+ }
252
+ }
253
+ }
254
+
255
+ async function sendOnce(
256
+ method: OperationBridgeMethod,
257
+ params: JsonRecord,
258
+ idempotencyKey: string | undefined,
259
+ requestOptions: { timeoutMs?: number; signal?: AbortSignal },
260
+ ): Promise<unknown> {
261
+ const connection = await ensureConnected();
262
+ if (requestOptions.signal?.aborted) throw new OperationBridgeError("closed", "operation bridge request was aborted");
263
+ const id = randomBytes(12).toString("hex");
264
+ const envelope = {
265
+ v: OPERATION_BRIDGE_VERSION,
266
+ id,
267
+ token: config.token,
268
+ runId: config.runId,
269
+ conversationId: config.conversationId,
270
+ method,
271
+ params,
272
+ ...(idempotencyKey ? { key: idempotencyKey } : {}),
273
+ };
274
+ const encoded = `${JSON.stringify(envelope)}\n`;
275
+ return await new Promise<unknown>((resolveRequest, rejectRequest) => {
276
+ const entry: PendingRequest = {
277
+ id,
278
+ method,
279
+ resolve: resolveRequest,
280
+ reject: rejectRequest,
281
+ };
282
+ pending.set(id, entry);
283
+ const timeoutMs = positive(requestOptions.timeoutMs ?? requestTimeoutMs, requestTimeoutMs);
284
+ entry.timer = setTimeout(() => {
285
+ if (!pending.delete(id)) return;
286
+ entry.removeAbort?.();
287
+ rejectRequest(new OperationBridgeError("handler-timeout", `operation bridge request timed out after ${timeoutMs} ms`, true));
288
+ }, timeoutMs);
289
+ entry.timer.unref?.();
290
+ if (requestOptions.signal) {
291
+ const onAbort = () => {
292
+ if (!pending.delete(id)) return;
293
+ if (entry.timer) clearTimeout(entry.timer);
294
+ rejectRequest(new OperationBridgeError("closed", "operation bridge request was aborted"));
295
+ };
296
+ requestOptions.signal.addEventListener("abort", onAbort, { once: true });
297
+ entry.removeAbort = () => requestOptions.signal!.removeEventListener("abort", onAbort);
298
+ }
299
+ connection.write(encoded, (error) => {
300
+ if (!error) return;
301
+ if (!pending.delete(id)) return;
302
+ if (entry.timer) clearTimeout(entry.timer);
303
+ entry.removeAbort?.();
304
+ rejectRequest(new OperationBridgeError("closed", "operation bridge connection failed", true));
305
+ });
306
+ });
307
+ }
308
+
309
+ async function ensureConnected(): Promise<Socket> {
310
+ if (closed) throw new OperationBridgeError("closed", "operation bridge client is closed");
311
+ if (socket && !socket.destroyed && socket.readyState === "open" && !socket.readableEnded && !socket.writableEnded) {
312
+ return socket;
313
+ }
314
+ if (connectPromise) return connectPromise;
315
+ connectPromise = new Promise<Socket>((resolveConnect, rejectConnect) => {
316
+ const next = endpoint.kind === "unix"
317
+ ? connect({ path: endpoint.path })
318
+ : connect({ host: endpoint.host, port: endpoint.port });
319
+ let settled = false;
320
+ const fail = (message: string) => {
321
+ if (!settled) {
322
+ settled = true;
323
+ rejectConnect(new OperationBridgeError("closed", message, true));
324
+ }
325
+ rejectAllPending(new OperationBridgeError("closed", message, true));
326
+ };
327
+ next.once("connect", () => {
328
+ settled = true;
329
+ socket = next;
330
+ connectionHandshaked = false;
331
+ resolveConnect(next);
332
+ });
333
+ next.on("data", (chunk: Buffer) => {
334
+ buffer = Buffer.concat([buffer, chunk]);
335
+ if (buffer.length > maxResponseBytes && buffer.indexOf(10) < 0) {
336
+ fail("operation bridge response exceeded the response size limit");
337
+ next.destroy();
338
+ return;
339
+ }
340
+ let newline = buffer.indexOf(10);
341
+ while (newline >= 0) {
342
+ const line = buffer.subarray(0, newline);
343
+ buffer = buffer.subarray(newline + 1);
344
+ if (line.length <= maxResponseBytes) handleLine(line.toString("utf8"));
345
+ newline = buffer.indexOf(10);
346
+ }
347
+ });
348
+ next.on("error", (error: Error) => {
349
+ fail(`operation bridge connection error: ${redactSecret(error.message)}`);
350
+ });
351
+ next.on("close", () => {
352
+ socket = undefined;
353
+ connectPromise = undefined;
354
+ connectionHandshaked = false;
355
+ if (!settled) {
356
+ settled = true;
357
+ rejectConnect(new OperationBridgeError("closed", "operation bridge connection closed", true));
358
+ }
359
+ rejectAllPending(new OperationBridgeError("closed", "operation bridge connection closed", true));
360
+ });
361
+ }).finally(() => {
362
+ if (!socket || socket.destroyed) connectPromise = undefined;
363
+ });
364
+ return connectPromise;
365
+ }
366
+
367
+ function handleLine(line: string): void {
368
+ let parsed: unknown;
369
+ try {
370
+ parsed = JSON.parse(line);
371
+ } catch {
372
+ rejectAllPending(new OperationBridgeError("invalid-json", "operation bridge returned malformed JSON"));
373
+ return;
374
+ }
375
+ if (!parsed || typeof parsed !== "object") {
376
+ rejectAllPending(new OperationBridgeError("invalid-request", "operation bridge returned a malformed response"));
377
+ return;
378
+ }
379
+ const response = parsed as {
380
+ v?: unknown; id?: unknown; ok?: unknown; result?: unknown;
381
+ error?: { code?: unknown; message?: unknown; retryable?: unknown };
382
+ };
383
+ if (response.v !== OPERATION_BRIDGE_VERSION || typeof response.id !== "string") {
384
+ rejectAllPending(new OperationBridgeError("invalid-request", "operation bridge response has no compatible version or id"));
385
+ return;
386
+ }
387
+ if (response.id === "" && response.ok !== true) {
388
+ const code = typeof response.error?.code === "string" ? response.error.code : "handler-error";
389
+ const message = typeof response.error?.message === "string" ? response.error.message : "operation bridge request failed";
390
+ rejectAllPending(new OperationBridgeError(code as OperationBridgeErrorCode, redactSecret(message), response.error?.retryable === true));
391
+ // The host answers framing failures without a request id, then may
392
+ // close the connection. Never reuse that half-closed socket for the
393
+ // next call; reconnect and handshake first.
394
+ socket?.destroy();
395
+ socket = undefined;
396
+ connectPromise = undefined;
397
+ connectionHandshaked = false;
398
+ return;
399
+ }
400
+ const request = pending.get(response.id);
401
+ if (!request) return;
402
+ pending.delete(response.id);
403
+ if (request.timer) clearTimeout(request.timer);
404
+ request.removeAbort?.();
405
+ if (response.ok === true) {
406
+ request.resolve(response.result);
407
+ return;
408
+ }
409
+ const code = typeof response.error?.code === "string" ? response.error.code : "handler-error";
410
+ const message = typeof response.error?.message === "string" ? response.error.message : "operation bridge request failed";
411
+ request.reject(new OperationBridgeError(code as OperationBridgeErrorCode, redactSecret(message), response.error?.retryable === true));
412
+ }
413
+
414
+ function rejectAllPending(error: Error): void {
415
+ for (const [id, request] of pending) {
416
+ pending.delete(id);
417
+ if (request.timer) clearTimeout(request.timer);
418
+ request.removeAbort?.();
419
+ request.reject(error);
420
+ }
421
+ }
422
+
423
+ async function close(): Promise<void> {
424
+ if (closed) return;
425
+ closed = true;
426
+ rejectAllPending(new OperationBridgeError("closed", "operation bridge client closed"));
427
+ const current = socket;
428
+ socket = undefined;
429
+ connectPromise = undefined;
430
+ connectionHandshaked = false;
431
+ if (current && !current.destroyed) {
432
+ await new Promise<void>((resolveClose) => {
433
+ current.once("close", () => resolveClose());
434
+ current.end(() => {
435
+ current.destroy();
436
+ resolveClose();
437
+ });
438
+ });
439
+ }
440
+ }
441
+ }
442
+
443
+ function positive(value: number | undefined, fallback: number): number {
444
+ if (value === undefined) return fallback;
445
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error("operation bridge timeout must be a positive integer");
446
+ return value;
447
+ }
448
+
449
+ /** Rejects an endpoint that tries to add tools or change the advertised contract. */
450
+ export function verifyDescriptor(value: unknown, config: Pick<ChildOperationBridgeConfig, "runId" | "conversationId">): OperationBridgeDescriptor {
451
+ if (!value || typeof value !== "object") throw new OperationBridgeError("invalid-request", "parent handshake is not an object");
452
+ const record = value as Record<string, unknown>;
453
+ if (record.bridgeVersion !== OPERATION_BRIDGE_VERSION) {
454
+ throw new OperationBridgeError("invalid-request", "parent bridge version is incompatible");
455
+ }
456
+ if (record.runId !== config.runId || record.conversationId !== config.conversationId) {
457
+ throw new OperationBridgeError("invalid-request", "parent handshake identity does not match this child run");
458
+ }
459
+ if (!Array.isArray(record.tools) || record.tools.length === 0) {
460
+ throw new OperationBridgeError("invalid-request", "parent handshake has no tools");
461
+ }
462
+ const tools: OperationToolDescriptor[] = [];
463
+ const seen = new Set<string>();
464
+ for (const rawTool of record.tools) {
465
+ if (!rawTool || typeof rawTool !== "object") throw new OperationBridgeError("invalid-request", "parent handshake tool is malformed");
466
+ const tool = rawTool as Record<string, unknown>;
467
+ if (typeof tool.name !== "string" || !OPERATION_BRIDGE_TOOL_NAMES.includes(tool.name as OperationBridgeToolName)) {
468
+ throw new OperationBridgeError("invalid-request", "parent handshake named a tool outside the bridge allowlist");
469
+ }
470
+ if (seen.has(tool.name)) throw new OperationBridgeError("invalid-request", "parent handshake repeated a tool");
471
+ seen.add(tool.name);
472
+ if (typeof tool.label !== "string" || typeof tool.description !== "string" ||
473
+ !tool.parameters || typeof tool.parameters !== "object" || Array.isArray(tool.parameters)) {
474
+ throw new OperationBridgeError("invalid-request", `parent handshake tool ${tool.name} is malformed`);
475
+ }
476
+ const support = validateJsonSchemaSupport(tool.parameters);
477
+ if (!support.ok) {
478
+ throw new OperationBridgeError("invalid-request", `parent handshake tool ${tool.name} schema: ${support.message}`);
479
+ }
480
+ tools.push(deepFreeze({
481
+ name: tool.name as OperationToolDescriptor["name"],
482
+ label: tool.label,
483
+ description: tool.description,
484
+ parameters: cloneJson(tool.parameters) as JsonRecord,
485
+ ...(Array.isArray(tool.promptGuidelines) ? { promptGuidelines: tool.promptGuidelines.filter((entry): entry is string => typeof entry === "string") } : {}),
486
+ ...(typeof tool.promptSnippet === "string" ? { promptSnippet: tool.promptSnippet } : {}),
487
+ }));
488
+ }
489
+ const capabilities = validateCapabilities(record.capabilities);
490
+ if (seen.has(WAIT_OPERATIONS_TOOL) && !(capabilities.wait && capabilities.parking)) {
491
+ throw new OperationBridgeError("invalid-request", "parent exposed wait_for_operations without a parking capability");
492
+ }
493
+ const expectedFingerprint = descriptorFingerprint(tools, capabilities);
494
+ if (record.fingerprint !== expectedFingerprint) {
495
+ throw new OperationBridgeError("invalid-request", "parent handshake fingerprint does not match its tools");
496
+ }
497
+ return deepFreeze({
498
+ bridgeVersion: OPERATION_BRIDGE_VERSION,
499
+ fingerprint: expectedFingerprint,
500
+ runId: config.runId,
501
+ conversationId: config.conversationId,
502
+ tools,
503
+ capabilities,
504
+ limits: validateLimits(record.limits),
505
+ });
506
+ }
507
+
508
+ function validateCapabilities(value: unknown): OperationBridgeCapabilities {
509
+ if (!value || typeof value !== "object") throw new OperationBridgeError("invalid-request", "parent handshake has no capabilities");
510
+ const record = value as Record<string, unknown>;
511
+ const background = record.background;
512
+ if (!background || typeof background !== "object") throw new OperationBridgeError("invalid-request", "parent handshake has no background capabilities");
513
+ const bg = background as Record<string, unknown>;
514
+ for (const key of ["spawn", "watch", "status", "log"] as const) {
515
+ if (typeof bg[key] !== "boolean") throw new OperationBridgeError("invalid-request", `parent capability background.${key} is invalid`);
516
+ }
517
+ for (const key of ["wait", "acknowledge", "parking"] as const) {
518
+ if (typeof record[key] !== "boolean") throw new OperationBridgeError("invalid-request", `parent capability ${key} is invalid`);
519
+ }
520
+ return Object.freeze({
521
+ background: Object.freeze({
522
+ spawn: bg.spawn as boolean,
523
+ watch: bg.watch as boolean,
524
+ status: bg.status as boolean,
525
+ log: bg.log as boolean,
526
+ }),
527
+ wait: record.wait as boolean,
528
+ acknowledge: record.acknowledge as boolean,
529
+ parking: record.parking as boolean,
530
+ });
531
+ }
532
+
533
+ function validateLimits(value: unknown): OperationBridgeLimits {
534
+ if (!value || typeof value !== "object") throw new OperationBridgeError("invalid-request", "parent handshake has no limits");
535
+ const record = value as Record<string, unknown>;
536
+ for (const key of ["maxRequestBytes", "maxResponseBytes", "requestTimeoutMs"] as const) {
537
+ if (typeof record[key] !== "number" || !Number.isSafeInteger(record[key]) || (record[key] as number) < 1) {
538
+ throw new OperationBridgeError("invalid-request", `parent limit ${key} is invalid`);
539
+ }
540
+ }
541
+ return Object.freeze({
542
+ maxRequestBytes: record.maxRequestBytes as number,
543
+ maxResponseBytes: record.maxResponseBytes as number,
544
+ requestTimeoutMs: record.requestTimeoutMs as number,
545
+ });
546
+ }
547
+
548
+ // ---- parking and checkpoint certification ----------------------------------
549
+
550
+ /** Same evidence shape as the parent's park-checkpoint helper. */
551
+ export type OperationCheckpointEvidence = ParkCheckpoint;
552
+
553
+ /** Parent policy hook for the trusted native-session path. */
554
+ export type SessionFileValidator = (realSessionFile: string) => boolean;
555
+
556
+ export interface PendingParkRequest {
557
+ waitId: string;
558
+ generation: number;
559
+ toolCallId: string;
560
+ marker: string;
561
+ taskIds: string[];
562
+ continuationNote?: string;
563
+ result: NormalizedWaitResult;
564
+ }
565
+
566
+ export type CheckpointVerification =
567
+ | { certified: true; evidence: OperationCheckpointEvidence }
568
+ | { certified: false; reason: string };
569
+
570
+ export interface CheckpointSessionContext {
571
+ sessionManager: {
572
+ getEntries(): readonly unknown[];
573
+ getSessionId(): string;
574
+ getSessionFile(): string | undefined;
575
+ };
576
+ shutdown(): void;
577
+ }
578
+
579
+ export type CheckpointVerifier = (input: {
580
+ pending: PendingParkRequest;
581
+ ctx: CheckpointSessionContext;
582
+ sessionFileValidator?: SessionFileValidator;
583
+ }) => CheckpointVerification | Promise<CheckpointVerification>;
584
+
585
+ /**
586
+ * Default verifier: the wait result must be the last persisted conversation
587
+ * message, and the session file must contain that exact prefix. This is the same
588
+ * evidence shape the park/finalization code uses, so the parent can verify it
589
+ * again after a restart instead of trusting an in-memory flag.
590
+ */
591
+ export function verifyToolResultCheckpoint(input: {
592
+ pending: PendingParkRequest;
593
+ ctx: CheckpointSessionContext;
594
+ sessionFileValidator?: SessionFileValidator;
595
+ }): CheckpointVerification {
596
+ try {
597
+ const manager = input.ctx.sessionManager;
598
+ const sessionId = manager.getSessionId();
599
+ const sessionFile = manager.getSessionFile();
600
+ if (!sessionFile) {
601
+ return { certified: false, reason: "the native conversation is not persisted to a session file" };
602
+ }
603
+ const resolved = realpathSync.native(sessionFile);
604
+ if (input.sessionFileValidator && !input.sessionFileValidator(resolved)) {
605
+ return { certified: false, reason: "the session file is not on the trusted native-session path" };
606
+ }
607
+ // The persisted file is the authority. Reuse the parent's helper so
608
+ // tool name, error state, wait generation, call/result pairing and the
609
+ // saved prefix all come from disk, not from the in-memory view.
610
+ const proof = captureParkCheckpoint({
611
+ sessionId,
612
+ sessionFile: resolved,
613
+ toolCallId: input.pending.toolCallId,
614
+ waitId: input.pending.waitId,
615
+ generation: input.pending.generation,
616
+ });
617
+ const bytes = readFileSync(proof.sessionFile);
618
+ const records = bytes.toString("utf8").trimEnd().split("\n").map((line) => JSON.parse(line));
619
+ const persisted = records.find((entry: any) => entry?.id === proof.entryId);
620
+ if (!persisted || persisted.type !== "message" || persisted.message?.role !== "toolResult" ||
621
+ persisted.message?.toolName !== WAIT_OPERATIONS_TOOL || persisted.message?.isError === true ||
622
+ persisted.message?.toolCallId !== input.pending.toolCallId) {
623
+ return { certified: false, reason: "the persisted wait tool result has the wrong tool, call id or error state" };
624
+ }
625
+ const details = persisted.message.details;
626
+ const waitMarker = details?.operationWait as { waitId?: unknown; generation?: unknown } | undefined;
627
+ if (waitMarker?.waitId !== input.pending.waitId || waitMarker?.generation !== input.pending.generation) {
628
+ return { certified: false, reason: "the persisted wait result does not match the registered wait generation" };
629
+ }
630
+ const bridgeMarker = details?.operationBridge as { marker?: unknown } | undefined;
631
+ if (bridgeMarker?.marker !== undefined && bridgeMarker.marker !== input.pending.marker) {
632
+ return { certified: false, reason: "the persisted wait result does not match this park request" };
633
+ }
634
+ const entries = manager.getEntries() as Array<Record<string, any>>;
635
+ const memoryMessages = entries.filter((entry) => entry?.type === "message" && entry.message && typeof entry.message === "object");
636
+ const memoryLast = memoryMessages.at(-1);
637
+ if (!memoryLast || memoryLast.id !== proof.entryId || memoryLast.message?.role !== "toolResult" ||
638
+ memoryLast.message?.toolName !== WAIT_OPERATIONS_TOOL || memoryLast.message?.isError === true ||
639
+ memoryLast.message?.toolCallId !== input.pending.toolCallId) {
640
+ return { certified: false, reason: "the native session view does not match the last persisted wait result" };
641
+ }
642
+ return { certified: true, evidence: proof };
643
+ } catch (error) {
644
+ return {
645
+ certified: false,
646
+ reason: `checkpoint verification failed: ${redactSecret(error instanceof Error ? error.message : String(error))}`,
647
+ };
648
+ }
649
+ }
650
+
651
+ export interface CompletePendingParkOptions {
652
+ pending: PendingParkRequest;
653
+ ctx: CheckpointSessionContext;
654
+ client: Pick<OperationBridgeClient, "request">;
655
+ verifier?: CheckpointVerifier;
656
+ attemptId?: string;
657
+ writerLeaseId?: string;
658
+ /** Parent-owned check that the real session file is the trusted native session path. */
659
+ sessionFileValidator?: SessionFileValidator;
660
+ onDiagnostic?: (event: ChildOperationDiagnostic) => void;
661
+ }
662
+
663
+ export interface ParkCompletion {
664
+ parked: boolean;
665
+ reason?: string;
666
+ evidence?: OperationCheckpointEvidence;
667
+ checkpointRecorded?: boolean;
668
+ }
669
+
670
+ /**
671
+ * Called after `agent_settled`, when Pi has persisted the wait tool result.
672
+ * The order is fixed: certify, tell the host, then request shutdown. A failure
673
+ * before the host acknowledgement keeps the attempt alive and records why.
674
+ */
675
+ export async function completePendingPark(options: CompletePendingParkOptions): Promise<ParkCompletion> {
676
+ const verify = options.verifier ?? verifyToolResultCheckpoint;
677
+ let verification: CheckpointVerification;
678
+ try {
679
+ verification = await verify({
680
+ pending: options.pending,
681
+ ctx: options.ctx,
682
+ sessionFileValidator: options.sessionFileValidator,
683
+ });
684
+ } catch (error) {
685
+ verification = {
686
+ certified: false,
687
+ reason: `checkpoint verifier failed: ${redactSecret(error instanceof Error ? error.message : String(error))}`,
688
+ };
689
+ }
690
+ if (!verification.certified) {
691
+ await reportParkFailure(options, verification.reason);
692
+ options.onDiagnostic?.({ event: "park-failed", code: "checkpoint-uncertified", message: verification.reason });
693
+ return { parked: false, reason: verification.reason };
694
+ }
695
+ if (verification.evidence.waitId !== options.pending.waitId ||
696
+ verification.evidence.generation !== options.pending.generation ||
697
+ verification.evidence.toolCallId !== options.pending.toolCallId) {
698
+ const reason = "checkpoint evidence does not match the registered wait generation";
699
+ await reportParkFailure(options, reason);
700
+ options.onDiagnostic?.({ event: "park-failed", code: "checkpoint-mismatch", message: reason });
701
+ return { parked: false, reason };
702
+ }
703
+ const checkpointParams: JsonRecord = {
704
+ wait_id: options.pending.waitId,
705
+ generation: options.pending.generation,
706
+ tool_call_id: options.pending.toolCallId,
707
+ evidence: verification.evidence,
708
+ ...(options.attemptId ? { attempt_id: options.attemptId } : {}),
709
+ ...(options.writerLeaseId ? { writer_lease_id: options.writerLeaseId } : {}),
710
+ };
711
+ try {
712
+ await options.client.request("checkpoint", checkpointParams);
713
+ } catch (error) {
714
+ const reason = `checkpoint was not recorded by the parent: ${redactSecret(error instanceof Error ? error.message : String(error))}`;
715
+ await reportParkFailure(options, reason);
716
+ options.onDiagnostic?.({ event: "park-failed", code: "checkpoint-not-recorded", message: reason });
717
+ return { parked: false, reason };
718
+ }
719
+ try {
720
+ options.ctx.shutdown();
721
+ } catch (error) {
722
+ const reason = `clean shutdown was not accepted by the SDK: ${redactSecret(error instanceof Error ? error.message : String(error))}`;
723
+ await reportParkFailure(options, reason);
724
+ options.onDiagnostic?.({ event: "park-failed", code: "shutdown-not-accepted", message: reason });
725
+ return { parked: false, reason, evidence: verification.evidence, checkpointRecorded: true };
726
+ }
727
+ options.onDiagnostic?.({ event: "parked", code: "checkpoint-recorded" });
728
+ return { parked: true, evidence: verification.evidence, checkpointRecorded: true };
729
+ }
730
+
731
+ async function reportParkFailure(options: CompletePendingParkOptions, reason: string): Promise<void> {
732
+ try {
733
+ await options.client.request("park_failed", {
734
+ wait_id: options.pending.waitId,
735
+ generation: options.pending.generation,
736
+ reason: reason.slice(0, 2_000),
737
+ }, { timeoutMs: 5_000 });
738
+ } catch {
739
+ // The child still keeps running. A lost park-failure notice becomes a
740
+ // held/monitored record on the parent side, never a simulated park.
741
+ }
742
+ }
743
+
744
+ // ---- child extension installer --------------------------------------------
745
+
746
+ export interface ChildOperationDiagnostic {
747
+ event: "disabled" | "invalid" | "connecting" | "ready" | "handshake-failed" | "parking" | "park-failed" | "parked" | "closed" | "tool-error" | "parking-unsupported";
748
+ code?: string;
749
+ message?: string;
750
+ }
751
+
752
+ export interface InstallChildOperationBridgeOptions {
753
+ env?: NodeJS.ProcessEnv;
754
+ config?: ChildOperationBridgeConfig;
755
+ clientFactory?: (config: ChildOperationBridgeConfig) => OperationBridgeClient;
756
+ verifier?: CheckpointVerifier;
757
+ /** Parent-owned check that the real session file is the trusted native session path. */
758
+ sessionFileValidator?: SessionFileValidator;
759
+ /** Test seam; production uses the loaded SDK version. */
760
+ sdkVersion?: string;
761
+ /** Default true. Remove bridge credentials from process.env around each tool execution. */
762
+ hideBridgeEnvironmentFromTools?: boolean;
763
+ requestTimeoutMs?: number;
764
+ handshakeAttempts?: number;
765
+ handshakeRetryDelayMs?: number;
766
+ onDiagnostic?: (event: ChildOperationDiagnostic) => void;
767
+ }
768
+
769
+ export interface ChildOperationBridgeState {
770
+ status: "disabled" | "invalid" | "connecting" | "ready" | "handshake-failed" | "parking" | "parked" | "park-failed" | "closed";
771
+ descriptor?: OperationBridgeDescriptor;
772
+ pendingPark?: PendingParkRequest;
773
+ lastError?: string;
774
+ /** False when the installed SDK cannot stop before the next model request. */
775
+ parkingSupported?: boolean;
776
+ /** True while bridge credentials are removed from process.env for tool execution. */
777
+ bridgeEnvironmentHidden?: boolean;
778
+ /** How bridge credentials are kept away from command tools. */
779
+ bridgeEnvironmentIsolation?: "tool-execution" | "unavailable";
780
+ /** True when the current assistant message contains a wait plus another tool call. */
781
+ waitBatchConflict?: boolean;
782
+ }
783
+
784
+ export interface ChildOperationBridgeHandle {
785
+ getState(): ChildOperationBridgeState;
786
+ }
787
+
788
+ /**
789
+ * Parent-owned integration calls this once from a child extension loader. It
790
+ * registers no tools until a compatible parent handshake succeeds.
791
+ */
792
+ export function installChildOperationBridge(
793
+ pi: ExtensionAPI,
794
+ options: InstallChildOperationBridgeOptions = {},
795
+ ): ChildOperationBridgeHandle {
796
+ const state: ChildOperationBridgeState = {
797
+ status: "disabled",
798
+ parkingSupported: supportsParkingBoundary(options.sdkVersion ?? PI_CODING_AGENT_VERSION),
799
+ bridgeEnvironmentHidden: false,
800
+ bridgeEnvironmentIsolation: options.hideBridgeEnvironmentFromTools === false ? "unavailable" : "tool-execution",
801
+ waitBatchConflict: false,
802
+ };
803
+ let client: OperationBridgeClient | undefined;
804
+ const hiddenBridgeEnvironment = new Map<string, string | undefined>();
805
+ let activeToolExecutions = 0;
806
+ let installed = false;
807
+ let starting: Promise<void> | undefined;
808
+ let completingPark = false;
809
+ const env = options.env ?? process.env;
810
+
811
+ const handle: ChildOperationBridgeHandle = {
812
+ getState: () => ({ ...state, ...(state.descriptor ? { descriptor: state.descriptor } : {}) }),
813
+ };
814
+
815
+ function hideBridgeEnvironment(): void {
816
+ if (state.bridgeEnvironmentIsolation !== "tool-execution" || hiddenBridgeEnvironment.size > 0) return;
817
+ for (const key of OPERATION_BRIDGE_ENV_KEYS) {
818
+ if (!Object.prototype.hasOwnProperty.call(process.env, key)) continue;
819
+ hiddenBridgeEnvironment.set(key, process.env[key]);
820
+ delete process.env[key];
821
+ }
822
+ state.bridgeEnvironmentHidden = hiddenBridgeEnvironment.size > 0;
823
+ }
824
+
825
+ function restoreBridgeEnvironment(): void {
826
+ for (const [key, value] of hiddenBridgeEnvironment) {
827
+ if (value === undefined) delete process.env[key];
828
+ else process.env[key] = value;
829
+ }
830
+ hiddenBridgeEnvironment.clear();
831
+ state.bridgeEnvironmentHidden = false;
832
+ }
833
+
834
+ pi.on("tool_execution_start", () => {
835
+ activeToolExecutions += 1;
836
+ hideBridgeEnvironment();
837
+ });
838
+ pi.on("tool_execution_end", () => {
839
+ activeToolExecutions = Math.max(0, activeToolExecutions - 1);
840
+ if (activeToolExecutions === 0) restoreBridgeEnvironment();
841
+ });
842
+
843
+ pi.on("session_start", async (_event, _ctx) => {
844
+ if (installed || starting) return starting;
845
+ starting = (async () => {
846
+ const read = options.config
847
+ ? { status: "ready" as const, config: options.config }
848
+ : readChildOperationBridgeConfig(env);
849
+ if (read.status !== "ready") {
850
+ state.status = read.status === "disabled" ? "disabled" : "invalid";
851
+ state.lastError = read.reason;
852
+ options.onDiagnostic?.({ event: state.status, message: read.reason });
853
+ return;
854
+ }
855
+ state.status = "connecting";
856
+ options.onDiagnostic?.({ event: "connecting" });
857
+ const active = (options.clientFactory ?? ((config) => createOperationBridgeClient(config, {
858
+ requestTimeoutMs: options.requestTimeoutMs,
859
+ })))(read.config);
860
+ let descriptor: OperationBridgeDescriptor;
861
+ try {
862
+ descriptor = await handshakeWithRetries(active, options);
863
+ } catch (error) {
864
+ state.status = "handshake-failed";
865
+ state.lastError = redactSecret(error instanceof Error ? error.message : String(error));
866
+ options.onDiagnostic?.({ event: "handshake-failed", code: "handshake", message: state.lastError });
867
+ await active.close().catch(() => {});
868
+ return;
869
+ }
870
+ client = active;
871
+ state.descriptor = descriptor;
872
+ try {
873
+ registerTools(descriptor, state.parkingSupported === true);
874
+ } catch (error) {
875
+ state.status = "handshake-failed";
876
+ state.lastError = redactSecret(error instanceof Error ? error.message : String(error));
877
+ options.onDiagnostic?.({ event: "handshake-failed", code: "tool-registration", message: state.lastError });
878
+ client = undefined;
879
+ await active.close().catch(() => {});
880
+ return;
881
+ }
882
+ state.status = "ready";
883
+ installed = true;
884
+ options.onDiagnostic?.({ event: "ready", code: "handshake" });
885
+ })().finally(() => { starting = undefined; });
886
+ return starting;
887
+ });
888
+
889
+ pi.on("message_end", (event) => {
890
+ const message = event.message as { role?: string; content?: unknown };
891
+ if (message.role !== "assistant" || !Array.isArray(message.content)) return;
892
+ const calls = message.content.filter((part): part is { type: "toolCall"; name: string } =>
893
+ Boolean(part) && typeof part === "object" && (part as { type?: unknown }).type === "toolCall" &&
894
+ typeof (part as { name?: unknown }).name === "string");
895
+ const hasWait = calls.some((call) => call.name === WAIT_OPERATIONS_TOOL);
896
+ state.waitBatchConflict = hasWait && calls.length !== 1;
897
+ });
898
+
899
+ pi.on("tool_call", (event) => {
900
+ if (event.toolName === WAIT_OPERATIONS_TOOL && state.waitBatchConflict) {
901
+ return {
902
+ block: true,
903
+ reason: "wait_for_operations must be the only tool call in its assistant message. Retry it alone so the SDK can stop before the next model request.",
904
+ };
905
+ }
906
+ if (state.status === "parking" || state.status === "parked") {
907
+ return { block: true, reason: "This worker is committing a park request; no further tools may run." };
908
+ }
909
+ return undefined;
910
+ });
911
+
912
+ pi.on("agent_settled", async (_event, ctx) => {
913
+ const pending = state.pendingPark;
914
+ if (!pending || !client || completingPark) return;
915
+ completingPark = true;
916
+ state.status = "parking";
917
+ try {
918
+ const result = await completePendingPark({
919
+ pending,
920
+ ctx,
921
+ client,
922
+ verifier: options.verifier,
923
+ sessionFileValidator: options.sessionFileValidator,
924
+ attemptId: options.config?.attemptId ?? env[OPERATIONS_ATTEMPT_ID_ENV],
925
+ writerLeaseId: options.config?.writerLeaseId ?? env[OPERATIONS_WRITER_LEASE_ID_ENV],
926
+ onDiagnostic: options.onDiagnostic,
927
+ });
928
+ state.status = result.parked ? "parked" : "park-failed";
929
+ if (!result.parked) state.lastError = result.reason;
930
+ // A failed park is not retried in a loop. The parent receives the
931
+ // explicit failure and decides whether to hold or re-register.
932
+ state.pendingPark = undefined;
933
+ } finally {
934
+ completingPark = false;
935
+ }
936
+ });
937
+
938
+ pi.on("session_shutdown", () => {
939
+ state.status = "closed";
940
+ restoreBridgeEnvironment();
941
+ options.onDiagnostic?.({ event: "closed" });
942
+ void client?.close().catch(() => {});
943
+ });
944
+
945
+ function registerTools(descriptor: OperationBridgeDescriptor, parkingSupported: boolean): void {
946
+ for (const tool of descriptor.tools) {
947
+ if (tool.name === WAIT_OPERATIONS_TOOL && !parkingSupported) {
948
+ state.lastError = "The installed SDK cannot stop before the next model request; wait_for_operations is unavailable.";
949
+ options.onDiagnostic?.({ event: "parking-unsupported", code: "sdk-version" });
950
+ continue;
951
+ }
952
+ pi.registerTool({
953
+ name: tool.name,
954
+ label: tool.label,
955
+ description: tool.description,
956
+ parameters: tool.parameters as any,
957
+ ...(tool.promptSnippet ? { promptSnippet: tool.promptSnippet } : {}),
958
+ ...(tool.promptGuidelines ? { promptGuidelines: [...tool.promptGuidelines] } : {}),
959
+ async execute(toolCallId: string, params: unknown, signal: AbortSignal | undefined, _onUpdate: unknown, _ctx: unknown) {
960
+ try {
961
+ return await invokeTool(tool, toolCallId, params, signal);
962
+ } catch (error) {
963
+ return toolErrorResult(error);
964
+ }
965
+ },
966
+ });
967
+ }
968
+ }
969
+
970
+ async function invokeTool(
971
+ tool: OperationToolDescriptor,
972
+ toolCallId: string,
973
+ rawParams: unknown,
974
+ signal: AbortSignal | undefined,
975
+ ): Promise<{ content: Array<{ type: "text"; text: string }>; details: unknown; isError?: boolean }> {
976
+ if (!client) throw new OperationToolError("the parent operation bridge is not connected");
977
+ if (!rawParams || typeof rawParams !== "object" || Array.isArray(rawParams)) {
978
+ throw new OperationToolError("tool parameters must be an object");
979
+ }
980
+ const params = rawParams as JsonRecord;
981
+ if (isLaunchTool(tool.name, params)) {
982
+ const bridgeEnvironmentField = findBridgeEnvironmentKey(params);
983
+ if (bridgeEnvironmentField) {
984
+ throw new OperationToolError(
985
+ `refusing to pass ${bridgeEnvironmentField} to a launched task`,
986
+ "bridge-env-leak",
987
+ );
988
+ }
989
+ }
990
+ const raw = await client.request(tool.name, params, { signal });
991
+ if (tool.name === WAIT_OPERATIONS_TOOL) {
992
+ return waitToolResult(toolCallId, raw);
993
+ }
994
+ return toolResult(raw);
995
+ }
996
+
997
+ function waitToolResult(
998
+ toolCallId: string,
999
+ raw: unknown,
1000
+ ): { content: Array<{ type: "text"; text: string }>; details: unknown; isError?: boolean; terminate?: boolean } {
1001
+ const normalized = normalizeWaitForOperationsResult(raw);
1002
+ if (!normalized.ok) throw new OperationToolError(`parent returned an invalid wait result: ${normalized.message}`);
1003
+ const marker = randomBytes(16).toString("hex");
1004
+ const details = {
1005
+ ...(raw && typeof raw === "object" ? raw as JsonRecord : {}),
1006
+ operationWait: normalized.result,
1007
+ operationBridge: {
1008
+ version: OPERATION_BRIDGE_VERSION,
1009
+ marker,
1010
+ waitId: normalized.result.waitId,
1011
+ generation: normalized.result.generation,
1012
+ toolCallId,
1013
+ },
1014
+ };
1015
+ const shouldPark = normalized.result.park && !normalized.result.settled;
1016
+ if (shouldPark) {
1017
+ if (!state.descriptor?.capabilities.parking) {
1018
+ throw new OperationToolError("the parent asked this worker to park without a parking capability");
1019
+ }
1020
+ state.pendingPark = {
1021
+ waitId: normalized.result.waitId,
1022
+ generation: normalized.result.generation,
1023
+ toolCallId,
1024
+ marker,
1025
+ taskIds: normalized.result.taskIds,
1026
+ ...(normalized.result.continuationNote ? { continuationNote: normalized.result.continuationNote } : {}),
1027
+ result: normalized.result,
1028
+ };
1029
+ state.status = "parking";
1030
+ options.onDiagnostic?.({ event: "parking", code: "wait-registered" });
1031
+ }
1032
+ return {
1033
+ content: [{ type: "text", text: formatToolText(details) }],
1034
+ details,
1035
+ // AgentToolResult.terminate stops the loop only when every result in
1036
+ // the batch sets it. installChildOperationBridge therefore refuses a
1037
+ // wait that shares an assistant message with another tool call.
1038
+ ...(shouldPark ? { terminate: true } : {}),
1039
+ };
1040
+ }
1041
+
1042
+ function toolResult(raw: unknown): { content: Array<{ type: "text"; text: string }>; details: unknown } {
1043
+ const details = raw && typeof raw === "object"
1044
+ ? { ...(raw as JsonRecord) }
1045
+ : { result: raw };
1046
+ return {
1047
+ content: [{ type: "text", text: formatToolText(raw) }],
1048
+ details,
1049
+ };
1050
+ }
1051
+
1052
+ function toolErrorResult(error: unknown): { content: Array<{ type: "text"; text: string }>; details: unknown; isError: true } {
1053
+ const code = error instanceof OperationBridgeError || error instanceof OperationToolError ? error.code : "handler-error";
1054
+ const message = redactSecret(error instanceof Error ? error.message : String(error));
1055
+ options.onDiagnostic?.({ event: "tool-error", code, message });
1056
+ return {
1057
+ content: [{ type: "text", text: `operation bridge: ${message}` }],
1058
+ details: { operationBridgeError: { code, message } },
1059
+ isError: true,
1060
+ };
1061
+ }
1062
+
1063
+ return handle;
1064
+ }
1065
+
1066
+ async function handshakeWithRetries(
1067
+ client: OperationBridgeClient,
1068
+ options: InstallChildOperationBridgeOptions,
1069
+ ): Promise<OperationBridgeDescriptor> {
1070
+ const attempts = Math.max(1, Math.min(10, options.handshakeAttempts ?? 3));
1071
+ const delay = Math.max(0, Math.min(2_000, options.handshakeRetryDelayMs ?? 50));
1072
+ let lastError: unknown;
1073
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
1074
+ try {
1075
+ return await client.handshake();
1076
+ } catch (error) {
1077
+ lastError = error;
1078
+ if (attempt + 1 < attempts && delay > 0) await new Promise((resolveDelay) => setTimeout(resolveDelay, delay));
1079
+ }
1080
+ }
1081
+ throw lastError;
1082
+ }
1083
+
1084
+ function formatToolText(value: unknown): string {
1085
+ if (value && typeof value === "object" && !Array.isArray(value)) {
1086
+ const text = (value as JsonRecord).text;
1087
+ if (typeof text === "string") return text;
1088
+ }
1089
+ let encoded: string;
1090
+ try {
1091
+ encoded = JSON.stringify(value, null, 2) ?? "null";
1092
+ } catch {
1093
+ encoded = String(value);
1094
+ }
1095
+ const bytes = Buffer.byteLength(encoded);
1096
+ if (bytes > 64 * 1024) {
1097
+ return `${Buffer.from(encoded).subarray(0, 64 * 1024).toString("utf8")}\n… output truncated by the operation bridge`;
1098
+ }
1099
+ return encoded;
1100
+ }
1101
+
1102
+ export default function childOperationsExtension(pi: ExtensionAPI): void {
1103
+ installChildOperationBridge(pi);
1104
+ }
1105
+
1106
+ // Keep these exports used and available to the parent integration without
1107
+ // widening the child's execution surface.
1108
+ export { ACKNOWLEDGE_OPERATION_TOOL, WAIT_OPERATIONS_TOOL };
1109
+ export type { OperationBridgeCapabilities, OperationBridgeLimits };