repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

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
 *
 * Configuration (settings.json):
 *   {
 *     "devil": {
 *       "model": "zai/glm-5.1",                // Optional: specific model
 *       "maxRounds": 2,                          // 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 { randomUUID } from "node:crypto";
import {
	chmodSync,
	mkdtempSync,
	readdirSync,
	rmSync,
	statSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
import { complete, type Model } from "@earendil-works/pi-ai";
import type {
	ExtensionAPI,
	ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import {
	createAgentSession,
	DefaultResourceLoader,
	getAgentDir,
	SessionManager,
	SettingsManager,
} from "@earendil-works/pi-coding-agent";
import { handleDebateResult } from "./handoff";
import {
	abortedResult,
	buildContextText,
	buildProposerPrompt,
	buildRoundPrompt,
	CONSENSUS_ROUNDS_REQUIRED,
	calcConcessionScore,
	checkAborted,
	countBlockingIssues,
	ROUND_HISTORY_TRUNCATE,
	textFromContent,
} from "./helpers";
import {
	formatDebateError,
	type TimeoutRole,
	withRoleTimeout,
} from "./timeouts";
import type { DebateOutput } from "./types";
import {
	createDebateState,
	DebateReviewComponent,
	type DebateRole,
	setDebateStatus,
	upsertDebateEntry,
} from "./ui";

export { buildMainAgentHandoff, handleDebateResult } from "./handoff";
export { DevilTimeoutError, withRoleTimeout } from "./timeouts";
export {
	createDebateState,
	DebateReviewComponent,
	renderDebateTranscript,
} from "./ui";

type AnyModel = Model<any>;

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 = 2;
const DEFAULT_STOPPING_CONDITIONS = "consensus";
const DEFAULT_CONCESSION_THRESHOLD = 0.7;
const DEFAULT_ON_BLOCKING = "surface";
const DEFAULT_EXTENSION_MODE = "all";
const DEFAULT_CONTEXT_HEADROOM = 0.85;
const DEFAULT_CONTEXT_OVERHEAD_TOKENS = 16_000;
const DEFAULT_ROLE_TIMEOUT_MS = 90_000;
export const DEFAULT_DEVIL_THINKING: ThinkingLevel = "medium";
export const DEFAULT_DEFENDER_THINKING: ThinkingLevel = "high";
export const DEFAULT_SYNTHESIS_THINKING: ThinkingLevel = "off";

interface DevilSettings {
	model?: string;
	defenderModel?: string;
	thinkingLevel?: ThinkingLevel;
	devilThinkingLevel?: ThinkingLevel;
	defenderThinkingLevel?: ThinkingLevel;
	synthesisThinkingLevel?: ThinkingLevel;
	roleTimeoutMs?: number;
	maxRounds?: number;
	extensionMode?: "all" | "off";
	stoppingConditions?: "consensus" | "blocking_found" | "max_rounds";
	concessionThreshold?: number;
	onBlocking?: "surface" | "escalate" | "ignore";
}

interface SettingsAPI extends ExtensionAPI {
	settingsManager?: { getSettings(): Record<string, unknown> | undefined };
}

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: AnyModel;
	defenderModel: AnyModel;
	ctx: ExtensionContext;
	apiKey: string;
	headers?: Record<string, string>;
	devilThinkingLevel: ThinkingLevel;
	defenderThinkingLevel: ThinkingLevel;
	synthesisThinkingLevel: ThinkingLevel;
	roleTimeoutMs: number;
	maxRounds: number;
	extensionMode: "all" | "off";
	stoppingConditions: "consensus" | "blocking_found" | "max_rounds";
	concessionThreshold: number;
	signal?: AbortSignal;
	onStatus?: (
		status: string,
		round: number,
		maxRounds: number,
		blocking: number,
	) => void;
	/** Fires while either agent streams */
	onPartial?: (
		role: DebateRole,
		round: number,
		maxRounds: number,
		blocking: number,
		text: string,
	) => 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;
}

// ── Helpers ───────────────────────────────────────────────────────────

const DISABLED_SUBAGENT_TOOLS = new Set(["write", "edit"]);
const DEVIL_TMP_PREFIX = "pi-devil-";
const DEVIL_TMP_TTL_MS = 24 * 60 * 60 * 1000;

function gatherContext(ctx: ExtensionContext): Record<string, string> {
	const context: Record<string, string> = {
		working_directory: ctx.cwd,
		session_context:
			"This debate runs in an ephemeral branch fork of the current Pi session. It reuses existing conversation, tool results, context files, skills, and loaded extensions already present in this branch.",
	};
	const usage = ctx.getContextUsage();
	if (usage) context["context_usage"] = JSON.stringify(usage);
	return context;
}

function gcEphemeralForks() {
	const now = Date.now();
	for (const name of readdirSync(tmpdir())) {
		if (!name.startsWith(DEVIL_TMP_PREFIX)) continue;
		const dir = join(tmpdir(), name);
		try {
			if (now - statSync(dir).mtimeMs > DEVIL_TMP_TTL_MS)
				rmSync(dir, { recursive: true, force: true });
		} catch {}
	}
}

export function normalizeThinkingLevel(
	value: unknown,
): ThinkingLevel | undefined {
	return ["off", "minimal", "low", "medium", "high", "xhigh"].includes(
		String(value),
	)
		? (String(value) as ThinkingLevel)
		: undefined;
}

export function formatTokenCount(tokens: number): string {
	return tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens);
}

export function devilContextLimit(
	usageTokens: number | null | undefined,
	devilModel: AnyModel,
	defenderModel: AnyModel,
	overheadTokens = DEFAULT_CONTEXT_OVERHEAD_TOKENS,
	headroom = DEFAULT_CONTEXT_HEADROOM,
):
	| { ok: true }
	| {
			ok: false;
			usageTokens: number;
			projectedTokens: number;
			limitTokens: number;
			minContextWindow: number;
			percent: number;
	  } {
	if (usageTokens === null || usageTokens === undefined) return { ok: true };
	const minContextWindow = Math.min(
		devilModel.contextWindow ?? Infinity,
		defenderModel.contextWindow ?? Infinity,
	);
	if (!Number.isFinite(minContextWindow)) return { ok: true };
	const projectedTokens = usageTokens + overheadTokens;
	const limitTokens = Math.floor(minContextWindow * headroom);
	if (projectedTokens <= limitTokens) return { ok: true };
	return {
		ok: false,
		usageTokens,
		projectedTokens,
		limitTokens,
		minContextWindow,
		percent: (projectedTokens / minContextWindow) * 100,
	};
}

function createEphemeralFork(ctx: ExtensionContext): {
	manager: SessionManager;
	cleanup: () => void;
} {
	const dir = mkdtempSync(join(tmpdir(), DEVIL_TMP_PREFIX));
	chmodSync(dir, 0o700);
	const file = join(dir, "branch.jsonl");
	const header = ctx.sessionManager.getHeader() ?? {
		type: "session",
		version: 3,
		id: randomUUID(),
		timestamp: new Date().toISOString(),
		cwd: ctx.cwd,
	};
	const entries = [
		{
			...header,
			cwd: ctx.cwd,
			parentSession: ctx.sessionManager.getSessionFile(),
		},
		...ctx.sessionManager.getBranch(),
	];
	writeFileSync(
		file,
		entries.map((entry) => JSON.stringify(entry)).join("\n") + "\n",
		{ encoding: "utf-8", mode: 0o600 },
	);

	return {
		manager: SessionManager.open(file, dir, ctx.cwd),
		cleanup: () => rmSync(dir, { recursive: true, force: true }),
	};
}

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 resolveDebateModel(
	ctx: ExtensionContext,
	modelSetting?: string,
): AnyModel | 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: [],
	};
}

