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

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