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

Pi Agent 自定义工具开发

注册展品看板工具,验证参数兼容、状态恢复、输出截断及并发文件变更。

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

学完这一章,你能够

给模型声明可选的工具

用 pi.registerTool 声明模型可用的工具。本站的展品看板用 add、list、remove 管理临时清单。description 说明用途,promptSnippet 提供简短提示,最终选哪个工具由模型和当前上下文决定。本章的本机模型模拟端点按固定输入发起调用,便于分别看到请求、工具结果和后续响应。

在会话分支内恢复状态

把清单的副本写入成功的 toolResult.details。重启后从 getBranch() 找最后一份成功结果,忽略其他分支和失败调用。另可用 pi.appendEntry 写入自定义条目,结合 pi.registerEntryRenderer 为终端定制展示。普通自定义条目可保存在会话分支中,发送到模型的消息不会自动带上这些条目。

声明参数并保留迁移兼容

模型看到稳定工具名和参数模式。promptGuidelines 中直接写工具名,因为规则会一起汇入系统提示。prepareArguments 在验证前迁移旧字段,本站例子把旧 operation 转为 action,同时保留已有的 action 值。公开的参数模式只声明当前字段。

三个操作选项用 StringEnum 生成一个字符串枚举。某些提供方对 Type.Union 与 Type.Literal 生成的联合模式支持不同,面向 Google 接口时优先使用 Pi 提供的枚举工具。本站验证了发出的模式与错误枚举的本机行为。

执行、进度、异常和结束条件

execute 接收调用 ID、已验证参数、可选的取消信号、进度回调和工具上下文。对长操作,把 signal 传给支持取消的 API。用 onUpdate 发部分进度,最终返回 content 和自需的 details。可选 usage 描述嵌套模型的用量。同批所有最终工具结果都要求 terminate 时,Pi 跳过自动追加的模型调用。

执行函数发现必要条件缺失时抛出 Error,由 Pi 生成失败的工具结果。模式验证也可以在执行前拒绝非法输入。业务上的正常空结果仍可返回解释,例如请求移除不存在的展品时报告未找到并保留清单。

串行化同一文件的读改写

先把工作文件定位为绝对路径,把读取、修改和写回一起放进 withFileMutationQueue 的回调。Pi 内置 edit、write 与使用此方法的自编变更共用按文件协调的队列。本机在同一批次向临时展品笔记写入两枚标记,两个结果均保留。队列协调参与它的操作,跨进程变更需要另行控制。

限制输出的行数和字节数

truncateHead 同时检查行数与 UTF-8 字节数。Pi 1.5.0 公开的默认上限为 2000 行和 51200 字节。本站例子使用较小上限清楚呈现行截断与字节截断,并附保留量与原总量。对更大的输入还应控制读取范围,避免用裁短结果掩盖读取开销。

覆盖内置工具时保留接口约定

扩展注册与内置工具相同的名字时可替换实现。本站明确启用同名 read,限制为自编的本机文件,再委托原读取定义执行并记录自定义条目。渲染函数分别继承,某个槽没有改写时可继续使用内置渲染函数。

覆盖实现要自行声明 promptSnippet 与需要的 promptGuidelines。read 仍需接受 path、可选 offset 和 limit,offset 从第 1 行计起。结果应保留内置结构,特别是截断时的 ReadToolDetails。实测分页返回指定行,长文件保留截断详情及下一页偏移。

registerTool 的注册字段

字段类型必填作用与条件
namestring是给模型和 JSON 工具调用使用的唯一工具名。
labelstring是供界面展示的短名称。
descriptionstring是告诉模型工具处理的任务与适用范围。
parametersTypeBox 模式是声明参数形状和允许的枚举值,执行前验证。
promptSnippetstring否模型系统提示的工具清单中使用的一行说明。
promptGuidelinesstring[]否附加给模型的调用指南。每条规则点明工具名。
prepareArguments(args) → 当前参数否在验证前转换旧参数,保留已提供的最新字段。
execute异步函数是执行工具逻辑,返回内容与本地详情,或抛出执行错误。

