蓝色天空网mbsky.com · 知识 · 实践 · 创造Pi Agent · 本地阅读预览
教程 / AI / 智能开发 / Pi Agent

Pi Agent 命令与快捷键注册

用本机展品实例验证命令、补全、快捷键、标志、消息及会话方法。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

注册命令并提供参数补全

扩展可注册斜线命令、键盘快捷键和 CLI 标志。用 registerCommand 注册处理器和说明。本站的 gallery-count 计数会话条目,条目还可能包含元数据。gallery-pick 依据前缀提供候选对象,没匹配时返回 null。实测终端按 Tab 选中 azure,再按 Enter 执行。

编辑扩展后可使用 /reload。名称冲突时 Pi 保留不同扩展的命令,按加载顺序给它们加数字后缀。本章两份扩展分别响应 /gallery-code:1 和 /gallery-code:2。

选择自定义消息或用户输入

sendMessage 写入自定义消息,可作为模型的参考;空闲时通常先保存,设置 triggerTurn 可立即运行。sendUserMessage 产生用户输入,输入钩子接管或命中指定命令时可以直接完成。流式处理中显式选择 steer 或 followUp。steer 等当前助手工具批次完成后在下一次模型调用前交付,followUp 等代理没有更多工作再交付。sendMessage 的 nextTurn 等下一次用户提示,届时才加入,也不会被 triggerTurn 强制提前。

命令上下文和会话替换

命令的 ExtensionCommandContext 继承扩展上下文,并支持等待空闲、读取提示词基础输入、创建或切换会话。要做会话选择器,可按当前项目查找会话文件并从 ctx.ui.select 取得选择。取消选择时终止命令。

withSession 在新会话启动后收到新上下文。回调只捕获旧会话的文件名、标识等普通数据。继续发送消息或调用会话接口时使用传入的新 ctx。本站通过会话 ID 变化验证了新上下文,也从 RPC 选择框选中原临时会话,读取切换后的文件路径验证确已返回。

在终端绑定快捷键和命令行标志

registerShortcut 支持 alt+9 这样的修饰键和按键组合。只有交互终端能分发这类按键。先核对目标版本和用户键位,组合键如 ctrl+shift+p 可能已有行为。本站在 Windows 终端实测 Alt+9 触发本地提示。

registerFlag 声明标志的类型、说明和默认值。CLI 先加载扩展再解析自定义标志。本站在工厂里先读到默认 false,在命令或 before_agent_start 里读到解析后的 --gallery-view。启用时给本次模型请求追加展品说明。

用事件总线和命令元数据连接扩展

pi.events 让两个扩展用同名事件和约定好的数据结构通信。本站一份扩展发送 Atlas 标签名称,另一份监听并显示,关闭会话时解除订阅。

pi.getCommands 列出可从 prompt 输入调用的扩展命令、提示词模板和技能命令。会话里的交互内置菜单另有处理路径。本站同时核对命令来源、描述、实际文件和用户或临时加载范围。

调整模型收到的工具清单

getActiveTools 给出当前启用的工具,getAllTools 提供注册条目与来源。CLI 工具参数决定起始集合,setActiveTools 可在运行时添加或替换声明集合。需要延迟加载优化时,优先在原集合上增量添加。若移除旧工具或新增带 promptSnippet、promptGuidelines 的工具,系统提示词可能重建,提供方缓存前缀可能失效。工具声明范围和操作系统可访问的权限分别配置。

命令上下文方法

方法作用与条件
getSystemPromptOptions()读取构建系统提示词的基础输入,如技能与上下文文件。
waitForIdle()等待模型、队列、重试和自动压缩等工作平息。
newSession(options)建立新会话,可指定父会话与初始化回调。
fork(entryId, options)从指定消息条目分叉,并在新会话中继续。
navigateTree(targetId, options)在同一会话树中切到指定节点。
switchSession(sessionPath, options)切换到选定会话文件。用 withSession 参数取得新的上下文。
reload()重新加载会话运行资源,行为与 /reload 对应。

命令目录字段

字段类型作用
namestring无斜线的调用名,重复名可含数字后缀。
descriptionstring 或 undefined有定义时用于补全列表的说明。
sourceextension、prompt、skill区分扩展命令、提示词模板和技能。
sourceInfo对象记录实际来源路径、资源范围和来源类型。

运行展品命令、补全与快捷键实验

typescript · 阅读源码
import {SessionManager, type ExtensionAPI} from "@earendil-works/pi-coding-agent";
import {Type} from "typebox";

