Hooks 机制
Hooks 系统让插件可以在关键生命周期事件中注入自定义逻辑——消息拦截、工具调用包装、会话管理、日志审计等。
可用 Hooks
Source: src/plugins/hooks.ts
Hook 名称一览
| Hook 名称 | 触发时机 | 典型用途 |
|---|---|---|
gateway-start | Gateway 启动完成 | 初始化外部服务 |
gateway-stop | Gateway 关闭前 | 清理资源 |
session-start | 会话开始 | 加载会话上下文 |
session-end | 会话结束 | 保存会话状态 |
before-agent-start | Agent 开始执行前 | 注入上下文 |
message-received | 收到用户消息 | 消息拦截、过滤 |
message-sending | 发送消息前 | 消息修改、审计 |
message-sent | 消息发送成功后 | 日志记录 |
before-tool-call | 工具调用前 | 权限检查、参数修改 |
after-tool-call | 工具调用后 | 结果处理、审计 |
before-compaction | 上下文压缩前 | 保存重要信息 |
after-compaction | 上下文压缩后 | 恢复状态 |
tool-result-persist | 工具结果持久化时 | 数据归档 |
Hook 注册
typescript
// src/plugins/hooks.ts (simplified)
interface PluginHookRegistration<K extends PluginHookName> {
event: K; // Hook event name
handler: PluginHookHandler<K>; // Handler function
priority?: number; // Execution priority (lower = earlier)
}插件通过 API 注册 Hook:
typescript
// Example: audit logging hook
api.registerHook({
event: "message-sent",
handler: async (ctx) => {
await auditLog.record({
sessionKey: ctx.sessionKey,
channel: ctx.channel,
direction: ctx.direction,
timestamp: Date.now(),
});
},
priority: 100, // Run after other hooks
});Hook 上下文类型
每种 Hook 接收不同的上下文:
Agent 上下文
typescript
interface PluginHookAgentContext {
runId: string; // Agent run ID
config: AgentConfig; // Agent configuration
workspaceDir: string; // Workspace directory
agentDir: string; // Agent directory
}消息上下文
typescript
interface PluginHookMessageContext {
sessionKey: string; // Session key
channel: string; // Source channel
senderId: string; // Sender identifier
direction: "received" | "sending" | "sent"; // Message direction
}工具上下文
typescript
interface PluginHookToolContext {
runId: string; // Agent run ID
toolName: string; // Tool being called
// before: includes args
// after: includes result
}会话上下文
typescript
interface PluginHookSessionContext {
sessionKey: string; // Session key
channel: string; // Channel
}执行模型
Hook 执行的关键特性:
| 特性 | 说明 |
|---|---|
| 并行执行 | 同一事件的多个 handler 并行运行 |
| 错误隔离 | 单个 handler 抛出不影响其他 handler |
| 优先级排序 | 数字越小越先执行 |
| Fire-and-forget | 大部分 hook 不等待结果 |
Gateway Hooks
Source: src/gateway/hooks.ts, src/gateway/hooks-mapping.ts
Gateway 层有自己的 Hooks 映射,将配置文件中的 hook 定义映射到运行时:
typescript
// src/gateway/hooks-mapping.ts (simplified)
// Maps config-defined hooks to runtime registrations
// Supports file-based hook definitions
// Validates hook event names and handler paths小结
- 13 种 Hook 事件覆盖 Gateway、Session、Agent、Message、Tool 五个生命周期
- Hook 通过 priority 排序,并行执行,错误隔离
- 四种上下文类型提供事件相关的数据
- 插件通过
api.registerHook()注册,支持动态添加 - Gateway 层额外支持基于配置文件的 Hook 定义
下一章:CLI 概述