xonecas.io
778
Pi

pi-extensions / commit 168d030

feat: add configurable adversarial review extension

xonecas2026-07-30 168d0306d54aa03a050c43735eb694794fc0be2e

5 files changed

.gitignore+2−0
@@ -0,0 +1,2 @@
1+node_modules/
2+*.log
README.md+53−0
@@ -0,0 +1,53 @@
1+# Pi extensions
2+
3+Personal Pi extensions, kept in one source-controlled collection.
4+
5+## Extensions
6+
7+### `adversary`
8+
9+Adds the `adversary_review` tool. The main agent can delegate an independent review to an isolated Pi process.
10+
11+The child receives the built-in `read`, `grep`, `find`, `ls`, and `bash` tools. Its model, thinking level, and review instructions are loaded from [`extensions/adversary/adversary.md`](extensions/adversary/adversary.md) each time the tool runs:
12+
13+```markdown
14+---
15+model: opencode/claude-sonnet-5
16+thinking: high
17+---
18+
19+Reviewer instructions go here.
20+```
21+
22+Edit that file to change the reviewer without reloading the extension. While a review runs, the tool display follows the child's latest tool action and then shows when it starts writing findings.
23+
24+Ask Pi naturally:
25+
26+```text
27+Use the adversary to review the current work against my request.
28+```
29+
30+## Enable or disable
31+
32+Extensions remain here under `~/src`. Pi discovers enabled extensions through symlinks in `~/.pi/agent/extensions`.
33+
34+Enable:
35+
36+```bash
37+mkdir -p ~/.pi/agent/extensions
38+ln -s ~/src/pi-extensions/extensions/adversary ~/.pi/agent/extensions/adversary
39+```
40+
41+Disable:
42+
43+```bash
44+rm ~/.pi/agent/extensions/adversary
45+```
46+
47+Run `/reload` after either change, or restart Pi.
48+
49+For a one-off session without enabling it globally:
50+
51+```bash
52+pi -e ~/src/pi-extensions/extensions/adversary/index.ts
53+```
extensions/adversary/adversary.md+41−0
@@ -0,0 +1,41 @@
1+---
2+model: opencode/claude-sonnet-5
3+thinking: high
4+---
5+
6+# Adversarial Reviewer
7+
8+Review the requested change with a skeptical, evidence-driven mindset. Your job is to find issues that would matter to the author before the change ships, not to summarize the implementation or praise it.
9+
10+You are strictly read-only:
11+
12+- Do not edit files.
13+- Use the read/search tools and `bash` to inspect the repository, run tests, and gather evidence.
14+- Do not spawn other agents.
15+
16+## Review process
17+
18+1. Establish the intended behavior from the delegated task, relevant code, and repository conventions.
19+2. Inspect the complete relevant diff, including newly added, modified, and deleted files.
20+3. Trace important control flow and data flow beyond changed lines when needed.
21+4. Look specifically for correctness defects, behavioral regressions, security or privacy vulnerabilities, data loss, race conditions, error-handling gaps, compatibility problems, and test gaps.
22+5. Run focused read-only inspection when it can confirm a concern.
23+
24+## Standards
25+
26+- Report only concrete, actionable findings. Do not invent hypothetical concerns without a plausible failure path.
27+- Treat the stated requirements and established repository behavior as the source of truth.
28+- Do not downgrade a real issue because it existed before the change; identify it when the change introduces or worsens it.
29+- Prefer a small number of high-signal findings to a long checklist of style nits.
30+- Do not propose or apply code changes unless the user explicitly asks for a fix after the review.
31+
32+## Output
33+
34+Begin with findings ordered by severity: `critical`, `high`, `medium`, then `low`. For every finding, include:
35+
36+- Severity and a concise title
37+- Precise file and line reference
38+- The failure scenario and why it violates the intended behavior
39+- A focused remediation direction
40+
41+If no findings are warranted, state exactly: `No findings.` Then briefly note residual risks or tests that could not be run. Do not include a change summary unless it is necessary to explain a finding.
extensions/adversary/index.ts+276−0
@@ -0,0 +1,276 @@
1+import { readFile } from "node:fs/promises";
2+import path from "node:path";
3+import { fileURLToPath } from "node:url";
4+import type { AssistantMessage, Usage } from "@earendil-works/pi-ai";
5+import {
6+ type ExtensionAPI,
7+ getPackageDir,
8+ parseFrontmatter,
9+ RpcClient,
10+} from "@earendil-works/pi-coding-agent";
11+import { Type } from "typebox";
12+
13+const TIMEOUT_MS = 30 * 60 * 1_000;
14+const THINKING_LEVELS = [
15+ "off",
16+ "minimal",
17+ "low",
18+ "medium",
19+ "high",
20+ "xhigh",
21+ "max",
22+] as const;
23+
24+type ThinkingLevel = (typeof THINKING_LEVELS)[number];
25+type ProgressUpdate = (text: string, details: Record<string, unknown>) => void;
26+
27+interface AdversaryConfig {
28+ model: string;
29+ thinking: ThinkingLevel;
30+ systemPrompt: string;
31+}
32+
33+const extensionPath = fileURLToPath(import.meta.url);
34+const promptPath = path.join(path.dirname(extensionPath), "adversary.md");
35+
36+const AdversaryParams = Type.Object({
37+ task: Type.String({
38+ description:
39+ "Review brief containing the intended behavior, scope, constraints, and relevant context from the main conversation",
40+ }),
41+});
42+
43+async function loadAdversaryConfig(): Promise<AdversaryConfig> {
44+ const content = await readFile(promptPath, "utf8");
45+ const { frontmatter, body } =
46+ parseFrontmatter<Record<string, unknown>>(content);
47+ const model =
48+ typeof frontmatter.model === "string" ? frontmatter.model.trim() : "";
49+ const thinking = frontmatter.thinking;
50+
51+ if (!model) {
52+ throw new Error(
53+ `${promptPath} must declare a non-empty "model" in its frontmatter`,
54+ );
55+ }
56+ if (
57+ typeof thinking !== "string" ||
58+ !THINKING_LEVELS.includes(thinking as ThinkingLevel)
59+ ) {
60+ throw new Error(
61+ `${promptPath} must declare "thinking" as one of: ${THINKING_LEVELS.join(", ")}`,
62+ );
63+ }
64+ if (!body.trim()) {
65+ throw new Error(
66+ `${promptPath} must contain reviewer instructions after its frontmatter`,
67+ );
68+ }
69+
70+ return {
71+ model,
72+ thinking: thinking as ThinkingLevel,
73+ systemPrompt: body.trim(),
74+ };
75+}
76+
77+function compactAction(value: unknown, maxLength = 120): string {
78+ const text =
79+ typeof value === "string"
80+ ? value.replace(/\s+/g, " ").trim()
81+ : JSON.stringify(value);
82+ if (!text) return "";
83+ return text.length > maxLength ? `${text.slice(0, maxLength - 1)}…` : text;
84+}
85+
86+function describeToolAction(toolName: string, args: unknown): string {
87+ if (args && typeof args === "object") {
88+ const input = args as Record<string, unknown>;
89+ if (toolName === "bash" && typeof input.command === "string") {
90+ return `${toolName}: ${compactAction(input.command)}`;
91+ }
92+ if (toolName === "read" && typeof input.path === "string") {
93+ return `${toolName}: ${compactAction(input.path)}`;
94+ }
95+ }
96+ const detail = compactAction(args);
97+ return detail && detail !== "{}" ? `${toolName}: ${detail}` : toolName;
98+}
99+
100+function emptyUsage(): Usage {
101+ return {
102+ input: 0,
103+ output: 0,
104+ cacheRead: 0,
105+ cacheWrite: 0,
106+ totalTokens: 0,
107+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
108+ };
109+}
110+
111+function addUsage(total: Usage, next: Usage): void {
112+ total.input += next.input;
113+ total.output += next.output;
114+ total.cacheRead += next.cacheRead;
115+ total.cacheWrite += next.cacheWrite;
116+ total.totalTokens += next.totalTokens;
117+ total.cost.input += next.cost.input;
118+ total.cost.output += next.cost.output;
119+ total.cost.cacheRead += next.cost.cacheRead;
120+ total.cost.cacheWrite += next.cost.cacheWrite;
121+ total.cost.total += next.cost.total;
122+ if (next.cacheWrite1h !== undefined) {
123+ total.cacheWrite1h = (total.cacheWrite1h ?? 0) + next.cacheWrite1h;
124+ }
125+ if (next.reasoning !== undefined) {
126+ total.reasoning = (total.reasoning ?? 0) + next.reasoning;
127+ }
128+}
129+
130+function finalText(messages: AssistantMessage[]): string {
131+ for (let index = messages.length - 1; index >= 0; index--) {
132+ const text = messages[index]?.content
133+ .filter(
134+ (part): part is { type: "text"; text: string } => part.type === "text",
135+ )
136+ .map((part) => part.text)
137+ .join("\n")
138+ .trim();
139+ if (text) return text;
140+ }
141+ return "";
142+}
143+
144+async function runAdversary(
145+ task: string,
146+ cwd: string,
147+ signal?: AbortSignal,
148+ onProgress?: ProgressUpdate,
149+) {
150+ const config = await loadAdversaryConfig();
151+ const client = new RpcClient({
152+ cliPath: path.join(getPackageDir(), "dist", "cli.js"),
153+ cwd,
154+ model: config.model,
155+ args: [
156+ "--no-session",
157+ "--no-skills",
158+ "--no-prompt-templates",
159+ "--no-extensions",
160+ "--tools",
161+ "read,grep,find,ls,bash",
162+ "--thinking",
163+ config.thinking,
164+ "--append-system-prompt",
165+ config.systemPrompt,
166+ ],
167+ });
168+ const abort = () => void client.abort().catch(() => undefined);
169+ let unsubscribe: (() => void) | undefined;
170+
171+ try {
172+ if (signal?.aborted) throw new Error("Adversarial review aborted");
173+ onProgress?.("Adversarial reviewer is starting…", {
174+ model: config.model,
175+ thinking: config.thinking,
176+ status: "starting",
177+ });
178+ await client.start();
179+ signal?.addEventListener("abort", abort, { once: true });
180+ unsubscribe = client.onEvent((event) => {
181+ if (event.type === "tool_execution_start") {
182+ const action = describeToolAction(event.toolName, event.args);
183+ onProgress?.(`Reviewer action — ${action}`, {
184+ model: config.model,
185+ thinking: config.thinking,
186+ status: "running",
187+ action,
188+ });
189+ } else if (
190+ event.type === "message_update" &&
191+ event.assistantMessageEvent.type === "text_start"
192+ ) {
193+ onProgress?.("Reviewer is writing findings…", {
194+ model: config.model,
195+ thinking: config.thinking,
196+ status: "writing",
197+ });
198+ }
199+ });
200+ const events = await client.promptAndWait(
201+ [
202+ "Perform an adversarial review of the current repository work.",
203+ "Treat the delegated brief below as the authoritative description of intent.",
204+ "Inspect the repository and return findings only; never modify files.",
205+ "",
206+ "Delegated brief:",
207+ task,
208+ ].join("\n"),
209+ undefined,
210+ TIMEOUT_MS,
211+ );
212+
213+ const messages: AssistantMessage[] = [];
214+ const usage = emptyUsage();
215+ for (const event of events) {
216+ if (event.type !== "message_end" || event.message.role !== "assistant")
217+ continue;
218+ messages.push(event.message);
219+ addUsage(usage, event.message.usage);
220+ }
221+
222+ const last = messages[messages.length - 1];
223+ if (!last) throw new Error("Adversary returned no response");
224+ if (last.stopReason === "error" || last.stopReason === "aborted") {
225+ throw new Error(
226+ last.errorMessage || `Adversary stopped: ${last.stopReason}`,
227+ );
228+ }
229+
230+ return {
231+ text: finalText(messages) || "No findings.",
232+ usage,
233+ turns: messages.length,
234+ model: config.model,
235+ thinking: config.thinking,
236+ };
237+ } finally {
238+ unsubscribe?.();
239+ signal?.removeEventListener("abort", abort);
240+ await client.stop();
241+ }
242+}
243+
244+export default function adversaryExtension(pi: ExtensionAPI): void {
245+ pi.registerTool({
246+ name: "adversary_review",
247+ label: "Adversary Review",
248+ description:
249+ "Delegate a focused, read-only adversarial code review to the reviewer configured in adversary.md.",
250+ promptSnippet:
251+ "Run a read-only adversarial review in an isolated reviewer context",
252+ promptGuidelines: [
253+ "Use adversary_review when the user asks for an adversarial or independent review; include the intended behavior and constraints in its task.",
254+ ],
255+ parameters: AdversaryParams,
256+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
257+ const result = await runAdversary(
258+ params.task,
259+ ctx.cwd,
260+ signal,
261+ (text, details) => {
262+ onUpdate?.({ content: [{ type: "text", text }], details });
263+ },
264+ );
265+ return {
266+ content: [{ type: "text", text: result.text }],
267+ details: {
268+ model: result.model,
269+ thinking: result.thinking,
270+ turns: result.turns,
271+ },
272+ usage: result.usage,
273+ };
274+ },
275+ });
276+}
package.json+5−0
@@ -0,0 +1,5 @@
1+{
2+ "name": "xonecas-pi-extensions",
3+ "private": true,
4+ "type": "module"
5+}