pi-ext bugabingas pi extensions
owned by bugabinga
README Source History Refs Compare Notes Search feat(ui): add ask and pfui foundations
759939356ca54eb56a1a2405dc58f303ba019be3
Oliver Jan Krylow <oliver@bugabinga.net > · 14 Sep 2026
SSH signature · not checked
Browse files Compare with HEAD
Changed files (23) .system/SYSTEM.md Modified 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.
16 16 "!skills/find-skills" ,
17 + "!extensions/iq/check/fixtures" ,
17 19 "!**/test-results" ,
18 20 "!**/playwright-report" ,
extensions/ask/README.md Added new file mode 100644 3 + Structured multiple-choice questions from the model to the human, similar to Claude Code's `AskUserQuestion` and Codex's `request_user_input`.
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.
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`.
40 + {
"status" :
"answered" ,
"answers" :{
"<id or question>" :{
"answers" :[
"Postgres (Recommended)" ]}}}
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" ,
17 + function tuiSession () {
20 + handleInput : (data
: string )
=> void ;
21 + handleMouse ?: (event
: {
22 + type
: "press" | "click" ;
33 + })
=> { handled
?: boolean }
| undefined ;
34 + render : (width
: number )
=> string [];
41 + keybindings
: unknown ,
42 + done : (value
: never )
=> void ,
45 + new Promise ((resolve)
=> {
46 + component
= factory (
47 + {
requestRender () {}, terminal: { rows:
40 } },
49 + fg : (_style
: string , text
: string )
=> text,
50 + bold : (text
: string )
=> text,
53 + matches : (data
: string , action
: string )
=> KEYS[action]
=== data,
56 + )
as typeof component;
62 + }
as unknown as ExtensionContext ;
63 + return { ctx,
component : ()
=> component };
77 + )
=> Promise <
string | undefined >;
80 + placeholder
?: string ,
82 + )
=> Promise <
string | undefined >;
87 + )
=> Promise <
boolean >;
89 + overrides
: Record <
string ,
unknown >
= {},
90 + )
: ExtensionContext {
95 + select: ui.select
?? (
async ()
=> undefined ),
96 + input: ui.
input ?? (
async ()
=> undefined ),
97 + confirm: ui.confirm
?? (
async ()
=> false ),
100 + }
as ExtensionContext ;
103 + function mouseEvent (type
: "press" | "click" , y
: number , width
= 80 ) {
106 + button:
"left" as const ,
119 + function singleQuestion () {
120 + return __test.
normalizeQuestions ([
123 + header:
"Database" ,
124 + question:
"Which database?" ,
126 + { label:
"Postgres (Recommended)" , description:
"Relational." },
127 + { label:
"SQLite" , description:
"Embedded." },
133 + describe (
"ask extension" , ()
=> {
134 + it (
"loads in real Pi extension runtime and registers ask_user_question" ,
async ()
=> {
135 + t
= await createTestSession ({ extensionFactories: [askExtension] });
137 + t.session.extensionRunner.extensions[
0 ].tools.
has (
"ask_user_question" ),
141 + it (
"terminates on cancel and reports missing UI at tool level" ,
async ()
=> {
142 + t
= await createTestSession ({ extensionFactories: [askExtension] });
144 + t.session.extensionRunner.extensions[
0 ].tools.
get (
"ask_user_question" );
145 + const definition
= tool?.definition;
146 + expect (definition).
toBeDefined ();
152 + { label:
"A" , description:
"a" },
153 + { label:
"B" , description:
"b" },
158 + const cancelled
= await definition.
execute (
165 + expect (cancelled.terminate).
toBe (
true );
166 + expect (
JSON .
parse (cancelled.
content [
0 ].
text ).
status ).
toBe (
"cancelled" );
168 + const unavailable
= await definition.
execute (
173 + fakeCtx ({}, { hasUI:
false }),
175 + expect (
JSON .
parse (unavailable.
content [
0 ].
text ).
status ).
toBe (
"unavailable" );
179 + describe (
"normalizeQuestions" , ()
=> {
180 + it (
"derives key and header and strips model-supplied Other options" , ()
=> {
181 + const [question]
= __test.
normalizeQuestions ([
183 + question:
"Which database?" ,
185 + { label:
"Postgres (Recommended)" , description:
"Relational." },
186 + { label:
"Other" , description:
"ignored" },
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)" );
196 + it (
"prefers id for key and header, dedupes keys, defaults multiSelect" , ()
=> {
197 + const [first, second]
= __test.
normalizeQuestions ([
201 + question:
"Deploy where?" ,
203 + { label:
"A" , description:
"a" },
204 + { label:
"B" , description:
"b" },
209 + question:
"Again?" ,
211 + { label:
"C" , description:
"c" },
212 + { label:
"D" , description:
"d" },
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" );
222 + it (
"rejects empty questions and questions without usable options" , ()
=> {
223 + expect (()
=> __test.
normalizeQuestions ([])).
toThrow (
/1-4 questions/ );
225 + __test.
normalizeQuestions ([
228 + options: [{ label:
"Other" , description:
"x" }],
231 + ).
toThrow (
/no usable options/ );
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 (
241 + select :
async (title, entries)
=> {
242 + calls.
push ([title, entries]);
247 + expect (result).
toEqual ({
248 + status:
"answered" ,
249 + answers: { db: { answers: [
"Postgres (Recommended)" ] } },
251 + expect (calls[
0 ][
0 ]).
toBe (
"Question 1/1 · Database" );
252 + expect (calls[
0 ][
1 ]).
toContain (__test.OTHER_LABEL);
255 + it (
"routes Other through free-text input and trims it" ,
async ()
=> {
256 + const result
= await __test.
runAskFlow (
259 + select :
async (_title, entries)
=> entries.
at (
- 1 )
?? __test.OTHER_LABEL,
260 + input :
async ()
=> " Whatever fits " ,
263 + expect (result).
toEqual ({
264 + status:
"answered" ,
265 + answers: { db: { answers: [
"Whatever fits" ] } },
269 + it (
"cancels the whole call when any dialog is dismissed" ,
async ()
=> {
270 + const result
= await __test.
runAskFlow (
273 + select :
async ()
=> undefined ,
274 + input :
async ()
=> "x" ,
277 + expect (result).
toEqual ({ status:
"cancelled" });
280 + it (
"collects multi-select confirms, then Done" ,
async ()
=> {
281 + const picks
= [
true ,
false ];
282 + const questions
= __test.
normalizeQuestions ([
285 + question:
"Which features?" ,
288 + { label:
"Auth" , description:
"a" },
289 + { label:
"Audit" , description:
"b" },
293 + const result
= await __test.
runAskFlow (
296 + select :
async (_title, entries)
=> 297 + entries[
0 ]
=== "Done" ? "Done" : undefined ,
298 + confirm :
async ()
=> picks.
shift ()
?? false ,
301 + expect (result).
toEqual ({
302 + status:
"answered" ,
303 + answers: { feat: { answers: [
"Auth" ] } },
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" ] } },
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" ] } },
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" } },
350 + it (
"wraps questions, options, and free-text input to the available width" ,
async ()
=> {
351 + const questions
= __test.
normalizeQuestions ([
354 + question:
"Which database should handle this unusually demanding workload?" ,
357 + label:
"Postgres with replication (Recommended)" ,
358 + description:
"Supports relational queries and resilient failover." ,
360 + { label:
"SQLite" , description:
"Embedded and deliberately simple." },
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" ] } },
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" ] } },
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" });
406 + it (
"toggles multi-select options with space" ,
async ()
=> {
407 + const questions
= __test.
normalizeQuestions ([
410 + question:
"Which features?" ,
413 + { label:
"Auth" , description:
"a" },
414 + { label:
"Audit" , description:
"b" },
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" ] } },
429 + expect (rendered).
toContain (
"Which features?" );
430 + expect (rendered).
toContain (
"Other" );
431 + expect (keys).
toContain (KEYS[
"tui.select.confirm" ]);
extensions/ask/ask-overlay.ts Added new file mode 100644 1 + import type { ExtensionContext, Theme }
from "@earendil-works/pi-coding-agent" ;
4 + type KeybindingsManager,
9 + type TuiMouseEventResult,
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 = {
19 + description:
"Type your own answer" ,
22 + export async function askInTui (
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),
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 );
43 + signal.
addEventListener (
"abort" , onAbort, { once:
true });
46 + signal.
removeEventListener (
"abort" , onAbort);
50 + signal.
removeEventListener (
"abort" , onAbort);
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 ;
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 ,
81 + const items
: SelectItem []
= [
82 + ... question.
options .
map ((option)
=> ({
83 + value: option.
label ,
84 + label: option.
label ,
85 + description: option.
description ,
89 + this.list
= new OptionList (
91 + question.multiSelect,
93 + ()
=> this.otherSelected,
94 + ()
=> this.
activateCurrent (),
96 + const editorTheme
= {
97 + borderColor : (text
: string )
=> theme.
fg (
"border" , text),
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),
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" );
127 + this.
activeInput ().
handleInput (data);
128 + this.tui.
requestRender ();
132 + this.keybindings.
matches (data,
"tui.select.up" )
|| 133 + this.keybindings.
matches (data,
"tui.select.down" )
136 + this.keybindings.
matches (data,
"tui.select.up" )
? - 1 : 1 ,
138 + }
else if (this.keybindings.
matches (data,
"tui.select.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 {
152 + event .
y >= this.listRow
&& 153 + event .
y < this.listRow
+ this.listHeight
155 + return this.list.
handleMouse (
156 + localMouseEvent (
event , this.listRow, this.listHeight),
160 + this.inputRow
!== undefined && 161 + event .
y >= this.inputRow
&& 162 + event .
y < this.inputRow
+ this.inputHeight
164 + const result
= this.
activeInput ().
handleMouse (
165 + localMouseEvent (
event , this.inputRow, this.inputHeight),
167 + return result
? {
... result, focus:
true }
: undefined ;
172 + render (width
: number )
: string [] {
174 + ... wrapStyled (this.theme.
fg (
"accent" , this.theme.
bold (this.
title )), width),
175 + ... wrapStyled (this.theme.
fg (
"toolOutput" , this.question.question), width),
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" ) {
190 + this.mode
=== "other" ? "Answer:" : "Notes:" ,
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));
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" );
225 + this.question.multiSelect
226 + ? this.
multiAnswers ()
227 + : this.list.
current ()
228 + ? [this.list.
current ()?.
label ?? "" ]
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" );
247 + this.list.
toggle ();
250 + private submitOther (value
: string )
: void {
251 + const text
= value.
trim ();
253 + if (this.question.multiSelect) {
254 + this.otherText
= text;
255 + this.otherSelected
= true ;
256 + this.
setMode (
"list" );
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
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 {
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 ;
313 + type ItemRows = { start
: number ; end
: number };
317 + private readonly toggled
= new Set <
string >();
318 + private itemRows
: ItemRows []
= [];
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 ,
328 + current ()
: SelectItem | undefined {
329 + return this.items[this.
index ];
332 + move (delta
: number )
: void {
334 + (this.
index + delta
+ this.items.
length )
% Math .
max (this.items.
length ,
1 );
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 [] {
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 };
358 + event .button
!== "left" || 359 + (
event .
type !== "press" && event .
type !== "click" )
362 + const itemIndex
= this.itemRows.
findIndex (
363 + (rows)
=> event .
y >= rows.
start && event .
y < rows.end,
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 ;
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" ;
389 + this.theme.
fg (labelStyle, item.
label ),
394 + if (item.
description ) {
397 + this.theme.
fg (
"dim" , item.
description ),
403 + this.itemRows.
push ({ start, end: lines.
length });
409 + function wrapStyled (text
: string , width
: number )
: string [] {
410 + if (width
<= 0 )
return [
"" ];
411 + return wrapTextWithAnsi (text, width).
map ((line)
=> 412 + truncateToWidth (line, width,
"" ),
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,
"" ),
425 + function localMouseEvent (
426 + event
: TuiMouseEvent ,
430 + return {
... event , y:
event .
y - row, height };
extensions/ask/ask-tool.ts Added new file mode 100644 3 + type ExtensionContext,
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" ;
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 (
24 + "Stable snake_case identifier for mapping answers. Derived from the question if omitted." ,
27 + question: Type.
String ({
29 + "The complete question to ask. Clear, specific, ends with a question mark." ,
31 + header: Type.
Optional (
34 + 'Very short label shown in the UI (max 12 chars), e.g. "Auth method". Derived if omitted.' ,
37 + multiSelect: Type.
Optional (
40 + description:
"Allow selecting multiple options instead of just one." ,
43 + options: Type.
Array (
45 + label: Type.
String ({
46 + description:
"Concise display text (1-5 words)." ,
48 + description: Type.
String ({
50 + "One short sentence explaining impact/tradeoff if selected." ,
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.' ,
64 + description:
"Questions to ask the user (1-4). Prefer fewer." ,
69 + export type AskOption = { label
: string ; description
: string };
71 + export type AskQuestionInput = {
75 + multiSelect
?: boolean ;
76 + options
: AskOption [];
79 + export type AskQuestion = {
83 + multiSelect
: boolean ;
84 + options
: AskOption [];
87 + export type AskAnswer = { answers
: string []; notes
?: string };
89 + export type AskFlowResult = 90 + | { status
: "answered" ; answers
: Record <
string ,
AskAnswer > }
91 + | { status
: "cancelled" };
97 + questions
: Array <
AskQuestion & { answer
?: AskAnswer }>;
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 ),
116 + if (options.
length === 0 )
118 + `Question ${index + 1} has no usable options; provide 2-4 distinct options and no "Other".` ,
120 + const baseKey
= (question.
id ?? question.question).
trim ();
123 + while (usedKeys.
has (key)) key
= `${baseKey}-${suffix ++ }` ;
127 + header: (question.header
?? question.
id ?? question.question)
130 + question: question.question,
131 + multiSelect: question.multiSelect
=== true ,
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}` ;
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 (
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 }` ,
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 (
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" ], {
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 (
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" ,
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 () {
221 + type:
"text" as const ,
222 + text:
textResult ({ status:
"cancelled" , message: CANCELLED_MESSAGE }),
225 + details: { kind:
"ask" , status:
"cancelled" as const },
230 + function unavailableResult () {
234 + type:
"text" as const ,
236 + status:
"unavailable" ,
237 + message: UNAVAILABLE_MESSAGE,
241 + details: { kind:
"ask" , status:
"unavailable" as const },
245 + function errorResult (message
: string ) {
249 + type:
"text" as const ,
250 + text:
textResult ({ status:
"error" , message }),
253 + details: { kind:
"ask" , status:
"error" as const , message },
257 + function answeredResult (
258 + questions
: AskQuestion [],
259 + answers
: Record <
string ,
AskAnswer >,
264 + type:
"text" as const ,
265 + text:
textResult ({ status:
"answered" , answers }),
269 + kind:
"ask" as const ,
270 + status:
"answered" as const ,
271 + questions: questions.
map ((question)
=> ({
273 + answer: answers[question.key],
279 + export function createAskTool () {
280 + return defineTool ({
281 + name:
"ask_user_question" ,
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.' ,
291 + renderCall (args, theme, context) {
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 (
300 + ` (${ keyHint ("app.tools.expand", "to expand")})` ,
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);
313 + renderResult (result, { expanded }, theme, context) {
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 ;
325 + `${answered}/${details.questions. length } answered` ,
328 + const lines
= details.questions.
map ((question)
=> {
329 + const answer
= question.answer
330 + ? [question.answer.answers.
join (
", " ), question.answer.notes]
334 + return `\n${theme. fg ("toolOutput", question.question)} ${theme. fg ("accent", answer)}` ;
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" );
343 + output
= theme.
fg (
"warning" ,
`error: ${details.message}` );
345 + text.
setText (output);
348 + async execute (_toolCallId, params, signal, _onUpdate, ctx) {
349 + let questions
: AskQuestion [];
351 + questions
= normalizeQuestions (params.questions);
353 + return errorResult (
354 + error
instanceof Error ? error.message
: String (error),
357 + if (
! ctx.hasUI)
return unavailableResult ();
358 + let flow
: AskFlowResult ;
360 + flow
= await runAskFlow (questions, ctx, signal);
362 + return cancelledResult ();
364 + if (flow.
status === "cancelled" )
return cancelledResult ();
365 + return answeredResult (questions, flow.answers);
extensions/ask/index.ts Added new file mode 100644 1 + import type { ExtensionAPI }
from "@earendil-works/pi-coding-agent" ;
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 2 + description =
"Format ask extension" 3 + depends = [
"//:install" ]
5 + "biome check --write ." ,
6 + "rumdl fmt README.md" ,
7 + "taplo format mise.toml" ,
11 + description =
"Lint ask extension" 12 + depends = [
"//:install" ]
14 + "biome ci --config-path ../.. ." ,
15 + "rumdl check --config ../../.rumdl.toml ." ,
16 + "taplo format --check --config ../../.taplo.toml mise.toml" ,
20 + description =
"Test ask extension" 21 + depends = [
"//:install" ]
23 + {
task =
"//:test" ,
args = [
"extensions/ask" ] },
27 + description =
"Check ask extension" 28 + depends = [
"//:install" ]
30 + {
task =
"//:build" ,
args = [
"ask" ] },
extensions/ask/package.json Added new file mode 100644 2 + "name" :
"@bugabinga/pi-ext-ask" ,
5 + "peerDependencies" : {
6 + "@earendil-works/pi-coding-agent" :
"*" ,
7 + "@earendil-works/pi-tui" :
"*" ,
11 + "description" :
"Ask the human structured multiple-choice questions from the model." ,
16 + "devDependencies" : {
17 + "@marcfargas/pi-test-harness" :
"^0.6.1" ,
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" :
"*" ,
extensions/pfui/README.md Added new file mode 100644 3 + Pain-Free User Interface gives Pi a small fallback identity and exports installed Pi context for tools and skills.
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.
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" ;
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}` ,
20 + path:
`/home/user/.pi/agent/skills/skill-${index}/SKILL.md` ,
22 + scope:
"user" as const ,
23 + origin:
"top-level" as const ,
26 + const options
: BuildSystemPromptOptions = {
27 + cwd:
"/home/user/work/project" ,
28 + selectedTools: [
"read" ,
"grep" ,
"ls" ,
"bash" ,
"edit" ,
"write" ],
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" ,
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." ,
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)}` ,
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 ({
62 + extensionFactories: [pfui],
64 + const runner
= testSession.session.extensionRunner;
65 + const compose = async ()
=> {
66 + const result
= await runner.
emitBeforeAgentStart (
69 + "Pi default prompt" ,
72 + consume (result?.systemPrompt);
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);
85 + `BenchmarkFallbackComposition\t${ITERATIONS}\t${(elapsed / ITERATIONS). toFixed (0)} ns/op` ,
89 + await runner.
emit ({ type:
"session_shutdown" , reason:
"quit" });
90 + testSession.
dispose ();
91 + rmSync (cwd, { recursive:
true , force:
true });
96 + if (sink
=== 42 )
console .
error (sink);
extensions/pfui/__tests__/harness.test.ts Added new file mode 100644 9 + import { tmpdir }
from "node:os" ;
10 + import path
from "node:path" ;
12 + type BuildSystemPromptOptions,
14 + DefaultPackageManager,
16 + formatSkillsForPrompt,
24 + }
from "@earendil-works/pi-coding-agent" ;
25 + import { afterEach, describe, expect, it }
from "vitest" ;
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);
45 + function copiedPfui (prefix
: string )
: string {
46 + const directory
= mkdtempSync (path.
join (extensionRoot, prefix));
47 + temporaryPaths.
push (directory);
49 + path.
join (extensionRoot,
"index.ts" ),
50 + path.
join (directory,
"index.ts" ),
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" ), {
62 + return createTestSession ({
65 + extensionFactories: options.extensionFactories
?? [pfui],
69 + async function stopSession ()
: Promise <
void > {
70 + if (
! t
|| shutdown)
return ;
71 + await t.session.extensionRunner.
emit ({
72 + type:
"session_shutdown" ,
78 + function baseOptions ()
: BuildSystemPromptOptions {
80 + cwd:
"/work/project" ,
81 + selectedTools: [
"read" ],
82 + toolSnippets: { read:
"Read files" },
83 + promptGuidelines: [],
87 + async function emittedPrompt (
88 + options
: BuildSystemPromptOptions ,
89 + eventSystemPrompt
= "PI SYSTEM" ,
91 + if (
! t)
throw new Error (
"Test session is not initialized" );
92 + const result
= await t.session.extensionRunner.
emitBeforeAgentStart (
98 + return result?.systemPrompt
?? eventSystemPrompt;
101 + afterEach (
async ()
=> {
102 + await stopSession ();
106 + delete (globalThis
as Record <
symbol ,
unknown >)[
107 + Symbol .
for (
"@bugabinga/pi-ext-pfui/state" )
109 + for (
const directory
of temporaryPaths.
splice (
0 )) {
110 + rmSync (directory, { recursive:
true , force:
true });
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" ,
127 + const packageManager
= new DefaultPackageManager ({
129 + agentDir: path.
join (t.cwd,
".test-home" , CONFIG_DIR_NAME,
"agent" ),
130 + settingsManager: SettingsManager.
inMemory (),
132 + const resolved
= await packageManager.
resolveExtensionSources (
134 + { temporary:
true },
136 + const pfuiPath
= path.
join (extensionRoot,
"index.ts" );
137 + expect (resolved.extensions[
0 ]?.path).
toBe (pfuiPath);
139 + resolved.extensions.
filter ((extension)
=> extension.path
=== pfuiPath),
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" ,
152 + options.promptGuidelines
= [
153 + " Keep paths explicit. " ,
154 + "Keep paths explicit." ,
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." ,
164 + expect (prompt).
toContain (
165 + "Available tools:\n- write: Write complete files\n- read: Read current files" ,
167 + expect (prompt).not.
toContain (
"inactive" );
168 + expect (prompt.
match (
/- Keep paths explicit\./ g )).
toHaveLength (
1 );
169 + expect (prompt).
toContain (
"- Verify changes." );
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" ,
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` ,
187 + t
= await createPfuiSession ({
188 + extensionFactories: [pfui, appendLater],
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." ,
197 + "Current working directory: /work/project\n\nLATER EXTENSION" ,
202 + it (
"preserves Pi prompt section formatting and normalizes cwd" ,
async ()
=> {
203 + t
= await createPfuiSession ();
204 + const skill
= t.session.resourceLoader
207 + (candidate
: { name
: string })
=> candidate.
name === "pi-knowledge" ,
209 + expect (skill).
toBeDefined ();
210 + const options
: BuildSystemPromptOptions = {
212 + cwd:
"C:\\work\\project" ,
213 + appendSystemPrompt:
"APPENDED" ,
214 + contextFiles: [{ path:
"/repo/AGENTS.md" , content:
"PROJECT RULE" }],
218 + const prompt
= await emittedPrompt (options);
219 + const identity
= readFileSync (
220 + path.
join (extensionRoot,
"SYSTEM.md" ),
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` ,
228 + it (
"omits skills when neither read nor bash is active" ,
async ()
=> {
229 + t
= await createPfuiSession ();
230 + const skill
= t.session.resourceLoader
233 + (candidate
: { name
: string })
=> candidate.
name === "pi-knowledge" ,
235 + const prompt
= await emittedPrompt ({
237 + selectedTools: [
"powershell" ],
238 + toolSnippets: { powershell:
"Run PowerShell" },
242 + expect (prompt).not.
toContain (
"<available_skills>" );
243 + expect (prompt).not.
toContain (
"pi-knowledge" );
246 + it (
"discovers the bundled pi-knowledge skill with its contract" ,
async ()
=> {
247 + t
= await createPfuiSession ();
248 + const skill
= t.session.resourceLoader
251 + (candidate
: { name
: string })
=> candidate.
name === "pi-knowledge" ,
254 + expect (skill?.filePath).
toBe (
255 + path.
join (extensionRoot,
"skills" ,
"pi-knowledge" ,
"SKILL.md" ),
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" ,
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" );
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" ));
275 + path.
join (extensionRoot,
"SYSTEM.md" ),
276 + path.
join (warned,
"SYSTEM.md" ),
278 + mkdirSync (path.
join (warned,
"skills" ,
"pi-knowledge" ), {
282 + path.
join (warned,
"skills" ,
"pi-knowledge" ,
"SKILL.md" ),
283 + `---\nname: pi-knowledge\ndescription: "${"x". repeat (1025)}"\n---\n\n# Pi knowledge\n` ,
285 + t
= await createTestSession ({
286 + cwd:
tempDirectory (
"pfui-warned-cwd-" ),
287 + extensions: [path.
join (warned,
"index.ts" )],
291 + t.session.resourceLoader
294 + (candidate
: { name
: string })
=> candidate.
name === "pi-knowledge" ,
299 + it (
"delivers each warning once without suppressing later warnings" ,
async ()
=> {
300 + t
= await createPfuiSession ();
303 + futureOption:
true ,
304 + }
as BuildSystemPromptOptions ;
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"' ,
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;
333 + t
= await createPfuiSession ({
334 + extensionFactories: [pfui, observeShutdown],
335 + env: { PI_CONTEXT_VERSION: VERSION },
337 + const packageDir
= getPackageDir ();
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,
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);
361 + it (
"preserves a conflicting context variable and warns" ,
async ()
=> {
362 + t
= await createPfuiSession ({
363 + env: { PI_CONTEXT_VERSION:
"external-version" },
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" ,
373 + await stopSession ();
374 + expect (
process .
env .PI_CONTEXT_VERSION).
toBe (
"external-version" );
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],
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" ,
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" ), {
396 + t
= await createTestSession ({
397 + cwd:
tempDirectory (
"pfui-missing-fallback-cwd-" ),
398 + extensions: [path.
join (broken,
"index.ts" )],
401 + expect (
await emittedPrompt (
baseOptions (),
"PI FALLBACK" )).
toBe (
404 + const warnings
= t.events
405 + .
uiCallsFor (
"notify" )
406 + .
map ((notification)
=> String (notification.args[
0 ]))
408 + expect (warnings).
toContain (
"Bundled SYSTEM.md is unavailable" );
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-` );
417 + path.
join (extensionRoot,
"SYSTEM.md" ),
418 + path.
join (broken,
"SYSTEM.md" ),
421 + mkdirSync (path.
join (broken,
"skills" ,
"pi-knowledge" ), {
425 + path.
join (broken,
"skills" ,
"pi-knowledge" ,
"SKILL.md" ),
429 + t
= await createTestSession ({
430 + cwd:
tempDirectory (
`pfui-${_case}-skill-cwd-` ),
431 + extensions: [path.
join (broken,
"index.ts" )],
435 + t.session.resourceLoader
438 + (candidate
: { name
: string })
=> candidate.
name === "pi-knowledge" ,
441 + const warnings
= t.events
442 + .
uiCallsFor (
"notify" )
443 + .
map ((notification)
=> String (notification.args[
0 ]))
445 + expect (warnings).
toContain (
`Bundled pi-knowledge skill ${message}` );
extensions/pfui/index.ts Added new file mode 100644 1 + import { existsSync, readFileSync }
from "node:fs" ;
2 + import { join }
from "node:path" ;
4 + type BuildSystemPromptOptions,
7 + type ExtensionContext,
8 + formatSkillsForPrompt,
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 ([
28 + "appendSystemPrompt" ,
34 + interface PfuiGlobalState {
35 + warnings
: Set <
string >;
36 + deliveredWarnings
: Set <
string >;
39 + type PfuiGlobal = typeof globalThis
& {
40 + [GLOBAL_STATE_KEY]
?: PfuiGlobalState ;
43 + interface EnvironmentValue {
49 + function globalState ()
: PfuiGlobalState {
50 + const scope
= globalThis
as PfuiGlobal ;
51 + const existing
= scope[GLOBAL_STATE_KEY];
52 + if (existing)
return existing;
54 + warnings:
new Set <
string >(),
55 + deliveredWarnings:
new Set <
string >(),
57 + scope[GLOBAL_STATE_KEY]
= 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),
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 ;
78 + packageDir
= getPackageDir ();
80 + warn (
"PI_CONTEXT_PACKAGE_DIR could not be resolved." );
83 + const resolvePath = (
85 + getter : ()
=> string ,
86 + )
: EnvironmentValue => {
88 + return { name, value:
getter (), path:
true };
90 + warn (
`${name} could not be resolved.` );
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" ),
107 + name:
"PI_CONTEXT_PACKAGE_JSON_PATH" ,
108 + value: packageDir
&& join (packageDir,
"package.json" ),
111 + { name:
"PI_CONTEXT_VERSION" , value: VERSION },
112 + { name:
"PI_CONTEXT_CONFIG_DIR_NAME" , value: CONFIG_DIR_NAME },
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 )) {
122 + `${resource. name } was omitted because its resource path is missing.` ,
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 ) {
133 + `${resource. name } already has a different value; PFUI preserved it.` ,
140 + function loadFallback ()
: string | undefined {
142 + return readFileSync (FALLBACK_PATH,
"utf8" ).
trim ();
145 + "Bundled SYSTEM.md is unavailable; PFUI will preserve Pi's system prompt." ,
151 + function discoverBundledSkill ()
: string | undefined {
152 + if (
! existsSync (SKILL_PATH)) {
153 + warn (
"Bundled pi-knowledge skill is missing and was omitted." );
157 + const loaded
= loadSkillsFromDir ({ dir: SKILL_DIR, source:
"pfui" });
158 + const errors
= loaded.diagnostics.
filter (
159 + (diagnostic)
=> diagnostic.
type === "error" ,
161 + const skill
= loaded.skills.
find (
162 + (candidate)
=> candidate.
name === "pi-knowledge" ,
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 (
"; " );
171 + ? `Bundled pi-knowledge skill is invalid and was omitted: ${detail}` 172 + : "Bundled pi-knowledge skill is invalid and was omitted." ,
176 + `Bundled pi-knowledge skill could not be validated and was omitted: ${error instanceof Error ? error.message : String (error)}` ,
182 + function projectContext (
183 + files
: NonNullable <
BuildSystemPromptOptions [
"contextFiles" ]>,
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 (
195 + options
: BuildSystemPromptOptions ,
197 + const tools
= options.selectedTools
|| [
"read" ,
"bash" ,
"edit" ,
"write" ];
198 + const visibleTools
= [
...new Set (tools)].
filter (
199 + (name)
=> !! options.toolSnippets?.[name],
202 + visibleTools.
length > 0 204 + .
map ((name)
=> `- ${name}: ${options.toolSnippets?.[name]}` )
207 + const guidelines
= [
209 + (options.promptGuidelines
?? [])
210 + .
map ((guideline)
=> guideline.
trim ())
214 + const guidelineLines
= 215 + guidelines.
length > 0 216 + ? guidelines.
map ((guideline)
=> `- ${guideline}` ).
join (
"\n" )
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),
227 + if (skillReadTool
&& options.skills?.
length ) {
228 + prompt
+= formatSkillsForPrompt (options.skills, skillReadTool);
230 + prompt
+= `\nCurrent working directory: ${options.cwd. replace (/\\/ g , "/")}` ;
234 + function warnUnknownOptions (options
: BuildSystemPromptOptions )
: void {
235 + for (
const key
of Object .
keys (options)) {
236 + if (
! KNOWN_PROMPT_OPTIONS.
has (key)) {
238 + `Unknown systemPromptOptions key ${ JSON . stringify (key)} was ignored.` ,
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 ,
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);
259 + warnUnknownOptions (
event .systemPromptOptions);
261 + deliverWarnings (ctx);
265 + const systemPrompt
= compileFallback (fallback,
event .systemPromptOptions);
266 + deliverWarnings (ctx);
267 + return { systemPrompt };
270 + pi.
on (
"session_shutdown" , ()
=> {
271 + for (
const [name, value]
of ownedEnvironment) {
272 + if (
process .
env [name]
=== value)
delete process .
env [name];
extensions/pfui/mise.toml Added new file mode 100644 2 + description =
"Benchmark PFUI fallback composition" 3 + depends = [
"//:install" ]
4 + run =
"node --no-warnings --experimental-strip-types __bench__/fallback.bench.ts" 7 + description =
"Profile PFUI fallback composition" 8 + depends = [
"//:install" ]
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" ,
15 + description =
"Lint pfui extension" 16 + depends = [
"//:install" ]
18 + "biome ci --config-path ../.. ." ,
19 + "rumdl check --config ../../.rumdl.toml ." ,
20 + "taplo format --check --config ../../.taplo.toml mise.toml" ,
24 + description =
"Test pfui extension" 25 + depends = [
"//:install" ]
27 + {
task =
"//:test" ,
args = [
"extensions/pfui" ] },
31 + description =
"Check pfui extension" 32 + depends = [
"//:install" ]
34 + {
task =
"//:build" ,
args = [
"pfui" ] },
extensions/pfui/package.json Added new file mode 100644 2 + "name" :
"@bugabinga/pi-ext-pfui" ,
7 + "description" :
"Pain-Free User Interface defaults and Pi context discovery." ,
12 + "peerDependencies" : {
13 + "@earendil-works/pi-coding-agent" :
"*" 15 + "devDependencies" : {
16 + "@marcfargas/pi-test-harness" :
"^0.6.1" ,
extensions/pfui/skills/pi-knowledge/SKILL.md Added new file mode 100644 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."
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.
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.
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" 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" 145 145 arg "[args]" var=#true package-lock.json Modified 44 + "name" :
"@bugabinga/pi-ext-ask" ,
46 + "devDependencies" : {
47 + "@marcfargas/pi-test-harness" :
"^0.6.1" ,
50 + "peerDependencies" : {
51 + "@earendil-works/pi-coding-agent" :
"*" ,
52 + "@earendil-works/pi-tui" :
"*" ,
43 56 "extensions/btw" : {
44 57 "name" :
"@bugabinga/pi-ext-btw" ,
194 207 "peerDependencies" : {
195 208 "@earendil-works/pi-ai" :
"*" ,
196 209 "@earendil-works/pi-coding-agent" :
"*" ,
210 + "@earendil-works/pi-tui" :
"*" ,
296 310 "@earendil-works/pi-coding-agent" :
"*" 313 + "extensions/pfui" : {
314 + "name" :
"@bugabinga/pi-ext-pfui" ,
316 + "devDependencies" : {
317 + "@marcfargas/pi-test-harness" :
"^0.6.1" ,
320 + "peerDependencies" : {
321 + "@earendil-works/pi-coding-agent" :
"*" 299 324 "extensions/prompt-autopsy" : {
300 325 "name" :
"@bugabinga/pi-ext-prompt-autopsy" ,
301 326 "license" :
"MIT" ,
1380 1405 "resolved" :
"extensions/angel" ,
1408 + "node_modules/@bugabinga/pi-ext-ask" : {
1409 + "resolved" :
"extensions/ask" ,
1383 1412 "node_modules/@bugabinga/pi-ext-btw" : {
1384 1413 "resolved" :
"extensions/btw" ,
1460 1489 "resolved" :
"extensions/os-notifier" ,
1492 + "node_modules/@bugabinga/pi-ext-pfui" : {
1493 + "resolved" :
"extensions/pfui" ,
1463 1496 "node_modules/@bugabinga/pi-ext-prompt-autopsy" : {
1464 1497 "resolved" :
"extensions/prompt-autopsy" ,
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']" );
830 + "root: pi.extensions must load pfui explicitly before the extension glob" ,
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(