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,569 @@
|
|
|
1
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_PACING_CONFIG = Object.freeze({
|
|
4
|
+
paceMarginPercent: 10,
|
|
5
|
+
longTaskMinRemainingPercent: 30,
|
|
6
|
+
defaultMinRemainingPercent: 20,
|
|
7
|
+
shortWindowMaxUsedPercent: 90,
|
|
8
|
+
recheckAfterMinutes: 15,
|
|
9
|
+
maxSnapshotAgeMinutes: 15,
|
|
10
|
+
resetCredit: {
|
|
11
|
+
skipIfResetWithinHours: 6,
|
|
12
|
+
expiryWarnHours: 72,
|
|
13
|
+
},
|
|
14
|
+
expiringBoost: {
|
|
15
|
+
resetWithinHours: 24,
|
|
16
|
+
minRemainingPercent: 30,
|
|
17
|
+
maxShortUsedPercent: 70,
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const isPercent = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 100;
|
|
22
|
+
|
|
23
|
+
function parseTimestampMs(value) {
|
|
24
|
+
if (value == null) return null;
|
|
25
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
26
|
+
const ms = value < 1e12 ? value * 1000 : value;
|
|
27
|
+
return Number.isFinite(new Date(ms).getTime()) ? ms : NaN;
|
|
28
|
+
}
|
|
29
|
+
if (typeof value === 'string' && value.trim()) {
|
|
30
|
+
const ms = Date.parse(value);
|
|
31
|
+
return Number.isFinite(ms) ? ms : NaN;
|
|
32
|
+
}
|
|
33
|
+
return NaN;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function inferAntigravityPool(model) {
|
|
37
|
+
if (typeof model !== 'string' || !model.trim()) return null;
|
|
38
|
+
const base = model.slice(model.lastIndexOf('/') + 1).toLowerCase();
|
|
39
|
+
if (base.includes('argon')) return 'argon';
|
|
40
|
+
if (base.includes('carbon')) return 'carbon';
|
|
41
|
+
if (base.startsWith('gemini')) return 'gemini';
|
|
42
|
+
if (base.startsWith('claude')) return 'claude';
|
|
43
|
+
if (base.startsWith('gpt')) return 'gpt';
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function evaluateWindow(win, { now = Date.now(), paceMarginPercent = 10 } = {}) {
|
|
48
|
+
if (!isObject(win)) {
|
|
49
|
+
return { valid: false, issue: 'Window must be an object' };
|
|
50
|
+
}
|
|
51
|
+
const nowMs = now instanceof Date ? now.getTime() : now;
|
|
52
|
+
const hasUsed = win.usedPercent != null;
|
|
53
|
+
const hasRem = win.remainingPercent != null;
|
|
54
|
+
if (!hasUsed && !hasRem) {
|
|
55
|
+
return { valid: false, issue: `Window ${win.id ?? 'unknown'} missing percentage` };
|
|
56
|
+
}
|
|
57
|
+
if ((hasUsed && !isPercent(win.usedPercent)) || (hasRem && !isPercent(win.remainingPercent))) {
|
|
58
|
+
return { valid: false, issue: `Window ${win.id ?? 'unknown'} percentage out of range 0..100` };
|
|
59
|
+
}
|
|
60
|
+
if (hasUsed && hasRem && Math.abs(win.usedPercent + win.remainingPercent - 100) > 1) {
|
|
61
|
+
return { valid: false, issue: `Window ${win.id ?? 'unknown'} usedPercent + remainingPercent mismatch` };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const usedPercent = hasUsed ? win.usedPercent : 100 - win.remainingPercent;
|
|
65
|
+
const remainingPercent = hasRem ? win.remainingPercent : 100 - win.usedPercent;
|
|
66
|
+
const effectiveRemainingPercent = hasUsed && hasRem
|
|
67
|
+
? Math.min(win.remainingPercent, 100 - win.usedPercent)
|
|
68
|
+
: remainingPercent;
|
|
69
|
+
|
|
70
|
+
const resetsAtMs = parseTimestampMs(win.resetsAt);
|
|
71
|
+
if (win.resetsAt != null && Number.isNaN(resetsAtMs)) {
|
|
72
|
+
return { valid: false, issue: `Window ${win.id ?? 'unknown'} invalid resetsAt` };
|
|
73
|
+
}
|
|
74
|
+
const duration = win.windowDurationMins;
|
|
75
|
+
if (duration != null && (!Number.isFinite(duration) || duration <= 0)) {
|
|
76
|
+
return { valid: false, issue: `Window ${win.id ?? 'unknown'} invalid windowDurationMins` };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const resetsAt = resetsAtMs !== null ? new Date(resetsAtMs).toISOString() : null;
|
|
80
|
+
const resetsInMins = resetsAtMs !== null ? (resetsAtMs - nowMs) / 60000 : null;
|
|
81
|
+
const resetsInHours = resetsInMins !== null ? resetsInMins / 60 : null;
|
|
82
|
+
const expiredReset = resetsInMins !== null && resetsInMins <= 0;
|
|
83
|
+
|
|
84
|
+
const remainingTimePercent = Number.isFinite(duration) && duration > 0
|
|
85
|
+
&& resetsInMins !== null && resetsInMins > 0 && resetsInMins <= duration
|
|
86
|
+
? (resetsInMins / duration) * 100
|
|
87
|
+
: null;
|
|
88
|
+
|
|
89
|
+
const paceBalancePercent = remainingTimePercent !== null
|
|
90
|
+
? effectiveRemainingPercent - remainingTimePercent
|
|
91
|
+
: null;
|
|
92
|
+
|
|
93
|
+
const pace = paceBalancePercent === null
|
|
94
|
+
? 'unknown'
|
|
95
|
+
: paceBalancePercent >= paceMarginPercent
|
|
96
|
+
? 'surplus'
|
|
97
|
+
: paceBalancePercent <= -paceMarginPercent
|
|
98
|
+
? 'conserve'
|
|
99
|
+
: 'balanced';
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
valid: true,
|
|
103
|
+
id: win.id ?? null,
|
|
104
|
+
kind: win.kind ?? 'other',
|
|
105
|
+
label: win.label ?? win.id ?? 'window',
|
|
106
|
+
pool: win.pool ?? null,
|
|
107
|
+
modelIds: Array.isArray(win.modelIds) ? win.modelIds : null,
|
|
108
|
+
providerIds: Array.isArray(win.providerIds) ? win.providerIds : null,
|
|
109
|
+
applicableByDefault: win.applicableByDefault !== false,
|
|
110
|
+
usedPercent,
|
|
111
|
+
remainingPercent,
|
|
112
|
+
effectiveRemainingPercent,
|
|
113
|
+
resetsAt,
|
|
114
|
+
resetsAtMs,
|
|
115
|
+
resetsInMins,
|
|
116
|
+
resetsInHours,
|
|
117
|
+
expiredReset,
|
|
118
|
+
windowDurationMins: Number.isFinite(duration) && duration > 0 ? duration : null,
|
|
119
|
+
remainingTimePercent,
|
|
120
|
+
paceBalancePercent,
|
|
121
|
+
pace,
|
|
122
|
+
creditAdjustedBalancePercent: paceBalancePercent,
|
|
123
|
+
creditAdjustedPace: pace,
|
|
124
|
+
creditBacked: false,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function isWindowApplicable(win, { driver, model = null, pool = null, claudeModel = null } = {}) {
|
|
129
|
+
if (win.applicableByDefault === false) return false;
|
|
130
|
+
|
|
131
|
+
const baseModel = typeof model === 'string' && model.trim()
|
|
132
|
+
? model.slice(model.lastIndexOf('/') + 1)
|
|
133
|
+
: null;
|
|
134
|
+
|
|
135
|
+
if (Array.isArray(win.modelIds) && win.modelIds.length > 0) {
|
|
136
|
+
if (!model) return false;
|
|
137
|
+
const matches = win.modelIds.includes(model) || (baseModel && win.modelIds.includes(baseModel));
|
|
138
|
+
if (!matches) return false;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (Array.isArray(win.providerIds) && win.providerIds.length > 0 && model) {
|
|
142
|
+
const prefix = model.includes('/') ? model.split('/')[0] : null;
|
|
143
|
+
if (prefix && !win.providerIds.includes(prefix)) return false;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (driver === 'antigravity' || driver === 'gemini' || pool) {
|
|
147
|
+
const candPool = (pool ?? inferAntigravityPool(model))?.toLowerCase() ?? null;
|
|
148
|
+
const winPool = win.pool?.toLowerCase() ?? null;
|
|
149
|
+
if (candPool && winPool) {
|
|
150
|
+
if (candPool !== winPool) {
|
|
151
|
+
const threePartyWindowCovers = winPool === '3p' && (candPool === 'claude' || candPool === 'gpt');
|
|
152
|
+
const threePartyCandCovers = candPool === '3p' && (winPool === 'claude' || winPool === 'gpt');
|
|
153
|
+
if (!threePartyWindowCovers && !threePartyCandCovers) return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if ((driver === 'claudeAgent' || driver === 'claude') && typeof win.id === 'string' && win.id.startsWith('seven_day_')) {
|
|
159
|
+
const suffix = win.id.slice('seven_day_'.length).toLowerCase();
|
|
160
|
+
const explicitClaudeModel = claudeModel?.trim().toLowerCase() ?? null;
|
|
161
|
+
if (explicitClaudeModel) {
|
|
162
|
+
return explicitClaudeModel === suffix;
|
|
163
|
+
}
|
|
164
|
+
if (baseModel) {
|
|
165
|
+
const tokens = baseModel.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
166
|
+
return tokens.includes(suffix);
|
|
167
|
+
}
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (driver === 'opencode' && typeof win.id === 'string' && win.id.startsWith('go_') && model) {
|
|
172
|
+
if (!model.startsWith('opencode-go/')) return false;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function cardCoversWindow(card, win) {
|
|
179
|
+
if (!card || !win) return false;
|
|
180
|
+
if (Array.isArray(card.coversWindowIds) && card.coversWindowIds.length > 0) {
|
|
181
|
+
return card.coversWindowIds.includes(win.id);
|
|
182
|
+
}
|
|
183
|
+
if (Array.isArray(card.coversWindowPrefixes) && card.coversWindowPrefixes.length > 0) {
|
|
184
|
+
return typeof win.id === 'string' && card.coversWindowPrefixes.some((p) => win.id.startsWith(p));
|
|
185
|
+
}
|
|
186
|
+
switch (card.resetType) {
|
|
187
|
+
case 'claudeSession':
|
|
188
|
+
return win.id === 'five_hour';
|
|
189
|
+
case 'claudeWeekly':
|
|
190
|
+
return win.id === 'seven_day' || (typeof win.id === 'string' && win.id.startsWith('seven_day_'));
|
|
191
|
+
case 'claudeFable':
|
|
192
|
+
return win.id === 'seven_day_fable';
|
|
193
|
+
case 'claudeFull':
|
|
194
|
+
case 'codexRateLimits':
|
|
195
|
+
case 'custom':
|
|
196
|
+
default:
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function evaluateFreshness(checkedAt, nowMs, maxSnapshotAgeMinutes = 15) {
|
|
202
|
+
if (!checkedAt) return { freshness: 'unknown', ageMinutes: null, checkedAtIso: null };
|
|
203
|
+
const ms = parseTimestampMs(checkedAt);
|
|
204
|
+
if (Number.isNaN(ms)) return { freshness: 'unknown', ageMinutes: null, checkedAtIso: null };
|
|
205
|
+
const ageMinutes = (nowMs - ms) / 60000;
|
|
206
|
+
const freshness = ageMinutes < 0
|
|
207
|
+
? 'future'
|
|
208
|
+
: ageMinutes >= maxSnapshotAgeMinutes
|
|
209
|
+
? 'stale'
|
|
210
|
+
: 'fresh';
|
|
211
|
+
return { freshness, ageMinutes, checkedAtIso: new Date(ms).toISOString() };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function evaluateBudget(budget, nowMs) {
|
|
215
|
+
if (!budget || !isObject(budget)) return null;
|
|
216
|
+
const spent = Number.isFinite(budget.spent) ? budget.spent : 0;
|
|
217
|
+
const limit = Number.isFinite(budget.budget) && budget.budget > 0 ? budget.budget : null;
|
|
218
|
+
const balance = Number.isFinite(budget.balance) ? budget.balance : null;
|
|
219
|
+
const isAvailable = budget.isAvailable !== false;
|
|
220
|
+
const resetsAtMs = parseTimestampMs(budget.resetsAt);
|
|
221
|
+
const resetsAt = resetsAtMs && !Number.isNaN(resetsAtMs) ? new Date(resetsAtMs).toISOString() : null;
|
|
222
|
+
|
|
223
|
+
const budgetRemainingPct = limit !== null ? Math.max(0, ((limit - spent) / limit) * 100) : null;
|
|
224
|
+
const balanceRemainingPct = limit !== null && balance !== null
|
|
225
|
+
? (isAvailable ? Math.max(0, (balance / limit) * 100) : 0)
|
|
226
|
+
: null;
|
|
227
|
+
const remainingPercent = budgetRemainingPct !== null && balanceRemainingPct !== null
|
|
228
|
+
? Math.min(budgetRemainingPct, balanceRemainingPct)
|
|
229
|
+
: (budgetRemainingPct ?? (balance !== null && balance <= 0 ? 0 : null));
|
|
230
|
+
|
|
231
|
+
const blockers = [];
|
|
232
|
+
if (!isAvailable) {
|
|
233
|
+
blockers.push({
|
|
234
|
+
windowId: 'account-balance',
|
|
235
|
+
state: 'exhausted',
|
|
236
|
+
remainingPercent: 0,
|
|
237
|
+
minimumRemainingPercent: 0,
|
|
238
|
+
resetsAt: null,
|
|
239
|
+
reason: 'Pay-as-you-go account marked unavailable',
|
|
240
|
+
});
|
|
241
|
+
} else if (balance !== null && balance <= 0) {
|
|
242
|
+
blockers.push({
|
|
243
|
+
windowId: 'account-balance',
|
|
244
|
+
state: 'exhausted',
|
|
245
|
+
remainingPercent: 0,
|
|
246
|
+
minimumRemainingPercent: 0,
|
|
247
|
+
resetsAt: null,
|
|
248
|
+
reason: `Account balance exhausted (${balance})`,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
if (limit !== null && spent >= limit) {
|
|
252
|
+
blockers.push({
|
|
253
|
+
windowId: 'monthly-budget',
|
|
254
|
+
state: 'exhausted',
|
|
255
|
+
remainingPercent: 0,
|
|
256
|
+
minimumRemainingPercent: 0,
|
|
257
|
+
resetsAt: resetsAtMs && resetsAtMs > nowMs ? resetsAt : null,
|
|
258
|
+
reason: `Spent ${spent} reached budget ${limit}`,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return {
|
|
263
|
+
spent,
|
|
264
|
+
budget: limit,
|
|
265
|
+
balance,
|
|
266
|
+
isAvailable,
|
|
267
|
+
remainingPercent,
|
|
268
|
+
resetsAt,
|
|
269
|
+
blockers,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function evaluateInstanceCandidate({
|
|
274
|
+
instance,
|
|
275
|
+
instancePolicy = {},
|
|
276
|
+
candidate = {},
|
|
277
|
+
request = {},
|
|
278
|
+
pacingConfig = DEFAULT_PACING_CONFIG,
|
|
279
|
+
now = Date.now(),
|
|
280
|
+
} = {}) {
|
|
281
|
+
const nowMs = now instanceof Date ? now.getTime() : now;
|
|
282
|
+
const task = request.task ?? 'general';
|
|
283
|
+
const waitMinutes = Number.isFinite(request.waitMinutes) ? request.waitMinutes : 0;
|
|
284
|
+
const margin = pacingConfig.paceMarginPercent ?? 10;
|
|
285
|
+
|
|
286
|
+
if (!instance) {
|
|
287
|
+
return {
|
|
288
|
+
quotaState: 'unknown',
|
|
289
|
+
eligible: false,
|
|
290
|
+
freshness: 'unknown',
|
|
291
|
+
ageMinutes: null,
|
|
292
|
+
checkedAt: null,
|
|
293
|
+
windows: [],
|
|
294
|
+
applicableWindows: [],
|
|
295
|
+
blockers: [],
|
|
296
|
+
issues: ['Instance not found in snapshot'],
|
|
297
|
+
warnings: [],
|
|
298
|
+
usableCredits: [],
|
|
299
|
+
coveringCredits: [],
|
|
300
|
+
availableAfter: null,
|
|
301
|
+
paceScore: null,
|
|
302
|
+
expiringBonus: 0,
|
|
303
|
+
budgetView: null,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (instance.enabled === false || instance.status === 'disabled') {
|
|
308
|
+
return {
|
|
309
|
+
quotaState: 'disabled',
|
|
310
|
+
eligible: false,
|
|
311
|
+
freshness: 'unknown',
|
|
312
|
+
ageMinutes: null,
|
|
313
|
+
checkedAt: instance.checkedAt ?? null,
|
|
314
|
+
windows: [],
|
|
315
|
+
applicableWindows: [],
|
|
316
|
+
blockers: [],
|
|
317
|
+
issues: [],
|
|
318
|
+
warnings: [],
|
|
319
|
+
usableCredits: [],
|
|
320
|
+
coveringCredits: [],
|
|
321
|
+
availableAfter: null,
|
|
322
|
+
paceScore: null,
|
|
323
|
+
expiringBonus: 0,
|
|
324
|
+
budgetView: null,
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const issues = [];
|
|
329
|
+
const warnings = [];
|
|
330
|
+
const { freshness, ageMinutes, checkedAtIso } = evaluateFreshness(
|
|
331
|
+
instance.checkedAt,
|
|
332
|
+
nowMs,
|
|
333
|
+
pacingConfig.maxSnapshotAgeMinutes ?? 15,
|
|
334
|
+
);
|
|
335
|
+
|
|
336
|
+
if (instance.status === 'unavailable' || instance.status === 'not_applicable') {
|
|
337
|
+
issues.push(instance.detail || `Instance status is ${instance.status}`);
|
|
338
|
+
} else if (freshness === 'stale' || freshness === 'future') {
|
|
339
|
+
issues.push(`Snapshot is ${freshness} (age ${ageMinutes?.toFixed(1)}m)`);
|
|
340
|
+
} else if (freshness === 'unknown') {
|
|
341
|
+
warnings.push('Snapshot timestamp missing; freshness unknown');
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// Evaluate reset credits
|
|
345
|
+
const rawCards = Array.isArray(instance.resetCredits?.cards) ? instance.resetCredits.cards : [];
|
|
346
|
+
const creditsKnown = instance.resetCredits?.known === true;
|
|
347
|
+
const usableCredits = creditsKnown
|
|
348
|
+
? rawCards
|
|
349
|
+
.map((card) => {
|
|
350
|
+
const expMs = parseTimestampMs(card.expiresAt);
|
|
351
|
+
const expiresInHours = expMs !== null && !Number.isNaN(expMs) ? (expMs - nowMs) / 3600000 : null;
|
|
352
|
+
const usable = card.status === 'available'
|
|
353
|
+
&& Number.isSafeInteger(card.resetsLeft)
|
|
354
|
+
&& card.resetsLeft >= 1
|
|
355
|
+
&& (expiresInHours === null || expiresInHours > 0);
|
|
356
|
+
return { ...card, expiresInHours, usable };
|
|
357
|
+
})
|
|
358
|
+
.filter((card) => card.usable)
|
|
359
|
+
.sort((a, b) => (a.expiresInHours ?? Infinity) - (b.expiresInHours ?? Infinity))
|
|
360
|
+
: [];
|
|
361
|
+
|
|
362
|
+
const expiryWarnHours = pacingConfig.resetCredit?.expiryWarnHours ?? 72;
|
|
363
|
+
if (usableCredits.length > 0 && usableCredits[0].expiresInHours !== null && usableCredits[0].expiresInHours <= expiryWarnHours) {
|
|
364
|
+
warnings.push(`Reset credit ${usableCredits[0].creditId} expires in ${usableCredits[0].expiresInHours.toFixed(1)}h`);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// Evaluate windows
|
|
368
|
+
const evaluatedWindows = [];
|
|
369
|
+
for (const rawWin of Array.isArray(instance.windows) ? instance.windows : []) {
|
|
370
|
+
const win = evaluateWindow(rawWin, { now: nowMs, paceMarginPercent: margin });
|
|
371
|
+
if (!win.valid) {
|
|
372
|
+
issues.push(win.issue);
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
if (win.paceBalancePercent !== null && usableCredits.length > 0) {
|
|
376
|
+
const exhaustionAt = nowMs + (win.effectiveRemainingPercent / 100) * win.windowDurationMins * 60000;
|
|
377
|
+
const backed = win.resetsAtMs !== null
|
|
378
|
+
&& exhaustionAt < win.resetsAtMs
|
|
379
|
+
&& usableCredits.some((card) => cardCoversWindow(card, win) && (card.expiresAt == null || Date.parse(card.expiresAt) > exhaustionAt));
|
|
380
|
+
if (backed) {
|
|
381
|
+
const adjusted = win.paceBalancePercent + 100;
|
|
382
|
+
win.creditBacked = true;
|
|
383
|
+
win.creditAdjustedBalancePercent = adjusted;
|
|
384
|
+
win.creditAdjustedPace = adjusted >= margin ? 'surplus' : adjusted <= -margin ? 'conserve' : 'balanced';
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
evaluatedWindows.push(win);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const applicableWindows = evaluatedWindows.filter((win) =>
|
|
391
|
+
isWindowApplicable(win, {
|
|
392
|
+
driver: instance.driver,
|
|
393
|
+
model: candidate.model ?? request.model ?? null,
|
|
394
|
+
pool: candidate.pool ?? request.pool ?? null,
|
|
395
|
+
claudeModel: request.claudeModel ?? candidate.claudeModel ?? null,
|
|
396
|
+
}),
|
|
397
|
+
);
|
|
398
|
+
|
|
399
|
+
for (const win of applicableWindows) {
|
|
400
|
+
if (win.expiredReset) {
|
|
401
|
+
issues.push(`Window ${win.id ?? win.label} reset timestamp (${win.resetsAt}) has already passed`);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// Evaluate budget
|
|
406
|
+
const budgetView = evaluateBudget(instance.budget, nowMs);
|
|
407
|
+
const blockers = [];
|
|
408
|
+
if (budgetView) {
|
|
409
|
+
blockers.push(...budgetView.blockers);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
if (instance.status === 'ready' && applicableWindows.length === 0 && !budgetView) {
|
|
413
|
+
// Allow zeroSpendCap or explicit API/custom without quota windows if marked ready,
|
|
414
|
+
// otherwise warn if windows were expected
|
|
415
|
+
if (['codex', 'claudeAgent', 'claude', 'antigravity'].includes(instance.driver)) {
|
|
416
|
+
warnings.push('No applicable usage windows reported for candidate');
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// Gate applicable windows
|
|
421
|
+
for (const win of applicableWindows) {
|
|
422
|
+
const isShort = (win.windowDurationMins !== null && win.windowDurationMins < 1440) || win.kind === 'session';
|
|
423
|
+
const rem = win.effectiveRemainingPercent;
|
|
424
|
+
|
|
425
|
+
if (isShort) {
|
|
426
|
+
const maxUsed = candidate.maxShortUsedPercent
|
|
427
|
+
?? instancePolicy.shortWindowMaxUsedPercent
|
|
428
|
+
?? pacingConfig.shortWindowMaxUsedPercent
|
|
429
|
+
?? 90;
|
|
430
|
+
const floor = Math.max(0, 100 - maxUsed);
|
|
431
|
+
if (rem === 0 || win.usedPercent >= maxUsed || rem < floor) {
|
|
432
|
+
const state = rem === 0 ? 'exhausted' : 'low';
|
|
433
|
+
blockers.push({
|
|
434
|
+
windowId: win.id ?? win.label,
|
|
435
|
+
state,
|
|
436
|
+
remainingPercent: rem,
|
|
437
|
+
usedPercent: win.usedPercent,
|
|
438
|
+
minimumRemainingPercent: floor,
|
|
439
|
+
maxUsedPercent: maxUsed,
|
|
440
|
+
resetsAt: win.resetsAt,
|
|
441
|
+
reason: `${win.id ?? win.label} ${state}: remaining ${rem.toFixed(1)}% (used ${win.usedPercent.toFixed(1)}%, max allowed ${maxUsed}%)`,
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const isLong = (win.windowDurationMins !== null && win.windowDurationMins >= 1440) || win.kind === 'weekly' || win.kind === 'monthly';
|
|
448
|
+
if (isLong && win.remainingTimePercent !== null) {
|
|
449
|
+
const balance = win.creditAdjustedBalancePercent ?? win.paceBalancePercent;
|
|
450
|
+
const lagging = task === 'long' ? balance < 0 : balance < -margin;
|
|
451
|
+
const floor = task === 'long'
|
|
452
|
+
? win.remainingTimePercent
|
|
453
|
+
: Math.max(0, win.remainingTimePercent - margin);
|
|
454
|
+
if (rem === 0 || lagging) {
|
|
455
|
+
const state = rem === 0 ? 'exhausted' : 'low';
|
|
456
|
+
blockers.push({
|
|
457
|
+
windowId: win.id ?? win.label,
|
|
458
|
+
state,
|
|
459
|
+
remainingPercent: rem,
|
|
460
|
+
minimumRemainingPercent: floor,
|
|
461
|
+
paceBalancePercent: balance,
|
|
462
|
+
resetsAt: win.resetsAt,
|
|
463
|
+
reason: `${win.id ?? win.label} ${state} (Even Pace): remaining ${rem.toFixed(1)}%, pace floor ${floor.toFixed(1)}%`,
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
} else {
|
|
467
|
+
const baseFloor = candidate.minRemainingPercent
|
|
468
|
+
?? instancePolicy.weeklyMinRemainingPercent
|
|
469
|
+
?? pacingConfig.defaultMinRemainingPercent
|
|
470
|
+
?? 20;
|
|
471
|
+
const floor = task === 'long'
|
|
472
|
+
? Math.max(baseFloor, pacingConfig.longTaskMinRemainingPercent ?? 30)
|
|
473
|
+
: baseFloor;
|
|
474
|
+
if (rem === 0 || rem < floor) {
|
|
475
|
+
const state = rem === 0 ? 'exhausted' : 'low';
|
|
476
|
+
blockers.push({
|
|
477
|
+
windowId: win.id ?? win.label,
|
|
478
|
+
state,
|
|
479
|
+
remainingPercent: rem,
|
|
480
|
+
minimumRemainingPercent: floor,
|
|
481
|
+
resetsAt: win.resetsAt,
|
|
482
|
+
reason: `${win.id ?? win.label} ${state}: remaining ${rem.toFixed(1)}%, floor ${floor.toFixed(1)}%`,
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
const availableAfter = blockers.length > 0 && blockers.every((b) => b.resetsAt && Date.parse(b.resetsAt) > nowMs)
|
|
489
|
+
? new Date(Math.max(...blockers.map((b) => Date.parse(b.resetsAt)))).toISOString()
|
|
490
|
+
: null;
|
|
491
|
+
|
|
492
|
+
const coveringCredits = blockers.length > 0
|
|
493
|
+
? usableCredits.filter((card) =>
|
|
494
|
+
blockers.some((b) => {
|
|
495
|
+
const win = applicableWindows.find((w) => (w.id ?? w.label) === b.windowId);
|
|
496
|
+
return win && cardCoversWindow(card, win);
|
|
497
|
+
}),
|
|
498
|
+
)
|
|
499
|
+
: [];
|
|
500
|
+
|
|
501
|
+
let quotaState = 'available';
|
|
502
|
+
if (issues.length > 0) {
|
|
503
|
+
quotaState = 'unknown';
|
|
504
|
+
} else if (blockers.length > 0) {
|
|
505
|
+
const anyExhausted = blockers.some((b) => b.state === 'exhausted');
|
|
506
|
+
const skipHours = pacingConfig.resetCredit?.skipIfResetWithinHours ?? 6;
|
|
507
|
+
const resetNear = availableAfter !== null
|
|
508
|
+
&& (Date.parse(availableAfter) - nowMs) / 60000 <= Math.max(waitMinutes, skipHours * 60);
|
|
509
|
+
|
|
510
|
+
if (coveringCredits.length > 0 && !resetNear && candidate.allowRedeem !== false) {
|
|
511
|
+
quotaState = anyExhausted ? 'credit_redeem' : 'credit_low';
|
|
512
|
+
if (quotaState === 'credit_low') {
|
|
513
|
+
warnings.push('Running below floor backed by reset credit; manual redeem needed if exhausted');
|
|
514
|
+
}
|
|
515
|
+
} else {
|
|
516
|
+
quotaState = anyExhausted ? 'exhausted' : 'low';
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// Compute paceScore & expiringBonus for tie-breaking across sibling instances
|
|
521
|
+
const pacedWindows = applicableWindows.filter((w) => w.paceBalancePercent !== null);
|
|
522
|
+
let paceScore = null;
|
|
523
|
+
if (pacedWindows.length > 0) {
|
|
524
|
+
paceScore = Math.min(...pacedWindows.map((w) => w.creditAdjustedBalancePercent ?? w.paceBalancePercent));
|
|
525
|
+
} else if (applicableWindows.length > 0) {
|
|
526
|
+
paceScore = Math.min(...applicableWindows.map((w) => w.effectiveRemainingPercent)) - 50;
|
|
527
|
+
} else if (budgetView?.remainingPercent != null) {
|
|
528
|
+
paceScore = budgetView.remainingPercent - 50;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
let expiringBonus = 0;
|
|
532
|
+
const boost = pacingConfig.expiringBoost;
|
|
533
|
+
if (boost && (quotaState === 'available' || quotaState === 'credit_low')) {
|
|
534
|
+
const shortHot = applicableWindows.some(
|
|
535
|
+
(w) => ((w.windowDurationMins !== null && w.windowDurationMins < 1440) || w.kind === 'session')
|
|
536
|
+
&& w.usedPercent >= (boost.maxShortUsedPercent ?? 70),
|
|
537
|
+
);
|
|
538
|
+
const hasExpiringSurplus = !shortHot && applicableWindows.some(
|
|
539
|
+
(w) => (w.windowDurationMins === null || w.windowDurationMins >= 1440)
|
|
540
|
+
&& w.resetsInHours !== null
|
|
541
|
+
&& w.resetsInHours > 0
|
|
542
|
+
&& w.resetsInHours <= (boost.resetWithinHours ?? 24)
|
|
543
|
+
&& w.effectiveRemainingPercent >= (boost.minRemainingPercent ?? 30)
|
|
544
|
+
&& (w.creditAdjustedPace === 'surplus' || w.pace === 'surplus'),
|
|
545
|
+
);
|
|
546
|
+
if (hasExpiringSurplus) {
|
|
547
|
+
expiringBonus = 1;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
return {
|
|
552
|
+
quotaState,
|
|
553
|
+
eligible: quotaState === 'available' || quotaState === 'credit_low',
|
|
554
|
+
freshness,
|
|
555
|
+
ageMinutes,
|
|
556
|
+
checkedAt: checkedAtIso,
|
|
557
|
+
windows: evaluatedWindows,
|
|
558
|
+
applicableWindows,
|
|
559
|
+
blockers,
|
|
560
|
+
issues,
|
|
561
|
+
warnings,
|
|
562
|
+
usableCredits,
|
|
563
|
+
coveringCredits,
|
|
564
|
+
availableAfter,
|
|
565
|
+
paceScore,
|
|
566
|
+
expiringBonus,
|
|
567
|
+
budgetView,
|
|
568
|
+
};
|
|
569
|
+
}
|