execute 的入参

参数类型作用与条件
toolCallIdstring关联开始、进度和最终结果的调用 ID。
params工具模式推断的对象验证通过的参数,业务规则仍在执行时判断。
signalAbortSignal 或 undefined接入支持取消的异步操作;交互退出或 RPC 可触发取消。
onUpdate可选回调把部分结果发送给界面或 RPC 消费者。
ctxExtensionToolContext扩展上下文,提供当前工作目录、UI、会话等能力。

在本机运行展品看板工具

typescript · 阅读源码
import {readFile, writeFile} from "node:fs/promises";
import {resolve} from "node:path";
import {setTimeout as delay} from "node:timers/promises";
import {
  createReadToolDefinition, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize,
  truncateHead, withFileMutationQueue, type ExtensionAPI,
} from "@earendil-works/pi-coding-agent";
import {StringEnum} from "@earendil-works/pi-ai";
import {Type} from "typebox";

export default function (pi: ExtensionAPI) {
  let displays: string[] = [];
  pi.on("session_start", (_event, ctx) => {
    const saved = ctx.sessionManager.getBranch().findLast(entry =>
      entry.type === "message" && entry.message.role === "toolResult" &&
      entry.message.toolName === "exhibit_board" && !entry.message.isError &&
      Array.isArray(entry.message.details?.displays));
    if (saved?.type === "message" && saved.message.role === "toolResult") {
      displays = [...saved.message.details.displays];
    } else {
      displays = [];
    }
  });
  pi.registerTool({
    name: "exhibit_board",
    label: "Exhibit board",
    description: "Maintains the list of planned exhibits.",
    promptSnippet: "Maintain the planned exhibit list.",
    promptGuidelines: ["Use exhibit_board to add, list or remove planned exhibits."],
    parameters: Type.Object({
      action: StringEnum(["add", "list", "remove"] as const),
      name: Type.Optional(Type.String()),
    }, {additionalProperties: false}),
    prepareArguments(args) {
      if (!args || typeof args !== "object" || Array.isArray(args)) return args;
      const {operation, ...current} = args as {operation?: unknown; action?: unknown};
      if (current.action === undefined && operation !== undefined) current.action = operation;
      return current;
    },
    async execute(id, params, signal, onUpdate, ctx) {
      signal?.throwIfAborted();
      onUpdate?.({content: [{type: "text", text: "Updating exhibit board."}], details: {}});
      const name = params.name?.trim();
      let text = "Exhibits: " + (displays.join(", ") || "none");
      if (params.action !== "list") {
        if (!name) throw new Error("An exhibit name is required.");
        if (params.action === "add") {
          if (displays.includes(name)) throw new Error("Exhibit already exists.");
          displays = [...displays, name];
          text = "Added exhibit: " + name;
        } else {
          const found = displays.includes(name);
          displays = displays.filter(entry => entry !== name);
          text = (found ? "Removed exhibit: " : "Exhibit not found: ") + name;
        }
        pi.appendEntry("exhibit-history", {id, marker: "local-exhibit-marker"});
        ctx.ui.notify(text, "info");
      }
      return {content: [{type: "text", text}], details: {displays: [...displays]}};
    },
  });

  pi.registerTool({
    name: "exhibit_ticket",
    label: "Exhibit ticket",
    description: "Provides a short label for an exhibit.",
    parameters: Type.Object({name: Type.String(), final: Type.Boolean()}),
    async execute(_id, params) {
      return {
        content: [{type: "text", text: "Ticket: " + params.name}],
        details: {name: params.name},
        terminate: params.final,
      };
    },
  });
  pi.registerTool({
    name: "stamp_exhibit_note",
    label: "Stamp exhibit note",
    description: "Adds a label to the case file created for this local exercise.",
    parameters: Type.Object({mark: StringEnum(["blue", "green"] as const)}),
    async execute(_id, params, signal, _onUpdate, ctx) {
      const file = resolve(ctx.cwd, "exhibit-note.txt");
      return withFileMutationQueue(file, async () => {
        const previous = await readFile(file, "utf8");
        await delay(60, undefined, {signal});
        await writeFile(file, previous + params.mark + "\n", "utf8");
        return {content: [{type: "text", text: "Stamped " + params.mark}], details: {}};
      });
    },
  });
  pi.registerTool({
    name: "preview_exhibit_note",
    label: "Preview exhibit note",
    description: "Previews a bounded excerpt of the locally generated exhibit note.",
    parameters: Type.Object({maxLines: Type.Integer({minimum: 1, maximum: 10}),
                             maxBytes: Type.Integer({minimum: 4, maximum: 256})}),
    async execute(_id, params, _signal, _onUpdate, ctx) {
      const input = await readFile(resolve(ctx.cwd, "exhibit-note.txt"), "utf8");
      const result = truncateHead(input, params);
      const notice = result.truncated
        ? "\n[Preview: " + result.outputLines + "/" + result.totalLines +
          " lines, " + formatSize(result.outputBytes) + "/" + formatSize(result.totalBytes) + "]"
        : "";
      return {content: [{type: "text", text: result.content + notice}],
              details: {...result, defaults: [DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES]}};
    },
  });
  pi.registerTool({
    name: "wait_exhibit",
    label: "Wait for exhibit label",
    description: "Waits for a short, cancellable local exercise.",
    parameters: Type.Object({}),
    async execute(_id, _params, signal, onUpdate) {
      onUpdate?.({content: [{type: "text", text: "Waiting for exhibit."}], details: {}});
      try {
        await delay(2000, undefined, {signal});
        return {content: [{type: "text", text: "Wait finished."}], details: {}};
      } catch (error) {
        if (!signal?.aborted) throw error;
        return {content: [{type: "text", text: "Wait cancelled."}], details: {cancelled: true}};
      }
    },
  });

  pi.registerTool({
    name: "read",
    label: "Read the fixture",
    description: "Reads the single fixture created for this local exercise.",
    parameters: Type.Object({
      path: Type.String(),
      offset: Type.Optional(Type.Number()),
      limit: Type.Optional(Type.Number()),
    }),
    promptSnippet: "Read the exhibit-note.txt fixture.",
    async execute(id, params, signal, onUpdate, ctx) {
      if (params.path !== "exhibit-note.txt") throw new Error("The exercise permits exhibit-note.txt only.");
      const base = createReadToolDefinition(ctx.cwd);
      const result = await base.execute(id, params, signal, onUpdate, ctx);
      pi.appendEntry("exhibit-fixture-read", {offset: params.offset, limit: params.limit});
      return result;
    },
  });
}

预期结果 · 待实际运行核验
  • 兼容旧字段并恢复同一分支的展品清单。两个并发标记都留在临时文件,截断后标明保留量。同名 read 保留原有分页及截断详情。
在本机运行展品看板工具

所需环境:Windows、Node.js 24.22.3、Pi 1.5.0、TypeBox、同一本机模拟端点。

当前源码 SHA256:84ecd46def38b5684514e21207b118904ac9bb234be6c0ce3a1f1507ad8f8830

下载本站示例源码

本地复跑

解压后按 README 执行 custom-tools-check.mjs,检查工具参数、返回、终止和文件写入各项结果。

下载展品看板工具与本机验证脚本

所需环境:Windows、Node.js 24.22.3、Pi 1.5.0、TypeBox、同一本机模拟端点。

ZIP SHA256:e634d79c6adde0fc90a03704485dcf6b4b62a8f5caef1aacf10abb475668cfca

常见错误与边界

  • 在执行前验证参数并安全处理取消。
  • 替换内置读取工具时保留分页、结果结构与输出限制。

练习与解答

为什么同一文件的读改写都要放在队列里?

展开参考解答

两条操作在进入队列后分别重新读取当前内容,因此下一条能看到前一条已写入的结果。

规范与官方依据