手册/第 04 章
04
一次提问:turn 与 step 的契约
架构图回答「有哪些零件」,时序图回答「它们按什么顺序说话」。 dsh 把这件事写成了契约——不是实现细节,而是文档正文。
画布 1080px,1× 下最小字号约 5.2px 勉强、2× 到 11px 舒适。
自上而下四段:① 认领输入与 agent/pre-step,② 组装与请求,③ 工具三道闸,④ 收束与 turn/end。
两个词定死了整件事
"A step is one model request plus the tools it calls. A turn is zero or more steps: it opens before its first input is claimed and closes once nothing is owed."
一个 step 是一次模型请求加上它调用的工具。一个 turn 是零个或多个 step:它在第一份输入被认领之前开始,在不再欠任何东西时关闭。
— docs/architecture.md:81
注意「零个 step」这个措辞。它不是为了严谨而加的:如果一个 turn 的第一份输入在
agent/pre-step 被拒绝、或被改写为空,这个 turn 会正常关闭,一个模型请求都不发。
这是 dsh 与「先发请求再说」那类实现的根本差别。
权威流程(文档原文)
docs/architecture.md:83–104 用一段缩进文本把整个 turn 写死了,
这也是读 agent-loop 源码前最好的地图:
turn/start
claim next-step input plus one queued message
snapshot Session model selection; assemble prompt sections + step-admitted tool schemas
-> agent/pre-step; project runtime context at fallback
reject | enter(messages, startsRequestSeries?)
reject, or a first enter rewritten empty -> close the turn with no step
step/start
agent/request -> prepareCall (cancellation commits neither system nor users)
reconcile system/message using the prepared call capability
append entered messages as user/message; reconcile retained runtime context
log request/header and request/context as needed
derive and freeze model history from the log
stream the bound prepared call -> llm/stream -> agent/assistant-stream start
agent/assistant-stream chunk*
assistant/message | assistant/attempt -> agent/assistant-stream end
tool/call* -> tools/pre-execute -> tools/execute -> tools/post-execute -> tool/result*
step/end
tools owe another request, or next-step input arrived -> claim -> next step
-> agent/turn-stopping
turn/end
五个与直觉不同的地方
Ⅰ日志先于请求
turn/start 是追加进会话日志的事件
(agent-loop/src/agent.ts:329 的 this.session.append('turn/start', …)),
不是内存里的一个标记。turn 一开始就是持久事实。
Ⅱpre-step 能拒绝,不只是能改
它是 waterfall:监听者调
next() 就委托,不调就直接短路。
所以「这条消息不让它进模型」的实现方式,就是不调 next()。
Ⅲ工具过三道闸,不是一道
tools/pre-execute → tools/execute → tools/post-execute
三道 waterfall(architecture.md:106)。
策略、审计、改写参数可以分别挂在不同的闸上。
Ⅳ失败也有座位
assistant/message 是成功落定;assistant/attempt 保留失败、重试、取消、
流错误,但不进模型历史。落定前的硬死则不留半条 attempt。
Ⅴ模型至少被调用两次
工具结果也是消息。第一次请求返回「我要调 bash」,工具跑完后结果作为新历史必须再请求一次。
循环条件就是:工具还欠一次请求 → 认领 → 下一个 step。
Ⅵ收尾是串行的,没有 next
agent/turn-stopping 是 serial 且没有 next()——
你不能在这里改写决定,只能观察。这是与三道工具闸刻意不同的设计。
architecture.md:81 · step / turn 定义 architecture.md:106 · 哪些是 waterfall agent.ts:329 · session.append('turn/start')