@juicesharp/rpiv-ask-user-question 1.20.0 → 2.1.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.
Files changed (44) hide show
  1. package/README.md +68 -86
  2. package/ask-user-question.ts +193 -32
  3. package/config.ts +65 -4
  4. package/docs/configuration.md +112 -0
  5. package/docs/hosts.md +87 -0
  6. package/docs/keyboard.md +87 -0
  7. package/docs/localization.md +83 -0
  8. package/docs/tool-schema.md +121 -0
  9. package/events.ts +12 -0
  10. package/index.ts +6 -1
  11. package/locales/de.json +3 -3
  12. package/locales/en.json +3 -3
  13. package/locales/es.json +3 -3
  14. package/locales/fr.json +3 -3
  15. package/locales/pt-BR.json +3 -3
  16. package/locales/pt.json +3 -3
  17. package/locales/ru.json +3 -3
  18. package/locales/uk.json +3 -3
  19. package/locales/zh.json +3 -3
  20. package/package.json +11 -5
  21. package/reconcile.ts +47 -0
  22. package/rpc-fallback.ts +166 -0
  23. package/state/build-questionnaire.ts +0 -10
  24. package/state/key-router.ts +45 -62
  25. package/state/questionnaire-session.ts +41 -11
  26. package/state/row-intent.ts +21 -37
  27. package/state/selectors/derivations.ts +3 -54
  28. package/state/selectors/focus.ts +3 -5
  29. package/state/selectors/projections.ts +28 -13
  30. package/state/state-reducer.ts +31 -36
  31. package/state/state.ts +6 -3
  32. package/tool/format-answer.ts +6 -24
  33. package/tool/types.ts +13 -16
  34. package/view/components/inline-input.ts +96 -0
  35. package/view/components/multi-select-view.ts +62 -6
  36. package/view/components/option-list-view.ts +1 -4
  37. package/view/components/preview/preview-layout-decider.ts +4 -3
  38. package/view/components/preview/preview-pane.ts +22 -1
  39. package/view/components/wrapping-select.ts +19 -58
  40. package/view/dialog-builder.ts +13 -11
  41. package/view/props-adapter.ts +2 -2
  42. package/view/stateful-view.ts +6 -7
  43. package/view/tab-content-strategy.ts +16 -18
  44. package/view/components/chat-row-view.ts +0 -56
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.
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. `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 an optional free-text "Other" fallback. 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, and widens to the full pane while you type.
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 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,6 +1,15 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { loadConfig, validateGuidanceFields } from "./config.js";
3
- import { ASK_USER_PROMPT_EVENT, type AskUserPromptEventPayload } from "./events.js";
2
+ import { isKeyRelease, isKeyRepeat, matchesKey } from "@earendil-works/pi-tui";
3
+ import { loadConfig, resolveCollapseKey, validateGuidanceFields } from "./config.js";
4
+ import {
5
+ ASK_USER_BLOCKED_EVENT,
6
+ ASK_USER_PROMPT_EVENT,
7
+ type AskUserBlockedEventPayload,
8
+ type AskUserPromptEventPayload,
9
+ } from "./events.js";
10
+ // Static import is fine — rpc-fallback pulls only types + the i18n bridge,
11
+ // none of the ~560ms TUI render graph that QuestionnaireSession lazy-loads.
12
+ import { hasDialogUI, runRpcQuestionnaire } from "./rpc-fallback.js";
4
13
  import { displayLabel } from "./state/i18n-bridge.js";
5
14
  import { sentinelsToAppend } from "./state/row-intent.js";
6
15
  import { buildQuestionnaireResponse, buildToolResult } from "./tool/response-envelope.js";
@@ -9,6 +18,7 @@ import {
9
18
  MAX_QUESTIONS,
10
19
  MIN_OPTIONS,
11
20
  type QuestionData,
21
+ type QuestionnaireError,
12
22
  type QuestionnaireResult,
13
23
  type QuestionParams,
14
24
  QuestionParamsSchema,
@@ -32,16 +42,71 @@ function emitAskUserPromptEvent(pi: ExtensionAPI, params: QuestionParams): void
32
42
  pi.events.emit(ASK_USER_PROMPT_EVENT, payload);
33
43
  }
34
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
+
50
+ /** Canonical tool name — single source of truth shared with the reconcile module. */
51
+ export const ASK_USER_QUESTION_TOOL_NAME = "ask_user_question";
52
+
35
53
  const ERROR_NO_UI = "Error: UI not available (running in non-interactive mode)";
36
54
 
55
+ const ERROR_NO_CUSTOM_UI =
56
+ "Error: this client cannot render the questionnaire (custom UI is unavailable, e.g. RPC/ACP hosts such as Zed or Paseo). The user never saw the questions — do NOT treat this as a decline. Ask the questions as plain chat text instead, without using this tool.";
57
+
58
+ const ERROR_SESSION_LOAD_FAILED =
59
+ "Error: the questionnaire UI failed to load — the host's installed dependencies were likely replaced or removed on disk while Pi was running (e.g. a package-manager install touched the store). The user never saw the questions — do NOT treat this as a decline. Ask the questions as plain chat text instead, and tell the user that restoring this tool requires repairing the install if needed and restarting Pi.";
60
+
61
+ const ERROR_STALE_MODULE_CACHE =
62
+ "Error: the questionnaire UI cannot load — the host's module cache went stale after an earlier failed load (typically dependencies replaced on disk mid-session). This is unrecoverable within the current Pi process. The user never saw the questions — do NOT treat this as a decline. Ask the questions as plain chat text instead, and tell the user to restart Pi to restore this tool.";
63
+
64
+ /** Delay before the background session-graph pre-warm; mirrors rpiv-workflow's /wf prewarm. */
65
+ export const PREWARM_DELAY_MS = 2000;
66
+
67
+ type SessionModule = typeof import("./state/questionnaire-session.js");
68
+
69
+ type SessionLoad =
70
+ | { ok: true; module: SessionModule }
71
+ | { ok: false; error: Extract<QuestionnaireError, "session_load_failed" | "stale_module_cache">; message: string };
72
+
73
+ /**
74
+ * Lazy-load the ~560ms QuestionnaireSession view/TUI render graph, guarding
75
+ * the two failure shapes of issue #107. Pi's jiti loader registers a module in
76
+ * its graph cache BEFORE evaluating the body and does not evict it when
77
+ * evaluation throws (jiti 2.7.0), so one failed load — e.g. `pnpm install
78
+ * --force` replacing the store entry mid-session — leaves every later import
79
+ * of this specifier resolving to a namespace without the class. That state is
80
+ * unrecoverable in-process (cache-busting specifiers fail jiti resolution);
81
+ * both branches therefore return an LLM-facing envelope that names the restart
82
+ * requirement instead of leaking a bare "not a constructor" TypeError.
83
+ */
84
+ export async function loadQuestionnaireSession(): Promise<SessionLoad> {
85
+ let mod: SessionModule;
86
+ try {
87
+ mod = await import("./state/questionnaire-session.js");
88
+ } catch (e) {
89
+ const cause = e instanceof Error ? e.message : String(e);
90
+ return { ok: false, error: "session_load_failed", message: `${ERROR_SESSION_LOAD_FAILED} (cause: ${cause})` };
91
+ }
92
+ if (typeof mod.QuestionnaireSession !== "function") {
93
+ const keys = JSON.stringify(Object.keys(mod));
94
+ return {
95
+ ok: false,
96
+ error: "stale_module_cache",
97
+ message: `${ERROR_STALE_MODULE_CACHE} (resolved namespace keys: ${keys})`,
98
+ };
99
+ }
100
+ return { ok: true, module: mod };
101
+ }
102
+
37
103
  export function buildItemsForQuestion(question: QuestionData): WrappingSelectItem[] {
38
104
  const items: WrappingSelectItem[] = question.options.map((o) => ({
39
105
  kind: "option",
40
106
  label: o.label,
41
107
  description: o.description,
42
108
  }));
43
- const hasAnyPreview = question.options.some((o) => typeof o.preview === "string" && o.preview.length > 0);
44
- for (const kind of sentinelsToAppend(question, hasAnyPreview)) {
109
+ for (const kind of sentinelsToAppend(question)) {
45
110
  items.push({ kind, label: displayLabel(kind) });
46
111
  }
47
112
  return items;
@@ -50,15 +115,15 @@ export function buildItemsForQuestion(question: QuestionData): WrappingSelectIte
50
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`;
51
116
  export const DEFAULT_PROMPT_GUIDELINES: string[] = [
52
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.`,
53
- `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 single-select questions) or pick "Chat about this" to abandon the questionnaire.`,
54
- `Set multiSelect: true when multiple answers are valid; this suppresses the "Type something." row. Provide an options[].preview markdown string when an option benefits from richer side-by-side context (mockups, code snippets, diagrams, configs) — single-select only. NOTE: any non-empty preview on a single-select question ALSO suppresses the "Type something." row (no room in the side-by-side layout); "Chat about this" remains the escape hatch. 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.`,
55
120
  "Do not stack multiple ask_user_question calls back-to-back — group all clarifying questions into one invocation.",
56
121
  ];
57
122
 
58
123
  export function registerAskUserQuestionTool(pi: ExtensionAPI): void {
59
124
  const guidance = validateGuidanceFields(loadConfig().guidance);
60
125
  pi.registerTool({
61
- name: "ask_user_question",
126
+ name: ASK_USER_QUESTION_TOOL_NAME,
62
127
  label: "Ask User Question",
63
128
  description: `Ask the user one or more structured questions during execution. Use when you need to:
