@trazum/core 1.82.0 → 1.83.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/receipt.ts ADDED
@@ -0,0 +1,351 @@
1
+ import { PROVIDER_REVIEWED, modelFrom } from './pricing.js';
2
+ import type { PricingCatalogue } from './pricing.js';
3
+ import { UNLABELLED } from './usage.js';
4
+ import type { UsageBreakdown, UsageProfileReport } from './usage.js';
5
+
6
+ /**
7
+ * The receipt: a bill's counts, with the provenance of every figure attached.
8
+ *
9
+ * ## What it is for
10
+ *
11
+ * A profile answers a question on the terminal where it ran. A receipt is the
12
+ * same figures shaped so they can still answer it somewhere else: aggregated by
13
+ * somebody's dashboard, filed against an invoice, or compared against last
14
+ * month's by a reader who was not there when the command ran.
15
+ *
16
+ * That is why every line carries the rate behind its money and the date that
17
+ * rate was last read. A dollar figure with no provenance cannot tell a
18
+ * repricing from a team whose spend moved, and the consumer that most needs
19
+ * that distinction is the one that cannot read a sentence explaining it.
20
+ *
21
+ * ## Why a line carries money per bucket and not only a rate
22
+ *
23
+ * The first version of this module published the catalogue's `inputPerMTok`
24
+ * and `outputPerMTok` beside a dollar figure computed by `profileUsage`. Those
25
+ * are not always the same rates. A model in a promotional window, or one whose
26
+ * long-context tier applied, is billed at `effectivePricing`'s figure, and a
27
+ * cached read is billed at a fraction of input that no published field named at
28
+ * all. **A consumer multiplying the stated rates by the stated tokens got a
29
+ * different number from the stated total, with nothing saying which was
30
+ * wrong.**
31
+ *
32
+ * That is a bad defect in a document whose entire purpose is that a figure can
33
+ * be recomputed by whoever receives it, and it is the exact failure the
34
+ * doctrine line at the foot of this comment is about.
35
+ *
36
+ * So a line now carries the **money as it was actually apportioned** -- input,
37
+ * cache reads, cache writes and output -- and `usd` is their sum. The rates stay
38
+ * as provenance, labelled as the catalogue's published figures rather than as
39
+ * the arithmetic. `receipt-arithmetic.test.js` fails if the four stop adding up,
40
+ * which is a property a reader can check on any receipt they are handed rather
41
+ * than a promise they have to take.
42
+ *
43
+ * ## What it carries, and what it has no field for
44
+ *
45
+ * Counts, model, provider, the money split by bucket, the published rates, the
46
+ * review date, the label the log carried, the period, and what could not be
47
+ * priced. There is **no field
48
+ * for prompt text, for an answer, for a file path, for a branch name or for a
49
+ * credential** — not redacted, not hashed, absent, because the input this takes
50
+ * has nowhere to hold them either.
51
+ *
52
+ * `receipt-redaction.test.js` holds that by planting all 4 in a log — in the
53
+ * session field among other places, which is the value this package has
54
+ * promised since it shipped never comes back out — and failing if any reaches
55
+ * the output. A property about what a document does not contain is exactly the
56
+ * kind this repository proves by breaking rather than by asserting.
57
+ *
58
+ * ## What it is not
59
+ *
60
+ * **Not a transport.** Nothing here opens a socket, reads an environment
61
+ * variable or takes an endpoint. `receiptFrom` returns a value; where it goes
62
+ * is the caller's decision. A module in this package that phoned home would
63
+ * break the roadmap's first rule, which is that no feature may make a network
64
+ * call a prerequisite for anything.
65
+ *
66
+ * **Not a new measurement.** Every figure is one `profileUsage` already
67
+ * produced. This adds provenance around them and takes nothing away.
68
+ *
69
+ * Doctrine: [A machine reader gets the provenance too](../../../docs/doctrine.md#a-machine-reader-gets-the-provenance-too)
70
+ */
71
+
72
+ /**
73
+ * The catalogue's published rates for this model, and when a human last read
74
+ * them off the provider's own page.
75
+ *
76
+ * **Provenance, not the arithmetic.** These are list rates. The money that was
77
+ * actually apportioned is in `ReceiptLine.money`, and the two differ whenever a
78
+ * promotion or a long-context tier applied, or for any token billed at a
79
+ * fraction of input -- which is every cached read. A consumer wanting the rate
80
+ * that was really charged divides a bucket's money by its tokens; a consumer
81
+ * wanting to know whether a provider repriced compares these.
82
+ */
83
+ export interface ReceiptPricing {
84
+ provider: string;
85
+ inputPerMTok: number;
86
+ outputPerMTok: number;
87
+ /**
88
+ * The date this provider's rates were last read off its own page, `null`
89
+ * when the catalogue carries no date for that provider.
90
+ *
91
+ * Per provider rather than per catalogue, because that is how the prices are
92
+ * actually reviewed: looking at one page and finding nothing changed is not
93
+ * the same event as not looking. A server comparing two receipts a month
94
+ * apart reads a repricing as a repricing instead of as a team missing a
95
+ * target.
96
+ */
97
+ reviewedOn: string | null;
98
+ }
99
+
100
+ /** Where a line's money went. The four add to `ReceiptLine.usd`. */
101
+ export interface ReceiptMoney {
102
+ inputUsd: number;
103
+ cacheReadUsd: number;
104
+ cacheWriteUsd: number;
105
+ outputUsd: number;
106
+ }
107
+
108
+ /** One slice of a bill: a label's calls to one model. */
109
+ export interface ReceiptLine {
110
+ /**
111
+ * The attribution the log carried, or `null` for the unlabelled bucket.
112
+ *
113
+ * `null` rather than the sentinel, which is an internal grouping key and is
114
+ * never serialised. A consumer that saw the raw sentinel would have to know
115
+ * this package's internals to render it.
116
+ */
117
+ label: string | null;
118
+ model: string;
119
+ calls: number;
120
+ inputTokens: number;
121
+ cacheReadTokens: number;
122
+ /** Every cache write, whatever its TTL. The sum of the two fields below. */
123
+ cacheWriteTokens: number;
124
+ /**
125
+ * The two write TTLs kept apart, because they are billed at different rates.
126
+ *
127
+ * They are here for the same reason `UsageBreakdown` keeps them: the ratio
128
+ * between them is not a constant across providers, so a total that has lost
129
+ * the split can be repriced only by guessing at it. A consumer repricing this
130
+ * traffic against another model's rates needs both.
131
+ */
132
+ cacheWrite5mTokens: number;
133
+ cacheWrite1hTokens: number;
134
+ outputTokens: number;
135
+ /**
136
+ * What it cost, which is exactly the sum of `money` below.
137
+ *
138
+ * Every line here is priced; what is not is in `gaps`.
139
+ */
140
+ usd: number;
141
+ /**
142
+ * Where the money went, as it was apportioned rather than as it might be
143
+ * recomputed.
144
+ *
145
+ * This is the field that makes a receipt checkable. `usd` alone can only be
146
+ * believed; these four can be added up, and each can be divided by its own
147
+ * token count to recover the rate that was really charged -- including the
148
+ * one for cached reads, which no published rate names.
149
+ */
150
+ money: ReceiptMoney;
151
+ /** The catalogue's published rates, as provenance. */
152
+ pricing: ReceiptPricing;
153
+ }
154
+
155
+ /** Everything a receipt refuses to answer, typed rather than left implicit. */
156
+ export type ReceiptGap =
157
+ /**
158
+ * Models the catalogue does not price, with the size of what they used.
159
+ *
160
+ * The counts are here rather than in a line, and the first draft of this
161
+ * module got that wrong in a way its own guard caught. `byLabelAndModel`
162
+ * excludes unpriced calls on purpose — the profile keeps them apart so that
163
+ * a total is never tokens from one set of calls over dollars from another —
164
+ * so a receipt built from that list alone silently loses them.
165
+ *
166
+ * The obvious repair was worse than the bug: emit a line with `label: null`.
167
+ * That reads as *this call carried no label*, when in fact it carried one the
168
+ * profile could not attach to a priced slice. Conflating "unlabelled" with
169
+ * "unattributable" is the exact failure this project refuses elsewhere, so
170
+ * the gap carries the magnitude instead and nothing pretends to an
171
+ * attribution it does not have.
172
+ */
173
+ | { kind: 'unpriced'; models: string[]; calls: number; inputTokens: number; outputTokens: number }
174
+ | { kind: 'unread-lines'; count: number }
175
+ | { kind: 'no-clock' }
176
+ /**
177
+ * Calls whose cache-write TTL the log did not state, so the cheaper rate was
178
+ * assumed.
179
+ *
180
+ * Reported because it changes what kind of figure this is. A total that
181
+ * includes an assumed TTL is a **floor** on those calls, not a measurement,
182
+ * and a document that says `counting: 'counted'` while quietly resting on an
183
+ * assumption is claiming a precision it does not have.
184
+ */
185
+ | { kind: 'assumed-write-ttl'; calls: number };
186
+
187
+ export interface ReceiptDocument {
188
+ /** The one thing a consumer must branch on. Set here, by the builder. */
189
+ schemaVersion: 1;
190
+ /**
191
+ * When this receipt was made, or `null`.
192
+ *
193
+ * Optional on purpose, and the reason is the same one `plan.json` gives: a
194
+ * document without a stamp is undated, which a reader can act on. A document
195
+ * with an invented stamp is wrong, which they cannot.
196
+ */
197
+ emittedAt: string | null;
198
+ /** The period the counts cover, from the log's own clock. */
199
+ span: { fromMs: number; toMs: number; calls: number } | null;
200
+ /**
201
+ * How the tokens were arrived at.
202
+ *
203
+ * `counted` for every receipt this function builds, because a usage log
204
+ * carries the provider's own counts. The field exists because a receipt built
205
+ * from an estimate would be a different kind of evidence, and a consumer must
206
+ * never have to guess which one it is holding.
207
+ */
208
+ counting: 'counted';
209
+ lines: ReceiptLine[];
210
+ total: { calls: number; usd: number };
211
+ /**
212
+ * What this receipt cannot say, and why.
213
+ *
214
+ * Present and empty rather than absent when there is nothing to report:
215
+ * "nothing was refused" and "this document does not record refusals" are
216
+ * different statements, and a server aggregating a thousand receipts has to
217
+ * be able to tell them apart.
218
+ */
219
+ gaps: ReceiptGap[];
220
+ }
221
+
222
+ /**
223
+ * The fields that leave this machine, listed once, in one place.
224
+ *
225
+ * The redaction guard reads this array rather than a copy of it, so a field
226
+ * added to `ReceiptLine` and not added here fails the guard. A whitelist
227
+ * maintained in two places is a whitelist with a hole in it.
228
+ */
229
+ export const RECEIPT_LINE_FIELDS = Object.freeze([
230
+ 'label',
231
+ 'model',
232
+ 'calls',
233
+ 'inputTokens',
234
+ 'cacheReadTokens',
235
+ 'cacheWriteTokens',
236
+ 'cacheWrite5mTokens',
237
+ 'cacheWrite1hTokens',
238
+ 'outputTokens',
239
+ 'usd',
240
+ 'money',
241
+ 'pricing',
242
+ ] as const);
243
+
244
+ const lineFrom = (
245
+ label: string,
246
+ model: string,
247
+ breakdown: UsageBreakdown,
248
+ catalogue: PricingCatalogue,
249
+ ): ReceiptLine => {
250
+ /*
251
+ * Every slice reaching here is priced: `byLabelAndModel` holds only what the
252
+ * catalogue knows. What it does not know is reported by the `unpriced` gap,
253
+ * with its size, so the receipt's total is never mistaken for the whole bill.
254
+ */
255
+ const priced = modelFrom(catalogue, model);
256
+ return {
257
+ label: label === UNLABELLED ? null : label,
258
+ model,
259
+ calls: breakdown.calls,
260
+ inputTokens: breakdown.inputTokens,
261
+ cacheReadTokens: breakdown.cacheReadTokens,
262
+ cacheWriteTokens: breakdown.cacheWriteTokens,
263
+ cacheWrite5mTokens: breakdown.cacheWrite5mTokens,
264
+ cacheWrite1hTokens: breakdown.cacheWrite1hTokens,
265
+ outputTokens: breakdown.outputTokens,
266
+ usd: breakdown.totalUsd,
267
+ /*
268
+ * Copied from the breakdown rather than recomputed from the rates below.
269
+ * Recomputing would reintroduce the defect this field exists to fix: the
270
+ * published rates are list rates, and a promotion, a long-context tier or
271
+ * any cached token is billed at something else.
272
+ */
273
+ money: {
274
+ inputUsd: breakdown.inputUsd,
275
+ cacheReadUsd: breakdown.cacheReadUsd,
276
+ cacheWriteUsd: breakdown.cacheWriteUsd,
277
+ outputUsd: breakdown.outputUsd,
278
+ },
279
+ pricing: {
280
+ provider: priced.provider ?? 'unknown',
281
+ inputPerMTok: priced.inputPerMTok,
282
+ outputPerMTok: priced.outputPerMTok,
283
+ reviewedOn: PROVIDER_REVIEWED[priced.provider ?? ''] ?? null,
284
+ },
285
+ };
286
+ };
287
+
288
+ export interface ReceiptOptions {
289
+ /** Stamp the document. Omit for an undated receipt, which is valid. */
290
+ emittedAt?: Date;
291
+ }
292
+
293
+ /**
294
+ * Build a receipt from a profile the caller already computed.
295
+ *
296
+ * Takes the report rather than the log text, and that is the guarantee rather
297
+ * than an ergonomic choice: `UsageProfileReport` has no field that can hold
298
+ * prompt content, so this function could not emit any even if it tried. The
299
+ * narrow input is what makes the promise checkable instead of merely stated.
300
+ */
301
+ export function receiptFrom(
302
+ report: UsageProfileReport,
303
+ catalogue: PricingCatalogue,
304
+ options: ReceiptOptions = {},
305
+ ): ReceiptDocument {
306
+ const lines = report.byLabelAndModel.map((slice) =>
307
+ lineFrom(slice.label, slice.model, slice.breakdown, catalogue),
308
+ );
309
+
310
+ const gaps: ReceiptGap[] = [];
311
+ if (report.unpricedModels.length > 0) {
312
+ gaps.push({
313
+ kind: 'unpriced',
314
+ models: [...report.unpricedModels],
315
+ calls: report.unpriced.calls,
316
+ inputTokens: report.unpriced.inputTokens,
317
+ outputTokens: report.unpriced.outputTokens,
318
+ });
319
+ }
320
+ if (report.skippedLines.length > 0) {
321
+ gaps.push({ kind: 'unread-lines', count: report.skippedLines.length });
322
+ }
323
+ if (report.span === null) gaps.push({ kind: 'no-clock' });
324
+
325
+ /*
326
+ * Summed across the lines rather than read off a total, because the profile
327
+ * keeps this per slice and a receipt reports it once for the document.
328
+ */
329
+ const assumed = report.byLabelAndModel.reduce(
330
+ (sum, slice) => sum + slice.breakdown.assumedWriteTtlCalls,
331
+ 0,
332
+ );
333
+ if (assumed > 0) gaps.push({ kind: 'assumed-write-ttl', calls: assumed });
334
+
335
+ return {
336
+ schemaVersion: 1,
337
+ emittedAt: options.emittedAt?.toISOString() ?? null,
338
+ span: report.span === null ? null : { ...report.span },
339
+ counting: 'counted',
340
+ lines,
341
+ /*
342
+ * `report.total` already excludes what could not be priced — the profile
343
+ * keeps those in `unpriced` precisely so a total is never tokens from one
344
+ * set of calls divided by dollars from another. The receipt inherits that
345
+ * separation rather than re-deriving it, and `gaps` carries the size of
346
+ * what is missing.
347
+ */
348
+ total: { calls: report.total.calls, usd: report.total.totalUsd },
349
+ gaps,
350
+ };
351
+ }
package/src/types.ts CHANGED
@@ -64,6 +64,7 @@ export type AdvisoryId =
64
64
  | 'tier-signals-conflict'
