pi-spine 2.32.0 → 2.33.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/bin/spine-plan.mjs +15 -5
- package/bin/spine-worker-runner.mjs +182 -15
- package/package.json +1 -1
- package/src/batch/engine-lanes/matrix-run.mjs +69 -9
- package/src/batch/engine-lanes/queue.mjs +54 -1
- package/src/batch/engine-lanes/review-plan.mjs +111 -48
- package/src/batch/engine-lanes/review-poll.mjs +6 -0
- package/src/batch/metrics.mjs +15 -0
- package/src/batch/pi-json-usage.mjs +262 -0
- package/src/batch/reconcile-classify.mjs +146 -164
- package/src/batch/review-spawn.mjs +48 -2
- package/src/batch/review-step.mjs +5 -0
- package/src/batch/worker-host.mjs +18 -18
|
@@ -35,20 +35,47 @@ import {
|
|
|
35
35
|
* Step number containing a plan review checkpoint marker, else the lowest step.
|
|
36
36
|
* Local mirror of findCodeReviewStepNumber for the engine plan phase (SP-695).
|
|
37
37
|
*
|
|
38
|
+
* SP-874 / #294: this is the LAST step of {@link findPlanReviewStepOrder} —
|
|
39
|
+
* the checkpoint (or fallback) step the phase reviews after the step-0
|
|
40
|
+
* (minimum-step) review has run and approved.
|
|
41
|
+
*
|
|
38
42
|
* @param {string} taskFolder
|
|
39
43
|
*/
|
|
40
44
|
function findPlanReviewStepNumber(taskFolder) {
|
|
45
|
+
return findPlanReviewStepOrder(taskFolder).at(-1) ?? 0;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Ordered plan-review steps for the engine phase (SP-874 / #294): the minimum
|
|
50
|
+
* step (step 0) first, then any explicit plan-review checkpoint step. A packet
|
|
51
|
+
* that declares a plan-review checkpoint at a later step must not silently
|
|
52
|
+
* drop the required step-0 plan review — step 0 is queued before the later
|
|
53
|
+
* checkpoint review so no later-step plan review runs while step 0 is
|
|
54
|
+
* unreviewed (#294 Expected item 1).
|
|
55
|
+
*
|
|
56
|
+
* - No PROMPT.md or no `### Step N` blocks → `[0]`.
|
|
57
|
+
* - No plan-review checkpoint marker → `[minStep]` (unchanged SP-695 fallback).
|
|
58
|
+
* - Checkpoint at C: `C > min` → `[min, C]`; `C <= min` → `[C]` (unchanged).
|
|
59
|
+
*
|
|
60
|
+
* @param {string} taskFolder
|
|
61
|
+
* @returns {number[]}
|
|
62
|
+
*/
|
|
63
|
+
export function findPlanReviewStepOrder(taskFolder) {
|
|
41
64
|
const promptPath = path.join(taskFolder, "PROMPT.md");
|
|
42
|
-
if (!fs.existsSync(promptPath)) return 0;
|
|
65
|
+
if (!fs.existsSync(promptPath)) return [0];
|
|
43
66
|
const content = fs.readFileSync(promptPath, "utf-8");
|
|
44
67
|
const stepBlocks = [...content.matchAll(/###\s+Step\s+(\d+)[:\s][\s\S]*?(?=###\s+Step\s+\d+|$)/g)];
|
|
68
|
+
if (stepBlocks.length === 0) return [0];
|
|
69
|
+
const minStep = Math.min(...stepBlocks.map((match) => Number(match[1])));
|
|
70
|
+
let checkpointStep = null;
|
|
45
71
|
for (const match of stepBlocks) {
|
|
46
72
|
if (/plan[-\s]review\s+checkpoint/i.test(match[0])) {
|
|
47
|
-
|
|
73
|
+
checkpointStep = Number(match[1]);
|
|
74
|
+
break;
|
|
48
75
|
}
|
|
49
76
|
}
|
|
50
|
-
if (
|
|
51
|
-
return
|
|
77
|
+
if (checkpointStep == null) return [minStep];
|
|
78
|
+
return checkpointStep > minStep ? [minStep, checkpointStep] : [checkpointStep];
|
|
52
79
|
}
|
|
53
80
|
|
|
54
81
|
/**
|
|
@@ -60,6 +87,7 @@ function findPlanReviewStepNumber(taskFolder) {
|
|
|
60
87
|
* @param {string} params.taskFolder
|
|
61
88
|
* @param {Array<Record<string, any>>} [params.journalEvents]
|
|
62
89
|
* @param {string} [params.taskId]
|
|
90
|
+
* @param {number} [params.stepNumber] Restrict the scan to this step's verdict (SP-874 / #294 ordering).
|
|
63
91
|
* @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
|
|
64
92
|
* @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
|
|
65
93
|
* @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
|
|
@@ -69,6 +97,7 @@ function findCompletedPlanReview({
|
|
|
69
97
|
taskFolder,
|
|
70
98
|
journalEvents = [],
|
|
71
99
|
taskId,
|
|
100
|
+
stepNumber,
|
|
72
101
|
worktreePath,
|
|
73
102
|
stubMode,
|
|
74
103
|
onReject,
|
|
@@ -81,6 +110,11 @@ function findCompletedPlanReview({
|
|
|
81
110
|
if (event.type !== "review.completed") continue;
|
|
82
111
|
const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
|
|
83
112
|
if (payload.reviewType !== "plan") continue;
|
|
113
|
+
// SP-874 / #294 ordering: a later-step plan verdict must not satisfy an
|
|
114
|
+
// earlier step's gate — events that declare a step must match the scan's
|
|
115
|
+
// step exactly. Legacy events without a stepNumber cannot claim a later
|
|
116
|
+
// step and stay honorable for the phase's target step.
|
|
117
|
+
if (stepNumber != null && payload.stepNumber != null && payload.stepNumber !== stepNumber) continue;
|
|
84
118
|
const verdict = normalizeCodeVerdict(payload.verdict);
|
|
85
119
|
if (!verdict) continue;
|
|
86
120
|
const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
|
|
@@ -104,8 +138,8 @@ function findCompletedPlanReview({
|
|
|
104
138
|
return result;
|
|
105
139
|
}
|
|
106
140
|
|
|
107
|
-
const
|
|
108
|
-
const latestArtifact = findLatestStepReviewArtifact(taskFolder,
|
|
141
|
+
const artifactStepNumber = stepNumber ?? findPlanReviewStepNumber(taskFolder);
|
|
142
|
+
const latestArtifact = findLatestStepReviewArtifact(taskFolder, artifactStepNumber);
|
|
109
143
|
if (latestArtifact) {
|
|
110
144
|
const reviewContent = fs.readFileSync(latestArtifact.artifactPath, "utf-8");
|
|
111
145
|
const { verdict, feedback } = parseReviewVerdict(reviewContent, { reviewType: "plan" });
|
|
@@ -139,6 +173,7 @@ function findCompletedPlanReview({
|
|
|
139
173
|
* @param {number} [params.attempt]
|
|
140
174
|
* @param {Record<string, any>} [params.journal]
|
|
141
175
|
* @param {{ next: () => string } | null} [params.stubVerdicts]
|
|
176
|
+
* @param {number} [params.planReviewStep] Explicit plan-review step override (SP-874 / #294 ordering); defaults to findPlanReviewStepNumber.
|
|
142
177
|
* @returns {Promise<{ ok: boolean, [key: string]: any }>}
|
|
143
178
|
*/
|
|
144
179
|
export async function runEnginePlanReview({
|
|
@@ -148,6 +183,7 @@ export async function runEnginePlanReview({
|
|
|
148
183
|
attempt = 1,
|
|
149
184
|
journal,
|
|
150
185
|
stubVerdicts = null,
|
|
186
|
+
planReviewStep,
|
|
151
187
|
}) {
|
|
152
188
|
const reviewLevel = readReviewLevel(taskFolder);
|
|
153
189
|
if (!isReviewTypeRequired(reviewLevel, "plan")) {
|
|
@@ -163,7 +199,7 @@ export async function runEnginePlanReview({
|
|
|
163
199
|
};
|
|
164
200
|
}
|
|
165
201
|
|
|
166
|
-
const stepNumber = findPlanReviewStepNumber(taskFolder);
|
|
202
|
+
const stepNumber = planReviewStep ?? findPlanReviewStepNumber(taskFolder);
|
|
167
203
|
const artifactPath = buildReviewArtifactPath(taskFolder, stepNumber);
|
|
168
204
|
const useStub = shouldUseReviewStub();
|
|
169
205
|
|
|
@@ -280,6 +316,13 @@ function recordPlanReviewTaskFailure({
|
|
|
280
316
|
* existing plan artifact/journal verdict, rework loop on REVISE, fail-closed
|
|
281
317
|
* on exhaustion or invalid verdict.
|
|
282
318
|
*
|
|
319
|
+
* SP-874 / #294: plan reviews are queued via findPlanReviewStepOrder — the
|
|
320
|
+
* step-0 (minimum-step) review is scheduled BEFORE any later-step
|
|
321
|
+
* (plan-review checkpoint) review for the same task/lane. Each queued step
|
|
322
|
+
* runs the honor fast-path then the review/rework poll loop; a spawn failure
|
|
323
|
+
* or exhausted rework loop at any step fails the task closed (the remaining
|
|
324
|
+
* schedule is not silently skipped).
|
|
325
|
+
*
|
|
283
326
|
* Params: projectRoot, state, batchId, config, task, lane,
|
|
284
327
|
* taskFolderInWorktree, wt, taskBranch, laneCorrelationId, fileScopePaths.
|
|
285
328
|
* Loosely typed because callers may forward a shared params bag
|
|
@@ -315,48 +358,68 @@ export async function runPlanReviewPhase({
|
|
|
315
358
|
|
|
316
359
|
// Materialize the stub queue once per phase and pass it via params so
|
|
317
360
|
// parallel lanes never share or mutate process.env stub state (SP-728).
|
|
361
|
+
// The queue spans the whole ordered schedule (SP-874): verdicts pop in
|
|
362
|
+
// order across steps, never reset per step.
|
|
318
363
|
const stubVerdicts = shouldUseReviewStub() ? createPhaseStubVerdictQueue("plan") : null;
|
|
319
364
|
|
|
320
|
-
|
|
321
|
-
const
|
|
322
|
-
reviewType: "plan",
|
|
323
|
-
passVerdict: "APPROVE",
|
|
324
|
-
attemptField: "planReviewAttempts",
|
|
325
|
-
attemptKey: "planReviewAttempt",
|
|
326
|
-
findCompletedReview: findCompletedPlanReview,
|
|
327
|
-
projectRoot,
|
|
328
|
-
state,
|
|
329
|
-
batchId,
|
|
330
|
-
task,
|
|
331
|
-
lane,
|
|
332
|
-
laneCorrelationId,
|
|
333
|
-
taskFolder: taskFolderInWorktree,
|
|
334
|
-
journalEvents,
|
|
335
|
-
worktreePath: wt,
|
|
336
|
-
});
|
|
337
|
-
if (honoredResult) return honoredResult;
|
|
365
|
+
// SP-874 / #294: step 0 first, then any later plan-review checkpoint step.
|
|
366
|
+
const planReviewSteps = findPlanReviewStepOrder(taskFolderInWorktree);
|
|
338
367
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
368
|
+
/** @type {{ ok: boolean, [key: string]: any }} */
|
|
369
|
+
let phaseResult = { ok: true };
|
|
370
|
+
for (const planReviewStep of planReviewSteps) {
|
|
371
|
+
// Re-read per step so the next step's honor scan sees verdicts the
|
|
372
|
+
// previous step just recorded.
|
|
373
|
+
const journalEvents = readJournalEvents(projectRoot, batchId);
|
|
374
|
+
const honoredResult = honorCompletedReview({
|
|
375
|
+
reviewType: "plan",
|
|
376
|
+
passVerdict: "APPROVE",
|
|
377
|
+
attemptField: "planReviewAttempts",
|
|
378
|
+
attemptKey: "planReviewAttempt",
|
|
379
|
+
findCompletedReview: (/** @type {Record<string, any>} */ finderParams) =>
|
|
380
|
+
findCompletedPlanReview(/** @type {any} */ ({ ...finderParams, stepNumber: planReviewStep })),
|
|
381
|
+
projectRoot,
|
|
382
|
+
state,
|
|
383
|
+
batchId,
|
|
384
|
+
task,
|
|
385
|
+
lane,
|
|
386
|
+
laneCorrelationId,
|
|
387
|
+
taskFolder: taskFolderInWorktree,
|
|
388
|
+
journalEvents,
|
|
389
|
+
worktreePath: wt,
|
|
390
|
+
});
|
|
391
|
+
if (honoredResult) {
|
|
392
|
+
phaseResult = honoredResult;
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
phaseResult = await runReviewPollLoop({
|
|
397
|
+
reviewType: "plan",
|
|
398
|
+
passVerdict: "APPROVE",
|
|
399
|
+
attemptField: "planReviewAttempts",
|
|
400
|
+
attemptKey: "planReviewAttempt",
|
|
401
|
+
maxAttempts: maxPlanReviewAttempts,
|
|
402
|
+
runEngineReview: (params) =>
|
|
403
|
+
runEnginePlanReview(/** @type {any} */ ({ ...params, stubVerdicts, planReviewStep })),
|
|
404
|
+
recordReviewTaskFailure: recordPlanReviewTaskFailure,
|
|
405
|
+
invalidVerdictOutput: "plan review artifact missing APPROVE or REVISE verdict",
|
|
406
|
+
journalEvents,
|
|
407
|
+
projectRoot,
|
|
408
|
+
state,
|
|
409
|
+
batchId,
|
|
410
|
+
config,
|
|
411
|
+
task,
|
|
412
|
+
lane,
|
|
413
|
+
taskFolderInWorktree,
|
|
414
|
+
wt,
|
|
415
|
+
taskBranch,
|
|
416
|
+
laneCorrelationId,
|
|
417
|
+
fileScopePaths,
|
|
418
|
+
});
|
|
419
|
+
// Fail-closed (#294 item 2): a spawn failure, exhausted rework loop, or
|
|
420
|
+
// invalid verdict at any queued step stops the schedule — later-step
|
|
421
|
+
// plan reviews must not run while an earlier step is unreviewed.
|
|
422
|
+
if (!phaseResult.ok) return phaseResult;
|
|
423
|
+
}
|
|
424
|
+
return phaseResult;
|
|
362
425
|
}
|
|
@@ -336,6 +336,8 @@ export async function runReviewPollLoop({
|
|
|
336
336
|
? `${reviewType}_review_provider_error`
|
|
337
337
|
: `${reviewType}_review_spawn_failed`;
|
|
338
338
|
// SP-837 (#325): one reviewer row per spawn failure / timeout / provider error.
|
|
339
|
+
// SP-880 (#338): forward spawn-result usage so failed reviewer spawns still
|
|
340
|
+
// attribute the tokens pi reported before failing (omitted when none).
|
|
339
341
|
recordReviewMetric({
|
|
340
342
|
projectRoot,
|
|
341
343
|
config,
|
|
@@ -352,6 +354,7 @@ export async function runReviewPollLoop({
|
|
|
352
354
|
? "provider_error"
|
|
353
355
|
: "spawn_failed",
|
|
354
356
|
failureReason: typeof reviewResult.reason === "string" ? reviewResult.reason : undefined,
|
|
357
|
+
usage: reviewResult.usage,
|
|
355
358
|
});
|
|
356
359
|
recordReviewTaskFailure({
|
|
357
360
|
projectRoot,
|
|
@@ -389,6 +392,8 @@ export async function runReviewPollLoop({
|
|
|
389
392
|
[attemptKey]: reviewAttempt + 1,
|
|
390
393
|
});
|
|
391
394
|
// SP-837 (#325): one reviewer row per recorded verdict (attempt is 1-based).
|
|
395
|
+
// SP-880 (#338): usage rides on the engine-review result (originating from
|
|
396
|
+
// the reviewer pi JSON stream) so verdict rows attribute cost by role/model.
|
|
392
397
|
recordReviewMetric({
|
|
393
398
|
projectRoot,
|
|
394
399
|
config,
|
|
@@ -400,6 +405,7 @@ export async function runReviewPollLoop({
|
|
|
400
405
|
attempt: reviewAttempt + 1,
|
|
401
406
|
durationMs: Date.now() - reviewStartedAt,
|
|
402
407
|
outcome: "verdict",
|
|
408
|
+
usage: reviewResult.usage,
|
|
403
409
|
});
|
|
404
410
|
|
|
405
411
|
if (reviewResult.verdict === passVerdict) {
|
package/src/batch/metrics.mjs
CHANGED
|
@@ -258,6 +258,9 @@ export function resolveReviewMetricPins(config, reviewType) {
|
|
|
258
258
|
* @param {"verdict"|"spawn_failed"|"timeout"|"provider_error"|"blocked"} [params.outcome]
|
|
259
259
|
* @param {string} [params.failureReason]
|
|
260
260
|
* @param {number} [params.endedAtMs]
|
|
261
|
+
* @param {{ tokensIn?: number, tokensOut?: number, estimatedUsd?: number }} [params.usage]
|
|
262
|
+
* pi `--mode json` usage totals from the reviewer spawn (SP-880 / #338). Only finite
|
|
263
|
+
* values are copied; absent/NaN/Infinity are omitted so rows never invent usage.
|
|
261
264
|
*/
|
|
262
265
|
export function buildReviewMetricRecord({
|
|
263
266
|
batchId,
|
|
@@ -274,6 +277,7 @@ export function buildReviewMetricRecord({
|
|
|
274
277
|
outcome = "verdict",
|
|
275
278
|
failureReason,
|
|
276
279
|
endedAtMs = Date.now(),
|
|
280
|
+
usage,
|
|
277
281
|
}) {
|
|
278
282
|
/** @type {Record<string, unknown>} */
|
|
279
283
|
const record = {
|
|
@@ -297,6 +301,15 @@ export function buildReviewMetricRecord({
|
|
|
297
301
|
if (Number.isFinite(attempt)) record.attempt = attempt;
|
|
298
302
|
if (Number.isFinite(durationMs)) record.durationMs = Math.max(0, /** @type {number} */ (durationMs));
|
|
299
303
|
if (typeof failureReason === "string" && failureReason !== "") record.failureReason = failureReason;
|
|
304
|
+
// SP-880 / #338: reviewer usage totals from the pi JSON stream. Same finite
|
|
305
|
+
// convention as task rows; keys stay absent when pi reported nothing. The
|
|
306
|
+
// metrics redaction allowlist (USAGE_KEYS) keeps these fields while redacting
|
|
307
|
+
// the rest of the record.
|
|
308
|
+
if (usage !== null && typeof usage === "object") {
|
|
309
|
+
if (Number.isFinite(usage.tokensIn)) record.tokensIn = usage.tokensIn;
|
|
310
|
+
if (Number.isFinite(usage.tokensOut)) record.tokensOut = usage.tokensOut;
|
|
311
|
+
if (Number.isFinite(usage.estimatedUsd)) record.estimatedUsd = usage.estimatedUsd;
|
|
312
|
+
}
|
|
300
313
|
|
|
301
314
|
return sanitizeMetricRecord(record);
|
|
302
315
|
}
|
|
@@ -328,6 +341,8 @@ export function appendReviewMetric(projectRoot, record, config = {}) {
|
|
|
328
341
|
* @param {number} [params.durationMs]
|
|
329
342
|
* @param {"verdict"|"spawn_failed"|"timeout"|"provider_error"|"blocked"} [params.outcome]
|
|
330
343
|
* @param {string} [params.failureReason]
|
|
344
|
+
* @param {{ tokensIn?: number, tokensOut?: number, estimatedUsd?: number }} [params.usage]
|
|
345
|
+
* pi `--mode json` usage totals from the reviewer spawn result (SP-880 / #338).
|
|
331
346
|
*/
|
|
332
347
|
export function recordReviewMetric({ projectRoot, config = {}, model, ...rest }) {
|
|
333
348
|
if (!isMetricsEnabled(config)) return null;
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure parser for `pi --mode json` NDJSON streams (SP-878, partial #338).
|
|
3
|
+
*
|
|
4
|
+
* Sums provider-reported token usage and cost from a pi JSON event stream so
|
|
5
|
+
* worker/reviewer producers (SP-879 / SP-880) can tee real usage into
|
|
6
|
+
* run-metrics instead of discarding it. This module performs no I/O and never
|
|
7
|
+
* invents values: usage keys are omitted from the result when pi reports none.
|
|
8
|
+
*
|
|
9
|
+
* Event shapes follow pi 1.5.2 `docs/json.md` and `docs/message-types.md`:
|
|
10
|
+
*
|
|
11
|
+
* - `message_end` — `message.usage` is the authoritative final usage for one
|
|
12
|
+
* assistant message. This is the primary counting source.
|
|
13
|
+
* - `message_update` — carries a cumulative top-level `usage` for the
|
|
14
|
+
* in-flight response; deliberately NOT summed (it would double-count every
|
|
15
|
+
* message that later reaches `message_end`). A stream truncated before any
|
|
16
|
+
* `message_end` therefore under-counts rather than over-counts.
|
|
17
|
+
* - `compaction_end` — `result.usage` on successful compaction (absent when
|
|
18
|
+
* aborted/failed).
|
|
19
|
+
* - `tool_execution_end` — `result.usage` when a tool performed nested model
|
|
20
|
+
* work. pi docs confirm this is not part of the main model-call usage, so
|
|
21
|
+
* summing it adds real spend without double-counting.
|
|
22
|
+
*
|
|
23
|
+
* `Usage` shape: `{ input, output, cacheRead, cacheWrite, cacheWrite1h?,
|
|
24
|
+
* reasoning?, totalTokens, cost: { input, output, cacheRead, cacheWrite,
|
|
25
|
+
* total } }`. Per pi docs `reasoning` is already included in `output` and
|
|
26
|
+
* `cacheWrite1h` is a subset of `cacheWrite`, so neither is added again:
|
|
27
|
+
* `tokensIn = input + cacheRead + cacheWrite`, `tokensOut = output`.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Summed usage totals. Fields are present only when pi reported at least one
|
|
32
|
+
* finite value for them; reported zeros are kept (they are real reports).
|
|
33
|
+
*
|
|
34
|
+
* @typedef {object} PiJsonUsageTotals
|
|
35
|
+
* @property {number} [tokensIn] input + cacheRead + cacheWrite tokens.
|
|
36
|
+
* @property {number} [tokensOut] output tokens (`reasoning` already included).
|
|
37
|
+
* @property {number} [estimatedUsd] sum of provider-reported `cost.total`.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @typedef {{ type?: unknown, [key: string]: unknown }} PiJsonEvent
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
/** @typedef {string | readonly string[] | Iterable<string>} PiJsonStreamInput */
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Validate one usage counter. Finite non-negative numbers are accepted as-is
|
|
48
|
+
* (including `0`); `NaN`, `Infinity`, negatives, and non-numbers are treated
|
|
49
|
+
* as absent so garbage cannot invent usage.
|
|
50
|
+
*
|
|
51
|
+
* @param {unknown} value
|
|
52
|
+
* @returns {number | undefined}
|
|
53
|
+
*/
|
|
54
|
+
function finiteCount(value) {
|
|
55
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Guard for stream-input parameters: a whole-NDJSON string, an array of
|
|
60
|
+
* records, or any iterable of record strings. Rejects everything else —
|
|
61
|
+
* including non-iterable plain objects, which `for...of` would otherwise
|
|
62
|
+
* reject with its own generic "not iterable" TypeError instead of this
|
|
63
|
+
* module's documented one.
|
|
64
|
+
*
|
|
65
|
+
* @param {PiJsonStreamInput} input
|
|
66
|
+
* @returns {void}
|
|
67
|
+
* @throws {TypeError} when input is neither a string nor iterable.
|
|
68
|
+
*/
|
|
69
|
+
function assertStreamInput(input) {
|
|
70
|
+
if (
|
|
71
|
+
typeof input !== "string" &&
|
|
72
|
+
(input === null ||
|
|
73
|
+
typeof input !== "object" ||
|
|
74
|
+
typeof /** @type {any} */ (input)[Symbol.iterator] !== "function")
|
|
75
|
+
) {
|
|
76
|
+
throw new TypeError("pi-json-usage: input must be a string or an iterable of strings");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Normalize stream input into individual JSONL records. Strings split on LF
|
|
82
|
+
* (pi framing: strict JSONL, optional preceding CR); iterables of strings are
|
|
83
|
+
* treated as records and split further if they embed newlines.
|
|
84
|
+
*
|
|
85
|
+
* @param {PiJsonStreamInput} input
|
|
86
|
+
* @yields {string}
|
|
87
|
+
*/
|
|
88
|
+
function* iterRecords(input) {
|
|
89
|
+
if (typeof input === "string") {
|
|
90
|
+
for (const record of input.split("\n")) {
|
|
91
|
+
yield record;
|
|
92
|
+
}
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
for (const record of input) {
|
|
96
|
+
if (typeof record !== "string") {
|
|
97
|
+
throw new TypeError("pi-json-usage: stream records must be strings");
|
|
98
|
+
}
|
|
99
|
+
if (record.includes("\n")) {
|
|
100
|
+
for (const part of record.split("\n")) {
|
|
101
|
+
yield part;
|
|
102
|
+
}
|
|
103
|
+
} else {
|
|
104
|
+
yield record;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Parse a pi JSON stream into event objects. Non-JSON and non-object records
|
|
111
|
+
* are skipped (pi writes strict JSONL; leniency here only ignores noise, it
|
|
112
|
+
* never fabricates usage).
|
|
113
|
+
*
|
|
114
|
+
* @param {PiJsonStreamInput} input
|
|
115
|
+
* @yields {PiJsonEvent}
|
|
116
|
+
*/
|
|
117
|
+
function* iterEvents(input) {
|
|
118
|
+
for (const record of iterRecords(input)) {
|
|
119
|
+
const trimmed = record.endsWith("\r") ? record.slice(0, -1) : record;
|
|
120
|
+
if (trimmed.trim().length === 0) continue;
|
|
121
|
+
let parsed;
|
|
122
|
+
try {
|
|
123
|
+
parsed = JSON.parse(trimmed);
|
|
124
|
+
} catch {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (parsed === null || typeof parsed !== "object") continue;
|
|
128
|
+
yield /** @type {PiJsonEvent} */ (parsed);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Accumulate one pi `Usage` object into the running totals.
|
|
134
|
+
*
|
|
135
|
+
* @param {unknown} usage
|
|
136
|
+
* @param {{ tokensIn: number, tokensOut: number, estimatedUsd: number, sawTokensIn: boolean, sawTokensOut: boolean, sawUsd: boolean }} totals
|
|
137
|
+
*/
|
|
138
|
+
function accumulateUsage(usage, totals) {
|
|
139
|
+
if (usage === null || typeof usage !== "object") return;
|
|
140
|
+
const input = finiteCount(/** @type {any} */ (usage).input);
|
|
141
|
+
const cacheRead = finiteCount(/** @type {any} */ (usage).cacheRead);
|
|
142
|
+
const cacheWrite = finiteCount(/** @type {any} */ (usage).cacheWrite);
|
|
143
|
+
const output = finiteCount(/** @type {any} */ (usage).output);
|
|
144
|
+
if (input !== undefined || cacheRead !== undefined || cacheWrite !== undefined) {
|
|
145
|
+
totals.tokensIn += (input ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0);
|
|
146
|
+
totals.sawTokensIn = true;
|
|
147
|
+
}
|
|
148
|
+
if (output !== undefined) {
|
|
149
|
+
totals.tokensOut += output;
|
|
150
|
+
totals.sawTokensOut = true;
|
|
151
|
+
}
|
|
152
|
+
const cost = /** @type {any} */ (usage).cost;
|
|
153
|
+
if (cost !== null && typeof cost === "object") {
|
|
154
|
+
const costTotal = finiteCount(cost.total);
|
|
155
|
+
if (costTotal !== undefined) {
|
|
156
|
+
totals.estimatedUsd += costTotal;
|
|
157
|
+
totals.sawUsd = true;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* @param {PiJsonEvent} event
|
|
164
|
+
* @param {{ tokensIn: number, tokensOut: number, estimatedUsd: number, sawTokensIn: boolean, sawTokensOut: boolean, sawUsd: boolean }} totals
|
|
165
|
+
*/
|
|
166
|
+
function accumulateEvent(event, totals) {
|
|
167
|
+
const type = event.type;
|
|
168
|
+
if (type === "message_end") {
|
|
169
|
+
const message = event.message;
|
|
170
|
+
if (message !== null && typeof message === "object" && /** @type {any} */ (message).role === "assistant") {
|
|
171
|
+
accumulateUsage(/** @type {any} */ (message).usage, totals);
|
|
172
|
+
}
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (type === "compaction_end") {
|
|
176
|
+
const result = event.result;
|
|
177
|
+
if (result !== null && typeof result === "object") {
|
|
178
|
+
accumulateUsage(/** @type {any} */ (result).usage, totals);
|
|
179
|
+
}
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (type === "tool_execution_end") {
|
|
183
|
+
const result = event.result;
|
|
184
|
+
if (result !== null && typeof result === "object") {
|
|
185
|
+
accumulateUsage(/** @type {any} */ (result).usage, totals);
|
|
186
|
+
}
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Sum usage from a `pi --mode json` (JSONL) stream.
|
|
193
|
+
*
|
|
194
|
+
* Only authoritative events are counted (`message_end` assistant usage,
|
|
195
|
+
* successful `compaction_end` usage, `tool_execution_end` nested usage), so
|
|
196
|
+
* totals never double-count streaming `message_update` snapshots. Keys are
|
|
197
|
+
* omitted when pi reported nothing — never invent costs.
|
|
198
|
+
*
|
|
199
|
+
* @param {PiJsonStreamInput} input Whole NDJSON text, an array of records, or any iterable of record strings.
|
|
200
|
+
* @returns {PiJsonUsageTotals}
|
|
201
|
+
* @throws {TypeError} when input is not a string/iterable or records are not strings.
|
|
202
|
+
*/
|
|
203
|
+
export function sumUsageFromPiJsonStream(input) {
|
|
204
|
+
assertStreamInput(input);
|
|
205
|
+
const totals = {
|
|
206
|
+
tokensIn: 0,
|
|
207
|
+
tokensOut: 0,
|
|
208
|
+
estimatedUsd: 0,
|
|
209
|
+
sawTokensIn: false,
|
|
210
|
+
sawTokensOut: false,
|
|
211
|
+
sawUsd: false,
|
|
212
|
+
};
|
|
213
|
+
for (const event of iterEvents(input)) {
|
|
214
|
+
accumulateEvent(event, totals);
|
|
215
|
+
}
|
|
216
|
+
/** @type {PiJsonUsageTotals} */
|
|
217
|
+
const result = {};
|
|
218
|
+
if (totals.sawTokensIn) result.tokensIn = totals.tokensIn;
|
|
219
|
+
if (totals.sawTokensOut) result.tokensOut = totals.tokensOut;
|
|
220
|
+
if (totals.sawUsd) result.estimatedUsd = totals.estimatedUsd;
|
|
221
|
+
return result;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Extract human-readable assistant text segments from a `pi --mode json`
|
|
226
|
+
* stream, for tee-ing readable output into run logs alongside usage totals.
|
|
227
|
+
*
|
|
228
|
+
* Segments come from authoritative `message_end` assistant messages only:
|
|
229
|
+
* their `text` content blocks are concatenated per message (tool-call and
|
|
230
|
+
* thinking blocks are skipped), in stream order. Streaming deltas from
|
|
231
|
+
* `message_update` are never used, so no partial/duplicated text leaks in.
|
|
232
|
+
*
|
|
233
|
+
* @param {PiJsonStreamInput} input Whole NDJSON text, an array of records, or any iterable of record strings.
|
|
234
|
+
* @returns {string[]}
|
|
235
|
+
* @throws {TypeError} when input is not a string/iterable or records are not strings.
|
|
236
|
+
*/
|
|
237
|
+
export function extractTextFromPiJsonStream(input) {
|
|
238
|
+
assertStreamInput(input);
|
|
239
|
+
/** @type {string[]} */
|
|
240
|
+
const segments = [];
|
|
241
|
+
for (const event of iterEvents(input)) {
|
|
242
|
+
if (event.type !== "message_end") continue;
|
|
243
|
+
const message = /** @type {any} */ (event.message);
|
|
244
|
+
if (message === null || typeof message !== "object" || message.role !== "assistant") continue;
|
|
245
|
+
const content = message.content;
|
|
246
|
+
if (!Array.isArray(content)) continue;
|
|
247
|
+
const text = content
|
|
248
|
+
.filter(
|
|
249
|
+
/** @returns {block is { type: "text", text: string }} */
|
|
250
|
+
(block) =>
|
|
251
|
+
block !== null &&
|
|
252
|
+
typeof block === "object" &&
|
|
253
|
+
block.type === "text" &&
|
|
254
|
+
typeof block.text === "string" &&
|
|
255
|
+
block.text.length > 0,
|
|
256
|
+
)
|
|
257
|
+
.map((block) => block.text)
|
|
258
|
+
.join("");
|
|
259
|
+
if (text.length > 0) segments.push(text);
|
|
260
|
+
}
|
|
261
|
+
return segments;
|
|
262
|
+
}
|