// ── Debate orchestration ────────────────────────────────────────────

export function responseTextFromContent(content: unknown): string {
	return textFromContent(
		content as Array<{ type: string; text?: string }>,
	).trim();
}

function extractAssistantText(
	messages: Array<{ role?: string; content?: unknown }>,
): string {
	const chunks = messages
		.filter((message) => message.role === "assistant")
		.map((message) => responseTextFromContent(message.content).trim())
		.filter(Boolean);
	return chunks.at(-1) ?? chunks.join("\n\n");
}

async function runRoleAgent(opts: {
	ctx: ExtensionContext;
	model: AnyModel;
	systemPrompt: string;
	userPrompt: string;
	signal?: AbortSignal;
	thinkingLevel: ThinkingLevel;
	timeoutMs: number;
	role: TimeoutRole;
	extensionMode: "all" | "off";
	onTool?: (toolName: string) => void;
	onText?: (text: string) => void;
	onStatus?: (status: string) => void;
}): Promise<string> {
	const agentDir = getAgentDir();
	opts.onStatus?.("loading settings");
	const settingsManager = SettingsManager.create(opts.ctx.cwd, agentDir);
	const loader = new DefaultResourceLoader({
		cwd: opts.ctx.cwd,
		agentDir,
		settingsManager,
		noExtensions: opts.extensionMode === "off",
		systemPromptOverride: (base) =>
			[base, opts.systemPrompt].filter(Boolean).join("\n\n"),
	});
	opts.onStatus?.("loading extensions/resources");
	await loader.reload();
	opts.onStatus?.(
		`extensions ${opts.extensionMode}/${loader.getExtensions().extensions.length}`,
	);

	opts.onStatus?.("forking session");
	const fork = createEphemeralFork(opts.ctx);
	opts.onStatus?.("starting sub-agent");
	const { session } = await createAgentSession({
		cwd: opts.ctx.cwd,
		agentDir,
		model: opts.model,
		thinkingLevel: opts.thinkingLevel,
		modelRegistry: opts.ctx.modelRegistry,
		resourceLoader: loader,
		sessionManager: fork.manager,
		settingsManager,
	});
	await session.bindExtensions({});
	opts.onStatus?.("selecting tools");

	const activeTools = session
		.getAllTools()
		.map((tool) => tool.name)
		.filter((name) => !DISABLED_SUBAGENT_TOOLS.has(name));
	session.setActiveToolsByName(activeTools);

	const before = session.messages.length;
	let streamed = "";
	let lastEmit = 0;
	const emitText = (force = false) => {
		const now = Date.now();
		if (!force && now - lastEmit < 80) return;
		lastEmit = now;
		if (streamed.trim()) opts.onText?.(streamed);
	};
	const unsubscribe = session.subscribe((event) => {
		if (event.type === "tool_execution_start") opts.onTool?.(event.toolName);
		if (event.type === "message_update") {
			const fromPartial =
				"partial" in event.assistantMessageEvent
					? responseTextFromContent(
							event.assistantMessageEvent.partial.content,
						).trim()
					: "";
			if (fromPartial.length >= streamed.length) streamed = fromPartial;
			else if (event.assistantMessageEvent.type === "text_delta")
				streamed += event.assistantMessageEvent.delta;
			emitText();
		}
	});
	try {
		opts.onStatus?.("streaming");
		await withRoleTimeout(
			opts.role,
			opts.timeoutMs,
			opts.signal,
			async () => session.prompt(opts.userPrompt, { source: "extension" }),
			() => void session.abort(),
		);
		const newMessages = session.messages.slice(before) as Array<{
			role?: string;
			content?: unknown;
			stopReason?: string;
			errorMessage?: string;
		}>;
		const failed = [...newMessages]
			.reverse()
			.find(
				(message) =>
					message.role === "assistant" && message.stopReason === "error",
			);
		if (failed) throw new Error(failed.errorMessage || "Sub-agent failed");
		const text = extractAssistantText(newMessages) || streamed;
		if (!text.trim()) throw new Error("Sub-agent returned no visible text");
		opts.onText?.(text);
		return text;
	} finally {
		unsubscribe();
		session.dispose();
		fork.cleanup();
	}
}

