#!/usr/bin/env python3 """ s04: Hooks — 把扩展逻辑从循环中移出,挂到 Hooks 上。 用户输入问题 │ ▼ ┌──────────────────┐ │ UserPromptSubmit │ ── LLM 调用前触发 trigger_hooks() └────────┬─────────┘ ▼ ┌────────────┐ ┌─────────────────────────────┐ │ messages │────▶│ LLM (stop_reason=tool_use?)│ └────────────┘ │ 否 ──▶ Stop hooks ──▶ 退出 │ │ 是 ──▶ tool_use block ──┐ │ └────────────────────────────┘ │ ▼ ┌──────────────────┐ │ trigger_hooks() │ │ PreToolUse: │ │ permission_hook │ │ log_hook │ └───────┬──────────┘ │ (未被拦截) ┌───────▼──────────┐ │ TOOL_HANDLERS[x] │ └───────┬──────────┘ │ ┌───────▼──────────┐ │ trigger_hooks() │ │ PostToolUse: │ │ large_output │ └───────┬──────────┘ │ results ──▶ 回到 messages """ import os, subprocess from pathlib import Path try: import readline readline.parse_and_bind('set bind-tty-special-chars off') readline.parse_and_bind('set input-meta on') readline.parse_and_bind('set output-meta on') readline.parse_and_bind('set convert-meta off') except ImportError: pass from anthropic import Anthropic from dotenv import load_dotenv load_dotenv(override=True) if os.getenv("ANTHROPIC_BASE_URL"): os.environ.pop("ANTHROPIC_AUTH_TOKEN", None) WORKDIR = Path.cwd() client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL")) MODEL = os.environ["MODEL_ID"] SYSTEM = f"你是位于 {WORKDIR}. 使用工具解决任务。直接行动,不要只解释。" # ═══════════════════════════════════════════════════════════ # 来自 s02-s03 : 工具实现 # ═══════════════════════════════════════════════════════════ def run_bash(command: str) -> str: try: r = subprocess.run(command, shell=True, cwd=WORKDIR, capture_output=True, text=True, timeout=120) out = (r.stdout + r.stderr).strip() return out[:50000] if out else "(无输出)" except subprocess.TimeoutExpired: return "错误:执行超时(120 秒)" def run_read(path: str, limit: int | None = None) -> str: try: file_path = (WORKDIR / path).resolve() lines = file_path.read_text().splitlines() if limit and limit < len(lines): lines = lines[:limit] + [f"... ({len(lines) - limit} 行更多内容)"] return "\n".join(lines) except Exception as e: return f"错误:{e}" def run_write(path: str, content: str) -> str: try: file_path = (WORKDIR / path).resolve() file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(content) return f"已写入 {len(content)} 字节到 {path}" except Exception as e: return f"错误:{e}" def run_edit(path: str, old_text: str, new_text: str) -> str: try: file_path = (WORKDIR / path).resolve() text = file_path.read_text() if old_text not in text: return f"错误:在文件中未找到目标文本:{path}" file_path.write_text(text.replace(old_text, new_text, 1)) return f"已编辑 {path}" except Exception as e: return f"错误:{e}" def run_glob(pattern: str) -> str: import glob as g try: results = [] for match in g.glob(pattern, root_dir=WORKDIR): if (WORKDIR / match).resolve().is_relative_to(WORKDIR): results.append(match) return "\n".join(results) if results else "(无匹配)" except Exception as e: return f"错误:{e}" TOOLS = [ {"name": "bash", "description": "运行一条 shell 命令。", "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}, {"name": "read_file", "description": "读取文件内容。", "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "limit": {"type": "integer"}}, "required": ["path"]}}, {"name": "write_file", "description": "向文件写入内容。", "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}, {"name": "edit_file", "description": "在文件中替换一次完全匹配的文本。", "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}}, "required": ["path", "old_text", "new_text"]}}, {"name": "glob", "description": "查找匹配 glob 模式的文件。", "input_schema": {"type": "object", "properties": {"pattern": {"type": "string"}}, "required": ["pattern"]}}, ] TOOL_HANDLERS = { "bash": run_bash, "read_file": run_read, "write_file": run_write, "edit_file": run_edit, "glob": run_glob, } # ═══════════════════════════════════════════════════════════ # 新增于 s04: Hook 系统 (s03 权限逻辑现在通过 Hooks 实现) # ═══════════════════════════════════════════════════════════ HOOKS = {"UserPromptSubmit": [], "PreToolUse": [], "PostToolUse": [], "Stop": []} def register_hook(event: str, callback): HOOKS[event].append(callback) def trigger_hooks(event: str, *args): for callback in HOOKS[event]: result = callback(*args) if result is not None: # 教学快捷方式:拦截这个工具调用 return result return None # s03 权限检查逻辑,现在封装成 Hook DENY_LIST = ["rm -rf /", "sudo", "shutdown", "reboot", "mkfs", "dd if="] DESTRUCTIVE = ["rm ", "> /etc/", "chmod 777"] def permission_hook(block): """PreToolUse: s03 check_permission() logic moved here.""" if block.name == "bash": for pattern in DENY_LIST: if pattern in block.input.get("command", ""): print(f"\n\033[31m⛔ 已拦截:'{pattern}'\033[0m") return "被拒绝列表拒绝授权" for kw in DESTRUCTIVE: if kw in block.input.get("command", ""): print(f"\n\033[33m⚠ 可能具有破坏性的命令\033[0m") print(f" 工具:{block.name}({block.input})") choice = input(" 是否允许?[y/N] ").strip().lower() if choice not in ("y", "yes"): return "用户拒绝授权" if block.name in ("read_file", "write_file", "edit_file"): path = block.input.get("path", "") if not (WORKDIR / path).resolve().is_relative_to(WORKDIR): print(f"\n\033[33m⚠ 访问工作区外部路径\033[0m") print(f" 工具:{block.name}({block.input})") choice = input(" 是否允许?[y/N] ").strip().lower() if choice not in ("y", "yes"): return "用户拒绝授权" return None def log_hook(block): """PreToolUse: log every tool call.""" args_preview = str(list(block.input.values())[:2])[:60] print(f"\033[90m[HOOK] {block.name}({args_preview})\033[0m") return None def large_output_hook(block, output): """PostToolUse: warn on large output.""" if len(str(output)) > 100000: print(f"\033[33m[HOOK] ⚠ 来自以下工具的大输出:{block.name}: {len(str(output))} 个字符\033[0m") return None # UserPromptSubmit Hook:在用户输入到达 LLM 前记录它 def context_inject_hook(query: str): print(f"\033[90m[HOOK] UserPromptSubmit: 工作目录:{WORKDIR}\033[0m") return None # Stop Hook:在循环即将退出时打印摘要 def summary_hook(messages: list): tool_count = sum(1 for m in messages for b in (m.get("content") if isinstance(m.get("content"), list) else []) if isinstance(b, dict) and b.get("type") == "tool_result") print(f"\033[90m[HOOK] Stop:会话使用了 {tool_count} 次工具调用\033[0m") return None register_hook("UserPromptSubmit", context_inject_hook) register_hook("PreToolUse", permission_hook) register_hook("PreToolUse", log_hook) register_hook("PostToolUse", large_output_hook) register_hook("Stop", summary_hook) # ═══════════════════════════════════════════════════════════ # agent_loop — 与 s03 结构相同,但没有硬编码检查 # s03: if not check_permission(block): ... # s04: if trigger_hooks("PreToolUse", block): ... # ═══════════════════════════════════════════════════════════ def agent_loop(messages: list): while True: response = client.messages.create( model=MODEL, system=SYSTEM, messages=messages, tools=TOOLS, max_tokens=8000, ) messages.append({"role": "assistant", "content": response.content}) if response.stop_reason != "tool_use": force = trigger_hooks("Stop", messages) if force: messages.append({"role": "user", "content": force}) continue return results = [] for block in response.content: if block.type != "tool_use": continue # s04 变化: Hook 替代硬编码的 check_permission() blocked = trigger_hooks("PreToolUse", block) if blocked: results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(blocked)}) continue handler = TOOL_HANDLERS.get(block.name) output = handler(**block.input) if handler else f"未知工具:{block.name}" trigger_hooks("PostToolUse", block, output) # s04: 后置 Hook results.append({"type": "tool_result", "tool_use_id": block.id, "content": output}) messages.append({"role": "user", "content": results}) if __name__ == "__main__": print("s04: Hooks — 扩展逻辑挂到 Hooks 上,循环保持干净") print("输入问题后按回车。输入 q 退出。\n") history = [] while True: try: query = input("\033[36ms04 >> \033[0m") except (EOFError, KeyboardInterrupt): break if query.strip().lower() in ("q", "exit", ""): break trigger_hooks("UserPromptSubmit", query) history.append({"role": "user", "content": query}) agent_loop(history) for block in history[-1]["content"]: if getattr(block, "type", None) == "text": print(block.text) print()