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, it } from "@effect/vitest";
8
9import { PI_T3_MCP_EXTENSION_SOURCE } from "./mcpExtensionSource.ts";
10
11type RequestHook = (
12 event: { payload: unknown },
13 ctx: { model: { provider: string } },
14) => Record<string, unknown> | undefined;
15
16interface SkillCommand {
17 readonly name: string;
18 readonly source: string;
19 readonly sourceInfo: { readonly path: string };
20}
21
22type InputHook = (
23 event: { text: string; images?: ReadonlyArray<unknown> },
24 ctx: { ui: { notify: (message: string, level: string) => void } },
25) => Promise<{ action: string; text: string; images?: ReadonlyArray<unknown> } | undefined>;
26
27async function loadHooks(commands: ReadonlyArray<SkillCommand> = []) {
28 const handlers = new Map<string, unknown>();
29 // Execute the shipped extension with MCP disabled; this path needs no Typebox.
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 // Frontmatter parsing belongs to Pi. These fixtures contain only skill bodies.
41 stripFrontmatter: (content: string) => content,
42 pi: {
43 on: (name: string, handler: unknown) => handlers.set(name, handler),
44 getCommands: () => commands,
45 },
46 });
47 return handlers;
48}
49
50interface RegisteredTool {
51 readonly name: string;
52 readonly description: string;
53 readonly parameters: unknown;
54 readonly exposure?: string;
55 readonly promptSnippet?: string;
56 readonly promptGuidelines?: ReadonlyArray<string>;
57 readonly execute: (
58 id: string,
59 args: Record<string, unknown>,
60 signal?: AbortSignal,
61 ) => Promise<{
62 readonly content: ReadonlyArray<{ readonly type: string; readonly text: string }>;
63 }>;
64}
65
66type AgentStartHook = (
67 event: { systemPrompt: string },
68 ctx: { ui: { notify: (message: string, severity: string) => void } },
69) => Promise<{ systemPrompt: string }>;
70
71async function loadMcpBridge(
72 options: {
73 readonly modern?: boolean;
74 readonly toolSearchAvailable?: boolean;
75 readonly toolSearchDisabled?: boolean;
76 readonly allowsTool?: (name: string) => boolean;
77 } = {},
78) {
79 const handlers = new Map<string, AgentStartHook>();
80 const tools: RegisteredTool[] = [];
81 const requests: Array<{ readonly method: string; readonly params?: unknown }> = [];
82 let activeTools = ["read"];
83 const transports: Array<{
84 readonly url: string;
85 readonly authorization: string;
86 readonly signal: AbortSignal | undefined;
87 }> = [];
88 const servers: Array<{ readonly name: string; readonly config: Record<string, unknown> }> = [];
89 const catalog = [
90 { name: "orchestrator_capabilities", description: "Discover available providers and models." },
91 { name: "delegate_task", description: "Delegate work to another agent." },
92 { name: "task_status", description: "Check delegated work." },
93 { name: "preview_snapshot", description: "Inspect the collaborative browser." },
94 ].map((tool) => ({ ...tool, inputSchema: { type: "object", properties: {} } }));
95 const source = NodeModule.stripTypeScriptTypes(
96 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
97 "export default async function",
98 "async function",
99 ),
100 );
101 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
102 process: {
103 env: { T3_MCP_URL: "http://fixture.invalid/mcp", T3_MCP_BEARER_TOKEN: "fixture-token" },
104 },
105 AbortSignal,
106 Type: { Unsafe: (schema: unknown) => schema },
107 fetch: async (
108 url: string,
109 options: { body: string; headers: Record<string, string>; signal?: AbortSignal },
110 ) => {
111 transports.push({
112 url,
113 authorization: options.headers.authorization!,
114 signal: options.signal,
115 });
116 const request = JSON.parse(options.body) as { id: number; method: string; params?: unknown };
117 requests.push(request);
118 const result =
119 request.method === "tools/list"
120 ? { tools: catalog }
121 : request.method === "tools/call"
122 ? { content: [{ type: "text", text: "browser snapshot" }] }
123 : {};
124 return new Response(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }), {
125 headers: { "content-type": "application/json" },
126 });
127 },
128 pi: {
129 on: (name: string, handler: AgentStartHook) => handlers.set(name, handler),
130 registerTool: (tool: RegisteredTool) => {
131 if (options.allowsTool && !options.allowsTool(tool.name)) return;
132 const index = tools.findIndex((current) => current.name === tool.name);
133 if (index === -1) tools.push(tool);
134 else tools[index] = tool;
135 },
136 getActiveTools: () => activeTools,
137 setActiveTools: (names: string[]) => {
138 activeTools = names.filter((name) => options.allowsTool?.(name) ?? true);
139 },
140 getAllTools: () =>
141 options.toolSearchAvailable &&
142 !options.toolSearchDisabled &&
143 (options.allowsTool?.("tool_search") ?? true)
144 ? [{ name: "tool_search", sourceInfo: { path: "builtin:tool-search" } }]
145 : [],
146 ...(options.modern
147 ? {
148 registerMcpServer: (name: string, config: Record<string, unknown>) =>
149 servers.push({ name, config }),
150 unregisterMcpServer: () => servers.splice(0),
151 }
152 : {}),
153 },
154 });
155 return {
156 handlers,
157 tools,
158 requests,
159 servers,
160 transports,
161 getActiveTools: () => activeTools,
162 restoreActiveTools: (names: string[]) => {
163 activeTools = names;
164 },
165 };
166}
167
168describe("Pi MCP tool exposure", () => {
169 it("keeps orchestration direct and optional bridge tools discoverable on modern Pi", async () => {
170 const bridge = await loadMcpBridge({ modern: true, toolSearchAvailable: true });
171 await bridge.handlers.get("session_start")!(
172 { systemPrompt: "" },
173 { ui: { notify: () => undefined } },
174 );
175 const start = bridge.handlers.get("before_agent_start");
176 assert.isDefined(start);
177 const prompt = await start!(
178 { systemPrompt: "Pi system prompt" },
179 { ui: { notify: () => undefined } },
180 );
181 assert.include(prompt.systemPrompt, "orchestrator_capabilities");
182 assert.equal(bridge.servers.length, 0);
183 assert.equal(bridge.tools.length, 8);
184 assert.deepEqual(bridge.getActiveTools(), ["read", "tool_search"]);
185 assert.deepEqual(
186 bridge.tools
187 .filter((tool) => tool.exposure !== "hidden")
188 .map((tool) => [tool.name, tool.exposure]),
189 [
190 ["mcp__t3-code__orchestrator_capabilities", "direct"],
191 ["mcp__t3-code__delegate_task", "direct"],
192 ["mcp__t3-code__task_status", "direct"],
193 ["mcp__t3-code__preview_snapshot", "deferred"],
194 ],
195 );
196 assert.deepEqual(
197 bridge.tools.filter((tool) => tool.exposure === "hidden").map((tool) => tool.name),
198 [
199 "mcp__t3_code__orchestrator_capabilities",
200 "mcp__t3_code__delegate_task",
201 "mcp__t3_code__task_status",
202 "mcp__t3_code__preview_snapshot",
203 ],
204 );
205 const result = await bridge.tools
206 .find((tool) => tool.name === "mcp__t3-code__preview_snapshot")!
207 .execute("call-1", { depth: 2 });
208 assert.equal(result.content[0]?.text, "browser snapshot");
209 assert.equal(bridge.requests.at(-1)?.method, "tools/call");
210 });
211
212 it.each(["legacy Pi", "disabled tool search"])(
213 "keeps tool execution available with %s",
214 async (mode) => {
215 const bridge = await loadMcpBridge({
216 modern: mode !== "legacy Pi",
217 toolSearchAvailable: mode === "disabled tool search",
218 toolSearchDisabled: mode === "disabled tool search",
219 });
220 if (mode !== "legacy Pi") {
221 const start = bridge.handlers.get("session_start");
222 await start!({ systemPrompt: "Pi system prompt" }, { ui: { notify: () => undefined } });
223 }
224 assert.equal(bridge.tools.filter((tool) => tool.exposure !== "hidden").length, 4);
225 assert.isTrue(
226 bridge.tools
227 .filter((tool) => tool.exposure !== "hidden")
228 .every((tool) => tool.exposure === undefined || tool.exposure === "direct"),
229 );
230 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot");
231 assert.isDefined(tool);
232 const controller = new AbortController();
233 const result = await tool!.execute("call-1", { depth: 2 }, controller.signal);
234 assert.equal(result.content[0]?.text, "browser snapshot");
235 assert.strictEqual(bridge.transports.at(-1)?.signal, controller.signal);
236 assert.equal(bridge.transports.at(-1)?.url, "http://fixture.invalid/mcp");
237 assert.equal(bridge.transports.at(-1)?.authorization, "Bearer fixture-token");
238 assert.deepEqual(JSON.parse(JSON.stringify(bridge.requests.at(-1))), {
239 jsonrpc: "2.0",
240 id: 3,
241 method: "tools/call",
242 params: { name: "preview_snapshot", arguments: { depth: 2 } },
243 });
244 assert.isUndefined(tool?.promptSnippet);
245 assert.isUndefined(tool?.promptGuidelines);
246 },
247 );
248
249 it("preserves legacy wildcard tool selection", async () => {
250 const bridge = await loadMcpBridge({
251 modern: true,
252 toolSearchAvailable: true,
253 allowsTool: (name) =>
254 name === "read" || name === "tool_search" || name.startsWith("mcp__t3-code__"),
255 });
256 await bridge.handlers.get("session_start")!(
257 { systemPrompt: "" },
258 { ui: { notify: () => undefined } },
259 );
260 assert.equal(bridge.tools.length, 4);
261 assert.equal(bridge.tools.filter((tool) => tool.exposure === "direct").length, 3);
262 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot");
263 assert.isDefined(tool);
264 assert.equal((await tool!.execute("selected", {})).content[0]?.text, "browser snapshot");
265 });
266
267 it.each([false, true])(
268 "reconciles tree loadouts while honoring search exclusion: %s",
269 async (excludeSearch) => {
270 const bridge = await loadMcpBridge({
271 modern: true,
272 toolSearchAvailable: true,
273 allowsTool: (name) =>
274 name !== "mcp__t3-code__delegate_task" && (!excludeSearch || name !== "tool_search"),
275 });
276 await bridge.handlers.get("session_start")!(
277 { systemPrompt: "" },
278 { ui: { notify: () => undefined } },
279 );
280 bridge.restoreActiveTools([
281 "read",
282 "mcp__t3-code__task_status",
283 "mcp__t3-code__preview_snapshot",
284 ]);
285 const tree = bridge.handlers.get("session_tree");
286 assert.isDefined(tree);
287 await tree!({ systemPrompt: "" }, { ui: { notify: () => undefined } });
288 assert.deepEqual(bridge.getActiveTools(), [
289 "read",
290 "mcp__t3-code__task_status",
291 "mcp__t3-code__preview_snapshot",
292 ...(!excludeSearch ? ["tool_search"] : []),
293 ]);
294 assert.isFalse(
295 bridge.tools.some(
296 (tool) => tool.exposure !== "hidden" && tool.name.endsWith("__delegate_task"),
297 ),
298 );
299 },
300 );
301});
302
303describe("Pi tool discovery permissions", () => {
304 it("allows discovery without confirmation and still gates the discovered tool", async () => {
305 type ToolCallHook = (
306 event: { toolName: string; input: unknown },
307 ctx: { ui: { confirm: (title: string, detail: string) => Promise<boolean> } },
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 ctx = {
329 ui: {
330 confirm: async (title: string) => {
331 confirmations.push(title);
332 return false;
333 },
334 },
335 };
336 assert.isUndefined(
337 await toolCall!({ toolName: "tool_search", input: { query: "preview_snapshot" } }, ctx),
338 );
339 assert.equal(confirmations.length, 0);
340 const result = await toolCall!({ toolName: "mcp__t3-code__preview_snapshot", input: {} }, ctx);
341 assert.equal(result?.block, true);
342 assert.deepEqual(confirmations, ["Allow mcp__t3-code__preview_snapshot?"]);
343
344 // An extension that replaces the search builtin is not known to be read-only.
345 searchPath = "/extensions/custom-search.ts";
346 const replaced = await toolCall!({ toolName: "tool_search", input: {} }, ctx);
347 assert.equal(replaced?.block, true);
348 assert.equal(confirmations.at(-1), "Allow tool_search?");
349 });
350});
351
352async function loadRequestHook(): Promise<RequestHook> {
353 const handlers = new Map<string, RequestHook>();
354 // Execute the shipped extension with MCP disabled; this path needs no Typebox.
355 const source = NodeModule.stripTypeScriptTypes(
356 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
357 "export default async function",
358 "async function",
359 ),
360 );
361 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
362 process: { env: {} },
363 pi: { on: (name: string, handler: RequestHook) => handlers.set(name, handler) },
364 });
365 const hook = handlers.get("before_provider_request");
366 assert.isDefined(hook);
367 return hook!;
368}
369
370describe("Pi upstream output-budget workaround", () => {
371 it.each(["max_tokens", "max_completion_tokens"])(
372 "caps %s without changing the conversation or tools",
373 async (key) => {
374 const hook = await loadRequestHook();
375 const payload = {
376 model: "moonshotai/kimi-k2.6",
377 messages: [{ role: "user", content: "hello" }],
378 tools: [{ type: "function", function: { name: "read" } }],
379 [key]: 231_969,
380 };
381 const result = hook({ payload }, { model: { provider: "openrouter" } });
382 assert.equal(result?.[key], 32_768);
383 assert.strictEqual(result?.messages, payload.messages);
384 assert.strictEqual(result?.tools, payload.tools);
385 assert.equal(result?.model, payload.model);
386 assert.equal(payload[key], 231_969);
387 },
388 );
389
390 it("preserves smaller budgets and other providers' payloads", async () => {
391 const hook = await loadRequestHook();
392 for (const payload of [{ max_tokens: 8192 }, { max_completion_tokens: 32_768 }, {}, null]) {
393 assert.isUndefined(hook({ payload }, { model: { provider: "openrouter" } }));
394 }
395 assert.isUndefined(
396 hook({ payload: { max_tokens: 231_969 } }, { model: { provider: "anthropic" } }),
397 );
398 });
399});
400
401async function loadInputHook(commands: ReadonlyArray<SkillCommand>) {
402 const handlers = await loadHooks(commands);
403 const hook = handlers.get("input");
404 assert.isDefined(hook);
405 return hook as InputHook;
406}
407
408describe("Pi skill references", () => {
409 it("loads every selected skill once while preserving inline prose, whitespace, and images", async () => {
410 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
411 try {
412 const alpha = NodePath.join(directory, "alpha.md");
413 const beta = NodePath.join(directory, "beta.md");
414 await NodeFSP.writeFile(alpha, "ALPHA_INSTRUCTIONS");
415 await NodeFSP.writeFile(beta, "BETA_INSTRUCTIONS");
416 const hook = await loadInputHook([
417 { name: "skill:alpha", source: "skill", sourceInfo: { path: alpha } },
418 { name: "skill:beta", source: "skill", sourceInfo: { path: beta } },
419 ]);
420 const text =
421 "Please use the $alpha philosophy, then $beta and $alpha\n```ts\n const x = 1;\n```";
422 const images = [{ type: "image", data: "fixture" }];
423 const result = await hook({ text, images }, { ui: { notify: assert.fail } });
424 assert.equal(result?.action, "transform");
425 assert.isTrue(result?.text.startsWith(text + "\n\n"));
426 assert.equal(result?.text.split("ALPHA_INSTRUCTIONS").length, 2);
427 assert.equal(result?.text.split("BETA_INSTRUCTIONS").length, 2);
428 assert.include(result?.text ?? "", `References are relative to ${directory}.`);
429 assert.strictEqual(result?.images, images);
430 } finally {
431 await NodeFSP.rm(directory, { recursive: true });
432 }
433 });
434
435 it("leaves unknown references and native skill commands for Pi", async () => {
436 const hook = await loadInputHook([
437 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
438 ]);
439 // Punctuation-adjacent references are plain text in the composer, not selected chips.
440 for (const text of [
441 "Explain $HOME",
442 "/skill:alpha use $alpha",
443 "Hello",
444 "$missing",
445 "Use $alpha, then continue",
446 "Use ($alpha)",
447 ]) {
448 assert.isUndefined(await hook({ text }, { ui: { notify: assert.fail } }));
449 }
450 });
451
452 it("loads additional chips without duplicating a leading native skill", async () => {
453 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
454 try {
455 const path = NodePath.join(directory, "beta.md");
456 await NodeFSP.writeFile(path, "BETA_INSTRUCTIONS");
457 const hook = await loadInputHook([
458 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
459 { name: "skill:beta", source: "skill", sourceInfo: { path } },
460 ]);
461 const text = "/skill:alpha use $alpha and $beta";
462 const result = await hook({ text }, { ui: { notify: assert.fail } });
463 assert.isTrue(result?.text.startsWith(text + "\n\n"));
464 assert.notInclude(result?.text ?? "", '<skill name="alpha"');
465 assert.include(result?.text ?? "", "BETA_INSTRUCTIONS");
466 } finally {
467 await NodeFSP.rm(directory, { recursive: true });
468 }
469 });
470
471 it("reports an unreadable skill without deleting its reference or other selected instructions", async () => {
472 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
473 try {
474 const path = NodePath.join(directory, "readable.md");
475 await NodeFSP.writeFile(path, "READABLE_INSTRUCTIONS");
476 const hook = await loadInputHook([
477 {
478 name: "skill:missing",
479 source: "skill",
480 sourceInfo: { path: NodePath.join(directory, "missing.md") },
481 },
482 { name: "skill:readable", source: "skill", sourceInfo: { path } },
483 ]);
484 const notices: string[] = [];
485 const text = "Use $missing and $readable";
486 const result = await hook(
487 { text },
488 {
489 ui: {
490 notify: (message) => {
491 notices.push(message);
492 },
493 },
494 },
495 );
496 assert.isTrue(result?.text.startsWith(text + "\n\n"));
497 assert.include(result?.text ?? "", "READABLE_INSTRUCTIONS");
498 assert.equal(notices.length, 1);
499 assert.include(notices[0] ?? "", "Could not load skill missing");
500 } finally {
501 await NodeFSP.rm(directory, { recursive: true });
502 }
503 });
504});