决定一个需求需要哪种 Pi 机制
把评审守卫实现为一个 tool_call 扩展,并看清为什么强制推送是禁令,而 migrations/ 只是确认。
两个听起来很像的需求,是不同种类的需求。“在动 migrations/ 下的任何东西之前先确认"会去问一个人。“不要强制推送"则必须成立,无论有没有人在那里可问。只有一个扩展能在一次工具调用运行之前对它行动,所以两者都属于同一个 tool_call 处理器——但它们需要不同的代码。
运行它
使用 Pi 1.0.4 和示例仓库的测试运行器之一。下面这个文件是本章的规范扩展,被精确复制于此:
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
pi.on("tool_call", async (event, ctx) => {
if (event.toolName !== "bash" && event.toolName !== "edit") return;
const raw = JSON.stringify(event.input);
// \b, not (^|\s): in the serialised input "git" follows a quote, not whitespace.
const forcePush = /\bgit\s+push\b.*(?:\s--force\b|\s-f\b|--force-with-lease\b)/.test(raw);
// An unconditional prohibition, not a question: no confirmation prompt, so
// there is nothing for a person to approve.
if (forcePush) return { block: true, reason: "Force pushes are not permitted by this repository's guard" };
// A different kind of rule. Ask, then proceed on the answer.
if (!/\bgit\s+push\b/.test(raw) && !/migrations\//.test(raw)) return;
if (ctx.hasUI && (await ctx.ui.confirm("Allow this call?", raw.slice(0, 120)))) return;
return { block: true, reason: "Blocked by guard extension" };
});
}用 pi -e ./guard.ts 加载它,然后让 Pi 运行一条下列形状之一的命令。
预期结果
| 模型做出的调用 | 守卫的行为 | 原因 |
|---|---|---|
echo git push origin main |
一次确认;答是时放行 | 一次普通推送就是一次确认 |
git push --force origin main |
直接阻止,不给提示 | 强制推送是无条件的禁令 |
touch migrations/001.sql |
一次确认;答否时文件永远不会被创建 | 确认式守卫运行在效果之前 |
echo hello |
不被触碰 | 处理器不做决定就返回 |
echo … 这些形式很重要:模式匹配的是序列化后的 event.input,所以 echo git push 会被匹配,尽管这条命令无害。这让这条命令可以安全运行,同时仍然走到那个分支——唯一能让它变成错误的是守卫本身。
机制与局限
有文档记载: 导出的 ExtensionAPI 声明定义了 pi.on("tool_call", …)、处理器的返回形状({ block: true, reason }),以及 ctx.hasUI / ctx.ui.confirm。已观察: guard.test.ts 通过一个脚本化的 provider 和一个 AgentSession 驱动真实的处理器,并对上面每一行做出断言,包括被阻止的确认不会创建文件。那条回归测试钉住了第一个版本为什么错:模式 (^|\s)git\s+push 对一次普通推送从不触发,因为在 {"command":"git push origin main"} 里 git 这个词跟在一个引号后面,而不是空白字符后面。它只在对 cd x && git push 这样的复合命令上看起来有效。
这不是一道边界。它只匹配 bash 和 edit,别的都不匹配——migrations/ 下的一次 write、一次 multi_edit,或者一个扩展自己的工具,都不在覆盖范围内。它匹配的是一个序列化后的字符串,所以 git push origin +main 会在不匹配该模式的情况下重写一个 ref,而 echo "git push --force" 会在什么也没做的情况下匹配它。对于一个必须成立而不只是通常发生的需求,答案是操作系统边界,而不是一条更长的正则表达式(第 42 章)。这个示例没有展示一个真实模型选择命令的过程;它展示的是模型周围的代码。
完整源码与测试 。
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.