@aiusage/cli 1.7.1 → 1.7.2

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 (3) hide show
  1. package/dist/cli.js +2155 -2008
  2. package/package.json +1 -1
  3. package/pricing-catalog.json +131 -5
package/dist/cli.js CHANGED
@@ -370,983 +370,1196 @@ import { readdir as readdir4, open as open2, readFile as readFile3 } from "node:
370
370
  import { join as join4 } from "node:path";
371
371
  import { homedir as homedir3 } from "node:os";
372
372
  import { createInterface as createInterface2 } from "node:readline";
373
- var FILE_CONCURRENCY2 = 16, MAX_LINE_BYTES2 = 64 * 1024 * 1024;
374
- async function scanCodexDates(targetDates, codexDir, projectAliases) {
375
- let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
376
- for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
377
- let baseDir = codexDir ?? join4(homedir3(), ".codex"), serviceTier = await detectCodexServiceTier(baseDir), sessionFiles = await collectSessionFiles(baseDir);
378
- if (sessionFiles.length === 0)
379
- return new Map([...targetDateSet].map((targetDate) => [targetDate, []]));
380
- let globalSeenSigs = /* @__PURE__ */ new Set();
381
- return await runWithConcurrency(sessionFiles, FILE_CONCURRENCY2, async (filePath) => {
382
- await processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs, serviceTier);
383
- }), new Map(
384
- [...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
385
- );
386
- }
387
- async function processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs, serviceTier) {
388
- let fh;
389
- try {
390
- fh = await open2(filePath, "r");
391
- } catch {
392
- return;
393
- }
394
- try {
395
- let rl = createInterface2({
396
- input: fh.createReadStream({ encoding: "utf-8" }),
397
- crlfDelay: 1 / 0
398
- }), currentModel = "unknown", currentProjectFields = { project: "unknown", projectDisplay: "unknown" }, previousTotal = {};
399
- for await (let line of rl) {
400
- if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES2) continue;
401
- let record;
402
- try {
403
- record = JSON.parse(line);
404
- } catch {
405
- continue;
406
- }
407
- if (record.type === "turn_context") {
408
- let rawModel = record.payload?.model ?? currentModel;
409
- rawModel !== "<synthetic>" && (currentModel = applyCodexServiceTier(normalizeModelName(rawModel), serviceTier)), record.payload?.cwd && (currentProjectFields = resolveProjectFields(record.payload.cwd, projectAliases));
410
- continue;
373
+
374
+ // ../shared/src/pricing/data/anthropic.ts
375
+ var anthropic = {
376
+ "claude-code": {
377
+ models: {
378
+ "claude-opus-4-8": {
379
+ currency: "USD",
380
+ input_per_million: 5,
381
+ output_per_million: 25,
382
+ cache_write_5m_per_million: 6.25,
383
+ cache_write_1h_per_million: 10,
384
+ cached_input_per_million: 0.5
385
+ },
386
+ "claude-opus-4-7": {
387
+ currency: "USD",
388
+ input_per_million: 5,
389
+ output_per_million: 25,
390
+ cache_write_5m_per_million: 6.25,
391
+ cache_write_1h_per_million: 10,
392
+ cached_input_per_million: 0.5
393
+ },
394
+ "claude-opus-4-6": {
395
+ currency: "USD",
396
+ input_per_million: 5,
397
+ output_per_million: 25,
398
+ cache_write_5m_per_million: 6.25,
399
+ cache_write_1h_per_million: 10,
400
+ cached_input_per_million: 0.5
401
+ },
402
+ "claude-opus-4-5": {
403
+ currency: "USD",
404
+ input_per_million: 5,
405
+ output_per_million: 25,
406
+ cache_write_5m_per_million: 6.25,
407
+ cache_write_1h_per_million: 10,
408
+ cached_input_per_million: 0.5
409
+ },
410
+ "claude-opus-4-1": {
411
+ currency: "USD",
412
+ input_per_million: 15,
413
+ output_per_million: 75,
414
+ cache_write_5m_per_million: 18.75,
415
+ cache_write_1h_per_million: 30,
416
+ cached_input_per_million: 1.5
417
+ },
418
+ "claude-opus-4": {
419
+ currency: "USD",
420
+ notes: "deprecated",
421
+ input_per_million: 15,
422
+ output_per_million: 75,
423
+ cache_write_5m_per_million: 18.75,
424
+ cache_write_1h_per_million: 30,
425
+ cached_input_per_million: 1.5
426
+ },
427
+ "claude-sonnet-4-6": {
428
+ currency: "USD",
429
+ input_per_million: 3,
430
+ output_per_million: 15,
431
+ cache_write_5m_per_million: 3.75,
432
+ cache_write_1h_per_million: 6,
433
+ cached_input_per_million: 0.3
434
+ },
435
+ "claude-sonnet-4-5": {
436
+ currency: "USD",
437
+ input_per_million: 3,
438
+ output_per_million: 15,
439
+ cache_write_5m_per_million: 3.75,
440
+ cache_write_1h_per_million: 6,
441
+ cached_input_per_million: 0.3
442
+ },
443
+ "claude-sonnet-4": {
444
+ currency: "USD",
445
+ notes: "deprecated",
446
+ input_per_million: 3,
447
+ output_per_million: 15,
448
+ cache_write_5m_per_million: 3.75,
449
+ cache_write_1h_per_million: 6,
450
+ cached_input_per_million: 0.3
451
+ },
452
+ "claude-haiku-4-5": {
453
+ currency: "USD",
454
+ input_per_million: 1,
455
+ output_per_million: 5,
456
+ cache_write_5m_per_million: 1.25,
457
+ cache_write_1h_per_million: 2,
458
+ cached_input_per_million: 0.1
459
+ },
460
+ "claude-haiku-3-5": {
461
+ currency: "USD",
462
+ notes: "retired except on Bedrock/Vertex",
463
+ input_per_million: 0.8,
464
+ output_per_million: 4,
465
+ cache_write_5m_per_million: 1,
466
+ cache_write_1h_per_million: 1.6,
467
+ cached_input_per_million: 0.08
411
468
  }
412
- if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
413
- let info = record.payload?.info;
414
- if (!info?.total_token_usage) continue;
415
- let ts = parseTimestamp2(record.timestamp);
416
- if (!ts) continue;
417
- let usageDate = toDateKey2(ts);
418
- if (!targetDateSet.has(usageDate)) continue;
419
- let total = info.total_token_usage;
420
- if ((total.input_tokens ?? 0) + (total.cached_input_tokens ?? 0) + (total.output_tokens ?? 0) + (total.reasoning_output_tokens ?? 0) + (total.total_tokens ?? 0) === 0) continue;
421
- let signature = `${total.input_tokens ?? 0}|${total.cached_input_tokens ?? 0}|${total.output_tokens ?? 0}|${total.reasoning_output_tokens ?? 0}|${total.total_tokens ?? 0}`;
422
- if (globalSeenSigs.has(signature)) continue;
423
- globalSeenSigs.add(signature);
424
- let last = info.last_token_usage ?? {
425
- input_tokens: Math.max(0, (total.input_tokens ?? 0) - (previousTotal.input_tokens ?? 0)),
426
- cached_input_tokens: Math.max(0, (total.cached_input_tokens ?? 0) - (previousTotal.cached_input_tokens ?? 0)),
427
- output_tokens: Math.max(0, (total.output_tokens ?? 0) - (previousTotal.output_tokens ?? 0)),
428
- reasoning_output_tokens: Math.max(0, (total.reasoning_output_tokens ?? 0) - (previousTotal.reasoning_output_tokens ?? 0))
429
- };
430
- previousTotal = total;
431
- let nonCachedInput = Math.max(0, (last.input_tokens ?? 0) - (last.cached_input_tokens ?? 0)), grouped = groupedByDate.get(usageDate);
432
- if (!grouped) continue;
433
- let key = `${currentModel}|${currentProjectFields.project}`, existing = grouped.get(key);
434
- existing ? (existing.eventCount += 1, existing.inputTokens += nonCachedInput, existing.cachedInputTokens += last.cached_input_tokens ?? 0, existing.outputTokens += last.output_tokens ?? 0, existing.reasoningOutputTokens += last.reasoning_output_tokens ?? 0) : grouped.set(key, {
435
- provider: "openai",
436
- product: "codex",
437
- channel: "cli",
438
- model: currentModel,
439
- project: currentProjectFields.project,
440
- projectDisplay: currentProjectFields.projectDisplay,
441
- projectAlias: currentProjectFields.projectAlias,
442
- eventCount: 1,
443
- inputTokens: nonCachedInput,
444
- cachedInputTokens: last.cached_input_tokens ?? 0,
445
- cacheWriteTokens: 0,
446
- outputTokens: last.output_tokens ?? 0,
447
- reasoningOutputTokens: last.reasoning_output_tokens ?? 0
448
- });
449
469
  }
450
- } finally {
451
- await fh.close();
452
- }
453
- }
454
- async function collectSessionFiles(baseDir) {
455
- let paths = [], archivedDir = join4(baseDir, "archived_sessions");
456
- try {
457
- let files = await readdir4(archivedDir);
458
- for (let f of files)
459
- f.endsWith(".jsonl") && paths.push(join4(archivedDir, f));
460
- } catch {
461
- }
462
- let sessionsDir = join4(baseDir, "sessions");
463
- return await walkDir(sessionsDir, paths), paths;
464
- }
465
- async function detectCodexServiceTier(baseDir) {
466
- let config = "";
467
- try {
468
- config = await readFile3(join4(baseDir, "config.toml"), "utf-8");
469
- } catch {
470
- return null;
471
- }
472
- let serviceTier = config.match(/^\s*service_tier\s*=\s*["']([^"']+)["']/m)?.[1]?.trim().toLowerCase();
473
- return serviceTier === "priority" ? "priority" : serviceTier === "fast" || config.match(/^\s*fast_mode\s*=\s*(true|false)\s*$/m)?.[1] === "true" ? "fast" : null;
474
- }
475
- function applyCodexServiceTier(model, serviceTier) {
476
- return !serviceTier || model.endsWith("-fast") || model.endsWith("-priority") ? model : model === "gpt-5.5" || model === "gpt-5.4" ? `${model}-${serviceTier}` : model;
477
- }
478
- async function walkDir(dir, result) {
479
- let entries;
480
- try {
481
- entries = await readdir4(dir, { withFileTypes: !0 });
482
- } catch {
483
- return;
484
- }
485
- for (let entry of entries) {
486
- let fullPath = join4(dir, entry.name);
487
- entry.isDirectory() ? await walkDir(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
488
- }
489
- }
490
- function parseTimestamp2(value) {
491
- if (!value) return null;
492
- try {
493
- let d = new Date(value);
494
- return isNaN(d.getTime()) ? null : d;
495
- } catch {
496
- return null;
497
470
  }
498
- }
499
- function toDateKey2(date) {
500
- let year = date.getFullYear(), month = String(date.getMonth() + 1).padStart(2, "0"), day = String(date.getDate()).padStart(2, "0");
501
- return `${year}-${month}-${day}`;
502
- }
471
+ };
503
472
 
504
- // src/scanners/copilot.ts
505
- import { readFile as readFile4 } from "node:fs/promises";
506
- import { join as join5 } from "node:path";
507
- import { homedir as homedir4 } from "node:os";
508
- async function scanCopilotDates(targetDates, baseDir, projectAliases) {
509
- let dates = new Set(targetDates), dir = baseDir ?? join5(homedir4(), ".copilot", "session-state"), files = await walkFiles(dir, ".jsonl");
510
- if (files.length === 0) return emptyResult(dates);
511
- let grouped = initDateMap(dates);
512
- for (let filePath of files) {
513
- let content;
514
- try {
515
- content = await readFile4(filePath, "utf-8");
516
- } catch {
517
- continue;
518
- }
519
- let sessionProjectFields = { project: "unknown", projectDisplay: "unknown" }, lines = content.split(`
520
- `);
521
- for (let line of lines) {
522
- if (!line.trim()) continue;
523
- let obj;
524
- try {
525
- obj = JSON.parse(line);
526
- } catch {
527
- continue;
528
- }
529
- if (obj.type === "session.start" || obj.type === "session.resume") {
530
- let ctx = obj.data?.context, raw = ctx?.gitRoot ?? ctx?.cwd;
531
- raw && (sessionProjectFields = resolveProjectFields(raw, projectAliases));
532
- }
533
- if (obj.type !== "session.shutdown") continue;
534
- let ts = parseTs(obj.timestamp);
535
- if (!ts) continue;
536
- let dk = dateKey(ts), dayMap = grouped.get(dk);
537
- if (!dayMap) continue;
538
- let metrics = obj.data?.modelMetrics;
539
- if (metrics)
540
- for (let [model, entry] of Object.entries(metrics)) {
541
- let usage = entry.usage;
542
- if (!usage) continue;
543
- let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, output = usage.outputTokens ?? 0, input = Math.max(rawInput - cacheRead, 0);
544
- accumulate(
545
- dayMap,
546
- `${model}|${sessionProjectFields.project}`,
547
- {
548
- provider: "github",
549
- product: "copilot-cli",
550
- channel: "cli",
551
- model,
552
- project: sessionProjectFields.project,
553
- projectDisplay: sessionProjectFields.projectDisplay,
554
- projectAlias: sessionProjectFields.projectAlias,
555
- inputTokens: 0,
556
- cachedInputTokens: 0,
557
- cacheWriteTokens: 0,
558
- outputTokens: 0,
559
- reasoningOutputTokens: 0
560
- },
561
- { input, cached: cacheRead, cacheWrite: 0, output, reasoning: 0 }
562
- );
563
- }
473
+ // ../shared/src/pricing/data/openai.ts
474
+ var openai = {
475
+ codex: {
476
+ models: {
477
+ // ── GPT-5.6 系列 ──
478
+ "gpt-5.6-sol": {
479
+ currency: "USD",
480
+ notes: "prompts over 272K input tokens bill the full request at long-context rates",
481
+ input_per_million: 5,
482
+ cached_input_per_million: 0.5,
483
+ cache_write_per_million: 6.25,
484
+ output_per_million: 30,
485
+ tiers: [
486
+ {
487
+ threshold: 272e3,
488
+ input_per_million: 5,
489
+ cached_input_per_million: 0.5,
490
+ cache_write_per_million: 6.25,
491
+ output_per_million: 30
492
+ },
493
+ {
494
+ input_per_million: 10,
495
+ cached_input_per_million: 1,
496
+ cache_write_per_million: 12.5,
497
+ output_per_million: 45
498
+ }
499
+ ]
500
+ },
501
+ "gpt-5.6-terra": {
502
+ currency: "USD",
503
+ notes: "prompts over 272K input tokens bill the full request at long-context rates",
504
+ input_per_million: 2.5,
505
+ cached_input_per_million: 0.25,
506
+ cache_write_per_million: 3.125,
507
+ output_per_million: 15,
508
+ tiers: [
509
+ {
510
+ threshold: 272e3,
511
+ input_per_million: 2.5,
512
+ cached_input_per_million: 0.25,
513
+ cache_write_per_million: 3.125,
514
+ output_per_million: 15
515
+ },
516
+ {
517
+ input_per_million: 5,
518
+ cached_input_per_million: 0.5,
519
+ cache_write_per_million: 6.25,
520
+ output_per_million: 22.5
521
+ }
522
+ ]
523
+ },
524
+ "gpt-5.6-luna": {
525
+ currency: "USD",
526
+ notes: "prompts over 272K input tokens bill the full request at long-context rates",
527
+ input_per_million: 1,
528
+ cached_input_per_million: 0.1,
529
+ cache_write_per_million: 1.25,
530
+ output_per_million: 6,
531
+ tiers: [
532
+ {
533
+ threshold: 272e3,
534
+ input_per_million: 1,
535
+ cached_input_per_million: 0.1,
536
+ cache_write_per_million: 1.25,
537
+ output_per_million: 6
538
+ },
539
+ {
540
+ input_per_million: 2,
541
+ cached_input_per_million: 0.2,
542
+ cache_write_per_million: 2.5,
543
+ output_per_million: 9
544
+ }
545
+ ]
546
+ },
547
+ // ── GPT-5.5 系列 ──
548
+ "gpt-5.5": {
549
+ currency: "USD",
550
+ notes: "prompts over 272K input tokens bill the full request at long-context rates",
551
+ input_per_million: 5,
552
+ cached_input_per_million: 0.5,
553
+ output_per_million: 30,
554
+ tiers: [
555
+ {
556
+ threshold: 272e3,
557
+ input_per_million: 5,
558
+ cached_input_per_million: 0.5,
559
+ output_per_million: 30
560
+ },
561
+ {
562
+ input_per_million: 10,
563
+ cached_input_per_million: 1,
564
+ output_per_million: 45
565
+ }
566
+ ]
567
+ },
568
+ "gpt-5.5-pro": {
569
+ currency: "USD",
570
+ notes: "prompts over 272K input tokens bill the full request at long-context rates",
571
+ input_per_million: 30,
572
+ cached_input_per_million: null,
573
+ output_per_million: 180,
574
+ tiers: [
575
+ {
576
+ threshold: 272e3,
577
+ input_per_million: 30,
578
+ cached_input_per_million: null,
579
+ output_per_million: 180
580
+ },
581
+ {
582
+ input_per_million: 60,
583
+ cached_input_per_million: null,
584
+ output_per_million: 270
585
+ }
586
+ ]
587
+ },
588
+ // ── GPT-5.4 系列 ──
589
+ "gpt-5.4": {
590
+ currency: "USD",
591
+ notes: "prompts over 272K input tokens bill the full request at long-context rates",
592
+ input_per_million: 2.5,
593
+ cached_input_per_million: 0.25,
594
+ output_per_million: 15,
595
+ tiers: [
596
+ {
597
+ threshold: 272e3,
598
+ input_per_million: 2.5,
599
+ cached_input_per_million: 0.25,
600
+ output_per_million: 15
601
+ },
602
+ {
603
+ input_per_million: 5,
604
+ cached_input_per_million: 0.5,
605
+ output_per_million: 22.5
606
+ }
607
+ ]
608
+ },
609
+ "gpt-5.4-mini": {
610
+ currency: "USD",
611
+ input_per_million: 0.75,
612
+ cached_input_per_million: 0.075,
613
+ output_per_million: 4.5
614
+ },
615
+ "gpt-5.4-nano": {
616
+ currency: "USD",
617
+ input_per_million: 0.2,
618
+ cached_input_per_million: 0.02,
619
+ output_per_million: 1.25
620
+ },
621
+ "gpt-5.4-pro": {
622
+ currency: "USD",
623
+ notes: "prompts over 272K input tokens bill the full request at long-context rates",
624
+ input_per_million: 30,
625
+ cached_input_per_million: null,
626
+ output_per_million: 180,
627
+ tiers: [
628
+ {
629
+ threshold: 272e3,
630
+ input_per_million: 30,
631
+ cached_input_per_million: null,
632
+ output_per_million: 180
633
+ },
634
+ {
635
+ input_per_million: 60,
636
+ cached_input_per_million: null,
637
+ output_per_million: 270
638
+ }
639
+ ]
640
+ },
641
+ // ── GPT-5.3 / 5.2 / Codex 变体 ──
642
+ "gpt-5.3-codex": {
643
+ currency: "USD",
644
+ input_per_million: 1.75,
645
+ cached_input_per_million: 0.175,
646
+ output_per_million: 14
647
+ },
648
+ "gpt-5.2-codex": {
649
+ currency: "USD",
650
+ input_per_million: 1.75,
651
+ cached_input_per_million: 0.175,
652
+ output_per_million: 14
653
+ },
654
+ "gpt-5.2-pro": {
655
+ currency: "USD",
656
+ input_per_million: 21,
657
+ cached_input_per_million: null,
658
+ output_per_million: 168
659
+ },
660
+ "gpt-5.2": {
661
+ currency: "USD",
662
+ input_per_million: 1.75,
663
+ cached_input_per_million: 0.175,
664
+ output_per_million: 14
665
+ },
666
+ // ── GPT-5.1 / 5 系列 ──
667
+ "gpt-5.1-codex-max": {
668
+ currency: "USD",
669
+ input_per_million: 1.25,
670
+ cached_input_per_million: 0.125,
671
+ output_per_million: 10
672
+ },
673
+ "gpt-5.1-codex-mini": {
674
+ currency: "USD",
675
+ input_per_million: 0.25,
676
+ cached_input_per_million: 0.025,
677
+ output_per_million: 2
678
+ },
679
+ "gpt-5.1-codex": {
680
+ currency: "USD",
681
+ input_per_million: 1.25,
682
+ cached_input_per_million: 0.125,
683
+ output_per_million: 10
684
+ },
685
+ "gpt-5.1": {
686
+ currency: "USD",
687
+ input_per_million: 1.25,
688
+ cached_input_per_million: 0.125,
689
+ output_per_million: 10
690
+ },
691
+ "gpt-5-pro": {
692
+ currency: "USD",
693
+ input_per_million: 15,
694
+ cached_input_per_million: null,
695
+ output_per_million: 120
696
+ },
697
+ "gpt-5-codex": {
698
+ currency: "USD",
699
+ input_per_million: 1.25,
700
+ cached_input_per_million: 0.125,
701
+ output_per_million: 10
702
+ },
703
+ "gpt-5-mini": {
704
+ currency: "USD",
705
+ input_per_million: 0.25,
706
+ cached_input_per_million: 0.025,
707
+ output_per_million: 2
708
+ },
709
+ "gpt-5-nano": {
710
+ currency: "USD",
711
+ input_per_million: 0.05,
712
+ cached_input_per_million: 5e-3,
713
+ output_per_million: 0.4
714
+ },
715
+ "gpt-5": {
716
+ currency: "USD",
717
+ input_per_million: 1.25,
718
+ cached_input_per_million: 0.125,
719
+ output_per_million: 10
720
+ },
721
+ // ── GPT-4.1 / 4o ──
722
+ "gpt-4.1": { currency: "USD", input_per_million: 2, cached_input_per_million: 0.5, output_per_million: 8 },
723
+ "gpt-4.1-mini": { currency: "USD", input_per_million: 0.4, cached_input_per_million: 0.1, output_per_million: 1.6 },
724
+ "gpt-4.1-nano": { currency: "USD", input_per_million: 0.1, cached_input_per_million: 0.025, output_per_million: 0.4 },
725
+ "gpt-4o": { currency: "USD", input_per_million: 2.5, cached_input_per_million: 1.25, output_per_million: 10 },
726
+ "gpt-4o-mini": { currency: "USD", input_per_million: 0.15, cached_input_per_million: 0.075, output_per_million: 0.6 },
727
+ "gpt-4o-2024-05-13": { currency: "USD", input_per_million: 5, cached_input_per_million: null, output_per_million: 15 },
728
+ // ── o 系列 ──
729
+ "o1-pro": { currency: "USD", input_per_million: 150, cached_input_per_million: null, output_per_million: 600 },
730
+ o1: { currency: "USD", input_per_million: 15, cached_input_per_million: 7.5, output_per_million: 60 },
731
+ "o1-mini": { currency: "USD", input_per_million: 1.1, cached_input_per_million: 0.55, output_per_million: 4.4 },
732
+ "o3-pro": { currency: "USD", input_per_million: 20, cached_input_per_million: null, output_per_million: 80 },
733
+ o3: { currency: "USD", input_per_million: 2, cached_input_per_million: 0.5, output_per_million: 8 },
734
+ "o3-mini": { currency: "USD", input_per_million: 1.1, cached_input_per_million: 0.55, output_per_million: 4.4 },
735
+ "o4-mini": { currency: "USD", input_per_million: 1.1, cached_input_per_million: 0.275, output_per_million: 4.4 },
736
+ // ── Deep research / 工具型 ──
737
+ "o3-deep-research": {
738
+ currency: "USD",
739
+ notes: "corrected from previous 10/40 entry on 2026-05-24",
740
+ input_per_million: 5,
741
+ cached_input_per_million: null,
742
+ output_per_million: 20
743
+ },
744
+ "o4-mini-deep-research": {
745
+ currency: "USD",
746
+ notes: "corrected from previous 2/8 entry on 2026-05-24",
747
+ input_per_million: 1,
748
+ cached_input_per_million: null,
749
+ output_per_million: 4
750
+ },
751
+ "computer-use-preview": {
752
+ currency: "USD",
753
+ notes: "corrected from previous 3/12 entry on 2026-05-24",
754
+ input_per_million: 1.5,
755
+ cached_input_per_million: null,
756
+ output_per_million: 6
757
+ },
758
+ // ── 历史模型(GPT-4 / 3.5 / davinci 等)──
759
+ "gpt-4-turbo-2024-04-09": { currency: "USD", input_per_million: 10, cached_input_per_million: null, output_per_million: 30 },
760
+ "gpt-4-0125-preview": { currency: "USD", input_per_million: 10, cached_input_per_million: null, output_per_million: 30 },
761
+ "gpt-4-1106-preview": { currency: "USD", input_per_million: 10, cached_input_per_million: null, output_per_million: 30 },
762
+ "gpt-4-1106-vision-preview": { currency: "USD", input_per_million: 10, cached_input_per_million: null, output_per_million: 30 },
763
+ "gpt-4-0613": { currency: "USD", input_per_million: 30, cached_input_per_million: null, output_per_million: 60 },
764
+ "gpt-4-0314": { currency: "USD", input_per_million: 30, cached_input_per_million: null, output_per_million: 60 },
765
+ "gpt-4-32k": { currency: "USD", input_per_million: 60, cached_input_per_million: null, output_per_million: 120 },
766
+ "gpt-3.5-turbo": { currency: "USD", input_per_million: 0.5, cached_input_per_million: null, output_per_million: 1.5 },
767
+ "gpt-3.5-turbo-0125": { currency: "USD", input_per_million: 0.5, cached_input_per_million: null, output_per_million: 1.5 },
768
+ "gpt-3.5-turbo-1106": { currency: "USD", input_per_million: 1, cached_input_per_million: null, output_per_million: 2 },
769
+ "gpt-3.5-turbo-0613": { currency: "USD", input_per_million: 1.5, cached_input_per_million: null, output_per_million: 2 },
770
+ "gpt-3.5-0301": { currency: "USD", input_per_million: 1.5, cached_input_per_million: null, output_per_million: 2 },
771
+ "gpt-3.5-turbo-instruct": { currency: "USD", input_per_million: 1.5, cached_input_per_million: null, output_per_million: 2 },
772
+ "gpt-3.5-turbo-16k-0613": { currency: "USD", input_per_million: 3, cached_input_per_million: null, output_per_million: 4 },
773
+ "davinci-002": { currency: "USD", input_per_million: 2, cached_input_per_million: null, output_per_million: 2 },
774
+ "babbage-002": { currency: "USD", input_per_million: 0.4, cached_input_per_million: null, output_per_million: 0.4 },
775
+ "codex-mini-latest": { currency: "USD", input_per_million: 1.5, cached_input_per_million: 0.375, output_per_million: 6 },
776
+ // ── Embeddings ──
777
+ "text-embedding-3-small": { currency: "USD", input_per_million: 0.02, cached_input_per_million: null, output_per_million: 0 },
778
+ "text-embedding-3-large": { currency: "USD", input_per_million: 0.13, cached_input_per_million: null, output_per_million: 0 },
779
+ "text-embedding-ada-002": { currency: "USD", input_per_million: 0.1, cached_input_per_million: null, output_per_million: 0 }
564
780
  }
565
781
  }
566
- return finalize(grouped);
567
- }
782
+ };
568
783
 
569
- // src/scanners/copilot-vscode.ts
570
- import { readFile as readFile5 } from "node:fs/promises";
571
- import { basename as basename2, dirname, join as join6 } from "node:path";
572
- import { homedir as homedir5 } from "node:os";
573
- async function scanCopilotVscodeDates(targetDates, baseDir, projectAliases, workspaceStorageDir) {
574
- let dates = new Set(targetDates), dir = baseDir ?? join6(homedir5(), "Library", "Application Support", "Code", "logs"), workspaceDir = workspaceStorageDir ?? join6(homedir5(), "Library", "Application Support", "Code", "User", "workspaceStorage"), logFiles = (await walkFiles(dir, ".log")).filter((filePath) => basename2(filePath) === "GitHub Copilot Chat.log"), sessionFiles = (await walkFiles(workspaceDir, ".json")).filter((filePath) => filePath.includes("/chatSessions/"));
575
- if (logFiles.length === 0 && sessionFiles.length === 0) return emptyResult(dates);
576
- let grouped = initDateMap(dates), seenEvents = /* @__PURE__ */ new Set();
577
- for (let filePath of logFiles) {
578
- let content;
579
- try {
580
- content = await readFile5(filePath, "utf-8");
581
- } catch {
582
- continue;
583
- }
584
- let sessionProject = "unknown";
585
- for (let line of content.split(`
586
- `)) {
587
- if (!line.trim()) continue;
588
- let projectPath = extractFileUriPath(line);
589
- projectPath && (sessionProject = projectFromPath(projectPath, projectAliases));
590
- let event = extractSuccessEvent(line);
591
- if (!event) continue;
592
- let dayMap = grouped.get(dateKey(event.timestamp));
593
- if (!dayMap) continue;
594
- let dedupeKey = `${event.requestId}|${event.timestamp.toISOString()}|${event.model}|${sessionProject}`;
595
- seenEvents.has(dedupeKey) || (seenEvents.add(dedupeKey), accumulate(
596
- dayMap,
597
- `${event.model}|${sessionProject}`,
598
- {
599
- provider: "github",
600
- product: "copilot-vscode",
601
- channel: "ide",
602
- model: event.model,
603
- project: sessionProject,
604
- inputTokens: 0,
605
- cachedInputTokens: 0,
606
- cacheWriteTokens: 0,
607
- outputTokens: 0,
608
- reasoningOutputTokens: 0
609
- },
610
- { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
611
- ));
784
+ // ../shared/src/pricing/data/google.ts
785
+ var google = {
786
+ // Antigravity 本地不输出 token 信息,仅事件计数;保留空 models 不算费用
787
+ antigravity: { models: {} },
788
+ "gemini-cli": {
789
+ models: {
790
+ // ── Gemini 3.x 系列 ──
791
+ "gemini-3.5-flash": {
792
+ currency: "USD",
793
+ input_per_million: 1.5,
794
+ output_per_million: 9,
795
+ cached_input_per_million: 0.15
796
+ },
797
+ "gemini-3.1-pro-preview": {
798
+ currency: "USD",
799
+ notes: "tiered by prompt length, 200K threshold",
800
+ tiers: [
801
+ { threshold: 2e5, input_per_million: 2, cached_input_per_million: 0.2, output_per_million: 12 },
802
+ { input_per_million: 4, cached_input_per_million: 0.4, output_per_million: 18 }
803
+ ]
804
+ },
805
+ "gemini-3.1-flash-lite": {
806
+ currency: "USD",
807
+ notes: "text/image/video price; audio is $0.50/M",
808
+ input_per_million: 0.25,
809
+ cached_input_per_million: 0.025,
810
+ output_per_million: 1.5
811
+ },
812
+ "gemini-3.1-flash-lite-preview": {
813
+ currency: "USD",
814
+ notes: "text/image/video price",
815
+ input_per_million: 0.25,
816
+ cached_input_per_million: 0.025,
817
+ output_per_million: 1.5
818
+ },
819
+ "gemini-3-flash-preview": {
820
+ currency: "USD",
821
+ notes: "text/image/video price; audio is $1.00/M",
822
+ input_per_million: 0.5,
823
+ cached_input_per_million: 0.05,
824
+ output_per_million: 3
825
+ },
826
+ // ── Gemini 2.5 系列 ──
827
+ "gemini-2.5-pro": {
828
+ currency: "USD",
829
+ notes: "tiered by prompt length, 200K threshold",
830
+ tiers: [
831
+ { threshold: 2e5, input_per_million: 1.25, cached_input_per_million: 0.125, output_per_million: 10 },
832
+ { input_per_million: 2.5, cached_input_per_million: 0.25, output_per_million: 15 }
833
+ ]
834
+ },
835
+ "gemini-2.5-flash": {
836
+ currency: "USD",
837
+ notes: "text/image/video price; audio is $1.00/M; corrected from 0.15/0.6 on 2026-05-24",
838
+ input_per_million: 0.3,
839
+ cached_input_per_million: 0.03,
840
+ output_per_million: 2.5
841
+ },
842
+ "gemini-2.5-flash-lite": {
843
+ currency: "USD",
844
+ notes: "text/image/video price; audio is $0.30/M",
845
+ input_per_million: 0.1,
846
+ cached_input_per_million: 0.01,
847
+ output_per_million: 0.4
848
+ },
849
+ "gemini-2.5-flash-lite-preview": {
850
+ currency: "USD",
851
+ input_per_million: 0.1,
852
+ cached_input_per_million: 0.01,
853
+ output_per_million: 0.4
854
+ },
855
+ "gemini-2.5-computer-use-preview": {
856
+ currency: "USD",
857
+ notes: "tiered by prompt length, 200K threshold",
858
+ tiers: [
859
+ { threshold: 2e5, input_per_million: 1.25, output_per_million: 10 },
860
+ { input_per_million: 2.5, output_per_million: 15 }
861
+ ]
862
+ },
863
+ // ── Gemini 2.0 系列 ──
864
+ "gemini-2.0-flash": {
865
+ currency: "USD",
866
+ notes: "text/image/video price; audio is $0.70/M",
867
+ input_per_million: 0.1,
868
+ cached_input_per_million: 0.025,
869
+ output_per_million: 0.4
870
+ },
871
+ "gemini-2.0-flash-lite": {
872
+ currency: "USD",
873
+ input_per_million: 0.075,
874
+ output_per_million: 0.3
875
+ },
876
+ // ── Gemini 1.5(legacy)──
877
+ "gemini-1.5-pro": {
878
+ currency: "USD",
879
+ notes: "legacy",
880
+ input_per_million: 1.25,
881
+ cached_input_per_million: 0.3125,
882
+ output_per_million: 5
883
+ },
884
+ "gemini-1.5-flash": {
885
+ currency: "USD",
886
+ notes: "legacy",
887
+ input_per_million: 0.075,
888
+ cached_input_per_million: 0.01875,
889
+ output_per_million: 0.3
890
+ },
891
+ // ── Robotics / Embedding ──
892
+ "gemini-robotics-er-1.6-preview": {
893
+ currency: "USD",
894
+ notes: "text/image/video price; audio is $2.00/M",
895
+ input_per_million: 1,
896
+ output_per_million: 5
897
+ },
898
+ "gemini-embedding-2": {
899
+ currency: "USD",
900
+ notes: "text input only price; image $0.45/M, audio $6.50/M, video $12.00/M",
901
+ input_per_million: 0.2,
902
+ output_per_million: 0
903
+ },
904
+ "gemini-embedding": {
905
+ currency: "USD",
906
+ input_per_million: 0.15,
907
+ output_per_million: 0
908
+ },
909
+ // ── Live API / TTS / Image / Video 走 perfect-fit 模型,按其代表单价;
910
+ // 这些模型的 input/output 不是简单的 text token,应在 scanner 侧匹配。 ──
911
+ "gemini-3.1-flash-live-preview": {
912
+ currency: "USD",
913
+ notes: "Live API text price; audio/video/image priced separately",
914
+ input_per_million: 0.75,
915
+ output_per_million: 4.5
916
+ },
917
+ "gemini-2.5-flash-native-audio": {
918
+ currency: "USD",
919
+ notes: "Live API text price; audio is $3.00 input / $12.00 output",
920
+ input_per_million: 0.5,
921
+ output_per_million: 2
922
+ },
923
+ "gemini-3.1-flash-tts-preview": {
924
+ currency: "USD",
925
+ notes: "text in, audio out",
926
+ input_per_million: 1,
927
+ output_per_million: 20
928
+ },
929
+ "gemini-2.5-flash-preview-tts": {
930
+ currency: "USD",
931
+ notes: "text in, audio out",
932
+ input_per_million: 0.5,
933
+ output_per_million: 10
934
+ },
935
+ "gemini-2.5-pro-preview-tts": {
936
+ currency: "USD",
937
+ notes: "text in, audio out",
938
+ input_per_million: 1,
939
+ output_per_million: 20
940
+ },
941
+ "gemini-3.1-flash-image-preview": {
942
+ currency: "USD",
943
+ notes: "text/image in, image out priced per-image",
944
+ input_per_million: 0.5,
945
+ output_per_million: 3
946
+ },
947
+ "gemini-2.5-flash-image": {
948
+ currency: "USD",
949
+ notes: "image out priced per-image ($0.039)",
950
+ input_per_million: 0.3,
951
+ output_per_million: 0
952
+ },
953
+ "gemini-3-pro-image-preview": {
954
+ currency: "USD",
955
+ notes: "image out priced per-image; text-output $12/M",
956
+ input_per_million: 2,
957
+ output_per_million: 12
958
+ }
612
959
  }
613
960
  }
614
- for (let filePath of sessionFiles)
615
- await collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases);
616
- return finalize(grouped);
617
- }
618
- function extractSuccessEvent(line) {
619
- if (!line.includes("ccreq:") || !line.includes("| success |")) return null;
620
- let timestampMatch = line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)/);
621
- if (!timestampMatch) return null;
622
- let timestamp = new Date(timestampMatch[1].replace(" ", "T"));
623
- if (Number.isNaN(timestamp.getTime())) return null;
624
- let parts = line.split("|").map((part) => part.trim());
625
- if (parts.length < 3 || parts[1] !== "success") return null;
626
- let requestId = parts[0].match(/ccreq:([^.|\s]+)/)?.[1] ?? `${timestamp.getTime()}`, model = normalizeModel(parts[2]);
627
- return model ? { requestId, timestamp, model } : null;
628
- }
629
- function normalizeModel(raw) {
630
- let parts = raw.split("->").map((part) => part.trim()).filter(Boolean);
631
- return parts[parts.length - 1] ?? raw.trim();
632
- }
633
- function extractFileUriPath(line) {
634
- let match = line.match(/file:\/\/\/([^\s.]+(?:\.[^\s.]+)?)/);
635
- if (!match) return null;
636
- try {
637
- return decodeURIComponent(`/${match[1]}`);
638
- } catch {
639
- return `/${match[1]}`;
640
- }
641
- }
642
- async function collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases) {
643
- let content;
644
- try {
645
- content = await readFile5(filePath, "utf-8");
646
- } catch {
647
- return;
648
- }
649
- let session;
650
- try {
651
- session = JSON.parse(content);
652
- } catch {
653
- return;
654
- }
655
- let workspacePath = await readWorkspaceFolderPath(filePath), project = workspacePath ? projectFromPath(workspacePath, projectAliases) : "unknown";
656
- for (let request of session.requests ?? []) {
657
- if (!request.response?.length || request.result?.errorDetails?.responseIsIncomplete) continue;
658
- let model = normalizeWorkspaceModel(request.modelId);
659
- if (!model) continue;
660
- let timestamp = new Date(request.timestamp ?? 0);
661
- if (Number.isNaN(timestamp.getTime())) continue;
662
- let dayMap = grouped.get(dateKey(timestamp));
663
- if (!dayMap) continue;
664
- let dedupeKey = `${request.requestId ?? `${timestamp.getTime()}`}|${timestamp.toISOString()}|${model}|${project}`;
665
- seenEvents.has(dedupeKey) || (seenEvents.add(dedupeKey), accumulate(
666
- dayMap,
667
- `${model}|${project}`,
668
- {
669
- provider: "github",
670
- product: "copilot-vscode",
671
- channel: "ide",
672
- model,
673
- project,
674
- inputTokens: 0,
675
- cachedInputTokens: 0,
676
- cacheWriteTokens: 0,
677
- outputTokens: 0,
678
- reasoningOutputTokens: 0
961
+ };
962
+
963
+ // ../shared/src/pricing/data/moonshot.ts
964
+ var moonshot = {
965
+ "kimi-code": {
966
+ models: {
967
+ "kimi-k2.6": {
968
+ currency: "CNY",
969
+ input_per_million: 6.5,
970
+ cached_input_per_million: 1.1,
971
+ output_per_million: 27
679
972
  },
680
- { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
681
- ));
682
- }
683
- }
684
- async function readWorkspaceFolderPath(sessionFilePath) {
685
- let workspaceJsonPath = join6(dirname(sessionFilePath), "..", "workspace.json"), content;
686
- try {
687
- content = await readFile5(workspaceJsonPath, "utf-8");
688
- } catch {
689
- return null;
973
+ "kimi-k2.5": {
974
+ currency: "CNY",
975
+ input_per_million: 4,
976
+ cached_input_per_million: 0.7,
977
+ output_per_million: 21
978
+ },
979
+ "kimi-k2-0905-preview": {
980
+ currency: "CNY",
981
+ notes: "will be retired 2026-05-25",
982
+ input_per_million: 4,
983
+ cached_input_per_million: 1,
984
+ output_per_million: 16
985
+ },
986
+ "kimi-k2-0711-preview": {
987
+ currency: "CNY",
988
+ notes: "will be retired 2026-05-25",
989
+ input_per_million: 4,
990
+ cached_input_per_million: 1,
991
+ output_per_million: 16
992
+ },
993
+ "kimi-k2-turbo-preview": {
994
+ currency: "CNY",
995
+ notes: "will be retired 2026-05-25",
996
+ input_per_million: 8,
997
+ cached_input_per_million: 1,
998
+ output_per_million: 58
999
+ },
1000
+ "kimi-k2-thinking": {
1001
+ currency: "CNY",
1002
+ input_per_million: 4,
1003
+ cached_input_per_million: 1,
1004
+ output_per_million: 16
1005
+ },
1006
+ "kimi-k2-thinking-turbo": {
1007
+ currency: "CNY",
1008
+ input_per_million: 8,
1009
+ cached_input_per_million: 1,
1010
+ output_per_million: 58
1011
+ },
1012
+ "moonshot-v1-8k": {
1013
+ currency: "CNY",
1014
+ input_per_million: 2,
1015
+ output_per_million: 10
1016
+ },
1017
+ "moonshot-v1-32k": {
1018
+ currency: "CNY",
1019
+ input_per_million: 5,
1020
+ output_per_million: 20
1021
+ },
1022
+ "moonshot-v1-128k": {
1023
+ currency: "CNY",
1024
+ input_per_million: 10,
1025
+ output_per_million: 30
1026
+ },
1027
+ "moonshot-v1-8k-vision-preview": {
1028
+ currency: "CNY",
1029
+ input_per_million: 2,
1030
+ output_per_million: 10
1031
+ },
1032
+ "moonshot-v1-32k-vision-preview": {
1033
+ currency: "CNY",
1034
+ input_per_million: 5,
1035
+ output_per_million: 20
1036
+ },
1037
+ "moonshot-v1-128k-vision-preview": {
1038
+ currency: "CNY",
1039
+ input_per_million: 10,
1040
+ output_per_million: 30
1041
+ }
1042
+ }
690
1043
  }
691
- try {
692
- let raw = JSON.parse(content).folder;
693
- return raw?.startsWith("file:///") ? decodeURIComponent(raw.replace(/^file:\/\//, "")) : null;
694
- } catch {
695
- return null;
1044
+ };
1045
+
1046
+ // ../shared/src/pricing/data/alibaba.ts
1047
+ var alibaba = {
1048
+ "qwen-code": {
1049
+ models: {
1050
+ "qwen3-coder-plus": {
1051
+ currency: "CNY",
1052
+ notes: "tiered by input length",
1053
+ tiers: [
1054
+ { threshold: 32e3, input_per_million: 4, output_per_million: 16 },
1055
+ { threshold: 128e3, input_per_million: 6, output_per_million: 24 },
1056
+ { threshold: 256e3, input_per_million: 10, output_per_million: 40 },
1057
+ { input_per_million: 20, output_per_million: 200 }
1058
+ ]
1059
+ },
1060
+ "qwen3-coder-flash": {
1061
+ currency: "CNY",
1062
+ tiers: [
1063
+ { threshold: 32e3, input_per_million: 1, output_per_million: 4 },
1064
+ { threshold: 128e3, input_per_million: 1.5, output_per_million: 6 },
1065
+ { threshold: 256e3, input_per_million: 2, output_per_million: 8 },
1066
+ { input_per_million: 3, output_per_million: 30 }
1067
+ ]
1068
+ },
1069
+ "qwen-coder-plus": {
1070
+ currency: "CNY",
1071
+ input_per_million: 3.5,
1072
+ output_per_million: 7
1073
+ },
1074
+ "qwen3-max": {
1075
+ currency: "CNY",
1076
+ tiers: [
1077
+ { threshold: 32e3, input_per_million: 2.5, output_per_million: 10 },
1078
+ { threshold: 128e3, input_per_million: 5, output_per_million: 20 },
1079
+ { threshold: 256e3, input_per_million: 10, output_per_million: 100 }
1080
+ ]
1081
+ },
1082
+ "qwen-max": {
1083
+ currency: "CNY",
1084
+ input_per_million: 2.4,
1085
+ output_per_million: 9.6
1086
+ },
1087
+ "qwen-plus": {
1088
+ currency: "CNY",
1089
+ notes: "cache hit \xA50.8/M",
1090
+ cached_input_per_million: 0.8,
1091
+ input_per_million: 2,
1092
+ output_per_million: 8
1093
+ },
1094
+ "qwen-turbo": {
1095
+ currency: "CNY",
1096
+ notes: "cache hit \xA50.3/M",
1097
+ cached_input_per_million: 0.3,
1098
+ input_per_million: 0.6,
1099
+ output_per_million: 3
1100
+ },
1101
+ "qwen3-32b": {
1102
+ currency: "CNY",
1103
+ input_per_million: 2,
1104
+ output_per_million: 8
1105
+ },
1106
+ "qwen3-235b-a22b-thinking-2507": {
1107
+ currency: "CNY",
1108
+ input_per_million: 2,
1109
+ output_per_million: 20
1110
+ },
1111
+ "qwen3-235b-a22b-instruct-2507": {
1112
+ currency: "CNY",
1113
+ input_per_million: 2,
1114
+ output_per_million: 8
1115
+ }
1116
+ }
696
1117
  }
697
- }
698
- function normalizeWorkspaceModel(raw) {
699
- return raw ? raw.replace(/^copilot\//, "").trim() : "";
700
- }
1118
+ };
701
1119
 
702
- // src/scanners/cursor.ts
703
- import { existsSync } from "node:fs";
704
- import { copyFile, mkdtemp, rm } from "node:fs/promises";
705
- import { homedir as homedir6, tmpdir } from "node:os";
706
- import { join as join7, resolve } from "node:path";
707
- var CURSOR_CONFIG_DIR_ENV = "CURSOR_CONFIG_DIR", CURSOR_STATE_DB_PATH_ENV = "CURSOR_STATE_DB_PATH", CURSOR_WEB_BASE_URL_ENV = "CURSOR_WEB_BASE_URL", CURSOR_STATE_DB_RELATIVE = join7("User", "globalStorage", "state.vscdb"), CURSOR_SESSION_COOKIE = "WorkosCursorSessionToken";
708
- function getDefaultDbPath() {
709
- if (process.platform === "darwin")
710
- return join7(homedir6(), "Library", "Application Support", "Cursor", CURSOR_STATE_DB_RELATIVE);
711
- if (process.platform === "win32") {
712
- let appData = process.env.APPDATA?.trim() || join7(homedir6(), "AppData", "Roaming");
713
- return join7(appData, "Cursor", CURSOR_STATE_DB_RELATIVE);
714
- }
715
- let xdg = process.env.XDG_CONFIG_HOME?.trim() || join7(homedir6(), ".config");
716
- return join7(xdg, "Cursor", CURSOR_STATE_DB_RELATIVE);
717
- }
718
- function findDbPath() {
719
- let explicit = process.env[CURSOR_STATE_DB_PATH_ENV]?.trim();
720
- if (explicit) {
721
- let p = resolve(explicit);
722
- return existsSync(p) ? p : null;
1120
+ // ../shared/src/pricing/data/deepseek.ts
1121
+ var deepseek = {
1122
+ "deepseek-chat": {
1123
+ models: {
1124
+ "deepseek-v4-flash": {
1125
+ currency: "USD",
1126
+ input_per_million: 0.14,
1127
+ cached_input_per_million: 28e-4,
1128
+ output_per_million: 0.28
1129
+ },
1130
+ "deepseek-v4-pro": {
1131
+ currency: "USD",
1132
+ notes: "75% off promo until 2026-05-31",
1133
+ input_per_million: 0.435,
1134
+ cached_input_per_million: 3625e-6,
1135
+ output_per_million: 0.87,
1136
+ effective_to: "2026-05-31"
1137
+ },
1138
+ // 兼容别名(chat = v4-flash 非思考,reasoner = v4-flash 思考),按 v4-flash 同价计
1139
+ "deepseek-chat": {
1140
+ currency: "USD",
1141
+ notes: "alias for v4-flash non-thinking",
1142
+ input_per_million: 0.14,
1143
+ cached_input_per_million: 28e-4,
1144
+ output_per_million: 0.28
1145
+ },
1146
+ "deepseek-reasoner": {
1147
+ currency: "USD",
1148
+ notes: "alias for v4-flash thinking",
1149
+ input_per_million: 0.14,
1150
+ cached_input_per_million: 28e-4,
1151
+ output_per_million: 0.28
1152
+ }
1153
+ }
723
1154
  }
724
- let dirs = process.env[CURSOR_CONFIG_DIR_ENV]?.trim(), candidates = dirs ? dirs.split(",").map((v) => {
725
- let r = resolve(v.trim());
726
- return r.endsWith(".vscdb") ? r : join7(r, CURSOR_STATE_DB_RELATIVE);
727
- }) : [getDefaultDbPath()];
728
- for (let c of candidates)
729
- if (existsSync(c)) return c;
730
- return null;
731
- }
732
- function readAuthFromDb(dbPath) {
733
- let { DatabaseSync } = __require("node:sqlite"), db = new DatabaseSync(dbPath, { open: !0 });
734
- try {
735
- let raw = db.prepare("SELECT value FROM ItemTable WHERE key = ? LIMIT 1").get("cursorAuth/accessToken")?.value, token;
736
- return typeof raw == "string" ? token = raw.trim() || void 0 : Buffer.isBuffer(raw) && (token = raw.toString("utf8").trim() || void 0), { accessToken: token };
737
- } finally {
738
- db.close();
1155
+ };
1156
+
1157
+ // ../shared/src/pricing/data/zhipu.ts
1158
+ var zhipu = {
1159
+ "glm-chat": {
1160
+ models: {
1161
+ "glm-5.1": {
1162
+ currency: "CNY",
1163
+ tiers: [
1164
+ { threshold: 32e3, input_per_million: 6, output_per_million: 24, cached_input_per_million: 1.3 },
1165
+ { input_per_million: 8, output_per_million: 28, cached_input_per_million: 2 }
1166
+ ]
1167
+ },
1168
+ "glm-5-turbo": {
1169
+ currency: "CNY",
1170
+ tiers: [
1171
+ { threshold: 32e3, input_per_million: 5, output_per_million: 22, cached_input_per_million: 1.2 },
1172
+ { input_per_million: 7, output_per_million: 26, cached_input_per_million: 1.8 }
1173
+ ]
1174
+ },
1175
+ "glm-5": {
1176
+ currency: "CNY",
1177
+ tiers: [
1178
+ { threshold: 32e3, input_per_million: 4, output_per_million: 18, cached_input_per_million: 1 },
1179
+ { input_per_million: 6, output_per_million: 22, cached_input_per_million: 1.5 }
1180
+ ]
1181
+ },
1182
+ "glm-4.7": {
1183
+ currency: "CNY",
1184
+ notes: "output<200 archetype; >200 doubles output rate",
1185
+ tiers: [
1186
+ { threshold: 32e3, input_per_million: 2, output_per_million: 8, cached_input_per_million: 0.4 },
1187
+ { threshold: 2e5, input_per_million: 4, output_per_million: 16, cached_input_per_million: 0.8 }
1188
+ ]
1189
+ },
1190
+ "glm-4.5-air": {
1191
+ currency: "CNY",
1192
+ tiers: [
1193
+ { threshold: 32e3, input_per_million: 0.8, output_per_million: 2, cached_input_per_million: 0.16 },
1194
+ { threshold: 128e3, input_per_million: 1.2, output_per_million: 8, cached_input_per_million: 0.24 }
1195
+ ]
1196
+ },
1197
+ "glm-4.7-flashx": {
1198
+ currency: "CNY",
1199
+ input_per_million: 0.5,
1200
+ cached_input_per_million: 0.1,
1201
+ output_per_million: 3
1202
+ },
1203
+ "glm-4.7-flash": {
1204
+ currency: "CNY",
1205
+ notes: "free tier",
1206
+ input_per_million: 0,
1207
+ cached_input_per_million: 0,
1208
+ output_per_million: 0
1209
+ },
1210
+ "glm-4-plus": {
1211
+ currency: "CNY",
1212
+ input_per_million: 5,
1213
+ output_per_million: 5
1214
+ },
1215
+ "glm-4-air": {
1216
+ currency: "CNY",
1217
+ input_per_million: 0.5,
1218
+ output_per_million: 0.5
1219
+ },
1220
+ "glm-4-airx": {
1221
+ currency: "CNY",
1222
+ input_per_million: 10,
1223
+ output_per_million: 10
1224
+ },
1225
+ "glm-4-flashx-250414": {
1226
+ currency: "CNY",
1227
+ input_per_million: 0.1,
1228
+ output_per_million: 0.1
1229
+ },
1230
+ "glm-4-long": {
1231
+ currency: "CNY",
1232
+ input_per_million: 1,
1233
+ output_per_million: 1
1234
+ },
1235
+ "glm-4.5": {
1236
+ currency: "CNY",
1237
+ notes: "legacy, 128K context",
1238
+ input_per_million: 4,
1239
+ output_per_million: 16
1240
+ },
1241
+ "glm-4.6": {
1242
+ currency: "CNY",
1243
+ notes: "legacy, 200K context",
1244
+ input_per_million: 4,
1245
+ output_per_million: 16
1246
+ }
1247
+ }
739
1248
  }
740
- }
741
- async function withSnapshot(dbPath, cb) {
742
- let dir = await mkdtemp(join7(tmpdir(), "aiusage-cursor-")), snap = join7(dir, "state.vscdb");
743
- await copyFile(dbPath, snap);
744
- for (let suffix of ["-shm", "-wal"])
745
- existsSync(`${dbPath}${suffix}`) && await copyFile(`${dbPath}${suffix}`, `${snap}${suffix}`);
746
- try {
747
- return cb(snap);
748
- } finally {
749
- await rm(dir, { recursive: !0, force: !0 });
1249
+ };
1250
+
1251
+ // ../shared/src/pricing/data/github.ts
1252
+ var github = {
1253
+ // copilot-vscode 仅事件计数(日志里无 token 数),保留空 models 不算费用
1254
+ "copilot-vscode": { models: {} },
1255
+ "copilot-cli": {
1256
+ models: {
1257
+ "gpt-4o": { currency: "USD", input_per_million: 2.5, cached_input_per_million: 1.25, output_per_million: 10 },
1258
+ "gpt-4o-mini": { currency: "USD", input_per_million: 0.15, cached_input_per_million: 0.075, output_per_million: 0.6 },
1259
+ "claude-sonnet-4": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
1260
+ "claude-sonnet-4-6": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
1261
+ "o3-mini": { currency: "USD", input_per_million: 1.1, cached_input_per_million: 0.55, output_per_million: 4.4 },
1262
+ "gemini-2.0-flash": { currency: "USD", input_per_million: 0.1, cached_input_per_million: 0.025, output_per_million: 0.4 }
1263
+ }
750
1264
  }
751
- }
752
- async function readAuth(dbPath) {
753
- try {
754
- return readAuthFromDb(dbPath);
755
- } catch (err) {
756
- if (err instanceof Error && /database is locked/i.test(err.message))
757
- return withSnapshot(dbPath, (snap) => readAuthFromDb(snap));
758
- throw err;
1265
+ };
1266
+
1267
+ // ../shared/src/pricing/data/sourcegraph.ts
1268
+ var sourcegraph = {
1269
+ amp: {
1270
+ models: {
1271
+ "claude-sonnet-4": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
1272
+ "claude-sonnet-3.7": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
1273
+ "gemini-2.5-pro": { currency: "USD", input_per_million: 1.25, cached_input_per_million: 0.125, output_per_million: 10 }
1274
+ }
759
1275
  }
760
- }
761
- function jwtSub(token) {
762
- let part = token.split(".")[1];
763
- if (!part) return;
764
- let b64 = part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=");
765
- try {
766
- return JSON.parse(Buffer.from(b64, "base64").toString("utf8")).sub?.trim();
767
- } catch {
768
- return;
1276
+ };
1277
+
1278
+ // ../shared/src/pricing/data/placeholders.ts
1279
+ var inflection = {
1280
+ pi: { models: {} }
1281
+ }, cursor = {
1282
+ cursor: { models: {} }
1283
+ }, droid = {
1284
+ droid: { models: {} }
1285
+ }, opencode = {
1286
+ opencode: { models: {} }
1287
+ };
1288
+
1289
+ // ../shared/src/pricing/catalog.ts
1290
+ var PRICING_VERSION = "2026-07-10-gpt-5.6-v1", aliases = {
1291
+ "claude-opus-4-7-20260201": "claude-opus-4-7",
1292
+ "claude-sonnet-4-6-20250301": "claude-sonnet-4-6",
1293
+ "claude-opus-4-6-20250301": "claude-opus-4-6",
1294
+ "claude-haiku-4-5-20251001": "claude-haiku-4-5",
1295
+ "claude-sonnet-4.6": "claude-sonnet-4-6",
1296
+ "gpt-5.6": "gpt-5.6-sol",
1297
+ "codex-auto-review": "gpt-5.4"
1298
+ }, catalog = {
1299
+ version: PRICING_VERSION,
1300
+ // 汇率(1 USD ≈ N CNY)。Worker 启动时可被 env 覆盖。
1301
+ fx: {
1302
+ CNY: 7.2
1303
+ },
1304
+ aliases,
1305
+ providers: {
1306
+ anthropic,
1307
+ openai,
1308
+ google,
1309
+ moonshot,
1310
+ alibaba,
1311
+ deepseek,
1312
+ zhipu,
1313
+ github,
1314
+ sourcegraph,
1315
+ inflection,
1316
+ cursor,
1317
+ droid,
1318
+ opencode
769
1319
  }
1320
+ };
1321
+
1322
+ // ../shared/src/pricing/calculate.ts
1323
+ var ANTHROPIC_FAST_MULTIPLIER = 6, FAST_SUPPORTED = /* @__PURE__ */ new Set([
1324
+ "claude-opus-4-8",
1325
+ "claude-opus-4-7",
1326
+ "claude-opus-4-6"
1327
+ ]), OPENAI_CODEX_TIER_MULTIPLIERS = {
1328
+ "gpt-5.6-sol": 2,
1329
+ "gpt-5.6-terra": 2,
1330
+ "gpt-5.6-luna": 2,
1331
+ "gpt-5.5": 2.5,
1332
+ "gpt-5.4": 2
1333
+ };
1334
+ function splitServiceTierSuffix(model) {
1335
+ return model.endsWith("-priority") ? { baseModel: model.replace(/-priority$/, ""), tier: "priority" } : model.endsWith("-fast") ? { baseModel: model.replace(/-fast$/, ""), tier: "fast" } : { baseModel: model, tier: null };
770
1336
  }
771
- function getWebBaseUrl() {
772
- return (process.env[CURSOR_WEB_BASE_URL_ENV]?.trim() || "https://cursor.com").replace(/\/+$/, "");
1337
+ function getServiceTierMultiplier(provider, product, resolvedModel, tier) {
1338
+ return tier ? provider === "openai" && product === "codex" ? tier === "fast" && resolvedModel.startsWith("gpt-5.6-") ? 1 : OPENAI_CODEX_TIER_MULTIPLIERS[resolvedModel] ?? 1 : tier === "fast" && FAST_SUPPORTED.has(resolvedModel) ? ANTHROPIC_FAST_MULTIPLIER : 1 : 1;
773
1339
  }
774
- async function fetchCsv(accessToken) {
775
- let url = new URL("/api/dashboard/export-usage-events-csv?strategy=tokens", getWebBaseUrl()), sub = jwtSub(accessToken), cookieValues = [accessToken, ...sub ? [`${sub}::${accessToken}`] : []], attempts = [{ Authorization: `Bearer ${accessToken}` }];
776
- for (let cv of cookieValues)
777
- attempts.push({ Cookie: `${CURSOR_SESSION_COOKIE}=${cv}` }), attempts.push({ Authorization: `Bearer ${accessToken}`, Cookie: `${CURSOR_SESSION_COOKIE}=${cv}` });
778
- let failures = [];
779
- for (let headers of attempts) {
780
- let res = await fetch(url, { headers: { Accept: "text/csv,*/*;q=0.8", ...headers } });
781
- if (res.ok) return res.text();
782
- failures.push(`${res.status} ${res.statusText}`);
1340
+ function resolveModelPricing(catalog2, provider, product, model) {
1341
+ let models = catalog2.providers[provider]?.[product]?.models;
1342
+ if (!models) return null;
1343
+ let aliasResolved = catalog2.aliases[model];
1344
+ if (aliasResolved && models[aliasResolved])
1345
+ return { resolvedModel: aliasResolved, pricing: models[aliasResolved], normalized: !1 };
1346
+ if (models[model])
1347
+ return { resolvedModel: model, pricing: models[model], normalized: !1 };
1348
+ for (let knownModel of Object.keys(models).sort((a, b) => b.length - a.length)) {
1349
+ if (!model.startsWith(`${knownModel}-`)) continue;
1350
+ let suffix = model.slice(knownModel.length + 1);
1351
+ if (!/^\d+(?:[-.]\d+)*(?:-\d{6,8})?$/.test(suffix))
1352
+ return { resolvedModel: knownModel, pricing: models[knownModel], normalized: !0 };
783
1353
  }
784
- throw new Error(`Cursor API failed: ${failures.join(", ")}`);
1354
+ return null;
785
1355
  }
786
- function parseCsvLine(line) {
787
- let vals = [], cur = "", inQ = !1;
788
- for (let i = 0; i < line.length; i++) {
789
- let c = line[i];
790
- c === '"' ? inQ && line[i + 1] === '"' ? (cur += '"', i++) : inQ = !inQ : c === "," && !inQ ? (vals.push(cur), cur = "") : cur += c;
1356
+ function selectTier(tiers, totalInputTokens) {
1357
+ for (let i = 0; i < tiers.length; i += 1) {
1358
+ let t2 = tiers[i];
1359
+ if (t2.threshold === void 0 || totalInputTokens <= t2.threshold)
1360
+ return { tier: t2, index: i };
791
1361
  }
792
- return vals.push(cur), vals;
793
- }
794
- function parseNum(v) {
795
- let n = Number((v ?? "").replace(/,/g, "").trim());
796
- return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
1362
+ return { tier: tiers[tiers.length - 1], index: tiers.length - 1 };
797
1363
  }
798
- function parseDateStr(v) {
799
- let s = v?.trim();
800
- if (!s) return null;
801
- if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
802
- let d = new Date(s);
803
- return isNaN(d.getTime()) ? null : dateKey(d);
1364
+ function toUsd(amount, currency, catalog2) {
1365
+ if (currency === "USD") return amount;
1366
+ let rate = catalog2.fx[currency];
1367
+ return rate ? amount / rate : amount;
804
1368
  }
805
- async function scanCursorDates(targetDates) {
806
- let dateSet = new Set(targetDates), empty = new Map(targetDates.map((d) => [d, []])), dbPath = findDbPath();
807
- if (!dbPath) return empty;
808
- let auth;
809
- try {
810
- auth = await readAuth(dbPath);
811
- } catch {
812
- return empty;
813
- }
814
- if (!auth.accessToken) return empty;
815
- let csvText;
816
- try {
817
- csvText = await fetchCsv(auth.accessToken);
818
- } catch {
819
- return empty;
820
- }
821
- let grouped = /* @__PURE__ */ new Map();
822
- for (let d of dateSet) grouped.set(d, /* @__PURE__ */ new Map());
823
- let headers = null;
824
- for (let rawLine of csvText.split(/\r?\n/)) {
825
- let line = rawLine.trim();
826
- if (!line) continue;
827
- let values = parseCsvLine(line);
828
- if (!headers) {
829
- headers = values;
830
- continue;
831
- }
832
- let row = {};
833
- headers.forEach((h, i) => {
834
- row[h] = values[i] ?? "";
835
- });
836
- let date = parseDateStr(row.Date);
837
- if (!date || !dateSet.has(date)) continue;
838
- let rawModel = row.Model?.trim();
839
- if (!rawModel) continue;
840
- let model = normalizeModelName(rawModel);
841
- if (!(parseNum(row["Total Tokens"]) || parseNum(row.Tokens))) continue;
842
- let inputWithCache = parseNum(row["Input (w/ Cache Write)"]), inputWithout = parseNum(row["Input (w/o Cache Write)"]), cacheRead = parseNum(row["Cache Read"]), output = parseNum(row["Output Tokens"]), inputTokens = inputWithCache + inputWithout + cacheRead, dayMap = grouped.get(date), existing = dayMap.get(model);
843
- existing ? (existing.eventCount += 1, existing.inputTokens += inputTokens, existing.cachedInputTokens += cacheRead, existing.cacheWriteTokens += inputWithCache, existing.outputTokens += output) : dayMap.set(model, {
844
- provider: "cursor",
845
- product: "cursor",
846
- channel: "ide",
847
- model,
848
- project: "unknown",
849
- projectDisplay: "unknown",
850
- eventCount: 1,
851
- inputTokens,
852
- cachedInputTokens: cacheRead,
853
- cacheWriteTokens: inputWithCache,
854
- outputTokens: output,
855
- reasoningOutputTokens: 0
856
- });
857
- }
858
- return new Map([...grouped.entries()].map(([d, m]) => [d, [...m.values()]]));
1369
+ function calculateCost(provider, product, model, tokens, options = {}) {
1370
+ let cat = options.catalog ?? catalog;
1371
+ if (tokens.inputTokens + tokens.cachedInputTokens + tokens.cacheWriteTokens + tokens.outputTokens === 0)
1372
+ return { estimatedCostUsd: 0, costStatus: "exact", pricingVersion: cat.version };
1373
+ let { baseModel, tier } = splitServiceTierSuffix(model), resolved = resolveModelPricing(cat, provider, product, baseModel);
1374
+ if (!resolved)
1375
+ return { estimatedCostUsd: 0, costStatus: "unavailable", pricingVersion: cat.version };
1376
+ let { resolvedModel, pricing, normalized } = resolved, costStatus = normalized ? "estimated" : "exact", unit, matchedTierIndex;
1377
+ if (pricing.tiers && pricing.tiers.length > 0) {
1378
+ let totalIn = tokens.inputTokens + tokens.cachedInputTokens + tokens.cacheWriteTokens, requestCount = Math.max(1, Math.floor(options.requestCount ?? 1)), tierInput = totalIn / requestCount, { tier: tier2, index } = selectTier(pricing.tiers, tierInput);
1379
+ unit = tier2, matchedTierIndex = index, requestCount > 1 && (costStatus = "estimated");
1380
+ } else
1381
+ unit = {
1382
+ input_per_million: pricing.input_per_million ?? 0,
1383
+ output_per_million: pricing.output_per_million ?? 0,
1384
+ cached_input_per_million: pricing.cached_input_per_million ?? null,
1385
+ cache_write_per_million: pricing.cache_write_per_million,
1386
+ cache_write_5m_per_million: pricing.cache_write_5m_per_million ?? 0,
1387
+ cache_write_1h_per_million: pricing.cache_write_1h_per_million ?? 0
1388
+ };
1389
+ let cw5Rate = unit.cache_write_5m_per_million ?? pricing.cache_write_5m_per_million ?? 0, cw1hRate = unit.cache_write_1h_per_million ?? pricing.cache_write_1h_per_million ?? 0, hasGenericCacheWriteRate = unit.cache_write_per_million !== void 0 || pricing.cache_write_per_million !== void 0, genericCwRate = unit.cache_write_per_million ?? pricing.cache_write_per_million ?? 0, cachedRate = unit.cached_input_per_million ?? pricing.cached_input_per_million ?? 0, cacheWriteCost = hasGenericCacheWriteRate ? tokens.cacheWriteTokens / 1e6 * genericCwRate : (tokens.cacheWrite5mTokens ?? tokens.cacheWriteTokens) / 1e6 * cw5Rate + (tokens.cacheWrite1hTokens ?? 0) / 1e6 * cw1hRate, raw = tokens.inputTokens / 1e6 * (unit.input_per_million ?? 0) + tokens.cachedInputTokens / 1e6 * (cachedRate ?? 0) + cacheWriteCost + tokens.outputTokens / 1e6 * (unit.output_per_million ?? 0);
1390
+ raw = toUsd(raw, pricing.currency, cat);
1391
+ let finalCost = raw * getServiceTierMultiplier(provider, product, resolvedModel, tier);
1392
+ return {
1393
+ estimatedCostUsd: Math.round(finalCost * 1e4) / 1e4,
1394
+ costStatus,
1395
+ pricingVersion: cat.version,
1396
+ resolvedModel,
1397
+ matchedTierIndex
1398
+ };
859
1399
  }
860
1400
 
861
- // src/scanners/gemini.ts
862
- import { readFile as readFile6 } from "node:fs/promises";
863
- import { basename as basename3, join as join8 } from "node:path";
864
- import { homedir as homedir7 } from "node:os";
865
- async function scanGeminiDates(targetDates, baseDir, projectAliases) {
866
- let dates = new Set(targetDates), dir = baseDir ?? join8(homedir7(), ".gemini", "tmp"), files = await walkFiles(dir, ".json");
867
- if (files.length === 0) return emptyResult(dates);
868
- let grouped = initDateMap(dates), tokenBackedDates = /* @__PURE__ */ new Set();
869
- for (let filePath of files) {
870
- if (basename3(filePath) === "logs.json") continue;
871
- let content;
872
- try {
873
- content = await readFile6(filePath, "utf-8");
874
- } catch {
875
- continue;
876
- }
877
- let session;
878
- try {
879
- session = JSON.parse(content);
880
- } catch {
881
- continue;
882
- }
883
- let messages = session.messages ?? session.history ?? session.data?.messages ?? session.data?.history ?? [], fallbackModel = session.model ?? session.data?.model ?? "unknown", fallbackTs = session.createTime ?? session.startTime ?? session.data?.createTime;
884
- for (let msg of messages) {
885
- let tokens = extractTokens(msg);
886
- if (!tokens) continue;
887
- let model = normalizeModelName(msg.model ?? fallbackModel), ts = parseTs(msg.timestamp) ?? parseTs(msg.createTime) ?? parseTs(fallbackTs);
888
- if (!ts) continue;
889
- let dk = dateKey(ts), dayMap = grouped.get(dk);
890
- dayMap && (tokenBackedDates.add(dk), accumulate(
891
- dayMap,
892
- `${model}|unknown`,
893
- {
894
- provider: "google",
895
- product: "gemini-cli",
896
- channel: "cli",
897
- model,
898
- project: "unknown",
899
- projectDisplay: "unknown",
900
- inputTokens: 0,
901
- cachedInputTokens: 0,
902
- cacheWriteTokens: 0,
903
- outputTokens: 0,
904
- reasoningOutputTokens: 0
905
- },
906
- tokens
907
- ));
908
- }
909
- }
910
- let logFiles = files.filter((filePath) => basename3(filePath) === "logs.json");
911
- for (let filePath of logFiles)
912
- await collectGeminiLogEvents(filePath, grouped, tokenBackedDates);
913
- return finalize(grouped);
914
- }
915
- async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
916
- let content;
917
- try {
918
- content = await readFile6(filePath, "utf-8");
919
- } catch {
920
- return;
921
- }
922
- let rows;
923
- try {
924
- rows = JSON.parse(content);
925
- } catch {
926
- return;
927
- }
928
- if (Array.isArray(rows))
929
- for (let row of rows) {
930
- if (row.type && row.type !== "user") continue;
931
- let ts = parseTs(row.timestamp);
932
- if (!ts) continue;
933
- let dk = dateKey(ts);
934
- if (tokenBackedDates.has(dk)) continue;
935
- let dayMap = grouped.get(dk);
936
- dayMap && accumulate(
937
- dayMap,
938
- "unknown|unknown",
939
- {
940
- provider: "google",
941
- product: "gemini-cli",
942
- channel: "cli",
943
- model: "unknown",
944
- project: "unknown",
945
- inputTokens: 0,
946
- cachedInputTokens: 0,
947
- cacheWriteTokens: 0,
948
- outputTokens: 0,
949
- reasoningOutputTokens: 0
950
- },
951
- { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
952
- );
953
- }
1401
+ // src/scanners/codex.ts
1402
+ var FILE_CONCURRENCY2 = 16, MAX_LINE_BYTES2 = 64 * 1024 * 1024;
1403
+ async function scanCodexDates(targetDates, codexDir, projectAliases) {
1404
+ let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
1405
+ for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
1406
+ let baseDir = codexDir ?? join4(homedir3(), ".codex"), serviceTier = await detectCodexServiceTier(baseDir), sessionFiles = await collectSessionFiles(baseDir);
1407
+ if (sessionFiles.length === 0)
1408
+ return new Map([...targetDateSet].map((targetDate) => [targetDate, []]));
1409
+ let globalSeenSigs = /* @__PURE__ */ new Set();
1410
+ return await runWithConcurrency(sessionFiles, FILE_CONCURRENCY2, async (filePath) => {
1411
+ await processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs, serviceTier);
1412
+ }), new Map(
1413
+ [...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
1414
+ );
954
1415
  }
955
- function extractTokens(msg) {
956
- if (msg.tokens) {
957
- let t2 = msg.tokens, cached2 = t2.cached ?? 0, input = Math.max((t2.input ?? 0) - cached2, 0), thoughts = t2.thoughts ?? 0, output = Math.max((t2.output ?? 0) - thoughts, 0);
958
- return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
959
- }
960
- let u = msg.usage ?? msg.usageMetadata;
961
- if (u) {
962
- let cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
963
- return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
1416
+ async function processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs, serviceTier) {
1417
+ let fh;
1418
+ try {
1419
+ fh = await open2(filePath, "r");
1420
+ } catch {
1421
+ return;
964
1422
  }
965
- return null;
966
- }
967
-
968
- // src/scanners/qwen.ts
969
- import { readFile as readFile7 } from "node:fs/promises";
970
- import { join as join9, basename as basename4, dirname as dirname2 } from "node:path";
971
- import { homedir as homedir8 } from "node:os";
972
- async function scanQwenDates(targetDates, baseDir, projectAliases) {
973
- let dates = new Set(targetDates), dir = baseDir ?? join9(homedir8(), ".qwen", "tmp"), files = await walkFiles(dir, ".jsonl");
974
- if (files.length === 0) return emptyResult(dates);
975
- let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
976
- for (let filePath of files) {
977
- let chatsDir = dirname2(filePath), projectDir = dirname2(chatsDir), projectId = basename4(projectDir), content;
978
- try {
979
- content = await readFile7(filePath, "utf-8");
980
- } catch {
981
- continue;
982
- }
983
- for (let line of content.split(`
984
- `)) {
985
- if (!line.trim()) continue;
986
- let obj;
1423
+ try {
1424
+ let rl = createInterface2({
1425
+ input: fh.createReadStream({ encoding: "utf-8" }),
1426
+ crlfDelay: 1 / 0
1427
+ }), currentModel = "unknown", currentProjectFields = { project: "unknown", projectDisplay: "unknown" }, previousTotal = {};
1428
+ for await (let line of rl) {
1429
+ if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES2) continue;
1430
+ let record;
987
1431
  try {
988
- obj = JSON.parse(line);
1432
+ record = JSON.parse(line);
989
1433
  } catch {
990
1434
  continue;
991
1435
  }
992
- if (obj.type !== "assistant") continue;
993
- let ts = parseTs(obj.timestamp);
994
- if (!ts) continue;
995
- let dk = dateKey(ts), dayMap = grouped.get(dk);
996
- if (!dayMap) continue;
997
- if (obj.uuid) {
998
- if (seen.has(obj.uuid)) continue;
999
- seen.add(obj.uuid);
1000
- }
1001
- let u = obj.usageMetadata;
1002
- if (!u) continue;
1003
- let model = obj.model ?? "unknown", fields = obj.cwd ? resolveProjectFields(obj.cwd, projectAliases) : resolveProjectFields(projectId, projectAliases), cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
1004
- accumulate(
1005
- dayMap,
1006
- `${model}|${fields.project}`,
1007
- {
1008
- provider: "alibaba",
1009
- product: "qwen-code",
1010
- channel: "cli",
1011
- model,
1012
- project: fields.project,
1013
- projectDisplay: fields.projectDisplay,
1014
- projectAlias: fields.projectAlias,
1015
- inputTokens: 0,
1016
- cachedInputTokens: 0,
1017
- cacheWriteTokens: 0,
1018
- outputTokens: 0,
1019
- reasoningOutputTokens: 0
1020
- },
1021
- { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts }
1022
- );
1023
- }
1024
- }
1025
- return finalize(grouped);
1026
- }
1027
-
1028
- // src/scanners/kimi.ts
1029
- import { readFile as readFile8 } from "node:fs/promises";
1030
- import { join as join10, basename as basename5, dirname as dirname3 } from "node:path";
1031
- import { homedir as homedir9 } from "node:os";
1032
- async function scanKimiDates(targetDates, baseDir, projectAliases) {
1033
- let dates = new Set(targetDates), kimiHome = baseDir ?? join10(homedir9(), ".kimi"), sessionsDir = join10(kimiHome, "sessions"), files = await walkFiles(sessionsDir, ".jsonl");
1034
- if (files.length === 0) return emptyResult(dates);
1035
- let workspaceMap = await loadWorkspaceMap(kimiHome), grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
1036
- for (let filePath of files) {
1037
- let sessionDir = dirname3(filePath), hashDir = dirname3(sessionDir), workDirHash = basename5(hashDir), projectFields = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
1038
- try {
1039
- content = await readFile8(filePath, "utf-8");
1040
- } catch {
1041
- continue;
1042
- }
1043
- let currentModel = "unknown";
1044
- for (let line of content.split(`
1045
- `)) {
1046
- if (!line.trim()) continue;
1047
- let obj;
1048
- try {
1049
- obj = JSON.parse(line);
1050
- } catch {
1436
+ if (record.type === "turn_context") {
1437
+ let rawModel = record.payload?.model ?? currentModel;
1438
+ rawModel !== "<synthetic>" && (currentModel = applyCodexServiceTier(normalizeModelName(rawModel), serviceTier)), record.payload?.cwd && (currentProjectFields = resolveProjectFields(record.payload.cwd, projectAliases));
1051
1439
  continue;
1052
1440
  }
1053
- if (obj.payload?.model && (currentModel = obj.payload.model), obj.type !== "StatusUpdate") continue;
1054
- let usage = obj.payload?.token_usage;
1055
- if (!usage) continue;
1056
- let ts = parseTs(obj.timestamp);
1441
+ if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
1442
+ let info = record.payload?.info;
1443
+ if (!info?.total_token_usage) continue;
1444
+ let ts = parseTimestamp2(record.timestamp);
1057
1445
  if (!ts) continue;
1058
- let dk = dateKey(ts), dayMap = grouped.get(dk);
1059
- if (!dayMap) continue;
1060
- let msgId = obj.payload?.message_id;
1061
- if (msgId) {
1062
- if (seen.has(msgId)) continue;
1063
- seen.add(msgId);
1064
- }
1065
- let input = usage.input_other ?? 0, cached2 = usage.input_cache_read ?? 0, output = usage.output ?? 0;
1066
- accumulate(
1067
- dayMap,
1068
- `${currentModel}|${projectFields.project}`,
1069
- {
1070
- provider: "moonshot",
1071
- product: "kimi-code",
1446
+ let usageDate = toDateKey2(ts);
1447
+ if (!targetDateSet.has(usageDate)) continue;
1448
+ let total = info.total_token_usage;
1449
+ if ((total.input_tokens ?? 0) + (total.cached_input_tokens ?? 0) + (total.output_tokens ?? 0) + (total.reasoning_output_tokens ?? 0) + (total.total_tokens ?? 0) === 0) continue;
1450
+ let signature = `${total.input_tokens ?? 0}|${total.cached_input_tokens ?? 0}|${total.output_tokens ?? 0}|${total.reasoning_output_tokens ?? 0}|${total.total_tokens ?? 0}`;
1451
+ if (globalSeenSigs.has(signature)) continue;
1452
+ globalSeenSigs.add(signature);
1453
+ let last = info.last_token_usage ?? {
1454
+ input_tokens: Math.max(0, (total.input_tokens ?? 0) - (previousTotal.input_tokens ?? 0)),
1455
+ cached_input_tokens: Math.max(0, (total.cached_input_tokens ?? 0) - (previousTotal.cached_input_tokens ?? 0)),
1456
+ output_tokens: Math.max(0, (total.output_tokens ?? 0) - (previousTotal.output_tokens ?? 0)),
1457
+ reasoning_output_tokens: Math.max(0, (total.reasoning_output_tokens ?? 0) - (previousTotal.reasoning_output_tokens ?? 0))
1458
+ };
1459
+ previousTotal = total;
1460
+ let nonCachedInput = Math.max(0, (last.input_tokens ?? 0) - (last.cached_input_tokens ?? 0)), cachedInput = last.cached_input_tokens ?? 0, output = last.output_tokens ?? 0, eventCost = calculateCost("openai", "codex", currentModel, {
1461
+ inputTokens: nonCachedInput,
1462
+ cachedInputTokens: cachedInput,
1463
+ cacheWriteTokens: 0,
1464
+ outputTokens: output
1465
+ }), exactEventCost = eventCost.costStatus === "exact" ? eventCost.estimatedCostUsd : void 0, grouped = groupedByDate.get(usageDate);
1466
+ if (!grouped) continue;
1467
+ let key = `${currentModel}|${currentProjectFields.project}`, existing = grouped.get(key);
1468
+ if (existing)
1469
+ existing.eventCount += 1, existing.inputTokens += nonCachedInput, existing.cachedInputTokens += cachedInput, existing.outputTokens += output, existing.reasoningOutputTokens += last.reasoning_output_tokens ?? 0, exactEventCost !== void 0 && (existing.costUSD = (existing.costUSD ?? 0) + exactEventCost, existing.pricingVersion = eventCost.pricingVersion);
1470
+ else {
1471
+ let breakdown = {
1472
+ provider: "openai",
1473
+ product: "codex",
1072
1474
  channel: "cli",
1073
1475
  model: currentModel,
1074
- project: projectFields.project,
1075
- projectDisplay: projectFields.projectDisplay,
1076
- projectAlias: projectFields.projectAlias,
1077
- inputTokens: 0,
1078
- cachedInputTokens: 0,
1476
+ project: currentProjectFields.project,
1477
+ projectDisplay: currentProjectFields.projectDisplay,
1478
+ projectAlias: currentProjectFields.projectAlias,
1479
+ eventCount: 1,
1480
+ inputTokens: nonCachedInput,
1481
+ cachedInputTokens: cachedInput,
1079
1482
  cacheWriteTokens: 0,
1080
- outputTokens: 0,
1081
- reasoningOutputTokens: 0
1082
- },
1083
- { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
1084
- );
1085
- }
1086
- }
1087
- return finalize(grouped);
1088
- }
1089
- function resolveKimiProject(hash, workspaceMap, aliases2) {
1090
- let wsPath = workspaceMap.get(hash);
1091
- return wsPath ? resolveProjectFields(wsPath, aliases2) : resolveProjectFields(hash, aliases2);
1092
- }
1093
- async function loadWorkspaceMap(kimiHome) {
1094
- let map = /* @__PURE__ */ new Map();
1095
- try {
1096
- let raw = await readFile8(join10(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
1097
- if (config.workspaces)
1098
- for (let [hash, info] of Object.entries(config.workspaces))
1099
- info.path && map.set(hash, info.path);
1100
- } catch {
1101
- }
1102
- return map;
1103
- }
1104
-
1105
- // src/scanners/amp.ts
1106
- import { readFile as readFile9 } from "node:fs/promises";
1107
- import { join as join11 } from "node:path";
1108
- import { homedir as homedir10 } from "node:os";
1109
- function resolveAmpDir(baseDir) {
1110
- if (baseDir) return baseDir;
1111
- let ampDataDir = process.env.AMP_DATA_DIR;
1112
- if (ampDataDir) return join11(ampDataDir, "threads");
1113
- let xdgDataHome = process.env.XDG_DATA_HOME;
1114
- return xdgDataHome ? join11(xdgDataHome, "amp", "threads") : join11(homedir10(), ".local", "share", "amp", "threads");
1115
- }
1116
- async function scanAmpDates(targetDates, baseDir, _projectAliases) {
1117
- let dates = new Set(targetDates), dir = resolveAmpDir(baseDir), threadFiles = (await walkFiles(dir, ".json")).filter((f) => {
1118
- let name = f.split("/").pop() ?? "";
1119
- return name.startsWith("T-") && name.endsWith(".json");
1120
- });
1121
- if (threadFiles.length === 0) return emptyResult(dates);
1122
- let grouped = initDateMap(dates);
1123
- for (let filePath of threadFiles) {
1124
- let raw;
1125
- try {
1126
- raw = await readFile9(filePath, "utf-8");
1127
- } catch {
1128
- continue;
1129
- }
1130
- let thread;
1131
- try {
1132
- thread = JSON.parse(raw);
1133
- } catch {
1134
- continue;
1135
- }
1136
- let ledgerEvents = thread.usageLedger?.events;
1137
- Array.isArray(ledgerEvents) && ledgerEvents.length > 0 ? processLedger(thread, ledgerEvents, dates, grouped) : processMessages(thread, dates, grouped);
1138
- }
1139
- return finalize(grouped);
1140
- }
1141
- function getMessageByKey(messages, key) {
1142
- if (messages) {
1143
- if (Array.isArray(messages)) {
1144
- let idx = parseInt(key, 10);
1145
- return isNaN(idx) ? void 0 : messages[idx];
1483
+ outputTokens: output,
1484
+ reasoningOutputTokens: last.reasoning_output_tokens ?? 0
1485
+ };
1486
+ exactEventCost !== void 0 && (breakdown.costUSD = exactEventCost, breakdown.pricingVersion = eventCost.pricingVersion), grouped.set(key, breakdown);
1487
+ }
1146
1488
  }
1147
- return messages[key];
1148
- }
1149
- }
1150
- function processLedger(thread, events, dates, grouped) {
1151
- for (let event of events) {
1152
- let ts = parseTs(event.timestamp);
1153
- if (!ts) continue;
1154
- let dk = dateKey(ts), dayMap = grouped.get(dk);
1155
- if (!dayMap) continue;
1156
- let model = event.model ?? "unknown", input = event.tokens?.input ?? 0, output = event.tokens?.output ?? 0, cached2 = 0;
1157
- event.toMessageId && (cached2 = getMessageByKey(thread.messages, event.toMessageId)?.usage?.cacheReadInputTokens ?? 0), accumulate(
1158
- dayMap,
1159
- `${model}|unknown`,
1160
- {
1161
- provider: "sourcegraph",
1162
- product: "amp",
1163
- channel: "cli",
1164
- model,
1165
- project: "unknown",
1166
- projectDisplay: "unknown",
1167
- inputTokens: 0,
1168
- cachedInputTokens: 0,
1169
- cacheWriteTokens: 0,
1170
- outputTokens: 0,
1171
- reasoningOutputTokens: 0
1172
- },
1173
- { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
1174
- );
1489
+ } finally {
1490
+ await fh.close();
1175
1491
  }
1176
1492
  }
1177
- function processMessages(thread, dates, grouped) {
1178
- let msgs2 = thread.messages;
1179
- if (!msgs2) return;
1180
- let entries = Array.isArray(msgs2) ? msgs2 : Object.values(msgs2);
1181
- for (let msg of entries) {
1182
- let usage = msg.usage;
1183
- if (!usage) continue;
1184
- let ts = parseTs(msg.timestamp ?? thread.created);
1185
- if (!ts) continue;
1186
- let dk = dateKey(ts), dayMap = grouped.get(dk);
1187
- if (!dayMap) continue;
1188
- let model = msg.model ?? "unknown", input = usage.inputTokens ?? 0, output = usage.outputTokens ?? 0, cached2 = usage.cacheReadInputTokens ?? 0;
1189
- accumulate(
1190
- dayMap,
1191
- `${model}|unknown`,
1192
- {
1193
- provider: "sourcegraph",
1194
- product: "amp",
1195
- channel: "cli",
1196
- model,
1197
- project: "unknown",
1198
- projectDisplay: "unknown",
1199
- inputTokens: 0,
1200
- cachedInputTokens: 0,
1201
- cacheWriteTokens: 0,
1202
- outputTokens: 0,
1203
- reasoningOutputTokens: 0
1204
- },
1205
- { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
1206
- );
1493
+ async function collectSessionFiles(baseDir) {
1494
+ let paths = [], archivedDir = join4(baseDir, "archived_sessions");
1495
+ try {
1496
+ let files = await readdir4(archivedDir);
1497
+ for (let f of files)
1498
+ f.endsWith(".jsonl") && paths.push(join4(archivedDir, f));
1499
+ } catch {
1207
1500
  }
1501
+ let sessionsDir = join4(baseDir, "sessions");
1502
+ return await walkDir(sessionsDir, paths), paths;
1208
1503
  }
1209
-
1210
- // src/scanners/droid.ts
1211
- import { readFile as readFile10 } from "node:fs/promises";
1212
- import { join as join12, dirname as dirname4, basename as basename6 } from "node:path";
1213
- import { homedir as homedir11 } from "node:os";
1214
- function extractProjectFromSlug(dirPath) {
1215
- let parts = basename6(dirPath).split("-").filter(Boolean);
1216
- return parts[parts.length - 1] || "unknown";
1504
+ async function detectCodexServiceTier(baseDir) {
1505
+ let config = "";
1506
+ try {
1507
+ config = await readFile3(join4(baseDir, "config.toml"), "utf-8");
1508
+ } catch {
1509
+ return null;
1510
+ }
1511
+ let serviceTier = config.match(/^\s*service_tier\s*=\s*["']([^"']+)["']/m)?.[1]?.trim().toLowerCase();
1512
+ return serviceTier === "priority" ? "priority" : serviceTier === "fast" || config.match(/^\s*fast_mode\s*=\s*(true|false)\s*$/m)?.[1] === "true" ? "fast" : null;
1217
1513
  }
1218
- async function scanDroidDates(targetDates, baseDir, projectAliases) {
1219
- let dates = new Set(targetDates), dir = baseDir ?? join12(homedir11(), ".factory", "sessions"), files = await walkFiles(dir, ".jsonl");
1220
- if (files.length === 0) return emptyResult(dates);
1221
- let grouped = initDateMap(dates);
1222
- for (let jsonlPath of files) {
1223
- let content;
1224
- try {
1225
- content = await readFile10(jsonlPath, "utf-8");
1226
- } catch {
1227
- continue;
1228
- }
1229
- let firstLine = content.split(`
1230
- `).find((l) => l.trim());
1231
- if (!firstLine) continue;
1232
- let firstObj;
1233
- try {
1234
- firstObj = JSON.parse(firstLine);
1235
- } catch {
1236
- continue;
1237
- }
1238
- let ts = parseTs(firstObj.timestamp);
1239
- if (!ts) continue;
1240
- let dk = dateKey(ts), dayMap = grouped.get(dk);
1241
- if (!dayMap) continue;
1242
- let sessionDir = dirname4(jsonlPath), jsonlName = basename6(jsonlPath, ".jsonl"), settingsPath = join12(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
1243
- try {
1244
- settingsRaw = await readFile10(settingsPath, "utf-8");
1245
- } catch {
1246
- continue;
1247
- }
1248
- let settings;
1249
- try {
1250
- settings = JSON.parse(settingsRaw);
1251
- } catch {
1252
- continue;
1253
- }
1254
- let usage = settings.tokenUsage;
1255
- if (!usage) continue;
1256
- let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, rawOutput = usage.outputTokens ?? 0, thinking = usage.thinkingTokens ?? 0, input = Math.max(rawInput - cacheRead, 0), output = Math.max(rawOutput - thinking, 0), model = settings.model ?? "unknown", rawProject = extractProjectFromSlug(sessionDir), alias = projectAliases?.[rawProject], project = alias ?? rawProject;
1257
- accumulate(
1258
- dayMap,
1259
- `${model}|${project}`,
1260
- {
1261
- provider: "droid",
1262
- product: "droid",
1263
- channel: "cli",
1264
- model,
1265
- project,
1266
- projectDisplay: rawProject,
1267
- projectAlias: alias,
1268
- inputTokens: 0,
1269
- cachedInputTokens: 0,
1270
- cacheWriteTokens: 0,
1271
- outputTokens: 0,
1272
- reasoningOutputTokens: 0
1273
- },
1274
- { input, cached: cacheRead, cacheWrite: 0, output, reasoning: thinking }
1275
- );
1514
+ function applyCodexServiceTier(model, serviceTier) {
1515
+ if (!serviceTier || model.endsWith("-fast") || model.endsWith("-priority")) return model;
1516
+ let supportsFast = model === "gpt-5.5" || model === "gpt-5.4";
1517
+ return serviceTier === "fast" && supportsFast || serviceTier === "priority" && (model === "gpt-5.6" || model === "gpt-5.6-sol" || model === "gpt-5.6-terra" || model === "gpt-5.6-luna" || supportsFast) ? `${model}-${serviceTier}` : model;
1518
+ }
1519
+ async function walkDir(dir, result) {
1520
+ let entries;
1521
+ try {
1522
+ entries = await readdir4(dir, { withFileTypes: !0 });
1523
+ } catch {
1524
+ return;
1525
+ }
1526
+ for (let entry of entries) {
1527
+ let fullPath = join4(dir, entry.name);
1528
+ entry.isDirectory() ? await walkDir(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
1276
1529
  }
1277
- return finalize(grouped);
1278
1530
  }
1279
-
1280
- // src/scanners/opencode.ts
1281
- import { readFile as readFile11 } from "node:fs/promises";
1282
- import { homedir as homedir12 } from "node:os";
1283
- async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
1284
- let dates = new Set(targetDates), dir = baseDir ?? `${homedir12()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
1285
- if (files.length === 0) return emptyResult(dates);
1286
- let grouped = initDateMap(dates);
1287
- for (let filePath of files) {
1288
- let raw;
1289
- try {
1290
- raw = await readFile11(filePath, "utf-8");
1291
- } catch {
1292
- continue;
1293
- }
1294
- let msg;
1295
- try {
1296
- msg = JSON.parse(raw);
1297
- } catch {
1298
- continue;
1299
- }
1300
- let tokens = msg.tokens;
1301
- if (!tokens) continue;
1302
- let input = tokens.input ?? 0, output = tokens.output ?? 0;
1303
- if (input === 0 && output === 0) continue;
1304
- let ts = parseTs(msg.time?.created);
1305
- if (!ts) continue;
1306
- let dk = dateKey(ts), dayMap = grouped.get(dk);
1307
- if (!dayMap) continue;
1308
- let model = msg.modelID ?? "unknown", cached2 = tokens.cache?.read ?? 0, reasoning = tokens.reasoning ?? 0, rootPath = msg.path?.root, fields = rootPath ? resolveProjectFields(rootPath, projectAliases) : { project: "unknown", projectDisplay: "unknown" };
1309
- accumulate(
1310
- dayMap,
1311
- `${model}|${fields.project}`,
1312
- {
1313
- provider: "opencode",
1314
- product: "opencode",
1315
- channel: "cli",
1316
- model,
1317
- project: fields.project,
1318
- projectDisplay: fields.projectDisplay,
1319
- projectAlias: fields.projectAlias,
1320
- inputTokens: 0,
1321
- cachedInputTokens: 0,
1322
- cacheWriteTokens: 0,
1323
- outputTokens: 0,
1324
- reasoningOutputTokens: 0
1325
- },
1326
- { input, cached: cached2, cacheWrite: 0, output, reasoning }
1327
- );
1531
+ function parseTimestamp2(value) {
1532
+ if (!value) return null;
1533
+ try {
1534
+ let d = new Date(value);
1535
+ return isNaN(d.getTime()) ? null : d;
1536
+ } catch {
1537
+ return null;
1328
1538
  }
1329
- return finalize(grouped);
1539
+ }
1540
+ function toDateKey2(date) {
1541
+ let year = date.getFullYear(), month = String(date.getMonth() + 1).padStart(2, "0"), day = String(date.getDate()).padStart(2, "0");
1542
+ return `${year}-${month}-${day}`;
1330
1543
  }
1331
1544
 
1332
- // src/scanners/pi.ts
1333
- import { readFile as readFile12 } from "node:fs/promises";
1334
- import { join as join13, basename as basename7, dirname as dirname5 } from "node:path";
1335
- import { homedir as homedir13 } from "node:os";
1336
- async function scanPiDates(targetDates, baseDir, projectAliases) {
1337
- let dates = new Set(targetDates), sessionsDir = baseDir ?? getSessionsDir(), files = await walkFiles(sessionsDir, ".jsonl");
1545
+ // src/scanners/copilot.ts
1546
+ import { readFile as readFile4 } from "node:fs/promises";
1547
+ import { join as join5 } from "node:path";
1548
+ import { homedir as homedir4 } from "node:os";
1549
+ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
1550
+ let dates = new Set(targetDates), dir = baseDir ?? join5(homedir4(), ".copilot", "session-state"), files = await walkFiles(dir, ".jsonl");
1338
1551
  if (files.length === 0) return emptyResult(dates);
1339
- let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
1552
+ let grouped = initDateMap(dates);
1340
1553
  for (let filePath of files) {
1341
1554
  let content;
1342
1555
  try {
1343
- content = await readFile12(filePath, "utf-8");
1556
+ content = await readFile4(filePath, "utf-8");
1344
1557
  } catch {
1345
1558
  continue;
1346
1559
  }
1347
- let parentDir = dirname5(filePath), encodedCwd = basename7(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(encodedCwd) };
1348
- for (let line of content.split(`
1349
- `)) {
1560
+ let sessionProjectFields = { project: "unknown", projectDisplay: "unknown" }, lines = content.split(`
1561
+ `);
1562
+ for (let line of lines) {
1350
1563
  if (!line.trim()) continue;
1351
1564
  let obj;
1352
1565
  try {
@@ -1354,1158 +1567,1088 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
1354
1567
  } catch {
1355
1568
  continue;
1356
1569
  }
1357
- if (obj.type === "session" && obj.cwd) {
1358
- sessionProjectFields = resolveProjectFields(obj.cwd, projectAliases);
1359
- continue;
1570
+ if (obj.type === "session.start" || obj.type === "session.resume") {
1571
+ let ctx = obj.data?.context, raw = ctx?.gitRoot ?? ctx?.cwd;
1572
+ raw && (sessionProjectFields = resolveProjectFields(raw, projectAliases));
1360
1573
  }
1361
- if (obj.type !== "message") continue;
1362
- let msg = obj.message;
1363
- if (!msg || msg.role !== "assistant") continue;
1364
- let usage = msg.usage;
1365
- if (!usage || usage.input == null && usage.output == null) continue;
1574
+ if (obj.type !== "session.shutdown") continue;
1366
1575
  let ts = parseTs(obj.timestamp);
1367
1576
  if (!ts) continue;
1368
1577
  let dk = dateKey(ts), dayMap = grouped.get(dk);
1369
1578
  if (!dayMap) continue;
1370
- if (obj.id) {
1371
- if (seen.has(obj.id)) continue;
1372
- seen.add(obj.id);
1373
- }
1374
- let model = msg.model ?? "unknown", input = usage.input ?? 0, cached2 = usage.cacheRead ?? 0, output = usage.output ?? 0;
1375
- accumulate(
1579
+ let metrics = obj.data?.modelMetrics;
1580
+ if (metrics)
1581
+ for (let [model, entry] of Object.entries(metrics)) {
1582
+ let usage = entry.usage;
1583
+ if (!usage) continue;
1584
+ let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, output = usage.outputTokens ?? 0, input = Math.max(rawInput - cacheRead, 0);
1585
+ accumulate(
1586
+ dayMap,
1587
+ `${model}|${sessionProjectFields.project}`,
1588
+ {
1589
+ provider: "github",
1590
+ product: "copilot-cli",
1591
+ channel: "cli",
1592
+ model,
1593
+ project: sessionProjectFields.project,
1594
+ projectDisplay: sessionProjectFields.projectDisplay,
1595
+ projectAlias: sessionProjectFields.projectAlias,
1596
+ inputTokens: 0,
1597
+ cachedInputTokens: 0,
1598
+ cacheWriteTokens: 0,
1599
+ outputTokens: 0,
1600
+ reasoningOutputTokens: 0
1601
+ },
1602
+ { input, cached: cacheRead, cacheWrite: 0, output, reasoning: 0 }
1603
+ );
1604
+ }
1605
+ }
1606
+ }
1607
+ return finalize(grouped);
1608
+ }
1609
+
1610
+ // src/scanners/copilot-vscode.ts
1611
+ import { readFile as readFile5 } from "node:fs/promises";
1612
+ import { basename as basename2, dirname, join as join6 } from "node:path";
1613
+ import { homedir as homedir5 } from "node:os";
1614
+ async function scanCopilotVscodeDates(targetDates, baseDir, projectAliases, workspaceStorageDir) {
1615
+ let dates = new Set(targetDates), dir = baseDir ?? join6(homedir5(), "Library", "Application Support", "Code", "logs"), workspaceDir = workspaceStorageDir ?? join6(homedir5(), "Library", "Application Support", "Code", "User", "workspaceStorage"), logFiles = (await walkFiles(dir, ".log")).filter((filePath) => basename2(filePath) === "GitHub Copilot Chat.log"), sessionFiles = (await walkFiles(workspaceDir, ".json")).filter((filePath) => filePath.includes("/chatSessions/"));
1616
+ if (logFiles.length === 0 && sessionFiles.length === 0) return emptyResult(dates);
1617
+ let grouped = initDateMap(dates), seenEvents = /* @__PURE__ */ new Set();
1618
+ for (let filePath of logFiles) {
1619
+ let content;
1620
+ try {
1621
+ content = await readFile5(filePath, "utf-8");
1622
+ } catch {
1623
+ continue;
1624
+ }
1625
+ let sessionProject = "unknown";
1626
+ for (let line of content.split(`
1627
+ `)) {
1628
+ if (!line.trim()) continue;
1629
+ let projectPath = extractFileUriPath(line);
1630
+ projectPath && (sessionProject = projectFromPath(projectPath, projectAliases));
1631
+ let event = extractSuccessEvent(line);
1632
+ if (!event) continue;
1633
+ let dayMap = grouped.get(dateKey(event.timestamp));
1634
+ if (!dayMap) continue;
1635
+ let dedupeKey = `${event.requestId}|${event.timestamp.toISOString()}|${event.model}|${sessionProject}`;
1636
+ seenEvents.has(dedupeKey) || (seenEvents.add(dedupeKey), accumulate(
1376
1637
  dayMap,
1377
- `${model}|${sessionProjectFields.project}`,
1638
+ `${event.model}|${sessionProject}`,
1378
1639
  {
1379
- provider: "inflection",
1380
- product: "pi",
1381
- channel: "cli",
1382
- model,
1383
- project: sessionProjectFields.project,
1384
- projectDisplay: sessionProjectFields.projectDisplay,
1385
- projectAlias: sessionProjectFields.projectAlias,
1640
+ provider: "github",
1641
+ product: "copilot-vscode",
1642
+ channel: "ide",
1643
+ model: event.model,
1644
+ project: sessionProject,
1386
1645
  inputTokens: 0,
1387
1646
  cachedInputTokens: 0,
1388
1647
  cacheWriteTokens: 0,
1389
1648
  outputTokens: 0,
1390
1649
  reasoningOutputTokens: 0
1391
1650
  },
1392
- { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
1393
- );
1651
+ { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
1652
+ ));
1394
1653
  }
1395
1654
  }
1655
+ for (let filePath of sessionFiles)
1656
+ await collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases);
1396
1657
  return finalize(grouped);
1397
1658
  }
1398
- function getSessionsDir() {
1399
- let envDir = process.env.PI_CODING_AGENT_DIR;
1400
- return envDir ? join13(envDir, "sessions") : join13(homedir13(), ".pi", "agent", "sessions");
1659
+ function extractSuccessEvent(line) {
1660
+ if (!line.includes("ccreq:") || !line.includes("| success |")) return null;
1661
+ let timestampMatch = line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)/);
1662
+ if (!timestampMatch) return null;
1663
+ let timestamp = new Date(timestampMatch[1].replace(" ", "T"));
1664
+ if (Number.isNaN(timestamp.getTime())) return null;
1665
+ let parts = line.split("|").map((part) => part.trim());
1666
+ if (parts.length < 3 || parts[1] !== "success") return null;
1667
+ let requestId = parts[0].match(/ccreq:([^.|\s]+)/)?.[1] ?? `${timestamp.getTime()}`, model = normalizeModel(parts[2]);
1668
+ return model ? { requestId, timestamp, model } : null;
1401
1669
  }
1402
- function extractProjectFromEncoded(encoded) {
1403
- let parts = encoded.split("-").filter(Boolean);
1404
- return parts.length > 0 ? parts[parts.length - 1] : "unknown";
1670
+ function normalizeModel(raw) {
1671
+ let parts = raw.split("->").map((part) => part.trim()).filter(Boolean);
1672
+ return parts[parts.length - 1] ?? raw.trim();
1405
1673
  }
1406
-
1407
- // src/scan.ts
1408
- async function scanDate(targetDate, options = {}) {
1409
- let [result] = await scanDates([targetDate], options);
1410
- return result ?? {
1411
- usageDate: targetDate,
1412
- breakdowns: [],
1413
- totals: createEmptyTotals()
1414
- };
1674
+ function extractFileUriPath(line) {
1675
+ let match = line.match(/file:\/\/\/([^\s.]+(?:\.[^\s.]+)?)/);
1676
+ if (!match) return null;
1677
+ try {
1678
+ return decodeURIComponent(`/${match[1]}`);
1679
+ } catch {
1680
+ return `/${match[1]}`;
1681
+ }
1415
1682
  }
1416
- async function scanDates(targetDates, options = {}) {
1417
- let uniqueDates = [...new Set(targetDates)];
1418
- if (uniqueDates.length === 0) return [];
1419
- let scanners = [
1420
- scanAntigravityDates(uniqueDates),
1421
- scanClaudeDates(uniqueDates, void 0, options.projectAliases),
1422
- scanCodexDates(uniqueDates, void 0, options.projectAliases),
1423
- scanCopilotDates(uniqueDates, void 0, options.projectAliases),
1424
- scanCopilotVscodeDates(uniqueDates, void 0, options.projectAliases),
1425
- scanCursorDates(uniqueDates),
1426
- scanGeminiDates(uniqueDates, void 0, options.projectAliases),
1427
- scanQwenDates(uniqueDates, void 0, options.projectAliases),
1428
- scanKimiDates(uniqueDates, void 0, options.projectAliases),
1429
- scanAmpDates(uniqueDates, void 0, options.projectAliases),
1430
- scanDroidDates(uniqueDates, void 0, options.projectAliases),
1431
- scanOpencodeDates(uniqueDates, void 0, options.projectAliases),
1432
- scanPiDates(uniqueDates, void 0, options.projectAliases)
1433
- ], results = await Promise.all(scanners);
1434
- return uniqueDates.map((usageDate) => {
1435
- let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []), totals = breakdowns.reduce(
1436
- (acc, b) => ({
1437
- eventCount: acc.eventCount + b.eventCount,
1438
- inputTokens: acc.inputTokens + b.inputTokens,
1439
- cachedInputTokens: acc.cachedInputTokens + b.cachedInputTokens,
1440
- cacheWriteTokens: acc.cacheWriteTokens + b.cacheWriteTokens,
1441
- outputTokens: acc.outputTokens + b.outputTokens,
1442
- reasoningOutputTokens: acc.reasoningOutputTokens + b.reasoningOutputTokens
1443
- }),
1444
- createEmptyTotals()
1445
- );
1446
- return { usageDate, breakdowns, totals };
1447
- });
1683
+ async function collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases) {
1684
+ let content;
1685
+ try {
1686
+ content = await readFile5(filePath, "utf-8");
1687
+ } catch {
1688
+ return;
1689
+ }
1690
+ let session;
1691
+ try {
1692
+ session = JSON.parse(content);
1693
+ } catch {
1694
+ return;
1695
+ }
1696
+ let workspacePath = await readWorkspaceFolderPath(filePath), project = workspacePath ? projectFromPath(workspacePath, projectAliases) : "unknown";
1697
+ for (let request of session.requests ?? []) {
1698
+ if (!request.response?.length || request.result?.errorDetails?.responseIsIncomplete) continue;
1699
+ let model = normalizeWorkspaceModel(request.modelId);
1700
+ if (!model) continue;
1701
+ let timestamp = new Date(request.timestamp ?? 0);
1702
+ if (Number.isNaN(timestamp.getTime())) continue;
1703
+ let dayMap = grouped.get(dateKey(timestamp));
1704
+ if (!dayMap) continue;
1705
+ let dedupeKey = `${request.requestId ?? `${timestamp.getTime()}`}|${timestamp.toISOString()}|${model}|${project}`;
1706
+ seenEvents.has(dedupeKey) || (seenEvents.add(dedupeKey), accumulate(
1707
+ dayMap,
1708
+ `${model}|${project}`,
1709
+ {
1710
+ provider: "github",
1711
+ product: "copilot-vscode",
1712
+ channel: "ide",
1713
+ model,
1714
+ project,
1715
+ inputTokens: 0,
1716
+ cachedInputTokens: 0,
1717
+ cacheWriteTokens: 0,
1718
+ outputTokens: 0,
1719
+ reasoningOutputTokens: 0
1720
+ },
1721
+ { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
1722
+ ));
1723
+ }
1448
1724
  }
1449
- function createEmptyTotals() {
1450
- return {
1451
- eventCount: 0,
1452
- inputTokens: 0,
1453
- cachedInputTokens: 0,
1454
- cacheWriteTokens: 0,
1455
- outputTokens: 0,
1456
- reasoningOutputTokens: 0
1457
- };
1725
+ async function readWorkspaceFolderPath(sessionFilePath) {
1726
+ let workspaceJsonPath = join6(dirname(sessionFilePath), "..", "workspace.json"), content;
1727
+ try {
1728
+ content = await readFile5(workspaceJsonPath, "utf-8");
1729
+ } catch {
1730
+ return null;
1731
+ }
1732
+ try {
1733
+ let raw = JSON.parse(content).folder;
1734
+ return raw?.startsWith("file:///") ? decodeURIComponent(raw.replace(/^file:\/\//, "")) : null;
1735
+ } catch {
1736
+ return null;
1737
+ }
1458
1738
  }
1459
-
1460
- // src/scanners/anthropic-admin-api.ts
1461
- var ADMIN_API_BASE = "https://api.anthropic.com", USAGE_ENDPOINT = "/v1/organizations/usage_report/messages", MAX_DAYS_PER_REQUEST = 31;
1462
- async function scanAnthropicApiDates(targetDates, adminApiKey) {
1463
- if (!targetDates.length || !adminApiKey)
1464
- return new Map(targetDates.map((d) => [d, []]));
1465
- let sorted = [...new Set(targetDates)].sort(), grouped = new Map(sorted.map((d) => [d, []])), chunks = chunkDateRange(sorted[0], sorted[sorted.length - 1]);
1466
- for (let { startingAt, endingAt } of chunks)
1467
- await fetchAndMerge(startingAt, endingAt, adminApiKey, sorted, grouped);
1468
- return grouped;
1739
+ function normalizeWorkspaceModel(raw) {
1740
+ return raw ? raw.replace(/^copilot\//, "").trim() : "";
1469
1741
  }
1470
- async function fetchAndMerge(startingAt, endingAt, adminApiKey, targetDates, grouped) {
1471
- let nextPage = null;
1472
- do {
1473
- let url = buildUrl(startingAt, endingAt, nextPage), resp;
1474
- try {
1475
- resp = await fetch(url, {
1476
- headers: {
1477
- "x-api-key": adminApiKey,
1478
- "anthropic-version": "2023-06-01"
1479
- }
1480
- });
1481
- } catch (err) {
1482
- throw new Error(`Anthropic Admin API request failed: ${err}`);
1483
- }
1484
- if (!resp.ok) {
1485
- let body = await resp.text().catch(() => "");
1486
- throw new Error(`Anthropic Admin API error ${resp.status}: ${body}`);
1487
- }
1488
- let data = await resp.json();
1489
- for (let bucket of data.data) {
1490
- let date = bucket.starting_at.slice(0, 10);
1491
- if (!targetDates.includes(date)) continue;
1492
- let breakdowns = grouped.get(date);
1493
- for (let result of bucket.results) {
1494
- if (!result.model) continue;
1495
- let model = normalizeModelName(result.model), inputTokens = result.uncached_input_tokens ?? 0, cachedInputTokens = result.cache_read_input_tokens ?? 0, cacheWrite5m = result.cache_creation?.ephemeral_5m_input_tokens ?? 0, cacheWrite1h = result.cache_creation?.ephemeral_1h_input_tokens ?? 0, cacheWriteTokens = cacheWrite5m + cacheWrite1h, outputTokens = result.output_tokens ?? 0;
1496
- if (inputTokens + outputTokens + cachedInputTokens + cacheWriteTokens === 0) continue;
1497
- let existing = breakdowns.find((b) => b.model === model);
1498
- existing ? (existing.eventCount += 1, existing.inputTokens += inputTokens, existing.cachedInputTokens += cachedInputTokens, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + cacheWrite5m, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + cacheWrite1h, existing.outputTokens += outputTokens) : breakdowns.push({
1499
- provider: "anthropic",
1500
- product: "claude-code",
1501
- channel: "cli",
1502
- model,
1503
- project: "unknown",
1504
- eventCount: 1,
1505
- inputTokens,
1506
- cachedInputTokens,
1507
- cacheWriteTokens,
1508
- cacheWrite5mTokens: cacheWrite5m,
1509
- cacheWrite1hTokens: cacheWrite1h,
1510
- outputTokens,
1511
- reasoningOutputTokens: 0
1512
- });
1513
- }
1514
- }
1515
- nextPage = data.has_more ? data.next_page : null;
1516
- } while (nextPage);
1742
+
1743
+ // src/scanners/cursor.ts
1744
+ import { existsSync } from "node:fs";
1745
+ import { copyFile, mkdtemp, rm } from "node:fs/promises";
1746
+ import { homedir as homedir6, tmpdir } from "node:os";
1747
+ import { join as join7, resolve } from "node:path";
1748
+ var CURSOR_CONFIG_DIR_ENV = "CURSOR_CONFIG_DIR", CURSOR_STATE_DB_PATH_ENV = "CURSOR_STATE_DB_PATH", CURSOR_WEB_BASE_URL_ENV = "CURSOR_WEB_BASE_URL", CURSOR_STATE_DB_RELATIVE = join7("User", "globalStorage", "state.vscdb"), CURSOR_SESSION_COOKIE = "WorkosCursorSessionToken";
1749
+ function getDefaultDbPath() {
1750
+ if (process.platform === "darwin")
1751
+ return join7(homedir6(), "Library", "Application Support", "Cursor", CURSOR_STATE_DB_RELATIVE);
1752
+ if (process.platform === "win32") {
1753
+ let appData = process.env.APPDATA?.trim() || join7(homedir6(), "AppData", "Roaming");
1754
+ return join7(appData, "Cursor", CURSOR_STATE_DB_RELATIVE);
1755
+ }
1756
+ let xdg = process.env.XDG_CONFIG_HOME?.trim() || join7(homedir6(), ".config");
1757
+ return join7(xdg, "Cursor", CURSOR_STATE_DB_RELATIVE);
1517
1758
  }
1518
- function buildUrl(startingAt, endingAt, page) {
1519
- let params = new URLSearchParams({
1520
- starting_at: startingAt,
1521
- ending_at: endingAt,
1522
- bucket_width: "1d"
1523
- });
1524
- return params.append("group_by[]", "model"), page && params.set("page", page), `${ADMIN_API_BASE}${USAGE_ENDPOINT}?${params}`;
1759
+ function findDbPath() {
1760
+ let explicit = process.env[CURSOR_STATE_DB_PATH_ENV]?.trim();
1761
+ if (explicit) {
1762
+ let p = resolve(explicit);
1763
+ return existsSync(p) ? p : null;
1764
+ }
1765
+ let dirs = process.env[CURSOR_CONFIG_DIR_ENV]?.trim(), candidates = dirs ? dirs.split(",").map((v) => {
1766
+ let r = resolve(v.trim());
1767
+ return r.endsWith(".vscdb") ? r : join7(r, CURSOR_STATE_DB_RELATIVE);
1768
+ }) : [getDefaultDbPath()];
1769
+ for (let c of candidates)
1770
+ if (existsSync(c)) return c;
1771
+ return null;
1525
1772
  }
1526
- function chunkDateRange(startDate, endDate) {
1527
- let chunks = [], current = /* @__PURE__ */ new Date(`${startDate}T00:00:00Z`), end = /* @__PURE__ */ new Date(`${endDate}T00:00:00Z`);
1528
- for (end.setUTCDate(end.getUTCDate() + 1); current < end; ) {
1529
- let chunkEnd = new Date(current);
1530
- chunkEnd.setUTCDate(chunkEnd.getUTCDate() + MAX_DAYS_PER_REQUEST);
1531
- let actualEnd = chunkEnd < end ? chunkEnd : end;
1532
- chunks.push({
1533
- startingAt: current.toISOString().replace(".000Z", "Z"),
1534
- endingAt: actualEnd.toISOString().replace(".000Z", "Z")
1535
- }), current = actualEnd;
1773
+ function readAuthFromDb(dbPath) {
1774
+ let { DatabaseSync } = __require("node:sqlite"), db = new DatabaseSync(dbPath, { open: !0 });
1775
+ try {
1776
+ let raw = db.prepare("SELECT value FROM ItemTable WHERE key = ? LIMIT 1").get("cursorAuth/accessToken")?.value, token;
1777
+ return typeof raw == "string" ? token = raw.trim() || void 0 : Buffer.isBuffer(raw) && (token = raw.toString("utf8").trim() || void 0), { accessToken: token };
1778
+ } finally {
1779
+ db.close();
1536
1780
  }
1537
- return chunks;
1538
1781
  }
1539
-
1540
- // src/scanners/anthropic-csv.ts
1541
- import { readFile as readFile13 } from "node:fs/promises";
1542
- async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
1543
- if (!targetDates.length) return /* @__PURE__ */ new Map();
1544
- let targetDateSet = new Set(targetDates), grouped = new Map(
1545
- targetDates.map((d) => [d, /* @__PURE__ */ new Map()])
1546
- );
1547
- for (let filePath of csvFilePaths) {
1548
- let content;
1549
- try {
1550
- content = await readFile13(filePath, "utf-8");
1551
- } catch {
1552
- continue;
1553
- }
1554
- let rows = parseCsv(content);
1555
- for (let row of rows) {
1556
- if (!targetDateSet.has(row.usage_date_utc) || row.usage_input_tokens_no_cache + row.usage_input_tokens_cache_write_5m + row.usage_input_tokens_cache_write_1h + row.usage_input_tokens_cache_read + row.usage_output_tokens === 0) continue;
1557
- let model = normalizeModelName(row.model_version), product = workspaceToProduct(row.workspace), key = `${model}|${product}`, byModel = grouped.get(row.usage_date_utc), existing = byModel.get(key), cacheWriteTokens = row.usage_input_tokens_cache_write_5m + row.usage_input_tokens_cache_write_1h;
1558
- existing ? (existing.eventCount += 1, existing.inputTokens += row.usage_input_tokens_no_cache, existing.cachedInputTokens += row.usage_input_tokens_cache_read, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + row.usage_input_tokens_cache_write_5m, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + row.usage_input_tokens_cache_write_1h, existing.outputTokens += row.usage_output_tokens) : byModel.set(key, {
1559
- provider: "anthropic",
1560
- product,
1561
- channel: "cli",
1562
- model,
1563
- project: "unknown",
1564
- eventCount: 1,
1565
- inputTokens: row.usage_input_tokens_no_cache,
1566
- cachedInputTokens: row.usage_input_tokens_cache_read,
1567
- cacheWriteTokens,
1568
- cacheWrite5mTokens: row.usage_input_tokens_cache_write_5m,
1569
- cacheWrite1hTokens: row.usage_input_tokens_cache_write_1h,
1570
- outputTokens: row.usage_output_tokens,
1571
- reasoningOutputTokens: 0
1572
- });
1573
- }
1782
+ async function withSnapshot(dbPath, cb) {
1783
+ let dir = await mkdtemp(join7(tmpdir(), "aiusage-cursor-")), snap = join7(dir, "state.vscdb");
1784
+ await copyFile(dbPath, snap);
1785
+ for (let suffix of ["-shm", "-wal"])
1786
+ existsSync(`${dbPath}${suffix}`) && await copyFile(`${dbPath}${suffix}`, `${snap}${suffix}`);
1787
+ try {
1788
+ return cb(snap);
1789
+ } finally {
1790
+ await rm(dir, { recursive: !0, force: !0 });
1574
1791
  }
1575
- return new Map(
1576
- [...grouped.entries()].map(([date, byModel]) => [date, [...byModel.values()]])
1577
- );
1578
1792
  }
1579
- function workspaceToProduct(workspace) {
1580
- let w = workspace.trim().toLowerCase();
1581
- return "claude-code";
1793
+ async function readAuth(dbPath) {
1794
+ try {
1795
+ return readAuthFromDb(dbPath);
1796
+ } catch (err) {
1797
+ if (err instanceof Error && /database is locked/i.test(err.message))
1798
+ return withSnapshot(dbPath, (snap) => readAuthFromDb(snap));
1799
+ throw err;
1800
+ }
1582
1801
  }
1583
- function parseCsv(content) {
1584
- let lines = content.split(`
1585
- `).map((l) => l.trim()).filter(Boolean);
1586
- if (lines.length < 2) return [];
1587
- let headers = lines[0].split(",").map((h) => h.trim()), rows = [];
1588
- for (let i = 1; i < lines.length; i++) {
1589
- let values = lines[i].split(","), row = {};
1590
- for (let j = 0; j < headers.length; j++)
1591
- row[headers[j]] = values[j]?.trim() ?? "";
1592
- let date = row.usage_date_utc;
1593
- !date || !/^\d{4}-\d{2}-\d{2}$/.test(date) || rows.push({
1594
- usage_date_utc: date,
1595
- model_version: row.model_version ?? "",
1596
- workspace: row.workspace ?? "",
1597
- usage_input_tokens_no_cache: parseInt(row.usage_input_tokens_no_cache ?? "0", 10) || 0,
1598
- usage_input_tokens_cache_write_5m: parseInt(row.usage_input_tokens_cache_write_5m ?? "0", 10) || 0,
1599
- usage_input_tokens_cache_write_1h: parseInt(row.usage_input_tokens_cache_write_1h ?? "0", 10) || 0,
1600
- usage_input_tokens_cache_read: parseInt(row.usage_input_tokens_cache_read ?? "0", 10) || 0,
1601
- usage_output_tokens: parseInt(row.usage_output_tokens ?? "0", 10) || 0
1602
- });
1802
+ function jwtSub(token) {
1803
+ let part = token.split(".")[1];
1804
+ if (!part) return;
1805
+ let b64 = part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=");
1806
+ try {
1807
+ return JSON.parse(Buffer.from(b64, "base64").toString("utf8")).sub?.trim();
1808
+ } catch {
1809
+ return;
1603
1810
  }
1604
- return rows;
1605
1811
  }
1606
-
1607
- // src/report.ts
1608
- import { readdir as readdir6, readFile as readFile14 } from "node:fs/promises";
1609
- import { homedir as homedir14 } from "node:os";
1610
- import { basename as basename8, join as join14 } from "node:path";
1611
-
1612
- // ../shared/src/pricing/data/anthropic.ts
1613
- var anthropic = {
1614
- "claude-code": {
1615
- models: {
1616
- "claude-opus-4-8": {
1617
- currency: "USD",
1618
- input_per_million: 5,
1619
- output_per_million: 25,
1620
- cache_write_5m_per_million: 6.25,
1621
- cache_write_1h_per_million: 10,
1622
- cached_input_per_million: 0.5
1623
- },
1624
- "claude-opus-4-7": {
1625
- currency: "USD",
1626
- input_per_million: 5,
1627
- output_per_million: 25,
1628
- cache_write_5m_per_million: 6.25,
1629
- cache_write_1h_per_million: 10,
1630
- cached_input_per_million: 0.5
1631
- },
1632
- "claude-opus-4-6": {
1633
- currency: "USD",
1634
- input_per_million: 5,
1635
- output_per_million: 25,
1636
- cache_write_5m_per_million: 6.25,
1637
- cache_write_1h_per_million: 10,
1638
- cached_input_per_million: 0.5
1639
- },
1640
- "claude-opus-4-5": {
1641
- currency: "USD",
1642
- input_per_million: 5,
1643
- output_per_million: 25,
1644
- cache_write_5m_per_million: 6.25,
1645
- cache_write_1h_per_million: 10,
1646
- cached_input_per_million: 0.5
1647
- },
1648
- "claude-opus-4-1": {
1649
- currency: "USD",
1650
- input_per_million: 15,
1651
- output_per_million: 75,
1652
- cache_write_5m_per_million: 18.75,
1653
- cache_write_1h_per_million: 30,
1654
- cached_input_per_million: 1.5
1655
- },
1656
- "claude-opus-4": {
1657
- currency: "USD",
1658
- notes: "deprecated",
1659
- input_per_million: 15,
1660
- output_per_million: 75,
1661
- cache_write_5m_per_million: 18.75,
1662
- cache_write_1h_per_million: 30,
1663
- cached_input_per_million: 1.5
1664
- },
1665
- "claude-sonnet-4-6": {
1666
- currency: "USD",
1667
- input_per_million: 3,
1668
- output_per_million: 15,
1669
- cache_write_5m_per_million: 3.75,
1670
- cache_write_1h_per_million: 6,
1671
- cached_input_per_million: 0.3
1672
- },
1673
- "claude-sonnet-4-5": {
1674
- currency: "USD",
1675
- input_per_million: 3,
1676
- output_per_million: 15,
1677
- cache_write_5m_per_million: 3.75,
1678
- cache_write_1h_per_million: 6,
1679
- cached_input_per_million: 0.3
1680
- },
1681
- "claude-sonnet-4": {
1682
- currency: "USD",
1683
- notes: "deprecated",
1684
- input_per_million: 3,
1685
- output_per_million: 15,
1686
- cache_write_5m_per_million: 3.75,
1687
- cache_write_1h_per_million: 6,
1688
- cached_input_per_million: 0.3
1689
- },
1690
- "claude-haiku-4-5": {
1691
- currency: "USD",
1692
- input_per_million: 1,
1693
- output_per_million: 5,
1694
- cache_write_5m_per_million: 1.25,
1695
- cache_write_1h_per_million: 2,
1696
- cached_input_per_million: 0.1
1697
- },
1698
- "claude-haiku-3-5": {
1699
- currency: "USD",
1700
- notes: "retired except on Bedrock/Vertex",
1701
- input_per_million: 0.8,
1702
- output_per_million: 4,
1703
- cache_write_5m_per_million: 1,
1704
- cache_write_1h_per_million: 1.6,
1705
- cached_input_per_million: 0.08
1706
- }
1812
+ function getWebBaseUrl() {
1813
+ return (process.env[CURSOR_WEB_BASE_URL_ENV]?.trim() || "https://cursor.com").replace(/\/+$/, "");
1814
+ }
1815
+ async function fetchCsv(accessToken) {
1816
+ let url = new URL("/api/dashboard/export-usage-events-csv?strategy=tokens", getWebBaseUrl()), sub = jwtSub(accessToken), cookieValues = [accessToken, ...sub ? [`${sub}::${accessToken}`] : []], attempts = [{ Authorization: `Bearer ${accessToken}` }];
1817
+ for (let cv of cookieValues)
1818
+ attempts.push({ Cookie: `${CURSOR_SESSION_COOKIE}=${cv}` }), attempts.push({ Authorization: `Bearer ${accessToken}`, Cookie: `${CURSOR_SESSION_COOKIE}=${cv}` });
1819
+ let failures = [];
1820
+ for (let headers of attempts) {
1821
+ let res = await fetch(url, { headers: { Accept: "text/csv,*/*;q=0.8", ...headers } });
1822
+ if (res.ok) return res.text();
1823
+ failures.push(`${res.status} ${res.statusText}`);
1824
+ }
1825
+ throw new Error(`Cursor API failed: ${failures.join(", ")}`);
1826
+ }
1827
+ function parseCsvLine(line) {
1828
+ let vals = [], cur = "", inQ = !1;
1829
+ for (let i = 0; i < line.length; i++) {
1830
+ let c = line[i];
1831
+ c === '"' ? inQ && line[i + 1] === '"' ? (cur += '"', i++) : inQ = !inQ : c === "," && !inQ ? (vals.push(cur), cur = "") : cur += c;
1832
+ }
1833
+ return vals.push(cur), vals;
1834
+ }
1835
+ function parseNum(v) {
1836
+ let n = Number((v ?? "").replace(/,/g, "").trim());
1837
+ return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
1838
+ }
1839
+ function parseDateStr(v) {
1840
+ let s = v?.trim();
1841
+ if (!s) return null;
1842
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
1843
+ let d = new Date(s);
1844
+ return isNaN(d.getTime()) ? null : dateKey(d);
1845
+ }
1846
+ async function scanCursorDates(targetDates) {
1847
+ let dateSet = new Set(targetDates), empty = new Map(targetDates.map((d) => [d, []])), dbPath = findDbPath();
1848
+ if (!dbPath) return empty;
1849
+ let auth;
1850
+ try {
1851
+ auth = await readAuth(dbPath);
1852
+ } catch {
1853
+ return empty;
1854
+ }
1855
+ if (!auth.accessToken) return empty;
1856
+ let csvText;
1857
+ try {
1858
+ csvText = await fetchCsv(auth.accessToken);
1859
+ } catch {
1860
+ return empty;
1861
+ }
1862
+ let grouped = /* @__PURE__ */ new Map();
1863
+ for (let d of dateSet) grouped.set(d, /* @__PURE__ */ new Map());
1864
+ let headers = null;
1865
+ for (let rawLine of csvText.split(/\r?\n/)) {
1866
+ let line = rawLine.trim();
1867
+ if (!line) continue;
1868
+ let values = parseCsvLine(line);
1869
+ if (!headers) {
1870
+ headers = values;
1871
+ continue;
1707
1872
  }
1873
+ let row = {};
1874
+ headers.forEach((h, i) => {
1875
+ row[h] = values[i] ?? "";
1876
+ });
1877
+ let date = parseDateStr(row.Date);
1878
+ if (!date || !dateSet.has(date)) continue;
1879
+ let rawModel = row.Model?.trim();
1880
+ if (!rawModel) continue;
1881
+ let model = normalizeModelName(rawModel);
1882
+ if (!(parseNum(row["Total Tokens"]) || parseNum(row.Tokens))) continue;
1883
+ let inputWithCache = parseNum(row["Input (w/ Cache Write)"]), inputWithout = parseNum(row["Input (w/o Cache Write)"]), cacheRead = parseNum(row["Cache Read"]), output = parseNum(row["Output Tokens"]), inputTokens = inputWithCache + inputWithout + cacheRead, dayMap = grouped.get(date), existing = dayMap.get(model);
1884
+ existing ? (existing.eventCount += 1, existing.inputTokens += inputTokens, existing.cachedInputTokens += cacheRead, existing.cacheWriteTokens += inputWithCache, existing.outputTokens += output) : dayMap.set(model, {
1885
+ provider: "cursor",
1886
+ product: "cursor",
1887
+ channel: "ide",
1888
+ model,
1889
+ project: "unknown",
1890
+ projectDisplay: "unknown",
1891
+ eventCount: 1,
1892
+ inputTokens,
1893
+ cachedInputTokens: cacheRead,
1894
+ cacheWriteTokens: inputWithCache,
1895
+ outputTokens: output,
1896
+ reasoningOutputTokens: 0
1897
+ });
1708
1898
  }
1709
- };
1899
+ return new Map([...grouped.entries()].map(([d, m]) => [d, [...m.values()]]));
1900
+ }
1710
1901
 
1711
- // ../shared/src/pricing/data/openai.ts
1712
- var openai = {
1713
- codex: {
1714
- models: {
1715
- // ── GPT-5.5 系列 ──
1716
- "gpt-5.5": {
1717
- currency: "USD",
1718
- input_per_million: 5,
1719
- cached_input_per_million: 0.5,
1720
- output_per_million: 30
1721
- },
1722
- "gpt-5.5-pro": {
1723
- currency: "USD",
1724
- input_per_million: 30,
1725
- cached_input_per_million: null,
1726
- output_per_million: 180
1727
- },
1728
- // ── GPT-5.4 系列 ──
1729
- "gpt-5.4": {
1730
- currency: "USD",
1731
- input_per_million: 2.5,
1732
- cached_input_per_million: 0.25,
1733
- output_per_million: 15
1734
- },
1735
- "gpt-5.4-mini": {
1736
- currency: "USD",
1737
- input_per_million: 0.75,
1738
- cached_input_per_million: 0.075,
1739
- output_per_million: 4.5
1740
- },
1741
- "gpt-5.4-nano": {
1742
- currency: "USD",
1743
- input_per_million: 0.2,
1744
- cached_input_per_million: 0.02,
1745
- output_per_million: 1.25
1746
- },
1747
- "gpt-5.4-pro": {
1748
- currency: "USD",
1749
- input_per_million: 30,
1750
- cached_input_per_million: null,
1751
- output_per_million: 180
1752
- },
1753
- // ── GPT-5.3 / 5.2 / Codex 变体 ──
1754
- "gpt-5.3-codex": {
1755
- currency: "USD",
1756
- input_per_million: 1.75,
1757
- cached_input_per_million: 0.175,
1758
- output_per_million: 14
1759
- },
1760
- "gpt-5.2-codex": {
1761
- currency: "USD",
1762
- input_per_million: 1.75,
1763
- cached_input_per_million: 0.175,
1764
- output_per_million: 14
1765
- },
1766
- "gpt-5.2-pro": {
1767
- currency: "USD",
1768
- input_per_million: 21,
1769
- cached_input_per_million: null,
1770
- output_per_million: 168
1771
- },
1772
- "gpt-5.2": {
1773
- currency: "USD",
1774
- input_per_million: 1.75,
1775
- cached_input_per_million: 0.175,
1776
- output_per_million: 14
1777
- },
1778
- // ── GPT-5.1 / 5 系列 ──
1779
- "gpt-5.1-codex-max": {
1780
- currency: "USD",
1781
- input_per_million: 1.25,
1782
- cached_input_per_million: 0.125,
1783
- output_per_million: 10
1784
- },
1785
- "gpt-5.1-codex-mini": {
1786
- currency: "USD",
1787
- input_per_million: 0.25,
1788
- cached_input_per_million: 0.025,
1789
- output_per_million: 2
1790
- },
1791
- "gpt-5.1-codex": {
1792
- currency: "USD",
1793
- input_per_million: 1.25,
1794
- cached_input_per_million: 0.125,
1795
- output_per_million: 10
1796
- },
1797
- "gpt-5.1": {
1798
- currency: "USD",
1799
- input_per_million: 1.25,
1800
- cached_input_per_million: 0.125,
1801
- output_per_million: 10
1802
- },
1803
- "gpt-5-pro": {
1804
- currency: "USD",
1805
- input_per_million: 15,
1806
- cached_input_per_million: null,
1807
- output_per_million: 120
1808
- },
1809
- "gpt-5-codex": {
1810
- currency: "USD",
1811
- input_per_million: 1.25,
1812
- cached_input_per_million: 0.125,
1813
- output_per_million: 10
1814
- },
1815
- "gpt-5-mini": {
1816
- currency: "USD",
1817
- input_per_million: 0.25,
1818
- cached_input_per_million: 0.025,
1819
- output_per_million: 2
1820
- },
1821
- "gpt-5-nano": {
1822
- currency: "USD",
1823
- input_per_million: 0.05,
1824
- cached_input_per_million: 5e-3,
1825
- output_per_million: 0.4
1826
- },
1827
- "gpt-5": {
1828
- currency: "USD",
1829
- input_per_million: 1.25,
1830
- cached_input_per_million: 0.125,
1831
- output_per_million: 10
1832
- },
1833
- // ── GPT-4.1 / 4o ──
1834
- "gpt-4.1": { currency: "USD", input_per_million: 2, cached_input_per_million: 0.5, output_per_million: 8 },
1835
- "gpt-4.1-mini": { currency: "USD", input_per_million: 0.4, cached_input_per_million: 0.1, output_per_million: 1.6 },
1836
- "gpt-4.1-nano": { currency: "USD", input_per_million: 0.1, cached_input_per_million: 0.025, output_per_million: 0.4 },
1837
- "gpt-4o": { currency: "USD", input_per_million: 2.5, cached_input_per_million: 1.25, output_per_million: 10 },
1838
- "gpt-4o-mini": { currency: "USD", input_per_million: 0.15, cached_input_per_million: 0.075, output_per_million: 0.6 },
1839
- "gpt-4o-2024-05-13": { currency: "USD", input_per_million: 5, cached_input_per_million: null, output_per_million: 15 },
1840
- // ── o 系列 ──
1841
- "o1-pro": { currency: "USD", input_per_million: 150, cached_input_per_million: null, output_per_million: 600 },
1842
- o1: { currency: "USD", input_per_million: 15, cached_input_per_million: 7.5, output_per_million: 60 },
1843
- "o1-mini": { currency: "USD", input_per_million: 1.1, cached_input_per_million: 0.55, output_per_million: 4.4 },
1844
- "o3-pro": { currency: "USD", input_per_million: 20, cached_input_per_million: null, output_per_million: 80 },
1845
- o3: { currency: "USD", input_per_million: 2, cached_input_per_million: 0.5, output_per_million: 8 },
1846
- "o3-mini": { currency: "USD", input_per_million: 1.1, cached_input_per_million: 0.55, output_per_million: 4.4 },
1847
- "o4-mini": { currency: "USD", input_per_million: 1.1, cached_input_per_million: 0.275, output_per_million: 4.4 },
1848
- // ── Deep research / 工具型 ──
1849
- "o3-deep-research": {
1850
- currency: "USD",
1851
- notes: "corrected from previous 10/40 entry on 2026-05-24",
1852
- input_per_million: 5,
1853
- cached_input_per_million: null,
1854
- output_per_million: 20
1855
- },
1856
- "o4-mini-deep-research": {
1857
- currency: "USD",
1858
- notes: "corrected from previous 2/8 entry on 2026-05-24",
1859
- input_per_million: 1,
1860
- cached_input_per_million: null,
1861
- output_per_million: 4
1862
- },
1863
- "computer-use-preview": {
1864
- currency: "USD",
1865
- notes: "corrected from previous 3/12 entry on 2026-05-24",
1866
- input_per_million: 1.5,
1867
- cached_input_per_million: null,
1868
- output_per_million: 6
1869
- },
1870
- // ── 历史模型(GPT-4 / 3.5 / davinci 等)──
1871
- "gpt-4-turbo-2024-04-09": { currency: "USD", input_per_million: 10, cached_input_per_million: null, output_per_million: 30 },
1872
- "gpt-4-0125-preview": { currency: "USD", input_per_million: 10, cached_input_per_million: null, output_per_million: 30 },
1873
- "gpt-4-1106-preview": { currency: "USD", input_per_million: 10, cached_input_per_million: null, output_per_million: 30 },
1874
- "gpt-4-1106-vision-preview": { currency: "USD", input_per_million: 10, cached_input_per_million: null, output_per_million: 30 },
1875
- "gpt-4-0613": { currency: "USD", input_per_million: 30, cached_input_per_million: null, output_per_million: 60 },
1876
- "gpt-4-0314": { currency: "USD", input_per_million: 30, cached_input_per_million: null, output_per_million: 60 },
1877
- "gpt-4-32k": { currency: "USD", input_per_million: 60, cached_input_per_million: null, output_per_million: 120 },
1878
- "gpt-3.5-turbo": { currency: "USD", input_per_million: 0.5, cached_input_per_million: null, output_per_million: 1.5 },
1879
- "gpt-3.5-turbo-0125": { currency: "USD", input_per_million: 0.5, cached_input_per_million: null, output_per_million: 1.5 },
1880
- "gpt-3.5-turbo-1106": { currency: "USD", input_per_million: 1, cached_input_per_million: null, output_per_million: 2 },
1881
- "gpt-3.5-turbo-0613": { currency: "USD", input_per_million: 1.5, cached_input_per_million: null, output_per_million: 2 },
1882
- "gpt-3.5-0301": { currency: "USD", input_per_million: 1.5, cached_input_per_million: null, output_per_million: 2 },
1883
- "gpt-3.5-turbo-instruct": { currency: "USD", input_per_million: 1.5, cached_input_per_million: null, output_per_million: 2 },
1884
- "gpt-3.5-turbo-16k-0613": { currency: "USD", input_per_million: 3, cached_input_per_million: null, output_per_million: 4 },
1885
- "davinci-002": { currency: "USD", input_per_million: 2, cached_input_per_million: null, output_per_million: 2 },
1886
- "babbage-002": { currency: "USD", input_per_million: 0.4, cached_input_per_million: null, output_per_million: 0.4 },
1887
- "codex-mini-latest": { currency: "USD", input_per_million: 1.5, cached_input_per_million: 0.375, output_per_million: 6 },
1888
- // ── Embeddings ──
1889
- "text-embedding-3-small": { currency: "USD", input_per_million: 0.02, cached_input_per_million: null, output_per_million: 0 },
1890
- "text-embedding-3-large": { currency: "USD", input_per_million: 0.13, cached_input_per_million: null, output_per_million: 0 },
1891
- "text-embedding-ada-002": { currency: "USD", input_per_million: 0.1, cached_input_per_million: null, output_per_million: 0 }
1902
+ // src/scanners/gemini.ts
1903
+ import { readFile as readFile6 } from "node:fs/promises";
1904
+ import { basename as basename3, join as join8 } from "node:path";
1905
+ import { homedir as homedir7 } from "node:os";
1906
+ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
1907
+ let dates = new Set(targetDates), dir = baseDir ?? join8(homedir7(), ".gemini", "tmp"), files = await walkFiles(dir, ".json");
1908
+ if (files.length === 0) return emptyResult(dates);
1909
+ let grouped = initDateMap(dates), tokenBackedDates = /* @__PURE__ */ new Set();
1910
+ for (let filePath of files) {
1911
+ if (basename3(filePath) === "logs.json") continue;
1912
+ let content;
1913
+ try {
1914
+ content = await readFile6(filePath, "utf-8");
1915
+ } catch {
1916
+ continue;
1917
+ }
1918
+ let session;
1919
+ try {
1920
+ session = JSON.parse(content);
1921
+ } catch {
1922
+ continue;
1923
+ }
1924
+ let messages = session.messages ?? session.history ?? session.data?.messages ?? session.data?.history ?? [], fallbackModel = session.model ?? session.data?.model ?? "unknown", fallbackTs = session.createTime ?? session.startTime ?? session.data?.createTime;
1925
+ for (let msg of messages) {
1926
+ let tokens = extractTokens(msg);
1927
+ if (!tokens) continue;
1928
+ let model = normalizeModelName(msg.model ?? fallbackModel), ts = parseTs(msg.timestamp) ?? parseTs(msg.createTime) ?? parseTs(fallbackTs);
1929
+ if (!ts) continue;
1930
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
1931
+ dayMap && (tokenBackedDates.add(dk), accumulate(
1932
+ dayMap,
1933
+ `${model}|unknown`,
1934
+ {
1935
+ provider: "google",
1936
+ product: "gemini-cli",
1937
+ channel: "cli",
1938
+ model,
1939
+ project: "unknown",
1940
+ projectDisplay: "unknown",
1941
+ inputTokens: 0,
1942
+ cachedInputTokens: 0,
1943
+ cacheWriteTokens: 0,
1944
+ outputTokens: 0,
1945
+ reasoningOutputTokens: 0
1946
+ },
1947
+ tokens
1948
+ ));
1892
1949
  }
1893
1950
  }
1894
- };
1895
-
1896
- // ../shared/src/pricing/data/google.ts
1897
- var google = {
1898
- // Antigravity 本地不输出 token 信息,仅事件计数;保留空 models 不算费用
1899
- antigravity: { models: {} },
1900
- "gemini-cli": {
1901
- models: {
1902
- // ── Gemini 3.x 系列 ──
1903
- "gemini-3.5-flash": {
1904
- currency: "USD",
1905
- input_per_million: 1.5,
1906
- output_per_million: 9,
1907
- cached_input_per_million: 0.15
1908
- },
1909
- "gemini-3.1-pro-preview": {
1910
- currency: "USD",
1911
- notes: "tiered by prompt length, 200K threshold",
1912
- tiers: [
1913
- { threshold: 2e5, input_per_million: 2, cached_input_per_million: 0.2, output_per_million: 12 },
1914
- { input_per_million: 4, cached_input_per_million: 0.4, output_per_million: 18 }
1915
- ]
1916
- },
1917
- "gemini-3.1-flash-lite": {
1918
- currency: "USD",
1919
- notes: "text/image/video price; audio is $0.50/M",
1920
- input_per_million: 0.25,
1921
- cached_input_per_million: 0.025,
1922
- output_per_million: 1.5
1923
- },
1924
- "gemini-3.1-flash-lite-preview": {
1925
- currency: "USD",
1926
- notes: "text/image/video price",
1927
- input_per_million: 0.25,
1928
- cached_input_per_million: 0.025,
1929
- output_per_million: 1.5
1930
- },
1931
- "gemini-3-flash-preview": {
1932
- currency: "USD",
1933
- notes: "text/image/video price; audio is $1.00/M",
1934
- input_per_million: 0.5,
1935
- cached_input_per_million: 0.05,
1936
- output_per_million: 3
1937
- },
1938
- // ── Gemini 2.5 系列 ──
1939
- "gemini-2.5-pro": {
1940
- currency: "USD",
1941
- notes: "tiered by prompt length, 200K threshold",
1942
- tiers: [
1943
- { threshold: 2e5, input_per_million: 1.25, cached_input_per_million: 0.125, output_per_million: 10 },
1944
- { input_per_million: 2.5, cached_input_per_million: 0.25, output_per_million: 15 }
1945
- ]
1946
- },
1947
- "gemini-2.5-flash": {
1948
- currency: "USD",
1949
- notes: "text/image/video price; audio is $1.00/M; corrected from 0.15/0.6 on 2026-05-24",
1950
- input_per_million: 0.3,
1951
- cached_input_per_million: 0.03,
1952
- output_per_million: 2.5
1953
- },
1954
- "gemini-2.5-flash-lite": {
1955
- currency: "USD",
1956
- notes: "text/image/video price; audio is $0.30/M",
1957
- input_per_million: 0.1,
1958
- cached_input_per_million: 0.01,
1959
- output_per_million: 0.4
1960
- },
1961
- "gemini-2.5-flash-lite-preview": {
1962
- currency: "USD",
1963
- input_per_million: 0.1,
1964
- cached_input_per_million: 0.01,
1965
- output_per_million: 0.4
1966
- },
1967
- "gemini-2.5-computer-use-preview": {
1968
- currency: "USD",
1969
- notes: "tiered by prompt length, 200K threshold",
1970
- tiers: [
1971
- { threshold: 2e5, input_per_million: 1.25, output_per_million: 10 },
1972
- { input_per_million: 2.5, output_per_million: 15 }
1973
- ]
1974
- },
1975
- // ── Gemini 2.0 系列 ──
1976
- "gemini-2.0-flash": {
1977
- currency: "USD",
1978
- notes: "text/image/video price; audio is $0.70/M",
1979
- input_per_million: 0.1,
1980
- cached_input_per_million: 0.025,
1981
- output_per_million: 0.4
1982
- },
1983
- "gemini-2.0-flash-lite": {
1984
- currency: "USD",
1985
- input_per_million: 0.075,
1986
- output_per_million: 0.3
1987
- },
1988
- // ── Gemini 1.5(legacy)──
1989
- "gemini-1.5-pro": {
1990
- currency: "USD",
1991
- notes: "legacy",
1992
- input_per_million: 1.25,
1993
- cached_input_per_million: 0.3125,
1994
- output_per_million: 5
1995
- },
1996
- "gemini-1.5-flash": {
1997
- currency: "USD",
1998
- notes: "legacy",
1999
- input_per_million: 0.075,
2000
- cached_input_per_million: 0.01875,
2001
- output_per_million: 0.3
2002
- },
2003
- // ── Robotics / Embedding ──
2004
- "gemini-robotics-er-1.6-preview": {
2005
- currency: "USD",
2006
- notes: "text/image/video price; audio is $2.00/M",
2007
- input_per_million: 1,
2008
- output_per_million: 5
2009
- },
2010
- "gemini-embedding-2": {
2011
- currency: "USD",
2012
- notes: "text input only price; image $0.45/M, audio $6.50/M, video $12.00/M",
2013
- input_per_million: 0.2,
2014
- output_per_million: 0
2015
- },
2016
- "gemini-embedding": {
2017
- currency: "USD",
2018
- input_per_million: 0.15,
2019
- output_per_million: 0
2020
- },
2021
- // ── Live API / TTS / Image / Video 走 perfect-fit 模型,按其代表单价;
2022
- // 这些模型的 input/output 不是简单的 text token,应在 scanner 侧匹配。 ──
2023
- "gemini-3.1-flash-live-preview": {
2024
- currency: "USD",
2025
- notes: "Live API text price; audio/video/image priced separately",
2026
- input_per_million: 0.75,
2027
- output_per_million: 4.5
2028
- },
2029
- "gemini-2.5-flash-native-audio": {
2030
- currency: "USD",
2031
- notes: "Live API text price; audio is $3.00 input / $12.00 output",
2032
- input_per_million: 0.5,
2033
- output_per_million: 2
2034
- },
2035
- "gemini-3.1-flash-tts-preview": {
2036
- currency: "USD",
2037
- notes: "text in, audio out",
2038
- input_per_million: 1,
2039
- output_per_million: 20
2040
- },
2041
- "gemini-2.5-flash-preview-tts": {
2042
- currency: "USD",
2043
- notes: "text in, audio out",
2044
- input_per_million: 0.5,
2045
- output_per_million: 10
2046
- },
2047
- "gemini-2.5-pro-preview-tts": {
2048
- currency: "USD",
2049
- notes: "text in, audio out",
2050
- input_per_million: 1,
2051
- output_per_million: 20
2052
- },
2053
- "gemini-3.1-flash-image-preview": {
2054
- currency: "USD",
2055
- notes: "text/image in, image out priced per-image",
2056
- input_per_million: 0.5,
2057
- output_per_million: 3
2058
- },
2059
- "gemini-2.5-flash-image": {
2060
- currency: "USD",
2061
- notes: "image out priced per-image ($0.039)",
2062
- input_per_million: 0.3,
2063
- output_per_million: 0
2064
- },
2065
- "gemini-3-pro-image-preview": {
2066
- currency: "USD",
2067
- notes: "image out priced per-image; text-output $12/M",
2068
- input_per_million: 2,
2069
- output_per_million: 12
1951
+ let logFiles = files.filter((filePath) => basename3(filePath) === "logs.json");
1952
+ for (let filePath of logFiles)
1953
+ await collectGeminiLogEvents(filePath, grouped, tokenBackedDates);
1954
+ return finalize(grouped);
1955
+ }
1956
+ async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
1957
+ let content;
1958
+ try {
1959
+ content = await readFile6(filePath, "utf-8");
1960
+ } catch {
1961
+ return;
1962
+ }
1963
+ let rows;
1964
+ try {
1965
+ rows = JSON.parse(content);
1966
+ } catch {
1967
+ return;
1968
+ }
1969
+ if (Array.isArray(rows))
1970
+ for (let row of rows) {
1971
+ if (row.type && row.type !== "user") continue;
1972
+ let ts = parseTs(row.timestamp);
1973
+ if (!ts) continue;
1974
+ let dk = dateKey(ts);
1975
+ if (tokenBackedDates.has(dk)) continue;
1976
+ let dayMap = grouped.get(dk);
1977
+ dayMap && accumulate(
1978
+ dayMap,
1979
+ "unknown|unknown",
1980
+ {
1981
+ provider: "google",
1982
+ product: "gemini-cli",
1983
+ channel: "cli",
1984
+ model: "unknown",
1985
+ project: "unknown",
1986
+ inputTokens: 0,
1987
+ cachedInputTokens: 0,
1988
+ cacheWriteTokens: 0,
1989
+ outputTokens: 0,
1990
+ reasoningOutputTokens: 0
1991
+ },
1992
+ { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
1993
+ );
1994
+ }
1995
+ }
1996
+ function extractTokens(msg) {
1997
+ if (msg.tokens) {
1998
+ let t2 = msg.tokens, cached2 = t2.cached ?? 0, input = Math.max((t2.input ?? 0) - cached2, 0), thoughts = t2.thoughts ?? 0, output = Math.max((t2.output ?? 0) - thoughts, 0);
1999
+ return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
2000
+ }
2001
+ let u = msg.usage ?? msg.usageMetadata;
2002
+ if (u) {
2003
+ let cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
2004
+ return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
2005
+ }
2006
+ return null;
2007
+ }
2008
+
2009
+ // src/scanners/qwen.ts
2010
+ import { readFile as readFile7 } from "node:fs/promises";
2011
+ import { join as join9, basename as basename4, dirname as dirname2 } from "node:path";
2012
+ import { homedir as homedir8 } from "node:os";
2013
+ async function scanQwenDates(targetDates, baseDir, projectAliases) {
2014
+ let dates = new Set(targetDates), dir = baseDir ?? join9(homedir8(), ".qwen", "tmp"), files = await walkFiles(dir, ".jsonl");
2015
+ if (files.length === 0) return emptyResult(dates);
2016
+ let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
2017
+ for (let filePath of files) {
2018
+ let chatsDir = dirname2(filePath), projectDir = dirname2(chatsDir), projectId = basename4(projectDir), content;
2019
+ try {
2020
+ content = await readFile7(filePath, "utf-8");
2021
+ } catch {
2022
+ continue;
2023
+ }
2024
+ for (let line of content.split(`
2025
+ `)) {
2026
+ if (!line.trim()) continue;
2027
+ let obj;
2028
+ try {
2029
+ obj = JSON.parse(line);
2030
+ } catch {
2031
+ continue;
2032
+ }
2033
+ if (obj.type !== "assistant") continue;
2034
+ let ts = parseTs(obj.timestamp);
2035
+ if (!ts) continue;
2036
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2037
+ if (!dayMap) continue;
2038
+ if (obj.uuid) {
2039
+ if (seen.has(obj.uuid)) continue;
2040
+ seen.add(obj.uuid);
2070
2041
  }
2042
+ let u = obj.usageMetadata;
2043
+ if (!u) continue;
2044
+ let model = obj.model ?? "unknown", fields = obj.cwd ? resolveProjectFields(obj.cwd, projectAliases) : resolveProjectFields(projectId, projectAliases), cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
2045
+ accumulate(
2046
+ dayMap,
2047
+ `${model}|${fields.project}`,
2048
+ {
2049
+ provider: "alibaba",
2050
+ product: "qwen-code",
2051
+ channel: "cli",
2052
+ model,
2053
+ project: fields.project,
2054
+ projectDisplay: fields.projectDisplay,
2055
+ projectAlias: fields.projectAlias,
2056
+ inputTokens: 0,
2057
+ cachedInputTokens: 0,
2058
+ cacheWriteTokens: 0,
2059
+ outputTokens: 0,
2060
+ reasoningOutputTokens: 0
2061
+ },
2062
+ { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts }
2063
+ );
2071
2064
  }
2072
2065
  }
2073
- };
2066
+ return finalize(grouped);
2067
+ }
2074
2068
 
2075
- // ../shared/src/pricing/data/moonshot.ts
2076
- var moonshot = {
2077
- "kimi-code": {
2078
- models: {
2079
- "kimi-k2.6": {
2080
- currency: "CNY",
2081
- input_per_million: 6.5,
2082
- cached_input_per_million: 1.1,
2083
- output_per_million: 27
2084
- },
2085
- "kimi-k2.5": {
2086
- currency: "CNY",
2087
- input_per_million: 4,
2088
- cached_input_per_million: 0.7,
2089
- output_per_million: 21
2090
- },
2091
- "kimi-k2-0905-preview": {
2092
- currency: "CNY",
2093
- notes: "will be retired 2026-05-25",
2094
- input_per_million: 4,
2095
- cached_input_per_million: 1,
2096
- output_per_million: 16
2097
- },
2098
- "kimi-k2-0711-preview": {
2099
- currency: "CNY",
2100
- notes: "will be retired 2026-05-25",
2101
- input_per_million: 4,
2102
- cached_input_per_million: 1,
2103
- output_per_million: 16
2104
- },
2105
- "kimi-k2-turbo-preview": {
2106
- currency: "CNY",
2107
- notes: "will be retired 2026-05-25",
2108
- input_per_million: 8,
2109
- cached_input_per_million: 1,
2110
- output_per_million: 58
2111
- },
2112
- "kimi-k2-thinking": {
2113
- currency: "CNY",
2114
- input_per_million: 4,
2115
- cached_input_per_million: 1,
2116
- output_per_million: 16
2117
- },
2118
- "kimi-k2-thinking-turbo": {
2119
- currency: "CNY",
2120
- input_per_million: 8,
2121
- cached_input_per_million: 1,
2122
- output_per_million: 58
2123
- },
2124
- "moonshot-v1-8k": {
2125
- currency: "CNY",
2126
- input_per_million: 2,
2127
- output_per_million: 10
2128
- },
2129
- "moonshot-v1-32k": {
2130
- currency: "CNY",
2131
- input_per_million: 5,
2132
- output_per_million: 20
2133
- },
2134
- "moonshot-v1-128k": {
2135
- currency: "CNY",
2136
- input_per_million: 10,
2137
- output_per_million: 30
2138
- },
2139
- "moonshot-v1-8k-vision-preview": {
2140
- currency: "CNY",
2141
- input_per_million: 2,
2142
- output_per_million: 10
2143
- },
2144
- "moonshot-v1-32k-vision-preview": {
2145
- currency: "CNY",
2146
- input_per_million: 5,
2147
- output_per_million: 20
2148
- },
2149
- "moonshot-v1-128k-vision-preview": {
2150
- currency: "CNY",
2151
- input_per_million: 10,
2152
- output_per_million: 30
2069
+ // src/scanners/kimi.ts
2070
+ import { readFile as readFile8 } from "node:fs/promises";
2071
+ import { join as join10, basename as basename5, dirname as dirname3 } from "node:path";
2072
+ import { homedir as homedir9 } from "node:os";
2073
+ async function scanKimiDates(targetDates, baseDir, projectAliases) {
2074
+ let dates = new Set(targetDates), kimiHome = baseDir ?? join10(homedir9(), ".kimi"), sessionsDir = join10(kimiHome, "sessions"), files = await walkFiles(sessionsDir, ".jsonl");
2075
+ if (files.length === 0) return emptyResult(dates);
2076
+ let workspaceMap = await loadWorkspaceMap(kimiHome), grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
2077
+ for (let filePath of files) {
2078
+ let sessionDir = dirname3(filePath), hashDir = dirname3(sessionDir), workDirHash = basename5(hashDir), projectFields = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
2079
+ try {
2080
+ content = await readFile8(filePath, "utf-8");
2081
+ } catch {
2082
+ continue;
2083
+ }
2084
+ let currentModel = "unknown";
2085
+ for (let line of content.split(`
2086
+ `)) {
2087
+ if (!line.trim()) continue;
2088
+ let obj;
2089
+ try {
2090
+ obj = JSON.parse(line);
2091
+ } catch {
2092
+ continue;
2093
+ }
2094
+ if (obj.payload?.model && (currentModel = obj.payload.model), obj.type !== "StatusUpdate") continue;
2095
+ let usage = obj.payload?.token_usage;
2096
+ if (!usage) continue;
2097
+ let ts = parseTs(obj.timestamp);
2098
+ if (!ts) continue;
2099
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2100
+ if (!dayMap) continue;
2101
+ let msgId = obj.payload?.message_id;
2102
+ if (msgId) {
2103
+ if (seen.has(msgId)) continue;
2104
+ seen.add(msgId);
2153
2105
  }
2106
+ let input = usage.input_other ?? 0, cached2 = usage.input_cache_read ?? 0, output = usage.output ?? 0;
2107
+ accumulate(
2108
+ dayMap,
2109
+ `${currentModel}|${projectFields.project}`,
2110
+ {
2111
+ provider: "moonshot",
2112
+ product: "kimi-code",
2113
+ channel: "cli",
2114
+ model: currentModel,
2115
+ project: projectFields.project,
2116
+ projectDisplay: projectFields.projectDisplay,
2117
+ projectAlias: projectFields.projectAlias,
2118
+ inputTokens: 0,
2119
+ cachedInputTokens: 0,
2120
+ cacheWriteTokens: 0,
2121
+ outputTokens: 0,
2122
+ reasoningOutputTokens: 0
2123
+ },
2124
+ { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
2125
+ );
2126
+ }
2127
+ }
2128
+ return finalize(grouped);
2129
+ }
2130
+ function resolveKimiProject(hash, workspaceMap, aliases2) {
2131
+ let wsPath = workspaceMap.get(hash);
2132
+ return wsPath ? resolveProjectFields(wsPath, aliases2) : resolveProjectFields(hash, aliases2);
2133
+ }
2134
+ async function loadWorkspaceMap(kimiHome) {
2135
+ let map = /* @__PURE__ */ new Map();
2136
+ try {
2137
+ let raw = await readFile8(join10(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
2138
+ if (config.workspaces)
2139
+ for (let [hash, info] of Object.entries(config.workspaces))
2140
+ info.path && map.set(hash, info.path);
2141
+ } catch {
2142
+ }
2143
+ return map;
2144
+ }
2145
+
2146
+ // src/scanners/amp.ts
2147
+ import { readFile as readFile9 } from "node:fs/promises";
2148
+ import { join as join11 } from "node:path";
2149
+ import { homedir as homedir10 } from "node:os";
2150
+ function resolveAmpDir(baseDir) {
2151
+ if (baseDir) return baseDir;
2152
+ let ampDataDir = process.env.AMP_DATA_DIR;
2153
+ if (ampDataDir) return join11(ampDataDir, "threads");
2154
+ let xdgDataHome = process.env.XDG_DATA_HOME;
2155
+ return xdgDataHome ? join11(xdgDataHome, "amp", "threads") : join11(homedir10(), ".local", "share", "amp", "threads");
2156
+ }
2157
+ async function scanAmpDates(targetDates, baseDir, _projectAliases) {
2158
+ let dates = new Set(targetDates), dir = resolveAmpDir(baseDir), threadFiles = (await walkFiles(dir, ".json")).filter((f) => {
2159
+ let name = f.split("/").pop() ?? "";
2160
+ return name.startsWith("T-") && name.endsWith(".json");
2161
+ });
2162
+ if (threadFiles.length === 0) return emptyResult(dates);
2163
+ let grouped = initDateMap(dates);
2164
+ for (let filePath of threadFiles) {
2165
+ let raw;
2166
+ try {
2167
+ raw = await readFile9(filePath, "utf-8");
2168
+ } catch {
2169
+ continue;
2170
+ }
2171
+ let thread;
2172
+ try {
2173
+ thread = JSON.parse(raw);
2174
+ } catch {
2175
+ continue;
2176
+ }
2177
+ let ledgerEvents = thread.usageLedger?.events;
2178
+ Array.isArray(ledgerEvents) && ledgerEvents.length > 0 ? processLedger(thread, ledgerEvents, dates, grouped) : processMessages(thread, dates, grouped);
2179
+ }
2180
+ return finalize(grouped);
2181
+ }
2182
+ function getMessageByKey(messages, key) {
2183
+ if (messages) {
2184
+ if (Array.isArray(messages)) {
2185
+ let idx = parseInt(key, 10);
2186
+ return isNaN(idx) ? void 0 : messages[idx];
2154
2187
  }
2188
+ return messages[key];
2155
2189
  }
2156
- };
2157
-
2158
- // ../shared/src/pricing/data/alibaba.ts
2159
- var alibaba = {
2160
- "qwen-code": {
2161
- models: {
2162
- "qwen3-coder-plus": {
2163
- currency: "CNY",
2164
- notes: "tiered by input length",
2165
- tiers: [
2166
- { threshold: 32e3, input_per_million: 4, output_per_million: 16 },
2167
- { threshold: 128e3, input_per_million: 6, output_per_million: 24 },
2168
- { threshold: 256e3, input_per_million: 10, output_per_million: 40 },
2169
- { input_per_million: 20, output_per_million: 200 }
2170
- ]
2171
- },
2172
- "qwen3-coder-flash": {
2173
- currency: "CNY",
2174
- tiers: [
2175
- { threshold: 32e3, input_per_million: 1, output_per_million: 4 },
2176
- { threshold: 128e3, input_per_million: 1.5, output_per_million: 6 },
2177
- { threshold: 256e3, input_per_million: 2, output_per_million: 8 },
2178
- { input_per_million: 3, output_per_million: 30 }
2179
- ]
2180
- },
2181
- "qwen-coder-plus": {
2182
- currency: "CNY",
2183
- input_per_million: 3.5,
2184
- output_per_million: 7
2185
- },
2186
- "qwen3-max": {
2187
- currency: "CNY",
2188
- tiers: [
2189
- { threshold: 32e3, input_per_million: 2.5, output_per_million: 10 },
2190
- { threshold: 128e3, input_per_million: 5, output_per_million: 20 },
2191
- { threshold: 256e3, input_per_million: 10, output_per_million: 100 }
2192
- ]
2193
- },
2194
- "qwen-max": {
2195
- currency: "CNY",
2196
- input_per_million: 2.4,
2197
- output_per_million: 9.6
2198
- },
2199
- "qwen-plus": {
2200
- currency: "CNY",
2201
- notes: "cache hit \xA50.8/M",
2202
- cached_input_per_million: 0.8,
2203
- input_per_million: 2,
2204
- output_per_million: 8
2205
- },
2206
- "qwen-turbo": {
2207
- currency: "CNY",
2208
- notes: "cache hit \xA50.3/M",
2209
- cached_input_per_million: 0.3,
2210
- input_per_million: 0.6,
2211
- output_per_million: 3
2212
- },
2213
- "qwen3-32b": {
2214
- currency: "CNY",
2215
- input_per_million: 2,
2216
- output_per_million: 8
2190
+ }
2191
+ function processLedger(thread, events, dates, grouped) {
2192
+ for (let event of events) {
2193
+ let ts = parseTs(event.timestamp);
2194
+ if (!ts) continue;
2195
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2196
+ if (!dayMap) continue;
2197
+ let model = event.model ?? "unknown", input = event.tokens?.input ?? 0, output = event.tokens?.output ?? 0, cached2 = 0;
2198
+ event.toMessageId && (cached2 = getMessageByKey(thread.messages, event.toMessageId)?.usage?.cacheReadInputTokens ?? 0), accumulate(
2199
+ dayMap,
2200
+ `${model}|unknown`,
2201
+ {
2202
+ provider: "sourcegraph",
2203
+ product: "amp",
2204
+ channel: "cli",
2205
+ model,
2206
+ project: "unknown",
2207
+ projectDisplay: "unknown",
2208
+ inputTokens: 0,
2209
+ cachedInputTokens: 0,
2210
+ cacheWriteTokens: 0,
2211
+ outputTokens: 0,
2212
+ reasoningOutputTokens: 0
2217
2213
  },
2218
- "qwen3-235b-a22b-thinking-2507": {
2219
- currency: "CNY",
2220
- input_per_million: 2,
2221
- output_per_million: 20
2214
+ { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
2215
+ );
2216
+ }
2217
+ }
2218
+ function processMessages(thread, dates, grouped) {
2219
+ let msgs2 = thread.messages;
2220
+ if (!msgs2) return;
2221
+ let entries = Array.isArray(msgs2) ? msgs2 : Object.values(msgs2);
2222
+ for (let msg of entries) {
2223
+ let usage = msg.usage;
2224
+ if (!usage) continue;
2225
+ let ts = parseTs(msg.timestamp ?? thread.created);
2226
+ if (!ts) continue;
2227
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2228
+ if (!dayMap) continue;
2229
+ let model = msg.model ?? "unknown", input = usage.inputTokens ?? 0, output = usage.outputTokens ?? 0, cached2 = usage.cacheReadInputTokens ?? 0;
2230
+ accumulate(
2231
+ dayMap,
2232
+ `${model}|unknown`,
2233
+ {
2234
+ provider: "sourcegraph",
2235
+ product: "amp",
2236
+ channel: "cli",
2237
+ model,
2238
+ project: "unknown",
2239
+ projectDisplay: "unknown",
2240
+ inputTokens: 0,
2241
+ cachedInputTokens: 0,
2242
+ cacheWriteTokens: 0,
2243
+ outputTokens: 0,
2244
+ reasoningOutputTokens: 0
2222
2245
  },
2223
- "qwen3-235b-a22b-instruct-2507": {
2224
- currency: "CNY",
2225
- input_per_million: 2,
2226
- output_per_million: 8
2227
- }
2228
- }
2246
+ { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
2247
+ );
2229
2248
  }
2230
- };
2249
+ }
2231
2250
 
2232
- // ../shared/src/pricing/data/deepseek.ts
2233
- var deepseek = {
2234
- "deepseek-chat": {
2235
- models: {
2236
- "deepseek-v4-flash": {
2237
- currency: "USD",
2238
- input_per_million: 0.14,
2239
- cached_input_per_million: 28e-4,
2240
- output_per_million: 0.28
2241
- },
2242
- "deepseek-v4-pro": {
2243
- currency: "USD",
2244
- notes: "75% off promo until 2026-05-31",
2245
- input_per_million: 0.435,
2246
- cached_input_per_million: 3625e-6,
2247
- output_per_million: 0.87,
2248
- effective_to: "2026-05-31"
2251
+ // src/scanners/droid.ts
2252
+ import { readFile as readFile10 } from "node:fs/promises";
2253
+ import { join as join12, dirname as dirname4, basename as basename6 } from "node:path";
2254
+ import { homedir as homedir11 } from "node:os";
2255
+ function extractProjectFromSlug(dirPath) {
2256
+ let parts = basename6(dirPath).split("-").filter(Boolean);
2257
+ return parts[parts.length - 1] || "unknown";
2258
+ }
2259
+ async function scanDroidDates(targetDates, baseDir, projectAliases) {
2260
+ let dates = new Set(targetDates), dir = baseDir ?? join12(homedir11(), ".factory", "sessions"), files = await walkFiles(dir, ".jsonl");
2261
+ if (files.length === 0) return emptyResult(dates);
2262
+ let grouped = initDateMap(dates);
2263
+ for (let jsonlPath of files) {
2264
+ let content;
2265
+ try {
2266
+ content = await readFile10(jsonlPath, "utf-8");
2267
+ } catch {
2268
+ continue;
2269
+ }
2270
+ let firstLine = content.split(`
2271
+ `).find((l) => l.trim());
2272
+ if (!firstLine) continue;
2273
+ let firstObj;
2274
+ try {
2275
+ firstObj = JSON.parse(firstLine);
2276
+ } catch {
2277
+ continue;
2278
+ }
2279
+ let ts = parseTs(firstObj.timestamp);
2280
+ if (!ts) continue;
2281
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2282
+ if (!dayMap) continue;
2283
+ let sessionDir = dirname4(jsonlPath), jsonlName = basename6(jsonlPath, ".jsonl"), settingsPath = join12(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
2284
+ try {
2285
+ settingsRaw = await readFile10(settingsPath, "utf-8");
2286
+ } catch {
2287
+ continue;
2288
+ }
2289
+ let settings;
2290
+ try {
2291
+ settings = JSON.parse(settingsRaw);
2292
+ } catch {
2293
+ continue;
2294
+ }
2295
+ let usage = settings.tokenUsage;
2296
+ if (!usage) continue;
2297
+ let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, rawOutput = usage.outputTokens ?? 0, thinking = usage.thinkingTokens ?? 0, input = Math.max(rawInput - cacheRead, 0), output = Math.max(rawOutput - thinking, 0), model = settings.model ?? "unknown", rawProject = extractProjectFromSlug(sessionDir), alias = projectAliases?.[rawProject], project = alias ?? rawProject;
2298
+ accumulate(
2299
+ dayMap,
2300
+ `${model}|${project}`,
2301
+ {
2302
+ provider: "droid",
2303
+ product: "droid",
2304
+ channel: "cli",
2305
+ model,
2306
+ project,
2307
+ projectDisplay: rawProject,
2308
+ projectAlias: alias,
2309
+ inputTokens: 0,
2310
+ cachedInputTokens: 0,
2311
+ cacheWriteTokens: 0,
2312
+ outputTokens: 0,
2313
+ reasoningOutputTokens: 0
2249
2314
  },
2250
- // 兼容别名(chat = v4-flash 非思考,reasoner = v4-flash 思考),按 v4-flash 同价计
2251
- "deepseek-chat": {
2252
- currency: "USD",
2253
- notes: "alias for v4-flash non-thinking",
2254
- input_per_million: 0.14,
2255
- cached_input_per_million: 28e-4,
2256
- output_per_million: 0.28
2315
+ { input, cached: cacheRead, cacheWrite: 0, output, reasoning: thinking }
2316
+ );
2317
+ }
2318
+ return finalize(grouped);
2319
+ }
2320
+
2321
+ // src/scanners/opencode.ts
2322
+ import { readFile as readFile11 } from "node:fs/promises";
2323
+ import { homedir as homedir12 } from "node:os";
2324
+ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
2325
+ let dates = new Set(targetDates), dir = baseDir ?? `${homedir12()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
2326
+ if (files.length === 0) return emptyResult(dates);
2327
+ let grouped = initDateMap(dates);
2328
+ for (let filePath of files) {
2329
+ let raw;
2330
+ try {
2331
+ raw = await readFile11(filePath, "utf-8");
2332
+ } catch {
2333
+ continue;
2334
+ }
2335
+ let msg;
2336
+ try {
2337
+ msg = JSON.parse(raw);
2338
+ } catch {
2339
+ continue;
2340
+ }
2341
+ let tokens = msg.tokens;
2342
+ if (!tokens) continue;
2343
+ let input = tokens.input ?? 0, output = tokens.output ?? 0;
2344
+ if (input === 0 && output === 0) continue;
2345
+ let ts = parseTs(msg.time?.created);
2346
+ if (!ts) continue;
2347
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2348
+ if (!dayMap) continue;
2349
+ let model = msg.modelID ?? "unknown", cached2 = tokens.cache?.read ?? 0, reasoning = tokens.reasoning ?? 0, rootPath = msg.path?.root, fields = rootPath ? resolveProjectFields(rootPath, projectAliases) : { project: "unknown", projectDisplay: "unknown" };
2350
+ accumulate(
2351
+ dayMap,
2352
+ `${model}|${fields.project}`,
2353
+ {
2354
+ provider: "opencode",
2355
+ product: "opencode",
2356
+ channel: "cli",
2357
+ model,
2358
+ project: fields.project,
2359
+ projectDisplay: fields.projectDisplay,
2360
+ projectAlias: fields.projectAlias,
2361
+ inputTokens: 0,
2362
+ cachedInputTokens: 0,
2363
+ cacheWriteTokens: 0,
2364
+ outputTokens: 0,
2365
+ reasoningOutputTokens: 0
2257
2366
  },
2258
- "deepseek-reasoner": {
2259
- currency: "USD",
2260
- notes: "alias for v4-flash thinking",
2261
- input_per_million: 0.14,
2262
- cached_input_per_million: 28e-4,
2263
- output_per_million: 0.28
2367
+ { input, cached: cached2, cacheWrite: 0, output, reasoning }
2368
+ );
2369
+ }
2370
+ return finalize(grouped);
2371
+ }
2372
+
2373
+ // src/scanners/pi.ts
2374
+ import { readFile as readFile12 } from "node:fs/promises";
2375
+ import { join as join13, basename as basename7, dirname as dirname5 } from "node:path";
2376
+ import { homedir as homedir13 } from "node:os";
2377
+ async function scanPiDates(targetDates, baseDir, projectAliases) {
2378
+ let dates = new Set(targetDates), sessionsDir = baseDir ?? getSessionsDir(), files = await walkFiles(sessionsDir, ".jsonl");
2379
+ if (files.length === 0) return emptyResult(dates);
2380
+ let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
2381
+ for (let filePath of files) {
2382
+ let content;
2383
+ try {
2384
+ content = await readFile12(filePath, "utf-8");
2385
+ } catch {
2386
+ continue;
2387
+ }
2388
+ let parentDir = dirname5(filePath), encodedCwd = basename7(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(encodedCwd) };
2389
+ for (let line of content.split(`
2390
+ `)) {
2391
+ if (!line.trim()) continue;
2392
+ let obj;
2393
+ try {
2394
+ obj = JSON.parse(line);
2395
+ } catch {
2396
+ continue;
2397
+ }
2398
+ if (obj.type === "session" && obj.cwd) {
2399
+ sessionProjectFields = resolveProjectFields(obj.cwd, projectAliases);
2400
+ continue;
2401
+ }
2402
+ if (obj.type !== "message") continue;
2403
+ let msg = obj.message;
2404
+ if (!msg || msg.role !== "assistant") continue;
2405
+ let usage = msg.usage;
2406
+ if (!usage || usage.input == null && usage.output == null) continue;
2407
+ let ts = parseTs(obj.timestamp);
2408
+ if (!ts) continue;
2409
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2410
+ if (!dayMap) continue;
2411
+ if (obj.id) {
2412
+ if (seen.has(obj.id)) continue;
2413
+ seen.add(obj.id);
2264
2414
  }
2415
+ let model = msg.model ?? "unknown", input = usage.input ?? 0, cached2 = usage.cacheRead ?? 0, output = usage.output ?? 0;
2416
+ accumulate(
2417
+ dayMap,
2418
+ `${model}|${sessionProjectFields.project}`,
2419
+ {
2420
+ provider: "inflection",
2421
+ product: "pi",
2422
+ channel: "cli",
2423
+ model,
2424
+ project: sessionProjectFields.project,
2425
+ projectDisplay: sessionProjectFields.projectDisplay,
2426
+ projectAlias: sessionProjectFields.projectAlias,
2427
+ inputTokens: 0,
2428
+ cachedInputTokens: 0,
2429
+ cacheWriteTokens: 0,
2430
+ outputTokens: 0,
2431
+ reasoningOutputTokens: 0
2432
+ },
2433
+ { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
2434
+ );
2265
2435
  }
2266
2436
  }
2267
- };
2437
+ return finalize(grouped);
2438
+ }
2439
+ function getSessionsDir() {
2440
+ let envDir = process.env.PI_CODING_AGENT_DIR;
2441
+ return envDir ? join13(envDir, "sessions") : join13(homedir13(), ".pi", "agent", "sessions");
2442
+ }
2443
+ function extractProjectFromEncoded(encoded) {
2444
+ let parts = encoded.split("-").filter(Boolean);
2445
+ return parts.length > 0 ? parts[parts.length - 1] : "unknown";
2446
+ }
2268
2447
 
2269
- // ../shared/src/pricing/data/zhipu.ts
2270
- var zhipu = {
2271
- "glm-chat": {
2272
- models: {
2273
- "glm-5.1": {
2274
- currency: "CNY",
2275
- tiers: [
2276
- { threshold: 32e3, input_per_million: 6, output_per_million: 24, cached_input_per_million: 1.3 },
2277
- { input_per_million: 8, output_per_million: 28, cached_input_per_million: 2 }
2278
- ]
2279
- },
2280
- "glm-5-turbo": {
2281
- currency: "CNY",
2282
- tiers: [
2283
- { threshold: 32e3, input_per_million: 5, output_per_million: 22, cached_input_per_million: 1.2 },
2284
- { input_per_million: 7, output_per_million: 26, cached_input_per_million: 1.8 }
2285
- ]
2286
- },
2287
- "glm-5": {
2288
- currency: "CNY",
2289
- tiers: [
2290
- { threshold: 32e3, input_per_million: 4, output_per_million: 18, cached_input_per_million: 1 },
2291
- { input_per_million: 6, output_per_million: 22, cached_input_per_million: 1.5 }
2292
- ]
2293
- },
2294
- "glm-4.7": {
2295
- currency: "CNY",
2296
- notes: "output<200 archetype; >200 doubles output rate",
2297
- tiers: [
2298
- { threshold: 32e3, input_per_million: 2, output_per_million: 8, cached_input_per_million: 0.4 },
2299
- { threshold: 2e5, input_per_million: 4, output_per_million: 16, cached_input_per_million: 0.8 }
2300
- ]
2301
- },
2302
- "glm-4.5-air": {
2303
- currency: "CNY",
2304
- tiers: [
2305
- { threshold: 32e3, input_per_million: 0.8, output_per_million: 2, cached_input_per_million: 0.16 },
2306
- { threshold: 128e3, input_per_million: 1.2, output_per_million: 8, cached_input_per_million: 0.24 }
2307
- ]
2308
- },
2309
- "glm-4.7-flashx": {
2310
- currency: "CNY",
2311
- input_per_million: 0.5,
2312
- cached_input_per_million: 0.1,
2313
- output_per_million: 3
2314
- },
2315
- "glm-4.7-flash": {
2316
- currency: "CNY",
2317
- notes: "free tier",
2318
- input_per_million: 0,
2319
- cached_input_per_million: 0,
2320
- output_per_million: 0
2321
- },
2322
- "glm-4-plus": {
2323
- currency: "CNY",
2324
- input_per_million: 5,
2325
- output_per_million: 5
2326
- },
2327
- "glm-4-air": {
2328
- currency: "CNY",
2329
- input_per_million: 0.5,
2330
- output_per_million: 0.5
2331
- },
2332
- "glm-4-airx": {
2333
- currency: "CNY",
2334
- input_per_million: 10,
2335
- output_per_million: 10
2336
- },
2337
- "glm-4-flashx-250414": {
2338
- currency: "CNY",
2339
- input_per_million: 0.1,
2340
- output_per_million: 0.1
2341
- },
2342
- "glm-4-long": {
2343
- currency: "CNY",
2344
- input_per_million: 1,
2345
- output_per_million: 1
2346
- },
2347
- "glm-4.5": {
2348
- currency: "CNY",
2349
- notes: "legacy, 128K context",
2350
- input_per_million: 4,
2351
- output_per_million: 16
2352
- },
2353
- "glm-4.6": {
2354
- currency: "CNY",
2355
- notes: "legacy, 200K context",
2356
- input_per_million: 4,
2357
- output_per_million: 16
2358
- }
2448
+ // src/scan.ts
2449
+ async function scanDate(targetDate, options = {}) {
2450
+ let [result] = await scanDates([targetDate], options);
2451
+ return result ?? {
2452
+ usageDate: targetDate,
2453
+ breakdowns: [],
2454
+ totals: createEmptyTotals()
2455
+ };
2456
+ }
2457
+ async function scanDates(targetDates, options = {}) {
2458
+ let uniqueDates = [...new Set(targetDates)];
2459
+ if (uniqueDates.length === 0) return [];
2460
+ let scanners = [
2461
+ scanAntigravityDates(uniqueDates),
2462
+ scanClaudeDates(uniqueDates, void 0, options.projectAliases),
2463
+ scanCodexDates(uniqueDates, void 0, options.projectAliases),
2464
+ scanCopilotDates(uniqueDates, void 0, options.projectAliases),
2465
+ scanCopilotVscodeDates(uniqueDates, void 0, options.projectAliases),
2466
+ scanCursorDates(uniqueDates),
2467
+ scanGeminiDates(uniqueDates, void 0, options.projectAliases),
2468
+ scanQwenDates(uniqueDates, void 0, options.projectAliases),
2469
+ scanKimiDates(uniqueDates, void 0, options.projectAliases),
2470
+ scanAmpDates(uniqueDates, void 0, options.projectAliases),
2471
+ scanDroidDates(uniqueDates, void 0, options.projectAliases),
2472
+ scanOpencodeDates(uniqueDates, void 0, options.projectAliases),
2473
+ scanPiDates(uniqueDates, void 0, options.projectAliases)
2474
+ ], results = await Promise.all(scanners);
2475
+ return uniqueDates.map((usageDate) => {
2476
+ let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []), totals = breakdowns.reduce(
2477
+ (acc, b) => ({
2478
+ eventCount: acc.eventCount + b.eventCount,
2479
+ inputTokens: acc.inputTokens + b.inputTokens,
2480
+ cachedInputTokens: acc.cachedInputTokens + b.cachedInputTokens,
2481
+ cacheWriteTokens: acc.cacheWriteTokens + b.cacheWriteTokens,
2482
+ outputTokens: acc.outputTokens + b.outputTokens,
2483
+ reasoningOutputTokens: acc.reasoningOutputTokens + b.reasoningOutputTokens
2484
+ }),
2485
+ createEmptyTotals()
2486
+ );
2487
+ return { usageDate, breakdowns, totals };
2488
+ });
2489
+ }
2490
+ function createEmptyTotals() {
2491
+ return {
2492
+ eventCount: 0,
2493
+ inputTokens: 0,
2494
+ cachedInputTokens: 0,
2495
+ cacheWriteTokens: 0,
2496
+ outputTokens: 0,
2497
+ reasoningOutputTokens: 0
2498
+ };
2499
+ }
2500
+
2501
+ // src/scanners/anthropic-admin-api.ts
2502
+ var ADMIN_API_BASE = "https://api.anthropic.com", USAGE_ENDPOINT = "/v1/organizations/usage_report/messages", MAX_DAYS_PER_REQUEST = 31;
2503
+ async function scanAnthropicApiDates(targetDates, adminApiKey) {
2504
+ if (!targetDates.length || !adminApiKey)
2505
+ return new Map(targetDates.map((d) => [d, []]));
2506
+ let sorted = [...new Set(targetDates)].sort(), grouped = new Map(sorted.map((d) => [d, []])), chunks = chunkDateRange(sorted[0], sorted[sorted.length - 1]);
2507
+ for (let { startingAt, endingAt } of chunks)
2508
+ await fetchAndMerge(startingAt, endingAt, adminApiKey, sorted, grouped);
2509
+ return grouped;
2510
+ }
2511
+ async function fetchAndMerge(startingAt, endingAt, adminApiKey, targetDates, grouped) {
2512
+ let nextPage = null;
2513
+ do {
2514
+ let url = buildUrl(startingAt, endingAt, nextPage), resp;
2515
+ try {
2516
+ resp = await fetch(url, {
2517
+ headers: {
2518
+ "x-api-key": adminApiKey,
2519
+ "anthropic-version": "2023-06-01"
2520
+ }
2521
+ });
2522
+ } catch (err) {
2523
+ throw new Error(`Anthropic Admin API request failed: ${err}`);
2359
2524
  }
2360
- }
2361
- };
2362
-
2363
- // ../shared/src/pricing/data/github.ts
2364
- var github = {
2365
- // copilot-vscode 仅事件计数(日志里无 token 数),保留空 models 不算费用
2366
- "copilot-vscode": { models: {} },
2367
- "copilot-cli": {
2368
- models: {
2369
- "gpt-4o": { currency: "USD", input_per_million: 2.5, cached_input_per_million: 1.25, output_per_million: 10 },
2370
- "gpt-4o-mini": { currency: "USD", input_per_million: 0.15, cached_input_per_million: 0.075, output_per_million: 0.6 },
2371
- "claude-sonnet-4": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
2372
- "claude-sonnet-4-6": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
2373
- "o3-mini": { currency: "USD", input_per_million: 1.1, cached_input_per_million: 0.55, output_per_million: 4.4 },
2374
- "gemini-2.0-flash": { currency: "USD", input_per_million: 0.1, cached_input_per_million: 0.025, output_per_million: 0.4 }
2525
+ if (!resp.ok) {
2526
+ let body = await resp.text().catch(() => "");
2527
+ throw new Error(`Anthropic Admin API error ${resp.status}: ${body}`);
2375
2528
  }
2376
- }
2377
- };
2378
-
2379
- // ../shared/src/pricing/data/sourcegraph.ts
2380
- var sourcegraph = {
2381
- amp: {
2382
- models: {
2383
- "claude-sonnet-4": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
2384
- "claude-sonnet-3.7": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
2385
- "gemini-2.5-pro": { currency: "USD", input_per_million: 1.25, cached_input_per_million: 0.125, output_per_million: 10 }
2529
+ let data = await resp.json();
2530
+ for (let bucket of data.data) {
2531
+ let date = bucket.starting_at.slice(0, 10);
2532
+ if (!targetDates.includes(date)) continue;
2533
+ let breakdowns = grouped.get(date);
2534
+ for (let result of bucket.results) {
2535
+ if (!result.model) continue;
2536
+ let model = normalizeModelName(result.model), inputTokens = result.uncached_input_tokens ?? 0, cachedInputTokens = result.cache_read_input_tokens ?? 0, cacheWrite5m = result.cache_creation?.ephemeral_5m_input_tokens ?? 0, cacheWrite1h = result.cache_creation?.ephemeral_1h_input_tokens ?? 0, cacheWriteTokens = cacheWrite5m + cacheWrite1h, outputTokens = result.output_tokens ?? 0;
2537
+ if (inputTokens + outputTokens + cachedInputTokens + cacheWriteTokens === 0) continue;
2538
+ let existing = breakdowns.find((b) => b.model === model);
2539
+ existing ? (existing.eventCount += 1, existing.inputTokens += inputTokens, existing.cachedInputTokens += cachedInputTokens, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + cacheWrite5m, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + cacheWrite1h, existing.outputTokens += outputTokens) : breakdowns.push({
2540
+ provider: "anthropic",
2541
+ product: "claude-code",
2542
+ channel: "cli",
2543
+ model,
2544
+ project: "unknown",
2545
+ eventCount: 1,
2546
+ inputTokens,
2547
+ cachedInputTokens,
2548
+ cacheWriteTokens,
2549
+ cacheWrite5mTokens: cacheWrite5m,
2550
+ cacheWrite1hTokens: cacheWrite1h,
2551
+ outputTokens,
2552
+ reasoningOutputTokens: 0
2553
+ });
2554
+ }
2386
2555
  }
2387
- }
2388
- };
2389
-
2390
- // ../shared/src/pricing/data/placeholders.ts
2391
- var inflection = {
2392
- pi: { models: {} }
2393
- }, cursor = {
2394
- cursor: { models: {} }
2395
- }, droid = {
2396
- droid: { models: {} }
2397
- }, opencode = {
2398
- opencode: { models: {} }
2399
- };
2400
-
2401
- // ../shared/src/pricing/catalog.ts
2402
- var PRICING_VERSION = "2026-06-22-codex-tier-v1", aliases = {
2403
- "claude-opus-4-7-20260201": "claude-opus-4-7",
2404
- "claude-sonnet-4-6-20250301": "claude-sonnet-4-6",
2405
- "claude-opus-4-6-20250301": "claude-opus-4-6",
2406
- "claude-haiku-4-5-20251001": "claude-haiku-4-5",
2407
- "claude-sonnet-4.6": "claude-sonnet-4-6",
2408
- "codex-auto-review": "gpt-5.4"
2409
- }, catalog = {
2410
- version: PRICING_VERSION,
2411
- // 汇率(1 USD ≈ N CNY)。Worker 启动时可被 env 覆盖。
2412
- fx: {
2413
- CNY: 7.2
2414
- },
2415
- aliases,
2416
- providers: {
2417
- anthropic,
2418
- openai,
2419
- google,
2420
- moonshot,
2421
- alibaba,
2422
- deepseek,
2423
- zhipu,
2424
- github,
2425
- sourcegraph,
2426
- inflection,
2427
- cursor,
2428
- droid,
2429
- opencode
2430
- }
2431
- };
2432
-
2433
- // ../shared/src/pricing/calculate.ts
2434
- var ANTHROPIC_FAST_MULTIPLIER = 6, FAST_SUPPORTED = /* @__PURE__ */ new Set([
2435
- "claude-opus-4-8",
2436
- "claude-opus-4-7",
2437
- "claude-opus-4-6"
2438
- ]), OPENAI_CODEX_TIER_MULTIPLIERS = {
2439
- "gpt-5.5": 2.5,
2440
- "gpt-5.4": 2
2441
- };
2442
- function splitServiceTierSuffix(model) {
2443
- return model.endsWith("-priority") ? { baseModel: model.replace(/-priority$/, ""), tier: "priority" } : model.endsWith("-fast") ? { baseModel: model.replace(/-fast$/, ""), tier: "fast" } : { baseModel: model, tier: null };
2556
+ nextPage = data.has_more ? data.next_page : null;
2557
+ } while (nextPage);
2444
2558
  }
2445
- function getServiceTierMultiplier(provider, product, resolvedModel, tier) {
2446
- return tier ? provider === "openai" && product === "codex" ? OPENAI_CODEX_TIER_MULTIPLIERS[resolvedModel] ?? 1 : tier === "fast" && FAST_SUPPORTED.has(resolvedModel) ? ANTHROPIC_FAST_MULTIPLIER : 1 : 1;
2559
+ function buildUrl(startingAt, endingAt, page) {
2560
+ let params = new URLSearchParams({
2561
+ starting_at: startingAt,
2562
+ ending_at: endingAt,
2563
+ bucket_width: "1d"
2564
+ });
2565
+ return params.append("group_by[]", "model"), page && params.set("page", page), `${ADMIN_API_BASE}${USAGE_ENDPOINT}?${params}`;
2447
2566
  }
2448
- function resolveModelPricing(catalog2, provider, product, model) {
2449
- let models = catalog2.providers[provider]?.[product]?.models;
2450
- if (!models) return null;
2451
- let aliasResolved = catalog2.aliases[model];
2452
- if (aliasResolved && models[aliasResolved])
2453
- return { resolvedModel: aliasResolved, pricing: models[aliasResolved], normalized: !1 };
2454
- if (models[model])
2455
- return { resolvedModel: model, pricing: models[model], normalized: !1 };
2456
- for (let knownModel of Object.keys(models).sort((a, b) => b.length - a.length)) {
2457
- if (!model.startsWith(`${knownModel}-`)) continue;
2458
- let suffix = model.slice(knownModel.length + 1);
2459
- if (!/^\d+(?:[-.]\d+)*(?:-\d{6,8})?$/.test(suffix))
2460
- return { resolvedModel: knownModel, pricing: models[knownModel], normalized: !0 };
2567
+ function chunkDateRange(startDate, endDate) {
2568
+ let chunks = [], current = /* @__PURE__ */ new Date(`${startDate}T00:00:00Z`), end = /* @__PURE__ */ new Date(`${endDate}T00:00:00Z`);
2569
+ for (end.setUTCDate(end.getUTCDate() + 1); current < end; ) {
2570
+ let chunkEnd = new Date(current);
2571
+ chunkEnd.setUTCDate(chunkEnd.getUTCDate() + MAX_DAYS_PER_REQUEST);
2572
+ let actualEnd = chunkEnd < end ? chunkEnd : end;
2573
+ chunks.push({
2574
+ startingAt: current.toISOString().replace(".000Z", "Z"),
2575
+ endingAt: actualEnd.toISOString().replace(".000Z", "Z")
2576
+ }), current = actualEnd;
2461
2577
  }
2462
- return null;
2578
+ return chunks;
2463
2579
  }
2464
- function selectTier(tiers, totalInputTokens) {
2465
- for (let i = 0; i < tiers.length; i += 1) {
2466
- let t2 = tiers[i];
2467
- if (t2.threshold === void 0 || totalInputTokens <= t2.threshold)
2468
- return { tier: t2, index: i };
2580
+
2581
+ // src/scanners/anthropic-csv.ts
2582
+ import { readFile as readFile13 } from "node:fs/promises";
2583
+ async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
2584
+ if (!targetDates.length) return /* @__PURE__ */ new Map();
2585
+ let targetDateSet = new Set(targetDates), grouped = new Map(
2586
+ targetDates.map((d) => [d, /* @__PURE__ */ new Map()])
2587
+ );
2588
+ for (let filePath of csvFilePaths) {
2589
+ let content;
2590
+ try {
2591
+ content = await readFile13(filePath, "utf-8");
2592
+ } catch {
2593
+ continue;
2594
+ }
2595
+ let rows = parseCsv(content);
2596
+ for (let row of rows) {
2597
+ if (!targetDateSet.has(row.usage_date_utc) || row.usage_input_tokens_no_cache + row.usage_input_tokens_cache_write_5m + row.usage_input_tokens_cache_write_1h + row.usage_input_tokens_cache_read + row.usage_output_tokens === 0) continue;
2598
+ let model = normalizeModelName(row.model_version), product = workspaceToProduct(row.workspace), key = `${model}|${product}`, byModel = grouped.get(row.usage_date_utc), existing = byModel.get(key), cacheWriteTokens = row.usage_input_tokens_cache_write_5m + row.usage_input_tokens_cache_write_1h;
2599
+ existing ? (existing.eventCount += 1, existing.inputTokens += row.usage_input_tokens_no_cache, existing.cachedInputTokens += row.usage_input_tokens_cache_read, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + row.usage_input_tokens_cache_write_5m, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + row.usage_input_tokens_cache_write_1h, existing.outputTokens += row.usage_output_tokens) : byModel.set(key, {
2600
+ provider: "anthropic",
2601
+ product,
2602
+ channel: "cli",
2603
+ model,
2604
+ project: "unknown",
2605
+ eventCount: 1,
2606
+ inputTokens: row.usage_input_tokens_no_cache,
2607
+ cachedInputTokens: row.usage_input_tokens_cache_read,
2608
+ cacheWriteTokens,
2609
+ cacheWrite5mTokens: row.usage_input_tokens_cache_write_5m,
2610
+ cacheWrite1hTokens: row.usage_input_tokens_cache_write_1h,
2611
+ outputTokens: row.usage_output_tokens,
2612
+ reasoningOutputTokens: 0
2613
+ });
2614
+ }
2469
2615
  }
2470
- return { tier: tiers[tiers.length - 1], index: tiers.length - 1 };
2616
+ return new Map(
2617
+ [...grouped.entries()].map(([date, byModel]) => [date, [...byModel.values()]])
2618
+ );
2471
2619
  }
2472
- function toUsd(amount, currency, catalog2) {
2473
- if (currency === "USD") return amount;
2474
- let rate = catalog2.fx[currency];
2475
- return rate ? amount / rate : amount;
2620
+ function workspaceToProduct(workspace) {
2621
+ let w = workspace.trim().toLowerCase();
2622
+ return "claude-code";
2476
2623
  }
2477
- function calculateCost(provider, product, model, tokens, options = {}) {
2478
- let cat = options.catalog ?? catalog;
2479
- if (tokens.inputTokens + tokens.cachedInputTokens + tokens.cacheWriteTokens + tokens.outputTokens === 0)
2480
- return { estimatedCostUsd: 0, costStatus: "exact", pricingVersion: cat.version };
2481
- let { baseModel, tier } = splitServiceTierSuffix(model), resolved = resolveModelPricing(cat, provider, product, baseModel);
2482
- if (!resolved)
2483
- return { estimatedCostUsd: 0, costStatus: "unavailable", pricingVersion: cat.version };
2484
- let { resolvedModel, pricing, normalized } = resolved, costStatus = normalized ? "estimated" : "exact", unit, matchedTierIndex;
2485
- if (pricing.tiers && pricing.tiers.length > 0) {
2486
- let totalIn = tokens.inputTokens + tokens.cachedInputTokens + tokens.cacheWriteTokens, { tier: tier2, index } = selectTier(pricing.tiers, totalIn);
2487
- unit = tier2, matchedTierIndex = index;
2488
- } else
2489
- unit = {
2490
- input_per_million: pricing.input_per_million ?? 0,
2491
- output_per_million: pricing.output_per_million ?? 0,
2492
- cached_input_per_million: pricing.cached_input_per_million ?? null,
2493
- cache_write_5m_per_million: pricing.cache_write_5m_per_million ?? 0,
2494
- cache_write_1h_per_million: pricing.cache_write_1h_per_million ?? 0
2495
- };
2496
- let cw5Rate = unit.cache_write_5m_per_million ?? pricing.cache_write_5m_per_million ?? 0, cw1hRate = unit.cache_write_1h_per_million ?? pricing.cache_write_1h_per_million ?? 0, cachedRate = unit.cached_input_per_million ?? pricing.cached_input_per_million ?? 0, raw = tokens.inputTokens / 1e6 * (unit.input_per_million ?? 0) + tokens.cachedInputTokens / 1e6 * (cachedRate ?? 0) + (tokens.cacheWrite5mTokens ?? tokens.cacheWriteTokens) / 1e6 * cw5Rate + (tokens.cacheWrite1hTokens ?? 0) / 1e6 * cw1hRate + tokens.outputTokens / 1e6 * (unit.output_per_million ?? 0);
2497
- raw = toUsd(raw, pricing.currency, cat);
2498
- let finalCost = raw * getServiceTierMultiplier(provider, product, resolvedModel, tier);
2499
- return {
2500
- estimatedCostUsd: Math.round(finalCost * 1e4) / 1e4,
2501
- costStatus,
2502
- pricingVersion: cat.version,
2503
- resolvedModel,
2504
- matchedTierIndex
2505
- };
2624
+ function parseCsv(content) {
2625
+ let lines = content.split(`
2626
+ `).map((l) => l.trim()).filter(Boolean);
2627
+ if (lines.length < 2) return [];
2628
+ let headers = lines[0].split(",").map((h) => h.trim()), rows = [];
2629
+ for (let i = 1; i < lines.length; i++) {
2630
+ let values = lines[i].split(","), row = {};
2631
+ for (let j = 0; j < headers.length; j++)
2632
+ row[headers[j]] = values[j]?.trim() ?? "";
2633
+ let date = row.usage_date_utc;
2634
+ !date || !/^\d{4}-\d{2}-\d{2}$/.test(date) || rows.push({
2635
+ usage_date_utc: date,
2636
+ model_version: row.model_version ?? "",
2637
+ workspace: row.workspace ?? "",
2638
+ usage_input_tokens_no_cache: parseInt(row.usage_input_tokens_no_cache ?? "0", 10) || 0,
2639
+ usage_input_tokens_cache_write_5m: parseInt(row.usage_input_tokens_cache_write_5m ?? "0", 10) || 0,
2640
+ usage_input_tokens_cache_write_1h: parseInt(row.usage_input_tokens_cache_write_1h ?? "0", 10) || 0,
2641
+ usage_input_tokens_cache_read: parseInt(row.usage_input_tokens_cache_read ?? "0", 10) || 0,
2642
+ usage_output_tokens: parseInt(row.usage_output_tokens ?? "0", 10) || 0
2643
+ });
2644
+ }
2645
+ return rows;
2506
2646
  }
2507
2647
 
2508
2648
  // src/report.ts
2649
+ import { readdir as readdir6, readFile as readFile14 } from "node:fs/promises";
2650
+ import { homedir as homedir14 } from "node:os";
2651
+ import { basename as basename8, join as join14 } from "node:path";
2509
2652
  async function buildLocalReport(range, options = {}) {
2510
2653
  let requestedDates = options.dates ? options.dates : range === "all" ? await discoverAllDates() : range === "today" ? [dateKey(getTodayLocalDate())] : buildPresetDates(range), daily = [], totals = createEmptyTotals2(), bySource = /* @__PURE__ */ new Map(), byModel = /* @__PURE__ */ new Map(), pricingWarnings = /* @__PURE__ */ new Set(), daysWithData = 0, results = await scanDates(requestedDates, { projectAliases: options.projectAliases });
2511
2654
  for (let result of results) {
@@ -2891,7 +3034,8 @@ function toBreakdownTotals(breakdown, warnings, pricingCatalog) {
2891
3034
  };
2892
3035
  }
2893
3036
  function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
2894
- if (breakdown.costUSD != null && breakdown.costUSD > 0)
3037
+ let effectivePricingVersion = pricingCatalog?.version ?? PRICING_VERSION, sourceCostMatchesCatalog = breakdown.pricingVersion == null || breakdown.pricingVersion === effectivePricingVersion;
3038
+ if (breakdown.costUSD != null && breakdown.costUSD > 0 && sourceCostMatchesCatalog)
2895
3039
  return breakdown.costUSD;
2896
3040
  let result = calculateCost(
2897
3041
  breakdown.provider,
@@ -2905,9 +3049,12 @@ function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
2905
3049
  cacheWrite1hTokens: breakdown.cacheWrite1hTokens,
2906
3050
  outputTokens: breakdown.outputTokens
2907
3051
  },
2908
- pricingCatalog ? { catalog: pricingCatalog } : {}
3052
+ {
3053
+ ...pricingCatalog ? { catalog: pricingCatalog } : {},
3054
+ requestCount: breakdown.eventCount
3055
+ }
2909
3056
  );
2910
- return result.costStatus === "unavailable" ? warnings.add(`${breakdown.provider}/${breakdown.product}/${breakdown.model} \u6682\u65E0\u5B9A\u4EF7\u914D\u7F6E\uFF0C\u5DF2\u8DF3\u8FC7\u6210\u672C\u4F30\u7B97\u3002`) : result.costStatus === "estimated" && result.resolvedModel && result.resolvedModel !== breakdown.model && warnings.add(`${breakdown.model} \u5DF2\u6309 ${result.resolvedModel} \u7684\u516C\u5F00\u5355\u4EF7\u4F30\u7B97\u3002`), result.estimatedCostUsd;
3057
+ return result.costStatus === "unavailable" ? warnings.add(`${breakdown.provider}/${breakdown.product}/${breakdown.model} \u6682\u65E0\u5B9A\u4EF7\u914D\u7F6E\uFF0C\u5DF2\u8DF3\u8FC7\u6210\u672C\u4F30\u7B97\u3002`) : result.costStatus === "estimated" && result.resolvedModel && result.resolvedModel !== breakdown.model ? warnings.add(`${breakdown.model} \u5DF2\u6309 ${result.resolvedModel} \u7684\u516C\u5F00\u5355\u4EF7\u4F30\u7B97\u3002`) : result.costStatus === "estimated" && result.matchedTierIndex !== void 0 && warnings.add(`${breakdown.model} \u7684\u9636\u68AF\u4EF7\u683C\u5DF2\u6309\u6BCF\u4E8B\u4EF6\u5E73\u5747\u8F93\u5165\u91CF\u4F30\u7B97\u3002`), result.estimatedCostUsd;
2911
3058
  }
2912
3059
 
2913
3060
  // src/i18n.ts