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

codex.md

182 lines10.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```bash
24npm install @tanstack/ai-codex
25```
26​
27A 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`).
28​
29## Authentication
30​
31The harness resolves credentials the same way the Codex CLI does:
32​
33- the `apiKey` config option (exported to the subprocess as `CODEX_API_KEY`; usage-based billing), or
34- an existing ChatGPT login on the machine (`codex login`).
35​
36## Basic Usage
37​
38```typescript
39import { chat } from "@tanstack/ai";
40import { codexText } from "@tanstack/ai-codex";
41​
42const stream = chat({
43 adapter: codexText("gpt-5.1-codex", {
44 cwd: "/path/to/project",
45 sandboxMode: "workspace-write",
46 }),
47 messages: [{ role: "user", content: "Fix the failing test in utils.test.ts" }],
48});
49```
50​
51## Configuration
52​
53| Option | Description |
54| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
55| `cwd` | Working directory for the harness session. Defaults to `process.cwd()`. |
56| `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`. |
57| `approvalPolicy` | Codex approval policy. Defaults to `'never'` — headless runs have no approval UI, so anything else can stall a turn. |
58| `modelReasoningEffort` | `'minimal'` \| `'low'` \| `'medium'` \| `'high'` \| `'xhigh'`. |
59| `skipGitRepoCheck` | Skip the harness's git-repo safety check. Defaults to `true` (server adapters routinely point at scratch directories). |
60| `networkAccessEnabled` | Allow network access inside the `workspace-write` sandbox. |
61| `webSearchMode` | `'disabled'` \| `'cached'` \| `'live'`. |
62| `additionalDirectories`| Extra writable directories beyond `cwd`. |
63| `apiKey` | OpenAI API key for the harness subprocess. |
64| `baseUrl` | Override the Codex backend base URL. |
65| `codexPathOverride` | Use a specific codex executable instead of the SDK's bundled binary. |
66| `env` | Environment variables for the subprocess. When set, `process.env` is **not** inherited (Codex SDK semantics). |
67| `config` | Extra `--config key=value` overrides passed to the Codex CLI (e.g. additional `mcp_servers` entries). |
68​
69Per-call overrides — `sessionId`, `sandboxMode`, `approvalPolicy`, `modelReasoningEffort`, `workingDirectory`, `skipGitRepoCheck` — go through `modelOptions`.
70​
71## Stateful Sessions
72​
73Codex 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.
74​
75Server endpoint:
76​
77```typescript
78import {
79 chat,
80 chatParamsFromRequest,
81 toServerSentEventsResponse,
82} from "@tanstack/ai";
83import { codexText } from "@tanstack/ai-codex";
84​
85export async function POST(request: Request) {
86 const params = await chatParamsFromRequest(request);
87​
88 // Extra fields the client puts in the connection `body` arrive here.
89 const sessionId =
90 typeof params.forwardedProps.sessionId === "string"
91 ? params.forwardedProps.sessionId
92 : undefined;
93​
94 const stream = chat({
95 adapter: codexText("gpt-5.1-codex", {
96 cwd: "/path/to/project",
97 sandboxMode: "workspace-write",
98 }),
99 messages: params.messages,
100 modelOptions: { sessionId },
101 });
102​
103 return toServerSentEventsResponse(stream);
105```
106​
107Client (React) — capture the session id from the custom event and send it back on subsequent requests:
108​
109```typescript
110import { useState } from "react";
111import { useChat } from "@tanstack/ai-react";
112import { fetchServerSentEvents } from "@tanstack/ai-client";
113​
114function CodingAssistant() {
115 const [sessionId, setSessionId] = useState<string | undefined>(undefined);
116​
117 const { messages, sendMessage } = useChat({
118 connection: fetchServerSentEvents("/api/chat", () => ({
119 body: { sessionId },
120 })),
121 onCustomEvent: (name, value) => {
122 if (
123 name === "codex.session-id" &&
124 typeof value === "object" &&
125 value !== null &&
126 "sessionId" in value &&
127 typeof value.sessionId === "string"
128 ) {
129 setSessionId(value.sessionId);
130 }
131 },
132 });
133​
134 // ... render messages; harness tool activity (command_execution,
135 // file_change, ...) arrives as regular tool-call parts with results.
137```
138​
139Sessions are stored on the machine that ran them (`~/.codex/sessions/`), so resuming only works on the same server instance.
140​
141## Tools
142​
143Two kinds of tools flow through this adapter:
144​
1451. **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.
146​
1472. **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.
148​
149```typescript
150import { z } from "zod";
151import { chat, toolDefinition } from "@tanstack/ai";
152import { codexText } from "@tanstack/ai-codex";
153​
154const lookupTicket = toolDefinition({
155 name: "lookup_ticket",
156 description: "Look up an issue ticket by id",
157 inputSchema: z.object({ ticketId: z.string() }),
158}).server(async ({ ticketId }) => {
159 return { ticketId, status: "open", title: "Crash on startup" };
160});
161​
162const stream = chat({
163 adapter: codexText("gpt-5.1-codex"),
164 messages: [{ role: "user", content: "What's the status of ticket T-123?" }],
165 tools: [lookupTicket],
166});
167```
168​
169**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.
170​
171## Structured Output
172​
173`structuredOutput()` uses Codex's native `outputSchema` support in a fresh, read-only, one-shot thread whose final message is a JSON string conforming to your schema. It works for finalization after a chat, but a plain provider adapter (e.g. `@tanstack/ai-openai`) is the better choice when structured extraction is the primary job — it's faster and doesn't spawn a subprocess.
174​
175## Limitations
176​
177- **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.
178- **Server-only (Node).** The harness spawns a subprocess.
179- **The harness owns the agent loop.** TanStack's agent-loop strategies and per-iteration middleware don't apply inside a harness turn.
180- **No sampling controls.** `temperature`-style options don't exist here.
181- **Sessions are machine-local.** Resume requires hitting the same server instance.
182- **Cold starts.** Each call spawns a harness turn; expect higher first-token latency than HTTP adapters.