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