repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/agent/extensions/devil/index.ts
RawFile outline
- DEVIL_SYSTEM_PROMPT line 33
- PROPOSER_SYSTEM_PROMPT line 59
- SYNTHESIS_SYSTEM_PROMPT line 74
- DEFAULT_MAX_ROUNDS line 104
- DEFAULT_STOPPING_CONDITIONS line 105
- DEFAULT_CONCESSION_THRESHOLD line 106
- DEFAULT_ON_BLOCKING line 107
- DevilSettings line 109
- model line 110
- maxRounds line 111
- stoppingConditions line 112
- concessionThreshold line 113
- onBlocking line 114
- text line 260
- type line 260
- text line 273
- type line 273
- text line 310
- type line 310
/**
* 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 a debate
* Call devils_advocate tool
*
* Configuration (settings.json):
* {
* "devilsAdvocate": {
* "model": "anthropic/claude-haiku-4-5", // Optional: specific model
* "maxRounds": 5, // Maximum debate rounds
* "stoppingConditions": "consensus", // consensus | blocking_found | max_rounds
* "concessionThreshold": 0.7, // 0.0-1.0 for concession detection
* "onBlocking": "surface" // surface | escalate | ignore
* }
* }
*
* Pi Session Implications:
* - Debates are stateless (no persistence between calls)
* - Uses current session's model and API credentials
* - Results are returned as tool output, not added to conversation
* - Context from current conversation is NOT automatically included
*/
import { Type } from "@sinclair/typebox";
import { complete, type Message } from "@mariozechner/pi-ai";
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
const DEVIL_SYSTEM_PROMPT = `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.
EXAMPLES:
- "Req auth missing" → blocking
- "Users confused" → addressable (add onboarding)
- "Assumes fast net" → assumed (premise fragile)
- "Blue vs green button" → minor
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.
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.
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 debate. Produce honest summary. Help user decide.
CLASSIFICATION:
- **blocking**: Must fix
- **addressable**: Has mitigations
- **assumed**: Premise unverified
- **minor**: Not worth fixing
OUTPUT:
## Summary
**Recommendation:** proceed / proceed_with_caution / revise / abandon
### Blocking Issues
- [concern] → [fix]
### Addressable Concerns
- [concern] → [mitigation]
### Survived
- [claims that held]
### Conceded
- [acknowledged weaknesses]
### Next Steps
1. [action]
2. [action]`;
// Default settings
const DEFAULT_MAX_ROUNDS = 5;
const DEFAULT_STOPPING_CONDITIONS = "consensus";
const DEFAULT_CONCESSION_THRESHOLD = 0.7;
const DEFAULT_ON_BLOCKING = "surface";
interface DevilSettings {
model?: string;
maxRounds?: number;
stoppingConditions?: "consensus" | "blocking_found" | "max_rounds";
concessionThreshold?: number;
onBlocking?: "surface" | "escalate" | "ignore";
}
export default async function (pi: ExtensionAPI) {
// Read settings
const settings = pi.settingsManager?.getSettings();
const devilSettings: DevilSettings = settings?.devilsAdvocate ?? {};
// Register the devil's advocate tool
pi.registerTool({
name: "devils_advocate",
label: "Devil's Advocate",
description: `Debate tool. STRESS TEST ideas. Surface blocking issues before committing.
Parameters:
- idea: Idea to debate (req)
- context: Background kvpairs (opt)
- model: Model override (opt)
- maxRounds: 1-10 rounds (default: ${devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS})
- stakeholder: security | cost | ux | impl | ethics | skeptical
- stoppingConditions: When stop (default: ${devilSettings.stoppingConditions ?? DEFAULT_STOPPING_CONDITIONS})
- output: full | summary_only`,
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(
Type.Union([
Type.Literal("security"),
Type.Literal("cost"),
Type.Literal("ux"),
Type.Literal("implementation"),
Type.Literal("ethics"),
Type.Literal("skeptical"),
])
),
stoppingConditions: Type.Optional(
Type.Union([
Type.Literal("consensus"),
Type.Literal("blocking_found"),
Type.Literal("max_rounds"),
])
),
concessionThreshold: Type.Optional(
Type.Number({ minimum: 0, maximum: 1 })
),
onBlocking: Type.Optional(
Type.Union([
Type.Literal("surface"),
Type.Literal("escalate"),
Type.Literal("ignore"),
])
),
output: Type.Optional(
Type.Union([Type.Literal("full"), Type.Literal("summary_only")])
),
}),
execute: async (_toolCallId, params, signal, onUpdate, ctx) => {
const {
idea,
context,
model: modelOverride,
maxRounds: maxRoundsParam,
stakeholder,
stoppingConditions: stoppingConditionsParam,
concessionThreshold: concessionThresholdParam,
onBlocking: onBlockingParam,
output = "summary_only"
} = params;
const maxRounds = maxRoundsParam ?? devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS;
const stoppingConditions = stoppingConditionsParam ?? devilSettings.stoppingConditions ?? DEFAULT_STOPPING_CONDITIONS;
const concessionThreshold = concessionThresholdParam ?? devilSettings.concessionThreshold ?? DEFAULT_CONCESSION_THRESHOLD;
const onBlocking = onBlockingParam ?? devilSettings.onBlocking ?? DEFAULT_ON_BLOCKING;
// Determine which model to use
let model = ctx.model;
if (modelOverride) {
const [provider, modelId] = modelOverride.includes("/")
? modelOverride.split("/")
: [modelOverride, modelOverride];
const foundModel = ctx.modelRegistry.find(provider, modelId);
if (foundModel) model = foundModel;
} else if (devilSettings.model && ctx.model) {
const [provider, modelId] = devilSettings.model.includes("/")
? devilSettings.model.split("/")
: [ctx.model.provider, devilSettings.model];
const foundModel = ctx.modelRegistry.find(provider, modelId);
if (foundModel) model = foundModel;
}
if (!model) {
return {
content: [{ type: "text", text: "Error: No model available. Select a model first with /model." }],
details: { error: "No model" },
};
}
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
if (!auth.ok || !auth.apiKey) {
return {
content: [{ type: "text", text: `Error: No API key for ${model.provider}` }],
details: { error: "No API key" },
};
}
const contextText = context
? Object.entries(context).map(([k, v]) => `- **${k}**: ${v}`).join("\n")
: "No additional context provided.";
const stakeholderContext = stakeholder
? `\n\n**Focus:** Challenge specifically from ${stakeholder} perspective.`
: "";
// Stream initial output
onUpdate?.({
content: [{ type: "text", text: `## 🗡️ Devil's Advocate Debate\n\n**Idea:** ${idea}\n\n**Context:**\n${contextText}\n\n**Config:** maxRounds=${maxRounds}, stopping=${stoppingConditions}, blocking=${onBlocking}\n**Model:** ${model.provider}/${model.id}\n\n---\n\n` }],
details: {},
});
try {
const rounds_data: string[] = [];
let blockingIssuesFound = 0;
let consecutiveResolved = 0;
let shouldContinue = true;
for (let i = 1; i <= maxRounds && shouldContinue; i++) {
// Devil's challenge
const devilMessages: Message[] = [
{ role: "system", content: [{ type: "text", text: DEVIL_SYSTEM_PROMPT }], timestamp: Date.now() },
{ role: "user", content: [{ type: "text", text: `Context:\n${contextText}${stakeholderContext}\n\nIdea: ${idea}\n\nRound ${i}/${maxRounds}. Identify the most blocking concern.` }], timestamp: Date.now() },
];
const devilResponse = await complete(model, { systemPrompt: "", messages: devilMessages }, { apiKey: auth.apiKey, headers: auth.headers, signal });
const devilOutput = devilResponse.content.filter((c): c is { type: "text"; text: string } => c.type === "text").map(c => c.text).join("\n");
// Count blocking issues
const roundBlockingCount = (devilOutput.match(/\[blocking\]/gi) || []).length;
blockingIssuesFound = Math.max(blockingIssuesFound, roundBlockingCount);
// Proposer's rebuttal
const proposerMessages: Message[] = [
{ role: "system", content: [{ type: "text", text: PROPOSER_SYSTEM_PROMPT }], timestamp: Date.now() },
{ role: "user", content: [{ type: "text", text: `Your idea: ${idea}\n\nChallenges:\n${devilOutput}\n\nRespond to these challenges.` }], timestamp: Date.now() },
];
const proposerResponse = await complete(model, { systemPrompt: "", messages: proposerMessages }, { apiKey: auth.apiKey, headers: auth.headers, signal });
const proposerOutput = proposerResponse.content.filter((c): c is { type: "text"; text: string } => c.type === "text").map(c => c.text).join("\n");
rounds_data.push(`### Round ${i}\n\n**Challenge:**\n${devilOutput}\n\n**Your Response:**\n${proposerOutput}`);
// Stream round result
onUpdate?.({
content: [{ type: "text", text: `### Round ${i}/${maxRounds}\n\n**Challenge identified.** Respond above.\n\n` }],
details: { round: i, blockingCount: roundBlockingCount },
});
// Check stopping conditions
const resolvedCount = (proposerOutput.match(/\*\*status\*\*:\s*resolved|status:\s*resolved/gi) || []).length;
const concessionIndicators = (proposerOutput.match(/fair point|good point|you're right|concede|acknowledge/i) || []).length;
const concessionScore = resolvedCount + (concessionIndicators * 0.5);
if (stoppingConditions === "consensus" && concessionScore >= concessionThreshold) {
consecutiveResolved++;
if (consecutiveResolved >= 2) {
shouldContinue = false;
}
} else if (stoppingConditions === "blocking_found" && roundBlockingCount === 0) {
shouldContinue = false;
} else if (stoppingConditions === "max_rounds") {
// Always continue until max_rounds
shouldContinue = i < maxRounds;
}
if (resolvedCount > 0) consecutiveResolved++;
}
// Synthesis
const synthesisMessages: Message[] = [
{ role: "system", content: [{ type: "text", text: SYNTHESIS_SYSTEM_PROMPT }], timestamp: Date.now() },
{ role: "user", content: [{ type: "text", text: `Idea: ${idea}\n\nDebate (${rounds_data.length} rounds):\n${rounds_data.join("\n\n---\n\n")}` }], timestamp: Date.now() },
];
const synthesisResponse = await complete(model, { systemPrompt: "", messages: synthesisMessages }, { apiKey: auth.apiKey, headers: auth.headers, signal });
const synthesisOutput = synthesisResponse.content.filter((c): c is { type: "text"; text: string } => c.type === "text").map(c => c.text).join("\n");
// Parse recommendation
const recMatch = synthesisOutput.match(/\*\*recommendation\*\*:\s*(\w+)/i);
let recommendation = "proceed_with_caution";
if (recMatch) {
recommendation = recMatch[1].toLowerCase();
if (!["proceed", "proceed_with_caution", "revise", "abandon"].includes(recommendation)) {
recommendation = "proceed_with_caution";
}
}
// Handle blocking issues based on onBlocking setting
let blockingNote = "";
if (blockingIssuesFound > 0 && onBlocking === "escalate") {
blockingNote = `\n\n⚠️ **${blockingIssuesFound} blocking issue(s) found.** Review before proceeding.`;
} else if (blockingIssuesFound > 0 && onBlocking === "ignore") {
blockingNote = "";
}
const outputText = output === "full"
? `## Full Debate\n\n${rounds_data.join("\n\n---\n\n")}\n\n---\n\n## Summary\n\n${synthesisOutput}${blockingNote}\n\n**Debate:** ${rounds_data.length} rounds | **Blocking issues:** ${blockingIssuesFound}`
: `${synthesisOutput}${blockingNote}\n\n*Debate: ${rounds_data.length} rounds | Blocking: ${blockingIssuesFound}*`;
return {
content: [{ type: "text", text: outputText }],
details: { recommendation, rounds: rounds_data.length, blockingIssues: blockingIssuesFound },
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
content: [{ type: "text", text: `## Debate Failed\n\nError: ${message}` }],
details: { error: message },
};
}
},
});
// Register the /devil command
pi.registerCommand("devil", {
description: "Start a devil's advocate debate",
handler: async (args, ctx) => {
const idea = args.trim();
if (!idea) {
ctx.ui?.notify("Usage: /devil <your idea>", "error");
return;
}
await ctx.tools?.invoke("devils_advocate", {
idea,
maxRounds: devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS,
stoppingConditions: (devilSettings.stoppingConditions as any) ?? DEFAULT_STOPPING_CONDITIONS,
});
},
});
}