export default function (pi: ExtensionAPI) {
  pi.registerFlag("gallery-view", {description: "Append a gallery note to model prompts", type: "boolean", default: false});
  const duringLoad = pi.getFlag("gallery-view");
  pi.on("before_agent_start", event => {
    if (pi.getFlag("gallery-view")) return {systemPrompt: event.systemPrompt + "\nGALLERY FIXTURE VIEW ACTIVE."};
  });
  pi.registerCommand("gallery-flag", {
    description: "Show the fixture flag seen at load and after parsing",
    handler: async (_args, ctx) => ctx.ui.notify("FLAG " + duringLoad + ":" + pi.getFlag("gallery-view"), "info"),
  });
  pi.registerCommand("gallery-count", {
    description: "Count session entries",
    handler: async (_args, ctx) => ctx.ui.notify("GALLERY ENTRIES " + ctx.sessionManager.getEntries().length, "info"),
  });
  pi.registerCommand("gallery-pick", {
    description: "Choose a color label",
    getArgumentCompletions(prefix) {
      const list = ["amber", "azure", "pearl"].filter(color => color.startsWith(prefix))
        .map(color => ({value: color, label: color}));
      return list.length ? list : null;
    },
    handler: async (args, ctx) => ctx.ui.notify(args ? "GALLERY PICK " + args.toUpperCase() : "PICK A COLOR LABEL", "info"),
  });
  pi.registerShortcut("alt+9", {
    description: "Display the local key marker",
    handler: async ctx => ctx.ui.notify("GALLERY HOTKEY OBSERVED", "info"),
  });
  pi.registerCommand("gallery-code", {
    description: "Report the first extension",
    handler: async (_args, ctx) => ctx.ui.notify("GALLERY CODE A", "info"),
  });
  pi.registerCommand("gallery-signal", {
    description: "Emit a synthetic label event",
    handler: async () => pi.events.emit("gallery:label", {name: "Atlas"}),
  });
  pi.registerCommand("gallery-index", {
    description: "List the sources of example commands",
    handler: async (_args, ctx) => {
      const choices = pi.getCommands().filter(command =>
        ["gallery-index", "gallery-template", "skill:gallery-skill"].includes(command.name));
      ctx.ui.notify("INDEX " + JSON.stringify(choices.map(command => ({
        name: command.name, description: command.description, source: command.source,
        path: command.sourceInfo.path, scope: command.sourceInfo.scope,
      }))), "info");
    },
  });
  pi.registerCommand("gallery-source", {
    description: "Inspect prompt inputs after idle",
    handler: async (_args, ctx) => {
      await ctx.waitForIdle();
      const input = ctx.getSystemPromptOptions();
      ctx.ui.notify("GALLERY SOURCE " + (input.cwd === ctx.cwd) + ":" + ctx.isIdle(), "info");
    },
  });
  pi.registerCommand("gallery-note", {
    description: "Add a fixture note for the next prompt",
    handler: async () => pi.sendMessage({customType: "gallery-note", content: "GALLERY REFERENCE", display: true}),
  });
  pi.registerCommand("gallery-run-note", {
    description: "Start a run with a fixture note",
    handler: async () => pi.sendMessage(
      {customType: "gallery-prompt", content: "GALLERY CUSTOM TRIGGER", display: true}, {triggerTurn: true}),
  });
  pi.registerCommand("gallery-user", {
    description: "Send a local synthetic user message",
    handler: async () => pi.sendUserMessage("GALLERY SYNTHETIC USER"),
  });
  pi.registerCommand("gallery-new", {
    description: "Start a new temporary session",
    handler: async (_args, ctx) => {
      const parentSession = ctx.sessionManager.getSessionFile();
      const oldId = ctx.sessionManager.getSessionId();
      await ctx.newSession({parentSession, withSession: async fresh => {
        fresh.ui.notify("GALLERY NEW " + (fresh.sessionManager.getSessionId() !== oldId), "info");
      }});
    },
  });

  pi.registerCommand("gallery-switch", {
    description: "Select a saved gallery session",
    handler: async (_args, ctx) => {
      if (!ctx.hasUI) return;
      const sessions = await SessionManager.list(ctx.cwd, ctx.sessionManager.getSessionDir());
      const paths = sessions.map(session => session.path);
      if (!paths.length) return;
      const chosen = await ctx.ui.select("Select a gallery session", paths, {timeout: 3000});
      if (chosen && paths.includes(chosen)) {
        await ctx.switchSession(chosen, {withSession: async fresh => {
          fresh.ui.notify("GALLERY SWITCH " + (fresh.sessionManager.getSessionFile() === chosen), "info");
        }});
      }
    },
  });

  for (const [name, initiallyActive] of [["gallery_card", true], ["gallery_index", false]] as const) {
    pi.registerTool({
      name, label: name, description: "Returns a synthetic gallery label.",
      promptSnippet: "Summarize " + name + " labels.",
      defaultActive: initiallyActive,
      parameters: Type.Object({}),
      async execute() {
        return {content: [{type: "text", text: "GALLERY " + name}], details: {}};
      },
    });
  }
  pi.registerCommand("gallery-tools", {
    description: "Change the tools declared for this exercise",
    handler: async (args, ctx) => {
      if (args === "add") pi.setActiveTools([...new Set([...pi.getActiveTools(), "gallery_index"])]);
      if (args === "card") pi.setActiveTools(["gallery_card"]);
      const declared = pi.getAllTools().filter(tool => tool.name.startsWith("gallery_"));
      ctx.ui.notify("ACTIVE " + JSON.stringify({active: pi.getActiveTools().filter(name => name.startsWith("gallery_")),
        registered: declared.map(tool => tool.name).sort()}), "info");
    },
  });
}

预期结果 · 待实际运行核验
  • 两份同名命令分配不同后缀,终端完成参数补全并响应 Alt+9。启用命令行标志会改变提示,选定的临时会话可切换回来。
运行展品命令、补全与快捷键实验

所需环境:Windows、Node.js 24.22.3、Pi 1.5.0、PyWinPTY 3.1.2、本机回环模型模拟。

当前源码 SHA256:a3afd095180dc04d0e0db8ec8603b8319aab344b2e919ef76d8d6924fa4a9b8c

下载本站示例源码

本地复跑

保留两个 TS 入口,分别按 README 运行 RPC 与终端驱动。

下载本站展品命令与终端实验

所需环境:Windows、Node.js 24.22.3、Pi 1.5.0、PyWinPTY 3.1.2、本机回环模型模拟。

ZIP SHA256:8ab652c39796b1b9ac24fd6ec3b141319e981e690b16c6f17df6da164ede80e5

常见错误与边界

  • 等待参数解析后再读取实际自定义标志。
  • 会话替换后使用 withSession 传入的新上下文。

练习与解答

重复注册 gallery-code 时怎样调用第二份实现?

展开参考解答

先从 get_commands 查看实际名字,再按加载顺序确定第二份命令的 gallery-code:2 后缀。

规范与官方依据