"""Exercise actual Codex skill discovery, validation, and enablement."""
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)
def main():
codex = shutil.which("codex.exe") or shutil.which("codex")
git = shutil.which("git")
if not codex or not git:
raise SystemExit("Install Git and Codex CLI, then make both available on PATH.")
cases = []
def check(name, inputs, operation, expected, actual):
assert expected == actual, (name,expected,actual)
cases.append(dict(name="cli_skills_"+name,input=inputs,operation=operation,expected=expected,actual=actual))
with TemporaryDirectory(prefix="mbsky-codex-skill-scopes-") as temporary:
root = Path(temporary)
home = root / "profile"
repo = root / "repo"
nested = repo / "src"
nested.mkdir(parents=True)
home.mkdir()
env = {key:value for key,value in os.environ.items() if not key.startswith(("GIT_","CODEX_"))}
env.update(CODEX_HOME=str(home),GIT_CONFIG_NOSYSTEM="1",GIT_CONFIG_GLOBAL=os.devnull)
subprocess.run([git,"init","--quiet","--template=",str(repo)],env=env,check=True,capture_output=True)
version = subprocess.run([codex,"--version"],env=env,cwd=repo,check=True,capture_output=True,
encoding="utf8",timeout=10).stdout.strip()
def skill(directory, name, description):
folder = directory / name
folder.mkdir(parents=True)
file = folder / "SKILL.md"
file.write_text(f"---\nname: {name}\ndescription: {description}\n---\n"
"Read local test cases and report failed assertions without editing the repository.\n",
encoding="utf8")
return file
basic = skill(repo/".agents/skills","mbsky-check-math","Check addition, division, and zero handling.")
feature = skill(nested/".agents/skills","mbsky-check-filter","Check test cases for a catalog filter.")
skill(repo/".codex/skills","mbsky-legacy-demo","Use the historical repository directory.")
malformed = nested/".agents/skills/mbsky-missing-description/SKILL.md"
malformed.parent.mkdir(parents=True)
malformed.write_text("---\nname: mbsky-missing-description\n---\nReport only failed tests.\n",encoding="utf8")
script = basic.parent / "examples.py"
script.write_bytes(b"import json\n\ndef divide(left, right):\n if right == 0:\n return None\n return left / right\n\nprint(json.dumps([divide(8, 2), divide(0, 3), divide(8, 0)]))\n")
configured = home / "config.toml"
with subprocess.Popen([codex,"app-server","--stdio"],cwd=repo,env=env,
stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,
encoding="utf8") as process:
rpc = Server(process)
try:
rpc.request("initialize",{"clientInfo":{"name":"mbsky-cli-skills-lab","version":"1"}},1)
rpc.request("initialized")
def inspect(directory, request, reload=False):
result, = rpc.request("skills/list",{"cwds":[str(directory)],"forceReload":reload},request)["data"]
owned = {row["name"]:row for row in result["skills"] if row["name"].startswith("mbsky-")}
errors = [row for row in result["errors"] if "mbsky-missing-description" in json.dumps(row)]
return owned,errors
plain,_ = inspect(repo,2)
scoped,errors = inspect(nested,3)
check("root","repository root", "Read skill names from root using the local server",
["mbsky-check-math","mbsky-legacy-demo"], sorted(plain))
check("nested",[".agents/skills","src/.agents/skills"], "Read at the child path and check both scopes",
["mbsky-check-filter","mbsky-check-math","mbsky-legacy-demo"],sorted(scoped))
check("bad_yaml","Missing description", "Compare the load errors and list entries",
[True,False],[bool(errors),"mbsky-missing-description" in scoped])
check("metadata",basic.name, "Compare effective metadata to the authored frontmatter",
["mbsky-check-math","Check addition, division, and zero handling.","repo"],
[scoped["mbsky-check-math"][k] for k in ("name","description","scope")])
selector = json.dumps(feature.as_posix(),ensure_ascii=False)
configured.write_bytes(f"[[skills.config]]\npath = {selector}\nenabled = false\n".encode())
disabled,_ = inspect(nested,4,True)
check("disable","Reload with a path-specific disabled entry", "Read current flags of the two skills",
[False,True],[disabled[name]["enabled"] for name in ("mbsky-check-filter","mbsky-check-math")])
finally:
rpc.close()
example = subprocess.run([sys.executable,"-I",str(script)],cwd=repo,env=env,check=True,capture_output=True,
encoding="utf8",timeout=10)
check("fixture",[["8/2","0/3","8/0"],sha256(script.read_bytes()).hexdigest()],
"Execute the independently authored optional test fixture",
[4.0,0.0,None],json.loads(example.stdout))
print(json.dumps(dict(version={"python":sys.version.split()[0],"codex":version},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_skills/cli_skills_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
cli_skills_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a98.zip