code.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. #!/usr/bin/env python3
  2. """
  3. s15: Agent 团队 — MessageBus + spawn_teammate_thread + 收件箱注入。
  4. 运行: python s15_agent_teams/code.py
  5. 需要: pip install anthropic python-dotenv + .env 中配置 ANTHROPIC_API_KEY
  6. 相对 s14 的变化:
  7. - MessageBus 类:基于文件的邮箱(.mailboxes/*.jsonl)
  8. - spawn_teammate_thread:在后台线程中创建队友
  9. - 队友运行自己的简化 agent_loop(bash、read、write、send_message)
  10. - Lead 工具:spawn_teammate、send_message、check_inbox(3 个新增)
  11. - Lead 收件箱:队友消息会注入历史(不只是打印)
  12. - 教学版本:队友限制为 10 轮(真实 CC 使用空闲循环)
  13. ASCII 流程:
  14. Lead: cron_queue → messages → prompt → LLM → TOOLS ────→ 循环
  15. ↑ ↓ |
  16. └── inbox ← MessageBus ← teammate.send_message ←┘
  17. Teammate: inbox → LLM → bash/read/write/send → 循环(最多 10 轮)
  18. """
  19. import os, subprocess, json, time, random, threading, queue
  20. from pathlib import Path
  21. from datetime import datetime
  22. from dataclasses import dataclass, asdict
  23. try:
  24. import readline
  25. readline.parse_and_bind('set bind-tty-special-chars off')
  26. except ImportError:
  27. pass
  28. from anthropic import Anthropic
  29. from dotenv import load_dotenv
  30. load_dotenv(override=True)
  31. if os.getenv("ANTHROPIC_BASE_URL"):
  32. os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
  33. WORKDIR = Path.cwd()
  34. MEMORY_DIR = WORKDIR / ".memory"
  35. MEMORY_INDEX = MEMORY_DIR / "MEMORY.md"
  36. client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
  37. MODEL = os.environ["MODEL_ID"]
  38. # ── 任务系统 (来自 s12,已同步) ──
  39. TASKS_DIR = WORKDIR / ".tasks"
  40. TASKS_DIR.mkdir(exist_ok=True)
  41. @dataclass
  42. class Task:
  43. id: str
  44. subject: str
  45. description: str
  46. status: str # pending | in_progress | completed
  47. owner: str | None
  48. blockedBy: list[str]
  49. def _task_path(task_id: str) -> Path:
  50. return TASKS_DIR / f"{task_id}.json"
  51. def create_task(subject: str, description: str = "",
  52. blockedBy: list[str] | None = None) -> Task:
  53. task = Task(
  54. id=f"task_{int(time.time())}_{random.randint(0, 9999):04d}",
  55. subject=subject, description=description,
  56. status="pending", owner=None,
  57. blockedBy=blockedBy or [],
  58. )
  59. save_task(task)
  60. return task
  61. def save_task(task: Task):
  62. _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))
  63. def load_task(task_id: str) -> Task:
  64. return Task(**json.loads(_task_path(task_id).read_text()))
  65. def list_tasks() -> list[Task]:
  66. return [Task(**json.loads(p.read_text()))
  67. for p in sorted(TASKS_DIR.glob("task_*.json"))]
  68. def get_task(task_id: str) -> str:
  69. """以 JSON 返回完整任务详情。"""
  70. task = load_task(task_id)
  71. return json.dumps(asdict(task), indent=2)
  72. def can_start(task_id: str) -> bool:
  73. """检查所有 blockedBy 依赖是否已完成;缺失依赖视为阻塞。"""
  74. task = load_task(task_id)
  75. for dep_id in task.blockedBy:
  76. if not _task_path(dep_id).exists():
  77. return False
  78. if load_task(dep_id).status != "completed":
  79. return False
  80. return True
  81. def claim_task(task_id: str, owner: str = "agent") -> str:
  82. task = load_task(task_id)
  83. if task.status != "pending":
  84. status = {"pending": "待处理", "in_progress": "进行中",
  85. "completed": "已完成"}.get(task.status, task.status)
  86. return f"任务 {task_id} 当前状态为 {status},无法认领"
  87. if not can_start(task_id):
  88. deps = [d for d in task.blockedBy
  89. if not _task_path(d).exists() or load_task(d).status != "completed"]
  90. return f"被阻塞于:{deps}"
  91. task.owner = owner
  92. task.status = "in_progress"
  93. save_task(task)
  94. print(f" \033[36m[认领] {task.subject} → in_progress(负责人:{owner})\033[0m")
  95. return f"已认领 {task.id} ({task.subject})"
  96. def complete_task(task_id: str) -> str:
  97. task = load_task(task_id)
  98. if task.status != "in_progress":
  99. status = {"pending": "待处理", "in_progress": "进行中",
  100. "completed": "已完成"}.get(task.status, task.status)
  101. return f"任务 {task_id} 当前状态为 {status},无法完成"
  102. task.status = "completed"
  103. save_task(task)
  104. unblocked = [t.subject for t in list_tasks()
  105. if t.status == "pending" and t.blockedBy and can_start(t.id)]
  106. print(f" \033[32m[完成] {task.subject} ✓\033[0m")
  107. msg = f"已完成 {task.id} ({task.subject})"
  108. if unblocked:
  109. msg += f"\n已解除阻塞:{', '.join(unblocked)}"
  110. print(f" \033[33m[已解除阻塞] {', '.join(unblocked)}\033[0m")
  111. return msg
  112. # ── 提示词组装 (来自 s10,已同步) ──
  113. PROMPT_SECTIONS = {
  114. "identity": "你是一个编码 Agent。直接行动,不要只解释。",
  115. "tools": "可用工具:bash, read_file, write_file, "
  116. "get_task, create_task, list_tasks, claim_task, complete_task, "
  117. "schedule_cron, list_crons, cancel_cron, "
  118. "spawn_teammate, send_message, check_inbox.",
  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. memories = context.get("memories", "")
  127. if memories:
  128. sections.append(f"相关记忆:\n{memories}")
  129. return "\n\n".join(sections)
  130. _last_context_key, _last_prompt = None, None
  131. def get_system_prompt(context: dict) -> str:
  132. global _last_context_key, _last_prompt
  133. key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)
  134. if key == _last_context_key and _last_prompt:
  135. return _last_prompt
  136. _last_context_key = key
  137. _last_prompt = assemble_system_prompt(context)
  138. return _last_prompt
  139. # ── 工具 ──
  140. def safe_path(p: str) -> Path:
  141. path = (WORKDIR / p).resolve()
  142. if not path.is_relative_to(WORKDIR):
  143. raise ValueError(f"路径逃逸出工作区:{p}")
  144. return path
  145. def run_bash(command: str, run_in_background: bool = False) -> str:
  146. # run_in_background 由 agent_loop 分发处理,不在这里处理
  147. try:
  148. r = subprocess.run(command, shell=True, cwd=WORKDIR,
  149. capture_output=True, text=True, timeout=120)
  150. out = (r.stdout + r.stderr).strip()
  151. return out[:50000] if out else "(无输出)"
  152. except subprocess.TimeoutExpired:
  153. return "错误:执行超时(120 秒)"
  154. def run_read(path: str, limit: int | None = None) -> str:
  155. try:
  156. lines = safe_path(path).read_text().splitlines()
  157. if limit and limit < len(lines):
  158. lines = lines[:limit] + [f"... ({len(lines) - limit} 行更多内容)"]
  159. return "\n".join(lines)
  160. except Exception as e:
  161. return f"错误:{e}"
  162. def run_write(path: str, content: str) -> str:
  163. try:
  164. fp = safe_path(path)
  165. fp.parent.mkdir(parents=True, exist_ok=True)
  166. fp.write_text(content)
  167. return f"已写入 {len(content)} 字节到 {path}"
  168. except Exception as e:
  169. return f"错误:{e}"
  170. # 任务工具
  171. def run_create_task(subject: str, description: str = "",
  172. blockedBy: list[str] | None = None) -> str:
  173. task = create_task(subject, description, blockedBy)
  174. deps = f"(依赖:{', '.join(blockedBy)})" if blockedBy else ""
  175. print(f" \033[34m[创建] {task.subject}{deps}\033[0m")
  176. return f"已创建 {task.id}: {task.subject}{deps}"
  177. def run_list_tasks() -> str:
  178. 个任务 = list_tasks()
  179. if not 个任务:
  180. return "暂无任务。请使用 create_task 添加任务。"
  181. lines = []
  182. for t in 个任务:
  183. icon = {"pending": "○", "in_progress": "●",
  184. "completed": "✓"}.get(t.status, "?")
  185. deps = f"(依赖:{', '.join(t.blockedBy)})" if t.blockedBy else ""
  186. owner = f" [负责人:{t.owner}]" if t.owner else ""
  187. status = {"pending": "待处理", "in_progress": "进行中",
  188. "completed": "已完成"}.get(t.status, t.status)
  189. lines.append(f" {icon} {t.id}: {t.subject} "
  190. f"[{status}]{owner}{deps}")
  191. return "\n".join(lines)
  192. def run_get_task(task_id: str) -> str:
  193. try:
  194. return get_task(task_id)
  195. except FileNotFoundError:
  196. return f"错误:任务 {task_id} 未找到"
  197. def run_claim_task(task_id: str) -> str:
  198. return claim_task(task_id, owner="agent")
  199. def run_complete_task(task_id: str) -> str:
  200. return complete_task(task_id)
  201. # ── 后台任务 (来自 s13,已同步) ──
  202. _bg_计数器 = 0
  203. background_tasks: dict[str, dict] = {}
  204. background_results: dict[str, str] = {}
  205. background_lock = threading.Lock()
  206. def is_slow_operation(tool_name: str, tool_input: dict) -> bool:
  207. """兜底启发式:判断命令是否可能超过 30 秒。"""
  208. if tool_name != "bash":
  209. return False
  210. cmd = tool_input.get("command", "").lower()
  211. slow_keywords = ["install", "build", "test", "deploy", "compile",
  212. "docker build", "pip install", "npm install",
  213. "cargo build", "pytest", "make"]
  214. return any(kw in cmd for kw in slow_keywords)
  215. def should_run_background(tool_name: str, tool_input: dict) -> bool:
  216. """模型的显式请求优先;否则使用启发式兜底。"""
  217. if tool_input.get("run_in_background"):
  218. return True
  219. return is_slow_operation(tool_name, tool_input)
  220. def execute_tool(block) -> str:
  221. """执行工具调用块并返回输出。"""
  222. handler = {
  223. "bash": run_bash, "read_file": run_read, "write_file": run_write,
  224. "create_task": run_create_task, "list_tasks": run_list_tasks,
  225. "get_task": run_get_task, "claim_task": run_claim_task,
  226. "complete_task": run_complete_task,
  227. "schedule_cron": run_schedule_cron, "list_crons": run_list_crons,
  228. "cancel_cron": run_cancel_cron,
  229. "spawn_teammate": run_spawn_teammate,
  230. "send_message": run_send_message, "check_inbox": run_check_inbox,
  231. }.get(block.name)
  232. if handler:
  233. return handler(**block.input)
  234. return f"未知工具:{block.name}"
  235. def start_background_task(block) -> str:
  236. """在守护线程中运行工具,并返回后台任务 ID。"""
  237. global _bg_计数器
  238. _bg_计数器 += 1
  239. bg_id = f"bg_{_bg_计数器:04d}"
  240. cmd = block.input.get("command", block.name)
  241. def worker():
  242. result = execute_tool(block)
  243. with background_lock:
  244. background_tasks[bg_id]["status"] = "completed"
  245. background_results[bg_id] = result
  246. with background_lock:
  247. background_tasks[bg_id] = {
  248. "tool_use_id": block.id,
  249. "command": cmd,
  250. "status": "running",
  251. }
  252. threading.Thread(target=worker, daemon=True).start()
  253. print(f" \033[33m[后台] 已分发 {bg_id}: {cmd[:40]}\033[0m")
  254. return bg_id
  255. def collect_background_results() -> list[str]:
  256. """将已完成的后台结果收集为 task_notification 消息。"""
  257. with background_lock:
  258. ready_ids = [bid for bid, task in background_tasks.items()
  259. if task["status"] == "completed"]
  260. notifications = []
  261. for bg_id in ready_ids:
  262. with background_lock:
  263. task = background_tasks.pop(bg_id)
  264. output = background_results.pop(bg_id, "")
  265. summary = output[:200] if len(output) > 200 else output
  266. notifications.append(
  267. f"<task_notification>\n"
  268. f" <task_id>{bg_id}</task_id>\n"
  269. f" <status>completed</status>\n"
  270. f" <command>{task['command']}</command>\n"
  271. f" <summary>{summary}</summary>\n"
  272. f"</task_notification>")
  273. print(f" \033[32m[后台完成] {bg_id}: "
  274. f"{task['command'][:40]} ({len(output)} 个字符)\033[0m")
  275. return notifications
  276. def has_pending_background() -> bool:
  277. """非破坏性检查:是否有后台任务已完成并等待收集。
  278. 收件箱轮询器会把它作为唤醒条件之一。"""
  279. with background_lock:
  280. return any(t["status"] == "completed" for t in background_tasks.values())
  281. # ── Cron 调度器 (来自 s14,已同步) ──
  282. DURABLE_PATH = WORKDIR / ".scheduled_tasks.json"
  283. @dataclass
  284. class CronJob:
  285. id: str
  286. cron: str # "0 9 * * *"
  287. prompt: str # 触发时要注入的消息
  288. recurring: bool # 为真 = 重复,为假 = 一次性
  289. durable: bool # 为真 = 持久化到磁盘
  290. scheduled_jobs: dict[str, CronJob] = {}
  291. cron_queue: list[CronJob] = []
  292. cron_lock = threading.Lock()
  293. _last_fired: dict[str, str] = {} # job_id → "YYYY-MM-DD HH:MM"
  294. def _cron_field_matches(field: str, value: int) -> bool:
  295. """将单个 cron 字段与一个值进行匹配。"""
  296. if field == "*":
  297. return True
  298. if field.startswith("*/"):
  299. step = int(field[2:])
  300. return step > 0 and value % step == 0
  301. if "," in field:
  302. return any(_cron_field_matches(f.strip(), value)
  303. for f in field.split(","))
  304. if "-" in field:
  305. lo, hi = field.split("-", 1)
  306. return int(lo) <= value <= int(hi)
  307. return value == int(field)
  308. def cron_matches(cron_expr: str, dt: datetime) -> bool:
  309. """检查 5 字段 cron 表达式是否匹配给定时间。
  310. 标准 cron 语义:月内日和周内日同时受限时,两者使用 OR。"""
  311. fields = cron_expr.strip().split()
  312. if len(fields) != 5:
  313. return False
  314. minute, hour, dom, month, dow = fields
  315. dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0
  316. m = _cron_field_matches(minute, dt.minute)
  317. h = _cron_field_matches(hour, dt.hour)
  318. dom_ok = _cron_field_matches(dom, dt.day)
  319. month_ok = _cron_field_matches(month, dt.month)
  320. dow_ok = _cron_field_matches(dow, dow_val)
  321. # 分钟、小时、月份必须全部匹配
  322. if not (m and h and month_ok):
  323. return False
  324. # DOM 和 DOW:如果两者都有限制,任一匹配即可(OR)
  325. dom_unconstrained = dom == "*"
  326. dow_unconstrained = dow == "*"
  327. if dom_unconstrained and dow_unconstrained:
  328. return True
  329. if dom_unconstrained:
  330. return dow_ok
  331. if dow_unconstrained:
  332. return dom_ok
  333. return dom_ok or dow_ok
  334. def _validate_cron_field(field: str, lo: int, hi: int) -> str | None:
  335. """校验单个 cron 字段值是否位于 [lo, hi] 范围内。"""
  336. if field == "*":
  337. return None
  338. if field.startswith("*/"):
  339. step_str = field[2:]
  340. if not step_str.isdigit():
  341. return f"无效步长:{field}"
  342. step = int(step_str)
  343. if step <= 0:
  344. return f"步长必须 > 0:{field}"
  345. return None
  346. if "," in field:
  347. for part in field.split(","):
  348. err = _validate_cron_field(part.strip(), lo, hi)
  349. if err: return err
  350. return None
  351. if "-" in field:
  352. parts = field.split("-", 1)
  353. if not parts[0].isdigit() or not parts[1].isdigit():
  354. return f"无效范围:{field}"
  355. a, b = int(parts[0]), int(parts[1])
  356. if a < lo or a > hi or b < lo or b > hi:
  357. return f"范围 {field} 超出边界 [{lo}-{hi}]"
  358. if a > b:
  359. return f"范围起点大于终点:{field}"
  360. return None
  361. if not field.isdigit():
  362. return f"无效字段:{field}"
  363. val = int(field)
  364. if val < lo or val > hi:
  365. return f"值 {val} 超出边界 [{lo}-{hi}]"
  366. return None
  367. def validate_cron(cron_expr: str) -> str | None:
  368. """校验 cron 表达式。返回错误消息或 None。"""
  369. fields = cron_expr.strip().split()
  370. if len(fields) != 5:
  371. return f"期望 5 个字段,实际得到 {len(fields)}"
  372. bounds = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 6)]
  373. names = ["分", "时", "月内日", "月", "周内日"]
  374. for i, (field, (lo, hi), name) in enumerate(zip(fields, bounds, names)):
  375. err = _validate_cron_field(field, lo, hi)
  376. if err:
  377. return f"{name}: {err}"
  378. return None
  379. def save_durable_jobs():
  380. """将持久任务保存到 .scheduled_tasks.json。"""
  381. durable = [asdict(j) for j in scheduled_jobs.values() if j.durable]
  382. DURABLE_PATH.write_text(json.dumps(durable, indent=2))
  383. def load_durable_jobs():
  384. """启动时从磁盘加载持久任务。"""
  385. if not DURABLE_PATH.exists():
  386. return
  387. try:
  388. jobs = json.loads(DURABLE_PATH.read_text())
  389. for j in jobs:
  390. job = CronJob(**j)
  391. err = validate_cron(job.cron)
  392. if err:
  393. print(f" \033[31m[cron] 跳过无效任务 {job.id}: {err}\033[0m")
  394. continue
  395. scheduled_jobs[job.id] = job
  396. valid = [j for j in jobs if j["id"] in scheduled_jobs]
  397. if valid:
  398. print(f" \033[35m[cron] 已加载 {len(valid)} 个持久任务\033[0m")
  399. except Exception:
  400. pass
  401. def schedule_job(cron: str, prompt: str, recurring: bool = True,
  402. durable: bool = True) -> CronJob | str:
  403. """注册一个新的 cron 任务。返回 CronJob 或错误字符串。"""
  404. err = validate_cron(cron)
  405. if err:
  406. return err
  407. job = CronJob(
  408. id=f"cron_{random.randint(0, 999999):06d}",
  409. cron=cron, prompt=prompt,
  410. recurring=recurring, durable=durable,
  411. )
  412. with cron_lock:
  413. scheduled_jobs[job.id] = job
  414. if durable:
  415. save_durable_jobs()
  416. print(f" \033[35m[cron 注册] {job.id} '{cron}' → {prompt[:40]}\033[0m")
  417. return job
  418. def cancel_job(job_id: str) -> str:
  419. """取消一个 cron 任务。"""
  420. with cron_lock:
  421. job = scheduled_jobs.pop(job_id, None)
  422. if not job:
  423. return f"任务 {job_id} 未找到"
  424. if job.durable:
  425. save_durable_jobs()
  426. print(f" \033[31m[cron 取消] {job_id}\033[0m")
  427. return f"已取消 {job_id}"
  428. def cron_scheduler_loop():
  429. """独立守护线程:每秒轮询一次并触发匹配任务。
  430. 单个任务出错会被捕获,避免整个调度线程退出。"""
  431. while True:
  432. time.sleep(1)
  433. now = datetime.now()
  434. # 带日期感知的标记,防止每日任务从第 2 天起被跳过
  435. minute_marker = now.strftime("%Y-%m-%d %H:%M")
  436. with cron_lock:
  437. for job in list(scheduled_jobs.values()):
  438. try:
  439. if cron_matches(job.cron, now):
  440. if _last_fired.get(job.id) != minute_marker:
  441. cron_queue.append(job)
  442. _last_fired[job.id] = minute_marker
  443. print(f" \033[35m[cron 触发] {job.id} → "
  444. f"{job.prompt[:40]}\033[0m")
  445. if not job.recurring:
  446. scheduled_jobs.pop(job.id, None)
  447. if job.durable:
  448. save_durable_jobs()
  449. except Exception as e:
  450. print(f" \033[31m[cron 错误] {job.id}: {e}\033[0m")
  451. def consume_cron_queue() -> list[CronJob]:
  452. """消费 cron_queue 中已触发的任务(由 agent_loop 调用)。"""
  453. with cron_lock:
  454. fired = list(cron_queue)
  455. cron_queue.clear()
  456. return fired
  457. # 启动时加载持久任务,然后启动调度线程
  458. load_durable_jobs()
  459. threading.Thread(target=cron_scheduler_loop, daemon=True).start()
  460. print(" \033[35m[cron] 调度线程已启动\033[0m")
  461. # Cron 工具处理器
  462. def run_schedule_cron(cron: str, prompt: str,
  463. recurring: bool = True, durable: bool = True) -> str:
  464. result = schedule_job(cron, prompt, recurring, durable)
  465. if isinstance(result, str):
  466. return f"错误:{result}"
  467. return f"已调度 {result.id}: '{cron}' → {prompt}"
  468. def run_list_crons() -> str:
  469. with cron_lock:
  470. jobs = list(scheduled_jobs.values())
  471. if not jobs:
  472. return "暂无 cron 任务。请使用 schedule_cron 添加一个。"
  473. lines = []
  474. for j in jobs:
  475. tag = "重复" if j.recurring else "一次性"
  476. dur = "持久化" if j.durable else "仅本会话"
  477. lines.append(f" {j.id}: '{j.cron}' → {j.prompt[:40]} "
  478. f"[{tag}, {dur}]")
  479. return "\n".join(lines)
  480. def run_cancel_cron(job_id: str) -> str:
  481. return cancel_job(job_id)
  482. # ── MessageBus (s15 新增) ──
  483. # 教学版本使用简单的文件追加 + 删除。
  484. # 真实 CC 使用 proper-lockfile 保证并发写入安全。
  485. MAILBOX_DIR = WORKDIR / ".mailboxes"
  486. MAILBOX_DIR.mkdir(exist_ok=True)
  487. class MessageBus:
  488. """基于文件的消息总线。每个 Agent 都有一个 .jsonl 收件箱。
  489. 读取是破坏性的:read_text + unlink 会消费消息。
  490. 教学版本不做文件锁;真实 CC 使用 proper-lockfile。"""
  491. def send(self, from_agent: str, to_agent: str, content: str,
  492. msg_type: str = "message"):
  493. msg = {"from": from_agent, "to": to_agent,
  494. "content": content, "type": msg_type,
  495. "ts": time.time()}
  496. inbox = MAILBOX_DIR / f"{to_agent}.jsonl"
  497. with open(inbox, "a") as f:
  498. f.write(json.dumps(msg) + "\n")
  499. print(f" \033[33m[bus] {from_agent} → {to_agent}: "
  500. f"{content[:50]}\033[0m")
  501. def read_inbox(self, agent: str) -> list[dict]:
  502. inbox = MAILBOX_DIR / f"{agent}.jsonl"
  503. if not inbox.exists():
  504. return []
  505. msgs = [json.loads(line) for line in inbox.read_text().splitlines()
  506. if line.strip()]
  507. inbox.unlink() # 消费:读取 + 删除
  508. return msgs
  509. def peek(self, agent: str) -> bool:
  510. """非破坏性检查:Agent 是否有未读收件箱消息。
  511. Lead 的收件箱轮询器用它决定是否唤醒一轮,同时不消费邮箱。"""
  512. inbox = MAILBOX_DIR / f"{agent}.jsonl"
  513. return inbox.exists() and inbox.stat().st_size > 0
  514. BUS = MessageBus()
  515. # 跟踪已启动的队友
  516. active_teammates: dict[str, bool] = {}
  517. # ── 队友线程 (s15 新增) ──
  518. def spawn_teammate_thread(name: str, role: str, prompt: str) -> str:
  519. """在后台线程中启动队友 Agent。
  520. 教学版本中每个队友最多运行 10 轮。
  521. 真实 CC 的队友使用空闲循环:等待收件箱、工作、重复,直到收到 shutdown_request。"""
  522. if name in active_teammates:
  523. return f"队友 '{name}' 已存在"
  524. system = (f"你是 '{name}',角色是 {role}。"
  525. f"使用工具完成任务。"
  526. f"通过 send_message 将结果发送给 'lead'。")
  527. def run():
  528. messages = [{"role": "user", "content": prompt}]
  529. sub_tools = [
  530. {"name": "bash", "description": "运行一条 shell 命令。",
  531. "input_schema": {"type": "object",
  532. "properties": {"command": {"type": "string"}},
  533. "required": ["command"]}},
  534. {"name": "read_file", "description": "读取文件内容。",
  535. "input_schema": {"type": "object",
  536. "properties": {"path": {"type": "string"}},
  537. "required": ["path"]}},
  538. {"name": "write_file", "description": "向文件写入内容。",
  539. "input_schema": {"type": "object",
  540. "properties": {"path": {"type": "string"},
  541. "content": {"type": "string"}},
  542. "required": ["path", "content"]}},
  543. {"name": "send_message",
  544. "description": "向另一个 Agent 发送消息。",
  545. "input_schema": {"type": "object",
  546. "properties": {"to": {"type": "string"},
  547. "content": {"type": "string"}},
  548. "required": ["to", "content"]}},
  549. ]
  550. sub_handlers = {
  551. "bash": run_bash, "read_file": run_read, "write_file": run_write,
  552. "send_message": lambda to, content: (BUS.send(name, to, content),
  553. "已发送")[1],
  554. }
  555. for _ in range(10):
  556. inbox = BUS.read_inbox(name)
  557. if inbox:
  558. messages.append({"role": "user",
  559. "content": f"<inbox>{json.dumps(inbox)}</inbox>"})
  560. try:
  561. response = client.messages.create(
  562. model=MODEL, system=system, messages=messages[-20:],
  563. tools=sub_tools, max_tokens=8000)
  564. except Exception:
  565. break
  566. messages.append({"role": "assistant", "content": response.content})
  567. if response.stop_reason != "tool_use":
  568. break
  569. results = []
  570. for block in response.content:
  571. if block.type == "tool_use":
  572. handler = sub_handlers.get(block.name)
  573. output = handler(**block.input) if handler else "未知"
  574. results.append({"type": "tool_result",
  575. "tool_use_id": block.id,
  576. "content": str(output)})
  577. messages.append({"role": "user", "content": results})
  578. # 向 Lead 发送最终摘要
  579. summary = "已完成。"
  580. for msg in reversed(messages):
  581. if msg["role"] == "assistant" and isinstance(msg["content"], list):
  582. for b in msg["content"]:
  583. if getattr(b, "type", None) == "text":
  584. summary = b.text
  585. break
  586. else:
  587. continue
  588. break
  589. BUS.send(name, "lead", summary, "result")
  590. active_teammates.pop(name, None)
  591. print(f" \033[32m[队友] {name} 已完成\033[0m")
  592. active_teammates[name] = True
  593. threading.Thread(target=run, daemon=True).start()
  594. print(f" \033[36m[队友] {name} 已作为 {role} 启动\033[0m")
  595. return f"队友 '{name}' 已启动为 {role}"
  596. # ── 团队工具处理器 (s15 新增) ──
  597. def run_spawn_teammate(name: str, role: str, prompt: str) -> str:
  598. return spawn_teammate_thread(name, role, prompt)
  599. def run_send_message(to: str, content: str) -> str:
  600. BUS.send("lead", to, content)
  601. return f"已发送给 {to}"
  602. def run_check_inbox() -> str:
  603. msgs = BUS.read_inbox("lead")
  604. if not msgs:
  605. return "(收件箱为空)"
  606. lines = []
  607. for m in msgs:
  608. lines.append(f" [{m['from']}] {m['content'][:200]}")
  609. return "\n".join(lines)
  610. # ── 工具定义 ──
  611. TOOLS = [
  612. {"name": "bash", "description": "运行一条 shell 命令。",
  613. "input_schema": {"type": "object",
  614. "properties": {
  615. "command": {"type": "string"},
  616. "run_in_background": {"type": "boolean"}},
  617. "required": ["command"]}},
  618. {"name": "read_file", "description": "读取文件内容。",
  619. "input_schema": {"type": "object",
  620. "properties": {"path": {"type": "string"},
  621. "limit": {"type": "integer"}},
  622. "required": ["path"]}},
  623. {"name": "write_file", "description": "向文件写入内容。",
  624. "input_schema": {"type": "object",
  625. "properties": {"path": {"type": "string"},
  626. "content": {"type": "string"}},
  627. "required": ["path", "content"]}},
  628. {"name": "create_task",
  629. "description": "创建一个新任务,可选 blockedBy 依赖。",
  630. "input_schema": {"type": "object",
  631. "properties": {
  632. "subject": {"type": "string"},
  633. "description": {"type": "string"},
  634. "blockedBy": {"type": "array",
  635. "items": {"type": "string"}}},
  636. "required": ["subject"]}},
  637. {"name": "list_tasks",
  638. "description": "列出所有任务及其状态、负责人和依赖。",
  639. "input_schema": {"type": "object", "properties": {},
  640. "required": []}},
  641. {"name": "get_task",
  642. "description": "按 ID 获取指定任务的完整详情。",
  643. "input_schema": {"type": "object",
  644. "properties": {"task_id": {"type": "string"}},
  645. "required": ["task_id"]}},
  646. {"name": "claim_task",
  647. "description": "认领一个待处理任务。设置 owner,并将状态改为 in_progress。",
  648. "input_schema": {"type": "object",
  649. "properties": {"task_id": {"type": "string"}},
  650. "required": ["task_id"]}},
  651. {"name": "complete_task",
  652. "description": "完成一个进行中的任务。报告被解除阻塞的下游任务。",
  653. "input_schema": {"type": "object",
  654. "properties": {"task_id": {"type": "string"}},
  655. "required": ["task_id"]}},
  656. {"name": "schedule_cron",
  657. "description": "调度一个 cron 任务。cron 为 5 字段:分 时 月内日 月 周内日。",
  658. "input_schema": {"type": "object",
  659. "properties": {
  660. "cron": {"type": "string",
  661. "description": "5 字段 cron 表达式"},
  662. "prompt": {"type": "string",
  663. "description": "触发时要注入的消息"},
  664. "recurring": {"type": "boolean",
  665. "description": "为真表示重复,为假表示一次性"},
  666. "durable": {"type": "boolean",
  667. "description": "为真表示持久化到磁盘"}},
  668. "required": ["cron", "prompt"]}},
  669. {"name": "list_crons",
  670. "description": "列出所有已注册的 cron 任务。",
  671. "input_schema": {"type": "object", "properties": {},
  672. "required": []}},
  673. {"name": "cancel_cron",
  674. "description": "按 ID 取消 cron 任务。",
  675. "input_schema": {"type": "object",
  676. "properties": {"job_id": {"type": "string"}},
  677. "required": ["job_id"]}},
  678. {"name": "spawn_teammate",
  679. "description": "在后台线程中启动一个队友 Agent。",
  680. "input_schema": {"type": "object",
  681. "properties": {
  682. "name": {"type": "string"},
  683. "role": {"type": "string"},
  684. "prompt": {"type": "string"}},
  685. "required": ["name", "role", "prompt"]}},
  686. {"name": "send_message",
  687. "description": "通过 MessageBus 向队友发送消息。",
  688. "input_schema": {"type": "object",
  689. "properties": {"to": {"type": "string"},
  690. "content": {"type": "string"}},
  691. "required": ["to", "content"]}},
  692. {"name": "check_inbox",
  693. "description": "检查 Lead 收件箱中的队友消息。",
  694. "input_schema": {"type": "object", "properties": {},
  695. "required": []}},
  696. ]
  697. # ── 上下文 ──
  698. def update_context(context: dict, messages: list) -> dict:
  699. """从真实状态推导上下文。"""
  700. memories = ""
  701. if MEMORY_INDEX.exists():
  702. content = MEMORY_INDEX.read_text().strip()
  703. if content:
  704. memories = content
  705. return {
  706. "enabled_tools": [t["name"] for t in TOOLS],
  707. "workspace": str(WORKDIR),
  708. "memories": memories,
  709. }
  710. # ── Agent 循环 ──
  711. # 教学代码保留基础 Agent 循环。省略 S11 的完整错误恢复。
  712. # 调用 agent_loop 时消费 Cron 队列;真实 CC 会通过
  713. # 队列处理器 (useQueueProcessor.ts) 在条目到达时。
  714. def agent_loop(messages: list, context: dict):
  715. system = get_system_prompt(context)
  716. while True:
  717. # 消费已触发的 cron 任务 → 作为消息注入
  718. fired = consume_cron_queue()
  719. for job in fired:
  720. messages.append({"role": "user",
  721. "content": f"[已调度] {job.prompt}"})
  722. print(f" \033[35m[注入 cron] {job.prompt[:50]}\033[0m")
  723. try:
  724. response = client.messages.create(
  725. model=MODEL, system=system, messages=messages,
  726. tools=TOOLS, max_tokens=8000)
  727. except Exception as e:
  728. messages.append({"role": "assistant", "content": [
  729. {"type": "text",
  730. "text": f"[错误] {type(e).__name__}: {e}"}]})
  731. return
  732. messages.append({"role": "assistant", "content": response.content})
  733. if response.stop_reason != "tool_use":
  734. return
  735. results = []
  736. for block in response.content:
  737. if block.type != "tool_use":
  738. continue
  739. print(f"\033[36m> {block.name}\033[0m")
  740. if should_run_background(block.name, block.input):
  741. bg_id = start_background_task(block)
  742. results.append({"type": "tool_result",
  743. "tool_use_id": block.id,
  744. "content": f"[后台任务 {bg_id} 已启动] "
  745. f"完成后结果将可用。"})
  746. else:
  747. output = execute_tool(block)
  748. print(str(output)[:300])
  749. results.append({"type": "tool_result",
  750. "tool_use_id": block.id,
  751. "content": output})
  752. # 将后台工具结果 + 通知合并成一条用户消息
  753. user_content = list(results)
  754. bg_notifications = collect_background_results()
  755. if bg_notifications:
  756. for notif in bg_notifications:
  757. user_content.append({"type": "text", "text": notif})
  758. messages.append({"role": "user", "content": user_content})
  759. context = update_context(context, messages)
  760. system = get_system_prompt(context)
  761. if __name__ == "__main__":
  762. print("s15: Agent 团队")
  763. print("输入问题后按回车发送。输入 q 退出。\n")
  764. history = []
  765. context = update_context({}, [])
  766. # input() 和 1 秒轮询器(队友收件箱或后台结果)共同写入一个
  767. # 事件队列(问题 #291、#46)。
  768. events = queue.Queue()
  769. def input_reader():
  770. while True:
  771. try:
  772. line = input("\033[36ms15 >> \033[0m")
  773. except (EOFError, KeyboardInterrupt):
  774. events.put(("quit", None))
  775. return
  776. events.put(("user", line))
  777. def inbox_poller():
  778. # 每约 1 秒轮询一次;当异步结果就绪时唤醒 Lead:队友
  779. # 收件箱消息或已完成的后台任务。不要依赖
  780. # active_teammates:队友发送结果后会移除自身,
  781. # 因此最终消息可能比注册表条目存在得更久。
  782. while True:
  783. time.sleep(1)
  784. if BUS.peek("lead") or has_pending_background():
  785. events.put(("唤醒", None))
  786. threading.Thread(target=input_reader, daemon=True).start()
  787. threading.Thread(target=inbox_poller, daemon=True).start()
  788. had_teammates = False
  789. while True:
  790. kind, payload = events.get()
  791. if kind == "quit":
  792. break
  793. if kind == "user":
  794. if payload.strip().lower() in ("q", "exit", ""):
  795. break
  796. history.append({"role": "user", "content": payload})
  797. else: # "唤醒": 队友收件箱或后台结果已就绪
  798. parts = []
  799. inbox = BUS.read_inbox("lead")
  800. if inbox:
  801. parts.append("[收件箱]\n" + "\n".join(
  802. f"来自 {m['from']}: {m['content'][:200]}" for m in inbox))
  803. bg = collect_background_results()
  804. parts.extend(bg)
  805. if not parts:
  806. continue # 已被更早的唤醒消费(幂等)
  807. history.append({"role": "user", "content": "\n".join(parts)})
  808. print(f"\n\033[33m[唤醒: {len(inbox)} 条收件箱消息 + {len(bg)} 条后台通知 "
  809. f"-> 新一轮]\033[0m")
  810. # 为唤醒来源执行一轮。
  811. agent_loop(history, context)
  812. context = update_context(context, history)
  813. for block in history[-1]["content"]:
  814. if getattr(block, "type", None) == "text":
  815. print(block.text)
  816. elif isinstance(block, dict) and block.get("type") == "text":
  817. print(block.get("text", ""))
  818. # 当所有队友完成且输出已消费后,只公告一次。
  819. if active_teammates:
  820. had_teammates = True
  821. elif had_teammates and not BUS.peek("lead") and not has_pending_background():
  822. print("\033[32m[所有队友已完成]\033[0m")
  823. had_teammates = False
  824. print()