Example

添加一条斜杠命令和一块尊重模式规则的自定义屏幕

一条在 RPC 下打开对话框、在没有 UI 时打印的 /guard 命令,以及一块只存在于真实终端里的自定义屏幕。

一条命令能不能做成任何事,取决于它的模式:对话框需要 ctx.hasUI,自定义屏幕需要一个真实终端。这个示例是最小的 /guard 命令、那个双守卫规则,以及一个按列宽适配的组件——全都观察自一个脚本化的模型。

运行它

使用 Pi 1.0.4 和示例仓库的测试运行器之一。最小的命令就是一次注册,用 pi -e ./guard.ts 加载:

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";

export default function (pi: ExtensionAPI) {
	pi.registerCommand("guard", {
		description: "Inspect and configure the path guard",
		handler: async (args, ctx) => {
			ctx.ui.notify(`guard received: "${args}"`, "info");
		},
	});
}

完整的命令来自 guard-ui.ts,它在那两个问题上分叉——对话框在 ctx.hasUI 为真的任何地方都能用,而没有 UI 时它会在退出途中说明这一点:

			if (ctx.hasUI) {
				const choice = await ctx.ui.select("Path guard", ["Show blocked calls", "Pause the guard", "Resume the guard"]);
				if (choice === "Show blocked calls") {
					ctx.ui.notify(`${blocks.length} blocked call(s) this session`, "info");
				}
				return;
			}

			// JSON and print: no UI at all. Say something useful on the way out.
			console.log(`[guard] ${blocks.length} blocked call(s); run this in interactive mode to configure`);

一块自定义屏幕是一个 tui 的东西,不是一个 hasUI 的东西——在 RPC 下它被拒绝,而不是被尝试:

			if (ctx.mode !== "tui") {
				ctx.ui.notify("/guard-blocks requires interactive mode", "error");
				return;
			}

这块屏幕通过一个来自 block-list.ts 的可复用组件渲染,后者为一个宽度画出行、度量显示列,并按宽度缓存:

	render(width: number): string[] {
		// Cache by width: re-laying-out on every keystroke is what makes a terminal feel slow.
		if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;

		const lines = [this.theme.fg("accent", this.theme.bold("Blocked calls")), ""];
		if (this.blocks.length === 0) lines.push(this.theme.fg("dim", "none on this branch"));
		for (const b of this.blocks) lines.push(`${b.tool}: ${b.reason}`);
		lines.push("", this.theme.fg("dim", "press q or Escape to close"));

		// Every line must fit the width, measured in display columns, not string length.
		this.cachedLines = lines.map((l) => (visibleWidth(l) > width ? truncateToWidth(l, width) : l));
		this.cachedWidth = width;
		return this.cachedLines;
	}

预期结果

模式 ctx.mode ctx.hasUI /guard /guard-blocks
交互式 "tui" true 一个对话框 一块自定义屏幕
RPC 风格的客户端 "rpc" true 通过客户端得到回答的对话框 被拒绝
JSON / print "json" / "print" false 打印 打印

RPC 和 print 两行是已观察的;那块自定义屏幕和那个条目渲染器没有被运行——自定义屏幕需要一个真实终端。

机制与局限

有文档记载: extensions.md,“UI and modes” 一节:交互式提供完整的终端 UI;RPC 转发对话框和通知,但不转发自定义终端组件;JSON 和 print 没有 UI。用 ctx.mode === "tui" 守护仅限终端的行为,用 ctx.hasUI 判断交互式和 RPC 客户端所支持的东西。已观察: ui.test.ts 绑定一个界面的录制型替身,并对每一行做出断言:有 UI 时,/guard 打开一个 select 并通过 notify 回答;没有 UI 时它打印;RPC 下 /guard-blocks 在尝试之前就拒绝;组件的行从不超过 20、40 或 80 列,包括宽字符,它的输出按宽度缓存,而 q/Escape 通过完成回调结束。

完整源码与测试 。

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.