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";
8import { PULL_REQUEST_LINKING_INSTRUCTIONS } from "@t3tools/provider-core/server/runtimeInstructions";
9
10import { PI_T3_MCP_EXTENSION_SOURCE, PI_T3_SERVICE_TIER_COMMAND } from "./mcpExtensionSource.ts";
11import { loadMcpBridge } from "./mcpBridge.testkit.ts";
12
13type RequestHook = (
14 event: { payload: unknown },
15 ctx: { model: { provider: string; serviceTiers?: ReadonlyArray<{ id: string }> } },
16) => Record<string, unknown> | undefined;
17
18type CommandHandler = (args: string) => Promise<void>;
19
20interface SkillCommand {
21 readonly name: string;
22 readonly source: string;
23 readonly sourceInfo: { readonly path: string };
24}
25
26type InputHook = (
27 event: { text: string; images?: ReadonlyArray<unknown> },
28 ctx: { ui: { notify: (message: string, level: string) => void } },
29) => Promise<{ action: string; text: string; images?: ReadonlyArray<unknown> } | undefined>;
30
31async function loadHooks(
32 commands: ReadonlyArray<SkillCommand> = [],
33 argv: ReadonlyArray<string> = [],
34) {
35 const handlers = new Map<string, unknown>();
36 const source = NodeModule.stripTypeScriptTypes(
37 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
38 "export default async function",
39 "async function",
40 ),
41 );
42 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
43 process: { env: {}, argv },
44 Buffer,
45 NodeFSP,
46 NodePath,
47 stripFrontmatter: (content: string) => content,
48 pi: {
49 on: (name: string, handler: unknown) => handlers.set(name, handler),
50 registerCommand: () => {},
51 getCommands: () => commands,
52 },
53 });
54 return handlers;
55}
56
57describe("Pi orchestration prompt section", () => {
58 it.each([
59 {
60 name: "on Pi builds without prompt sections",
61 events: [
62 { systemPrompt: "base" },
63 { systemPrompt: "base", systemPromptOptions: {} },
64 { systemPrompt: "base", systemPromptOptions: { sections: null } },
65 ],
66 },
67 {
68 name: "when an earlier extension forces the system prompt",
69 events: [
70 {
71 systemPrompt: "forced",
72 systemPromptOptions: { sections: {}, forceSystemPrompt: "forced" },
73 },
74 ],
75 },
76 ])("appends guidance $name", async ({ events }) => {
77 const bridge = await loadMcpBridge();
78 const hook = bridge.handlers.get("before_agent_start")!;
79 for (const event of events) {
80 const result = await hook(event, { ui: { notify: assert.fail } });
81 assert.isDefined(result);
82 assert.isTrue(result!.systemPrompt.startsWith(`${event.systemPrompt}\n\n`));
83 assert.include(result!.systemPrompt, "orchestrator_capabilities");
84 assert.include(result!.systemPrompt, PULL_REQUEST_LINKING_INSTRUCTIONS);
85 }
86 });
87
88 it("sets the guidance section on Pi builds with prompt sections", async () => {
89 const bridge = await loadMcpBridge();
90 const sections: Record<string, string> = {};
91 const result = await bridge.handlers.get("before_agent_start")!(
92 { systemPrompt: "base", systemPromptOptions: { sections } },
93 { ui: { notify: assert.fail } },
94 );
95 assert.isUndefined(result);
96 assert.include(sections.t3_code_orchestration, "orchestrator_capabilities");
97 assert.include(sections.t3_code_orchestration, PULL_REQUEST_LINKING_INSTRUCTIONS);
98 });
99});
100
101describe("Pi project trust", () => {
102 it.each([
103 { name: "a trusted folder", trusted: true, argv: [], notices: 0 },
104 { name: "an untrusted folder", trusted: false, argv: [], notices: 1 },
105 { name: "--no-approve", trusted: false, argv: ["--approve", "-na"], notices: 0 },
106 ])("sends $notices trust notice per session for $name", async ({ trusted, argv, notices }) => {
107 const sent: string[] = [];
108 const ctx = {
109 cwd: "/repo",
110 isProjectTrusted: () => trusted,
111 ui: { notify: (message: string) => sent.push(message) },
112 };
113 // Pi reruns extension factories on session replacement without asking about trust again.
114 for (const _session of [1, 2]) {
115 const handlers = (await loadHooks([], ["node", "pi", ...argv])) as Map<
116 string,
117 (event: unknown, ctx: unknown) => unknown
118 >;
119 for (const _turn of [1, 2]) await handlers.get("before_agent_start")!({}, ctx);
120 }
121 assert.equal(sent.length, notices * 2);
122 for (const message of sent)
123 assert.include(message, "for /repo because the folder is not trusted");
124 });
125});
126
127describe("Pi image media types", () => {
128 it("relabels a mislabelled image already in history before each model call", async () => {
129 const handlers = (await loadHooks()) as Map<
130 string,
131 (event: {
132 messages: ReadonlyArray<unknown>;
133 }) => { messages: ReadonlyArray<unknown> } | undefined
134 >;
135 const png = "iVBORw0KGgoAAAANSUhEUg==";
136 const jpeg = "/9j/4AAQSkZJRg==";
137 const history = [
138 {
139 role: "user",
140 content: [
141 { type: "text", text: "What colours are in this image?" },
142 { type: "image", data: png, mimeType: "image/jpeg" },
143 { type: "image", data: jpeg, mimeType: "image/jpeg" },
144 ],
145 },
146 { role: "assistant", content: [{ type: "text", text: "Provider error" }] },
147 { role: "user", content: [{ type: "text", text: "Say hi." }] },
148 ];
149
150 const result = handlers.get("context")!({ messages: history });
151
152 assert.deepEqual(result?.messages, [
153 {
154 role: "user",
155 content: [
156 { type: "text", text: "What colours are in this image?" },
157 { type: "image", data: png, mimeType: "image/png" },
158 { type: "image", data: jpeg, mimeType: "image/jpeg" },
159 ],
160 },
161 history[1],
162 history[2],
163 ]);
164 assert.isUndefined(handlers.get("context")!({ messages: [history[1], history[2]] }));
165 });
166});
167
168describe("Pi MCP tool results", () => {
169 it("returns mixed screenshot blocks and typed script output without repeating structured text", async () => {
170 const content = [
171 { type: "text", text: "Browser screenshot" },
172 { type: "image", data: "AAAA", mimeType: "image/png", _meta: { private: true } },
173 { type: "text", text: "Screenshot captured" },
174 ] as const;
175 const result = { content, structuredContent: { count: 2 }, _meta: { private: true } };
176 const bridge = await loadMcpBridge({ modern: true, result });
177 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot")!;
178 const output = await tool.execute("snapshot", {});
179 assert.deepEqual(output.content, [
180 content[0],
181 { type: "image", data: "AAAA", mimeType: "image/png" },
182 content[2],
183 ]);
184 assert.deepEqual(output.structuredContent, { content, structuredContent: { count: 2 } });
185 assert.deepEqual(tool.outputSchema, {
186 type: "object",
187 properties: {
188 content: { type: "array", items: { type: "object" } },
189 structuredContent: { type: "object", properties: { count: { type: "number" } } },
190 isError: { type: "boolean" },
191 _meta: { type: "object" },
192 },
193 required: ["content"],
194 });
195 });
196
197 it.each([false, true])(
198 "preserves image-only results and error status, isError=%s",
199 async (isError) => {
200 const image = { type: "image", data: "AAAA", mimeType: "image/png" };
201 const result = { content: [image], isError };
202 const bridge = await loadMcpBridge({ result });
203 const output = await bridge.tools[0]!.execute("image", {});
204 assert.deepEqual(output.content[0], image);
205 assert.equal(output.content.length, isError ? 2 : 1);
206 if (isError) assert.include(output.content[1]?.text ?? "", "returned an error");
207 assert.equal(output.isError, isError ? true : undefined);
208 assert.deepEqual(output.structuredContent, result);
209 },
210 );
211
212 it("uses structured output as model text when content is empty", async () => {
213 const result = { content: [], structuredContent: { count: 2 } };
214 const bridge = await loadMcpBridge({ result });
215 const output = await bridge.tools[0]!.execute("structured", {});
216 assert.deepEqual(output.content, [{ type: "text", text: '{"count":2}' }]);
217 assert.deepEqual(output.structuredContent, result);
218 });
219});
220
221describe("Pi MCP tool exposure", () => {
222 const discoveryContext = {
223 model: { api: "anthropic-messages" },
224 ui: { notify: () => undefined },
225 };
226
227 it("keeps orchestration direct and optional bridge tools discoverable on modern Pi", async () => {
228 const bridge = await loadMcpBridge({
229 modern: true,
230 toolSearchAvailable: true,
231 activatesOnRegistration: true,
232 });
233 await bridge.handlers.get("session_start")!({ systemPrompt: "" }, discoveryContext);
234 const start = bridge.handlers.get("before_agent_start");
235 assert.isDefined(start);
236 const prompt = await start!({ systemPrompt: "Pi system prompt" }, discoveryContext);
237 assert.include(prompt?.systemPrompt ?? "", "orchestrator_capabilities");
238 assert.equal(bridge.servers.length, 0);
239 assert.equal(bridge.tools.length, 8);
240 const aliases = [
241 "mcp__t3_code__orchestrator_capabilities",
242 "mcp__t3_code__delegate_task",
243 "mcp__t3_code__task_status",
244 "mcp__t3_code__preview_snapshot",
245 ];
246 const publicDirect = [
247 "mcp__t3-code__orchestrator_capabilities",
248 "mcp__t3-code__delegate_task",
249 "mcp__t3-code__task_status",
250 ];
251 assert.sameMembers(bridge.getActiveTools(), [
252 "read",
253 "tool_search",
254 ...publicDirect,
255 "mcp__t3_code__preview_snapshot",
256 ]);
257 assert.deepEqual(bridge.declaredTools(), publicDirect);
258 assert.deepEqual(
259 bridge.tools
260 .filter((tool) => tool.name.startsWith("mcp__t3-code__"))
261 .map((tool) => [tool.name, tool.exposure]),
262 [
263 ["mcp__t3-code__orchestrator_capabilities", "direct"],
264 ["mcp__t3-code__delegate_task", "direct"],
265 ["mcp__t3-code__task_status", "direct"],
266 ["mcp__t3-code__preview_snapshot", "deferred"],
267 ],
268 );
269 assert.deepEqual(
270 bridge.tools
271 .filter((tool) => tool.name.startsWith("mcp__t3_code__"))
272 .map((tool) => [tool.name, tool.exposure]),
273 aliases.map((name) => [name, "model-only"]),
274 );
275 const result = await bridge.tools
276 .find((tool) => tool.name === "mcp__t3-code__preview_snapshot")!
277 .execute("call-1", { depth: 2 });
278 assert.equal(result.content[0]?.text, "browser snapshot");
279 assert.equal(bridge.requests.at(-1)?.method, "tools/call");
280 });
281
282 it("restores gateway declarations after model switches and older tree loadouts without excluded tools", async () => {
283 const bridge = await loadMcpBridge({
284 modern: true,
285 toolSearchAvailable: true,
286 allowsTool: (name) => name !== "mcp__t3-code__delegate_task",
287 activatesOnRegistration: true,
288 });
289 const event = { systemPrompt: "" };
290 await bridge.handlers.get("session_start")!(event, discoveryContext);
291 assert.notInclude(bridge.getActiveTools(), "mcp__t3_code__delegate_task");
292 const gatewayContext = { model: { api: "openai-completions" }, ui: { notify: assert.fail } };
293 await bridge.handlers.get("model_select")!(event, gatewayContext);
294 bridge.restoreActiveTools(["read", "mcp__t3-code__task_status"]);
295 await bridge.handlers.get("session_tree")!(event, gatewayContext);
296 assert.deepEqual(bridge.getActiveTools(), [
297 "read",
298 "mcp__t3-code__task_status",
299 "tool_search",
300 "mcp__t3-code__orchestrator_capabilities",
301 "mcp__t3-code__preview_snapshot",
302 ]);
303 await bridge.handlers.get("model_select")!(event, discoveryContext);
304 assert.equal(
305 bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot")?.exposure,
306 "deferred",
307 );
308 assert.include(bridge.getActiveTools(), "mcp__t3-code__preview_snapshot");
309 });
310
311 it("keeps Pi's canonical MCP tool names callable by the model without declaring them twice", async () => {
312 const bridge = await loadMcpBridge({
313 modern: true,
314 toolSearchAvailable: true,
315 activatesOnRegistration: true,
316 });
317 const canonicalNames = [
318 "mcp__t3_code__orchestrator_capabilities",
319 "mcp__t3_code__delegate_task",
320 "mcp__t3_code__task_status",
321 "mcp__t3_code__preview_snapshot",
322 ];
323 const unreachableCanonicalNames = async () => {
324 const unreachable: string[] = [];
325 for (const name of canonicalNames) {
326 const result = await bridge.callModelTool(name, {});
327 if (result.isError === true) unreachable.push(name);
328 }
329 return unreachable;
330 };
331 const declaredCanonicalNames = () =>
332 bridge.declaredTools().filter((name) => name.startsWith("mcp__t3_code__"));
333 const event = { systemPrompt: "" };
334
335 await bridge.handlers.get("session_start")!(event, discoveryContext);
336 assert.deepEqual(
337 await unreachableCanonicalNames(),
338 [],
339 "model calls to these names fail with Tool not found after session start",
340 );
341 assert.deepEqual(declaredCanonicalNames(), [], "declared twice after session start");
342 assert.equal(bridge.requests.at(-1)?.method, "tools/call");
343
344 bridge.restoreActiveTools([
345 "read",
346 "mcp__t3-code__orchestrator_capabilities",
347 "mcp__t3-code__delegate_task",
348 "mcp__t3-code__task_status",
349 ]);
350 await bridge.handlers.get("session_tree")!(event, discoveryContext);
351 assert.deepEqual(
352 await unreachableCanonicalNames(),
353 [],
354 "model calls to these names fail with Tool not found after an older tree loadout",
355 );
356 assert.deepEqual(declaredCanonicalNames(), [], "declared twice after an older tree loadout");
357 assert.isFalse(
358 bridge.callableTools().some((name) => name.startsWith("mcp__t3_code__")),
359 "aliases duplicate the codemode catalog",
360 );
361
362 const requestCount = bridge.requests.length;
363 bridge.restoreActiveTools(
364 bridge.getActiveTools().filter((name) => name !== "mcp__t3-code__delegate_task"),
365 );
366 const late = await bridge.callModelTool("mcp__t3_code__delegate_task", {});
367 assert.isTrue(late.isError, "an alias runs after its public tool was switched off");
368 assert.equal(bridge.requests.length, requestCount);
369
370 bridge.restoreActiveTools(["read", "mcp__t3-code__task_status"]);
371 await bridge.handlers.get("session_tree")!(event, discoveryContext);
372 assert.deepEqual(
373 await unreachableCanonicalNames(),
374 ["mcp__t3_code__orchestrator_capabilities", "mcp__t3_code__delegate_task"],
375 "an alias stays callable while its direct public tool is off",
376 );
377 });
378
379 it("keeps a deferred tool's hidden alias active after tool_search loads its public tool", async () => {
380 const bridge = await loadMcpBridge({
381 modern: true,
382 toolSearchAvailable: true,
383 activatesOnRegistration: true,
384 });
385 const event = { systemPrompt: "" };
386 await bridge.handlers.get("session_start")!(event, discoveryContext);
387 assert.include(bridge.getActiveTools(), "mcp__t3_code__preview_snapshot");
388
389 // tool_search loads the deferred public tool during a run.
390 bridge.restoreActiveTools([...bridge.getActiveTools(), "mcp__t3-code__preview_snapshot"]);
391 await bridge.handlers.get("before_agent_start")!(event, discoveryContext);
392
393 // Pi hides recorded declarations with the current hidden set, so dropping the alias
394 // re-declares it in the prompt head and the next request misses the prompt cache.
395 assert.include(
396 bridge.getActiveTools(),
397 "mcp__t3_code__preview_snapshot",
398 "the next run drops the alias recorded in the transcript",
399 );
400 assert.notInclude(bridge.declaredTools(), "mcp__t3_code__preview_snapshot");
401 });
402
403 it.each(["legacy Pi", "disabled tool search"])(
404 "keeps tool execution available with %s",
405 async (mode) => {
406 const bridge = await loadMcpBridge({
407 modern: mode !== "legacy Pi",
408 toolSearchAvailable: mode === "disabled tool search",
409 toolSearchDisabled: mode === "disabled tool search",
410 });
411 if (mode !== "legacy Pi") {
412 const start = bridge.handlers.get("session_start");
413 await start!({ systemPrompt: "Pi system prompt" }, discoveryContext);
414 }
415 const publicTools = bridge.tools.filter((tool) => tool.name.startsWith("mcp__t3-code__"));
416 assert.equal(publicTools.length, 4);
417 assert.isTrue(
418 publicTools.every((tool) => tool.exposure === undefined || tool.exposure === "direct"),
419 );
420 assert.deepEqual(
421 bridge.tools
422 .filter((tool) => tool.name.startsWith("mcp__t3_code__"))
423 .map((tool) => tool.exposure),
424 mode === "legacy Pi" ? [] : ["model-only", "model-only", "model-only", "model-only"],
425 );
426 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot");
427 assert.isDefined(tool);
428 const controller = new AbortController();
429 const result = await tool!.execute("call-1", { depth: 2 }, controller.signal);
430 assert.equal(result.content[0]?.text, "browser snapshot");
431 assert.strictEqual(bridge.transports.at(-1)?.signal, controller.signal);
432 assert.equal(bridge.transports.at(-1)?.url, "http://fixture.invalid/mcp");
433 assert.equal(bridge.transports.at(-1)?.authorization, "Bearer fixture-token");
434 assert.deepEqual(JSON.parse(JSON.stringify(bridge.requests.at(-1))), {
435 jsonrpc: "2.0",
436 id: 3,
437 method: "tools/call",
438 params: { name: "preview_snapshot", arguments: { depth: 2 } },
439 });
440 assert.isUndefined(tool?.promptSnippet);
441 assert.isUndefined(tool?.promptGuidelines);
442 },
443 );
444});
445
446describe("Pi MCP tool schemas", () => {
447 it.each([{ type: "object" }, {}])(
448 "declares empty properties on object schemas that omit them: %j",
449 async (inputSchema) => {
450 const bridge = await loadMcpBridge({ inputSchema });
451 assert.isAbove(bridge.tools.length, 0);
452 for (const tool of bridge.tools) {
453 assert.deepEqual(tool.parameters, { type: "object", properties: {} });
454 }
455 },
456 );
457
458 it("keeps declared properties and other schema keywords", async () => {
459 const inputSchema = {
460 type: "object",
461 properties: { depth: { type: "number" } },
462 required: ["depth"],
463 additionalProperties: false,
464 };
465 const bridge = await loadMcpBridge({ inputSchema });
466 for (const tool of bridge.tools) {
467 assert.deepEqual(tool.parameters, inputSchema);
468 }
469 });
470
471 it("records each T3 schema once on Pi, which keeps hidden alias declarations in the transcript", async () => {
472 const inputSchema = {
473 type: "object",
474 properties: { depth: { type: "number", description: "Snapshot depth" } },
475 required: ["depth"],
476 };
477 const bridge = await loadMcpBridge({
478 modern: true,
479 inputSchema,
480 activatesOnRegistration: true,
481 });
482 await bridge.handlers.get("session_start")!(
483 { systemPrompt: "" },
484 { model: { api: "openai-completions" }, ui: { notify: assert.fail } },
485 );
486 const aliases = bridge.tools.filter((tool) => tool.name.startsWith("mcp__t3_code__"));
487 assert.isAbove(aliases.length, 0);
488 for (const alias of aliases) {
489 const label = alias.name.slice("mcp__t3_code__".length);
490 const publicTool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__" + label)!;
491 assert.deepEqual(publicTool.parameters, inputSchema);
492 assert.deepEqual(alias.parameters, { type: "object", properties: {} });
493 assert.equal(alias.description, "Same as mcp__t3-code__" + label + ".");
494 }
495 await bridge.callModelTool("mcp__t3_code__preview_snapshot", { depth: 2 });
496 assert.deepEqual(JSON.parse(JSON.stringify(bridge.requests.at(-1))).params, {
497 name: "preview_snapshot",
498 arguments: { depth: 2 },
499 });
500 });
501});
502
503describe("Pi tool discovery permissions", () => {
504 it.each(["approval-required", "auto-accept-edits", "auto"])(
505 "allows annotated T3 reads in %s while gating mutations and replacements",
506 async (runtimeMode) => {
507 const bridge = await loadMcpBridge({ modern: true, runtimeMode });
508 const hook = bridge.handlers.get("tool_call") as unknown as (
509 event: { toolName: string; input: unknown },
510 ctx: { ui: { confirm: (title: string) => Promise<boolean> } },
511 ) => Promise<{ block: true; reason: string } | undefined>;
512 const confirmations: string[] = [];
513 const ctx = {
514 ui: {
515 confirm: async (title: string) => {
516 confirmations.push(title);
517 return false;
518 },
519 },
520 };
521 for (const prefix of ["mcp__t3-code__", "mcp__t3_code__"]) {
522 assert.isUndefined(
523 await hook({ toolName: prefix + "orchestrator_capabilities", input: {} }, ctx),
524 );
525 assert.equal(
526 (await hook({ toolName: prefix + "delegate_task", input: {} }, ctx))?.block,
527 true,
528 );
529 assert.equal(
530 (await hook({ toolName: prefix + "task_status", input: {} }, ctx))?.block,
531 true,
532 );
533 }
534 assert.equal(confirmations.length, 4);
535 bridge.setBridgeSourcePath("/user/extensions/replacement.ts");
536 assert.equal(
537 (await hook({ toolName: "mcp__t3-code__orchestrator_capabilities", input: {} }, ctx))
538 ?.block,
539 true,
540 );
541 assert.equal(
542 (await hook({ toolName: "mcp__other__orchestrator_capabilities", input: {} }, ctx))?.block,
543 true,
544 );
545 assert.equal(confirmations.length, 6);
546 },
547 );
548
549 it("allows discovery without confirmation and still gates the discovered tool", async () => {
550 type ToolCallHook = (
551 event: { toolName: string; input: unknown },
552 ctx: {
553 signal: AbortSignal;
554 ui: {
555 confirm: (
556 title: string,
557 detail: string,
558 options: { signal: AbortSignal },
559 ) => Promise<boolean>;
560 };
561 },
562 ) => Promise<{ block: true; reason: string } | undefined>;
563 let toolCall: ToolCallHook | undefined;
564 let searchPath = "builtin:tool-search";
565 const source = NodeModule.stripTypeScriptTypes(
566 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
567 "export default async function",
568 "async function",
569 ),
570 );
571 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
572 process: { env: { T3_PI_RUNTIME_MODE: "approval-required" } },
573 pi: {
574 on: (name: string, handler: ToolCallHook) => {
575 if (name === "tool_call") toolCall = handler;
576 },
577 registerCommand: () => {},
578 getAllTools: () => [{ name: "tool_search", sourceInfo: { path: searchPath } }],
579 },
580 });
581 assert.isDefined(toolCall);
582 const confirmations: string[] = [];
583 const controller = new AbortController();
584 const ctx = {
585 signal: controller.signal,
586 ui: {
587 confirm: async (title: string, _detail: string, options: { signal: AbortSignal }) => {
588 assert.strictEqual(options.signal, controller.signal);
589 confirmations.push(title);
590 return false;
591 },
592 },
593 };
594 for (const builtinPath of ["builtin:tool-search", "<builtin:tool-search>"]) {
595 searchPath = builtinPath;
596 assert.isUndefined(
597 await toolCall!({ toolName: "tool_search", input: { query: "preview_snapshot" } }, ctx),
598 );
599 }
600 assert.equal(confirmations.length, 0);
601 const result = await toolCall!({ toolName: "mcp__t3-code__preview_snapshot", input: {} }, ctx);
602 assert.equal(result?.block, true);
603 assert.deepEqual(confirmations, ["Allow mcp__t3-code__preview_snapshot?"]);
604
605 searchPath = "/extensions/custom-search.ts";
606 const replaced = await toolCall!({ toolName: "tool_search", input: {} }, ctx);
607 assert.equal(replaced?.block, true);
608 assert.equal(confirmations.at(-1), "Allow tool_search?");
609 });
610
611 it("gives long inputs that differ past the shown text different confirmation details", async () => {
612 const bridge = await loadMcpBridge({ runtimeMode: "approval-required" });
613 const hook = bridge.handlers.get("tool_call") as unknown as (
614 event: { toolName: string; input: unknown },
615 ctx: { ui: { confirm: (title: string, detail: string) => Promise<boolean> } },
616 ) => Promise<{ block: true; reason: string } | undefined>;
617 const details: string[] = [];
618 const ctx = {
619 ui: {
620 confirm: async (_title: string, detail: string) => {
621 details.push(detail);
622 return true;
623 },
624 },
625 };
626 const filler = "a".repeat(4_100);
627 await hook({ toolName: "bash", input: { command: filler + "\necho one" } }, ctx);
628 await hook({ toolName: "bash", input: { command: filler + "\necho two" } }, ctx);
629 await hook({ toolName: "bash", input: { command: "ls" } }, ctx);
630 const [first, second, short] = details;
631 assert.equal(first!.slice(0, 4_000), second!.slice(0, 4_000));
632 assert.notEqual(first, second);
633 assert.match(first!, /\n\.\.\. \d+ more characters not shown \(sha256 [0-9a-f]{64}\)$/);
634 assert.equal(short, JSON.stringify({ command: "ls" }, null, 2));
635 });
636});
637
638async function loadRequestHook() {
639 const handlers = new Map<string, RequestHook>();
640 const commands = new Map<string, CommandHandler>();
641 const source = NodeModule.stripTypeScriptTypes(
642 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
643 "export default async function",
644 "async function",
645 ),
646 );
647 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
648 process: { env: {} },
649 pi: {
650 on: (name: string, handler: RequestHook) => handlers.set(name, handler),
651 registerCommand: (name: string, options: { handler: CommandHandler }) =>
652 commands.set(name, options.handler),
653 },
654 });
655 const hook = handlers.get("before_provider_request");
656 const setServiceTier = commands.get(PI_T3_SERVICE_TIER_COMMAND);
657 assert.isDefined(hook);
658 assert.isDefined(setServiceTier);
659 return Object.assign(hook!, { setServiceTier: setServiceTier! });
660}
661
662describe("Pi service tier", () => {
663 it("sends only a tier the active model advertises, until Standard clears it", async () => {
664 const hook = await loadRequestHook();
665 const sol = {
666 provider: "columbia-codex",
667 serviceTiers: [{ id: "priority" }, { id: "ultrafast" }],
668 };
669 const payload = { model: "gpt-6.1-sol", reasoning: { effort: "high" } };
670 assert.isUndefined(hook({ payload }, { model: sol }));
671
672 await hook.setServiceTier("priority");
673 assert.deepEqual(hook({ payload }, { model: sol }), { ...payload, service_tier: "priority" });
674
675 await hook.setServiceTier("ultrafast");
676 assert.equal(hook({ payload }, { model: sol })?.service_tier, "ultrafast");
677 const fastOnly = { provider: "columbia-codex", serviceTiers: [{ id: "priority" }] };
678 assert.isUndefined(hook({ payload }, { model: fastOnly }));
679 assert.isUndefined(hook({ payload }, { model: { provider: "anthropic" } }));
680
681 await hook.setServiceTier("");
682 assert.isUndefined(hook({ payload }, { model: sol }));
683 });
684});
685
686describe("Pi upstream output-budget workaround", () => {
687 it.each(["max_tokens", "max_completion_tokens"])(
688 "caps %s without changing the conversation or tools",
689 async (key) => {
690 const hook = await loadRequestHook();
691 const payload = {
692 model: "moonshotai/kimi-k2.6",
693 messages: [{ role: "user", content: "hello" }],
694 tools: [{ type: "function", function: { name: "read" } }],
695 [key]: 231_969,
696 };
697 const result = hook({ payload }, { model: { provider: "openrouter" } });
698 assert.equal(result?.[key], 32_768);
699 assert.strictEqual(result?.messages, payload.messages);
700 assert.strictEqual(result?.tools, payload.tools);
701 assert.equal(result?.model, payload.model);
702 assert.equal(payload[key], 231_969);
703 },
704 );
705
706 it("preserves smaller budgets and other providers' payloads", async () => {
707 const hook = await loadRequestHook();
708 for (const payload of [{ max_tokens: 8192 }, { max_completion_tokens: 32_768 }, {}, null]) {
709 assert.isUndefined(hook({ payload }, { model: { provider: "openrouter" } }));
710 }
711 assert.isUndefined(
712 hook({ payload: { max_tokens: 231_969 } }, { model: { provider: "anthropic" } }),
713 );
714 });
715});
716
717async function loadInputHook(commands: ReadonlyArray<SkillCommand>) {
718 const handlers = await loadHooks(commands);
719 const hook = handlers.get("input");
720 assert.isDefined(hook);
721 return hook as InputHook;
722}
723
724describe("Pi skill references", () => {
725 it("loads every selected skill once while preserving inline prose, whitespace, and images", async () => {
726 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
727 try {
728 const alpha = NodePath.join(directory, "alpha.md");
729 const beta = NodePath.join(directory, "beta.md");
730 await NodeFSP.writeFile(alpha, "ALPHA_INSTRUCTIONS");
731 await NodeFSP.writeFile(beta, "BETA_INSTRUCTIONS");
732 const hook = await loadInputHook([
733 { name: "skill:alpha", source: "skill", sourceInfo: { path: alpha } },
734 { name: "skill:beta", source: "skill", sourceInfo: { path: beta } },
735 ]);
736 const text =
737 "Please use the $alpha philosophy, then $beta and $alpha\n```ts\n const x = 1;\n```";
738 const images = [{ type: "image", data: "fixture" }];
739 const result = await hook({ text, images }, { ui: { notify: assert.fail } });
740 assert.equal(result?.action, "transform");
741 assert.isTrue(result?.text.startsWith(text + "\n\n"));
742 assert.equal(result?.text.split("ALPHA_INSTRUCTIONS").length, 2);
743 assert.equal(result?.text.split("BETA_INSTRUCTIONS").length, 2);
744 assert.include(result?.text ?? "", `References are relative to ${directory}.`);
745 assert.strictEqual(result?.images, images);
746 } finally {
747 await NodeFSP.rm(directory, { recursive: true });
748 }
749 });
750
751 it("leaves unknown references and native skill commands for Pi", async () => {
752 const hook = await loadInputHook([
753 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
754 ]);
755 for (const text of [
756 "Explain $HOME",
757 "/skill:alpha use $alpha",
758 "Hello",
759 "$missing",
760 "Use $alpha, then continue",
761 "Use ($alpha)",
762 ]) {
763 assert.isUndefined(await hook({ text }, { ui: { notify: assert.fail } }));
764 }
765 });
766
767 it("loads additional chips without duplicating a leading native skill", async () => {
768 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
769 try {
770 const path = NodePath.join(directory, "beta.md");
771 await NodeFSP.writeFile(path, "BETA_INSTRUCTIONS");
772 const hook = await loadInputHook([
773 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
774 { name: "skill:beta", source: "skill", sourceInfo: { path } },
775 ]);
776 const text = "/skill:alpha use $alpha and $beta";
777 const result = await hook({ text }, { ui: { notify: assert.fail } });
778 assert.isTrue(result?.text.startsWith(text + "\n\n"));
779 assert.notInclude(result?.text ?? "", '<skill name="alpha"');
780 assert.include(result?.text ?? "", "BETA_INSTRUCTIONS");
781 } finally {
782 await NodeFSP.rm(directory, { recursive: true });
783 }
784 });
785
786 it("reports an unreadable skill without deleting its reference or other selected instructions", async () => {
787 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
788 try {
789 const path = NodePath.join(directory, "readable.md");
790 await NodeFSP.writeFile(path, "READABLE_INSTRUCTIONS");
791 const hook = await loadInputHook([
792 {
793 name: "skill:missing",
794 source: "skill",
795 sourceInfo: { path: NodePath.join(directory, "missing.md") },
796 },
797 { name: "skill:readable", source: "skill", sourceInfo: { path } },
798 ]);
799 const notices: string[] = [];
800 const text = "Use $missing and $readable";
801 const result = await hook(
802 { text },
803 {
804 ui: {
805 notify: (message) => {
806 notices.push(message);
807 },
808 },
809 },
810 );
811 assert.isTrue(result?.text.startsWith(text + "\n\n"));
812 assert.include(result?.text ?? "", "READABLE_INSTRUCTIONS");
813 assert.equal(notices.length, 1);
814 assert.include(notices[0] ?? "", "Could not load skill missing");
815 } finally {
816 await NodeFSP.rm(directory, { recursive: true });
817 }
818 });
819});