Open History to see the last commit
1---
2title: Codex
3id: codex-adapter
4order: 12
5description: "Run OpenAI's Codex agent inside a sandbox from TanStack AI. It runs shell commands and edits files in a real repo, and streams each step to your UI."
6keywords:
7 - tanstack ai
8 - codex
9 - codex sdk
10 - openai
11 - harness
12 - agent
13 - coding agent
14 - adapter
15---
16
17The Codex adapter runs the `codex` CLI in a sandbox and streams each step to `chat()`. The agent runs shell commands and edits files in a repo.
18
19You need:
20
21- A sandbox provider. The samples use Docker, so Docker must run on your machine.
22- A `CODEX_API_KEY`, or a `codex login` on the machine.
23- The `codex` CLI inside the sandbox. A setup step in the sandbox installs it.
24
25Do you only want a GPT chat, with no repo and no shell? Use the [OpenAI adapter](./openai).
26
27## 1. Install
28
29<!-- ::start:tabs variant="package-manager" mode="install" -->
30
31react: @tanstack/ai-codex @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
32vue: @tanstack/ai-codex @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
33solid: @tanstack/ai-codex @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
34svelte: @tanstack/ai-codex @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
35preact: @tanstack/ai-codex @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
36angular: @tanstack/ai-codex @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
37vanilla: @tanstack/ai-codex @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
38octane: @tanstack/ai-codex @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
39
40<!-- ::end:tabs -->
41
42## 2. Set the API key
43
44Put your OpenAI API key in the environment of your server, with the name `CODEX_API_KEY`:
45
46```bash
47CODEX_API_KEY=sk-...
48```
49
50The sandbox in step 3 gives this key to the `codex` process as a workspace secret. `codex exec` signs in with `CODEX_API_KEY`. A bare `OPENAI_API_KEY` is not enough.
51
52Did the machine already run `codex login`? Then you can use that login and no key. See [Harness Auth](../sandbox/auth).
53
54## 3. Run the agent from the server
55
56Define the sandbox once. It clones your repo into a Docker container and installs the `codex` CLI:
57
58```ts
59// sandbox.ts
60import {
61 createSecrets,
62 defineSandbox,
63 defineWorkspace,
64 githubRepo,
65} from "@tanstack/ai-sandbox";
66import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
67
68export const sandbox = defineSandbox({
69 id: "codex-agent",
70 provider: dockerSandbox({ image: "node:22" }),
71 workspace: defineWorkspace({
72 source: githubRepo({ repo: "owner/app" }),
73 setup: ["npm install -g @openai/codex --include=optional && codex --version"],
74 secrets: createSecrets({
75 CODEX_API_KEY: process.env.CODEX_API_KEY ?? "",
76 }),
77 }),
78});
79```
80
81Then pass the adapter and the sandbox to `chat()` in your route:
82
83```ts
84// api/agent.ts
85import {
86 chat,
87 chatParamsFromRequest,
88 toServerSentEventsResponse,
89} from "@tanstack/ai";
90import { codexText } from "@tanstack/ai-codex";
91import { withSandbox } from "@tanstack/ai-sandbox";
92import { sandbox } from "./sandbox";
93
94export async function POST(request: Request) {
95 const { messages, threadId, runId } = await chatParamsFromRequest(request);
96
97 const stream = chat({
98 adapter: codexText("gpt-5.3-codex"),
99 messages,
100 threadId,
101 runId,
102 middleware: [withSandbox(sandbox)],
103 });
104
105 return toServerSentEventsResponse(stream);
106}
107```
108
109Replace `owner/app` with your repo.
110
111## 4. Render the agent's work
112
113The client is the same as for any chat. Render the text, and show each tool that the agent ran:
114
115```tsx
116import { useState } from "react";
117import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
118
119export function CodingAgent() {
120 const [input, setInput] = useState("");
121 const { messages, sendMessage } = useChat({
122 connection: fetchServerSentEvents("/api/agent"),
123 threadId: "support-chat",
124 });
125
126 return (
127 <form
128 onSubmit={(event) => {
129 event.preventDefault();
130 sendMessage(input);
131 setInput("");
132 }}
133 >
134 {messages.map((message) =>
135 message.parts.map((part, index) => {
136 if (part.type === "text") {
137 return <p key={`${message.id}-${index}`}>{part.content}</p>;
138 }
139 if (part.type === "tool-call") {
140 return <code key={part.id}>{part.name}</code>;
141 }
142 return null;
143 }),
144 )}
145 <input value={input} onChange={(event) => setInput(event.target.value)} />
146 </form>
147 );
148}
149```
150
151Ask it "Fix the failing test in utils.test.ts". You see the agent's text, plus a line for each tool it used: `command_execution`, `file_change`, and more. The agent edited the files inside the container.
152
153## How it works
154
155- `codexText` declares that it needs a sandbox. `withSandbox(sandbox)` gives it one. Without a sandbox, `chat()` fails at the call site.
156- Each `chat()` call runs one full agent turn. Codex runs its own loop and its own tools.
157- The tools of the agent stream back as `tool-call` parts with the results attached. Your code does not run them.
158- Codex also has its own inner sandbox. `sandboxMode` sets it. The outer TanStack sandbox is the real boundary.
159
160To learn more about sandboxes, see [Sandboxes](../sandbox/overview).
161
162## Resume a session
163
164Codex keeps its working context between turns: the files it read, the commands it ran, and what it found. The adapter sends the thread id of each new run as a custom event named `codex.session-id`. Send it back in `modelOptions.sessionId` to continue the thread.
165
166On the server, read the id from the request:
167
168```ts
169import {
170 chat,
171 chatParamsFromRequest,
172 toServerSentEventsResponse,
173} from "@tanstack/ai";
174import { codexText } from "@tanstack/ai-codex";
175import { withSandbox } from "@tanstack/ai-sandbox";
176import { sandbox } from "./sandbox";
177
178export async function POST(request: Request) {
179 const params = await chatParamsFromRequest(request);
180
181 // The client sends the id in `forwardedProps`.
182 const sessionId =
183 typeof params.forwardedProps.sessionId === "string"
184 ? params.forwardedProps.sessionId
185 : undefined;
186
187 const stream = chat({
188 adapter: codexText("gpt-5.3-codex"),
189 messages: params.messages,
190 threadId: params.threadId,
191 runId: params.runId,
192 middleware: [withSandbox(sandbox)],
193 modelOptions: { sessionId },
194 });
195
196 return toServerSentEventsResponse(stream);
197}
198```
199
200On the client, keep the id from the custom event and pass it to `forwardedProps`. `useChat` sends the latest value with each request:
201
202```tsx
203import { useState } from "react";
204import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
205
206export function useCodingAgent() {
207 const [sessionId, setSessionId] = useState<string | undefined>(undefined);
208
209 return useChat({
210 connection: fetchServerSentEvents("/api/agent"),
211 forwardedProps: { sessionId },
212 threadId: "support-chat",
213 onCustomEvent: (name, value) => {
214 if (
215 name === "codex.session-id" &&
216 typeof value === "object" &&
217 value !== null &&
218 "sessionId" in value &&
219 typeof value.sessionId === "string"
220 ) {
221 setSessionId(value.sessionId);
222 }
223 },
224 });
225}
226```
227
228- On a resumed thread, the adapter sends only the latest user message. The agent already has the rest.
229- Codex saves the thread inside the sandbox. Resume works only when the next call runs in the same sandbox. See [Lifecycle & Snapshots](../sandbox/lifecycle).
230
231## Give the agent your own tools
232
233The agent has its own tools for files and the shell. It cannot reach your database or your secrets. Pass your server tools to `chat()`, and the adapter bridges them into the sandbox:
234
235```ts group=tools
236import { z } from "zod";
237import { chat, toolDefinition } from "@tanstack/ai";
238import { codexText } from "@tanstack/ai-codex";
239import { withSandbox } from "@tanstack/ai-sandbox";
240import { sandbox } from "./sandbox";
241
242const lookupTicket = toolDefinition({
243 name: "lookup_ticket",
244 description: "Look up an issue ticket by id",
245 inputSchema: z.object({ ticketId: z.string() }),
246}).server(async ({ ticketId }) => {
247 return { ticketId, status: "open", title: "Crash on startup" };
248});
249
250const stream = chat({
251 adapter: codexText("gpt-5.3-codex"),
252 messages: [{ role: "user", content: "What's the status of ticket T-123?" }],
253 threadId: "thread-1",
254 tools: [lookupTicket],
255 middleware: [withSandbox(sandbox)],
256});
257```
258
259- Each tool runs on your server, with its closures and secrets. The result goes back into the sandbox.
260- The tool-call events use the names you gave.
261- Only server tools work here. A client tool has no server `execute()`, so the agent cannot run it.
262
263For how the bridge reaches your server from each provider, see [Sandbox Tools](../sandbox/tools).
264
265## Tool choice
266
267You want Codex to skip your tools, or to see only one of them. Pass `toolChoice` to `chat()`:
268
269```ts group=tools
270const noBridgedTools = chat({
271 adapter: codexText("gpt-5.3-codex"),
272 messages: [{ role: "user", content: "Explain the bug in src/app.ts." }],
273 threadId: "thread-1",
274 tools: [lookupTicket],
275 toolChoice: "none",
276 middleware: [withSandbox(sandbox)],
277});
278```
279
280`toolChoice` limits only the tools that the adapter bridges into Codex. The built-in Codex tools always stay on, and Codex decides when it calls a tool.
281
282| Value | What the adapter does |
283| --- | --- |
284| `'auto'` | Bridges all of your tools. |
285| `'none'` | Bridges none of your tools. |
286| `{ type: 'tool', name }` | Bridges only the named tool. Codex does not have to call it. |
287| `'required'` | Bridges all of your tools. Codex does not have to call one. |
288
289Each value except `'auto'` logs a warning the first time an adapter instance gets it.
290
291For the values on other adapters, see [Choose when the model calls a tool](../tools/tools#choose-when-the-model-calls-a-tool).
292
293## Structured output
294
295You want a typed report after the agent reads the repo. Pass `outputSchema` on the same `chat()` call:
296
297```ts
298import { chat } from "@tanstack/ai";
299import { codexText } from "@tanstack/ai-codex";
300import { withSandbox } from "@tanstack/ai-sandbox";
301import { z } from "zod";
302import { sandbox } from "./sandbox";
303
304const Report = z.object({
305 summary: z.string(),
306 filesChanged: z.array(z.string()),
307});
308
309const report = await chat({
310 adapter: codexText("gpt-5.3-codex"),
311 messages: [{ role: "user", content: "Review this repo." }],
312 threadId: "thread-1",
313 outputSchema: Report,
314 middleware: [withSandbox(sandbox)],
315});
316
317console.log(report.summary);
318```
319
320On the client, pass the same schema to `useChat` and read `final`. `partial` stays empty until the end.
321
322```tsx
323import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";
324import { z } from "zod";
325
326const Report = z.object({
327 summary: z.string(),
328 filesChanged: z.array(z.string()),
329});
330
331export function ReportView() {
332 const { final, isLoading } = useChat({
333 connection: fetchServerSentEvents("/api/repo-report"),
334 threadId: "support-chat",
335 outputSchema: Report,
336 });
337
338 if (isLoading) return <p>The agent is inspecting the repo.</p>;
339 if (!final) return null;
340 return <p>{final.summary}</p>;
341}
342```
343
344- Codex runs one turn and limits its last message with `--output-schema`.
345- Tool activity and text stream as Codex writes them.
346- The adapter parses the last message as the schema object. It arrives as `structured-output.complete`.
347
348Do you only need JSON from a prompt, with no repo? Use `@tanstack/ai-openai`. That is faster. For the full walkthrough, see [Harness Agents](../structured-outputs/harnesses).
349
350## Models and options
351
352### Models
353
354| Model | Reasoning levels |
355| --- | --- |
356| `gpt-5.3-codex` | `off`, `low`, `medium`, `high`, `xhigh` |
357| `gpt-5.2-codex` | `low`, `medium`, `high`, `xhigh` |
358| `gpt-5.1-codex`, `gpt-5.1-codex-mini` | `low`, `medium`, `high` |
359| `gpt-5.1` | `off`, `low`, `medium`, `high` |
360
361The package exports this list as `CODEX_MODELS`. The adapter also takes any other model id that Codex accepts, as a string.
362
363### Reasoning
364
365Set `reasoning` on `chat()`. Codex gets it as `model_reasoning_effort`:
366
367```ts
368import { chat } from "@tanstack/ai";
369import { codexText } from "@tanstack/ai-codex";
370import { withSandbox } from "@tanstack/ai-sandbox";
371import { sandbox } from "./sandbox";
372
373const stream = chat({
374 adapter: codexText("gpt-5.3-codex"),
375 messages: [{ role: "user", content: "Fix the failing test in utils.test.ts" }],
376 threadId: "thread-1",
377 reasoning: "xhigh",
378 middleware: [withSandbox(sandbox)],
379});
380```
381
382A call with no `reasoning` uses `modelReasoningEffort` from the adapter options. See [Reasoning](../chat/reasoning).
383
384### Adapter options
385
386Pass these as the second argument of `codexText`:
387
388| Option | What it does |
389| --- | --- |
390| `cwd` | The working directory inside the sandbox. Default `/workspace`. |
391| `sandboxMode` | The inner Codex sandbox: `'read-only'`, `'workspace-write'`, or `'danger-full-access'`. See [Inner sandbox mode](#inner-sandbox-mode). |
392| `approvalPolicy` | `'never'` (default), `'on-failure'`, `'on-request'`, or `'untrusted'`. A headless run has no approval UI, so another value can stop a turn. |
393| `modelReasoningEffort` | The effort when a call sets no `reasoning`: `'minimal'`, `'low'`, `'medium'`, or `'high'`. |
394| `skipGitRepoCheck` | Skip the git repo check of Codex. Default `true`. |
395| `networkAccessEnabled` | Allow network access inside the `workspace-write` sandbox. |
396| `webSearchMode` | `'disabled'` or `'live'`. |
397| `additionalDirectories` | More writable directories next to `cwd`. |
398| `authMode` | `'api-key'` (default) expects `CODEX_API_KEY`. `'host'` uses `codex login`. See [Harness Auth](../sandbox/auth). |
399| `codexExecutable` | The path or name of the `codex` executable in the sandbox. Default `codex`. |
400| `env` | More environment variables for the `codex` process. |
401| `config` | More `--config key=value` overrides for the Codex CLI, for example more `mcp_servers` entries. Values go through as TOML. |
402
403### Per-call options
404
405Pass these in `modelOptions` on `chat()`. They override the adapter options for one call:
406
407- `sessionId`: resume a thread. See [Resume a session](#resume-a-session).
408- `sandboxMode`, `approvalPolicy`, `skipGitRepoCheck`.
409- `workingDirectory`: the working directory for this call.
410- `authMode`: `'host'` or `'api-key'`.
411
412## Advanced
413
414### Inner sandbox mode
415
416The default `sandboxMode` depends on the provider:
417
418- Local-process and Docker: `'workspace-write'`.
419- Daytona and Cloudflare: `'danger-full-access'`. These providers cannot create a nested bubblewrap namespace. The outer VM and your sandbox [Policy](../sandbox/policy) are then the isolation.
420
421The inner Codex sandbox does not work on Windows and on some Linux images. There it fails with `os error 2`. If you see this error, set `sandboxMode: 'danger-full-access'`. The outer sandbox is still the boundary.
422
423### Text streaming
424
425Codex reports text as items that grow. The adapter streams each new piece of an item, so text can arrive in larger pieces than with an HTTP adapter. Tool activity, such as a command that starts or ends, streams live.
426
427### Limitations
428
429- **A sandbox is required.** Every call needs `withSandbox(...)`.
430- **The agent owns the loop.** TanStack agent-loop strategies and per-iteration middleware do not apply inside a turn.
431- **No sampling options.** Options such as `temperature` do not exist here.
432- **Sessions stay in the sandbox.** Resume needs the same sandbox.
433- **Cold starts.** Each call starts a CLI turn, so the first token arrives later than with an HTTP adapter.
434- **No `wrapFetch`.** This adapter ignores [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call), because the `codex` process sends the model requests.
435
436### Example apps
437
438- [`examples/sandbox-cloudflare`](https://github.com/TanStack/ai/tree/main/examples/sandbox-cloudflare): a TanStack Start app on Workers. You pick Claude Code, Codex, or Grok Build in the UI. It shows session resume, the tool timeline, and tool bridging.
439- [`examples/sandbox-web`](https://github.com/TanStack/ai/tree/main/examples/sandbox-web): Claude Code on Docker, with durable runs that continue after a page refresh. To use Codex there, change the adapter in `src/sandbox-agent.ts`.