Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- Pi extensions run outside Effect; these tests exercise their native filesystem boundary.
2import * as NodeFSP from "node:fs/promises";
3import * as NodePath from "node:path";
4import * as NodeOS from "node:os";
5import * as NodeModule from "node:module";
6import * as NodeVM from "node:vm";
7import { assert, describe, expect, it } from "@effect/vitest";
8
9import { PI_T3_MCP_EXTENSION_SOURCE } from "./mcpExtensionSource.ts";
10import { loadMcpBridge } from "./mcpBridge.testkit.ts";
11
12type RequestHook = (
13 event: { payload: unknown },
14 ctx: { model: { provider: string } },
15) => Record<string, unknown> | undefined;
16
17interface SkillCommand {
18 readonly name: string;
19 readonly source: string;
20 readonly sourceInfo: { readonly path: string };
21}
22
23type InputHook = (
24 event: { text: string; images?: ReadonlyArray<unknown> },
25 ctx: { ui: { notify: (message: string, level: string) => void } },
26) => Promise<{ action: string; text: string; images?: ReadonlyArray<unknown> } | undefined>;
27
28async function loadHooks(commands: ReadonlyArray<SkillCommand> = []) {
29 const handlers = new Map<string, unknown>();
30 // Execute the shipped extension with MCP disabled; this path needs no Typebox.
31 const source = NodeModule.stripTypeScriptTypes(
32 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
33 "export default async function",
34 "async function",
35 ),
36 );
37 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
38 process: { env: {} },
39 NodeFSP,
40 NodePath,
41 // Frontmatter parsing belongs to Pi. These fixtures contain only skill bodies.
42 stripFrontmatter: (content: string) => content,
43 pi: {
44 on: (name: string, handler: unknown) => handlers.set(name, handler),
45 getCommands: () => commands,
46 },
47 });
48 return handlers;
49}
50
51describe("Pi MCP tool results", () => {
52 it("returns mixed screenshot blocks and typed script output without repeating structured text", async () => {
53 const content = [
54 { type: "text", text: "Browser screenshot" },
55 { type: "image", data: "AAAA", mimeType: "image/png", _meta: { private: true } },
56 { type: "text", text: "Screenshot captured" },
57 ] as const;
58 const result = { content, structuredContent: { count: 2 }, _meta: { private: true } };
59 const bridge = await loadMcpBridge({ modern: true, result });
60 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot")!;
61 const output = await tool.execute("snapshot", {});
62 assert.deepEqual(output.content, [
63 content[0],
64 { type: "image", data: "AAAA", mimeType: "image/png" },
65 content[2],
66 ]);
67 assert.deepEqual(output.structuredContent, { content, structuredContent: { count: 2 } });
68 assert.deepEqual(tool.outputSchema, {
69 type: "object",
70 properties: {
71 content: { type: "array", items: { type: "object" } },
72 structuredContent: { type: "object", properties: { count: { type: "number" } } },
73 isError: { type: "boolean" },
74 _meta: { type: "object" },
75 },
76 required: ["content"],
77 });
78 });
79
80 it.each([false, true])(
81 "preserves image-only results and error status, isError=%s",
82 async (isError) => {
83 const image = { type: "image", data: "AAAA", mimeType: "image/png" };
84 const result = { content: [image], isError };
85 const bridge = await loadMcpBridge({ result });
86 const output = await bridge.tools[0]!.execute("image", {});
87 assert.deepEqual(output.content[0], image);
88 assert.equal(output.content.length, isError ? 2 : 1);
89 if (isError) assert.include(output.content[1]?.text ?? "", "returned an error");
90 assert.equal(output.isError, isError ? true : undefined);
91 assert.deepEqual(output.structuredContent, result);
92 },
93 );
94
95 it("uses structured output as model text when content is empty", async () => {
96 const result = { content: [], structuredContent: { count: 2 } };
97 const bridge = await loadMcpBridge({ result });
98 const output = await bridge.tools[0]!.execute("structured", {});
99 assert.deepEqual(output.content, [{ type: "text", text: '{"count":2}' }]);
100 assert.deepEqual(output.structuredContent, result);
101 });
102
103 it("propagates cancellation without returning a successful result", async () => {
104 const bridge = await loadMcpBridge();
105 const controller = new AbortController();
106 controller.abort();
107 await expect(bridge.tools[0]!.execute("cancelled", {}, controller.signal)).rejects.toThrow(
108 "aborted",
109 );
110 });
111});
112
113describe("Pi MCP tool exposure", () => {
114 it("keeps orchestration direct and optional bridge tools discoverable on modern Pi", async () => {
115 const bridge = await loadMcpBridge({ modern: true, toolSearchAvailable: true });
116 await bridge.handlers.get("session_start")!(
117 { systemPrompt: "" },
118 { ui: { notify: () => undefined } },
119 );
120 const start = bridge.handlers.get("before_agent_start");
121 assert.isDefined(start);
122 const prompt = await start!(
123 { systemPrompt: "Pi system prompt" },
124 { ui: { notify: () => undefined } },
125 );
126 assert.include(prompt.systemPrompt, "orchestrator_capabilities");
127 assert.equal(bridge.servers.length, 0);
128 assert.equal(bridge.tools.length, 8);
129 assert.deepEqual(bridge.getActiveTools(), ["read", "tool_search"]);
130 assert.deepEqual(
131 bridge.tools
132 .filter((tool) => tool.exposure !== "hidden")
133 .map((tool) => [tool.name, tool.exposure]),
134 [
135 ["mcp__t3-code__orchestrator_capabilities", "direct"],
136 ["mcp__t3-code__delegate_task", "direct"],
137 ["mcp__t3-code__task_status", "direct"],
138 ["mcp__t3-code__preview_snapshot", "deferred"],
139 ],
140 );
141 assert.deepEqual(
142 bridge.tools.filter((tool) => tool.exposure === "hidden").map((tool) => tool.name),
143 [
144 "mcp__t3_code__orchestrator_capabilities",
145 "mcp__t3_code__delegate_task",
146 "mcp__t3_code__task_status",
147 "mcp__t3_code__preview_snapshot",
148 ],
149 );
150 const result = await bridge.tools
151 .find((tool) => tool.name === "mcp__t3-code__preview_snapshot")!
152 .execute("call-1", { depth: 2 });
153 assert.equal(result.content[0]?.text, "browser snapshot");
154 assert.equal(bridge.requests.at(-1)?.method, "tools/call");
155 });
156
157 it.each(["legacy Pi", "disabled tool search"])(
158 "keeps tool execution available with %s",
159 async (mode) => {
160 const bridge = await loadMcpBridge({
161 modern: mode !== "legacy Pi",
162 toolSearchAvailable: mode === "disabled tool search",
163 toolSearchDisabled: mode === "disabled tool search",
164 });
165 if (mode !== "legacy Pi") {
166 const start = bridge.handlers.get("session_start");
167 await start!({ systemPrompt: "Pi system prompt" }, { ui: { notify: () => undefined } });
168 }
169 assert.equal(bridge.tools.filter((tool) => tool.exposure !== "hidden").length, 4);
170 assert.isTrue(
171 bridge.tools
172 .filter((tool) => tool.exposure !== "hidden")
173 .every((tool) => tool.exposure === undefined || tool.exposure === "direct"),
174 );
175 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot");
176 assert.isDefined(tool);
177 const controller = new AbortController();
178 const result = await tool!.execute("call-1", { depth: 2 }, controller.signal);
179 assert.equal(result.content[0]?.text, "browser snapshot");
180 assert.strictEqual(bridge.transports.at(-1)?.signal, controller.signal);
181 assert.equal(bridge.transports.at(-1)?.url, "http://fixture.invalid/mcp");
182 assert.equal(bridge.transports.at(-1)?.authorization, "Bearer fixture-token");
183 assert.deepEqual(JSON.parse(JSON.stringify(bridge.requests.at(-1))), {
184 jsonrpc: "2.0",
185 id: 3,
186 method: "tools/call",
187 params: { name: "preview_snapshot", arguments: { depth: 2 } },
188 });
189 assert.isUndefined(tool?.promptSnippet);
190 assert.isUndefined(tool?.promptGuidelines);
191 },
192 );
193
194 it("preserves legacy wildcard tool selection", async () => {
195 const bridge = await loadMcpBridge({
196 modern: true,
197 toolSearchAvailable: true,
198 allowsTool: (name) =>
199 name === "read" || name === "tool_search" || name.startsWith("mcp__t3-code__"),
200 });
201 await bridge.handlers.get("session_start")!(
202 { systemPrompt: "" },
203 { ui: { notify: () => undefined } },
204 );
205 assert.equal(bridge.tools.length, 4);
206 assert.equal(bridge.tools.filter((tool) => tool.exposure === "direct").length, 3);
207 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot");
208 assert.isDefined(tool);
209 assert.equal((await tool!.execute("selected", {})).content[0]?.text, "browser snapshot");
210 });
211
212 it.each([false, true])(
213 "reconciles tree loadouts while honoring search exclusion: %s",
214 async (excludeSearch) => {
215 const bridge = await loadMcpBridge({
216 modern: true,
217 toolSearchAvailable: true,
218 allowsTool: (name) =>
219 name !== "mcp__t3-code__delegate_task" && (!excludeSearch || name !== "tool_search"),
220 });
221 await bridge.handlers.get("session_start")!(
222 { systemPrompt: "" },
223 { ui: { notify: () => undefined } },
224 );
225 bridge.restoreActiveTools([
226 "read",
227 "mcp__t3-code__task_status",
228 "mcp__t3-code__preview_snapshot",
229 ]);
230 const tree = bridge.handlers.get("session_tree");
231 assert.isDefined(tree);
232 await tree!({ systemPrompt: "" }, { ui: { notify: () => undefined } });
233 assert.deepEqual(bridge.getActiveTools(), [
234 "read",
235 "mcp__t3-code__task_status",
236 "mcp__t3-code__preview_snapshot",
237 ...(!excludeSearch ? ["tool_search"] : []),
238 ]);
239 assert.isFalse(
240 bridge.tools.some(
241 (tool) => tool.exposure !== "hidden" && tool.name.endsWith("__delegate_task"),
242 ),
243 );
244 },
245 );
246});
247
248describe("Pi tool discovery permissions", () => {
249 it("allows discovery without confirmation and still gates the discovered tool", async () => {
250 type ToolCallHook = (
251 event: { toolName: string; input: unknown },
252 ctx: { ui: { confirm: (title: string, detail: string) => Promise<boolean> } },
253 ) => Promise<{ block: true; reason: string } | undefined>;
254 let toolCall: ToolCallHook | undefined;
255 let searchPath = "builtin:tool-search";
256 const source = NodeModule.stripTypeScriptTypes(
257 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
258 "export default async function",
259 "async function",
260 ),
261 );
262 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
263 process: { env: { T3_PI_RUNTIME_MODE: "approval-required" } },
264 pi: {
265 on: (name: string, handler: ToolCallHook) => {
266 if (name === "tool_call") toolCall = handler;
267 },
268 getAllTools: () => [{ name: "tool_search", sourceInfo: { path: searchPath } }],
269 },
270 });
271 assert.isDefined(toolCall);
272 const confirmations: string[] = [];
273 const ctx = {
274 ui: {
275 confirm: async (title: string) => {
276 confirmations.push(title);
277 return false;
278 },
279 },
280 };
281 assert.isUndefined(
282 await toolCall!({ toolName: "tool_search", input: { query: "preview_snapshot" } }, ctx),
283 );
284 assert.equal(confirmations.length, 0);
285 const result = await toolCall!({ toolName: "mcp__t3-code__preview_snapshot", input: {} }, ctx);
286 assert.equal(result?.block, true);
287 assert.deepEqual(confirmations, ["Allow mcp__t3-code__preview_snapshot?"]);
288
289 // An extension that replaces the search builtin is not known to be read-only.
290 searchPath = "/extensions/custom-search.ts";
291 const replaced = await toolCall!({ toolName: "tool_search", input: {} }, ctx);
292 assert.equal(replaced?.block, true);
293 assert.equal(confirmations.at(-1), "Allow tool_search?");
294 });
295});
296
297async function loadRequestHook(): Promise<RequestHook> {
298 const handlers = new Map<string, RequestHook>();
299 // Execute the shipped extension with MCP disabled; this path needs no Typebox.
300 const source = NodeModule.stripTypeScriptTypes(
301 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
302 "export default async function",
303 "async function",
304 ),
305 );
306 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
307 process: { env: {} },
308 pi: { on: (name: string, handler: RequestHook) => handlers.set(name, handler) },
309 });
310 const hook = handlers.get("before_provider_request");
311 assert.isDefined(hook);
312 return hook!;
313}
314
315describe("Pi upstream output-budget workaround", () => {
316 it.each(["max_tokens", "max_completion_tokens"])(
317 "caps %s without changing the conversation or tools",
318 async (key) => {
319 const hook = await loadRequestHook();
320 const payload = {
321 model: "moonshotai/kimi-k2.6",
322 messages: [{ role: "user", content: "hello" }],
323 tools: [{ type: "function", function: { name: "read" } }],
324 [key]: 231_969,
325 };
326 const result = hook({ payload }, { model: { provider: "openrouter" } });
327 assert.equal(result?.[key], 32_768);
328 assert.strictEqual(result?.messages, payload.messages);
329 assert.strictEqual(result?.tools, payload.tools);
330 assert.equal(result?.model, payload.model);
331 assert.equal(payload[key], 231_969);
332 },
333 );
334
335 it("preserves smaller budgets and other providers' payloads", async () => {
336 const hook = await loadRequestHook();
337 for (const payload of [{ max_tokens: 8192 }, { max_completion_tokens: 32_768 }, {}, null]) {
338 assert.isUndefined(hook({ payload }, { model: { provider: "openrouter" } }));
339 }
340 assert.isUndefined(
341 hook({ payload: { max_tokens: 231_969 } }, { model: { provider: "anthropic" } }),
342 );
343 });
344});
345
346async function loadInputHook(commands: ReadonlyArray<SkillCommand>) {
347 const handlers = await loadHooks(commands);
348 const hook = handlers.get("input");
349 assert.isDefined(hook);
350 return hook as InputHook;
351}
352
353describe("Pi skill references", () => {
354 it("loads every selected skill once while preserving inline prose, whitespace, and images", async () => {
355 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
356 try {
357 const alpha = NodePath.join(directory, "alpha.md");
358 const beta = NodePath.join(directory, "beta.md");
359 await NodeFSP.writeFile(alpha, "ALPHA_INSTRUCTIONS");
360 await NodeFSP.writeFile(beta, "BETA_INSTRUCTIONS");
361 const hook = await loadInputHook([
362 { name: "skill:alpha", source: "skill", sourceInfo: { path: alpha } },
363 { name: "skill:beta", source: "skill", sourceInfo: { path: beta } },
364 ]);
365 const text =
366 "Please use the $alpha philosophy, then $beta and $alpha\n```ts\n const x = 1;\n```";
367 const images = [{ type: "image", data: "fixture" }];
368 const result = await hook({ text, images }, { ui: { notify: assert.fail } });
369 assert.equal(result?.action, "transform");
370 assert.isTrue(result?.text.startsWith(text + "\n\n"));
371 assert.equal(result?.text.split("ALPHA_INSTRUCTIONS").length, 2);
372 assert.equal(result?.text.split("BETA_INSTRUCTIONS").length, 2);
373 assert.include(result?.text ?? "", `References are relative to ${directory}.`);
374 assert.strictEqual(result?.images, images);
375 } finally {
376 await NodeFSP.rm(directory, { recursive: true });
377 }
378 });
379
380 it("leaves unknown references and native skill commands for Pi", async () => {
381 const hook = await loadInputHook([
382 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
383 ]);
384 // Punctuation-adjacent references are plain text in the composer, not selected chips.
385 for (const text of [
386 "Explain $HOME",
387 "/skill:alpha use $alpha",
388 "Hello",
389 "$missing",
390 "Use $alpha, then continue",
391 "Use ($alpha)",
392 ]) {
393 assert.isUndefined(await hook({ text }, { ui: { notify: assert.fail } }));
394 }
395 });
396
397 it("loads additional chips without duplicating a leading native skill", async () => {
398 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
399 try {
400 const path = NodePath.join(directory, "beta.md");
401 await NodeFSP.writeFile(path, "BETA_INSTRUCTIONS");
402 const hook = await loadInputHook([
403 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
404 { name: "skill:beta", source: "skill", sourceInfo: { path } },
405 ]);
406 const text = "/skill:alpha use $alpha and $beta";
407 const result = await hook({ text }, { ui: { notify: assert.fail } });
408 assert.isTrue(result?.text.startsWith(text + "\n\n"));
409 assert.notInclude(result?.text ?? "", '<skill name="alpha"');
410 assert.include(result?.text ?? "", "BETA_INSTRUCTIONS");
411 } finally {
412 await NodeFSP.rm(directory, { recursive: true });
413 }
414 });
415
416 it("reports an unreadable skill without deleting its reference or other selected instructions", async () => {
417 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
418 try {
419 const path = NodePath.join(directory, "readable.md");
420 await NodeFSP.writeFile(path, "READABLE_INSTRUCTIONS");
421 const hook = await loadInputHook([
422 {
423 name: "skill:missing",
424 source: "skill",
425 sourceInfo: { path: NodePath.join(directory, "missing.md") },
426 },
427 { name: "skill:readable", source: "skill", sourceInfo: { path } },
428 ]);
429 const notices: string[] = [];
430 const text = "Use $missing and $readable";
431 const result = await hook(
432 { text },
433 {
434 ui: {
435 notify: (message) => {
436 notices.push(message);
437 },
438 },
439 },
440 );
441 assert.isTrue(result?.text.startsWith(text + "\n\n"));
442 assert.include(result?.text ?? "", "READABLE_INSTRUCTIONS");
443 assert.equal(notices.length, 1);
444 assert.include(notices[0] ?? "", "Could not load skill missing");
445 } finally {
446 await NodeFSP.rm(directory, { recursive: true });
447 }
448 });
449});