pi-auto-reviewer 1.2.0 → 1.3.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/README.md CHANGED
@@ -47,7 +47,7 @@ These behaviors are included in the reviewer prompt:
47
47
  Global (all projects):
48
48
 
49
49
  ```bash
50
- cp auto-reviewer.ts review-tool.ts jev-decisions.ts ~/.pi/agent/extensions/pi-auto-reviewer/
50
+ cp auto-reviewer.ts review-tool.ts jev-decisions.ts reviewer-cost.ts ~/.pi/agent/extensions/pi-auto-reviewer/
51
51
  ```
52
52
 
53
53
  Via npm:
@@ -59,7 +59,7 @@ pi install npm:pi-auto-reviewer
59
59
  Single project:
60
60
 
61
61
  ```bash
62
- cp auto-reviewer.ts review-tool.ts jev-decisions.ts .pi/extensions/
62
+ cp auto-reviewer.ts review-tool.ts jev-decisions.ts reviewer-cost.ts .pi/extensions/
63
63
  ```
64
64
 
65
65
  Pi loads extensions from `.pi/extensions/` only after the project is trusted.
@@ -70,7 +70,7 @@ Single session:
70
70
  pi -e ./auto-reviewer.ts
71
71
  ```
72
72
 
73
- All three `.ts` files must sit side by side. `jev-decisions.ts` provides the Jev HTTP driver. For the pi backend, `review-tool.ts` provides the structured decision channel; without it the reviewer falls back to text parsing only. On Windows PowerShell, use the matching copy commands and extension paths.
73
+ All four `.ts` files must sit side by side. `jev-decisions.ts` provides the Jev HTTP driver. For the pi backend, `review-tool.ts` provides the structured decision channel; without it the reviewer falls back to text parsing only. On Windows PowerShell, use the matching copy commands and extension paths.
74
74
 
75
75
  ## Usage
76
76
 
@@ -170,3 +170,52 @@ Edit `auto-reviewer.ts`: `AUTO_PERMITTED` / `AUTO_BLOCKED` for tier patterns, `d
170
170
  ---
171
171
 
