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 const source = NodeModule.stripTypeScriptTypes(
31 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
32 "export default async function",
33 "async function",
34 ),
35 );
36 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
37 process: { env: {} },
38 NodeFSP,
39 NodePath,
40 stripFrontmatter: (content: string) => content,
41 pi: {
42 on: (name: string, handler: unknown) => handlers.set(name, handler),
43 getCommands: () => commands,
44 },
45 });
46 return handlers;
47}
48
49describe("Pi MCP tool results", () => {
50 it("returns mixed screenshot blocks and typed script output without repeating structured text", async () => {
51 const content = [
52 { type: "text", text: "Browser screenshot" },
53 { type: "image", data: "AAAA", mimeType: "image/png", _meta: { private: true } },
54 { type: "text", text: "Screenshot captured" },
55 ] as const;
56 const result = { content, structuredContent: { count: 2 }, _meta: { private: true } };
57 const bridge = await loadMcpBridge({ modern: true, result });
58 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot")!;
59 const output = await tool.execute("snapshot", {});
60 assert.deepEqual(output.content, [
61 content[0],
62 { type: "image", data: "AAAA", mimeType: "image/png" },
63 content[2],
64 ]);
65 assert.deepEqual(output.structuredContent, { content, structuredContent: { count: 2 } });
66 assert.deepEqual(tool.outputSchema, {
67 type: "object",
68 properties: {
69 content: { type: "array", items: { type: "object" } },
70 structuredContent: { type: "object", properties: { count: { type: "number" } } },
71 isError: { type: "boolean" },
72 _meta: { type: "object" },
73 },
74 required: ["content"],
75 });
76 });
77
78 it.each([false, true])(
79 "preserves image-only results and error status, isError=%s",
80 async (isError) => {
81 const image = { type: "image", data: "AAAA", mimeType: "image/png" };
82 const result = { content: [image], isError };
83 const bridge = await loadMcpBridge({ result });
84 const output = await bridge.tools[0]!.execute("image", {});
85 assert.deepEqual(output.content[0], image);
86 assert.equal(output.content.length, isError ? 2 : 1);
87 if (isError) assert.include(output.content[1]?.text ?? "", "returned an error");
88 assert.equal(output.isError, isError ? true : undefined);
89 assert.deepEqual(output.structuredContent, result);
90 },
91 );
92
93 it("uses structured output as model text when content is empty", async () => {
94 const result = { content: [], structuredContent: { count: 2 } };
95 const bridge = await loadMcpBridge({ result });
96 const output = await bridge.tools[0]!.execute("structured", {});
97 assert.deepEqual(output.content, [{ type: "text", text: '{"count":2}' }]);
98 assert.deepEqual(output.structuredContent, result);
99 });
100
101 it("propagates cancellation without returning a successful result", async () => {
102 const bridge = await loadMcpBridge();
103 const controller = new AbortController();
104 controller.abort();
105 await expect(bridge.tools[0]!.execute("cancelled", {}, controller.signal)).rejects.toThrow(
106 "aborted",
107 );
108 });
109});
110
111describe("Pi MCP tool exposure", () => {
112 const discoveryContext = {
113 model: { api: "anthropic-messages" },
114 ui: { notify: () => undefined },
115 };
116
117 it.each(["session_start", "session_tree", "model_select", "before_agent_start"])(
118 "declares optional T3 tools for OpenAI-compatible gateways at %s",
119 async (hookName) => {
120 const bridge = await loadMcpBridge({ modern: true, toolSearchAvailable: true });
121 const hook = bridge.handlers.get(hookName);
122 assert.isDefined(hook);
123 await hook!(
124 { systemPrompt: "Pi system prompt" },
125 { model: { api: "openai-completions" }, ui: { notify: assert.fail } },
126 );
127 assert.isTrue(
128 bridge.tools
129 .filter((tool) => tool.name.startsWith("mcp__t3-code__"))
130 .every((tool) => bridge.getActiveTools().includes(tool.name)),
131 );
132 const result = await bridge.tools
133 .find((tool) => tool.name === "mcp__t3-code__preview_snapshot")!
134 .execute("gateway-call", {});
135 assert.equal(result.content[0]?.text, "browser snapshot");
136 assert.equal(bridge.tools.filter((tool) => tool.exposure === "hidden").length, 4);
137 },
138 );
139
140 it("keeps orchestration direct and optional bridge tools discoverable on modern Pi", async () => {
141 const bridge = await loadMcpBridge({ modern: true, toolSearchAvailable: true });
142 await bridge.handlers.get("session_start")!({ systemPrompt: "" }, discoveryContext);
143 const start = bridge.handlers.get("before_agent_start");
144 assert.isDefined(start);
145 const prompt = await start!({ systemPrompt: "Pi system prompt" }, discoveryContext);
146 assert.include(prompt.systemPrompt, "orchestrator_capabilities");
147 assert.equal(bridge.servers.length, 0);
148 assert.equal(bridge.tools.length, 8);
149 assert.deepEqual(bridge.getActiveTools(), ["read", "tool_search"]);
150 assert.deepEqual(
151 bridge.tools
152 .filter((tool) => tool.exposure !== "hidden")
153 .map((tool) => [tool.name, tool.exposure]),
154 [
155 ["mcp__t3-code__orchestrator_capabilities", "direct"],
156 ["mcp__t3-code__delegate_task", "direct"],
157 ["mcp__t3-code__task_status", "direct"],
158 ["mcp__t3-code__preview_snapshot", "deferred"],
159 ],
160 );
161 assert.deepEqual(
162 bridge.tools.filter((tool) => tool.exposure === "hidden").map((tool) => tool.name),
163 [
164 "mcp__t3_code__orchestrator_capabilities",
165 "mcp__t3_code__delegate_task",
166 "mcp__t3_code__task_status",
167 "mcp__t3_code__preview_snapshot",
168 ],
169 );
170 const result = await bridge.tools
171 .find((tool) => tool.name === "mcp__t3-code__preview_snapshot")!
172 .execute("call-1", { depth: 2 });
173 assert.equal(result.content[0]?.text, "browser snapshot");
174 assert.equal(bridge.requests.at(-1)?.method, "tools/call");
175 });
176
177 it("restores gateway declarations after model switches and older tree loadouts without excluded tools", async () => {
178 const bridge = await loadMcpBridge({
179 modern: true,
180 toolSearchAvailable: true,
181 allowsTool: (name) => name !== "mcp__t3-code__delegate_task",
182 });
183 const event = { systemPrompt: "" };
184 await bridge.handlers.get("session_start")!(event, discoveryContext);
185 const gatewayContext = { model: { api: "openai-completions" }, ui: { notify: assert.fail } };
186 await bridge.handlers.get("model_select")!(event, gatewayContext);
187 bridge.restoreActiveTools(["read", "mcp__t3-code__task_status"]);
188 await bridge.handlers.get("session_tree")!(event, gatewayContext);
189 assert.deepEqual(bridge.getActiveTools(), [
190 "read",
191 "mcp__t3-code__task_status",
192 "tool_search",
193 "mcp__t3-code__orchestrator_capabilities",
194 "mcp__t3-code__preview_snapshot",
195 ]);
196 await bridge.handlers.get("model_select")!(event, discoveryContext);
197 assert.equal(
198 bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot")?.exposure,
199 "deferred",
200 );
201 assert.include(bridge.getActiveTools(), "mcp__t3-code__preview_snapshot");
202 });
203
204 it.each(["legacy Pi", "disabled tool search"])(
205 "keeps tool execution available with %s",
206 async (mode) => {
207 const bridge = await loadMcpBridge({
208 modern: mode !== "legacy Pi",
209 toolSearchAvailable: mode === "disabled tool search",
210 toolSearchDisabled: mode === "disabled tool search",
211 });
212 if (mode !== "legacy Pi") {
213 const start = bridge.handlers.get("session_start");
214 await start!({ systemPrompt: "Pi system prompt" }, discoveryContext);
215 }
216 assert.equal(bridge.tools.filter((tool) => tool.exposure !== "hidden").length, 4);
217 assert.isTrue(
218 bridge.tools
219 .filter((tool) => tool.exposure !== "hidden")
220 .every((tool) => tool.exposure === undefined || tool.exposure === "direct"),
221 );
222 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot");
223 assert.isDefined(tool);
224 const controller = new AbortController();
225 const result = await tool!.execute("call-1", { depth: 2 }, controller.signal);
226 assert.equal(result.content[0]?.text, "browser snapshot");
227 assert.strictEqual(bridge.transports.at(-1)?.signal, controller.signal);
228 assert.equal(bridge.transports.at(-1)?.url, "http://fixture.invalid/mcp");
229 assert.equal(bridge.transports.at(-1)?.authorization, "Bearer fixture-token");
230 assert.deepEqual(JSON.parse(JSON.stringify(bridge.requests.at(-1))), {
231 jsonrpc: "2.0",
232 id: 3,
233 method: "tools/call",
234 params: { name: "preview_snapshot", arguments: { depth: 2 } },
235 });
236 assert.isUndefined(tool?.promptSnippet);
237 assert.isUndefined(tool?.promptGuidelines);
238 },
239 );
240
241 it("preserves legacy wildcard tool selection", async () => {
242 const bridge = await loadMcpBridge({
243 modern: true,
244 toolSearchAvailable: true,
245 allowsTool: (name) =>
246 name === "read" || name === "tool_search" || name.startsWith("mcp__t3-code__"),
247 });
248 await bridge.handlers.get("session_start")!({ systemPrompt: "" }, discoveryContext);
249 assert.equal(bridge.tools.length, 4);
250 assert.equal(bridge.tools.filter((tool) => tool.exposure === "direct").length, 3);
251 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot");
252 assert.isDefined(tool);
253 assert.equal((await tool!.execute("selected", {})).content[0]?.text, "browser snapshot");
254 });
255
256 it.each([false, true])(
257 "reconciles tree loadouts while honoring search exclusion: %s",
258 async (excludeSearch) => {
259 const bridge = await loadMcpBridge({
260 modern: true,
261 toolSearchAvailable: true,
262 allowsTool: (name) =>
263 name !== "mcp__t3-code__delegate_task" && (!excludeSearch || name !== "tool_search"),
264 });
265 await bridge.handlers.get("session_start")!({ systemPrompt: "" }, discoveryContext);
266 bridge.restoreActiveTools([
267 "read",
268 "mcp__t3-code__task_status",
269 "mcp__t3-code__preview_snapshot",
270 ]);
271 const tree = bridge.handlers.get("session_tree");
272 assert.isDefined(tree);
273 await tree!({ systemPrompt: "" }, discoveryContext);
274 assert.deepEqual(bridge.getActiveTools(), [
275 "read",
276 "mcp__t3-code__task_status",
277 "mcp__t3-code__preview_snapshot",
278 ...(!excludeSearch ? ["tool_search"] : []),
279 ]);
280 assert.isFalse(
281 bridge.tools.some(
282 (tool) => tool.exposure !== "hidden" && tool.name.endsWith("__delegate_task"),
283 ),
284 );
285 },
286 );
287});
288
289describe("Pi tool discovery permissions", () => {
290 it.each(["approval-required", "auto-accept-edits", "auto"])(
291 "allows annotated T3 reads in %s while gating mutations and replacements",
292 async (runtimeMode) => {
293 const bridge = await loadMcpBridge({ modern: true, runtimeMode });
294 const hook = bridge.handlers.get("tool_call") as unknown as (
295 event: { toolName: string; input: unknown },
296 ctx: { ui: { confirm: (title: string) => Promise<boolean> } },
297 ) => Promise<{ block: true; reason: string } | undefined>;
298 const confirmations: string[] = [];
299 const ctx = {
300 ui: {
301 confirm: async (title: string) => {
302 confirmations.push(title);
303 return false;
304 },
305 },
306 };
307 for (const prefix of ["mcp__t3-code__", "mcp__t3_code__"]) {
308 assert.isUndefined(
309 await hook({ toolName: prefix + "orchestrator_capabilities", input: {} }, ctx),
310 );
311 assert.equal(
312 (await hook({ toolName: prefix + "delegate_task", input: {} }, ctx))?.block,
313 true,
314 );
315 assert.equal(
316 (await hook({ toolName: prefix + "task_status", input: {} }, ctx))?.block,
317 true,
318 );
319 }
320 assert.equal(confirmations.length, 4);
321 bridge.setBridgeSourcePath("/user/extensions/replacement.ts");
322 assert.equal(
323 (await hook({ toolName: "mcp__t3-code__orchestrator_capabilities", input: {} }, ctx))
324 ?.block,
325 true,
326 );
327 assert.equal(
328 (await hook({ toolName: "mcp__other__orchestrator_capabilities", input: {} }, ctx))?.block,
329 true,
330 );
331 assert.equal(confirmations.length, 6);
332 },
333 );
334
335 it("allows discovery without confirmation and still gates the discovered tool", async () => {
336 type ToolCallHook = (
337 event: { toolName: string; input: unknown },
338 ctx: {
339 signal: AbortSignal;
340 ui: {
341 confirm: (
342 title: string,
343 detail: string,
344 options: { signal: AbortSignal },
345 ) => Promise<boolean>;
346 };
347 },
348 ) => Promise<{ block: true; reason: string } | undefined>;
349 let toolCall: ToolCallHook | undefined;
350 let searchPath = "builtin:tool-search";
351 const source = NodeModule.stripTypeScriptTypes(
352 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
353 "export default async function",
354 "async function",
355 ),
356 );
357 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
358 process: { env: { T3_PI_RUNTIME_MODE: "approval-required" } },
359 pi: {
360 on: (name: string, handler: ToolCallHook) => {
361 if (name === "tool_call") toolCall = handler;
362 },
363 getAllTools: () => [{ name: "tool_search", sourceInfo: { path: searchPath } }],
364 },
365 });
366 assert.isDefined(toolCall);
367 const confirmations: string[] = [];
368 const controller = new AbortController();
369 const ctx = {
370 signal: controller.signal,
371 ui: {
372 confirm: async (title: string, _detail: string, options: { signal: AbortSignal }) => {
373 assert.strictEqual(options.signal, controller.signal);
374 confirmations.push(title);
375 return false;
376 },
377 },
378 };
379 assert.isUndefined(
380 await toolCall!({ toolName: "tool_search", input: { query: "preview_snapshot" } }, ctx),
381 );
382 assert.equal(confirmations.length, 0);
383 const result = await toolCall!({ toolName: "mcp__t3-code__preview_snapshot", input: {} }, ctx);
384 assert.equal(result?.block, true);
385 assert.deepEqual(confirmations, ["Allow mcp__t3-code__preview_snapshot?"]);
386
387 searchPath = "/extensions/custom-search.ts";
388 const replaced = await toolCall!({ toolName: "tool_search", input: {} }, ctx);
389 assert.equal(replaced?.block, true);
390 assert.equal(confirmations.at(-1), "Allow tool_search?");
391 });
392});
393
394async function loadRequestHook(): Promise<RequestHook> {
395 const handlers = new Map<string, RequestHook>();
396 const source = NodeModule.stripTypeScriptTypes(
397 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
398 "export default async function",
399 "async function",
400 ),
401 );
402 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
403 process: { env: {} },
404 pi: { on: (name: string, handler: RequestHook) => handlers.set(name, handler) },
405 });
406 const hook = handlers.get("before_provider_request");
407 assert.isDefined(hook);
408 return hook!;
409}
410
411describe("Pi upstream output-budget workaround", () => {
412 it.each(["max_tokens", "max_completion_tokens"])(
413 "caps %s without changing the conversation or tools",
414 async (key) => {
415 const hook = await loadRequestHook();
416 const payload = {
417 model: "moonshotai/kimi-k2.6",
418 messages: [{ role: "user", content: "hello" }],
419 tools: [{ type: "function", function: { name: "read" } }],
420 [key]: 231_969,
421 };
422 const result = hook({ payload }, { model: { provider: "openrouter" } });
423 assert.equal(result?.[key], 32_768);
424 assert.strictEqual(result?.messages, payload.messages);
425 assert.strictEqual(result?.tools, payload.tools);
426 assert.equal(result?.model, payload.model);
427 assert.equal(payload[key], 231_969);
428 },
429 );
430
431 it("preserves smaller budgets and other providers' payloads", async () => {
432 const hook = await loadRequestHook();
433 for (const payload of [{ max_tokens: 8192 }, { max_completion_tokens: 32_768 }, {}, null]) {
434 assert.isUndefined(hook({ payload }, { model: { provider: "openrouter" } }));
435 }
436 assert.isUndefined(
437 hook({ payload: { max_tokens: 231_969 } }, { model: { provider: "anthropic" } }),
438 );
439 });
440});
441
442async function loadInputHook(commands: ReadonlyArray<SkillCommand>) {
443 const handlers = await loadHooks(commands);
444 const hook = handlers.get("input");
445 assert.isDefined(hook);
446 return hook as InputHook;
447}
448
449describe("Pi skill references", () => {
450 it("loads every selected skill once while preserving inline prose, whitespace, and images", async () => {
451 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
452 try {
453 const alpha = NodePath.join(directory, "alpha.md");
454 const beta = NodePath.join(directory, "beta.md");
455 await NodeFSP.writeFile(alpha, "ALPHA_INSTRUCTIONS");
456 await NodeFSP.writeFile(beta, "BETA_INSTRUCTIONS");
457 const hook = await loadInputHook([
458 { name: "skill:alpha", source: "skill", sourceInfo: { path: alpha } },
459 { name: "skill:beta", source: "skill", sourceInfo: { path: beta } },
460 ]);
461 const text =
462 "Please use the $alpha philosophy, then $beta and $alpha\n```ts\n const x = 1;\n```";
463 const images = [{ type: "image", data: "fixture" }];
464 const result = await hook({ text, images }, { ui: { notify: assert.fail } });
465 assert.equal(result?.action, "transform");
466 assert.isTrue(result?.text.startsWith(text + "\n\n"));
467 assert.equal(result?.text.split("ALPHA_INSTRUCTIONS").length, 2);
468 assert.equal(result?.text.split("BETA_INSTRUCTIONS").length, 2);
469 assert.include(result?.text ?? "", `References are relative to ${directory}.`);
470 assert.strictEqual(result?.images, images);
471 } finally {
472 await NodeFSP.rm(directory, { recursive: true });
473 }
474 });
475
476 it("leaves unknown references and native skill commands for Pi", async () => {
477 const hook = await loadInputHook([
478 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
479 ]);
480 for (const text of [
481 "Explain $HOME",
482 "/skill:alpha use $alpha",
483 "Hello",
484 "$missing",
485 "Use $alpha, then continue",
486 "Use ($alpha)",
487 ]) {
488 assert.isUndefined(await hook({ text }, { ui: { notify: assert.fail } }));
489 }
490 });
491
492 it("loads additional chips without duplicating a leading native skill", async () => {
493 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
494 try {
495 const path = NodePath.join(directory, "beta.md");
496 await NodeFSP.writeFile(path, "BETA_INSTRUCTIONS");
497 const hook = await loadInputHook([
498 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
499 { name: "skill:beta", source: "skill", sourceInfo: { path } },
500 ]);
501 const text = "/skill:alpha use $alpha and $beta";
502 const result = await hook({ text }, { ui: { notify: assert.fail } });
503 assert.isTrue(result?.text.startsWith(text + "\n\n"));
504 assert.notInclude(result?.text ?? "", '<skill name="alpha"');
505 assert.include(result?.text ?? "", "BETA_INSTRUCTIONS");
506 } finally {
507 await NodeFSP.rm(directory, { recursive: true });
508 }
509 });
510
511 it("reports an unreadable skill without deleting its reference or other selected instructions", async () => {
512 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
513 try {
514 const path = NodePath.join(directory, "readable.md");
515 await NodeFSP.writeFile(path, "READABLE_INSTRUCTIONS");
516 const hook = await loadInputHook([
517 {
518 name: "skill:missing",
519 source: "skill",
520 sourceInfo: { path: NodePath.join(directory, "missing.md") },
521 },
522 { name: "skill:readable", source: "skill", sourceInfo: { path } },
523 ]);
524 const notices: string[] = [];
525 const text = "Use $missing and $readable";
526 const result = await hook(
527 { text },
528 {
529 ui: {
530 notify: (message) => {
531 notices.push(message);
532 },
533 },
534 },
535 );
536 assert.isTrue(result?.text.startsWith(text + "\n\n"));
537 assert.include(result?.text ?? "", "READABLE_INSTRUCTIONS");
538 assert.equal(notices.length, 1);
539 assert.include(notices[0] ?? "", "Could not load skill missing");
540 } finally {
541 await NodeFSP.rm(directory, { recursive: true });
542 }
543 });
544});