@trazum/core 1.81.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.
Files changed (84) hide show
  1. package/README.md +34 -18
  2. package/dist/advisories.d.ts +33 -1
  3. package/dist/advisories.d.ts.map +1 -1
  4. package/dist/advisories.js +130 -20
  5. package/dist/advisories.js.map +1 -1
  6. package/dist/band.d.ts +131 -0
  7. package/dist/band.d.ts.map +1 -0
  8. package/dist/band.js +210 -0
  9. package/dist/band.js.map +1 -0
  10. package/dist/conform.d.ts +1 -1
  11. package/dist/conform.d.ts.map +1 -1
  12. package/dist/conform.js +84 -1
  13. package/dist/conform.js.map +1 -1
  14. package/dist/helicone.d.ts +92 -0
  15. package/dist/helicone.d.ts.map +1 -0
  16. package/dist/helicone.js +194 -0
  17. package/dist/helicone.js.map +1 -0
  18. package/dist/i18n/en.d.ts.map +1 -1
  19. package/dist/i18n/en.js +16 -3
  20. package/dist/i18n/en.js.map +1 -1
  21. package/dist/i18n/es.d.ts.map +1 -1
  22. package/dist/i18n/es.js +17 -3
  23. package/dist/i18n/es.js.map +1 -1
  24. package/dist/i18n/types.d.ts +60 -1
  25. package/dist/i18n/types.d.ts.map +1 -1
  26. package/dist/index.d.ts +16 -3
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +9 -3
  29. package/dist/index.js.map +1 -1
  30. package/dist/langsmith.d.ts +104 -0
  31. package/dist/langsmith.d.ts.map +1 -0
  32. package/dist/langsmith.js +270 -0
  33. package/dist/langsmith.js.map +1 -0
  34. package/dist/levers.d.ts +1 -1
  35. package/dist/levers.js +2 -2
  36. package/dist/levers.js.map +1 -1
  37. package/dist/litellm.d.ts +98 -0
  38. package/dist/litellm.d.ts.map +1 -0
  39. package/dist/litellm.js +207 -0
  40. package/dist/litellm.js.map +1 -0
  41. package/dist/measured-profile.d.ts +4 -0
  42. package/dist/measured-profile.d.ts.map +1 -1
  43. package/dist/measured-profile.js +22 -1
  44. package/dist/measured-profile.js.map +1 -1
  45. package/dist/pricing.d.ts +98 -3
  46. package/dist/pricing.d.ts.map +1 -1
  47. package/dist/pricing.js +393 -35
  48. package/dist/pricing.js.map +1 -1
  49. package/dist/receipt.d.ts +253 -0
  50. package/dist/receipt.d.ts.map +1 -0
  51. package/dist/receipt.js +111 -0
  52. package/dist/receipt.js.map +1 -0
  53. package/dist/schemas.d.ts.map +1 -1
  54. package/dist/schemas.js +36 -0
  55. package/dist/schemas.js.map +1 -1
  56. package/dist/tokenizer.d.ts +45 -49
  57. package/dist/tokenizer.d.ts.map +1 -1
  58. package/dist/tokenizer.js +100 -51
  59. package/dist/tokenizer.js.map +1 -1
  60. package/dist/types.d.ts +108 -1
  61. package/dist/types.d.ts.map +1 -1
  62. package/dist/verdict-bridge.d.ts +113 -0
  63. package/dist/verdict-bridge.d.ts.map +1 -0
  64. package/dist/verdict-bridge.js +127 -0
  65. package/dist/verdict-bridge.js.map +1 -0
  66. package/package.json +1 -1
  67. package/src/advisories.ts +166 -19
  68. package/src/band.ts +213 -0
  69. package/src/conform.ts +100 -1
  70. package/src/helicone.ts +227 -0
  71. package/src/i18n/en.ts +19 -3
  72. package/src/i18n/es.ts +20 -3
  73. package/src/i18n/types.ts +63 -1
  74. package/src/index.ts +31 -2
  75. package/src/langsmith.ts +315 -0
  76. package/src/levers.ts +3 -3
  77. package/src/litellm.ts +243 -0
  78. package/src/measured-profile.ts +26 -2
  79. package/src/pricing.ts +430 -30
  80. package/src/receipt.ts +351 -0
  81. package/src/schemas.ts +36 -0
  82. package/src/tokenizer.ts +101 -51
  83. package/src/types.ts +104 -0
  84. package/src/verdict-bridge.ts +200 -0
