Lesson 11 · 协作

自己找活干的 agent

「The agent finds work itself.」不需要人类派单,它会从任务板上自己拿活。

⏱ 약 12 분 · 📝 3 개 인터랙티브 컴포넌트 · 🧑‍💻 기반 shareAI-lab · s11_autonomous_agents.py

从 "被叫醒" 到 "自己找活"

s09 / s10 的 teammate 是被动的:要有人通过邮箱 send message,它才开始干;做完就 idle,再被叫醒再干。

s11 的 autonomous teammate 主动:没活的时候也不真的停下,它会每 5 秒扫一次 .tasks/ 目录——看到没主的 task 就 claim_task 认领,开始干。

Teammate lifecycle:
  +-------+
  | spawn |
  +---+---+
      |
      v
  +-------+
  | WORK  | <-- LLM tool_use 循环
  +---+---+
      |
      | stop_reason != tool_use OR tool_use("idle")
      v
  +-------+
  | IDLE  | poll 每 5s,共 12 次 = 60s 超时
  +---+---+
      |
      +--> inbox 有新消息?  → resume WORK
      |
      +--> scan .tasks/,发现未认领 → claim → resume WORK
      |
      +--> 60s 什么都没等到 → status = shutdown,线程退出

Auto-claim · 从任务板"拿单"

核心函数:

def scan_unclaimed_tasks() -> list:
    unclaimed = []
    for f in sorted(TASKS_DIR.glob("task_*.json")):
        task = json.loads(f.read_text())
        if (task.get("status") == "pending"
                and not task.get("owner")
                and not task.get("blockedBy")):
            unclaimed.append(task)
    return unclaimed

三条过滤 = pending + 无 owner + 无 blockedBy。缺一不可。

claim 动作本身有锁(_claim_lock),防止两个 agent 同时看到同一个 unclaimed task 都去抢——lock 内再读一次、检查 owner 是否还是空、然后 "in_progress" 标记+ owner 写入磁盘。

模拟多个 agent 同时扫任务板

3 个 teammate 在 idle 状态,3 个 task 等待认领。点「下一轮扫描」看谁先抢到。

Identity 重注入 · 压缩后还知道自己是谁

s06 讲过 auto_compact 会把 messages 替换成 summary。autonomous agent 跑个把小时很容易触发——压缩后模型不知道自己叫什么、是什么角色

s11 的招数:claim 到新 task 时,如果 len(messages) ≤ 3(说明刚被压缩过),自动在头部插入 identity 块:

if len(messages) <= 3:
    messages.insert(0, {
        "role": "user",
        "content": f"<identity>You are 'alice', role: coder, team: my-team. Continue your work.</identity>",
    })
    messages.insert(1, {"role":"assistant", "content": f"I am alice. Continuing."})

这个模式叫 identity reinjection——用人为构造的一轮对话「告诉模型它是谁」,让它找回角色感。

Interactive

Widget 1 · Task Scanner · 3 个 agent 抢 3 个 task

alice / bob / charlie 三人都在 idle。点扫描,看谁按字母序先 claim 到第一个 unclaimed task。

.tasks/ 目录
Teammates 状态
所有人都 idle,等着扫
Interactive

Widget 2 · Identity Drift · 压缩后 agent 还记得自己吗

模拟 context 压缩前后,agent 回答「你是谁?」的对比。没有 identity 重注入会怎样?

没有 identity 重注入
有 identity 重注入
Interactive

Widget 3 · Autonomous vs Assisted · 哪些角色适合自治

决定让这个 role 跑自治循环还是被动待命。思考 "失控代价" 和 "人工干预频率"。

答对 0 / 5