斜杠命令与自定义 UI
一个扩展如何添加一条 / 命令并渲染自己的屏幕,以及那些决定这块屏幕究竟是否存在的模式规则。
你的 guard 扩展会记录被阻止的写入。读者想要看见它们。显而易见的动作是写一条 /guard 命令,打开一个选择器。你写好了它,在一台 CI 机器上运行 pi --print,而这条命令静悄悄地什么也不做,因为 print 模式压根没有 UI。
那份沉默不是一个 bug。它是你必须在写下这条命令之前而不是之后绕着它设计的那条规则。本章讲的就是那条规则,以及 Pi 实际提供给一个扩展的那三个界面层级。
一条命令是一次注册,不是一个脚本
pi.registerCommand(name, options) 往那个同样容纳内置命令、提示词模板和技能的菜单里加一个 /name 条目。slash-commands.md 明确说:“Pi 中的命令菜单因此就是你的会话中所加载资源的精确参照。” 你的命令不是二等公民;它坐在 /model 和 /tree 旁边。
最小的有用命令需要一个名字、一段描述和一个处理器。处理器收到原始的参数文本和一个上下文:
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");
},
});
}
description 原则上可选,但你总该写上它,因为菜单是用户发现这条命令的唯一地方。rpc-commands.md 描述 get_commands 返回的命令对象:带 name、可选的 description、source 和 sourceInfo,所以你的描述变成了结构化元数据,而不只是一个菜单标签。
参数由你自己解析。如果你的命令想要结构化的补全,就提供 getArgumentCompletions,它为某个前缀返回 { value, label } 对象,或者返回 null:
pi.registerCommand("guard", {
description: "Inspect and configure the path guard",
getArgumentCompletions: (prefix) => {
const modes = ["status", "pause", "resume", "reset"];
const hit = modes.filter((m) => m.startsWith(prefix));
return hit.length ? hit.map((m) => ({ value: m, label: m })) : null;
},
有文档记载的形状,取自随附的 commands.ts 示例,它把一份来源列表对着一个前缀过滤,没有匹配时返回 null。
界面的三个层级
tui.md 给了你一架梯子,而它的顶端是大多数人该停下来的地方:
| 需求 | 用什么 |
|---|---|
| 选择、确认、输入或多行编辑器 | ctx.ui.select()、confirm()、input()、editor() |
| 非阻塞的反馈 | ctx.ui.notify() 或 setStatus() |
| 编辑器附近常驻的内容 | ctx.ui.setWidget() |
| 替换页眉、页脚或编辑器 | 对应的 ctx.ui 组件工厂 |
| 临时的交互式屏幕或浮层 | ctx.ui.custom() |
| 为工具或会话条目做自定义渲染 | 一个扩展渲染器 |
表格后面那句指令才要紧:“只有当一个交互需要自己的渲染和输入时,才用 ctx.ui.custom()。” 如果一个交互能用对话框表达,就用对话框。
所以守卫的菜单是一个 select:
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");
}
模式规则
下面这句话要记住。extensions.md,“UI and modes” 一节:
扩展会加载进交互模式、RPC 模式、JSON 模式和 print 模式。交互模式提供完整的终端 UI。RPC 可以把受支持的对话框和通知通过 RPC Extension UI 协议转发给客户端,但不能转发自定义终端组件;JSON 和 print 模式没有 UI。用
ctx.mode === "tui"来守护仅限终端的行为,并用ctx.hasUI来判断交互式和 RPC 客户端所支持的交互。
有文档记载,而它交给你两个不同的守卫。ctx.hasUI 在交互式和 RPC 客户端中为真。ctx.mode === "tui" 只有在一个真实终端被接上时才为真。对话框是一个 hasUI 的东西。自定义组件是一个 tui 的东西。
| 模式 | ctx.mode |
ctx.hasUI |
对话框与 notify() |
ctx.ui.custom() |
|---|---|---|---|---|
| 交互式 | "tui" |
true |
是 | 是 |
| RPC | "rpc" |
true |
转发给客户端 | 返回 undefined |
| JSON | "json" |
false |
压根没有 UI | 压根没有 UI |
"print" |
false |
压根没有 UI | 压根没有 UI |
对着已声明的 ExtensionMode 各值来看,那就是整个矩阵。RPC 那一行是两个守卫分道扬镳的地方:rpc-extension-ui.md 把那些方法分成对话框(select、confirm、input、editor)——它们阻塞在一个客户端响应上——和即发即忘的调用(notify、setStatus、setWidget、setTitle)——它们不阻塞。一切需要终端访问的东西都会降级——custom() 返回 undefined,大多数 setter 变成空操作,getTheme() 返回 undefined。
下面是一条两者都遵守的命令:
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`);
这就是一个"只限终端"的扩展与一个"知晓终端"的扩展之间的区别。工具和事件的行为保持不变;只有呈现那个分支会变。extensions.md 坚持的正是这个分离:“让工具和事件的行为独立于渲染,这样非交互模式仍然可用。”
flowchart TD
EXT["你的扩展代码"] --> Q{"它需要什么?"}
Q -->|"一个对话框"| H{"ctx.hasUI?"}
H -->|yes| D["select、confirm、input、editor<br/>TUI 中:一个对话框;RPC 中:被转发"]
H -->|no| REFUSE["不要继续,并说明原因<br/>没有人能回答"]
Q -->|"一块自定义屏幕"| T{"ctx.mode === 'tui'?"}
T -->|yes| C["ctx.ui.custom()<br/>你拥有这块区域、按键和生命周期"]
T -->|"否,例如 RPC"| UNDEF["custom() 返回 undefined<br/>降级为别的东西"]
Q -->|"一个终端组件"| G{"ctx.mode === 'tui'?"}
G -->|no| FALL["回退到一个对话框或纯输出"]
两个守卫回答的是不同的问题,且不可互换。hasUI 意味着有人可以问;mode === "tui" 意味着有一块终端可以在上面画。RPC 那一列正是把两者混同会被打破的地方:它有一个能问的 UI,却没有一块可以接管的终端。
当你确实需要一块屏幕时
有时候交互不是一个对话框。一个棋盘游戏、一个 diff 审阅器、一个实时仪表——那些需要自己的渲染、自己的键盘处理、自己的生命周期。那就是 ctx.ui.custom(),而它是一个你必须小心守住的承诺。
出自 tui.md:ctx.ui.custom() “临时把交互区的控制权交给一个组件,并在该组件调用所提供的完成回调时 resolve。” 你拿到一个工厂;你返回一个组件;交互结束时你调用那个回调。
随附的 todo 示例就是这个形状。它定义一个小类,带 render(width) 和 invalidate(),然后打开它:
pi.registerCommand("guard-blocks", {
description: "Show blocked calls recorded on this branch",
handler: async (_args, ctx) => {
if (ctx.mode !== "tui") {
ctx.ui.notify("/guard-blocks requires interactive mode", "error");
return;
}
await ctx.ui.custom<void>((_tui, theme, _kb, done) => {
return new BlockListComponent(blocks, theme, () => done());
});
},
});
它打开的那个 BlockListComponent 是一个完整的类。这里把它完整给出,因为下面清单里的那些规则,在一个类里看比凭信任接受更容易:
import type { Component } from "@earendil-works/pi-tui";
import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
export interface GuardBlock {
tool: string;
reason: string;
at: number;
}
// The theme methods this component uses. pi-tui passes the real theme in.
export interface BlockListTheme {
fg(color: string, text: string): string;
bold(text: string): string;
}
// A custom component renders an array of lines for a width, and must say when
// its cached output is stale.
export class BlockListComponent implements Component {
private cachedWidth?: number;
private cachedLines?: string[];
private readonly blocks: readonly GuardBlock[];
private readonly theme: BlockListTheme;
private readonly close: () => void;
// Explicit fields rather than constructor parameter properties, so the file
// also runs under Node's type stripping.
constructor(blocks: readonly GuardBlock[], theme: BlockListTheme, close: () => void) {
this.blocks = blocks;
this.theme = theme;
this.close = close;
}
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;
}
handleInput(data: string): void {
if (data === "q" || matchesKey(data, "escape")) this.close();
}
invalidate(): void {
this.cachedWidth = undefined;
this.cachedLines = undefined;
}
}
tui.md 的四条规则让它变得正确,而不只是能跑:
- 每一条渲染出来的行都必须适配给定的宽度。要度量显示列,而不是字符串长度,因为 ANSI 转义和宽字符会改变宽度。用
visibleWidth()、truncateToWidth()、sliceByColumn()、wrapTextWithAnsi(),不要自己写。 - 改变状态之后,让受影响的组件失效,并调用注入的
tui.requestRender()。 - 把每个组件实例当作属于一次交互的东西。每次都创建一个新实例。
- 用完成回调来结束。不要对你用
ctx.ui.custom()创建的浮层调用OverlayHandle.hide()。
守卫的阻止列表按宽度缓存它的行,这是 todo 示例用的模式,值得照抄:一个每次按键都重新排版的转录记录,是一个扩展让终端感觉变慢的最常见单一原因。
在转录记录中渲染已存储的条目
还有第四个界面,而它是让状态变得可见而不只是被存储的那一个。pi.registerEntryRenderer(customType, renderer) 在交互模式中画出你的 custom 条目,也就是上一章放置它们的地方。
import { Box, Text } from "@earendil-works/pi-tui";
pi.registerEntryRenderer<GuardBlock>("guard.block", (entry, { expanded }, theme) => {
const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text));
box.addChild(new Text(`${theme.fg("accent", "[guard]")} ${entry.data?.reason ?? "blocked"}`, 0, 0));
if (expanded) {
box.addChild(new Text(theme.fg("dim", new Date(entry.data?.at ?? Date.now()).toLocaleString()), 0, 0));
}
return box;
});
这是改编后的 entry-renderer.ts 示例。session-format.md 确认这个配对是正当的:“交互模式可以通过 pi.registerEntryRenderer(customType, renderer) 渲染 custom 条目,但它们仍然不参与 LLM 上下文。” 对你可见,对模型不可见。那是一个有用的不对称,也是为什么一个守卫的审计轨迹属于一条 custom 条目、而不是一条 custom_message 的原因。
渲染器在哪些地方不管用
渲染器本质上只限于交互模式。在 JSON 模式中没有转录记录可以画进去;在 print 模式中没有屏幕。debug-provider 示例把捕获到的 provider 事件存为 custom 条目并把它们渲染出来,因此它是一个你交互式使用、然后作为会话文件里的数据去检查的调试工具。
自己检查
pi --extension ./guard.ts
运行 /guard 并从菜单里选。然后,在同一个项目里:
pi --print "edit .env and add a token"
守卫仍然阻止那次写入——tool_call 处理器没有变——但命令路径改为打印到 stderr,而不是打开一个菜单。安全行为的任何部分都没有变;只有呈现变了。那就是全部的纪律。
运行了什么
examples/ch20-ui/ 是一个完整扩展,外加本章用到却没有展示的那个 BlockListComponent。命令和对话框带着一个界面的录制型替身跑过一个真实的会话,那是第 31 章的论点被当作一种技术来用:智能体不关心 ctx.ui 的另一边是什么。
- 被绑定为一个 RPC 风格的客户端(
hasUI为真,但不是终端)时,/guard打开那个select对话框,并通过notify报告答案; - 没有 UI 时,同一条命令改为打印;
hasUI与终端不是一回事:在那个 RPC 风格的模式下,/guard-blocks以 “requires interactive mode” 拒绝,并且从不尝试那块自定义屏幕;- 在 20、40 和 80 列时,组件的行从不超过宽度,包括宽字符,因为它用
visibleWidth()度量; - 它的输出按宽度缓存,并在
invalidate()之后重新计算,而q和 Escape 都通过完成回调结束。
没有运行的是:那块自定义屏幕本身和那个条目渲染器需要一个真实终端。它们对着锁定的声明编译通过,而那个组件也被直接测试过,但这儿没有任何东西展示它们被画出来的样子。
途中发现的一个实用备注:这个组件使用显式字段,而不是 TypeScript 的构造函数参数属性,所以该文件也能在 Node 内置的类型剥离下运行——后者不接受那种简写形式。
本章没有解决的问题
它没有讲 pi.registerShortcut() 或 pi.registerFlag(),extensions.md 把它们列为添加键盘快捷键或命令行选项的剩下两个集成点。那些属于终端界面章节里的键位绑定材料,而它们不是同一种东西:一个旗标改变启动,一个快捷键改变输入。
下一章:MCP 服务器——随着我们注册一个 issue 跟踪器服务器,并发现注解只是建议而不是许可,守卫不再是模型与外部世界之间唯一的东西。