172
172
  The `autoReviewer` settings support is based on [PR #2](https://github.com/vinzenzu/pi-auto-reviewer/pull/2) by [JiChenSSG](https://github.com/JiChenSSG).
173
+
174
+ ## OpenRouter review costs
175
+
176
+ Review results show the provider-confirmed charge, for example
177
+ `Auto-reviewer: ✓ Read-only check · OpenRouter $0.003072`. Billing lookups run in the
178
+ background. The result shows pending costs first when needed, followed by an
179
+ updated notification once OpenRouter reports them. Billing never changes the
180
+ allow/block decision or delays command execution. Confirmed review charges also
181
+ enter pi's native cost totals and breakdown through persisted, cost-only usage
182
+ entries. This works without any other extension and leaves token counts intact.
183
+ Billing currently supports OpenRouter only. Reviews through other providers
184
+ show no cost label and emit no OpenRouter billing events.
185
+
186
+ Tested only with pi 0.87.1.
187
+
188
+ Uses pi's saved OpenRouter credential. The pi backend looks up generation charges;
189
+ the Jev backend uses OpenRouter's returned `usage.cost`, including billed attempts
190
+ with invalid verdicts, without a second lookup when that charge is available.
191
+ Each generation is counted once, including
192
+ failed review attempts and IDs observed before a subprocess was killed. Missing
193
+ IDs, credentials or billing records stay visibly unavailable. Lookups retry six
194
+ times, with a five-second timeout and at most three concurrent lookups per review.
195
+ If a process exits before billing settles, its saved pending IDs can be
196
+ reconciled by a cost-extension consumer on resume. No spending cap is added.
197
+
198
+ Public integration: subscribe to `pi-auto-reviewer:cost` through `pi.events.on`.
199
+ Payload type `ReviewerCostEvent` is exported from `reviewer-cost.ts`:
200
+
201
+ ```typescript
202
+ {
203
+ parentSessionId: string; // accounting owner, not an OpenRouter routing setting
204
+ reviewId: string; // shell tool-call ID
205
+ provider: "openrouter";
206
+ responseId: string;
207
+ model?: string;
208
+ status: "pending" | "confirmed" | "unavailable";
209
+ costUSD?: number; // present only when confirmed; zero is valid
210
+ }
211
+ ```
212
+
213
+ The same payload is persisted in custom entries named `pi-auto-reviewer-cost`,
214
+ outside the model context. Consumers should deduplicate by response ID and use
215
+ the confirmed `costUSD`; they do not need to issue a second billing lookup.
216
+ The package has no dependency on a particular cost extension or local path.
217
+ This feature does not change reviewer session IDs or provider routing.
218
+
219
+ For source tests, use Node.js 24, run `npm install` to resolve the pi peer
220
+ dependency, then `npm test`. Tests use fake credentials and mocked provider
221
+ responses, plus a local HTTP fixture; they do not issue paid model requests.
package/auto-reviewer.ts CHANGED
@@ -27,8 +27,9 @@
27
27
  * falling back to a conservative block / manual prompt.
28
28
  */
29
29
 
30
- import { requestJevReview, resolveJevApiKey, type JevConfig } from "./jev-decisions.ts";
30
+ import { requestJevReview, resolveJevApiKey, type JevConfig, type JevCharge } from "./jev-decisions.ts";
31
31
  import { spawn } from "node:child_process";
32
+ import { ReviewerCosts, ReviewerOutput, REVIEWER_COST_ENTRY, REVIEWER_COST_EVENT, REVIEWER_USAGE_KIND, formatReviewerCost } from "./reviewer-cost.ts";
32
33
  import * as fs from "node:fs";
33
34
  import * as os from "node:os";
34
35
  import * as path from "node:path";
@@ -1200,6 +1201,8 @@ async function reviewWithLLM(
1200
1201
  attempt: number,
1201
1202
  projectTrusted: boolean,
1202
1203
  modelRegistry: ExtensionContext["modelRegistry"],
1204
+ onBillingResponse: (message: unknown) => void,
1205
+ onCharge: (charge: JevCharge) => void,
1203
1206
  ): Promise<{ allowed: boolean; reason: string }> {
1204
1207
  // Gather context first; the prompt is built from it. Each source is
1205
1208
  // time-bounded and falls back to an empty context on failure so a slow
@@ -1220,7 +1223,7 @@ async function reviewWithLLM(
1220
1223
  const apiKey = await resolveJevApiKey(
1221
1224
  overrides, provider => modelRegistry.getApiKeyForProvider(provider), process.env, reviewSignal,
1222
1225
  );
1223
- result = await requestJevReview(overrides, prompt, REVIEW_TIMEOUT_MS, reviewSignal, apiKey);
1226
+ result = await requestJevReview(overrides, prompt, REVIEW_TIMEOUT_MS, reviewSignal, apiKey, fetch, onCharge);
1224
1227
  } catch (error) {
1225
1228
  const detail = error instanceof Error ? error.message : "Jev review failed";
1226
1229
  await writeDebugFile({
@@ -1305,6 +1308,7 @@ async function reviewWithLLM(
1305
1308
  piArgs.push(prompt);
1306
1309
 
1307
1310
  let capturedStderr = "";
1311
+ const billingOutput = new ReviewerOutput(onBillingResponse);
1308
1312
 
1309
1313
  const fullOutput = await new Promise<string>((resolve, reject) => {
1310
1314
  const proc = spawn(piCmd, piArgs, {
@@ -1315,7 +1319,10 @@ async function reviewWithLLM(
1315
1319
 
1316
1320
  let stdout = "";
1317
1321
 
1318
- proc.stdout.on("data", (data: Buffer) => { stdout += data.toString(); });
1322
+ proc.stdout.on("data", (data: Buffer) => {
1323
+ stdout += data.toString();
1324
+ billingOutput.write(data);
1325
+ });
1319
1326
  proc.stderr.on("data", (data: Buffer) => { capturedStderr += data.toString(); });
1320
1327
 
1321
1328
  const timeout = setTimeout(() => {
@@ -1324,6 +1331,7 @@ async function reviewWithLLM(
1324
1331
  }, REVIEW_TIMEOUT_MS);
1325
1332
 
1326
1333
  proc.on("close", (code) => {
1334
+ billingOutput.end();
1327
1335
  clearTimeout(timeout);
1328
1336
  if (code === 0 || code === null) {
1329
1337
  resolve(stdout.trim());
@@ -1379,6 +1387,13 @@ async function reviewWithLLM(
1379
1387
  }
1380
1388
 
1381
1389
  export default function (pi: ExtensionAPI) {
1390
+ let activeSessionId: string | undefined;
1391
+ const billingTrackers = new Set<ReviewerCosts>();
1392
+ pi.on("session_start", (_event, ctx) => {
1393
+ for (const tracker of billingTrackers) tracker.dispose();
1394
+ billingTrackers.clear();
1395
+ activeSessionId = ctx.sessionManager.getSessionId();
1396
+ });
1382
1397
  pi.on("tool_call", async (event, ctx) => {
1383
1398
  if (event.toolName !== "bash") return undefined;
1384
1399
 
@@ -1408,6 +1423,42 @@ export default function (pi: ExtensionAPI) {
1408
1423
 
1409
1424
  let lastError: Error | null = null;
1410
1425
  const projectTrusted = ctx.isProjectTrusted();
1426
+ const parentSessionId = ctx.sessionManager.getSessionId();
1427
+ let resultLabel: string | undefined;
1428
+ let resultLevel: "info" | "warning" = "info";
1429
+ let shownCost: string | undefined;
1430
+ const costs = new ReviewerCosts({
1431
+ parentSessionId, reviewId: event.toolCallId,
1432
+ getApiKey: () => ctx.modelRegistry.getApiKeyForProvider("openrouter"),
1433
+ report: cost => {
1434
+ if (activeSessionId !== parentSessionId) return;
1435
+ if (cost.status === "confirmed") {
1436
+ // Pi 0.87.1 exposes the public SessionManager at runtime.
1437
+ // Cost-only usage preserves token counts and survives reloads.
1438
+ const manager = ctx.sessionManager as SessionManager;
1439
+ manager.appendUsage(REVIEWER_USAGE_KIND, cost.provider, cost.model ?? "unknown", {
1440
+ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
1441
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: cost.costUSD! },
1442
+ }, cost.responseId);
1443
+ }
1444
+ pi.appendEntry(REVIEWER_COST_ENTRY, cost);
1445
+ pi.events.emit(REVIEWER_COST_EVENT, cost);
1446
+ const label = formatReviewerCost(costs.summary());
1447
+ if (ctx.hasUI && resultLabel && label !== shownCost) {
1448
+ shownCost = label;
1449
+ ctx.ui.notify(`${resultLabel} · ${label}`, resultLevel);
1450
+ }
1451
+ if (resultLabel && costs.summary().pending === 0) billingTrackers.delete(costs);
1452
+ },
1453
+ });
1454
+ billingTrackers.add(costs);
1455
+ const showResult = (label: string, level: "info" | "warning") => {
1456
+ resultLabel = label;
1457
+ resultLevel = level;
1458
+ shownCost = formatReviewerCost(costs.summary());
1459
+ if (ctx.hasUI) ctx.ui.notify(label + (shownCost ? ` · ${shownCost}` : ""), level);
1460
+ if (costs.summary().pending === 0) billingTrackers.delete(costs);
1461
+ };
1411
1462
 
1412
1463
  for (let attempt = 1; attempt <= MAX_REVIEW_ATTEMPTS; attempt++) {
1413
1464
  try {
@@ -1424,15 +1475,17 @@ export default function (pi: ExtensionAPI) {
1424
1475
  attempt,
1425
1476
  projectTrusted,
1426
1477
  ctx.modelRegistry,
1478
+ message => costs.observe(message),
1479
+ charge => costs.observeCharge(charge),
1427
1480
  );
1428
1481
 
1429
1482
  if (ctx.hasUI) ctx.ui.setStatus("auto-reviewer", undefined);
1430
1483
 
1431
1484
  if (decision.allowed) {
1432
- if (ctx.hasUI) ctx.ui.notify(`Auto-reviewer: ✓ ${decision.reason}`, "info");
1485
+ showResult(`Auto-reviewer: ✓ ${decision.reason}`, "info");
1433
1486
  return undefined; // allow through
1434
1487
  } else {
1435
- if (ctx.hasUI) ctx.ui.notify(`Auto-reviewer: ✗ ${decision.reason}`, "warning");
1488
+ showResult(`Auto-reviewer: ✗ ${decision.reason}`, "warning");
1436
1489
  return { block: true, reason: `Auto-reviewer blocked: ${decision.reason}` };
1437
1490
  }
1438
1491
  } catch (err) {
@@ -1445,6 +1498,8 @@ export default function (pi: ExtensionAPI) {
1445
1498
 
1446
1499
  if (ctx.hasUI) ctx.ui.setStatus("auto-reviewer", undefined);
1447
1500
 
1501
+ showResult(`Auto-reviewer failed: ${lastError!.message.split("\n")[0].slice(0, 150)}`, "warning");
1502
+
1448
1503
  if (ctx.hasUI) {
1449
1504
  // All attempts failed — fall back to manual UI
1450
1505
  const msg = lastError!.message;
@@ -1463,6 +1518,8 @@ export default function (pi: ExtensionAPI) {
1463
1518
 
1464
1519
  // Clean up status on session end
1465
1520
  pi.on("session_shutdown", async (_event, _ctx) => {
1466
- // No cleanup needed; status is session-scoped
1521
+ for (const tracker of billingTrackers) tracker.dispose();
1522
+ billingTrackers.clear();
1523
+ activeSessionId = undefined;
1467
1524
  });
1468
1525
  }
package/jev-decisions.ts CHANGED
@@ -11,6 +11,13 @@ const PROVIDER_ENDPOINTS: Record<string, string> = {
11
11
  openrouter: "https://openrouter.ai/api/alpha/decisions",
12
12
  };
13
13
 
14
+ export interface JevCharge {
15
+ provider?: string;
16
+ responseId?: string;
17
+ model?: string;
18
+ costUSD?: unknown;
19
+ }
20
+
14
21
  export type JevCredentialResolver = (provider: string) => Promise<string | undefined>;
15
22
 
16
23
  function getEndpoint(config: JevConfig): URL {
@@ -106,6 +113,7 @@ export async function requestJevReview(
106
113
  signal: AbortSignal | undefined,
107
114
  apiKey: string,
108
115
  fetchImpl: typeof fetch = fetch,
116
+ onCharge?: (charge: JevCharge) => void,
109
117
  ): Promise<{ decision: { allowed: boolean; reason: string }; fullOutput: string }> {
110
118
  const endpoint = getEndpoint(config).href;
111
119
  if (!config.model) throw new Error("Jev requires a model");
@@ -140,6 +148,13 @@ export async function requestJevReview(
140
148
  } catch {
141
149
  throw new Error("Jev returned invalid JSON");
142
150
  }
151
+ const result = asRecord(data);
152
+ try {
153
+ onCharge?.({ provider: config.provider,
154
+ responseId: typeof result.id === "string" ? result.id : undefined,
155
+ model: typeof result.model === "string" ? result.model : config.model,
156
+ costUSD: asRecord(result.usage).cost });
157
+ } catch { /* Billing consumers cannot change the decision. */ }
143
158
  const answer = asRecord(asRecord(asRecord(data).answers).command_review);
144
159
  const probabilities = asRecord(answer.probabilities);
145
160
  if (answer.type !== "choice" || typeof answer.choice !== "string" || !Object.hasOwn(CRITERIA, answer.choice) ||
package/package.json CHANGED
@@ -1,25 +1,28 @@
1
- {
2
- "name": "pi-auto-reviewer",
3
- "version": "1.2.0",
4
- "description": "Auto-review bash commands before your pi agent executes them — akin to Codex Auto-review and Claude Code auto mode.",
5
- "keywords": [
6
- "pi-package"
7
- ],
8
- "license": "MIT",
9
- "repository": {
10
- "type": "git",
11
- "url": "git+https://github.com/vinzenzu/pi-auto-reviewer.git"
12
- },
13
- "homepage": "https://github.com/vinzenzu/pi-auto-reviewer#readme",
14
- "bugs": {
15
- "url": "https://github.com/vinzenzu/pi-auto-reviewer/issues"
16
- },
17
- "pi": {
18
- "extensions": [
19
- "./auto-reviewer.ts"
20
- ]
21
- },
22
- "peerDependencies": {
23
- "@earendil-works/pi-coding-agent": "*"
24
- }
25
- }
1
+ {
2
+ "name": "pi-auto-reviewer",
3
+ "version": "1.3.0",
4
+ "description": "Auto-review bash commands before your pi agent executes them — akin to Codex Auto-review and Claude Code auto mode.",
5
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/vinzenzu/pi-auto-reviewer.git"
12
+ },
13
+ "homepage": "https://github.com/vinzenzu/pi-auto-reviewer#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/vinzenzu/pi-auto-reviewer/issues"
16
+ },
17
+ "pi": {
18
+ "extensions": [
19
+ "./auto-reviewer.ts"
20
+ ]
21
+ },
22
+ "scripts": {
23
+ "test": "node --test --test-isolation=none tests/*.test.ts"
24
+ },
25
+ "peerDependencies": {
26
+ "@earendil-works/pi-coding-agent": "*"
27
+ }
28
+ }
@@ -0,0 +1,190 @@
1
+ import { StringDecoder } from 'node:string_decoder';
2
+
3
+ export const REVIEWER_COST_EVENT = 'pi-auto-reviewer:cost';
4
+ export const REVIEWER_COST_ENTRY = 'pi-auto-reviewer-cost';
5
+ export const REVIEWER_USAGE_KIND = 'auto-reviewer';
6
+ const GENERATION_URL = 'https://openrouter.ai/api/v1/generation';
7
+ const LOOKUP_TIMEOUT_MS = 5000;
8
+ const MAX_LOOKUP_ATTEMPTS = 6;
9
+ const MAX_CONCURRENT_LOOKUPS = 3;
10
+
11
+ export interface ReviewerCostEvent {
12
+ parentSessionId: string;
13
+ reviewId: string;
14
+ provider: 'openrouter';
15
+ responseId: string;
16
+ model?: string;
17
+ status: 'pending' | 'confirmed' | 'unavailable';
18
+ costUSD?: number;
19
+ }
20
+
21
+ export interface ReviewerCostSummary {
22
+ costUSD: number;
23
+ confirmed: number;
24
+ pending: number;
25
+ unavailable: number;
26
+ }
27
+
28
+ interface ReviewerCostOptions {
29
+ parentSessionId: string;
30
+ reviewId: string;
31
+ getApiKey: () => Promise<string | undefined>;
32
+ report: (event: ReviewerCostEvent) => void;
33
+ fetch?: typeof fetch;
34
+ }
35
+
36
+ export function formatReviewerCost(summary: ReviewerCostSummary): string {
37
+ if (!summary.confirmed && !summary.pending && !summary.unavailable) return '';
38
+ const parts = summary.confirmed ? [`OpenRouter $${summary.costUSD.toFixed(6)}`] : ['OpenRouter cost'];
39
+ if (summary.pending) parts.push(`${summary.pending} pending`);
40
+ if (summary.unavailable) parts.push(`${summary.unavailable} unavailable`);
41
+ return parts.join(' · ');
42
+ }
43
+
44
+ // Domain-level billing API. Parent IDs group accounting; they do not change routing.
45
+ export class ReviewerCosts {
46
+ private options: ReviewerCostOptions;
47
+ private records = new Map<string, ReviewerCostEvent>();
48
+ private queue: string[] = [];
49
+ private active = 0;
50
+ private abort = new AbortController();
51
+
52
+ constructor(options: ReviewerCostOptions) { this.options = options; }
53
+
54
+ observe(message: any): void {
55
+ if (this.abort.signal.aborted || message?.provider !== 'openrouter') return;
56
+ const responseId = message.responseId || `missing:reviewer:${this.options.reviewId}:${this.records.size}`;
57
+ if (this.records.has(responseId)) return;
58
+ this.save({
59
+ parentSessionId: this.options.parentSessionId,
60
+ reviewId: this.options.reviewId, provider: 'openrouter', responseId,
61
+ model: typeof message.model === 'string' ? message.model : undefined,
62
+ status: message.responseId ? 'pending' : 'unavailable',
63
+ });
64
+ if (!message.responseId) return;
65
+ this.queue.push(responseId);
66
+ this.start();
67
+ }
68
+
69
+ observeCharge(charge: { provider?: string; responseId?: string; model?: string; costUSD?: unknown }): void {
70
+ if (this.abort.signal.aborted || charge.provider !== 'openrouter') return;
71
+ if (typeof charge.costUSD !== 'number' || !Number.isFinite(charge.costUSD) || charge.costUSD < 0) {
72
+ this.observe(charge);
73
+ return;
74
+ }
75
+ // Some Decisions responses report a charge without a generation ID.
76
+ const responseId = charge.responseId || `billed:reviewer:${this.options.parentSessionId}:${this.options.reviewId}:${this.records.size}`;
77
+ if (this.records.has(responseId)) return;
78
+ this.save({ parentSessionId: this.options.parentSessionId, reviewId: this.options.reviewId,
79
+ provider: 'openrouter', responseId, model: charge.model, status: 'confirmed', costUSD: charge.costUSD });
80
+ }
81
+
82
+ summary(): ReviewerCostSummary {
83
+ const total = { costUSD: 0, confirmed: 0, pending: 0, unavailable: 0 };
84
+ for (const record of this.records.values()) {
85
+ total[record.status]++;
86
+ if (record.status === 'confirmed') total.costUSD += record.costUSD!;
87
+ }
88
+ return total;
89
+ }
90
+
91
+ dispose(): void { this.abort.abort(); }
92
+
93
+ private save(record: ReviewerCostEvent): void {
94
+ this.records.set(record.responseId, record);
95
+ try { this.options.report({ ...record }); } catch { /* Billing observers cannot affect verdicts. */ }
96
+ }
97
+
98
+ private start(): void {
99
+ if (this.abort.signal.aborted) return;
100
+ while (this.active < MAX_CONCURRENT_LOOKUPS && this.queue.length) {
101
+ const id = this.queue.shift()!;
102
+ this.active++;
103
+ void this.resolve(id).finally(() => { this.active--; this.start(); });
104
+ }
105
+ }
106
+
107
+ private async resolve(responseId: string): Promise<void> {
108
+ try {
109
+ const key = await this.options.getApiKey();
110
+ if (this.abort.signal.aborted) return;
111
+ if (!key) throw new Error('No OpenRouter credential');
112
+ for (let attempt = 0; attempt < MAX_LOOKUP_ATTEMPTS; attempt++) {
113
+ try {
114
+ const url = new URL(GENERATION_URL);
115
+ url.searchParams.set('id', responseId);
116
+ const response = await (this.options.fetch ?? globalThis.fetch)(url, {
117
+ headers: { Authorization: `Bearer ${key}` },
118
+ signal: AbortSignal.any([this.abort.signal, AbortSignal.timeout(LOOKUP_TIMEOUT_MS)]),
119
+ });
120
+ if (!response.ok) throw new Error('Billing lookup unavailable');
121
+ const body = await response.json();
122
+ const cost = body?.data?.total_cost;
123
+ if (body?.data?.id !== responseId || typeof cost !== 'number' || !Number.isFinite(cost) || cost < 0) throw new Error('Invalid billed cost');
124
+ if (!this.abort.signal.aborted) this.save({ ...this.records.get(responseId)!, status: 'confirmed', costUSD: cost });
125
+ return;
126
+ } catch {
127
+ if (this.abort.signal.aborted) return;
128
+ if (attempt === MAX_LOOKUP_ATTEMPTS - 1) break;
129
+ await this.wait(1000 * 2 ** attempt);
130
+ }
131
+ }
132
+ } catch { /* Missing credentials and cancelled waits also leave charges unconfirmed. */ }
133
+ if (!this.abort.signal.aborted) this.save({ ...this.records.get(responseId)!, status: 'unavailable' });
134
+ }
135
+
136
+ private wait(ms: number): Promise<void> {
137
+ return new Promise((resolve, reject) => {
138
+ const cancelled = () => { clearTimeout(timer); reject(new Error('Cancelled')); };
139
+ const timer = setTimeout(() => { this.abort.signal.removeEventListener('abort', cancelled); resolve(); }, ms);
140
+ timer.unref();
141
+ this.abort.signal.addEventListener('abort', cancelled, { once: true });
142
+ });
143
+ }
144
+ }
145
+
146
+ // Read subprocess output without changing the decision parser or its output.
147
+ export class ReviewerOutput {
148
+ private decoder = new StringDecoder('utf8');
149
+ private buffer = '';
150
+ private unfinished = new Map<string, any>();
151
+ private observe: (message: any) => void;
152
+
153
+ constructor(observe: (message: any) => void) { this.observe = observe; }
154
+
155
+ write(bytes: Buffer): void {
156
+ this.buffer += this.decoder.write(bytes);
157
+ let newline: number;
158
+ while ((newline = this.buffer.indexOf('\n')) >= 0) {
159
+ this.readLine(this.buffer.slice(0, newline));
160
+ this.buffer = this.buffer.slice(newline + 1);
161
+ }
162
+ }
163
+
164
+ end(): void {
165
+ this.buffer += this.decoder.end();
166
+ this.readLine(this.buffer);
167
+ this.buffer = '';
168
+ for (const message of this.unfinished.values()) this.report(message);
169
+ this.unfinished.clear();
170
+ }
171
+
172
+ private readLine(line: string): void {
173
+ try {
174
+ const event = JSON.parse(line);
175
+ if (event.message?.role !== 'assistant' || event.message.provider !== 'openrouter') return;
176
+ if (event.type === 'message_update' && event.message.responseId) {
177
+ const { provider, responseId, model, timestamp } = event.message;
178
+ this.unfinished.set(responseId, { provider, responseId, model, timestamp });
179
+ return;
180
+ }
181
+ if (event.type !== 'message_end') return;
182
+ this.unfinished.delete(event.message.responseId);
183
+ this.report(event.message);
184
+ } catch { /* Non-JSON output is still handled by the original decision parser. */ }
185
+ }
186
+
187
+ private report(message: any): void {
188
+ try { this.observe(message); } catch { /* Preserve review decisions. */ }
189
+ }
190
+ }
@@ -137,3 +137,15 @@ test("the HTTP driver interoperates with a compatible server and refuses redirec
137
137
  await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
138
138
  }
139
139
  });
140
+
141
+
142
+ test("billing survives an invalid verdict and observer errors cannot change a valid verdict", async () => {
143
+ const bills: any[] = [];
144
+ await assert.rejects(requestJevReview({ provider: "openrouter", model: "typesafe/jev" }, "state", 1000, undefined, "key",
145
+ async () => Response.json({ id: "gen-billed-invalid", usage: { cost: 0.002 }, answers: {} }),
146
+ bill => bills.push(bill)), /invalid/);
147
+ assert.deepEqual(bills, [{ provider: "openrouter", responseId: "gen-billed-invalid", model: "typesafe/jev", costUSD: 0.002 }]);
148
+ const result = await requestJevReview(config, "state", 1000, undefined, "key", async () => response(),
149
+ () => { throw new Error("consumer error"); });
150
+ assert.equal(result.decision.allowed, true);
151
+ });
@@ -58,7 +58,7 @@ function install(t: any, cwd: string, getProviderApiKey = async (_provider: stri
58
58
  return command => handler({ toolName: "bash", input: { command }, toolCallId: "pending" }, {
59
59
  cwd, hasUI: false, isProjectTrusted: () => false,
60
60
  modelRegistry: { getApiKeyForProvider: getProviderApiKey },
61
- sessionManager: { getBranch: () => [{ message: { role: "user", content: "Please run the project tests." } }] },
61
+ sessionManager: { getSessionId: () => "test-session", appendUsage() {}, getBranch: () => [{ message: { role: "user", content: "Please run the project tests." } }] },
62
62
  });
63
63
  }
64
64
 
@@ -0,0 +1,103 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { ReviewerCosts, ReviewerOutput, REVIEWER_COST_EVENT, formatReviewerCost } from '../reviewer-cost.ts';
4
+
5
+ const flush = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); };
6
+
7
+ test('reviewer exposes actual billing once per generation and uses the saved credential resolver', async () => {
8
+ const events: any[] = [];
9
+ let calls = 0;
10
+ const costs = new ReviewerCosts({ parentSessionId: 'parent', reviewId: 'tool-1',
11
+ getApiKey: async () => 'saved-key', report: event => events.push(event),
12
+ fetch: async (url, options) => {
13
+ calls++;
14
+ assert.equal(new Headers(options?.headers).get('Authorization'), 'Bearer saved-key');
15
+ return Response.json({ data: { id: new URL(String(url)).searchParams.get('id'), total_cost: 0.0030718 } });
16
+ },
17
+ });
18
+ const message = { provider: 'openrouter', model: 'reviewer-model', responseId: 'gen-1' };
19
+ costs.observe(message); costs.observe(message);
20
+ await flush();
21
+ assert.equal(calls, 1);
22
+ assert.deepEqual(events.map(event => event.status), ['pending', 'confirmed']);
23
+ assert.equal(events[1].costUSD, 0.0030718);
24
+ assert.equal(events[1].parentSessionId, 'parent');
25
+ assert.equal(REVIEWER_COST_EVENT, 'pi-auto-reviewer:cost');
26
+ assert.equal(formatReviewerCost(costs.summary()), 'OpenRouter $0.003072');
27
+ costs.dispose();
28
+ });
29
+
30
+ test('zero bills and failed review attempts count; other providers are not called OpenRouter bills', async () => {
31
+ const costs = new ReviewerCosts({ parentSessionId: 'parent', reviewId: 'tool-2', getApiKey: async () => 'key', report: () => {},
32
+ fetch: async url => Response.json({ data: { id: new URL(String(url)).searchParams.get('id'), total_cost: 0 } }),
33
+ });
34
+ costs.observe({ provider: 'openrouter', responseId: 'failed-attempt', stopReason: 'error' });
35
+ costs.observe({ provider: 'openrouter', responseId: 'retry-success' });
36
+ costs.observe({ provider: 'another-provider', responseId: 'other' });
37
+ await flush();
38
+ assert.deepEqual(costs.summary(), { costUSD: 0, confirmed: 2, pending: 0, unavailable: 0 });
39
+ costs.dispose();
40
+ });
41
+
42
+ test('missing IDs and credentials remain visibly unavailable', async () => {
43
+ const costs = new ReviewerCosts({ parentSessionId: 'parent', reviewId: 'tool-3', getApiKey: async () => undefined, report: () => {} });
44
+ costs.observe({ provider: 'openrouter', timestamp: 1 });
45
+ costs.observe({ provider: 'openrouter', responseId: 'cannot-auth' });
46
+ await flush();
47
+ assert.equal(costs.summary().unavailable, 2);
48
+ assert.match(formatReviewerCost(costs.summary()), /unavailable/);
49
+ costs.dispose();
50
+ });
51
+
52
+ test('observer failures cannot change review decisions; unfinished subprocess IDs survive', () => {
53
+ const ids: string[] = [];
54
+ const parser = new ReviewerOutput(message => ids.push(message.responseId));
55
+ const bytes = Buffer.from(JSON.stringify({ type: 'message_update', message: { role: 'assistant', provider: 'openrouter', responseId: 'unfinished', content: '€' } }) + '\n');
56
+ for (const byte of bytes) parser.write(Buffer.from([byte]));
57
+ assert.deepEqual(ids, []);
58
+ parser.end();
59
+ assert.deepEqual(ids, ['unfinished']);
60
+ const failing = new ReviewerOutput(() => { throw new Error('observer'); });
61
+ assert.doesNotThrow(() => { failing.write(bytes); failing.end(); });
62
+ });
63
+
64
+ test('late billing callbacks are cancelled when the session shuts down', async () => {
65
+ let resolve!: (response: Response) => void;
66
+ const events: any[] = [];
67
+ const costs = new ReviewerCosts({ parentSessionId: 'parent', reviewId: 'tool-4', getApiKey: async () => 'key', report: event => events.push(event),
68
+ fetch: () => new Promise(done => { resolve = done; }),
69
+ });
70
+ costs.observe({ provider: 'openrouter', responseId: 'late' });
71
+ await flush();
72
+ costs.dispose();
73
+ resolve(Response.json({ data: { id: 'late', total_cost: 9 } }));
74
+ await flush();
75
+ assert.deepEqual(events.map(event => event.status), ['pending']);
76
+ });
77
+
78
+
79
+ test('Jev uses provider-reported cost without an extra lookup and keeps missing billing unavailable', () => {
80
+ const events: any[] = [];
81
+ const costs = new ReviewerCosts({ parentSessionId: 'parent', reviewId: 'jev-review', getApiKey: async () => 'key', report: event => events.push(event),
82
+ fetch: async () => { throw new Error('Jev reported its charge already'); },
83
+ });
84
+ costs.observeCharge({ provider: 'openrouter', responseId: 'jev-1', model: 'typesafe/jev', costUSD: 0.000017 });
85
+ costs.observeCharge({ provider: 'openrouter', responseId: 'jev-1', costUSD: 0.000017 });
86
+ costs.observeCharge({ provider: 'openrouter', costUSD: 0 });
87
+ costs.observeCharge({ provider: 'openrouter', costUSD: 'invalid' });
88
+ assert.deepEqual(costs.summary(), { costUSD: 0.000017, confirmed: 2, pending: 0, unavailable: 1 });
89
+ assert.equal(events.filter(e => e.status === 'confirmed').length, 2);
90
+ costs.dispose();
91
+ });
92
+
93
+
94
+ test('billing labels name OpenRouter and never label another provider as OpenRouter', () => {
95
+ assert.equal(formatReviewerCost({ costUSD: 0, confirmed: 0, pending: 1, unavailable: 1 }), 'OpenRouter cost · 1 pending · 1 unavailable');
96
+ const events: unknown[] = [];
97
+ const costs = new ReviewerCosts({ parentSessionId: 'parent', reviewId: 'other-provider', getApiKey: async () => { throw new Error('Must not resolve an OpenRouter key'); }, report: event => events.push(event) });
98
+ costs.observe({ provider: 'anthropic', responseId: 'other-message' });
99
+ costs.observeCharge({ provider: 'typesafe', responseId: 'other-decision', costUSD: 0.002 });
100
+ assert.equal(formatReviewerCost(costs.summary()), '');
101
+ assert.deepEqual(events, []);
102
+ costs.dispose();
103
+ });
@@ -0,0 +1,62 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import * as fs from 'node:fs';
4
+ import * as os from 'node:os';
5
+ import * as path from 'node:path';
6
+ import { SessionManager } from '@earendil-works/pi-coding-agent';
7
+ import extension from '../auto-reviewer.ts';
8
+
9
+ // This fixture loads only the public reviewer. No consumer extension is present.
10
+ test('standalone Jev reviewer shows actual charges and persists native usage, including failed attempts', async t => {
11
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'reviewer-native-'));
12
+ const manager = SessionManager.create(cwd, path.join(cwd, 'sessions'));
13
+ manager.appendMessage({ role: 'user', content: 'Run the project tests.', timestamp: Date.now() });
14
+ // Pi flushes earlier entries once an assistant message exists.
15
+ manager.appendMessage({ role: 'assistant', provider: 'fixture', model: 'fixture', api: 'openai-completions', content: [],
16
+ timestamp: Date.now(), stopReason: 'stop', usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
17
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } });
18
+ const keys = ['PI_REVIEWER_BACKEND', 'PI_REVIEWER_PROVIDER', 'PI_REVIEWER_MODEL', 'PI_REVIEWER_ENDPOINT', 'PI_REVIEWER_API_KEY_ENV'];
19
+ const originalEnv = Object.fromEntries(keys.map(key => [key, process.env[key]]));
20
+ const originalFetch = globalThis.fetch;
21
+ for (const key of keys) delete process.env[key];
22
+ Object.assign(process.env, { PI_REVIEWER_BACKEND: 'jev', PI_REVIEWER_PROVIDER: 'openrouter', PI_REVIEWER_MODEL: 'typesafe/jev' });
23
+ t.after(() => {
24
+ globalThis.fetch = originalFetch;
25
+ for (const key of keys) {
26
+ if (originalEnv[key] === undefined) delete process.env[key];
27
+ else process.env[key] = originalEnv[key];
28
+ }
29
+ fs.rmSync(cwd, { recursive: true, force: true });
30
+ });
31
+ const handlers = new Map<string, any>();
32
+ const events: any[] = [];
33
+ const notifications: string[] = [];
34
+ extension({ on: (name: string, handler: any) => handlers.set(name, handler),
35
+ appendEntry: (type: string, data: unknown) => manager.appendCustomEntry(type, data),
36
+ events: { emit: (name: string, data: unknown) => events.push({ name, data }) },
37
+ } as any);
38
+ const ctx: any = { cwd, hasUI: true, sessionManager: manager, isProjectTrusted: () => false,
39
+ modelRegistry: { getApiKeyForProvider: async () => 'saved-key' },
40
+ ui: { notify: (message: string) => notifications.push(message), setStatus() {},
41
+ select: () => { throw new Error('Unexpected approval prompt'); } },
42
+ };
43
+ handlers.get('session_start')({}, ctx);
44
+ let calls = 0;
45
+ globalThis.fetch = async (url, options) => {
46
+ assert.equal(String(url), 'https://openrouter.ai/api/alpha/decisions');
47
+ assert.equal(new Headers(options?.headers).get('Authorization'), 'Bearer saved-key');
48
+ calls++;
49
+ return Response.json({ id: `gen-attempt-${calls}`, model: 'typesafe/jev', usage: { cost: calls === 1 ? 0.003 : 0.007 },
50
+ answers: calls === 1 ? {} : { command_review: { type: 'choice', choice: 'allow', confidence: 0.9, probabilities: { allow: 0.9, block: 0.1 } } } });
51
+ };
52
+ assert.equal(await handlers.get('tool_call')({ toolName: 'bash', toolCallId: 'review-1', input: { command: 'npm test' } }, ctx), undefined);
53
+ assert.equal(calls, 2);
54
+ const billed = manager.getEntries().filter(e => e.type === 'usage');
55
+ assert.equal(billed.length, 2);
56
+ assert.ok(Math.abs(billed.reduce((sum, e) => sum + e.usage.cost.total, 0) - 0.01) < 1e-12);
57
+ assert.ok(billed.every(e => e.usage.totalTokens === 0 && e.provider === 'openrouter'));
58
+ assert.ok(notifications.some(message => message.includes('Auto-reviewer: ✓') && message.includes('OpenRouter $0.010000')));
59
+ assert.equal(events.filter(e => e.name === 'pi-auto-reviewer:cost' && e.data.status === 'confirmed').length, 2);
60
+ assert.equal(SessionManager.open(manager.getSessionFile()!).getEntries().filter(e => e.type === 'usage').length, 2);
61
+ await handlers.get('session_shutdown')({}, ctx);
62
+ });