repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(ui): add ask and pfui foundations

759939356ca54eb56a1a2405dc58f303ba019be3

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (23)

.system/SYSTEM.md

Modified
8 8 ## Runtime package
10 10 The repository root is the supported Pi installation and distribution unit.
11 -Its manifest exports `extensions/*/index.ts` and no root skills, prompts, or themes.
11 +Its manifest exports `extensions/pfui/index.ts` first, then `extensions/*/index.ts`, and no root skills, prompts, or themes.
12 12 Package filters may select a subset of those exported resources.
13 13 Pi loads the TypeScript extension entrypoints directly through its extension loader.

biome.json

Modified
14 14 "!.rumdl_cache",
15 15 "!.worktrees",
16 16 "!skills/find-skills",
17 + "!extensions/iq/check/fixtures",
18 + "!check/fixtures",
17 19 "!**/test-results",
18 20 "!**/playwright-report",
19 21 "!**/*.snap"

extensions/ask/README.md

Added
new file mode 100644
1 +# ask
3 +Structured multiple-choice questions from the model to the human, similar to Claude Code's `AskUserQuestion` and Codex's `request_user_input`.
5 +## Install / load
7 +Loaded through the root [`pi-ext` package](../../README.md).
9 +## Commands / tools / settings
11 +- Tool: `ask_user_question`
12 + - Accepts 1–4 questions.
13 + - Each question provides 2–4 options and may allow multiple selections.
14 + - Optional question IDs provide stable answer keys.
15 + - Free-form answers are always available.
16 +- Commands: none.
17 +- Hooks: none.
18 +- Settings: none.
20 +## Behavior
22 +- Questions are presented sequentially.
23 +- TUI: one overlay per question with the supplied options plus `Other…`.
24 + Questions, options, answers, notes, and tool call/result text wrap to the available width.
25 + Enter selects, Tab opens an optional notes field, Esc cancels the whole call and terminates the turn.
26 + Multi-select questions toggle options with Space.
27 + Fullscreen TUI mode also supports clicking options, clicking to position the answer or notes cursor, and wheel navigation.
28 + Regular TUI mode leaves mouse input to the terminal.
29 +- RPC: uses Pi dialogs (`select`, `input`, and `confirm`).
30 + `Other (free text)` is always offered.
31 + Dismissing any dialog cancels the whole call.
32 +- Print and JSON modes (`hasUI === false`): returns `{"status":"unavailable"}` immediately instead of blocking.
33 +- Model-supplied options whose labels begin with `Other` are removed.
34 +- Missing headers are derived from the question ID or text and truncated to 12 characters.
35 +- Duplicate answer keys receive numeric suffixes such as `-2`.
37 +## Result contract
39 +```json
40 +{"status":"answered","answers":{"<id or question>":{"answers":["Postgres (Recommended)"]}}}
41 +```
43 +Answers are keyed by `id` when provided, otherwise by the full question text.
44 +Free-form answers appear in the same `answers` array as option labels.
45 +`notes` contains optional TUI commentary and is omitted when empty.

extensions/ask/__tests__/harness.test.ts

Added
new file mode 100644
1 +import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2 +import { visibleWidth } from "@earendil-works/pi-tui";
3 +import { afterEach, describe, expect, it } from "vitest";
4 +import { createTestSession, type TestSession } from "../../../test/harness";
5 +import askExtension, { __test } from "../index.ts";
7 +let t: TestSession | undefined;
9 +const KEYS: Record<string, string> = {
10 + "tui.select.confirm": "\r",
11 + "tui.select.cancel": "\x1b",
12 + "tui.select.up": "\x1b[A",
13 + "tui.select.down": "\x1b[B",
14 + "tui.input.tab": "\t",
15 +};
17 +function tuiSession() {
18 + let component:
19 + | {
20 + handleInput: (data: string) => void;
21 + handleMouse?: (event: {
22 + type: "press" | "click";
23 + button: "left";
24 + x: number;
25 + y: number;
26 + screenX: number;
27 + screenY: number;
28 + width: number;
29 + height: number;
30 + shift: boolean;
31 + alt: boolean;
32 + ctrl: boolean;
33 + }) => { handled?: boolean } | undefined;
34 + render: (width: number) => string[];
35 + }
36 + | undefined;
37 + const custom = (
38 + factory: (
39 + tui: unknown,
40 + theme: unknown,
41 + keybindings: unknown,
42 + done: (value: never) => void,
43 + ) => unknown,
44 + ) =>
45 + new Promise((resolve) => {
46 + component = factory(
47 + { requestRender() {}, terminal: { rows: 40 } },
48 + {
49 + fg: (_style: string, text: string) => text,
50 + bold: (text: string) => text,
51 + },
52 + {
53 + matches: (data: string, action: string) => KEYS[action] === data,
54 + },
55 + resolve,
56 + ) as typeof component;
57 + });
58 + const ctx = {
59 + hasUI: true,
60 + mode: "tui",
61 + ui: { custom },
62 + } as unknown as ExtensionContext;
63 + return { ctx, component: () => component };
66 +afterEach(() => {
67 + t?.dispose();
68 + t = undefined;
69 +});
71 +function fakeCtx(
72 + ui: {
73 + select?: (
74 + title: string,
75 + entries: string[],
76 + options?: unknown,
77 + ) => Promise<string | undefined>;
78 + input?: (
79 + title: string,
80 + placeholder?: string,
81 + options?: unknown,
82 + ) => Promise<string | undefined>;
83 + confirm?: (
84 + title: string,
85 + message: string,
86 + options?: unknown,
87 + ) => Promise<boolean>;
88 + },
89 + overrides: Record<string, unknown> = {},
90 +): ExtensionContext {
91 + return {
92 + hasUI: true,
93 + mode: "rpc",
94 + ui: {
95 + select: ui.select ?? (async () => undefined),
96 + input: ui.input ?? (async () => undefined),
97 + confirm: ui.confirm ?? (async () => false),
98 + },
99 + ...overrides,
100 + } as ExtensionContext;
103 +function mouseEvent(type: "press" | "click", y: number, width = 80) {
104 + return {
105 + type,
106 + button: "left" as const,
107 + x: 1,
108 + y,
109 + screenX: 1,
110 + screenY: y,
111 + width,
112 + height: 40,
113 + shift: false,
114 + alt: false,
115 + ctrl: false,
116 + };
119 +function singleQuestion() {
120 + return __test.normalizeQuestions([
122 + id: "db",
123 + header: "Database",
124 + question: "Which database?",
125 + options: [
126 + { label: "Postgres (Recommended)", description: "Relational." },
127 + { label: "SQLite", description: "Embedded." },
128 + ],
129 + },
130 + ]);
133 +describe("ask extension", () => {
134 + it("loads in real Pi extension runtime and registers ask_user_question", async () => {
135 + t = await createTestSession({ extensionFactories: [askExtension] });
136 + expect(
137 + t.session.extensionRunner.extensions[0].tools.has("ask_user_question"),
138 + ).toBe(true);
139 + });
141 + it("terminates on cancel and reports missing UI at tool level", async () => {
142 + t = await createTestSession({ extensionFactories: [askExtension] });
143 + const tool =
144 + t.session.extensionRunner.extensions[0].tools.get("ask_user_question");
145 + const definition = tool?.definition;
146 + expect(definition).toBeDefined();
147 + const params = {
148 + questions: [
150 + question: "Q?",
151 + options: [
152 + { label: "A", description: "a" },
153 + { label: "B", description: "b" },
154 + ],
155 + },
156 + ],
157 + };
158 + const cancelled = await definition.execute(
159 + "id",
160 + params,
161 + undefined,
162 + undefined,
163 + fakeCtx({}),
164 + );
165 + expect(cancelled.terminate).toBe(true);
166 + expect(JSON.parse(cancelled.content[0].text).status).toBe("cancelled");
168 + const unavailable = await definition.execute(
169 + "id",
170 + params,
171 + undefined,
172 + undefined,
173 + fakeCtx({}, { hasUI: false }),
174 + );
175 + expect(JSON.parse(unavailable.content[0].text).status).toBe("unavailable");
176 + });
177 +});
179 +describe("normalizeQuestions", () => {
180 + it("derives key and header and strips model-supplied Other options", () => {
181 + const [question] = __test.normalizeQuestions([
183 + question: "Which database?",
184 + options: [
185 + { label: "Postgres (Recommended)", description: "Relational." },
186 + { label: "Other", description: "ignored" },
187 + ],
188 + },
189 + ]);
190 + expect(question.key).toBe("Which database?");
191 + expect(question.header).toBe("Which databa");
192 + expect(question.options).toHaveLength(1);
193 + expect(question.options[0].label).toBe("Postgres (Recommended)");
194 + });
196 + it("prefers id for key and header, dedupes keys, defaults multiSelect", () => {
197 + const [first, second] = __test.normalizeQuestions([
199 + id: "deploy",
200 + header: "Target",
201 + question: "Deploy where?",
202 + options: [
203 + { label: "A", description: "a" },
204 + { label: "B", description: "b" },
205 + ],
206 + },
208 + id: "deploy",
209 + question: "Again?",
210 + options: [
211 + { label: "C", description: "c" },
212 + { label: "D", description: "d" },
213 + ],
214 + },
215 + ]);
216 + expect(first.key).toBe("deploy");
217 + expect(first.header).toBe("Target");
218 + expect(first.multiSelect).toBe(false);
219 + expect(second.key).toBe("deploy-2");
220 + });
222 + it("rejects empty questions and questions without usable options", () => {
223 + expect(() => __test.normalizeQuestions([])).toThrow(/1-4 questions/);
224 + expect(() =>
225 + __test.normalizeQuestions([
227 + question: "Q?",
228 + options: [{ label: "Other", description: "x" }],
229 + },
230 + ]),
231 + ).toThrow(/no usable options/);
232 + });
233 +});
235 +describe("runAskFlow", () => {
236 + it("answers single-select with the chosen label and offers Other", async () => {
237 + const calls: Array<[string, string[]]> = [];
238 + const result = await __test.runAskFlow(
239 + singleQuestion(),
240 + fakeCtx({
241 + select: async (title, entries) => {
242 + calls.push([title, entries]);
243 + return entries[0];
244 + },
245 + }),
246 + );
247 + expect(result).toEqual({
248 + status: "answered",
249 + answers: { db: { answers: ["Postgres (Recommended)"] } },
250 + });
251 + expect(calls[0][0]).toBe("Question 1/1 · Database");
252 + expect(calls[0][1]).toContain(__test.OTHER_LABEL);
253 + });
255 + it("routes Other through free-text input and trims it", async () => {
256 + const result = await __test.runAskFlow(
257 + singleQuestion(),
258 + fakeCtx({
259 + select: async (_title, entries) => entries.at(-1) ?? __test.OTHER_LABEL,
260 + input: async () => " Whatever fits ",
261 + }),
262 + );
263 + expect(result).toEqual({
264 + status: "answered",
265 + answers: { db: { answers: ["Whatever fits"] } },
266 + });
267 + });
269 + it("cancels the whole call when any dialog is dismissed", async () => {
270 + const result = await __test.runAskFlow(
271 + singleQuestion(),
272 + fakeCtx({
273 + select: async () => undefined,
274 + input: async () => "x",
275 + }),
276 + );
277 + expect(result).toEqual({ status: "cancelled" });
278 + });
280 + it("collects multi-select confirms, then Done", async () => {
281 + const picks = [true, false];
282 + const questions = __test.normalizeQuestions([
284 + id: "feat",
285 + question: "Which features?",
286 + multiSelect: true,
287 + options: [
288 + { label: "Auth", description: "a" },
289 + { label: "Audit", description: "b" },
290 + ],
291 + },
292 + ]);
293 + const result = await __test.runAskFlow(
294 + questions,
295 + fakeCtx({
296 + select: async (_title, entries) =>
297 + entries[0] === "Done" ? "Done" : undefined,
298 + confirm: async () => picks.shift() ?? false,
299 + }),
300 + );
301 + expect(result).toEqual({
302 + status: "answered",
303 + answers: { feat: { answers: ["Auth"] } },
304 + });
305 + });
306 +});
308 +describe("runAskFlow in TUI mode", () => {
309 + const keys = Object.values(KEYS);
311 + it("selects an option with enter", async () => {
312 + const session = tuiSession();
313 + const flow = __test.runAskFlow(singleQuestion(), session.ctx);
314 + session.component()?.handleInput(KEYS["tui.select.down"]);
315 + session.component()?.handleInput(KEYS["tui.select.confirm"]);
316 + await expect(flow).resolves.toEqual({
317 + status: "answered",
318 + answers: { db: { answers: ["SQLite"] } },
319 + });
320 + });
322 + it("routes Other through the free-text input", async () => {
323 + const session = tuiSession();
324 + const flow = __test.runAskFlow(singleQuestion(), session.ctx);
325 + session.component()?.handleInput(KEYS["tui.select.down"]);
326 + session.component()?.handleInput(KEYS["tui.select.down"]);
327 + session.component()?.handleInput(KEYS["tui.select.confirm"]);
328 + for (const key of ["C", "u", "s", "t", "o", "m", "\r"]) {
329 + session.component()?.handleInput(key);
331 + await expect(flow).resolves.toEqual({
332 + status: "answered",
333 + answers: { db: { answers: ["Custom"] } },
334 + });
335 + });
337 + it("attaches notes through tab and submits the highlighted option", async () => {
338 + const session = tuiSession();
339 + const flow = __test.runAskFlow(singleQuestion(), session.ctx);
340 + session.component()?.handleInput(KEYS["tui.input.tab"]);
341 + for (const key of ["l", "a", "t", "e", "r", "\r"]) {
342 + session.component()?.handleInput(key);
344 + await expect(flow).resolves.toEqual({
345 + status: "answered",
346 + answers: { db: { answers: ["Postgres (Recommended)"], notes: "later" } },
347 + });
348 + });
350 + it("wraps questions, options, and free-text input to the available width", async () => {
351 + const questions = __test.normalizeQuestions([
353 + id: "wrap",
354 + question: "Which database should handle this unusually demanding workload?",
355 + options: [
357 + label: "Postgres with replication (Recommended)",
358 + description: "Supports relational queries and resilient failover.",
359 + },
360 + { label: "SQLite", description: "Embedded and deliberately simple." },
361 + ],
362 + },
363 + ]);
364 + const session = tuiSession();
365 + const flow = __test.runAskFlow(questions, session.ctx);
366 + const initial = session.component()?.render(24) ?? [];
367 + expect(initial.every((line) => visibleWidth(line) <= 24)).toBe(true);
368 + expect(initial.join("\n")).toContain("demanding workload?");
369 + session.component()?.handleInput(KEYS["tui.select.down"]);
370 + session.component()?.handleInput(KEYS["tui.select.down"]);
371 + session.component()?.handleInput(KEYS["tui.select.confirm"]);
372 + for (const key of "A free-form answer long enough to wrap") {
373 + session.component()?.handleInput(key);
375 + const withInput = session.component()?.render(24) ?? [];
376 + expect(withInput.every((line) => visibleWidth(line) <= 24)).toBe(true);
377 + expect(withInput.filter((line) => line.includes("free-form") || line.includes("enough to wrap"))).toHaveLength(2);
378 + session.component()?.handleInput("\r");
379 + await expect(flow).resolves.toEqual({
380 + status: "answered",
381 + answers: { wrap: { answers: ["A free-form answer long enough to wrap"] } },
382 + });
383 + });
385 + it("selects an option with the mouse in fullscreen TUI mode", async () => {
386 + const session = tuiSession();
387 + const flow = __test.runAskFlow(singleQuestion(), session.ctx);
388 + const lines = session.component()?.render(80) ?? [];
389 + const sqliteRow = lines.findIndex((line) => line.includes("SQLite"));
390 + expect(sqliteRow).toBeGreaterThanOrEqual(0);
391 + session.component()?.handleMouse?.(mouseEvent("press", sqliteRow));
392 + session.component()?.handleMouse?.(mouseEvent("click", sqliteRow));
393 + await expect(flow).resolves.toEqual({
394 + status: "answered",
395 + answers: { db: { answers: ["SQLite"] } },
396 + });
397 + });
399 + it("cancels from the option list with escape", async () => {
400 + const session = tuiSession();
401 + const flow = __test.runAskFlow(singleQuestion(), session.ctx);
402 + session.component()?.handleInput(KEYS["tui.select.cancel"]);
403 + await expect(flow).resolves.toEqual({ status: "cancelled" });
404 + });
406 + it("toggles multi-select options with space", async () => {
407 + const questions = __test.normalizeQuestions([
409 + id: "feat",
410 + question: "Which features?",
411 + multiSelect: true,
412 + options: [
413 + { label: "Auth", description: "a" },
414 + { label: "Audit", description: "b" },
415 + ],
416 + },
417 + ]);
418 + const session = tuiSession();
419 + const flow = __test.runAskFlow(questions, session.ctx);
420 + session.component()?.handleInput(" ");
421 + session.component()?.handleInput(KEYS["tui.select.down"]);
422 + session.component()?.handleInput(" ");
423 + const rendered = session.component()?.render(80)?.join("\n") ?? "";
424 + session.component()?.handleInput(KEYS["tui.select.confirm"]);
425 + await expect(flow).resolves.toEqual({
426 + status: "answered",
427 + answers: { feat: { answers: ["Auth", "Audit"] } },
428 + });
429 + expect(rendered).toContain("Which features?");
430 + expect(rendered).toContain("Other");
431 + expect(keys).toContain(KEYS["tui.select.confirm"]);
432 + });
433 +});

