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