repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

feat(masks): add fuzzy picker and prompt scope

4b9669748d8a4d08ef9fee13c27e4dafda1e86bd

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (7)

CHANGELOG.md

Modified
2 2 # Changelog
4 4 ## Unreleased
6 +- Add Masks for quickly switching between named model and thinking combinations with `/masks`, `Alt+M`, configurable direct shortcuts, and fuzzy matching
7 +- Let prompts select a Mask for one agent turn with an optional `mask` frontmatter field
6 8 - Change Tune's fullscreen shortcut to `Ctrl+Alt+T`
7 9 - Generate git-safe's fixed-executable wrapper on first Bash use and reuse it across reloads
8 10 - Defer unused extension implementations, PATH checks, settings reads, prompt loading, and RTK probes beyond startup and reload

extensions/masks/CHANGELOG.md

Modified
3 3 # Changelog
5 5 ## 0.0.3
7 7 - Add `/masks`, configurable picker shortcut, and per-mask shortcuts
8 +- Fuzzy-match masks by name, model, thinking level, and shortcut
8 9 - Apply configured model and thinking level together
10 +- Let prompt templates equip a mask for one agent run through `mask` frontmatter
11 +- Restore the previous model and thinking level after masked prompt runs
9 12 - Validate global `masks` settings and report invalid entries

extensions/masks/README.md

Modified
12 12 Commands:
14 -- `/masks` opens the mask picker.
14 +- `/masks` opens the fuzzy mask picker.
15 15 - `/masks <name>` equips one mask directly.
17 17 Tools:
20 20 Hooks:
22 +- `input` detects prompt templates declaring a mask.
23 +- `before_agent_start` equips a prompt mask.
24 +- `agent_end` restores the previous model and thinking level.
22 25 - `session_start` reports invalid mask settings.
24 27 Settings:
47 50 Settings are global because masks describe personal model access and bindings.
48 51 Run `/reload` after changing them.
53 +Prompt templates may equip a mask for one agent run:
55 +```markdown
56 +---
57 +description: Review this change
58 +mask: terra
59 +---
60 +Review the current change.
61 +```
63 +`mask` must exactly match a configured mask name.
64 +The mask lasts through the prompt's tool loop and is restored at `agent_end`.
65 +Masked prompts cannot be queued while another agent run is active.
50 67 ## Behavior
52 -The picker shows every configured mask in settings order.
69 +The picker fuzzy-matches mask names, models, thinking levels, and shortcuts.
70 +Without a query, it shows every configured mask in settings order.
53 71 A mask changes the model first, then applies its thinking level.
54 72 Missing models or credentials leave the thinking level unchanged and report an error.
55 73 Successful switches add no status because Pi's existing footer shows model and thinking.

extensions/masks/__tests__/harness.test.ts

