pi-spine 2.31.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-batch.mjs +16 -2
- package/bin/spine-gate.mjs +24 -2
- package/bin/spine-integrate.mjs +23 -3
- package/bin/spine-journal.mjs +25 -2
- package/bin/spine-plan.mjs +15 -5
- package/bin/spine-state.mjs +22 -1
- package/bin/spine-worker-runner.mjs +182 -15
- package/package.json +1 -1
- package/src/batch/batch-id.mjs +55 -0
- package/src/batch/contract-exec.mjs +64 -56
- 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/gate-posture-approve.mjs +47 -46
- package/src/batch/gate-posture-streak.mjs +69 -25
- package/src/batch/integrate.mjs +1 -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-scope.mjs +3 -0
- package/src/batch/review-spawn.mjs +48 -2
- package/src/batch/review-step.mjs +8 -0
- package/src/batch/worker-host.mjs +18 -18
- package/src/cli/handoff.mjs +14 -1
- package/src/config/cursor-rules/profile.mjs +7 -2
- package/src/config/worker-context.mjs +6 -3
- package/src/dashboard/server.mjs +101 -9
- package/src/tasks/validate-contract-warn.mjs +121 -0
- package/templates/rules-profile.json +1 -27
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
incrementKindStreak,
|
|
20
20
|
resetCategoryStreak,
|
|
21
21
|
resetKindStreak,
|
|
22
|
+
withGatePostureStreakLock,
|
|
22
23
|
} from "./gate-posture-streak.mjs";
|
|
23
24
|
import { gateRecordPath, loadGateRecord } from "./gate-evidence-read.mjs";
|
|
24
25
|
import { appendJournalEvent } from "./journal.mjs";
|
|
@@ -373,61 +374,61 @@ export function maybeAutoApproveIntegrateGate(ctx) {
|
|
|
373
374
|
};
|
|
374
375
|
}
|
|
375
376
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
377
|
+
// SP-868 / #314: streak read → decision → auto-approve + increment must be
|
|
378
|
+
// atomic against concurrent locked streak RMWs, or a stale high count read
|
|
379
|
+
// before a reset could unlock auto-approve. Lock-acquisition failure
|
|
380
|
+
// propagates (no auto-approve happened — fail-closed), matching batch-state
|
|
381
|
+
// writer behavior; production streak I/O re-enters this hold harmlessly.
|
|
382
|
+
return withGatePostureStreakLock(projectRoot, () => {
|
|
383
|
+
const consecutiveApprovals = getCategoryStreak(projectRoot, category);
|
|
384
|
+
const mergedTags = [...(Array.isArray(gate.tags) ? gate.tags : []), ...tags].filter(
|
|
385
|
+
(tag) => typeof tag === "string",
|
|
386
|
+
);
|
|
387
|
+
|
|
388
|
+
const evaluation = evaluateGatePosture({
|
|
389
|
+
category,
|
|
390
|
+
posture: categoryEntry.posture,
|
|
391
|
+
autoApproveAfterN: categoryEntry.autoApproveAfterN,
|
|
392
|
+
consecutiveApprovals,
|
|
393
|
+
tags: mergedTags,
|
|
394
|
+
alwaysBreakOn: postureConfig.alwaysBreakOn,
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
if (evaluation.decision !== "allow-auto") {
|
|
398
|
+
return {
|
|
399
|
+
ok: true,
|
|
400
|
+
approved: false,
|
|
401
|
+
evaluation,
|
|
402
|
+
optedIn,
|
|
403
|
+
category,
|
|
404
|
+
consecutiveApprovals,
|
|
405
|
+
reason: evaluation.reason,
|
|
406
|
+
gate,
|
|
407
|
+
};
|
|
382
408
|
}
|
|
383
|
-
}
|
|
384
|
-
for (const tag of tags) {
|
|
385
|
-
if (typeof tag === "string") mergedTags.push(tag);
|
|
386
|
-
}
|
|
387
409
|
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
});
|
|
410
|
+
const approved = approveIntegrateGate({
|
|
411
|
+
projectRoot,
|
|
412
|
+
batchId,
|
|
413
|
+
decidedBy: "auto",
|
|
414
|
+
postureEvaluation: evaluation,
|
|
415
|
+
streakIo,
|
|
416
|
+
});
|
|
396
417
|
|
|
397
|
-
if (evaluation.decision !== "allow-auto") {
|
|
398
418
|
return {
|
|
399
|
-
ok:
|
|
400
|
-
|
|
419
|
+
ok: approved.ok,
|
|
420
|
+
exitCode: approved.exitCode,
|
|
421
|
+
approved: approved.ok === true,
|
|
401
422
|
evaluation,
|
|
402
423
|
optedIn,
|
|
403
424
|
category,
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
425
|
+
decidedBy: "auto",
|
|
426
|
+
gate: approved.gate ?? gate,
|
|
427
|
+
headline: approved.headline,
|
|
428
|
+
error: approved.error,
|
|
429
|
+
blockers: approved.blockers,
|
|
407
430
|
};
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
const approved = approveIntegrateGate({
|
|
411
|
-
projectRoot,
|
|
412
|
-
batchId,
|
|
413
|
-
decidedBy: "auto",
|
|
414
|
-
postureEvaluation: evaluation,
|
|
415
|
-
streakIo,
|
|
416
431
|
});
|
|
417
|
-
|
|
418
|
-
return {
|
|
419
|
-
ok: approved.ok,
|
|
420
|
-
exitCode: approved.exitCode,
|
|
421
|
-
approved: approved.ok === true,
|
|
422
|
-
evaluation,
|
|
423
|
-
optedIn,
|
|
424
|
-
category,
|
|
425
|
-
decidedBy: "auto",
|
|
426
|
-
gate: approved.gate ?? gate,
|
|
427
|
-
headline: approved.headline,
|
|
428
|
-
error: approved.error,
|
|
429
|
-
blockers: approved.blockers,
|
|
430
|
-
};
|
|
431
432
|
}
|
|
432
433
|
|
|
433
434
|
/**
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import fs from "node:fs";
|
|
9
9
|
import path from "node:path";
|
|
10
10
|
import { writeJsonAtomic } from "../fs/atomic-write.mjs";
|
|
11
|
+
import { withBatchStateLock } from "./batch-state-lock.mjs";
|
|
11
12
|
import { GATE_CATEGORIES } from "./gate-posture-defaults.mjs";
|
|
12
13
|
|
|
13
14
|
/** @typedef {import("./gate-posture-defaults.mjs").GateCategory} GateCategory */
|
|
@@ -33,6 +34,33 @@ export const GATE_POSTURE_STREAK_REL = path.join(
|
|
|
33
34
|
|
|
34
35
|
const CATEGORY_SET = new Set(/** @type {string[]} */ ([...GATE_CATEGORIES]));
|
|
35
36
|
|
|
37
|
+
/**
|
|
38
|
+
* SP-868 / #314 — serialize streak read-modify-write across processes.
|
|
39
|
+
*
|
|
40
|
+
* The streak store is project-wide JSON under `.spine/runtime/` while approve /
|
|
41
|
+
* reject / auto-approve decisions run in separate processes (CLI, engine,
|
|
42
|
+
* supervisor). Without a lock, a concurrent increment and reset can both read
|
|
43
|
+
* the same prev count and the last writer wins whole-file — a lost reset leaves
|
|
44
|
+
* a stale high streak that unlocks auto-approve early.
|
|
45
|
+
*
|
|
46
|
+
* Uses the same project-local lock primitive as the batch-state writers
|
|
47
|
+
* (`withBatchStateLock`: exclusive lock file published via temp + `linkSync`,
|
|
48
|
+
* PID-liveness stale breaking, token-gated release, per-process re-entrancy).
|
|
49
|
+
* Sharing that lock file also serializes streak RMWs against batch-state
|
|
50
|
+
* writers, and any caller already inside a batch-state critical section
|
|
51
|
+
* composes re-entrantly instead of deadlocking. Streak critical sections never
|
|
52
|
+
* acquire the resume handoff lock, so the SP-722 lock-ordering rules hold.
|
|
53
|
+
*
|
|
54
|
+
* @template T
|
|
55
|
+
* @param {string} projectRoot
|
|
56
|
+
* @param {() => T} fn synchronous critical section
|
|
57
|
+
* @param {{ timeoutMs?: number }} [options]
|
|
58
|
+
* @returns {T} `fn`'s return value
|
|
59
|
+
*/
|
|
60
|
+
export function withGatePostureStreakLock(projectRoot, fn, options = {}) {
|
|
61
|
+
return /** @type {T} */ (withBatchStateLock(projectRoot, fn, options));
|
|
62
|
+
}
|
|
63
|
+
|
|
36
64
|
/**
|
|
37
65
|
* Absolute path to the streak JSON file.
|
|
38
66
|
* @param {string} projectRoot
|
|
@@ -182,23 +210,27 @@ export function getKindStreak(projectRoot, kind) {
|
|
|
182
210
|
|
|
183
211
|
/**
|
|
184
212
|
* Increment category streak after an approval. Returns the new count.
|
|
213
|
+
* Read-modify-write runs under the streak lock (SP-868 / #314).
|
|
185
214
|
* @param {string} projectRoot
|
|
186
215
|
* @param {GateCategory | string} category
|
|
187
216
|
* @returns {number}
|
|
188
217
|
*/
|
|
189
218
|
export function incrementCategoryStreak(projectRoot, category) {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
219
|
+
return withGatePostureStreakLock(projectRoot, () => {
|
|
220
|
+
const state = loadGatePostureStreaks(projectRoot);
|
|
221
|
+
const prevRaw = state.categories[category];
|
|
222
|
+
const prev =
|
|
223
|
+
typeof prevRaw === "number" && Number.isInteger(prevRaw) && prevRaw >= 0 ? prevRaw : 0;
|
|
224
|
+
const next = prev + 1;
|
|
225
|
+
state.categories[category] = next;
|
|
226
|
+
saveGatePostureStreaks(projectRoot, state);
|
|
227
|
+
return next;
|
|
228
|
+
});
|
|
198
229
|
}
|
|
199
230
|
|
|
200
231
|
/**
|
|
201
232
|
* Increment kind streak after an approval. Returns the new count.
|
|
233
|
+
* Read-modify-write runs under the streak lock (SP-868 / #314).
|
|
202
234
|
* @param {string} projectRoot
|
|
203
235
|
* @param {string} kind
|
|
204
236
|
* @returns {number}
|
|
@@ -207,40 +239,48 @@ export function incrementKindStreak(projectRoot, kind) {
|
|
|
207
239
|
if (typeof kind !== "string" || kind.trim() === "") {
|
|
208
240
|
throw new Error("gate posture kind streak key must be a non-empty string");
|
|
209
241
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
242
|
+
return withGatePostureStreakLock(projectRoot, () => {
|
|
243
|
+
const state = loadGatePostureStreaks(projectRoot);
|
|
244
|
+
const prevRaw = state.kinds[kind];
|
|
245
|
+
const prev =
|
|
246
|
+
typeof prevRaw === "number" && Number.isInteger(prevRaw) && prevRaw >= 0 ? prevRaw : 0;
|
|
247
|
+
const next = prev + 1;
|
|
248
|
+
state.kinds[kind] = next;
|
|
249
|
+
saveGatePostureStreaks(projectRoot, state);
|
|
250
|
+
return next;
|
|
251
|
+
});
|
|
218
252
|
}
|
|
219
253
|
|
|
220
254
|
/**
|
|
221
255
|
* Reset category streak on reject or manual break.
|
|
256
|
+
* Read-modify-write runs under the streak lock (SP-868 / #314).
|
|
222
257
|
* @param {string} projectRoot
|
|
223
258
|
* @param {GateCategory | string} category
|
|
224
259
|
* @returns {number} Always 0 after reset
|
|
225
260
|
*/
|
|
226
261
|
export function resetCategoryStreak(projectRoot, category) {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
262
|
+
return withGatePostureStreakLock(projectRoot, () => {
|
|
263
|
+
const state = loadGatePostureStreaks(projectRoot);
|
|
264
|
+
state.categories[category] = 0;
|
|
265
|
+
saveGatePostureStreaks(projectRoot, state);
|
|
266
|
+
return 0;
|
|
267
|
+
});
|
|
231
268
|
}
|
|
232
269
|
|
|
233
270
|
/**
|
|
234
271
|
* Reset kind streak on reject or manual break.
|
|
272
|
+
* Read-modify-write runs under the streak lock (SP-868 / #314).
|
|
235
273
|
* @param {string} projectRoot
|
|
236
274
|
* @param {string} kind
|
|
237
275
|
* @returns {number} Always 0 after reset
|
|
238
276
|
*/
|
|
239
277
|
export function resetKindStreak(projectRoot, kind) {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
278
|
+
return withGatePostureStreakLock(projectRoot, () => {
|
|
279
|
+
const state = loadGatePostureStreaks(projectRoot);
|
|
280
|
+
state.kinds[kind] = 0;
|
|
281
|
+
saveGatePostureStreaks(projectRoot, state);
|
|
282
|
+
return 0;
|
|
283
|
+
});
|
|
244
284
|
}
|
|
245
285
|
|
|
246
286
|
/**
|
|
@@ -249,7 +289,11 @@ export function resetKindStreak(projectRoot, kind) {
|
|
|
249
289
|
* @returns {GatePostureStreakState}
|
|
250
290
|
*/
|
|
251
291
|
export function resetAllStreaks(projectRoot) {
|
|
252
|
-
|
|
292
|
+
// Locked so a concurrent locked increment's read cannot straddle this whole
|
|
293
|
+
// store replacement and resurrect a stale-high count over it (SP-868 / #314).
|
|
294
|
+
return withGatePostureStreakLock(projectRoot, () =>
|
|
295
|
+
saveGatePostureStreaks(projectRoot, emptyStreakState()),
|
|
296
|
+
);
|
|
253
297
|
}
|
|
254
298
|
|
|
255
299
|
/**
|
package/src/batch/integrate.mjs
CHANGED
|
@@ -422,6 +422,7 @@ export function integrateOrchToBase(ctx) {
|
|
|
422
422
|
mergeCommit,
|
|
423
423
|
commitsAhead,
|
|
424
424
|
gateRequired: gateCheck.required ?? false,
|
|
425
|
+
gateForced: gateCheck.forced ?? false,
|
|
425
426
|
headline: `Integrated ${orchBranch} into ${baseBranch}`,
|
|
426
427
|
suggestedCommand: waiting?.suggestedCommand ?? "spine batch complete",
|
|
427
428
|
alternatives: waiting
|
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
|
+
}
|