生命周期钩子

钩子让你在 Agent 活动发生时进行观测和把控。你针对某个生命周期事件注册一个具名回调, 运行时会在该节点调用它,回调返回一个决策,例如 { action: "continue" }。钩子可用于 审计、脱敏、日志记录,或在不修改 Agent 提示词的前提下实施策略。

其生命周期是对称的:registerHook 按名称添加回调,hookCount 告诉你当前有多少个钩子 处于活动状态,unregisterHook 则按名称移除某个钩子。

Node.js
Python
TypeScript
import { Agent } from '@a3s-lab/code';
const agent = await Agent.create('agent.acl');
const session = agent.session(process.cwd());
// Register a named hook on a lifecycle event. The callback must NOT throw —
// always return a decision such as { action: 'continue' }.
session.registerHook(
'observe-env-read',
'pre_tool_use',
{ pathPattern: '**/.env*' },
{ priority: 100 },
() => ({ action: 'continue' }),
);
console.log('active hooks:', session.hookCount()); // 1
await session.run('Read the project README and summarize it.');
// Remove the hook by name when you no longer need it.
session.unregisterHook('observe-env-read');
console.log('active hooks:', session.hookCount()); // 0
session.close();

注意事项:

  • 钩子回调返回一个决策。返回 { action: "continue" }(Node)/ {"action": "continue"}(Python)即可让 Agent 继续执行。
  • 匹配器({ pathPattern: '**/.env*' })将钩子限定到路径匹配该模式的事件,而 { priority: 100 } 用于对同一事件上的多个钩子排序(数值越大越先执行)。
  • Node 钩子回调不得抛出异常——未捕获的抛出可能会终止进程。请让处理逻辑保持完备, 并始终返回一个决策。
  • hookCount / hook_count 反映当前已注册钩子的数量,在测试中可方便地断言注册与 清理是否生效。
  • unregisterHook / unregister_hook 接收你注册时使用的名称。请始终拆除不再需要的 钩子,以免它们在多次运行之间泄漏。
  • 把钩子当作生产关卡前,请先验证你所依赖的具体 event path。