questionnaire.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. /**
  2. * Questionnaire Tool - Unified tool for asking single or multiple questions
  3. *
  4. * Single question: simple options list
  5. * Multiple questions: tab bar navigation between questions
  6. */
  7. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  8. import { Editor, type EditorTheme, Key, matchesKey, Text, truncateToWidth } from "@earendil-works/pi-tui";
  9. import { Type } from "typebox";
  10. // Types
  11. interface QuestionOption {
  12. value: string;
  13. label: string;
  14. description?: string;
  15. }
  16. type RenderOption = QuestionOption & { isOther?: boolean };
  17. interface Question {
  18. id: string;
  19. label: string;
  20. prompt: string;
  21. options: QuestionOption[];
  22. allowOther: boolean;
  23. }
  24. interface Answer {
  25. id: string;
  26. value: string;
  27. label: string;
  28. wasCustom: boolean;
  29. index?: number;
  30. }
  31. interface QuestionnaireResult {
  32. questions: Question[];
  33. answers: Answer[];
  34. cancelled: boolean;
  35. }
  36. // Schema
  37. const QuestionOptionSchema = Type.Object({
  38. value: Type.String({ description: "The value returned when selected" }),
  39. label: Type.String({ description: "Display label for the option" }),
  40. description: Type.Optional(Type.String({ description: "Optional description shown below label" })),
  41. });
  42. const QuestionSchema = Type.Object({
  43. id: Type.String({ description: "Unique identifier for this question" }),
  44. label: Type.Optional(
  45. Type.String({
  46. description: "Short contextual label for tab bar, e.g. 'Scope', 'Priority' (defaults to Q1, Q2)",
  47. }),
  48. ),
  49. prompt: Type.String({ description: "The full question text to display" }),
  50. options: Type.Array(QuestionOptionSchema, { description: "Available options to choose from" }),
  51. allowOther: Type.Optional(Type.Boolean({ description: "Allow 'Type something' option (default: true)" })),
  52. });
  53. const QuestionnaireParams = Type.Object({
  54. questions: Type.Array(QuestionSchema, { description: "Questions to ask the user" }),
  55. });
  56. function errorResult(
  57. message: string,
  58. questions: Question[] = [],
  59. ): { content: { type: "text"; text: string }[]; details: QuestionnaireResult } {
  60. return {
  61. content: [{ type: "text", text: message }],
  62. details: { questions, answers: [], cancelled: true },
  63. };
  64. }
  65. export default function questionnaire(pi: ExtensionAPI) {
  66. pi.registerTool({
  67. name: "questionnaire",
  68. label: "Questionnaire",
  69. description:
  70. "Ask the user one or more questions. Use for clarifying requirements, getting preferences, or confirming decisions. For single questions, shows a simple option list. For multiple questions, shows a tab-based interface.",
  71. parameters: QuestionnaireParams,
  72. async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
  73. if (ctx.mode !== "tui") {
  74. return errorResult("Error: UI not available (running in non-interactive mode)");
  75. }
  76. if (params.questions.length === 0) {
  77. return errorResult("Error: No questions provided");
  78. }
  79. // Normalize questions with defaults
  80. const questions: Question[] = params.questions.map((q, i) => ({
  81. ...q,
  82. label: q.label || `Q${i + 1}`,
  83. allowOther: q.allowOther !== false,
  84. }));
  85. const isMulti = questions.length > 1;
  86. const totalTabs = questions.length + 1; // questions + Submit
  87. const result = await ctx.ui.custom<QuestionnaireResult>((tui, theme, _kb, done) => {
  88. // State
  89. let currentTab = 0;
  90. let optionIndex = 0;
  91. let inputMode = false;
  92. let inputQuestionId: string | null = null;
  93. let cachedLines: string[] | undefined;
  94. const answers = new Map<string, Answer>();
  95. // Editor for "Type something" option
  96. const editorTheme: EditorTheme = {
  97. borderColor: (s) => theme.fg("accent", s),
  98. selectList: {
  99. selectedPrefix: (t) => theme.fg("accent", t),
  100. selectedText: (t) => theme.fg("accent", t),
  101. description: (t) => theme.fg("muted", t),
  102. scrollInfo: (t) => theme.fg("dim", t),
  103. noMatch: (t) => theme.fg("warning", t),
  104. },
  105. };
  106. const editor = new Editor(tui, editorTheme);
  107. // Helpers
  108. function refresh() {
  109. cachedLines = undefined;
  110. tui.requestRender();
  111. }
  112. function submit(cancelled: boolean) {
  113. done({ questions, answers: Array.from(answers.values()), cancelled });
  114. }
  115. function currentQuestion(): Question | undefined {
  116. return questions[currentTab];
  117. }
  118. function currentOptions(): RenderOption[] {
  119. const q = currentQuestion();
  120. if (!q) return [];
  121. const opts: RenderOption[] = [...q.options];
  122. if (q.allowOther) {
  123. opts.push({ value: "__other__", label: "Type something.", isOther: true });
  124. }
  125. return opts;
  126. }
  127. function allAnswered(): boolean {
  128. return questions.every((q) => answers.has(q.id));
  129. }
  130. function advanceAfterAnswer() {
  131. if (!isMulti) {
  132. submit(false);
  133. return;
  134. }
  135. if (currentTab < questions.length - 1) {
  136. currentTab++;
  137. } else {
  138. currentTab = questions.length; // Submit tab
  139. }
  140. optionIndex = 0;
  141. refresh();
  142. }
  143. function saveAnswer(questionId: string, value: string, label: string, wasCustom: boolean, index?: number) {
  144. answers.set(questionId, { id: questionId, value, label, wasCustom, index });
  145. }
  146. // Editor submit callback
  147. editor.onSubmit = (value) => {
  148. if (!inputQuestionId) return;
  149. const trimmed = value.trim() || "(no response)";
  150. saveAnswer(inputQuestionId, trimmed, trimmed, true);
  151. inputMode = false;
  152. inputQuestionId = null;
  153. editor.setText("");
  154. advanceAfterAnswer();
  155. };
  156. function handleInput(data: string) {
  157. // Input mode: route to editor
  158. if (inputMode) {
  159. if (matchesKey(data, Key.escape)) {
  160. inputMode = false;
  161. inputQuestionId = null;
  162. editor.setText("");
  163. refresh();
  164. return;
  165. }
  166. editor.handleInput(data);
  167. refresh();
  168. return;
  169. }
  170. const q = currentQuestion();
  171. const opts = currentOptions();
  172. // Tab navigation (multi-question only)
  173. if (isMulti) {
  174. if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) {
  175. currentTab = (currentTab + 1) % totalTabs;
  176. optionIndex = 0;
  177. refresh();
  178. return;
  179. }
  180. if (matchesKey(data, Key.shift("tab")) || matchesKey(data, Key.left)) {
  181. currentTab = (currentTab - 1 + totalTabs) % totalTabs;
  182. optionIndex = 0;
  183. refresh();
  184. return;
  185. }
  186. }
  187. // Submit tab
  188. if (currentTab === questions.length) {
  189. if (matchesKey(data, Key.enter) && allAnswered()) {
  190. submit(false);
  191. } else if (matchesKey(data, Key.escape)) {
  192. submit(true);
  193. }
  194. return;
  195. }
  196. // Option navigation
  197. if (matchesKey(data, Key.up)) {
  198. optionIndex = Math.max(0, optionIndex - 1);
  199. refresh();
  200. return;
  201. }
  202. if (matchesKey(data, Key.down)) {
  203. optionIndex = Math.min(opts.length - 1, optionIndex + 1);
  204. refresh();
  205. return;
  206. }
  207. // Select option
  208. if (matchesKey(data, Key.enter) && q) {
  209. const opt = opts[optionIndex];
  210. if (opt.isOther) {
  211. inputMode = true;
  212. inputQuestionId = q.id;
  213. editor.setText("");
  214. refresh();
  215. return;
  216. }
  217. saveAnswer(q.id, opt.value, opt.label, false, optionIndex + 1);
  218. advanceAfterAnswer();
  219. return;
  220. }
  221. // Cancel
  222. if (matchesKey(data, Key.escape)) {
  223. submit(true);
  224. }
  225. }
  226. function render(width: number): string[] {
  227. if (cachedLines) return cachedLines;
  228. const lines: string[] = [];
  229. const q = currentQuestion();
  230. const opts = currentOptions();
  231. // Helper to add truncated line
  232. const add = (s: string) => lines.push(truncateToWidth(s, width));
  233. add(theme.fg("accent", "─".repeat(width)));
  234. // Tab bar (multi-question only)
  235. if (isMulti) {
  236. const tabs: string[] = ["← "];
  237. for (let i = 0; i < questions.length; i++) {
  238. const isActive = i === currentTab;
  239. const isAnswered = answers.has(questions[i].id);
  240. const lbl = questions[i].label;
  241. const box = isAnswered ? "■" : "□";
  242. const color = isAnswered ? "success" : "muted";
  243. const text = ` ${box} ${lbl} `;
  244. const styled = isActive ? theme.bg("selectedBg", theme.fg("text", text)) : theme.fg(color, text);
  245. tabs.push(`${styled} `);
  246. }
  247. const canSubmit = allAnswered();
  248. const isSubmitTab = currentTab === questions.length;
  249. const submitText = " ✓ Submit ";
  250. const submitStyled = isSubmitTab
  251. ? theme.bg("selectedBg", theme.fg("text", submitText))
  252. : theme.fg(canSubmit ? "success" : "dim", submitText);
  253. tabs.push(`${submitStyled} →`);
  254. add(` ${tabs.join("")}`);
  255. lines.push("");
  256. }
  257. // Helper to render options list
  258. function renderOptions() {
  259. for (let i = 0; i < opts.length; i++) {
  260. const opt = opts[i];
  261. const selected = i === optionIndex;
  262. const isOther = opt.isOther === true;
  263. const prefix = selected ? theme.fg("accent", "> ") : " ";
  264. const color = selected ? "accent" : "text";
  265. // Mark "Type something" differently when in input mode
  266. if (isOther && inputMode) {
  267. add(prefix + theme.fg("accent", `${i + 1}. ${opt.label} ✎`));
  268. } else {
  269. add(prefix + theme.fg(color, `${i + 1}. ${opt.label}`));
  270. }
  271. if (opt.description) {
  272. add(` ${theme.fg("muted", opt.description)}`);
  273. }
  274. }
  275. }
  276. // Content
  277. if (inputMode && q) {
  278. add(theme.fg("text", ` ${q.prompt}`));
  279. lines.push("");
  280. // Show options for reference
  281. renderOptions();
  282. lines.push("");
  283. add(theme.fg("muted", " Your answer:"));
  284. for (const line of editor.render(width - 2)) {
  285. add(` ${line}`);
  286. }
  287. lines.push("");
  288. add(theme.fg("dim", " Enter to submit • Esc to cancel"));
  289. } else if (currentTab === questions.length) {
  290. add(theme.fg("accent", theme.bold(" Ready to submit")));
  291. lines.push("");
  292. for (const question of questions) {
  293. const answer = answers.get(question.id);
  294. if (answer) {
  295. const prefix = answer.wasCustom ? "(wrote) " : "";
  296. add(`${theme.fg("muted", ` ${question.label}: `)}${theme.fg("text", prefix + answer.label)}`);
  297. }
  298. }
  299. lines.push("");
  300. if (allAnswered()) {
  301. add(theme.fg("success", " Press Enter to submit"));
  302. } else {
  303. const missing = questions
  304. .filter((q) => !answers.has(q.id))
  305. .map((q) => q.label)
  306. .join(", ");
  307. add(theme.fg("warning", ` Unanswered: ${missing}`));
  308. }
  309. } else if (q) {
  310. add(theme.fg("text", ` ${q.prompt}`));
  311. lines.push("");
  312. renderOptions();
  313. }
  314. lines.push("");
  315. if (!inputMode) {
  316. const help = isMulti
  317. ? " Tab/←→ navigate • ↑↓ select • Enter confirm • Esc cancel"
  318. : " ↑↓ navigate • Enter select • Esc cancel";
  319. add(theme.fg("dim", help));
  320. }
  321. add(theme.fg("accent", "─".repeat(width)));
  322. cachedLines = lines;
  323. return lines;
  324. }
  325. return {
  326. render,
  327. invalidate: () => {
  328. cachedLines = undefined;
  329. },
  330. handleInput,
  331. };
  332. });
  333. if (result.cancelled) {
  334. return {
  335. content: [{ type: "text", text: "User cancelled the questionnaire" }],
  336. details: result,
  337. };
  338. }
  339. const answerLines = result.answers.map((a) => {
  340. const qLabel = questions.find((q) => q.id === a.id)?.label || a.id;
  341. if (a.wasCustom) {
  342. return `${qLabel}: user wrote: ${a.label}`;
  343. }
  344. return `${qLabel}: user selected: ${a.index}. ${a.label}`;
  345. });
  346. return {
  347. content: [{ type: "text", text: answerLines.join("\n") }],
  348. details: result,
  349. };
  350. },
  351. renderCall(args, theme, _context) {
  352. const qs = (args.questions as Question[]) || [];
  353. const count = qs.length;
  354. const labels = qs.map((q) => q.label || q.id).join(", ");
  355. let text = theme.fg("toolTitle", theme.bold("questionnaire "));
  356. text += theme.fg("muted", `${count} question${count !== 1 ? "s" : ""}`);
  357. if (labels) {
  358. text += theme.fg("dim", ` (${truncateToWidth(labels, 40)})`);
  359. }
  360. return new Text(text, 0, 0);
  361. },
  362. renderResult(result, _options, theme, _context) {
  363. const details = result.details as QuestionnaireResult | undefined;
  364. if (!details) {
  365. const text = result.content[0];
  366. return new Text(text?.type === "text" ? text.text : "", 0, 0);
  367. }
  368. if (details.cancelled) {
  369. return new Text(theme.fg("warning", "Cancelled"), 0, 0);
  370. }
  371. const lines = details.answers.map((a) => {
  372. if (a.wasCustom) {
  373. return `${theme.fg("success", "✓ ")}${theme.fg("accent", a.id)}: ${theme.fg("muted", "(wrote) ")}${a.label}`;
  374. }
  375. const display = a.index ? `${a.index}. ${a.label}` : a.label;
  376. return `${theme.fg("success", "✓ ")}${theme.fg("accent", a.id)}: ${display}`;
  377. });
  378. return new Text(lines.join("\n"), 0, 0);
  379. },
  380. });
  381. }