@juicesharp/rpiv-ask-user-question 2.0.0 → 2.2.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/README.md CHANGED
@@ -1,109 +1,91 @@
1
- # rpiv-ask-user-question
1
+ # @juicesharp/rpiv-ask-user-question
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@juicesharp/rpiv-ask-user-question.svg)](https://www.npmjs.com/package/@juicesharp/rpiv-ask-user-question)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
2
5
 
3
6
  <div align="center">
4
7
  <a href="https://github.com/juicesharp/rpiv-mono/tree/main/packages/rpiv-ask-user-question">
5
- <picture>
6
- <img src="https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-ask-user-question/docs/cover.png" alt="rpiv-ask-user-question cover" width="50%">
7
- </picture>
8
+ <img src="https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-ask-user-question/docs/cover.png" alt="rpiv-ask-user-question cover: a tabbed terminal questionnaire asking Which real development task are we planning right now?, with numbered options — Bug fix, New feature, Refactor — each under a one-line description, and a footer of key hints" width="50%">
8
9
  </a>
9
10
  </div>
10
11
 
11
- Let the model ask you structured clarifying questions instead of guessing. `rpiv-ask-user-question` adds the `ask_user_question` tool to [Pi Agent](https://github.com/badlogic/pi-mono) - a tabbed dialog with single- and multi-select questions, side-by-side previews, per-option notes, and a Submit tab that reviews answers before they go back to the model.
12
+ Let the model ask you instead of guessing. This extension gives [Pi Agent](https://github.com/badlogic/pi-mono) one tool — `ask_user_question` — that opens a terminal dialog of up to four questions with written-out options, and hands your choices back as structured data. Install it if you would rather spend fifteen seconds picking than an hour undoing a wrong assumption.
12
13
 
13
- ![Side-by-side code preview](https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-ask-user-question/docs/code-preview.jpg)
14
+ ## Install
14
15
 
15
- ## Features
16
+ ```sh
17
+ pi install npm:@juicesharp/rpiv-ask-user-question
18
+ ```
16
19
 
17
- - **Multi-question dialogs** - ask several questions in one turn with a tab bar (`Tab` to switch).
18
- - **Preview pane** - render an ASCII diagram, code snippet, or markdown next to each option, side-by-side or stacked depending on terminal width.
19
- - **Per-option notes** - press `n` on a previewed option to attach a free-text note that travels back with the answer.
20
- - **Multi-select questions** - checkboxes with `Space` to toggle, Enter-as-toggle on rows, a `Next` sentinel to advance, and toggles persisted across tab switches.
21
- - **Submit tab** - review every answer before submitting; warns about unanswered questions and offers a Submit picker.
22
- - **Chat row on every tab** - redirect the conversation without leaving the dialog.
23
- - **Terminal-row-aware overflow scroll** - when the dialog is taller than the terminal, the body scrolls between a sticky heading and sticky hints/border; overflow indicators (↑ / ↓ / ↕) show what's clipped.
24
- - **"Other" free-text fallback** - type a custom answer when no option fits; available on every single-select question, even in preview mode (the input expands to the full pane width while typing).
25
- - **Localized UI** - sentinel rows, hints, submit/cancel labels, review pane, and notes affordance display in the user's chosen language via `@juicesharp/rpiv-i18n`. Ships Deutsch / English / Español / Français / Português (PT) / Português (BR) / Русский / Українська; switch with `/languages` or `pi --locale <code>`. LLM-facing copy (tool description, schemas, errors) stays English by design.
20
+ Restart your Pi session.
26
21
 
27
- ## Screens
22
+ ## Quick start
28
23
 
29
- | | |
30
- |---|---|
31
- | ![Single-question dialog](https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-ask-user-question/docs/single-question.jpg) | ![Multi-tab + ASCII preview](https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-ask-user-question/docs/multi-tab-preview.jpg) |
32
- | ![Multi-select with checkboxes](https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-ask-user-question/docs/multi-select.jpg) | ![Submit tab review](https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-ask-user-question/docs/submit-tab.jpg) |
33
- | ![Localized UI - German](https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-ask-user-question/docs/localized-german-ui.jpg) | |
24
+ Nothing to set up — the tool is live as soon as Pi restarts. Hand the model a task with a real decision buried in it:
34
25
 
35
- ## Install
26
+ > Add caching to the API client.
36
27
 
37
- ```bash
38
- pi install npm:@juicesharp/rpiv-ask-user-question
39
- ```
28
+ Rather than picking a strategy on your behalf, the model calls `ask_user_question` and a dialog takes over the bottom of your terminal. Move with `↑`/`↓`, choose with `Enter`, press `n` to attach a note, or land on the `Type something.` row to answer in your own words. While typing, `Shift+Enter` adds a line, `Ctrl+G` opens Pi's configured external editor, and `Ctrl+U` clears the draft; browsing another option and returning keeps what you wrote. `Esc` abandons the questionnaire entirely.
40
29
 
41
- Then restart your Pi session.
30
+ ![Single question in the dialog: the tab strip reads Feature Type, Design Tab, Testing, Release, Submit; the question Which real development task are we planning right now? sits above four numbered options — Bug fix (Recommended), New feature, Refactor, Perf tuning — each with a one-line description, followed by the appended Type something. row](https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-ask-user-question/docs/single-question.jpg)
42
31
 
43
- ### Optional: localization
32
+ When the model asks several things at once, `Tab` moves between them and a Submit tab reviews everything before it goes back:
44
33
 
45
- `rpiv-ask-user-question` works standalone - install only this package and you get the full English UI. Install `@juicesharp/rpiv-i18n` alongside it to flip sentinel labels, dialog hints, review-tab heading, and chat-summary lines to your active locale:
34
+ ![Submit tab of a four-question dialog: a Review your answers list showing Feature Type set to Bug fix and Testing set to Unit tests plus Integration tests, a warning naming Design Tab and Release as still unanswered, and a picker offering Submit answers or Cancel](https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-ask-user-question/docs/submit-tab.jpg)
46
35
 
47
- ```bash
48
- pi install npm:@juicesharp/rpiv-i18n
49
- ```
36
+ ## What you get
50
37
 
51
- With the SDK present, locale resolves from `--locale <code>` → `~/.config/rpiv-i18n/locale.json` → `LANG` / `LC_ALL` → English. The `/languages` interactive picker and `pi --locale <code>` startup flag are also enabled. Without the SDK, the dialog stays online and renders English at every call site - no warning, no crash. Users who installed via `pi install npm:@juicesharp/rpiv-pi` + `/rpiv-setup` get the SDK automatically.
52
-
53
- ## Tool
54
-
55
- - **`ask_user_question`** - present one or more structured questions, each with 2+ options, optional `multiSelect`, optional per-option `preview`, and a free-text "Other" fallback available on every single-select question (even with previews). Returns the user's selection(s) plus any notes. See the tool's `promptGuidelines` for usage policy.
56
-
57
- ### Schema
58
-
59
- ```ts
60
- ask_user_question({
61
- questions: [
62
- {
63
- question: string, // full question text, ends with "?"
64
- header: string, // chip label, max 16 chars
65
- options: [
66
- {
67
- label: string, // 1-5 words, max 60 chars
68
- description: string, // explains the choice / its trade-off
69
- preview?: string, // optional markdown shown next to options
70
- },
71
- // … 2-4 options total
72
- ],
73
- multiSelect?: boolean, // default false
74
- },
75
- // … 1-4 questions total
76
- ]
77
- })
78
- ```
38
+ - **Typed options instead of a wall of prose** — each question carries 2-4 authored choices, and every choice comes with a description of what it means or what it costs you.
39
+ - **You can always answer in your own words** — a `Type something.` row is appended to every question, single- or multi-select, widens to the full pane while you type, keeps its multiline draft visible in that row while you browse, and supports Pi's `Shift+Enter` newline and `Ctrl+G` external-editor flows.
40
+ - **Compare real artifacts, not just labels** — an option can carry a markdown `preview` (ASCII mockup, code, diagram, config) that renders in a bordered box beside the option list.
41
+ - **One interruption, not five** — up to four questions arrive in a single tabbed dialog, and the Submit tab lists your answers and names anything still blank before you commit.
42
+ - **Notes on any answer** — `n` opens a multiline note editor on any question tab; the note travels back to the model alongside the choice without marking the question answered.
43
+ - **Read the transcript behind the dialog** — `Ctrl+]` collapses the overlay so you can scroll the conversation, then brings it back with your answers intact.
44
+ - **Works outside the terminal too** — in RPC and ACP hosts such as the VS Code pendant or Zed the questionnaire walks through the host's native dialogs, and in non-interactive runs the tool is removed from the model's tool list instead of failing every call.
45
+
46
+ ## Configuration
47
+
48
+ Optional. Settings live in `~/.config/rpiv-ask-user-question/config.json`; the file is read, never written.
49
+
50
+ | Setting | What it does | Default |
51
+ | --- | --- | --- |
52
+ | `collapseKey` | Key that collapses and expands the dialog. Accepts Pi keybinding ids such as `alt+o`; `"off"` disables the shortcut. | `"ctrl+]"` |
53
+ | `guidance.promptSnippet` | One-line description of the tool in the system prompt — tune how eagerly the model asks. | built-in snippet |
54
+ | `guidance.promptGuidelines` | Usage guidelines given to the model, as a list of strings. | 4 built-in guidelines |
79
55
 
80
- Reserved option labels (rejected at validation): `"Other"`, plus the runtime sentinels (`"Type something."`, `"Chat about this"`, `"Next →"`).
81
-
82
- Returns:
83
-
84
- ```ts
85
- {
86
- content: [{ type: "text", text: string }], // human-readable envelope or DECLINE_MESSAGE
87
- details: {
88
- answers: Array<{
89
- questionIndex: number,
90
- question: string,
91
- kind: "option" | "custom" | "chat" | "multi",
92
- answer: string | null,
93
- selected?: string[], // present for multi-select
94
- notes?: string, // free-text note, when typed
95
- preview?: string, // echoed back when option carried a preview
96
- }>,
97
- cancelled: boolean,
98
- error?: "no_ui" | "no_questions" | "empty_options" | "too_many_questions"
99
- | "duplicate_question" | "duplicate_option_label" | "reserved_label",
100
- }
101
- }
56
+ ```json
57
+ { "collapseKey": "alt+o" }
102
58
  ```
103
59
 
104
- ## License
60
+ Malformed JSON falls back to the defaults with a warning; an individual unusable value is silently dropped back to its default. Never an error.
105
61
 
106
- [![npm version](https://img.shields.io/npm/v/@juicesharp/rpiv-ask-user-question.svg)](https://www.npmjs.com/package/@juicesharp/rpiv-ask-user-question)
107
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
62
+ ## Reference
63
+
64
+ - [Tool schema](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-ask-user-question/docs/tool-schema.md) — parameters, limits, reserved labels, validation errors, the result envelope, and the `rpiv:ask-user:prompt` event.
65
+ - [Keyboard and layout](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-ask-user-question/docs/keyboard.md) — every key, the rows the dialog appends, notes, collapse mode, and how previews and overflow adapt to terminal size.
66
+ - [Configuration](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-ask-user-question/docs/configuration.md) — file lookup and `XDG_CONFIG_HOME`, the `collapseKey` grammar, the `guidance.*` prompt overrides, and how invalid values are handled.
67
+ - [Hosts and runtime behavior](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-ask-user-question/docs/hosts.md) — terminal vs RPC vs non-interactive, what degrades in each, and the load-failure envelopes.
68
+ - [Localization](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-ask-user-question/docs/localization.md) — the nine shipped languages, how the locale is chosen, and how to add one.
69
+
70
+ ## Requirements
71
+
72
+ - Node.js 22 or newer.
73
+ - Pi Agent, with an interactive terminal or an RPC/ACP host. Non-interactive runs never see the tool.
74
+ - A terminal at least 100 columns wide for side-by-side previews; narrower terminals stack the preview under the options.
75
+
76
+ No native dependencies, no compiler, no API keys — the extension makes no model calls of its own.
77
+
78
+ ## Troubleshooting
79
+
80
+ **The model says the questionnaire UI failed to load and asks its questions as chat text.** The dialog's modules were replaced on disk while Pi was running, usually by a package-manager install touching the store. Repair the install if it is broken, then restart Pi; the failure is not recoverable inside the running process.
81
+
82
+ **`Ctrl+]` does nothing.** On keyboard layouts where `]` sits on the shifted layer (Latin American among them) the default is unreachable. Set `collapseKey` to something you can type, for example `"alt+o"`.
83
+
84
+ ## Related
85
+
86
+ - [`@juicesharp/rpiv-i18n`](https://www.npmjs.com/package/@juicesharp/rpiv-i18n) — optional; installing it renders the dialog chrome in your language and adds `/languages`.
87
+ - [`@juicesharp/rpiv-pi`](https://www.npmjs.com/package/@juicesharp/rpiv-pi) — the umbrella package whose workflow skills use `ask_user_question` as their developer checkpoint. `/rpiv-setup` offers to install this extension.
88
+
89
+ ## License
108
90
 
109
- MIT
91
+ MIT — see [LICENSE](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-ask-user-question/LICENSE).
@@ -1,11 +1,16 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { matchesKey } from "@earendil-works/pi-tui";
2
+ import { isKeyRelease, isKeyRepeat, matchesKey } from "@earendil-works/pi-tui";
3
3
  import { loadConfig, resolveCollapseKey, validateGuidanceFields } from "./config.js";
4
- import { ASK_USER_PROMPT_EVENT, type AskUserPromptEventPayload } from "./events.js";
4
+ import {
5
+ ASK_USER_BLOCKED_EVENT,
6
+ ASK_USER_PROMPT_EVENT,
7
+ type AskUserBlockedEventPayload,
8
+ type AskUserPromptEventPayload,
9
+ } from "./events.js";
5
10
  // Static import is fine — rpc-fallback pulls only types + the i18n bridge,
6
11
  // none of the ~560ms TUI render graph that QuestionnaireSession lazy-loads.
7
12
  import { hasDialogUI, runRpcQuestionnaire } from "./rpc-fallback.js";
8
- import { displayLabel } from "./state/i18n-bridge.js";
13
+ import { displayLabel, t } from "./state/i18n-bridge.js";
9
14
  import { sentinelsToAppend } from "./state/row-intent.js";
10
15
  import { buildQuestionnaireResponse, buildToolResult } from "./tool/response-envelope.js";
11
16
  import {
@@ -37,6 +42,11 @@ function emitAskUserPromptEvent(pi: ExtensionAPI, params: QuestionParams): void
37
42
  pi.events.emit(ASK_USER_PROMPT_EVENT, payload);
38
43
  }
39
44
 
45
+ function emitAskUserBlockedEvent(pi: ExtensionAPI, active: boolean): void {
46
+ const payload: AskUserBlockedEventPayload = { active };
47
+ pi.events.emit(ASK_USER_BLOCKED_EVENT, payload);
48
+ }
49
+
40
50
  /** Canonical tool name — single source of truth shared with the reconcile module. */
41
51
  export const ASK_USER_QUESTION_TOOL_NAME = "ask_user_question";
42
52
 
@@ -105,8 +115,8 @@ export function buildItemsForQuestion(question: QuestionData): WrappingSelectIte
105
115
  export const DEFAULT_PROMPT_SNIPPET = `Ask the user up to ${MAX_QUESTIONS} structured questions (${MIN_OPTIONS}-${MAX_OPTIONS} options each) when requirements are ambiguous`;
106
116
  export const DEFAULT_PROMPT_GUIDELINES: string[] = [
107
117
  `Use ask_user_question whenever the user's request is underspecified and you cannot proceed without concrete decisions — you can ask up to ${MAX_QUESTIONS} questions per invocation.`,
108
- `Each question MUST have ${MIN_OPTIONS}-${MAX_OPTIONS} options. Every option requires a concise label (1-5 words) and a description explaining what the choice means or its trade-offs. The user can additionally type a custom answer ("Type something." row is appended automatically to every question) or press Esc to abandon the questionnaire.`,
109
- `Set multiSelect: true when multiple answers are valid. Provide an options[].preview markdown string when an option benefits from richer side-by-side context (mockups, code snippets, diagrams, configs) — single-select only. The "Type something." row is appended to every single-select question regardless of whether any option carries a preview; in preview mode it expands to the full pane width while typing so the custom answer is not cramped into the narrow options column. If you recommend a specific option, make it the first option and append "(Recommended)" to its label.`,
118
+ `Each question MUST have ${MIN_OPTIONS}-${MAX_OPTIONS} options. Every option requires a concise label (1-5 words) and a description explaining what the choice means or its trade-offs. The user can additionally type a custom answer via the automatically appended "Type something." row on every question, or press Esc to abandon the questionnaire. Do NOT author "Other" or "Type something." labels yourself — reserved labels are rejected at runtime.`,
119
+ `Set multiSelect: true when multiple answers are valid. Provide an options[].preview markdown string when an option benefits from richer side-by-side context (mockups, code snippets, diagrams, configs) — single-select only. The "Type something." row is appended to every question; in preview mode it expands to the full pane width while typing so the custom answer is not cramped into the narrow options column. If you recommend a specific option, make that the first option and append "(Recommended)" to its label.`,
110
120
  "Do not stack multiple ask_user_question calls back-to-back — group all clarifying questions into one invocation.",
111
121
  ];
