@anthonyhan/token-pilot 0.2.3 → 0.3.1

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 (162) hide show
  1. package/README.md +38 -13
  2. package/bin/token-pilot.js +10 -7
  3. package/dist/adapters/claude-code.js +251 -0
  4. package/dist/adapters/codex.js +163 -0
  5. package/dist/adapters/dsh.js +163 -0
  6. package/dist/adapters/kimi-code.js +165 -0
  7. package/dist/adapters/opencode.js +126 -0
  8. package/dist/adapters/pi.js +119 -0
  9. package/dist/adapters/qoder.js +51 -0
  10. package/dist/adapters/types.js +7 -0
  11. package/dist/adapters/volc-ark.js +92 -0
  12. package/dist/adapters/workbuddy.js +144 -0
  13. package/dist/cli/index.js +286 -0
  14. package/dist/cli/serve.js +211 -0
  15. package/dist/core/aggregate.js +813 -0
  16. package/dist/core/alert.js +32 -0
  17. package/dist/core/autocompact.js +40 -0
  18. package/dist/core/breaker.js +49 -0
  19. package/dist/core/budget.js +23 -0
  20. package/dist/core/collector.js +213 -0
  21. package/dist/core/compression.js +129 -0
  22. package/dist/core/config.js +44 -0
  23. package/dist/core/contract.js +4 -0
  24. package/dist/core/metrics.js +53 -0
  25. package/dist/core/price-fetch.js +128 -0
  26. package/dist/core/pricing.js +156 -0
  27. package/dist/core/registry.js +144 -0
  28. package/dist/core/retry-detector.js +41 -0
  29. package/dist/core/rtk.js +58 -0
  30. package/dist/core/savings.js +43 -0
  31. package/dist/core/schema.js +3 -0
  32. package/dist/core/unknown-models.js +50 -0
  33. package/package.json +18 -5
  34. package/web/dashboard.html +98 -4
  35. package/.github/FUNDING.yml +0 -3
  36. package/.github/workflows/build-desktop.yml +0 -68
  37. package/.idea/go.imports.xml +0 -10
  38. package/.idea/modules.xml +0 -8
  39. package/.idea/sonarlint/vulnerabilitystore/default/index.pb +0 -0
  40. package/.idea/thriftCompilerAssist.xml +0 -6
  41. package/.idea/token-pilot.iml +0 -9
  42. package/.idea/vcs.xml +0 -6
  43. package/README-en.md +0 -127
  44. package/docs/assets/dashboard.png +0 -0
  45. package/docs/assets/icon.png +0 -0
  46. package/docs/assets/menubar-panel.png +0 -0
  47. package/docs/assets/sponsor-alipay.png +0 -0
  48. package/docs/assets/sponsor-wechat.png +0 -0
  49. package/llms.txt +0 -40
  50. package/menubar/package-lock.json +0 -248
  51. package/menubar/package.json +0 -16
  52. package/menubar/src/dashboard.html +0 -1266
  53. package/menubar/src/index.html +0 -674
  54. package/menubar/src-tauri/Cargo.lock +0 -4963
  55. package/menubar/src-tauri/Cargo.toml +0 -15
  56. package/menubar/src-tauri/build.rs +0 -3
  57. package/menubar/src-tauri/gen/schemas/acl-manifests.json +0 -1
  58. package/menubar/src-tauri/gen/schemas/capabilities.json +0 -1
  59. package/menubar/src-tauri/gen/schemas/desktop-schema.json +0 -2526
  60. package/menubar/src-tauri/gen/schemas/macOS-schema.json +0 -2526
  61. package/menubar/src-tauri/icons/128x128.png +0 -0
  62. package/menubar/src-tauri/icons/128x128@2x.png +0 -0
  63. package/menubar/src-tauri/icons/32x32.png +0 -0
  64. package/menubar/src-tauri/icons/64x64.png +0 -0
  65. package/menubar/src-tauri/icons/Square107x107Logo.png +0 -0
  66. package/menubar/src-tauri/icons/Square142x142Logo.png +0 -0
  67. package/menubar/src-tauri/icons/Square150x150Logo.png +0 -0
  68. package/menubar/src-tauri/icons/Square284x284Logo.png +0 -0
  69. package/menubar/src-tauri/icons/Square30x30Logo.png +0 -0
  70. package/menubar/src-tauri/icons/Square310x310Logo.png +0 -0
  71. package/menubar/src-tauri/icons/Square44x44Logo.png +0 -0
  72. package/menubar/src-tauri/icons/Square71x71Logo.png +0 -0
  73. package/menubar/src-tauri/icons/Square89x89Logo.png +0 -0
  74. package/menubar/src-tauri/icons/StoreLogo.png +0 -0
  75. package/menubar/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml +0 -5
  76. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png +0 -0
  77. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png +0 -0
  78. package/menubar/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png +0 -0
  79. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png +0 -0
  80. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png +0 -0
  81. package/menubar/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png +0 -0
  82. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png +0 -0
  83. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png +0 -0
  84. package/menubar/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png +0 -0
  85. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png +0 -0
  86. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png +0 -0
  87. package/menubar/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png +0 -0
  88. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png +0 -0
  89. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
  90. package/menubar/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png +0 -0
  91. package/menubar/src-tauri/icons/android/values/ic_launcher_background.xml +0 -4
  92. package/menubar/src-tauri/icons/icon.icns +0 -0
  93. package/menubar/src-tauri/icons/icon.ico +0 -0
  94. package/menubar/src-tauri/icons/icon.png +0 -0
  95. package/menubar/src-tauri/icons/ios/AppIcon-20x20@1x.png +0 -0
  96. package/menubar/src-tauri/icons/ios/AppIcon-20x20@2x-1.png +0 -0
  97. package/menubar/src-tauri/icons/ios/AppIcon-20x20@2x.png +0 -0
  98. package/menubar/src-tauri/icons/ios/AppIcon-20x20@3x.png +0 -0
  99. package/menubar/src-tauri/icons/ios/AppIcon-29x29@1x.png +0 -0
  100. package/menubar/src-tauri/icons/ios/AppIcon-29x29@2x-1.png +0 -0
  101. package/menubar/src-tauri/icons/ios/AppIcon-29x29@2x.png +0 -0
  102. package/menubar/src-tauri/icons/ios/AppIcon-29x29@3x.png +0 -0
  103. package/menubar/src-tauri/icons/ios/AppIcon-40x40@1x.png +0 -0
  104. package/menubar/src-tauri/icons/ios/AppIcon-40x40@2x-1.png +0 -0
  105. package/menubar/src-tauri/icons/ios/AppIcon-40x40@2x.png +0 -0
  106. package/menubar/src-tauri/icons/ios/AppIcon-40x40@3x.png +0 -0
  107. package/menubar/src-tauri/icons/ios/AppIcon-512@2x.png +0 -0
  108. package/menubar/src-tauri/icons/ios/AppIcon-60x60@2x.png +0 -0
  109. package/menubar/src-tauri/icons/ios/AppIcon-60x60@3x.png +0 -0
  110. package/menubar/src-tauri/icons/ios/AppIcon-76x76@1x.png +0 -0
  111. package/menubar/src-tauri/icons/ios/AppIcon-76x76@2x.png +0 -0
  112. package/menubar/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png +0 -0
  113. package/menubar/src-tauri/icons/tray-win.png +0 -0
  114. package/menubar/src-tauri/icons/tray.png +0 -0
  115. package/menubar/src-tauri/src/main.rs +0 -486
  116. package/menubar/src-tauri/tauri.conf.json +0 -56
  117. package/scripts/gen-icons.py +0 -153
  118. package/scripts/reconcile.py +0 -162
  119. package/scripts/verify-dashboard.py +0 -101
  120. package/src/adapters/claude-code.ts +0 -246
  121. package/src/adapters/codex.ts +0 -166
  122. package/src/adapters/dsh.ts +0 -156
  123. package/src/adapters/kimi-code.ts +0 -164
  124. package/src/adapters/opencode.ts +0 -120
  125. package/src/adapters/pi.ts +0 -99
  126. package/src/adapters/qoder.ts +0 -43
  127. package/src/adapters/types.ts +0 -39
  128. package/src/adapters/volc-ark.ts +0 -102
  129. package/src/adapters/workbuddy.ts +0 -135
  130. package/src/cli/index.ts +0 -294
  131. package/src/cli/serve.ts +0 -209
  132. package/src/core/aggregate.ts +0 -821
  133. package/src/core/alert.ts +0 -33
  134. package/src/core/autocompact.ts +0 -46
  135. package/src/core/budget.ts +0 -42
  136. package/src/core/collector.ts +0 -209
  137. package/src/core/compression.ts +0 -163
  138. package/src/core/config.ts +0 -71
  139. package/src/core/contract.ts +0 -181
  140. package/src/core/metrics.ts +0 -72
  141. package/src/core/price-fetch.ts +0 -112
  142. package/src/core/pricing.ts +0 -182
  143. package/src/core/registry.ts +0 -141
  144. package/src/core/retry-detector.ts +0 -64
  145. package/src/core/rtk.ts +0 -58
  146. package/src/core/savings.ts +0 -55
  147. package/src/core/schema.ts +0 -66
  148. package/src/core/unknown-models.ts +0 -64
  149. package/tests/adapters-dsh.test.ts +0 -35
  150. package/tests/adapters-opencode.test.ts +0 -39
  151. package/tests/adapters-pi.test.ts +0 -33
  152. package/tests/adapters-workbuddy.test.ts +0 -34
  153. package/tests/adapters.test.ts +0 -45
  154. package/tests/aggregate.test.ts +0 -153
  155. package/tests/compression.test.ts +0 -71
  156. package/tests/fixtures/claude-session.jsonl +0 -9
  157. package/tests/fixtures/codex-rollout.jsonl +0 -5
  158. package/tests/fixtures/kimi-wire.jsonl +0 -6
  159. package/tests/pricing-timebased.test.ts +0 -51
  160. package/tests/pricing.test.ts +0 -73
  161. package/tests/serve.test.ts +0 -29
  162. package/tsconfig.json +0 -19
