import { Type } from "@sinclair/typebox"; import { Text } from "@earendil-works/pi-tui"; import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { bbForms, encodeQuestions, type FormAnswer, type FormValue } from "../bb-forms.js"; import { detectHost, fitLine } from "../host.js"; import { askQuestion, formatOptionList, formatResponse, isCancel, isNavigate, normalizeOptions, reviewAnswers, type AskResponse, type CancelReason, type QuestionOption } from "./ui.js"; import { ANSWER_TYPE, NOT_SHOWN_AFTER_RUN, questionTitle, type Answer, type PendingQuestions } from "./deferred.js"; import { renderConfirmOutcome } from "./confirm.js"; export { askUser, isCancel, type AskCancel, type AskResponse, type CancelReason, type QuestionOption } from "./ui.js"; type AskStatus = "registered" | "answered" | "cancelled" | "unattended" | "typing_unavailable" | "incomplete"; interface AskToolDetails { question: string; header?: string; options: QuestionOption[]; recommended?: string; response: AskResponse | null; cancelled: boolean; cancelReason?: CancelReason; cancelNote?: string; status?: AskStatus; // With `questions`: per-question outcomes in order; the top-level fields then describe the last one asked. answers?: AskToolDetails[]; } interface AskItem { question: string; header?: string; options?: QuestionOption[]; recommended?: string; allowMultiple?: boolean; allowFreeform?: boolean; allowComment?: boolean; } interface AskParams extends Partial { questions?: AskItem[]; } const DESCRIPTION = "Ask the user one focused question with optional multiple-choice answers — or several related questions via `questions`, presented one by one — at the end of this turn. The call does not wait: it registers the question and returns at once. Then write your final message, with the substantive context, reasoning and findings the question needs, in full markdown, and end the turn without calling another tool; the question opens under that message and the answer arrives as the next message. Text written before the call may never reach the user, so that final message must stand on its own. NEVER bundle multiple decisions into a single question's text or options; use `questions` for a sequence instead. Keep each `question` short — two or three lines at most. A question offers no options at all (a free-text answer) or at least two distinct ones. Never add an option that only declines (\"cancel\", \"no\", \"skip\") — every dialog has its own Cancel — nor one that says the user will type their own answer: the built-in \"Other…\" entry covers that. For a single yes/no decision, or to ask permission to go ahead, use confirm instead."; const PROMPT_SNIPPET = "Ask the user one short, focused question with optional multiple-choice answers to gather information interactively"; const PROMPT_GUIDELINES = [ "Keep the `question` field short — two or three lines at most. The user reads the substance in your final message, shown right above the dialog.", "After ask_user returns, write the substantive context as your final message and end the turn: the question and options are intentionally terse, so that message must make them interpretable. A question with no message above it reaches the user as a bare demand for approval. Call no other tool after ask_user; they are blocked until the user answers.", "Give each question a `header` of one to three words, and mark the option you would pick yourself as `recommended` when you have a reasoned preference.", "If the user answers with a question or an objection instead of picking an option, that is not a vote: answer it in a message and end the turn there. Do not re-ask, do not reword the options, and never put the answer in the next `question` field.", "Use ask_user when the user's intent is ambiguous, when a decision requires explicit user input, or when multiple valid options exist. Use confirm for a plain yes/no or go-ahead decision.", "Each question must carry exactly one decision. For several related decisions, pass them as the `questions` array (asked one by one) instead of merging them into one prompt or spawning separate calls.", ]; const optionSchema = Type.Union([ Type.String({ description: "Short title for this option" }), Type.Object({ title: Type.String({ description: "Short title for this option" }), description: Type.Optional(Type.String({ description: "One line explaining this option" })), }), ]); const itemFields = { header: Type.Optional(Type.String({ description: "One to three words naming the decision, shown as the dialog's label" })), options: Type.Optional(Type.Array(optionSchema, { description: "Choices for the user; none for a free-text answer, otherwise at least two" })), recommended: Type.Optional(Type.String({ description: "Title of the option you recommend; focused first and marked" })), allowMultiple: Type.Optional(Type.Boolean({ description: "Allow selecting multiple options. Default: false" })), allowFreeform: Type.Optional(Type.Boolean({ description: "Offer an \"Other…\" entry for a typed answer. Default: true" })), allowComment: Type.Optional(Type.Boolean({ description: "Invite an optional comment on the chosen option. Default: the user can add one in the terminal only" })), }; const PARAMETERS = Type.Object({ question: Type.Optional(Type.String({ description: "The question to ask the user. Keep it short — two or three lines at most. Put detail and reasoning in your final message, not here. Omit when using `questions`." })), questions: Type.Optional(Type.Array( Type.Object({ question: Type.String({ description: "One short, focused question — exactly one decision." }), ...itemFields }), { description: "Several related questions asked one by one, each with its own options. Use INSTEAD of `question` for multi-decision asks." }, )), ...itemFields, }); const DECLINE_ONLY = /^(no|nope|cancel|skip|none|abort|stop|decline|nothing|не надо|нет|отмена|отменить|пропустить)\.?$/i; // Runs before schema validation, so salvaged options and the `multiSelect` alias pass it. function prepareItem(raw: Record): Record { const { multiSelect, context: _context, ...item } = raw; if (Array.isArray(item.options)) item.options = normalizeOptions(item.options); if (item.allowMultiple === undefined && typeof multiSelect === "boolean") item.allowMultiple = multiSelect; return item; } function prepareArguments(args: unknown): any { if (!args || typeof args !== "object") return args; const prepared = prepareItem(args as Record); if (Array.isArray(prepared.questions)) { prepared.questions = prepared.questions.map((item: unknown) => (item && typeof item === "object" ? prepareItem(item as Record) : item)); } return prepared; } /** Why a question cannot be put to the user as written, phrased for the model to fix it. */ function problemWith(item: AskItem, label: string): string | undefined { if (!item.question?.trim()) return `${label} has no text.`; const options = normalizeOptions(item.options ?? []); if (options.length === 1) return `${label} offers one option; one option is not a choice. Offer at least two, or none for a free-text answer.`; const seen = new Set(); for (const option of options) { const key = option.title.trim().toLowerCase(); if (seen.has(key)) return `${label} offers "${option.title}" twice; make every option distinct.`; seen.add(key); } const decline = options.find((option) => DECLINE_ONLY.test(option.title.trim())); if (decline) return `${label} offers "${decline.title}", which only declines; every dialog has its own Cancel. For a yes/no decision use confirm.`; if (item.recommended && !options.some((option) => option.title === item.recommended)) return `${label}'s recommended "${item.recommended}" is not one of its options.`; return undefined; } const text = (value: string) => [{ type: "text" as const, text: value }]; function describe(item: AskItem): Pick { return { question: item.question, header: item.header?.trim() || undefined, options: normalizeOptions(item.options ?? []), ...(item.recommended ? { recommended: item.recommended } : {}) }; } function outcomeText(details: AskToolDetails, prefix = ""): string { if (details.response) return `${prefix}${formatResponse(details.response)}`; if (details.status === "typing_unavailable") return `${prefix}(not answered: this host cannot collect typed text)`; if (details.status === "incomplete") return `${prefix}(not answered: the dialog kept returning the same choice${details.cancelNote ? `; unconfirmed: ${details.cancelNote}` : ""})`; return `${prefix}(cancelled${details.cancelNote ? `: "${details.cancelNote}"` : ""})`; } const CANCELLED_GUIDANCE = "Do not ask it again; propose a different approach in prose or ask what they want instead."; const NO_TEXT_GUIDANCE = "This host cannot collect typed answers. Ask the question in plain prose in your reply and end the turn; do not call ask_user for it again."; const INCOMPLETE_GUIDANCE = "The host could not complete the selection. Ask the question in plain prose in your reply and end the turn."; function cancelledResult(shown: AskToolDetails, multi: boolean, answers: AskToolDetails[], index: number, total: number) { const status = shown.status!; const guidance = status === "typing_unavailable" ? NO_TEXT_GUIDANCE : status === "incomplete" ? INCOMPLETE_GUIDANCE : CANCELLED_GUIDANCE; // An incomplete answer's note is the unconfirmed selection, already in the headline. const reason = shown.cancelNote && status === "cancelled" ? ` Their reason: "${shown.cancelNote}".` : ""; const headline = status === "cancelled" ? "User cancelled the question." : `Not answered ${outcomeText(shown).slice("(not answered".length).replace(/\)$/, "").replace(/^: /, "— ")}.`; if (!multi) return { content: text(`${headline}${reason} ${guidance}`), details: shown }; const done = answers.slice(0, index).filter((answer) => answer.response); const summary = done.map((answer, i) => `${i + 1}. ${answer.question}: ${outcomeText(answer)}`).join("\n"); return { content: text(`Stopped at question ${index + 1}/${total}: ${outcomeText(shown)}.${reason} ${guidance}${summary ? `\nAnswered before stopping (not submitted as a batch):\n${summary}` : ""}`), details: { ...shown, answers }, }; } const REGISTERED = "Registered: the question opens for the user when this turn ends, under your final message. Write that message now — everything the user needs to decide: what you found, the options, your recommendation — in full markdown, and end the turn. Call no tool: they are blocked until the user answers, and the answer arrives as the next message. Text you wrote before this call may not have reached the user, so the final message must stand on its own."; export function registerAskUser(pi: ExtensionAPI, questions: PendingQuestions): void { const renderAnswer = (message: any, { expanded }: { expanded: boolean }, theme: any) => { const details = message.details; if (details?.error) return new Text(theme.fg("warning", `✗ ${details.error}`), 0, 0); if (details?.tool === "confirm") return renderConfirmOutcome(details, theme); if (details?.tool === "ask_user") return renderAskOutcome(details, expanded, theme); return undefined; }; pi.registerMessageRenderer?.(ANSWER_TYPE, renderAnswer); pi.registerTool({ name: "ask_user", label: "Ask User", description: DESCRIPTION, promptSnippet: PROMPT_SNIPPET, promptGuidelines: PROMPT_GUIDELINES, // Registered before the turn's later calls run, so the guard holds them back until the user has answered. executionMode: "sequential", parameters: PARAMETERS, prepareArguments, async execute(_id, raw, _signal, _onUpdate, ctx) { const params = raw as AskParams; const multi = params.questions?.length ? params.questions : undefined; if (!params.question && !multi) { return { content: text("ask_user requires `question` or a non-empty `questions` array"), isError: true, details: { error: "missing question" } }; } if (params.question && multi) { return { content: text("Use either `question` or `questions`, not both"), isError: true, details: { error: "ambiguous question input" } }; } const items: AskItem[] = multi ?? [params as AskItem]; const problem = items.map((item, i) => problemWith(item, multi ? `Question ${i + 1}` : "The question")).find(Boolean); if (problem) return { content: text(`${problem} Nothing was shown to the user; fix the call and ask again.`), isError: true, details: { error: problem } }; if (!ctx.hasUI || !ctx.ui) return unattended(items, !!multi); const title = questionTitle(multi ? multi.map((item) => item.question).join(" / ") : items[0]!.question); const registered = questions.register({ tool: "ask_user", title, form: "ask", present: (target, signal, afterRun) => present(target, params, items, multi, signal, afterRun) }); if (!registered) { return { content: text("Not asked: another question is already waiting for the user. End the turn, and ask this one after their answer."), isError: true, details: { error: "a question is already registered" } }; } const details: AskToolDetails = { ...describe(items[0]!), response: null, cancelled: false, status: "registered", ...(multi ? { answers: items.map((item) => ({ ...describe(item), response: null, cancelled: false, status: "registered" as const })) } : {}) }; return { content: text(REGISTERED), details }; }, renderCall(args: any, theme) { const questions: any[] = Array.isArray(args.questions) ? args.questions : []; const label = questions.length ? `${questions.length} questions` : args.header || args.question || ""; return new Text(theme.fg("toolTitle", theme.bold("ask_user ")) + theme.fg("muted", label), 0, 0); }, renderResult(result, options, theme) { const details = result.details as (AskToolDetails & { error?: string }) | undefined; if (details?.error) return new Text(theme.fg("error", `✗ ${details.error}`), 0, 0); if (!details) return new Text(theme.fg("warning", "✗ cancelled"), 0, 0); if (details.status === "registered") return new Text(theme.fg("muted", "asked when the turn ends"), 0, 0); return renderAskOutcome(details, options.expanded, theme); }, }); } /** Every answer on a line of its own; with one question, expanded, its options with the chosen ones marked. */ function renderAskOutcome(details: AskToolDetails, expanded: boolean, theme: any): Text { const line = (answer: AskToolDetails) => { const subject = theme.fg("muted", fitLine(answer.header || answer.question, 60)); if (!answer.response) return `${theme.fg("warning", "✗")} ${subject} ${theme.fg("warning", outcomeText(answer).replace(/^\(|\)$/g, ""))}`; const r = answer.response; const value = r.kind === "freeform" ? `“${r.text}”` : [...r.selections, ...(r.other ? [`“${r.other}”`] : [])].join(", "); const comment = r.kind === "selection" && r.comment ? theme.fg("muted", ` “${r.comment}”`) : ""; return `${theme.fg("success", "✓")} ${subject} ${theme.fg("dim", "→")} ${theme.fg("accent", value)}${comment}`; }; const all = details.answers?.length ? details.answers : [details]; let out = all.map(line).join("\n"); if (expanded && all.length === 1 && details.options.length) { const chosen = new Set(details.response?.kind === "selection" ? details.response.selections : []); for (const option of details.options) { const marker = chosen.has(option.title) ? theme.fg("success", "●") : theme.fg("dim", "○"); out += `\n ${marker} ${theme.fg("dim", option.title)}${theme.fg("dim", option.description ? ` — ${option.description}` : "")}`; } } return new Text(out, 0, 0); } type AskResult = { content: Array<{ type: "text"; text: string }>; details: AskToolDetails }; /** * The answer to deliver. A form or a dialog the user only dismissed, with no * reason and nothing typed, has nothing to act on: it waits for their next message. */ function toAnswer(result: AskResult, typed = false): Answer { const all = result.details.answers?.length ? result.details.answers : [result.details]; const dismissed = all.every((answer) => !answer.response && answer.status === "cancelled" && answer.cancelReason === "user" && !answer.cancelNote); return { text: result.content[0]!.text, details: result.details as unknown as Record, wake: typed || !dismissed }; } /** Puts registered questions to the user: pi-pi's bb form, the terminal's own component, or the host's dialogs. */ async function present(ctx: any, params: AskParams, items: AskItem[], multi: AskItem[] | undefined, signal: AbortSignal, afterRun: boolean): Promise { const terminal = ctx.mode === undefined || ctx.mode === "tui"; const viaForm = terminal ? undefined : await askViaBbForm(ctx, items, !!multi, signal, afterRun); if (viaForm) return viaForm; if (afterRun) return { text: NOT_SHOWN_AFTER_RUN, details: { error: "not shown" }, wake: false }; const answers: AskToolDetails[] = []; let index = 0; // Set while one answer is being changed from the review: back to the review after it. let revising = false; while (index <= items.length) { if (index === items.length) { if (!multi || terminal) break; const verdict = await reviewAnswers(ctx as any, answers.map((answer) => `${fitLine(answer.question, 60)}: ${outcomeText(answer)}`), signal); if (signal.aborted || verdict === undefined) { const summary = answers.map((answer, i) => `${i + 1}. ${answer.question}: ${outcomeText(answer)}`).join("\n"); const details: AskToolDetails = { ...answers[answers.length - 1]!, response: null, cancelled: true, cancelReason: signal.aborted ? "signal" : "user", status: "cancelled", answers }; return toAnswer({ content: text(`User dismissed the final review; the answers were not submitted. ${CANCELLED_GUIDANCE}\nAnswers given before that:\n${summary}`), details }); } if (verdict === "submit") break; index = verdict; revising = true; continue; } const item = items[index]!; const shown = describe(item); const previous = answers[index]?.response; const picked = previous?.kind === "selection" ? previous.selections.map((title) => shown.options.findIndex((o) => o.title === title)).filter((i) => i >= 0) : []; const result = await askQuestion(ctx as any, { ...item, options: shown.options, signal, declineNote: true, paseoCombined: paseoCombines(params, item, multi), ...(multi && { // Forward only from an answered question, so none can be skipped. navigation: { index, total: items.length, canPrev: index > 0, canNext: index < items.length - 1 && previous != null }, ...(picked.length ? { initialIndex: picked[0], checkedIndices: picked } : {}), }), }); if (isNavigate(result)) { index += result.__navigate === "prev" ? -1 : 1; revising = false; continue; } if (result === null || isCancel(result)) { const reason = isCancel(result) ? result.reason : "user"; const status: AskStatus = reason === "no_text" ? "typing_unavailable" : reason === "incomplete" ? "incomplete" : "cancelled"; const cancelled: AskToolDetails = { ...shown, response: null, cancelled: true, cancelReason: reason, status, ...(isCancel(result) && result.note ? { cancelNote: result.note } : {}) }; answers[index] = cancelled; return toAnswer(cancelledResult(cancelled, !!multi, answers, index, items.length)); } answers[index] = { ...shown, response: result, cancelled: false, status: "answered" }; index = revising ? items.length : index + 1; revising = false; } if (!multi) return toAnswer({ content: text(`User answered: ${formatResponse(answers[0]!.response!)}`), details: answers[0]! }); const summary = answers.map((answer, i) => `${i + 1}. ${answer.question}: ${formatResponse(answer.response!)}`).join("\n"); return toAnswer({ content: text(`User answered:\n${summary}`), details: { ...answers[answers.length - 1]!, answers } }); } /** * Under bb with pi-pi's plugin: every question in one form. Undefined when no * form could be shown, and the stock dialogs ask instead. */ async function askViaBbForm(ctx: any, items: AskItem[], multi: boolean, signal: AbortSignal, afterRun: boolean): Promise { const forms = detectHost(ctx.mode).id === "bb" ? bbForms() : null; if (!forms) return undefined; const shown = items.map(describe); const questions = items.map((item, i) => ({ question: item.question, ...(shown[i]!.header ? { header: shown[i]!.header } : {}), options: shown[i]!.options, ...(item.recommended ? { recommended: item.recommended } : {}), allowMultiple: item.allowMultiple === true, allowFreeform: item.allowFreeform !== false, allowComment: item.allowComment !== false, })); const encoded = encodeQuestions(questions); const outcome = await forms.ask({ version: 1, kind: "ask", questions: encoded.questions }, { title: fitLine(shown[0]!.header || (multi ? `${items.length} questions` : items[0]!.question), 160), signal, // Inside the run, a reply typed in the chat answers the form's first question; the rest stay unanswered. // After it, the reply is a prompt of its own and takes the form down. ...(afterRun ? {} : { onTyped: (typed: string): FormValue => ({ kind: "ask", answers: [{ kind: "freeform", text: typed }] }) }), }); if (outcome.outcome === "unavailable") return undefined; const also = outcome.alsoTyped ? `\nAfterwards, the user also wrote in the chat: "${outcome.alsoTyped}"` : ""; const withAlso = (result: ReturnType) => (also ? { ...result, content: text(`${result.content[0]!.text}${also}`) } : result); if (outcome.outcome === "cancelled" || outcome.value.kind === "decline") { const note = outcome.outcome === "submitted" && outcome.value.kind === "decline" ? outcome.value.note : undefined; // Anything but the user's own cancel or the tool's abort is bb taking the form down: not the user's choice. const reason: CancelReason = outcome.outcome === "submitted" || outcome.reason === "user" ? "user" : "signal"; const cancelled: AskToolDetails = { ...shown[0]!, response: null, cancelled: true, cancelReason: reason, status: "cancelled", ...(note ? { cancelNote: note } : {}) }; if (outcome.outcome === "cancelled" && outcome.reason !== "user" && outcome.reason !== "signal") { // After the run, bb takes a form down for the user's Stop, among others: nothing is to start on its own then. if (afterRun) return { text: `The question was not answered: bb took the form down (${outcome.reason}) after your turn had ended. Wait for the user's next message; do not ask it again unprompted.`, details: cancelled as unknown as Record, wake: false }; return toAnswer({ content: text(`The question was not answered: bb took the form down (${outcome.reason}). Ask it in plain prose in your reply and end the turn.`), details: cancelled }); } // The form is cancelled as a whole, so no question in it was answered. return toAnswer(multi ? { content: text(`User cancelled the form with all ${items.length} questions.${note ? ` Their reason: "${note}".` : ""} ${CANCELLED_GUIDANCE}${also}`), details: { ...cancelled, answers: shown.map((entry) => ({ ...entry, response: null, cancelled: true, cancelReason: reason, ...(note ? { cancelNote: note } : {}), status: "cancelled" as const })) } } : withAlso(cancelledResult(cancelled, false, [cancelled], 0, 1)), !!also); } if (outcome.value.kind !== "ask") return undefined; const given = encoded.decode(outcome.value.answers); const answers: AskToolDetails[] = shown.map((entry, i) => { const response = toResponse(given[i]); return response ? { ...entry, response, cancelled: false, status: "answered" } : { ...entry, response: null, cancelled: true, cancelReason: "user", status: "cancelled" }; }); if (!multi) { const only = answers[0]!; return toAnswer(only.response ? { content: text(`User answered: ${formatResponse(only.response)}${also}`), details: only } : withAlso(cancelledResult(only, false, [only], 0, 1)), !!also); } // A reply typed in the chat answers only the first; say which went unanswered rather than inventing answers. const summary = answers.map((answer, i) => `${i + 1}. ${answer.question}: ${outcomeText(answer)}`).join("\n"); const unanswered = answers.some((answer) => !answer.response); return toAnswer({ content: text(`User answered:\n${summary}${unanswered ? "\nThey replied in the chat instead of answering every question; ask the rest in prose if you still need them." : ""}${also}`), details: { ...answers[answers.length - 1]!, answers } }, !!also); } function toResponse(answer: FormAnswer | undefined): AskResponse | null { if (!answer) return null; if (answer.kind === "freeform") return answer.text.trim() ? { kind: "freeform", text: answer.text.trim() } : null; const selections = answer.selections.map((title) => title.trim()).filter(Boolean); const other = answer.other?.trim(); if (!selections.length && !other) return null; const comment = answer.comment?.trim(); return { kind: "selection", selections, ...(other ? { other } : {}), ...(comment ? { comment } : {}) }; } /** * Paseo answers an ask_user select with its own form, holding a custom answer * and a comment, whenever the call's top-level arguments ask for a comment * and not for several answers; it never looks inside `questions`. */ function paseoCombines(params: AskParams, _item: AskItem, _multi: AskItem[] | undefined): boolean { if (!process.env.PASEO_AGENT_ID) return false; return params.allowComment === true && params.allowMultiple !== true; } function unattended(items: AskItem[], multi: boolean) { const blocks = items.map((item, i) => { const shown = describe(item); const lines = [`${multi ? `${i + 1}) ` : ""}${shown.question}${item.allowMultiple ? " (several answers allowed)" : ""}`]; if (shown.options.length) lines.push(formatOptionList(shown.options, shown.recommended)); return lines.join("\n"); }); const recommended = items.map((item) => item.recommended).filter(Boolean); const advice = recommended.length === items.length ? "Take the recommended option for each, state that as your assumption, and continue." : "Choose the most reasonable answer for each, state it as your assumption, and continue."; const details: AskToolDetails = { ...describe(items[0]!), response: null, cancelled: true, status: "unattended", ...(multi ? { answers: items.map((item) => ({ ...describe(item), response: null, cancelled: true, status: "unattended" as const })) } : {}) }; return { content: text(`No user is available to answer (non-interactive run).\n\n${blocks.join("\n\n")}\n\n${advice}`), details }; } export { registerConfirm } from "./confirm.js";