dsh-token-usage-ledger 0.0.0-stage → 0.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +1081 -0
  2. package/LICENSE +21 -0
  3. package/README.md +247 -2
  4. package/cordis.patch.yml +30 -0
  5. package/docs/token-usage-image01.png +0 -0
  6. package/docs/token-usage-image02.png +0 -0
  7. package/lib/client.js +4469 -0
  8. package/lib/host/aggregate.d.ts +132 -0
  9. package/lib/host/aggregate.js +840 -0
  10. package/lib/host/api.d.ts +118 -0
  11. package/lib/host/api.js +346 -0
  12. package/lib/host/backfill.d.ts +54 -0
  13. package/lib/host/backfill.js +265 -0
  14. package/lib/host/collector.d.ts +139 -0
  15. package/lib/host/collector.js +441 -0
  16. package/lib/host/ledger-io.d.ts +125 -0
  17. package/lib/host/ledger-io.js +211 -0
  18. package/lib/host/operation-error.d.ts +22 -0
  19. package/lib/host/operation-error.js +28 -0
  20. package/lib/host/paths.d.ts +35 -0
  21. package/lib/host/paths.js +63 -0
  22. package/lib/host/pricing-module.d.ts +112 -0
  23. package/lib/host/pricing-module.js +63 -0
  24. package/lib/host/pricing-modules/deepseek-2026-09-10.d.ts +31 -0
  25. package/lib/host/pricing-modules/deepseek-2026-09-10.js +67 -0
  26. package/lib/host/pricing-modules/index.d.ts +27 -0
  27. package/lib/host/pricing-modules/index.js +30 -0
  28. package/lib/host/pricing.d.ts +192 -0
  29. package/lib/host/pricing.js +287 -0
  30. package/lib/host/records.d.ts +47 -0
  31. package/lib/host/records.js +116 -0
  32. package/lib/host/runtime-marker.d.ts +67 -0
  33. package/lib/host/runtime-marker.js +71 -0
  34. package/lib/host/schema.d.ts +77 -0
  35. package/lib/host/schema.js +158 -0
  36. package/lib/host/store.d.ts +171 -0
  37. package/lib/host/store.js +337 -0
  38. package/lib/host/workspace-titles.d.ts +38 -0
  39. package/lib/host/workspace-titles.js +136 -0
  40. package/lib/host/zstd.d.ts +41 -0
  41. package/lib/host/zstd.js +134 -0
  42. package/lib/index.d.ts +82 -0
  43. package/lib/index.js +512 -0
  44. package/lib/shared/format.d.ts +415 -0
  45. package/lib/shared/format.js +714 -0
  46. package/lib/shared/protocol.d.ts +646 -0
  47. package/lib/shared/protocol.js +129 -0
  48. package/package.json +87 -4