async function runRound(
	round: number,
	maxRounds: number,
	idea: string,
	contextText: string,
	roundHistory: string,
	model: AnyModel,
	defenderModel: AnyModel,
	ctx: ExtensionContext,
	extensionMode: "all" | "off",
	devilThinkingLevel: ThinkingLevel,
	defenderThinkingLevel: ThinkingLevel,
	roleTimeoutMs: number,
	signal: AbortSignal | undefined,
	onStatus: RunDebateOptions["onStatus"],
	onChallenge: RunDebateOptions["onChallenge"],
	onPartial: RunDebateOptions["onPartial"],
): Promise<{
	devilOutput: string;
	proposerOutput: string;
	roundBlockingCount: number;
	aborted: boolean;
}> {
	onStatus?.(
		`Round ${round}/${maxRounds} · devil challenging`,
		round,
		maxRounds,
		0,
	);

	const devilUserText = buildRoundPrompt(
		round,
		maxRounds,
		idea,
		contextText,
		roundHistory,
	);
	const devilOutput = await runRoleAgent({
		ctx,
		model,
		systemPrompt: DEVIL_SYSTEM_PROMPT,
		userPrompt: devilUserText,
		signal,
		thinkingLevel: devilThinkingLevel,
		timeoutMs: roleTimeoutMs,
		role: "Devil",
		extensionMode,
		onStatus: (phase) =>
			onStatus?.(
				`Round ${round}/${maxRounds} · Devil ${phase}`,
				round,
				maxRounds,
				0,
			),
		onTool: (toolName) =>
			onStatus?.(
				`Round ${round}/${maxRounds} · Devil using ${toolName}`,
				round,
				maxRounds,
				0,
			),
		onText: (text) =>
			onPartial?.("devil", round, maxRounds, countBlockingIssues(text), text),
	});
	const roundBlockingCount = countBlockingIssues(devilOutput);
	onChallenge?.(round, maxRounds, roundBlockingCount, devilOutput);

	onStatus?.(
		`Round ${round}/${maxRounds} · Defense starting`,
		round,
		maxRounds,
		roundBlockingCount,
	);

	const proposerUserText = buildProposerPrompt(
		idea,
		roundHistory,
		round,
		devilOutput,
	);
	const proposerOutput = await runRoleAgent({
		ctx,
		model: defenderModel,
		systemPrompt: PROPOSER_SYSTEM_PROMPT,
		userPrompt: proposerUserText,
		signal,
		thinkingLevel: defenderThinkingLevel,
		timeoutMs: roleTimeoutMs,
		role: "Defense",
		extensionMode,
		onStatus: (phase) =>
			onStatus?.(
				`Round ${round}/${maxRounds} · Defense ${phase}`,
				round,
				maxRounds,
				roundBlockingCount,
			),
		onTool: (toolName) =>
			onStatus?.(
				`Round ${round}/${maxRounds} · Defense using ${toolName}`,
				round,
				maxRounds,
				roundBlockingCount,
			),
		onText: (text) =>
			onPartial?.("proposer", round, maxRounds, roundBlockingCount, text),
	});

	return {
		devilOutput,
		proposerOutput,
		roundBlockingCount,
		aborted: !!signal?.aborted,
	};
}

