Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

text.ts

561 lines21.4 KB

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