opencode-quota-gui 1.1.0 → 1.2.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.
Files changed (73) hide show
  1. package/README.md +7 -5
  2. package/dist/contracts/analytics-temporal.d.ts +39 -0
  3. package/dist/contracts/analytics-temporal.d.ts.map +1 -0
  4. package/dist/contracts/analytics-temporal.js +11 -0
  5. package/dist/contracts/analytics-temporal.js.map +1 -0
  6. package/dist/contracts/build-identity.js +1 -1
  7. package/dist/contracts/dashboard.d.ts +13 -0
  8. package/dist/contracts/dashboard.d.ts.map +1 -1
  9. package/dist/contracts/dashboard.js.map +1 -1
  10. package/dist/contracts/temporal.d.ts +126 -0
  11. package/dist/contracts/temporal.d.ts.map +1 -0
  12. package/dist/contracts/temporal.js +10 -0
  13. package/dist/contracts/temporal.js.map +1 -0
  14. package/dist/data/modelsdev-temporal.min.json +3075 -0
  15. package/dist/gui/aggregation.d.ts.map +1 -1
  16. package/dist/gui/aggregation.js +3 -0
  17. package/dist/gui/aggregation.js.map +1 -1
  18. package/dist/gui/analytics-engine.d.ts.map +1 -1
  19. package/dist/gui/analytics-engine.js +30 -0
  20. package/dist/gui/analytics-engine.js.map +1 -1
  21. package/dist/gui/analytics-model.d.ts.map +1 -1
  22. package/dist/gui/analytics-model.js +181 -1
  23. package/dist/gui/analytics-model.js.map +1 -1
  24. package/dist/gui/analytics-pricing-revision.d.ts +43 -0
  25. package/dist/gui/analytics-pricing-revision.d.ts.map +1 -0
  26. package/dist/gui/analytics-pricing-revision.js +160 -0
  27. package/dist/gui/analytics-pricing-revision.js.map +1 -0
  28. package/dist/gui/analytics-state.d.ts +7 -2
  29. package/dist/gui/analytics-state.d.ts.map +1 -1
  30. package/dist/gui/analytics-state.js +14 -2
  31. package/dist/gui/analytics-state.js.map +1 -1
  32. package/dist/gui/config.d.ts +2 -2
  33. package/dist/gui/config.d.ts.map +1 -1
  34. package/dist/gui/config.js +18 -0
  35. package/dist/gui/config.js.map +1 -1
  36. package/dist/gui/sources.d.ts.map +1 -1
  37. package/dist/gui/sources.js +28 -0
  38. package/dist/gui/sources.js.map +1 -1
  39. package/dist/gui/temporal-quota-policy-data.d.ts +24 -0
  40. package/dist/gui/temporal-quota-policy-data.d.ts.map +1 -0
  41. package/dist/gui/temporal-quota-policy-data.js +43 -0
  42. package/dist/gui/temporal-quota-policy-data.js.map +1 -0
  43. package/dist/gui/temporal-quota-policy.d.ts +38 -0
  44. package/dist/gui/temporal-quota-policy.d.ts.map +1 -0
  45. package/dist/gui/temporal-quota-policy.js +182 -0
  46. package/dist/gui/temporal-quota-policy.js.map +1 -0
  47. package/dist/gui/temporal-status.d.ts +53 -0
  48. package/dist/gui/temporal-status.d.ts.map +1 -0
  49. package/dist/gui/temporal-status.js +815 -0
  50. package/dist/gui/temporal-status.js.map +1 -0
  51. package/dist/lib/config.d.ts +1 -1
  52. package/dist/lib/config.d.ts.map +1 -1
  53. package/dist/lib/config.js +33 -0
  54. package/dist/lib/config.js.map +1 -1
  55. package/dist/lib/modelsdev-temporal.d.ts +143 -0
  56. package/dist/lib/modelsdev-temporal.d.ts.map +1 -0
  57. package/dist/lib/modelsdev-temporal.js +896 -0
  58. package/dist/lib/modelsdev-temporal.js.map +1 -0
  59. package/dist/lib/quota-stats.d.ts +22 -1
  60. package/dist/lib/quota-stats.d.ts.map +1 -1
  61. package/dist/lib/quota-stats.js +111 -15
  62. package/dist/lib/quota-stats.js.map +1 -1
  63. package/dist/lib/types.d.ts +6 -0
  64. package/dist/lib/types.d.ts.map +1 -1
  65. package/dist/lib/types.js +1 -0
  66. package/dist/lib/types.js.map +1 -1
  67. package/dist/ui/assets/{index-BZwMJ6Ax.css → index-Cs-nrywz.css} +1 -1
  68. package/dist/ui/assets/index-D9lFKhSN.js +9 -0
  69. package/dist/ui/assets/popover-DKRrwr_K.js +1 -0
  70. package/dist/ui/assets/popover-mkHTmNjv.css +1 -0
  71. package/dist/ui/index.html +2 -2
  72. package/package.json +2 -1
  73. package/dist/ui/assets/index-CjNjqsse.js +0 -8
