"""Read current Codex model settings without sending inference or contacting an endpoint."""
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 = "lesson-model"
model_provider = "lesson"
model_reasoning_effort = "medium"
plan_mode_reasoning_effort = "high"
model_reasoning_summary = "concise"
[model_providers.lesson]
name = "Local config fixture"
base_url = "http://127.0.0.1:1/v1"
env_key = "MBSKY_TUTORIAL_TOKEN"
wire_api = "responses"
[model_providers.lesson.http_headers]
"X-Lesson" = "config-only"
"""
def main():
codex = shutil.which("codex.exe") or shutil.which("codex")
if not codex:
raise SystemExit("Install the Codex CLI first.")
cases = []
def check(name, inputs, operation, expected, actual):
assert expected == actual,(name,expected,actual)
cases.append(dict(name="cli_models_"+name,input=inputs,operation=operation,expected=expected,actual=actual))
with TemporaryDirectory(prefix="mbsky-codex-model-choices-") as temporary:
root=Path(temporary)
home=root/"home"
home.mkdir()
cfg=home/"config.toml"
env={k:v for k,v in os.environ.items() if not k.startswith("CODEX_")}
env.pop("MBSKY_TUTORIAL_TOKEN",None)
env["CODEX_HOME"]=str(home)
def invoke(*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-model-settings","version":"1"}},1)
client.request("initialized")
return client.request("config/read",{"includeLayers":True,"cwd":str(root)},2)["config"]
finally:
client.close()
cfg.write_bytes(CONFIG.encode())
value=read()
check("model","model and provider in user config","Read actual config output",
["lesson-model","lesson"],[value["model"],value["model_provider"]])
check("override",'-c model="alternate-model"',"Read effective model with an explicit override",
"alternate-model",read("-c",'model="alternate-model"')["model"])
check("effort","Task and Plan reasoning settings","Read the two actual configuration values",
["medium","high"],[value["model_reasoning_effort"],value["plan_mode_reasoning_effort"]])
for summary,label in (("auto","auto"),("concise","concise"),("detailed","detailed"),("none","none")):
current=read("-c",f'model_reasoning_summary="{summary}"')
check("summary_"+label,summary,"Read summary preference, without requesting a summary",
summary,current["model_reasoning_summary"])
provider=value["model_providers"]["lesson"]
check("provider",["base_url","env_key","wire_api","http_headers"],"Read Responses protocol and nonsecret header",
["http://127.0.0.1:1/v1","MBSKY_TUTORIAL_TOKEN","responses",{"X-Lesson":"config-only"}],
[provider[k] for k in ("base_url","env_key","wire_api","http_headers")])
help_result=invoke("exec","--help")
help_result.check_returncode()
check("cli_flag","codex exec --help","Check CLI help for model selection",True,"--model" in help_result.stdout)
cfg.write_bytes(CONFIG.replace('wire_api = "responses"','wire_api = "chat"').encode())
old=invoke("debug","prompt-input","--","Inspect teaching fixture.")
check("legacy_chat","wire_api=chat","Check the installed CLI rejects the legacy protocol",
[True,True],[old.returncode !=0,"wire_api" in old.stderr or "Responses API" in old.stderr])
version=invoke("--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_models/cli_models_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
cli_models_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a96.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip