Codex 自动化:非交互命令、流水线与本地协议
按输出与集成目标选择 CLI、SDK 或 App Server,并用真实本机协议检查验证连接。
学完这一章,你能够
- 按输出与集成目标选择 CLI、SDK 或 App Server,并用真实本机协议检查验证连接。
给非交互运行定义输入和成功条件
codex exec 可接受命令行任务,或用单个 - 读取标准输入。脚本可通过管道、文件重定向或 Bash 的 here-document 提供多行请求,选择与所用 Shell 相符的语法。模型、项目目录和沙箱按实际任务配置。
区分最终消息文件和逐行事件。-o 保存最终消息,--json 输出事件行,--output-schema 约束最终消息的 JSON 结构。后续步骤仍需检查退出状态及业务条件。--ephemeral 用来避免保存用于恢复的会话文件,需要续跑时保留会话并记录标识。
恢复最近会话可用 codex exec resume --last,需要精确目标时可传已保存的会话标识作为位置参数,再给后续提示。当前检查拒绝旧 --session 参数。恢复流程还要确认目录、任务状态和权限。
在 Docker 或隔离 runner 中先安装固定版本,配置项目、认证和准确权限。直接运行 exec 可按官方认证说明使用 CODEX_API_KEY,流水线保存在 Secrets 中并按任务注入。遇到超时或部分修改先检查实际文件差异,再决定重试、续跑或回滚。
选择合适的编程入口
TypeScript 包仍可用 npm install @openai/codex-sdk 安装。当前典型顺序是创建 Codex 客户端、调用 startThread()、对 thread.run() 传入任务,读取 finalResponse。后续调用可沿用同一个 thread,进程重启后可持有效 ID 用 resumeThread 恢复。旧材料把 run 直接挂在根客户端的写法要迁移。
SDK 适合批量处理、服务内部工作流和流水线。需管理完整客户端会话、逐条事件或审批时,可通过 App Server 对接。客户端先完成 initialize,再发 initialized,之后按当前协议与方法发请求。标准输入输出使用逐行 JSON 消息。
本站与本机 App Server 握手,验证请求编号、客户端标记及隔离配置目录。初始化后发送未知方法,观察实现返回的错误码,最后关闭输入并检查退出。下图对应这些步骤。

