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