code.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. #!/usr/bin/env python3
  2. """
  3. s08_context_compact.py - 上下文压缩
  4. 在调用 LLM 前插入四层压缩流水线:
  5. L1: snip_compact — 消息数量 > 50 时裁掉中间消息
  6. L2: micro_compact — 用占位符替换旧的 tool_results
  7. L3: tool_result_budget — 把大型结果持久化到磁盘
  8. L4: compact_history — LLM 完整摘要(1 次 API 调用)
  9. 应急:reactive_compact — 当 API 仍然返回 prompt_too_long 时触发
  10. ┌─────────────────────────────────────────────────────────────┐
  11. │ messages[] │
  12. │ ↓ │
  13. │ L3 budget ─→ L1 snip ─→ L2 micro ─→ [token > threshold?] │
  14. │ ├─ 否 → LLM │
  15. │ └─ 是 → L4 summary │
  16. │ ↓ │
  17. │ LLM 调用 │
  18. │ [prompt_too_long?] │
  19. │ └─ 是 → reactive │
  20. └─────────────────────────────────────────────────────────────┘
  21. 核心原则:先便宜,后昂贵。
  22. 执行顺序匹配 CC 源码:budget → snip → micro → auto。
  23. 基于 s07(技能加载)构建。用法:
  24. python s08_context_compact/code.py
  25. 需要: pip install anthropic python-dotenv + .env 中配置 ANTHROPIC_API_KEY
  26. """
  27. import ast, json, os, subprocess, time
  28. from pathlib import Path
  29. try:
  30. import readline
  31. readline.parse_and_bind('set bind-tty-special-chars off')
  32. except ImportError:
  33. pass
  34. from anthropic import Anthropic
  35. from dotenv import load_dotenv
  36. load_dotenv(override=True)
  37. if os.getenv("ANTHROPIC_BASE_URL"):
  38. os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
  39. WORKDIR = Path.cwd()
  40. SKILLS_DIR = WORKDIR / "skills"
  41. TRANSCRIPT_DIR = WORKDIR / ".transcripts"
  42. TOOL_RESULTS_DIR = WORKDIR / ".task_outputs" / "tool-results"
  43. client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
  44. MODEL = os.environ["MODEL_ID"]
  45. CURRENT_TODOS: list[dict] = []
  46. # s07: 技能目录扫描 (继承自 s07)
  47. def _parse_frontmatter(text: str) -> tuple[dict, str]:
  48. if not text.startswith("---"):
  49. return {}, text
  50. parts = text.split("---", 2)
  51. if len(parts) < 3:
  52. return {}, text
  53. meta = {}
  54. for line in parts[1].strip().splitlines():
  55. if ":" in line:
  56. k, v = line.split(":", 1)
  57. meta[k.strip()] = v.strip().strip('"').strip("'")
  58. return meta, parts[2].strip()
  59. SKILL_REGISTRY: dict[str, dict] = {}
  60. def _scan_skills():
  61. if not SKILLS_DIR.exists():
  62. return
  63. for d in sorted(SKILLS_DIR.iterdir()):
  64. if not d.is_dir():
  65. continue
  66. manifest = d / "SKILL.md"
  67. if manifest.exists():
  68. raw = manifest.read_text()
  69. meta, body = _parse_frontmatter(raw)
  70. name = meta.get("name", d.name)
  71. desc = meta.get("description", raw.split("\n")[0].lstrip("#").strip())
  72. SKILL_REGISTRY[name] = {"name": name, "description": desc, "content": raw}
  73. _scan_skills()
  74. def list_skills() -> str:
  75. if not SKILL_REGISTRY:
  76. return "(未找到技能)"
  77. return "\n".join(f"- **{s['name']}**: {s['description']}" for s in SKILL_REGISTRY.values())
  78. def load_skill(name: str) -> str:
  79. skill = SKILL_REGISTRY.get(name)
  80. if not skill:
  81. return f"未找到技能:{name}"
  82. return skill["content"]
  83. # s08: SYSTEM 包含技能目录 (继承自 s07 build_system)
  84. def build_system() -> str:
  85. catalog = list_skills()
  86. return (
  87. f"你是位于 {WORKDIR}. "
  88. f"可用技能:\n{catalog}\n"
  89. "需要时使用 load_skill 获取完整详情。"
  90. )
  91. SYSTEM = build_system()
  92. # s08: 子 Agent 使用自己的系统提示词 — 不压缩、不加载技能
  93. SUB_SYSTEM = (
  94. f"你是位于 {WORKDIR}. "
  95. "完成交给你的任务,然后返回简洁摘要。"
  96. "不要继续委派。"
  97. )
  98. # ═══════════════════════════════════════════════════════════
  99. # 来自 s02-s07 (未改动): 基础工具
  100. # ═══════════════════════════════════════════════════════════
  101. def safe_path(p: str) -> Path:
  102. path = (WORKDIR / p).resolve()
  103. if not path.is_relative_to(WORKDIR):
  104. raise ValueError(f"路径逃逸出工作区:{p}")
  105. return path
  106. def run_bash(command: str) -> str:
  107. try:
  108. r = subprocess.run(
  109. command,
  110. shell=True,
  111. cwd=WORKDIR,
  112. capture_output=True,
  113. text=True,
  114. timeout=120,
  115. )
  116. out = (r.stdout + r.stderr).strip()
  117. if out:
  118. return out[:50000]
  119. return "(无输出)"
  120. except subprocess.TimeoutExpired:
  121. return "错误:执行超时(120 秒)"
  122. def run_read(path: str, limit: int | None = None) -> str:
  123. try:
  124. lines = safe_path(path).read_text().splitlines()
  125. if limit and limit < len(lines):
  126. lines = lines[:limit] + [f"... ({len(lines) - limit} 行更多内容)"]
  127. return "\n".join(lines)
  128. except Exception as e:
  129. return f"错误:{e}"
  130. def run_write(path: str, content: str) -> str:
  131. try:
  132. file_path = safe_path(path)
  133. file_path.parent.mkdir(parents=True, exist_ok=True)
  134. file_path.write_text(content)
  135. return f"已写入 {len(content)} 字节到 {path}"
  136. except Exception as e:
  137. return f"错误:{e}"
  138. def run_edit(path: str, old_text: str, new_text: str) -> str:
  139. try:
  140. file_path = safe_path(path)
  141. text = file_path.read_text()
  142. if old_text not in text:
  143. return f"错误:在文件中未找到目标文本:{path}"
  144. file_path.write_text(text.replace(old_text, new_text, 1))
  145. return f"已编辑 {path}"
  146. except Exception as e:
  147. return f"错误:{e}"
  148. def run_glob(pattern: str) -> str:
  149. import glob as g
  150. try:
  151. results = []
  152. for match in g.glob(pattern, root_dir=WORKDIR):
  153. if (WORKDIR / match).resolve().is_relative_to(WORKDIR):
  154. results.append(match)
  155. if results:
  156. return "\n".join(results)
  157. return "(无匹配)"
  158. except Exception as e:
  159. return f"错误:{e}"
  160. def _normalize_todos(todos):
  161. if isinstance(todos, str):
  162. try:
  163. todo_list = json.loads(todos)
  164. except json.JSONDecodeError:
  165. try:
  166. todo_list = ast.literal_eval(todos)
  167. except (SyntaxError, ValueError):
  168. return None, "错误:todos 必须是列表或 JSON 数组字符串"
  169. else:
  170. todo_list = todos
  171. if not isinstance(todo_list, list):
  172. return None, "错误:todos 必须是列表"
  173. for i, t in enumerate(todo_list):
  174. if not isinstance(t, dict):
  175. return None, f"错误:todos[{i}] 必须是对象"
  176. if "content" not in t or "status" not in t:
  177. return None, f"错误:todos[{i}] 缺少 'content' 或 'status'"
  178. if t["status"] not in ("pending", "in_progress", "completed"):
  179. return None, f"错误:todos[{i}] 包含无效状态 '{t['status']}'"
  180. return todo_list, None
  181. def run_todo_write(todos: list) -> str:
  182. global CURRENT_TODOS
  183. todo_list, error = _normalize_todos(todos)
  184. if error:
  185. return error
  186. CURRENT_TODOS = todo_list
  187. lines = ["\n\033[33m## 当前任务\033[0m"]
  188. for t in CURRENT_TODOS:
  189. icon = {"pending": " ", "in_progress": "\033[36m▸\033[0m", "completed": "\033[32m✓\033[0m"}[t["status"]]
  190. lines.append(f" [{icon}] {t['content']}")
  191. print("\n".join(lines))
  192. return f"已更新 {len(CURRENT_TODOS)} 个任务"
  193. def extract_text(content) -> str:
  194. if not isinstance(content, list):
  195. return str(content)
  196. texts = []
  197. for block in content:
  198. if getattr(block, "type", None) == "text":
  199. texts.append(getattr(block, "text", ""))
  200. return "\n".join(texts)
  201. # ═══════════════════════════════════════════════════════════
  202. # 来自 s06-s07 (未改动): 子 Agent
  203. # ═══════════════════════════════════════════════════════════
  204. SUB_TOOLS = [
  205. {"name": "bash", "description": "运行一条 shell 命令。",
  206. "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}},
  207. {"name": "read_file", "description": "读取文件内容。",
  208. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}},
  209. {"name": "write_file", "description": "向文件写入内容。",
  210. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}},
  211. {"name": "edit_file", "description": "在文件中替换一次完全匹配的文本。",
  212. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}}, "required": ["path", "old_text", "new_text"]}},
  213. {"name": "glob", "description": "查找匹配 glob 模式的文件。",
  214. "input_schema": {"type": "object", "properties": {"pattern": {"type": "string"}}, "required": ["pattern"]}},
  215. ]
  216. SUB_HANDLERS = {"bash": run_bash, "read_file": run_read, "write_file": run_write,
  217. "edit_file": run_edit, "glob": run_glob}
  218. def spawn_subagent(description: str) -> str:
  219. print(f"\n\033[35m[子 Agent 已启动]\033[0m")
  220. messages = [{"role": "user", "content": description}]
  221. for _ in range(30):
  222. response = client.messages.create(
  223. model=MODEL,
  224. system=SUB_SYSTEM,
  225. messages=messages,
  226. tools=SUB_TOOLS,
  227. max_tokens=8000,
  228. )
  229. messages.append({"role": "assistant", "content": response.content})
  230. if response.stop_reason != "tool_use":
  231. break
  232. results = []
  233. for block in response.content:
  234. if block.type == "tool_use":
  235. blocked = trigger_hooks("PreToolUse", block)
  236. if blocked:
  237. results.append({"type": "tool_result", "tool_use_id": block.id,
  238. "content": str(blocked)})
  239. continue
  240. handler = SUB_HANDLERS.get(block.name)
  241. output = handler(**block.input) if handler else f"未知工具:{block.name}"
  242. trigger_hooks("PostToolUse", block, output)
  243. print(f" \033[90m[sub] {block.name}: {str(output)[:100]}\033[0m")
  244. results.append({
  245. "type": "tool_result",
  246. "tool_use_id": block.id,
  247. "content": output,
  248. })
  249. messages.append({"role": "user", "content": results})
  250. result = extract_text(messages[-1]["content"])
  251. if not result:
  252. for msg in reversed(messages):
  253. if msg["role"] == "assistant":
  254. result = extract_text(msg["content"])
  255. if result:
  256. break
  257. if not result:
  258. result = "子 Agent 已等待 30 轮仍未给出最终回答,已停止。"
  259. print(f"\033[35m[子 Agent 已完成]\033[0m")
  260. return result
  261. # ═══════════════════════════════════════════════════════════
  262. # 新增于 s08: 四层压缩流水线
  263. # ═══════════════════════════════════════════════════════════
  264. # 估算消息体超过这个大小时,触发 LLM 摘要压缩。
  265. CONTEXT_LIMIT = 50000
  266. # micro_compact 中保留最近几个完整 tool_result,旧结果会被占位符替换。
  267. KEEP_RECENT = 3
  268. # 单个工具输出超过这个大小时,写入磁盘,只把预览留在上下文里。
  269. PERSIST_THRESHOLD = 30000
  270. def estimate_size(msgs): return len(str(msgs))
  271. def _block_type(block):
  272. return block.get("type") if isinstance(block, dict) else getattr(block, "type", None)
  273. def _message_has_tool_use(msg):
  274. if msg.get("role") != "assistant":
  275. return False
  276. content = msg.get("content")
  277. if not isinstance(content, list):
  278. return False
  279. return any(_block_type(block) == "tool_use" for block in content)
  280. def _is_tool_result_message(msg):
  281. if msg.get("role") != "user":
  282. return False
  283. content = msg.get("content")
  284. if not isinstance(content, list):
  285. return False
  286. return any(isinstance(block, dict) and block.get("type") == "tool_result"
  287. for block in content)
  288. # L1: snipCompact — 裁剪中间消息
  289. def snip_compact(messages, max_messages=50):
  290. if len(messages) <= max_messages: return messages
  291. keep_head, keep_tail = 3, max_messages - 3
  292. head_end, tail_start = keep_head, len(messages) - keep_tail
  293. if head_end > 0 and _message_has_tool_use(messages[head_end - 1]):
  294. while head_end < len(messages) and _is_tool_result_message(messages[head_end]):
  295. head_end += 1
  296. if (tail_start > 0 and tail_start < len(messages)
  297. and _is_tool_result_message(messages[tail_start])
  298. and _message_has_tool_use(messages[tail_start - 1])):
  299. tail_start -= 1
  300. if head_end >= tail_start:
  301. return messages
  302. snipped = tail_start - head_end
  303. return messages[:head_end] + [{"role": "user", "content": f"[已省略中间 {snipped} 条消息]"}] + messages[tail_start:]
  304. # L2: microCompact — 旧结果占位符
  305. def collect_tool_results(messages):
  306. blocks = []
  307. for mi, msg in enumerate(messages):
  308. if msg.get("role") != "user" or not isinstance(msg.get("content"), list): continue
  309. for bi, block in enumerate(msg["content"]):
  310. if isinstance(block, dict) and block.get("type") == "tool_result":
  311. blocks.append((mi, bi, block))
  312. return blocks
  313. def micro_compact(messages):
  314. tool_results = collect_tool_results(messages)
  315. if len(tool_results) <= KEEP_RECENT: return messages
  316. for _, _, block in tool_results[:-KEEP_RECENT]:
  317. if len(block.get("content", "")) > 120:
  318. block["content"] = "[早前工具结果已压缩。如有需要请重新运行。]"
  319. return messages
  320. # L3: toolResultBudget — 将大型结果持久化到磁盘
  321. def persist_large_output(tool_use_id, output):
  322. if len(output) <= PERSIST_THRESHOLD: return output
  323. TOOL_RESULTS_DIR.mkdir(parents=True, exist_ok=True)
  324. path = TOOL_RESULTS_DIR / f"{tool_use_id}.txt"
  325. if not path.exists(): path.write_text(output)
  326. return f"<persisted-output>\n完整输出:{path}\n预览:\n{output[:2000]}\n</persisted-output>"
  327. def tool_result_budget(messages, max_bytes=200_000):
  328. # 详细讲解见 代码讲解.md:L3 toolResultBudget。
  329. last = messages[-1] if messages else None
  330. if not last or last.get("role") != "user" or not isinstance(last.get("content"), list): return messages
  331. blocks = [(i, b) for i, b in enumerate(last["content"]) if isinstance(b, dict) and b.get("type") == "tool_result"]
  332. total = sum(len(str(b.get("content", ""))) for _, b in blocks)
  333. if total <= max_bytes: return messages
  334. ranked = sorted(blocks, key=lambda p: len(str(p[1].get("content", ""))), reverse=True)
  335. for _, block in ranked:
  336. if total <= max_bytes: break
  337. content = str(block.get("content", ""))
  338. if len(content) <= PERSIST_THRESHOLD: continue
  339. tid = block.get("tool_use_id", "unknown")
  340. block["content"] = persist_large_output(tid, content)
  341. # 替换掉一个大输出后,重新计算当前 tool_result 总大小。
  342. # 下一轮循环会根据新的 total 判断是否还需要继续处理。
  343. total = sum(len(str(b.get("content", ""))) for _, b in blocks)
  344. return messages
  345. # L4: autoCompact — LLM 完整摘要
  346. def write_transcript(messages):
  347. TRANSCRIPT_DIR.mkdir(parents=True, exist_ok=True)
  348. path = TRANSCRIPT_DIR / f"transcript_{int(time.time())}.jsonl"
  349. with path.open("w") as f:
  350. for msg in messages: f.write(json.dumps(msg, default=str) + "\n")
  351. return path
  352. def summarize_history(messages):
  353. conversation = json.dumps(messages, default=str)[:80000]
  354. prompt = ("总结这段编码 Agent 对话,以便继续工作。\n"
  355. "保留:1. 当前目标,2. 关键发现/决策,3. 已读/已改文件,"
  356. "4. 剩余工作,5. 用户约束。\n保持简洁但具体。\n\n" + conversation)
  357. response = client.messages.create(model=MODEL, messages=[{"role": "user", "content": prompt}], max_tokens=2000)
  358. return "\n".join(
  359. getattr(block, "text", "")
  360. for block in response.content
  361. if getattr(block, "type", None) == "text").strip() or "(空摘要)"
  362. def compact_history(messages):
  363. transcript_path = write_transcript(messages)
  364. print(f"[对话记录已保存:{transcript_path}]")
  365. summary = summarize_history(messages)
  366. return [{"role": "user", "content": f"[已压缩]\n\n{summary}"}]
  367. # 应急:reactiveCompact — API 错误时触发
  368. def reactive_compact(messages):
  369. transcript = write_transcript(messages)
  370. tail_start = max(0, len(messages) - 5)
  371. if (tail_start > 0 and tail_start < len(messages)
  372. and _is_tool_result_message(messages[tail_start])
  373. and _message_has_tool_use(messages[tail_start - 1])):
  374. tail_start -= 1
  375. summary = summarize_history(messages[:tail_start])
  376. return [{"role": "user", "content": f"[响应式压缩]\n\n{summary}"}, *messages[tail_start:]]
  377. # ═══════════════════════════════════════════════════════════
  378. # 来自 s07: 工具定义
  379. # ═══════════════════════════════════════════════════════════
  380. TOOLS = [
  381. {"name": "bash", "description": "运行一条 shell 命令。",
  382. "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}},
  383. {"name": "read_file", "description": "读取文件内容。",
  384. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "limit": {"type": "integer"}}, "required": ["path"]}},
  385. {"name": "write_file", "description": "向文件写入内容。",
  386. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}},
  387. {"name": "edit_file", "description": "在文件中替换一次完全匹配的文本。",
  388. "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}}, "required": ["path", "old_text", "new_text"]}},
  389. {"name": "glob", "description": "查找匹配 glob 模式的文件。",
  390. "input_schema": {"type": "object", "properties": {"pattern": {"type": "string"}}, "required": ["pattern"]}},
  391. {"name": "todo_write", "description": "为当前编码会话创建并维护任务清单。",
  392. "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"]}},
  393. {"name": "task", "description": "启动一个子 Agent 处理复杂子任务。只返回最终结论。",
  394. "input_schema": {"type": "object", "properties": {"description": {"type": "string"}}, "required": ["description"]}},
  395. {"name": "load_skill", "description": "按名称加载某个技能的完整内容。",
  396. "input_schema": {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}},
  397. # s08 变化: 新的 compact 工具 — 触发 compact_history,而不是空操作
  398. {"name": "compact", "description": "总结早前对话以释放上下文空间。",
  399. "input_schema": {"type": "object", "properties": {"focus": {"type": "string"}}}},
  400. ]
  401. TOOL_HANDLERS = {
  402. "bash": run_bash, "read_file": run_read, "write_file": run_write,
  403. "edit_file": run_edit, "glob": run_glob, "todo_write": run_todo_write,
  404. "task": spawn_subagent, "load_skill": load_skill,
  405. }
  406. # 来自 s04 (未改动): Hooks
  407. HOOKS = {"PreToolUse": [], "PostToolUse": []}
  408. def trigger_hooks(event, *args):
  409. for cb in HOOKS[event]:
  410. r = cb(*args)
  411. if r is not None: return r
  412. return None
  413. DENY_LIST = ["rm -rf /", "sudo", "shutdown"]
  414. def permission_hook(block):
  415. if block.name == "bash":
  416. for p in DENY_LIST:
  417. if p in block.input.get("command", ""): return "权限被拒绝"
  418. return None
  419. def log_hook(block):
  420. print(f"\033[90m[钩子] {block.name}\033[0m")
  421. return None
  422. HOOKS["PreToolUse"].append(permission_hook)
  423. HOOKS["PreToolUse"].append(log_hook)
  424. # ═══════════════════════════════════════════════════════════
  425. # agent_loop — s08 核心:调用 LLM 前运行压缩流水线
  426. # ═══════════════════════════════════════════════════════════
  427. MAX_REACTIVE_RETRIES = 1 # 响应式压缩的重试上限
  428. def agent_loop(messages: list):
  429. reactive_retries = 0
  430. while True:
  431. # s08 变化: 三个预处理器(0 次 API 调用,便宜的优先)
  432. # 顺序匹配 CC 源码:budget → snip → micro
  433. messages[:] = tool_result_budget(messages) # L3: 先持久化大型结果
  434. messages[:] = snip_compact(messages) # L1: 裁剪中间部分
  435. messages[:] = micro_compact(messages) # L2: 旧结果占位符
  436. # s08 变化: tokens 仍超过阈值 → LLM 摘要(1 次 API 调用)
  437. if estimate_size(messages) > CONTEXT_LIMIT:
  438. print("[自动压缩]")
  439. messages[:] = compact_history(messages)
  440. try:
  441. response = client.messages.create(model=MODEL, system=SYSTEM, messages=messages, tools=TOOLS, max_tokens=8000)
  442. reactive_retries = 0 # API 调用成功后重置
  443. except Exception as e:
  444. if ("prompt_too_long" in str(e).lower() or "token 过多" in str(e).lower()) and reactive_retries < MAX_REACTIVE_RETRIES:
  445. print("[响应式压缩]")
  446. messages[:] = reactive_compact(messages)
  447. reactive_retries += 1
  448. continue
  449. raise
  450. messages.append({"role": "assistant", "content": response.content})
  451. if response.stop_reason != "tool_use": return
  452. results = []
  453. for block in response.content:
  454. if block.type != "tool_use": continue
  455. print(f"\033[36m> {block.name}\033[0m")
  456. # s08: compact 工具触发 compact_history,而不是返回空操作字符串
  457. if block.name == "compact":
  458. messages[:] = compact_history(messages)
  459. results.append({"type": "tool_result", "tool_use_id": block.id,
  460. "content": "[已压缩。对话历史已完成摘要。]"})
  461. messages.append({"role": "user", "content": results})
  462. break # 结束当前轮次,使用压缩后的上下文重新开始
  463. blocked = trigger_hooks("PreToolUse", block)
  464. if blocked:
  465. results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(blocked)})
  466. continue
  467. handler = TOOL_HANDLERS.get(block.name)
  468. output = handler(**block.input) if handler else f"未知工具:{block.name}"
  469. trigger_hooks("PostToolUse", block, output)
  470. print(str(output)[:200])
  471. results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(output)})
  472. else:
  473. # 正常路径:没有调用 compact
  474. messages.append({"role": "user", "content": results})
  475. continue
  476. # 已调用 compact:结果已在上方追加
  477. continue
  478. if __name__ == "__main__":
  479. print("s08: 上下文压缩 — 四层压缩流水线")
  480. print("输入问题,回车发送。输入 q 退出。\n")
  481. history = []
  482. while True:
  483. try: query = input("\033[36ms08 >> \033[0m")
  484. except (EOFError, KeyboardInterrupt): break
  485. if query.strip().lower() in ("q", "exit", ""): break
  486. history.append({"role": "user", "content": query})
  487. agent_loop(history)
  488. for block in history[-1]["content"]:
  489. if getattr(block, "type", None) == "text": print(block.text)
  490. print()