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.each(["approval-required", "auto-accept-edits", "auto"])(
250 "allows annotated T3 reads in %s while gating mutations and replacements",
251 async (runtimeMode) => {
252 const bridge = await loadMcpBridge({ modern: true, runtimeMode });
253 const hook = bridge.handlers.get("tool_call") as unknown as (
254 event: { toolName: string; input: unknown },
255 ctx: { ui: { confirm: (title: string) => Promise<boolean> } },
256 ) => Promise<{ block: true; reason: string } | undefined>;
257 const confirmations: string[] = [];
258 const ctx = {
259 ui: {
260 confirm: async (title: string) => {
261 confirmations.push(title);
262 return false;
263 },
264 },
265 };
266 for (const prefix of ["mcp__t3-code__", "mcp__t3_code__"]) {
267 assert.isUndefined(
268 await hook({ toolName: prefix + "orchestrator_capabilities", input: {} }, ctx),
269 );
270 assert.equal(
271 (await hook({ toolName: prefix + "delegate_task", input: {} }, ctx))?.block,
272 true,
273 );
274 // task_status acknowledges result delivery, and is intentionally not read-only.
275 assert.equal(
276 (await hook({ toolName: prefix + "task_status", input: {} }, ctx))?.block,
277 true,
278 );
279 }
280 assert.equal(confirmations.length, 4);
281 bridge.setBridgeSourcePath("/user/extensions/replacement.ts");
282 assert.equal(
283 (await hook({ toolName: "mcp__t3-code__orchestrator_capabilities", input: {} }, ctx))
284 ?.block,
285 true,
286 );
287 assert.equal(
288 (await hook({ toolName: "mcp__other__orchestrator_capabilities", input: {} }, ctx))?.block,
289 true,
290 );
291 assert.equal(confirmations.length, 6);
292 },
293 );
294
295 it("allows discovery without confirmation and still gates the discovered tool", async () => {
296 type ToolCallHook = (
297 event: { toolName: string; input: unknown },
298 ctx: {
299 signal: AbortSignal;
300 ui: {
301 confirm: (
302 title: string,
303 detail: string,
304 options: { signal: AbortSignal },
305 ) => Promise<boolean>;
306 };
307 },
308 ) => Promise<{ block: true; reason: string } | undefined>;
309 let toolCall: ToolCallHook | undefined;
310 let searchPath = "builtin:tool-search";
311 const source = NodeModule.stripTypeScriptTypes(
312 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
313 "export default async function",
314 "async function",
315 ),
316 );
317 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
318 process: { env: { T3_PI_RUNTIME_MODE: "approval-required" } },
319 pi: {
320 on: (name: string, handler: ToolCallHook) => {
321 if (name === "tool_call") toolCall = handler;
322 },
323 getAllTools: () => [{ name: "tool_search", sourceInfo: { path: searchPath } }],
324 },
325 });
326 assert.isDefined(toolCall);
327 const confirmations: string[] = [];
328 const controller = new AbortController();
329 const ctx = {
330 signal: controller.signal,
331 ui: {
332 confirm: async (title: string, _detail: string, options: { signal: AbortSignal }) => {
333 assert.strictEqual(options.signal, controller.signal);
334 confirmations.push(title);
335 return false;
336 },
337 },
338 };
339 assert.isUndefined(
340 await toolCall!({ toolName: "tool_search", input: { query: "preview_snapshot" } }, ctx),
341 );
342 assert.equal(confirmations.length, 0);
343 const result = await toolCall!({ toolName: "mcp__t3-code__preview_snapshot", input: {} }, ctx);
344 assert.equal(result?.block, true);
345 assert.deepEqual(confirmations, ["Allow mcp__t3-code__preview_snapshot?"]);
346
347 // An extension that replaces the search builtin is not known to be read-only.
348 searchPath = "/extensions/custom-search.ts";
349 const replaced = await toolCall!({ toolName: "tool_search", input: {} }, ctx);
350 assert.equal(replaced?.block, true);
351 assert.equal(confirmations.at(-1), "Allow tool_search?");
352 });
353});
354
355async function loadRequestHook(): Promise<RequestHook> {
356 const handlers = new Map<string, RequestHook>();
357 // Execute the shipped extension with MCP disabled; this path needs no Typebox.
358 const source = NodeModule.stripTypeScriptTypes(
359 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
360 "export default async function",
361 "async function",
362 ),
363 );
364 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
365 process: { env: {} },
366 pi: { on: (name: string, handler: RequestHook) => handlers.set(name, handler) },
367 });
368 const hook = handlers.get("before_provider_request");
369 assert.isDefined(hook);
370 return hook!;
371}
372
373describe("Pi upstream output-budget workaround", () => {
374 it.each(["max_tokens", "max_completion_tokens"])(
375 "caps %s without changing the conversation or tools",
376 async (key) => {
377 const hook = await loadRequestHook();
378 const payload = {
379 model: "moonshotai/kimi-k2.6",
380 messages: [{ role: "user", content: "hello" }],
381 tools: [{ type: "function", function: { name: "read" } }],
382 [key]: 231_969,
383 };
384 const result = hook({ payload }, { model: { provider: "openrouter" } });
385 assert.equal(result?.[key], 32_768);
386 assert.strictEqual(result?.messages, payload.messages);
387 assert.strictEqual(result?.tools, payload.tools);
388 assert.equal(result?.model, payload.model);
389 assert.equal(payload[key], 231_969);
390 },
391 );
392
393 it("preserves smaller budgets and other providers' payloads", async () => {
394 const hook = await loadRequestHook();
395 for (const payload of [{ max_tokens: 8192 }, { max_completion_tokens: 32_768 }, {}, null]) {
396 assert.isUndefined(hook({ payload }, { model: { provider: "openrouter" } }));
397 }
398 assert.isUndefined(
399 hook({ payload: { max_tokens: 231_969 } }, { model: { provider: "anthropic" } }),
400 );
401 });
402});
403
404async function loadInputHook(commands: ReadonlyArray<SkillCommand>) {
405 const handlers = await loadHooks(commands);
406 const hook = handlers.get("input");
407 assert.isDefined(hook);
408 return hook as InputHook;
409}
410
411describe("Pi skill references", () => {
412 it("loads every selected skill once while preserving inline prose, whitespace, and images", async () => {
413 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
414 try {
415 const alpha = NodePath.join(directory, "alpha.md");
416 const beta = NodePath.join(directory, "beta.md");
417 await NodeFSP.writeFile(alpha, "ALPHA_INSTRUCTIONS");
418 await NodeFSP.writeFile(beta, "BETA_INSTRUCTIONS");
419 const hook = await loadInputHook([
420 { name: "skill:alpha", source: "skill", sourceInfo: { path: alpha } },
421 { name: "skill:beta", source: "skill", sourceInfo: { path: beta } },
422 ]);
423 const text =
424 "Please use the $alpha philosophy, then $beta and $alpha\n```ts\n const x = 1;\n```";
425 const images = [{ type: "image", data: "fixture" }];
426 const result = await hook({ text, images }, { ui: { notify: assert.fail } });
427 assert.equal(result?.action, "transform");
428 assert.isTrue(result?.text.startsWith(text + "\n\n"));
429 assert.equal(result?.text.split("ALPHA_INSTRUCTIONS").length, 2);
430 assert.equal(result?.text.split("BETA_INSTRUCTIONS").length, 2);
431 assert.include(result?.text ?? "", `References are relative to ${directory}.`);
432 assert.strictEqual(result?.images, images);
433 } finally {
434 await NodeFSP.rm(directory, { recursive: true });
435 }
436 });
437
438 it("leaves unknown references and native skill commands for Pi", async () => {
439 const hook = await loadInputHook([
440 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
441 ]);
442 // Punctuation-adjacent references are plain text in the composer, not selected chips.
443 for (const text of [
444 "Explain $HOME",
445 "/skill:alpha use $alpha",
446 "Hello",
447 "$missing",
448 "Use $alpha, then continue",
449 "Use ($alpha)",
450 ]) {
451 assert.isUndefined(await hook({ text }, { ui: { notify: assert.fail } }));
452 }
453 });
454
455 it("loads additional chips without duplicating a leading native skill", async () => {
456 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
457 try {
458 const path = NodePath.join(directory, "beta.md");
459 await NodeFSP.writeFile(path, "BETA_INSTRUCTIONS");
460 const hook = await loadInputHook([
461 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
462 { name: "skill:beta", source: "skill", sourceInfo: { path } },
463 ]);
464 const text = "/skill:alpha use $alpha and $beta";
465 const result = await hook({ text }, { ui: { notify: assert.fail } });
466 assert.isTrue(result?.text.startsWith(text + "\n\n"));
467 assert.notInclude(result?.text ?? "", '<skill name="alpha"');
468 assert.include(result?.text ?? "", "BETA_INSTRUCTIONS");
469 } finally {
470 await NodeFSP.rm(directory, { recursive: true });
471 }
472 });
473
474 it("reports an unreadable skill without deleting its reference or other selected instructions", async () => {
475 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
476 try {
477 const path = NodePath.join(directory, "readable.md");
478 await NodeFSP.writeFile(path, "READABLE_INSTRUCTIONS");
479 const hook = await loadInputHook([
480 {
481 name: "skill:missing",
482 source: "skill",
483 sourceInfo: { path: NodePath.join(directory, "missing.md") },
484 },
485 { name: "skill:readable", source: "skill", sourceInfo: { path } },
486 ]);
487 const notices: string[] = [];
488 const text = "Use $missing and $readable";
489 const result = await hook(
490 { text },
491 {
492 ui: {
493 notify: (message) => {
494 notices.push(message);
495 },
496 },
497 },
498 );
499 assert.isTrue(result?.text.startsWith(text + "\n\n"));
500 assert.include(result?.text ?? "", "READABLE_INSTRUCTIONS");
501 assert.equal(notices.length, 1);
502 assert.include(notices[0] ?? "", "Could not load skill missing");
503 } finally {
504 await NodeFSP.rm(directory, { recursive: true });
505 }
506 });
507});