通用 Agent:状态、事件循环、工具执行与钩子General-purpose agent with transport abstraction, state management, and attachment support
← → 翻页 · F 全屏 · O 目录 · T 明暗 · L 语言← → navigate · F fullscreen · O overview · T theme · L language
index.ts 只有 5 行:export * 四个模块,再单独导出 setDefaultStreamFn(getDefaultStreamFn 不导出)。index.ts is five lines: export * from four modules plus setDefaultStreamFn alone (getDefaultStreamFn stays internal).
prompt() 在运行中调用会抛错,提示改用 steer() 或 followUp()——这是唯一的并发入口约束。prompt() throws while a run is active, pointing at steer() or followUp() — the single concurrency rule at the entry.
transformContext 作用于 AgentMessage[](可含自定义消息),convertToLlm 再把它们转成 pi-ai 的 Message[]——压缩、裁剪放前者,格式转换放后者。transformContext works on AgentMessage[] (custom messages included); convertToLlm then turns them into pi-ai Message[] — pruning belongs in the former, format conversion in the latter.getApiKey 每次请求都调用,让短期 OAuth token 在长时间工具执行期间也能刷新。getApiKey is called on every request, so short-lived OAuth tokens can refresh during long tool runs.message_update 同时携带 assistantMessageEvent(原始 pi-ai 事件),UI 可以按 delta 精细渲染。message_update also carries assistantMessageEvent (the raw pi-ai event), so a UI can render per delta.
默认模式都是 one-at-a-time:每个轮询点只取一条,剩下的留到下一轮,避免一次塞入大量插话。Both default to one-at-a-time: each poll takes one message and leaves the rest for later turns, so a burst of nudges doesn't arrive at once.
立即结果(未知工具、参数校验失败、被 beforeToolCall 阻止)不进入执行,直接得到 error 结果。Immediate outcomes (unknown tool, failed validation, blocked by beforeToolCall) skip execution and get an error result directly.
解析顺序:AgentOptions.streamFn → setDefaultStreamFn() 安装的全局默认 → 都没有则抛出 “No default stream function configured”。Resolution: AgentOptions.streamFn → the global default from setDefaultStreamFn() → otherwise throw “No default stream function configured”.
AgentState 的 tools 与 messages 赋值时复制数组;pendingToolCalls 每次替换为新的 Set,方便 UI 做引用比较。AgentState.tools and messages copy on assignment; pendingToolCalls is replaced with a new Set each time so UIs can compare by reference.
替换模型调用:直连、代理、录制回放、测试桩。Swap the model call: direct, proxy, record/replay, test stubs.
自定义消息 → LLM 消息;压缩、裁剪、注入上下文。Custom messages → LLM messages; compaction, pruning, context injection.
权限审批、阻止、改写结果、终止。Approval, blocking, rewriting results, terminating.
每轮改模型 / 工具 / 选项,决定是否继续。Change model / tools / options per turn and decide whether to continue.
每次请求取凭据(短期 OAuth token)。Fetch credentials per request (short-lived OAuth tokens).