@@ -0,0 +1,646 @@
1
+ /**
2
+ * Host↔Client wire protocol and the pure vocabulary shared by both halves.
3
+ *
4
+ * Everything in this module is dependency-free plain data + arithmetic so that
5
+ * the browser bundle can import it without pulling in any Node builtin or any
6
+ * `@deepseek-ai/*` runtime package. The Host half is the only writer of the
7
+ * ledger; the Client half is a read-only consumer of the JSON summary below.
8
+ *
9
+ * @module dsh-token-usage-ledger/shared/protocol
10
+ */
11
+ /** Bumped whenever the persisted record shape changes incompatibly. */
12
+ export declare const RECORD_SCHEMA_VERSION = 1;
13
+ /** Bumped whenever the wire summary shape changes incompatibly. */
14
+ export declare const SUMMARY_SCHEMA_VERSION = 1;
15
+ /** Currency of the pricing table. The official pages publish both sets independently. */
16
+ export type Currency = 'CNY' | 'USD';
17
+ /**
18
+ * Disjoint provider-reported token buckets, exactly as the harness `TokenUsage`
19
+ * convention defines them.
20
+ *
21
+ * `uncachedInput` excludes cache reads (the DeepSeek adapter subtracts them out
22
+ * of the wire `prompt_tokens`), so the four buckets never double-count.
23
+ * `reasoning` is a SUBSET of `output` and is therefore never priced on its own.
24
+ */
25
+ export interface TokenBuckets {
26
+ /** Prompt tokens served without a cache hit. */
27
+ uncachedInput: number;
28
+ /** Prompt tokens served from the provider's context cache. */
29
+ cacheRead: number;
30
+ /** Prompt tokens written into a cache, when the route reports that bucket. */
31
+ cacheWrite: number;
32
+ /** Completion tokens, reasoning tokens included. */
33
+ output: number;
34
+ /** Reasoning subset of {@link output}; informational only. */
35
+ reasoning: number;
36
+ }
37
+ /** One billed attempt inside a Turn: the usage sample plus the route that produced it. */
38
+ export interface UsageAttempt {
39
+ /** Provider id of the billed route. */
40
+ provider: string;
41
+ /** Model id of the billed route. */
42
+ model: string;
43
+ /** Local epoch milliseconds when the attempt settled. */
44
+ at: number;
45
+ /** Provider-reported buckets for this attempt. */
46
+ tokens: TokenBuckets;
47
+ /** `totalTokens` reported by the provider for this attempt. */
48
+ total: number;
49
+ /**
50
+ * Priced amount for THIS attempt, in the record's currency, frozen at write
51
+ * time. Stored per attempt so a model-filtered view can sum exactly the
52
+ * turns' matching attempts instead of apportioning a whole-turn figure.
53
+ */
54
+ cost: number;
55
+ /** True when this attempt had no exact price row and used the fallback. */
56
+ estimated: boolean;
57
+ /**
58
+ * Why the amount is an estimate, when it is:
59
+ * `'no-price-row'` (nothing matched) or `'before-first-known-price'`
60
+ * (the attempt predates every published price row of the pricing module).
61
+ */
62
+ estimatedReason?: string;
63
+ /**
64
+ * Dated price row this attempt was priced with, or `''` when a configuration
65
+ * override applied. Recorded so a figure can be explained after the price
66
+ * table gains newer rows.
67
+ */
68
+ pricedBy?: string;
69
+ /**
70
+ * Pricing window this attempt was billed under, or `'unknown'` when no price
71
+ * row matched at all — claiming a window there would be a fabrication.
72
+ */
73
+ window: 'peak' | 'off-peak' | 'unknown';
74
+ }
75
+ /** Cost decomposition of one record, frozen at write time so history stays auditable. */
76
+ export interface CostBreakdown {
77
+ /** Currency the amounts are expressed in. */
78
+ currency: Currency;
79
+ /** Total amount in {@link currency}. */
80
+ total: number;
81
+ /** Amount contributed by `uncachedInput`. */
82
+ uncachedInput: number;
83
+ /** Amount contributed by `cacheRead`. */
84
+ cacheRead: number;
85
+ /** Amount contributed by `cacheWrite`. */
86
+ cacheWrite: number;
87
+ /** Amount contributed by `output`. */
88
+ output: number;
89
+ /** True when at least one attempt had no exact price and the fallback price was applied. */
90
+ estimated: boolean;
91
+ /** Why, when {@link estimated} is true. */
92
+ estimatedReason?: string;
93
+ }
94
+ /**
95
+ * One completed Turn's ledger line — the unit of persistence.
96
+ *
97
+ * `sessionId` + `turn` is the idempotency key: aggregation collapses duplicates
98
+ * keeping the newest line, so a double append can never double-count.
99
+ */
100
+ export interface UsageRecord {
101
+ /** Record schema version this line was written with. */
102
+ v: number;
103
+ /** Local epoch milliseconds of `turn/end`. */
104
+ ts: number;
105
+ /** Local epoch milliseconds of `turn/start`. */
106
+ startedAt: number;
107
+ /** Local epoch milliseconds of `turn/end`. */
108
+ endedAt: number;
109
+ /** Session identity the turn belongs to. */
110
+ sessionId: string;
111
+ /** Turn number inside that session. */
112
+ turn: number;
113
+ /** Session workspace root (`session.header.cwd`), `''` when the header has none. */
114
+ workspace: string;
115
+ /** Display label for {@link workspace} (its basename). */
116
+ workspaceLabel: string;
117
+ /** Agent preset in force for the session, when the header records one. */
118
+ agentPreset: string;
119
+ /** `'subagent'` for a delegated session; `''` for a top-level one. */
120
+ origin: string;
121
+ /** Delegation depth for a subagent session, `0` otherwise. */
122
+ delegationDepth: number;
123
+ /** Parent session id for a forked/delegated session, `''` otherwise. */
124
+ parentSession: string;
125
+ /** Why the turn ended (`completed` / `aborted` / `error` / …). */
126
+ reason: string;
127
+ /** Distinct routes that billed this turn, `provider/model` joined by `,`. */
128
+ routes: string;
129
+ /** Per-attempt usage detail; the sum of these is the record's token total. */
130
+ attempts: UsageAttempt[];
131
+ /** Bucket sums across {@link attempts}. */
132
+ tokens: TokenBuckets;
133
+ /** Prompt + output across {@link attempts}. */
134
+ total: number;
135
+ /** Priced cost, frozen at write time. */
136
+ cost: CostBreakdown;
137
+ }
138
+ /** One selectable value in a filter control. */
139
+ export interface Facet {
140
+ /** Stable filter key. */
141
+ key: string;
142
+ /** Human-facing label. */
143
+ label: string;
144
+ /** Turns contributing to this facet. */
145
+ turns: number;
146
+ /** Tokens contributing to this facet. */
147
+ tokens: number;
148
+ /** Cost contributing to this facet. */
149
+ cost: number;
150
+ /**
151
+ * Route provider id for MODEL facets (`deepseek-account`, `aliyun-bailian`, …).
152
+ *
153
+ * Two providers can serve the same wire model id, so the model label alone is
154
+ * ambiguous; the provider is what makes two same-named rows distinguishable.
155
+ * Absent on the other facet kinds and on payloads from older Host builds.
156
+ */
157
+ provider?: string | undefined;
158
+ }
159
+ /**
160
+ * One raw workspace path inside a (possibly merged) workspace facet.
161
+ *
162
+ * The dashboard merges workspaces by display label (basename) so a project that
163
+ * moved from one platform/path to another reads as one row. The original paths
164
+ * are kept here so the merge stays inspectable and a single path can still be
165
+ * selected exactly.
166
+ */
167
+ export interface WorkspacePathUsage {
168
+ /** Original workspace root, exactly as recorded (`/home/...` or `H:\...`). */
169
+ workspace: string;
170
+ /** Path shape, used only to label the origin in the UI. */
171
+ platform: 'windows' | 'unix' | 'unknown';
172
+ /** Turns recorded under this exact path. */
173
+ turns: number;
174
+ /** Tokens recorded under this exact path. */
175
+ tokens: number;
176
+ /** Cost recorded under this exact path (only when priced in the summary currency). */
177
+ cost: number;
178
+ }
179
+ /**
180
+ * A workspace facet. The base fields describe the MERGED group; `paths` breaks
181
+ * the same figures down per original path.
182
+ *
183
+ * `paths` / `mergedCount` are optional on the wire so a client can also consume
184
+ * a payload from an older Host build that predates the merge.
185
+ */
186
+ export interface WorkspaceFacet extends Facet {
187
+ /** Per-path breakdown, sorted by path; at least one entry from a current Host. */
188
+ paths?: WorkspacePathUsage[] | undefined;
189
+ /** Number of distinct raw paths in this group (`paths.length`); 1 when unknown. */
190
+ mergedCount?: number | undefined;
191
+ }
192
+ /** Per-day aggregate powering the bar charts and the calendar heatmap. */
193
+ export interface DailyPoint {
194
+ /** Local calendar day, `YYYY-MM-DD`. */
195
+ date: string;
196
+ /** Turns completed on this day. */
197
+ turns: number;
198
+ /** Bucket sums for this day. */
199
+ tokens: TokenBuckets;
200
+ /** Prompt + output for this day. */
201
+ total: number;
202
+ /** Priced cost for this day. */
203
+ cost: number;
204
+ /** True when any contributing record carried an estimated price. */
205
+ estimated: boolean;
206
+ /** Why, when every contributing record agrees; `undefined` otherwise. */
207
+ estimatedReason?: string;
208
+ }
209
+ /** Cumulative figures for the active filter, or all-time when unfiltered. */
210
+ export interface Totals {
211
+ /** Turns counted. */
212
+ turns: number;
213
+ /** Bucket sums. */
214
+ tokens: TokenBuckets;
215
+ /** Prompt + output. */
216
+ total: number;
217
+ /** Priced cost. */
218
+ cost: number;
219
+ /** True when any contributing record carried an estimated price. */
220
+ estimated: boolean;
221
+ }
222
+ /** One row in a non-filterable dimension (agent preset, origin, or reason). */
223
+ export interface DimensionUsage {
224
+ /** Stable key. */
225
+ key: string;
226
+ /** Display label. */
227
+ label: string;
228
+ /** Turns in this dimension. */
229
+ turns: number;
230
+ /** Model calls (attempts) in this dimension. */
231
+ calls: number;
232
+ /** Provider-reported total tokens. */
233
+ tokens: number;
234
+ /** Cache-hit input tokens (attempt-level). */
235
+ cacheRead: number;
236
+ /** Cache-miss input tokens (attempt-level). */
237
+ uncachedInput: number;
238
+ /** Output tokens (attempt-level). */
239
+ output: number;
240
+ /** Priced cost in the summary currency. */
241
+ cost: number;
242
+ }
243
+ /** Peak/off-peak usage split (attempt-level). */
244
+ export interface WindowUsage {
245
+ /** Pricing window key. */
246
+ key: 'peak' | 'off-peak' | 'unknown';
247
+ /** Display label. */
248
+ label: string;
249
+ /** Model calls in this window. */
250
+ calls: number;
251
+ /** Provider-reported total tokens. */
252
+ tokens: number;
253
+ /** Priced cost in the summary currency. */
254
+ cost: number;
255
+ }
256
+ /** One histogram bin. */
257
+ export interface CountBin {
258
+ /** Display label. */
259
+ label: string;
260
+ /** Number of items in the bin. */
261
+ count: number;
262
+ }
263
+ /** Activity in one local hour of the day (0–23). */
264
+ export interface HourUsage {
265
+ /** Local hour, 0–23. */
266
+ hour: number;
267
+ /** Turns started in this hour. */
268
+ turns: number;
269
+ /** Model calls settled in this hour. */
270
+ calls: number;
271
+ /** Provider-reported total tokens for the calls. */
272
+ tokens: number;
273
+ /** Priced cost for the calls. */
274
+ cost: number;
275
+ }
276
+ /** Call-efficiency counters for the current filter. */
277
+ export interface CallStats {
278
+ /** Total model calls. */
279
+ total: number;
280
+ /** Turns represented. */
281
+ turns: number;
282
+ /** Turns with more than one call. */
283
+ multiCallTurns: number;
284
+ /** Median calls per turn. */
285
+ medianPerTurn: number;
286
+ /** 90th-percentile calls per turn. */
287
+ p90PerTurn: number;
288
+ /** Maximum calls in one turn. */
289
+ maxPerTurn: number;
290
+ /** Mean calls per turn. */
291
+ averagePerTurn: number;
292
+ /** Median total tokens per turn. */
293
+ tokensPerTurnMedian: number;
294
+ /** Median cost per turn. */
295
+ costPerTurnMedian: number;
296
+ }
297
+ /** Turn-duration statistics. */
298
+ export interface DurationStats {
299
+ /** Median duration in milliseconds. */
300
+ median: number;
301
+ /** 90th-percentile duration in milliseconds. */
302
+ p90: number;
303
+ /** Longest duration in milliseconds. */
304
+ max: number;
305
+ /** Mean duration in milliseconds. */
306
+ average: number;
307
+ /** Turns with a valid duration. */
308
+ samples: number;
309
+ }
310
+ /** Session-level counters for the current filter. */
311
+ export interface SessionStats {
312
+ /** Distinct sessions. */
313
+ count: number;
314
+ /** Mean turns per session. */
315
+ averageTurns: number;
316
+ /** Median turns per session. */
317
+ medianTurns: number;
318
+ /** Median tokens per session. */
319
+ medianTokens: number;
320
+ /** Median cost per session. */
321
+ medianCost: number;
322
+ }
323
+ /**
324
+ * Additional statistics derived only from fields already present in the ledger.
325
+ *
326
+ * Computed on the same workspace/model/provider-filtered record set as
327
+ * {@link SummaryResponse.totals} (all-time under that filter, unaffected by the
328
+ * dashboard's local date range). Optional on the wire so a client can also read
329
+ * a payload from an older Host build.
330
+ */
331
+ export interface Analytics {
332
+ /** Call efficiency. */
333
+ calls: CallStats;
334
+ /** Turn duration statistics. */
335
+ durations: DurationStats;
336
+ /** Calls-per-turn histogram. */
337
+ attemptBins: CountBin[];
338
+ /** Turn-duration histogram. */
339
+ durationBins: CountBin[];
340
+ /** Session statistics. */
341
+ sessions: SessionStats;
342
+ /** Agent-preset breakdown. */
343
+ agents: DimensionUsage[];
344
+ /** Top-level vs subagent breakdown. */
345
+ origins: DimensionUsage[];
346
+ /** Turn-end reason breakdown. */
347
+ reasons: DimensionUsage[];
348
+ /** Peak/off-peak split. */
349
+ windows: WindowUsage[];
350
+ /** Local hour-of-day activity (always 24 entries, 0–23). */
351
+ hours: HourUsage[];
352
+ }
353
+ /** Pricing provenance the dashboard displays so a figure can be traced to its source. */
354
+ export interface PricingProvenance {
355
+ /** Price-table version string. */
356
+ version: string;
357
+ /** Which price era this is, in words. */
358
+ label: string;
359
+ /** Where the numbers came from (the page they were read off). */
360
+ source: string;
361
+ /** Date the numbers were checked against that page. */
362
+ checkedAt: string;
363
+ /** Peak-hour rule in human-readable form. */
364
+ peakRule: string;
365
+ /** Currency every number below is in. */
366
+ currency: Currency;
367
+ /** Tokens one unit of every price buys (1e6: prices are per million tokens). */
368
+ unitTokens: number;
369
+ /**
370
+ * The published rows for {@link currency}, in the order they apply.
371
+ *
372
+ * Sent to the panel so the explanation can show the ACTUAL numbers instead of
373
+ * only a formula: a formula without the prices it multiplies is not something
374
+ * a reader can check.
375
+ */
376
+ rows: readonly PricingRow[];
377
+ /** Peak windows as `HH:MM–HH:MM` in {@link timezoneOffsetMinutes}. */
378
+ peakWindows: readonly string[];
379
+ /** Multiplier applied outside those windows. */
380
+ offPeakRatio: number;
381
+ /** UTC offset, in minutes, the windows are expressed in. */
382
+ timezoneOffsetMinutes: number;
383
+ /** Retired ids billed at another model's prices. */
384
+ aliases: Readonly<Record<string, string>>;
385
+ /**
386
+ * Models whose price comes from local configuration rather than this page.
387
+ *
388
+ * Listed so the panel can say so: an overridden number is NOT the official
389
+ * one, and the reader must not be told otherwise.
390
+ */
391
+ overriddenModels: readonly string[];
392
+ }
393
+ /** One published price row, shown in the panel so a figure is explainable. */
394
+ export interface PricingRow {
395
+ /** Model id this row prices (an id the provider bills under). */
396
+ model: string;
397
+ /** Cache-hit input price per {@link PricingProvenance.unitTokens} tokens. */
398
+ cacheHit: number;
399
+ /** Cache-miss input price per {@link PricingProvenance.unitTokens} tokens. */
400
+ cacheMiss: number;
401
+ /** Output price per {@link PricingProvenance.unitTokens} tokens. */
402
+ output: number;
403
+ /** Instant this row took effect (ISO 8601 with offset). */
404
+ effectiveFrom: string;
405
+ }
406
+ /** Non-fatal conditions the Host reports instead of failing the request. */
407
+ export interface HealthReport {
408
+ /** Ledger lines skipped because they were not valid records. */
409
+ malformedLines: number;
410
+ /** Failed append attempts since process start. */
411
+ writeErrors: number;
412
+ /** Most recent write error message, or `''`. */
413
+ lastWriteError: string;
414
+ /** Records held in the in-process append queue. */
415
+ pendingWrites: number;
416
+ /** Records lost to a repeated append failure (after the single retry). */
417
+ droppedRecords: number;
418
+ /** Turns observed whose usage could not be derived and were therefore not recorded. */
419
+ skippedTurns: number;
420
+ /**
421
+ * Ledger lines written by a NEWER plugin than this build understands.
422
+ *
423
+ * Counted separately from `malformedLines` because they are not corruption:
424
+ * they are data this build cannot yet read, and silently folding them into
425
+ * the malformed count would look like damage.
426
+ */
427
+ unsupportedRecords: number;
428
+ /**
429
+ * Records whose stored cost is in a DIFFERENT currency than the one reported.
430
+ *
431
+ * One harness home can serve profiles configured with different currencies
432
+ * while sharing the single ledger, and a cost figure is only meaningful inside
433
+ * its own currency. Such records still contribute their TOKENS — those are
434
+ * currency-independent — but their money is excluded from every total, and the
435
+ * count is surfaced so the exclusion is never silent.
436
+ */
437
+ currencyMismatches: number;
438
+ /**
439
+ * True when the ledger exceeded the reader's record cap and was truncated.
440
+ *
441
+ * Reported instead of failing: a truncated view with a visible warning beats
442
+ * an empty dashboard that looks like "no usage yet".
443
+ */
444
+ ledgerTruncated: boolean;
445
+ }
446
+ /** Payload of `GET <prefix>/api/summary`. */
447
+ export interface SummaryResponse {
448
+ /** Wire schema version. */
449
+ schemaVersion: number;
450
+ /** Local epoch milliseconds this summary was produced. */
451
+ generatedAt: number;
452
+ /** Plugin version that produced it. */
453
+ pluginVersion: string;
454
+ /** Currency all amounts use. */
455
+ currency: Currency;
456
+ /** Pricing provenance. */
457
+ pricing: PricingProvenance;
458
+ /** Filters actually applied. */
459
+ filters: {
460
+ /** Selected workspace key, or `null` for all. */
461
+ workspace: string | null;
462
+ /** Selected model key (provider/model), or `null` for all. */
463
+ model: string | null;
464
+ /** Selected provider id, or `null` for all. */
465
+ provider: string | null;
466
+ /** Width of the daily window in days. */
467
+ days: number;
468
+ };
469
+ /** Cumulative figures under the active filter. */
470
+ totals: Totals;
471
+ /** Cumulative figures with no filter at all (the headline "累计" row). */
472
+ allTime: Totals;
473
+ /** Selectable filter values, always computed unfiltered. */
474
+ facets: {
475
+ /** Workspace facets (merged by display label), most-used first. */
476
+ workspaces: WorkspaceFacet[];
477
+ /** Model facets (one per provider/model route), most-used first. */
478
+ models: Facet[];
479
+ /** Provider facets (attempt-level), most-used first. */
480
+ providers: Facet[];
481
+ /** Distinct calendar days present in the ledger. */
482
+ activeDays: number;
483
+ /** First day present, `YYYY-MM-DD`, or `''`. */
484
+ firstDay: string;
485
+ /** Last day present, `YYYY-MM-DD`, or `''`. */
486
+ lastDay: string;
487
+ /** Total ledger lines accepted (after de-duplication). */
488
+ records: number;
489
+ };
490
+ /** Daily series over the requested window, oldest first, gaps filled with zeros. */
491
+ daily: DailyPoint[];
492
+ /** Per-model totals under the active filter. */
493
+ byModel: Facet[];
494
+ /** Per-workspace totals under the active filter (merged by display label). */
495
+ byWorkspace: WorkspaceFacet[];
496
+ /**
497
+ * Additional call/agent/outcome statistics for the current filter.
498
+ *
499
+ * Absent only on payloads from a Host build older than this client.
500
+ */
501
+ analytics?: Analytics | undefined;
502
+ /** Degradation counters. */
503
+ health: HealthReport;
504
+ }
505
+ /** Error payload of any `<prefix>/api/*` failure. */
506
+ export interface ApiErrorResponse {
507
+ /** Always `false`; successful payloads carry no `ok` field. */
508
+ ok: false;
509
+ /** Stable machine-readable code. */
510
+ error: string;
511
+ /** Human-readable detail (never contains credentials). */
512
+ message: string;
513
+ }
514
+ /**
515
+ * Report whether a value is a currency this build can price and display.
516
+ * @param value - candidate.
517
+ * @returns true for a supported currency.
518
+ */
519
+ export declare function isCurrency(value: unknown): value is Currency;
520
+ /**
521
+ * Shallow structural check of a summary payload.
522
+ *
523
+ * The dashboard reads a fixed set of containers (`daily`, `facets`, `totals`,
524
+ * `pricing`, both breakdown arrays). Validating just those containers before the
525
+ * type assertion keeps a malformed or half-upgraded Host response from throwing
526
+ * inside the render tree; every deeper field is still read defensively at the
527
+ * call site. It is deliberately shallow: a few thousand daily points are not
528
+ * worth validating field by field on every fetch.
529
+ *
530
+ * @param value - parsed JSON body.
531
+ * @returns true when the payload carries the containers the dashboard reads.
532
+ */
533
+ export declare function isSummaryResponseLike(value: unknown): value is SummaryResponse;
534
+ /** Server-enforced bounds, mirrored by the client's own controls. */
535
+ export declare const API_LIMITS: {
536
+ /** Default daily window. */
537
+ readonly defaultDays: 90;
538
+ /** Maximum daily window the server will serialize. */
539
+ readonly maxDays: 1825;
540
+ /**
541
+ * Largest number of ledger records the reader will hold.
542
+ *
543
+ * The reader streams the ledger, so this bounds MEMORY rather than file size;
544
+ * reaching it sets `HealthReport.ledgerTruncated` and keeps the newest records.
545
+ */
546
+ readonly maxRecords: 500000;
547
+ };
548
+ /** Marker written into backup files exported from the dashboard. */
549
+ export declare const BACKUP_FORMAT: "dsh-token-usage-backup";
550
+ /** Backup envelope version this build writes and can read. */
551
+ export declare const BACKUP_FORMAT_VERSION = 1;
552
+ /** Bounds shared by the Host endpoints and the browser's file picker. */
553
+ export declare const BACKUP_LIMITS: {
554
+ /** Maximum JSON bytes accepted for one export/import operation. */
555
+ readonly maxBytes: number;
556
+ /** Maximum record count accepted from one backup file. */
557
+ readonly maxRecords: 200000;
558
+ };
559
+ /**
560
+ * One self-contained backup file.
561
+ *
562
+ * `records` are the canonical ledger records (validated by the Host's schema
563
+ * readers), so importing on a later plugin version still upgrades through the
564
+ * normal reader table instead of trusting a frozen serialization.
565
+ */
566
+ export interface BackupFile {
567
+ /** Fixed format marker. */
568
+ format: typeof BACKUP_FORMAT;
569
+ /** Envelope version. */
570
+ formatVersion: number;
571
+ /** Export time, epoch ms. */
572
+ exportedAt: number;
573
+ /** Plugin version that produced the file. */
574
+ pluginVersion: string;
575
+ /** Ledger record schema version this build reads/writes. */
576
+ recordSchemaVersion: number;
577
+ /** Number of valid records in {@link records}. */
578
+ recordCount: number;
579
+ /** Canonical ledger records. */
580
+ records: UsageRecord[];
581
+ /** Lines skipped while reading the source ledger. */
582
+ malformedLines: number;
583
+ /** Records from a newer schema than this build understands. */
584
+ unsupportedRecords: number;
585
+ }
586
+ /** Result of importing a backup into an existing ledger. */
587
+ export interface ImportResult {
588
+ /** Records appended. */
589
+ added: number;
590
+ /** Records skipped because their `(sessionId, turn)` already existed. */
591
+ duplicates: number;
592
+ /** Records rejected by the schema reader (the import is rejected before writing). */
593
+ invalid: number;
594
+ /** Total records offered by the file. */
595
+ total: number;
596
+ /** Records with a schema version newer than this build (also rejects the import). */
597
+ unsupported: number;
598
+ }
599
+ /** Counters reported by one backfill scan. */
600
+ export interface BackfillReport {
601
+ /** Session logs successfully read. */
602
+ logsScanned: number;
603
+ /** Session logs that could not be read. */
604
+ logsFailed: number;
605
+ /** Session logs with an unknown filename/format. */
606
+ logsUnknownFormat: number;
607
+ /** Events replayed through the collector. */
608
+ eventsReplayed: number;
609
+ /** Leading inherited events skipped by the cheap pre-filter. */
610
+ inheritedEventsSkipped: number;
611
+ /** Turns the collector closed. */
612
+ turnsSeen: number;
613
+ /** Turns already present in the ledger. */
614
+ turnsAlreadyRecorded: number;
615
+ /** Turns skipped because a fork copied them verbatim. */
616
+ turnsInheritedCopy: number;
617
+ /** Turns the collector could not prove. */
618
+ turnsUndecidable: number;
619
+ /** Turns excluded by the `--since` filter (unused by the UI today). */
620
+ turnsFilteredOut: number;
621
+ /** Turns that can be appended. */
622
+ turnsBackfillable: number;
623
+ /** First backfillable turn end, ISO string or `''`. */
624
+ firstTurn: string;
625
+ /** Last backfillable turn end, ISO string or `''`. */
626
+ lastTurn: string;
627
+ }
628
+ /** Result of a backfill request. */
629
+ export interface BackfillResult {
630
+ /** True when nothing was written (preview). */
631
+ dryRun: boolean;
632
+ /** Records actually appended. */
633
+ written: number;
634
+ /** Scan counters. */
635
+ report: BackfillReport;
636
+ }
637
+ /**
638
+ * Report whether a value is shaped like a backup file.
639
+ *
640
+ * Deliberately shallow: the Host re-validates every record through the schema
641
+ * reader. The browser only needs enough to avoid POSTing an unrelated JSON file.
642
+ *
643
+ * @param value - parsed JSON value.
644
+ * @returns true when the envelope fields are present and sane.
645
+ */
646
+ export declare function isBackupFileLike(value: unknown): value is BackupFile;