repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/devil/index.ts

Raw
File outline
/**
 * 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 <your idea> - Start an interactive debate with live progress
 *   Call devils_advocate tool - Non-interactive debate (for LLM use)
 *
 * 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
 *     }
 *   }
 */

import { Type } from "@sinclair/typebox";
import * as fs from "node:fs";
import * as path from "node:path";
import { complete, StringEnum, type Message } from "@mariozechner/pi-ai";
import {
	BorderedLoader,
	convertToLlm,
	serializeConversation,
} from "@mariozechner/pi-coding-agent";
import type {
	ExtensionAPI,
	ExtensionContext,
	Model,
	SessionEntry,
} from "@mariozechner/pi-coding-agent";
import { Text } from "@mariozechner/pi-tui";
import { Key } 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<string, string>;
	model: Model;
	apiKey: string;
	headers?: Record<string, string>;
	maxRounds: number;
	stoppingConditions: "consensus" | "blocking_found" | "max_rounds";
	concessionThreshold: number;
	signal?: AbortSignal;
	/** 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;
}

// ── 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<string, unknown>;
}

function gatherContext(ctx: ExtensionContext): Record<string, string> {
	const context: Record<string, string> = {};
	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<string>();

	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\`${content}\``;
				} 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<string, string> = {
		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 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<DebateOutput> {
	const {
		idea,
		context,
		model,
		apiKey,
		headers,
		maxRounds,
		stoppingConditions,
		concessionThreshold,
		signal,
		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,
			};
		}

		// ── 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(/\[blocking\]/gi) || []).length +
			(devilOutput.match(/\*\*blocking\*\*/gi) || []).length;
		blockingIssuesFound = Math.max(blockingIssuesFound, roundBlockingCount);

		// Mid-round update: devil has spoken, widget shows challenge
		onChallenge?.(i, maxRounds, blockingIssuesFound, devilOutput);

		// ── 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`;
		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,
		};
	}

	// ── 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} raised, ${output.blockingRemaining} remaining*`;

	return `${output.synthesis}${blockingNote}\n\n${meta}`;
}

// ── Extension entry ───────────────────────────────────────────────────

