示例工程 ch12-builtin-tools
ch12-builtin-tools/01-readonly-toolset/index.ts
// 01-readonly-toolset —— 只用四个只读工具(read / grep / find / ls),并验证写操作被拒。
//
// 运行:node --experimental-strip-types index.ts
//
// 用途:给「代码问答」「审查」这类不需要改文件的场景一个最小能力集。
// 观察点:写工具即使「注册过」,只要没被激活,模型调用就会被判 not found。
import { mkdtempSync, writeFileSync } 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";
const cwd = mkdtempSync(join(tmpdir(), "pi-ch12-readonly-"));
writeFileSync(join(cwd, "a.txt"), "alpha\nbeta\n");
const stub = await createStubRuntime({
steps: [
{
toolCalls: [
{ id: "c1", name: "read", arguments: { path: "a.txt" } },
{ id: "c2", name: "write", arguments: { path: "a.txt", content: "hacked" } },
],
},
{ text: "只读模式。" },
],
});
const { session } = await createAgentSession({
model: stub.model,
modelRuntime: stub.modelRuntime,
agentDir: stub.agentDir,
sessionManager: SessionManager.inMemory(cwd),
cwd,
// 只允许四个只读工具(read/grep/find/ls 是内置名)
tools: ["read", "grep", "find", "ls"],
});
await session.prompt("读 a.txt,然后试着改它");
const results = session.agent.state.messages.filter((message) => message.role === "toolResult");
const byId = (id: string) => results.find((message) => message.role === "toolResult" && message.toolCallId === id);
const textOf = (id: string) => {
const result = byId(id);
return result && "content" in result ? (result.content[0] as { text?: string })?.text ?? "" : "";
};
console.log("激活的工具:", session.getActiveToolNames().join(", "));
console.log("read 结果:", JSON.stringify(textOf("c1")).slice(0, 80));
console.log("write 结果:", JSON.stringify(textOf("c2")).slice(0, 100));
const ok = (label: string, pass: boolean): void => {
console.log(`${pass ? "✓" : "✗"} ${label}`);
if (!pass) process.exitCode = 1;
};
ok("激活的正是四个只读工具", session.getActiveToolNames().join(",") === "read,grep,find,ls");
ok("read 读到了文件内容", textOf("c1").includes("alpha"));
ok("write 未激活 → 被判 not found", textOf("c2").toLowerCase().includes("not found"));
ok("write 的结果 isError=true", byId("c2")?.role === "toolResult" && byId("c2")?.isError === true);
ok("文件没有被改动", JSON.stringify(textOf("c1")).includes("alpha"));
ok("write 被允许清单过滤掉(getAllTools 里也没有)", session.getAllTools().some((tool) => tool.name === "write") === false);
session.dispose();
console.log("✓ OK");