code.py 30 KB

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