quotacap 0.0.58 → 0.0.60

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 (53) hide show
  1. package/README.md +1 -1
  2. package/dist/adapters/muse.d.ts +1 -1
  3. package/dist/adapters/muse.js +5 -3
  4. package/dist/advisory/engine.js +9 -5
  5. package/dist/advisory/snapshot.js +10 -11
  6. package/dist/cli/advise.d.ts +1 -1
  7. package/dist/cli/advise.js +6 -2
  8. package/dist/cli/models.js +2 -2
  9. package/dist/cli/status.js +2 -2
  10. package/dist/format/markdown.js +5 -5
  11. package/dist/format/rate-limit-wait.d.ts +3 -3
  12. package/dist/format/rate-limit-wait.js +8 -26
  13. package/dist/format/rows.d.ts +40 -6
  14. package/dist/format/rows.js +48 -42
  15. package/dist/format/terminal.js +12 -11
  16. package/dist/format/time.d.ts +19 -0
  17. package/dist/format/time.js +69 -0
  18. package/dist/mcp/server.d.ts +25 -5
  19. package/dist/mcp/server.js +36 -3
  20. package/dist/store/quotas.d.ts +7 -2
  21. package/dist/store/quotas.js +94 -15
  22. package/dist/version.js +1 -1
  23. package/dist/web/src/components/AdviceDrawer.d.ts +3 -1
  24. package/dist/web/src/components/AdviceDrawer.js +25 -4
  25. package/dist/web/src/components/ClosedWeeks.d.ts +4 -1
  26. package/dist/web/src/components/ClosedWeeks.js +17 -5
  27. package/dist/web/src/components/PaceBar.d.ts +26 -25
  28. package/dist/web/src/components/PaceBar.js +57 -119
  29. package/dist/web/src/components/PacingLegend.js +9 -8
  30. package/dist/web/src/components/ProviderCard.js +1 -1
  31. package/dist/web/src/components/ProviderDrawer.d.ts +9 -2
  32. package/dist/web/src/components/ProviderDrawer.js +37 -27
  33. package/dist/web/src/components/ProviderIcon.d.ts +7 -2
  34. package/dist/web/src/components/ProviderIcon.js +9 -17
  35. package/dist/web/src/components/Recommendation.d.ts +4 -3
  36. package/dist/web/src/components/Recommendation.js +16 -8
  37. package/dist/web/src/components/ResetRail.d.ts +2 -0
  38. package/dist/web/src/components/ResetRail.js +15 -5
  39. package/dist/web/src/components/WindowsRow.d.ts +2 -2
  40. package/dist/web/src/components/WindowsRow.js +3 -13
  41. package/dist/web/src/components/settings/ProvidersPanel.d.ts +3 -2
  42. package/dist/web/src/components/settings/ProvidersPanel.js +4 -1
  43. package/dist/web/src/pages/Onboarding.js +1 -1
  44. package/dist/web/src/state.d.ts +5 -0
  45. package/dist/web/src/state.js +18 -0
  46. package/dist/webAssets.js +1 -1
  47. package/dist/webHtml.js +1 -1
  48. package/package.json +2 -2
  49. package/web/dist/assets/index-8X8QSsxH.js +13 -0
  50. package/web/dist/assets/index-CRt0tdTj.css +1 -0
  51. package/web/dist/index.html +2 -2
  52. package/web/dist/assets/index-CnAonL1R.css +0 -1
  53. package/web/dist/assets/index-DGCyW-uy.js +0 -13
