Codex CLI 配置:核对生效值与迁移旧选项
用独立 CODEX_HOME 查看配置层、终端选项和工具审批,并区分本地解析与实际运行。
学完这一章,你能够
- 用独立 CODEX_HOME 查看配置层、终端选项和工具审批,并区分本地解析与实际运行。
读取配置并判断覆盖来源
用户 TOML 通常位于 CODEX_HOME 下,默认是用户目录的 .codex。没有用户文件时可先使用默认值,需要时再创建。建议修改后在目标目录启动新命令,检查实际读取到的是用户、项目或命令行哪一层。
账户和设备管理要求可以约束选项。只在可信项目读取项目级配置,且某些机器级字段受限。命令行 -c 可临时覆盖普通字段。本站用独立 app-server 的 config/read 读到用户文件里的标记,并用 -c 覆盖模型和终端选项。
模型、计划与终端界面
模型 ID 写在顶层 model,模型推理强度写 model_reasoning_effort,计划模式可单设 plan_mode_reasoning_effort。取值须在所选模型和客户端支持的范围内。旧 o4-mini、o4-mini-high、o3 与 o3-pro 的名称只用来说明历史资料,使用前按认证方式、模型目录和价格核对可用性。
tui.alternate_screen 可选 auto、always、never。auto 是默认,在 Zellij 可保留滚动历史。always 选择替代屏幕,never 关闭它。一次运行也可用 --no-alt-screen。旧宽高键在本机读取结果中未出现,尺寸由终端环境提供。
起步可保留默认配置。交互调试时按需保留滚动记录。遇到复杂任务再调整模型或推理强度并比较耗时和质量。本站只读三个模型相关字段和一组覆盖值,模型响应及计费待验证。
技能与 MCP 按官方目录和字段设置
将技能写成包含 SKILL.md 的目录,按当前客户端支持的作用域发现。旧示例的 skills.enabled 与 skills.directory 不应直接迁移成新配置。用技能列表和已支持的逐技能配置检查启停。
配置 MCP 时注明服务器 ID、启动命令或端点和允许的工具。enabled_tools 和 disabled_tools 控制工具暴露范围。每工具 approval_mode 当前支持 auto、prompt、writes、approve。旧 ask 的意图对应可核对的 prompt,旧 deny 的禁用需求可用 disabled_tools。允许列表与审批目的各自对应的字段要一起核查。
本站实测读取 command、args、工具名单和 prompt 值。本机拒绝旧 deny 值,实际触发审批须在真实工具调用中核对。旧 features.js_repl、features.js_repl_tools_only 与 js_repl_node_path 属于历史执行入口,当前功能和管理限制以客户端及配置参考为准。
通知、SQLite 状态与日志
TUI 通知可用 tui.notifications 及相应筛选设置。外部通知命令按现行顶层 notify 的参数数组配置。旧 notify.enabled 或 CODEX_NOTIFY_HOOK 不能作为当前通用写法。本站只核对命令被读取,事件派发待实际触发。
用 sqlite_home 指定本机状态库目录,旧环境变量和默认路径按具体版本及部署核对。log_dir 指定日志目录,默认位于 CODEX_HOME/log。显式设置可启用明文 TUI 日志,公开诊断前应去除敏感信息。
RUST_LOG 按模块和等级筛选,error、warn、info、debug、trace 依次增加细节。变更等级后重启目标命令,再核查实际输出。历史资料里的 TUI 与 exec 默认等级按实际版本和日志输出判断。
模型键的迁移
| 旧资料的键 | 现行字段和含义 |
| model.default | 顶层 model 选可用模型。旧表形式被本机拒绝。 |
| model.reasoning_effort | 顶层 model_reasoning_effort 设置推理强度,范围由模型决定。 |
终端行为
| 配置项 | 现行含义 |
| tui.alternate_screen | auto、always 或 never。一次运行可使用 --no-alt-screen。 |
| tui.width | 本机有效配置没有该历史字段。使用终端窗口宽度。 |
| tui.height | 本机有效配置没有该历史字段。使用终端窗口高度。 |
技能目录和启停
| 历史键 | 迁移方向 |
| skills.enabled | 查已加载的技能,使用当前产品提供的开关。 |
| skills.directory | 按当前作用域和发现目录放置 SKILL.md。 |
历史 JavaScript 工具选项
| 历史键 | 迁移方向 |
| features.js_repl | 核对当前客户端支持的工具及管理限制。 |
| features.js_repl_tools_only | 核对当前可用的工具权限与范围。 |
通知设置
| 历史键 | 迁移方向 |
| notify.enabled | 终端使用 tui.notifications。外部命令使用顶层 notify 数组。 |
本机状态目录
| 历史环境变量 | 现行配置 |
| CODEX_SQLITE_HOME | sqlite_home 可指定运行状态库目录。环境别名待复核。 |
日志等级
| 等级 | 内容 |
| error | 仅错误及更严重事件。 |
| warn | 增加警告。 |
| info | 增加一般运行事件。 |
| debug | 增加调试细节。 |
| trace | 增加最细粒度的跟踪。 |
在不同配置层读取本机 CLI 生效值
展开查看收起
"""Read effective CLI settings from a local Codex app-server without a model call."""
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
class Server:
def __init__(self, process):
self.process = process
self.messages = Queue()
self.reader = Thread(target=self.receive, daemon=True)
self.reader.start()
def receive(self):
for line in self.process.stdout:
self.messages.put(json.loads(line))
self.messages.put(None)
def request(self, method, params=None, request_id=None):
message = {"method":method,"jsonrpc":"2.0"}
if params is not None:
message["params"] = params
if request_id is not None:
message["id"] = request_id
self.process.stdin.write(json.dumps(message) + "\n")
self.process.stdin.flush()
if request_id is None:
return None
deadline = monotonic() + 8
while True:
result = self.messages.get(timeout=max(0, deadline - monotonic()))
if result is None:
raise RuntimeError("Local app server closed its stream.")
if result.get("id") == request_id:
assert "error" not in result, result
return result["result"]
def close(self):
self.process.stdin.close()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
self.reader.join(timeout=2)
CONFIG = """
model = "fixture-default"
model_reasoning_effort = "low"
plan_mode_reasoning_effort = "high"
sqlite_home = "fixture-state"
notify = ["fixture-notifier"]
[tui]
alternate_screen = "never"
width = 84
height = 20
notifications = false
[mcp_servers.catalog]
command = "fixture-catalog"
args = ["--read-only"]
enabled_tools = ["find"]
[mcp_servers.catalog.tools.find]
approval_mode = "prompt"
"""
def main():
codex = shutil.which("codex.exe") or shutil.which("codex")
if not codex:
raise SystemExit("Install Codex CLI and make it available on PATH.")
cases = []
def check(name, inputs, operation, expected, actual):
assert actual == expected, (name, expected, actual)
cases.append(dict(name="cli_config_" + name,input=inputs,operation=operation,expected=expected,actual=actual))
with TemporaryDirectory(prefix="mbsky-cli-config-read-") as temporary:
root = Path(temporary)
home = root / "profile"
home.mkdir()
config = home / "config.toml"
env = {k:v for k,v in os.environ.items() if not k.startswith("CODEX_")}
env["CODEX_HOME"] = str(home)
def cli(*args):
return subprocess.run([codex,*args],cwd=root,env=env,capture_output=True,encoding="utf8",timeout=15)
def read(*overrides):
with subprocess.Popen([codex,*overrides,"app-server","--stdio"],cwd=root,env=env,stdin=subprocess.PIPE,
stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,encoding="utf8") as process:
client=Server(process)
try:
client.request("initialize",{"clientInfo":{"name":"mbsky-config-lab","version":"1"}},1)
client.request("initialized")
config_result=client.request("config/read",{"includeLayers":True,"cwd":str(root)},2)["config"]
finally:
client.close()
return config_result
config.write_bytes(b"[tui]\nnotifications = true\n")
default = read()
check("default_screen","TUI table without alternate_screen","Read local defaults through config/read","auto",default["tui"]["alternate_screen"])
config.write_bytes(CONFIG.encode())
current = read()
check("model", ["model","model_reasoning_effort","plan_mode_reasoning_effort"], "Read settings from the local server",
["fixture-default","low","high"],[current[k] for k in ("model","model_reasoning_effort","plan_mode_reasoning_effort")])
overridden = read("-c",'model="fixture-override"',"-c",'tui.alternate_screen="always"')
check("overrides", ["model","tui.alternate_screen"], "Launch a new app server with command-line overrides",
["fixture-override","always"], [overridden["model"],overridden["tui"]["alternate_screen"]])
tui = current["tui"]
check("tui", ["never","width","height","notifications"], "Read real effective TUI fields and test for legacy sizes",
["never",False,False,False], [tui["alternate_screen"],"width" in tui,"height" in tui,tui["notifications"]])
check("screen_cli", "--no-alt-screen", "Check the installed CLI help for the alternate-screen flag",
True,"--no-alt-screen" in cli("--help").stdout)
tool = current["mcp_servers"]["catalog"]
check("mcp", ["command","args","enabled_tools","approval_mode"],
"Read the configured MCP tool without starting the command",
["fixture-catalog",["--read-only"],["find"],"prompt"],
[tool["command"],tool["args"],tool["enabled_tools"],tool["tools"]["find"]["approval_mode"]])
check("notify","notify","Read the external notification command and argv without executing it",
["fixture-notifier"],current["notify"])
check("sqlite","sqlite_home","Read the SQLite directory setting",
"fixture-state",Path(current["sqlite_home"]).name)
config.write_bytes(b'[model]\ndefault = "old-model"\n')
failed = cli("debug","prompt-input","--","Observe fixture config.")
check("old_model", "[model] table", "Attempt to load old nesting in the installed CLI",
[1,True],[failed.returncode,"model" in failed.stderr and "string" in failed.stderr])
config.write_bytes(b'[mcp_servers.fixture]\ncommand = "fixture-catalog"\n[mcp_servers.fixture.tools.find]\napproval_mode = "deny"\n')
failed = cli("debug","prompt-input","--","Observe fixture config.")
check("old_mcp", "approval_mode=deny", "Attempt to read the old disabled-tool value",
[1,True],[failed.returncode,"approval_mode" in failed.stderr and "deny" in failed.stderr])
version = cli("--version")
version.check_returncode()
print(json.dumps(dict(version={"python":sys.version.split()[0],"codex":version.stdout.strip()},
codex_sha256=sha256(Path(codex).read_bytes()).hexdigest(),cases=cases)))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
CLI 配置练习 ZIP
含读取设置、对比覆盖、旧选项检查和本地结果页。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
用户配置里的模式变为 always,未设置时仍为 auto。