@juicesharp/rpiv-ask-user-question 2.1.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
@@ -25,7 +25,7 @@ Nothing to set up — the tool is live as soon as Pi restarts. Hand the model a
25
25
 
26
26
  > Add caching to the API client.
27
27
 
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.
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.
29
29
 
30
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)
31
31
 
@@ -36,10 +36,10 @@ When the model asks several things at once, `Tab` moves between them and a Submi
36
36
  ## What you get
37
37
 
38
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.
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
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
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.
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
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
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
45
 
@@ -10,7 +10,7 @@ import {
10
10
  // Static import is fine — rpc-fallback pulls only types + the i18n bridge,
11
11
  // none of the ~560ms TUI render graph that QuestionnaireSession lazy-loads.
12
12
  import { hasDialogUI, runRpcQuestionnaire } from "./rpc-fallback.js";
13
- import { displayLabel } from "./state/i18n-bridge.js";
13
+ import { displayLabel, t } from "./state/i18n-bridge.js";
14
14
  import { sentinelsToAppend } from "./state/row-intent.js";
15
15
  import { buildQuestionnaireResponse, buildToolResult } from "./tool/response-envelope.js";
16
16
  import {
@@ -233,13 +233,31 @@ Preview content is rendered as markdown in a monospace box. Multi-line text with
233
233
  emitAskUserBlockedEvent(pi, true);
234
234
  try {
235
235
  const result = await ctx.ui.custom<QuestionnaireResult>(
236
- (tui, theme, _kb, done) => {
236
+ (tui, theme, keybindings, done) => {
237
237
  const session = new QuestionnaireSession({
238
238
  tui,
239
239
  theme,
240
240
  params: typed,
241
241
  itemsByTab,
242
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
+ },
243
261
  collapseKey,
244
262
  });
245
263
  sessionRef.current = session;
package/docs/keyboard.md CHANGED
@@ -8,11 +8,14 @@ adapts to the size of your terminal.
8
8
  | Key | What it does | Where it applies |
9
9
  | --- | --- | --- |
10
10
  | `↑` / `↓` | Move between rows. Wraps at both ends. | Option list, Submit picker |
11
- | `Enter` | Confirm the focused option, commit typed text, or activate the focused Submit-picker row. | Everywhere |
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 |
12
13
  | `Esc` | Cancel the whole questionnaire. | Everywhere except the notes editor, where it closes notes |
13
14
  | `Tab` / `Shift+Tab` | Next / previous tab, wrapping. `→` / `←` do the same. | Multi-question dialogs only |
14
15
  | `Space` | Toggle the focused checkbox. | Multi-select questions |
15
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 |
16
19
  | `Ctrl+]` | Collapse or expand the dialog. Configurable via `collapseKey`. | Everywhere, including while collapsed |
17
20
 
18
21
  In a multi-select question, `Enter` on a regular row toggles its checkbox exactly like
@@ -31,9 +34,14 @@ answer).
31
34
  | Custom answer | `Type something.` | Every question — single-select and multi-select, with or without previews |
32
35
  | Commit | `Next` | Multi-select questions only |
33
36
 
34
- Focusing `Type something.` switches the row into an inline text input. In preview mode it
35
- expands to the full pane width while you type, so a long custom answer is not squeezed
36
- into the narrow options column. Confirming it produces an answer of `kind: "custom"`.
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"`.
37
45
 
38
46
  Both labels are reserved — the model cannot author an option that collides with them.
39
47
  Both localize with the rest of the UI chrome; the reserved-label check always compares
@@ -47,8 +55,8 @@ side-band keyed by tab index, not inside the answer, so writing a note does not
47
55
  question as answered — the Submit tab still lists it as outstanding. The note merges into
48
56
  the answer when you confirm it, and reaches the model as `user notes: <text>`.
49
57
 
50
- Inside the editor, `Esc` and `Enter` both close it and every other keystroke goes to the
51
- text buffer, so `n` types an `n`.
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.
52
60
 
53
61
  ## Collapse mode
54
62
 
@@ -81,7 +89,8 @@ When the dialog is taller than the terminal, the body scrolls between a sticky h
81
89
  a sticky footer, and an overflow indicator shows which direction is clipped: `↑` for
82
90
  content above, `↓` for content below, `↕` for both.
83
91
 
84
- The footer hint line adapts to context — it drops the notes hint while the notes editor or
85
- the inline input has the keyboard, and adds the tab hint only in multi-question dialogs.
86
- On narrow terminals the collapse hint at the end of the line clips with `…` so the core
87
- hints survive.
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.
@@ -54,8 +54,8 @@ Nine locale files ship in `locales/`:
54
54
  Translation covers the chrome you read: the `Type something.` and `Next` sentinel rows,
55
55
  the footer hint segments (including the collapsed-state line), the Submit picker labels,
56
56
  the review-tab heading with its submit-readiness prompt and incomplete-answers warning, the
57
- preview pane's empty and notes-affordance lines, the notes header, and the two RPC dialog
58
- prompts. Twenty keys in total, all under the namespace
57
+ preview pane's empty and notes-affordance lines, the notes header, the external-editor
58
+ failure notification, and the two RPC dialog prompts. Twenty-three keys in total, all under the namespace
59
59
  `@juicesharp/rpiv-ask-user-question`.
60
60
 
61
61
  Everything the *model* reads stays English by design: the tool description, the parameter
package/locales/de.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n) are universal CLI conventions and stay untranslated.",
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n, Ctrl+G, Ctrl+U) are universal CLI conventions and stay untranslated.",
3
3
 
4
4
  "sentinel.other": "Schreibe etwas.",
5
5
  "sentinel.next": "Weiter",
@@ -9,6 +9,8 @@
9
9
 
10
10
  "hint.enter": "Enter zum Auswählen",
11
11
  "hint.navigate": "↑/↓ zur Navigation",
12
+ "hint.newline": "Umschalt+Enter für neue Zeile",
13
+ "hint.clear": "Ctrl+U zum Leeren",
12
14
  "hint.toggle": "Leertaste zum Umschalten",
13
15
  "hint.notes": "n für Notizen",
14
16
  "hint.tab": "Tab wechselt die Frage",
@@ -22,6 +24,8 @@
22
24
  "preview.notes_affordance": "Notizen: drücke n, um Notizen hinzuzufügen",
23
25
  "notes.header": "Notizen:",
24
26
 
27
+ "editor.failed": "Externer Editor fehlgeschlagen",
28
+
25
29
  "rpc.multi_instructions": "Gib die Nummern aller zutreffenden Optionen durch Komma getrennt ein (z. B. \"1,3\") oder tippe eine eigene Antwort als Text.",
26
30
  "rpc.custom_answer_title": "Gib deine Antwort ein:"
27
31
  }
package/locales/en.json CHANGED
@@ -7,6 +7,8 @@
7
7
 
8
8
  "hint.enter": "Enter to select",
9
9
  "hint.navigate": "↑/↓ to navigate",
10
+ "hint.newline": "Shift+Enter for newline",
11
+ "hint.clear": "Ctrl+U to clear",
10
12
  "hint.toggle": "Space to toggle",
11
13
  "hint.notes": "n to add notes",
12
14
  "hint.tab": "Tab to switch questions",
@@ -22,6 +24,8 @@
22
24
  "preview.notes_affordance": "Notes: press n to add notes",
23
25
  "notes.header": "Notes:",
24
26
 
27
+ "editor.failed": "External editor failed",
28
+
25
29
  "rpc.multi_instructions": "Enter the numbers of all that apply, comma-separated (e.g. \"1,3\"), or type a custom answer as plain text.",
26
30
  "rpc.custom_answer_title": "Type your answer:"
27
31
  }
