@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,1182 @@
1
+ // ../harness/dist/bridge/index.js
2
+ import { appendFile, mkdir, writeFile } from "fs/promises";
3
+ import { existsSync, readFileSync } from "fs";
4
+ import { env as procEnv, pid, stdout } from "process";
5
+ import { WebSocketServer } from "ws";
6
+ var DEBUG_LEVEL_WEIGHT = {
7
+ error: 0,
8
+ warn: 1,
9
+ info: 2,
10
+ debug: 3,
11
+ trace: 4
12
+ };
13
+ function subsystemMatches(filters, subsystem) {
14
+ if (!filters || filters.length === 0) return true;
15
+ return filters.some(
16
+ (filter) => subsystem === filter || subsystem.startsWith(`${filter}.`)
17
+ );
18
+ }
19
+ function formatBridgeError(err) {
20
+ if (err instanceof Error) {
21
+ return { name: err.name, message: err.message, stack: err.stack };
22
+ }
23
+ return { message: String(err) };
24
+ }
25
+ function parseEnvList(value) {
26
+ if (!value) return void 0;
27
+ const items = value.split(",").map((item) => item.trim()).filter(Boolean);
28
+ return items.length > 0 ? items : void 0;
29
+ }
30
+ var ENV_TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
31
+ var WS_OPEN = 1;
32
+ async function runBridge(options) {
33
+ const { bridgeType, bridgeStateDir: bridgeStateDir2, onStart, onDetach } = options;
34
+ const expectedToken = options.token ?? procEnv.BRIDGE_CHANNEL_TOKEN ?? "";
35
+ const bridgeWsPort = options.port ?? parseInt(procEnv.BRIDGE_WS_PORT ?? "0", 10);
36
+ const bridgeMetaPath = `${bridgeStateDir2}/bridge-meta.json`;
37
+ const startConfigPath = `${bridgeStateDir2}/start-config.json`;
38
+ const rerunStartConfigPath = `${bridgeStateDir2}/rerun-start-config.json`;
39
+ const eventLogPath = `${bridgeStateDir2}/event-log.ndjson`;
40
+ try {
41
+ await mkdir(bridgeStateDir2, { recursive: true });
42
+ } catch {
43
+ }
44
+ let currentBoundPort = 0;
45
+ let currentTurnState = "init";
46
+ let activeSocket;
47
+ let isFirstTurn = true;
48
+ let turnAbort;
49
+ let currentUserMessages;
50
+ let debugConfig;
51
+ let consoleCaptureInstalled = false;
52
+ const envDebugEnabled = ENV_TRUTHY.has(
53
+ (procEnv.HARNESS_DEBUG ?? "").toLowerCase()
54
+ );
55
+ let seqCounter = 0;
56
+ let eventLog = [];
57
+ let diskBuffer = "";
58
+ let flushPromise = null;
59
+ const flushEventsToDisk = async () => {
60
+ while (diskBuffer.length > 0) {
61
+ const buf = diskBuffer;
62
+ diskBuffer = "";
63
+ await appendFile(eventLogPath, buf).catch(() => {
64
+ });
65
+ }
66
+ };
67
+ const scheduleEventFlush = () => {
68
+ if (flushPromise) return;
69
+ flushPromise = new Promise((resolve) => {
70
+ setImmediate(() => {
71
+ void flushEventsToDisk().finally(resolve);
72
+ });
73
+ }).finally(() => {
74
+ flushPromise = null;
75
+ if (diskBuffer.length > 0) {
76
+ scheduleEventFlush();
77
+ }
78
+ });
79
+ };
80
+ const flushPendingEventsToDisk = async () => {
81
+ if (diskBuffer.length > 0 && !flushPromise) {
82
+ scheduleEventFlush();
83
+ }
84
+ let inFlight = flushPromise;
85
+ while (inFlight) {
86
+ await inFlight;
87
+ inFlight = flushPromise;
88
+ }
89
+ };
90
+ const replayFromDisk = procEnv.BRIDGE_REPLAY_FROM_DISK === "1";
91
+ if (replayFromDisk && existsSync(eventLogPath)) {
92
+ try {
93
+ const lines = readFileSync(eventLogPath, "utf8").split("\n").map((line) => line.trim()).filter(Boolean);
94
+ eventLog = lines.map((line) => ({
95
+ seq: JSON.parse(line).seq,
96
+ line
97
+ }));
98
+ seqCounter = eventLog.at(-1)?.seq ?? 0;
99
+ } catch {
100
+ eventLog = [];
101
+ seqCounter = 0;
102
+ }
103
+ }
104
+ const pendingToolResults = /* @__PURE__ */ new Map();
105
+ const pendingToolApprovals = /* @__PURE__ */ new Map();
106
+ const writeBridgeMeta = async (state) => {
107
+ try {
108
+ await writeFile(
109
+ bridgeMetaPath,
110
+ JSON.stringify({
111
+ type: bridgeType,
112
+ port: currentBoundPort,
113
+ state,
114
+ pid
115
+ })
116
+ );
117
+ } catch {
118
+ }
119
+ };
120
+ const writeStartConfig = async (start) => {
121
+ try {
122
+ const serialized = JSON.stringify(start);
123
+ await writeFile(startConfigPath, serialized);
124
+ if (!existsSync(rerunStartConfigPath)) {
125
+ await writeFile(rerunStartConfigPath, serialized);
126
+ }
127
+ } catch {
128
+ }
129
+ };
130
+ const sendControl = (msg) => {
131
+ if (activeSocket?.readyState === WS_OPEN) {
132
+ try {
133
+ activeSocket.send(JSON.stringify(msg));
134
+ } catch {
135
+ }
136
+ }
137
+ };
138
+ const emit = (event) => {
139
+ const seq = ++seqCounter;
140
+ const line = JSON.stringify({ ...event, seq });
141
+ eventLog.push({ seq, line });
142
+ diskBuffer += `${line}
143
+ `;
144
+ scheduleEventFlush();
145
+ if (activeSocket?.readyState === WS_OPEN) {
146
+ try {
147
+ activeSocket.send(line);
148
+ } catch {
149
+ }
150
+ }
151
+ };
152
+ const replay = (ws, afterSeq) => {
153
+ for (const entry of eventLog) {
154
+ if (entry.seq > afterSeq && ws.readyState === WS_OPEN) {
155
+ ws.send(entry.line);
156
+ }
157
+ }
158
+ };
159
+ const shouldEmitDebugEvent = (level, subsystem) => {
160
+ if (!debugConfig?.enabled) return false;
161
+ const threshold = debugConfig.level ?? "debug";
162
+ if (DEBUG_LEVEL_WEIGHT[level] > DEBUG_LEVEL_WEIGHT[threshold]) return false;
163
+ return subsystemMatches(debugConfig.subsystems, subsystem);
164
+ };
165
+ const rawStdoutWrite = process.stdout.write.bind(process.stdout);
166
+ const rawStderrWrite = process.stderr.write.bind(process.stderr);
167
+ const installConsoleCapture = () => {
168
+ if (consoleCaptureInstalled) return;
169
+ consoleCaptureInstalled = true;
170
+ const buffers = {
171
+ stdout: "",
172
+ stderr: ""
173
+ };
174
+ const patch = (stream, raw) => (chunk, encoding, cb) => {
175
+ if (debugConfig?.enabled) {
176
+ try {
177
+ const enc = typeof encoding === "string" ? encoding : "utf8";
178
+ const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString(
179
+ enc
180
+ );
181
+ const combined = buffers[stream] + text.replace(/\r\n/g, "\n");
182
+ const parts = combined.split("\n");
183
+ buffers[stream] = parts.pop() ?? "";
184
+ for (const line of parts) {
185
+ const trimmed = line.replace(/\s+$/, "");
186
+ if (trimmed) {
187
+ emit({
188
+ type: "sandbox-log",
189
+ source: bridgeType,
190
+ stream,
191
+ line: trimmed
192
+ });
193
+ }
194
+ }
195
+ } catch {
196
+ }
197
+ }
198
+ return raw(
199
+ chunk,
200
+ encoding,
201
+ cb
202
+ );
203
+ };
204
+ process.stdout.write = patch(
205
+ "stdout",
206
+ rawStdoutWrite
207
+ );
208
+ process.stderr.write = patch(
209
+ "stderr",
210
+ rawStderrWrite
211
+ );
212
+ };
213
+ const handleInbound = async (msg, ws) => {
214
+ switch (msg.type) {
215
+ case "start": {
216
+ const firstTurn = isFirstTurn;
217
+ isFirstTurn = false;
218
+ eventLog = [];
219
+ diskBuffer = "";
220
+ void writeFile(eventLogPath, "").catch(() => {
221
+ });
222
+ turnAbort = new AbortController();
223
+ currentTurnState = "running";
224
+ void writeStartConfig(msg);
225
+ void writeBridgeMeta("running");
226
+ const startDebug = msg.debug;
227
+ debugConfig = {
228
+ enabled: startDebug?.enabled ?? envDebugEnabled,
229
+ level: startDebug?.level ?? procEnv.HARNESS_DEBUG_LEVEL,
230
+ subsystems: startDebug?.subsystems ?? parseEnvList(procEnv.HARNESS_DEBUG_SUBSYSTEMS)
231
+ };
232
+ if (debugConfig.enabled) {
233
+ installConsoleCapture();
234
+ }
235
+ const turn = {
236
+ emit,
237
+ requestToolResult: (toolCallId) => new Promise((resolve) => {
238
+ pendingToolResults.set(toolCallId, resolve);
239
+ }),
240
+ requestToolApproval: (approvalId) => new Promise((resolve) => {
241
+ pendingToolApprovals.set(approvalId, resolve);
242
+ }),
243
+ pendingUserMessages: [],
244
+ abortSignal: turnAbort.signal,
245
+ firstTurn,
246
+ bridgeLog: (input) => {
247
+ const level = input.level ?? "debug";
248
+ if (!shouldEmitDebugEvent(level, input.subsystem)) return;
249
+ emit({
250
+ type: "debug-event",
251
+ level,
252
+ subsystem: input.subsystem,
253
+ message: input.message,
254
+ ...input.attrs ? { attrs: input.attrs } : {},
255
+ ...input.error !== void 0 ? { error: formatBridgeError(input.error) } : {}
256
+ });
257
+ }
258
+ };
259
+ currentUserMessages = turn.pendingUserMessages;
260
+ try {
261
+ await onStart(msg, turn);
262
+ } catch (err) {
263
+ emit({ type: "error", error: serialiseError(err) });
264
+ } finally {
265
+ currentTurnState = "waiting";
266
+ void writeBridgeMeta("waiting");
267
+ }
268
+ return;
269
+ }
270
+ case "tool-result": {
271
+ const resolver = pendingToolResults.get(msg.toolCallId);
272
+ if (resolver) {
273
+ pendingToolResults.delete(msg.toolCallId);
274
+ resolver({ output: msg.output, isError: msg.isError });
275
+ }
276
+ return;
277
+ }
278
+ case "tool-approval-response": {
279
+ const resolver = pendingToolApprovals.get(msg.approvalId);
280
+ if (resolver) {
281
+ pendingToolApprovals.delete(msg.approvalId);
282
+ resolver({ approved: msg.approved, reason: msg.reason });
283
+ }
284
+ return;
285
+ }
286
+ case "user-message":
287
+ currentUserMessages?.push(msg.text);
288
+ return;
289
+ case "abort":
290
+ turnAbort?.abort();
291
+ return;
292
+ case "resume":
293
+ replay(ws, msg.lastSeenEventId);
294
+ return;
295
+ case "shutdown":
296
+ currentTurnState = "done";
297
+ void writeBridgeMeta("done");
298
+ drainThenExit(ws, 1e3, "shutdown");
299
+ return;
300
+ case "detach": {
301
+ currentTurnState = "done";
302
+ void writeBridgeMeta("done");
303
+ const data = await onDetach?.() ?? {};
304
+ sendControl({ type: "bridge-detach", data });
305
+ drainThenExit(ws, 1e3, "detach");
306
+ return;
307
+ }
308
+ }
309
+ };
310
+ void writeBridgeMeta("init");
311
+ const wss = new WebSocketServer({ port: bridgeWsPort, host: "0.0.0.0" });
312
+ const exit = () => {
313
+ if (options.onExit) {
314
+ options.onExit();
315
+ return;
316
+ }
317
+ wss.close(() => process.exit(0));
318
+ setTimeout(() => process.exit(0), 1e3).unref();
319
+ };
320
+ const drainThenExit = (ws, code, reason) => {
321
+ const start = Date.now();
322
+ const tick = () => {
323
+ const drained = ws.bufferedAmount === 0 || ws.readyState !== WS_OPEN;
324
+ if (drained || Date.now() - start >= 5e3) {
325
+ void flushPendingEventsToDisk().finally(() => {
326
+ try {
327
+ ws.close(code, reason);
328
+ } finally {
329
+ exit();
330
+ }
331
+ });
332
+ return;
333
+ }
334
+ setTimeout(tick, 10).unref();
335
+ };
336
+ tick();
337
+ };
338
+ wss.on("listening", () => {
339
+ const addr = wss.address();
340
+ currentBoundPort = typeof addr === "object" && addr ? addr.port : 0;
341
+ currentTurnState = "waiting";
342
+ void writeBridgeMeta("waiting");
343
+ stdout.write(
344
+ JSON.stringify({
345
+ type: "bridge-ready",
346
+ port: currentBoundPort
347
+ }) + "\n"
348
+ );
349
+ options.onListening?.(currentBoundPort);
350
+ });
351
+ wss.on("connection", (ws, req) => {
352
+ const url = new URL(req.url ?? "/", "http://localhost");
353
+ if (url.searchParams.get("agent_bridge_token") !== expectedToken) {
354
+ ws.close(1008, "unauthorized");
355
+ return;
356
+ }
357
+ activeSocket = ws;
358
+ sendControl({
359
+ type: "bridge-hello",
360
+ state: currentTurnState,
361
+ lastSeq: seqCounter
362
+ });
363
+ ws.on("message", (raw) => {
364
+ let parsed;
365
+ try {
366
+ const text = typeof raw === "string" ? raw : Buffer.from(raw).toString("utf8");
367
+ parsed = JSON.parse(text);
368
+ } catch (err) {
369
+ sendControl({
370
+ type: "error",
371
+ error: `protocol parse error: ${err.message}`
372
+ });
373
+ return;
374
+ }
375
+ void handleInbound(parsed, ws);
376
+ });
377
+ ws.on("close", () => {
378
+ if (activeSocket === ws) {
379
+ activeSocket = void 0;
380
+ }
381
+ });
382
+ ws.on("error", () => {
383
+ });
384
+ });
385
+ process.on("uncaughtException", (err) => {
386
+ emit({ type: "error", error: serialiseError(err) });
387
+ });
388
+ process.on("unhandledRejection", (err) => {
389
+ emit({ type: "error", error: serialiseError(err) });
390
+ });
391
+ await new Promise((resolve, reject) => {
392
+ if (wss.address() != null) {
393
+ resolve();
394
+ return;
395
+ }
396
+ wss.once("listening", resolve);
397
+ wss.once("error", reject);
398
+ });
399
+ return {
400
+ port: currentBoundPort,
401
+ close: () => new Promise((resolve) => {
402
+ wss.close(() => resolve());
403
+ })
404
+ };
405
+ }
406
+ function serialiseError(err) {
407
+ if (err instanceof Error) {
408
+ return { name: err.name, message: err.message, stack: err.stack };
409
+ }
410
+ return err;
411
+ }
412
+
413
+ // src/bridge/index.ts
414
+ import { randomUUID } from "crypto";
415
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
416
+ import { createServer } from "http";
417
+
418
+ // src/bridge/cli-relay.ts
419
+ var CLI_SHIM_FILENAME = "harness-tool.mjs";
420
+ function buildCliShimScript({
421
+ relayPort
422
+ }) {
423
+ return `#!/usr/bin/env node
424
+ const [toolName, inputJson = '{}'] = process.argv.slice(2);
425
+ if (!toolName) {
426
+ console.error('Usage: harness-tool <tool_name> <json_input>');
427
+ process.exit(64);
428
+ }
429
+ let input;
430
+ try {
431
+ input = JSON.parse(inputJson);
432
+ } catch (error) {
433
+ console.error('Invalid JSON input: ' + (error instanceof Error ? error.message : String(error)));
434
+ process.exit(64);
435
+ }
436
+ const requestId = 'cli-' + Date.now() + '-' + Math.random().toString(16).slice(2);
437
+ const response = await fetch('http://127.0.0.1:${relayPort}', {
438
+ method: 'POST',
439
+ headers: { 'Content-Type': 'application/json' },
440
+ body: JSON.stringify({ requestId, toolName, input }),
441
+ });
442
+ const text = await response.text();
443
+ let payload;
444
+ try {
445
+ payload = text ? JSON.parse(text) : {};
446
+ } catch {
447
+ payload = { error: text };
448
+ }
449
+ if (!response.ok || payload.error) {
450
+ console.error(String(payload.error ?? ('tool relay failed with HTTP ' + response.status)));
451
+ process.exit(1);
452
+ }
453
+ console.log(JSON.stringify(payload.result ?? payload, null, 2));
454
+ `;
455
+ }
456
+ function parseToolRelayCommand({
457
+ command,
458
+ cliShimPath
459
+ }) {
460
+ return parseToolRelayCommandInternal({ command, cliShimPath, depth: 0 });
461
+ }
462
+ function parseToolRelayCommandInternal({
463
+ command,
464
+ cliShimPath,
465
+ depth
466
+ }) {
467
+ const argv2 = parseShellWords(command);
468
+ if (!argv2) return void 0;
469
+ const relayCall = parseDirectToolRelayArgv({ argv: argv2, cliShimPath });
470
+ if (relayCall) return relayCall;
471
+ const innerCommand = extractShellEvalCommand(argv2);
472
+ if (!innerCommand || depth >= 2) return void 0;
473
+ return parseToolRelayCommandInternal({
474
+ command: innerCommand,
475
+ cliShimPath,
476
+ depth: depth + 1
477
+ });
478
+ }
479
+ function parseDirectToolRelayArgv({
480
+ argv: argv2,
481
+ cliShimPath
482
+ }) {
483
+ if (argv2.length < 3 || argv2.length > 4) return void 0;
484
+ if (argv2[0] !== "node" || argv2[1] !== cliShimPath) return void 0;
485
+ const toolName = argv2[2];
486
+ if (!toolName) return void 0;
487
+ try {
488
+ return { toolName, input: JSON.parse(argv2[3] ?? "{}") };
489
+ } catch {
490
+ return void 0;
491
+ }
492
+ }
493
+ function extractShellEvalCommand(argv2) {
494
+ if (argv2.length !== 3) return void 0;
495
+ const shellName = argv2[0].split("/").at(-1);
496
+ if (shellName !== "bash" && shellName !== "sh" && shellName !== "zsh") {
497
+ return void 0;
498
+ }
499
+ if (argv2[1] !== "-c" && argv2[1] !== "-lc") return void 0;
500
+ return argv2[2];
501
+ }
502
+ function parseShellWords(command) {
503
+ const words = [];
504
+ let current = "";
505
+ let quote;
506
+ let hasCurrent = false;
507
+ const pushCurrent = () => {
508
+ if (!hasCurrent) return;
509
+ words.push(current);
510
+ current = "";
511
+ hasCurrent = false;
512
+ };
513
+ for (let i = 0; i < command.length; i++) {
514
+ const char = command[i];
515
+ if (quote === "'") {
516
+ if (char === "'") {
517
+ quote = void 0;
518
+ } else {
519
+ current += char;
520
+ }
521
+ hasCurrent = true;
522
+ continue;
523
+ }
524
+ if (quote === '"') {
525
+ if (char === '"') {
526
+ quote = void 0;
527
+ } else if (char === "\\" && i + 1 < command.length) {
528
+ current += command[++i];
529
+ } else {
530
+ current += char;
531
+ }
532
+ hasCurrent = true;
533
+ continue;
534
+ }
535
+ if (/\s/.test(char)) {
536
+ pushCurrent();
537
+ continue;
538
+ }
539
+ if (char === '"' || char === "'") {
540
+ quote = char;
541
+ hasCurrent = true;
542
+ continue;
543
+ }
544
+ if (char === "\\" && i + 1 < command.length) {
545
+ current += command[++i];
546
+ hasCurrent = true;
547
+ continue;
548
+ }
549
+ if (/[;&|<>()`$]/.test(char)) return void 0;
550
+ current += char;
551
+ hasCurrent = true;
552
+ }
553
+ if (quote) return void 0;
554
+ pushCurrent();
555
+ return words;
556
+ }
557
+
558
+ // src/bridge/tool-relay-auth.ts
559
+ import { readdir, readFile, readlink } from "fs/promises";
560
+ var ToolRelayAuthorizer = class {
561
+ constructor({
562
+ ttlMs = 1e4,
563
+ now = Date.now
564
+ } = {}) {
565
+ this.authorizations = [];
566
+ this.ttlMs = ttlMs;
567
+ this.now = now;
568
+ }
569
+ authorizeToolCall(call) {
570
+ this.pruneExpired();
571
+ this.authorizations.push({
572
+ key: toolRelayCallKey(call),
573
+ expiresAt: this.now() + this.ttlMs
574
+ });
575
+ }
576
+ authorizeAnyToolCall() {
577
+ this.pruneExpired();
578
+ this.authorizations.push({
579
+ expiresAt: this.now() + this.ttlMs
580
+ });
581
+ }
582
+ consumeToolCall(call) {
583
+ this.pruneExpired();
584
+ const key = toolRelayCallKey(call);
585
+ let index = this.authorizations.findIndex((auth) => auth.key === key);
586
+ if (index === -1) {
587
+ index = this.authorizations.findIndex((auth) => auth.key === void 0);
588
+ }
589
+ if (index === -1) return false;
590
+ this.authorizations.splice(index, 1);
591
+ return true;
592
+ }
593
+ pruneExpired() {
594
+ const now = this.now();
595
+ for (let i = this.authorizations.length - 1; i >= 0; i--) {
596
+ if (this.authorizations[i].expiresAt <= now) {
597
+ this.authorizations.splice(i, 1);
598
+ }
599
+ }
600
+ }
601
+ };
602
+ var ToolRelayPendingCalls = class {
603
+ constructor() {
604
+ this.calls = /* @__PURE__ */ new Map();
605
+ }
606
+ begin({
607
+ call,
608
+ run
609
+ }) {
610
+ const key = toolRelayCallKey(call);
611
+ const existing = this.calls.get(key);
612
+ if (existing) return { result: existing, isNew: false };
613
+ const result = run();
614
+ this.calls.set(key, result);
615
+ void result.finally(() => {
616
+ if (this.calls.get(key) === result) {
617
+ this.calls.delete(key);
618
+ }
619
+ }).catch(() => {
620
+ });
621
+ return { result, isNew: true };
622
+ }
623
+ };
624
+ function toolRelayCallKey({ toolName, input }) {
625
+ return `${toolName}\0${canonicalJson(input ?? {})}`;
626
+ }
627
+ function canonicalJson(value) {
628
+ return JSON.stringify(normalizeJsonValue(value));
629
+ }
630
+ function normalizeJsonValue(value) {
631
+ if (Array.isArray(value)) {
632
+ return value.map(normalizeJsonValue);
633
+ }
634
+ if (value && typeof value === "object") {
635
+ return Object.fromEntries(
636
+ Object.entries(value).filter(([, entryValue]) => entryValue !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue)])
637
+ );
638
+ }
639
+ return value;
640
+ }
641
+ async function isToolRelayRequestFromAllowedProcess({
642
+ socket,
643
+ allowedScriptPaths
644
+ }) {
645
+ if (process.platform !== "linux") return false;
646
+ if (!socket.remotePort || !socket.localPort) return false;
647
+ const inode = await findTcpSocketInode({
648
+ clientPort: socket.remotePort,
649
+ serverPort: socket.localPort
650
+ });
651
+ if (!inode) return false;
652
+ const cmdline = await findProcessCmdlineForSocketInode({ inode });
653
+ return cmdline?.some((arg) => allowedScriptPaths.has(arg)) ?? false;
654
+ }
655
+ async function findTcpSocketInode({
656
+ clientPort,
657
+ serverPort
658
+ }) {
659
+ for (const tablePath of ["/proc/net/tcp", "/proc/net/tcp6"]) {
660
+ const table = await readFile(tablePath, "utf8").catch(() => void 0);
661
+ if (!table) continue;
662
+ for (const line of table.split("\n").slice(1)) {
663
+ const columns = line.trim().split(/\s+/);
664
+ if (columns.length < 10) continue;
665
+ const local = parseProcNetAddress(columns[1]);
666
+ const remote = parseProcNetAddress(columns[2]);
667
+ if (local?.port === clientPort && remote?.port === serverPort && columns[9] !== "0") {
668
+ return columns[9];
669
+ }
670
+ }
671
+ }
672
+ return void 0;
673
+ }
674
+ function parseProcNetAddress(value) {
675
+ const [, portHex] = value.split(":");
676
+ if (!portHex) return void 0;
677
+ return { port: Number.parseInt(portHex, 16) };
678
+ }
679
+ async function findProcessCmdlineForSocketInode({
680
+ inode
681
+ }) {
682
+ const procEntries = await readdir("/proc", { withFileTypes: true }).catch(
683
+ () => []
684
+ );
685
+ for (const entry of procEntries) {
686
+ if (!entry.isDirectory() || !/^\d+$/.test(entry.name)) continue;
687
+ const fdDir = `/proc/${entry.name}/fd`;
688
+ const fds = await readdir(fdDir).catch(() => []);
689
+ for (const fd of fds) {
690
+ const target = await readlink(`${fdDir}/${fd}`).catch(() => void 0);
691
+ if (target !== `socket:[${inode}]`) continue;
692
+ const cmdline = await readFile(`/proc/${entry.name}/cmdline`, "utf8").then((value) => value.split("\0").filter(Boolean)).catch(() => void 0);
693
+ if (cmdline) return cmdline;
694
+ }
695
+ }
696
+ return void 0;
697
+ }
698
+
699
+ // src/bridge/index.ts
700
+ import { argv, env as procEnv2, stdout as stdout2 } from "process";
701
+ import * as codexSdkModule from "@openai/codex-sdk";
702
+ var NATIVE_TO_COMMON = {
703
+ shell: "bash",
704
+ web_search: "webSearch"
705
+ };
706
+ function toCommonName(nativeName) {
707
+ return NATIVE_TO_COMMON[nativeName] ?? nativeName;
708
+ }
709
+ var args = parseArgs(argv.slice(2));
710
+ var workdir = requireArg({ value: args.workdir, name: "--workdir" });
711
+ var bridgeStateDir = requireArg({
712
+ value: args.bridgeStateDir,
713
+ name: "--bridge-state-dir"
714
+ });
715
+ var cliShimDir = requireArg({
716
+ value: args.cliShimDir,
717
+ name: "--cli-shim-dir"
718
+ });
719
+ var bootstrapDir = args.bootstrapDir ?? workdir;
720
+ var HARNESS_CLIENT_APP = procEnv2.AI_SDK_HARNESS_CLIENT_APP;
721
+ var codexSdk = codexSdkModule;
722
+ var threadState = { id: void 0 };
723
+ await runBridge({
724
+ bridgeType: "codex",
725
+ bridgeStateDir,
726
+ onStart: runTurn,
727
+ onDetach: () => threadState.id ? { threadId: threadState.id } : {}
728
+ });
729
+ async function runTurn(start, turn) {
730
+ const emit = (msg) => turn.emit(msg);
731
+ if (typeof start.resumeThreadId === "string" && start.resumeThreadId.length > 0) {
732
+ threadState.id = start.resumeThreadId;
733
+ }
734
+ const mcpServers = {};
735
+ let relay;
736
+ let cliShimPath;
737
+ if (start.tools && start.tools.length > 0) {
738
+ cliShimPath = `${cliShimDir}/${CLI_SHIM_FILENAME}`;
739
+ relay = await startToolRelay({
740
+ allowedScriptPaths: [cliShimPath, `${bootstrapDir}/host-tool-mcp.mjs`],
741
+ tools: start.tools,
742
+ emit,
743
+ requestToolResult: turn.requestToolResult
744
+ });
745
+ mcpServers["harness-tools"] = {
746
+ enabled: true,
747
+ command: "node",
748
+ args: [`${bootstrapDir}/host-tool-mcp.mjs`],
749
+ env: {
750
+ TOOL_SCHEMAS: JSON.stringify(
751
+ start.tools.map((t) => ({
752
+ name: t.name,
753
+ description: t.description,
754
+ inputSchema: t.inputSchema
755
+ }))
756
+ ),
757
+ TOOL_RELAY_URL: `http://127.0.0.1:${relay.port}`
758
+ }
759
+ };
760
+ await mkdir2(cliShimDir, { recursive: true });
761
+ await writeFile2(
762
+ cliShimPath,
763
+ buildCliShimScript({ relayPort: relay.port }),
764
+ "utf8"
765
+ );
766
+ }
767
+ const codexConfig = {};
768
+ if (Object.keys(mcpServers).length > 0) codexConfig.mcp_servers = mcpServers;
769
+ const gatewayBaseUrl = procEnv2.AI_GATEWAY_BASE_URL;
770
+ const hasGatewayAuth = Boolean(procEnv2.AI_GATEWAY_API_KEY || gatewayBaseUrl);
771
+ if (hasGatewayAuth && !gatewayBaseUrl) {
772
+ throw new Error(
773
+ "AI Gateway auth was selected but AI_GATEWAY_BASE_URL is missing from the Codex bridge environment."
774
+ );
775
+ }
776
+ const apiBaseUrl = hasGatewayAuth ? gatewayBaseUrl : procEnv2.OPENAI_BASE_URL;
777
+ if (apiBaseUrl) {
778
+ codexConfig.preferred_auth_method = "apikey";
779
+ codexConfig.model_provider = "agent_bridge_openai";
780
+ codexConfig.model_providers = {
781
+ agent_bridge_openai: {
782
+ name: procEnv2.CODEX_MODEL_PROVIDER_NAME || "Agent Bridge OpenAI",
783
+ base_url: apiBaseUrl,
784
+ env_key: "CODEX_API_KEY",
785
+ wire_api: "responses",
786
+ supports_websockets: false,
787
+ ...hasGatewayAuth && HARNESS_CLIENT_APP ? {
788
+ http_headers: {
789
+ "User-Agent": HARNESS_CLIENT_APP,
790
+ "x-client-app": HARNESS_CLIENT_APP
791
+ }
792
+ } : {}
793
+ }
794
+ };
795
+ }
796
+ const usesConfiguredModelProvider = typeof codexConfig.model_provider === "string";
797
+ const codex = new codexSdk.Codex({
798
+ ...procEnv2.CODEX_API_KEY ? { apiKey: procEnv2.CODEX_API_KEY } : {},
799
+ ...!usesConfiguredModelProvider && apiBaseUrl ? { baseUrl: apiBaseUrl } : {},
800
+ env: Object.fromEntries(
801
+ Object.entries(procEnv2).filter(
802
+ (entry) => typeof entry[1] === "string"
803
+ )
804
+ ),
805
+ ...Object.keys(codexConfig).length > 0 ? { config: codexConfig } : {}
806
+ });
807
+ const threadOptions = {
808
+ ...start.model ? { model: start.model } : {},
809
+ sandboxMode: "danger-full-access",
810
+ approvalPolicy: "never",
811
+ workingDirectory: workdir,
812
+ skipGitRepoCheck: true,
813
+ ...start.reasoningEffort ? { modelReasoningEffort: start.reasoningEffort } : {},
814
+ webSearchMode: start.webSearch ? "live" : "disabled"
815
+ };
816
+ const thread = threadState.id ? codex.resumeThread(threadState.id, threadOptions) : codex.startThread(threadOptions);
817
+ emit({ type: "stream-start" });
818
+ const userMessage = start.prompt;
819
+ let turnUsage;
820
+ const textByItem = /* @__PURE__ */ new Map();
821
+ const reasoningByItem = /* @__PURE__ */ new Map();
822
+ try {
823
+ const { events } = await thread.runStreamed(userMessage, {
824
+ signal: turn.abortSignal
825
+ });
826
+ for await (const event of events) {
827
+ if (turn.abortSignal.aborted) break;
828
+ if (event.type === "thread.started" && typeof event.thread_id === "string") {
829
+ threadState.id = event.thread_id;
830
+ emit({ type: "bridge-thread", threadId: event.thread_id });
831
+ }
832
+ if (cliShimPath && event.item?.type === "command_execution") {
833
+ const relayCall = typeof event.item.command === "string" ? parseToolRelayCommand({
834
+ command: event.item.command,
835
+ cliShimPath
836
+ }) : void 0;
837
+ if (event.type === "item.started" && relay) {
838
+ if (relayCall) {
839
+ relay.authorizeToolCall(relayCall);
840
+ } else if (typeof event.item.command !== "string") {
841
+ relay.authorizeAnyToolCall();
842
+ }
843
+ }
844
+ if (relayCall) {
845
+ continue;
846
+ }
847
+ }
848
+ if (relay && isHostMcpToolEvent(event)) {
849
+ const relayCall = relayCallFromCodexMcpEvent(event);
850
+ if (relayCall) relay.authorizeToolCall(relayCall);
851
+ continue;
852
+ }
853
+ translateAndEmit(event, {
854
+ send: emit,
855
+ textByItem,
856
+ reasoningByItem,
857
+ setTurnUsage: (u) => turnUsage = u
858
+ });
859
+ }
860
+ } catch (err) {
861
+ emit({ type: "error", error: serialiseError2(err) });
862
+ return;
863
+ } finally {
864
+ relay?.close();
865
+ }
866
+ emit({
867
+ type: "finish",
868
+ finishReason: { unified: "stop", raw: "stop" },
869
+ totalUsage: turnUsage ?? defaultUsage()
870
+ });
871
+ void turn.pendingUserMessages;
872
+ }
873
+ function extractMcpToolCallResult(item) {
874
+ if (item.result === void 0 || item.result === null || typeof item.result !== "object") {
875
+ return item.error?.message ? { error: item.error.message } : null;
876
+ }
877
+ const result = item.result;
878
+ if (result.structured_content !== void 0 && result.structured_content !== null) {
879
+ return result.structured_content;
880
+ }
881
+ return result.content ?? null;
882
+ }
883
+ function isHostMcpToolEvent(event) {
884
+ return event.item?.type === "mcp_tool_call" && event.item.server === "harness-tools";
885
+ }
886
+ function relayCallFromCodexMcpEvent(event) {
887
+ if (event.type !== "item.started") return void 0;
888
+ const toolName = event.item?.tool;
889
+ if (!toolName) return void 0;
890
+ return {
891
+ toolName,
892
+ input: event.item?.arguments ?? {}
893
+ };
894
+ }
895
+ function translateAndEmit(event, ctx) {
896
+ if (event.type === "turn.completed") {
897
+ if (event.usage) ctx.setTurnUsage(mapUsage(event.usage));
898
+ ctx.send({
899
+ type: "finish-step",
900
+ finishReason: { unified: "stop", raw: "stop" },
901
+ usage: event.usage ? mapUsage(event.usage) : defaultUsage()
902
+ });
903
+ return;
904
+ }
905
+ if (event.type === "turn.failed") {
906
+ ctx.send({
907
+ type: "error",
908
+ error: event.error?.message ?? "codex turn failed"
909
+ });
910
+ return;
911
+ }
912
+ if (event.type === "error") {
913
+ ctx.send({ type: "error", error: event.message ?? "codex error" });
914
+ return;
915
+ }
916
+ if (!event.item) return;
917
+ const item = event.item;
918
+ const id = item.id ?? randomUUID();
919
+ if (item.type === "agent_message" && typeof item.text === "string") {
920
+ if (!ctx.textByItem.has(id)) {
921
+ ctx.send({ type: "text-start", id });
922
+ ctx.textByItem.set(id, "");
923
+ }
924
+ const last = ctx.textByItem.get(id) ?? "";
925
+ const next = item.text;
926
+ if (next.length > last.length) {
927
+ ctx.send({ type: "text-delta", id, delta: next.slice(last.length) });
928
+ ctx.textByItem.set(id, next);
929
+ }
930
+ if (event.type === "item.completed") ctx.send({ type: "text-end", id });
931
+ return;
932
+ }
933
+ if (item.type === "reasoning" && typeof item.text === "string") {
934
+ if (!ctx.reasoningByItem.has(id)) {
935
+ ctx.send({ type: "reasoning-start", id });
936
+ ctx.reasoningByItem.set(id, "");
937
+ }
938
+ const last = ctx.reasoningByItem.get(id) ?? "";
939
+ const next = item.text;
940
+ if (next.length > last.length) {
941
+ ctx.send({ type: "reasoning-delta", id, delta: next.slice(last.length) });
942
+ ctx.reasoningByItem.set(id, next);
943
+ }
944
+ if (event.type === "item.completed")
945
+ ctx.send({ type: "reasoning-end", id });
946
+ return;
947
+ }
948
+ if (item.type === "command_execution") {
949
+ const nativeName = "shell";
950
+ if (event.type === "item.started") {
951
+ ctx.send({
952
+ type: "tool-call",
953
+ toolCallId: id,
954
+ toolName: toCommonName(nativeName),
955
+ nativeName,
956
+ input: JSON.stringify({ command: item.command ?? "" }),
957
+ providerExecuted: true
958
+ });
959
+ } else if (event.type === "item.completed") {
960
+ ctx.send({
961
+ type: "tool-result",
962
+ toolCallId: id,
963
+ toolName: toCommonName(nativeName),
964
+ result: {
965
+ exitCode: item.exit_code ?? null,
966
+ output: item.aggregated_output ?? "",
967
+ status: item.status ?? "completed"
968
+ }
969
+ });
970
+ }
971
+ return;
972
+ }
973
+ if (item.type === "mcp_tool_call") {
974
+ const isHostTool = item.server === "harness-tools";
975
+ if (event.type === "item.started") {
976
+ ctx.send({
977
+ type: "tool-call",
978
+ toolCallId: id,
979
+ toolName: item.tool ?? "unknown",
980
+ ...isHostTool ? {} : { nativeName: item.tool ?? "unknown" },
981
+ input: JSON.stringify(item.arguments ?? {}),
982
+ providerExecuted: !isHostTool
983
+ });
984
+ } else if (event.type === "item.completed") {
985
+ ctx.send({
986
+ type: "tool-result",
987
+ toolCallId: id,
988
+ toolName: item.tool ?? "unknown",
989
+ result: extractMcpToolCallResult(item)
990
+ });
991
+ }
992
+ return;
993
+ }
994
+ if (item.type === "web_search") {
995
+ const nativeName = "web_search";
996
+ if (event.type === "item.started") {
997
+ ctx.send({
998
+ type: "tool-call",
999
+ toolCallId: id,
1000
+ toolName: toCommonName(nativeName),
1001
+ nativeName,
1002
+ input: JSON.stringify({ query: item.query ?? "" }),
1003
+ providerExecuted: true
1004
+ });
1005
+ } else if (event.type === "item.completed") {
1006
+ ctx.send({
1007
+ type: "tool-result",
1008
+ toolCallId: id,
1009
+ toolName: toCommonName(nativeName),
1010
+ result: item.result ?? null
1011
+ });
1012
+ }
1013
+ return;
1014
+ }
1015
+ if (item.type === "file_change" && event.type === "item.completed") {
1016
+ for (const change of item.changes ?? []) {
1017
+ ctx.send({
1018
+ type: "file-change",
1019
+ event: change.kind === "add" ? "create" : change.kind === "delete" ? "delete" : "modify",
1020
+ path: change.path
1021
+ });
1022
+ }
1023
+ return;
1024
+ }
1025
+ if (item.type === "error" && event.type === "item.completed") {
1026
+ ctx.send({
1027
+ type: "error",
1028
+ error: item.message ?? "codex item error"
1029
+ });
1030
+ return;
1031
+ }
1032
+ }
1033
+ function mapUsage(usage) {
1034
+ const input = usage.input_tokens ?? 0;
1035
+ const cacheRead = usage.cached_input_tokens ?? 0;
1036
+ return {
1037
+ inputTokens: {
1038
+ total: input,
1039
+ noCache: Math.max(0, input - cacheRead),
1040
+ cacheRead,
1041
+ cacheWrite: 0
1042
+ },
1043
+ outputTokens: {
1044
+ total: usage.output_tokens ?? 0,
1045
+ text: usage.output_tokens ?? 0
1046
+ }
1047
+ };
1048
+ }
1049
+ function defaultUsage() {
1050
+ return {
1051
+ inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
1052
+ outputTokens: { total: 0, text: 0 }
1053
+ };
1054
+ }
1055
+ async function startToolRelay({
1056
+ allowedScriptPaths,
1057
+ tools,
1058
+ emit,
1059
+ requestToolResult
1060
+ }) {
1061
+ const toolNames = new Set(tools.map((t) => t.name));
1062
+ const allowedScriptPathSet = new Set(allowedScriptPaths);
1063
+ const authorizer = new ToolRelayAuthorizer();
1064
+ const pendingCalls = new ToolRelayPendingCalls();
1065
+ const server = createServer(async (req, res) => {
1066
+ try {
1067
+ if (req.method !== "POST" || req.url !== "/") {
1068
+ res.writeHead(401, { "Content-Type": "application/json" });
1069
+ res.end(JSON.stringify({ error: "unauthorized tool relay request" }));
1070
+ return;
1071
+ }
1072
+ const chunks = [];
1073
+ for await (const chunk of req) {
1074
+ chunks.push(chunk);
1075
+ }
1076
+ const body = Buffer.concat(chunks).toString("utf8");
1077
+ const { requestId, toolName, input } = JSON.parse(body);
1078
+ if (!toolNames.has(toolName)) {
1079
+ res.writeHead(403, { "Content-Type": "application/json" });
1080
+ res.end(
1081
+ JSON.stringify({ error: `Tool "${toolName}" is not available` })
1082
+ );
1083
+ return;
1084
+ }
1085
+ const relayCall = { toolName, input };
1086
+ const authorized = authorizer.consumeToolCall(relayCall) || await isToolRelayRequestFromAllowedProcess({
1087
+ socket: req.socket,
1088
+ allowedScriptPaths: allowedScriptPathSet
1089
+ });
1090
+ if (!authorized) {
1091
+ res.writeHead(401, { "Content-Type": "application/json" });
1092
+ res.end(JSON.stringify({ error: "unauthorized tool relay request" }));
1093
+ return;
1094
+ }
1095
+ const { result } = pendingCalls.begin({
1096
+ call: relayCall,
1097
+ run: async () => {
1098
+ emit({
1099
+ type: "tool-call",
1100
+ toolCallId: requestId,
1101
+ toolName,
1102
+ input: JSON.stringify(input ?? {}),
1103
+ providerExecuted: false
1104
+ });
1105
+ const toolResult = await requestToolResult(requestId);
1106
+ emit({
1107
+ type: "tool-result",
1108
+ toolCallId: requestId,
1109
+ toolName,
1110
+ result: toolResult.output ?? null,
1111
+ isError: !!toolResult.isError
1112
+ });
1113
+ return toolResult;
1114
+ }
1115
+ });
1116
+ const { output } = await result;
1117
+ res.writeHead(200, { "Content-Type": "application/json" });
1118
+ res.end(JSON.stringify({ result: output }));
1119
+ } catch (error) {
1120
+ res.writeHead(500, { "Content-Type": "application/json" });
1121
+ res.end(
1122
+ JSON.stringify({
1123
+ error: error instanceof Error ? error.message : String(error)
1124
+ })
1125
+ );
1126
+ }
1127
+ });
1128
+ await new Promise(
1129
+ (resolve) => server.listen(0, "127.0.0.1", () => resolve())
1130
+ );
1131
+ const address = server.address();
1132
+ if (!address || typeof address === "string") {
1133
+ throw new Error("tool relay did not expose a numeric port");
1134
+ }
1135
+ return {
1136
+ port: address.port,
1137
+ close: () => closeServer(server),
1138
+ authorizeToolCall: (call) => authorizer.authorizeToolCall(call),
1139
+ authorizeAnyToolCall: () => authorizer.authorizeAnyToolCall()
1140
+ };
1141
+ }
1142
+ function closeServer(server) {
1143
+ try {
1144
+ server.close();
1145
+ } catch {
1146
+ }
1147
+ }
1148
+ function parseArgs(args2) {
1149
+ const out = {};
1150
+ for (let i = 0; i < args2.length; i++) {
1151
+ if (args2[i] === "--workdir" && i + 1 < args2.length) {
1152
+ out.workdir = args2[++i];
1153
+ } else if (args2[i] === "--bridge-state-dir" && i + 1 < args2.length) {
1154
+ out.bridgeStateDir = args2[++i];
1155
+ } else if (args2[i] === "--bootstrap-dir" && i + 1 < args2.length) {
1156
+ out.bootstrapDir = args2[++i];
1157
+ } else if (args2[i] === "--cli-shim-dir" && i + 1 < args2.length) {
1158
+ out.cliShimDir = args2[++i];
1159
+ }
1160
+ }
1161
+ return out;
1162
+ }
1163
+ function serialiseError2(err) {
1164
+ if (err instanceof Error) {
1165
+ return { name: err.name, message: err.message, stack: err.stack };
1166
+ }
1167
+ return err;
1168
+ }
1169
+ function emitFatal(message) {
1170
+ stdout2.write(JSON.stringify({ type: "bridge-fatal", message }) + "\n");
1171
+ process.exit(1);
1172
+ }
1173
+ function requireArg({
1174
+ value,
1175
+ name
1176
+ }) {
1177
+ if (!value) {
1178
+ emitFatal(`Missing ${name} argument.`);
1179
+ }
1180
+ return value;
1181
+ }
1182
+ //# sourceMappingURL=index.mjs.map