Codex SDKCodex SDK
「把 Codex CLI 变成 Node 进程里可驱动的对象」。官方 README 首句就是 「Embed the Codex agent in your workflows and apps」,第二句划清了形态:
The TypeScript SDK wraps thecodexCLI from@openai/codex. It spawns the CLI and exchanges JSONL events over stdin/stdout.
"Turns the Codex CLI into an object you can drive inside a Node process" — the official README opens with "Embed the Codex agent in your workflows and apps"; the second sentence settles the form:
The TypeScript SDK wraps thecodexCLI from@openai/codex. It spawns the CLI and exchanges JSONL events over stdin/stdout.
适合与不适合When to use it, when not to
适合:要把 Codex 塞进 Node / Electron 应用或 CI。需要非交互执行。 需要精确到路径的权限规则。TS 或 Python 栈。 不适合:想要纯库、不愿多背一个 CLI 子进程的人。那种情况用 OpenAI Agents SDK。 目标目录不是 Git 仓库又不愿开 skipGitRepoCheck 的也不行。 需要 SDK 层直接暴露压缩 API 的也不行(CLI 侧可配 compact_prompt,见 axes.fit)。
A good fit in four cases:
- You want to put Codex inside your own Node app, Electron app or CI
- You need non-interactive execution
- You need file-level permission rules
- You are on a TypeScript or Python stack, have settled on OpenAI models, but want the model layer swappable
Not a fit in two cases:
- You want a pure library and do not want to carry a spawned CLI child process — use the OpenAI Agents SDK instead
- Your target directory is not a Git repository and you do not want to pass
skipGitRepoCheck
⚠ One more capability boundary: if you need a compaction API exposed at the SDK layer, it does not have one. The CLI side has compact_prompt / experimental_compact_prompt_file plus PreCompact / PostCompact hooks, but the SDK layer has no dedicated compaction interface — config pass-through is the only route.
中文生态China availability 国产 / 国内可直接用 / 备案状态 · 快照domestic / direct access / CAC filing · snapshot 2026-10-20
- 出品属地Origin
- 国外出品foreign-made 国外主体(网信办公示名单未见对应备案主体)。foreign entity (no matching filing entity in the CAC registry).
- 国内使用Direct access
- 直连不可达direct blocked developers.openai.com 大陆直连被拦(403),走代理 200。developers.openai.com 403 direct from mainland, 200 via proxy.
- 备案状态CAC filing
- 未见于备案名单not in filing list:未见于网信办公示名单(2026-10-20 检索 13 批附件,https://www.cac.gov.cn/2024-04/02/c_1713729983803145.htm);该产品未面向大陆公众提供服务,备案不适用。not in the CAC public registry (13 batch attachments searched 2026-10-20, https://www.cac.gov.cn/2024-04/02/c_1713729983803145.htm); the product does not serve the mainland public, so filing does not apply.
备案信息以网信办《生成式人工智能服务已备案信息》公示名单为准(按批次滚动更新,本站只抄编号不解读);「大陆可直连」是本站从大陆网络直连实测的结果,不是厂商承诺。GitHub 类站点当日实测有波动,口径写在依据里。Filing status is quoted from the CAC public registry (updated batch by batch; this site copies the number and does not interpret it). "Direct access" is this site's own reachability measurement from a mainland network, not a vendor promise. GitHub-hosted sites fluctuated on the measurement day — the note says so.
固定坐标系Fixed coordinate system
8 个维度dimensions, 与同分区其他对象逐项可比each comparable item by item against others in the same section.
- 模型与开放条件Model & openness
默认走 OpenAI,但架构上没锁死。
三条证据:
- README 的配置示例里
baseUrl会被翻译成--config openai_base_url=...传给 CLI —— 也就是说,换 API 端点是一等配置项
- 官方
config-advanced有专节 Custom model providers(已核验): 顶层model = ...配model_provider = "proxy",再写[model_providers.<id>](字段有base_url/env_key/wire_api/http_headers/auth.command)
ThreadOptions有独立的model?: string字段
内置的 provider ID:保留
openai、ollama、lmstudio, 另内置amazon-bedrock与azure。openai_base_url可以改内置 provider 的 base URL。官方示例直接给了第三方:
官方示例:
[model_providers.mistral]base_url = "https://api.mistral.ai/v1"还支持 OSS 模式:
--oss配oss_provider = "ollama" | "lmstudio"。即:官方明确支持接非 OpenAI 模型(本地 Ollama / LM Studio、Mistral、Bedrock 等)。
README 原文:If you set
baseUrl, the SDK passes it as a--config openai_base_url=...override⚠ 但换第三方模型之后呢?工具调用与 structured output 的质量如何?官方没给量化结论。本站也没实测。
Defaults to OpenAI, but the architecture is not locked down.
Three pieces of evidence:
- the README's config example translates
baseUrlinto--config openai_base_url=...passed to the CLI — i.e. switching the API endpoint is a first-class config item
- the official
config-advancedpage has a dedicated Custom model providers section (verified): top-levelmodel = ...withmodel_provider = "proxy", then[model_providers.<id>](fields includebase_url/env_key/wire_api/http_headers/auth.command)
ThreadOptionshas its ownmodel?: stringfield
Built-in provider IDs: reserved
openai,ollama,lmstudio, plus built-inamazon-bedrockandazure.openai_base_urlcan change a built-in provider's base URL.The official example directly gives a third party:
Official example:
[model_providers.mistral]base_url = "https://api.mistral.ai/v1"OSS mode is also supported:
--osswithoss_provider = "ollama" | "lmstudio".That is: the official docs explicitly support non-OpenAI models (local Ollama / LM Studio, Mistral, Bedrock etc.).
README wording: If you set
baseUrl, the SDK passes it as a--config openai_base_url=...override⚠ But after switching to a third-party model? How good are tool calling and structured output quality? The official docs give no quantified conclusion. This site has not measured either.
- README 的配置示例里
- 运行位置Where it runs
进程形态是「你的 Node 进程 + 一个被 spawn 的 CLI 子进程」。
README 的
env参数说明值得注意。默认情况下 CLI 继承 Node 进程的环境变量。 所以你可以整体控制 CLI 能看到哪些变量。官方给的用途是 sandboxed hosts(例如 Electron 应用)。SDK 会在继承之上再注入自己需要的变量(如
CODEX_API_KEY)。这条对 Electron / 桌面应用集成是决定性的 —— 官方明确点了这个场景。
README 原文:By default, the Codex CLI inherits the Node.js process environment
The process form is "your Node process + a spawned CLI subprocess."
The README's
envparameter note is worth attention. By default the CLI inherits the Node process environment. So you can fully control which variables the CLI sees. The official use case given is sandboxed hosts (e.g. Electron apps).The SDK injects its own needed variables (like
CODEX_API_KEY) on top of the inheritance.This is decisive for Electron / desktop-app integration — the official docs call out this scenario explicitly.
README wording: By default, the Codex CLI inherits the Node.js process environment
- 本地文件Local files
本地文件是 CLI 的原生能力,SDK 侧只需要给工作目录。
三个相关参数:
workingDirectory—— 设置运行目录additionalDirectories—— 追加额外目录local_image类型的输入条目 —— 把本地图片传给 CLI(走--image)
⚠ 一个必须知道的行为:Codex 要求工作目录是一个 Git 仓库。不满足就拒绝运行。 可以用
skipGitRepoCheck跳过这个检查。这对选型是硬约束:非 Git 目录(纯数据目录、临时目录)里开箱用不了。
官方原文:To avoid unrecoverable errors, Codex requires the working directory to be a Git repository
Local files are a native CLI capability; the SDK side only needs a working directory.
Three relevant parameters:
workingDirectory— sets the run directoryadditionalDirectories— appends extra directorieslocal_imagetype input items — pass local images to the CLI (via--image)
⚠ One behavior you must know: Codex requires the working directory to be a Git repository. It refuses to run otherwise. The check can be skipped with
skipGitRepoCheck.This is a selection-level hard constraint: it does not work out of the box in non-Git directories (pure data dirs, temp dirs).
Official wording: To avoid unrecoverable errors, Codex requires the working directory to be a Git repository
- 关机后的任务Tasks after shutdown
这是本站收录对象里,唯一被官方明确支持「非交互执行」的一个。
核验:官方
noninteractive页已核验(docs/exec.md指向它)。codex exec面向 scripts 与 CI。- 默认 read-only sandbox;可用
--sandbox workspace-write或danger-full-access --json输出 JSONL--output-schema给结构化输出--ephemeral不落盘- 可续跑:
codex exec resume --last,或codex exec resume <SESSION_ID>
SDK 侧对应
resumeThread(),Threads 持久化在~/.codex/sessions。(这与 CLI 条目的对照构成一组。那边「Gemini CLI 是唯一明确支持非交互」。)
⚠ 注意
~/.codex/sessions是文件目录,不是数据库。状态与进程在同一台机器上。跨机迁移与多进程并发写的语义,官方未说明。 (已查 noninteractive 与 config-reference 两页,它们只讲
history.persistence与 resume。)官方对
codex exec的定位:scripts and CIAmong objects collected on this site, this is the only one officially and explicitly supported for non-interactive execution.
Verified: the official
noninteractivepage is verified (docs/exec.mdpoints to it).codex exectargets scripts and CI.- default read-only sandbox;
--sandbox workspace-writeordanger-full-accessavailable --jsonoutputs JSONL--output-schemafor structured output--ephemeralwrites nothing to disk- resumable:
codex exec resume --last, orcodex exec resume <SESSION_ID>
The SDK-side counterpart is
resumeThread(); Threads persist under~/.codex/sessions.(This forms a pair with the CLI entry. Over there, "Gemini CLI is the only one explicitly supporting non-interactive".)
⚠ Note
~/.codex/sessionsis a file directory, not a database. State and process live on the same machine.Cross-machine migration and multi-process concurrent-write semantics are not stated officially. (noninteractive and config-reference pages checked; they only cover
history.persistenceand resume.)The official positioning of
codex exec: scripts and CI- 默认 read-only sandbox;可用
- 工具与扩展Tools & extensions
工具面完全由 CLI 决定 —— SDK 既不新增也不裁剪。
SDK 侧你拿到的是结构化事件流。
runStreamed()返回 async generator。事件类型有:item.completed—— 工具调用、流式响应、文件变更通知turn.completed—— 含 usage 统计
Structured output 是 SDK 明确支持的一等能力:
outputSchema可以传 JSON Schema, 官方还推荐 Zod 转换路径zodToJsonSchema(schema, { target: "openAi" })。⚠ 这里有个命名陷阱:那个 target 写的是
"openAi"。 但它产出的是通用 JSON Schema。给任何遵守该 schema 的模型用都行,不代表只能用 OpenAI。MCP 的情况要说清。README 全文没出现 MCP。本站收录的 9 个 MCP server 里也没有它的位置。 但 Codex CLI 的 MCP 支持已核验(官方有独立 MCP 页):
- 传输:STDIO(command / args / env / env_vars / cwd)与 Streamable HTTP(url / bearer / headers)
- 配置:
codex mcp命令行,或config.toml的[mcp_servers.<name>] - 工具开关:
enabled_tools/disabled_tools - 审批:per-server 与 per-tool 的
approval_mode(auto/prompt/approve) - 认证:
codex mcp login走 OAuth
官方原文:Codex supports MCP servers in both the CLI and the IDE extension SDK 侧:SDK 的
config透传即写入 CLI 的config.toml,故 MCP 可经此可用; 但官方未在 SDK README 明写这条衔接,本站只把它记作 CLI 能力, 仍不与 MCP 站的 server 建立关联。The tool surface is entirely decided by the CLI — the SDK neither adds nor trims.
On the SDK side you get a structured event stream.
runStreamed()returns an async generator. Event types:item.completed— tool calls, streaming responses, file-change notificationsturn.completed— includes usage stats
Structured output is a first-class capability the SDK explicitly supports:
outputSchematakes a JSON Schema, and the official docs also recommend the Zod conversion pathzodToJsonSchema(schema, { target: "openAi" }).⚠ There is a naming trap here: that target says
"openAi". But what it produces is generic JSON Schema. Any model honoring that schema can use it — it does not mean OpenAI only.The MCP situation needs stating clearly. The README never mentions MCP. None of the 9 MCP servers collected on this site involve it either. But Codex CLI's MCP support is verified (the official docs have a standalone MCP page):
- transports: STDIO (command / args / env / env_vars / cwd) and Streamable HTTP (url / bearer / headers)
- config: the
codex mcpcommand line, or[mcp_servers.<name>]inconfig.toml - tool switches:
enabled_tools/disabled_tools - approvals: per-server and per-tool
approval_mode(auto/prompt/approve) - auth:
codex mcp loginvia OAuth
Official wording: Codex supports MCP servers in both the CLI and the IDE extension SDK side: the SDK's
configpassthrough writes into the CLI'sconfig.toml, so MCP is reachable this way; but the official SDK README does not spell out this linkage, so this site records it only as a CLI capability and still does not link it to the MCP-site servers.- 上下文与记忆Context & memory
它提供的是「会话续接」,不是「上下文管理」。
证据是
resumeThread(threadId)。它能恢复对话继续跑,但没有压缩、摘要或落盘机制。换句话说,
Thread解决的是可靠续跑(本站说的「状态」面), 不解决长上下文(本站说的「上下文」面)。要压上下文,只能靠 CLI 侧的配置或换模型 —— SDK 层没有暴露相关选项。
⚠ SDK 侧与 MCP 的衔接:SDK 的
config透传会写入 CLI 的config.toml, 所以 MCP 理论上可经此可用。但官方没有在 SDK README 里明写这条衔接 —— 本站只把它记作 CLI 的能力,不与 MCP 站的 server 建立关联。What it provides is "session continuation", not "context management".
The evidence is
resumeThread(threadId). It can restore a conversation and keep running, but there is no compaction, summarization or offloading mechanism.In other words,
Threadsolves reliable resume (the "state" surface as this site defines it), not long context (the "context" surface as this site defines it).To compact context you can only rely on CLI-side config or switch models — the SDK layer exposes no related options.
⚠ SDK-side linkage with MCP: the SDK's
configpassthrough writes into the CLI'sconfig.toml, so MCP is theoretically reachable this way. But the official SDK README does not spell out this linkage — this site records it only as a CLI capability and does not link it to the MCP-site servers.- 权限与限制Permissions & limits
这是本站核对下来最有价值的一处发现:它补上了 CLI 条目里遗留的审批枚举缺口。
证据来自 SDK 源码(不是文档)
sdk/typescript/src/threadOptions.ts的类型定义:- 审批模式四档 ——
ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted" - 沙箱三档 ——
SandboxMode = "read-only" | "workspace-write" | "danger-full-access" - 网络单独控制 ——
networkAccessEnabled?: boolean、webSearchMode?: "disabled" | "cached" | "live"、webSearchEnabled?: boolean
- 推理强度 8 档 ——
ModelReasoningEffort:minimal / low / medium / high / xhigh / max / ultra / persistent
另一层是配置透传。SDK 支持
config,它会自动展平成 dotted path、转 TOML 传给--config。 另有configOverrides(原始 TOML 逐条透传)。官方示例直接给了文件系统级规则:官方示例:
permissions.audit.filesystem={":root"="read","/path/to/project/.env"="deny"}也就是可以按路径精确拒绝读
.env这类文件。官方说明的优先级: 原始 overrides > 结构化 config > SDK 托管设置。沙箱与审批的官方口径已核验(
agent-approvals-security与config-advanced):- 本地默认 workspace-write + 网络关闭;非版本控制目录默认 read-only
- 顶层键
approval_policy(untrusted/on-request/never/granular, 含approvals_reviewer = "auto_review")与sandbox_mode成对使用
[sandbox_workspace_write]可设writable_roots、network_access- 有命名 profile:
:read-only/:workspace/:danger-full-access workspace-write下,.git/.agents/.codex仍递归只读- 网络另有
features.network_proxy域名 allowlist + DNS 重绑定防护
⚠ 三档沙箱在各平台的实现有差异。平台指 Windows / macOS / Linux。官方没有逐条给出这些差异。 官方只说「OS-level mechanisms enforce sandbox policies」,默认无网络、写入限工作区。
(已查
agent-approvals-security、config-advanced、config-reference三页。)This is the most valuable finding from this site's cross-check: it fills the approval-enum gap left in the CLI entry.
The evidence comes from SDK source (not docs), the type definitions in
sdk/typescript/src/threadOptions.ts:- four approval modes —
ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted" - three sandbox tiers —
SandboxMode = "read-only" | "workspace-write" | "danger-full-access" - network controlled separately —
networkAccessEnabled?: boolean,webSearchMode?: "disabled" | "cached" | "live",webSearchEnabled?: boolean
- reasoning effort has 8 levels —
ModelReasoningEffort: minimal / low / medium / high / xhigh / max / ultra / persistent
The other layer is config passthrough. The SDK supports
config, auto-flattened into dotted paths and converted to TOML for--config. There is alsoconfigOverrides(raw TOML passed item by item). The official example directly gives filesystem-level rules:Official example:
permissions.audit.filesystem={":root"="read","/path/to/project/.env"="deny"}That means reading a file like
.envcan be denied precisely by path. The official precedence: raw overrides > structured config > SDK-managed settings.Sandbox and approval official defaults verified (
agent-approvals-securityandconfig-advanced):- local default workspace-write + network off; non-version-controlled dirs default to read-only
- top-level keys
approval_policy(untrusted/on-request/never/granular, includingapprovals_reviewer = "auto_review") pair withsandbox_mode
[sandbox_workspace_write]can setwritable_roots,network_access- there are named profiles:
:read-only/:workspace/:danger-full-access - under
workspace-write,.git/.agents/.codexremain recursively read-only - network additionally has
features.network_proxydomain allowlist + DNS-rebinding protection
⚠ The three sandbox tiers differ in per-platform implementation. Platforms mean Windows / macOS / Linux. The official docs do not enumerate these differences item by item. They only say "OS-level mechanisms enforce sandbox policies", with no network by default and writes limited to the workspace.
(
agent-approvals-security,config-advanced,config-referencepages checked.)- 审批模式四档 ——
- 适合什么任务Best for
适合四类情况:
- 要把 Codex 塞进自己的 Node 应用 / Electron 应用 / CI
- 需要非交互执行
- 需要精确到文件级的权限规则
- TypeScript 或 Python 栈,且已决定用 OpenAI 模型但想让模型层可换
不适合两类情况:
- 想要一个纯库、不想额外背一个 CLI 子进程 —— 那用 OpenAI Agents SDK
- 目标目录不是 Git 仓库,又不愿开
skipGitRepoCheck
⚠ 还有一处能力边界:需要 SDK 层直接暴露压缩 API 的话它不满足。
CLI 侧有
compact_prompt/experimental_compact_prompt_file与PreCompact/PostCompacthooks 可配,但 SDK 层没有专门的压缩接口, 只能靠 config 透传。Fits four scenarios:
- embedding Codex into your own Node app / Electron app / CI
- needing non-interactive execution
- needing file-path-precise permission rules
- TypeScript or Python stacks, already committed to OpenAI models but wanting the model layer swappable
Does not fit two scenarios:
- wanting a pure library without carrying an extra CLI subprocess — use the OpenAI Agents SDK for that
- the target directory is not a Git repo and you are unwilling to enable
skipGitRepoCheck
⚠ One more capability boundary: if you need a compaction API exposed directly at the SDK layer, it does not deliver.
The CLI side has
compact_prompt/experimental_compact_prompt_fileandPreCompact/PostCompacthooks configurable, but the SDK layer has no dedicated compaction interface, only config passthrough.
头号误解Top misconception
- 以为 v3 计划里的 openai/codex-sdk 存在 —— 该仓 404,SDK 是 monorepo 子目录Assuming openai/codex-sdk from the v3 roadmap exists — that repo 404s; the SDK is a subdirectory of the monorepo
- 以为 SDK 版本号能反映能力 —— package.json 里是 0.0.0-dev,实际版本跟CLI 走(当前 0.159.3)Assuming the SDK version number reflects the capability — package.json says 0.0.0-dev; the real version tracks the CLI (currently 0.159.3)
- 在非 Git 目录里开箱即用就跑不了 —— CLI 要求工作目录是 Git 仓库,必须显式跳过Expecting it to work out of the box outside a Git directory — the CLI requires the working directory to be a Git repository, so you must skip explicitly
- 把
sandbox_workspace_write.network_access与 SDK 的networkAccessEnabled当成两套东西 —— 后者才是 SDK 层入口,前者是 config透传的写法Treatingsandbox_workspace_write.network_accessand the SDK'snetworkAccessEnabledas two separate things — the latter is the SDK-level entry point; the former is a config passthrough - 把 OpenAI Agents SDK(纯 Python 库)当成本 SDK 的同类替代 —— 形态不同,见 layer_positionTreating OpenAI Agents SDK (a pure Python library) as a like-for-like alternative — the forms differ, see layer_position
未知项清单Known unknowns
- 三档沙箱在 Windows / macOS / Linux 的逐平台实现差异(尤其 Windows 是否走 WSL)
- 第三方 provider 换用后工具调用与 structured output 的质量对齐度
- Python SDK 的 API 是否与 TS 版对齐(
Thread/run/resumeThread概念是否一致) ~/.codex/sessions的并发写与跨机迁移语义permissions.audit规则的完整语法(官方只给了文件系统一项示例)
- Per-platform implementation differences of the three sandbox tiers on Windows / macOS / Linux (especially whether Windows goes through WSL)
- Tool-calling and structured-output quality alignment after switching to third-party providers
- Whether the Python SDK's API aligns with the TS version (whether
Thread/run/resumeThreadconcepts match) - Concurrent-write and cross-machine migration semantics of
~/.codex/sessions - The full syntax of
permissions.auditrules (the official docs give only the filesystem example)
证据来源Evidence sources
判断可回到以下一手源复核。本站核验日Every judgement can be rechecked against the primary sources below. Verified on 2026-10-23,内容更新日content updated on 2026-10-01。
| 类型Type | 名称Name | 链接Link |
|---|---|---|
| repo | openai/codex · 仓库(monorepo,SDK 在 sdk/ 子目录)openai/codex · repository (monorepo, SDK under sdk/ subdirectories) | https://github.com/openai/codex |
| docs | TypeScript SDK README(包裹 CLI、JSONL 通信、thread/turn、resume、config 透传)TypeScript SDK README (wraps the CLI, JSONL communication, thread/turn, resume, config passthrough) | https://github.com/openai/codex/tree/main/sdk/typescript |
| code | 源码 sdk/typescript/src/threadOptions.ts(ApprovalMode 四档/ SandboxMode 三档 / 网络与推理强度)Source sdk/typescript/src/threadOptions.ts (ApprovalMode four tiers / SandboxMode three tiers / network and reasoning effort) | https://github.com/openai/codex/blob/main/sdk/typescript/src/threadOptions.ts |
| code | sdk/typescript/package.json(包名 @openai/codex-sdk、Apache-2.0、Node≥18)sdk/typescript/package.json (package name @openai/codex-sdk, Apache-2.0, Node≥18) | https://github.com/openai/codex/blob/main/sdk/typescript/package.json |
| docs | docs/exec.md · Non-interactive mode(正文仅外链)docs/exec.md · Non-interactive mode (body is an external link only) | https://github.com/openai/codex/blob/main/docs/exec.md |
| docs | docs/sandbox.md · Sandbox & approvals(正文仅外链)docs/sandbox.md · Sandbox & approvals (body is an external link only) | https://github.com/openai/codex/blob/main/docs/sandbox.md |
| docs | 官方 Agent approvals & security(沙箱三档、审批策略、网络策略、受保护路径)Official Agent approvals & security (three sandbox tiers, approval policies, network policies, protected paths) | https://developers.openai.com/codex/agent-approvals-security |
| docs | 官方 Configuration Reference(approval_policy / sandbox_mode / model_provider 等键)Official Configuration Reference (approval_policy / sandbox_mode / model_provider etc. keys) | https://developers.openai.com/codex/config-reference |
| docs | 官方 Advanced Configuration(Custom model providers、OSS 模式、压缩、hooks)Official Advanced Configuration (Custom model providers, OSS mode, compaction, hooks) | https://developers.openai.com/codex/config-advanced |
| docs | 官方 MCP 文档(CLI 与 IDE 支持 STDIO / Streamable HTTP)Official MCP docs (CLI and IDE support STDIO / Streamable HTTP) | https://developers.openai.com/codex/mcp |
| docs | 官方 Non-interactive mode(codex exec、resume、默认 read-only)Official Non-interactive mode (codex exec, resume, read-only default) | https://developers.openai.com/codex/noninteractive |
| repo | Python SDK 目录(本站记录存在,细节未核验)Python SDK directory (existence recorded by this site; details unverified) | https://github.com/openai/codex/tree/main/sdk/python |
| changelog | Releases(0.159.3 @ 2026-09-30,另有 0.161.0-alpha 预发布)Releases (0.159.3 @ 2026-09-30, plus 0.161.0-alpha pre-releases) | https://github.com/openai/codex/releases |
| docs | 官方安全文档(沙箱与审批,JS 渲染,本站点未取到正文)Official security docs (sandbox and approvals, JS-rendered; body not captured by this site) | https://developers.openai.com/codex/security |
实测记录Measured runs
本档未跑集成与性能实测;结论只覆盖 API 与官方文档披露的能力面。
实测建议(按本 SDK 形态定制):
| # | 测什么 | 为什么值得测 |
|---|---|---|
| 1 | CLI 与 SDK 版本组合矩阵(CLI 0.159.3 / 0.161.0-alpha × SDK) | SDK 版本号不反映能力,得知道哪些组合是验过的 |
| 2 | permissions.audit.filesystem 的 deny 规则能否真的挡住读 .env | 官方示例给了写法,但拦截强度未核验 |
| 3 | resumeThread 在进程崩溃后恢复的完整度 | 本站最关心的「可靠长期运行」 |
| 4 | 8 档 modelReasoningEffort 的实际耗时与成本差异 | 官方只给枚举,不给代价 |
| 5 | 非交互模式跑一条真实任务链的失败率与中断行为 | 无人值守场景的核心指标 |
| 6 | 换 baseUrl 接第三方 provider 后 structured output 是否仍可靠 | 架构上没锁死,但可靠性未知 |
This site has not completed measured runs.
The test protocol is at protocols/framework/_protocol.md.
Suggested measurement (tailored to this SDK's form):
| # | What to test | Why it is worth testing |
|---|---|---|
| 1 | CLI × SDK version combination matrix (CLI 0.159.3 / 0.161.0-alpha × SDK) | the SDK version does not reflect capability; you need to know which combinations are validated |
| 2 | Whether permissions.audit.filesystem deny rules actually block reading .env | the official example gives the syntax, but interception strength is unverified |
| 3 | How complete resumeThread recovery is after a process crash | this site's top concern: "reliable long-running operation" |
| 4 | Real time and cost differences across the 8 modelReasoningEffort levels | the official docs give the enum but not the price |
| 5 | Failure rate and interruption behavior of running a real task chain in non-interactive mode | the core metric of unattended scenarios |
| 6 | Whether structured output stays reliable after switching baseUrl to a third-party provider | the architecture is not locked down, but reliability is unknown |
形态澄清:这是本站第一个「CLI 包装型」对象Form clarification: this is the first "CLI-wrapped" object on this site
本站三种编程底座形态里,这个属于第2 类(包装既有 CLI):
| 形态 | 谁在跑 agent loop | 本站收录对象 |
|---|---|---|
| ① 自建 loop 框架 | 你的进程里一个库 | OpenAI Agents SDK、Deep Agents |
| ② 包装既有 CLI | 外部 CLI 子进程 | Codex SDK、Claude Agent SDK |
| ③ 自带完整运行时 | 厂商托管 | (暂无) |
这个差别不是措辞问题,它决定了几件实际的事:
1. 行为边界 = CLI 版本边界。SDK 本身版本号是 0.0.0-dev(package.json 实测), 真正决定能力的是它 spawn 的那个 CLI —— 当前 0.159.3(releases @ 2026-09-30, 另有 0.161.0-alpha.7 预发布)。升级 CLI 就等于升级 SDK 的能力与风险面。 2. 沙箱与审批不由你定。它们是 CLI 的能力,SDK 只能通过参数影响(见下文 permissions)。 3. 多一个进程就多一份开销和一个失败点。但换来的是 CLI 侧的全部能力不用你实现。
Of this site's three coding-base forms, this belongs to type 2 (wrapping an existing CLI):
| Form | Who runs the agent loop | Objects on this site |
|---|---|---|
| ① build-your-own-loop framework | a library inside your process | OpenAI Agents SDK, Deep Agents |
| ② wrapping an existing CLI | an external CLI subprocess | Codex SDK, Claude Agent SDK |
| ③ ships a full runtime | vendor-hosted | (none yet) |
This difference is not a matter of wording; it decides several practical things:
1. Behavior boundary = CLI version boundary. The SDK's own version number is 0.0.0-dev (measured in package.json); what really decides capability is the CLI it spawns — currently 0.159.3 (releases @ 2026-09-30, with 0.161.0-alpha.7 pre-release). Upgrading the CLI equals upgrading the SDK's capability and risk surface. 2. Sandbox and approvals are not yours to define. They are CLI capabilities; the SDK can only influence them via parameters (see permissions below). 3. One more process means one more overhead and one more failure point. But in exchange you get the CLI's full capabilities without implementing them.
权限面:源码给出了四种审批模式与三档沙箱The permission surface: source code gives four approval modes and three sandbox tiers
⚠ 这一段纠正了本站 CLI 站档案里的一个「未核验」: 本站 CLI 档案(cli/products/codex-cli.md)当时写了一句话。 原话是「具体审批模式本次未核验」。原因是在 CLI 文档里找不到枚举。 (2026-10-08 该档已按官方文档补全审批四档。) 这次从 SDK 源码的类型定义里找到了 —— 文档外链里没有,源码里有:
// sdk/typescript/src/threadOptions.ts(核验 2026-10-01)
export type ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted";
export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
配套还有:
| 选项 | 取值 | 作用 |
|---|---|---|
networkAccessEnabled | bool | 沙箱内是否放行网络 |
webSearchMode | disabled / cached / live | 联网检索的三档 |
webSearchEnabled | bool | 检索总开关 |
modelReasoningEffort | 8 档:minimal / low / medium / high / xhigh / max / ultra / persistent | 推理强度 |
additionalDirectories | string[] | 追加可访问目录 |
更深一层:可以按路径精确拒绝读文件。 SDK 支持 configOverrides 逐条透传原始 TOML, 官方示例直接给了文件系统规则:
configOverrides: ['permissions.audit.filesystem={":root"="read","/path/to/project/.env"="deny"}']
这意味着 .env 这类文件可以被单独 deny。它不靠「沙箱一刀切不写」这种粗粒度保护。 官方给出了优先级顺序。从高到低是:原始 overrides、结构化 config、SDK 托管设置。
沙箱 / 审批默认值已核验(见 axes.permissions):本地默认 workspace-write + 网络关闭, 非版本控制目录默认 read-only;workspace-write 下 .git / .agents / .codex 递归只读。 三档沙箱的逐平台实现差异官方未逐条说明:只说 "OS-level mechanisms enforce sandbox policies",未分别列举 Windows / macOS / Linux 的差别(已查 agent-approvals-security 与 config-advanced 两页)。Windows 用户尤其要自己确认。
⚠ This passage corrects an "unverified" in this site's CLI-site entry: this site's CLI entry (cli/products/codex-cli.md) once carried one sentence. It read "the specific approval modes were not verified the 2026-10-08 pass" (translated). The reason: no enum could be found in the CLI docs. (On 2026-10-08 that entry was completed with the four official approval tiers.) This time the enum was found in the SDK source's type definitions — not in the doc external links, but in the source:
// sdk/typescript/src/threadOptions.ts (verified 2026-10-01)
export type ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted";
export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
Accompanying options:
| Option | Values | Role |
|---|---|---|
networkAccessEnabled | bool | whether the sandbox allows network |
webSearchMode | disabled / cached / live | three tiers of web search |
webSearchEnabled | bool | master search switch |
modelReasoningEffort | 8 levels: minimal / low / medium / high / xhigh / max / ultra / persistent | reasoning effort |
additionalDirectories | string[] | append accessible directories |
One layer deeper: reading files can be denied precisely by path. The SDK supports configOverrides passing raw TOML item by item, and the official example directly gives filesystem rules:
configOverrides: ['permissions.audit.filesystem={":root"="read","/path/to/project/.env"="deny"}']
This means files like .env can be denied individually. It is not coarse-grained "sandbox blocks all writes" protection. The official precedence, high to low: raw overrides, structured config, SDK-managed settings.
Sandbox / approval defaults verified (see axes.permissions): local default workspace-write + network off, non-version-controlled dirs default read-only; under workspace-write, .git / .agents / .codex are recursively read-only. The per-platform implementation differences of the three sandbox tiers are not enumerated officially: they only say "OS-level mechanisms enforce sandbox policies", without listing Windows / macOS / Linux differences separately (agent-approvals-security and config-advanced pages checked). Windows users especially should verify themselves.
本地文件:有个硬约束,必须知道Local files: there is a hard constraint you must know
To avoid unrecoverable errors, Codex requires the working directory to be a Git repository.
不满足就拒绝运行,可以用 skipGitRepoCheck: true 跳过。
这是一条选型级约束:在纯数据目录、临时目录、上传目录里直接开箱即用是不行的, 而这类场景恰恰是「嵌进自己的产品」时最常遇到的。
To avoid unrecoverable errors, Codex requires the working directory to be a Git repository.
It refuses to run otherwise; skipGitRepoCheck: true can skip it.
This is a selection-level constraint: out-of-the-box use in pure data dirs, temp dirs, upload dirs does not work, and those scenarios are exactly what you hit most when "embedding into your own product".
状态 vs 上下文:它只解决前者State vs context: it only solves the former
| 本站关心的面 | 本SDK 的官方手段 | 够不够 |
|---|---|---|
| 状态(可靠续跑) | resumeThread(id),Threads 持久化在 ~/.codex/sessions | ✅ 有官方支撑 |
| 上下文(长任务压缩) | 无。SDK 层没有压缩/摘要/落盘选项 | ❌ 只能靠 CLI 侧配置 |
「状态 ≠ 上下文」这条主张在这里正好得到印证:它把会话完整保住了, 但没有对内容做任何压缩 —— 线程长了之后成本与延迟是另一回事。
⚠ ~/.codex/sessions 是文件目录而非数据库。跨机迁移、多进程并发写同一会话的语义官方未说明。
| The surface this site cares about | This SDK's official means | Enough? |
|---|---|---|
| state (reliable resume) | resumeThread(id), Threads persisted under ~/.codex/sessions | ✅ official support exists |
| context (long-task compaction) | none. No compaction/summarization/offloading options at the SDK layer | ❌ only CLI-side config |
The "state ≠ context" stance is confirmed right here: it preserves the conversation completely, but does no compaction of content — cost and latency once threads grow is a separate matter.
⚠ ~/.codex/sessions is a file directory, not a database. Cross-machine migration and multi-process concurrent writes to the same session are not stated officially.
非交互执行:这站里目前唯一有官方证据的候选Non-interactive execution: the only candidate here with official evidence so far
docs/exec.md 的标题就是 Non-interactive mode。
这与 CLI 站那份档案形成一组有意思的对照: 在 CLI 站 6 个对象里,只有 Gemini CLI 明确支持非交互脚本模式。其余的这项都标为未核验。 而在这个 harness 站,Codex SDK 是目前唯一的官方非交互文档对象。
如果你要的是「无人值守跑完一串任务」,这两个是仅有的两个有证据的落点—— 一个在你的终端,一个在你的 Node 进程里。
The title of docs/exec.md is Non-interactive mode.
This forms an interesting pair with that CLI-site entry: among the CLI site's 6 objects, only Gemini CLI explicitly supports non-interactive script mode. The rest are marked unverified on this item. And on this harness site, Codex SDK is currently the only object with official non-interactive documentation.
If what you want is "run a chain of tasks unattended", these two are the only evidence-backed landing points — one in your terminal, one inside your Node process.
Structured output:支持得很完整Structured output: supported quite completely
const turn = await thread.run("Summarize repository status", { outputSchema: schema });
- 可直接传 JSON Schema(
as const带类型) - 也可从 Zod 转换:
zodToJsonSchema(schema, { target: "openAi" })
⚠ 这里有个命名陷阱。那个 target: "openAi" 只是告诉转换器用哪种目标格式。 它产出的是标准 JSON Schema,不代表只能 OpenAI 模型用。
const turn = await thread.run("Summarize repository status", { outputSchema: schema });
- JSON Schema can be passed directly (
as constwith types) - or converted from Zod:
zodToJsonSchema(schema, { target: "openAi" })
⚠ There is a naming trap here. That target: "openAi" only tells the converter which target format to use. What it produces is standard JSON Schema — it does not mean only OpenAI models can use it.
MCP:Codex CLI 官方支持,SDK 侧经 config 透传MCP: officially supported by Codex CLI, reachable on the SDK side via config passthrough
SDK README 全文没有出现 MCP,主仓 docs/ 目录里也没有 mcp.md(核验 2026-10-01)。 但官方开发者文档有独立的 MCP 页(核验 2026-10-08):
Codex supports MCP servers in both the CLI and the IDE extension.
支持 STDIO 与 Streamable HTTP 两种传输,codex mcp add ... 与 config.toml 的 [mcp_servers.<name>] 均可配,并有 per-server / per-tool approval_mode (auto / prompt / approve)与 enabled_tools / disabled_tools。 SDK 侧:SDK 的 config 透传即写入 CLI 的 config.toml,因此 MCP server 可经此可用; 不过官方未在 SDK README 明写这条衔接,本站只把它记作 CLI 能力, 仍不与本站 MCP 站的 9 个官方 server 建立关联。
The SDK README never mentions MCP, and the main repo's docs/ directory has no mcp.md either (verified 2026-10-01). But the official developer docs have a standalone MCP page (verified 2026-10-08):
Codex supports MCP servers in both the CLI and the IDE extension.
STDIO and Streamable HTTP transports are both supported, configurable via codex mcp add ... and [mcp_servers.<name>] in config.toml, with per-server / per-tool approval_mode (auto / prompt / approve) and enabled_tools / disabled_tools. SDK side: the SDK's config passthrough writes into the CLI's config.toml, so MCP servers are reachable this way; but the official SDK README does not spell out this linkage, so this site records it only as a CLI capability and still does not link it to the 9 official servers on this site's MCP section.
核验说明Verification notes
confidence: partial 的依据(2026-10-03 由 verified 降级):
为什么降级:下方 ❌ 项的主语是本站的取证缺口,不是「官方未提供」。 按 v3 铁律「未知就说未知」,这些条目存在时标 verified 属于虚高,故降为 partial。 主要缺口:三档沙箱的逐平台实现差异、第三方 provider 能力对齐、权限审计规则语法。 (2026-10-08 已补:MCP 官方支持、model/provider 配置面、沙箱与审批默认值、非交互配置已核验。)
- ✅ 已核验:仓库存在与星数(130,474 · 滚动核验 2026-10-23)、许可(Apache-2.0)、最近推送(2026-10-22,仍活跃)、 最新稳定版 0.163.0(releases @ 2026-10-15)、
sdk/typescript/package.json全文(包名@openai/codex-sdk、版本 0.0.0-dev、Node≥18)、sdk/typescript/README.md全文六节(quickstart / streaming / structured output / images / resume / 环境与 config)、sdk/typescript/src/threadOptions.ts类型定义全文(审批四档、沙箱三档、网络与检索、推理八档)、docs/目录清单、sdk/下python/typescript/python-runtime 三个子目录存在
- ❌ 未核验:三档沙箱的逐平台实现差异(官方只说 OS 级强制,未逐条列举)、 第三方模型换用后工具调用与 structured output 的质量对齐度、 Python SDK 的 API 形态与 TS 版是否一致、
~/.codex/sessions的并发写语义
⚠ 顺带纠正计划。v3 计划里写的 codex-sdk(标注 127k★)作为独立仓库不存在。 gh api 返回 404。127,448★ 是 openai/codex monorepo 的星数, SDK 是它的 sdk/typescript 子目录。
Basis for confidence: partial (downgraded from verified on 2026-10-03):
Why downgraded: the subject of the ❌ items below is this site's evidence gap, not "not provided officially". Per the v3 rule "say unknown when unknown", marking verified while these items exist would be inflated, hence partial. Main gaps: per-platform implementation differences of the three sandbox tiers, third-party provider capability alignment, permission-audit rule syntax. (2026-10-08 additions: official MCP support, model/provider config surface, sandbox and approval defaults, non-interactive config all verified.)
- ✅ Verified: repository exists and star count (130,474 · rolling check 2026-10-23), license (Apache-2.0), last push (2026-10-22, still active), latest stable 0.163.0 (releases @ 2026-10-15), full
sdk/typescript/package.json(package name@openai/codex-sdk, version 0.0.0-dev, Node≥18), full six sections ofsdk/typescript/README.md(quickstart / streaming / structured output / images / resume / environment and config), full type definitions ofsdk/typescript/src/threadOptions.ts(four approval tiers, three sandbox tiers, network and search, eight reasoning levels), thedocs/directory listing, and the existence of python/typescript/python-runtime subdirectories undersdk/
- ❌ Not verified: per-platform implementation differences of the three sandbox tiers (official only says OS-level enforcement, not enumerated item by item), tool-calling and structured-output quality alignment after switching to third-party models, whether the Python SDK's API shape matches the TS version, concurrent-write semantics of
~/.codex/sessions
⚠ Also correcting the plan. The codex-sdk written in the v3 plan (labeled 127k★) does not exist as a standalone repository. gh api returns 404. The 127,448★ is the star count of the openai/codex monorepo; the SDK is its sdk/typescript subdirectory.
相关条目Related entries
- Claude Agent SDKClaude Agent SDK本站最该对照的一对:同样是 CLI 包装型(捆绑 / spawn CLI + 进程通信),但Claude 侧 README 明说只支持 Claude、没有 provider 旁路,而本 SDK 有
baseUrl与model_providers。The pair this site should contrast most: both are CLI-wrapped (bundled / spawn CLI + inter-process communication), but the Claude side's README states Claude-only with no provider bypass, while this SDK hasbaseUrlandmodel_providers. - OpenAI Agents SDKOpenAI Agents SDK同一家厂商的两种形态:那个是纯 Python 库(primitives-only),这个是 Node + CLI 子进程包装。选型第一问就是「要不要多背一个 CLI 进程」。Two forms from the same vendor: that one is a pure Python library (primitives-only), this one is a Node + CLI-subprocess wrapper. The first selection question is "do you want to carry an extra CLI process".
- Deep AgentsDeep Agentsbatteries-included 的对照面:本 SDK 不预置任何东西,工具与沙箱全由 CLI 版本决定。The batteries-included contrast surface: this SDK presets nothing; tools and sandbox are entirely decided by the CLI version.
- LangGraphLangGraph若要「非交互 + 有图结构 + 多Agent 协作」,编排框架才是对应层;本 SDK 只给单线程执行。If you need "non-interactive + graph structure + multi-agent collaboration", an orchestration framework is the matching layer; this SDK only gives single-thread execution.
- Codex CLICodex CLI另一层 · AI 编程Other layer · AI coding
本页由This page is generated from the ai-handbook 数据层生成(CC BY 4.0)。data layer (CC BY 4.0).
方法论与坐标系定义见仓库内For the methodology and coordinate definitions, see METHODOLOGY.md.