question.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /**
  2. * Question Tool - Single question with options
  3. * Full custom UI: options list + inline editor for "Type something..."
  4. * Escape in editor returns to options, Escape in options cancels
  5. */
  6. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  7. import { Editor, type EditorTheme, Key, matchesKey, Text, truncateToWidth } from "@earendil-works/pi-tui";
  8. import { Type } from "typebox";
  9. interface OptionWithDesc {
  10. label: string;
  11. description?: string;
  12. }
  13. type DisplayOption = OptionWithDesc & { isOther?: boolean };
  14. interface QuestionDetails {
  15. question: string;
  16. options: string[];
  17. answer: string | null;
  18. wasCustom?: boolean;
  19. }
  20. // Options with labels and optional descriptions
  21. const OptionSchema = Type.Object({
  22. label: Type.String({ description: "Display label for the option" }),
  23. description: Type.Optional(Type.String({ description: "Optional description shown below label" })),
  24. });
  25. const QuestionParams = Type.Object({
  26. question: Type.String({ description: "The question to ask the user" }),
  27. options: Type.Array(OptionSchema, { description: "Options for the user to choose from" }),
  28. });
  29. export default function question(pi: ExtensionAPI) {
  30. pi.registerTool({
  31. name: "question",
  32. label: "Question",
  33. description: "Ask the user a question and let them pick from options. Use when you need user input to proceed.",
  34. parameters: QuestionParams,
  35. async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
  36. if (ctx.mode !== "tui") {
  37. return {
  38. content: [{ type: "text", text: "Error: UI not available (running in non-interactive mode)" }],
  39. details: {
  40. question: params.question,
  41. options: params.options.map((o) => o.label),
  42. answer: null,
  43. } as QuestionDetails,
  44. };
  45. }
  46. if (params.options.length === 0) {
  47. return {
  48. content: [{ type: "text", text: "Error: No options provided" }],
  49. details: { question: params.question, options: [], answer: null } as QuestionDetails,
  50. };
  51. }
  52. const allOptions: DisplayOption[] = [...params.options, { label: "Type something.", isOther: true }];
  53. const result = await ctx.ui.custom<{ answer: string; wasCustom: boolean; index?: number } | null>(
  54. (tui, theme, _kb, done) => {
  55. let optionIndex = 0;
  56. let editMode = false;
  57. let cachedLines: string[] | undefined;
  58. const editorTheme: EditorTheme = {
  59. borderColor: (s) => theme.fg("accent", s),
  60. selectList: {
  61. selectedPrefix: (t) => theme.fg("accent", t),
  62. selectedText: (t) => theme.fg("accent", t),
  63. description: (t) => theme.fg("muted", t),
  64. scrollInfo: (t) => theme.fg("dim", t),
  65. noMatch: (t) => theme.fg("warning", t),
  66. },
  67. };
  68. const editor = new Editor(tui, editorTheme);
  69. editor.onSubmit = (value) => {
  70. const trimmed = value.trim();
  71. if (trimmed) {
  72. done({ answer: trimmed, wasCustom: true });
  73. } else {
  74. editMode = false;
  75. editor.setText("");
  76. refresh();
  77. }
  78. };
  79. function refresh() {
  80. cachedLines = undefined;
  81. tui.requestRender();
  82. }
  83. function handleInput(data: string) {
  84. if (editMode) {
  85. if (matchesKey(data, Key.escape)) {
  86. editMode = false;
  87. editor.setText("");
  88. refresh();
  89. return;
  90. }
  91. editor.handleInput(data);
  92. refresh();
  93. return;
  94. }
  95. if (matchesKey(data, Key.up)) {
  96. optionIndex = Math.max(0, optionIndex - 1);
  97. refresh();
  98. return;
  99. }
  100. if (matchesKey(data, Key.down)) {
  101. optionIndex = Math.min(allOptions.length - 1, optionIndex + 1);
  102. refresh();
  103. return;
  104. }
  105. if (matchesKey(data, Key.enter)) {
  106. const selected = allOptions[optionIndex];
  107. if (selected.isOther) {
  108. editMode = true;
  109. refresh();
  110. } else {
  111. done({ answer: selected.label, wasCustom: false, index: optionIndex + 1 });
  112. }
  113. return;
  114. }
  115. if (matchesKey(data, Key.escape)) {
  116. done(null);
  117. }
  118. }
  119. function render(width: number): string[] {
  120. if (cachedLines) return cachedLines;
  121. const lines: string[] = [];
  122. const add = (s: string) => lines.push(truncateToWidth(s, width));
  123. add(theme.fg("accent", "─".repeat(width)));
  124. add(theme.fg("text", ` ${params.question}`));
  125. lines.push("");
  126. for (let i = 0; i < allOptions.length; i++) {
  127. const opt = allOptions[i];
  128. const selected = i === optionIndex;
  129. const isOther = opt.isOther === true;
  130. const prefix = selected ? theme.fg("accent", "> ") : " ";
  131. if (isOther && editMode) {
  132. add(prefix + theme.fg("accent", `${i + 1}. ${opt.label} ✎`));
  133. } else if (selected) {
  134. add(prefix + theme.fg("accent", `${i + 1}. ${opt.label}`));
  135. } else {
  136. add(` ${theme.fg("text", `${i + 1}. ${opt.label}`)}`);
  137. }
  138. // Show description if present
  139. if (opt.description) {
  140. add(` ${theme.fg("muted", opt.description)}`);
  141. }
  142. }
  143. if (editMode) {
  144. lines.push("");
  145. add(theme.fg("muted", " Your answer:"));
  146. for (const line of editor.render(width - 2)) {
  147. add(` ${line}`);
  148. }
  149. }
  150. lines.push("");
  151. if (editMode) {
  152. add(theme.fg("dim", " Enter to submit • Esc to go back"));
  153. } else {
  154. add(theme.fg("dim", " ↑↓ navigate • Enter to select • Esc to cancel"));
  155. }
  156. add(theme.fg("accent", "─".repeat(width)));
  157. cachedLines = lines;
  158. return lines;
  159. }
  160. return {
  161. render,
  162. invalidate: () => {
  163. cachedLines = undefined;
  164. },
  165. handleInput,
  166. };
  167. },
  168. );
  169. // Build simple options list for details
  170. const simpleOptions = params.options.map((o) => o.label);
  171. if (!result) {
  172. return {
  173. content: [{ type: "text", text: "User cancelled the selection" }],
  174. details: { question: params.question, options: simpleOptions, answer: null } as QuestionDetails,
  175. };
  176. }
  177. if (result.wasCustom) {
  178. return {
  179. content: [{ type: "text", text: `User wrote: ${result.answer}` }],
  180. details: {
  181. question: params.question,
  182. options: simpleOptions,
  183. answer: result.answer,
  184. wasCustom: true,
  185. } as QuestionDetails,
  186. };
  187. }
  188. return {
  189. content: [{ type: "text", text: `User selected: ${result.index}. ${result.answer}` }],
  190. details: {
  191. question: params.question,
  192. options: simpleOptions,
  193. answer: result.answer,
  194. wasCustom: false,
  195. } as QuestionDetails,
  196. };
  197. },
  198. renderCall(args, theme, _context) {
  199. let text = theme.fg("toolTitle", theme.bold("question ")) + theme.fg("muted", args.question);
  200. const opts = Array.isArray(args.options) ? args.options : [];
  201. if (opts.length) {
  202. const labels = opts.map((o: OptionWithDesc) => o.label);
  203. const numbered = [...labels, "Type something."].map((o, i) => `${i + 1}. ${o}`);
  204. text += `\n${theme.fg("dim", ` Options: ${numbered.join(", ")}`)}`;
  205. }
  206. return new Text(text, 0, 0);
  207. },
  208. renderResult(result, _options, theme, _context) {
  209. const details = result.details as QuestionDetails | undefined;
  210. if (!details) {
  211. const text = result.content[0];
  212. return new Text(text?.type === "text" ? text.text : "", 0, 0);
  213. }
  214. if (details.answer === null) {
  215. return new Text(theme.fg("warning", "Cancelled"), 0, 0);
  216. }
  217. if (details.wasCustom) {
  218. return new Text(
  219. theme.fg("success", "✓ ") + theme.fg("muted", "(wrote) ") + theme.fg("accent", details.answer),
  220. 0,
  221. 0,
  222. );
  223. }
  224. const idx = details.options.indexOf(details.answer) + 1;
  225. const display = idx > 0 ? `${idx}. ${details.answer}` : details.answer;
  226. return new Text(theme.fg("success", "✓ ") + theme.fg("accent", display), 0, 0);
  227. },
  228. });
  229. }