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;
},
});
}
本例需在 Windows、Node.js 24.22.3、Pi 1.5.0、TypeBox、同一本机模拟端点。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Node.js 24.22.3、Pi 1.5.0、TypeBox、同一本机模拟端点。
入口文件:projects/pi-agent-custom-tools-lab/exhibit.ts
本地运行步骤快速上手
- 点击上方“保存源码”保存为
exhibit.ts,或下载右侧课程工程包。 - 确认本地已准备 Windows、Node.js 24.22.3、Pi 1.5.0、TypeBox、同一本机模拟端点。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a272.zip
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip