@trazum/core 1.10.0 → 1.26.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.
Files changed (84) hide show
  1. package/dist/against.d.ts +32 -0
  2. package/dist/against.d.ts.map +1 -0
  3. package/dist/against.js +34 -0
  4. package/dist/against.js.map +1 -0
  5. package/dist/config-schema.d.ts +42 -1
  6. package/dist/config-schema.d.ts.map +1 -1
  7. package/dist/config-schema.js +61 -0
  8. package/dist/config-schema.js.map +1 -1
  9. package/dist/conversation.d.ts +121 -0
  10. package/dist/conversation.d.ts.map +1 -0
  11. package/dist/conversation.js +157 -0
  12. package/dist/conversation.js.map +1 -0
  13. package/dist/csv.d.ts +61 -0
  14. package/dist/csv.d.ts.map +1 -0
  15. package/dist/csv.js +149 -0
  16. package/dist/csv.js.map +1 -0
  17. package/dist/evaluate.d.ts +24 -0
  18. package/dist/evaluate.d.ts.map +1 -1
  19. package/dist/evaluate.js +5 -2
  20. package/dist/evaluate.js.map +1 -1
  21. package/dist/index.d.ts +25 -3
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +28 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/input-shape.d.ts +104 -0
  26. package/dist/input-shape.d.ts.map +1 -0
  27. package/dist/input-shape.js +132 -0
  28. package/dist/input-shape.js.map +1 -0
  29. package/dist/levers.d.ts +151 -0
  30. package/dist/levers.d.ts.map +1 -0
  31. package/dist/levers.js +160 -0
  32. package/dist/levers.js.map +1 -0
  33. package/dist/node.d.ts +1 -1
  34. package/dist/node.d.ts.map +1 -1
  35. package/dist/output-shape.d.ts +96 -0
  36. package/dist/output-shape.d.ts.map +1 -0
  37. package/dist/output-shape.js +145 -0
  38. package/dist/output-shape.js.map +1 -0
  39. package/dist/pricing-overlay.d.ts +1 -1
  40. package/dist/pricing-overlay.d.ts.map +1 -1
  41. package/dist/pricing-overlay.js +46 -0
  42. package/dist/pricing-overlay.js.map +1 -1
  43. package/dist/repeats.d.ts +75 -0
  44. package/dist/repeats.d.ts.map +1 -0
  45. package/dist/repeats.js +82 -0
  46. package/dist/repeats.js.map +1 -0
  47. package/dist/reprice.d.ts +143 -0
  48. package/dist/reprice.d.ts.map +1 -0
  49. package/dist/reprice.js +82 -0
  50. package/dist/reprice.js.map +1 -0
  51. package/dist/session-cost.d.ts +70 -0
  52. package/dist/session-cost.d.ts.map +1 -0
  53. package/dist/session-cost.js +90 -0
  54. package/dist/session-cost.js.map +1 -0
  55. package/dist/session-ledger.d.ts +77 -0
  56. package/dist/session-ledger.d.ts.map +1 -0
  57. package/dist/session-ledger.js +99 -0
  58. package/dist/session-ledger.js.map +1 -0
  59. package/dist/ttl-fit.d.ts +103 -0
  60. package/dist/ttl-fit.d.ts.map +1 -0
  61. package/dist/ttl-fit.js +184 -0
  62. package/dist/ttl-fit.js.map +1 -0
  63. package/dist/usage.d.ts +434 -16
  64. package/dist/usage.d.ts.map +1 -1
  65. package/dist/usage.js +383 -23
  66. package/dist/usage.js.map +1 -1
  67. package/package.json +1 -1
  68. package/src/against.ts +48 -0
  69. package/src/config-schema.ts +106 -0
  70. package/src/conversation.ts +305 -0
  71. package/src/csv.ts +184 -0
  72. package/src/evaluate.ts +33 -3
  73. package/src/index.ts +51 -1
  74. package/src/input-shape.ts +259 -0
  75. package/src/levers.ts +331 -0
  76. package/src/node.ts +1 -1
  77. package/src/output-shape.ts +254 -0
  78. package/src/pricing-overlay.ts +52 -1
  79. package/src/repeats.ts +166 -0
  80. package/src/reprice.ts +227 -0
  81. package/src/session-cost.ts +170 -0
  82. package/src/session-ledger.ts +189 -0
  83. package/src/ttl-fit.ts +251 -0
  84. package/src/usage.ts +795 -7
