modelpace 0.0.0-stage → 0.1.0
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/AGENTS.md +147 -0
- package/CHANGELOG.md +14 -0
- package/LICENSE +21 -0
- package/README.md +216 -2
- package/README.zh-CN.md +198 -0
- package/SECURITY.md +16 -0
- package/bin/modelpace-mcp.mjs +337 -0
- package/bin/modelpace.mjs +383 -0
- package/docs/SCHEMA.md +170 -0
- package/examples/multi-account.config.json +168 -0
- package/examples/multi-account.snapshot.json +227 -0
- package/examples/record.example.json +23 -0
- package/examples/sample-snapshot.json +173 -0
- package/llms.txt +26 -0
- package/package.json +56 -4
- package/skills/modelpace/SKILL.md +82 -0
- package/src/adapters/json-snapshot.mjs +360 -0
- package/src/adapters/t3-auto.mjs +160 -0
- package/src/adapters/t3-config.mjs +337 -0
- package/src/adapters/t3-rpc.mjs +275 -0
- package/src/context.mjs +73 -0
- package/src/core/decide.mjs +435 -0
- package/src/core/pacing.mjs +569 -0
- package/src/core/policy.mjs +252 -0
- package/src/core/scores.mjs +491 -0
- package/src/index.mjs +48 -0
- package/src/speed/collect.mjs +47 -0
- package/src/speed/histogram.mjs +170 -0
- package/src/speed/scanner.mjs +390 -0
- package/src/ui/client.js +522 -0
- package/src/ui/dashboard.css +106 -0
- package/src/ui/dashboard.mjs +150 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { DEFAULT_SCORING_CONFIG, dispatchSucceeded } from '../core/scores.mjs';
|
|
2
|
+
|
|
3
|
+
// 稀疏对数直方图:相邻桶比 1.02,中位数误差不超过 1%。
|
|
4
|
+
export const BIN_RATIO = 1.02;
|
|
5
|
+
export const BIN_OFFSET = 200;
|
|
6
|
+
|
|
7
|
+
export const SPEED_MIN_OUTPUT_TOKENS = 100;
|
|
8
|
+
export const SPEED_LONG_OUTPUT_TOKENS = 1000;
|
|
9
|
+
export const SPEED_SHORT_MAX_OUTPUT_TOKENS = 300;
|
|
10
|
+
export const SPEED_LOW_SAMPLE_LONG_REQUESTS = 20;
|
|
11
|
+
const MIN_REQUEST_SECONDS = 0.5;
|
|
12
|
+
const MAX_REQUEST_SECONDS = 900;
|
|
13
|
+
|
|
14
|
+
/** 输出过短或耗时过短、过长的请求没有速度意义,返回 null。 */
|
|
15
|
+
export function speedSample(outputTokens, startMs, endMs) {
|
|
16
|
+
const seconds = (endMs - startMs) / 1000;
|
|
17
|
+
if (
|
|
18
|
+
!(outputTokens >= SPEED_MIN_OUTPUT_TOKENS) ||
|
|
19
|
+
!(seconds > MIN_REQUEST_SECONDS) ||
|
|
20
|
+
!(seconds < MAX_REQUEST_SECONDS)
|
|
21
|
+
) {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
return { outputTokens, seconds, tokensPerSecond: outputTokens / seconds };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const speedBin = (value) => Math.max(0, Math.round(Math.log(value) / Math.log(BIN_RATIO)) + BIN_OFFSET);
|
|
28
|
+
const binValue = (bin) => BIN_RATIO ** (bin - BIN_OFFSET);
|
|
29
|
+
|
|
30
|
+
export function addToBins(bins, value) {
|
|
31
|
+
const bin = speedBin(value);
|
|
32
|
+
bins.set(bin, (bins.get(bin) ?? 0) + 1);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function addPairsToBins(bins, pairs) {
|
|
36
|
+
for (let index = 0; index + 1 < pairs.length; index += 2) {
|
|
37
|
+
bins.set(pairs[index], (bins.get(pairs[index]) ?? 0) + pairs[index + 1]);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 稀疏直方图序列化为 [bin, count, bin, count, ...]。 */
|
|
42
|
+
export const binsToPairs = (bins) => [...bins].sort(([a], [b]) => a - b).flat();
|
|
43
|
+
|
|
44
|
+
const binsCount = (bins) => [...bins.values()].reduce((sum, value) => sum + value, 0);
|
|
45
|
+
|
|
46
|
+
export function binsMedian(bins) {
|
|
47
|
+
const sorted = [...bins].sort(([a], [b]) => a - b);
|
|
48
|
+
const total = binsCount(bins);
|
|
49
|
+
if (total === 0) return null;
|
|
50
|
+
const at = (rank) => {
|
|
51
|
+
let seen = 0;
|
|
52
|
+
for (const [bin, count] of sorted) {
|
|
53
|
+
seen += count;
|
|
54
|
+
if (rank < seen) return binValue(bin);
|
|
55
|
+
}
|
|
56
|
+
return binValue(sorted.at(-1)[0]);
|
|
57
|
+
};
|
|
58
|
+
return total % 2 === 1 ? at((total - 1) / 2) : (at(total / 2 - 1) + at(total / 2)) / 2;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const ANTIGRAVITY_VARIANT_SUFFIX = /(?:-(?:extra-low|low|medium|high|xhigh|trial))+$/;
|
|
62
|
+
|
|
63
|
+
/** Antigravity 按 effort 与路由给同一模型起不同名字,合并时剥掉后缀;其他通道的后缀属于模型 id。 */
|
|
64
|
+
export const speedModel = (provider, model) =>
|
|
65
|
+
provider === 'antigravity' ? model.replace(ANTIGRAVITY_VARIANT_SUFFIX, '') : model;
|
|
66
|
+
|
|
67
|
+
const scoreKey = (provider, model) => `${provider}\u0000${speedModel(provider, model)}`;
|
|
68
|
+
|
|
69
|
+
export const speedRowKey = (row) => JSON.stringify([row.provider, row.model, row.tier ?? null]);
|
|
70
|
+
|
|
71
|
+
/** 派发评分与速度共用的分组:按 provider × 归一后 model 汇总成功数与总数,成功公式只用 dispatchSucceeded。 */
|
|
72
|
+
export function speedDispatchScores(records, aliases = DEFAULT_SCORING_CONFIG.aliases) {
|
|
73
|
+
const grouped = new Map();
|
|
74
|
+
for (const record of records) {
|
|
75
|
+
const provider = aliases?.provider?.[record.executor.provider] ?? record.executor.provider;
|
|
76
|
+
const model = speedModel(provider, record.executor.model);
|
|
77
|
+
const key = scoreKey(provider, model);
|
|
78
|
+
const held = grouped.get(key) ?? { provider, model, successes: 0, total: 0 };
|
|
79
|
+
held.total += 1;
|
|
80
|
+
if (dispatchSucceeded(record)) held.successes += 1;
|
|
81
|
+
grouped.set(key, held);
|
|
82
|
+
}
|
|
83
|
+
return [...grouped.values()];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 把同一模型跨来源、跨变体的行加总,按长输出速率降序排名,没有长输出样本的行排最后。 */
|
|
87
|
+
export function rankSpeedRows(rows, scores = []) {
|
|
88
|
+
const scoreByModel = new Map(scores.map((score) => [scoreKey(score.provider, score.model), score]));
|
|
89
|
+
const grouped = new Map();
|
|
90
|
+
for (const row of rows) {
|
|
91
|
+
const model = speedModel(row.provider, row.model);
|
|
92
|
+
const key = speedRowKey({ provider: row.provider, model, tier: row.tier });
|
|
93
|
+
let group = grouped.get(key);
|
|
94
|
+
if (group === undefined) {
|
|
95
|
+
group = {
|
|
96
|
+
provider: row.provider,
|
|
97
|
+
model,
|
|
98
|
+
tier: row.tier,
|
|
99
|
+
long: new Map(),
|
|
100
|
+
all: new Map(),
|
|
101
|
+
short: new Map(),
|
|
102
|
+
outputTokens: 0,
|
|
103
|
+
firstMs: row.firstMs,
|
|
104
|
+
lastMs: row.lastMs,
|
|
105
|
+
};
|
|
106
|
+
grouped.set(key, group);
|
|
107
|
+
}
|
|
108
|
+
addPairsToBins(group.long, row.long);
|
|
109
|
+
addPairsToBins(group.all, row.all);
|
|
110
|
+
addPairsToBins(group.short, row.short);
|
|
111
|
+
group.outputTokens += row.outputTokens;
|
|
112
|
+
group.firstMs = Math.min(group.firstMs, row.firstMs);
|
|
113
|
+
group.lastMs = Math.max(group.lastMs, row.lastMs);
|
|
114
|
+
}
|
|
115
|
+
return [...grouped.values()]
|
|
116
|
+
.map((group) => {
|
|
117
|
+
const longRequests = binsCount(group.long);
|
|
118
|
+
const score = scoreByModel.get(scoreKey(group.provider, group.model));
|
|
119
|
+
return {
|
|
120
|
+
provider: group.provider,
|
|
121
|
+
model: group.model,
|
|
122
|
+
...(group.tier ? { tier: group.tier } : {}),
|
|
123
|
+
requests: binsCount(group.all),
|
|
124
|
+
longRequests,
|
|
125
|
+
shortRequests: binsCount(group.short),
|
|
126
|
+
outputTokens: group.outputTokens,
|
|
127
|
+
firstMs: group.firstMs,
|
|
128
|
+
lastMs: group.lastMs,
|
|
129
|
+
longRate: binsMedian(group.long),
|
|
130
|
+
allRate: binsMedian(group.all),
|
|
131
|
+
shortSeconds: binsMedian(group.short),
|
|
132
|
+
lowSample: longRequests < SPEED_LOW_SAMPLE_LONG_REQUESTS,
|
|
133
|
+
dispatch: score === undefined ? null : { successes: score.successes, total: score.total },
|
|
134
|
+
};
|
|
135
|
+
})
|
|
136
|
+
.filter((ranking) => ranking.requests > 0)
|
|
137
|
+
.sort((a, b) => {
|
|
138
|
+
if ((a.longRate === null) !== (b.longRate === null)) return a.longRate === null ? 1 : -1;
|
|
139
|
+
return (b.longRate ?? b.allRate ?? 0) - (a.longRate ?? a.allRate ?? 0);
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** 样本少的行折叠到末尾;全部都少时没有可比的基准,不拆分。 */
|
|
144
|
+
export function splitSparseRows(rows) {
|
|
145
|
+
const solid = rows.filter((row) => !row.lowSample);
|
|
146
|
+
return solid.length === 0
|
|
147
|
+
? { solid: rows, sparse: [] }
|
|
148
|
+
: { solid, sparse: rows.filter((row) => row.lowSample) };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 输出可直接传给 decideDispatch({ speedMetrics }) 的映射 { [model]: { longRate, ... } }。
|
|
153
|
+
* 只收长输出样本足够的行;同一模型经多个通道时取长输出样本最多的一行。
|
|
154
|
+
*/
|
|
155
|
+
export function toSpeedMetricsMap(ranking) {
|
|
156
|
+
const map = {};
|
|
157
|
+
for (const row of ranking) {
|
|
158
|
+
if (row.longRate === null || row.lowSample) continue;
|
|
159
|
+
const held = map[row.model];
|
|
160
|
+
if (held && held.longRequests >= row.longRequests) continue;
|
|
161
|
+
map[row.model] = {
|
|
162
|
+
longRate: Number(row.longRate.toFixed(2)),
|
|
163
|
+
allRate: row.allRate === null ? null : Number(row.allRate.toFixed(2)),
|
|
164
|
+
shortSeconds: row.shortSeconds === null ? null : Number(row.shortSeconds.toFixed(2)),
|
|
165
|
+
longRequests: row.longRequests,
|
|
166
|
+
provider: row.provider,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
return map;
|
|
170
|
+
}
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import readline from 'node:readline';
|
|
5
|
+
import {
|
|
6
|
+
SPEED_LONG_OUTPUT_TOKENS,
|
|
7
|
+
SPEED_SHORT_MAX_OUTPUT_TOKENS,
|
|
8
|
+
addToBins,
|
|
9
|
+
binsToPairs,
|
|
10
|
+
speedSample,
|
|
11
|
+
} from './histogram.mjs';
|
|
12
|
+
|
|
13
|
+
const CACHE_VERSION = 1;
|
|
14
|
+
const DAY_MS = 86_400_000;
|
|
15
|
+
|
|
16
|
+
// 只读本地日志与数据库;路径全部可注入,默认才落到家目录。
|
|
17
|
+
export function resolveSpeedPaths({ homeDir, env = process.env, ...overrides } = {}) {
|
|
18
|
+
const home = homeDir ?? os.homedir();
|
|
19
|
+
const listFromEnv = (value) => (value ? value.split(path.delimiter).filter(Boolean) : null);
|
|
20
|
+
const cacheBase = env.XDG_CACHE_HOME ? env.XDG_CACHE_HOME : path.join(home, '.cache');
|
|
21
|
+
return {
|
|
22
|
+
claudeDir: overrides.claudeDir ?? env.MODELPACE_CLAUDE_DIR ?? path.join(home, '.claude', 'projects'),
|
|
23
|
+
codexDir: overrides.codexDir ?? env.MODELPACE_CODEX_DIR ?? path.join(home, '.codex', 'sessions'),
|
|
24
|
+
opencodeDb:
|
|
25
|
+
overrides.opencodeDb ?? env.MODELPACE_OPENCODE_DB ?? path.join(home, '.local', 'share', 'opencode', 'opencode.db'),
|
|
26
|
+
antigravityPaths:
|
|
27
|
+
overrides.antigravityPaths ??
|
|
28
|
+
listFromEnv(env.MODELPACE_ANTIGRAVITY_PATHS) ?? [path.join(home, '.gemini', 'antigravity')],
|
|
29
|
+
cacheFile:
|
|
30
|
+
overrides.cacheFile ?? env.MODELPACE_SPEED_CACHE ?? path.join(cacheBase, 'modelpace', 'speed-cache.json'),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function parseMs(value) {
|
|
35
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value < 1e11 ? value * 1000 : value;
|
|
36
|
+
if (typeof value === 'string' && value) {
|
|
37
|
+
const ms = Date.parse(value);
|
|
38
|
+
return Number.isFinite(ms) ? ms : null;
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 单个文件内的请求累加器,按 provider × model × tier × UTC 日分行,便于缓存后再按窗口筛选。 */
|
|
44
|
+
class RowAccumulator {
|
|
45
|
+
#rows = new Map();
|
|
46
|
+
|
|
47
|
+
add(provider, model, tier, outputTokens, startMs, endMs) {
|
|
48
|
+
if (!model || !Number.isFinite(startMs) || !Number.isFinite(endMs)) return;
|
|
49
|
+
const sample = speedSample(outputTokens, startMs, endMs);
|
|
50
|
+
if (sample === null) return;
|
|
51
|
+
const day = new Date(endMs).toISOString().slice(0, 10);
|
|
52
|
+
const key = JSON.stringify([provider, model, tier ?? null, day]);
|
|
53
|
+
let row = this.#rows.get(key);
|
|
54
|
+
if (!row) {
|
|
55
|
+
row = {
|
|
56
|
+
provider, model, ...(tier ? { tier } : {}), day,
|
|
57
|
+
long: new Map(), all: new Map(), short: new Map(),
|
|
58
|
+
outputTokens: 0, firstMs: endMs, lastMs: endMs,
|
|
59
|
+
};
|
|
60
|
+
this.#rows.set(key, row);
|
|
61
|
+
}
|
|
62
|
+
addToBins(row.all, sample.tokensPerSecond);
|
|
63
|
+
if (outputTokens >= SPEED_LONG_OUTPUT_TOKENS) addToBins(row.long, sample.tokensPerSecond);
|
|
64
|
+
if (outputTokens <= SPEED_SHORT_MAX_OUTPUT_TOKENS) addToBins(row.short, sample.seconds);
|
|
65
|
+
row.outputTokens += outputTokens;
|
|
66
|
+
row.firstMs = Math.min(row.firstMs, endMs);
|
|
67
|
+
row.lastMs = Math.max(row.lastMs, endMs);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
toRows() {
|
|
71
|
+
return [...this.#rows.values()].map((row) => ({
|
|
72
|
+
...row,
|
|
73
|
+
long: binsToPairs(row.long),
|
|
74
|
+
all: binsToPairs(row.all),
|
|
75
|
+
short: binsToPairs(row.short),
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function forEachLine(file, onLine) {
|
|
81
|
+
const rl = readline.createInterface({ input: fs.createReadStream(file, { encoding: 'utf8' }), crlfDelay: Infinity });
|
|
82
|
+
for await (const line of rl) onLine(line);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const parseJson = (line) => {
|
|
86
|
+
try {
|
|
87
|
+
return JSON.parse(line);
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
// Claude Code:type=user 条目为起点,同 message.id 最后一块的时间戳为终点。
|
|
94
|
+
async function scanClaudeFile(file) {
|
|
95
|
+
const acc = new RowAccumulator();
|
|
96
|
+
let lastUserMs = null;
|
|
97
|
+
let current = null;
|
|
98
|
+
const flush = () => {
|
|
99
|
+
if (current && current.startMs !== null && !String(current.model ?? '<').startsWith('<')) {
|
|
100
|
+
acc.add('claude', current.model, null, current.tokens, current.startMs, current.endMs);
|
|
101
|
+
}
|
|
102
|
+
current = null;
|
|
103
|
+
};
|
|
104
|
+
await forEachLine(file, (line) => {
|
|
105
|
+
const userLine = line.includes('"type":"user"');
|
|
106
|
+
if (!userLine && !line.includes('"output_tokens"')) return;
|
|
107
|
+
const entry = parseJson(line);
|
|
108
|
+
if (!entry) return;
|
|
109
|
+
const ms = parseMs(entry.timestamp);
|
|
110
|
+
if (entry.type === 'user') {
|
|
111
|
+
flush();
|
|
112
|
+
if (ms !== null) lastUserMs = ms;
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const message = entry.message;
|
|
116
|
+
if (entry.type !== 'assistant' || !message?.id || ms === null) return;
|
|
117
|
+
const tokens = message.usage?.output_tokens;
|
|
118
|
+
if (!Number.isFinite(tokens)) return;
|
|
119
|
+
if (current?.id !== message.id) {
|
|
120
|
+
flush();
|
|
121
|
+
current = { id: message.id, model: message.model, startMs: lastUserMs, endMs: ms, tokens };
|
|
122
|
+
}
|
|
123
|
+
current.endMs = Math.max(current.endMs, ms);
|
|
124
|
+
current.tokens = Math.max(current.tokens, tokens);
|
|
125
|
+
});
|
|
126
|
+
flush();
|
|
127
|
+
return acc.toRows();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const CODEX_START_ITEMS = new Set(['function_call_output', 'custom_tool_call_output', 'local_shell_call_output']);
|
|
131
|
+
const CODEX_OUTPUT_ITEMS = new Set(['reasoning', 'function_call', 'custom_tool_call', 'local_shell_call']);
|
|
132
|
+
|
|
133
|
+
// Codex:用户消息 / task_started / 工具输出为起点,本次最后一个模型输出项为终点,
|
|
134
|
+
// 在 token_usage_record(新格式)或 token_count(旧格式)处出账。
|
|
135
|
+
async function scanCodexFile(file) {
|
|
136
|
+
const acc = new RowAccumulator();
|
|
137
|
+
let model = null;
|
|
138
|
+
let startMs = null;
|
|
139
|
+
let lastOutputMs = null;
|
|
140
|
+
let lastTotal = null;
|
|
141
|
+
const seenResponses = new Set();
|
|
142
|
+
const settle = (out) => {
|
|
143
|
+
if (startMs !== null && lastOutputMs !== null && Number.isFinite(out)) {
|
|
144
|
+
acc.add('codex', model, null, out, startMs, lastOutputMs);
|
|
145
|
+
}
|
|
146
|
+
startMs = null;
|
|
147
|
+
lastOutputMs = null;
|
|
148
|
+
};
|
|
149
|
+
await forEachLine(file, (line) => {
|
|
150
|
+
if (!line.includes('"payload"')) return;
|
|
151
|
+
const entry = parseJson(line);
|
|
152
|
+
const payload = entry?.payload;
|
|
153
|
+
const ms = parseMs(entry?.timestamp);
|
|
154
|
+
if (!payload || ms === null) return;
|
|
155
|
+
if (entry.type === 'turn_context') {
|
|
156
|
+
if (typeof payload.model === 'string') model = payload.model;
|
|
157
|
+
} else if (entry.type === 'token_usage_record') {
|
|
158
|
+
const id = payload.response_id;
|
|
159
|
+
if (id && seenResponses.has(id)) return;
|
|
160
|
+
if (id) seenResponses.add(id);
|
|
161
|
+
settle(payload.usage?.output_tokens);
|
|
162
|
+
} else if (entry.type === 'event_msg') {
|
|
163
|
+
if (payload.type === 'task_started') {
|
|
164
|
+
startMs = ms;
|
|
165
|
+
lastOutputMs = null;
|
|
166
|
+
} else if (payload.type === 'token_count' && payload.info) {
|
|
167
|
+
const total = payload.info.total_token_usage?.total_tokens;
|
|
168
|
+
if (total !== undefined && total === lastTotal) return;
|
|
169
|
+
lastTotal = total ?? null;
|
|
170
|
+
settle(payload.info.last_token_usage?.output_tokens);
|
|
171
|
+
}
|
|
172
|
+
} else if (entry.type === 'response_item') {
|
|
173
|
+
if (payload.type === 'message' && payload.role === 'user') {
|
|
174
|
+
startMs = ms;
|
|
175
|
+
lastOutputMs = null;
|
|
176
|
+
} else if (CODEX_START_ITEMS.has(payload.type)) {
|
|
177
|
+
startMs = ms;
|
|
178
|
+
lastOutputMs = null;
|
|
179
|
+
} else if (CODEX_OUTPUT_ITEMS.has(payload.type) || (payload.type === 'message' && payload.role === 'assistant')) {
|
|
180
|
+
lastOutputMs = ms;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
return acc.toRows();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// 通用事件交换格式(Antigravity / Gemini):每条 { model, outputTokens, startedAt, endedAt },时间可为毫秒或 ISO。
|
|
188
|
+
const addEvent = (acc, event, provider) => {
|
|
189
|
+
if (!event || typeof event !== 'object') return;
|
|
190
|
+
acc.add(
|
|
191
|
+
event.provider ?? provider,
|
|
192
|
+
event.model,
|
|
193
|
+
event.tier ?? null,
|
|
194
|
+
Number(event.outputTokens ?? event.output_tokens),
|
|
195
|
+
parseMs(event.startedAt ?? event.started_at ?? event.startMs ?? event.started_ms),
|
|
196
|
+
parseMs(event.endedAt ?? event.ended_at ?? event.endMs ?? event.ended_ms),
|
|
197
|
+
);
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
async function scanEventsJsonl(file, provider) {
|
|
201
|
+
const acc = new RowAccumulator();
|
|
202
|
+
await forEachLine(file, (line) => {
|
|
203
|
+
if (line.includes('"model"')) addEvent(acc, parseJson(line), provider);
|
|
204
|
+
});
|
|
205
|
+
return acc.toRows();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function openSqlite(file) {
|
|
209
|
+
try {
|
|
210
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
211
|
+
return new DatabaseSync(file, { readOnly: true });
|
|
212
|
+
} catch {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// OpenCode:message 表 data 内 time.created → time.completed,输出 = output + reasoning。
|
|
218
|
+
async function scanOpencodeDb(file) {
|
|
219
|
+
const db = await openSqlite(file);
|
|
220
|
+
if (!db) return null;
|
|
221
|
+
const acc = new RowAccumulator();
|
|
222
|
+
try {
|
|
223
|
+
for (const { data } of db.prepare('SELECT data FROM message').all()) {
|
|
224
|
+
const message = parseJson(data);
|
|
225
|
+
if (message?.role !== 'assistant' || !message.time?.completed) continue;
|
|
226
|
+
const tokens = (message.tokens?.output ?? 0) + (message.tokens?.reasoning ?? 0);
|
|
227
|
+
acc.add('opencode', message.modelID, null, tokens, parseMs(message.time.created), parseMs(message.time.completed));
|
|
228
|
+
}
|
|
229
|
+
} catch {
|
|
230
|
+
return null;
|
|
231
|
+
} finally {
|
|
232
|
+
db.close();
|
|
233
|
+
}
|
|
234
|
+
return acc.toRows();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// 通用事件库:表 speed_events(model, output_tokens, started_ms, ended_ms[, provider, tier])。
|
|
238
|
+
async function scanEventsSqlite(file, provider) {
|
|
239
|
+
const db = await openSqlite(file);
|
|
240
|
+
const acc = new RowAccumulator();
|
|
241
|
+
if (!db) return acc.toRows();
|
|
242
|
+
try {
|
|
243
|
+
for (const event of db.prepare('SELECT * FROM speed_events').all()) addEvent(acc, event, provider);
|
|
244
|
+
} catch {
|
|
245
|
+
// 没有 speed_events 表的数据库不是速度事件库
|
|
246
|
+
} finally {
|
|
247
|
+
db.close();
|
|
248
|
+
}
|
|
249
|
+
return acc.toRows();
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function walk(root, extensions, files = []) {
|
|
253
|
+
let entries;
|
|
254
|
+
try {
|
|
255
|
+
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
256
|
+
} catch {
|
|
257
|
+
return files;
|
|
258
|
+
}
|
|
259
|
+
for (const entry of entries) {
|
|
260
|
+
const full = path.join(root, entry.name);
|
|
261
|
+
if (entry.isDirectory()) walk(full, extensions, files);
|
|
262
|
+
else if (extensions.includes(path.extname(entry.name))) files.push(full);
|
|
263
|
+
}
|
|
264
|
+
return files;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const listFiles = (target, extensions) => {
|
|
268
|
+
let stat;
|
|
269
|
+
try {
|
|
270
|
+
stat = fs.statSync(target);
|
|
271
|
+
} catch {
|
|
272
|
+
return [];
|
|
273
|
+
}
|
|
274
|
+
return stat.isDirectory() ? walk(target, extensions) : [target];
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
function readCache(cacheFile) {
|
|
278
|
+
try {
|
|
279
|
+
const cache = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
|
|
280
|
+
if (cache?.version === CACHE_VERSION && cache.files && typeof cache.files === 'object') return cache.files;
|
|
281
|
+
} catch {
|
|
282
|
+
// 缓存缺失或损坏时从头扫描
|
|
283
|
+
}
|
|
284
|
+
return {};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function writeCache(cacheFile, files) {
|
|
288
|
+
try {
|
|
289
|
+
fs.mkdirSync(path.dirname(cacheFile), { recursive: true, mode: 0o700 });
|
|
290
|
+
const tmp = `${cacheFile}.${process.pid}.tmp`;
|
|
291
|
+
fs.writeFileSync(tmp, JSON.stringify({ version: CACHE_VERSION, files }), { mode: 0o600 });
|
|
292
|
+
fs.renameSync(tmp, cacheFile);
|
|
293
|
+
} catch {
|
|
294
|
+
// 缓存只是加速手段,写失败不影响结果
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* 增量扫描本地日志与数据库,返回按天分行的速度行(直方图为稀疏对)。
|
|
300
|
+
* 缓存按文件路径 + mtime + size 命中;窗口外且未改动的文件不读。
|
|
301
|
+
*/
|
|
302
|
+
export async function scanSpeed({
|
|
303
|
+
days = 30,
|
|
304
|
+
now = Date.now(),
|
|
305
|
+
providers = ['claude', 'codex', 'opencode', 'antigravity'],
|
|
306
|
+
cache = true,
|
|
307
|
+
...pathOptions
|
|
308
|
+
} = {}) {
|
|
309
|
+
const paths = resolveSpeedPaths(pathOptions);
|
|
310
|
+
const sinceMs = now - days * DAY_MS;
|
|
311
|
+
const cached = cache ? readCache(paths.cacheFile) : {};
|
|
312
|
+
const next = {};
|
|
313
|
+
const rows = [];
|
|
314
|
+
const sources = {};
|
|
315
|
+
const warnings = [];
|
|
316
|
+
|
|
317
|
+
const jobs = [];
|
|
318
|
+
if (providers.includes('claude')) {
|
|
319
|
+
for (const file of listFiles(paths.claudeDir, ['.jsonl'])) jobs.push({ provider: 'claude', file, scan: scanClaudeFile });
|
|
320
|
+
}
|
|
321
|
+
if (providers.includes('codex')) {
|
|
322
|
+
for (const file of listFiles(paths.codexDir, ['.jsonl'])) jobs.push({ provider: 'codex', file, scan: scanCodexFile });
|
|
323
|
+
}
|
|
324
|
+
if (providers.includes('opencode') && fs.existsSync(paths.opencodeDb)) {
|
|
325
|
+
jobs.push({ provider: 'opencode', file: paths.opencodeDb, scan: scanOpencodeDb, extra: [`${paths.opencodeDb}-wal`] });
|
|
326
|
+
}
|
|
327
|
+
if (providers.includes('antigravity')) {
|
|
328
|
+
for (const target of paths.antigravityPaths) {
|
|
329
|
+
for (const file of listFiles(target, ['.jsonl', '.sqlite', '.db'])) {
|
|
330
|
+
const sqlite = path.extname(file) !== '.jsonl';
|
|
331
|
+
jobs.push({
|
|
332
|
+
provider: 'antigravity',
|
|
333
|
+
file,
|
|
334
|
+
scan: (f) => (sqlite ? scanEventsSqlite(f, 'antigravity') : scanEventsJsonl(f, 'antigravity')),
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
for (const job of jobs) {
|
|
341
|
+
const source = (sources[job.provider] ??= { files: 0, scanned: 0, cached: 0, skipped: 0 });
|
|
342
|
+
let stat;
|
|
343
|
+
let signature;
|
|
344
|
+
try {
|
|
345
|
+
stat = fs.statSync(job.file);
|
|
346
|
+
const extraStats = (job.extra ?? []).map((extra) => {
|
|
347
|
+
try {
|
|
348
|
+
const s = fs.statSync(extra);
|
|
349
|
+
return `${s.mtimeMs}:${s.size}`;
|
|
350
|
+
} catch {
|
|
351
|
+
return '-';
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
signature = [stat.mtimeMs, stat.size, ...extraStats].join('|');
|
|
355
|
+
} catch {
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (stat.mtimeMs < sinceMs) {
|
|
359
|
+
source.skipped += 1;
|
|
360
|
+
if (cached[job.file]?.signature === signature) next[job.file] = cached[job.file];
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
source.files += 1;
|
|
364
|
+
const hit = cached[job.file];
|
|
365
|
+
let fileRows;
|
|
366
|
+
if (hit && hit.signature === signature) {
|
|
367
|
+
fileRows = hit.rows;
|
|
368
|
+
source.cached += 1;
|
|
369
|
+
} else {
|
|
370
|
+
try {
|
|
371
|
+
fileRows = await job.scan(job.file);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
warnings.push(`${job.provider}: ${path.basename(job.file)}: ${error.message}`);
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
if (fileRows === null) {
|
|
377
|
+
warnings.push(`${job.provider}: ${path.basename(job.file)} skipped (node:sqlite unavailable or unreadable)`);
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
source.scanned += 1;
|
|
381
|
+
}
|
|
382
|
+
next[job.file] = { signature, rows: fileRows };
|
|
383
|
+
for (const row of fileRows) {
|
|
384
|
+
if (row.lastMs >= sinceMs) rows.push(row);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (cache) writeCache(paths.cacheFile, next);
|
|
389
|
+
return { rows, sources, warnings, sinceMs, days };
|
|
390
|
+
}
|