Solution:外面一层壳,里面一台机器

在进入 Loop 细节之前,先搞清楚它所在的位置。代码里有两个东西,很容易混淆:

你发一条消息
    ↓
QueryEngine.submitMessage()   ← 【外层】对话管理器,维护整个会话状态
    ↓
query()                       ← 【内层】Agent Loop,执行这一轮任务
    ↓
queryLoop() 内部循环
    ├── 调用 Claude API
    ├── 执行工具
    └── 循环,直到任务完成
    ↓
返回结果给 QueryEngine
QueryEngine 更新消息历史,等待下一条消息
QueryEngine(外层)query()(内层)
生命周期整个对话(多轮)单轮任务
状态持久化(消息历史、文件缓存、用量)轮次内临时状态

QueryEngine 的注释原话:

"One QueryEngine per conversation. Each submitMessage() call starts a new turn within the same conversation. State (messages, file cache, usage…) persists across turns."

理解了外层之后,下面进入内层——Agent Loop 的五个步骤。