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.
- package/CHANGELOG.md +1081 -0
- package/LICENSE +21 -0
- package/README.md +247 -2
- package/cordis.patch.yml +30 -0
- package/docs/token-usage-image01.png +0 -0
- package/docs/token-usage-image02.png +0 -0
- package/lib/client.js +4469 -0
- package/lib/host/aggregate.d.ts +132 -0
- package/lib/host/aggregate.js +840 -0
- package/lib/host/api.d.ts +118 -0
- package/lib/host/api.js +346 -0
- package/lib/host/backfill.d.ts +54 -0
- package/lib/host/backfill.js +265 -0
- package/lib/host/collector.d.ts +139 -0
- package/lib/host/collector.js +441 -0
- package/lib/host/ledger-io.d.ts +125 -0
- package/lib/host/ledger-io.js +211 -0
- package/lib/host/operation-error.d.ts +22 -0
- package/lib/host/operation-error.js +28 -0
- package/lib/host/paths.d.ts +35 -0
- package/lib/host/paths.js +63 -0
- package/lib/host/pricing-module.d.ts +112 -0
- package/lib/host/pricing-module.js +63 -0
- package/lib/host/pricing-modules/deepseek-2026-09-10.d.ts +31 -0
- package/lib/host/pricing-modules/deepseek-2026-09-10.js +67 -0
- package/lib/host/pricing-modules/index.d.ts +27 -0
- package/lib/host/pricing-modules/index.js +30 -0
- package/lib/host/pricing.d.ts +192 -0
- package/lib/host/pricing.js +287 -0
- package/lib/host/records.d.ts +47 -0
- package/lib/host/records.js +116 -0
- package/lib/host/runtime-marker.d.ts +67 -0
- package/lib/host/runtime-marker.js +71 -0
- package/lib/host/schema.d.ts +77 -0
- package/lib/host/schema.js +158 -0
- package/lib/host/store.d.ts +171 -0
- package/lib/host/store.js +337 -0
- package/lib/host/workspace-titles.d.ts +38 -0
- package/lib/host/workspace-titles.js +136 -0
- package/lib/host/zstd.d.ts +41 -0
- package/lib/host/zstd.js +134 -0
- package/lib/index.d.ts +82 -0
- package/lib/index.js +512 -0
- package/lib/shared/format.d.ts +415 -0
- package/lib/shared/format.js +714 -0
- package/lib/shared/protocol.d.ts +646 -0
- package/lib/shared/protocol.js +129 -0
- package/package.json +87 -4
|
@@ -0,0 +1,30 @@
|
|
|
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 { deepseek20260910 } from './deepseek-2026-09-10.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 const PRICING_MODULES = [deepseek20260910];
|
|
20
|
+
/** Id of the module used when configuration names none. */
|
|
21
|
+
export const DEFAULT_PRICING_MODULE_ID = PRICING_MODULES[0]?.id ?? '';
|
|
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 function pricingModuleById(id) {
|
|
28
|
+
return PRICING_MODULES.find((module) => module.id === id);
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pricing ENGINE: turns a {@link PricingModule} (data) plus configuration
|
|
3
|
+
* into a per-attempt amount.
|
|
4
|
+
*
|
|
5
|
+
* The split is deliberate. Prices change; arithmetic does not. Everything the
|
|
6
|
+
* engine needs to know about a price era arrives through the module, so adding
|
|
7
|
+
* or switching an era never touches this file — a price era lives in
|
|
8
|
+
* `pricing-modules/`.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-token-usage-ledger/host/pricing
|
|
11
|
+
*/
|
|
12
|
+
import type { CostBreakdown, Currency, PricingProvenance, TokenBuckets } from '../shared/protocol.js';
|
|
13
|
+
import { type PricingModule } from './pricing-module.js';
|
|
14
|
+
export { PRICING_MODULES, pricingModuleById } from './pricing-modules/index.js';
|
|
15
|
+
export type { PriceEpoch, PricingModule, PricingModuleProvenance } from './pricing-module.js';
|
|
16
|
+
export { selectEpoch } from './pricing-module.js';
|
|
17
|
+
/** Peak-hour prices for one model, per one million tokens, in one currency. */
|
|
18
|
+
export interface ModelPrices {
|
|
19
|
+
/** Price of a prompt token served from the provider cache. */
|
|
20
|
+
cacheHit: number;
|
|
21
|
+
/** Price of a prompt token NOT served from cache. */
|
|
22
|
+
cacheMiss: number;
|
|
23
|
+
/** Price of one completion token. */
|
|
24
|
+
output: number;
|
|
25
|
+
}
|
|
26
|
+
/** Which half of the schedule one instant falls into. */
|
|
27
|
+
export type PricingWindow = 'peak' | 'off-peak';
|
|
28
|
+
/** Why a figure is an estimate rather than a direct reading of a price row. */
|
|
29
|
+
export type EstimatedReason =
|
|
30
|
+
/** No price row matched the model at all, so a zero amount was recorded. */
|
|
31
|
+
'no-price-row'
|
|
32
|
+
/** The attempt predates every published price row of the module. */
|
|
33
|
+
| 'before-first-known-price'
|
|
34
|
+
/**
|
|
35
|
+
* The model has no row of its own, so the module's fallback model priced it.
|
|
36
|
+
*
|
|
37
|
+
* The NUMBER is exact for that fallback row; the ATTRIBUTION is the guess, and
|
|
38
|
+
* presenting it as an exact figure for this model would overstate confidence.
|
|
39
|
+
*/
|
|
40
|
+
| 'unknown-model';
|
|
41
|
+
/** The effective rule: a price module plus the deployment's own adjustments. */
|
|
42
|
+
export interface PricingRule {
|
|
43
|
+
/** The price era in force. */
|
|
44
|
+
readonly module: PricingModule;
|
|
45
|
+
/** Currency every amount is expressed in. */
|
|
46
|
+
readonly currency: Currency;
|
|
47
|
+
/** Multiplier applied outside peak hours. */
|
|
48
|
+
readonly offPeakRatio: number;
|
|
49
|
+
/** Pricing-timezone offset from UTC, in minutes. */
|
|
50
|
+
readonly peakOffsetMinutes: number;
|
|
51
|
+
/** Model id whose prices stand in for an unknown model. */
|
|
52
|
+
readonly fallbackModel: string;
|
|
53
|
+
/**
|
|
54
|
+
* Date-less price overrides from configuration.
|
|
55
|
+
*
|
|
56
|
+
* They win at EVERY instant, because that is the only reading a date-less
|
|
57
|
+
* number can have. A deployment that needs date awareness belongs in a module
|
|
58
|
+
* (`pricing-modules/`), where rows carry their own `effectiveFrom`.
|
|
59
|
+
*/
|
|
60
|
+
readonly overrides: Readonly<Record<string, ModelPrices>>;
|
|
61
|
+
}
|
|
62
|
+
/** Which route produced a model's prices. */
|
|
63
|
+
export type PriceRoute =
|
|
64
|
+
/** A date-less configuration override. */
|
|
65
|
+
'override'
|
|
66
|
+
/** The model's own dated rows. */
|
|
67
|
+
| 'model'
|
|
68
|
+
/** A retired id resolved through the module's alias table. */
|
|
69
|
+
| 'alias'
|
|
70
|
+
/** The module's fallback model stood in for an unknown id. */
|
|
71
|
+
| 'fallback';
|
|
72
|
+
/** Prices resolved for one model at one instant. */
|
|
73
|
+
export interface ResolvedPrice {
|
|
74
|
+
/** Per-million-token prices in force. */
|
|
75
|
+
readonly prices: ModelPrices;
|
|
76
|
+
/** The dated row that supplied them, or `''` for a configuration override. */
|
|
77
|
+
readonly effectiveFrom: string;
|
|
78
|
+
/** Which route produced them. */
|
|
79
|
+
readonly route: PriceRoute;
|
|
80
|
+
/** True when the figure is an approximation. */
|
|
81
|
+
readonly estimated: boolean;
|
|
82
|
+
/** Why it is an approximation. */
|
|
83
|
+
readonly estimatedReason: EstimatedReason | undefined;
|
|
84
|
+
}
|
|
85
|
+
/** Priced outcome for one attempt. */
|
|
86
|
+
export interface AttemptPrice {
|
|
87
|
+
/** Amount for this attempt, in the rule's currency. */
|
|
88
|
+
amount: number;
|
|
89
|
+
/** Amount contributed by the uncached prompt bucket. */
|
|
90
|
+
uncachedInput: number;
|
|
91
|
+
/** Amount contributed by the cache-read bucket. */
|
|
92
|
+
cacheRead: number;
|
|
93
|
+
/** Amount contributed by the cache-write bucket. */
|
|
94
|
+
cacheWrite: number;
|
|
95
|
+
/** Amount contributed by the output bucket. */
|
|
96
|
+
output: number;
|
|
97
|
+
/** Window the attempt was billed under. */
|
|
98
|
+
window: PricingWindow;
|
|
99
|
+
/** True when no exact row applied. */
|
|
100
|
+
estimated: boolean;
|
|
101
|
+
/** Why, when {@link estimated} is true. */
|
|
102
|
+
estimatedReason: EstimatedReason | undefined;
|
|
103
|
+
/** The dated row used, or `''` for a configuration override. */
|
|
104
|
+
effectiveFrom: string;
|
|
105
|
+
}
|
|
106
|
+
/** The bucket subset pricing reads; `reasoning` is a subset of `output`. */
|
|
107
|
+
export type TokenBucketsLike = Pick<TokenBuckets, 'uncachedInput' | 'cacheRead' | 'cacheWrite' | 'output'>;
|
|
108
|
+
/**
|
|
109
|
+
* Classify one instant into the peak/off-peak schedule.
|
|
110
|
+
*
|
|
111
|
+
* The decision reads the wall clock of the MODULE's timezone (Beijing for the
|
|
112
|
+
* DeepSeek modules) rather than the host's local zone, so a server anywhere
|
|
113
|
+
* prices identically. Weekends are entirely off-peak, matching the published
|
|
114
|
+
* rule that only weekday business hours are peak.
|
|
115
|
+
*
|
|
116
|
+
* @param epochMs - instant to classify.
|
|
117
|
+
* @param rule - rule supplying the timezone offset and windows.
|
|
118
|
+
* @returns the window the instant belongs to.
|
|
119
|
+
*/
|
|
120
|
+
export declare function classifyWindow(epochMs: number, rule: PricingRule): PricingWindow;
|
|
121
|
+
/**
|
|
122
|
+
* Resolve the prices billed for one wire model id at one instant.
|
|
123
|
+
*
|
|
124
|
+
* Order: the deployment's date-less override, then the module's own dated rows
|
|
125
|
+
* for the id, then its alias target, then the fallback model. `Object.hasOwn`
|
|
126
|
+
* rather than a truthiness test, because the id comes off the wire and
|
|
127
|
+
* `prices['constructor']` would otherwise resolve through the prototype chain.
|
|
128
|
+
*
|
|
129
|
+
* @param model - wire model id.
|
|
130
|
+
* @param at - instant to price at, in epoch milliseconds.
|
|
131
|
+
* @param rule - rule in force.
|
|
132
|
+
* @returns the resolved prices, or undefined when nothing matches.
|
|
133
|
+
*/
|
|
134
|
+
export declare function resolvePrices(model: string, at: number, rule: PricingRule): ResolvedPrice | undefined;
|
|
135
|
+
/**
|
|
136
|
+
* Resolve prices for one model at the current instant.
|
|
137
|
+
* @param model - wire model id.
|
|
138
|
+
* @param rule - rule in force.
|
|
139
|
+
* @returns the prices in force now, or undefined when nothing matches.
|
|
140
|
+
*/
|
|
141
|
+
export declare function pricesForModel(model: string, rule: PricingRule): ModelPrices | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* Build the effective pricing rule.
|
|
144
|
+
*
|
|
145
|
+
* @param options - module plus the deployment's adjustments.
|
|
146
|
+
* @returns the rule to price with.
|
|
147
|
+
* @throws when neither the requested module nor the default exists.
|
|
148
|
+
*/
|
|
149
|
+
export declare function buildPricingRule(options: {
|
|
150
|
+
module?: PricingModule | undefined;
|
|
151
|
+
currency: Currency;
|
|
152
|
+
overrides?: Readonly<Record<string, ModelPrices>> | undefined;
|
|
153
|
+
offPeakRatio?: number | undefined;
|
|
154
|
+
peakOffsetMinutes?: number | undefined;
|
|
155
|
+
fallbackModel?: string | undefined;
|
|
156
|
+
}): PricingRule;
|
|
157
|
+
/**
|
|
158
|
+
* Price exactly one attempt.
|
|
159
|
+
*
|
|
160
|
+
* Extracted so a record can keep a per-attempt amount — which is what makes a
|
|
161
|
+
* model-filtered view exact rather than apportioned — while the record aggregate
|
|
162
|
+
* is built from the very same arithmetic.
|
|
163
|
+
*
|
|
164
|
+
* @param tokens - provider-reported buckets.
|
|
165
|
+
* @param model - wire model id of the attempt's route.
|
|
166
|
+
* @param at - settle instant, which selects BOTH the price row and the window.
|
|
167
|
+
* @param rule - rule in force.
|
|
168
|
+
* @returns the priced attempt, or undefined when no price row matches at all.
|
|
169
|
+
*/
|
|
170
|
+
export declare function priceAttempt(tokens: TokenBucketsLike, model: string, at: number, rule: PricingRule): AttemptPrice | undefined;
|
|
171
|
+
/**
|
|
172
|
+
* Price all attempts of one Turn.
|
|
173
|
+
*
|
|
174
|
+
* Each attempt is priced under the window AND the price row of its own settle
|
|
175
|
+
* time, so a turn that straddles a schedule boundary — or a price change — is
|
|
176
|
+
* never mispriced wholesale.
|
|
177
|
+
*
|
|
178
|
+
* @param attempts - billed attempts with their routes and timestamps.
|
|
179
|
+
* @param rule - rule in force.
|
|
180
|
+
* @returns the frozen cost breakdown for the record.
|
|
181
|
+
*/
|
|
182
|
+
export declare function computeCost(attempts: readonly {
|
|
183
|
+
tokens: TokenBucketsLike;
|
|
184
|
+
model: string;
|
|
185
|
+
at: number;
|
|
186
|
+
}[], rule: PricingRule): CostBreakdown;
|
|
187
|
+
/**
|
|
188
|
+
* Report the provenance of a rule's price era, for display.
|
|
189
|
+
* @param rule - rule in force.
|
|
190
|
+
* @returns the provenance block the dashboard shows, tagged with the module id.
|
|
191
|
+
*/
|
|
192
|
+
export declare function provenanceOf(rule: PricingRule): PricingProvenance;
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pricing ENGINE: turns a {@link PricingModule} (data) plus configuration
|
|
3
|
+
* into a per-attempt amount.
|
|
4
|
+
*
|
|
5
|
+
* The split is deliberate. Prices change; arithmetic does not. Everything the
|
|
6
|
+
* engine needs to know about a price era arrives through the module, so adding
|
|
7
|
+
* or switching an era never touches this file — a price era lives in
|
|
8
|
+
* `pricing-modules/`.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-token-usage-ledger/host/pricing
|
|
11
|
+
*/
|
|
12
|
+
import { PRICE_UNIT } from '../shared/format.js';
|
|
13
|
+
import { selectEpoch } from './pricing-module.js';
|
|
14
|
+
import { DEFAULT_PRICING_MODULE_ID, pricingModuleById } from './pricing-modules/index.js';
|
|
15
|
+
export { PRICING_MODULES, pricingModuleById } from './pricing-modules/index.js';
|
|
16
|
+
export { selectEpoch } from './pricing-module.js';
|
|
17
|
+
/** Milliseconds in one minute. */
|
|
18
|
+
const MINUTE_MS = 60_000;
|
|
19
|
+
/**
|
|
20
|
+
* Classify one instant into the peak/off-peak schedule.
|
|
21
|
+
*
|
|
22
|
+
* The decision reads the wall clock of the MODULE's timezone (Beijing for the
|
|
23
|
+
* DeepSeek modules) rather than the host's local zone, so a server anywhere
|
|
24
|
+
* prices identically. Weekends are entirely off-peak, matching the published
|
|
25
|
+
* rule that only weekday business hours are peak.
|
|
26
|
+
*
|
|
27
|
+
* @param epochMs - instant to classify.
|
|
28
|
+
* @param rule - rule supplying the timezone offset and windows.
|
|
29
|
+
* @returns the window the instant belongs to.
|
|
30
|
+
*/
|
|
31
|
+
export function classifyWindow(epochMs, rule) {
|
|
32
|
+
const shifted = new Date(epochMs + rule.peakOffsetMinutes * MINUTE_MS);
|
|
33
|
+
const dayOfWeek = shifted.getUTCDay();
|
|
34
|
+
// 0 = Sunday, 6 = Saturday: both fall entirely outside the peak windows.
|
|
35
|
+
if (dayOfWeek === 0 || dayOfWeek === 6)
|
|
36
|
+
return 'off-peak';
|
|
37
|
+
const minutes = shifted.getUTCHours() * 60 + shifted.getUTCMinutes();
|
|
38
|
+
for (const [startHour, endHour] of rule.module.peakWindows) {
|
|
39
|
+
if (minutes >= startHour * 60 && minutes < endHour * 60)
|
|
40
|
+
return 'peak';
|
|
41
|
+
}
|
|
42
|
+
return 'off-peak';
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Resolve the prices billed for one wire model id at one instant.
|
|
46
|
+
*
|
|
47
|
+
* Order: the deployment's date-less override, then the module's own dated rows
|
|
48
|
+
* for the id, then its alias target, then the fallback model. `Object.hasOwn`
|
|
49
|
+
* rather than a truthiness test, because the id comes off the wire and
|
|
50
|
+
* `prices['constructor']` would otherwise resolve through the prototype chain.
|
|
51
|
+
*
|
|
52
|
+
* @param model - wire model id.
|
|
53
|
+
* @param at - instant to price at, in epoch milliseconds.
|
|
54
|
+
* @param rule - rule in force.
|
|
55
|
+
* @returns the resolved prices, or undefined when nothing matches.
|
|
56
|
+
*/
|
|
57
|
+
export function resolvePrices(model, at, rule) {
|
|
58
|
+
const override = ownEntry(rule.overrides, model);
|
|
59
|
+
if (override !== undefined) {
|
|
60
|
+
return {
|
|
61
|
+
prices: override,
|
|
62
|
+
effectiveFrom: '',
|
|
63
|
+
route: 'override',
|
|
64
|
+
estimated: false,
|
|
65
|
+
estimatedReason: undefined,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
const direct = ownEntry(rule.module.prices[rule.currency], model);
|
|
69
|
+
if (direct !== undefined)
|
|
70
|
+
return fromEpochs(direct, at, 'model');
|
|
71
|
+
const alias = ownEntry(rule.module.aliases, model);
|
|
72
|
+
if (alias !== undefined) {
|
|
73
|
+
const aliased = ownEntry(rule.module.prices[rule.currency], alias);
|
|
74
|
+
if (aliased !== undefined)
|
|
75
|
+
return fromEpochs(aliased, at, 'alias');
|
|
76
|
+
}
|
|
77
|
+
const fallback = ownEntry(rule.module.prices[rule.currency], rule.fallbackModel);
|
|
78
|
+
if (fallback !== undefined)
|
|
79
|
+
return fromEpochs(fallback, at, 'fallback');
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Resolve prices for one model at the current instant.
|
|
84
|
+
* @param model - wire model id.
|
|
85
|
+
* @param rule - rule in force.
|
|
86
|
+
* @returns the prices in force now, or undefined when nothing matches.
|
|
87
|
+
*/
|
|
88
|
+
export function pricesForModel(model, rule) {
|
|
89
|
+
return resolvePrices(model, Date.now(), rule)?.prices;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Select and project one model's dated rows.
|
|
93
|
+
* @param rows - dated rows.
|
|
94
|
+
* @param at - instant to price at.
|
|
95
|
+
* @returns the resolved price, or undefined when no row parses.
|
|
96
|
+
*/
|
|
97
|
+
function fromEpochs(rows, at, route) {
|
|
98
|
+
const selected = selectEpoch(rows, at);
|
|
99
|
+
if (selected === undefined)
|
|
100
|
+
return undefined;
|
|
101
|
+
// Two independent reasons to call a figure an estimate. A model that has no
|
|
102
|
+
// row of its own is the stronger one — the operator's question is "is this my
|
|
103
|
+
// model's price?", and "the row is older than my usage" is secondary to that.
|
|
104
|
+
const reason = route === 'fallback'
|
|
105
|
+
? 'unknown-model'
|
|
106
|
+
: selected.beforeFirstKnownPrice
|
|
107
|
+
? 'before-first-known-price'
|
|
108
|
+
: undefined;
|
|
109
|
+
return {
|
|
110
|
+
prices: {
|
|
111
|
+
cacheHit: selected.epoch.cacheHit,
|
|
112
|
+
cacheMiss: selected.epoch.cacheMiss,
|
|
113
|
+
output: selected.epoch.output,
|
|
114
|
+
},
|
|
115
|
+
effectiveFrom: selected.epoch.effectiveFrom,
|
|
116
|
+
route,
|
|
117
|
+
estimated: reason !== undefined,
|
|
118
|
+
estimatedReason: reason,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Read one own entry of a record, ignoring the prototype chain.
|
|
123
|
+
* @param table - record to read.
|
|
124
|
+
* @param key - key to look up.
|
|
125
|
+
* @returns the value, or undefined when the key is not an own property.
|
|
126
|
+
*/
|
|
127
|
+
function ownEntry(table, key) {
|
|
128
|
+
return Object.hasOwn(table, key) ? table[key] : undefined;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Build the effective pricing rule.
|
|
132
|
+
*
|
|
133
|
+
* @param options - module plus the deployment's adjustments.
|
|
134
|
+
* @returns the rule to price with.
|
|
135
|
+
* @throws when neither the requested module nor the default exists.
|
|
136
|
+
*/
|
|
137
|
+
export function buildPricingRule(options) {
|
|
138
|
+
const module = options.module ?? pricingModuleById(DEFAULT_PRICING_MODULE_ID);
|
|
139
|
+
if (module === undefined) {
|
|
140
|
+
throw new Error(`pricing: no pricing module available (looked for "${DEFAULT_PRICING_MODULE_ID}")`);
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
module,
|
|
144
|
+
currency: options.currency,
|
|
145
|
+
offPeakRatio: options.offPeakRatio ?? module.offPeakRatio,
|
|
146
|
+
peakOffsetMinutes: options.peakOffsetMinutes ?? module.timezoneOffsetMinutes,
|
|
147
|
+
fallbackModel: options.fallbackModel ?? module.fallbackModel,
|
|
148
|
+
overrides: options.overrides ?? {},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Price exactly one attempt.
|
|
153
|
+
*
|
|
154
|
+
* Extracted so a record can keep a per-attempt amount — which is what makes a
|
|
155
|
+
* model-filtered view exact rather than apportioned — while the record aggregate
|
|
156
|
+
* is built from the very same arithmetic.
|
|
157
|
+
*
|
|
158
|
+
* @param tokens - provider-reported buckets.
|
|
159
|
+
* @param model - wire model id of the attempt's route.
|
|
160
|
+
* @param at - settle instant, which selects BOTH the price row and the window.
|
|
161
|
+
* @param rule - rule in force.
|
|
162
|
+
* @returns the priced attempt, or undefined when no price row matches at all.
|
|
163
|
+
*/
|
|
164
|
+
export function priceAttempt(tokens, model, at, rule) {
|
|
165
|
+
const resolved = resolvePrices(model, at, rule);
|
|
166
|
+
if (resolved === undefined)
|
|
167
|
+
return undefined;
|
|
168
|
+
const window = classifyWindow(at, rule);
|
|
169
|
+
const scale = (window === 'peak' ? 1 : rule.offPeakRatio) / PRICE_UNIT;
|
|
170
|
+
const { prices } = resolved;
|
|
171
|
+
const uncachedInput = tokens.uncachedInput * prices.cacheMiss * scale;
|
|
172
|
+
const cacheRead = tokens.cacheRead * prices.cacheHit * scale;
|
|
173
|
+
// DeepSeek reports no cache-write bucket and publishes no write price; pricing
|
|
174
|
+
// a write as uncached input is the conservative reading.
|
|
175
|
+
const cacheWrite = tokens.cacheWrite * prices.cacheMiss * scale;
|
|
176
|
+
const output = tokens.output * prices.output * scale;
|
|
177
|
+
return {
|
|
178
|
+
amount: uncachedInput + cacheRead + cacheWrite + output,
|
|
179
|
+
uncachedInput,
|
|
180
|
+
cacheRead,
|
|
181
|
+
cacheWrite,
|
|
182
|
+
output,
|
|
183
|
+
window,
|
|
184
|
+
estimated: resolved.estimated,
|
|
185
|
+
estimatedReason: resolved.estimatedReason,
|
|
186
|
+
effectiveFrom: resolved.effectiveFrom,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Price all attempts of one Turn.
|
|
191
|
+
*
|
|
192
|
+
* Each attempt is priced under the window AND the price row of its own settle
|
|
193
|
+
* time, so a turn that straddles a schedule boundary — or a price change — is
|
|
194
|
+
* never mispriced wholesale.
|
|
195
|
+
*
|
|
196
|
+
* @param attempts - billed attempts with their routes and timestamps.
|
|
197
|
+
* @param rule - rule in force.
|
|
198
|
+
* @returns the frozen cost breakdown for the record.
|
|
199
|
+
*/
|
|
200
|
+
export function computeCost(attempts, rule) {
|
|
201
|
+
const acc = {
|
|
202
|
+
total: 0,
|
|
203
|
+
uncachedInput: 0,
|
|
204
|
+
cacheRead: 0,
|
|
205
|
+
cacheWrite: 0,
|
|
206
|
+
output: 0,
|
|
207
|
+
estimated: false,
|
|
208
|
+
reason: undefined,
|
|
209
|
+
};
|
|
210
|
+
for (const attempt of attempts) {
|
|
211
|
+
const priced = priceAttempt(attempt.tokens, attempt.model, attempt.at, rule);
|
|
212
|
+
if (priced === undefined) {
|
|
213
|
+
acc.estimated = true;
|
|
214
|
+
acc.reason ??= 'no-price-row';
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
acc.total += priced.amount;
|
|
218
|
+
acc.uncachedInput += priced.uncachedInput;
|
|
219
|
+
acc.cacheRead += priced.cacheRead;
|
|
220
|
+
acc.cacheWrite += priced.cacheWrite;
|
|
221
|
+
acc.output += priced.output;
|
|
222
|
+
acc.estimated = acc.estimated || priced.estimated;
|
|
223
|
+
acc.reason ??= priced.estimatedReason;
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
currency: rule.currency,
|
|
227
|
+
total: acc.total,
|
|
228
|
+
uncachedInput: acc.uncachedInput,
|
|
229
|
+
cacheRead: acc.cacheRead,
|
|
230
|
+
cacheWrite: acc.cacheWrite,
|
|
231
|
+
output: acc.output,
|
|
232
|
+
estimated: acc.estimated,
|
|
233
|
+
...(acc.reason === undefined ? {} : { estimatedReason: acc.reason }),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Report the provenance of a rule's price era, for display.
|
|
238
|
+
* @param rule - rule in force.
|
|
239
|
+
* @returns the provenance block the dashboard shows, tagged with the module id.
|
|
240
|
+
*/
|
|
241
|
+
export function provenanceOf(rule) {
|
|
242
|
+
const published = rule.module.prices[rule.currency] ?? {};
|
|
243
|
+
const rows = [];
|
|
244
|
+
for (const [model, epochs] of Object.entries(published)) {
|
|
245
|
+
for (const epoch of epochs) {
|
|
246
|
+
rows.push({
|
|
247
|
+
model,
|
|
248
|
+
cacheHit: epoch.cacheHit,
|
|
249
|
+
cacheMiss: epoch.cacheMiss,
|
|
250
|
+
output: epoch.output,
|
|
251
|
+
effectiveFrom: epoch.effectiveFrom,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return {
|
|
256
|
+
version: rule.module.id,
|
|
257
|
+
label: rule.module.label,
|
|
258
|
+
...rule.module.provenance,
|
|
259
|
+
currency: rule.currency,
|
|
260
|
+
unitTokens: PRICE_UNIT,
|
|
261
|
+
rows,
|
|
262
|
+
// Rendered here from the RULE (not the module), so a config override of the
|
|
263
|
+
// schedule is described by the numbers actually in force.
|
|
264
|
+
peakWindows: describePeakWindows(rule.module.peakWindows),
|
|
265
|
+
offPeakRatio: rule.offPeakRatio,
|
|
266
|
+
timezoneOffsetMinutes: rule.peakOffsetMinutes,
|
|
267
|
+
aliases: rule.module.aliases ?? {},
|
|
268
|
+
overriddenModels: Object.keys(rule.overrides).sort(),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Render peak windows as clock ranges.
|
|
273
|
+
*
|
|
274
|
+
* The stored hours are ALREADY in the pricing timezone — that is exactly what
|
|
275
|
+
* `classifyWindow` assumes when it shifts the instant by `peakOffsetMinutes` and
|
|
276
|
+
* then reads UTC hours — so this must format them as they are. Applying the
|
|
277
|
+
* offset here again would print `17:00–20:00` next to the module's own
|
|
278
|
+
* `09:00–12:00` rule text: two contradicting answers in one popover.
|
|
279
|
+
*
|
|
280
|
+
* @param windows - `[fromHour, toHour)` pairs in the pricing timezone.
|
|
281
|
+
* @returns `HH:MM–HH:MM` strings.
|
|
282
|
+
*/
|
|
283
|
+
function describePeakWindows(windows) {
|
|
284
|
+
const clock = (hour) => `${String(hour).padStart(2, '0')}:00`;
|
|
285
|
+
return windows.map(([from, to]) => `${clock(from)}–${clock(to)}`);
|
|
286
|
+
}
|
|
287
|
+
//# sourceMappingURL=pricing.js.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn outcome → ledger record.
|
|
3
|
+
*
|
|
4
|
+
* This is the one place where collected token accounting meets the price table
|
|
5
|
+
* and the Session's identity, producing the immutable line that is appended to
|
|
6
|
+
* the ledger. Pricing happens here, at write time, so a later price-table edit
|
|
7
|
+
* cannot silently rewrite history.
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-token-usage-ledger/host/records
|
|
10
|
+
*/
|
|
11
|
+
import { type UsageRecord } from '../shared/protocol.js';
|
|
12
|
+
import type { TurnOutcome } from './collector.js';
|
|
13
|
+
import { type PricingRule } from './pricing.js';
|
|
14
|
+
/** Session identity a Turn belongs to, as read from the live Session object. */
|
|
15
|
+
export interface RecordContext {
|
|
16
|
+
/** Session id. */
|
|
17
|
+
sessionId: string;
|
|
18
|
+
/** Session workspace root (`session.header.cwd`), `''` when the header has none. */
|
|
19
|
+
workspace: string;
|
|
20
|
+
/** Agent preset in force, `''` when unset. */
|
|
21
|
+
agentPreset: string;
|
|
22
|
+
/** `'subagent'` for a delegated session, `''` otherwise. */
|
|
23
|
+
origin: string;
|
|
24
|
+
/** Delegation depth, `0` when not a subagent. */
|
|
25
|
+
delegationDepth: number;
|
|
26
|
+
/** Parent session id, `''` when none. */
|
|
27
|
+
parentSession: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Derive a short, stable display label for a workspace path.
|
|
31
|
+
*
|
|
32
|
+
* Trailing separators are ignored so `/a/b/` and `/a/b` label identically; a
|
|
33
|
+
* root path keeps its full form rather than collapsing to an empty string.
|
|
34
|
+
*
|
|
35
|
+
* @param workspace - absolute workspace path, possibly empty.
|
|
36
|
+
* @returns the label to show in the dashboard.
|
|
37
|
+
*/
|
|
38
|
+
export declare function workspaceLabelOf(workspace: string): string;
|
|
39
|
+
/**
|
|
40
|
+
* Build the ledger line for one completed Turn.
|
|
41
|
+
*
|
|
42
|
+
* @param outcome - exact token accounting from the collector.
|
|
43
|
+
* @param context - Session identity.
|
|
44
|
+
* @param rule - pricing rule in force.
|
|
45
|
+
* @returns the immutable record to append.
|
|
46
|
+
*/
|
|
47
|
+
export declare function buildRecord(outcome: TurnOutcome, context: RecordContext, rule: PricingRule): UsageRecord;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn outcome → ledger record.
|
|
3
|
+
*
|
|
4
|
+
* This is the one place where collected token accounting meets the price table
|
|
5
|
+
* and the Session's identity, producing the immutable line that is appended to
|
|
6
|
+
* the ledger. Pricing happens here, at write time, so a later price-table edit
|
|
7
|
+
* cannot silently rewrite history.
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-token-usage-ledger/host/records
|
|
10
|
+
*/
|
|
11
|
+
import { basename } from 'node:path';
|
|
12
|
+
import { RECORD_SCHEMA_VERSION } from '../shared/protocol.js';
|
|
13
|
+
import { priceAttempt } from './pricing.js';
|
|
14
|
+
/**
|
|
15
|
+
* Derive a short, stable display label for a workspace path.
|
|
16
|
+
*
|
|
17
|
+
* Trailing separators are ignored so `/a/b/` and `/a/b` label identically; a
|
|
18
|
+
* root path keeps its full form rather than collapsing to an empty string.
|
|
19
|
+
*
|
|
20
|
+
* @param workspace - absolute workspace path, possibly empty.
|
|
21
|
+
* @returns the label to show in the dashboard.
|
|
22
|
+
*/
|
|
23
|
+
export function workspaceLabelOf(workspace) {
|
|
24
|
+
if (workspace.length === 0)
|
|
25
|
+
return '(未知工作区)';
|
|
26
|
+
const trimmed = workspace.replace(/[/\\]+$/, '');
|
|
27
|
+
if (trimmed.length === 0)
|
|
28
|
+
return workspace;
|
|
29
|
+
return basename(trimmed) || trimmed;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Build the ledger line for one completed Turn.
|
|
33
|
+
*
|
|
34
|
+
* @param outcome - exact token accounting from the collector.
|
|
35
|
+
* @param context - Session identity.
|
|
36
|
+
* @param rule - pricing rule in force.
|
|
37
|
+
* @returns the immutable record to append.
|
|
38
|
+
*/
|
|
39
|
+
export function buildRecord(outcome, context, rule) {
|
|
40
|
+
const attempts = [];
|
|
41
|
+
let costTotal = 0;
|
|
42
|
+
let costUncached = 0;
|
|
43
|
+
let costCacheRead = 0;
|
|
44
|
+
let costCacheWrite = 0;
|
|
45
|
+
let costOutput = 0;
|
|
46
|
+
let estimated = false;
|
|
47
|
+
const routeKeys = new Set();
|
|
48
|
+
let estimatedReason;
|
|
49
|
+
for (const attempt of outcome.attempts) {
|
|
50
|
+
// An unattributed attempt is priced with the configured fallback so the
|
|
51
|
+
// figure stays useful, but it is recorded as unattributed and marked
|
|
52
|
+
// estimated rather than being passed off as exact.
|
|
53
|
+
const priced = priceAttempt(attempt.tokens, attempt.model.length === 0 ? rule.fallbackModel : attempt.model, attempt.at, rule);
|
|
54
|
+
const amount = priced?.amount ?? 0;
|
|
55
|
+
const attemptEstimated = priced === undefined || priced.estimated;
|
|
56
|
+
costTotal += amount;
|
|
57
|
+
costUncached += priced?.uncachedInput ?? 0;
|
|
58
|
+
costCacheRead += priced?.cacheRead ?? 0;
|
|
59
|
+
costCacheWrite += priced?.cacheWrite ?? 0;
|
|
60
|
+
costOutput += priced?.output ?? 0;
|
|
61
|
+
estimated = estimated || attemptEstimated;
|
|
62
|
+
if (attempt.model.length > 0) {
|
|
63
|
+
routeKeys.add(attempt.provider.length > 0 ? `${attempt.provider}/${attempt.model}` : attempt.model);
|
|
64
|
+
}
|
|
65
|
+
attempts.push({
|
|
66
|
+
provider: attempt.provider,
|
|
67
|
+
model: attempt.model,
|
|
68
|
+
at: attempt.at,
|
|
69
|
+
tokens: attempt.tokens,
|
|
70
|
+
total: attempt.total,
|
|
71
|
+
cost: amount,
|
|
72
|
+
estimated: attemptEstimated,
|
|
73
|
+
// The reason and the row are kept so a figure stays explainable after the
|
|
74
|
+
// price table gains newer rows — "why is this 0.009?" must remain answerable.
|
|
75
|
+
...(priced?.estimatedReason === undefined ? {} : { estimatedReason: priced.estimatedReason }),
|
|
76
|
+
...(priced === undefined ? { estimatedReason: 'no-price-row' } : {}),
|
|
77
|
+
...(priced?.effectiveFrom === undefined || priced.effectiveFrom === ''
|
|
78
|
+
? {}
|
|
79
|
+
: { pricedBy: priced.effectiveFrom }),
|
|
80
|
+
window: priced?.window ?? 'unknown',
|
|
81
|
+
});
|
|
82
|
+
estimatedReason ??= attemptEstimated
|
|
83
|
+
? (priced?.estimatedReason ?? 'no-price-row')
|
|
84
|
+
: undefined;
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
v: RECORD_SCHEMA_VERSION,
|
|
88
|
+
ts: outcome.endedAt,
|
|
89
|
+
startedAt: outcome.startedAt,
|
|
90
|
+
endedAt: outcome.endedAt,
|
|
91
|
+
sessionId: context.sessionId,
|
|
92
|
+
turn: outcome.turn,
|
|
93
|
+
workspace: context.workspace,
|
|
94
|
+
workspaceLabel: workspaceLabelOf(context.workspace),
|
|
95
|
+
agentPreset: context.agentPreset,
|
|
96
|
+
origin: context.origin,
|
|
97
|
+
delegationDepth: context.delegationDepth,
|
|
98
|
+
parentSession: context.parentSession,
|
|
99
|
+
reason: outcome.reason,
|
|
100
|
+
routes: [...routeKeys].sort().join(','),
|
|
101
|
+
attempts,
|
|
102
|
+
tokens: outcome.tokens,
|
|
103
|
+
total: outcome.total,
|
|
104
|
+
cost: {
|
|
105
|
+
currency: rule.currency,
|
|
106
|
+
total: costTotal,
|
|
107
|
+
uncachedInput: costUncached,
|
|
108
|
+
cacheRead: costCacheRead,
|
|
109
|
+
cacheWrite: costCacheWrite,
|
|
110
|
+
output: costOutput,
|
|
111
|
+
estimated,
|
|
112
|
+
...(estimatedReason === undefined ? {} : { estimatedReason }),
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
//# sourceMappingURL=records.js.map
|