For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
Primary navigation

Codex App Server

Embed Codex into your product with the app-server protocol

Codex 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). See the Open Source page for the full list of open-source Codex components.

If you are automating jobs or running Codex in CI, use the Codex SDK instead.

Connect the CLI terminal UI

Remote terminal UI mode lets you run app-server on one machine and connect the Codex CLI terminal interface from another. Start a WebSocket listener:

codex app-server --listen ws://127.0.0.1:4500

Then connect the terminal UI:

codex --remote ws://127.0.0.1:4500

For a non-local connection, configure WebSocket authentication and put the connection behind TLS. Store the bearer token in an environment variable and pass its name instead of putting the token on the command line:

export CODEX_REMOTE_TOKEN="$(cat "$HOME/.codex/app-server-token")"
codex --remote wss://remote-host:4500 \
  --remote-auth-token-env CODEX_REMOTE_TOKEN

The --remote option accepts ws://, wss://, unix://, and unix://PATH endpoints. Use plain WebSockets only for localhost or an SSH port-forwarded connection.

Connect a remote Code Mode host

By default, app-server starts a local Code Mode host. To use a remote host instead, pass its secure WebSocket URL:

codex app-server --code-mode-host wss://code-mode.example.com/host

--code-mode-host controls the outbound connection from app-server to its Code Mode host. It doesn’t change --listen, which controls how clients connect to app-server. Every thread in the same app-server process shares the selected Code Mode host connection.

Use wss:// for a remote host. Use ws:// only for a localhost or SSH-forwarded connection. The app-server command and WebSocket transport are experimental and aren’t supported for production workloads.

Protocol

Like MCP, codex app-server supports bidirectional communication using JSON-RPC 2.0 messages (with the "jsonrpc":"2.0" header omitted on the wire).

