蓝色天空网mbsky.com · 知识 · 实践 · 创造Codex 教程 · 本地阅读预览
教程 / AI / 智能开发 / Codex 教程

Codex CLI Skills:发现、编写与按文件启停

编写具备工作范围、输入和验收的技能,并用临时仓库核对发现、错误诊断和启停。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

把重复任务整理成技能目录

技能把可复用指令、必要的参考资料和可选脚本放在同一目录。可用来组织测试、代码审查、排错、重构与文档工作。目录职责尽量单一。独立的工作流程可以按需要组合,分别保留输入条件和输出检查。

Codex 当前的仓库发现目录是 .agents/skills。它从工作目录沿父目录查到仓库根,适合把模块专用技能放在工作范围附近。用户目录下的 .agents/skills 用在多个仓库。官方还区分管理员和内置层。本机本次同时发现仓库内旧 .codex/skills。迁移采用现行官方位置,旧位置和 skills.directory 的支持范围按具体版本验证。

编写 SKILL.md 并验证错误情况

每个技能目录的入口整名是 SKILL.md。YAML 前置区包含 name 和 description。目录和名称可用简单清晰的短标识,正文和描述可采用团队的语言。描述写明何时使用、任务对象和应排除的场景。

缺 description 时,本机 skills/list 给出错误,且不显示该技能。有效的示例会返回名称、描述和仓库作用域。对生成测试,可写明先看规格,识别正常、边界和异常输入,再用已有测试框架执行并报告结果。本实例主动运行本站除法脚本,核对 8/2、0/3 和除零三条预期。

临时仓库根和嵌套目录的技能实际列表
本站实验从本机技能注册结果生成。

选择使用方式与职责

Codex 可以根据任务语义选择合适技能,也可明确用 $技能名调用。官方目前支持用 agents/openai.yaml 中的 allow_implicit_invocation 控制是否允许隐式调用。旧 trigger、when、基于扩展名的自动匹配和固定的优先级没有本章运行证据。将语言、目录和任务限制写进明确的描述与说明。

如果要实现从需求到交付的流程,先写验收、接口和边界,再编辑、运行测试并记录结果。是否提交 Git 根据任务授权。代码审查、调试、重构和文档是独立教学场景,不能假定每个客户端都自带同名技能或固定关键词。

列出、禁用并重新加载

在支持的终端版本用 /skills 查看入口或通过 $ 打开技能选择。技能不可见时检查当前目录、文件名与元数据。当前文档建议用 [[skills.config]] 按绝对 path 或 name 单独控制 enabled。一条只用一个选择器,多个匹配按最后一条生效。

本机从根目录读取仓库范围,从 src 同时读取根级和 src 级技能。该版本还保留了根目录的旧路径兼容。通过本地服务刷新后,用路径禁用过滤技能,数学技能仍启用。和目录层级一起检查更容易定位问题。更新未显示时可重启,无需假定旧 /debug 命令能给出匹配详情。

实际模型如何选择、何时加载说明和操作外部工具,仍需在目标模型与权限条件下复查。技能示例可参考官方现行 OpenAI 技能仓库。

技能作用域

位置当前阅读方式
~/.codex/skills/历史用户位置。按现行文档使用用户 .agents/skills,旧位置按版本另测。
{项目目录}/.codex/skills/现行仓库入口为 .agents/skills,可按嵌套范围放置。
配置指定的目录旧 skills.directory 需核对。当前用已知目录及 skills.config 按项启停。

前置区字段

字段含义要求
name便于调用和区分的名称。必需。
description清楚写出何时使用以及范围。必需,缺失可在诊断中发现。
trigger历史示例的关键词。用 description 表达语义,按可用的策略键限定隐式调用。当前官方必填两项里没有此字段。

按职责划分技能

示例工作约定
代码审查列出影响、证据和可复现步骤。
调试先稳定复现,记录输入和真实错误,再验证修正。
重构列出对外接口和兼容要求,确认原行为。
文档按使用者的入口、步骤和结果写说明,并维护已验证的运行条件。

从临时仓库列出技能并核对元数据和开关

python · 阅读源码
"""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。

当前源码 SHA256:d579ce734a047bd029a2d620642b4e6a09cfca2c47154b7ad70cbe081226115e

CLI 技能练习 ZIP

含临时仓库练习、独立脚本执行、说明和结果页。

下载 CLI 技能发现检查

所需环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。

ZIP SHA256:c4b4eb0155225540bdb90b056794f0234745bd6e94e174be4550173553f142d6

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

给缺说明的 SKILL.md 加符合场景的 description,再次检查列表。

展开参考解答

该技能出现在 src 范围,原缺说明报错消失。

规范与官方依据