@luxass/pi-questions 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lucas Nørgård
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @luxass/pi-questions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Answer structured questions from [Pi](https://github.com/badlogic/pi-mono) with choices, custom answers, notes, and Markdown previews.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pi install npm:@luxass/pi-questions
9
+ ```
10
+
11
+ Requires interactive Pi. RPC, JSON, and print modes are not supported. There are no commands or configuration files.
12
+
13
+ ## Use
14
+
15
+ The model can use `ask_questions` without an explicit request. Its instructions tell it to clarify unclear goals, scope, and constraints before implementing a new system or substantial feature. It skips questions you already answered and routine implementation details. You can also ask it to use the tool explicitly.
16
+
17
+ Each questionnaire accepts one to four questions, with two to four options per question.
18
+
19
+ The questionnaire opens below the conversation in Pi's editor area. With one question, confirming an answer submits it directly. With multiple questions, selecting an option moves to the next tab. The final Review tab lets you submit or cancel.
20
+
21
+ | Key | Action |
22
+ | --------------- | ---------------------------------------------------------- |
23
+ | Tab / Shift+Tab | Move to the next or previous tab outside text editors. |
24
+ | Right / Left | Move to the next or previous tab outside text editors. |
25
+ | Up / Down | Move between choices. |
26
+ | Enter | Choose an option, toggle a checkbox, or save custom text. |
27
+ | Space | Toggle an authored checkbox in a multi-select question. |
28
+ | 1–4 | Choose the corresponding authored option. |
29
+ | n | Edit a question note, or a global note on the Review tab. |
30
+ | q / p | Read the complete question or the focused option preview. |
31
+ | Ctrl+] | Collapse or expand without losing answers or drafts. |
32
+ | Ctrl+U | Clear the custom-answer draft while typing. |
33
+ | Delete | Clear the current answer outside text editors. Keep notes. |
34
+ | Escape | Cancel, save a note, or return from a question or preview. |
35
+
36
+ Focus `Type something.` to write a custom answer. Enter saves it, and Shift+Enter adds a line. Up or Down leaves the editor at the first or last line without discarding its text. For a multi-select question, custom text counts alongside checked options. Choose Next when you finish selecting.
37
+
38
+ Outside text editors, press q to read a long question or p to read the focused option's Markdown preview. Up, Down, Home, and End scroll these views. Escape returns to your choices. Wide terminals also show the preview beside the options. Narrow terminals show it below them.
39
+
40
+ Press n outside text editors to add a note. Enter or Escape saves the note. Notes do not count as choices. The Review tab allows partial answers and names unanswered questions. A note-only submission is allowed, but an empty submission is not.
41
+
42
+ Cancelling discards all draft answers. The questionnaire also closes when the agent aborts its request. Unanswered questions remain undecided.
43
+
44
+ In fullscreen Pi, Page Up, Page Down, and the mouse wheel scroll the conversation while you answer. In regular mode, use your terminal's scrollback controls.
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@luxass/pi-questions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.0",
4
+ "description": "Ask structured questions in Pi with tabs, choices, notes, and Markdown previews.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-extension",
8
+ "pi-package",
9
+ "questions"
10
+ ],
11
+ "license": "MIT",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/luxass/agent-extensions",
15
+ "directory": "packages/pi-questions"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "type": "module",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "peerDependencies": {
27
+ "@earendil-works/pi-coding-agent": "*",
28
+ "@earendil-works/pi-tui": "*",
29
+ "typebox": "*"
30
+ },
31
+ "pi": {
32
+ "image": "https://raw.githubusercontent.com/luxass/agent-extensions/main/packages/pi-questions/docs/cover.png",
33
+ "extensions": [
34
+ "./src/index.ts"
35
+ ]
36
+ },
37
+ "scripts": {
38
+ "lint": "oxlint --deny-warnings .",
39
+ "lint:fix": "oxlint --fix --deny-warnings .",
40
+ "fmt": "oxfmt .",
41
+ "fmt:check": "oxfmt --check .",
42
+ "typecheck": "tsc -p tsconfig.json"
43
+ }
6
44
  }
package/src/dialog.ts ADDED
@@ -0,0 +1,594 @@
1
+ import { getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ CURSOR_MARKER,
4
+ Editor,
5
+ isKeyRelease,
6
+ isKeyRepeat,
7
+ Markdown,
8
+ matchesKey,
9
+ ScrollView,
10
+ stripTerminalSequences,
11
+ truncateToWidth,
12
+ visibleWidth,
13
+ wrapTextWithAnsi,
14
+ type Component,
15
+ type Focusable,
16
+ type KeybindingsManager,
17
+ type TUI,
18
+ } from "@earendil-works/pi-tui";
19
+
20
+ import {
21
+ answerText,
22
+ cancelledResult,
23
+ collectAnswers,
24
+ type AnswerDraft,
25
+ type QuestionResult,
26
+ type Questions,
27
+ } from "./questions.ts";
28
+
29
+ interface DialogOptions {
30
+ params: Questions;
31
+ tui: TUI;
32
+ theme: Theme;
33
+ keybindings: KeybindingsManager;
34
+ done: (result: QuestionResult) => void;
35
+ }
36
+
37
+ type EditMode = "custom" | "notes";
38
+ type Mode = EditMode | "preview" | "question" | undefined;
39
+
40
+ interface Keys {
41
+ cancel: boolean;
42
+ confirm: boolean;
43
+ up: boolean;
44
+ down: boolean;
45
+ newLine: boolean;
46
+ }
47
+
48
+ export class QuestionDialog implements Component, Focusable {
49
+ private readonly options: DialogOptions;
50
+ private readonly questions: Questions["questions"];
51
+ private readonly drafts: AnswerDraft[];
52
+ private readonly rows: number[];
53
+ private readonly editors = new Map<string, Editor>();
54
+ private readonly markdown = new Map<string, Markdown>();
55
+ private readonly scroll: ScrollView;
56
+ private tab = 0;
57
+ private mode: Mode;
58
+ private globalNote = "";
59
+ private reviewRow = 0;
60
+ private focus = false;
61
+ private closed = false;
62
+ private collapsed = false;
63
+ private followSelection = true;
64
+ private selectedLine = 0;
65
+ private page = 1;
66
+ private warning = "";
67
+
68
+ constructor(options: DialogOptions) {
69
+ this.options = options;
70
+ this.questions = options.params.questions;
71
+ this.drafts = this.questions.map(() => ({
72
+ selected: new Set<number>(),
73
+ custom: "",
74
+ notes: "",
75
+ }));
76
+ this.rows = this.questions.map(() => 0);
77
+ this.scroll = new ScrollView(
78
+ {
79
+ render: (width) => this.body(width),
80
+ invalidate: () => this.markdown.clear(),
81
+ },
82
+ { scrollbar: "hidden" },
83
+ );
84
+ }
85
+
86
+ get focused(): boolean {
87
+ return this.focus;
88
+ }
89
+ set focused(value: boolean) {
90
+ this.focus = value;
91
+ this.syncFocus();
92
+ }
93
+
94
+ /** The Review tab follows the question tabs and only exists with several questions. */
95
+ private get isReview(): boolean {
96
+ return this.tab === this.drafts.length;
97
+ }
98
+
99
+ /** Focusing the `Type something.` row, which follows the options, opens its editor. */
100
+ private modeForRow(tab: number): Mode {
101
+ const question = this.questions[tab];
102
+ return question && this.rows[tab] === question.options.length ? "custom" : undefined;
103
+ }
104
+
105
+ private syncFocus(): void {
106
+ for (const editor of this.editors.values()) editor.focused = false;
107
+ if (!this.collapsed && (this.mode === "custom" || this.mode === "notes"))
108
+ this.editor(this.mode).focused = this.focus;
109
+ }
110
+
111
+ private editor(mode: EditMode): Editor {
112
+ const key = `${this.tab}:${mode}`;
113
+ const existing = this.editors.get(key);
114
+ if (existing) return existing;
115
+ const { tui, theme } = this.options;
116
+ const tab = this.tab;
117
+ const editor = new Editor(
118
+ tui,
119
+ {
120
+ borderColor: (text) => theme.fg("accent", text),
121
+ selectList: {
122
+ selectedPrefix: (text) => theme.fg("accent", text),
123
+ selectedText: (text) => theme.fg("accent", text),
124
+ description: (text) => theme.fg("muted", text),
125
+ scrollInfo: (text) => theme.fg("dim", text),
126
+ noMatch: (text) => theme.fg("warning", text),
127
+ },
128
+ },
129
+ { paddingX: 0 },
130
+ );
131
+ editor.onChange = () => {
132
+ // Multi-select custom text counts while typing; single-choice text counts once committed.
133
+ if (mode === "custom" && this.questions[tab]?.multiSelect)
134
+ this.drafts[tab]!.custom = editor.getExpandedText().trim();
135
+ };
136
+ editor.onSubmit = (text) => {
137
+ const value = text.trim();
138
+ const question = this.questions[tab];
139
+ const draft = this.drafts[tab];
140
+ // An empty single-choice custom answer is not a choice.
141
+ if (mode === "custom" && !value && !question?.multiSelect) return;
142
+ // Pi's Editor clears itself on submit. Keep saved text editable on return.
143
+ editor.setText(value);
144
+ if (mode === "notes") {
145
+ if (draft) draft.notes = value;
146
+ else this.globalNote = value;
147
+ } else if (draft) {
148
+ draft.custom = value;
149
+ if (value && !question?.multiSelect) draft.selected.clear();
150
+ }
151
+ // Leaving a note returns to the custom editor if that row is focused.
152
+ this.mode = mode === "notes" ? this.modeForRow(tab) : undefined;
153
+ if (mode === "custom") {
154
+ // If we are in multi select mode, we should not advance.
155
+ if (!question?.multiSelect) this.advance();
156
+ }
157
+
158
+ this.syncFocus();
159
+ this.followSelection = true;
160
+ tui.requestRender();
161
+ };
162
+ this.editors.set(key, editor);
163
+ return editor;
164
+ }
165
+
166
+ private switchTab(tab: number): void {
167
+ const count = this.drafts.length + (this.drafts.length > 1 ? 1 : 0);
168
+ this.tab = (tab + count) % count;
169
+ this.mode = this.modeForRow(this.tab);
170
+ this.warning = "";
171
+ this.scroll.scrollToStart();
172
+ this.followSelection = true;
173
+ this.syncFocus();
174
+ }
175
+
176
+ /** Moves to the next tab, or submits directly when there is only one question. */
177
+ private advance(): void {
178
+ if (this.drafts.length > 1) {
179
+ this.switchTab(this.tab + 1);
180
+ return;
181
+ }
182
+ const result = collectAnswers(this.options.params, this.drafts, this.globalNote);
183
+ if (result.answers.length) this.finish(result);
184
+ else this.warning = "Choose an option, write an answer, or add a note.";
185
+ }
186
+
187
+ private moveRow(delta: number): void {
188
+ if (this.isReview) this.reviewRow = (this.reviewRow + delta + 2) % 2;
189
+ else {
190
+ const question = this.questions[this.tab]!;
191
+ // Options, `Type something.`, and a Next or Submit row when needed.
192
+ const count =
193
+ question.options.length + (question.multiSelect || this.questions.length === 1 ? 2 : 1);
194
+ this.rows[this.tab] = (this.rows[this.tab]! + delta + count) % count;
195
+ this.mode = this.modeForRow(this.tab);
196
+ this.syncFocus();
197
+ }
198
+ this.followSelection = true;
199
+ }
200
+
201
+ private finish(result: QuestionResult): void {
202
+ if (this.closed) return;
203
+ this.closed = true;
204
+ this.options.done(result);
205
+ }
206
+
207
+ abort(): void {
208
+ this.finish(cancelledResult("aborted"));
209
+ }
210
+
211
+ private choose(): void {
212
+ if (this.isReview) {
213
+ if (this.reviewRow === 1) {
214
+ this.finish(cancelledResult());
215
+ return;
216
+ }
217
+ const result = collectAnswers(this.options.params, this.drafts, this.globalNote);
218
+ if (!result.answers.length && !result.globalNote) {
219
+ this.warning = "Provide an answer or a note before submitting.";
220
+ this.followSelection = true;
221
+ return;
222
+ }
223
+ this.finish(result);
224
+ return;
225
+ }
226
+ const question = this.questions[this.tab]!;
227
+ const row = this.rows[this.tab]!;
228
+ const draft = this.drafts[this.tab]!;
229
+ if (row === question.options.length) {
230
+ this.mode = "custom";
231
+ this.scroll.scrollToStart();
232
+ this.syncFocus();
233
+ } else if (row > question.options.length) {
234
+ // The Next or Submit row.
235
+ this.advance();
236
+ } else if (question.multiSelect) {
237
+ if (draft.selected.has(row)) draft.selected.delete(row);
238
+ else draft.selected.add(row);
239
+ } else {
240
+ draft.selected.clear();
241
+ draft.selected.add(row);
242
+ draft.custom = "";
243
+ this.advance();
244
+ }
245
+ this.followSelection = true;
246
+ }
247
+
248
+ private preview(): string | undefined {
249
+ return this.questions[this.tab]?.options[this.rows[this.tab] ?? 0]?.preview;
250
+ }
251
+
252
+ private wrap(
253
+ text: string,
254
+ width: number,
255
+ color: "text" | "muted" | "accent" | "warning" = "text",
256
+ ): string[] {
257
+ return wrapTextWithAnsi(this.options.theme.fg(color, stripTerminalSequences(text)), width);
258
+ }
259
+
260
+ private previewLines(text: string, width: number): string[] {
261
+ let component = this.markdown.get(text);
262
+ if (!component) {
263
+ component = new Markdown(stripTerminalSequences(text), 0, 0, getMarkdownTheme());
264
+ this.markdown.set(text, component);
265
+ }
266
+ return component.render(width);
267
+ }
268
+
269
+ private questionBody(width: number): string[] {
270
+ const question = this.questions[this.tab]!;
271
+ const draft = this.drafts[this.tab]!;
272
+ const preview = this.preview();
273
+ const sideBySide = Boolean(preview && width >= 96);
274
+ const leftWidth = sideBySide ? Math.floor(width * 0.45) : width;
275
+ const lines: string[] = [];
276
+ const current = this.rows[this.tab]!;
277
+ const add = (index: number, label: string, description?: string) => {
278
+ if (index === current) this.selectedLine = lines.length;
279
+ lines.push(
280
+ ...this.wrap(
281
+ `${index === current ? ">" : " "} ${label}`,
282
+ leftWidth,
283
+ index === current ? "accent" : "text",
284
+ ),
285
+ );
286
+ if (description) lines.push(...this.wrap(` ${description}`, leftWidth, "muted"));
287
+ lines.push("");
288
+ };
289
+ question.options.forEach((option, index) => {
290
+ const checked = draft.selected.has(index);
291
+ const marker = question.multiSelect ? (checked ? "[x]" : "[ ]") : checked ? "(x)" : "( )";
292
+ add(index, `${marker} ${index + 1}. ${option.label}`, option.description);
293
+ });
294
+ // Uncommitted editor text wins over the committed custom answer.
295
+ const customText =
296
+ this.editors.get(`${this.tab}:custom`)?.getExpandedText().trim() || draft.custom;
297
+ add(
298
+ question.options.length,
299
+ `${question.multiSelect ? (customText ? "[x] " : "[ ] ") : ""}Type something.`,
300
+ this.mode === "custom" ? undefined : customText || "Write your own answer.",
301
+ );
302
+ if (this.mode === "custom") lines.push(...this.editor("custom").render(width), "");
303
+ if (this.questions.length === 1 && !question.multiSelect)
304
+ add(
305
+ question.options.length + 1,
306
+ "Submit",
307
+ "Submit an answer or a note. Notes alone leave this question undecided.",
308
+ );
309
+ else if (question.multiSelect)
310
+ add(question.options.length + 1, "Next", "Keep these choices and move to the next tab.");
311
+ if (draft.notes) lines.push(...this.wrap(`Note: ${draft.notes}`, leftWidth, "muted"));
312
+ if (this.warning) lines.push(...this.wrap(this.warning, leftWidth, "warning"));
313
+ if (!preview) return lines;
314
+ const previewWidth = sideBySide ? width - leftWidth - 3 : width;
315
+ const rendered = this.previewLines(preview, previewWidth);
316
+ const pane = [
317
+ this.options.theme.fg("muted", "Preview · p opens full view"),
318
+ ...rendered.slice(0, 10),
319
+ ];
320
+ if (rendered.length > 10) pane.push(this.options.theme.fg("dim", "… press p to read more"));
321
+ if (!sideBySide) return [...lines, "", ...pane];
322
+ return Array.from({ length: Math.max(lines.length, pane.length) }, (_unused, index) => {
323
+ const left = truncateToWidth(lines[index] ?? "", leftWidth, "");
324
+ return (
325
+ left +
326
+ " ".repeat(Math.max(0, leftWidth - visibleWidth(left))) +
327
+ this.options.theme.fg("borderAccent", " │ ") +
328
+ (pane[index] ?? "")
329
+ );
330
+ });
331
+ }
332
+
333
+ private reviewBody(width: number): string[] {
334
+ const result = collectAnswers(this.options.params, this.drafts, this.globalNote);
335
+ const lines = [...this.wrap("Review your answers", width, "accent"), ""];
336
+ this.questions.forEach((question, index) => {
337
+ const answer = result.answers.find((candidate) => candidate.questionIndex === index);
338
+ lines.push(
339
+ ...this.wrap(
340
+ `${index + 1}. ${question.header}: ${answer ? answerText(answer) : "Not answered"}`,
341
+ width,
342
+ ),
343
+ );
344
+ if (answer?.notes) lines.push(...this.wrap(` Note: ${answer.notes}`, width, "muted"));
345
+ });
346
+ if (this.globalNote)
347
+ lines.push("", ...this.wrap(`Global note: ${this.globalNote}`, width, "muted"));
348
+ if (result.unanswered?.length)
349
+ lines.push(
350
+ "",
351
+ ...this.wrap(
352
+ `Unanswered: ${result.unanswered.map((index) => this.questions[index]!.header).join(", ")}. Submitting leaves these undecided.`,
353
+ width,
354
+ "warning",
355
+ ),
356
+ );
357
+ if (this.warning) lines.push("", ...this.wrap(this.warning, width, "warning"));
358
+ lines.push("");
359
+ this.selectedLine = lines.length + this.reviewRow;
360
+ lines.push(
361
+ ...["Submit answers", "Cancel questionnaire"].map((label, index) =>
362
+ this.options.theme.fg(
363
+ index === this.reviewRow ? "accent" : "text",
364
+ `${index === this.reviewRow ? ">" : " "} ${label}`,
365
+ ),
366
+ ),
367
+ );
368
+ return lines;
369
+ }
370
+
371
+ private body(width: number): string[] {
372
+ if (this.mode === "notes") {
373
+ const title = this.isReview ? "Global note" : "Question note";
374
+ return [this.options.theme.fg("accent", title), ...this.editor("notes").render(width)];
375
+ }
376
+ if (this.mode === "preview") return this.previewLines(this.preview() ?? "", width);
377
+ if (this.mode === "question")
378
+ return this.wrap(this.questions[this.tab]!.question, width, "accent");
379
+ this.selectedLine = 0;
380
+ return this.isReview ? this.reviewBody(width) : this.questionBody(width);
381
+ }
382
+
383
+ private renderTabs(width: number): string {
384
+ const { theme } = this.options;
385
+ const titles = this.questions.map((question, index) => {
386
+ const draft = this.drafts[index]!;
387
+ const label = `${index + 1}. ${question.header}${draft.selected.size || draft.custom ? " ✓" : ""}`;
388
+ return index === this.tab
389
+ ? theme.fg("accent", `[${stripTerminalSequences(label)}]`)
390
+ : theme.fg("muted", stripTerminalSequences(label));
391
+ });
392
+ if (this.drafts.length > 1)
393
+ titles.push(this.isReview ? theme.fg("accent", "[Review]") : theme.fg("muted", "Review"));
394
+ const tabs = titles.join(" · ");
395
+ if (visibleWidth(tabs) <= width) return tabs;
396
+ // Too narrow for every title: show the position and the current title only.
397
+ return theme.fg(
398
+ "accent",
399
+ `${this.tab + 1}/${titles.length} · ${stripTerminalSequences(this.questions[this.tab]?.header ?? "Review")}`,
400
+ );
401
+ }
402
+
403
+ private renderHelp(width: number): string {
404
+ if (this.mode === "custom" || this.mode === "notes")
405
+ return `Enter save · Shift+Enter newline · Ctrl+] collapse · Esc ${this.mode === "notes" ? "save note" : "cancel"}`;
406
+ if (this.mode === "preview" || this.mode === "question")
407
+ return `↑↓ scroll ${this.mode} · Ctrl+] collapse · Esc back`;
408
+ if (width < 70) return "q question · Enter choose · Ctrl+] collapse · Esc cancel";
409
+ return `${this.drafts.length > 1 ? "Tab tabs · " : ""}↑↓ move · Enter choose · q question · n note · p preview · Ctrl+] collapse · Esc cancel`;
410
+ }
411
+
412
+ render(width: number): string[] {
413
+ const { theme, tui } = this.options;
414
+ if (this.collapsed)
415
+ return [
416
+ theme.fg(
417
+ "dim",
418
+ truncateToWidth(
419
+ "Questions collapsed · Ctrl+] expand · Esc cancel",
420
+ Math.max(0, width),
421
+ "",
422
+ ),
423
+ ),
424
+ ];
425
+ // Cap the editor-slot height to leave room for the transcript.
426
+ const height = Math.min(tui.terminal.rows, Math.max(12, Math.floor(tui.terminal.rows * 0.7)));
427
+ if (width < 12 || height < 8)
428
+ return [
429
+ truncateToWidth("Resize to answer · Ctrl+] collapse · Esc cancel", Math.max(0, width), ""),
430
+ ];
431
+ const inner = width - 4;
432
+ const reading = this.mode === "preview" || this.mode === "question";
433
+ let heading =
434
+ !this.isReview && !reading
435
+ ? this.wrap(this.questions[this.tab]!.question, inner, "accent")
436
+ : [];
437
+ const headingLimit = Math.min(3, height - 6);
438
+ if (heading.length > headingLimit)
439
+ heading = [
440
+ ...heading.slice(0, headingLimit - 1),
441
+ theme.fg("muted", truncateToWidth("… q to read full question", inner, "")),
442
+ ];
443
+ // Borders, tabs, and help take four rows.
444
+ this.page = height - 4 - heading.length;
445
+ const lines = this.scroll.render(inner);
446
+ this.scroll.updateLayout(lines.length, this.page, () => tui.requestRender());
447
+ const editing = this.mode === "custom" || this.mode === "notes";
448
+ const focusLine = editing
449
+ ? lines.findIndex((line) => line.includes(CURSOR_MARKER))
450
+ : this.selectedLine;
451
+ if ((editing || this.followSelection) && !reading && focusLine >= 0) {
452
+ if (focusLine < this.scroll.scrollTop) this.scroll.scrollTo(focusLine);
453
+ else if (focusLine >= this.scroll.scrollTop + this.page)
454
+ this.scroll.scrollTo(focusLine - this.page + 1);
455
+ }
456
+ this.followSelection = false;
457
+ const visible = lines.slice(this.scroll.scrollTop, this.scroll.scrollTop + this.page);
458
+ while (visible.length < this.page) visible.push("");
459
+ const row = (text: string) => {
460
+ const fitted = truncateToWidth(text, inner, "");
461
+ return (
462
+ theme.fg("borderAccent", "│ ") +
463
+ fitted +
464
+ " ".repeat(Math.max(0, inner - visibleWidth(fitted))) +
465
+ theme.fg("borderAccent", " │")
466
+ );
467
+ };
468
+ return [
469
+ theme.fg("borderAccent", `┌${"─".repeat(width - 2)}┐`),
470
+ row(this.renderTabs(inner)),
471
+ ...heading.map(row),
472
+ ...visible.map(row),
473
+ row(theme.fg("dim", this.renderHelp(width))),
474
+ theme.fg("borderAccent", `└${"─".repeat(width - 2)}┘`),
475
+ ];
476
+ }
477
+
478
+ handleInput(data: string): void {
479
+ if (this.closed || isKeyRelease(data)) return;
480
+ const { keybindings, tui } = this.options;
481
+ // Collapse must work in every mode without changing any answers or editor drafts.
482
+ if (matchesKey(data, "ctrl+]")) {
483
+ if (!isKeyRepeat(data)) {
484
+ this.collapsed = !this.collapsed;
485
+ this.syncFocus();
486
+ this.followSelection = true;
487
+ tui.requestRender();
488
+ }
489
+ return;
490
+ }
491
+ const keys: Keys = {
492
+ cancel: keybindings.matches(data, "tui.select.cancel"),
493
+ confirm:
494
+ keybindings.matches(data, "tui.select.confirm") ||
495
+ keybindings.matches(data, "tui.input.submit"),
496
+ up: keybindings.matches(data, "tui.select.up"),
497
+ down: keybindings.matches(data, "tui.select.down"),
498
+ newLine: keybindings.matches(data, "tui.input.newLine"),
499
+ };
500
+ if (this.collapsed) {
501
+ if (keys.cancel) this.finish(cancelledResult());
502
+ return;
503
+ }
504
+ // These keys belong to Pi's transcript, not the questionnaire's body.
505
+ if (
506
+ keybindings.matches(data, "tui.select.pageUp") ||
507
+ keybindings.matches(data, "tui.select.pageDown")
508
+ )
509
+ return;
510
+ if (this.mode === "notes") this.handleNotesInput(data, keys);
511
+ else if (this.mode === "custom") this.handleCustomInput(data, keys);
512
+ else if (this.mode === "preview" || this.mode === "question") {
513
+ if (keys.cancel) {
514
+ this.mode = undefined;
515
+ this.scroll.scrollToStart();
516
+ this.followSelection = true;
517
+ } else this.scrollInput(data);
518
+ } else this.handleBrowseInput(data, keys);
519
+ tui.requestRender();
520
+ }
521
+
522
+ /** Enter and Escape both save the note. */
523
+ private handleNotesInput(data: string, keys: Keys): void {
524
+ const editor = this.editor("notes");
525
+ if (keys.cancel || (keys.confirm && !keys.newLine)) editor.onSubmit?.(editor.getExpandedText());
526
+ else editor.handleInput(data);
527
+ }
528
+
529
+ private handleCustomInput(data: string, keys: Keys): void {
530
+ const editor = this.editor("custom");
531
+ if (keys.cancel) this.finish(cancelledResult());
532
+ else if (keys.newLine) editor.handleInput(data);
533
+ else if (keys.confirm && !isKeyRepeat(data)) editor.onSubmit?.(editor.getExpandedText());
534
+ else if (matchesKey(data, "ctrl+u")) editor.setText("");
535
+ // Up and Down leave the editor at its edges, keeping the draft.
536
+ else if (keys.up && editor.getCursor().line === 0) this.moveRow(-1);
537
+ else if (keys.down && editor.getCursor().line === editor.getLines().length - 1) this.moveRow(1);
538
+ else editor.handleInput(data);
539
+ }
540
+
541
+ private handleBrowseInput(data: string, keys: Keys): void {
542
+ const multiTab = this.drafts.length > 1;
543
+ const question = this.questions[this.tab];
544
+ if (keys.cancel) this.finish(cancelledResult());
545
+ else if (multiTab && (matchesKey(data, "tab") || matchesKey(data, "right")))
546
+ this.switchTab(this.tab + 1);
547
+ else if (multiTab && (matchesKey(data, "shift+tab") || matchesKey(data, "left")))
548
+ this.switchTab(this.tab - 1);
549
+ else if (keys.up || keys.down) this.moveRow(keys.up ? -1 : 1);
550
+ else if (keys.confirm && !isKeyRepeat(data)) this.choose();
551
+ else if (
552
+ matchesKey(data, "space") &&
553
+ !isKeyRepeat(data) &&
554
+ question?.multiSelect &&
555
+ this.rows[this.tab]! < question.options.length
556
+ )
557
+ this.choose();
558
+ else if (matchesKey(data, "n") && !isKeyRepeat(data)) {
559
+ this.mode = "notes";
560
+ this.scroll.scrollToStart();
561
+ this.syncFocus();
562
+ } else if (matchesKey(data, "q") && question) {
563
+ this.mode = "question";
564
+ this.scroll.scrollToStart();
565
+ } else if (matchesKey(data, "p") && this.preview()) {
566
+ this.mode = "preview";
567
+ this.scroll.scrollToStart();
568
+ } else if (/^[1-9]$/.test(data) && question) {
569
+ const index = Number(data) - 1;
570
+ if (index < question.options.length) {
571
+ this.rows[this.tab] = index;
572
+ this.choose();
573
+ }
574
+ } else if (matchesKey(data, "delete") && question) {
575
+ const draft = this.drafts[this.tab]!;
576
+ draft.selected.clear();
577
+ draft.custom = "";
578
+ this.editors.get(`${this.tab}:custom`)?.setText("");
579
+ } else this.scrollInput(data);
580
+ }
581
+
582
+ private scrollInput(data: string): void {
583
+ const { keybindings } = this.options;
584
+ if (keybindings.matches(data, "tui.select.up")) this.scroll.scrollBy(-1);
585
+ else if (keybindings.matches(data, "tui.select.down")) this.scroll.scrollBy(1);
586
+ else if (matchesKey(data, "home")) this.scroll.scrollToStart();
587
+ else if (matchesKey(data, "end")) this.scroll.scrollToEnd();
588
+ }
589
+
590
+ invalidate(): void {
591
+ this.markdown.clear();
592
+ for (const editor of this.editors.values()) editor.invalidate();
593
+ }
594
+ }
package/src/index.ts ADDED
@@ -0,0 +1,156 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { stripTerminalSequences, Text } from "@earendil-works/pi-tui";
3
+
4
+ import { QuestionDialog } from "./dialog.ts";
5
+ import {
6
+ cancelledResult,
7
+ findQuestionsProblem,
8
+ MAX_OPTIONS,
9
+ MAX_QUESTIONS,
10
+ MIN_OPTIONS,
11
+ QuestionsSchema,
12
+ RESERVED_LABELS_TEXT,
13
+ ResultSchema,
14
+ type QuestionResult,
15
+ type Questions,
16
+ } from "./questions.ts";
17
+
18
+ const TOOL_NAME = "ask_questions";
19
+ // Only one questionnaire can own Pi's editor slot. Others stack at the bottom as overlays.
20
+ let inlineInUse = false;
21
+
22
+ async function showQuestions(
23
+ params: Questions,
24
+ ctx: ExtensionContext,
25
+ signal?: AbortSignal,
26
+ ): Promise<QuestionResult> {
27
+ const problem = findQuestionsProblem(params);
28
+ if (problem) return cancelledResult("invalid_questions", problem);
29
+ if (ctx.mode !== "tui")
30
+ return cancelledResult(
31
+ "no_ui",
32
+ "Questions were not shown. This tool requires interactive Pi. Ask the user in plain chat instead.",
33
+ );
34
+ if (signal?.aborted) return cancelledResult("aborted");
35
+ let dialog: QuestionDialog | undefined;
36
+ const abort = () => dialog?.abort();
37
+ signal?.addEventListener("abort", abort);
38
+ // Resolves to `undefined` when an inline mount finds the editor slot covered by an overlay.
39
+ const mount = (overlay: boolean) =>
40
+ ctx.ui.custom<QuestionResult | undefined>(
41
+ (tui, theme, keybindings, done) => {
42
+ // Do not mount an invisible question beneath an existing overlay.
43
+ if (!overlay && tui.hasOverlay()) {
44
+ done(undefined);
45
+ return { render: () => [], invalidate() {} };
46
+ }
47
+ dialog = new QuestionDialog({ params, tui, theme, keybindings, done });
48
+ if (signal?.aborted) dialog.abort();
49
+ return dialog;
50
+ },
51
+ overlay
52
+ ? {
53
+ overlay: true,
54
+ overlayOptions: { width: "100%", maxHeight: "70%", anchor: "bottom-center" },
55
+ }
56
+ : { overlay: false },
57
+ );
58
+ let ownsInlineSlot = !inlineInUse;
59
+ if (ownsInlineSlot) inlineInUse = true;
60
+ try {
61
+ if (ownsInlineSlot) {
62
+ const result = await mount(false);
63
+ if (result) return result;
64
+ inlineInUse = false;
65
+ ownsInlineSlot = false;
66
+ if (signal?.aborted) return cancelledResult("aborted");
67
+ }
68
+ return (await mount(true)) ?? cancelledResult("aborted");
69
+ } finally {
70
+ if (ownsInlineSlot) inlineInUse = false;
71
+ signal?.removeEventListener("abort", abort);
72
+ }
73
+ }
74
+ export default function askQuestions(pi: ExtensionAPI) {
75
+ pi.registerTool<typeof QuestionsSchema, QuestionResult>({
76
+ name: TOOL_NAME,
77
+ label: "Ask user",
78
+ description: `Ask the user 1–${MAX_QUESTIONS} related questions in a tabbed questionnaire. Give each question ${MIN_OPTIONS}–${MAX_OPTIONS} distinct options with descriptions. Optional previews are Markdown: use code fences for code or ASCII mockups. The user can select one or several options, type a custom answer, add notes, and review before submitting. Do not author ${RESERVED_LABELS_TEXT} options. Never treat cancellation or unanswered questions as approval.`,
79
+ promptSnippet:
80
+ "Clarify unclear goals, scope, and constraints before implementation instead of guessing.",
81
+ promptGuidelines: [
82
+ `Before implementing a new system or substantial feature, use ${TOOL_NAME} to clarify unclear goals, scope, and constraints. Skip questions the user has already answered.`,
83
+ `Use ${TOOL_NAME} when a meaningful user decision blocks progress, not for routine implementation details.`,
84
+ "Batch related questions and describe the trade-offs of each option. The UI supplies custom answers and notes.",
85
+ "Include Markdown previews when examples help the user compare alternatives.",
86
+ "Do not infer a choice for cancelled or unanswered questions. Notes alone do not answer a question.",
87
+ ],
88
+ parameters: QuestionsSchema,
89
+ outputSchema: ResultSchema,
90
+ exposure: "model-only",
91
+ // Sequential execution keeps two questionnaires from competing for input.
92
+ executionMode: "sequential",
93
+ annotations: {
94
+ readOnlyHint: true,
95
+ destructiveHint: false,
96
+ idempotentHint: false,
97
+ openWorldHint: false,
98
+ },
99
+ async execute(_id, params, signal, _update, ctx) {
100
+ const result = await showQuestions(params, ctx, signal);
101
+ const prefix =
102
+ result.message ??
103
+ (result.cancelled
104
+ ? "The questionnaire was cancelled. No answers were submitted."
105
+ : "The user submitted these answers. Unanswered questions remain undecided.");
106
+ return {
107
+ content: [{ type: "text", text: `${prefix}\n${JSON.stringify(result, null, 2)}` }],
108
+ details: result,
109
+ structuredContent: result,
110
+ isError: Boolean(result.error && result.error !== "aborted"),
111
+ };
112
+ },
113
+ renderCall(args, theme) {
114
+ const headers = Array.isArray(args.questions)
115
+ ? args.questions
116
+ .map((question) => question?.header)
117
+ .filter((header) => typeof header === "string")
118
+ : [];
119
+ return new Text(
120
+ theme.fg("toolTitle", "Ask user") +
121
+ theme.fg("muted", ` · ${stripTerminalSequences(headers.join(" · "))}`),
122
+ 0,
123
+ 0,
124
+ );
125
+ },
126
+ renderResult(result, options, theme) {
127
+ const details = result.details;
128
+ if (!details)
129
+ return new Text(
130
+ result.content
131
+ .filter((part) => part.type === "text")
132
+ .map((part) => part.text)
133
+ .join("\n"),
134
+ 0,
135
+ 0,
136
+ );
137
+ if (options.expanded) return new Text(JSON.stringify(details, null, 2), 0, 0);
138
+ const count = details.answers.length;
139
+ const label = details.error
140
+ ? (details.message ?? details.error)
141
+ : details.cancelled
142
+ ? "Questionnaire cancelled"
143
+ : `${count} ${count === 1 ? "answer" : "answers"} submitted${details.unanswered?.length ? ` · ${details.unanswered.length} unanswered` : ""}`;
144
+ return new Text(
145
+ theme.fg(details.cancelled ? "warning" : "success", stripTerminalSequences(label)),
146
+ 0,
147
+ 0,
148
+ );
149
+ },
150
+ });
151
+
152
+ pi.on("session_start", (_event, ctx) => {
153
+ if (ctx.mode !== "tui")
154
+ pi.setActiveTools(pi.getActiveTools().filter((name) => name !== TOOL_NAME));
155
+ });
156
+ }
@@ -0,0 +1,193 @@
1
+ import { Type, type Static } from "typebox";
2
+ import { Errors } from "typebox/value";
3
+
4
+ export const MAX_QUESTIONS = 4;
5
+ export const MIN_OPTIONS = 2;
6
+ export const MAX_OPTIONS = 4;
7
+ export const MAX_HEADER_LENGTH = 16;
8
+ export const MAX_LABEL_LENGTH = 60;
9
+
10
+ /** Labels the dialog supplies itself. Authored options must not duplicate them. */
11
+ export const RESERVED_LABELS = ["Other", "Type something.", "Next"] as const;
12
+
13
+ /** Human-readable list of reserved labels, e.g. for tool descriptions and errors. */
14
+ export const RESERVED_LABELS_TEXT = `${RESERVED_LABELS.slice(0, -1).join(", ")}, or ${RESERVED_LABELS.at(-1)}`;
15
+ // RESERVED_LABELS lowercased without punctuation, for matching.
16
+ const RESERVED = new Set(["other", "type something", "next"]);
17
+
18
+ const OptionSchema = Type.Object(
19
+ {
20
+ label: Type.String({ minLength: 1, maxLength: MAX_LABEL_LENGTH }),
21
+ description: Type.String({ minLength: 1 }),
22
+ preview: Type.Optional(
23
+ Type.String({ description: "Markdown, code, or a mockup for this option." }),
24
+ ),
25
+ },
26
+ { additionalProperties: false },
27
+ );
28
+
29
+ export const QuestionsSchema = Type.Object(
30
+ {
31
+ questions: Type.Array(
32
+ Type.Object(
33
+ {
34
+ question: Type.String({ minLength: 1 }),
35
+ header: Type.String({ minLength: 1, maxLength: MAX_HEADER_LENGTH }),
36
+ options: Type.Array(OptionSchema, { minItems: MIN_OPTIONS, maxItems: MAX_OPTIONS }),
37
+ multiSelect: Type.Optional(Type.Boolean()),
38
+ },
39
+ { additionalProperties: false },
40
+ ),
41
+ { minItems: 1, maxItems: MAX_QUESTIONS },
42
+ ),
43
+ },
44
+ { additionalProperties: false },
45
+ );
46
+
47
+ const QuestionIndexSchema = Type.Integer({ minimum: 0, maximum: MAX_QUESTIONS - 1 });
48
+
49
+ export const ResultSchema = Type.Object(
50
+ {
51
+ answers: Type.Array(
52
+ Type.Object(
53
+ {
54
+ questionIndex: QuestionIndexSchema,
55
+ question: Type.String(),
56
+ kind: Type.Union([Type.Literal("option"), Type.Literal("custom"), Type.Literal("multi")]),
57
+ answer: Type.Union([Type.String(), Type.Null()]),
58
+ selected: Type.Optional(Type.Array(Type.String())),
59
+ notes: Type.Optional(Type.String()),
60
+ preview: Type.Optional(Type.String()),
61
+ },
62
+ { additionalProperties: false },
63
+ ),
64
+ ),
65
+ cancelled: Type.Boolean(),
66
+ globalNote: Type.Optional(Type.String()),
67
+ unanswered: Type.Optional(Type.Array(QuestionIndexSchema)),
68
+ message: Type.Optional(Type.String()),
69
+ error: Type.Optional(
70
+ Type.Union([
71
+ Type.Literal("no_ui"),
72
+ Type.Literal("invalid_questions"),
73
+ Type.Literal("aborted"),
74
+ ]),
75
+ ),
76
+ },
77
+ { additionalProperties: false },
78
+ );
79
+
80
+ export type Questions = Static<typeof QuestionsSchema>;
81
+ export type Question = Questions["questions"][number];
82
+ export type QuestionResult = Static<typeof ResultSchema>;
83
+ export type QuestionError = NonNullable<QuestionResult["error"]>;
84
+ export type Answer = QuestionResult["answers"][number];
85
+
86
+ export interface AnswerDraft {
87
+ selected: Set<number>;
88
+ custom: string;
89
+ notes: string;
90
+ }
91
+
92
+ /** Builds a result that carries no answers, optionally explaining why. */
93
+ export function cancelledResult(error?: QuestionError, message?: string): QuestionResult {
94
+ return {
95
+ answers: [],
96
+ cancelled: true,
97
+ ...(error ? { error } : {}),
98
+ ...(message ? { message } : {}),
99
+ };
100
+ }
101
+
102
+ /** Returns a model-readable problem description, or `undefined` when the questions are valid. */
103
+ export function findQuestionsProblem(params: unknown): string | undefined {
104
+ const problems = new Set<string>();
105
+ for (const error of Errors(QuestionsSchema, params))
106
+ // `additionalProperties: false` also reports a less useful `schema is false` entry.
107
+ if (error.keyword !== "boolean") problems.add(`${error.instancePath || "/"} ${error.message}`);
108
+ if (problems.size)
109
+ return `Provide 1–${MAX_QUESTIONS} questions with ${MIN_OPTIONS}–${MAX_OPTIONS} options each, non-empty text, headers up to ${MAX_HEADER_LENGTH} characters, and labels up to ${MAX_LABEL_LENGTH} characters. Problems: ${[...problems].slice(0, 5).join("; ")}.`;
110
+ const { questions } = params as Questions;
111
+ const seenQuestions = new Set<string>();
112
+ for (const question of questions) {
113
+ const key = question.question.trim().toLowerCase();
114
+ if (!key || !question.header.trim()) return "Questions and headers must not be blank.";
115
+ if (seenQuestions.has(key)) return "Questions must be distinct.";
116
+ seenQuestions.add(key);
117
+ const seenLabels = new Set<string>();
118
+ for (const option of question.options) {
119
+ const label = option.label.trim().toLowerCase();
120
+ if (!label || !option.description.trim())
121
+ return "Option labels and descriptions must not be blank.";
122
+ // Ignore punctuation so `Other:` or `Type something` still match.
123
+ if (
124
+ RESERVED.has(
125
+ label
126
+ .replace(/[^\p{L}\p{N}\s]/gu, "")
127
+ .replace(/\s+/g, " ")
128
+ .trim(),
129
+ )
130
+ )
131
+ return `Do not author ${RESERVED_LABELS_TEXT} options. The UI provides custom answers and navigation.`;
132
+ if (seenLabels.has(label)) return "Option labels must be distinct within each question.";
133
+ seenLabels.add(label);
134
+ }
135
+ }
136
+ return undefined;
137
+ }
138
+
139
+ export function collectAnswers(
140
+ params: Questions,
141
+ drafts: readonly AnswerDraft[],
142
+ globalNote: string,
143
+ ): QuestionResult {
144
+ const answers: Answer[] = [];
145
+ const unanswered: number[] = [];
146
+ params.questions.forEach((question, questionIndex) => {
147
+ const draft = drafts[questionIndex];
148
+ if (!draft) return;
149
+ const options = question.options.filter((_option, index) => draft.selected.has(index));
150
+ const custom = draft.custom.trim();
151
+ const notes = draft.notes.trim();
152
+ const answered = options.length > 0 || custom.length > 0;
153
+ if (!answered) unanswered.push(questionIndex);
154
+ if (!answered && !notes) return;
155
+ const notesField = notes ? { notes } : {};
156
+ if (question.multiSelect) {
157
+ answers.push({
158
+ questionIndex,
159
+ question: question.question,
160
+ kind: "multi",
161
+ answer: custom || null,
162
+ selected: options.map((option) => option.label),
163
+ ...notesField,
164
+ });
165
+ return;
166
+ }
167
+ const [option] = options;
168
+ answers.push({
169
+ questionIndex,
170
+ question: question.question,
171
+ kind: option ? "option" : "custom",
172
+ answer: option?.label ?? (custom || null),
173
+ ...notesField,
174
+ ...(option?.preview ? { preview: option.preview } : {}),
175
+ });
176
+ });
177
+ const note = globalNote.trim();
178
+ return {
179
+ answers,
180
+ cancelled: false,
181
+ ...(note ? { globalNote: note } : {}),
182
+ ...(unanswered.length ? { unanswered } : {}),
183
+ };
184
+ }
185
+
186
+ export function answerText(answer: Answer): string {
187
+ if (answer.kind === "multi")
188
+ return (
189
+ [...(answer.selected ?? []), ...(answer.answer ? [answer.answer] : [])].join(", ") ||
190
+ "Not answered"
191
+ );
192
+ return answer.answer || "Not answered";
193
+ }