@@ -0,0 +1,315 @@
1
+ /**
2
+ * LangSmith's run export, read as a usage log.
3
+ *
4
+ * The fifth converter in the pattern `from-claude-code` started: a pure
5
+ * function turns one tool's export into Trazum's usage-log records, and every
6
+ * door prices it from there. LangSmith is the tracing product most LangChain
7
+ * teams already run, so the export exists before Trazum does.
8
+ *
9
+ * **The format is derived, not guessed.** Every field below is `RunBase` and
10
+ * `Run` in `python/langsmith/schemas.py` in langchain-ai/langsmith-sdk. A
11
+ * converter written from memory of an API is a converter that silently
12
+ * mis-reads somebody's bill.
13
+ *
14
+ * ## A run is not a call, and that is the whole difficulty
15
+ *
16
+ * LangSmith records a **run**, and a trace is a tree of them: chains, tools and
17
+ * retrievers alongside the model calls. Only `run_type: "llm"` carries token
18
+ * counts, and summing the tree would count the same tokens once per level. So
19
+ * everything else is skipped and **counted out loud** — a converter that
20
+ * quietly dropped two thirds of a file would look like one that read it.
21
+ *
22
+ * ## The model, and why it is refused rather than inferred
23
+ *
24
+ * There is no model column. The name lives in `extra.metadata.ls_model_name`,
25
+ * or in the invocation parameters the SDK records beside it, and a run whose
26
+ * metadata carries neither cannot be priced. The obvious guess is the run's
27
+ * own `name` — LangChain names them after the class, `ChatOpenAI`, which is a
28
+ * client and not a model. Pricing a call by the class that made it would be a
29
+ * figure attributed to something it does not describe, which is the fault this
30
+ * repository keeps finding in itself. Such a run is counted in `unnamedModel`
31
+ * and dropped.
32
+ *
33
+ * ## What deliberately does not cross
34
+ *
35
+ * `inputs` and `outputs` are the prompt and the completion, on every single
36
+ * run. **Neither is read.** `extra.metadata` is read for two named keys and
37
+ * nothing else, because it is a free-form bag the operator fills and the next
38
+ * thing they put in it might be a credential. The converter names the fields
39
+ * it takes and takes nothing else, and a fixture plants a marker in each and
40
+ * greps the whole output.
41
+ *
42
+ * ## What it refuses to invent
43
+ *
44
+ * There is no cache-token split. `prompt_cost_details` looks like one and is
45
+ * not: it is LangSmith's own priced breakdown in dollars, computed from
46
+ * LangSmith's price table. It never enters a record, and neither does
47
+ * `total_cost` — `reportedCostUsd` returns it on its own, the way
48
+ * `from-litellm` keeps the gateway's arithmetic apart from Trazum's. Two price
49
+ * tables, two figures; merging them is how a report becomes quietly wrong.
50
+ */
51
+
52
+ /** One converted record, shaped exactly as `parseUsageLine` reads it. */
53
+ export interface LangsmithRecord {
54
+ model: string;
55
+ ts?: string;
56
+ label?: string;
57
+ session?: string;
58
+ usage: {
59
+ input_tokens: number;
60
+ output_tokens: number;
61
+ };
62
+ }
63
+
64
+ export interface LangsmithConversion {
65
+ records: LangsmithRecord[];
66
+ /** Runs that were model calls and converted. */
67
+ rows: number;
68
+ /**
69
+ * Runs that were not model calls: chains, tools, retrievers, prompts.
70
+ *
71
+ * Counted rather than ignored. They are most of a LangSmith export, and a
72
+ * reader who converted a thousand runs into three hundred records is owed
73
+ * the reason.
74
+ */
75
+ notModelCalls: number;
76
+ /** Model calls whose metadata named no model: counted, never guessed. */
77
+ unnamedModel: number;
78
+ /** Model calls carrying no token counts at all. */
79
+ noTokens: number;
80
+ /**
81
+ * LangSmith's own cost total, in dollars, or null when no run reported one.
82
+ *
83
+ * Kept apart from anything Trazum computes and never merged into a record.
84
+ * Null is an absence, not a total of nothing.
85
+ */
86
+ reportedCostUsd: number | null;
87
+ /** Lines or documents that did not parse as JSON at all. */
88
+ unparseable: number;
89
+ }
90
+
91
+ const asObject = (value: unknown): Record<string, unknown> | null =>
92
+ typeof value === 'object' && value !== null && !Array.isArray(value)
93
+ ? (value as Record<string, unknown>)
94
+ : null;
95
+
96
+ const tryParse = (text: string): unknown => {
97
+ try {
98
+ return JSON.parse(text);
99
+ } catch {
100
+ return undefined;
101
+ }
102
+ };
103
+
104
+ const asCount = (value: unknown): number | undefined => {
105
+ const n = typeof value === 'string' ? Number(value) : value;
106
+ return typeof n === 'number' && Number.isFinite(n) && n >= 0 ? n : undefined;
107
+ };
108
+
109
+ const asName = (value: unknown): string | null =>
110
+ typeof value === 'string' && value.trim() !== '' ? value.trim() : null;
111
+
112
+ /** `extra.metadata`, which is where LangSmith documents everything user-set. */
113
+ function metadataOf(run: Record<string, unknown>): Record<string, unknown> | null {
114
+ const extra = asObject(run.extra);
115
+ return extra === null ? asObject(run.metadata) : (asObject(extra.metadata) ?? asObject(run.metadata));
116
+ }
117
+
118
+ /**
119
+ * The model, from the two named places it is recorded and nowhere else.
120
+ *
121
+ * `ls_model_name` is what the SDK writes; `model` and `model_name` are what a
122
+ * team writes by hand when they set metadata themselves. The run's `name` is
123
+ * deliberately not consulted: LangChain names a run after the client class,
124
+ * and `ChatOpenAI` is not a model anybody can price.
125
+ */
126
+ function modelOf(run: Record<string, unknown>): string | null {
127
+ const metadata = metadataOf(run);
128
+ if (metadata !== null) {
129
+ for (const key of ['ls_model_name', 'model_name', 'model']) {
130
+ const found = asName(metadata[key]);
131
+ if (found !== null) return found;
132
+ }
133
+ // The invocation parameters, where the SDK also records it.
134
+ const params = asObject(metadata.invocation_params);
135
+ if (params !== null) {
136
+ for (const key of ['model', 'model_name']) {
137
+ const found = asName(params[key]);
138
+ if (found !== null) return found;
139
+ }
140
+ }
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /**
146
+ * The label, from the tags a team already puts on its traces.
147
+ *
148
+ * `tags` is LangSmith's own list and the first entry wins, because a workload
149
+ * has one name in a bill. Then the two metadata keys a team would plausibly
150
+ * name a workload by. Never joined, never invented.
151
+ */
152
+ function labelOf(run: Record<string, unknown>): string | undefined {
153
+ if (Array.isArray(run.tags)) {
154
+ for (const tag of run.tags) {
155
+ const found = asName(tag);
156
+ if (found !== null) return found;
157
+ }
158
+ }
159
+ const metadata = metadataOf(run);
160
+ if (metadata !== null) {
161
+ for (const key of ['label', 'workload']) {
162
+ const found = asName(metadata[key]);
163
+ if (found !== null) return found;
164
+ }
165
+ }
166
+ return undefined;
167
+ }
168
+
169
+ /** The run's start time as an ISO instant, or undefined. */
170
+ function timeOf(run: Record<string, unknown>): string | undefined {
171
+ const raw = run.start_time ?? run.startTime;
172
+ if (typeof raw !== 'string' && typeof raw !== 'number') return undefined;
173
+ const ms = typeof raw === 'number' ? raw : Date.parse(raw);
174
+ if (!Number.isFinite(ms)) return undefined;
175
+ return new Date(ms).toISOString();
176
+ }
177
+
178
+ /**
179
+ * The token counts, from the two shapes LangSmith has written them in.
180
+ *
181
+ * `prompt_tokens` and `completion_tokens` sit on the run; newer exports also
182
+ * carry a nested `usage_metadata` with `input_tokens` and `output_tokens`.
183
+ * Both are read because both are in the wild, and an export from last year is
184
+ * still somebody's bill.
185
+ */
186
+ function tokensOf(run: Record<string, unknown>): { input?: number; output?: number } {
187
+ const nested = asObject(run.usage_metadata);
188
+ return {
189
+ input: asCount(run.prompt_tokens) ?? asCount(nested?.input_tokens),
190
+ output: asCount(run.completion_tokens) ?? asCount(nested?.output_tokens),
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Convert a LangSmith run export.
196
+ *
197
+ * Accepts a JSON array of runs, a single run, `{ runs: [...] }` as the list
198
+ * endpoint returns it, or newline-delimited runs. Pure over its input.
199
+ */
200
+ export function langsmithRecords(text: string): LangsmithConversion {
201
+ const out: LangsmithConversion = {
202
+ records: [],
203
+ rows: 0,
204
+ notModelCalls: 0,
205
+ unnamedModel: 0,
206
+ noTokens: 0,
207
+ reportedCostUsd: null,
208
+ unparseable: 0,
209
+ };
210
+
211
+ const runs: unknown[] = [];
212
+ const whole = tryParse(text);
213
+ if (whole !== undefined) {
214
+ if (Array.isArray(whole)) runs.push(...whole);
215
+ else {
216
+ const doc = asObject(whole);
217
+ if (doc !== null && Array.isArray(doc.runs)) runs.push(...doc.runs);
218
+ else if (doc !== null) runs.push(doc);
219
+ }
220
+ } else {
221
+ for (const line of text.split('\n')) {
222
+ if (line.trim() === '') continue;
223
+ const parsed = tryParse(line);
224
+ if (parsed === undefined) out.unparseable += 1;
225
+ else if (Array.isArray(parsed)) runs.push(...parsed);
226
+ else runs.push(parsed);
227
+ }
228
+ }
229
+
230
+ let cost = 0;
231
+ let sawCost = false;
232
+
233
+ for (const raw of runs) {
234
+ const run = asObject(raw);
235
+ if (run === null) continue;
236
+
237
+ /*
238
+ A run is only a call when LangSmith says it is one. The tree carries
239
+ chains, tools, retrievers and prompts alongside the model calls, and the
240
+ parent chain of an llm run repeats its child's tokens: summing the tree
241
+ would bill the same tokens once per level. `run_type` is the field that
242
+ settles it, and a run with no run_type at all is not a run.
243
+ */
244
+ const type = asName(run.run_type);
245
+ if (type === null) continue;
246
+ if (type !== 'llm') {
247
+ out.notModelCalls += 1;
248
+ continue;
249
+ }
250
+
251
+ out.rows += 1;
252
+
253
+ const reported = asCount(run.total_cost);
254
+ if (reported !== undefined) {
255
+ cost += reported;
256
+ sawCost = true;
257
+ }
258
+
259
+ const model = modelOf(run);
260
+ if (model === null) {
261
+ out.unnamedModel += 1;
262
+ continue;
263
+ }
264
+
265
+ const { input, output } = tokensOf(run);
266
+ if (input === undefined && output === undefined) {
267
+ out.noTokens += 1;
268
+ continue;
269
+ }
270
+ if (input === 0 && output === 0) out.noTokens += 1;
271
+
272
+ const ts = timeOf(run);
273
+ const label = labelOf(run);
274
+ /*
275
+ The trace is the conversation and the run id is one call. `trace_id`
276
+ spans the calls a single request made, which is the identity Trazum's
277
+ conversation findings need; answering them from `id` would report every
278
+ call as a conversation of one.
279
+ */
280
+ const session = asName(run.trace_id);
281
+
282
+ out.records.push({
283
+ model,
284
+ ...(ts !== undefined ? { ts } : {}),
285
+ ...(label !== undefined ? { label } : {}),
286
+ ...(session !== null ? { session } : {}),
287
+ usage: { input_tokens: input ?? 0, output_tokens: output ?? 0 },
288
+ });
289
+ }
290
+
291
+ // Rounded because these are dollars summed in floating point, and a total
292
+ // printed to eight decimal places reads as a precision nobody has.
293
+ if (sawCost) out.reportedCostUsd = Math.round(cost * 1e6) / 1e6;
294
+
295
+ return out;
296
+ }
297
+
298
+ /**
299
+ * Whether a file looks like a LangSmith run export, by shape.
300
+ *
301
+ * Deliberately narrow: `run_type` beside one of the trace fields only
302
+ * LangSmith writes. A looser test would claim a Helicone export or a LiteLLM
303
+ * spend log — both carry `prompt_tokens` — and refuse it in this file's words
304
+ * instead of letting the code that can read it try.
305
+ */
306
+ export function looksLikeLangsmith(text: string, prefixBytes = 8192): boolean {
307
+ const head = text.slice(0, prefixBytes);
308
+ if (!head.includes('"run_type"')) return false;
309
+ return (
310
+ head.includes('"trace_id"') ||
311
+ head.includes('"dotted_order"') ||
312
+ head.includes('"start_time"') ||
313
+ head.includes('"session_id"')
314
+ );
315
+ }
package/src/levers.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { effectivePricing, multipliersFor } from './pricing.js';
1
+ import { effectivePricing, isOffered, multipliersFor } from './pricing.js';
2
2
  import { UNLABELLED } from './usage.js';
3
3
  import type { PricingCatalogue } from './pricing.js';
4
4
  import type { UsageBreakdown, UsageProfileReport } from './usage.js';
@@ -21,7 +21,7 @@ import type { Capability, ModelPricing } from './types.js';
21
21
  *
22
22
  * | lever | what it moves |
23
23
  * |---|---|
24
- * | which model the call goes to | Opus 5 → Sonnet 5 is 40% off; → Haiku 4.5 is 80% |
24
+ * | which model the call goes to | Opus 5 → Sonnet 5 is 60% off; → Haiku 4.5 is 80% |
25
25
  * | the Batch API | 50% flat, on input and output |
26
26
  * | prompt caching | 3–4x the rules |
27
27
  * | shortening the prompt | ~1% |
@@ -204,7 +204,7 @@ function candidateFor(
204
204
  m.id !== model.id &&
205
205
  m.capability === target &&
206
206
  m.provider === model.provider &&
207
- m.recommendable !== false &&
207
+ isOffered(m) &&
208
208
  m.contextWindow >= avgInput,
209
209
  );
210
210
  if (candidates.length === 0) return null;
package/src/litellm.ts ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * LiteLLM's spend log, read as a usage log.
3
+ *
4
+ * `from-claude-code` proved the pattern and `from-otel` generalised it: a pure
5
+ * converter turns one tool's export into Trazum's usage-log records, and every
6
+ * door prices it from there. LiteLLM is the gateway a great many teams already
7
+ * put in front of every provider, so its `LiteLLM_SpendLogs` table is the one
8
+ * export most likely to already exist on somebody's disk.
9
+ *
10
+ * **The format is derived, not guessed.** Every field below is read off
11
+ * `litellm/proxy/schema.prisma` in BerriAI/litellm, model `LiteLLM_SpendLogs`.
12
+ * A converter written from memory of an API is a converter that silently
13
+ * mis-reads somebody's bill, and this project has one rule above all others
14
+ * about numbers it cannot justify.
15
+ *
16
+ * ## What maps
17
+ *
18
+ * | LiteLLM | Trazum |
19
+ * | --- | --- |
20
+ * | `model` | `model` |
21
+ * | `prompt_tokens` | `usage.input_tokens` |
22
+ * | `completion_tokens` | `usage.output_tokens` |
23
+ * | `startTime` | `ts` |
24
+ * | `session_id` | `session` |
25
+ * | `request_tags[0]`, else `metadata.tags[0]`, else `model_group` | `label` |
26
+ *
27
+ * ## What deliberately does not cross
28
+ *
29
+ * The row carries `messages` and `response` — the prompt itself and the
30
+ * completion — plus `api_key` (hashed, still credential-shaped),
31
+ * `requester_ip_address`, `user` and `end_user`. **None of it is read.** The
32
+ * converter names the fields it takes and takes nothing else, and a fixture
33
+ * plants a marker in each of them and greps the whole output.
34
+ *
35
+ * ## What it refuses to invent
36
+ *
37
+ * `cache_hit` is a flag and `cache_key` an identifier; neither is a token
38
+ * count. A converted record therefore carries no cache split at all, and the
39
+ * caching questions come back `cannot-tell` rather than answered from a
40
+ * guess — the same refusal as inventing a price. `cacheFlagged` counts the
41
+ * rows that said "hit" so the operator can see the gap is real rather than
42
+ * empty.
43
+ *
44
+ * `spend` is LiteLLM's own priced figure and is **never** merged into
45
+ * Trazum's catalogue-priced total. It is a second measurement of the same
46
+ * calls, kept apart the way the store's provider-billed standing is kept
47
+ * apart from the log's, and returned on its own so a caller who wants to
48
+ * compare the two can, deliberately.
49
+ */
50
+
51
+ /** One converted record, shaped exactly as `parseUsageLine` reads it. */
52
+ export interface LiteLlmRecord {
53
+ model: string;
54
+ ts?: string;
55
+ label?: string;
56
+ session?: string;
57
+ usage: {
58
+ input_tokens: number;
59
+ output_tokens: number;
60
+ };
61
+ }
62
+
63
+ export interface LiteLlmConversion {
64
+ records: LiteLlmRecord[];
65
+ /** Rows that were spend logs and converted. */
66
+ rows: number;
67
+ /** Rows naming no model: counted, never guessed at, never dropped silently. */
68
+ unnamedModel: number;
69
+ /** Rows carrying no token counts at all — a logged call nobody can price. */
70
+ noTokens: number;
71
+ /** Rows LiteLLM marked as a cache hit, with no token split to act on. */
72
+ cacheFlagged: number;
73
+ /**
74
+ * LiteLLM's own total for the converted rows, in USD, or null when no row
75
+ * carried one. **Never** added to anything Trazum computes: it is the
76
+ * gateway's arithmetic over the gateway's price table, and merging two
77
+ * price tables into one figure is how a report becomes quietly wrong.
78
+ */
79
+ reportedSpendUsd: number | null;
80
+ /** Lines or documents that did not parse as JSON at all. */
81
+ unparseable: number;
82
+ }
83
+
84
+ const asObject = (value: unknown): Record<string, unknown> | null =>
85
+ typeof value === 'object' && value !== null && !Array.isArray(value)
86
+ ? (value as Record<string, unknown>)
87
+ : null;
88
+
89
+ const tryParse = (text: string): unknown => {
90
+ try {
91
+ return JSON.parse(text);
92
+ } catch {
93
+ return undefined;
94
+ }
95
+ };
96
+
97
+ const asCount = (value: unknown): number | undefined => {
98
+ const n = typeof value === 'string' ? Number(value) : value;
99
+ return typeof n === 'number' && Number.isFinite(n) && n >= 0 ? n : undefined;
100
+ };
101
+
102
+ /**
103
+ * The first tag LiteLLM carries for a row, from the two places it puts them.
104
+ *
105
+ * `request_tags` is the documented column and `metadata.tags` is where the
106
+ * proxy writes them when the caller passes them in the request body. First
107
+ * only: a workload has one name in a bill, and joining several tags into one
108
+ * label would invent a workload that does not exist.
109
+ */
110
+ function labelOf(row: Record<string, unknown>): string | undefined {
111
+ const fromColumn = Array.isArray(row.request_tags) ? row.request_tags : null;
112
+ if (fromColumn !== null && typeof fromColumn[0] === 'string' && fromColumn[0] !== '') {
113
+ return fromColumn[0];
114
+ }
115
+ const metadata = asObject(row.metadata);
116
+ const fromMetadata = metadata !== null && Array.isArray(metadata.tags) ? metadata.tags : null;
117
+ if (fromMetadata !== null && typeof fromMetadata[0] === 'string' && fromMetadata[0] !== '') {
118
+ return fromMetadata[0];
119
+ }
120
+ // The public model name a proxy route is known by. A weaker label than a
121
+ // tag — it groups by route rather than by workload — and better than none.
122
+ if (typeof row.model_group === 'string' && row.model_group !== '') return row.model_group;
123
+ return undefined;
124
+ }
125
+
126
+ /** `startTime` as an ISO instant, or undefined when it is not a time. */
127
+ function timeOf(row: Record<string, unknown>): string | undefined {
128
+ const raw = row.startTime ?? row.start_time;
129
+ if (typeof raw !== 'string' && typeof raw !== 'number') return undefined;
130
+ const ms = typeof raw === 'number' ? raw : Date.parse(raw);
131
+ if (!Number.isFinite(ms)) return undefined;
132
+ return new Date(ms).toISOString();
133
+ }
134
+
135
+ /**
136
+ * Convert a LiteLLM spend-log export.
137
+ *
138
+ * Accepts a JSON array of rows, a single row, `{ data: [...] }` as the proxy's
139
+ * own endpoints return it, or newline-delimited rows — so a `psql --json`
140
+ * dump, an API response and a streamed capture all work. Pure over its input.
141
+ */
142
+ export function litellmRecords(text: string): LiteLlmConversion {
143
+ const out: LiteLlmConversion = {
144
+ records: [],
145
+ rows: 0,
146
+ unnamedModel: 0,
147
+ noTokens: 0,
148
+ cacheFlagged: 0,
149
+ reportedSpendUsd: null,
150
+ unparseable: 0,
151
+ };
152
+
153
+ const rows: unknown[] = [];
154
+ const whole = tryParse(text);
155
+ if (whole !== undefined) {
156
+ if (Array.isArray(whole)) rows.push(...whole);
157
+ else {
158
+ const doc = asObject(whole);
159
+ // `{ data: [...] }` is what the proxy's spend endpoints return.
160
+ if (doc !== null && Array.isArray(doc.data)) rows.push(...doc.data);
161
+ else if (doc !== null) rows.push(doc);
162
+ }
163
+ } else {
164
+ for (const line of text.split('\n')) {
165
+ if (line.trim() === '') continue;
166
+ const parsed = tryParse(line);
167
+ if (parsed === undefined) out.unparseable += 1;
168
+ else if (Array.isArray(parsed)) rows.push(...parsed);
169
+ else rows.push(parsed);
170
+ }
171
+ }
172
+
173
+ let spend = 0;
174
+ let sawSpend = false;
175
+
176
+ for (const raw of rows) {
177
+ const row = asObject(raw);
178
+ if (row === null) continue;
179
+ // A spend log row is one that carries at least one of the two token
180
+ // columns. Anything else in the same file is not a call and is skipped
181
+ // rather than converted into a record of zero.
182
+ const input = asCount(row.prompt_tokens);
183
+ const output = asCount(row.completion_tokens);
184
+ if (input === undefined && output === undefined) continue;
185
+
186
+ out.rows += 1;
187
+
188
+ if (input === 0 && output === 0) out.noTokens += 1;
189
+ if (row.cache_hit === true || row.cache_hit === 'true' || row.cache_hit === 'True') {
190
+ out.cacheFlagged += 1;
191
+ }
192
+
193
+ const reported = asCount(row.spend);
194
+ if (reported !== undefined) {
195
+ spend += reported;
196
+ sawSpend = true;
197
+ }
198
+
199
+ const model = typeof row.model === 'string' ? row.model.trim() : '';
200
+ if (model === '') {
201
+ // Counted, never guessed at. `model_group` is a route name, not a model,
202
+ // and pricing a call by the route it took would be a figure attributed
203
+ // to something it does not describe.
204
+ out.unnamedModel += 1;
205
+ continue;
206
+ }
207
+
208
+ const ts = timeOf(row);
209
+ const label = labelOf(row);
210
+ const session = typeof row.session_id === 'string' && row.session_id !== ''
211
+ ? row.session_id
212
+ : undefined;
213
+
214
+ out.records.push({
215
+ model,
216
+ ...(ts !== undefined ? { ts } : {}),
217
+ ...(label !== undefined ? { label } : {}),
218
+ ...(session !== undefined ? { session } : {}),
219
+ usage: { input_tokens: input ?? 0, output_tokens: output ?? 0 },
220
+ });
221
+ }
222
+
223
+ out.reportedSpendUsd = sawSpend ? spend : null;
224
+ return out;
225
+ }
226
+
227
+ /**
228
+ * Whether a file looks like a LiteLLM spend log, by shape.
229
+ *
230
+ * Deliberately narrow: `request_id` beside one of the two token columns, and
231
+ * a field no other export in this project carries. A looser test would claim
232
+ * an OpenAI usage response, whose rows also have `prompt_tokens`, and refuse
233
+ * it in this file's words instead of letting the code that can read it try.
234
+ */
235
+ export function looksLikeLiteLlm(text: string, prefixBytes = 8192): boolean {
236
+ const head = text.slice(0, prefixBytes);
237
+ if (!head.includes('prompt_tokens') && !head.includes('completion_tokens')) return false;
238
+ return (
239
+ head.includes('"request_id"') ||
240
+ head.includes('"custom_llm_provider"') ||
241
+ head.includes('"model_group"')
242
+ );
243
+ }
@@ -70,6 +70,10 @@ export interface MeasuredUsage {
70
70
  * call is the same size. It is handed over as the better of two
71
71
  * approximations — a measured token share beats a typed call share — and
72
72
  * named honestly here so no rendering can call it something it is not.
73
+ *
74
+ * The denominator is every input token, **writes included**. Leaving writes
75
+ * out made a constantly-rewritten cache report a high hit rate, which is the
76
+ * one workload that most needs to be told otherwise.
73
77
  */
74
78
  cacheReadShare: number;
75
79
  /**
@@ -105,6 +109,7 @@ export function measuredUsage(
105
109
  const outputTokens = slices.reduce((sum, row) => sum + row.breakdown.outputTokens, 0);
106
110
  const inputTokens = slices.reduce((sum, row) => sum + row.breakdown.inputTokens, 0);
107
111
  const cacheReadTokens = slices.reduce((sum, row) => sum + row.breakdown.cacheReadTokens, 0);
112
+ const cacheWriteTokens = slices.reduce((sum, row) => sum + row.breakdown.cacheWriteTokens, 0);
108
113
 
109
114
  // The model carrying the most spend. Ties break on the larger call count, so
110
115
  // the answer is stable rather than dependent on map ordering.
@@ -127,8 +132,27 @@ export function measuredUsage(
127
132
  ? { fromDays: spanDays, factor: SCALE_TO_DAYS / spanDays }
128
133
  : null;
129
134
 
130
- const readShare =
131
- inputTokens + cacheReadTokens > 0 ? cacheReadTokens / (inputTokens + cacheReadTokens) : 0;
135
+ /**
136
+ * Every input token in the denominator, writes included.
137
+ *
138
+ * This was `reads / (input + reads)`, which leaves cache *writes* out of the
139
+ * total it is a share of. A workload that rewrites its prefix on every call
140
+ * and reads it back rarely then reports a **high** hit rate: with 100 read
141
+ * tokens, no plain input and 10,000 written, the old expression answers 100%
142
+ * where the truth is 1%.
143
+ *
144
+ * That is the worst direction for this number to be wrong in. It is handed
145
+ * to `optimize` as `cacheHitRate`, which decides whether caching is paying
146
+ * off — so the shape that is burning money on writes was the shape most
147
+ * likely to be told its cache was working perfectly.
148
+ *
149
+ * Writes are input tokens: they are billed at the input rate times the write
150
+ * multiplier, they arrive in the same `usage` block, and any accounting of
151
+ * "what share of the input came from cache" that omits them is answering a
152
+ * narrower question than the one it is named for.
153
+ */
154
+ const allInputTokens = inputTokens + cacheReadTokens + cacheWriteTokens;
155
+ const readShare = allInputTokens > 0 ? cacheReadTokens / allInputTokens : 0;
132
156
 
133
157
  return {
134
158
  profile: {