4.3 控制运行中的 Agent
上一课我们将工具循环交给了 Agent 自动执行。在实际应用中,还需要对运行中的 Agent 施加两类控制:
- 工具权限与审计:面对修改状态或执行命令等敏感工具,需要在执行前按策略拦截,并在执行后记录审计信息或改写结果。
- 运行期间的消息调度:
Agent正在执行时,再次调用agent.prompt()会直接抛出错误(同一时刻只允许一个活跃运行)。如果需要在中途调整方向,或在当前任务完成后追加后续指令,就需要借助内置的消息队列。
@earendil-works/pi-agent-core 通过两对机制支持上述控制:工具前后钩子(beforeToolCall / afterToolCall) 和 双消息队列(steer() / followUp())。
它们在 Turn 循环中的触发时机
下图展示了四个控制点在 Agent 循环中的执行顺序:
flowchart TD
Req["发起模型请求(streamFn)"] --> HasTool{"回复包含 ToolCall?"}
HasTool -- "是" --> Validate["pi-schema 自动校验参数"]
Validate --> Before["beforeToolCall 钩子:是否拦截?"]
Before -- "block: true" --> Blocked["跳过 execute(),生成 isError: true 结果"]
Before -- "放行" --> Exec["执行 tool.execute()"]
Exec --> After["afterToolCall 钩子:审计或覆写结果"]
Blocked --> EmitResult["写入 toolResult,结束当前 Turn"]
After --> EmitResult
EmitResult --> SteerCheck{"steering 队列有消息?"}
HasTool -- "否" --> SteerCheck
SteerCheck -- "有" --> InjectSteer["注入 steering 消息,进入下一个 Turn"]
InjectSteer --> Req
SteerCheck -- "无" --> ContinueCheck{"本轮产生过 toolResult?"}
ContinueCheck -- "是" --> Req
ContinueCheck -- "否" --> FollowUpCheck{"followUp 队列有消息?"}
FollowUpCheck -- "有" --> InjectFollow["注入 followUp 消息,继续下一轮"]
InjectFollow --> Req
FollowUpCheck -- "无" --> End["发出 agent_end,结束运行"]
观察受控库存 Agent 的完整运行
在 4.2 的只读工具 lookup_stock 之外,本课新增了写操作工具 adjust_stock(sku, delta)。下面的演示先向 followUp 队列预排了一条总结指令,再在只读模式下发起请求“帮我把 KB-75 补货 5 件,再查一下当前库存”。点击“运行示例”,观察写操作被拦截、只读查询通过审计以及追问自动续跑的完整过程:
查看审计记录与 agent.state.messages
请先运行示例。
工具钩子:beforeToolCall 与 afterToolCall
两个钩子可在创建 Agent 时传入,也可在运行时动态赋值(详见官方 Agent Options):
beforeToolCall(源码见agent-loop.ts#L737-L765):在pi-schema参数校验通过之后、tool.execute()之前执行。- 返回
undefined表示放行; - 返回
{ block: true, reason: "..." }表示拦截:Agent会跳过execute(),直接将reason封装为isError: true的toolResult返回给模型。
- 返回
afterToolCall(源码见agent-loop.ts#L873-L905):在tool.execute()完成后、tool_execution_end和toolResult事件发出之前执行。- 可按字段覆写
content、details、isError或terminate,未返回的字段保持原值。
- 可按字段覆写
双消息队列:steer() 与 followUp()
当 Agent 正在运行(agent.state.isStreaming === true)时,直接再次调用 agent.prompt() 会抛出错误,提示改用队列接口(见 agent.ts#L383-L387;队列轮询时机见 agent-loop.ts#L304-L315):
| 队列方法 | 触发时机 | 典型用途 |
|---|---|---|
agent.steer(message) | 当前 Turn 的工具全部执行完毕后立即注入,优先级高于 followUp | 运行中途调整方向(例如“跳过鼠标,只查询键盘”) |
agent.followUp(message) | 仅在本轮不再有工具调用、且 steering 队列为空、Agent 即将结束运行时取出执行 | 追加收尾任务(例如“查询完成后给出一句总结”) |
steer() 和 followUp() 都是同步方法(返回 void),只负责把消息推入队列,不会等待执行。两个队列默认采用 "one-at-a-time" 模式(每次取出队首一条),也可通过 agent.steeringMode = "all" 或 agent.followUpMode = "all" 改为一次性全部取出;需要丢弃排队消息时可调用 agent.clearSteeringQueue()、agent.clearFollowUpQueue() 或 agent.clearAllQueues()。
与之配套的还有异步入口 agent.continue()(见 agent.ts#L393-L419),用于在空闲状态下不追加新参数直接续跑,仅在两类场景下有效:
- 队尾是
user或toolResult消息:例如上一轮请求失败或溢出后删掉了错误的assistant消息、或从磁盘恢复了未回复的会话,调continue()直接续发而不重复写入用户消息。 - 队尾是
assistant消息,但steering或followUp队列非空:例如在agent_end回调中新排入了消息,或上一次运行因abort()中断留下了未消费的队列消息,调continue()会按优先顺序取出队列继续运行;若此时两个队列均为空,则直接抛出Cannot continue from message role: assistant。
解答 展开
本课的改动集中在 examples/hello-pi-agent-core/control/control.ts 的三处实现和启用 control/control.test.ts 中的三条测试。
1. 实现 createToolHooks()
beforeToolCall:检查toolCall.name === "adjust_stock" && options.isReadOnly(),满足时返回{ block: true, reason: "当前处于只读模式,禁止修改库存。" }直接阻断执行;其余情况返回undefined放行。afterToolCall:若isError为true则直接返回undefined保留原错误;否则在原有result.details基础上合并{ audited: true },触发options.onAudit?.(toolCall.name, details)并返回{ details }。
2. 实现 queueSteer() 与 queueFollowUp()
分别构造一条标准 UserMessage({ role: "user", content: text, timestamp: Date.now() }),调用 agent.steer(...) 和 agent.followUp(...) 入队。
3. 启用验收测试
把 examples/hello-pi-agent-core/control/control.test.ts 中的三条 it.skip 改为 it,运行 pnpm format && pnpm check && pnpm test:run,确认 49 条测试全部通过。