@@ -0,0 +1,815 @@
1
+ /**
2
+ * Server-side temporal status projection for the dashboard.
3
+ *
4
+ * `src/lib/modelsdev-temporal.ts` is the only models.dev policy evaluator, and
5
+ * it reads its bundled snapshot with `node:fs`, so this module is server-only.
6
+ * It evaluates exact snapshot routes plus provider-maintained quota policies,
7
+ * and emits a browser-safe DTO. Display labels never become model ids: a route
8
+ * is included only when its exact provider/model key exists in a policy.
9
+ */
10
+ import { readFileSync } from "node:fs";
11
+ import { lookupCost } from "../lib/modelsdev-pricing.js";
12
+ import { getNextTemporalTransition, getTemporalInstantState, getTemporalPolicy, getTemporalSnapshotMeta, listTemporalIntervals, TEMPORAL_DAYS, TEMPORAL_HOLIDAYS, } from "../lib/modelsdev-temporal.js";
13
+ import { getQuotaProviderDisplayLabel, normalizeQuotaProviderId, } from "../lib/provider-metadata.js";
14
+ import { buildQuotaPolicyModels } from "./temporal-quota-policy.js";
15
+ import { TEMPORAL_QUOTA_POLICIES } from "./temporal-quota-policy-data.js";
16
+ /** How far ahead exact schedule windows are projected for the popover. */
17
+ export const TEMPORAL_SCHEDULE_HORIZON_MS = 3 * 24 * 60 * 60 * 1000;
18
+ const MAX_INTERVALS_PER_MODEL = 24;
19
+ const MAX_HOLIDAYS_PER_PROVIDER = 8;
20
+ /**
21
+ * Mirrors core's private `MAX_TRANSITION_HORIZON_MS` (five 366-day years). The
22
+ * GUI searches the same supported horizon instead of inventing a step cutoff.
23
+ */
24
+ const TRANSITION_SEARCH_HORIZON_MS = 5 * 366 * 24 * 60 * 60 * 1000;
25
+ /** Chunk the horizon so long no-op runs exit before allocating years of windows. */
26
+ const TRANSITION_SEARCH_CHUNK_MS = 31 * 24 * 60 * 60 * 1000;
27
+ const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
28
+ const RATE_KEYS = ["input", "output", "cache_read", "cache_write", "reasoning"];
29
+ let bundledCatalog;
30
+ function isRecord(value) {
31
+ return typeof value === "object" && value !== null && !Array.isArray(value);
32
+ }
33
+ /** Reads the one bundled snapshot as exact route keys plus holiday calendars. */
34
+ export function readBundledTemporalCatalog() {
35
+ if (bundledCatalog)
36
+ return bundledCatalog;
37
+ const raw = JSON.parse(readFileSync(new URL("../data/modelsdev-temporal.min.json", import.meta.url), "utf8"));
38
+ const routes = {};
39
+ const root = isRecord(raw) ? raw : {};
40
+ if (isRecord(root.providers)) {
41
+ for (const [providerId, models] of Object.entries(root.providers)) {
42
+ if (!isRecord(models))
43
+ continue;
44
+ // "Capable" means at least one model with a real policy. An entry that is
45
+ // only `unsupported` has no schedule at all, so it neither earns a
46
+ // Settings row nor an unknown chip on Quota.
47
+ const capable = Object.entries(models)
48
+ .filter(([, entry]) => isRecord(entry) && entry.status !== "unsupported")
49
+ .map(([modelId]) => modelId)
50
+ .sort((left, right) => left.localeCompare(right));
51
+ if (capable.length > 0)
52
+ routes[providerId] = capable;
53
+ }
54
+ }
55
+ const holidays = [];
56
+ if (isRecord(root.jurisdictions)) {
57
+ for (const [jurisdiction, years] of Object.entries(root.jurisdictions)) {
58
+ if (jurisdiction !== "CN" && jurisdiction !== "US" && jurisdiction !== "CA")
59
+ continue;
60
+ if (!isRecord(years))
61
+ continue;
62
+ for (const calendar of Object.values(years)) {
63
+ if (!isRecord(calendar) || !Array.isArray(calendar.intervals))
64
+ continue;
65
+ for (const interval of calendar.intervals) {
66
+ if (!isRecord(interval))
67
+ continue;
68
+ const { id, localStart, localEnd, startMs, endMs } = interval;
69
+ if (typeof id !== "string" ||
70
+ typeof localStart !== "string" ||
71
+ typeof localEnd !== "string" ||
72
+ typeof startMs !== "number" ||
73
+ !Number.isFinite(startMs) ||
74
+ typeof endMs !== "number" ||
75
+ !Number.isFinite(endMs)) {
76
+ continue;
77
+ }
78
+ holidays.push({
79
+ jurisdiction,
80
+ id,
81
+ localStart,
82
+ localEnd,
83
+ startMs,
84
+ endMs,
85
+ });
86
+ }
87
+ }
88
+ }
89
+ }
90
+ holidays.sort((left, right) => left.startMs - right.startMs);
91
+ bundledCatalog = { routes, holidays };
92
+ return bundledCatalog;
93
+ }
94
+ function ratesFromCost(providerId, modelId) {
95
+ const cost = lookupCost(providerId, modelId);
96
+ if (!cost)
97
+ return null;
98
+ const rates = {};
99
+ for (const key of RATE_KEYS) {
100
+ const value = cost[key];
101
+ if (typeof value === "number" && Number.isFinite(value))
102
+ rates[key] = value;
103
+ }
104
+ return Object.keys(rates).length > 0 ? rates : null;
105
+ }
106
+ function mergeActiveRates(policy, activeRuleIds, base) {
107
+ const active = new Set(activeRuleIds);
108
+ const rates = { ...base };
109
+ for (const override of policy.overrides) {
110
+ if (!active.has(override.id))
111
+ continue;
112
+ for (const key of RATE_KEYS) {
113
+ const value = override.rates[key];
114
+ if (value !== undefined)
115
+ rates[key] = value;
116
+ }
117
+ }
118
+ for (const multiplier of policy.multipliers) {
119
+ if (!active.has(multiplier.id))
120
+ continue;
121
+ const factor = typeof multiplier.factor === "number" ? multiplier.factor : multiplier.factor.text;
122
+ for (const key of RATE_KEYS) {
123
+ const value = rates[key];
124
+ if (value !== undefined)
125
+ rates[key] = value * factor;
126
+ }
127
+ }
128
+ return rates;
129
+ }
130
+ /**
131
+ * Compare every applicable rate bucket, not just the first one. An override
132
+ * that changes only some buckets has no single multiplier; the returned factor
133
+ * is then only a representative value explicitly marked non-scalar. A zero or
134
+ * missing base with a positive resolved rate has no finite ratio and also
135
+ * prevents a scalar classification.
136
+ */
137
+ function effectFactor(policy, activeRuleIds, base) {
138
+ const active = new Set(activeRuleIds);
139
+ if (base) {
140
+ const resolved = mergeActiveRates(policy, activeRuleIds, base);
141
+ let factor;
142
+ let scalar = true;
143
+ for (const key of RATE_KEYS) {
144
+ const baseValue = base[key];
145
+ const resolvedValue = resolved[key];
146
+ const hasBase = typeof baseValue === "number" && Number.isFinite(baseValue);
147
+ const hasResolved = typeof resolvedValue === "number" && Number.isFinite(resolvedValue);
148
+ if (!hasBase) {
149
+ // An override or multiplier introduced a bucket the base does not
150
+ // price, so no single ratio can describe the whole model.
151
+ if (hasResolved)
152
+ scalar = false;
153
+ continue;
154
+ }
155
+ if (!hasResolved) {
156
+ scalar = false;
157
+ continue;
158
+ }
159
+ if (baseValue === 0) {
160
+ // A zero base has no ratio; only an unchanged zero is comparable.
161
+ if (resolvedValue !== 0)
162
+ scalar = false;
163
+ continue;
164
+ }
165
+ const ratio = resolvedValue / baseValue;
166
+ if (factor === undefined) {
167
+ factor = ratio;
168
+ }
169
+ else if (Math.abs(ratio - factor) >
170
+ TEMPORAL_FACTOR_EPSILON * Math.max(1, Math.abs(factor))) {
171
+ scalar = false;
172
+ }
173
+ }
174
+ return factor === undefined ? undefined : { factor, scalar };
175
+ }
176
+ let factor = 1;
177
+ let activeMultiplier = false;
178
+ for (const multiplier of policy.multipliers) {
179
+ if (!active.has(multiplier.id))
180
+ continue;
181
+ activeMultiplier = true;
182
+ factor *= typeof multiplier.factor === "number" ? multiplier.factor : multiplier.factor.text;
183
+ }
184
+ // An active override without any base rate cannot be compared to anything,
185
+ // so it stays unknown instead of being guessed as a discount.
186
+ if (!activeMultiplier && policy.overrides.some((override) => active.has(override.id))) {
187
+ return undefined;
188
+ }
189
+ // No base comparison was possible; explicit multipliers remain one scalar,
190
+ // but the payload does not claim a cross-rate classification.
191
+ return { factor };
192
+ }
193
+ const TEMPORAL_FACTOR_EPSILON = 1e-9;
194
+ /**
195
+ * Relative movement of every comparable base rate. This mirrors the analytics
196
+ * baseline rule: a policy that only discounts keeps its unchanged base on
197
+ * peak, while a policy that only surcharges keeps its unchanged base on
198
+ * off-peak. Opposite movements in one state are ambiguous and unusable.
199
+ */
200
+ function rateMovement(base, resolved) {
201
+ let comparable = false;
202
+ let sawIncrease = false;
203
+ let sawDecrease = false;
204
+ for (const key of RATE_KEYS) {
205
+ const baseRate = base[key];
206
+ const resolvedRate = resolved[key];
207
+ if (typeof baseRate !== "number" ||
208
+ baseRate <= 0 ||
209
+ typeof resolvedRate !== "number" ||
210
+ !Number.isFinite(resolvedRate)) {
211
+ continue;
212
+ }
213
+ comparable = true;
214
+ if (resolvedRate > baseRate * (1 + TEMPORAL_FACTOR_EPSILON))
215
+ sawIncrease = true;
216
+ else if (resolvedRate < baseRate * (1 - TEMPORAL_FACTOR_EPSILON))
217
+ sawDecrease = true;
218
+ }
219
+ if (!comparable)
220
+ return "incomparable";
221
+ if (sawIncrease && sawDecrease)
222
+ return "mixed";
223
+ if (sawIncrease)
224
+ return "increase";
225
+ if (sawDecrease)
226
+ return "decrease";
227
+ return "equal";
228
+ }
229
+ function multiplierMovement(factor) {
230
+ const value = typeof factor === "number" ? factor : factor.text;
231
+ if (!Number.isFinite(value))
232
+ return "incomparable";
233
+ if (value > 1 + TEMPORAL_FACTOR_EPSILON)
234
+ return "increase";
235
+ if (value < 1 - TEMPORAL_FACTOR_EPSILON)
236
+ return "decrease";
237
+ return "equal";
238
+ }
239
+ /**
240
+ * Direction of every admissible rule in one policy. A discount-only policy
241
+ * has a peak base state; a surcharge-only policy has an off-peak base state.
242
+ * Mixed, equal-only, or unverifiable rules cannot establish which side the
243
+ * unchanged base belongs to, so they fail closed.
244
+ */
245
+ function policyDirection(policy, base) {
246
+ let discount = false;
247
+ let surcharge = false;
248
+ let unverifiedOverride = false;
249
+ for (const override of policy.overrides) {
250
+ if (!base) {
251
+ unverifiedOverride = true;
252
+ continue;
253
+ }
254
+ const movement = rateMovement(base, override.rates);
255
+ if (movement === "mixed")
256
+ return "mixed";
257
+ if (movement === "incomparable")
258
+ continue;
259
+ if (movement === "increase")
260
+ surcharge = true;
261
+ else if (movement === "decrease")
262
+ discount = true;
263
+ }
264
+ for (const multiplier of policy.multipliers) {
265
+ const movement = multiplierMovement(multiplier.factor);
266
+ if (movement === "incomparable")
267
+ continue;
268
+ if (movement === "increase")
269
+ surcharge = true;
270
+ else if (movement === "decrease")
271
+ discount = true;
272
+ }
273
+ if (discount && surcharge)
274
+ return "mixed";
275
+ if (unverifiedOverride)
276
+ return "incomparable";
277
+ if (discount)
278
+ return "discount";
279
+ if (surcharge)
280
+ return "surcharge";
281
+ return "equal";
282
+ }
283
+ function stateMovement(policy, activeRuleIds, base) {
284
+ if (base)
285
+ return rateMovement(base, mergeActiveRates(policy, activeRuleIds, base));
286
+ const active = new Set(activeRuleIds);
287
+ if (policy.overrides.some((override) => active.has(override.id)))
288
+ return "incomparable";
289
+ const factor = effectFactor(policy, activeRuleIds, null)?.factor;
290
+ return factor === undefined ? "incomparable" : multiplierMovement(factor);
291
+ }
292
+ function effectFor(value, movement) {
293
+ if (!value || !Number.isFinite(value.factor) || value.factor < 0)
294
+ return undefined;
295
+ if (movement !== "increase" && movement !== "decrease" && movement !== "equal") {
296
+ return undefined;
297
+ }
298
+ // Direction describes every comparable rate, never just the representative
299
+ // factor of a non-scalar effect.
300
+ const direction = movement === "increase" ? "peak" : movement === "decrease" ? "offpeak" : "unchanged";
301
+ return {
302
+ factor: value.factor,
303
+ direction,
304
+ unit: "api_price",
305
+ ...(value.scalar !== undefined ? { scalar: value.scalar } : {}),
306
+ };
307
+ }
308
+ function classifyState(policy, activeRuleIds, base) {
309
+ if (!policy || policy.status === "unsupported")
310
+ return { phase: "unknown" };
311
+ // Without a direction, factor 1 is not evidence of off-peak (or peak).
312
+ const direction = policyDirection(policy, base);
313
+ if (direction === "mixed" || direction === "equal" || direction === "incomparable") {
314
+ return { phase: "unknown" };
315
+ }
316
+ const movement = stateMovement(policy, activeRuleIds, base);
317
+ if (movement === "mixed" || movement === "incomparable")
318
+ return { phase: "unknown" };
319
+ let phase = "unknown";
320
+ if (direction === "discount") {
321
+ if (movement === "decrease")
322
+ phase = "offpeak";
323
+ else if (movement === "equal")
324
+ phase = "peak";
325
+ }
326
+ else {
327
+ if (movement === "increase")
328
+ phase = "peak";
329
+ else if (movement === "equal")
330
+ phase = "offpeak";
331
+ }
332
+ if (phase === "unknown")
333
+ return { phase };
334
+ return {
335
+ phase,
336
+ effect: effectFor(effectFactor(policy, activeRuleIds, base), movement),
337
+ };
338
+ }
339
+ /** Classify an instant, keeping unresolved/unsupported states unknown. */
340
+ function classifyInstant(policy, instant, base) {
341
+ if (instant.status !== "resolved")
342
+ return { phase: "unknown" };
343
+ return classifyState(policy, instant.activeRuleIds, base);
344
+ }
345
+ function sameEffect(a, b) {
346
+ if (!a || !b)
347
+ return a === b;
348
+ return (a.factor === b.factor &&
349
+ a.direction === b.direction &&
350
+ a.unit === b.unit &&
351
+ a.scalar === b.scalar);
352
+ }
353
+ function weeklyClockMinutes(value) {
354
+ const [hours, minutes] = value.split(":").map((part) => Number.parseInt(part, 10));
355
+ return (hours ?? 0) * 60 + (minutes ?? 0);
356
+ }
357
+ function weeklyChoiceMatches(value, op, expected) {
358
+ return op === "equals"
359
+ ? typeof expected === "string" && value === expected
360
+ : Array.isArray(expected) && expected.includes(value);
361
+ }
362
+ function weeklyClockMatches(minute, condition) {
363
+ if (condition.op === "in") {
364
+ const values = Array.isArray(condition.value) ? condition.value : [];
365
+ return values.some((value) => minute === weeklyClockMinutes(value));
366
+ }
367
+ const target = weeklyClockMinutes(condition.value);
368
+ switch (condition.op) {
369
+ case "equals":
370
+ return minute === target;
371
+ case "gt":
372
+ return minute > target;
373
+ case "gte":
374
+ return minute >= target;
375
+ case "lt":
376
+ return minute < target;
377
+ case "lte":
378
+ return minute <= target;
379
+ }
380
+ }
381
+ /**
382
+ * Source-AST base week. Holiday leaves evaluate false so the recurring base is
383
+ * the non-holiday schedule; exact holiday dates remain separate intervals.
384
+ */
385
+ function weeklyConditionMatches(condition, day, minute) {
386
+ switch (condition.type) {
387
+ case "all":
388
+ return condition.of.every((child) => weeklyConditionMatches(child, day, minute));
389
+ case "any":
390
+ return condition.of.some((child) => weeklyConditionMatches(child, day, minute));
391
+ case "not":
392
+ return !weeklyConditionMatches(condition.of, day, minute);
393
+ case "utc_days":
394
+ return weeklyChoiceMatches(day, condition.op, condition.value);
395
+ case "utc_hours":
396
+ return weeklyClockMatches(minute, condition);
397
+ case "holiday":
398
+ return false;
399
+ }
400
+ }
401
+ function collectWeeklyBoundaries(condition, minutes) {
402
+ switch (condition.type) {
403
+ case "all":
404
+ case "any":
405
+ for (const child of condition.of)
406
+ collectWeeklyBoundaries(child, minutes);
407
+ return;
408
+ case "not":
409
+ collectWeeklyBoundaries(condition.of, minutes);
410
+ return;
411
+ case "utc_hours": {
412
+ const values = Array.isArray(condition.value) ? condition.value : [condition.value];
413
+ for (const value of values) {
414
+ const target = weeklyClockMinutes(value);
415
+ if (condition.op === "equals" ||
416
+ condition.op === "in" ||
417
+ condition.op === "gt" ||
418
+ condition.op === "lte") {
419
+ minutes.add(target + 1);
420
+ }
421
+ if (condition.op !== "gt")
422
+ minutes.add(target);
423
+ }
424
+ return;
425
+ }
426
+ default:
427
+ return;
428
+ }
429
+ }
430
+ /** Exact base-week segments from the AST, or undefined when classification is unknown. */
431
+ function policyWeeklySegments(policy, base) {
432
+ const boundaries = new Set([0, 1440]);
433
+ const rules = [...policy.overrides, ...policy.multipliers];
434
+ for (const rule of rules)
435
+ collectWeeklyBoundaries(rule.when, boundaries);
436
+ const sorted = [...boundaries]
437
+ .filter((minute) => minute >= 0 && minute <= 1440)
438
+ .sort((left, right) => left - right);
439
+ const segments = [];
440
+ for (const day of TEMPORAL_DAYS) {
441
+ let previous;
442
+ for (let index = 0; index < sorted.length - 1; index += 1) {
443
+ const startMinute = sorted[index];
444
+ const endMinute = sorted[index + 1];
445
+ if (startMinute === undefined || endMinute === undefined || endMinute <= startMinute) {
446
+ continue;
447
+ }
448
+ const activeRuleIds = [];
449
+ for (const rule of rules) {
450
+ if (weeklyConditionMatches(rule.when, day, startMinute))
451
+ activeRuleIds.push(rule.id);
452
+ }
453
+ const classified = classifyState(policy, activeRuleIds, base);
454
+ if (classified.phase === "unknown" || !classified.effect)
455
+ return undefined;
456
+ if (previous &&
457
+ previous.endMinute === startMinute &&
458
+ previous.phase === classified.phase &&
459
+ sameEffect(previous.effect, classified.effect)) {
460
+ previous.endMinute = endMinute;
461
+ }
462
+ else {
463
+ previous = {
464
+ day,
465
+ startMinute,
466
+ endMinute,
467
+ phase: classified.phase,
468
+ effect: classified.effect,
469
+ };
470
+ segments.push(previous);
471
+ }
472
+ }
473
+ }
474
+ return segments;
475
+ }
476
+ /** Browser-safe weekly descriptor, or undefined when no exact base week is provable. */
477
+ function policyWeeklySchedule(policy, base) {
478
+ if (!policy || policy.status !== "supported")
479
+ return undefined;
480
+ const segments = policyWeeklySegments(policy, base);
481
+ if (!segments || segments.length === 0)
482
+ return undefined;
483
+ const baseSegment = segments.find((segment) => segment.day === "mon" && segment.startMinute === 0);
484
+ if (!baseSegment)
485
+ return undefined;
486
+ const grouped = new Map();
487
+ for (const day of TEMPORAL_DAYS) {
488
+ let run;
489
+ const flush = (endMinute) => {
490
+ if (!run)
491
+ return;
492
+ const key = JSON.stringify([run.startMinute, endMinute, run.phase, run.effect]);
493
+ const existing = grouped.get(key);
494
+ if (existing) {
495
+ existing.days.add(day);
496
+ }
497
+ else {
498
+ grouped.set(key, {
499
+ days: new Set([day]),
500
+ startMinute: run.startMinute,
501
+ endMinute,
502
+ phase: run.phase,
503
+ effect: run.effect,
504
+ });
505
+ }
506
+ run = undefined;
507
+ };
508
+ for (const segment of segments) {
509
+ if (segment.day !== day)
510
+ continue;
511
+ const deviates = segment.phase !== baseSegment.phase || !sameEffect(segment.effect, baseSegment.effect);
512
+ if (deviates) {
513
+ if (run)
514
+ flush(segment.startMinute);
515
+ run = segment;
516
+ }
517
+ else {
518
+ flush(segment.startMinute);
519
+ }
520
+ }
521
+ flush(1440);
522
+ }
523
+ const windows = [...grouped.values()]
524
+ .sort((left, right) => left.startMinute - right.startMinute || left.endMinute - right.endMinute)
525
+ .map((window) => ({
526
+ days: TEMPORAL_DAYS.filter((day) => window.days.has(day)),
527
+ startMinute: window.startMinute,
528
+ endMinute: window.endMinute,
529
+ phase: window.phase,
530
+ effect: window.effect,
531
+ }));
532
+ const holidays = holidayJurisdictions(policy);
533
+ const exceptHolidays = TEMPORAL_HOLIDAYS.filter((jurisdiction) => holidays.has(jurisdiction));
534
+ return {
535
+ timeZone: "UTC",
536
+ utcOffsetMinutes: 0,
537
+ basePhase: baseSegment.phase,
538
+ baseEffect: baseSegment.effect,
539
+ windows,
540
+ ...(exceptHolidays.length > 0 ? { exceptHolidays } : {}),
541
+ };
542
+ }
543
+ function isMeaningfulTransition(after, current) {
544
+ return after.phase !== current.phase || !sameEffect(after.effect, current.effect);
545
+ }
546
+ /**
547
+ * Core reports active-rule-id changes too, which can leave the classified
548
+ * phase and effect untouched. Skip those so the countdown only names a
549
+ * transition the user can observe, scanning the same five-year horizon as the
550
+ * core within a short preview-style chunk. An unresolved `after` is unknown.
551
+ */
552
+ function nextMeaningfulTransitionAt(providerId, modelId, nowMs, policy, base, current) {
553
+ const first = getNextTemporalTransition(providerId, modelId, nowMs);
554
+ if (!first)
555
+ return undefined;
556
+ const firstAfter = classifyInstant(policy, first.after, base);
557
+ if (isMeaningfulTransition(firstAfter, current)) {
558
+ return { atMs: first.atMs, phase: firstAfter.phase };
559
+ }
560
+ const horizonEnd = nowMs + TRANSITION_SEARCH_HORIZON_MS;
561
+ // Without holiday references the policy is strictly weekly-periodic, so a
562
+ // full no-op week proves the cycle repeats. Holiday policies must keep
563
+ // scanning: repeated rule ids can still be broken by a future holiday.
564
+ const weeklyCycle = holidayJurisdictions(policy).size === 0;
565
+ let cursor = first.atMs;
566
+ while (cursor <= horizonEnd) {
567
+ const chunkEnd = Math.min(cursor + TRANSITION_SEARCH_CHUNK_MS, horizonEnd + 1);
568
+ if (chunkEnd <= cursor)
569
+ break;
570
+ // Rates are irrelevant here; active rule ids and status prove the boundary.
571
+ const intervals = listTemporalIntervals(providerId, modelId, cursor, chunkEnd);
572
+ for (const interval of intervals) {
573
+ // The first interval starts at the known no-op transition.
574
+ if (interval.startMs <= first.atMs)
575
+ continue;
576
+ const after = classifyInstant(policy, interval, base);
577
+ if (isMeaningfulTransition(after, current)) {
578
+ return { atMs: interval.startMs, phase: after.phase };
579
+ }
580
+ }
581
+ if (weeklyCycle && chunkEnd - first.atMs >= WEEK_MS)
582
+ return undefined;
583
+ cursor = chunkEnd;
584
+ }
585
+ return undefined;
586
+ }
587
+ function collectHolidays(condition, into) {
588
+ switch (condition.type) {
589
+ case "all":
590
+ case "any":
591
+ for (const child of condition.of)
592
+ collectHolidays(child, into);
593
+ return;
594
+ case "not":
595
+ collectHolidays(condition.of, into);
596
+ return;
597
+ case "holiday": {
598
+ const values = Array.isArray(condition.value) ? condition.value : [condition.value];
599
+ for (const value of values)
600
+ into.add(value);
601
+ return;
602
+ }
603
+ default:
604
+ return;
605
+ }
606
+ }
607
+ function holidayJurisdictions(policy) {
608
+ const jurisdictions = new Set();
609
+ if (!policy || policy.status !== "supported")
610
+ return jurisdictions;
611
+ for (const override of policy.overrides)
612
+ collectHolidays(override.when, jurisdictions);
613
+ for (const multiplier of policy.multipliers)
614
+ collectHolidays(multiplier.when, jurisdictions);
615
+ return jurisdictions;
616
+ }
617
+ function providerPhase(models) {
618
+ let peak = false;
619
+ let offpeak = false;
620
+ for (const model of models) {
621
+ // Known states cannot outvote an in-scope unknown model: the provider
622
+ // aggregate is conservative and must not imply more precision than it has.
623
+ if (model.state === "unknown")
624
+ return "unknown";
625
+ if (model.state === "peak")
626
+ peak = true;
627
+ if (model.state === "offpeak")
628
+ offpeak = true;
629
+ }
630
+ if (peak && offpeak)
631
+ return "mixed";
632
+ if (peak)
633
+ return "peak";
634
+ if (offpeak)
635
+ return "offpeak";
636
+ return "unknown";
637
+ }
638
+ function upcomingHolidays(catalog, jurisdictions, nowMs) {
639
+ if (jurisdictions.size === 0)
640
+ return [];
641
+ return catalog
642
+ .filter((holiday) => jurisdictions.has(holiday.jurisdiction) && holiday.endMs > nowMs)
643
+ .slice(0, MAX_HOLIDAYS_PER_PROVIDER)
644
+ .map((holiday) => ({ ...holiday }));
645
+ }
646
+ function policySource(policy) {
647
+ return {
648
+ label: policy.sourceLabel,
649
+ url: policy.source,
650
+ accessedAt: policy.sourceAccessedAt,
651
+ };
652
+ }
653
+ function matchingQuotaPolicy(policies, providerId) {
654
+ return policies.find((policy) => policy.providerId === providerId || policy.aliases.includes(providerId));
655
+ }
656
+ /**
657
+ * Every provider with a temporal policy, discovered or not. Account discovery
658
+ * only decides the default visibility; it never removes a Settings row.
659
+ */
660
+ export function listTemporalProviderSources(catalog, policies, cards) {
661
+ const cardsById = new Map();
662
+ for (const card of cards) {
663
+ if (!cardsById.has(card.providerId))
664
+ cardsById.set(card.providerId, card);
665
+ const normalized = normalizeQuotaProviderId(card.providerId);
666
+ if (!cardsById.has(normalized))
667
+ cardsById.set(normalized, card);
668
+ }
669
+ const claimed = new Set();
670
+ const sources = [];
671
+ for (const policy of policies) {
672
+ const ids = [policy.providerId, ...policy.aliases];
673
+ const card = ids
674
+ .map((id) => cardsById.get(id) ?? cardsById.get(normalizeQuotaProviderId(id)))
675
+ .find((entry) => entry !== undefined);
676
+ for (const id of ids)
677
+ claimed.add(id);
678
+ sources.push({
679
+ providerId: policy.providerId,
680
+ providerLabel: card?.providerLabel ?? policy.providerLabel,
681
+ discovered: card !== undefined,
682
+ });
683
+ }
684
+ for (const providerId of Object.keys(catalog.routes)) {
685
+ if (claimed.has(providerId))
686
+ continue;
687
+ const card = cardsById.get(providerId) ?? cardsById.get(normalizeQuotaProviderId(providerId));
688
+ sources.push({
689
+ providerId,
690
+ providerLabel: card?.providerLabel ?? getQuotaProviderDisplayLabel(providerId),
691
+ discovered: card !== undefined,
692
+ });
693
+ }
694
+ // Account-backed providers first so the Settings list starts with what the
695
+ // user is actually using; the rest remain available to pre-enable.
696
+ return sources.sort((left, right) => Number(right.discovered) - Number(left.discovered) ||
697
+ left.providerLabel.localeCompare(right.providerLabel));
698
+ }
699
+ /** Computes the whole browser-safe temporal status for the given providers. */
700
+ export function buildTemporalStatus(input) {
701
+ const resolveBase = input.baseRates ?? ratesFromCost;
702
+ const holidays = input.holidays ?? [];
703
+ const quotaPolicies = input.quotaPolicies ?? TEMPORAL_QUOTA_POLICIES;
704
+ const providers = [];
705
+ const seen = new Set();
706
+ for (const provider of input.providers) {
707
+ const quotaPolicy = matchingQuotaPolicy(quotaPolicies, provider.providerId);
708
+ const providerId = quotaPolicy?.providerId ?? provider.providerId;
709
+ if (seen.has(providerId))
710
+ continue;
711
+ seen.add(providerId);
712
+ let models;
713
+ const jurisdictions = new Set();
714
+ let source;
715
+ if (quotaPolicy) {
716
+ models = buildQuotaPolicyModels(quotaPolicy, input.nowMs, TEMPORAL_SCHEDULE_HORIZON_MS);
717
+ source = policySource(quotaPolicy);
718
+ }
719
+ else {
720
+ models = [];
721
+ const routes = input.routes[provider.providerId] ?? [];
722
+ for (const modelId of routes) {
723
+ const policy = getTemporalPolicy(provider.providerId, modelId);
724
+ if (!policy)
725
+ continue;
726
+ models.push(modelStatus(provider.providerId, modelId, input.nowMs, resolveBase));
727
+ for (const jurisdiction of holidayJurisdictions(policy))
728
+ jurisdictions.add(jurisdiction);
729
+ }
730
+ }
731
+ if (models.length === 0)
732
+ continue;
733
+ providers.push({
734
+ providerId,
735
+ providerLabel: provider.providerLabel,
736
+ discovered: provider.discovered,
737
+ phase: providerPhase(models),
738
+ models,
739
+ holidays: quotaPolicy ? [] : upcomingHolidays(holidays, jurisdictions, input.nowMs),
740
+ ...(source ? { source } : {}),
741
+ });
742
+ }
743
+ const meta = getTemporalSnapshotMeta();
744
+ return {
745
+ generatedAtMs: input.nowMs,
746
+ providers,
747
+ snapshot: {
748
+ revision: meta.revision,
749
+ generatedAtMs: meta.generatedAt,
750
+ },
751
+ };
752
+ }
753
+ function modelStatus(providerId, modelId, nowMs, baseRates) {
754
+ const policy = getTemporalPolicy(providerId, modelId);
755
+ const base = baseRates(providerId, modelId);
756
+ const state = getTemporalInstantState(providerId, modelId, nowMs);
757
+ const current = classifyInstant(policy, state, base);
758
+ const intervals = projectIntervals(providerId, modelId, nowMs, baseRates);
759
+ const weekly = policyWeeklySchedule(policy, base);
760
+ // The preview is deliberately short, so its last interval ends at the horizon
761
+ // rather than at a proved transition. Ask the core evaluator for the real
762
+ // next transition independently so a long holiday or sparse rule does not
763
+ // suppress a change that simply falls outside the display window.
764
+ const next = nextMeaningfulTransitionAt(providerId, modelId, nowMs, policy, base, current);
765
+ const status = {
766
+ modelId,
767
+ state: current.phase,
768
+ intervals,
769
+ };
770
+ if (current.effect)
771
+ status.effect = current.effect;
772
+ if (weekly)
773
+ status.weekly = weekly;
774
+ if (next) {
775
+ status.nextChangeAtMs = next.atMs;
776
+ status.nextState = next.phase;
777
+ }
778
+ if (state.reason)
779
+ status.reason = state.reason;
780
+ return status;
781
+ }
782
+ function projectIntervals(providerId, modelId, nowMs, baseRates) {
783
+ const policy = getTemporalPolicy(providerId, modelId);
784
+ if (!policy || policy.status === "unsupported")
785
+ return [];
786
+ const base = baseRates(providerId, modelId);
787
+ const rawIntervals = listTemporalIntervals(providerId, modelId, nowMs, nowMs + TEMPORAL_SCHEDULE_HORIZON_MS, base ?? undefined);
788
+ const projected = [];
789
+ for (const interval of rawIntervals) {
790
+ const classified = interval.status === "resolved"
791
+ ? classifyState(policy, interval.activeRuleIds, base)
792
+ : undefined;
793
+ const next = {
794
+ startMs: interval.startMs,
795
+ endMs: interval.endMs,
796
+ // An unresolved calendar or rule must stay unknown: peak/off-peak labels
797
+ // would otherwise look like a resolved price window.
798
+ phase: classified?.phase ?? "unknown",
799
+ ...(classified?.effect ? { effect: classified.effect } : {}),
800
+ ...(interval.reason ? { reason: interval.reason } : {}),
801
+ };
802
+ const previous = projected[projected.length - 1];
803
+ if (previous &&
804
+ previous.phase === next.phase &&
805
+ previous.reason === next.reason &&
806
+ JSON.stringify(previous.effect) === JSON.stringify(next.effect)) {
807
+ previous.endMs = next.endMs;
808
+ }
809
+ else {
810
+ projected.push(next);
811
+ }
812
+ }
813
+ return projected.slice(0, MAX_INTERVALS_PER_MODEL);
814
+ }
815
+ //# sourceMappingURL=temporal-status.js.map