import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@mariozechner/pi-coding-agent"; import type { ThinkingLevel } from "@mariozechner/pi-ai"; import type { ActiveRun, FinalizationResult, IterationRecord, StopReason } from "./types.js"; import { sendCompletionMessage, sendReviewStartMessage, setUltrathinkStatus } from "./ui.js"; type AssistantLike = { role: "assistant"; content: Array<{ type: string; text?: string }>; stopReason?: string; }; type UserLike = { role: "user"; content: string | Array<{ type: string; text?: string }>; }; type AgentMessageLike = { role: string; content?: unknown; stopReason?: string; }; type SessionMessageEntryLike = { type: "message"; id: string; message: AgentMessageLike; }; let configModulePromise: Promise | undefined; let gitModulePromise: Promise | undefined; let namingModulePromise: Promise | undefined; let promptEditorModulePromise: Promise | undefined; let reviewModulePromise: Promise | undefined; let stateModulePromise: Promise | undefined; let oracleModulePromise: Promise | undefined; let oracleSetupWidgetModulePromise: Promise | undefined; function loadConfigModule(): Promise { return (configModulePromise ??= import("./config.js")); } function loadGitModule(): Promise { return (gitModulePromise ??= import("./git.js")); } function loadNamingModule(): Promise { return (namingModulePromise ??= import("./naming.js")); } function loadPromptEditorModule(): Promise { return (promptEditorModulePromise ??= import("./promptEditor.js")); } function loadReviewModule(): Promise { return (reviewModulePromise ??= import("./review.js")); } function loadStateModule(): Promise { return (stateModulePromise ??= import("./state.js")); } function loadOracleModule(): Promise { return (oracleModulePromise ??= import("./oracle.js")); } function loadOracleSetupWidgetModule(): Promise { return (oracleSetupWidgetModulePromise ??= import("./oracleSetupWidget.js")); } function isAssistantMessage(message: AgentMessageLike): message is AssistantLike { return message.role === "assistant" && Array.isArray(message.content); } function isUserMessage(message: AgentMessageLike): message is UserLike { return message.role === "user"; } function getAssistantText(message: AssistantLike): string { return message.content .filter((block): block is { type: "text"; text: string } => block.type === "text" && typeof block.text === "string") .map((block) => block.text) .join("\n"); } function getPromptText(message: UserLike): string { if (typeof message.content === "string") { return message.content; } return message.content .filter((block): block is { type: "text"; text: string } => block.type === "text" && typeof block.text === "string") .map((block) => block.text) .join("\n"); } function getAgentPromptText(messages: AgentMessageLike[]): string | undefined { const userMessage = messages.find(isUserMessage); return userMessage ? getPromptText(userMessage) : undefined; } function getLastAssistant(messages: AgentMessageLike[]): AssistantLike | undefined { return [...messages].reverse().find(isAssistantMessage); } function getLeafAssistantEntryId(ctx: ExtensionContext): string | undefined { const leaf = ctx.sessionManager.getLeafEntry() as SessionMessageEntryLike | undefined; if (!leaf || leaf.type !== "message") return undefined; if (!isAssistantMessage(leaf.message)) return undefined; return leaf.id; } function isNormalCompletion(stopReason: StopReason): boolean { return stopReason === "no-git-changes" || stopReason === "max-iterations" || stopReason === "naming-error" || stopReason === "oracle-accepted" || stopReason === "oracle-max-rounds"; } function createPreservedFinalization(run: ActiveRun, stopReason: StopReason): FinalizationResult { return { mode: "preserved", success: false, scratchBranchDeleted: false, error: run.scratchBranchName ? `Automatic reintegration was skipped because the run ended with ${stopReason}; scratch branch ${run.scratchBranchName} was preserved.` : `Automatic reintegration was skipped because the run ended with ${stopReason}.`, }; } const DEFAULT_REVIEW_RUN_PROMPT_TEXT = "Review and improve the current branch changes"; export default function ultrathinkExtension(pi: ExtensionAPI): void { let activeRun: ActiveRun | undefined; function clearRunState(ctx: ExtensionContext): void { activeRun = undefined; setUltrathinkStatus(ctx, undefined); } async function finalizeRunIfNeeded(ctx: ExtensionContext, run: ActiveRun, stopReason: StopReason): Promise { if (!run.originalBranchName || !run.scratchBranchName) { return; } if (!isNormalCompletion(stopReason)) { run.finalization = createPreservedFinalization(run, stopReason); return; } try { const gitModule = await loadGitModule(); const actualCommitCount = await gitModule.countCommitsBetween({ exec: pi.exec, cwd: ctx.cwd, fromRef: run.originalBranchName, toRef: run.scratchBranchName, }); let mergeCommitMessage: | { subject: string; body: string; } | undefined; if (actualCommitCount > 1 && run.namingModel) { const namingModule = await loadNamingModule(); const branchDiff = await gitModule.describeCommitRange({ cwd: ctx.cwd, exec: pi.exec, fromRef: run.originalBranchName, toRef: run.scratchBranchName, }); const scratchCommits = await gitModule.listCommitDetailsBetween({ cwd: ctx.cwd, exec: pi.exec, fromRef: run.originalBranchName, toRef: run.scratchBranchName, }); mergeCommitMessage = await namingModule.generateMergeCommitMessage({ ctx, config: run.namingModel, promptText: run.originalPromptText, scratchBranchName: run.scratchBranchName, commits: scratchCommits, diffSummary: branchDiff.diffSummary, }); } run.finalization = await gitModule.finalizeScratchBranchRun({ cwd: ctx.cwd, exec: pi.exec, originalBranchName: run.originalBranchName, scratchBranchName: run.scratchBranchName, mergeCommitMessage, commitBodyMaxChars: run.commitBodyMaxChars, }); } catch (error) { run.finalization = { mode: "preserved", success: false, scratchBranchDeleted: false, error: error instanceof Error ? error.message : String(error), }; } } async function finishRun(ctx: ExtensionContext, stopReason: StopReason): Promise { const run = activeRun; if (!run) return; const lastIteration = run.iterations.at(-1); if (lastIteration && !lastIteration.stopReason) { lastIteration.stopReason = stopReason; } // Dispose oracle session if present if (run.mode === "oracle") { const { disposeOracle } = await loadOracleModule(); disposeOracle((run as any)._oracleSession); (run as any)._oracleSession = undefined; } if (run.mode === "git") { await finalizeRunIfNeeded(ctx, run, stopReason); } const { persistStop } = await loadStateModule(); persistStop(pi, run, stopReason); sendCompletionMessage(pi, { run, stopReason, iterations: run.iterations }); clearRunState(ctx); } async function startRun(promptText: string, ctx: ExtensionCommandContext): Promise { if (activeRun) { await finishRun(ctx, "cancelled-by-user"); } if (!ctx.isIdle()) { ctx.abort(); await ctx.waitForIdle(); } const promptEditorPromise = ctx.hasUI ? loadPromptEditorModule() : undefined; const [{ loadUltrathinkConfig }, gitModule, namingModule, stateModule] = await Promise.all([ loadConfigModule(), loadGitModule(), loadNamingModule(), loadStateModule(), ]); const config = await loadUltrathinkConfig(); const continuationPromptTemplate = promptEditorPromise ? await (await promptEditorPromise).promptForContinuationTemplate(ctx, config.continuationPromptTemplate) : config.continuationPromptTemplate; if (continuationPromptTemplate === null) { ctx.ui.notify("Ultrathink start cancelled.", "info"); return; } let namingModel; try { namingModel = await namingModule.ensureNamingModel(ctx, config); } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); return; } if (!namingModel) { ctx.ui.notify("Ultrathink start cancelled.", "info"); return; } const runId = stateModule.createRunId(); let gitSetup; try { gitSetup = await gitModule.prepareScratchBranchRun({ cwd: ctx.cwd, exec: pi.exec, generateBranchSlug: async (existingBranchNames) => await namingModule.generateBranchSlug({ ctx, config: namingModel, promptText, existingBranchNames: existingBranchNames.filter((branchName) => branchName.startsWith("ultrathink/")), }), }); } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); return; } activeRun = stateModule.createActiveRun({ mode: "git", gitRunKind: "task", runId, promptText, config, continuationPromptTemplate, namingModel, originalHeadSha: gitSetup.originalHeadSha, reviewBaseSha: gitSetup.originalHeadSha, originalBranchName: gitSetup.originalBranchName, scratchBranchName: gitSetup.scratchBranchName, }); activeRun.gitBaseline = gitSetup.baseline; stateModule.persistRunStart(pi, activeRun); setUltrathinkStatus(ctx, activeRun); pi.sendUserMessage(promptText); } pi.registerCommand("ultrathink", { description: "Run a prompt in an Ultrathink scratch branch and continue only while each iteration still changes git-tracked work", handler: async (args, ctx) => { const promptText = args.trim(); if (!promptText) { ctx.ui.notify("Usage: /ultrathink ", "warning"); return; } await startRun(promptText, ctx); }, }); async function startReviewRun(rawPromptText: string, ctx: ExtensionCommandContext): Promise { if (activeRun) { await finishRun(ctx, "cancelled-by-user"); } if (!ctx.isIdle()) { ctx.abort(); await ctx.waitForIdle(); } const [{ loadUltrathinkConfig }, gitModule, namingModule, reviewModule, stateModule] = await Promise.all([ loadConfigModule(), loadGitModule(), loadNamingModule(), loadReviewModule(), loadStateModule(), ]); const config = await loadUltrathinkConfig(); const trimmedPromptText = rawPromptText.trim(); const promptText = trimmedPromptText || DEFAULT_REVIEW_RUN_PROMPT_TEXT; const continuationPromptTemplate = trimmedPromptText || config.continuationPromptTemplate; let namingModel; try { namingModel = await namingModule.ensureNamingModel(ctx, config); } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); return; } if (!namingModel) { ctx.ui.notify("Ultrathink review start cancelled.", "info"); return; } const runId = stateModule.createRunId(); let reviewSetup; try { reviewSetup = await gitModule.prepareReviewRun({ cwd: ctx.cwd, exec: pi.exec, generateBranchSlug: async (existingBranchNames) => await namingModule.generateBranchSlug({ ctx, config: namingModel, promptText, existingBranchNames: existingBranchNames.filter((branchName) => branchName.startsWith("ultrathink/")), }), createBootstrapCommitMessage: async ({ changedFiles, diffSummary }) => await namingModule.generateBootstrapCommitMessage({ ctx, config: namingModel, promptText, changedFiles, diffSummary, }), commitBodyMaxChars: config.commitBodyMaxChars, }); } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); return; } const reviewPrompt = reviewModule.buildReviewPrompt({ kind: "review", template: continuationPromptTemplate, originalPromptText: promptText, reviewBaseSha: reviewSetup.reviewExclusiveBaseSha, }); activeRun = stateModule.createActiveRun({ mode: "git", gitRunKind: "review", runId, promptText, config, continuationPromptTemplate, namingModel, originalHeadSha: reviewSetup.originalHeadSha, reviewBaseSha: reviewSetup.reviewExclusiveBaseSha, reviewSource: reviewSetup.reviewSource, reviewStartSha: reviewSetup.reviewStartSha, reviewExclusiveBaseSha: reviewSetup.reviewExclusiveBaseSha, reviewCommits: reviewSetup.reviewCommits, seedScratchCommits: reviewSetup.seedScratchCommits, originalBranchName: reviewSetup.originalBranchName, scratchBranchName: reviewSetup.scratchBranchName, }); activeRun.gitBaseline = reviewSetup.baseline; activeRun.expectedPromptText = reviewPrompt; activeRun.awaitingExtensionFollowUp = true; stateModule.persistRunStart(pi, activeRun); setUltrathinkStatus(ctx, activeRun); sendReviewStartMessage(pi, { runId, originalBranchName: reviewSetup.originalBranchName, scratchBranchName: reviewSetup.scratchBranchName, reviewSource: reviewSetup.reviewSource, reviewStartSha: reviewSetup.reviewStartSha, reviewExclusiveBaseSha: reviewSetup.reviewExclusiveBaseSha, reviewCommits: reviewSetup.reviewCommits, }); pi.sendUserMessage(reviewPrompt); } pi.registerCommand("ultrathink-review", { description: "Review and improve the existing branch changes in an Ultrathink scratch branch", handler: async (args, ctx) => { await startReviewRun(args, ctx); }, }); // ------------------------------------------------------------------- // Oracle mode // ------------------------------------------------------------------- async function startOracleRun(promptText: string, ctx: ExtensionCommandContext): Promise { if (activeRun) { await finishRun(ctx, "cancelled-by-user"); } if (!ctx.isIdle()) { ctx.abort(); await ctx.waitForIdle(); } const [{ loadUltrathinkConfig }, stateModule, oracleModule, setupWidgetModule] = await Promise.all([ loadConfigModule(), loadStateModule(), loadOracleModule(), loadOracleSetupWidgetModule(), ]); const config = await loadUltrathinkConfig(); const oracleConfig = config.oracle ?? {}; const maxRounds = oracleConfig.maxRounds ?? 5; // Resolve default model for oracle const availableModels = ctx.modelRegistry.getAvailable(); if (availableModels.length === 0) { ctx.ui.notify("No models available. Check your API keys.", "error"); return; } let defaultModel = ctx.model ?? availableModels[0]; if (oracleConfig.provider && oracleConfig.modelId) { const configured = ctx.modelRegistry.find(oracleConfig.provider, oracleConfig.modelId); if (configured) defaultModel = configured; } const defaultThinkingLevel: ThinkingLevel = (oracleConfig.thinkingLevel as ThinkingLevel) ?? "high"; const defaultSystemPrompt = oracleConfig.systemPromptTemplate ?? oracleModule.DEFAULT_ORACLE_SYSTEM_PROMPT; // Show setup widget const setupResult = await setupWidgetModule.showOracleSetup(ctx, { models: availableModels, defaultModel, defaultThinkingLevel, defaultSystemPrompt, }); if (!setupResult) { ctx.ui.notify("Oracle run cancelled.", "info"); return; } // Create the oracle session let oracleSession: import("./oracle.js").OracleSession; try { oracleSession = await oracleModule.createOracleSession({ model: setupResult.model, thinkingLevel: setupResult.thinkingLevel, systemPrompt: setupResult.systemPrompt, cwd: ctx.cwd, }); } catch (error) { ctx.ui.notify(`Failed to create oracle session: ${error instanceof Error ? error.message : String(error)}`, "error"); return; } const runId = stateModule.createRunId(); activeRun = stateModule.createActiveRun({ mode: "oracle", runId, promptText, config, continuationPromptTemplate: "", oracleMaxRounds: maxRounds, }); (activeRun as any)._oracleSession = oracleSession; stateModule.persistRunStart(pi, activeRun); setUltrathinkStatus(ctx, activeRun); pi.sendUserMessage(promptText); } async function handleOracleAgentEnd(event: { messages: AgentMessageLike[] }, ctx: ExtensionContext): Promise { const run = activeRun; if (!run || run.mode !== "oracle") return; const oracleSession: import("./oracle.js").OracleSession | undefined = (run as any)._oracleSession; if (!oracleSession) { await finishRun(ctx, "cancelled-by-user"); return; } const assistantMessage = getLastAssistant(event.messages); if (!assistantMessage) return; if (assistantMessage.stopReason === "aborted") { await finishRun(ctx, "cancelled-by-interrupt"); return; } if (run.cancelRequested === "user") { await finishRun(ctx, "cancelled-by-user"); return; } const assistantText = getAssistantText(assistantMessage); run.oracleRound = (run.oracleRound ?? 0) + 1; const round = run.oracleRound; run.iteration = round; // Label the assistant entry const assistantEntryId = getLeafAssistantEntryId(ctx); if (assistantEntryId) { pi.setLabel(assistantEntryId, `ultrathink-oracle:v${round}`); } // Send agent's response to the oracle for review setUltrathinkStatus(ctx, run); const { sendToOracle } = await loadOracleModule(); let oracleResult: import("./oracle.js").OracleResult; try { const oraclePrompt = round === 1 ? `The user's task was:\n\n${run.originalPromptText}\n\nThe agent has completed its first pass. Here is its response:\n\n${assistantText}\n\nPlease review the work by examining the codebase with your tools. If the work is complete and correct, call oracle_accept. Otherwise, provide specific feedback.` : `The agent has responded to your feedback:\n\n${assistantText}\n\nPlease review again. If the work is now complete and correct, call oracle_accept. Otherwise, provide further feedback.`; oracleResult = await sendToOracle(oracleSession, oraclePrompt); } catch (error) { pi.sendMessage( { customType: "ultrathink-oracle-error", display: true, content: `Oracle error: ${error instanceof Error ? error.message : String(error)}` }, { triggerTurn: false }, ); await finishRun(ctx, "oracle-max-rounds"); return; } if (run.cancelRequested === "user") { await finishRun(ctx, "cancelled-by-user"); return; } if (oracleResult.accepted) { run.oracleAcceptSummary = oracleResult.acceptSummary; await finishRun(ctx, "oracle-accepted"); return; } // Check max rounds const maxRounds = run.oracleMaxRounds ?? 5; if (round >= maxRounds) { await finishRun(ctx, "oracle-max-rounds"); return; } // Send oracle feedback to the main agent as a visible user message const feedbackMessage = `🔮 **Oracle Review (round ${round}):**\n\n${oracleResult.responseText}`; run.awaitingExtensionFollowUp = true; run.expectedPromptText = feedbackMessage; setUltrathinkStatus(ctx, run); if (ctx.isIdle()) { pi.sendUserMessage(feedbackMessage); } else { pi.sendUserMessage(feedbackMessage, { deliverAs: "followUp" }); } } pi.registerCommand("ultrathink-oracle", { description: "Start an oracle-reviewed ultrathink session (no git required)", handler: async (args, ctx) => { const promptText = args.trim(); if (!promptText) { ctx.ui.notify("Usage: /ultrathink-oracle ", "warning"); return; } await startOracleRun(promptText, ctx); }, }); pi.on("session_start", async (_event, ctx) => { clearRunState(ctx); }); pi.on("input", async (event, ctx) => { if (!activeRun) { return { action: "continue" }; } if (event.source === "extension") { activeRun.awaitingExtensionFollowUp = false; return { action: "continue" }; } activeRun.cancelRequested = "user"; activeRun.awaitingExtensionFollowUp = false; if (ctx.isIdle()) { await finishRun(ctx, "cancelled-by-user"); } return { action: "continue" }; }); pi.on("agent_end", async (event, ctx) => { const run = activeRun; if (!run) return; if (run.mode === "oracle") { const promptText = getAgentPromptText(event.messages); if (!promptText || promptText !== run.expectedPromptText) { return; } await handleOracleAgentEnd(event, ctx); return; } // ── Git mode (unchanged) ── const promptText = getAgentPromptText(event.messages); if (!promptText || promptText !== run.expectedPromptText) { return; } const assistantMessage = getLastAssistant(event.messages); if (!assistantMessage) { return; } if (assistantMessage.stopReason === "aborted") { await finishRun(ctx, "cancelled-by-interrupt"); return; } const assistantText = getAssistantText(assistantMessage); const [reviewModule, gitModule, namingModule, stateModule] = await Promise.all([ loadReviewModule(), loadGitModule(), loadNamingModule(), loadStateModule(), ]); const { buildReviewPrompt, computeAnswerDigest, decideStop } = reviewModule; const { NO_REPOSITORY_CHANGES_NOTE, captureGitSnapshot, commitPreparedIteration, getHeadCommitInfo, prepareIterationCommit } = gitModule; const { persistIteration } = stateModule; const answerDigest = computeAnswerDigest(assistantText); const previousDigest = run.previousDigest; run.iteration += 1; run.previousDigest = answerDigest; let commitCreated = false; let commitSha: string | undefined; let commitParentSha: string | undefined; let commitSubject: string | undefined; let commitBody: string | undefined; let commitNote: string | undefined; let stopReason: StopReason | null = null; try { const pendingCommit = await prepareIterationCommit({ cwd: ctx.cwd, exec: pi.exec, baselineHead: run.gitBaseline?.head ?? undefined, }); if (pendingCommit.agentCommitted) { const headInfo = await getHeadCommitInfo({ exec: pi.exec, cwd: ctx.cwd }); commitCreated = true; commitSha = headInfo.sha; commitParentSha = headInfo.parentSha; commitSubject = headInfo.subject || `ultrathink iteration ${run.iteration}`; commitBody = headInfo.body || "Agent committed changes directly"; commitNote = "agent committed changes directly"; run.gitBaseline = await captureGitSnapshot(pi.exec, ctx.cwd); } else if (!pendingCommit.readyToCommit) { commitNote = pendingCommit.noCommitReason; } else { let namingFailed = false; let generatedSubject = `ultrathink iteration v${run.iteration}`; let generatedBody = `Automatic commit for iteration v${run.iteration}`; if (!run.namingModel) { namingFailed = true; commitNote = "Ultrathink naming model was unavailable; using fallback commit message"; } else { try { const generatedCommit = await namingModule.generateIterationCommitMessage({ ctx, config: run.namingModel, promptText: run.originalPromptText, iteration: run.iteration, assistantOutput: assistantText, diffSummary: pendingCommit.diffSummary, changedFiles: pendingCommit.changedFiles, }); generatedSubject = generatedCommit.subject; generatedBody = generatedCommit.body; } catch (namingError) { namingFailed = true; commitNote = `Naming model failed, using fallback message: ${namingError instanceof Error ? namingError.message : String(namingError)}`; } } try { const commitResult = await commitPreparedIteration({ cwd: ctx.cwd, subject: generatedSubject, body: generatedBody, commitBodyMaxChars: run.commitBodyMaxChars, exec: pi.exec, }); commitCreated = commitResult.commitCreated; commitSha = commitResult.commitSha; commitParentSha = commitResult.commitParentSha; commitSubject = commitResult.commitSubject; commitBody = commitResult.commitBody; if (!namingFailed) commitNote = commitResult.noCommitReason; run.gitBaseline = await captureGitSnapshot(pi.exec, ctx.cwd); } catch (gitError) { commitNote = gitError instanceof Error ? gitError.message : String(gitError); stopReason = "git-error"; } } } catch (error) { commitNote = error instanceof Error ? error.message : String(error); stopReason = "git-error"; } if (!stopReason) { if (run.cancelRequested === "user") { stopReason = "cancelled-by-user"; } else { stopReason = decideStop({ iteration: run.iteration, maxIterations: run.maxIterations, noGitChangesDetected: !commitCreated && commitNote === NO_REPOSITORY_CHANGES_NOTE, }); } } const record: IterationRecord = { iteration: run.iteration, label: `v${run.iteration}`, answerDigest, previousDigest, commitCreated, commitSha, commitParentSha, commitSubject, commitBody, commitNote, stopReason: stopReason ?? undefined, }; run.iterations.push(record); persistIteration(pi, run, record); const assistantEntryId = getLeafAssistantEntryId(ctx); if (assistantEntryId) { pi.setLabel(assistantEntryId, `ultrathink:${record.label}`); } if (stopReason) { await finishRun(ctx, stopReason); return; } if (!commitSha) { record.stopReason = "git-error"; await finishRun(ctx, "git-error"); return; } const reviewPrompt = buildReviewPrompt({ kind: run.gitRunKind === "review" ? "review" : "task", template: run.continuationPromptTemplate, originalPromptText: run.originalPromptText, reviewBaseSha: run.reviewBaseSha, }); run.awaitingExtensionFollowUp = true; run.expectedPromptText = reviewPrompt; setUltrathinkStatus(ctx, run); if (ctx.isIdle()) { pi.sendUserMessage(reviewPrompt); } else { pi.sendUserMessage(reviewPrompt, { deliverAs: "followUp" }); } }); }