@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.
- package/.github/FUNDING.yml +3 -0
- package/.github/workflows/build-desktop.yml +68 -0
- package/.idea/go.imports.xml +10 -0
- package/.idea/modules.xml +8 -0
- package/.idea/sonarlint/vulnerabilitystore/default/index.pb +0 -0
- package/.idea/thriftCompilerAssist.xml +6 -0
- package/.idea/token-pilot.iml +9 -0
- package/.idea/vcs.xml +6 -0
- package/README-en.md +127 -0
- package/README.md +146 -2
- package/bin/token-pilot.js +15 -0
- 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 +40 -0
- package/menubar/package-lock.json +248 -0
- package/menubar/package.json +16 -0
- package/menubar/src/dashboard.html +1266 -0
- package/menubar/src/index.html +674 -0
- package/menubar/src-tauri/Cargo.lock +4963 -0
- package/menubar/src-tauri/Cargo.toml +15 -0
- package/menubar/src-tauri/build.rs +3 -0
- package/menubar/src-tauri/gen/schemas/acl-manifests.json +1 -0
- package/menubar/src-tauri/gen/schemas/capabilities.json +1 -0
- package/menubar/src-tauri/gen/schemas/desktop-schema.json +2526 -0
- package/menubar/src-tauri/gen/schemas/macOS-schema.json +2526 -0
- 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 +5 -0
- 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 +4 -0
- 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 +486 -0
- package/menubar/src-tauri/tauri.conf.json +56 -0
- package/package.json +20 -3
- package/pricing/models.json +311 -0
- package/scripts/gen-icons.py +153 -0
- package/scripts/reconcile.py +162 -0
- package/scripts/verify-dashboard.py +101 -0
- package/src/adapters/claude-code.ts +246 -0
- package/src/adapters/codex.ts +166 -0
- package/src/adapters/dsh.ts +156 -0
- package/src/adapters/kimi-code.ts +164 -0
- package/src/adapters/opencode.ts +120 -0
- package/src/adapters/pi.ts +99 -0
- package/src/adapters/qoder.ts +43 -0
- package/src/adapters/types.ts +39 -0
- package/src/adapters/volc-ark.ts +102 -0
- package/src/adapters/workbuddy.ts +135 -0
- package/src/cli/index.ts +294 -0
- package/src/cli/serve.ts +209 -0
- package/src/core/aggregate.ts +821 -0
- package/src/core/alert.ts +33 -0
- package/src/core/autocompact.ts +46 -0
- package/src/core/budget.ts +42 -0
- package/src/core/collector.ts +209 -0
- package/src/core/compression.ts +163 -0
- package/src/core/config.ts +71 -0
- package/src/core/contract.ts +181 -0
- package/src/core/metrics.ts +72 -0
- package/src/core/price-fetch.ts +112 -0
- package/src/core/pricing.ts +182 -0
- package/src/core/registry.ts +141 -0
- package/src/core/retry-detector.ts +64 -0
- package/src/core/rtk.ts +58 -0
- package/src/core/savings.ts +55 -0
- package/src/core/schema.ts +66 -0
- package/src/core/unknown-models.ts +64 -0
- package/tests/adapters-dsh.test.ts +35 -0
- package/tests/adapters-opencode.test.ts +39 -0
- package/tests/adapters-pi.test.ts +33 -0
- package/tests/adapters-workbuddy.test.ts +34 -0
- package/tests/adapters.test.ts +45 -0
- package/tests/aggregate.test.ts +153 -0
- package/tests/compression.test.ts +71 -0
- package/tests/fixtures/claude-session.jsonl +9 -0
- package/tests/fixtures/codex-rollout.jsonl +5 -0
- package/tests/fixtures/kimi-wire.jsonl +6 -0
- package/tests/pricing-timebased.test.ts +51 -0
- package/tests/pricing.test.ts +73 -0
- package/tests/serve.test.ts +29 -0
- package/tsconfig.json +19 -0
- package/web/dashboard.html +1266 -0
- package/web/panel.html +674 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Doubao · 火山 adapter — 云端用量 API(经 arkcli usage stats,日粒度)
|
|
2
|
+
// 与本地日志粒度不同:云端是「每天×模型」的合计,一个 record 是一天总量(非单次调用)。
|
|
3
|
+
// 事件时间戳取当天中午;调用次数字段无法精确(记录的是 ReqCnt 汇总),会话维度不适用。
|
|
4
|
+
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import type { UsageEvent } from '../core/schema.ts';
|
|
8
|
+
import type { Adapter } from './types.ts';
|
|
9
|
+
|
|
10
|
+
const execFileP = promisify(execFile);
|
|
11
|
+
|
|
12
|
+
interface ArkRecord {
|
|
13
|
+
Day?: string;
|
|
14
|
+
Model?: string;
|
|
15
|
+
ModelID?: string;
|
|
16
|
+
Endpoint?: string;
|
|
17
|
+
InputTokens?: number;
|
|
18
|
+
CacheTokensHit?: number;
|
|
19
|
+
OutputTokens?: number;
|
|
20
|
+
TotalTokens?: number;
|
|
21
|
+
ReqCnt?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// arkcli 输出尾部可能跟非 JSON 行(升级提示等),只解析第一个完整 JSON 对象
|
|
25
|
+
function extractJson(raw: string): { records?: ArkRecord[] } | null {
|
|
26
|
+
const start = raw.indexOf('{');
|
|
27
|
+
if (start < 0) return null;
|
|
28
|
+
let depth = 0;
|
|
29
|
+
for (let i = start; i < raw.length; i++) {
|
|
30
|
+
if (raw[i] === '{') depth++;
|
|
31
|
+
else if (raw[i] === '}') {
|
|
32
|
+
depth--;
|
|
33
|
+
if (depth === 0) {
|
|
34
|
+
try { return JSON.parse(raw.slice(start, i + 1)); } catch { return null; }
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function ymd(d: Date): string {
|
|
42
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const volcArkAdapter: Adapter = {
|
|
46
|
+
meta: {
|
|
47
|
+
id: 'volc-ark',
|
|
48
|
+
displayName: 'Doubao · 火山',
|
|
49
|
+
detectPaths: [],
|
|
50
|
+
detectCommands: ['arkcli'],
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
async detect() {
|
|
54
|
+
try {
|
|
55
|
+
await execFileP('arkcli', ['--version'], { timeout: 5000 });
|
|
56
|
+
return true;
|
|
57
|
+
} catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
|
|
62
|
+
async readEvents(sinceMs = 0): Promise<UsageEvent[]> {
|
|
63
|
+
const start = ymd(new Date(sinceMs > 0 ? sinceMs : Date.now() - 40 * 86400_000));
|
|
64
|
+
let out: string;
|
|
65
|
+
try {
|
|
66
|
+
const r = await execFileP('arkcli', ['usage', 'stats', '--start', start, '--format', 'json'], { timeout: 30_000 });
|
|
67
|
+
out = r.stdout;
|
|
68
|
+
} catch {
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
const parsed = extractJson(out);
|
|
72
|
+
if (!parsed?.records) return [];
|
|
73
|
+
|
|
74
|
+
const events: UsageEvent[] = [];
|
|
75
|
+
for (const rec of parsed.records) {
|
|
76
|
+
const input = Math.max((rec.InputTokens ?? 0) - (rec.CacheTokensHit ?? 0), 0);
|
|
77
|
+
const cacheRead = rec.CacheTokensHit ?? 0;
|
|
78
|
+
const output = rec.OutputTokens ?? 0;
|
|
79
|
+
if (input + cacheRead + output === 0) continue;
|
|
80
|
+
const model = rec.Model ?? rec.ModelID ?? rec.Endpoint ?? 'doubao-cloud';
|
|
81
|
+
// 日粒度:时间戳定当天中午
|
|
82
|
+
const ts = rec.Day ? new Date(rec.Day + 'T12:00:00').getTime() : Date.now();
|
|
83
|
+
if (ts < sinceMs) continue;
|
|
84
|
+
events.push({
|
|
85
|
+
agent: 'volc-ark',
|
|
86
|
+
sessionId: `cloud-${rec.Day}`,
|
|
87
|
+
eventId: `volc-${rec.Day}-${model}`,
|
|
88
|
+
timestamp: ts,
|
|
89
|
+
provider: 'doubao',
|
|
90
|
+
model,
|
|
91
|
+
usage: {
|
|
92
|
+
inputTokens: input,
|
|
93
|
+
outputTokens: output,
|
|
94
|
+
cacheReadTokens: cacheRead,
|
|
95
|
+
cacheCreationTokens: 0,
|
|
96
|
+
totalTokens: input + output + cacheRead,
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
return events;
|
|
101
|
+
},
|
|
102
|
+
};
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// WorkBuddy / WorkBuddy AI adapter — 只读解析 ~/.workbuddy{,-ai}/traces/*/**\/*.jsonl
|
|
2
|
+
// 结构:OTel 风格 trace 文件;trace_end.summary.modelInfo 有完整用量:
|
|
3
|
+
// { models, totalInputTokens, totalOutputTokens, totalCachedTokens, callCount }
|
|
4
|
+
// 口径:trace 级聚合(一个 trace = 一次 Agent 工作流),逐调用粒度不可得——如实标注。
|
|
5
|
+
|
|
6
|
+
import { promises as fs } from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import type { UsageEvent } from '../core/schema.ts';
|
|
10
|
+
import type { Adapter } from './types.ts';
|
|
11
|
+
|
|
12
|
+
const HOME = os.homedir();
|
|
13
|
+
const ROOTS: [string, string][] = [
|
|
14
|
+
[path.join(HOME, '.workbuddy', 'traces'), 'workbuddy'],
|
|
15
|
+
[path.join(HOME, '.workbuddy-ai', 'traces'), 'workbuddy-ai'],
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
interface WbSummary {
|
|
19
|
+
sessionId?: string;
|
|
20
|
+
startedAt?: string;
|
|
21
|
+
endedAt?: string;
|
|
22
|
+
modelInfo?: {
|
|
23
|
+
models?: string[];
|
|
24
|
+
totalInputTokens?: number;
|
|
25
|
+
totalOutputTokens?: number;
|
|
26
|
+
totalCachedTokens?: number;
|
|
27
|
+
callCount?: number;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface WbLine {
|
|
32
|
+
type?: string;
|
|
33
|
+
summary?: WbSummary;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function* walkJsonl(dir: string): AsyncGenerator<string> {
|
|
37
|
+
let entries: fs.Dirent[];
|
|
38
|
+
try { entries = await fs.readdir(dir, { withFileTypes: true }); } catch { return; }
|
|
39
|
+
for (const e of entries) {
|
|
40
|
+
const full = path.join(dir, e.name);
|
|
41
|
+
if (e.isDirectory()) yield* walkJsonl(full);
|
|
42
|
+
else if (e.isFile() && e.name.endsWith('.jsonl')) yield full;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function parseTraceEnd(line: string, file: string, agent: string): UsageEvent | null {
|
|
47
|
+
if (!line.includes('"trace_end"') || !line.includes('modelInfo')) return null;
|
|
48
|
+
let d: WbLine;
|
|
49
|
+
try { d = JSON.parse(line); } catch { return null; }
|
|
50
|
+
if (d.type !== 'trace_end') return null;
|
|
51
|
+
const s = d.summary;
|
|
52
|
+
const mi = s?.modelInfo;
|
|
53
|
+
if (!s || !mi || !mi.models?.length) return null;
|
|
54
|
+
|
|
55
|
+
const totalIn = mi.totalInputTokens ?? 0;
|
|
56
|
+
const cacheRead = mi.totalCachedTokens ?? 0;
|
|
57
|
+
const input = Math.max(totalIn - cacheRead, 0);
|
|
58
|
+
const output = mi.totalOutputTokens ?? 0;
|
|
59
|
+
if (input + cacheRead + output === 0) return null;
|
|
60
|
+
|
|
61
|
+
const model = mi.models[0];
|
|
62
|
+
return {
|
|
63
|
+
agent,
|
|
64
|
+
sessionId: s.sessionId ?? path.basename(file, '.jsonl'),
|
|
65
|
+
eventId: path.basename(file, '.jsonl'),
|
|
66
|
+
timestamp: s.endedAt ? new Date(s.endedAt).getTime() : 0,
|
|
67
|
+
provider: providerFromModel(model),
|
|
68
|
+
model,
|
|
69
|
+
usage: {
|
|
70
|
+
inputTokens: input,
|
|
71
|
+
outputTokens: output,
|
|
72
|
+
cacheReadTokens: cacheRead,
|
|
73
|
+
cacheCreationTokens: 0,
|
|
74
|
+
totalTokens: input + output + cacheRead,
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function providerFromModel(model: string): string {
|
|
80
|
+
const m = model.toLowerCase();
|
|
81
|
+
if (m.startsWith('hy') || m.includes('hunyuan')) return 'hunyuan';
|
|
82
|
+
if (m.includes('glm')) return 'glm';
|
|
83
|
+
if (m.includes('deepseek')) return 'deepseek';
|
|
84
|
+
if (m.includes('kimi')) return 'kimi';
|
|
85
|
+
if (m.includes('claude')) return 'anthropic';
|
|
86
|
+
if (m.includes('gpt')) return 'openai';
|
|
87
|
+
return 'unknown';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function readFileEvents(file: string, sinceMs: number, agent: string): Promise<UsageEvent[]> {
|
|
91
|
+
let content: string;
|
|
92
|
+
try { content = await fs.readFile(file, 'utf8'); } catch { return []; }
|
|
93
|
+
const events: UsageEvent[] = [];
|
|
94
|
+
for (const line of content.split('\n')) {
|
|
95
|
+
if (!line.trim()) continue;
|
|
96
|
+
const ev = parseTraceEnd(line, file, agent);
|
|
97
|
+
if (ev && ev.timestamp >= sinceMs) events.push(ev);
|
|
98
|
+
}
|
|
99
|
+
return events;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function makeAdapter(root: string, agentId: string, displayName: string): Adapter {
|
|
103
|
+
return {
|
|
104
|
+
meta: { id: agentId, displayName, detectPaths: [path.dirname(root)] },
|
|
105
|
+
async detect() {
|
|
106
|
+
try { await fs.access(root); return true; } catch { return false; }
|
|
107
|
+
},
|
|
108
|
+
async listFiles() {
|
|
109
|
+
const out: string[] = [];
|
|
110
|
+
for await (const f of walkJsonl(root)) out.push(f);
|
|
111
|
+
return out;
|
|
112
|
+
},
|
|
113
|
+
async readFileEvents(file: string, sinceMs = 0) {
|
|
114
|
+
return readFileEvents(file, sinceMs, agentId);
|
|
115
|
+
},
|
|
116
|
+
async readEvents(sinceMs = 0) {
|
|
117
|
+
return readFileEventsList(await this.listFiles!(), sinceMs, agentId);
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function readFileEventsList(files: string[], sinceMs: number, agent: string): Promise<UsageEvent[]> {
|
|
123
|
+
const events: UsageEvent[] = [];
|
|
124
|
+
for (const file of files) {
|
|
125
|
+
try {
|
|
126
|
+
const st = await fs.stat(file);
|
|
127
|
+
if (st.mtimeMs < sinceMs) continue;
|
|
128
|
+
} catch { continue; }
|
|
129
|
+
events.push(...(await readFileEvents(file, sinceMs, agent)));
|
|
130
|
+
}
|
|
131
|
+
return events;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export const workbuddyAdapter = makeAdapter(ROOTS[0][0], 'workbuddy', 'WorkBuddy');
|
|
135
|
+
export const workbuddyAiAdapter = makeAdapter(ROOTS[1][0], 'workbuddy-ai', 'WorkBuddy AI');
|
package/src/cli/index.ts
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// token-pilot CLI — 多宿主聚合
|
|
3
|
+
// 命令:today | month | report | sync | dash | serve
|
|
4
|
+
|
|
5
|
+
import { costOf, loadPricingWithOverrides } from '../core/pricing.ts';
|
|
6
|
+
import { progressBar } from '../core/budget.ts';
|
|
7
|
+
import { detectRetryLoops } from '../core/retry-detector.ts';
|
|
8
|
+
import { savingsAdvice } from '../core/savings.ts';
|
|
9
|
+
import { notify } from '../core/alert.ts';
|
|
10
|
+
import { loadConfig, fxRate, monthlyBudgetCny } from '../core/config.ts';
|
|
11
|
+
import { writeSummary } from '../core/metrics.ts';
|
|
12
|
+
import { collectAll, collectCached, acquireSyncLock, releaseSyncLock } from '../core/collector.ts';
|
|
13
|
+
import { hasKnownPrice, priceFor } from '../core/pricing.ts';
|
|
14
|
+
import { trackUnknown, loadUnknown } from '../core/unknown-models.ts';
|
|
15
|
+
import { autoFetchPrices, autoOverrides } from '../core/price-fetch.ts';
|
|
16
|
+
import { buildDashboardData } from '../core/aggregate.ts';
|
|
17
|
+
import { serve, bakeDashboard, writeDashboardDataFile } from './serve.ts';
|
|
18
|
+
import type { UsageEvent } from '../core/schema.ts';
|
|
19
|
+
|
|
20
|
+
function startOfToday(): number {
|
|
21
|
+
const d = new Date();
|
|
22
|
+
d.setHours(0, 0, 0, 0);
|
|
23
|
+
return d.getTime();
|
|
24
|
+
}
|
|
25
|
+
function startOfMonth(): number {
|
|
26
|
+
const d = new Date();
|
|
27
|
+
d.setDate(1);
|
|
28
|
+
d.setHours(0, 0, 0, 0);
|
|
29
|
+
return d.getTime();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface CellAgg {
|
|
33
|
+
tokens: number;
|
|
34
|
+
cost: number;
|
|
35
|
+
events: number;
|
|
36
|
+
}
|
|
37
|
+
interface Agg {
|
|
38
|
+
tokens: number;
|
|
39
|
+
cost: number;
|
|
40
|
+
events: number;
|
|
41
|
+
byAgent: Map<string, CellAgg>;
|
|
42
|
+
byModel: Map<string, CellAgg>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function aggregate(events: UsageEvent[]): Agg {
|
|
46
|
+
const agg: Agg = { tokens: 0, cost: 0, events: events.length, byAgent: new Map(), byModel: new Map() };
|
|
47
|
+
for (const e of events) {
|
|
48
|
+
const c = costOf(e.model, e.usage, undefined, e.timestamp);
|
|
49
|
+
const tok = e.usage.totalTokens;
|
|
50
|
+
agg.tokens += tok;
|
|
51
|
+
agg.cost += c.totalUsd;
|
|
52
|
+
for (const [map, key] of [[agg.byAgent, e.agent], [agg.byModel, e.model]] as const) {
|
|
53
|
+
const cell = map.get(key) ?? { tokens: 0, cost: 0, events: 0 };
|
|
54
|
+
cell.tokens += tok;
|
|
55
|
+
cell.cost += c.totalUsd;
|
|
56
|
+
cell.events += 1;
|
|
57
|
+
map.set(key, cell);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return agg;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function fmtUsd(n: number): string {
|
|
64
|
+
return '$' + n.toFixed(2);
|
|
65
|
+
}
|
|
66
|
+
function fmtTokens(n: number): string {
|
|
67
|
+
if (n >= 1_000_000) return (n / 1_000_000).toFixed(2) + 'M';
|
|
68
|
+
if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K';
|
|
69
|
+
return String(n);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function printMap(title: string, map: Map<string, CellAgg>) {
|
|
73
|
+
console.log(title);
|
|
74
|
+
const sorted = [...map.entries()].sort((a, b) => b[1].cost - a[1].cost);
|
|
75
|
+
for (const [key, c] of sorted) {
|
|
76
|
+
console.log(` ${key.padEnd(30)} ${fmtTokens(c.tokens).padStart(9)} tokens ${fmtUsd(c.cost).padStart(9)} ${c.events} 次`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function cmdReport(cmd: string) {
|
|
81
|
+
const since = cmd === 'today' ? startOfToday() : cmd === 'month' ? startOfMonth() : 0;
|
|
82
|
+
const label = cmd === 'today' ? '今天' : cmd === 'month' ? '本月' : '全部';
|
|
83
|
+
console.log(`\ntoken-pilot · ${label}\n`);
|
|
84
|
+
|
|
85
|
+
const { events: allEvents, detected } = await collectAll(since);
|
|
86
|
+
console.log(`已检测宿主:${detected.join('、') || '无'}\n`);
|
|
87
|
+
|
|
88
|
+
if (allEvents.length === 0) {
|
|
89
|
+
console.log('该时段无用量记录');
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const agg = aggregate(allEvents);
|
|
94
|
+
printMap('按宿主:', agg.byAgent);
|
|
95
|
+
console.log('');
|
|
96
|
+
printMap('按模型:', agg.byModel);
|
|
97
|
+
console.log('');
|
|
98
|
+
console.log(`合计:${fmtTokens(agg.tokens)} tokens · ${fmtUsd(agg.cost)} · ${agg.events} 次调用`);
|
|
99
|
+
|
|
100
|
+
const cfg = loadConfig();
|
|
101
|
+
const budgetCny = monthlyBudgetCny(cfg);
|
|
102
|
+
if (budgetCny) {
|
|
103
|
+
const { events: monthEvents } = await collectAll(startOfMonth());
|
|
104
|
+
const monthCostUsd = monthEvents.reduce((s, e) => s + costOf(e.model, e.usage, undefined, e.timestamp).totalUsd, 0);
|
|
105
|
+
const monthCostCny = monthCostUsd * fxRate(cfg);
|
|
106
|
+
const pct = (monthCostCny / budgetCny) * 100;
|
|
107
|
+
const forecast = (monthCostCny / new Date().getDate()) * new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate();
|
|
108
|
+
console.log('');
|
|
109
|
+
console.log(`预算:¥${monthCostCny.toFixed(0)} / ¥${budgetCny} ${progressBar(pct)}`);
|
|
110
|
+
console.log(`照这个速度,月底预计:¥${forecast.toFixed(0)}${forecast > budgetCny ? '(预计超支)' : ''}`);
|
|
111
|
+
const threshold = cfg.alertOnPercent ?? 80;
|
|
112
|
+
if (pct >= threshold) {
|
|
113
|
+
notify('token-pilot 预算告警', `本月已用 ${pct.toFixed(0)}%(¥${monthCostCny.toFixed(0)} / ¥${budgetCny})`);
|
|
114
|
+
}
|
|
115
|
+
} else if (cmd === 'month') {
|
|
116
|
+
const today = new Date().getDate();
|
|
117
|
+
const daysInMonth = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate();
|
|
118
|
+
console.log(`\n照这个速度,月底预计:${fmtUsd((agg.cost / today) * daysInMonth)}`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// 同步写 summary(兼容菜单栏旧路径)
|
|
122
|
+
try {
|
|
123
|
+
const todayEvents = allEvents.filter((e) => e.timestamp >= startOfToday());
|
|
124
|
+
const monthEvents = cmd === 'month' ? allEvents : (await collectAll(startOfMonth())).events;
|
|
125
|
+
writeSummary(todayEvents, monthEvents, undefined);
|
|
126
|
+
} catch { /* 不阻塞 */ }
|
|
127
|
+
|
|
128
|
+
if (cmd === 'report' || cmd === 'month') {
|
|
129
|
+
const alerts = detectRetryLoops(allEvents, (m, u) => costOf(m, u));
|
|
130
|
+
if (alerts.length > 0) {
|
|
131
|
+
console.log('\n打转/异常重试检测:');
|
|
132
|
+
for (const a of alerts.slice(0, 5)) {
|
|
133
|
+
console.log(` ⚠️ ${a.agent} · ${a.model} · ${a.calls} 次 · ${fmtUsd(a.totalCostUsd)} — ${a.reason}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const savings = savingsAdvice(allEvents);
|
|
137
|
+
if (savings.length > 0) {
|
|
138
|
+
console.log('\n省钱建议:');
|
|
139
|
+
for (const s of savings) {
|
|
140
|
+
console.log(` 💡 ${s.observation}`);
|
|
141
|
+
console.log(` ${s.suggestion}(约省 ${fmtUsd(s.estimatedSavingsUsdPerMonth)}/月)`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
console.log('');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function cmdSync(): Promise<void> {
|
|
149
|
+
// 单飞:已有 sync 在跑直接退出(菜单栏 60s 定时器叠加 spawn 也不会堆积)
|
|
150
|
+
if (!(await acquireSyncLock())) {
|
|
151
|
+
console.log('已有 sync 在运行,跳过');
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const cfg = loadConfig();
|
|
156
|
+
const fx = fxRate(cfg);
|
|
157
|
+
const pricing = loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fx);
|
|
158
|
+
const { events, contentEvents, detected, parsedFiles, cachedFiles } = await collectCached(0);
|
|
159
|
+
|
|
160
|
+
// 未知模型追踪:定价表+覆写都没有的,记账待补价
|
|
161
|
+
const seen = new Set<string>();
|
|
162
|
+
for (const e of events) {
|
|
163
|
+
if (seen.has(e.model)) continue;
|
|
164
|
+
seen.add(e.model);
|
|
165
|
+
if (!hasKnownPrice(e.model, pricing)) trackUnknown(e.model, e.agent);
|
|
166
|
+
}
|
|
167
|
+
// 每天最多一次自动查价补全
|
|
168
|
+
const fetched = await maybeAutoFetch(fx);
|
|
169
|
+
if (fetched.length > 0) {
|
|
170
|
+
console.log('自动补价(待核对):');
|
|
171
|
+
for (const n of fetched) console.log(` + ${n}`);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const data = await buildDashboardData(events, cfg, loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fx), contentEvents);
|
|
175
|
+
writeDashboardDataFile(data);
|
|
176
|
+
console.log(`token-pilot sync · ${detected.length} 宿主 · 解析 ${parsedFiles} 文件 / 缓存命中 ${cachedFiles}`);
|
|
177
|
+
console.log(`今日:¥${data.hero.today.costCny.toFixed(2)} · ${data.hero.today.calls} 次调用 · 托盘:${data.trayTitle}`);
|
|
178
|
+
} finally {
|
|
179
|
+
await releaseSyncLock();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// 自动补价节流:每天最多一次(状态落盘,跨进程生效)
|
|
184
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
185
|
+
import path from 'node:path';
|
|
186
|
+
import { CONFIG_DIR } from '../core/config.ts';
|
|
187
|
+
const FETCH_STATE = path.join(CONFIG_DIR, 'price-fetch-state.json');
|
|
188
|
+
async function maybeAutoFetch(fx: number): Promise<string[]> {
|
|
189
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
190
|
+
try {
|
|
191
|
+
if (existsSync(FETCH_STATE)) {
|
|
192
|
+
const s = JSON.parse(readFileSync(FETCH_STATE, 'utf8'));
|
|
193
|
+
if (s.lastRun === today) return [];
|
|
194
|
+
}
|
|
195
|
+
} catch { /* 重来 */ }
|
|
196
|
+
const notes = await autoFetchPrices(fx, 3);
|
|
197
|
+
try { writeFileSync(FETCH_STATE, JSON.stringify({ lastRun: today }), 'utf8'); } catch { /* 忽略 */ }
|
|
198
|
+
return notes;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function cmdDash(): Promise<void> {
|
|
202
|
+
const out = await bakeDashboard();
|
|
203
|
+
console.log(`已生成 ${out}`);
|
|
204
|
+
try {
|
|
205
|
+
const { spawn } = await import('node:child_process');
|
|
206
|
+
spawn('open', [out], { detached: true, stdio: 'ignore' }).unref();
|
|
207
|
+
} catch { /* 手动打开 */ }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// 价格核对台:每个在用的模型当前按什么价算、价格从哪来
|
|
211
|
+
function cmdPrices(): void {
|
|
212
|
+
const cfg = loadConfig();
|
|
213
|
+
const fx = fxRate(cfg);
|
|
214
|
+
const pricing = loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fx);
|
|
215
|
+
const unknown = loadUnknown();
|
|
216
|
+
|
|
217
|
+
console.log('\ntoken-pilot · 价格核对台(¥ / 1M tokens)\n');
|
|
218
|
+
console.log(' 模型'.padEnd(34) + '输入'.padStart(8) + '输出'.padStart(8) + '缓存读'.padStart(8) + ' 来源');
|
|
219
|
+
|
|
220
|
+
const rows = new Set<string>([...Object.keys(pricing.models), ...Object.keys(unknown)]);
|
|
221
|
+
const lines: string[] = [];
|
|
222
|
+
for (const m of rows) {
|
|
223
|
+
const p = priceFor(m, pricing);
|
|
224
|
+
const inC = (p.input * fx).toFixed(2);
|
|
225
|
+
const outC = (p.output * fx).toFixed(2);
|
|
226
|
+
const crC = ((p.cacheRead ?? p.input * 0.1) * fx).toFixed(2);
|
|
227
|
+
let src = '目录价';
|
|
228
|
+
if (cfg.priceOverrides?.[m]) src = '人工覆写 ✓';
|
|
229
|
+
else if (unknown[m]?.autoPrice) src = `自动填充·待核对(${unknown[m].source ?? ''})`;
|
|
230
|
+
else if (!hasKnownPrice(m)) src = '⚠️ 无定价,按 fallback 估';
|
|
231
|
+
lines.push(` ${m.padEnd(32)}${inC.padStart(8)}${outC.padStart(8)}${crC.padStart(8)} ${src}`);
|
|
232
|
+
}
|
|
233
|
+
lines.sort().forEach((l) => console.log(l));
|
|
234
|
+
const pending = Object.values(unknown).filter((u) => u.autoPrice && u.needsReview);
|
|
235
|
+
if (pending.length) {
|
|
236
|
+
console.log(`\n ${pending.length} 个自动填充待核对 → 看板「数据设置」里可直接改`);
|
|
237
|
+
}
|
|
238
|
+
console.log('');
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// 压缩潜力报告(CLI 明细版)
|
|
242
|
+
async function cmdCompressReport(): Promise<void> {
|
|
243
|
+
const cfg = loadConfig();
|
|
244
|
+
const fx = fxRate(cfg);
|
|
245
|
+
const pricing = loadPricingWithOverrides({ ...autoOverrides(), ...(cfg.priceOverrides ?? {}) }, fx);
|
|
246
|
+
const { events, contentEvents } = await collectCached(0);
|
|
247
|
+
const { computeCompression } = await import('../core/compression.ts');
|
|
248
|
+
const r = computeCompression(events, contentEvents, pricing);
|
|
249
|
+
console.log('\ntoken-pilot · 压缩潜力报告(本月)\n');
|
|
250
|
+
if (r.itemCount === 0) {
|
|
251
|
+
console.log('未发现明显可压缩的上下文浪费。');
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
console.log(`可压缩空间(估算):$${r.potentialUsd.toFixed(2)} – $${r.potentialUsdMax.toFixed(2)} / 月`);
|
|
255
|
+
console.log(`模式拆分:陈旧 tool 输出 $${r.patterns.stale.toFixed(2)} · 重复读取 $${r.patterns.reread.toFixed(2)} · 超长输出 $${r.patterns.long.toFixed(2)}`);
|
|
256
|
+
console.log('\n最浪费的会话:');
|
|
257
|
+
for (const s of r.sessions) {
|
|
258
|
+
console.log(` ${s.agent} · ${s.key.slice(-16)} · $${s.wasteUsd.toFixed(2)} · ${s.items} 处 · ${s.topPatterns.join('/')}`);
|
|
259
|
+
}
|
|
260
|
+
// 2B:当前活跃会话里该 compact 的
|
|
261
|
+
const { buildDashboardData } = await import('../core/aggregate.ts');
|
|
262
|
+
const data = await buildDashboardData(events, cfg, pricing, contentEvents);
|
|
263
|
+
const hot = data.live.sessions.filter((x) => x.needsCompact);
|
|
264
|
+
if (hot.length) {
|
|
265
|
+
console.log('\n当前该压缩的活跃会话(上下文 >100K,继续在烧):');
|
|
266
|
+
for (const x of hot) {
|
|
267
|
+
console.log(` ${x.agent} · ${x.label.slice(0, 40)} · 上下文 ${Math.round((x.ctxTokens ?? 0) / 1000)}K → 跑 /compact`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
console.log('\n建议:上下文压缩代理可把这部分省下来(规则法已验证 −29%~−48% 输入)。');
|
|
271
|
+
console.log('');
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async function main() {
|
|
275
|
+
const cmd = process.argv[2] ?? 'today';
|
|
276
|
+
if (cmd === 'serve') {
|
|
277
|
+
const port = Number(process.argv[3] ?? 17895);
|
|
278
|
+
await serve(port);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
if (cmd === 'sync') return cmdSync();
|
|
282
|
+
if (cmd === 'dash') return cmdDash();
|
|
283
|
+
if (cmd === 'prices') return cmdPrices();
|
|
284
|
+
if (cmd === 'compress-report') return cmdCompressReport();
|
|
285
|
+
if (cmd === 'today' || cmd === 'month' || cmd === 'report' || cmd === 'all') {
|
|
286
|
+
return cmdReport(cmd === 'all' ? 'all' : cmd);
|
|
287
|
+
}
|
|
288
|
+
console.log('用法:token-pilot [today|month|report|sync|dash|serve]');
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
main().catch((e) => {
|
|
292
|
+
console.error('错误:', e.message);
|
|
293
|
+
process.exit(1);
|
|
294
|
+
});
|