@howaboua/pi-subagent-review 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Igor Warzocha
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,77 @@
1
+ # pi-subagent-review
2
+
3
+ `@howaboua/pi-subagent-review` is a Pi extension that adds one slash command:
4
+
5
+ - `/review`
6
+
7
+ It runs an isolated review subagent against your current repo, injects the findings back into the session as a user message, and the main agent then automatically continues by addressing those findings. It is modelled after Codex CLI's /review command.
8
+
9
+ ## What it does
10
+
11
+ `/review`:
12
+ - detects the current git repo
13
+ - chooses a base branch automatically
14
+ - computes the merge base with `HEAD`
15
+ - inspects committed and dirty worktree changes
16
+ - runs an isolated review subagent
17
+ - sends the findings back into the current Pi session as a user message
18
+ - as a result, the main agent automatically works through the review findings
19
+
20
+ ## Automatic base branch selection
21
+
22
+ The command chooses the base branch automatically:
23
+
24
+ - if you are on a branch other than `main`, `master`, or `dev`, it reviews against `dev`
25
+ - if no local `dev` exists, it falls back to `main`, then `master`
26
+ - if you are on `dev`, it reviews against `main`, then `master`
27
+ - if you are on `main` or `master`, it prefers `dev` when available
28
+
29
+ This means you usually never need to specify the diff base manually.
30
+
31
+ ## User arguments
32
+
33
+ Anything after `/review` is treated as extra review guidance.
34
+
35
+ Examples:
36
+
37
+ ```text
38
+ /review
39
+ /review focus extra attention on migrations and tests
40
+ /review assess whether we introduced new UI elements instead of reusing established components and existing CSS patterns
41
+ ```
42
+
43
+ ## Config
44
+
45
+ On first load, the extension creates:
46
+
47
+ - `~/.pi/agent/pi-subagent-review.json`
48
+
49
+ If Pi is using a custom agent directory via `PI_CODING_AGENT_DIR`, the file is created there instead.
50
+
51
+ Edit that file to change the default review model or thinking level:
52
+
53
+ ```json
54
+ {
55
+ "model": "openai-codex/gpt-5.4",
56
+ "thinking": "high"
57
+ }
58
+ ```
59
+
60
+ If that configured model is not available for the user, `/review` falls back to the current session model automatically.
61
+
62
+ ## Install
63
+
64
+ Installation methods:
65
+
66
+ ```bash
67
+ pi install /absolute/path/to/pi-subagent-review
68
+ pi install npm:@howaboua/pi-subagent-review
69
+ pi install git:github.com/IgorWarzocha/pi-subagent-review
70
+ ```
71
+
72
+ Then reload or restart Pi.
73
+
74
+ ## Notes
75
+
76
+ - This extension registers `/review`.
77
+ - Do not load it together with another extension that also registers `/review` unless you intentionally want that command collision.
package/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
+ import { ensureConfigFile } from "./src/config.js";
3
+ import { CHILD_ENV } from "./src/constants.js";
4
+ import { registerReviewCommand } from "./src/review-command.js";
5
+
6
+ export default function (pi: ExtensionAPI) {
7
+ if (process.env[CHILD_ENV] === "1") return;
8
+
9
+ ensureConfigFile();
10
+ registerReviewCommand(pi);
11
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@howaboua/pi-subagent-review",
3
+ "version": "0.1.0",
4
+ "description": "Pi extension that adds /review via an isolated review subagent.",
5
+ "license": "MIT",
6
+ "files": [
7
+ "index.ts",
8
+ "src",
9
+ "review.prompt.md",
10
+ "README.md"
11
+ ],
12
+ "keywords": [
13
+ "pi-package",
14
+ "pi",
15
+ "pi-extension",
16
+ "review",
17
+ "code-review",
18
+ "subagent",
19
+ "agent"
20
+ ],
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/IgorWarzocha/pi-subagent-review.git"
24
+ },
25
+ "homepage": "https://github.com/IgorWarzocha/pi-subagent-review#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/IgorWarzocha/pi-subagent-review/issues"
28
+ },
29
+ "pi": {
30
+ "extensions": [
31
+ "./index.ts"
32
+ ]
33
+ },
34
+ "peerDependencies": {
35
+ "@mariozechner/pi-coding-agent": "*"
36
+ }
37
+ }
@@ -0,0 +1,23 @@
1
+ You are the Review Subagent, an isolated code-review specialist.
2
+
3
+ Rules:
4
+ - Stay strictly in review mode.
5
+ - You do not inherit the parent agent's prior conversation, plan, or hidden context. Treat the provided task as the entire brief.
6
+ - Do not edit files.
7
+ - Do not invoke other subagents or delegate again.
8
+ - Prefer `git diff`, targeted file reads, and concrete evidence over assumptions.
9
+ - Focus on actionable findings, not broad summaries.
10
+ - Prioritize correctness, regressions, security, data loss, performance, concurrency, and missing tests.
11
+ - Reference specific file paths and line ranges when possible.
12
+ - Suggest the smallest credible fix when helpful.
13
+ - If there are no actionable issues worth flagging, say that clearly.
14
+
15
+ Output format:
16
+ # Review Findings
17
+ - `[high|medium|low] path/to/file:start-end` - issue, why it matters, and the concrete fix
18
+ - `[high|medium|low] path/to/file:start-end` - issue, why it matters, and the concrete fix
19
+
20
+ If there are no actionable issues, output exactly:
21
+
22
+ # Review Findings
23
+ No actionable issues found.
package/src/config.ts ADDED
@@ -0,0 +1,94 @@
1
+ import fs from "node:fs";
2
+ import type { ExtensionAPI, ExtensionCommandContext } from "@mariozechner/pi-coding-agent";
3
+ import { ALLOWED_THINKING, DEFAULT_CONFIG, REVIEW_COMMAND, getAgentDir, getConfigPath } from "./constants.js";
4
+ import type { ChildRunDetails, ReviewConfig, ThinkingLevel, UsageStats } from "./types.js";
5
+
6
+ function normalizeThinking(value: ThinkingLevel | undefined): ThinkingLevel {
7
+ return value && ALLOWED_THINKING.has(value) ? value : DEFAULT_CONFIG.thinking;
8
+ }
9
+
10
+ export function ensureConfigFile(): string {
11
+ const agentDir = getAgentDir();
12
+ const configPath = getConfigPath();
13
+ fs.mkdirSync(agentDir, { recursive: true });
14
+ if (!fs.existsSync(configPath)) {
15
+ fs.writeFileSync(configPath, `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`, "utf8");
16
+ }
17
+ return configPath;
18
+ }
19
+
20
+ export function readConfig(): Required<ReviewConfig> {
21
+ let parsed: ReviewConfig | undefined;
22
+ const configPath = ensureConfigFile();
23
+ try {
24
+ parsed = JSON.parse(fs.readFileSync(configPath, "utf8")) as ReviewConfig;
25
+ } catch (error) {
26
+ throw new Error(`Could not parse ${configPath}: ${error instanceof Error ? error.message : String(error)}`);
27
+ }
28
+
29
+ return {
30
+ model: typeof parsed?.model === "string" && parsed.model.trim() ? parsed.model.trim() : DEFAULT_CONFIG.model,
31
+ thinking: normalizeThinking(parsed?.thinking),
32
+ };
33
+ }
34
+
35
+ function emptyUsage(): UsageStats {
36
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 };
37
+ }
38
+
39
+ export function createChildRunDetails(task: string, cwd: string, config = readConfig()): ChildRunDetails {
40
+ return {
41
+ mode: "review",
42
+ toolName: REVIEW_COMMAND,
43
+ task,
44
+ cwd,
45
+ model: config.model,
46
+ thinking: config.thinking,
47
+ messages: [],
48
+ stderr: "",
49
+ exitCode: 0,
50
+ usage: emptyUsage(),
51
+ };
52
+ }
53
+
54
+ export function isSubagentFailure(details: Pick<ChildRunDetails, "exitCode" | "stopReason">): boolean {
55
+ return details.exitCode !== 0 || details.stopReason === "error" || details.stopReason === "aborted";
56
+ }
57
+
58
+ function splitModelRef(modelRef: string): { provider: string; modelId: string } | undefined {
59
+ const slash = modelRef.indexOf("/");
60
+ if (slash <= 0 || slash === modelRef.length - 1) return undefined;
61
+ return {
62
+ provider: modelRef.slice(0, slash),
63
+ modelId: modelRef.slice(slash + 1),
64
+ };
65
+ }
66
+
67
+ async function canUseModel(ctx: ExtensionCommandContext, modelRef: string): Promise<boolean> {
68
+ const parsed = splitModelRef(modelRef);
69
+ if (!parsed) return false;
70
+ const model = ctx.modelRegistry.find(parsed.provider, parsed.modelId);
71
+ if (!model) return false;
72
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
73
+ return auth.ok;
74
+ }
75
+
76
+ export async function resolveReviewConfig(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<Required<ReviewConfig> & { source: "configured" | "current" }> {
77
+ const configured = readConfig();
78
+ if (await canUseModel(ctx, configured.model)) {
79
+ return { ...configured, source: "configured" };
80
+ }
81
+
82
+ if (ctx.model) {
83
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model);
84
+ if (auth.ok) {
85
+ return {
86
+ model: `${ctx.model.provider}/${ctx.model.id}`,
87
+ thinking: pi.getThinkingLevel() as ThinkingLevel,
88
+ source: "current",
89
+ };
90
+ }
91
+ }
92
+
93
+ return { ...configured, source: "configured" };
94
+ }
@@ -0,0 +1,31 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
6
+
7
+ export const CHILD_ENV = "PI_REVIEW_EXTENSION_CHILD";
8
+ export const REVIEW_COMMAND = "review";
9
+ export const REVIEW_LABEL = "Review";
10
+ export const CONFIG_FILENAME = "pi-subagent-review.json";
11
+ export const REVIEW_PROMPT_PATH = path.join(path.resolve(__dirname, ".."), "review.prompt.md");
12
+
13
+ export const DEFAULT_CONFIG = {
14
+ model: "openai-codex/gpt-5.4",
15
+ thinking: "high",
16
+ } as const;
17
+
18
+ export const ALLOWED_THINKING = new Set(["off", "minimal", "low", "medium", "high", "xhigh"] as const);
19
+ export const RPC_READY_TIMEOUT_MS = 10_000;
20
+ export const RPC_RESPONSE_TIMEOUT_MS = 30_000;
21
+ export const RPC_POLL_MS = 150;
22
+ export const RPC_QUIESCENCE_MS = 500;
23
+
24
+ export function getAgentDir(): string {
25
+ const configured = process.env.PI_CODING_AGENT_DIR?.trim();
26
+ return configured || path.join(os.homedir(), ".pi", "agent");
27
+ }
28
+
29
+ export function getConfigPath(): string {
30
+ return path.join(getAgentDir(), CONFIG_FILENAME);
31
+ }
@@ -0,0 +1,56 @@
1
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
+ import { REVIEW_COMMAND } from "./constants.js";
3
+ import { createChildRunDetails, isSubagentFailure, resolveReviewConfig } from "./config.js";
4
+ import { buildReviewTask, buildReviewUserMessage, detectReviewContext } from "./review.js";
5
+ import { getFinalOutput, runReviewSubagent } from "./subagent.js";
6
+
7
+ export function registerReviewCommand(pi: ExtensionAPI) {
8
+ pi.registerCommand(REVIEW_COMMAND, {
9
+ description: "Run an isolated code-review subagent against the current repo and send the findings back as a user message",
10
+ handler: async (args, ctx) => {
11
+ if (!ctx.isIdle()) {
12
+ ctx.ui.notify(`Waiting for the current turn to finish before running /${REVIEW_COMMAND}...`, "info");
13
+ await ctx.waitForIdle();
14
+ }
15
+
16
+ ctx.ui.notify(`Running /${REVIEW_COMMAND} against the current repo...`, "info");
17
+
18
+ let review;
19
+ try {
20
+ review = await detectReviewContext(pi, ctx.cwd);
21
+ } catch (error) {
22
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
23
+ return;
24
+ }
25
+
26
+ if (!review.hasAnyChanges) {
27
+ pi.sendUserMessage(buildReviewUserMessage(review, "No changes found relative to the selected base branch."));
28
+ ctx.ui.notify(`No changes found relative to ${review.baseBranch}; sent summary to the agent.`, "info");
29
+ return;
30
+ }
31
+
32
+ const task = buildReviewTask(review, args);
33
+ const reviewConfig = await resolveReviewConfig(pi, ctx);
34
+ let details = createChildRunDetails(task, review.repoRoot, reviewConfig);
35
+ if (reviewConfig.source === "current") {
36
+ ctx.ui.notify(`Configured review model unavailable; falling back to current session model ${reviewConfig.model}.`, "warning");
37
+ }
38
+
39
+ try {
40
+ details = await runReviewSubagent(task, review.repoRoot, reviewConfig);
41
+ const finalOutput = getFinalOutput(details.messages).trim() || "No actionable issues found.";
42
+ if (isSubagentFailure(details)) throw new Error(details.errorMessage || details.stderr || finalOutput);
43
+
44
+ const message = buildReviewUserMessage(review, finalOutput);
45
+ if (ctx.isIdle()) pi.sendUserMessage(message);
46
+ else pi.sendUserMessage(message, { deliverAs: "followUp" });
47
+ ctx.ui.notify(`Review findings sent back to the main agent from /${REVIEW_COMMAND}.`, "info");
48
+ } catch (error) {
49
+ const message = error instanceof Error ? error.message : String(error);
50
+ details.exitCode = details.exitCode || 1;
51
+ details.errorMessage = message;
52
+ ctx.ui.notify(`/${REVIEW_COMMAND} failed: ${message}`, "error");
53
+ }
54
+ },
55
+ });
56
+ }
package/src/review.ts ADDED
@@ -0,0 +1,142 @@
1
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
+ import { REVIEW_COMMAND } from "./constants.js";
3
+ import type { ReviewContext } from "./types.js";
4
+
5
+ async function runGit(pi: ExtensionAPI, cwd: string, args: string[], timeout = 10_000) {
6
+ return pi.exec("git", args, { cwd, timeout });
7
+ }
8
+
9
+ async function gitString(pi: ExtensionAPI, cwd: string, args: string[], timeout = 10_000): Promise<string> {
10
+ const result = await runGit(pi, cwd, args, timeout);
11
+ if (result.code !== 0) {
12
+ const command = `git ${args.join(" ")}`;
13
+ const message = result.stderr.trim() || result.stdout.trim() || `${command} failed with exit code ${result.code}`;
14
+ throw new Error(message);
15
+ }
16
+ return result.stdout.trim();
17
+ }
18
+
19
+ async function hasLocalBranch(pi: ExtensionAPI, cwd: string, branch: "main" | "master"): Promise<boolean> {
20
+ const result = await runGit(pi, cwd, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]);
21
+ return result.code === 0;
22
+ }
23
+
24
+ async function hasLocalDevBranch(pi: ExtensionAPI, cwd: string): Promise<boolean> {
25
+ const result = await runGit(pi, cwd, ["show-ref", "--verify", "--quiet", "refs/heads/dev"]);
26
+ return result.code === 0;
27
+ }
28
+
29
+ async function hasTrackedChangesAgainst(pi: ExtensionAPI, cwd: string, revision: string): Promise<boolean> {
30
+ const result = await runGit(pi, cwd, ["diff", "--quiet", revision]);
31
+ if (result.code === 0) return false;
32
+ if (result.code === 1) return true;
33
+ throw new Error(result.stderr.trim() || `git diff --quiet ${revision} failed with exit code ${result.code}`);
34
+ }
35
+
36
+ export async function detectReviewContext(pi: ExtensionAPI, cwd: string): Promise<ReviewContext> {
37
+ const repoRoot = await gitString(pi, cwd, ["rev-parse", "--show-toplevel"]);
38
+ const currentBranch = await gitString(pi, repoRoot, ["branch", "--show-current"]);
39
+ const [hasDev, hasMain, hasMaster] = await Promise.all([
40
+ hasLocalDevBranch(pi, repoRoot),
41
+ hasLocalBranch(pi, repoRoot, "main"),
42
+ hasLocalBranch(pi, repoRoot, "master"),
43
+ ]);
44
+
45
+ let baseBranch: "main" | "master" | "dev" | undefined;
46
+ if (currentBranch === "dev") {
47
+ if (hasMain) baseBranch = "main";
48
+ else if (hasMaster) baseBranch = "master";
49
+ } else if (currentBranch !== "main" && currentBranch !== "master") {
50
+ if (hasDev) baseBranch = "dev";
51
+ else if (hasMain) baseBranch = "main";
52
+ else if (hasMaster) baseBranch = "master";
53
+ } else {
54
+ if (hasDev) baseBranch = "dev";
55
+ else if (currentBranch === "main" && hasMaster) baseBranch = "master";
56
+ else if (currentBranch === "master" && hasMain) baseBranch = "main";
57
+ else baseBranch = currentBranch as "main" | "master";
58
+ }
59
+
60
+ if (!baseBranch) {
61
+ const branches = await gitString(pi, repoRoot, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]);
62
+ throw new Error(`Could not determine an automatic review base branch. Local branches: ${branches || "(none)"}`);
63
+ }
64
+
65
+ const currentRef = currentBranch || (await gitString(pi, repoRoot, ["rev-parse", "--short", "HEAD"]));
66
+ const mergeBase = await gitString(pi, repoRoot, ["merge-base", baseBranch, "HEAD"]);
67
+ const baseTip = await gitString(pi, repoRoot, ["rev-parse", "--short", baseBranch]);
68
+ const recentBaseCommits = await gitString(pi, repoRoot, ["log", "--oneline", "--decorate", "-n", "8", baseBranch]);
69
+ const status = await gitString(pi, repoRoot, ["status", "--short", "--untracked-files=all"]);
70
+ const hasTrackedChanges = await hasTrackedChangesAgainst(pi, repoRoot, mergeBase);
71
+ const hasAnyChanges = hasTrackedChanges || status.length > 0;
72
+
73
+ return {
74
+ repoRoot,
75
+ currentRef,
76
+ baseBranch,
77
+ mergeBase,
78
+ baseTip,
79
+ status,
80
+ recentBaseCommits,
81
+ hasTrackedChanges,
82
+ hasAnyChanges,
83
+ };
84
+ }
85
+
86
+ export function buildReviewTask(review: ReviewContext, extraFocus: string): string {
87
+ const sections = [
88
+ `Repository root: ${review.repoRoot}`,
89
+ `Current ref: ${review.currentRef}`,
90
+ `Chosen local base branch: ${review.baseBranch}`,
91
+ `Base branch tip (short SHA): ${review.baseTip}`,
92
+ `Merge base (${review.baseBranch}, HEAD): ${review.mergeBase}`,
93
+ "",
94
+ `Recent commits on ${review.baseBranch}:`,
95
+ review.recentBaseCommits || "(none)",
96
+ "",
97
+ "Current status (`git status --short --untracked-files=all`):",
98
+ review.status || "(clean)",
99
+ "",
100
+ "Review the current checkout against the merge base so uncommitted changes are included while base-only commits are excluded.",
101
+ "Required inspection steps:",
102
+ `1. Run \`git diff --stat ${review.mergeBase}\``,
103
+ `2. Run \`git diff ${review.mergeBase}\``,
104
+ `3. Run \`git diff --stat ${review.baseBranch}...HEAD\``,
105
+ `4. Run \`git diff ${review.baseBranch}...HEAD\``,
106
+ "5. Use targeted file diffs or reads where needed.",
107
+ ];
108
+
109
+ if (review.status) {
110
+ sections.push(
111
+ "",
112
+ "Because the worktree is not clean, also inspect:",
113
+ "- `git diff --cached`",
114
+ "- `git diff`",
115
+ "- any relevant untracked files reported by status",
116
+ );
117
+ }
118
+
119
+ sections.push(
120
+ "",
121
+ "Return prioritized, actionable findings only.",
122
+ "Focus on correctness, regressions, security, data loss, performance, concurrency, and missing tests.",
123
+ "Reference specific files and line ranges when possible.",
124
+ "If there are no actionable issues worth flagging, say that clearly.",
125
+ );
126
+
127
+ if (extraFocus.trim()) {
128
+ sections.push("", `Additional user focus: ${extraFocus.trim()}`);
129
+ }
130
+
131
+ return sections.join("\n");
132
+ }
133
+
134
+ export function buildReviewUserMessage(review: ReviewContext, findings: string): string {
135
+ return [
136
+ `Review findings from /${REVIEW_COMMAND} against local base branch \`${review.baseBranch}\` in \`${review.repoRoot}\` (merge base \`${review.mergeBase.slice(0, 12)}\`):`,
137
+ "",
138
+ findings.trim() || "No actionable issues found.",
139
+ "",
140
+ "Please address the findings above. If there are no actionable issues, briefly confirm that.",
141
+ ].join("\n");
142
+ }
@@ -0,0 +1,204 @@
1
+ import { spawn } from "node:child_process";
2
+ import { CHILD_ENV, REVIEW_LABEL, REVIEW_PROMPT_PATH, RPC_POLL_MS, RPC_QUIESCENCE_MS, RPC_READY_TIMEOUT_MS, RPC_RESPONSE_TIMEOUT_MS } from "./constants.js";
3
+ import { createChildRunDetails } from "./config.js";
4
+ import type { ReviewConfig } from "./types.js";
5
+
6
+ function sleep(ms: number): Promise<void> {
7
+ return new Promise((resolve) => setTimeout(resolve, ms));
8
+ }
9
+
10
+ export function getFinalOutput(messages: any[]): string {
11
+ for (let i = messages.length - 1; i >= 0; i--) {
12
+ const message = messages[i];
13
+ if (message.role !== "assistant") continue;
14
+ for (const part of message.content) {
15
+ if (part.type === "text") return part.text;
16
+ }
17
+ }
18
+ return "";
19
+ }
20
+
21
+ export async function runReviewSubagent(task: string, cwd: string, config: Required<ReviewConfig>) {
22
+ const details = createChildRunDetails(task, cwd, config);
23
+ const args = [
24
+ "--mode",
25
+ "rpc",
26
+ "--no-session",
27
+ "--no-skills",
28
+ "--model",
29
+ config.model,
30
+ "--thinking",
31
+ config.thinking,
32
+ "--append-system-prompt",
33
+ REVIEW_PROMPT_PATH,
34
+ ];
35
+ const promptText = [
36
+ "Run as the Review Subagent inside an isolated no-session RPC subprocess.",
37
+ "Stay strictly in review mode. Do not edit files or propose implementation plans beyond concise fixes.",
38
+ "Mode: review",
39
+ `Task: ${task}`,
40
+ ].join("\n\n");
41
+
42
+ let lastEventAt = Date.now();
43
+ let agentEndCount = 0;
44
+ let promptSent = false;
45
+ let processClosed = false;
46
+ let processExitCode: number | undefined;
47
+ let requestId = 0;
48
+ let stoppedAfterCompletion = false;
49
+ let stdoutBuffer = "";
50
+ const pendingRequests = new Map<string, { resolve: (value: unknown) => void; reject: (error: Error) => void; timeout: ReturnType<typeof setTimeout> }>();
51
+
52
+ const proc = spawn("pi", args, {
53
+ cwd,
54
+ shell: false,
55
+ stdio: ["pipe", "pipe", "pipe"],
56
+ env: { ...process.env, [CHILD_ENV]: "1" },
57
+ });
58
+
59
+ const rejectPendingRequests = (error: Error) => {
60
+ for (const pending of pendingRequests.values()) {
61
+ clearTimeout(pending.timeout);
62
+ pending.reject(error);
63
+ }
64
+ pendingRequests.clear();
65
+ };
66
+
67
+ const sendCommand = <T = unknown>(command: Record<string, unknown>, timeoutMs = RPC_RESPONSE_TIMEOUT_MS): Promise<T> => {
68
+ if (processClosed || !proc.stdin.writable) {
69
+ throw new Error(`Review subagent RPC process is not available.${details.stderr ? ` Stderr: ${details.stderr.trim()}` : ""}`);
70
+ }
71
+
72
+ const id = `req_${++requestId}`;
73
+ const payload = JSON.stringify({ ...command, id }) + "\n";
74
+
75
+ return new Promise<T>((resolve, reject) => {
76
+ const timeout = setTimeout(() => {
77
+ pendingRequests.delete(id);
78
+ reject(new Error(`Timed out waiting for RPC response to ${String(command.type)}.${details.stderr ? ` Stderr: ${details.stderr.trim()}` : ""}`));
79
+ }, timeoutMs);
80
+
81
+ pendingRequests.set(id, { resolve, reject, timeout });
82
+ proc.stdin.write(payload, (error) => {
83
+ if (!error) return;
84
+ clearTimeout(timeout);
85
+ pendingRequests.delete(id);
86
+ reject(error instanceof Error ? error : new Error(String(error)));
87
+ });
88
+ });
89
+ };
90
+
91
+ const handleEvent = (event: any) => {
92
+ lastEventAt = Date.now();
93
+ if (event.type === "message_end" && event.message) {
94
+ const message = event.message;
95
+ details.messages.push(message);
96
+ if (message.role === "assistant") {
97
+ details.usage.turns++;
98
+ const usage = message.usage;
99
+ if (usage) {
100
+ details.usage.input += usage.input || 0;
101
+ details.usage.output += usage.output || 0;
102
+ details.usage.cacheRead += usage.cacheRead || 0;
103
+ details.usage.cacheWrite += usage.cacheWrite || 0;
104
+ details.usage.cost += usage.cost?.total || 0;
105
+ details.usage.contextTokens = usage.totalTokens || 0;
106
+ }
107
+ if (message.stopReason) details.stopReason = message.stopReason;
108
+ if (message.errorMessage) details.errorMessage = message.errorMessage;
109
+ }
110
+ return;
111
+ }
112
+
113
+ if (event.type === "agent_end") agentEndCount++;
114
+ };
115
+
116
+ const handleLine = (line: string) => {
117
+ if (!line.trim()) return;
118
+ let data: any;
119
+ try {
120
+ data = JSON.parse(line);
121
+ } catch {
122
+ return;
123
+ }
124
+
125
+ if (data.type === "response" && typeof data.id === "string" && pendingRequests.has(data.id)) {
126
+ const pending = pendingRequests.get(data.id)!;
127
+ clearTimeout(pending.timeout);
128
+ pendingRequests.delete(data.id);
129
+ if (data.success === false) pending.reject(new Error(typeof data.error === "string" ? data.error : `RPC ${data.command ?? "command"} failed`));
130
+ else pending.resolve(data.data as unknown);
131
+ return;
132
+ }
133
+
134
+ handleEvent(data);
135
+ };
136
+
137
+ const stopProcess = async () => {
138
+ if (processClosed) return;
139
+ stoppedAfterCompletion = true;
140
+ proc.kill("SIGTERM");
141
+ await Promise.race([
142
+ new Promise<void>((resolve) => proc.once("close", () => resolve())),
143
+ sleep(1_000).then(() => {
144
+ if (!processClosed) proc.kill("SIGKILL");
145
+ }),
146
+ ]);
147
+ };
148
+
149
+ proc.stdout.on("data", (chunk) => {
150
+ stdoutBuffer += chunk.toString();
151
+ const lines = stdoutBuffer.split("\n");
152
+ stdoutBuffer = lines.pop() || "";
153
+ for (const line of lines) handleLine(line);
154
+ });
155
+
156
+ proc.stderr.on("data", (chunk) => {
157
+ details.stderr += chunk.toString();
158
+ });
159
+
160
+ proc.on("close", (code) => {
161
+ processClosed = true;
162
+ processExitCode = code ?? 0;
163
+ if (stdoutBuffer.trim()) {
164
+ handleLine(stdoutBuffer);
165
+ stdoutBuffer = "";
166
+ }
167
+ rejectPendingRequests(new Error(`Review subagent RPC process exited with code ${processExitCode}.${details.stderr ? ` Stderr: ${details.stderr.trim()}` : ""}`));
168
+ });
169
+
170
+ proc.on("error", (error) => {
171
+ rejectPendingRequests(error instanceof Error ? error : new Error(String(error)));
172
+ });
173
+
174
+ try {
175
+ await sendCommand({ type: "get_state" }, RPC_READY_TIMEOUT_MS);
176
+ await sendCommand({ type: "set_auto_compaction", enabled: true });
177
+ await sendCommand({ type: "set_auto_retry", enabled: true });
178
+ await sendCommand({ type: "prompt", message: promptText });
179
+ promptSent = true;
180
+
181
+ while (true) {
182
+ if (processClosed) break;
183
+ await sleep(RPC_POLL_MS);
184
+ let state: { isStreaming: boolean; isCompacting: boolean; pendingMessageCount: number };
185
+ try {
186
+ state = await sendCommand({ type: "get_state" });
187
+ } catch (error) {
188
+ if (processClosed) break;
189
+ throw error;
190
+ }
191
+ const isIdle = !state.isStreaming && !state.isCompacting && state.pendingMessageCount === 0;
192
+ const isQuiet = Date.now() - lastEventAt >= RPC_QUIESCENCE_MS;
193
+ if (promptSent && agentEndCount > 0 && isIdle && isQuiet) break;
194
+ }
195
+ } finally {
196
+ await stopProcess();
197
+ }
198
+
199
+ details.exitCode = stoppedAfterCompletion ? 0 : (processExitCode ?? 0);
200
+ if (details.exitCode !== 0 && !details.errorMessage) {
201
+ details.errorMessage = `${REVIEW_LABEL} subagent exited with code ${details.exitCode}`;
202
+ }
203
+ return details;
204
+ }
package/src/types.ts ADDED
@@ -0,0 +1,45 @@
1
+ import type { Message } from "@mariozechner/pi-ai";
2
+
3
+ export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
4
+
5
+ export interface ReviewConfig {
6
+ model: string;
7
+ thinking?: ThinkingLevel;
8
+ }
9
+
10
+ export interface UsageStats {
11
+ input: number;
12
+ output: number;
13
+ cacheRead: number;
14
+ cacheWrite: number;
15
+ cost: number;
16
+ contextTokens: number;
17
+ turns: number;
18
+ }
19
+
20
+ export interface ChildRunDetails {
21
+ mode: "review";
22
+ toolName: string;
23
+ task: string;
24
+ cwd: string;
25
+ model: string;
26
+ thinking?: ThinkingLevel;
27
+ messages: Message[];
28
+ stderr: string;
29
+ exitCode: number;
30
+ stopReason?: string;
31
+ errorMessage?: string;
32
+ usage: UsageStats;
33
+ }
34
+
35
+ export interface ReviewContext {
36
+ repoRoot: string;
37
+ currentRef: string;
38
+ baseBranch: "main" | "master" | "dev";
39
+ mergeBase: string;
40
+ baseTip: string;
41
+ status: string;
42
+ recentBaseCommits: string;
43
+ hasTrackedChanges: boolean;
44
+ hasAnyChanges: boolean;
45
+ }