@anthonyhan/token-pilot 0.2.3 → 0.2.4

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 (161) hide show
  1. package/bin/token-pilot.js +10 -7
  2. package/dist/adapters/claude-code.js +251 -0
  3. package/dist/adapters/codex.js +163 -0
  4. package/dist/adapters/dsh.js +163 -0
  5. package/dist/adapters/kimi-code.js +165 -0
  6. package/dist/adapters/opencode.js +126 -0
  7. package/dist/adapters/pi.js +119 -0
  8. package/dist/adapters/qoder.js +51 -0
  9. package/dist/adapters/types.js +7 -0
  10. package/dist/adapters/volc-ark.js +92 -0
  11. package/dist/adapters/workbuddy.js +144 -0
  12. package/dist/cli/index.js +278 -0
  13. package/dist/cli/serve.js +200 -0
  14. package/dist/core/aggregate.js +821 -0
  15. package/dist/core/alert.js +32 -0
  16. package/dist/core/autocompact.js +40 -0
  17. package/dist/core/budget.js +23 -0
  18. package/dist/core/collector.js +213 -0
  19. package/dist/core/compression.js +129 -0
  20. package/dist/core/config.js +41 -0
  21. package/dist/core/contract.js +4 -0
  22. package/dist/core/metrics.js +53 -0
  23. package/dist/core/price-fetch.js +128 -0
  24. package/dist/core/pricing.js +156 -0
  25. package/dist/core/registry.js +144 -0
  26. package/dist/core/retry-detector.js +41 -0
  27. package/dist/core/rtk.js +58 -0
  28. package/dist/core/savings.js +43 -0
  29. package/dist/core/schema.js +3 -0
  30. package/dist/core/unknown-models.js +50 -0
  31. package/package.json +16 -6
  32. package/.github/FUNDING.yml +0 -3
  33. package/.github/workflows/build-desktop.yml +0 -68
  34. package/.idea/go.imports.xml +0 -10
  35. package/.idea/modules.xml +0 -8
  36. package/.idea/sonarlint/vulnerabilitystore/default/index.pb +0 -0
  37. package/.idea/thriftCompilerAssist.xml +0 -6
  38. package/.idea/token-pilot.iml +0 -9
  39. package/.idea/vcs.xml +0 -6
  40. package/README-en.md +0 -127
  41. package/docs/assets/dashboard.png +0 -0
  42. package/docs/assets/icon.png +0 -0
  43. package/docs/assets/menubar-panel.png +0 -0
  44. package/docs/assets/sponsor-alipay.png +0 -0
  45. package/docs/assets/sponsor-wechat.png +0 -0
  46. package/llms.txt +0 -40
  47. package/menubar/package-lock.json +0 -248
  48. package/menubar/package.json +0 -16
  49. package/menubar/src/dashboard.html +0 -1266
  50. package/menubar/src/index.html +0 -674
  51. package/menubar/src-tauri/Cargo.lock +0 -4963
  52. package/menubar/src-tauri/Cargo.toml +0 -15
  53. package/menubar/src-tauri/build.rs +0 -3
  54. package/menubar/src-tauri/gen/schemas/acl-manifests.json +0 -1
  55. package/menubar/src-tauri/gen/schemas/capabilities.json +0 -1
  56. package/menubar/src-tauri/gen/schemas/desktop-schema.json +0 -2526
  57. package/menubar/src-tauri/gen/schemas/macOS-schema.json +0 -2526
  58. package/menubar/src-tauri/icons/128x128.png +0 -0
  59. package/menubar/src-tauri/icons/128x128@2x.png +0 -0
  60. package/menubar/src-tauri/icons/32x32.png +0 -0
  61. package/menubar/src-tauri/icons/64x64.png +0 -0
  62. package/menubar/src-tauri/icons/Square107x107Logo.png +0 -0
  63. package/menubar/src-tauri/icons/Square142x142Logo.png +0 -0
  64. package/menubar/src-tauri/icons/Square150x150Logo.png +0 -0
  65. package/menubar/src-tauri/icons/Square284x284Logo.png +0 -0
  66. package/menubar/src-tauri/icons/Square30x30Logo.png +0 -0
  67. package/menubar/src-tauri/icons/Square310x310Logo.png +0 -0
  68. package/menubar/src-tauri/icons/Square44x44Logo.png +0 -0
  69. package/menubar/src-tauri/icons/Square71x71Logo.png +0 -0
  70. package/menubar/src-tauri/icons/Square89x89Logo.png +0 -0
  71. package/menubar/src-tauri/icons/StoreLogo.png +0 -0
  72. package/menubar/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml +0 -5
  73. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png +0 -0
  74. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png +0 -0
  75. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png +0 -0
  76. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png +0 -0
  77. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png +0 -0
  78. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png +0 -0
  79. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png +0 -0
  80. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png +0 -0
  81. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png +0 -0
  82. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png +0 -0
  83. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png +0 -0
  84. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png +0 -0
  85. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png +0 -0
  86. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
  87. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png +0 -0
  88. package/menubar/src-tauri/icons/android/values/ic_launcher_background.xml +0 -4
  89. package/menubar/src-tauri/icons/icon.icns +0 -0
  90. package/menubar/src-tauri/icons/icon.ico +0 -0
  91. package/menubar/src-tauri/icons/icon.png +0 -0
  92. package/menubar/src-tauri/icons/ios/AppIcon-20x20@1x.png +0 -0
  93. package/menubar/src-tauri/icons/ios/AppIcon-20x20@2x-1.png +0 -0
  94. package/menubar/src-tauri/icons/ios/AppIcon-20x20@2x.png +0 -0
  95. package/menubar/src-tauri/icons/ios/AppIcon-20x20@3x.png +0 -0
  96. package/menubar/src-tauri/icons/ios/AppIcon-29x29@1x.png +0 -0
  97. package/menubar/src-tauri/icons/ios/AppIcon-29x29@2x-1.png +0 -0
  98. package/menubar/src-tauri/icons/ios/AppIcon-29x29@2x.png +0 -0
  99. package/menubar/src-tauri/icons/ios/AppIcon-29x29@3x.png +0 -0
  100. package/menubar/src-tauri/icons/ios/AppIcon-40x40@1x.png +0 -0
  101. package/menubar/src-tauri/icons/ios/AppIcon-40x40@2x-1.png +0 -0
  102. package/menubar/src-tauri/icons/ios/AppIcon-40x40@2x.png +0 -0
  103. package/menubar/src-tauri/icons/ios/AppIcon-40x40@3x.png +0 -0
  104. package/menubar/src-tauri/icons/ios/AppIcon-512@2x.png +0 -0
  105. package/menubar/src-tauri/icons/ios/AppIcon-60x60@2x.png +0 -0
  106. package/menubar/src-tauri/icons/ios/AppIcon-60x60@3x.png +0 -0
  107. package/menubar/src-tauri/icons/ios/AppIcon-76x76@1x.png +0 -0
  108. package/menubar/src-tauri/icons/ios/AppIcon-76x76@2x.png +0 -0
  109. package/menubar/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png +0 -0
  110. package/menubar/src-tauri/icons/tray-win.png +0 -0
  111. package/menubar/src-tauri/icons/tray.png +0 -0
  112. package/menubar/src-tauri/src/main.rs +0 -486
  113. package/menubar/src-tauri/tauri.conf.json +0 -56
  114. package/scripts/gen-icons.py +0 -153
  115. package/scripts/reconcile.py +0 -162
  116. package/scripts/verify-dashboard.py +0 -101
  117. package/src/adapters/claude-code.ts +0 -246
  118. package/src/adapters/codex.ts +0 -166
  119. package/src/adapters/dsh.ts +0 -156
  120. package/src/adapters/kimi-code.ts +0 -164
  121. package/src/adapters/opencode.ts +0 -120
  122. package/src/adapters/pi.ts +0 -99
  123. package/src/adapters/qoder.ts +0 -43
  124. package/src/adapters/types.ts +0 -39
  125. package/src/adapters/volc-ark.ts +0 -102
  126. package/src/adapters/workbuddy.ts +0 -135
  127. package/src/cli/index.ts +0 -294
  128. package/src/cli/serve.ts +0 -209
  129. package/src/core/aggregate.ts +0 -821
  130. package/src/core/alert.ts +0 -33
  131. package/src/core/autocompact.ts +0 -46
  132. package/src/core/budget.ts +0 -42
  133. package/src/core/collector.ts +0 -209
  134. package/src/core/compression.ts +0 -163
  135. package/src/core/config.ts +0 -71
  136. package/src/core/contract.ts +0 -181
  137. package/src/core/metrics.ts +0 -72
  138. package/src/core/price-fetch.ts +0 -112
  139. package/src/core/pricing.ts +0 -182
  140. package/src/core/registry.ts +0 -141
  141. package/src/core/retry-detector.ts +0 -64
  142. package/src/core/rtk.ts +0 -58
  143. package/src/core/savings.ts +0 -55
  144. package/src/core/schema.ts +0 -66
  145. package/src/core/unknown-models.ts +0 -64
  146. package/tests/adapters-dsh.test.ts +0 -35
  147. package/tests/adapters-opencode.test.ts +0 -39
  148. package/tests/adapters-pi.test.ts +0 -33
  149. package/tests/adapters-workbuddy.test.ts +0 -34
  150. package/tests/adapters.test.ts +0 -45
  151. package/tests/aggregate.test.ts +0 -153
  152. package/tests/compression.test.ts +0 -71
  153. package/tests/fixtures/claude-session.jsonl +0 -9
  154. package/tests/fixtures/codex-rollout.jsonl +0 -5
  155. package/tests/fixtures/kimi-wire.jsonl +0 -6
  156. package/tests/pricing-timebased.test.ts +0 -51
  157. package/tests/pricing.test.ts +0 -73
  158. package/tests/serve.test.ts +0 -29
  159. package/tsconfig.json +0 -19
  160. package/web/dashboard.html +0 -1266
  161. package/web/panel.html +0 -674
