@aiusage/cli 1.7.1 → 1.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -370,679 +370,1233 @@ 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 }
780
+ }
781
+ }
782
+ };
783
+
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
+ }
564
959
  }
565
960
  }
566
- return finalize(grouped);
567
- }
961
+ };
568
962
 
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
- ));
612
- }
613
- }
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
963
+ // ../shared/src/pricing/data/moonshot.ts
964
+ var moonshot = {
965
+ "kimi-code": {
966
+ models: {
967
+ "kimi-k3": {
968
+ currency: "CNY",
969
+ effective_from: "2026-07-17",
970
+ input_per_million: 20,
971
+ cached_input_per_million: 2,
972
+ cache_write_per_million: 20,
973
+ output_per_million: 100
974
+ },
975
+ "kimi-k2.7-code": {
976
+ currency: "CNY",
977
+ input_per_million: 6.5,
978
+ cached_input_per_million: 1.3,
979
+ cache_write_per_million: 6.5,
980
+ output_per_million: 27
981
+ },
982
+ "kimi-k2.7-code-highspeed": {
983
+ currency: "CNY",
984
+ input_per_million: 13,
985
+ cached_input_per_million: 2.6,
986
+ cache_write_per_million: 13,
987
+ output_per_million: 54
988
+ },
989
+ "kimi-k2.6": {
990
+ currency: "CNY",
991
+ input_per_million: 6.5,
992
+ cached_input_per_million: 1.1,
993
+ cache_write_per_million: 6.5,
994
+ output_per_million: 27
995
+ },
996
+ "kimi-k2.5": {
997
+ currency: "CNY",
998
+ input_per_million: 4,
999
+ cached_input_per_million: 0.7,
1000
+ cache_write_per_million: 4,
1001
+ output_per_million: 21
1002
+ },
1003
+ "kimi-k2-0905-preview": {
1004
+ currency: "CNY",
1005
+ notes: "will be retired 2026-05-25",
1006
+ input_per_million: 4,
1007
+ cached_input_per_million: 1,
1008
+ cache_write_per_million: 4,
1009
+ output_per_million: 16
1010
+ },
1011
+ "kimi-k2-0711-preview": {
1012
+ currency: "CNY",
1013
+ notes: "will be retired 2026-05-25",
1014
+ input_per_million: 4,
1015
+ cached_input_per_million: 1,
1016
+ cache_write_per_million: 4,
1017
+ output_per_million: 16
1018
+ },
1019
+ "kimi-k2-turbo-preview": {
1020
+ currency: "CNY",
1021
+ notes: "will be retired 2026-05-25",
1022
+ input_per_million: 8,
1023
+ cached_input_per_million: 1,
1024
+ cache_write_per_million: 8,
1025
+ output_per_million: 58
1026
+ },
1027
+ "kimi-k2-thinking": {
1028
+ currency: "CNY",
1029
+ input_per_million: 4,
1030
+ cached_input_per_million: 1,
1031
+ cache_write_per_million: 4,
1032
+ output_per_million: 16
1033
+ },
1034
+ "kimi-k2-thinking-turbo": {
1035
+ currency: "CNY",
1036
+ input_per_million: 8,
1037
+ cached_input_per_million: 1,
1038
+ cache_write_per_million: 8,
1039
+ output_per_million: 58
1040
+ },
1041
+ "moonshot-v1-8k": {
1042
+ currency: "CNY",
1043
+ input_per_million: 2,
1044
+ cache_write_per_million: 2,
1045
+ output_per_million: 10
1046
+ },
1047
+ "moonshot-v1-32k": {
1048
+ currency: "CNY",
1049
+ input_per_million: 5,
1050
+ cache_write_per_million: 5,
1051
+ output_per_million: 20
1052
+ },
1053
+ "moonshot-v1-128k": {
1054
+ currency: "CNY",
1055
+ input_per_million: 10,
1056
+ cache_write_per_million: 10,
1057
+ output_per_million: 30
1058
+ },
1059
+ "moonshot-v1-8k-vision-preview": {
1060
+ currency: "CNY",
1061
+ input_per_million: 2,
1062
+ cache_write_per_million: 2,
1063
+ output_per_million: 10
679
1064
  },
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;
690
- }
691
- try {
692
- let raw = JSON.parse(content).folder;
693
- return raw?.startsWith("file:///") ? decodeURIComponent(raw.replace(/^file:\/\//, "")) : null;
694
- } catch {
695
- return null;
1065
+ "moonshot-v1-32k-vision-preview": {
1066
+ currency: "CNY",
1067
+ input_per_million: 5,
1068
+ cache_write_per_million: 5,
1069
+ output_per_million: 20
1070
+ },
1071
+ "moonshot-v1-128k-vision-preview": {
1072
+ currency: "CNY",
1073
+ input_per_million: 10,
1074
+ cache_write_per_million: 10,
1075
+ output_per_million: 30
1076
+ }
1077
+ }
696
1078
  }
697
- }
698
- function normalizeWorkspaceModel(raw) {
699
- return raw ? raw.replace(/^copilot\//, "").trim() : "";
700
- }
1079
+ };
701
1080
 
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);
1081
+ // ../shared/src/pricing/data/alibaba.ts
1082
+ var alibaba = {
1083
+ "qwen-code": {
1084
+ models: {
1085
+ "qwen3-coder-plus": {
1086
+ currency: "CNY",
1087
+ notes: "tiered by input length",
1088
+ tiers: [
1089
+ { threshold: 32e3, input_per_million: 4, output_per_million: 16 },
1090
+ { threshold: 128e3, input_per_million: 6, output_per_million: 24 },
1091
+ { threshold: 256e3, input_per_million: 10, output_per_million: 40 },
1092
+ { input_per_million: 20, output_per_million: 200 }
1093
+ ]
1094
+ },
1095
+ "qwen3-coder-flash": {
1096
+ currency: "CNY",
1097
+ tiers: [
1098
+ { threshold: 32e3, input_per_million: 1, output_per_million: 4 },
1099
+ { threshold: 128e3, input_per_million: 1.5, output_per_million: 6 },
1100
+ { threshold: 256e3, input_per_million: 2, output_per_million: 8 },
1101
+ { input_per_million: 3, output_per_million: 30 }
1102
+ ]
1103
+ },
1104
+ "qwen-coder-plus": {
1105
+ currency: "CNY",
1106
+ input_per_million: 3.5,
1107
+ output_per_million: 7
1108
+ },
1109
+ "qwen3-max": {
1110
+ currency: "CNY",
1111
+ tiers: [
1112
+ { threshold: 32e3, input_per_million: 2.5, output_per_million: 10 },
1113
+ { threshold: 128e3, input_per_million: 5, output_per_million: 20 },
1114
+ { threshold: 256e3, input_per_million: 10, output_per_million: 100 }
1115
+ ]
1116
+ },
1117
+ "qwen-max": {
1118
+ currency: "CNY",
1119
+ input_per_million: 2.4,
1120
+ output_per_million: 9.6
1121
+ },
1122
+ "qwen-plus": {
1123
+ currency: "CNY",
1124
+ notes: "cache hit \xA50.8/M",
1125
+ cached_input_per_million: 0.8,
1126
+ input_per_million: 2,
1127
+ output_per_million: 8
1128
+ },
1129
+ "qwen-turbo": {
1130
+ currency: "CNY",
1131
+ notes: "cache hit \xA50.3/M",
1132
+ cached_input_per_million: 0.3,
1133
+ input_per_million: 0.6,
1134
+ output_per_million: 3
1135
+ },
1136
+ "qwen3-32b": {
1137
+ currency: "CNY",
1138
+ input_per_million: 2,
1139
+ output_per_million: 8
1140
+ },
1141
+ "qwen3-235b-a22b-thinking-2507": {
1142
+ currency: "CNY",
1143
+ input_per_million: 2,
1144
+ output_per_million: 20
1145
+ },
1146
+ "qwen3-235b-a22b-instruct-2507": {
1147
+ currency: "CNY",
1148
+ input_per_million: 2,
1149
+ output_per_million: 8
1150
+ }
1151
+ }
714
1152
  }
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;
1153
+ };
1154
+
1155
+ // ../shared/src/pricing/data/deepseek.ts
1156
+ var deepseek = {
1157
+ "deepseek-chat": {
1158
+ models: {
1159
+ "deepseek-v4-flash": {
1160
+ currency: "USD",
1161
+ input_per_million: 0.14,
1162
+ cached_input_per_million: 28e-4,
1163
+ output_per_million: 0.28
1164
+ },
1165
+ "deepseek-v4-pro": {
1166
+ currency: "USD",
1167
+ notes: "75% off promo until 2026-05-31",
1168
+ input_per_million: 0.435,
1169
+ cached_input_per_million: 3625e-6,
1170
+ output_per_million: 0.87,
1171
+ effective_to: "2026-05-31"
1172
+ },
1173
+ // 兼容别名(chat = v4-flash 非思考,reasoner = v4-flash 思考),按 v4-flash 同价计
1174
+ "deepseek-chat": {
1175
+ currency: "USD",
1176
+ notes: "alias for v4-flash non-thinking",
1177
+ input_per_million: 0.14,
1178
+ cached_input_per_million: 28e-4,
1179
+ output_per_million: 0.28
1180
+ },
1181
+ "deepseek-reasoner": {
1182
+ currency: "USD",
1183
+ notes: "alias for v4-flash thinking",
1184
+ input_per_million: 0.14,
1185
+ cached_input_per_million: 28e-4,
1186
+ output_per_million: 0.28
1187
+ }
1188
+ }
723
1189
  }
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();
1190
+ };
1191
+
1192
+ // ../shared/src/pricing/data/zhipu.ts
1193
+ var zhipu = {
1194
+ "glm-chat": {
1195
+ models: {
1196
+ "glm-5.1": {
1197
+ currency: "CNY",
1198
+ tiers: [
1199
+ { threshold: 32e3, input_per_million: 6, output_per_million: 24, cached_input_per_million: 1.3 },
1200
+ { input_per_million: 8, output_per_million: 28, cached_input_per_million: 2 }
1201
+ ]
1202
+ },
1203
+ "glm-5-turbo": {
1204
+ currency: "CNY",
1205
+ tiers: [
1206
+ { threshold: 32e3, input_per_million: 5, output_per_million: 22, cached_input_per_million: 1.2 },
1207
+ { input_per_million: 7, output_per_million: 26, cached_input_per_million: 1.8 }
1208
+ ]
1209
+ },
1210
+ "glm-5": {
1211
+ currency: "CNY",
1212
+ tiers: [
1213
+ { threshold: 32e3, input_per_million: 4, output_per_million: 18, cached_input_per_million: 1 },
1214
+ { input_per_million: 6, output_per_million: 22, cached_input_per_million: 1.5 }
1215
+ ]
1216
+ },
1217
+ "glm-4.7": {
1218
+ currency: "CNY",
1219
+ notes: "output<200 archetype; >200 doubles output rate",
1220
+ tiers: [
1221
+ { threshold: 32e3, input_per_million: 2, output_per_million: 8, cached_input_per_million: 0.4 },
1222
+ { threshold: 2e5, input_per_million: 4, output_per_million: 16, cached_input_per_million: 0.8 }
1223
+ ]
1224
+ },
1225
+ "glm-4.5-air": {
1226
+ currency: "CNY",
1227
+ tiers: [
1228
+ { threshold: 32e3, input_per_million: 0.8, output_per_million: 2, cached_input_per_million: 0.16 },
1229
+ { threshold: 128e3, input_per_million: 1.2, output_per_million: 8, cached_input_per_million: 0.24 }
1230
+ ]
1231
+ },
1232
+ "glm-4.7-flashx": {
1233
+ currency: "CNY",
1234
+ input_per_million: 0.5,
1235
+ cached_input_per_million: 0.1,
1236
+ output_per_million: 3
1237
+ },
1238
+ "glm-4.7-flash": {
1239
+ currency: "CNY",
1240
+ notes: "free tier",
1241
+ input_per_million: 0,
1242
+ cached_input_per_million: 0,
1243
+ output_per_million: 0
1244
+ },
1245
+ "glm-4-plus": {
1246
+ currency: "CNY",
1247
+ input_per_million: 5,
1248
+ output_per_million: 5
1249
+ },
1250
+ "glm-4-air": {
1251
+ currency: "CNY",
1252
+ input_per_million: 0.5,
1253
+ output_per_million: 0.5
1254
+ },
1255
+ "glm-4-airx": {
1256
+ currency: "CNY",
1257
+ input_per_million: 10,
1258
+ output_per_million: 10
1259
+ },
1260
+ "glm-4-flashx-250414": {
1261
+ currency: "CNY",
1262
+ input_per_million: 0.1,
1263
+ output_per_million: 0.1
1264
+ },
1265
+ "glm-4-long": {
1266
+ currency: "CNY",
1267
+ input_per_million: 1,
1268
+ output_per_million: 1
1269
+ },
1270
+ "glm-4.5": {
1271
+ currency: "CNY",
1272
+ notes: "legacy, 128K context",
1273
+ input_per_million: 4,
1274
+ output_per_million: 16
1275
+ },
1276
+ "glm-4.6": {
1277
+ currency: "CNY",
1278
+ notes: "legacy, 200K context",
1279
+ input_per_million: 4,
1280
+ output_per_million: 16
1281
+ }
1282
+ }
739
1283
  }
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 });
1284
+ };
1285
+
1286
+ // ../shared/src/pricing/data/github.ts
1287
+ var github = {
1288
+ // copilot-vscode 仅事件计数(日志里无 token 数),保留空 models 不算费用
1289
+ "copilot-vscode": { models: {} },
1290
+ "copilot-cli": {
1291
+ models: {
1292
+ "gpt-4o": { currency: "USD", input_per_million: 2.5, cached_input_per_million: 1.25, output_per_million: 10 },
1293
+ "gpt-4o-mini": { currency: "USD", input_per_million: 0.15, cached_input_per_million: 0.075, output_per_million: 0.6 },
1294
+ "claude-sonnet-4": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
1295
+ "claude-sonnet-4-6": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
1296
+ "o3-mini": { currency: "USD", input_per_million: 1.1, cached_input_per_million: 0.55, output_per_million: 4.4 },
1297
+ "gemini-2.0-flash": { currency: "USD", input_per_million: 0.1, cached_input_per_million: 0.025, output_per_million: 0.4 }
1298
+ }
750
1299
  }
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;
1300
+ };
1301
+
1302
+ // ../shared/src/pricing/data/sourcegraph.ts
1303
+ var sourcegraph = {
1304
+ amp: {
1305
+ models: {
1306
+ "claude-sonnet-4": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
1307
+ "claude-sonnet-3.7": { currency: "USD", input_per_million: 3, cached_input_per_million: 0.3, output_per_million: 15 },
1308
+ "gemini-2.5-pro": { currency: "USD", input_per_million: 1.25, cached_input_per_million: 0.125, output_per_million: 10 }
1309
+ }
759
1310
  }
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;
1311
+ };
1312
+
1313
+ // ../shared/src/pricing/data/placeholders.ts
1314
+ var inflection = {
1315
+ pi: { models: {} }
1316
+ }, cursor = {
1317
+ cursor: { models: {} }
1318
+ }, droid = {
1319
+ droid: { models: {} }
1320
+ }, opencode = {
1321
+ opencode: { models: {} }
1322
+ };
1323
+
1324
+ // ../shared/src/pricing/catalog.ts
1325
+ var PRICING_VERSION = "2026-07-18-kimi-k3-v1", aliases = {
1326
+ "claude-opus-4-7-20260201": "claude-opus-4-7",
1327
+ "claude-sonnet-4-6-20250301": "claude-sonnet-4-6",
1328
+ "claude-opus-4-6-20250301": "claude-opus-4-6",
1329
+ "claude-haiku-4-5-20251001": "claude-haiku-4-5",
1330
+ "claude-sonnet-4.6": "claude-sonnet-4-6",
1331
+ "gpt-5.6": "gpt-5.6-sol",
1332
+ "codex-auto-review": "gpt-5.4",
1333
+ k3: "kimi-k3",
1334
+ "kimi-code/k3": "kimi-k3"
1335
+ }, catalog = {
1336
+ version: PRICING_VERSION,
1337
+ // 汇率(1 USD ≈ N CNY)。Worker 启动时可被 env 覆盖。
1338
+ fx: {
1339
+ CNY: 7.2
1340
+ },
1341
+ aliases,
1342
+ providers: {
1343
+ anthropic,
1344
+ openai,
1345
+ google,
1346
+ moonshot,
1347
+ alibaba,
1348
+ deepseek,
1349
+ zhipu,
1350
+ github,
1351
+ sourcegraph,
1352
+ inflection,
1353
+ cursor,
1354
+ droid,
1355
+ opencode
769
1356
  }
1357
+ };
1358
+
1359
+ // ../shared/src/pricing/calculate.ts
1360
+ var ANTHROPIC_FAST_MULTIPLIER = 6, FAST_SUPPORTED = /* @__PURE__ */ new Set([
1361
+ "claude-opus-4-8",
1362
+ "claude-opus-4-7",
1363
+ "claude-opus-4-6"
1364
+ ]), OPENAI_CODEX_TIER_MULTIPLIERS = {
1365
+ "gpt-5.6-sol": 2,
1366
+ "gpt-5.6-terra": 2,
1367
+ "gpt-5.6-luna": 2,
1368
+ "gpt-5.5": 2.5,
1369
+ "gpt-5.4": 2
1370
+ };
1371
+ function splitServiceTierSuffix(model) {
1372
+ return model.endsWith("-priority") ? { baseModel: model.replace(/-priority$/, ""), tier: "priority" } : model.endsWith("-fast") ? { baseModel: model.replace(/-fast$/, ""), tier: "fast" } : { baseModel: model, tier: null };
770
1373
  }
