@ai-sdk/harness-codex 0.0.0 → 1.0.0-canary.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/LICENSE +13 -0
- package/README.md +73 -0
- package/dist/bridge/host-tool-mcp.mjs +105 -0
- package/dist/bridge/host-tool-mcp.mjs.map +1 -0
- package/dist/bridge/index.mjs +932 -0
- package/dist/bridge/index.mjs.map +1 -0
- package/dist/bridge/package.json +12 -0
- package/dist/bridge/pnpm-lock.yaml +879 -0
- package/dist/index.d.ts +73 -0
- package/dist/index.js +811 -0
- package/dist/index.js.map +1 -0
- package/package.json +76 -1
- package/src/bridge/cli-relay.ts +114 -0
- package/src/bridge/host-tool-mcp.ts +163 -0
- package/src/bridge/index.ts +695 -0
- package/src/bridge/package.json +12 -0
- package/src/bridge/pnpm-lock.yaml +879 -0
- package/src/codex-auth.ts +100 -0
- package/src/codex-bridge-protocol.ts +48 -0
- package/src/codex-harness.ts +1029 -0
- package/src/index.ts +12 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,811 @@
|
|
|
1
|
+
// src/codex-harness.ts
|
|
2
|
+
import { randomBytes } from "crypto";
|
|
3
|
+
import { readFile } from "fs/promises";
|
|
4
|
+
import { fileURLToPath } from "url";
|
|
5
|
+
import {
|
|
6
|
+
commonTool,
|
|
7
|
+
HarnessCapabilityUnsupportedError,
|
|
8
|
+
harnessV1DiagnosticFromBridgeFrame
|
|
9
|
+
} from "@ai-sdk/harness";
|
|
10
|
+
import { classifyDiskLog, SandboxChannel } from "@ai-sdk/harness/utils";
|
|
11
|
+
import {
|
|
12
|
+
safeParseJSON
|
|
13
|
+
} from "@ai-sdk/provider-utils";
|
|
14
|
+
import { WebSocket } from "ws";
|
|
15
|
+
import { z as z2 } from "zod";
|
|
16
|
+
|
|
17
|
+
// src/codex-auth.ts
|
|
18
|
+
function resolveCodexEnv(auth, processEnv = process.env) {
|
|
19
|
+
if (auth?.openaiCompatible) {
|
|
20
|
+
return pickOpenAICompatible(auth.openaiCompatible, processEnv);
|
|
21
|
+
}
|
|
22
|
+
if (auth?.openai) {
|
|
23
|
+
return pickOpenAI({ explicit: auth.openai, processEnv });
|
|
24
|
+
}
|
|
25
|
+
if (auth?.gateway) {
|
|
26
|
+
return pickGateway(auth.gateway, processEnv);
|
|
27
|
+
}
|
|
28
|
+
if (processEnv.AI_GATEWAY_API_KEY) {
|
|
29
|
+
return pickGateway({}, processEnv);
|
|
30
|
+
}
|
|
31
|
+
return pickOpenAI({ processEnv });
|
|
32
|
+
}
|
|
33
|
+
function pickOpenAICompatible(explicit, processEnv) {
|
|
34
|
+
const env = {};
|
|
35
|
+
const apiKey = explicit.apiKey ?? processEnv.OPENAI_API_KEY ?? processEnv.CODEX_API_KEY;
|
|
36
|
+
if (apiKey) env.CODEX_API_KEY = apiKey;
|
|
37
|
+
if (explicit.baseUrl) env.OPENAI_BASE_URL = explicit.baseUrl;
|
|
38
|
+
if (explicit.modelProviderName)
|
|
39
|
+
env.CODEX_MODEL_PROVIDER_NAME = explicit.modelProviderName;
|
|
40
|
+
if (explicit.queryParamsJson)
|
|
41
|
+
env.OPENAI_QUERY_PARAMS_JSON = explicit.queryParamsJson;
|
|
42
|
+
return env;
|
|
43
|
+
}
|
|
44
|
+
function pickOpenAI({
|
|
45
|
+
explicit,
|
|
46
|
+
processEnv
|
|
47
|
+
}) {
|
|
48
|
+
const env = {};
|
|
49
|
+
const apiKey = explicit?.apiKey ?? processEnv.OPENAI_API_KEY ?? processEnv.CODEX_API_KEY;
|
|
50
|
+
if (apiKey) env.CODEX_API_KEY = apiKey;
|
|
51
|
+
const baseUrl = explicit?.baseUrl ?? processEnv.OPENAI_BASE_URL;
|
|
52
|
+
if (baseUrl) env.OPENAI_BASE_URL = baseUrl;
|
|
53
|
+
const organization = explicit?.organization ?? processEnv.OPENAI_ORGANIZATION;
|
|
54
|
+
if (organization) env.OPENAI_ORGANIZATION = organization;
|
|
55
|
+
const project = explicit?.project ?? processEnv.OPENAI_PROJECT;
|
|
56
|
+
if (project) env.OPENAI_PROJECT = project;
|
|
57
|
+
return env;
|
|
58
|
+
}
|
|
59
|
+
function pickGateway(explicit, processEnv) {
|
|
60
|
+
const apiKey = explicit.apiKey ?? processEnv.AI_GATEWAY_API_KEY;
|
|
61
|
+
const baseUrl = explicit.baseUrl ?? processEnv.AI_GATEWAY_BASE_URL ?? "https://ai-gateway.vercel.sh/v1";
|
|
62
|
+
const env = {};
|
|
63
|
+
if (apiKey) {
|
|
64
|
+
env.AI_GATEWAY_API_KEY = apiKey;
|
|
65
|
+
env.CODEX_API_KEY = apiKey;
|
|
66
|
+
}
|
|
67
|
+
env.AI_GATEWAY_BASE_URL = baseUrl;
|
|
68
|
+
return env;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// src/codex-bridge-protocol.ts
|
|
72
|
+
import {
|
|
73
|
+
harnessV1BridgeInboundCommandSchemas,
|
|
74
|
+
harnessV1BridgeOutboundMessageSchema,
|
|
75
|
+
harnessV1BridgeReadySchema,
|
|
76
|
+
harnessV1BridgeStartBaseSchema
|
|
77
|
+
} from "@ai-sdk/harness";
|
|
78
|
+
import { z } from "zod/v4";
|
|
79
|
+
var outboundMessageSchema = harnessV1BridgeOutboundMessageSchema;
|
|
80
|
+
var startMessageSchema = harnessV1BridgeStartBaseSchema.extend({
|
|
81
|
+
instructions: z.string().optional(),
|
|
82
|
+
reasoningEffort: z.enum(["low", "medium", "high"]).optional(),
|
|
83
|
+
webSearch: z.boolean().optional(),
|
|
84
|
+
skills: z.array(
|
|
85
|
+
z.object({
|
|
86
|
+
name: z.string(),
|
|
87
|
+
description: z.string(),
|
|
88
|
+
content: z.string()
|
|
89
|
+
})
|
|
90
|
+
).optional(),
|
|
91
|
+
// Resume signal. When supplied, the bridge calls
|
|
92
|
+
// `codex.resumeThread(resumeThreadId, …)` instead of starting a fresh thread.
|
|
93
|
+
// The host sources the id from lifecycle state `data` cached from a prior
|
|
94
|
+
// `agent.detach`.
|
|
95
|
+
resumeThreadId: z.string().optional()
|
|
96
|
+
});
|
|
97
|
+
var inboundMessageSchema = z.discriminatedUnion("type", [
|
|
98
|
+
startMessageSchema,
|
|
99
|
+
...harnessV1BridgeInboundCommandSchemas
|
|
100
|
+
]);
|
|
101
|
+
var bridgeReadySchema = harnessV1BridgeReadySchema;
|
|
102
|
+
|
|
103
|
+
// src/codex-harness.ts
|
|
104
|
+
var DEFAULT_CODEX_MODEL = "gpt-5.3-codex";
|
|
105
|
+
var CODEX_BUILTIN_TOOLS = {
|
|
106
|
+
bash: commonTool("bash", {
|
|
107
|
+
nativeName: "shell",
|
|
108
|
+
toolUseKind: "bash",
|
|
109
|
+
description: "Execute a shell command",
|
|
110
|
+
inputSchema: z2.object({ command: z2.string() })
|
|
111
|
+
}),
|
|
112
|
+
webSearch: commonTool("webSearch", {
|
|
113
|
+
nativeName: "web_search",
|
|
114
|
+
toolUseKind: "readonly",
|
|
115
|
+
description: "Search the web",
|
|
116
|
+
inputSchema: z2.object({ query: z2.string() })
|
|
117
|
+
})
|
|
118
|
+
};
|
|
119
|
+
var BOOTSTRAP_DIR = "/tmp/harness/codex";
|
|
120
|
+
var bridgeCoordsSchema = z2.object({
|
|
121
|
+
port: z2.number(),
|
|
122
|
+
token: z2.string(),
|
|
123
|
+
lastSeenEventId: z2.number(),
|
|
124
|
+
sandboxId: z2.string().optional()
|
|
125
|
+
});
|
|
126
|
+
var codexResumeStateSchema = z2.object({
|
|
127
|
+
threadId: z2.string().optional(),
|
|
128
|
+
bridge: bridgeCoordsSchema.optional()
|
|
129
|
+
});
|
|
130
|
+
function createCodex(settings = {}) {
|
|
131
|
+
let cachedBootstrap;
|
|
132
|
+
return {
|
|
133
|
+
specificationVersion: "harness-v1",
|
|
134
|
+
harnessId: "codex",
|
|
135
|
+
builtinTools: CODEX_BUILTIN_TOOLS,
|
|
136
|
+
supportsBuiltinToolApprovals: false,
|
|
137
|
+
lifecycleStateSchema: codexResumeStateSchema,
|
|
138
|
+
getBootstrap: async () => {
|
|
139
|
+
if (cachedBootstrap != null) return cachedBootstrap;
|
|
140
|
+
const [pkg, lock, bridge, hostToolMcp] = await Promise.all([
|
|
141
|
+
readBridgeAsset("package.json"),
|
|
142
|
+
readBridgeAsset("pnpm-lock.yaml"),
|
|
143
|
+
readBridgeAsset("index.mjs"),
|
|
144
|
+
readBridgeAsset("host-tool-mcp.mjs")
|
|
145
|
+
]);
|
|
146
|
+
cachedBootstrap = {
|
|
147
|
+
harnessId: "codex",
|
|
148
|
+
bootstrapDir: BOOTSTRAP_DIR,
|
|
149
|
+
files: [
|
|
150
|
+
{ path: `${BOOTSTRAP_DIR}/package.json`, content: pkg },
|
|
151
|
+
{ path: `${BOOTSTRAP_DIR}/pnpm-lock.yaml`, content: lock },
|
|
152
|
+
{ path: `${BOOTSTRAP_DIR}/bridge.mjs`, content: bridge },
|
|
153
|
+
{
|
|
154
|
+
path: `${BOOTSTRAP_DIR}/host-tool-mcp.mjs`,
|
|
155
|
+
content: hostToolMcp
|
|
156
|
+
}
|
|
157
|
+
],
|
|
158
|
+
commands: [
|
|
159
|
+
{ command: `mkdir -p ${BOOTSTRAP_DIR}` },
|
|
160
|
+
{
|
|
161
|
+
command: `pnpm --dir ${BOOTSTRAP_DIR} install --frozen-lockfile --store-dir ${BOOTSTRAP_DIR}/.pnpm-store`
|
|
162
|
+
}
|
|
163
|
+
]
|
|
164
|
+
};
|
|
165
|
+
return cachedBootstrap;
|
|
166
|
+
},
|
|
167
|
+
doStart: async (startOpts) => {
|
|
168
|
+
if (startOpts.permissionMode != null && startOpts.permissionMode !== "allow-all") {
|
|
169
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
170
|
+
message: "Harness 'codex' does not support built-in tool approval requests; use permissionMode: 'allow-all'.",
|
|
171
|
+
harnessId: "codex"
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
const sandboxSession = startOpts.sandboxSession;
|
|
175
|
+
const session = sandboxSession.restricted();
|
|
176
|
+
const sandboxId = sandboxSession.id;
|
|
177
|
+
const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;
|
|
178
|
+
const isResume = lifecycleState != null;
|
|
179
|
+
const isContinue = startOpts.continueFrom != null;
|
|
180
|
+
const resumeData = isResume && typeof lifecycleState?.data === "object" ? lifecycleState.data : void 0;
|
|
181
|
+
const resumeThreadId = resumeData?.threadId;
|
|
182
|
+
const resumeThreadIdString = typeof resumeThreadId === "string" && resumeThreadId.length > 0 ? resumeThreadId : void 0;
|
|
183
|
+
const coords = resumeData?.bridge;
|
|
184
|
+
const workDir = startOpts.sessionWorkDir;
|
|
185
|
+
const sessionDataDir = `${sandboxSession.defaultWorkingDirectory}/.agent-runs/${startOpts.sessionId}`;
|
|
186
|
+
const bridgeStateDir = `${sessionDataDir}/bridge`;
|
|
187
|
+
const timeoutMs = settings.startupTimeoutMs ?? 12e4;
|
|
188
|
+
const report = startOpts.observability?.report;
|
|
189
|
+
const onDiagnostic = report ? (frame) => report(
|
|
190
|
+
harnessV1DiagnosticFromBridgeFrame(frame, {
|
|
191
|
+
sessionId: startOpts.sessionId,
|
|
192
|
+
timestamp: Date.now()
|
|
193
|
+
})
|
|
194
|
+
) : void 0;
|
|
195
|
+
if (coords) {
|
|
196
|
+
try {
|
|
197
|
+
const attachUrl = await sandboxSession.getPortUrl({
|
|
198
|
+
port: coords.port,
|
|
199
|
+
protocol: "ws"
|
|
200
|
+
}) + `?agent_bridge_token=${encodeURIComponent(coords.token)}`;
|
|
201
|
+
const attachChannel = new SandboxChannel({
|
|
202
|
+
connect: () => openWebSocket(attachUrl),
|
|
203
|
+
outboundSchema: outboundMessageSchema,
|
|
204
|
+
initialLastSeenEventId: coords.lastSeenEventId,
|
|
205
|
+
onDiagnostic
|
|
206
|
+
});
|
|
207
|
+
await attachChannel.open(isContinue ? { resume: true } : void 0);
|
|
208
|
+
return createSession({
|
|
209
|
+
sessionId: startOpts.sessionId,
|
|
210
|
+
channel: attachChannel,
|
|
211
|
+
// The live bridge was spawned by another process; no process handle.
|
|
212
|
+
proc: void 0,
|
|
213
|
+
skills: startOpts.skills,
|
|
214
|
+
model: settings.model ?? DEFAULT_CODEX_MODEL,
|
|
215
|
+
reasoningEffort: settings.reasoningEffort,
|
|
216
|
+
webSearch: settings.webSearch,
|
|
217
|
+
resumeThreadId: resumeThreadIdString,
|
|
218
|
+
isResume: true,
|
|
219
|
+
seedResumeThreadOnFirstPrompt: false,
|
|
220
|
+
rerunContinue: false,
|
|
221
|
+
bridgePort: coords.port,
|
|
222
|
+
bridgeToken: coords.token,
|
|
223
|
+
sandboxId,
|
|
224
|
+
debug: startOpts.observability?.debug,
|
|
225
|
+
permissionMode: startOpts.permissionMode
|
|
226
|
+
});
|
|
227
|
+
} catch {
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
let respawnStrategy = isResume ? "rerun" : void 0;
|
|
231
|
+
if (coords && isContinue) {
|
|
232
|
+
const logRaw = await Promise.resolve(
|
|
233
|
+
session.readTextFile({
|
|
234
|
+
path: `${bridgeStateDir}/event-log.ndjson`,
|
|
235
|
+
abortSignal: startOpts.abortSignal
|
|
236
|
+
})
|
|
237
|
+
).catch(() => null);
|
|
238
|
+
if (await classifyDiskLog(logRaw) === "replay") {
|
|
239
|
+
respawnStrategy = "replay";
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const port = resolveBridgePort(sandboxSession, settings.port);
|
|
243
|
+
const token = randomBytes(32).toString("hex");
|
|
244
|
+
const env = {
|
|
245
|
+
...resolveCodexEnv(settings.auth),
|
|
246
|
+
BRIDGE_CHANNEL_TOKEN: token,
|
|
247
|
+
BRIDGE_WS_PORT: String(port),
|
|
248
|
+
...respawnStrategy === "replay" ? { BRIDGE_REPLAY_FROM_DISK: "1" } : {}
|
|
249
|
+
};
|
|
250
|
+
if (respawnStrategy === void 0) {
|
|
251
|
+
await session.run({
|
|
252
|
+
command: `mkdir -p ${workDir} ${bridgeStateDir}`,
|
|
253
|
+
abortSignal: startOpts.abortSignal
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
const proc = await session.spawn({
|
|
257
|
+
command: `node ${BOOTSTRAP_DIR}/bridge.mjs --workdir ${workDir} --bridge-state-dir ${bridgeStateDir} --bootstrap-dir ${BOOTSTRAP_DIR}`,
|
|
258
|
+
env,
|
|
259
|
+
abortSignal: startOpts.abortSignal
|
|
260
|
+
});
|
|
261
|
+
const { port: boundPort } = await waitForBridgeReady({
|
|
262
|
+
proc,
|
|
263
|
+
timeoutMs,
|
|
264
|
+
abortSignal: startOpts.abortSignal
|
|
265
|
+
});
|
|
266
|
+
const wsUrl = await sandboxSession.getPortUrl({
|
|
267
|
+
port: boundPort,
|
|
268
|
+
protocol: "ws"
|
|
269
|
+
}) + `?agent_bridge_token=${encodeURIComponent(token)}`;
|
|
270
|
+
const channel = new SandboxChannel({
|
|
271
|
+
connect: () => openWebSocket(wsUrl),
|
|
272
|
+
outboundSchema: outboundMessageSchema,
|
|
273
|
+
onDiagnostic,
|
|
274
|
+
// In replay mode the respawned bridge reloaded the finished turn from
|
|
275
|
+
// disk; seed the cursor and resume so it streams the tail (incl.
|
|
276
|
+
// `finish`).
|
|
277
|
+
...respawnStrategy === "replay" ? { initialLastSeenEventId: coords?.lastSeenEventId ?? 0 } : {}
|
|
278
|
+
});
|
|
279
|
+
await channel.open(
|
|
280
|
+
respawnStrategy === "replay" ? { resume: true } : void 0
|
|
281
|
+
);
|
|
282
|
+
return createSession({
|
|
283
|
+
sessionId: startOpts.sessionId,
|
|
284
|
+
channel,
|
|
285
|
+
proc,
|
|
286
|
+
skills: startOpts.skills,
|
|
287
|
+
model: settings.model ?? DEFAULT_CODEX_MODEL,
|
|
288
|
+
reasoningEffort: settings.reasoningEffort,
|
|
289
|
+
webSearch: settings.webSearch,
|
|
290
|
+
resumeThreadId: resumeThreadIdString,
|
|
291
|
+
isResume: respawnStrategy !== void 0,
|
|
292
|
+
seedResumeThreadOnFirstPrompt: respawnStrategy !== void 0,
|
|
293
|
+
rerunContinue: respawnStrategy === "rerun",
|
|
294
|
+
bridgePort: boundPort,
|
|
295
|
+
bridgeToken: token,
|
|
296
|
+
sandboxId,
|
|
297
|
+
debug: startOpts.observability?.debug,
|
|
298
|
+
permissionMode: startOpts.permissionMode
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
function resolveBridgePort(sandboxSession, override) {
|
|
304
|
+
if (override !== void 0) return override;
|
|
305
|
+
if (sandboxSession.ports.length > 0) return sandboxSession.ports[0];
|
|
306
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
307
|
+
harnessId: "codex",
|
|
308
|
+
message: "The codex harness needs a TCP port exposed by the sandbox. Create the sandbox with `ports: [<port>]` or pass `createCodex({ port })`."
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
async function readBridgeAsset(name) {
|
|
312
|
+
const candidates = [
|
|
313
|
+
new URL(`./bridge/${name}`, import.meta.url),
|
|
314
|
+
new URL(`../bridge/${name}`, import.meta.url)
|
|
315
|
+
];
|
|
316
|
+
let lastErr;
|
|
317
|
+
for (const url of candidates) {
|
|
318
|
+
try {
|
|
319
|
+
return await readFile(fileURLToPath(url), "utf8");
|
|
320
|
+
} catch (err) {
|
|
321
|
+
const code = err.code;
|
|
322
|
+
if (code !== "ENOENT") throw err;
|
|
323
|
+
lastErr = err;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
throw lastErr ?? new Error(`bridge asset not found: ${name}`);
|
|
327
|
+
}
|
|
328
|
+
async function waitForBridgeReady({
|
|
329
|
+
proc,
|
|
330
|
+
timeoutMs,
|
|
331
|
+
abortSignal
|
|
332
|
+
}) {
|
|
333
|
+
const reader = proc.stdout.pipeThrough(new TextDecoderStream()).getReader();
|
|
334
|
+
const decoder = lineDecoder();
|
|
335
|
+
const deadline = Date.now() + timeoutMs;
|
|
336
|
+
try {
|
|
337
|
+
while (true) {
|
|
338
|
+
if (abortSignal?.aborted) {
|
|
339
|
+
await proc.kill();
|
|
340
|
+
throw abortSignal.reason ?? new DOMException("Aborted", "AbortError");
|
|
341
|
+
}
|
|
342
|
+
const remaining = deadline - Date.now();
|
|
343
|
+
if (remaining <= 0) {
|
|
344
|
+
await proc.kill();
|
|
345
|
+
throw new Error("codex bridge did not become ready in time.");
|
|
346
|
+
}
|
|
347
|
+
const { value, done } = await Promise.race([
|
|
348
|
+
reader.read(),
|
|
349
|
+
new Promise(
|
|
350
|
+
(resolve) => setTimeout(
|
|
351
|
+
() => resolve({ value: void 0, done: false }),
|
|
352
|
+
remaining
|
|
353
|
+
)
|
|
354
|
+
)
|
|
355
|
+
]);
|
|
356
|
+
if (done) {
|
|
357
|
+
throw new Error("codex bridge exited before becoming ready.");
|
|
358
|
+
}
|
|
359
|
+
if (value === void 0) continue;
|
|
360
|
+
for (const line of decoder.push(value)) {
|
|
361
|
+
const parsed = await safeParseJSON({
|
|
362
|
+
text: line,
|
|
363
|
+
schema: bridgeReadySchema
|
|
364
|
+
});
|
|
365
|
+
if (parsed.success) return { port: parsed.value.port };
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
} finally {
|
|
369
|
+
reader.releaseLock();
|
|
370
|
+
void drainRest(proc.stdout);
|
|
371
|
+
void forwardBridgeStderr(proc.stderr);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
function lineDecoder() {
|
|
375
|
+
let buffer = "";
|
|
376
|
+
return {
|
|
377
|
+
push(chunk) {
|
|
378
|
+
buffer += chunk;
|
|
379
|
+
const lines = [];
|
|
380
|
+
let nl;
|
|
381
|
+
while ((nl = buffer.indexOf("\n")) !== -1) {
|
|
382
|
+
const raw = buffer.slice(0, nl);
|
|
383
|
+
buffer = buffer.slice(nl + 1);
|
|
384
|
+
const line = raw.replace(/\r$/, "").trim();
|
|
385
|
+
if (line.length > 0) lines.push(line);
|
|
386
|
+
}
|
|
387
|
+
return lines;
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
async function forwardBridgeStderr(stream) {
|
|
392
|
+
try {
|
|
393
|
+
const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
|
|
394
|
+
while (true) {
|
|
395
|
+
const { value, done } = await reader.read();
|
|
396
|
+
if (done) return;
|
|
397
|
+
if (value) {
|
|
398
|
+
const trimmed = value.endsWith("\n") ? value.slice(0, -1) : value;
|
|
399
|
+
if (trimmed.length > 0) {
|
|
400
|
+
console.log(`[bridge stderr] ${trimmed}`);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
} catch {
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
async function drainRest(stream) {
|
|
408
|
+
try {
|
|
409
|
+
const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
|
|
410
|
+
while (true) {
|
|
411
|
+
const { done } = await reader.read();
|
|
412
|
+
if (done) return;
|
|
413
|
+
}
|
|
414
|
+
} catch {
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
function openWebSocket(url) {
|
|
418
|
+
return new Promise((resolve, reject) => {
|
|
419
|
+
const ws = new WebSocket(url);
|
|
420
|
+
const onOpen = () => {
|
|
421
|
+
ws.off("error", onError);
|
|
422
|
+
resolve(ws);
|
|
423
|
+
};
|
|
424
|
+
const onError = (err) => {
|
|
425
|
+
ws.off("open", onOpen);
|
|
426
|
+
reject(err);
|
|
427
|
+
};
|
|
428
|
+
ws.once("open", onOpen);
|
|
429
|
+
ws.once("error", onError);
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
function createSession({
|
|
433
|
+
sessionId,
|
|
434
|
+
channel,
|
|
435
|
+
proc,
|
|
436
|
+
skills,
|
|
437
|
+
model,
|
|
438
|
+
reasoningEffort,
|
|
439
|
+
webSearch,
|
|
440
|
+
resumeThreadId,
|
|
441
|
+
isResume,
|
|
442
|
+
seedResumeThreadOnFirstPrompt,
|
|
443
|
+
rerunContinue,
|
|
444
|
+
bridgePort,
|
|
445
|
+
bridgeToken,
|
|
446
|
+
sandboxId,
|
|
447
|
+
debug,
|
|
448
|
+
permissionMode
|
|
449
|
+
}) {
|
|
450
|
+
let stopped = false;
|
|
451
|
+
let stopPromise;
|
|
452
|
+
let pendingResumeThreadId = seedResumeThreadOnFirstPrompt ? resumeThreadId : void 0;
|
|
453
|
+
let instructionsApplied = isResume;
|
|
454
|
+
let latestThreadId = resumeThreadId;
|
|
455
|
+
channel.on("bridge-thread", (msg) => {
|
|
456
|
+
latestThreadId = msg.threadId;
|
|
457
|
+
});
|
|
458
|
+
const wireTurn = (turnOpts) => {
|
|
459
|
+
let pendingResolve;
|
|
460
|
+
let pendingReject;
|
|
461
|
+
const done = new Promise((resolve, reject) => {
|
|
462
|
+
pendingResolve = resolve;
|
|
463
|
+
pendingReject = reject;
|
|
464
|
+
});
|
|
465
|
+
const unsubs = [];
|
|
466
|
+
const forward = (event) => {
|
|
467
|
+
try {
|
|
468
|
+
turnOpts.emit(event);
|
|
469
|
+
} catch {
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
const eventTypes = [
|
|
473
|
+
"stream-start",
|
|
474
|
+
"text-start",
|
|
475
|
+
"text-delta",
|
|
476
|
+
"text-end",
|
|
477
|
+
"reasoning-start",
|
|
478
|
+
"reasoning-delta",
|
|
479
|
+
"reasoning-end",
|
|
480
|
+
"tool-call",
|
|
481
|
+
"tool-approval-request",
|
|
482
|
+
"tool-result",
|
|
483
|
+
"file-change",
|
|
484
|
+
"finish-step",
|
|
485
|
+
"raw"
|
|
486
|
+
];
|
|
487
|
+
let isSettled = false;
|
|
488
|
+
const settleSuccess = () => {
|
|
489
|
+
if (isSettled) return;
|
|
490
|
+
isSettled = true;
|
|
491
|
+
for (const u of unsubs) u();
|
|
492
|
+
pendingResolve();
|
|
493
|
+
};
|
|
494
|
+
const settleError = (err) => {
|
|
495
|
+
if (isSettled) return;
|
|
496
|
+
isSettled = true;
|
|
497
|
+
for (const u of unsubs) u();
|
|
498
|
+
pendingReject(err);
|
|
499
|
+
};
|
|
500
|
+
for (const type of eventTypes) {
|
|
501
|
+
unsubs.push(
|
|
502
|
+
channel.on(type, (msg) => {
|
|
503
|
+
forward(msg);
|
|
504
|
+
})
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
unsubs.push(
|
|
508
|
+
channel.on("finish", (msg) => {
|
|
509
|
+
forward(msg);
|
|
510
|
+
settleSuccess();
|
|
511
|
+
})
|
|
512
|
+
);
|
|
513
|
+
unsubs.push(
|
|
514
|
+
channel.on("error", (msg) => {
|
|
515
|
+
forward(msg);
|
|
516
|
+
settleError(msg.error);
|
|
517
|
+
})
|
|
518
|
+
);
|
|
519
|
+
const onClose = (_code, reason) => {
|
|
520
|
+
if (isSettled) return;
|
|
521
|
+
if (reason === "suspended") {
|
|
522
|
+
settleSuccess();
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
settleError(new Error("codex bridge closed before the turn finished."));
|
|
526
|
+
};
|
|
527
|
+
channel.onClose(onClose);
|
|
528
|
+
const onAbort = () => {
|
|
529
|
+
if (isSettled) return;
|
|
530
|
+
try {
|
|
531
|
+
channel.send({ type: "abort" });
|
|
532
|
+
} catch {
|
|
533
|
+
}
|
|
534
|
+
settleError(
|
|
535
|
+
turnOpts.abortSignal?.reason ?? new DOMException("Aborted", "AbortError")
|
|
536
|
+
);
|
|
537
|
+
};
|
|
538
|
+
if (turnOpts.abortSignal) {
|
|
539
|
+
if (turnOpts.abortSignal.aborted) {
|
|
540
|
+
onAbort();
|
|
541
|
+
} else {
|
|
542
|
+
turnOpts.abortSignal.addEventListener("abort", onAbort, {
|
|
543
|
+
once: true
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return {
|
|
548
|
+
submitToolResult: async (input) => {
|
|
549
|
+
channel.send({
|
|
550
|
+
type: "tool-result",
|
|
551
|
+
toolCallId: input.toolCallId,
|
|
552
|
+
output: input.output,
|
|
553
|
+
isError: input.isError
|
|
554
|
+
});
|
|
555
|
+
},
|
|
556
|
+
submitToolApproval: async (input) => {
|
|
557
|
+
channel.send({
|
|
558
|
+
type: "tool-approval-response",
|
|
559
|
+
approvalId: input.approvalId,
|
|
560
|
+
approved: input.approved,
|
|
561
|
+
reason: input.reason
|
|
562
|
+
});
|
|
563
|
+
},
|
|
564
|
+
submitUserMessage: async (text) => {
|
|
565
|
+
channel.send({ type: "user-message", text });
|
|
566
|
+
},
|
|
567
|
+
done
|
|
568
|
+
};
|
|
569
|
+
};
|
|
570
|
+
return {
|
|
571
|
+
sessionId,
|
|
572
|
+
isResume,
|
|
573
|
+
modelId: model,
|
|
574
|
+
doPromptTurn: async (promptOpts) => {
|
|
575
|
+
const control = wireTurn({
|
|
576
|
+
emit: promptOpts.emit,
|
|
577
|
+
abortSignal: promptOpts.abortSignal
|
|
578
|
+
});
|
|
579
|
+
const applyInstructions = !instructionsApplied && !!promptOpts.instructions;
|
|
580
|
+
instructionsApplied = true;
|
|
581
|
+
const startMessage = {
|
|
582
|
+
type: "start",
|
|
583
|
+
prompt: extractUserText(promptOpts.prompt),
|
|
584
|
+
...applyInstructions ? { instructions: promptOpts.instructions } : {},
|
|
585
|
+
tools: (promptOpts.tools ?? []).map((t) => ({
|
|
586
|
+
name: t.name,
|
|
587
|
+
description: t.description,
|
|
588
|
+
inputSchema: t.inputSchema
|
|
589
|
+
})),
|
|
590
|
+
model,
|
|
591
|
+
reasoningEffort,
|
|
592
|
+
webSearch,
|
|
593
|
+
...permissionMode ? { permissionMode } : {},
|
|
594
|
+
...skills && skills.length > 0 ? {
|
|
595
|
+
skills: skills.map((s) => ({
|
|
596
|
+
name: s.name,
|
|
597
|
+
description: s.description,
|
|
598
|
+
content: s.content
|
|
599
|
+
}))
|
|
600
|
+
} : {},
|
|
601
|
+
...pendingResumeThreadId ? { resumeThreadId: pendingResumeThreadId } : {},
|
|
602
|
+
...debug ? { debug } : {}
|
|
603
|
+
};
|
|
604
|
+
pendingResumeThreadId = void 0;
|
|
605
|
+
channel.send(startMessage);
|
|
606
|
+
return control;
|
|
607
|
+
},
|
|
608
|
+
doContinueTurn: async (continueOpts) => {
|
|
609
|
+
const control = wireTurn({
|
|
610
|
+
emit: continueOpts.emit,
|
|
611
|
+
abortSignal: continueOpts.abortSignal
|
|
612
|
+
});
|
|
613
|
+
if (rerunContinue) {
|
|
614
|
+
const threadId = pendingResumeThreadId ?? latestThreadId;
|
|
615
|
+
pendingResumeThreadId = void 0;
|
|
616
|
+
channel.send({
|
|
617
|
+
type: "start",
|
|
618
|
+
/*
|
|
619
|
+
* A continuation nudge rather than an empty prompt: `resumeThreadId`
|
|
620
|
+
* rehydrates the prior thread, and this is the new user turn that
|
|
621
|
+
* drives it forward. Keeping it non-empty avoids handing the runtime
|
|
622
|
+
* an empty user message (and mirrors the claude-code adapter, where an
|
|
623
|
+
* empty text block trips the Anthropic API's `cache_control` rule).
|
|
624
|
+
*/
|
|
625
|
+
prompt: "Continue.",
|
|
626
|
+
tools: (continueOpts.tools ?? []).map((t) => ({
|
|
627
|
+
name: t.name,
|
|
628
|
+
description: t.description,
|
|
629
|
+
inputSchema: t.inputSchema
|
|
630
|
+
})),
|
|
631
|
+
model,
|
|
632
|
+
reasoningEffort,
|
|
633
|
+
webSearch,
|
|
634
|
+
...permissionMode ? { permissionMode } : {},
|
|
635
|
+
...threadId ? { resumeThreadId: threadId } : {},
|
|
636
|
+
...debug ? { debug } : {}
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
return control;
|
|
640
|
+
},
|
|
641
|
+
doCompact: async () => {
|
|
642
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
643
|
+
message: "Harness 'codex' does not support manual compaction; Codex auto-compacts its context internally.",
|
|
644
|
+
harnessId: "codex"
|
|
645
|
+
});
|
|
646
|
+
},
|
|
647
|
+
doDetach: async () => {
|
|
648
|
+
if (stopped) {
|
|
649
|
+
throw new Error(
|
|
650
|
+
`codex session ${sessionId} is already stopped; cannot detach.`
|
|
651
|
+
);
|
|
652
|
+
}
|
|
653
|
+
stopped = true;
|
|
654
|
+
const lastSeenEventId = await channel.suspend();
|
|
655
|
+
const payload = {
|
|
656
|
+
type: "resume-session",
|
|
657
|
+
harnessId: "codex",
|
|
658
|
+
specificationVersion: "harness-v1",
|
|
659
|
+
data: {
|
|
660
|
+
...latestThreadId ? { threadId: latestThreadId } : {},
|
|
661
|
+
bridge: {
|
|
662
|
+
port: bridgePort,
|
|
663
|
+
token: bridgeToken,
|
|
664
|
+
lastSeenEventId,
|
|
665
|
+
sandboxId
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
return payload;
|
|
670
|
+
},
|
|
671
|
+
doDestroy: async () => {
|
|
672
|
+
if (stopped) return stopPromise;
|
|
673
|
+
stopped = true;
|
|
674
|
+
stopPromise = (async () => {
|
|
675
|
+
channel.beginClose();
|
|
676
|
+
try {
|
|
677
|
+
if (!channel.isClosed()) {
|
|
678
|
+
channel.send({ type: "shutdown" });
|
|
679
|
+
}
|
|
680
|
+
} catch {
|
|
681
|
+
}
|
|
682
|
+
let stopTimer;
|
|
683
|
+
try {
|
|
684
|
+
if (proc) {
|
|
685
|
+
await Promise.race([
|
|
686
|
+
proc.wait(),
|
|
687
|
+
new Promise((resolve) => {
|
|
688
|
+
stopTimer = setTimeout(resolve, 5e3);
|
|
689
|
+
stopTimer.unref?.();
|
|
690
|
+
})
|
|
691
|
+
]);
|
|
692
|
+
}
|
|
693
|
+
} finally {
|
|
694
|
+
if (stopTimer) clearTimeout(stopTimer);
|
|
695
|
+
try {
|
|
696
|
+
await proc?.kill();
|
|
697
|
+
} catch {
|
|
698
|
+
}
|
|
699
|
+
channel.close();
|
|
700
|
+
}
|
|
701
|
+
})();
|
|
702
|
+
return stopPromise;
|
|
703
|
+
},
|
|
704
|
+
doStop: async () => {
|
|
705
|
+
if (stopped) {
|
|
706
|
+
throw new Error(
|
|
707
|
+
`codex session ${sessionId} is already stopped; cannot stop.`
|
|
708
|
+
);
|
|
709
|
+
}
|
|
710
|
+
stopped = true;
|
|
711
|
+
channel.beginClose();
|
|
712
|
+
const data = channel.isClosed() ? {} : await new Promise((resolve, reject) => {
|
|
713
|
+
const timer = setTimeout(() => {
|
|
714
|
+
unsub();
|
|
715
|
+
reject(
|
|
716
|
+
new Error(
|
|
717
|
+
`codex session ${sessionId} did not reply to detach within 5s.`
|
|
718
|
+
)
|
|
719
|
+
);
|
|
720
|
+
}, 5e3);
|
|
721
|
+
timer.unref?.();
|
|
722
|
+
const unsub = channel.on("bridge-detach", (msg) => {
|
|
723
|
+
clearTimeout(timer);
|
|
724
|
+
unsub();
|
|
725
|
+
resolve(msg.data);
|
|
726
|
+
});
|
|
727
|
+
try {
|
|
728
|
+
channel.send({ type: "detach" });
|
|
729
|
+
} catch (err) {
|
|
730
|
+
clearTimeout(timer);
|
|
731
|
+
unsub();
|
|
732
|
+
reject(err);
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
let stopTimer;
|
|
736
|
+
try {
|
|
737
|
+
if (proc) {
|
|
738
|
+
await Promise.race([
|
|
739
|
+
proc.wait(),
|
|
740
|
+
new Promise((resolve) => {
|
|
741
|
+
stopTimer = setTimeout(resolve, 5e3);
|
|
742
|
+
stopTimer.unref?.();
|
|
743
|
+
})
|
|
744
|
+
]);
|
|
745
|
+
}
|
|
746
|
+
} finally {
|
|
747
|
+
if (stopTimer) clearTimeout(stopTimer);
|
|
748
|
+
try {
|
|
749
|
+
await proc?.kill();
|
|
750
|
+
} catch {
|
|
751
|
+
}
|
|
752
|
+
channel.close();
|
|
753
|
+
}
|
|
754
|
+
const payload = {
|
|
755
|
+
type: "resume-session",
|
|
756
|
+
harnessId: "codex",
|
|
757
|
+
specificationVersion: "harness-v1",
|
|
758
|
+
data: data ?? {}
|
|
759
|
+
};
|
|
760
|
+
return payload;
|
|
761
|
+
},
|
|
762
|
+
doSuspendTurn: async () => {
|
|
763
|
+
if (stopped) {
|
|
764
|
+
throw new Error(
|
|
765
|
+
`codex session ${sessionId} is stopped; cannot suspend.`
|
|
766
|
+
);
|
|
767
|
+
}
|
|
768
|
+
stopped = true;
|
|
769
|
+
const lastSeenEventId = await channel.suspend();
|
|
770
|
+
const payload = {
|
|
771
|
+
type: "continue-turn",
|
|
772
|
+
harnessId: "codex",
|
|
773
|
+
specificationVersion: "harness-v1",
|
|
774
|
+
data: {
|
|
775
|
+
...latestThreadId ? { threadId: latestThreadId } : {},
|
|
776
|
+
bridge: {
|
|
777
|
+
port: bridgePort,
|
|
778
|
+
token: bridgeToken,
|
|
779
|
+
lastSeenEventId,
|
|
780
|
+
sandboxId
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
};
|
|
784
|
+
return payload;
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
function extractUserText(prompt) {
|
|
789
|
+
if (typeof prompt === "string") return prompt;
|
|
790
|
+
const { content } = prompt;
|
|
791
|
+
if (typeof content === "string") return content;
|
|
792
|
+
const parts = [];
|
|
793
|
+
for (const part of content) {
|
|
794
|
+
if (part.type !== "text") {
|
|
795
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
796
|
+
harnessId: "codex",
|
|
797
|
+
message: `The codex harness does not yet support user message parts of type '${part.type}'. Pass a string or a user message whose content contains only text parts.`
|
|
798
|
+
});
|
|
799
|
+
}
|
|
800
|
+
parts.push(part.text);
|
|
801
|
+
}
|
|
802
|
+
return parts.join("\n\n");
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// src/index.ts
|
|
806
|
+
var codex = createCodex();
|
|
807
|
+
export {
|
|
808
|
+
codex,
|
|
809
|
+
createCodex
|
|
810
|
+
};
|
|
811
|
+
//# sourceMappingURL=index.js.map
|