pi-asker 0.0.0-stage → 1.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 msvart
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,56 @@
1
- # Temporary Holding Version
1
+ # pi-asker
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
+ An `ask_user_question` tool for [pi](https://pi.dev). When the model would otherwise guess, it asks you instead, with options to pick from.
4
+
5
+ ```
6
+ ← ☑ Database ☐ Features ✔ Submit →
7
+
8
+ Which database should we use?
9
+
10
+ ❯ 1. Postgres (Recommended) ╭─ Preview ─────────────────────────╮
11
+ Relational and mature. │ services: │
12
+ 2. SQLite │ db: │
13
+ One file, no server. │ image: postgres:17 │
14
+ 3. Type something. ╰───────────────────────────────────╯
15
+
16
+ ────────────────────────────────────────
17
+ 4. 💬 I'm unsure – discuss this
18
+
19
+ Enter select · ↑↓ move · Tab/←→ switch · Esc cancel
20
+ ```
21
+
22
+ - **Tabs** – one per question plus a Submit tab. Move freely between them; answered questions are ticked.
23
+ - **Single and multi-select** – numbered options with descriptions; checkboxes when several answers apply.
24
+ - **Free text** – every question has a "Type something." row you type into directly.
25
+ - **Discuss** – unsure? Flag the question, optionally say why, and carry on with the rest. The model is told the question is not answered and to talk it through with you first.
26
+ - **Previews** – mockups, code or configs shown next to the options (below them in narrow terminals). Text is kept verbatim; fenced code blocks are syntax highlighted.
27
+ - **Review** – the Submit tab lists every answer, warns about unanswered questions, and takes an optional note for the model.
28
+ - **No hard limits** – the schema only requires one question and two options. The tool description steers the model towards a few short questions instead.
29
+ - **Interactive only** – in print, JSON and RPC mode (and in subagents) the tool is hidden from the model, since there is no one to answer.
30
+
31
+ ## Install
32
+
33
+ Requires pi 1.4 or newer.
34
+
35
+ ```bash
36
+ pi install npm:pi-asker
37
+ # or straight from GitHub
38
+ pi install git:github.com/msvart/pi-asker
39
+ ```
40
+
41
+ It registers the tool as `ask_user_question`, so remove any other package that registers the same name, such as `@juicesharp/rpiv-ask-user-question`.
42
+
43
+ ## Keys
44
+
45
+ | Key | Action |
46
+ | --- | --- |
47
+ | `↑` `↓` | Move between rows |
48
+ | `Enter` | Select, toggle, or confirm typed text |
49
+ | `Space` | Select or toggle an option |
50
+ | `1`–`9` | Jump to a row and select it |
51
+ | `Tab` `Shift+Tab` `←` `→` | Switch question (`←` `→` move the text cursor once you have typed something) |
52
+ | `Esc` | Cancel the questionnaire |
53
+
54
+ ## License
55
+
56
+ MIT
@@ -0,0 +1,706 @@
1
+ import { type ExtensionAPI, highlightCode, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ type Component,
4
+ type Focusable,
5
+ Input,
6
+ Key,
7
+ matchesKey,
8
+ Text,
9
+ type TUI,
10
+ truncateToWidth,
11
+ visibleWidth,
12
+ wrapTextWithAnsi,
13
+ } from "@earendil-works/pi-tui";
14
+ import { type Static, Type } from "typebox";
15
+
16
+ /**
17
+ * ask_user_question: a tab per question plus a Submit tab, numbered options, multi-select, a free-text row, a "discuss" row that flags a
18
+ * question for discussion instead of answering it, previews next to the options, and an
19
+ * optional note on the Submit tab. The schema only sets minimums; there are no length caps.
20
+ */
21
+
22
+ const OptionSchema = Type.Object({
23
+ label: Type.String({
24
+ description: "The text the user sees and selects. Keep it short (a few words) and clear.",
25
+ }),
26
+ description: Type.String({
27
+ description: "What this option means or what happens if chosen, including trade-offs.",
28
+ }),
29
+ preview: Type.Optional(
30
+ Type.String({
31
+ description:
32
+ "Optional preview shown next to the options while this option is focused: a mockup, code snippet, diagram or config to compare. Single-select only.",
33
+ }),
34
+ ),
35
+ });
36
+
37
+ const QuestionSchema = Type.Object({
38
+ question: Type.String({
39
+ description:
40
+ 'The complete question, clear and specific, ending with a question mark, e.g. "Which library should we use for date formatting?"',
41
+ }),
42
+ header: Type.String({
43
+ description: 'Short tag shown in the tab bar, one or two words, e.g. "Auth method", "Library".',
44
+ }),
45
+ options: Type.Array(OptionSchema, {
46
+ minItems: 2,
47
+ description:
48
+ "The choices, distinct and mutually exclusive unless multiSelect is set. A free-text row and a discuss row are appended automatically; do not author them.",
49
+ }),
50
+ multiSelect: Type.Optional(
51
+ Type.Boolean({ description: "Let the user select several options. Use when the choices are not exclusive." }),
52
+ ),
53
+ });
54
+
55
+ const ParamsSchema = Type.Object({
56
+ questions: Type.Array(QuestionSchema, { minItems: 1, description: "The questions to ask, one tab each." }),
57
+ });
58
+
59
+ type Params = Static<typeof ParamsSchema>;
60
+ type Question = Static<typeof QuestionSchema>;
61
+
62
+ interface Answer {
63
+ header: string;
64
+ question: string;
65
+ /** Chosen option labels, followed by the typed answer if it was chosen. */
66
+ values: string[];
67
+ /** Present when the user flagged the question for discussion: what they wrote, possibly empty. */
68
+ discuss?: string;
69
+ /** Preview of the chosen option of a single-select question. */
70
+ preview?: string;
71
+ }
72
+
73
+ interface Details {
74
+ answers: Answer[];
75
+ note?: string;
76
+ cancelled: boolean;
77
+ }
78
+
79
+ type Row = { kind: "option"; index: number } | { kind: "custom" } | { kind: "discuss" } | { kind: "next" };
80
+
81
+ interface QuestionState {
82
+ cursor: number;
83
+ chosen: Set<number>;
84
+ customChosen: boolean;
85
+ discussChosen: boolean;
86
+ custom: Input;
87
+ discuss: Input;
88
+ }
89
+
90
+ const TOOL_NAME = "ask_user_question";
91
+ const SUBMIT_ROWS = ["submit", "note", "cancel"] as const;
92
+ const SIDE_BY_SIDE_MIN_WIDTH = 100;
93
+ const STACKED_PREVIEW_HEIGHT = 12;
94
+ const TAB_HEADER_WIDTH = 24;
95
+
96
+ const DESCRIPTION = `Ask the user one or more structured questions during execution. Use when you need to:
97
+ 1. Gather user preferences or requirements
98
+ 2. Clarify ambiguous instructions
99
+ 3. Get decisions on implementation choices as you work
100
+ 4. Offer choices about what direction to take
101
+
102
+ Each question is a tab; the user can move freely between them and reviews all answers on a final Submit tab, where they can also add a note for you.
103
+
104
+ Usage notes:
105
+ - Every question gets two rows appended automatically: a free-text row ("Type something.") and a "Discuss this question" row. Do NOT author "Other", "Type something" or "Discuss" options yourself.
106
+ - A question the user flags for discussion is NOT answered. The result says so, with what they are unsure about; discuss it with them before acting on it.
107
+ - The user may submit with questions unanswered or press Esc to decline the whole questionnaire.
108
+ - Use multiSelect: true when several answers can apply.
109
+ - If you recommend an option, put it first and add "(Recommended)" at the end of its label.
110
+ - There is no hard limit on the number of questions or options, but each one costs the user attention: ask only what actually blocks you, typically up to about 4 questions with 2-5 options each.
111
+
112
+ Preview feature:
113
+ Use the optional \`preview\` field on options when presenting concrete artifacts the user needs to compare visually:
114
+ - ASCII mockups of UI layouts or components
115
+ - Code snippets showing different implementations
116
+ - Diagram variations
117
+ - Configuration examples
118
+
119
+ Previews are shown as preformatted monospace text next to the option list (below it in narrow terminals): line breaks and spacing are kept exactly, nothing is wrapped, and \`\`\`lang fenced blocks are syntax highlighted. Do not use previews for simple preference questions where labels and descriptions suffice. Previews are only supported for single-select questions.`;
120
+
121
+ const PROMPT_SNIPPET = "Ask the user structured multiple-choice questions when requirements are ambiguous";
122
+
123
+ const PROMPT_GUIDELINES = [
124
+ "Use ask_user_question whenever the user's request is underspecified and you cannot proceed without concrete decisions. Batch the related clarifying questions of one decision point into one call.",
125
+ "Give every question at least 2 distinct options, each with a short label and a description of what it means or its trade-offs. A free-text row and a discuss row are appended automatically; never author 'Other', 'Type something' or 'Discuss' options.",
126
+ "Set multiSelect: true when several answers can apply. Use options[].preview for concrete artifacts to compare (mockups, code, configs) on single-select questions. Put a recommended option first and append '(Recommended)' to its label.",
127
+ "A question the user flagged for discussion is not answered: talk it through with them before acting on it.",
128
+ ];
129
+
130
+ function isAnswered(answer: Answer): boolean {
131
+ return answer.values.length > 0 || answer.discuss !== undefined;
132
+ }
133
+
134
+ function answerOf(question: Question, state: QuestionState): Answer {
135
+ const values = question.options.filter((_, i) => state.chosen.has(i)).map((option) => option.label);
136
+ const custom = state.custom.getValue().trim();
137
+ if (state.customChosen && custom) values.push(custom);
138
+ const [only] = state.chosen;
139
+ const preview = question.multiSelect || only === undefined ? undefined : question.options[only].preview;
140
+ return {
141
+ header: question.header,
142
+ question: question.question,
143
+ values,
144
+ ...(state.discussChosen ? { discuss: state.discuss.getValue().trim() } : {}),
145
+ ...(preview ? { preview } : {}),
146
+ };
147
+ }
148
+
149
+ /** The model-facing result text. */
150
+ function envelope(details: Details): string {
151
+ if (details.cancelled) return "User declined to answer questions";
152
+ const answered = details.answers.filter(isAnswered);
153
+ const parts = answered.map((a) => {
154
+ if (a.discuss !== undefined) {
155
+ return `"${a.question}"=(not answered: the user wants to discuss this first${a.discuss ? `: ${a.discuss}` : ""})`;
156
+ }
157
+ return `"${a.question}"="${a.values.join(", ")}"${a.preview ? ` selected preview: ${a.preview}` : ""}`;
158
+ });
159
+ const unanswered = details.answers.filter((a) => !isAnswered(a)).map((a) => `"${a.question}"`);
160
+
161
+ let text = parts.length
162
+ ? `User has answered your questions: ${parts.join(". ")}.`
163
+ : "User submitted without answering any question.";
164
+ if (unanswered.length) text += ` Unanswered: ${unanswered.join(", ")}.`;
165
+ if (details.note) text += ` User note: "${details.note}".`;
166
+ text += answered.some((a) => a.discuss !== undefined)
167
+ ? " Discuss the flagged questions with the user before acting on them; continue with the other answers in mind."
168
+ : " You can now continue with the user's answers in mind.";
169
+ return text;
170
+ }
171
+
172
+ /** Models sometimes send the questions array as a JSON string. */
173
+ function parseArgs(args: unknown): Params {
174
+ const raw = args as { questions?: unknown };
175
+ if (typeof raw?.questions !== "string") return args as Params;
176
+ try {
177
+ return { ...raw, questions: JSON.parse(raw.questions) } as Params;
178
+ } catch {
179
+ return args as Params;
180
+ }
181
+ }
182
+
183
+ function clamp(value: number, min: number, max: number): number {
184
+ return Math.min(max, Math.max(min, value));
185
+ }
186
+
187
+ /** Cut or pad a line to exactly `width` columns. */
188
+ function fit(line: string, width: number): string {
189
+ const cut = truncateToWidth(line, width, "");
190
+ return cut + " ".repeat(Math.max(0, width - visibleWidth(cut)));
191
+ }
192
+
193
+ /** Preview text as display lines: kept verbatim, with ```lang fenced blocks highlighted. */
194
+ function previewLines(text: string): string[] {
195
+ const out: string[] = [];
196
+ let fence: { lang: string; body: string[] } | undefined;
197
+ const flush = () => {
198
+ if (fence) out.push(...highlightCode(fence.body.join("\n"), fence.lang || undefined));
199
+ fence = undefined;
200
+ };
201
+ for (const line of text.replace(/\r\n?/g, "\n").replace(/\t/g, " ").split("\n")) {
202
+ const marker = /^\s*```(\S*)/.exec(line);
203
+ if (marker) {
204
+ if (fence) flush();
205
+ else fence = { lang: marker[1], body: [] };
206
+ } else if (fence) {
207
+ fence.body.push(line);
208
+ } else {
209
+ out.push(line);
210
+ }
211
+ }
212
+ flush();
213
+ while (out.length && out[out.length - 1].trim() === "") out.pop();
214
+ return out;
215
+ }
216
+
217
+ class Dialog implements Component, Focusable {
218
+ private tab = 0;
219
+ private submitCursor = 0;
220
+ private closed = false;
221
+ private hasFocus = false;
222
+ private cache?: { width: number; lines: string[] };
223
+ private readonly states: QuestionState[];
224
+ private readonly note: Input;
225
+
226
+ constructor(
227
+ private readonly tui: TUI,
228
+ private readonly theme: Theme,
229
+ private readonly questions: Question[],
230
+ private readonly done: (details: Details) => void,
231
+ ) {
232
+ this.states = questions.map(() => ({
233
+ cursor: 0,
234
+ chosen: new Set<number>(),
235
+ customChosen: false,
236
+ discussChosen: false,
237
+ custom: this.input("Type something."),
238
+ discuss: this.input("What are you unsure about? (optional)"),
239
+ }));
240
+ this.note = this.input("Add a note for the agent (optional)");
241
+ }
242
+
243
+ get focused(): boolean {
244
+ return this.hasFocus;
245
+ }
246
+
247
+ set focused(value: boolean) {
248
+ this.hasFocus = value;
249
+ this.invalidate();
250
+ }
251
+
252
+ cancel(): void {
253
+ this.finish(false);
254
+ }
255
+
256
+ invalidate(): void {
257
+ this.cache = undefined;
258
+ }
259
+
260
+ handleInput(data: string): void {
261
+ this.onKey(data);
262
+ this.invalidate();
263
+ this.tui.requestRender();
264
+ }
265
+
266
+ render(width: number): string[] {
267
+ if (this.cache?.width === width) return this.cache.lines;
268
+ const t = this.theme;
269
+ const active = this.activeInput();
270
+ for (const input of this.inputs()) input.focused = input === active && this.hasFocus;
271
+
272
+ const rule = t.fg("accent", "─".repeat(width));
273
+ const head = [rule, this.tabBar(width), ""];
274
+ const foot = ["", ` ${t.fg("dim", this.help())}`, rule];
275
+ const budget = Math.max(8, this.tui.terminal.rows - 6) - head.length - foot.length;
276
+ const body = this.onSubmitTab() ? this.submitBody(width, budget) : this.questionBody(width, budget);
277
+ const lines = [...head, ...body, ...foot].map((line) => truncateToWidth(line, width, ""));
278
+ this.cache = { width, lines };
279
+ return lines;
280
+ }
281
+
282
+ // --- state -------------------------------------------------------------------------------
283
+
284
+ private input(placeholder: string): Input {
285
+ return new Input({ prompt: "", placeholder, placeholderStyle: (text) => this.theme.fg("dim", text) });
286
+ }
287
+
288
+ private inputs(): Input[] {
289
+ return [...this.states.flatMap((s) => [s.custom, s.discuss]), this.note];
290
+ }
291
+
292
+ private onSubmitTab(): boolean {
293
+ return this.tab === this.questions.length;
294
+ }
295
+
296
+ private rows(tab: number): Row[] {
297
+ const question = this.questions[tab];
298
+ const rows: Row[] = question.options.map((_, index) => ({ kind: "option", index }));
299
+ rows.push({ kind: "custom" });
300
+ if (question.multiSelect) rows.push({ kind: "next" });
301
+ rows.push({ kind: "discuss" });
302
+ return rows;
303
+ }
304
+
305
+ private currentRow(): Row {
306
+ return this.rows(this.tab)[this.states[this.tab].cursor];
307
+ }
308
+
309
+ /** The text field under the cursor, if any. */
310
+ private activeInput(): Input | undefined {
311
+ if (this.onSubmitTab()) return SUBMIT_ROWS[this.submitCursor] === "note" ? this.note : undefined;
312
+ const state = this.states[this.tab];
313
+ const row = this.currentRow();
314
+ return row.kind === "custom" ? state.custom : row.kind === "discuss" ? state.discuss : undefined;
315
+ }
316
+
317
+ private answers(): Answer[] {
318
+ return this.questions.map((question, i) => answerOf(question, this.states[i]));
319
+ }
320
+
321
+ private finish(submitted: boolean): void {
322
+ if (this.closed) return;
323
+ this.closed = true;
324
+ const note = this.note.getValue().trim();
325
+ this.done(
326
+ submitted
327
+ ? { answers: this.answers(), ...(note ? { note } : {}), cancelled: false }
328
+ : { answers: [], cancelled: true },
329
+ );
330
+ }
331
+
332
+ // --- input -------------------------------------------------------------------------------
333
+
334
+ private onKey(data: string): void {
335
+ const input = this.activeInput();
336
+ if (matchesKey(data, Key.escape)) return this.finish(false);
337
+ if (matchesKey(data, Key.tab)) return this.switchTab(1);
338
+ if (matchesKey(data, Key.shift("tab"))) return this.switchTab(-1);
339
+ if (matchesKey(data, Key.up)) return this.move(-1);
340
+ if (matchesKey(data, Key.down)) return this.move(1);
341
+ if (matchesKey(data, Key.enter)) return this.confirm();
342
+ // Left/right move the text cursor once there is text, and switch tabs otherwise.
343
+ if (input && input.getValue() !== "") return input.handleInput(data);
344
+ if (matchesKey(data, Key.left)) return this.switchTab(-1);
345
+ if (matchesKey(data, Key.right)) return this.switchTab(1);
346
+ if (input) return input.handleInput(data);
347
+ if (matchesKey(data, Key.space)) return this.confirm();
348
+ if (/^[1-9]$/.test(data)) this.jump(Number(data) - 1);
349
+ }
350
+
351
+ private switchTab(delta: number): void {
352
+ const count = this.questions.length + 1;
353
+ this.tab = (this.tab + delta + count) % count;
354
+ if (this.onSubmitTab()) this.submitCursor = 0;
355
+ }
356
+
357
+ private move(delta: number): void {
358
+ if (this.onSubmitTab()) {
359
+ this.submitCursor = clamp(this.submitCursor + delta, 0, SUBMIT_ROWS.length - 1);
360
+ return;
361
+ }
362
+ const state = this.states[this.tab];
363
+ state.cursor = clamp(state.cursor + delta, 0, this.rows(this.tab).length - 1);
364
+ }
365
+
366
+ private jump(index: number): void {
367
+ if (this.onSubmitTab()) {
368
+ if (index >= SUBMIT_ROWS.length) return;
369
+ this.submitCursor = index;
370
+ if (SUBMIT_ROWS[index] !== "note") this.confirm();
371
+ return;
372
+ }
373
+ const rows = this.rows(this.tab);
374
+ if (index >= rows.length) return;
375
+ this.states[this.tab].cursor = index;
376
+ if (rows[index].kind === "option" || rows[index].kind === "next") this.confirm();
377
+ }
378
+
379
+ private advance(): void {
380
+ this.switchTab(this.onSubmitTab() ? 0 : 1);
381
+ }
382
+
383
+ private confirm(): void {
384
+ if (this.onSubmitTab()) {
385
+ const row = SUBMIT_ROWS[this.submitCursor];
386
+ return this.finish(row !== "cancel");
387
+ }
388
+ const question = this.questions[this.tab];
389
+ const state = this.states[this.tab];
390
+ const row = this.currentRow();
391
+ switch (row.kind) {
392
+ case "option":
393
+ state.discussChosen = false;
394
+ if (question.multiSelect) {
395
+ if (!state.chosen.delete(row.index)) state.chosen.add(row.index);
396
+ return;
397
+ }
398
+ state.chosen = new Set([row.index]);
399
+ state.customChosen = false;
400
+ return this.advance();
401
+ case "custom": {
402
+ const hasText = state.custom.getValue().trim() !== "";
403
+ if (question.multiSelect) {
404
+ state.customChosen = hasText && !state.customChosen;
405
+ if (state.customChosen) state.discussChosen = false;
406
+ return;
407
+ }
408
+ if (!hasText) return;
409
+ state.chosen.clear();
410
+ state.customChosen = true;
411
+ state.discussChosen = false;
412
+ return this.advance();
413
+ }
414
+ case "discuss":
415
+ state.chosen.clear();
416
+ state.customChosen = false;
417
+ state.discussChosen = true;
418
+ return this.advance();
419
+ case "next":
420
+ return this.advance();
421
+ }
422
+ }
423
+
424
+ // --- rendering ---------------------------------------------------------------------------
425
+
426
+ private help(): string {
427
+ const input = this.activeInput();
428
+ if (this.onSubmitTab()) {
429
+ return input
430
+ ? "Type a note · Enter submit · ↑↓ move · Tab switch · Esc cancel"
431
+ : "Enter confirm · ↑↓ move · Tab/←→ switch · Esc cancel";
432
+ }
433
+ const row = this.currentRow();
434
+ if (row.kind === "discuss") return "Type what you're unsure about · Enter flag for discussion · ↑↓ move · Esc cancel";
435
+ if (row.kind === "custom") return "Type your answer · Enter confirm · ↑↓ move · Tab switch · Esc cancel";
436
+ const select = this.questions[this.tab].multiSelect ? "Enter/Space toggle" : "Enter select";
437
+ return `${select} · ↑↓ move · Tab/←→ switch · Esc cancel`;
438
+ }
439
+
440
+ private tabBar(width: number): string {
441
+ const t = this.theme;
442
+ const answers = this.answers();
443
+ const tabs = answers.map((answer, i) => {
444
+ const discuss = answer.discuss !== undefined;
445
+ const mark = discuss ? "?" : isAnswered(answer) ? "☑" : "☐";
446
+ const text = ` ${mark} ${truncateToWidth(answer.header, TAB_HEADER_WIDTH)} `;
447
+ if (i === this.tab) return t.bg("selectedBg", t.fg("text", text));
448
+ return t.fg(discuss ? "warning" : isAnswered(answer) ? "success" : "muted", text);
449
+ });
450
+ const submit = " ✔ Submit ";
451
+ tabs.push(
452
+ this.onSubmitTab()
453
+ ? t.bg("selectedBg", t.fg("text", submit))
454
+ : t.fg(answers.every(isAnswered) ? "success" : "dim", submit),
455
+ );
456
+
457
+ // Drop tabs farthest from the current one until the bar fits.
458
+ let start = 0;
459
+ let end = tabs.length;
460
+ const room = width - 10;
461
+ while (end - start > 1 && visibleWidth(tabs.slice(start, end).join(" ")) > room) {
462
+ if (this.tab - start > end - 1 - this.tab) start++;
463
+ else end--;
464
+ }
465
+ const left = start > 0 ? t.fg("dim", "… ") : "";
466
+ const right = end < tabs.length ? t.fg("dim", " …") : "";
467
+ return ` ${t.fg("dim", "←")} ${left}${tabs.slice(start, end).join(" ")}${right} ${t.fg("dim", "→")}`;
468
+ }
469
+
470
+ private questionBody(width: number, budget: number): string[] {
471
+ const question = this.questions[this.tab];
472
+ const state = this.states[this.tab];
473
+ const title = wrapTextWithAnsi(this.theme.bold(question.question), width - 1).map((line) => ` ${line}`);
474
+ const hasPreview = !question.multiSelect && question.options.some((option) => option.preview);
475
+ const sideBySide = hasPreview && width >= SIDE_BY_SIDE_MIN_WIDTH;
476
+ const listWidth = sideBySide ? Math.min(60, Math.floor(width * 0.42)) : width;
477
+
478
+ const row = this.currentRow();
479
+ const [chosen] = state.chosen;
480
+ const previewIndex = row.kind === "option" ? row.index : chosen;
481
+ const preview = previewIndex === undefined ? undefined : question.options[previewIndex].preview;
482
+ const stackedHeight =
483
+ hasPreview && !sideBySide ? Math.min(STACKED_PREVIEW_HEIGHT, (preview ? previewLines(preview).length : 1) + 2) : 0;
484
+
485
+ const listBudget = Math.max(3, budget - title.length - 1 - (stackedHeight ? stackedHeight + 1 : 0));
486
+ const list = this.windowed(this.rowBlocks(listWidth), state.cursor, listBudget);
487
+ const out = [...title, ""];
488
+ if (!hasPreview) return [...out, ...list];
489
+
490
+ if (!sideBySide) return [...out, ...list, "", ...this.box(preview, width - 1, stackedHeight).map((l) => ` ${l}`)];
491
+
492
+ const box = this.box(preview, width - listWidth - 2, Math.max(list.length, listBudget));
493
+ for (let i = 0; i < Math.max(list.length, box.length); i++) {
494
+ out.push(`${fit(list[i] ?? "", listWidth)} ${box[i] ?? ""}`);
495
+ }
496
+ return out;
497
+ }
498
+
499
+ /** One block of lines per row of the current question. */
500
+ private rowBlocks(width: number): string[][] {
501
+ const t = this.theme;
502
+ const question = this.questions[this.tab];
503
+ const state = this.states[this.tab];
504
+ const rows = this.rows(this.tab);
505
+ const numberWidth = String(rows.length).length;
506
+ const lastQuestion = this.tab === this.questions.length - 1;
507
+
508
+ return rows.map((row, i) => {
509
+ const active = i === state.cursor;
510
+ const pointer = active ? t.fg("accent", "❯ ") : " ";
511
+ const number = `${String(i + 1).padStart(numberWidth)}. `;
512
+ const checkbox = (checked: boolean) => (checked ? t.fg("success", "[✔] ") : t.fg("muted", "[ ] "));
513
+ const tick = (checked: boolean) => (checked ? t.fg("success", " ✔") : "");
514
+ const color = active ? "accent" : "text";
515
+
516
+ let mark = "";
517
+ let label: string;
518
+ let description: string | undefined;
519
+ let input: Input | undefined;
520
+ switch (row.kind) {
521
+ case "option": {
522
+ const option = question.options[row.index];
523
+ const checked = state.chosen.has(row.index);
524
+ if (question.multiSelect) mark = checkbox(checked);
525
+ label = t.fg(color, option.label) + (question.multiSelect ? "" : tick(checked));
526
+ description = option.description;
527
+ break;
528
+ }
529
+ case "custom": {
530
+ const text = state.custom.getValue();
531
+ const checked = state.customChosen && text.trim() !== "";
532
+ if (question.multiSelect) mark = checkbox(checked);
533
+ if (active) input = state.custom;
534
+ label = (text ? t.fg(color, text) : t.fg("dim", "Type something.")) + (question.multiSelect ? "" : tick(checked));
535
+ break;
536
+ }
537
+ case "discuss": {
538
+ const text = state.discuss.getValue();
539
+ if (active) input = state.discuss;
540
+ const base = text ? `Discuss: ${text}` : "💬 I'm unsure – discuss this";
541
+ label = t.fg(state.discussChosen ? "warning" : active ? "accent" : "muted", base);
542
+ if (state.discussChosen) label += t.fg("warning", " ?");
543
+ break;
544
+ }
545
+ case "next":
546
+ label = t.fg(color, lastQuestion ? "Review answers →" : "Next question →");
547
+ break;
548
+ }
549
+
550
+ const lead = pointer + t.fg(active ? "accent" : "muted", number) + mark;
551
+ const indent = " ".repeat(visibleWidth(lead));
552
+ const textWidth = Math.max(1, width - visibleWidth(lead));
553
+ const lines = input
554
+ ? [lead + input.render(textWidth)[0]]
555
+ : wrapTextWithAnsi(label, textWidth).map((line, j) => (j === 0 ? lead : indent) + line);
556
+ if (description) {
557
+ lines.push(...wrapTextWithAnsi(t.fg("muted", description), textWidth).map((line) => indent + line));
558
+ }
559
+ // Discuss is not an answer: set it apart from the options.
560
+ if (row.kind === "discuss") lines.unshift("", ` ${t.fg("dim", "─".repeat(Math.max(1, Math.min(40, width - 2))))}`);
561
+ return lines;
562
+ });
563
+ }
564
+
565
+ /** The blocks around the cursor that fit in `budget` lines, with markers for the rest. */
566
+ private windowed(blocks: string[][], cursor: number, budget: number): string[] {
567
+ if (blocks.reduce((sum, block) => sum + block.length, 0) <= budget) return blocks.flat();
568
+ const room = Math.max(1, budget - 2);
569
+ let start = cursor;
570
+ let end = cursor + 1;
571
+ let used = blocks[cursor].length;
572
+ for (let grew = true; grew; ) {
573
+ grew = false;
574
+ if (end < blocks.length && used + blocks[end].length <= room) {
575
+ used += blocks[end++].length;
576
+ grew = true;
577
+ }
578
+ if (start > 0 && used + blocks[start - 1].length <= room) {
579
+ used += blocks[--start].length;
580
+ grew = true;
581
+ }
582
+ }
583
+ const dim = (text: string) => this.theme.fg("dim", text);
584
+ return [
585
+ ...(start > 0 ? [dim(` ↑ ${start} more`)] : []),
586
+ ...blocks.slice(start, end).flat().slice(0, room),
587
+ ...(end < blocks.length ? [dim(` ↓ ${blocks.length - end} more`)] : []),
588
+ ];
589
+ }
590
+
591
+ private box(preview: string | undefined, width: number, height: number): string[] {
592
+ const t = this.theme;
593
+ const inner = Math.max(1, width - 4);
594
+ const room = Math.max(1, height - 2);
595
+ let body = preview ? previewLines(preview) : [t.fg("dim", "No preview")];
596
+ if (body.length > room) {
597
+ body = [...body.slice(0, room - 1), t.fg("dim", `… +${body.length - room + 1} lines`)];
598
+ }
599
+ const title = " Preview ";
600
+ const border = (text: string) => t.fg("border", text);
601
+ return [
602
+ border(`╭─${title}${"─".repeat(Math.max(0, width - 3 - title.length))}╮`),
603
+ ...body.map((line) => `${border("│")} ${fit(line, inner)} ${border("│")}`),
604
+ border(`╰${"─".repeat(Math.max(0, width - 2))}╯`),
605
+ ];
606
+ }
607
+
608
+ private submitBody(width: number, budget: number): string[] {
609
+ const t = this.theme;
610
+ const answers = this.answers();
611
+ const wrap = (text: string, indent: string) =>
612
+ wrapTextWithAnsi(text, Math.max(1, width - indent.length)).map((line) => indent + line);
613
+
614
+ let review: string[] = [];
615
+ for (const answer of answers) {
616
+ review.push(...wrap(`${t.fg("muted", "●")} ${answer.question}`, " "));
617
+ const result =
618
+ answer.discuss !== undefined
619
+ ? t.fg("warning", `→ Discuss${answer.discuss ? `: ${answer.discuss}` : ""}`)
620
+ : isAnswered(answer)
621
+ ? t.fg("success", `→ ${answer.values.join(", ")}`)
622
+ : t.fg("dim", "→ (unanswered)");
623
+ review.push(...wrap(result, " "));
624
+ }
625
+
626
+ const missing = answers.filter((answer) => !isAnswered(answer)).length;
627
+ const warning = missing
628
+ ? ["", ` ${t.fg("warning", `${missing} unanswered question${missing === 1 ? "" : "s"}: submit anyway or go back`)}`]
629
+ : [];
630
+ const rows = SUBMIT_ROWS.map((row, i) => {
631
+ const active = i === this.submitCursor;
632
+ const lead = (active ? t.fg("accent", "❯ ") : " ") + t.fg(active ? "accent" : "muted", `${i + 1}. `);
633
+ const color = active ? "accent" : "text";
634
+ if (row === "submit") return lead + t.fg(color, "Submit answers");
635
+ if (row === "cancel") return lead + t.fg(color, "Cancel");
636
+ if (active) return lead + this.note.render(Math.max(1, width - 5))[0];
637
+ const note = this.note.getValue();
638
+ return lead + (note ? t.fg(color, `Note: ${note}`) : t.fg("dim", "Add a note for the agent (optional)"));
639
+ });
640
+
641
+ const room = Math.max(1, budget - 2 - warning.length - 1 - rows.length);
642
+ if (review.length > room) review = [...review.slice(0, room - 1), t.fg("dim", " …")];
643
+ return [` ${t.bold("Review your answers")}`, "", ...review, ...warning, "", ...rows];
644
+ }
645
+ }
646
+
647
+ export default function (pi: ExtensionAPI) {
648
+ // Without the terminal UI (print, JSON, RPC, subagents) the dialog cannot be shown, so the
649
+ // model should not see the tool at all. The mode is fixed for the process.
650
+ pi.on("before_agent_start", (_event, ctx) => {
651
+ if (ctx.mode === "tui") return;
652
+ const active = pi.getActiveTools();
653
+ if (active.includes(TOOL_NAME)) pi.setActiveTools(active.filter((name) => name !== TOOL_NAME));
654
+ });
655
+
656
+ pi.registerTool({
657
+ name: TOOL_NAME,
658
+ label: "Ask User Question",
659
+ description: DESCRIPTION,
660
+ promptSnippet: PROMPT_SNIPPET,
661
+ promptGuidelines: PROMPT_GUIDELINES,
662
+ parameters: ParamsSchema,
663
+ exposure: "model-only",
664
+ executionMode: "sequential",
665
+
666
+ prepareArguments: parseArgs,
667
+
668
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
669
+ const details = await ctx.ui.custom<Details>((tui, theme, _keybindings, done) => {
670
+ const dialog = new Dialog(tui, theme, params.questions, done);
671
+ signal?.addEventListener("abort", () => dialog.cancel(), { once: true });
672
+ return dialog;
673
+ });
674
+ return { content: [{ type: "text", text: envelope(details) }], details };
675
+ },
676
+
677
+ renderCall(args, theme) {
678
+ const parsed = parseArgs(args)?.questions;
679
+ const questions = Array.isArray(parsed) ? parsed : [];
680
+ const headers = questions.map((q) => q?.header).filter(Boolean);
681
+ let text = theme.fg("toolTitle", theme.bold("ask_user_question "));
682
+ text += theme.fg("muted", `${questions.length} question${questions.length === 1 ? "" : "s"}`);
683
+ if (headers.length) text += theme.fg("dim", ` (${headers.join(", ")})`);
684
+ return new Text(text, 0, 0);
685
+ },
686
+
687
+ renderResult(result, _options, theme) {
688
+ const details = result.details as Details | undefined;
689
+ if (!details?.answers) {
690
+ const first = result.content[0];
691
+ return new Text(first?.type === "text" ? first.text : "", 0, 0);
692
+ }
693
+ if (details.cancelled) return new Text(theme.fg("warning", "Cancelled"), 0, 0);
694
+ const lines = details.answers.map((a) => {
695
+ const header = theme.fg("accent", a.header);
696
+ if (a.discuss !== undefined) {
697
+ return `${theme.fg("warning", "? ")}${header}: ${theme.fg("warning", "discuss")}${a.discuss ? ` – ${a.discuss}` : ""}`;
698
+ }
699
+ if (isAnswered(a)) return `${theme.fg("success", "✓ ")}${header}: ${a.values.join(", ")}`;
700
+ return `${theme.fg("dim", "– ")}${header}: ${theme.fg("dim", "unanswered")}`;
701
+ });
702
+ if (details.note) lines.push(`${theme.fg("muted", "Note:")} ${details.note}`);
703
+ return new Text(lines.join("\n"), 0, 0);
704
+ },
705
+ });
706
+ }
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "pi-asker",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "ask_user_question for pi: tabs, multi-select, previews, a review tab, and a way to flag a question for discussion",
5
+ "keywords": ["pi-package"],
6
+ "license": "MIT",
7
+ "author": "msvart",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/msvart/pi-asker.git"
11
+ },
12
+ "type": "module",
13
+ "files": ["extensions", "README.md", "LICENSE"],
14
+ "pi": {
15
+ "extensions": ["./extensions/ask-user-question.ts"]
16
+ },
17
+ "peerDependencies": {
18
+ "@earendil-works/pi-coding-agent": "*",
19
+ "@earendil-works/pi-tui": "*",
20
+ "typebox": "*"
21
+ }
22
+ }