@ai-sdk/harness-codex 0.0.0-cca10482-20260708215408

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,737 @@
1
+ // Long-running process that runs alongside the `codex` CLI in the sandbox.
2
+ // The generic transport — WebSocket server, token auth, single-flight
3
+ // reconnect, the in-memory event log + `seq`, resume replay, and the
4
+ // lifecycle/meta files — lives in the shared `@ai-sdk/harness/bridge` runtime.
5
+ // This file supplies only the Codex-specific turn driver.
6
+ //
7
+ // Host-defined tools are routed through an HTTP relay bound to
8
+ // `127.0.0.1:0`. The codex CLI spawns `host-tool-mcp.mjs` (shipped alongside
9
+ // this file) as a stdio MCP server; the shim POSTs each tool call to the
10
+ // relay, which emits `tool-call` to the host and waits for the matching
11
+ // `tool-result`.
12
+
13
+ import {
14
+ runBridge,
15
+ type BridgeEvent,
16
+ type BridgeTurn,
17
+ } from '@ai-sdk/harness/bridge';
18
+ import type { HarnessV1BuiltinToolName } from '@ai-sdk/harness';
19
+ import type { StartMessage } from '../codex-bridge-protocol';
20
+ import { randomUUID } from 'node:crypto';
21
+ import { mkdir, writeFile } from 'node:fs/promises';
22
+ import { createServer, type Server } from 'node:http';
23
+ // Temporary workaround for upstream codex MCP-tool bug — see ./cli-relay.ts
24
+ import {
25
+ CLI_SHIM_FILENAME,
26
+ buildCliShimScript,
27
+ parseToolRelayCommand,
28
+ } from './cli-relay';
29
+ import {
30
+ ToolRelayAuthorizer,
31
+ ToolRelayPendingCalls,
32
+ isToolRelayRequestFromAllowedProcess,
33
+ type ToolRelayCall,
34
+ } from './tool-relay-auth';
35
+ import { argv, env as procEnv, stdout } from 'node:process';
36
+
37
+ /*
38
+ * CONSTRAINT — the third-party imports below are NEVER bundled into the
39
+ * compiled `bridge/index.mjs`. They are declared `external` in
40
+ * tsup.config.ts and resolved at runtime from the node_modules that this
41
+ * bridge installs *inside the sandbox* from `src/bridge/package.json` (and
42
+ * its pinned `pnpm-lock.yaml`). That bridge package.json — NOT this host
43
+ * package — is the single source of truth for these packages and their
44
+ * versions; the published `@ai-sdk/harness-codex` package does not provide
45
+ * them at runtime.
46
+ *
47
+ * When adding or changing a third-party import here you MUST keep all three
48
+ * in sync, or the bridge will either get the dependency bundled in or fail
49
+ * to resolve it in the sandbox:
50
+ * 1. the import statement below,
51
+ * 2. the `external` array in tsup.config.ts, and
52
+ * 3. the dependency entry in `src/bridge/package.json`.
53
+ */
54
+ import * as codexSdkModule from '@openai/codex-sdk';
55
+
56
+ /*
57
+ * Native Codex tool name → cross-harness common name. Tools outside this map
58
+ * (e.g. MCP tools the model invokes by name) have no common equivalent; their
59
+ * native name is forwarded as-is on `tool-call` events.
60
+ */
61
+ const NATIVE_TO_COMMON: Readonly<Record<string, HarnessV1BuiltinToolName>> = {
62
+ shell: 'bash',
63
+ web_search: 'webSearch',
64
+ };
65
+
66
+ function toCommonName(nativeName: string): HarnessV1BuiltinToolName | string {
67
+ return NATIVE_TO_COMMON[nativeName] ?? nativeName;
68
+ }
69
+
70
+ const args = parseArgs(argv.slice(2));
71
+ const workdir = requireArg({ value: args.workdir, name: '--workdir' });
72
+ const bridgeStateDir = requireArg({
73
+ value: args.bridgeStateDir,
74
+ name: '--bridge-state-dir',
75
+ });
76
+ const cliShimDir = requireArg({
77
+ value: args.cliShimDir,
78
+ name: '--cli-shim-dir',
79
+ });
80
+ const bootstrapDir = args.bootstrapDir ?? workdir;
81
+ const HARNESS_CLIENT_APP = procEnv.AI_SDK_HARNESS_CLIENT_APP;
82
+
83
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
84
+ const codexSdk = codexSdkModule as any;
85
+
86
+ // Codex thread id — survives across turns within this bridge process and is
87
+ // returned to the host on `detach` so a future process can resume the thread.
88
+ const threadState: { id: string | undefined } = { id: undefined };
89
+
90
+ await runBridge<StartMessage>({
91
+ bridgeType: 'codex',
92
+ bridgeStateDir,
93
+ onStart: runTurn,
94
+ onDetach: () => (threadState.id ? { threadId: threadState.id } : {}),
95
+ });
96
+
97
+ type Emit = (msg: Record<string, unknown>) => void;
98
+ type ToolRelay = {
99
+ port: number;
100
+ close(): void;
101
+ authorizeToolCall(call: ToolRelayCall): void;
102
+ authorizeAnyToolCall(): void;
103
+ };
104
+
105
+ async function runTurn(start: StartMessage, turn: BridgeTurn): Promise<void> {
106
+ const emit: Emit = msg => turn.emit(msg as BridgeEvent);
107
+
108
+ // Cross-process resume: the host carries the threadId we returned on detach.
109
+ // Seed `threadState.id` so the codex SDK call below takes the `resumeThread`
110
+ // branch.
111
+ if (
112
+ typeof start.resumeThreadId === 'string' &&
113
+ start.resumeThreadId.length > 0
114
+ ) {
115
+ threadState.id = start.resumeThreadId;
116
+ }
117
+
118
+ /*
119
+ * Known limitation: codex CLI does not currently surface MCP tools to the
120
+ * model in `codex exec --experimental-json` mode (the path the
121
+ * `@openai/codex-sdk` uses). The MCP handshake completes and `tools/list`
122
+ * returns the host tool, but codex never registers it as a model-callable
123
+ * function. Built-in MCP-resource accessors (`list_mcp_resources` etc.) are
124
+ * exposed; tools are not. Tracked upstream at
125
+ * https://github.com/openai/codex/issues/19425.
126
+ *
127
+ * Until that's fixed, host tools are made available to the model via a
128
+ * separate CLI-relay workaround (see `./cli-relay.ts`). The MCP server
129
+ * config below is kept so that the day codex starts exposing MCP tools
130
+ * properly, host tools work both ways. Writing the shim here, adding matching
131
+ * prompt guidance in the host adapter, and filtering the shim command below
132
+ * implement the workaround and can be removed once the upstream bug is fixed.
133
+ */
134
+ const mcpServers: Record<string, unknown> = {};
135
+ let relay: ToolRelay | undefined;
136
+ let cliShimPath: string | undefined;
137
+ if (start.tools && start.tools.length > 0) {
138
+ cliShimPath = `${cliShimDir}/${CLI_SHIM_FILENAME}`;
139
+ relay = await startToolRelay({
140
+ allowedScriptPaths: [cliShimPath, `${bootstrapDir}/host-tool-mcp.mjs`],
141
+ tools: start.tools,
142
+ emit,
143
+ requestToolResult: turn.requestToolResult,
144
+ });
145
+ mcpServers['harness-tools'] = {
146
+ enabled: true,
147
+ command: 'node',
148
+ args: [`${bootstrapDir}/host-tool-mcp.mjs`],
149
+ env: {
150
+ TOOL_SCHEMAS: JSON.stringify(
151
+ start.tools.map(t => ({
152
+ name: t.name,
153
+ description: t.description,
154
+ inputSchema: t.inputSchema,
155
+ })),
156
+ ),
157
+ TOOL_RELAY_URL: `http://127.0.0.1:${relay.port}`,
158
+ },
159
+ };
160
+ // Temporary workaround for upstream codex MCP-tool bug — see ./cli-relay.ts
161
+ await mkdir(cliShimDir, { recursive: true });
162
+ await writeFile(
163
+ cliShimPath,
164
+ buildCliShimScript({ relayPort: relay.port }),
165
+ 'utf8',
166
+ );
167
+ }
168
+
169
+ const codexConfig: Record<string, unknown> = {};
170
+ if (Object.keys(mcpServers).length > 0) codexConfig.mcp_servers = mcpServers;
171
+
172
+ const gatewayBaseUrl = procEnv.AI_GATEWAY_BASE_URL;
173
+ const hasGatewayAuth = Boolean(procEnv.AI_GATEWAY_API_KEY || gatewayBaseUrl);
174
+ if (hasGatewayAuth && !gatewayBaseUrl) {
175
+ throw new Error(
176
+ 'AI Gateway auth was selected but AI_GATEWAY_BASE_URL is missing from the Codex bridge environment.',
177
+ );
178
+ }
179
+ const apiBaseUrl = hasGatewayAuth ? gatewayBaseUrl : procEnv.OPENAI_BASE_URL;
180
+ if (apiBaseUrl) {
181
+ codexConfig.preferred_auth_method = 'apikey';
182
+ codexConfig.model_provider = 'agent_bridge_openai';
183
+ codexConfig.model_providers = {
184
+ agent_bridge_openai: {
185
+ name: procEnv.CODEX_MODEL_PROVIDER_NAME || 'Agent Bridge OpenAI',
186
+ base_url: apiBaseUrl,
187
+ env_key: 'CODEX_API_KEY',
188
+ wire_api: 'responses',
189
+ supports_websockets: false,
190
+ ...(hasGatewayAuth && HARNESS_CLIENT_APP
191
+ ? {
192
+ http_headers: {
193
+ 'User-Agent': HARNESS_CLIENT_APP,
194
+ 'x-client-app': HARNESS_CLIENT_APP,
195
+ },
196
+ }
197
+ : {}),
198
+ },
199
+ };
200
+ }
201
+ const usesConfiguredModelProvider =
202
+ typeof codexConfig.model_provider === 'string';
203
+
204
+ const codex = new codexSdk.Codex({
205
+ ...(procEnv.CODEX_API_KEY ? { apiKey: procEnv.CODEX_API_KEY } : {}),
206
+ ...(!usesConfiguredModelProvider && apiBaseUrl
207
+ ? { baseUrl: apiBaseUrl }
208
+ : {}),
209
+ env: Object.fromEntries(
210
+ Object.entries(procEnv).filter(
211
+ (entry): entry is [string, string] => typeof entry[1] === 'string',
212
+ ),
213
+ ),
214
+ ...(Object.keys(codexConfig).length > 0 ? { config: codexConfig } : {}),
215
+ });
216
+
217
+ const threadOptions = {
218
+ ...(start.model ? { model: start.model } : {}),
219
+ sandboxMode: 'danger-full-access',
220
+ approvalPolicy: 'never',
221
+ workingDirectory: workdir,
222
+ skipGitRepoCheck: true,
223
+ ...(start.reasoningEffort
224
+ ? { modelReasoningEffort: start.reasoningEffort }
225
+ : {}),
226
+ webSearchMode: start.webSearch ? 'live' : 'disabled',
227
+ };
228
+ const thread = threadState.id
229
+ ? codex.resumeThread(threadState.id, threadOptions)
230
+ : codex.startThread(threadOptions);
231
+
232
+ emit({ type: 'stream-start' });
233
+
234
+ const userMessage = start.prompt;
235
+ let turnUsage: Record<string, unknown> | undefined;
236
+ const textByItem = new Map<string, string>();
237
+ const reasoningByItem = new Map<string, string>();
238
+
239
+ try {
240
+ const { events } = await thread.runStreamed(userMessage, {
241
+ signal: turn.abortSignal,
242
+ });
243
+ for await (const event of events as AsyncIterable<CodexEvent>) {
244
+ if (turn.abortSignal.aborted) break;
245
+ if (
246
+ event.type === 'thread.started' &&
247
+ typeof event.thread_id === 'string'
248
+ ) {
249
+ threadState.id = event.thread_id;
250
+ // Announce to the host so it can include the id in resume state.
251
+ emit({ type: 'bridge-thread', threadId: event.thread_id });
252
+ }
253
+ // Temporary workaround for upstream codex MCP-tool bug — see ./cli-relay.ts
254
+ if (cliShimPath && event.item?.type === 'command_execution') {
255
+ const relayCall =
256
+ typeof event.item.command === 'string'
257
+ ? parseToolRelayCommand({
258
+ command: event.item.command,
259
+ cliShimPath,
260
+ })
261
+ : undefined;
262
+ if (event.type === 'item.started' && relay) {
263
+ if (relayCall) {
264
+ relay.authorizeToolCall(relayCall);
265
+ } else if (typeof event.item.command !== 'string') {
266
+ relay.authorizeAnyToolCall();
267
+ }
268
+ }
269
+ if (relayCall) {
270
+ continue;
271
+ }
272
+ }
273
+ if (relay && isHostMcpToolEvent(event)) {
274
+ const relayCall = relayCallFromCodexMcpEvent(event);
275
+ if (relayCall) relay.authorizeToolCall(relayCall);
276
+ continue;
277
+ }
278
+ translateAndEmit(event, {
279
+ send: emit,
280
+ textByItem,
281
+ reasoningByItem,
282
+ setTurnUsage: u => (turnUsage = u),
283
+ });
284
+ }
285
+ } catch (err) {
286
+ emit({ type: 'error', error: serialiseError(err) });
287
+ return;
288
+ } finally {
289
+ relay?.close();
290
+ }
291
+
292
+ emit({
293
+ type: 'finish',
294
+ finishReason: { unified: 'stop', raw: 'stop' },
295
+ totalUsage: turnUsage ?? defaultUsage(),
296
+ });
297
+
298
+ void turn.pendingUserMessages; // accepted but only consumed when codex supports streamed user input
299
+ }
300
+
301
+ type CodexItem = {
302
+ type: string;
303
+ id?: string;
304
+ text?: string;
305
+ command?: string;
306
+ exit_code?: number;
307
+ aggregated_output?: string;
308
+ status?: 'in_progress' | 'completed' | 'failed';
309
+ server?: string;
310
+ tool?: string;
311
+ arguments?: unknown;
312
+ result?: { content?: unknown; structured_content?: unknown } | unknown;
313
+ error?: { message?: string };
314
+ query?: string;
315
+ message?: string;
316
+ changes?: ReadonlyArray<{
317
+ path: string;
318
+ kind: 'add' | 'delete' | 'update';
319
+ }>;
320
+ };
321
+
322
+ function extractMcpToolCallResult(item: CodexItem): unknown {
323
+ if (
324
+ item.result === undefined ||
325
+ item.result === null ||
326
+ typeof item.result !== 'object'
327
+ ) {
328
+ return item.error?.message ? { error: item.error.message } : null;
329
+ }
330
+ const result = item.result as {
331
+ content?: unknown;
332
+ structured_content?: unknown;
333
+ };
334
+ if (
335
+ result.structured_content !== undefined &&
336
+ result.structured_content !== null
337
+ ) {
338
+ return result.structured_content;
339
+ }
340
+ return result.content ?? null;
341
+ }
342
+
343
+ type CodexEvent = {
344
+ type:
345
+ | 'thread.started'
346
+ | 'turn.completed'
347
+ | 'turn.failed'
348
+ | 'error'
349
+ | 'item.started'
350
+ | 'item.updated'
351
+ | 'item.completed';
352
+ item?: CodexItem;
353
+ usage?: Record<string, number>;
354
+ error?: { message: string };
355
+ message?: string;
356
+ thread_id?: string;
357
+ };
358
+
359
+ function isHostMcpToolEvent(event: CodexEvent): boolean {
360
+ return (
361
+ event.item?.type === 'mcp_tool_call' &&
362
+ event.item.server === 'harness-tools'
363
+ );
364
+ }
365
+
366
+ function relayCallFromCodexMcpEvent(
367
+ event: CodexEvent,
368
+ ): ToolRelayCall | undefined {
369
+ if (event.type !== 'item.started') return undefined;
370
+ const toolName = event.item?.tool;
371
+ if (!toolName) return undefined;
372
+ return {
373
+ toolName,
374
+ input: event.item?.arguments ?? {},
375
+ };
376
+ }
377
+
378
+ function translateAndEmit(
379
+ event: CodexEvent,
380
+ ctx: {
381
+ send: Emit;
382
+ textByItem: Map<string, string>;
383
+ reasoningByItem: Map<string, string>;
384
+ setTurnUsage: (u: Record<string, unknown>) => void;
385
+ },
386
+ ): void {
387
+ if (event.type === 'turn.completed') {
388
+ if (event.usage) ctx.setTurnUsage(mapUsage(event.usage));
389
+ ctx.send({
390
+ type: 'finish-step',
391
+ finishReason: { unified: 'stop', raw: 'stop' },
392
+ usage: event.usage ? mapUsage(event.usage) : defaultUsage(),
393
+ });
394
+ return;
395
+ }
396
+ if (event.type === 'turn.failed') {
397
+ ctx.send({
398
+ type: 'error',
399
+ error: event.error?.message ?? 'codex turn failed',
400
+ });
401
+ return;
402
+ }
403
+ if (event.type === 'error') {
404
+ ctx.send({ type: 'error', error: event.message ?? 'codex error' });
405
+ return;
406
+ }
407
+ if (!event.item) return;
408
+ const item = event.item;
409
+ const id = item.id ?? randomUUID();
410
+
411
+ if (item.type === 'agent_message' && typeof item.text === 'string') {
412
+ /*
413
+ * The presence of `id` in `textByItem` — not the `item.started` event —
414
+ * marks the text part as opened. Codex does not guarantee an
415
+ * `item.started` event carrying text precedes the first `item.updated`
416
+ * with text, so keying the `text-start` off the event type can emit a
417
+ * `text-delta` for a part that was never opened. Opening lazily on the
418
+ * first event with text keeps `text-start` before any `text-delta`.
419
+ */
420
+ if (!ctx.textByItem.has(id)) {
421
+ ctx.send({ type: 'text-start', id });
422
+ ctx.textByItem.set(id, '');
423
+ }
424
+ const last = ctx.textByItem.get(id) ?? '';
425
+ const next = item.text;
426
+ if (next.length > last.length) {
427
+ ctx.send({ type: 'text-delta', id, delta: next.slice(last.length) });
428
+ ctx.textByItem.set(id, next);
429
+ }
430
+ if (event.type === 'item.completed') ctx.send({ type: 'text-end', id });
431
+ return;
432
+ }
433
+
434
+ if (item.type === 'reasoning' && typeof item.text === 'string') {
435
+ if (!ctx.reasoningByItem.has(id)) {
436
+ ctx.send({ type: 'reasoning-start', id });
437
+ ctx.reasoningByItem.set(id, '');
438
+ }
439
+ const last = ctx.reasoningByItem.get(id) ?? '';
440
+ const next = item.text;
441
+ if (next.length > last.length) {
442
+ ctx.send({ type: 'reasoning-delta', id, delta: next.slice(last.length) });
443
+ ctx.reasoningByItem.set(id, next);
444
+ }
445
+ if (event.type === 'item.completed')
446
+ ctx.send({ type: 'reasoning-end', id });
447
+ return;
448
+ }
449
+
450
+ if (item.type === 'command_execution') {
451
+ const nativeName = 'shell';
452
+ if (event.type === 'item.started') {
453
+ ctx.send({
454
+ type: 'tool-call',
455
+ toolCallId: id,
456
+ toolName: toCommonName(nativeName),
457
+ nativeName,
458
+ input: JSON.stringify({ command: item.command ?? '' }),
459
+ providerExecuted: true,
460
+ });
461
+ } else if (event.type === 'item.completed') {
462
+ ctx.send({
463
+ type: 'tool-result',
464
+ toolCallId: id,
465
+ toolName: toCommonName(nativeName),
466
+ result: {
467
+ exitCode: item.exit_code ?? null,
468
+ output: item.aggregated_output ?? '',
469
+ status: item.status ?? 'completed',
470
+ },
471
+ });
472
+ }
473
+ return;
474
+ }
475
+
476
+ if (item.type === 'mcp_tool_call') {
477
+ const isHostTool = item.server === 'harness-tools';
478
+ if (event.type === 'item.started') {
479
+ ctx.send({
480
+ type: 'tool-call',
481
+ toolCallId: id,
482
+ toolName: item.tool ?? 'unknown',
483
+ ...(isHostTool ? {} : { nativeName: item.tool ?? 'unknown' }),
484
+ input: JSON.stringify(item.arguments ?? {}),
485
+ providerExecuted: !isHostTool,
486
+ });
487
+ } else if (event.type === 'item.completed') {
488
+ ctx.send({
489
+ type: 'tool-result',
490
+ toolCallId: id,
491
+ toolName: item.tool ?? 'unknown',
492
+ result: extractMcpToolCallResult(item),
493
+ });
494
+ }
495
+ return;
496
+ }
497
+
498
+ if (item.type === 'web_search') {
499
+ const nativeName = 'web_search';
500
+ if (event.type === 'item.started') {
501
+ ctx.send({
502
+ type: 'tool-call',
503
+ toolCallId: id,
504
+ toolName: toCommonName(nativeName),
505
+ nativeName,
506
+ input: JSON.stringify({ query: item.query ?? '' }),
507
+ providerExecuted: true,
508
+ });
509
+ } else if (event.type === 'item.completed') {
510
+ ctx.send({
511
+ type: 'tool-result',
512
+ toolCallId: id,
513
+ toolName: toCommonName(nativeName),
514
+ result: item.result ?? null,
515
+ });
516
+ }
517
+ return;
518
+ }
519
+
520
+ if (item.type === 'file_change' && event.type === 'item.completed') {
521
+ for (const change of item.changes ?? []) {
522
+ ctx.send({
523
+ type: 'file-change',
524
+ event:
525
+ change.kind === 'add'
526
+ ? 'create'
527
+ : change.kind === 'delete'
528
+ ? 'delete'
529
+ : 'modify',
530
+ path: change.path,
531
+ });
532
+ }
533
+ return;
534
+ }
535
+
536
+ if (item.type === 'error' && event.type === 'item.completed') {
537
+ ctx.send({
538
+ type: 'error',
539
+ error: (item as { message?: string }).message ?? 'codex item error',
540
+ });
541
+ return;
542
+ }
543
+ }
544
+
545
+ function mapUsage(usage: Record<string, number>): Record<string, unknown> {
546
+ const input = usage.input_tokens ?? 0;
547
+ const cacheRead = usage.cached_input_tokens ?? 0;
548
+ return {
549
+ inputTokens: {
550
+ total: input,
551
+ noCache: Math.max(0, input - cacheRead),
552
+ cacheRead,
553
+ cacheWrite: 0,
554
+ },
555
+ outputTokens: {
556
+ total: usage.output_tokens ?? 0,
557
+ text: usage.output_tokens ?? 0,
558
+ },
559
+ };
560
+ }
561
+
562
+ function defaultUsage(): Record<string, unknown> {
563
+ return {
564
+ inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
565
+ outputTokens: { total: 0, text: 0 },
566
+ };
567
+ }
568
+
569
+ /**
570
+ * Tool relay — HTTP server on 127.0.0.1:0. The MCP stdio shim spawned by
571
+ * codex POSTs each tool invocation here; the relay forwards the call to the
572
+ * host (via the shared runtime's `emit`), awaits the matching `tool-result`
573
+ * (via `requestToolResult`), and responds with `{ result }`.
574
+ */
575
+ async function startToolRelay({
576
+ allowedScriptPaths,
577
+ tools,
578
+ emit,
579
+ requestToolResult,
580
+ }: {
581
+ allowedScriptPaths: ReadonlyArray<string>;
582
+ tools: ReadonlyArray<{ name: string }>;
583
+ emit: Emit;
584
+ requestToolResult: (
585
+ toolCallId: string,
586
+ ) => Promise<{ output: unknown; isError?: boolean }>;
587
+ }): Promise<ToolRelay> {
588
+ const toolNames = new Set(tools.map(t => t.name));
589
+ const allowedScriptPathSet = new Set(allowedScriptPaths);
590
+ const authorizer = new ToolRelayAuthorizer();
591
+ const pendingCalls = new ToolRelayPendingCalls();
592
+
593
+ const server = createServer(async (req, res) => {
594
+ try {
595
+ if (req.method !== 'POST' || req.url !== '/') {
596
+ res.writeHead(401, { 'Content-Type': 'application/json' });
597
+ res.end(JSON.stringify({ error: 'unauthorized tool relay request' }));
598
+ return;
599
+ }
600
+ const chunks: Buffer[] = [];
601
+ for await (const chunk of req) {
602
+ chunks.push(chunk as Buffer);
603
+ }
604
+ const body = Buffer.concat(chunks).toString('utf8');
605
+ const { requestId, toolName, input } = JSON.parse(body) as {
606
+ requestId: string;
607
+ toolName: string;
608
+ input: unknown;
609
+ };
610
+
611
+ if (!toolNames.has(toolName)) {
612
+ res.writeHead(403, { 'Content-Type': 'application/json' });
613
+ res.end(
614
+ JSON.stringify({ error: `Tool "${toolName}" is not available` }),
615
+ );
616
+ return;
617
+ }
618
+ const relayCall = { toolName, input };
619
+ const authorized =
620
+ authorizer.consumeToolCall(relayCall) ||
621
+ (await isToolRelayRequestFromAllowedProcess({
622
+ socket: req.socket,
623
+ allowedScriptPaths: allowedScriptPathSet,
624
+ }));
625
+ if (!authorized) {
626
+ res.writeHead(401, { 'Content-Type': 'application/json' });
627
+ res.end(JSON.stringify({ error: 'unauthorized tool relay request' }));
628
+ return;
629
+ }
630
+
631
+ const { result } = pendingCalls.begin({
632
+ call: relayCall,
633
+ run: async () => {
634
+ emit({
635
+ type: 'tool-call',
636
+ toolCallId: requestId,
637
+ toolName,
638
+ input: JSON.stringify(input ?? {}),
639
+ providerExecuted: false,
640
+ });
641
+
642
+ const toolResult = await requestToolResult(requestId);
643
+ emit({
644
+ type: 'tool-result',
645
+ toolCallId: requestId,
646
+ toolName,
647
+ result: toolResult.output ?? null,
648
+ isError: !!toolResult.isError,
649
+ });
650
+ return toolResult;
651
+ },
652
+ });
653
+ const { output } = await result;
654
+
655
+ res.writeHead(200, { 'Content-Type': 'application/json' });
656
+ res.end(JSON.stringify({ result: output }));
657
+ } catch (error) {
658
+ res.writeHead(500, { 'Content-Type': 'application/json' });
659
+ res.end(
660
+ JSON.stringify({
661
+ error: error instanceof Error ? error.message : String(error),
662
+ }),
663
+ );
664
+ }
665
+ });
666
+
667
+ await new Promise<void>(resolve =>
668
+ server.listen(0, '127.0.0.1', () => resolve()),
669
+ );
670
+ const address = server.address();
671
+ if (!address || typeof address === 'string') {
672
+ throw new Error('tool relay did not expose a numeric port');
673
+ }
674
+ return {
675
+ port: address.port,
676
+ close: () => closeServer(server),
677
+ authorizeToolCall: call => authorizer.authorizeToolCall(call),
678
+ authorizeAnyToolCall: () => authorizer.authorizeAnyToolCall(),
679
+ };
680
+ }
681
+
682
+ function closeServer(server: Server): void {
683
+ try {
684
+ server.close();
685
+ } catch {}
686
+ }
687
+
688
+ function parseArgs(args: string[]): {
689
+ workdir?: string;
690
+ bridgeStateDir?: string;
691
+ bootstrapDir?: string;
692
+ cliShimDir?: string;
693
+ } {
694
+ const out: {
695
+ workdir?: string;
696
+ bridgeStateDir?: string;
697
+ bootstrapDir?: string;
698
+ cliShimDir?: string;
699
+ } = {};
700
+ for (let i = 0; i < args.length; i++) {
701
+ if (args[i] === '--workdir' && i + 1 < args.length) {
702
+ out.workdir = args[++i];
703
+ } else if (args[i] === '--bridge-state-dir' && i + 1 < args.length) {
704
+ out.bridgeStateDir = args[++i];
705
+ } else if (args[i] === '--bootstrap-dir' && i + 1 < args.length) {
706
+ out.bootstrapDir = args[++i];
707
+ } else if (args[i] === '--cli-shim-dir' && i + 1 < args.length) {
708
+ out.cliShimDir = args[++i];
709
+ }
710
+ }
711
+ return out;
712
+ }
713
+
714
+ function serialiseError(err: unknown): unknown {
715
+ if (err instanceof Error) {
716
+ return { name: err.name, message: err.message, stack: err.stack };
717
+ }
718
+ return err;
719
+ }
720
+
721
+ function emitFatal(message: string): never {
722
+ stdout.write(JSON.stringify({ type: 'bridge-fatal', message }) + '\n');
723
+ process.exit(1);
724
+ }
725
+
726
+ function requireArg({
727
+ value,
728
+ name,
729
+ }: {
730
+ value: string | undefined;
731
+ name: string;
732
+ }): string {
733
+ if (!value) {
734
+ emitFatal(`Missing ${name} argument.`);
735
+ }
736
+ return value;
737
+ }