repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi(ext/devil): move into dir, add README and types

84b39b567aff97467aeb0e8f8c70ae0c061410d7

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (3)

pi/agent/extensions/devil/README.md

Added
new file mode 100644
1 +# devil
3 +Structured debate tool for stress-testing ideas against a devil's advocate. Canonical names:
5 +- Slash command: `/devil <idea>`
6 +- Tool: `devil`
7 +- Settings key: `devil`
8 +- Extension dir: `extensions/devil/`
9 +- Shortcut: `ctrl+alt+d` starts `/devil` with current editor text
11 +## Quick Start
13 +```bash
14 +pi
15 +/devil we should switch to microservices
16 +```
18 +Tool call:
20 +```javascript
21 +devil({
22 + idea: "Use SQLite as primary database",
23 + context: {
24 + scale: "10k users",
25 + team_size: "5 devs",
26 + requirement: "ACID required"
27 + }
28 +})
29 +```
31 +## Behavior
33 +| Aspect | Behavior |
34 +|--------|----------|
35 +| Session state | Stateless. Each debate call is independent. |
36 +| Conversation context | Automatically includes working dir, recent conversation, current contents of recently touched files. Explicit `context` overrides/augments it. |
37 +| Model | Uses `devil.model` if configured, else current model. Tool `model` param overrides both. |
38 +| UI | `/devil` opens interactive progress UI, then result editor. Tool call streams round updates. |
39 +| Results | Tool result stored in conversation like normal tool output. `/devil` writes edited result into main editor for user submission. |
41 +## Configuration
43 +`~/.pi/agent/settings.json`:
45 +```json
47 + "devil": {
48 + "model": "zai/glm-5.1",
49 + "maxRounds": 5,
50 + "stoppingConditions": "consensus",
51 + "concessionThreshold": 0.7,
52 + "onBlocking": "surface"
53 + }
55 +```
57 +CLI flags:
59 +```bash
60 +pi --devil-max-rounds 3 --devil-stop max_rounds
61 +```
63 +## Parameters
65 +```javascript
66 +devil({
67 + idea: string, // required
68 + context?: Record<string,string>, // optional extra background
69 + model?: string, // optional provider/model override
70 + maxRounds?: number, // 1-10
71 + stakeholder?: "security" | "cost" | "ux" | "implementation" | "ethics" | "skeptical",
72 + stoppingConditions?: "consensus" | "blocking_found" | "max_rounds",
73 + concessionThreshold?: number, // 0.0-1.0
74 + onBlocking?: "surface" | "escalate" | "ignore",
75 + output?: "full" | "summary_only"
76 +})
77 +```
79 +## Output
81 +Returns synthesis with:
83 +- recommendation: `proceed`, `proceed_with_caution`, `revise`, `abandon`
84 +- blocking issues
85 +- addressable concerns
86 +- survived claims
87 +- conceded weaknesses
88 +- next steps
89 +- debate metadata: rounds, blocking challenges raised, unresolved blocking issues in final verdict
91 +## When to Use
93 +Good:
94 +- Before architectural/impl decisions
95 +- When responses feel too agreeable
96 +- To surface blocking issues before committing
97 +- To document concerns for stakeholders
99 +Not ideal:
100 +- Quick questions
101 +- Already contested decisions
102 +- Sensitive/personal topics
104 +## Troubleshooting
106 +### "No model available"
108 +Select model with `/model`, or configure `devil.model`.
110 +### "No API key"
112 +Log in / configure key for selected or configured provider.
114 +### Irrelevant challenges
116 +Add explicit `context`, choose `stakeholder`, make `idea` more specific.

pi/agent/extensions/devil/index.ts