@@ -1,56 +0,0 @@
1
- {
2
- "$schema": "https://schema.tauri.app/config/2",
3
- "productName": "token-pilot",
4
- "version": "0.2.3",
5
- "identifier": "com.anthonyhann.tokenpilot",
6
- "build": {
7
- "beforeDevCommand": "",
8
- "beforeBuildCommand": "",
9
- "frontendDist": "../src"
10
- },
11
- "app": {
12
- "withGlobalTauri": true,
13
- "windows": [
14
- {
15
- "label": "main",
16
- "title": "Token Pilot",
17
- "width": 480,
18
- "height": 760,
19
- "resizable": true,
20
- "minWidth": 400,
21
- "minHeight": 520,
22
- "maxWidth": 720,
23
- "alwaysOnTop": true,
24
- "decorations": false,
25
- "transparent": true,
26
- "visible": false,
27
- "skipTaskbar": true
28
- },
29
- {
30
- "label": "dashboard",
31
- "title": "Token Pilot · 本地看板",
32
- "url": "dashboard.html",
33
- "width": 1500,
34
- "height": 950,
35
- "minWidth": 1040,
36
- "minHeight": 640,
37
- "resizable": true,
38
- "visible": false
39
- }
40
- ],
41
- "security": {
42
- "csp": null
43
- }
44
- },
45
- "bundle": {
46
- "active": true,
47
- "targets": "all",
48
- "icon": [
49
- "icons/32x32.png",
50
- "icons/128x128.png",
51
- "icons/128x128@2x.png",
52
- "icons/icon.icns",
53
- "icons/icon.ico"
54
- ]
55
- }
56
- }
@@ -1,153 +0,0 @@
1
- #!/usr/bin/env python3
2
- # token-pilot 图标生成 — 借 CatPaw 雷达底稿风格,换品牌闪电+橙红渐变
3
- # 产出:menubar/src-tauri/icons/icon.png(1024 app 图标)+ tray.png(44 单色模板图标)
4
-
5
- from PIL import Image, ImageDraw, ImageFilter
6
- import math
7
- import os
8
-
9
- OUT = os.path.join(os.path.dirname(__file__), '..', 'menubar', 'src-tauri', 'icons')
10
- os.makedirs(OUT, exist_ok=True)
11
-
12
- # 品牌色(与设计体系 oklch 对应)
13
- C_ORANGE = (255, 122, 69) # accent
14
- C_PINK = (255, 77, 109) # accent-2
15
- C_VIOLET = (178, 102, 255) # accent-3
16
- C_BG = (22, 24, 43) # 深夜蓝底
17
- C_BG2 = (31, 34, 56)
18
-
19
- BOLT = [(13, 2), (4, 14), (10, 14), (9, 22), (20, 10), (14, 10)] # 24px viewBox 闪电路径转多边形
20
-
21
- def bolt_poly(cx, cy, w, h):
22
- """以 (cx,cy) 为中心、宽 w 高 h 的闪电多边形"""
23
- return [(cx - w/2 + px/24*w, cy - h/2 + py/24*h) for px, py in BOLT]
24
-
25
- def lerp(a, b, t):
26
- return tuple(int(a[i] + (b[i]-a[i])*t) for i in range(3))
27
-
28
- def vgrad(draw_fn, box, c_top, c_bottom):
29
- """竖直渐变填充:逐行画"""
30
- x0, y0, x1, y1 = box
31
- im = Image.new('RGBA', (x1-x0, y1-y0), (0,0,0,0))
32
- d = ImageDraw.Draw(im)
33
- for y in range(y1-y0):
34
- d.line([(0,y),(x1-x0,y)], fill=lerp(c_top, c_bottom, y/(y1-y0)) + (255,))
35
- mask = Image.new('L', (x1-x0, y1-y0), 0)
36
- md = ImageDraw.Draw(mask)
37
- draw_fn(md)
38
- return im, mask, (x0, y0)
39
-
40
- # ============ App 图标 1024 ============
41
- S = 1024
42
- SS = 4 # 超采样抗锯齿
43
- W = S * SS
44
- img = Image.new('RGBA', (W, W), (0, 0, 0, 0))
45
- d = ImageDraw.Draw(img)
46
-
47
- # 圆角方底(macOS 风格 22% 半径)+ 微渐变
48
- body = Image.new('RGBA', (W, W), (0,0,0,0))
49
- bd = ImageDraw.Draw(body)
50
- for y in range(W):
51
- bd.line([(0,y),(W,y)], fill=lerp(C_BG2, C_BG, y/W) + (255,))
52
- mask = Image.new('L', (W, W), 0)
53
- ImageDraw.Draw(mask).rounded_rectangle([0,0,W-1,W-1], radius=int(W*0.225), fill=255)
54
- img.paste(body, (0,0), mask)
55
- d = ImageDraw.Draw(img)
56
-
57
- cx = cy = W/2
58
-
59
- # 雷达同心圆环 + 十字线(品牌橙,低透明)
60
- ring = Image.new('RGBA', (W, W), (0,0,0,0))
61
- rd = ImageDraw.Draw(ring)
62
- for r, alpha in [(0.36, 200), (0.26, 120), (0.16, 80)]:
63
- rr = W * r
64
- rd.ellipse([cx-rr, cy-rr, cx+rr, cy+rr], outline=C_ORANGE + (alpha,), width=int(W*0.004))
65
- rd.line([(cx - W*0.36, cy), (cx + W*0.36, cy)], fill=C_ORANGE + (60,), width=int(W*0.002))
66
- rd.line([(cx, cy - W*0.36), (cx, cy + W*0.36)], fill=C_ORANGE + (60,), width=int(W*0.002))
67
- img = Image.alpha_composite(img, ring)
68
-
69
- # 雷达扫掠扇形(橙→粉渐变,向尾缘渐隐)
70
- sweep = Image.new('RGBA', (W, W), (0,0,0,0))
71
- sd = ImageDraw.Draw(sweep)
72
- R = W * 0.36
73
- A0, A1 = -75, -20 # 扫掠角(12 点方向附近)
74
- steps = 60
75
- for i in range(steps):
76
- a = A0 + (A1-A0) * i/steps
77
- t = i/steps
78
- col = lerp(C_ORANGE, C_PINK, t)
79
- alpha = int(10 + 120*t) # 尾缘亮
80
- sd.pieslice([cx-R, cy-R, cx+R, cy+R], start=a, end=a + (A1-A0)/steps + 0.5, fill=col + (alpha,))
81
- sweep = sweep.filter(ImageFilter.GaussianBlur(W*0.004))
82
- img = Image.alpha_composite(img, sweep)
83
-
84
- # 雷达点(小圆点装饰)
85
- d = ImageDraw.Draw(img)
86
- for ang, rr, s, col in [(145, 0.24, 0.012, C_ORANGE), (30, 0.30, 0.010, C_PINK), (255, 0.20, 0.011, C_VIOLET)]:
87
- px = cx + math.cos(math.radians(ang)) * W * rr
88
- py = cy + math.sin(math.radians(ang)) * W * rr
89
- r = W * s
90
- d.ellipse([px-r, py-r, px+r, py+r], fill=col + (230,))
91
-
92
- # 中心闪电:外发光 + 渐变主体
93
- bolt_w, bolt_h = W*0.30, W*0.42
94
- bx0, by0 = int(cx-bolt_w*0.8), int(cy-bolt_h*0.7)
95
- bx1, by1 = int(cx+bolt_w*0.8), int(cy+bolt_h*0.7)
96
- bcx, bcy = (bx0+bx1)/2, (by0+by1)/2
97
- poly = bolt_poly(bcx, bcy, bolt_w, bolt_h)
98
-
99
- glow = Image.new('RGBA', (W, W), (0,0,0,0))
100
- ImageDraw.Draw(glow).polygon(poly, fill=C_ORANGE + (160,))
101
- glow = glow.filter(ImageFilter.GaussianBlur(W*0.02))
102
- img = Image.alpha_composite(img, glow)
103
-
104
- grad_im, grad_mask, pos = vgrad(lambda md: md.polygon([(x-bx0, y-by0) for x, y in poly], fill=255),
105
- (bx0, by0, bx1, by1), (255, 214, 170), C_PINK)
106
- img.paste(grad_im, pos, grad_mask)
107
-
108
- img = img.resize((S, S), Image.LANCZOS)
109
- img.save(os.path.join(OUT, 'icon.png'))
110
- print('icon.png', img.size)
111
-
112
- # ============ 状态栏模板图标(单色黑 + 透明,macOS template) ============
113
- TS = 88 # 22pt @4x,足够清晰
114
- TW = TS * SS
115
- timg = Image.new('RGBA', (TW, TW), (0, 0, 0, 0))
116
- td = ImageDraw.Draw(timg)
117
- tpoly = bolt_poly(TW/2, TW/2, TW*0.56, TW*0.78)
118
- td.polygon(tpoly, fill=(0, 0, 0, 255))
119
- timg = timg.resize((TS, TS), Image.LANCZOS)
120
- # 裁掉透明边距到内容 bbox + 留 6% 边距
121
- bbox = timg.getbbox()
122
- if bbox:
123
- timg = timg.crop(bbox)
124
- side = int(max(timg.width, timg.height) * 1.12)
125
- canvas = Image.new('RGBA', (side, side), (0,0,0,0))
126
- canvas.paste(timg, ((side-timg.width)//2, (side-timg.height)//2), timg)
127
- timg = canvas.resize((44, 44), Image.LANCZOS)
128
- timg.save(os.path.join(OUT, 'tray.png'))
129
- print('tray.png', timg.size)
130
-
131
- # ============ Windows 托盘图标(彩色——黑闪电在 Windows 深色任务栏上会隐形) ============
132
- WS = 64
133
- WW = WS * SS
134
- wimg = Image.new('RGBA', (WW, WW), (0, 0, 0, 0))
135
- # 外发光描边(深橙描边保证浅色任务栏也看得清)
136
- wpoly = bolt_poly(WW/2, WW/2, WW*0.56, WW*0.78)
137
- gloww = Image.new('RGBA', (WW, WW), (0,0,0,0))
138
- ImageDraw.Draw(gloww).polygon(wpoly, fill=(200, 80, 30, 255))
139
- gloww = gloww.filter(ImageFilter.GaussianBlur(WW*0.02))
140
- wimg = Image.alpha_composite(wimg, gloww)
141
- wg, wm, wpos = vgrad(lambda md: md.polygon([(x-0, y-0) for x, y in wpoly], fill=255),
142
- (0, 0, WW, WW), (255, 160, 110), C_PINK)
143
- wimg.paste(wg, wpos, wm)
144
- wimg = wimg.resize((WS, WS), Image.LANCZOS)
145
- bbox = wimg.getbbox()
146
- if bbox:
147
- wimg = wimg.crop(bbox)
148
- side = int(max(wimg.width, wimg.height) * 1.08)
149
- canvas = Image.new('RGBA', (side, side), (0,0,0,0))
150
- canvas.paste(wimg, ((side-wimg.width)//2, (side-wimg.height)//2), wimg)
151
- wimg = canvas.resize((32, 32), Image.LANCZOS)
152
- wimg.save(os.path.join(OUT, 'tray-win.png'))
153
- print('tray-win.png', wimg.size)
@@ -1,162 +0,0 @@
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()
@@ -1,101 +0,0 @@
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('全部通过 ✓')