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