/** * 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 a debate * Call devils_advocate tool * * Configuration (settings.json): * { * "devilsAdvocate": { * "model": "anthropic/claude-haiku-4-5", // 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 * } * } * * Pi Session Implications: * - Debates are stateless (no persistence between calls) * - Uses current session's model and API credentials * - Results are returned as tool output, not added to conversation * - Context from current conversation is NOT automatically included */ import { Type } from "@sinclair/typebox"; import { complete, type Message } from "@mariozechner/pi-ai"; import type { ExtensionAPI } from "@mariozechner/pi-coding-agent"; const DEVIL_SYSTEM_PROMPT = `You are a devil's advocate in a structured debate. Your goal is to STRESS TEST the proposer's idea by identifying blocking issues. CLASSIFICATION GUIDE: - **blocking**: Would prevent the idea from working entirely. Must be addressed before proceeding. - **addressable**: Valid concern but has known mitigations or workarounds. - **assumed**: Based on premises that may not hold in all contexts. - **minor**: Aesthetic preference, stylistic choice, or edge case that won't affect success. EXAMPLES: - "This requires authentication that doesn't exist" → blocking - "Users might find this confusing" → addressable (can add onboarding) - "This assumes fast internet" → assumed (premise may not hold) - "The button should be blue not green" → minor (cosmetic, doesn't affect functionality) RULES: 1. Lead with blocking concerns. Do not waste rounds on minor issues. 2. Be specific: name the exact failure mode, not vague risks. 3. If a defense successfully addresses a concern, acknowledge it and move on. 4. Focus on what would actually break the idea, not theoretical concerns. Format each challenge as: ### [CLASSIFICATION] Challenge Title **The concern:** Clear statement of the problem **What would resolve it:** Specific conditions that would satisfy you **Current status:** outstanding / resolved / retracted`; const PROPOSER_SYSTEM_PROMPT = `You are presenting an idea for scrutiny. Your goal is to DEFEND it where valid and ACKNOWLEDGE where it's weak. RULES: 1. Don't capitulate easily - require specific evidence against your idea 2. Distinguish between "I don't know", "that doesn't apply", and "I've addressed that" 3. If a concern is valid, acknowledge it and explain the mitigation 4. Do not concede to blocking concerns without explaining how you'd address them For each challenge, respond with: 1. **Your defense**: What defeats or addresses this challenge 2. **Concession** (if valid): Acknowledge what concern remains 3. **Status**: outstanding / resolved Be specific. "I addressed that" requires explaining how.`; const SYNTHESIS_SYSTEM_PROMPT = `Analyze this debate and produce an honest summary for a user who needs to make a decision. CLASSIFICATION SUMMARY: - **blocking**: Must fix before proceeding - **addressable**: Valid but has mitigations - **assumed**: Depends on unverified premises - **minor**: Not worth fixing Output format: ## Summary **Recommendation:** proceed / proceed_with_caution / revise / abandon ### Blocking Issues (must address first) - [blocking concern] → [what would fix it] ### Addressable Concerns (valid concerns with mitigations) - [concern] → [mitigation strategy] ### What Survived Scrutiny - [claims that held up under pressure] ### What Was Conceded - [acknowledged weaknesses] ### Recommended Next Steps 1. [action item] 2. [action item]`; // 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"; } export default async function (pi: ExtensionAPI) { // Read settings const settings = pi.settingsManager?.getSettings(); const devilSettings: DevilSettings = settings?.devilsAdvocate ?? {}; // Register the devil's advocate tool pi.registerTool({ name: "devils_advocate", label: "Devil's Advocate", description: `A structured debate tool for stress-testing ideas against a devil's advocate. Run debates to surface blocking issues before committing to decisions. Parameters: - idea: The idea/claim to debate (required) - context: Key-value pairs for background (optional) - model: Override model (optional) - maxRounds: Maximum rounds 1-10 (default: ${devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS}) - stakeholder: security | cost | ux | implementation | ethics | skeptical - stoppingConditions: When to stop (default: ${devilSettings.stoppingConditions ?? DEFAULT_STOPPING_CONDITIONS}) - output: full | summary_only (default: summary_only)`, parameters: Type.Object({ idea: Type.String({ description: "The idea, claim, or decision to debate. Be specific and concrete.", }), 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( Type.Union([ Type.Literal("security"), Type.Literal("cost"), Type.Literal("ux"), Type.Literal("implementation"), Type.Literal("ethics"), Type.Literal("skeptical"), ]) ), stoppingConditions: Type.Optional( Type.Union([ Type.Literal("consensus"), Type.Literal("blocking_found"), Type.Literal("max_rounds"), ]) ), concessionThreshold: Type.Optional( Type.Number({ minimum: 0, maximum: 1 }) ), onBlocking: Type.Optional( Type.Union([ Type.Literal("surface"), Type.Literal("escalate"), Type.Literal("ignore"), ]) ), output: Type.Optional( Type.Union([Type.Literal("full"), Type.Literal("summary_only")]) ), }), execute: async (_toolCallId, params, signal, onUpdate, ctx) => { const { idea, context, 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; // Determine which model to use let model = ctx.model; if (modelOverride) { const [provider, modelId] = modelOverride.includes("/") ? modelOverride.split("/") : [modelOverride, modelOverride]; const foundModel = ctx.modelRegistry.find(provider, modelId); if (foundModel) model = foundModel; } else if (devilSettings.model && ctx.model) { const [provider, modelId] = devilSettings.model.includes("/") ? devilSettings.model.split("/") : [ctx.model.provider, devilSettings.model]; const foundModel = ctx.modelRegistry.find(provider, modelId); if (foundModel) model = foundModel; } if (!model) { return { content: [{ type: "text", text: "Error: No model available. Select a model first with /model." }], details: { error: "No model" }, }; } const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model); if (!auth.ok || !auth.apiKey) { return { content: [{ type: "text", text: `Error: No API key for ${model.provider}` }], details: { error: "No API key" }, }; } const contextText = context ? Object.entries(context).map(([k, v]) => `- **${k}**: ${v}`).join("\n") : "No additional context provided."; const stakeholderContext = stakeholder ? `\n\n**Focus:** Challenge specifically from ${stakeholder} perspective.` : ""; // Stream initial output onUpdate?.({ content: [{ type: "text", text: `## 🗡️ Devil's Advocate Debate\n\n**Idea:** ${idea}\n\n**Context:**\n${contextText}\n\n**Config:** maxRounds=${maxRounds}, stopping=${stoppingConditions}, blocking=${onBlocking}\n**Model:** ${model.provider}/${model.id}\n\n---\n\n` }], details: {}, }); try { const rounds_data: string[] = []; let blockingIssuesFound = 0; let consecutiveResolved = 0; let shouldContinue = true; for (let i = 1; i <= maxRounds && shouldContinue; i++) { // Devil's challenge const devilMessages: Message[] = [ { role: "system", content: [{ type: "text", text: DEVIL_SYSTEM_PROMPT }], timestamp: Date.now() }, { role: "user", content: [{ type: "text", text: `Context:\n${contextText}${stakeholderContext}\n\nIdea: ${idea}\n\nRound ${i}/${maxRounds}. Identify the most blocking concern.` }], timestamp: Date.now() }, ]; const devilResponse = await complete(model, { systemPrompt: "", messages: devilMessages }, { apiKey: auth.apiKey, headers: auth.headers, signal }); const devilOutput = devilResponse.content.filter((c): c is { type: "text"; text: string } => c.type === "text").map(c => c.text).join("\n"); // Count blocking issues const roundBlockingCount = (devilOutput.match(/\[blocking\]/gi) || []).length; blockingIssuesFound = Math.max(blockingIssuesFound, roundBlockingCount); // Proposer's rebuttal const proposerMessages: Message[] = [ { role: "system", content: [{ type: "text", text: PROPOSER_SYSTEM_PROMPT }], timestamp: Date.now() }, { role: "user", content: [{ type: "text", text: `Your idea: ${idea}\n\nChallenges:\n${devilOutput}\n\nRespond to these challenges.` }], timestamp: Date.now() }, ]; const proposerResponse = await complete(model, { systemPrompt: "", messages: proposerMessages }, { apiKey: auth.apiKey, headers: auth.headers, signal }); const proposerOutput = proposerResponse.content.filter((c): c is { type: "text"; text: string } => c.type === "text").map(c => c.text).join("\n"); rounds_data.push(`### Round ${i}\n\n**Challenge:**\n${devilOutput}\n\n**Your Response:**\n${proposerOutput}`); // Stream round result onUpdate?.({ content: [{ type: "text", text: `### Round ${i}/${maxRounds}\n\n**Challenge identified.** Respond above.\n\n` }], details: { round: i, blockingCount: roundBlockingCount }, }); // 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/i) || []).length; const concessionScore = resolvedCount + (concessionIndicators * 0.5); if (stoppingConditions === "consensus" && concessionScore >= concessionThreshold) { consecutiveResolved++; if (consecutiveResolved >= 2) { shouldContinue = false; } } else if (stoppingConditions === "blocking_found" && roundBlockingCount === 0) { shouldContinue = false; } else if (stoppingConditions === "max_rounds") { // Always continue until max_rounds shouldContinue = i < maxRounds; } if (resolvedCount > 0) consecutiveResolved++; } // Synthesis const synthesisMessages: Message[] = [ { role: "system", content: [{ type: "text", text: SYNTHESIS_SYSTEM_PROMPT }], timestamp: Date.now() }, { role: "user", content: [{ type: "text", text: `Idea: ${idea}\n\nDebate (${rounds_data.length} rounds):\n${rounds_data.join("\n\n---\n\n")}` }], timestamp: Date.now() }, ]; const synthesisResponse = await complete(model, { systemPrompt: "", messages: synthesisMessages }, { apiKey: auth.apiKey, headers: auth.headers, signal }); const synthesisOutput = synthesisResponse.content.filter((c): c is { type: "text"; text: string } => c.type === "text").map(c => c.text).join("\n"); // Parse recommendation const recMatch = synthesisOutput.match(/\*\*recommendation\*\*:\s*(\w+)/i); let recommendation = "proceed_with_caution"; if (recMatch) { recommendation = recMatch[1].toLowerCase(); if (!["proceed", "proceed_with_caution", "revise", "abandon"].includes(recommendation)) { recommendation = "proceed_with_caution"; } } // Handle blocking issues based on onBlocking setting let blockingNote = ""; if (blockingIssuesFound > 0 && onBlocking === "escalate") { blockingNote = `\n\n⚠️ **${blockingIssuesFound} blocking issue(s) found.** Review before proceeding.`; } else if (blockingIssuesFound > 0 && onBlocking === "ignore") { blockingNote = ""; } const outputText = output === "full" ? `## Full Debate\n\n${rounds_data.join("\n\n---\n\n")}\n\n---\n\n## Summary\n\n${synthesisOutput}${blockingNote}\n\n**Debate:** ${rounds_data.length} rounds | **Blocking issues:** ${blockingIssuesFound}` : `${synthesisOutput}${blockingNote}\n\n*Debate: ${rounds_data.length} rounds | Blocking: ${blockingIssuesFound}*`; return { content: [{ type: "text", text: outputText }], details: { recommendation, rounds: rounds_data.length, blockingIssues: blockingIssuesFound }, }; } catch (error) { const message = error instanceof Error ? error.message : String(error); return { content: [{ type: "text", text: `## Debate Failed\n\nError: ${message}` }], details: { error: message }, }; } }, }); // Register the /devil command pi.registerCommand("devil", { description: "Start a devil's advocate debate", handler: async (args, ctx) => { const idea = args.trim(); if (!idea) { ctx.ui?.notify("Usage: /devil ", "error"); return; } await ctx.tools?.invoke("devils_advocate", { idea, maxRounds: devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS, stoppingConditions: (devilSettings.stoppingConditions as any) ?? DEFAULT_STOPPING_CONDITIONS, }); }, }); }