旧 app-server --port 不适用于此版本。远程开发按当前文档检查 --listen 所选传输、地址和认证。旧 codex mcp-server 命令已移除,已有调用迁移到 App Server。CLI 的 codex mcp 管理外部服务器,是另一项功能。
把自动化接入 GitHub Actions
用可信 PR 或其他明确事件启动任务。检查差异范围的流水线需取得正确分支和基线。官方 Action 的 prompt 和 prompt-file 选择其一,按用途设模型和沙箱。输出可保留为工作流产物,授权后再交给评论或 PR 审查步骤。
用 openai-api-key 引用 Secret,不在工作流或日志写出密钥。检查 runner 权限和仓库权限,按实际平台选择 safety-strategy。配置低权限执行账户时,用配套的 unprivileged-user 策略和 codex-user 字段。allow-users 与 allow-bots 按当前 action 输入约定指定可信触发者。
流程应验证返回状态、输出文件与实际差异。可复现的构建或测试由明确命令执行。若失败,保留运行结果并按版本化产物排查。涉及 PR 评论或发布的步骤需有对应授权。
exec 参数
| 参数 | 可观察作用与条件 |
|---|---|
| -m | 选择当前账号或提供方可用模型。 |
| -o | 把最后一条代理消息写入指定路径。 |
| --full-auto | 本机进入 exec 时已拒绝此旧写法,按实际沙箱和任务要求设置。 |
| --ephemeral | 运行时不保存用于恢复的会话文件。 |
| --json | 以 JSON Lines 输出事件,按事件类型消费。 |
| --output-schema | 引用 JSON Schema 文件约束最终消息。 |
| --sandbox | 根据任务选择只读、工作区写入或已授权运行方式。 |
GitHub Action 输入
| 字段 | 用法 |
|---|---|
| prompt | 在受版本管理的工作流中直接写任务。 |
| prompt-file | 从检出的可信文件读取任务内容。 |
| model | 选择本次任务所需且可用的模型。 |
| sandbox | 按任务性质传合适的沙箱策略。 |
| output-file | 指定最终消息产物的位置。 |
| codex-args | 传入额外 CLI 选项,可用 JSON 数组或 Shell 参数字符串。 |
用标准输入输出检查 App Server 连接
"""Exercise App Server message exchange and CLI compatibility on a local installation."""
from hashlib import sha256
import json
import os
from pathlib import Path
from queue import Queue
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
from threading import Thread
from time import monotonic
def inspect_protocol(binary, root, env):
hello = dict(jsonrpc="2.0", id=1, method="initialize",
params={"clientInfo": {"name": "mbsky-lab", "version": "1.0.0"}})
ready = dict(jsonrpc="2.0", method="initialized")
invalid = dict(jsonrpc="2.0", id=2, method="mbsky/unknown")
messages = Queue()
with subprocess.Popen([binary, "app-server", "--stdio"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, cwd=root, env=env, text=True, encoding="utf8") as server:
def receive():
for line in server.stdout:
messages.put(json.loads(line))
messages.put(None)
def send(document):
server.stdin.write(json.dumps(document) + "\n")
server.stdin.flush()
def response(request_id):
deadline = monotonic() + 6
while True:
document = messages.get(timeout=max(0, deadline - monotonic()))
if document is None:
raise RuntimeError("The local server closed the message stream.")
if document.get("id") == request_id:
return document
reader = Thread(target=receive, daemon=True)
reader.start()
try:
send(hello)
handshake = response(hello["id"])
send(ready)
send(invalid)
error = response(invalid["id"])
finally:
server.stdin.close()
try:
server.wait(timeout=5)
except subprocess.TimeoutExpired:
server.kill()
server.wait()
reader.join(timeout=2)
conditions = [hello["method"], ready["method"], invalid["method"]]
initialized = [handshake["id"], "mbsky-lab" in handshake["result"]["userAgent"],
Path(handshake["result"]["codexHome"]).resolve() == root.resolve()]
error_result = [error["id"], error["error"]["code"], "mbsky/unknown" in error["error"]["message"]]
return conditions, initialized, error_result, server.returncode
def main():
binary = shutil.which("codex.exe") or shutil.which("codex")
if not binary:
raise SystemExit("Codex CLI is required on PATH.")
cases = []
def check(name, data, operation, expected, actual):
assert expected == actual, (name, expected, actual)
cases.append(dict(name="automation_" + name, input=data, operation=operation, expected=expected, actual=actual))
with TemporaryDirectory(prefix="mbsky-codex-app-server-") as temporary:
root = Path(temporary)
env = dict(os.environ, CODEX_HOME=str(root))
args, initialized, error, status = inspect_protocol(binary, root, env)
check("initialize", args[:2], "Send initialize over stdio and check the returned client tag and temporary home",
[1,True,True], initialized)
check("rpc_error", args[2], "Send an unknown method after initialization and read the actual implementation error",
[2,-32600,True], error)
check("server_exit", "close stdin", "Wait for the local process to exit", 0, status)
def cli(*options):
return subprocess.run([binary, *options], cwd=root, env=env, capture_output=True,
encoding="utf-8", timeout=10)
for name, options in (("legacy_port", ["app-server","--port","3000"]),
("legacy_auto", ["exec","--full-auto","--help"]),
("legacy_resume", ["exec","resume","--session","fixture","--help"])):
result = cli(*options)
check(name, options, "Read how the installed CLI parser handles the historical flag",
[2,True], [result.returncode,"unexpected argument" in result.stderr])
options = ["exec", "resume", "--help"]
result = cli(*options)
check("resume_help", options, "Read actual help for the positional session identifier and --last",
[0,True], [result.returncode, "[SESSION_ID]" in result.stdout and "--last" in result.stdout])
options = ["mcp-server", "--help"]
result = cli(*options)
check("legacy_mcp", options, "Verify the old word falls through to global interactive CLI help",
[0, True, False], [result.returncode, "Usage: codex [OPTIONS] [PROMPT]" in result.stdout,
"Usage: codex mcp-server" in result.stdout])
version = cli("--version")
assert version.returncode == 0
print(json.dumps(dict(version={"python":sys.version.split()[0], "codex":version.stdout.strip()},
codex_sha256=sha256(Path(binary).read_bytes()).hexdigest(), cases=cases)))
if __name__ == "__main__":
main()
- 读到初始化编号 1,未知方法返回本机错误码 -32600,关闭输入后进程退出 0。三项历史参数被拒绝。
所需环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。
当前源码 SHA256:f8e24eeed4363abfa5afabedb2a12a6363ac6d7cfe6060b876ccce67909bb6c8
自动化协议练习 ZIP
含本机 App Server 检查脚本、运行说明与可切换观测页。
所需环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。
ZIP SHA256:21afda0725e7058843790ce629f7178c22db6936c97178ecbcbfaa71c0952536
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
修改客户端名称,并同步检查 userAgent 中的名字。
展开参考解答
本机握手应显示新的客户端标记,未知方法仍应产生错误记录。