pi-spine 2.32.0 → 2.33.1

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.
@@ -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
+ }