771
- function getWebBaseUrl() {
772
- return (process.env[CURSOR_WEB_BASE_URL_ENV]?.trim() || "https://cursor.com").replace(/\/+$/, "");
1374
+ function getServiceTierMultiplier(provider, product, resolvedModel, tier) {
1375
+ 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
1376
  }
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}`);
1377
+ function resolveModelPricing(catalog2, provider, product, model) {
1378
+ let models = catalog2.providers[provider]?.[product]?.models;
1379
+ if (!models) return null;
1380
+ let aliasResolved = catalog2.aliases[model];
1381
+ if (aliasResolved && models[aliasResolved])
1382
+ return { resolvedModel: aliasResolved, pricing: models[aliasResolved], normalized: !1 };
1383
+ if (models[model])
1384
+ return { resolvedModel: model, pricing: models[model], normalized: !1 };
1385
+ for (let knownModel of Object.keys(models).sort((a, b) => b.length - a.length)) {
1386
+ if (!model.startsWith(`${knownModel}-`)) continue;
1387
+ let suffix = model.slice(knownModel.length + 1);
1388
+ if (!/^\d+(?:[-.]\d+)*(?:-\d{6,8})?$/.test(suffix))
1389
+ return { resolvedModel: knownModel, pricing: models[knownModel], normalized: !0 };
783
1390
  }
784
- throw new Error(`Cursor API failed: ${failures.join(", ")}`);
1391
+ return null;
785
1392
  }
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;
1393
+ function selectTier(tiers, totalInputTokens) {
1394
+ for (let i = 0; i < tiers.length; i += 1) {
1395
+ let t2 = tiers[i];
1396
+ if (t2.threshold === void 0 || totalInputTokens <= t2.threshold)
1397
+ return { tier: t2, index: i };
791
1398
  }
792
- return vals.push(cur), vals;
1399
+ return { tier: tiers[tiers.length - 1], index: tiers.length - 1 };
793
1400
  }
794
- function parseNum(v) {
795
- let n = Number((v ?? "").replace(/,/g, "").trim());
796
- return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
1401
+ function toUsd(amount, currency, catalog2) {
1402
+ if (currency === "USD") return amount;
1403
+ let rate = catalog2.fx[currency];
1404
+ return rate ? amount / rate : amount;
797
1405
  }
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);
1406
+ function calculateCost(provider, product, model, tokens, options = {}) {
1407
+ let cat = options.catalog ?? catalog;
1408
+ if (tokens.inputTokens + tokens.cachedInputTokens + tokens.cacheWriteTokens + tokens.outputTokens === 0)
1409
+ return { estimatedCostUsd: 0, costStatus: "exact", pricingVersion: cat.version };
1410
+ let { baseModel, tier } = splitServiceTierSuffix(model), resolved = resolveModelPricing(cat, provider, product, baseModel);
1411
+ if (!resolved)
1412
+ return { estimatedCostUsd: 0, costStatus: "unavailable", pricingVersion: cat.version };
1413
+ let { resolvedModel, pricing, normalized } = resolved, costStatus = normalized ? "estimated" : "exact", unit, matchedTierIndex;
1414
+ if (pricing.tiers && pricing.tiers.length > 0) {
1415
+ 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);
1416
+ unit = tier2, matchedTierIndex = index, requestCount > 1 && (costStatus = "estimated");
1417
+ } else
1418
+ unit = {
1419
+ input_per_million: pricing.input_per_million ?? 0,
1420
+ output_per_million: pricing.output_per_million ?? 0,
1421
+ cached_input_per_million: pricing.cached_input_per_million ?? null,
1422
+ cache_write_per_million: pricing.cache_write_per_million,
1423
+ cache_write_5m_per_million: pricing.cache_write_5m_per_million ?? 0,
1424
+ cache_write_1h_per_million: pricing.cache_write_1h_per_million ?? 0
1425
+ };
1426
+ 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);
1427
+ raw = toUsd(raw, pricing.currency, cat);
1428
+ let finalCost = raw * getServiceTierMultiplier(provider, product, resolvedModel, tier);
1429
+ return {
1430
+ estimatedCostUsd: Math.round(finalCost * 1e4) / 1e4,
1431
+ costStatus,
1432
+ pricingVersion: cat.version,
1433
+ resolvedModel,
1434
+ matchedTierIndex
1435
+ };
804
1436
  }
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()]]));
1437
+
1438
+ // src/scanners/codex.ts
1439
+ var FILE_CONCURRENCY2 = 16, MAX_LINE_BYTES2 = 64 * 1024 * 1024;
1440
+ async function scanCodexDates(targetDates, codexDir, projectAliases) {
1441
+ let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
1442
+ for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
1443
+ let baseDir = codexDir ?? join4(homedir3(), ".codex"), serviceTier = await detectCodexServiceTier(baseDir), sessionFiles = await collectSessionFiles(baseDir);
1444
+ if (sessionFiles.length === 0)
1445
+ return new Map([...targetDateSet].map((targetDate) => [targetDate, []]));
1446
+ let globalSeenSigs = /* @__PURE__ */ new Set();
1447
+ return await runWithConcurrency(sessionFiles, FILE_CONCURRENCY2, async (filePath) => {
1448
+ await processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs, serviceTier);
1449
+ }), new Map(
1450
+ [...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
1451
+ );
859
1452
  }
860
-
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);
1453
+ async function processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs, serviceTier) {
1454
+ let fh;
1455
+ try {
1456
+ fh = await open2(filePath, "r");
1457
+ } catch {
1458
+ return;
1459
+ }
1460
+ try {
1461
+ let rl = createInterface2({
1462
+ input: fh.createReadStream({ encoding: "utf-8" }),
1463
+ crlfDelay: 1 / 0
1464
+ }), currentModel = "unknown", currentProjectFields = { project: "unknown", projectDisplay: "unknown" }, previousTotal = {};
1465
+ for await (let line of rl) {
1466
+ if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES2) continue;
1467
+ let record;
1468
+ try {
1469
+ record = JSON.parse(line);
1470
+ } catch {
1471
+ continue;
1472
+ }
1473
+ if (record.type === "turn_context") {
1474
+ let rawModel = record.payload?.model ?? currentModel;
1475
+ rawModel !== "<synthetic>" && (currentModel = applyCodexServiceTier(normalizeModelName(rawModel), serviceTier)), record.payload?.cwd && (currentProjectFields = resolveProjectFields(record.payload.cwd, projectAliases));
1476
+ continue;
1477
+ }
1478
+ if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
1479
+ let info = record.payload?.info;
1480
+ if (!info?.total_token_usage) continue;
1481
+ let ts = parseTimestamp2(record.timestamp);
888
1482
  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",
1483
+ let usageDate = toDateKey2(ts);
1484
+ if (!targetDateSet.has(usageDate)) continue;
1485
+ let total = info.total_token_usage;
1486
+ 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;
1487
+ let signature = `${total.input_tokens ?? 0}|${total.cached_input_tokens ?? 0}|${total.output_tokens ?? 0}|${total.reasoning_output_tokens ?? 0}|${total.total_tokens ?? 0}`;
1488
+ if (globalSeenSigs.has(signature)) continue;
1489
+ globalSeenSigs.add(signature);
1490
+ let last = info.last_token_usage ?? {
1491
+ input_tokens: Math.max(0, (total.input_tokens ?? 0) - (previousTotal.input_tokens ?? 0)),
1492
+ cached_input_tokens: Math.max(0, (total.cached_input_tokens ?? 0) - (previousTotal.cached_input_tokens ?? 0)),
1493
+ output_tokens: Math.max(0, (total.output_tokens ?? 0) - (previousTotal.output_tokens ?? 0)),
1494
+ reasoning_output_tokens: Math.max(0, (total.reasoning_output_tokens ?? 0) - (previousTotal.reasoning_output_tokens ?? 0))
1495
+ };
1496
+ previousTotal = total;
1497
+ 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, {
1498
+ inputTokens: nonCachedInput,
1499
+ cachedInputTokens: cachedInput,
1500
+ cacheWriteTokens: 0,
1501
+ outputTokens: output
1502
+ }), exactEventCost = eventCost.costStatus === "exact" ? eventCost.estimatedCostUsd : void 0, grouped = groupedByDate.get(usageDate);
1503
+ if (!grouped) continue;
1504
+ let key = `${currentModel}|${currentProjectFields.project}`, existing = grouped.get(key);
1505
+ if (existing)
1506
+ 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);
1507
+ else {
1508
+ let breakdown = {
1509
+ provider: "openai",
1510
+ product: "codex",
896
1511
  channel: "cli",
897
- model,
898
- project: "unknown",
899
- projectDisplay: "unknown",
900
- inputTokens: 0,
901
- cachedInputTokens: 0,
1512
+ model: currentModel,
1513
+ project: currentProjectFields.project,
1514
+ projectDisplay: currentProjectFields.projectDisplay,
1515
+ projectAlias: currentProjectFields.projectAlias,
1516
+ eventCount: 1,
1517
+ inputTokens: nonCachedInput,
1518
+ cachedInputTokens: cachedInput,
902
1519
  cacheWriteTokens: 0,
903
- outputTokens: 0,
904
- reasoningOutputTokens: 0
905
- },
906
- tokens
907
- ));
1520
+ outputTokens: output,
1521
+ reasoningOutputTokens: last.reasoning_output_tokens ?? 0
1522
+ };
1523
+ exactEventCost !== void 0 && (breakdown.costUSD = exactEventCost, breakdown.pricingVersion = eventCost.pricingVersion), grouped.set(key, breakdown);
1524
+ }
908
1525
  }
1526
+ } finally {
1527
+ await fh.close();
909
1528
  }
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
1529
  }
915
- async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
916
- let content;
1530
+ async function collectSessionFiles(baseDir) {
1531
+ let paths = [], archivedDir = join4(baseDir, "archived_sessions");
917
1532
  try {
918
- content = await readFile6(filePath, "utf-8");
1533
+ let files = await readdir4(archivedDir);
1534
+ for (let f of files)
1535
+ f.endsWith(".jsonl") && paths.push(join4(archivedDir, f));
919
1536
  } catch {
920
- return;
921
1537
  }
922
- let rows;
1538
+ let sessionsDir = join4(baseDir, "sessions");
1539
+ return await walkDir(sessionsDir, paths), paths;
1540
+ }
1541
+ async function detectCodexServiceTier(baseDir) {
1542
+ let config = "";
923
1543
  try {
924
- rows = JSON.parse(content);
1544
+ config = await readFile3(join4(baseDir, "config.toml"), "utf-8");
925
1545
  } catch {
926
- return;
1546
+ return null;
927
1547
  }
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
- }
1548
+ let serviceTier = config.match(/^\s*service_tier\s*=\s*["']([^"']+)["']/m)?.[1]?.trim().toLowerCase();
1549
+ return serviceTier === "priority" ? "priority" : serviceTier === "fast" || config.match(/^\s*fast_mode\s*=\s*(true|false)\s*$/m)?.[1] === "true" ? "fast" : null;
954
1550
  }
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 };
1551
+ function applyCodexServiceTier(model, serviceTier) {
1552
+ if (!serviceTier || model.endsWith("-fast") || model.endsWith("-priority")) return model;
1553
+ let supportsFast = model === "gpt-5.5" || model === "gpt-5.4";
1554
+ 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;
1555
+ }
1556
+ async function walkDir(dir, result) {
1557
+ let entries;
1558
+ try {
1559
+ entries = await readdir4(dir, { withFileTypes: !0 });
1560
+ } catch {
1561
+ return;
959
1562
  }
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 };
1563
+ for (let entry of entries) {
1564
+ let fullPath = join4(dir, entry.name);
1565
+ entry.isDirectory() ? await walkDir(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
964
1566
  }
965
- return null;
966
1567
  }
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;
987
- try {
988
- obj = JSON.parse(line);
989
- } catch {
990
- continue;
991
- }
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
- }
1568
+ function parseTimestamp2(value) {
1569
+ if (!value) return null;
1570
+ try {
1571
+ let d = new Date(value);
1572
+ return isNaN(d.getTime()) ? null : d;
1573
+ } catch {
1574
+ return null;
1024
1575
  }
1025
- return finalize(grouped);
1576
+ }
1577
+ function toDateKey2(date) {
1578
+ let year = date.getFullYear(), month = String(date.getMonth() + 1).padStart(2, "0"), day = String(date.getDate()).padStart(2, "0");
1579
+ return `${year}-${month}-${day}`;
1026
1580
  }
1027
1581
 
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");
1582
+ // src/scanners/copilot.ts
1583
+ import { readFile as readFile4 } from "node:fs/promises";
1584
+ import { join as join5 } from "node:path";
1585
+ import { homedir as homedir4 } from "node:os";
1586
+ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
1587
+ let dates = new Set(targetDates), dir = baseDir ?? join5(homedir4(), ".copilot", "session-state"), files = await walkFiles(dir, ".jsonl");
1034
1588
  if (files.length === 0) return emptyResult(dates);
1035
- let workspaceMap = await loadWorkspaceMap(kimiHome), grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
1589
+ let grouped = initDateMap(dates);
1036
1590
  for (let filePath of files) {
1037
- let sessionDir = dirname3(filePath), hashDir = dirname3(sessionDir), workDirHash = basename5(hashDir), projectFields = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
1591
+ let content;
1038
1592
  try {
1039
- content = await readFile8(filePath, "utf-8");
1593
+ content = await readFile4(filePath, "utf-8");
1040
1594
  } catch {
1041
1595
  continue;
1042
1596
  }
1043
- let currentModel = "unknown";
1044
- for (let line of content.split(`
1045
- `)) {
1597
+ let sessionProjectFields = { project: "unknown", projectDisplay: "unknown" }, lines = content.split(`
1598
+ `);
1599
+ for (let line of lines) {
1046
1600
  if (!line.trim()) continue;
1047
1601
  let obj;
1048
1602
  try {
@@ -1050,1462 +1604,1249 @@ async function scanKimiDates(targetDates, baseDir, projectAliases) {
1050
1604
  } catch {
1051
1605
  continue;
1052
1606
  }
1053
- if (obj.payload?.model && (currentModel = obj.payload.model), obj.type !== "StatusUpdate") continue;
1054
- let usage = obj.payload?.token_usage;
1055
- if (!usage) continue;
1607
+ if (obj.type === "session.start" || obj.type === "session.resume") {
1608
+ let ctx = obj.data?.context, raw = ctx?.gitRoot ?? ctx?.cwd;
1609
+ raw && (sessionProjectFields = resolveProjectFields(raw, projectAliases));
1610
+ }
1611
+ if (obj.type !== "session.shutdown") continue;
1056
1612
  let ts = parseTs(obj.timestamp);
1057
1613
  if (!ts) continue;
1058
1614
  let dk = dateKey(ts), dayMap = grouped.get(dk);
1059
1615
  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(
1616
+ let metrics = obj.data?.modelMetrics;
1617
+ if (metrics)
1618
+ for (let [model, entry] of Object.entries(metrics)) {
1619
+ let usage = entry.usage;
1620
+ if (!usage) continue;
1621
+ let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, output = usage.outputTokens ?? 0, input = Math.max(rawInput - cacheRead, 0);
1622
+ accumulate(
1623
+ dayMap,
1624
+ `${model}|${sessionProjectFields.project}`,
1625
+ {
1626
+ provider: "github",
1627
+ product: "copilot-cli",
1628
+ channel: "cli",
1629
+ model,
1630
+ project: sessionProjectFields.project,
1631
+ projectDisplay: sessionProjectFields.projectDisplay,
1632
+ projectAlias: sessionProjectFields.projectAlias,
1633
+ inputTokens: 0,
1634
+ cachedInputTokens: 0,
1635
+ cacheWriteTokens: 0,
1636
+ outputTokens: 0,
1637
+ reasoningOutputTokens: 0
1638
+ },
1639
+ { input, cached: cacheRead, cacheWrite: 0, output, reasoning: 0 }
1640
+ );
1641
+ }
1642
+ }
1643
+ }
1644
+ return finalize(grouped);
1645
+ }
1646
+
1647
+ // src/scanners/copilot-vscode.ts
1648
+ import { readFile as readFile5 } from "node:fs/promises";
1649
+ import { basename as basename2, dirname, join as join6 } from "node:path";
1650
+ import { homedir as homedir5 } from "node:os";
1651
+ async function scanCopilotVscodeDates(targetDates, baseDir, projectAliases, workspaceStorageDir) {
1652
+ 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/"));
1653
+ if (logFiles.length === 0 && sessionFiles.length === 0) return emptyResult(dates);
1654
+ let grouped = initDateMap(dates), seenEvents = /* @__PURE__ */ new Set();
1655
+ for (let filePath of logFiles) {
1656
+ let content;
1657
+ try {
1658
+ content = await readFile5(filePath, "utf-8");
1659
+ } catch {
1660
+ continue;
1661
+ }
1662
+ let sessionProject = "unknown";
1663
+ for (let line of content.split(`
1664
+ `)) {
1665
+ if (!line.trim()) continue;
1666
+ let projectPath = extractFileUriPath(line);
1667
+ projectPath && (sessionProject = projectFromPath(projectPath, projectAliases));
1668
+ let event = extractSuccessEvent(line);
1669
+ if (!event) continue;
1670
+ let dayMap = grouped.get(dateKey(event.timestamp));
1671
+ if (!dayMap) continue;
1672
+ let dedupeKey = `${event.requestId}|${event.timestamp.toISOString()}|${event.model}|${sessionProject}`;
1673
+ seenEvents.has(dedupeKey) || (seenEvents.add(dedupeKey), accumulate(
1067
1674
  dayMap,
1068
- `${currentModel}|${projectFields.project}`,
1675
+ `${event.model}|${sessionProject}`,
1069
1676
  {
1070
- provider: "moonshot",
1071
- product: "kimi-code",
1072
- channel: "cli",
1073
- model: currentModel,
1074
- project: projectFields.project,
1075
- projectDisplay: projectFields.projectDisplay,
1076
- projectAlias: projectFields.projectAlias,
1677
+ provider: "github",
1678
+ product: "copilot-vscode",
1679
+ channel: "ide",
1680
+ model: event.model,
1681
+ project: sessionProject,
1077
1682
  inputTokens: 0,
1078
1683
  cachedInputTokens: 0,
1079
1684
  cacheWriteTokens: 0,
1080
1685
  outputTokens: 0,
1081
1686
  reasoningOutputTokens: 0
1082
1687
  },
1083
- { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
1084
- );
1688
+ { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
1689
+ ));
1085
1690
  }
1086
1691
  }
1692
+ for (let filePath of sessionFiles)
1693
+ await collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases);
1087
1694
  return finalize(grouped);
1088
1695
  }
1089
- function resolveKimiProject(hash, workspaceMap, aliases2) {
1090
- let wsPath = workspaceMap.get(hash);
1091
- return wsPath ? resolveProjectFields(wsPath, aliases2) : resolveProjectFields(hash, aliases2);
1696
+ function extractSuccessEvent(line) {
1697
+ if (!line.includes("ccreq:") || !line.includes("| success |")) return null;
1698
+ let timestampMatch = line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)/);
1699
+ if (!timestampMatch) return null;
1700
+ let timestamp = new Date(timestampMatch[1].replace(" ", "T"));
1701
+ if (Number.isNaN(timestamp.getTime())) return null;
1702
+ let parts = line.split("|").map((part) => part.trim());
1703
+ if (parts.length < 3 || parts[1] !== "success") return null;
1704
+ let requestId = parts[0].match(/ccreq:([^.|\s]+)/)?.[1] ?? `${timestamp.getTime()}`, model = normalizeModel(parts[2]);
1705
+ return model ? { requestId, timestamp, model } : null;
1706
+ }
1707
+ function normalizeModel(raw) {
1708
+ let parts = raw.split("->").map((part) => part.trim()).filter(Boolean);
1709
+ return parts[parts.length - 1] ?? raw.trim();
1092
1710
  }
1093
- async function loadWorkspaceMap(kimiHome) {
1094
- let map = /* @__PURE__ */ new Map();
1711
+ function extractFileUriPath(line) {
1712
+ let match = line.match(/file:\/\/\/([^\s.]+(?:\.[^\s.]+)?)/);
1713
+ if (!match) return null;
1095
1714
  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);
1715
+ return decodeURIComponent(`/${match[1]}`);
1100
1716
  } 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];
1146
- }
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
- );
1717
+ return `/${match[1]}`;
1175
1718
  }
1176
1719
  }
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
- );
1720
+ async function collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases) {
1721
+ let content;
1722
+ try {
1723
+ content = await readFile5(filePath, "utf-8");
1724
+ } catch {
1725
+ return;
1207
1726
  }
1208
- }
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";
1217
- }
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);
1727
+ let session;
1728
+ try {
1729
+ session = JSON.parse(content);
1730
+ } catch {
1731
+ return;
1732
+ }
1733
+ let workspacePath = await readWorkspaceFolderPath(filePath), project = workspacePath ? projectFromPath(workspacePath, projectAliases) : "unknown";
1734
+ for (let request of session.requests ?? []) {
1735
+ if (!request.response?.length || request.result?.errorDetails?.responseIsIncomplete) continue;
1736
+ let model = normalizeWorkspaceModel(request.modelId);
1737
+ if (!model) continue;
1738
+ let timestamp = new Date(request.timestamp ?? 0);
1739
+ if (Number.isNaN(timestamp.getTime())) continue;
1740
+ let dayMap = grouped.get(dateKey(timestamp));
1241
1741
  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(
1742
+ let dedupeKey = `${request.requestId ?? `${timestamp.getTime()}`}|${timestamp.toISOString()}|${model}|${project}`;
1743
+ seenEvents.has(dedupeKey) || (seenEvents.add(dedupeKey), accumulate(
1258
1744
  dayMap,
1259
1745
  `${model}|${project}`,
1260
1746
  {
1261
- provider: "droid",
1262
- product: "droid",
1263
- channel: "cli",
1747
+ provider: "github",
1748
+ product: "copilot-vscode",
1749
+ channel: "ide",
1264
1750
  model,
1265
1751
  project,
1266
- projectDisplay: rawProject,
1267
- projectAlias: alias,
1268
1752
  inputTokens: 0,
1269
1753
  cachedInputTokens: 0,
1270
1754
  cacheWriteTokens: 0,
1271
1755
  outputTokens: 0,
1272
1756
  reasoningOutputTokens: 0
1273
1757
  },
1274
- { input, cached: cacheRead, cacheWrite: 0, output, reasoning: thinking }
1275
- );
1758
+ { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
1759
+ ));
1276
1760
  }
1277
- return finalize(grouped);
1761
+ }
1762
+ async function readWorkspaceFolderPath(sessionFilePath) {
1763
+ let workspaceJsonPath = join6(dirname(sessionFilePath), "..", "workspace.json"), content;
1764
+ try {
1765
+ content = await readFile5(workspaceJsonPath, "utf-8");
1766
+ } catch {
1767
+ return null;
1768
+ }
1769
+ try {
1770
+ let raw = JSON.parse(content).folder;
1771
+ return raw?.startsWith("file:///") ? decodeURIComponent(raw.replace(/^file:\/\//, "")) : null;
1772
+ } catch {
1773
+ return null;
1774
+ }
1775
+ }
1776
+ function normalizeWorkspaceModel(raw) {
1777
+ return raw ? raw.replace(/^copilot\//, "").trim() : "";
1278
1778
  }
1279
1779
 
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 {
1780
+ // src/scanners/cursor.ts
1781
+ import { existsSync } from "node:fs";
1782
+ import { copyFile, mkdtemp, rm } from "node:fs/promises";
1783
+ import { homedir as homedir6, tmpdir } from "node:os";
1784
+ import { join as join7, resolve } from "node:path";
1785
+ 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";
1786
+ function getDefaultDbPath() {
1787
+ if (process.platform === "darwin")
1788
+ return join7(homedir6(), "Library", "Application Support", "Cursor", CURSOR_STATE_DB_RELATIVE);
1789
+ if (process.platform === "win32") {
1790
+ let appData = process.env.APPDATA?.trim() || join7(homedir6(), "AppData", "Roaming");
1791
+ return join7(appData, "Cursor", CURSOR_STATE_DB_RELATIVE);
1792
+ }
1793
+ let xdg = process.env.XDG_CONFIG_HOME?.trim() || join7(homedir6(), ".config");
1794
+ return join7(xdg, "Cursor", CURSOR_STATE_DB_RELATIVE);
1795
+ }
1796
+ function findDbPath() {
1797
+ let explicit = process.env[CURSOR_STATE_DB_PATH_ENV]?.trim();
1798
+ if (explicit) {
1799
+ let p = resolve(explicit);
1800
+ return existsSync(p) ? p : null;
1801
+ }
1802
+ let dirs = process.env[CURSOR_CONFIG_DIR_ENV]?.trim(), candidates = dirs ? dirs.split(",").map((v) => {
1803
+ let r = resolve(v.trim());
1804
+ return r.endsWith(".vscdb") ? r : join7(r, CURSOR_STATE_DB_RELATIVE);
1805
+ }) : [getDefaultDbPath()];
1806
+ for (let c of candidates)
1807
+ if (existsSync(c)) return c;
1808
+ return null;
1809
+ }
1810
+ function readAuthFromDb(dbPath) {
1811
+ let { DatabaseSync } = __require("node:sqlite"), db = new DatabaseSync(dbPath, { open: !0 });
1812
+ try {
1813
+ let raw = db.prepare("SELECT value FROM ItemTable WHERE key = ? LIMIT 1").get("cursorAuth/accessToken")?.value, token;
1814
+ return typeof raw == "string" ? token = raw.trim() || void 0 : Buffer.isBuffer(raw) && (token = raw.toString("utf8").trim() || void 0), { accessToken: token };
1815
+ } finally {
1816
+ db.close();
1817
+ }
1818
+ }
1819
+ async function withSnapshot(dbPath, cb) {
1820
+ let dir = await mkdtemp(join7(tmpdir(), "aiusage-cursor-")), snap = join7(dir, "state.vscdb");
1821
+ await copyFile(dbPath, snap);
1822
+ for (let suffix of ["-shm", "-wal"])
1823
+ existsSync(`${dbPath}${suffix}`) && await copyFile(`${dbPath}${suffix}`, `${snap}${suffix}`);
1824
+ try {
1825
+ return cb(snap);
1826
+ } finally {
1827
+ await rm(dir, { recursive: !0, force: !0 });
1828
+ }
1829
+ }
1830
+ async function readAuth(dbPath) {
1831
+ try {
1832
+ return readAuthFromDb(dbPath);
1833
+ } catch (err) {
1834
+ if (err instanceof Error && /database is locked/i.test(err.message))
1835
+ return withSnapshot(dbPath, (snap) => readAuthFromDb(snap));
1836
+ throw err;
1837
+ }
1838
+ }
1839
+ function jwtSub(token) {
1840
+ let part = token.split(".")[1];
1841
+ if (!part) return;
1842
+ let b64 = part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=");
1843
+ try {
1844
+ return JSON.parse(Buffer.from(b64, "base64").toString("utf8")).sub?.trim();
1845
+ } catch {
1846
+ return;
1847
+ }
1848
+ }
1849
+ function getWebBaseUrl() {
1850
+ return (process.env[CURSOR_WEB_BASE_URL_ENV]?.trim() || "https://cursor.com").replace(/\/+$/, "");
1851
+ }
1852
+ async function fetchCsv(accessToken) {
1853
+ 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}` }];
1854
+ for (let cv of cookieValues)
1855
+ attempts.push({ Cookie: `${CURSOR_SESSION_COOKIE}=${cv}` }), attempts.push({ Authorization: `Bearer ${accessToken}`, Cookie: `${CURSOR_SESSION_COOKIE}=${cv}` });
1856
+ let failures = [];
1857
+ for (let headers of attempts) {
1858
+ let res = await fetch(url, { headers: { Accept: "text/csv,*/*;q=0.8", ...headers } });
1859
+ if (res.ok) return res.text();
1860
+ failures.push(`${res.status} ${res.statusText}`);
1861
+ }
1862
+ throw new Error(`Cursor API failed: ${failures.join(", ")}`);
1863
+ }
1864
+ function parseCsvLine(line) {
1865
+ let vals = [], cur = "", inQ = !1;
1866
+ for (let i = 0; i < line.length; i++) {
1867
+ let c = line[i];
1868
+ c === '"' ? inQ && line[i + 1] === '"' ? (cur += '"', i++) : inQ = !inQ : c === "," && !inQ ? (vals.push(cur), cur = "") : cur += c;
1869
+ }
1870
+ return vals.push(cur), vals;
1871
+ }
1872
+ function parseNum(v) {
1873
+ let n = Number((v ?? "").replace(/,/g, "").trim());
1874
+ return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
1875
+ }
1876
+ function parseDateStr(v) {
1877
+ let s = v?.trim();
1878
+ if (!s) return null;
1879
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
1880
+ let d = new Date(s);
1881
+ return isNaN(d.getTime()) ? null : dateKey(d);
1882
+ }
1883
+ async function scanCursorDates(targetDates) {
1884
+ let dateSet = new Set(targetDates), empty = new Map(targetDates.map((d) => [d, []])), dbPath = findDbPath();
1885
+ if (!dbPath) return empty;
1886
+ let auth;
1887
+ try {
1888
+ auth = await readAuth(dbPath);
1889
+ } catch {
1890
+ return empty;
1891
+ }
1892
+ if (!auth.accessToken) return empty;
1893
+ let csvText;
1894
+ try {
1895
+ csvText = await fetchCsv(auth.accessToken);
1896
+ } catch {
1897
+ return empty;
1898
+ }
1899
+ let grouped = /* @__PURE__ */ new Map();
1900
+ for (let d of dateSet) grouped.set(d, /* @__PURE__ */ new Map());
1901
+ let headers = null;
1902
+ for (let rawLine of csvText.split(/\r?\n/)) {
1903
+ let line = rawLine.trim();
1904
+ if (!line) continue;
1905
+ let values = parseCsvLine(line);
1906
+ if (!headers) {
1907
+ headers = values;
1298
1908
  continue;
1299
1909
  }
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
- );
1910
+ let row = {};
1911
+ headers.forEach((h, i) => {
1912
+ row[h] = values[i] ?? "";
1913
+ });
1914
+ let date = parseDateStr(row.Date);
1915
+ if (!date || !dateSet.has(date)) continue;
1916
+ let rawModel = row.Model?.trim();
1917
+ if (!rawModel) continue;
1918
+ let model = normalizeModelName(rawModel);
1919
+ if (!(parseNum(row["Total Tokens"]) || parseNum(row.Tokens))) continue;
1920
+ 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);
1921
+ existing ? (existing.eventCount += 1, existing.inputTokens += inputTokens, existing.cachedInputTokens += cacheRead, existing.cacheWriteTokens += inputWithCache, existing.outputTokens += output) : dayMap.set(model, {
1922
+ provider: "cursor",
1923
+ product: "cursor",
1924
+ channel: "ide",
1925
+ model,
1926
+ project: "unknown",
1927
+ projectDisplay: "unknown",
1928
+ eventCount: 1,
1929
+ inputTokens,
1930
+ cachedInputTokens: cacheRead,
1931
+ cacheWriteTokens: inputWithCache,
1932
+ outputTokens: output,
1933
+ reasoningOutputTokens: 0
1934
+ });
1328
1935
  }