/** Synthesize the debate into a final verdict */
async function synthesizeDebate(
	idea: string,
	roundsData: string[],
	model: AnyModel,
	apiKey: string,
	headers: Record<string, string> | undefined,
	signal: AbortSignal | undefined,
	thinkingLevel: ThinkingLevel,
	roleTimeoutMs: number,
): Promise<SynthesisResult> {
	const synthesisUserText = [
		`Idea: ${idea}`,
		`Debate (${roundsData.length} rounds):`,
		roundsData.join("\n\n---\n\n"),
	].join("\n\n");

	const synthesisResponse = await withRoleTimeout(
		"Synthesis",
		roleTimeoutMs,
		signal,
		async (timeoutSignal) =>
			complete(
				model,
				{
					systemPrompt: SYNTHESIS_SYSTEM_PROMPT,
					messages: [
						{
							role: "user",
							content: [{ type: "text", text: synthesisUserText }],
							timestamp: Date.now(),
						},
					],
				},
				{
					apiKey,
					headers,
					signal: timeoutSignal,
					reasoning: thinkingLevel,
					cacheRetention: "none",
				},
			),
	);
	if (synthesisResponse.stopReason === "error") {
		throw new Error(synthesisResponse.errorMessage || "Synthesis failed");
	}

	return parseSynthesis(responseTextFromContent(synthesisResponse.content));
}

// ── Core debate logic ─────────────────────────────────────────────────

