repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(masks): switch model and thinking together

e7462aec3a87b0e3dbdf8c6073db78b3d97ed15b

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (7)

README.md

Modified
82 82 | `goal` | Persistent standing-goal loop for Pi sessions. | [README](extensions/goal/README.md) |
83 83 | `leaks` | Provider-bound secret redaction for Pi. | [README](extensions/leaks/README.md) |
84 84 | `llmiterate` | Manual editor-save bridge from comment markers to background Pi edits. | [README](extensions/llmiterate/README.md) |
85 +| `masks` | Named model and thinking combinations for Pi. | [README](extensions/masks/README.md) |
85 86 | `model-info` | Model and thinking telemetry for Pi. | [README](extensions/model-info/README.md) |
86 87 | `neko` | Tiny animated editor cat for Pi. Pointless. Correct. | [README](extensions/neko/README.md) |
87 88 | `notes` | Session-backed pending prompt notes for Pi. | [README](extensions/notes/README.md) |

extensions/masks/CHANGELOG.md

Added
new file mode 100644
1 +# Changelog
3 +## 0.0.3
5 +- Add `/masks`, configurable picker shortcut, and per-mask shortcuts
6 +- Apply configured model and thinking level together
7 +- Validate global `masks` settings and report invalid entries

extensions/masks/README.md

Added
new file mode 100644
1 +# masks
3 +Switch model and thinking level together.
5 +## Install / load
7 +This extension is loaded through the root pi-ext package.
8 +See [root README](../../README.md).
10 +## Commands / tools / settings
12 +Commands:
14 +- `/masks` opens the mask picker.
15 +- `/masks <name>` equips one mask directly.
17 +Tools:
18 +none.
20 +Hooks:
22 +- `session_start` reports invalid mask settings.
24 +Settings:
26 +```json
28 + "masks": {
29 + "pickerShortcut": "alt+m",
30 + "items": [
31 + {
32 + "name": "sol",
33 + "model": "openai-codex/gpt-5.6-sol",
34 + "thinkingLevel": "high",
35 + "shortcut": "alt+1"
36 + }
37 + ]
38 + }
40 +```
42 +`masks.pickerShortcut` is optional and defaults to `alt+m`.
43 +`masks.items` is an ordered array.
44 +Each item requires a unique `name`, a `provider/model`, and a `thinkingLevel`.
45 +`shortcut` is optional and must not collide with the picker or another mask.
46 +Thinking levels are `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`.
47 +Settings are global because masks describe personal model access and bindings.
48 +Run `/reload` after changing them.
50 +## Behavior
52 +The picker shows every configured mask in settings order.
53 +A mask changes the model first, then applies its thinking level.
54 +Missing models or credentials leave the thinking level unchanged and report an error.
55 +Successful switches add no status because Pi's existing footer shows model and thinking.

extensions/masks/__tests__/harness.test.ts

