@dreb/coding-agent 2.51.0 → 2.52.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 (38) hide show
  1. package/README.md +7 -5
  2. package/dist/cli/args.d.ts.map +1 -1
  3. package/dist/cli/args.js +11 -6
  4. package/dist/cli/args.js.map +1 -1
  5. package/dist/core/extensions/types.d.ts +31 -11
  6. package/dist/core/extensions/types.d.ts.map +1 -1
  7. package/dist/core/extensions/types.js.map +1 -1
  8. package/dist/core/tools/ask-user.d.ts +28 -20
  9. package/dist/core/tools/ask-user.d.ts.map +1 -1
  10. package/dist/core/tools/ask-user.js +130 -106
  11. package/dist/core/tools/ask-user.js.map +1 -1
  12. package/dist/core/tools/index.d.ts +9 -7
  13. package/dist/core/tools/index.d.ts.map +1 -1
  14. package/dist/core/tools/index.js.map +1 -1
  15. package/dist/modes/interactive/components/ask-wizard.d.ts +83 -0
  16. package/dist/modes/interactive/components/ask-wizard.d.ts.map +1 -0
  17. package/dist/modes/interactive/components/ask-wizard.js +464 -0
  18. package/dist/modes/interactive/components/ask-wizard.js.map +1 -0
  19. package/dist/modes/interactive/interactive-mode.d.ts +4 -2
  20. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  21. package/dist/modes/interactive/interactive-mode.js +7 -5
  22. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  23. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  24. package/dist/modes/rpc/rpc-mode.js +100 -20
  25. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  26. package/dist/modes/rpc/rpc-types.d.ts +18 -7
  27. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  28. package/dist/modes/rpc/rpc-types.js.map +1 -1
  29. package/docs/dashboard.md +1 -1
  30. package/docs/extensions.md +35 -18
  31. package/docs/rpc.md +26 -8
  32. package/examples/extensions/rpc-demo.ts +29 -0
  33. package/examples/rpc-extension-ui.ts +162 -6
  34. package/package.json +1 -1
  35. package/dist/modes/interactive/components/ask-user.d.ts +0 -59
  36. package/dist/modes/interactive/components/ask-user.d.ts.map +0 -1
  37. package/dist/modes/interactive/components/ask-user.js +0 -240
  38. package/dist/modes/interactive/components/ask-user.js.map +0 -1
package/docs/rpc.md CHANGED
@@ -2015,7 +2015,7 @@ Expected response: `extension_ui_response` with `value` (the edited text) or `ca
2015
2015
 
2016
2016
  #### ask
2017
2017
 
2018
- Ask the user a rich clarifying question with Markdown-formatted question text, optional single- or multi-select options, and an optional free-text field. This powers the built-in `ask_user` tool. `options` (2-4 nonblank strings) is optional; `allowFreeText` (default `true`), `multiSelect`, and `multiline` are optional booleans.
2018
+ Ask the user one or more rich clarifying questions together as a single wizard. Each question has Markdown-formatted question text, optional single- or multi-select options, and an optional free-text field. This powers the built-in `ask_user` tool. The request carries a `questions` array (1-10 entries); per question, `options` (2-4 nonblank strings) is optional and `allowFreeText` (default `true`), `multiSelect`, and `multiline` are optional booleans. An overall `title` defaults to `"Question"`.
2019
2019
 
2020
2020
  ```json
2021
2021
  {
@@ -2023,11 +2023,20 @@ Ask the user a rich clarifying question with Markdown-formatted question text, o
2023
2023
  "id": "uuid-5",
2024
2024
  "method": "ask",
2025
2025
  "title": "Choose a database",
2026
- "question": "Which persistence strategy should I use?",
2027
- "options": ["SQLite", "PostgreSQL", "Keep the JSON file"],
2028
- "allowFreeText": true,
2029
- "multiSelect": false,
2030
- "multiline": false,
2026
+ "questions": [
2027
+ {
2028
+ "question": "Which persistence strategy should I use?",
2029
+ "title": "Storage",
2030
+ "options": ["SQLite", "PostgreSQL", "Keep the JSON file"],
2031
+ "allowFreeText": true,
2032
+ "multiSelect": false,
2033
+ "multiline": false
2034
+ },
2035
+ {
2036
+ "question": "Any migration constraints I should know about?",
2037
+ "multiline": true
2038
+ }
2039
+ ],
2031
2040
  "timeout": 60000,
2032
2041
  "expiresAt": 1785434460000
2033
2042
  }
