@howaboua/pi-subagent-review 0.2.5 → 0.2.6

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/README.md CHANGED
@@ -85,7 +85,7 @@ Edit that file to change the default review model or thinking level, and the mod
85
85
  }
86
86
  ```
87
87
 
88
- The summary model uses the same `provider/model` string format as the reviewer model. The generated summary is injected into the isolated review task as branch-style context; raw conversation turns are not sent to the review subagent. If the configured review or summary model is not available for the user, `/review` falls back to the current session model automatically. If conversation summarization still fails, `/review` continues with a diff-only review.
88
+ The summary model uses the same `provider/model` string format as the reviewer model. Thinking levels through `max` are accepted and clamped to model capabilities. The generated summary is injected into the isolated review task as branch-style context; raw conversation turns are not sent to the review subagent. If the configured review or summary model is not available for the user, `/review` falls back to the current session model automatically. If conversation summarization still fails, `/review` continues with a diff-only review.
89
89
 
90
90
  Existing config files from older versions are migrated on load. If a config has `model` and `thinking` but no `summary` block, the extension adds one using the same model and low thinking:
91
91
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-subagent-review",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "Pi extension that adds /review via an isolated review subagent.",
5
5
  "type": "module",
6
6
  "main": "index.ts",
@@ -38,19 +38,20 @@
38
38
  ]
39
39
  },
40
40
  "peerDependencies": {
41
- "@earendil-works/pi-ai": "*",
42
- "@earendil-works/pi-coding-agent": "*"
41
+ "@earendil-works/pi-ai": ">=0.80.6",
42
+ "@earendil-works/pi-coding-agent": ">=0.80.6"
43
43
  },
44
44
  "scripts": {
45
- "check": "bun run lint && bun run typecheck",
45
+ "check": "bun run lint && bun run typecheck && bun run test",
46
46
  "prepack": "bun run check",
47
+ "test": "bun test",
47
48
  "typecheck": "tsgo --noEmit",
48
49
  "lint": "biome check .",
49
50
  "format": "biome check --write ."
50
51
  },
51
52
  "devDependencies": {
52
- "@earendil-works/pi-ai": "0.80.1",
53
- "@earendil-works/pi-coding-agent": "0.80.1",
53
+ "@earendil-works/pi-ai": "0.80.6",
54
+ "@earendil-works/pi-coding-agent": "0.80.6",
54
55
  "@types/node": "^24.10.0",
55
56
  "typescript": "^5.9.3",
56
57
  "@biomejs/biome": "^2.4.16"
package/src/config.ts CHANGED
@@ -19,7 +19,7 @@ import type {
19
19
  UsageStats,
20
20
  } from "./types.js";
21
21
 
22
- function normalizeThinking(
22
+ export function normalizeThinking(
23
23
  value: ThinkingLevel | undefined,
24
24
  fallback: ThinkingLevel = DEFAULT_CONFIG.thinking,
25
25
  ): ThinkingLevel {
package/src/constants.ts CHANGED
@@ -30,11 +30,10 @@ export const ALLOWED_THINKING = new Set([
30
30
  "medium",
31
31
  "high",
32
32
  "xhigh",
33
+ "max",
33
34
  ] as const);
34
35
  export const RPC_READY_TIMEOUT_MS = 10_000;
35
36
  export const RPC_RESPONSE_TIMEOUT_MS = 30_000;
36
- export const RPC_POLL_MS = 150;
37
- export const RPC_QUIESCENCE_MS = 500;
38
37
 
39
38
  export function getAgentDir(): string {
40
39
  const configured = process.env["PI_CODING_AGENT_DIR"]?.trim();
@@ -1,120 +1,104 @@
1
- import type {
2
- Api,
3
- AssistantMessage,
4
- AssistantMessageEventStream,
5
- Context,
6
- Model,
7
- SimpleStreamOptions,
8
- } from "@earendil-works/pi-ai";
9
- import * as piAiRuntime from "@earendil-works/pi-ai";
10
- import type {
11
- ExtensionCommandContext,
12
- SessionEntry,
1
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
+ import {
3
+ createAgentSession,
4
+ DefaultResourceLoader,
5
+ type ExtensionCommandContext,
6
+ getAgentDir,
7
+ type SessionEntry,
8
+ SessionManager,
9
+ SettingsManager,
13
10
  } from "@earendil-works/pi-coding-agent";
14
11
  import type { ResolvedReviewConfig } from "./types.js";
15
12
 
16
- type RegisteredProviderConfig = {
17
- api?: Api;
18
- authHeader?: boolean;
19
- streamSimple?: (
20
- model: Model<Api>,
21
- context: Context,
22
- options?: SimpleStreamOptions,
23
- ) => AssistantMessageEventStream;
24
- };
25
-
26
- type ModelRegistryInternals = {
27
- providerRequestConfigs?: Map<
28
- string,
29
- Pick<RegisteredProviderConfig, "authHeader">
30
- >;
31
- registeredProviders?: Map<string, RegisteredProviderConfig>;
32
- };
33
-
34
- type PiAiRuntime = {
35
- completeSimple(
36
- model: Model<Api>,
37
- context: Context,
38
- options?: SimpleStreamOptions,
39
- ): Promise<AssistantMessage>;
40
- };
41
-
42
- const { completeSimple: completeWithPiRuntime } =
43
- piAiRuntime as unknown as PiAiRuntime;
44
-
45
- function getModelRegistryInternals(
46
- modelRegistry: ExtensionCommandContext["modelRegistry"],
47
- ): ModelRegistryInternals {
48
- return modelRegistry as unknown as ModelRegistryInternals;
49
- }
50
-
51
- function getRegisteredStreamSimple(
52
- modelRegistry: ExtensionCommandContext["modelRegistry"],
53
- model: Model<Api>,
54
- ): RegisteredProviderConfig["streamSimple"] {
55
- const providerConfig = getModelRegistryInternals(
56
- modelRegistry,
57
- ).registeredProviders?.get(model.provider);
58
- if (providerConfig?.api !== model.api) return undefined;
59
- return providerConfig.streamSimple;
60
- }
61
-
62
- function isMissingApiKeyError(error: string, provider: string): boolean {
63
- return error === `No API key found for "${provider}"`;
13
+ const SUMMARY_SYSTEM_PROMPT =
14
+ "Summarize supplied conversation context for a separate code-review agent. Follow the user's summary format exactly and do not use tools.";
15
+
16
+ function lastAssistantMessage(
17
+ messages: readonly unknown[],
18
+ ): AssistantMessage | undefined {
19
+ for (let index = messages.length - 1; index >= 0; index--) {
20
+ const message = messages[index];
21
+ if (
22
+ message &&
23
+ typeof message === "object" &&
24
+ (message as { role?: unknown }).role === "assistant"
25
+ ) {
26
+ return message as AssistantMessage;
27
+ }
28
+ }
29
+ return undefined;
64
30
  }
65
31
 
66
- async function getSummaryOptions(
32
+ async function completeSummary(
67
33
  ctx: ExtensionCommandContext,
68
- model: Model<Api>,
69
34
  config: ResolvedReviewConfig,
70
- ): Promise<SimpleStreamOptions> {
71
- const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
72
- const fallbackApiKey =
73
- auth.ok && auth.apiKey
74
- ? undefined
75
- : await ctx.modelRegistry.getApiKeyForProvider(model.provider);
76
- if (!auth.ok && !isMissingApiKeyError(auth.error, model.provider)) {
77
- throw new Error(`Summary model unavailable: ${auth.error}`);
78
- }
79
- if (!auth.ok && !fallbackApiKey) {
80
- throw new Error(`Summary model unavailable: ${auth.error}`);
81
- }
82
-
83
- let headers = auth.ok ? auth.headers : undefined;
84
- if (
85
- fallbackApiKey &&
86
- getModelRegistryInternals(ctx.modelRegistry).providerRequestConfigs?.get(
87
- model.provider,
88
- )?.authHeader
89
- ) {
90
- headers = { ...headers, Authorization: `Bearer ${fallbackApiKey}` };
91
- }
35
+ prompt: string,
36
+ ): Promise<AssistantMessage> {
37
+ const signal = ctx.signal;
38
+ if (signal?.aborted) throw new Error("Summary model was aborted");
92
39
 
93
- const options: SimpleStreamOptions = {};
94
- const apiKey = auth.ok && auth.apiKey ? auth.apiKey : fallbackApiKey;
95
- const env = auth.ok
96
- ? auth.env
97
- : ctx.modelRegistry.authStorage.getProviderEnv(model.provider);
98
- if (apiKey) options.apiKey = apiKey;
99
- if (headers) options.headers = headers;
100
- if (env) options.env = env;
101
- if (model.reasoning && config.summary.thinking !== "off") {
102
- options.reasoning = config.summary.thinking;
103
- }
104
- if (ctx.signal) options.signal = ctx.signal;
105
- return options;
106
- }
40
+ const parsed = config.summary.modelParsed;
41
+ const model = ctx.modelRegistry.find(parsed.provider, parsed.modelId);
42
+ if (!model)
43
+ throw new Error(`Summary model not found: ${config.summary.model}`);
107
44
 
108
- async function completeSummaryWithModelApi(
109
- model: Model<Api>,
110
- context: Context,
111
- options: SimpleStreamOptions,
112
- registeredStreamSimple: RegisteredProviderConfig["streamSimple"],
113
- ): Promise<AssistantMessage> {
114
- if (registeredStreamSimple) {
115
- return registeredStreamSimple(model, context, options).result();
45
+ const settingsManager = SettingsManager.inMemory({
46
+ compaction: { enabled: false },
47
+ });
48
+ const resourceLoader = new DefaultResourceLoader({
49
+ cwd: ctx.cwd,
50
+ agentDir: getAgentDir(),
51
+ settingsManager,
52
+ noExtensions: true,
53
+ noSkills: true,
54
+ noPromptTemplates: true,
55
+ noThemes: true,
56
+ noContextFiles: true,
57
+ systemPrompt: SUMMARY_SYSTEM_PROMPT,
58
+ });
59
+ await resourceLoader.reload();
60
+
61
+ const { session } = await createAgentSession({
62
+ cwd: ctx.cwd,
63
+ model,
64
+ thinkingLevel: config.summary.thinking,
65
+ authStorage: ctx.modelRegistry.authStorage,
66
+ modelRegistry: ctx.modelRegistry,
67
+ noTools: "all",
68
+ resourceLoader,
69
+ sessionManager: SessionManager.inMemory(ctx.cwd),
70
+ settingsManager,
71
+ });
72
+ let abortPromise: Promise<void> | undefined;
73
+ const abortSummary = () => {
74
+ abortPromise ??= session.abort();
75
+ };
76
+ signal?.addEventListener("abort", abortSummary, { once: true });
77
+
78
+ try {
79
+ if (signal?.aborted) {
80
+ abortSummary();
81
+ throw new Error("Summary model was aborted");
82
+ }
83
+ await session.prompt(prompt, {
84
+ expandPromptTemplates: false,
85
+ source: "extension",
86
+ });
87
+ const response = lastAssistantMessage(session.messages);
88
+ if (!response)
89
+ throw new Error("Summary model returned no assistant message");
90
+ if (response.stopReason === "error") {
91
+ throw new Error(response.errorMessage || "Summary model failed");
92
+ }
93
+ if (response.stopReason === "aborted") {
94
+ throw new Error("Summary model was aborted");
95
+ }
96
+ return response;
97
+ } finally {
98
+ signal?.removeEventListener("abort", abortSummary);
99
+ await abortPromise;
100
+ session.dispose();
116
101
  }
117
- return completeWithPiRuntime(model, context, options);
118
102
  }
119
103
 
120
104
  function textFromContent(content: unknown): string {
@@ -221,25 +205,10 @@ export async function buildReviewConversationSummary(
221
205
  const conversation = buildSummaryInput(ctx.sessionManager.getBranch());
222
206
  if (!conversation.trim()) return undefined;
223
207
 
224
- const parsed = config.summary.modelParsed;
225
- const model = ctx.modelRegistry.find(parsed.provider, parsed.modelId);
226
- if (!model)
227
- throw new Error(`Summary model not found: ${config.summary.model}`);
228
- const options = await getSummaryOptions(ctx, model, config);
229
-
230
- const response = await completeSummaryWithModelApi(
231
- model,
232
- {
233
- messages: [
234
- {
235
- role: "user" as const,
236
- content: [{ type: "text" as const, text: buildPrompt(conversation) }],
237
- timestamp: Date.now(),
238
- },
239
- ],
240
- },
241
- options,
242
- getRegisteredStreamSimple(ctx.modelRegistry, model),
208
+ const response = await completeSummary(
209
+ ctx,
210
+ config,
211
+ buildPrompt(conversation),
243
212
  );
244
213
 
245
214
  const summary = response.content
package/src/subagent.ts CHANGED
@@ -1,19 +1,17 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { StringDecoder } from "node:string_decoder";
2
3
  import { createChildRunDetails } from "./config.js";
3
4
  import {
4
5
  CHILD_ENV,
5
6
  REVIEW_LABEL,
6
7
  REVIEW_PROMPT_PATH,
7
- RPC_POLL_MS,
8
- RPC_QUIESCENCE_MS,
9
8
  RPC_READY_TIMEOUT_MS,
10
9
  RPC_RESPONSE_TIMEOUT_MS,
11
10
  } from "./constants.js";
12
11
  import type { ResolvedReviewConfig } from "./types.js";
13
12
 
14
- function sleep(ms: number): Promise<void> {
15
- return new Promise((resolve) => setTimeout(resolve, ms));
16
- }
13
+ const sleep = (ms: number) =>
14
+ new Promise<void>((resolve) => setTimeout(resolve, ms));
17
15
 
18
16
  export function getFinalOutput(messages: any[]): string {
19
17
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -53,14 +51,19 @@ export async function runReviewSubagent(
53
51
  `Task: ${task}`,
54
52
  ].join("\n\n");
55
53
 
56
- let lastEventAt = Date.now();
57
- let agentEndCount = 0;
58
- let promptSent = false;
59
54
  let processClosed = false;
60
55
  let processExitCode: number | undefined;
61
56
  let requestId = 0;
62
57
  let stoppedAfterCompletion = false;
63
58
  let stdoutBuffer = "";
59
+ const stdoutDecoder = new StringDecoder("utf8");
60
+ let resolveSettled!: () => void;
61
+ let rejectSettled!: (error: Error) => void;
62
+ const settledPromise = new Promise<void>((resolve, reject) => {
63
+ resolveSettled = resolve;
64
+ rejectSettled = reject;
65
+ });
66
+ void settledPromise.catch(() => undefined);
64
67
  const pendingRequests = new Map<
65
68
  string,
66
69
  {
@@ -123,7 +126,6 @@ export async function runReviewSubagent(
123
126
  };
124
127
 
125
128
  const handleEvent = (event: any) => {
126
- lastEventAt = Date.now();
127
129
  if (event["type"] === "message_end" && event.message) {
128
130
  const message = event.message;
129
131
  details.messages.push(message);
@@ -144,7 +146,7 @@ export async function runReviewSubagent(
144
146
  return;
145
147
  }
146
148
 
147
- if (event["type"] === "agent_end") agentEndCount++;
149
+ if (event["type"] === "agent_settled") resolveSettled();
148
150
  };
149
151
 
150
152
  const handleLine = (line: string) => {
@@ -192,15 +194,20 @@ export async function runReviewSubagent(
192
194
  };
193
195
 
194
196
  const abortProcess = () => {
197
+ rejectSettled(new Error(`${REVIEW_LABEL} aborted.`));
195
198
  void stopProcess();
196
199
  };
197
200
  signal?.addEventListener("abort", abortProcess, { once: true });
198
201
 
199
202
  proc.stdout.on("data", (chunk) => {
200
- stdoutBuffer += chunk.toString();
203
+ stdoutBuffer += stdoutDecoder.write(chunk);
201
204
  const lines = stdoutBuffer.split("\n");
202
205
  stdoutBuffer = lines.pop() || "";
203
- for (const line of lines) handleLine(line);
206
+ for (const line of lines)
207
+ handleLine(line.endsWith("\r") ? line.slice(0, -1) : line);
208
+ });
209
+ proc.stdout.on("end", () => {
210
+ stdoutBuffer += stdoutDecoder.end();
204
211
  });
205
212
 
206
213
  proc.stderr.on("data", (chunk) => {
@@ -211,7 +218,9 @@ export async function runReviewSubagent(
211
218
  processClosed = true;
212
219
  processExitCode = code ?? 0;
213
220
  if (stdoutBuffer.trim()) {
214
- handleLine(stdoutBuffer);
221
+ handleLine(
222
+ stdoutBuffer.endsWith("\r") ? stdoutBuffer.slice(0, -1) : stdoutBuffer,
223
+ );
215
224
  stdoutBuffer = "";
216
225
  }
217
226
  rejectPendingRequests(
@@ -219,12 +228,20 @@ export async function runReviewSubagent(
219
228
  `Review subagent RPC process exited with code ${processExitCode}.${details.stderr ? ` Stderr: ${details.stderr.trim()}` : ""}`,
220
229
  ),
221
230
  );
231
+ if (!stoppedAfterCompletion) {
232
+ rejectSettled(
233
+ new Error(
234
+ `Review subagent exited before agent_settled.${details.stderr ? ` Stderr: ${details.stderr.trim()}` : ""}`,
235
+ ),
236
+ );
237
+ }
222
238
  });
223
239
 
224
240
  proc.on("error", (error) => {
225
- rejectPendingRequests(
226
- error instanceof Error ? error : new Error(String(error)),
227
- );
241
+ const processError =
242
+ error instanceof Error ? error : new Error(String(error));
243
+ rejectPendingRequests(processError);
244
+ rejectSettled(processError);
228
245
  });
229
246
 
230
247
  try {
@@ -234,30 +251,7 @@ export async function runReviewSubagent(
234
251
  await sendCommand({ type: "set_auto_compaction", enabled: true });
235
252
  await sendCommand({ type: "set_auto_retry", enabled: true });
236
253
  await sendCommand({ type: "prompt", message: promptText });
237
- promptSent = true;
238
-
239
- while (true) {
240
- if (signal?.aborted) throw new Error(`${REVIEW_LABEL} aborted.`);
241
- if (processClosed) break;
242
- await sleep(RPC_POLL_MS);
243
- let state: {
244
- isStreaming: boolean;
245
- isCompacting: boolean;
246
- pendingMessageCount: number;
247
- };
248
- try {
249
- state = await sendCommand({ type: "get_state" });
250
- } catch (error) {
251
- if (processClosed) break;
252
- throw error;
253
- }
254
- const isIdle =
255
- !state.isStreaming &&
256
- !state.isCompacting &&
257
- state.pendingMessageCount === 0;
258
- const isQuiet = Date.now() - lastEventAt >= RPC_QUIESCENCE_MS;
259
- if (promptSent && agentEndCount > 0 && isIdle && isQuiet) break;
260
- }
254
+ await settledPromise;
261
255
  } finally {
262
256
  signal?.removeEventListener("abort", abortProcess);
263
257
  await stopProcess();
package/src/types.ts CHANGED
@@ -1,12 +1,6 @@
1
- import type { Message } from "@earendil-works/pi-ai";
1
+ import type { Message, ModelThinkingLevel } from "@earendil-works/pi-ai";
2
2
 
3
- export type ThinkingLevel =
4
- | "off"
5
- | "minimal"
6
- | "low"
7
- | "medium"
8
- | "high"
9
- | "xhigh";
3
+ export type ThinkingLevel = ModelThinkingLevel;
10
4
 
11
5
  export interface SummaryConfig {
12
6
  enabled?: boolean;