Added
new file mode 100644
1 +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 +import { tmpdir } from "node:os";
3 +import { join } from "node:path";
4 +import { fileURLToPath } from "node:url";
5 +import { afterEach, describe, expect, it } from "vitest";
6 +import { createTestSession, type TestSession } from "../../../test/harness";
7 +import { __test } from "../index.ts";
9 +let root: string | undefined;
10 +let t: TestSession | undefined;
12 +function extensionPath(): string {
13 + return fileURLToPath(new URL("../index.ts", import.meta.url));
16 +function writeSettings(settings: Record<string, unknown>): string {
17 + root = mkdtempSync(join(tmpdir(), "masks-test-"));
18 + const agentDir = join(root, ".test-home", ".pi", "agent");
19 + mkdirSync(agentDir, { recursive: true });
20 + writeFileSync(join(agentDir, "settings.json"), JSON.stringify(settings));
21 + return root;
24 +function extension() {
25 + if (!t) throw new Error("missing test session");
26 + return t.session.extensionRunner.extensions[0];
29 +function context() {
30 + if (!t) throw new Error("missing test session");
31 + return t.session.extensionRunner.createCommandContext();
34 +afterEach(() => {
35 + t?.dispose();
36 + t = undefined;
37 + if (root) rmSync(root, { recursive: true, force: true });
38 + root = undefined;
39 +});
41 +describe("masks pi-test-harness", () => {
42 + it("switches complete masks from direct shortcut, picker, and command", async () => {
43 + const cwd = writeSettings({
44 + masks: {
45 + pickerShortcut: "alt+m",
46 + items: [
47 + {
48 + name: "low",
49 + model: "openai/gpt-4o",
50 + thinkingLevel: "low",
51 + shortcut: "alt+1",
52 + },
53 + {
54 + name: "high",
55 + model: "openai/gpt-4o",
56 + thinkingLevel: "high",
57 + shortcut: "alt+2",
58 + },
59 + {
60 + name: "missing",
61 + model: "absent/nope",
62 + thinkingLevel: "max",
63 + shortcut: "alt+3",
64 + },
65 + ],
66 + },
67 + });
68 + t = await createTestSession({
69 + cwd,
70 + extensions: [extensionPath()],
71 + mockUI: { select: 1 },
72 + });
74 + const model = context().modelRegistry.find("openai", "gpt-4o");
75 + if (!model) throw new Error("missing harness model");
76 + model.reasoning = true;
78 + expect([...extension().commands.keys()]).toEqual(["masks"]);
79 + expect([...extension().shortcuts.keys()]).toEqual([
80 + "alt+m",
81 + "alt+1",
82 + "alt+2",
83 + "alt+3",
84 + ]);
86 + await extension().shortcuts.get("alt+1").handler(context());
87 + expect(t.session.model.provider).toBe("openai");
88 + expect(t.session.model.id).toBe("gpt-4o");
89 + expect(t.session.thinkingLevel).toBe("low");
91 + await extension().shortcuts.get("alt+m").handler(context());
92 + expect(t.session.thinkingLevel).toBe("high");
93 + expect(t.events.uiCallsFor("select")[0].args).toEqual([
94 + "Masks",
95 + [
96 + "low openai/gpt-4o:low",
97 + "high openai/gpt-4o:high",
98 + "missing absent/nope:max",
99 + ],
100 + ]);
102 + await extension().commands.get("masks").handler("low", context());
103 + expect(t.session.thinkingLevel).toBe("low");
105 + await extension().shortcuts.get("alt+3").handler(context());
106 + expect(t.session.thinkingLevel).toBe("low");
107 + expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
108 + 'Mask "missing": model absent/nope not found',
109 + "error",
110 + ]);
111 + });
113 + it("validates schema while preserving usable picker entries", () => {
114 + const parsed = __test.parseMasksSettings({
115 + pickerShortcut: "alt+m",
116 + items: [
118 + name: "a",
119 + model: "provider/a",
120 + thinkingLevel: "high",
121 + shortcut: "alt+1",
122 + },
124 + name: "a",
125 + model: "provider/b",
126 + thinkingLevel: "low",
127 + },
129 + name: "b",
130 + model: "provider/b",
131 + thinkingLevel: "low",
132 + shortcut: "alt+1",
133 + },
134 + { name: "bad", model: "missing-provider", thinkingLevel: "huge" },
135 + ],
136 + });
138 + expect(parsed.config).toEqual({
139 + pickerShortcut: "alt+m",
140 + items: [
142 + name: "a",
143 + model: "provider/a",
144 + thinkingLevel: "high",
145 + shortcut: "alt+1",
146 + },
148 + name: "b",
149 + model: "provider/b",
150 + thinkingLevel: "low",
151 + shortcut: undefined,
152 + },
153 + ],
154 + });
155 + expect(parsed.errors).toEqual([
156 + 'masks.items[1].name duplicates "a"',
157 + 'masks.items[2].shortcut duplicates "alt+1"',
158 + "masks.items[3].model must be provider/model",
159 + "masks.items[3].thinkingLevel is invalid",
160 + ]);
161 + });
163 + it("keeps a model id containing slashes", () => {
164 + expect(__test.splitModelRef("provider/org/model")).toEqual([
165 + "provider",
166 + "org/model",
167 + ]);
168 + });
169 +});

extensions/masks/index.ts

