claude-code-cost 1.8.0 → 1.9.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/lib/costs.js +315 -139
- package/package.json +1 -1
- package/public/app.js +27 -5
package/lib/costs.js
CHANGED
|
@@ -2,8 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
const path = require('node:path');
|
|
4
4
|
const fs = require('node:fs');
|
|
5
|
-
const { createReadStream } = fs;
|
|
6
|
-
const { createInterface } = require('node:readline');
|
|
7
5
|
const os = require('node:os');
|
|
8
6
|
const { probeUsage, normalizeUsage } = require('./usage-probe');
|
|
9
7
|
|
|
@@ -110,9 +108,19 @@ async function fetchPricing() {
|
|
|
110
108
|
}
|
|
111
109
|
}
|
|
112
110
|
|
|
111
|
+
// A miss on the exact and prefixed names falls to a scan of every LiteLLM model, run once per turn
|
|
112
|
+
// of that model, so the answer is memoized for each pricing table.
|
|
113
|
+
const pricingMemo = new WeakMap();
|
|
114
|
+
|
|
113
115
|
function getModelPricing(pricing, modelName) {
|
|
114
116
|
if (!modelName) return null;
|
|
117
|
+
if (!pricingMemo.has(pricing)) pricingMemo.set(pricing, new Map());
|
|
118
|
+
const memo = pricingMemo.get(pricing);
|
|
119
|
+
if (!memo.has(modelName)) memo.set(modelName, lookupModelPricing(pricing, modelName));
|
|
120
|
+
return memo.get(modelName);
|
|
121
|
+
}
|
|
115
122
|
|
|
123
|
+
function lookupModelPricing(pricing, modelName) {
|
|
116
124
|
// Exact match
|
|
117
125
|
const direct = pricing.get(modelName);
|
|
118
126
|
if (direct) return direct;
|
|
@@ -146,20 +154,29 @@ function calculateTieredCost(totalTokens, basePrice, tieredPrice, threshold = TI
|
|
|
146
154
|
return 0;
|
|
147
155
|
}
|
|
148
156
|
|
|
157
|
+
function calculateCostParts(tokens, modelPricing) {
|
|
158
|
+
return {
|
|
159
|
+
input: calculateTieredCost(
|
|
160
|
+
tokens.input_tokens, modelPricing.input_cost_per_token,
|
|
161
|
+
modelPricing.input_cost_per_token_above_200k_tokens),
|
|
162
|
+
output: calculateTieredCost(
|
|
163
|
+
tokens.output_tokens, modelPricing.output_cost_per_token,
|
|
164
|
+
modelPricing.output_cost_per_token_above_200k_tokens),
|
|
165
|
+
cacheCreation: calculateTieredCost(
|
|
166
|
+
tokens.cache_creation_input_tokens, modelPricing.cache_creation_input_token_cost,
|
|
167
|
+
modelPricing.cache_creation_input_token_cost_above_200k_tokens),
|
|
168
|
+
cacheRead: calculateTieredCost(
|
|
169
|
+
tokens.cache_read_input_tokens, modelPricing.cache_read_input_token_cost,
|
|
170
|
+
modelPricing.cache_read_input_token_cost_above_200k_tokens),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function sumParts(p) {
|
|
175
|
+
return p.input + p.output + p.cacheCreation + p.cacheRead;
|
|
176
|
+
}
|
|
177
|
+
|
|
149
178
|
function calculateCost(tokens, modelPricing) {
|
|
150
|
-
|
|
151
|
-
tokens.input_tokens, modelPricing.input_cost_per_token,
|
|
152
|
-
modelPricing.input_cost_per_token_above_200k_tokens);
|
|
153
|
-
const outputCost = calculateTieredCost(
|
|
154
|
-
tokens.output_tokens, modelPricing.output_cost_per_token,
|
|
155
|
-
modelPricing.output_cost_per_token_above_200k_tokens);
|
|
156
|
-
const cacheCreationCost = calculateTieredCost(
|
|
157
|
-
tokens.cache_creation_input_tokens, modelPricing.cache_creation_input_token_cost,
|
|
158
|
-
modelPricing.cache_creation_input_token_cost_above_200k_tokens);
|
|
159
|
-
const cacheReadCost = calculateTieredCost(
|
|
160
|
-
tokens.cache_read_input_tokens, modelPricing.cache_read_input_token_cost,
|
|
161
|
-
modelPricing.cache_read_input_token_cost_above_200k_tokens);
|
|
162
|
-
return inputCost + outputCost + cacheCreationCost + cacheReadCost;
|
|
179
|
+
return sumParts(calculateCostParts(tokens, modelPricing));
|
|
163
180
|
}
|
|
164
181
|
|
|
165
182
|
function calculateCostForModel(tokens, modelName, pricing, speed) {
|
|
@@ -174,15 +191,241 @@ function calculateCostForModel(tokens, modelName, pricing, speed) {
|
|
|
174
191
|
|
|
175
192
|
// #region JSONL_PARSING
|
|
176
193
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
194
|
+
const READ_CHUNK = 1 << 20;
|
|
195
|
+
|
|
196
|
+
function parseJsonLine(bytes) {
|
|
197
|
+
try {
|
|
198
|
+
const parsed = JSON.parse(bytes.toString('utf-8'));
|
|
199
|
+
return parsed && typeof parsed === 'object' ? parsed : undefined;
|
|
200
|
+
} catch {
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Calls onParsed for each JSON line that ends in [start, size) and returns the offset after the
|
|
206
|
+
// last one consumed. A line still being written has no newline yet, so it waits for the next read;
|
|
207
|
+
// a last line without one is taken only when it already parses.
|
|
208
|
+
async function readJsonLinesFrom(filePath, start, size, onParsed) {
|
|
209
|
+
const fh = await fs.promises.open(filePath, 'r');
|
|
210
|
+
const buf = Buffer.allocUnsafe(Math.min(READ_CHUNK, size - start));
|
|
211
|
+
let pos = start;
|
|
212
|
+
let tail = null;
|
|
213
|
+
try {
|
|
214
|
+
while (pos < size) {
|
|
215
|
+
const { bytesRead } = await fh.read(buf, 0, Math.min(buf.length, size - pos), pos);
|
|
216
|
+
if (!bytesRead) break;
|
|
217
|
+
pos += bytesRead;
|
|
218
|
+
const chunk = buf.subarray(0, bytesRead);
|
|
219
|
+
let from = 0;
|
|
220
|
+
for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, from)) {
|
|
221
|
+
const part = chunk.subarray(from, nl);
|
|
222
|
+
const parsed = parseJsonLine(tail ? Buffer.concat([tail, part]) : part);
|
|
223
|
+
tail = null;
|
|
224
|
+
if (parsed) onParsed(parsed);
|
|
225
|
+
from = nl + 1;
|
|
226
|
+
}
|
|
227
|
+
if (from < bytesRead) tail = Buffer.concat(tail ? [tail, chunk.subarray(from)] : [chunk.subarray(from)]);
|
|
228
|
+
}
|
|
229
|
+
} finally {
|
|
230
|
+
await fh.close();
|
|
231
|
+
}
|
|
232
|
+
if (!tail) return pos;
|
|
233
|
+
const last = parseJsonLine(tail);
|
|
234
|
+
if (!last) return pos - tail.length;
|
|
235
|
+
onParsed(last);
|
|
236
|
+
return pos;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function joinTools(a, b) {
|
|
240
|
+
return a && b ? a.concat(b) : a || b;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function indexByHash(f) {
|
|
244
|
+
return new Map(f.turns.filter((t) => t.hash).map((t) => [t.hash, t]));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Parsed facts per transcript, kept for the server's lifetime. A transcript only grows, so an entry
|
|
248
|
+
// whose file has the same size and mtime is current, and a grown file is read from where the last
|
|
249
|
+
// read stopped. Facts hold token counts, not cost, so a pricing refresh needs no re-read.
|
|
250
|
+
const fileCache = new Map();
|
|
251
|
+
const fileReads = new Map();
|
|
252
|
+
|
|
253
|
+
// JSON.parse makes a new string for every model and tool name; one copy each is enough.
|
|
254
|
+
const interned = new Map();
|
|
255
|
+
function intern(s) {
|
|
256
|
+
if (typeof s !== 'string') return s;
|
|
257
|
+
const hit = interned.get(s);
|
|
258
|
+
if (hit !== undefined) return hit;
|
|
259
|
+
interned.set(s, s);
|
|
260
|
+
return s;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Only what the turn needs: `parsed` also holds the turn's content blocks.
|
|
264
|
+
function turnFacts(parsed) {
|
|
265
|
+
const u = parsed.message.usage;
|
|
266
|
+
return {
|
|
267
|
+
ts: parsed.timestamp,
|
|
268
|
+
model: intern(parsed.message.model) || null,
|
|
269
|
+
speed: intern(u.speed) || 'standard',
|
|
270
|
+
costUSD: parsed.costUSD ?? null,
|
|
271
|
+
in: u.input_tokens || 0,
|
|
272
|
+
out: u.output_tokens || 0,
|
|
273
|
+
cw: u.cache_creation_input_tokens || 0,
|
|
274
|
+
cr: u.cache_read_input_tokens || 0,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function hasUsage(parsed) {
|
|
279
|
+
return (parsed.message?.usage?.input_tokens || parsed.message?.usage?.input_tokens === 0) && !!parsed.timestamp;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function internTools(content) {
|
|
283
|
+
const tools = extractTools(content);
|
|
284
|
+
return tools?.map(intern) ?? null;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const sessionParser = {
|
|
288
|
+
init: () => ({ customTitle: null, firstPrompt: '', turns: [], skillAgents: {}, skillCalls: {}, pending: null }),
|
|
289
|
+
line(f, byHash, parsed) {
|
|
290
|
+
noteSkillAgent(parsed, f.skillCalls, f.skillAgents);
|
|
291
|
+
if (parsed.type === 'custom-title' && parsed.customTitle) {
|
|
292
|
+
f.customTitle = parsed.customTitle;
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (parsed.type === 'system' && parsed.subtype === 'compact_boundary' && parsed.timestamp) {
|
|
296
|
+
f.pending = compactionFacts(parsed);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
if (!hasUsage(parsed)) return;
|
|
300
|
+
const hash = createDedupeHash(parsed);
|
|
301
|
+
const tools = internTools(parsed.message?.content);
|
|
302
|
+
const prev = hash && byHash.get(hash);
|
|
303
|
+
if (prev) {
|
|
304
|
+
// Streaming writes one JSONL line per content block of the same API message. Usage is
|
|
305
|
+
// identical on every line (deduped), but each line carries different tool_use blocks,
|
|
306
|
+
// so tools must be unioned across duplicates or most calls are lost.
|
|
307
|
+
prev.tools = joinTools(prev.tools, tools);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
const turn = { ...turnFacts(parsed), hash, tools, compaction: f.pending };
|
|
311
|
+
f.pending = null;
|
|
312
|
+
f.turns.push(turn);
|
|
313
|
+
if (hash) byHash.set(hash, turn);
|
|
314
|
+
if (!f.firstPrompt && parsed.type === 'human' && parsed.message?.content) {
|
|
315
|
+
const content = Array.isArray(parsed.message.content)
|
|
316
|
+
? parsed.message.content.map(c => c.text || '').join(' ')
|
|
317
|
+
: (typeof parsed.message.content === 'string' ? parsed.message.content : '');
|
|
318
|
+
if (content.trim()) f.firstPrompt = content.trim().slice(0, 120);
|
|
319
|
+
}
|
|
320
|
+
},
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
const agentParser = {
|
|
324
|
+
init: () => ({ turns: [], unhashed: [] }),
|
|
325
|
+
line(f, byHash, parsed) {
|
|
326
|
+
if (!hasUsage(parsed)) return;
|
|
327
|
+
const hash = createDedupeHash(parsed);
|
|
328
|
+
const turn = { ...turnFacts(parsed), hash, tools: internTools(parsed.message?.content) };
|
|
329
|
+
if (!hash) {
|
|
330
|
+
f.unhashed.push(turn);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
const prev = byHash.get(hash);
|
|
334
|
+
if (!prev) {
|
|
335
|
+
byHash.set(hash, turn);
|
|
336
|
+
f.turns.push(turn);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
const tools = joinTools(prev.tools, turn.tools);
|
|
340
|
+
if (turn.out > prev.out) Object.assign(prev, turn);
|
|
341
|
+
prev.tools = tools;
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
function statFile(filePath) {
|
|
346
|
+
try {
|
|
347
|
+
const st = fs.statSync(filePath);
|
|
348
|
+
return { size: st.size, mtimeMs: st.mtimeMs };
|
|
349
|
+
} catch {
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const EDGE_BYTES = 64;
|
|
355
|
+
|
|
356
|
+
async function readEdges(filePath, offset) {
|
|
357
|
+
const n = Math.min(EDGE_BYTES, offset);
|
|
358
|
+
const head = Buffer.alloc(n);
|
|
359
|
+
const tail = Buffer.alloc(n);
|
|
360
|
+
const fh = await fs.promises.open(filePath, 'r');
|
|
361
|
+
try {
|
|
362
|
+
await fh.read(head, 0, n, 0);
|
|
363
|
+
await fh.read(tail, 0, n, offset - n);
|
|
364
|
+
} finally {
|
|
365
|
+
await fh.close();
|
|
366
|
+
}
|
|
367
|
+
return head.toString('latin1') + tail.toString('latin1');
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async function readFacts(filePath, parser) {
|
|
371
|
+
const st = statFile(filePath);
|
|
372
|
+
if (!st) {
|
|
373
|
+
fileCache.delete(filePath);
|
|
374
|
+
return parser.init();
|
|
185
375
|
}
|
|
376
|
+
let entry = fileCache.get(filePath);
|
|
377
|
+
if (entry && entry.size === st.size && entry.mtimeMs === st.mtimeMs) return entry.facts;
|
|
378
|
+
if (fileReads.has(filePath)) return fileReads.get(filePath);
|
|
379
|
+
const fresh = () => ({ size: 0, mtimeMs: 0, offset: 0, edges: '', facts: parser.init() });
|
|
380
|
+
// An appended file only grows, so a new mtime at the same size, a smaller size, or changed bytes
|
|
381
|
+
// around the old offset mean another tool rewrote it. The edge check is a cheap sample, not a
|
|
382
|
+
// full hash: a rewrite that keeps both edges is missed until the process restarts.
|
|
383
|
+
if (!entry || st.size <= entry.offset || st.size === entry.size) entry = fresh();
|
|
384
|
+
const read = (async () => {
|
|
385
|
+
if (entry.offset && entry.edges !== (await readEdges(filePath, entry.offset))) entry = fresh();
|
|
386
|
+
const byHash = indexByHash(entry.facts);
|
|
387
|
+
entry.offset = await readJsonLinesFrom(filePath, entry.offset, st.size, (parsed) => {
|
|
388
|
+
parser.line(entry.facts, byHash, parsed);
|
|
389
|
+
});
|
|
390
|
+
entry.size = st.size;
|
|
391
|
+
entry.mtimeMs = st.mtimeMs;
|
|
392
|
+
entry.edges = entry.offset ? await readEdges(filePath, entry.offset) : '';
|
|
393
|
+
fileCache.set(filePath, entry);
|
|
394
|
+
return entry.facts;
|
|
395
|
+
})();
|
|
396
|
+
fileReads.set(filePath, read);
|
|
397
|
+
try {
|
|
398
|
+
return await read;
|
|
399
|
+
} catch (err) {
|
|
400
|
+
// The facts may hold part of the read while the offset does not, so start over next time.
|
|
401
|
+
fileCache.delete(filePath);
|
|
402
|
+
throw err;
|
|
403
|
+
} finally {
|
|
404
|
+
fileReads.delete(filePath);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function turnCost(t, pricing) {
|
|
409
|
+
// Auto mode: use costUSD if present, otherwise calculate
|
|
410
|
+
if (t.costUSD != null) return t.costUSD;
|
|
411
|
+
if (!t.model) return 0;
|
|
412
|
+
return calculateCostForModel(
|
|
413
|
+
{ input_tokens: t.in, output_tokens: t.out, cache_creation_input_tokens: t.cw, cache_read_input_tokens: t.cr },
|
|
414
|
+
t.model, pricing, t.speed);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function turnMessage(t, pricing) {
|
|
418
|
+
return {
|
|
419
|
+
timestamp: t.ts,
|
|
420
|
+
model: t.model || 'unknown',
|
|
421
|
+
cost: turnCost(t, pricing),
|
|
422
|
+
inputTokens: t.in,
|
|
423
|
+
outputTokens: t.out,
|
|
424
|
+
cacheCreationTokens: t.cw,
|
|
425
|
+
cacheReadTokens: t.cr,
|
|
426
|
+
speed: t.speed,
|
|
427
|
+
tools: t.tools,
|
|
428
|
+
};
|
|
186
429
|
}
|
|
187
430
|
|
|
188
431
|
|
|
@@ -201,14 +444,6 @@ function extractTools(content) {
|
|
|
201
444
|
return tools.length > 0 ? tools : null;
|
|
202
445
|
}
|
|
203
446
|
|
|
204
|
-
function calculateEntryCost(data, pricing) {
|
|
205
|
-
// Auto mode: use costUSD if present, otherwise calculate
|
|
206
|
-
if (data.costUSD != null) return data.costUSD;
|
|
207
|
-
const model = data.message?.model;
|
|
208
|
-
if (!model) return 0;
|
|
209
|
-
const speed = data.message?.usage?.speed;
|
|
210
|
-
return calculateCostForModel(data.message.usage, model, pricing, speed);
|
|
211
|
-
}
|
|
212
447
|
|
|
213
448
|
// The summarization call behind a compact_boundary is not logged with usage, so its cost is an
|
|
214
449
|
// estimate: the whole pre-compaction context read from cache, and a summary no larger than the
|
|
@@ -521,36 +756,12 @@ function mostFrequentModel(counts) {
|
|
|
521
756
|
// final usage on every line, which is why first-wins reads the same there.
|
|
522
757
|
// Session and project loads read every agent log for its totals alone, so tools are opt-in.
|
|
523
758
|
async function readAgentTurns(filePath, pricing, { withTools = false } = {}) {
|
|
524
|
-
const
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
const usage = parsed.message?.usage;
|
|
530
|
-
if (!usage?.input_tokens && usage?.input_tokens !== 0) return;
|
|
531
|
-
if (!parsed.timestamp) return;
|
|
532
|
-
|
|
533
|
-
// Only what the turn needs: `parsed` also holds the turn's content blocks.
|
|
534
|
-
const entry = { costUSD: parsed.costUSD, timestamp: parsed.timestamp, message: { model: parsed.message.model, usage }, tools: null };
|
|
535
|
-
const tools = withTools ? extractTools(parsed.message?.content) : null;
|
|
536
|
-
const hash = createDedupeHash(parsed);
|
|
537
|
-
if (!hash) { entry.tools = tools; unhashed.push(entry); return; }
|
|
538
|
-
const prev = kept.get(hash);
|
|
539
|
-
const allTools = prev?.tools && tools ? prev.tools.concat(tools) : prev?.tools || tools;
|
|
540
|
-
if (!prev || (usage.output_tokens || 0) > (prev.message.usage.output_tokens || 0)) kept.set(hash, entry);
|
|
541
|
-
kept.get(hash).tools = allTools;
|
|
759
|
+
const f = await readFacts(filePath, agentParser);
|
|
760
|
+
return f.turns.concat(f.unhashed).map((t) => {
|
|
761
|
+
const msg = turnMessage(t, pricing);
|
|
762
|
+
if (!withTools) msg.tools = null;
|
|
763
|
+
return msg;
|
|
542
764
|
});
|
|
543
|
-
return [...kept.values(), ...unhashed].map(e => ({
|
|
544
|
-
cost: calculateEntryCost(e, pricing),
|
|
545
|
-
inputTokens: e.message.usage.input_tokens || 0,
|
|
546
|
-
outputTokens: e.message.usage.output_tokens || 0,
|
|
547
|
-
cacheCreationTokens: e.message.usage.cache_creation_input_tokens || 0,
|
|
548
|
-
cacheReadTokens: e.message.usage.cache_read_input_tokens || 0,
|
|
549
|
-
speed: e.message.usage.speed || 'standard',
|
|
550
|
-
model: e.message.model || 'unknown',
|
|
551
|
-
timestamp: e.timestamp,
|
|
552
|
-
tools: e.tools,
|
|
553
|
-
}));
|
|
554
765
|
}
|
|
555
766
|
|
|
556
767
|
const SKILL_TEXT_MAX = 200;
|
|
@@ -564,15 +775,17 @@ function noteSkillAgent(parsed, calls, texts) {
|
|
|
564
775
|
for (const b of content) {
|
|
565
776
|
if (b.type === 'tool_use' && b.name === 'Skill' && b.input?.skill) {
|
|
566
777
|
const text = `/${b.input.skill} ${b.input.args || ''}`.replace(/\s+/g, ' ').trim();
|
|
567
|
-
calls
|
|
778
|
+
calls[b.id] = { skill: b.input.skill, text: text.length > SKILL_TEXT_MAX ? `${text.slice(0, SKILL_TEXT_MAX - 1)}…` : text };
|
|
568
779
|
}
|
|
569
780
|
}
|
|
570
781
|
return;
|
|
571
782
|
}
|
|
572
783
|
const agentId = parsed.toolUseResult?.agentId;
|
|
573
784
|
if (!agentId) return;
|
|
574
|
-
const
|
|
575
|
-
if (
|
|
785
|
+
const id = content.find(b => b.type === 'tool_result')?.tool_use_id;
|
|
786
|
+
if (!id || !Object.hasOwn(calls, id)) return;
|
|
787
|
+
texts[`agent-${agentId}`] = calls[id];
|
|
788
|
+
delete calls[id];
|
|
576
789
|
}
|
|
577
790
|
|
|
578
791
|
async function loadSubagentData(subagentInfos, pricing) {
|
|
@@ -624,87 +837,39 @@ async function loadProjectData(files, pricing) {
|
|
|
624
837
|
});
|
|
625
838
|
}
|
|
626
839
|
const session = sessions.get(sessionId);
|
|
840
|
+
const f = await readFacts(file, sessionParser);
|
|
841
|
+
if (f.customTitle) session.customTitle = f.customTitle;
|
|
842
|
+
if (!session.firstPrompt) session.firstPrompt = f.firstPrompt;
|
|
843
|
+
|
|
627
844
|
// A boundary is attributed to the next counted turn, so the message list is the only record
|
|
628
|
-
// of compactions; a boundary with no turn after it has nothing to price and is dropped.
|
|
845
|
+
// of compactions; a boundary with no turn after it has nothing to price and is dropped. A turn
|
|
846
|
+
// that an earlier file of the project already counted passes its boundary on.
|
|
629
847
|
let pendingCompaction = null;
|
|
630
|
-
const
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
noteSkillAgent(parsed, skillCalls, skillAgents);
|
|
638
|
-
|
|
639
|
-
if (parsed.type === 'custom-title' && parsed.customTitle) {
|
|
640
|
-
session.customTitle = parsed.customTitle;
|
|
641
|
-
return;
|
|
848
|
+
for (const t of f.turns) {
|
|
849
|
+
const orig = t.hash && seen.get(t.hash);
|
|
850
|
+
if (orig) {
|
|
851
|
+
orig.tools = joinTools(orig.tools, t.tools);
|
|
852
|
+
if (t.compaction) pendingCompaction = t.compaction;
|
|
853
|
+
continue;
|
|
642
854
|
}
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
if (
|
|
651
|
-
|
|
652
|
-
const hash = createDedupeHash(parsed);
|
|
653
|
-
if (hash && seen.has(hash)) {
|
|
654
|
-
// Streaming writes one JSONL line per content block of the same API message. Usage is
|
|
655
|
-
// identical on every line (deduped), but each line carries different tool_use blocks,
|
|
656
|
-
// so tools must be unioned across duplicates or most calls are lost.
|
|
657
|
-
const dupTools = extractTools(parsed.message?.content);
|
|
658
|
-
if (dupTools) {
|
|
659
|
-
const orig = seen.get(hash);
|
|
660
|
-
orig.tools = (orig.tools || []).concat(dupTools);
|
|
661
|
-
}
|
|
662
|
-
return;
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
const cost = calculateEntryCost(parsed, pricing);
|
|
666
|
-
const usage = parsed.message.usage;
|
|
667
|
-
const model = parsed.message?.model || 'unknown';
|
|
668
|
-
const ts = parsed.timestamp;
|
|
669
|
-
|
|
670
|
-
session.totalCost += cost;
|
|
671
|
-
session.inputTokens += usage.input_tokens || 0;
|
|
672
|
-
session.outputTokens += usage.output_tokens || 0;
|
|
673
|
-
session.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
|
|
674
|
-
session.cacheReadTokens += (usage.cache_read_input_tokens || 0);
|
|
675
|
-
if (isRealModel(model)) session.models.add(model);
|
|
855
|
+
const msg = turnMessage(t, pricing);
|
|
856
|
+
const ts = msg.timestamp;
|
|
857
|
+
session.totalCost += msg.cost;
|
|
858
|
+
session.inputTokens += msg.inputTokens;
|
|
859
|
+
session.outputTokens += msg.outputTokens;
|
|
860
|
+
session.cacheCreationTokens += msg.cacheCreationTokens;
|
|
861
|
+
session.cacheReadTokens += msg.cacheReadTokens;
|
|
862
|
+
if (isRealModel(msg.model)) session.models.add(msg.model);
|
|
676
863
|
|
|
677
864
|
if (!session.firstTimestamp || ts < session.firstTimestamp) session.firstTimestamp = ts;
|
|
678
865
|
if (!session.lastTimestamp || ts > session.lastTimestamp) session.lastTimestamp = ts;
|
|
679
866
|
|
|
680
|
-
const
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
cost,
|
|
684
|
-
inputTokens: usage.input_tokens || 0,
|
|
685
|
-
outputTokens: usage.output_tokens || 0,
|
|
686
|
-
cacheCreationTokens: usage.cache_creation_input_tokens || 0,
|
|
687
|
-
cacheReadTokens: usage.cache_read_input_tokens || 0,
|
|
688
|
-
speed: usage.speed || 'standard',
|
|
689
|
-
tools: extractTools(parsed.message?.content),
|
|
690
|
-
};
|
|
691
|
-
if (pendingCompaction) {
|
|
692
|
-
msg.compaction = priceCompaction(pendingCompaction, msg, pricing);
|
|
693
|
-
pendingCompaction = null;
|
|
694
|
-
}
|
|
867
|
+
const facts = t.compaction || pendingCompaction;
|
|
868
|
+
if (facts) msg.compaction = priceCompaction(facts, msg, pricing);
|
|
869
|
+
pendingCompaction = null;
|
|
695
870
|
session.messages.push(msg);
|
|
696
|
-
if (hash) seen.set(hash, msg);
|
|
697
|
-
|
|
698
|
-
// Capture first user prompt from the JSONL (look for human/user messages)
|
|
699
|
-
if (!session.firstPrompt && parsed.type === 'human' && parsed.message?.content) {
|
|
700
|
-
const content = Array.isArray(parsed.message.content)
|
|
701
|
-
? parsed.message.content.map(c => c.text || '').join(' ')
|
|
702
|
-
: (typeof parsed.message.content === 'string' ? parsed.message.content : '');
|
|
703
|
-
if (content.trim()) {
|
|
704
|
-
session.firstPrompt = content.trim().slice(0, 120);
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
});
|
|
871
|
+
if (t.hash) seen.set(t.hash, msg);
|
|
872
|
+
}
|
|
708
873
|
|
|
709
874
|
// Fold subagent costs into session totals
|
|
710
875
|
const sessionDir = path.join(path.dirname(file), sessionId);
|
|
@@ -716,7 +881,7 @@ async function loadProjectData(files, pricing) {
|
|
|
716
881
|
// response — would fold in as a zero-cost message dated at the session's own start,
|
|
717
882
|
// which stretches every span it lands in.
|
|
718
883
|
if (sa.messageCount === 0) continue;
|
|
719
|
-
const skill = skillAgents
|
|
884
|
+
const skill = f.skillAgents[sa.agentId];
|
|
720
885
|
session.totalCost += sa.totalCost;
|
|
721
886
|
session.inputTokens += sa.inputTokens;
|
|
722
887
|
session.outputTokens += sa.outputTokens;
|
|
@@ -1455,11 +1620,21 @@ async function getInsightsData(range, projectFilter) {
|
|
|
1455
1620
|
// getModelPricing falls back to a linear scan of the whole LiteLLM map on a miss, so resolve
|
|
1456
1621
|
// it once per distinct model rather than once per message.
|
|
1457
1622
|
const priceMemo = new Map();
|
|
1623
|
+
const tokenCosts = { input: 0, output: 0, cacheCreation: 0, cacheRead: 0 };
|
|
1458
1624
|
for (const m of all) {
|
|
1625
|
+
if (!priceMemo.has(m.model)) priceMemo.set(m.model, getModelPricing(pricing, m.model));
|
|
1626
|
+
const mp = priceMemo.get(m.model);
|
|
1627
|
+
// Scaled to m.cost, so the parts carry the fast-mode multiplier and a logged costUSD.
|
|
1628
|
+
if (mp && m.cost > 0) {
|
|
1629
|
+
const parts = calculateCostParts({
|
|
1630
|
+
input_tokens: m.inputTokens, output_tokens: m.outputTokens,
|
|
1631
|
+
cache_creation_input_tokens: m.cacheCreationTokens, cache_read_input_tokens: m.cacheReadTokens,
|
|
1632
|
+
}, mp);
|
|
1633
|
+
const raw = sumParts(parts);
|
|
1634
|
+
if (raw > 0) for (const k of Object.keys(parts)) tokenCosts[k] += (parts[k] / raw) * m.cost;
|
|
1635
|
+
}
|
|
1459
1636
|
// What the same tokens would have cost as fresh input, minus what cache reads actually cost.
|
|
1460
1637
|
if (m.cacheReadTokens > 0) {
|
|
1461
|
-
if (!priceMemo.has(m.model)) priceMemo.set(m.model, getModelPricing(pricing, m.model));
|
|
1462
|
-
const mp = priceMemo.get(m.model);
|
|
1463
1638
|
if (mp?.input_cost_per_token != null && mp?.cache_read_input_token_cost != null) {
|
|
1464
1639
|
cacheSavings += m.cacheReadTokens * (mp.input_cost_per_token - mp.cache_read_input_token_cost);
|
|
1465
1640
|
}
|
|
@@ -1506,6 +1681,7 @@ async function getInsightsData(range, projectFilter) {
|
|
|
1506
1681
|
|
|
1507
1682
|
const result = {
|
|
1508
1683
|
tokens,
|
|
1684
|
+
tokenCosts,
|
|
1509
1685
|
cacheSavings,
|
|
1510
1686
|
runRate: { dailyAvg, projectedMonthly: dailyAvg * 30, days: dayCount },
|
|
1511
1687
|
blocks,
|
package/package.json
CHANGED
package/public/app.js
CHANGED
|
@@ -1016,7 +1016,12 @@ function renderInsights() {
|
|
|
1016
1016
|
|
|
1017
1017
|
<div class="charts-row">
|
|
1018
1018
|
<div class="chart-box">
|
|
1019
|
-
<div class="chart-title">Token Composition
|
|
1019
|
+
<div class="chart-title share-head">Token Composition
|
|
1020
|
+
<div class="seg" role="group" aria-label="Measure">
|
|
1021
|
+
<button type="button" class="seg-btn${tokenSplitMode === 'tokens' ? ' on' : ''}" data-token-split="tokens" onclick="setTokenSplitMode('tokens')">tokens</button>
|
|
1022
|
+
<button type="button" class="seg-btn${tokenSplitMode === 'cost' ? ' on' : ''}" data-token-split="cost" onclick="setTokenSplitMode('cost')">cost</button>
|
|
1023
|
+
</div>
|
|
1024
|
+
</div>
|
|
1020
1025
|
<canvas id="tokenSplitChart"></canvas>
|
|
1021
1026
|
</div>
|
|
1022
1027
|
<div class="chart-box">
|
|
@@ -1072,7 +1077,7 @@ function renderInsights() {
|
|
|
1072
1077
|
|
|
1073
1078
|
initHeatmapTooltip();
|
|
1074
1079
|
requestAnimationFrame(() => {
|
|
1075
|
-
renderTokenSplitChart(d
|
|
1080
|
+
renderTokenSplitChart(d);
|
|
1076
1081
|
if (d.tools.length) renderToolsChart(d.tools);
|
|
1077
1082
|
if (showWeekly) renderWeeklyChart(d.weekly);
|
|
1078
1083
|
});
|
|
@@ -2227,11 +2232,25 @@ function drawRangeOverview(svg, messages) {
|
|
|
2227
2232
|
}
|
|
2228
2233
|
// #endregion
|
|
2229
2234
|
|
|
2230
|
-
|
|
2235
|
+
let tokenSplitMode = localStorage.getItem('cc-cost:token-split') === 'cost' ? 'cost' : 'tokens';
|
|
2236
|
+
window.setTokenSplitMode = setTokenSplitMode;
|
|
2237
|
+
|
|
2238
|
+
function setTokenSplitMode(mode) {
|
|
2239
|
+
tokenSplitMode = mode;
|
|
2240
|
+
localStorage.setItem('cc-cost:token-split', mode);
|
|
2241
|
+
for (const b of document.querySelectorAll('[data-token-split]'))
|
|
2242
|
+
b.classList.toggle('on', b.dataset.tokenSplit === mode);
|
|
2243
|
+
if (insightsData) renderTokenSplitChart(insightsData);
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
function renderTokenSplitChart(d) {
|
|
2231
2247
|
const canvas = document.getElementById('tokenSplitChart');
|
|
2232
2248
|
if (!canvas) return;
|
|
2233
2249
|
destroyChart('tokenSplit');
|
|
2234
2250
|
|
|
2251
|
+
const byCost = tokenSplitMode === 'cost';
|
|
2252
|
+
const t = byCost ? d.tokenCosts : d.tokens;
|
|
2253
|
+
const fmt = byCost ? formatCost : formatTokens;
|
|
2235
2254
|
const c = getChartColors();
|
|
2236
2255
|
const defaults = chartDefaults();
|
|
2237
2256
|
const rows = [
|
|
@@ -2258,13 +2277,16 @@ function renderTokenSplitChart(t) {
|
|
|
2258
2277
|
indexAxis: 'y',
|
|
2259
2278
|
interaction: { mode: 'index', axis: 'y', intersect: false },
|
|
2260
2279
|
plugins: withTooltip(defaults, {
|
|
2261
|
-
label: (ctx) => `${
|
|
2280
|
+
label: (ctx) => `${fmt(ctx.parsed.x)} (${formatPct(ctx.parsed.x, total)}%)`,
|
|
2262
2281
|
}),
|
|
2263
2282
|
scales: {
|
|
2264
2283
|
...defaults.scales,
|
|
2265
2284
|
// Log scale: cache reads structurally dwarf fresh input by 3-5 orders of magnitude,
|
|
2266
2285
|
// so a linear axis renders every other bar invisible. Tooltip carries exact values + %.
|
|
2267
|
-
|
|
2286
|
+
// Cost parts sit within about one order of magnitude, so cost mode stays linear.
|
|
2287
|
+
x: byCost
|
|
2288
|
+
? { ...defaults.scales.x, beginAtZero: true, ticks: { ...defaults.scales.x.ticks, callback: formatCost } }
|
|
2289
|
+
: logAxis(defaults.scales.x, Math.max(...rows.map((r) => r[1]))),
|
|
2268
2290
|
},
|
|
2269
2291
|
},
|
|
2270
2292
|
});
|