@@ -2035,12 +2044,21 @@ Ask the user a rich clarifying question with Markdown-formatted question text, o
2035
2044
 
2036
2045
  `timeout` is the original duration in milliseconds. `expiresAt` is the corresponding absolute Unix timestamp in milliseconds; Dashboard clients should use it for the visible countdown so reload, resync, or drill-in recovery does not restart the full duration.
2037
2046
 
2038
- Expected response: `extension_ui_response` with `selected` (an array of strings) and optional string `customText` (the typed answer). Sending `cancelled: true`, or an empty `selected` with no nonblank `customText`, stops the current agent turn rather than continuing without an answer. A timeout has the same stop semantics. Other malformed ask responses are rejected as protocol failures.
2047
+ Expected response: `extension_ui_response` with `answers` — an array with one entry per question, in the same order. Each answer has `selected` (an array of strings) and optional string `customText` (the typed answer); an answer with an empty `selected` and no nonblank `customText` is treated as skipped (an explicit `skipped: true` is also honored). Answering submits the batch even when some questions are skipped. Sending `cancelled: true` stops the current agent turn rather than continuing; a timeout has the same stop semantics. A missing/non-array `answers`, or a malformed `selected`/`customText`, is rejected as a protocol failure.
2039
2048
 
2040
2049
  ```json
2041
- { "type": "extension_ui_response", "id": "uuid-5", "selected": ["SQLite"], "customText": "with WAL enabled" }
2050
+ {
2051
+ "type": "extension_ui_response",
2052
+ "id": "uuid-5",
2053
+ "answers": [
2054
+ { "selected": ["SQLite"], "customText": "with WAL enabled" },
2055
+ { "selected": [], "skipped": true }
2056
+ ]
2057
+ }
2042
2058
  ```
2043
2059
 
2060
+ `ask` requests are single-flight per RPC runtime. If parallel tool execution starts several calls concurrently, RPC emits only the first request and queues the rest in FIFO order. The next request is emitted only after the active request settles; a queued call that is aborted before it starts settles without emitting. Hosts therefore need to render at most one pending `ask` wizard at a time.
2061
+
2044
2062
  #### notify
2045
2063
 
2046
2064
  Display a notification. Fire-and-forget, no response expected.
@@ -10,6 +10,7 @@
10
10
  * - confirm() - on session_before_switch
11
11
  * - input() - via /rpc-input command
12
12
  * - editor() - via /rpc-editor command
13
+ * - ask() - via /rpc-ask command
13
14
  * - notify() - after each dialog completes
14
15
  * - setStatus() - on turn_start/turn_end
15
16
  * - setWidget() - on session_start
@@ -112,6 +113,34 @@ export default function (dreb: ExtensionAPI) {
112
113
  },
113
114
  });
114
115
 
116
+ // -- batch ask wizard via command --
117
+
118
+ dreb.registerCommand("rpc-ask", {
119
+ description: "Open a batch question wizard (demonstrates ctx.ui.ask in RPC)",
120
+ handler: async (_args, ctx) => {
121
+ const result = await ctx.ui.ask({
122
+ title: "Configure the RPC demo",
123
+ questions: [
124
+ {
125
+ question: "Which **transport checks** should run?",
126
+ title: "Checks",
127
+ options: ["Protocol", "Reconnect", "Timeout"],
128
+ multiSelect: true,
129
+ allowFreeText: true,
130
+ },
131
+ {
132
+ question: "Anything else the RPC host should display?",
133
+ title: "Notes",
134
+ multiline: true,
135
+ },
136
+ ],
137
+ });
138
+ if (!result) return;
139
+ const answered = result.answers.filter((answer) => !answer.skipped).length;
140
+ ctx.ui.notify(`Submitted ${answered} of ${result.answers.length} answers`, "info");
141
+ },
142
+ });
143
+
115
144
  // -- setEditorText via command --
116
145
 