1329
- return finalize(grouped);
1936
+ return new Map([...grouped.entries()].map(([d, m]) => [d, [...m.values()]]));
1330
1937
  }
1331
1938
 
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");
1939
+ // src/scanners/gemini.ts
1940
+ import { readFile as readFile6 } from "node:fs/promises";
1941
+ import { basename as basename3, join as join8 } from "node:path";
1942
+ import { homedir as homedir7 } from "node:os";
1943
+ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
1944
+ let dates = new Set(targetDates), dir = baseDir ?? join8(homedir7(), ".gemini", "tmp"), files = await walkFiles(dir, ".json");
1338
1945
  if (files.length === 0) return emptyResult(dates);
1339
- let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
1946
+ let grouped = initDateMap(dates), tokenBackedDates = /* @__PURE__ */ new Set();
1340
1947
  for (let filePath of files) {
1948
+ if (basename3(filePath) === "logs.json") continue;
1341
1949
  let content;
1342
1950
  try {
1343
- content = await readFile12(filePath, "utf-8");
1951
+ content = await readFile6(filePath, "utf-8");
1344
1952
  } catch {
1345
1953
  continue;
1346
1954
  }
1347
- let parentDir = dirname5(filePath), encodedCwd = basename7(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(encodedCwd) };
1348
- for (let line of content.split(`
1349
- `)) {
1350
- if (!line.trim()) continue;
1351
- let obj;
1352
- try {
1353
- obj = JSON.parse(line);
1354
- } catch {
1355
- continue;
1356
- }
1357
- if (obj.type === "session" && obj.cwd) {
1358
- sessionProjectFields = resolveProjectFields(obj.cwd, projectAliases);
1359
- continue;
1360
- }
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;
1366
- let ts = parseTs(obj.timestamp);
1955
+ let session;
1956
+ try {
1957
+ session = JSON.parse(content);
1958
+ } catch {
1959
+ continue;
1960
+ }
1961
+ 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;
1962
+ for (let msg of messages) {
1963
+ let tokens = extractTokens(msg);
1964
+ if (!tokens) continue;
1965
+ let model = normalizeModelName(msg.model ?? fallbackModel), ts = parseTs(msg.timestamp) ?? parseTs(msg.createTime) ?? parseTs(fallbackTs);
1367
1966
  if (!ts) continue;
1368
1967
  let dk = dateKey(ts), dayMap = grouped.get(dk);
1369
- 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(
1968
+ dayMap && (tokenBackedDates.add(dk), accumulate(
1376
1969
  dayMap,
1377
- `${model}|${sessionProjectFields.project}`,
1970
+ `${model}|unknown`,
1378
1971
  {
1379
- provider: "inflection",
1380
- product: "pi",
1972
+ provider: "google",
1973
+ product: "gemini-cli",
1381
1974
  channel: "cli",
1382
1975
  model,
1383
- project: sessionProjectFields.project,
1384
- projectDisplay: sessionProjectFields.projectDisplay,
1385
- projectAlias: sessionProjectFields.projectAlias,
1976
+ project: "unknown",
1977
+ projectDisplay: "unknown",
1386
1978
  inputTokens: 0,
1387
1979
  cachedInputTokens: 0,
1388
1980
  cacheWriteTokens: 0,
1389
1981
  outputTokens: 0,
1390
1982
  reasoningOutputTokens: 0
1391
1983
  },
1392
- { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
1393
- );
1984
+ tokens
1985
+ ));
1394
1986
  }
1395
1987
  }
1988
+ let logFiles = files.filter((filePath) => basename3(filePath) === "logs.json");
1989
+ for (let filePath of logFiles)
1990
+ await collectGeminiLogEvents(filePath, grouped, tokenBackedDates);
1396
1991
  return finalize(grouped);
1397
1992
  }
1398
- function getSessionsDir() {
1399
- let envDir = process.env.PI_CODING_AGENT_DIR;
1400
- return envDir ? join13(envDir, "sessions") : join13(homedir13(), ".pi", "agent", "sessions");
1401
- }
1402
- function extractProjectFromEncoded(encoded) {
1403
- let parts = encoded.split("-").filter(Boolean);
1404
- return parts.length > 0 ? parts[parts.length - 1] : "unknown";
1405
- }
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
- };
1415
- }
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
- });
1993
+ async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
1994
+ let content;
1995
+ try {
1996
+ content = await readFile6(filePath, "utf-8");
1997
+ } catch {
1998
+ return;
1999
+ }
2000
+ let rows;
2001
+ try {
2002
+ rows = JSON.parse(content);
2003
+ } catch {
2004
+ return;
2005
+ }
2006
+ if (Array.isArray(rows))
2007
+ for (let row of rows) {
2008
+ if (row.type && row.type !== "user") continue;
2009
+ let ts = parseTs(row.timestamp);
2010
+ if (!ts) continue;
2011
+ let dk = dateKey(ts);
2012
+ if (tokenBackedDates.has(dk)) continue;
2013
+ let dayMap = grouped.get(dk);
2014
+ dayMap && accumulate(
2015
+ dayMap,
2016
+ "unknown|unknown",
2017
+ {
2018
+ provider: "google",
2019
+ product: "gemini-cli",
2020
+ channel: "cli",
2021
+ model: "unknown",
2022
+ project: "unknown",
2023
+ inputTokens: 0,
2024
+ cachedInputTokens: 0,
2025
+ cacheWriteTokens: 0,
2026
+ outputTokens: 0,
2027
+ reasoningOutputTokens: 0
2028
+ },
2029
+ { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }
2030
+ );
2031
+ }
1448
2032
  }