Supported transports:

  • stdio (--listen stdio://, default): newline-delimited JSON (JSONL).
  • websocket (--listen ws://IP:PORT, experimental and unsupported): one JSON-RPC message per WebSocket text frame.
  • Unix socket (--listen unix:// or --listen unix://PATH): WebSocket connections over Codex’s default app-server control socket or a custom Unix socket path, using the standard HTTP Upgrade handshake.
  • off (--listen off): don’t expose a local transport.

When you run with --listen ws://IP:PORT, the same listener also serves basic HTTP health probes:

  • GET /readyz returns 200 OK once the listener accepts new connections.
  • GET /healthz returns 200 OK when the request doesn’t include an Origin header.
  • Requests with an Origin header are rejected with 403 Forbidden.

WebSocket transport is experimental and unsupported. Local listeners such as ws://127.0.0.1:PORT are appropriate for localhost and SSH port-forwarding workflows. Non-loopback WebSocket listeners currently allow unauthenticated connections by default during rollout, so configure WebSocket auth before exposing one remotely.

Supported WebSocket auth flags:

  • --ws-auth capability-token --ws-token-file /absolute/path
  • --ws-auth capability-token --ws-token-sha256 HEX
  • --ws-auth signed-bearer-token --ws-shared-secret-file /absolute/path

For signed bearer tokens, you can also set --ws-issuer, --ws-audience, and --ws-max-clock-skew-seconds. Clients present the credential as Authorization: Bearer <token> during the WebSocket handshake, and app-server enforces auth before JSON-RPC initialize.

Prefer --ws-token-file over passing raw bearer tokens on the command line. Use --ws-token-sha256 only when the client keeps the raw high-entropy token in a separate local secret store; the hash is only a verifier, and clients still need the original token.

In 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.

Message schema

Requests include method, params, and id:

{ "method": "thread/start", "id": 10, "params": { "model": "gpt-5.6-terra" } }

Responses echo the id with either result or error:

{ "id": 10, "result": { "thread": { "id": "thr_123" } } }
{ "id": 10, "error": { "code": 123, "message": "Something went wrong" } }

Notifications omit id and use only method and params:

{ "method": "turn/started", "params": { "turn": { "id": "turn_456" } } }

You can generate a TypeScript schema or a JSON Schema bundle from the CLI. Each output is specific to the Codex version you ran, so the generated artifacts match that version exactly:

codex app-server generate-ts --out ./schemas
codex app-server generate-json-schema --out ./schemas

Getting started

  1. Start the server with codex app-server (default stdio transport), codex app-server --listen ws://127.0.0.1:4500 (TCP WebSocket), or codex app-server --listen unix:// (default Unix socket).
  2. Connect a client over the selected transport, then send initialize followed by the initialized notification.
  3. Start a thread and a turn, then keep reading notifications from the active transport stream.

Example (Node.js / TypeScript):

import { spawn } from "node:child_process";
import readline from "node:readline";

const proc = spawn("codex", ["app-server"], {
  stdio: ["pipe", "pipe", "inherit"],
});
const rl = readline.createInterface({ input: proc.stdout });

const send = (message: unknown) => {
  proc.stdin.write(`${JSON.stringify(message)}\n`);
};

let threadId: string | null = null;

rl.on("line", (line) => {
  const msg = JSON.parse(line) as any;
  console.log("server:", msg);

  if (msg.id === 1 && msg.result?.thread?.id && !threadId) {
    threadId = msg.result.thread.id;
    send({
      method: "turn/start",
      id: 2,
      params: {
        threadId,
        input: [{ type: "text", text: "Summarize this repo." }],
      },
    });
  }
});

send({
  method: "initialize",
  id: 0,
  params: {
    clientInfo: {
      name: "my_product",
      title: "My Product",
      version: "0.1.0",
    },
  },
});
send({ method: "initialized", params: {} });
send({ method: "thread/start", id: 1, params: { model: "gpt-5.6-terra" } });

Core primitives

  • Thread: A conversation between a user and the Codex agent. Threads contain turns.
  • Turn: A single user request and the agent work that follows. Turns contain items and stream incremental updates.
  • Item: A unit of input or output (user message, agent message, command runs, file change, tool call, and more).

Use the thread APIs to create, list, or archive conversations. Drive a conversation with turn APIs and stream progress via turn notifications.

Lifecycle overview

  • Initialize once per connection: Immediately after opening a transport connection, send an initialize request with your client metadata, then emit initialized. The server rejects any request on that connection before this handshake.
  • Start (or resume) a thread: Call thread/start for a new conversation, thread/resume to continue an existing one, or thread/fork to branch history into a new thread id.
  • Begin a turn: Call turn/start with the target threadId and user input. Optional fields override model, personality, cwd, sandbox policy, and more.
  • Steer an active turn: Call turn/steer to append user input to the currently in-flight turn without creating a new turn.
  • Stream events: After turn/start, keep reading notifications on stdout: thread/archived, thread/unarchived, item/started, item/completed, item/agentMessage/delta, tool progress, and other updates.
  • Finish the turn: The server emits turn/completed with final status when the model finishes or after a turn/interrupt cancellation.

Initialization

Clients 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.

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.

initialize.params.capabilities also supports these client capabilities:

  • optOutNotificationMethods - exact notification method names to suppress for this connection. Matching is exact (no wildcards or prefixes); unknown names are accepted and ignored.
  • requestAttestation - opt into the server-initiated attestation/generate request. Desktop hosts that provide upstream attestation respond with an opaque { "token": "..." } value.
  • mcpServerOpenaiFormElicitation - allow downstream MCP servers to send the OpenAI extended-form variant of mcpServer/elicitation/request.

Important: Use clientInfo.name to identify your client for the OpenAI Compliance Logs Platform. If you are developing a new Codex integration intended for enterprise use, please contact OpenAI to get it added to a known clients list. For more context, see the Codex logs reference.

Example (from the Codex VS Code extension):

{
  "method": "initialize",
  "id": 0,
  "params": {
    "clientInfo": {
      "name": "codex_vscode",
      "title": "Codex VS Code Extension",
      "version": "0.1.0"
    }
  }
}

Example with notification opt-out:

{
  "method": "initialize",
  "id": 1,
  "params": {
    "clientInfo": {
      "name": "my_client",
      "title": "My Client",
      "version": "0.1.0"
    },
    "capabilities": {
      "experimentalApi": true,
      "optOutNotificationMethods": ["thread/started", "item/agentMessage/delta"]
    }
  }
}

Experimental API opt-in

Some app-server methods and fields are intentionally gated behind experimentalApi capability.

  • Omit capabilities (or set experimentalApi to false) to stay on the stable API surface, and the server rejects experimental methods/fields.
  • Set capabilities.experimentalApi to true to enable experimental methods and fields.
{
  "method": "initialize",
  "id": 1,
  "params": {
    "clientInfo": {
      "name": "my_client",
      "title": "My Client",
      "version": "0.1.0"
    },
    "capabilities": {
      "experimentalApi": true
    }
  }
}

If a client sends an experimental method or field without opting in, app-server rejects it with:

<descriptor> requires experimentalApi capability

API overview

  • thread/start - create a new thread; emits thread/started and automatically subscribes you to turn/item events for that thread.
  • thread/resume - reopen an existing thread by id so later turn/start calls append to it.
  • thread/fork - fork a thread into a new thread id by copying stored history. Pass lastTurnId to copy history through that turn and omit later turns, or ephemeral: true to create an in-memory fork. Emits thread/started for the new thread; returned threads include forkedFromId when available.
  • thread/read - read a stored thread by id without resuming it; set includeTurns to return full turn history. Returned thread objects include runtime status.
  • thread/list - page through stored thread logs; supports cursor-based pagination plus modelProviders, sourceKinds, archived, isPinned, cwd, useStateDbOnly, searchTerm, and experimental parentThreadId or ancestorThreadId filters. Returned thread objects include runtime status.
  • thread/turns/list - experimental; page through a stored thread’s turn history without resuming it. itemsView controls whether turn items are omitted, summarized, or fully loaded.
  • thread/items/list - experimental; page through persisted thread items, optionally restricted to one turnId. The active thread store must support item pagination.
  • thread/loaded/list - list the thread ids currently loaded in memory.
  • thread/name/set - set or update a thread’s user-facing name for a loaded thread or a persisted rollout; emits thread/name/updated.
  • thread/goal/set - set the goal for a thread; emits thread/goal/updated.
  • thread/goal/get - read the current goal for a thread.
  • thread/goal/clear - clear the goal for a thread; emits thread/goal/cleared.
  • thread/metadata/update - patch SQLite-backed stored thread metadata, including persisted gitInfo and isPinned.
  • thread/archive - move a thread’s log file into the archived directory and attempt to archive spawned descendant thread logs that aren’t already archived; returns {} on success and emits thread/archived for each archived thread.
  • thread/delete - permanently delete a persisted active or archived thread and any spawned descendant threads; returns {} on success and emits thread/deleted for each deleted thread.
  • 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.
  • thread/unarchive - restore an archived thread rollout back into the active sessions directory; returns the restored thread and emits thread/unarchived.
  • thread/status/changed - notification emitted when a loaded thread’s runtime status changes.
  • thread/compact/start - trigger conversation history compaction for a thread; returns {} immediately while progress streams via turn/* and item/* notifications.
  • 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.
  • thread/backgroundTerminals/clean - stop all running background terminals for a thread (experimental; requires capabilities.experimentalApi).
  • thread/backgroundTerminals/list - list running background terminals for a loaded thread (experimental; requires capabilities.experimentalApi).
  • thread/backgroundTerminals/terminate - terminate one running background terminal by app-server processId (experimental; requires capabilities.experimentalApi).
  • thread/rollback - deprecated; drop the last N turns from the in-memory context and persist a rollback marker; returns the updated thread.
  • 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.”
  • thread/inject_items - append raw Responses API items to a loaded thread’s model-visible history without starting a user turn.
  • turn/steer - append user input to the active in-flight turn for a thread; returns the accepted turnId.
  • turn/interrupt - request cancellation of an in-flight turn; success is {} and the turn ends with status: "interrupted".
  • review/start - kick off the Codex reviewer for a thread; emits enteredReviewMode and exitedReviewMode items.
  • command/exec - run a single command under the server sandbox without starting a thread/turn.
  • command/exec/write - write stdin bytes to a running command/exec session or close stdin.
  • command/exec/resize - resize a running PTY-backed command/exec session.
  • command/exec/terminate - stop a running command/exec session.
  • command/exec/outputDelta (notify) - emitted for base64-encoded stdout/stderr chunks from a streaming command/exec session.
  • process/spawn - start an explicit process session outside Codex’s sandbox (experimental; requires capabilities.experimentalApi).
  • process/writeStdin - write stdin bytes to a running process/spawn session or close stdin (experimental).
  • process/resizePty - resize a running PTY-backed process session (experimental).
  • process/kill - terminate a running process session (experimental).
  • process/outputDelta and process/exited (notify) - emitted for streaming process output and process exit status (experimental).
  • model/list - list available models (set includeHidden: true to include entries with hidden: true) with effort options, optional upgrade, and inputModalities.
  • modelProvider/capabilities/read - read provider capability bounds for model/provider combinations.
  • experimentalFeature/list - list feature flags with lifecycle stage metadata and cursor pagination.
  • experimentalFeature/enablement/set - patch in-memory runtime settings for supported feature keys such as apps and plugins.
  • environment/info - experimental; connect to a configured execution environment and return its shell plus default working directory.
  • permissionProfile/list - list beta permission profiles and whether effective requirements allow them, with cursor pagination.
  • collaborationMode/list - list collaboration mode presets (experimental, no pagination).
  • skills/list - list skills for one or more cwd values (supports forceReload and optional perCwdExtraUserRoots).
  • skills/extraRoots/set - replace the process-level extra roots used to discover standalone skills without persisting them.
  • skills/changed (notify) - emitted when watched local skill files change.
  • hooks/list - list discovered lifecycle hooks for one or more cwd values.
  • marketplace/add - add a remote plugin marketplace and persist it into the user’s marketplace config.
  • marketplace/remove - remove a configured marketplace and its installed marketplace root when present.
  • marketplace/upgrade - refresh a configured Git marketplace, or all configured Git marketplaces when you omit the marketplace name.
  • plugin/list - under development; list discovered plugin marketplaces and plugin state, including install/auth policy metadata, marketplace load errors, featured plugin ids, and local, Git, package-registry, or remote plugin source metadata. Summaries can include remote version, local localVersion, structured light/dark icons, and installPolicySource, which can be null, WORKSPACE_SETTING, or IMPLICIT_CANONICAL_APP for current remote rows. Don’t call this method from production clients yet.
  • plugin/read - under development; read one plugin by marketplace path or remote marketplace name and plugin name, including bundled skills, apps, MCP server names, and a remote plugin shareUrl when the remote catalog provides one. Don’t call this method from production clients yet.
  • plugin/install - under development; install a plugin from a marketplace path or remote marketplace name. Don’t call this method from production clients yet.
  • plugin/uninstall - under development; uninstall an installed plugin. Don’t call this method from production clients yet.
  • plugin/skill/read - read remote plugin skill Markdown on demand by remote marketplace, plugin id, and skill name.
  • app/installed - read installed app runtime state, including each app’s effective enabled and callable states.
  • app/list - list available apps (connectors) with pagination plus accessibility/enabled metadata.
  • app/read - fetch metadata and optional display-only tool summaries for specific app ids.
  • skills/config/write - enable or disable skills by path.
  • mcpServer/oauth/login - start an OAuth login for a configured MCP server; returns an authorization URL and emits mcpServer/oauthLogin/completed on completion.
  • tool/requestUserInput - prompt the user with 1-3 short questions for a tool call (experimental); questions can set isOther for a free-form option.
  • mcpServer/elicitation/request (server request) - ask the client for structured form input or confirmation of a URL flow requested by an MCP server.
  • item/permissions/requestApproval (server request) - ask the client to grant a subset of network or filesystem permissions requested by the built-in request_permissions tool.
  • config/mcpServer/reload - reload MCP server configuration from disk and queue a refresh for loaded threads.
  • 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.
  • mcpServer/resource/read - read a single MCP resource through an initialized MCP server.
  • mcpServer/tool/call - call a tool on a thread’s configured MCP server.
  • mcpServer/startupStatus/updated (notify) - emitted when a configured MCP server’s startup status changes for a loaded thread.
  • windowsSandbox/setupStart - start Windows sandbox setup for elevated or unelevated mode; returns quickly and later emits windowsSandbox/setupCompleted.
  • feedback/upload - submit a feedback report (classification + optional reason/logs + conversation id, plus optional extraLogFiles attachments).
  • config/read - fetch the effective configuration on disk after resolving configuration layering.
  • externalAgentConfig/detect - detect external-agent artifacts that can be migrated with includeHome and optional cwds; each detected item includes 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; non-empty imports emit externalAgentConfig/import/progress and externalAgentConfig/import/completed as work finishes. Plugin and session imports can complete asynchronously.
  • config/value/write - write a single configuration key/value to the user’s config.toml on disk.
  • config/batchWrite - apply configuration edits atomically to the user’s config.toml on disk.
  • configRequirements/read - fetch requirements from requirements.toml and/or MDM, including exact managed configuration, allowlists, pinned featureRequirements, and network requirements (or null if you haven’t set any up).
  • 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.

Plugin summaries include a source union. Local plugins return { "type": "local", "path": ... }, Git-backed marketplace entries return { "type": "git", "url": ..., "path": ..., "refName": ..., "sha": ... }, package-registry entries return { "type": "npm", "package": ..., "version": ..., "registry": ... }, and remote catalog entries return { "type": "remote" }. For remote-only catalog entries, PluginMarketplaceEntry.path can be null; pass remoteMarketplaceName instead of marketplacePath when reading or installing those plugins.

Models

List models (model/list)

Call model/list to discover available models and their capabilities before rendering model or personality selectors.

{ "method": "model/list", "id": 6, "params": { "limit": 20, "includeHidden": false } }
{ "id": 6, "result": {
  "data": [{
    "id": "gpt-5.6-sol",
    "model": "gpt-5.6-sol",
    "displayName": "GPT-5.6-Sol",
    "hidden": false,
    "defaultReasoningEffort": "low",
    "supportedReasoningEfforts": [{
      "reasoningEffort": "low",
      "description": "Fast responses with lighter reasoning"
    }],
    "inputModalities": ["text", "image"],
    "supportsPersonality": true,
    "isDefault": true
  }],
  "nextCursor": null
} }

Each model entry can include:

  • supportedReasoningEfforts - supported effort options for the model.
  • defaultReasoningEffort - suggested default effort for clients.
  • upgrade - optional recommended upgrade model id for migration prompts in clients.
  • upgradeInfo - optional upgrade metadata for migration prompts in clients.
  • hidden - whether the model is hidden from the default picker list.
  • inputModalities - supported input types for the model (for example text, image).
  • supportsPersonality - whether the model supports personality-specific instructions such as /personality.
  • isDefault - whether the model is the recommended default.

By default, model/list returns picker-visible models only. Set includeHidden: true if you need the full list and want to filter on the client side using hidden.

When inputModalities is missing (older model catalogs), treat it as ["text", "image"] for backward compatibility.

List experimental features (experimentalFeature/list)

Use this endpoint to discover feature flags with metadata and lifecycle stage:

{ "method": "experimentalFeature/list", "id": 7, "params": { "limit": 20 } }
{ "id": 7, "result": {
  "data": [{
    "name": "unified_exec",
    "stage": "beta",
    "displayName": "Unified exec",
    "description": "Use the unified PTY-backed execution tool.",
    "announcement": "Beta rollout for improved command execution reliability.",
    "enabled": false,
    "defaultEnabled": false
  }],
  "nextCursor": null
} }

stage can be beta, underDevelopment, stable, deprecated, or removed. For non-beta flags, displayName, description, and announcement may be null.

Inspect an execution environment (experimental)

Use environment/info to inspect a configured remote environment before starting work there. The method requires capabilities.experimentalApi = true.

{ "method": "environment/info", "id": 8, "params": { "environmentId": "devbox" } }
{ "id": 8, "result": {
  "shell": { "name": "zsh", "path": "/bin/zsh" },
  "cwd": "file:///workspace/project"
} }

cwd can be null. When present, it’s a canonical file: URI that uses the environment’s native path syntax. Unknown environment IDs and connection or protocol failures return request errors.

Threads

  • thread/read reads a stored thread without subscribing to it; set includeTurns to include turns.
  • thread/turns/list is experimental and pages through a stored thread’s turn history without resuming it. Use itemsView to choose whether turn items are omitted, summarized, or fully loaded.
  • thread/items/list is experimental and pages through persisted thread items, optionally restricted to one turn.
  • thread/list supports cursor pagination plus modelProviders, sourceKinds, archived, isPinned, cwd, useStateDbOnly, searchTerm, and experimental parentThreadId or ancestorThreadId filtering.
  • thread/loaded/list returns the thread IDs currently in memory.
  • thread/archive moves the thread’s persisted JSONL log into the archived directory and attempts to archive spawned descendant thread logs that aren’t already archived.
  • thread/delete permanently deletes a persisted active or archived thread and its spawned descendant threads.
  • thread/metadata/update patches stored thread metadata, including persisted gitInfo and isPinned.
  • thread/unsubscribe unsubscribes the current connection from a loaded thread and can trigger thread/closed after an inactivity grace period.
  • thread/unarchive restores an archived thread rollout back into the active sessions directory.
  • thread/compact/start triggers compaction and returns {} immediately.
  • thread/rollback is deprecated. It drops the last N turns from the in-memory context and records a rollback marker in the thread’s persisted JSONL log.
  • thread/inject_items appends raw Responses API items to a loaded thread’s model-visible history without starting a user turn.

Start or resume a thread

Start a fresh thread when you need a new Codex conversation.

{ "method": "thread/start", "id": 10, "params": {
  "model": "gpt-5.6-terra",
  "cwd": "/Users/me/project",
  "approvalPolicy": "never",
  "sandbox": "workspaceWrite",
  "personality": "friendly",
  "serviceName": "my_app_server_client"
} }
{ "id": 10, "result": {
  "thread": {
    "id": "thr_123",
    "sessionId": "thr_123",
    "preview": "",
    "ephemeral": false,
    "modelProvider": "openai",
    "createdAt": 1730910000
  }
} }
{ "method": "thread/started", "params": { "thread": { "id": "thr_123" } } }

serviceName is optional. Set it when you want app-server to tag thread-level metrics with your integration’s service name.

thread/start, thread/resume, and thread/fork return instructionSources, an array of loaded instruction-file paths. Each path uses its source environment’s native absolute syntax, including for remote environments.

Experimental clients can set historyMode on thread/start to "legacy" (the default) or "paginated". Paginated thread creation isn’t supported yet and returns JSON-RPC error -32601. App-server can list and read summaries for existing paginated records, but full-history reads, turn pagination, and resume fail closed until paginated history is supported.

Beta clients that opt into capabilities.experimentalApi can pass a named permission-profile id in permissions instead of the legacy sandbox field. Don’t send permissions and sandbox together. Use permissionProfile/list with the project cwd to discover available profiles and whether managed requirements allow each one.

thread.sessionId identifies the current live session tree root. Root threads use their own thread id as the session id; forked threads keep the session id of the root they came from. Clients should read the session id from thread.sessionId instead of deriving it from the thread id.

To 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:

{ "method": "thread/resume", "id": 11, "params": {
  "threadId": "thr_123",
  "personality": "friendly"
} }
{ "id": 11, "result": { "thread": { "id": "thr_123", "name": "Bug bash notes", "ephemeral": false } } }

Resuming a thread doesn’t update thread.updatedAt (or the rollout file’s modified time) by itself. The timestamp updates when you start a turn.

If you mark an enabled MCP server as required in config and that server fails to initialize, thread/start and thread/resume fail instead of continuing without it.

dynamicTools on thread/start is an experimental field (requires capabilities.experimentalApi = true). Codex persists these dynamic tools in the thread rollout metadata and restores them on thread/resume when you don’t supply new dynamic tools.

If 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.

Manage a thread goal

Use thread/goal/set, thread/goal/get, and thread/goal/clear to manage the same persisted goal state surfaced by /goal in the TUI.

{ "method": "thread/goal/set", "id": 13, "params": {
  "threadId": "thr_123",
  "objective": "Finish the migration and keep tests green",
  "status": "active",
  "tokenBudget": 40000
} }
{ "id": 13, "result": { "goal": {
  "threadId": "thr_123",
  "objective": "Finish the migration and keep tests green",
  "status": "active",
  "tokenBudget": 40000,
  "tokensUsed": 0,
  "timeUsedSeconds": 0
} } }
{ "method": "thread/goal/updated", "params": {
  "threadId": "thr_123",
  "goal": {
    "threadId": "thr_123",
    "objective": "Finish the migration and keep tests green",
    "status": "active",
    "tokenBudget": 40000,
    "tokensUsed": 0,
    "timeUsedSeconds": 0
  }
} }

Goal objectives must be non-empty and at most 4,000 characters. Supplying a new objective replaces the goal and resets usage accounting. Supplying the current non-terminal objective, or omitting objective, updates status or token budget while preserving usage history.

To 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. Pass lastTurnId to copy history through that turn, inclusive, and omit later turns:

{ "method": "thread/fork", "id": 12, "params": { "threadId": "thr_123", "lastTurnId": "turn_456" } }
{ "id": 12, "result": { "thread": { "id": "thr_456", "sessionId": "thr_123", "forkedFromId": "thr_123" } } }
{ "method": "thread/started", "params": { "thread": { "id": "thr_456" } } }

App-server rejects an in-progress lastTurnId. If you omit the field while the source thread is mid-turn, the fork records an interruption marker instead of retaining an unmarked partial turn.

Pass ephemeral: true to create an in-memory fork without adding it to stored thread listings:

{
  "method": "thread/fork",
  "id": 13,
  "params": {
    "threadId": "thr_123",
    "ephemeral": true
  }
}
{
  "id": 13,
  "result": {
    "thread": {
      "id": "thr_789",
      "sessionId": "thr_789",
      "forkedFromId": "thr_123",
      "ephemeral": true
    }
  }
}

Ephemeral forks of paginated threads also require excludeTurns: true. That field is experimental and requires capabilities.experimentalApi = true.

When a user-facing thread title has been set, app-server hydrates thread.name on thread/list, thread/read, thread/resume, thread/unarchive, and thread/rollback responses. thread/start and thread/fork may omit name (or return null) until a title is set later.

Read a stored thread (without resuming)

Use thread/read when you want stored thread data but don’t want to resume the thread or subscribe to its events.

  • includeTurns - when true, the response includes the thread’s turns; when false or omitted, you get the thread summary only.
  • Returned thread objects include runtime status (notLoaded, idle, systemError, or active with activeFlags).
{ "method": "thread/read", "id": 19, "params": { "threadId": "thr_123", "includeTurns": true } }
{ "id": 19, "result": { "thread": { "id": "thr_123", "name": "Bug bash notes", "ephemeral": false, "status": { "type": "notLoaded" }, "turns": [] } } }

Unlike thread/resume, thread/read doesn’t load the thread into memory or emit thread/started.

List thread turns

thread/turns/list is experimental. Use it 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.

itemsView controls how much turn-item data the response includes:

  • notLoaded omits items.
  • summary returns summarized item data and is the default when omitted.
  • full returns full item data.
{ "method": "thread/turns/list", "id": 20, "params": {
  "threadId": "thr_123",
  "limit": 50,
  "sortDirection": "desc",
  "itemsView": "summary"
} }
{ "id": 20, "result": {
  "data": [],
  "nextCursor": "older-turns-cursor-or-null",
  "backwardsCursor": "newer-turns-cursor-or-null"
} }

thread/items/list is also experimental. It pages persisted items without resuming the thread. Pass turnId to restrict results to one turn, or omit it to page items across the thread. The active thread store must support item pagination; otherwise, the server returns an unsupported-method error.

List threads (with pagination & filters)

thread/list lets you render a history UI. Results default to newest-first by createdAt. Filters apply before pagination. Pass any combination of:

  • cursor - opaque string from a prior response; omit for the first page.
  • limit - server defaults to a reasonable page size if unset.
  • sortKey - created_at (default), updated_at, or recency_at.
  • sortDirection - desc (default) or asc.
  • modelProviders - restrict results to specific providers; unset, null, or an empty array includes all providers.
  • sourceKinds - restrict results to specific thread sources. When omitted or [], the server defaults to interactive sources only: cli and vscode.
  • archived - when true, list archived threads only. When false or omitted, list non-archived threads (default).
  • isPinned - when provided, return only threads with the matching persisted pin state. Omit it to return pinned and unpinned threads.
  • cwd - restrict results to threads whose session current working directory exactly matches this path, or one of the paths in an array. Relative paths resolve from the app-server process working directory.
  • useStateDbOnly - when true, return state database results without scanning JSONL thread logs to repair metadata. Omit it or pass false for the default scan-and-repair behavior.
  • searchTerm - restrict results to threads whose extracted title contains this case-sensitive text fragment.
  • parentThreadId - restrict results to direct child threads of the given parent thread. This filter is experimental and requires capabilities.experimentalApi = true.
  • ancestorThreadId - restrict results to spawned descendants of the given thread at any depth. This filter is experimental and requires capabilities.experimentalApi = true; don’t combine it with parentThreadId.

sourceKinds accepts the following values:

  • cli
  • vscode
  • exec
  • appServer
  • subAgent
  • subAgentReview
  • subAgentCompact
  • subAgentThreadSpawn
  • subAgentOther
  • unknown

Example:

{ "method": "thread/list", "id": 20, "params": {
  "cursor": null,
  "limit": 25,
  "sortKey": "created_at"
} }
{ "id": 20, "result": {
  "data": [
    { "id": "thr_a", "preview": "Create a TUI", "ephemeral": false, "isPinned": true, "modelProvider": "openai", "createdAt": 1730831111, "updatedAt": 1730831111, "name": "TUI prototype", "status": { "type": "notLoaded" } },
    { "id": "thr_b", "preview": "Fix tests", "ephemeral": false, "isPinned": false, "modelProvider": "openai", "createdAt": 1730750000, "updatedAt": 1730750000, "status": { "type": "notLoaded" } }
  ],
  "nextCursor": "opaque-token-or-null"
} }

When nextCursor is null, you have reached the final page.

Update stored thread metadata

Use thread/metadata/update to patch stored thread metadata without resuming the thread. Set isPinned to pin or unpin the thread, or update gitInfo to change persisted Git metadata. Omitted fields stay unchanged; explicit null clears a stored Git metadata value.

{ "method": "thread/metadata/update", "id": 21, "params": {
  "threadId": "thr_123",
  "isPinned": true,
  "gitInfo": { "branch": "feature/sidebar-pr" }
} }
{ "id": 21, "result": {
  "thread": {
    "id": "thr_123",
    "isPinned": true,
    "gitInfo": { "sha": null, "branch": "feature/sidebar-pr", "originUrl": null }
  }
} }

Track thread status changes

thread/status/changed is emitted whenever a loaded thread’s runtime status changes. The payload includes threadId and the new status.

{
  "method": "thread/status/changed",
  "params": {
    "threadId": "thr_123",
    "status": { "type": "active", "activeFlags": ["waitingOnApproval"] }
  }
}

List loaded threads

thread/loaded/list returns thread IDs currently loaded in memory.

{ "method": "thread/loaded/list", "id": 21 }
{ "id": 21, "result": { "data": ["thr_123", "thr_456"] } }

Unsubscribe from a loaded thread

thread/unsubscribe removes the current connection’s subscription to a thread. The response status is one of:

  • unsubscribed when the connection was subscribed and is now removed.
  • notSubscribed when the connection wasn’t subscribed to that thread.
  • notLoaded when the thread isn’t loaded.

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.

{ "method": "thread/unsubscribe", "id": 22, "params": { "threadId": "thr_123" } }
{ "id": 22, "result": { "status": "unsubscribed" } }

If the thread later expires:

{ "method": "thread/status/changed", "params": {
    "threadId": "thr_123",
    "status": { "type": "notLoaded" }
} }
{ "method": "thread/closed", "params": { "threadId": "thr_123" } }

Archive a thread

Use thread/archive to move the persisted thread log (stored as a JSONL file on disk) into the archived sessions directory. Archiving a thread also attempts to archive spawned descendant threads that aren’t already archived.

{ "method": "thread/archive", "id": 22, "params": { "threadId": "thr_b" } }
{ "id": 22, "result": {} }
{ "method": "thread/archived", "params": { "threadId": "thr_b" } }
{ "method": "thread/archived", "params": { "threadId": "thr_child" } }

Archived threads won’t appear in future calls to thread/list unless you pass archived: true. The server emits one thread/archived notification for each thread it actually archives; if a spawned descendant can’t be archived, the request can still succeed without an archived notification for that descendant.

Delete a thread

Use thread/delete to permanently delete a persisted active or archived thread and its spawned descendant threads. The server removes existing rollout files and associated metadata before returning success; missing rollout files are treated as already deleted. Ephemeral root threads can’t be deleted.

{ "method": "thread/delete", "id": 23, "params": { "threadId": "thr_b" } }
{ "id": 23, "result": {} }
{ "method": "thread/deleted", "params": { "threadId": "thr_b" } }
{ "method": "thread/deleted", "params": { "threadId": "thr_child" } }

Unarchive a thread

Use thread/unarchive to move an archived thread rollout back into the active sessions directory.

{ "method": "thread/unarchive", "id": 24, "params": { "threadId": "thr_b" } }
{ "id": 24, "result": { "thread": { "id": "thr_b", "name": "Bug bash notes" } } }
{ "method": "thread/unarchived", "params": { "threadId": "thr_b" } }

Trigger thread compaction

Use thread/compact/start to trigger manual history compaction for a thread. The request returns immediately with {}.

App-server emits progress as standard turn/* and item/* notifications on the same threadId, including a contextCompaction item lifecycle (item/started then item/completed).

{ "method": "thread/compact/start", "id": 25, "params": { "threadId": "thr_b" } }
{ "id": 25, "result": {} }

Run a thread shell command

Use 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.

This 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.

If 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.

{ "method": "thread/shellCommand", "id": 26, "params": { "threadId": "thr_b", "command": "git status --short" } }
{ "id": 26, "result": {} }

Clean background terminals

Use thread/backgroundTerminals/clean to stop all running background terminals associated with a thread. This method is experimental and requires capabilities.experimentalApi = true.

{ "method": "thread/backgroundTerminals/clean", "id": 27, "params": { "threadId": "thr_b" } }
{ "id": 27, "result": {} }

Use thread/backgroundTerminals/list to inspect running background terminals for a loaded thread. The request supports standard cursor and limit pagination, and the returned processId is the app-server process id. This method is experimental and requires capabilities.experimentalApi = true:

{ "method": "thread/backgroundTerminals/list", "id": 28, "params": { "threadId": "thr_b" } }
{ "id": 28, "result": { "data": [
  {
    "itemId": "item_456",
    "processId": "42",
    "command": "python3 -m http.server",
    "cwd": "/workspace",
    "osPid": null,
    "cpuPercent": null,
    "rssKb": null
  }
], "nextCursor": null } }

Use thread/backgroundTerminals/terminate with that processId to stop one background terminal. This method is experimental and requires capabilities.experimentalApi = true:

{ "method": "thread/backgroundTerminals/terminate", "id": 29, "params": { "threadId": "thr_b", "processId": "42" } }
{ "id": 29, "result": { "terminated": true } }

Roll back recent turns

thread/rollback is deprecated and will be removed. It removes the last numTurns entries from the in-memory context and persists a rollback marker in the rollout log. The returned thread includes turns populated after the rollback.

{ "method": "thread/rollback", "id": 30, "params": { "threadId": "thr_b", "numTurns": 1 } }
{ "id": 30, "result": { "thread": { "id": "thr_b", "name": "Bug bash notes", "ephemeral": false } } }

Turns

The input field accepts a list of items:

  • { "type": "text", "text": "Explain this diff" }
  • { "type": "image", "url": "https://.../design.png" }
  • { "type": "localImage", "path": "/tmp/screenshot.png" }

You can override configuration settings per turn (model, effort, personality, cwd, sandbox policy, summary). When specified, these settings become the defaults for later turns on the same thread. outputSchema applies only to the current turn. For sandboxPolicy.type = "externalSandbox", set networkAccess to restricted or enabled; for workspaceWrite, networkAccess remains a boolean.

For turn/start.collaborationMode, settings.developer_instructions: null means “use built-in instructions for the selected mode” rather than clearing mode instructions.

Sandbox read access (ReadOnlyAccess)

sandboxPolicy supports explicit read-access controls:

  • readOnly: optional access ({ "type": "fullAccess" } by default, or restricted roots).
  • workspaceWrite: optional readOnlyAccess ({ "type": "fullAccess" } by default, or restricted roots).

Restricted read access shape:

{
  "type": "restricted",
  "includePlatformDefaults": true,
  "readableRoots": ["/Users/me/shared-read-only"]
}

On macOS, includePlatformDefaults: true appends a curated platform-default Seatbelt policy for restricted-read sessions. This improves tool compatibility without broadly allowing all of /System.

Examples:

{ "type": "readOnly", "access": { "type": "fullAccess" } }
{
  "type": "workspaceWrite",
  "writableRoots": ["/Users/me/project"],
  "readOnlyAccess": {
    "type": "restricted",
    "includePlatformDefaults": true,
    "readableRoots": ["/Users/me/shared-read-only"]
  },
  "networkAccess": false
}

Start a turn

{ "method": "turn/start", "id": 30, "params": {
  "threadId": "thr_123",
  "input": [ { "type": "text", "text": "Run tests" } ],
  "cwd": "/Users/me/project",
  "approvalPolicy": "unlessTrusted",
  "sandboxPolicy": {
    "type": "workspaceWrite",
    "writableRoots": ["/Users/me/project"],
    "networkAccess": true
  },
  "model": "gpt-5.6-terra",
  "effort": "medium",
  "summary": "concise",
  "personality": "friendly",
  "outputSchema": {
    "type": "object",
    "properties": { "answer": { "type": "string" } },
    "required": ["answer"],
    "additionalProperties": false
  }
} }
{ "id": 30, "result": { "turn": { "id": "turn_456", "status": "inProgress", "items": [], "error": null } } }

Inject items into a thread

Use 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.

{ "method": "thread/inject_items", "id": 31, "params": {
  "threadId": "thr_123",
  "items": [
    {
      "type": "message",
      "role": "assistant",
      "content": [{ "type": "output_text", "text": "Previously computed context." }]
    }
  ]
} }
{ "id": 31, "result": {} }

Steer an active turn

Use turn/steer to append more user input to the active in-flight turn.

  • Include expectedTurnId; it must match the active turn id.
  • The request fails if there is no active turn on the thread.
  • turn/steer doesn’t emit a new turn/started notification.
  • turn/steer doesn’t accept turn-level overrides (model, cwd, sandboxPolicy, or outputSchema).
{ "method": "turn/steer", "id": 32, "params": {
  "threadId": "thr_123",
  "input": [ { "type": "text", "text": "Actually focus on failing tests first." } ],
  "expectedTurnId": "turn_456"
} }
{ "id": 32, "result": { "turnId": "turn_456" } }

Start a turn (invoke a skill)

Invoke a skill explicitly by including $<skill-name> in the text input and adding a skill input item alongside it.

{ "method": "turn/start", "id": 33, "params": {
  "threadId": "thr_123",
  "input": [
    { "type": "text", "text": "$skill-creator Add a new skill for triaging flaky CI and include step-by-step usage." },
    { "type": "skill", "name": "skill-creator", "path": "/Users/me/.codex/skills/skill-creator/SKILL.md" }
  ]
} }
{ "id": 33, "result": { "turn": { "id": "turn_457", "status": "inProgress", "items": [], "error": null } } }

Interrupt a turn

{ "method": "turn/interrupt", "id": 31, "params": { "threadId": "thr_123", "turnId"