@laoyuehanni/dsh-token-usage 0.3.12 → 0.4.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/README.md +21 -86
- package/README.zh.md +21 -90
- package/docs/pricing.md +79 -0
- package/lib/client/DateRangePicker.d.ts +39 -0
- package/lib/client/DateRangePicker.d.ts.map +1 -0
- package/lib/client/DateRangePicker.js +134 -0
- package/lib/client/DateRangePicker.js.map +1 -0
- package/lib/client/MenuSelect.d.ts +47 -0
- package/lib/client/MenuSelect.d.ts.map +1 -0
- package/lib/client/MenuSelect.js +152 -0
- package/lib/client/MenuSelect.js.map +1 -0
- package/lib/client/StatCard.d.ts +61 -5
- package/lib/client/StatCard.d.ts.map +1 -1
- package/lib/client/StatCard.js +39 -1
- package/lib/client/StatCard.js.map +1 -1
- package/lib/client/TokenUsageCard.d.ts.map +1 -1
- package/lib/client/TokenUsageCard.js +23 -12
- package/lib/client/TokenUsageCard.js.map +1 -1
- package/lib/client/TokenUsageSection.d.ts.map +1 -1
- package/lib/client/TokenUsageSection.js +31 -13
- package/lib/client/TokenUsageSection.js.map +1 -1
- package/lib/client/TrendChart.d.ts +12 -3
- package/lib/client/TrendChart.d.ts.map +1 -1
- package/lib/client/TrendChart.js +30 -19
- package/lib/client/TrendChart.js.map +1 -1
- package/lib/client/UsageView.d.ts +6 -5
- package/lib/client/UsageView.d.ts.map +1 -1
- package/lib/client/UsageView.js +19 -14
- package/lib/client/UsageView.js.map +1 -1
- package/lib/client/day.d.ts +22 -0
- package/lib/client/day.d.ts.map +1 -1
- package/lib/client/day.js +31 -0
- package/lib/client/day.js.map +1 -1
- package/lib/client/format.d.ts +18 -3
- package/lib/client/format.d.ts.map +1 -1
- package/lib/client/format.js +45 -3
- package/lib/client/format.js.map +1 -1
- package/lib/client/locales.d.ts +34 -3
- package/lib/client/locales.d.ts.map +1 -1
- package/lib/client/locales.js +68 -6
- package/lib/client/locales.js.map +1 -1
- package/lib/client/trend-chart/index.d.ts +1 -1
- package/lib/client/trend-chart/index.d.ts.map +1 -1
- package/lib/client/trend-chart/index.js +1 -1
- package/lib/client/trend-chart/index.js.map +1 -1
- package/lib/client/trend-chart/points.d.ts +11 -0
- package/lib/client/trend-chart/points.d.ts.map +1 -1
- package/lib/client/trend-chart/points.js +20 -0
- package/lib/client/trend-chart/points.js.map +1 -1
- package/lib/client.js +864 -145
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +14 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +117 -28
- package/lib/index.js.map +1 -1
- package/lib/log.d.ts +18 -0
- package/lib/log.d.ts.map +1 -0
- package/lib/log.js +16 -0
- package/lib/log.js.map +1 -0
- package/lib/migrate.d.ts +2 -1
- package/lib/migrate.d.ts.map +1 -1
- package/lib/migrate.js +3 -2
- package/lib/migrate.js.map +1 -1
- package/lib/pricing.d.ts +5 -2
- package/lib/pricing.d.ts.map +1 -1
- package/lib/pricing.js +15 -12
- package/lib/pricing.js.map +1 -1
- package/lib/record-cache.d.ts +11 -4
- package/lib/record-cache.d.ts.map +1 -1
- package/lib/record-cache.js +16 -9
- package/lib/record-cache.js.map +1 -1
- package/lib/rollup.d.ts +15 -8
- package/lib/rollup.d.ts.map +1 -1
- package/lib/rollup.js +14 -9
- package/lib/rollup.js.map +1 -1
- package/lib/stats-route.d.ts +3 -0
- package/lib/stats-route.d.ts.map +1 -1
- package/lib/stats-route.js +6 -4
- package/lib/stats-route.js.map +1 -1
- package/lib/stats.d.ts +8 -5
- package/lib/stats.d.ts.map +1 -1
- package/lib/stats.js +74 -26
- package/lib/stats.js.map +1 -1
- package/lib/sync-state.d.ts +2 -1
- package/lib/sync-state.d.ts.map +1 -1
- package/lib/sync-state.js +3 -2
- package/lib/sync-state.js.map +1 -1
- package/lib/sync.d.ts +24 -3
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +42 -10
- package/lib/sync.js.map +1 -1
- package/lib/usage-log.d.ts +23 -8
- package/lib/usage-log.d.ts.map +1 -1
- package/lib/usage-log.js +129 -17
- package/lib/usage-log.js.map +1 -1
- package/lib/usage-record.d.ts +88 -7
- package/lib/usage-record.d.ts.map +1 -1
- package/lib/usage-record.js +140 -4
- package/lib/usage-record.js.map +1 -1
- package/lib/wire.d.ts +19 -1
- package/lib/wire.d.ts.map +1 -1
- package/lib/wire.js.map +1 -1
- package/package.json +7 -1
package/lib/usage-log.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Durable JSONL store of the token-usage plugin: per-local-day files, a
|
|
3
3
|
* serialized append queue, and the process-wide request-id dedupe set that
|
|
4
|
-
* both the live hook and the manual sync share.
|
|
4
|
+
* both the live hook and the manual sync share. A row lands in the day
|
|
5
|
+
* file of its event time (`record.time` in local Y-M-D), never the wall
|
|
6
|
+
* clock of the append — live events and history backfill share that rule.
|
|
5
7
|
*
|
|
6
8
|
* @module token-usage/usage-log
|
|
7
9
|
*/
|
|
8
|
-
import { appendFile, mkdir, readdir, readFile } from 'node:fs/promises';
|
|
10
|
+
import { appendFile, mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
9
11
|
import { join } from 'node:path';
|
|
12
|
+
import { consoleLogger } from "./log.js";
|
|
10
13
|
import { parseRecord, serializeRecord } from "./usage-record.js";
|
|
11
14
|
const DAY_FILE = /^usage-\d{4}-\d{2}-\d{2}\.jsonl$/u;
|
|
12
15
|
/** Test for this store's per-day file names; the migration shares the naming contract. */
|
|
@@ -18,30 +21,34 @@ export function dayFileName(date) {
|
|
|
18
21
|
const day = String(date.getDate()).padStart(2, '0');
|
|
19
22
|
return `usage-${year}-${month}-${day}.jsonl`;
|
|
20
23
|
}
|
|
21
|
-
|
|
22
|
-
|
|
24
|
+
/** Day-file name of a record's event time, matching {@link dayFileName}. */
|
|
25
|
+
export function dayFileNameOf(time) {
|
|
26
|
+
return dayFileName(new Date(time));
|
|
27
|
+
}
|
|
28
|
+
function dayFilePath(dir, time) {
|
|
29
|
+
return join(dir, dayFileNameOf(time));
|
|
23
30
|
}
|
|
24
31
|
/**
|
|
25
32
|
* Append-only per-day JSONL log with request-id dedupe.
|
|
26
33
|
*
|
|
27
|
-
* Ordering: every append runs on one promise chain, so
|
|
28
|
-
* land in call order. Dedupe: a request id is claimed
|
|
29
|
-
* its append is queued; a failed append releases the
|
|
30
|
-
* be retried later.
|
|
34
|
+
* Ordering: every append (and a refile pass) runs on one promise chain, so
|
|
35
|
+
* concurrent callers land in call order. Dedupe: a request id is claimed
|
|
36
|
+
* synchronously before its append is queued; a failed append releases the
|
|
37
|
+
* claim, so the row can be retried later.
|
|
31
38
|
*/
|
|
32
39
|
export class UsageLog {
|
|
33
40
|
dir;
|
|
34
|
-
|
|
41
|
+
logger;
|
|
35
42
|
seen = new Set();
|
|
36
43
|
queue = Promise.resolve();
|
|
37
44
|
ready;
|
|
38
45
|
/**
|
|
39
46
|
* @param dir - absolute data directory (created lazily on first write).
|
|
40
|
-
* @param
|
|
47
|
+
* @param logger - diagnostic sink; defaults to console.
|
|
41
48
|
*/
|
|
42
|
-
constructor(dir,
|
|
49
|
+
constructor(dir, logger = consoleLogger) {
|
|
43
50
|
this.dir = dir;
|
|
44
|
-
this.
|
|
51
|
+
this.logger = logger;
|
|
45
52
|
}
|
|
46
53
|
/** Whether a request id is already known to this log. */
|
|
47
54
|
has(requestId) {
|
|
@@ -69,14 +76,14 @@ export class UsageLog {
|
|
|
69
76
|
names = await readdir(this.dir);
|
|
70
77
|
}
|
|
71
78
|
catch (error) {
|
|
72
|
-
|
|
79
|
+
this.logger.error('[token-usage] cannot list data dir ' + this.dir + ':', error);
|
|
73
80
|
return;
|
|
74
81
|
}
|
|
75
82
|
for (const name of names) {
|
|
76
83
|
if (!DAY_FILE.test(name))
|
|
77
84
|
continue;
|
|
78
85
|
const text = await readFile(join(this.dir, name), 'utf8').catch((error) => {
|
|
79
|
-
|
|
86
|
+
this.logger.error(`[token-usage] cannot read ${name}:`, error);
|
|
80
87
|
return '';
|
|
81
88
|
});
|
|
82
89
|
for (const line of text.split('\n')) {
|
|
@@ -84,7 +91,7 @@ export class UsageLog {
|
|
|
84
91
|
continue;
|
|
85
92
|
const record = parseRecord(line);
|
|
86
93
|
if (record === null) {
|
|
87
|
-
|
|
94
|
+
this.logger.error(`[token-usage] skipping malformed line in ${name}: ${line.slice(0, 120)}`);
|
|
88
95
|
continue;
|
|
89
96
|
}
|
|
90
97
|
this.seen.add(record.requestId);
|
|
@@ -111,10 +118,29 @@ export class UsageLog {
|
|
|
111
118
|
.catch((error) => {
|
|
112
119
|
// Release the claim so a later sync can retry this row.
|
|
113
120
|
this.seen.delete(record.requestId);
|
|
114
|
-
|
|
121
|
+
this.logger.error('[token-usage] append failed:', error);
|
|
115
122
|
return false;
|
|
116
123
|
});
|
|
117
124
|
}
|
|
125
|
+
/**
|
|
126
|
+
* Move rows that sit in the wrong day file onto `dayFileNameOf(record.time)`.
|
|
127
|
+
* Idempotent: a crash after the target already holds a request id just
|
|
128
|
+
* strips it from the source on the next pass. Runs on the append queue so
|
|
129
|
+
* a live write cannot interleave with the rewrite.
|
|
130
|
+
* @returns the number of rows that had to move.
|
|
131
|
+
*/
|
|
132
|
+
refileByEventDay() {
|
|
133
|
+
let moved = 0;
|
|
134
|
+
const task = this.queue.then(async () => {
|
|
135
|
+
await this.ensureDir();
|
|
136
|
+
moved = await refileDayFiles(this.dir, this.logger);
|
|
137
|
+
});
|
|
138
|
+
this.queue = task.catch(() => { });
|
|
139
|
+
return task.then(() => moved).catch((error) => {
|
|
140
|
+
this.logger.error('[token-usage] refile by event day failed:', error);
|
|
141
|
+
return 0;
|
|
142
|
+
});
|
|
143
|
+
}
|
|
118
144
|
/** The directory is created once and remembered; an external deletion
|
|
119
145
|
* forces a rebuild on the next append (see {@link appendOnce}). */
|
|
120
146
|
async ensureDir() {
|
|
@@ -126,9 +152,11 @@ export class UsageLog {
|
|
|
126
152
|
* cached creation: the data location may be removed underneath a running
|
|
127
153
|
* process (a migration that stayed behind, a user cleanup), and failing
|
|
128
154
|
* every append forever after would silently drop the whole session's rows.
|
|
155
|
+
* The destination is the local day of {@link UsageRecord.time}, so a
|
|
156
|
+
* history sync lands each row on the day the request happened.
|
|
129
157
|
*/
|
|
130
158
|
async appendOnce(record) {
|
|
131
|
-
const path = dayFilePath(this.dir,
|
|
159
|
+
const path = dayFilePath(this.dir, record.time);
|
|
132
160
|
try {
|
|
133
161
|
await appendFile(path, `${serializeRecord(record)}\n`, { flag: 'a' });
|
|
134
162
|
}
|
|
@@ -141,4 +169,88 @@ export class UsageLog {
|
|
|
141
169
|
}
|
|
142
170
|
}
|
|
143
171
|
}
|
|
172
|
+
async function readDayLines(dir, name, logger) {
|
|
173
|
+
const text = await readFile(join(dir, name), 'utf8').catch((error) => {
|
|
174
|
+
if (error.code !== 'ENOENT') {
|
|
175
|
+
logger.error(`[token-usage] cannot read ${name}:`, error);
|
|
176
|
+
}
|
|
177
|
+
return '';
|
|
178
|
+
});
|
|
179
|
+
const lines = [];
|
|
180
|
+
for (const raw of text.split('\n')) {
|
|
181
|
+
if (raw === '')
|
|
182
|
+
continue;
|
|
183
|
+
lines.push({ record: parseRecord(raw), raw });
|
|
184
|
+
}
|
|
185
|
+
return lines;
|
|
186
|
+
}
|
|
187
|
+
async function rewriteDayFile(dir, name, records) {
|
|
188
|
+
const target = join(dir, name);
|
|
189
|
+
if (records.length === 0) {
|
|
190
|
+
await unlink(target).catch(() => undefined);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const tmp = join(dir, `${name}.tmp`);
|
|
194
|
+
await writeFile(tmp, `${records.map(serializeRecord).join('\n')}\n`, 'utf8');
|
|
195
|
+
await unlink(target).catch(() => undefined);
|
|
196
|
+
await rename(tmp, target);
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Redistribute parsed rows onto the day file their event time names.
|
|
200
|
+
* Malformed lines stay in the source file so a bad row is never dropped.
|
|
201
|
+
*/
|
|
202
|
+
async function refileDayFiles(dir, logger) {
|
|
203
|
+
let names;
|
|
204
|
+
try {
|
|
205
|
+
names = (await readdir(dir)).filter(name => DAY_FILE.test(name)).sort();
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
logger.error('[token-usage] cannot list data dir ' + dir + ':', error);
|
|
209
|
+
return 0;
|
|
210
|
+
}
|
|
211
|
+
let moved = 0;
|
|
212
|
+
for (const source of names) {
|
|
213
|
+
const lines = await readDayLines(dir, source, logger);
|
|
214
|
+
const stay = [];
|
|
215
|
+
const stray = [];
|
|
216
|
+
const leave = new Map();
|
|
217
|
+
for (const line of lines) {
|
|
218
|
+
if (line.record === null) {
|
|
219
|
+
stray.push(line.raw);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
const target = dayFileNameOf(line.record.time);
|
|
223
|
+
if (target === source) {
|
|
224
|
+
stay.push(line.record);
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
const bucket = leave.get(target) ?? [];
|
|
228
|
+
bucket.push(line.record);
|
|
229
|
+
leave.set(target, bucket);
|
|
230
|
+
moved += 1;
|
|
231
|
+
}
|
|
232
|
+
if (leave.size === 0)
|
|
233
|
+
continue;
|
|
234
|
+
for (const [target, records] of leave) {
|
|
235
|
+
const existing = (await readDayLines(dir, target, logger))
|
|
236
|
+
.map(line => line.record)
|
|
237
|
+
.filter((record) => record !== null);
|
|
238
|
+
const seen = new Set(existing.map(record => record.requestId));
|
|
239
|
+
const appended = records.filter(record => !seen.has(record.requestId));
|
|
240
|
+
await rewriteDayFile(dir, target, [...existing, ...appended]);
|
|
241
|
+
}
|
|
242
|
+
if (stray.length > 0) {
|
|
243
|
+
const target = join(dir, source);
|
|
244
|
+
const body = `${stay.map(serializeRecord).join('\n')}${stay.length > 0 ? '\n' : ''}${stray.join('\n')}\n`;
|
|
245
|
+
const tmp = join(dir, `${source}.tmp`);
|
|
246
|
+
await writeFile(tmp, body, 'utf8');
|
|
247
|
+
await unlink(target).catch(() => undefined);
|
|
248
|
+
await rename(tmp, target);
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
await rewriteDayFile(dir, source, stay);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return moved;
|
|
255
|
+
}
|
|
144
256
|
//# sourceMappingURL=usage-log.js.map
|
package/lib/usage-log.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-log.js","sourceRoot":"","sources":["../src/usage-log.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"usage-log.js","sourceRoot":"","sources":["../src/usage-log.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAClG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,aAAa,EAAmB,MAAM,UAAU,CAAA;AACzD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAoB,MAAM,mBAAmB,CAAA;AAElF,MAAM,QAAQ,GAAG,mCAAmC,CAAA;AAEpD,0FAA0F;AAC1F,OAAO,EAAE,QAAQ,EAAE,CAAA;AAEnB,0EAA0E;AAC1E,MAAM,UAAU,WAAW,CAAC,IAAU;IACpC,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW,EAAE,CAAA;IAC/B,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAA;IAC1D,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAA;IACnD,OAAO,SAAS,IAAI,IAAI,KAAK,IAAI,GAAG,QAAQ,CAAA;AAC9C,CAAC;AAED,4EAA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AM,CAAC,CAAA;QAC3B,CAAC;aAAM,CAAC;YACN,MAAM,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;QACzC,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC"}
|
package/lib/usage-record.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Pure record vocabulary of the token-usage plugin: the JSONL row type, its
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
3
|
+
* projections from session events (assistant messages, compaction
|
|
4
|
+
* summaries, turn-ending LLM failures, and retried failed attempts), and
|
|
5
|
+
* lenient line parsing for the dedupe scan. No I/O and no runtime imports,
|
|
6
|
+
* so every consumer shares
|
|
7
|
+
* one wire format. Rows stay minimal: request id, model, the four base
|
|
8
|
+
* token buckets, time, session id, and the optional origin kind — absent
|
|
9
|
+
* optional buckets are omitted, never null.
|
|
7
10
|
*
|
|
8
11
|
* @module token-usage/usage-record
|
|
9
12
|
*/
|
|
@@ -20,18 +23,35 @@ export interface UsageFields {
|
|
|
20
23
|
/** Cache-write input tokens; omitted when the provider reported none. */
|
|
21
24
|
cacheWriteTokens?: number;
|
|
22
25
|
}
|
|
23
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* Where a record came from: a plain model request (the default), a
|
|
28
|
+
* compaction summarize request (a provider-billed call of its own), or a
|
|
29
|
+
* failed model request (a turn that ended in an LLM error, or a provider
|
|
30
|
+
* attempt that `dsh-llm-retry` scheduled a retry for — counted in its own
|
|
31
|
+
* `failures` dimension, never in `requests`).
|
|
32
|
+
*/
|
|
33
|
+
export type UsageRecordKind = 'request' | 'compaction' | 'failure';
|
|
34
|
+
/** One JSONL row: one provider model call (successful or failed). */
|
|
24
35
|
export interface UsageRecord {
|
|
25
|
-
/** Stable request identity: the assistant message id (dedupe key)
|
|
36
|
+
/** Stable request identity: the assistant message id (dedupe key), or a
|
|
37
|
+
* synthesized `failure:<session>:<seq>` for a failed-request row. */
|
|
26
38
|
requestId: string;
|
|
27
39
|
/** Session-event wall time, epoch milliseconds. */
|
|
28
40
|
time: number;
|
|
29
41
|
/** Owning session id. */
|
|
30
42
|
sessionId: string;
|
|
31
|
-
/** Provider model id that produced the message
|
|
43
|
+
/** Provider model id that produced the message; a failure row carries the
|
|
44
|
+
* session's last-known route model ('' when none was ever observed). */
|
|
32
45
|
model: string;
|
|
33
46
|
/** Token buckets; omitted when the provider reported no usage at all. */
|
|
34
47
|
usage?: UsageFields;
|
|
48
|
+
/** Record origin; absent means a plain request (legacy rows predate the
|
|
49
|
+
* key, so the on-disk default is omission, never `'request'`). */
|
|
50
|
+
kind?: UsageRecordKind;
|
|
51
|
+
/** Failure row only: the provider-neutral `LlmFailure.code` the attempt
|
|
52
|
+
* failed with (RATE_LIMIT, TRANSPORT, QUOTA, …). Absent on every other
|
|
53
|
+
* kind; a future code renders verbatim. */
|
|
54
|
+
failureCode?: string;
|
|
35
55
|
}
|
|
36
56
|
/**
|
|
37
57
|
* Project the event's optional provider usage into the four base buckets.
|
|
@@ -41,8 +61,69 @@ export interface UsageRecord {
|
|
|
41
61
|
export declare function projectUsage(usage: TokenUsage | undefined): UsageFields | undefined;
|
|
42
62
|
/** Build the log row for one assistant/message session event. */
|
|
43
63
|
export declare function recordFromEvent(event: SessionEvent<'assistant/message'>, sessionId: string): UsageRecord;
|
|
64
|
+
/**
|
|
65
|
+
* Build the log row for one `compaction/summary` session event — the
|
|
66
|
+
* summarize provider call that reads the compacted history and writes the
|
|
67
|
+
* summary. The row is billed exactly like a plain request: `model` is the
|
|
68
|
+
* event's summarize model, and the usage buckets are the provider-reported
|
|
69
|
+
* figures for the call. A missing or invalid usage renders the record null:
|
|
70
|
+
* an unusage compaction cannot be priced, and `shadowedTokenCount` (the
|
|
71
|
+
* shadow price of the replaced context) is not a billing figure, so the
|
|
72
|
+
* event is skipped rather than recorded unpriced.
|
|
73
|
+
*
|
|
74
|
+
* The request id is `compaction:<sessionId>:<seq>` — the event's persistent
|
|
75
|
+
* seq is monotonic and unique within the session (the compactionId is an
|
|
76
|
+
* opaque, unvalidated string), so one row lands per compaction and repeated
|
|
77
|
+
* syncs dedupe.
|
|
78
|
+
* @returns the record, or null when the event carries no usable usage.
|
|
79
|
+
*/
|
|
80
|
+
export declare function recordFromCompaction(event: SessionEvent<'compaction/summary'>, sessionId: string): UsageRecord | null;
|
|
44
81
|
/** One JSONL line without the trailing newline. */
|
|
45
82
|
export declare function serializeRecord(record: UsageRecord): string;
|
|
83
|
+
/**
|
|
84
|
+
* Build the log row for one `turn/end` session event whose reason is an LLM
|
|
85
|
+
* error — the terminal failed model request of a turn. Only
|
|
86
|
+
* `reason.kind === 'error'` counts: an aborted turn was cancelled by the
|
|
87
|
+
* user/parent (not a provider failure), `max-tokens` truncated a request
|
|
88
|
+
* that otherwise succeeded, and `blocked`/`interrupted` never reached the
|
|
89
|
+
* provider. Intermediate attempts that `dsh-llm-retry` recovered are
|
|
90
|
+
* recorded separately via {@link recordFromRetry}. The row carries no
|
|
91
|
+
* usage (a failed call bills nothing), the `model` the caller tracked for
|
|
92
|
+
* the session's route — `turn/end` itself names no model, so the recorder
|
|
93
|
+
* follows `request/context` / `assistant/message` events to keep one
|
|
94
|
+
* last-known model id per session — and the provider-neutral
|
|
95
|
+
* `failureCode` (the `LlmFailure.code`, e.g. RATE_LIMIT / TRANSPORT /
|
|
96
|
+
* QUOTA) the failure classifier assigned.
|
|
97
|
+
* @returns the record, or null when the turn ended for a non-error reason.
|
|
98
|
+
*/
|
|
99
|
+
export declare function recordFromTurnEnd(event: SessionEvent<'turn/end'>, sessionId: string, model: string): UsageRecord | null;
|
|
100
|
+
/**
|
|
101
|
+
* Build the log row for one `llm/retry` session event — a provider attempt
|
|
102
|
+
* that failed and that `dsh-llm-retry` scheduled another try for. Every
|
|
103
|
+
* such event is a real failed call (the plugin writes it before the wait,
|
|
104
|
+
* so a later cancel during backoff still counts the original attempt).
|
|
105
|
+
* The row carries no usage; `model` is the session's last-known route
|
|
106
|
+
* (the event names the provider, not the model); `failureCode` is the
|
|
107
|
+
* `LlmFailure.code` on the payload. `llm/retry-started` is the wait-
|
|
108
|
+
* complete marker and is not a failure — the caller ignores it.
|
|
109
|
+
*/
|
|
110
|
+
export declare function recordFromRetry(event: SessionEvent<'llm/retry'>, sessionId: string, model: string): UsageRecord;
|
|
111
|
+
/**
|
|
112
|
+
* Project one session event into a log row, or null when the event is not
|
|
113
|
+
* a recorded origin. Live listening and history sync share this so a new
|
|
114
|
+
* origin cannot land on only one path. `lastModel` is the session's last
|
|
115
|
+
* known route (failure rows name no model of their own); compaction
|
|
116
|
+
* recording follows the same `recordCompaction` switch both callers take.
|
|
117
|
+
*/
|
|
118
|
+
export declare function recordOfEvent(event: SessionEvent, sessionId: string, lastModel: string, recordCompaction?: boolean): UsageRecord | null;
|
|
119
|
+
/**
|
|
120
|
+
* The model id an event reveals about the session's current route, when it
|
|
121
|
+
* does: `request/context` announces route changes before dispatch (it logs
|
|
122
|
+
* only on change), and `assistant/message` confirms the model that actually
|
|
123
|
+
* produced a message. Both fold into the same last-known value, so a turn
|
|
124
|
+
* that ends in an error can still attribute its failure row to a model.
|
|
125
|
+
*/
|
|
126
|
+
export declare function modelOfEvent(event: SessionEvent): string | undefined;
|
|
46
127
|
/**
|
|
47
128
|
* Coerce an unknown value into a record, normalizing extra fields and null
|
|
48
129
|
* buckets to omission, so rows written by older field sets still dedupe
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-record.d.ts","sourceRoot":"","sources":["../src/usage-record.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"usage-record.d.ts","sourceRoot":"","sources":["../src/usage-record.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;A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U,CAAC,EAC/B,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,GACZ,WAAW,GAAG,IAAI,CAGpB;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,YAAY,CAAC,WAAW,CAAC,EAChC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,GACZ,WAAW,CAEb;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,YAAY,EACnB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,gBAAgB,UAAO,GACtB,WAAW,GAAG,IAAI,CAapB;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAIpE;AAsBD;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,WAAW,GAAG,IAAI,CA0C/D;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI,CAS5D"}
|
package/lib/usage-record.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Pure record vocabulary of the token-usage plugin: the JSONL row type, its
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
3
|
+
* projections from session events (assistant messages, compaction
|
|
4
|
+
* summaries, turn-ending LLM failures, and retried failed attempts), and
|
|
5
|
+
* lenient line parsing for the dedupe scan. No I/O and no runtime imports,
|
|
6
|
+
* so every consumer shares
|
|
7
|
+
* one wire format. Rows stay minimal: request id, model, the four base
|
|
8
|
+
* token buckets, time, session id, and the optional origin kind — absent
|
|
9
|
+
* optional buckets are omitted, never null.
|
|
7
10
|
*
|
|
8
11
|
* @module token-usage/usage-record
|
|
9
12
|
*/
|
|
@@ -38,10 +41,128 @@ export function recordFromEvent(event, sessionId) {
|
|
|
38
41
|
...(usage !== undefined ? { usage } : {}),
|
|
39
42
|
};
|
|
40
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* Build the log row for one `compaction/summary` session event — the
|
|
46
|
+
* summarize provider call that reads the compacted history and writes the
|
|
47
|
+
* summary. The row is billed exactly like a plain request: `model` is the
|
|
48
|
+
* event's summarize model, and the usage buckets are the provider-reported
|
|
49
|
+
* figures for the call. A missing or invalid usage renders the record null:
|
|
50
|
+
* an unusage compaction cannot be priced, and `shadowedTokenCount` (the
|
|
51
|
+
* shadow price of the replaced context) is not a billing figure, so the
|
|
52
|
+
* event is skipped rather than recorded unpriced.
|
|
53
|
+
*
|
|
54
|
+
* The request id is `compaction:<sessionId>:<seq>` — the event's persistent
|
|
55
|
+
* seq is monotonic and unique within the session (the compactionId is an
|
|
56
|
+
* opaque, unvalidated string), so one row lands per compaction and repeated
|
|
57
|
+
* syncs dedupe.
|
|
58
|
+
* @returns the record, or null when the event carries no usable usage.
|
|
59
|
+
*/
|
|
60
|
+
export function recordFromCompaction(event, sessionId) {
|
|
61
|
+
const usage = projectUsage(event.data.usage);
|
|
62
|
+
if (usage === undefined)
|
|
63
|
+
return null;
|
|
64
|
+
return {
|
|
65
|
+
requestId: `compaction:${sessionId}:${String(event.seq)}`,
|
|
66
|
+
time: event.time,
|
|
67
|
+
sessionId,
|
|
68
|
+
model: event.data.model,
|
|
69
|
+
usage,
|
|
70
|
+
kind: 'compaction',
|
|
71
|
+
};
|
|
72
|
+
}
|
|
41
73
|
/** One JSONL line without the trailing newline. */
|
|
42
74
|
export function serializeRecord(record) {
|
|
43
75
|
return JSON.stringify(record);
|
|
44
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* Build the log row for one failed provider attempt. Shared by a terminal
|
|
79
|
+
* `turn/end` error and an `llm/retry` (a failed attempt that the retry
|
|
80
|
+
* plugin then scheduled another try for). The request id is
|
|
81
|
+
* `failure:<sessionId>:<seq>` — the event's persistent seq is monotonic
|
|
82
|
+
* and unique within the session, so the two sources never collide and
|
|
83
|
+
* repeated syncs dedupe.
|
|
84
|
+
*/
|
|
85
|
+
function failureRow(event, sessionId, model, code) {
|
|
86
|
+
return {
|
|
87
|
+
requestId: `failure:${sessionId}:${String(event.seq)}`,
|
|
88
|
+
time: event.time,
|
|
89
|
+
sessionId,
|
|
90
|
+
model,
|
|
91
|
+
kind: 'failure',
|
|
92
|
+
// The classifier always names a code (an unclassified throw flattens to
|
|
93
|
+
// 'UNKNOWN'); keep the row honest even if a future event omits it.
|
|
94
|
+
...(code !== undefined && code !== '' ? { failureCode: code } : {}),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Build the log row for one `turn/end` session event whose reason is an LLM
|
|
99
|
+
* error — the terminal failed model request of a turn. Only
|
|
100
|
+
* `reason.kind === 'error'` counts: an aborted turn was cancelled by the
|
|
101
|
+
* user/parent (not a provider failure), `max-tokens` truncated a request
|
|
102
|
+
* that otherwise succeeded, and `blocked`/`interrupted` never reached the
|
|
103
|
+
* provider. Intermediate attempts that `dsh-llm-retry` recovered are
|
|
104
|
+
* recorded separately via {@link recordFromRetry}. The row carries no
|
|
105
|
+
* usage (a failed call bills nothing), the `model` the caller tracked for
|
|
106
|
+
* the session's route — `turn/end` itself names no model, so the recorder
|
|
107
|
+
* follows `request/context` / `assistant/message` events to keep one
|
|
108
|
+
* last-known model id per session — and the provider-neutral
|
|
109
|
+
* `failureCode` (the `LlmFailure.code`, e.g. RATE_LIMIT / TRANSPORT /
|
|
110
|
+
* QUOTA) the failure classifier assigned.
|
|
111
|
+
* @returns the record, or null when the turn ended for a non-error reason.
|
|
112
|
+
*/
|
|
113
|
+
export function recordFromTurnEnd(event, sessionId, model) {
|
|
114
|
+
if (event.data.reason.kind !== 'error')
|
|
115
|
+
return null;
|
|
116
|
+
return failureRow(event, sessionId, model, event.data.reason.error.code);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Build the log row for one `llm/retry` session event — a provider attempt
|
|
120
|
+
* that failed and that `dsh-llm-retry` scheduled another try for. Every
|
|
121
|
+
* such event is a real failed call (the plugin writes it before the wait,
|
|
122
|
+
* so a later cancel during backoff still counts the original attempt).
|
|
123
|
+
* The row carries no usage; `model` is the session's last-known route
|
|
124
|
+
* (the event names the provider, not the model); `failureCode` is the
|
|
125
|
+
* `LlmFailure.code` on the payload. `llm/retry-started` is the wait-
|
|
126
|
+
* complete marker and is not a failure — the caller ignores it.
|
|
127
|
+
*/
|
|
128
|
+
export function recordFromRetry(event, sessionId, model) {
|
|
129
|
+
return failureRow(event, sessionId, model, event.data.failure.code);
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Project one session event into a log row, or null when the event is not
|
|
133
|
+
* a recorded origin. Live listening and history sync share this so a new
|
|
134
|
+
* origin cannot land on only one path. `lastModel` is the session's last
|
|
135
|
+
* known route (failure rows name no model of their own); compaction
|
|
136
|
+
* recording follows the same `recordCompaction` switch both callers take.
|
|
137
|
+
*/
|
|
138
|
+
export function recordOfEvent(event, sessionId, lastModel, recordCompaction = true) {
|
|
139
|
+
switch (event.type) {
|
|
140
|
+
case 'assistant/message':
|
|
141
|
+
return recordFromEvent(event, sessionId);
|
|
142
|
+
case 'compaction/summary':
|
|
143
|
+
return recordCompaction ? recordFromCompaction(event, sessionId) : null;
|
|
144
|
+
case 'turn/end':
|
|
145
|
+
return recordFromTurnEnd(event, sessionId, lastModel);
|
|
146
|
+
case 'llm/retry':
|
|
147
|
+
return recordFromRetry(event, sessionId, lastModel);
|
|
148
|
+
default:
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The model id an event reveals about the session's current route, when it
|
|
154
|
+
* does: `request/context` announces route changes before dispatch (it logs
|
|
155
|
+
* only on change), and `assistant/message` confirms the model that actually
|
|
156
|
+
* produced a message. Both fold into the same last-known value, so a turn
|
|
157
|
+
* that ends in an error can still attribute its failure row to a model.
|
|
158
|
+
*/
|
|
159
|
+
export function modelOfEvent(event) {
|
|
160
|
+
if (event.type === 'request/context')
|
|
161
|
+
return event.data.model;
|
|
162
|
+
if (event.type === 'assistant/message')
|
|
163
|
+
return event.data.message.source.model;
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
45
166
|
function normalizeCount(value) {
|
|
46
167
|
return isCount(value) ? value : undefined;
|
|
47
168
|
}
|
|
@@ -72,12 +193,25 @@ export function coerceRecord(value) {
|
|
|
72
193
|
return null;
|
|
73
194
|
// The guard already validated the structure; this cast only enables field access.
|
|
74
195
|
const record = value;
|
|
196
|
+
// Kind normalization: only a compaction or failure row keeps the key —
|
|
197
|
+
// plain rows (and unknown future kinds) read as requests, so a newer row
|
|
198
|
+
// set never drops.
|
|
199
|
+
const isFailure = record.kind === 'failure';
|
|
200
|
+
const kind = record.kind === 'compaction' ? { kind: 'compaction' }
|
|
201
|
+
: isFailure ? { kind: 'failure' }
|
|
202
|
+
: {};
|
|
203
|
+
// Failure classification survives the round trip on failure rows only
|
|
204
|
+
// (a non-string or foreign-kind code normalizes to omission).
|
|
205
|
+
const failureCode = isFailure && typeof record.failureCode === 'string' && record.failureCode !== ''
|
|
206
|
+
? { failureCode: record.failureCode } : {};
|
|
75
207
|
if (record.usage === undefined || record.usage === null) {
|
|
76
208
|
return {
|
|
77
209
|
requestId: record.requestId,
|
|
78
210
|
time: record.time,
|
|
79
211
|
sessionId: record.sessionId,
|
|
80
212
|
model: record.model,
|
|
213
|
+
...kind,
|
|
214
|
+
...failureCode,
|
|
81
215
|
};
|
|
82
216
|
}
|
|
83
217
|
const fields = record.usage;
|
|
@@ -88,6 +222,8 @@ export function coerceRecord(value) {
|
|
|
88
222
|
time: record.time,
|
|
89
223
|
sessionId: record.sessionId,
|
|
90
224
|
model: record.model,
|
|
225
|
+
...kind,
|
|
226
|
+
...failureCode,
|
|
91
227
|
usage: {
|
|
92
228
|
inputTokens: fields.inputTokens,
|
|
93
229
|
outputTokens: fields.outputTokens,
|
package/lib/usage-record.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-record.js","sourceRoot":"","sources":["../src/usage-record.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"usage-record.js","sourceRoot":"","sources":["../src/usage-record.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAuDH,SAAS,OAAO,CAAC,KAAc;IAC7B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAA;AAC1E,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,KAA6B;IACxD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IACzC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,YAAY,CAAC;QAAE,OAAO,SAAS,CAAA;IACjF,OAAO;QACL,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,KAAK,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACrF,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACzF,CAAA;AACH,CAAC;AAED,iEAAiE;AACjE,MAAM,UAAU,eAAe,CAC7B,KAAwC,EACxC,SAAiB;IAEjB,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IAC5C,OAAO;QACL,SAAS,EAAE,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;QAChC,IAAI,EAAE,KAAK,CAAC,IAA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YACL,WAAW,EAAE,MAAM,CAAC,WAAqB;YACzC,YAAY,EAAE,MAAM,CAAC,YAAsB;YAC3C,GAAG,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAClE,GAAG,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACtE;KACF,CAAA;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,IAAI,KAAc,CAAA;IAClB,IAAI,CAAC;QACH,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,+EAA+E;QAC/E,OAAO,IAAI,CAAA;IACb,CAAC;IACD,OAAO,YAAY,CAAC,KAAK,CAAC,CAAA;AAC5B,CAAC"}
|
package/lib/wire.d.ts
CHANGED
|
@@ -108,19 +108,23 @@ export type FullSyncView = {
|
|
|
108
108
|
total: number;
|
|
109
109
|
added: number;
|
|
110
110
|
skipped: number;
|
|
111
|
+
failedSessions: number;
|
|
111
112
|
} | {
|
|
112
113
|
status: 'done';
|
|
113
114
|
processed: number;
|
|
114
115
|
total: number;
|
|
115
116
|
added: number;
|
|
116
117
|
skipped: number;
|
|
118
|
+
failedSessions: number;
|
|
117
119
|
} | {
|
|
118
120
|
status: 'failed';
|
|
119
121
|
error: string;
|
|
120
122
|
};
|
|
121
123
|
/** Aggregated token counts over one group of records. */
|
|
122
124
|
export interface UsageTotals {
|
|
123
|
-
/** Number of recorded
|
|
125
|
+
/** Number of recorded provider-billed calls: plain requests plus
|
|
126
|
+
* compaction summarize requests (records without provider usage count
|
|
127
|
+
* here). Failed requests never join this count — see {@link failures}. */
|
|
124
128
|
requests: number;
|
|
125
129
|
/** Uncached input tokens; billed input = input + cacheRead + cacheWrite. */
|
|
126
130
|
inputTokens: number;
|
|
@@ -130,6 +134,20 @@ export interface UsageTotals {
|
|
|
130
134
|
cacheReadTokens: number;
|
|
131
135
|
/** Cache-write input tokens. */
|
|
132
136
|
cacheWriteTokens: number;
|
|
137
|
+
/** Compaction summarize requests in this group; absent on legacy rollups
|
|
138
|
+
* (reads as 0). Plain requests = `requests - (compactions ?? 0)`. */
|
|
139
|
+
compactions?: number;
|
|
140
|
+
/** Failed model requests in this group (`turn/end` LLM errors plus
|
|
141
|
+
* `llm/retry` scheduled after a failed attempt); absent on legacy
|
|
142
|
+
* rollups and pre-failure shapes (reads as 0). Success rate =
|
|
143
|
+
* requests / (requests + failures) is attempt-level, not turn-level. */
|
|
144
|
+
failures?: number;
|
|
145
|
+
/** Failure counts by the provider-neutral `LlmFailure.code`
|
|
146
|
+
* (`{ RATE_LIMIT: 16, TRANSPORT: 2, … }`); absent when the
|
|
147
|
+
* group holds no failures or the shape predates the key (reads as an
|
|
148
|
+
* empty map). Sums to `failures` when present. Codes are an open set:
|
|
149
|
+
* unknown future codes read verbatim. */
|
|
150
|
+
failuresByCode?: Record<string, number>;
|
|
133
151
|
}
|
|
134
152
|
/** One per-day aggregation row, keyed by local date `YYYY-MM-DD`. */
|
|
135
153
|
export interface UsageDayRow {
|