112
122
 
@@ -122,8 +132,8 @@ export function registerAskUserQuestionTool(pi: ExtensionAPI): void {
122
132
  4. Offer choices to the user about what direction to take
123
133
 
124
134
  Usage notes:
125
- - Users will always be able to type a custom answer ("Type something." row is appended automatically to every question) or press Esc to abandon the questionnaire. Do NOT author "Other" / "Type something." labels yourself — duplicates are rejected at runtime.
126
- - Use multiSelect: true to allow multiple answers to be selected for a question. It is always available on every question (even when options carry a \`preview\`), expanding to the full pane width while typing so the custom answer is not cramped into the narrow options column.
135
+ - Users can type a custom answer via the automatically appended "Type something." row on every question or press Esc to abandon the questionnaire. Do NOT author "Other" or "Type something." labels yourself — reserved labels are rejected at runtime.
136
+ - Use multiSelect: true when multiple answers are valid. The "Type something." row is available on every question, including when options carry a \`preview\`; in preview mode it expands to the full pane width while typing so the custom answer is not cramped into the narrow options column.
127
137
  - If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label.
128
138
 
129
139
  Preview feature:
@@ -161,7 +171,12 @@ Preview content is rendered as markdown in a monospace box. Multi-line text with
161
171
  // import entirely; RPC builds that predate ctx.mode are caught by the
162
172
  // custom()-resolved-undefined backstop below. See ./rpc-fallback.ts.
163
173
  if ((ctx as { mode?: string }).mode === "rpc" && hasDialogUI(ctx.ui)) {
164
- return buildQuestionnaireResponse(await runRpcQuestionnaire(ctx.ui, typed), typed);
174
+ emitAskUserBlockedEvent(pi, true);
175
+ try {
176
+ return buildQuestionnaireResponse(await runRpcQuestionnaire(ctx.ui, typed), typed);
177
+ } finally {
178
+ emitAskUserBlockedEvent(pi, false);
179
+ }
165
180
  }
166
181
 
167
182
  const itemsByTab: WrappingSelectItem[][] = typed.questions.map((q) => buildItemsForQuestion(q));
@@ -202,6 +217,10 @@ Preview content is rendered as markdown in a monospace box. Multi-line text with
202
217
  // toggling the questionnaire from underneath it.
203
218
  if (!handle.isHidden() && !handle.isFocused()) return undefined;
204
219
  if (!matchesKey(data, collapseKey as Parameters<typeof matchesKey>[1])) return undefined;
220
+ // Kitty-protocol terminals report press, repeat, and release separately.
221
+ // Toggle only on the initial press so a tap does not immediately reopen
222
+ // the overlay and a held key does not toggle it repeatedly.
223
+ if (isKeyRelease(data) || isKeyRepeat(data)) return { consume: true };
205
224
  sessionRef.current?.toggleCollapsedExternal();
206
225
  if (handle.isHidden() && !hasAnnouncedHide) {
207
226
  hasAnnouncedHide = true;
@@ -211,15 +230,34 @@ Preview content is rendered as markdown in a monospace box. Multi-line text with
211
230
  });
212
231
  }
213
232
 
233
+ emitAskUserBlockedEvent(pi, true);
214
234
  try {
215
235
  const result = await ctx.ui.custom<QuestionnaireResult>(
216
- (tui, theme, _kb, done) => {
236
+ (tui, theme, keybindings, done) => {
217
237
  const session = new QuestionnaireSession({
218
238
  tui,
219
239
  theme,
220
240
  params: typed,
221
241
  itemsByTab,
222
242
  done,
243
+ keybindings,
244
+ editInput: async (value) => {
245
+ try {
246
+ const [{ SettingsManager }, { editWithExternalEditor }] = await Promise.all([
247
+ import("@earendil-works/pi-coding-agent"),
248
+ import("./state/external-editor.js"),
249
+ ]);
250
+ const editorCommand = SettingsManager.create(ctx.cwd, undefined, {
251
+ projectTrusted: ctx.isProjectTrusted(),
252
+ }).getExternalEditorCommand();
253
+ if (!editorCommand) throw new Error("No external editor command is configured");
254
+ return await editWithExternalEditor(tui, editorCommand, value);
255
+ } catch (error) {
256
+ const message = error instanceof Error ? error.message : String(error);
257
+ ctx.ui.notify(`${t("editor.failed", "External editor failed")}: ${message}`, "error");
258
+ return undefined;
259
+ }
260
+ },
223
261
  collapseKey,
224
262
  });
225
263
  sessionRef.current = session;
@@ -256,6 +294,7 @@ Preview content is rendered as markdown in a monospace box. Multi-line text with
256
294
  return buildQuestionnaireResponse(result, typed);
257
295
  } finally {
258
296
  removeOverlayInputListener?.();
297
+ emitAskUserBlockedEvent(pi, false);
259
298
  }
260
299
  },
261
300
  });
@@ -0,0 +1,112 @@
1
+ # Configuration
2
+
3
+ Every setting the package reads, where the file lives, and what happens when a value is
4
+ wrong.
5
+
6
+ ## The config file
7
+
8
+ ```
9
+ ~/.config/rpiv-ask-user-question/config.json
10
+ ```
11
+
12
+ The file is optional — with no config at all, every setting takes its default. This
13
+ package only ever *reads* the file; it never creates, writes or chmods it, so its
14
+ permissions are whatever you give it.
15
+
16
+ A complete example:
17
+
18
+ ```json
19
+ {
20
+ "collapseKey": "alt+o",
21
+ "guidance": {
22
+ "promptSnippet": "Ask me before guessing on anything ambiguous",
23
+ "promptGuidelines": [
24
+ "Batch every clarifying question into one ask_user_question call.",
25
+ "Put your recommended option first and suffix it with (Recommended)."
26
+ ]
27
+ }
28
+ }
29
+ ```
30
+
31
+ ### Where the file is looked up
32
+
33
+ 1. `$XDG_CONFIG_HOME/rpiv-ask-user-question/config.json`, if `XDG_CONFIG_HOME` is set,
34
+ non-empty and absolute. A leading `~` is expanded first; a relative value is ignored.
35
+ Unset or ignored, the directory falls back to `~/.config`.
36
+ 2. If that file does not exist, the legacy path `~/.config/rpiv-ask-user-question/config.json`
37
+ is read. This path deliberately ignores `XDG_CONFIG_HOME`, so an existing config keeps
38
+ working after you set the variable.
39
+ 3. Neither present: all defaults.
40
+
41
+ If the XDG-path file exists, its result wins even when it is malformed — there is no
42
+ second chance at the legacy path.
43
+
44
+ ### When the file is invalid
45
+
46
+ Malformed JSON is not fatal. The loader warns on stderr and continues with defaults:
47
+
48
+ ```
49
+ rpiv-config: invalid JSON at <path>, using default ({}) — <parser message>
50
+ ```
51
+
52
+ Valid JSON that is not an object (a string, number, `null`, or an array) is rejected too,
53
+ falling back to defaults — but silently, with no warning. Individual keys with the wrong
54
+ type are likewise dropped back to their default without a warning.
55
+
56
+ ## Settings
57
+
58
+ | Setting | What it does | Default |
59
+ | --- | --- | --- |
60
+ | `collapseKey` | Key that collapses and expands the dialog overlay. | `"ctrl+]"` |
61
+ | `guidance.promptSnippet` | One-line snippet describing the tool in the system prompt. | built-in snippet |
62
+ | `guidance.promptGuidelines` | List of usage guidelines given to the model. | 4 built-in guidelines |
63
+
64
+ ### `collapseKey`
65
+
66
+ The value uses Pi's keybinding id format: zero or more distinct modifiers from `ctrl`,
67
+ `shift`, `alt`, `super`, joined by `+`, followed by a base key. Values are trimmed and
68
+ lowercased before matching.
69
+
70
+ The base key is either a single printable character from
71
+ `a-z 0-9 _ - ! @ # $ % ^ & * ( ) | ~ \` ' " : ; , . / < > ? [ ] { } = \`, or one of the
72
+ named keys `escape`, `esc`, `enter`, `return`, `tab`, `space`, `backspace`, `delete`,
73
+ `insert`, `clear`, `home`, `end`, `pageup`, `pagedown`, `up`, `down`, `left`, `right`,
74
+ `f1`–`f12`.
75
+
76
+ Examples that work: `"ctrl+]"`, `"alt+o"`, `"ctrl+shift+h"`, `"f9"`, `"ctrl+}"`.
77
+
78
+ Set `"off"` (any casing) to disable the collapse shortcut entirely — no raw terminal
79
+ listener is registered in that case.
80
+
81
+ A spec that does not match the grammar is rejected and the default is used. This is
82
+ strict on purpose: Pi's parser takes the last `+`-separated part as the key and ignores
83
+ unknown parts, so a typo like `"ctr+]"` would otherwise silently capture every bare `]`
84
+ keypress at the terminal level.
85
+
86
+ One known rough edge: the footer hint line inside the dialog always reads `Ctrl+] to
87
+ collapse` and does not interpolate a custom `collapseKey`. The one-shot notification you
88
+ get when the dialog first collapses *does* name your configured key.
89
+
90
+ ### `guidance.promptSnippet` and `guidance.promptGuidelines`
91
+
92
+ These replace the text Pi puts in the system prompt about when to reach for
93
+ `ask_user_question`. Use them to make the model ask more or less often, or to enforce a
94
+ house style for options.
95
+
96
+ `promptSnippet` is used only when it is a non-empty string. `promptGuidelines` is used
97
+ only when it is a non-empty array whose entries are all non-empty strings. Anything else
98
+ falls back to the built-in defaults. Both are read once, when the extension registers the
99
+ tool, so changes take effect on the next Pi restart.
100
+
101
+ ## Environment variables
102
+
103
+ | Variable | Effect |
104
+ | --- | --- |
105
+ | `XDG_CONFIG_HOME` | Relocates the config directory, as described above. Must be absolute. |
106
+
107
+ `LANG` and `LC_ALL` influence the dialog language, but they are read by
108
+ [`@juicesharp/rpiv-i18n`](https://www.npmjs.com/package/@juicesharp/rpiv-i18n) rather than
109
+ by this package — see [localization.md](./localization.md).
110
+
111
+ No other environment variables are read. The package makes no model calls, so it needs no
112
+ API keys or model settings of its own.
package/docs/hosts.md ADDED
@@ -0,0 +1,87 @@
1
+ # Hosts and runtime behavior
2
+
3
+ Where the questionnaire renders, what it degrades to, and what happens when it cannot
4
+ render at all.
5
+
6
+ ## Three environments
7
+
8
+ | Environment | What the model sees | What you see |
9
+ | --- | --- | --- |
10
+ | Interactive terminal | `ask_user_question` in its tool list | The full tabbed TUI overlay |
11
+ | RPC / ACP host (VS Code pendant, Zed, Paseo) | `ask_user_question` in its tool list | A sequence of the host's own native select and input dialogs |
12
+ | Non-interactive run (no UI) | Nothing — the tool is removed | Nothing |
13
+
14
+ ### Non-interactive runs
15
+
16
+ A `before_agent_start` hook reconciles the active tool set against `ctx.hasUI` before every
17
+ turn. When there is no UI, `ask_user_question` is stripped from the list so the model never
18
+ sees a tool it cannot use — better than offering it and auto-declining every call. When UI
19
+ comes back, the tool is restored. The reconciler is idempotent and leaves sibling tools
20
+ untouched.
21
+
22
+ A second guard lives inside the tool handler as a one-turn backstop: if a call somehow
23
+ arrives without UI, it returns `error: "no_ui"` and the text
24
+ `Error: UI not available (running in non-interactive mode)`.
25
+
26
+ ### RPC and ACP hosts
27
+
28
+ RPC hosts report `hasUI: true` because Pi's dialog sub-protocol works there, but custom
29
+ terminal UI does not render. The package detects this two ways: hosts that advertise
30
+ `ctx.mode === "rpc"` route straight to the dialog walker, skipping the TUI import
31
+ entirely, and older RPC builds are caught by a backstop when custom UI resolves without
32
+ rendering anything. Either path requires the host to expose both `select` and `input`.
33
+
34
+ The walker asks one question per dialog and returns exactly the same result envelope the
35
+ TUI produces. Trade-offs inherent to the native primitives:
36
+
37
+ - No side-by-side preview pane. Previews are folded into the dialog title instead,
38
+ truncated at 600 characters each.
39
+ - No tab bar and no Submit review tab — one dialog per question, in order.
40
+ - Multi-select is a free-text input: type the option numbers, comma-separated
41
+ (`1,3`). Any token that is not a valid option index is treated as a typed custom answer,
42
+ which is how the `Type something.` escape survives. An empty input commits an empty
43
+ selection, matching `Next` with nothing toggled.
44
+ - Dismissing any dialog cancels the whole questionnaire, mirroring `Esc` in the TUI.
45
+
46
+ If the host can render neither custom UI nor dialogs, the call returns
47
+ `error: "no_custom_ui"` with text telling the model the user never saw the questions and
48
+ that it should ask them as plain chat text instead — explicitly not a decline.
49
+
50
+ ## Conditional surfaces
51
+
52
+ Some parts of the dialog exist only under the right conditions:
53
+
54
+ | Surface | Appears when |
55
+ | --- | --- |
56
+ | Tab bar and Submit tab | The call carries more than one question |
57
+ | `Next` row | The question is multi-select |
58
+ | `Type something.` row | Always |
59
+ | Side-by-side preview | An option carries a `preview`, and terminal and pane are both ≥ 100 columns |
60
+ | Preview pane at all | Single-select questions only |
61
+ | Collapse shortcut | `collapseKey` is not `"off"` and the host exposes raw terminal input |
62
+ | Localized chrome | `@juicesharp/rpiv-i18n` is installed |
63
+
64
+ ## Loading and startup cost
65
+
66
+ The dialog's render graph costs roughly 560 ms to import, so it is loaded lazily — on the
67
+ first tool call, not when the extension registers. To keep that first call fast and safe,
68
+ the graph is also pre-warmed in the background two seconds after startup. The pre-warm
69
+ timer is unref'd, so it never holds a process open, and a failed pre-warm is swallowed:
70
+ the first real call re-imports and reports properly.
71
+
72
+ The pre-warm exists for a specific failure. Pi's module loader registers a module in its
73
+ graph cache *before* evaluating it and does not evict it if evaluation throws. If your
74
+ package manager replaces the dependency store while Pi is running, one failed import can
75
+ poison the cache for the rest of the process. Evaluating the graph early, while the paths
76
+ Pi resolved at boot still exist, keeps it in memory for the process lifetime and makes
77
+ that unreachable.
78
+
79
+ When it does happen, you get a structured envelope rather than a raw `TypeError`:
80
+
81
+ | `error` | Meaning | Fix |
82
+ | --- | --- | --- |
83
+ | `session_load_failed` | The dialog module could not be imported. | Repair the install if needed, then restart Pi. |
84
+ | `stale_module_cache` | The module cache went stale after an earlier failed import. | Restart Pi — this is unrecoverable in the running process. |
85
+
86
+ Both messages tell the model the questions were never shown and to ask them as plain chat
87
+ text instead of treating the failure as a decline.
@@ -0,0 +1,96 @@
1
+ # Keyboard and dialog layout
2
+
3
+ Every key the questionnaire dialog reacts to, the rows it appends for you, and how it
4
+ adapts to the size of your terminal.
5
+
6
+ ## Keys
7
+
8
+ | Key | What it does | Where it applies |
9
+ | --- | --- | --- |
10
+ | `↑` / `↓` | Move between rows. Wraps at both ends. | Option list, Submit picker |
11
+ | `Enter` | Confirm the focused option, commit typed text, close notes, or activate the focused Submit-picker row. | Everywhere |
12
+ | `Shift+Enter` | Insert a newline. | `Type something.` input, notes editor |
13
+ | `Esc` | Cancel the whole questionnaire. | Everywhere except the notes editor, where it closes notes |
14
+ | `Tab` / `Shift+Tab` | Next / previous tab, wrapping. `→` / `←` do the same. | Multi-question dialogs only |
15
+ | `Space` | Toggle the focused checkbox. | Multi-select questions |
16
+ | `n` | Open the notes editor for the current question. | Every question tab |
17
+ | `Ctrl+G` | Open Pi's configured external editor with the current custom-answer draft. | `Type something.` input |
18
+ | `Ctrl+U` | Clear the current custom-answer draft. | `Type something.` input |
19
+ | `Ctrl+]` | Collapse or expand the dialog. Configurable via `collapseKey`. | Everywhere, including while collapsed |
20
+
21
+ In a multi-select question, `Enter` on a regular row toggles its checkbox exactly like
22
+ `Space` — it does not submit. Committing the question means focusing the `Next` row and
23
+ pressing `Enter`. That is deliberate: it makes `Enter` a zero-cost way to flip boxes
24
+ without leaving the home row.
25
+
26
+ `Space` is suppressed on two rows: `Next` (it is a command, not a choice) and
27
+ `Type something.` (it is an inline text input, so the space character belongs to your
28
+ answer).
29
+
30
+ ## The rows the dialog adds
31
+
32
+ | Row | Label | Appended to |
33
+ | --- | --- | --- |
34
+ | Custom answer | `Type something.` | Every question — single-select and multi-select, with or without previews |
35
+ | Commit | `Next` | Multi-select questions only |
36
+
37
+ Focusing `Type something.` switches the row into an inline multiline editor. In preview
38
+ mode it expands to the full pane width while you type, so a long custom answer is not
39
+ squeezed into the narrow options column. `Shift+Enter` inserts a line break; vertical
40
+ arrows move between lines and return to row navigation at the draft's top and bottom.
41
+ The draft replaces the static row label while you browse other options and is isolated
42
+ per question. `Ctrl+G` round-trips it through Pi's configured external editor; `Ctrl+U`
43
+ clears it, while `Esc` remains the explicit way to cancel the questionnaire. Confirming
44
+ it produces an answer of `kind: "custom"`.
45
+
46
+ Both labels are reserved — the model cannot author an option that collides with them.
47
+ Both localize with the rest of the UI chrome; the reserved-label check always compares
48
+ against the canonical English strings.
49
+
50
+ ## Notes
51
+
52
+ `n` opens a notes editor on any question tab, whether the question is single- or
53
+ multi-select and whether or not its options carry previews. Notes are stored in a
54
+ side-band keyed by tab index, not inside the answer, so writing a note does not mark a
55
+ question as answered — the Submit tab still lists it as outstanding. The note merges into
56
+ the answer when you confirm it, and reaches the model as `user notes: <text>`.
57
+
58
+ Inside the editor, `Shift+Enter` inserts a newline, while `Esc` and `Enter` close it; other
59
+ keystrokes edit the buffer, so `n` types an `n`. Pasted line breaks are preserved.
60
+
61
+ ## Collapse mode
62
+
63
+ `Ctrl+]` gets the dialog out of the way: the overlay is marked hidden in Pi's overlay
64
+ stack and shrinks to a single dim hint row, so the transcript it was covering becomes
65
+ readable and chat scrolling resumes. Press the same key to bring the questionnaire back
66
+ with your answers intact. The first time you collapse, Pi notifies you with the key to
67
+ press — that message names your configured key.
68
+
69
+ Because Pi routes no input to a hidden overlay, the collapse key is additionally captured
70
+ at the raw terminal level. It only acts when the questionnaire is hidden or focused, so a
71
+ different overlay on top of it (for example `/btw`) keeps its keystrokes.
72
+
73
+ While collapsed, every keystroke other than cancel is ignored, so you cannot mutate
74
+ answers you cannot see.
75
+
76
+ The default `ctrl+]` is free in Terminal.app, iTerm2, Warp, tmux, zellij and screen. On
77
+ keyboard layouts where `]` sits on the shifted layer — Latin American `es-AR` / `es-MX`,
78
+ among others — set a different `collapseKey`, or `"off"` to disable the shortcut.
79
+
80
+ ## Layout
81
+
82
+ Options render in a vertical list. When any option in a single-select question carries a
83
+ `preview`, the dialog splits into a side-by-side layout with the option list on the left
84
+ and a bordered monospace preview box on the right — but only when both the terminal and
85
+ the dialog pane are at least 100 columns wide. Below that, the preview stacks underneath
86
+ the options instead.
87
+
88
+ When the dialog is taller than the terminal, the body scrolls between a sticky heading and
89
+ a sticky footer, and an overflow indicator shows which direction is clipped: `↑` for
90
+ content above, `↓` for content below, `↕` for both.
91
+
92
+ The footer hint line adapts to context — it drops the notes hint and appends the
93
+ `Shift+Enter` newline hint whenever a text editor has the keyboard, with `Ctrl+U` still at
94
+ the far right for custom answers. It adds the tab hint only in multi-question dialogs.
95
+ `Ctrl+G` remains Pi's global external-editor shortcut and is not repeated there. On narrow
96
+ terminals the right edge clips with `…` so the core hints survive.