package/locales/es.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n) are universal CLI conventions and stay untranslated.",
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n, Ctrl+G, Ctrl+U) are universal CLI conventions and stay untranslated.",
3
3
 
4
4
  "sentinel.other": "Escribe algo.",
5
5
  "sentinel.next": "Siguiente",
@@ -9,6 +9,8 @@
9
9
 
10
10
  "hint.enter": "Enter para seleccionar",
11
11
  "hint.navigate": "↑/↓ para navegar",
12
+ "hint.newline": "Mayús+Enter para nueva línea",
13
+ "hint.clear": "Ctrl+U para borrar",
12
14
  "hint.toggle": "Espacio para alternar",
13
15
  "hint.notes": "n para añadir notas",
14
16
  "hint.tab": "Tab para cambiar de pregunta",
@@ -22,6 +24,8 @@
22
24
  "preview.notes_affordance": "Notas: pulsa n para añadir notas",
23
25
  "notes.header": "Notas:",
24
26
 
27
+ "editor.failed": "Error del editor externo",
28
+
25
29
  "rpc.multi_instructions": "Introduce los números de todas las opciones que apliquen, separados por comas (p. ej. \"1,3\"), o escribe una respuesta propia como texto.",
26
30
  "rpc.custom_answer_title": "Escribe tu respuesta:"