Modified
21 21 return root;
24 +function writePrompt(name: string, content: string): void {
25 + if (!root) throw new Error("missing test root");
26 + const promptsDir = join(root, "prompts");
27 + mkdirSync(promptsDir, { recursive: true });
28 + writeFileSync(join(promptsDir, `${name}.md`), content);
24 31 function extension() {
25 32 if (!t) throw new Error("missing test session");
26 33 return t.session.extensionRunner.extensions[0];
120 + it("applies prompt frontmatter for one agent run, then restores", async () => {
121 + const cwd = writeSettings({
122 + masks: {
123 + items: [
125 + name: "focused",
126 + model: "openai/gpt-4o",
127 + thinkingLevel: "high",
128 + },
129 + ],
130 + },
131 + });
132 + writePrompt(
133 + "review",
134 + "---\ndescription: Review changes\nmask: focused\n---\nReview it.",
135 + );
136 + t = await createTestSession({ cwd, extensions: [extensionPath()] });
137 + const model = context().modelRegistry.find("openai", "gpt-4o");
138 + if (!model) throw new Error("missing harness model");
139 + model.reasoning = true;
141 + const inputHandler = extension().handlers.get("input")[0];
142 + const beforeHandler = extension().handlers.get("before_agent_start")[0];
143 + const endHandler = extension().handlers.get("agent_end")[0];
144 + expect(
145 + await inputHandler(
146 + { type: "input", text: "/review", source: "interactive" },
147 + context(),
148 + ),
149 + ).toEqual({ action: "continue" });
151 + await beforeHandler(
153 + type: "before_agent_start",
154 + prompt: "Review it.",
155 + images: undefined,
156 + systemPrompt: "",
157 + systemPromptOptions: {},
158 + },
159 + context(),
160 + );
161 + expect(t.session.thinkingLevel).toBe("high");
163 + await endHandler({ type: "agent_end", messages: [] }, context());
164 + expect(t.session.model.provider).toBe("openai");
165 + expect(t.session.model.id).toBe("gpt-4o");
166 + expect(t.session.thinkingLevel).toBe("off");
167 + });
169 + it("rejects masked prompt templates queued mid-run", async () => {
170 + const cwd = writeSettings({
171 + masks: {
172 + items: [
174 + name: "focused",
175 + model: "openai/gpt-4o",
176 + thinkingLevel: "high",
177 + },
178 + ],
179 + },
180 + });
181 + writePrompt("review", "---\nmask: focused\n---\nReview it.");
182 + t = await createTestSession({ cwd, extensions: [extensionPath()] });
183 + const busyContext = { ...context(), isIdle: () => false };
184 + const result = await extension().handlers.get("input")[0](
186 + type: "input",
187 + text: "/review later",
188 + source: "interactive",
189 + streamingBehavior: "followUp",
190 + },
191 + busyContext,
192 + );
194 + expect(result).toEqual({ action: "handled" });
195 + expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
196 + "Prompt /review: masked prompts cannot be queued mid-run",
197 + "warning",
198 + ]);
199 + });
201 + it("fuzzy-matches non-prefix mask queries", () => {
202 + const parsed = __test.parseMasksSettings({
203 + items: [
205 + name: "terra",
206 + model: "openai-codex/gpt-5.6-terra",
207 + thinkingLevel: "medium",
208 + },
210 + name: "sol-xhigh",
211 + model: "openai-codex/gpt-5.6-sol",
212 + thinkingLevel: "xhigh",
213 + },
214 + ],
215 + });
217 + expect(
218 + __test.fuzzyMasks(parsed.config.items, "sxh").map((mask) => mask.name),
219 + ).toEqual(["sol-xhigh"]);
220 + });
222 + it("equips the fuzzy picker's selected result", async () => {
223 + const parsed = __test.parseMasksSettings({
224 + items: [
226 + name: "terra",
227 + model: "openai-codex/gpt-5.6-terra",
228 + thinkingLevel: "medium",
229 + },
231 + name: "sol-xhigh",
232 + model: "openai-codex/gpt-5.6-sol",
233 + thinkingLevel: "xhigh",
234 + },
235 + ],
236 + });
237 + const selected = await __test.chooseFuzzyMask(parsed.config.items, {
238 + ui: {
239 + custom: async (factory: any) => {
240 + let result: string | undefined;
241 + const component = await factory(
242 + { requestRender() {} },
244 + bold: (text: string) => text,
245 + fg: (_color: string, text: string) => text,
246 + },
248 + matches: (data: string, action: string) =>
249 + action === "tui.select.confirm" && data === "\r",
250 + },
251 + (value: string | undefined) => {
252 + result = value;
253 + },
254 + );
255 + for (const key of ["s", "x", "h", "\r"]) component.handleInput(key);
256 + return result;
257 + },
258 + },
259 + } as any);
261 + expect(selected?.name).toBe("sol-xhigh");
262 + });
113 264 it("validates schema while preserving usable picker entries", () => {
114 265 const parsed = __test.parseMasksSettings({
115 266 pickerShortcut: "alt+m",

extensions/masks/index.ts

Modified
1 +import { readFileSync } from "node:fs";
1 2 import type {
2 3 ExtensionAPI,
3 4 ExtensionContext,
4 5 } from "@earendil-works/pi-coding-agent";
5 -import { SettingsManager } from "@earendil-works/pi-coding-agent";
6 +import {
7 + DynamicBorder,
8 + parseFrontmatter,
9 + SettingsManager,
10 +} from "@earendil-works/pi-coding-agent";
11 +import {
12 + Container,
13 + fuzzyFilter,
14 + Input,
15 + SelectList,
16 + Spacer,
17 + Text,
18 +} from "@earendil-works/pi-tui";
7 20 const SETTINGS_KEY = "masks";
8 21 const DEFAULT_PICKER_SHORTCUT = "alt+m";
136 149 return [model.slice(0, separator), model.slice(separator + 1)];
152 +function fuzzyMasks(items: Mask[], query: string): Mask[] {
153 + if (!query.trim()) return items;
154 + return fuzzyFilter(
155 + items,
156 + query,
157 + (mask) =>
158 + `${mask.name} ${mask.model} ${mask.thinkingLevel} ${mask.shortcut ?? ""}`,
159 + );
162 +async function chooseFuzzyMask(
163 + items: Mask[],
164 + ctx: ExtensionContext,
165 +): Promise<Mask | undefined> {
166 + const selectedName = await ctx.ui.custom<string | undefined>(
167 + (tui, theme, keybindings, done) => {
168 + const container = new Container();
169 + const input = new Input();
170 + input.focused = true;
171 + let list: SelectList;
173 + function rebuild(): void {
174 + const filtered = fuzzyMasks(items, input.getValue());
175 + list = new SelectList(
176 + filtered.map((mask) => ({
177 + value: mask.name,
178 + label: mask.name,
179 + description: `${mask.model}:${mask.thinkingLevel}${mask.shortcut ? ` · ${mask.shortcut}` : ""}`,
180 + })),
181 + Math.min(Math.max(filtered.length, 1), 8),
183 + selectedPrefix: (text) => theme.fg("accent", text),
184 + selectedText: (text) => theme.fg("accent", text),
185 + description: (text) => theme.fg("muted", text),
186 + scrollInfo: (text) => theme.fg("dim", text),
187 + noMatch: (text) => theme.fg("warning", text),
188 + },
189 + );
190 + list.onSelect = (item) => done(item.value);
191 + list.onCancel = () => done(undefined);
193 + container.clear();
194 + container.addChild(
195 + new DynamicBorder((text) => theme.fg("accent", text)),
196 + );
197 + container.addChild(
198 + new Text(theme.fg("accent", theme.bold("Masks")), 1, 0),
199 + );
200 + container.addChild(new Text(theme.fg("dim", "Fuzzy filter"), 1, 0));
201 + container.addChild(input);
202 + container.addChild(new Spacer(1));
203 + container.addChild(list);
204 + container.addChild(
205 + new Text(
206 + theme.fg(
207 + "dim",
208 + "type to filter · ↑↓ select · enter equip · esc cancel",
209 + ),
210 + 1,
211 + 0,
212 + ),
213 + );
214 + container.addChild(
215 + new DynamicBorder((text) => theme.fg("accent", text)),
216 + );
219 + rebuild();
220 + return {
221 + render: (width: number) => container.render(width),
222 + invalidate: () => container.invalidate(),
223 + handleInput(data: string) {
224 + if (
225 + keybindings.matches(data, "tui.select.up") ||
226 + keybindings.matches(data, "tui.select.down")
227 + ) {
228 + list.handleInput(data);
229 + tui.requestRender();
230 + return;
232 + if (keybindings.matches(data, "tui.select.confirm")) {
233 + const selected = list.getSelectedItem();
234 + if (selected) done(selected.value);
235 + return;
237 + if (keybindings.matches(data, "tui.select.cancel")) {
238 + done(undefined);
239 + return;
242 + const previous = input.getValue();
243 + input.handleInput(data);
244 + if (input.getValue() !== previous) rebuild();
245 + tui.requestRender();
246 + },
247 + };
248 + },
249 + );
250 + return items.find((mask) => mask.name === selectedName);
253 +function promptCommandName(text: string): string | undefined {
254 + return /^\/([^\s]+)(?:\s|$)/u.exec(text)?.[1];
139 257 async function applyMask(
140 258 pi: ExtensionAPI,
141 259 mask: Mask,
164 282 export default function masksExtension(pi: ExtensionAPI): void {
165 283 const { config, errors } = readMasksSettings();
284 + let pendingMask: Mask | undefined;
285 + let restoreState:
286 + | {
287 + model: NonNullable<ExtensionContext["model"]>;
288 + thinkingLevel: ThinkingLevel;
290 + | undefined;
167 292 async function chooseMask(ctx: ExtensionContext): Promise<void> {
168 293 if (config.items.length === 0) {
169 294 ctx.ui.notify("No masks configured in settings.json", "warning");
170 295 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);
297 + let mask: Mask | undefined;
298 + if (ctx.mode === "tui") {
299 + mask = await chooseFuzzyMask(config.items, ctx);
300 + } else {
301 + const options = config.items.map(
302 + (item) => `${item.name} ${item.model}:${item.thinkingLevel}`,
303 + );
304 + const selected = await ctx.ui.select("Masks", options);
305 + const index = selected === undefined ? -1 : options.indexOf(selected);
306 + mask = index >= 0 ? config.items[index] : undefined;
308 + if (mask) await applyMask(pi, mask, ctx);
181 311 pi.registerShortcut(config.pickerShortcut as Shortcut, {
342 + pi.on("input", (event, ctx) => {
343 + pendingMask = undefined;
344 + const commandName = promptCommandName(event.text);
345 + if (!commandName) return { action: "continue" };
346 + const command = pi
347 + .getCommands()
348 + .find((item) => item.source === "prompt" && item.name === commandName);
349 + if (!command) return { action: "continue" };
351 + let frontmatter: Record<string, unknown>;
352 + try {
353 + frontmatter = parseFrontmatter(
354 + readFileSync(command.sourceInfo.path, "utf8"),
355 + ).frontmatter;
356 + } catch (error) {
357 + ctx.ui.notify(
358 + `Prompt /${commandName}: ${error instanceof Error ? error.message : String(error)}`,
359 + "error",
360 + );
361 + return { action: "handled" };
363 + if (!Object.hasOwn(frontmatter, "mask")) return { action: "continue" };
364 + const maskName = nonEmptyString(frontmatter.mask);
365 + if (!maskName) {
366 + ctx.ui.notify(
367 + `Prompt /${commandName}: mask must be a non-empty string`,
368 + "error",
369 + );
370 + return { action: "handled" };
372 + const mask = config.items.find((item) => item.name === maskName);
373 + if (!mask) {
374 + ctx.ui.notify(
375 + `Prompt /${commandName}: unknown mask "${maskName}"`,
376 + "error",
377 + );
378 + return { action: "handled" };
380 + if (!ctx.isIdle()) {
381 + ctx.ui.notify(
382 + `Prompt /${commandName}: masked prompts cannot be queued mid-run`,
383 + "warning",
384 + );
385 + return { action: "handled" };
387 + pendingMask = mask;
388 + return { action: "continue" };
389 + });
391 + pi.on("before_agent_start", async (_event, ctx) => {
392 + const mask = pendingMask;
393 + pendingMask = undefined;
394 + if (!mask) return;
395 + if (!ctx.model) {
396 + ctx.ui.notify(
397 + `Mask "${mask.name}": no current model to restore`,
398 + "error",
399 + );
400 + return;
402 + const previous = {
403 + model: ctx.model,
404 + thinkingLevel: pi.getThinkingLevel(),
405 + };
406 + if (await applyMask(pi, mask, ctx)) restoreState = previous;
407 + });
409 + async function restoreTemporaryMask(ctx: ExtensionContext): Promise<void> {
410 + const previous = restoreState;
411 + restoreState = undefined;
412 + if (!previous) return;
413 + if (!(await pi.setModel(previous.model))) {
414 + ctx.ui.notify("Failed to restore model after prompt mask", "error");
415 + return;
417 + pi.setThinkingLevel(previous.thinkingLevel);
420 + pi.on("agent_end", async (_event, ctx) => restoreTemporaryMask(ctx));
212 421 pi.on("session_start", (_event, ctx) => {
213 422 for (const error of errors) ctx.ui.notify(error, "warning");
424 + pi.on("session_shutdown", async (_event, ctx) => {
425 + pendingMask = undefined;
426 + await restoreTemporaryMask(ctx);
427 + });
217 -export const __test = { applyMask, parseMasksSettings, splitModelRef };
430 +export const __test = {
431 + applyMask,
432 + chooseFuzzyMask,
433 + fuzzyMasks,
434 + parseMasksSettings,
435 + promptCommandName,
436 + splitModelRef,

extensions/masks/package.json

Modified
4 4 "name": "@bugabinga/pi-ext-masks",
5 5 "type": "module",
6 6 "main": "index.ts",
7 7 "peerDependencies": {
8 - "@earendil-works/pi-coding-agent": "*"
8 + "@earendil-works/pi-coding-agent": "*",
9 + "@earendil-works/pi-tui": "*"
10 11 "license": "MIT",
11 12 "description": "Named model and thinking combinations for Pi.",

package-lock.json

Modified
317 317 "vitest": "^4.1.9"
319 319 "peerDependencies": {
320 - "@earendil-works/pi-coding-agent": "*"
320 + "@earendil-works/pi-coding-agent": "*",
321 + "@earendil-works/pi-tui": "*"
323 324 "extensions/model-info": {