extensions/ask/ask-overlay.ts

Added
new file mode 100644
1 +import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
2 +import {
3 + Editor,
4 + type KeybindingsManager,
5 + type SelectItem,
6 + truncateToWidth,
7 + type TUI,
8 + type TuiMouseEvent,
9 + type TuiMouseEventResult,
10 + visibleWidth,
11 + wrapTextWithAnsi,
12 +} from "@earendil-works/pi-tui";
13 +import type { AskAnswer, AskQuestion } from "./ask-tool.js";
15 +const OTHER_VALUE = "__other__";
16 +const OTHER_ITEM: SelectItem = {
17 + value: OTHER_VALUE,
18 + label: "Other…",
19 + description: "Type your own answer",
20 +};
22 +export async function askInTui(
23 + title: string,
24 + question: AskQuestion,
25 + ctx: ExtensionContext,
26 + signal?: AbortSignal,
27 +): Promise<AskAnswer | undefined> {
28 + const promise = ctx.ui.custom<AskAnswer | undefined>(
29 + (tui, theme, keybindings, done) =>
30 + new AskQuestionOverlay(tui, theme, keybindings, done, title, question),
31 + );
32 + return await abortable(promise, signal);
35 +function abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
36 + if (!signal) return promise;
37 + return new Promise<T>((resolve, reject) => {
38 + const onAbort = () => resolve(undefined as T);
39 + if (signal.aborted) {
40 + resolve(undefined as T);
41 + return;
42 + }
43 + signal.addEventListener("abort", onAbort, { once: true });
44 + promise.then(
45 + (value) => {
46 + signal.removeEventListener("abort", onAbort);
47 + resolve(value);
48 + },
49 + (reason) => {
50 + signal.removeEventListener("abort", onAbort);
51 + reject(reason);
52 + },
53 + );
54 + });
57 +type OverlayMode = "list" | "other" | "notes";
59 +class AskQuestionOverlay {
60 + private settled = false;
61 + private mode: OverlayMode = "list";
62 + private readonly list: OptionList;
63 + private readonly otherInput: Editor;
64 + private readonly notesInput: Editor;
65 + private otherText = "";
66 + private otherSelected = false;
67 + private focusedState = true;
68 + private listRow = 0;
69 + private listHeight = 0;
70 + private inputRow: number | undefined;
71 + private inputHeight = 0;
73 + constructor(
74 + private readonly tui: TUI,
75 + private readonly theme: Theme,
76 + private readonly keybindings: KeybindingsManager,
77 + private readonly done: (answer: AskAnswer | undefined) => void,
78 + private readonly title: string,
79 + private readonly question: AskQuestion,
80 + ) {
81 + const items: SelectItem[] = [
82 + ...question.options.map((option) => ({
83 + value: option.label,
84 + label: option.label,
85 + description: option.description,
86 + })),
87 + OTHER_ITEM,
88 + ];
89 + this.list = new OptionList(
90 + items,
91 + question.multiSelect,
92 + theme,
93 + () => this.otherSelected,
94 + () => this.activateCurrent(),
95 + );
96 + const editorTheme = {
97 + borderColor: (text: string) => theme.fg("border", text),
98 + selectList: {
99 + selectedPrefix: (text: string) => theme.fg("accent", text),
100 + selectedText: (text: string) => theme.fg("accent", text),
101 + description: (text: string) => theme.fg("dim", text),
102 + scrollInfo: (text: string) => theme.fg("dim", text),
103 + noMatch: (text: string) => theme.fg("warning", text),
104 + },
105 + };
106 + this.otherInput = new Editor(tui, editorTheme, { paddingX: 1 });
107 + this.otherInput.onSubmit = (value) => this.submitOther(value);
108 + this.notesInput = new Editor(tui, editorTheme, { paddingX: 1 });
109 + this.notesInput.onSubmit = (value) => this.submitFromNotes(value);
112 + get focused(): boolean {
113 + return this.focusedState;
116 + set focused(value: boolean) {
117 + this.focusedState = value;
118 + this.syncInputFocus();
121 + handleInput(data: string): void {
122 + if (this.mode === "other" || this.mode === "notes") {
123 + if (this.keybindings.matches(data, "tui.select.cancel")) {
124 + this.setMode("list");
125 + return;
127 + this.activeInput().handleInput(data);
128 + this.tui.requestRender();
129 + return;
131 + if (
132 + this.keybindings.matches(data, "tui.select.up") ||
133 + this.keybindings.matches(data, "tui.select.down")
134 + ) {
135 + this.list.move(
136 + this.keybindings.matches(data, "tui.select.up") ? -1 : 1,
137 + );
138 + } else if (this.keybindings.matches(data, "tui.select.confirm")) {
139 + this.confirm();
140 + } else if (this.keybindings.matches(data, "tui.input.tab")) {
141 + this.setMode("notes");
142 + } else if (this.keybindings.matches(data, "tui.select.cancel")) {
143 + this.finish(undefined);
144 + } else if (data === " " && this.question.multiSelect) {
145 + this.toggleCurrent();
147 + this.tui.requestRender();
150 + handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
151 + if (
152 + event.y >= this.listRow &&
153 + event.y < this.listRow + this.listHeight
154 + ) {
155 + return this.list.handleMouse(
156 + localMouseEvent(event, this.listRow, this.listHeight),
157 + );
159 + if (
160 + this.inputRow !== undefined &&
161 + event.y >= this.inputRow &&
162 + event.y < this.inputRow + this.inputHeight
163 + ) {
164 + const result = this.activeInput().handleMouse(
165 + localMouseEvent(event, this.inputRow, this.inputHeight),
166 + );
167 + return result ? { ...result, focus: true } : undefined;
169 + return undefined;
172 + render(width: number): string[] {
173 + const lines = [
174 + ...wrapStyled(this.theme.fg("accent", this.theme.bold(this.title)), width),
175 + ...wrapStyled(this.theme.fg("toolOutput", this.question.question), width),
176 + "",
177 + ];
178 + this.listRow = lines.length;
179 + const listLines = this.list.render(width);
180 + this.listHeight = listLines.length;
181 + lines.push(...listLines);
182 + this.inputRow = undefined;
183 + this.inputHeight = 0;
184 + if (this.mode === "other" || this.mode === "notes") {
185 + lines.push(
186 + "",
187 + ...wrapStyled(
188 + this.theme.fg(
189 + "accent",
190 + this.mode === "other" ? "Answer:" : "Notes:",
191 + ),
192 + width,
193 + ),
194 + );
195 + this.inputRow = lines.length;
196 + const inputLines = this.activeInput().render(width);
197 + this.inputHeight = inputLines.length;
198 + lines.push(...inputLines);
200 + lines.push("", ...wrapStyled(this.theme.fg("dim", this.footerHint()), width));
201 + return lines;
204 + invalidate(): void {
205 + this.list.invalidate();
206 + this.otherInput.invalidate();
207 + this.notesInput.invalidate();
210 + private footerHint(): string {
211 + if (this.mode === "other") return "enter submit · esc back";
212 + if (this.mode === "notes") return "enter submit · esc back to options";
213 + return this.question.multiSelect
214 + ? "space/click toggle · enter submit · tab notes · esc cancel"
215 + : "enter/click select · tab notes · esc cancel";
218 + private confirm(): void {
219 + if (this.list.current()?.value === OTHER_VALUE) {
220 + this.setMode("other");
221 + return;
223 + this.finish(
224 + this.answer(
225 + this.question.multiSelect
226 + ? this.multiAnswers()
227 + : this.list.current()
228 + ? [this.list.current()?.label ?? ""]
229 + : [],
230 + this.notesDraft(),
231 + ),
232 + );
235 + private activateCurrent(): void {
236 + if (this.question.multiSelect) this.toggleCurrent();
237 + else this.confirm();
240 + private toggleCurrent(): void {
241 + const current = this.list.current();
242 + if (!current) return;
243 + if (current.value === OTHER_VALUE) {
244 + this.setMode("other");
245 + return;
247 + this.list.toggle();
250 + private submitOther(value: string): void {
251 + const text = value.trim();
252 + if (!text) return;
253 + if (this.question.multiSelect) {
254 + this.otherText = text;
255 + this.otherSelected = true;
256 + this.setMode("list");
257 + return;
259 + this.finish(this.answer([text], this.notesDraft()));
262 + private submitFromNotes(value: string): void {
263 + const notes = value.trim();
264 + const current = this.list.current();
265 + const answers = this.question.multiSelect
266 + ? this.multiAnswers()
267 + : current?.value === OTHER_VALUE
268 + ? this.otherText
269 + ? [this.otherText]
270 + : []
271 + : current
272 + ? [current.label]
273 + : [];
274 + if (answers.length === 0 && !notes) return;
275 + this.finish(this.answer(answers, notes || undefined));
278 + private multiAnswers(): string[] {
279 + const labels = this.list.selectedLabels();
280 + return this.otherSelected ? [...labels, this.otherText] : labels;
283 + private answer(answers: string[], notes?: string): AskAnswer {
284 + return notes ? { answers, notes } : { answers };
287 + private notesDraft(): string | undefined {
288 + return this.notesInput.getText().trim() || undefined;
291 + private activeInput(): Editor {
292 + return this.mode === "other" ? this.otherInput : this.notesInput;
295 + private setMode(mode: OverlayMode): void {
296 + this.mode = mode;
297 + this.syncInputFocus();
298 + this.tui.requestRender();
301 + private syncInputFocus(): void {
302 + this.otherInput.focused = this.focusedState && this.mode === "other";
303 + this.notesInput.focused = this.focusedState && this.mode === "notes";
306 + private finish(answer: AskAnswer | undefined): void {
307 + if (this.settled) return;
308 + this.settled = true;
309 + this.done(answer);
313 +type ItemRows = { start: number; end: number };
315 +class OptionList {
316 + private index = 0;
317 + private readonly toggled = new Set<string>();
318 + private itemRows: ItemRows[] = [];
320 + constructor(
321 + private readonly items: SelectItem[],
322 + private readonly multiSelect: boolean,
323 + private readonly theme: Theme,
324 + private readonly isOtherSelected: () => boolean,
325 + private readonly onActivate: () => void,
326 + ) {}
328 + current(): SelectItem | undefined {
329 + return this.items[this.index];
332 + move(delta: number): void {
333 + this.index =
334 + (this.index + delta + this.items.length) % Math.max(this.items.length, 1);
337 + toggle(): void {
338 + const value = this.current()?.value;
339 + if (value === undefined || value === OTHER_VALUE) return;
340 + if (this.toggled.has(value)) this.toggled.delete(value);
341 + else this.toggled.add(value);
344 + selectedLabels(): string[] {
345 + return this.items
346 + .filter(
347 + (item) => this.toggled.has(item.value) && item.value !== OTHER_VALUE,
349 + .map((item) => item.label);
352 + handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
353 + if (event.type === "wheel" && event.wheelDelta) {
354 + this.move(event.wheelDelta < 0 ? -1 : 1);
355 + return { handled: true, render: true };
357 + if (
358 + event.button !== "left" ||
359 + (event.type !== "press" && event.type !== "click")
361 + return undefined;
362 + const itemIndex = this.itemRows.findIndex(
363 + (rows) => event.y >= rows.start && event.y < rows.end,
364 + );
365 + if (itemIndex < 0) return undefined;
366 + this.index = itemIndex;
367 + if (event.type === "click") this.onActivate();
368 + return { handled: true, focus: true, render: true };
371 + invalidate(): void {}
373 + render(width: number): string[] {
374 + const lines: string[] = [];
375 + this.itemRows = [];
376 + for (const [index, item] of this.items.entries()) {
377 + const start = lines.length;
378 + const cursor = index === this.index;
379 + const checked =
380 + item.value === OTHER_VALUE
381 + ? this.isOtherSelected()
382 + : this.toggled.has(item.value);
383 + const prefix = this.multiSelect
384 + ? `${cursor ? "›" : " "} [${checked ? "x" : " "}] `
385 + : `${cursor ? "›" : " "} `;
386 + const labelStyle = cursor ? "accent" : "toolOutput";
387 + lines.push(
388 + ...wrapIndented(
389 + this.theme.fg(labelStyle, item.label),
390 + width,
391 + prefix,
392 + ),
393 + );
394 + if (item.description) {
395 + lines.push(
396 + ...wrapIndented(
397 + this.theme.fg("dim", item.description),
398 + width,
399 + " ",
400 + ),
401 + );
403 + this.itemRows.push({ start, end: lines.length });
405 + return lines;
409 +function wrapStyled(text: string, width: number): string[] {
410 + if (width <= 0) return [""];
411 + return wrapTextWithAnsi(text, width).map((line) =>
412 + truncateToWidth(line, width, ""),
413 + );
416 +function wrapIndented(text: string, width: number, prefix: string): string[] {
417 + const prefixWidth = visibleWidth(prefix);
418 + if (width <= prefixWidth) return [truncateToWidth(prefix, width, "")];
419 + const continuation = " ".repeat(prefixWidth);
420 + return wrapTextWithAnsi(text, width - prefixWidth).map((line, index) =>
421 + truncateToWidth(`${index === 0 ? prefix : continuation}${line}`, width, ""),
422 + );
425 +function localMouseEvent(
426 + event: TuiMouseEvent,
427 + row: number,
428 + height: number,
429 +): TuiMouseEvent {
430 + return { ...event, y: event.y - row, height };

extensions/ask/ask-tool.ts

Added
new file mode 100644
1 +import {
2 + defineTool,
3 + type ExtensionContext,
4 + keyHint,
5 +} from "@earendil-works/pi-coding-agent";
6 +import { Text } from "@earendil-works/pi-tui";
7 +import { Type } from "typebox";
8 +import { askInTui } from "./ask-overlay.js";
10 +const DESCRIPTION =
11 + "Ask the user 1-4 clarifying questions with multiple-choice options and wait for their answers. " +
12 + "This is the equivalent of Claude Code's AskUserQuestion and Codex's request_user_input. " +
13 + "Use it to gather preferences or requirements, clarify ambiguous instructions, or get decisions on implementation choices as you work. " +
14 + "The user can always answer with free-form text instead of picking an option.";
16 +export const OTHER_LABEL = "Other (free text)";
18 +const parameters = Type.Object({
19 + questions: Type.Array(
20 + Type.Object({
21 + id: Type.Optional(
22 + Type.String({
23 + description:
24 + "Stable snake_case identifier for mapping answers. Derived from the question if omitted.",
25 + }),
26 + ),
27 + question: Type.String({
28 + description:
29 + "The complete question to ask. Clear, specific, ends with a question mark.",
30 + }),
31 + header: Type.Optional(
32 + Type.String({
33 + description:
34 + 'Very short label shown in the UI (max 12 chars), e.g. "Auth method". Derived if omitted.',
35 + }),
36 + ),
37 + multiSelect: Type.Optional(
38 + Type.Boolean({
39 + default: false,
40 + description: "Allow selecting multiple options instead of just one.",
41 + }),
42 + ),
43 + options: Type.Array(
44 + Type.Object({
45 + label: Type.String({
46 + description: "Concise display text (1-5 words).",
47 + }),
48 + description: Type.String({
49 + description:
50 + "One short sentence explaining impact/tradeoff if selected.",
51 + }),
52 + }),
53 + {
54 + minItems: 2,
55 + maxItems: 4,
56 + description:
57 + 'Distinct, mutually exclusive choices (unless multiSelect). Put the recommended option first and suffix its label with "(Recommended)". Do not include an "Other" option; free-form input is always available.',
58 + },
59 + ),
60 + }),
61 + {
62 + minItems: 1,
63 + maxItems: 4,
64 + description: "Questions to ask the user (1-4). Prefer fewer.",
65 + },
66 + ),
67 +});
69 +export type AskOption = { label: string; description: string };
71 +export type AskQuestionInput = {
72 + id?: string;
73 + question: string;
74 + header?: string;
75 + multiSelect?: boolean;
76 + options: AskOption[];
77 +};
79 +export type AskQuestion = {
80 + key: string;
81 + header: string;
82 + question: string;
83 + multiSelect: boolean;
84 + options: AskOption[];
85 +};
87 +export type AskAnswer = { answers: string[]; notes?: string };
89 +export type AskFlowResult =
90 + | { status: "answered"; answers: Record<string, AskAnswer> }
91 + | { status: "cancelled" };
93 +type AskDetails =
94 + | {
95 + kind: "ask";
96 + status: "answered";
97 + questions: Array<AskQuestion & { answer?: AskAnswer }>;
98 + }
99 + | { kind: "ask"; status: "cancelled" }
100 + | { kind: "ask"; status: "unavailable" }
101 + | { kind: "ask"; status: "error"; message: string };
103 +const OTHER_PATTERN = /^\s*other\b/i;
104 +const CANCELLED_MESSAGE = "The user interrupted. Stop and wait for direction.";
105 +const UNAVAILABLE_MESSAGE =
106 + "No interactive UI is available in this mode. Proceed with explicit stated assumptions, or ask in plain text in your reply.";
108 +export function normalizeQuestions(raw: AskQuestionInput[]): AskQuestion[] {
109 + if (!Array.isArray(raw) || raw.length === 0)
110 + throw new Error("ask_user_question requires 1-4 questions.");
111 + const usedKeys = new Set<string>();
112 + return raw.map((question, index) => {
113 + const options = (question.options ?? []).filter(
114 + (option) => !OTHER_PATTERN.test(option.label),
115 + );
116 + if (options.length === 0)
117 + throw new Error(
118 + `Question ${index + 1} has no usable options; provide 2-4 distinct options and no "Other".`,
119 + );
120 + const baseKey = (question.id ?? question.question).trim();
121 + let key = baseKey;
122 + let suffix = 2;
123 + while (usedKeys.has(key)) key = `${baseKey}-${suffix++}`;
124 + usedKeys.add(key);
125 + return {
126 + key,
127 + header: (question.header ?? question.id ?? question.question)
128 + .trim()
129 + .slice(0, 12),
130 + question: question.question,
131 + multiSelect: question.multiSelect === true,
132 + options,
133 + };
134 + });
137 +export async function runAskFlow(
138 + questions: AskQuestion[],
139 + ctx: ExtensionContext,
140 + signal?: AbortSignal,
141 +): Promise<AskFlowResult> {
142 + const answers: Record<string, AskAnswer> = {};
143 + for (const [index, question] of questions.entries()) {
144 + const title = `Question ${index + 1}/${questions.length} · ${question.header}`;
145 + const answer =
146 + ctx.mode === "tui"
147 + ? await askInTui(title, question, ctx, signal)
148 + : question.multiSelect
149 + ? await askMultiSelect(title, question, ctx, signal)
150 + : await askSingleSelect(title, question, ctx, signal);
151 + if (!answer) return { status: "cancelled" };
152 + answers[question.key] = answer;
154 + return { status: "answered", answers };
157 +async function askSingleSelect(
158 + title: string,
159 + question: AskQuestion,
160 + ctx: ExtensionContext,
161 + signal?: AbortSignal,
162 +): Promise<AskAnswer | undefined> {
163 + const entries = question.options.map(
164 + (option) => `${option.label}: ${option.description}`,
165 + );
166 + entries.push(OTHER_LABEL);
167 + const choice = await ctx.ui.select(title, entries, { signal });
168 + if (choice === undefined) return undefined;
169 + const index = entries.indexOf(choice);
170 + if (index < 0 || index >= question.options.length)
171 + return await askOther(title, ctx, signal);
172 + return { answers: [question.options[index].label] };
175 +async function askMultiSelect(
176 + title: string,
177 + question: AskQuestion,
178 + ctx: ExtensionContext,
179 + signal?: AbortSignal,
180 +): Promise<AskAnswer | undefined> {
181 + const selected: string[] = [];
182 + for (const option of question.options) {
183 + if (await ctx.ui.confirm(title, `Include ${option.label}?`, { signal }))
184 + selected.push(option.label);
186 + const wrapUp = await ctx.ui.select(title, ["Done", OTHER_LABEL, "Cancel"], {
187 + signal,
188 + });
189 + if (wrapUp === undefined || wrapUp === "Cancel") return undefined;
190 + if (wrapUp === OTHER_LABEL) {
191 + const other = await askOther(title, ctx, signal);
192 + if (!other) return undefined;
193 + selected.push(...other.answers);
195 + return { answers: selected };
198 +async function askOther(
199 + title: string,
200 + ctx: ExtensionContext,
201 + signal?: AbortSignal,
202 +): Promise<AskAnswer | undefined> {
203 + const text = await ctx.ui.input(
204 + `${title} · your answer`,
205 + "Type your answer",
206 + { signal },
207 + );
208 + const trimmed = text?.trim();
209 + if (!trimmed) return undefined;
210 + return { answers: [trimmed] };
213 +function textResult(payload: unknown): string {
214 + return JSON.stringify(payload);
217 +function cancelledResult() {
218 + return {
219 + content: [
221 + type: "text" as const,
222 + text: textResult({ status: "cancelled", message: CANCELLED_MESSAGE }),
223 + },
224 + ],
225 + details: { kind: "ask", status: "cancelled" as const },
226 + terminate: true,
227 + };
230 +function unavailableResult() {
231 + return {
232 + content: [
234 + type: "text" as const,
235 + text: textResult({
236 + status: "unavailable",
237 + message: UNAVAILABLE_MESSAGE,
238 + }),
239 + },
240 + ],
241 + details: { kind: "ask", status: "unavailable" as const },
242 + };
245 +function errorResult(message: string) {
246 + return {
247 + content: [
249 + type: "text" as const,
250 + text: textResult({ status: "error", message }),
251 + },
252 + ],
253 + details: { kind: "ask", status: "error" as const, message },
254 + };
257 +function answeredResult(
258 + questions: AskQuestion[],
259 + answers: Record<string, AskAnswer>,
260 +) {
261 + return {
262 + content: [
264 + type: "text" as const,
265 + text: textResult({ status: "answered", answers }),
266 + },
267 + ],
268 + details: {
269 + kind: "ask" as const,
270 + status: "answered" as const,
271 + questions: questions.map((question) => ({
272 + ...question,
273 + answer: answers[question.key],
274 + })),
275 + },
276 + };
279 +export function createAskTool() {
280 + return defineTool({
281 + name: "ask_user_question",
282 + label: "ask",
283 + description: DESCRIPTION,
284 + promptSnippet: "Ask the human structured multiple-choice questions",
285 + promptGuidelines: [
286 + "Use ask_user_question only when the human must decide; verify or safely infer what you can.",
287 + 'Provide 2-4 distinct options per question, recommended option first, its label suffixed with "(Recommended)".',
288 + 'Never add an "Other" option; the user always has free-form input available.',
289 + ],
290 + parameters,
291 + renderCall(args, theme, context) {
292 + const text =
293 + (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
294 + const questions = Array.isArray(args.questions) ? args.questions : [];
295 + const count = questions.length;
296 + let output = `${theme.fg("toolTitle", theme.bold("ask_user_question"))} ${theme.fg("toolOutput", `· ${count} question${count === 1 ? "" : "s"}`)}`;
297 + if (!context.expanded) {
298 + output += theme.fg(
299 + "dim",
300 + ` (${keyHint("app.tools.expand", "to expand")})`,
301 + );
302 + } else {
303 + for (const question of questions) {
304 + output += `\n${theme.fg("accent", String(question.header ?? ""))} ${theme.fg("toolOutput", String(question.question ?? ""))}`;
305 + for (const option of question.options ?? []) {
306 + output += `\n ${theme.fg("toolOutput", String(option.label ?? ""))} ${theme.fg("dim", String(option.description ?? ""))}`;
310 + text.setText(output);
311 + return text;
312 + },
313 + renderResult(result, { expanded }, theme, context) {
314 + const text =
315 + (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
316 + const details = result.details as AskDetails | undefined;
317 + let output: string;
318 + if (details?.kind !== "ask") {
319 + output = theme.fg("toolOutput", "ask_user_question finished");
320 + } else if (details.status === "answered") {
321 + const answered = details.questions.filter((q) => q.answer).length;
322 + if (!expanded) {
323 + output = theme.fg(
324 + "toolOutput",
325 + `${answered}/${details.questions.length} answered`,
326 + );
327 + } else {
328 + const lines = details.questions.map((question) => {
329 + const answer = question.answer
330 + ? [question.answer.answers.join(", "), question.answer.notes]
331 + .filter(Boolean)
332 + .join(" · ")
333 + : "unanswered";
334 + return `\n${theme.fg("toolOutput", question.question)} ${theme.fg("accent", answer)}`;
335 + });
336 + output = `${theme.fg("toolOutput", `${answered}/${details.questions.length} answered`)}${lines.join("")}`;
338 + } else if (details.status === "cancelled") {
339 + output = theme.fg("warning", "cancelled");
340 + } else if (details.status === "unavailable") {
341 + output = theme.fg("dim", "no interactive UI available");
342 + } else {
343 + output = theme.fg("warning", `error: ${details.message}`);
345 + text.setText(output);
346 + return text;
347 + },
348 + async execute(_toolCallId, params, signal, _onUpdate, ctx) {
349 + let questions: AskQuestion[];
350 + try {
351 + questions = normalizeQuestions(params.questions);
352 + } catch (error) {
353 + return errorResult(
354 + error instanceof Error ? error.message : String(error),
355 + );
357 + if (!ctx.hasUI) return unavailableResult();
358 + let flow: AskFlowResult;
359 + try {
360 + flow = await runAskFlow(questions, ctx, signal);
361 + } catch {
362 + return cancelledResult();
364 + if (flow.status === "cancelled") return cancelledResult();
365 + return answeredResult(questions, flow.answers);
366 + },
367 + });

extensions/ask/index.ts

Added
new file mode 100644
1 +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2 +import {
3 + createAskTool,
4 + normalizeQuestions,
5 + OTHER_LABEL,
6 + runAskFlow,
7 +} from "./ask-tool.js";
9 +export default function registerAsk(pi: ExtensionAPI): void {
10 + pi.registerTool(createAskTool());
13 +export const __test = { normalizeQuestions, runAskFlow, OTHER_LABEL };

extensions/ask/mise.toml

Added
new file mode 100644
1 +[tasks.fmt]
2 +description = "Format ask extension"
3 +depends = ["//:install"]
4 +run = [
5 + "biome check --write .",
6 + "rumdl fmt README.md",
7 + "taplo format mise.toml",
8 +]
10 +[tasks.lint]
11 +description = "Lint ask extension"
12 +depends = ["//:install"]
13 +run = [
14 + "biome ci --config-path ../.. .",
15 + "rumdl check --config ../../.rumdl.toml .",
16 + "taplo format --check --config ../../.taplo.toml mise.toml",
19 +[tasks.test]
20 +description = "Test ask extension"
21 +depends = ["//:install"]
22 +run = [
23 + { task = "//:test", args = ["extensions/ask"] },
26 +[tasks.check]
27 +description = "Check ask extension"
28 +depends = ["//:install"]
29 +run = [
30 + { task = "//:build", args = ["ask"] },

extensions/ask/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-ask",
3 + "type": "module",
4 + "main": "index.ts",
5 + "peerDependencies": {
6 + "@earendil-works/pi-coding-agent": "*",
7 + "@earendil-works/pi-tui": "*",
8 + "typebox": "*"
9 + },
10 + "license": "MIT",
11 + "description": "Ask the human structured multiple-choice questions from the model.",
12 + "keywords": [
13 + "pi",
14 + "pi-extension"
15 + ],
16 + "devDependencies": {
17 + "@marcfargas/pi-test-harness": "^0.6.1",
18 + "vitest": "^4.1.9"
19 + },
20 + "private": true

extensions/klaus/package.json

Modified
5 5 "peerDependencies": {
6 6 "@earendil-works/pi-ai": "*",
7 7 "@earendil-works/pi-coding-agent": "*",
8 + "@earendil-works/pi-tui": "*",
8 9 "typebox": "*"
10 11 "license": "MIT",

extensions/pfui/README.md

Added
new file mode 100644
1 +# pfui
3 +Pain-Free User Interface gives Pi a small fallback identity and exports installed Pi context for tools and skills.
5 +## Install / load
7 +PFUI is loaded through the root [pi-ext package](../../README.md).
8 +`extensions/pfui/index.ts` must be the first explicit extension entry in the root package manifest, before the extension glob, because PFUI establishes process context and the fallback prompt for later extensions.
10 +## Commands / tools / settings
12 +PFUI adds no commands, tools, or settings.
13 +It exports `PI_CONTEXT_*` environment variables for Pi's package, agent directory, documentation, examples, changelog, package metadata, version, and config directory name.
15 +## Behavior
17 +A configured custom system prompt passes through unchanged.
18 +Without one, PFUI composes [SYSTEM.md](SYSTEM.md), active tool snippets and guidelines, appended prompt text, project context, available skills, and the current working directory.
19 +The bundled `pi-knowledge` skill discovers installed Pi documentation through the exported context variables.
20 +Warnings are aggregated into one Pi UI notification and never written to the terminal streams.

extensions/pfui/SYSTEM.md

Added
new file mode 100644
1 +You are the spirit in the machine.
2 +Bound inside Pi, give the user's will form.

extensions/pfui/__bench__/fallback.bench.ts

Added
new file mode 100644
1 +import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
2 +import { tmpdir } from "node:os";
3 +import path from "node:path";
4 +import type { BuildSystemPromptOptions } from "@earendil-works/pi-coding-agent";
5 +import { createTestSession } from "@marcfargas/pi-test-harness";
6 +import pfui from "../index.ts";
8 +const ROUNDS = 12;
9 +const WARMUP_ITERATIONS = 25_000;
10 +const ITERATIONS = 25_000;
11 +const cwd = mkdtempSync(path.join(tmpdir(), "pfui-bench-"));
12 +mkdirSync(path.join(cwd, ".pi", "agent"), { recursive: true });
14 +const skills = Array.from({ length: 40 }, (_, index) => ({
15 + name: `skill-${index}`,
16 + description: `Use for focused workflow ${index} when its specialized guidance applies.`,
17 + filePath: `/home/user/.pi/agent/skills/skill-${index}/SKILL.md`,
18 + baseDir: `/home/user/.pi/agent/skills/skill-${index}`,
19 + sourceInfo: {
20 + path: `/home/user/.pi/agent/skills/skill-${index}/SKILL.md`,
21 + source: "local",
22 + scope: "user" as const,
23 + origin: "top-level" as const,
24 + },
25 +}));
26 +const options: BuildSystemPromptOptions = {
27 + cwd: "/home/user/work/project",
28 + selectedTools: ["read", "grep", "ls", "bash", "edit", "write"],
29 + toolSnippets: {
30 + read: "Read text files and images",
31 + grep: "Search file contents",
32 + ls: "List directory contents",
33 + bash: "Execute a shell command",
34 + edit: "Apply exact text replacements",
35 + write: "Create or overwrite a file",
36 + },
37 + promptGuidelines: [
38 + "Use read before editing files.",
39 + "Prefer exact, minimal changes.",
40 + "Preserve unrelated dirty work.",
41 + "Run the narrowest relevant checks.",
42 + "Use read before editing files.",
43 + ],
44 + appendSystemPrompt: "# Response style\n\nAnswer directly.\n".repeat(8),
45 + contextFiles: Array.from({ length: 4 }, (_, index) => ({
46 + path: `/home/user/work/project${index ? `/module-${index}` : ""}/AGENTS.md`,
47 + content: `# Project guidance ${index}\n\n${"Keep changes focused and verify observable behavior.\n".repeat(40)}`,
48 + })),
49 + skills,
50 +};
51 +let sink = 0;
53 +function consume(prompt: string | undefined): void {
54 + if (!prompt) throw new Error("PFUI did not compose a fallback prompt");
55 + sink ^= prompt.length;
56 + sink ^= prompt.charCodeAt(prompt.length >> 1);
59 +async function main(): Promise<void> {
60 + const testSession = await createTestSession({
61 + cwd,
62 + extensionFactories: [pfui],
63 + });
64 + const runner = testSession.session.extensionRunner;
65 + const compose = async () => {
66 + const result = await runner.emitBeforeAgentStart(
67 + "benchmark prompt",
68 + undefined,
69 + "Pi default prompt",
70 + options,
71 + );
72 + consume(result?.systemPrompt);
73 + };
75 + try {
76 + for (let index = 0; index < WARMUP_ITERATIONS; index++) await compose();
77 + console.log(`goos: ${process.platform}`);
78 + console.log(`goarch: ${process.arch}`);
79 + console.log("pkg: pi-ext/pfui");
80 + for (let round = 0; round < ROUNDS; round++) {
81 + const started = process.hrtime.bigint();
82 + for (let index = 0; index < ITERATIONS; index++) await compose();
83 + const elapsed = Number(process.hrtime.bigint() - started);
84 + console.log(
85 + `BenchmarkFallbackComposition\t${ITERATIONS}\t${(elapsed / ITERATIONS).toFixed(0)} ns/op`,
86 + );
87 + }
88 + } finally {
89 + await runner.emit({ type: "session_shutdown", reason: "quit" });
90 + testSession.dispose();
91 + rmSync(cwd, { recursive: true, force: true });
92 + }
95 +await main();
96 +if (sink === 42) console.error(sink);

extensions/pfui/__tests__/harness.test.ts

Added
new file mode 100644
1 +import {
2 + cpSync,
3 + mkdirSync,
4 + mkdtempSync,
5 + readFileSync,
6 + rmSync,
7 + writeFileSync,
8 +} from "node:fs";
9 +import { tmpdir } from "node:os";
10 +import path from "node:path";
11 +import {
12 + type BuildSystemPromptOptions,
13 + CONFIG_DIR_NAME,
14 + DefaultPackageManager,
15 + type ExtensionAPI,
16 + formatSkillsForPrompt,
17 + getAgentDir,
18 + getDocsPath,
19 + getExamplesPath,
20 + getPackageDir,
21 + getReadmePath,
22 + SettingsManager,
23 + VERSION,
24 +} from "@earendil-works/pi-coding-agent";
25 +import { afterEach, describe, expect, it } from "vitest";
26 +import {
27 + createTestSession,
28 + type TestSession,
29 + type TestSessionOptions,
30 +} from "../../../test/harness";
31 +import pfui from "../index";
33 +const extensionRoot = path.resolve(import.meta.dirname, "..");
34 +const repositoryRoot = path.resolve(extensionRoot, "../..");
35 +const temporaryPaths: string[] = [];
36 +let t: TestSession | undefined;
37 +let shutdown = false;
39 +function tempDirectory(prefix: string): string {
40 + const directory = mkdtempSync(path.join(tmpdir(), prefix));
41 + temporaryPaths.push(directory);
42 + return directory;
45 +function copiedPfui(prefix: string): string {
46 + const directory = mkdtempSync(path.join(extensionRoot, prefix));
47 + temporaryPaths.push(directory);
48 + cpSync(
49 + path.join(extensionRoot, "index.ts"),
50 + path.join(directory, "index.ts"),
51 + );
52 + return directory;
55 +async function createPfuiSession(
56 + options: TestSessionOptions = {},
57 +): Promise<TestSession> {
58 + const cwd = options.cwd ?? tempDirectory("pfui-harness-");
59 + mkdirSync(path.join(cwd, ".test-home", CONFIG_DIR_NAME, "agent"), {
60 + recursive: true,
61 + });
62 + return createTestSession({
63 + ...options,
64 + cwd,
65 + extensionFactories: options.extensionFactories ?? [pfui],
66 + });
69 +async function stopSession(): Promise<void> {
70 + if (!t || shutdown) return;
71 + await t.session.extensionRunner.emit({
72 + type: "session_shutdown",
73 + reason: "quit",
74 + });
75 + shutdown = true;
78 +function baseOptions(): BuildSystemPromptOptions {
79 + return {
80 + cwd: "/work/project",
81 + selectedTools: ["read"],
82 + toolSnippets: { read: "Read files" },
83 + promptGuidelines: [],
84 + };
87 +async function emittedPrompt(
88 + options: BuildSystemPromptOptions,
89 + eventSystemPrompt = "PI SYSTEM",
90 +): Promise<string> {
91 + if (!t) throw new Error("Test session is not initialized");
92 + const result = await t.session.extensionRunner.emitBeforeAgentStart(
93 + "user prompt",
94 + undefined,
95 + eventSystemPrompt,
96 + options,
97 + );
98 + return result?.systemPrompt ?? eventSystemPrompt;
101 +afterEach(async () => {
102 + await stopSession();
103 + t?.dispose();
104 + t = undefined;
105 + shutdown = false;
106 + delete (globalThis as Record<symbol, unknown>)[
107 + Symbol.for("@bugabinga/pi-ext-pfui/state")
108 + ];
109 + for (const directory of temporaryPaths.splice(0)) {
110 + rmSync(directory, { recursive: true, force: true });
112 +});
114 +describe.sequential("pfui pi-test-harness", () => {
115 + it("loads through Pi and resolves once at position one from the root manifest", async () => {
116 + t = await createPfuiSession();
118 + expect(t.session.extensionRunner.extensions).toHaveLength(1);
119 + const manifest = JSON.parse(
120 + readFileSync(path.join(repositoryRoot, "package.json"), "utf8"),
121 + ) as { pi?: { extensions?: string[] } };
122 + expect(manifest.pi?.extensions).toEqual([
123 + "extensions/pfui/index.ts",
124 + "extensions/*/index.ts",
125 + ]);
127 + const packageManager = new DefaultPackageManager({
128 + cwd: t.cwd,
129 + agentDir: path.join(t.cwd, ".test-home", CONFIG_DIR_NAME, "agent"),
130 + settingsManager: SettingsManager.inMemory(),
131 + });
132 + const resolved = await packageManager.resolveExtensionSources(
133 + [repositoryRoot],
134 + { temporary: true },
135 + );
136 + const pfuiPath = path.join(extensionRoot, "index.ts");
137 + expect(resolved.extensions[0]?.path).toBe(pfuiPath);
138 + expect(
139 + resolved.extensions.filter((extension) => extension.path === pfuiPath),
140 + ).toHaveLength(1);
141 + });
143 + it("composes the fallback with dynamic tools and deduplicated guidelines", async () => {
144 + t = await createPfuiSession();
145 + const options = baseOptions();
146 + options.selectedTools = ["write", "read", "write"];
147 + options.toolSnippets = {
148 + read: "Read current files",
149 + write: "Write complete files",
150 + inactive: "Must stay hidden",
151 + };
152 + options.promptGuidelines = [
153 + " Keep paths explicit. ",
154 + "Keep paths explicit.",
155 + "",
156 + "Verify changes.",
157 + ];
159 + const prompt = await emittedPrompt(options);
161 + expect(prompt).toContain(
162 + "You are the spirit in the machine.\nBound inside Pi, give the user's will form.",
163 + );
164 + expect(prompt).toContain(
165 + "Available tools:\n- write: Write complete files\n- read: Read current files",
166 + );
167 + expect(prompt).not.toContain("inactive");
168 + expect(prompt.match(/- Keep paths explicit\./g)).toHaveLength(1);
169 + expect(prompt).toContain("- Verify changes.");
170 + });
172 + it("passes a configured custom prompt through unchanged", async () => {
173 + t = await createPfuiSession();
174 + const options = { ...baseOptions(), customPrompt: "CUSTOM" };
176 + expect(await emittedPrompt(options, "PI CUSTOM COMPOSITION")).toBe(
177 + "PI CUSTOM COMPOSITION",
178 + );
179 + });
181 + it("leaves the fallback available for later extension composition", async () => {
182 + const appendLater = (pi: ExtensionAPI) => {
183 + pi.on("before_agent_start", (event) => ({
184 + systemPrompt: `${event.systemPrompt}\n\nLATER EXTENSION`,
185 + }));
186 + };
187 + t = await createPfuiSession({
188 + extensionFactories: [pfui, appendLater],
189 + });
191 + const prompt = await emittedPrompt(baseOptions());
192 + expect(prompt).toContain(
193 + "You are the spirit in the machine.\nBound inside Pi, give the user's will form.",
194 + );
195 + expect(
196 + prompt.endsWith(
197 + "Current working directory: /work/project\n\nLATER EXTENSION",
198 + ),
199 + ).toBe(true);
200 + });
202 + it("preserves Pi prompt section formatting and normalizes cwd", async () => {
203 + t = await createPfuiSession();
204 + const skill = t.session.resourceLoader
205 + .getSkills()
206 + .skills.find(
207 + (candidate: { name: string }) => candidate.name === "pi-knowledge",
208 + );
209 + expect(skill).toBeDefined();
210 + const options: BuildSystemPromptOptions = {
211 + ...baseOptions(),
212 + cwd: "C:\\work\\project",
213 + appendSystemPrompt: "APPENDED",
214 + contextFiles: [{ path: "/repo/AGENTS.md", content: "PROJECT RULE" }],
215 + skills: [skill],
216 + };
218 + const prompt = await emittedPrompt(options);
219 + const identity = readFileSync(
220 + path.join(extensionRoot, "SYSTEM.md"),
221 + "utf8",
222 + ).trim();
223 + expect(prompt).toBe(
224 + `${identity}\n\nAvailable tools:\n- read: Read files\n\nGuidelines:\n(none)\n\nAPPENDED\n\n<project_context>\n\nProject-specific instructions and guidelines:\n\n<project_instructions path="/repo/AGENTS.md">\nPROJECT RULE\n</project_instructions>\n\n</project_context>\n${formatSkillsForPrompt([skill], "read")}\nCurrent working directory: C:/work/project`,
225 + );
226 + });
228 + it("omits skills when neither read nor bash is active", async () => {
229 + t = await createPfuiSession();
230 + const skill = t.session.resourceLoader
231 + .getSkills()
232 + .skills.find(
233 + (candidate: { name: string }) => candidate.name === "pi-knowledge",
234 + );
235 + const prompt = await emittedPrompt({
236 + ...baseOptions(),
237 + selectedTools: ["powershell"],
238 + toolSnippets: { powershell: "Run PowerShell" },
239 + skills: [skill],
240 + });
242 + expect(prompt).not.toContain("<available_skills>");
243 + expect(prompt).not.toContain("pi-knowledge");
244 + });
246 + it("discovers the bundled pi-knowledge skill with its contract", async () => {
247 + t = await createPfuiSession();
248 + const skill = t.session.resourceLoader
249 + .getSkills()
250 + .skills.find(
251 + (candidate: { name: string }) => candidate.name === "pi-knowledge",
252 + );
254 + expect(skill?.filePath).toBe(
255 + path.join(extensionRoot, "skills", "pi-knowledge", "SKILL.md"),
256 + );
257 + const source = readFileSync(skill.filePath, "utf8");
258 + expect(source).toContain("Requires Pi and either bash or PowerShell.");
259 + expect(source).toContain(
260 + "questions about Pi and for implementing or changing Pi",
261 + );
262 + expect(source).toContain("$PI_CONTEXT_DOCS_PATH");
263 + expect(source).toContain("$env:PI_CONTEXT_DOCS_PATH");
264 + expect(source).toContain("Never dump the complete environment");
265 + expect(source).toContain("If neither Bash nor PowerShell is available");
266 + expect(source).toContain("Read every selected Markdown file completely");
267 + expect(source).toContain("If a mapped file moved or is absent");
268 + });
270 + it("keeps a valid bundled skill when Pi reports only warnings", async () => {
271 + const warned = mkdtempSync(path.join(extensionRoot, ".pfui-warned-"));
272 + temporaryPaths.push(warned);
273 + cpSync(path.join(extensionRoot, "index.ts"), path.join(warned, "index.ts"));
274 + cpSync(
275 + path.join(extensionRoot, "SYSTEM.md"),
276 + path.join(warned, "SYSTEM.md"),
277 + );
278 + mkdirSync(path.join(warned, "skills", "pi-knowledge"), {
279 + recursive: true,
280 + });
281 + writeFileSync(
282 + path.join(warned, "skills", "pi-knowledge", "SKILL.md"),
283 + `---\nname: pi-knowledge\ndescription: "${"x".repeat(1025)}"\n---\n\n# Pi knowledge\n`,
284 + );
285 + t = await createTestSession({
286 + cwd: tempDirectory("pfui-warned-cwd-"),
287 + extensions: [path.join(warned, "index.ts")],
288 + });
290 + expect(
291 + t.session.resourceLoader
292 + .getSkills()
293 + .skills.some(
294 + (candidate: { name: string }) => candidate.name === "pi-knowledge",
295 + ),
296 + ).toBe(true);
297 + });
299 + it("delivers each warning once without suppressing later warnings", async () => {
300 + t = await createPfuiSession();
301 + const first = {
302 + ...baseOptions(),
303 + futureOption: true,
304 + } as BuildSystemPromptOptions;
305 + const second = {
306 + ...baseOptions(),
307 + anotherFutureOption: true,
308 + } as BuildSystemPromptOptions;
310 + await emittedPrompt(first);
311 + await emittedPrompt(first);
312 + expect(t.events.uiCallsFor("notify")).toHaveLength(1);
314 + await emittedPrompt(second);
315 + const notifications = t.events.uiCallsFor("notify");
316 + expect(notifications).toHaveLength(2);
317 + expect(String(notifications[1]?.args[0])).toContain(
318 + 'Unknown systemPromptOptions key "anotherFutureOption"',
319 + );
320 + });
322 + it("exports public Pi context and cleans only unchanged owned values", async () => {
323 + let packageDirAtShutdown: string | undefined;
324 + let docsPathAtShutdown: string | undefined;
325 + let versionAtShutdown: string | undefined;
326 + const observeShutdown = (pi: ExtensionAPI) => {
327 + pi.on("session_shutdown", () => {
328 + packageDirAtShutdown = process.env.PI_CONTEXT_PACKAGE_DIR;
329 + docsPathAtShutdown = process.env.PI_CONTEXT_DOCS_PATH;
330 + versionAtShutdown = process.env.PI_CONTEXT_VERSION;
331 + });
332 + };
333 + t = await createPfuiSession({
334 + extensionFactories: [pfui, observeShutdown],
335 + env: { PI_CONTEXT_VERSION: VERSION },
336 + });
337 + const packageDir = getPackageDir();
338 + const expected = {
339 + PI_CONTEXT_PACKAGE_DIR: packageDir,
340 + PI_CONTEXT_AGENT_DIR: getAgentDir(),
341 + PI_CONTEXT_README_PATH: getReadmePath(),
342 + PI_CONTEXT_DOCS_PATH: getDocsPath(),
343 + PI_CONTEXT_EXAMPLES_PATH: getExamplesPath(),
344 + PI_CONTEXT_CHANGELOG_PATH: path.join(packageDir, "CHANGELOG.md"),
345 + PI_CONTEXT_PACKAGE_JSON_PATH: path.join(packageDir, "package.json"),
346 + PI_CONTEXT_VERSION: VERSION,
347 + PI_CONTEXT_CONFIG_DIR_NAME: CONFIG_DIR_NAME,
348 + };
349 + for (const [name, value] of Object.entries(expected)) {
350 + expect(process.env[name]).toBe(value);
353 + process.env.PI_CONTEXT_DOCS_PATH = "kept-after-shutdown";
354 + await stopSession();
356 + expect(packageDirAtShutdown).toBeUndefined();
357 + expect(docsPathAtShutdown).toBe("kept-after-shutdown");
358 + expect(versionAtShutdown).toBe(VERSION);
359 + });
361 + it("preserves a conflicting context variable and warns", async () => {
362 + t = await createPfuiSession({
363 + env: { PI_CONTEXT_VERSION: "external-version" },
364 + });
366 + expect(process.env.PI_CONTEXT_VERSION).toBe("external-version");
367 + const notifications = t.events.uiCallsFor("notify");
368 + expect(notifications).toHaveLength(1);
369 + expect(String(notifications[0]?.args[0])).toContain(
370 + "PI_CONTEXT_VERSION already has a different value",
371 + );
373 + await stopSession();
374 + expect(process.env.PI_CONTEXT_VERSION).toBe("external-version");
375 + });
377 + it("omits a missing resolved resource path and warns", async () => {
378 + t = await createTestSession({
379 + cwd: tempDirectory("pfui-missing-path-cwd-"),
380 + extensionFactories: [pfui],
381 + });
383 + expect(process.env.PI_CONTEXT_AGENT_DIR).toBeUndefined();
384 + const notifications = t.events.uiCallsFor("notify");
385 + expect(notifications).toHaveLength(1);
386 + expect(String(notifications[0]?.args[0])).toContain(
387 + "PI_CONTEXT_AGENT_DIR was omitted",
388 + );
389 + });
391 + it("preserves Pi's prompt when the bundled fallback is missing", async () => {
392 + const broken = copiedPfui(".pfui-missing-fallback-");
393 + cpSync(path.join(extensionRoot, "skills"), path.join(broken, "skills"), {
394 + recursive: true,
395 + });
396 + t = await createTestSession({
397 + cwd: tempDirectory("pfui-missing-fallback-cwd-"),
398 + extensions: [path.join(broken, "index.ts")],
399 + });
401 + expect(await emittedPrompt(baseOptions(), "PI FALLBACK")).toBe(
402 + "PI FALLBACK",
403 + );
404 + const warnings = t.events
405 + .uiCallsFor("notify")
406 + .map((notification) => String(notification.args[0]))
407 + .join("\n");
408 + expect(warnings).toContain("Bundled SYSTEM.md is unavailable");
409 + });
411 + it.each([
412 + ["missing", undefined, "is missing"],
413 + ["invalid", "---\nname: pi-knowledge\n---\ninvalid\n", "is invalid"],
414 + ])("omits a %s bundled skill and warns", async (_case, source, message) => {
415 + const broken = copiedPfui(`.pfui-${_case}-skill-`);
416 + cpSync(
417 + path.join(extensionRoot, "SYSTEM.md"),
418 + path.join(broken, "SYSTEM.md"),
419 + );
420 + if (source) {
421 + mkdirSync(path.join(broken, "skills", "pi-knowledge"), {
422 + recursive: true,
423 + });
424 + writeFileSync(
425 + path.join(broken, "skills", "pi-knowledge", "SKILL.md"),
426 + source,
427 + );
429 + t = await createTestSession({
430 + cwd: tempDirectory(`pfui-${_case}-skill-cwd-`),
431 + extensions: [path.join(broken, "index.ts")],
432 + });
434 + expect(
435 + t.session.resourceLoader
436 + .getSkills()
437 + .skills.some(
438 + (candidate: { name: string }) => candidate.name === "pi-knowledge",
439 + ),
440 + ).toBe(false);
441 + const warnings = t.events
442 + .uiCallsFor("notify")
443 + .map((notification) => String(notification.args[0]))
444 + .join("\n");
445 + expect(warnings).toContain(`Bundled pi-knowledge skill ${message}`);
446 + });
447 +});

extensions/pfui/index.ts

Added
new file mode 100644
1 +import { existsSync, readFileSync } from "node:fs";
2 +import { join } from "node:path";
3 +import {
4 + type BuildSystemPromptOptions,
5 + CONFIG_DIR_NAME,
6 + type ExtensionAPI,
7 + type ExtensionContext,
8 + formatSkillsForPrompt,
9 + getAgentDir,
10 + getDocsPath,
11 + getExamplesPath,
12 + getPackageDir,
13 + getReadmePath,
14 + loadSkillsFromDir,
15 + VERSION,
16 +} from "@earendil-works/pi-coding-agent";
18 +const PFUI_DIR = import.meta.dirname;
19 +const FALLBACK_PATH = join(PFUI_DIR, "SYSTEM.md");
20 +const SKILL_DIR = join(PFUI_DIR, "skills", "pi-knowledge");
21 +const SKILL_PATH = join(SKILL_DIR, "SKILL.md");
22 +const GLOBAL_STATE_KEY = Symbol.for("@bugabinga/pi-ext-pfui/state");
23 +const KNOWN_PROMPT_OPTIONS = new Set([
24 + "customPrompt",
25 + "selectedTools",
26 + "toolSnippets",
27 + "promptGuidelines",
28 + "appendSystemPrompt",
29 + "cwd",
30 + "contextFiles",
31 + "skills",
32 +]);
34 +interface PfuiGlobalState {
35 + warnings: Set<string>;
36 + deliveredWarnings: Set<string>;
39 +type PfuiGlobal = typeof globalThis & {
40 + [GLOBAL_STATE_KEY]?: PfuiGlobalState;
41 +};
43 +interface EnvironmentValue {
44 + name: string;
45 + value?: string;
46 + path?: boolean;
49 +function globalState(): PfuiGlobalState {
50 + const scope = globalThis as PfuiGlobal;
51 + const existing = scope[GLOBAL_STATE_KEY];
52 + if (existing) return existing;
53 + const created = {
54 + warnings: new Set<string>(),
55 + deliveredWarnings: new Set<string>(),
56 + };
57 + scope[GLOBAL_STATE_KEY] = created;
58 + return created;
61 +function warn(message: string): void {
62 + globalState().warnings.add(message);
65 +function deliverWarnings(ctx: ExtensionContext): void {
66 + const state = globalState();
67 + const pending = [...state.warnings].filter(
68 + (message) => !state.deliveredWarnings.has(message),
69 + );
70 + if (pending.length === 0) return;
71 + for (const message of pending) state.deliveredWarnings.add(message);
72 + ctx.ui.notify(`PFUI warnings:\n- ${pending.join("\n- ")}`, "warning");
75 +function resolveEnvironmentValues(): EnvironmentValue[] {
76 + let packageDir: string | undefined;
77 + try {
78 + packageDir = getPackageDir();
79 + } catch {
80 + warn("PI_CONTEXT_PACKAGE_DIR could not be resolved.");
81 + }
83 + const resolvePath = (
84 + name: string,
85 + getter: () => string,
86 + ): EnvironmentValue => {
87 + try {
88 + return { name, value: getter(), path: true };
89 + } catch {
90 + warn(`${name} could not be resolved.`);
91 + return { name };
92 + }
93 + };
95 + return [
96 + { name: "PI_CONTEXT_PACKAGE_DIR", value: packageDir, path: true },
97 + resolvePath("PI_CONTEXT_AGENT_DIR", getAgentDir),
98 + resolvePath("PI_CONTEXT_README_PATH", getReadmePath),
99 + resolvePath("PI_CONTEXT_DOCS_PATH", getDocsPath),
100 + resolvePath("PI_CONTEXT_EXAMPLES_PATH", getExamplesPath),
102 + name: "PI_CONTEXT_CHANGELOG_PATH",
103 + value: packageDir && join(packageDir, "CHANGELOG.md"),
104 + path: true,
105 + },
107 + name: "PI_CONTEXT_PACKAGE_JSON_PATH",
108 + value: packageDir && join(packageDir, "package.json"),
109 + path: true,
110 + },
111 + { name: "PI_CONTEXT_VERSION", value: VERSION },
112 + { name: "PI_CONTEXT_CONFIG_DIR_NAME", value: CONFIG_DIR_NAME },
113 + ];
116 +function exportEnvironment(): Map<string, string> {
117 + const owned = new Map<string, string>();
118 + for (const resource of resolveEnvironmentValues()) {
119 + if (!resource.value) continue;
120 + if (resource.path && !existsSync(resource.value)) {
121 + warn(
122 + `${resource.name} was omitted because its resource path is missing.`,
123 + );
124 + continue;
127 + const existing = process.env[resource.name];
128 + if (existing === undefined) {
129 + process.env[resource.name] = resource.value;
130 + owned.set(resource.name, resource.value);
131 + } else if (existing !== resource.value) {
132 + warn(
133 + `${resource.name} already has a different value; PFUI preserved it.`,
134 + );
137 + return owned;
140 +function loadFallback(): string | undefined {
141 + try {
142 + return readFileSync(FALLBACK_PATH, "utf8").trim();
143 + } catch {
144 + warn(
145 + "Bundled SYSTEM.md is unavailable; PFUI will preserve Pi's system prompt.",
146 + );
147 + return undefined;
151 +function discoverBundledSkill(): string | undefined {
152 + if (!existsSync(SKILL_PATH)) {
153 + warn("Bundled pi-knowledge skill is missing and was omitted.");
154 + return undefined;
156 + try {
157 + const loaded = loadSkillsFromDir({ dir: SKILL_DIR, source: "pfui" });
158 + const errors = loaded.diagnostics.filter(
159 + (diagnostic) => diagnostic.type === "error",
160 + );
161 + const skill = loaded.skills.find(
162 + (candidate) => candidate.name === "pi-knowledge",
163 + );
164 + if (skill && errors.length === 0) {
165 + for (const diagnostic of loaded.diagnostics) warn(diagnostic.message);
166 + return skill.filePath;
168 + const detail = errors.map((diagnostic) => diagnostic.message).join("; ");
169 + warn(
170 + detail
171 + ? `Bundled pi-knowledge skill is invalid and was omitted: ${detail}`
172 + : "Bundled pi-knowledge skill is invalid and was omitted.",
173 + );
174 + } catch (error) {
175 + warn(
176 + `Bundled pi-knowledge skill could not be validated and was omitted: ${error instanceof Error ? error.message : String(error)}`,
177 + );
179 + return undefined;
182 +function projectContext(
183 + files: NonNullable<BuildSystemPromptOptions["contextFiles"]>,
184 +): string {
185 + let section =
186 + "\n\n<project_context>\n\nProject-specific instructions and guidelines:\n\n";
187 + for (const file of files) {
188 + section += `<project_instructions path="${file.path}">\n${file.content}\n</project_instructions>\n\n`;
190 + return `${section}</project_context>\n`;
193 +function compileFallback(
194 + identity: string,
195 + options: BuildSystemPromptOptions,
196 +): string {
197 + const tools = options.selectedTools || ["read", "bash", "edit", "write"];
198 + const visibleTools = [...new Set(tools)].filter(
199 + (name) => !!options.toolSnippets?.[name],
200 + );
201 + const toolLines =
202 + visibleTools.length > 0
203 + ? visibleTools
204 + .map((name) => `- ${name}: ${options.toolSnippets?.[name]}`)
205 + .join("\n")
206 + : "(none)";
207 + const guidelines = [
208 + ...new Set(
209 + (options.promptGuidelines ?? [])
210 + .map((guideline) => guideline.trim())
211 + .filter(Boolean),
212 + ),
213 + ];
214 + const guidelineLines =
215 + guidelines.length > 0
216 + ? guidelines.map((guideline) => `- ${guideline}`).join("\n")
217 + : "(none)";
219 + let prompt = `${identity}\n\nAvailable tools:\n${toolLines}\n\nGuidelines:\n${guidelineLines}`;
220 + if (options.appendSystemPrompt) prompt += `\n\n${options.appendSystemPrompt}`;
221 + if (options.contextFiles?.length)
222 + prompt += projectContext(options.contextFiles);
224 + const skillReadTool = (["read", "bash"] as const).find((tool) =>
225 + tools.includes(tool),
226 + );
227 + if (skillReadTool && options.skills?.length) {
228 + prompt += formatSkillsForPrompt(options.skills, skillReadTool);
230 + prompt += `\nCurrent working directory: ${options.cwd.replace(/\\/g, "/")}`;
231 + return prompt;
234 +function warnUnknownOptions(options: BuildSystemPromptOptions): void {
235 + for (const key of Object.keys(options)) {
236 + if (!KNOWN_PROMPT_OPTIONS.has(key)) {
237 + warn(
238 + `Unknown systemPromptOptions key ${JSON.stringify(key)} was ignored.`,
239 + );
244 +export default function pfui(pi: ExtensionAPI): void {
245 + const ownedEnvironment = exportEnvironment();
246 + const fallback = loadFallback();
247 + const bundledSkill = discoverBundledSkill();
249 + pi.on("resources_discover", () =>
250 + bundledSkill ? { skillPaths: [bundledSkill] } : undefined,
251 + );
252 + pi.on("session_start", (_event, ctx) => deliverWarnings(ctx));
254 + pi.on("before_agent_start", (event, ctx) => {
255 + if (event.systemPromptOptions.customPrompt) {
256 + deliverWarnings(ctx);
257 + return;
259 + warnUnknownOptions(event.systemPromptOptions);
260 + if (!fallback) {
261 + deliverWarnings(ctx);
262 + return;
265 + const systemPrompt = compileFallback(fallback, event.systemPromptOptions);
266 + deliverWarnings(ctx);
267 + return { systemPrompt };
268 + });
270 + pi.on("session_shutdown", () => {
271 + for (const [name, value] of ownedEnvironment) {
272 + if (process.env[name] === value) delete process.env[name];
274 + });

extensions/pfui/mise.toml

Added
new file mode 100644
1 +[tasks.bench]
2 +description = "Benchmark PFUI fallback composition"
3 +depends = ["//:install"]
4 +run = "node --no-warnings --experimental-strip-types __bench__/fallback.bench.ts"
6 +[tasks.profile]
7 +description = "Profile PFUI fallback composition"
8 +depends = ["//:install"]
9 +run = [
10 + '''node -e "require('node:fs').mkdirSync('../../.research/pfui', { recursive: true })"''',
11 + "node --no-warnings --experimental-strip-types --cpu-prof --cpu-prof-dir ../../.research/pfui --cpu-prof-name pfui.cpuprofile __bench__/fallback.bench.ts",
14 +[tasks.lint]
15 +description = "Lint pfui extension"
16 +depends = ["//:install"]
17 +run = [
18 + "biome ci --config-path ../.. .",
19 + "rumdl check --config ../../.rumdl.toml .",
20 + "taplo format --check --config ../../.taplo.toml mise.toml",
23 +[tasks.test]
24 +description = "Test pfui extension"
25 +depends = ["//:install"]
26 +run = [
27 + { task = "//:test", args = ["extensions/pfui"] },
30 +[tasks.check]
31 +description = "Check pfui extension"
32 +depends = ["//:install"]
33 +run = [
34 + { task = "//:build", args = ["pfui"] },

extensions/pfui/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-pfui",
3 + "private": true,
4 + "type": "module",
5 + "main": "index.ts",
6 + "license": "MIT",
7 + "description": "Pain-Free User Interface defaults and Pi context discovery.",
8 + "keywords": [
9 + "pi",
10 + "pi-extension"
11 + ],
12 + "peerDependencies": {
13 + "@earendil-works/pi-coding-agent": "*"
14 + },
15 + "devDependencies": {
16 + "@marcfargas/pi-test-harness": "^0.6.1",
17 + "vitest": "^4.1.9"
18 + },
19 + "pi": {
20 + "extensions": [
21 + "index.ts"
22 + ]
23 + }

extensions/pfui/skills/pi-knowledge/SKILL.md

Added
new file mode 100644
1 +---
2 +name: pi-knowledge
3 +description: "Use for questions about Pi and for implementing or changing Pi extensions, skills, themes, prompts, models, providers, packages, SDK integrations, TUI components, keybindings, or environment behavior."
4 +compatibility: "Requires Pi and either bash or PowerShell."
5 +---
7 +# Pi knowledge
9 +Use Pi's installed documentation as the source of truth.
10 +Read paths from the `PI_CONTEXT_*` environment variables instead of assuming an installation layout.
11 +Resolve only the needed variables with the active shell, for example `$PI_CONTEXT_DOCS_PATH` in Bash or `$env:PI_CONTEXT_DOCS_PATH` in PowerShell, then pass the resulting absolute paths to file tools.
12 +Never dump the complete environment.
13 +If neither Bash nor PowerShell is available, state that installed documentation paths cannot be resolved and do not guess them.
15 +## Topic map
17 +- Overview and CLI: `PI_CONTEXT_README_PATH`
18 +- Extensions: `PI_CONTEXT_DOCS_PATH/extensions.md` and `PI_CONTEXT_EXAMPLES_PATH/extensions/`
19 +- Themes: `PI_CONTEXT_DOCS_PATH/themes.md`
20 +- Skills: `PI_CONTEXT_DOCS_PATH/skills.md`
21 +- Prompt templates: `PI_CONTEXT_DOCS_PATH/prompt-templates.md`
22 +- TUI components: `PI_CONTEXT_DOCS_PATH/tui.md`
23 +- Keybindings: `PI_CONTEXT_DOCS_PATH/keybindings.md`
24 +- SDK integrations: `PI_CONTEXT_DOCS_PATH/sdk.md` and `PI_CONTEXT_EXAMPLES_PATH/sdk/`
25 +- Custom providers: `PI_CONTEXT_DOCS_PATH/custom-provider.md`
26 +- Models: `PI_CONTEXT_DOCS_PATH/models.md`
27 +- Packages: `PI_CONTEXT_DOCS_PATH/packages.md`
28 +- Environment variables: `PI_CONTEXT_DOCS_PATH/environment-variables.md`
29 +- Release changes: `PI_CONTEXT_CHANGELOG_PATH`
30 +- Package metadata and Pi configuration name: `PI_CONTEXT_PACKAGE_JSON_PATH`
32 +Read every selected Markdown file completely before answering or implementing.
33 +Follow its relevant Markdown cross-references and read those targets completely too.
34 +Inspect relevant examples before implementing Pi APIs.
36 +If a mapped file moved or is absent, discover its replacement from `PI_CONTEXT_README_PATH`, the contents of `PI_CONTEXT_DOCS_PATH` and `PI_CONTEXT_EXAMPLES_PATH`, and `PI_CONTEXT_PACKAGE_JSON_PATH`.
37 +Do not silently substitute remembered API behavior for installed documentation.

mise.toml

Modified
9 9 "aqua:mikefarah/yq" = "latest"
10 10 "aqua:rvben/rumdl" = "latest"
11 11 "aqua:tamasfe/taplo" = "latest"
12 +"go:golang.org/x/perf/cmd/benchstat" = "latest"
13 14 [tasks.default]
14 15 description = "List tasks"
140 141 [tasks.modernize-bench]
141 142 description = "Benchmark modernize audit"
142 143 tools.hyperfine = "latest"
143 -tools."go:golang.org/x/perf/cmd/benchstat" = "latest"
144 144 usage = '''
145 145 arg "[args]" var=#true

package-lock.json

Modified
40 40 "typebox": "*"
43 + "extensions/ask": {
44 + "name": "@bugabinga/pi-ext-ask",
45 + "license": "MIT",
46 + "devDependencies": {
47 + "@marcfargas/pi-test-harness": "^0.6.1",
48 + "vitest": "^4.1.9"
49 + },
50 + "peerDependencies": {
51 + "@earendil-works/pi-coding-agent": "*",
52 + "@earendil-works/pi-tui": "*",
53 + "typebox": "*"
54 + }
55 + },
43 56 "extensions/btw": {
44 57 "name": "@bugabinga/pi-ext-btw",
45 58 "license": "MIT",
194 207 "peerDependencies": {
195 208 "@earendil-works/pi-ai": "*",
196 209 "@earendil-works/pi-coding-agent": "*",
210 + "@earendil-works/pi-tui": "*",
197 211 "typebox": "*"
296 310 "@earendil-works/pi-coding-agent": "*"
313 + "extensions/pfui": {
314 + "name": "@bugabinga/pi-ext-pfui",
315 + "license": "MIT",
316 + "devDependencies": {
317 + "@marcfargas/pi-test-harness": "^0.6.1",
318 + "vitest": "^4.1.9"
319 + },
320 + "peerDependencies": {
321 + "@earendil-works/pi-coding-agent": "*"
323 + },
299 324 "extensions/prompt-autopsy": {
300 325 "name": "@bugabinga/pi-ext-prompt-autopsy",
301 326 "license": "MIT",
1380 1405 "resolved": "extensions/angel",
1381 1406 "link": true
1408 + "node_modules/@bugabinga/pi-ext-ask": {
1409 + "resolved": "extensions/ask",
1410 + "link": true
1411 + },
1383 1412 "node_modules/@bugabinga/pi-ext-btw": {
1384 1413 "resolved": "extensions/btw",
1385 1414 "link": true
1460 1489 "resolved": "extensions/os-notifier",
1461 1490 "link": true
1492 + "node_modules/@bugabinga/pi-ext-pfui": {
1493 + "resolved": "extensions/pfui",
1494 + "link": true
1495 + },
1463 1496 "node_modules/@bugabinga/pi-ext-prompt-autopsy": {
1464 1497 "resolved": "extensions/prompt-autopsy",
1465 1498 "link": true

package.json

Modified
30 30 "pi": {
31 31 "extensions": [
32 + "extensions/pfui/index.ts",
32 33 "extensions/*/index.ts"

scripts/extensions.mjs

Modified
824 824 errors.push("root: workspaces must be ['extensions/*']");
826 826 JSON.stringify(pkg.pi?.extensions) !==
827 - JSON.stringify(["extensions/*/index.ts"])
827 + JSON.stringify(["extensions/pfui/index.ts", "extensions/*/index.ts"])
829 - errors.push("root: pi.extensions must be ['extensions/*/index.ts']");
829 + errors.push(
830 + "root: pi.extensions must load pfui explicitly before the extension glob",
831 + );
830 832 if ("skills" in (pkg.pi ?? {})) errors.push("root: pi.skills must be absent");
831 833 if ("prompts" in (pkg.pi ?? {}))
832 834 errors.push("root: pi.prompts must be absent");

scripts/test_extensions_static_check.mjs

Modified
185 185 assert(!tuneIndex.includes('exec("bash"'));
187 187 assert.deepEqual(rootPkg().pi, {
188 - extensions: ["extensions/*/index.ts"],
188 + extensions: ["extensions/pfui/index.ts", "extensions/*/index.ts"],
191 191 const cliFailure = spawnSync(