repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/agent/extensions/devil/index.ts
RawFile outline
- DEVIL_SYSTEM_PROMPT line 59
- PROPOSER_SYSTEM_PROMPT line 82
- SYNTHESIS_SYSTEM_PROMPT line 99
- DEFAULT_MAX_ROUNDS line 124
- DEFAULT_STOPPING_CONDITIONS line 125
- DEFAULT_CONCESSION_THRESHOLD line 126
- DEFAULT_ON_BLOCKING line 127
- DevilSettings line 130
- model line 131
- maxRounds line 132
- stoppingConditions line 133
- concessionThreshold line 134
- onBlocking line 135
- SynthesisResult line 138
- recommendation line 139
- summary line 140
- blocking line 141
- addressable line 142
- survived line 143
- conceded line 144
- next_steps line 145
- RunDebateOptions line 148
- idea line 149
- context line 150
- model line 151
- apiKey line 152
- headers line 153
- maxRounds line 154
- stoppingConditions line 155
- concessionThreshold line 156
- signal line 157
- onStatus line 158
- onChallenge line 160
- onRound line 167
- DebateRole line 177
- DebateTranscriptEntry line 179
- role line 180
- round line 181
- text line 182
- blocking line 183
- DebateLiveState line 186
- idea line 187
- maxRounds line 188
- status line 189
- currentRound line 190
- blocking line 191
- entries line 192
- startedAt line 193
- MAX_FILE_CHARS line 198
- MAX_FILES line 199
- FILE_TOOL_NAMES line 200
- ToolCallBlock line 202
- type line 203
- name line 204
- arguments line 205
- createDebateState line 208
- setDebateStatus line 220
- addDebateEntry line 231
- padToWidth line 245
- frameLine line 251
- renderDebateTranscript line 261
- DebateReviewComponent line 295
- scrollOffset line 296
- followMode line 297
- finished line 298
- disposed line 299
- cachedBodyWidth line 300
- cachedBodyKey line 301
- cachedBody line 302
- constructor line 304
- signal line 312
- isActive line 316
- cancel line 320
- finish line 325
- refresh line 332
- handleInput line 337
- getBody line 377
- render line 397
- invalidate line 426
- dispose line 432
- gatherContext line 438
- type line 498
- formatSynthesis line 514
- resolveDebateModel line 550
- parseSynthesis line 570
- runRound line 615
- synthesizeDebate line 649
- runDebate line 677
- formatDebateOutput line 735
/**
* 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": 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 * as fs from "node:fs";
import * as path from "node:path";
import { complete } from "@earendil-works/pi-ai";
import {
convertToLlm,
serializeConversation,
} from "@earendil-works/pi-coding-agent";
import type {
ExtensionAPI,
ExtensionContext,
Model,
SessionEntry,
} from "@earendil-works/pi-coding-agent";
import type { Theme } from "@earendil-works/pi-coding-agent";
import {
matchesKey,
truncateToWidth,
visibleWidth,
wrapTextWithAnsi,
type Component,
type TUI,
} from "@earendil-works/pi-tui";
import type { DebateOutput } from "./types";
import {
textFromContent,
abortedResult,
checkAborted,
countBlockingIssues,
calcConcessionScore,
buildContextText,
buildRoundPrompt,
buildProposerPrompt,
cleanTranscriptText,
ROUND_HISTORY_TRUNCATE,
CONSENSUS_ROUNDS_REQUIRED,
} from "./helpers";
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;
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<string, unknown>;
}
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 });
}
// ── State helpers ───────────────────────────────────────────────────
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 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<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\`\`\`\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;
}
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,
): 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: [],
};
}
// ── Debate orchestration ────────────────────────────────────────────
async function runRound(
round: number,
maxRounds: number,
idea: string,
contextText: string,
roundHistory: string,
model: Model,
apiKey: string,
headers: Record<string, string> | undefined,
signal: AbortSignal | undefined,
onStatus: RunDebateOptions["onStatus"],
): 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 devilResponse = await complete(model, { systemPrompt: DEVIL_SYSTEM_PROMPT, messages: [{ role: "user", content: [{ type: "text", text: devilUserText }], timestamp: Date.now() }] }, { apiKey, headers, signal });
const devilOutput = textFromContent(devilResponse.content);
const roundBlockingCount = countBlockingIssues(devilOutput);
onStatus?.(`Round ${round}/${maxRounds} · proposer defending`, round, maxRounds, roundBlockingCount);
const proposerUserText = buildProposerPrompt(idea, roundHistory, round, devilOutput);
const proposerResponse = await complete(model, { systemPrompt: PROPOSER_SYSTEM_PROMPT, messages: [{ role: "user", content: [{ type: "text", text: proposerUserText }], timestamp: Date.now() }] }, { apiKey, headers, signal });
const proposerOutput = textFromContent(proposerResponse.content);
return { devilOutput, proposerOutput, roundBlockingCount, aborted: !!signal?.aborted };
}
/** Synthesize the debate into a final verdict */
async function synthesizeDebate(
idea: string,
roundsData: string[],
model: Model,
apiKey: string,
headers: Record<string, string> | undefined,
signal: AbortSignal | undefined,
): Promise<SynthesisResult> {
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 },
);
return parseSynthesis(textFromContent(synthesisResponse.content));
}
// ── Core debate logic ─────────────────────────────────────────────────
async function runDebate(opts: RunDebateOptions): Promise<DebateOutput> {
const { idea, context, model, apiKey, headers, maxRounds, stoppingConditions, concessionThreshold, signal, onStatus, onChallenge, 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, apiKey, headers, signal, onStatus,
);
if (aborted) return abortedResult(roundsData, blockingIssuesFound);
blockingIssuesFound += roundBlockingCount;
onChallenge?.(round, maxRounds, blockingIssuesFound, devilOutput);
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);
return {
synthesis: formatSynthesis(synthesis),
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<AbortController>();
// ── 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: 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 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<DebateOutput | null>(
(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);
}
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,
);
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);
},
});
}