27
31
  }
package/locales/fr.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n) are universal CLI conventions and stay untranslated.",
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n, Ctrl+G, Ctrl+U) are universal CLI conventions and stay untranslated.",
3
3
 
4
4
  "sentinel.other": "Écrivez quelque chose.",
5
5
  "sentinel.next": "Suivant",
@@ -9,6 +9,8 @@
9
9
 
10
10
  "hint.enter": "Entrée pour sélectionner",
11
11
  "hint.navigate": "↑/↓ pour naviguer",
12
+ "hint.newline": "Maj+Entrée pour une nouvelle ligne",
13
+ "hint.clear": "Ctrl+U pour effacer",
12
14
  "hint.toggle": "Espace pour basculer",
13
15
  "hint.notes": "n pour ajouter des notes",
14
16
  "hint.tab": "Tab pour changer de question",
@@ -22,6 +24,8 @@
22
24
  "preview.notes_affordance": "Notes : appuyez sur n pour ajouter des notes",
23
25
  "notes.header": "Notes :",
24
26
 
27
+ "editor.failed": "Échec de l’éditeur externe",
28
+
25
29
  "rpc.multi_instructions": "Saisissez les numéros de toutes les options applicables, séparés par des virgules (p. ex. « 1,3 »), ou tapez une réponse libre en texte.",
26
30
  "rpc.custom_answer_title": "Tapez votre réponse :"
27
31
  }
@@ -1,5 +1,5 @@
1
1
  {
2
- "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n) are universal CLI conventions and stay untranslated.",
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n, Ctrl+G, Ctrl+U) are universal CLI conventions and stay untranslated.",
3
3
 
4
4
  "sentinel.other": "Digite algo.",
5
5
  "sentinel.next": "Próximo",
@@ -9,6 +9,8 @@
9
9
 
10
10
  "hint.enter": "Enter para selecionar",
11
11
  "hint.navigate": "↑/↓ para navegar",
12
+ "hint.newline": "Shift+Enter para nova linha",
13
+ "hint.clear": "Ctrl+U para limpar",
12
14
  "hint.toggle": "Espaço para alternar",
13
15
  "hint.notes": "n para adicionar notas",
14
16
  "hint.tab": "Tab para trocar de pergunta",
@@ -22,6 +24,8 @@
22
24
  "preview.notes_affordance": "Notas: pressione n para adicionar notas",
23
25
  "notes.header": "Notas:",
24
26
 
27
+ "editor.failed": "Falha no editor externo",
28
+
25
29
  "rpc.multi_instructions": "Digite os números de todas as opções aplicáveis, separados por vírgula (ex.: \"1,3\") ou digite uma resposta própria em texto.",
26
30
  "rpc.custom_answer_title": "Digite sua resposta:"
27
31
  }
package/locales/pt.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "_meta.notes": "European Portuguese (Portugal). Auto-translated draft. Native-speaker review welcome via PR. Distinct from pt-BR (Brasil): differs in lexicon (utilizador / você), conjugation, and some terms. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n) are universal CLI conventions and stay untranslated.",
2
+ "_meta.notes": "European Portuguese (Portugal). Auto-translated draft. Native-speaker review welcome via PR. Distinct from pt-BR (Brasil): differs in lexicon (utilizador / você), conjugation, and some terms. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n, Ctrl+G, Ctrl+U) are universal CLI conventions and stay untranslated.",
3
3
 
4
4
  "sentinel.other": "Escreva algo.",
5
5
  "sentinel.next": "Seguinte",
@@ -9,6 +9,8 @@
9
9
 
10
10
  "hint.enter": "Enter para selecionar",
11
11
  "hint.navigate": "↑/↓ para navegar",
