code.py 36 KB

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