权限
权限回调让宿主应用在工具真正执行前做拦截。它适合文件写入、Shell、外部 API、付款、删除数据等敏感操作。
回调会在模型请求调用已注册工具之后、工具参数解析和工具 handler 执行之前运行。返回 { behavior: "allow" } 会继续执行工具;返回 { behavior: "deny", message } 会阻止本次工具调用。
import { createAgent } from "agent-lattice";
const agent = createAgent({ apiKey: process.env.DEEPSEEK_API_KEY, baseURL: "https://api.deepseek.com/anthropic", model: "deepseek-v4-flash", workspace: { cwd: process.cwd(), allowedDirectories: [process.cwd()], }, permission: async request => { if (request.toolName === "Bash") { return { behavior: "deny", message: "Shell access is disabled for this session.", }; }
return { behavior: "allow" }; },});如果没有传 permission 回调,所有已注册工具调用都会被允许。传了回调后,返回 { behavior: "allow" } 就表示允许当前这一次工具调用。
上面的例子是 deny-list 策略:命中 Bash 就拒绝,最后的 return { behavior: "allow" } 表示其它工具都放行。
如果你想写 allow-list 策略,可以反过来判断:
import type { AgentOptions } from "agent-lattice";
const readOnlyTools = new Set(["Read", "LS", "Glob", "Grep"]);
const permission: AgentOptions["permission"] = async request => { if (readOnlyTools.has(request.toolName)) { return { behavior: "allow" }; }
return { behavior: "deny", message: "Only read-only tools are allowed for this session.", };};拒绝不是崩溃
Section titled “拒绝不是崩溃”当回调返回 deny 时,SDK 不会直接抛出异常结束整个 agent loop。它会把拒绝原因作为错误 tool_result 回给模型。
这样模型可以:
- 告诉用户该操作被策略拒绝。
- 尝试使用其它允许的工具。
- 请求用户补充授权。
权限回调会收到:
| 字段 | 说明 |
|---|---|
toolName |
模型想调用的工具名。 |
input |
模型传入的原始工具参数。把它当作不可信输入处理。 |
toolUseId |
当前工具调用 id。 |
按输入做策略
Section titled “按输入做策略”你可以检查 request.input 再决定是否允许执行。策略逻辑属于宿主应用;SDK 只负责调用它。
import type { AgentOptions } from "agent-lattice";
const permission: AgentOptions["permission"] = async request => { if (request.toolName === "Bash") { const command = String(request.input.command ?? "");
if (command.includes("rm -rf")) { return { behavior: "deny", message: "Destructive shell commands are disabled for this session.", }; } }
return { behavior: "allow" };};权限回调是一层审批逻辑,不是完整沙箱。它不会改写模型输出、隐藏 prompt 内容,也不会替你校验每个自定义工具参数。
对内置文件工具,建议把权限回调和 allowedDirectories 一起使用,让文件访问限制在你配置的 workspace 内。对 Bash 和会访问外部系统的自定义工具,还需要在宿主运行环境里做真实边界:只暴露必要工具、校验输入、使用最小权限凭证,并在记录日志前脱敏敏感值。