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