13 13 *
"model":
"zai/glm-5.1",
15 15 *
"stoppingConditions":
"consensus",
16 16 *
"concessionThreshold":
0.7,
17 17 *
"onBlocking":
"surface" 22 -import * as fs
from "node:fs";
23 -import * as path
from "node:path";
24 -import { complete }
from "@earendil-works/pi-ai";
22 +import { chmodSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync }
from "node:fs";
23 +import { tmpdir }
from "node:os";
24 +import { join }
from "node:path";
25 +import { randomUUID }
from "node:crypto";
26 +import { complete, type Model }
from "@earendil-works/pi-ai";
27 - serializeConversation,
29 + DefaultResourceLoader,
28 33 }
from "@earendil-works/pi-coding-agent";
34 37 }
from "@earendil-works/pi-coding-agent";
35 38 import type { Theme }
from "@earendil-works/pi-coding-agent";
56 59 CONSENSUS_ROUNDS_REQUIRED,
57 60 } from
"./helpers";
62 +type AnyModel = Model<
any>;
59 64 const DEVIL_SYSTEM_PROMPT
= `Devil advocate. STRESS TEST ideas. Find blocking issues. 121 126 - Otherwise:
"proceed_with_caution"`; 123 128 // Default settings 124 -const DEFAULT_MAX_ROUNDS = 5; 129 +const DEFAULT_MAX_ROUNDS = 2; 125 130 const DEFAULT_STOPPING_CONDITIONS = "consensus"; 126 131 const DEFAULT_CONCESSION_THRESHOLD = 0.7; 127 132 const DEFAULT_ON_BLOCKING = "surface"; 135 140 onBlocking
?: "surface" | "escalate" | "ignore";
143 +interface SettingsAPI extends ExtensionAPI {
144 + settingsManager
?: {
getSettings()
: Record<
string,
unknown>
| undefined };
138 147 interface SynthesisResult {
139 148 recommendation
: "proceed" | "proceed_with_caution" | "revise" | "abandon";
148 157 interface RunDebateOptions {
150 159 context
?: Record<
string,
string>;
161 + ctx
: ExtensionContext;
153 163 headers
?: Record<
string,
string>;
154 164 maxRounds
: number;
156 166 concessionThreshold: number;
157 167 signal
?: AbortSignal;
158 168 onStatus
?: (status
: string, round
: number, maxRounds
: number, blocking
: number)
=> void;
183 201 blocking: number;
186 205 interface DebateLiveState {
198 -const MAX_FILE_CHARS
= 3000;
199 -const MAX_FILES
= 10;
200 -const FILE_TOOL_NAMES
= new Set([
"read",
"edit",
"write"]);
202 -interface ToolCallBlock {
205 - arguments
: Record<
string,
unknown>;
217 +const DISABLED_SUBAGENT_TOOLS
= new Set([
"write",
"edit"]);
218 +const DEVIL_TMP_PREFIX
= "pi-devil-";
219 +const DEVIL_TMP_TTL_MS
= 24 * 60 * 60 * 1000;
208 221 export function createDebateState(idea
: string, maxRounds
: number)
: DebateLiveState {
228 241 state.blocking
= blocking;
231 -function addDebateEntry(
244 +function upsertDebateEntry(
232 245 state
: DebateLiveState,
233 246 role
: DebateRole,
235 248 blocking
: number,
238 252 state.currentRound
= round;
239 253 state.blocking
= blocking;
240 - state.entries.
push({ role, round, blocking, text });
254 + const existing
= state.entries.
find((entry)
=> entry.role
=== role
&& entry.round
=== round);
256 + existing.blocking
= blocking;
257 + existing.
text = text;
258 + existing.final
= final;
261 + state.entries.
push({ role, round, blocking, text, final });
280 301 for (
const entry
of entries) {
281 302 const icon
= entry.role
=== "devil" ? "⚑" : "✓";
282 303 const label
= entry.role
=== "devil" ? "Devil" : "Defense";
283 - lines.
push(theme.
fg(entry.role
=== "devil" ? "warning" : "success",
truncateToWidth(
`${icon} R${entry.round} ${label}`, usableWidth)));
304 + const stateLabel
= entry.final
? "final" : "streaming…";
305 + lines.
push(theme.
fg(entry.role
=== "devil" ? "warning" : "success",
truncateToWidth(
`${icon} R${entry.round} ${label} · ${stateLabel}`, usableWidth)));
285 307 const bodyWidth
= Math.
max(
1, usableWidth
- 2);
286 308 const body
= cleanTranscriptText(entry.
text, options.
compact ? 700 : 20000);
353 - if (
matchesKey(data,
"pageup")
|| matchesKey(data,
"ctrl+u")) {
375 + if (
matchesKey(data,
"pageUp")
|| matchesKey(data,
"ctrl+u")) {
354 376 this.followMode
= false;
355 377 this.scrollOffset
= Math.
max(
0, this.scrollOffset
- 10);
359 - if (
matchesKey(data,
"pagedown")
|| matchesKey(data,
"ctrl+d")) {
381 + if (
matchesKey(data,
"pageDown")
|| matchesKey(data,
"ctrl+d")) {
360 382 this.scrollOffset
+= 10;
438 460 function gatherContext(ctx
: ExtensionContext)
: Record<
string,
string> {
439 - const context
: Record<
string,
string>
= {};
440 - context[
"working_directory"]
= ctx.cwd;
442 - const branch
= ctx.sessionManager.
getBranch();
448 - const filePaths
= new Set<
string>();
450 - for (
const entry
of branch) {
451 - if (entry.
type !== "message")
continue;
452 - const msg
= entry.message;
453 - if (
!msg
|| msg.role
!== "assistant" || !Array.
isArray(msg.
content))
continue;
455 - for (
const block
of msg.
content) {
456 - const tc
= block
as ToolCallBlock;
457 - if (tc.
type !== "toolCall" || !FILE_TOOL_NAMES.
has(tc.
name))
continue;
460 - const filePath
= (tc.
arguments.path
?? tc.
arguments.file_path)
as string | undefined;
461 - if (
typeof filePath
!== "string" || !filePath.
trim())
continue;
463 - const resolved
= path.
resolve(ctx.cwd, filePath.
trim());
465 - if (fs.
existsSync(resolved)
&& fs.
statSync(resolved).
isFile()) {
466 - filePaths.
add(resolved);
474 - if (filePaths.
size > 0) {
475 - const files
= [
...filePaths].
slice(
0, MAX_FILES);
476 - const fileContents
= files
479 - let content
= fs.
readFileSync(fp,
"utf-8");
480 - if (content.
length > MAX_FILE_CHARS) {
481 - content
= content.
slice(
0, MAX_FILE_CHARS)
+ "\n... (truncated)";
483 - const rel
= path.
relative(ctx.cwd, fp);
484 - return `### ${rel}\n\`\`\`\n${content}\n\`\`\``;
489 - .
filter((c)
: c
is string => c
!== null);
490 - if (fileContents.
length > 0) {
491 - context[
"relevant_files"]
= fileContents.
join(
"\n\n");
496 - const messages
= branch
498 - (entry)
: entry
is SessionEntry & { type
: "message" }
=> 499 - entry.
type === "message",
501 - .
map((entry)
=> entry.message);
503 - if (messages.
length > 0) {
504 - const recent
= messages.
slice(
-20);
505 - const llmMessages
= convertToLlm(recent);
506 - context[
"conversation"]
= serializeConversation(llmMessages);
461 + const context
: Record<
string,
string>
= {
462 + working_directory: ctx.cwd,
463 + session_context:
"This debate runs in an ephemeral full fork of the current Pi session. Use the existing conversation, tool results, context files, skills, and loaded extensions already present in this fork.",
465 + const usage
= ctx.
getContextUsage();
466 + if (usage) context[
"context_usage"]
= JSON.
stringify(usage);
470 +function gcEphemeralForks() {
471 + const now
= Date.
now();
472 + for (
const name
of readdirSync(
tmpdir())) {
473 + if (
!name.
startsWith(DEVIL_TMP_PREFIX))
continue;
474 + const dir
= join(
tmpdir(), name);
476 + if (now
- statSync(dir).mtimeMs
> DEVIL_TMP_TTL_MS)
rmSync(dir, { recursive:
true, force:
true });
481 +function createEphemeralFork(ctx
: ExtensionContext)
: { manager
: SessionManager;
cleanup: ()
=> void } {
482 + const dir
= mkdtempSync(
join(
tmpdir(), DEVIL_TMP_PREFIX));
483 + chmodSync(dir,
0o700);
484 + const file
= join(dir,
"branch.jsonl");
485 + const header
= ctx.sessionManager.
getHeader()
?? {
489 + timestamp:
new Date().
toISOString(),
493 + {
...header, cwd: ctx.cwd, parentSession: ctx.sessionManager.
getSessionFile() },
494 + ...ctx.sessionManager.
getBranch(),
496 + writeFileSync(file, entries.
map((entry)
=> JSON.
stringify(entry)).
join(
"\n")
+ "\n", { encoding:
"utf-8", mode:
0o600 });
499 + manager: SessionManager.
open(file, dir, ctx.cwd),
500 + cleanup: ()
=> rmSync(dir, { recursive:
true, force:
true }),
514 504 function formatSynthesis(s
: SynthesisResult)
: string {
515 505 const recEmoji
: Record<
string,
string>
= {
550 540 function resolveDebateModel(
551 541 ctx
: ExtensionContext,
552 542 modelSetting
?: string,
543 +)
: AnyModel | null {
554 544 const current
= ctx.model
?? null;
556 546 if (modelSetting) {
606 +function extractAssistantText(messages
: Array<{ role
?: string; content
?: unknown }>)
: string {
607 + const chunks
= messages
608 + .
filter((message)
=> message.role
=== "assistant")
609 + .
map((message)
=> textFromContent(message.
content as Array<{ type
: string; text
?: string }>).
trim())
611 + return chunks.
at(
-1)
?? chunks.
join(
"\n\n");
614 +async function runRoleAgent(opts
: {
615 + ctx
: ExtensionContext;
617 + systemPrompt
: string;
618 + userPrompt
: string;
619 + signal
?: AbortSignal;
620 + onTool?: (toolName
: string)
=> void;
621 + onText?: (text
: string)
=> void;
622 + onStatus?: (status
: string)
=> void;
623 +})
: Promise<
string> {
624 + const agentDir
= getAgentDir();
625 + opts.
onStatus?.(
"loading settings");
626 + const settingsManager
= SettingsManager.
create(opts.ctx.cwd, agentDir);
627 + const loader
= new DefaultResourceLoader({
631 + systemPromptOverride: (base)
=> [base, opts.systemPrompt].
filter(
Boolean).
join(
"\n\n"),
633 + opts.
onStatus?.(
"loading extensions/resources");
634 + await loader.
reload();
636 + opts.
onStatus?.(
"forking session");
637 + const fork
= createEphemeralFork(opts.ctx);
638 + opts.
onStatus?.(
"starting sub-agent");
639 + const { session }
= await createAgentSession({
643 + thinkingLevel:
"medium",
644 + modelRegistry: opts.ctx.modelRegistry,
645 + resourceLoader: loader,
646 + sessionManager: fork.manager,
649 + await session.
bindExtensions({});
650 + opts.
onStatus?.(
"selecting tools");
652 + const activeTools
= session
654 + .
map((tool)
=> tool.
name)
655 + .
filter((name)
=> !DISABLED_SUBAGENT_TOOLS.
has(name));
656 + session.
setActiveToolsByName(activeTools);
658 + const before
= session.messages.
length;
661 + const emitText = (force
= false)
=> {
662 + const now
= Date.
now();
663 + if (
!force
&& now
- lastEmit
< 80)
return;
665 + if (streamed.
trim()) opts.
onText?.(streamed);
667 + const unsubscribe
= session.
subscribe((event)
=> {
668 + if (
event.
type === "tool_execution_start") opts.
onTool?.(
event.toolName);
669 + if (
event.
type === "message_update" && event.assistantMessageEvent.
type === "text_delta") {
670 + streamed
+= event.assistantMessageEvent.delta;
674 + const abort = ()
=> void session.
abort();
675 + opts.signal?.
addEventListener(
"abort", abort, { once:
true });
678 + opts.
onStatus?.(
"streaming");
679 + await session.
prompt(opts.userPrompt, { source:
"extension" });
680 + const text
= extractAssistantText(session.messages.
slice(before))
|| streamed;
681 + if (text) opts.
onText?.(text);
682 + return text
|| "No response.";
684 + opts.signal?.
removeEventListener(
"abort", abort);
615 691 async function runRound(
617 693 maxRounds
: number,
619 695 contextText
: string,
620 696 roundHistory
: string,
623 - headers
: Record<
string,
string>
| undefined,
698 + ctx
: ExtensionContext,
624 699 signal
: AbortSignal | undefined,
625 700 onStatus
: RunDebateOptions[
"onStatus"],
701 + onChallenge
: RunDebateOptions[
"onChallenge"],
702 + onPartial
: RunDebateOptions[
"onPartial"],
627 704 devilOutput
: string;
628 705 proposerOutput
: string;
632 709 onStatus?.(
`Round ${round}/${maxRounds} · devil challenging`, round, maxRounds,
0);
634 711 const devilUserText
= buildRoundPrompt(round, maxRounds, idea, contextText, roundHistory);
635 - const devilResponse
= await complete(model, { systemPrompt: DEVIL_SYSTEM_PROMPT, messages: [{ role:
"user", content: [{ type:
"text", text: devilUserText }], timestamp:
Date.
now() }] }, { apiKey, headers, signal });
636 - const devilOutput
= textFromContent(devilResponse.
content);
712 + const devilOutput
= await runRoleAgent({
715 + systemPrompt: DEVIL_SYSTEM_PROMPT,
716 + userPrompt: devilUserText,
718 + onStatus: (phase)
=> onStatus?.(
`Round ${round}/${maxRounds} · Devil ${phase}`, round, maxRounds,
0),
719 + onTool: (toolName)
=> onStatus?.(
`Round ${round}/${maxRounds} · Devil using ${toolName}`, round, maxRounds,
0),
720 + onText: (text)
=> onPartial?.(
"devil", round, maxRounds,
countBlockingIssues(text), text),
637 722 const roundBlockingCount
= countBlockingIssues(devilOutput);
723 + onChallenge?.(round, maxRounds, roundBlockingCount, devilOutput);
639 - onStatus?.(
`Round ${round}/${maxRounds} · proposer defending`, round, maxRounds, roundBlockingCount);
725 + onStatus?.(
`Round ${round}/${maxRounds} · Defense starting`, round, maxRounds, roundBlockingCount);
641 727 const proposerUserText
= buildProposerPrompt(idea, roundHistory, round, devilOutput);
642 - const proposerResponse
= await complete(model, { systemPrompt: PROPOSER_SYSTEM_PROMPT, messages: [{ role:
"user", content: [{ type:
"text", text: proposerUserText }], timestamp:
Date.
now() }] }, { apiKey, headers, signal });
643 - const proposerOutput
= textFromContent(proposerResponse.
content);
728 + const proposerOutput
= await runRoleAgent({
731 + systemPrompt: PROPOSER_SYSTEM_PROMPT,
732 + userPrompt: proposerUserText,
734 + onStatus: (phase)
=> onStatus?.(
`Round ${round}/${maxRounds} · Defense ${phase}`, round, maxRounds, roundBlockingCount),
735 + onTool: (toolName)
=> onStatus?.(
`Round ${round}/${maxRounds} · Defense using ${toolName}`, round, maxRounds, roundBlockingCount),
736 + onText: (text)
=> onPartial?.(
"proposer", round, maxRounds, roundBlockingCount, text),
645 739 return { devilOutput, proposerOutput, roundBlockingCount, aborted:
!!signal?.aborted };
649 743 async function synthesizeDebate(
651 745 roundsData
: string[],
654 748 headers
: Record<
string,
string>
| undefined,
655 749 signal
: AbortSignal | undefined,
677 771 async function runDebate(opts
: RunDebateOptions)
: Promise<
DebateOutput> {
678 - const { idea, context, model, apiKey, headers, maxRounds, stoppingConditions, concessionThreshold, signal, onStatus, onChallenge, onRound }
= opts;
772 + const { idea, context, model, ctx, apiKey, headers, maxRounds, stoppingConditions, concessionThreshold, signal, onStatus, onChallenge, onPartial, onRound }
= opts;
680 774 const contextText
= buildContextText(context);
681 775 const roundsData
: string[]
= [];
689 783 if (earlyExit)
return earlyExit;
691 785 const { devilOutput, proposerOutput, roundBlockingCount, aborted }
= await runRound(
692 - round, maxRounds, idea, contextText, roundHistory, model, apiKey, headers, signal, onStatus,
786 + round, maxRounds, idea, contextText, roundHistory, model, ctx, signal, onStatus, onChallenge, onPartial,
694 788 if (aborted)
return abortedResult(roundsData, blockingIssuesFound);
696 790 blockingIssuesFound
+= roundBlockingCount;
697 - onChallenge?.(round, maxRounds, blockingIssuesFound, devilOutput);
699 792 roundsData.
push(
`### Round ${round}\n\n**Challenge:**\n${devilOutput}\n\n**Response:**\n${proposerOutput}`);
700 793 roundHistory
+= `### Round ${round}\n**Challenge:** ${devilOutput.slice(0, ROUND_HISTORY_TRUNCATE)}\n**Response:** ${proposerOutput.slice(0, ROUND_HISTORY_TRUNCATE)}\n\n`;
748 841 return `${output.synthesis}${blockingNote}\n\n${meta}`;
844 +function buildMainAgentHandoff(idea
: string, verdict
: string)
: string {
846 + "Devil's Advocate report follows. Treat it as advisory evidence, not truth.",
847 + "Critically evaluate it against current repo/session context. Call out anything wrong, overstated, stale, or unsupported.",
848 + "Do not change files or run bash from this report alone. Present a concrete plan first; user can cancel or redirect before execution.",
849 + `Original idea:\n${idea}`,
850 + `Report:\n${verdict}`,
753 856 export default async function (pi
: ExtensionAPI) {
754 - const settings
= pi.settingsManager?.
getSettings();
755 - const devilSettings
: DevilSettings = settings?.devil
?? {};
857 + gcEphemeralForks();
858 + const settings
= (pi
as SettingsAPI).settingsManager?.
getSettings();
859 + const devilSettings
: DevilSettings = (settings?.devil
?? {})
as DevilSettings;
756 860 const activeControllers
= new Set<
AbortController>();
760 - pi.
registerFlag(
"devil-max-rounds", {
761 - description:
"Override max debate rounds (1-10)",
763 - default: devilSettings.maxRounds
?? DEFAULT_MAX_ROUNDS,
864 + pi.
registerFlag(
"devil-rounds", {
865 + description:
"Override max debate rounds (1-5)",
867 + default:
String(devilSettings.maxRounds
?? DEFAULT_MAX_ROUNDS),
766 870 pi.
registerFlag(
"devil-stop", {
775 879 activeControllers.
clear();
780 885 pi.
registerCommand(
"devil", {
804 - const maxRounds
= pi.
getFlag(
"devil-max-rounds")
as number ?? devilSettings.maxRounds
?? DEFAULT_MAX_ROUNDS;
909 + const usage
= ctx.
getContextUsage();
910 + if (usage?.percent
!== null && usage?.percent
!== undefined && usage.percent
> 85) {
911 + const ok
= await ctx.ui.
confirm(
913 + `Current session uses ${usage.percent.toFixed(1)}% of ${model.id}'s context. Continue Devil anyway?`,
918 + const maxRounds
= Math.
max(
1,
Math.
min(
5,
Number(pi.
getFlag(
"devil-rounds")
?? devilSettings.maxRounds
?? DEFAULT_MAX_ROUNDS)
|| DEFAULT_MAX_ROUNDS));
805 919 const stoppingConditions
= ((pi.
getFlag(
"devil-stop")
as string)
?? 806 920 devilSettings.stoppingConditions
?? 807 921 DEFAULT_STOPPING_CONDITIONS)
as "consensus" | "blocking_found" | "max_rounds";
825 939 context: debateContext,
827 942 apiKey: auth.apiKey
!,
828 943 headers: auth.
headers,
835 950 setDebateStatus(live, status, round, blocking);
836 951 review.
refresh();
953 + onPartial: (role, round, _max, blocking, text)
=> {
954 + if (
!review.
isActive())
return;
955 + upsertDebateEntry(live, role, round, blocking, text,
false);
838 958 onChallenge: (round, _max, blocking, devilOutput)
=> {
839 959 if (
!review.
isActive())
return;
840 - addDebateEntry(live,
"devil", round, blocking, devilOutput);
960 + upsertDebateEntry(live,
"devil", round, blocking, devilOutput,
true);
841 961 review.
refresh();
843 963 onRound: (round, _max, blocking, _status, _devilOutput, proposerOutput)
=> {
844 964 if (
!review.
isActive())
return;
845 - addDebateEntry(live,
"proposer", round, blocking, proposerOutput);
965 + upsertDebateEntry(live,
"proposer", round, blocking, proposerOutput,
true);
846 966 review.
refresh();
872 992 const outputText
= formatDebateOutput(result, onBlocking);
875 994 const edited
= await ctx.ui.
editor(
876 - `🗡️ ${result.recommendation.replace(/_/g, " ")} · ${result.blockingRaised} raised · ${result.blockingRemaining} unresolved`,
995 + `🗡️ ${result.recommendation.replace(/_/g, " ")} · Enter sends · Ctrl+G editor · Esc discards`,
891 1010 blockingRemaining: result.blockingRemaining,
892 1011 timestamp:
Date.
now(),
894 - pi.
sendUserMessage(edited);
1013 + pi.
sendUserMessage(
buildMainAgentHandoff(idea, edited));