Example

把一个守卫的被阻止计数持久化为一条会话条目

用 pi.appendEntry() 记录一次被阻止的写入,用 /guard-blocks 把它读回来,并看着计数跟随分支。

一个模块级 let 随进程一起消亡:/reload 和恢复都会把它重置。修复办法是用 Pi 已经交给你的那个持久存储。这个示例把每一次被阻止的写入记录为一条模型永远看不见的 custom 会话条目,并在 session_start 时和导航时从活动分支重建计数。这些论断观察自一个脚本化的模型和一个录制型 UI。

运行它

使用 Pi 1.0.4 和示例仓库的测试运行器之一。下面这个文件是本章那条规范 guard-blocks.ts 的摘录:

	pi.on("tool_call", async (event, ctx) => {
		if (event.toolName !== "write" && event.toolName !== "edit") return undefined;

		const path = String(event.input.path ?? "");
		const hit = PROTECTED.find((p) => path.includes(p));
		if (!hit) return undefined;

		const entry: GuardBlock = {
			tool: event.toolName,
			reason: `path matches ${hit}`,
			at: Date.now(),
		};
		blocks = [...blocks, entry];

		// Durable, branch-aware, and invisible to the model.
		pi.appendEntry<GuardBlock>("guard.block", entry);

		if (ctx.hasUI) ctx.ui.notify(`Blocked ${event.toolName} on ${path}`, "warning");
		return { block: true, reason: `Path "${path}" is protected` };
	});

	pi.registerCommand("guard-blocks", {
		description: "List blocked tool calls recorded in this session",
		handler: async (_args, ctx) => {
			ctx.ui.notify(
				blocks.length === 0 ? "No blocked calls in this session" : blocks.map((b) => b.reason).join("; "),
				"info",
			);
		},
	});

内存中的 blocks 数组是一个缓存,不是存储。用活动分支重新填满它,绝不用文件里的每一个条目——被放弃的分支是替代的历史,而它们的阻止不能计数:

	// The module variable is a cache, not the store. Refill it from the active
	// branch, never from every entry in the file.
	const rebuild = (ctx: ExtensionContext) => {
		const next: GuardBlock[] = [];
		for (const entry of ctx.sessionManager.getBranch()) {
			if (entry.type === "custom" && entry.customType === "guard.block") {
				next.push(entry.data as GuardBlock);
			}
		}
		blocks = next;
	};

	pi.on("session_start", async (_e, ctx) => rebuild(ctx));
	pi.on("session_tree", async (_e, ctx) => rebuild(ctx));

预期结果

步骤 结果(已观察)
模型写入 .env 这次写入被阻止;用户看到一条 warning 通知;一条 customType 为 “guard.block” 的 custom 条目落在会话里
下一次请求发出 条目和理由文本都不到达 provider
运行 /guard-blocks 它报告 path matches .env
导航到那次阻止之前,再运行一次 No blocked calls in this session——计数是相对于分支的

机制与局限

有文档记载: pi.appendEntry(customType, data) 写入一条 custom 会话条目;会话格式文档指出,一个 CustomEntry “不参与 LLM 上下文”;extensions.md 说要在 session_start 期间从 ctx.sessionManager.getBranch() 重建对分支敏感的状态,而不是从每一个文件条目重建。已观察: guard-blocks.test.ts 用一个脚本化的 provider 和一个录制型 UI,把真实的扩展跑过一个 AgentSession,并对上面每一行做出断言——包括那段理由文本不在 provider 收到的转录记录里,这是"对模型不可见"最强的形式。

这个示例没有展示一个真实模型,也没有展示条目在转录记录里:渲染它们是 pi.registerEntryRenderer,它只限交互模式,属于下一章。计数能在重载后活下来,只是因为 /reload 会重新运行工厂、而 session_start 会重建它——工厂本身并不持久。

完整源码与测试 。

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.