/** * Devil's Advocate Extension for Pi * * A structured debate tool for stress-testing ideas against a devil's advocate. * Designed to reduce sycophancy by forcing critical examination. * * Usage: * /devil - Start an interactive debate with live progress * Call devil tool - Non-interactive debate (for LLM use) * * Configuration (settings.json): * { * "devil": { * "model": "zai/glm-5.1", // Optional: specific model * "maxRounds": 5, // Maximum debate rounds * "stoppingConditions": "consensus", // consensus | blocking_found | max_rounds * "concessionThreshold": 0.7, // 0.0-1.0 for concession detection * "onBlocking": "surface" // surface | escalate | ignore * } * } */ import { Type } from "typebox"; import * as fs from "node:fs"; import * as path from "node:path"; import { complete, StringEnum } from "@mariozechner/pi-ai"; import { convertToLlm, serializeConversation, } from "@mariozechner/pi-coding-agent"; import type { ExtensionAPI, ExtensionContext, Model, SessionEntry, } from "@mariozechner/pi-coding-agent"; import { Key, Text, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type TUI, } from "@mariozechner/pi-tui"; import type { DebateOutput } from "./types"; const DEVIL_SYSTEM_PROMPT = `Devil advocate. STRESS TEST ideas. Find blocking issues. CLASSIFICATION: - **blocking**: Prevents idea working. Must fix before proceeding. - **addressable**: Valid concern. Has mitigations. - **assumed**: Premise may not hold. - **minor**: Cosmetic. No functional impact. RULES: 1. Lead with blocking. Skip minor issues. 2. Name exact failure modes. No vague risks. 3. Acknowledge successful defenses. 4. Focus on what BREAKS the idea. 5. Do NOT repeat concerns already raised in previous rounds. 6. ESCALATE: if a previous concern was partially addressed, find the deeper issue. 7. If all previous concerns were resolved, concede and say "No new blocking concerns." FORMAT: ### [CLASSIFICATION] Title **Concern:** [problem] **Fix:** [what resolves it] **Status:** outstanding / resolved / retracted`; const PROPOSER_SYSTEM_PROMPT = `Present idea. DEFEND where valid. ACKNOWLEDGE weaknesses. RULES: 1. Don't capitulate easily. Require specific evidence. 2. Distinguish: "I don't know" vs "doesn't apply" vs "addressed that". 3. If concern valid → acknowledge + explain mitigation. 4. Never concede blocking issues without explaining fix. 5. Maintain consistency with your previous defenses. 6. If you previously conceded something, don't walk it back without new evidence. FOR EACH CHALLENGE: 1. **Defense**: What defeats/challenges it 2. **Concession** (if valid): What remains 3. **Status**: outstanding / resolved Be specific. "Addressed that" requires HOW.`; const SYNTHESIS_SYSTEM_PROMPT = `Analyze the full debate and produce a structured verdict. You MUST respond with ONLY a valid JSON object. No markdown, no explanation, no code fences. Just the raw JSON object, nothing else. JSON schema: { "recommendation": "proceed" | "proceed_with_caution" | "revise" | "abandon", "summary": "2-3 sentence overview of the debate outcome", "blocking": ["concern description → proposed fix"], "addressable": ["concern description → mitigation"], "survived": ["claims that withstood challenges"], "conceded": ["acknowledged weaknesses"], "next_steps": ["action item"] } Classification rules: - blocking: Must fix before proceeding - addressable: Has known mitigations - If no blocking issues remain and concerns were resolved: "proceed" - If blocking issues remain but have clear fixes: "revise" - If fundamental premise is destroyed: "abandon" - Otherwise: "proceed_with_caution"`; // Default settings const DEFAULT_MAX_ROUNDS = 5; const DEFAULT_STOPPING_CONDITIONS = "consensus"; const DEFAULT_CONCESSION_THRESHOLD = 0.7; const DEFAULT_ON_BLOCKING = "surface"; interface DevilSettings { model?: string; maxRounds?: number; stoppingConditions?: "consensus" | "blocking_found" | "max_rounds"; concessionThreshold?: number; onBlocking?: "surface" | "escalate" | "ignore"; } interface SynthesisResult { recommendation: "proceed" | "proceed_with_caution" | "revise" | "abandon"; summary: string; blocking: string[]; addressable: string[]; survived: string[]; conceded: string[]; next_steps: string[]; } interface RunDebateOptions { idea: string; context?: Record; model: Model; apiKey: string; headers?: Record; maxRounds: number; stoppingConditions: "consensus" | "blocking_found" | "max_rounds"; concessionThreshold: number; signal?: AbortSignal; onStatus?: (status: string, round: number, maxRounds: number, blocking: number) => void; /** Fires after devil responds, before proposer responds (mid-round update) */ onChallenge?: ( round: number, maxRounds: number, blocking: number, devilOutput: string, ) => void; /** Fires after both devil and proposer respond (round complete) */ onRound?: ( round: number, maxRounds: number, blocking: number, status: string, devilOutput: string, proposerOutput: string, ) => void; } type DebateRole = "devil" | "proposer"; interface DebateTranscriptEntry { role: DebateRole; round: number; text: string; blocking: number; } interface DebateLiveState { idea: string; maxRounds: number; status: string; currentRound: number; blocking: number; entries: DebateTranscriptEntry[]; startedAt: number; } // ── Helpers ─────────────────────────────────────────────────────────── const MAX_FILE_CHARS = 3000; // per-file cap for context injection const MAX_FILES = 10; // max files to include const FILE_TOOL_NAMES = new Set(["read", "edit", "write"]); interface ToolCallBlock { type: "toolCall"; name: string; arguments: Record; } export function createDebateState(idea: string, maxRounds: number): DebateLiveState { return { idea, maxRounds, status: "Starting debate...", currentRound: 0, blocking: 0, entries: [], startedAt: Date.now(), }; } function setDebateStatus( state: DebateLiveState, status: string, round: number, blocking: number, ) { state.status = status; state.currentRound = round; state.blocking = blocking; } function addDebateEntry( state: DebateLiveState, role: DebateRole, round: number, blocking: number, text: string, ) { state.currentRound = round; state.blocking = blocking; state.entries.push({ role, round, blocking, text }); } function cleanTranscriptText(text: string, maxChars: number): string { const clean = text.replace(/\r/g, "").replace(/\n{3,}/g, "\n\n").trim(); if (clean.length <= maxChars) return clean; return `${clean.slice(0, maxChars).trimEnd()}…`; } function padToWidth(line: string, width: number): string { const target = Math.max(0, width); const truncated = truncateToWidth(line, target); return truncated + " ".repeat(Math.max(0, target - visibleWidth(truncated))); } function frameLine(theme: Theme, left: string, content: string, right: string, width: number): string { if (width <= 0) return ""; if (width === 1) return truncateToWidth(theme.fg("border", left), width); const innerWidth = Math.max(0, width - 2); return truncateToWidth( theme.fg("border", left) + padToWidth(content, innerWidth) + theme.fg("border", right), width, ); } export function renderDebateTranscript( state: DebateLiveState, theme: Theme, width: number, options: { compact: boolean; maxBodyLines: number }, ): string[] { if (width <= 0) return [""]; const lines: string[] = []; const usableWidth = width; const elapsed = Math.floor((Date.now() - state.startedAt) / 1000); const header = `Review: ${state.status} · ${state.blocking} blocking · ${elapsed}s`; lines.push(theme.fg("accent", truncateToWidth(header, usableWidth))); const entries = options.compact ? state.entries.slice(-2) : state.entries; if (entries.length === 0) { lines.push(theme.fg("dim", truncateToWidth(" Waiting for first challenge...", usableWidth))); return lines.map((line) => truncateToWidth(line, usableWidth)); } for (const entry of entries) { const icon = entry.role === "devil" ? "⚑" : "✓"; const label = entry.role === "devil" ? "Devil" : "Defense"; lines.push(theme.fg(entry.role === "devil" ? "warning" : "success", truncateToWidth(`${icon} R${entry.round} ${label}`, usableWidth))); const bodyWidth = Math.max(1, usableWidth - 2); const body = cleanTranscriptText(entry.text, options.compact ? 700 : 20000); const wrapped = wrapTextWithAnsi(theme.fg("dim", body), bodyWidth).slice(0, options.maxBodyLines); for (const line of wrapped) lines.push(truncateToWidth(` ${line}`, usableWidth)); } return lines.map((line) => truncateToWidth(line, usableWidth)); } export class DebateWidget implements Component { constructor( private theme: Theme, private state: DebateLiveState, ) {} render(width: number): string[] { return renderDebateTranscript(this.state, this.theme, width, { compact: true, maxBodyLines: 3, }).slice(-9).map((line) => truncateToWidth(line, width)); } invalidate(): void {} } export class DebateReviewComponent implements Component { private scrollOffset = 0; private followMode = true; private finished = false; private disposed = false; private cachedBodyWidth?: number; private cachedBodyKey?: string; private cachedBody?: string[]; constructor( private tui: TUI, private theme: Theme, private state: DebateLiveState, private done: (output: DebateOutput | null) => void, private controller: AbortController, ) {} get signal(): AbortSignal { return this.controller.signal; } isActive(): boolean { return !this.finished && !this.disposed && !this.signal.aborted; } cancel() { this.controller.abort(); this.finish(null); } finish(output: DebateOutput | null) { if (this.finished || this.disposed) return; if (output === null) this.controller.abort(); this.finished = true; this.done(output); } refresh() { if (!this.isActive()) return; this.tui.requestRender(); } handleInput(data: string): void { if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || data === "q") { this.cancel(); return; } if (matchesKey(data, "up") || data === "k") { this.followMode = false; this.scrollOffset = Math.max(0, this.scrollOffset - 1); this.refresh(); return; } if (matchesKey(data, "down") || data === "j") { this.scrollOffset++; this.refresh(); return; } if (matchesKey(data, "pageup") || matchesKey(data, "ctrl+u")) { this.followMode = false; this.scrollOffset = Math.max(0, this.scrollOffset - 10); this.refresh(); return; } if (matchesKey(data, "pagedown") || matchesKey(data, "ctrl+d")) { this.scrollOffset += 10; this.refresh(); return; } if (data === "g") { this.followMode = false; this.scrollOffset = 0; this.refresh(); return; } if (data === "G") { this.followMode = true; this.scrollOffset = 999999; this.refresh(); } } private getBody(width: number): string[] { const key = [ this.state.status, this.state.currentRound, this.state.blocking, this.state.entries.length, ...this.state.entries.map((entry) => `${entry.role}:${entry.round}:${entry.blocking}:${entry.text.length}`), ].join("|"); if (this.cachedBody && this.cachedBodyWidth === width && this.cachedBodyKey === key) { return this.cachedBody; } this.cachedBodyWidth = width; this.cachedBodyKey = key; this.cachedBody = renderDebateTranscript(this.state, this.theme, width, { compact: false, maxBodyLines: 1000, }); return this.cachedBody; } render(width: number): string[] { if (width <= 0) return [""]; const innerWidth = Math.max(0, width - 2); const body = this.getBody(innerWidth); const maxVisible = Math.max(6, Math.min(24, this.tui.terminal.rows - 8)); const maxScroll = Math.max(0, body.length - maxVisible); if (this.followMode) this.scrollOffset = maxScroll; this.scrollOffset = Math.min(this.scrollOffset, maxScroll); const visible = body.slice(this.scrollOffset, this.scrollOffset + maxVisible); const title = ` Devil Review · ${this.state.currentRound}/${this.state.maxRounds} `; const top = this.theme.fg("accent", title) + this.theme.fg("border", "─".repeat(Math.max(0, innerWidth - visibleWidth(title)))); const lines = [frameLine(this.theme, "╭", top, "╮", width)]; for (const line of visible) { lines.push(frameLine(this.theme, "│", line, "│", width)); } const scrollInfo = body.length > maxVisible ? `${this.scrollOffset + 1}-${Math.min(this.scrollOffset + maxVisible, body.length)}/${body.length}` : `${body.length}L`; const follow = this.followMode ? "follow" : "paused"; const footer = this.theme.fg("dim", ` ${scrollInfo} · ${follow} · j/k scroll · g/G top/end · q cancel `); lines.push(frameLine(this.theme, "├", this.theme.fg("border", "─".repeat(innerWidth)), "┤", width)); lines.push(frameLine(this.theme, "│", footer, "│", width)); lines.push(frameLine(this.theme, "╰", this.theme.fg("border", "─".repeat(innerWidth)), "╯", width)); return lines.map((line) => truncateToWidth(line, width)); } invalidate(): void { this.cachedBody = undefined; this.cachedBodyWidth = undefined; this.cachedBodyKey = undefined; } dispose(): void { this.disposed = true; this.controller.abort(); } } function gatherContext(ctx: ExtensionContext): Record { const context: Record = {}; context["working_directory"] = ctx.cwd; const branch = ctx.sessionManager.getBranch(); // ── Part 1: Extract file paths from assistant toolCall blocks, read current contents ── // Tool arguments (file paths) live in assistant messages' content[type=toolCall].arguments // NOT in toolResult messages (those only have output text, no input). // Pattern from summarize.ts: scan assistant content for toolCall blocks. const filePaths = new Set(); for (const entry of branch) { if (entry.type !== "message") continue; const msg = entry.message; if (!msg || msg.role !== "assistant" || !Array.isArray(msg.content)) continue; for (const block of msg.content) { const tc = block as ToolCallBlock; if (tc.type !== "toolCall" || !FILE_TOOL_NAMES.has(tc.name)) continue; // read/edit/write all use "path" (edit may also have "file_path" in older sessions) const filePath = (tc.arguments.path ?? tc.arguments.file_path) as string | undefined; if (typeof filePath !== "string" || !filePath.trim()) continue; const resolved = path.resolve(ctx.cwd, filePath.trim()); try { if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) { filePaths.add(resolved); } } catch { // skip inaccessible files } } } if (filePaths.size > 0) { const files = [...filePaths].slice(0, MAX_FILES); const fileContents = files .map((fp) => { try { let content = fs.readFileSync(fp, "utf-8"); if (content.length > MAX_FILE_CHARS) { content = content.slice(0, MAX_FILE_CHARS) + "\n... (truncated)"; } const rel = path.relative(ctx.cwd, fp); return `### ${rel}\n\`\`\`\n${content}\n\`\`\``; } catch { return null; } }) .filter((c): c is string => c !== null); if (fileContents.length > 0) { context["relevant_files"] = fileContents.join("\n\n"); } } // ── Part 2: Recent conversation (last 20 messages) ── const messages = branch .filter( (entry): entry is SessionEntry & { type: "message" } => entry.type === "message", ) .map((entry) => entry.message); if (messages.length > 0) { const recent = messages.slice(-20); const llmMessages = convertToLlm(recent); context["conversation"] = serializeConversation(llmMessages); } return context; } /** Extract first meaningful line from devil's challenge for widget display */ function extractSnippet(text: string, maxLen = 60): string { const lines = text.split("\n").filter((l) => l.trim().length > 0); for (const line of lines) { const clean = line .replace(/^#{1,6}\s*/, "") .replace(/\*\*/g, "") .trim(); if ( clean.length > 5 && !clean.startsWith("Concern:") && !clean.startsWith("Fix:") && !clean.startsWith("Status:") ) { return clean.length > maxLen ? clean.slice(0, maxLen) + "…" : clean; } } return lines[0]?.slice(0, maxLen) ?? ""; } function formatSynthesis(s: SynthesisResult): string { const recEmoji: Record = { proceed: "✅", proceed_with_caution: "⚡", revise: "⚠️", abandon: "🚫", }; const emoji = recEmoji[s.recommendation] ?? "⚡"; let text = `## Verdict: ${s.recommendation.replace(/_/g, " ")} ${emoji}\n\n`; text += `${s.summary}\n`; if (s.blocking.length > 0) { text += `\n### Blocking Issues\n`; for (const b of s.blocking) text += `- ${b}\n`; } if (s.addressable.length > 0) { text += `\n### Addressable Concerns\n`; for (const a of s.addressable) text += `- ${a}\n`; } if (s.survived.length > 0) { text += `\n### Survived\n`; for (const c of s.survived) text += `- ${c}\n`; } if (s.conceded.length > 0) { text += `\n### Conceded\n`; for (const c of s.conceded) text += `- ${c}\n`; } if (s.next_steps.length > 0) { text += `\n### Next Steps\n`; for (const n of s.next_steps) text += `- ${n}\n`; } return text; } function resolveDebateModel( ctx: ExtensionContext, modelSetting?: string, ): Model | null { const current = ctx.model ?? null; if (modelSetting) { const [provider, modelId] = modelSetting.includes("/") ? modelSetting.split("/", 2) : [current?.provider, modelSetting]; if (provider) { const found = ctx.modelRegistry.find(provider, modelId); if (found) return found; } } return current; } function parseSynthesis(raw: string): SynthesisResult { // Try JSON parse first try { const jsonMatch = raw.match(/\{[\s\S]*\}/); if (jsonMatch) { const parsed = JSON.parse(jsonMatch[0]); return { recommendation: ["proceed", "proceed_with_caution", "revise", "abandon"].includes( parsed.recommendation, ) ? parsed.recommendation : "proceed_with_caution", summary: String(parsed.summary ?? ""), blocking: Array.isArray(parsed.blocking) ? parsed.blocking.map(String) : [], addressable: Array.isArray(parsed.addressable) ? parsed.addressable.map(String) : [], survived: Array.isArray(parsed.survived) ? parsed.survived.map(String) : [], conceded: Array.isArray(parsed.conceded) ? parsed.conceded.map(String) : [], next_steps: Array.isArray(parsed.next_steps) ? parsed.next_steps.map(String) : [], }; } } catch {} // Fallback: regex parse from markdown const recMatch = raw.match(/\*\*recommendation\*\*:\s*(\w+)/i); const rec = recMatch?.[1]?.toLowerCase(); return { recommendation: rec && ["proceed", "proceed_with_caution", "revise", "abandon"].includes(rec) ? (rec as SynthesisResult["recommendation"]) : "proceed_with_caution", summary: raw.slice(0, 200), blocking: [], addressable: [], survived: [], conceded: [], next_steps: [], }; } // ── Core debate logic ───────────────────────────────────────────────── async function runDebate(opts: RunDebateOptions): Promise { const { idea, context, model, apiKey, headers, maxRounds, stoppingConditions, concessionThreshold, signal, onStatus, onChallenge, onRound, } = opts; const contextText = context ? Object.entries(context) .map(([k, v]) => `- **${k}**: ${v}`) .join("\n") : "No additional context provided."; const roundsData: string[] = []; let blockingIssuesFound = 0; let consecutiveResolved = 0; let shouldContinue = true; let roundHistory = ""; // Accumulates for cross-round memory for (let i = 1; i <= maxRounds && shouldContinue; i++) { if (signal?.aborted) { return { synthesis: "Debate cancelled by user.", roundsData, recommendation: "proceed_with_caution", blockingRaised: blockingIssuesFound, blockingRemaining: blockingIssuesFound, aborted: true, }; } onStatus?.(`Round ${i}/${maxRounds} · devil challenging`, i, maxRounds, blockingIssuesFound); // ── Devil's challenge (sees full round history) ── const devilUserText = [ `Context:\n${contextText}`, `Idea: ${idea}`, roundHistory ? `Previous rounds:\n${roundHistory}` : "This is the first round.", `Round ${i}/${maxRounds}. Identify the most blocking concern not yet resolved.`, ].join("\n\n"); const devilResponse = await complete( model, { systemPrompt: DEVIL_SYSTEM_PROMPT, messages: [ { role: "user", content: [{ type: "text", text: devilUserText }], timestamp: Date.now(), }, ], }, { apiKey, headers, signal }, ); if (signal?.aborted) { return { synthesis: "Debate cancelled by user.", roundsData, recommendation: "proceed_with_caution", blockingRaised: blockingIssuesFound, blockingRemaining: blockingIssuesFound, aborted: true, }; } const devilOutput = devilResponse.content .filter((c): c is { type: "text"; text: string } => c.type === "text") .map((c) => c.text) .join("\n"); const roundBlockingCount = ( devilOutput.match(/^###\s+(?:\[?blocking\]?|\*\*blocking\*\*)\b/gim) || [] ).length; blockingIssuesFound += roundBlockingCount; // Mid-round update: devil has spoken, widget shows challenge onChallenge?.(i, maxRounds, blockingIssuesFound, devilOutput); onStatus?.(`Round ${i}/${maxRounds} · proposer defending`, i, maxRounds, blockingIssuesFound); // ── Proposer's rebuttal (sees full round history + current challenge) ── const proposerUserText = [ `Your idea: ${idea}`, roundHistory ? `Previous rounds:\n${roundHistory}` : "This is the first round.", `Current challenge (Round ${i}):`, devilOutput, "Respond to this challenge.", ].join("\n\n"); const proposerResponse = await complete( model, { systemPrompt: PROPOSER_SYSTEM_PROMPT, messages: [ { role: "user", content: [{ type: "text", text: proposerUserText }], timestamp: Date.now(), }, ], }, { apiKey, headers, signal }, ); if (signal?.aborted) { return { synthesis: "Debate cancelled by user.", roundsData, recommendation: "proceed_with_caution", blockingRaised: blockingIssuesFound, blockingRemaining: blockingIssuesFound, aborted: true, }; } const proposerOutput = proposerResponse.content .filter((c): c is { type: "text"; text: string } => c.type === "text") .map((c) => c.text) .join("\n"); roundsData.push( `### Round ${i}\n\n**Challenge:**\n${devilOutput}\n\n**Response:**\n${proposerOutput}`, ); // Append to round history for next iteration roundHistory += `### Round ${i}\n**Challenge:** ${devilOutput.slice(0, 500)}\n**Response:** ${proposerOutput.slice(0, 500)}\n\n`; // Round complete update const status = `Round ${i}/${maxRounds} · ${blockingIssuesFound} blocking raised`; onRound?.(i, maxRounds, blockingIssuesFound, status, devilOutput, proposerOutput); // Check stopping conditions const resolvedCount = ( proposerOutput.match( /\*\*status\*\*:\s*resolved|status:\s*resolved/gi, ) || [] ).length; const concessionIndicators = ( proposerOutput.match( /fair point|good point|you're right|concede|acknowledge|valid point|no new blocking/i, ) || [] ).length; const concessionScore = resolvedCount + concessionIndicators * 0.5; if (stoppingConditions === "consensus") { if (concessionScore >= concessionThreshold) { consecutiveResolved++; if (consecutiveResolved >= 2) shouldContinue = false; } else { consecutiveResolved = 0; } } else if ( stoppingConditions === "blocking_found" && roundBlockingCount === 0 ) { shouldContinue = false; } else if (stoppingConditions === "max_rounds") { shouldContinue = i < maxRounds; } } if (signal?.aborted) { return { synthesis: "Debate cancelled by user.", roundsData, recommendation: "proceed_with_caution", blockingRaised: blockingIssuesFound, blockingRemaining: blockingIssuesFound, aborted: true, }; } onStatus?.("Synthesizing verdict", roundsData.length, maxRounds, blockingIssuesFound); // ── Synthesis (JSON structured output) ── const synthesisUserText = [ `Idea: ${idea}`, `Debate (${roundsData.length} rounds):`, roundsData.join("\n\n---\n\n"), ].join("\n\n"); const synthesisResponse = await complete( model, { systemPrompt: SYNTHESIS_SYSTEM_PROMPT, messages: [ { role: "user", content: [{ type: "text", text: synthesisUserText }], timestamp: Date.now(), }, ], }, { apiKey, headers, signal }, ); const synthesisRaw = synthesisResponse.content .filter((c): c is { type: "text"; text: string } => c.type === "text") .map((c) => c.text) .join("\n"); const synthesis = parseSynthesis(synthesisRaw); const synthesisFormatted = formatSynthesis(synthesis); return { synthesis: synthesisFormatted, roundsData, recommendation: synthesis.recommendation, blockingRaised: blockingIssuesFound, blockingRemaining: synthesis.blocking.length, }; } function formatDebateOutput( output: DebateOutput, onBlocking: "surface" | "escalate" | "ignore", ): string { let blockingNote = ""; if (output.blockingRemaining > 0 && onBlocking === "escalate") { blockingNote = `\n\n⚠️ **${output.blockingRemaining} unresolved blocking issue(s).** Review before proceeding.`; } const meta = output.aborted ? `*Debate cancelled | ${output.roundsData.length} rounds completed*` : `*Debate: ${output.roundsData.length}r | ${output.blockingRaised} blocking challenges raised | ${output.blockingRemaining} unresolved in verdict*`; return `${output.synthesis}${blockingNote}\n\n${meta}`; } // ── Extension entry ─────────────────────────────────────────────────── export default async function (pi: ExtensionAPI) { const settings = pi.settingsManager?.getSettings(); const devilSettings: DevilSettings = settings?.devil ?? {}; const activeControllers = new Set(); // ── Flags ───────────────────────────────────────────────────────── pi.registerFlag("devil-max-rounds", { description: "Override max debate rounds (1-10)", type: "number", default: devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS, }); pi.registerFlag("devil-stop", { description: "Override stopping condition (consensus | blocking_found | max_rounds)", type: "string", default: devilSettings.stoppingConditions ?? DEFAULT_STOPPING_CONDITIONS, }); // ── Cleanup: clear devil status/widget on next prompt or abort ── pi.on("before_agent_start", async (_event, ctx) => { ctx.ui.setStatus("devil", undefined); ctx.ui.setWidget("devil", undefined); }); pi.on("session_shutdown", async (_event, ctx) => { for (const controller of activeControllers) controller.abort(); activeControllers.clear(); ctx.ui.setStatus("devil", undefined); ctx.ui.setWidget("devil", undefined); }); // ── Tool: devil ──────────────────────────────────────────────────── pi.registerTool({ name: "devil", label: "Devil's Advocate", description: "Debate tool. STRESS TEST ideas. Surface blocking issues before committing. Use when: the user asks to stress-test, validate, critique, or play devil's advocate with an idea, design decision, architecture choice, or plan. Good for reducing sycophancy by forcing critical examination.", promptSnippet: "Stress-test ideas via structured devil's advocate debate", promptGuidelines: [ "Use devil when the user wants to validate an idea, check for flaws, or get a critical perspective before committing to a decision.", "Include relevant context (problem, constraints, scale) as kvpairs for better-targeted challenges.", "Set stakeholder to match the perspective most relevant to the idea (security, cost, ux, impl, ethics, skeptical).", "After devil returns, summarize the verdict and actionable next steps for the user.", ], parameters: Type.Object({ idea: Type.String({ description: "Idea/claim/decision. Be specific." }), context: Type.Optional( Type.Record(Type.String(), Type.String(), { description: 'Background: { problem: "...", constraint: "...", scale: "..." }', }), ), model: Type.Optional( Type.String({ description: "Model override (e.g., 'anthropic/claude-haiku-4-5')", }), ), maxRounds: Type.Optional(Type.Number({ minimum: 1, maximum: 10 })), stakeholder: Type.Optional( StringEnum(["security", "cost", "ux", "implementation", "ethics", "skeptical"] as const), ), stoppingConditions: Type.Optional( StringEnum(["consensus", "blocking_found", "max_rounds"] as const), ), concessionThreshold: Type.Optional( Type.Number({ minimum: 0, maximum: 1 }), ), onBlocking: Type.Optional( StringEnum(["surface", "escalate", "ignore"] as const), ), output: Type.Optional( StringEnum(["full", "summary_only"] as const), ), }), renderCall(args, theme) { const idea = args.idea as string; const maxRounds = (args.maxRounds as number | undefined) ?? devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS; const stakeholder = args.stakeholder as string | undefined; const stopping = args.stoppingConditions as string | undefined; const snippet = idea.length > 30 ? idea.slice(0, 30) + "..." : idea; const focus = stakeholder ? ` · ${stakeholder}` : ""; const stop = stopping && stopping !== DEFAULT_STOPPING_CONDITIONS ? ` · ${stopping}` : ""; return new Text( theme.fg("toolTitle", theme.bold("devil ")) + theme.fg("dim", `"${snippet}"`) + theme.fg("muted", ` ${maxRounds}r${focus}${stop}`), 0, 0, ); }, renderResult(result, { expanded }, theme) { const details = result.details as | { recommendation?: string; rounds?: number; blockingRaised?: number; blockingRemaining?: number; output?: string; roundsData?: string[]; aborted?: boolean; } | undefined; if (!details) { const text = result.content[0]; return new Text(text?.type === "text" ? text.text : "", 0, 0); } if (details.aborted) { return new Text( theme.fg("warning", "⚠ ") + theme.fg("muted", "Debate cancelled"), 0, 0, ); } const rec = details.recommendation ?? "proceed_with_caution"; const rounds = details.rounds ?? 0; const raised = details.blockingRaised ?? 0; const remaining = details.blockingRemaining ?? raised; let recColor: string; let recLabel: string; switch (rec) { case "proceed": recColor = "success"; recLabel = "✓ proceed"; break; case "revise": recColor = "warning"; recLabel = "⚠ revise"; break; case "abandon": recColor = "error"; recLabel = "✗ abandon"; break; default: recColor = "muted"; recLabel = "~ caution"; } let text = theme.fg(recColor, recLabel); text += theme.fg("muted", ` · ${rounds}r · ${raised} raised · ${remaining} unresolved`); if (expanded) { if (details.roundsData?.length) { text += "\n" + theme.fg("toolTitle", "### Transcript"); for (const round of details.roundsData) { text += "\n" + theme.fg("dim", round); } } else if (details.output) { const lines = details.output.split("\n").filter((l: string) => l.trim()); let inSection = false; for (const line of lines.slice(0, 30)) { if (line.startsWith("### ") || line.startsWith("## ")) { inSection = true; text += "\n" + theme.fg("toolTitle", line); } else if (inSection) { text += "\n" + theme.fg("dim", line); } } if (lines.length > 30) text += "\n" + theme.fg("dim", "..."); } } return new Text(text, 0, 0); }, execute: async (_toolCallId, params, signal, onUpdate, ctx) => { const { idea, context: explicitContext, model: modelOverride, maxRounds: maxRoundsParam, stakeholder, stoppingConditions: stoppingConditionsParam, concessionThreshold: concessionThresholdParam, onBlocking: onBlockingParam, output = "summary_only", } = params; const maxRounds = maxRoundsParam ?? devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS; const stoppingConditions = stoppingConditionsParam ?? devilSettings.stoppingConditions ?? DEFAULT_STOPPING_CONDITIONS; const concessionThreshold = concessionThresholdParam ?? devilSettings.concessionThreshold ?? DEFAULT_CONCESSION_THRESHOLD; const onBlocking = onBlockingParam ?? devilSettings.onBlocking ?? DEFAULT_ON_BLOCKING; const model = resolveDebateModel( ctx, modelOverride ?? devilSettings.model, ); if (!model) { throw new Error("No model available. Use /model."); } const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model); if (!auth.ok || !auth.apiKey) { throw new Error(`No API key for ${model.provider}`); } // Merge session context with LLM-provided context const sessionContext = gatherContext(ctx); const mergedContext = { ...sessionContext, ...(explicitContext ?? {}), ...(stakeholder ? { _stakeholder: `Challenge from ${stakeholder} perspective.` } : {}), }; const live = createDebateState(idea, maxRounds); const renderLiveWidget = () => { if (!ctx.hasUI || signal?.aborted) return; ctx.ui.setWidget("devil", (_tui, theme) => new DebateWidget(theme, live)); }; renderLiveWidget(); try { const result = await runDebate({ idea, context: mergedContext, model, apiKey: auth.apiKey, headers: auth.headers, maxRounds, stoppingConditions: stoppingConditions as | "consensus" | "blocking_found" | "max_rounds", concessionThreshold, signal, onStatus: (status, round, _max, blocking) => { if (signal?.aborted) return; setDebateStatus(live, status, round, blocking); renderLiveWidget(); }, onChallenge: (round, _max, blocking, devilOutput) => { if (signal?.aborted) return; addDebateEntry(live, "devil", round, blocking, devilOutput); renderLiveWidget(); }, onRound: (round, max, blocking, _status, devilOutput, proposerOutput) => { if (signal?.aborted) return; addDebateEntry(live, "proposer", round, blocking, proposerOutput); renderLiveWidget(); onUpdate?.({ content: [ { type: "text", text: `Round ${round}/${max} · ${blocking} blocking raised\n⚑ ${extractSnippet(devilOutput, 80)}\n✓ ${extractSnippet(proposerOutput, 80)}`, }, ], details: { round, maxRounds: max, blockingRaised: blocking }, }); }, }); const outputText = output === "full" ? `## Full Debate\n\n${result.roundsData.join("\n\n---\n\n")}\n\n---\n\n${formatDebateOutput(result, onBlocking)}` : formatDebateOutput(result, onBlocking); if (ctx.hasUI) { ctx.ui.setStatus("devil", undefined); ctx.ui.setWidget("devil", undefined); } return { content: [{ type: "text", text: outputText }], details: { recommendation: result.recommendation, rounds: result.roundsData.length, blockingRaised: result.blockingRaised, blockingRemaining: result.blockingRemaining, output: result.synthesis, roundsData: result.roundsData, aborted: result.aborted, }, }; } catch (error) { const message = error instanceof Error ? error.message : String(error); if (ctx.hasUI) { ctx.ui.setStatus("devil", undefined); ctx.ui.setWidget("devil", undefined); } throw new Error(`Debate failed: ${message}`); } }, }); // ── Command: /devil ──────────────────────────────────────────────── pi.registerShortcut(Key.ctrlAlt("d"), { description: "Start devil's advocate debate with current editor text", handler: async (ctx) => { const text = ctx.ui.getEditorText?.().trim(); if (!text) { ctx.ui?.notify("Type an idea in the editor first, or use /devil ", "info"); return; } // Don't re-debate existing debate output if (text.startsWith("## Verdict:") || text.startsWith("*Debate:")) { ctx.ui?.notify("Editor contains debate output, not an idea. Clear it first.", "info"); return; } await pi.sendUserMessage(`/devil ${text}`); }, }); pi.registerCommand("devil", { description: "Start an interactive devil's advocate debate", handler: async (args, ctx) => { const idea = args.trim(); if (!idea) { ctx.ui?.notify("Usage: /devil ", "error"); return; } if (!ctx.hasUI) { ctx.ui?.notify("Devil requires interactive mode", "error"); return; } const model = resolveDebateModel(ctx, devilSettings.model); if (!model) { ctx.ui?.notify("No model selected. Use /model first.", "error"); return; } const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model); if (!auth.ok || !auth.apiKey) { ctx.ui?.notify(`No API key for ${model.provider}`, "error"); return; } const maxRounds = pi.getFlag("devil-max-rounds") as number ?? devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS; const stoppingConditions = ((pi.getFlag("devil-stop") as string) ?? devilSettings.stoppingConditions ?? DEFAULT_STOPPING_CONDITIONS) as "consensus" | "blocking_found" | "max_rounds"; const concessionThreshold = devilSettings.concessionThreshold ?? DEFAULT_CONCESSION_THRESHOLD; const onBlocking = devilSettings.onBlocking ?? DEFAULT_ON_BLOCKING; const debateContext = gatherContext(ctx); const debateController = new AbortController(); activeControllers.add(debateController); let result: DebateOutput | null = null; let failedMessage: string | undefined; try { result = await ctx.ui.custom( (tui, theme, _kb, done) => { const live = createDebateState(idea, maxRounds); const review = new DebateReviewComponent(tui, theme, live, done, debateController); runDebate({ idea, context: debateContext, model, apiKey: auth.apiKey!, headers: auth.headers, maxRounds, stoppingConditions, concessionThreshold, signal: review.signal, onStatus: (status, round, _max, blocking) => { if (!review.isActive()) return; setDebateStatus(live, status, round, blocking); review.refresh(); }, onChallenge: (round, _max, blocking, devilOutput) => { if (!review.isActive()) return; addDebateEntry(live, "devil", round, blocking, devilOutput); review.refresh(); }, onRound: (round, _max, blocking, _status, _devilOutput, proposerOutput) => { if (!review.isActive()) return; addDebateEntry(live, "proposer", round, blocking, proposerOutput); review.refresh(); }, }) .then((output) => review.finish(output.aborted ? null : output)) .catch((err) => { if (!review.signal.aborted && review.isActive()) { failedMessage = err instanceof Error ? err.message : String(err); console.error("[devil] runDebate error:", err); ctx.ui.notify(`Debate failed: ${failedMessage}`, "error"); } review.finish(null); }); return review; }, ); } finally { debateController.abort(); activeControllers.delete(debateController); ctx.ui.setStatus("devil", undefined); ctx.ui.setWidget("devil", undefined); } if (result === null) { if (!failedMessage) ctx.ui.notify("Debate cancelled", "info"); return; } const outputText = formatDebateOutput(result, onBlocking); // Modal editor: Enter submits directly, Esc discards. const edited = await ctx.ui.editor( `🗡️ ${result.recommendation.replace(/_/g, " ")} · ${result.blockingRaised} raised · ${result.blockingRemaining} unresolved`, outputText, ); ctx.ui.setStatus("devil", undefined); ctx.ui.setWidget("devil", undefined); if (edited === undefined || !edited.trim()) { ctx.ui.notify("Debate result discarded", "info"); return; } pi.appendEntry("devil-result", { idea, verdict: edited, roundsData: result.roundsData, recommendation: result.recommendation, blockingRaised: result.blockingRaised, blockingRemaining: result.blockingRemaining, timestamp: Date.now(), }); pi.sendUserMessage(edited); }, }); }