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