s09 teammate执行费事任务,导致Lead因为没有工具调用,提前退出怎么办,也没有最佳实践
s09 teammate执行费事任务,导致Lead因为没有工具调用,提前退出怎么办,也没有最佳实践
我个人的解决方案,想问问有没有最佳实践
Lead 提前退出问题分析与修复
问题描述
Lead 在孵化 Teammate 后,只要 LLM 返回纯文本(不调用工具),AgentRunner 立即退出循环,REPL 显示 MiniCode >> 提示符。
但此时 Teammate 守护线程仍在后台执行任务,导致:
- 提示符与 Teammate 输出交织:
MiniCode >>出现在 Teammate 工具调用日志中间,终端输出混乱 - Lead 丢失队员结果:Teammate 完成任务后发送的 inbox 消息无人消费,Lead 无法汇总最终结果
根因分析
AgentRunner.run() 的退出条件过于简单:
# runner.py — 原逻辑
if not assistant_msg.tool_calls:
return last_text # 无工具调用就直接退出
Lead 说完"我已孵化队员"后不再调工具 → runner 退出 → agent_loop 返回 → REPL 回到 input()。
而 Teammate 线程是 daemon=True,独立运行,不受 Lead 循环影响。
解决方案
核心思路
在 runner 的"无 tool_calls → 退出"路径上增加一个钩子 wait_for_teammates,让 Lead 阻塞等待直到:
- 有新的 inbox / BG 数据到达 → 唤醒 LLM 处理
- 所有 Teammate 已 shutdown → 正常退出
改动清单
| 文件 | 改动 |
|---|---|
tools/runner.py |
新增 wait_for_teammates 钩子参数;无 tool_calls 时先调钩子,返回 "continue" 则继续循环 |
agent.py |
实现 wait_for_teammates 回调:阻塞轮询 BUS.peek("lead") 和 BG.has_pending(),有数据才唤醒 |
tools/messaging.py |
新增 peek(name) 方法:检查邮箱文件是否非空,不消费 |
tools/background.py |
新增 has_pending() 方法:检查通知队列是否非空,不消费 |
tools/team.py |
新增 all_shutdown() 方法:判断是否所有队员都已 shutdown |
agent.py 的 pre_step |
新增 all_shutdown() 检查:全部队员结束时返回 "stop" 干净退出 |
关键代码
runner.py — 退出条件增加钩子
if not assistant_msg.tool_calls:
if self.wait_for_teammates and self.wait_for_teammates(messages) == "continue":
continue # 不退出,继续下一轮(等待队员结果)
return last_text
agent.py — 阻塞等待实现
def wait_for_teammates(msgs: list):
if not TEAM.config["members"] or TEAM.all_shutdown():
return None # 没队员或全部结束,正常退出
while True:
time.sleep(POLL_INTERVAL)
if TEAM.all_shutdown():
return None
if BUS.peek("lead") or BG.has_pending():
return "continue" # 有新数据,唤醒 LLM
完整生命周期(修复后)
1. 用户输入任务 → agent_loop 启动
2. Lead 调用 spawn_teammate 孵化队员
3. Lead 返回纯文本 → wait_for_teammates 介入,阻塞等待
4. Teammate 完成任务 → 发 inbox 给 Lead
5. wait_for_teammates 检测到 inbox 有数据 → return "continue"
6. pre_step 消费 inbox → 注入对话 → LLM 处理结果
7. 重复 3-6 直到所有 Teammate shutdown
8. pre_step 检测 all_shutdown() → return "stop"
9. agent_loop 返回 → REPL 显示 MiniCode >>
Lead等team是不是有点降低身份了,要不给Lead提供一个叫床服务,Lead还是可以睡觉的
感谢 @artmeng 提出这个问题,也感谢你给出的分析和方案。我们在新版本更新中已经把 input() 和 turn 解耦,用一个 inbox poller 每秒轮询,一旦检测到队友消息或后台任务完成,就自动开启新的一轮 turn。既不需要用户输入、也不阻塞 prompt,这和 Claude Code 的 useInboxPoller 的实现思路一致。