app-server.md +430 −64
3Codex app-server is the interface Codex uses to power rich clients (for example, the Codex VS Code extension). Use it when you want a deep integration inside your own product: authentication, conversation history, approvals, and streamed agent events. The app-server implementation is open source in the Codex GitHub repository ([openai/codex/codex-rs/app-server](https://github.com/openai/codex/tree/main/codex-rs/app-server)). See the [Open Source](https://developers.openai.com/codex/open-source) page for the full list of open-source Codex components.3Codex app-server is the interface Codex uses to power rich clients (for example, the Codex VS Code extension). Use it when you want a deep integration inside your own product: authentication, conversation history, approvals, and streamed agent events. The app-server implementation is open source in the Codex GitHub repository ([openai/codex/codex-rs/app-server](https://github.com/openai/codex/tree/main/codex-rs/app-server)). See the [Open Source](https://developers.openai.com/codex/open-source) page for the full list of open-source Codex components.
4 4
5If you are automating jobs or running Codex in CI, use the5If you are automating jobs or running Codex in CI, use the
66[Codex SDK](https://developers.openai.com/codex/sdk) instead. <a href="/codex/sdk">Codex SDK</a> instead.
7 7
8## Protocol8## Protocol
9 9
12Supported transports:12Supported transports:
13 13
14- `stdio` (`--listen stdio://`, default): newline-delimited JSON (JSONL).14- `stdio` (`--listen stdio://`, default): newline-delimited JSON (JSONL).
1515- `websocket` (`--listen ws://IP:PORT`, experimental): one JSON-RPC message per WebSocket text frame.- `websocket` (`--listen ws://IP:PORT`, experimental and unsupported): one
1616 JSON-RPC message per WebSocket text frame.
1717In WebSocket mode, app-server uses bounded queues. When request ingress is full, the server rejects new requests with JSON-RPC error code `-32001` and message `"Server overloaded; retry later."` Clients should retry with an exponentially increasing delay and jitter.- Unix socket (`--listen unix://` or `--listen unix://PATH`): WebSocket
18 connections over Codex's default app-server control socket or a custom Unix
19 socket path, using the standard HTTP Upgrade handshake.
20- `off` (`--listen off`): don't expose a local transport.
21
22When you run with `--listen ws://IP:PORT`, the same listener also serves basic
23HTTP health probes:
24
25- `GET /readyz` returns `200 OK` once the listener accepts new connections.
26- `GET /healthz` returns `200 OK` when the request doesn't include an `Origin`
27 header.
28- Requests with an `Origin` header are rejected with `403 Forbidden`.
29
30WebSocket transport is experimental and unsupported. Local listeners such as
31`ws://127.0.0.1:PORT` are appropriate for localhost and SSH port-forwarding
32workflows. Non-loopback WebSocket listeners currently allow unauthenticated
33connections by default during rollout, so configure WebSocket auth before
34exposing one remotely.
35
36Supported WebSocket auth flags:
37
38- `--ws-auth capability-token --ws-token-file /absolute/path`
39- `--ws-auth capability-token --ws-token-sha256 HEX`
40- `--ws-auth signed-bearer-token --ws-shared-secret-file /absolute/path`
41
42For signed bearer tokens, you can also set `--ws-issuer`, `--ws-audience`, and
43`--ws-max-clock-skew-seconds`. Clients present the credential as
44`Authorization: Bearer <token>` during the WebSocket handshake, and app-server
45enforces auth before JSON-RPC `initialize`.
46
47Prefer `--ws-token-file` over passing raw bearer tokens on the command line. Use
48`--ws-token-sha256` only when the client keeps the raw high-entropy token in a
49separate local secret store; the hash is only a verifier, and clients still need
50the original token.
51
52In WebSocket mode, app-server uses bounded queues. When request ingress is full,
53the server rejects new requests with JSON-RPC error code `-32001` and message
54`"Server overloaded; retry later."` Clients should retry with an exponentially
55increasing delay and jitter.
18 56
19## Message schema57## Message schema
20 58
21Requests include `method`, `params`, and `id`:59Requests include `method`, `params`, and `id`:
22 60
23```json61```json
2462{ "method": "thread/start", "id": 10, "params": { "model": "gpt-5.1-codex" } }{ "method": "thread/start", "id": 10, "params": { "model": "gpt-5.4" } }
25```63```
26 64
27Responses echo the `id` with either `result` or `error`:65Responses echo the `id` with either `result` or `error`:
49 87
50## Getting started88## Getting started
51 89
52901. Start the server with `codex app-server` (default stdio transport) or `codex app-server --listen ws://127.0.0.1:4500` (experimental WebSocket transport).1. Start the server with `codex app-server` (default stdio transport),
91 `codex app-server --listen ws://127.0.0.1:4500` (TCP WebSocket), or
92 `codex app-server --listen unix://` (default Unix socket).
532. Connect a client over the selected transport, then send `initialize` followed by the `initialized` notification.932. Connect a client over the selected transport, then send `initialize` followed by the `initialized` notification.
543. Start a thread and a turn, then keep reading notifications from the active transport stream.943. Start a thread and a turn, then keep reading notifications from the active transport stream.
55 95
56Example (Node.js / TypeScript):96Example (Node.js / TypeScript):
57 97
58```ts98```ts
5999import { spawn } from "node:child_process";
60100import readline from "node:readline";
61 101
62const proc = spawn("codex", ["app-server"], {102const proc = spawn("codex", ["app-server"], {
63 stdio: ["pipe", "pipe", "inherit"],103 stdio: ["pipe", "pipe", "inherit"],
99 },139 },
100});140});
101send({ method: "initialized", params: {} });141send({ method: "initialized", params: {} });
102142send({ method: "thread/start", id: 1, params: { model: "gpt-5.1-codex" } });send({ method: "thread/start", id: 1, params: { model: "gpt-5.4" } });
103```143```
104 144
105## Core primitives145## Core primitives
123 163
124Clients must send a single `initialize` request per transport connection before invoking any other method on that connection, then acknowledge with an `initialized` notification. Requests sent before initialization receive a `Not initialized` error, and repeated `initialize` calls on the same connection return `Already initialized`.164Clients must send a single `initialize` request per transport connection before invoking any other method on that connection, then acknowledge with an `initialized` notification. Requests sent before initialization receive a `Not initialized` error, and repeated `initialize` calls on the same connection return `Already initialized`.
125 165
126166The server returns the user agent string it will present to upstream services. Set `clientInfo` to identify your integration.The server returns the user agent string it will present to upstream services plus `platformFamily` and `platformOs` values that describe the runtime target. Set `clientInfo` to identify your integration.
127 167
128`initialize.params.capabilities` also supports per-connection notification opt-out via `optOutNotificationMethods`, which is a list of exact method names to suppress for that connection. Matching is exact (no wildcards/prefixes). Unknown method names are accepted and ignored.168`initialize.params.capabilities` also supports per-connection notification opt-out via `optOutNotificationMethods`, which is a list of exact method names to suppress for that connection. Matching is exact (no wildcards/prefixes). Unknown method names are accepted and ignored.
129 169
159 },199 },
160 "capabilities": {200 "capabilities": {
161 "experimentalApi": true,201 "experimentalApi": true,
162202 "optOutNotificationMethods": [ "optOutNotificationMethods": ["thread/started", "item/agentMessage/delta"]
163 "codex/event/session_configured",
164 "item/agentMessage/delta"
165 ]
166 }203 }
167 }204 }
168}205}
200 237
201- `thread/start` - create a new thread; emits `thread/started` and automatically subscribes you to turn/item events for that thread.238- `thread/start` - create a new thread; emits `thread/started` and automatically subscribes you to turn/item events for that thread.
202- `thread/resume` - reopen an existing thread by id so later `turn/start` calls append to it.239- `thread/resume` - reopen an existing thread by id so later `turn/start` calls append to it.
203240- `thread/fork` - fork a thread into a new thread id by copying stored history; emits `thread/started` for the new thread.- `thread/fork` - fork a thread into a new thread id by copying stored history; emits `thread/started` for the new thread. Returned threads include `forkedFromId` when available.
204- `thread/read` - read a stored thread by id without resuming it; set `includeTurns` to return full turn history. Returned `thread` objects include runtime `status`.241- `thread/read` - read a stored thread by id without resuming it; set `includeTurns` to return full turn history. Returned `thread` objects include runtime `status`.
205242- `thread/list` - page through stored thread logs; supports cursor-based pagination plus `modelProviders`, `sourceKinds`, `archived`, and `cwd` filters. Returned `thread` objects include runtime `status`.- `thread/list` - page through stored thread logs; supports cursor-based pagination plus `modelProviders`, `sourceKinds`, `archived`, `cwd`, and `searchTerm` filters. Returned `thread` objects include runtime `status`.
243- `thread/turns/list` - page through a stored thread's turn history without resuming it. `itemsView` controls whether turn items are omitted, summarized, or fully loaded.
244- `thread/turns/items/list` - reserved for paged turn-item loading; currently returns unsupported.
206- `thread/loaded/list` - list the thread ids currently loaded in memory.245- `thread/loaded/list` - list the thread ids currently loaded in memory.
246- `thread/name/set` - set or update a thread's user-facing name for a loaded thread or a persisted rollout; emits `thread/name/updated`.
247- `thread/goal/set` - set the goal for a loaded thread (experimental; requires `capabilities.experimentalApi`); emits `thread/goal/updated`.
248- `thread/goal/get` - read the current goal for a loaded thread (experimental; requires `capabilities.experimentalApi`).
249- `thread/goal/clear` - clear the goal for a loaded thread (experimental; requires `capabilities.experimentalApi`); emits `thread/goal/cleared`.
250- `thread/metadata/update` - patch SQLite-backed stored thread metadata; currently supports persisted `gitInfo`.
207- `thread/archive` - move a thread's log file into the archived directory; returns `{}` on success and emits `thread/archived`.251- `thread/archive` - move a thread's log file into the archived directory; returns `{}` on success and emits `thread/archived`.
208252- `thread/unsubscribe` - unsubscribe this connection from thread turn/item events. If this was the last subscriber, the server unloads the thread and emits `thread/closed`.- `thread/unsubscribe` - unsubscribe this connection from thread turn/item events. If this was the last subscriber, the server unloads the thread after a no-subscriber inactivity grace period and emits `thread/closed`.
209- `thread/unarchive` - restore an archived thread rollout back into the active sessions directory; returns the restored `thread` and emits `thread/unarchived`.253- `thread/unarchive` - restore an archived thread rollout back into the active sessions directory; returns the restored `thread` and emits `thread/unarchived`.
210- `thread/status/changed` - notification emitted when a loaded thread's runtime `status` changes.254- `thread/status/changed` - notification emitted when a loaded thread's runtime `status` changes.
211- `thread/compact/start` - trigger conversation history compaction for a thread; returns `{}` immediately while progress streams via `turn/*` and `item/*` notifications.255- `thread/compact/start` - trigger conversation history compaction for a thread; returns `{}` immediately while progress streams via `turn/*` and `item/*` notifications.
256- `thread/shellCommand` - run a user-initiated shell command against a thread. This runs outside the sandbox with full access and doesn't inherit the thread sandbox policy.
257- `thread/backgroundTerminals/clean` - stop all running background terminals for a thread (experimental; requires `capabilities.experimentalApi`).
212- `thread/rollback` - drop the last N turns from the in-memory context and persist a rollback marker; returns the updated `thread`.258- `thread/rollback` - drop the last N turns from the in-memory context and persist a rollback marker; returns the updated `thread`.
213- `turn/start` - add user input to a thread and begin Codex generation; responds with the initial `turn` and streams events. For `collaborationMode`, `settings.developer_instructions: null` means "use built-in instructions for the selected mode."259- `turn/start` - add user input to a thread and begin Codex generation; responds with the initial `turn` and streams events. For `collaborationMode`, `settings.developer_instructions: null` means "use built-in instructions for the selected mode."
260- `thread/inject_items` - append raw Responses API items to a loaded thread's model-visible history without starting a user turn.
214- `turn/steer` - append user input to the active in-flight turn for a thread; returns the accepted `turnId`.261- `turn/steer` - append user input to the active in-flight turn for a thread; returns the accepted `turnId`.
215- `turn/interrupt` - request cancellation of an in-flight turn; success is `{}` and the turn ends with `status: "interrupted"`.262- `turn/interrupt` - request cancellation of an in-flight turn; success is `{}` and the turn ends with `status: "interrupted"`.
216- `review/start` - kick off the Codex reviewer for a thread; emits `enteredReviewMode` and `exitedReviewMode` items.263- `review/start` - kick off the Codex reviewer for a thread; emits `enteredReviewMode` and `exitedReviewMode` items.
217- `command/exec` - run a single command under the server sandbox without starting a thread/turn.264- `command/exec` - run a single command under the server sandbox without starting a thread/turn.
265- `command/exec/write` - write `stdin` bytes to a running `command/exec` session or close `stdin`.
266- `command/exec/resize` - resize a running PTY-backed `command/exec` session.
267- `command/exec/terminate` - stop a running `command/exec` session.
268- `command/exec/outputDelta` (notify) - emitted for base64-encoded stdout/stderr chunks from a streaming `command/exec` session.
269- `process/spawn` - start an explicit process session outside Codex's sandbox (experimental; requires `capabilities.experimentalApi`).
270- `process/writeStdin` - write stdin bytes to a running `process/spawn` session or close stdin (experimental).
271- `process/resizePty` - resize a running PTY-backed process session (experimental).
272- `process/kill` - terminate a running process session (experimental).
273- `process/outputDelta` and `process/exited` (notify) - emitted for streaming process output and process exit status (experimental).
218- `model/list` - list available models (set `includeHidden: true` to include entries with `hidden: true`) with effort options, optional `upgrade`, and `inputModalities`.274- `model/list` - list available models (set `includeHidden: true` to include entries with `hidden: true`) with effort options, optional `upgrade`, and `inputModalities`.
275- `modelProvider/capabilities/read` - read provider capability bounds for model/provider combinations (experimental; requires `capabilities.experimentalApi`).
219- `experimentalFeature/list` - list feature flags with lifecycle stage metadata and cursor pagination.276- `experimentalFeature/list` - list feature flags with lifecycle stage metadata and cursor pagination.
277- `experimentalFeature/enablement/set` - patch in-memory runtime settings for supported feature keys such as `apps` and `plugins`.
220- `collaborationMode/list` - list collaboration mode presets (experimental, no pagination).278- `collaborationMode/list` - list collaboration mode presets (experimental, no pagination).
221- `skills/list` - list skills for one or more `cwd` values (supports `forceReload` and optional `perCwdExtraUserRoots`).279- `skills/list` - list skills for one or more `cwd` values (supports `forceReload` and optional `perCwdExtraUserRoots`).
280- `skills/changed` (notify) - emitted when watched local skill files change.
281- `marketplace/add` - add a remote plugin marketplace and persist it into the user's marketplace config.
282- `marketplace/upgrade` - refresh a configured Git marketplace, or all configured Git marketplaces when you omit the marketplace name.
283- `plugin/list` - list discovered plugin marketplaces and plugin state, including install/auth policy metadata, marketplace load errors, featured plugin ids, and local, Git, or remote plugin source metadata.
284- `plugin/read` - read one plugin by marketplace path or remote marketplace name and plugin name, including bundled skills, apps, and MCP server names when those details are available.
285- `plugin/install` - install a plugin from a marketplace path or remote marketplace name.
286- `plugin/uninstall` - uninstall an installed plugin.
222- `app/list` - list available apps (connectors) with pagination plus accessibility/enabled metadata.287- `app/list` - list available apps (connectors) with pagination plus accessibility/enabled metadata.
223- `skills/config/write` - enable or disable skills by path.288- `skills/config/write` - enable or disable skills by path.
224- `mcpServer/oauth/login` - start an OAuth login for a configured MCP server; returns an authorization URL and emits `mcpServer/oauthLogin/completed` on completion.289- `mcpServer/oauth/login` - start an OAuth login for a configured MCP server; returns an authorization URL and emits `mcpServer/oauthLogin/completed` on completion.
225- `tool/requestUserInput` - prompt the user with 1-3 short questions for a tool call (experimental); questions can set `isOther` for a free-form option.290- `tool/requestUserInput` - prompt the user with 1-3 short questions for a tool call (experimental); questions can set `isOther` for a free-form option.
226- `config/mcpServer/reload` - reload MCP server configuration from disk and queue a refresh for loaded threads.291- `config/mcpServer/reload` - reload MCP server configuration from disk and queue a refresh for loaded threads.
227292- `mcpServerStatus/list` - list MCP servers, tools, resources, and auth status (cursor + limit pagination).- `mcpServerStatus/list` - list MCP servers, tools, resources, and auth status (cursor + limit pagination). Use `detail: "full"` for full data or `detail: "toolsAndAuthOnly"` to omit resources.
293- `mcpServer/resource/read` - read a single MCP resource through an initialized MCP server.
294- `mcpServer/tool/call` - call a tool on a thread's configured MCP server.
295- `mcpServer/startupStatus/updated` (notify) - emitted when a configured MCP server's startup status changes for a loaded thread.
228- `windowsSandbox/setupStart` - start Windows sandbox setup for `elevated` or `unelevated` mode; returns quickly and later emits `windowsSandbox/setupCompleted`.296- `windowsSandbox/setupStart` - start Windows sandbox setup for `elevated` or `unelevated` mode; returns quickly and later emits `windowsSandbox/setupCompleted`.
229- `feedback/upload` - submit a feedback report (classification + optional reason/logs + conversation id, plus optional `extraLogFiles` attachments).297- `feedback/upload` - submit a feedback report (classification + optional reason/logs + conversation id, plus optional `extraLogFiles` attachments).
230- `config/read` - fetch the effective configuration on disk after resolving configuration layering.298- `config/read` - fetch the effective configuration on disk after resolving configuration layering.
231299- `externalAgentConfig/detect` - detect migratable external-agent artifacts with `includeHome` and optional `cwds`; each detected item includes `cwd` (`null` for home).- `externalAgentConfig/detect` - detect external-agent artifacts that can be migrated with `includeHome` and optional `cwds`; each detected item includes `cwd` (`null` for home).
232300- `externalAgentConfig/import` - apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home).- `externalAgentConfig/import` - apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home). Supported item types include config, skills, `AGENTS.md`, plugins, MCP server config, subagents, hooks, commands, and sessions; plugin imports emit `externalAgentConfig/import/completed`.
233- `config/value/write` - write a single configuration key/value to the user's `config.toml` on disk.301- `config/value/write` - write a single configuration key/value to the user's `config.toml` on disk.
234- `config/batchWrite` - apply configuration edits atomically to the user's `config.toml` on disk.302- `config/batchWrite` - apply configuration edits atomically to the user's `config.toml` on disk.
235303- `configRequirements/read` - fetch requirements from `requirements.toml` and/or MDM, including allow-lists and residency requirements (or `null` if you haven’t set any up).- `configRequirements/read` - fetch requirements from `requirements.toml` and/or MDM, including allow-lists, pinned `featureRequirements`, and residency/network requirements (or `null` if you haven't set any up).
304- `fs/readFile`, `fs/writeFile`, `fs/createDirectory`, `fs/getMetadata`, `fs/readDirectory`, `fs/remove`, `fs/copy`, `fs/watch`, `fs/unwatch`, and `fs/changed` (notify) - operate on absolute filesystem paths through the app-server v2 filesystem API.
305
306Plugin summaries include a `source` union. Local plugins return
307`{ "type": "local", "path": ... }`, Git-backed marketplace entries return
308`{ "type": "git", "url": ..., "path": ..., "refName": ..., "sha": ... }`,
309and remote catalog entries return `{ "type": "remote" }`. For remote-only
310catalog entries, `PluginMarketplaceEntry.path` can be `null`; pass
311`remoteMarketplaceName` instead of `marketplacePath` when reading or installing
312those plugins.
236 313
237## Models314## Models
238 315
244{ "method": "model/list", "id": 6, "params": { "limit": 20, "includeHidden": false } }321{ "method": "model/list", "id": 6, "params": { "limit": 20, "includeHidden": false } }
245{ "id": 6, "result": {322{ "id": 6, "result": {
246 "data": [{323 "data": [{
247324 "id": "gpt-5.2-codex", "id": "gpt-5.4",
248325 "model": "gpt-5.2-codex", "model": "gpt-5.4",
249326 "upgrade": "gpt-5.3-codex", "displayName": "GPT-5.4",
250 "displayName": "GPT-5.2 Codex",
251 "hidden": false,327 "hidden": false,
252 "defaultReasoningEffort": "medium",328 "defaultReasoningEffort": "medium",
253329 "reasoningEffort": [{ "supportedReasoningEfforts": [{
254330 "effort": "low", "reasoningEffort": "low",
255 "description": "Lower latency"331 "description": "Lower latency"
256 }],332 }],
257 "inputModalities": ["text", "image"],333 "inputModalities": ["text", "image"],
264 340
265Each model entry can include:341Each model entry can include:
266 342
267343- `reasoningEffort` - supported effort options for the model.- `supportedReasoningEfforts` - supported effort options for the model.
268- `defaultReasoningEffort` - suggested default effort for clients.344- `defaultReasoningEffort` - suggested default effort for clients.
269- `upgrade` - optional recommended upgrade model id for migration prompts in clients.345- `upgrade` - optional recommended upgrade model id for migration prompts in clients.
346- `upgradeInfo` - optional upgrade metadata for migration prompts in clients.
270- `hidden` - whether the model is hidden from the default picker list.347- `hidden` - whether the model is hidden from the default picker list.
271- `inputModalities` - supported input types for the model (for example `text`, `image`).348- `inputModalities` - supported input types for the model (for example `text`, `image`).
272- `supportsPersonality` - whether the model supports personality-specific instructions such as `/personality`.349- `supportsPersonality` - whether the model supports personality-specific instructions such as `/personality`.
301## Threads378## Threads
302 379
303- `thread/read` reads a stored thread without subscribing to it; set `includeTurns` to include turns.380- `thread/read` reads a stored thread without subscribing to it; set `includeTurns` to include turns.
304381- `thread/list` supports cursor pagination plus `modelProviders`, `sourceKinds`, `archived`, and `cwd` filtering.- `thread/turns/list` pages through a stored thread's turn history without
382 resuming it. Use `itemsView` to choose whether turn items are omitted,
383 summarized, or fully loaded.
384- `thread/list` supports cursor pagination plus `modelProviders`, `sourceKinds`, `archived`, `cwd`, and `searchTerm` filtering.
305- `thread/loaded/list` returns the thread IDs currently in memory.385- `thread/loaded/list` returns the thread IDs currently in memory.
306- `thread/archive` moves the thread's persisted JSONL log into the archived directory.386- `thread/archive` moves the thread's persisted JSONL log into the archived directory.
307387- `thread/unsubscribe` unsubscribes the current connection from a loaded thread and can trigger `thread/closed`.- `thread/metadata/update` patches stored thread metadata, currently including persisted `gitInfo`.
388- `thread/unsubscribe` unsubscribes the current connection from a loaded thread and can trigger `thread/closed` after an inactivity grace period.
308- `thread/unarchive` restores an archived thread rollout back into the active sessions directory.389- `thread/unarchive` restores an archived thread rollout back into the active sessions directory.
309- `thread/compact/start` triggers compaction and returns `{}` immediately.390- `thread/compact/start` triggers compaction and returns `{}` immediately.
310- `thread/rollback` drops the last N turns from the in-memory context and records a rollback marker in the thread's persisted JSONL log.391- `thread/rollback` drops the last N turns from the in-memory context and records a rollback marker in the thread's persisted JSONL log.
392- `thread/inject_items` appends raw Responses API items to a loaded thread's model-visible history without starting a user turn.
311 393
312### Start or resume a thread394### Start or resume a thread
313 395
315 397
316```json398```json
317{ "method": "thread/start", "id": 10, "params": {399{ "method": "thread/start", "id": 10, "params": {
318400 "model": "gpt-5.1-codex", "model": "gpt-5.4",
319 "cwd": "/Users/me/project",401 "cwd": "/Users/me/project",
320 "approvalPolicy": "never",402 "approvalPolicy": "never",
321 "sandbox": "workspaceWrite",403 "sandbox": "workspaceWrite",
325{ "id": 10, "result": {407{ "id": 10, "result": {
326 "thread": {408 "thread": {
327 "id": "thr_123",409 "id": "thr_123",
410 "sessionId": "thr_123",
328 "preview": "",411 "preview": "",
329 "ephemeral": false,412 "ephemeral": false,
330 "modelProvider": "openai",413 "modelProvider": "openai",
336 419
337`serviceName` is optional. Set it when you want app-server to tag thread-level metrics with your integration's service name.420`serviceName` is optional. Set it when you want app-server to tag thread-level metrics with your integration's service name.
338 421
422`thread.sessionId` identifies the current live session tree root. Root threads
423use their own thread id as the session id; forked threads keep the session id
424of the root they came from. Clients should read the session id from
425`thread.sessionId` instead of deriving it from the thread id.
426
339To continue a stored session, call `thread/resume` with the `thread.id` you recorded earlier. The response shape matches `thread/start`. You can also pass the same configuration overrides supported by `thread/start`, such as `personality`:427To continue a stored session, call `thread/resume` with the `thread.id` you recorded earlier. The response shape matches `thread/start`. You can also pass the same configuration overrides supported by `thread/start`, such as `personality`:
340 428
341```json429```json
354 442
355If you resume with a different model than the one recorded in the rollout, Codex emits a warning and applies a one-time model-switch instruction on the next turn.443If you resume with a different model than the one recorded in the rollout, Codex emits a warning and applies a one-time model-switch instruction on the next turn.
356 444
445### Manage a thread goal
446
447`thread/goal/set`, `thread/goal/get`, and `thread/goal/clear` are experimental
448and require `capabilities.experimentalApi = true` plus the `goals` feature. Use
449them for the same persisted goal state surfaced by `/goal` in the TUI.
450
451```json
452{ "method": "thread/goal/set", "id": 13, "params": {
453 "threadId": "thr_123",
454 "objective": "Finish the migration and keep tests green",
455 "status": "active",
456 "tokenBudget": 40000
457} }
458{ "id": 13, "result": { "goal": {
459 "threadId": "thr_123",
460 "objective": "Finish the migration and keep tests green",
461 "status": "active",
462 "tokenBudget": 40000,
463 "tokensUsed": 0,
464 "timeUsedSeconds": 0
465} } }
466{ "method": "thread/goal/updated", "params": {
467 "threadId": "thr_123",
468 "goal": {
469 "threadId": "thr_123",
470 "objective": "Finish the migration and keep tests green",
471 "status": "active",
472 "tokenBudget": 40000,
473 "tokensUsed": 0,
474 "timeUsedSeconds": 0
475 }
476} }
477```
478
479Goal objectives must be non-empty and at most 4,000 characters. Supplying a new
480objective replaces the goal and resets usage accounting. Supplying the current
481non-terminal objective, or omitting `objective`, updates status or token budget
482while preserving usage history.
483
357To branch from a stored session, call `thread/fork` with the `thread.id`. This creates a new thread id and emits a `thread/started` notification for it:484To branch from a stored session, call `thread/fork` with the `thread.id`. This creates a new thread id and emits a `thread/started` notification for it:
358 485
359```json486```json
360{ "method": "thread/fork", "id": 12, "params": { "threadId": "thr_123" } }487{ "method": "thread/fork", "id": 12, "params": { "threadId": "thr_123" } }
361488{ "id": 12, "result": { "thread": { "id": "thr_456" } } }{ "id": 12, "result": { "thread": { "id": "thr_456", "sessionId": "thr_123", "forkedFromId": "thr_123" } } }
362{ "method": "thread/started", "params": { "thread": { "id": "thr_456" } } }489{ "method": "thread/started", "params": { "thread": { "id": "thr_456" } } }
363```490```
364 491
378 505
379Unlike `thread/resume`, `thread/read` doesn't load the thread into memory or emit `thread/started`.506Unlike `thread/resume`, `thread/read` doesn't load the thread into memory or emit `thread/started`.
380 507
508### List thread turns
509
510Use `thread/turns/list` to page a stored thread's turn history without resuming it. Results default to newest-first so clients can fetch older turns with `nextCursor`. The response also includes `backwardsCursor`; pass it as `cursor` with `sortDirection: "asc"` to fetch turns newer than the first item from the earlier page.
511
512`itemsView` controls how much turn-item data the response includes:
513
514- `notLoaded` omits items.
515- `summary` returns summarized item data and is the default when omitted.
516- `full` returns full item data.
517
518```json
519{ "method": "thread/turns/list", "id": 20, "params": {
520 "threadId": "thr_123",
521 "limit": 50,
522 "sortDirection": "desc",
523 "itemsView": "summary"
524} }
525{ "id": 20, "result": {
526 "data": [],
527 "nextCursor": "older-turns-cursor-or-null",
528 "backwardsCursor": "newer-turns-cursor-or-null"
529} }
530```
531
532`thread/turns/items/list` is reserved for paged turn-item loading, but the
533current server returns an unsupported-method error.
534
381### List threads (with pagination & filters)535### List threads (with pagination & filters)
382 536
383`thread/list` lets you render a history UI. Results default to newest-first by `createdAt`. Filters apply before pagination. Pass any combination of:537`thread/list` lets you render a history UI. Results default to newest-first by `createdAt`. Filters apply before pagination. Pass any combination of:
389- `sourceKinds` - restrict results to specific thread sources. When omitted or `[]`, the server defaults to interactive sources only: `cli` and `vscode`.543- `sourceKinds` - restrict results to specific thread sources. When omitted or `[]`, the server defaults to interactive sources only: `cli` and `vscode`.
390- `archived` - when `true`, list archived threads only. When `false` or omitted, list non-archived threads (default).544- `archived` - when `true`, list archived threads only. When `false` or omitted, list non-archived threads (default).
391- `cwd` - restrict results to threads whose session current working directory exactly matches this path.545- `cwd` - restrict results to threads whose session current working directory exactly matches this path.
546- `searchTerm` - search stored thread summaries and metadata before pagination.
392 547
393`sourceKinds` accepts the following values:548`sourceKinds` accepts the following values:
394 549
422 577
423When `nextCursor` is `null`, you have reached the final page.578When `nextCursor` is `null`, you have reached the final page.
424 579
580### Update stored thread metadata
581
582Use `thread/metadata/update` to patch stored thread metadata without resuming the thread. Today this supports persisted `gitInfo`; omitted fields are left unchanged, and explicit `null` clears a stored value.
583
584```json
585{ "method": "thread/metadata/update", "id": 21, "params": {
586 "threadId": "thr_123",
587 "gitInfo": { "branch": "feature/sidebar-pr" }
588} }
589{ "id": 21, "result": {
590 "thread": {
591 "id": "thr_123",
592 "gitInfo": { "sha": null, "branch": "feature/sidebar-pr", "originUrl": null }
593 }
594} }
595```
596
425### Track thread status changes597### Track thread status changes
426 598
427`thread/status/changed` is emitted whenever a loaded thread's runtime status changes. The payload includes `threadId` and the new `status`.599`thread/status/changed` is emitted whenever a loaded thread's runtime status changes. The payload includes `threadId` and the new `status`.
450`thread/unsubscribe` removes the current connection's subscription to a thread. The response status is one of:622`thread/unsubscribe` removes the current connection's subscription to a thread. The response status is one of:
451 623
452- `unsubscribed` when the connection was subscribed and is now removed.624- `unsubscribed` when the connection was subscribed and is now removed.
453625- `notSubscribed` when the connection was not subscribed to that thread.- `notSubscribed` when the connection wasn't subscribed to that thread.
454626- `notLoaded` when the thread is not loaded.- `notLoaded` when the thread isn't loaded.
455 627
456628If this was the last subscriber, the server unloads the thread and emits a `thread/status/changed` transition to `notLoaded` plus `thread/closed`.If this was the last subscriber, the server keeps the thread loaded until it has no subscribers and no thread activity for 30 minutes. When the grace period expires, app-server unloads the thread and emits a `thread/status/changed` transition to `notLoaded` plus `thread/closed`.
457 629
458```json630```json
459{ "method": "thread/unsubscribe", "id": 22, "params": { "threadId": "thr_123" } }631{ "method": "thread/unsubscribe", "id": 22, "params": { "threadId": "thr_123" } }
460{ "id": 22, "result": { "status": "unsubscribed" } }632{ "id": 22, "result": { "status": "unsubscribed" } }
633```
634
635If the thread later expires:
636
637```json
461{ "method": "thread/status/changed", "params": {638{ "method": "thread/status/changed", "params": {
462 "threadId": "thr_123",639 "threadId": "thr_123",
463 "status": { "type": "notLoaded" }640 "status": { "type": "notLoaded" }
498{ "id": 25, "result": {} }675{ "id": 25, "result": {} }
499```676```
500 677
678### Run a thread shell command
679
680Use `thread/shellCommand` for user-initiated shell commands that belong to a thread. The request returns immediately with `{}` while progress streams through standard `turn/*` and `item/*` notifications.
681
682This API runs outside the sandbox with full access and doesn't inherit the thread sandbox policy. Clients should expose it only for explicit user-initiated commands.
683
684If the thread already has an active turn, the command runs as an auxiliary action on that turn and its formatted output is injected into the turn's message stream. If the thread is idle, app-server starts a standalone turn for the shell command.
685
686```json
687{ "method": "thread/shellCommand", "id": 26, "params": { "threadId": "thr_b", "command": "git status --short" } }
688{ "id": 26, "result": {} }
689```
690
691### Clean background terminals
692
693Use `thread/backgroundTerminals/clean` to stop all running background terminals associated with a thread. This method is experimental and requires `capabilities.experimentalApi = true`.
694
695```json
696{ "method": "thread/backgroundTerminals/clean", "id": 27, "params": { "threadId": "thr_b" } }
697{ "id": 27, "result": {} }
698```
699
501### Roll back recent turns700### Roll back recent turns
502 701
503Use `thread/rollback` to remove the last `numTurns` entries from the in-memory context and persist a rollback marker in the rollout log. The returned `thread` includes `turns` populated after the rollback.702Use `thread/rollback` to remove the last `numTurns` entries from the in-memory context and persist a rollback marker in the rollout log. The returned `thread` includes `turns` populated after the rollback.
504 703
505```json704```json
506705{ "method": "thread/rollback", "id": 26, "params": { "threadId": "thr_b", "numTurns": 1 } }{ "method": "thread/rollback", "id": 28, "params": { "threadId": "thr_b", "numTurns": 1 } }
507706{ "id": 26, "result": { "thread": { "id": "thr_b", "name": "Bug bash notes", "ephemeral": false } } }{ "id": 28, "result": { "thread": { "id": "thr_b", "name": "Bug bash notes", "ephemeral": false } } }
508```707```
509 708
510## Turns709## Turns
570 "writableRoots": ["/Users/me/project"],769 "writableRoots": ["/Users/me/project"],
571 "networkAccess": true770 "networkAccess": true
572 },771 },
573772 "model": "gpt-5.1-codex", "model": "gpt-5.4",
574 "effort": "medium",773 "effort": "medium",
575 "summary": "concise",774 "summary": "concise",
576 "personality": "friendly",775 "personality": "friendly",
584{ "id": 30, "result": { "turn": { "id": "turn_456", "status": "inProgress", "items": [], "error": null } } }783{ "id": 30, "result": { "turn": { "id": "turn_456", "status": "inProgress", "items": [], "error": null } } }
585```784```
586 785
786### Inject items into a thread
787
788Use `thread/inject_items` to append prebuilt Responses API items to a loaded thread's prompt history without starting a user turn. These items are persisted to the rollout and included in subsequent model requests.
789
790```json
791{ "method": "thread/inject_items", "id": 31, "params": {
792 "threadId": "thr_123",
793 "items": [
794 {
795 "type": "message",
796 "role": "assistant",
797 "content": [{ "type": "output_text", "text": "Previously computed context." }]
798 }
799 ]
800} }
801{ "id": 31, "result": {} }
802```
803
587### Steer an active turn804### Steer an active turn
588 805
589Use `turn/steer` to append more user input to the active in-flight turn.806Use `turn/steer` to append more user input to the active in-flight turn.
692 909
693Use this notification to render the reviewer output in your client.910Use this notification to render the reviewer output in your client.
694 911
912## Process execution
913
914`process/*` is an experimental, explicit process-control API. It requires
915`capabilities.experimentalApi = true` and runs outside Codex's sandbox. Use it
916only when your client intentionally exposes local process control without a
917sandbox.
918
919Start a process with `process/spawn` and provide a `processHandle`, then use
920that handle for stdin, resize, and kill requests. Output streams through
921`process/outputDelta` notifications and completion streams through
922`process/exited`.
923
924```json
925{ "method": "process/spawn", "id": 48, "params": {
926 "command": ["python3", "-m", "pytest", "-q"],
927 "processHandle": "pytest-1",
928 "cwd": "/Users/me/project",
929 "tty": true
930} }
931{ "id": 48, "result": {} }
932{ "method": "process/outputDelta", "params": {
933 "processHandle": "pytest-1",
934 "stream": "stdout",
935 "deltaBase64": "Li4u"
936} }
937{ "method": "process/exited", "params": {
938 "processHandle": "pytest-1",
939 "exitCode": 0
940} }
941```
942
943Use `process/writeStdin` with `deltaBase64`, `closeStdin`, or both to send
944input. Use `process/resizePty` for PTY resize events and `process/kill` to
945terminate a running process.
946
695## Command execution947## Command execution
696 948
697`command/exec` runs a single command (`argv` array) under the server sandbox without creating a thread.949`command/exec` runs a single command (`argv` array) under the server sandbox without creating a thread.
713- The server rejects empty `command` arrays.965- The server rejects empty `command` arrays.
714- `sandboxPolicy` accepts the same shape used by `turn/start` (for example, `dangerFullAccess`, `readOnly`, `workspaceWrite`, `externalSandbox`).966- `sandboxPolicy` accepts the same shape used by `turn/start` (for example, `dangerFullAccess`, `readOnly`, `workspaceWrite`, `externalSandbox`).
715- When omitted, `timeoutMs` falls back to the server default.967- When omitted, `timeoutMs` falls back to the server default.
968- Set `tty: true` for PTY-backed sessions, and use `processId` when you plan to follow up with `command/exec/write`, `command/exec/resize`, or `command/exec/terminate`.
969- Set `streamStdoutStderr: true` to receive `command/exec/outputDelta` notifications while the command is running.
716 970
717### Read admin requirements (`configRequirements/read`)971### Read admin requirements (`configRequirements/read`)
718 972
724 "requirements": {978 "requirements": {
725 "allowedApprovalPolicies": ["onRequest", "unlessTrusted"],979 "allowedApprovalPolicies": ["onRequest", "unlessTrusted"],
726 "allowedSandboxModes": ["readOnly", "workspaceWrite"],980 "allowedSandboxModes": ["readOnly", "workspaceWrite"],
981 "featureRequirements": {
982 "personality": true,
983 "unified_exec": false
984 },
727 "network": {985 "network": {
728 "enabled": true,986 "enabled": true,
729 "allowedDomains": ["api.openai.com"],987 "allowedDomains": ["api.openai.com"],
734} }992} }
735```993```
736 994
737995`result.requirements` is `null` when no requirements are configured. When present, the optional `network` object carries managed proxy constraints (domain rules, proxy settings, and unix-socket policy).`result.requirements` is `null` when no requirements are configured. See the docs on [`requirements.toml`](https://developers.openai.com/codex/config-reference#requirementstoml) for details on supported keys and values.
738 996
739### Windows sandbox setup (`windowsSandbox/setupStart`)997### Windows sandbox setup (`windowsSandbox/setupStart`)
740 998
759- `elevated` - run the elevated Windows sandbox setup path.1017- `elevated` - run the elevated Windows sandbox setup path.
760- `unelevated` - run the legacy setup/preflight path.1018- `unelevated` - run the legacy setup/preflight path.
761 1019
1020## Filesystem
1021
1022The v2 filesystem APIs operate on absolute paths. Use `fs/watch` when a client needs to invalidate UI state after a file or directory changes.
1023
1024```json
1025{ "method": "fs/watch", "id": 54, "params": {
1026 "watchId": "0195ec6b-1d6f-7c2e-8c7a-56f2c4a8b9d1",
1027 "path": "/Users/me/project/.git/HEAD"
1028} }
1029{ "id": 54, "result": { "path": "/Users/me/project/.git/HEAD" } }
1030{ "method": "fs/changed", "params": {
1031 "watchId": "0195ec6b-1d6f-7c2e-8c7a-56f2c4a8b9d1",
1032 "changedPaths": ["/Users/me/project/.git/HEAD"]
1033} }
1034{ "method": "fs/unwatch", "id": 55, "params": {
1035 "watchId": "0195ec6b-1d6f-7c2e-8c7a-56f2c4a8b9d1"
1036} }
1037{ "id": 55, "result": {} }
1038```
1039
1040Watching a file emits `fs/changed` for that file path, including updates delivered by replace or rename operations.
1041
762## Events1042## Events
763 1043
764Event notifications are the server-initiated stream for thread lifecycles, turn lifecycles, and the items within them. After you start or resume a thread, keep reading the active transport stream for `thread/started`, `thread/archived`, `thread/unarchived`, `thread/closed`, `thread/status/changed`, `turn/*`, `item/*`, and `serverRequest/resolved` notifications.1044Event notifications are the server-initiated stream for thread lifecycles, turn lifecycles, and the items within them. After you start or resume a thread, keep reading the active transport stream for `thread/started`, `thread/archived`, `thread/unarchived`, `thread/closed`, `thread/status/changed`, `turn/*`, `item/*`, and `serverRequest/resolved` notifications.
769 1049
770- Exact-match only: `item/agentMessage/delta` suppresses only that method.1050- Exact-match only: `item/agentMessage/delta` suppresses only that method.
771- Unknown method names are ignored.1051- Unknown method names are ignored.
7721052- Applies to both legacy (`codex/event/*`) and v2 (`thread/*`, `turn/*`, `item/*`, etc.) notifications.- Applies to the current `thread/*`, `turn/*`, `item/*`, and related v2 notifications.
773- Doesn't apply to requests, responses, or errors.1053- Doesn't apply to requests, responses, or errors.
774 1054
775### Fuzzy file search events (experimental)1055### Fuzzy file search events (experimental)
829- `item/reasoning/summaryPartAdded` - marks a boundary between reasoning summary sections.1109- `item/reasoning/summaryPartAdded` - marks a boundary between reasoning summary sections.
830- `item/reasoning/textDelta` - streams raw reasoning text (when supported by the model).1110- `item/reasoning/textDelta` - streams raw reasoning text (when supported by the model).
831- `item/commandExecution/outputDelta` - streams stdout/stderr for a command; append deltas in order.1111- `item/commandExecution/outputDelta` - streams stdout/stderr for a command; append deltas in order.
8321112- `item/fileChange/outputDelta` - contains the tool call response of the underlying `apply_patch` tool call.- `item/fileChange/outputDelta` - deprecated compatibility notification for legacy `apply_patch` text output. Current app-server versions no longer emit it; use `fileChange` items and `turn/diff/updated` instead.
833 1113
834## Errors1114## Errors
835 1115
868 1149
869When `networkApprovalContext` is present, the prompt is for managed network access (not a general shell-command approval). The current v2 schema exposes the target `host` and `protocol`; clients should render a network-specific prompt and not rely on `command` being a user-meaningful shell command preview.1150When `networkApprovalContext` is present, the prompt is for managed network access (not a general shell-command approval). The current v2 schema exposes the target `host` and `protocol`; clients should render a network-specific prompt and not rely on `command` being a user-meaningful shell command preview.
870 1151
8711152Codex deduplicates concurrent network approval prompts by destination (`host`, protocol, and port). The app-server may therefore send one prompt that unblocks multiple queued requests to the same destination, while different ports on the same host are treated separately.Codex groups concurrent network approval prompts by destination (`host`, protocol, and port). The app-server may therefore send one prompt that unblocks multiple queued requests to the same destination, while different ports on the same host are treated separately.
872 1153
873### File change approvals1154### File change approvals
874 1155
888 1169
889`dynamicTools` on `thread/start` and the corresponding `item/tool/call` request or response flow are experimental APIs.1170`dynamicTools` on `thread/start` and the corresponding `item/tool/call` request or response flow are experimental APIs.
890 1171
1172Dynamic tool names and namespace names must follow Responses API naming
1173constraints. Avoid reserved namespace names used by built-in Codex tools.
1174
891When a dynamic tool is invoked during a turn, app-server emits:1175When a dynamic tool is invoked during a turn, app-server emits:
892 1176
8931. `item/started` with `item.type = "dynamicToolCall"`, `status = "inProgress"`, plus `tool` and `arguments`.11771. `item/started` with `item.type = "dynamicToolCall"`, `status = "inProgress"`, plus `tool` and `arguments`.
979} }1263} }
980```1264```
981 1265
1266The server also emits `skills/changed` notifications when watched local skill files change. Treat this as an invalidation signal and rerun `skills/list` with your current params when needed.
1267
982To enable or disable a skill by path:1268To enable or disable a skill by path:
983 1269
984```json1270```json
1145 1431
1146### Detect and import external agent config1432### Detect and import external agent config
1147 1433
11481434Use `externalAgentConfig/detect` to discover migratable external-agent artifacts, then pass the selected entries to `externalAgentConfig/import`.Use `externalAgentConfig/detect` to discover external-agent artifacts that can be migrated, then pass the selected entries to `externalAgentConfig/import`.
1149 1435
1150Detection example:1436Detection example:
1151 1437
1185{ "id": 64, "result": {} }1471{ "id": 64, "result": {} }
1186```1472```
1187 1473
11881474Supported `itemType` values are `AGENTS_MD`, `CONFIG`, `SKILLS`, and `MCP_SERVER_CONFIG`. Detection returns only items that still have work to do. For example, AGENTS migration is skipped when `AGENTS.md` already exists and is non-empty, and skill imports do not overwrite existing skill directories.When a request includes plugin imports, the server emits `externalAgentConfig/import/completed` after the import finishes. This notification may arrive immediately after the response or after background remote imports complete.
1475
1476Supported `itemType` values are `AGENTS_MD`, `CONFIG`, `SKILLS`, `PLUGINS`,
1477and `MCP_SERVER_CONFIG`. For `PLUGINS` items, `details.plugins` lists each
1478`marketplaceName` and the `pluginNames` Codex can try to migrate. Detection
1479returns only items that still have work to do. For example, Codex skips AGENTS
1480migration when `AGENTS.md` already exists and is non-empty, and skill imports
1481don't overwrite existing skill directories.
1482
1483When detecting plugins from `.claude/settings.json`, Codex reads configured
1484marketplace sources from `extraKnownMarketplaces`. If `enabledPlugins` contains
1485plugins from `claude-plugins-official` but the marketplace source is missing,
1486Codex infers `anthropics/claude-plugins-official` as the source.
1189 1487
1190## Auth endpoints1488## Auth endpoints
1191 1489
11921490The JSON-RPC auth/account surface exposes request/response methods plus server-initiated notifications (no `id`). Use these to determine auth state, start or cancel logins, logout, and inspect ChatGPT rate limits.The JSON-RPC auth/account surface exposes request/response methods plus server-initiated notifications (no `id`). Use these to determine auth state, start or cancel logins, logout, inspect ChatGPT rate limits, and notify workspace owners about depleted credits or usage limits.
1193 1491
1194### Authentication modes1492### Authentication modes
1195 1493
11961494Codex supports three authentication modes. `account/updated.authMode` shows the active mode, and `account/read` also reports it.Codex supports these authentication modes. `account/updated.authMode` shows the active mode and includes the current ChatGPT `planType` when available. `account/read` also reports account and plan details.
1197 1495
11981496- **API key (`apikey`)** - the caller supplies an OpenAI API key and Codex stores it for API requests.- **API key (`apikey`)** - the caller supplies an OpenAI API key with `type: "apiKey"`, and Codex stores it for API requests.
11991497- **ChatGPT managed (`chatgpt`)** - Codex owns the ChatGPT OAuth flow, persists tokens, and refreshes them automatically.- **ChatGPT managed (`chatgpt`)** - Codex owns the ChatGPT OAuth flow, persists tokens, and refreshes them automatically. Start with `type: "chatgpt"` for the browser flow or `type: "chatgptDeviceCode"` for the device-code flow.
12001498- **ChatGPT external tokens (`chatgptAuthTokens`)** - a host app supplies `idToken` and `accessToken` directly. Codex stores these tokens in memory, and the host app must refresh them when asked.- **ChatGPT external tokens (`chatgptAuthTokens`)** - experimental and intended for host apps that already own the user's ChatGPT auth lifecycle. The host app supplies an `accessToken`, `chatgptAccountId`, and optional `chatgptPlanType` directly, and must refresh the token when asked.
1201 1499
1202### API overview1500### API overview
1203 1501
1204- `account/read` - fetch current account info; optionally refresh tokens.1502- `account/read` - fetch current account info; optionally refresh tokens.
12051503- `account/login/start` - begin login (`apiKey`, `chatgpt`, or `chatgptAuthTokens`).- `account/login/start` - begin login (`apiKey`, `chatgpt`, `chatgptDeviceCode`, or experimental `chatgptAuthTokens`).
1206- `account/login/completed` (notify) - emitted when a login attempt finishes (success or error).1504- `account/login/completed` (notify) - emitted when a login attempt finishes (success or error).
12071505- `account/login/cancel` - cancel a pending ChatGPT login by `loginId`.- `account/login/cancel` - cancel a pending managed ChatGPT login by `loginId`.
1208- `account/logout` - sign out; triggers `account/updated`.1506- `account/logout` - sign out; triggers `account/updated`.
12091507- `account/updated` (notify) - emitted whenever auth mode changes (`authMode`: `apikey`, `chatgpt`, `chatgptAuthTokens`, or `null`).- `account/updated` (notify) - emitted whenever auth mode changes (`authMode`: `apikey`, `chatgpt`, `chatgptAuthTokens`, or `null`) and includes `planType` when available.
1210- `account/chatgptAuthTokens/refresh` (server request) - request fresh externally managed ChatGPT tokens after an authorization error.1508- `account/chatgptAuthTokens/refresh` (server request) - request fresh externally managed ChatGPT tokens after an authorization error.
1211- `account/rateLimits/read` - fetch ChatGPT rate limits.1509- `account/rateLimits/read` - fetch ChatGPT rate limits.
1212- `account/rateLimits/updated` (notify) - emitted whenever a user's ChatGPT rate limits change.1510- `account/rateLimits/updated` (notify) - emitted whenever a user's ChatGPT rate limits change.
1511- `account/sendAddCreditsNudgeEmail` - ask ChatGPT to email a workspace owner about depleted credits or a reached usage limit.
1213- `mcpServer/oauthLogin/completed` (notify) - emitted after a `mcpServer/oauth/login` flow finishes; payload includes `{ name, success, error? }`.1512- `mcpServer/oauthLogin/completed` (notify) - emitted after a `mcpServer/oauth/login` flow finishes; payload includes `{ name, success, error? }`.
1513- `mcpServer/startupStatus/updated` (notify) - emitted when a configured MCP server's startup status changes for a loaded thread; payload includes `{ name, status, error }`.
1214 1514
1215### 1) Check auth state1515### 1) Check auth state
1216 1516
1282 ```1584 ```
1283 1585
1284 ```json1586 ```json
12851587 { "method": "account/updated", "params": { "authMode": "apikey" } } {
1588 "method": "account/updated",
1589 "params": { "authMode": "apikey", "planType": null }
1590 }
1286 ```1591 ```
1287 1592
1288### 3) Log in with ChatGPT (browser flow)1593### 3) Log in with ChatGPT (browser flow)
1314 ```1620 ```
1315 1621
1316 ```json1622 ```json
13171623 { "method": "account/updated", "params": { "authMode": "chatgpt" } } {
1624 "method": "account/updated",
1625 "params": { "authMode": "chatgpt", "planType": "plus" }
1626 }
1318 ```1627 ```
1319 1628
13201629### 3b) Log in with externally managed ChatGPT tokens (`chatgptAuthTokens`)### 3b) Log in with ChatGPT (device-code flow)
1321 1630
13221631Use this mode when a host application owns the user’s ChatGPT auth lifecycle and supplies tokens directly.Use this flow when your client owns the sign-in ceremony or when a browser callback is brittle.
1632
16331. Start:
1634
1635 ```json
1636 {
1637 "method": "account/login/start",
1638 "id": 4,
1639 "params": { "type": "chatgptDeviceCode" }
1640 }
1641 ```
1642
1643 ```json
1644 {
1645 "id": 4,
1646 "result": {
1647 "type": "chatgptDeviceCode",
1648 "loginId": "<uuid>",
1649 "verificationUrl": "https://auth.openai.com/codex/device",
1650 "userCode": "ABCD-1234"
1651 }
1652 }
1653 ```
1654
16552. Show `verificationUrl` and `userCode` to the user; the frontend owns the UX.
16563. Wait for notifications:
1657
1658 ```json
1659 {
1660 "method": "account/login/completed",
1661 "params": { "loginId": "<uuid>", "success": true, "error": null }
1662 }
1663 ```
1664
1665 ```json
1666 {
1667 "method": "account/updated",
1668 "params": { "authMode": "chatgpt", "planType": "plus" }
1669 }
1670 ```
1671
1672### 3c) Log in with externally managed ChatGPT tokens (`chatgptAuthTokens`)
1673
1674Use this experimental mode only when a host application owns the user's ChatGPT auth lifecycle and supplies tokens directly. Clients must set `capabilities.experimentalApi = true` during `initialize` before using this login type.
1323 1675
13241. Send:16761. Send:
1325 1677
1329 "id": 7,1681 "id": 7,
1330 "params": {1682 "params": {
1331 "type": "chatgptAuthTokens",1683 "type": "chatgptAuthTokens",
13321684 "idToken": "<jwt>", "accessToken": "<jwt>",
13331685 "accessToken": "<jwt>" "chatgptAccountId": "org-123",
1686 "chatgptPlanType": "business"
1334 }1687 }
1335 }1688 }
1336 ```1689 ```
1351 ```json1706 ```json
1352 {1707 {
1353 "method": "account/updated",1708 "method": "account/updated",
13541709 "params": { "authMode": "chatgptAuthTokens" } "params": { "authMode": "chatgptAuthTokens", "planType": "business" }
1355 }1710 }
1356 ```1711 ```
1357 1712
1363 "id": 8,1718 "id": 8,
1364 "params": { "reason": "unauthorized", "previousAccountId": "org-123" }1719 "params": { "reason": "unauthorized", "previousAccountId": "org-123" }
1365}1720}
13661721{ "id": 8, "result": { "idToken": "<jwt>", "accessToken": "<jwt>" } }{ "id": 8, "result": { "accessToken": "<jwt>", "chatgptAccountId": "org-123", "chatgptPlanType": "business" } }
1367```1722```
1368 1723
1369The server retries the original request after a successful refresh response. Requests time out after about 10 seconds.1724The server retries the original request after a successful refresh response. Requests time out after about 10 seconds.
1380```json1735```json
1381{ "method": "account/logout", "id": 5 }1736{ "method": "account/logout", "id": 5 }
1382{ "id": 5, "result": {} }1737{ "id": 5, "result": {} }
13831738{ "method": "account/updated", "params": { "authMode": null } }{ "method": "account/updated", "params": { "authMode": null, "planType": null } }
1384```1739```
1385 1740
1386### 6) Rate limits (ChatGPT)1741### 6) Rate limits (ChatGPT)
1392 "limitId": "codex",1747 "limitId": "codex",
1393 "limitName": null,1748 "limitName": null,
1394 "primary": { "usedPercent": 25, "windowDurationMins": 15, "resetsAt": 1730947200 },1749 "primary": { "usedPercent": 25, "windowDurationMins": 15, "resetsAt": 1730947200 },
13951750 "secondary": null "secondary": null,
1751 "rateLimitReachedType": null
1396 },1752 },
1397 "rateLimitsByLimitId": {1753 "rateLimitsByLimitId": {
1398 "codex": {1754 "codex": {
1399 "limitId": "codex",1755 "limitId": "codex",
1400 "limitName": null,1756 "limitName": null,
1401 "primary": { "usedPercent": 25, "windowDurationMins": 15, "resetsAt": 1730947200 },1757 "primary": { "usedPercent": 25, "windowDurationMins": 15, "resetsAt": 1730947200 },
14021758 "secondary": null "secondary": null,
1759 "rateLimitReachedType": null
1403 },1760 },
1404 "codex_other": {1761 "codex_other": {
1405 "limitId": "codex_other",1762 "limitId": "codex_other",
1406 "limitName": "codex_other",1763 "limitName": "codex_other",
1407 "primary": { "usedPercent": 42, "windowDurationMins": 60, "resetsAt": 1730950800 },1764 "primary": { "usedPercent": 42, "windowDurationMins": 60, "resetsAt": 1730950800 },
14081765 "secondary": null "secondary": null,
1766 "rateLimitReachedType": null
1409 }1767 }
1410 }1768 }
1411} }1769} }
1426- `usedPercent` is current usage within the quota window.1784- `usedPercent` is current usage within the quota window.
1427- `windowDurationMins` is the quota window length.1785- `windowDurationMins` is the quota window length.
1428- `resetsAt` is a Unix timestamp (seconds) for the next reset.1786- `resetsAt` is a Unix timestamp (seconds) for the next reset.
1787- `planType` is included when the server returns the ChatGPT plan associated with a bucket.
1788- `credits` is included when the server returns remaining workspace credit details.
1789- `rateLimitReachedType` identifies the server-classified limit state when one has been reached.
1790
1791### 7) Notify a workspace owner about a limit
1792
1793Use `account/sendAddCreditsNudgeEmail` to ask ChatGPT to email a workspace owner when credits are depleted or a usage limit has been reached.
1794
1795```json
1796{ "method": "account/sendAddCreditsNudgeEmail", "id": 7, "params": { "creditType": "credits" } }
1797{ "id": 7, "result": { "status": "sent" } }
1798```
1799
1800Use `creditType: "credits"` when workspace credits are depleted, or `creditType: "usage_limit"` when the workspace usage limit has been reached. If the owner was already notified recently, the response status is `cooldown_active`.