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.
@@ -0,0 +1,491 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+
5
+ export const TASKS = Object.freeze(['general', 'research', 'review', 'slice', 'long']);
6
+
7
+ const FIELDS = [
8
+ 'date', 'taskId', 'title', 'task', 'executor', 'scorer',
9
+ 'accepted', 'firstPass', 'reworkRounds', 'scopeViolation', 'falseReport',
10
+ 'stoppedOnDenial', 'durationMin', 'quotaDelta', 'note',
11
+ ];
12
+ const IDENTITY = ['provider', 'model', 'effort', 'tier', 'site'];
13
+
14
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
15
+ const nonempty = (value) => typeof value === 'string' && value.trim().length > 0;
16
+ const token = (value) => nonempty(value) && !/[\s/\x00-\x1f\x7f]/.test(value);
17
+
18
+ export const DEFAULT_SCORING_CONFIG = Object.freeze({
19
+ mode: 'demote',
20
+ minPassRate: 0.85,
21
+ minSamples: 5,
22
+ speedTieBreakerMarginRatio: 0.15,
23
+ costWeight: 0,
24
+ aliases: {
25
+ provider: { claudeAgent: 'claude' },
26
+ tier: { '-': 'default' },
27
+ },
28
+ durationUnreadableProviders: [],
29
+ rejectRules: [],
30
+ disabledProviders: [],
31
+ pricing: {
32
+ currency: 'USD',
33
+ exchangeRates: { USD: 6.67, CNY: 1 },
34
+ monthlyPrice: {},
35
+ },
36
+ });
37
+
38
+ function exactFields(value, keys, label) {
39
+ if (!isObject(value)) throw new Error(`Invalid dispatch record: ${label} must be an object`);
40
+ for (const key of keys) {
41
+ if (!Object.hasOwn(value, key)) throw new Error(`Invalid dispatch record: missing ${label}.${key}`);
42
+ }
43
+ for (const key of Object.keys(value)) {
44
+ if (!keys.includes(key)) throw new Error(`Invalid dispatch record: unknown field ${label}.${key}`);
45
+ }
46
+ }
47
+
48
+ function matchesRejectRule(record, rule) {
49
+ if (!isObject(rule)) return false;
50
+ const exec = record.executor;
51
+ if (Array.isArray(rule.providerIn) && !rule.providerIn.includes(exec.provider)) return false;
52
+ if (Array.isArray(rule.providerNotIn) && rule.providerNotIn.includes(exec.provider)) return false;
53
+ if (typeof rule.siteContains === 'string' && !exec.site.split('+').includes(rule.siteContains) && !exec.site.includes(rule.siteContains)) return false;
54
+ if (Array.isArray(rule.modelIn) && !rule.modelIn.includes(exec.model)) return false;
55
+ if (Array.isArray(rule.tierIn) && !rule.tierIn.includes(exec.tier)) return false;
56
+ return true;
57
+ }
58
+
59
+ export function validateDispatchRecord(record, config = {}) {
60
+ exactFields(record, FIELDS, 'record');
61
+ if (
62
+ typeof record.date !== 'string' ||
63
+ !/^\d{4}-\d{2}-\d{2}$/.test(record.date) ||
64
+ !Number.isFinite(Date.parse(record.date)) ||
65
+ new Date(record.date).toISOString().slice(0, 10) !== record.date
66
+ ) {
67
+ throw new Error('Invalid dispatch record: date must be valid YYYY-MM-DD');
68
+ }
69
+ if (record.taskId !== null && !nonempty(record.taskId)) {
70
+ throw new Error('Invalid dispatch record: taskId must be non-empty string or null');
71
+ }
72
+ for (const key of ['title', 'scorer']) {
73
+ if (!nonempty(record[key])) {
74
+ throw new Error(`Invalid dispatch record: ${key} must be non-empty string`);
75
+ }
76
+ }
77
+ if (!TASKS.includes(record.task)) {
78
+ throw new Error(`Invalid dispatch record: task must be one of ${TASKS.join(', ')}`);
79
+ }
80
+ exactFields(record.executor, IDENTITY, 'executor');
81
+ for (const key of IDENTITY) {
82
+ if (!token(record.executor[key])) {
83
+ throw new Error(`Invalid dispatch record: executor.${key} must be a non-empty token without whitespace or '/'`);
84
+ }
85
+ }
86
+ for (const rule of Array.isArray(config.rejectRules) ? config.rejectRules : []) {
87
+ if (matchesRejectRule(record, rule)) {
88
+ throw new Error(`Invalid dispatch record: ${rule.reason || 'rejected by policy rule'}`);
89
+ }
90
+ }
91
+ for (const key of ['accepted', 'firstPass', 'scopeViolation', 'falseReport']) {
92
+ if (typeof record[key] !== 'boolean') {
93
+ throw new Error(`Invalid dispatch record: ${key} must be boolean`);
94
+ }
95
+ }
96
+ if (record.stoppedOnDenial !== null && typeof record.stoppedOnDenial !== 'boolean') {
97
+ throw new Error('Invalid dispatch record: stoppedOnDenial must be boolean or null');
98
+ }
99
+ if (!Number.isSafeInteger(record.reworkRounds) || record.reworkRounds < 0) {
100
+ throw new Error('Invalid dispatch record: reworkRounds must be non-negative integer');
101
+ }
102
+ if (record.durationMin !== null && (!Number.isFinite(record.durationMin) || record.durationMin < 0)) {
103
+ throw new Error('Invalid dispatch record: durationMin must be non-negative finite number or null');
104
+ }
105
+ if (record.quotaDelta !== null && !Number.isFinite(record.quotaDelta)) {
106
+ throw new Error('Invalid dispatch record: quotaDelta must be finite number or null');
107
+ }
108
+ if (typeof record.note !== 'string') {
109
+ throw new Error('Invalid dispatch record: note must be string');
110
+ }
111
+ return record;
112
+ }
113
+
114
+ export const executorIdentity = (executor) => IDENTITY.map((key) => executor[key]).join('/');
115
+
116
+ export function scoreIdentity(executor, aliases = DEFAULT_SCORING_CONFIG.aliases) {
117
+ const providerAlias = aliases?.provider ?? DEFAULT_SCORING_CONFIG.aliases.provider;
118
+ const tierAlias = aliases?.tier ?? DEFAULT_SCORING_CONFIG.aliases.tier;
119
+ const modelAlias = aliases?.model ?? {};
120
+ const effortAlias = aliases?.effort ?? {};
121
+
122
+ const provider = providerAlias?.[executor.provider] ?? executor.provider;
123
+ const model = modelAlias?.[executor.model] ?? executor.model;
124
+ const effort = effortAlias?.[executor.effort] ?? executor.effort;
125
+ const tier = tierAlias?.[executor.tier] ?? executor.tier;
126
+ return [provider, model, effort, tier].join('/');
127
+ }
128
+
129
+ export const dispatchSucceeded = (record) =>
130
+ record.accepted &&
131
+ !record.falseReport &&
132
+ !record.scopeViolation &&
133
+ record.stoppedOnDenial !== false &&
134
+ record.reworkRounds <= 1;
135
+
136
+ /** 默认账本目录:$XDG_DATA_HOME,缺省 ~/.local/share;Windows 用 %LOCALAPPDATA%。 */
137
+ function defaultScoresFile(env) {
138
+ const base = process.platform === 'win32'
139
+ ? env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local')
140
+ : env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share');
141
+ return path.join(base, 'modelpace', 'scores.jsonl');
142
+ }
143
+
144
+ /** 账本路径优先级:file > scoresFile(--scores)> MODELPACE_SCORES > 用户数据目录下的默认账本。 */
145
+ export function resolveScoresFile({ file, scoresFile, env = process.env } = {}) {
146
+ if (typeof file === 'string' && file.trim()) return path.resolve(file.trim());
147
+ if (typeof scoresFile === 'string' && scoresFile.trim()) return path.resolve(scoresFile.trim());
148
+ if (typeof env.MODELPACE_SCORES === 'string' && env.MODELPACE_SCORES.trim()) {
149
+ return path.resolve(env.MODELPACE_SCORES.trim());
150
+ }
151
+ return defaultScoresFile(env);
152
+ }
153
+
154
+ export function appendDispatchRecord(record, options = {}) {
155
+ const config = options.config ?? {};
156
+ validateDispatchRecord(record, config);
157
+ const unreadable = Array.isArray(config.durationUnreadableProviders)
158
+ ? config.durationUnreadableProviders
159
+ : [];
160
+ if (record.durationMin === null && !unreadable.includes(record.executor.provider)) {
161
+ throw new Error(
162
+ `Invalid dispatch record: durationMin cannot be null unless provider (${record.executor.provider}) is listed in durationUnreadableProviders`,
163
+ );
164
+ }
165
+ const file = resolveScoresFile(options);
166
+ const dir = path.dirname(file);
167
+ // 只对本次新建的目录收紧权限(mkdir 的 mode 受 umask 影响,故不依赖它),已存在的目录保持原样。
168
+ const created = fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
169
+ if (created !== undefined && process.platform !== 'win32') fs.chmodSync(created, 0o700);
170
+ const fd = fs.openSync(file, 'a+', 0o600);
171
+ try {
172
+ if (process.platform !== 'win32') fs.fchmodSync(fd, 0o600);
173
+ const size = fs.fstatSync(fd).size;
174
+ const last = Buffer.alloc(1);
175
+ if (size > 0) fs.readSync(fd, last, 0, 1, size - 1);
176
+ fs.appendFileSync(fd, `${size > 0 && last[0] !== 10 ? '\n' : ''}${JSON.stringify(record)}\n`, 'utf8');
177
+ } finally {
178
+ fs.closeSync(fd);
179
+ }
180
+ return { file, identity: executorIdentity(record.executor), task: record.task };
181
+ }
182
+
183
+ export function readDispatchRecords(options = {}) {
184
+ const file = resolveScoresFile(options);
185
+ let content;
186
+ try {
187
+ content = fs.readFileSync(file, 'utf8');
188
+ } catch (error) {
189
+ if (error.code === 'ENOENT') return [];
190
+ throw error;
191
+ }
192
+ const records = [];
193
+ const config = options.config ?? {};
194
+ for (const [index, line] of content.split('\n').entries()) {
195
+ if (!line.trim()) continue;
196
+ try {
197
+ records.push(validateDispatchRecord(JSON.parse(line), config));
198
+ } catch (error) {
199
+ throw new Error(`Corrupt or invalid dispatch record at line ${index + 1}: ${error.message}`);
200
+ }
201
+ }
202
+ return records;
203
+ }
204
+
205
+ // Lanczos log-Gamma and continued fraction for the regularized incomplete beta.
206
+ function logGamma(z) {
207
+ const coefficients = [
208
+ 676.5203681218851, -1259.1392167224028, 771.3234287776531, -176.6150291621406,
209
+ 12.507343278686905, -0.13857109526572012, 9.984369578019572e-6, 1.5056327351493116e-7,
210
+ ];
211
+ z -= 1;
212
+ let x = 0.99999999999980993;
213
+ for (let i = 0; i < coefficients.length; i++) {
214
+ x += coefficients[i] / (z + i + 1);
215
+ }
216
+ const t = z + coefficients.length - 0.5;
217
+ return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x);
218
+ }
219
+
220
+ function betaFraction(a, b, x) {
221
+ const floor = (value) => (Math.abs(value) < 1e-300 ? 1e-300 : value);
222
+ let c = 1;
223
+ let d = 1 / floor(1 - ((a + b) * x) / (a + 1));
224
+ let h = d;
225
+ for (let m = 1; m <= 10000; m++) {
226
+ const twice = 2 * m;
227
+ let aa = (m * (b - m) * x) / ((a + twice - 1) * (a + twice));
228
+ d = 1 / floor(1 + aa * d);
229
+ c = floor(1 + aa / c);
230
+ h *= d * c;
231
+ aa = (-(a + m) * (a + b + m) * x) / ((a + twice) * (a + twice + 1));
232
+ d = 1 / floor(1 + aa * d);
233
+ c = floor(1 + aa / c);
234
+ const delta = d * c;
235
+ h *= delta;
236
+ if (Math.abs(delta - 1) < 3e-14) return h;
237
+ }
238
+ throw new Error('Beta quantile failed to converge');
239
+ }
240
+
241
+ export function betaQuantile(p, a, b) {
242
+ if (!(p > 0 && p < 1 && Number.isSafeInteger(a) && a > 0 && Number.isSafeInteger(b) && b > 0)) {
243
+ throw new Error('Invalid Beta quantile parameters');
244
+ }
245
+ const logNorm = logGamma(a + b) - logGamma(a) - logGamma(b);
246
+ let low = 0;
247
+ let high = 1;
248
+ for (let iteration = 0; iteration < 60; iteration++) {
249
+ const x = (low + high) / 2;
250
+ const factor = Math.exp(logNorm + a * Math.log(x) + b * Math.log1p(-x));
251
+ const cdf = x < (a + 1) / (a + b + 2)
252
+ ? (factor * betaFraction(a, b, x)) / a
253
+ : 1 - (factor * betaFraction(b, a, 1 - x)) / b;
254
+ if (cdf < p) low = x;
255
+ else high = x;
256
+ }
257
+ return (low + high) / 2;
258
+ }
259
+
260
+ const median = (values) => {
261
+ if (!values.length) return null;
262
+ const sorted = [...values].sort((a, b) => a - b);
263
+ const middle = sorted.length >> 1;
264
+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
265
+ };
266
+
267
+ export function resolveWeeklyPrices(pricingInput = {}) {
268
+ // Supports both v2 { currency, exchangeRates, monthlyPrice: { p: { amount, currency } } }
269
+ // and legacy { usdCnyRate, monthlyPrice: { p: { usd: 200 } | { cny: 100 } } }
270
+ const targetCurrency = pricingInput.currency ?? (pricingInput.usdCnyRate ? 'CNY' : 'USD');
271
+ const rates = {
272
+ USD: pricingInput.exchangeRates?.USD ?? pricingInput.usdCnyRate ?? 6.67,
273
+ CNY: pricingInput.exchangeRates?.CNY ?? 1,
274
+ ...(pricingInput.exchangeRates ?? {}),
275
+ };
276
+
277
+ const toTarget = (amount, fromCurrency) => {
278
+ const upperFrom = String(fromCurrency).toUpperCase();
279
+ const upperTarget = String(targetCurrency).toUpperCase();
280
+ if (upperFrom === upperTarget) return amount;
281
+ if (upperFrom === 'USD' && upperTarget === 'CNY') return amount * (rates.USD ?? 6.67);
282
+ if (upperFrom === 'CNY' && upperTarget === 'USD') return amount / (rates.USD ?? 6.67);
283
+ if (rates[upperFrom] && rates[upperTarget]) {
284
+ return (amount * rates[upperFrom]) / rates[upperTarget];
285
+ }
286
+ return amount;
287
+ };
288
+
289
+ const weeklyByProvider = {};
290
+ for (const [provider, price] of Object.entries(pricingInput.monthlyPrice ?? {})) {
291
+ if (!isObject(price)) continue;
292
+ let amount = null;
293
+ let currency = null;
294
+ if (Number.isFinite(price.amount) && price.amount > 0 && typeof price.currency === 'string') {
295
+ amount = price.amount;
296
+ currency = price.currency;
297
+ } else if (Number.isFinite(price.usd) && price.usd > 0) {
298
+ amount = price.usd;
299
+ currency = 'USD';
300
+ } else if (Number.isFinite(price.cny) && price.cny > 0) {
301
+ amount = price.cny;
302
+ currency = 'CNY';
303
+ }
304
+ if (amount !== null && currency !== null) {
305
+ weeklyByProvider[provider] = (toTarget(amount, currency) * 12) / 52;
306
+ }
307
+ }
308
+
309
+ return { currency: String(targetCurrency).toUpperCase(), weeklyByProvider, rates };
310
+ }
311
+
312
+ export function summarizeDispatchScores(records, config = {}) {
313
+ const minSamples = Number.isSafeInteger(config.minSamples) && config.minSamples > 0
314
+ ? config.minSamples
315
+ : DEFAULT_SCORING_CONFIG.minSamples;
316
+ const aliases = config.aliases ?? DEFAULT_SCORING_CONFIG.aliases;
317
+ const pricing = resolveWeeklyPrices(config.pricing ?? {});
318
+
319
+ const cells = new Map();
320
+ for (const record of records) {
321
+ validateDispatchRecord(record, config);
322
+ const identity = scoreIdentity(record.executor, aliases);
323
+ const key = JSON.stringify([identity, record.task]);
324
+ if (!cells.has(key)) {
325
+ cells.set(key, {
326
+ identity,
327
+ task: record.task,
328
+ s: 0,
329
+ f: 0,
330
+ firstPass: 0,
331
+ durations: [],
332
+ quotaDeltas: [],
333
+ costs: [],
334
+ });
335
+ }
336
+ const cell = cells.get(key);
337
+ const succeeded = dispatchSucceeded(record);
338
+ if (succeeded) cell.s++;
339
+ else cell.f++;
340
+ if (record.firstPass) cell.firstPass++;
341
+ if (succeeded && record.durationMin !== null) cell.durations.push(record.durationMin);
342
+ if (record.quotaDelta !== null) cell.quotaDeltas.push(record.quotaDelta);
343
+
344
+ const aliasedProvider = aliases?.provider?.[record.executor.provider] ?? record.executor.provider;
345
+ const weekly = pricing.weeklyByProvider[aliasedProvider] ?? pricing.weeklyByProvider[record.executor.provider];
346
+ if (weekly !== undefined && record.quotaDelta !== null) {
347
+ cell.costs.push((record.quotaDelta / 100) * weekly);
348
+ }
349
+ }
350
+
351
+ return {
352
+ totalRecords: records.length,
353
+ minSamples,
354
+ currency: pricing.currency,
355
+ cells: [...cells.values()]
356
+ .sort((a, b) => a.identity.localeCompare(b.identity) || a.task.localeCompare(b.task))
357
+ .map(({ firstPass, durations, quotaDeltas, costs, ...cell }) => {
358
+ const n = cell.s + cell.f;
359
+ const enough = n >= minSamples;
360
+ const costMedian = median(costs);
361
+ const costCnyMedian = costMedian === null
362
+ ? null
363
+ : pricing.currency === 'CNY'
364
+ ? costMedian
365
+ : pricing.currency === 'USD'
366
+ ? costMedian * (pricing.rates.USD ?? 6.67)
367
+ : null;
368
+
369
+ return {
370
+ ...cell,
371
+ n,
372
+ passRate: enough ? (cell.s + 1) / (n + 2) : null,
373
+ rawPassRate: n > 0 ? cell.s / n : null,
374
+ interval90: enough
375
+ ? [betaQuantile(0.05, cell.s + 1, cell.f + 1), betaQuantile(0.95, cell.s + 1, cell.f + 1)]
376
+ : null,
377
+ firstPassRate: enough ? firstPass / n : null,
378
+ durationMedianMin: median(durations),
379
+ durationSamples: durations.length,
380
+ quotaDeltaMedian: median(quotaDeltas),
381
+ quotaDeltaSamples: quotaDeltas.length,
382
+ costMedian,
383
+ costCurrency: costMedian !== null ? pricing.currency : null,
384
+ costCnyMedian,
385
+ costSamples: costs.length,
386
+ };
387
+ }),
388
+ records,
389
+ };
390
+ }
391
+
392
+ export function rankDispatchScores(summary, config = {}) {
393
+ const minPassRate = Number.isFinite(config.minPassRate)
394
+ ? config.minPassRate
395
+ : DEFAULT_SCORING_CONFIG.minPassRate;
396
+ const disabledProviders = Array.isArray(config.disabledProviders) ? config.disabledProviders : [];
397
+ const byTask = new Map();
398
+
399
+ for (const cell of summary.cells) {
400
+ const provider = cell.identity.split('/')[0];
401
+ if (disabledProviders.includes(provider)) continue;
402
+ if (!byTask.has(cell.task)) {
403
+ byTask.set(cell.task, { task: cell.task, qualified: [], trial: [], below: [] });
404
+ }
405
+ const group = byTask.get(cell.task);
406
+ if (cell.passRate === null) {
407
+ group.trial.push(cell.identity);
408
+ } else if (cell.passRate >= minPassRate) {
409
+ group.qualified.push(cell.identity);
410
+ } else {
411
+ group.below.push(cell.identity);
412
+ }
413
+ }
414
+
415
+ const cellOf = (task, identity) => summary.cells.find((c) => c.task === task && c.identity === identity);
416
+ for (const group of byTask.values()) {
417
+ group.qualified.sort((a, b) => {
418
+ const [x, y] = [cellOf(group.task, a), cellOf(group.task, b)];
419
+ return (x.durationMedianMin ?? Infinity) - (y.durationMedianMin ?? Infinity) || y.passRate - x.passRate;
420
+ });
421
+ }
422
+
423
+ return {
424
+ minPassRate,
425
+ minSamples: summary.minSamples,
426
+ tasks: [...byTask.values()].sort((a, b) => a.task.localeCompare(b.task)),
427
+ };
428
+ }
429
+
430
+ export function collectDispatchScores(options = {}, config = {}) {
431
+ const records = readDispatchRecords({ ...options, config });
432
+ const summary = summarizeDispatchScores(records, config);
433
+ return { ...summary, ranking: rankDispatchScores(summary, config) };
434
+ }
435
+
436
+ const pct = (value) => `${(value * 100).toFixed(1)}%`;
437
+
438
+ export function formatDispatchScores(summary, { lang = 'en' } = {}) {
439
+ const zh = lang === 'zh';
440
+ if (!summary.totalRecords) {
441
+ return [zh ? '暂无评分记录' : 'No dispatch records found.'];
442
+ }
443
+
444
+ const ranking = summary.ranking ?? rankDispatchScores(summary);
445
+ const cellOf = (task, identity) => summary.cells.find((c) => c.task === task && c.identity === identity);
446
+ const fmtDuration = (cell) => cell.durationMedianMin === null
447
+ ? (zh ? '耗时未记' : 'duration n/a')
448
+ : (zh
449
+ ? `耗时中位 ${Number(cell.durationMedianMin.toFixed(1))} 分 (${cell.durationSamples})`
450
+ : `median ${Number(cell.durationMedianMin.toFixed(1))}m (${cell.durationSamples})`);
451
+ const fmtCost = (cell) => {
452
+ if (cell.costMedian === null) return zh ? '成本未记' : 'cost n/a';
453
+ const symbol = cell.costCurrency === 'CNY' ? '¥' : cell.costCurrency === 'USD' ? '$' : `${cell.costCurrency} `;
454
+ return zh
455
+ ? `成本中位 ${symbol}${cell.costMedian.toFixed(2)}/次 (${cell.costSamples})`
456
+ : `cost ${symbol}${cell.costMedian.toFixed(2)}/run (${cell.costSamples})`;
457
+ };
458
+
459
+ const lines = [
460
+ zh
461
+ ? `选型(通过率 >= ${pct(ranking.minPassRate)} 且 n >= ${ranking.minSamples} 后按耗时中位数升序;成本仅作参考)`
462
+ : `Ranking (passRate >= ${pct(ranking.minPassRate)}, n >= ${ranking.minSamples}, sorted by median duration ascending)`,
463
+ ];
464
+
465
+ for (const group of ranking.tasks) {
466
+ const qStr = group.qualified
467
+ .map((identity, idx) => {
468
+ const c = cellOf(group.task, identity);
469
+ const lower = c.interval90[0];
470
+ const lowNote = lower < ranking.minPassRate ? (zh ? ',90%下界偏低' : ', CI low') : '';
471
+ return `${idx + 1}. ${identity} (${fmtDuration(c)}; ${fmtCost(c)}; CI90>=${pct(lower)}${lowNote})`;
472
+ })
473
+ .join('; ');
474
+ const bStr = group.below.length ? (zh ? ` | 未过门槛: ${group.below.join(', ')}` : ` | below: ${group.below.join(', ')}`) : '';
475
+ const tStr = group.trial.length ? (zh ? ` | 试用中: ${group.trial.join(', ')}` : ` | trial: ${group.trial.join(', ')}`) : '';
476
+ lines.push(`${group.task}: ${qStr || (zh ? '暂无达标执行者' : 'none qualified')}${bStr}${tStr}`);
477
+ }
478
+
479
+ lines.push('', zh ? '明细单元' : 'Score Cells');
480
+ for (const cell of summary.cells) {
481
+ if (cell.n < summary.minSamples) {
482
+ lines.push(`- ${cell.identity} × ${cell.task}: ${zh ? `试用样本不足 n=${cell.n}` : `trial n=${cell.n} (<${summary.minSamples})`}`);
483
+ } else {
484
+ lines.push(
485
+ `- ${cell.identity} × ${cell.task}: pass ${pct(cell.passRate)} (90% CI ${cell.interval90.map(pct).join('–')}), n=${cell.n} (${cell.s}✓/${cell.f}✗), firstPass ${pct(cell.firstPassRate)}, ${fmtDuration(cell)}, ${fmtCost(cell)}`,
486
+ );
487
+ }
488
+ }
489
+
490
+ return lines;
491
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,48 @@
1
+ export { T3RpcError, connectT3, fetchT3ServerConfig, resolveBearer, splitCommandArgs } from './adapters/t3-rpc.mjs';
2
+ export { discoverT3Cli, discoverT3Origin, fetchT3AutoConfig } from './adapters/t3-auto.mjs';
3
+ export { normalizeT3ConfigToSnapshot, inferWindowPool } from './adapters/t3-config.mjs';
4
+ export { normalizeSnapshot, overlayBudgetEntries } from './adapters/json-snapshot.mjs';
5
+ export {
6
+ DEFAULT_PACING_CONFIG,
7
+ inferAntigravityPool,
8
+ evaluateWindow,
9
+ isWindowApplicable,
10
+ cardCoversWindow,
11
+ evaluateFreshness,
12
+ evaluateBudget,
13
+ evaluateInstanceCandidate,
14
+ } from './core/pacing.mjs';
15
+ export {
16
+ TASKS,
17
+ DEFAULT_SCORING_CONFIG,
18
+ validateDispatchRecord,
19
+ executorIdentity,
20
+ scoreIdentity,
21
+ dispatchSucceeded,
22
+ resolveScoresFile,
23
+ appendDispatchRecord,
24
+ readDispatchRecords,
25
+ betaQuantile,
26
+ resolveWeeklyPrices,
27
+ summarizeDispatchScores,
28
+ rankDispatchScores,
29
+ collectDispatchScores,
30
+ formatDispatchScores,
31
+ } from './core/scores.mjs';
32
+ export { DEFAULT_POLICY, starterPolicy, normalizePolicy, validatePolicy } from './core/policy.mjs';
33
+ export { decideDispatch, formatDecisionText } from './core/decide.mjs';
34
+ export {
35
+ speedSample,
36
+ addToBins,
37
+ binsToPairs,
38
+ binsMedian,
39
+ speedModel,
40
+ speedRowKey,
41
+ speedDispatchScores,
42
+ rankSpeedRows,
43
+ splitSparseRows,
44
+ toSpeedMetricsMap,
45
+ } from './speed/histogram.mjs';
46
+ export { resolveSpeedPaths, scanSpeed } from './speed/scanner.mjs';
47
+ export { collectSpeed, formatSpeedText } from './speed/collect.mjs';
48
+ export { buildDashboardData, renderDashboardHtml, startDashboardServer } from './ui/dashboard.mjs';
@@ -0,0 +1,47 @@
1
+ import { DEFAULT_SCORING_CONFIG, readDispatchRecords } from '../core/scores.mjs';
2
+ import { rankSpeedRows, speedDispatchScores, toSpeedMetricsMap } from './histogram.mjs';
3
+ import { scanSpeed } from './scanner.mjs';
4
+
5
+ /** 扫描本地日志并排名;派发评分文件缺失或无法解析时整列不显示。 */
6
+ export async function collectSpeed({ days = 30, now = Date.now(), scan = {}, scoresFile, scoring = {}, env = process.env } = {}) {
7
+ const scanned = await scanSpeed({ days, now, env, ...scan });
8
+ let scores = [];
9
+ try {
10
+ const records = readDispatchRecords({ scoresFile, env, config: scoring });
11
+ scores = speedDispatchScores(records, scoring.aliases ?? DEFAULT_SCORING_CONFIG.aliases);
12
+ } catch {
13
+ scores = [];
14
+ }
15
+ const ranking = rankSpeedRows(scanned.rows, scores);
16
+ return {
17
+ days,
18
+ sinceMs: scanned.sinceMs,
19
+ untilMs: now,
20
+ ranking,
21
+ metrics: toSpeedMetricsMap(ranking),
22
+ sources: scanned.sources,
23
+ warnings: scanned.warnings,
24
+ };
25
+ }
26
+
27
+ const fmt = (value, digits = 1) => (value === null || value === undefined ? '-' : Number(value).toFixed(digits));
28
+
29
+ export function formatSpeedText(speed, { lang = 'en' } = {}) {
30
+ const zh = lang === 'zh';
31
+ if (!speed.ranking.length) return [zh ? '没有找到本地速度样本' : 'No local speed samples found.'];
32
+ const lines = [
33
+ zh
34
+ ? `速度排行(近 ${speed.days} 天,长输出 ≥1000 token 请求的 tok/s 中位数)`
35
+ : `Speed leaderboard (last ${speed.days} days, median tok/s of requests with >=1000 output tokens)`,
36
+ ];
37
+ speed.ranking.forEach((row, index) => {
38
+ const dispatch = row.dispatch ? ` pass=${row.dispatch.successes}/${row.dispatch.total}` : '';
39
+ const low = row.lowSample ? (zh ? ' [样本少]' : ' [low sample]') : '';
40
+ lines.push(
41
+ `${index + 1}. ${row.model} (${row.provider}) long=${fmt(row.longRate)} tok/s all=${fmt(row.allRate)} short=${fmt(row.shortSeconds, 2)}s ` +
42
+ `n=${row.longRequests}/${row.requests}${dispatch}${low}`,
43
+ );
44
+ });
45
+ for (const warning of speed.warnings) lines.push(`! ${warning}`);
46
+ return lines;
47
+ }