"""Test discovery of an authored example skill in a disposable repository."""
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
SKILL = """---
name: catalog-check
description: Verify field names and duplicate keys in a local product catalog CSV when asked for a catalog audit.
---
Read the selected local CSV and the project column definitions.
Report missing required columns and duplicated item codes with row numbers.
Use read-only operations and return a summary without exposing unnecessary values.
"""
SETTINGS = '[[skills.config]]\nname = "catalog-check"\nenabled = false\n'
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, input_data, operation, expected, actual):
assert actual == expected, (name, expected, actual)
cases.append(dict(name="skills_" + name, input=input_data, operation=operation, expected=expected, actual=actual))
with TemporaryDirectory(prefix="mbsky-skills-discovery-") as temporary:
root = Path(temporary)
profile = root / "profile"
repo = root / "repo"
skill = repo / ".agents/skills/catalog-check/SKILL.md"
skill.parent.mkdir(parents=True)
profile.mkdir()
skill.write_bytes(SKILL.encode())
env = {key:value for key,value in os.environ.items() if not key.startswith(("GIT_","CODEX_THREAD"))}
env.update(CODEX_HOME=str(profile),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()
with subprocess.Popen([codex,"app-server","--stdio"],cwd=repo,env=env,
stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,
encoding="utf8") as process:
server = Server(process)
try:
server.request("initialize",{"clientInfo":{"name":"mbsky-skill-lab","version":"1"}},1)
server.request("initialized")
def listed(request_id, reload):
report = server.request("skills/list",{"cwds":[str(repo)],"forceReload":reload},request_id)
group, = report["data"]
assert not group["errors"], group["errors"]
own, = (row for row in group["skills"] if row["name"]=="catalog-check")
assert Path(own["path"]).resolve() == skill.resolve()
return [own["name"], own["scope"], own["enabled"], own["description"] == SKILL.splitlines()[2].removeprefix("description: ")]
check("discovered", {"skill":SKILL,"forceReload":False},
"Start a local server and list repository skills",
["catalog-check","repo",True,True],listed(2,False))
(profile / "config.toml").write_bytes(SETTINGS.encode())
check("cached", {"config":SETTINGS,"forceReload":False},
"Repeat the query in the same process after changing the isolated config",
["catalog-check","repo",True,True],listed(3,False))
check("disabled", {"config":SETTINGS,"forceReload":True},
"Explicitly reload the isolated config then query the skill",
["catalog-check","repo",False,True],listed(4,True))
finally:
server.close()
assert process.returncode == 0
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、Git。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1、Git。
入口文件:projects/codex-agent_skills/agent_skills_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
agent_skills_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1、Git。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a88.zip