@anthonyhan/token-pilot 0.0.0-stage → 0.2.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.
Files changed (134) hide show
  1. package/.github/FUNDING.yml +3 -0
  2. package/.github/workflows/build-desktop.yml +68 -0
  3. package/.idea/go.imports.xml +10 -0
  4. package/.idea/modules.xml +8 -0
  5. package/.idea/sonarlint/vulnerabilitystore/default/index.pb +0 -0
  6. package/.idea/thriftCompilerAssist.xml +6 -0
  7. package/.idea/token-pilot.iml +9 -0
  8. package/.idea/vcs.xml +6 -0
  9. package/README-en.md +127 -0
  10. package/README.md +146 -2
  11. package/bin/token-pilot.js +15 -0
  12. package/docs/assets/dashboard.png +0 -0
  13. package/docs/assets/icon.png +0 -0
  14. package/docs/assets/menubar-panel.png +0 -0
  15. package/docs/assets/sponsor-alipay.png +0 -0
  16. package/docs/assets/sponsor-wechat.png +0 -0
  17. package/llms.txt +40 -0
  18. package/menubar/package-lock.json +248 -0
  19. package/menubar/package.json +16 -0
  20. package/menubar/src/dashboard.html +1266 -0
  21. package/menubar/src/index.html +674 -0
  22. package/menubar/src-tauri/Cargo.lock +4963 -0
  23. package/menubar/src-tauri/Cargo.toml +15 -0
  24. package/menubar/src-tauri/build.rs +3 -0
  25. package/menubar/src-tauri/gen/schemas/acl-manifests.json +1 -0
  26. package/menubar/src-tauri/gen/schemas/capabilities.json +1 -0
  27. package/menubar/src-tauri/gen/schemas/desktop-schema.json +2526 -0
  28. package/menubar/src-tauri/gen/schemas/macOS-schema.json +2526 -0
  29. package/menubar/src-tauri/icons/128x128.png +0 -0
  30. package/menubar/src-tauri/icons/128x128@2x.png +0 -0
  31. package/menubar/src-tauri/icons/32x32.png +0 -0
  32. package/menubar/src-tauri/icons/64x64.png +0 -0
  33. package/menubar/src-tauri/icons/Square107x107Logo.png +0 -0
  34. package/menubar/src-tauri/icons/Square142x142Logo.png +0 -0
  35. package/menubar/src-tauri/icons/Square150x150Logo.png +0 -0
  36. package/menubar/src-tauri/icons/Square284x284Logo.png +0 -0
  37. package/menubar/src-tauri/icons/Square30x30Logo.png +0 -0
  38. package/menubar/src-tauri/icons/Square310x310Logo.png +0 -0
  39. package/menubar/src-tauri/icons/Square44x44Logo.png +0 -0
  40. package/menubar/src-tauri/icons/Square71x71Logo.png +0 -0
  41. package/menubar/src-tauri/icons/Square89x89Logo.png +0 -0
  42. package/menubar/src-tauri/icons/StoreLogo.png +0 -0
  43. package/menubar/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml +5 -0
  44. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png +0 -0
  45. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png +0 -0
  46. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png +0 -0
  47. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png +0 -0
  48. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png +0 -0
  49. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png +0 -0
  50. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png +0 -0
  51. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png +0 -0
  52. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png +0 -0
  53. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png +0 -0
  54. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png +0 -0
  55. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png +0 -0
  56. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png +0 -0
  57. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
  58. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png +0 -0
  59. package/menubar/src-tauri/icons/android/values/ic_launcher_background.xml +4 -0
  60. package/menubar/src-tauri/icons/icon.icns +0 -0
  61. package/menubar/src-tauri/icons/icon.ico +0 -0
  62. package/menubar/src-tauri/icons/icon.png +0 -0
  63. package/menubar/src-tauri/icons/ios/AppIcon-20x20@1x.png +0 -0
  64. package/menubar/src-tauri/icons/ios/AppIcon-20x20@2x-1.png +0 -0
  65. package/menubar/src-tauri/icons/ios/AppIcon-20x20@2x.png +0 -0
  66. package/menubar/src-tauri/icons/ios/AppIcon-20x20@3x.png +0 -0
  67. package/menubar/src-tauri/icons/ios/AppIcon-29x29@1x.png +0 -0
  68. package/menubar/src-tauri/icons/ios/AppIcon-29x29@2x-1.png +0 -0
  69. package/menubar/src-tauri/icons/ios/AppIcon-29x29@2x.png +0 -0
  70. package/menubar/src-tauri/icons/ios/AppIcon-29x29@3x.png +0 -0
  71. package/menubar/src-tauri/icons/ios/AppIcon-40x40@1x.png +0 -0
  72. package/menubar/src-tauri/icons/ios/AppIcon-40x40@2x-1.png +0 -0
  73. package/menubar/src-tauri/icons/ios/AppIcon-40x40@2x.png +0 -0
  74. package/menubar/src-tauri/icons/ios/AppIcon-40x40@3x.png +0 -0
  75. package/menubar/src-tauri/icons/ios/AppIcon-512@2x.png +0 -0
  76. package/menubar/src-tauri/icons/ios/AppIcon-60x60@2x.png +0 -0
  77. package/menubar/src-tauri/icons/ios/AppIcon-60x60@3x.png +0 -0
  78. package/menubar/src-tauri/icons/ios/AppIcon-76x76@1x.png +0 -0
  79. package/menubar/src-tauri/icons/ios/AppIcon-76x76@2x.png +0 -0
  80. package/menubar/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png +0 -0
  81. package/menubar/src-tauri/icons/tray-win.png +0 -0
  82. package/menubar/src-tauri/icons/tray.png +0 -0
  83. package/menubar/src-tauri/src/main.rs +486 -0
  84. package/menubar/src-tauri/tauri.conf.json +56 -0
  85. package/package.json +20 -3
  86. package/pricing/models.json +311 -0
  87. package/scripts/gen-icons.py +153 -0
  88. package/scripts/reconcile.py +162 -0
  89. package/scripts/verify-dashboard.py +101 -0
  90. package/src/adapters/claude-code.ts +246 -0
  91. package/src/adapters/codex.ts +166 -0
  92. package/src/adapters/dsh.ts +156 -0
  93. package/src/adapters/kimi-code.ts +164 -0
  94. package/src/adapters/opencode.ts +120 -0
  95. package/src/adapters/pi.ts +99 -0
  96. package/src/adapters/qoder.ts +43 -0
  97. package/src/adapters/types.ts +39 -0
  98. package/src/adapters/volc-ark.ts +102 -0
  99. package/src/adapters/workbuddy.ts +135 -0
  100. package/src/cli/index.ts +294 -0
  101. package/src/cli/serve.ts +209 -0
  102. package/src/core/aggregate.ts +821 -0
  103. package/src/core/alert.ts +33 -0
  104. package/src/core/autocompact.ts +46 -0
  105. package/src/core/budget.ts +42 -0
  106. package/src/core/collector.ts +209 -0
  107. package/src/core/compression.ts +163 -0
  108. package/src/core/config.ts +71 -0
  109. package/src/core/contract.ts +181 -0
  110. package/src/core/metrics.ts +72 -0
  111. package/src/core/price-fetch.ts +112 -0
  112. package/src/core/pricing.ts +182 -0
  113. package/src/core/registry.ts +141 -0
  114. package/src/core/retry-detector.ts +64 -0
  115. package/src/core/rtk.ts +58 -0
  116. package/src/core/savings.ts +55 -0
  117. package/src/core/schema.ts +66 -0
  118. package/src/core/unknown-models.ts +64 -0
  119. package/tests/adapters-dsh.test.ts +35 -0
  120. package/tests/adapters-opencode.test.ts +39 -0
  121. package/tests/adapters-pi.test.ts +33 -0
  122. package/tests/adapters-workbuddy.test.ts +34 -0
  123. package/tests/adapters.test.ts +45 -0
  124. package/tests/aggregate.test.ts +153 -0
  125. package/tests/compression.test.ts +71 -0
  126. package/tests/fixtures/claude-session.jsonl +9 -0
  127. package/tests/fixtures/codex-rollout.jsonl +5 -0
  128. package/tests/fixtures/kimi-wire.jsonl +6 -0
  129. package/tests/pricing-timebased.test.ts +51 -0
  130. package/tests/pricing.test.ts +73 -0
  131. package/tests/serve.test.ts +29 -0
  132. package/tsconfig.json +19 -0
  133. package/web/dashboard.html +1266 -0
  134. package/web/panel.html +674 -0
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env python3
2
+ # token-pilot 数据对账 — 独立重算原始日志,与 CLI 输出比对
3
+ # 故意不用适配器代码:这是第三方视角的独立审计。
4
+ # 注意:不按 mtime 跳文件,顺便验证 mtime 快跳的正确性。
5
+ #
6
+ # 用法:python3 scripts/reconcile.py [month|today]
7
+
8
+ import json
9
+ import os
10
+ import sys
11
+ import glob
12
+ from datetime import datetime
13
+
14
+ HOME = os.path.expanduser('~')
15
+ MODE = sys.argv[1] if len(sys.argv) > 1 else 'month'
16
+
17
+ now = datetime.now()
18
+ if MODE == 'today':
19
+ since = now.replace(hour=0, minute=0, second=0, microsecond=0).timestamp()
20
+ else:
21
+ since = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0).timestamp()
22
+
23
+
24
+ def blank():
25
+ return dict(input=0, output=0, cache_read=0, cache_creation=0, calls=0)
26
+
27
+
28
+ def audit_claude():
29
+ """~/.claude/projects/**/*.jsonl — 按 message.id 去重取最大"""
30
+ agg = blank()
31
+ by_id = {}
32
+ for f in glob.glob(os.path.join(HOME, '.claude', 'projects', '**', '*.jsonl'), recursive=True):
33
+ try:
34
+ with open(f, 'r', errors='replace') as fh:
35
+ for line in fh:
36
+ if '"usage"' not in line:
37
+ continue
38
+ try:
39
+ d = json.loads(line)
40
+ except Exception:
41
+ continue
42
+ m = d.get('message') or {}
43
+ u = m.get('usage')
44
+ model = m.get('model')
45
+ if not u or not model or model in ('<synthetic>', 'error'):
46
+ continue
47
+ ts = d.get('timestamp')
48
+ if not ts:
49
+ continue
50
+ try:
51
+ t = datetime.fromisoformat(ts.replace('Z', '+00:00')).timestamp()
52
+ except Exception:
53
+ continue
54
+ if t < since:
55
+ continue
56
+ mid = m.get('id') or f'{f}#{id(line)}'
57
+ total = (u.get('input_tokens') or 0) + (u.get('output_tokens') or 0) \
58
+ + (u.get('cache_read_input_tokens') or 0) + (u.get('cache_creation_input_tokens') or 0)
59
+ prev = by_id.get(mid)
60
+ if prev is None or total > prev[0]:
61
+ by_id[mid] = (total, u)
62
+ except Exception:
63
+ continue
64
+ for _, u in by_id.values():
65
+ agg['input'] += u.get('input_tokens') or 0
66
+ agg['output'] += u.get('output_tokens') or 0
67
+ agg['cache_read'] += u.get('cache_read_input_tokens') or 0
68
+ agg['cache_creation'] += u.get('cache_creation_input_tokens') or 0
69
+ agg['calls'] += 1
70
+ return agg
71
+
72
+
73
+ def audit_codex():
74
+ """~/.codex/sessions/**/*.jsonl — token_usage_record;input 含 cached 子集"""
75
+ agg = blank()
76
+ for f in glob.glob(os.path.join(HOME, '.codex', 'sessions', '**', '*.jsonl'), recursive=True):
77
+ try:
78
+ with open(f, 'r', errors='replace') as fh:
79
+ for line in fh:
80
+ if 'token_usage_record' not in line:
81
+ continue
82
+ try:
83
+ d = json.loads(line)
84
+ except Exception:
85
+ continue
86
+ if d.get('type') != 'token_usage_record':
87
+ continue
88
+ u = (d.get('payload') or {}).get('usage') or {}
89
+ ts = d.get('timestamp')
90
+ if not ts:
91
+ continue
92
+ try:
93
+ t = datetime.fromisoformat(ts.replace('Z', '+00:00')).timestamp()
94
+ except Exception:
95
+ continue
96
+ if t < since:
97
+ continue
98
+ cached = u.get('cached_input_tokens') or 0
99
+ agg['input'] += max((u.get('input_tokens') or 0) - cached, 0)
100
+ agg['output'] += u.get('output_tokens') or 0
101
+ agg['cache_read'] += cached
102
+ agg['cache_creation'] += u.get('cache_write_input_tokens') or 0
103
+ agg['calls'] += 1
104
+ except Exception:
105
+ continue
106
+ return agg
107
+
108
+
109
+ def audit_kimi():
110
+ """~/.kimi-code/sessions/**/wire.jsonl — 只认 usage.record"""
111
+ agg = blank()
112
+ for f in glob.glob(os.path.join(HOME, '.kimi-code', 'sessions', '**', 'wire.jsonl'), recursive=True):
113
+ try:
114
+ with open(f, 'r', errors='replace') as fh:
115
+ for line in fh:
116
+ if '"usage.record"' not in line:
117
+ continue
118
+ try:
119
+ d = json.loads(line)
120
+ except Exception:
121
+ continue
122
+ if d.get('type') != 'usage.record':
123
+ continue
124
+ u = d.get('usage') or {}
125
+ t = (d.get('time') or 0) / 1000
126
+ if t < since:
127
+ continue
128
+ agg['input'] += u.get('inputOther') or 0
129
+ agg['output'] += u.get('output') or 0
130
+ agg['cache_read'] += u.get('inputCacheRead') or 0
131
+ agg['cache_creation'] += u.get('inputCacheCreation') or 0
132
+ agg['calls'] += 1
133
+ except Exception:
134
+ continue
135
+ return agg
136
+
137
+
138
+ def fmt(n):
139
+ return f'{n:,}'
140
+
141
+
142
+ def main():
143
+ truth = {
144
+ 'claude-code': audit_claude(),
145
+ 'codex': audit_codex(),
146
+ 'kimi-code': audit_kimi(),
147
+ }
148
+ print(f'== 独立对账({MODE},since {datetime.fromtimestamp(since)})==')
149
+ grand = blank()
150
+ for agent, a in truth.items():
151
+ total = a['input'] + a['output'] + a['cache_read'] + a['cache_creation']
152
+ grand = {k: grand[k] + a[k] for k in grand}
153
+ print(f"{agent:12s} calls={fmt(a['calls']):>8} total={fmt(total):>14} "
154
+ f"in={fmt(a['input'])} out={fmt(a['output'])} cr={fmt(a['cache_read'])} cw={fmt(a['cache_creation'])}")
155
+ gt = grand['input'] + grand['output'] + grand['cache_read'] + grand['cache_creation']
156
+ print(f"{'TOTAL':12s} calls={fmt(grand['calls']):>8} total={fmt(gt):>14}")
157
+ print()
158
+ print('拿这组数字对比:token-pilot month 的「按宿主」tokens/次数(应逐项相等)')
159
+
160
+
161
+ if __name__ == '__main__':
162
+ main()
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env python3
2
+ # token-pilot 看板数据不变量验证 — 直接对 dashboard-data.json 做算法级校验
3
+ # 与 reconcile.py 互补:reconcile 验证采集正确性,本脚本验证聚合算法正确性。
4
+ #
5
+ # 用法:python3 scripts/verify-dashboard.py
6
+
7
+ import json
8
+ import math
9
+ import os
10
+ import sys
11
+ from datetime import datetime
12
+
13
+ DATA = os.path.expanduser('~/.token-pilot/dashboard-data.json')
14
+ d = json.load(open(DATA))
15
+
16
+ fails = []
17
+ def check(name, ok, detail=''):
18
+ print(('✅' if ok else '❌'), name, detail)
19
+ if not ok:
20
+ fails.append(name)
21
+
22
+ gen = datetime.fromtimestamp(d['generatedAt'] / 1000)
23
+ print(f'数据生成于 {gen}\n')
24
+
25
+ # ---- 1. 三周期包含关系:today ≤ week ≤ month ----
26
+ h = d['hero']
27
+ check('today ≤ week ≤ month(花费)',
28
+ h['today']['costCny'] <= h['week']['costCny'] + 0.01 <= h['month']['costCny'] + 0.02,
29
+ f"{h['today']['costCny']:.2f} ≤ {h['week']['costCny']:.2f} ≤ {h['month']['costCny']:.2f}")
30
+
31
+ # ---- 2. hero 内部一致性:命中率在 [0,1],calls/tokens 非负 ----
32
+ for p in ('today', 'week', 'month'):
33
+ pp = h[p]
34
+ check(f'hero.{p} 命中率∈[0,1]', 0 <= pp['cacheHitRate'] <= 1, f"{pp['cacheHitRate']:.3f}")
35
+ check(f'hero.{p} pills=4', len(pp['pills']) == 4, str([x['label'] for x in pp['pills']]))
36
+
37
+ # ---- 3. 趋势日序列:28 天、今天=hero.today、花费非负 ----
38
+ days = d['trend']['days']
39
+ check('趋势 28 天', len(days) == 28, str(len(days)))
40
+ today_cost = days[-1]['costUsd'] * d['usdToCny']
41
+ check('趋势末日 = hero.today', abs(today_cost - h['today']['costCny']) < 0.01,
42
+ f'{today_cost:.2f} vs {h["today"]["costCny"]:.2f}')
43
+ check('趋势无负值', all(x['costUsd'] >= 0 and x['tokens'] >= 0 and x['calls'] >= 0 for x in days))
44
+ # 本周花费 = 本周一的日期起日序列之和
45
+ wd = datetime.now().weekday() # 周一=0
46
+ week_sum = sum(x['costUsd'] for x in days[-(wd + 1):]) * d['usdToCny']
47
+ check('本周花费 = 日序列周一起求和', abs(week_sum - h['week']['costCny']) < 0.02,
48
+ f'{week_sum:.2f} vs {h["week"]["costCny"]:.2f}')
49
+
50
+ # ---- 4. 实时流速:分摊总量守恒(buckets60 × 20s ≈ 近60分钟 output 总量无法外部验证,验证自身一致性) ----
51
+ live = d['live']
52
+ check('buckets30 是 buckets60 的末 90 桶',
53
+ live['buckets30'] == live['buckets60'][90:], '')
54
+ check('currentTokS = 末3桶均值',
55
+ abs(live['currentTokS'] - sum(live['buckets60'][-3:]) / 3) < 0.01,
56
+ f"{live['currentTokS']:.2f}")
57
+ check('peak ≥ current', live['peakTokS'] + 0.01 >= live['currentTokS'],
58
+ f"peak {live['peakTokS']:.1f} cur {live['currentTokS']:.1f}")
59
+ check('会话数 = active+idle 内一致', live['activeCount'] >= 0 and live['idleCount'] >= 0)
60
+ for s in live['sessions']:
61
+ check(f'会话 spark 长度=10', len(s['spark']) == 10, s['label'][:20])
62
+
63
+ # ---- 5. 构成:pct ≈ 100,三周期都有 ----
64
+ for period in ('today', 'week', 'month'):
65
+ for dim in ('model', 'tool', 'proj'):
66
+ rows = d['mix'][period][dim]
67
+ if rows:
68
+ total = sum(r['pct'] for r in rows)
69
+ check(f'mix.{period}.{dim} pct≈100', abs(total - 100) < 1.5, f'{total:.1f}')
70
+
71
+ # ---- 6. 排行:pct 降序、与 mix.today.model 头部一致 ----
72
+ mr = d['modelRank']
73
+ check('modelRank 降序', all(mr[i]['pct'] >= mr[i+1]['pct'] - 0.01 for i in range(len(mr)-1)))
74
+ if mr and d['mix']['today']['model']:
75
+ check('modelRank 榜首 = mix 榜首', mr[0]['name'] == d['mix']['today']['model'][0]['name'],
76
+ f"{mr[0]['name']}")
77
+
78
+ # ---- 7. 预算:spent = 本月用量 + 固定费;pct 自洽 ----
79
+ b = d['budget']
80
+ if b:
81
+ fixed = sum(x['monthlyCny'] for x in d['settings']['cloudApis']) + sum(x['monthlyCny'] for x in d['settings']['subscriptions'])
82
+ expect_spent = h['month']['costCny'] + fixed
83
+ check('budget.spent = 本月用量 + 固定费', abs(b['spentCny'] - expect_spent) < 0.5,
84
+ f"{b['spentCny']:.1f} vs {expect_spent:.1f}(固定费 {fixed})")
85
+ check('budget.pct 自洽', abs(b['pct'] - b['spentCny'] / b['monthlyCny'] * 100) < 0.5)
86
+ check('budget.daily = monthly/当月天数', abs(b['dailyCny'] - b['monthlyCny'] / 31) < b['monthlyCny'] / 31 * 0.15)
87
+
88
+ # ---- 8. 缓存省钱条:命中率为本月口径 ----
89
+ cs = d['cacheStrip']
90
+ if cs:
91
+ check('cacheStrip 命中率 = hero.month 命中率', abs(cs['hitRate'] - h['month']['cacheHitRate']) < 0.001)
92
+ check('cacheStrip 节省 > 0', cs['savedCny'] > 0, f"¥{cs['savedCny']:.0f}")
93
+
94
+ # ---- 9. 设置:价格表非空 ----
95
+ check('settings.models 非空', len(d['settings']['models']) > 0, f"{len(d['settings']['models'])} 个模型")
96
+
97
+ print()
98
+ if fails:
99
+ print(f'❌ {len(fails)} 项失败:{fails}')
100
+ sys.exit(1)
101
+ print('全部通过 ✓')
@@ -0,0 +1,246 @@
1
+ // Claude Code adapter — 只读解析 ~/.claude/projects/**/*.jsonl
2
+ // 参考 ccusage 路线:不注入 hook,不改配置,纯只读
3
+
4
+ import { promises as fs } from 'node:fs';
5
+ import path from 'node:path';
6
+ import os from 'node:os';
7
+ import type { UsageEvent, ContentEvent } from '../core/schema.ts';
8
+ import type { Adapter } from './types.ts';
9
+
10
+ const HOME = os.homedir();
11
+ const PROJECTS_DIR = path.join(HOME, '.claude', 'projects');
12
+
13
+ interface ClaudeUsage {
14
+ input_tokens?: number;
15
+ output_tokens?: number;
16
+ cache_read_input_tokens?: number;
17
+ cache_creation_input_tokens?: number;
18
+ }
19
+
20
+ interface ClaudeLine {
21
+ timestamp?: string;
22
+ sessionId?: string;
23
+ cwd?: string;
24
+ message?: {
25
+ id?: string;
26
+ model?: string;
27
+ usage?: ClaudeUsage;
28
+ };
29
+ }
30
+
31
+ async function* walkJsonl(dir: string): AsyncGenerator<string> {
32
+ let entries: fs.Dirent[];
33
+ try {
34
+ entries = await fs.readdir(dir, { withFileTypes: true });
35
+ } catch {
36
+ return;
37
+ }
38
+ for (const e of entries) {
39
+ const full = path.join(dir, e.name);
40
+ if (e.isDirectory()) {
41
+ yield* walkJsonl(full);
42
+ } else if (e.isFile() && e.name.endsWith('.jsonl')) {
43
+ yield full;
44
+ }
45
+ }
46
+ }
47
+
48
+ function parseLine(line: string, file: string, lineNo: number): UsageEvent | null {
49
+ if (!line.includes('"usage"')) return null;
50
+ let d: ClaudeLine;
51
+ try {
52
+ d = JSON.parse(line);
53
+ } catch {
54
+ return null;
55
+ }
56
+ const usage = d.message?.usage;
57
+ const model = d.message?.model;
58
+ if (!usage || !model || model === '<synthetic>' || model === 'error') return null;
59
+
60
+ const input = usage.input_tokens ?? 0;
61
+ const output = usage.output_tokens ?? 0;
62
+ const cacheRead = usage.cache_read_input_tokens ?? 0;
63
+ const cacheCreation = usage.cache_creation_input_tokens ?? 0;
64
+
65
+ // eventId 用 message.id 做去重键;缺 id 时退化为 文件+行号(不参与去重)
66
+ const msgId = d.message?.id;
67
+ const eventId = msgId ?? `${path.basename(file, '.jsonl')}#${lineNo}`;
68
+
69
+ return {
70
+ agent: 'claude-code',
71
+ sessionId: d.sessionId ?? path.basename(file, '.jsonl'),
72
+ eventId,
73
+ timestamp: d.timestamp ? new Date(d.timestamp).getTime() : 0,
74
+ provider: providerFromModel(model),
75
+ model,
76
+ usage: {
77
+ inputTokens: input,
78
+ outputTokens: output,
79
+ cacheReadTokens: cacheRead,
80
+ cacheCreationTokens: cacheCreation,
81
+ totalTokens: input + output + cacheRead + cacheCreation,
82
+ },
83
+ workspace: d.cwd,
84
+ };
85
+ }
86
+
87
+ // 从 model 名推 provider(国产模型识别在这)
88
+ function providerFromModel(model: string): string {
89
+ const m = model.toLowerCase();
90
+ if (m.includes('claude')) return 'anthropic';
91
+ if (m.includes('deepseek')) return 'deepseek';
92
+ if (m.includes('glm')) return 'glm';
93
+ if (m.includes('kimi')) return 'kimi';
94
+ if (m.includes('qwen')) return 'qwen';
95
+ if (m.includes('doubao') || m.includes('seed')) return 'doubao';
96
+ if (m.includes('minimax')) return 'minimax';
97
+ if (m.includes('hunyuan') || m.includes('hy')) return 'hunyuan';
98
+ if (m.includes('mimo')) return 'mimo';
99
+ if (m.includes('longcat')) return 'longcat';
100
+ if (m.includes('gpt')) return 'openai';
101
+ return 'unknown';
102
+ }
103
+
104
+ // 抓会话标题:首条用户文本消息,截 40 字符
105
+ function grabTitle(line: string, out: Map<string, string>): void {
106
+ try {
107
+ const d = JSON.parse(line);
108
+ if (d?.type !== 'user' || !d?.sessionId) return;
109
+ if (out.has(d.sessionId)) return;
110
+ const c = d.message?.content;
111
+ let text = '';
112
+ if (typeof c === 'string') text = c;
113
+ else if (Array.isArray(c)) {
114
+ const t = c.find((b: { type?: string; text?: string }) => b?.type === 'text' && typeof b.text === 'string');
115
+ text = t?.text ?? '';
116
+ }
117
+ text = text.replace(/\s+/g, ' ').trim();
118
+ // 跳过系统注入块:xml 标签、[SYSTEM]/[MESSAGE FROM...] 等方括号标签
119
+ if (!text || text.startsWith('<') || text.startsWith('[')) return;
120
+ out.set(d.sessionId, text.slice(0, 40));
121
+ } catch {
122
+ // 非 JSON 行忽略
123
+ }
124
+ }
125
+
126
+ // 解析单个 jsonl 文件:文件内按 message.id 去重(取 totalTokens 最大),附会话标题
127
+ async function readFileEvents(file: string, sinceMs = 0): Promise<UsageEvent[]> {
128
+ let content: string;
129
+ try {
130
+ content = await fs.readFile(file, 'utf8');
131
+ } catch {
132
+ return [];
133
+ }
134
+ const byId = new Map<string, UsageEvent>();
135
+ const titleBySession = new Map<string, string>();
136
+ const lines = content.split('\n');
137
+ for (let i = 0; i < lines.length; i++) {
138
+ const line = lines[i];
139
+ if (!line.trim()) continue;
140
+ // 顺手抓会话标题(首条用户文本消息),成本只是一次子串判断
141
+ if (line.includes('"type":"user"') && line.includes('"content"')) {
142
+ grabTitle(line, titleBySession);
143
+ }
144
+ const ev = parseLine(line, file, i);
145
+ if (!ev || ev.timestamp < sinceMs) continue;
146
+ const prev = byId.get(ev.eventId);
147
+ if (!prev || ev.usage.totalTokens > prev.usage.totalTokens) {
148
+ byId.set(ev.eventId, ev);
149
+ }
150
+ }
151
+ const events = [...byId.values()];
152
+ for (const ev of events) {
153
+ const t = titleBySession.get(ev.sessionId);
154
+ if (t) ev.sessionTitle = t;
155
+ }
156
+ return events;
157
+ }
158
+
159
+ async function listFiles(): Promise<string[]> {
160
+ const out: string[] = [];
161
+ for await (const f of walkJsonl(PROJECTS_DIR)) out.push(f);
162
+ return out;
163
+ }
164
+
165
+ // 内容流:tool_use(assistant)与 tool_result(user)只取尺寸与目标路径,不落内容
166
+ async function readFileContentEvents(file: string, sinceMs = 0): Promise<ContentEvent[]> {
167
+ let content: string;
168
+ try { content = await fs.readFile(file, 'utf8'); } catch { return []; }
169
+ const events: ContentEvent[] = [];
170
+ const sessionId = path.basename(file, '.jsonl');
171
+ for (const line of content.split('\n')) {
172
+ if (!line.includes('tool_use') && !line.includes('tool_result')) continue;
173
+ let d: {
174
+ type?: string; timestamp?: string;
175
+ message?: { content?: unknown };
176
+ };
177
+ try { d = JSON.parse(line); } catch { continue; }
178
+ const ts = d.timestamp ? new Date(d.timestamp).getTime() : 0;
179
+ if (ts < sinceMs) continue;
180
+ const items = d.message?.content;
181
+ if (!Array.isArray(items)) continue;
182
+ for (const c of items) {
183
+ if (!c || typeof c !== 'object') continue;
184
+ const cc = c as { type?: string; name?: string; input?: unknown; content?: unknown };
185
+ if (d.type === 'assistant' && cc.type === 'tool_use') {
186
+ const input = cc.input as { file_path?: string; path?: string; command?: string } | undefined;
187
+ events.push({
188
+ agent: 'claude-code',
189
+ sessionId,
190
+ timestamp: ts,
191
+ kind: 'tool_use',
192
+ tool: cc.name,
193
+ targetPath: input?.file_path ?? input?.path,
194
+ sizeBytes: cc.input ? JSON.stringify(cc.input).length : 0,
195
+ });
196
+ } else if (d.type === 'user' && cc.type === 'tool_result') {
197
+ events.push({
198
+ agent: 'claude-code',
199
+ sessionId,
200
+ timestamp: ts,
201
+ kind: 'tool_result',
202
+ sizeBytes: cc.content ? JSON.stringify(cc.content).length : 0,
203
+ });
204
+ }
205
+ }
206
+ }
207
+ return events;
208
+ }
209
+
210
+ export const claudeCodeAdapter: Adapter = {
211
+ meta: {
212
+ id: 'claude-code',
213
+ displayName: 'Claude Code',
214
+ detectPaths: ['~/.claude'],
215
+ detectCommands: ['claude'],
216
+ },
217
+
218
+ async detect() {
219
+ try {
220
+ await fs.access(PROJECTS_DIR);
221
+ return true;
222
+ } catch {
223
+ return false;
224
+ }
225
+ },
226
+
227
+ listFiles,
228
+ readFileEvents,
229
+ readFileContentEvents,
230
+
231
+ async readEvents(sinceMs = 0): Promise<UsageEvent[]> {
232
+ // 同一 message.id 只可能出现在一个会话文件里,按文件合并即可
233
+ const events: UsageEvent[] = [];
234
+ for (const file of await listFiles()) {
235
+ // 文件 mtime 早于 since 就整个跳过(快计算)
236
+ try {
237
+ const st = await fs.stat(file);
238
+ if (st.mtimeMs < sinceMs) continue;
239
+ } catch {
240
+ continue;
241
+ }
242
+ events.push(...(await readFileEvents(file, sinceMs)));
243
+ }
244
+ return events;
245
+ },
246
+ };
@@ -0,0 +1,166 @@
1
+ // Codex adapter — 只读解析 ~/.codex/sessions/**/*.jsonl
2
+ // 格式:rollout jsonl,token 在 type=token_usage_record 事件的 payload.usage
3
+
4
+ import { promises as fs } from 'node:fs';
5
+ import path from 'node:path';
6
+ import os from 'node:os';
7
+ import type { UsageEvent } from '../core/schema.ts';
8
+ import type { Adapter } from './types.ts';
9
+
10
+ const HOME = os.homedir();
11
+ const SESSIONS_DIR = path.join(HOME, '.codex', 'sessions');
12
+
13
+ interface CodexUsage {
14
+ input_tokens?: number;
15
+ cached_input_tokens?: number;
16
+ cache_write_input_tokens?: number;
17
+ output_tokens?: number;
18
+ total_tokens?: number;
19
+ }
20
+
21
+ interface CodexLine {
22
+ timestamp?: string;
23
+ type?: string;
24
+ payload?: {
25
+ session_id?: string;
26
+ usage?: CodexUsage;
27
+ // model 在别的 event 里,rollout 里用 model_context_window / 或另查
28
+ };
29
+ }
30
+
31
+ async function* walkJsonl(dir: string): AsyncGenerator<string> {
32
+ let entries: fs.Dirent[];
33
+ try {
34
+ entries = await fs.readdir(dir, { withFileTypes: true });
35
+ } catch {
36
+ return;
37
+ }
38
+ for (const e of entries) {
39
+ const full = path.join(dir, e.name);
40
+ if (e.isDirectory()) yield* walkJsonl(full);
41
+ else if (e.isFile() && e.name.endsWith('.jsonl')) yield full;
42
+ }
43
+ }
44
+
45
+ function parseLine(line: string, file: string, lineNo: number): UsageEvent | null {
46
+ if (!line.includes('"token_usage_record"')) return null;
47
+ let d: CodexLine;
48
+ try {
49
+ d = JSON.parse(line);
50
+ } catch {
51
+ return null;
52
+ }
53
+ if (d.type !== 'token_usage_record') return null;
54
+ const u = d.payload?.usage;
55
+ if (!u) return null;
56
+
57
+ // OpenAI 语义实测:input_tokens 包含 cached_input_tokens(cached 是子集),
58
+ // total_tokens = input_tokens + output_tokens。
59
+ // 新输入 = input − cached,缓存部分走 cacheRead 单价,不重复计费。
60
+ const inputRaw = u.input_tokens ?? 0;
61
+ const cacheRead = u.cached_input_tokens ?? 0;
62
+ const cacheCreation = u.cache_write_input_tokens ?? 0;
63
+ const output = u.output_tokens ?? 0;
64
+ const input = Math.max(inputRaw - cacheRead, 0);
65
+
66
+ return {
67
+ agent: 'codex',
68
+ sessionId: d.payload?.session_id ?? path.basename(file, '.jsonl'),
69
+ eventId: `${path.basename(file, '.jsonl')}#${lineNo}`,
70
+ timestamp: d.timestamp ? new Date(d.timestamp).getTime() : 0,
71
+ provider: 'openai',
72
+ model: 'codex', // rollout 里 model 名不稳定,先标 codex
73
+ usage: {
74
+ inputTokens: input,
75
+ outputTokens: output,
76
+ cacheReadTokens: cacheRead,
77
+ cacheCreationTokens: cacheCreation,
78
+ totalTokens: input + output + cacheRead + cacheCreation,
79
+ },
80
+ };
81
+ }
82
+
83
+ async function readFileEvents(file: string, sinceMs = 0): Promise<UsageEvent[]> {
84
+ let content: string;
85
+ try {
86
+ content = await fs.readFile(file, 'utf8');
87
+ } catch {
88
+ return [];
89
+ }
90
+ const events: UsageEvent[] = [];
91
+ const lines = content.split('\n');
92
+ for (let i = 0; i < lines.length; i++) {
93
+ const line = lines[i];
94
+ if (!line.trim()) continue;
95
+ const ev = parseLine(line, file, i);
96
+ if (ev && ev.timestamp >= sinceMs) events.push(ev);
97
+ }
98
+ return events;
99
+ }
100
+
101
+ async function listFiles(): Promise<string[]> {
102
+ const out: string[] = [];
103
+ for await (const f of walkJsonl(SESSIONS_DIR)) out.push(f);
104
+ return out;
105
+ }
106
+
107
+ export const codexAdapter: Adapter = {
108
+ meta: {
109
+ id: 'codex',
110
+ displayName: 'Codex',
111
+ detectPaths: ['~/.codex'],
112
+ detectCommands: ['codex'],
113
+ },
114
+ async detect() {
115
+ try {
116
+ await fs.access(SESSIONS_DIR);
117
+ return true;
118
+ } catch {
119
+ return false;
120
+ }
121
+ },
122
+ listFiles,
123
+ readFileEvents,
124
+ readFileContentEvents: readCodexContentEvents,
125
+ async readEvents(sinceMs = 0): Promise<UsageEvent[]> {
126
+ const events: UsageEvent[] = [];
127
+ for (const file of await listFiles()) {
128
+ try {
129
+ const st = await fs.stat(file);
130
+ if (st.mtimeMs < sinceMs) continue;
131
+ } catch {
132
+ continue;
133
+ }
134
+ events.push(...(await readFileEvents(file, sinceMs)));
135
+ }
136
+ return events;
137
+ },
138
+ };
139
+
140
+ // 内容流:response_item 的 function_call / function_call_output,只取尺寸
141
+ export async function readCodexContentEvents(file: string, sinceMs = 0): Promise<import('../core/schema.ts').ContentEvent[]> {
142
+ let content: string;
143
+ try { content = await fs.readFile(file, 'utf8'); } catch { return []; }
144
+ const events: import('../core/schema.ts').ContentEvent[] = [];
145
+ const sessionId = path.basename(file, '.jsonl');
146
+ for (const line of content.split('\n')) {
147
+ if (!line.includes('function_call')) continue;
148
+ let d: { timestamp?: string; payload?: { type?: string; name?: string; arguments?: string; output?: string } };
149
+ try { d = JSON.parse(line); } catch { continue; }
150
+ const ts = d.timestamp ? new Date(d.timestamp).getTime() : 0;
151
+ if (ts < sinceMs) continue;
152
+ const p = d.payload;
153
+ if (p?.type === 'function_call') {
154
+ events.push({
155
+ agent: 'codex', sessionId, timestamp: ts, kind: 'tool_use',
156
+ tool: p.name, sizeBytes: (p.arguments ?? '').length,
157
+ });
158
+ } else if (p?.type === 'function_call_output') {
159
+ events.push({
160
+ agent: 'codex', sessionId, timestamp: ts, kind: 'tool_result',
161
+ sizeBytes: (p.output ?? '').length,
162
+ });
163
+ }
164
+ }
165
+ return events;
166
+ }