"""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()
本例需在 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。
入口文件:projects/codex-cli_config/cli_config_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
cli_config_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a93.zip