文档导航

Codex App Server

使用 app-server 协议将 Codex 嵌入您的产品

Codex 通过 app-server 接口为 Codex VS Code 扩展程序等功能丰富的客户端提供支持。如果您希望在自己的产品中深度集成 Codex,可以通过该接口实现身份验证、访问对话历史、处理审批,并以流式方式接收智能体事件。app-server 的实现已在 Codex 的 GitHub 代码仓库中开源(openai/codex/codex-rs/app-server)。有关 Codex 开源组件的完整列表,请参阅开源页面。

如果您要自动执行作业或在 CI 中运行 Codex,请使用 Codex SDK。

连接 CLI 终端界面

在远程终端界面模式下,您可以在一台机器上运行 app-server,再从另一台机器上的 Codex CLI 终端界面连接到它。启动 WebSocket 监听器:

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

然后连接终端界面:

codex --remote ws://127.0.0.1:4500

对于非本地连接,请配置 WebSocket 身份验证,并使用 TLS 保护连接。将持有者令牌存入环境变量,在命令行上传入变量名,以免直接暴露令牌:

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

--remote 选项接受 ws://、wss://、unix:// 和 unix://PATH 端点。仅对 localhost 或经 SSH 端口转发的连接使用明文 WebSocket。

连接远程代码模式主机

默认情况下,app-server 会启动本地代码模式主机。要让同一 app-server 进程中的多个线程共享一台远程主机,请将远程主机基于 HTTP/2 的 gRPC 端点传给 --code-mode-host。

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

连接远程主机时,请使用 HTTPS 保护工具参数和结果。仅在使用回环地址或通过安全隧道连接时使用 HTTP。URL 中应填写主机名,也可以指定端口。请省略凭据、路径、查询字符串和片段。客户端到 app-server 的连接需单独通过 --listen 配置。

协议

与 MCP 一样,codex app-server 支持使用 JSON-RPC 2.0 消息进行双向通信(传输时省略 "jsonrpc":"2.0" 标头)。

支持的传输方式:

  • stdio(--listen stdio://,默认):以换行符分隔的 JSON(JSONL)。
  • websocket(--listen ws://IP:PORT,实验性,不提供支持):每个 WebSocket 文本帧承载一条 JSON-RPC 消息。
  • Unix 套接字(--listen unix:// 或 --listen unix://PATH):通过 Codex 默认的 app-server 控制套接字或自定义 Unix 套接字路径,使用标准 HTTP Upgrade 握手建立 WebSocket 连接。
  • off(--listen off):不开放本地传输接口。

使用 --listen ws://IP:PORT 运行时,同一监听器还支持基本的 HTTP 健康探测:

  • GET /readyz 在监听器开始接受新连接后返回 200 OK。
  • GET /healthz 返回 200 OK 的条件是请求中不含 Origin 标头。
  • 包含 Origin 标头的请求会被拒绝,并收到 403 Forbidden。

WebSocket 传输为实验性功能,不提供支持。ws://127.0.0.1:PORT 等本地监听器适用于 localhost 和 SSH 端口转发。在当前逐步推出期间,非回环地址上的 WebSocket 监听器默认允许未经身份验证的连接,请先配置 WebSocket 身份验证,再开放远程访问。

支持的 WebSocket 身份验证参数:

  • --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

对于已签名的持有者令牌,还可以设置 --ws-issuer、--ws-audience 和 --ws-max-clock-skew-seconds。客户端在 WebSocket 握手时以 Authorization: Bearer <token> 的形式提交凭据,app-server 会在 JSON-RPC initialize 之前强制执行身份验证。

优先使用 --ws-token-file,避免在命令行中传入原始持有者令牌。仅当客户端将原始高熵令牌保存在独立的本地密钥存储中时,才使用 --ws-token-sha256。哈希值仅用于验证,客户端仍需要原始令牌。

在 WebSocket 模式下,app-server 使用有界队列。入站请求队列已满时,服务器会拒绝新请求,并返回 JSON-RPC 错误代码 -32001 和消息 "Server overloaded; retry later."。客户端应采用指数退避并加入随机抖动后重试。

消息模式

请求包含 method、params 和 id。

请求示例使用 GPT-6.1 Sol,已登录的账号或工作空间需要有权访问该模型。如有需要,请使用 model/list 选择可用模型。

{ "method": "thread/start", "id": 10, "params": { "model": "gpt-6.1-sol" } }

响应会返回请求中的 id,并包含 result 或 error:

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

通知省略 id,只使用 method 和 params:

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

您可以通过 CLI 生成 TypeScript 模式或 JSON Schema 包。生成的文件与运行该命令时使用的 Codex 版本完全匹配:

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

快速入门

  1. 使用 codex app-server(默认 stdio 传输)、codex app-server --listen ws://127.0.0.1:4500(TCP WebSocket)或 codex app-server --listen unix://(默认 Unix 套接字)启动服务器。
  2. 通过所选传输方式连接客户端,先发送 initialize,再发送 initialized 通知。
  3. 启动线程并开始一个轮次,然后持续从当前传输流读取通知。

以下示例使用 stdio 传输:

启动 app-server 对话
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 === 0 && msg.result) {
    send({ method: "initialized", params: {} });
    send({
      method: "thread/start",
      id: 1,
      params: { model: "gpt-6.1-sol" },
    });
  }
  if (msg.method === "turn/completed") {
    if (msg.params?.turn?.status !== "completed") {
      console.error(msg.params?.turn?.error ?? "The turn did not complete.");
      process.exitCode = 1;
    }
    proc.stdin.end();
    rl.close();
  }
  if (msg.error) {
    console.error(msg.error);
    process.exitCode = 1;
    proc.stdin.end();
    rl.close();
  }
  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",
    },
  },
});
proc.on("error", (error) => {
  console.error(error);
  process.exitCode = 1;
  rl.close();
});
proc.on("exit", (code) => {
  if (code !== 0) process.exitCode = code ?? 1;
});

核心概念

  • 线程:用户与 Codex 智能体之间的一段对话。线程包含轮次。
  • 轮次:一次用户请求以及智能体随后执行的工作。轮次包含条目,并以流式方式提供增量更新。
  • 条目:一个输入或输出单元,例如用户消息、智能体消息、命令执行、文件更改或工具调用。

使用线程 API 创建、列出或归档对话。使用轮次 API 推进对话,并通过轮次通知实时获取进度。

生命周期概览

  • 每个连接初始化一次:建立传输连接后,立即发送包含客户端元数据的 initialize 请求,再发送 initialized。握手完成前,服务器会拒绝该连接上的其他请求。
  • 启动或恢复线程:调用 thread/start 创建对话,调用 thread/resume 继续已有对话,或调用 thread/fork 从已有历史派生具有新 ID 的线程。
  • 开始轮次:调用 turn/start,传入目标 threadId 和用户输入。可通过可选字段覆盖模型、工作目录和沙盒策略。
  • 引导进行中的轮次:调用 turn/steer 将用户输入追加到当前正在进行的轮次,无需创建新轮次。
  • 接收事件流:调用 turn/start 后,持续从标准输出读取通知,包括 thread/archived、thread/unarchived、item/started、item/completed、item/agentMessage/delta、工具进度和其他更新。
  • 结束轮次:模型完成工作或通过 turn/interrupt 取消轮次后,服务器会发送包含最终状态的 turn/completed 通知。

初始化

客户端必须在每个传输连接上先发送一次 initialize 请求,再发送 initialized 通知以确认初始化,然后才能在该连接上调用其他方法。初始化前发送的请求会收到 Not initialized 错误,在同一连接上重复调用 initialize 会返回 Already initialized。

服务器返回向上游服务提供的用户代理字符串,以及描述目标运行平台的 platformFamily 和 platformOs 值。请设置 clientInfo 以标识您的集成。

initialize.params.capabilities 还支持以下客户端能力:

  • optOutNotificationMethods:指定要在此连接上屏蔽的通知方法全名。仅支持精确匹配,不支持通配符或前缀。未知名称会被接受,但不生效。
  • requestAttestation:主动启用由服务器发起的 attestation/generate 请求。提供上游证明的桌面主机会返回一个不透明的 { "token": "..." } 值。
  • mcpServerOpenaiFormElicitation:允许下游 MCP 服务器发送 mcpServer/elicitation/request 的 OpenAI 扩展表单变体。

重要:请使用 clientInfo.name 标识您的客户端,以便合规日志平台识别。如果您正在开发供企业使用的新 Codex 集成,请联系 OpenAI,将其加入已知客户端列表。有关详细信息,请参阅 Codex 日志参考。

示例(来自 Codex VS Code 扩展程序):

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

屏蔽部分通知的示例:

{
  "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"]
    }
  }
}

启用实验性 API

部分 app-server 方法和字段需要显式启用 experimentalApi 能力才能使用。

  • 省略 capabilities(或将 experimentalApi 设为 false)即可只使用稳定 API。服务器会拒绝实验性方法和字段。
  • 将 capabilities.experimentalApi 设为 true 即可启用实验性方法和字段。
{
  "method": "initialize",
  "id": 1,
  "params": {
    "clientInfo": {
      "name": "my_client",
      "title": "My Client",
      "version": "0.1.0"
    },
    "capabilities": {
      "experimentalApi": true
    }
  }
}

如果客户端未启用此能力就发送实验性方法或字段,app-server 会拒绝请求并返回:

<descriptor> requires experimentalApi capability

