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. """Check if all blockedBy dependencies are completed.
  78. Missing dependencies are treated as blocked."""
  79. task = load_task(task_id)
  80. for dep_id in task.blockedBy:
  81. if not _task_path(dep_id).exists():
  82. return False
  83. if load_task(dep_id).status != "completed":
  84. return False
  85. return True
  86. def claim_task(task_id: str, owner: str = "agent") -> str:
  87. task = load_task(task_id)
  88. if task.status != "pending":
  89. return f"任务 {task_id} 当前状态为 {task.status},无法认领"
  90. if not can_start(task_id):
  91. deps = [d for d in task.blockedBy
  92. if not _task_path(d).exists() or load_task(d).status != "completed"]
  93. return f"Blocked by: {deps}"
  94. task.owner = owner
  95. task.status = "in_progress"
  96. save_task(task)
  97. print(f" \033[36m[claim] {task.subject} → in_progress (owner: {owner})\033[0m")
  98. return f"已认领 {task.id} ({task.subject})"
  99. def complete_task(task_id: str) -> str:
  100. task = load_task(task_id)
  101. if task.status != "in_progress":
  102. return f"任务 {task_id} 当前状态为 {task.status},无法完成"
  103. task.status = "completed"
  104. save_task(task)
  105. unblocked = [t.subject for t in list_tasks()
  106. if t.status == "pending" and t.blockedBy and can_start(t.id)]
  107. print(f" \033[32m[complete] {task.subject} ✓\033[0m")
  108. msg = f"已完成 {task.id} ({task.subject})"
  109. if unblocked:
  110. msg += f"\n已解除阻塞:{', '.join(unblocked)}"
  111. print(f" \033[33m[unblocked] {', '.join(unblocked)}\033[0m")
  112. return msg
  113. # ── 提示词组装 (来自 s10,已同步) ──
  114. PROMPT_SECTIONS = {
  115. "identity": "你是一个编码 Agent。直接行动,不要只解释。",
  116. "tools": "可用工具:bash, read_file, write_file, "
  117. "get_task, create_task, list_tasks, claim_task, complete_task, "
  118. "spawn_teammate, send_message, check_inbox, "
  119. "request_shutdown, request_plan, review_plan.",
  120. "workspace": f"工作目录:{WORKDIR}",
  121. "memory": "有可用的相关记忆时,会在下方注入。",
  122. }
  123. def assemble_system_prompt(context: dict) -> str:
  124. sections = [PROMPT_SECTIONS["identity"],
  125. PROMPT_SECTIONS["tools"],
  126. PROMPT_SECTIONS["workspace"]]
  127. memories = context.get("memories", "")
  128. if memories:
  129. sections.append(f"Relevant memories:\n{memories}")
  130. return "\n\n".join(sections)
  131. _last_context_key, _last_prompt = None, None
  132. def get_system_prompt(context: dict) -> str:
  133. global _last_context_key, _last_prompt
  134. key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)
  135. if key == _last_context_key and _last_prompt:
  136. return _last_prompt
  137. _last_context_key = key
  138. _last_prompt = assemble_system_prompt(context)
  139. return _last_prompt
  140. # ── 工具 ──
  141. def safe_path(p: str) -> Path:
  142. path = (WORKDIR / p).resolve()
  143. if not path.is_relative_to(WORKDIR):
  144. raise ValueError(f"路径逃逸出工作区:{p}")
  145. return path
  146. def run_bash(command: str, run_in_background: bool = False) -> str:
  147. # run_in_background 由 agent_loop 分发处理,不在这里处理
  148. try:
  149. r = subprocess.run(command, shell=True, cwd=WORKDIR,
  150. capture_output=True, text=True, timeout=120)
  151. out = (r.stdout + r.stderr).strip()
  152. return out[:50000] if out else "(无输出)"
  153. except subprocess.TimeoutExpired:
  154. return "错误:执行超时(120 秒)"
  155. def run_read(path: str, limit: int | None = None) -> str:
  156. try:
  157. lines = safe_path(path).read_text().splitlines()
  158. if limit and limit < len(lines):
  159. lines = lines[:limit] + [f"... ({len(lines) - limit} 行更多内容)"]
  160. return "\n".join(lines)
  161. except Exception as e:
  162. return f"错误:{e}"
  163. def run_write(path: str, content: str) -> str:
  164. try:
  165. fp = safe_path(path)
  166. fp.parent.mkdir(parents=True, exist_ok=True)
  167. fp.write_text(content)
  168. return f"已写入 {len(content)} 字节到 {path}"
  169. except Exception as e:
  170. return f"错误:{e}"
  171. # 任务工具
  172. def run_create_task(subject: str, description: str = "",
  173. blockedBy: list[str] | None = None) -> str:
  174. task = create_task(subject, description, blockedBy)
  175. deps = f" (blockedBy: {', '.join(blockedBy)})" if blockedBy else ""
  176. print(f" \033[34m[create] {task.subject}{deps}\033[0m")
  177. return f"已创建 {task.id}: {task.subject}{deps}"
  178. def run_list_tasks() -> str:
  179. 个任务 = list_tasks()
  180. if not 个任务:
  181. return "暂无任务。请使用 create_task 添加任务。"
  182. lines = []
  183. for t in 个任务:
  184. icon = {"pending": "○", "in_progress": "●",
  185. "completed": "✓"}.get(t.status, "?")
  186. deps = f" (blockedBy: {', '.join(t.blockedBy)})" if t.blockedBy else ""
  187. owner = f" [{t.owner}]" if t.owner else ""
  188. lines.append(f" {icon} {t.id}: {t.subject} "
  189. f"[{t.status}]{owner}{deps}")
  190. return "\n".join(lines)
  191. def run_get_task(task_id: str) -> str:
  192. try:
  193. return get_task(task_id)
  194. except FileNotFoundError:
  195. return f"错误:任务 {task_id} 未找到"
  196. def run_claim_task(task_id: str) -> str:
  197. return claim_task(task_id, owner="agent")
  198. def run_complete_task(task_id: str) -> str:
  199. return complete_task(task_id)
  200. # ── 后台任务 (来自 s13,已同步) ──
  201. _bg_计数器 = 0
  202. background_tasks: dict[str, dict] = {}
  203. background_results: dict[str, str] = {}
  204. background_lock = threading.Lock()
  205. def is_slow_operation(tool_name: str, tool_input: dict) -> bool:
  206. """兜底启发式:判断命令是否可能超过 30 秒。"""
  207. if tool_name != "bash":
  208. return False
  209. cmd = tool_input.get("command", "").lower()
  210. slow_keywords = ["install", "build", "test", "deploy", "compile",
  211. "docker build", "pip install", "npm install",
  212. "cargo build", "pytest", "make"]
  213. return any(kw in cmd for kw in slow_keywords)
  214. def should_run_background(tool_name: str, tool_input: dict) -> bool:
  215. """模型的显式请求优先;否则使用启发式兜底。"""
  216. if tool_input.get("run_in_background"):
  217. return True
  218. return is_slow_operation(tool_name, tool_input)
  219. def start_background_task(block) -> str:
  220. """在守护线程中运行工具,并返回后台任务 ID。"""
  221. global _bg_计数器
  222. _bg_计数器 += 1
  223. bg_id = f"bg_{_bg_计数器:04d}"
  224. cmd = block.input.get("command", block.name)
  225. def worker():
  226. result = execute_tool(block)
  227. with background_lock:
  228. background_tasks[bg_id]["status"] = "completed"
  229. background_results[bg_id] = result
  230. with background_lock:
  231. background_tasks[bg_id] = {
  232. "tool_use_id": block.id,
  233. "command": cmd,
  234. "status": "running",
  235. }
  236. threading.Thread(target=worker, daemon=True).start()
  237. print(f" \033[33m[background] dispatched {bg_id}: {cmd[:40]}\033[0m")
  238. return bg_id
  239. def collect_background_results() -> list[str]:
  240. """将已完成的后台结果收集为 task_notification 消息。"""
  241. with background_lock:
  242. ready_ids = [bid for bid, task in background_tasks.items()
  243. if task["status"] == "completed"]
  244. notifications = []
  245. for bg_id in ready_ids:
  246. with background_lock:
  247. task = background_tasks.pop(bg_id)
  248. output = background_results.pop(bg_id, "")
  249. summary = output[:200] if len(output) > 200 else output
  250. notifications.append(
  251. f"<task_notification>\n"
  252. f" <task_id>{bg_id}</task_id>\n"
  253. f" <status>completed</status>\n"
  254. f" <command>{task['command']}</command>\n"
  255. f" <summary>{summary}</summary>\n"
  256. f"</task_notification>")
  257. print(f" \033[32m[background done] {bg_id}: "
  258. f"{task['command'][:40]} ({len(output)} 个字符)\033[0m")
  259. return notifications
  260. # ── MessageBus (来自 s15) ──
  261. MAILBOX_DIR = WORKDIR / ".mailboxes"
  262. MAILBOX_DIR.mkdir(exist_ok=True)
  263. class MessageBus:
  264. """File-based message bus. Each agent has a .jsonl inbox.
  265. Read is destructive: read_text + unlink (consumes messages).
  266. Teaching version: no file locking; real CC uses proper-lockfile."""
  267. def send(self, from_agent: str, to_agent: str, content: str,
  268. msg_type: str = "message", metadata: dict = None):
  269. msg = {"from": from_agent, "to": to_agent,
  270. "content": content, "type": msg_type,
  271. "ts": time.time(), "metadata": metadata or {}}
  272. inbox = MAILBOX_DIR / f"{to_agent}.jsonl"
  273. with open(inbox, "a") as f:
  274. f.write(json.dumps(msg) + "\n")
  275. print(f" \033[33m[bus] {from_agent} → {to_agent}: "
  276. f"({msg_type}) {content[:50]}\033[0m")
  277. def read_inbox(self, agent: str) -> list[dict]:
  278. inbox = MAILBOX_DIR / f"{agent}.jsonl"
  279. if not inbox.exists():
  280. return []
  281. msgs = [json.loads(line) for line in inbox.read_text().splitlines()
  282. if line.strip()]
  283. inbox.unlink() # 消费:读取 + 删除
  284. return msgs
  285. BUS = MessageBus()
  286. active_teammates: dict[str, bool] = {}
  287. # ── 协议状态 (s16 新增) ──
  288. @dataclass
  289. class ProtocolState:
  290. request_id: str
  291. type: str # "shutdown" | "plan_approval"
  292. sender: str
  293. target: str
  294. status: str # pending | approved | rejected
  295. payload: str # 计划文本或关闭原因
  296. created_at: float = field(default_factory=time.time)
  297. pending_requests: dict[str, ProtocolState] = {}
  298. def new_request_id() -> str:
  299. return f"req_{random.randint(0, 999999):06d}"
  300. def match_response(response_type: str, request_id: str, approve: bool):
  301. """Correlate a response to the original request via request_id.
  302. Validates that response_type matches the request type."""
  303. state = pending_requests.get(request_id)
  304. if not state:
  305. print(f" \033[31m[protocol] unknown request_id: {request_id}\033[0m")
  306. return
  307. # 校验响应类型是否匹配请求类型
  308. if state.type == "shutdown" and response_type != "shutdown_response":
  309. print(f" \033[31m[protocol] type mismatch: expected shutdown_response, "
  310. f"got {response_type}\033[0m")
  311. return
  312. if state.type == "plan_approval" and response_type != "plan_approval_response":
  313. print(f" \033[31m[protocol] type mismatch: expected plan_approval_response, "
  314. f"got {response_type}\033[0m")
  315. return
  316. if state.status != "pending":
  317. print(f" \033[33m[protocol] {request_id} already {state.status}, "
  318. f"ignoring duplicate\033[0m")
  319. return
  320. state.status = "approved" if approve else "rejected"
  321. icon = "✓" if approve else "✗"
  322. color = "32" if approve else "31"
  323. print(f" \033[{color}m[protocol] {state.type} {icon} "
  324. f"({request_id}: {state.status})\033[0m")
  325. # ── 统一 Lead 收件箱消费者 (s16 修复) ──
  326. # check_inbox 工具和主循环都会调用这个函数。
  327. # 返回前通过 match_response 路由协议响应。
  328. def consume_lead_inbox(route_protocol: bool = True) -> list[dict]:
  329. """Read Lead's inbox. Route protocol responses, return all messages.
  330. Called by both run_check_inbox() and main loop to avoid
  331. messages being consumed without protocol routing."""
  332. msgs = BUS.read_inbox("lead")
  333. if not msgs:
  334. return []
  335. if route_protocol:
  336. for msg in msgs:
  337. meta = msg.get("metadata", {})
  338. req_id = meta.get("request_id", "")
  339. msg_type = msg.get("type", "")
  340. if req_id and msg_type.endswith("_response"):
  341. approve = meta.get("approve", False)
  342. match_response(msg_type, req_id, approve)
  343. return msgs
  344. # ── 队友线程 (s16: 空闲循环 + 分发) ──
  345. def spawn_teammate_thread(name: str, role: str, prompt: str) -> str:
  346. """Spawn a teammate agent in a background thread.
  347. Uses idle loop: 等待 each LLM 轮次, waits for inbox messages
  348. (shutdown_request, new task) instead of exiting."""
  349. if name in active_teammates:
  350. return f"队友 '{name}' 已存在"
  351. system = (f"你是 '{name}',角色是 {role}。"
  352. f"使用工具完成任务。"
  353. f"检查收件箱中的协议消息(shutdown_request 等)。")
  354. def handle_inbox_message(name: str, msg: dict, messages: list) -> bool:
  355. """Dispatch incoming protocol messages by type.
  356. Returns True if teammate should stop."""
  357. msg_type = msg.get("type", "message")
  358. meta = msg.get("metadata", {})
  359. req_id = meta.get("request_id", "")
  360. if msg_type == "shutdown_request":
  361. BUS.send(name, "lead", "正在平滑关闭。",
  362. "shutdown_response",
  363. {"request_id": req_id, "approve": True})
  364. print(f" \033[35m[protocol] {name} approved shutdown "
  365. f"({req_id})\033[0m")
  366. return True # 停止循环
  367. if msg_type == "plan_approval_response":
  368. approve = meta.get("approve", False)
  369. if approve:
  370. messages.append({"role": "user",
  371. "content": f"[计划已批准] 继续执行任务。"})
  372. else:
  373. messages.append({"role": "user",
  374. "content": f"[计划已拒绝] 反馈:{msg['content']}"})
  375. return False # 继续
  376. def run():
  377. messages = [{"role": "user", "content": prompt}]
  378. sub_tools = [
  379. {"name": "bash", "description": "运行一条 shell 命令。",
  380. "input_schema": {"type": "object",
  381. "properties": {"command": {"type": "string"}},
  382. "required": ["command"]}},
  383. {"name": "read_file", "description": "读取文件。",
  384. "input_schema": {"type": "object",
  385. "properties": {"path": {"type": "string"}},
  386. "required": ["path"]}},
  387. {"name": "write_file", "description": "写入文件。",
  388. "input_schema": {"type": "object",
  389. "properties": {"path": {"type": "string"},
  390. "content": {"type": "string"}},
  391. "required": ["path", "content"]}},
  392. {"name": "send_message",
  393. "description": "Send message to another agent.",
  394. "input_schema": {"type": "object",
  395. "properties": {"to": {"type": "string"},
  396. "content": {"type": "string"}},
  397. "required": ["to", "content"]}},
  398. {"name": "submit_plan",
  399. "description": "提交计划给 Lead 审批。",
  400. "input_schema": {"type": "object",
  401. "properties": {"plan": {"type": "string"}},
  402. "required": ["plan"]}},
  403. ]
  404. sub_handlers = {
  405. "bash": run_bash, "read_file": run_read, "write_file": run_write,
  406. "send_message": lambda to, content: (BUS.send(name, to, content),
  407. "Sent")[1],
  408. "submit_plan": lambda plan: _teammate_submit_plan(name, plan),
  409. }
  410. shutdown_requested = False
  411. while not shutdown_requested:
  412. # 检查收件箱中的协议消息
  413. inbox = BUS.read_inbox(name)
  414. should_stop = False
  415. non_protocol = []
  416. for msg in inbox:
  417. if msg.get("type") in ("shutdown_request", "plan_approval_response"):
  418. should_stop = handle_inbox_message(name, msg, messages)
  419. if should_stop:
  420. break
  421. else:
  422. non_protocol.append(msg)
  423. if should_stop:
  424. shutdown_requested = True
  425. break
  426. if non_protocol:
  427. inbox_json = json.dumps(non_protocol)
  428. messages.append({"role": "user",
  429. "content": "<inbox>" + inbox_json + "</inbox>"})
  430. # LLM 轮次
  431. try:
  432. response = client.messages.create(
  433. model=MODEL, system=system, messages=messages[-20:],
  434. tools=sub_tools, max_tokens=8000)
  435. except Exception:
  436. break
  437. messages.append({"role": "assistant", "content": response.content})
  438. if response.stop_reason != "tool_use":
  439. # 空闲:等待收件箱消息,而不是退出
  440. # 真实 CC 会在这里向 Lead 发送 idle_notification
  441. while not shutdown_requested:
  442. time.sleep(1)
  443. inbox = BUS.read_inbox(name)
  444. if not inbox:
  445. continue
  446. for msg in inbox:
  447. if msg.get("type") in ("shutdown_request", "plan_approval_response"):
  448. should_stop = handle_inbox_message(name, msg, messages)
  449. if should_stop:
  450. shutdown_requested = True
  451. break
  452. else:
  453. non_protocol.append(msg)
  454. if shutdown_requested:
  455. break
  456. if non_protocol:
  457. inbox_json = json.dumps(non_protocol)
  458. messages.append({"role": "user",
  459. "content": "<inbox>" + inbox_json + "</inbox>"})
  460. break # 带着新消息回到 LLM 轮次
  461. # 执行工具调用
  462. results = []
  463. for block in response.content:
  464. if block.type == "tool_use":
  465. handler = sub_handlers.get(block.name)
  466. output = handler(**block.input) if handler else "未知"
  467. results.append({"type": "tool_result",
  468. "tool_use_id": block.id,
  469. "content": str(output)})
  470. messages.append({"role": "user", "content": results})
  471. # 向 Lead 发送最终摘要
  472. summary = "已完成。"
  473. for msg in reversed(messages):
  474. if msg["role"] == "assistant" and isinstance(msg["content"], list):
  475. for b in msg["content"]:
  476. if getattr(b, "type", None) == "text":
  477. summary = b.text
  478. break
  479. else:
  480. continue
  481. break
  482. BUS.send(name, "lead", summary, "result")
  483. active_teammates.pop(name, None)
  484. print(f" \033[32m[teammate] {name} finished\033[0m")
  485. active_teammates[name] = True
  486. threading.Thread(target=run, daemon=True).start()
  487. print(f" \033[36m[teammate] {name} spawned as {role}\033[0m")
  488. return f"队友 '{name}' 已启动为 {role}"
  489. def _teammate_submit_plan(from_name: str, plan: str) -> str:
  490. """Teammate submits a plan to Lead for approval.
  491. Note: This is a protocol-level request, not a code-level gate.
  492. After submitting, the teammate's thread 继续s running — it can
  493. still call bash/write/etc. Real enforcement relies on the model
  494. waiting for the approval response before acting. Code-level tool
  495. gating would require blocking the teammate's tool dispatch until
  496. approval arrives.
  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 Protocol 工具 (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[protocol] 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 asks a teammate to submit a plan for a task."""
  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 ("Approved" if approve else "Rejected"),
  533. "plan_approval_response",
  534. {"request_id": request_id, "approve": approve})
  535. icon = "✓" if approve else "✗"
  536. print(f" \033[32m[protocol] plan {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": "Send message to a teammate via 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. """Derive context from real state."""
  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"[Background task {bg_id} started] "
  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[Inbox: {len(inbox_msgs)} 条消息已注入]\033[0m")
  739. print()