4.3 控制运行中的 Agent

上一课我们将工具循环交给了 Agent 自动执行。在实际应用中,还需要对运行中的 Agent 施加两类控制:

  1. 工具权限与审计:面对修改状态或执行命令等敏感工具,需要在执行前按策略拦截,并在执行后记录审计信息或改写结果。
  2. 运行期间的消息调度: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):

双消息队列: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),用于在空闲状态下不追加新参数直接续跑,仅在两类场景下有效:

  1. 队尾是 user 或 toolResult 消息:例如上一轮请求失败或溢出后删掉了错误的 assistant 消息、或从磁盘恢复了未回复的会话,调 continue() 直接续发而不重复写入用户消息。
  2. 队尾是 assistant 消息,但 steering 或 followUp 队列非空:例如在 agent_end 回调中新排入了消息,或上一次运行因 abort() 中断留下了未消费的队列消息,调 continue() 会按优先顺序取出队列继续运行;若此时两个队列均为空,则直接抛出 Cannot continue from message role: assistant。
解答 展开 收起
GitHub 代码对比

本课的改动集中在 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 条测试全部通过。