async function runDebate(opts: RunDebateOptions): Promise<DebateOutput> {
	const {
		idea,
		context,
		model,
		defenderModel,
		ctx,
		apiKey,
		headers,
		devilThinkingLevel,
		defenderThinkingLevel,
		synthesisThinkingLevel,
		roleTimeoutMs,
		maxRounds,
		extensionMode,
		stoppingConditions,
		concessionThreshold,
		signal,
		onStatus,
		onChallenge,
		onPartial,
		onRound,
	} = opts;

	const contextText = buildContextText(context);
	const roundsData: string[] = [];
	let blockingIssuesFound = 0;
	let consecutiveResolved = 0;
	let roundHistory = "";

	// Run debate rounds
	for (
		let round = 1;
		round <= maxRounds && consecutiveResolved < CONSENSUS_ROUNDS_REQUIRED;
		round++
	) {
		const earlyExit = checkAborted(signal, roundsData, blockingIssuesFound);
		if (earlyExit) return earlyExit;

		const { devilOutput, proposerOutput, roundBlockingCount, aborted } =
			await runRound(
				round,
				maxRounds,
				idea,
				contextText,
				roundHistory,
				model,
				defenderModel,
				ctx,
				extensionMode,
				devilThinkingLevel,
				defenderThinkingLevel,
				roleTimeoutMs,
				signal,
				onStatus,
				onChallenge,
				onPartial,
			);
		if (aborted) return abortedResult(roundsData, blockingIssuesFound);

		blockingIssuesFound += roundBlockingCount;

		roundsData.push(
			`### Round ${round}\n\n**Challenge:**\n${devilOutput}\n\n**Response:**\n${proposerOutput}`,
		);
		roundHistory += `### Round ${round}\n**Challenge:** ${devilOutput.slice(0, ROUND_HISTORY_TRUNCATE)}\n**Response:** ${proposerOutput.slice(0, ROUND_HISTORY_TRUNCATE)}\n\n`;

		const status = `Round ${round}/${maxRounds} · ${blockingIssuesFound} blocking raised`;
		onRound?.(
			round,
			maxRounds,
			blockingIssuesFound,
			status,
			devilOutput,
			proposerOutput,
		);

		// Check stopping conditions
		const concessionScore = calcConcessionScore(proposerOutput);
		if (stoppingConditions === "consensus") {
			if (concessionScore >= concessionThreshold) {
				consecutiveResolved++;
			} else {
				consecutiveResolved = 0;
			}
		} else if (
			stoppingConditions === "blocking_found" &&
			roundBlockingCount === 0
		) {
			break;
		} else if (stoppingConditions === "max_rounds" && round >= maxRounds) {
			break;
		}
	}

	const finalAbort = checkAborted(signal, roundsData, blockingIssuesFound);
	if (finalAbort) return finalAbort;

	onStatus?.(
		"Synthesizing verdict",
		roundsData.length,
		maxRounds,
		blockingIssuesFound,
	);
	const synthesis = await synthesizeDebate(
		idea,
		roundsData,
		model,
		apiKey,
		headers,
		signal,
		synthesisThinkingLevel,
		roleTimeoutMs,
	);

	return {
		synthesis: formatSynthesis(synthesis),
		roundsData,
		recommendation: synthesis.recommendation,
		blockingRaised: blockingIssuesFound,
		blockingRemaining: synthesis.blocking.length,
	};
}

function resolveRoundConfig(
	pi: ExtensionAPI,
	settings: DevilSettings,
): { value: number; source: string } {
	const raw = pi.getFlag("devil-rounds");
	const fallback = settings.maxRounds ?? DEFAULT_MAX_ROUNDS;
	const value = Math.max(
		1,
		Math.min(5, Number(raw ?? fallback) || DEFAULT_MAX_ROUNDS),
	);
	const source =
		raw !== undefined && String(raw) !== String(fallback)
			? "flag"
			: settings.maxRounds !== undefined
				? "settings"
				: "default";
	return { value, source };
}

function resolveRoleTimeoutMs(settings: DevilSettings): number {
	const value = Number(settings.roleTimeoutMs ?? DEFAULT_ROLE_TIMEOUT_MS);
	if (!Number.isFinite(value)) return DEFAULT_ROLE_TIMEOUT_MS;
	return Math.max(10_000, Math.min(600_000, value));
}

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