@@ -0,0 +1,189 @@
1
+ import { effectivePricing, multipliersFor } from './pricing.js';
2
+ import { UNLABELLED } from './usage.js';
3
+ import type { PricingCatalogue } from './pricing.js';
4
+ import type { UsageRecord } from './usage.js';
5
+
6
+ /**
7
+ * Cache writes made by conversations that never came back.
8
+ *
9
+ * ## The waste the aggregate hides
10
+ *
11
+ * A cache write is a bet: pay 1.25x input now (2x at the 1-hour TTL) so the
12
+ * *next* call reads the prefix at 0.1x. A conversation that ends after its
13
+ * first turn never places that next call — its write bought reuse that its own
14
+ * conversation never made. On a workload with many short sessions this is a
15
+ * steady leak, and it hides inside healthy-looking totals: the long sessions'
16
+ * reads pay for the cache overall, so `cacheEconomics` reports `paid-off`
17
+ * while every one-turn drive-by pays the premium for nothing.
18
+ *
19
+ * ## The caveat that keeps the figure honest
20
+ *
21
+ * The provider's cache is keyed by prefix content, not by conversation. A
22
+ * one-turn session's write **can** be read back by a different session that
23
+ * sends the same prefix within the TTL — a shared system prompt does exactly
24
+ * that — and a usage log cannot see whose write a read hit. So the figure
25
+ * reported here is a **ceiling, named as one**: these writes paid off only if
26
+ * another conversation shared the prefix in time, and the log cannot say
27
+ * whether one did.
28
+ *
29
+ * There is one case where the ceiling collapses into a fact, and the caller
30
+ * can detect it from the slice it already has: when the slice recorded **zero
31
+ * cache reads**, nothing read those writes — within the session, across
32
+ * sessions, at all. The row deliberately does not decide this itself; the
33
+ * breakdown holding the slice's reads belongs to the caller, and deriving it
34
+ * twice is how two figures drift.
35
+ *
36
+ * Session keys group turns and never leave this module, like everywhere else
37
+ * the field is touched.
38
+ */
39
+
40
+ export interface SingleTurnCacheWrites {
41
+ label: string;
42
+ model: string;
43
+ modelName: string;
44
+ /** Conversations seen in this slice — with a session key, priced model. */
45
+ sessions: number;
46
+ /** Median turns per conversation, for scale: 1-turn sessions in a sea of 40-turn ones read differently than in a sea of 2s. */
47
+ medianTurns: number;
48
+ /** Conversations that ended after exactly one recorded turn. */
49
+ singleTurnSessions: number;
50
+ /** Cache-write tokens those one-turn conversations paid for. */
51
+ singleTurnWriteTokens: number;
52
+ /**
53
+ * What those writes cost, at the same rates the bill used — the 5-minute
54
+ * rate for writes whose TTL the log did not state, so like the bill it is
55
+ * a floor when `assumedTtlTokens` is non-zero. A **ceiling on the waste**
56
+ * (another conversation may have read the prefix; the log cannot see it)
57
+ * built on a **floor of a price** — both directions named, neither guessed.
58
+ */
59
+ singleTurnWriteUsd: number;
60
+ /** The part of `singleTurnWriteTokens` whose TTL the log did not record. */
61
+ assumedTtlTokens: number;
62
+ }
63
+
64
+ export interface SessionLedgerOptions {
65
+ catalogue: PricingCatalogue;
66
+ /** Date the prices are read at, so a promotional rate resolves the same way. */
67
+ on?: Date;
68
+ }
69
+
70
+ export interface SessionLedgerTracker {
71
+ add(record: UsageRecord): void;
72
+ finish(): SingleTurnCacheWrites[];
73
+ }
74
+
75
+ interface SessionTally {
76
+ turns: number;
77
+ write5mTokens: number;
78
+ write1hTokens: number;
79
+ assumedTokens: number;
80
+ }
81
+
82
+ const median = (sorted: number[]): number => {
83
+ const mid = Math.floor(sorted.length / 2);
84
+ return sorted.length % 2 === 1 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2;
85
+ };
86
+
87
+ /**
88
+ * An accumulator, like the TTL-fit tracker and for the same reason: one pass
89
+ * over a log measured in megabytes, holding one small tally per conversation.
90
+ * No timestamp needed — "came back" is a fact about turn count, not the clock,
91
+ * so this measures logs the TTL-fit cannot.
92
+ */
93
+ export function createSessionLedgerTracker(options: SessionLedgerOptions): SessionLedgerTracker {
94
+ const { catalogue, on = new Date() } = options;
95
+ const slices = new Map<string, Map<string, SessionTally>>();
96
+
97
+ const add = (record: UsageRecord): void => {
98
+ // An unpriced model has no rate to price the waste at, and contributes no
99
+ // dollars anywhere else either.
100
+ if (record.session === null || !catalogue.byId.has(record.model)) return;
101
+
102
+ const key = `${record.label ?? UNLABELLED}\n${record.model}`;
103
+ let sessions = slices.get(key);
104
+ if (!sessions) {
105
+ sessions = new Map();
106
+ slices.set(key, sessions);
107
+ }
108
+ let tally = sessions.get(record.session);
109
+ if (!tally) {
110
+ tally = { turns: 0, write5mTokens: 0, write1hTokens: 0, assumedTokens: 0 };
111
+ sessions.set(record.session, tally);
112
+ }
113
+ tally.turns += 1;
114
+ if (record.writeTtlKnown) {
115
+ tally.write5mTokens += record.cacheWrite5mTokens;
116
+ tally.write1hTokens += record.cacheWrite1hTokens;
117
+ } else {
118
+ // The flat count sits in the 5m bucket by pricing convention; kept
119
+ // apart here so the row can say how much of its price is a floor.
120
+ tally.assumedTokens += record.cacheWrite5mTokens;
121
+ }
122
+ };
123
+
124
+ const finish = (): SingleTurnCacheWrites[] => {
125
+ const out: SingleTurnCacheWrites[] = [];
126
+
127
+ for (const [key, sessions] of slices) {
128
+ let singleTurnSessions = 0;
129
+ let write5m = 0;
130
+ let write1h = 0;
131
+ let assumed = 0;
132
+ const turnCounts: number[] = [];
133
+ for (const tally of sessions.values()) {
134
+ turnCounts.push(tally.turns);
135
+ if (tally.turns !== 1) continue;
136
+ singleTurnSessions += 1;
137
+ write5m += tally.write5mTokens;
138
+ write1h += tally.write1hTokens;
139
+ assumed += tally.assumedTokens;
140
+ }
141
+ const singleTurnWriteTokens = write5m + write1h + assumed;
142
+ // One-turn conversations that wrote nothing wasted nothing; a row about
143
+ // them would be a finding about the absence of a finding.
144
+ if (singleTurnWriteTokens === 0) continue;
145
+
146
+ const split = key.indexOf('\n');
147
+ const modelId = key.slice(split + 1);
148
+ const model = catalogue.byId.get(modelId)!;
149
+ const { inputPerMTok } = effectivePricing(model, on);
150
+ const rates = multipliersFor(model);
151
+ const per = (tokens: number, rate: number): number =>
152
+ (tokens / 1_000_000) * inputPerMTok * rate;
153
+ // The bill's own convention: unstated TTLs at the cheaper rate, so this
154
+ // is the same floor the totals already stand on — never a new guess.
155
+ const singleTurnWriteUsd =
156
+ per(write5m + assumed, rates.cacheWrite5m) + per(write1h, rates.cacheWrite1h);
157
+
158
+ turnCounts.sort((a, b) => a - b);
159
+ out.push({
160
+ label: key.slice(0, split),
161
+ model: modelId,
162
+ modelName: model.displayName,
163
+ sessions: sessions.size,
164
+ medianTurns: median(turnCounts),
165
+ singleTurnSessions,
166
+ singleTurnWriteTokens,
167
+ singleTurnWriteUsd,
168
+ assumedTtlTokens: assumed,
169
+ });
170
+ }
171
+
172
+ // The most money first — the order somebody would act in.
173
+ return out.sort(
174
+ (a, b) => b.singleTurnWriteUsd - a.singleTurnWriteUsd || a.label.localeCompare(b.label),
175
+ );
176
+ };
177
+
178
+ return { add, finish };
179
+ }
180
+
181
+ /** The same measurement over a list, for a caller holding one already. */
182
+ export function singleTurnCacheWrites(
183
+ records: readonly UsageRecord[],
184
+ options: SessionLedgerOptions,
185
+ ): SingleTurnCacheWrites[] {
186
+ const tracker = createSessionLedgerTracker(options);
187
+ for (const record of records) tracker.add(record);
188
+ return tracker.finish();
189
+ }
package/src/ttl-fit.ts ADDED
@@ -0,0 +1,251 @@
1
+ import { effectivePricing, multipliersFor } from './pricing.js';
2
+ import { UNLABELLED } from './usage.js';
3
+ import type { PricingCatalogue } from './pricing.js';
4
+ import type { UsageRecord } from './usage.js';
5
+
6
+ /**
7
+ * Does the cache TTL fit how fast the turns actually arrive?
8
+ *
9
+ * ## The mechanism nothing else can see
10
+ *
11
+ * A cache entry lives 5 minutes, or an hour at twice the write price. Whether
12
+ * either is the right choice depends on one number the bill never shows: **how
13
+ * long the workload waits between turns.** A support agent whose users answer in
14
+ * nine minutes writes a 5-minute entry on every turn and reads it back on none of
15
+ * them — every write expires unread, which from the bill is indistinguishable
16
+ * from any other losing cache. `cacheEconomics` can say *that* money was lost;
17
+ * only the clock can say *why*, and the why decides the fix: the 1-hour TTL, or
18
+ * caching switched off.
19
+ *
20
+ * The opposite mistake is quieter and this is the only place it appears at all:
21
+ * turns arriving seconds apart, written at the 1-hour rate. Those writes work —
22
+ * the verdict above reads `paid-off` — and every one of them pays 2x input for
23
+ * endurance the workload never uses. **Switching them to the 5-minute TTL is the
24
+ * one exact saving in this module**: the same tokens at 1.25x instead of 2x,
25
+ * which is the same-tokens-different-rate arithmetic `cacheEconomics` already
26
+ * draws the counterfactual line at.
27
+ *
28
+ * ## What it measures, and how it stays honest
29
+ *
30
+ * The gap between consecutive turns **of the same conversation**, from the
31
+ * recorded clock — sessions are what a cache entry actually serves, and gaps
32
+ * between unrelated calls of a label say nothing about whether *this*
33
+ * conversation's next turn found the entry alive. Timestamps are sorted within
34
+ * each session before differencing, so the measurement is independent of the
35
+ * order of the log — the property the conversation tracker had to learn the
36
+ * hard way.
37
+ *
38
+ * The reported number is the **median** gap, named as such: a median survives
39
+ * the overnight gap between a user's Tuesday and Wednesday in a way a mean does
40
+ * not, and a verdict hung on a mean would flip on one lunch break.
41
+ *
42
+ * When the log did not record which TTL the writes used, the gap can sit where
43
+ * the verdict depends on the answer — over 5 minutes and under an hour survives
44
+ * one TTL and not the other. That is reported as `unsettled`, the same refusal
45
+ * `cacheEconomics` makes for the same missing field, and never resolved in the
46
+ * flattering direction.
47
+ *
48
+ * The session key is used to group turns and never leaves this module, like
49
+ * everywhere else the field is touched.
50
+ */
51
+
52
+ /** Cache-entry lifetimes, in milliseconds. Anthropic's two published TTLs. */
53
+ export const TTL_5M_MS = 5 * 60 * 1000;
54
+ export const TTL_1H_MS = 60 * 60 * 1000;
55
+
56
+ export type TtlFitVerdict =
57
+ /** The median gap outlives the entry: writes expire before the next turn. */
58
+ | 'expires-before-reuse'
59
+ /** 1-hour writes on gaps inside the 5-minute window: paying 2x for nothing. */
60
+ | 'overlong-ttl'
61
+ /** The TTL the log did not record decides the verdict, so nothing does. */
62
+ | 'unsettled'
63
+ /** The entry outlives the gap at the TTL the writes actually used. */
64
+ | 'fits';
65
+
66
+ export interface CacheTtlFit {
67
+ label: string;
68
+ model: string;
69
+ modelName: string;
70
+ /** Conversations with at least two timestamped turns. Never which ones. */
71
+ sessions: number;
72
+ /** Gaps measured across them. */
73
+ gaps: number;
74
+ medianGapMs: number;
75
+ /** Write tokens the log said were 5-minute entries. */
76
+ write5mTokens: number;
77
+ /** Write tokens the log said were 1-hour entries. */
78
+ write1hTokens: number;
79
+ /** Write tokens whose TTL the log did not record. */
80
+ assumedTtlTokens: number;
81
+ verdict: TtlFitVerdict;
82
+ /**
83
+ * What the 1-hour writes would save at the 5-minute rate, when the gaps show
84
+ * the hour is never needed. Exact — the same tokens at 1.25x instead of 2x,
85
+ * at the model's own input rate — and zero for every other verdict.
86
+ */
87
+ overpayUsd: number;
88
+ }
89
+
90
+ export interface TtlFitOptions {
91
+ catalogue: PricingCatalogue;
92
+ /** Date the prices are read at, so a promotional rate resolves the same way. */
93
+ on?: Date;
94
+ }
95
+
96
+ export interface TtlFitTracker {
97
+ /** Feed one parsed record. */
98
+ add(record: UsageRecord): void;
99
+ /** The finished measurement. */
100
+ finish(): CacheTtlFit[];
101
+ }
102
+
103
+ interface Slice {
104
+ write5mTokens: number;
105
+ write1hTokens: number;
106
+ assumedTtlTokens: number;
107
+ /** Timestamps per session, sorted only at the end. */
108
+ sessions: Map<string, number[]>;
109
+ }
110
+
111
+ const median = (sorted: number[]): number => {
112
+ const mid = Math.floor(sorted.length / 2);
113
+ return sorted.length % 2 === 1 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2;
114
+ };
115
+
116
+ /**
117
+ * An accumulator, like the conversation tracker and for the same reason: a
118
+ * usage log is measured in megabytes and `profileUsage` makes one pass. What
119
+ * this holds is one number per timestamped call that belongs to a session,
120
+ * which is the minimum the gaps can be computed from at all.
121
+ */
122
+ export function createTtlFitTracker(options: TtlFitOptions): TtlFitTracker {
123
+ const { catalogue, on = new Date() } = options;
124
+ const slices = new Map<string, Slice>();
125
+
126
+ const add = (record: UsageRecord): void => {
127
+ // An unpriced model has no rates to judge a TTL against, and contributes no
128
+ // dollars anywhere else either.
129
+ if (!catalogue.byId.has(record.model)) return;
130
+
131
+ const writes =
132
+ record.cacheWrite5mTokens + record.cacheWrite1hTokens;
133
+ const hasClockedTurn = record.session !== null && record.ts !== null;
134
+ // A slice exists once it writes to the cache or can contribute a gap;
135
+ // everything else has nothing to say here.
136
+ if (writes === 0 && !hasClockedTurn) return;
137
+
138
+ const key = `${record.label ?? UNLABELLED}\n${record.model}`;
139
+ let slice = slices.get(key);
140
+ if (!slice) {
141
+ slice = { write5mTokens: 0, write1hTokens: 0, assumedTtlTokens: 0, sessions: new Map() };
142
+ slices.set(key, slice);
143
+ }
144
+
145
+ if (record.writeTtlKnown) {
146
+ slice.write5mTokens += record.cacheWrite5mTokens;
147
+ slice.write1hTokens += record.cacheWrite1hTokens;
148
+ } else {
149
+ // The flat count sits in the 5m bucket by pricing convention; here it is
150
+ // kept apart, because the whole question is which TTL it really was.
151
+ slice.assumedTtlTokens += record.cacheWrite5mTokens;
152
+ }
153
+
154
+ if (hasClockedTurn) {
155
+ const turns = slice.sessions.get(record.session!);
156
+ if (turns) turns.push(record.ts!);
157
+ else slice.sessions.set(record.session!, [record.ts!]);
158
+ }
159
+ };
160
+
161
+ const finish = (): CacheTtlFit[] => {
162
+ const out: CacheTtlFit[] = [];
163
+
164
+ for (const [key, slice] of slices) {
165
+ const writes = slice.write5mTokens + slice.write1hTokens + slice.assumedTtlTokens;
166
+ // No writes means no TTL to judge. Gaps alone are the conversation
167
+ // tracker's business, not this module's.
168
+ if (writes === 0) continue;
169
+
170
+ const gaps: number[] = [];
171
+ let sessions = 0;
172
+ for (const turns of slice.sessions.values()) {
173
+ if (turns.length < 2) continue;
174
+ sessions += 1;
175
+ turns.sort((a, b) => a - b);
176
+ for (let i = 1; i < turns.length; i += 1) gaps.push(turns[i]! - turns[i - 1]!);
177
+ }
178
+ // Writes with no measurable gap: the caller reports "could not be
179
+ // measured" from the absence of a row, the same way missing sessions
180
+ // read everywhere else.
181
+ if (gaps.length === 0) continue;
182
+
183
+ const split = key.indexOf('\n');
184
+ const modelId = key.slice(split + 1);
185
+ const model = catalogue.byId.get(modelId)!;
186
+
187
+ gaps.sort((a, b) => a - b);
188
+ const gap = median(gaps);
189
+
190
+ /**
191
+ * First match wins, ordered so that a certain failure outranks an
192
+ * uncertain one and money comes last: writes that expire are broken at
193
+ * any price, and only writes that demonstrably work can be overpaying.
194
+ */
195
+ let verdict: TtlFitVerdict;
196
+ if (slice.write5mTokens > 0 && gap > TTL_5M_MS) verdict = 'expires-before-reuse';
197
+ else if (slice.write1hTokens > 0 && gap > TTL_1H_MS) verdict = 'expires-before-reuse';
198
+ else if (slice.assumedTtlTokens > 0 && gap > TTL_1H_MS) verdict = 'expires-before-reuse';
199
+ else if (slice.write1hTokens > 0 && gap <= TTL_5M_MS) verdict = 'overlong-ttl';
200
+ else if (slice.assumedTtlTokens > 0 && gap > TTL_5M_MS) verdict = 'unsettled';
201
+ else verdict = 'fits';
202
+
203
+ const { inputPerMTok } = effectivePricing(model, on);
204
+ const rates = multipliersFor(model);
205
+ const overpayUsd =
206
+ verdict === 'overlong-ttl'
207
+ ? (slice.write1hTokens / 1_000_000) *
208
+ inputPerMTok *
209
+ (rates.cacheWrite1h - rates.cacheWrite5m)
210
+ : 0;
211
+
212
+ out.push({
213
+ label: key.slice(0, split),
214
+ model: modelId,
215
+ modelName: model.displayName,
216
+ sessions,
217
+ gaps: gaps.length,
218
+ medianGapMs: gap,
219
+ write5mTokens: slice.write5mTokens,
220
+ write1hTokens: slice.write1hTokens,
221
+ assumedTtlTokens: slice.assumedTtlTokens,
222
+ verdict,
223
+ overpayUsd,
224
+ });
225
+ }
226
+
227
+ // Broken first, then overpaying by money, then the rest — the order
228
+ // somebody would act in.
229
+ const rank: Record<TtlFitVerdict, number> = {
230
+ 'expires-before-reuse': 0,
231
+ 'overlong-ttl': 1,
232
+ unsettled: 2,
233
+ fits: 3,
234
+ };
235
+ return out.sort(
236
+ (a, b) => rank[a.verdict] - rank[b.verdict] || b.overpayUsd - a.overpayUsd,
237
+ );
238
+ };
239
+
240
+ return { add, finish };
241
+ }
242
+
243
+ /** The same measurement over a list, for a caller holding one already. */
244
+ export function cacheTtlFit(
245
+ records: readonly UsageRecord[],
246
+ options: TtlFitOptions,
247
+ ): CacheTtlFit[] {
248
+ const tracker = createTtlFitTracker(options);
249
+ for (const record of records) tracker.add(record);
250
+ return tracker.finish();
251
+ }