@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,153 @@
1
+ // 聚合引擎测试:合成事件 → DashboardData 不变量
2
+
3
+ import { test } from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import { buildDashboardData } from '../src/core/aggregate.ts';
6
+ import type { UsageEvent } from '../src/core/schema.ts';
7
+ import type { PricingTable } from '../src/core/pricing.ts';
8
+ import type { TokenPilotConfig } from '../src/core/config.ts';
9
+
10
+ const pricing: PricingTable = {
11
+ models: {
12
+ 'test-model': { provider: 'test', input: 1.0, output: 2.0, cacheRead: 0.1, cacheCreation: 1.25 },
13
+ },
14
+ fallback: { provider: 'x', input: 1.0, output: 5.0 },
15
+ };
16
+
17
+ function ev(offsetMs: number, over: Partial<UsageEvent> & { out?: number; inp?: number; cr?: number; cw?: number } = {}): UsageEvent {
18
+ const inp = over.inp ?? 1000;
19
+ const out = over.out ?? 500;
20
+ const cr = over.cr ?? 9000;
21
+ const cw = over.cw ?? 0;
22
+ return {
23
+ agent: over.agent ?? 'claude-code',
24
+ sessionId: over.sessionId ?? 's1',
25
+ eventId: over.eventId ?? `e-${Math.random().toString(36).slice(2)}`,
26
+ timestamp: Date.now() - offsetMs,
27
+ provider: 'test',
28
+ model: over.model ?? 'test-model',
29
+ usage: {
30
+ inputTokens: inp, outputTokens: out, cacheReadTokens: cr, cacheCreationTokens: cw,
31
+ totalTokens: inp + out + cr + cw,
32
+ },
33
+ workspace: over.workspace ?? '/proj-a',
34
+ };
35
+ }
36
+
37
+ const H = 3600_000;
38
+ const DAY = 86400_000;
39
+
40
+ test('周期包含关系 + 趋势末日=今日', async () => {
41
+ const events = [ev(1 * H), ev(3 * DAY), ev(10 * DAY), ev(40 * DAY)]; // 40 天前不进本月
42
+ const d = await buildDashboardData(events, {}, pricing);
43
+ assert.ok(d.hero.today.costCny <= d.hero.week.costCny + 1e-9);
44
+ assert.ok(d.hero.week.costCny <= d.hero.month.costCny + 1e-9);
45
+ assert.equal(d.trend.days.length, 28);
46
+ const lastDay = d.trend.days[d.trend.days.length - 1];
47
+ assert.ok(Math.abs(lastDay.costUsd * d.usdToCny - d.hero.today.costCny) < 0.01);
48
+ // 40 天前的事件不进任何周期
49
+ assert.ok(d.hero.month.costCny > 0);
50
+ assert.ok(d.hero.month.calls <= 3);
51
+ });
52
+
53
+ test('构成 pct≈100(三周期三维度)', async () => {
54
+ const events = [
55
+ ev(1 * H, { model: 'test-model', agent: 'claude-code', workspace: '/a' }),
56
+ ev(2 * H, { model: 'fallback-model', agent: 'codex', workspace: '/b' }),
57
+ ev(3 * DAY, { model: 'test-model', agent: 'kimi-code', workspace: '/c' }),
58
+ ];
59
+ const d = await buildDashboardData(events, {}, pricing);
60
+ for (const period of ['today', 'week', 'month'] as const) {
61
+ for (const dim of ['model', 'tool', 'proj'] as const) {
62
+ const rows = d.mix[period][dim];
63
+ if (rows.length) {
64
+ const sum = rows.reduce((s, r) => s + r.pct, 0);
65
+ assert.ok(Math.abs(sum - 100) < 1.5, `${period}.${dim} pct=${sum}`);
66
+ }
67
+ }
68
+ }
69
+ });
70
+
71
+ test('live 分摊总量守恒:buckets60×20s ≈ 近 60 分钟 output 总量', async () => {
72
+ // 同会话两个事件相隔 60s,第二个 output=6000 应分摊到这 60s 窗口
73
+ const events = [
74
+ ev(90_000, { sessionId: 'live-1', out: 0 }),
75
+ ev(30_000, { sessionId: 'live-1', out: 6000, inp: 0, cr: 0 }),
76
+ ];
77
+ const d = await buildDashboardData(events, {}, pricing);
78
+ const sumTok = d.live.buckets60.reduce((s, r) => s + r * 20, 0);
79
+ assert.ok(Math.abs(sumTok - 6000) < 1, `分摊后总量 ${sumTok} ≠ 6000`);
80
+ // 分摊:曲线应覆盖多个桶而非单点
81
+ const nonZero = d.live.buckets60.filter((r) => r > 0).length;
82
+ assert.ok(nonZero >= 2, `只有 ${nonZero} 个非零桶,说明没分摊`);
83
+ // 速率峰值不应超过 6000/60=100(若全压在一个桶会是 300)
84
+ assert.ok(d.live.peakTokS <= 101, `peak ${d.live.peakTokS} 超上限`);
85
+ });
86
+
87
+ test('预算:spent = 本月用量×汇率 + 固定费;pct 自洽', async () => {
88
+ const events = [ev(1 * H, { out: 1_000_000, inp: 1_000_000, cr: 0 })]; // $1×1M in + $2×1M out = $3
89
+ const cfg: TokenPilotConfig = {
90
+ monthlyBudgetCny: 1500,
91
+ usdToCny: 7.0,
92
+ subscriptions: [{ name: 'X', monthlyCny: 100 }],
93
+ cloudApis: [{ name: 'Y', monthlyCny: 50 }],
94
+ };
95
+ const d = await buildDashboardData(events, cfg, pricing);
96
+ assert.ok(d.budget);
97
+ const expect = 3 * 7.0 + 150;
98
+ assert.ok(Math.abs(d.budget!.spentCny - expect) < 0.01, `spent ${d.budget!.spentCny} ≠ ${expect}`);
99
+ assert.ok(Math.abs(d.budget!.pct - (expect / 1500) * 100) < 0.01);
100
+ assert.ok(d.trayTitle.includes('¥'));
101
+ });
102
+
103
+ test('无预算时 budget=null 且托盘只显示金额', async () => {
104
+ const d = await buildDashboardData([ev(1000)], {}, pricing);
105
+ assert.equal(d.budget, null);
106
+ assert.ok(!d.trayTitle.includes('%'));
107
+ });
108
+
109
+ test('缓存省钱 = Σ cacheRead × (input − cacheRead 价) × 汇率', async () => {
110
+ // 本月一次调用:cacheRead 10M,test-model 省 (1.0−0.1)×10 = $9 → ×7.2 = ¥64.8
111
+ const d = await buildDashboardData([ev(1 * H, { cr: 10_000_000 })], { usdToCny: 7.2 }, pricing);
112
+ assert.ok(d.cacheStrip);
113
+ assert.ok(Math.abs(d.cacheStrip!.savedCny - 64.8) < 0.5, `saved ${d.cacheStrip!.savedCny}`);
114
+ });
115
+
116
+ test('会话 spark 恒为 10 桶;活跃判定 2 分钟', async () => {
117
+ const events = [
118
+ ev(30_000, { sessionId: 'hot', out: 100 }),
119
+ ev(5 * 60_000, { sessionId: 'warm', out: 100 }),
120
+ ];
121
+ const d = await buildDashboardData(events, {}, pricing);
122
+ for (const s of d.live.sessions) {
123
+ assert.equal(s.spark.length, 10);
124
+ }
125
+ const hot = d.live.sessions.find((s) => s.key.includes('hot'));
126
+ assert.ok(hot?.active);
127
+ });
128
+
129
+ test('防重复计费:宿主日志已覆盖 doubao 的当天,云端日汇总被丢弃', async () => {
130
+ const today = new Date(); today.setHours(12, 0, 0, 0);
131
+ const ts = today.getTime();
132
+ const hostEv = ev(1000, { agent: 'kimi-code', model: 'doubao-seed-2-1-pro', out: 100 });
133
+ hostEv.timestamp = ts;
134
+ const cloudEv = ev(1000, { agent: 'volc-ark', model: 'doubao-cloud', out: 5000, inp: 100000 });
135
+ cloudEv.timestamp = ts;
136
+ const d = await buildDashboardData([hostEv, cloudEv], {}, pricing);
137
+ // 只有宿主那条计入:云端那条被闸门丢弃
138
+ const tool = d.mix.today.tool.map((r) => r.name);
139
+ assert.ok(!tool.includes('Doubao · 火山'), '云端事件应与宿主去重');
140
+ });
141
+
142
+ test('2B:上下文超 100K 的活跃会话标 needsCompact 并进建议卡', async () => {
143
+ const big = ev(30_000, { sessionId: 'big-ctx' });
144
+ big.usage.inputTokens = 150_000; big.usage.cacheReadTokens = 0; big.usage.totalTokens = 150_050;
145
+ big.usage.cacheCreationTokens = 0;
146
+ const small = ev(20_000, { sessionId: 'small-ctx' });
147
+ const d = await buildDashboardData([big, small], {}, pricing);
148
+ const bigS = d.live.sessions.find((s) => s.key.includes('big-ctx'));
149
+ const smallS = d.live.sessions.find((s) => s.key.includes('small-ctx'));
150
+ assert.ok(bigS?.needsCompact, '大会话应标记');
151
+ assert.ok(!smallS?.needsCompact, '小会话不标');
152
+ assert.ok(d.savings.some((c) => c.title === '该 compact 了'), '建议卡应出现');
153
+ });
@@ -0,0 +1,71 @@
1
+ // 压缩潜力引擎测试(纯规则)
2
+
3
+ import { test } from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import { computeCompression } from '../src/core/compression.ts';
6
+ import type { UsageEvent, ContentEvent } from '../src/core/schema.ts';
7
+ import type { PricingTable } from '../src/core/pricing.ts';
8
+
9
+ const pricing: PricingTable = {
10
+ models: { 'test-model': { provider: 'test', input: 1.0, output: 2.0, cacheRead: 0.1 } },
11
+ fallback: { provider: 'x', input: 1.0, output: 5.0 },
12
+ };
13
+
14
+ const T0 = Date.now() - 3600_000;
15
+
16
+ function usage(ts: number, session = 's1'): UsageEvent {
17
+ return {
18
+ agent: 'claude-code', sessionId: session, eventId: `u${ts}-${Math.random()}`, timestamp: ts,
19
+ provider: 'test', model: 'test-model',
20
+ usage: { inputTokens: 100, outputTokens: 50, cacheReadTokens: 0, cacheCreationTokens: 0, totalTokens: 150 },
21
+ };
22
+ }
23
+ function toolResult(ts: number, sizeBytes: number, session = 's1'): ContentEvent {
24
+ return { agent: 'claude-code', sessionId: session, timestamp: ts, kind: 'tool_result', sizeBytes };
25
+ }
26
+ function toolUse(ts: number, path: string, session = 's1'): ContentEvent {
27
+ return { agent: 'claude-code', sessionId: session, timestamp: ts, kind: 'tool_use', tool: 'Read', targetPath: path, sizeBytes: 100 };
28
+ }
29
+
30
+ test('W1 陈旧输出:K 轮后仍在重发的部分计入', () => {
31
+ // 1 个 tool_result(4KB≈1000 tokens)+ 后面 10 轮调用 → after=10,K=5 → 5 轮陈旧
32
+ const events = [usage(T0), ...Array.from({ length: 10 }, (_, i) => usage(T0 + (i + 1) * 60_000))];
33
+ const content = [toolResult(T0 + 1000, 4000)];
34
+ const r = computeCompression(events, content, pricing);
35
+ assert.ok(r.patterns.stale > 0);
36
+ // 1000 tok × 0.85 × 5 轮 × $1/1M ≈ $0.00425
37
+ assert.ok(Math.abs(r.patterns.stale - 0.00425) < 0.001, `stale=${r.patterns.stale}`);
38
+ assert.equal(r.itemCount, 1);
39
+ });
40
+
41
+ test('W2 重复读取:同路径前 N−1 次读取冗余', () => {
42
+ const events = [usage(T0), usage(T0 + 10 * 60_000), usage(T0 + 20 * 60_000)];
43
+ const content = [toolUse(T0 + 1000, '/a.ts'), toolUse(T0 + 5 * 60_000, '/a.ts'), toolUse(T0 + 15 * 60_000, '/a.ts')];
44
+ const r = computeCompression(events, content, pricing);
45
+ assert.ok(r.patterns.reread > 0, '重复读取应计入');
46
+ assert.ok(r.sessions[0].topPatterns.includes('reread'));
47
+ });
48
+
49
+ test('W3 超长输出:超出 2KB 的部分计入', () => {
50
+ const events = [usage(T0), usage(T0 + 60_000), usage(T0 + 120_000), usage(T0 + 180_000), usage(T0 + 240_000), usage(T0 + 300_000)];
51
+ const content = [toolResult(T0 + 500, 50 * 1024)]; // 50KB
52
+ const r = computeCompression(events, content, pricing);
53
+ assert.ok(r.patterns.long > 0);
54
+ });
55
+
56
+ test('无内容流时不报错返回零', () => {
57
+ const r = computeCompression([usage(T0)], [], pricing);
58
+ assert.equal(r.potentialUsd, 0);
59
+ assert.equal(r.itemCount, 0);
60
+ });
61
+
62
+ test('不叠加:同一项命中多个模式取最大', () => {
63
+ // 超长 + 陈旧同一项
64
+ const events = [usage(T0), ...Array.from({ length: 8 }, (_, i) => usage(T0 + (i + 1) * 60_000))];
65
+ const content = [toolResult(T0 + 500, 30 * 1024)];
66
+ const r = computeCompression(events, content, pricing);
67
+ assert.equal(r.itemCount, 1, '同一项只计一次');
68
+ // stale+long 只入账一个
69
+ const both = [r.patterns.stale > 0, r.patterns.long > 0].filter(Boolean).length;
70
+ assert.equal(both, 1);
71
+ });
@@ -0,0 +1,9 @@
1
+ // claude-code fixture:同一 message.id 的流式快照(前 2 行全零,末行真实值)
2
+ // + 一条 <synthetic>(应过滤)+ 一条无 usage(应过滤)+ 用户消息(抓标题)
3
+ // 期望产出:1 个事件(output 4263),sessionTitle='修复登录页样式'
4
+ {"type":"user","sessionId":"sess-fixture-1","timestamp":"2026-10-20T08:00:00.000Z","cwd":"/Users/test/myproj","message":{"content":"修复登录页样式"}}
5
+ {"type":"assistant","sessionId":"sess-fixture-1","timestamp":"2026-10-20T08:00:05.000Z","cwd":"/Users/test/myproj","message":{"id":"msg-dup-1","model":"claude-sonnet-4-6","usage":{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}
6
+ {"type":"assistant","sessionId":"sess-fixture-1","timestamp":"2026-10-20T08:00:08.000Z","cwd":"/Users/test/myproj","message":{"id":"msg-dup-1","model":"claude-sonnet-4-6","usage":{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}
7
+ {"type":"assistant","sessionId":"sess-fixture-1","timestamp":"2026-10-20T08:00:12.000Z","cwd":"/Users/test/myproj","message":{"id":"msg-dup-1","model":"claude-sonnet-4-6","usage":{"input_tokens":239,"output_tokens":4263,"cache_read_input_tokens":93760,"cache_creation_input_tokens":0}}}
8
+ {"type":"assistant","sessionId":"sess-fixture-1","timestamp":"2026-10-20T08:00:20.000Z","message":{"id":"msg-syn","model":"<synthetic>","usage":{"input_tokens":1,"output_tokens":1}}}
9
+ {"type":"summary","sessionId":"sess-fixture-1","timestamp":"2026-10-20T08:00:30.000Z"}
@@ -0,0 +1,5 @@
1
+ // codex fixture:token_usage_record;input_tokens 含 cached_input_tokens 子集
2
+ // 期望产出:2 个事件;第一个 input=56369-5760=50609
3
+ {"timestamp":"2026-10-09T18:28:10.000Z","type":"token_usage_record","payload":{"session_id":"codex-fixture-1","usage":{"input_tokens":56369,"cached_input_tokens":5760,"cache_write_input_tokens":0,"output_tokens":956,"total_tokens":57325}}}
4
+ {"timestamp":"2026-10-09T18:28:20.000Z","type":"response_item","payload":{"session_id":"codex-fixture-1"}}
5
+ {"timestamp":"2026-10-09T18:29:00.000Z","type":"token_usage_record","payload":{"session_id":"codex-fixture-1","usage":{"input_tokens":67119,"cached_input_tokens":56192,"cache_write_input_tokens":0,"output_tokens":429,"total_tokens":67548}}}
@@ -0,0 +1,6 @@
1
+ // kimi-code fixture:usage.record 才算数;context.append_loop_event / agent.message.appended 带 usage 字样但不是计费记录
2
+ // 期望产出:2 个事件;input 只算 inputOther(不并入缓存)
3
+ {"type":"usage.record","model":"gpt-5.4","usage":{"inputOther":42369,"output":172,"inputCacheRead":0,"inputCacheCreation":0},"time":1791859777047}
4
+ {"type":"context.append_loop_event","time":1791859777077,"usage":null}
5
+ {"type":"agent.message.appended","time":1791859778000,"usage":{"inputOther":999999}}
6
+ {"type":"usage.record","model":"gpt-5.4","usage":{"inputOther":203,"output":320,"inputCacheRead":42240,"inputCacheCreation":0},"time":1791859784180}
@@ -0,0 +1,51 @@
1
+ // 分时定价 + 币种归一 + 别名 测试
2
+
3
+ import { test } from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import { isDeepSeekPeak, costOf, priceFor, loadPricingNormalized, loadPricingWithOverrides } from '../src/core/pricing.ts';
6
+
7
+ const U = (i: number, o: number, cr = 0, cw = 0) => ({ inputTokens: i, outputTokens: o, cacheReadTokens: cr, cacheCreationTokens: cw, totalTokens: i + o + cr + cw });
8
+
9
+ test('DeepSeek 高峰:周四 10:00 北京时间 = peak', () => {
10
+ // 2026-10-22 是周四;10:00 CST = 02:00 UTC
11
+ const t = Date.UTC(2026, 9, 22, 2, 0, 0);
12
+ assert.equal(isDeepSeekPeak(t), true);
13
+ });
14
+
15
+ test('DeepSeek 空闲:周四 12:30(午间)/ 周六 / 国庆 = offpeak', () => {
16
+ assert.equal(isDeepSeekPeak(Date.UTC(2026, 9, 22, 4, 30)), false); // 周四 12:30 CST
17
+ assert.equal(isDeepSeekPeak(Date.UTC(2026, 9, 24, 10, 0)), false); // 周六
18
+ assert.equal(isDeepSeekPeak(Date.UTC(2026, 9, 1, 2, 0)), false); // 国庆 10-01
19
+ });
20
+
21
+ test('分时计价:同量不同价', () => {
22
+ const t = loadPricingNormalized(7.2);
23
+ const peak = costOf('deepseek-flash', U(1_000_000, 100_000), t, Date.UTC(2026, 9, 22, 2, 0));
24
+ const off = costOf('deepseek-flash', U(1_000_000, 100_000), t, Date.UTC(2026, 9, 22, 4, 30));
25
+ // peak: 2/8 元; offpeak: 1/4 元 → peak = 2× off
26
+ assert.ok(Math.abs(peak.totalUsd / off.totalUsd - 2) < 0.01, `比值 ${peak.totalUsd / off.totalUsd}`);
27
+ });
28
+
29
+ test('别名:deepseek-v4.1-flash 命中 deepseek-flash 的分时价', () => {
30
+ const t = loadPricingNormalized(7.2);
31
+ const p = priceFor('deepseek-v4.1-flash', t);
32
+ assert.ok(p.peak, '别名应解析到分时表');
33
+ assert.equal(p.provider, 'deepseek');
34
+ });
35
+
36
+ test('CNY 归一:glm-5.3 按汇率折算成 USD', () => {
37
+ const t = loadPricingNormalized(7.2);
38
+ const p = priceFor('glm-5.3', t);
39
+ assert.ok(Math.abs(p.input - 8.0 / 7.2) < 0.001, `glm-5.3 input $${p.input}`);
40
+ });
41
+
42
+ test('人工覆写优先于官方目录价', () => {
43
+ const t = loadPricingWithOverrides({ 'glm-5.3': { input: 7.2, output: 36, cacheRead: 0.72 } }, 7.2);
44
+ const p = priceFor('glm-5.3', t);
45
+ assert.ok(Math.abs(p.input - 1.0) < 0.001);
46
+ });
47
+
48
+ test('本地模型(.gguf/路径)零费用', () => {
49
+ const c = costOf('/Users/x/.workbuddy/local-models/files/local_model.gguf', U(1_000_000, 100_000));
50
+ assert.equal(c.totalUsd, 0);
51
+ });
@@ -0,0 +1,73 @@
1
+ // 定价层测试:匹配策略 + 成本核算不重复计费 + 覆写换算
2
+
3
+ import { test } from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import { priceFor, costOf, cacheSavingsUsd, loadPricing, loadPricingWithOverrides } from '../src/core/pricing.ts';
6
+
7
+ const usage = (i: number, o: number, cr: number, cw: number) => ({
8
+ inputTokens: i, outputTokens: o, cacheReadTokens: cr, cacheCreationTokens: cw,
9
+ totalTokens: i + o + cr + cw,
10
+ });
11
+
12
+ test('精确匹配', () => {
13
+ const p = priceFor('claude-sonnet-4-6');
14
+ assert.equal(p.input, 3.0);
15
+ assert.equal(p.output, 15.0);
16
+ assert.equal(p.cacheRead, 0.3);
17
+ });
18
+
19
+ test('大小写归一:MiniMax-M3 命中 minimax-m3', () => {
20
+ const p = priceFor('MiniMax-M3');
21
+ assert.equal(p.provider, 'minimax');
22
+ });
23
+
24
+ test('前缀匹配:deepseek-v4.1-flash-20260601 → deepseek-flash(分时,offpeak 平铺)', () => {
25
+ const p = priceFor('deepseek-v4.1-flash-20260601');
26
+ assert.equal(p.provider, 'deepseek');
27
+ assert.ok(p.offpeak, '应带分时表');
28
+ assert.equal(p.offpeak!.input, 1.0); // CNY 目录价(未归一)
29
+ });
30
+
31
+ test('横杠别名:deepseek-v4-1-flash 不掉进 fallback', () => {
32
+ const p = priceFor('deepseek-v4-1-flash');
33
+ assert.equal(p.provider, 'deepseek');
34
+ });
35
+
36
+ test('未知模型走 fallback', () => {
37
+ const p = priceFor('some-unknown-model');
38
+ assert.equal(p.input, 1.0);
39
+ assert.equal(p.output, 5.0);
40
+ });
41
+
42
+ test('costOf 分项独立计价:缓存不按全价重复计', () => {
43
+ // sonnet: in 3 / out 15 / cacheRead 0.3 / cacheCreation 3.75
44
+ const c = costOf('claude-sonnet-4-6', usage(1_000_000, 100_000, 10_000_000, 1_000_000));
45
+ assert.ok(Math.abs(c.inputUsd - 3.0) < 1e-9);
46
+ assert.ok(Math.abs(c.outputUsd - 1.5) < 1e-9);
47
+ assert.ok(Math.abs(c.cacheReadUsd - 3.0) < 1e-9); // 10M × 0.3 = $3(若按全价 input 算会是 $30)
48
+ assert.ok(Math.abs(c.cacheCreationUsd - 3.75) < 1e-9);
49
+ assert.ok(Math.abs(c.totalUsd - 11.25) < 1e-9);
50
+ });
51
+
52
+ test('缺 cacheRead 价的模型按 input×0.1 折算', () => {
53
+ const t = loadPricing();
54
+ const noCache = Object.entries(t.models).find(([, v]) => v.cacheRead === undefined);
55
+ if (noCache) {
56
+ const c = costOf(noCache[0], usage(0, 0, 1_000_000, 0));
57
+ assert.ok(Math.abs(c.cacheReadUsd - noCache[1].input * 0.1) < 1e-9);
58
+ }
59
+ });
60
+
61
+ test('cacheSavingsUsd = cacheRead × (input − cacheRead 价)', () => {
62
+ // sonnet: (3.0 − 0.3) × 10M = $27
63
+ const s = cacheSavingsUsd('claude-sonnet-4-6', 10_000_000);
64
+ assert.ok(Math.abs(s - 27.0) < 1e-9);
65
+ });
66
+
67
+ test('用户覆写(¥/M)按汇率折算合并', () => {
68
+ const t = loadPricingWithOverrides({ 'my-model': { input: 7.2, output: 36, cacheRead: 0.72 } }, 7.2);
69
+ const p = priceFor('my-model', t);
70
+ assert.ok(Math.abs(p.input - 1.0) < 1e-9);
71
+ assert.ok(Math.abs(p.output - 5.0) < 1e-9);
72
+ assert.ok(Math.abs((p.cacheRead ?? 0) - 0.1) < 1e-9);
73
+ });
@@ -0,0 +1,29 @@
1
+ // serve 层纯函数测试:数据注入标记 + 资源读取(回归:bake 曾把 HTML 当文件名写)
2
+
3
+ import { test } from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import { injectData, readWebAsset } from '../src/cli/serve.ts';
6
+
7
+ test('injectData:恰好替换注入标记一次,且内容可 JSON.parse', () => {
8
+ const html = '<html><script>window.__TP_DATA__=null;</script></html>';
9
+ const out = injectData(html, { generatedAt: 123 } as never);
10
+ assert.ok(!out.includes('__TP_DATA__=null'));
11
+ const m = out.match(/window\.__TP_DATA__=(\{.*?\});/);
12
+ assert.ok(m, '注入标记未被替换');
13
+ assert.equal(JSON.parse(m![1]).generatedAt, 123);
14
+ });
15
+
16
+ test('injectData:HTML 中的 </script> 会被转义,不破坏文档结构', () => {
17
+ const html = '<script>window.__TP_DATA__=null;</script>';
18
+ const payload = { generatedAt: 1, note: '</script><script>alert(1)</script>' } as never;
19
+ const out = injectData(html, payload);
20
+ assert.ok(!out.includes('</script><script>alert'), 'XSS 注入必须被 \\u003c 转义');
21
+ });
22
+
23
+ test('readWebAsset:dashboard.html / panel.html 存在且非空', () => {
24
+ for (const name of ['dashboard.html', 'panel.html']) {
25
+ const html = readWebAsset(name);
26
+ assert.ok(html && html.length > 10_000, `${name} 缺失或为空`);
27
+ assert.ok(html.includes('window.__TP_DATA__=null;'), `${name} 缺注入标记`);
28
+ }
29
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "outDir": "./dist",
7
+ "rootDir": "./src",
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "declaration": true,
12
+ "resolveJsonModule": true,
13
+ "allowImportingTsExtensions": true,
14
+ "noEmit": true
15
+ },
16
+ "include": [
17
+ "src/**/*"
18
+ ]
19
+ }