12
+ "hint.newline": "Shift+Enter para nova linha",
13
+ "hint.clear": "Ctrl+U para limpar",
12
14
  "hint.toggle": "Espaço para alternar",
13
15
  "hint.notes": "n para adicionar notas",
14
16
  "hint.tab": "Tab para mudar de pergunta",
@@ -22,6 +24,8 @@
22
24
  "preview.notes_affordance": "Notas: prima n para adicionar notas",
23
25
  "notes.header": "Notas:",
24
26
 
27
+ "editor.failed": "Falha no editor externo",
28
+
25
29
  "rpc.multi_instructions": "Introduza os números de todas as opções aplicáveis, separados por vírgulas (ex.: \"1,3\") ou escreva uma resposta própria em texto.",
26
30
  "rpc.custom_answer_title": "Escreva a sua resposta:"
27
31
  }
package/locales/ru.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n) are universal CLI conventions and stay untranslated.",
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n, Ctrl+G, Ctrl+U) are universal CLI conventions and stay untranslated.",
3
3
 
4
4
  "sentinel.other": "Введите что-нибудь.",
5
5
  "sentinel.next": "Далее",
@@ -9,6 +9,8 @@
9
9
 
10
10
  "hint.enter": "Enter — выбрать",
11
11
  "hint.navigate": "↑/↓ — навигация",
12
+ "hint.newline": "Shift+Enter — новая строка",
13
+ "hint.clear": "Ctrl+U — очистить",
12
14
  "hint.toggle": "Space — переключить",
13
15
  "hint.notes": "n — добавить заметки",
14
16
  "hint.tab": "Tab — следующий вопрос",
@@ -22,6 +24,8 @@
22
24
  "preview.notes_affordance": "Заметки: нажмите n, чтобы добавить заметки",
23
25
  "notes.header": "Заметки:",
24
26
 
27
+ "editor.failed": "Ошибка внешнего редактора",
28
+
25
29
  "rpc.multi_instructions": "Введите номера всех подходящих вариантов через запятую (например, \"1,3\") или введите свой ответ текстом.",
26
30
  "rpc.custom_answer_title": "Введите свой ответ:"
27
31
  }
package/locales/uk.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n) are universal CLI conventions and stay untranslated.",
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. TUI symbols (↑/↓, ⚠) and key names (Enter, Esc, Tab, Space, n, Ctrl+G, Ctrl+U) are universal CLI conventions and stay untranslated.",
3
3
 
4
4
  "sentinel.other": "Введіть щось.",
5
5
  "sentinel.next": "Далі",
@@ -9,6 +9,8 @@
9
9
 
10
10
  "hint.enter": "Enter — обрати",
11
11
  "hint.navigate": "↑/↓ — навігація",
12
+ "hint.newline": "Shift+Enter — новий рядок",
13
+ "hint.clear": "Ctrl+U — очистити",
12
14
  "hint.toggle": "Space — перемкнути",
13
15
  "hint.notes": "n — додати нотатки",
14
16
  "hint.tab": "Tab — наступне питання",
@@ -22,6 +24,8 @@
22
24
  "preview.notes_affordance": "Нотатки: натисніть n, щоб додати нотатки",
23
25
  "notes.header": "Нотатки:",
24
26
 
27
+ "editor.failed": "Помилка зовнішнього редактора",
28
+
25
29
  "rpc.multi_instructions": "Введіть номери всіх відповідних варіантів через кому (наприклад, \"1,3\") або введіть власну відповідь текстом.",
26
30
  "rpc.custom_answer_title": "Введіть свою відповідь:"
27
31
  }
package/locales/zh.json CHANGED
@@ -9,6 +9,8 @@
9
9
 
10
10
  "hint.enter": "回车选择",
11
11
  "hint.navigate": "↑/↓ 导航",
12
+ "hint.newline": "Shift+Enter 换行",
13
+ "hint.clear": "Ctrl+U 清空",
12
14
  "hint.toggle": "空格切换",
13
15
  "hint.notes": "按 n 添加备注",
14
16
  "hint.tab": "Tab 切换问题",
@@ -24,6 +26,8 @@
24
26
  "preview.notes_affordance": "备注:按 n 添加",
25
27
  "notes.header": "备注:",
26
28
 
