@ai-sdk/harness-codex 0.0.0 → 1.0.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1029 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { fileURLToPath } from 'node:url';
4
+ import {
5
+ commonTool,
6
+ HarnessCapabilityUnsupportedError,
7
+ harnessV1DiagnosticFromBridgeFrame,
8
+ type HarnessV1,
9
+ type HarnessV1Bootstrap,
10
+ type HarnessV1DebugConfig,
11
+ type HarnessV1BuiltinTool,
12
+ type HarnessV1ContinueTurnState,
13
+ type HarnessV1Prompt,
14
+ type HarnessV1PromptControl,
15
+ type HarnessV1ResumeSessionState,
16
+ type HarnessV1NetworkSandboxSession,
17
+ type HarnessV1PermissionMode,
18
+ type HarnessV1Session,
19
+ type HarnessV1Skill,
20
+ type HarnessV1StreamPart,
21
+ } from '@ai-sdk/harness';
22
+ import { classifyDiskLog, SandboxChannel } from '@ai-sdk/harness/utils';
23
+ import {
24
+ safeParseJSON,
25
+ type Experimental_SandboxProcess,
26
+ } from '@ai-sdk/provider-utils';
27
+ import { WebSocket } from 'ws';
28
+ import { z } from 'zod';
29
+ import { resolveCodexEnv, type CodexAuthOptions } from './codex-auth';
30
+ import {
31
+ bridgeReadySchema,
32
+ outboundMessageSchema,
33
+ type InboundMessage,
34
+ type OutboundMessage,
35
+ } from './codex-bridge-protocol';
36
+
37
+ type CodexChannel = SandboxChannel<OutboundMessage, InboundMessage>;
38
+ type CodexRespawnStrategy = 'replay' | 'rerun';
39
+
40
+ /*
41
+ * The model the adapter pins when the consumer configures none. The Codex SDK
42
+ * does not report the model it resolves to at runtime (no model field on any
43
+ * event), and exposes no default-model constant, so we pin the latest
44
+ * codex-specialized model available for the bundled `@openai/codex@0.130.0`
45
+ * (published 2026-05-08): `gpt-5.3-codex` (released 2026-02). Keep this in sync
46
+ * when bumping the codex SDK/binary. Passing it explicitly makes the resolved
47
+ * model deterministic and the telemetry (`gen_ai.request.model`) accurate.
48
+ */
49
+ const DEFAULT_CODEX_MODEL = 'gpt-5.3-codex';
50
+
51
+ export type CodexHarnessSettings = {
52
+ readonly auth?: CodexAuthOptions;
53
+ /**
54
+ * OpenAI model id the underlying `codex` CLI should use. Leaving this unset
55
+ * pins the adapter default (`DEFAULT_CODEX_MODEL`).
56
+ */
57
+ readonly model?: string;
58
+ /**
59
+ * Reasoning effort for reasoning-capable models. Leaving this unset
60
+ * defers to the CLI's default.
61
+ */
62
+ readonly reasoningEffort?: 'low' | 'medium' | 'high';
63
+ /**
64
+ * When `true`, allow the underlying runtime to use live web search.
65
+ */
66
+ readonly webSearch?: boolean;
67
+ /**
68
+ * Override the port the bridge binds inside the sandbox. By default the
69
+ * adapter uses the first port the sandbox declares via `sandbox.ports`.
70
+ * Only set this if the sandbox declares multiple ports and the first one
71
+ * is reserved for something else.
72
+ */
73
+ readonly port?: number;
74
+ /** Maximum milliseconds to wait for the bridge to advertise its port. Defaults to 120000. */
75
+ readonly startupTimeoutMs?: number;
76
+ };
77
+
78
+ /*
79
+ * Every native tool the Codex CLI can invoke as a model-callable tool,
80
+ * declared as a `ToolSet` keyed by what the bridge emits as `toolName` on
81
+ * the wire (`commonName ?? nativeName`). Schemas reflect the `ThreadItem`
82
+ * union in `@openai/codex-sdk`'s `dist/index.d.ts`.
83
+ *
84
+ * Codex's other native operations (`apply_patch`, todo planning) surface
85
+ * only as side-effect events (`file_change`, `todo_list`) and are not
86
+ * model-callable tools — they don't appear here.
87
+ */
88
+ const CODEX_BUILTIN_TOOLS = {
89
+ bash: commonTool('bash', {
90
+ nativeName: 'shell',
91
+ toolUseKind: 'bash',
92
+ description: 'Execute a shell command',
93
+ inputSchema: z.object({ command: z.string() }),
94
+ }),
95
+ webSearch: commonTool('webSearch', {
96
+ nativeName: 'web_search',
97
+ toolUseKind: 'readonly',
98
+ description: 'Search the web',
99
+ inputSchema: z.object({ query: z.string() }),
100
+ }),
101
+ } as const satisfies Record<string, HarnessV1BuiltinTool<any, any>>;
102
+
103
+ /*
104
+ * Bootstrap lives in /tmp because it's pure derived state — the harness can
105
+ * reinstall the CLI and bridge files on any fresh sandbox from the recipe.
106
+ * Persistence comes from the sandbox provider's snapshot, not the path.
107
+ *
108
+ * The session work dir (`startOpts.sessionWorkDir`) and the bridge-state dir
109
+ * derived from `sandboxSession.defaultWorkingDirectory` both live under the sandbox's
110
+ * default working directory — the provider's persistent mount — so the
111
+ * workdir's contents (the codex CLI shim and any files the agent edits) and
112
+ * the bridge state files survive both detach -> attach and
113
+ * stop -> snapshot -> resume cycles.
114
+ */
115
+ const BOOTSTRAP_DIR = '/tmp/harness/codex';
116
+
117
+ /**
118
+ * Live bridge coordinates returned by `doDetach()` and `doSuspendTurn()`. A
119
+ * future process uses them to reopen a socket to the still-running bridge
120
+ * (`attach`) instead of re-spawning it. Absent on a `doStop()` payload.
121
+ */
122
+ const bridgeCoordsSchema = z.object({
123
+ port: z.number(),
124
+ token: z.string(),
125
+ lastSeenEventId: z.number(),
126
+ sandboxId: z.string().optional(),
127
+ });
128
+
129
+ /**
130
+ * Schema for the adapter-specific lifecycle `data` payload Codex produces.
131
+ * `threadId` is what `codex.resumeThread(...)` requires for the replay/rerun
132
+ * rungs; the sandbox lookup is handled separately via
133
+ * `provider.resumeSession({ sessionId })`. `bridge` carries live coordinates
134
+ * for cross-process `attach` (present on `doDetach()` and `doSuspendTurn()`
135
+ * payloads).
136
+ */
137
+ const codexResumeStateSchema = z.object({
138
+ threadId: z.string().optional(),
139
+ bridge: bridgeCoordsSchema.optional(),
140
+ });
141
+
142
+ type CodexBridgeCoords = z.infer<typeof bridgeCoordsSchema>;
143
+
144
+ export function createCodex(
145
+ settings: CodexHarnessSettings = {},
146
+ ): HarnessV1<typeof CODEX_BUILTIN_TOOLS> {
147
+ let cachedBootstrap: HarnessV1Bootstrap | undefined;
148
+
149
+ return {
150
+ specificationVersion: 'harness-v1',
151
+ harnessId: 'codex',
152
+ builtinTools: CODEX_BUILTIN_TOOLS,
153
+ supportsBuiltinToolApprovals: false,
154
+ lifecycleStateSchema: codexResumeStateSchema,
155
+ getBootstrap: async () => {
156
+ if (cachedBootstrap != null) return cachedBootstrap;
157
+ const [pkg, lock, bridge, hostToolMcp] = await Promise.all([
158
+ readBridgeAsset('package.json'),
159
+ readBridgeAsset('pnpm-lock.yaml'),
160
+ readBridgeAsset('index.mjs'),
161
+ readBridgeAsset('host-tool-mcp.mjs'),
162
+ ]);
163
+ cachedBootstrap = {
164
+ harnessId: 'codex',
165
+ bootstrapDir: BOOTSTRAP_DIR,
166
+ files: [
167
+ { path: `${BOOTSTRAP_DIR}/package.json`, content: pkg },
168
+ { path: `${BOOTSTRAP_DIR}/pnpm-lock.yaml`, content: lock },
169
+ { path: `${BOOTSTRAP_DIR}/bridge.mjs`, content: bridge },
170
+ {
171
+ path: `${BOOTSTRAP_DIR}/host-tool-mcp.mjs`,
172
+ content: hostToolMcp,
173
+ },
174
+ ],
175
+ commands: [
176
+ { command: `mkdir -p ${BOOTSTRAP_DIR}` },
177
+ {
178
+ command: `pnpm --dir ${BOOTSTRAP_DIR} install --frozen-lockfile --store-dir ${BOOTSTRAP_DIR}/.pnpm-store`,
179
+ },
180
+ ],
181
+ };
182
+ return cachedBootstrap;
183
+ },
184
+ doStart: async startOpts => {
185
+ if (
186
+ startOpts.permissionMode != null &&
187
+ startOpts.permissionMode !== 'allow-all'
188
+ ) {
189
+ throw new HarnessCapabilityUnsupportedError({
190
+ message:
191
+ "Harness 'codex' does not support built-in tool approval requests; use permissionMode: 'allow-all'.",
192
+ harnessId: 'codex',
193
+ });
194
+ }
195
+ const sandboxSession = startOpts.sandboxSession;
196
+ const session = sandboxSession.restricted();
197
+ const sandboxId = sandboxSession.id;
198
+ const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;
199
+ const isResume = lifecycleState != null;
200
+ const isContinue = startOpts.continueFrom != null;
201
+ const resumeData =
202
+ isResume && typeof lifecycleState?.data === 'object'
203
+ ? (lifecycleState.data as {
204
+ threadId?: unknown;
205
+ bridge?: CodexBridgeCoords;
206
+ })
207
+ : undefined;
208
+ const resumeThreadId = resumeData?.threadId;
209
+ const resumeThreadIdString =
210
+ typeof resumeThreadId === 'string' && resumeThreadId.length > 0
211
+ ? resumeThreadId
212
+ : undefined;
213
+ const coords = resumeData?.bridge;
214
+
215
+ const workDir = startOpts.sessionWorkDir;
216
+ const sessionDataDir = `${sandboxSession.defaultWorkingDirectory}/.agent-runs/${startOpts.sessionId}`;
217
+ const bridgeStateDir = `${sessionDataDir}/bridge`;
218
+ const timeoutMs = settings.startupTimeoutMs ?? 120_000;
219
+
220
+ // Normalize each forwarded bridge diagnostics frame into the general
221
+ // `HarnessV1Diagnostic` and report it. The adapter does no telemetry work
222
+ // beyond this transport→emission mapping.
223
+ const report = startOpts.observability?.report;
224
+ const onDiagnostic = report
225
+ ? (frame: Parameters<typeof harnessV1DiagnosticFromBridgeFrame>[0]) =>
226
+ report(
227
+ harnessV1DiagnosticFromBridgeFrame(frame, {
228
+ sessionId: startOpts.sessionId,
229
+ timestamp: Date.now(),
230
+ }),
231
+ )
232
+ : undefined;
233
+
234
+ /*
235
+ * Rung 1 — ATTACH. With live coordinates, reopen a socket to the
236
+ * still-running bridge. Parked between-turn sessions just attach and wait
237
+ * for the next `start`; suspended in-flight turns request replay of
238
+ * everything past the persisted cursor. No spawn, no fresh token. If the
239
+ * bridge is gone the open throws and we fall through to a spawn-based
240
+ * recovery.
241
+ */
242
+ if (coords) {
243
+ try {
244
+ const attachUrl =
245
+ (await sandboxSession.getPortUrl({
246
+ port: coords.port,
247
+ protocol: 'ws',
248
+ })) + `?agent_bridge_token=${encodeURIComponent(coords.token)}`;
249
+ const attachChannel: CodexChannel = new SandboxChannel({
250
+ connect: () => openWebSocket(attachUrl),
251
+ outboundSchema: outboundMessageSchema,
252
+ initialLastSeenEventId: coords.lastSeenEventId,
253
+ onDiagnostic,
254
+ });
255
+ await attachChannel.open(isContinue ? { resume: true } : undefined);
256
+ return createSession({
257
+ sessionId: startOpts.sessionId,
258
+ channel: attachChannel,
259
+ // The live bridge was spawned by another process; no process handle.
260
+ proc: undefined,
261
+ skills: startOpts.skills,
262
+ model: settings.model ?? DEFAULT_CODEX_MODEL,
263
+ reasoningEffort: settings.reasoningEffort,
264
+ webSearch: settings.webSearch,
265
+ resumeThreadId: resumeThreadIdString,
266
+ isResume: true,
267
+ seedResumeThreadOnFirstPrompt: false,
268
+ rerunContinue: false,
269
+ bridgePort: coords.port,
270
+ bridgeToken: coords.token,
271
+ sandboxId,
272
+ debug: startOpts.observability?.debug,
273
+ permissionMode: startOpts.permissionMode,
274
+ });
275
+ } catch {
276
+ // Bridge no longer reachable — recover by respawning below.
277
+ }
278
+ }
279
+
280
+ /*
281
+ * Rungs 2/3 — REPLAY vs RERUN. Respawn the bridge. `replay` is only sound
282
+ * for `continueFrom`: those coordinates include the cursor the on-disk
283
+ * log is replayed *from*. `resumeFrom` is a between-turn resume; even when
284
+ * it carries bridge coordinates, replaying the previous turn would
285
+ * re-deliver stale events into the next turn. Those resumes always `rerun`
286
+ * via `codex.resumeThread(threadId)` when attach is unavailable.
287
+ */
288
+ let respawnStrategy: CodexRespawnStrategy | undefined = isResume
289
+ ? 'rerun'
290
+ : undefined;
291
+ if (coords && isContinue) {
292
+ const logRaw = await Promise.resolve(
293
+ session.readTextFile({
294
+ path: `${bridgeStateDir}/event-log.ndjson`,
295
+ abortSignal: startOpts.abortSignal,
296
+ }),
297
+ ).catch(() => null);
298
+ if ((await classifyDiskLog(logRaw)) === 'replay') {
299
+ respawnStrategy = 'replay';
300
+ }
301
+ }
302
+
303
+ const port = resolveBridgePort(sandboxSession, settings.port);
304
+ const token = randomBytes(32).toString('hex');
305
+ const env = {
306
+ ...resolveCodexEnv(settings.auth),
307
+ BRIDGE_CHANNEL_TOKEN: token,
308
+ BRIDGE_WS_PORT: String(port),
309
+ ...(respawnStrategy === 'replay'
310
+ ? { BRIDGE_REPLAY_FROM_DISK: '1' }
311
+ : {}),
312
+ };
313
+
314
+ if (respawnStrategy === undefined) {
315
+ await session.run({
316
+ command: `mkdir -p ${workDir} ${bridgeStateDir}`,
317
+ abortSignal: startOpts.abortSignal,
318
+ });
319
+ }
320
+
321
+ const proc = await session.spawn({
322
+ command: `node ${BOOTSTRAP_DIR}/bridge.mjs --workdir ${workDir} --bridge-state-dir ${bridgeStateDir} --bootstrap-dir ${BOOTSTRAP_DIR}`,
323
+ env,
324
+ abortSignal: startOpts.abortSignal,
325
+ });
326
+
327
+ const { port: boundPort } = await waitForBridgeReady({
328
+ proc,
329
+ timeoutMs,
330
+ abortSignal: startOpts.abortSignal,
331
+ });
332
+
333
+ const wsUrl =
334
+ (await sandboxSession.getPortUrl({
335
+ port: boundPort,
336
+ protocol: 'ws',
337
+ })) + `?agent_bridge_token=${encodeURIComponent(token)}`;
338
+
339
+ const channel: CodexChannel = new SandboxChannel({
340
+ connect: () => openWebSocket(wsUrl),
341
+ outboundSchema: outboundMessageSchema,
342
+ onDiagnostic,
343
+ // In replay mode the respawned bridge reloaded the finished turn from
344
+ // disk; seed the cursor and resume so it streams the tail (incl.
345
+ // `finish`).
346
+ ...(respawnStrategy === 'replay'
347
+ ? { initialLastSeenEventId: coords?.lastSeenEventId ?? 0 }
348
+ : {}),
349
+ });
350
+ await channel.open(
351
+ respawnStrategy === 'replay' ? { resume: true } : undefined,
352
+ );
353
+
354
+ return createSession({
355
+ sessionId: startOpts.sessionId,
356
+ channel,
357
+ proc,
358
+ skills: startOpts.skills,
359
+ model: settings.model ?? DEFAULT_CODEX_MODEL,
360
+ reasoningEffort: settings.reasoningEffort,
361
+ webSearch: settings.webSearch,
362
+ resumeThreadId: resumeThreadIdString,
363
+ isResume: respawnStrategy !== undefined,
364
+ seedResumeThreadOnFirstPrompt: respawnStrategy !== undefined,
365
+ rerunContinue: respawnStrategy === 'rerun',
366
+ bridgePort: boundPort,
367
+ bridgeToken: token,
368
+ sandboxId,
369
+ debug: startOpts.observability?.debug,
370
+ permissionMode: startOpts.permissionMode,
371
+ });
372
+ },
373
+ };
374
+ }
375
+
376
+ function resolveBridgePort(
377
+ sandboxSession: HarnessV1NetworkSandboxSession,
378
+ override: number | undefined,
379
+ ): number {
380
+ if (override !== undefined) return override;
381
+ if (sandboxSession.ports.length > 0) return sandboxSession.ports[0];
382
+ throw new HarnessCapabilityUnsupportedError({
383
+ harnessId: 'codex',
384
+ message:
385
+ 'The codex harness needs a TCP port exposed by the sandbox. ' +
386
+ 'Create the sandbox with `ports: [<port>]` or pass `createCodex({ port })`.',
387
+ });
388
+ }
389
+
390
+ async function readBridgeAsset(name: string): Promise<string> {
391
+ const candidates = [
392
+ new URL(`./bridge/${name}`, import.meta.url),
393
+ new URL(`../bridge/${name}`, import.meta.url),
394
+ ];
395
+ let lastErr: unknown;
396
+ for (const url of candidates) {
397
+ try {
398
+ return await readFile(fileURLToPath(url), 'utf8');
399
+ } catch (err) {
400
+ const code = (err as NodeJS.ErrnoException).code;
401
+ if (code !== 'ENOENT') throw err;
402
+ lastErr = err;
403
+ }
404
+ }
405
+ throw lastErr ?? new Error(`bridge asset not found: ${name}`);
406
+ }
407
+
408
+ async function waitForBridgeReady({
409
+ proc,
410
+ timeoutMs,
411
+ abortSignal,
412
+ }: {
413
+ proc: Experimental_SandboxProcess;
414
+ timeoutMs: number;
415
+ abortSignal: AbortSignal | undefined;
416
+ }): Promise<{ port: number }> {
417
+ const reader = proc.stdout.pipeThrough(new TextDecoderStream()).getReader();
418
+
419
+ const decoder = lineDecoder();
420
+
421
+ const deadline = Date.now() + timeoutMs;
422
+ try {
423
+ while (true) {
424
+ if (abortSignal?.aborted) {
425
+ await proc.kill();
426
+ throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');
427
+ }
428
+ const remaining = deadline - Date.now();
429
+ if (remaining <= 0) {
430
+ await proc.kill();
431
+ throw new Error('codex bridge did not become ready in time.');
432
+ }
433
+ const { value, done } = (await Promise.race([
434
+ reader.read(),
435
+ new Promise(resolve =>
436
+ setTimeout(
437
+ () => resolve({ value: undefined, done: false }),
438
+ remaining,
439
+ ),
440
+ ),
441
+ ])) as ReadableStreamReadResult<string>;
442
+ if (done) {
443
+ throw new Error('codex bridge exited before becoming ready.');
444
+ }
445
+ if (value === undefined) continue;
446
+ for (const line of decoder.push(value)) {
447
+ const parsed = await safeParseJSON({
448
+ text: line,
449
+ schema: bridgeReadySchema,
450
+ });
451
+ if (parsed.success) return { port: parsed.value.port };
452
+ }
453
+ }
454
+ } finally {
455
+ reader.releaseLock();
456
+ void drainRest(proc.stdout);
457
+ /*
458
+ * Bridge stderr is the only diagnostic channel for what happens
459
+ * inside the sandbox once the bridge is running (uncaught
460
+ * exceptions, Codex SDK errors, network failures). Forward it
461
+ * line-by-line to the host console so a mid-turn bridge crash can
462
+ * be inspected from `pnpm dev` logs without redeploying. The
463
+ * bridge itself writes nothing to stderr in steady state, so this
464
+ * is silent on the happy path.
465
+ */
466
+ void forwardBridgeStderr(proc.stderr);
467
+ }
468
+ }
469
+
470
+ function lineDecoder() {
471
+ let buffer = '';
472
+ return {
473
+ push(chunk: string): string[] {
474
+ buffer += chunk;
475
+ const lines: string[] = [];
476
+ let nl: number;
477
+ while ((nl = buffer.indexOf('\n')) !== -1) {
478
+ const raw = buffer.slice(0, nl);
479
+ buffer = buffer.slice(nl + 1);
480
+ const line = raw.replace(/\r$/, '').trim();
481
+ if (line.length > 0) lines.push(line);
482
+ }
483
+ return lines;
484
+ },
485
+ };
486
+ }
487
+
488
+ async function forwardBridgeStderr(
489
+ stream: ReadableStream<Uint8Array>,
490
+ ): Promise<void> {
491
+ try {
492
+ const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
493
+ while (true) {
494
+ const { value, done } = await reader.read();
495
+ if (done) return;
496
+ if (value) {
497
+ const trimmed = value.endsWith('\n') ? value.slice(0, -1) : value;
498
+ if (trimmed.length > 0) {
499
+ // eslint-disable-next-line no-console
500
+ console.log(`[bridge stderr] ${trimmed}`);
501
+ }
502
+ }
503
+ }
504
+ } catch {
505
+ // Reader errors are non-fatal — best-effort diagnostic only.
506
+ }
507
+ }
508
+
509
+ async function drainRest(stream: ReadableStream<Uint8Array>): Promise<void> {
510
+ try {
511
+ const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
512
+ while (true) {
513
+ const { done } = await reader.read();
514
+ if (done) return;
515
+ }
516
+ } catch {}
517
+ }
518
+
519
+ function openWebSocket(url: string): Promise<WebSocket> {
520
+ return new Promise((resolve, reject) => {
521
+ const ws = new WebSocket(url);
522
+ const onOpen = () => {
523
+ ws.off('error', onError);
524
+ resolve(ws);
525
+ };
526
+ const onError = (err: Error) => {
527
+ ws.off('open', onOpen);
528
+ reject(err);
529
+ };
530
+ ws.once('open', onOpen);
531
+ ws.once('error', onError);
532
+ });
533
+ }
534
+
535
+ function createSession({
536
+ sessionId,
537
+ channel,
538
+ proc,
539
+ skills,
540
+ model,
541
+ reasoningEffort,
542
+ webSearch,
543
+ resumeThreadId,
544
+ isResume,
545
+ seedResumeThreadOnFirstPrompt,
546
+ rerunContinue,
547
+ bridgePort,
548
+ bridgeToken,
549
+ sandboxId,
550
+ debug,
551
+ permissionMode,
552
+ }: {
553
+ sessionId: string;
554
+ channel: CodexChannel;
555
+ /** Undefined on `attach` — the live bridge was spawned by another process. */
556
+ proc: Experimental_SandboxProcess | undefined;
557
+ skills: ReadonlyArray<HarnessV1Skill> | undefined;
558
+ model: string | undefined;
559
+ reasoningEffort: 'low' | 'medium' | 'high' | undefined;
560
+ webSearch: boolean | undefined;
561
+ resumeThreadId: string | undefined;
562
+ isResume: boolean;
563
+ seedResumeThreadOnFirstPrompt: boolean;
564
+ rerunContinue: boolean;
565
+ bridgePort: number;
566
+ bridgeToken: string;
567
+ sandboxId: string;
568
+ debug: HarnessV1DebugConfig | undefined;
569
+ permissionMode: HarnessV1PermissionMode | undefined;
570
+ }): HarnessV1Session {
571
+ let stopped = false;
572
+ let stopPromise: Promise<void> | undefined;
573
+ /*
574
+ * Send the persisted threadId on the first prompt only when the bridge was
575
+ * respawned (rerun/replay) so it takes the `codex.resumeThread(...)` branch.
576
+ * An `attach`ed bridge already holds its threadState in memory and continues
577
+ * on its own, so it needs no seed.
578
+ */
579
+ let pendingResumeThreadId = seedResumeThreadOnFirstPrompt
580
+ ? resumeThreadId
581
+ : undefined;
582
+ /*
583
+ * Instructions are prepended to the first user message of a fresh session
584
+ * only. A resumed session (attach/replay/rerun) already carried them in its
585
+ * original first message (preserved in the persisted thread), so it starts
586
+ * "applied".
587
+ */
588
+ let instructionsApplied = isResume;
589
+
590
+ /*
591
+ * Latest codex thread id, cached from the bridge's `bridge-thread`
592
+ * announcements. Seeded from lifecycle state so `doDetach()` and `doStop()`
593
+ * can include a thread id even before this process has run a turn.
594
+ */
595
+ let latestThreadId = resumeThreadId;
596
+ channel.on('bridge-thread', msg => {
597
+ latestThreadId = msg.threadId;
598
+ });
599
+
600
+ /*
601
+ * Wire the channel into one turn's worth of events and return the control
602
+ * surface. Shared by `doPromptTurn` (which sends a `start` afterwards) and
603
+ * `doContinueTurn` (which attaches to an already-running/replayed turn, or sends
604
+ * a rerun `start`). The only difference between the two entry points is the
605
+ * `start` message, not the listener/abort/settle plumbing.
606
+ */
607
+ const wireTurn = (turnOpts: {
608
+ emit: (event: HarnessV1StreamPart) => void;
609
+ abortSignal?: AbortSignal;
610
+ }): HarnessV1PromptControl => {
611
+ let pendingResolve: (() => void) | undefined;
612
+ let pendingReject: ((err: unknown) => void) | undefined;
613
+ const done = new Promise<void>((resolve, reject) => {
614
+ pendingResolve = resolve;
615
+ pendingReject = reject;
616
+ });
617
+
618
+ const unsubs: Array<() => void> = [];
619
+ const forward = (event: HarnessV1StreamPart) => {
620
+ try {
621
+ turnOpts.emit(event);
622
+ } catch {}
623
+ };
624
+
625
+ const eventTypes = [
626
+ 'stream-start',
627
+ 'text-start',
628
+ 'text-delta',
629
+ 'text-end',
630
+ 'reasoning-start',
631
+ 'reasoning-delta',
632
+ 'reasoning-end',
633
+ 'tool-call',
634
+ 'tool-approval-request',
635
+ 'tool-result',
636
+ 'file-change',
637
+ 'finish-step',
638
+ 'raw',
639
+ ] as const;
640
+ let isSettled = false;
641
+ const settleSuccess = () => {
642
+ if (isSettled) return;
643
+ isSettled = true;
644
+ for (const u of unsubs) u();
645
+ pendingResolve!();
646
+ };
647
+ const settleError = (err: unknown) => {
648
+ if (isSettled) return;
649
+ isSettled = true;
650
+ for (const u of unsubs) u();
651
+ pendingReject!(err);
652
+ };
653
+
654
+ for (const type of eventTypes) {
655
+ unsubs.push(
656
+ channel.on(type, msg => {
657
+ forward(msg);
658
+ }),
659
+ );
660
+ }
661
+ unsubs.push(
662
+ channel.on('finish', msg => {
663
+ forward(msg);
664
+ settleSuccess();
665
+ }),
666
+ );
667
+ unsubs.push(
668
+ channel.on('error', msg => {
669
+ forward(msg);
670
+ settleError(msg.error);
671
+ }),
672
+ );
673
+
674
+ /*
675
+ * A `'suspended'` close is a graceful slice-boundary freeze the host
676
+ * initiated (`doSuspendTurn`): the turn keeps running in the bridge and its
677
+ * tail is replayed to the next process, so wind this turn down cleanly
678
+ * rather than failing it. Any other close mid-turn is an unexpected drop.
679
+ */
680
+ const onClose = (_code?: number, reason?: string) => {
681
+ if (isSettled) return;
682
+ if (reason === 'suspended') {
683
+ settleSuccess();
684
+ return;
685
+ }
686
+ settleError(new Error('codex bridge closed before the turn finished.'));
687
+ };
688
+ channel.onClose(onClose);
689
+
690
+ const onAbort = () => {
691
+ if (isSettled) return;
692
+ try {
693
+ channel.send({ type: 'abort' });
694
+ } catch {}
695
+ settleError(
696
+ turnOpts.abortSignal?.reason ??
697
+ new DOMException('Aborted', 'AbortError'),
698
+ );
699
+ };
700
+ if (turnOpts.abortSignal) {
701
+ if (turnOpts.abortSignal.aborted) {
702
+ onAbort();
703
+ } else {
704
+ turnOpts.abortSignal.addEventListener('abort', onAbort, {
705
+ once: true,
706
+ });
707
+ }
708
+ }
709
+
710
+ return {
711
+ submitToolResult: async input => {
712
+ channel.send({
713
+ type: 'tool-result',
714
+ toolCallId: input.toolCallId,
715
+ output: input.output,
716
+ isError: input.isError,
717
+ });
718
+ },
719
+ submitToolApproval: async input => {
720
+ channel.send({
721
+ type: 'tool-approval-response',
722
+ approvalId: input.approvalId,
723
+ approved: input.approved,
724
+ reason: input.reason,
725
+ });
726
+ },
727
+ submitUserMessage: async text => {
728
+ channel.send({ type: 'user-message', text });
729
+ },
730
+ done,
731
+ };
732
+ };
733
+
734
+ return {
735
+ sessionId,
736
+ isResume,
737
+ modelId: model,
738
+ doPromptTurn: async promptOpts => {
739
+ const control = wireTurn({
740
+ emit: promptOpts.emit,
741
+ abortSignal: promptOpts.abortSignal,
742
+ });
743
+
744
+ const applyInstructions =
745
+ !instructionsApplied && !!promptOpts.instructions;
746
+ instructionsApplied = true;
747
+
748
+ const startMessage = {
749
+ type: 'start' as const,
750
+ prompt: extractUserText(promptOpts.prompt),
751
+ ...(applyInstructions ? { instructions: promptOpts.instructions } : {}),
752
+ tools: (promptOpts.tools ?? []).map(t => ({
753
+ name: t.name,
754
+ description: t.description,
755
+ inputSchema: t.inputSchema,
756
+ })),
757
+ model,
758
+ reasoningEffort,
759
+ webSearch,
760
+ ...(permissionMode ? { permissionMode } : {}),
761
+ ...(skills && skills.length > 0
762
+ ? {
763
+ skills: skills.map(s => ({
764
+ name: s.name,
765
+ description: s.description,
766
+ content: s.content,
767
+ })),
768
+ }
769
+ : {}),
770
+ ...(pendingResumeThreadId
771
+ ? { resumeThreadId: pendingResumeThreadId }
772
+ : {}),
773
+ ...(debug ? { debug } : {}),
774
+ };
775
+ pendingResumeThreadId = undefined;
776
+ channel.send(startMessage);
777
+
778
+ return control;
779
+ },
780
+ doContinueTurn: async continueOpts => {
781
+ const control = wireTurn({
782
+ emit: continueOpts.emit,
783
+ abortSignal: continueOpts.abortSignal,
784
+ });
785
+
786
+ /*
787
+ * attach / replay: the still-running (or disk-replayed) turn streams into
788
+ * the wired listeners — `doStart` opened the channel with `{ resume: true }`
789
+ * so the bridge replays everything past the persisted cursor (including a
790
+ * `finish` if the turn ended during the gap). No `start` is sent: issuing
791
+ * one would clear the bridge's replay log and begin a new turn. Lossless.
792
+ *
793
+ * rerun: the bridge was respawned with no in-flight turn to attach to, so
794
+ * re-drive codex's own thread via `resumeThreadId`. Lossy — work in flight
795
+ * at the interruption is recomputed. This is the rare bridge-died
796
+ * fallback; the common slice path is `attach`.
797
+ */
798
+ if (rerunContinue) {
799
+ const threadId = pendingResumeThreadId ?? latestThreadId;
800
+ pendingResumeThreadId = undefined;
801
+ channel.send({
802
+ type: 'start' as const,
803
+ /*
804
+ * A continuation nudge rather than an empty prompt: `resumeThreadId`
805
+ * rehydrates the prior thread, and this is the new user turn that
806
+ * drives it forward. Keeping it non-empty avoids handing the runtime
807
+ * an empty user message (and mirrors the claude-code adapter, where an
808
+ * empty text block trips the Anthropic API's `cache_control` rule).
809
+ */
810
+ prompt: 'Continue.',
811
+ tools: (continueOpts.tools ?? []).map(t => ({
812
+ name: t.name,
813
+ description: t.description,
814
+ inputSchema: t.inputSchema,
815
+ })),
816
+ model,
817
+ reasoningEffort,
818
+ webSearch,
819
+ ...(permissionMode ? { permissionMode } : {}),
820
+ ...(threadId ? { resumeThreadId: threadId } : {}),
821
+ ...(debug ? { debug } : {}),
822
+ });
823
+ }
824
+
825
+ return control;
826
+ },
827
+ doCompact: async () => {
828
+ /*
829
+ * Codex compacts its context automatically inside the core turn loop
830
+ * (~90% of the model context window), but the `codex exec` transport this
831
+ * adapter drives exposes no manual compaction trigger and emits no
832
+ * compaction event. Manual `compact()` is therefore unsupported; Codex's
833
+ * own auto-compaction continues to run regardless.
834
+ */
835
+ throw new HarnessCapabilityUnsupportedError({
836
+ message:
837
+ "Harness 'codex' does not support manual compaction; Codex auto-compacts its context internally.",
838
+ harnessId: 'codex',
839
+ });
840
+ },
841
+ doDetach: async () => {
842
+ if (stopped) {
843
+ throw new Error(
844
+ `codex session ${sessionId} is already stopped; cannot detach.`,
845
+ );
846
+ }
847
+ stopped = true;
848
+ const lastSeenEventId = await channel.suspend();
849
+ const payload: HarnessV1ResumeSessionState = {
850
+ type: 'resume-session',
851
+ harnessId: 'codex',
852
+ specificationVersion: 'harness-v1',
853
+ data: {
854
+ ...(latestThreadId ? { threadId: latestThreadId } : {}),
855
+ bridge: {
856
+ port: bridgePort,
857
+ token: bridgeToken,
858
+ lastSeenEventId,
859
+ sandboxId,
860
+ },
861
+ },
862
+ };
863
+ return payload;
864
+ },
865
+ doDestroy: async () => {
866
+ if (stopped) return stopPromise;
867
+ stopped = true;
868
+ stopPromise = (async () => {
869
+ // Tell the channel we are tearing down so the bridge's post-shutdown
870
+ // socket close finalises instead of triggering a reconnect.
871
+ channel.beginClose();
872
+ try {
873
+ if (!channel.isClosed()) {
874
+ channel.send({ type: 'shutdown' });
875
+ }
876
+ } catch {}
877
+ let stopTimer: ReturnType<typeof setTimeout> | undefined;
878
+ try {
879
+ if (proc) {
880
+ await Promise.race([
881
+ proc.wait(),
882
+ new Promise<void>(resolve => {
883
+ stopTimer = setTimeout(resolve, 5000);
884
+ stopTimer.unref?.();
885
+ }),
886
+ ]);
887
+ }
888
+ } finally {
889
+ if (stopTimer) clearTimeout(stopTimer);
890
+ try {
891
+ await proc?.kill();
892
+ } catch {}
893
+ channel.close();
894
+ }
895
+ })();
896
+ return stopPromise;
897
+ },
898
+ doStop: async () => {
899
+ if (stopped) {
900
+ throw new Error(
901
+ `codex session ${sessionId} is already stopped; cannot stop.`,
902
+ );
903
+ }
904
+ stopped = true;
905
+ /*
906
+ * If the bridge's channel already closed (e.g. mid-turn WS drop)
907
+ * there is no one to ack a `detach` message. Synthesize an empty
908
+ * payload — the workdir is still captured by the sandbox snapshot
909
+ * during the subsequent `sandboxSession.stop()`, so the next turn can
910
+ * resume the filesystem state. The trade-off: we lose
911
+ * `threadId`, so the codex CLI starts a fresh thread on the
912
+ * preserved workdir rather than resuming the prior conversation
913
+ * inside Codex's runtime. Ability to continue beats throwing.
914
+ */
915
+ // Tell the channel we are tearing down so the bridge's post-detach
916
+ // socket close finalises instead of triggering a reconnect.
917
+ channel.beginClose();
918
+ const data: unknown = channel.isClosed()
919
+ ? {}
920
+ : await new Promise<unknown>((resolve, reject) => {
921
+ const timer = setTimeout(() => {
922
+ unsub();
923
+ reject(
924
+ new Error(
925
+ `codex session ${sessionId} did not reply to detach within 5s.`,
926
+ ),
927
+ );
928
+ }, 5000);
929
+ timer.unref?.();
930
+ const unsub = channel.on('bridge-detach', msg => {
931
+ clearTimeout(timer);
932
+ unsub();
933
+ resolve(msg.data);
934
+ });
935
+ try {
936
+ channel.send({ type: 'detach' });
937
+ } catch (err) {
938
+ clearTimeout(timer);
939
+ unsub();
940
+ reject(err);
941
+ }
942
+ });
943
+
944
+ let stopTimer: ReturnType<typeof setTimeout> | undefined;
945
+ try {
946
+ if (proc) {
947
+ await Promise.race([
948
+ proc.wait(),
949
+ new Promise<void>(resolve => {
950
+ stopTimer = setTimeout(resolve, 5000);
951
+ stopTimer.unref?.();
952
+ }),
953
+ ]);
954
+ }
955
+ } finally {
956
+ if (stopTimer) clearTimeout(stopTimer);
957
+ try {
958
+ await proc?.kill();
959
+ } catch {}
960
+ channel.close();
961
+ }
962
+
963
+ const payload: HarnessV1ResumeSessionState = {
964
+ type: 'resume-session',
965
+ harnessId: 'codex',
966
+ specificationVersion: 'harness-v1',
967
+ data: (data ?? {}) as HarnessV1ResumeSessionState['data'],
968
+ };
969
+ return payload;
970
+ },
971
+ doSuspendTurn: async () => {
972
+ if (stopped) {
973
+ throw new Error(
974
+ `codex session ${sessionId} is stopped; cannot suspend.`,
975
+ );
976
+ }
977
+ stopped = true;
978
+ /*
979
+ * Gracefully freeze the active turn at a precise cursor. `channel.suspend`
980
+ * stops processing inbound frames (the cursor stops advancing exactly at
981
+ * the last delivered event), drains what was already dispatched, then
982
+ * closes the host socket with reason `'suspended'` — which `wireTurn`'s
983
+ * `onClose` treats as a clean turn end. The bridge keeps the turn running
984
+ * and accumulates events past the cursor for the next slice to replay. The
985
+ * sandbox process is deliberately left alive (no `shutdown`/`detach`).
986
+ */
987
+ const lastSeenEventId = await channel.suspend();
988
+ const payload: HarnessV1ContinueTurnState = {
989
+ type: 'continue-turn',
990
+ harnessId: 'codex',
991
+ specificationVersion: 'harness-v1',
992
+ data: {
993
+ ...(latestThreadId ? { threadId: latestThreadId } : {}),
994
+ bridge: {
995
+ port: bridgePort,
996
+ token: bridgeToken,
997
+ lastSeenEventId,
998
+ sandboxId,
999
+ },
1000
+ },
1001
+ };
1002
+ return payload;
1003
+ },
1004
+ };
1005
+ }
1006
+
1007
+ /*
1008
+ * Reduce a `HarnessV1Prompt` to the plain user text the bridge forwards
1009
+ * to the Codex SDK. File and image parts on the message are not yet
1010
+ * supported by the underlying runtime — throw rather than silently drop
1011
+ * them so callers learn about the gap instead of seeing mysteriously
1012
+ * truncated prompts.
1013
+ */
1014
+ function extractUserText(prompt: HarnessV1Prompt): string {
1015
+ if (typeof prompt === 'string') return prompt;
1016
+ const { content } = prompt;
1017
+ if (typeof content === 'string') return content;
1018
+ const parts: string[] = [];
1019
+ for (const part of content) {
1020
+ if (part.type !== 'text') {
1021
+ throw new HarnessCapabilityUnsupportedError({
1022
+ harnessId: 'codex',
1023
+ 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.`,
1024
+ });
1025
+ }
1026
+ parts.push(part.text);
1027
+ }
1028
+ return parts.join('\n\n');
1029
+ }