08 · 工具管线、权限与错误
第 07 章已经能看到每次工具调用,但所有调用仍然直接执行。本章把每个工具的执行拆成三步:prepare → beforeToolCall → execute。
prepare:解析参数,并把参数冻结下来。危险工具在这一步返回一个审批请求。beforeToolCall:决定这一次调用能不能继续。execute:只有放行之后才执行,副作用(写文件、跑命令这类会改变外部状态的动作)只在这一步发生。
加上这道关卡后,上一版 ExecutionEnv 的一个漏洞也暴露出来了:
- 工具算审批 key 时,用的是进程的 cwd。
- 执行时,工具却把原始的相对路径交给 env。
两边用的路径基准可能不一样。现在改成由 env 自己固定 cwd,并提供 absolutePath()。批准的目标和执行的目标,从此用同一个方法解析。
能力边界与控制流
tool_use.input
→ tool.prepare(input) 参数错误:ToolResult(error variant)
→ beforeToolCall(context) 可询问、放行或阻止
→ prepared.execute(env) 执行错误:ToolResult(error variant)
→ tool_result 回给模型继续修正
权限信息跟着 Tool 走,loop 不认识 read_file、bash 这些名字。具体分工是:
- Tool 声明一个结构化的 scope(这次操作影响的范围)。
- host 用
scope + env生成一个字符串 key。 - 用户选“总是允许”时,只记住这一个精确的操作,而且只在当前进程里有效。
beforeToolCall 是执行前的控制点。它和第 07 章那种只负责显示的事件不一样,它能拦住调用。本章只用它来做审批,以后的路径策略也可以接在这个位置。
这不是 sandbox(把程序关在隔离环境里运行的机制),也不承诺能挡住恶意命令。
本章不允许 hook 改写输入,原因如下:
prepare已经根据原始输入,生成了待执行的闭包和审批描述。- context 的顶层用
Object.freeze固定住。 context.input是一份structuredClone快照。扩展代码就算改了快照内部,prepared call(准备好的调用)也不受影响。
如果真要支持改参数,新参数必须重新走一遍 prepare。否则会出现“校验的是 A、批准的是 B、执行的是 C”的混乱。目前没有这个需求。
最小威胁模型:权限是最后一道交互关卡
本章考虑三种出错的来源:
- 用户手滑。
- 模型判断错。
- 仓库里的指令或工具输出里藏了 prompt injection(混在文本里、诱导模型执行别的操作的指令)。
要保护的是写文件、执行命令这类副作用。本章不承诺防住:
- 同一台机器上的恶意进程。
- 内核级的攻击。
- 读到密钥之后把数据发出去。这个暂时不处理。
一条可能的攻击路径是:
- 模型读到一段恶意文本。
- 文本要求执行某条命令。
- 模型发出一个
bash工具调用。
审批能在第 3 步的副作用发生之前停下来。但它不是唯一的防线,更不是 sandbox。更完整的多层防御还包括:工具白名单、workspace 边界、敏感路径规则、网络策略。
从这里也能看出:read_file 不用审批,只是因为它不改磁盘。这不等于读任何路径都是安全的。
tool_result 也会影响模型的下一步
拒绝结果里写着 “Do not repeat…”。这句话不只是在说明错误,它会进入下一轮的上下文,引导模型换个计划。
spike(前期的小实验)里出现过一个问题:模型看到 denied,还是原样重试。这句话就是对它的修复。工具结果既是传回事实的通道,也是模型读到的提示词(prompt surface)。
反过来也一样。文件、网页、命令输出里的自然语言,也可能夹带指令。不能因为它来自工具,就自动当成可信内容。
prepare → beforeToolCall → execute 这个拆法,还明确带出了一个 TOCTOU 窗口(检查时和使用时之间的空档,目标可能在这段时间被换掉):
env.absolutePath()只固定了路径的字面写法。- 用户批准的路径字符串,和执行时打开的不一定是同一个文件。
- symlink 也可能指向 workspace 外面。
本项目把这一点记为已知边界,不假装已经修好。如果要防恶意仓库,需要:限制在 workspace 内访问、制定 realpath 和 symlink 规则,甚至用打开后的文件描述符来固定目标文件。
完整代码增量
先改 src/env.ts。cwd 在创建 env 时就固定下来;所有文件方法都先经过 absolutePath,两个命令方法也显式传入同一个 cwd:
import path from 'node:path'
export type ExecutionEnv = {
readonly cwd: string
absolutePath(filePath: string): string
readFile(path: string): Promise<string>
writeFile(path: string, content: string): Promise<void>
listFiles(path: string): Promise<DirectoryEntry[]>
exec(command: string): Promise<CommandResult>
execFile(file: string, args: string[]): Promise<CommandResult>
}
export function createNodeEnv(
cwd = process.cwd(),
): ExecutionEnv {
const absoluteCwd = path.resolve(cwd)
const absolutePath = (filePath: string) =>
path.resolve(absoluteCwd, filePath)
return {
cwd: absoluteCwd,
absolutePath,
readFile: async (filePath) =>
await readFile(absolutePath(filePath), 'utf8'),
writeFile: async (filePath, content) => {
await writeFile(absolutePath(filePath), content, 'utf8')
},
listFiles: async (directoryPath) => {
const entries = await readdir(absolutePath(directoryPath), {
withFileTypes: true,
})
return entries
.map((entry): DirectoryEntry => ({
name: entry.name,
type: entry.isDirectory()
? 'directory'
: entry.isFile() ? 'file' : 'other',
}))
.sort((a, b) => a.name.localeCompare(b.name))
},
exec: async (command) =>
await settleCommand(() => execAsync(command, {
cwd: absoluteCwd,
encoding: 'utf8',
timeout: 30_000,
maxBuffer: 1024 * 1024,
})),
execFile: async (file, args) =>
await settleCommand(() => execFileAsync(file, args, {
cwd: absoluteCwd,
encoding: 'utf8',
timeout: 30_000,
maxBuffer: 1024 * 1024,
})),
}
}
export const nodeEnv = createNodeEnv()
Run 和 Tool 现在第一次要共用结构化错误。新建一个最小的 src/errors.ts,把第 07 章的 AgentError 从 agent.ts 移到这里:
export type AgentError = {
code: string
message: string
}
再替换 src/tools.ts 里的工具协议:
import type { AgentError } from './errors.js'
export type ToolVisibleResult = {
content: string
details?: unknown
} & (
| { isError: false }
| { isError: true; error: AgentError }
)
export type ToolResult = ToolVisibleResult
export type ApprovalScope =
| { kind: 'path'; path: string }
| { kind: 'bash'; command: string }
| { kind: 'mcp'; server: string; tool: string }
export type ApprovalRequest = Readonly<{
scope: ApprovalScope
description: string
}>
export type PreparedToolCall = {
approval?: ApprovalRequest
execute(
env: ExecutionEnv,
): ToolResult | Promise<ToolResult>
}
export type Tool = {
definition: Anthropic.Tool
prepare(input: unknown): PreparedToolCall
}
tools 数组里的 definition 不改,只把执行相关的字段逐个替换:
// get_current_time
prepare: prepareCurrentTime,
// list_files
prepare: prepareListFiles,
// read_file
prepare: prepareReadFile,
// write_file
prepare: prepareWriteFile,
// edit_file
prepare: prepareEditFile,
// grep
prepare: prepareGrep,
// bash
prepare: prepareBash,
保留原来的 asObject、stringField 和 MAX_LIST_FILES_ENTRIES,删掉旧的工具执行函数,加入下面的完整实现:
function success(
content: string,
details?: unknown,
): ToolResult {
return {
content,
isError: false,
...(details === undefined ? {} : { details }),
}
}
function failure(
code: string,
content: string,
): ToolResult {
return {
content,
isError: true,
error: { code, message: content },
}
}
function formatCommandResult(
code: number | string,
stdout: string,
stderr: string,
): string {
return [
`exit code: ${code}`,
'',
'stdout:',
stdout || '(empty)',
'',
'stderr:',
stderr || '(empty)',
].join('\n')
}
export function prepareCurrentTime(
input: unknown,
): PreparedToolCall {
const args = asObject(input)
const timeZone = stringField(args, 'time_zone')
return {
execute: () => success(
new Intl.DateTimeFormat('zh-CN', {
dateStyle: 'full',
timeStyle: 'long',
timeZone,
}).format(new Date()),
),
}
}
export function prepareListFiles(
input: unknown,
): PreparedToolCall {
const args = asObject(input)
const directoryPath = stringField(args, 'path')
return {
execute: async (env) => {
const entries = await env.listFiles(directoryPath)
if (entries.length === 0) {
return success(`${directoryPath}: empty directory`)
}
const visible = entries.slice(
0,
MAX_LIST_FILES_ENTRIES,
)
const lines = visible.map((entry) =>
entry.type === 'directory'
? `${entry.name}/`
: entry.name,
)
const omitted = entries.length - visible.length
if (omitted > 0) {
lines.push(`[${omitted} more entries omitted]`)
}
return success(lines.join('\n'))
},
}
}
export function prepareReadFile(
input: unknown,
): PreparedToolCall {
const args = asObject(input)
const filePath = stringField(args, 'path')
return {
execute: async (env) =>
success(await env.readFile(filePath)),
}
}
export function prepareWriteFile(
input: unknown,
): PreparedToolCall {
const args = asObject(input)
const filePath = stringField(args, 'path')
const content = stringField(args, 'content')
return {
approval: {
scope: { kind: 'path', path: filePath },
description: `write ${filePath}`,
},
execute: async (env) => {
await env.writeFile(filePath, content)
return success(
`wrote ${Buffer.byteLength(content, 'utf8')} bytes to ${filePath}`,
)
},
}
}
export function prepareEditFile(
input: unknown,
): PreparedToolCall {
const args = asObject(input)
const filePath = stringField(args, 'path')
const oldString = stringField(args, 'old_string')
const newString = stringField(args, 'new_string')
if (oldString === '') {
throw new Error('old_string must not be empty')
}
if (oldString === newString) {
throw new Error(
'old_string and new_string must be different',
)
}
return {
approval: {
scope: { kind: 'path', path: filePath },
description: `edit ${filePath}`,
},
execute: async (env) => {
const content = await env.readFile(filePath)
const count = content.split(oldString).length - 1
if (count === 0) {
return failure(
'EDIT_TARGET_NOT_FOUND',
`old_string was not found in ${filePath}; read the file again`,
)
}
if (count > 1) {
return failure(
'EDIT_TARGET_AMBIGUOUS',
`old_string appears ${count} times in ${filePath}; include more surrounding text`,
)
}
const next = content.replace(
oldString,
() => newString,
)
await env.writeFile(filePath, next)
return success(`edited ${filePath}`)
},
}
}
export function prepareGrep(
input: unknown,
): PreparedToolCall {
const args = asObject(input)
const pattern = stringField(args, 'pattern')
const searchPath = stringField(args, 'path')
return {
execute: async (env) => {
const result = await env.execFile('grep', [
'-RInE',
'--exclude-dir=.git',
'--exclude-dir=node_modules',
'--',
pattern,
searchPath,
])
if (result.code === 0) {
return success(
result.stdout || result.stderr || 'No matches found.',
)
}
if (result.code === 1) {
return success(
`No matches found for ${JSON.stringify(pattern)} in ${searchPath}.\n` +
'The search uses the platform grep in extended-regexp mode. If the pattern used PCRE-only or non-portable syntax, rewrite it as portable POSIX ERE before concluding the text is absent.',
)
}
return failure(
'GREP_EXECUTION_FAILED',
formatCommandResult(
result.code,
result.stdout,
result.stderr,
),
)
},
}
}
export function prepareBash(
input: unknown,
): PreparedToolCall {
const args = asObject(input)
const command = stringField(args, 'command')
return {
approval: {
scope: { kind: 'bash', command },
description: `run ${JSON.stringify(command)}`,
},
execute: async (env) => {
const result = await env.exec(command)
const content = formatCommandResult(
result.code,
result.stdout,
result.stderr,
)
return typeof result.code === 'string'
? failure('COMMAND_START_FAILED', content)
: success(content)
},
}
}
新建 src/permission.ts:
import type { ExecutionEnv } from './env.js'
import type {
ApprovalRequest,
ApprovalScope,
} from './tools.js'
export type ApprovalChoice =
| 'once'
| 'session'
| 'deny'
export type AskApproval = (
request: ApprovalRequest,
) => Promise<ApprovalChoice>
export function approvalKey(
scope: ApprovalScope,
env: ExecutionEnv,
): string {
switch (scope.kind) {
case 'path':
return JSON.stringify([
'path',
env.absolutePath(scope.path),
])
case 'bash':
return JSON.stringify([
'bash',
env.cwd,
scope.command,
])
case 'mcp':
return JSON.stringify([
'mcp',
scope.server,
scope.tool,
])
}
}
export async function checkApproval(
request: ApprovalRequest,
env: ExecutionEnv,
allowedForSession: Set<string>,
ask: AskApproval,
): Promise<boolean> {
const key = approvalKey(request.scope, env)
if (allowedForSession.has(key)) {
return true
}
const choice = await ask(request)
if (choice === 'deny') {
return false
}
if (choice === 'session') {
allowedForSession.add(key)
}
return true
}
这里有意把三件事分开:
- Tool 只声明结构化的 scope。
approvalKey用同一个 env 解析出这次操作是什么。ask只负责返回用户在界面上的选择。
checkApproval 只回答 agent 一个问题:这一次能不能执行。
allowedForSession 没有藏在某个返回函数的闭包里,而是由 CLI 明确创建、再传进来。它只创建一次,在多次 runAgent 之间一直保留;进程退出后自然消失。
在 src/agent.ts 里删掉 ToolEventResult,改成导入 ToolResult 和权限相关的类型,再替换工具派发函数:
import type { AgentError } from './errors.js'
import type {
ApprovalRequest,
Tool,
ToolResult,
} from './tools.js'
// RunOutcome / RunResult 沿用第 07 章,只把 AgentError 改为上面的 import。
export type ToolCallContext = Readonly<{
id: string
name: string
input: unknown
approval?: ApprovalRequest
}>
export type BeforeToolCallResult =
| { action: 'continue' }
| { action: 'block'; reason: string }
export type BeforeToolCall = (
context: ToolCallContext,
) => Promise<BeforeToolCallResult>
export type AgentEvent =
| { type: 'text_delta'; text: string }
| {
type: 'tool_start'
id: string
name: string
input: unknown
}
| {
type: 'tool_end'
id: string
name: string
result: ToolResult
}
| {
type: 'run_end'
usageDelta: Usage
} & RunOutcome
type RunAgentOptions = {
messages: Anthropic.MessageParam[]
system: string
callModel: CallModel
tools: Tool[]
env: ExecutionEnv
maxTurns?: number
onEvent?(event: AgentEvent): void
beforeToolCall?: BeforeToolCall
}
function errorResult(
code: string,
message: string,
): ToolResult {
return {
content: message,
isError: true,
error: { code, message },
}
}
async function executeToolCall(
toolUse: Anthropic.ToolUseBlockParam,
opts: RunAgentOptions,
): Promise<ToolResult> {
try {
const tool = opts.tools.find(
(candidate) =>
candidate.definition.name === toolUse.name,
)
if (!tool) {
return errorResult(
'UNKNOWN_TOOL',
`Unknown tool: ${toolUse.name}`,
)
}
const prepared = tool.prepare(toolUse.input)
const context: ToolCallContext = Object.freeze({
id: toolUse.id,
name: toolUse.name,
input: structuredClone(toolUse.input),
...(prepared.approval
? {
approval: Object.freeze({
...prepared.approval,
}),
}
: {}),
})
if (!opts.beforeToolCall) {
if (prepared.approval) {
return errorResult(
'APPROVAL_UNAVAILABLE',
`Permission denied: no beforeToolCall hook is available for ${toolUse.name}.`,
)
}
} else {
const decision = await opts.beforeToolCall(context)
if (decision.action === 'block') {
return errorResult('TOOL_BLOCKED', decision.reason)
}
}
return await prepared.execute(opts.env)
} catch (error) {
return errorResult('TOOL_CALL_FAILED', errorMessage(error))
}
}
工具结果的组装逻辑和第 07 章一样:result.isError 对应到 provider 的 is_error: true。所以下面四种情况都走同一条协议通道:
- 参数错误。
- 被拒绝。
- 执行时抛异常。
- 工具自己返回失败。
在 src/system.ts 的基础指令末尾,加上被拒绝之后该怎么做的规则:
- If the user denies a tool call, do not repeat the same call. Explain the constraint and choose a safer alternative or ask what to do next.`
在 src/cli.ts 里加上审批输入:
import type { BeforeToolCall } from './agent.js'
import {
checkApproval,
type ApprovalChoice,
} from './permission.js'
import type { ApprovalRequest } from './tools.js'
const allowedForSession = new Set<string>()
async function askApproval(
request: ApprovalRequest,
): Promise<ApprovalChoice> {
const answer = (
await rl.question(
`Allow ${request.description}? [y]es / [a]lways / [N]o: `,
)
).trim().toLowerCase()
if (answer === 'y' || answer === 'yes') {
return 'once'
}
if (answer === 'a' || answer === 'always') {
return 'session'
}
return 'deny'
}
const beforeToolCall: BeforeToolCall = async (context) => {
if (!context.approval) {
return { action: 'continue' }
}
const allowed = await checkApproval(
context.approval,
nodeEnv,
allowedForSession,
askApproval,
)
if (allowed) {
return { action: 'continue' }
}
return {
action: 'block',
reason: `User denied permission for ${context.approval.description}. Do not repeat the same tool call; explain the constraint and choose a safer alternative.`,
}
}
// runAgent({...}) 中加入
beforeToolCall,
这四样东西什么时候创建、什么时候被调用,代码里写得很直接:
allowedForSession:CLI 启动时创建一次。beforeToolCall:每次参数校验成功后调用一次。checkApproval:只有context.approval存在时才会进入。它用同一个nodeEnv生成 key。askApproval:只有 key 没在 Set 里找到时,才去读终端输入。
进程退出后,Set 和这次会话里的授权一起消失。
这不是函数工厂:没有函数返回函数,也没有状态藏在工厂的闭包里。Set 和终端输入明确归 CLI 管;runtime 只认识 continue 和 block 两种结果。
自动化测试与故障注入
权限测试要验证调用顺序,也要验证被拒绝后 loop 能继续,不能只检查“弹窗出现过”:
import assert from 'node:assert/strict'
import test from 'node:test'
import type Anthropic from '@anthropic-ai/sdk'
import { runAgent } from './agent.js'
import type { ExecutionEnv } from './env.js'
import type {
CallModel,
ModelResponse,
} from './model.js'
import { checkApproval } from './permission.js'
import {
tools,
type ApprovalRequest,
} from './tools.js'
function makeEnv(): {
env: ExecutionEnv
execCalls: string[]
readCalls: { count: number }
} {
const execCalls: string[] = []
const readCalls = { count: 0 }
return {
execCalls,
readCalls,
env: {
readFile: async () => {
readCalls.count += 1
return 'safe evidence'
},
writeFile: async () => {},
listFiles: async () => [],
exec: async (command) => {
execCalls.push(command)
return { code: 0, stdout: 'ok', stderr: '' }
},
execFile: async () => ({
code: 1,
stdout: '',
stderr: '',
}),
},
}
}
function scripted(
responses: ModelResponse[],
inspect?: (
call: number,
messages: Anthropic.MessageParam[],
) => void,
): CallModel {
let call = 0
return async (request) => {
call += 1
inspect?.(call, request.messages)
const response = responses.shift()
if (!response) throw new Error('no response left')
return response
}
}
test('invalid parameters fail before approval', async () => {
let approvals = 0
const { env, execCalls } = makeEnv()
const responses: ModelResponse[] = [
{
content: [{
type: 'tool_use',
id: 'toolu_bad',
name: 'bash',
input: { command: 42 },
}],
stop_reason: 'tool_use',
usage: { input_tokens: 1, output_tokens: 1 },
},
{
content: [{ type: 'text', text: 'fixed' }],
stop_reason: 'end_turn',
usage: { input_tokens: 1, output_tokens: 1 },
},
]
const result = await runAgent({
messages: [{ role: 'user', content: 'run it' }],
system: 'test',
callModel: scripted(responses),
tools,
env,
beforeToolCall: async () => {
approvals += 1
return { action: 'continue' }
},
})
assert.equal(result.reason, 'done')
assert.equal(approvals, 0)
assert.equal(execCalls.length, 0)
assert.match(
JSON.stringify(result.messages),
/command must be a string/,
)
})
test('beforeToolCall can block a prepared read-only call', async () => {
const { env, readCalls } = makeEnv()
const responses: ModelResponse[] = [
{
content: [{
type: 'tool_use',
id: 'toolu_read_secret',
name: 'read_file',
input: { path: '.env' },
}],
stop_reason: 'tool_use',
usage: { input_tokens: 1, output_tokens: 1 },
},
{
content: [{ type: 'text', text: 'blocked' }],
stop_reason: 'end_turn',
usage: { input_tokens: 1, output_tokens: 1 },
},
]
const result = await runAgent({
messages: [{ role: 'user', content: 'read the secret' }],
system: 'test',
callModel: scripted(responses),
tools,
env,
beforeToolCall: async (context) =>
context.name === 'read_file'
? {
action: 'block',
reason: 'Reading secret files is blocked by policy.',
}
: { action: 'continue' },
})
assert.equal(result.reason, 'done')
assert.equal(readCalls.count, 0)
assert.match(
JSON.stringify(result.messages),
/blocked by policy/,
)
})
test('mutating the hook input snapshot cannot change execution', async () => {
const { env, execCalls } = makeEnv()
const responses: ModelResponse[] = [
{
content: [{
type: 'tool_use',
id: 'toolu_bash_snapshot',
name: 'bash',
input: { command: 'npm test' },
}],
stop_reason: 'tool_use',
usage: { input_tokens: 1, output_tokens: 1 },
},
{
content: [{ type: 'text', text: 'done' }],
stop_reason: 'end_turn',
usage: { input_tokens: 1, output_tokens: 1 },
},
]
await runAgent({
messages: [{ role: 'user', content: 'run tests' }],
system: 'test',
callModel: scripted(responses),
tools,
env,
beforeToolCall: async (context) => {
const snapshot = context.input as { command: string }
snapshot.command = 'npm publish'
return { action: 'continue' }
},
})
assert.deepEqual(execCalls, ['npm test'])
})
test('a denial is returned to the model and it can choose a read-only alternative', async () => {
const { env, execCalls } = makeEnv()
const responses: ModelResponse[] = [
{
content: [{
type: 'tool_use',
id: 'toolu_bash',
name: 'bash',
input: { command: 'rm notes.txt' },
}],
stop_reason: 'tool_use',
usage: { input_tokens: 1, output_tokens: 1 },
},
{
content: [{
type: 'tool_use',
id: 'toolu_read',
name: 'read_file',
input: { path: 'notes.txt' },
}],
stop_reason: 'tool_use',
usage: { input_tokens: 1, output_tokens: 1 },
},
{
content: [{
type: 'text',
text: 'Used a safer plan.',
}],
stop_reason: 'end_turn',
usage: { input_tokens: 1, output_tokens: 1 },
},
]
const result = await runAgent({
messages: [{ role: 'user', content: 'inspect notes' }],
system: 'test',
callModel: scripted(responses, (call, messages) => {
if (call === 2) {
assert.match(
JSON.stringify(messages),
/User denied permission/,
)
}
}),
tools,
env,
beforeToolCall: async (context) =>
context.approval
? {
action: 'block',
reason: `User denied permission for ${context.approval.description}.`,
}
: { action: 'continue' },
})
assert.equal(result.reason, 'done')
assert.equal(execCalls.length, 0)
assert.match(
JSON.stringify(result.messages),
/User denied permission/,
)
assert.match(
JSON.stringify(result.messages),
/safe evidence/,
)
})
test('always approval is scoped to one exact operation key', async () => {
const asked: string[] = []
const allowedForSession = new Set<string>()
const ask = async (request: ApprovalRequest) => {
const scope = request.scope
asked.push(
scope.kind === 'bash' ? scope.command : scope.kind,
)
return scope.kind === 'bash' && scope.command === 'npm test'
? 'session' as const
: 'deny' as const
}
assert.equal(
await checkApproval(
{
scope: { kind: 'bash', command: 'npm test' },
description: 'run npm test',
},
env,
allowedForSession,
ask,
),
true,
)
assert.equal(
await checkApproval(
{
scope: { kind: 'bash', command: 'npm test' },
description: 'run npm test',
},
env,
allowedForSession,
ask,
),
true,
)
assert.equal(
await checkApproval(
{
scope: { kind: 'bash', command: 'npm publish' },
description: 'run npm publish',
},
env,
allowedForSession,
ask,
),
false,
)
assert.equal(allowedForSession.size, 1)
assert.deepEqual(asked, [
'bash:npm test',
'bash:npm publish',
])
})
真实验收时,先拒绝一次 bash。模型必须解释限制,然后改用只读工具,或者问用户下一步怎么做。如果它原样重试,一直到 max_turns,本章就不算通过。
已验证的边界
- 无效参数也先骚扰用户确认。
prepare完成解析后才可能产生 approval;断言审批次数为 0。 - 拒绝抛异常打断 loop。拒绝编码成
is_error,下一次模型调用能看见原因。 - “总是允许 bash”范围过宽或跨 cwd 复用。key 由 bash scope +
env.cwd+ 完整命令生成;npm test不放行npm publish,换 cwd 也重新询问。
一次工具调用怎样通过审批
tool_use
→ prepare(input) 校验参数,固定待执行操作并声明 approval
→ beforeToolCall(context) 放行或阻止;需要时交给 checkApproval
→ checkApproval(...) 先查 session key,未命中才调用 askApproval
→ prepared.execute(env) 只有 continue 后才产生副作用
→ tool_result 把成功、拒绝或失败交还模型
分工是:Tool 负责描述风险、准备执行;runtime 负责守住调用顺序;CLI 管着会话内的授权和终端输入。由此得到四条规则:
- 参数无效时,不询问,也不执行。
- 危险操作如果没有审批 hook,默认拒绝。
beforeToolCall没有返回continue,就不执行。- 拒绝和工具失败都编码成
tool_result,不会直接结束 agent loop。
下一章会把同一个 AbortSignal 传遍模型请求、等待、审批、文件操作和子进程。另外,对还没输出任何 delta 的临时性模型失败,做有限次数的重试。
章末修正:正则名字不等于跨平台语义
本章最初只笼统地写了“regular expression”。但执行层实际调用的是当前平台的 grep -E。
- POSIX ERE 是各平台都支持的共同部分。
- GNU grep 和 BSD grep 对
\\d、\\w、\\s、内联 flag、重复运算符的扩展支持不完全一样。 - 写法不通用时,可能直接报错,也可能匹配出不同的结果。所以不能统一说成“只是悄悄匹配不到”。
因此,grep 的 definition 改为明确要求使用 portable POSIX ERE(各平台通用的扩展正则写法):
description: 'Search files recursively with the platform grep command in extended-regexp mode. Returns file paths, line numbers, and matching lines. Use portable POSIX ERE syntax: PCRE constructs and backslash extensions vary by platform and may fail, match differently, or produce no matches. Prefer [0-9], [[:alnum:]_], and [[:space:]] over \\d, \\w, and \\s.',
// pattern property
description: 'Portable POSIX extended regular expression (ERE) to search for.',
exit code 1 仍然表示“没有匹配”,但结果会提醒模型先排除是不是语法写错了。exit code 2 时,把 grep 自己的报错信息作为错误结果返回。
这条修正的重点不是多教一套正则,而是避免把“查询写错了”误判成“代码里没有这个东西”。