@anthonyhan/token-pilot 0.0.0-stage → 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/README.md +146 -2
- package/bin/token-pilot.js +18 -0
- 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 +30 -3
- package/pricing/models.json +311 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// 系统通知 — macOS 用 osascript,Windows 用 PowerShell toast,零依赖
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
export function notify(title, message) {
|
|
5
|
+
const platform = os.platform();
|
|
6
|
+
try {
|
|
7
|
+
if (platform === 'darwin') {
|
|
8
|
+
const script = `display notification ${JSON.stringify(message)} with title ${JSON.stringify(title)}`;
|
|
9
|
+
const r = spawnSync('osascript', ['-e', script], { stdio: 'ignore' });
|
|
10
|
+
return r.status === 0;
|
|
11
|
+
}
|
|
12
|
+
if (platform === 'win32') {
|
|
13
|
+
// Windows Toast via PowerShell(BurntToast 或基础通知)
|
|
14
|
+
const ps = `
|
|
15
|
+
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
|
|
16
|
+
$t = [Windows.UI.Notifications.ToastTemplateType]::ToastText02
|
|
17
|
+
$x = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent($t)
|
|
18
|
+
$x.SelectSingleNode('//text[@id="1"]').AppendChild($x.CreateTextNode(${JSON.stringify(title)})) | Out-Null
|
|
19
|
+
$x.SelectSingleNode('//text[@id="2"]').AppendChild($x.CreateTextNode(${JSON.stringify(message)})) | Out-Null
|
|
20
|
+
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('token-pilot').Show($x)
|
|
21
|
+
`;
|
|
22
|
+
const r = spawnSync('powershell', ['-NoProfile', '-Command', ps], { stdio: 'ignore' });
|
|
23
|
+
return r.status === 0;
|
|
24
|
+
}
|
|
25
|
+
// linux: notify-send
|
|
26
|
+
const r = spawnSync('notify-send', [title, message], { stdio: 'ignore' });
|
|
27
|
+
return r.status === 0;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// 自动压缩执行层
|
|
2
|
+
// 诚实边界:运行中的会话无法从外部压缩(那需要代理层)。
|
|
3
|
+
// 能做的是:① 经用户明示后写入 Claude Code 的 autoCompactEnabled(影响新会话)
|
|
4
|
+
// ② 超阈值会话发系统通知提醒手动 /compact
|
|
5
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
const CLAUDE_SETTINGS = path.join(os.homedir(), '.claude', 'settings.json');
|
|
9
|
+
// 写入/关闭 Claude Code 的 autoCompactEnabled(用户明示后才调用)
|
|
10
|
+
export function applyClaudeAutoCompact(enabled) {
|
|
11
|
+
try {
|
|
12
|
+
let cfg = {};
|
|
13
|
+
if (existsSync(CLAUDE_SETTINGS)) {
|
|
14
|
+
cfg = JSON.parse(readFileSync(CLAUDE_SETTINGS, 'utf8'));
|
|
15
|
+
}
|
|
16
|
+
cfg.autoCompactEnabled = enabled;
|
|
17
|
+
mkdirSync(path.dirname(CLAUDE_SETTINGS), { recursive: true });
|
|
18
|
+
writeFileSync(CLAUDE_SETTINGS, JSON.stringify(cfg, null, 2) + '\n', 'utf8');
|
|
19
|
+
return {
|
|
20
|
+
ok: true,
|
|
21
|
+
message: enabled
|
|
22
|
+
? '已开启 Claude Code 自动压缩(对之后新开的会话生效;进行中的会话请手动 /compact)'
|
|
23
|
+
: '已关闭 Claude Code 自动压缩',
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
return { ok: false, message: `写入失败:${String(e)}` };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function readClaudeAutoCompact() {
|
|
31
|
+
try {
|
|
32
|
+
if (!existsSync(CLAUDE_SETTINGS))
|
|
33
|
+
return null;
|
|
34
|
+
const cfg = JSON.parse(readFileSync(CLAUDE_SETTINGS, 'utf8'));
|
|
35
|
+
return typeof cfg.autoCompactEnabled === 'boolean' ? cfg.autoCompactEnabled : null;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// 预算引擎 — 月度预算 + 进度 + 超支判定 + 趋势预测
|
|
2
|
+
export function evalBudget(spentUsd, cfg, now = new Date()) {
|
|
3
|
+
const today = now.getDate();
|
|
4
|
+
const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
|
|
5
|
+
const forecastMonthEndUsd = today > 0 ? (spentUsd / today) * daysInMonth : spentUsd;
|
|
6
|
+
return {
|
|
7
|
+
budgetUsd: cfg.monthlyUsd,
|
|
8
|
+
spentUsd,
|
|
9
|
+
remainingUsd: cfg.monthlyUsd - spentUsd,
|
|
10
|
+
percent: cfg.monthlyUsd > 0 ? (spentUsd / cfg.monthlyUsd) * 100 : 0,
|
|
11
|
+
overspent: spentUsd > cfg.monthlyUsd,
|
|
12
|
+
forecastMonthEndUsd,
|
|
13
|
+
forecastOverspend: forecastMonthEndUsd > cfg.monthlyUsd,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
// 预算进度条(文本版,给 CLI 用)
|
|
17
|
+
export function progressBar(percent, width = 20) {
|
|
18
|
+
const clamped = Math.min(percent, 100);
|
|
19
|
+
const filled = Math.round((clamped / 100) * width);
|
|
20
|
+
const bar = '█'.repeat(filled) + '░'.repeat(width - filled);
|
|
21
|
+
const mark = percent > 100 ? ' ⚠️ 超支' : percent > 80 ? ' ⚠️ 接近上限' : '';
|
|
22
|
+
return `${bar} ${percent.toFixed(0)}%${mark}`;
|
|
23
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// 采集器 — 磁盘增量缓存 + 单飞锁
|
|
2
|
+
//
|
|
3
|
+
// 卡死教训:CLI sync 每次冷启动全量扫 ~2GB 日志(实测 7s 满 CPU),
|
|
4
|
+
// 菜单栏 60s 定时器叠加 spawn → 多进程堆积 → IO/CPU 雪崩。
|
|
5
|
+
// 修复:
|
|
6
|
+
// 1. 磁盘缓存 events-cache.json——文件 mtime 没变就复用缓存事件,只重解析变化的文件
|
|
7
|
+
// 2. 单飞锁 sync.lock——已有 sync 在跑就直接跳过
|
|
8
|
+
// 3. 缓存窗口 40 天(看板最远用到近 30 天 + 本月)
|
|
9
|
+
import { promises as fs } from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { claudeCodeAdapter } from '../adapters/claude-code.js';
|
|
12
|
+
import { codexAdapter } from '../adapters/codex.js';
|
|
13
|
+
import { kimiCodeAdapter } from '../adapters/kimi-code.js';
|
|
14
|
+
import { opencodeAdapter } from '../adapters/opencode.js';
|
|
15
|
+
import { piAdapter } from '../adapters/pi.js';
|
|
16
|
+
import { volcArkAdapter } from '../adapters/volc-ark.js';
|
|
17
|
+
import { dshAdapter } from '../adapters/dsh.js';
|
|
18
|
+
import { workbuddyAdapter, workbuddyAiAdapter } from '../adapters/workbuddy.js';
|
|
19
|
+
import { CONFIG_DIR } from './config.js';
|
|
20
|
+
export const ALL_ADAPTERS = [claudeCodeAdapter, codexAdapter, kimiCodeAdapter, opencodeAdapter, piAdapter, volcArkAdapter, dshAdapter, workbuddyAdapter, workbuddyAiAdapter];
|
|
21
|
+
const CACHE_PATH = path.join(CONFIG_DIR, 'events-cache.json');
|
|
22
|
+
const LOCK_PATH = path.join(CONFIG_DIR, 'sync.lock');
|
|
23
|
+
const WINDOW_MS = 40 * 86400_000;
|
|
24
|
+
const LOCK_TTL_MS = 120_000;
|
|
25
|
+
// ---------- 单飞锁 ----------
|
|
26
|
+
export async function acquireSyncLock() {
|
|
27
|
+
try {
|
|
28
|
+
const raw = await fs.readFile(LOCK_PATH, 'utf8');
|
|
29
|
+
const lock = JSON.parse(raw);
|
|
30
|
+
const fresh = typeof lock.ts === 'number' && Date.now() - lock.ts < LOCK_TTL_MS;
|
|
31
|
+
if (fresh && typeof lock.pid === 'number') {
|
|
32
|
+
try {
|
|
33
|
+
process.kill(lock.pid, 0); // 进程还在
|
|
34
|
+
return false; // 有人在跑,跳过
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// 进程死了,锁是僵尸,接管
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
// 无锁文件
|
|
43
|
+
}
|
|
44
|
+
await fs.mkdir(CONFIG_DIR, { recursive: true });
|
|
45
|
+
await fs.writeFile(LOCK_PATH, JSON.stringify({ pid: process.pid, ts: Date.now() }), 'utf8');
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
export async function releaseSyncLock() {
|
|
49
|
+
try {
|
|
50
|
+
await fs.unlink(LOCK_PATH);
|
|
51
|
+
}
|
|
52
|
+
catch { /* 已不在 */ }
|
|
53
|
+
}
|
|
54
|
+
async function loadCache() {
|
|
55
|
+
try {
|
|
56
|
+
const raw = await fs.readFile(CACHE_PATH, 'utf8');
|
|
57
|
+
const c = JSON.parse(raw);
|
|
58
|
+
if (c.version === 2 && c.files)
|
|
59
|
+
return c;
|
|
60
|
+
}
|
|
61
|
+
catch { /* 无缓存 */ }
|
|
62
|
+
return { version: 2, files: {} };
|
|
63
|
+
}
|
|
64
|
+
async function saveCache(cache) {
|
|
65
|
+
await fs.mkdir(CONFIG_DIR, { recursive: true });
|
|
66
|
+
const tmp = CACHE_PATH + '.tmp';
|
|
67
|
+
await fs.writeFile(tmp, JSON.stringify(cache), 'utf8');
|
|
68
|
+
await fs.rename(tmp, CACHE_PATH);
|
|
69
|
+
}
|
|
70
|
+
// 带缓存的采集:mtime 不变的文件直接复用缓存事件
|
|
71
|
+
export async function collectCached(sinceMs = 0) {
|
|
72
|
+
const cache = await loadCache();
|
|
73
|
+
const windowStart = Math.max(sinceMs, Date.now() - WINDOW_MS);
|
|
74
|
+
const nextFiles = {};
|
|
75
|
+
const detected = [];
|
|
76
|
+
let parsed = 0;
|
|
77
|
+
let cached = 0;
|
|
78
|
+
for (const ad of ALL_ADAPTERS) {
|
|
79
|
+
if (!(await ad.detect()))
|
|
80
|
+
continue;
|
|
81
|
+
detected.push(ad.meta.displayName);
|
|
82
|
+
if (ad.listFiles && ad.readFileEvents) {
|
|
83
|
+
let files = [];
|
|
84
|
+
try {
|
|
85
|
+
files = await ad.listFiles();
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
await Promise.all(files.map(async (f) => {
|
|
91
|
+
let mtime = 0;
|
|
92
|
+
try {
|
|
93
|
+
mtime = (await fs.stat(f)).mtimeMs;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const prev = cache.files[f];
|
|
99
|
+
if (prev && prev.adapter === ad.meta.id && prev.mtime === mtime) {
|
|
100
|
+
nextFiles[f] = prev;
|
|
101
|
+
cached++;
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const events = await ad.readFileEvents(f, windowStart);
|
|
105
|
+
// 内容流(压缩潜力用):有能力的 adapter 顺手采,只取尺寸不落内容
|
|
106
|
+
let contentEv;
|
|
107
|
+
if (ad.readFileContentEvents) {
|
|
108
|
+
try {
|
|
109
|
+
contentEv = await ad.readFileContentEvents(f, windowStart);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
contentEv = undefined;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
nextFiles[f] = { mtime, adapter: ad.meta.id, events, content: contentEv };
|
|
116
|
+
parsed++;
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
// 无文件级能力的 adapter:全量读(目前没有这种)
|
|
121
|
+
try {
|
|
122
|
+
const events = await ad.readEvents(windowStart);
|
|
123
|
+
nextFiles[`__whole__:${ad.meta.id}`] = { mtime: Date.now(), adapter: ad.meta.id, events };
|
|
124
|
+
}
|
|
125
|
+
catch { /* 单 adapter 失败不阻塞 */ }
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
// 合并 + 按 agent:eventId 去重(取 totalTokens 最大,防流式快照残留)+ 窗口过滤
|
|
129
|
+
const contentAll = [];
|
|
130
|
+
const byId = new Map();
|
|
131
|
+
for (const entry of Object.values(nextFiles)) {
|
|
132
|
+
if (entry.content) {
|
|
133
|
+
for (const c of entry.content)
|
|
134
|
+
if (c.timestamp >= sinceMs)
|
|
135
|
+
contentAll.push(c);
|
|
136
|
+
}
|
|
137
|
+
for (const e of entry.events) {
|
|
138
|
+
if (e.timestamp < sinceMs)
|
|
139
|
+
continue;
|
|
140
|
+
const key = `${e.agent}:${e.eventId}`;
|
|
141
|
+
const prev = byId.get(key);
|
|
142
|
+
if (!prev || e.usage.totalTokens > prev.usage.totalTokens)
|
|
143
|
+
byId.set(key, e);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
// 写缓存(下次 sync 提速)
|
|
147
|
+
try {
|
|
148
|
+
await saveCache({ version: 2, files: nextFiles });
|
|
149
|
+
}
|
|
150
|
+
catch { /* 缓存失败不阻塞 */ }
|
|
151
|
+
return { events: [...byId.values()], contentEvents: contentAll, detected, parsedFiles: parsed, cachedFiles: cached };
|
|
152
|
+
}
|
|
153
|
+
// 无缓存全量(today/month/report 命令的直读路径)
|
|
154
|
+
export async function collectAll(sinceMs = 0) {
|
|
155
|
+
const all = [];
|
|
156
|
+
const contentAll = [];
|
|
157
|
+
const detected = [];
|
|
158
|
+
for (const ad of ALL_ADAPTERS) {
|
|
159
|
+
if (!(await ad.detect()))
|
|
160
|
+
continue;
|
|
161
|
+
detected.push(ad.meta.displayName);
|
|
162
|
+
try {
|
|
163
|
+
all.push(...(await ad.readEvents(sinceMs)));
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
// 单 adapter 失败不阻塞整体
|
|
167
|
+
}
|
|
168
|
+
if (ad.listFiles && ad.readFileContentEvents) {
|
|
169
|
+
try {
|
|
170
|
+
for (const f of await ad.listFiles()) {
|
|
171
|
+
try {
|
|
172
|
+
const st = await fs.stat(f);
|
|
173
|
+
if (st.mtimeMs < sinceMs)
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
contentAll.push(...(await ad.readFileContentEvents(f, sinceMs)));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
catch { /* 忽略 */ }
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return { events: all, contentEvents: contentAll, detected };
|
|
186
|
+
}
|
|
187
|
+
// 常驻内存增量采集器(serve 用):启动走磁盘缓存,之后内存增量合并,全量降频 30min
|
|
188
|
+
export class Collector {
|
|
189
|
+
byId = new Map();
|
|
190
|
+
lastFull = 0;
|
|
191
|
+
async sync() {
|
|
192
|
+
const now = Date.now();
|
|
193
|
+
const wantFull = this.byId.size === 0 || now - this.lastFull > 30 * 60_000;
|
|
194
|
+
// 全量分支抢锁:CLI sync 在跑就让路,退化为增量,绝不叠加全量扫描
|
|
195
|
+
if (wantFull && (await acquireSyncLock())) {
|
|
196
|
+
try {
|
|
197
|
+
const { events, contentEvents, detected } = await collectCached(0);
|
|
198
|
+
this.byId = new Map(events.map((e) => [`${e.agent}:${e.eventId}`, e]));
|
|
199
|
+
this.lastFull = now;
|
|
200
|
+
return { events, contentEvents, detected };
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
await releaseSyncLock();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const since = now - 3 * 60_000; // 增量窗口留 3 分钟重叠
|
|
207
|
+
const { events, contentEvents, detected } = await collectAll(since);
|
|
208
|
+
for (const e of events) {
|
|
209
|
+
this.byId.set(`${e.agent}:${e.eventId}`, e);
|
|
210
|
+
}
|
|
211
|
+
return { events: [...this.byId.values()], contentEvents, detected };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// 压缩潜力量化引擎 — 纯规则,零外部依赖
|
|
2
|
+
// 原理:agent 每轮把整个会话历史重发给模型。陈旧 tool 输出/重复读取/超长输出
|
|
3
|
+
// 在每轮都被计费——把它们的「体积 × 存活轮数 × 单价」算出来,就是压缩能省的钱。
|
|
4
|
+
// 红线:只用量尺寸,不读内容。
|
|
5
|
+
import { priceFor } from './pricing.js';
|
|
6
|
+
const BYTES_PER_TOKEN = 4; // 英文代码口径的经验值
|
|
7
|
+
export function computeCompression(events, contentEvents, pricing, opts = {}) {
|
|
8
|
+
const K = opts.staleTurnsK ?? 5;
|
|
9
|
+
const LONG = (opts.longOutputKb ?? 10) * 1024;
|
|
10
|
+
const KEEP = opts.keepRatio ?? 0.15;
|
|
11
|
+
const KEEP_MIN = 0.10;
|
|
12
|
+
// 每会话:usage 事件时间序列(turn 序列)+ 主导模型
|
|
13
|
+
const sessionTurns = new Map();
|
|
14
|
+
const sessionModel = new Map();
|
|
15
|
+
const sessionAgent = new Map();
|
|
16
|
+
for (const e of events) {
|
|
17
|
+
const key = `${e.agent}:${e.sessionId}`;
|
|
18
|
+
const arr = sessionTurns.get(key) ?? [];
|
|
19
|
+
arr.push(e.timestamp);
|
|
20
|
+
sessionTurns.set(key, arr);
|
|
21
|
+
sessionModel.set(key, e.model);
|
|
22
|
+
sessionAgent.set(key, e.agent);
|
|
23
|
+
}
|
|
24
|
+
for (const arr of sessionTurns.values())
|
|
25
|
+
arr.sort((a, b) => a - b);
|
|
26
|
+
// 每会话 tool_use 序列(重复读取检测用 targetPath)
|
|
27
|
+
const sessionUses = new Map();
|
|
28
|
+
const results = [];
|
|
29
|
+
for (const c of contentEvents) {
|
|
30
|
+
const key = `${c.agent}:${c.sessionId}`;
|
|
31
|
+
if (c.kind === 'tool_result') {
|
|
32
|
+
results.push(c);
|
|
33
|
+
}
|
|
34
|
+
else if (c.targetPath) {
|
|
35
|
+
const arr = sessionUses.get(key) ?? [];
|
|
36
|
+
arr.push(c);
|
|
37
|
+
sessionUses.set(key, arr);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
// 每个会话的单价(主导模型 input 价,USD/token)
|
|
41
|
+
function pricePerTok(sessionKey) {
|
|
42
|
+
const model = sessionModel.get(sessionKey) ?? '';
|
|
43
|
+
const p = priceFor(model, pricing);
|
|
44
|
+
return p.input / 1_000_000;
|
|
45
|
+
}
|
|
46
|
+
const patterns = { stale: 0, reread: 0, long: 0 };
|
|
47
|
+
const sessionWaste = new Map();
|
|
48
|
+
let itemCount = 0;
|
|
49
|
+
function addWaste(key, usd, usdMax, pat) {
|
|
50
|
+
if (usd <= 0)
|
|
51
|
+
return;
|
|
52
|
+
itemCount++;
|
|
53
|
+
patterns[pat] += usd;
|
|
54
|
+
const s = sessionWaste.get(key) ?? { waste: 0, items: 0, pats: new Set() };
|
|
55
|
+
s.waste += usd;
|
|
56
|
+
s.items++;
|
|
57
|
+
s.pats.add(pat);
|
|
58
|
+
sessionWaste.set(key, s);
|
|
59
|
+
void usdMax;
|
|
60
|
+
}
|
|
61
|
+
// W1/W3:tool_result 的陈旧与超长
|
|
62
|
+
for (const r of results) {
|
|
63
|
+
const key = `${r.agent}:${r.sessionId}`;
|
|
64
|
+
const turns = sessionTurns.get(key);
|
|
65
|
+
if (!turns || turns.length === 0)
|
|
66
|
+
continue;
|
|
67
|
+
// 该结果之后还有多少轮调用(它被重发的次数)
|
|
68
|
+
let after = 0;
|
|
69
|
+
for (const t of turns)
|
|
70
|
+
if (t > r.timestamp)
|
|
71
|
+
after++;
|
|
72
|
+
const tok = r.sizeBytes / BYTES_PER_TOKEN;
|
|
73
|
+
const price = pricePerTok(key);
|
|
74
|
+
const wastes = [];
|
|
75
|
+
// W1 陈旧:K 轮之后还在重发的部分
|
|
76
|
+
if (after > K) {
|
|
77
|
+
wastes.push({ pat: 'stale', usd: tok * (1 - KEEP) * (after - K) * price });
|
|
78
|
+
}
|
|
79
|
+
// W3 超长:超出 2KB 的部分在存活轮内的重发(不要求超过 K 轮——长输出第一次重发就浪费)
|
|
80
|
+
if (r.sizeBytes > LONG) {
|
|
81
|
+
const excessTok = (r.sizeBytes - 2048) / BYTES_PER_TOKEN;
|
|
82
|
+
wastes.push({ pat: 'long', usd: excessTok * (1 - KEEP) * Math.max(after, 1) * price });
|
|
83
|
+
}
|
|
84
|
+
// 同一项取最大,不叠加(防重复计)
|
|
85
|
+
if (wastes.length) {
|
|
86
|
+
const best = wastes.sort((a, b) => b.usd - a.usd)[0];
|
|
87
|
+
const maxUsd = best.pat === 'stale'
|
|
88
|
+
? tok * (1 - KEEP_MIN) * (after - 3) * price
|
|
89
|
+
: ((r.sizeBytes - 2048) / BYTES_PER_TOKEN) * (1 - KEEP_MIN) * Math.max(after, 1) * price;
|
|
90
|
+
addWaste(key, best.usd, maxUsd, best.pat);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// W2:同会话同路径重复读取(前 N−1 次的结果冗余)
|
|
94
|
+
for (const [key, uses] of sessionUses) {
|
|
95
|
+
const byPath = new Map();
|
|
96
|
+
for (const u of uses) {
|
|
97
|
+
const arr = byPath.get(u.targetPath) ?? [];
|
|
98
|
+
arr.push(u);
|
|
99
|
+
byPath.set(u.targetPath, arr);
|
|
100
|
+
}
|
|
101
|
+
const price = pricePerTok(key);
|
|
102
|
+
for (const [, reads] of byPath) {
|
|
103
|
+
if (reads.length < 2)
|
|
104
|
+
continue;
|
|
105
|
+
reads.sort((a, b) => a.timestamp - b.timestamp);
|
|
106
|
+
// 前 N−1 次读取的 tool_use 体积冗余(最后一次才是有效上下文)
|
|
107
|
+
for (let i = 0; i < reads.length - 1; i++) {
|
|
108
|
+
const tok = reads[i].sizeBytes / BYTES_PER_TOKEN;
|
|
109
|
+
// 该次读取的 result 存活到下一次读取为止
|
|
110
|
+
const aliveTurns = Math.max(1, Math.round((reads[i + 1].timestamp - reads[i].timestamp) / 60_000));
|
|
111
|
+
addWaste(key, tok * (1 - KEEP) * aliveTurns * price, tok * (1 - KEEP_MIN) * aliveTurns * price, 'reread');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const sessions = [...sessionWaste.entries()]
|
|
116
|
+
.map(([key, s]) => ({
|
|
117
|
+
key,
|
|
118
|
+
agent: sessionAgent.get(key) ?? '',
|
|
119
|
+
wasteUsd: s.waste,
|
|
120
|
+
items: s.items,
|
|
121
|
+
topPatterns: [...s.pats],
|
|
122
|
+
}))
|
|
123
|
+
.sort((a, b) => b.wasteUsd - a.wasteUsd)
|
|
124
|
+
.slice(0, 5);
|
|
125
|
+
const potentialUsd = patterns.stale + patterns.reread + patterns.long;
|
|
126
|
+
// 口径B(上限):同一组数据用 K=3 / keep 10% 重算一轮太贵,这里按系数近似(保守 1.5×)
|
|
127
|
+
const potentialUsdMax = potentialUsd * 1.5;
|
|
128
|
+
return { potentialUsd, potentialUsdMax, itemCount, patterns, sessions };
|
|
129
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// 配置加载/保存 — ~/.token-pilot/config.json,环境变量优先
|
|
2
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
export const CONFIG_DIR = path.join(os.homedir(), '.token-pilot');
|
|
6
|
+
export const CONFIG_PATH = path.join(CONFIG_DIR, 'config.json');
|
|
7
|
+
export const DATA_PATH = path.join(CONFIG_DIR, 'dashboard-data.json');
|
|
8
|
+
export function loadConfig() {
|
|
9
|
+
// 环境变量优先
|
|
10
|
+
if (process.env.TOKEN_PILOT_MONTHLY_BUDGET_USD) {
|
|
11
|
+
return {
|
|
12
|
+
monthlyBudgetUsd: Number(process.env.TOKEN_PILOT_MONTHLY_BUDGET_USD),
|
|
13
|
+
usdToCny: Number(process.env.TOKEN_PILOT_USD_TO_CNY ?? 7.2),
|
|
14
|
+
alertOnPercent: Number(process.env.TOKEN_PILOT_ALERT_ON_PERCENT ?? 80),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
if (existsSync(CONFIG_PATH)) {
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return {};
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
export function saveConfig(cfg) {
|
|
28
|
+
mkdirSync(CONFIG_DIR, { recursive: true });
|
|
29
|
+
writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2) + '\n', 'utf8');
|
|
30
|
+
}
|
|
31
|
+
export function fxRate(cfg) {
|
|
32
|
+
return cfg.usdToCny && cfg.usdToCny > 0 ? cfg.usdToCny : 7.2;
|
|
33
|
+
}
|
|
34
|
+
// 月度预算统一折算成 CNY;未设置返回 undefined
|
|
35
|
+
export function monthlyBudgetCny(cfg) {
|
|
36
|
+
if (cfg.monthlyBudgetCny && cfg.monthlyBudgetCny > 0)
|
|
37
|
+
return cfg.monthlyBudgetCny;
|
|
38
|
+
if (cfg.monthlyBudgetUsd && cfg.monthlyBudgetUsd > 0)
|
|
39
|
+
return cfg.monthlyBudgetUsd * fxRate(cfg);
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// 写 metrics-summary.json 给菜单栏/看板读
|
|
2
|
+
// 学 LoongSuite Pilot:dataDir/logs/metrics-summary.json
|
|
3
|
+
import { writeFileSync, mkdirSync, readFileSync, existsSync } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import { costOf } from './pricing.js';
|
|
7
|
+
const DATA_DIR = path.join(os.homedir(), '.token-pilot');
|
|
8
|
+
const SUMMARY_PATH = path.join(DATA_DIR, 'metrics-summary.json');
|
|
9
|
+
export function summaryPath() {
|
|
10
|
+
return SUMMARY_PATH;
|
|
11
|
+
}
|
|
12
|
+
export function writeSummary(todayEvents, monthEvents, budget) {
|
|
13
|
+
function agg(evs) {
|
|
14
|
+
let tokens = 0, costUsd = 0;
|
|
15
|
+
for (const e of evs) {
|
|
16
|
+
tokens += e.usage.totalTokens;
|
|
17
|
+
costUsd += costOf(e.model, e.usage, undefined, e.timestamp).totalUsd;
|
|
18
|
+
}
|
|
19
|
+
return { tokens, costUsd, events: evs.length };
|
|
20
|
+
}
|
|
21
|
+
function group(evs, key) {
|
|
22
|
+
const m = {};
|
|
23
|
+
for (const e of evs) {
|
|
24
|
+
const k = key === 'agent' ? e.agent : e.model;
|
|
25
|
+
const c = m[k] ?? { tokens: 0, costUsd: 0 };
|
|
26
|
+
c.tokens += e.usage.totalTokens;
|
|
27
|
+
c.costUsd += costOf(e.model, e.usage, undefined, e.timestamp).totalUsd;
|
|
28
|
+
m[k] = c;
|
|
29
|
+
}
|
|
30
|
+
return m;
|
|
31
|
+
}
|
|
32
|
+
const summary = {
|
|
33
|
+
updatedAt: new Date().toISOString(),
|
|
34
|
+
today: agg(todayEvents),
|
|
35
|
+
month: agg(monthEvents),
|
|
36
|
+
budget,
|
|
37
|
+
byAgent: group(monthEvents, 'agent'),
|
|
38
|
+
byModel: group(monthEvents, 'model'),
|
|
39
|
+
};
|
|
40
|
+
mkdirSync(DATA_DIR, { recursive: true });
|
|
41
|
+
writeFileSync(SUMMARY_PATH, JSON.stringify(summary, null, 2));
|
|
42
|
+
return SUMMARY_PATH;
|
|
43
|
+
}
|
|
44
|
+
export function readSummary() {
|
|
45
|
+
if (!existsSync(SUMMARY_PATH))
|
|
46
|
+
return null;
|
|
47
|
+
try {
|
|
48
|
+
return JSON.parse(readFileSync(SUMMARY_PATH, 'utf8'));
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// 自动补价 — 对采集到但定价表缺失的模型,每天最多一次去网络查公开目录价
|
|
2
|
+
// 策略:按 provider 找官方定价页 → r.jina.ai 读成文本 → 在模型名附近抓价格数字
|
|
3
|
+
// 所有自动填充都标记 needsReview,人工可在看板「数据设置」里核对修改。
|
|
4
|
+
import { loadUnknown, markPriced, markFailed, saveUnknown } from './unknown-models.js';
|
|
5
|
+
const PROVIDER_PRICE_PAGES = {
|
|
6
|
+
anthropic: 'https://claude.com/pricing#api',
|
|
7
|
+
openai: 'https://developers.openai.com/api/docs/pricing',
|
|
8
|
+
deepseek: 'https://api-docs.deepseek.com/zh-cn/quick_start/pricing/',
|
|
9
|
+
glm: 'https://docs.bigmodel.cn/cn/guide/start/pricing',
|
|
10
|
+
kimi: 'https://platform.kimi.com/docs/pricing/chat',
|
|
11
|
+
qwen: 'https://help.aliyun.com/zh/model-studio/models',
|
|
12
|
+
doubao: 'https://www.volcengine.com/docs/82379/1099320',
|
|
13
|
+
minimax: 'https://platform.minimax.cn/docs/pricing/overview',
|
|
14
|
+
hunyuan: 'https://cloud.tencent.com/document/product/1729/97731',
|
|
15
|
+
grok: 'https://grok.cadn.net.cn/docs_cn/models.html',
|
|
16
|
+
mimo: 'https://mimo.mi.com/docs/zh-CN/price/pay-as-you-go',
|
|
17
|
+
longcat: 'https://longcat.chat/platform/docs/zh/api-pay-as-you-go',
|
|
18
|
+
gemini: 'https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing?hl=zh-CN',
|
|
19
|
+
};
|
|
20
|
+
function providerFromModel(model) {
|
|
21
|
+
const m = model.toLowerCase();
|
|
22
|
+
if (m.includes('claude'))
|
|
23
|
+
return 'anthropic';
|
|
24
|
+
if (m.includes('gpt') || m.includes('o4') || m.includes('codex'))
|
|
25
|
+
return 'openai';
|
|
26
|
+
if (m.includes('deepseek'))
|
|
27
|
+
return 'deepseek';
|
|
28
|
+
if (m.includes('glm'))
|
|
29
|
+
return 'glm';
|
|
30
|
+
if (m.includes('kimi'))
|
|
31
|
+
return 'kimi';
|
|
32
|
+
if (m.includes('qwen'))
|
|
33
|
+
return 'qwen';
|
|
34
|
+
if (m.includes('doubao') || m.includes('seed'))
|
|
35
|
+
return 'doubao';
|
|
36
|
+
if (m.includes('minimax'))
|
|
37
|
+
return 'minimax';
|
|
38
|
+
if (m.includes('hunyuan'))
|
|
39
|
+
return 'hunyuan';
|
|
40
|
+
if (m.includes('gemini') || m.includes('google/'))
|
|
41
|
+
return 'google';
|
|
42
|
+
return '';
|
|
43
|
+
}
|
|
44
|
+
// 从定价页文本里抓模型名附近的价格($/1M 或 ¥/1M 都试)
|
|
45
|
+
function extractPrices(text, model) {
|
|
46
|
+
const idx = text.toLowerCase().indexOf(model.toLowerCase());
|
|
47
|
+
if (idx < 0)
|
|
48
|
+
return null;
|
|
49
|
+
// 取模型名前后 800 字符窗口
|
|
50
|
+
const win = text.slice(Math.max(0, idx - 400), idx + 800);
|
|
51
|
+
// 价格形态:$3.00 / $0.15 / 3.00 / ¥2 / 0.5 元
|
|
52
|
+
const nums = [...win.matchAll(/[$¥]?\s*(\d+(?:\.\d+)?)\s*(?:USD|美元|元|\/1M|\/ 1M|per 1M|\/MTok)?/g)]
|
|
53
|
+
.map((m) => parseFloat(m[1]))
|
|
54
|
+
.filter((n) => n > 0.001 && n < 10000);
|
|
55
|
+
if (nums.length < 2)
|
|
56
|
+
return null;
|
|
57
|
+
// 粗规则:窗口里最小的两个正数大概率是 input/output(output >= input 更常见)
|
|
58
|
+
nums.sort((a, b) => a - b);
|
|
59
|
+
const input = nums[0];
|
|
60
|
+
const output = nums.length > 1 ? nums[1] : nums[0] * 3;
|
|
61
|
+
const cny = win.includes('¥') || win.includes('元') || win.includes('人民币');
|
|
62
|
+
return { input, output, cny };
|
|
63
|
+
}
|
|
64
|
+
async function fetchPricePage(url) {
|
|
65
|
+
try {
|
|
66
|
+
const r = await fetch(`https://r.jina.ai/${url}`, { signal: AbortSignal.timeout(20_000) });
|
|
67
|
+
if (!r.ok)
|
|
68
|
+
return null;
|
|
69
|
+
return await r.text();
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
// 对 unknown-models 里待补价的模型逐个查价(每次最多 3 个,失败记数)
|
|
76
|
+
export async function autoFetchPrices(usdToCny, maxPerRun = 3) {
|
|
77
|
+
const state = loadUnknown();
|
|
78
|
+
const notes = [];
|
|
79
|
+
const candidates = Object.values(state)
|
|
80
|
+
.filter((u) => !u.autoPrice && (u.failedAttempts ?? 0) < 3)
|
|
81
|
+
.sort((a, b) => b.calls - a.calls)
|
|
82
|
+
.slice(0, maxPerRun);
|
|
83
|
+
for (const u of candidates) {
|
|
84
|
+
const prov = providerFromModel(u.model);
|
|
85
|
+
const page = PROVIDER_PRICE_PAGES[prov];
|
|
86
|
+
if (!page) {
|
|
87
|
+
markFailed(u.model);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const text = await fetchPricePage(page);
|
|
91
|
+
if (!text) {
|
|
92
|
+
markFailed(u.model);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const got = extractPrices(text, u.model);
|
|
96
|
+
if (!got) {
|
|
97
|
+
markFailed(u.model);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
// 统一存 ¥/1M
|
|
101
|
+
const price = got.cny
|
|
102
|
+
? { input: got.input, output: got.output }
|
|
103
|
+
: { input: got.input * usdToCny, output: got.output * usdToCny };
|
|
104
|
+
markPriced(u.model, price, page);
|
|
105
|
+
notes.push(`${u.model}: ¥${price.input.toFixed(2)}/¥${price.output.toFixed(2)}(来源 ${page},待核对)`);
|
|
106
|
+
}
|
|
107
|
+
return notes;
|
|
108
|
+
}
|
|
109
|
+
// 把已补价的模型合并进配置的价格覆写(auto 标记保留在 unknown-models.json 里供前端标注)
|
|
110
|
+
export function autoOverrides() {
|
|
111
|
+
const state = loadUnknown();
|
|
112
|
+
const out = {};
|
|
113
|
+
for (const u of Object.values(state)) {
|
|
114
|
+
if (u.autoPrice)
|
|
115
|
+
out[u.model] = u.autoPrice;
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
export function reviewInfo() {
|
|
120
|
+
const state = loadUnknown();
|
|
121
|
+
const out = {};
|
|
122
|
+
for (const [k, u] of Object.entries(state)) {
|
|
123
|
+
if (u.autoPrice)
|
|
124
|
+
out[k] = u;
|
|
125
|
+
}
|
|
126
|
+
void saveUnknown;
|
|
127
|
+
return out;
|
|
128
|
+
}
|