1449
- function createEmptyTotals() {
1450
- return {
1451
- eventCount: 0,
1452
- inputTokens: 0,
1453
- cachedInputTokens: 0,
1454
- cacheWriteTokens: 0,
1455
- outputTokens: 0,
1456
- reasoningOutputTokens: 0
1457
- };
2033
+ function extractTokens(msg) {
2034
+ if (msg.tokens) {
2035
+ 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);
2036
+ return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
2037
+ }
2038
+ let u = msg.usage ?? msg.usageMetadata;
2039
+ if (u) {
2040
+ 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);
2041
+ return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
2042
+ }
2043
+ return null;
1458
2044
  }
1459
2045
 
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;
1469
- }
1470
- async function fetchAndMerge(startingAt, endingAt, adminApiKey, targetDates, grouped) {
1471
- let nextPage = null;
1472
- do {
1473
- let url = buildUrl(startingAt, endingAt, nextPage), resp;
2046
+ // src/scanners/qwen.ts
2047
+ import { readFile as readFile7 } from "node:fs/promises";
2048
+ import { join as join9, basename as basename4, dirname as dirname2 } from "node:path";
2049
+ import { homedir as homedir8 } from "node:os";
2050
+ async function scanQwenDates(targetDates, baseDir, projectAliases) {
2051
+ let dates = new Set(targetDates), dir = baseDir ?? join9(homedir8(), ".qwen", "tmp"), files = await walkFiles(dir, ".jsonl");
2052
+ if (files.length === 0) return emptyResult(dates);
2053
+ let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
2054
+ for (let filePath of files) {
2055
+ let chatsDir = dirname2(filePath), projectDir = dirname2(chatsDir), projectId = basename4(projectDir), content;
1474
2056
  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}`);
2057
+ content = await readFile7(filePath, "utf-8");
2058
+ } catch {
2059
+ continue;
1487
2060
  }
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",
2061
+ for (let line of content.split(`
2062
+ `)) {
2063
+ if (!line.trim()) continue;
2064
+ let obj;
2065
+ try {
2066
+ obj = JSON.parse(line);
2067
+ } catch {
2068
+ continue;
2069
+ }
2070
+ if (obj.type !== "assistant") continue;
2071
+ let ts = parseTs(obj.timestamp);
2072
+ if (!ts) continue;
2073
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2074
+ if (!dayMap) continue;
2075
+ if (obj.uuid) {
2076
+ if (seen.has(obj.uuid)) continue;
2077
+ seen.add(obj.uuid);
2078
+ }
2079
+ let u = obj.usageMetadata;
2080
+ if (!u) continue;
2081
+ 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);
2082
+ accumulate(
2083
+ dayMap,
2084
+ `${model}|${fields.project}`,
2085
+ {
2086
+ provider: "alibaba",
2087
+ product: "qwen-code",
1501
2088
  channel: "cli",
1502
2089
  model,
1503
- project: "unknown",
1504
- eventCount: 1,
1505
- inputTokens,
1506
- cachedInputTokens,
1507
- cacheWriteTokens,
1508
- cacheWrite5mTokens: cacheWrite5m,
1509
- cacheWrite1hTokens: cacheWrite1h,
1510
- outputTokens,
2090
+ project: fields.project,
2091
+ projectDisplay: fields.projectDisplay,
2092
+ projectAlias: fields.projectAlias,
2093
+ inputTokens: 0,
2094
+ cachedInputTokens: 0,
2095
+ cacheWriteTokens: 0,
2096
+ outputTokens: 0,
1511
2097
  reasoningOutputTokens: 0
1512
- });
1513
- }
2098
+ },
2099
+ { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts }
2100
+ );
1514
2101
  }
1515
- nextPage = data.has_more ? data.next_page : null;
1516
- } while (nextPage);
1517
- }
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}`;
1525
- }
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;
1536
2102
  }
1537
- return chunks;
2103
+ return finalize(grouped);
1538
2104
  }
