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

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 (46) hide show
  1. package/CHANGELOG.md +1067 -0
  2. package/LICENSE +21 -0
  3. package/README.md +237 -2
  4. package/cordis.patch.yml +30 -0
  5. package/lib/client.js +4469 -0
  6. package/lib/host/aggregate.d.ts +132 -0
  7. package/lib/host/aggregate.js +840 -0
  8. package/lib/host/api.d.ts +118 -0
  9. package/lib/host/api.js +346 -0
  10. package/lib/host/backfill.d.ts +54 -0
  11. package/lib/host/backfill.js +265 -0
  12. package/lib/host/collector.d.ts +139 -0
  13. package/lib/host/collector.js +441 -0
  14. package/lib/host/ledger-io.d.ts +125 -0
  15. package/lib/host/ledger-io.js +211 -0
  16. package/lib/host/operation-error.d.ts +22 -0
  17. package/lib/host/operation-error.js +28 -0
  18. package/lib/host/paths.d.ts +35 -0
  19. package/lib/host/paths.js +63 -0
  20. package/lib/host/pricing-module.d.ts +112 -0
  21. package/lib/host/pricing-module.js +63 -0
  22. package/lib/host/pricing-modules/deepseek-2026-09-10.d.ts +31 -0
  23. package/lib/host/pricing-modules/deepseek-2026-09-10.js +67 -0
  24. package/lib/host/pricing-modules/index.d.ts +27 -0
  25. package/lib/host/pricing-modules/index.js +30 -0
  26. package/lib/host/pricing.d.ts +192 -0
  27. package/lib/host/pricing.js +287 -0
  28. package/lib/host/records.d.ts +47 -0
  29. package/lib/host/records.js +116 -0
  30. package/lib/host/runtime-marker.d.ts +67 -0
  31. package/lib/host/runtime-marker.js +71 -0
  32. package/lib/host/schema.d.ts +77 -0
  33. package/lib/host/schema.js +158 -0
  34. package/lib/host/store.d.ts +171 -0
  35. package/lib/host/store.js +337 -0
  36. package/lib/host/workspace-titles.d.ts +38 -0
  37. package/lib/host/workspace-titles.js +136 -0
  38. package/lib/host/zstd.d.ts +41 -0
  39. package/lib/host/zstd.js +134 -0
  40. package/lib/index.d.ts +82 -0
  41. package/lib/index.js +512 -0
  42. package/lib/shared/format.d.ts +415 -0
  43. package/lib/shared/format.js +714 -0
  44. package/lib/shared/protocol.d.ts +646 -0
  45. package/lib/shared/protocol.js +129 -0
  46. package/package.json +85 -4
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Ledger file IO for the backup/import/backfill operations.
3
+ *
4
+ * The dashboard's own reader (`UsageStore`) is bounded and de-duplicated for
5
+ * rendering; a backup must instead capture EVERY valid line, so these helpers
6
+ * read the file directly and keep the canonical records returned by the schema
7
+ * readers. Import/backfill use the same helpers for the duplicate key set, so
8
+ * all three features agree on `(sessionId, turn)`.
9
+ *
10
+ * @module dsh-token-usage-ledger/host/ledger-io
11
+ */
12
+ import { readFile } from 'node:fs/promises';
13
+ import { BACKUP_FORMAT, BACKUP_FORMAT_VERSION, BACKUP_LIMITS, RECORD_SCHEMA_VERSION, } from '../shared/protocol.js';
14
+ import { OperationError } from './operation-error.js';
15
+ import { parseRecordLine, readRecordValue } from './schema.js';
16
+ /**
17
+ * Stable idempotency key for one turn.
18
+ * @param record - ledger record.
19
+ * @returns the key used by the reader and by imports.
20
+ */
21
+ export function recordKey(record) {
22
+ return `${record.sessionId}\u0000${String(record.turn)}`;
23
+ }
24
+ /**
25
+ * Fork fingerprint used by the backfill scanner.
26
+ *
27
+ * A forked session copies its parent's events verbatim, so `(sessionId, turn)`
28
+ * alone cannot recognise that copy (the child has a different session id); the
29
+ * log-assigned timestamps and total token count are copied unchanged.
30
+ *
31
+ * @param turn - turn number.
32
+ * @param startedAt - turn start epoch ms.
33
+ * @param endedAt - turn end epoch ms.
34
+ * @param settleTimes - attempt settlement times.
35
+ * @param total - provider-reported total tokens.
36
+ * @returns the fingerprint string.
37
+ */
38
+ export function fingerprintOfParts(turn, startedAt, endedAt, settleTimes, total) {
39
+ return [turn, startedAt, endedAt, settleTimes.join(','), total].join('|');
40
+ }
41
+ /**
42
+ * Fork fingerprint of one ledger record.
43
+ * @param record - ledger record.
44
+ * @returns the fingerprint string.
45
+ */
46
+ export function fingerprintOf(record) {
47
+ return fingerprintOfParts(record.turn, record.startedAt, record.endedAt, record.attempts.map((attempt) => attempt.at), record.total);
48
+ }
49
+ /**
50
+ * Read every valid record from a ledger file.
51
+ *
52
+ * An absent file is the normal first-run state and yields an empty read; any
53
+ * other IO failure is surfaced as an internal operation error so the caller can
54
+ * answer 500 without exposing the path.
55
+ *
56
+ * @param path - absolute ledger path.
57
+ * @returns the full ledger read.
58
+ */
59
+ export async function readLedgerFile(path) {
60
+ let text;
61
+ try {
62
+ text = await readFile(path, 'utf8');
63
+ }
64
+ catch (error) {
65
+ if (isMissingFile(error)) {
66
+ return { records: [], lines: 0, malformedLines: 0, unsupportedRecords: 0 };
67
+ }
68
+ throw new OperationError(500, 'write-failed', 'could not read the ledger');
69
+ }
70
+ const records = [];
71
+ let lines = 0;
72
+ let malformedLines = 0;
73
+ let unsupportedRecords = 0;
74
+ for (const line of text.split('\n')) {
75
+ if (line.trim().length === 0)
76
+ continue;
77
+ lines += 1;
78
+ const outcome = parseRecordLine(line);
79
+ if (!outcome.ok) {
80
+ if (outcome.reason === 'unsupported-version')
81
+ unsupportedRecords += 1;
82
+ else
83
+ malformedLines += 1;
84
+ continue;
85
+ }
86
+ records.push(outcome.record);
87
+ }
88
+ return { records, lines, malformedLines, unsupportedRecords };
89
+ }
90
+ /**
91
+ * Read the duplicate-tracking views of a ledger.
92
+ * @param path - absolute ledger path.
93
+ * @returns keys/fingerprints plus parse tallies.
94
+ */
95
+ export async function readLedgerKeys(path) {
96
+ const read = await readLedgerFile(path);
97
+ return {
98
+ keys: new Set(read.records.map(recordKey)),
99
+ fingerprints: new Set(read.records.map(fingerprintOf)),
100
+ malformedLines: read.malformedLines,
101
+ unsupportedRecords: read.unsupportedRecords,
102
+ };
103
+ }
104
+ /**
105
+ * Build the downloadable backup envelope from the full ledger.
106
+ * @param path - absolute ledger path.
107
+ * @param pluginVersion - running plugin version.
108
+ * @returns the backup file.
109
+ */
110
+ export async function createBackup(path, pluginVersion) {
111
+ const read = await readLedgerFile(path);
112
+ return {
113
+ format: BACKUP_FORMAT,
114
+ formatVersion: BACKUP_FORMAT_VERSION,
115
+ exportedAt: Date.now(),
116
+ pluginVersion,
117
+ recordSchemaVersion: RECORD_SCHEMA_VERSION,
118
+ recordCount: read.records.length,
119
+ records: read.records,
120
+ malformedLines: read.malformedLines,
121
+ unsupportedRecords: read.unsupportedRecords,
122
+ };
123
+ }
124
+ /**
125
+ * Validate a parsed backup payload.
126
+ *
127
+ * Envelope problems throw `unsupported-format`; record problems are counted and
128
+ * returned so the caller can reject the whole import before writing.
129
+ *
130
+ * @param value - parsed JSON body.
131
+ * @returns accepted records and per-record tallies.
132
+ * @throws OperationError when the envelope itself is unusable.
133
+ */
134
+ export function parseBackup(value) {
135
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
136
+ throw new OperationError(400, 'unsupported-format', 'not a token-usage backup file');
137
+ }
138
+ const raw = value;
139
+ if (raw['format'] !== BACKUP_FORMAT) {
140
+ throw new OperationError(400, 'unsupported-format', 'not a token-usage backup file');
141
+ }
142
+ if (typeof raw['formatVersion'] !== 'number' ||
143
+ !Number.isSafeInteger(raw['formatVersion']) ||
144
+ raw['formatVersion'] > BACKUP_FORMAT_VERSION ||
145
+ raw['formatVersion'] < 1) {
146
+ throw new OperationError(400, 'unsupported-format', 'unsupported backup format version');
147
+ }
148
+ const records = raw['records'];
149
+ if (!Array.isArray(records)) {
150
+ throw new OperationError(400, 'unsupported-format', 'backup has no records array');
151
+ }
152
+ if (records.length > BACKUP_LIMITS.maxRecords) {
153
+ throw new OperationError(413, 'payload-too-large', 'backup contains too many records');
154
+ }
155
+ if (typeof raw['recordCount'] === 'number' && raw['recordCount'] !== records.length) {
156
+ throw new OperationError(400, 'unsupported-format', 'backup record count does not match its records');
157
+ }
158
+ const accepted = [];
159
+ let invalid = 0;
160
+ let unsupported = 0;
161
+ for (const record of records) {
162
+ const outcome = readRecordValue(record);
163
+ if (outcome.ok)
164
+ accepted.push(outcome.record);
165
+ else if (outcome.reason === 'unsupported-version')
166
+ unsupported += 1;
167
+ else
168
+ invalid += 1;
169
+ }
170
+ return { records: accepted, total: records.length, invalid, unsupported };
171
+ }
172
+ /**
173
+ * Select records that are not already present (and de-duplicate the file itself).
174
+ * @param records - validated records from the backup.
175
+ * @param existing - duplicate-tracking view of the current ledger.
176
+ * @returns new records and the duplicate count.
177
+ */
178
+ export function selectNewRecords(records, existing) {
179
+ const seen = new Set(existing.keys);
180
+ const fresh = [];
181
+ let duplicates = 0;
182
+ for (const record of records) {
183
+ const key = recordKey(record);
184
+ if (seen.has(key)) {
185
+ duplicates += 1;
186
+ continue;
187
+ }
188
+ seen.add(key);
189
+ fresh.push(record);
190
+ }
191
+ return { records: fresh, duplicates };
192
+ }
193
+ /**
194
+ * Build the import result object.
195
+ * @param total - records offered by the file.
196
+ * @param added - records appended.
197
+ * @param duplicates - skipped duplicates.
198
+ * @returns the response.
199
+ */
200
+ export function importResult(total, added, duplicates) {
201
+ return { added, duplicates, invalid: 0, total, unsupported: 0 };
202
+ }
203
+ /**
204
+ * Report whether an error is a missing-file error.
205
+ * @param error - thrown value.
206
+ * @returns true for ENOENT.
207
+ */
208
+ function isMissingFile(error) {
209
+ return typeof error === 'object' && error !== null && error.code === 'ENOENT';
210
+ }
211
+ //# sourceMappingURL=ledger-io.js.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Error with an HTTP status/code understood by the plugin's own API layer.
3
+ *
4
+ * The store and the data operations never throw into the conversation path, but
5
+ * the write endpoints need to distinguish "busy" or "bad backup" from an
6
+ * internal failure without exposing internals to the browser.
7
+ *
8
+ * @module dsh-token-usage-ledger/host/operation-error
9
+ */
10
+ /** One error that maps directly to an API response. */
11
+ export declare class OperationError extends Error {
12
+ /** HTTP status to send. */
13
+ readonly status: number;
14
+ /** Stable machine-readable code. */
15
+ readonly code: string;
16
+ /**
17
+ * @param status - HTTP status.
18
+ * @param code - stable error code.
19
+ * @param message - short, user-safe detail (never record contents/paths).
20
+ */
21
+ constructor(status: number, code: string, message: string);
22
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Error with an HTTP status/code understood by the plugin's own API layer.
3
+ *
4
+ * The store and the data operations never throw into the conversation path, but
5
+ * the write endpoints need to distinguish "busy" or "bad backup" from an
6
+ * internal failure without exposing internals to the browser.
7
+ *
8
+ * @module dsh-token-usage-ledger/host/operation-error
9
+ */
10
+ /** One error that maps directly to an API response. */
11
+ export class OperationError extends Error {
12
+ /** HTTP status to send. */
13
+ status;
14
+ /** Stable machine-readable code. */
15
+ code;
16
+ /**
17
+ * @param status - HTTP status.
18
+ * @param code - stable error code.
19
+ * @param message - short, user-safe detail (never record contents/paths).
20
+ */
21
+ constructor(status, code, message) {
22
+ super(message);
23
+ this.name = 'OperationError';
24
+ this.status = status;
25
+ this.code = code;
26
+ }
27
+ }
28
+ //# sourceMappingURL=operation-error.js.map
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Harness-home resolution, reproduced locally instead of imported.
3
+ *
4
+ * `@deepseek-ai/dsh-home-paths` is a published dsh package, but importing it at
5
+ * runtime would make this plugin's load path depend on how the profile's module
6
+ * fallback resolves internal packages — a coupling that can break the plugin on
7
+ * a dsh upgrade. The rule it implements is small and documented (explicit path >
8
+ * `$DSH_HOME` > `~/.dsh`), so it is restated here and covered by tests.
9
+ *
10
+ * @module dsh-token-usage-ledger/host/paths
11
+ */
12
+ /** Directory name of the default harness home under the OS home. */
13
+ export declare const DSH_HOME_DIR_NAME = ".dsh";
14
+ /** Environment variable that overrides the default harness home. */
15
+ export declare const DSH_HOME_ENV = "DSH_HOME";
16
+ /**
17
+ * Resolve the harness home with the harness's own precedence.
18
+ *
19
+ * A blank or whitespace-only `$DSH_HOME` counts as unset, so an empty override
20
+ * never resolves the home to the current working directory.
21
+ *
22
+ * @param configured - explicit override, highest precedence.
23
+ * @param env - environment mapping to read `$DSH_HOME` from.
24
+ * @param home - OS home directory, injectable for tests.
25
+ * @returns an absolute, normalized harness home path.
26
+ */
27
+ export declare function resolveDshHome(configured?: string | undefined, env?: Record<string, string | undefined>, home?: string): string;
28
+ /**
29
+ * Join segments onto the resolved harness home.
30
+ * @param segments - path segments appended to the home.
31
+ * @param configured - explicit harness-home override.
32
+ * @param env - environment mapping to read `$DSH_HOME` from.
33
+ * @returns the joined path.
34
+ */
35
+ export declare function dshHomePath(segments: readonly string[], configured?: string | undefined, env?: Record<string, string | undefined>): string;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Harness-home resolution, reproduced locally instead of imported.
3
+ *
4
+ * `@deepseek-ai/dsh-home-paths` is a published dsh package, but importing it at
5
+ * runtime would make this plugin's load path depend on how the profile's module
6
+ * fallback resolves internal packages — a coupling that can break the plugin on
7
+ * a dsh upgrade. The rule it implements is small and documented (explicit path >
8
+ * `$DSH_HOME` > `~/.dsh`), so it is restated here and covered by tests.
9
+ *
10
+ * @module dsh-token-usage-ledger/host/paths
11
+ */
12
+ import { homedir } from 'node:os';
13
+ import { isAbsolute, join, normalize, resolve } from 'node:path';
14
+ /** Directory name of the default harness home under the OS home. */
15
+ export const DSH_HOME_DIR_NAME = '.dsh';
16
+ /** Environment variable that overrides the default harness home. */
17
+ export const DSH_HOME_ENV = 'DSH_HOME';
18
+ /**
19
+ * Resolve the harness home with the harness's own precedence.
20
+ *
21
+ * A blank or whitespace-only `$DSH_HOME` counts as unset, so an empty override
22
+ * never resolves the home to the current working directory.
23
+ *
24
+ * @param configured - explicit override, highest precedence.
25
+ * @param env - environment mapping to read `$DSH_HOME` from.
26
+ * @param home - OS home directory, injectable for tests.
27
+ * @returns an absolute, normalized harness home path.
28
+ */
29
+ export function resolveDshHome(configured, env = process.env, home = homedir()) {
30
+ const explicit = configured?.trim();
31
+ if (explicit !== undefined && explicit.length > 0)
32
+ return absolutize(explicit, home);
33
+ const fromEnv = env[DSH_HOME_ENV];
34
+ const trimmedEnv = fromEnv?.trim();
35
+ if (trimmedEnv !== undefined && trimmedEnv.length > 0)
36
+ return absolutize(trimmedEnv, home);
37
+ return join(home, DSH_HOME_DIR_NAME);
38
+ }
39
+ /**
40
+ * Join segments onto the resolved harness home.
41
+ * @param segments - path segments appended to the home.
42
+ * @param configured - explicit harness-home override.
43
+ * @param env - environment mapping to read `$DSH_HOME` from.
44
+ * @returns the joined path.
45
+ */
46
+ export function dshHomePath(segments, configured, env = process.env) {
47
+ return join(resolveDshHome(configured, env), ...segments);
48
+ }
49
+ /**
50
+ * Absolutize one configured path, expanding a leading `~`.
51
+ * @param value - configured path, possibly tilde-prefixed.
52
+ * @param home - OS home used for expansion.
53
+ * @returns an absolute normalized path.
54
+ */
55
+ function absolutize(value, home) {
56
+ if (value === '~')
57
+ return home;
58
+ if (value.startsWith('~/') || value.startsWith('~\\')) {
59
+ return normalize(join(home, value.slice(2)));
60
+ }
61
+ return isAbsolute(value) ? normalize(value) : resolve(value);
62
+ }
63
+ //# sourceMappingURL=paths.js.map
@@ -0,0 +1,112 @@
1
+ /**
2
+ * The pricing-module contract: one self-contained description of a price era.
3
+ *
4
+ * A "module" is DATA + RULES, not code: how much each token bucket costs, when
5
+ * those numbers took effect, what the peak windows are, and which retired model
6
+ * ids alias which live ones. The arithmetic that consumes a module lives in
7
+ * `pricing.ts` and never changes when prices do.
8
+ *
9
+ * ## Why this is a separate file per era
10
+ *
11
+ * DeepSeek changes its prices (it has both raised and cut them), so the plugin
12
+ * must be able to acquire a new price table WITHOUT touching the engine and
13
+ * without losing the old one. Adding an era is therefore:
14
+ *
15
+ * 1. add `pricing-modules/<era>.ts` exporting one `PricingModule`;
16
+ * 2. add it to the registry in `pricing-modules/index.ts`;
17
+ * 3. optionally point `config.pricingModule` at it.
18
+ *
19
+ * Older modules are kept, so a deployment can switch back and forth, and
20
+ * `scripts/recompute-cost.mjs` can re-price history under any of them.
21
+ *
22
+ * @module dsh-token-usage-ledger/host/pricing-module
23
+ */
24
+ import type { Currency } from '../shared/protocol.js';
25
+ /**
26
+ * One dated price row for one model, per **one million tokens**.
27
+ *
28
+ * `effectiveFrom` is a full ISO-8601 instant WITH an offset, because official
29
+ * announcements are made in a specific timezone (DeepSeek's are in Beijing
30
+ * time) and a bare date would be ambiguous by up to a day.
31
+ */
32
+ export interface PriceEpoch {
33
+ /** Instant this row takes effect, e.g. `2026-09-10T12:00:00+08:00`. */
34
+ readonly effectiveFrom: string;
35
+ /** Price of a prompt token served from the provider cache. */
36
+ readonly cacheHit: number;
37
+ /** Price of a prompt token NOT served from the provider cache. */
38
+ readonly cacheMiss: number;
39
+ /** Price of one completion token. */
40
+ readonly output: number;
41
+ }
42
+ /** Provenance a module carries so a figure can always be traced to its source. */
43
+ export interface PricingModuleProvenance {
44
+ /** Human-readable source URL. */
45
+ readonly source: string;
46
+ /** Date the numbers were verified against that source. */
47
+ readonly checkedAt: string;
48
+ /** The peak-hour rule, in words. */
49
+ readonly peakRule: string;
50
+ }
51
+ /**
52
+ * One price era: everything needed to price an attempt at a given instant.
53
+ *
54
+ * `timezoneOffsetMinutes` is part of the module rather than of the engine
55
+ * because the schedule is published in a timezone (Beijing for DeepSeek), and a
56
+ * different provider could publish in another one.
57
+ */
58
+ export interface PricingModule {
59
+ /** Stable id, used by `config.pricingModule` and by recompute runs. */
60
+ readonly id: string;
61
+ /** Display label for the dashboard. */
62
+ readonly label: string;
63
+ /** Where these numbers came from. */
64
+ readonly provenance: PricingModuleProvenance;
65
+ /** Peak windows as `[startHour, endHour)` in the module's timezone. */
66
+ readonly peakWindows: readonly (readonly [number, number])[];
67
+ /** Multiplier applied outside the peak windows (`0.5` = "off-peak is half"). */
68
+ readonly offPeakRatio: number;
69
+ /** Offset of the pricing timezone from UTC, in minutes (`480` = UTC+8). */
70
+ readonly timezoneOffsetMinutes: number;
71
+ /**
72
+ * Prices per currency, then per wire model id, then per dated row.
73
+ *
74
+ * Rows need not be sorted; {@link selectEpoch} orders them. An array rather
75
+ * than a single object is what lets one module describe a price CUT without
76
+ * discarding the prices that applied before it.
77
+ */
78
+ readonly prices: Readonly<Record<Currency, Readonly<Record<string, readonly PriceEpoch[]>>>>;
79
+ /**
80
+ * Retired ids that resolve to another model's row.
81
+ *
82
+ * DeepSeek keeps serving retired names and bills them at the successor's
83
+ * price, so they are aliases rather than rows of their own.
84
+ */
85
+ readonly aliases: Readonly<Record<string, string>>;
86
+ /** Model id whose prices stand in for an unknown model. */
87
+ readonly fallbackModel: string;
88
+ }
89
+ /** The row selected for one instant, plus how confident that selection is. */
90
+ export interface SelectedEpoch {
91
+ /** The price row in force. */
92
+ readonly epoch: PriceEpoch;
93
+ /**
94
+ * True when the instant predates EVERY row in the module, so the earliest
95
+ * known row was used as a stand-in. The figure is then an approximation, and
96
+ * callers must say so rather than present it as exact.
97
+ */
98
+ readonly beforeFirstKnownPrice: boolean;
99
+ }
100
+ /**
101
+ * Pick the price row in force at one instant.
102
+ *
103
+ * The last row whose `effectiveFrom` is at or before `at` wins — the standard
104
+ * "as of" reading of a dated table. An instant older than every row selects the
105
+ * EARLIEST row and flags it, because refusing to price would lose real usage
106
+ * while silently pricing it as exact would overstate confidence.
107
+ *
108
+ * @param rows - the model's dated rows, in any order.
109
+ * @param at - instant to price at, in epoch milliseconds.
110
+ * @returns the selected row, or undefined when there are no rows.
111
+ */
112
+ export declare function selectEpoch(rows: readonly PriceEpoch[] | undefined, at: number): SelectedEpoch | undefined;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The pricing-module contract: one self-contained description of a price era.
3
+ *
4
+ * A "module" is DATA + RULES, not code: how much each token bucket costs, when
5
+ * those numbers took effect, what the peak windows are, and which retired model
6
+ * ids alias which live ones. The arithmetic that consumes a module lives in
7
+ * `pricing.ts` and never changes when prices do.
8
+ *
9
+ * ## Why this is a separate file per era
10
+ *
11
+ * DeepSeek changes its prices (it has both raised and cut them), so the plugin
12
+ * must be able to acquire a new price table WITHOUT touching the engine and
13
+ * without losing the old one. Adding an era is therefore:
14
+ *
15
+ * 1. add `pricing-modules/<era>.ts` exporting one `PricingModule`;
16
+ * 2. add it to the registry in `pricing-modules/index.ts`;
17
+ * 3. optionally point `config.pricingModule` at it.
18
+ *
19
+ * Older modules are kept, so a deployment can switch back and forth, and
20
+ * `scripts/recompute-cost.mjs` can re-price history under any of them.
21
+ *
22
+ * @module dsh-token-usage-ledger/host/pricing-module
23
+ */
24
+ /**
25
+ * Pick the price row in force at one instant.
26
+ *
27
+ * The last row whose `effectiveFrom` is at or before `at` wins — the standard
28
+ * "as of" reading of a dated table. An instant older than every row selects the
29
+ * EARLIEST row and flags it, because refusing to price would lose real usage
30
+ * while silently pricing it as exact would overstate confidence.
31
+ *
32
+ * @param rows - the model's dated rows, in any order.
33
+ * @param at - instant to price at, in epoch milliseconds.
34
+ * @returns the selected row, or undefined when there are no rows.
35
+ */
36
+ export function selectEpoch(rows, at) {
37
+ if (rows === undefined || rows.length === 0)
38
+ return undefined;
39
+ let best;
40
+ let bestAt = Number.NEGATIVE_INFINITY;
41
+ let earliest;
42
+ let earliestAt = Number.POSITIVE_INFINITY;
43
+ for (const row of rows) {
44
+ const from = Date.parse(row.effectiveFrom);
45
+ // An unparseable timestamp must not silently win or lose a comparison.
46
+ if (!Number.isFinite(from))
47
+ continue;
48
+ if (from <= at && from > bestAt) {
49
+ best = row;
50
+ bestAt = from;
51
+ }
52
+ if (from < earliestAt) {
53
+ earliest = row;
54
+ earliestAt = from;
55
+ }
56
+ }
57
+ if (best !== undefined)
58
+ return { epoch: best, beforeFirstKnownPrice: false };
59
+ if (earliest === undefined)
60
+ return undefined;
61
+ return { epoch: earliest, beforeFirstKnownPrice: true };
62
+ }
63
+ //# sourceMappingURL=pricing-module.js.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Price era `deepseek-2026-09-10` — the DeepSeek API price list that took effect
3
+ * at 2026-09-10 12:00 Beijing time (04:00 UTC).
4
+ *
5
+ * **This is the one file to edit when DeepSeek changes its prices.** Add a new
6
+ * dated row to `prices` (do not delete the old one: history priced under the old
7
+ * number must stay explainable), or — for a change that also alters the peak
8
+ * schedule — copy this file to a new module id and register it, keeping this one
9
+ * intact so a deployment can switch back.
10
+ *
11
+ * Verified 2026-09-13 against:
12
+ * - <https://api-docs.deepseek.com/quick_start/pricing> (USD)
13
+ * - <https://api-docs.deepseek.com/zh-cn/quick_start/pricing> (CNY)
14
+ *
15
+ * The two pages publish SEPARATE tables (they are not conversions of one
16
+ * another: 0.04/0.006 ≈ 6.67 while 9.0/1.32 ≈ 6.82), which is why the currency
17
+ * is part of the module rather than derived from an exchange rate.
18
+ *
19
+ * @module dsh-token-usage-ledger/host/pricing-modules/deepseek-2026-09-10
20
+ */
21
+ import type { PricingModule } from '../pricing-module.js';
22
+ /**
23
+ * The module.
24
+ *
25
+ * Only one dated row exists per model: the numbers published for the 2026-09-10
26
+ * tier. Prices from BEFORE that tier are not published on the current page, so
27
+ * an attempt older than {@link EFFECTIVE} is priced from this row and flagged
28
+ * `beforeFirstKnownPrice` — visible as an estimated figure rather than passed
29
+ * off as exact.
30
+ */
31
+ export declare const deepseek20260910: PricingModule;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Price era `deepseek-2026-09-10` — the DeepSeek API price list that took effect
3
+ * at 2026-09-10 12:00 Beijing time (04:00 UTC).
4
+ *
5
+ * **This is the one file to edit when DeepSeek changes its prices.** Add a new
6
+ * dated row to `prices` (do not delete the old one: history priced under the old
7
+ * number must stay explainable), or — for a change that also alters the peak
8
+ * schedule — copy this file to a new module id and register it, keeping this one
9
+ * intact so a deployment can switch back.
10
+ *
11
+ * Verified 2026-09-13 against:
12
+ * - <https://api-docs.deepseek.com/quick_start/pricing> (USD)
13
+ * - <https://api-docs.deepseek.com/zh-cn/quick_start/pricing> (CNY)
14
+ *
15
+ * The two pages publish SEPARATE tables (they are not conversions of one
16
+ * another: 0.04/0.006 ≈ 6.67 while 9.0/1.32 ≈ 6.82), which is why the currency
17
+ * is part of the module rather than derived from an exchange rate.
18
+ *
19
+ * @module dsh-token-usage-ledger/host/pricing-modules/deepseek-2026-09-10
20
+ */
21
+ /** Instant the 2026-09-10 price list took effect (Beijing 12:00). */
22
+ const EFFECTIVE = '2026-09-10T12:00:00+08:00';
23
+ /** Peak-hour windows: Beijing 09:00–12:00 and 14:00–18:00, weekdays only. */
24
+ const PEAK_WINDOWS = [
25
+ [9, 12],
26
+ [14, 18],
27
+ ];
28
+ /**
29
+ * The module.
30
+ *
31
+ * Only one dated row exists per model: the numbers published for the 2026-09-10
32
+ * tier. Prices from BEFORE that tier are not published on the current page, so
33
+ * an attempt older than {@link EFFECTIVE} is priced from this row and flagged
34
+ * `beforeFirstKnownPrice` — visible as an estimated figure rather than passed
35
+ * off as exact.
36
+ */
37
+ export const deepseek20260910 = {
38
+ id: 'deepseek-2026-09-10',
39
+ label: 'DeepSeek 2026-09-10 价目',
40
+ provenance: {
41
+ source: 'https://api-docs.deepseek.com/quick_start/pricing',
42
+ checkedAt: '2026-09-13',
43
+ peakRule: '周一至周五 09:00–12:00 / 14:00–18:00(北京时间 UTC+8)为高峰,其余时段(含周末)按 50% 计价',
44
+ },
45
+ peakWindows: PEAK_WINDOWS,
46
+ offPeakRatio: 0.5,
47
+ timezoneOffsetMinutes: 480,
48
+ prices: {
49
+ CNY: {
50
+ 'deepseek-flash': [{ effectiveFrom: EFFECTIVE, cacheHit: 0.04, cacheMiss: 2, output: 8 }],
51
+ 'deepseek-v4-pro': [{ effectiveFrom: EFFECTIVE, cacheHit: 0.3, cacheMiss: 9, output: 27 }],
52
+ },
53
+ USD: {
54
+ 'deepseek-flash': [{ effectiveFrom: EFFECTIVE, cacheHit: 0.006, cacheMiss: 0.3, output: 1.2 }],
55
+ 'deepseek-v4-pro': [{ effectiveFrom: EFFECTIVE, cacheHit: 0.044, cacheMiss: 1.32, output: 3.96 }],
56
+ },
57
+ },
58
+ // Retired ids the provider still accepts and bills at the successor's price.
59
+ aliases: {
60
+ 'deepseek-v4-flash': 'deepseek-flash',
61
+ 'deepseek-v4-flash-vision-exp': 'deepseek-flash',
62
+ 'deepseek-chat': 'deepseek-flash',
63
+ 'deepseek-reasoner': 'deepseek-flash',
64
+ },
65
+ fallbackModel: 'deepseek-flash',
66
+ };
67
+ //# sourceMappingURL=deepseek-2026-09-10.js.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The pricing-module registry — the one list to extend when a price era is added.
3
+ *
4
+ * Adding a price era is deliberately a two-line change in this repository:
5
+ * create `pricing-modules/<era>.ts` and import it below. Nothing else in the
6
+ * engine knows how many eras exist or which is current, and every earlier module
7
+ * stays registered so a deployment can switch back with `config.pricingModule`
8
+ * and `scripts/recompute-cost.mjs` can re-price history under any of them.
9
+ *
10
+ * @module dsh-token-usage-ledger/host/pricing-modules
11
+ */
12
+ import type { PricingModule } from '../pricing-module.js';
13
+ /**
14
+ * Every price era this build can price with, in the order they are offered.
15
+ *
16
+ * The FIRST entry is the default for a deployment that does not set
17
+ * `config.pricingModule`; keep the newest era first when appending.
18
+ */
19
+ export declare const PRICING_MODULES: readonly PricingModule[];
20
+ /** Id of the module used when configuration names none. */
21
+ export declare const DEFAULT_PRICING_MODULE_ID: string;
22
+ /**
23
+ * Look up a price era by id.
24
+ * @param id - module id, e.g. `deepseek-2026-09-10`.
25
+ * @returns the module, or undefined when this build does not carry it.
26
+ */
27
+ export declare function pricingModuleById(id: string): PricingModule | undefined;