Modified
7 7 * Usage:
8 8 * /devil <your idea> - Start an interactive debate with live progress
9 - * Call devils_advocate tool - Non-interactive debate (for LLM use)
9 + * Call devil tool - Non-interactive debate (for LLM use)
11 11 * Configuration (settings.json):
13 - * "devilsAdvocate": {
14 - * "model": "anthropic/claude-haiku-4-5", // Optional: specific model
13 + * "devil": {
14 + * "model": "zai/glm-5.1", // Optional: specific model
15 15 * "maxRounds": 5, // Maximum debate rounds
16 16 * "stoppingConditions": "consensus", // consensus | blocking_found | max_rounds
17 17 * "concessionThreshold": 0.7, // 0.0-1.0 for concession detection
23 -import { Type } from "@sinclair/typebox";
23 +import { Type } from "typebox";
24 24 import * as fs from "node:fs";
25 25 import * as path from "node:path";
26 -import { complete, StringEnum, type Message } from "@mariozechner/pi-ai";
26 +import { complete, StringEnum } from "@mariozechner/pi-ai";
27 27 import {
28 - BorderedLoader,
29 28 convertToLlm,
30 29 serializeConversation,
31 30 } from "@mariozechner/pi-coding-agent";
35 34 Model,
36 35 SessionEntry,
37 36 } from "@mariozechner/pi-coding-agent";
38 -import { Text } from "@mariozechner/pi-tui";
39 -import { Key } from "@mariozechner/pi-tui";
37 +import {
38 + Key,
39 + Text,
40 + matchesKey,
41 + truncateToWidth,
42 + visibleWidth,
43 + wrapTextWithAnsi,
44 + type Component,
45 + type TUI,
46 +} from "@mariozechner/pi-tui";
40 47 import type { DebateOutput } from "./types";
42 49 const DEVIL_SYSTEM_PROMPT = `Devil advocate. STRESS TEST ideas. Find blocking issues.
137 144 stoppingConditions: "consensus" | "blocking_found" | "max_rounds";
138 145 concessionThreshold: number;
139 146 signal?: AbortSignal;
147 + onStatus?: (status: string, round: number, maxRounds: number, blocking: number) => void;
140 148 /** Fires after devil responds, before proposer responds (mid-round update) */
141 149 onChallenge?: (
142 150 round: number,
155 163 ) => void;
158 -// ── Helpers ───────────────────────────────────────────────────────────
166 +type DebateRole = "devil" | "proposer";
168 +interface DebateTranscriptEntry {
169 + role: DebateRole;
170 + round: number;
171 + text: string;
172 + blocking: number;
175 +interface DebateLiveState {
176 + idea: string;
177 + maxRounds: number;
178 + status: string;
179 + currentRound: number;
180 + blocking: number;
181 + entries: DebateTranscriptEntry[];
182 + startedAt: number;
185 +// ── Helpers ───────────────────────────────────────────────────────────
161 187 const MAX_FILE_CHARS = 3000; // per-file cap for context injection
162 188 const MAX_FILES = 10; // max files to include
168 194 arguments: Record<string, unknown>;
197 +export function createDebateState(idea: string, maxRounds: number): DebateLiveState {
198 + return {
199 + idea,
200 + maxRounds,
201 + status: "Starting debate...",
202 + currentRound: 0,
203 + blocking: 0,
204 + entries: [],
205 + startedAt: Date.now(),
206 + };
209 +function setDebateStatus(
210 + state: DebateLiveState,
211 + status: string,
212 + round: number,
213 + blocking: number,
214 +) {
215 + state.status = status;
216 + state.currentRound = round;
217 + state.blocking = blocking;
220 +function addDebateEntry(
221 + state: DebateLiveState,
222 + role: DebateRole,
223 + round: number,
224 + blocking: number,
225 + text: string,
226 +) {
227 + state.currentRound = round;
228 + state.blocking = blocking;
229 + state.entries.push({ role, round, blocking, text });
232 +function cleanTranscriptText(text: string, maxChars: number): string {
233 + const clean = text.replace(/\r/g, "").replace(/\n{3,}/g, "\n\n").trim();
234 + if (clean.length <= maxChars) return clean;
235 + return `${clean.slice(0, maxChars).trimEnd()}…`;
238 +function padToWidth(line: string, width: number): string {
239 + const target = Math.max(0, width);
240 + const truncated = truncateToWidth(line, target);
241 + return truncated + " ".repeat(Math.max(0, target - visibleWidth(truncated)));
244 +function frameLine(theme: Theme, left: string, content: string, right: string, width: number): string {
245 + if (width <= 0) return "";
246 + if (width === 1) return truncateToWidth(theme.fg("border", left), width);
247 + const innerWidth = Math.max(0, width - 2);
248 + return truncateToWidth(
249 + theme.fg("border", left) + padToWidth(content, innerWidth) + theme.fg("border", right),
250 + width,
251 + );
254 +export function renderDebateTranscript(
255 + state: DebateLiveState,
256 + theme: Theme,
257 + width: number,
258 + options: { compact: boolean; maxBodyLines: number },
259 +): string[] {
260 + if (width <= 0) return [""];
261 + const lines: string[] = [];
262 + const usableWidth = width;
263 + const elapsed = Math.floor((Date.now() - state.startedAt) / 1000);
264 + const header = `Review: ${state.status} · ${state.blocking} blocking · ${elapsed}s`;
265 + lines.push(theme.fg("accent", truncateToWidth(header, usableWidth)));
267 + const entries = options.compact ? state.entries.slice(-2) : state.entries;
268 + if (entries.length === 0) {
269 + lines.push(theme.fg("dim", truncateToWidth(" Waiting for first challenge...", usableWidth)));
270 + return lines.map((line) => truncateToWidth(line, usableWidth));
273 + for (const entry of entries) {
274 + const icon = entry.role === "devil" ? "⚑" : "✓";
275 + const label = entry.role === "devil" ? "Devil" : "Defense";
276 + lines.push(theme.fg(entry.role === "devil" ? "warning" : "success", truncateToWidth(`${icon} R${entry.round} ${label}`, usableWidth)));
278 + const bodyWidth = Math.max(1, usableWidth - 2);
279 + const body = cleanTranscriptText(entry.text, options.compact ? 700 : 20000);
280 + const wrapped = wrapTextWithAnsi(theme.fg("dim", body), bodyWidth).slice(0, options.maxBodyLines);
281 + for (const line of wrapped) lines.push(truncateToWidth(` ${line}`, usableWidth));
284 + return lines.map((line) => truncateToWidth(line, usableWidth));
287 +export class DebateWidget implements Component {
288 + constructor(
289 + private theme: Theme,
290 + private state: DebateLiveState,
291 + ) {}
293 + render(width: number): string[] {
294 + return renderDebateTranscript(this.state, this.theme, width, {
295 + compact: true,
296 + maxBodyLines: 3,
297 + }).slice(-9).map((line) => truncateToWidth(line, width));
300 + invalidate(): void {}
303 +export class DebateReviewComponent implements Component {
304 + private scrollOffset = 0;
305 + private followMode = true;
306 + private finished = false;
307 + private disposed = false;
308 + private cachedBodyWidth?: number;
309 + private cachedBodyKey?: string;
310 + private cachedBody?: string[];
312 + constructor(
313 + private tui: TUI,
314 + private theme: Theme,
315 + private state: DebateLiveState,
316 + private done: (output: DebateOutput | null) => void,
317 + private controller: AbortController,
318 + ) {}
320 + get signal(): AbortSignal {
321 + return this.controller.signal;
324 + isActive(): boolean {
325 + return !this.finished && !this.disposed && !this.signal.aborted;
328 + cancel() {
329 + this.controller.abort();
330 + this.finish(null);
333 + finish(output: DebateOutput | null) {
334 + if (this.finished || this.disposed) return;
335 + if (output === null) this.controller.abort();
336 + this.finished = true;
337 + this.done(output);
340 + refresh() {
341 + if (!this.isActive()) return;
342 + this.tui.requestRender();
345 + handleInput(data: string): void {
346 + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || data === "q") {
347 + this.cancel();
348 + return;
350 + if (matchesKey(data, "up") || data === "k") {
351 + this.followMode = false;
352 + this.scrollOffset = Math.max(0, this.scrollOffset - 1);
353 + this.refresh();
354 + return;
356 + if (matchesKey(data, "down") || data === "j") {
357 + this.scrollOffset++;
358 + this.refresh();
359 + return;
361 + if (matchesKey(data, "pageup") || matchesKey(data, "ctrl+u")) {
362 + this.followMode = false;
363 + this.scrollOffset = Math.max(0, this.scrollOffset - 10);
364 + this.refresh();
365 + return;
367 + if (matchesKey(data, "pagedown") || matchesKey(data, "ctrl+d")) {
368 + this.scrollOffset += 10;
369 + this.refresh();
370 + return;
372 + if (data === "g") {
373 + this.followMode = false;
374 + this.scrollOffset = 0;
375 + this.refresh();
376 + return;
378 + if (data === "G") {
379 + this.followMode = true;
380 + this.scrollOffset = 999999;
381 + this.refresh();
385 + private getBody(width: number): string[] {
386 + const key = [
387 + this.state.status,
388 + this.state.currentRound,
389 + this.state.blocking,
390 + this.state.entries.length,
391 + ...this.state.entries.map((entry) => `${entry.role}:${entry.round}:${entry.blocking}:${entry.text.length}`),
392 + ].join("|");
393 + if (this.cachedBody && this.cachedBodyWidth === width && this.cachedBodyKey === key) {
394 + return this.cachedBody;
396 + this.cachedBodyWidth = width;
397 + this.cachedBodyKey = key;
398 + this.cachedBody = renderDebateTranscript(this.state, this.theme, width, {
399 + compact: false,
400 + maxBodyLines: 1000,
401 + });
402 + return this.cachedBody;
405 + render(width: number): string[] {
406 + if (width <= 0) return [""];
407 + const innerWidth = Math.max(0, width - 2);
408 + const body = this.getBody(innerWidth);
409 + const maxVisible = Math.max(6, Math.min(24, this.tui.terminal.rows - 8));
410 + const maxScroll = Math.max(0, body.length - maxVisible);
411 + if (this.followMode) this.scrollOffset = maxScroll;
412 + this.scrollOffset = Math.min(this.scrollOffset, maxScroll);
413 + const visible = body.slice(this.scrollOffset, this.scrollOffset + maxVisible);
415 + const title = ` Devil Review · ${this.state.currentRound}/${this.state.maxRounds} `;
416 + const top = this.theme.fg("accent", title) + this.theme.fg("border", "─".repeat(Math.max(0, innerWidth - visibleWidth(title))));
417 + const lines = [frameLine(this.theme, "╭", top, "╮", width)];
419 + for (const line of visible) {
420 + lines.push(frameLine(this.theme, "│", line, "│", width));
423 + const scrollInfo = body.length > maxVisible
424 + ? `${this.scrollOffset + 1}-${Math.min(this.scrollOffset + maxVisible, body.length)}/${body.length}`
425 + : `${body.length}L`;
426 + const follow = this.followMode ? "follow" : "paused";
427 + const footer = this.theme.fg("dim", ` ${scrollInfo} · ${follow} · j/k scroll · g/G top/end · q cancel `);
428 + lines.push(frameLine(this.theme, "├", this.theme.fg("border", "─".repeat(innerWidth)), "┤", width));
429 + lines.push(frameLine(this.theme, "│", footer, "│", width));
430 + lines.push(frameLine(this.theme, "╰", this.theme.fg("border", "─".repeat(innerWidth)), "╯", width));
431 + return lines.map((line) => truncateToWidth(line, width));
434 + invalidate(): void {
435 + this.cachedBody = undefined;
436 + this.cachedBodyWidth = undefined;
437 + this.cachedBodyKey = undefined;
440 + dispose(): void {
441 + this.disposed = true;
442 + this.controller.abort();
171 446 function gatherContext(ctx: ExtensionContext): Record<string, string> {
172 447 const context: Record<string, string> = {};
173 448 context["working_directory"] = ctx.cwd;
214 489 content = content.slice(0, MAX_FILE_CHARS) + "\n... (truncated)";
216 491 const rel = path.relative(ctx.cwd, fp);
217 - return `### ${rel}\n\`${content}\``;
492 + return `### ${rel}\n\`\`\`\n${content}\n\`\`\``;
218 493 } catch {
219 494 return null;
293 568 if (s.next_steps.length > 0) {
294 569 text += `\n### Next Steps\n`;
295 - for (const n of s.next_steps) text += `${n}\n`;
570 + for (const n of s.next_steps) text += `- ${n}\n`;
298 573 return text;
576 +function resolveDebateModel(
577 + ctx: ExtensionContext,
578 + modelSetting?: string,
579 +): Model | null {
580 + const current = ctx.model ?? null;
582 + if (modelSetting) {
583 + const [provider, modelId] = modelSetting.includes("/")
584 + ? modelSetting.split("/", 2)
585 + : [current?.provider, modelSetting];
587 + if (provider) {
588 + const found = ctx.modelRegistry.find(provider, modelId);
589 + if (found) return found;
593 + return current;
301 596 function parseSynthesis(raw: string): SynthesisResult {
302 597 // Try JSON parse first
355 650 stoppingConditions,
356 651 concessionThreshold,
357 652 signal,
653 + onStatus,
358 654 onChallenge,
359 655 onRound,
360 656 } = opts;
682 + onStatus?.(`Round ${i}/${maxRounds} · devil challenging`, i, maxRounds, blockingIssuesFound);
386 684 // ── Devil's challenge (sees full round history) ──
387 685 const devilUserText = [
388 686 `Context:\n${contextText}`,
424 722 .map((c) => c.text)
425 723 .join("\n");
427 - const roundBlockingCount =
428 - (devilOutput.match(/\[blocking\]/gi) || []).length +
429 - (devilOutput.match(/\*\*blocking\*\*/gi) || []).length;
430 - blockingIssuesFound = Math.max(blockingIssuesFound, roundBlockingCount);
725 + const roundBlockingCount = (
726 + devilOutput.match(/^###\s+(?:\[?blocking\]?|\*\*blocking\*\*)\b/gim) || []
727 + ).length;
728 + blockingIssuesFound += roundBlockingCount;
432 730 // Mid-round update: devil has spoken, widget shows challenge
433 731 onChallenge?.(i, maxRounds, blockingIssuesFound, devilOutput);
732 + onStatus?.(`Round ${i}/${maxRounds} · proposer defending`, i, maxRounds, blockingIssuesFound);
435 734 // ── Proposer's rebuttal (sees full round history + current challenge) ──
436 735 const proposerUserText = [
482 781 roundHistory += `### Round ${i}\n**Challenge:** ${devilOutput.slice(0, 500)}\n**Response:** ${proposerOutput.slice(0, 500)}\n\n`;
484 783 // Round complete update
485 - const status = `Round ${i}/${maxRounds} · ${blockingIssuesFound} blocking`;
784 + const status = `Round ${i}/${maxRounds} · ${blockingIssuesFound} blocking raised`;
486 785 onRound?.(i, maxRounds, blockingIssuesFound, status, devilOutput, proposerOutput);
488 787 // Check stopping conditions
522 821 roundsData,
523 822 recommendation: "proceed_with_caution",
524 823 blockingRaised: blockingIssuesFound,
525 - blockingRemaining: blockingIssuesFound,
824 + blockingRemaining: blockingIssuesFound,
526 825 aborted: true,
829 + onStatus?.("Synthesizing verdict", roundsData.length, maxRounds, blockingIssuesFound);
530 831 // ── Synthesis (JSON structured output) ──
531 832 const synthesisUserText = [
532 833 `Idea: ${idea}`,
578 879 const meta = output.aborted
579 880 ? `*Debate cancelled | ${output.roundsData.length} rounds completed*`
580 - : `*Debate: ${output.roundsData.length}r | ${output.blockingRaised} raised, ${output.blockingRemaining} remaining*`;
881 + : `*Debate: ${output.roundsData.length}r | ${output.blockingRaised} blocking challenges raised | ${output.blockingRemaining} unresolved in verdict*`;
582 883 return `${output.synthesis}${blockingNote}\n\n${meta}`;
587 888 export default async function (pi: ExtensionAPI) {
588 889 const settings = pi.settingsManager?.getSettings();
589 - const devilSettings: DevilSettings = settings?.devilsAdvocate ?? {};
890 + const devilSettings: DevilSettings = settings?.devil ?? {};
891 + const activeControllers = new Set<AbortController>();
591 893 // ── Flags ─────────────────────────────────────────────────────────
608 910 ctx.ui.setWidget("devil", undefined);
610 912 pi.on("session_shutdown", async (_event, ctx) => {
913 + for (const controller of activeControllers) controller.abort();
914 + activeControllers.clear();
611 915 ctx.ui.setStatus("devil", undefined);
612 916 ctx.ui.setWidget("devil", undefined);
615 - // ── Tool: devils_advocate ──────────────────────────────────────────
919 + // ── Tool: devil ────────────────────────────────────────────────────
617 921 pi.registerTool({
618 - name: "devils_advocate",
922 + name: "devil",
619 923 label: "Devil's Advocate",
620 924 description:
621 925 "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.",
622 926 promptSnippet: "Stress-test ideas via structured devil's advocate debate",
623 927 promptGuidelines: [
624 - "Use devils_advocate when the user wants to validate an idea, check for flaws, or get a critical perspective before committing to a decision.",
928 + "Use devil when the user wants to validate an idea, check for flaws, or get a critical perspective before committing to a decision.",
625 929 "Include relevant context (problem, constraints, scale) as kvpairs for better-targeted challenges.",
626 930 "Set stakeholder to match the perspective most relevant to the idea (security, cost, ux, impl, ethics, skeptical).",
627 - "After devils_advocate returns, summarize the verdict and actionable next steps for the user.",
931 + "After devil returns, summarize the verdict and actionable next steps for the user.",
629 933 parameters: Type.Object({
630 934 idea: Type.String({ description: "Idea/claim/decision. Be specific." }),
669 973 const stop = stopping && stopping !== DEFAULT_STOPPING_CONDITIONS ? ` · ${stopping}` : "";
671 975 return new Text(
672 - theme.fg("toolTitle", theme.bold("devils_advocate ")) +
976 + theme.fg("toolTitle", theme.bold("devil ")) +
673 977 theme.fg("dim", `"${snippet}"`) +
674 978 theme.fg("muted", ` ${maxRounds}r${focus}${stop}`),
685 989 blockingRaised?: number;
686 990 blockingRemaining?: number;
687 991 output?: string;
992 + roundsData?: string[];
688 993 aborted?: boolean;
690 995 | undefined;
730 1035 let text = theme.fg(recColor, recLabel);
731 - text += theme.fg("muted", ` · ${rounds}r · ${raised}→${remaining} blocking`);
1036 + text += theme.fg("muted", ` · ${rounds}r · ${raised} raised · ${remaining} unresolved`);
733 - if (expanded && details.output) {
734 - const lines = details.output.split("\n").filter((l: string) => l.trim());
735 - let inSection = false;
736 - for (const line of lines.slice(0, 30)) {
737 - if (line.startsWith("### ") || line.startsWith("## ")) {
738 - inSection = true;
739 - text += "\n" + theme.fg("toolTitle", line);
740 - } else if (inSection) {
741 - text += "\n" + theme.fg("dim", line);
1038 + if (expanded) {
1039 + if (details.roundsData?.length) {
1040 + text += "\n" + theme.fg("toolTitle", "### Transcript");
1041 + for (const round of details.roundsData) {
1042 + text += "\n" + theme.fg("dim", round);
1044 + } else if (details.output) {
1045 + const lines = details.output.split("\n").filter((l: string) => l.trim());
1046 + let inSection = false;
1047 + for (const line of lines.slice(0, 30)) {
1048 + if (line.startsWith("### ") || line.startsWith("## ")) {
1049 + inSection = true;
1050 + text += "\n" + theme.fg("toolTitle", line);
1051 + } else if (inSection) {
1052 + text += "\n" + theme.fg("dim", line);
1055 + if (lines.length > 30) text += "\n" + theme.fg("dim", "...");
744 - if (lines.length > 30) text += "\n" + theme.fg("dim", "...");
747 1059 return new Text(text, 0, 0);
773 1085 const onBlocking =
774 1086 onBlockingParam ?? devilSettings.onBlocking ?? DEFAULT_ON_BLOCKING;
776 - // Resolve model
777 - let model = ctx.model;
778 - if (modelOverride) {
779 - const [provider, modelId] = modelOverride.includes("/")
780 - ? modelOverride.split("/")
781 - : [modelOverride, modelOverride];
782 - const found = ctx.modelRegistry.find(provider, modelId);
783 - if (found) model = found;
784 - } else if (devilSettings.model && ctx.model) {
785 - const [provider, modelId] = devilSettings.model.includes("/")
786 - ? devilSettings.model.split("/")
787 - : [ctx.model.provider, devilSettings.model];
788 - const found = ctx.modelRegistry.find(provider, modelId);
789 - if (found) model = found;
1088 + const model = resolveDebateModel(
1089 + ctx,
1090 + modelOverride ?? devilSettings.model,
1091 + );
792 1092 if (!model) {
793 - return {
794 - content: [
795 - { type: "text", text: "Error: No model available. Use /model." },
796 - ],
797 - details: { error: "No model" },
798 - };
1093 + throw new Error("No model available. Use /model.");
801 1096 const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
802 1097 if (!auth.ok || !auth.apiKey) {
803 - return {
804 - content: [
805 - { type: "text", text: `Error: No API key for ${model.provider}` },
806 - ],
807 - details: { error: "No API key" },
808 - };
1098 + throw new Error(`No API key for ${model.provider}`);
811 1101 // Merge session context with LLM-provided context
821 - if (ctx.hasUI) {
822 - ctx.ui.setStatus(
823 - "devil",
824 - `🗡️ Devil: ${idea.slice(0, 40)}... (${maxRounds}r)`,
825 - );
1111 + const live = createDebateState(idea, maxRounds);
1112 + const renderLiveWidget = () => {
1113 + if (!ctx.hasUI || signal?.aborted) return;
1114 + ctx.ui.setWidget("devil", (_tui, theme) => new DebateWidget(theme, live));
1115 + };
1116 + renderLiveWidget();
829 1119 const result = await runDebate({
839 1129 | "max_rounds",
840 1130 concessionThreshold,
841 1131 signal,
842 - onChallenge: (round, max, blocking, devilOutput) => {
843 - if (ctx.hasUI) {
844 - ctx.ui.setStatus("devil", `🗡️ Devil: R${round}/${max} challenging...`);
845 - const snippet = extractSnippet(devilOutput, 60);
846 - ctx.ui.setWidget("devil", [
847 - `🗡️ Round ${round}/${max} · ${blocking} blocking`,
848 - snippet ? ` ⚑ ${snippet}` : " ⚑ Analyzing...",
849 - ]);
1132 + onStatus: (status, round, _max, blocking) => {
1133 + if (signal?.aborted) return;
1134 + setDebateStatus(live, status, round, blocking);
1135 + renderLiveWidget();
852 - onRound: (round, max, blocking, status, devilOutput, proposerOutput) => {
853 - if (ctx.hasUI) {
854 - ctx.ui.setStatus("devil", `🗡️ Devil: ${status}`);
855 - const snippet = extractSnippet(proposerOutput, 60);
856 - ctx.ui.setWidget("devil", [
857 - `🗡️ Round ${round}/${max} · ${blocking} blocking`,
858 - snippet ? ` ✓ ${snippet}` : " ✓ Defended",
859 - ]);
1137 + onChallenge: (round, _max, blocking, devilOutput) => {
1138 + if (signal?.aborted) return;
1139 + addDebateEntry(live, "devil", round, blocking, devilOutput);
1140 + renderLiveWidget();
1141 + },
1142 + onRound: (round, max, blocking, _status, devilOutput, proposerOutput) => {
1143 + if (signal?.aborted) return;
1144 + addDebateEntry(live, "proposer", round, blocking, proposerOutput);
1145 + renderLiveWidget();
861 1146 onUpdate?.({
862 1147 content: [
864 1149 type: "text",
865 - text: `Round ${round}/${max} · ${blocking} blocking\n⚑ ${extractSnippet(devilOutput, 80)}\n✓ ${extractSnippet(proposerOutput, 80)}`,
1150 + text: `Round ${round}/${max} · ${blocking} blocking raised\n⚑ ${extractSnippet(devilOutput, 80)}\n✓ ${extractSnippet(proposerOutput, 80)}`,
868 1153 details: { round, maxRounds: max, blockingRaised: blocking },
888 1173 blockingRaised: result.blockingRaised,
889 1174 blockingRemaining: result.blockingRemaining,
890 1175 output: result.synthesis,
1176 + roundsData: result.roundsData,
891 1177 aborted: result.aborted,
897 1183 ctx.ui.setStatus("devil", undefined);
898 1184 ctx.ui.setWidget("devil", undefined);
900 - return {
901 - content: [{ type: "text", text: `## Debate Failed\n\nError: ${message}` }],
902 - details: { error: message },
903 - };
1186 + throw new Error(`Debate failed: ${message}`);
920 1203 ctx.ui?.notify("Editor contains debate output, not an idea. Clear it first.", "info");
921 1204 return;
923 - pi.sendUserMessage(`/devil ${text}`);
1206 + await pi.sendUserMessage(`/devil ${text}`);
936 1219 ctx.ui?.notify("Devil requires interactive mode", "error");
937 1220 return;
939 - if (!ctx.model) {
1222 + const model = resolveDebateModel(ctx, devilSettings.model);
1223 + if (!model) {
940 1224 ctx.ui?.notify("No model selected. Use /model first.", "error");
941 1225 return;
944 - const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model);
1228 + const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
945 1229 if (!auth.ok || !auth.apiKey) {
946 - ctx.ui?.notify(`No API key for ${ctx.model.provider}`, "error");
1230 + ctx.ui?.notify(`No API key for ${model.provider}`, "error");
947 1231 return;
956 1240 const onBlocking = devilSettings.onBlocking ?? DEFAULT_ON_BLOCKING;
957 1241 const debateContext = gatherContext(ctx);
959 - const result = await ctx.ui.custom<DebateOutput | null>(
960 - (tui, theme, _kb, done) => {
961 - const loader = new BorderedLoader(
962 - tui,
963 - theme,
964 - `🗡️ Devil: "${idea.length > 40 ? idea.slice(0, 40) + "..." : idea}" (${maxRounds}r)`,
965 - );
966 - loader.onAbort = () => done(null);
1243 + const debateController = new AbortController();
1244 + activeControllers.add(debateController);
1245 + let result: DebateOutput | null = null;
1246 + let failedMessage: string | undefined;
1247 + try {
1248 + result = await ctx.ui.custom<DebateOutput | null>(
1249 + (tui, theme, _kb, done) => {
1250 + const live = createDebateState(idea, maxRounds);
1251 + const review = new DebateReviewComponent(tui, theme, live, done, debateController);
968 - runDebate({
969 - idea,
970 - context: debateContext,
971 - model: ctx.model!,
972 - apiKey: auth.apiKey!,
973 - headers: auth.headers,
974 - maxRounds,
975 - stoppingConditions,
976 - concessionThreshold,
977 - signal: loader.signal,
978 - onChallenge: (round, max, blocking, devilOutput) => {
979 - ctx.ui.setStatus("devil", `🗡️ Devil: R${round}/${max} challenging...`);
980 - const snippet = extractSnippet(devilOutput, 60);
981 - ctx.ui.setWidget("devil", [
982 - `🗡️ Round ${round}/${max} · ${blocking} blocking`,
983 - snippet ? ` ⚑ ${snippet}` : " ⚑ Analyzing...",
984 - ]);
985 - },
986 - onRound: (round, max, blocking, _status, _devilOutput, proposerOutput) => {
987 - ctx.ui.setStatus("devil", `🗡️ Devil: R${round}/${max} defending...`);
988 - const snippet = extractSnippet(proposerOutput, 60);
989 - ctx.ui.setWidget("devil", [
990 - `🗡️ Round ${round}/${max} · ${blocking} blocking`,
991 - snippet ? ` ✓ ${snippet}` : " ✓ Defended",
992 - ]);
993 - },
994 - })
995 - .then((output) => {
996 - ctx.ui.setWidget("devil", undefined);
997 - if (output.aborted) done(null);
998 - else done(output);
1253 + runDebate({
1254 + idea,
1255 + context: debateContext,
1256 + model,
1257 + apiKey: auth.apiKey!,
1258 + headers: auth.headers,
1259 + maxRounds,
1260 + stoppingConditions,
1261 + concessionThreshold,
1262 + signal: review.signal,
1263 + onStatus: (status, round, _max, blocking) => {
1264 + if (!review.isActive()) return;
1265 + setDebateStatus(live, status, round, blocking);
1266 + review.refresh();
1267 + },
1268 + onChallenge: (round, _max, blocking, devilOutput) => {
1269 + if (!review.isActive()) return;
1270 + addDebateEntry(live, "devil", round, blocking, devilOutput);
1271 + review.refresh();
1272 + },
1273 + onRound: (round, _max, blocking, _status, _devilOutput, proposerOutput) => {
1274 + if (!review.isActive()) return;
1275 + addDebateEntry(live, "proposer", round, blocking, proposerOutput);
1276 + review.refresh();
1277 + },
1000 - .catch((err) => {
1001 - ctx.ui.setWidget("devil", undefined);
1002 - console.error("[devil] runDebate error:", err);
1003 - done(null);
1004 - });
1279 + .then((output) => review.finish(output.aborted ? null : output))
1280 + .catch((err) => {
1281 + if (!review.signal.aborted && review.isActive()) {
1282 + failedMessage = err instanceof Error ? err.message : String(err);
1283 + console.error("[devil] runDebate error:", err);
1284 + ctx.ui.notify(`Debate failed: ${failedMessage}`, "error");
1286 + review.finish(null);
1287 + });
1006 - return loader;
1007 - },
1008 - );
1010 - if (result === null) {
1289 + return review;
1290 + },
1291 + );
1292 + } finally {
1293 + debateController.abort();
1294 + activeControllers.delete(debateController);
1011 1295 ctx.ui.setStatus("devil", undefined);
1012 1296 ctx.ui.setWidget("devil", undefined);
1013 - ctx.ui.notify("Debate cancelled", "info");
1299 + if (result === null) {
1300 + if (!failedMessage) ctx.ui.notify("Debate cancelled", "info");
1014 1301 return;
1017 1304 const outputText = formatDebateOutput(result, onBlocking);
1019 - // Modal editor: Enter confirms (→ main editor), Esc discards
1306 + // Modal editor: Enter submits directly, Esc discards.
1020 1307 const edited = await ctx.ui.editor(
1021 - `🗡️ ${result.recommendation.replace(/_/g, " ")} · ${result.blockingRaised} raised, ${result.blockingRemaining} remaining`,
1308 + `🗡️ ${result.recommendation.replace(/_/g, " ")} · ${result.blockingRaised} raised · ${result.blockingRemaining} unresolved`,
1022 1309 outputText,
1025 1312 ctx.ui.setStatus("devil", undefined);
1026 1313 ctx.ui.setWidget("devil", undefined);
1028 - if (edited === undefined) {
1315 + if (edited === undefined || !edited.trim()) {
1029 1316 ctx.ui.notify("Debate result discarded", "info");
1030 1317 return;
1033 - ctx.ui.setEditorText(edited);
1034 - ctx.ui.notify("Edit and submit when ready", "success");
1320 + pi.appendEntry("devil-result", {
1321 + idea,
1322 + verdict: edited,
1323 + roundsData: result.roundsData,
1324 + recommendation: result.recommendation,
1325 + blockingRaised: result.blockingRaised,
1326 + blockingRemaining: result.blockingRemaining,
1327 + timestamp: Date.now(),
1328 + });
1329 + pi.sendUserMessage(edited);

pi/agent/tools/devils_advocate.md

Deleted
deleted file mode 100644
1 -# devils_advocate
3 -A structured debate tool for stress-testing ideas against a devil's advocate. Designed to reduce sycophancy by forcing critical examination of decisions before commitment.
5 ----
7 -## Quick Start
9 -```bash
10 -pi
11 -/devil we should switch to microservices
12 -```
14 -Or call the tool directly with parameters.
16 ----
18 -## Pi User Implications
20 -### Session Behavior
22 -| Aspect | Behavior |
23 -|--------|----------|
24 -| **Session state** | Debates are stateless. Each call is independent. |
25 -| **Conversation history** | Debate results are NOT automatically added to the conversation. |
26 -| **Model** | Uses the currently selected model (or configured model). |
27 -| **Context** | Does NOT automatically include current conversation context. You must pass it explicitly. |
28 -| **API credentials** | Uses current session's API keys. |
29 -| **Tool results** | Displayed inline, stored in tool details, but not in conversation history unless you add them. |
31 -### When to Use
33 -**Good use cases:**
34 -- Before implementing architectural decisions
35 -- When you're unsure about a direction and want pushback
36 -- After getting too much agreement (sign of sycophancy)
37 -- To document concerns for stakeholders
39 -**Not ideal for:**
40 -- Quick questions (overhead too high)
41 -- When you already have strong disagreement (you don't need a devil)
42 -- Sensitive topics where disagreement feels personal
44 -### Integration with Workflow
46 -```
47 -1. You're working on something
48 -2. You get suspicious agreement → /devil <your idea>
49 -3. Review blocking issues
50 -4. Decide: proceed, revise, or abandon
51 -5. Continue with confidence (or a better idea)
52 -```
54 -### Passing Context
56 -Because debates don't auto-include conversation context:
58 -```javascript
59 -// Good: Explicit context
60 -devils_advocate({
61 - idea: "Add authentication to this endpoint",
62 - context: {
63 - current_approach: "API key in query params",
64 - security_requirements: "Need OAuth for third-party access",
65 - timeline: "Must ship by Friday"
66 - }
67 -})
69 -// Bad: Missing context (devil won't know your constraints)
70 -devils_advocate({
71 - idea: "Add authentication"
72 -})
73 -```
75 ----
77 -## Configuration
79 -Add to `~/.pi/agent/settings.json`:
81 -```json
83 - "devilsAdvocate": {
84 - "model": "anthropic/claude-haiku-4-5",
85 - "maxRounds": 5,
86 - "stoppingConditions": "consensus",
87 - "concessionThreshold": 0.7,
88 - "onBlocking": "surface"
89 - }
91 -```
93 -### Settings Reference
95 -| Setting | Type | Default | Description |
96 -|---------|------|---------|-------------|
97 -| `model` | string | current model | Model for debates. Use cheaper models for speed. |
98 -| `maxRounds` | number | 5 | Maximum debate rounds (1-10). |
99 -| `stoppingConditions` | string | "consensus" | When to stop debating. |
100 -| `concessionThreshold` | number | 0.7 | How much concession triggers early stop (0.0-1.0). |
101 -| `onBlocking` | string | "surface" | What to do with blocking issues. |
103 -### Stopping Conditions
105 -| Value | Behavior |
106 -|-------|----------|
107 -| `consensus` | Stop after 2 consecutive rounds with significant resolutions. |
108 -| `blocking_found` | Stop as soon as no blocking issues remain. |
109 -| `max_rounds` | Always run full `maxRounds`. |
110 -| `user_stops` | (Future: user-controlled stopping.) |
112 -### On Blocking Behavior
114 -| Value | Behavior |
115 -|-------|----------|
116 -| `surface` | Always show blocking issues in output. |
117 -| `escalate` | Add warning if blocking issues found. |
118 -| `ignore` | Don't flag blocking issues (not recommended). |
120 ----
122 -## Parameters
124 -```javascript
125 -devils_advocate({
126 - idea: string, // Required: what to debate
127 - context?: object, // Optional: { key: "value" } pairs
128 - model?: string, // Optional: override model
129 - maxRounds?: number, // Optional: 1-10
130 - stakeholder?: string, // Optional: focus area
131 - stoppingConditions?: string, // Optional: when to stop
132 - concessionThreshold?: number, // Optional: 0.0-1.0
133 - onBlocking?: string, // Optional: blocking behavior
134 - output?: string // Optional: "full" or "summary_only"
135 -})
136 -```
138 -### Stakeholder Focus
140 -| Value | Focus |
141 -|-------|-------|
142 -| `security` | Security concerns, attack vectors, vulnerabilities |
143 -| `cost` | Cost, ROI, resource implications, scaling costs |
144 -| `ux` | User experience, accessibility, friction points |
145 -| `implementation` | Technical complexity, dependencies, maintenance |
146 -| `ethics` | Ethical concerns, societal impact, fairness |
147 -| `skeptical` | General skepticism, challenged assumptions |
149 ----
151 -## Output Format
153 -### Challenge Classification
155 -Each challenge is classified:
157 -| Classification | Meaning | Action |
158 -|---------------|---------|--------|
159 -| **blocking** | Would prevent the idea from working | Must address first |
160 -| **addressable** | Valid concern with known mitigations | Consider mitigations |
161 -| **assumed** | Based on premises that may not hold | Verify assumptions |
162 -| **minor** | Aesthetic or edge case | Not worth debating |
164 -### Recommendation
166 -| Value | Meaning |
167 -|-------|---------|
168 -| `proceed` | No blocking issues, idea holds up |
169 -| `proceed_with_caution` | Addressable concerns exist |
170 -| `revise` | Blocking issues require design changes |
171 -| `abandon` | Fundamental flaws identified |
173 -### Example Output
175 -```markdown
176 -## Summary
178 -**Recommendation:** proceed_with_caution
180 -### Blocking Issues (must address first)
181 -- Vendor lock-in → Use abstraction layer or multi-cloud strategy
183 -### Addressable Concerns (valid concerns with mitigations)
184 -- Migration complexity → Use migration tooling (Alembic, Flyway)
186 -### What Survived Scrutiny
187 -- SQLite handles our current read/write volume
188 -- Simple deployment model reduces ops burden
190 -### What Was Conceded
191 -- WAL mode limits concurrent read performance at scale
193 -### Recommended Next Steps
194 -1. Define cloud abstraction layer
195 -2. Benchmark with production data volume
196 -3. Prototype migration strategy
198 -*Debate: 3 rounds | Blocking: 1*
199 -```
201 ----
203 -## Examples
205 -### Basic Usage
207 -```
208 -devils_advocate({
209 - idea: "We should migrate from REST to GraphQL"
210 -})
211 -```
213 -### With Context
215 -```
216 -devils_advocate({
217 - idea: "Use SQLite as primary database",
218 - context: {
219 - scale: "10k concurrent users",
220 - team_size: "5 developers",
221 - requirement: "ACID compliance required",
222 - timeline: "MVP by Q2"
223 - }
224 -})
225 -```
227 -### Focused Challenge
229 -```
230 -devils_advocate({
231 - idea: "Add real-time notifications",
232 - stakeholder: "implementation",
233 - stoppingConditions: "blocking_found"
234 -})
235 -```
237 -### Full Debate with All Parameters
239 -```
240 -devils_advocate({
241 - idea: "Implement OAuth2 authentication",
242 - context: {
243 - current: "API keys in headers",
244 - users: "1000 monthly active",
245 - security_level: "medium"
246 - },
247 - model: "anthropic/claude-sonnet-4-5",
248 - maxRounds: 3,
249 - stakeholder: "security",
250 - stoppingConditions: "consensus",
251 - concessionThreshold: 0.8,
252 - onBlocking: "escalate",
253 - output: "full"
254 -})
255 -```
257 ----
259 -## Best Practices
261 -### Writing Good Ideas
263 -**Good:**
264 -- "Add rate limiting to the API"
265 -- "Use event sourcing for order management"
266 -- "Implement dark mode across all screens"
268 -**Bad:**
269 -- "Improve performance" (vague)
270 -- "Make it better" (unmeasurable)
271 -- "Add auth" (missing context)
273 -### Providing Context
275 -Context is critical for relevant challenges:
277 -```
278 -// Include relevant constraints
279 -context: {
280 - current_approach: "What you're doing now",
281 - constraints: "What limits you",
282 - requirements: "What must be preserved",
283 - timeline: "When it needs to ship"
285 -```
287 -### Interpreting Results
289 -- **Multiple blocking issues**: Revise the idea significantly
290 -- **Addressable concerns only**: Proceed with mitigations planned
291 -- **Survived full debate**: Good confidence in the idea
292 -- **Early stop (consensus)**: Either the idea is solid or concessions were too easy
294 ----
296 -## Limitations
298 -1. **No conversation memory**: Each debate is independent
299 -2. **LLM classification**: Challenge classification depends on model interpretation
300 -3. **Concession detection**: Keyword matching can be fooled
301 -4. **No escalation actions**: Blocking issues are surfaced, not acted upon
302 -5. **Model-dependent quality**: Challenge quality varies by model
304 ----
306 -## Troubleshooting
308 -### "No model available"
309 -- Select a model first with `/model`
310 -- Or configure `devilsAdvocate.model` in settings
312 -### "Debate took too long"
313 -- Reduce `maxRounds`
314 -- Use a faster model (haiku vs opus)
315 -- Use `stoppingConditions: "blocking_found"`
317 -### "Challenges aren't relevant"
318 -- Provide more specific `context`
319 -- Use `stakeholder` to focus the challenge domain
320 -- Refine your `idea` to be more specific
322 -### "Too many minor challenges"
323 -- Use `stakeholder: "skeptical"` for priority concerns
324 -- Add `context.constraints` to narrow scope
326 ----
328 -## Related
330 -- `/compact` - Summarize conversation (use after debate)
331 -- `/tree` - Review decision history
332 -- `/fork` - Branch on different decisions