API 概览

  • thread/start:创建新线程,发送 thread/started,并自动为当前连接订阅该线程的轮次和条目事件。
  • thread/resume:按 ID 重新打开已有线程,使后续 turn/start 调用将轮次追加到该线程。
  • thread/fork:复制已存储的历史,派生具有新 ID 的线程。传入 lastTurnId 可复制截至该轮次(含该轮次)的历史并排除后续轮次,也可传入 ephemeral: true 在内存中创建派生线程。服务器为新线程发送 thread/started,并在可用时在返回的线程中包含 forkedFromId。
  • thread/read:按 ID 读取已存储的线程元数据,无需恢复线程。使用 thread/turns/list 和 thread/items/list 加载历史。返回的 thread 对象包含运行时 status。
  • thread/list:分页读取已存储的线程及其运行时状态。请参阅分页和筛选。
  • thread/turns/list:分页读取已存储线程的轮次历史,无需恢复线程。itemsView 控制是否省略轮次条目、仅加载摘要或加载完整条目。
  • thread/items/list:分页读取持久化的线程条目,可将范围限定为单个 turnId。当前线程存储必须支持条目分页。
  • thread/loaded/list:列出当前已加载到内存中的线程 ID。
  • thread/name/set:为已加载的线程或已持久化的会话记录设置或更新用户可见的线程名称,并发送 thread/name/updated。
  • thread/goal/set:设置线程目标,并发送 thread/goal/updated。
  • thread/goal/get:读取线程的当前目标。
  • thread/goal/clear:清除线程目标,并发送 thread/goal/cleared。
  • thread/metadata/update:更新为线程保存的 Git 元数据。
  • thread/archive:将线程日志文件移入归档目录,并尝试归档由该线程衍生且尚未归档的后代线程日志。成功时返回 {},并为每个已归档线程发送 thread/archived。
  • thread/delete:永久删除已持久化的活动线程或归档线程及其衍生的后代线程。成功时返回 {},并为每个已删除线程发送 thread/deleted。
  • thread/unsubscribe:取消当前连接对线程轮次和条目事件的订阅。如果这是最后一个订阅方,且线程在宽限期内一直空闲且无人订阅,服务器会卸载线程,并发送 thread/closed。
  • thread/unarchive:将已归档的线程记录移回活动会话目录,返回恢复后的 thread,并发送 thread/unarchived。
  • thread/status/changed:已加载线程的运行时 status 发生变化时发送的通知。
  • thread/compact/start:触发线程对话历史压缩,立即返回 {},并通过 turn/* 和 item/* 通知实时报告进度。
  • thread/shellCommand:针对线程执行用户主动发起的 shell 命令。该命令在沙盒外以完全访问权限运行,不继承线程的沙盒策略。
  • thread/backgroundTerminals/clean:停止线程中所有正在运行的后台终端(实验性,需要 capabilities.experimentalApi)。
  • thread/backgroundTerminals/list:列出已加载线程中正在运行的后台终端(实验性,需要 capabilities.experimentalApi)。
  • thread/backgroundTerminals/terminate:按 app-server 的 processId 终止一个运行中的后台终端(实验性,需要 capabilities.experimentalApi)。
  • thread/revert:从使用分页历史的持久化线程中移除指定轮次及其后的所有轮次,返回更新后的元数据和历史游标,然后发送 thread/reverted。
  • turn/start:向线程添加用户输入或独立工具输出,并让 Codex 开始生成内容。响应包含初始 turn,后续事件以流式方式发送。对于 collaborationMode,settings.developer_instructions: null 表示“使用所选模式的内置指令”。
  • thread/inject_items:将原始 Responses API 条目追加到已加载线程中模型可见的历史,无需开始用户轮次。
  • turn/steer:将用户输入追加到线程当前正在进行的轮次,返回接收该输入的 turnId。
  • turn/interrupt:请求取消正在进行的轮次。成功时返回 {},轮次以 status: "interrupted" 结束。
  • review/start:启动 Codex 审查器对线程进行审查,发送 enteredReviewMode 和 exitedReviewMode 条目。
  • command/exec:在服务器沙盒内执行单条命令,无需启动线程或轮次。
  • command/exec/write:将 stdin 字节写入运行中的 command/exec 会话,或关闭 stdin。
  • command/exec/resize:调整运行中的 command/exec 会话的伪终端(PTY)大小。
  • command/exec/terminate:停止运行中的 command/exec 会话。
  • command/exec/outputDelta(通知):流式 command/exec 会话产生标准输出或标准错误数据块时发送,数据采用 Base64 编码。
  • process/spawn:在 Codex 沙盒外显式启动进程会话(实验性,需要 capabilities.experimentalApi)。
  • process/writeStdin:向运行中的 process/spawn 会话的标准输入写入字节,或关闭标准输入(实验性)。
  • process/resizePty:调整运行中进程会话的 PTY 大小(实验性)。
  • process/kill:终止运行中的进程会话(实验性)。
  • process/outputDelta 和 process/exited(通知):分别报告流式进程输出和进程退出状态(实验性)。
  • model/list:列出可用模型(设置 includeHidden: true 可包含标记为 hidden: true 的条目),以及推理强度选项、可选的 upgrade 和 inputModalities。
  • modelProvider/capabilities/read:读取指定模型与提供商组合的能力范围。
  • experimentalFeature/list:按游标分页列出功能开关及其生命周期阶段元数据。
  • experimentalFeature/enablement/set:局部更新内存中受支持功能键的运行时设置,例如 apps 和 plugins。
  • environment/info:实验性方法,连接已配置的执行环境并返回其 shell 和默认工作目录。
  • permissionProfile/list:按游标分页列出测试版的权限配置方案,并指明当前生效的要求是否允许使用各方案。
  • collaborationMode/list:列出协作模式预设(实验性,不分页)。
  • skills/list:列出一个或多个 cwd 对应的技能(支持 forceReload 和可选的 perCwdExtraUserRoots)。
  • skills/extraRoots/set:替换用于发现独立技能的进程级额外根目录设置,不将其持久化。
  • skills/changed(通知):受监视的本地技能文件更改时发送。
  • hooks/list:列出在一个或多个 cwd 中发现的生命周期钩子。
  • marketplace/add:添加远程插件市场,并将其保存到用户的市场配置中。
  • marketplace/remove:移除已配置的市场,并在其安装根目录存在时一并移除。
  • marketplace/upgrade:刷新已配置的 Git 市场,省略市场名称时刷新所有已配置的 Git 市场。
  • plugin/list:开发中。列出已发现的插件市场及插件状态,包括安装和身份验证策略元数据、市场加载错误、精选插件 ID,以及本地、Git、软件包注册表或远程插件来源的元数据。摘要可包含远程 version、本地 localVersion、结构化的浅色和深色图标,以及 installPolicySource。对于当前的远程条目,后者可以是 null、WORKSPACE_SETTING 或 IMPLICIT_CANONICAL_APP。暂勿在生产客户端中调用此方法。
  • plugin/read:开发中。通过市场路径或远程市场名称,加上插件名称,读取单个插件。结果包括随附的技能、应用、MCP 服务器名称,以及远程目录提供的插件 shareUrl(如有)。暂勿在生产客户端中调用此方法。
  • plugin/install:开发中。通过市场路径或远程市场名称安装插件。暂勿在生产客户端中调用此方法。
  • plugin/uninstall:开发中。卸载已安装的插件。暂勿在生产客户端中调用此方法。
  • plugin/skill/read:按远程市场、插件 ID 和技能名称,按需读取远程插件技能的 Markdown 内容。
  • app/installed:读取已安装应用的运行时状态,包括各应用实际是否已启用以及是否可调用。
  • app/list:分页列出可用应用(连接器),并提供访问权限和启用状态元数据。
  • app/read:获取指定应用 ID 的元数据,以及可选的仅供展示的工具摘要。
  • skills/config/write:按路径启用或禁用技能。
  • mcpServer/oauth/login:为已配置的 MCP 服务器启动 OAuth 登录。打开返回的 HTTP 或 HTTPS authorizationUrl,并根据 loginId 匹配相应的 mcpServer/oauthLogin/completed 通知。
  • tool/requestUserInput:为工具调用向用户提出 1 至 3 个简短问题(实验性)。问题可以设置 isOther 以提供自由填写的选项。
  • mcpServer/elicitation/request(服务器请求):请客户端提供结构化表单输入,或确认 MCP 服务器请求的 URL 流程。
  • item/permissions/requestApproval(服务器请求):请客户端从内置 request_permissions 工具所请求的网络或文件系统权限中选择要授予的权限。
  • config/mcpServer/reload:从磁盘重新加载 MCP 服务器配置,并将已加载线程的刷新操作加入队列。
  • mcpServerStatus/list:列出 MCP 服务器、工具、资源和身份验证状态(按游标和数量上限分页)。使用 detail: "full" 获取完整数据,或使用 detail: "toolsAndAuthOnly" 省略资源。两种模式都会返回服务器声明的 serverCapabilities,成功初始化前该值为 null。传入 serverName 可查询单台服务器。传入 threadId 时,请求会复用该线程的 MCP 连接。
  • mcpServer/resource/read:通过已初始化的 MCP 服务器读取单个 MCP 资源。
  • mcpServer/tool/call:调用线程所配置的 MCP 服务器上的工具。
  • mcpServer/startupStatus/updated(通知):已加载线程所配置的 MCP 服务器启动状态发生变化时发送。
  • windowsSandbox/readiness:检查 Windows 沙盒是否就绪。如果返回 updateRequired,请调用 windowsSandbox/setupStart 并等待 windowsSandbox/setupCompleted。
  • feedback/upload:提交反馈报告,包含分类和对话 ID,可附上原因、日志及 extraLogFiles 附件。
  • config/read:解析各配置层后,获取磁盘上实际生效的配置。
  • externalAgentConfig/detect:使用 includeHome 和可选的 cwds 检测可迁移的外部智能体资源。每个检测到的条目都包含 cwd(主目录对应 null)。
  • externalAgentConfig/import:显式传入 migrationItems,为各条目指定 cwd(主目录对应 null),以导入选定的外部智能体资源。支持配置、技能、AGENTS.md、插件、MCP 服务器配置、子智能体、钩子、命令和会话。导入列表非空时,服务器会随导入进度发送 externalAgentConfig/import/progress 和 externalAgentConfig/import/completed。插件和会话可异步完成导入。
  • config/value/write:将单个配置键值对写入磁盘上的用户 config.toml。
  • config/batchWrite:以原子操作将配置更改写入磁盘上的用户 config.toml。
  • configRequirements/read:从 requirements.toml、MDM 或两者获取要求,包括允许列表和固定的 featureRequirements。启用 experimentalApi 的客户端还可以读取托管网络要求。
  • fs/readFile、fs/writeFile、fs/createDirectory、fs/getMetadata、fs/readDirectory、fs/remove、fs/copy、fs/watch、fs/unwatch 和 fs/changed(通知):通过 app-server v2 文件系统 API 操作绝对路径。

插件摘要包含联合类型 source。本地插件返回 { "type": "local", "path": ... },来自 Git 市场的条目返回 { "type": "git", "url": ..., "path": ..., "refName": ..., "sha": ... },来自软件包注册表的条目返回 { "type": "npm", "package": ..., "version": ..., "registry": ... },远程目录条目返回 { "type": "remote" }。对于仅存在于远程目录中的条目,PluginMarketplaceEntry.path 可以是 null。读取或安装这些插件时,请传入 remoteMarketplaceName 代替 marketplacePath。

模型

列出模型(model/list)

调用 model/list,在模型选择器中显示可用模型及其支持的推理强度。传入 modelProvider 可列出指定的已配置提供商所提供的模型。省略此字段时,服务器使用启动时选定的默认提供商。

下面的响应展示了数据结构。可用模型、推理强度及默认值取决于客户端和账号,请使用实际返回的值,避免将示例值硬编码到客户端中。

{ "method": "model/list", "id": 6, "params": { "limit": 20, "includeHidden": false } }
{ "id": 6, "result": {
  "data": [{
    "id": "gpt-6.1-sol",
    "model": "gpt-6.1-sol",
    "displayName": "GPT-6.1 Sol",
    "hidden": false,
    "defaultReasoningEffort": "medium",
    "supportedReasoningEfforts": [{
      "reasoningEffort": "medium",
      "description": "Balances speed and reasoning depth for everyday tasks"
    }],
    "inputModalities": ["text", "image"],
    "supportsPersonality": false,
    "isDefault": true
  }],
  "nextCursor": null
} }

每个模型条目可以包含以下字段:

  • supportedReasoningEfforts:模型支持的推理强度选项。
  • defaultReasoningEffort:建议客户端使用的默认推理强度。
  • upgrade:可选的推荐升级模型 ID,供客户端显示迁移提示。
  • upgradeInfo:可选的升级元数据,供客户端显示迁移提示。
  • hidden:是否从默认选择器列表中隐藏该模型。
  • inputModalities:模型支持的输入类型,例如 text、image。
  • supportsPersonality:已弃用的兼容性字段,始终为 false。模型已不再支持选择个性。
  • isDefault:该模型是否为推荐的默认模型。

如果 modelProvider 指定了未知的提供商,服务器会返回 -32600,其中 data.type 为 modelProviderNotConfigured。如果所选提供商不再满足托管要求,model/list 会返回 -32600,并要求客户端重启 Codex。

默认情况下,model/list 仅返回选择器中可见的模型。设置 includeHidden: true 可获取完整列表,然后在客户端根据 hidden 筛选。

如果缺少 inputModalities(较旧的模型目录),请将其视为 ["text", "image"],以保持向后兼容。

列出实验性功能(experimentalFeature/list)

使用此端点查询功能开关及其元数据和生命周期阶段:

{ "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 可以是 beta、underDevelopment、stable、deprecated 或 removed。对于不处于 beta 阶段的功能开关,displayName、description 和 announcement 可以是 null。

查看执行环境(实验性)

在已配置的远程环境中开始工作之前,使用 environment/info 查看该环境。此方法要求设置 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 可以是 null。有值时,它是采用环境原生路径语法的规范 file: URI。环境 ID 未知、连接失败或协议出错时,会返回请求错误。

线程

  • thread/read 读取已存储的线程元数据,无需订阅线程事件。
  • thread/turns/list 分页读取已存储线程的轮次历史,无需恢复线程。使用 itemsView 选择省略轮次条目、仅加载摘要或加载完整条目。
  • thread/items/list 分页读取持久化的线程条目,也可将范围限定为单个轮次。
  • thread/list 分页读取已存储的线程。使用 sectionId 列出指定分组中的线程,或使用 excludedThreadIds 排除界面上已显示的线程。
  • thread/loaded/list 返回当前位于内存中的线程 ID。
  • thread/archive 将线程持久化的 JSONL 日志移入归档目录,并尝试归档由该线程衍生且尚未归档的后代线程日志。
  • thread/delete 永久删除已持久化的活动线程或归档线程及其衍生的后代线程。
  • thread/metadata/update 更新为线程保存的 gitInfo。
  • thread/unsubscribe 取消当前连接对已加载线程的订阅,并可能在空闲宽限期结束后触发 thread/closed。
  • thread/unarchive 将已归档的线程记录移回活动会话目录。
  • thread/compact/start 触发压缩,并立即返回 {}。
  • thread/revert 从使用分页历史的持久化线程中移除指定轮次及其后的所有轮次。此操作不会更改本地文件。
  • thread/inject_items 将原始 Responses API 条目追加到已加载线程中模型可见的历史,无需开始用户轮次。

启动或恢复线程

需要开始新的 Codex 对话时,请启动新线程。

{ "method": "thread/start", "id": 10, "params": {
"model": "gpt-6.1-sol",
"cwd": "/Users/me/project",
"approvalPolicy": "never",
"sandbox": "workspace-write",
"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 为可选字段。如果您希望 app-server 用集成服务的名称标记线程级指标,请设置此字段。

thread/start、thread/resume 和 thread/fork 返回 instructionSources,即已加载指令文件的路径数组。每个路径都采用其来源环境的原生绝对路径语法,包括来自远程环境的路径。

新建的持久化本地线程默认使用分页历史。使用 thread/turns/list 和 thread/items/list 加载历史。显式将 historyMode 设为 "legacy" 或 "paginated" 是 thread/start 的实验性功能,需要设置 capabilities.experimentalApi = true。

启用了 capabilities.experimentalApi 的测试版客户端可以在 permissions 中传入命名权限配置方案的 ID,以替代旧版 sandbox 字段。不要同时发送 permissions 和 sandbox。使用 permissionProfile/list 并传入项目的 cwd,即可查询可用方案以及托管要求是否允许使用各方案。

thread.sessionId 标识当前活动会话树的根。根线程使用自己的线程 ID 作为会话 ID,派生线程沿用来源根线程的会话 ID。客户端应从 thread.sessionId 读取会话 ID,避免根据线程 ID 推算。

要继续已存储的会话,请调用 thread/resume 并传入先前记录的 thread.id。传入 excludeTurns: true 可返回线程元数据和实时会话状态,然后使用分页方法加载历史:

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

对于分页线程,thread/resume 和 thread/fork 返回完整历史的方式已弃用,并会触发 deprecationNotice。这两个方法均接受 excludeTurns: true,无需启用实验性 API。thread/resume 响应还可能返回 turnsBackwardsCursor 和 itemsBackwardsCursor。请将每个游标分别传给对应的分页方法,并设置 sortDirection: "desc"。第一页包含游标对应的锚点。

恢复线程本身不会更新 thread.updatedAt(或会话记录文件的修改时间)。开始轮次时才会更新时间戳。

如果您在配置中将某个已启用的 MCP 服务器标记为 required,而该服务器初始化失败,thread/start 和 thread/resume 都会失败。

dynamicTools 是 thread/start 的实验性字段(需要设置 capabilities.experimentalApi = true)。Codex 会将这些动态工具持久化到线程记录的元数据中。如果您在 thread/resume 时未提供新的动态工具,Codex 会恢复已保存的工具。

如果配置的模型提供商与线程中保存的提供商不同,调用 thread/resume 或提交新输入都会返回 -32600,其中 data.type 为 modelProviderMismatch。要显示线程历史,请分页读取线程轮次,使用的方法是 thread/turns/list。要继续原线程,请切换回已保存的提供商。也可以调用 thread/fork,使用当前提供商从已有历史派生新线程。

如果恢复线程时使用的模型与会话记录中的模型不同,Codex 会发出警告,并在下一轮次应用一次模型切换指令。

管理线程目标

使用 thread/goal/set、thread/goal/get 和 thread/goal/clear 管理持久化的目标状态。TUI 中的 /goal 显示的就是同一状态。

{ "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
  }
} }

目标描述不能为空,最多可包含 4,000 个字符。提供新的描述会替换目标并重置用量统计。提供当前尚未结束的目标描述,或省略 objective,则会更新状态或 Token 预算,同时保留用量历史。

要从已存储的会话派生新线程,请调用 thread/fork 并传入 thread.id。这会创建新的线程 ID,并为其发送 thread/started 通知。传入 lastTurnId 可复制截至指定轮次(含该轮次)的历史,并排除后续轮次:

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

如果 lastTurnId 对应的轮次仍在进行,app-server 会拒绝请求。如果省略此字段,而源线程的当前轮次尚未结束,派生线程会记录一个中断标记,避免留下未标记的不完整轮次。

传入 ephemeral: true 可在内存中创建派生线程,该线程不会出现在已存储线程的列表中:

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

从分页线程派生临时线程时,必须设置 excludeTurns: true。

设置用户可见的线程标题后,app-server 会在 thread/list、thread/read、thread/resume 和 thread/unarchive 的响应中填充 thread.name。在设置标题之前,thread/start 和 thread/fork 可能省略 name(或返回 null)。

读取已存储的线程(无需恢复)

如果您需要已存储的线程数据,但无需恢复线程或订阅其事件,请使用 thread/read。

  • includeTurns:设为 false 或省略时,仅返回线程摘要。设为 true 会加载完整历史。对于分页线程,此方式已弃用,并会触发 deprecationNotice。请改用分页方法。
  • 返回的 thread 对象包含运行时 status(notLoaded、idle、systemError 或 active,最后一种状态附带 activeFlags)。
{ "method": "thread/read", "id": 19, "params": { "threadId": "thr_123" } }
{ "id": 19, "result": { "thread": { "id": "thr_123", "name": "Bug bash notes", "ephemeral": false, "status": { "type": "notLoaded" }, "turns": [] } } }

与 thread/resume 不同,thread/read 不会将线程加载到内存,也不会发送 thread/started。

列出线程轮次

使用 thread/turns/list 分页读取已存储线程的轮次历史,无需恢复线程。结果默认按从新到旧的顺序排列,客户端可使用 nextCursor 获取较早的轮次。响应还包含 backwardsCursor。将其作为 cursor 传入,并将 sortDirection 设为相反方向,即可反向翻页。结果会再次包含锚点轮次,以便获取其更新。

itemsView 控制响应中轮次条目的详细程度:

  • notLoaded 省略条目。
  • summary 返回条目摘要,为省略此字段时的默认值。
  • full 返回完整条目数据。
{ "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 分页读取持久化的条目,无需恢复线程。传入 turnId 可将结果限定为单个轮次,省略时则分页读取整个线程的条目。默认按从旧到新的顺序返回结果(sortDirection: "asc")。当前线程存储必须支持条目分页,否则服务器会返回方法不受支持的错误。

传入上一次响应中的不透明 nextCursor 即可继续翻页。要从某个已知条目之后开始读取,请传入条目锚点和非空的 turnId:

{ "method": "thread/items/list", "id": 21, "params": {
  "threadId": "thr_123",
  "turnId": "turn_456",
  "cursor": { "type": "item", "itemId": "item_123" },
  "sortDirection": "asc",
  "limit": 50
} }
{ "id": 21, "result": {
  "data": [],
  "nextCursor": null,
  "backwardsCursor": null
} }

结果不包含锚点条目本身。升序返回较新的条目,降序返回较旧的条目。锚点条目必须属于所请求轮次的可见历史。如果缺少 turnId、条目 ID 为空,或条目未知或超出范围,会返回参数无效错误(-32602)。使用返回的字符串 nextCursor 继续翻页。每个结果条目包含 turnId、item,并可能包含记录的开始和完成时间戳。

列出线程(支持分页和筛选)

使用 thread/list 可构建历史记录界面。结果默认按 createdAt 从新到旧排列,先筛选再分页。以下参数可组合使用:

  • cursor:上一次响应中的不透明字符串,获取第一页时省略。
  • limit:未设置时,服务器使用默认的每页条数。
  • sortKey:created_at(默认)、updated_at、recency_at 或 section_position。使用 section_position 时,必须提供值不为 null 的 sectionId。
  • sortDirection:asc 或 desc。省略 sortDirection 时,section_position 按升序排列,基于时间的键按降序排列。
  • sectionId:传入分组 ID 可列出该组中的线程,传入 null 则列出未分组的线程。省略此字段时,结果包含所有分组中的线程和未分组的线程。
  • excludedThreadIds:最多可指定 100 个要排除的线程 ID,重复的 ID 也计入这 100 个名额。服务器先排除匹配的线程,再应用每页数量上限。每次使用游标翻页时,都应发送相同的排除列表。
  • modelProviders:仅返回指定提供商的结果。传入 [] 可包含所有提供商。如果省略此字段或传入 null,服务器默认使用已配置的提供商,但按线程关系筛选时会包含所有提供商。
  • sourceKinds:仅返回指定来源的线程。省略或设为 [] 时,服务器默认仅包含交互式来源,即 cli 和 vscode。
  • archived:为 true 时仅列出已归档线程,为 false 或省略时列出未归档线程(默认)。
  • cwd:仅返回会话当前工作目录与此路径或数组中某个路径完全匹配的线程。相对路径以 app-server 进程的工作目录为基准解析。
  • useStateDbOnly:为 true 时直接返回状态数据库中的结果,不扫描 JSONL 线程日志来修复元数据。省略或传入 false 时采用默认的扫描和修复行为。
  • searchTerm:仅返回提取出的标题包含指定文本片段的线程,匹配时区分大小写。
  • parentThreadId:仅返回指定父线程的直接子线程。这是实验性筛选条件,需要设置 capabilities.experimentalApi = true。
  • ancestorThreadId:仅返回指定线程衍生的后代线程,不限层级。这是实验性筛选条件,需要设置 capabilities.experimentalApi = true。不要与 parentThreadId 一起使用。

sourceKinds 接受以下值:

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

示例:

{ "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, "section": { "id": "01984de2-8f74-7c91-a3b2-5c5e937cf318", "name": "Pinned", "appearance": null }, "modelProvider": "openai", "createdAt": 1730831111, "updatedAt": 1730831111, "name": "TUI prototype", "status": { "type": "notLoaded" } },
    { "id": "thr_b", "preview": "Fix tests", "ephemeral": false, "section": null, "modelProvider": "openai", "createdAt": 1730750000, "updatedAt": 1730750000, "status": { "type": "notLoaded" } }
  ],
  "nextCursor": "opaque-token-or-null"
} }

nextCursor 为 null 表示已到达最后一页。

将线程归入分组

使用 threadSection/create 创建命名分组,再将返回的 section.id 传给 thread/section/move。传入 beforeThreadId 可将线程插入到组内指定线程之前,省略时则追加到组末尾。传入 sectionId: null 可将线程移出当前分组。使用 threadSection/list、threadSection/update 和 threadSection/delete 分别分页查看、重命名和删除自定义分组。要置顶线程,请将其移动到 threadSection/list 返回的内置置顶分组。

管理线程附件

使用附件可将 Pull Request 等资源关联到已存储的线程。管理这些引用时,无需恢复线程。

  • thread/attachment/add 接受 threadId、attachmentType、identityKey 和 JSON 格式的 payload。如果再次向同一线程添加类型和键均相同的附件,会返回已有附件。
  • thread/attachment/list 分页列出线程附件。要查找引用某个资源的线程,请调用 thread/attachmentOwner/list 并传入该资源的 attachmentType 和 identityKey。
  • thread/attachment/remove 接受 threadId、attachmentType 和 identityKey。移除附件后,原资源仍然可用。
  • thread/attachment/updated 在关联发生变化时报告 created 或 deleted 操作。

更新已存储的线程元数据

使用 thread/metadata/update 局部更新已存储的线程元数据,无需恢复线程。在 gitInfo 中传入要更新的 Git 字段。省略字段可保留原值,传入 null 可清除其值。

{ "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/changed。通知包含 threadId 和新的 status。

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

列出已加载的线程

thread/loaded/list 返回当前已加载到内存中的线程 ID。

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

取消订阅已加载的线程

thread/unsubscribe 取消当前连接对线程的订阅。响应状态为以下值之一:

  • unsubscribed:当前连接此前已订阅,现已取消订阅。
  • notSubscribed:当前连接此前未订阅该线程。
  • notLoaded:线程未加载。

最后一个订阅方离开后,app-server 默认在线程连续空闲 60 秒后将其卸载。可通过 thread_unload_delay_secs 调整这一时长。卸载时,app-server 会发送 thread/status/changed 通知,将状态报告为 notLoaded,并发送 thread/closed 通知。

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

如果线程随后超过宽限期:

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

归档线程

使用 thread/archive 将持久化的线程日志(以 JSONL 文件形式存储在磁盘上)移入已归档会话目录。归档线程时,服务器还会尝试归档由该线程衍生且尚未归档的后代线程。

{ "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" } }

后续调用 thread/list 时,只有传入 archived: true 才会列出已归档线程。服务器会为每个实际归档的线程发送一条 thread/archived 通知。如果某个后代线程无法归档,请求仍可能成功,但不会为该后代线程发送归档通知。

删除线程

使用 thread/delete 永久删除已持久化的活动线程或归档线程及其衍生的后代线程。服务器会先移除现有的会话记录文件及关联元数据,再返回成功响应。缺失的会话记录文件视为已删除。临时根线程不能删除。

{ "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/unarchive 将已归档的线程记录移回活动会话目录。

{ "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/compact/start 手动触发线程历史压缩。请求立即返回 {}。

app-server 通过标准的 turn/* 和 item/* 通知在同一 threadId 上报告进度,包括 contextCompaction 条目的生命周期事件(先发送 item/started,再发送 item/completed)。

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

在线程中运行 shell 命令

对于用户在线程中主动发起的 shell 命令,请使用 thread/shellCommand。请求立即返回 {},执行进度则通过标准的 turn/* 和 item/* 通知实时发送。

此 API 在沙盒外以完全访问权限运行,不继承线程的沙盒策略。客户端应仅对用户明确发起的命令开放此 API。

如果线程已有正在进行的轮次,该命令会作为该轮次的辅助操作运行,格式化后的输出会注入轮次的消息流。如果线程处于空闲状态,app-server 会为该 shell 命令启动独立轮次。

设置 timeoutMs 可限制执行时间,单位为毫秒。省略此字段或传入 null 时,默认时限为一小时。0 表示立即超时,负值会被拒绝。无论时限如何设置,RPC 请求都会立即得到确认。

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

清理后台终端

使用 thread/backgroundTerminals/clean 停止与线程关联的所有正在运行的后台终端。此方法为实验性方法,需要设置 capabilities.experimentalApi = true。

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

使用 thread/backgroundTerminals/list 查看已加载线程中正在运行的后台终端。请求支持通过标准的 cursor 和 limit 参数分页,返回的 processId 为 app-server 使用的进程 ID。此方法为实验性方法,需要设置 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 并传入该 processId 可停止单个后台终端。此方法为实验性方法,需要设置 capabilities.experimentalApi = true:

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

回退线程历史

使用 thread/revert 从使用分页历史的持久化线程中移除 beforeTurnId 指定的轮次及其后的所有轮次。此操作不会撤销本地文件更改。如果线程尚未加载,请先恢复线程。此方法不支持临时线程或使用旧版历史格式的线程。

{ "method": "thread/revert", "id": 30, "params": { "threadId": "thr_b", "beforeTurnId": "turn_456" } }
{ "id": 30, "result": {
  "thread": { "id": "thr_b", "ephemeral": false, "turns": [] },
  "turnsBackwardsCursor": "retained-turn-cursor-or-null",
  "itemsBackwardsCursor": "retained-item-cursor-or-null"
} }
{ "method": "thread/reverted", "params": { "threadId": "thr_b" } }

返回的 thread.turns 始终为空。将返回的游标传给 thread/turns/list 或 thread/items/list,并设置 sortDirection: "desc",即可加载保留的历史,包括游标对应的锚点。

thread/rollback 已移除,调用时会返回未知方法错误。以前保存的线程中已有的回滚标记仍可读取。

轮次

input 字段接受条目列表:

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

您可以按轮次覆盖配置设置(模型、推理强度、cwd、沙盒策略、摘要)。指定后,这些设置将成为同一线程后续轮次的默认值。outputSchema 仅适用于当前轮次。当 sandboxPolicy.type = "externalSandbox" 时,请将 networkAccess 设为 restricted 或 enabled。对于 workspaceWrite,networkAccess 仍为布尔值。

对于 turn/start.collaborationMode,settings.developer_instructions: null 表示“使用所选模式的内置指令”,不会清除模式指令。

沙盒读取权限(ReadOnlyAccess)

sandboxPolicy 支持显式控制读取权限:

  • readOnly:可选的 access(默认为 { "type": "fullAccess" },也可限制可读根目录)。
  • workspaceWrite:可选的 readOnlyAccess(默认为 { "type": "fullAccess" },也可限制可读根目录)。

受限读取权限的结构:

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

在 macOS 上,includePlatformDefaults: true 会为读取权限受限的会话追加一组经过筛选的平台默认 Seatbelt 策略。这样可以提高工具兼容性,同时避免开放整个 /System 的读取权限。

示例:

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

开始轮次

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

设置 serviceTierForTurn 可单独指定新轮次的服务层级。使用 "default" 表示标准速度,省略此字段则继承线程的服务层级。要同时更改本轮次和后续轮次的服务层级,请设置 serviceTier。

要使用客户端运行工具所得的输出开始轮次,请传入 toolOutput,其中包含非空的 name、可选的 namespace 和 output(字符串或内容条目数组)。将 input 设为空数组,toolOutput 不能与非空用户输入一起使用。

{
  "method": "turn/start",
  "id": 31,
  "params": {
    "threadId": "thr_123",
    "input": [],
    "toolOutput": {
      "name": "run_tests",
      "namespace": null,
      "output": "All 42 tests passed."
    }
  }
}

该输出在对话中保留为工具输出,并以 functionCallOutput 条目出现在通知和持久化历史中。如果已有常规轮次正在进行,Codex 会将输出加入该轮次的队列。

向线程注入条目

使用 thread/inject_items 将预先构建的 Responses API 条目追加到已加载线程的提示词历史中,无需开始用户轮次。这些条目会持久化到会话记录中,并包含在后续模型请求中。

{ "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": {} }

引导进行中的轮次

使用 turn/steer 将更多用户输入追加到当前正在进行的轮次。

  • 请提供 expectedTurnId,其值必须与当前轮次 ID 匹配。
  • 如果线程没有正在进行的轮次,请求会失败。
  • turn/steer 不会发送新的 turn/started 通知。
  • turn/steer 不接受轮次级配置覆盖(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" } }

开始轮次并调用技能

要显式调用技能,请在文本输入中包含 $<skill-name>,并同时添加 skill 输入条目。

{ "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 } } }

中断轮次

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

成功时,轮次以 status: "interrupted" 结束。

审查

review/start 启动 Codex 审查器对线程进行审查,并以流式方式发送审查条目。支持的审查目标包括:

  • uncommittedChanges
  • baseBranch(与指定分支比较差异)
  • commit(审查特定提交)
  • custom(自由编写审查指令)

review/start 在指定线程上运行审查。可以省略 delivery 或传入 "inline"。要单独运行审查,可使用 thread/fork 派生包含现有历史的线程,或使用 thread/start 创建没有历史的新线程。然后调用 review/start 并传入新线程的 ID。

请求和响应示例:

{ "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"
} }

Codex 会照常发送 turn/started 通知,随后发送 item/started,其中包含 enteredReviewMode 条目:

{
  "method": "item/started",
  "params": {
    "item": {
      "type": "enteredReviewMode",
      "id": "turn_900",
      "review": "current changes"
    }
  }
}

审查器完成工作时,服务器会发送 item/started 和 item/completed,其中包含带有最终审查文本的 exitedReviewMode 条目:

{
  "method": "item/completed",
  "params": {
    "item": {
      "type": "exitedReviewMode",
      "id": "turn_900",
      "review": "Looks solid overall..."
    }
  }
}

使用此通知在客户端中显示审查结果。

进程执行

process/* 是用于显式控制进程的实验性 API。它需要设置 capabilities.experimentalApi = true,并在 Codex 沙盒外运行。仅当客户端明确提供不受沙盒限制的本地进程控制功能时,才使用此 API。

使用 process/spawn 启动进程并提供 processHandle,然后使用该句柄发送写入标准输入、调整终端大小和终止进程的请求。进程输出通过 process/outputDelta 通知实时发送,完成状态通过 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 或两者,以发送输入或关闭标准输入。使用 process/resizePty 处理 PTY 大小调整事件,使用 process/kill 终止运行中的进程。

命令执行

command/exec 在服务器沙盒内执行单条命令(argv 数组),无需创建线程。

{ "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": "" } }

如果服务器进程已在沙盒中运行,并且您希望 Codex 跳过自身的沙盒限制,请使用 sandboxPolicy.type = "externalSandbox"。在外部沙盒模式下,将 networkAccess 设为 restricted(默认)或 enabled。对于 readOnly 和 workspaceWrite,请使用上文所示的可选 access / readOnlyAccess 结构。

注意事项:

  • 服务器会拒绝空的 command 数组。
  • sandboxPolicy 接受与 turn/start 相同的结构(例如 dangerFullAccess、readOnly、workspaceWrite、externalSandbox)。
  • 省略 timeoutMs 时,使用服务器默认值。
  • 对于使用 PTY 的会话,请设置 tty: true。如果计划继续操作该会话,请使用 processId 调用 command/exec/write、command/exec/resize 或 command/exec/terminate。
  • 设置 streamStdoutStderr: true 可在命令运行期间接收 command/exec/outputDelta 通知。

读取管理员要求(configRequirements/read)

使用 configRequirements/read 查看从 requirements.toml、MDM 或两者加载的实际生效的管理员要求。

{ "method": "configRequirements/read", "id": 52, "params": {} }
{ "id": 52, "result": {
  "requirements": {
    "allowedApprovalPolicies": ["on-request", "never"],
    "allowedSandboxModes": ["read-only", "workspace-write"],
    "featureRequirements": {
      "unified_exec": false
    }
  }
} }

未配置任何要求时,result.requirements 为 null。如果 result.supportsIndependentSpeedModes 为 true,fast_mode 和 ultrafast_mode 的要求分别生效。旧版服务器省略此字段,对两种模式都使用 fast_mode 的要求。有关支持的键和值,请参阅 requirements.toml 参考。

设置 Windows 沙盒(windowsSandbox/setupStart)

提示用户进行设置前,请先调用 windowsSandbox/readiness。MXC 和已配置的旧版沙盒都可以返回 ready。如果旧版沙盒返回 updateRequired,请调用 windowsSandbox/setupStart 异步启动设置流程。如果 Windows 沙盒已禁用,或主机运行其他操作系统,就绪检查会返回 notConfigured。

{ "method": "windowsSandbox/setupStart", "id": 53, "params": { "mode": "elevated" } }
{ "id": 53, "result": { "started": true } }

app-server 会在后台启动设置流程,并在完成后发送通知:

{
  "method": "windowsSandbox/setupCompleted",
  "params": { "mode": "elevated", "success": true, "error": null }
}

模式:

  • elevated:运行使用提升权限的 Windows 沙盒设置流程。
  • unelevated:运行旧版设置和预检流程。

文件系统

v2 文件系统 API 使用绝对路径。如果客户端需要在文件或目录发生变化后将相关界面状态标记为失效,请使用 fs/watch。

{ "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": {} }

监视文件时,服务器会针对该文件路径发送 fs/changed,包括通过替换或重命名操作产生的更新。

事件

服务器通过事件通知流报告线程、轮次以及其中条目的生命周期。启动或恢复线程后,请持续从当前传输流读取 thread/started、thread/archived、thread/unarchived、thread/closed、thread/status/changed、turn/*、item/* 和 serverRequest/resolved 通知。

屏蔽通知

客户端可以在 initialize.params.capabilities.optOutNotificationMethods 中发送完整的方法名称,针对每个连接屏蔽特定通知。

  • 仅支持精确匹配:item/agentMessage/delta 只屏蔽该方法。
  • 未知方法名称会被忽略。
  • 适用于当前的 thread/*、turn/*、item/* 及相关 v2 通知。
  • 不适用于请求、响应或错误。

文件模糊搜索事件(实验性)

文件模糊搜索会话 API 会按查询发送通知:

  • fuzzyFileSearch/sessionUpdated:发送 { sessionId, query, files },包含当前查询的匹配结果。
  • fuzzyFileSearch/sessionCompleted:该查询的索引构建和匹配完成后,发送 { sessionId }。

警告事件

  • configWarning:发送 { summary, details?, path?, range? },报告可恢复的配置或初始化问题。
  • warning:发送 { threadId?, message },报告非致命的运行时警告。

Windows 沙盒设置事件

  • windowsSandbox/setupCompleted:发送 { mode, success, error },表示 windowsSandbox/setupStart 请求已完成。

轮次事件

  • turn/started:发送 { turn },包含轮次 ID、空的 items 和 status: "inProgress"。
  • turn/completed:发送 { turn },其中 turn.status 为 completed、interrupted 或 failed。失败时附带 { error: { message, codexErrorInfo?, additionalDetails? } }。
  • turn/diff/updated:发送 { threadId, turnId, diff },包含汇总本轮次所有文件更改的最新统一差异。
  • turn/plan/updated:智能体每次分享或更改计划时发送 { turnId, explanation?, plan }。每个 plan 条目的结构为 { step, status },其中 status 为 pending、inProgress 或 completed。
  • hook/started 和 hook/completed:分别在同步生命周期钩子开始运行和最终运行摘要可用时发送 { threadId, turnId?, run }。异步钩子不会触发这些通知。
  • model/safetyBuffering/updated:响应进入临时安全缓冲阶段时发送 { threadId, turnId, model, useCases, reasons, showBufferingUi, fasterModel }。
  • model/rerouted:服务将请求路由到其他模型时发送 { threadId, turnId, fromModel, toModel, reason }。
  • model/verification:服务要求进一步验证账号时发送 { threadId, turnId, verifications }。
  • thread/tokenUsage/updated:报告当前线程的用量更新。

即使正在发送条目事件,turn/diff/updated 和 turn/plan/updated 当前也会包含空的 items 数组。轮次条目以 item/* 通知为准。

条目

ThreadItem 是轮次响应和 item/* 通知中携带的带标签联合类型。常见条目类型包括:

  • userMessage:{id, content},其中 content 是用户输入列表(text、image 或 localImage)。
  • functionCallOutput:{id, name, namespace, output},表示通过 turn/start.toolOutput 提供的独立工具输出。namespace 可以是 null。
  • agentMessage:{id, text, phase?},包含截至当前累积的智能体回复。若存在 phase,其值采用 Responses API 的传输格式(commentary、partial_answer、final_answer)。partial_answer 是已确定的回答文本,其后可能还有其他输出或工具调用。
  • plan:{id, text},包含计划模式下提出的计划文本。请以 item/completed 发送的最终 plan 条目为准。
  • reasoning:{id, summary, content},其中 summary 保存流式推理摘要,content 保存原始推理块。
  • commandExecution:{id, command, cwd, status, commandActions, aggregatedOutput?, exitCode?, durationMs?}。
  • fileChange:{id, changes, status},描述拟议的编辑。changes 列表的条目结构为 {path, kind, diff}。
  • mcpToolCall:记录调用的 id、server、tool、status 和 arguments。 调用还包含 appContext、mcpAppUi、pluginId、readOnlyHint、result、error 和 durationMs,这些字段均可为 null。旧版字段 mcpAppResourceUri 为可选字段。 对于受信任的 MCP 应用,appContext 包含 connectorId。其余字段(linkId、resourceUri、appName 和 actionName)均可为 null。 如果工具描述符指定了资源 URI 和显示模式(inline 或 fullscreen),mcpAppUi 会包含 resourceUri 和 preferredModelDisplayMode。如果保存调用时没有这些显示元数据,app-server 会返回 null 作为 mcpAppUi 的值。
  • dynamicToolCall:{id, tool, arguments, status, contentItems?, success?, durationMs?},表示由客户端执行的动态工具调用。
  • collabToolCall:{id, tool, status, senderThreadId, receiverThreadId?, newThreadId?, prompt?, agentStatus?}。
  • webSearch:{id, query, action?},表示智能体发起的网页搜索请求。
  • imageView:智能体调用图像查看工具时发送 {id, path}。
  • enteredReviewMode:审查器开始工作时发送 {id, review}。
  • exitedReviewMode:审查器完成工作时发送 {id, review}。
  • contextCompaction:Codex 压缩对话历史时发送 {id}。

对于 webSearch.action,操作的 type 可以是 search(query?、queries?)、openPage(url?)或 findInPage(url?、pattern?)。

App Server 已弃用旧版 thread/compacted 通知,请改用 contextCompaction 条目。

所有条目都有以下两个生命周期事件:

  • item/started:新的工作单元开始时发送完整的 item。其 item.id 与增量更新中的 itemId 匹配。
  • item/completed:工作完成后发送最终的 item。请以此条目为准确定最终状态。

条目增量更新

  • item/agentMessage/delta:为智能体消息追加流式文本。
  • item/plan/delta:流式发送拟议的计划文本。最终的 plan 条目可能与拼接后的增量文本不完全相同。
  • item/reasoning/summaryTextDelta:流式发送可读的推理摘要。开始新的摘要段落时,summaryIndex 递增。
  • item/reasoning/summaryPartAdded:标记推理摘要段落之间的分界。
  • item/reasoning/textDelta:流式发送原始推理文本(模型支持时)。
  • item/commandExecution/outputDelta:流式发送命令的标准输出和标准错误。请按顺序追加各个增量。
  • item/fileChange/outputDelta:用于兼容旧版 apply_patch 文本输出的通知,已弃用。当前版本的 app-server 不再发送此通知,请改用 fileChange 条目和 turn/diff/updated。

错误

app-server 在正常关闭过程中拒绝新任务时,会返回 JSON-RPC 错误,错误代码为 -32600,data.reason 为 serverShuttingDown。

error 通知包含嵌套的 error 对象,其中有 message 和可选的 additionalDetails。其 codexErrorInfo 字段可以是 null。如果 willRetry 为 true,服务器会重试,轮次继续处于活动状态。失败的轮次以 status: "failed" 结束。常见的 codexErrorInfo 值包括 contextWindowExceeded、usageLimitExceeded、badRequest、unauthorized 和 sandboxError。上游请求失败时,该值可以是对象,例如 { "httpConnectionFailed": { "httpStatusCode": 503 } }。

审批

根据用户的 Codex 设置,执行命令和更改文件可能需要审批。app-server 主动向客户端发送 JSON-RPC 请求,客户端在响应中返回审批决定。

  • 命令执行审批决定:accept、acceptForSession、decline、cancel 或 { "acceptWithExecpolicyAmendment": { "execpolicy_amendment": ["cmd", "..."] } }。

  • 文件更改审批决定:accept、acceptForSession、decline、cancel。

  • 请求包含 threadId 和 turnId,请使用它们将界面状态限定到当前对话。

  • 服务器会继续执行或拒绝操作,并通过 item/completed 结束该条目。

命令执行审批

消息顺序如下:

  1. item/started 显示待审批的 commandExecution 条目,其中包含 command、cwd 和其他字段。
  2. item/commandExecution/requestApproval 包含 itemId、threadId、turnId,以及可选字段 reason、command、cwd、commandActions、proposedExecpolicyAmendment、networkApprovalContext 和 availableDecisions。设置 initialize.params.capabilities.experimentalApi = true 时,请求还可能包含实验性字段 additionalPermissions,用于描述单条命令请求的沙盒访问权限。传输时,additionalPermissions 中的所有文件系统路径均为绝对路径。
  3. 客户端返回上述命令执行审批决定之一。
  4. serverRequest/resolved 确认待处理请求已得到答复或已清除。
  5. item/completed 返回最终的 commandExecution 条目,其状态为 status: completed | failed | declined。

如果存在 networkApprovalContext,则提示用户审批的是托管网络访问,而非一般的 shell 命令执行。当前 v2 模式提供目标 host 和 protocol。客户端应显示针对网络访问的提示,不能假定 command 一定包含用户能够理解的 shell 命令预览。

Codex 按目的地(host、协议和端口)对并发的网络审批提示进行分组。因此,app-server 可以用一条审批提示放行多个发往同一目的地的排队请求。同一主机的不同端口会分别处理。

文件更改审批

消息顺序如下:

  1. item/started 发送 fileChange 条目,其中包含拟议的 changes 和 status: "inProgress"。
  2. item/fileChange/requestApproval 包含 itemId、threadId、turnId,以及可选的 reason 和 grantRoot。
  3. 客户端返回上述文件更改审批决定之一。
  4. serverRequest/resolved 确认待处理请求已得到答复或已清除。
  5. item/completed 返回最终的 fileChange 条目,其状态为 status: completed | failed | declined。

tool/requestUserInput

客户端响应 item/tool/requestUserInput 时,app-server 会发送 serverRequest/resolved,其中包含 { threadId, requestId }。如果在客户端答复之前,轮次开始、完成或中断导致待处理请求被清除,服务器也会发送同一通知。

请求参数包含 autoResolutionMs,其值为以毫秒为单位的整数超时时长或 null。如果指定了时长,而用户未答复,宿主客户端可以在该时长过后自动处理该提示。

权限请求

内置 request_permissions 工具会发送 item/permissions/requestApproval,其中包含 threadId、turnId、itemId、environmentId、cwd、可选的 reason,以及所请求的网络或文件系统权限。请在响应的 permissions 中仅包含获准的权限。将 scope 设为 "session" 可使授权在同一会话的后续轮次中持续生效,省略此字段或使用 "turn" 则仅对本轮次授权。未请求的权限会被忽略。

MCP 服务器引导式提取请求

MCP 服务器可以通过 mcpServer/elicitation/request 中断轮次。请求包含 threadId、可选的 turnId、serverName,并采用以下结构之一:

  • mode: "form" 或 mode: "openai/form",包含 message 和 requestedSchema。
  • mode: "url",包含 message、url 和 elicitationId。

接受时返回 action: "accept" 及请求的 content。拒绝或取消时返回 action: "decline" 或 "cancel",并设置 content: null。随后 app-server 会发送 serverRequest/resolved。要接收 openai/form 变体,请启用 initialize.params.capabilities.mcpServerOpenaiFormElicitation。

动态工具调用(实验性)

dynamicTools 是 thread/start 的实验性字段,对应的 item/tool/call 请求和响应流程也属于实验性 API。

动态工具名称和命名空间名称必须符合 Responses API 的命名约束。避免使用 Codex 内置工具保留的命名空间名称。

轮次中调用动态工具时,app-server 的消息流程如下:

  1. 发送 item/started,其中包含 item.type = "dynamicToolCall"、status = "inProgress",以及 tool 和 arguments。
  2. 向客户端发送服务器请求 item/tool/call。
  3. 客户端在响应中返回内容条目。
  4. 发送 item/completed,其中包含 item.type = "dynamicToolCall"、最终 status,以及返回的 contentItems 或 success 值(如有)。

MCP 工具调用审批(应用)

应用(连接器)的工具调用也可能需要审批。如果应用工具调用有副作用,服务器可能通过 tool/requestUserInput 请求审批,并提供接受、拒绝和取消等选项。标注为破坏性操作的工具始终会触发审批,即使该工具同时声明了权限较低的提示属性。如果用户拒绝或取消,相关 mcpToolCall 条目会以错误结束,工具不会运行。

技能

在用户文本输入中包含 $<skill-name> 即可调用技能。建议同时添加 skill 输入条目,让服务器注入完整的技能指令,无需依赖模型解析技能名称。

{
  "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"
      }
    ]
  }
}

如果省略 skill 条目,模型仍会解析 $<skill-name> 标记并尝试查找该技能,这可能增加延迟。

示例:

$skill-creator 新建一个用于排查 CI 间歇性故障的技能,并附上分步使用说明。

使用 skills/list 获取可用技能(可通过 cwds 限定范围,并使用 forceReload 强制重新加载)。您还可以提供 perCwdExtraUserRoots,以 user 作用域扫描为特定 cwd 指定的其他绝对路径。app-server 会忽略 cwd 未列入 cwds 的条目。skills/list 可能会复用各 cwd 的缓存结果,设置 forceReload: true 可从磁盘刷新。服务器还会读取 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": []
  }]
} }

受监视的本地技能文件发生更改时,服务器还会发送 skills/changed 通知。这表示缓存可能已失效,请根据需要使用当前参数重新调用 skills/list。

按路径启用或禁用技能:

{
  "method": "skills/config/write",
  "id": 26,
  "params": {
    "path": "/Users/me/.codex/skills/skill-creator/SKILL.md",
    "enabled": false
  }
}

应用(连接器)

使用 app/installed 读取最近一次提交的已安装应用运行时快照。每个结果包含应用的 id、runtimeName(或 null)、实际生效的 enabled 状态和 callable 状态。只有在生效的配置启用该应用,且至少有一个模型可见的工具符合应用策略和工具策略时,该应用才可调用。

{
  "method": "app/installed",
  "id": 49,
  "params": {
    "threadId": "thread-1",
    "forceRefresh": false
  }
}
{
  "id": 49,
  "result": {
    "apps": [
      {
        "id": "demo-app",
        "runtimeName": "Demo App",
        "enabled": true,
        "callable": true
      }
    ]
  }
}

省略 threadId 时使用全局配置。设置 forceRefresh: true 可在读取前刷新连接器运行时快照。如果全局策略或工作空间策略阻止访问某个应用,该应用仍可能出现在结果中,此时 enabled 和 callable 均为 false。

使用 app/list 获取可用应用。在 CLI/TUI 中,用户可通过 /apps 选择应用。自定义客户端可直接调用 app/list。每个条目同时包含 isAccessible(用户是否可访问)和 isEnabled(是否已在 config.toml 中启用),以便客户端区分安装或访问状态与本地启用状态。应用条目还可能包含可选的 branding、appMetadata 和 labels 字段。

{ "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
} }

如果提供 threadId,应用功能开关(features.apps)使用该线程的配置快照。省略时,app-server 使用最新的全局配置。

app/list 会在可访问的应用和目录中的应用都加载完成后返回。设置 forceRefetch: true 可绕过应用缓存并获取最新数据。只有刷新成功时才会替换缓存条目。

每当任一来源(可访问的应用或目录中的应用)加载完成,服务器还会发送 app/list/updated 通知。每条通知均包含最新的合并应用列表。

{
  "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
      }
    ]
  }
}

如果您已知应用 ID,且需要查询应用元数据而非已安装应用的运行时状态,请使用 app/read。最多可传入 100 个 appIds。服务器仅保留每个 ID 的首次出现,并在 apps 和 missingAppIds 中保持该顺序。未知或无法访问的应用会列在 missingAppIds 中,不会导致整个请求失败。

{
  "method": "app/read",
  "id": 52,
  "params": {
    "appIds": ["demo-app", "missing-app"],
    "includeTools": true
  }
}
{
  "id": 52,
  "result": {
    "apps": [
      {
        "id": "demo-app",
        "name": "Demo App",
        "description": "Example connector for documentation.",
        "iconUrl": null,
        "iconUrlDark": null,
        "distributionChannel": null,
        "installUrl": null,
        "pluginDisplayNames": [],
        "toolSummaries": [
          {
            "name": "search",
            "title": "Search",
            "description": "Search the app.",
            "isEnabled": true,
            "disabledReason": null,
            "isReadOnly": true
          }
        ]
      }
    ],
    "missingAppIds": ["missing-app"]
  }
}

设置 includeTools: true 可请求仅供展示的公开工具摘要。元数据响应不包含已安装应用的运行时状态,也不授权工具调用。请使用 app/installed 检查实际生效的 enabled 和 callable 状态。

要调用应用,请在文本输入中插入 $<app-slug>,并添加 mention 输入条目,在其中指定 app://<id> 路径(推荐)。

{
  "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"
      }
    ]
  }
}

使用配置 RPC 管理应用设置的示例

使用 config/read、config/value/write 和 config/batchWrite 查看或更新 config.toml 中的应用控制设置。

读取实际生效的应用配置结构(包括 _default 和针对单个工具的覆盖设置):

{ "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 设置所有应用的默认审批方,各应用可以单独覆盖该设置。如果两处都省略,应用将继承顶层 approvals_reviewer 的值。使用 apps.<id>.tools.<tool>.approvals_reviewer 可为单个工具指定审批方。apps._default.default_tools_approval_mode 为没有应用级或工具级覆盖设置的工具指定默认审批模式。托管审批模式要求优先于工具的审批模式设置。

更新单项应用设置:

{
  "method": "config/value/write",
  "id": 61,
  "params": {
    "keyPath": "apps.google_drive.default_tools_approval_mode",
    "value": "prompt",
    "mergeStrategy": "replace"
  }
}

以原子操作应用多项更改:

{
  "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"
      }
    ]
  }
}

检测并导入外部智能体配置

使用 externalAgentConfig/detect 查找可迁移的外部智能体资源,然后将选定的条目传给 externalAgentConfig/import。

检测示例:

{ "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
    }
  ]
} }

导入示例:

{ "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" } }

可选的顶层导入参数 source 用于标识生成所选迁移条目的产品。

每完成一类条目的导入,服务器就会发送 externalAgentConfig/import/progress。所有同步和后台导入都完成后,服务器会发送 externalAgentConfig/import/completed。这些通知包含与响应相同的 importId,以及按类型列出 successes 和 failures 的 itemTypeResults。完成通知可能紧随响应到达,也可能在后台远程导入完成后才到达。

{ "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": []
    }
  ]
} }

读取此前已完成的导入记录:

{ "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": []
  }
] } }

支持的 itemType 值为 AGENTS_MD、CONFIG、SKILLS、PLUGINS、MCP_SERVER_CONFIG、SUBAGENTS、HOOKS、COMMANDS 和 SESSIONS。对于 PLUGINS 条目,details.plugins 列出各个 marketplaceName 及 Codex 可尝试迁移的 pluginNames。检测仅返回仍需处理的条目。例如,当 AGENTS.md 已存在且非空时,Codex 会跳过 AGENTS 迁移。导入技能时也不会覆盖现有技能目录。

从 .claude/settings.json 检测插件时,Codex 会从 extraKnownMarketplaces 读取已配置的市场来源。如果 enabledPlugins 包含来自 claude-plugins-official 的插件,但缺少对应市场来源,Codex 会将 anthropics/claude-plugins-official 推定为来源。

身份验证端点

如果您已使用 Codex app-server 身份验证构建本地或开源应用,可以继续使用这种方式。我们建议迁移到“使用 ChatGPT 登录”,以便用户更清楚地了解并掌控自己的用量。有关“使用 ChatGPT 登录”,请参阅开发者文档和实现指南。商业服务或托管服务一直都不得使用 app-server 身份验证。我们推出“使用 ChatGPT 登录”是为了支持这些场景,也期待看到您构建的应用。欢迎加入合作伙伴候补名单。

JSON-RPC 身份验证和账号接口提供请求/响应方法,以及服务器主动发送的通知(不含 id)。您可以使用这些接口确定身份验证状态、发起或取消登录、退出登录、查看 ChatGPT 速率限制,以及在额度耗尽或达到用量上限时通知工作空间所有者。

身份验证模式

Codex 支持以下身份验证模式。account/updated.authMode 显示当前模式,并在可用时附带当前 ChatGPT planType。account/read 也会返回账号和套餐详情。

  • API 密钥(apikey):调用方通过 type: "apiKey" 提供 OpenAI API 密钥,Codex 会保存该密钥,用于后续 API 请求。
  • 托管式 ChatGPT 身份验证(chatgpt):Codex 负责 ChatGPT OAuth 流程,持久化保存令牌并自动刷新。使用 type: "chatgpt" 启动浏览器流程,或使用 type: "chatgptDeviceCode" 启动设备代码流程。
  • 外部管理的 ChatGPT 令牌(chatgptAuthTokens):此实验性模式适用于已负责用户 ChatGPT 身份验证生命周期的宿主应用。宿主应用直接提供 accessToken、chatgptAccountId 和可选的 chatgptPlanType,并且必须在收到请求时刷新令牌。
  • Amazon Bedrock:account/read 将 Bedrock 账号报告为 type: "amazonBedrock",并指明凭据来自 Codex 管理的 Bedrock API 密钥(credentialSource: "codexManaged")还是外部 AWS 凭据链(credentialSource: "awsManaged")。对于 Codex 管理的 Bedrock API 密钥,account/updated.authMode 的值为 bedrockApiKey。

API 概览

  • account/read:获取当前账号信息,可选择刷新令牌。
  • account/login/start:使用 apiKey、chatgpt 或 chatgptDeviceCode 开始登录。实验性登录类型包括 chatgptAuthTokens、amazonBedrock 和 amazonBedrockAccessKeys。
  • account/bedrock/setup(实验性):使用 AWS 配置文件或环境凭据配置 Amazon Bedrock。
  • account/login/completed(通知):登录尝试结束时发送,无论成功还是出错。
  • account/login/cancel:通过 loginId 取消待完成的托管式 ChatGPT 登录。
  • account/logout:退出登录,并触发 account/updated。
  • account/updated(通知):身份验证模式更改时发送(authMode 可为 apikey、chatgpt、chatgptAuthTokens、agentIdentity、personalAccessToken、bedrockApiKey 或 null),并在可用时包含 planType。
  • account/chatgptAuthTokens/refresh(服务器请求):在发生授权错误后,请求刷新由外部管理的 ChatGPT 令牌。
  • account/rateLimits/read:获取 ChatGPT 速率限制。
  • account/rateLimits/updated(通知):用户的 ChatGPT 速率限制发生变化时发送。
  • account/sendAddCreditsNudgeEmail:请求 ChatGPT 在额度耗尽或达到用量上限时向工作空间所有者发送电子邮件。
  • account/rateLimitResetCredit/consume:使用调用方提供的 idempotencyKey 兑换一次已获得的速率限制重置额度。
  • account/usage/read:获取 ChatGPT 账号的 Token 用量摘要和按日统计的数据。
  • account/workspaceMessages/read:获取工作空间当前有效的消息,并在可用时包含通知标题。
  • mcpServer/oauthLogin/completed(通知):mcpServer/oauth/login 流程结束后发送,内容包括 { name, threadId, loginId?, success, error? }。旧版服务器省略 loginId。对于应用级或插件 OAuth 流程,threadId 可以是 null。
  • mcpServer/startupStatus/updated(通知):已配置的 MCP 服务器启动状态发生变化时发送,内容包括 { threadId, name, status, error, failureReason }。对于应用级启动,threadId 为 null。启动失败时,failureReason: "reauthenticationRequired" 表示已存储的 OAuth 凭据过期且无法刷新,此时客户端应提供重新连接服务器的选项。

选择 Amazon Bedrock Runtime

初始化时,将 capabilities.experimentalApi 设为 true。将 providerId: "amazon-bedrock-runtime" 传给 account/bedrock/setup,或在调用 account/login/start 时传入该参数,并将登录类型设为 amazonBedrock 或 amazonBedrockAccessKeys。省略 providerId 或传入 null 时,会选择 Bedrock Mantle(amazon-bedrock)。

登录已配置的网关

如果客户端负责网关登录,请在初始化时将 capabilities.explicitGatewayOauth 设为 true。对于每个连接,都要先成功调用 account/gatewayOAuth/read,再发送需要身份验证的请求。要检查特定网关的登录状态或登录该网关,请传入 modelProvider。省略此字段时使用当前提供商。

使用设备代码登录时,请先确认 account/gatewayOAuth/read 返回 supportsDeviceAuth: true。然后调用 account/gatewayOAuth/login,传入相同的 modelProvider 和 deviceAuth: true。如果返回的登录提示为 null,表示服务器已复用或刷新凭据。否则,请向用户显示 prompt.verificationUrl 和 prompt.userCode,然后等待带有匹配 loginId 的 account/gatewayOAuth/changed 通知,并据此报告登录是否成功。

1)检查身份验证状态

请求:

{ "method": "account/read", "id": 1, "params": { "refreshToken": false } }

响应示例:

{ "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
  }
}

字段说明:

  • refreshToken(布尔值):设为 true 可在托管式 ChatGPT 模式下强制刷新令牌。在外部令牌模式(chatgptAuthTokens)下,app-server 会忽略此标志。
  • email:ChatGPT 账号没有电子邮件地址时为 null。
  • requiresOpenaiAuth 反映当前提供商的要求。为 false 时,Codex 无需 OpenAI 凭据即可运行。
  • Amazon Bedrock 使用 Codex 管理的 Bedrock API 密钥时,返回 credentialSource: "codexManaged"。使用外部 AWS 凭据链时,返回 credentialSource: "awsManaged"。此字段仅标识选定的凭据来源,不会验证 AWS 凭据链是否能实际解析出凭据。

2)使用 API 密钥登录

  1. 发送请求:

    {
      "method": "account/login/start",
      "id": 2,
      "params": { "type": "apiKey", "apiKey": "sk-..." }
    }
  2. 预期响应:

    { "id": 2, "result": { "type": "apiKey" } }
  3. 通知:

    {
      "method": "account/login/completed",
      "params": { "loginId": null, "success": true, "error": null }
    }
    {
      "method": "account/updated",
      "params": { "authMode": "apikey", "planType": null }
    }

3)使用 ChatGPT 登录(浏览器流程)

  1. 开始登录:

    {
      "method": "account/login/start",
      "id": 3,
      "params": {
        "type": "chatgpt",
        "useHostedLoginSuccessPage": true,
        "appBrand": "chatgpt"
      }
    }

    默认情况下,浏览器回调成功后会重定向到本地的登录成功页面。设置 useHostedLoginSuccessPage: true 后,如果无需设置组织,则会使用托管的登录成功页面。启用托管成功页面后,appBrand 可以是 "codex" 或 "chatgpt"。省略此字段或传入 null 时,默认为 "codex"。

    {
      "id": 3,
      "result": {
        "type": "chatgpt",
        "loginId": "<uuid>",
        "authUrl": "https://chatgpt.com/...&redirect_uri=http%3A%2F%2Flocalhost%3A<port>%2Fauth%2Fcallback"
      }
    }
  2. 在浏览器中打开 authUrl。app-server 负责处理本地回调。

  3. 等待通知:

    {
      "method": "account/login/completed",
      "params": { "loginId": "<uuid>", "success": true, "error": null }
    }
    {
      "method": "account/updated",
      "params": { "authMode": "chatgpt", "planType": "plus" }
    }

3b)使用 ChatGPT 登录(设备代码流程)

如果客户端负责登录交互,或者浏览器回调不可靠,请使用此流程。

  1. 开始登录:

    {
      "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"
      }
    }
  2. 向用户显示 verificationUrl 和 userCode。前端负责这一步的用户交互。

  3. 等待通知:

    {
      "method": "account/login/completed",
      "params": { "loginId": "<uuid>", "success": true, "error": null }
    }
    {
      "method": "account/updated",
      "params": { "authMode": "chatgpt", "planType": "plus" }
    }

3c)使用外部管理的 ChatGPT 令牌登录(chatgptAuthTokens)

仅当宿主应用负责用户 ChatGPT 身份验证的整个生命周期,并直接提供令牌时,才使用此实验性模式。客户端必须在 initialize 时设置 capabilities.experimentalApi = true,才能使用此登录类型。

  1. 发送请求:

    {
      "method": "account/login/start",
      "id": 7,
      "params": {
        "type": "chatgptAuthTokens",
        "accessToken": "<jwt>",
        "chatgptAccountId": "org-123",
        "chatgptPlanType": "business"
      }
    }
  2. 预期响应:

    { "id": 7, "result": { "type": "chatgptAuthTokens" } }
  3. 通知:

    {
      "method": "account/login/completed",
      "params": { "loginId": null, "success": true, "error": null }
    }
    {
      "method": "account/updated",
      "params": { "authMode": "chatgptAuthTokens", "planType": "business" }
    }

服务器收到 401 Unauthorized 时,可能会请求宿主应用提供刷新后的令牌:

{
  "method": "account/chatgptAuthTokens/refresh",
  "id": 8,
  "params": { "reason": "unauthorized", "previousAccountId": "org-123" }
}
{ "id": 8, "result": { "accessToken": "<jwt>", "chatgptAccountId": "org-123", "chatgptPlanType": "business" } }

收到刷新成功的响应后,服务器会重试原始请求。刷新请求约在 10 秒后超时。

4)取消 ChatGPT 登录

{ "method": "account/login/cancel", "id": 4, "params": { "loginId": "<uuid>" } }
{ "method": "account/login/completed", "params": { "loginId": "<uuid>", "success": false, "error": "..." } }

5)退出登录

{ "method": "account/logout", "id": 5 }
{ "id": 5, "result": {} }
{ "method": "account/updated", "params": { "authMode": null, "planType": null } }

6)速率限制(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,
    "credits": [{
      "id": "RateLimitResetCredit_1",
      "resetType": "codexRateLimits",
      "status": "available",
      "grantedAt": 1781654400,
      "expiresAt": 1784246400,
      "title": "Rate-limit reset",
      "description": "Reset an eligible Codex rate-limit window."
    }]
  }
} }
{ "method": "account/rateLimits/updated", "params": {
  "rateLimits": {
    "limitId": "codex",
    "primary": { "usedPercent": 31, "windowDurationMins": 15, "resetsAt": 1730948100 }
  }
} }

字段说明:

  • rateLimits 是向后兼容的单个计量分组视图。
  • rateLimitsByLimitId(如存在)是多个计量分组的视图,以计量用的 limit_id(例如 codex)为键。
  • limitId 是计量分组的标识符。
  • limitName 是向用户显示的可选分组名称。
  • usedPercent 是配额窗口内当前已用额度的百分比。
  • windowDurationMins 是配额窗口的持续时长(分钟)。
  • resetsAt 是下次重置的 Unix 时间戳(秒)。
  • 服务器返回与某个分组关联的 ChatGPT 套餐时,会包含 planType。
  • 服务器返回工作空间剩余额度详情时,会包含 credits。
  • rateLimitReachedType 表示达到限制后服务器判定的限制状态。
  • rateLimitResetCredits 包含已获得且可用的重置次数。如果服务未提供该数据,则为 null。
  • rateLimitResetCredits.credits 在仅知道次数时为 null。空数组表示服务已查询详情,但没有返回可用额度。服务可能限制返回的明细条数,因此可用次数以 availableCount 为准。
  • 每条明细包含不透明的 id、resetType、status、grantedAt、expiresAt(可以是 null)、title(可以是 null)和 description(可以是 null)。
  • 使用一次重置额度后,请调用 account/rateLimits/read 获取最新限制。

7)Token 用量(ChatGPT)

使用 account/usage/read 获取 ChatGPT 的 Token 用量摘要字段,以及可选的按日统计数据。

{ "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 }
  ]
} }

字段说明:

  • 如果服务尚未返回某项指标,summary 中对应的值可以是 null。
  • dailyUsageBuckets 可以是 null。如果存在,每个日统计条目都包含 startDate 和 tokens。
  • 此端点需要由 Codex 服务支持的身份验证。支持 ChatGPT、外部 ChatGPT 令牌、智能体身份和个人访问令牌身份验证,不支持仅使用 API 密钥或使用 Bedrock 的身份验证方式。

8)兑换已获得的速率限制重置额度(ChatGPT)

使用 account/rateLimitResetCredit/consume 兑换一次已获得的重置额度。

{ "method": "account/rateLimitResetCredit/consume", "id": 8, "params": { "idempotencyKey": "8ae96ff3-3425-4f4c-8772-b6fd61502868", "creditId": "RateLimitResetCredit_1" } }
{ "id": 8, "result": { "outcome": "reset" } }

字段说明:

  • idempotencyKey 必须非空。每次独立的兑换操作都应使用一个 UUID,重试同一操作时复用该值。
  • creditId 为可选字段。如果提供,必须是从 account/rateLimits/read 获取的非空不透明 ID。省略时,服务会选择下一笔可用额度。
  • reset 表示已使用一次重置额度。
  • alreadyRedeemed 表示同一兑换操作此前已完成。请按幂等成功处理,并刷新账号限制。
  • nothingToReset 表示没有符合重置条件的速率限制窗口。
  • noCredit 表示账号没有已获得且可用的重置额度。
  • 使用一次重置额度后,请调用 account/rateLimits/read 获取最新窗口信息,避免根据兑换响应推算。

9)向工作空间所有者发送限额通知

在额度耗尽或达到用量上限时,使用 account/sendAddCreditsNudgeEmail 请求 ChatGPT 向工作空间所有者发送电子邮件。

{ "method": "account/sendAddCreditsNudgeEmail", "id": 9, "params": { "creditType": "credits" } }
{ "id": 9, "result": { "status": "sent" } }

工作空间额度耗尽时,使用 creditType: "credits"。工作空间达到用量上限时,使用 creditType: "usage_limit"。如果近期已通知过所有者,响应状态为 cooldown_active。

10)工作空间消息(ChatGPT)

使用 account/workspaceMessages/read 获取当前工作空间内有效的消息,并在可用时获取通知标题。

{ "method": "account/workspaceMessages/read", "id": 10 }
{ "id": 10, "result": { "featureEnabled": true, "messages": [
  { "messageId": "msg_123", "messageType": "headline", "messageBody": "Workspace maintenance starts at 5pm.", "createdAt": 1781395200, "archivedAt": null }
] } }

输入关键词搜索中文文档。