code.py 24 KB

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