export default async function (pi: ExtensionAPI) {
	gcEphemeralForks();
	const settings = (pi as SettingsAPI).settingsManager?.getSettings();
	const devilSettings: DevilSettings = (settings?.devil ?? {}) as DevilSettings;
	const activeControllers = new Set<AbortController>();

	// ── Flags ─────────────────────────────────────────────────────────

	pi.registerFlag("devil-rounds", {
		description: "Override max debate rounds (1-5)",
		type: "string",
		default: String(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: cancel active debates on shutdown ────────────────────────
	pi.on("session_shutdown", async () => {
		for (const controller of activeControllers) controller.abort();
		activeControllers.clear();
	});

	// ── Command: /devil ────────────────────────────────────────────────

	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;
			}
			const model = resolveDebateModel(ctx, devilSettings.model);
			if (!model) {
				ctx.ui?.notify("No model selected. Use /model first.", "error");
				return;
			}

			const defenderModel = resolveDebateModel(
				ctx,
				devilSettings.defenderModel,
			);
			if (!defenderModel) {
				ctx.ui?.notify(
					"No defender model selected. Use /model first or set devil.defenderModel.",
					"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 defenderAuth =
				await ctx.modelRegistry.getApiKeyAndHeaders(defenderModel);
			if (!defenderAuth.ok || !defenderAuth.apiKey) {
				ctx.ui?.notify(
					`No API key for defender ${defenderModel.provider}`,
					"error",
				);
				return;
			}

			const usage = ctx.getContextUsage();
			const contextLimit = devilContextLimit(
				usage?.tokens,
				model,
				defenderModel,
			);
			if (!contextLimit.ok) {
				ctx.ui.notify(
					`Devil blocked: projected context ${formatTokenCount(contextLimit.projectedTokens)}/${formatTokenCount(contextLimit.minContextWindow)} (${contextLimit.percent.toFixed(1)}%) exceeds safe limit ${formatTokenCount(contextLimit.limitTokens)} for ${model.provider}/${model.id} ∧ ${defenderModel.provider}/${defenderModel.id}. Run /compact, then retry /devil.`,
					"error",
				);
				ctx.ui.setEditorText(`/devil ${idea}`);
				return;
			}

			const roundConfig = resolveRoundConfig(pi, devilSettings);
			const maxRounds = roundConfig.value;
			const extensionMode =
				devilSettings.extensionMode ?? DEFAULT_EXTENSION_MODE;
			const roleTimeoutMs = resolveRoleTimeoutMs(devilSettings);
			const defaultThinkingLevel = normalizeThinkingLevel(
				devilSettings.thinkingLevel,
			);
			const devilThinkingLevel =
				normalizeThinkingLevel(devilSettings.devilThinkingLevel) ??
				defaultThinkingLevel ??
				DEFAULT_DEVIL_THINKING;
			const defenderThinkingLevel =
				normalizeThinkingLevel(devilSettings.defenderThinkingLevel) ??
				defaultThinkingLevel ??
				DEFAULT_DEFENDER_THINKING;
			const synthesisThinkingLevel =
				normalizeThinkingLevel(devilSettings.synthesisThinkingLevel) ??
				defaultThinkingLevel ??
				DEFAULT_SYNTHESIS_THINKING;
			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<DebateOutput | null>(
					(tui, theme, _kb, done) => {
						const live = createDebateState(idea, maxRounds);
						setDebateStatus(
							live,
							`Starting · ${maxRounds} rounds (${roundConfig.source}) · timeout ${Math.round(roleTimeoutMs / 1000)}s · D:${devilThinkingLevel} F:${defenderThinkingLevel} S:${synthesisThinkingLevel} · defender ${defenderModel.id} · extensions ${extensionMode}`,
							0,
							0,
						);
						const review = new DebateReviewComponent(
							tui,
							theme,
							live,
							done,
							debateController,
						);

						runDebate({
							idea,
							context: debateContext,
							model,
							defenderModel,
							ctx,
							apiKey: auth.apiKey!,
							headers: auth.headers,
							devilThinkingLevel,
							defenderThinkingLevel,
							synthesisThinkingLevel,
							roleTimeoutMs,
							maxRounds,
							extensionMode,
							stoppingConditions,
							concessionThreshold,
							signal: review.signal,
							onStatus: (status, round, _max, blocking) => {
								if (!review.isActive()) return;
								setDebateStatus(live, status, round, blocking);
								review.refresh();
							},
							onPartial: (role, round, _max, blocking, text) => {
								if (!review.isActive()) return;
								upsertDebateEntry(live, role, round, blocking, text, false);
								review.refresh();
							},
							onChallenge: (round, _max, blocking, devilOutput) => {
								if (!review.isActive()) return;
								upsertDebateEntry(
									live,
									"devil",
									round,
									blocking,
									devilOutput,
									true,
								);
								review.refresh();
							},
							onRound: (
								round,
								_max,
								blocking,
								_status,
								_devilOutput,
								proposerOutput,
							) => {
								if (!review.isActive()) return;
								upsertDebateEntry(
									live,
									"proposer",
									round,
									blocking,
									proposerOutput,
									true,
								);
								review.refresh();
							},
						})
							.then((output) => review.finish(output.aborted ? null : output))
							.catch((err) => {
								if (!review.signal.aborted && review.isActive()) {
									failedMessage = formatDebateError(err);
									console.error("[devil] runDebate error:", err);
									live.error = failedMessage;
									setDebateStatus(
										live,
										"Failed",
										live.currentRound,
										live.blocking,
									);
									ctx.ui.notify(`Debate failed: ${failedMessage}`, "error");
									review.fail();
									return;
								}
								review.finish(null);
							});

						return review;
					},
				);
			} finally {
				debateController.abort();
				activeControllers.delete(debateController);
			}

			await handleDebateResult(
				idea,
				result,
				failedMessage,
				onBlocking,
				ctx.ui,
				pi,
			);
		},
	});
}