code.py 31 KB

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