Added
new file mode 100644
1 +import type {
2 + ExtensionAPI,
3 + ExtensionContext,
4 +} from "@earendil-works/pi-coding-agent";
5 +import { SettingsManager } from "@earendil-works/pi-coding-agent";
7 +const SETTINGS_KEY = "masks";
8 +const DEFAULT_PICKER_SHORTCUT = "alt+m";
9 +const THINKING_LEVELS = [
10 + "off",
11 + "minimal",
12 + "low",
13 + "medium",
14 + "high",
15 + "xhigh",
16 + "max",
17 +] as const;
19 +type ThinkingLevel = (typeof THINKING_LEVELS)[number];
20 +type Shortcut = Parameters<ExtensionAPI["registerShortcut"]>[0];
22 +interface Mask {
23 + name: string;
24 + model: string;
25 + thinkingLevel: ThinkingLevel;
26 + shortcut?: string;
29 +interface MasksConfig {
30 + pickerShortcut: string;
31 + items: Mask[];
34 +interface ParsedMasks {
35 + config: MasksConfig;
36 + errors: string[];
39 +function isRecord(value: unknown): value is Record<string, unknown> {
40 + return typeof value === "object" && value !== null && !Array.isArray(value);
43 +function nonEmptyString(value: unknown): string | undefined {
44 + return typeof value === "string" && value.trim() ? value.trim() : undefined;
47 +function isThinkingLevel(value: unknown): value is ThinkingLevel {
48 + return THINKING_LEVELS.includes(value as ThinkingLevel);
51 +function parseMasksSettings(value: unknown): ParsedMasks {
52 + const errors: string[] = [];
53 + const config: MasksConfig = {
54 + pickerShortcut: DEFAULT_PICKER_SHORTCUT,
55 + items: [],
56 + };
57 + if (value === undefined) return { config, errors };
58 + if (!isRecord(value)) {
59 + return { config, errors: ["masks must be an object"] };
60 + }
62 + if (value.pickerShortcut !== undefined) {
63 + const shortcut = nonEmptyString(value.pickerShortcut);
64 + if (shortcut) config.pickerShortcut = shortcut;
65 + else errors.push("masks.pickerShortcut must be a non-empty string");
66 + }
68 + if (value.items === undefined) return { config, errors };
69 + if (!Array.isArray(value.items)) {
70 + errors.push("masks.items must be an array");
71 + return { config, errors };
72 + }
74 + const names = new Set<string>();
75 + const shortcuts = new Set<string>([config.pickerShortcut]);
76 + for (const [index, valueItem] of value.items.entries()) {
77 + const path = `masks.items[${index}]`;
78 + if (!isRecord(valueItem)) {
79 + errors.push(`${path} must be an object`);
80 + continue;
81 + }
83 + const name = nonEmptyString(valueItem.name);
84 + const model = nonEmptyString(valueItem.model);
85 + const thinkingLevel = valueItem.thinkingLevel;
86 + let valid = true;
87 + if (!name) {
88 + errors.push(`${path}.name must be a non-empty string`);
89 + valid = false;
90 + } else if (names.has(name)) {
91 + errors.push(`${path}.name duplicates "${name}"`);
92 + valid = false;
93 + }
94 + if (
95 + !model ||
96 + model.startsWith("/") ||
97 + model.endsWith("/") ||
98 + !model.includes("/")
99 + ) {
100 + errors.push(`${path}.model must be provider/model`);
101 + valid = false;
103 + if (!isThinkingLevel(thinkingLevel)) {
104 + errors.push(`${path}.thinkingLevel is invalid`);
105 + valid = false;
107 + if (!valid || !name || !model || !isThinkingLevel(thinkingLevel)) continue;
109 + let shortcut: string | undefined;
110 + if (valueItem.shortcut !== undefined) {
111 + shortcut = nonEmptyString(valueItem.shortcut);
112 + if (!shortcut) {
113 + errors.push(`${path}.shortcut must be a non-empty string`);
114 + } else if (shortcuts.has(shortcut)) {
115 + errors.push(`${path}.shortcut duplicates "${shortcut}"`);
116 + shortcut = undefined;
120 + names.add(name);
121 + if (shortcut) shortcuts.add(shortcut);
122 + config.items.push({ name, model, thinkingLevel, shortcut });
124 + return { config, errors };
127 +function readMasksSettings(): ParsedMasks {
128 + const settings = SettingsManager.create(
129 + process.cwd(),
130 + ).getGlobalSettings() as Record<string, unknown>;
131 + return parseMasksSettings(settings[SETTINGS_KEY]);
134 +function splitModelRef(model: string): [provider: string, modelId: string] {
135 + const separator = model.indexOf("/");
136 + return [model.slice(0, separator), model.slice(separator + 1)];
139 +async function applyMask(
140 + pi: ExtensionAPI,
141 + mask: Mask,
142 + ctx: ExtensionContext,
143 +): Promise<boolean> {
144 + const [provider, modelId] = splitModelRef(mask.model);
145 + const model = ctx.modelRegistry.find(provider, modelId);
146 + if (!model) {
147 + ctx.ui.notify(
148 + `Mask "${mask.name}": model ${mask.model} not found`,
149 + "error",
150 + );
151 + return false;
153 + if (!(await pi.setModel(model))) {
154 + ctx.ui.notify(
155 + `Mask "${mask.name}": no credentials for ${mask.model}`,
156 + "error",
157 + );
158 + return false;
160 + pi.setThinkingLevel(mask.thinkingLevel);
161 + return true;
164 +export default function masksExtension(pi: ExtensionAPI): void {
165 + const { config, errors } = readMasksSettings();
167 + async function chooseMask(ctx: ExtensionContext): Promise<void> {
168 + if (config.items.length === 0) {
169 + ctx.ui.notify("No masks configured in settings.json", "warning");
170 + return;
172 + const options = config.items.map(
173 + (mask) => `${mask.name} ${mask.model}:${mask.thinkingLevel}`,
174 + );
175 + const selected = await ctx.ui.select("Masks", options);
176 + if (selected === undefined) return;
177 + const index = options.indexOf(selected);
178 + if (index >= 0) await applyMask(pi, config.items[index], ctx);
181 + pi.registerShortcut(config.pickerShortcut as Shortcut, {
182 + description: "Choose model and thinking mask",
183 + handler: chooseMask,
184 + });
185 + for (const mask of config.items) {
186 + if (!mask.shortcut) continue;
187 + pi.registerShortcut(mask.shortcut as Shortcut, {
188 + description: `Equip mask ${mask.name}`,
189 + handler: async (ctx) => {
190 + await applyMask(pi, mask, ctx);
191 + },
192 + });
195 + pi.registerCommand("masks", {
196 + description: "Switch model and thinking mask",
197 + handler: async (args, ctx) => {
198 + const name = args?.trim();
199 + if (!name) {
200 + await chooseMask(ctx);
201 + return;
203 + const mask = config.items.find((item) => item.name === name);
204 + if (!mask) {
205 + ctx.ui.notify(`Unknown mask "${name}"`, "error");
206 + return;
208 + await applyMask(pi, mask, ctx);
209 + },
210 + });
212 + pi.on("session_start", (_event, ctx) => {
213 + for (const error of errors) ctx.ui.notify(error, "warning");
214 + });
217 +export const __test = { applyMask, parseMasksSettings, splitModelRef };

extensions/masks/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-masks",
3 + "type": "module",
4 + "main": "index.ts",
5 + "peerDependencies": {
6 + "@earendil-works/pi-coding-agent": "*"
7 + },
8 + "license": "MIT",
9 + "description": "Named model and thinking combinations for Pi.",
10 + "keywords": [
11 + "pi",
12 + "pi-extension"
13 + ],
14 + "devDependencies": {
15 + "@marcfargas/pi-test-harness": "^0.6.1",
16 + "vitest": "^4.1.9"
17 + },
18 + "scripts": {},
19 + "private": true

package-lock.json

Modified
309 309 "@earendil-works/pi-tui": "*"
312 + "extensions/masks": {
313 + "name": "@bugabinga/pi-ext-masks",
314 + "license": "MIT",
315 + "devDependencies": {
316 + "@marcfargas/pi-test-harness": "^0.6.1",
317 + "vitest": "^4.1.9"
318 + },
319 + "peerDependencies": {
320 + "@earendil-works/pi-coding-agent": "*"
322 + },
312 323 "extensions/model-info": {
313 324 "name": "@bugabinga/pi-ext-model-info",
314 325 "license": "MIT",
1503 1514 "resolved": "extensions/llmiterate",
1504 1515 "link": true
1517 + "node_modules/@bugabinga/pi-ext-masks": {
1518 + "resolved": "extensions/masks",
1519 + "link": true
1520 + },
1506 1521 "node_modules/@bugabinga/pi-ext-model-info": {
1507 1522 "resolved": "extensions/model-info",
1508 1523 "link": true