Open History to see the last commit
1import { EventType, normalizeSystemPrompts } from '@tanstack/ai'
2import {
3 resolveReasoning,
4 toRunErrorRawEvent,
5} from '@tanstack/ai/adapter-internals'
6import { BaseTextAdapter } from '@tanstack/ai/adapters'
7import {
8 SandboxCapability,
9 alignedIfAttaching,
10 createBridgeEventChannel,
11 createRunScopedIdGen,
12 encodeRunId,
13 getSandbox,
14 getSandboxDurability,
15 getSandboxPolicy,
16 getToolBridgeProvisioner,
17 getWorkspaceProjection,
18 journalOptionsFor,
19 mergeChunkStreams,
20 nodeHttpBridgeProvisioner,
21 resolveDurableRunId,
22 resolveDurableThreadId,
23 spawnNdjson,
24} from '@tanstack/ai-sandbox'
25import { buildPrompt } from '../messages/prompt'
26import { translateThreadEvents } from '../stream/translate'
27import { projectCodexWorkspace } from './projection'
28import { mapPolicyToCodexFlags } from './policy-map'
29import { CODEX_MODEL_REASONING } from '../model-meta'
30import type { CodexPolicyFlags } from './policy-map'
31import type { HostToolBridge, SandboxHandle } from '@tanstack/ai-sandbox'
32import type {
33 StructuredOutputOptions,
34 StructuredOutputResult,
35} from '@tanstack/ai/adapters'
36import type {
37 DefaultMessageMetadataByModality,
38 Modality,
39 AdapterYieldChunk,
40 ReasoningRequest,
41 TextOptions,
42} from '@tanstack/ai'
43import type { CodexModel, CodexModelReasoningByName } from '../model-meta'
44import type { CodexTextProviderOptions } from '../provider-options'
45import type { CodexThreadEvent } from '../stream/sdk-types'
46
47export type CodexSandboxMode =
48 | 'read-only'
49 | 'workspace-write'
50 | 'danger-full-access'
51export type CodexApprovalMode =
52 | 'never'
53 | 'on-failure'
54 | 'on-request'
55 | 'untrusted'
56
57const DEFAULT_WORKDIR = '/workspace'
58
59/**
60 * Providers that already isolate the agent in a VM or container where Codex
61 * cannot create a nested bubblewrap user namespace. Isolation is then the
62 * outer sandbox plus `defineSandboxPolicy`. Issue #1081 item 8.
63 */
64const NESTED_BWRAP_UNSUPPORTED = new Set(['daytona', 'cloudflare'])
65
66function defaultSandboxMode(provider: string): CodexSandboxMode {
67 return NESTED_BWRAP_UNSUPPORTED.has(provider)
68 ? 'danger-full-access'
69 : 'workspace-write'
70}
71
72export type CodexAuthMode = 'host' | 'api-key'
73
74export interface CodexTextConfig {
75 /** Working directory inside the sandbox. Defaults to `/workspace`. */
76 cwd?: string
77 /**
78 * Codex's own sandbox mode (`--sandbox`). Defaults to `'workspace-write'`
79 * so the agent can edit the workspace — the outer TanStack sandbox is the
80 * real isolation boundary.
81 */
82 sandboxMode?: CodexSandboxMode
83 /** Codex approval policy (`--config approval_policy=`). Defaults to `'never'`. */
84 approvalPolicy?: CodexApprovalMode
85 /**
86 * The default reasoning effort (`--config model_reasoning_effort=`) when a
87 * call sets no `chat({ reasoning })`.
88 */
89 modelReasoningEffort?: 'minimal' | 'low' | 'medium' | 'high'
90 /** Skip Codex's git-repo safety check (`--skip-git-repo-check`). Defaults to true. */
91 skipGitRepoCheck?: boolean
92 /** Allow network in `workspace-write` (`--config sandbox_workspace_write.network_access=`). */
93 networkAccessEnabled?: boolean
94 /** Web search mode (`--config web_search=`). */
95 webSearchMode?: 'disabled' | 'live'
96 /** Extra writable directories (`--add-dir`). */
97 additionalDirectories?: Array<string>
98 /** Path/name of the codex executable inside the sandbox. Defaults to `codex`. */
99 codexExecutable?: string
100 /**
101 * `'api-key'` (default) expects `CODEX_API_KEY` in the process or sandbox
102 * secrets. `'host'` uses `codex login`. Not inferred from the sandbox.
103 */
104 authMode?: CodexAuthMode
105 /** Extra environment variables for the codex process inside the sandbox. */
106 env?: Record<string, string>
107 /** Extra raw `--config key=value` overrides (values passed verbatim as TOML). */
108 config?: Record<string, string>
109}
110
111function q(value: string): string {
112 return `'${value.replace(/'/g, `'\\''`)}'`
113}
114
115/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */
116type ResolveReasoning<TModel extends string> =
117 TModel extends keyof CodexModelReasoningByName
118 ? CodexModelReasoningByName[TModel]
119 : never
120
121/**
122 * Codex's `model_reasoning_effort` for `chat({ reasoning })`: the model's
123 * effort for the level, or `fallback` when the call sets none.
124 */
125export function codexReasoningEffort(
126 model: string,
127 request: ReasoningRequest | undefined,
128 fallback: string | undefined,
129): string | undefined {
130 return (
131 resolveReasoning(request, CODEX_MODEL_REASONING[model])?.value ?? fallback
132 )
133}
134
135export class CodexTextAdapter<
136 TModel extends CodexModel,
137> extends BaseTextAdapter<
138 TModel,
139 CodexTextProviderOptions,
140 ReadonlyArray<Modality> & readonly ['text'],
141 DefaultMessageMetadataByModality,
142 ReadonlyArray<string>,
143 unknown,
144 never,
145 ResolveReasoning<TModel>
146> {
147 readonly name = 'codex' as const
148
149 override readonly requires = [SandboxCapability] as const
150
151 private readonly adapterConfig: CodexTextConfig
152
153 /** `toolChoice` warnings that this instance already logged. */
154 private readonly toolChoiceWarnings = new Set<string>()
155
156 constructor(config: CodexTextConfig, model: TModel) {
157 super({}, model)
158 this.adapterConfig = config
159 }
160
161 /**
162 * The chat() tools to bridge for `toolChoice`: none for `'none'`, and only
163 * the named tool for `{ type: 'tool', name }`. Codex cannot turn off its
164 * built-in tools or force a tool call, so every value except `'auto'` logs
165 * a warning once.
166 */
167 private toolsForChoice(options: TextOptions<CodexTextProviderOptions>) {
168 const { toolChoice, tools = [] } = options
169 if (toolChoice === undefined || toolChoice === 'auto') return tools
170 const warning =
171 toolChoice === 'required'
172 ? "codex: toolChoice 'required' is not supported. The agent decides which tools to call."
173 : 'codex: toolChoice limits only the chat() tools. The built-in Codex tools stay on.'
174 if (!this.toolChoiceWarnings.has(warning)) {
175 this.toolChoiceWarnings.add(warning)
176 options.logger.warn(warning)
177 }
178 if (toolChoice === 'none') return []
179 if (toolChoice === 'required') return tools
180 return tools.filter((tool) => tool.name === toolChoice.name)
181 }
182
183 private sandboxFrom(
184 options: TextOptions<CodexTextProviderOptions>,
185 ): SandboxHandle {
186 const ctx = options.capabilities
187 if (!ctx) {
188 throw new Error(
189 'Adapter "codex" requires a sandbox. Add withSandbox(defineSandbox({ ... })) to chat() middleware.',
190 )
191 }
192 return getSandbox(ctx)
193 }
194
195 private workdir(options: TextOptions<CodexTextProviderOptions>): string {
196 return (
197 options.modelOptions?.workingDirectory ??
198 this.adapterConfig.cwd ??
199 DEFAULT_WORKDIR
200 )
201 }
202
203 supportsCombinedToolsAndSchema(): boolean {
204 return true
205 }
206
207 combinedStructuredOutputSource(): 'event' {
208 return 'event'
209 }
210
211 /** Mirror @openai/codex-sdk's `codex exec --experimental-json` invocation. */
212 private buildCommand(
213 options: TextOptions<CodexTextProviderOptions>,
214 resume: string | undefined,
215 bridge: HostToolBridge | undefined,
216 policyFlags: CodexPolicyFlags,
217 provider: string,
218 outputSchemaPath: string | undefined,
219 ): string {
220 const config = this.adapterConfig
221 const modelOptions = options.modelOptions
222 const exe = config.codexExecutable ?? 'codex'
223 const args: Array<string> = ['exec', '--experimental-json']
224
225 // Precedence: per-call modelOptions > adapter config > sandbox policy >
226 // provider default. Daytona/Cloudflare cannot nest bubblewrap.
227 const sandboxMode =
228 modelOptions?.sandboxMode ??
229 config.sandboxMode ??
230 policyFlags.sandboxMode ??
231 defaultSandboxMode(provider)
232 const approvalPolicy =
233 modelOptions?.approvalPolicy ??
234 config.approvalPolicy ??
235 policyFlags.approvalPolicy ??
236 'never'
237 const networkAccessEnabled =
238 config.networkAccessEnabled ?? policyFlags.networkAccessEnabled
239 const reasoning = codexReasoningEffort(
240 this.model,
241 options.reasoning,
242 config.modelReasoningEffort,
243 )
244 const skipGitRepoCheck =
245 modelOptions?.skipGitRepoCheck ?? config.skipGitRepoCheck
246
247 args.push('--model', q(this.model))
248 args.push('--sandbox', q(sandboxMode))
249 // NOTE: do NOT pass `--cd <cwd>`. `cwd` is the VIRTUAL `/workspace` root; the
250 // provider handle already maps it to the sandbox's real workdir and runs the
251 // process there (e.g. Daytona's `/home/daytona/workspace`). Passing it as a
252 // literal `--cd` makes codex chdir to a path that doesn't exist on the real
253 // filesystem → "No such file or directory (os error 2)". Codex inherits the
254 // handle-set process cwd instead.
255 if (skipGitRepoCheck !== false) args.push('--skip-git-repo-check')
256 for (const dir of config.additionalDirectories ?? []) {
257 args.push('--add-dir', q(dir))
258 }
259
260 const cfg: Record<string, string> = {
261 approval_policy: `"${approvalPolicy}"`,
262 ...(reasoning ? { model_reasoning_effort: `"${reasoning}"` } : {}),
263 ...(networkAccessEnabled !== undefined
264 ? {
265 'sandbox_workspace_write.network_access':
266 String(networkAccessEnabled),
267 }
268 : {}),
269 ...(config.webSearchMode
270 ? { web_search: `"${config.webSearchMode}"` }
271 : {}),
272 // Bridge chat()-provided tools via a streamable-HTTP MCP server. A `url`
273 // makes codex use its streamable-HTTP transport, which authenticates via an
274 // `Authorization` header — codex REJECTS inline `bearer_token` for this
275 // transport ("bearer_token is not supported for streamable_http"; that field
276 // is only for the stdio transport). Pass the per-run bearer as an HTTP header
277 // instead; the host tool-bridge checks `Authorization: Bearer <token>`.
278 ...(bridge
279 ? {
280 [`mcp_servers.${bridge.name}.url`]: `"${bridge.url}"`,
281 [`mcp_servers.${bridge.name}.http_headers`]: `{ "Authorization" = "Bearer ${bridge.token}" }`,
282 }
283 : {}),
284 ...config.config,
285 }
286 for (const [key, value] of Object.entries(cfg)) {
287 args.push('--config', q(`${key}=${value}`))
288 }
289
290 if (outputSchemaPath !== undefined) {
291 args.push('--output-schema', q(outputSchemaPath))
292 }
293
294 // Resume an existing thread (mirrors the SDK's `resume <threadId>`).
295 if (resume !== undefined) args.push('resume', q(resume))
296
297 return `${exe} ${args.join(' ')}`
298 }
299
300 async *chatStream(
301 options: TextOptions<CodexTextProviderOptions>,
302 ): AsyncIterable<AdapterYieldChunk> {
303 const { logger } = options
304 let bridge: HostToolBridge | undefined
305 const tempFiles: Array<string> = []
306 let cleanupSandbox: SandboxHandle | undefined
307 // Durability caveat: the journaled path below derives its journal file
308 // path from `runId` alone (see `journalPaths` in `@tanstack/ai-sandbox`),
309 // and a successor host must recompute that same path to resume this run.
310 // That is only possible when the caller supplies a stable `runId`.
311 // `resolveDurableRunId` enforces that when durability is wired (both
312 // `runs` and `durability.adapter` given to `withSandbox`) and preserves
313 // the generated fallback — `this.generateId()`, a fresh random id every
314 // call — when it is not, so a non-durable run's behavior is unchanged.
315 const durability = options.capabilities
316 ? getSandboxDurability(options.capabilities, { optional: true })
317 : undefined
318 const runId = resolveDurableRunId(options.runId, {
319 durable: durability !== undefined,
320 adapter: 'codex',
321 fallback: () => this.generateId(),
322 })
323 // `threadId` is stamped on every chunk `translateThreadEvents` emits, so an
324 // ATTACHING run that mints a fresh one replays a stream the stored log
325 // cannot match at index 0. `resolveDurableThreadId` refuses that up front
326 // instead of letting alignment discover it mid-stream; a durable FRESH run
327 // and a non-durable run both keep the generated fallback untouched.
328 const threadId = resolveDurableThreadId(options.threadId, {
329 durable: durability !== undefined,
330 attaching: durability?.attach === true,
331 adapter: 'codex',
332 fallback: () => this.generateId(),
333 })
334 // Surfaces custom events from bridged tools (e.g. code mode console logs)
335 // on this run's live output stream.
336 const channel = createBridgeEventChannel({
337 model: this.model,
338 threadId,
339 runId,
340 })
341 try {
342 const tools = this.toolsForChoice(options)
343 const sandbox = this.sandboxFrom(options)
344 cleanupSandbox = sandbox
345 const cwd = this.workdir(options)
346
347 // Project declarative workspace inputs (MCP/skills) into codex's native
348 // format. Re-runs each call so rotated secrets re-apply; idempotent ops
349 // are marker-gated inside the projector.
350 const projection = options.capabilities
351 ? getWorkspaceProjection(options.capabilities, { optional: true })
352 : undefined
353 if (projection) await projectCodexWorkspace(sandbox, projection)
354
355 if (tools.length > 0) {
356 const provisioner =
357 (options.capabilities
358 ? getToolBridgeProvisioner(options.capabilities, { optional: true })
359 : undefined) ?? nodeHttpBridgeProvisioner
360 bridge = await provisioner.provision(tools, {
361 provider: sandbox.provider,
362 context: options.context,
363 emitCustomEvent: channel.emitCustomEvent,
364 ...(options.abortController?.signal
365 ? { signal: options.abortController.signal }
366 : {}),
367 })
368 }
369
370 const { prompt, resume } = buildPrompt(
371 options.messages,
372 options.modelOptions?.sessionId,
373 )
374 const systemPrompts = normalizeSystemPrompts(options.systemPrompts)
375 .map((p) => p.content)
376 .filter((c) => c.trim() !== '')
377 const fullPrompt =
378 systemPrompts.length > 0
379 ? `${systemPrompts.join('\n\n')}\n\n${prompt}`
380 : prompt
381
382 const policy = options.capabilities
383 ? getSandboxPolicy(options.capabilities, { optional: true })
384 : undefined
385 let outputSchemaArg: string | undefined
386 if (options.outputSchema) {
387 const schemaFile = `.tanstack-output-schema-${encodeRunId(runId)}.json`
388 const schemaPath = `${cwd}/${schemaFile}`
389 await sandbox.fs.write(schemaPath, JSON.stringify(options.outputSchema))
390 tempFiles.push(schemaPath)
391 outputSchemaArg = schemaFile
392 }
393 const command = this.buildCommand(
394 options,
395 resume,
396 bridge,
397 mapPolicyToCodexFlags(policy),
398 sandbox.provider,
399 outputSchemaArg,
400 )
401
402 logger.request(
403 `activity=chat provider=codex model=${this.model} sandbox=${sandbox.provider} messages=${options.messages.length} resume=${resume ?? 'none'}`,
404 { provider: 'codex', model: this.model },
405 )
406
407 // Deliver the prompt. Default: over stdin. Providers without a writable
408 // host→process stdin can't accept that — Docker's hijacked exec severs
409 // stdout when stdin EOF is signalled (losing the agent's output), and
410 // Cloudflare can't write stdin at all — so feed the prompt from a file
411 // (`codex exec … < file`) instead.
412 let runCommand = command
413 let stdinInput: string | undefined = fullPrompt
414 if (sandbox.capabilities.writableStdin === false) {
415 // Reuse the ALREADY-RESOLVED `runId`, not a fresh `options.runId ?? this.generateId()`
416 // re-derivation: the latter mints a SECOND random id whenever
417 // `options.runId` is absent, so the prompt file's suffix would not
418 // even match the journal path derived from the run's own `runId`
419 // above (see `resolveDurableRunId`). That mismatch is invisible
420 // (the prompt still gets read), but it defeats the whole point of a
421 // stable, caller-supplied `runId` for anything keyed off it.
422 // `encodeRunId`, because durability makes `runId` CALLER-chosen and this
423 // interpolates it into a filesystem path. Raw, a `/` would silently turn
424 // the basename into a nested path (writing outside `/tmp` or failing on a
425 // missing dir), `..` would climb out of it, and a long id would fail the
426 // spawn with `ENAMETOOLONG`. The encoder collapses every id to one
427 // bounded, injective path segment — the same one `journalPaths` uses, so
428 // the prompt file and the journal agree on how this id spells.
429 const promptPath = `/tmp/tanstack-codex-prompt-${encodeRunId(runId)}`
430 await sandbox.fs.write(promptPath, fullPrompt)
431 tempFiles.push(promptPath)
432 runCommand = `${command} < ${q(promptPath)}`
433 stdinInput = undefined
434 }
435
436 // `undefined` whenever the run is not durable, so `spawnNdjson` takes its
437 // original, unjournaled path and behavior stays byte-identical to a
438 // pre-durability run. When durable, this also carries `attach`, which is
439 // how `spawnNdjson` decides to tail an EXISTING journal instead of
440 // starting a new agent — set by the attach route's `drive()` callback,
441 // never by an application's POST handler (see `SandboxDurabilityOptions.attach`).
442 const journalOptions = journalOptionsFor(durability, runId)
443
444 const rawEvents = spawnNdjson(sandbox, runCommand, {
445 cwd,
446 ...(stdinInput !== undefined ? { input: stdinInput } : {}),
447 ...(this.adapterConfig.env ? { env: this.adapterConfig.env } : {}),
448 ...(options.abortController?.signal
449 ? { signal: options.abortController.signal }
450 : options.request?.signal
451 ? { signal: options.request.signal }
452 : {}),
453 onNonJsonLine: (line) =>
454 logger.provider(`provider=codex non-json line: ${line}`, {
455 chunk: line,
456 }),
457 // Route stdout through the in-sandbox journal so a resuming host can
458 // re-read it from byte 0 (see `@tanstack/ai-sandbox`'s journal.ts).
459 ...(journalOptions === undefined ? {} : { journal: journalOptions }),
460 })
461
462 async function* asEvents(): AsyncIterable<CodexThreadEvent> {
463 for await (const event of rawEvents) yield event as CodexThreadEvent
464 }
465
466 // Deterministic, run-scoped ids: journal replay re-translates the same
467 // journal bytes, and `this.generateId()` (Date.now() + Math.random())
468 // would mint different message ids on every replay. See
469 // chunk-identity.ts in `@tanstack/ai-sandbox` for why this is required.
470 const genId = createRunScopedIdGen(runId)
471
472 // `mergeChunkStreams` below interleaves `translateThreadEvents`'s
473 // deterministic output with `channel.stream` (host-tool-bridge CUSTOM
474 // events from LIVE tool execution — see `createBridgeEventChannel`
475 // above). Those events do not occur on a replay, so a takeover's replay
476 // is NOT chunk-for-chunk identical to what the log holds.
477 // `alignedIfAttaching` handles it: alignment skips stored out-of-band
478 // CUSTOM entries within a bounded window (see `align.ts`), so a
479 // bridged-tool run can be taken over without a spurious
480 // `JournalReplayDivergedError`, while a genuine determinism regression
481 // still throws. It is a no-op (passes the stream through untouched)
482 // whenever the run is not durable or is not attaching, so a
483 // non-durable run's output is unaffected byte for byte.
484 //
485 // The wrap goes OUTSIDE `mergeChunkStreams`, never around the pre-merge
486 // translator alone: the stored log holds the previous host's MERGED
487 // output, so comparing against anything else would compare against a
488 // stream the log never contained.
489 yield* alignedIfAttaching(
490 mergeChunkStreams(
491 translateThreadEvents(asEvents(), {
492 model: this.model,
493 runId,
494 threadId,
495 ...(options.parentRunId !== undefined && {
496 parentRunId: options.parentRunId,
497 }),
498 genId,
499 ...(options.outputSchema ? { expectStructuredOutput: true } : {}),
500 onThreadEvent: (event) =>
501 logger.provider(`provider=codex type=${event.type}`, {
502 chunk: event,
503 }),
504 }),
505 channel.stream,
506 ),
507 durability,
508 logger,
509 )
510 } catch (error: unknown) {
511 const err = error as Error & { code?: string }
512 const rawEvent = toRunErrorRawEvent(error)
513 logger.errors('codex.chatStream fatal', {
514 error,
515 source: 'codex.chatStream',
516 })
517 yield {
518 type: EventType.RUN_ERROR,
519 model: options.model,
520 timestamp: Date.now(),
521 message: err.message || 'Unknown error occurred',
522 ...(err.code !== undefined && { code: err.code }),
523 ...(rawEvent !== undefined && { rawEvent }),
524 error: {
525 message: err.message || 'Unknown error occurred',
526 ...(err.code !== undefined && { code: err.code }),
527 },
528 }
529 } finally {
530 channel.close()
531 await bridge?.close()
532 if (cleanupSandbox) {
533 for (const path of tempFiles) {
534 try {
535 await cleanupSandbox.fs.remove(path)
536 } catch {
537 // already gone / sandbox torn down — nothing to clean up
538 }
539 }
540 }
541 }
542 }
543
544 structuredOutput(
545 _options: StructuredOutputOptions<CodexTextProviderOptions>,
546 ): Promise<StructuredOutputResult<unknown>> {
547 return Promise.reject(
548 new Error(
549 'This harness honors outputSchema on chat() in the same turn. ' +
550 'Pass outputSchema to chat(), or use a model adapter for a one-shot extract.',
551 ),
552 )
553 }
554}
555
556/**
557 * Creates a Codex harness adapter that runs **inside a sandbox**.
558 *
559 * It declares `requires: [SandboxCapability]` and spawns
560 * `codex exec --experimental-json` inside the sandbox (mirroring
561 * `@openai/codex-sdk`'s own CLI invocation), feeding the prompt via stdin and
562 * streaming its JSONL thread events back as AG-UI chunks. The sandbox image
563 * must provide the `codex` executable and `CODEX_API_KEY` (or a `codex login`)
564 * in its environment.
565 */
566export function codexText<TModel extends CodexModel>(
567 model: TModel,
568 config: CodexTextConfig = {},
569): CodexTextAdapter<TModel> {
570 return new CodexTextAdapter(config, model)
571}