@mrclrchtr/supi-review 3.0.0 → 3.2.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.
Files changed (39) hide show
  1. package/README.md +41 -20
  2. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  3. package/package.json +2 -2
  4. package/src/git-choices.ts +42 -0
  5. package/src/git-command.ts +172 -2
  6. package/src/git.ts +126 -291
  7. package/src/history/collect.ts +15 -6
  8. package/src/review-input.ts +36 -0
  9. package/src/review-limits.ts +12 -0
  10. package/src/review-path.ts +18 -12
  11. package/src/review-result.ts +26 -5
  12. package/src/review.ts +201 -76
  13. package/src/session/review-artifact-store.ts +97 -0
  14. package/src/session/review-plan-store.ts +93 -12
  15. package/src/target/change-metadata.ts +125 -0
  16. package/src/target/diff.ts +43 -0
  17. package/src/target/file-manifest.ts +40 -0
  18. package/src/target/packet.ts +17 -6
  19. package/src/target/resolve.ts +209 -0
  20. package/src/tool/agent-review-schemas.ts +21 -9
  21. package/src/tool/agent-review-tools.ts +66 -17
  22. package/src/tool/child-failure-diagnostics.ts +35 -0
  23. package/src/tool/child-lifecycle-trace.ts +27 -11
  24. package/src/tool/child-session-runner.ts +28 -11
  25. package/src/tool/child-usage.ts +73 -0
  26. package/src/tool/diagnostic-sanitizer.ts +35 -0
  27. package/src/tool/output-page.ts +26 -0
  28. package/src/tool/planner-runner.ts +28 -10
  29. package/src/tool/review-output-tool.ts +93 -0
  30. package/src/tool/review-runner.ts +9 -7
  31. package/src/tool/review-tools.ts +90 -12
  32. package/src/tool/review-workflow.ts +163 -83
  33. package/src/tool/schemas.ts +24 -5
  34. package/src/tool/session-lifecycle.ts +44 -54
  35. package/src/tool/usage-format.ts +15 -0
  36. package/src/tui/common.ts +58 -1
  37. package/src/tui/prepare.ts +57 -31
  38. package/src/tui/run.ts +13 -3
  39. package/src/types.ts +62 -19
