@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,12 @@
1
1
  import { resolveReviewSnapshot, summarizeReviewSnapshot } from "../git.ts";
2
+ import { normalizeReviewInput } from "../review-input.ts";
2
3
  import { normalizeReviewSubmission } from "../review-result.ts";
3
- import type { ReviewPlanStore } from "../session/review-plan-store.ts";
4
+ import type { ReviewPlanLease, ReviewPlanStore } from "../session/review-plan-store.ts";
5
+ import { buildFileManifest } from "../target/file-manifest.ts";
4
6
  import { buildReviewPacket } from "../target/packet.ts";
5
7
  import type {
6
8
  PlannerDraft,
9
+ PlannerRunResult,
7
10
  PlanningRecord,
8
11
  ReviewBatchDetails,
9
12
  ReviewInput,
@@ -12,7 +15,11 @@ import type {
12
15
  ReviewTargetSpec,
13
16
  ReviewTaskResult,
14
17
  } from "../types.ts";
15
- import { createUnobservedChildFailureDiagnostics } from "./child-failure-diagnostics.ts";
18
+ import {
19
+ createEarlyCancellationDiagnostics,
20
+ createUnobservedChildFailureDiagnostics,
21
+ } from "./child-failure-diagnostics.ts";
22
+ import { combineUsage } from "./child-usage.ts";
16
23
  import { PLANNER_PROMPT_VERSION, runPlanner } from "./planner-runner.ts";
17
24
  import { runReviewer } from "./review-runner.ts";
18
25
 
@@ -60,97 +67,114 @@ export interface PreparedRunInput {
60
67
  /** Discriminated union accepted by `runReview` for both Direct and Prepared paths. */
61
68
  export type RunReviewInput = DirectRunInput | PreparedRunInput;
62
69
 
63
- const MAX_PLANNER_FILE_COUNT = 200;
64
- const MAX_PLANNER_FILE_CHARS = 8_000;
65
-
66
- /** Canonicalize and semantically validate review input for every adapter. */
67
- export function normalizeReviewInput(review: ReviewInput): ReviewInput {
68
- const sharedContext = review.sharedContext?.trim();
69
- const tasks = review.tasks.map((task) => ({
70
- id: task.id.trim(),
71
- instructions: task.instructions.trim(),
72
- }));
73
- if (tasks.length < 1 || tasks.length > 4)
74
- throw new Error("Provide between one and four review tasks.");
75
- if (tasks.some((task) => !task.id || !task.instructions)) {
76
- throw new Error("Review task ids and instructions must not be blank.");
77
- }
78
- if (tasks.some((task) => task.id.length > 64)) {
79
- throw new Error("Review task ids must not exceed 64 characters.");
80
- }
81
- if (new Set(tasks.map((task) => task.id)).size !== tasks.length) {
82
- throw new Error("Review task ids must be unique.");
83
- }
84
- return { ...(sharedContext ? { sharedContext } : {}), tasks };
85
- }
86
-
87
- function plannerFileManifest(files: string[]): string[] {
88
- const lines: string[] = [];
89
- let size = 0;
90
- for (const file of files) {
91
- const line = `- ${JSON.stringify(file)}`;
92
- if (
93
- lines.length >= MAX_PLANNER_FILE_COUNT ||
94
- size + line.length + 1 > MAX_PLANNER_FILE_CHARS - 100
95
- ) {
96
- break;
97
- }
98
- lines.push(line);
99
- size += line.length + 1;
100
- }
101
- const omitted = files.length - lines.length;
102
- if (omitted > 0) lines.push(`- … ${omitted} additional file(s) omitted`);
103
- return lines;
104
- }
105
-
106
70
  function plannerPrompt(snapshot: ReviewSnapshot, context: string): string {
107
71
  return [
108
72
  "# Review Planning Input",
109
73
  "",
110
74
  `Target: ${snapshot.title}`,
111
- `Changed files: ${snapshot.changedFiles.length}`,
75
+ `Changed files: ${snapshot.changes.length}`,
112
76
  `Diff stats: +${snapshot.stats.additions} / -${snapshot.stats.deletions}`,
113
77
  "",
114
- "## Changed file names",
115
- ...plannerFileManifest(snapshot.changedFiles),
78
+ "## Changed-path inventory",
79
+ ...buildFileManifest(snapshot.changes),
116
80
  "",
117
81
  "## Bounded session conversation",
118
82
  context || "No session conversation was available.",
119
83
  ].join("\n");
120
84
  }
121
85
 
122
- /** Resolve and store a one-shot plan, optionally asking the advisory Planner for tasks. */
123
- export async function prepareReview(input: PrepareReviewInput) {
86
+ /** Translate a resolveReviewSnapshot error to a no-target reason. */
87
+ function snapshotErrorReason(error: unknown): string {
88
+ if (error instanceof Error) return error.message;
89
+ return "No reviewable changes found.";
90
+ }
91
+
92
+ interface PlannerPreparation {
93
+ draft?: PlannerDraft;
94
+ failure?: Exclude<PlannerRunResult, { kind: "success" }>;
95
+ canceled?: Extract<PlannerRunResult, { kind: "canceled" }>;
96
+ usage?: PlannerRunResult["usage"];
97
+ modelId?: string;
98
+ promptVersion?: string;
99
+ }
100
+
101
+ async function preparePlanner(
102
+ input: PrepareReviewInput,
103
+ snapshot: ReviewSnapshot,
104
+ ): Promise<PlannerPreparation> {
105
+ if (input.planning === "none") return {};
106
+ if (!input.plannerModel) {
107
+ return { failure: { kind: "failed", failureCode: "session-creation-failed" } };
108
+ }
124
109
  input.onUpdate?.({
125
- content: [{ type: "text", text: "Resolving target…" }],
110
+ content: [{ type: "text", text: "Running planner…" }],
126
111
  details: {},
127
112
  });
128
- const snapshot = await resolveReviewSnapshot(input.cwd, input.target);
129
- if (!snapshot) return { kind: "no-target" as const, reason: "No reviewable changes found." };
130
- let plannerDraft: PlannerDraft | undefined;
131
- if (input.planning === "suggest") {
132
- if (!input.plannerModel) throw new Error("A configured Planner model is required.");
133
- input.onUpdate?.({
134
- content: [{ type: "text", text: "Running planner…" }],
135
- details: {},
136
- });
137
- const result = await runPlanner({
138
- cwd: input.cwd,
113
+ const modelId = input.plannerModel.canonicalId;
114
+ const promptVersion = PLANNER_PROMPT_VERSION;
115
+ let result: PlannerRunResult;
116
+ try {
117
+ result = await runPlanner({
118
+ cwd: snapshot.repositoryRoot,
139
119
  model: input.plannerModel.model,
140
120
  prompt: plannerPrompt(snapshot, input.plannerContext),
141
121
  signal: input.signal,
142
122
  });
143
- if (result.kind !== "success") return { kind: "planner-failed" as const, result };
144
- plannerDraft = normalizeReviewInput(result.draft);
123
+ } catch {
124
+ if (input.signal?.aborted) {
125
+ return {
126
+ canceled: { kind: "canceled", diagnostics: createEarlyCancellationDiagnostics() },
127
+ modelId,
128
+ promptVersion,
129
+ };
130
+ }
131
+ return {
132
+ failure: {
133
+ kind: "failed",
134
+ failureCode: "unexpected-runner-failure",
135
+ diagnostics: createUnobservedChildFailureDiagnostics(),
136
+ },
137
+ modelId,
138
+ promptVersion,
139
+ };
140
+ }
141
+ const identity = {
142
+ ...(result.usage ? { usage: result.usage } : {}),
143
+ modelId,
144
+ promptVersion,
145
+ };
146
+ if (result.kind === "canceled") return { canceled: result, ...identity };
147
+ if (result.kind === "success") {
148
+ return { draft: normalizeReviewInput(result.draft), ...identity };
149
+ }
150
+ return { failure: result, ...identity };
151
+ }
152
+
153
+ /** Resolve and store a one-shot plan, optionally asking the advisory Planner for tasks. */
154
+ export async function prepareReview(input: PrepareReviewInput) {
155
+ input.onUpdate?.({
156
+ content: [{ type: "text", text: "Resolving target…" }],
157
+ details: {},
158
+ });
159
+ let snapshot: Awaited<ReturnType<typeof resolveReviewSnapshot>>;
160
+ try {
161
+ snapshot = await resolveReviewSnapshot(input.cwd, input.target);
162
+ } catch (error) {
163
+ return { kind: "no-target" as const, reason: snapshotErrorReason(error) };
145
164
  }
165
+ if (!snapshot) return { kind: "no-target" as const, reason: "No reviewable changes found." };
166
+ const planning = await preparePlanner(input, snapshot);
167
+ if (planning.canceled) return { kind: "canceled" as const, result: planning.canceled };
146
168
  const plan = input.planStore.create({
147
169
  snapshot,
148
170
  reviewerModel: input.reviewerModel,
149
- ...(plannerDraft ? { plannerDraft } : {}),
150
- ...(input.plannerModel ? { plannerModelId: input.plannerModel.canonicalId } : {}),
151
- ...(plannerDraft ? { plannerPromptVersion: PLANNER_PROMPT_VERSION } : {}),
171
+ ...(planning.draft ? { plannerDraft: planning.draft } : {}),
172
+ ...(planning.failure ? { plannerFailure: planning.failure } : {}),
173
+ ...(planning.usage ? { plannerUsage: planning.usage } : {}),
174
+ ...(planning.modelId ? { plannerModelId: planning.modelId } : {}),
175
+ ...(planning.promptVersion ? { plannerPromptVersion: planning.promptVersion } : {}),
152
176
  });
153
- return { kind: "prepared" as const, plan };
177
+ return { kind: "prepared" as const, plan, ...(planning.usage ? { usage: planning.usage } : {}) };
154
178
  }
155
179
 
156
180
  function toTaskResult(
@@ -158,7 +182,12 @@ function toTaskResult(
158
182
  packetHash: string,
159
183
  result: Awaited<ReturnType<typeof runReviewer>>,
160
184
  ): ReviewTaskResult {
161
- const identity = { taskId, packetHash, modelId: result.modelId };
185
+ const identity = {
186
+ taskId,
187
+ packetHash,
188
+ modelId: result.modelId,
189
+ ...(result.usage ? { usage: result.usage } : {}),
190
+ };
162
191
  if (result.kind === "success") {
163
192
  const normalized = normalizeReviewSubmission(result.submission);
164
193
  return {
@@ -188,6 +217,14 @@ function toTaskResult(
188
217
  };
189
218
  }
190
219
 
220
+ function emitUpdate(onUpdate: OnUpdate | undefined, result: Parameters<OnUpdate>[0]): void {
221
+ try {
222
+ onUpdate?.(result);
223
+ } catch {
224
+ // Progress presentation cannot change review execution semantics.
225
+ }
226
+ }
227
+
191
228
  // biome-ignore lint/complexity/useMaxParams: compact internal fan-out helper
192
229
  async function execute(
193
230
  cwd: string,
@@ -212,11 +249,21 @@ async function execute(
212
249
  prompt: packet.prompt,
213
250
  model,
214
251
  signal,
252
+ onProgress: (progress) =>
253
+ emitUpdate(onUpdate, {
254
+ content: [
255
+ {
256
+ type: "text",
257
+ text: `Task ${task.id}: ${progress.turns} turns, ${progress.toolUses} tool uses${progress.tokens ? `, ${progress.tokens.total} tokens` : ""}`,
258
+ },
259
+ ],
260
+ details: { taskId: task.id, progress, completedCount, totalCount },
261
+ }),
215
262
  });
216
263
  const taskResult = toTaskResult(task.id, packet.packetHash, result);
217
264
  completedCount++;
218
265
  const verb = taskResult.status === "completed" ? "complete" : taskResult.status;
219
- onUpdate?.({
266
+ emitUpdate(onUpdate, {
220
267
  content: [
221
268
  { type: "text", text: `Task ${task.id} ${verb} (${completedCount} of ${totalCount})` },
222
269
  ],
@@ -233,7 +280,7 @@ async function execute(
233
280
  diagnostics: createUnobservedChildFailureDiagnostics(),
234
281
  };
235
282
  completedCount++;
236
- onUpdate?.({
283
+ emitUpdate(onUpdate, {
237
284
  content: [
238
285
  {
239
286
  type: "text",
@@ -255,20 +302,26 @@ export async function runReview(input: RunReviewInput) {
255
302
  let review: ReviewInput;
256
303
  let model: ReviewModelSelection;
257
304
  let planning: PlanningRecord | undefined;
305
+ let lease: ReviewPlanLease | undefined;
258
306
  let provenance: ReviewBatchDetails["provenance"] = "caller-supplied";
259
307
 
260
308
  if (input.mode === "direct") {
261
- const resolved = await resolveReviewSnapshot(input.cwd, input.target);
309
+ let resolved: Awaited<ReturnType<typeof resolveReviewSnapshot>>;
310
+ try {
311
+ resolved = await resolveReviewSnapshot(input.cwd, input.target);
312
+ } catch (error) {
313
+ return { kind: "no-target" as const, reason: snapshotErrorReason(error) };
314
+ }
262
315
  if (!resolved) return { kind: "no-target" as const, reason: "No reviewable changes found." };
263
316
  snapshot = resolved;
264
317
  review = normalizeReviewInput(input.review);
265
318
  model = input.reviewerModel;
266
319
  } else {
267
- const plan = input.planStore.take(input.planId);
320
+ const plan = input.planStore.peek(input.planId);
268
321
  if (!plan) {
269
322
  return {
270
323
  kind: "invalid" as const,
271
- reason: `Review Plan ${input.planId} was not found or was already consumed.`,
324
+ reason: `Review Plan ${input.planId} was not found, is already running, or was consumed.`,
272
325
  };
273
326
  }
274
327
  if (input.decision.kind === "accept-draft" && !plan.plannerDraft) {
@@ -281,21 +334,47 @@ export async function runReview(input: RunReviewInput) {
281
334
  if (!selectedReview) {
282
335
  return { kind: "invalid" as const, reason: "This plan has no Planner Draft." };
283
336
  }
284
- snapshot = plan.snapshot;
337
+ lease = input.planStore.acquire(input.planId);
338
+ if (!lease) {
339
+ return {
340
+ kind: "invalid" as const,
341
+ reason: `Review Plan ${input.planId} is already running.`,
342
+ };
343
+ }
344
+ snapshot = lease.plan.snapshot;
285
345
  review = selectedReview;
286
- model = plan.reviewerModel;
287
- if (plan.plannerDraft) provenance = "planner-assisted";
288
- if (plan.plannerDraft && plan.plannerModelId && plan.plannerPromptVersion) {
346
+ model = lease.plan.reviewerModel;
347
+ provenance = input.decision.kind === "accept-draft" ? "planner-assisted" : "caller-supplied";
348
+ if (lease.plan.plannerDraft && lease.plan.plannerModelId && lease.plan.plannerPromptVersion) {
289
349
  planning = {
290
- promptVersion: plan.plannerPromptVersion,
291
- modelId: plan.plannerModelId,
292
- draft: plan.plannerDraft,
350
+ promptVersion: lease.plan.plannerPromptVersion,
351
+ modelId: lease.plan.plannerModelId,
352
+ ...(lease.plan.plannerUsage ? { usage: lease.plan.plannerUsage } : {}),
353
+ draft: lease.plan.plannerDraft,
293
354
  effectiveReview: review,
294
355
  decision: input.decision.kind,
295
356
  };
296
357
  }
297
358
  }
298
359
 
360
+ let results: ReviewTaskResult[];
361
+ try {
362
+ results = await execute(
363
+ snapshot.repositoryRoot,
364
+ snapshot,
365
+ review,
366
+ model,
367
+ input.signal,
368
+ input.onUpdate,
369
+ );
370
+ } catch (error) {
371
+ if (lease && input.mode === "prepared") input.planStore.release(lease);
372
+ throw error;
373
+ }
374
+ if (lease && input.mode === "prepared") {
375
+ if (results.some((result) => result.status === "completed")) input.planStore.consume(lease);
376
+ else input.planStore.release(lease);
377
+ }
299
378
  const details: ReviewBatchDetails = {
300
379
  kind: "review-batch",
301
380
  mode: input.mode,
@@ -303,7 +382,8 @@ export async function runReview(input: RunReviewInput) {
303
382
  snapshot: summarizeReviewSnapshot(snapshot),
304
383
  review,
305
384
  ...(planning ? { planning } : {}),
306
- results: await execute(input.cwd, snapshot, review, model, input.signal, input.onUpdate),
385
+ results,
307
386
  };
308
- return { kind: "completed" as const, details };
387
+ const usage = combineUsage(results.map((result) => result.usage));
388
+ return { kind: "completed" as const, details, ...(usage ? { usage } : {}) };
309
389
  }
@@ -1,16 +1,18 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
2
  import { Type } from "typebox";
3
+ import { REVIEW_LIMITS } from "../review-limits.ts";
3
4
 
4
5
  /** TypeBox schema for one caller-defined review task (provider-visible). */
5
6
  export const reviewTaskSchema = Type.Object(
6
7
  {
7
8
  id: Type.String({
8
9
  minLength: 1,
9
- maxLength: 64,
10
+ maxLength: REVIEW_LIMITS.taskIdCharacters,
10
11
  description: "Stable caller-defined task id, such as standards or spec.",
11
12
  }),
12
13
  instructions: Type.String({
13
14
  minLength: 1,
15
+ maxLength: REVIEW_LIMITS.taskInstructionCharacters,
14
16
  description: "Complete freeform methodology and acceptance instructions for this task.",
15
17
  }),
16
18
  },
@@ -21,7 +23,10 @@ export const reviewTaskSchema = Type.Object(
21
23
  export const reviewInputSchema = Type.Object(
22
24
  {
23
25
  sharedContext: Type.Optional(
24
- Type.String({ description: "Optional context shared unchanged with every task." }),
26
+ Type.String({
27
+ maxLength: REVIEW_LIMITS.sharedContextCharacters,
28
+ description: "Optional context shared unchanged with every task.",
29
+ }),
25
30
  ),
26
31
  tasks: Type.Array(reviewTaskSchema, {
27
32
  minItems: 1,
@@ -35,9 +40,14 @@ export const reviewInputSchema = Type.Object(
35
40
  /** TypeBox schema for a single structured finding (provider-visible). */
36
41
  export const reviewFindingSchema = Type.Object(
37
42
  {
38
- title: Type.String({ minLength: 1, description: "Concise finding title." }),
43
+ title: Type.String({
44
+ minLength: 1,
45
+ maxLength: REVIEW_LIMITS.findingTitleCharacters,
46
+ description: "Concise finding title.",
47
+ }),
39
48
  description: Type.String({
40
49
  minLength: 1,
50
+ maxLength: REVIEW_LIMITS.findingDescriptionCharacters,
41
51
  description: "Concrete evidence-backed explanation of the issue.",
42
52
  }),
43
53
  blocksAcceptance: Type.Boolean({
@@ -57,7 +67,11 @@ export const reviewFindingSchema = Type.Object(
57
67
  location: Type.Optional(
58
68
  Type.Object(
59
69
  {
60
- path: Type.String({ minLength: 1, description: "Repository-relative target path." }),
70
+ path: Type.String({
71
+ minLength: 1,
72
+ maxLength: REVIEW_LIMITS.locationPathCharacters,
73
+ description: "Repository-relative target path.",
74
+ }),
61
75
  startLine: Type.Integer({ minimum: 1 }),
62
76
  endLine: Type.Integer({ minimum: 1 }),
63
77
  },
@@ -71,8 +85,13 @@ export const reviewFindingSchema = Type.Object(
71
85
  /** TypeBox schema for the submit_review tool parameters (provider-visible). */
72
86
  export const reviewSubmissionSchema = Type.Object(
73
87
  {
74
- summary: Type.String({ minLength: 1, description: "Task-level review summary." }),
88
+ summary: Type.String({
89
+ minLength: 1,
90
+ maxLength: REVIEW_LIMITS.summaryCharacters,
91
+ description: "Task-level review summary.",
92
+ }),
75
93
  findings: Type.Array(reviewFindingSchema, {
94
+ maxItems: REVIEW_LIMITS.findingsPerTask,
76
95
  description: "Findings in the reviewer's intended order; use an empty array when none exist.",
77
96
  }),
78
97
  },
@@ -1,3 +1,4 @@
1
+ import type { Usage } from "@earendil-works/pi-ai";
1
2
  import type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
2
3
  import type { ChildFailureCode, ChildFailureDiagnostics, ReviewProgress } from "../types.ts";
3
4
  import { buildChildFailureDiagnostics } from "./child-failure-diagnostics.ts";
@@ -7,6 +8,10 @@ import {
7
8
  ChildLifecycleTraceCollector,
8
9
  getRegisteredToolNames,
9
10
  } from "./child-lifecycle-trace.ts";
11
+ import { collectChildUsage } from "./child-usage.ts";
12
+
13
+ /** Maximum time cancellation waits for a provider abort before host cleanup continues. */
14
+ export const CHILD_ABORT_GRACE_MS = 2_000;
10
15
 
11
16
  /**
12
17
  * Context passed to event handlers, timeout callbacks, and result factories.
@@ -33,15 +38,10 @@ export interface LifecycleCtx<TResult> {
33
38
  getLifecycleTrace: () => ChildLifecycleTrace;
34
39
  /** Build a safe non-success diagnostic artifact from the observed child run. */
35
40
  getFailureDiagnostics: () => ChildFailureDiagnostics;
41
+ /** Aggregate nested-model usage observed in the child transcript. */
42
+ getUsage: () => Usage | undefined;
36
43
  /** Add one allowlisted runner-control marker to the Child Lifecycle Trace. */
37
44
  recordHostMarker: (marker: ChildLifecycleHostMarker) => void;
38
- /**
39
- * Register a teardown function that runs when cleanup is called.
40
- * Useful for custom timers or resources set up by `onTimeout`.
41
- */
42
- addTeardown: (fn: () => void) => void;
43
- /** Timestamp (ms) when the lifecycle started, for elapsed-time display. */
44
- startTime: number;
45
45
  }
46
46
 
47
47
  /** Configuration for `runWithLifecycle`. */
@@ -52,20 +52,13 @@ export interface RunWithLifecycleConfig<TResult> {
52
52
  prompt: string;
53
53
  /** Optional abort signal. */
54
54
  signal?: AbortSignal;
55
- /** Timeout in milliseconds before the session is aborted. */
56
- timeoutMs: number;
55
+ /** Optional timeout in milliseconds before the session is aborted. */
56
+ timeoutMs?: number;
57
57
  /**
58
58
  * Event handler. Receives each session event and the lifecycle context.
59
59
  * Call `ctx.resolve(ctx.cleanup(result))` to settle the promise.
60
60
  */
61
61
  onEvent: (event: AgentSessionEvent, ctx: LifecycleCtx<TResult>) => void;
62
- /**
63
- * Custom timeout behavior. When omitted, the session is hard-aborted
64
- * and resolved with `timeoutResult`. When provided, the callback can
65
- * steer the session and schedule a hard abort, registering cleanup
66
- * via `ctx.addTeardown`.
67
- */
68
- onTimeout?: (ctx: LifecycleCtx<TResult>) => void;
69
62
  /** Factory for the result produced when the abort signal fires. */
70
63
  canceledResult: (ctx: LifecycleCtx<TResult>) => TResult;
71
64
  /** Factory for the result produced when prompt preflight or execution fails. */
@@ -100,14 +93,12 @@ function startPrompt(options: StartPromptOptions): void {
100
93
  /**
101
94
  * Manages the lifecycle of a child agent session: subscribes to events,
102
95
  * wires abort-signal handling, enforces a timeout, and provides idempotent
103
- * cleanup. The caller supplies an event handler and optional custom timeout
104
- * behavior via `onTimeout`.
96
+ * cleanup. The caller supplies the structured event/result mapping.
105
97
  *
106
98
  * The returned promise resolves when:
107
99
  * - The event handler calls `ctx.resolve(ctx.cleanup(result))`
108
100
  * - The abort signal fires (resolves via `canceledResult(ctx)`)
109
- * - The timeout expires (resolves via `timeoutResult`, or `onTimeout` handles
110
- * it by calling `ctx.resolve(ctx.cleanup(...))` itself)
101
+ * - The optional timeout expires and resolves via `timeoutResult`
111
102
  * - `session.prompt()` rejects (resolves via `failedResult`)
112
103
  */
113
104
  // biome-ignore lint/complexity/noExcessiveLinesPerFunction: lifecycle ownership must remain in one state-machine closure
@@ -120,7 +111,6 @@ export function runWithLifecycle<TResult>(
120
111
  signal,
121
112
  timeoutMs,
122
113
  onEvent,
123
- onTimeout,
124
114
  canceledResult,
125
115
  failedResult,
126
116
  timeoutResult,
@@ -157,12 +147,14 @@ export function runWithLifecycle<TResult>(
157
147
  if (state.settled) return result;
158
148
  state.settled = true;
159
149
  cancelTeardown();
160
- session.dispose();
150
+ try {
151
+ session.dispose();
152
+ } catch {
153
+ // Disposal is best-effort after the outcome is already determined.
154
+ }
161
155
  return result;
162
156
  };
163
157
 
164
- const startTime = Date.now();
165
-
166
158
  return new Promise<TResult>((resolve) => {
167
159
  const ctx: LifecycleCtx<TResult> = {
168
160
  resolve,
@@ -178,9 +170,8 @@ export function runWithLifecycle<TResult>(
178
170
  lifecycleTrace: lifecycleTrace.snapshot(),
179
171
  recentActivity: lifecycleTrace.recentActivitySnapshot(),
180
172
  }),
173
+ getUsage: () => collectChildUsage(session),
181
174
  recordHostMarker: (marker) => lifecycleTrace.recordHostMarker(marker),
182
- addTeardown,
183
- startTime,
184
175
  };
185
176
 
186
177
  let promptSettled = false;
@@ -203,7 +194,7 @@ export function runWithLifecycle<TResult>(
203
194
  dispatchEvent(event);
204
195
  };
205
196
 
206
- session.subscribe((event: AgentSessionEvent) => {
197
+ const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
207
198
  lifecycleTrace.observe(event);
208
199
  if (event.type === "agent_settled" && !promptSettled) {
209
200
  deferredAgentSettled = event;
@@ -211,18 +202,29 @@ export function runWithLifecycle<TResult>(
211
202
  }
212
203
  dispatchEvent(event);
213
204
  });
205
+ if (typeof unsubscribe === "function") addTeardown(unsubscribe);
206
+
207
+ const finishAfterAbort = (result: () => TResult): void => {
208
+ let graceId: ReturnType<typeof setTimeout> | undefined;
209
+ const grace = new Promise<void>((resolveGrace) => {
210
+ graceId = setTimeout(resolveGrace, CHILD_ABORT_GRACE_MS);
211
+ graceId.unref?.();
212
+ });
213
+ const abort = Promise.resolve()
214
+ .then(() => session.abort())
215
+ .catch(() => undefined);
216
+ void Promise.race([abort, grace]).finally(() => {
217
+ if (graceId) clearTimeout(graceId);
218
+ resolve(cleanup(result()));
219
+ });
220
+ };
214
221
 
215
222
  // Abort signal handler
216
223
  const onAbort = () => {
217
224
  if (state.settled || state.aborting) return;
218
225
  state.aborting = true;
219
226
  ctx.recordHostMarker({ type: "abort_requested", reason: "canceled" });
220
- void session
221
- .abort()
222
- .catch(() => {})
223
- .finally(() => {
224
- resolve(cleanup(canceledResult(ctx)));
225
- });
227
+ finishAfterAbort(() => canceledResult(ctx));
226
228
  };
227
229
  if (signal) {
228
230
  signal.addEventListener("abort", onAbort, { once: true });
@@ -235,30 +237,18 @@ export function runWithLifecycle<TResult>(
235
237
 
236
238
  // Timeout handler
237
239
  const onTimeoutExpired = () => {
238
- if (state.settled || state.aborting) return;
240
+ if (timeoutMs === undefined || state.settled || state.aborting) return;
239
241
  ctx.recordHostMarker({ type: "timeout_expired" });
240
242
 
241
- if (onTimeout) {
242
- try {
243
- onTimeout(ctx);
244
- } catch {
245
- resolve(cleanup(failedResult("unexpected-runner-failure", ctx)));
246
- }
247
- } else {
248
- // Default: hard abort
249
- state.aborting = true;
250
- ctx.recordHostMarker({ type: "abort_requested", reason: "timeout" });
251
- void session
252
- .abort()
253
- .catch(() => {})
254
- .finally(() => {
255
- resolve(cleanup(timeoutResult(timeoutMs, ctx)));
256
- });
257
- }
243
+ state.aborting = true;
244
+ ctx.recordHostMarker({ type: "abort_requested", reason: "timeout" });
245
+ finishAfterAbort(() => timeoutResult(timeoutMs, ctx));
258
246
  };
259
- const timeoutId = setTimeout(onTimeoutExpired, timeoutMs);
260
- timeoutId.unref?.();
261
- addTeardown(() => clearTimeout(timeoutId));
247
+ if (timeoutMs !== undefined) {
248
+ const timeoutId = setTimeout(onTimeoutExpired, timeoutMs);
249
+ timeoutId.unref?.();
250
+ addTeardown(() => clearTimeout(timeoutId));
251
+ }
262
252
 
263
253
  // Start the session. Prompt rejection is a distinct host-owned outcome;
264
254
  // caught provider or runner errors are intentionally never retained.
@@ -0,0 +1,15 @@
1
+ import type { Usage } from "@earendil-works/pi-ai";
2
+
3
+ /** Format nested-model usage consistently across Markdown and TUI surfaces. */
4
+ export function formatReviewUsage(usage: Usage): string {
5
+ const tokens = `${usage.totalTokens.toLocaleString("en-US")} tokens`;
6
+ const parts = [
7
+ tokens,
8
+ `${usage.input.toLocaleString("en-US")} in`,
9
+ `${usage.output.toLocaleString("en-US")} out`,
10
+ ];
11
+ if (usage.cacheRead > 0) parts.push(`${usage.cacheRead.toLocaleString("en-US")} cache read`);
12
+ if (usage.cacheWrite > 0) parts.push(`${usage.cacheWrite.toLocaleString("en-US")} cache write`);
13
+ if (usage.cost.total > 0) parts.push(`$${usage.cost.total.toFixed(4)}`);
14
+ return parts.join(" · ");
15
+ }