code.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. #!/usr/bin/env python3
  2. """
  3. s16: 团队协议 — 请求-响应协议 + request_id + 分发 + 状态机。
  4. 运行: python s16_team_protocols/code.py
  5. 需要: pip install anthropic python-dotenv + .env 中配置 ANTHROPIC_API_KEY
  6. 相对 s15 的变化:
  7. - ProtocolState dataclass(request_id、type、sender、status、created_at)
  8. - pending_requests 字典:跟踪进行中的协议请求
  9. - dispatch_message:按类型把收到的消息路由给处理器
  10. - request_shutdown:Lead 发送关闭协议请求
  11. - request_plan:Lead 要求队友提交计划
  12. - handle_shutdown_request / handle_plan_response:队友接收并响应
  13. - match_response:Lead 通过 request_id 关联响应(并校验类型)
  14. - 队友空闲循环:等待收件箱消息,而不是 10 轮后退出
  15. - 统一 consume_lead_inbox:协议路由 + 注入历史
  16. - 3 个新 Lead 工具:request_shutdown、request_plan、review_plan
  17. - 1 个新队友工具:submit_plan
  18. ASCII 流程:
  19. Lead: BUS.send("shutdown_request", {request_id}) ──────→ 队友收件箱
  20. Teammate: 分发 → 处理器 → BUS.send("shutdown_response", {request_id}) ─→ Lead 收件箱
  21. Lead: consume_lead_inbox → match_response(request_id) → pending_requests[req_id].status = approved
  22. """
  23. import os, subprocess, json, time, random, threading
  24. from pathlib import Path
  25. from datetime import datetime
  26. from dataclasses import dataclass, asdict, field
  27. try:
  28. import readline
  29. readline.parse_and_bind('set bind-tty-special-chars off')
  30. except ImportError:
  31. pass
  32. from anthropic import Anthropic
  33. from dotenv import load_dotenv
  34. load_dotenv(override=True)
  35. if os.getenv("ANTHROPIC_BASE_URL"):
  36. os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
  37. WORKDIR = Path.cwd()
  38. MEMORY_DIR = WORKDIR / ".memory"
  39. MEMORY_INDEX = MEMORY_DIR / "MEMORY.md"
  40. client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
  41. MODEL = os.environ["MODEL_ID"]
  42. # ── 任务系统 (来自 s12,已同步) ──
  43. TASKS_DIR = WORKDIR / ".tasks"
  44. TASKS_DIR.mkdir(exist_ok=True)
  45. @dataclass
  46. class Task:
  47. id: str
  48. subject: str
  49. description: str
  50. status: str # pending | in_progress | completed
  51. owner: str | None
  52. blockedBy: list[str]
  53. def _task_path(task_id: str) -> Path:
  54. return TASKS_DIR / f"{task_id}.json"
  55. def create_task(subject: str, description: str = "",
  56. blockedBy: list[str] | None = None) -> Task:
  57. task = Task(
  58. id=f"task_{int(time.time())}_{random.randint(0, 9999):04d}",
  59. subject=subject, description=description,
  60. status="pending", owner=None,
  61. blockedBy=blockedBy or [],
  62. )
  63. save_task(task)
  64. return task
  65. def save_task(task: Task):
  66. _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))
  67. def load_task(task_id: str) -> Task:
  68. return Task(**json.loads(_task_path(task_id).read_text()))
  69. def list_tasks() -> list[Task]:
  70. return [Task(**json.loads(p.read_text()))
  71. for p in sorted(TASKS_DIR.glob("task_*.json"))]
  72. def get_task(task_id: str) -> str:
  73. """以 JSON 返回完整任务详情。"""
  74. task = load_task(task_id)
  75. return json.dumps(asdict(task), indent=2)
  76. def can_start(task_id: str) -> bool:
  77. """检查所有 blockedBy 依赖是否已完成;缺失依赖视为阻塞。"""
  78. task = load_task(task_id)
  79. for dep_id in task.blockedBy:
  80. if not _task_path(dep_id).exists():
  81. return False
  82. if load_task(dep_id).status != "completed":
  83. return False
  84. return True
  85. def claim_task(task_id: str, owner: str = "agent") -> str:
  86. task = load_task(task_id)
  87. if task.status != "pending":
  88. status = {"pending": "待处理", "in_progress": "进行中",
  89. "completed": "已完成"}.get(task.status, task.status)
  90. return f"任务 {task_id} 当前状态为 {status},无法认领"
  91. if not can_start(task_id):
  92. deps = [d for d in task.blockedBy
  93. if not _task_path(d).exists() or load_task(d).status != "completed"]
  94. return f"被阻塞于:{deps}"
  95. task.owner = owner
  96. task.status = "in_progress"
  97. save_task(task)
  98. print(f" \033[36m[认领] {task.subject} → in_progress(负责人:{owner})\033[0m")
  99. return f"已认领 {task.id} ({task.subject})"
  100. def complete_task(task_id: str) -> str:
  101. task = load_task(task_id)
  102. if task.status != "in_progress":
  103. status = {"pending": "待处理", "in_progress": "进行中",
  104. "completed": "已完成"}.get(task.status, task.status)
  105. return f"任务 {task_id} 当前状态为 {status},无法完成"
  106. task.status = "completed"
  107. save_task(task)
  108. unblocked = [t.subject for t in list_tasks()
  109. if t.status == "pending" and t.blockedBy and can_start(t.id)]
  110. print(f" \033[32m[完成] {task.subject} ✓\033[0m")
  111. msg = f"已完成 {task.id} ({task.subject})"
  112. if unblocked:
  113. msg += f"\n已解除阻塞:{', '.join(unblocked)}"
  114. print(f" \033[33m[已解除阻塞] {', '.join(unblocked)}\033[0m")
  115. return msg
  116. # ── 提示词组装 (来自 s10,已同步) ──
  117. PROMPT_SECTIONS = {
  118. "identity": "你是一个编码 Agent。直接行动,不要只解释。",
  119. "tools": "可用工具:bash, read_file, write_file, "
  120. "get_task, create_task, list_tasks, claim_task, complete_task, "
  121. "spawn_teammate, send_message, check_inbox, "
  122. "request_shutdown, request_plan, review_plan.",
  123. "workspace": f"工作目录:{WORKDIR}",
  124. "memory": "有可用的相关记忆时,会在下方注入。",
  125. }
  126. def assemble_system_prompt(context: dict) -> str:
  127. sections = [PROMPT_SECTIONS["identity"],
  128. PROMPT_SECTIONS["tools"],
  129. PROMPT_SECTIONS["workspace"]]
  130. memories = context.get("memories", "")
  131. if memories:
  132. sections.append(f"相关记忆:\n{memories}")
  133. return "\n\n".join(sections)
  134. _last_context_key, _last_prompt = None, None
  135. def get_system_prompt(context: dict) -> str:
  136. global _last_context_key, _last_prompt
  137. key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)
  138. if key == _last_context_key and _last_prompt:
  139. return _last_prompt
  140. _last_context_key = key
  141. _last_prompt = assemble_system_prompt(context)
  142. return _last_prompt
  143. # ── 工具 ──
  144. def safe_path(p: str) -> Path:
  145. path = (WORKDIR / p).resolve()
  146. if not path.is_relative_to(WORKDIR):
  147. raise ValueError(f"路径逃逸出工作区:{p}")
  148. return path
  149. def run_bash(command: str, run_in_background: bool = False) -> str:
  150. # run_in_background 由 agent_loop 分发处理,不在这里处理
  151. try:
  152. r = subprocess.run(command, shell=True, cwd=WORKDIR,
  153. capture_output=True, text=True, timeout=120)
  154. out = (r.stdout + r.stderr).strip()
  155. return out[:50000] if out else "(无输出)"
  156. except subprocess.TimeoutExpired:
  157. return "错误:执行超时(120 秒)"
  158. def run_read(path: str, limit: int | None = None) -> str:
  159. try:
  160. lines = safe_path(path).read_text().splitlines()
  161. if limit and limit < len(lines):
  162. lines = lines[:limit] + [f"... ({len(lines) - limit} 行更多内容)"]
  163. return "\n".join(lines)
  164. except Exception as e:
  165. return f"错误:{e}"
  166. def run_write(path: str, content: str) -> str:
  167. try:
  168. fp = safe_path(path)
  169. fp.parent.mkdir(parents=True, exist_ok=True)
  170. fp.write_text(content)
  171. return f"已写入 {len(content)} 字节到 {path}"
  172. except Exception as e:
  173. return f"错误:{e}"
  174. # 任务工具
  175. def run_create_task(subject: str, description: str = "",
  176. blockedBy: list[str] | None = None) -> str:
  177. task = create_task(subject, description, blockedBy)
  178. deps = f"(依赖:{', '.join(blockedBy)})" if blockedBy else ""
  179. print(f" \033[34m[创建] {task.subject}{deps}\033[0m")
  180. return f"已创建 {task.id}: {task.subject}{deps}"
  181. def run_list_tasks() -> str:
  182. 个任务 = list_tasks()
  183. if not 个任务:
  184. return "暂无任务。请使用 create_task 添加任务。"
  185. lines = []
  186. for t in 个任务:
  187. icon = {"pending": "○", "in_progress": "●",
  188. "completed": "✓"}.get(t.status, "?")
  189. deps = f"(依赖:{', '.join(t.blockedBy)})" if t.blockedBy else ""
  190. owner = f" [负责人:{t.owner}]" if t.owner else ""
  191. status = {"pending": "待处理", "in_progress": "进行中",
  192. "completed": "已完成"}.get(t.status, t.status)
  193. lines.append(f" {icon} {t.id}: {t.subject} "
  194. f"[{status}]{owner}{deps}")
  195. return "\n".join(lines)
  196. def run_get_task(task_id: str) -> str:
  197. try:
  198. return get_task(task_id)
  199. except FileNotFoundError:
  200. return f"错误:任务 {task_id} 未找到"
  201. def run_claim_task(task_id: str) -> str:
  202. return claim_task(task_id, owner="agent")
  203. def run_complete_task(task_id: str) -> str:
  204. return complete_task(task_id)
  205. # ── 后台任务 (来自 s13,已同步) ──
  206. _bg_计数器 = 0
  207. background_tasks: dict[str, dict] = {}
  208. background_results: dict[str, str] = {}
  209. background_lock = threading.Lock()
  210. def is_slow_operation(tool_name: str, tool_input: dict) -> bool:
  211. """兜底启发式:判断命令是否可能超过 30 秒。"""
  212. if tool_name != "bash":
  213. return False
  214. cmd = tool_input.get("command", "").lower()
  215. slow_keywords = ["install", "build", "test", "deploy", "compile",
  216. "docker build", "pip install", "npm install",
  217. "cargo build", "pytest", "make"]
  218. return any(kw in cmd for kw in slow_keywords)
  219. def should_run_background(tool_name: str, tool_input: dict) -> bool:
  220. """模型的显式请求优先;否则使用启发式兜底。"""
  221. if tool_input.get("run_in_background"):
  222. return True
  223. return is_slow_operation(tool_name, tool_input)
  224. def start_background_task(block) -> str:
  225. """在守护线程中运行工具,并返回后台任务 ID。"""
  226. global _bg_计数器
  227. _bg_计数器 += 1
  228. bg_id = f"bg_{_bg_计数器:04d}"
  229. cmd = block.input.get("command", block.name)
  230. def worker():
  231. result = execute_tool(block)
  232. with background_lock:
  233. background_tasks[bg_id]["status"] = "completed"
  234. background_results[bg_id] = result
  235. with background_lock:
  236. background_tasks[bg_id] = {
  237. "tool_use_id": block.id,
  238. "command": cmd,
  239. "status": "running",
  240. }
  241. threading.Thread(target=worker, daemon=True).start()
  242. print(f" \033[33m[后台] 已分发 {bg_id}: {cmd[:40]}\033[0m")
  243. return bg_id
  244. def collect_background_results() -> list[str]:
  245. """将已完成的后台结果收集为 task_notification 消息。"""
  246. with background_lock:
  247. ready_ids = [bid for bid, task in background_tasks.items()
  248. if task["status"] == "completed"]
  249. notifications = []
  250. for bg_id in ready_ids:
  251. with background_lock:
  252. task = background_tasks.pop(bg_id)
  253. output = background_results.pop(bg_id, "")
  254. summary = output[:200] if len(output) > 200 else output
  255. notifications.append(
  256. f"<task_notification>\n"
  257. f" <task_id>{bg_id}</task_id>\n"
  258. f" <status>completed</status>\n"
  259. f" <command>{task['command']}</command>\n"
  260. f" <summary>{summary}</summary>\n"
  261. f"</task_notification>")
  262. print(f" \033[32m[后台完成] {bg_id}: "
  263. f"{task['command'][:40]} ({len(output)} 个字符)\033[0m")
  264. return notifications
  265. # ── MessageBus (来自 s15) ──
  266. MAILBOX_DIR = WORKDIR / ".mailboxes"
  267. MAILBOX_DIR.mkdir(exist_ok=True)
  268. class MessageBus:
  269. """基于文件的消息总线。每个 Agent 都有一个 .jsonl 收件箱。
  270. 读取是破坏性的:read_text + unlink 会消费消息。
  271. 教学版本不做文件锁;真实 CC 使用 proper-lockfile。"""
  272. def send(self, from_agent: str, to_agent: str, content: str,
  273. msg_type: str = "message", metadata: dict = None):
  274. msg = {"from": from_agent, "to": to_agent,
  275. "content": content, "type": msg_type,
  276. "ts": time.time(), "metadata": metadata or {}}
  277. inbox = MAILBOX_DIR / f"{to_agent}.jsonl"
  278. with open(inbox, "a") as f:
  279. f.write(json.dumps(msg) + "\n")
  280. print(f" \033[33m[bus] {from_agent} → {to_agent}: "
  281. f"({msg_type}) {content[:50]}\033[0m")
  282. def read_inbox(self, agent: str) -> list[dict]:
  283. inbox = MAILBOX_DIR / f"{agent}.jsonl"
  284. if not inbox.exists():
  285. return []
  286. msgs = [json.loads(line) for line in inbox.read_text().splitlines()
  287. if line.strip()]
  288. inbox.unlink() # 消费:读取 + 删除
  289. return msgs
  290. BUS = MessageBus()
  291. active_teammates: dict[str, bool] = {}
  292. # ── 协议状态 (s16 新增) ──
  293. @dataclass
  294. class ProtocolState:
  295. request_id: str
  296. type: str # "shutdown" | "plan_approval"
  297. sender: str
  298. target: str
  299. status: str # pending | approved | rejected
  300. payload: str # 计划文本或关闭原因
  301. created_at: float = field(default_factory=time.time)
  302. pending_requests: dict[str, ProtocolState] = {}
  303. def new_request_id() -> str:
  304. return f"req_{random.randint(0, 999999):06d}"
  305. def match_response(response_type: str, request_id: str, approve: bool):
  306. """通过 request_id 将响应关联到原始请求,并校验响应类型是否匹配。"""
  307. state = pending_requests.get(request_id)
  308. if not state:
  309. print(f" \033[31m[协议] 未知 request_id: {request_id}\033[0m")
  310. return
  311. # 校验响应类型是否匹配请求类型
  312. if state.type == "shutdown" and response_type != "shutdown_response":
  313. print(f" \033[31m[协议] 类型不匹配:期望 shutdown_response,"
  314. f"实际得到 {response_type}\033[0m")
  315. return
  316. if state.type == "plan_approval" and response_type != "plan_approval_response":
  317. print(f" \033[31m[协议] 类型不匹配:期望 plan_approval_response,"
  318. f"实际得到 {response_type}\033[0m")
  319. return
  320. if state.status != "pending":
  321. print(f" \033[33m[协议] {request_id} 已经是 {state.status},"
  322. f"忽略重复响应\033[0m")
  323. return
  324. state.status = "approved" if approve else "rejected"
  325. icon = "✓" if approve else "✗"
  326. color = "32" if approve else "31"
  327. print(f" \033[{color}m[协议] {state.type} {icon} "
  328. f"({request_id}: {state.status})\033[0m")
  329. # ── 统一 Lead 收件箱消费者 (s16 修复) ──
  330. # check_inbox 工具和主循环都会调用这个函数。
  331. # 返回前通过 match_response 路由协议响应。
  332. def consume_lead_inbox(route_protocol: bool = True) -> list[dict]:
  333. """读取 Lead 收件箱,路由协议响应,并返回所有消息。
  334. run_check_inbox() 和主循环都会调用,避免消息被消费却没有经过协议路由。"""
  335. msgs = BUS.read_inbox("lead")
  336. if not msgs:
  337. return []
  338. if route_protocol:
  339. for msg in msgs:
  340. meta = msg.get("metadata", {})
  341. req_id = meta.get("request_id", "")
  342. msg_type = msg.get("type", "")
  343. if req_id and msg_type.endswith("_response"):
  344. approve = meta.get("approve", False)
  345. match_response(msg_type, req_id, approve)
  346. return msgs
  347. # ── 队友线程 (s16: 空闲循环 + 分发) ──
  348. def spawn_teammate_thread(name: str, role: str, prompt: str) -> str:
  349. """在后台线程中启动队友 Agent。
  350. 队友使用空闲循环:每轮 LLM 后等待收件箱消息
  351. (shutdown_request 或新任务),而不是直接退出。"""
  352. if name in active_teammates:
  353. return f"队友 '{name}' 已存在"
  354. system = (f"你是 '{name}',角色是 {role}。"
  355. f"使用工具完成任务。"
  356. f"检查收件箱中的协议消息(shutdown_request 等)。")
  357. def handle_inbox_message(name: str, msg: dict, messages: list) -> bool:
  358. """按类型分发收到的协议消息。返回 True 表示队友应停止。"""
  359. msg_type = msg.get("type", "message")
  360. meta = msg.get("metadata", {})
  361. req_id = meta.get("request_id", "")
  362. if msg_type == "shutdown_request":
  363. BUS.send(name, "lead", "正在平滑关闭。",
  364. "shutdown_response",
  365. {"request_id": req_id, "approve": True})
  366. print(f" \033[35m[协议] {name} 已批准关闭 "
  367. f"({req_id})\033[0m")
  368. return True # 停止循环
  369. if msg_type == "plan_approval_response":
  370. approve = meta.get("approve", False)
  371. if approve:
  372. messages.append({"role": "user",
  373. "content": f"[计划已批准] 继续执行任务。"})
  374. else:
  375. messages.append({"role": "user",
  376. "content": f"[计划已拒绝] 反馈:{msg['content']}"})
  377. return False # 继续
  378. def run():
  379. messages = [{"role": "user", "content": prompt}]
  380. sub_tools = [
  381. {"name": "bash", "description": "运行一条 shell 命令。",
  382. "input_schema": {"type": "object",
  383. "properties": {"command": {"type": "string"}},
  384. "required": ["command"]}},
  385. {"name": "read_file", "description": "读取文件。",
  386. "input_schema": {"type": "object",
  387. "properties": {"path": {"type": "string"}},
  388. "required": ["path"]}},
  389. {"name": "write_file", "description": "写入文件。",
  390. "input_schema": {"type": "object",
  391. "properties": {"path": {"type": "string"},
  392. "content": {"type": "string"}},
  393. "required": ["path", "content"]}},
  394. {"name": "send_message",
  395. "description": "向另一个 Agent 发送消息。",
  396. "input_schema": {"type": "object",
  397. "properties": {"to": {"type": "string"},
  398. "content": {"type": "string"}},
  399. "required": ["to", "content"]}},
  400. {"name": "submit_plan",
  401. "description": "提交计划给 Lead 审批。",
  402. "input_schema": {"type": "object",
  403. "properties": {"plan": {"type": "string"}},
  404. "required": ["plan"]}},
  405. ]
  406. sub_handlers = {
  407. "bash": run_bash, "read_file": run_read, "write_file": run_write,
  408. "send_message": lambda to, content: (BUS.send(name, to, content),
  409. "已发送")[1],
  410. "submit_plan": lambda plan: _teammate_submit_plan(name, plan),
  411. }
  412. shutdown_requested = False
  413. while not shutdown_requested:
  414. # 检查收件箱中的协议消息
  415. inbox = BUS.read_inbox(name)
  416. should_stop = False
  417. non_protocol = []
  418. for msg in inbox:
  419. if msg.get("type") in ("shutdown_request", "plan_approval_response"):
  420. should_stop = handle_inbox_message(name, msg, messages)
  421. if should_stop:
  422. break
  423. else:
  424. non_protocol.append(msg)
  425. if should_stop:
  426. shutdown_requested = True
  427. break
  428. if non_protocol:
  429. inbox_json = json.dumps(non_protocol)
  430. messages.append({"role": "user",
  431. "content": "<inbox>" + inbox_json + "</inbox>"})
  432. # LLM 轮次
  433. try:
  434. response = client.messages.create(
  435. model=MODEL, system=system, messages=messages[-20:],
  436. tools=sub_tools, max_tokens=8000)
  437. except Exception:
  438. break
  439. messages.append({"role": "assistant", "content": response.content})
  440. if response.stop_reason != "tool_use":
  441. # 空闲:等待收件箱消息,而不是退出
  442. # 真实 CC 会在这里向 Lead 发送 idle_notification
  443. while not shutdown_requested:
  444. time.sleep(1)
  445. inbox = BUS.read_inbox(name)
  446. if not inbox:
  447. continue
  448. for msg in inbox:
  449. if msg.get("type") in ("shutdown_request", "plan_approval_response"):
  450. should_stop = handle_inbox_message(name, msg, messages)
  451. if should_stop:
  452. shutdown_requested = True
  453. break
  454. else:
  455. non_protocol.append(msg)
  456. if shutdown_requested:
  457. break
  458. if non_protocol:
  459. inbox_json = json.dumps(non_protocol)
  460. messages.append({"role": "user",
  461. "content": "<inbox>" + inbox_json + "</inbox>"})
  462. break # 带着新消息回到 LLM 轮次
  463. # 执行工具调用
  464. results = []
  465. for block in response.content:
  466. if block.type == "tool_use":
  467. handler = sub_handlers.get(block.name)
  468. output = handler(**block.input) if handler else "未知"
  469. results.append({"type": "tool_result",
  470. "tool_use_id": block.id,
  471. "content": str(output)})
  472. messages.append({"role": "user", "content": results})
  473. # 向 Lead 发送最终摘要
  474. summary = "已完成。"
  475. for msg in reversed(messages):
  476. if msg["role"] == "assistant" and isinstance(msg["content"], list):
  477. for b in msg["content"]:
  478. if getattr(b, "type", None) == "text":
  479. summary = b.text
  480. break
  481. else:
  482. continue
  483. break
  484. BUS.send(name, "lead", summary, "result")
  485. active_teammates.pop(name, None)
  486. print(f" \033[32m[队友] {name} 已完成\033[0m")
  487. active_teammates[name] = True
  488. threading.Thread(target=run, daemon=True).start()
  489. print(f" \033[36m[队友] {name} 已作为 {role} 启动\033[0m")
  490. return f"队友 '{name}' 已启动为 {role}"
  491. def _teammate_submit_plan(from_name: str, plan: str) -> str:
  492. """队友向 Lead 提交计划以供审批。
  493. 注意:这是协议层请求,不是代码层闸门。
  494. 提交后,队友线程仍会继续运行,仍然可以调用 bash/write 等工具。
  495. 真实约束依赖模型在行动前等待审批响应。
  496. 若要做代码层工具闸门,需要在审批到达前阻塞队友的工具分发。
  497. """
  498. req_id = new_request_id()
  499. pending_requests[req_id] = ProtocolState(
  500. request_id=req_id, type="plan_approval",
  501. sender=from_name, target="lead",
  502. status="pending", payload=plan)
  503. BUS.send(from_name, "lead", plan,
  504. "plan_approval_request",
  505. {"request_id": req_id})
  506. return f"计划已提交({req_id})。正在等待审批..."
  507. # ── Lead 协议工具 (s16 新增) ──
  508. def run_request_shutdown(teammate: str) -> str:
  509. req_id = new_request_id()
  510. pending_requests[req_id] = ProtocolState(
  511. request_id=req_id, type="shutdown",
  512. sender="lead", target=teammate,
  513. status="pending", payload="")
  514. BUS.send("lead", teammate, "请平滑关闭。",
  515. "shutdown_request",
  516. {"request_id": req_id})
  517. print(f" \033[35m[协议] shutdown_request → {teammate} "
  518. f"({req_id})\033[0m")
  519. return f"已向 {teammate} 发送关闭请求(req: {req_id})"
  520. def run_request_plan(teammate: str, task: str) -> str:
  521. """Lead 要求队友为指定任务提交计划。"""
  522. BUS.send("lead", teammate, f"请为以下任务提交计划:{task}",
  523. "message")
  524. return f"已要求 {teammate} 提交计划"
  525. def run_review_plan(request_id: str, approve: bool, feedback: str = "") -> str:
  526. state = pending_requests.get(request_id)
  527. if not state:
  528. return f"请求 {request_id} 未找到"
  529. if state.status != "pending":
  530. return f"请求 {request_id} 已经是 {state.status}"
  531. state.status = "approved" if approve else "rejected"
  532. BUS.send("lead", state.sender, feedback or ("已批准" if approve else "已拒绝"),
  533. "plan_approval_response",
  534. {"request_id": request_id, "approve": approve})
  535. icon = "✓" if approve else "✗"
  536. print(f" \033[32m[协议] 计划 {icon} ({request_id})\033[0m")
  537. return f"计划已{'批准' if approve else '拒绝'}({request_id})"
  538. # ── 其他 Lead 工具处理器 ──
  539. def run_spawn_teammate(name: str, role: str, prompt: str) -> str:
  540. return spawn_teammate_thread(name, role, prompt)
  541. def run_send_message(to: str, content: str) -> str:
  542. BUS.send("lead", to, content)
  543. return f"已发送给 {to}"
  544. def run_check_inbox() -> str:
  545. """检查 Lead 收件箱,并通过 match_response 路由协议响应。"""
  546. msgs = consume_lead_inbox(route_protocol=True)
  547. if not msgs:
  548. return "(收件箱为空)"
  549. lines = []
  550. for m in msgs:
  551. meta = m.get("metadata", {})
  552. req_id = meta.get("request_id", "")
  553. tag = f" [{m['type']} req:{req_id}]" if req_id else f" [{m['type']}]"
  554. lines.append(f" [{m['from']}]{tag} {m['content'][:200]}")
  555. return "\n".join(lines)
  556. # ── 工具分发 ──
  557. def execute_tool(block) -> str:
  558. """执行工具调用块并返回输出。"""
  559. handler = {
  560. "bash": run_bash, "read_file": run_read, "write_file": run_write,
  561. "create_task": run_create_task, "list_tasks": run_list_tasks,
  562. "get_task": run_get_task, "claim_task": run_claim_task,
  563. "complete_task": run_complete_task,
  564. "spawn_teammate": run_spawn_teammate,
  565. "send_message": run_send_message, "check_inbox": run_check_inbox,
  566. "request_shutdown": run_request_shutdown,
  567. "request_plan": run_request_plan, "review_plan": run_review_plan,
  568. }.get(block.name)
  569. if handler:
  570. return handler(**block.input)
  571. return f"未知工具:{block.name}"
  572. # ── 工具定义 ──
  573. TOOLS = [
  574. {"name": "bash", "description": "运行一条 shell 命令。",
  575. "input_schema": {"type": "object",
  576. "properties": {
  577. "command": {"type": "string"},
  578. "run_in_background": {"type": "boolean"}},
  579. "required": ["command"]}},
  580. {"name": "read_file", "description": "读取文件内容。",
  581. "input_schema": {"type": "object",
  582. "properties": {"path": {"type": "string"},
  583. "limit": {"type": "integer"}},
  584. "required": ["path"]}},
  585. {"name": "write_file", "description": "向文件写入内容。",
  586. "input_schema": {"type": "object",
  587. "properties": {"path": {"type": "string"},
  588. "content": {"type": "string"}},
  589. "required": ["path", "content"]}},
  590. {"name": "create_task",
  591. "description": "创建一个新任务,可选 blockedBy 依赖。",
  592. "input_schema": {"type": "object",
  593. "properties": {
  594. "subject": {"type": "string"},
  595. "description": {"type": "string"},
  596. "blockedBy": {"type": "array",
  597. "items": {"type": "string"}}},
  598. "required": ["subject"]}},
  599. {"name": "list_tasks",
  600. "description": "列出所有任务及其状态、负责人和依赖。",
  601. "input_schema": {"type": "object", "properties": {},
  602. "required": []}},
  603. {"name": "get_task",
  604. "description": "按 ID 获取指定任务的完整详情。",
  605. "input_schema": {"type": "object",
  606. "properties": {"task_id": {"type": "string"}},
  607. "required": ["task_id"]}},
  608. {"name": "claim_task",
  609. "description": "认领一个待处理任务。设置 owner,并将状态改为 in_progress。",
  610. "input_schema": {"type": "object",
  611. "properties": {"task_id": {"type": "string"}},
  612. "required": ["task_id"]}},
  613. {"name": "complete_task",
  614. "description": "完成一个进行中的任务。报告被解除阻塞的下游任务。",
  615. "input_schema": {"type": "object",
  616. "properties": {"task_id": {"type": "string"}},
  617. "required": ["task_id"]}},
  618. {"name": "spawn_teammate",
  619. "description": "在后台线程中启动一个队友 Agent。",
  620. "input_schema": {"type": "object",
  621. "properties": {
  622. "name": {"type": "string"},
  623. "role": {"type": "string"},
  624. "prompt": {"type": "string"}},
  625. "required": ["name", "role", "prompt"]}},
  626. {"name": "send_message",
  627. "description": "通过 MessageBus 向队友发送消息。",
  628. "input_schema": {"type": "object",
  629. "properties": {"to": {"type": "string"},
  630. "content": {"type": "string"}},
  631. "required": ["to", "content"]}},
  632. {"name": "check_inbox",
  633. "description": "检查 Lead 收件箱,并自动路由协议响应。",
  634. "input_schema": {"type": "object", "properties": {},
  635. "required": []}},
  636. {"name": "request_shutdown",
  637. "description": "请求队友平滑关闭。",
  638. "input_schema": {"type": "object",
  639. "properties": {"teammate": {"type": "string"}},
  640. "required": ["teammate"]}},
  641. {"name": "request_plan",
  642. "description": "要求队友提交计划以供审查。",
  643. "input_schema": {"type": "object",
  644. "properties": {"teammate": {"type": "string"},
  645. "task": {"type": "string"}},
  646. "required": ["teammate", "task"]}},
  647. {"name": "review_plan",
  648. "description": "按 request_id 批准或拒绝已提交的计划。",
  649. "input_schema": {"type": "object",
  650. "properties": {
  651. "request_id": {"type": "string"},
  652. "approve": {"type": "boolean"},
  653. "feedback": {"type": "string"}},
  654. "required": ["request_id", "approve"]}},
  655. ]
  656. # ── 上下文 ──
  657. def update_context(context: dict, messages: list) -> dict:
  658. """从真实状态推导上下文。"""
  659. memories = ""
  660. if MEMORY_INDEX.exists():
  661. content = MEMORY_INDEX.read_text().strip()
  662. if content:
  663. memories = content
  664. return {
  665. "enabled_tools": [t["name"] for t in TOOLS],
  666. "workspace": str(WORKDIR),
  667. "memories": memories,
  668. }
  669. # ── Agent 循环 ──
  670. def agent_loop(messages: list, context: dict):
  671. system = get_system_prompt(context)
  672. while True:
  673. try:
  674. response = client.messages.create(
  675. model=MODEL, system=system, messages=messages,
  676. tools=TOOLS, max_tokens=8000)
  677. except Exception as e:
  678. messages.append({"role": "assistant", "content": [
  679. {"type": "text",
  680. "text": f"[错误] {type(e).__name__}: {e}"}]})
  681. return
  682. messages.append({"role": "assistant", "content": response.content})
  683. if response.stop_reason != "tool_use":
  684. return
  685. results = []
  686. for block in response.content:
  687. if block.type != "tool_use":
  688. continue
  689. print(f"\033[36m> {block.name}\033[0m")
  690. if should_run_background(block.name, block.input):
  691. bg_id = start_background_task(block)
  692. results.append({"type": "tool_result",
  693. "tool_use_id": block.id,
  694. "content": f"[后台任务 {bg_id} 已启动] "
  695. f"完成后结果将可用。"})
  696. else:
  697. output = execute_tool(block)
  698. print(str(output)[:300])
  699. results.append({"type": "tool_result",
  700. "tool_use_id": block.id,
  701. "content": output})
  702. # 将后台工具结果 + 通知合并成一条用户消息
  703. user_content = list(results)
  704. bg_notifications = collect_background_results()
  705. if bg_notifications:
  706. for notif in bg_notifications:
  707. user_content.append({"type": "text", "text": notif})
  708. messages.append({"role": "user", "content": user_content})
  709. context = update_context(context, messages)
  710. system = get_system_prompt(context)
  711. if __name__ == "__main__":
  712. print("s16: 团队协议")
  713. print("输入问题后按回车发送。输入 q 退出。\n")
  714. history = []
  715. context = update_context({}, [])
  716. while True:
  717. try:
  718. query = input("\033[36ms16 >> \033[0m")
  719. except (EOFError, KeyboardInterrupt):
  720. break
  721. if query.strip().lower() in ("q", "exit", ""):
  722. break
  723. history.append({"role": "user", "content": query})
  724. agent_loop(history, context)
  725. context = update_context(context, history)
  726. for block in history[-1]["content"]:
  727. if getattr(block, "type", None) == "text":
  728. print(block.text)
  729. elif isinstance(block, dict) and block.get("type") == "text":
  730. print(block.get("text", ""))
  731. # 检查收件箱 → 路由协议 + 注入历史
  732. inbox_msgs = consume_lead_inbox(route_protocol=True)
  733. if inbox_msgs:
  734. inbox_text = "\n".join(
  735. f"来自 {m['from']}: {m['content'][:200]}" for m in inbox_msgs)
  736. history.append({"role": "user",
  737. "content": f"[收件箱]\n{inbox_text}"})
  738. print(f"\n\033[33m[收件箱:已注入 {len(inbox_msgs)} 条消息]\033[0m")
  739. print()