29
+ "editor.failed": "外部编辑器启动失败",
30
+
27
31
  "rpc.multi_instructions": "输入所有适用选项的编号,用逗号分隔(例如 \"1,3\"),或直接输入自定义回答。",
28
32
  "rpc.custom_answer_title": "输入你的回答:"
29
33
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-ask-user-question",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Pi extension. A structured questionnaire the model can put to you when it would otherwise guess, with typed options instead of free-form replies.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -44,6 +44,7 @@
44
44
  "!docs/*.svg",
45
45
  "README.md",
46
46
  "state/build-questionnaire.ts",
47
+ "state/external-editor.ts",
47
48
  "state/i18n-bridge.ts",
48
49
  "state/key-router.ts",
49
50
  "state/questionnaire-session.ts",
@@ -92,7 +93,7 @@
92
93
  }
93
94
  },
94
95
  "dependencies": {
95
- "@juicesharp/rpiv-config": "^2.1.0",
96
+ "@juicesharp/rpiv-config": "^2.2.0",
96
97
  "typebox": "^1.1.24"
97
98
  }
98
99
  }
@@ -1,5 +1,5 @@
1
1
  import { getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
2
- import { Input } from "@earendil-works/pi-tui";
2
+ import { Editor, type EditorTheme, type TUI } from "@earendil-works/pi-tui";
3
3
  import type { QuestionData } from "../tool/types.js";
4
4
  import {
5
5
  type BoundGlobalBinding,
@@ -33,7 +33,7 @@ import {
33
33
  import type { QuestionnaireState } from "./state.js";
34
34
 
35
35
  export interface QuestionnaireBuildConfig {
36
- tui: { terminal: { columns: number; rows: number }; requestRender(): void };
36
+ tui: TUI;
37
37
  theme: Theme;
38
38
  questions: readonly QuestionData[];
39
39
  itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>;
@@ -44,8 +44,8 @@ export interface QuestionnaireBuildConfig {
44
44
 
45
45
  export interface QuestionnaireBuilt {
46
46
  adapter: QuestionnairePropsAdapter;
47
- notesInput: Input;
48
- inlineInput: Input;
47
+ notesInput: Editor;
48
+ inlineInput: Editor;
49
49
  render: (width: number) => string[];
50
50
  invalidate: () => void;
51
51
  }
@@ -56,10 +56,23 @@ interface HeightComputers {
56
56
  }
57
57
 
58
58
  function previewBodyHeights(pane: PreviewPane): (width: number) => TabBodyHeights {
59
- return (width) => ({
60
- current: pane.naturalHeight(width),
61
- max: pane.maxNaturalHeight(width),
62
- });
59
+ return (width) => {
60
+ const current = pane.naturalHeight(width);
61
+ return { current, max: Math.max(current, pane.maxNaturalHeight(width)) };
62
+ };
63
+ }
64
+
65
+ function editorTheme(theme: Theme): EditorTheme {
66
+ return {
67
+ borderColor: (text) => theme.fg("borderMuted", text),
68
+ selectList: {
69
+ selectedPrefix: (text) => theme.bg("selectedBg", theme.fg("accent", text)),
70
+ selectedText: (text) => theme.bg("selectedBg", theme.bold(text)),
71
+ description: (text) => theme.fg("muted", text),
72
+ scrollInfo: (text) => theme.fg("dim", text),
73
+ noMatch: (text) => theme.fg("warning", text),
74
+ },
75
+ };
63
76
  }
64
77
 
65
78
  function multiSelectBodyHeights(view: MultiSelectView): (width: number) => TabBodyHeights {
@@ -74,8 +87,8 @@ const isActiveTab: PerTabSelector<boolean> = (s, ctx) =>
74
87
 
75
88
  /**
76
89
  * Pure factory: assembles every TUI component, the props adapter, and a
77
- * lifecycle handle. Session-state dependencies arrive via `getCurrentTab` and
78
- * the `inputBuffer` cell. Initial paint is delegated to
90
+ * lifecycle handle. Session-state dependencies arrive via `getCurrentTab`; live
91
+ * custom text stays in the headless Editor. Initial paint is delegated to
79
92
  * `adapter.apply(initialState)` (called by the session at construction-end);
80
93
  * no selector is invoked here.
81
94
  */
@@ -99,8 +112,8 @@ class QuestionnaireBuilder {
99
112
 
100
113
  private readonly selectTheme: WrappingSelectTheme;
101
114
  private readonly markdownTheme = getMarkdownTheme();
102
- private readonly notesInput = new Input();
103
- private readonly inlineInput = new Input();
115
+ private readonly notesInput: Editor;
116
+ private readonly inlineInput: Editor;
104
117
  private readonly getTerminalWidth = () => this.tui.terminal.columns;
105
118
  private readonly getTerminalRows = () => this.tui.terminal.rows;
106
119
 
@@ -114,6 +127,9 @@ class QuestionnaireBuilder {
114
127
  this.getCurrentTab = config.getCurrentTab;
115
128
 
116
129
  this.selectTheme = this.makeSelectTheme();
130
+ const textEditorTheme = editorTheme(this.theme);
131
+ this.notesInput = new Editor(this.tui, textEditorTheme);
132
+ this.inlineInput = new Editor(this.tui, textEditorTheme);
117
133
  }
118
134
 
119
135
  build(): QuestionnaireBuilt {
@@ -0,0 +1,62 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ export interface ExternalEditorTui {
7
+ stop(): void;
8
+ start(): void;
9
+ requestRender(force?: boolean): void;
10
+ }
11
+
12
+ function runEditor(command: string, file: string): Promise<void> {
13
+ // Keep the command grammar identical to Pi's built-in external-editor flow. A
14
+ // separate shell or argv parser here would make Ctrl+G behave differently.
15
+ const [editor, ...args] = command.split(" ");
16
+ if (!editor) return Promise.reject(new Error("External editor command is empty"));
17
+
18
+ return new Promise((resolve, reject) => {
19
+ const child = spawn(editor, [...args, file], {
20
+ stdio: "inherit",
21
+ shell: process.platform === "win32",
22
+ });
23
+ child.once("error", reject);
24
+ child.once("close", (code, signal) => {
25
+ if (code === 0) {
26
+ resolve();
27
+ return;
28
+ }
29
+ const reason = signal ? `signal ${signal}` : `exit code ${code ?? "unknown"}`;
30
+ reject(new Error(`External editor exited with ${reason}`));
31
+ });
32
+ });
33
+ }
34
+
35
+ /**
36
+ * Edit a custom answer with Pi's configured external-editor command. The TUI lifecycle
37
+ * and one-trailing-newline normalization intentionally match Pi's main editor flow.
38
+ */
39
+ export async function editWithExternalEditor(tui: ExternalEditorTui, command: string, value: string): Promise<string> {
40
+ const tempDir = mkdtempSync(join(tmpdir(), "rpiv-ask-user-question-"));
41
+ const tempFile = join(tempDir, "answer.md");
42
+ let tuiStopped = false;
43
+
44
+ try {
45
+ writeFileSync(tempFile, value, "utf8");
46
+ tui.stop();
47
+ tuiStopped = true;
48
+ process.stdout.write(`Launching external editor: ${command}\nPi will resume when the editor exits.\n`);
49
+ await runEditor(command, tempFile);
50
+ return readFileSync(tempFile, "utf8").replace(/\r?\n$/, "");
51
+ } finally {
52
+ try {
53
+ rmSync(tempDir, { recursive: true, force: true });
54
+ } catch {
55
+ // Temp cleanup is best effort; never leave the TUI stopped because it failed.
56
+ }
57
+ if (tuiStopped) {
58
+ tui.start();
59
+ tui.requestRender(true);
60
+ }
61
+ }
62
+ }
@@ -7,12 +7,20 @@ const KEYBIND_UP = "tui.select.up";
7
7
  const KEYBIND_DOWN = "tui.select.down";
8
8
  const KEYBIND_CONFIRM = "tui.select.confirm";
9
9
  const KEYBIND_CANCEL = "tui.select.cancel";
10
+ const KEYBIND_NEW_LINE = "tui.input.newLine";
11
+ const KEYBIND_EDITOR_UP = "tui.editor.cursorUp";
12
+ const KEYBIND_EDITOR_DOWN = "tui.editor.cursorDown";
13
+ const KEYBIND_CLEAR = "tui.editor.deleteToLineStart";
14
+ const KEYBIND_EXTERNAL_EDITOR = "app.editor.external";
10
15
 
11
16
  const NOTES_ACTIVATE_KEY = "n";
12
17
  const SPACE_KEY = " ";
13
18
 
14
19
  export type QuestionnaireAction =
15
- | { kind: "nav"; nextIndex: number }
20
+ | { kind: "nav"; nextIndex: number; inputValue: string }
21
+ | { kind: "input_clear" }
22
+ | { kind: "input_edit"; value: string }
23
+ | { kind: "input_replace"; value: string }
16
24
  | { kind: "tab_switch"; nextTab: number }
17
25
  | { kind: "confirm"; answer: QuestionAnswer; autoAdvanceTab?: number }
18
26
  | { kind: "toggle"; index: number }
@@ -115,12 +123,20 @@ function tabSwitchAction(
115
123
 
116
124
  // DOWN at the last item wraps to the first (cycle through [option0, …, optionLast]).
117
125
  function nextNavOnDown(state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
118
- return { kind: "nav", nextIndex: wrapTab(state.optionIndex + 1, Math.max(1, runtime.items.length)) };
126
+ return {
127
+ kind: "nav",
128
+ nextIndex: wrapTab(state.optionIndex + 1, Math.max(1, runtime.items.length)),
129
+ inputValue: runtime.inputBuffer,
130
+ };
119
131
  }
120
132
 
121
133
  // UP at the first item wraps to the last (symmetric with nextNavOnDown).
122
134
  function prevNavOnUp(state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
123
- return { kind: "nav", nextIndex: wrapTab(state.optionIndex - 1, Math.max(1, runtime.items.length)) };
135
+ return {
136
+ kind: "nav",
137
+ nextIndex: wrapTab(state.optionIndex - 1, Math.max(1, runtime.items.length)),
138
+ inputValue: runtime.inputBuffer,
139
+ };
124
140
  }
125
141
 
126
142
  export function routeKey(data: string, state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
@@ -166,23 +182,31 @@ export function routeKey(data: string, state: QuestionnaireState, runtime: Quest
166
182
 
167
183
  if (state.notesVisible) {
168
184
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "notes_exit" };
185
+ if (kb.matches(data, KEYBIND_NEW_LINE)) return { kind: "notes_forward", data };
169
186
  if (kb.matches(data, KEYBIND_CONFIRM)) return { kind: "notes_exit" };
170
187
  return { kind: "notes_forward", data };
171
188
  }
172
189
 
173
190
  if (state.inputMode) {
191
+ // Newline takes precedence over confirmation if a user configuration binds
192
+ // the same physical key to both semantic actions.
193
+ if (kb.matches(data, KEYBIND_NEW_LINE)) return { kind: "ignore" };
174
194
  if (kb.matches(data, KEYBIND_CONFIRM)) {
175
195
  const answer = buildSingleSelectAnswer(state, runtime);
176
196
  if (!answer) return { kind: "ignore" };
177
197
  return { kind: "confirm", answer, autoAdvanceTab: computeAutoAdvanceTab(state, runtime) };
178
198
  }
199
+ // Treat Pi's Ctrl+U line-kill binding as an explicit whole-draft clear,
200
+ // independent of the current cursor position.
201
+ if (kb.matches(data, KEYBIND_CLEAR)) return { kind: "input_clear" };
202
+ if (kb.matches(data, KEYBIND_EXTERNAL_EDITOR)) return { kind: "input_edit", value: runtime.inputBuffer };
179
203
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "cancel" };
180
- if (kb.matches(data, KEYBIND_UP)) {
181
- return prevNavOnUp(state, runtime);
182
- }
183
- if (kb.matches(data, KEYBIND_DOWN)) {
184
- return nextNavOnDown(state, runtime);
204
+ if (kb.matches(data, KEYBIND_EDITOR_UP) && runtime.canMoveInputUp) return { kind: "ignore" };
205
+ if (kb.matches(data, KEYBIND_EDITOR_DOWN) && runtime.canMoveInputDown) {
206
+ return { kind: "ignore" };
185
207
  }
208
+ if (kb.matches(data, KEYBIND_UP)) return prevNavOnUp(state, runtime);
209
+ if (kb.matches(data, KEYBIND_DOWN)) return nextNavOnDown(state, runtime);
186
210
  return { kind: "ignore" };
187
211
  }
188
212