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

codex.md

257 lines12.0 KB

1---
2title: Codex
3id: codex-adapter
4order: 12
5description: "Use OpenAI Codex as a chat backend in TanStack AI — agent harness with local tool execution, stateful coding sessions, and tool bridging via @tanstack/ai-codex."
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 [OpenAI Codex](https://developers.openai.com/codex) (via the `@openai/codex-sdk`) as a chat backend. Unlike HTTP provider adapters, this is a **harness adapter**: Codex runs its own agent loop and executes its own tools — shell commands, file changes, web search — locally on your server, inside its sandbox. Each `chat()` call runs one full harness turn; the harness's tool activity streams back as already-resolved tool-call events your UI can render.
18​
19> **Server-only.** The harness spawns the Codex runtime (bundled with the SDK) as a subprocess, so this adapter only works in a Node.js server environment — never in the browser. The sandbox mode is the safety boundary; configure it deliberately.
20​
21## Installation
22​
23<!-- ::start:tabs variant="package-manager" mode="install" -->
24​
25react: @tanstack/ai-codex
26vue: @tanstack/ai-codex
27solid: @tanstack/ai-codex
28svelte: @tanstack/ai-codex
29preact: @tanstack/ai-codex
30angular: @tanstack/ai-codex
31vanilla: @tanstack/ai-codex
32octane: @tanstack/ai-codex
33​
34<!-- ::end:tabs -->
35​
36A runnable demo lives at [`examples/sandbox-cloudflare`](https://github.com/TanStack/ai/tree/main/examples/sandbox-cloudflare) — pick Claude Code, Codex, or Grok Build in the UI, with session resume, the harness tool timeline, and tool bridging, wired into a TanStack Start app on Workers. For the same wiring on plain Node with durable, refresh-surviving runs (Claude Code on Docker), see [`examples/sandbox-web`](https://github.com/TanStack/ai/tree/main/examples/sandbox-web) — swapping in this adapter is a one-line change (`src/sandbox-agent.ts`).
37​
38## Authentication
39​
40Your laptop can already have `codex login`. A CI runner only has
41`CODEX_API_KEY`. The default `authMode` is `'api-key'`. Set `'host'` when
42you want `codex login`. See [Harness Auth](../sandbox/auth).
43​
44```ts
45import { codexText } from "@tanstack/ai-codex"
46​
47codexText("gpt-5.5")
48codexText("gpt-5.5", { authMode: "host" })
49```
50​
51- `'api-key'` (default): expect `CODEX_API_KEY` (or pass `apiKey`).
52- `'host'`: use `codex login`. Do not inject `CODEX_API_KEY`.
53​
54## Basic Usage
55​
56```typescript
57import { chat } from "@tanstack/ai";
58import { codexText } from "@tanstack/ai-codex";
59​
60const stream = chat({
61 adapter: codexText("gpt-5.1-codex", {
62 cwd: "/path/to/project",
63 sandboxMode: "workspace-write",
64 }),
65 messages: [{ role: "user", content: "Fix the failing test in utils.test.ts" }],
66});
67```
68​
69## Configuration
70​
71| Option | Description |
72| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
73| `cwd` | Working directory for the harness session. Defaults to `process.cwd()`. |
74| `sandboxMode` | Codex sandbox: `'read-only'`, `'workspace-write'`, or `'danger-full-access'`. Default is `'workspace-write'` on local-process and Docker. Default is `'danger-full-access'` on Daytona and Cloudflare, because those providers cannot create a nested bubblewrap namespace. Isolation is then the outer VM plus `defineSandboxPolicy`. |
75| `approvalPolicy` | Codex approval policy. Defaults to `'never'` — headless runs have no approval UI, so anything else can stall a turn. |
76| `modelReasoningEffort` | `'minimal'` \| `'low'` \| `'medium'` \| `'high'` \| `'xhigh'`. |
77| `skipGitRepoCheck` | Skip the harness's git-repo safety check. Defaults to `true` (server adapters routinely point at scratch directories). |
78| `networkAccessEnabled` | Allow network access inside the `workspace-write` sandbox. |
79| `webSearchMode` | `'disabled'` \| `'cached'` \| `'live'`. |
80| `additionalDirectories`| Extra writable directories beyond `cwd`. |
81| `authMode` | `'api-key'` (default) expects `CODEX_API_KEY`. `'host'` uses `codex login`. See [Harness Auth](../sandbox/auth). |
82| `apiKey` | OpenAI API key for the harness subprocess. |
83| `baseUrl` | Override the Codex backend base URL. |
84| `codexPathOverride` | Use a specific codex executable instead of the SDK's bundled binary. |
85| `env` | Environment variables for the subprocess. When set, `process.env` is **not** inherited (Codex SDK semantics). |
86| `config` | Extra `--config key=value` overrides passed to the Codex CLI (e.g. additional `mcp_servers` entries). |
87​
88Per-call overrides go through `modelOptions`: `sessionId`, `sandboxMode`,
89`approvalPolicy`, `modelReasoningEffort`, `workingDirectory`,
90`skipGitRepoCheck`, and `authMode`.
91​
92## Stateful Sessions
93​
94Codex threads are stateful — the harness keeps the full working context (files read, commands run, conclusions reached) between turns. The adapter surfaces the thread id of every fresh run as a custom stream event named `codex.session-id`; thread it back via `modelOptions.sessionId` to resume. When resuming, only the latest user message is sent — the harness already holds the prior context.
95​
96Server endpoint:
97​
98```typescript
99import {
100 chat,
101 chatParamsFromRequest,
102 toServerSentEventsResponse,
103} from "@tanstack/ai";
104import { codexText } from "@tanstack/ai-codex";
105​
106export async function POST(request: Request) {
107 const params = await chatParamsFromRequest(request);
108​
109 // Extra fields the client puts in the connection `body` arrive here.
110 const sessionId =
111 typeof params.forwardedProps.sessionId === "string"
112 ? params.forwardedProps.sessionId
113 : undefined;
114​
115 const stream = chat({
116 adapter: codexText("gpt-5.1-codex", {
117 cwd: "/path/to/project",
118 sandboxMode: "workspace-write",
119 }),
120 messages: params.messages,
121 modelOptions: { sessionId },
122 });
123​
124 return toServerSentEventsResponse(stream);
126```
127​
128Client (React) — capture the session id from the custom event and send it back on subsequent requests:
129​
130```typescript
131import { useState } from "react";
132import { useChat } from "@tanstack/ai-react";
133import { fetchServerSentEvents } from "@tanstack/ai-client";
134​
135function CodingAssistant() {
136 const [sessionId, setSessionId] = useState<string | undefined>(undefined);
137​
138 const { messages, sendMessage } = useChat({
139 connection: fetchServerSentEvents("/api/chat", () => ({
140 body: { sessionId },
141 })),
142 onCustomEvent: (name, value) => {
143 if (
144 name === "codex.session-id" &&
145 typeof value === "object" &&
146 value !== null &&
147 "sessionId" in value &&
148 typeof value.sessionId === "string"
149 ) {
150 setSessionId(value.sessionId);
151 }
152 },
153 });
154​
155 // ... render messages; harness tool activity (command_execution,
156 // file_change, ...) arrives as regular tool-call parts with results.
158```
159​
160Sessions are stored on the machine that ran them (`~/.codex/sessions/`), so resuming only works on the same server instance.
161​
162## Tools
163​
164Two kinds of tools flow through this adapter:
165​
1661. **Built-in harness tools** are executed by Codex itself and stream back as tool-call events with results already attached: `command_execution` (shell), `file_change` (patches), `web_search`, and `todo_list` (the agent's running plan). Your code never executes them.
167​
1682. **Your TanStack tools** are bridged *into* the harness: the adapter starts a short-lived Streamable-HTTP MCP server on `127.0.0.1` for the duration of the turn and points Codex at it. Define tools as usual with `toolDefinition().server()`; tool-call events come back under the names you registered.
169​
170```typescript
171import { z } from "zod";
172import { chat, toolDefinition } from "@tanstack/ai";
173import { codexText } from "@tanstack/ai-codex";
174​
175const lookupTicket = toolDefinition({
176 name: "lookup_ticket",
177 description: "Look up an issue ticket by id",
178 inputSchema: z.object({ ticketId: z.string() }),
179}).server(async ({ ticketId }) => {
180 return { ticketId, status: "open", title: "Crash on startup" };
181});
182​
183const stream = chat({
184 adapter: codexText("gpt-5.1-codex"),
185 messages: [{ role: "user", content: "What's the status of ticket T-123?" }],
186 tools: [lookupTicket],
187});
188```
189​
190**Client-side and approval-gated tools are not supported.** The harness executes tools inside a live subprocess, which cannot pause across HTTP requests to wait for a browser round-trip or a human approval. Passing a tool without a server `execute()` implementation — or one marked `needsApproval` — fails fast with a descriptive error. Run those tools outside the harness with a regular provider adapter.
191​
192## Structured Output
193​
194Pass `outputSchema` on `chat()`. Codex runs one harness turn and constrains the last message with `--output-schema`. Tool activity and assistant text stream as Codex writes them. The last message is also parsed as the schema object and arrives as `structured-output.complete`.
195​
196```ts
197import { chat } from "@tanstack/ai"
198import { codexText } from "@tanstack/ai-codex"
199import { defineSandbox, withSandbox } from "@tanstack/ai-sandbox"
200import { dockerSandbox } from "@tanstack/ai-sandbox-docker"
201import { z } from "zod"
202​
203const Report = z.object({
204 summary: z.string(),
205 filesChanged: z.array(z.string()),
206})
207​
208const sandbox = defineSandbox({
209 id: "repo-report",
210 provider: dockerSandbox({ image: "node:22" }),
211})
212​
213const report = await chat({
214 adapter: codexText("gpt-5.3-codex"),
215 messages: [{ role: "user", content: "Review this repo." }],
216 outputSchema: Report,
217 middleware: [withSandbox(sandbox)],
218})
219​
220report.summary
221```
222​
223On the client, pass the same schema to `useChat` and read `final`. `partial` stays empty until the end.
224​
225```tsx
226import { fetchServerSentEvents, useChat } from "@tanstack/ai-react"
227import { z } from "zod"
228​
229const Report = z.object({
230 summary: z.string(),
231 filesChanged: z.array(z.string()),
232})
233​
234function ReportView() {
235 const { final, isLoading } = useChat({
236 connection: fetchServerSentEvents("/api/repo-report"),
237 outputSchema: Report,
238 })
239​
240 if (isLoading) return <p>The agent is inspecting the repo.</p>
241 if (!final) return null
242 return <p>{final.summary}</p>
244```
245​
246If you only need to extract JSON from a prompt and do not need a sandbox, use `@tanstack/ai-openai`. That path is faster.
247​
248Full walkthrough, including the client: [Harness Agents](../structured-outputs/harnesses).
249​
250## Limitations
251​
252- **No token-level text streaming.** The Codex SDK reports assistant text and reasoning only as completed items, so text arrives message-at-a-time. Tool activity (commands starting/finishing) still streams live, which keeps the UI feeling alive during long turns.
253- **Server-only (Node).** The harness spawns a subprocess.
254- **The harness owns the agent loop.** TanStack's agent-loop strategies and per-iteration middleware don't apply inside a harness turn.
255- **No sampling controls.** `temperature`-style options don't exist here.
256- **Sessions are machine-local.** Resume requires hitting the same server instance.
257- **Cold starts.** Each call spawns a harness turn; expect higher first-token latency than HTTP adapters.