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,435 @@
1
+ import { evaluateInstanceCandidate } from './pacing.mjs';
2
+ import { normalizePolicy } from './policy.mjs';
3
+ import { TASKS, scoreIdentity } from './scores.mjs';
4
+
5
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
6
+
7
+ function resolveSpeedRate(speedMetrics, candidate, identity) {
8
+ if (!speedMetrics || !isObject(speedMetrics)) return null;
9
+ const lookup = (entry) => {
10
+ if (typeof entry === 'number' && Number.isFinite(entry)) return entry;
11
+ if (isObject(entry)) {
12
+ const rate = entry.longRate ?? entry.tokensPerSec ?? entry.tokPerSec ?? entry.rate;
13
+ if (typeof rate === 'number' && Number.isFinite(rate)) return rate;
14
+ }
15
+ return null;
16
+ };
17
+ return (
18
+ lookup(speedMetrics[candidate.model]) ??
19
+ lookup(speedMetrics.models?.[candidate.model]) ??
20
+ lookup(speedMetrics[identity]) ??
21
+ lookup(speedMetrics.identities?.[identity]) ??
22
+ null
23
+ );
24
+ }
25
+
26
+ function lookupScoreCell(scoresSummary, identity, task) {
27
+ if (!scoresSummary || !Array.isArray(scoresSummary.cells)) return null;
28
+ return scoresSummary.cells.find((c) => c.identity === identity && c.task === task) ?? null;
29
+ }
30
+
31
+ function qualityTierRank(qualityTier, mode) {
32
+ if (mode === 'advisory') return 0;
33
+ if (qualityTier === 'qualified') return 0;
34
+ if (qualityTier === 'trial') return 1;
35
+ return 2; // below_threshold (demote)
36
+ }
37
+
38
+ function compareCandidates(a, b, policy) {
39
+ const mode = policy.scoring.mode;
40
+ const marginRatio = policy.scoring.speedTieBreakerMarginRatio ?? 0.15;
41
+
42
+ // 1. Quality tier (qualified > trial > below_threshold when mode === 'demote')
43
+ const qRankDiff = qualityTierRank(a.qualityTier, mode) - qualityTierRank(b.qualityTier, mode);
44
+ if (qRankDiff !== 0) return qRankDiff;
45
+
46
+ // 2. Within qualified: sort by task success median duration ascending (speed tie-breaks within margin)
47
+ if (a.qualityTier === 'qualified' && b.qualityTier === 'qualified') {
48
+ const aDur = a.scoreCell?.durationMedianMin ?? null;
49
+ const bDur = b.scoreCell?.durationMedianMin ?? null;
50
+ if (aDur !== null && bDur !== null) {
51
+ const minDur = Math.min(aDur, bDur);
52
+ const significant = minDur === 0
53
+ ? aDur !== bDur
54
+ : Math.abs(aDur - bDur) / minDur > marginRatio;
55
+ if (significant) return aDur - bDur;
56
+ } else if (aDur !== null || bDur !== null) {
57
+ return aDur !== null ? -1 : 1;
58
+ }
59
+
60
+ // Tie-breaker 1: Speed longRate descending
61
+ const aRate = a.speedLongRate ?? -Infinity;
62
+ const bRate = b.speedLongRate ?? -Infinity;
63
+ if (aRate !== bRate) return bRate - aRate;
64
+
65
+ // Tie-breaker 2: Expiring-soon boost descending
66
+ if (a.expiringBonus !== b.expiringBonus) return b.expiringBonus - a.expiringBonus;
67
+
68
+ // Tie-breaker 3: Even Pace surplus descending
69
+ const aPace = a.paceScore ?? -Infinity;
70
+ const bPace = b.paceScore ?? -Infinity;
71
+ if (aPace !== bPace) return bPace - aPace;
72
+
73
+ // Tie-breaker 4: Configured priority ascending
74
+ return a.priority - b.priority || a.orderIndex - b.orderIndex;
75
+ }
76
+
77
+ // 3. Within trial (or advisory): configured priority first, then expiring boost, Even Pace, Speed longRate
78
+ if (a.priority !== b.priority) return a.priority - b.priority;
79
+ if (a.expiringBonus !== b.expiringBonus) return b.expiringBonus - a.expiringBonus;
80
+ const aPace = a.paceScore ?? -Infinity;
81
+ const bPace = b.paceScore ?? -Infinity;
82
+ if (aPace !== bPace) return bPace - aPace;
83
+ const aRate = a.speedLongRate ?? -Infinity;
84
+ const bRate = b.speedLongRate ?? -Infinity;
85
+ if (aRate !== bRate) return bRate - aRate;
86
+
87
+ return a.orderIndex - b.orderIndex;
88
+ }
89
+
90
+ export function decideDispatch({
91
+ snapshot,
92
+ policy: rawPolicy,
93
+ scoresSummary = null,
94
+ speedMetrics = null,
95
+ request = {},
96
+ now = Date.now(),
97
+ } = {}) {
98
+ const policy = normalizePolicy(rawPolicy);
99
+ const nowMs = now instanceof Date ? now.getTime() : now;
100
+ if (!Number.isFinite(nowMs) || !Number.isFinite(new Date(nowMs).getTime())) {
101
+ throw new Error('Invalid now timestamp');
102
+ }
103
+
104
+ const task = request.task ?? 'general';
105
+ if (!TASKS.includes(task)) {
106
+ throw new Error(`Invalid task "${task}": expected one of ${TASKS.join(', ')}`);
107
+ }
108
+ const tier = request.tier ?? policy.defaultTier ?? null;
109
+ if (tier !== null && !policy.tiers.includes(tier)) {
110
+ throw new Error(`Invalid tier "${tier}": expected one of ${policy.tiers.join(', ')} (tiers come from the config; omit --tier to skip tier gating)`);
111
+ }
112
+ const waitMinutes = request.waitMinutes ?? 0;
113
+ if (!Number.isFinite(waitMinutes) || waitMinutes < 0 || waitMinutes > 1440) {
114
+ throw new Error('Invalid waitMinutes: expected 0..1440');
115
+ }
116
+ const slot = request.slot ?? policy.taskToSlot[task] ?? Object.keys(policy.slots)[0];
117
+ const slotDef = policy.slots[slot];
118
+ if (!slotDef) {
119
+ throw new Error(`Unknown dispatch slot "${slot}": expected one of ${Object.keys(policy.slots).join(', ')} (slots come from the config; omit --slot to use taskToSlot)`);
120
+ }
121
+
122
+ const instances = snapshot?.instances ?? {};
123
+ const audit = [];
124
+ const reasons = [];
125
+
126
+ for (let idx = 0; idx < slotDef.candidates.length; idx++) {
127
+ const candidate = slotDef.candidates[idx];
128
+ const instancePolicy = policy.instances[candidate.instanceId] ?? {};
129
+ const instance = instances[candidate.instanceId] ?? null;
130
+
131
+ // Step 1: Compliance & Scope Gate
132
+ const scopeRejections = [];
133
+ if (candidate.enabled === false || instancePolicy.enabled === false) {
134
+ scopeRejections.push('disabled by policy');
135
+ }
136
+ if (tier !== null) {
137
+ const allowedTiers = candidate.tiers ?? instancePolicy.tiers ?? null;
138
+ if (Array.isArray(allowedTiers) && !allowedTiers.includes(tier)) {
139
+ scopeRejections.push(`tier "${tier}" not allowed (allowed: ${allowedTiers.join(', ')})`);
140
+ }
141
+ }
142
+ const allowedTasks = candidate.tasks ?? instancePolicy.tasks ?? null;
143
+ if (Array.isArray(allowedTasks) && !allowedTasks.includes(task)) {
144
+ scopeRejections.push(`task "${task}" not allowed (allowed: ${allowedTasks.join(', ')})`);
145
+ }
146
+
147
+ if (scopeRejections.length > 0) {
148
+ audit.push({
149
+ candidateId: candidate.id,
150
+ instanceId: candidate.instanceId,
151
+ driver: instance?.driver ?? instancePolicy.driver ?? null,
152
+ model: candidate.model,
153
+ effort: candidate.effort,
154
+ priority: candidate.priority,
155
+ orderIndex: idx,
156
+ compliant: false,
157
+ eligible: false,
158
+ quotaState: 'skipped',
159
+ qualityTier: null,
160
+ rejectionReasons: scopeRejections,
161
+ warnings: [],
162
+ });
163
+ continue;
164
+ }
165
+
166
+ // Step 2: Quota, Even Pace & Reset Credit Gate
167
+ const pacingEval = evaluateInstanceCandidate({
168
+ instance,
169
+ instancePolicy,
170
+ candidate,
171
+ request: { ...request, task, waitMinutes, tier },
172
+ pacingConfig: policy.pacing,
173
+ now: nowMs,
174
+ });
175
+
176
+ // Step 3: Quality × Speed Fusion
177
+ const rawProvider = instancePolicy.scoreProvider ?? instance?.driver ?? candidate.instanceId;
178
+ const executor = {
179
+ provider: rawProvider,
180
+ model: candidate.model,
181
+ effort: candidate.effort ?? 'default',
182
+ tier: candidate.scoreTier ?? candidate.serviceTier ?? 'default',
183
+ };
184
+ const identity = scoreIdentity(executor, policy.scoring.aliases);
185
+ const cell = lookupScoreCell(scoresSummary, identity, task);
186
+ const speedLongRate = resolveSpeedRate(speedMetrics, candidate, identity);
187
+
188
+ const minSamples = policy.scoring.minSamples;
189
+ const minPassRate = policy.scoring.minPassRate;
190
+ let qualityTier = 'trial';
191
+ let qualityEligible = true;
192
+ const qualityWarnings = [];
193
+ const qualityRejections = [];
194
+
195
+ if (cell && cell.n >= minSamples && cell.passRate !== null) {
196
+ if (cell.passRate >= minPassRate) {
197
+ qualityTier = 'qualified';
198
+ } else {
199
+ qualityTier = 'below_threshold';
200
+ const pctStr = `${(cell.passRate * 100).toFixed(1)}%`;
201
+ const minStr = `${(minPassRate * 100).toFixed(1)}%`;
202
+ if (policy.scoring.mode === 'strict') {
203
+ qualityEligible = false;
204
+ qualityRejections.push(`quality below threshold (${pctStr} < ${minStr}, n=${cell.n}, strict mode)`);
205
+ } else if (policy.scoring.mode === 'demote') {
206
+ qualityWarnings.push(`demoted: passRate ${pctStr} < ${minStr} (n=${cell.n})`);
207
+ } else {
208
+ qualityWarnings.push(`advisory: passRate ${pctStr} < ${minStr} (n=${cell.n})`);
209
+ }
210
+ }
211
+ }
212
+
213
+ const combinedWarnings = [...pacingEval.warnings, ...qualityWarnings];
214
+ const rejectionReasons = [
215
+ ...pacingEval.issues,
216
+ ...pacingEval.blockers.map((b) => b.reason),
217
+ ...qualityRejections,
218
+ ];
219
+ const eligible = pacingEval.eligible && qualityEligible;
220
+
221
+ audit.push({
222
+ candidateId: candidate.id,
223
+ instanceId: candidate.instanceId,
224
+ driver: instance?.driver ?? instancePolicy.driver ?? null,
225
+ model: candidate.model,
226
+ effort: candidate.effort,
227
+ options: candidate.options ?? null,
228
+ pool: candidate.pool ?? null,
229
+ priority: candidate.priority,
230
+ orderIndex: idx,
231
+ compliant: true,
232
+ eligible,
233
+ quotaState: pacingEval.quotaState,
234
+ qualityTier,
235
+ scoreIdentity: identity,
236
+ scoreExecutor: executor,
237
+ scoreCell: cell
238
+ ? {
239
+ n: cell.n,
240
+ s: cell.s,
241
+ f: cell.f,
242
+ passRate: cell.passRate,
243
+ interval90: cell.interval90,
244
+ durationMedianMin: cell.durationMedianMin,
245
+ costMedian: cell.costMedian,
246
+ costCurrency: cell.costCurrency,
247
+ }
248
+ : null,
249
+ speedLongRate,
250
+ paceScore: pacingEval.paceScore,
251
+ expiringBonus: pacingEval.expiringBonus,
252
+ availableAfter: pacingEval.availableAfter,
253
+ coveringCredits: pacingEval.coveringCredits,
254
+ applicableWindows: pacingEval.applicableWindows,
255
+ blockers: pacingEval.blockers,
256
+ freshness: pacingEval.freshness,
257
+ checkedAt: pacingEval.checkedAt,
258
+ warnings: combinedWarnings,
259
+ rejectionReasons,
260
+ });
261
+ }
262
+
263
+ // Rank eligible candidates
264
+ const eligibleCandidates = audit.filter((c) => c.eligible).sort((a, b) => compareCandidates(a, b, policy));
265
+ const compliant = audit.filter((c) => c.compliant);
266
+
267
+ // Compute resetEvents & nextCheckAt
268
+ const resetEvents = [];
269
+ const seenWindow = new Set();
270
+ for (const c of compliant) {
271
+ for (const win of c.applicableWindows ?? []) {
272
+ if (win.resetsAt && win.resetsInHours > 0) {
273
+ const key = `${c.instanceId}:${win.id ?? win.label}:${win.resetsAt}`;
274
+ if (!seenWindow.has(key)) {
275
+ seenWindow.add(key);
276
+ resetEvents.push({
277
+ instanceId: c.instanceId,
278
+ windowId: win.id ?? win.label,
279
+ at: win.resetsAt,
280
+ });
281
+ }
282
+ }
283
+ }
284
+ }
285
+ resetEvents.sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
286
+
287
+ const anyStaleOrUnknown = compliant.some((c) => c.quotaState === 'unknown');
288
+ const expiryTimes = compliant
289
+ .filter((c) => c.checkedAt && c.freshness === 'fresh')
290
+ .map((c) => Date.parse(c.checkedAt) + policy.pacing.maxSnapshotAgeMinutes * 60000);
291
+
292
+ let nextCheckAtMs = anyStaleOrUnknown
293
+ ? nowMs
294
+ : Math.min(
295
+ nowMs + policy.pacing.recheckAfterMinutes * 60000,
296
+ ...resetEvents.map((e) => Date.parse(e.at)),
297
+ ...expiryTimes,
298
+ );
299
+
300
+ let action = 'pause';
301
+ let recommended = null;
302
+ let waitUntil = null;
303
+ let redeemCandidate = null;
304
+
305
+ if (eligibleCandidates.length > 0) {
306
+ const winner = eligibleCandidates[0];
307
+ action = 'run';
308
+ recommended = {
309
+ candidateId: winner.candidateId,
310
+ instanceId: winner.instanceId,
311
+ driver: winner.driver,
312
+ model: winner.model,
313
+ effort: winner.effort,
314
+ options: winner.options,
315
+ target: {
316
+ providerInstanceId: winner.instanceId,
317
+ model: winner.model,
318
+ ...(winner.options ? { options: winner.options } : {}),
319
+ },
320
+ delegateReady: true,
321
+ quotaState: winner.quotaState,
322
+ qualityTier: winner.qualityTier,
323
+ scoreIdentity: winner.scoreIdentity,
324
+ executor: winner.scoreExecutor,
325
+ paceScore: winner.paceScore,
326
+ warnings: winner.warnings,
327
+ };
328
+ reasons.push(
329
+ `Selected ${winner.candidateId} (${winner.instanceId}/${winner.model}) for slot=${slot}, task=${task}` +
330
+ (tier ? `, tier=${tier}` : '') +
331
+ ` [quota=${winner.quotaState}, quality=${winner.qualityTier}` +
332
+ (winner.scoreCell?.durationMedianMin != null ? `, median=${winner.scoreCell.durationMedianMin.toFixed(1)}m` : '') +
333
+ (winner.speedLongRate != null ? `, speed=${winner.speedLongRate} tok/s` : '') +
334
+ `].`,
335
+ );
336
+ if (winner.warnings.length > 0) {
337
+ reasons.push(`Warnings: ${winner.warnings.join('; ')}.`);
338
+ }
339
+ } else {
340
+ // Check wait budget
341
+ const waitable = compliant
342
+ .filter((c) => ['exhausted', 'low'].includes(c.quotaState) && c.availableAfter)
343
+ .filter((c) => (Date.parse(c.availableAfter) - nowMs) / 60000 <= waitMinutes)
344
+ .sort((a, b) => Date.parse(a.availableAfter) - Date.parse(b.availableAfter));
345
+
346
+ const redeemable = compliant.find((c) => c.quotaState === 'credit_redeem');
347
+
348
+ if (waitable.length > 0) {
349
+ action = 'wait';
350
+ waitUntil = waitable[0].availableAfter;
351
+ nextCheckAtMs = Date.parse(waitUntil);
352
+ reasons.push(
353
+ `No candidate currently eligible; ${waitable[0].candidateId} resets at ${waitUntil} (within ${waitMinutes}m wait budget).`,
354
+ );
355
+ } else if (redeemable) {
356
+ action = 'redeem';
357
+ nextCheckAtMs = nowMs;
358
+ const card = redeemable.coveringCredits[0];
359
+ redeemCandidate = {
360
+ candidateId: redeemable.candidateId,
361
+ instanceId: redeemable.instanceId,
362
+ driver: redeemable.driver,
363
+ creditId: card?.creditId ?? null,
364
+ resetType: card?.resetType ?? null,
365
+ expiresAt: card?.expiresAt ?? null,
366
+ };
367
+ reasons.push(
368
+ `No candidate available naturally; redeem reset credit "${card?.creditId}" (${card?.resetType}) on ${redeemable.instanceId} and re-query.`,
369
+ );
370
+ } else if (anyStaleOrUnknown) {
371
+ action = 'refresh';
372
+ reasons.push('Relevant provider snapshot is missing, stale, or unavailable; refresh usage snapshot before dispatching (live: use --t3-auto or --t3-origin; replaying a saved file: pass --now close to its observedAt).');
373
+ } else {
374
+ action = 'pause';
375
+ reasons.push('All compliant candidates are blocked by quota or strict quality gates; retry after nextCheckAt, raise --wait-minutes, or relax the config (scoring.mode, pacing thresholds).');
376
+ }
377
+ }
378
+
379
+ for (const c of audit) {
380
+ if (c.candidateId === recommended?.candidateId) continue;
381
+ if (!c.compliant) {
382
+ reasons.push(`Skipped ${c.candidateId}: ${c.rejectionReasons.join('; ')}.`);
383
+ } else if (!c.eligible) {
384
+ reasons.push(`Blocked ${c.candidateId} (${c.quotaState}): ${c.rejectionReasons.join('; ')}.`);
385
+ }
386
+ }
387
+
388
+ return {
389
+ action,
390
+ slot,
391
+ task,
392
+ tier,
393
+ recommended,
394
+ waitUntil,
395
+ redeemCandidate,
396
+ nextCheckAt: new Date(nextCheckAtMs).toISOString(),
397
+ resetEvents,
398
+ reasons,
399
+ candidates: audit,
400
+ rankedEligibleIds: eligibleCandidates.map((c) => c.candidateId),
401
+ };
402
+ }
403
+
404
+ export function formatDecisionText(decision, { lang = 'en' } = {}) {
405
+ const zh = lang === 'zh';
406
+ const lines = [];
407
+ if (decision.action === 'run' && decision.recommended) {
408
+ const r = decision.recommended;
409
+ lines.push(
410
+ zh
411
+ ? `建议动作: run → ${r.instanceId} / ${r.model} (槽位 ${decision.slot}, 任务 ${decision.task}${decision.tier ? `, 档位 ${decision.tier}` : ''})`
412
+ : `Action: run -> ${r.instanceId} / ${r.model} (slot=${decision.slot}, task=${decision.task}${decision.tier ? `, tier=${decision.tier}` : ''})`,
413
+ );
414
+ lines.push(
415
+ zh
416
+ ? `delegate_task target: ${JSON.stringify(r.target)}`
417
+ : `delegate_task target: ${JSON.stringify(r.target)}`,
418
+ );
419
+ } else {
420
+ lines.push(
421
+ zh
422
+ ? `建议动作: ${decision.action}${decision.waitUntil ? ` (等待至 ${decision.waitUntil})` : ''}`
423
+ : `Action: ${decision.action}${decision.waitUntil ? ` (waitUntil ${decision.waitUntil})` : ''}`,
424
+ );
425
+ }
426
+ for (const reason of decision.reasons) {
427
+ lines.push(`- ${reason}`);
428
+ }
429
+ lines.push(
430
+ zh
431
+ ? `下次检查: ${decision.nextCheckAt}`
432
+ : `Next check: ${decision.nextCheckAt}`,
433
+ );
434
+ return lines.join('\n') + '\n';
435
+ }