64
129
  1. Gather user preferences or requirements
@@ -67,8 +132,8 @@ export function registerAskUserQuestionTool(pi: ExtensionAPI): void {
67
132
  4. Offer choices to the user about what direction to take
68
133
 
69
134
  Usage notes:
70
- - Users will always be able to type a custom answer ("Type something." row is appended automatically to every single-select question) or pick "Chat about this" to abandon the questionnaire and continue in free-form conversation. Do NOT author "Other" / "Type something." / "Chat about this" labels yourself — duplicates are rejected at runtime.
71
- - Use multiSelect: true to allow multiple answers to be selected for a question. The "Type something." row is suppressed on multi-select questions, and is ALSO suppressed on single-select questions where any option carries a \`preview\` (the side-by-side layout has no room for inline custom text — "Chat about this" remains as the free-form escape hatch).
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.
72
137
  - If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label.
73
138
 
74
139
  Preview feature:
@@ -99,37 +164,133 @@ Preview content is rendered as markdown in a monospace box. Multi-line text with
99
164
  // Emit event for external listeners (e.g., notification plugins)
100
165
  emitAskUserPromptEvent(pi, typed);
101
166
 
167
+ // RPC hosts (VSCode pendant, ACP clients like Zed/Paseo — issue #78):
168
+ // ui.custom() cannot render there, but the select/input dialog
169
+ // sub-protocol works. Hosts that advertise ctx.mode (pi ≥0.79) route to
170
+ // the sequential dialog walker up front, skipping the TUI render-graph
171
+ // import entirely; RPC builds that predate ctx.mode are caught by the
172
+ // custom()-resolved-undefined backstop below. See ./rpc-fallback.ts.
173
+ if ((ctx as { mode?: string }).mode === "rpc" && hasDialogUI(ctx.ui)) {
174
+ emitAskUserBlockedEvent(pi, true);
175
+ try {
176
+ return buildQuestionnaireResponse(await runRpcQuestionnaire(ctx.ui, typed), typed);
177
+ } finally {
178
+ emitAskUserBlockedEvent(pi, false);
179
+ }
180
+ }
181
+
102
182
  const itemsByTab: WrappingSelectItem[][] = typed.questions.map((q) => buildItemsForQuestion(q));
103
183
 
104
184
  // Lazy — QuestionnaireSession pulls the ~560ms view/TUI render graph;
105
185
  // load it only when the tool runs, not at extension registration.
106
- const { QuestionnaireSession } = await import("./state/questionnaire-session.js");
107
-
108
- const result = await ctx.ui.custom<QuestionnaireResult>(
109
- (tui, theme, _kb, done) => {
110
- const session = new QuestionnaireSession({
111
- tui,
112
- theme,
113
- params: typed,
114
- itemsByTab,
115
- done,
116
- });
117
- return session.component;
118
- },
119
- {
120
- overlay: true,
121
- overlayOptions: {
122
- anchor: "bottom-center",
123
- width: "100%",
124
- maxHeight: "100%",
125
- margin: { left: 0, right: 0, bottom: 0 },
186
+ const sessionLoad = await loadQuestionnaireSession();
187
+ if (!sessionLoad.ok) {
188
+ return buildToolResult(sessionLoad.message, { answers: [], cancelled: true, error: sessionLoad.error });
189
+ }
190
+ const { QuestionnaireSession } = sessionLoad.module;
191
+ // Resolve the collapse/expand key spec from config. Default is `ctrl+]`; users
192
+ // with non-US layouts (e.g. Latin American, where `]` is shifted) can override
193
+ // via the `collapseKey` config field. `resolveCollapseKey` also accepts the
194
+ // sentinel value `"off"` to disable the shortcut entirely.
195
+ const collapseKey = resolveCollapseKey(loadConfig());
196
+
197
+ // Capture the overlay handle so the session can call `setHidden()` when the
198
+ // user toggles collapse, and register a raw terminal input listener for the
199
+ // same key so the toggle still works while the overlay is hidden (pi-tui does
200
+ // not route input to a hidden overlay's `component.handleInput`).
201
+ const sessionRef: {
202
+ current: import("./state/questionnaire-session.js").QuestionnaireSession | null;
203
+ } = { current: null };
204
+ const overlayHandleRef: { current: import("@earendil-works/pi-tui").OverlayHandle | undefined } = {
205
+ current: undefined,
206
+ };
207
+ let hasAnnouncedHide = false;
208
+ let removeOverlayInputListener: (() => void) | undefined;
209
+
210
+ if (collapseKey !== "off" && typeof ctx.ui.onTerminalInput === "function") {
211
+ removeOverlayInputListener = ctx.ui.onTerminalInput((data) => {
212
+ const handle = overlayHandleRef.current;
213
+ if (!handle) return undefined;
214
+ // Only act while the questionnaire is hidden (its handleInput is
215
+ // unreachable) or actually focused. When some other overlay is on
216
+ // top (e.g. `/btw`), leave the keystroke to that overlay instead of
217
+ // toggling the questionnaire from underneath it.
218
+ if (!handle.isHidden() && !handle.isFocused()) return undefined;
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 };
224
+ sessionRef.current?.toggleCollapsedExternal();
225
+ if (handle.isHidden() && !hasAnnouncedHide) {
226
+ hasAnnouncedHide = true;
227
+ ctx.ui.notify?.(`ask_user_question hidden — press ${collapseKey} to reopen`, "info");
228
+ }
229
+ return { consume: true };
230
+ });
231
+ }
232
+
233
+ emitAskUserBlockedEvent(pi, true);
234
+ try {
235
+ const result = await ctx.ui.custom<QuestionnaireResult>(
236
+ (tui, theme, _kb, done) => {
237
+ const session = new QuestionnaireSession({
238
+ tui,
239
+ theme,
240
+ params: typed,
241
+ itemsByTab,
242
+ done,
243
+ collapseKey,
244
+ });
245
+ sessionRef.current = session;
246
+ return session.component;
247
+ },
248
+ {
249
+ overlay: true,
250
+ overlayOptions: {
251
+ anchor: "bottom-center",
252
+ width: "100%",
253
+ maxHeight: "100%",
254
+ margin: { left: 0, right: 0, bottom: 0 },
255
+ },
256
+ onHandle: (handle) => {
257
+ overlayHandleRef.current = handle;
258
+ sessionRef.current?.setOverlayHandle(handle);
259
+ },
126
260
  },
127
- },
128
- );
261
+ );
129
262
 
130
- return buildQuestionnaireResponse(result, typed);
263
+ // A TUI questionnaire ALWAYS resolves a QuestionnaireResult (cancel
264
+ // included — state-reducer emits `{ answers, cancelled }`), so
265
+ // `undefined` uniquely means "host cannot render", never "user
266
+ // declined". RPC builds that predate ctx.mode land here: run the
267
+ // dialog walker when the host has the primitives; otherwise tell the
268
+ // model the user never saw the questions.
269
+ if (result === undefined) {
270
+ if (hasDialogUI(ctx.ui)) {
271
+ return buildQuestionnaireResponse(await runRpcQuestionnaire(ctx.ui, typed), typed);
272
+ }
273
+ return buildToolResult(ERROR_NO_CUSTOM_UI, { answers: [], cancelled: true, error: "no_custom_ui" });
274
+ }
275
+
276
+ return buildQuestionnaireResponse(result, typed);
277
+ } finally {
278
+ removeOverlayInputListener?.();
279
+ emitAskUserBlockedEvent(pi, false);
280
+ }
131
281
  },
132
282
  });
283
+
284
+ // Pre-warm the lazy session graph once startup settles (#107). A graph
285
+ // evaluated while the paths Pi resolved at boot still exist stays in memory
286
+ // for the process lifetime, so later on-disk dependency churn (e.g. `pnpm
287
+ // install --force` replacing the store mid-session) can no longer poison
288
+ // jiti's graph cache. Swallowed failure is safe: the first real call
289
+ // re-imports and surfaces it through loadQuestionnaireSession's structured
290
+ // envelope. unref keeps the timer from holding a non-TUI embedder's process
291
+ // open.
292
+ const timer = setTimeout(() => void loadQuestionnaireSession().catch(() => undefined), PREWARM_DELAY_MS);
293
+ timer.unref?.();
133
294
  }
