burnoff 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +93 -2
- package/bin/burnoff.mjs +406 -0
- package/hooks/hook-io.mjs +590 -0
- package/hooks/hooks.json +12 -0
- package/hooks/post-tool-use.mjs +118 -0
- package/hooks/pre-tool-use.mjs +149 -0
- package/package.json +42 -4
- package/src/ci/ci-gate.mjs +270 -0
- package/src/ci/pr-cost.mjs +582 -0
- package/src/ci/team-digest.mjs +123 -0
- package/src/cli/audit.mjs +196 -0
- package/src/cli/doctor.mjs +257 -0
- package/src/cli/init.mjs +306 -0
- package/src/config/catalog.json +874 -0
- package/src/config/loader.mjs +626 -0
- package/src/config/paths.mjs +196 -0
- package/src/config/policy.mjs +208 -0
- package/src/guards/loop-breaker.mjs +501 -0
- package/src/guards/post-tool-engine.mjs +573 -0
- package/src/guards/pre-tool-engine.mjs +563 -0
- package/src/guards/read-clamp.mjs +730 -0
- package/src/guards/shell-guard.mjs +1140 -0
- package/src/ipc/daemon.mjs +273 -0
- package/src/ipc/fast-client.mjs +198 -0
- package/src/ipc/protocol.mjs +142 -0
- package/src/storage/atomic-io.mjs +151 -0
- package/src/storage/file-lock.mjs +206 -0
- package/src/storage/fts5-archive.mjs +718 -0
- package/src/storage/jsonl-parser.mjs +760 -0
- package/src/storage/ledger.mjs +1150 -0
- package/src/storage/sqlite-client.mjs +566 -0
|
@@ -0,0 +1,626 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { getHomeDir } from './paths.mjs';
|
|
4
|
+
|
|
5
|
+
const CATALOG_URL = new URL('./catalog.json', import.meta.url);
|
|
6
|
+
let cachedBaseCatalog = null;
|
|
7
|
+
|
|
8
|
+
export const UNKNOWN_MODEL_ID = 'unknown';
|
|
9
|
+
|
|
10
|
+
export function loadModelCatalog(options = {}) {
|
|
11
|
+
if (!cachedBaseCatalog) {
|
|
12
|
+
const raw = fs.readFileSync(CATALOG_URL, 'utf8');
|
|
13
|
+
cachedBaseCatalog = JSON.parse(raw);
|
|
14
|
+
}
|
|
15
|
+
const cloned = JSON.parse(JSON.stringify(cachedBaseCatalog));
|
|
16
|
+
const customCeilings = options.customCeilings !== undefined
|
|
17
|
+
? options.customCeilings
|
|
18
|
+
: loadCustomCeilings(options);
|
|
19
|
+
return applyCeilingOverrides(cloned, customCeilings);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function hasExtended1MHint(rawModelId = '', options = {}) {
|
|
23
|
+
if (options?.extendedContext1M === true) return true;
|
|
24
|
+
const raw = String(rawModelId || '').toLowerCase().trim();
|
|
25
|
+
return /\[1m\]|(?:^|[-_:\s])1m(?:$|[-_:\s\]])/.test(raw);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function formatUnknownModelAdvisory(rawModelId = '') {
|
|
29
|
+
const displayId = String(rawModelId || '').trim() || UNKNOWN_MODEL_ID;
|
|
30
|
+
return `Prices for model "${displayId}" are unknown (not in price catalog); dollar figures and price-based holds are disabled.`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const SHORT_MODEL_ALIASES = Object.freeze({
|
|
34
|
+
opus: 'claude-opus-5-5',
|
|
35
|
+
best: 'claude-opus-5-5',
|
|
36
|
+
opusplan: 'claude-opus-5-5',
|
|
37
|
+
sonnet: 'claude-sonnet-5-5',
|
|
38
|
+
haiku: 'claude-haiku-5-5',
|
|
39
|
+
fable: 'claude-fable-5-2',
|
|
40
|
+
mythos: 'claude-mythos-5-2',
|
|
41
|
+
'claude-opus-4': 'claude-opus-4-0',
|
|
42
|
+
'claude-sonnet-4': 'claude-sonnet-4-0',
|
|
43
|
+
'claude-3-5-sonnet-v2': 'claude-3-5-sonnet'
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
function canonicalizeModelToken(rawModelId = '') {
|
|
47
|
+
let s = String(rawModelId || '')
|
|
48
|
+
.toLowerCase()
|
|
49
|
+
.trim()
|
|
50
|
+
.replace(/\[[12]m\]/gi, '')
|
|
51
|
+
.replace(/[-_:\s]+1m$/g, '')
|
|
52
|
+
.replace(/\s*\((?:xhigh|extra[\s-]*high|high|medium|med|low|max|minimal|auto|fast|thinking|standard|extended[\s-]*thinking)(?:\s*[,/|]\s*(?:xhigh|extra[\s-]*high|high|medium|med|low|max|minimal|auto|fast|thinking|standard|extended[\s-]*thinking))*\)\s*$/gi, '')
|
|
53
|
+
.trim()
|
|
54
|
+
.replace(/\s+/g, '-');
|
|
55
|
+
|
|
56
|
+
if (!s) return '';
|
|
57
|
+
|
|
58
|
+
const slashIdx = s.lastIndexOf('/');
|
|
59
|
+
if (slashIdx !== -1) {
|
|
60
|
+
const providerPart = s.slice(0, slashIdx);
|
|
61
|
+
const tail = s.slice(slashIdx + 1);
|
|
62
|
+
if (providerPart === 'anthropic' || providerPart.endsWith('/anthropic')) {
|
|
63
|
+
s = tail;
|
|
64
|
+
} else {
|
|
65
|
+
return s.replace(/\./g, '-');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const bedrockMatch = s.match(/^(?:[a-z-]+\.)?anthropic\.(claude-.*)$/);
|
|
70
|
+
if (bedrockMatch) {
|
|
71
|
+
s = bedrockMatch[1];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
s = s
|
|
75
|
+
.replace(/\./g, '-')
|
|
76
|
+
.replace(/-v\d+(?::\d+)?$/i, '')
|
|
77
|
+
.replace(/[@-]\d{8}$/i, '')
|
|
78
|
+
.replace(/-(?:thinking|fast|latest|xhigh|extra-high|high|medium|med|low)$/i, '');
|
|
79
|
+
|
|
80
|
+
const altOrder = s.match(/^claude-([4-9]\d*-\d+)-(opus|sonnet|haiku|fable|mythos)$/);
|
|
81
|
+
if (altOrder) {
|
|
82
|
+
s = `claude-${altOrder[2]}-${altOrder[1]}`;
|
|
83
|
+
}
|
|
84
|
+
const threeXOrder = s.match(/^claude-(haiku|sonnet)-(3-[57])$/);
|
|
85
|
+
if (threeXOrder) {
|
|
86
|
+
s = `claude-${threeXOrder[2]}-${threeXOrder[1]}`;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (Object.prototype.hasOwnProperty.call(SHORT_MODEL_ALIASES, s)) {
|
|
90
|
+
return SHORT_MODEL_ALIASES[s];
|
|
91
|
+
}
|
|
92
|
+
if (/^(?:opus|sonnet|haiku|fable|mythos)-/.test(s) && !s.startsWith('claude-')) {
|
|
93
|
+
return `claude-${s}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return s;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function loadCustomCeilings(options = {}) {
|
|
100
|
+
if (options.customCeilings && typeof options.customCeilings === 'object') {
|
|
101
|
+
return options.customCeilings;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const candidatePaths = [];
|
|
105
|
+
if (typeof options.customCeilingsPath === 'string' && options.customCeilingsPath.trim()) {
|
|
106
|
+
candidatePaths.push(options.customCeilingsPath.trim());
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const cwd = options.cwd || process.cwd();
|
|
110
|
+
if (cwd && cwd !== '.') {
|
|
111
|
+
candidatePaths.push(path.join(cwd, '.claude', 'burnoff', 'customCeilings.json'));
|
|
112
|
+
candidatePaths.push(path.join(cwd, 'customCeilings.json'));
|
|
113
|
+
candidatePaths.push(path.join(cwd, '.claude', 'customCeilings.json'));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const homeDir = options.homeDir || getHomeDir();
|
|
117
|
+
if (homeDir) {
|
|
118
|
+
candidatePaths.push(path.join(homeDir, '.burnoff', 'customCeilings.json'));
|
|
119
|
+
candidatePaths.push(path.join(homeDir, '.claude', 'customCeilings.json'));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
for (const candidate of candidatePaths) {
|
|
123
|
+
try {
|
|
124
|
+
if (fs.existsSync(candidate)) {
|
|
125
|
+
const parsed = JSON.parse(fs.readFileSync(candidate, 'utf8'));
|
|
126
|
+
if (parsed && typeof parsed === 'object') return parsed;
|
|
127
|
+
}
|
|
128
|
+
} catch {
|
|
129
|
+
// ignore: invalid customCeilings override falls back cleanly
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function isKnownCatalogModel(rawModelId = '', options = {}) {
|
|
136
|
+
const raw = String(rawModelId || '').trim();
|
|
137
|
+
if (!raw || raw.toLowerCase() === UNKNOWN_MODEL_ID) return false;
|
|
138
|
+
const cleaned = canonicalizeModelToken(raw);
|
|
139
|
+
if (!cleaned) return false;
|
|
140
|
+
const catalog = options.catalog || loadModelCatalog(options);
|
|
141
|
+
return Boolean(catalog?.models && Object.prototype.hasOwnProperty.call(catalog.models, cleaned));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function normalizeModelId(rawModelId = '', options = {}) {
|
|
145
|
+
const catalog = options.catalog || loadModelCatalog(options);
|
|
146
|
+
const raw = String(rawModelId || '').trim();
|
|
147
|
+
if (!raw) return catalog.defaultModel || 'claude-sonnet-5-5';
|
|
148
|
+
const cleaned = canonicalizeModelToken(raw);
|
|
149
|
+
if (!cleaned) return catalog.defaultModel || 'claude-sonnet-5-5';
|
|
150
|
+
if (catalog?.models && Object.prototype.hasOwnProperty.call(catalog.models, cleaned)) {
|
|
151
|
+
return cleaned;
|
|
152
|
+
}
|
|
153
|
+
return UNKNOWN_MODEL_ID;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function extractCeilingNumber(val) {
|
|
157
|
+
if (typeof val === 'number' && val > 0) return val;
|
|
158
|
+
if (val && typeof val === 'object') {
|
|
159
|
+
if (typeof val.contextCeiling === 'number' && val.contextCeiling > 0) return val.contextCeiling;
|
|
160
|
+
if (typeof val.ceiling === 'number' && val.ceiling > 0) return val.ceiling;
|
|
161
|
+
}
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function resolveCustomCeilingForModel(modelId = '', options = {}) {
|
|
166
|
+
const customCeilings = loadCustomCeilings(options);
|
|
167
|
+
if (!customCeilings || typeof customCeilings !== 'object') return null;
|
|
168
|
+
|
|
169
|
+
const sourceMap = customCeilings.models && typeof customCeilings.models === 'object'
|
|
170
|
+
? customCeilings.models
|
|
171
|
+
: customCeilings.ceilings && typeof customCeilings.ceilings === 'object'
|
|
172
|
+
? customCeilings.ceilings
|
|
173
|
+
: customCeilings;
|
|
174
|
+
|
|
175
|
+
const normId = normalizeModelId(modelId, options);
|
|
176
|
+
const cleanedRaw = canonicalizeModelToken(modelId);
|
|
177
|
+
if (modelId && Object.prototype.hasOwnProperty.call(sourceMap, modelId)) {
|
|
178
|
+
const direct = extractCeilingNumber(sourceMap[modelId]);
|
|
179
|
+
if (direct !== null) return direct;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
for (const [rawKey, overrideVal] of Object.entries(sourceMap)) {
|
|
183
|
+
if (rawKey === '*' || rawKey === 'schemaVersion') continue;
|
|
184
|
+
const keyMatched =
|
|
185
|
+
(cleanedRaw && (rawKey === cleanedRaw || canonicalizeModelToken(rawKey) === cleanedRaw)) ||
|
|
186
|
+
(normId !== UNKNOWN_MODEL_ID && (rawKey === normId || normalizeModelId(rawKey, options) === normId));
|
|
187
|
+
if (keyMatched) {
|
|
188
|
+
const matched = extractCeilingNumber(overrideVal);
|
|
189
|
+
if (matched !== null) return matched;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (Object.prototype.hasOwnProperty.call(sourceMap, '*')) {
|
|
194
|
+
return extractCeilingNumber(sourceMap['*']);
|
|
195
|
+
}
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function applyCeilingOverrides(catalog, customCeilings) {
|
|
200
|
+
if (!customCeilings || typeof customCeilings !== 'object') return catalog;
|
|
201
|
+
|
|
202
|
+
const sourceMap = customCeilings.models && typeof customCeilings.models === 'object'
|
|
203
|
+
? customCeilings.models
|
|
204
|
+
: customCeilings.ceilings && typeof customCeilings.ceilings === 'object'
|
|
205
|
+
? customCeilings.ceilings
|
|
206
|
+
: customCeilings;
|
|
207
|
+
|
|
208
|
+
if (typeof sourceMap['*'] === 'number' && sourceMap['*'] > 0) {
|
|
209
|
+
for (const modelSpec of Object.values(catalog.models)) {
|
|
210
|
+
modelSpec.contextCeiling = sourceMap['*'];
|
|
211
|
+
}
|
|
212
|
+
} else if (sourceMap['*'] && typeof sourceMap['*'] === 'object') {
|
|
213
|
+
for (const modelSpec of Object.values(catalog.models)) {
|
|
214
|
+
if (typeof sourceMap['*'].contextCeiling === 'number') modelSpec.contextCeiling = sourceMap['*'].contextCeiling;
|
|
215
|
+
if (typeof sourceMap['*'].operationalSoftCeiling === 'number') {
|
|
216
|
+
modelSpec.operationalSoftCeiling = sourceMap['*'].operationalSoftCeiling;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
for (const [rawKey, overrideVal] of Object.entries(sourceMap)) {
|
|
222
|
+
if (rawKey === '*' || rawKey === 'schemaVersion') continue;
|
|
223
|
+
const cleanedKey = canonicalizeModelToken(rawKey);
|
|
224
|
+
const normId = catalog.models[rawKey]
|
|
225
|
+
? rawKey
|
|
226
|
+
: catalog.models[cleanedKey]
|
|
227
|
+
? cleanedKey
|
|
228
|
+
: normalizeModelId(rawKey, { catalog });
|
|
229
|
+
let target = normId !== UNKNOWN_MODEL_ID ? catalog.models[normId] : null;
|
|
230
|
+
if (!target && overrideVal && typeof overrideVal === 'object' && overrideVal.ratesPer1M) {
|
|
231
|
+
const customId = cleanedKey || rawKey;
|
|
232
|
+
catalog.models[customId] = {
|
|
233
|
+
id: customId,
|
|
234
|
+
label: overrideVal.label || customId,
|
|
235
|
+
shortLabel: overrideVal.shortLabel || overrideVal.label || customId,
|
|
236
|
+
family: overrideVal.family || 'custom',
|
|
237
|
+
generation: overrideVal.generation || null,
|
|
238
|
+
contextCeiling: Number(overrideVal.contextCeiling || overrideVal.ceiling || 200000),
|
|
239
|
+
operationalSoftCeiling: Number(overrideVal.operationalSoftCeiling || 160000),
|
|
240
|
+
ratesPer1M: { ...overrideVal.ratesPer1M },
|
|
241
|
+
multipliers: overrideVal.multipliers || { write5m: 1.25, write1h: 2.0, read: 0.1 },
|
|
242
|
+
source: overrideVal.source || 'customCeilings.json',
|
|
243
|
+
dateRead: overrideVal.dateRead || null,
|
|
244
|
+
pricingCliff: overrideVal.pricingCliff || null
|
|
245
|
+
};
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (!target) continue;
|
|
249
|
+
|
|
250
|
+
if (typeof overrideVal === 'number' && overrideVal > 0) {
|
|
251
|
+
target.contextCeiling = overrideVal;
|
|
252
|
+
} else if (overrideVal && typeof overrideVal === 'object') {
|
|
253
|
+
if (typeof overrideVal.contextCeiling === 'number' && overrideVal.contextCeiling > 0) {
|
|
254
|
+
target.contextCeiling = overrideVal.contextCeiling;
|
|
255
|
+
}
|
|
256
|
+
if (typeof overrideVal.ceiling === 'number' && overrideVal.ceiling > 0) {
|
|
257
|
+
target.contextCeiling = overrideVal.ceiling;
|
|
258
|
+
}
|
|
259
|
+
if (typeof overrideVal.operationalSoftCeiling === 'number' && overrideVal.operationalSoftCeiling > 0) {
|
|
260
|
+
target.operationalSoftCeiling = overrideVal.operationalSoftCeiling;
|
|
261
|
+
}
|
|
262
|
+
if (overrideVal.ratesPer1M && typeof overrideVal.ratesPer1M === 'object') {
|
|
263
|
+
target.ratesPer1M = { ...target.ratesPer1M, ...overrideVal.ratesPer1M };
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return catalog;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function getModelSpec(modelId = '', options = {}) {
|
|
272
|
+
const catalog = options.catalog || loadModelCatalog(options);
|
|
273
|
+
const rawTrimmed = String(modelId || '').trim();
|
|
274
|
+
if (!rawTrimmed) {
|
|
275
|
+
const fallbackSpec = catalog.models[catalog.defaultModel] || catalog.models['claude-sonnet-5-5'];
|
|
276
|
+
if (
|
|
277
|
+
hasExtended1MHint(modelId, options) &&
|
|
278
|
+
resolveCustomCeilingForModel(fallbackSpec.id, options) === null &&
|
|
279
|
+
fallbackSpec.contextCeiling < 1000000
|
|
280
|
+
) {
|
|
281
|
+
return { ...fallbackSpec, contextCeiling: 1000000, operationalSoftCeiling: 800000, unknownModel: false };
|
|
282
|
+
}
|
|
283
|
+
return { ...fallbackSpec, unknownModel: false };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const cleaned = canonicalizeModelToken(rawTrimmed);
|
|
287
|
+
const normId = normalizeModelId(rawTrimmed, { ...options, catalog });
|
|
288
|
+
const directCustomSpec = catalog.models[cleaned] || (normId !== UNKNOWN_MODEL_ID ? catalog.models[normId] : null);
|
|
289
|
+
|
|
290
|
+
if (!directCustomSpec || normId === UNKNOWN_MODEL_ID) {
|
|
291
|
+
const customCeiling = resolveCustomCeilingForModel(rawTrimmed, options);
|
|
292
|
+
const defaultCeiling = hasExtended1MHint(rawTrimmed, options) ? 1000000 : 200000;
|
|
293
|
+
const contextCeiling = Number(customCeiling || defaultCeiling);
|
|
294
|
+
return {
|
|
295
|
+
id: UNKNOWN_MODEL_ID,
|
|
296
|
+
rawModelId: rawTrimmed,
|
|
297
|
+
unknownModel: true,
|
|
298
|
+
label: `Unknown Model (${rawTrimmed})`,
|
|
299
|
+
shortLabel: 'Unknown Model',
|
|
300
|
+
family: 'unknown',
|
|
301
|
+
generation: null,
|
|
302
|
+
contextCeiling,
|
|
303
|
+
operationalSoftCeiling: Math.round(contextCeiling * 0.8),
|
|
304
|
+
ratesPer1M: null,
|
|
305
|
+
multipliers: null,
|
|
306
|
+
source: null,
|
|
307
|
+
dateRead: null,
|
|
308
|
+
pricingCliff: null,
|
|
309
|
+
advisory: formatUnknownModelAdvisory(rawTrimmed)
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (
|
|
314
|
+
(normId === 'claude-opus-4-6' ||
|
|
315
|
+
normId === 'claude-sonnet-4-6' ||
|
|
316
|
+
normId === 'claude-opus-4-5' ||
|
|
317
|
+
normId === 'claude-sonnet-4-5') &&
|
|
318
|
+
hasExtended1MHint(modelId, options) &&
|
|
319
|
+
resolveCustomCeilingForModel(modelId, options) === null
|
|
320
|
+
) {
|
|
321
|
+
return { ...directCustomSpec, contextCeiling: 1000000, operationalSoftCeiling: 800000, unknownModel: false };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return { ...directCustomSpec, unknownModel: false };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export const resolveModelSpec = getModelSpec;
|
|
328
|
+
|
|
329
|
+
export function getModelPricingCliff(modelId = '', options = {}) {
|
|
330
|
+
const spec = getModelSpec(modelId, options);
|
|
331
|
+
return spec?.pricingCliff || null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export function estimateTokensFromChars(charCount = 0) {
|
|
335
|
+
const n = Number(charCount || 0);
|
|
336
|
+
if (!Number.isFinite(n) || n <= 0) return 0;
|
|
337
|
+
return Math.ceil(n / 4);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
export function extractNormalizedTokenBreakdown(usage = {}) {
|
|
341
|
+
if (!usage || typeof usage !== 'object') {
|
|
342
|
+
return {
|
|
343
|
+
uncachedInputTokens: 0,
|
|
344
|
+
cacheReadTokens: 0,
|
|
345
|
+
write5mTokens: 0,
|
|
346
|
+
write1hTokens: 0,
|
|
347
|
+
remainingGenericWriteTokens: 0,
|
|
348
|
+
effectiveWrite5mTokens: 0,
|
|
349
|
+
effectiveWrite1hTokens: 0,
|
|
350
|
+
totalCacheWriteTokens: 0,
|
|
351
|
+
outputTokens: 0,
|
|
352
|
+
thinkingTokens: 0
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const uncachedInputTokens = Math.max(
|
|
357
|
+
0,
|
|
358
|
+
Number(usage.uncachedInputTokens ?? usage.freshInputTokens ?? usage.inputTokens ?? usage.input_tokens ?? 0)
|
|
359
|
+
);
|
|
360
|
+
const cacheReadTokens = Math.max(
|
|
361
|
+
0,
|
|
362
|
+
Number(usage.cacheReadTokens ?? usage.cacheReadInputTokens ?? usage.cache_read_input_tokens ?? 0)
|
|
363
|
+
);
|
|
364
|
+
const nestedCreation = usage.cache_creation && typeof usage.cache_creation === 'object' ? usage.cache_creation : null;
|
|
365
|
+
|
|
366
|
+
const write5mTokens = Math.max(
|
|
367
|
+
0,
|
|
368
|
+
Number(usage.cacheWrite5mTokens ?? usage.cache_write_5m_tokens ?? nestedCreation?.ephemeral_5m_input_tokens ?? 0)
|
|
369
|
+
);
|
|
370
|
+
const write1hTokens = Math.max(
|
|
371
|
+
0,
|
|
372
|
+
Number(usage.cacheWrite1hTokens ?? usage.cache_write_1h_tokens ?? nestedCreation?.ephemeral_1h_input_tokens ?? 0)
|
|
373
|
+
);
|
|
374
|
+
const genericWriteTokens = Math.max(
|
|
375
|
+
0,
|
|
376
|
+
Number(usage.cacheWriteTokens ?? usage.cacheCreationInputTokens ?? usage.cache_creation_input_tokens ?? usage.lastWriteTokens ?? 0)
|
|
377
|
+
);
|
|
378
|
+
|
|
379
|
+
const remainingGenericWriteTokens = Math.max(0, genericWriteTokens - (write5mTokens + write1hTokens));
|
|
380
|
+
const defaultTier = usage.cacheTtlTier === '1h' || usage.ttlTier === '1h' ? '1h' : '5m';
|
|
381
|
+
const effectiveWrite5mTokens = write5mTokens + (defaultTier === '5m' ? remainingGenericWriteTokens : 0);
|
|
382
|
+
const effectiveWrite1hTokens = write1hTokens + (defaultTier === '1h' ? remainingGenericWriteTokens : 0);
|
|
383
|
+
const totalCacheWriteTokens = effectiveWrite5mTokens + effectiveWrite1hTokens;
|
|
384
|
+
|
|
385
|
+
const outputTokens = Math.max(0, Number(usage.outputTokens ?? usage.output_tokens ?? usage.lastOutputTokens ?? 0));
|
|
386
|
+
const thinkingTokens = Math.max(
|
|
387
|
+
0,
|
|
388
|
+
Number(usage.thinkingTokens ?? usage.thinking_tokens ?? usage.reasoning_tokens ?? nestedCreation?.thinking_tokens ?? usage.lastThinkingTokens ?? 0)
|
|
389
|
+
);
|
|
390
|
+
|
|
391
|
+
return {
|
|
392
|
+
uncachedInputTokens,
|
|
393
|
+
cacheReadTokens,
|
|
394
|
+
write5mTokens,
|
|
395
|
+
write1hTokens,
|
|
396
|
+
remainingGenericWriteTokens,
|
|
397
|
+
effectiveWrite5mTokens,
|
|
398
|
+
effectiveWrite1hTokens,
|
|
399
|
+
totalCacheWriteTokens,
|
|
400
|
+
outputTokens,
|
|
401
|
+
thinkingTokens
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export function computeTotalPromptTokens(usage = {}) {
|
|
406
|
+
if (!usage || typeof usage !== 'object') return 0;
|
|
407
|
+
|
|
408
|
+
if (usage.turnPromptTokens !== undefined && usage.turnPromptTokens !== null) {
|
|
409
|
+
const breakdown = extractNormalizedTokenBreakdown(usage);
|
|
410
|
+
const splitSum = breakdown.uncachedInputTokens + breakdown.cacheReadTokens + breakdown.totalCacheWriteTokens;
|
|
411
|
+
return Math.max(splitSum, Math.max(0, Number(usage.turnPromptTokens)));
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const breakdown = extractNormalizedTokenBreakdown(usage);
|
|
415
|
+
const hasExplicitCacheRead =
|
|
416
|
+
usage.cacheReadTokens !== undefined ||
|
|
417
|
+
usage.cacheReadInputTokens !== undefined ||
|
|
418
|
+
usage.cache_read_input_tokens !== undefined;
|
|
419
|
+
const unattributedCached = !hasExplicitCacheRead
|
|
420
|
+
? Math.max(0, Number(usage.cachedTokens ?? usage.cached_tokens ?? 0) - breakdown.totalCacheWriteTokens)
|
|
421
|
+
: 0;
|
|
422
|
+
|
|
423
|
+
const computedPromptTokens =
|
|
424
|
+
breakdown.uncachedInputTokens +
|
|
425
|
+
breakdown.cacheReadTokens +
|
|
426
|
+
breakdown.totalCacheWriteTokens +
|
|
427
|
+
unattributedCached;
|
|
428
|
+
|
|
429
|
+
const hasExplicitUncached =
|
|
430
|
+
usage.uncachedInputTokens !== undefined ||
|
|
431
|
+
usage.freshInputTokens !== undefined ||
|
|
432
|
+
usage.inputTokens !== undefined ||
|
|
433
|
+
usage.input_tokens !== undefined;
|
|
434
|
+
|
|
435
|
+
if (hasExplicitUncached && (hasExplicitCacheRead || breakdown.totalCacheWriteTokens > 0)) {
|
|
436
|
+
return computedPromptTokens;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const explicitSingleTurnTotal = Math.max(
|
|
440
|
+
0,
|
|
441
|
+
Number(usage.totalPromptTokens ?? usage.totalInputTokens ?? usage.total_input_tokens ?? 0)
|
|
442
|
+
);
|
|
443
|
+
|
|
444
|
+
return Math.max(computedPromptTokens, explicitSingleTurnTotal);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export function resolveEffectiveRates(modelId = 'claude-sonnet-5-5', totalPromptTokens = 0, options = {}) {
|
|
448
|
+
const spec = getModelSpec(modelId, options);
|
|
449
|
+
const promptTokens = Math.max(0, Number(totalPromptTokens || 0));
|
|
450
|
+
|
|
451
|
+
if (spec.unknownModel) {
|
|
452
|
+
return {
|
|
453
|
+
modelId: UNKNOWN_MODEL_ID,
|
|
454
|
+
rawModelId: spec.rawModelId || String(modelId || '').trim(),
|
|
455
|
+
unknownModel: true,
|
|
456
|
+
label: spec.label,
|
|
457
|
+
shortLabel: spec.shortLabel || 'Unknown Model',
|
|
458
|
+
family: 'unknown',
|
|
459
|
+
contextCeiling: spec.contextCeiling,
|
|
460
|
+
operationalSoftCeiling: spec.operationalSoftCeiling,
|
|
461
|
+
inputPer1M: null,
|
|
462
|
+
outputPer1M: null,
|
|
463
|
+
write5mPer1M: null,
|
|
464
|
+
write1hPer1M: null,
|
|
465
|
+
readPer1M: null,
|
|
466
|
+
multipliers: null,
|
|
467
|
+
source: null,
|
|
468
|
+
dateRead: null,
|
|
469
|
+
cliffTriggered: false,
|
|
470
|
+
preCliffWarningTriggered: false,
|
|
471
|
+
cliffThresholdTokens: null,
|
|
472
|
+
cliffMultiplier: 1.0,
|
|
473
|
+
advisory: spec.advisory || formatUnknownModelAdvisory(modelId)
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const cliff = spec.pricingCliff || null;
|
|
478
|
+
const cliffTriggered = Boolean(cliff && promptTokens > cliff.thresholdTokens);
|
|
479
|
+
const preCliffWarningTriggered = Boolean(
|
|
480
|
+
cliff && promptTokens >= (cliff.preCliffWarningTokens || cliff.thresholdTokens * 0.9)
|
|
481
|
+
);
|
|
482
|
+
|
|
483
|
+
const activeRates = cliffTriggered && cliff.ratesPer1MAboveCliff
|
|
484
|
+
? cliff.ratesPer1MAboveCliff
|
|
485
|
+
: spec.ratesPer1M;
|
|
486
|
+
|
|
487
|
+
return {
|
|
488
|
+
modelId: spec.id,
|
|
489
|
+
unknownModel: false,
|
|
490
|
+
label: spec.label,
|
|
491
|
+
shortLabel: spec.shortLabel || spec.label,
|
|
492
|
+
family: spec.family,
|
|
493
|
+
contextCeiling: spec.contextCeiling,
|
|
494
|
+
operationalSoftCeiling: spec.operationalSoftCeiling,
|
|
495
|
+
inputPer1M: activeRates.input,
|
|
496
|
+
outputPer1M: activeRates.output,
|
|
497
|
+
write5mPer1M: activeRates.write5m,
|
|
498
|
+
write1hPer1M: activeRates.write1h,
|
|
499
|
+
readPer1M: activeRates.read,
|
|
500
|
+
multipliers: { ...spec.multipliers },
|
|
501
|
+
source: spec.source || null,
|
|
502
|
+
dateRead: spec.dateRead || null,
|
|
503
|
+
cliffTriggered,
|
|
504
|
+
preCliffWarningTriggered,
|
|
505
|
+
cliffThresholdTokens: cliff ? cliff.thresholdTokens : null,
|
|
506
|
+
cliffMultiplier: cliffTriggered ? cliff.multiplier : 1.0,
|
|
507
|
+
cliffCachedReadMultiplier: cliffTriggered ? (cliff.cachedReadMultiplier ?? cliff.multiplier) : 1.0,
|
|
508
|
+
cliffOutputMultiplier: cliffTriggered ? (cliff.outputMultiplier ?? cliff.multiplier) : 1.0
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
export function calculateTurnCostUSD(usage = {}, options = {}) {
|
|
513
|
+
const breakdown = extractNormalizedTokenBreakdown(usage);
|
|
514
|
+
const uncachedInput = breakdown.uncachedInputTokens;
|
|
515
|
+
const outputTokens = breakdown.outputTokens;
|
|
516
|
+
const thinkingTokens = breakdown.thinkingTokens;
|
|
517
|
+
const cacheReadTokens = breakdown.cacheReadTokens;
|
|
518
|
+
const write5mTokens = breakdown.effectiveWrite5mTokens;
|
|
519
|
+
const write1hTokens = breakdown.effectiveWrite1hTokens;
|
|
520
|
+
const totalCacheWriteTokens = breakdown.totalCacheWriteTokens;
|
|
521
|
+
const totalPromptTokens = computeTotalPromptTokens(usage);
|
|
522
|
+
|
|
523
|
+
const rawModel = usage.model || usage.modelId || 'claude-sonnet-5-5';
|
|
524
|
+
const rates = resolveEffectiveRates(rawModel, totalPromptTokens, options);
|
|
525
|
+
|
|
526
|
+
if (rates.unknownModel) {
|
|
527
|
+
return {
|
|
528
|
+
modelId: UNKNOWN_MODEL_ID,
|
|
529
|
+
rawModelId: rates.rawModelId || String(rawModel),
|
|
530
|
+
unknownModel: true,
|
|
531
|
+
advisory: rates.advisory,
|
|
532
|
+
rates,
|
|
533
|
+
tokens: {
|
|
534
|
+
uncachedInput,
|
|
535
|
+
cacheWrite5m: write5mTokens,
|
|
536
|
+
cacheWrite1h: write1hTokens,
|
|
537
|
+
totalCacheWrite: totalCacheWriteTokens,
|
|
538
|
+
cacheRead: cacheReadTokens,
|
|
539
|
+
totalPrompt: totalPromptTokens,
|
|
540
|
+
output: outputTokens,
|
|
541
|
+
thinking: thinkingTokens,
|
|
542
|
+
totalOutput: outputTokens + thinkingTokens
|
|
543
|
+
},
|
|
544
|
+
costsUSD: {
|
|
545
|
+
uncachedInput: null,
|
|
546
|
+
write5m: null,
|
|
547
|
+
write1h: null,
|
|
548
|
+
cacheRead: null,
|
|
549
|
+
output: null,
|
|
550
|
+
actualCacheSpendUSD: null,
|
|
551
|
+
uncachedCacheEquivalentUSD: null,
|
|
552
|
+
totalActualSpendUSD: null,
|
|
553
|
+
totalUncachedEquivalentUSD: null,
|
|
554
|
+
netCacheSavingsUSD: null
|
|
555
|
+
},
|
|
556
|
+
cliffTriggered: false,
|
|
557
|
+
preCliffWarningTriggered: false
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const inputCostUSD = (uncachedInput / 1_000_000) * rates.inputPer1M;
|
|
562
|
+
const write5mCostUSD = (write5mTokens / 1_000_000) * rates.write5mPer1M;
|
|
563
|
+
const write1hCostUSD = (write1hTokens / 1_000_000) * rates.write1hPer1M;
|
|
564
|
+
const readCostUSD = (cacheReadTokens / 1_000_000) * rates.readPer1M;
|
|
565
|
+
const outputCostUSD = ((outputTokens + thinkingTokens) / 1_000_000) * rates.outputPer1M;
|
|
566
|
+
|
|
567
|
+
const actualCacheSpendUSD = write5mCostUSD + write1hCostUSD + readCostUSD;
|
|
568
|
+
const uncachedCacheEquivalentUSD = ((totalCacheWriteTokens + cacheReadTokens) / 1_000_000) * rates.inputPer1M;
|
|
569
|
+
|
|
570
|
+
const totalActualSpendUSD = inputCostUSD + actualCacheSpendUSD + outputCostUSD;
|
|
571
|
+
const totalUncachedEquivalentUSD = inputCostUSD + uncachedCacheEquivalentUSD + outputCostUSD;
|
|
572
|
+
const netCacheSavingsUSD = totalUncachedEquivalentUSD - totalActualSpendUSD;
|
|
573
|
+
|
|
574
|
+
return {
|
|
575
|
+
modelId: rates.modelId,
|
|
576
|
+
unknownModel: false,
|
|
577
|
+
rates,
|
|
578
|
+
tokens: {
|
|
579
|
+
uncachedInput,
|
|
580
|
+
cacheWrite5m: write5mTokens,
|
|
581
|
+
cacheWrite1h: write1hTokens,
|
|
582
|
+
totalCacheWrite: totalCacheWriteTokens,
|
|
583
|
+
cacheRead: cacheReadTokens,
|
|
584
|
+
totalPrompt: totalPromptTokens,
|
|
585
|
+
output: outputTokens,
|
|
586
|
+
thinking: thinkingTokens,
|
|
587
|
+
totalOutput: outputTokens + thinkingTokens
|
|
588
|
+
},
|
|
589
|
+
costsUSD: {
|
|
590
|
+
uncachedInput: Number(inputCostUSD.toFixed(6)),
|
|
591
|
+
write5m: Number(write5mCostUSD.toFixed(6)),
|
|
592
|
+
write1h: Number(write1hCostUSD.toFixed(6)),
|
|
593
|
+
cacheRead: Number(readCostUSD.toFixed(6)),
|
|
594
|
+
output: Number(outputCostUSD.toFixed(6)),
|
|
595
|
+
actualCacheSpendUSD: Number(actualCacheSpendUSD.toFixed(6)),
|
|
596
|
+
uncachedCacheEquivalentUSD: Number(uncachedCacheEquivalentUSD.toFixed(6)),
|
|
597
|
+
totalActualSpendUSD: Number(totalActualSpendUSD.toFixed(6)),
|
|
598
|
+
totalUncachedEquivalentUSD: Number(totalUncachedEquivalentUSD.toFixed(6)),
|
|
599
|
+
netCacheSavingsUSD: Number(netCacheSavingsUSD.toFixed(6))
|
|
600
|
+
},
|
|
601
|
+
cliffTriggered: rates.cliffTriggered,
|
|
602
|
+
preCliffWarningTriggered: rates.preCliffWarningTriggered
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
export const computeTokenCostUsd = calculateTurnCostUSD;
|
|
607
|
+
|
|
608
|
+
export default {
|
|
609
|
+
UNKNOWN_MODEL_ID,
|
|
610
|
+
formatUnknownModelAdvisory,
|
|
611
|
+
hasExtended1MHint,
|
|
612
|
+
isKnownCatalogModel,
|
|
613
|
+
normalizeModelId,
|
|
614
|
+
loadCustomCeilings,
|
|
615
|
+
resolveCustomCeilingForModel,
|
|
616
|
+
loadModelCatalog,
|
|
617
|
+
getModelSpec,
|
|
618
|
+
resolveModelSpec,
|
|
619
|
+
getModelPricingCliff,
|
|
620
|
+
estimateTokensFromChars,
|
|
621
|
+
extractNormalizedTokenBreakdown,
|
|
622
|
+
computeTotalPromptTokens,
|
|
623
|
+
resolveEffectiveRates,
|
|
624
|
+
calculateTurnCostUSD,
|
|
625
|
+
computeTokenCostUsd
|
|
626
|
+
};
|