65
65
  | 'output-dominated'
66
66
  | 'promo-pricing'
67
+ | 'model-retired'
67
68
  | 'contradictory-instructions'
68
69
  | 'redundant-examples'
69
70
  | 'restated-output-format'
@@ -149,6 +150,59 @@ export type CachingMode =
149
150
  */
150
151
  export type Capability = 'small' | 'mid' | 'large' | 'frontier' | 'unknown';
151
152
 
153
+ /**
154
+ * What makes a conditional rate apply, as data a machine can evaluate.
155
+ *
156
+ * Deliberately a closed union rather than a predicate function. A catalogue
157
+ * entry is reviewed the way a price is reviewed, and a reviewer can check
158
+ * "peak is 01:00-04:00 and 06:00-10:00 UTC on weekdays" against a provider's
159
+ * page; nobody can review a closure. It also means the condition survives
160
+ * `JSON.stringify`, which matters because the catalogue can be overlaid from a
161
+ * file.
162
+ */
163
+ export type TierCondition =
164
+ /**
165
+ * The prompt is larger than `tokens` input tokens.
166
+ *
167
+ * Decidable only where the token count is known, which is most of the places
168
+ * that price a specific call and none of the places that merely rank models.
169
+ * `effectivePricing` says which happened rather than guessing.
170
+ */
171
+ | { kind: 'input-tokens-above'; tokens: number }
172
+ /**
173
+ * The call falls inside one of `hours` in UTC, optionally on weekdays only.
174
+ *
175
+ * Decidable everywhere, because every caller already passes the date it is
176
+ * pricing for. `hours` lists the hour each window *starts*, so 01:00-04:00
177
+ * is `[1, 2, 3]` and not `[1, 4]`: an endpoint convention is the kind of
178
+ * thing two readers disagree about silently.
179
+ */
180
+ | { kind: 'utc-hours'; hours: number[]; weekdaysOnly: boolean };
181
+
182
+ /**
183
+ * A rate that applies when its condition holds.
184
+ *
185
+ * Deliberately carries no multipliers of its own, and the first draft did. The
186
+ * reasoning for adding them was that DeepSeek halves the cache-hit price at
187
+ * off-peak along with everything else, so a cache read priced off the base
188
+ * would be wrong about the money — which is true of the *price* and false of
189
+ * the *ratio*: $0.007 against $0.22 and $0.014 against $0.44 are the same
190
+ * 3.18% to the last digit, on both models. Multiplying a tier's own input rate
191
+ * by the model's multiplier already gives the right answer.
192
+ *
193
+ * It was removed because the guard written to prove it mattered could not: with
194
+ * the tier multiplier equal to the base one, dropping it changed nothing and
195
+ * the test passed either way. An option nothing can distinguish from its
196
+ * absence is a claim nobody checks, which is worse than not having it.
197
+ */
198
+ export interface PricingTier {
199
+ /** Short, stable, and printed: a reader has to be able to see which applied. */
200
+ id: string;
201
+ when: TierCondition;
202
+ inputPerMTok: number;
203
+ outputPerMTok: number;
204
+ }
205
+
152
206
  export interface ModelPricing {
153
207
  id: string;
154
208
  displayName: string;
@@ -180,6 +234,32 @@ export interface ModelPricing {
180
234
  * buy is advice that wastes their time.
181
235
  */
182
236
  recommendable?: boolean;
237
+ /**
238
+ * Set when the provider refused a real request for this id.
239
+ *
240
+ * A retired model keeps its price and loses its future. Both halves matter:
241
+ * a log full of `deepseek-v3` calls records money that was genuinely spent,
242
+ * so deleting the row would make somebody's own history unpriceable — and a
243
+ * *new* call on that id will not happen at all, so quoting it as an option is
244
+ * a number for a question nobody can ask.
245
+ *
246
+ * `on` is the day `scripts/check-model-availability.mjs` was refused, and
247
+ * `because` is the provider's own sentence, quoted rather than paraphrased.
248
+ * Neither is a judgement, and neither implies anything about what the
249
+ * replacement costs: that is a price, and a price comes off the provider's
250
+ * own page or not at all.
251
+ *
252
+ * A retired model is never recommended, never offered as a cheaper
253
+ * alternative and never chosen as a tier's representative, in the same places
254
+ * `recommendable: false` is honoured — this is a stronger statement than that
255
+ * one and must not be weaker in effect.
256
+ */
257
+ retired?: {
258
+ /** ISO date the refusal was recorded. */
259
+ on: string;
260
+ /** What the provider answered, in the provider's words. */
261
+ because: string;
262
+ };
183
263
  /** Capability, on a vendor-neutral scale. */
184
264
  capability: Capability;
185
265
  /**
@@ -195,6 +275,29 @@ export interface ModelPricing {
195
275
  /** ISO date (inclusive) the promotional price applies until. */
196
276
  until: string;
197
277
  };
278
+ /**
279
+ * Rates that apply only under a stated condition.
280
+ *
281
+ * The catalogue held one input price and one output price per model until a
282
+ * real credential was pointed at the providers and two of them turned out not
283
+ * to charge that way:
284
+ *
285
+ * - **DeepSeek V4 bills by the clock.** Peak is 01:00-04:00 and 06:00-10:00
286
+ * UTC, Monday to Friday, and off-peak is exactly half. That is 35 hours of
287
+ * 168, so the common case is the cheap one and a single number would have
288
+ * been wrong by 2x in whichever direction it was chosen.
289
+ * - **Gemini 3.1 Pro bills by prompt size**, $2/$12 up to 200k input tokens
290
+ * and $4/$18 above it.
291
+ *
292
+ * Both are *conditions*, so both are written as data rather than as prose in
293
+ * `notes`: a note is something a reader has to apply by hand, and this
294
+ * product exists to stop people doing arithmetic by hand.
295
+ *
296
+ * The base `inputPerMTok` and `outputPerMTok` stay the rate that applies when
297
+ * no condition matches, which keeps every model that has no tiers unchanged
298
+ * and keeps this field optional in effect as well as in the type.
299
+ */
300
+ tiers?: PricingTier[];
198
301
  /**
199
302
  * Other ids that bill at exactly this rate.
200
303
  *