117
146
  dreb.registerCommand("rpc-prefill", {
@@ -3,15 +3,16 @@
3
3
  *
4
4
  * A lightweight TUI chat client that spawns the agent in RPC mode.
5
5
  * Demonstrates how to build a custom UI on top of the RPC protocol,
6
- * including handling extension UI requests (select, confirm, input, editor).
6
+ * including handling extension UI requests (select, confirm, input, editor, ask).
7
7
  *
8
8
  * Usage: npx tsx examples/rpc-extension-ui.ts
9
9
  *
10
10
  * Slash commands:
11
- * /select - demo select dialog
12
- * /confirm - demo confirm dialog
13
- * /input - demo input dialog
14
- * /editor - demo editor dialog
11
+ * /select - demo select dialog
12
+ * /confirm - demo confirm dialog
13
+ * /input - demo input dialog
14
+ * /editor - demo editor dialog
15
+ * /rpc-ask - demo batch ask wizard from the companion extension
15
16
  */
16
17
 
17
18
  import { spawn } from "node:child_process";
@@ -39,12 +40,28 @@ const RESET = "\x1b[0m";
39
40
  // Extension UI request type (subset of rpc-types.ts)
40
41
  // ============================================================================
41
42
 
43
+ interface AskQuestion {
44
+ question: string;
45
+ title?: string;
46
+ options?: string[];
47
+ allowFreeText?: boolean;
48
+ multiSelect?: boolean;
49
+ multiline?: boolean;
50
+ }
51
+
52
+ interface AskAnswer {
53
+ selected: string[];
54
+ customText?: string;
55
+ skipped?: boolean;
56
+ }
57
+
42
58
  interface ExtensionUIRequest {
43
59
  type: "extension_ui_request";
44
60
  id: string;
45
61
  method: string;
46
62
  title?: string;
47
63
  options?: string[];
64
+ questions?: AskQuestion[];
48
65
  message?: string;
49
66
  placeholder?: string;
50
67
  prefill?: string;
@@ -239,6 +256,98 @@ class InputDialog implements Component {
239
256
  }
240
257
  }
241
258
 
259
+ /**
260
+ * Compact batch-question wizard for the RPC example. Each page accepts option
261
+ * numbers and optional free text separated by commas, then sends one ordered
262
+ * answers[] response after the final question.
263
+ */
264
+ class AskDialog implements Component {
265
+ private readonly input = new Input();
266
+ private readonly answers: AskAnswer[] = [];
267
+ private questionIndex = 0;
268
+ onSubmit?: (answers: AskAnswer[]) => void;
269
+ onCancel?: () => void;
270
+ onCtrlD?: () => void;
271
+
272
+ constructor(
273
+ private readonly title: string,
274
+ private readonly questions: AskQuestion[],
275
+ ) {
276
+ this.input.onSubmit = (value) => this.acceptAnswer(value);
277
+ this.input.onEscape = () => this.onCancel?.();
278
+ }
279
+
280
+ private acceptAnswer(value: string): void {
281
+ const question = this.questions[this.questionIndex];
282
+ if (!question) return;
283
+ const raw = value.trim();
284
+ const options = question.options ?? [];
285
+ const selected: string[] = [];
286
+ const customParts: string[] = [];
287
+
288
+ if (options.length === 0) {
289
+ if (raw) customParts.push(raw);
290
+ } else if (raw) {
291
+ for (const token of raw
292
+ .split(",")
293
+ .map((part) => part.trim())
294
+ .filter(Boolean)) {
295
+ const numericIndex = /^\d+$/.test(token) ? Number(token) - 1 : -1;
296
+ const matched =
297
+ options[numericIndex] ?? options.find((option) => option.toLowerCase() === token.toLowerCase());
298
+ if (matched && (question.multiSelect || selected.length === 0)) {
299
+ if (!selected.includes(matched)) selected.push(matched);
300
+ } else if (!matched && question.allowFreeText !== false) {
301
+ customParts.push(token);
302
+ }
303
+ }
304
+ }
305
+
306
+ const customText = customParts.join(", ").trim() || undefined;
307
+ this.answers.push(selected.length > 0 || customText ? { selected, customText } : { selected: [], skipped: true });
308
+ this.questionIndex++;
309
+ if (this.questionIndex >= this.questions.length) {
310
+ this.onSubmit?.(this.answers);
311
+ return;
312
+ }
313
+ this.input.setValue("");
314
+ }
315
+
316
+ handleInput(data: string): void {
317
+ if (matchesKey(data, "ctrl+d")) {
318
+ this.onCtrlD?.();
319
+ return;
320
+ }
321
+ this.input.handleInput(data);
322
+ }
323
+
324
+ invalidate(): void {
325
+ this.input.invalidate();
326
+ }
327
+
328
+ render(width: number): string[] {
329
+ const question = this.questions[this.questionIndex];
330
+ if (!question) return [`${RED}Invalid empty ask request${RESET}`];
331
+ const options = question.options ?? [];
332
+ const optionLines = options.map((option, index) => ` ${index + 1}. ${option}`);
333
+ const answerHint =
334
+ options.length === 0
335
+ ? "Type an answer"
336
+ : question.multiSelect
337
+ ? "Type option numbers separated by commas"
338
+ : "Type one option number";
339
+ const customHint = options.length > 0 && question.allowFreeText !== false ? ", plus optional text" : "";
340
+ return [
341
+ `${MAGENTA}${BOLD}${this.title} — ${this.questionIndex + 1}/${this.questions.length}${RESET}`,
342
+ `${BOLD}${question.title ?? question.question}${RESET}`,
343
+ ...(question.title ? [question.question] : []),
344
+ ...optionLines,
345
+ ...this.input.render(width),
346
+ `${DIM}${answerHint}${customHint}. Enter to continue, Esc to cancel.${RESET}`,
347
+ ];
348
+ }
349
+ }
350
+
242
351
  // ============================================================================
243
352
  // Main
244
353
  // ============================================================================
@@ -300,6 +409,7 @@ async function main() {
300
409
  // These helpers swap between them.
301
410
 
302
411
  let activeDialog: Component | null = null;
412
+ let activeDialogId: string | null = null;
303
413
 
304
414
  function setBottomComponent(component: Component): void {
305
415
  root.clear();
@@ -312,6 +422,7 @@ async function main() {
312
422
 
313
423
  function showPrompt(): void {
314
424
  activeDialog = null;
425
+ activeDialogId = null;
315
426
  setBottomComponent(promptInput);
316
427
  tui.setFocus(promptInput.input);
317
428
  }
@@ -374,8 +485,27 @@ async function main() {
374
485
  tui.setFocus(dialog.inputComponent);
375
486
  }
376
487
 
488
+ function showAskDialog(
489
+ title: string,
490
+ questions: AskQuestion[],
491
+ onDone: (answers: AskAnswer[] | undefined) => void,
492
+ ): void {
493
+ const dialog = new AskDialog(title, questions);
494
+ dialog.onSubmit = (answers) => {
495
+ showPrompt();
496
+ onDone(answers);
497
+ };
498
+ dialog.onCancel = () => {
499
+ showPrompt();
500
+ onDone(undefined);
501
+ };
502
+ dialog.onCtrlD = exit;
503
+ showDialog(dialog);
504
+ }
505
+
377
506
  function handleExtensionUI(req: ExtensionUIRequest): void {
378
507
  const { id, method } = req;
508
+ if (["select", "confirm", "input", "editor", "ask"].includes(method)) activeDialogId = id;
379
509
 
380
510
  switch (method) {
381
511
  // Dialog methods: replace prompt with interactive component
@@ -422,6 +552,23 @@ async function main() {
422
552
  break;
423
553
  }
424
554
 
555
+ case "ask": {
556
+ const questions = req.questions ?? [];
557
+ if (questions.length === 0) {
558
+ showPrompt();
559
+ send({ type: "extension_ui_response", id, cancelled: true });
560
+ break;
561
+ }
562
+ showAskDialog(req.title ?? "Question", questions, (answers) => {
563
+ if (answers) {
564
+ send({ type: "extension_ui_response", id, answers });
565
+ } else {
566
+ send({ type: "extension_ui_response", id, cancelled: true });
567
+ }
568
+ });
569
+ break;
570
+ }
571
+
425
572
  // Fire-and-forget methods: display as notification
426
573
  case "notify": {
427
574
  const notifyType = (req.notifyType as string) ?? "info";
@@ -450,6 +597,10 @@ async function main() {
450
597
  break;
451
598
  }
452
599
 
600
+ case "setTitle":
601
+ terminal.setTitle(req.title ?? "");
602
+ break;
603
+
453
604
  case "set_editor_text":
454
605
  promptInput.input.setValue((req.text as string) ?? "");
455
606
  tui.requestRender();
@@ -535,6 +686,11 @@ async function main() {
535
686
  return;
536
687
  }
537
688
 
689
+ if (data.type === "extension_ui_response_handled") {
690
+ if (data.id === activeDialogId) showPrompt();
691
+ return;
692
+ }
693
+
538
694
  if (data.type === "message_update") {
539
695
  const evt = data.assistantMessageEvent as Record<string, unknown> | undefined;
540
696
  if (evt?.type === "text_delta") {
@@ -620,7 +776,7 @@ async function main() {
620
776
 
621
777
  outputLog.append(`${BOLD}RPC Chat${RESET}`);
622
778
  outputLog.append(`${DIM}Type a message and press Enter. Esc to abort or exit. Ctrl+D to quit.${RESET}`);
623
- outputLog.append(`${DIM}Slash commands: /select /confirm /input /editor${RESET}`);
779
+ outputLog.append(`${DIM}Slash commands: /select /confirm /input /editor /rpc-ask${RESET}`);
624
780
  outputLog.append("");
625
781
 
626
782
  tui.start();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreb/coding-agent",
3
- "version": "2.51.0",
3
+ "version": "2.52.0",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "drebConfig": {
@@ -1,59 +0,0 @@
1
- /**
2
- * ask_user question component.
3
- *
4
- * Renders a clarifying question with optional single- or multi-select options
5
- * and an optional free-text field, matching the approved cross-surface design.
6
- *
7
- * Keyboard model (settled in issue 396 discussion):
8
- * ↑/↓ move a single cursor through the options and, last, the free-text field
9
- * Space toggle the highlighted checkbox (multi-select only)
10
- * Enter single-select: pick the highlighted option and submit;
11
- * free-text field: submit the typed answer;
12
- * multi-select: submit all checked options plus any free text
13
- * Shift+Enter insert a newline in the multiline free-text field
14
- * Esc stop the current agent turn
15
- */
16
- import { Container, type Focusable, type TUI } from "@dreb/tui";
17
- import type { AskRequest, AskResult } from "../../../core/extensions/types.js";
18
- export interface AskUserComponentOptions {
19
- tui?: TUI;
20
- timeout?: number;
21
- }
22
- export declare class AskUserComponent extends Container implements Focusable {
23
- private options;
24
- private allowFreeText;
25
- private multiSelect;
26
- private multiline;
27
- /** Cursor over [options..., freeTextRow?]. */
28
- private cursorIndex;
29
- /** Checkbox state for multi-select, aligned to options. */
30
- private checked;
31
- private onSubmitCallback;
32
- private onStopCallback;
33
- private titleText;
34
- private baseTitle;
35
- private optionsContainer;
36
- private fieldLabel;
37
- private input;
38
- private editor;
39
- private countdown;
40
- private submitted;
41
- private _focused;
42
- get focused(): boolean;
43
- set focused(value: boolean);
44
- private get freeTextRow();
45
- private get lastRow();
46
- private cursorOnField;
47
- constructor(request: AskRequest, onSubmit: (result: AskResult) => void, onStop: () => void, opts?: AskUserComponentOptions);
48
- private buildHint;
49
- private renderRows;
50
- private syncFieldFocus;
51
- private moveCursor;
52
- private fieldText;
53
- private currentAnswer;
54
- private submit;
55
- private stop;
56
- handleInput(keyData: string): void;
57
- dispose(): void;
58
- }
59
- //# sourceMappingURL=ask-user.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ask-user.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/ask-user.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,SAAS,EAAU,KAAK,SAAS,EAAiD,KAAK,GAAG,EAAE,MAAM,WAAW,CAAC;AACvH,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAM/E,MAAM,WAAW,uBAAuB;IACvC,GAAG,CAAC,EAAE,GAAG,CAAC;IACV,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,qBAAa,gBAAiB,SAAQ,SAAU,YAAW,SAAS;IACnE,OAAO,CAAC,OAAO,CAAW;IAC1B,OAAO,CAAC,aAAa,CAAU;IAC/B,OAAO,CAAC,WAAW,CAAU;IAC7B,OAAO,CAAC,SAAS,CAAU;IAE3B,8CAA8C;IAC9C,OAAO,CAAC,WAAW,CAAK;IACxB,2DAA2D;IAC3D,OAAO,CAAC,OAAO,CAAY;IAE3B,OAAO,CAAC,gBAAgB,CAA8B;IACtD,OAAO,CAAC,cAAc,CAAa;IAEnC,OAAO,CAAC,SAAS,CAAO;IACxB,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,gBAAgB,CAAY;IACpC,OAAO,CAAC,UAAU,CAAmB;IACrC,OAAO,CAAC,KAAK,CAAoB;IACjC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,SAAS,CAA6B;IAC9C,OAAO,CAAC,SAAS,CAAS;IAE1B,OAAO,CAAC,QAAQ,CAAS;IACzB,IAAI,OAAO,IAAI,OAAO,CAErB;IACD,IAAI,OAAO,CAAC,KAAK,EAAE,OAAO,EAGzB;IAED,OAAO,KAAK,WAAW,GAEtB;IAED,OAAO,KAAK,OAAO,GAElB;IAED,OAAO,CAAC,aAAa;IAIrB,YACC,OAAO,EAAE,UAAU,EACnB,QAAQ,EAAE,CAAC,MAAM,EAAE,SAAS,KAAK,IAAI,EACrC,MAAM,EAAE,MAAM,IAAI,EAClB,IAAI,CAAC,EAAE,uBAAuB,EA8D9B;IAED,OAAO,CAAC,SAAS;IASjB,OAAO,CAAC,UAAU;IAkBlB,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,UAAU;IASlB,OAAO,CAAC,SAAS;IAMjB,OAAO,CAAC,aAAa;IAkBrB,OAAO,CAAC,MAAM;IAQd,OAAO,CAAC,IAAI;IAMZ,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CA8CjC;IAED,OAAO,IAAI,IAAI,CAEd;CACD","sourcesContent":["/**\n * ask_user question component.\n *\n * Renders a clarifying question with optional single- or multi-select options\n * and an optional free-text field, matching the approved cross-surface design.\n *\n * Keyboard model (settled in issue 396 discussion):\n * ↑/↓ move a single cursor through the options and, last, the free-text field\n * Space toggle the highlighted checkbox (multi-select only)\n * Enter single-select: pick the highlighted option and submit;\n * free-text field: submit the typed answer;\n * multi-select: submit all checked options plus any free text\n * Shift+Enter insert a newline in the multiline free-text field\n * Esc stop the current agent turn\n */\n\nimport { Container, Editor, type Focusable, getKeybindings, Input, Markdown, Spacer, Text, type TUI } from \"@dreb/tui\";\nimport type { AskRequest, AskResult } from \"../../../core/extensions/types.js\";\nimport { getEditorTheme, getMarkdownTheme, theme } from \"../theme/theme.js\";\nimport { CountdownTimer } from \"./countdown-timer.js\";\nimport { DynamicBorder } from \"./dynamic-border.js\";\nimport { keyHint, rawKeyHint } from \"./keybinding-hints.js\";\n\nexport interface AskUserComponentOptions {\n\ttui?: TUI;\n\ttimeout?: number;\n}\n\nexport class AskUserComponent extends Container implements Focusable {\n\tprivate options: string[];\n\tprivate allowFreeText: boolean;\n\tprivate multiSelect: boolean;\n\tprivate multiline: boolean;\n\n\t/** Cursor over [options..., freeTextRow?]. */\n\tprivate cursorIndex = 0;\n\t/** Checkbox state for multi-select, aligned to options. */\n\tprivate checked: boolean[];\n\n\tprivate onSubmitCallback: (result: AskResult) => void;\n\tprivate onStopCallback: () => void;\n\n\tprivate titleText: Text;\n\tprivate baseTitle: string;\n\tprivate optionsContainer: Container;\n\tprivate fieldLabel: Text | undefined;\n\tprivate input: Input | undefined;\n\tprivate editor: Editor | undefined;\n\tprivate countdown: CountdownTimer | undefined;\n\tprivate submitted = false;\n\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.syncFieldFocus();\n\t}\n\n\tprivate get freeTextRow(): number {\n\t\treturn this.allowFreeText ? this.options.length : -1;\n\t}\n\n\tprivate get lastRow(): number {\n\t\treturn this.allowFreeText ? this.options.length : this.options.length - 1;\n\t}\n\n\tprivate cursorOnField(): boolean {\n\t\treturn this.allowFreeText && this.cursorIndex === this.freeTextRow;\n\t}\n\n\tconstructor(\n\t\trequest: AskRequest,\n\t\tonSubmit: (result: AskResult) => void,\n\t\tonStop: () => void,\n\t\topts?: AskUserComponentOptions,\n\t) {\n\t\tsuper();\n\n\t\tthis.options = request.options ?? [];\n\t\tthis.allowFreeText = request.allowFreeText !== false;\n\t\tthis.multiSelect = request.multiSelect === true && this.options.length > 0;\n\t\tthis.multiline = request.multiline === true;\n\t\tthis.checked = this.options.map(() => false);\n\t\tthis.onSubmitCallback = onSubmit;\n\t\tthis.onStopCallback = onStop;\n\t\tthis.baseTitle = request.title?.trim() || \"Question\";\n\n\t\t// Start the cursor on the first option, or the free-text field when there\n\t\t// are no options.\n\t\tthis.cursorIndex = this.options.length > 0 ? 0 : this.freeTextRow;\n\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\tthis.titleText = new Text(theme.fg(\"accent\", theme.bold(this.baseTitle)), 1, 0);\n\t\tthis.addChild(this.titleText);\n\t\tthis.addChild(new Spacer(1));\n\n\t\tthis.addChild(new Markdown(request.question, 1, 0, getMarkdownTheme(), undefined, true));\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (opts?.timeout && opts.timeout > 0 && opts.tui) {\n\t\t\tthis.countdown = new CountdownTimer(\n\t\t\t\topts.timeout,\n\t\t\t\topts.tui,\n\t\t\t\t(s) => this.titleText.setText(theme.fg(\"accent\", theme.bold(`${this.baseTitle} (${s}s)`))),\n\t\t\t\t() => this.stop(),\n\t\t\t);\n\t\t}\n\n\t\tthis.optionsContainer = new Container();\n\t\tthis.addChild(this.optionsContainer);\n\n\t\tif (this.allowFreeText) {\n\t\t\tthis.addChild(new Spacer(1));\n\t\t\tthis.fieldLabel = new Text(\"\", 1, 0);\n\t\t\tthis.addChild(this.fieldLabel);\n\t\t\tif (this.multiline && opts?.tui) {\n\t\t\t\tthis.editor = new Editor(opts.tui, getEditorTheme(), {});\n\t\t\t\t// The Editor clears its own state before invoking onSubmit, so we must\n\t\t\t\t// use the text it hands us rather than re-reading the now-empty editor.\n\t\t\t\tthis.editor.onSubmit = (text) => this.submit(text);\n\t\t\t\tthis.addChild(this.editor);\n\t\t\t} else {\n\t\t\t\tthis.input = new Input();\n\t\t\t\tthis.addChild(this.input);\n\t\t\t}\n\t\t}\n\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(this.buildHint(), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tthis.renderRows();\n\t\tthis.syncFieldFocus();\n\t}\n\n\tprivate buildHint(): string {\n\t\tconst parts = [rawKeyHint(\"↑↓\", \"move\")];\n\t\tif (this.multiSelect) parts.push(rawKeyHint(\"Space\", \"toggle\"));\n\t\tparts.push(keyHint(\"tui.select.confirm\", \"submit\"));\n\t\tif (this.multiline) parts.push(keyHint(\"tui.input.newLine\", \"newline\"));\n\t\tparts.push(keyHint(\"tui.select.cancel\", \"stop agent\"));\n\t\treturn parts.join(\" \");\n\t}\n\n\tprivate renderRows(): void {\n\t\tthis.optionsContainer.clear();\n\t\tfor (let i = 0; i < this.options.length; i++) {\n\t\t\tconst focused = this.cursorIndex === i;\n\t\t\tconst cursor = focused ? theme.fg(\"accent\", \"→ \") : \" \";\n\t\t\tconst glyph = this.multiSelect ? (this.checked[i] ? \"[x]\" : \"[ ]\") : focused ? \"(•)\" : \"( )\";\n\t\t\tconst label = focused ? theme.fg(\"accent\", this.options[i]) : theme.fg(\"text\", this.options[i]);\n\t\t\tconst glyphColored = this.checked[i] || (!this.multiSelect && focused) ? theme.fg(\"accent\", glyph) : glyph;\n\t\t\tthis.optionsContainer.addChild(new Text(`${cursor}${glyphColored} ${label}`, 1, 0));\n\t\t}\n\t\tif (this.fieldLabel) {\n\t\t\tconst focused = this.cursorOnField();\n\t\t\tconst prefix = focused ? theme.fg(\"accent\", \"→ \") : \" \";\n\t\t\tconst labelText = this.options.length > 0 ? \"Or type your own answer:\" : \"Your answer:\";\n\t\t\tthis.fieldLabel.setText(prefix + (focused ? theme.fg(\"accent\", labelText) : theme.fg(\"muted\", labelText)));\n\t\t}\n\t}\n\n\tprivate syncFieldFocus(): void {\n\t\tconst fieldFocused = this._focused && this.cursorOnField();\n\t\tif (this.input) this.input.focused = fieldFocused;\n\t\tif (this.editor) this.editor.focused = fieldFocused;\n\t}\n\n\tprivate moveCursor(delta: number): void {\n\t\tconst first = this.options.length > 0 ? 0 : this.freeTextRow;\n\t\tconst next = Math.max(first, Math.min(this.lastRow, this.cursorIndex + delta));\n\t\tif (next === this.cursorIndex) return;\n\t\tthis.cursorIndex = next;\n\t\tthis.renderRows();\n\t\tthis.syncFieldFocus();\n\t}\n\n\tprivate fieldText(editorTextOverride?: string): string {\n\t\tif (this.editor) return (editorTextOverride ?? this.editor.getText()).trim();\n\t\tif (this.input) return this.input.getValue().trim();\n\t\treturn \"\";\n\t}\n\n\tprivate currentAnswer(editorTextOverride?: string): AskResult | undefined {\n\t\tconst customText = this.fieldText(editorTextOverride) || undefined;\n\t\tif (this.multiSelect) {\n\t\t\tconst selected = this.options.filter((_, i) => this.checked[i]);\n\t\t\tif (selected.length === 0 && !customText) return undefined;\n\t\t\treturn { selected, customText };\n\t\t}\n\t\tif (this.cursorOnField()) {\n\t\t\tif (!customText) return undefined;\n\t\t\treturn { selected: [], customText };\n\t\t}\n\t\tconst option = this.options[this.cursorIndex];\n\t\t// Single-select: submit the highlighted option together with any typed\n\t\t// free text, matching the Dashboard, which combines a radio selection with\n\t\t// custom text (and the tool's own combined-answer result formatting).\n\t\treturn option ? { selected: [option], customText } : undefined;\n\t}\n\n\tprivate submit(editorTextOverride?: string): void {\n\t\tif (this.submitted) return;\n\t\tconst answer = this.currentAnswer(editorTextOverride);\n\t\tif (!answer) return; // Nothing to submit yet — Esc stops the turn instead.\n\t\tthis.submitted = true;\n\t\tthis.onSubmitCallback(answer);\n\t}\n\n\tprivate stop(): void {\n\t\tif (this.submitted) return;\n\t\tthis.submitted = true;\n\t\tthis.onStopCallback();\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\n\t\tif (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.stop();\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.cursorOnField()) {\n\t\t\t// Multiline editor: Enter submits (via onSubmit), Shift+Enter inserts a\n\t\t\t// newline, ↑ at the top line leaves to the options, everything else edits.\n\t\t\tif (this.editor) {\n\t\t\t\tif (kb.matches(keyData, \"tui.select.up\") && this.editor.getCursor().line === 0) {\n\t\t\t\t\tthis.moveCursor(-1);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.editor.handleInput(keyData);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Single-line input: ↑ leaves to the options, Enter submits, else edits.\n\t\t\tif (this.input) {\n\t\t\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\t\t\tthis.moveCursor(-1);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (kb.matches(keyData, \"tui.select.confirm\") || keyData === \"\\n\") {\n\t\t\t\t\tthis.submit();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.input.handleInput(keyData);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Cursor on an option row.\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tthis.moveCursor(-1);\n\t\t} else if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tthis.moveCursor(1);\n\t\t} else if (this.multiSelect && keyData === \" \") {\n\t\t\tthis.checked[this.cursorIndex] = !this.checked[this.cursorIndex];\n\t\t\tthis.renderRows();\n\t\t} else if (kb.matches(keyData, \"tui.select.confirm\") || keyData === \"\\n\") {\n\t\t\tthis.submit();\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.countdown?.dispose();\n\t}\n}\n"]}