Codex app-server 是 Codex 用来支撑 rich clients(例如 Codex VS Code extension)的接口。当你希望在自己的产品中做深度集成时使用它:authentication、conversation history、approvals,以及 streamed agent events。app-server implementation 在 Codex GitHub repository ( openai/codex/codex-rs/app-server ) 中开源。完整的 open-source Codex components 列表请参见 Open Source 页面。
如果你是在自动化 jobs 或在 CI 中运行 Codex,请改用 Codex SDK 。
协议
与 MCP 类似,codex app-server 使用 JSON-RPC 2.0 messages 支持双向通信(wire 上会省略 "jsonrpc":"2.0" header)。
支持的 transports:
stdio (--listen stdio://, default):newline-delimited JSON (JSONL).
websocket (--listen ws://IP:PORT, experimental 和 unsupported):one JSON-RPC message per WebSocket text frame.
Unix socket (--listen unix:// 或 --listen unix://PATH):WebSocket connections over Codex’s default app-server control socket 或 a custom Unix socket path, using the standard HTTP Upgrade handshake.
off (--listen off):don’t expose a local transport.
当使用 --listen ws://IP:PORT 运行时,同一个 listener 也提供基本 HTTP health probes:
GET /readyz 返回 200 OK once the listener accepts new connections.
GET /healthz 返回 200 OK 当 the request doesn’t 包含 an Origin header.
Requests 使用 an Origin header are rejected 使用 403 Forbidden.
WebSocket transport 是 experimental 且 unsupported。ws://127.0.0.1:PORT 这样的 local listeners 适用于 localhost 和 SSH port-forwarding workflows。rollout 期间,non-loopback WebSocket listeners 当前默认允许 unauthenticated connections,因此在远程暴露之前请先配置 WebSocket auth。
支持的 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
对于 signed bearer tokens,你还可以设置 --ws-issuer、--ws-audience 和 --ws-max-clock-skew-seconds。clients 在 WebSocket handshake 期间以 Authorization: Bearer <token> 提交 credential,app-server 会在 JSON-RPC initialize 之前强制执行 auth。
优先使用 --ws-token-file,不要在 command line 上传递 raw bearer tokens。只有当 client 把 raw high-entropy token 保存在独立 local secret store 中时,才使用 --ws-token-sha256;hash 只是 verifier,clients 仍然需要原始 token。
在 WebSocket mode 下,app-server 使用 bounded queues。当 request ingress 已满时,server 会用 JSON-RPC error code -32001 和 message "Server overloaded; retry later." 拒绝新 requests。clients 应使用指数递增 delay 和 jitter 重试。
消息 schema
Requests 包含 method、params 和 id:
{ "method": "thread/start", "id": 10, "params": { "model": "gpt-5.4" } } Responses 会回显 id,并包含 result 或 error:
{ "id": 10, "result": { "thread": { "id": "thr_123" } } } { "id": 10, "error": { "code": 123, "message": "Something went wrong" } } Notifications 省略 id,只使用 method 和 params:
{ "method": "turn/started", "params": { "turn": { "id": "turn_456" } } } 你可以从 CLI 生成 TypeScript schema 或 JSON Schema bundle。每个输出都对应你运行的 Codex version,因此生成的 artifacts 会与该 version 精确匹配:
codex app-server generate-ts --out ./schemas codex app-server generate-json-schema --out ./schemas 开始使用
Start the server 使用 codex app-server (default stdio transport), codex app-server --listen ws://127.0.0.1:4500 (TCP WebSocket), 或 codex app-server --listen unix:// (default Unix socket).
Connect a client over 所选 transport, then send initialize followed by the initialized notification.
Start a thread 和 a turn, then keep reading notifications 从 the active transport stream.
示例(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.4" } }); 核心 primitives
Thread:A conversation between a user 和 the Codex agent。Threads contain turns.
Turn:A single user request 和 the agent work that follows。Turns contain items 和 stream incremental 更新.
Item:A unit of input 或 output (user message, agent message, command runs, file change, tool 调用, 和 more).
使用 thread APIs 创建、列出或归档 conversations。使用 turn APIs 驱动 conversation,并通过 turn notifications stream progress。
生命周期概览
Initialize once per connection:Immediately 之后 opening a transport connection, send an initialize request 使用 your client metadata, then emit initialized。The server rejects any request on that connection 之前 this handshake.
Start (or resume) a thread:调用 thread/启动 for 新的 conversation, thread/resume to continue 已有的 one, 或 thread/fork to branch history 到 新的 thread id.
Begin a turn:调用 turn/启动 使用 the target threadId 和 user input。Optional fields override model, personality, cwd, sandbox policy, 和 more.
Steer an active turn:调用 turn/steer to append user input to the currently in-flight turn 不使用 creating 新的 turn.
Stream events:After turn/启动, keep reading notifications on stdout:thread/archived, thread/unarchived, item/started, item/completed, item/agentMessage/delta, tool progress, 和 other 更新.
Finish the turn:The server 发出 turn/completed 使用 final status 当 the model finishes 或 之后 a turn/interrupt cancellation.
初始化
Clients must send a single initialize request per transport connection 之前 invoking any other method on that connection, then acknowledge 使用 an initialized notification。Requests sent 之前 initialization receive a Not initialized error, 和 repeated initialize calls on 相同 connection 返回 Already initialized.
The server 返回 the user agent string it will present to upstream services 以及 platformFamily 和 platformOs values that describe the runtime target。设置 clientInfo to identify your integration.
initialize.params.capabilities also 支持 per-connection notification opt-out 通过 optOutNotificationMethods, which is a 列出 of exact method names to suppress for that connection。Matching is exact (no wildcards/prefixes)。Unknown method names are accepted 和 ignored.
Important:使用 clientInfo.name to identify your client for the OpenAI Compliance Logs Platform。如果 you are developing 新的 Codex integration intended for enterprise 使用, please contact OpenAI to get it added to a known clients 列出。For more context, see the Codex logs reference .
Example (从 the Codex VS Code extension):
{ "method": "initialize", "id": 0, "params": { "clientInfo": { "name": "codex_vscode", "title": "Codex VS Code Extension", "version": "0.1.0" } } } Example 使用 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
部分 app-server methods 和 fields 有意放在 experimentalApi capability 之后。
省略 capabilities (或 设置 experimentalApi to false) to stay on the stable API surface, 和 the server rejects experimental methods/fields.
设置 capabilities.experimentalApi to true to enable experimental methods 和 fields.
{ "method": "initialize", "id": 1, "params": { "clientInfo": { "name": "my_client", "title": "My Client", "version": "0.1.0" }, "capabilities": { "experimentalApi": true } } } 如果 client 未 opt in 就发送 experimental method 或 field,app-server 会以下列内容拒绝:
<descriptor> requires experimentalApi capability
API 概览
thread/start - 创建 新的 thread;发出 thread/started 和 自动 subscribes you to turn/item events for that thread.
thread/resume - reopen 已有的 thread by id so later turn/启动 calls append to it.
thread/fork - fork a thread 到 新的 thread id by copying stored history;发出 thread/started for the new thread。Returned threads 包含 forkedFromId 当 available.
thread/read - 读取 a stored thread by id 不使用 resuming it;设置 includeTurns to 返回 full turn history。Returned thread objects 包含 runtime status.
thread/list - 分页读取 stored thread logs;支持 cursor-based pagination 以及 modelProviders, sourceKinds, archived, cwd, searchTerm, 和 experimental parentThreadId filters。Returned thread objects 包含 runtime status.
thread/turns/list - 分页读取 a stored thread’s turn history 不使用 resuming it。itemsView controls whether turn items are omitted, summarized, 或 fully loaded.
thread/turns/items/list - reserved for paged turn-item loading;currently 返回 unsupported.
thread/loaded/list - 列出 the thread ids currently loaded in memory.
thread/name/set - 设置 或 更新 a thread’s user-facing name for a loaded thread 或 a persisted rollout;发出 thread/name/updated.
thread/goal/set - 设置 the goal for a thread;发出 thread/goal/updated.
thread/goal/get - 读取 当前 goal for a thread.
thread/goal/clear - clear the goal for a thread;发出 thread/goal/cleared.
thread/metadata/update - patch SQLite-backed stored thread metadata;currently 支持 persisted gitInfo.
thread/archive - move a thread’s log file 到 the archived directory 和 attempt to 归档 spawned descendant thread logs that aren’t already archived;返回 {} on success 和 发出 thread/archived for each archived thread.
thread/delete - permanently 删除 a persisted active 或 archived thread 和 any spawned descendant threads;返回 {} on success 和 发出 thread/deleted for each deleted thread.
thread/unsubscribe - unsubscribe this connection 从 thread turn/item events。如果 this was the last subscriber, the server unloads the thread 之后 a no-subscriber inactivity grace period 和 发出 thread/closed.
thread/unarchive - 恢复 an archived thread rollout back 到 the active sessions directory;返回 the restored thread 和 发出 thread/unarchived.
thread/status/changed - notification 发出 当 a loaded thread’s runtime status changes.
thread/compact/start - trigger conversation history compaction for a thread;返回 {} 立即 while progress streams 通过 turn/* 和 item/* notifications.
thread/shellCommand - run a user-initiated shell command against a thread。This runs outside the sandbox 使用 full access 和 doesn’t inherit the thread sandbox policy.
thread/backgroundTerminals/clean - 停止 all running background terminals for a thread (experimental;需要 capabilities.experimentalApi).
thread/backgroundTerminals/list - 列出 running background terminals for a loaded thread (experimental;需要 capabilities.experimentalApi).
thread/backgroundTerminals/terminate - terminate one running background terminal by app-server processId (experimental;需要 capabilities.experimentalApi).
thread/rollback - drop the last N turns 从 the in-memory context 和 persist a rollback marker;返回 the updated thread.
turn/start - add user input to a thread 和 begin Codex generation;responds 使用 the initial turn 和 streams events。For collaborationMode, settings.developer_instructions:null means “使用 built-in instructions for 所选 mode.”
thread/inject_items - append raw Responses API items to a loaded thread’s model-visible history 不使用 starting a user turn.
turn/steer - append user input to the active in-flight turn for a thread;返回 the accepted turnId.
turn/interrupt - request cancellation of an in-flight turn;success is {} 和 the turn ends 使用 status:"interrupted".
review/start - kick off the Codex reviewer for a thread;发出 enteredReviewMode 和 exitedReviewMode items.
command/exec - run a single command under the server sandbox 不使用 starting a thread/turn.
command/exec/write - 写入 stdin bytes to a running command/exec session 或 close stdin.
command/exec/resize - resize a running PTY-backed command/exec session.
command/exec/terminate - 停止 a running command/exec session.
command/exec/outputDelta (notify) - 发出 for base64-encoded stdout/stderr chunks 从 a streaming command/exec session.
process/spawn - 启动 an explicit process session outside Codex’s sandbox (experimental;需要 capabilities.experimentalApi).
process/writeStdin - 写入 stdin bytes to a running process/spawn session 或 close stdin (experimental).
process/resizePty - resize a running PTY-backed process session (experimental).
process/kill - terminate a running process session (experimental).
process/outputDelta 和 process/exited (notify) - 发出 for streaming process output 和 process exit status (experimental).
model/list - 列出 available models (设置 includeHidden:true to 包含 entries 使用 hidden:true) 使用 effort options, optional upgrade, 和 inputModalities.
modelProvider/capabilities/read - 读取 provider capability bounds for model/provider combinations (experimental;需要 capabilities.experimentalApi).
experimentalFeature/list - 列出 feature flags 使用 lifecycle stage metadata 和 cursor pagination.
experimentalFeature/enablement/set - patch in-memory runtime settings for 支持的 feature keys such as apps 和 plugins.
collaborationMode/list - 列出 collaboration mode presets (experimental, no pagination).
skills/list - 列出 skills for one 或 more cwd values (支持 forceReload 和 optional perCwdExtraUserRoots).
skills/changed (notify) - 发出 当 watched local skill files change.
marketplace/add - add a remote plugin marketplace 和 persist it 到 the user’s marketplace config.
marketplace/upgrade - refresh a configured Git marketplace, 或 all configured Git marketplaces 当 you 省略 the marketplace name.
plugin/list - 列出 discovered plugin marketplaces 和 plugin state, including install/auth policy metadata, marketplace load errors, featured plugin ids, 和 local, Git, 或 remote plugin source metadata.
plugin/read - 读取 one plugin by marketplace path 或 remote marketplace name 和 plugin name, including bundled skills, apps, MCP server names, 和 a remote plugin shareUrl 当 the remote catalog provides one.
plugin/install - install a plugin 从 a marketplace path 或 remote marketplace name.
plugin/uninstall - uninstall an installed plugin.
app/list - 列出 available apps (connectors) 使用 pagination 以及 accessibility/enabled metadata.
skills/config/write - enable 或 disable skills by path.
mcpServer/oauth/login - 启动 an OAuth login for a configured MCP server;返回 an authorization URL 和 发出 mcpServer/oauthLogin/completed on completion.
tool/requestUserInput - prompt the user 使用 1-3 short questions for a tool 调用 (experimental);questions can 设置 isOther for a free-form option.
config/mcpServer/reload - reload MCP server configuration 从 disk 和 queue a refresh for loaded threads.
mcpServerStatus/list - 列出 MCP servers, tools, resources, 和 auth status (cursor + limit pagination)。使用 detail:"full" for full data 或 detail:"toolsAndAuthOnly" to 省略 resources.
mcpServer/resource/read - 读取 a single MCP resource through an initialized MCP server.
mcpServer/tool/call - 调用 a tool on a thread’s configured MCP server.
mcpServer/startupStatus/updated (notify) - 发出 当 a configured MCP server’s startup status changes for a loaded thread.
windowsSandbox/setupStart - 启动 Windows sandbox setup for elevated 或 unelevated mode;返回 quickly 和 later 发出 windowsSandbox/setupCompleted.
feedback/upload - submit a feedback report (classification + optional reason/logs + conversation id, 以及 optional extraLogFiles attachments).
config/read - 获取 the effective configuration on disk 之后 resolving configuration layering.
externalAgentConfig/detect - detect external-agent artifacts that can be migrated 使用 includeHome 和 optional cwds;each detected item includes cwd (null for home).
externalAgentConfig/import - apply selected external-agent migration items by passing explicit migrationItems 使用 cwd (null for home)。Supported item types 包含 config, skills, AGENTS.md, plugins, MCP server config, subagents, hooks, commands, 和 sessions;non-empty imports emit externalAgentConfig/import/progress 和 externalAgentConfig/import/completed as work finishes。Plugin 和 session imports can complete asynchronously.
config/value/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 - 获取 requirements 从 requirements.toml 和/或 MDM, including allow-列出, pinned featureRequirements, 和 residency/network requirements (或 null 如果 you haven’t 设置 any up).
fs/readFile, fs/writeFile, fs/createDirectory, fs/getMetadata, fs/readDirectory, fs/remove, fs/copy, fs/watch, fs/unwatch, 和 fs/changed (notify) - operate on absolute filesystem paths through the app-server v2 filesystem API.
Plugin summaries 包含 source union。Local plugins 返回 { "type": "local", "path": ... },Git-backed marketplace entries 返回 { "type": "git", "url": ..., "path": ..., "refName": ..., "sha": ... },remote catalog entries 返回 { "type": "remote" }。对于 remote-only catalog entries,PluginMarketplaceEntry.path 可以为 null;读取或安装这些 plugins 时,请传入 remoteMarketplaceName,而不是 marketplacePath。
Models
列出 models (model/list)
调用 model/列出 to discover available models 和 their capabilities 之前 rendering model 或 personality selectors.
{ "method": "model/list", "id": 6, "params": { "limit": 20, "includeHidden": false } } { "id": 6, "result": { "data": [{ "id": "gpt-5.4", "model": "gpt-5.4", "displayName": "GPT-5.4", "hidden": false, "defaultReasoningEffort": "medium", "supportedReasoningEfforts": [{ "reasoningEffort": "low", "description": "Lower latency" }], "inputModalities": ["text", "image"], "supportsPersonality": true, "isDefault": true }], "nextCursor": null } } Each model entry can 包含:
supportedReasoningEfforts - 支持的 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 从 the default picker 列出.
inputModalities - 支持的 input types for the model (例如 text, image).
supportsPersonality - whether the model 支持 personality-specific instructions such as /personality.
isDefault - whether the model is the recommended default.
By default, model/列出 返回 picker-visible models only。设置 includeHidden:true 如果 you need 完整 列出 和 want to filter on the client side using hidden.
When inputModalities is missing (older model catalogs), treat it as ["text", "image"] for backward compatibility.
列出 experimental features (experimentalFeature/list)
使用 this endpoint to discover feature flags 使用 metadata 和 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, 或 removed。For non-beta flags, displayName, description, 和 announcement may be null.
Threads
thread/读取 读取 a stored thread 不使用 subscribing to it;设置 includeTurns to 包含 turns.
thread/turns/列出 pages through a stored thread’s turn history 不使用 resuming it。使用 itemsView to choose whether turn items are omitted, summarized, 或 fully loaded.
thread/列出 支持 cursor pagination 以及 modelProviders, sourceKinds, archived, cwd, searchTerm, 和 experimental parentThreadId filtering.
thread/loaded/列出 返回 the thread IDs currently in memory.
thread/归档 moves the thread’s persisted JSONL log 到 the archived directory 和 attempts to 归档 spawned descendant thread logs that aren’t already archived.
thread/删除 permanently 删除 a persisted active 或 archived thread 和 its spawned descendant threads.
thread/metadata/更新 patches stored thread metadata, currently including persisted gitInfo.
thread/unsubscribe unsubscribes 当前 connection 从 a loaded thread 和 can trigger thread/closed 之后 an inactivity grace period.
thread/取消归档 恢复 an archived thread rollout back 到 the active sessions directory.
thread/compact/启动 triggers compaction 和 返回 {} 立即.
thread/rollback drops the last N turns 从 the in-memory context 和 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 不使用 starting a user turn.
启动或恢复 thread
Start a fresh thread 当 you need 新的 Codex conversation.
{ "method": "thread/start", "id": 10, "params": { "model": "gpt-5.4", "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。设置 it 当 you want app-server to tag thread-level metrics 使用 your integration’s service name.
thread.sessionId identifies 当前 live session tree root。Root threads 使用 their own thread id as the session id;forked threads keep the session id of the root they came 从。Clients should 读取 the session id 从 thread.sessionId 而不是 deriving it 从 the thread id.
To continue a stored session, 调用 thread/resume 使用 the thread.id you recorded earlier。The response shape matches thread/启动。你可以 also pass 相同 configuration overrides 支持的 by thread/启动, 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 更新 thread.updatedAt (或 the rollout file’s modified time) by itself。The timestamp 更新 当 you 启动 a turn.
如果 you mark an enabled MCP server as required in config 和 that server fails to initialize, thread/启动 和 thread/resume fail 而不是 continuing 不使用 it.
dynamicTools on thread/启动 is an experimental field (需要 capabilities.experimentalApi = true)。Codex persists these dynamic tools in the thread rollout metadata 和 恢复 them on thread/resume 当 you don’t supply new dynamic tools.
如果 you resume 使用 a different model than the one recorded in the rollout, Codex 发出 a warning 和 applies a one-time model-switch instruction on the next turn.
管理 thread goal
使用 thread/goal/设置, thread/goal/get, 和 thread/goal/clear to manage 相同 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 和 at most 4,000 characters。Supplying 新的 objective replaces the goal 和 resets usage accounting。Supplying 当前 non-terminal objective, 或 omitting objective, 更新 status 或 token budget while preserving usage history.
To branch 从 a stored session, 调用 thread/fork 使用 the thread.id。This 创建 新的 thread id 和 发出 a thread/started notification for it:
{ "method": "thread/fork", "id": 12, "params": { "threadId": "thr_123" } } { "id": 12, "result": { "thread": { "id": "thr_456", "sessionId": "thr_123", "forkedFromId": "thr_123" } } } { "method": "thread/started", "params": { "thread": { "id": "thr_456" } } } When a user-facing thread title has been 设置, app-server hydrates thread.name on thread/列出, thread/读取, thread/resume, thread/取消归档, 和 thread/rollback responses。thread/启动 和 thread/fork may 省略 name (或 返回 null) until a title is 设置 later.
读取 stored thread(不恢复)
使用 thread/读取 当 you want stored thread data but don’t want to resume the thread 或 subscribe to its events.
includeTurns - 当 true, the response includes the thread’s turns;当 false 或 omitted, you get the thread summary only.
Returned thread objects 包含 runtime status (notLoaded, idle, systemError, 或 active 使用 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/读取 doesn’t load the thread 到 memory 或 emit thread/started.
列出 thread turns
使用 thread/turns/列出 to page a stored thread’s turn history 不使用 resuming it。Results default to newest-first so clients can 获取 older turns 使用 nextCursor。The response also includes backwardsCursor;pass it as cursor 使用 sortDirection:"asc" to 获取 turns newer than the first item 从 the earlier page.
itemsView controls how much turn-item data the response includes:
notLoaded omits items.
summary 返回 summarized item data 和 is the default 当 omitted.
full 返回 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/turns/items/列出 is reserved for paged turn-item loading, but 当前 server 返回 an unsupported-method error.
列出 threads(分页和 filters)
thread/列出 lets you render a history UI。Results default to newest-first by createdAt。Filters apply 之前 pagination。Pass any combination of:
cursor - opaque string 从 a prior response;省略 for the first page.
limit - server defaults to a reasonable page size 如果 unset.
sortKey - created_at (default), updated_at, 或 recency_at.
sortDirection - desc (default) 或 asc.
modelProviders - restrict results to specific providers;unset, null, 或 an empty array includes all providers.
sourceKinds - restrict results to specific thread sources。When omitted 或 [], the server defaults to interactive sources only:cli 和 vscode.
archived - 当 true, 列出 archived threads only。When false 或 omitted, 列出 non-archived threads (default).
cwd - restrict results to threads whose session current working directory exactly matches this path.
searchTerm - search stored thread summaries 和 metadata 之前 pagination.
parentThreadId - restrict results to direct child threads of the given parent thread。This filter is experimental 和 需要 capabilities.experimentalApi = true.
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, "modelProvider": "openai", "createdAt": 1730831111, "updatedAt": 1730831111, "name": "TUI prototype", "status": { "type": "notLoaded" } }, { "id": "thr_b", "preview": "Fix tests", "ephemeral": true, "modelProvider": "openai", "createdAt": 1730750000, "updatedAt": 1730750000, "status": { "type": "notLoaded" } } ], "nextCursor": "opaque-token-or-null" } } When nextCursor is null, you have reached the final page.
更新 stored thread metadata
使用 thread/metadata/更新 to patch stored thread metadata 不使用 resuming the thread。Today this 支持 persisted gitInfo;omitted fields are left unchanged, 和 explicit null clears a stored value.
{ "method": "thread/metadata/update", "id": 21, "params": { "threadId": "thr_123", "gitInfo": { "branch": "feature/sidebar-pr" } } } { "id": 21, "result": { "thread": { "id": "thr_123", "gitInfo": { "sha": null, "branch": "feature/sidebar-pr", "originUrl": null } } } } 跟踪 thread status changes
thread/status/changed is 发出 whenever a loaded thread’s runtime status changes。The payload includes threadId 和 the new status.
{ "method": "thread/status/changed", "params": { "threadId": "thr_123", "status": { "type": "active", "activeFlags": ["waitingOnApproval"] } } } 列出 loaded threads
thread/loaded/列出 返回 thread IDs currently loaded in memory.
{ "method": "thread/loaded/list", "id": 21 } { "id": 21, "result": { "data": ["thr_123", "thr_456"] } } 取消订阅 loaded thread
thread/unsubscribe removes 当前 connection’s subscription to a thread。The response status is one of:
unsubscribed 当 the connection was subscribed 和 is now removed.
notSubscribed 当 the connection wasn’t subscribed to that thread.
notLoaded 当 the thread isn’t loaded.
如果 this was the last subscriber, the server keeps the thread loaded until it has no subscribers 和 no thread activity for 30 minutes。When the grace period expires, app-server unloads the thread 和 发出 a thread/status/changed transition to notLoaded 以及 thread/closed.
{ "method": "thread/unsubscribe", "id": 22, "params": { "threadId": "thr_123" } } { "id": 22, "result": { "status": "unsubscribed" } } 如果 the thread later expires:
{ "method": "thread/status/changed", "params": { "threadId": "thr_123", "status": { "type": "notLoaded" } } } { "method": "thread/closed", "params": { "threadId": "thr_123" } } 归档 thread
使用 thread/归档 to move the persisted thread log (stored as a JSONL file on disk) 到 the archived sessions directory。Archiving a thread also attempts to 归档 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/列出 unless you pass archived:true。The server 发出 one thread/archived notification for each thread it actually 归档;如果 a spawned descendant can’t be archived, the request can still succeed 不使用 an archived notification for that descendant.
删除 thread
使用 thread/删除 to permanently 删除 a persisted active 或 archived thread 和 its spawned descendant threads。The server removes existing rollout files 和 associated metadata 之前 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" } } 取消归档 thread
使用 thread/取消归档 to move an archived thread rollout back 到 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" } } 触发 thread compaction
使用 thread/compact/启动 to trigger manual history compaction for a thread。The request 返回 立即 使用 {}.
App-server 发出 progress as standard turn/* 和 item/* notifications on 相同 threadId, including a contextCompaction item lifecycle (item/started then item/completed).
{ "method": "thread/compact/start", "id": 25, "params": { "threadId": "thr_b" } } { "id": 25, "result": {} } 运行 thread shell command
使用 thread/shellCommand for user-initiated shell commands that belong to a thread。The request 返回 立即 使用 {} while progress streams through standard turn/* 和 item/* notifications.
This API runs outside the sandbox 使用 full access 和 doesn’t inherit the thread sandbox policy。Clients should expose it only for explicit user-initiated commands.
如果 the thread already has an active turn, the command runs as an auxiliary action on that turn 和 its formatted output is injected 到 the turn’s message stream。如果 the thread is idle, app-server 启动 a standalone turn for the shell command.
{ "method": "thread/shellCommand", "id": 26, "params": { "threadId": "thr_b", "command": "git status --short" } } { "id": 26, "result": {} } 清理 background terminals
使用 thread/backgroundTerminals/clean to 停止 all running background terminals associated 使用 a thread。This method is experimental 和 需要 capabilities.experimentalApi = true.
{ "method": "thread/backgroundTerminals/clean", "id": 27, "params": { "threadId": "thr_b" } } { "id": 27, "result": {} } 使用 thread/backgroundTerminals/列出 to inspect running background terminals for a loaded thread。The request 支持 standard cursor 和 limit pagination, 和 the returned processId is the app-server process id。This method is experimental 和 需要 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 } } 使用 thread/backgroundTerminals/terminate 使用 that processId to 停止 one background terminal。This method is experimental 和 需要 capabilities.experimentalApi = true:
{ "method": "thread/backgroundTerminals/terminate", "id": 29, "params": { "threadId": "thr_b", "processId": "42" } } { "id": 29, "result": { "terminated": true } } 回滚 recent turns
使用 thread/rollback to remove the last numTurns entries 从 the in-memory context 和 persist a rollback marker in the rollout log。The returned thread includes turns populated 之后 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 列出 of items:
{ "type":"text", "text":"Explain this diff" }
{ "type":"image", "url":"https://.../design.png" }
{ "type":"localImage", "path":"/tmp/screenshot.png" }
你可以 override configuration settings per turn (model, effort, personality, cwd, sandbox policy, summary)。When specified, these settings become the defaults for later turns on 相同 thread。outputSchema applies only to 当前 turn。For sandboxPolicy.type = "externalSandbox", 设置 networkAccess to restricted 或 enabled;for workspaceWrite, networkAccess remains a boolean.
For turn/启动.collaborationMode, settings.developer_instructions:null means “使用 built-in instructions for 所选 mode” rather than clearing mode instructions.
Sandbox read access (ReadOnlyAccess)
sandboxPolicy 支持 explicit 读取-access controls:
readOnly:optional access ({ "type":"fullAccess" } by default, 或 restricted roots).
workspaceWrite:optional readOnlyAccess ({ "type":"fullAccess" } by default, 或 restricted roots).
Restricted 读取 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-读取 sessions。This improves tool compatibility 不使用 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 } 启动 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.4", "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 } } } 向 thread 注入 items
使用 thread/inject_items to append prebuilt Responses API items to a loaded thread’s prompt history 不使用 starting a user turn。These items are persisted to the rollout 和 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": {} } 引导 active turn
使用 turn/steer to append more user input to the active in-flight turn.
包含 expectedTurnId;it must match the active turn id.
The request fails 如果 there is no active turn on the thread.
turn/steer doesn’t emit 新的 turn/started notification.
turn/steer doesn’t accept turn-level overrides (model, cwd, sandboxPolicy, 或 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" } } 启动 turn(调用 skill)
Invoke a skill explicitly by including $<skill-name> in the text input 和 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 } } } 中断 turn
{ "method": "turn/interrupt", "id": 31, "params": { "threadId": "thr_123", "turnId": "turn_456" } } { "id": 31, "result": {} } On success, the turn finishes 使用 status:"interrupted".
Review
review/启动 runs the Codex reviewer for a thread 和 streams review items。Targets 包含:
uncommittedChanges
baseBranch (diff against a branch)
commit (review a specific commit)
custom (free-form instructions)
Use delivery:"inline" (default) to run the review on the existing thread, 或 delivery:"detached" to fork 新的 review thread.
Example request/response:
{ "method": "review/start", "id": 40, "params": { "threadId": "thr_123", "delivery": "inline", "target": { "type": "commit", "sha": "1234567deadbeef", "title": "Polish tui colors" } } } { "id": 40, "result": { "turn": { "id": "turn_900", "status": "inProgress", "items": [ { "type": "userMessage", "id": "turn_900", "content": [ { "type": "text", "text": "Review commit 1234567: Polish tui colors" } ] } ], "error": null }, "reviewThreadId": "thr_123" } } For a detached review, 使用 "delivery":"detached"。The response is 相同 shape, but reviewThreadId will be the id of the new review thread (different 从 原始 threadId)。The server also 发出 a thread/started notification for that new thread 之前 streaming the review turn.
Codex streams the usual turn/started notification followed by an item/started 使用 an enteredReviewMode item:
{ "method": "item/started", "params": { "item": { "type": "enteredReviewMode", "id": "turn_900", "review": "current changes" } } } When the reviewer finishes, the server 发出 item/started 和 item/completed containing an exitedReviewMode item 使用 the final review text:
{ "method": "item/completed", "params": { "item": { "type": "exitedReviewMode", "id": "turn_900", "review": "Looks solid overall..." } } } 使用 this notification to render the reviewer output in your client.
Process execution
process/* is an experimental, explicit process-control API。It 需要 capabilities.experimentalApi = true 和 runs outside Codex’s sandbox。使用 it only 当 your client intentionally exposes local process control 不使用 a sandbox.
Start a process 使用 process/spawn 和 provide a processHandle, then 使用 that handle for stdin, resize, 和 kill requests。Output streams through process/outputDelta notifications 和 completion streams through process/exited.
{ "method": "process/spawn", "id": 48, "params": { "command": ["python3", "-m", "pytest", "-q"], "processHandle": "pytest-1", "cwd": "/Users/me/project", "tty": true } } { "id": 48, "result": {} } { "method": "process/outputDelta", "params": { "processHandle": "pytest-1", "stream": "stdout", "deltaBase64": "Li4u" } } { "method": "process/exited", "params": { "processHandle": "pytest-1", "exitCode": 0 } } 使用 process/writeStdin 使用 deltaBase64, closeStdin, 或 both to send input。使用 process/resizePty for PTY resize events 和 process/kill to terminate a running process.
Command execution
command/exec runs a single command (argv array) under the server sandbox 不使用 creating a thread.
{ "method": "command/exec", "id": 50, "params": { "command": ["ls", "-la"], "cwd": "/Users/me/project", "sandboxPolicy": { "type": "workspaceWrite" }, "timeoutMs": 10000 } } { "id": 50, "result": { "exitCode": 0, "stdout": "...", "stderr": "" } } 使用 sandboxPolicy.type = "externalSandbox" 如果 you already sandbox the server process 和 want Codex to skip its own sandbox enforcement。For external sandbox mode, 设置 networkAccess to restricted (default) 或 enabled。For readOnly 和 workspaceWrite, 使用 相同 optional access / readOnlyAccess structure shown above.
Notes:
The server rejects empty command arrays.
sandboxPolicy accepts 相同 shape used by turn/启动 (例如, dangerFullAccess, readOnly, workspaceWrite, externalSandbox).
When omitted, timeoutMs falls back to the server default.
Set tty:true for PTY-backed sessions, 和 使用 processId 当 you plan to follow up 使用 command/exec/写入, command/exec/resize, 或 command/exec/terminate.
Set streamStdoutStderr:true to receive command/exec/outputDelta notifications while the command is running.
读取 admin requirements (configRequirements/read)
使用 configRequirements/读取 to inspect the effective admin requirements loaded 从 requirements.toml 和/或 MDM.
{ "method": "configRequirements/read", "id": 52, "params": {} } { "id": 52, "result": { "requirements": { "allowedApprovalPolicies": ["onRequest", "unlessTrusted"], "allowedSandboxModes": ["readOnly", "workspaceWrite"], "featureRequirements": { "personality": true, "unified_exec": false }, "network": { "enabled": true, "allowedDomains": ["api.openai.com"], "allowUnixSockets": ["/tmp/example.sock"], "dangerouslyAllowAllUnixSockets": false } } } } result.requirements is null 当 no requirements are configured。See the docs on requirements.toml for details on 支持的 keys 和 values.
Windows sandbox setup (windowsSandbox/setupStart)
Custom Windows clients can trigger sandbox setup asynchronously 而不是 blocking on startup checks.
{ "method": "windowsSandbox/setupStart", "id": 53, "params": { "mode": "elevated" } } { "id": 53, "result": { "started": true } } App-server 启动 setup in the background 和 later 发出 a completion notification:
{ "method": "windowsSandbox/setupCompleted", "params": { "mode": "elevated", "success": true, "error": null } } Modes:
elevated - run the elevated Windows sandbox setup path.
unelevated - run the legacy setup/preflight path.
Filesystem
The v2 filesystem APIs operate on absolute paths。使用 fs/watch 当 a client needs to invalidate UI state 之后 a file 或 directory changes.
{ "method": "fs/watch", "id": 54, "params": { "watchId": "0195ec6b-1d6f-7c2e-8c7a-56f2c4a8b9d1", "path": "/Users/me/project/.git/HEAD" } } { "id": 54, "result": { "path": "/Users/me/project/.git/HEAD" } } { "method": "fs/changed", "params": { "watchId": "0195ec6b-1d6f-7c2e-8c7a-56f2c4a8b9d1", "changedPaths": ["/Users/me/project/.git/HEAD"] } } { "method": "fs/unwatch", "id": 55, "params": { "watchId": "0195ec6b-1d6f-7c2e-8c7a-56f2c4a8b9d1" } } { "id": 55, "result": {} } Watching a file 发出 fs/changed for that file path, including 更新 delivered by replace 或 rename operations.
Events
Event notifications are the server-initiated stream for thread lifecycles, turn lifecycles, 和 the items within them。After you 启动 或 resume a thread, keep reading the active transport stream for thread/started, thread/archived, thread/unarchived, thread/closed, thread/status/changed, turn/*, item/*, 和 serverRequest/resolved notifications.
Notification opt-out
Clients can suppress specific notifications per connection by sending exact method names in initialize.params.capabilities.optOutNotificationMethods.
Exact-match only:item/agentMessage/delta suppresses only that method.
Unknown method names are ignored.
Applies to 当前 thread/*, turn/*, item/*, 和 related v2 notifications.
Doesn’t apply to requests, responses, 或 errors.
Fuzzy file search events (experimental)
The fuzzy file search session API 发出 per-query notifications:
fuzzyFileSearch/sessionUpdated - { sessionId, query, files } 使用 当前 matches for the active query.
fuzzyFileSearch/sessionCompleted - { sessionId } once indexing 和 matching for that query completes.
Windows sandbox setup events
windowsSandbox/setupCompleted - { mode, success, error } 发出 之后 a windowsSandbox/setupStart request finishes.
Turn events
turn/started - { turn } 使用 the turn id, empty items, 和 status:"inProgress".
turn/completed - { turn } where turn.status is completed, interrupted, 或 failed;failures carry { error:{ message, codexErrorInfo?, additionalDetails? } }.
turn/diff/updated - { threadId, turnId, diff } 使用 the latest aggregated unified diff across every file change in the turn.
turn/plan/updated - { turnId, explanation?, plan } whenever the agent shares 或 changes its plan;each plan entry is { step, status } 使用 status in pending, inProgress, 或 completed.
thread/tokenUsage/updated - usage 更新 for the active thread.
turn/diff/updated 和 turn/plan/updated currently 包含 empty items arrays even 当 item events stream。使用 item/* notifications as the source of truth for turn items.
Items
ThreadItem is the tagged union carried in turn responses 和 item/* notifications。Common item types 包含:
userMessage - {id, content} where content is a 列出 of user inputs (text, image, 或 localImage).
agentMessage - {id, text, phase?} containing the accumulated agent reply。When present, phase uses Responses API wire values (commentary, final_answer).
plan - {id, text} containing proposed plan text in plan mode。Treat the final plan item 从 item/completed as authoritative.
reasoning - {id, summary, content} where summary holds streamed reasoning summaries 和 content holds raw reasoning blocks.
commandExecution - {id, command, cwd, status, commandActions, aggregatedOutput?, exitCode?, durationMs?}.
fileChange - {id, changes, status} describing proposed edits;changes 列出 {path, kind, diff}.
mcpToolCall - {id, server, tool, status, arguments, result?, error?}.
dynamicToolCall - {id, tool, arguments, status, contentItems?, success?, durationMs?} for client-executed dynamic tool invocations.
collabToolCall - {id, tool, status, senderThreadId, receiverThreadId?, newThreadId?, prompt?, agentStatus?}.
webSearch - {id, query, action?} for web search requests issued by the agent.
imageView - {id, path} 发出 当 the agent invokes the image viewer tool.
enteredReviewMode - {id, review} sent 当 the reviewer 启动.
exitedReviewMode - {id, review} 发出 当 the reviewer finishes.
contextCompaction - {id} 发出 当 Codex compacts the conversation history.
For webSearch.action, the action type can be search (query?, queries?), openPage (url?), 或 findInPage (url?, pattern?).
The app server deprecates the legacy thread/compacted notification;使用 the contextCompaction item instead.
All items emit two shared lifecycle events:
item/started - 发出 完整 item 当 新的 unit of work begins;the item.id matches the itemId used by deltas.
item/completed - sends the final item once work finishes;treat this as the authoritative state.
Item deltas
item/agentMessage/delta - appends streamed text for the agent message.
item/plan/delta - streams proposed plan text。The final plan item may not exactly equal the concatenated deltas.
item/reasoning/summaryTextDelta - streams readable reasoning summaries;summaryIndex increments 当 新的 summary section opens.
item/reasoning/summaryPartAdded - marks a boundary between reasoning summary sections.
item/reasoning/textDelta - streams raw reasoning text (当 支持的 by the model).
item/commandExecution/outputDelta - streams stdout/stderr for a command;append deltas in order.
item/fileChange/outputDelta - deprecated compatibility notification for legacy apply_patch text output。Current app-server versions no longer emit it;使用 fileChange items 和 turn/diff/updated instead.
Errors
如果 a turn fails, the server 发出 an error event 使用 { error:{ message, codexErrorInfo?, additionalDetails? } } 和 then finishes the turn 使用 status:"failed"。When an upstream HTTP status is available, it appears in codexErrorInfo.httpStatusCode.
Common codexErrorInfo values 包含:
ContextWindowExceeded
UsageLimitExceeded
HttpConnectionFailed (4xx/5xx upstream errors)
ResponseStreamConnectionFailed
ResponseStreamDisconnected
ResponseTooManyFailedAttempts
BadRequest, Unauthorized, SandboxError, InternalServerError, Other
When an upstream HTTP status is available, the server forwards it in httpStatusCode on the relevant codexErrorInfo variant.
Approvals
Depending on a user’s Codex settings, command execution 和 file changes may 需要 approval。The app-server sends a server-initiated JSON-RPC request to the client, 和 the client responds 使用 a decision payload.
Command execution decisions:accept, acceptForSession, decline, cancel, 或 { "acceptWithExecpolicyAmendment":{ "execpolicy_amendment":["cmd", "..."] } }.
Command execution decisions:accept, acceptForSession, decline, cancel, 或 { "acceptWithExecpolicyAmendment":{ "execpolicy_amendment":["cmd", "..."] } }.
File change decisions:accept, acceptForSession, decline, cancel.
File change decisions:accept, acceptForSession, decline, cancel.
Requests 包含 threadId 和 turnId - 使用 them to scope UI state to the active conversation.
Requests 包含 threadId 和 turnId - 使用 them to scope UI state to the active conversation.
The server resumes 或 declines the work 和 ends the item 使用 item/completed.
The server resumes 或 declines the work 和 ends the item 使用 item/completed.
Command execution approvals
Order of messages:
item/started shows the pending commandExecution item 使用 command, cwd, 和 other fields.
item/commandExecution/requestApproval includes itemId, threadId, turnId, optional reason, optional command, optional cwd, optional commandActions, optional proposedExecpolicyAmendment, optional networkApprovalContext, 和 optional availableDecisions。When initialize.params.capabilities.experimentalApi = true, the payload can also 包含 experimental additionalPermissions describing requested per-command sandbox access。Any filesystem paths inside additionalPermissions are absolute on the wire.
Client responds 使用 one of the command execution approval decisions above.
serverRequest/resolved confirms that the pending request has been answered 或 cleared.
item/completed returns the final commandExecution item with status:completed | failed | declined.
When networkApprovalContext is present, the prompt is for managed network access (not a general shell-command approval)。The current v2 schema exposes the target host 和 protocol;clients should render a network-specific prompt 和 not rely on command being a user-meaningful shell command preview.
Codex groups concurrent network approval prompts by destination (host, protocol, 和 port)。The app-server may therefore send one prompt that unblocks multiple queued requests to 相同 destination, while different ports on 相同 host are treated separately.
File change approvals
Order of messages:
item/started emits a fileChange item with proposed changes and status:"inProgress".
item/fileChange/requestApproval includes itemId, threadId, turnId, optional reason, 和 optional grantRoot.
Client responds 使用 one of the file change approval decisions above.
serverRequest/resolved confirms that the pending request has been answered 或 cleared.
item/completed returns the final fileChange item with status:completed | failed | declined.
tool/requestUserInput
When the client responds to item/tool/requestUserInput, app-server 发出 serverRequest/resolved 使用 { threadId, requestId }。如果 the pending request is cleared by turn 启动, turn completion, 或 turn interruption 之前 the client answers, the server 发出 相同 notification for that cleanup.
Request params 包含 autoResolutionMs as an integer millisecond timeout 或 null。When present, host clients can resolve the prompt 自动 之后 that interval 如果 the user doesn’t answer.
Dynamic tool calls (experimental)
dynamicTools on thread/启动 和 the corresponding item/tool/调用 request 或 response flow are experimental APIs.
Dynamic tool names 和 namespace names must follow Responses API naming constraints。Avoid reserved namespace names used by built-in Codex tools.
When a dynamic tool is invoked during a turn, app-server 发出:
item/started 使用 item.type = "dynamicToolCall", status = "inProgress", 以及 tool 和 arguments.
item/tool/调用 as a server request to the client.
The client response payload 使用 returned content items.
item/completed 使用 item.type = "dynamicToolCall", the final status, 和 any returned contentItems 或 success value.
MCP tool-call approvals (apps)
App (connector) tool calls can also 需要 approval。When an app tool 调用 has side effects, the server may elicit approval 使用 tool/requestUserInput 和 options such as Accept, Decline, 和 Cancel。Destructive tool annotations always trigger approval even 当 the tool also advertises less-privileged hints。如果 the user declines 或 cancels, the related mcpToolCall item completes 使用 an error 而不是 running the tool.
Skills
Invoke a skill by including $<skill-name> in the user text input。Add a skill input item (recommended) so the server injects full skill instructions 而不是 relying on the model to resolve the name.
{ "method": "turn/start", "id": 101, "params": { "threadId": "thread-1", "input": [ { "type": "text", "text": "$skill-creator Add a new skill for triaging flaky CI." }, { "type": "skill", "name": "skill-creator", "path": "/Users/me/.codex/skills/skill-creator/SKILL.md" } ] } } 如果 you 省略 the skill item, the model will still parse the $<skill-name> marker 和 try to locate the skill, which can add latency.
Example:
$skill-creator Add a new skill for triaging flaky CI and include step-by-step usage. 使用 skills/列出 to 获取 available skills (optionally scoped by cwds, 使用 forceReload)。你可以 also 包含 perCwdExtraUserRoots to scan extra absolute paths as user scope for specific cwd values。App-server ignores entries whose cwd isn’t present in cwds。skills/列出 may reuse a cached result per cwd;设置 forceReload:true to refresh 从 disk。When present, the server 读取 interface 和 dependencies 从 SKILL.json.
{ "method": "skills/list", "id": 25, "params": { "cwds": ["/Users/me/project", "/Users/me/other-project"], "forceReload": true, "perCwdExtraUserRoots": [ { "cwd": "/Users/me/project", "extraUserRoots": ["/Users/me/shared-skills"] } ] } } { "id": 25, "result": { "data": [{ "cwd": "/Users/me/project", "skills": [ { "name": "skill-creator", "description": "Create or update a Codex skill", "enabled": true, "interface": { "displayName": "Skill Creator", "shortDescription": "Create or update a Codex skill" }, "dependencies": { "tools": [ { "type": "env_var", "value": "GITHUB_TOKEN", "description": "GitHub API token" }, { "type": "mcp", "value": "github", "transport": "streamable_http", "url": "https://example.com/mcp" } ] } } ], "errors": [] }] } } The server also 发出 skills/changed notifications 当 watched local skill files change。Treat this as an invalidation signal 和 rerun skills/列出 使用 your current params 当 needed.
To enable 或 disable a skill by path:
{ "method": "skills/config/write", "id": 26, "params": { "path": "/Users/me/.codex/skills/skill-creator/SKILL.md", "enabled": false } } Apps (connectors)
使用 app/列出 to 获取 available apps。In the CLI/TUI, /apps is the user-facing picker;in custom clients, 调用 app/列出 directly。Each entry includes both isAccessible (available to the user) 和 isEnabled (enabled in config.toml) so clients can distinguish install/access 从 local enabled state。App entries can also 包含 optional branding, appMetadata, 和 labels fields.
{ "method": "app/list", "id": 50, "params": { "cursor": null, "limit": 50, "threadId": "thread-1", "forceRefetch": false } } { "id": 50, "result": { "data": [ { "id": "demo-app", "name": "Demo App", "description": "Example connector for documentation.", "logoUrl": "https://example.com/demo-app.png", "logoUrlDark": null, "distributionChannel": null, "branding": null, "appMetadata": null, "labels": null, "installUrl": "https://chatgpt.com/apps/demo-app/demo-app", "isAccessible": true, "isEnabled": true } ], "nextCursor": null } } 如果 you provide threadId, app feature gating (features.apps) uses that thread’s config snapshot。When omitted, app-server uses the latest global config.
app/列出 返回 之后 both accessible apps 和 directory apps load。设置 forceRefetch:true to bypass app caches 和 获取 fresh data。Cache entries are only replaced 当 refreshes succeed.
The server also 发出 app/列出/updated notifications whenever either source (accessible apps 或 directory apps) finishes loading。Each notification includes the latest merged app 列出.
{ "method": "app/list/updated", "params": { "data": [ { "id": "demo-app", "name": "Demo App", "description": "Example connector for documentation.", "logoUrl": "https://example.com/demo-app.png", "logoUrlDark": null, "distributionChannel": null, "branding": null, "appMetadata": null, "labels": null, "installUrl": "https://chatgpt.com/apps/demo-app/demo-app", "isAccessible": true, "isEnabled": true } ] } } Invoke an app by inserting $<app-slug> in the text input 和 adding a mention input item 使用 the app://<id> path (recommended).
{ "method": "turn/start", "id": 51, "params": { "threadId": "thread-1", "input": [ { "type": "text", "text": "$demo-app Pull the latest updates from the team." }, { "type": "mention", "name": "Demo App", "path": "app://demo-app" } ] } } app settings 的 Config RPC 示例
使用 config/读取, config/value/写入, 和 config/batchWrite to inspect 或 更新 app controls in config.toml.
Read the effective app config shape (including _default 和 per-tool overrides):
{ "method": "config/read", "id": 60, "params": { "includeLayers": false } } { "id": 60, "result": { "config": { "apps": { "_default": { "enabled": true, "destructive_enabled": true, "open_world_enabled": true, "approvals_reviewer": "user", "default_tools_approval_mode": "auto" }, "google_drive": { "enabled": true, "destructive_enabled": false, "approvals_reviewer": "auto_review", "default_tools_approval_mode": "prompt", "tools": { "files/delete": { "enabled": false, "approval_mode": "approve" } } } } } } } apps._default.approvals_reviewer sets the reviewer for all apps unless a per-app value overrides it。When both are omitted, the app inherits the top-level approvals_reviewer value。apps._default.default_tools_approval_mode sets the fallback approval mode for tools 不使用 a per-app 或 per-tool override。Managed approval-mode requirements override tool approval-mode settings.
Update a single app setting:
{ "method": "config/value/write", "id": 61, "params": { "keyPath": "apps.google_drive.default_tools_approval_mode", "value": "prompt", "mergeStrategy": "replace" } } Apply multiple app edits atomically:
{ "method": "config/batchWrite", "id": 62, "params": { "edits": [ { "keyPath": "apps._default.destructive_enabled", "value": false, "mergeStrategy": "upsert" }, { "keyPath": "apps.google_drive.tools.files/delete.approval_mode", "value": "approve", "mergeStrategy": "upsert" } ] } } 检测并导入 external agent config
使用 externalAgentConfig/detect to discover external-agent artifacts that can be migrated, then pass 所选 entries to externalAgentConfig/import.
Detection example:
{ "method": "externalAgentConfig/detect", "id": 63, "params": { "includeHome": true, "cwds": ["/Users/me/project"] } } { "id": 63, "result": { "items": [ { "itemType": "AGENTS_MD", "description": "Import /Users/me/project/CLAUDE.md to /Users/me/project/AGENTS.md.", "cwd": "/Users/me/project" }, { "itemType": "SKILLS", "description": "Copy skill folders from /Users/me/.claude/skills to /Users/me/.agents/skills.", "cwd": null } ] } } Import example:
{ "method": "externalAgentConfig/import", "id": 64, "params": { "migrationItems": [ { "itemType": "AGENTS_MD", "description": "Import /Users/me/project/CLAUDE.md to /Users/me/project/AGENTS.md.", "cwd": "/Users/me/project" } ], "source": "claude-code" } } { "id": 64, "result": { "importId": "8ae96ff3-3425-4f4c-8772-b6fd61502868" } } The optional top-level source import parameter labels the product that produced 所选 migration items.
The server 发出 externalAgentConfig/import/progress as item types complete, 和 externalAgentConfig/import/completed 之后 all synchronous 和 background imports finish。These notifications 包含 相同 importId 从 the response 和 itemTypeResults 使用 per-type successes 和 failures。Completion may arrive 立即 之后 the response 或 之后 background remote imports complete.
{ "method": "externalAgentConfig/import/progress", "params": { "importId": "8ae96ff3-3425-4f4c-8772-b6fd61502868", "itemTypeResults": [ { "itemType": "AGENTS_MD", "successes": [ { "itemType": "AGENTS_MD", "cwd": "/Users/me/project", "source": null, "target": "/Users/me/project/AGENTS.md" } ], "failures": [] } ] } } { "method": "externalAgentConfig/import/completed", "params": { "importId": "8ae96ff3-3425-4f4c-8772-b6fd61502868", "itemTypeResults": [ { "itemType": "AGENTS_MD", "successes": [ { "itemType": "AGENTS_MD", "cwd": "/Users/me/project", "source": null, "target": "/Users/me/project/AGENTS.md" } ], "failures": [] } ] } } Read prior completed imports:
{ "method": "externalAgentConfig/import/readHistories", "id": 65 } { "id": 65, "result": { "data": [ { "importId": "8ae96ff3-3425-4f4c-8772-b6fd61502868", "completedAtMs": 1781784000000, "successes": [ { "itemType": "AGENTS_MD", "cwd": "/Users/me/project", "source": null, "target": "/Users/me/project/AGENTS.md" } ], "failures": [] } ] } } Supported itemType values are AGENTS_MD, CONFIG, SKILLS, PLUGINS, MCP_SERVER_CONFIG, SUBAGENTS, HOOKS, COMMANDS, 和 SESSIONS。For PLUGINS items, details.plugins 列出 each marketplaceName 和 the pluginNames Codex can try to migrate。Detection 返回 only items that still have work to do。For example, Codex skips AGENTS migration 当 AGENTS.md already exists 和 is non-empty, 和 skill imports don’t overwrite existing skill directories.
When detecting plugins 从 .claude/settings.json, Codex 读取 configured marketplace sources 从 extraKnownMarketplaces。如果 enabledPlugins contains plugins 从 claude-plugins-official but the marketplace source is missing, Codex infers anthropics/claude-plugins-official as the source.
Auth endpoints
The JSON-RPC auth/account surface exposes request/response methods 以及 server-initiated notifications (no id)。使用 these to determine auth state, 启动 或 cancel logins, logout, inspect ChatGPT rate limits, 和 notify workspace owners about depleted credits 或 usage limits.
Authentication modes
Codex 支持 these authentication modes。account/updated.authMode shows the active mode 和 includes 当前 ChatGPT planType 当 available。account/读取 also reports account 和 plan details.
API key (apikey) - the caller supplies an OpenAI API key with type:"apiKey", 和 Codex stores it for API requests.
ChatGPT managed (chatgpt) - Codex owns the ChatGPT OAuth flow, persists tokens, 和 refreshes them 自动。Start 使用 type:"chatgpt" for the browser flow 或 type:"chatgptDeviceCode" for the device-code flow.
ChatGPT external tokens (chatgptAuthTokens) - experimental 和 intended for host apps that already own the user’s ChatGPT auth lifecycle。The host app supplies an accessToken, chatgptAccountId, 和 optional chatgptPlanType directly, 和 must refresh the token 当 asked.
Amazon Bedrock - account/read reports Bedrock accounts as type:"amazonBedrock" 和 indicates whether credentials come 从 a Codex-managed Bedrock API key (credentialSource:"codexManaged") 或 the external AWS credential chain (credentialSource:"awsManaged")。account/updated.authMode uses bedrockApiKey for Codex-managed Bedrock API keys.
API 概览
account/read - 获取 current account info;optionally refresh tokens.
account/login/start - begin login (apiKey, chatgpt, chatgptDeviceCode, 或 experimental chatgptAuthTokens).
account/login/completed (notify) - 发出 当 a login attempt finishes (success 或 error).
account/login/cancel - cancel a pending managed ChatGPT login by loginId.
account/logout - sign out;triggers account/updated.
account/updated (notify) - emitted whenever auth mode changes (authMode:apikey, chatgpt, chatgptAuthTokens, agentIdentity, personalAccessToken, bedrockApiKey, 或 null) 和 includes planType 当 available.
account/chatgptAuthTokens/refresh (server request) - request fresh externally managed ChatGPT tokens 之后 an authorization error.
account/rateLimits/read - 获取 ChatGPT rate limits.
account/rateLimits/updated (notify) - 发出 whenever a user’s ChatGPT rate limits change.
account/sendAddCreditsNudgeEmail - ask ChatGPT to email a workspace owner about depleted credits 或 a reached usage limit.
account/rateLimitResetCredit/consume - consume one earned rate-limit reset using a caller-provided idempotencyKey value.
account/usage/read - 获取 ChatGPT account token-activity summaries 和 daily buckets.
mcpServer/oauthLogin/completed (notify) - 发出 之后 a mcpServer/oauth/login flow finishes;payload includes { name, success, error? }.
mcpServer/startupStatus/updated (notify) - 发出 当 a configured MCP server’s startup status changes for a loaded thread;payload includes { name, status, error }.
1) 检查 auth state
Request:
{ "method": "account/read", "id": 1, "params": { "refreshToken": false } } Response examples:
{ "id": 1, "result": { "account": null, "requiresOpenaiAuth": false } } { "id": 1, "result": { "account": null, "requiresOpenaiAuth": true } } { "id": 1, "result": { "account": { "type": "apiKey" }, "requiresOpenaiAuth": true } } { "id": 1, "result": { "account": { "type": "amazonBedrock", "credentialSource": "codexManaged" }, "requiresOpenaiAuth": false } } { "id": 1, "result": { "account": { "type": "amazonBedrock", "credentialSource": "awsManaged" }, "requiresOpenaiAuth": false } } { "id": 1, "result": { "account": { "type": "chatgpt", "email": "user@example.com", "planType": "pro" }, "requiresOpenaiAuth": true } } Field notes:
refreshToken (boolean):设置 true to force a token refresh in managed ChatGPT mode。In external token mode (chatgptAuthTokens), app-server ignores this flag.
requiresOpenaiAuth reflects the active provider;当 false, Codex can run 不使用 OpenAI credentials.
Amazon Bedrock reports credentialSource:"codexManaged" 当 it uses a Bedrock API key managed by Codex。It reports credentialSource:"awsManaged" for the external AWS credential path。This identifies 所选 credential source;it doesn’t validate that the AWS credential chain can resolve credentials.
2) 使用 API key 登录
Send:{ "method":"account/login/启动", "id":2, "params":{ "type":"apiKey", "apiKey":"sk-..." } }
Send:
{ "method": "account/login/start", "id": 2, "params": { "type": "apiKey", "apiKey": "sk-..." } } Expect:{ "id":2, "result":{ "type":"apiKey" } }
Expect:
{ "id": 2, "result": { "type": "apiKey" } } Notifications:{ "method":"account/login/completed", "params":{ "loginId":null, "success":true, "error":null } } { "method":"account/updated", "params":{ "authMode":"apikey", "planType":null } }
Notifications:
{ "method": "account/login/completed", "params": { "loginId": null, "success": true, "error": null } } { "method": "account/updated", "params": { "authMode": "apikey", "planType": null } } 3) 使用 ChatGPT 登录(browser flow)
Start:{ "method":"account/login/启动", "id":3, "params":{ "type":"chatgpt" } } { "id":3, "result":{ "type":"chatgpt", "loginId":"<uuid>", "authUrl":"https://chatgpt.com/...&redirect_uri=http%3A%2F%2Flocalhost%3A<port>%2Fauth%2Fcallback" } }
Start:
{ "method": "account/login/start", "id": 3, "params": { "type": "chatgpt" } } { "id": 3, "result": { "type": "chatgpt", "loginId": "<uuid>", "authUrl": "https://chatgpt.com/...&redirect_uri=http%3A%2F%2Flocalhost%3A<port>%2Fauth%2Fcallback" } } Open authUrl in a browser;the app-server hosts the local callback.
Open authUrl in a browser;the app-server hosts the local callback.
Wait for notifications:{ "method":"account/login/completed", "params":{ "loginId":"<uuid>", "success":true, "error":null } } { "method":"account/updated", "params":{ "authMode":"chatgpt", "planType":"以及" } }
Wait for notifications:
{ "method": "account/login/completed", "params": { "loginId": "<uuid>", "success": true, "error": null } } { "method": "account/updated", "params": { "authMode": "chatgpt", "planType": "plus" } } 3b) 使用 ChatGPT 登录(device-code flow)
使用 this flow 当 your client owns the sign-in ceremony 或 当 a browser callback is brittle.
Start:{ "method":"account/login/启动", "id":4, "params":{ "type":"chatgptDeviceCode" } } { "id":4, "result":{ "type":"chatgptDeviceCode", "loginId":"<uuid>", "verificationUrl":"https://auth.openai.com/codex/device", "userCode":"ABCD-1234" } }
Start:
{ "method": "account/login/start", "id": 4, "params": { "type": "chatgptDeviceCode" } } { "id": 4, "result": { "type": "chatgptDeviceCode", "loginId": "<uuid>", "verificationUrl": "https://auth.openai.com/codex/device", "userCode": "ABCD-1234" } } Show verificationUrl 和 userCode to the user;the frontend owns the UX.
Show verificationUrl 和 userCode to the user;the frontend owns the UX.
Wait for notifications:{ "method":"account/login/completed", "params":{ "loginId":"<uuid>", "success":true, "error":null } } { "method":"account/updated", "params":{ "authMode":"chatgpt", "planType":"以及" } }
Wait for notifications:
{ "method": "account/login/completed", "params": { "loginId": "<uuid>", "success": true, "error": null } } { "method": "account/updated", "params": { "authMode": "chatgpt", "planType": "plus" } } 3c) 使用 externally managed ChatGPT tokens 登录 (chatgptAuthTokens)
使用 this experimental mode only 当 a host application owns the user’s ChatGPT auth lifecycle 和 supplies tokens directly。Clients must 设置 capabilities.experimentalApi = true during initialize 之前 using this login type.
Send:{ "method":"account/login/启动", "id":7, "params":{ "type":"chatgptAuthTokens", "accessToken":"<jwt>", "chatgptAccountId":"org-123", "chatgptPlanType":"business" } }
Send:
{ "method": "account/login/start", "id": 7, "params": { "type": "chatgptAuthTokens", "accessToken": "<jwt>", "chatgptAccountId": "org-123", "chatgptPlanType": "business" } } Expect:{ "id":7, "result":{ "type":"chatgptAuthTokens" } }
Expect:
{ "id": 7, "result": { "type": "chatgptAuthTokens" } } Notifications:{ "method":"account/login/completed", "params":{ "loginId":null, "success":true, "error":null } } { "method":"account/updated", "params":{ "authMode":"chatgptAuthTokens", "planType":"business" } }
Notifications:
{ "method": "account/login/completed", "params": { "loginId": null, "success": true, "error": null } } { "method": "account/updated", "params": { "authMode": "chatgptAuthTokens", "planType": "business" } } When the server receives a 401 Unauthorized, it may request refreshed tokens 从 the host app:
{ "method": "account/chatgptAuthTokens/refresh", "id": 8, "params": { "reason": "unauthorized", "previousAccountId": "org-123" } } { "id": 8, "result": { "accessToken": "<jwt>", "chatgptAccountId": "org-123", "chatgptPlanType": "business" } } The server retries 原始 request 之后 a successful refresh response。Requests time out 之后 about 10 seconds.
4) 取消 ChatGPT login
{ "method": "account/login/cancel", "id": 4, "params": { "loginId": "<uuid>" } } { "method": "account/login/completed", "params": { "loginId": "<uuid>", "success": false, "error": "..." } } 5) Logout
{ "method": "account/logout", "id": 5 } { "id": 5, "result": {} } { "method": "account/updated", "params": { "authMode": null, "planType": null } } 6) Rate limits (ChatGPT)
{ "method": "account/rateLimits/read", "id": 6 } { "id": 6, "result": { "rateLimits": { "limitId": "codex", "limitName": null, "primary": { "usedPercent": 25, "windowDurationMins": 15, "resetsAt": 1730947200 }, "secondary": null, "rateLimitReachedType": null }, "rateLimitsByLimitId": { "codex": { "limitId": "codex", "limitName": null, "primary": { "usedPercent": 25, "windowDurationMins": 15, "resetsAt": 1730947200 }, "secondary": null, "rateLimitReachedType": null }, "codex_other": { "limitId": "codex_other", "limitName": "codex_other", "primary": { "usedPercent": 42, "windowDurationMins": 60, "resetsAt": 1730950800 }, "secondary": null, "rateLimitReachedType": null } }, "rateLimitResetCredits": { "availableCount": 2 } } } { "method": "account/rateLimits/updated", "params": { "rateLimits": { "limitId": "codex", "primary": { "usedPercent": 31, "windowDurationMins": 15, "resetsAt": 1730948100 } } } } Field notes:
rateLimits is the backward-compatible single-bucket view.
rateLimitsByLimitId (当 present) is the multi-bucket view keyed by metered limit_id (例如 codex).
limitId is the metered bucket identifier.
limitName is an optional user-facing label for the bucket.
usedPercent is current usage within the quota window.
windowDurationMins is the quota window length.
resetsAt is a Unix timestamp (seconds) for the next reset.
planType is included 当 the server 返回 the ChatGPT plan associated 使用 a bucket.
credits is included 当 the server 返回 remaining workspace credit details.
rateLimitReachedType identifies the server-classified limit state 当 one has been reached.
rateLimitResetCredits contains the available earned-reset count 当 the service provides it。Fetch account/rateLimits/读取 之后 consuming a reset.
7) Token usage (ChatGPT)
使用 account/usage/读取 to 获取 ChatGPT token-activity summary fields 和 optional daily buckets.
{ "method": "account/usage/read", "id": 7 } { "id": 7, "result": { "summary": { "lifetimeTokens": 1234567, "peakDailyTokens": 45678, "longestRunningTurnSec": 540, "currentStreakDays": 8, "longestStreakDays": 14 }, "dailyUsageBuckets": [ { "startDate": "2026-06-18", "tokens": 12345 } ] } } Field notes:
summary values may be null 当 the service hasn’t returned that metric.
dailyUsageBuckets may be null;当 present, each bucket includes startDate 和 tokens.
The endpoint 需要 authentication backed by Codex services。ChatGPT, external ChatGPT tokens, agent identity, 和 personal access token auth work;API-key-only 和 Bedrock auth don’t.
8) Earned rate-limit resets (ChatGPT)
使用 account/rateLimitResetCredit/consume to consume one earned reset.
{ "method": "account/rateLimitResetCredit/consume", "id": 8, "params": { "idempotencyKey": "8ae96ff3-3425-4f4c-8772-b6fd61502868" } } { "id": 8, "result": { "outcome": "reset" } } Field notes:
idempotencyKey must be non-empty。使用 a UUID for each logical redemption attempt 和 reuse 相同 value 当 retrying that attempt.
reset means a credit was consumed.
alreadyRedeemed means 相同 redemption completed previously。Treat it as an idempotent success 和 refresh account limits.
nothingToReset means there is no eligible rate-limit window to reset.
noCredit means the account has no earned reset credits available.
Fetch account/rateLimits/读取 之后 consuming a reset 而不是 inferring updated windows 从 this response.
9) 通知 workspace owner 额度限制
使用 account/sendAddCreditsNudgeEmail to ask ChatGPT to email a workspace owner 当 credits are depleted 或 a usage limit has been reached.
{ "method": "account/sendAddCreditsNudgeEmail", "id": 9, "params": { "creditType": "credits" } } { "id": 9, "result": { "status": "sent" } } Use creditType:"credits" 当 workspace credits are depleted, 或 creditType:"usage_limit" 当 the workspace usage limit has been reached。如果 the owner was already notified recently, the response status is cooldown_active.