1539
2105
 
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;
2106
+ // src/scanners/kimi.ts
2107
+ import { readFile as readFile8, stat } from "node:fs/promises";
2108
+ import { join as join10, basename as basename5, dirname as dirname3 } from "node:path";
2109
+ import { homedir as homedir9 } from "node:os";
2110
+ var DEFAULT_MODEL = "kimi-for-coding";
2111
+ function resolveKimiCodeHome(home = homedir9()) {
2112
+ return process.env.KIMI_CODE_HOME?.trim() || join10(home, ".kimi-code");
2113
+ }
2114
+ async function scanKimiDates(targetDates, legacyBaseDir, projectAliases, kimiCodeBaseDir) {
2115
+ let dates = new Set(targetDates), legacyHome = legacyBaseDir ?? join10(homedir9(), ".kimi"), codeHome = kimiCodeBaseDir ?? (legacyBaseDir ? void 0 : resolveKimiCodeHome()), [legacyFiles, codeFiles] = await Promise.all([
2116
+ findWireFiles(join10(legacyHome, "sessions")),
2117
+ codeHome ? findWireFiles(join10(codeHome, "sessions")) : Promise.resolve([])
2118
+ ]);
2119
+ if (legacyFiles.length === 0 && codeFiles.length === 0) return emptyResult(dates);
2120
+ let [legacyWorkspaceMap, legacyModel, codeSessionIndex] = await Promise.all([
2121
+ loadLegacyWorkspaceMap(legacyHome),
2122
+ loadLegacyModel(legacyHome),
2123
+ codeHome ? loadKimiCodeSessionIndex(codeHome) : Promise.resolve(/* @__PURE__ */ new Map())
2124
+ ]), grouped = initDateMap(dates), sessionSets = /* @__PURE__ */ new Map(), codeProjectCache = /* @__PURE__ */ new Map();
2125
+ for (let filePath of legacyFiles) {
2126
+ let sessionDir = dirname3(filePath), workspaceHash = basename5(dirname3(sessionDir)), sessionId = basename5(sessionDir), rawProject = legacyWorkspaceMap.get(workspaceHash) ?? workspaceHash, projectFields = resolveProjectFields(rawProject, projectAliases), usages = await parseLegacyFile(filePath, legacyModel);
2127
+ for (let usage of usages)
2128
+ addUsage(grouped, sessionSets, dates, usage, projectFields, sessionId);
2129
+ }
2130
+ for (let filePath of codeFiles) {
2131
+ let pathInfo = getKimiCodePathInfo(filePath);
2132
+ if (!pathInfo) continue;
2133
+ let projectFields = codeProjectCache.get(pathInfo.sessionDir);
2134
+ if (!projectFields) {
2135
+ let rawProject = await resolveKimiCodeProjectPath(pathInfo, codeSessionIndex);
2136
+ projectFields = resolveProjectFields(rawProject, projectAliases), codeProjectCache.set(pathInfo.sessionDir, projectFields);
2137
+ }
2138
+ let usages = await parseKimiCodeFile(filePath);
2139
+ for (let usage of usages)
2140
+ addUsage(grouped, sessionSets, dates, usage, projectFields, pathInfo.sessionId);
2141
+ }
2142
+ let result = finalize(grouped);
2143
+ for (let [usageDate, breakdowns] of result)
2144
+ for (let breakdown of breakdowns) {
2145
+ let key = `${usageDate}|${breakdown.model}|${breakdown.project}`;
2146
+ breakdown.sessionCount = sessionSets.get(key)?.size ?? 0;
2147
+ }
2148
+ return result;
2149
+ }
2150
+ async function findWireFiles(sessionsDir) {
2151
+ return (await walkFiles(sessionsDir, ".jsonl")).filter((filePath) => basename5(filePath) === "wire.jsonl");
2152
+ }
2153
+ async function parseLegacyFile(filePath, fallbackModel) {
2154
+ let content = await safeRead(filePath);
2155
+ if (content == null) return [];
2156
+ let fallbackTimestamp = await fileModifiedDate(filePath), usages = [], keyedIndices = /* @__PURE__ */ new Map(), currentModel = fallbackModel;
2157
+ for (let line of content.split(`
2158
+ `)) {
2159
+ if (!line.trim()) continue;
2160
+ let record;
1549
2161
  try {
1550
- content = await readFile13(filePath, "utf-8");
2162
+ record = JSON.parse(line);
1551
2163
  } catch {
1552
2164
  continue;
1553
2165
  }
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
- });
2166
+ let payload = record.message?.payload ?? record.payload;
2167
+ if (payload?.model && (currentModel = normalizeModel2(payload.model)), (record.message?.type ?? record.type) !== "StatusUpdate" || !payload?.token_usage) continue;
2168
+ let tokens = normalizeUsage(payload.token_usage);
2169
+ if (tokens.input + tokens.cached + tokens.cacheWrite + tokens.output === 0) continue;
2170
+ let timestamp = parseTs(record.timestamp) ?? fallbackTimestamp;
2171
+ if (!timestamp) continue;
2172
+ let usage = {
2173
+ timestamp,
2174
+ model: currentModel,
2175
+ ...tokens,
2176
+ messageId: payload.message_id
2177
+ };
2178
+ pushOrReplaceProgressiveUsage(usages, keyedIndices, usage);
2179
+ }
2180
+ return usages;
2181
+ }
2182
+ async function parseKimiCodeFile(filePath) {
2183
+ let content = await safeRead(filePath);
2184
+ if (content == null) return [];
2185
+ let fallbackTimestamp = await fileModifiedDate(filePath), usages = [];
2186
+ for (let line of content.split(`
2187
+ `)) {
2188
+ if (!line.trim()) continue;
2189
+ let record;
2190
+ try {
2191
+ record = JSON.parse(line);
2192
+ } catch {
2193
+ continue;
1573
2194
  }
2195
+ if (record.type !== "usage.record" || record.usageScope !== "turn" || !record.usage) continue;
2196
+ let tokens = normalizeUsage(record.usage);
2197
+ if (tokens.input + tokens.cached + tokens.cacheWrite + tokens.output === 0) continue;
2198
+ let timestamp = parseTs(record.time ?? record.created_at) ?? fallbackTimestamp;
2199
+ timestamp && usages.push({
2200
+ timestamp,
2201
+ model: normalizeModel2(record.model ?? DEFAULT_MODEL),
2202
+ ...tokens
2203
+ });
1574
2204
  }
1575
- return new Map(
1576
- [...grouped.entries()].map(([date, byModel]) => [date, [...byModel.values()]])
2205
+ return usages;
2206
+ }
2207
+ function addUsage(grouped, sessionSets, dates, usage, projectFields, sessionId) {
2208
+ let usageDate = dateKey(usage.timestamp);
2209
+ if (!dates.has(usageDate)) return;
2210
+ let dayMap = grouped.get(usageDate);
2211
+ if (!dayMap) return;
2212
+ let breakdownKey = `${usage.model}|${projectFields.project}`;
2213
+ accumulate(
2214
+ dayMap,
2215
+ breakdownKey,
2216
+ {
2217
+ provider: "moonshot",
2218
+ product: "kimi-code",
2219
+ channel: "cli",
2220
+ model: usage.model,
2221
+ project: projectFields.project,
2222
+ projectDisplay: projectFields.projectDisplay,
2223
+ projectAlias: projectFields.projectAlias,
2224
+ sessionCount: 0,
2225
+ inputTokens: 0,
2226
+ cachedInputTokens: 0,
2227
+ cacheWriteTokens: 0,
2228
+ outputTokens: 0,
2229
+ reasoningOutputTokens: 0
2230
+ },
2231
+ {
2232
+ input: usage.input,
2233
+ cached: usage.cached,
2234
+ cacheWrite: usage.cacheWrite,
2235
+ output: usage.output,
2236
+ reasoning: 0
2237
+ }
1577
2238
  );
2239
+ let sessionKey = `${usageDate}|${breakdownKey}`, sessions = sessionSets.get(sessionKey);
2240
+ sessions || (sessions = /* @__PURE__ */ new Set(), sessionSets.set(sessionKey, sessions)), sessions.add(sessionId);
1578
2241
  }
1579
- function workspaceToProduct(workspace) {
1580
- let w = workspace.trim().toLowerCase();
1581
- return "claude-code";
2242
+ function normalizeUsage(usage) {
2243
+ return {
2244
+ input: normalizeTokenCount(usage.inputOther ?? usage.input_other),
2245
+ cached: normalizeTokenCount(usage.inputCacheRead ?? usage.input_cache_read),
2246
+ cacheWrite: normalizeTokenCount(usage.inputCacheCreation ?? usage.input_cache_creation),
2247
+ output: normalizeTokenCount(usage.output)
2248
+ };
1582
2249
  }
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
- });
2250
+ function normalizeTokenCount(value) {
2251
+ return typeof value == "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
2252
+ }
2253
+ function normalizeModel2(model) {
2254
+ return model.trim().replace(/^kimi-code\//, "") || DEFAULT_MODEL;
2255
+ }
2256
+ function pushOrReplaceProgressiveUsage(usages, keyedIndices, candidate) {
2257
+ let messageId = candidate.messageId?.trim();
2258
+ if (!messageId) {
2259
+ usages.push(candidate);
2260
+ return;
1603
2261
  }
1604
- return rows;
2262
+ let existingIndex = keyedIndices.get(messageId);
2263
+ if (existingIndex == null) {
2264
+ keyedIndices.set(messageId, usages.length), usages.push(candidate);
2265
+ return;
2266
+ }
2267
+ let existing = usages[existingIndex], existingTotal = totalUsage(existing), candidateTotal = totalUsage(candidate);
2268
+ (candidateTotal > existingTotal || candidateTotal === existingTotal && candidate.timestamp >= existing.timestamp) && (usages[existingIndex] = candidate);
1605
2269
  }
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
2270
+ function totalUsage(usage) {
2271
+ return usage.input + usage.cached + usage.cacheWrite + usage.output;
2272
+ }
2273
+ function getKimiCodePathInfo(filePath) {
2274
+ let agentDir = dirname3(filePath), agentsDir = dirname3(agentDir);
2275
+ if (basename5(agentsDir) !== "agents") return null;
2276
+ let sessionDir = dirname3(agentsDir);
2277
+ return {
2278
+ sessionDir,
2279
+ sessionId: basename5(sessionDir),
2280
+ workspaceKey: basename5(dirname3(sessionDir))
2281
+ };
2282
+ }
2283
+ async function resolveKimiCodeProjectPath(pathInfo, sessionIndex) {
2284
+ try {
2285
+ let raw = await readFile8(join10(pathInfo.sessionDir, "state.json"), "utf-8"), state = JSON.parse(raw);
2286
+ if (state.workDir?.trim()) return state.workDir;
2287
+ } catch {
2288
+ }
2289
+ let indexed = sessionIndex.get(pathInfo.sessionId);
2290
+ return indexed || workspaceLabel(pathInfo.workspaceKey);
2291
+ }
2292
+ function workspaceLabel(workspaceKey) {
2293
+ return workspaceKey.match(/^wd_(.+)_[0-9a-f]{12}$/i)?.[1] || workspaceKey;
2294
+ }
2295
+ async function loadKimiCodeSessionIndex(kimiCodeHome) {
2296
+ let map = /* @__PURE__ */ new Map(), content = await safeRead(join10(kimiCodeHome, "session_index.jsonl"));
2297
+ if (content == null) return map;
2298
+ for (let line of content.split(`
2299
+ `))
2300
+ if (line.trim())
2301
+ try {
2302
+ let record = JSON.parse(line);
2303
+ record.sessionId?.trim() && record.workDir?.trim() && map.set(record.sessionId, record.workDir);
2304
+ } catch {
2305
+ continue;
1706
2306
  }
2307
+ return map;
2308
+ }
2309
+ async function loadLegacyWorkspaceMap(kimiHome) {
2310
+ let map = /* @__PURE__ */ new Map();
2311
+ try {
2312
+ let raw = await readFile8(join10(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
2313
+ for (let [hash, info] of Object.entries(config.workspaces ?? {}))
2314
+ info.path?.trim() && map.set(hash, info.path);
2315
+ } catch {
2316
+ }
2317
+ return map;
2318
+ }
2319
+ async function loadLegacyModel(kimiHome) {
2320
+ for (let name of ["config.json", "kimi.json"])
2321
+ try {
2322
+ let raw = await readFile8(join10(kimiHome, name), "utf-8"), config = JSON.parse(raw);
2323
+ if (config.model?.trim()) return normalizeModel2(config.model);
2324
+ } catch {
2325
+ continue;
1707
2326
  }
2327
+ return DEFAULT_MODEL;
2328
+ }
2329
+ async function safeRead(filePath) {
2330
+ try {
2331
+ return await readFile8(filePath, "utf-8");
2332
+ } catch {
2333
+ return null;
1708
2334
  }
1709
- };
2335
+ }
2336
+ async function fileModifiedDate(filePath) {
2337
+ try {
2338
+ return (await stat(filePath)).mtime;
2339
+ } catch {
2340
+ return null;
2341
+ }
2342
+ }
1710
2343
 
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
2344
+ // src/scanners/amp.ts
2345
+ import { readFile as readFile9 } from "node:fs/promises";
2346
+ import { join as join11 } from "node:path";
2347
+ import { homedir as homedir10 } from "node:os";
2348
+ function resolveAmpDir(baseDir) {
2349
+ if (baseDir) return baseDir;
2350
+ let ampDataDir = process.env.AMP_DATA_DIR;
2351
+ if (ampDataDir) return join11(ampDataDir, "threads");
2352
+ let xdgDataHome = process.env.XDG_DATA_HOME;
2353
+ return xdgDataHome ? join11(xdgDataHome, "amp", "threads") : join11(homedir10(), ".local", "share", "amp", "threads");
2354
+ }
2355
+ async function scanAmpDates(targetDates, baseDir, _projectAliases) {
2356
+ let dates = new Set(targetDates), dir = resolveAmpDir(baseDir), threadFiles = (await walkFiles(dir, ".json")).filter((f) => {
2357
+ let name = f.split("/").pop() ?? "";
2358
+ return name.startsWith("T-") && name.endsWith(".json");
2359
+ });
2360
+ if (threadFiles.length === 0) return emptyResult(dates);
2361
+ let grouped = initDateMap(dates);
2362
+ for (let filePath of threadFiles) {
2363
+ let raw;
2364
+ try {
2365
+ raw = await readFile9(filePath, "utf-8");
2366
+ } catch {
2367
+ continue;
2368
+ }
2369
+ let thread;
2370
+ try {
2371
+ thread = JSON.parse(raw);
2372
+ } catch {
2373
+ continue;
2374
+ }
2375
+ let ledgerEvents = thread.usageLedger?.events;
2376
+ Array.isArray(ledgerEvents) && ledgerEvents.length > 0 ? processLedger(thread, ledgerEvents, dates, grouped) : processMessages(thread, dates, grouped);
2377
+ }
2378
+ return finalize(grouped);
2379
+ }
2380
+ function getMessageByKey(messages, key) {
2381
+ if (messages) {
2382
+ if (Array.isArray(messages)) {
2383
+ let idx = parseInt(key, 10);
2384
+ return isNaN(idx) ? void 0 : messages[idx];
2385
+ }
2386
+ return messages[key];
2387
+ }
2388
+ }
2389
+ function processLedger(thread, events, dates, grouped) {
2390
+ for (let event of events) {
2391
+ let ts = parseTs(event.timestamp);
2392
+ if (!ts) continue;
2393
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2394
+ if (!dayMap) continue;
2395
+ let model = event.model ?? "unknown", input = event.tokens?.input ?? 0, output = event.tokens?.output ?? 0, cached2 = 0;
2396
+ event.toMessageId && (cached2 = getMessageByKey(thread.messages, event.toMessageId)?.usage?.cacheReadInputTokens ?? 0), accumulate(
2397
+ dayMap,
2398
+ `${model}|unknown`,
2399
+ {
2400
+ provider: "sourcegraph",
2401
+ product: "amp",
2402
+ channel: "cli",
2403
+ model,
2404
+ project: "unknown",
2405
+ projectDisplay: "unknown",
2406
+ inputTokens: 0,
2407
+ cachedInputTokens: 0,
2408
+ cacheWriteTokens: 0,
2409
+ outputTokens: 0,
2410
+ reasoningOutputTokens: 0
1862
2411
  },
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
2412
+ { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
2413
+ );
2414
+ }
2415
+ }
2416
+ function processMessages(thread, dates, grouped) {
2417
+ let msgs2 = thread.messages;
2418
+ if (!msgs2) return;
2419
+ let entries = Array.isArray(msgs2) ? msgs2 : Object.values(msgs2);
2420
+ for (let msg of entries) {
2421
+ let usage = msg.usage;
2422
+ if (!usage) continue;
2423
+ let ts = parseTs(msg.timestamp ?? thread.created);
2424
+ if (!ts) continue;
2425
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2426
+ if (!dayMap) continue;
2427
+ let model = msg.model ?? "unknown", input = usage.inputTokens ?? 0, output = usage.outputTokens ?? 0, cached2 = usage.cacheReadInputTokens ?? 0;
2428
+ accumulate(
2429
+ dayMap,
2430
+ `${model}|unknown`,
2431
+ {
2432
+ provider: "sourcegraph",
2433
+ product: "amp",
2434
+ channel: "cli",
2435
+ model,
2436
+ project: "unknown",
2437
+ projectDisplay: "unknown",
2438
+ inputTokens: 0,
2439
+ cachedInputTokens: 0,
2440
+ cacheWriteTokens: 0,
2441
+ outputTokens: 0,
2442
+ reasoningOutputTokens: 0
1869
2443
  },
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 }
1892
- }
2444
+ { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
2445
+ );
1893
2446
  }
1894
- };
2447
+ }
1895
2448
 
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
2070
- }
2449
+ // src/scanners/droid.ts
2450
+ import { readFile as readFile10 } from "node:fs/promises";
2451
+ import { join as join12, dirname as dirname4, basename as basename6 } from "node:path";
2452
+ import { homedir as homedir11 } from "node:os";
2453
+ function extractProjectFromSlug(dirPath) {
2454
+ let parts = basename6(dirPath).split("-").filter(Boolean);
2455
+ return parts[parts.length - 1] || "unknown";
2456
+ }
2457
+ async function scanDroidDates(targetDates, baseDir, projectAliases) {
2458
+ let dates = new Set(targetDates), dir = baseDir ?? join12(homedir11(), ".factory", "sessions"), files = await walkFiles(dir, ".jsonl");
2459
+ if (files.length === 0) return emptyResult(dates);
2460
+ let grouped = initDateMap(dates);
2461
+ for (let jsonlPath of files) {
2462
+ let content;
2463
+ try {
2464
+ content = await readFile10(jsonlPath, "utf-8");
2465
+ } catch {
2466
+ continue;
2467
+ }
2468
+ let firstLine = content.split(`
2469
+ `).find((l) => l.trim());
2470
+ if (!firstLine) continue;
2471
+ let firstObj;
2472
+ try {
2473
+ firstObj = JSON.parse(firstLine);
2474
+ } catch {
2475
+ continue;
2476
+ }
2477
+ let ts = parseTs(firstObj.timestamp);
2478
+ if (!ts) continue;
2479
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2480
+ if (!dayMap) continue;
2481
+ let sessionDir = dirname4(jsonlPath), jsonlName = basename6(jsonlPath, ".jsonl"), settingsPath = join12(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
2482
+ try {
2483
+ settingsRaw = await readFile10(settingsPath, "utf-8");
2484
+ } catch {
2485
+ continue;
2486
+ }
2487
+ let settings;
2488
+ try {
2489
+ settings = JSON.parse(settingsRaw);
2490
+ } catch {
2491
+ continue;
2071
2492
  }
2493
+ let usage = settings.tokenUsage;
2494
+ if (!usage) continue;
2495
+ 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;
2496
+ accumulate(
2497
+ dayMap,
2498
+ `${model}|${project}`,
2499
+ {
2500
+ provider: "droid",
2501
+ product: "droid",
2502
+ channel: "cli",
2503
+ model,
2504
+ project,
2505
+ projectDisplay: rawProject,
2506
+ projectAlias: alias,
2507
+ inputTokens: 0,
2508
+ cachedInputTokens: 0,
2509
+ cacheWriteTokens: 0,
2510
+ outputTokens: 0,
2511
+ reasoningOutputTokens: 0
2512
+ },
2513
+ { input, cached: cacheRead, cacheWrite: 0, output, reasoning: thinking }
2514
+ );
2072
2515
  }
2073
- };
2516
+ return finalize(grouped);
2517
+ }
2074
2518
 
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
2153
- }
2519
+ // src/scanners/opencode.ts
2520
+ import { readFile as readFile11 } from "node:fs/promises";
2521
+ import { homedir as homedir12 } from "node:os";
2522
+ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
2523
+ let dates = new Set(targetDates), dir = baseDir ?? `${homedir12()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
2524
+ if (files.length === 0) return emptyResult(dates);
2525
+ let grouped = initDateMap(dates);
2526
+ for (let filePath of files) {
2527
+ let raw;
2528
+ try {
2529
+ raw = await readFile11(filePath, "utf-8");
2530
+ } catch {
2531
+ continue;
2154
2532
  }
2533
+ let msg;
2534
+ try {
2535
+ msg = JSON.parse(raw);
2536
+ } catch {
2537
+ continue;
2538
+ }
2539
+ let tokens = msg.tokens;
2540
+ if (!tokens) continue;
2541
+ let input = tokens.input ?? 0, output = tokens.output ?? 0;
2542
+ if (input === 0 && output === 0) continue;
2543
+ let ts = parseTs(msg.time?.created);
2544
+ if (!ts) continue;
2545
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2546
+ if (!dayMap) continue;
2547
+ 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" };
2548
+ accumulate(
2549
+ dayMap,
2550
+ `${model}|${fields.project}`,
2551
+ {
2552
+ provider: "opencode",
2553
+ product: "opencode",
2554
+ channel: "cli",
2555
+ model,
2556
+ project: fields.project,
2557
+ projectDisplay: fields.projectDisplay,
2558
+ projectAlias: fields.projectAlias,
2559
+ inputTokens: 0,
2560
+ cachedInputTokens: 0,
2561
+ cacheWriteTokens: 0,
2562
+ outputTokens: 0,
2563
+ reasoningOutputTokens: 0
2564
+ },
2565
+ { input, cached: cached2, cacheWrite: 0, output, reasoning }
2566
+ );
2155
2567
  }
2156
- };
2568
+ return finalize(grouped);
2569
+ }
2157
2570
 
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
2217
- },
2218
- "qwen3-235b-a22b-thinking-2507": {
2219
- currency: "CNY",
2220
- input_per_million: 2,
2221
- output_per_million: 20
2222
- },
2223
- "qwen3-235b-a22b-instruct-2507": {
2224
- currency: "CNY",
2225
- input_per_million: 2,
2226
- output_per_million: 8
2571
+ // src/scanners/pi.ts
2572
+ import { readFile as readFile12 } from "node:fs/promises";
2573
+ import { join as join13, basename as basename7, dirname as dirname5 } from "node:path";
2574
+ import { homedir as homedir13 } from "node:os";
2575
+ async function scanPiDates(targetDates, baseDir, projectAliases) {
2576
+ let dates = new Set(targetDates), sessionsDir = baseDir ?? getSessionsDir(), files = await walkFiles(sessionsDir, ".jsonl");
2577
+ if (files.length === 0) return emptyResult(dates);
2578
+ let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
2579
+ for (let filePath of files) {
2580
+ let content;
2581
+ try {
2582
+ content = await readFile12(filePath, "utf-8");
2583
+ } catch {
2584
+ continue;
2585
+ }
2586
+ let parentDir = dirname5(filePath), encodedCwd = basename7(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(encodedCwd) };
2587
+ for (let line of content.split(`
2588
+ `)) {
2589
+ if (!line.trim()) continue;
2590
+ let obj;
2591
+ try {
2592
+ obj = JSON.parse(line);
2593
+ } catch {
2594
+ continue;
2595
+ }
2596
+ if (obj.type === "session" && obj.cwd) {
2597
+ sessionProjectFields = resolveProjectFields(obj.cwd, projectAliases);
2598
+ continue;
2599
+ }
2600
+ if (obj.type !== "message") continue;
2601
+ let msg = obj.message;
2602
+ if (!msg || msg.role !== "assistant") continue;
2603
+ let usage = msg.usage;
2604
+ if (!usage || usage.input == null && usage.output == null) continue;
2605
+ let ts = parseTs(obj.timestamp);
2606
+ if (!ts) continue;
2607
+ let dk = dateKey(ts), dayMap = grouped.get(dk);
2608
+ if (!dayMap) continue;
2609
+ if (obj.id) {
2610
+ if (seen.has(obj.id)) continue;
2611
+ seen.add(obj.id);
2227
2612
  }
2613
+ let model = msg.model ?? "unknown", input = usage.input ?? 0, cached2 = usage.cacheRead ?? 0, output = usage.output ?? 0;
2614
+ accumulate(
2615
+ dayMap,
2616
+ `${model}|${sessionProjectFields.project}`,
2617
+ {
2618
+ provider: "inflection",
2619
+ product: "pi",
2620
+ channel: "cli",
2621
+ model,
2622
+ project: sessionProjectFields.project,
2623
+ projectDisplay: sessionProjectFields.projectDisplay,
2624
+ projectAlias: sessionProjectFields.projectAlias,
2625
+ inputTokens: 0,
2626
+ cachedInputTokens: 0,
2627
+ cacheWriteTokens: 0,
2628
+ outputTokens: 0,
2629
+ reasoningOutputTokens: 0
2630
+ },
2631
+ { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
2632
+ );
2228
2633
  }
2229
2634
  }
2230
- };
2635
+ return finalize(grouped);
2636
+ }
2637
+ function getSessionsDir() {
2638
+ let envDir = process.env.PI_CODING_AGENT_DIR;
2639
+ return envDir ? join13(envDir, "sessions") : join13(homedir13(), ".pi", "agent", "sessions");
2640
+ }
2641
+ function extractProjectFromEncoded(encoded) {
2642
+ let parts = encoded.split("-").filter(Boolean);
2643
+ return parts.length > 0 ? parts[parts.length - 1] : "unknown";
2644
+ }
2231
2645
 
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"
2249
- },
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
2257
- },
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
2264
- }
2265
- }
2266
- }
2267
- };
2646
+ // src/scan.ts
2647
+ async function scanDate(targetDate, options = {}) {
2648
+ let [result] = await scanDates([targetDate], options);
2649
+ return result ?? {
2650
+ usageDate: targetDate,
2651
+ breakdowns: [],
2652
+ totals: createEmptyTotals()
2653
+ };
2654
+ }
2655
+ async function scanDates(targetDates, options = {}) {
2656
+ let uniqueDates = [...new Set(targetDates)];
2657
+ if (uniqueDates.length === 0) return [];
2658
+ let scanners = [
2659
+ scanAntigravityDates(uniqueDates),
2660
+ scanClaudeDates(uniqueDates, void 0, options.projectAliases),
2661
+ scanCodexDates(uniqueDates, void 0, options.projectAliases),
2662
+ scanCopilotDates(uniqueDates, void 0, options.projectAliases),
2663
+ scanCopilotVscodeDates(uniqueDates, void 0, options.projectAliases),
2664
+ scanCursorDates(uniqueDates),
2665
+ scanGeminiDates(uniqueDates, void 0, options.projectAliases),
2666
+ scanQwenDates(uniqueDates, void 0, options.projectAliases),
2667
+ scanKimiDates(uniqueDates, void 0, options.projectAliases),
2668
+ scanAmpDates(uniqueDates, void 0, options.projectAliases),
2669
+ scanDroidDates(uniqueDates, void 0, options.projectAliases),
2670
+ scanOpencodeDates(uniqueDates, void 0, options.projectAliases),
2671
+ scanPiDates(uniqueDates, void 0, options.projectAliases)
2672
+ ], results = await Promise.all(scanners);
2673
+ return uniqueDates.map((usageDate) => {
2674
+ let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []), totals = breakdowns.reduce(
2675
+ (acc, b) => ({
2676
+ eventCount: acc.eventCount + b.eventCount,
2677
+ inputTokens: acc.inputTokens + b.inputTokens,
2678
+ cachedInputTokens: acc.cachedInputTokens + b.cachedInputTokens,
2679
+ cacheWriteTokens: acc.cacheWriteTokens + b.cacheWriteTokens,
2680
+ outputTokens: acc.outputTokens + b.outputTokens,
2681
+ reasoningOutputTokens: acc.reasoningOutputTokens + b.reasoningOutputTokens
2682
+ }),
2683
+ createEmptyTotals()
2684
+ );
2685
+ return { usageDate, breakdowns, totals };
2686
+ });
2687
+ }
2688
+ function createEmptyTotals() {
2689
+ return {
2690
+ eventCount: 0,
2691
+ inputTokens: 0,
2692
+ cachedInputTokens: 0,
2693
+ cacheWriteTokens: 0,
2694
+ outputTokens: 0,
2695
+ reasoningOutputTokens: 0
2696
+ };
2697
+ }
2268
2698
 
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
2699
+ // src/scanners/anthropic-admin-api.ts
2700
+ var ADMIN_API_BASE = "https://api.anthropic.com", USAGE_ENDPOINT = "/v1/organizations/usage_report/messages", MAX_DAYS_PER_REQUEST = 31;
2701
+ async function scanAnthropicApiDates(targetDates, adminApiKey) {
2702
+ if (!targetDates.length || !adminApiKey)
2703
+ return new Map(targetDates.map((d) => [d, []]));
2704
+ let sorted = [...new Set(targetDates)].sort(), grouped = new Map(sorted.map((d) => [d, []])), chunks = chunkDateRange(sorted[0], sorted[sorted.length - 1]);
2705
+ for (let { startingAt, endingAt } of chunks)
2706
+ await fetchAndMerge(startingAt, endingAt, adminApiKey, sorted, grouped);
2707
+ return grouped;
2708
+ }
2709
+ async function fetchAndMerge(startingAt, endingAt, adminApiKey, targetDates, grouped) {
2710
+ let nextPage = null;
2711
+ do {
2712
+ let url = buildUrl(startingAt, endingAt, nextPage), resp;
2713
+ try {
2714
+ resp = await fetch(url, {
2715
+ headers: {
2716
+ "x-api-key": adminApiKey,
2717
+ "anthropic-version": "2023-06-01"
2718
+ }
2719
+ });
2720
+ } catch (err) {
2721
+ throw new Error(`Anthropic Admin API request failed: ${err}`);
2722
+ }
2723
+ if (!resp.ok) {
2724
+ let body = await resp.text().catch(() => "");
2725
+ throw new Error(`Anthropic Admin API error ${resp.status}: ${body}`);
2726
+ }
2727
+ let data = await resp.json();
2728
+ for (let bucket of data.data) {
2729
+ let date = bucket.starting_at.slice(0, 10);
2730
+ if (!targetDates.includes(date)) continue;
2731
+ let breakdowns = grouped.get(date);
2732
+ for (let result of bucket.results) {
2733
+ if (!result.model) continue;
2734
+ 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;
2735
+ if (inputTokens + outputTokens + cachedInputTokens + cacheWriteTokens === 0) continue;
2736
+ let existing = breakdowns.find((b) => b.model === model);
2737
+ 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({
2738
+ provider: "anthropic",
2739
+ product: "claude-code",
2740
+ channel: "cli",
2741
+ model,
2742
+ project: "unknown",
2743
+ eventCount: 1,
2744
+ inputTokens,
2745
+ cachedInputTokens,
2746
+ cacheWriteTokens,
2747
+ cacheWrite5mTokens: cacheWrite5m,
2748
+ cacheWrite1hTokens: cacheWrite1h,
2749
+ outputTokens,
2750
+ reasoningOutputTokens: 0
2751
+ });
2358
2752
  }
2359
2753
  }
2754
+ nextPage = data.has_more ? data.next_page : null;
2755
+ } while (nextPage);
2756
+ }
2757
+ function buildUrl(startingAt, endingAt, page) {
2758
+ let params = new URLSearchParams({
2759
+ starting_at: startingAt,
2760
+ ending_at: endingAt,
2761
+ bucket_width: "1d"
2762
+ });
2763
+ return params.append("group_by[]", "model"), page && params.set("page", page), `${ADMIN_API_BASE}${USAGE_ENDPOINT}?${params}`;
2764
+ }
2765
+ function chunkDateRange(startDate, endDate) {
2766
+ let chunks = [], current = /* @__PURE__ */ new Date(`${startDate}T00:00:00Z`), end = /* @__PURE__ */ new Date(`${endDate}T00:00:00Z`);
2767
+ for (end.setUTCDate(end.getUTCDate() + 1); current < end; ) {
2768
+ let chunkEnd = new Date(current);
2769
+ chunkEnd.setUTCDate(chunkEnd.getUTCDate() + MAX_DAYS_PER_REQUEST);
2770
+ let actualEnd = chunkEnd < end ? chunkEnd : end;
2771
+ chunks.push({
2772
+ startingAt: current.toISOString().replace(".000Z", "Z"),
2773
+ endingAt: actualEnd.toISOString().replace(".000Z", "Z")
2774
+ }), current = actualEnd;
2360
2775
  }
2361
- };
2776
+ return chunks;
2777
+ }
2362
2778
 
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 }
2779
+ // src/scanners/anthropic-csv.ts
2780
+ import { readFile as readFile13 } from "node:fs/promises";
2781
+ async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
2782
+ if (!targetDates.length) return /* @__PURE__ */ new Map();
2783
+ let targetDateSet = new Set(targetDates), grouped = new Map(
2784
+ targetDates.map((d) => [d, /* @__PURE__ */ new Map()])
2785
+ );
2786
+ for (let filePath of csvFilePaths) {
2787
+ let content;
2788
+ try {
2789
+ content = await readFile13(filePath, "utf-8");
2790
+ } catch {
2791
+ continue;
2375
2792
  }
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 }
2793
+ let rows = parseCsv(content);
2794
+ for (let row of rows) {
2795
+ 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;
2796
+ 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;
2797
+ 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, {
2798
+ provider: "anthropic",
2799
+ product,
2800
+ channel: "cli",
2801
+ model,
2802
+ project: "unknown",
2803
+ eventCount: 1,
2804
+ inputTokens: row.usage_input_tokens_no_cache,
2805
+ cachedInputTokens: row.usage_input_tokens_cache_read,
2806
+ cacheWriteTokens,
2807
+ cacheWrite5mTokens: row.usage_input_tokens_cache_write_5m,
2808
+ cacheWrite1hTokens: row.usage_input_tokens_cache_write_1h,
2809
+ outputTokens: row.usage_output_tokens,
2810
+ reasoningOutputTokens: 0
2811
+ });
2386
2812
  }
2387
2813
  }
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 };
2444
- }
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;
2814
+ return new Map(
2815
+ [...grouped.entries()].map(([date, byModel]) => [date, [...byModel.values()]])
2816
+ );
2447
2817
  }
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 };
2461
- }
2462
- return null;
2818
+ function workspaceToProduct(workspace) {
2819
+ let w = workspace.trim().toLowerCase();
2820
+ return "claude-code";
2463
2821
  }
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 };
2822
+ function parseCsv(content) {
2823
+ let lines = content.split(`
2824
+ `).map((l) => l.trim()).filter(Boolean);
2825
+ if (lines.length < 2) return [];
2826
+ let headers = lines[0].split(",").map((h) => h.trim()), rows = [];
2827
+ for (let i = 1; i < lines.length; i++) {
2828
+ let values = lines[i].split(","), row = {};
2829
+ for (let j = 0; j < headers.length; j++)
2830
+ row[headers[j]] = values[j]?.trim() ?? "";
2831
+ let date = row.usage_date_utc;
2832
+ !date || !/^\d{4}-\d{2}-\d{2}$/.test(date) || rows.push({
2833
+ usage_date_utc: date,
2834
+ model_version: row.model_version ?? "",
2835
+ workspace: row.workspace ?? "",
2836
+ usage_input_tokens_no_cache: parseInt(row.usage_input_tokens_no_cache ?? "0", 10) || 0,
2837
+ usage_input_tokens_cache_write_5m: parseInt(row.usage_input_tokens_cache_write_5m ?? "0", 10) || 0,
2838
+ usage_input_tokens_cache_write_1h: parseInt(row.usage_input_tokens_cache_write_1h ?? "0", 10) || 0,
2839
+ usage_input_tokens_cache_read: parseInt(row.usage_input_tokens_cache_read ?? "0", 10) || 0,
2840
+ usage_output_tokens: parseInt(row.usage_output_tokens ?? "0", 10) || 0
2841
+ });
2469
2842
  }
2470
- return { tier: tiers[tiers.length - 1], index: tiers.length - 1 };
2471
- }
2472
- function toUsd(amount, currency, catalog2) {
2473
- if (currency === "USD") return amount;
2474
- let rate = catalog2.fx[currency];
2475
- return rate ? amount / rate : amount;
2476
- }
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
- };
2843
+ return rows;
2506
2844
  }
2507
2845
 
2508
2846
  // src/report.ts
2847
+ import { readdir as readdir6, readFile as readFile14 } from "node:fs/promises";
2848
+ import { homedir as homedir14 } from "node:os";
2849
+ import { basename as basename8, join as join14 } from "node:path";
2509
2850
  async function buildLocalReport(range, options = {}) {
2510
2851
  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
2852
  for (let result of results) {
@@ -2583,6 +2924,7 @@ async function discoverAllDates() {
2583
2924
  discoverGenericJsonlDates(join14(home, ".copilot", "session-state"), dates),
2584
2925
  discoverGenericJsonlDates(join14(home, ".qwen", "tmp"), dates),
2585
2926
  discoverGenericJsonlDates(join14(home, ".kimi", "sessions"), dates),
2927
+ discoverGenericJsonlDates(join14(resolveKimiCodeHome(home), "sessions"), dates),
2586
2928
  discoverGenericJsonDates(join14(home, ".local", "share", "amp", "threads"), dates),
2587
2929
  discoverGenericJsonlDates(join14(home, ".factory", "sessions"), dates),
2588
2930
  discoverGenericJsonDates(join14(home, ".local", "share", "opencode"), dates),
@@ -2604,7 +2946,7 @@ async function discoverGenericJsonlDates(baseDir, dates) {
2604
2946
  } catch {
2605
2947
  continue;
2606
2948
  }
2607
- let ts = parseTs(record.timestamp);
2949
+ let ts = parseTs(record.timestamp ?? record.time ?? record.created_at);
2608
2950
  ts && dates.add(dateKey(ts));
2609
2951
  }
2610
2952
  }
@@ -2891,7 +3233,8 @@ function toBreakdownTotals(breakdown, warnings, pricingCatalog) {
2891
3233
  };
2892
3234
  }
2893
3235
  function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
2894
- if (breakdown.costUSD != null && breakdown.costUSD > 0)
3236
+ let effectivePricingVersion = pricingCatalog?.version ?? PRICING_VERSION, sourceCostMatchesCatalog = breakdown.pricingVersion == null || breakdown.pricingVersion === effectivePricingVersion;
3237
+ if (breakdown.costUSD != null && breakdown.costUSD > 0 && sourceCostMatchesCatalog)
2895
3238
  return breakdown.costUSD;
2896
3239
  let result = calculateCost(
2897
3240
  breakdown.provider,
@@ -2905,9 +3248,12 @@ function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
2905
3248
  cacheWrite1hTokens: breakdown.cacheWrite1hTokens,
2906
3249
  outputTokens: breakdown.outputTokens
2907
3250
  },
2908
- pricingCatalog ? { catalog: pricingCatalog } : {}
3251
+ {
3252
+ ...pricingCatalog ? { catalog: pricingCatalog } : {},
3253
+ requestCount: breakdown.eventCount
3254
+ }
2909
3255
  );
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;
3256
+ 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
3257
  }
2912
3258
 
2913
3259
  // src/i18n.ts
@@ -3914,7 +4260,7 @@ async function requestJson(url, init) {
3914
4260
  }
3915
4261
 
3916
4262
  // src/schedule.ts
3917
- import { mkdir as mkdir2, readFile as readFile16, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
4263
+ import { mkdir as mkdir2, readFile as readFile16, stat as stat2, unlink, writeFile as writeFile2 } from "node:fs/promises";
3918
4264
  import { execFile } from "node:child_process";
3919
4265
  import { promisify } from "node:util";
3920
4266
  import { homedir as homedir17, platform, tmpdir as tmpdir2 } from "node:os";
@@ -4013,7 +4359,7 @@ async function disableLaunchd() {
4013
4359
  }
4014
4360
  async function getLaunchdStatus() {
4015
4361
  try {
4016
- await stat(PLIST_PATH);
4362
+ await stat2(PLIST_PATH);
4017
4363
  } catch {
4018
4364
  return { enabled: !1 };
4019
4365
  }
@@ -4123,7 +4469,7 @@ function escapeXml(value) {
4123
4469
  }
4124
4470
 
4125
4471
  // src/doctor.ts
4126
- import { readdir as readdir8, stat as stat2 } from "node:fs/promises";
4472
+ import { readdir as readdir8, stat as stat3 } from "node:fs/promises";
4127
4473
  import { homedir as homedir18 } from "node:os";
4128
4474
  import { join as join18 } from "node:path";
4129
4475
  var msgs = {
@@ -4196,7 +4542,7 @@ async function countFiles(dir, exts, cap = 1e3) {
4196
4542
  async function runDoctor(lang = "zh") {
4197
4543
  let s = msgs[lang], checks = [], config = await readConfig(), g1 = s.groupConfig, configPath = getConfigPath();
4198
4544
  try {
4199
- await stat2(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
4545
+ await stat3(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
4200
4546
  } catch {
4201
4547
  checks.push({ group: g1, name: s.config, status: "fail", message: s.configMissing });
4202
4548
  }
@@ -4225,7 +4571,8 @@ async function runDoctor(lang = "zh") {
4225
4571
  { dir: join18(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
4226
4572
  { dir: join18(home, ".gemini", "antigravity"), label: "Antigravity", exts: [".json"] },
4227
4573
  { dir: join18(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
4228
- { dir: join18(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
4574
+ { dir: join18(resolveKimiCodeHome(home), "sessions"), label: "Kimi Code", exts: [".jsonl"] },
4575
+ { dir: join18(home, ".kimi", "sessions"), label: "Kimi CLI (legacy)", exts: [".jsonl"] },
4229
4576
  { dir: join18(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
4230
4577
  { dir: join18(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
4231
4578
  { dir: join18(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
@@ -4233,7 +4580,7 @@ async function runDoctor(lang = "zh") {
4233
4580
  ];
4234
4581
  for (let tool of tools) {
4235
4582
  try {
4236
- await stat2(tool.dir);
4583
+ await stat3(tool.dir);
4237
4584
  } catch {
4238
4585
  checks.push({ group: g3, name: tool.label, status: "warn", message: s.notInstalled });
4239
4586
  continue;
@@ -4279,7 +4626,9 @@ async function discoverProjects(projectAliases) {
4279
4626
  discoverGeminiProjects().then((names) => names.forEach((n) => add(n, "gemini"))),
4280
4627
  // Antigravity: ~/.gemini/antigravity/knowledge/*/metadata.json
4281
4628
  // 仅读取知识项元数据标题,不读取对话内容
4282
- discoverAntigravityProjects().then((names) => names.forEach((n) => add(n, "antigravity")))
4629
+ discoverAntigravityProjects().then((names) => names.forEach((n) => add(n, "antigravity"))),
4630
+ // Kimi CLI / Kimi Code: legacy workspace map + new session metadata.
4631
+ discoverKimiProjects().then((names) => names.forEach((n) => add(n, "kimi")))
4283
4632
  ]);
4284
4633
  let results = [];
4285
4634
  for (let [name, sources] of projectMap) {
@@ -4490,6 +4839,40 @@ async function discoverAntigravityProjects() {
4490
4839
  }
4491
4840
  return [...projects];
4492
4841
  }
4842
+ async function discoverKimiProjects() {
4843
+ let projects = /* @__PURE__ */ new Set(), home = homedir19();
4844
+ try {
4845
+ let raw = await readFile17(join19(home, ".kimi", "kimi.json"), "utf-8"), data = JSON.parse(raw);
4846
+ for (let workspace of Object.values(data.workspaces ?? {})) {
4847
+ let name = basename11(workspace.path?.trim() ?? "");
4848
+ name && name !== "unknown" && projects.add(name);
4849
+ }
4850
+ } catch {
4851
+ }
4852
+ let codeHome = resolveKimiCodeHome(home);
4853
+ try {
4854
+ let raw = await readFile17(join19(codeHome, "session_index.jsonl"), "utf-8");
4855
+ for (let line of raw.split(`
4856
+ `))
4857
+ if (line.trim())
4858
+ try {
4859
+ let record = JSON.parse(line), name = basename11(record.workDir?.trim() ?? "");
4860
+ name && name !== "unknown" && projects.add(name);
4861
+ } catch {
4862
+ continue;
4863
+ }
4864
+ } catch {
4865
+ }
4866
+ let stateFiles = (await walkFiles2(join19(codeHome, "sessions"), ".json")).filter((filePath) => basename11(filePath) === "state.json");
4867
+ for (let filePath of stateFiles)
4868
+ try {
4869
+ let raw = await readFile17(filePath, "utf-8"), state = JSON.parse(raw), name = basename11(state.workDir?.trim() ?? "");
4870
+ name && name !== "unknown" && projects.add(name);
4871
+ } catch {
4872
+ continue;
4873
+ }
4874
+ return [...projects];
4875
+ }
4493
4876
  function nameFromFileUri(raw) {
4494
4877
  let path = pathFromFileUri(raw);
4495
4878
  if (!path) return;