Skip to content
FunCoding

Search

Search docs, agents, posts, Skills and MCP servers

非交互模式(codex exec)

用 codex exec 在脚本、CI 和定时任务里运行 Codex:基本用法、权限、JSONL 输出、结构化输出、认证。

非交互模式让你不打开交互式 TUI,就能在脚本(如 CI 任务)里运行 Codex,命令是 codex exec。适用场景:作为流水线的一部分(CI、合并前检查、定时任务)、产出可以管道传给其他工具的输出(比如生成发布说明)、把命令输出串进 Codex 再把结果传给其他工具,以及用事先设定好的沙箱和审批设置运行。

基本用法

把任务提示词作为单个参数传入:

codex exec "summarize the repository structure and list the top 5 risky areas"

codex exec 运行时把进度流式输出到 stderr,只把最终的智能体消息打印到 stdout,所以可以方便地重定向或管道:

codex exec "generate release notes for the last 10 commits" | tee release-notes.md
  • 不想把会话 rollout 文件持久化到磁盘,用 --ephemeral

  • 标准输入有管道内容同时又给了提示词参数时,提示词是指令,管道内容是额外上下文:

    curl -s https://jsonplaceholder.typicode.com/comments \
      | codex exec "format the top 20 items into a markdown table" \
      > table.md

权限与安全

默认情况下 codex exec 在只读沙箱里运行。 在自动化里请设置工作流所需的最小权限:

  • 允许编辑:codex exec --sandbox workspace-write "<task>"
  • 允许更宽的访问:codex exec --sandbox danger-full-access "<task>"(只在受控环境里用,例如隔离的 CI 运行器或容器)

codex exec --full-auto 是保留的已弃用兼容标志,会打印警告,新脚本请用显式的 --sandbox workspace-write。需要不加载 $CODEX_HOME/config.toml 的运行用 --ignore-user-config;在受控的自动化环境里想跳过用户和项目的 execpolicy .rules 文件用 --ignore-rules。如果你把某个启用的 MCP 服务器配置为 required = true 而它初始化失败,codex exec 会以错误退出,而不是在缺少该服务器的情况下继续。

让输出可被机器读取

用 JSON Lines 输出:

codex exec --json "summarize the repo structure" | jq

启用 --json 后 stdout 成为 JSONL 流,可以捕获 Codex 运行时发出的每个事件:事件类型有 thread.started、turn.started、turn.completed、turn.failed、item.* 和 error;条目类型包括智能体消息、推理、命令执行、文件变更、MCP 工具调用、网络搜索和计划更新。示例(每行一个 JSON 对象):

{"type":"thread.started","thread_id":"0199a213-81c0-7800-8aa1-bbab2a035a53"}
{"type":"turn.started"}
{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"Repo contains docs, sdk, and examples directories."}}
{"type":"turn.completed","usage":{"input_tokens":24763,"cached_input_tokens":24448,"output_tokens":122,"reasoning_output_tokens":0}}

只需要最终消息时,用 -o <path>(--output-last-message <path>)把它写入文件,同时仍打印到 stdout。

用 schema 产出结构化输出

下游步骤需要结构化数据时,用 --output-schema 要求最终回复符合某个 JSON Schema,适合需要稳定字段的自动化(任务摘要、风险报告、发布元数据)。先准备 schema.json:

{
  "type": "object",
  "properties": {
    "project_name": { "type": "string" },
    "programming_languages": { "type": "array", "items": { "type": "string" } }
  },
  "required": ["project_name", "programming_languages"],
  "additionalProperties": false
}

然后运行并把最终 JSON 回复写入磁盘:

codex exec "Extract project metadata" \
  --output-schema ./schema.json \
  -o ./project-metadata.json

在自动化里认证

codex exec 默认复用已保存的 CLI 认证;CI 里通常显式提供凭据。程序化的 Codex CLI 工作流(如 CI/CD 任务)使用 API Key 认证,不要在不受信任或公开的环境里暴露 Codex 执行。在 GitHub Actions 里,用 Codex GitHub Action 而不是自己安装和认证 CLI:它的设计是减少 API Key 暴露,安装 Codex、启动 Responses API 代理,并以可配置的安全策略运行 Codex(见「GitHub Action 与 SDK」)。