@@ -0,0 +1,69 @@
1
+ // One duration and one clock vocabulary for every human surface: the
2
+ // dashboard imports these, the CLI rows and the engine reason use them, so
3
+ // one instant never reads "5d 23h" in one place and "6d 0h" or "6.0d" in
4
+ // another. Pinned to en-US with a 24-hour clock: the sentences they feed
5
+ // are English, so a non-English machine must not print localized parts.
6
+ const DAY_MS = 86400000;
7
+ const HOUR_MS = 3600000;
8
+ const MIN_MS = 60000;
9
+ /**
10
+ * Floored duration: "6d 23h" from one day up, "5h 12m" from one hour up,
11
+ * else "45m". Sub-minute spans read "1m" so a live window never prints 0m.
12
+ */
13
+ export function durationText(ms) {
14
+ if (!Number.isFinite(ms) || ms <= 0)
15
+ return "0m";
16
+ const totalMinutes = Math.floor(ms / MIN_MS);
17
+ const days = Math.floor(ms / DAY_MS);
18
+ const hours = Math.floor((ms % DAY_MS) / HOUR_MS);
19
+ if (days >= 1)
20
+ return `${days}d ${hours}h`;
21
+ if (hours >= 1)
22
+ return `${hours}h ${totalMinutes % 60}m`;
23
+ return `${Math.max(1, totalMinutes)}m`;
24
+ }
25
+ /** Duration from fractional days, for engine fields such as daysLeft. */
26
+ export function durationFromDays(days) {
27
+ return durationText(days * DAY_MS);
28
+ }
29
+ function weekday(when) {
30
+ return when.toLocaleDateString("en-US", { weekday: "short" });
31
+ }
32
+ function clock24(when) {
33
+ return when.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
34
+ }
35
+ /**
36
+ * Wall-clock instant: "Sat 14:46" within 7 days of `nowMs`, where the
37
+ * weekday is unambiguous, else "Sun 22 Nov 23:05". Without `nowMs` the
38
+ * dated form is used. Null when unparseable.
39
+ */
40
+ export function clockText(iso, nowMs) {
41
+ const ms = iso ? Date.parse(iso) : NaN;
42
+ if (!Number.isFinite(ms))
43
+ return null;
44
+ const when = new Date(ms);
45
+ if (nowMs !== undefined && Number.isFinite(nowMs) && Math.abs(ms - nowMs) < 7 * DAY_MS) {
46
+ return `${weekday(when)} ${clock24(when)}`;
47
+ }
48
+ return `${weekday(when)} ${dateText(iso)} ${clock24(when)}`;
49
+ }
50
+ /** Calendar date without the weekday or clock, e.g. "22 Nov". Empty when unparseable. */
51
+ export function dateText(iso) {
52
+ const ms = iso ? Date.parse(iso) : NaN;
53
+ if (!Number.isFinite(ms))
54
+ return "";
55
+ const when = new Date(ms);
56
+ return `${when.getDate()} ${when.toLocaleDateString("en-US", { month: "short" })}`;
57
+ }
58
+ /** Weekday plus calendar date, e.g. "Sun 22 Nov". */
59
+ export function dayText(iso) {
60
+ const ms = iso ? Date.parse(iso) : NaN;
61
+ if (!Number.isFinite(ms))
62
+ return "Invalid Date";
63
+ return `${weekday(new Date(ms))} ${dateText(iso)}`;
64
+ }
65
+ /** The one waste sentence: "16% unused at reset (Fri 13:14)". */
66
+ export function unusedAtReset(wastePct, resetsAt, nowMs) {
67
+ const clock = clockText(resetsAt, nowMs);
68
+ return `${Math.round(wastePct)}% unused at reset${clock ? ` (${clock})` : ""}`;
69
+ }
@@ -1,10 +1,11 @@
1
+ import type { StateSnapshot } from "../advisory/types.js";
1
2
  export declare const tools: ({
2
3
  name: string;
3
4
  description: string;
4
5
  inputSchema: {
5
6
  type: string;
6
7
  properties: {
7
- task?: undefined;
8
+ verbose?: undefined;
8
9
  provider?: undefined;
9
10
  };
10
11
  required: never[];
@@ -15,9 +16,9 @@ export declare const tools: ({
15
16
  inputSchema: {
16
17
  type: string;
17
18
  properties: {
18
- task: {
19
+ verbose: {
19
20
  type: string;
20
- enum: string[];
21
+ description: string;
21
22
  };
22
23
  provider?: undefined;
23
24
  };
@@ -29,7 +30,7 @@ export declare const tools: ({
29
30
  inputSchema: {
30
31
  type: string;
31
32
  properties: {
32
- task?: undefined;
33
+ verbose?: undefined;
33
34
  provider: {
34
35
  type: string;
35
36
  };
@@ -42,7 +43,7 @@ export declare const tools: ({
42
43
  inputSchema: {
43
44
  type: string;
44
45
  properties: {
45
- task?: undefined;
46
+ verbose?: undefined;
46
47
  provider: {
47
48
  type: string;
48
49
  };
@@ -50,6 +51,25 @@ export declare const tools: ({
50
51
  required: string[];
51
52
  };
52
53
  })[];
54
+ /**
55
+ * The default get_recommendation payload: the pick, its reason, and the
56
+ * other shown providers in recommended order with what an agent needs to
57
+ * choose. The full projection is behind `verbose: true`.
58
+ */
59
+ export declare function compactRecommendation(snapshot: StateSnapshot, now: Date): {
60
+ use: string;
61
+ reason: string;
62
+ wastePct: number | null;
63
+ recommendationBasis: import("../advisory/types.js").RecommendationBasis;
64
+ bindingWindow: import("../advisory/types.js").BindingWindow;
65
+ alternatives: {
66
+ provider: string;
67
+ state: import("../format/rows.js").StateWord;
68
+ available: boolean;
69
+ resetsAt: string | null;
70
+ wait?: string | undefined;
71
+ }[];
72
+ };
53
73
  export declare function handleTool(name: string, args: any): Promise<{
54
74
  content: {
55
75
  type: string;
@@ -2,7 +2,8 @@ import { adapters } from "../adapters/index.js";
2
2
  import { projectQuotasResponse, projectRecommendationResponse, } from "../advisory/snapshot.js";
3
3
  import { validateForecastProvider, validateTask } from "../advisory/validate.js";
4
4
  import { getDbPath, readConfig } from "../config.js";
5
- import { forecastText, stateWord } from "../format/rows.js";
5
+ import { bindingResetsAt, forecastText, shownProviders, sortProviders, stateWord } from "../format/rows.js";
6
+ import { rateLimitWaits } from "../format/rate-limit-wait.js";
6
7
  import { renderMarkdownTable, renderRecommendationSummary, renderModelsMarkdownTable } from "../format/markdown.js";
7
8
  import { createServiceClientForBase, ServiceUnavailable } from "../runtime/client.js";
8
9
  import { CATALOG_CLIENT_TIMEOUT_MS } from "../catalog/index.js";
@@ -10,7 +11,7 @@ import { VERSION } from "../version.js";
10
11
  import { ClientError, OFFLINE_LABEL, resolveSnapshot, } from "../cli/snapshot-source.js";
11
12
  export const tools = [
12
13
  { name: "get_quotas", description: "All quotas with resets and health", inputSchema: { type: "object", properties: {}, required: [] } },
13
- { name: "get_recommendation", description: "Which provider to use next (same advice for every task). Also names a full 5h limit or a full week on a monthly plan, and when that limit clears.", inputSchema: { type: "object", properties: { task: { type: "string", enum: ["any", "heavy", "light"] } } } },
14
+ { name: "get_recommendation", description: "Which provider to use next (same advice for every task), plus each other provider's state, availability and reset. Also names a full 5h limit or a full week on a monthly plan, and when that limit clears. Pass verbose: true for every quota, advisory and model list.", inputSchema: { type: "object", properties: { verbose: { type: "boolean", description: "Return the full recommendation payload (all quotas, advisories and model lists)" } } } },
14
15
  { name: "get_models", description: "Currently listed models per quota bucket (inventory, not a task ranking)", inputSchema: { type: "object", properties: { provider: { type: "string" } } } },
15
16
  { name: "forecast", description: "Burn (24h + window avg) vs ideal + waste for a provider", inputSchema: { type: "object", properties: { provider: { type: "string" } }, required: ["provider"] } },
16
17
  ];
@@ -38,6 +39,34 @@ async function resolveState() {
38
39
  throw e;
39
40
  }
40
41
  }
42
+ const UNAVAILABLE = new Set(["Quota exhausted", "Monthly exhausted", "Not reporting"]);
43
+ /**
44
+ * The default get_recommendation payload: the pick, its reason, and the
45
+ * other shown providers in recommended order with what an agent needs to
46
+ * choose. The full projection is behind `verbose: true`.
47
+ */
48
+ export function compactRecommendation(snapshot, now) {
49
+ const rec = snapshot.recommendation;
50
+ const others = sortProviders(shownProviders(snapshot.providers), "recommended", rec.use).filter((p) => p.id !== rec.use);
51
+ return {
52
+ use: rec.use,
53
+ reason: rec.reason,
54
+ wastePct: rec.wastePct,
55
+ recommendationBasis: rec.recommendationBasis,
56
+ bindingWindow: rec.bindingWindow,
57
+ alternatives: others.map((p) => {
58
+ const state = stateWord(p);
59
+ const waits = rateLimitWaits(p, now);
60
+ return {
61
+ provider: p.id,
62
+ state,
63
+ available: !UNAVAILABLE.has(state) && waits.length === 0,
64
+ resetsAt: bindingResetsAt(p),
65
+ ...(waits.length > 0 ? { wait: waits.map((w) => w.text).join(", ") } : {}),
66
+ };
67
+ }),
68
+ };
69
+ }
41
70
  function rejectMissingProvider(args) {
42
71
  try {
43
72
  validateForecastProvider(args?.provider, { registered: [], storedIds: [] });
@@ -63,15 +92,19 @@ export async function handleTool(name, args) {
63
92
  };
64
93
  }
65
94
  if (name === "get_recommendation") {
95
+ // task is no longer advertised; old clients that send it still validate.
66
96
  const task = validateTask(args?.task ?? "any");
67
97
  const { snapshot, source } = await resolveState();
68
98
  if (source === "offline")
69
99
  console.error(OFFLINE_LABEL);
70
100
  const now = new Date();
101
+ const body = args?.verbose === true
102
+ ? projectRecommendationResponse(snapshot, task)
103
+ : compactRecommendation(snapshot, now);
71
104
  return {
72
105
  content: [
73
106
  { type: "text", text: renderRecommendationSummary(snapshot, now) },
74
- { type: "text", text: JSON.stringify(projectRecommendationResponse(snapshot, task), null, 2) },
107
+ { type: "text", text: JSON.stringify(body, null, 2) },
75
108
  ],
76
109
  };
77
110
  }
@@ -8,7 +8,11 @@ export declare function isWeeklyCycleBreak(prev: {
8
8
  resetsAt: string | null;
9
9
  }): boolean;
10
10
  export declare function upsertQuota(db: any, q: any): void;
11
- export declare function getWindowCloses(db: any, provider: string, limit?: number, window?: "weekly" | "monthly"): Array<{
11
+ interface CloseWindow {
12
+ resetsAt: string | null;
13
+ resetsAtEstimated?: boolean;
14
+ }
15
+ export declare function getWindowCloses(db: any, provider: string, limit?: number, window?: "weekly" | "monthly", current?: CloseWindow | null): Array<{
12
16
  provider: string;
13
17
  plan: string | null;
14
18
  usedPct: number;
@@ -29,4 +33,5 @@ export declare function getExhaustedTimestamps(db: any, now?: number): {
29
33
  weekly: Map<string, string>;
30
34
  monthly: Map<string, string>;
31
35
  };
32
- export declare function getHistoryBaseline(db: any, limit?: number): Map<string, number>;
36
+ export declare function getHistoryBaseline(db: any, limit?: number, current?: Map<string, CloseWindow>): Map<string, number>;
37
+ export {};
@@ -55,7 +55,9 @@ function mapRow(row) {
55
55
  function cycleBreakReason(prev, cur) {
56
56
  const dropped = cur.usedPct < prev.usedPct;
57
57
  const prevResets = prev.resetsAt ? new Date(prev.resetsAt).getTime() : NaN;
58
- const boundaryRolled = !Number.isNaN(prevResets) && prevResets <= cur.t && prev.resetsAt !== cur.resetsAt;
58
+ // Instants, not strings: one reset written as "+10:00" and as "Z" is one boundary.
59
+ const curResets = cur.resetsAt ? new Date(cur.resetsAt).getTime() : NaN;
60
+ const boundaryRolled = !Number.isNaN(prevResets) && prevResets <= cur.t && prevResets !== curResets;
59
61
  if (dropped && boundaryRolled)
60
62
  return "both";
61
63
  if (dropped)
@@ -67,12 +69,28 @@ function cycleBreakReason(prev, cur) {
67
69
  export function isWeeklyCycleBreak(prev, cur) {
68
70
  return cycleBreakReason(prev, cur) !== null;
69
71
  }
72
+ // One timestamp format on the wire: adapters report offsets as their
73
+ // source prints them ("+10:00", "Z"), so ingest stores UTC ISO.
74
+ function utcIso(v) {
75
+ if (typeof v !== "string")
76
+ return v;
77
+ const ms = Date.parse(v);
78
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : v;
79
+ }
70
80
  export function upsertQuota(db, q) {
71
81
  if (Array.isArray(q)) {
72
82
  for (const item of q)
73
83
  upsertQuota(db, item);
74
84
  return;
75
85
  }
86
+ q = {
87
+ ...q,
88
+ resetsAt: utcIso(q.resetsAt),
89
+ periodStart: utcIso(q.periodStart),
90
+ fetchedAt: utcIso(q.fetchedAt),
91
+ monthlyResetsAt: utcIso(q.monthlyResetsAt),
92
+ fiveHourResetsAt: utcIso(q.fiveHourResetsAt),
93
+ };
76
94
  const credits = q.creditsUsd ?? q.credits_usd ?? null;
77
95
  const estimated = q.resetsAtEstimated ? 1 : null;
78
96
  // Either spelling binds; an explicit null stays null (SQLite binds it),
@@ -102,6 +120,51 @@ export function upsertQuota(db, q) {
102
120
  throw e;
103
121
  }
104
122
  }
123
+ const DAY_MS = 86_400_000;
124
+ // Verified resets this close together name one window: claude reports the
125
+ // same reset as 20:59 and 21:00.
126
+ const SAME_WINDOW_MS = 60 * 60 * 1000;
127
+ // A close that ran under a day says too little about a week's pace.
128
+ const MIN_CLOSE_SPAN_DAYS = 1;
129
+ function sameVerifiedWindow(a, b) {
130
+ if (a.resetsAtEstimated || b.resetsAtEstimated || !a.resetsAt || !b.resetsAt)
131
+ return false;
132
+ const aMs = Date.parse(a.resetsAt);
133
+ const bMs = Date.parse(b.resetsAt);
134
+ return Number.isFinite(aMs) && Number.isFinite(bMs) && Math.abs(aMs - bMs) <= SAME_WINDOW_MS;
135
+ }
136
+ /**
137
+ * Finished windows only, one row each. A usage drop inside the window still
138
+ * open is not a close, and a window that dropped more than once keeps its
139
+ * newest row. Estimated resets pass through: their boundaries move per poll.
140
+ */
141
+ function settleCloses(newestFirst, current) {
142
+ const out = [];
143
+ for (const c of newestFirst) {
144
+ if (current && sameVerifiedWindow(c, current))
145
+ continue;
146
+ if (out.some((kept) => sameVerifiedWindow(kept, c)))
147
+ continue;
148
+ out.push(c);
149
+ }
150
+ return out;
151
+ }
152
+ /**
153
+ * Daily pace over the days a close actually ran: a window the provider reset
154
+ * early, or one last sampled days before its reset, covers fewer than seven.
155
+ * Null under MIN_CLOSE_SPAN_DAYS. Estimated or undated closes keep used / 7.
156
+ */
157
+ function closeDailyRate(c) {
158
+ const start = c.periodStart ? Date.parse(c.periodStart) : NaN;
159
+ const end = c.resetsAt ? Date.parse(c.resetsAt) : NaN;
160
+ const sampled = Date.parse(c.sampledAt);
161
+ if (c.resetsAtEstimated || !Number.isFinite(start) || !Number.isFinite(end) || !Number.isFinite(sampled)) {
162
+ return c.usedPct / 7;
163
+ }
164
+ const ranUntil = end - sampled <= SAME_WINDOW_MS ? end : Math.min(sampled, end);
165
+ const days = (ranUntil - start) / DAY_MS;
166
+ return days >= MIN_CLOSE_SPAN_DAYS ? c.usedPct / days : null;
167
+ }
105
168
  function monthlyPeriodStart(resetIso) {
106
169
  if (!resetIso)
107
170
  return null;
@@ -112,7 +175,7 @@ function monthlyPeriodStart(resetIso) {
112
175
  start.setMonth(start.getMonth() - 1);
113
176
  return start.toISOString();
114
177
  }
115
- export function getWindowCloses(db, provider, limit = 4, window = "weekly") {
178
+ export function getWindowCloses(db, provider, limit = 4, window = "weekly", current) {
116
179
  if (window === "monthly") {
117
180
  let qRows = [];
118
181
  try {
@@ -164,7 +227,7 @@ export function getWindowCloses(db, provider, limit = 4, window = "weekly") {
164
227
  }
165
228
  let rows = [];
166
229
  try {
167
- rows = db.prepare(`SELECT provider, plan, used_pct, leftover_pct, sampled_at, period_start, resets_at, resets_at_estimated, detected_at, reason FROM window_closes WHERE provider=? ORDER BY detected_at DESC, id DESC LIMIT ?`).all(provider, limit);
230
+ rows = db.prepare(`SELECT provider, plan, used_pct, leftover_pct, sampled_at, period_start, resets_at, resets_at_estimated, detected_at, reason FROM window_closes WHERE provider=? ORDER BY detected_at DESC, id DESC`).all(provider);
168
231
  }
169
232
  catch (e) {
170
233
  // A pre-observability database read offline is never migrated, so the
@@ -172,7 +235,7 @@ export function getWindowCloses(db, provider, limit = 4, window = "weekly") {
172
235
  if (!/no such table/i.test(String(e?.message ?? "")))
173
236
  throw e;
174
237
  }
175
- return rows.map((r) => ({
238
+ const mapped = rows.map((r) => ({
176
239
  provider: r.provider,
177
240
  plan: r.plan ?? null,
178
241
  usedPct: r.used_pct,
@@ -184,6 +247,7 @@ export function getWindowCloses(db, provider, limit = 4, window = "weekly") {
184
247
  detectedAt: r.detected_at,
185
248
  reason: r.reason,
186
249
  }));
250
+ return settleCloses(mapped, current).slice(0, limit);
187
251
  }
188
252
  export function getLatestByProvider(db, provider) {
189
253
  const row = db.prepare(`SELECT * FROM quotas WHERE provider=? ORDER BY fetched_at DESC LIMIT 1`).get(provider);
@@ -213,21 +277,28 @@ function currentCycle(sorted) {
213
277
  }
214
278
  export function getBurnRates(db, now = Date.now()) {
215
279
  // Burn is the used-pct delta over a real rolling window of poll history
216
- // (up to 24h) within the current cycle.
217
- const rows = db.prepare(`SELECT provider, used_pct, fetched_at, resets_at FROM quotas`).all();
280
+ // (up to 24h) within the current cycle. Readings taken before the latest
281
+ // window opened are dropped: a rolling window that opens on first use
282
+ // (Codex) would otherwise price its first hours over idle time from before
283
+ // it existed. An estimated reset derives periodStart from the poll time,
284
+ // so the drop applies to verified clocks only.
285
+ const rows = db.prepare(`SELECT provider, used_pct, fetched_at, resets_at, period_start, resets_at_estimated FROM quotas`).all();
218
286
  const byProvider = new Map();
219
287
  for (const r of rows) {
220
288
  const t = new Date(r.fetched_at).getTime();
221
289
  if (Number.isNaN(t) || t > now)
222
290
  continue;
223
291
  const pts = byProvider.get(r.provider) ?? [];
224
- pts.push({ usedPct: r.used_pct, t, resetsAt: r.resets_at });
292
+ pts.push({ usedPct: r.used_pct, t, resetsAt: r.resets_at, periodStart: r.period_start, estimated: !!r.resets_at_estimated });
225
293
  byProvider.set(r.provider, pts);
226
294
  }
227
295
  const out = new Map();
228
296
  for (const [provider, all] of byProvider) {
229
- const sorted = currentCycle(all.sort((a, b) => a.t - b.t));
297
+ let sorted = currentCycle(all.sort((a, b) => a.t - b.t));
230
298
  const latest = sorted[sorted.length - 1];
299
+ const opened = latest.estimated || !latest.periodStart ? NaN : Date.parse(latest.periodStart);
300
+ if (Number.isFinite(opened))
301
+ sorted = sorted.filter((p) => p.t >= opened || p === latest);
231
302
  const cutoff = latest.t - 86400000;
232
303
  const windowStart = sorted.find((p) => p.t >= cutoff) ?? sorted[0];
233
304
  const days = (latest.t - windowStart.t) / 86400000;
@@ -291,10 +362,10 @@ export function getExhaustedTimestamps(db, now = Date.now()) {
291
362
  }
292
363
  return { weekly, monthly };
293
364
  }
294
- export function getHistoryBaseline(db, limit = 4) {
365
+ export function getHistoryBaseline(db, limit = 4, current) {
295
366
  let rows = [];
296
367
  try {
297
- rows = db.prepare(`SELECT provider, used_pct, resets_at_estimated FROM window_closes ORDER BY detected_at DESC, id DESC`).all();
368
+ rows = db.prepare(`SELECT provider, used_pct, sampled_at, period_start, resets_at, resets_at_estimated FROM window_closes ORDER BY detected_at DESC, id DESC`).all();
298
369
  }
299
370
  catch (e) {
300
371
  // A pre-observability database read offline is never migrated, so the
@@ -305,18 +376,26 @@ export function getHistoryBaseline(db, limit = 4) {
305
376
  const byProvider = new Map();
306
377
  for (const r of rows) {
307
378
  const closes = byProvider.get(r.provider) ?? [];
308
- closes.push({ usedPct: r.used_pct, verified: !r.resets_at_estimated });
379
+ closes.push({
380
+ usedPct: r.used_pct,
381
+ sampledAt: r.sampled_at,
382
+ periodStart: r.period_start ?? null,
383
+ resetsAt: r.resets_at ?? null,
384
+ resetsAtEstimated: !!r.resets_at_estimated,
385
+ });
309
386
  byProvider.set(r.provider, closes);
310
387
  }
311
388
  const out = new Map();
312
389
  for (const [provider, newestFirst] of byProvider) {
313
- const pool = newestFirst.slice(0, limit);
390
+ const pool = settleCloses(newestFirst, current?.get(provider)).slice(0, limit);
314
391
  if (!pool.length)
315
392
  continue;
316
- const verified = pool.filter((c) => c.verified);
393
+ const verified = pool.filter((c) => !c.resetsAtEstimated);
317
394
  const chosen = verified.length ? verified : pool;
318
- const mean = chosen.reduce((sum, c) => sum + c.usedPct, 0) / chosen.length;
319
- const rate = mean / 7;
395
+ const rates = chosen.map(closeDailyRate).filter((r) => r !== null);
396
+ if (!rates.length)
397
+ continue;
398
+ const rate = rates.reduce((sum, r) => sum + r, 0) / rates.length;
320
399
  if (Number.isFinite(rate))
321
400
  out.set(provider, rate);
322
401
  }
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // generated by scripts/build-embed.mjs — do not edit
2
- export const VERSION = "0.0.58";
2
+ export const VERSION = "0.0.60";
@@ -1,5 +1,7 @@
1
1
  import React from "react";
2
- import type { ProviderView, RecommendationView } from "../state.js";
2
+ import type { AdvisoryView, ProviderView, RecommendationView } from "../state.js";
3
+ /** Names the rate the forecast is priced at, matching the engine's blend inputs. */
4
+ export declare function forecastBasisWords(advisory: AdvisoryView | null | undefined): string;
3
5
  export declare function AdviceDrawer({ open, recommendation, providers, asOf, onClose, onSelectProvider, }: {
4
6
  open: boolean;
5
7
  recommendation: RecommendationView;
@@ -1,9 +1,24 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useEffect, useRef } from "react";
3
3
  import { quotaResetsAt, quotaUsedPct, timeLeft } from "./PaceBar.js";
4
+ import { clockText } from "../../../src/format/time.js";
4
5
  import { ProviderIcon, providerTint } from "./ProviderIcon.js";
5
6
  import { lanesFor } from "./Recommendation.js";
6
7
  import { CopyButton } from "./CopyButton.js";
8
+ /** Names the rate the forecast is priced at, matching the engine's blend inputs. */
9
+ export function forecastBasisWords(advisory) {
10
+ if (!advisory)
11
+ return "forecast pace";
12
+ const recent = advisory.recentRate ?? null;
13
+ const baseline = advisory.baselineRate ?? null;
14
+ if (recent !== null && baseline !== null)
15
+ return "24h pace blended with history";
16
+ if (recent !== null || advisory.paceSource === "recent")
17
+ return "24h pace";
18
+ if (advisory.paceSource === "window-average")
19
+ return "window-average pace";
20
+ return "forecast pace";
21
+ }
7
22
  export function AdviceDrawer({ open, recommendation, providers, asOf, onClose, onSelectProvider, }) {
8
23
  const dialogRef = useRef(null);
9
24
  const previouslyFocused = useRef(null);
@@ -55,7 +70,7 @@ export function AdviceDrawer({ open, recommendation, providers, asOf, onClose, o
55
70
  : null;
56
71
  // A monthly-bound pick's leftover is unusable until the month resets, so
57
72
  // the weekly expiry sentence would restate issue 109; show the reason.
58
- const monthlyBound = recommendation.bindingWindow === "monthly";
73
+ const monthlyBound = recommendation.bindingWindow === "monthly" || pick?.advisory?.bindingWindow === "monthly";
59
74
  const waste = monthlyBound
60
75
  ? null
61
76
  : recommendation.wastePct !== null
@@ -65,14 +80,20 @@ export function AdviceDrawer({ open, recommendation, providers, asOf, onClose, o
65
80
  : null;
66
81
  const pickReset = pick ? quotaResetsAt(pick) : null;
67
82
  const left = pickReset ? timeLeft(pickReset, asOfMs) : null;
68
- const basis = pick?.advisory?.paceSource === "window-average" ? "window-average pace" : "current 24h pace";
83
+ const pickClock = clockText(pickReset, asOfMs);
84
+ const basis = forecastBasisWords(pick?.advisory);
69
85
  const othersMore = useMore.filter((a) => a.provider !== pickId);
70
86
  const titleId = "advice-drawer-title";
71
- return (_jsxs(_Fragment, { children: [_jsx("div", { "data-testid": "advice-scrim", className: "scrim is-open", "aria-hidden": "true", onClick: onClose }), _jsxs("aside", { ref: dialogRef, tabIndex: -1, "data-testid": "advice-drawer", role: "dialog", "aria-modal": "true", "aria-labelledby": titleId, className: "drawer is-open", onClick: (e) => e.stopPropagation(), children: [_jsxs("div", { className: "drawer-head", children: [_jsx("span", { className: "picon rec-picon", "aria-hidden": "true", children: _jsx("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "m12 3-1.9 5.8a2 2 0 0 1-1.3 1.3L3 12l5.8 1.9a2 2 0 0 1 1.3 1.3L12 21l1.9-5.8a2 2 0 0 1 1.3-1.3L21 12l-5.8-1.9a2 2 0 0 1-1.3-1.3z" }) }) }), _jsxs("div", { style: { flex: 1 }, children: [_jsx("h2", { id: titleId, children: "Quota Advice & Pacing" }), _jsx("span", { className: "sub", children: "Which quota to burn next, and why" })] }), _jsx("button", { className: "drawer-close", type: "button", "aria-label": "Close advice", onClick: onClose, children: _jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.4", strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "M6 6l12 12M18 6L6 18" }) }) })] }), _jsxs("div", { className: "dsec", children: [_jsx("h3", { children: "Recommended for next session" }), pick && pickName ? (_jsxs("div", { className: "advice-card", style: { marginTop: 8 }, children: [_jsxs("div", { className: "advice-card-main", children: [_jsxs("div", { className: "advice-card-lead", children: [_jsx("span", { className: "sq", style: providerTint(pick.id), children: _jsx(ProviderIcon, { id: pick.id, title: pickName, size: 16 }) }), _jsxs("div", { style: { display: "flex", alignItems: "center", gap: 8 }, children: [_jsx("span", { className: "name", children: pickName }), _jsxs("span", { className: "recommended-badge", children: [_jsx("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m12 3-1.9 5.8a2 2 0 0 1-1.3 1.3L3 12l5.8 1.9a2 2 0 0 1 1.3 1.3L12 21l1.9-5.8a2 2 0 0 1 1.3-1.3L21 12l-5.8-1.9a2 2 0 0 1-1.3-1.3z" }) }), "Recommended"] })] })] }), waste !== null && left && (_jsxs("div", { className: "advice-card-stats", children: [_jsxs("b", { children: [waste, "%"] }), " unused quota expires in ", _jsx("b", { children: left })] }))] }), _jsx("p", { className: "advice-card-body", children: remaining !== null && left && !monthlyBound ? (_jsxs(_Fragment, { children: [_jsx("b", { children: pickName }), " has ", remaining, "% quota remaining with ", left, " to reset, forecast at the ", basis, "."] })) : (recommendation.reason) }), onSelectProvider && (_jsx("div", { children: _jsxs("button", { type: "button", className: "goto-link", onClick: () => onSelectProvider(pick.id), children: ["View ", pickName, " details \u2192"] }) }))] })) : (_jsx("p", { className: "advice-card-body", children: recommendation.reason }))] }), _jsxs("div", { className: "dsec", children: [_jsx("h3", { children: "Fleet Pacing Breakdown" }), _jsxs("dl", { className: "lane-group", children: [_jsxs("dt", { className: "um", children: [_jsx("span", { "aria-hidden": "true", children: "\u2191" }), " Use more"] }), _jsx("dd", { children: othersMore.length
87
+ return (_jsxs(_Fragment, { children: [_jsx("div", { "data-testid": "advice-scrim", className: "scrim is-open", "aria-hidden": "true", onClick: onClose }), _jsxs("aside", { ref: dialogRef, tabIndex: -1, "data-testid": "advice-drawer", role: "dialog", "aria-modal": "true", "aria-labelledby": titleId, className: "drawer is-open", onClick: (e) => e.stopPropagation(), children: [_jsxs("div", { className: "drawer-head", children: [_jsx("span", { className: "picon rec-picon", "aria-hidden": "true", children: _jsx("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "m12 3-1.9 5.8a2 2 0 0 1-1.3 1.3L3 12l5.8 1.9a2 2 0 0 1 1.3 1.3L12 21l1.9-5.8a2 2 0 0 1 1.3-1.3L21 12l-5.8-1.9a2 2 0 0 1-1.3-1.3z" }) }) }), _jsxs("div", { style: { flex: 1 }, children: [_jsx("h2", { id: titleId, children: "Quota Advice & Pacing" }), _jsx("span", { className: "sub", children: "Which quota to burn next, and why" })] }), _jsx("button", { className: "drawer-close", type: "button", "aria-label": "Close advice", onClick: onClose, children: _jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.4", strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "M6 6l12 12M18 6L6 18" }) }) })] }), _jsxs("div", { className: "dsec", children: [_jsx("h3", { children: "Recommended for next session" }), pick && pickName ? (_jsxs("div", { className: "advice-card", style: { marginTop: 8 }, children: [_jsxs("div", { className: "advice-card-main", children: [_jsxs("div", { className: "advice-card-lead", children: [_jsx("span", { className: "sq", style: providerTint(pick.id), children: _jsx(ProviderIcon, { title: pickName, size: 16 }) }), _jsxs("div", { style: { display: "flex", alignItems: "center", gap: 8 }, children: [_jsx("span", { className: "name", children: pickName }), _jsxs("span", { className: "recommended-badge", children: [_jsx("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m12 3-1.9 5.8a2 2 0 0 1-1.3 1.3L3 12l5.8 1.9a2 2 0 0 1 1.3 1.3L12 21l1.9-5.8a2 2 0 0 1 1.3-1.3L21 12l-5.8-1.9a2 2 0 0 1-1.3-1.3z" }) }), "Recommended"] })] })] }), waste !== null && left && (_jsxs("div", { className: "advice-card-stats", children: [_jsxs("b", { children: [waste, "%"] }), " unused at reset", pickClock ? _jsxs(_Fragment, { children: [" (", _jsx("b", { children: pickClock }), ")"] }) : null] }))] }), _jsx("p", { className: "advice-card-body", children: remaining !== null && left && !monthlyBound ? (_jsxs(_Fragment, { children: [_jsx("b", { children: pickName }), " has ", remaining, "% quota remaining with ", left, " to reset, forecast at the ", basis, "."] })) : (recommendation.reason) }), onSelectProvider && (_jsx("div", { children: _jsxs("button", { type: "button", className: "goto-link", onClick: () => onSelectProvider(pick.id), children: ["View ", pickName, " details \u2192"] }) }))] })) : (_jsx("p", { className: "advice-card-body", children: recommendation.reason }))] }), _jsxs("div", { className: "dsec", children: [_jsx("h3", { children: "Fleet Pacing Breakdown" }), _jsxs("dl", { className: "lane-group", children: [_jsxs("dt", { className: "um", children: [_jsx("span", { "aria-hidden": "true", children: "\u2191" }), " Use more"] }), _jsx("dd", { children: othersMore.length
72
88
  ? othersMore.map((a) => {
73
89
  const p = providers.find((x) => x.id === a.provider);
74
90
  const name = p?.displayName ?? a.provider;
75
- const unused = a.wastePct !== null ? `${Math.round(a.wastePct)}% unused` : null;
91
+ // A month-bound row reads the month, like its card.
92
+ const unused = a.bindingWindow === "monthly"
93
+ ? `${Math.round(a.bindingRemaining)}% of month left`
94
+ : a.wastePct !== null
95
+ ? `${Math.round(a.wastePct)}% unused at reset`
96
+ : null;
76
97
  const resetIso = p ? quotaResetsAt(p) : null;
77
98
  const t = resetIso ? timeLeft(resetIso, asOfMs) : null;
78
99
  const meta = [unused, t ? `resets in ${t}` : null].filter(Boolean).join(" · ");
@@ -5,12 +5,15 @@ export declare function lastClose(provider: {
5
5
  }): WindowCloseView | null;
6
6
  export declare function closeDateLabel(resetsAt: string | null): string | null;
7
7
  export declare function closeIsStale(c: WindowCloseView): boolean;
8
+ /** Milliseconds the provider reset ahead of schedule, or null for an on-schedule close. */
9
+ export declare function closeResetEarlyMs(c: WindowCloseView): number | null;
8
10
  export declare function closeSampleStamp(sampledAt: string): string | null;
9
11
  export declare function closeResetStamp(resetsAt: string): string | null;
10
12
  /** Bar chart of closed quota windows, oldest left. The solid segment is
11
13
  * used at close, the hatched cap is the stored leftover; a cap under 3% is
12
14
  * label-only. One bar per real close, never a placeholder. Stale samples
13
- * name their earliness on the label; exact stamps stay in the tooltip. */
15
+ * name their earliness on the label; a provider's early reset is dated when
16
+ * it was seen and named as a reset; exact stamps stay in the tooltip. */
14
17
  export declare function ClosedWeeks({ closes, windowName, }: {
15
18
  closes: WindowCloseView[];
16
19
  windowName?: "Weekly" | "Monthly";
@@ -1,6 +1,8 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { format } from "date-fns";
3
3
  const STALE_EARLY_MS = 15 * 60 * 1000;
4
+ // A drop seen this long before the scheduled reset means the provider reset early.
5
+ const EARLY_RESET_MS = 60 * 60 * 1000;
4
6
  export function lastClose(provider) {
5
7
  const closes = provider.lastCloses;
6
8
  return Array.isArray(closes) && closes.length > 0 ? closes[0] : null;
@@ -22,6 +24,13 @@ export function closeIsStale(c) {
22
24
  return true;
23
25
  return resetMs - sampledMs > STALE_EARLY_MS;
24
26
  }
27
+ /** Milliseconds the provider reset ahead of schedule, or null for an on-schedule close. */
28
+ export function closeResetEarlyMs(c) {
29
+ if (c.resetsAtEstimated || !c.resetsAt)
30
+ return null;
31
+ const early = Date.parse(c.resetsAt) - Date.parse(c.detectedAt);
32
+ return Number.isFinite(early) && early > EARLY_RESET_MS ? early : null;
33
+ }
25
34
  export function closeSampleStamp(sampledAt) {
26
35
  const ms = Date.parse(sampledAt);
27
36
  if (!Number.isFinite(ms))
@@ -63,16 +72,18 @@ function earlyWords(ms) {
63
72
  /** Bar chart of closed quota windows, oldest left. The solid segment is
64
73
  * used at close, the hatched cap is the stored leftover; a cap under 3% is
65
74
  * label-only. One bar per real close, never a placeholder. Stale samples
66
- * name their earliness on the label; exact stamps stay in the tooltip. */
75
+ * name their earliness on the label; a provider's early reset is dated when
76
+ * it was seen and named as a reset; exact stamps stay in the tooltip. */
67
77
  export function ClosedWeeks({ closes, windowName, }) {
68
78
  if (!Array.isArray(closes) || closes.length === 0)
69
79
  return null;
70
80
  const cells = [...closes].reverse();
71
- const labels = cells.map((c) => closeDateLabel(c.resetsAt));
81
+ const labels = cells.map((c) => closeDateLabel(closeResetEarlyMs(c) !== null ? c.detectedAt : c.resetsAt));
72
82
  return (_jsxs("section", { className: "dsec", "aria-label": "History", children: [windowName ? (_jsxs("div", { className: "burn-head", children: [_jsx("h3", { children: "History" }), _jsxs("span", { className: "burn-win", children: [windowName, " quota window"] })] })) : (_jsx("h3", { children: "History" })), _jsxs("div", { className: "hchart", "data-testid": "closed-weeks", children: [_jsx("div", { className: "hgrid", children: _jsx("span", { children: "100%" }) }), cells.map((c, i) => {
73
83
  const used = Math.min(100, Math.max(0, c.usedPct));
74
84
  const leftover = Math.min(100, Math.max(0, c.leftoverPct));
75
- const stale = closeIsStale(c);
85
+ const resetEarlyMs = closeResetEarlyMs(c);
86
+ const stale = resetEarlyMs === null && closeIsStale(c);
76
87
  const sampled = closeSampleStamp(c.sampledAt);
77
88
  const reset = c.resetsAt ? closeResetStamp(c.resetsAt) : null;
78
89
  const earlyMs = c.resetsAt ? Date.parse(c.resetsAt) - Date.parse(c.sampledAt) : NaN;
@@ -80,11 +91,12 @@ export function ClosedWeeks({ closes, windowName, }) {
80
91
  const title = [
81
92
  `${c.usedPct}% used`,
82
93
  `${c.leftoverPct}% leftover`,
83
- reset ? `reset ${reset}${est}` : "reset unknown",
94
+ resetEarlyMs !== null ? "provider reset early" : null,
95
+ reset ? `${resetEarlyMs !== null ? "scheduled reset" : "reset"} ${reset}${est}` : "reset unknown",
84
96
  stale && sampled ? `last reading ${sampled}` : null,
85
97
  ]
86
98
  .filter(Boolean)
87
99
  .join(", ");
88
- return (_jsxs("div", { className: "hcol", title: title, children: [_jsx("div", { className: "hbars", children: _jsxs("div", { className: "hbar", children: [leftover >= 3 && _jsx("span", { className: "hatch", style: { height: `${leftover}%` } }), _jsx("span", { className: "solid", style: { height: `${used}%` } })] }) }), _jsxs("div", { className: "hlab", children: [labels[i] ?? "date unknown", _jsxs("b", { children: [c.leftoverPct, "% leftover", est] }), stale && Number.isFinite(earlyMs) && earlyMs > 0 && _jsxs(_Fragment, { children: ["read ", earlyCompact(earlyMs), " early"] })] })] }, `${c.detectedAt}-${c.sampledAt}`));
100
+ return (_jsxs("div", { className: "hcol", title: title, children: [_jsx("div", { className: "hbars", children: _jsxs("div", { className: "hbar", children: [leftover >= 3 && _jsx("span", { className: "hatch", style: { height: `${leftover}%` } }), _jsx("span", { className: "solid", style: { height: `${used}%` } })] }) }), _jsxs("div", { className: "hlab", children: [labels[i] ?? "date unknown", _jsxs("b", { children: [c.leftoverPct, "% leftover", est] }), resetEarlyMs !== null && _jsxs(_Fragment, { children: ["reset ", earlyCompact(resetEarlyMs), " early"] }), stale && Number.isFinite(earlyMs) && earlyMs > 0 && _jsxs(_Fragment, { children: ["read ", earlyCompact(earlyMs), " early"] })] })] }, `${c.detectedAt}-${c.sampledAt}`));
89
101
  })] })] }));
90
102
  }