@@ -0,0 +1,813 @@
1
+ // 聚合引擎 — 单遍扫描 UsageEvent[],产出 DashboardData 契约全量
2
+ // 原则:快计算(一次排序 + 一次主循环)、金额内部 USD、展示 CNY 由 fx 折算
3
+ import { costOf, cacheSavingsUsd, priceFor } from './pricing.js';
4
+ import { fxRate, monthlyBudgetCny } from './config.js';
5
+ import { detectRetryLoops } from './retry-detector.js';
6
+ import { savingsAdvice } from './savings.js';
7
+ import { computeCompression } from './compression.js';
8
+ import { buildAdapterTiers, HOST_TIERS } from './registry.js';
9
+ const AGENT_NAMES = {
10
+ 'claude-code': 'Claude Code',
11
+ 'kimi-code': 'Kimi Code',
12
+ 'codex': 'Codex',
13
+ 'opencode': 'OpenCode',
14
+ 'qoder': 'Qoder',
15
+ 'pi': 'pi',
16
+ 'dsh': 'DeepSeek Harness',
17
+ 'workbuddy': 'WorkBuddy',
18
+ 'workbuddy-ai': 'WorkBuddy AI',
19
+ 'volc-ark': 'Doubao · 火山',
20
+ };
21
+ const PROVIDER_NAMES = {
22
+ anthropic: 'Anthropic', deepseek: 'DeepSeek', glm: '智谱', kimi: 'Moonshot',
23
+ openai: 'OpenAI', qwen: '阿里', doubao: '字节', minimax: 'MiniMax',
24
+ hunyuan: '腾讯', mimo: '小米', longcat: '美团', unknown: '未知',
25
+ };
26
+ const WD = '日一二三四五六';
27
+ // ---------- 时间边界 ----------
28
+ function startOfToday(now) {
29
+ const d = new Date(now);
30
+ d.setHours(0, 0, 0, 0);
31
+ return d.getTime();
32
+ }
33
+ function startOfWeek(now) {
34
+ const d = new Date(now);
35
+ d.setHours(0, 0, 0, 0);
36
+ const dow = d.getDay(); // 0=周日
37
+ d.setDate(d.getDate() - ((dow + 6) % 7)); // 周一
38
+ return d.getTime();
39
+ }
40
+ function startOfMonth(now) {
41
+ const d = new Date(now);
42
+ d.setDate(1);
43
+ d.setHours(0, 0, 0, 0);
44
+ return d.getTime();
45
+ }
46
+ function daysInMonth(now) {
47
+ return new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
48
+ }
49
+ // ---------- 格式化 ----------
50
+ export function fmtCny(n) {
51
+ if (n >= 100)
52
+ return '¥' + Math.round(n).toLocaleString('zh-CN');
53
+ const s = n.toFixed(2);
54
+ return '¥' + (s.endsWith('0') ? s.slice(0, -1) : s);
55
+ }
56
+ export function fmtTok(n) {
57
+ if (n >= 1e8)
58
+ return trim1(n / 1e8) + '亿';
59
+ if (n >= 1e4)
60
+ return trim1(n / 1e4) + '万';
61
+ return String(Math.round(n));
62
+ }
63
+ function trim1(n) {
64
+ const s = n.toFixed(n >= 100 ? 0 : 1);
65
+ return s.endsWith('.0') ? s.slice(0, -2) : s;
66
+ }
67
+ function agoLabel(ts, now) {
68
+ const s = Math.max(0, (now - ts) / 1000);
69
+ if (s < 90)
70
+ return '刚刚';
71
+ const m = s / 60;
72
+ if (m < 60)
73
+ return `${Math.round(m)} 分钟前`;
74
+ const h = m / 60;
75
+ if (h < 24)
76
+ return `${Math.round(h)} 小时前`;
77
+ const d = new Date(ts);
78
+ return `${d.getMonth() + 1}月${d.getDate()}日`;
79
+ }
80
+ function hhmm(ts) {
81
+ const d = new Date(ts);
82
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
83
+ }
84
+ function newAgg() {
85
+ return { costUsd: 0, tokens: 0, output: 0, calls: 0, cacheRead: 0, cacheCreation: 0, input: 0 };
86
+ }
87
+ function hitRateOf(a) {
88
+ const denom = a.cacheRead + a.cacheCreation + a.input;
89
+ return denom > 0 ? a.cacheRead / denom : 0;
90
+ }
91
+ export async function buildDashboardData(rawEvents, cfg, pricing, contentEvents = []) {
92
+ const now = new Date();
93
+ const nowMs = now.getTime();
94
+ const fx = fxRate(cfg);
95
+ // 防重复计费闸门:云端 API(volc-ark,账号级日汇总)与宿主日志可能报同一批流量。
96
+ // 规则:某天已有宿主日志记录到 doubao 系模型(provider=doubao 或模型名含 doubao/seed),
97
+ // 则当天的云端日汇总事件丢弃(宿主日志粒度更细,云端只补「非宿主通道」的部分)。
98
+ const hostDoubaoDays = new Set();
99
+ for (const e of rawEvents) {
100
+ if (e.agent === 'volc-ark')
101
+ continue;
102
+ const isDoubao = e.provider === 'doubao' || /doubao|seed/i.test(e.model);
103
+ if (isDoubao && e.timestamp > 0) {
104
+ hostDoubaoDays.add(new Date(e.timestamp).toISOString().slice(0, 10));
105
+ }
106
+ }
107
+ const filtered = rawEvents.filter((e) => {
108
+ if (e.agent !== 'volc-ark')
109
+ return true;
110
+ const day = new Date(e.timestamp).toISOString().slice(0, 10);
111
+ return !hostDoubaoDays.has(day);
112
+ });
113
+ // 排序 + 预算成本(单遍)
114
+ const events = filtered
115
+ .filter((e) => e.timestamp > 0)
116
+ .map((e) => {
117
+ const c = costOf(e.model, e.usage, pricing, e.timestamp);
118
+ return Object.assign(e, { _costUsd: c.totalUsd, _cost: c });
119
+ })
120
+ .sort((a, b) => a.timestamp - b.timestamp);
121
+ const t0 = startOfToday(now);
122
+ const w0 = startOfWeek(now);
123
+ const m0 = startOfMonth(now);
124
+ const d30 = nowMs - 30 * 86400_000;
125
+ const d28 = t0 - 27 * 86400_000;
126
+ const d14 = t0 - 13 * 86400_000;
127
+ const d7 = nowMs - 7 * 86400_000;
128
+ const today = newAgg();
129
+ const week = newAgg();
130
+ const month = newAgg();
131
+ const last30 = newAgg();
132
+ const dayMap = new Map();
133
+ for (let i = 0; i < 28; i++)
134
+ dayMap.set(d28 + i * 86400_000, { cost: 0, tokens: 0, calls: 0, output: 0, cacheRead: 0, cacheCreation: 0, input: 0 });
135
+ const byModel = new Map();
136
+ const byAgent = new Map();
137
+ const byProj = new Map();
138
+ // 今日成本分项
139
+ const split = { cacheRead: 0, cacheWrite: 0, output: 0, newInput: 0 };
140
+ // 速率样本(同会话相邻事件)
141
+ let prevBySession = new Map();
142
+ const speedToday = [];
143
+ const speedByModel = new Map();
144
+ const speedByDay = new Map();
145
+ const sessMap = new Map();
146
+ const cell = (map, key, e) => {
147
+ let c = map.get(key);
148
+ if (!c) {
149
+ c = { cost: 0, tokens: 0, calls: 0, output: 0, cacheRead: 0, cacheCreation: 0, input: 0, lastTs: 0, agent: e.agent };
150
+ map.set(key, c);
151
+ }
152
+ return c;
153
+ };
154
+ for (const e of events) {
155
+ const ts = e.timestamp;
156
+ const u = e.usage;
157
+ const cost = e._costUsd;
158
+ const c = e._cost;
159
+ if (ts >= t0) {
160
+ today.costUsd += cost;
161
+ today.tokens += u.totalTokens;
162
+ today.output += u.outputTokens;
163
+ today.calls++;
164
+ today.cacheRead += u.cacheReadTokens;
165
+ today.cacheCreation += u.cacheCreationTokens;
166
+ today.input += u.inputTokens;
167
+ split.cacheRead += c.cacheReadUsd;
168
+ split.cacheWrite += c.cacheCreationUsd;
169
+ split.output += c.outputUsd;
170
+ split.newInput += c.inputUsd;
171
+ cell(byModel, e.model, e);
172
+ cell(byAgent, e.agent, e);
173
+ cell(byProj, projKey(e), e);
174
+ for (const cc of [byModel.get(e.model), byAgent.get(e.agent), byProj.get(projKey(e))]) {
175
+ cc.cost += cost;
176
+ cc.tokens += u.totalTokens;
177
+ cc.calls++;
178
+ cc.output += u.outputTokens;
179
+ cc.cacheRead += u.cacheReadTokens;
180
+ cc.cacheCreation += u.cacheCreationTokens;
181
+ cc.input += u.inputTokens;
182
+ cc.lastTs = Math.max(cc.lastTs, ts);
183
+ }
184
+ }
185
+ if (ts >= w0) {
186
+ week.costUsd += cost;
187
+ week.tokens += u.totalTokens;
188
+ week.output += u.outputTokens;
189
+ week.calls++;
190
+ week.cacheRead += u.cacheReadTokens;
191
+ week.cacheCreation += u.cacheCreationTokens;
192
+ week.input += u.inputTokens;
193
+ }
194
+ if (ts >= m0) {
195
+ month.costUsd += cost;
196
+ month.tokens += u.totalTokens;
197
+ month.output += u.outputTokens;
198
+ month.calls++;
199
+ month.cacheRead += u.cacheReadTokens;
200
+ month.cacheCreation += u.cacheCreationTokens;
201
+ month.input += u.inputTokens;
202
+ }
203
+ if (ts >= d30) {
204
+ last30.costUsd += cost;
205
+ last30.tokens += u.totalTokens;
206
+ last30.output += u.outputTokens;
207
+ last30.calls++;
208
+ last30.cacheRead += u.cacheReadTokens;
209
+ last30.cacheCreation += u.cacheCreationTokens;
210
+ last30.input += u.inputTokens;
211
+ }
212
+ // 日序列
213
+ if (ts >= d28) {
214
+ // 对齐到当地 0 点
215
+ const d = new Date(ts);
216
+ d.setHours(0, 0, 0, 0);
217
+ const dp = dayMap.get(d.getTime());
218
+ if (dp) {
219
+ dp.cost += cost;
220
+ dp.tokens += u.totalTokens;
221
+ dp.calls++;
222
+ dp.output += u.outputTokens;
223
+ dp.cacheRead += u.cacheReadTokens;
224
+ dp.cacheCreation += u.cacheCreationTokens;
225
+ dp.input += u.inputTokens;
226
+ }
227
+ }
228
+ // 速率样本
229
+ const sk = `${e.agent}:${e.sessionId}`;
230
+ const prev = prevBySession.get(sk);
231
+ if (prev) {
232
+ const dur = (ts - prev.ts) / 1000;
233
+ if (dur >= 1 && dur <= 300 && u.outputTokens > 0) {
234
+ const rate = u.outputTokens / dur;
235
+ if (ts >= t0) {
236
+ speedToday.push(rate);
237
+ const arr = speedByModel.get(e.model) ?? [];
238
+ arr.push(rate);
239
+ speedByModel.set(e.model, arr);
240
+ }
241
+ if (ts >= d14) {
242
+ const d = new Date(ts);
243
+ d.setHours(0, 0, 0, 0);
244
+ const arr = speedByDay.get(d.getTime()) ?? [];
245
+ arr.push(rate);
246
+ speedByDay.set(d.getTime(), arr);
247
+ }
248
+ }
249
+ }
250
+ prevBySession.set(sk, { ts });
251
+ // 会话聚合(近 7 天内的会话才值得跟)
252
+ if (ts >= d7) {
253
+ let s = sessMap.get(sk);
254
+ if (!s) {
255
+ s = { agent: e.agent, model: e.model, lastTs: 0, lastCtx: 0, out10: 0, out60: 0, spark: [], calls: 0, cacheRead: 0, cacheCreation: 0, input: 0, costUsd: 0, label: projKey(e), title: e.sessionTitle, firstTs: ts };
256
+ sessMap.set(sk, s);
257
+ }
258
+ s.lastTs = Math.max(s.lastTs, ts);
259
+ s.lastCtx = u.inputTokens + u.cacheReadTokens + u.cacheCreationTokens;
260
+ s.calls++;
261
+ s.costUsd += cost;
262
+ s.cacheRead += u.cacheReadTokens;
263
+ s.cacheCreation += u.cacheCreationTokens;
264
+ s.input += u.inputTokens;
265
+ if (!s.title && e.sessionTitle)
266
+ s.title = e.sessionTitle;
267
+ }
268
+ }
269
+ prevBySession.clear();
270
+ // ---------- 日序列输出 ----------
271
+ const days = [];
272
+ const dayAggs = [];
273
+ for (let i = 0; i < 28; i++) {
274
+ const t = d28 + i * 86400_000;
275
+ const d = new Date(t);
276
+ const dp = dayMap.get(t) ?? { cost: 0, tokens: 0, calls: 0, output: 0, cacheRead: 0, cacheCreation: 0, input: 0 };
277
+ dayAggs.push(dp);
278
+ days.push({ date: `${d.getMonth() + 1}/${d.getDate()}`, weekday: `周${WD[d.getDay()]}`, costUsd: dp.cost, tokens: dp.tokens, calls: dp.calls });
279
+ }
280
+ const days14 = days.slice(14);
281
+ const dayAggs14 = dayAggs.slice(14);
282
+ // ---------- 预算 ----------
283
+ const budgetCny = monthlyBudgetCny(cfg);
284
+ const fixedFeesCny = (cfg.cloudApis ?? []).reduce((s, x) => s + (x.monthlyCny || 0), 0)
285
+ + (cfg.subscriptions ?? []).reduce((s, x) => s + (x.monthlyCny || 0), 0);
286
+ const dim = daysInMonth(now);
287
+ const dayOfMonth = now.getDate();
288
+ let budget = null;
289
+ if (budgetCny) {
290
+ const spentCny = month.costUsd * fx + fixedFeesCny;
291
+ const forecastCny = (month.costUsd / dayOfMonth) * dim * fx + fixedFeesCny;
292
+ budget = {
293
+ monthlyCny: budgetCny,
294
+ spentCny,
295
+ remainingCny: Math.max(budgetCny - spentCny, 0),
296
+ pct: (spentCny / budgetCny) * 100,
297
+ dailyCny: budgetCny / dim,
298
+ forecastCny,
299
+ };
300
+ }
301
+ // ---------- Hero ----------
302
+ const dailyAvgCny = (month.costUsd / dayOfMonth) * fx;
303
+ const forecastCny = (month.costUsd / dayOfMonth) * dim * fx + fixedFeesCny;
304
+ const mkPills = (p) => {
305
+ const pills = [];
306
+ if (p === 'today')
307
+ pills.push({ icon: 'cal', label: '本周', value: fmtCny(week.costUsd * fx) });
308
+ if (p === 'week')
309
+ pills.push({ icon: 'cal', label: '今日', value: fmtCny(today.costUsd * fx) });
310
+ if (p === 'month') {
311
+ pills.push({ icon: 'cal', label: '今日', value: fmtCny(today.costUsd * fx) });
312
+ pills.push({ icon: 'cal', label: '本周', value: fmtCny(week.costUsd * fx) });
313
+ }
314
+ if (p !== 'month')
315
+ pills.push({ icon: 'cal', label: '近 30 天', value: fmtCny(last30.costUsd * fx) });
316
+ pills.push({ icon: 'clk', label: '日均', value: fmtCny(dailyAvgCny) });
317
+ if (budget && p !== 'month')
318
+ pills.push({ icon: 'shd', label: '本月预算剩', value: fmtCny(budget.remainingCny) });
319
+ // 月底预计不依赖预算,总能给
320
+ pills.push({ icon: 'trd', label: '月底预计', value: fmtCny(budget ? budget.forecastCny : forecastCny) });
321
+ return pills.slice(0, 4);
322
+ };
323
+ const heroPeriod = (lab, a, p, hosts) => ({
324
+ label: lab,
325
+ costCny: a.costUsd * fx,
326
+ tokens: a.tokens,
327
+ outputTokens: a.output,
328
+ calls: a.calls,
329
+ cacheHitRate: hitRateOf(a),
330
+ hosts,
331
+ pills: mkPills(p),
332
+ });
333
+ const hostsSince = (sinceMs) => {
334
+ const s = new Set();
335
+ for (const e of events)
336
+ if (e.timestamp >= sinceMs)
337
+ s.add(e.agent);
338
+ return s.size;
339
+ };
340
+ const hero = {
341
+ today: heroPeriod('今天已花费', today, 'today', hostsSince(t0)),
342
+ week: heroPeriod('本周已花费', week, 'week', hostsSince(w0)),
343
+ month: heroPeriod('本月已花费', month, 'month', hostsSince(m0)),
344
+ };
345
+ // ---------- 缓存省钱条(本月) ----------
346
+ let cacheStrip = null;
347
+ if (month.cacheRead > 0) {
348
+ let savedUsd = 0;
349
+ for (const e of events) {
350
+ if (e.timestamp >= m0 && e.usage.cacheReadTokens > 0) {
351
+ savedUsd += cacheSavingsUsd(e.model, e.usage.cacheReadTokens, pricing);
352
+ }
353
+ }
354
+ cacheStrip = { savedCny: savedUsd * fx, hitRate: hitRateOf(month) };
355
+ }
356
+ // ---------- 实时流速 ----------
357
+ const live = buildLive(events, sessMap, nowMs);
358
+ // ---------- 统计卡 ----------
359
+ const stats = buildStats(today, month, last30, dayOfMonth, dayAggs14, speedToday, speedByDay, d14);
360
+ // ---------- 趋势 ----------
361
+ const sum14Cny = days14.reduce((s, d) => s + d.costUsd, 0) * fx;
362
+ const peakCny = Math.max(...days.map((d) => d.costUsd)) * fx;
363
+ const trend = {
364
+ days,
365
+ budgetDailyCny: budget ? budget.dailyCny : null,
366
+ todaySplit: {
367
+ cacheReadCny: split.cacheRead * fx,
368
+ cacheWriteCny: split.cacheWrite * fx,
369
+ outputCny: split.output * fx,
370
+ newInputCny: split.newInput * fx,
371
+ },
372
+ sum14Cny,
373
+ peakCny,
374
+ };
375
+ const cellsFor = (sinceMs) => {
376
+ const bm = new Map();
377
+ const ba = new Map();
378
+ const bp = new Map();
379
+ for (const e of events) {
380
+ if (e.timestamp < sinceMs)
381
+ continue;
382
+ for (const [map, key] of [[bm, e.model], [ba, e.agent], [bp, projKey(e)]]) {
383
+ const c = map.get(key) ?? { cost: 0 };
384
+ c.cost += e._costUsd;
385
+ map.set(key, c);
386
+ }
387
+ }
388
+ return { byModel: bm, byAgent: ba, byProj: bp };
389
+ };
390
+ const cellsToday = cellsFor(t0);
391
+ const cellsWeek = cellsFor(w0);
392
+ const cellsMonth = cellsFor(m0);
393
+ const mix = {
394
+ today: { model: mixRows(cellsToday.byModel, today.costUsd), tool: mixRows(cellsToday.byAgent, today.costUsd, (k) => AGENT_NAMES[k] ?? k), proj: mixRows(cellsToday.byProj, today.costUsd) },
395
+ week: { model: mixRows(cellsWeek.byModel, week.costUsd), tool: mixRows(cellsWeek.byAgent, week.costUsd, (k) => AGENT_NAMES[k] ?? k), proj: mixRows(cellsWeek.byProj, week.costUsd) },
396
+ month: { model: mixRows(cellsMonth.byModel, month.costUsd), tool: mixRows(cellsMonth.byAgent, month.costUsd, (k) => AGENT_NAMES[k] ?? k), proj: mixRows(cellsMonth.byProj, month.costUsd) },
397
+ };
398
+ // ---------- Token 趋势主力 ----------
399
+ const topOf = (map) => {
400
+ const rows = [...map.entries()].sort((a, b) => b[1].cost - a[1].cost);
401
+ if (!rows.length || today.costUsd <= 0)
402
+ return '';
403
+ const [k, v] = rows[0];
404
+ return `${Math.round((v.cost / today.costUsd) * 100)}%`;
405
+ };
406
+ const topName = (map, fmt) => {
407
+ const rows = [...map.entries()].sort((a, b) => b[1].cost - a[1].cost);
408
+ if (!rows.length)
409
+ return '';
410
+ const k = rows[0][0];
411
+ return fmt ? fmt(k) : k;
412
+ };
413
+ const tokTrend = {
414
+ days,
415
+ top: {
416
+ model: byModel.size ? `主力模型 ${topName(byModel)} 占 ${topOf(byModel)}` : '',
417
+ tool: byAgent.size ? `主力工具 ${topName(byAgent, (k) => AGENT_NAMES[k] ?? k)} 占 ${topOf(byAgent)}` : '',
418
+ proj: byProj.size ? `主力项目 ${topName(byProj)} 占 ${topOf(byProj)}` : '',
419
+ },
420
+ };
421
+ // ---------- 排行 ----------
422
+ const modelRank = [...byModel.entries()]
423
+ .sort((a, b) => b[1].cost - a[1].cost)
424
+ .slice(0, 4)
425
+ .map(([name, c]) => {
426
+ const e0 = events.find((e) => e.model === name);
427
+ const prov = PROVIDER_NAMES[e0?.provider ?? 'unknown'] ?? '未知';
428
+ const sp = speedByModel.get(name) ?? [];
429
+ const hit = (c.cacheRead + c.cacheCreation + c.input) > 0 ? Math.round((c.cacheRead / (c.cacheRead + c.cacheCreation + c.input)) * 100) : 0;
430
+ return {
431
+ name,
432
+ meta: `${prov} · ${c.calls} 次调用 · ${agoLabel(c.lastTs, nowMs)}`,
433
+ costUsd: c.cost,
434
+ pct: today.costUsd > 0 ? (c.cost / today.costUsd) * 100 : 0,
435
+ sub: `输出 ${fmtTok(c.output)} · 命中 ${hit}% · ${Math.round(median(sp))} tok/s`,
436
+ };
437
+ });
438
+ if (byModel.size > 4) {
439
+ const rest = [...byModel.entries()].sort((a, b) => b[1].cost - a[1].cost).slice(4);
440
+ const restCost = rest.reduce((s, [, c]) => s + c.cost, 0);
441
+ const restCalls = rest.reduce((s, [, c]) => s + c.calls, 0);
442
+ const restOut = rest.reduce((s, [, c]) => s + c.output, 0);
443
+ const names = rest.map(([n]) => n).slice(0, 2).join(' / ');
444
+ modelRank.push({
445
+ name: '其他',
446
+ meta: `${names}${rest.length > 2 ? ' 等' : ''} · ${restCalls} 次调用`,
447
+ costUsd: restCost,
448
+ pct: today.costUsd > 0 ? (restCost / today.costUsd) * 100 : 0,
449
+ sub: `输出 ${fmtTok(restOut)}`,
450
+ });
451
+ }
452
+ const hostRank = [...byAgent.entries()]
453
+ .sort((a, b) => b[1].cost - a[1].cost)
454
+ .map(([id, c]) => {
455
+ const tier = HOST_TIERS[id];
456
+ const hit = (c.cacheRead + c.cacheCreation + c.input) > 0 ? Math.round((c.cacheRead / (c.cacheRead + c.cacheCreation + c.input)) * 100) : 0;
457
+ return {
458
+ name: AGENT_NAMES[id] ?? id,
459
+ meta: `${tier?.label ?? ''} · 本地日志 · ${c.calls} 次调用 · ${agoLabel(c.lastTs, nowMs)}`,
460
+ costUsd: c.cost,
461
+ pct: today.costUsd > 0 ? (c.cost / today.costUsd) * 100 : 0,
462
+ tier,
463
+ sub: `输出 ${fmtTok(c.output)} · 命中 ${hit}%`,
464
+ };
465
+ });
466
+ // ---------- 省钱建议 ----------
467
+ const savings = buildSavings(events, cfg, pricing, sessMap, fx, d7, t0);
468
+ // ---------- 压缩潜力(2A:规则引擎,本月窗口) ----------
469
+ const monthEvents = events.filter((e) => e.timestamp >= m0);
470
+ const monthContent = contentEvents.filter((c) => c.timestamp >= m0);
471
+ const comp = monthContent.length > 0 ? computeCompression(monthEvents, monthContent, pricing) : null;
472
+ const compression = comp && comp.potentialUsd > 0.01
473
+ ? {
474
+ potentialCny: comp.potentialUsd * fx,
475
+ potentialCnyMax: comp.potentialUsdMax * fx,
476
+ itemCount: comp.itemCount,
477
+ patterns: { stale: comp.patterns.stale * fx, reread: comp.patterns.reread * fx, long: comp.patterns.long * fx },
478
+ sessions: comp.sessions.map((s) => ({ key: s.key, agent: s.agent, wasteCny: s.wasteUsd * fx, items: s.items, topPatterns: s.topPatterns })),
479
+ }
480
+ : null;
481
+ // 压缩潜力不再塞进省钱建议卡:看板已有独立的「压缩潜力」板块
482
+ // (带模式拆分 + 最浪费会话),原先这里再放一张会让同一件事重复出现。
483
+ // ---------- 2B:该 compact 了(活跃会话上下文超阈值) ----------
484
+ const COMPACT_AT = 100_000;
485
+ const needCompact = live.sessions.filter((s) => s.needsCompact);
486
+ if (needCompact.length > 0) {
487
+ const biggest = needCompact.sort((a, b) => (b.ctxTokens ?? 0) - (a.ctxTokens ?? 0))[0];
488
+ savings.push({
489
+ kind: 'info',
490
+ icon: 'route',
491
+ title: '该 compact 了',
492
+ desc: `${needCompact.length} 个活跃会话上下文超 ${Math.round(COMPACT_AT / 1000)}K tokens(最大 ${fmtTok(biggest.ctxTokens ?? 0)}),后续每轮都全量重发。在宿主里跑 /compact 可立即降本。`,
493
+ amount: `${needCompact.length} 个会话`,
494
+ });
495
+ }
496
+ // ---------- 适配器状态 ----------
497
+ const adapters = await buildAdapterTiers(cfg);
498
+ // ---------- 设置 ----------
499
+ const settings = await buildSettings(events, cfg, pricing, fx, d30);
500
+ // ---------- 托盘 ----------
501
+ const trayTitle = budget
502
+ ? `${fmtCny(today.costUsd * fx)} · ${Math.round(budget.pct)}%`
503
+ : fmtCny(today.costUsd * fx);
504
+ return {
505
+ generatedAt: nowMs,
506
+ usdToCny: fx,
507
+ dateLabel: `${now.getMonth() + 1}月${now.getDate()}日 周${WD[now.getDay()]}`,
508
+ trayTitle,
509
+ hero,
510
+ budget,
511
+ cacheStrip,
512
+ live,
513
+ stats,
514
+ trend,
515
+ mix,
516
+ tokTrend,
517
+ modelRank,
518
+ hostRank,
519
+ savings,
520
+ compression,
521
+ adapters,
522
+ settings,
523
+ };
524
+ }
525
+ // ---------- 项目键 ----------
526
+ import os from 'node:os';
527
+ const HOME_DIR = os.homedir();
528
+ function projKey(e) {
529
+ if (e.workspace) {
530
+ const ws = e.workspace.replace(/\/+$/, '');
531
+ if (ws === HOME_DIR)
532
+ return '(主目录)';
533
+ const parts = ws.split('/');
534
+ return '/' + (parts[parts.length - 1] || e.workspace);
535
+ }
536
+ return '(未记录项目)';
537
+ }
538
+ // ---------- 实时流速 ----------
539
+ // tok/s 记账口径修复:日志里一条事件的 tokens 全记在「调用完成时刻」,
540
+ // 直接分桶会把整个生成过程的量压进一个 20s 桶(虚高尖峰+滞后)。
541
+ // 修复:把每条事件的 output/ctx 按 [同会话上一事件时刻, 完成时刻] 匀速分摊
542
+ // (上限 120s 防长停顿稀释),总量不变,速率曲线回到真实形状。
543
+ const MAX_SPAN_MS = 120_000;
544
+ function buildLive(events, sessMap, nowMs) {
545
+ const BUCKET = 20_000;
546
+ const N60 = 180; // 60 分钟
547
+ const outB = new Array(N60).fill(0);
548
+ const ctxB = new Array(N60).fill(0);
549
+ const t0 = nowMs - N60 * BUCKET;
550
+ const t10 = nowMs - 600_000;
551
+ const m1 = nowMs - 60_000;
552
+ // 会话分钟桶(spark 用):key → 10 个 60s 桶
553
+ const sessSpark = new Map();
554
+ let calls60 = 0;
555
+ const prevTs = new Map();
556
+ for (const e of events) {
557
+ const sk = `${e.agent}:${e.sessionId}`;
558
+ const prev = prevTs.get(sk);
559
+ prevTs.set(sk, e.timestamp);
560
+ if (e.timestamp >= m1)
561
+ calls60++;
562
+ if (e.timestamp < t0)
563
+ continue;
564
+ const spanStart = Math.max(prev ?? 0, e.timestamp - MAX_SPAN_MS, t0);
565
+ const span = Math.max(e.timestamp - spanStart, 1000);
566
+ const out = e.usage.outputTokens;
567
+ const ctx = e.usage.inputTokens + e.usage.cacheReadTokens + e.usage.cacheCreationTokens;
568
+ if (out === 0 && ctx === 0)
569
+ continue;
570
+ const i0 = Math.max(0, Math.floor((spanStart - t0) / BUCKET));
571
+ const i1 = Math.min(N60 - 1, Math.floor((e.timestamp - t0) / BUCKET));
572
+ for (let i = i0; i <= i1; i++) {
573
+ const b0 = t0 + i * BUCKET;
574
+ const ov = Math.min(b0 + BUCKET, e.timestamp) - Math.max(b0, spanStart);
575
+ if (ov <= 0)
576
+ continue;
577
+ outB[i] += (out * ov) / span;
578
+ ctxB[i] += (ctx * ov) / span;
579
+ }
580
+ // 会话 spark:近 10 分钟内的部分按同样口径分摊到 60s 桶
581
+ if (e.timestamp >= t10) {
582
+ let spark = sessSpark.get(sk);
583
+ if (!spark) {
584
+ spark = new Array(10).fill(0);
585
+ sessSpark.set(sk, spark);
586
+ }
587
+ const s0 = Math.max(spanStart, t10);
588
+ const j0 = Math.max(0, Math.floor((s0 - t10) / 60_000));
589
+ const j1 = Math.min(9, Math.floor((e.timestamp - t10) / 60_000));
590
+ const sSpan = Math.max(e.timestamp - s0, 1000);
591
+ for (let j = j0; j <= j1; j++) {
592
+ const b0 = t10 + j * 60_000;
593
+ const ov = Math.min(b0 + 60_000, e.timestamp) - Math.max(b0, s0);
594
+ if (ov <= 0)
595
+ continue;
596
+ spark[j] += (out * ov) / sSpan;
597
+ }
598
+ }
599
+ }
600
+ const rates = outB.map((v) => v / 20);
601
+ let peak = 0;
602
+ let peakIdx = 0;
603
+ rates.forEach((r, i) => { if (r > peak) {
604
+ peak = r;
605
+ peakIdx = i;
606
+ } });
607
+ // 当前/上下文:近 60s = 末 3 桶
608
+ const out60 = outB[N60 - 1] + outB[N60 - 2] + outB[N60 - 3];
609
+ const ctx60 = ctxB[N60 - 1] + ctxB[N60 - 2] + ctxB[N60 - 3];
610
+ // 会话:近 30 分钟有事件的进入列表
611
+ const sessions = [];
612
+ let activeCount = 0;
613
+ let idleCount = 0;
614
+ const sorted = [...sessMap.entries()]
615
+ .filter(([, s]) => nowMs - s.lastTs < 30 * 60_000)
616
+ .sort((a, b) => b[1].lastTs - a[1].lastTs);
617
+ for (const [key, s] of sorted) {
618
+ const active = nowMs - s.lastTs < 120_000;
619
+ if (active)
620
+ activeCount++;
621
+ else
622
+ idleCount++;
623
+ if (sessions.length >= 5)
624
+ continue;
625
+ // out10min 仍是原始量(计数不是速率);rate/spark 用分摊后的分钟桶
626
+ let out10 = 0;
627
+ for (let i = events.length - 1; i >= 0; i--) {
628
+ const e = events[i];
629
+ if (e.timestamp < t10)
630
+ break;
631
+ if (`${e.agent}:${e.sessionId}` !== key)
632
+ continue;
633
+ out10 += e.usage.outputTokens;
634
+ }
635
+ const spark = sessSpark.get(key) ?? new Array(10).fill(0);
636
+ sessions.push({
637
+ key,
638
+ agent: s.agent,
639
+ label: s.title ? `${s.label} · ${s.title}` : s.label,
640
+ model: s.model,
641
+ ctxTokens: s.lastCtx,
642
+ needsCompact: s.lastCtx > 100_000,
643
+ active,
644
+ ago: agoLabel(s.lastTs, nowMs),
645
+ out10min: out10,
646
+ rateTokS: spark[9] / 60,
647
+ spark: spark.map((v) => v / 60),
648
+ });
649
+ }
650
+ return {
651
+ currentTokS: out60 / 60,
652
+ peakTokS: peak,
653
+ peakAt: peak > 0 ? hhmm(t0 + peakIdx * BUCKET) : '—',
654
+ ctxPerMin: ctx60,
655
+ callsPerMin: calls60,
656
+ activeCount,
657
+ idleCount,
658
+ buckets30: rates.slice(90),
659
+ buckets60: rates,
660
+ sessions,
661
+ };
662
+ }
663
+ // ---------- 统计卡 ----------
664
+ function median(arr) {
665
+ if (!arr.length)
666
+ return 0;
667
+ const s = [...arr].sort((a, b) => a - b);
668
+ return s[Math.floor(s.length / 2)];
669
+ }
670
+ function p90(arr) {
671
+ if (!arr.length)
672
+ return 0;
673
+ const s = [...arr].sort((a, b) => a - b);
674
+ return s[Math.min(s.length - 1, Math.floor(s.length * 0.9))];
675
+ }
676
+ function buildStats(today, month, last30, dayOfMonth, dayAggs14, speedToday, speedByDay, d14) {
677
+ const monthDailyAvgTok = month.tokens / dayOfMonth;
678
+ const todayHit = (today.cacheRead + today.cacheCreation + today.input) > 0
679
+ ? (today.cacheRead / (today.cacheRead + today.cacheCreation + today.input)) * 100 : 0;
680
+ const hit30d = (last30.cacheRead + last30.cacheCreation + last30.input) > 0
681
+ ? (last30.cacheRead / (last30.cacheRead + last30.cacheCreation + last30.input)) * 100 : 0;
682
+ const speedMed = median(speedToday);
683
+ const speedP90 = p90(speedToday);
684
+ const avgInPerCall = today.calls > 0 ? (today.input + today.cacheRead + today.cacheCreation) / today.calls : 0;
685
+ // 各卡的 14 天 mini 序列(各用各的指标)
686
+ const hitOfDay = (d) => {
687
+ const dn = d.cacheRead + d.cacheCreation + d.input;
688
+ return dn > 0 ? (d.cacheRead / dn) * 100 : 0;
689
+ };
690
+ const speedMini = dayAggs14.map((_, i) => {
691
+ const dayStart = d14 + i * 86400_000;
692
+ return median(speedByDay.get(dayStart) ?? []);
693
+ });
694
+ return {
695
+ tokens: { value: fmtTok(today.tokens), sub: `日均 ${fmtTok(monthDailyAvgTok)}`, mini: dayAggs14.map((d) => d.tokens) },
696
+ output: { value: fmtTok(today.output), sub: today.tokens > 0 ? `占今日总量 ${Math.round((today.output / today.tokens) * 100)}%` : '—', mini: dayAggs14.map((d) => d.output) },
697
+ cacheRead: { value: fmtTok(today.cacheRead), sub: `占读入 ${todayHit.toFixed(1)}%`, mini: dayAggs14.map((d) => d.cacheRead) },
698
+ cacheWrite: { value: fmtTok(today.cacheCreation), sub: '新写进提示缓存', mini: dayAggs14.map((d) => d.cacheCreation) },
699
+ newInput: { value: fmtTok(today.input), sub: '不走缓存的输入', mini: dayAggs14.map((d) => d.input) },
700
+ hitRate: { value: `${hit30d.toFixed(1)}%`, sub: `近 30 天 · 今日 ${todayHit.toFixed(0)}%`, mini: dayAggs14.map(hitOfDay) },
701
+ speed: { value: speedMed.toFixed(1), sub: `中位 ${speedMed.toFixed(1)} · P90 ${speedP90.toFixed(0)} tok/s`, mini: speedMini },
702
+ calls: { value: String(today.calls), sub: `每次读入 ${fmtTok(avgInPerCall)}`, mini: dayAggs14.map((d) => d.calls) },
703
+ };
704
+ }
705
+ // ---------- 构成 ----------
706
+ function mixRows(map, total, fmt) {
707
+ const rows = [...map.entries()].sort((a, b) => b[1].cost - a[1].cost);
708
+ const out = [];
709
+ let rest = 0;
710
+ rows.forEach(([k, v], i) => {
711
+ if (i < 4)
712
+ out.push({ name: fmt ? fmt(k) : k, costUsd: v.cost, pct: total > 0 ? (v.cost / total) * 100 : 0 });
713
+ else
714
+ rest += v.cost;
715
+ });
716
+ if (rest > 0)
717
+ out.push({ name: '其他', costUsd: rest, pct: total > 0 ? (rest / total) * 100 : 0 });
718
+ return out;
719
+ }
720
+ // ---------- 省钱建议 ----------
721
+ function buildSavings(events, cfg, pricing, sessMap, fx, d7, _t0) {
722
+ const cards = [];
723
+ const weekEvents = events.filter((e) => e.timestamp >= d7);
724
+ // 1) 打转检测(近 7 天,阈值放宽到 30 次)
725
+ const alerts = detectRetryLoops(weekEvents, (m, u) => costOf(m, u, pricing), { minCallsPerSession: 30, minCostUsd: 0.3 });
726
+ if (alerts.length > 0) {
727
+ // 浪费 ≈ 超出前 30 次调用的那部分成本
728
+ let waste = 0;
729
+ let totalCalls = 0;
730
+ for (const a of alerts.slice(0, 5)) {
731
+ const sessEvents = weekEvents.filter((e) => e.sessionId === a.sessionId && e.agent === a.agent);
732
+ sessEvents.forEach((e, i) => { if (i >= 30)
733
+ waste += e._costUsd; });
734
+ totalCalls += a.calls;
735
+ }
736
+ const wasteCny = waste * fx;
737
+ cards.push({
738
+ kind: 'warn', icon: 'retry', title: '检测到打转',
739
+ desc: `${alerts.length} 个会话出现重复重试共 ${totalCalls} 次,浪费 ${fmtCny(wasteCny)}。常见于工具报错后原地重试,建议人工介入。`,
740
+ amount: `−${fmtCny(wasteCny)}`,
741
+ });
742
+ }
743
+ // 2) 模型迁移建议(近 30 天)
744
+ const advice = savingsAdvice(events)[0];
745
+ if (advice) {
746
+ cards.push({
747
+ kind: 'info', icon: 'route', title: '模型迁移建议',
748
+ desc: `${advice.observation}。${advice.suggestion}。`,
749
+ amount: `约省 ${fmtCny(advice.estimatedSavingsUsdPerMonth * fx)}/月`,
750
+ });
751
+ }
752
+ // 3) 缓存优化空间(近 7 天低命中会话)
753
+ let lowN = 0;
754
+ let lowHit = 1;
755
+ let saveWeekUsd = 0;
756
+ for (const s of sessMap.values()) {
757
+ const totalIn = s.cacheRead + s.cacheCreation + s.input;
758
+ if (s.calls < 10 || totalIn <= 0)
759
+ continue;
760
+ const hit = s.cacheRead / totalIn;
761
+ if (hit >= 0.6)
762
+ continue;
763
+ lowN++;
764
+ lowHit = Math.min(lowHit, hit);
765
+ const p = priceFor(s.model, pricing);
766
+ const missed = (0.95 - hit) * totalIn;
767
+ saveWeekUsd += (missed / 1_000_000) * Math.max(p.input - (p.cacheRead ?? p.input * 0.1), 0);
768
+ }
769
+ if (lowN > 0 && saveWeekUsd > 0.01) {
770
+ cards.push({
771
+ kind: 'pos', icon: 'cache', title: '缓存优化空间',
772
+ desc: `${lowN} 个会话命中率仅 ${Math.round(lowHit * 100)}%,稳定系统提示词并复用会话可恢复到 95% 水平。`,
773
+ amount: `${fmtCny(saveWeekUsd * fx)}/周`,
774
+ });
775
+ }
776
+ void cfg;
777
+ return cards.slice(0, 3);
778
+ }
779
+ // ---------- 设置 ----------
780
+ async function buildSettings(events, cfg, pricing, fx, d30) {
781
+ // 近 30 天出现过的模型(按花费降序)∪ 用户覆写
782
+ const costByModel = new Map();
783
+ for (const e of events) {
784
+ if (e.timestamp < d30)
785
+ continue;
786
+ costByModel.set(e.model, (costByModel.get(e.model) ?? 0) + 1);
787
+ }
788
+ const names = [...costByModel.keys()];
789
+ for (const k of Object.keys(cfg.priceOverrides ?? {})) {
790
+ if (!names.includes(k))
791
+ names.push(k);
792
+ }
793
+ const models = names.slice(0, 12).map((name) => {
794
+ const p = priceFor(name, pricing);
795
+ const cr = p.cacheRead ?? p.input * 0.1;
796
+ return {
797
+ name,
798
+ inputCny: Math.round(p.input * fx * 100) / 100,
799
+ outputCny: Math.round(p.output * fx * 100) / 100,
800
+ cacheReadCny: Math.round(cr * fx * 100) / 100,
801
+ };
802
+ });
803
+ return {
804
+ autoCompact: cfg.autoCompact ?? { enabled: false },
805
+ rtkInstalled: await import('./rtk.js').then((m) => m.rtkInstalled()).catch(() => false),
806
+ models,
807
+ overrideNames: Object.keys(cfg.priceOverrides ?? {}),
808
+ cloudApis: cfg.cloudApis ?? [],
809
+ subscriptions: cfg.subscriptions ?? [],
810
+ monthlyBudgetCny: monthlyBudgetCny(cfg) ?? null,
811
+ usdToCny: fx,
812
+ };
813
+ }