main
  1/**
  2 * Ask User Tool
  3 *
  4 * Allows the AI to ask the user a question and wait for their response.
  5 * Supports free-form text input, single-choice suggestions, and
  6 * multi-select checkboxes.
  7 *
  8 * Usage by the AI:
  9 *   AskUserQuestion({ question: "Which database should I use?" })
 10 *   AskUserQuestion({ question: "How should I handle errors?", suggestions: ["retry", "fail fast", "log and continue"] })
 11 *   AskUserQuestion({ question: "Which features?", suggestions: ["auth", "logging", "caching"], multiSelect: true })
 12 */
 13
 14import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
 15import { DynamicBorder, getSettingsListTheme } from "@earendil-works/pi-coding-agent";
 16import { Container, type SettingItem, SettingsList, Text } from "@earendil-works/pi-tui";
 17import { Type } from "@sinclair/typebox";
 18
 19import { multiSelectInputPrompt, parseMultiSelectAnswer } from "./ask-user/ask-user-utils";
 20
 21/**
 22 * Serializes TUI access across concurrent tool calls.
 23 *
 24 * The harness may execute several tool calls from a single assistant turn
 25 * concurrently. Since AskUserQuestion grabs the single TUI input focus
 26 * (ctx.ui.custom/select/input), running more than one at once deadlocks:
 27 * the overlays fight for focus and none ever resolves, so no tool results
 28 * are produced and the turn hangs forever.
 29 *
 30 * This mutex chains executions so each question is presented (and answered)
 31 * before the next one starts.
 32 */
 33let uiLock: Promise<void> = Promise.resolve();
 34
 35function acquireUILock(): Promise<() => void> {
 36	let release!: () => void;
 37	const next = new Promise<void>((resolve) => {
 38		release = resolve;
 39	});
 40	const prev = uiLock;
 41	uiLock = uiLock.then(() => next);
 42	return prev.then(() => release);
 43}
 44
 45export default function (pi: ExtensionAPI) {
 46	pi.registerTool({
 47		name: "AskUserQuestion",
 48		label: "Ask User",
 49		description:
 50			"Ask the user a question and wait for their response. Use when you need clarification, a decision, or user input to proceed. Supports optional suggestions the user can pick from or ignore.",
 51		promptSnippet: "Ask the user a concise question when a decision or missing information blocks progress.",
 52		promptGuidelines: [
 53			"Use AskUserQuestion when you need user input, clarification, or a decision before proceeding.",
 54			"Prefer AskUserQuestion over guessing when the choice significantly affects the outcome.",
 55			"Keep questions concise and specific. Provide suggestions when there are obvious options.",
 56			"Use multiSelect: true when the user may want to pick more than one option from the suggestions.",
 57		],
 58		parameters: Type.Object({
 59			question: Type.String({ description: "The question to ask the user" }),
 60			suggestions: Type.Optional(
 61				Type.Array(Type.String(), {
 62					description:
 63						"Optional list of suggested answers. User can pick one or type their own response.",
 64				}),
 65			),
 66			multiSelect: Type.Optional(
 67				Type.Boolean({
 68					description:
 69						"If true, user can select multiple suggestions (checkbox-style). Requires suggestions to be provided.",
 70				}),
 71			),
 72		}),
 73
 74		async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
 75			if (!ctx.hasUI) {
 76				return {
 77					content: [
 78						{
 79							type: "text",
 80							text: "Error: Cannot ask user — running in non-interactive mode",
 81						},
 82					],
 83					details: { question: params.question, answer: null },
 84				};
 85			}
 86
 87			// Serialize: if the model asked several questions in one turn, present
 88			// them sequentially instead of letting the overlays deadlock.
 89			const release = await acquireUILock();
 90			try {
 91			const { question, suggestions, multiSelect } = params;
 92			const hasSuggestions = suggestions && suggestions.length > 0;
 93
 94			let answer: string | undefined;
 95
 96			if (multiSelect && hasSuggestions) {
 97				if (ctx.mode !== "tui") {
 98					const selected = parseMultiSelectAnswer(await ctx.ui.input(multiSelectInputPrompt(question, suggestions)));
 99					if (selected.length === 0) {
100						return {
101							content: [{ type: "text", text: "User cancelled — did not select any options." }],
102							details: { question, suggestions, multiSelect: true, answer: null, selected: [] },
103						};
104					}
105
106					answer = selected.join(", ");
107					return {
108						content: [{ type: "text", text: `User selected: ${answer}` }],
109						details: { question, suggestions, multiSelect: true, answer, selected },
110					};
111				}
112
113				// Multi-select: checkbox-style toggles using SettingsList
114				const selected = new Set<string>();
115
116				const result = await ctx.ui.custom<string[] | null>((tui, theme, _kb, done) => {
117					const container = new Container();
118
119					container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
120					container.addChild(new Text(theme.fg("accent", theme.bold(question)), 1, 0));
121					container.addChild(new Text(theme.fg("dim", "Space/Enter toggle • Tab confirm • Esc cancel"), 1, 0));
122
123					const items: SettingItem[] = suggestions.map((s) => ({
124						id: s,
125						label: s,
126						currentValue: "☐",
127						values: ["☐", "☑"],
128					}));
129
130					const settingsList = new SettingsList(
131						items,
132						Math.min(items.length + 2, 15),
133						getSettingsListTheme(),
134						(id, newValue) => {
135							if (newValue === "☑") {
136								selected.add(id);
137							} else {
138								selected.delete(id);
139							}
140						},
141						() => done(null), // Esc → cancel
142					);
143					container.addChild(settingsList);
144
145					container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
146
147					return {
148						render: (w) => container.render(w),
149						invalidate: () => container.invalidate(),
150						handleInput: (data) => {
151							// Tab = confirm selections
152							if (data === "\t") {
153								done(Array.from(selected));
154								return;
155							}
156							settingsList.handleInput(data);
157							tui.requestRender();
158						},
159					};
160				});
161
162				if (result === null || result.length === 0) {
163					return {
164						content: [{ type: "text", text: "User cancelled — did not select any options." }],
165						details: { question, suggestions, multiSelect: true, answer: null, selected: [] },
166					};
167				}
168
169				answer = result.join(", ");
170				return {
171					content: [{ type: "text", text: `User selected: ${answer}` }],
172					details: { question, suggestions, multiSelect: true, answer, selected: result },
173				};
174			} else if (hasSuggestions) {
175				// Single-select: show suggestions as selectable options + free-form input
176				const freeFormOption = "✎ Type a different answer…";
177				const options = [...suggestions, freeFormOption];
178				const choice = await ctx.ui.select(question, options);
179
180				if (choice === undefined) {
181					return {
182						content: [{ type: "text", text: "User cancelled — did not answer the question." }],
183						details: { question, suggestions, answer: null },
184					};
185				}
186
187				if (choice === freeFormOption) {
188					answer = await ctx.ui.input(question);
189				} else {
190					answer = choice;
191				}
192			} else {
193				// Free-form text input
194				answer = await ctx.ui.input(question);
195			}
196
197			if (answer === undefined || answer.trim() === "") {
198				return {
199					content: [{ type: "text", text: "User cancelled — did not answer the question." }],
200					details: { question, suggestions, answer: null },
201				};
202			}
203
204			return {
205				content: [{ type: "text", text: `User answered: ${answer}` }],
206				details: { question, suggestions, answer },
207			};
208			} finally {
209				release();
210			}
211		},
212	});
213}