134
295
 
135
296
  export { buildQuestionnaireResponse, buildToolResult };
package/config.ts CHANGED
@@ -1,14 +1,75 @@
1
1
  import type { GuidanceFields } from "@juicesharp/rpiv-config";
2
- import { configPath, loadJsonConfig, validateGuidanceFields } from "@juicesharp/rpiv-config";
2
+ import { loadJsonConfigWithLegacyFallback, validateGuidanceFields } from "@juicesharp/rpiv-config";
3
3
 
4
- const CONFIG_PATH = configPath("rpiv-ask-user-question");
4
+ /** Key spec for the overlay collapse/expand shortcut, e.g. `"ctrl+]"` or `"alt+o"`. */
5
+ export type CollapseKeySpec = string;
5
6
 
6
- interface AskUserQuestionConfig {
7
+ export const DEFAULT_COLLAPSE_KEY: CollapseKeySpec = "ctrl+]";
8
+ export const COLLAPSE_KEY_OFF: CollapseKeySpec = "off";
9
+
10
+ export interface AskUserQuestionConfig {
7
11
  guidance?: GuidanceFields;
12
+ /**
13
+ * Key spec for the collapse/expand shortcut, in the same format as pi-coding-agent
14
+ * keybinding ids (`modifier+key`, e.g. `ctrl+]`, `alt+o`, `ctrl+shift+h`). Defaults
15
+ * to `"ctrl+]"`. Set this to a key that is reachable on your keyboard layout — Latin
16
+ * American layouts (where `]` is on the shifted layer) often want `"ctrl+}"` instead.
17
+ * Pass `"off"` to disable the collapse shortcut entirely.
18
+ */
19
+ collapseKey?: CollapseKeySpec;
20
+ }
21
+
22
+ // Named keys accepted by pi-tui's `matchesKey` (keys.js switch on the parsed base key).
23
+ // parseKeyId lowercases the id before matching, so lowercase spellings are canonical.
24
+ const SPECIAL_KEYS = new Set([
25
+ "escape",
26
+ "esc",
27
+ "enter",
28
+ "return",
29
+ "tab",
30
+ "space",
31
+ "backspace",
32
+ "delete",
33
+ "insert",
34
+ "clear",
35
+ "home",
36
+ "end",
37
+ "pageup",
38
+ "pagedown",
39
+ "up",
40
+ "down",
41
+ "left",
42
+ "right",
43
+ ...Array.from({ length: 12 }, (_, i) => `f${i + 1}`),
44
+ ]);
45
+
46
+ const MODIFIERS = new Set(["ctrl", "shift", "alt", "super"]);
47
+
48
+ function isValidCollapseKeySpec(spec: string): boolean {
49
+ // Mirror pi-tui's KeyId grammar strictly: zero or more distinct modifiers, then a
50
+ // base key that is a single printable character or a named special key. A loose
51
+ // check is not enough — pi-tui's `parseKeyId` takes the LAST `+`-part as the key
52
+ // and ignores unknown parts, so a typo like `ctr+]` would silently match every
53
+ // bare `]` keypress (and the raw terminal listener would consume them globally).
54
+ if (!spec) return false;
55
+ if (spec.startsWith("+") || spec.endsWith("+") || spec.includes("++")) return false;
56
+ const parts = spec.split("+");
57
+ const base = parts[parts.length - 1] ?? "";
58
+ const modifiers = parts.slice(0, -1);
59
+ if (modifiers.length !== new Set(modifiers).size) return false;
60
+ if (!modifiers.every((m) => MODIFIERS.has(m))) return false;
61
+ return base.length === 1 ? /[a-z0-9_\-!@#$%^&*()|~`'":;,./<>?[\]{}=\\]/.test(base) : SPECIAL_KEYS.has(base);
62
+ }
63
+
64
+ export function resolveCollapseKey(config: Pick<AskUserQuestionConfig, "collapseKey">): CollapseKeySpec {
65
+ const raw = config.collapseKey?.trim().toLowerCase();
66
+ if (raw === undefined || raw === "") return DEFAULT_COLLAPSE_KEY;
67
+ if (raw === COLLAPSE_KEY_OFF) return COLLAPSE_KEY_OFF;
68
+ return isValidCollapseKeySpec(raw) ? raw : DEFAULT_COLLAPSE_KEY;
8
69
  }
9
70
 
10
71
  export function loadConfig(): AskUserQuestionConfig {
11
- return loadJsonConfig<AskUserQuestionConfig>(CONFIG_PATH);
72
+ return loadJsonConfigWithLegacyFallback<AskUserQuestionConfig>("rpiv-ask-user-question");
12
73
  }
13
74
 
14
75
  export { validateGuidanceFields };