code.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. #!/usr/bin/env python3
  2. """
  3. s06: 子 Agent — 用全新的 messages[] 启动子 Agent,实现上下文隔离。
  4. 父 Agent 子 Agent
  5. +------------------+ +------------------+
  6. | messages=[...] | | messages=[task] | <-- 全新上下文
  7. | | 分发 | |
  8. | tool: task | ---------------> | 自己的 while 循环 |
  9. | prompt="..." | | bash/read/... |
  10. | | 只返回摘要 | (最多 30 轮) |
  11. | result = "..." | <--------------- | 返回最后文本 |
  12. +------------------+ +------------------+
  13. ^ |
  14. | 中间结果会被丢弃 |
  15. +--------------------------------------+
  16. 子 Agent 工具:bash、read、write、edit、glob(没有 task,避免递归)
  17. 相对 s05 的变化:
  18. + task 工具 + 使用全新 messages[] 的 spawn_subagent()
  19. + 安全上限:每个子 Agent 最多 30 轮
  20. + extract_text() 辅助函数
  21. 子 Agent 不能再启动子子 Agent(sub_tools 里没有 task 工具)。
  22. 主循环不变:task 通过 TOOL_HANDLERS 自动分发。
  23. 运行: python s06_subagent/code.py
  24. 需要: pip install anthropic python-dotenv + .env 中配置 ANTHROPIC_API_KEY
  25. """
  26. import ast, json, os, subprocess
  27. from pathlib import Path
  28. try:
  29. import readline
  30. readline.parse_and_bind('set bind-tty-special-chars off')
  31. except ImportError:
  32. pass
  33. from anthropic import Anthropic
  34. from dotenv import load_dotenv
  35. load_dotenv(override=True)
  36. if os.getenv("ANTHROPIC_BASE_URL"):
  37. os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
  38. WORKDIR = Path.cwd()
  39. client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
  40. MODEL = os.environ["MODEL_ID"]
  41. CURRENT_TODOS: list[dict] = []
  42. SYSTEM = (
  43. f"你是位于 {WORKDIR}. "
  44. "遇到复杂子问题时,使用 task 工具启动一个子 Agent。"
  45. )
  46. # s06: 子 Agent 使用自己的系统提示词 — 没有 task,不递归
  47. SUB_SYSTEM = (
  48. f"你是位于 {WORKDIR}. "
  49. "完成交给你的任务,然后返回简洁摘要。"
  50. "不要继续委派。"
  51. )
  52. # ═══════════════════════════════════════════════════════════
  53. # 来自 s02-s05 (未改动): 工具实现
  54. # ═══════════════════════════════════════════════════════════
  55. def safe_path(p: str) -> Path:
  56. path = (WORKDIR / p).resolve()
  57. if not path.is_relative_to(WORKDIR):
  58. raise ValueError(f"路径逃逸出工作区:{p}")
  59. return path
  60. def run_bash(command: str) -> str:
  61. try:
  62. r = subprocess.run(command, shell=True, cwd=WORKDIR,
  63. capture_output=True, text=True, timeout=120)
  64. out = (r.stdout + r.stderr).strip()
  65. return out[:50000] if out else "(无输出)"
  66. except subprocess.TimeoutExpired:
  67. return "错误:执行超时(120 秒)"
  68. def run_read(path: str, limit: int | None = None) -> str:
  69. try:
  70. lines = safe_path(path).read_text().splitlines()
  71. if limit and limit < len(lines):
  72. lines = lines[:limit] + [f"... ({len(lines) - limit} 行更多内容)"]
  73. return "\n".join(lines)
  74. except Exception as e:
  75. return f"错误:{e}"
  76. def run_write(path: str, content: str) -> str:
  77. try:
  78. file_path = safe_path(path)
  79. file_path.parent.mkdir(parents=True, exist_ok=True)
  80. file_path.write_text(content)
  81. return f"已写入 {len(content)} 字节到 {path}"
  82. except Exception as e:
  83. return f"错误:{e}"
  84. def run_edit(path: str, old_text: str, new_text: str) -> str:
  85. try:
  86. file_path = safe_path(path)
  87. text = file_path.read_text()
  88. if old_text not in text:
  89. return f"错误:在文件中未找到目标文本:{path}"
  90. file_path.write_text(text.replace(old_text, new_text, 1))
  91. return f"已编辑 {path}"
  92. except Exception as e:
  93. return f"错误:{e}"
  94. def run_glob(pattern: str) -> str:
  95. import glob as g
  96. try:
  97. results = []
  98. for match in g.glob(pattern, root_dir=WORKDIR):
  99. if (WORKDIR / match).resolve().is_relative_to(WORKDIR):
  100. results.append(match)
  101. return "\n".join(results) if results else "(无匹配)"
  102. except Exception as e:
  103. return f"错误:{e}"
  104. def _normalize_todos(todos):
  105. if isinstance(todos, str):
  106. try:
  107. todo_list = json.loads(todos)
  108. except json.JSONDecodeError:
  109. try:
  110. todo_list = ast.literal_eval(todos)
  111. except (SyntaxError, ValueError):
  112. return None, "错误:todos 必须是列表或 JSON 数组字符串"
  113. if not isinstance(todos, list):
  114. return None, "错误:todos 必须是列表"
  115. for i, t in enumerate(todos):
  116. if not isinstance(t, dict):
  117. return None, f"错误:todos[{i}] 必须是对象"
  118. if "content" not in t or "status" not in t:
  119. return None, f"错误:todos[{i}] 缺少 'content' 或 'status'"
  120. if t["status"] not in ("pending", "in_progress", "completed"):
  121. return None, f"错误:todos[{i}] 包含无效状态 '{t['status']}'"
  122. return todo_list, None
  123. def run_todo_write(todos: list) -> str:
  124. global CURRENT_TODOS
  125. todo_list, error = _normalize_todos(todos)
  126. if error:
  127. return error
  128. CURRENT_TODOS = todo_list
  129. lines = ["\n\033[33m## 当前任务\033[0m"]
  130. for t in CURRENT_TODOS:
  131. icon = {"pending": " ", "in_progress": "\033[36m▸\033[0m", "completed": "\033[32m✓\033[0m"}[t["status"]]
  132. lines.append(f" [{icon}] {t['content']}")
  133. print("\n".join(lines))
  134. return f"已更新 {len(CURRENT_TODOS)} 个任务"
  135. TOOLS = [
  136. {"name": "bash", "description": "运行一条 shell 命令。",
  137. "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}},
  138. {"name": "read_file", "description": "读取文件内容。",
  139. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "limit": {"type": "integer"}}, "required": ["path"]}},
  140. {"name": "write_file", "description": "向文件写入内容。",
  141. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}},
  142. {"name": "edit_file", "description": "在文件中替换一次完全匹配的文本。",
  143. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}}, "required": ["path", "old_text", "new_text"]}},
  144. {"name": "glob", "description": "查找匹配 glob 模式的文件。",
  145. "input_schema": {"type": "object", "properties": {"pattern": {"type": "string"}}, "required": ["pattern"]}},
  146. {"name": "todo_write", "description": "为当前编码会话创建并维护任务清单。",
  147. "input_schema": {"type": "object", "properties": {"todos": {"type": "array", "items": {"type": "object", "properties": {"content": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "in_progress", "completed"]}}, "required": ["content", "status"]}}}, "required": ["todos"]}},
  148. ]
  149. TOOL_HANDLERS = {
  150. "bash": run_bash, "read_file": run_read, "write_file": run_write,
  151. "edit_file": run_edit, "glob": run_glob, "todo_write": run_todo_write,
  152. }
  153. # ═══════════════════════════════════════════════════════════
  154. # 新增于 s06: 子 Agent — 全新 messages[],只返回摘要
  155. # ═══════════════════════════════════════════════════════════
  156. SUB_TOOLS = [
  157. {"name": "bash", "description": "运行一条 shell 命令。",
  158. "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}},
  159. {"name": "read_file", "description": "读取文件内容。",
  160. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}},
  161. {"name": "write_file", "description": "向文件写入内容。",
  162. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}},
  163. {"name": "edit_file", "description": "在文件中替换一次完全匹配的文本。",
  164. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}}, "required": ["path", "old_text", "new_text"]}},
  165. {"name": "glob", "description": "查找匹配 glob 模式的文件。",
  166. "input_schema": {"type": "object", "properties": {"pattern": {"type": "string"}}, "required": ["pattern"]}},
  167. ]
  168. # 没有 "task" 工具 — 防止递归启动
  169. SUB_HANDLERS = {
  170. "bash": run_bash, "read_file": run_read, "write_file": run_write,
  171. "edit_file": run_edit, "glob": run_glob,
  172. }
  173. def extract_text(content) -> str:
  174. """从消息内容块中提取文本。"""
  175. if not isinstance(content, list):
  176. return str(content)
  177. return "\n".join(getattr(b, "text", "") for b in content if getattr(b, "type", None) == "text")
  178. def spawn_subagent(description: str) -> str:
  179. """用全新的 messages[] 启动子 Agent,只返回摘要。"""
  180. print(f"\n\033[35m[子 Agent 已启动]\033[0m")
  181. messages = [{"role": "user", "content": description}] # 全新上下文
  182. for _ in range(30): # 安全上限
  183. response = client.messages.create(
  184. model=MODEL, system=SUB_SYSTEM,
  185. messages=messages, tools=SUB_TOOLS, max_tokens=8000,
  186. )
  187. messages.append({"role": "assistant", "content": response.content})
  188. if response.stop_reason != "tool_use":
  189. break
  190. results = []
  191. for block in response.content:
  192. if block.type == "tool_use":
  193. # 问题 1:子 Agent 也运行 Hooks(权限同样生效)
  194. blocked = trigger_hooks("PreToolUse", block)
  195. if blocked:
  196. results.append({"type": "tool_result", "tool_use_id": block.id,
  197. "content": str(blocked)})
  198. continue
  199. handler = SUB_HANDLERS.get(block.name)
  200. output = handler(**block.input) if handler else f"未知工具:{block.name}"
  201. trigger_hooks("PostToolUse", block, output)
  202. print(f" \033[90m[sub] {block.name}: {str(output)[:100]}\033[0m")
  203. results.append({"type": "tool_result", "tool_use_id": block.id,
  204. "content": output})
  205. messages.append({"role": "user", "content": results})
  206. # 问题 5:如果在 tool_use 期间触发安全上限,则使用兜底逻辑
  207. result = extract_text(messages[-1]["content"])
  208. if not result:
  209. # 最后一条消息是 tool_result,向前查找 assistant 文本
  210. for msg in reversed(messages):
  211. if msg["role"] == "assistant":
  212. result = extract_text(msg["content"])
  213. if result:
  214. break
  215. if not result:
  216. result = "子 Agent 已等待 30 轮仍未给出最终回答,已停止。"
  217. print(f"\033[35m[子 Agent 已完成]\033[0m")
  218. return result # 只保留摘要,完整消息历史会被丢弃
  219. # 把 task 工具加入父 Agent 的工具列表
  220. TOOLS.append({
  221. "name": "task",
  222. "description": "启动一个子 Agent 处理复杂子任务。只返回最终结论。",
  223. "input_schema": {"type": "object", "properties": {"description": {"type": "string"}}, "required": ["description"]},
  224. })
  225. TOOL_HANDLERS["task"] = spawn_subagent
  226. # ═══════════════════════════════════════════════════════════
  227. # 来自 s04 (未改动): Hook 系统
  228. # ═══════════════════════════════════════════════════════════
  229. HOOKS = {"UserPromptSubmit": [], "PreToolUse": [], "PostToolUse": [], "Stop": []}
  230. def register_hook(event: str, callback):
  231. HOOKS[event].append(callback)
  232. def trigger_hooks(event: str, *args):
  233. for callback in HOOKS[event]:
  234. result = callback(*args)
  235. if result is not None:
  236. return result
  237. return None
  238. DENY_LIST = ["rm -rf /", "sudo", "shutdown", "reboot", "mkfs", "dd if="]
  239. def permission_hook(block):
  240. """PreToolUse:检查拒绝列表。"""
  241. if block.name == "bash":
  242. for p in DENY_LIST:
  243. if p in block.input.get("command", ""):
  244. print(f"\n\033[31m⛔ 已拦截:'{p}'\033[0m")
  245. return "权限被拒绝"
  246. return None
  247. def log_hook(block):
  248. """PreToolUse:记录工具调用。"""
  249. print(f"\033[90m[钩子] {block.name}\033[0m")
  250. return None
  251. def context_inject_hook(query: str):
  252. """UserPromptSubmit:记录当前工作目录。"""
  253. print(f"\033[90m[钩子] UserPromptSubmit: 工作目录:{WORKDIR}\033[0m")
  254. return None
  255. def summary_hook(messages: list):
  256. """Stop:打印工具调用次数。"""
  257. tool_count = sum(1 for m in messages
  258. for b in (m.get("content") if isinstance(m.get("content"), list) else [])
  259. if isinstance(b, dict) and b.get("type") == "tool_result")
  260. print(f"\033[90m[钩子] Stop:会话使用了 {tool_count} 次工具调用\033[0m")
  261. return None
  262. register_hook("UserPromptSubmit", context_inject_hook)
  263. register_hook("PreToolUse", permission_hook)
  264. register_hook("PreToolUse", log_hook)
  265. register_hook("Stop", summary_hook)
  266. # ═══════════════════════════════════════════════════════════
  267. # agent_loop — 与以下相同: s05 + 催办提醒, task 会自动分发
  268. # ═══════════════════════════════════════════════════════════
  269. def agent_loop(messages: list):
  270. rounds_since_todo = 0
  271. while True:
  272. # s05: 催办提醒
  273. if rounds_since_todo >= 3 and messages:
  274. messages.append({"role": "user",
  275. "content": "<reminder>请更新你的待办事项。</reminder>"})
  276. rounds_since_todo = 0
  277. response = client.messages.create(
  278. model=MODEL, system=SYSTEM, messages=messages,
  279. tools=TOOLS, max_tokens=8000,
  280. )
  281. messages.append({"role": "assistant", "content": response.content})
  282. if response.stop_reason != "tool_use":
  283. force = trigger_hooks("Stop", messages)
  284. if force:
  285. messages.append({"role": "user", "content": force})
  286. continue
  287. return
  288. rounds_since_todo += 1
  289. results = []
  290. for block in response.content:
  291. if block.type != "tool_use":
  292. continue
  293. blocked = trigger_hooks("PreToolUse", block)
  294. if blocked:
  295. results.append({"type": "tool_result", "tool_use_id": block.id,
  296. "content": str(blocked)})
  297. continue
  298. handler = TOOL_HANDLERS.get(block.name)
  299. output = handler(**block.input) if handler else f"未知工具:{block.name}"
  300. trigger_hooks("PostToolUse", block, output)
  301. if block.name == "todo_write":
  302. rounds_since_todo = 0
  303. results.append({"type": "tool_result", "tool_use_id": block.id,
  304. "content": output})
  305. messages.append({"role": "user", "content": results})
  306. if __name__ == "__main__":
  307. print("s06: 子 Agent — 使用全新上下文启动,只返回摘要")
  308. print("输入问题后按回车。输入 q 退出。\n")
  309. history = []
  310. while True:
  311. try:
  312. query = input("\033[36ms06 >> \033[0m")
  313. except (EOFError, KeyboardInterrupt):
  314. break
  315. if query.strip().lower() in ("q", "exit", ""):
  316. break
  317. trigger_hooks("UserPromptSubmit", query)
  318. history.append({"role": "user", "content": query})
  319. agent_loop(history)
  320. for block in history[-1]["content"]:
  321. if getattr(block, "type", None) == "text":
  322. print(block.text)
  323. print()