export default async function (pi: ExtensionAPI) {
	const settings = pi.settingsManager?.getSettings();
	const devilSettings: DevilSettings = settings?.devilsAdvocate ?? {};

	// ── 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) => {
		ctx.ui.setStatus("devil", undefined);
		ctx.ui.setWidget("devil", undefined);
	});

	// ── Tool: devils_advocate ──────────────────────────────────────────

	pi.registerTool({
		name: "devils_advocate",
		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 devils_advocate 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 devils_advocate 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("devils_advocate ")) +
					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;
						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}→${remaining} blocking`);

			if (expanded && 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;

			// Resolve model
			let model = ctx.model;
			if (modelOverride) {
				const [provider, modelId] = modelOverride.includes("/")
					? modelOverride.split("/")
					: [modelOverride, modelOverride];
				const found = ctx.modelRegistry.find(provider, modelId);
				if (found) model = found;
			} else if (devilSettings.model && ctx.model) {
				const [provider, modelId] = devilSettings.model.includes("/")
					? devilSettings.model.split("/")
					: [ctx.model.provider, devilSettings.model];
				const found = ctx.modelRegistry.find(provider, modelId);
				if (found) model = found;
			}

			if (!model) {
				return {
					content: [
						{ type: "text", text: "Error: No model available. Use /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" },
				};
			}

			// Merge session context with LLM-provided context
			const sessionContext = gatherContext(ctx);
			const mergedContext = {
				...sessionContext,
				...(explicitContext ?? {}),
				...(stakeholder
					? { _stakeholder: `Challenge from ${stakeholder} perspective.` }
					: {}),
			};

			if (ctx.hasUI) {
				ctx.ui.setStatus(
					"devil",
					`🗡️ Devil: ${idea.slice(0, 40)}... (${maxRounds}r)`,
				);
			}

			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,
					onChallenge: (round, max, blocking, devilOutput) => {
						if (ctx.hasUI) {
							ctx.ui.setStatus("devil", `🗡️ Devil: R${round}/${max} challenging...`);
							const snippet = extractSnippet(devilOutput, 60);
							ctx.ui.setWidget("devil", [
								`🗡️ Round ${round}/${max} · ${blocking} blocking`,
								snippet ? `  ⚑ ${snippet}` : "  ⚑ Analyzing...",
							]);
						}
					},
					onRound: (round, max, blocking, status, devilOutput, proposerOutput) => {
						if (ctx.hasUI) {
							ctx.ui.setStatus("devil", `🗡️ Devil: ${status}`);
							const snippet = extractSnippet(proposerOutput, 60);
							ctx.ui.setWidget("devil", [
								`🗡️ Round ${round}/${max} · ${blocking} blocking`,
								snippet ? `  ✓ ${snippet}` : "  ✓ Defended",
							]);
						}
						onUpdate?.({
							content: [
								{
									type: "text",
									text: `Round ${round}/${max} · ${blocking} blocking\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,
						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);
				}
				return {
					content: [{ type: "text", text: `## Debate Failed\n\nError: ${message}` }],
					details: { error: 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 <idea>", "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;
			}
			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 <your idea>", "error");
				return;
			}
			if (!ctx.hasUI) {
				ctx.ui?.notify("Devil requires interactive mode", "error");
				return;
			}
			if (!ctx.model) {
				ctx.ui?.notify("No model selected. Use /model first.", "error");
				return;
			}

			const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model);
			if (!auth.ok || !auth.apiKey) {
				ctx.ui?.notify(`No API key for ${ctx.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 result = await ctx.ui.custom<DebateOutput | null>(
				(tui, theme, _kb, done) => {
					const loader = new BorderedLoader(
						tui,
						theme,
						`🗡️ Devil: "${idea.length > 40 ? idea.slice(0, 40) + "..." : idea}" (${maxRounds}r)`,
					);
					loader.onAbort = () => done(null);

					runDebate({
						idea,
						context: debateContext,
						model: ctx.model!,
						apiKey: auth.apiKey!,
						headers: auth.headers,
						maxRounds,
						stoppingConditions,
						concessionThreshold,
						signal: loader.signal,
						onChallenge: (round, max, blocking, devilOutput) => {
							ctx.ui.setStatus("devil", `🗡️ Devil: R${round}/${max} challenging...`);
							const snippet = extractSnippet(devilOutput, 60);
							ctx.ui.setWidget("devil", [
								`🗡️ Round ${round}/${max} · ${blocking} blocking`,
								snippet ? `  ⚑ ${snippet}` : "  ⚑ Analyzing...",
							]);
						},
						onRound: (round, max, blocking, _status, _devilOutput, proposerOutput) => {
							ctx.ui.setStatus("devil", `🗡️ Devil: R${round}/${max} defending...`);
							const snippet = extractSnippet(proposerOutput, 60);
							ctx.ui.setWidget("devil", [
								`🗡️ Round ${round}/${max} · ${blocking} blocking`,
								snippet ? `  ✓ ${snippet}` : "  ✓ Defended",
							]);
						},
					})
						.then((output) => {
							ctx.ui.setWidget("devil", undefined);
							if (output.aborted) done(null);
							else done(output);
						})
						.catch((err) => {
							ctx.ui.setWidget("devil", undefined);
							console.error("[devil] runDebate error:", err);
							done(null);
						});

					return loader;
				},
			);

			if (result === null) {
				ctx.ui.setStatus("devil", undefined);
				ctx.ui.setWidget("devil", undefined);
				ctx.ui.notify("Debate cancelled", "info");
				return;
			}

			const outputText = formatDebateOutput(result, onBlocking);

			// Modal editor: Enter confirms (→ main editor), Esc discards
			const edited = await ctx.ui.editor(
				`🗡️ ${result.recommendation.replace(/_/g, " ")} · ${result.blockingRaised} raised, ${result.blockingRemaining} remaining`,
				outputText,
			);

			ctx.ui.setStatus("devil", undefined);
			ctx.ui.setWidget("devil", undefined);

			if (edited === undefined) {
				ctx.ui.notify("Debate result discarded", "info");
				return;
			}

			ctx.ui.setEditorText(edited);
			ctx.ui.notify("Edit and submit when ready", "success");
		},
	});
}