@@ -1,9 +1,11 @@
1
+ import type { Usage } from "@earendil-works/pi-ai";
1
2
  import { buildSessionContext, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
3
  import { StatusSpinner } from "@mrclrchtr/supi-core/status-spinner";
3
4
  import { loadReviewConfig } from "../config.ts";
4
5
  import { summarizeReviewSnapshot } from "../git.ts";
5
6
  import { collectPlannerContext } from "../history/collect.ts";
6
7
  import { resolveAgentReviewModel } from "../model.ts";
8
+ import type { ReviewArtifactStore } from "../session/review-artifact-store.ts";
7
9
  import type { ReviewPlanStore } from "../session/review-plan-store.ts";
8
10
  import { renderPrepareCall, renderPrepareResult } from "../tui/prepare.ts";
9
11
  import { renderRunCall, renderRunResult } from "../tui/run.ts";
@@ -15,25 +17,40 @@ import {
15
17
  prepareReviewSchema,
16
18
  runReviewSchema,
17
19
  } from "./agent-review-schemas.ts";
18
- import { pageText } from "./output-page.ts";
20
+ import { formatChildFailureDiagnostics } from "./child-failure-diagnostics.ts";
21
+ import { createReviewOutput } from "./review-output-tool.ts";
19
22
  import { prepareReview, runReview } from "./review-workflow.ts";
23
+ import { formatReviewUsage } from "./usage-format.ts";
20
24
 
21
25
  function target(input: PrepareReviewToolInput["target"]): ReviewTargetSpec {
22
26
  return (input ?? { kind: "working-tree" }) as ReviewTargetSpec;
23
27
  }
24
28
 
29
+ function plannerFailureReason(failure: {
30
+ kind: string;
31
+ failureCode?: string;
32
+ timeoutMs?: number;
33
+ }): string {
34
+ if (failure.kind === "failed") return failure.failureCode ?? "failed";
35
+ if (failure.kind === "timeout") return `timeout (${failure.timeoutMs} ms)`;
36
+ return failure.kind;
37
+ }
38
+
25
39
  function formatPrepared(plan: {
26
40
  id: string;
27
- snapshot: { title: string; changedFiles: string[] };
41
+ snapshot: { title: string; changes: Array<{ path: string }> };
28
42
  plannerDraft?: { sharedContext?: string; tasks: Array<{ id: string; instructions: string }> };
43
+ plannerFailure?: { kind: string; failureCode?: string; timeoutMs?: number };
44
+ plannerUsage?: Usage;
29
45
  }): string {
30
46
  const lines = [
31
47
  "# Review Plan Prepared",
32
48
  "",
33
49
  `Plan ID: ${plan.id}`,
34
50
  `Target: ${plan.snapshot.title}`,
35
- `Files changed: ${plan.snapshot.changedFiles.length}`,
51
+ `Files changed: ${plan.snapshot.changes.length}`,
36
52
  ];
53
+ if (plan.plannerUsage) lines.push(`Planner usage: ${formatReviewUsage(plan.plannerUsage)}`);
37
54
  if (plan.plannerDraft) {
38
55
  lines.push("", "## Planner Draft");
39
56
  if (plan.plannerDraft.sharedContext) lines.push("", plan.plannerDraft.sharedContext);
@@ -42,6 +59,10 @@ function formatPrepared(plan: {
42
59
  }
43
60
  lines.push("", "Call supi_review_run with an explicit accept-draft or use-review decision.");
44
61
  } else {
62
+ if (plan.plannerFailure) {
63
+ const reason = plannerFailureReason(plan.plannerFailure);
64
+ lines.push("", `Planner unavailable: ${reason}. The plan remains usable without a draft.`);
65
+ }
45
66
  lines.push("", "Call supi_review_run with a use-review decision containing one to four tasks.");
46
67
  }
47
68
  return lines.join("\n");
@@ -54,10 +75,27 @@ function formatTaskResult(result: ReviewTaskResult): string[] {
54
75
  `Model: ${result.modelId}`,
55
76
  `Packet SHA-256: ${result.packetHash}`,
56
77
  ];
57
- if (result.status === "failed") return [...lines, `Status: failed (${result.failureCode})`];
58
- if (result.status === "canceled") return [...lines, "Status: canceled"];
78
+ if (result.usage) lines.push(`Usage: ${formatReviewUsage(result.usage)}`);
79
+ if (result.status === "failed") {
80
+ lines.push(`Status: failed (${result.failureCode})`);
81
+ if (result.diagnostics) {
82
+ lines.push("", ...formatChildFailureDiagnostics(result.diagnostics));
83
+ }
84
+ return lines;
85
+ }
86
+ if (result.status === "canceled") {
87
+ lines.push("Status: canceled");
88
+ if (result.diagnostics) {
89
+ lines.push("", ...formatChildFailureDiagnostics(result.diagnostics));
90
+ }
91
+ return lines;
92
+ }
59
93
  if (result.status === "timeout") {
60
- return [...lines, `Status: timeout (${result.timeoutMs} ms)`];
94
+ lines.push(`Status: timeout (${result.timeoutMs} ms)`);
95
+ if (result.diagnostics) {
96
+ lines.push("", ...formatChildFailureDiagnostics(result.diagnostics));
97
+ }
98
+ return lines;
61
99
  }
62
100
  lines.push(`Verdict: ${result.verdict.toUpperCase()}`, "", result.summary);
63
101
  for (const finding of result.findings) {
@@ -77,7 +115,7 @@ function formatTaskResult(result: ReviewTaskResult): string[] {
77
115
 
78
116
  export function formatReviewBatch(details: ReviewBatchDetails): string {
79
117
  const lines = [
80
- "# Review Complete",
118
+ "# Review Finished",
81
119
  "",
82
120
  `Mode: ${details.mode}`,
83
121
  `Provenance: ${details.provenance}`,
@@ -87,6 +125,9 @@ export function formatReviewBatch(details: ReviewBatchDetails): string {
87
125
  lines.push(
88
126
  `Planner: ${details.planning.modelId} (protocol ${details.planning.promptVersion})`,
89
127
  `Planner decision: ${details.planning.decision}`,
128
+ ...(details.planning.usage
129
+ ? [`Planner usage: ${formatReviewUsage(details.planning.usage)}`]
130
+ : []),
90
131
  );
91
132
  }
92
133
  for (const result of details.results) lines.push(...formatTaskResult(result));
@@ -99,7 +140,7 @@ function resolveModels(ctx: Parameters<Parameters<ExtensionAPI["registerTool"]>[
99
140
  const planner = resolveAgentReviewModel(ctx, config.plannerModel);
100
141
  if (!reviewer)
101
142
  throw new Error(`Configured reviewer model "${config.agentModel}" is unavailable.`);
102
- return { reviewer, planner, config };
143
+ return { reviewer, planner };
103
144
  }
104
145
 
105
146
  /**
@@ -157,6 +198,7 @@ function initialTaskCount(
157
198
  /** Factory for the supi_review_run execute function with animated status-bar spinner. */
158
199
  function makeRunReviewExecute(
159
200
  planStore: ReviewPlanStore,
201
+ artifactStore: ReviewArtifactStore,
160
202
  ): NonNullable<Parameters<ExtensionAPI["registerTool"]>[0]["execute"]> {
161
203
  // biome-ignore lint/complexity/useMaxParams: Pi ToolDefinition execute signature
162
204
  return async (_id, params, signal, onUpdate, ctx) => {
@@ -192,9 +234,11 @@ function makeRunReviewExecute(
192
234
  onUpdate: wrappedUpdate,
193
235
  });
194
236
  if (outcome.kind !== "completed") throw new Error(outcome.reason);
237
+ const output = createReviewOutput(artifactStore, formatReviewBatch(outcome.details));
195
238
  return {
196
- content: [{ type: "text", text: pageText(formatReviewBatch(outcome.details)).text }],
197
- details: outcome.details,
239
+ content: [{ type: "text", text: output.text }],
240
+ details: { ...outcome.details, output: output.reference },
241
+ ...(outcome.usage ? { usage: outcome.usage } : {}),
198
242
  };
199
243
  } finally {
200
244
  statusSpinner.stop();
@@ -219,7 +263,11 @@ function throwPrepareFailure(
219
263
  }
220
264
 
221
265
  /** Register optional preparation and universal direct/prepared execution tools. */
222
- export function registerAgentReviewTools(pi: ExtensionAPI, planStore: ReviewPlanStore): void {
266
+ export function registerAgentReviewTools(
267
+ pi: ExtensionAPI,
268
+ planStore: ReviewPlanStore,
269
+ artifactStore: ReviewArtifactStore,
270
+ ): void {
223
271
  pi.registerTool({
224
272
  name: "supi_review_prepare",
225
273
  label: "Prepare Review",
@@ -236,10 +284,6 @@ export function registerAgentReviewTools(pi: ExtensionAPI, planStore: ReviewPlan
236
284
  async execute(_id, params, signal, onUpdate, ctx) {
237
285
  const input = parsePrepareReviewToolInput(params);
238
286
  const models = resolveModels(ctx);
239
- if ((input.planning ?? "none") === "suggest" && !models.planner) {
240
- throw new Error(`Configured Planner model "${models.config.plannerModel}" is unavailable.`);
241
- }
242
-
243
287
  const { statusSpinner, wrappedUpdate } = wireSpinnerToProgress(
244
288
  ctx,
245
289
  onUpdate,
@@ -263,8 +307,9 @@ export function registerAgentReviewTools(pi: ExtensionAPI, planStore: ReviewPlan
263
307
  onUpdate: wrappedUpdate,
264
308
  });
265
309
  if (outcome.kind !== "prepared") throwPrepareFailure(outcome);
310
+ const output = createReviewOutput(artifactStore, formatPrepared(outcome.plan));
266
311
  return {
267
- content: [{ type: "text", text: pageText(formatPrepared(outcome.plan)).text }],
312
+ content: [{ type: "text", text: output.text }],
268
313
  details: {
269
314
  kind: "review-prepared",
270
315
  planId: outcome.plan.id,
@@ -273,7 +318,11 @@ export function registerAgentReviewTools(pi: ExtensionAPI, planStore: ReviewPlan
273
318
  plannerDraft: outcome.plan.plannerDraft,
274
319
  plannerModelId: outcome.plan.plannerModelId,
275
320
  plannerPromptVersion: outcome.plan.plannerPromptVersion,
321
+ plannerUsage: outcome.plan.plannerUsage,
322
+ plannerFailure: outcome.plan.plannerFailure,
323
+ output: output.reference,
276
324
  },
325
+ ...(outcome.usage ? { usage: outcome.usage } : {}),
277
326
  };
278
327
  } finally {
279
328
  statusSpinner.stop();
@@ -293,7 +342,7 @@ export function registerAgentReviewTools(pi: ExtensionAPI, planStore: ReviewPlan
293
342
  parameters: runReviewSchema,
294
343
  renderCall: renderRunCall,
295
344
  renderResult: renderRunResult,
296
- execute: makeRunReviewExecute(planStore),
345
+ execute: makeRunReviewExecute(planStore, artifactStore),
297
346
  });
298
347
 
299
348
  pi.on("session_start", () => planStore.clear());
@@ -8,10 +8,12 @@ import type {
8
8
  import {
9
9
  type ChildLifecycleTrace,
10
10
  ChildLifecycleTraceCollector,
11
+ extractLastLifecycleErrorText,
11
12
  formatChildLifecycleTrace,
12
13
  getRegisteredToolNames,
13
14
  toSafeAssistantStopReason,
14
15
  } from "./child-lifecycle-trace.ts";
16
+ import { sanitizeChildErrorText } from "./diagnostic-sanitizer.ts";
15
17
  import { buildProgressTokens } from "./runner-helpers.ts";
16
18
 
17
19
  /** Inputs used to create one safe non-success child-run diagnostic artifact. */
@@ -40,6 +42,8 @@ export function buildChildFailureDiagnostics(
40
42
  recentActivity: input.recentActivity.length > 0 ? [...input.recentActivity] : undefined,
41
43
  lastAssistantStopReason: lastAssistant?.stopReason,
42
44
  lastAssistantToolCalls: lastAssistant?.toolCalls,
45
+ lastAssistantErrorText: lastAssistant?.errorText,
46
+ lastLifecycleErrorText: extractLastLifecycleErrorText(input.lifecycleTrace),
43
47
  };
44
48
  }
45
49
 
@@ -78,6 +82,28 @@ export function formatChildFailureCopy(stage: ChildStage, code: ChildFailureCode
78
82
  }
79
83
  }
80
84
 
85
+ export interface ChildDiagnosticErrorRow {
86
+ label: "Last assistant error" | "Lifecycle error";
87
+ text: string;
88
+ }
89
+
90
+ /** Return the distinct bounded provider error summaries shared by text and TUI rendering. */
91
+ export function getChildDiagnosticErrorRows(
92
+ diagnostics: ChildFailureDiagnostics,
93
+ ): ChildDiagnosticErrorRow[] {
94
+ const rows: ChildDiagnosticErrorRow[] = [];
95
+ if (diagnostics.lastAssistantErrorText) {
96
+ rows.push({ label: "Last assistant error", text: diagnostics.lastAssistantErrorText });
97
+ }
98
+ if (
99
+ diagnostics.lastLifecycleErrorText &&
100
+ diagnostics.lastLifecycleErrorText !== diagnostics.lastAssistantErrorText
101
+ ) {
102
+ rows.push({ label: "Lifecycle error", text: diagnostics.lastLifecycleErrorText });
103
+ }
104
+ return rows;
105
+ }
106
+
81
107
  /** Format the complete retained safe diagnostic artifact for parent-facing text. */
82
108
  export function formatChildFailureDiagnostics(diagnostics: ChildFailureDiagnostics): string[] {
83
109
  const lines = [
@@ -95,6 +121,7 @@ export function formatChildFailureDiagnostics(diagnostics: ChildFailureDiagnosti
95
121
  diagnostics.lastAssistantToolCalls && diagnostics.lastAssistantToolCalls.length > 0
96
122
  ? `- Last assistant tools: ${diagnostics.lastAssistantToolCalls.join(", ")}`
97
123
  : undefined,
124
+ ...getChildDiagnosticErrorRows(diagnostics).map((row) => `- ${row.label}: ${row.text}`),
98
125
  `- ${formatChildLifecycleTrace(diagnostics.lifecycleTrace)}`,
99
126
  ];
100
127
  return lines.filter((line): line is string => !!line);
@@ -103,6 +130,7 @@ export function formatChildFailureDiagnostics(diagnostics: ChildFailureDiagnosti
103
130
  interface LastAssistantMetadata {
104
131
  stopReason?: string;
105
132
  toolCalls?: string[];
133
+ errorText?: string;
106
134
  }
107
135
 
108
136
  function extractLastAssistantMetadata(session: AgentSession): LastAssistantMetadata | undefined {
@@ -117,9 +145,11 @@ function extractLastAssistantMetadata(session: AgentSession): LastAssistantMetad
117
145
 
118
146
  const stopReason = toSafeAssistantStopReason(message.stopReason);
119
147
  const toolCalls = extractAssistantToolCalls(message.content, registeredToolNames);
148
+ const errorText = stopReason === "error" ? extractAssistantErrorText(message) : undefined;
120
149
  return {
121
150
  stopReason,
122
151
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
152
+ errorText,
123
153
  };
124
154
  }
125
155
  return undefined;
@@ -143,3 +173,8 @@ function extractAssistantToolCalls(content: unknown, registeredToolNames: Set<st
143
173
  })
144
174
  .filter((name): name is string => !!name);
145
175
  }
176
+
177
+ /** Extract only Pi's canonical provider error field from an errored assistant message. */
178
+ function extractAssistantErrorText(message: Record<string, unknown>): string | undefined {
179
+ return sanitizeChildErrorText(message.errorMessage);
180
+ }
@@ -1,4 +1,5 @@
1
1
  import type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
2
+ import { sanitizeChildErrorText } from "./diagnostic-sanitizer.ts";
2
3
 
3
4
  /** Maximum number of observed Child Lifecycle Trace entries retained per child run. */
4
5
  export const CHILD_LIFECYCLE_TRACE_MAX = 32;
@@ -53,9 +54,16 @@ export type ChildLifecycleTraceEntry =
53
54
  willRetry: boolean;
54
55
  hasResult: boolean;
55
56
  hasError: boolean;
57
+ errorText?: string;
56
58
  }
57
59
  | { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number }
58
- | { type: "auto_retry_end"; success: boolean; attempt: number; hasFinalError: boolean }
60
+ | {
61
+ type: "auto_retry_end";
62
+ success: boolean;
63
+ attempt: number;
64
+ hasFinalError: boolean;
65
+ finalErrorText?: string;
66
+ }
59
67
  | {
60
68
  type: "summarization_retry_scheduled";
61
69
  attempt: number;
@@ -73,7 +81,6 @@ export type ChildLifecycleTraceEntry =
73
81
 
74
82
  /** Minimal runner-control transitions that explain host-originated termination. */
75
83
  export type ChildLifecycleHostMarker =
76
- | { type: "steer_requested"; reason: "submit" | "timeout" }
77
84
  | { type: "timeout_expired" }
78
85
  | { type: "abort_requested"; reason: "canceled" | "timeout" }
79
86
  | { type: "prompt_rejected" };
@@ -115,11 +122,6 @@ export class ChildLifecycleTraceCollector {
115
122
  /** Record an allowlisted runner-control transition. */
116
123
  recordHostMarker(marker: ChildLifecycleHostMarker): void {
117
124
  switch (marker.type) {
118
- case "steer_requested":
119
- if (marker.reason === "submit" || marker.reason === "timeout") {
120
- this.push({ type: "steer_requested", reason: marker.reason });
121
- }
122
- break;
123
125
  case "abort_requested":
124
126
  if (marker.reason === "canceled" || marker.reason === "timeout") {
125
127
  this.push({ type: "abort_requested", reason: marker.reason });
@@ -161,6 +163,20 @@ export class ChildLifecycleTraceCollector {
161
163
  }
162
164
  }
163
165
 
166
+ /**
167
+ * Extract error text from the most recent lifecycle entry that carries an error.
168
+ * Checks compaction_end.errorText and auto_retry_end.finalErrorText.
169
+ */
170
+ export function extractLastLifecycleErrorText(trace: ChildLifecycleTrace): string | undefined {
171
+ // Walk backwards to find the most recent error
172
+ for (let i = trace.entries.length - 1; i >= 0; i--) {
173
+ const entry = trace.entries[i];
174
+ if (entry.type === "compaction_end" && entry.errorText) return entry.errorText;
175
+ if (entry.type === "auto_retry_end" && entry.finalErrorText) return entry.finalErrorText;
176
+ }
177
+ return undefined;
178
+ }
179
+
164
180
  /** Format the complete retained Child Lifecycle Trace for parent-facing diagnostics. */
165
181
  export function formatChildLifecycleTrace(trace: ChildLifecycleTrace): string {
166
182
  const tail =
@@ -185,11 +201,11 @@ function formatChildLifecycleTraceEntry(entry: ChildLifecycleTraceEntry): string
185
201
  case "compaction_start":
186
202
  return `compaction_start(reason=${entry.reason})`;
187
203
  case "compaction_end":
188
- return `compaction_end(reason=${entry.reason}, aborted=${entry.aborted}, willRetry=${entry.willRetry}, hasResult=${entry.hasResult}, hasError=${entry.hasError})`;
204
+ return `compaction_end(reason=${entry.reason}, aborted=${entry.aborted}, willRetry=${entry.willRetry}, hasResult=${entry.hasResult}, hasError=${entry.hasError}${entry.errorText ? `, error=${JSON.stringify(entry.errorText)}` : ""})`;
189
205
  case "auto_retry_start":
190
206
  return `auto_retry_start(attempt=${entry.attempt}/${entry.maxAttempts}, delayMs=${entry.delayMs})`;
191
207
  case "auto_retry_end":
192
- return `auto_retry_end(success=${entry.success}, attempt=${entry.attempt}, hasFinalError=${entry.hasFinalError})`;
208
+ return `auto_retry_end(success=${entry.success}, attempt=${entry.attempt}, hasFinalError=${entry.hasFinalError}${entry.finalErrorText ? `, error=${JSON.stringify(entry.finalErrorText)}` : ""})`;
193
209
  case "summarization_retry_scheduled":
194
210
  return `summarization_retry_scheduled(attempt=${entry.attempt}/${entry.maxAttempts}, delayMs=${entry.delayMs})`;
195
211
  case "summarization_retry_attempt_start":
@@ -198,8 +214,6 @@ function formatChildLifecycleTraceEntry(entry: ChildLifecycleTraceEntry): string
198
214
  : `summarization_retry_attempt_start(source=${entry.source})`;
199
215
  case "queue_update":
200
216
  return `queue_update(steering=${entry.steeringCount}, followUp=${entry.followUpCount})`;
201
- case "steer_requested":
202
- return `steer_requested(reason=${entry.reason})`;
203
217
  case "abort_requested":
204
218
  return `abort_requested(reason=${entry.reason})`;
205
219
  }
@@ -269,6 +283,7 @@ function mapLifecycleEvent(event: AgentSessionEvent): ChildLifecycleTraceEntry |
269
283
  willRetry: event.willRetry,
270
284
  hasResult: event.result !== undefined,
271
285
  hasError: event.errorMessage !== undefined,
286
+ errorText: sanitizeChildErrorText(event.errorMessage),
272
287
  }
273
288
  : undefined;
274
289
  case "auto_retry_start":
@@ -289,6 +304,7 @@ function mapLifecycleEvent(event: AgentSessionEvent): ChildLifecycleTraceEntry |
289
304
  success: event.success,
290
305
  attempt: event.attempt,
291
306
  hasFinalError: event.finalError !== undefined,
307
+ finalErrorText: sanitizeChildErrorText(event.finalError),
292
308
  }
293
309
  : undefined;
294
310
  case "summarization_retry_scheduled":
@@ -1,4 +1,4 @@
1
- import type { clampThinkingLevel, Model } from "@earendil-works/pi-ai";
1
+ import type { clampThinkingLevel, Model, Usage } from "@earendil-works/pi-ai";
2
2
  import {
3
3
  createAgentSession,
4
4
  SessionManager,
@@ -6,6 +6,7 @@ import {
6
6
  } from "@earendil-works/pi-coding-agent";
7
7
  import type { ChildFailureDiagnostics, ReviewProgress } from "../types.ts";
8
8
  import { createIsolatedChildResources } from "./child-resource-loader.ts";
9
+ import { buildProgressTokens } from "./runner-helpers.ts";
9
10
  import { runWithLifecycle } from "./session-lifecycle.ts";
10
11
 
11
12
  /** Configuration for one isolated child run — resource loading, session, and lifecycle. */
@@ -15,19 +16,24 @@ export interface IsolatedRunConfig<THolder, TResult> {
15
16
  // biome-ignore lint/suspicious/noExplicitAny: Model<any> is Pi's canonical type
16
17
  model: Model<any>;
17
18
  thinkingLevel: ReturnType<typeof clampThinkingLevel>;
18
- timeoutMs: number;
19
+ timeoutMs?: number;
19
20
  prompt: string;
20
21
  signal?: AbortSignal;
21
22
  tools: string[];
22
23
  customTools: ToolDefinition[];
23
24
  holder: { value?: THolder };
24
- successResult: (value: THolder) => TResult;
25
- canceledResult: (diagnostics: ChildFailureDiagnostics) => TResult;
25
+ successResult: (value: THolder, usage?: Usage) => TResult;
26
+ canceledResult: (diagnostics: ChildFailureDiagnostics, usage?: Usage) => TResult;
26
27
  failedResult: (
27
28
  failureCode: "prompt-rejected" | "missing-structured-output" | "unexpected-runner-failure",
28
29
  diagnostics: ChildFailureDiagnostics,
30
+ usage?: Usage,
31
+ ) => TResult;
32
+ timeoutResult: (
33
+ timeoutMs: number,
34
+ diagnostics: ChildFailureDiagnostics,
35
+ usage?: Usage,
29
36
  ) => TResult;
30
- timeoutResult: (timeoutMs: number, diagnostics: ChildFailureDiagnostics) => TResult;
31
37
  sessionFailedResult: TResult;
32
38
  onProgress?: (progress: ReviewProgress) => void;
33
39
  }
@@ -62,20 +68,31 @@ export async function runIsolatedChild<THolder, TResult>(
62
68
  signal: config.signal,
63
69
  timeoutMs: config.timeoutMs,
64
70
  onEvent: (event, ctx) => {
71
+ const reportsProgress =
72
+ event.type === "turn_end" ||
73
+ event.type === "tool_execution_start" ||
74
+ event.type === "agent_settled";
65
75
  if (event.type === "turn_end") ctx.progress.turns++;
66
76
  if (event.type === "tool_execution_start") ctx.progress.toolUses++;
67
- config.onProgress?.(ctx.progress);
77
+ if (reportsProgress) {
78
+ ctx.progress.tokens = buildProgressTokens(() => ctx.session.getSessionStats());
79
+ config.onProgress?.({ ...ctx.progress });
80
+ }
68
81
  if (event.type !== "agent_settled") return;
69
82
  const result = config.holder.value
70
- ? config.successResult(config.holder.value)
71
- : config.failedResult("missing-structured-output", ctx.getFailureDiagnostics());
83
+ ? config.successResult(config.holder.value, ctx.getUsage())
84
+ : config.failedResult(
85
+ "missing-structured-output",
86
+ ctx.getFailureDiagnostics(),
87
+ ctx.getUsage(),
88
+ );
72
89
  ctx.resolve(ctx.cleanup(result));
73
90
  },
74
- canceledResult: (ctx) => config.canceledResult(ctx.getFailureDiagnostics()),
91
+ canceledResult: (ctx) => config.canceledResult(ctx.getFailureDiagnostics(), ctx.getUsage()),
75
92
  failedResult: (failureCode, ctx) =>
76
- config.failedResult(failureCode, ctx.getFailureDiagnostics()),
93
+ config.failedResult(failureCode, ctx.getFailureDiagnostics(), ctx.getUsage()),
77
94
  timeoutResult: (timeoutMs, ctx) =>
78
- config.timeoutResult(timeoutMs, ctx.getFailureDiagnostics()),
95
+ config.timeoutResult(timeoutMs, ctx.getFailureDiagnostics(), ctx.getUsage()),
79
96
  });
80
97
  } catch {
81
98
  return config.sessionFailedResult;
@@ -0,0 +1,73 @@
1
+ import type { Usage } from "@earendil-works/pi-ai";
2
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
3
+
4
+ function addOptional(first: number | undefined, second: number | undefined): number | undefined {
5
+ return first === undefined && second === undefined ? undefined : (first ?? 0) + (second ?? 0);
6
+ }
7
+
8
+ /** Add two provider Usage records without dropping optional reasoning/cache fields. */
9
+ export function addUsage(first: Usage, second: Usage): Usage {
10
+ const cacheWrite1h = addOptional(first.cacheWrite1h, second.cacheWrite1h);
11
+ const reasoning = addOptional(first.reasoning, second.reasoning);
12
+ return {
13
+ input: first.input + second.input,
14
+ output: first.output + second.output,
15
+ cacheRead: first.cacheRead + second.cacheRead,
16
+ cacheWrite: first.cacheWrite + second.cacheWrite,
17
+ ...(cacheWrite1h === undefined ? {} : { cacheWrite1h }),
18
+ ...(reasoning === undefined ? {} : { reasoning }),
19
+ totalTokens: first.totalTokens + second.totalTokens,
20
+ cost: {
21
+ input: first.cost.input + second.cost.input,
22
+ output: first.cost.output + second.cost.output,
23
+ cacheRead: first.cost.cacheRead + second.cost.cacheRead,
24
+ cacheWrite: first.cost.cacheWrite + second.cost.cacheWrite,
25
+ total: first.cost.total + second.cost.total,
26
+ },
27
+ };
28
+ }
29
+
30
+ /** Sum available Usage records, returning undefined when no model call reported usage. */
31
+ export function combineUsage(usages: Array<Usage | undefined>): Usage | undefined {
32
+ return usages.reduce<Usage | undefined>(
33
+ (total, usage) => (usage ? (total ? addUsage(total, usage) : usage) : total),
34
+ undefined,
35
+ );
36
+ }
37
+
38
+ /** Snapshot aggregate assistant usage from one isolated child transcript. */
39
+ export function collectChildUsage(session: AgentSession): Usage | undefined {
40
+ try {
41
+ const messages = session.messages as unknown;
42
+ if (!Array.isArray(messages)) return undefined;
43
+ return combineUsage(
44
+ messages.map((message) => {
45
+ if (!message || typeof message !== "object") return undefined;
46
+ const candidate = message as { role?: unknown; usage?: unknown };
47
+ return candidate.role === "assistant" && isUsage(candidate.usage)
48
+ ? candidate.usage
49
+ : undefined;
50
+ }),
51
+ );
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ }
56
+
57
+ function isUsage(value: unknown): value is Usage {
58
+ if (!value || typeof value !== "object") return false;
59
+ const usage = value as Partial<Usage>;
60
+ return (
61
+ typeof usage.input === "number" &&
62
+ typeof usage.output === "number" &&
63
+ typeof usage.cacheRead === "number" &&
64
+ typeof usage.cacheWrite === "number" &&
65
+ typeof usage.totalTokens === "number" &&
66
+ !!usage.cost &&
67
+ typeof usage.cost.input === "number" &&
68
+ typeof usage.cost.output === "number" &&
69
+ typeof usage.cost.cacheRead === "number" &&
70
+ typeof usage.cost.cacheWrite === "number" &&
71
+ typeof usage.cost.total === "number"
72
+ );
73
+ }
@@ -0,0 +1,35 @@
1
+ import { redactDebugData } from "@mrclrchtr/supi-core/debug";
2
+
3
+ /** Maximum retained characters for one provider-owned diagnostic summary. */
4
+ export const MAX_CHILD_ERROR_CHARACTERS = 500;
5
+
6
+ const ANSI_ESCAPE_RE = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
7
+ const JSON_SECRET_RE =
8
+ /(["']?(?:token|password|passwd|secret|api[_-]?key|authorization|credential)["']?\s*:\s*)(["'])[^"']*\2/gi;
9
+ const UNQUOTED_SECRET_RE =
10
+ /(["']?(?:token|password|passwd|secret|api[_-]?key|authorization|credential)["']?\s*:\s*)[^\s,}\]]+/gi;
11
+
12
+ function stripControlCharacters(value: string): string {
13
+ return Array.from(value, (character) => {
14
+ const code = character.codePointAt(0) ?? 0;
15
+ return code < 32 || (code >= 127 && code <= 159) ? " " : character;
16
+ }).join("");
17
+ }
18
+
19
+ /** Redact, normalize, and bound provider-owned error text before session persistence. */
20
+ export function sanitizeChildErrorText(value: unknown): string | undefined {
21
+ if (typeof value !== "string" || !value.trim()) return undefined;
22
+ const redacted = redactDebugData(value)
23
+ .replace(JSON_SECRET_RE, (_match, prefix: string, quote: string) => {
24
+ return `${prefix}${quote}[REDACTED]${quote}`;
25
+ })
26
+ .replace(UNQUOTED_SECRET_RE, (_match, prefix: string) => `${prefix}[REDACTED]`);
27
+ const normalized = stripControlCharacters(redacted.replace(ANSI_ESCAPE_RE, " "))
28
+ .replace(/\s+/g, " ")
29
+ .trim();
30
+ if (!normalized) return undefined;
31
+ if (normalized.length <= MAX_CHILD_ERROR_CHARACTERS) return normalized;
32
+ let end = MAX_CHILD_ERROR_CHARACTERS - 1;
33
+ if (/[\uD800-\uDBFF]/.test(normalized[end - 1] ?? "")) end--;
34
+ return `${normalized.slice(0, end)}…`;
35
+ }
@@ -13,6 +13,32 @@ export interface TextPage {
13
13
  totalCharacters: number;
14
14
  }
15
15
 
16
+ /** One selected 1-based line range before character paging is applied. */
17
+ export interface LineSelection {
18
+ text: string;
19
+ startLine: number;
20
+ endLine: number;
21
+ totalLines: number;
22
+ }
23
+
24
+ /** Select a bounded 1-based line range from file text. */
25
+ export function selectLineRange(text: string, startLine: number, lineCount = 200): LineSelection {
26
+ const lines = text.split("\n");
27
+ if (!Number.isSafeInteger(startLine) || startLine < 1 || startLine > lines.length) {
28
+ throw new Error(`Start line must be an integer between 1 and ${lines.length}.`);
29
+ }
30
+ if (!Number.isSafeInteger(lineCount) || lineCount < 1 || lineCount > MAX_PAGE_LINES) {
31
+ throw new Error(`Line count must be an integer between 1 and ${MAX_PAGE_LINES}.`);
32
+ }
33
+ const endLine = Math.min(lines.length, startLine + lineCount - 1);
34
+ return {
35
+ text: lines.slice(startLine - 1, endLine).join("\n"),
36
+ startLine,
37
+ endLine,
38
+ totalLines: lines.length,
39
+ };
40
+ }
41
+
16
42
  function lineBoundedEnd(text: string, start: number, proposedEnd: number): number {
17
43
  let lines = 1;
18
44
  for (let index = start; index < proposedEnd; index++) {