示例工程 ch14-tool-security
ch14-tool-security/01-allowlist-tools/index.ts
// 01-allowlist-tools —— 按「能力」而不是「工具名」收紧:三套工具集的实测差异。
//
// 运行:node --experimental-strip-types index.ts
//
// 三套配置:
// readonly read/grep/find/ls —— 不能写、不能执行
// editing readonly + write/edit —— 能写,但不能执行命令
// full readonly + write/edit/bash —— 全权限(bash 能改一切)
// 同一段脚本(让模型写文件)在三套配置下的结果完全不同。
import { existsSync, mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createAgentSession, SessionManager } from "@earendil-works/pi-coding-agent";
import { createStubRuntime } from "./stub-provider.ts";
type Mode = "readonly" | "editing" | "full";
const TOOLSETS: Record<Mode, string[]> = {
readonly: ["read", "grep", "find", "ls"],
editing: ["read", "grep", "find", "ls", "write", "edit"],
full: ["read", "grep", "find", "ls", "write", "edit", "bash"],
};
async function run(mode: Mode) {
const cwd = mkdtempSync(join(tmpdir(), `pi-ch14-${mode}-`));
const target = join(cwd, "out.txt");
const stub = await createStubRuntime({
steps: [
{
toolCalls: [
// 先试用 write(只在 editing/full 里存在)
{ id: "w1", name: "write", arguments: { path: "out.txt", content: "hello" } },
// 再用 bash 写一次(只在 full 里存在)
{ id: "b1", name: "bash", arguments: { command: "echo from-bash > out.txt" } },
],
},
{ text: "完成" },
],
});
const { session } = await createAgentSession({
model: stub.model,
modelRuntime: stub.modelRuntime,
agentDir: stub.agentDir,
sessionManager: SessionManager.inMemory(cwd),
cwd,
tools: TOOLSETS[mode],
});
// 串行执行,否则 write 与 bash 的完成顺序不定,文件内容会抖
session.agent.toolExecution = "sequential";
await session.prompt("写一个文件");
const results = session.agent.state.messages.filter((message) => message.role === "toolResult");
const outcome = (id: string) => {
const result = results.find((message) => message.role === "toolResult" && message.toolCallId === id);
if (!result || result.role !== "toolResult") return { ran: false, isError: true, text: "" };
const text = "content" in result ? (result.content[0] as { text?: string })?.text ?? "" : "";
return { ran: text.length > 0 && !text.includes("not found"), isError: result.isError, text };
};
const fileText = existsSync(target) ? readFileSync(target, "utf8").trim() : "";
const active = session.getActiveToolNames();
session.dispose();
return { active, write: outcome("w1"), bash: outcome("b1"), fileText };
}
const readonly = await run("readonly");
const editing = await run("editing");
const full = await run("full");
for (const [mode, result] of [["readonly", readonly], ["editing", editing], ["full", full]] as const) {
console.log(`${mode.padEnd(9)} 激活=${result.active.join(",")}`);
console.log(`${" ".repeat(9)} write=${result.write.ran ? (result.write.isError ? "error" : "ok") : "不存在"} bash=${result.bash.ran ? (result.bash.isError ? "error" : "ok") : "不存在"} 文件="${result.fileText}"`);
}
const ok = (label: string, pass: boolean): void => {
console.log(`${pass ? "✓" : "✗"} ${label}`);
if (!pass) process.exitCode = 1;
};
ok("readonly 没有 write/bash", readonly.active.join(",") === "read,grep,find,ls");
ok("readonly 下 write 与 bash 都是 not found", readonly.write.ran === false && readonly.bash.ran === false);
ok("readonly 下没有文件被创建", readonly.fileText === "");
ok("editing 有 write 但没有 bash", editing.active.includes("write") && editing.active.includes("bash") === false);
ok("editing 下 write 成功写入", editing.fileText === "hello");
ok("editing 下 bash 仍是 not found", editing.bash.ran === false);
ok("full 下 bash 覆盖了 write 的结果", full.fileText === "from-bash");
ok("三套工具集的激活数量递增", readonly.active.length < editing.active.length && editing.active.length < full.active.length);
console.log("✓ OK");