import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { bbForms, type FormSpec } from "../bb-forms.js"; import { detectHost, fitLine } from "../host.js"; import { getLogger } from "../log.js"; /** * ask_user and confirm put their question to the user at the end of the turn, * not when they are called. Text a model writes between tool calls can come * back from the provider as a summarized thinking block, so an explanation * written before a blocking call often never reached the user; the turn's * final message always does. The call registers the question, the model * writes its explanation as that final message, and the question opens under * it. The answer comes back as a message of its own. */ /** The custom message that carries the user's answer to the model. */ export const ANSWER_TYPE = "pp-answer"; /** After the run only pi-pi's own form is known to show; bb's dialogs are not tried there. */ export const NOT_SHOWN_AFTER_RUN = "The question could not be shown: pi-pi's bb form was unavailable once your turn had ended. The user can still answer in the chat; wait for their next message."; export interface Answer { /** What the model reads; bb shows it in the chat as it is. */ text: string; /** Kept on the message for the terminal's renderer. */ details: Record; /** False when there is nothing to act on until the user writes: a bare dismissal, or a question bb took down. */ wake: boolean; } export interface Question { tool: "ask_user" | "confirm"; /** What the question asks, for the model when a tool is blocked on it. */ title: string; /** The plugin form that shows it under bb. */ form: FormSpec["kind"]; /** * Asks the user. `afterRun` when the run has already ended: a message the * user sends then is a new prompt for the agent, not an answer to the form. */ present(ctx: any, signal: AbortSignal, afterRun: boolean): Promise; } type AnswerMessage = { customType: string; content: string; display: boolean; details: Record }; export interface QuestionHost { send(message: AnswerMessage, options: { deliverAs?: "steer" | "followUp"; triggerTurn: boolean }): void; /** Tells the user something went wrong with their answer. */ warn(text: string): void; } /** How long a run started for an answer has to take it in before the answer is kept for the next one instead. */ export const ANSWER_START_MS = 10_000; /** How often an answer waiting for the session to be free to start a run checks again. */ const ANSWER_RETRY_MS = 250; export class PendingQuestions { private pending: { question: Question; ready: boolean; userQueued: boolean } | null = null; private showing: { controller: AbortController; afterRun: boolean } | null = null; /** An answer steered into a run that goes on with the user's own message first, until the model has it. */ private unseen: { question: Question; message: AnswerMessage; carried?: boolean } | null = null; /** An answer sent to start a run of its own, until the model has it; `runSeen` once a run started after it. */ private starting: { id: string; message: AnswerMessage; timer: ReturnType; runSeen: boolean } | null = null; private running = false; /** How the last turn ended, kept for its run's end. */ private lastStop: string | undefined; private generation = 0; private sequence = 0; private readonly listeners = new Set<(open: boolean) => void>(); constructor(private readonly host: QuestionHost) {} /** False while another question waits or is open: a turn ends on one question. */ register(question: Question): boolean { if (this.pending || this.showing) return false; this.pending = { question, ready: false, userQueued: false }; return true; } /** A question is registered and not shown yet: nothing else may run before the user answers. */ get waiting(): boolean { return this.pending !== null; } /** A question's dialog or form is up. */ get open(): boolean { return this.showing !== null; } /** Why a tool call is refused while a question waits; undefined when none does. */ blockReason(toolName: string): string | undefined { if (this.unseen) return `Not run: the user has answered your question ("${this.unseen.question.title}"), and the answer reaches you after their other message. Their answer: ${this.unseen.message.content}`; const question = this.pending?.question; if (!question) return undefined; if (toolName === "ask_user" || toolName === "confirm") { return `Not asked: a question ("${question.title}") is already registered for the end of this turn, and a turn ends on one question. Put several decisions in one ask_user call's \`questions\` array; ask this one after the answer.`; } return `A question for the user ("${question.title}") is registered for the end of this turn, so no tool runs until they answer. Write your final message now, with everything they need to decide, and end the turn.`; } /** Called with true when a question's dialog opens and false when it closes. */ subscribe(listener: (open: boolean) => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); } /** * A turn ended. True when it ended on a registered question, which then * owns the end of the run: no hold, no automatic continuation. */ async turnEnded(ctx: any, message: any): Promise { const pending = this.pending; if (!pending) return false; // Stopped by the user: they took the conversation back. if (message?.stopReason === "aborted") { this.pending = null; return false; } // A failed, cut-off or empty turn is recovered first: a question with no // explanation above it is what this exists to avoid. It waits for the turn that ends it. if (message?.stopReason !== "stop" || !hasText(message)) return false; const afterRun = await showsAfterRun(ctx, pending.question); // Asking the plugin takes a round trip, in which the session may have moved on or the user stopped the run. if (this.pending !== pending) return true; if (ctx?.signal?.aborted) { this.pending = null; return true; } // The user wrote while the explanation was coming: the run goes on with their message, and the question opens after it. // Workers' updates queued meanwhile do not hold it back. if (pending.userQueued && ctx?.hasPendingMessages?.()) { pending.userQueued = false; return true; } if (afterRun) { pending.ready = true; return true; } this.pending = null; await this.show(pending.question, ctx, ctx?.signal, false); return true; } /** The run settled: a question left for this moment opens now. */ settled(ctx: any): void { this.running = false; // A run ended without the answer it was to start with: pi did not start one on it. if (this.starting?.runSeen) this.notStarted(); // A stopped run that never took its steered answer in dropped it with pi's queue: it is kept for the next run. // Otherwise it may still be queued: pi hands queued steers to the next run before its first response. if (this.unseen && this.lastStop === "aborted") this.keepUnseen(); else if (this.unseen) this.unseen.carried = true; const pending = this.pending; if (!pending?.ready) return; this.pending = null; void this.show(pending.question, ctx, undefined, true); } /** * The user wrote something no form took as its answer. While the run is * still going it joins the run, and the question still opens after it. * Otherwise they moved on: a question not shown yet is not asked, one open * after the run is taken down, and their message is the reply. */ userWrote(streaming: boolean): void { if (this.showing?.afterRun) this.showing.controller.abort(); const pending = this.pending; if (!pending) return; if (streaming) { pending.userQueued = true; return; } this.pending = null; this.deliver(pending.question, { text: `Your question ("${pending.question.title}") was not shown: the user wrote before it opened, and their message is the reply.`, details: { error: "not asked: you wrote first" }, wake: false }, false, undefined); } /** A message entered the conversation: an answer in it has reached the model's context. */ messageStarted(message: any): void { // The next run is answering without the carried answer, which may not be queued after all: it is // steered in again, and tools stay held until one copy is in. A second copy is the price of not guessing. if (message?.role === "assistant" && this.unseen?.carried) this.steer(this.unseen.question, this.unseen.message); if (message?.role !== "custom" || message.customType !== ANSWER_TYPE) return; this.unseen = null; if (this.starting && message.details?.answerId === this.starting.id) { clearTimeout(this.starting.timer); this.starting = null; } } recordStop(message: any): void { this.lastStop = message?.stopReason; } runStarted(): void { this.running = true; // A run is under way: whether it holds the answer is known when it ends, however long its start takes. if (this.starting) { clearTimeout(this.starting.timer); this.starting.runSeen = true; } } /** The session is going away, or was replaced: nothing registered or open survives it. */ reset(): void { this.generation++; this.pending = null; this.unseen = null; this.running = false; if (this.starting) clearTimeout(this.starting.timer); this.starting = null; const showing = this.showing; if (!showing) return; this.showing = null; showing.controller.abort(); this.notify(false); } private async show(question: Question, ctx: any, runSignal: AbortSignal | undefined, afterRun: boolean): Promise { const controller = new AbortController(); const abort = () => controller.abort(); runSignal?.addEventListener("abort", abort, { once: true }); if (runSignal?.aborted) controller.abort(); const showing = { controller, afterRun }; this.showing = showing; this.notify(true); let answer: Answer; try { answer = await question.present(ctx, controller.signal, afterRun); } catch (error: any) { getLogger().warn({ s: "ask", tool: question.tool, err: error?.message }, "showing a question failed"); answer = { text: `The question could not be shown to the user (${error?.message ?? String(error)}). Ask it in plain prose in your reply and end the turn.`, details: { error: "not shown" }, wake: !afterRun }; } finally { runSignal?.removeEventListener("abort", abort); // A reset already closed it, and a newer question may own the dialog state by now. if (this.showing === showing) { this.showing = null; this.notify(false); } } // Aborted with the run or the session: whoever stopped it has the conversation now. if (controller.signal.aborted) return; // A message the user sent while the question was open keeps the run going. this.deliver(question, answer, afterRun, ctx, !afterRun && !!ctx?.hasPendingMessages?.()); } private deliver(question: Question, answer: Answer, afterRun: boolean, ctx: any, runGoesOn = false): void { const message: AnswerMessage = { customType: ANSWER_TYPE, content: answer.text, display: true, details: { tool: question.tool, ...answer.details } }; try { // A run that goes on reads only what is steered into it, one message a // request, the user's first: tools wait until the answer is in. After // the run, a run something else started meanwhile goes on the same way. if (runGoesOn) this.steer(question, message); // Into the conversation at once, so whatever runs next sees it, whoever starts that run. else if (!answer.wake) this.host.send(message, { triggerTurn: false }); else if (!afterRun) this.host.send(message, { deliverAs: "followUp", triggerTurn: true }); else this.startRun(question, message, ctx, this.generation); } catch (error: any) { getLogger().warn({ s: "ask", tool: question.tool, err: error?.message }, "delivering an answer failed"); } } /** * Starts a run with the answer once the session is free to: not while it * compacts. pi reports a run it could not start only to its log, so one that * has not taken the answer in soon after is given up on, and the answer is * kept for the user's next message instead. */ private startRun(question: Question, message: AnswerMessage, ctx: any, generation: number): void { if (generation !== this.generation) return; // A run something else started meanwhile (a worker's update) goes on with the answer instead. if (this.running) { this.steer(question, message); return; } if (typeof ctx?.isIdle === "function" && !ctx.isIdle()) { setTimeout(() => this.startRun(question, message, ctx, generation), ANSWER_RETRY_MS).unref?.(); return; } const id = `a${++this.sequence}`; const timer = setTimeout(() => { if (this.starting?.id === id && !this.starting.runSeen) this.notStarted(); }, ANSWER_START_MS); timer.unref?.(); this.starting = { id, message, timer, runSeen: false }; this.host.send({ ...message, details: { ...message.details, answerId: id } }, { triggerTurn: true }); } /** An answer pi dropped from its queue goes into the conversation as it is. */ private keepUnseen(): void { const dropped = this.unseen; this.unseen = null; if (!dropped) return; try { this.host.send(dropped.message, { triggerTurn: false }); } catch {} } /** pi reports a run it could not start only to its log: the answer is kept for the next message, and the user told. */ private notStarted(): void { const starting = this.starting; if (!starting) return; clearTimeout(starting.timer); this.starting = null; getLogger().warn({ s: "ask" }, "the run for an answer did not start; keeping the answer for the next message"); try { this.host.send(starting.message, { triggerTurn: false }); } catch {} this.host.warn("pi did not start the agent on your answer. It is kept in the conversation: send a message to continue."); } /** * Into a run that goes on: it reads only what is steered into it, one * message a request, so tools wait until the answer is in. */ private steer(question: Question, message: AnswerMessage): void { this.unseen = { question, message }; this.host.send(message, { deliverAs: "steer", triggerTurn: true }); } private notify(open: boolean): void { for (const listener of this.listeners) { try { listener(open); } catch {} } } } function hasText(message: any): boolean { return Array.isArray(message?.content) && message.content.some((part: any) => part?.type === "text" && typeof part.text === "string" && part.text.trim()); } /** The question's title as the model and the logs name it. */ export function questionTitle(text: string): string { return fitLine(text, 120); } /** * bb draws a turn's final message only once the run has ended, so a question * asked inside the run would sit under an explanation nobody can see yet; * there pi-pi's plugin shows it after the run instead. Everywhere else, and * under bb without the plugin, it is asked before the run ends, where every * host shows its dialogs. */ async function showsAfterRun(ctx: any, question: Question): Promise { if (detectHost(ctx?.mode).id !== "bb") return false; return (await bbForms()?.supports([question.form])) === true; } /** Blocks every tool while a question waits, and opens or drops it as the run settles or the user writes. */ export function registerQuestionHooks(pi: ExtensionAPI, questions: PendingQuestions): void { pi.on("tool_call", async (event: any) => { const reason = questions.blockReason(String(event?.toolName ?? "")); return reason ? { block: true, reason } : undefined; }); pi.on("agent_start", async () => questions.runStarted()); pi.on("turn_end", async (event: any) => questions.recordStop(event?.message)); pi.on("agent_settled", async (_event, ctx) => questions.settled(ctx)); pi.on("message_start", async (event: any) => questions.messageStarted(event?.message)); pi.on("input", async (event: any, ctx: any) => { // pi-pi's own continuations are not the user moving on. if (event?.source !== "extension") questions.userWrote(typeof ctx?.isIdle === "function" ? !ctx.isIdle() : event?.streamingBehavior !== undefined); return { action: "continue" as const }; }); pi.on("session_start", async () => questions.reset()); pi.on("session_shutdown", async () => questions.reset()); }