蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

核对已注册的事件并实际运行脚本

PYTHONWindows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。hooks_lab.py
hooks_lab.py146 行
"""Check the installed Codex hook registry and test an independent policy handler."""
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


HANDLER = '''import json
import sys

data = json.load(sys.stdin)
if data.get("hook_event_name") == "PreToolUse":
    command = data.get("tool_input", {}).get("command", "")
    if command == "fixture-write protected":
        result = {"hookSpecificOutput":{"hookEventName":"PreToolUse",
                 "permissionDecision":"deny","permissionDecisionReason":"Protected fixture."}}
    else:
        result = {}
    print(json.dumps(result))
elif data.get("hook_event_name") == "Stop":
    print(json.dumps({"decision":"block","reason":"Verify the fixture once more."}
                     if not data.get("stop_hook_active") else {}))
else:
    print("{}")
'''


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")
    if not codex:
        raise SystemExit("Put Codex CLI on PATH.")
    cases = []

    def check(name, inputs, action, expect, actual):
        assert actual==expect,(name,expect,actual)
        cases.append(dict(name="hooks_"+name,input=inputs,operation=action,expected=expect,actual=actual))

    with TemporaryDirectory(prefix="mbsky-hooks-check-") as temporary:
        root = Path(temporary)
        home = root / "local-profile"
        home.mkdir()
        handler = root / "fixture_hook.py"
        handler.write_bytes(HANDLER.encode())
        command = f'python "{handler}"'
        config = {"hooks":{
            "PreToolUse":[{"matcher":"^Bash$","hooks":[{"type":"command","command":command,"timeout":5}]}],
            "Stop":[{"hooks":[{"type":"command","command":command,"timeout":4}]}],
        }}
        (home/"hooks.json").write_bytes(json.dumps(config).encode())
        env = dict(os.environ,CODEX_HOME=str(home))
        version = subprocess.run([codex,"--version"],cwd=root,env=env,encoding="utf8",
                                 capture_output=True,check=True,timeout=10).stdout.strip()
        with subprocess.Popen([codex,"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-hook-lab","version":"1"}},1)
                client.request("initialized")
                response=client.request("hooks/list",{"cwd":str(root)},2)
                group,=response["data"]
                assert not group["errors"] and not group["warnings"]
                registered = {hook["eventName"]:hook for hook in group["hooks"]}
                check("registry", {"events":list(config["hooks"]),"timeouts":[5,4]},
                    "List the actual temporary hook registry over stdio",
                    [["preToolUse","command",5,"^Bash$"],["stop","command",4,None]],
                    [[row["eventName"],row["handlerType"],row["timeoutSec"],row["matcher"]]
                     for row in (registered["preToolUse"],registered["stop"])])
                check("trust","New hooks in a fresh profile",
                      "Read the real trust state without sending a turn request",
                      ["untrusted","untrusted"],[registered[name]["trustStatus"] for name in ("preToolUse","stop")])
            finally:
                client.close()
            assert process.returncode == 0

        def run_hook(data):
            result=subprocess.run([sys.executable,"-I","-B",str(handler)],cwd=root,input=json.dumps(data),
                                  capture_output=True,text=True,encoding="utf8",check=True,timeout=5)
            return json.loads(result.stdout)

        data = [{"hook_event_name":"PreToolUse","tool_input":{"command":command}}
                for command in ("fixture-read","fixture-write protected")]
        outputs=[run_hook(item) for item in data]
        check("script_filter",data,"Feed a real child process two locally generated tool events",
              ["继续","拒绝"],["拒绝" if row.get("hookSpecificOutput",{}).get("permissionDecision")=="deny" else "继续"
                               for row in outputs])
        data = [{"hook_event_name":"Stop","stop_hook_active":active} for active in (False,True)]
        outputs=[run_hook(item) for item in data]
        check("script_stop",data,"Exercise the script once before and once after an earlier continuation",
              ["补充检查","结束"],["补充检查" if row.get("decision")=="block" else "结束" for row in outputs])
    print(json.dumps(dict(version={"python":sys.version.split()[0],"codex":version},
                          codex_sha256=sha256(Path(codex).read_bytes()).hexdigest(),
                          handler_sha256=sha256(HANDLER.encode()).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-hooks/hooks_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 hooks_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Codex 教程

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip

下载课程关联工程包:Codex 教程

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a106.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习