quotacap 0.0.57 → 0.0.59

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 (56) 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 +9 -4
  8. package/dist/cli/models.js +2 -2
  9. package/dist/cli/status.js +2 -2
  10. package/dist/format/markdown.d.ts +1 -1
  11. package/dist/format/markdown.js +11 -8
  12. package/dist/format/rate-limit-wait.d.ts +38 -0
  13. package/dist/format/rate-limit-wait.js +86 -0
  14. package/dist/format/rows.d.ts +46 -6
  15. package/dist/format/rows.js +50 -42
  16. package/dist/format/terminal.d.ts +1 -1
  17. package/dist/format/terminal.js +28 -14
  18. package/dist/format/time.d.ts +19 -0
  19. package/dist/format/time.js +69 -0
  20. package/dist/mcp/server.d.ts +25 -5
  21. package/dist/mcp/server.js +38 -4
  22. package/dist/store/quotas.d.ts +7 -2
  23. package/dist/store/quotas.js +94 -15
  24. package/dist/version.js +1 -1
  25. package/dist/web/src/components/AdviceDrawer.d.ts +3 -1
  26. package/dist/web/src/components/AdviceDrawer.js +25 -4
  27. package/dist/web/src/components/ClosedWeeks.d.ts +4 -1
  28. package/dist/web/src/components/ClosedWeeks.js +17 -5
  29. package/dist/web/src/components/PaceBar.d.ts +26 -25
  30. package/dist/web/src/components/PaceBar.js +57 -119
  31. package/dist/web/src/components/PacingLegend.js +9 -8
  32. package/dist/web/src/components/ProviderCard.js +2 -1
  33. package/dist/web/src/components/ProviderDrawer.d.ts +9 -2
  34. package/dist/web/src/components/ProviderDrawer.js +38 -27
  35. package/dist/web/src/components/ProviderRow.js +2 -1
  36. package/dist/web/src/components/RateLimitNote.d.ts +7 -0
  37. package/dist/web/src/components/RateLimitNote.js +11 -0
  38. package/dist/web/src/components/Recommendation.d.ts +4 -3
  39. package/dist/web/src/components/Recommendation.js +11 -7
  40. package/dist/web/src/components/ResetRail.d.ts +2 -0
  41. package/dist/web/src/components/ResetRail.js +15 -5
  42. package/dist/web/src/components/WindowsRow.d.ts +2 -2
  43. package/dist/web/src/components/WindowsRow.js +3 -13
  44. package/dist/web/src/components/settings/ProvidersPanel.d.ts +3 -2
  45. package/dist/web/src/components/settings/ProvidersPanel.js +4 -1
  46. package/dist/web/src/pages/Onboarding.js +1 -1
  47. package/dist/web/src/state.d.ts +5 -0
  48. package/dist/web/src/state.js +18 -0
  49. package/dist/webAssets.js +1 -1
  50. package/dist/webHtml.js +1 -1
  51. package/package.json +1 -1
  52. package/web/dist/assets/index-DQ2jUHo6.js +13 -0
  53. package/web/dist/assets/index-DSNVHbgI.css +1 -0
  54. package/web/dist/index.html +2 -2
  55. package/web/dist/assets/index-BFBVZ1r_.js +0 -13
  56. package/web/dist/assets/index-Co33DTl5.css +0 -1
package/README.md CHANGED
@@ -70,7 +70,7 @@ No setup ceremony: config is provisioned on first use, and bare `quotacap` is th
70
70
 
71
71
  Use `"command": "npx", "args": ["quotacap", "mcp"]` when installed via npm only.
72
72
 
73
- Tools: `get_quotas`, `get_recommendation`, `forecast`.
73
+ Tools: `get_quotas`, `get_recommendation`, `forecast`, `get_models`. `get_recommendation` returns the pick, its reason, and each other provider's state, availability and reset; pass `verbose: true` for every quota, advisory and model list.
74
74
 
75
75
  ## HTTP API
76
76
 
@@ -29,7 +29,7 @@ export interface RecoveryDeps {
29
29
  */
30
30
  export declare function recoverSubscription(deps: RecoveryDeps): Promise<ParsedQuota>;
31
31
  export declare function museProbeDir(): string;
32
- export declare function parseMusePlan(cleaned: string): string;
32
+ export declare function parseMusePlan(text: string): string;
33
33
  export declare function parseMuseQuotaExhausted(text: string, plan?: string, now?: Date): ParsedQuota | null;
34
34
  export declare function parseMuseTui(text: string, now?: Date, dims?: Partial<GridDims>): ParsedQuota;
35
35
  export declare const museAdapter: {
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { parseResetText } from "./parse.js";
5
- import { runPty } from "./pty.js";
5
+ import { runPty, stripAnsi } from "./pty.js";
6
6
  import { parseScreens } from "./vt.js";
7
7
  import { adapterSignal, trackedExecFile } from "../runtime/spawn.js";
8
8
  import { attachEvidence, getErrorEvidence } from "../diagnostics/failure.js";
@@ -89,8 +89,10 @@ export async function recoverSubscription(deps) {
89
89
  export function museProbeDir() {
90
90
  return path.join(process.env.QUOTACAP_HOME ?? os.homedir(), ".quotacap", "muse-probe");
91
91
  }
92
- export function parseMusePlan(cleaned) {
93
- const planMatch = cleaned.match(/Subscription\s*·\s*Muse Code\s+(.+?)(?:\s{2,}|\r?\n|$)/i);
92
+ // The recovery path hands over raw stdout, so escape codes are stripped here
93
+ // and the match stops at the panel's box-drawing border.
94
+ export function parseMusePlan(text) {
95
+ const planMatch = stripAnsi(text).match(/Subscription\s*·\s*Muse Code\s+(.+?)(?:\s{2,}|\s*[\u2500-\u257F]|\r?\n|$)/i);
94
96
  return planMatch ? planMatch[1].trim() : "unknown";
95
97
  }
96
98
  export function parseMuseQuotaExhausted(text, plan = "unknown", now = new Date()) {
@@ -1,4 +1,5 @@
1
1
  import { MIN_PACE_SPAN_DAYS, BLEND_K, RISK_MARGIN, GATE_TOL, paceTube } from "./types.js";
2
+ import { durationFromDays, unusedAtReset } from "../format/time.js";
2
3
  const DAY_MS = 86400000;
3
4
  /**
4
5
  * Pace from a single reading.
@@ -160,7 +161,10 @@ export function computeAdvisory(q, recent, baseline, now = new Date(), exhausted
160
161
  const estimated = q.resetsAtEstimated === true;
161
162
  const gate = elapsed !== null && !estimated && q.weeklyPct >= elapsed * (1 - GATE_TOL);
162
163
  const aheadOfElapsed = elapsed !== null && !estimated && q.weeklyPct > elapsed * (1 + GATE_TOL);
163
- const wastePct = Math.max(0, remaining - burnRate * daysLeft);
164
+ // Waste never assumes a pace slower than the one measured now: the blend
165
+ // may lean on a quieter history, but a provider whose 24h rate already
166
+ // spends its remainder has nothing spare to recommend.
167
+ const wastePct = Math.max(0, remaining - Math.max(recent ?? 0, burnRate) * daysLeft);
164
168
  const daysToExhaust = burnRate > 0 ? remaining / burnRate : Infinity;
165
169
  const over = daysToExhaust < daysLeft * (1 - RISK_MARGIN);
166
170
  const missFrac = Number.isFinite(daysToExhaust) ? Math.abs(daysToExhaust - daysLeft) / daysLeft : Infinity;
@@ -231,8 +235,8 @@ export function recommend(quotas, _task, paceByProvider = new Map(), now = new D
231
235
  return {
232
236
  use: use.provider,
233
237
  reason: use.bindingWindow === "monthly"
234
- ? `${Math.round(use.bindingRemaining)}% of month left in ${use.bindingDaysLeft.toFixed(1)}d`
235
- : `${Math.round(use.wastePct)}% waste in ${use.daysLeft.toFixed(1)}d`,
238
+ ? `${Math.round(use.bindingRemaining)}% of month left in ${durationFromDays(use.bindingDaysLeft)}`
239
+ : unusedAtReset(use.wastePct, quotas.find(q => q.provider === use.provider)?.resetsAt, now.getTime()),
236
240
  wastePct: rankWaste(use),
237
241
  idealRate: use.idealRate,
238
242
  recommendationBasis: "known-waste",
@@ -248,8 +252,8 @@ export function recommend(quotas, _task, paceByProvider = new Map(), now = new D
248
252
  return {
249
253
  use: use.provider,
250
254
  reason: use.bindingWindow === "monthly"
251
- ? `Measuring pace; ${Math.round(use.bindingRemaining)}% of month left with ${use.bindingDaysLeft.toFixed(1)}d until reset`
252
- : `Measuring pace; ${Math.round(use.remaining)}% remains with ${use.daysLeft.toFixed(1)}d until reset`,
255
+ ? `Measuring pace; ${Math.round(use.bindingRemaining)}% of month left with ${durationFromDays(use.bindingDaysLeft)} until reset`
256
+ : `Measuring pace; ${Math.round(use.remaining)}% remains with ${durationFromDays(use.daysLeft)} until reset`,
253
257
  wastePct: null,
254
258
  idealRate: use.idealRate,
255
259
  recommendationBasis: "unknown-headroom",
@@ -52,12 +52,12 @@ export function buildSnapshot(db, opts) {
52
52
  const unionIds = Array.from(new Set([...opts.enabledProviders, ...storedIds])).sort((a, b) => a.localeCompare(b));
53
53
  const burnRates = getBurnRates(db, asOfMs);
54
54
  const exhaustedTimestamps = getExhaustedTimestamps(db, asOfMs);
55
- const history = getHistoryBaseline(db);
55
+ const history = getHistoryBaseline(db, 4, quotaMap);
56
56
  const catalogMap = getCatalogs(db);
57
57
  const providerSnapshots = [];
58
58
  const eligibleQuotas = [];
59
59
  const paceByProvider = new Map();
60
- const allValidAdvisories = [];
60
+ const eligibleAdvisories = [];
61
61
  for (const id of unionIds) {
62
62
  const quota = quotaMap.get(id) ?? null;
63
63
  let attempt = attemptMap.get(id) ?? null;
@@ -149,10 +149,9 @@ export function buildSnapshot(db, opts) {
149
149
  if (quota?.resetsAtEstimated) {
150
150
  evidence.push("estimated-reset");
151
151
  }
152
- if (advisory) {
153
- allValidAdvisories.push(advisory);
154
- }
155
152
  if (enabled && quota !== null && exclusionReason === null) {
153
+ if (advisory)
154
+ eligibleAdvisories.push(advisory);
156
155
  eligibleQuotas.push(quota);
157
156
  if (pace)
158
157
  paceByProvider.set(id, pace);
@@ -178,11 +177,11 @@ export function buildSnapshot(db, opts) {
178
177
  evidence,
179
178
  exclusionReason,
180
179
  advisory,
181
- lastCloses: getWindowCloses(db, id, 4, closeWindow),
180
+ lastCloses: getWindowCloses(db, id, 4, closeWindow, quota),
182
181
  catalog,
183
182
  });
184
183
  }
185
- // 2. Recommendation: ranked from eligible providers only; advisories cover all valid rows
184
+ // 2. Recommendation: ranked from eligible providers only; advisories cover the same rows
186
185
  let recommendation;
187
186
  if (!eligibleQuotas.length) {
188
187
  recommendation = {
@@ -196,7 +195,7 @@ export function buildSnapshot(db, opts) {
196
195
  catalogStatus: "unfetched",
197
196
  catalogFetchedAt: null,
198
197
  alternatives: [],
199
- advisories: allValidAdvisories,
198
+ advisories: eligibleAdvisories,
200
199
  };
201
200
  }
202
201
  else {
@@ -204,8 +203,8 @@ export function buildSnapshot(db, opts) {
204
203
  const chosenProvider = eligibleQuotas.find((q) => q.provider === rec.use);
205
204
  let reason = rec.reason;
206
205
  if (chosenProvider?.resetsAtEstimated) {
207
- if (reason.includes("waste in")) {
208
- reason = reason.replace("waste in", "estimated waste in");
206
+ if (reason.includes("unused at reset")) {
207
+ reason = reason.replace("unused at reset", "unused at estimated reset");
209
208
  }
210
209
  else if (reason.includes("until reset")) {
211
210
  reason = reason.replace("until reset", "until estimated reset");
@@ -228,7 +227,7 @@ export function buildSnapshot(db, opts) {
228
227
  catalogStatus: rec.use === "none" ? "unfetched" : pickCatalog.status,
229
228
  catalogFetchedAt: pickCatalog.fetchedAt,
230
229
  alternatives: alternativesWithCatalog,
231
- advisories: allValidAdvisories,
230
+ advisories: eligibleAdvisories,
232
231
  };
233
232
  }
234
233
  return {
@@ -1,3 +1,3 @@
1
- import type { Command } from "commander";
1
+ import { type Command } from "commander";
2
2
  import type { ClientCommandDeps } from "./clients.js";
3
3
  export declare function registerAdviseCommand(program: Command, deps: ClientCommandDeps): void;
@@ -1,4 +1,9 @@
1
+ // advise: which provider to use next, over the shared projection. The
2
+ // hidden --task flag is still accepted and validated for old scripts, but it
3
+ // never changes the ranking, so help no longer offers it.
4
+ import { Option } from "commander";
1
5
  import { projectRecommendationResponse } from "../advisory/snapshot.js";
6
+ import { renderRecommendationSummary } from "../format/markdown.js";
2
7
  import { validateTask } from "../advisory/validate.js";
3
8
  import { ensureConfig, getDbPath } from "../config.js";
4
9
  import { createServiceClient } from "../runtime/client.js";
@@ -36,9 +41,9 @@ export function registerAdviseCommand(program, deps) {
36
41
  (() => refreshUpdateCache({ channel: detectChannel(), current: VERSION }));
37
42
  program
38
43
  .command("advise")
39
- .description("show which provider to use next (same advice for every task)")
44
+ .description("show which provider to use next")
40
45
  .option("--json", "machine-readable output")
41
- .option("--task <t>", "task type: any|heavy|light", "any")
46
+ .addOption(new Option("--task <t>").default("any").hideHelp())
42
47
  .action(async (o) => {
43
48
  // Task validation precedes any I/O: a bogus task never touches the
44
49
  // network, config, or database.
@@ -128,7 +133,7 @@ export function registerAdviseCommand(program, deps) {
128
133
  if (o.json)
129
134
  console.log(JSON.stringify(rec, null, 2));
130
135
  else {
131
- console.log(`${rec.use}: ${rec.reason}`);
136
+ console.log(renderRecommendationSummary(emptySnapshot(t, cfg.providerNames), t));
132
137
  printVersionLine(o, VERSION, health?.version);
133
138
  printUpdateFooter(o, footer);
134
139
  }
@@ -144,7 +149,7 @@ export function registerAdviseCommand(program, deps) {
144
149
  if (o.json)
145
150
  console.log(JSON.stringify(rec, null, 2));
146
151
  else {
147
- console.log(`${rec.use}: ${rec.reason}`);
152
+ console.log(renderRecommendationSummary(resolved.snapshot, t));
148
153
  const modelsLine = formatModelsLine(rec, t, cfg.catalogTtlHours);
149
154
  if (modelsLine)
150
155
  console.log(modelsLine);
@@ -40,11 +40,11 @@ function printTable(list) {
40
40
  });
41
41
  const maxProv = Math.max(8, ...rows.map((r) => r.prov.length));
42
42
  const maxLeft = Math.max(8, ...rows.map((r) => r.leftover.length));
43
- const maxStat = Math.max(6, ...rows.map((r) => r.status.length));
43
+ const maxStat = Math.max("CATALOG".length, ...rows.map((r) => r.status.length));
44
44
  const header = [
45
45
  "PROVIDER".padEnd(maxProv),
46
46
  "LEFTOVER".padEnd(maxLeft),
47
- "STATUS".padEnd(maxStat),
47
+ "CATALOG".padEnd(maxStat),
48
48
  "MODELS",
49
49
  ].join(" ");
50
50
  const lines = rows.map((r) => [r.prov.padEnd(maxProv), r.leftover.padEnd(maxLeft), r.status.padEnd(maxStat), r.ids].join(" "));
@@ -2,7 +2,7 @@ import { projectQuotasResponse } from "../advisory/snapshot.js";
2
2
  import { ensureConfig, getDbPath } from "../config.js";
3
3
  import { renderCompact, renderNarrow, renderWide } from "../format/terminal.js";
4
4
  import { renderIssues } from "../format/issues.js";
5
- import { assertValidSortKey } from "../format/rows.js";
5
+ import { COMPACT_LEGEND, assertValidSortKey } from "../format/rows.js";
6
6
  import { createServiceClient } from "../runtime/client.js";
7
7
  import { VERSION } from "../version.js";
8
8
  import { isServiceManaged, runServiceCommand } from "../service/index.js";
@@ -25,7 +25,7 @@ export function registerStatusCommand(program, deps) {
25
25
  .command("status")
26
26
  .description("show quota status (service when reachable, stored readings otherwise)")
27
27
  .option("--json", "machine-readable output")
28
- .option("--compact", "one-line statusline")
28
+ .option("--compact", `one-line statusline (${COMPACT_LEGEND})`)
29
29
  .option("--ascii", "ASCII glyphs without color")
30
30
  .option("--sort <key>", "row order: recommended|reset-asc|reset-desc|used-desc|used-asc", "recommended")
31
31
  .option("--verbose", "show provider failure guidance and diagnostics")
@@ -1,4 +1,4 @@
1
1
  import type { StateSnapshot } from "../advisory/types.js";
2
2
  export declare function renderMarkdownTable(snapshot: StateSnapshot, now: Date): string;
3
- export declare function renderRecommendationSummary(snapshot: StateSnapshot): string;
3
+ export declare function renderRecommendationSummary(snapshot: StateSnapshot, now?: Date): string;
4
4
  export declare function renderModelsMarkdownTable(models: any[]): string;
@@ -1,26 +1,29 @@
1
- import { buildRow, sortProviders } from "./rows.js";
1
+ import { rateLimitWaitLines } from "./rate-limit-wait.js";
2
+ import { buildRow, shownProviders, sortProviders, useName } from "./rows.js";
2
3
  function esc(cell) {
3
4
  return cell.replace(/\|/g, "\\|").replace(/[\r\n]+/g, " ");
4
5
  }
5
6
  export function renderMarkdownTable(snapshot, now) {
6
7
  const use = snapshot.recommendation.use;
7
- const sorted = sortProviders(snapshot.providers, "recommended", use);
8
+ const sorted = sortProviders(shownProviders(snapshot.providers), "recommended", use);
8
9
  const lines = sorted.map((p) => {
9
10
  const row = buildRow(p, now);
10
11
  const name = p.id === use && use !== "none" ? `★ ${p.displayName}` : p.displayName;
11
12
  const used = row.usedPct === null ? "—" : `${row.usedPct}%`;
12
13
  const elapsed = row.elapsedPct === null ? "—" : `${row.elapsedPct}%`;
13
- return `| ${esc(name)} | ${used} | ${elapsed} | ${esc(row.pace)} | ${esc(row.countdown)} | ${esc(row.state)} | ${esc(row.forecast)} |`;
14
+ const wait = row.wait === "" ? "—" : row.wait;
15
+ return `| ${esc(name)} | ${used} | ${elapsed} | ${esc(row.pace)} | ${esc(row.countdown)} | ${esc(row.state)} | ${esc(row.forecast)} | ${esc(wait)} |`;
14
16
  });
15
17
  return [
16
- "| Provider | Used | Elapsed | Pace (%/day avg · 24h) | Resets | State | Forecast |",
17
- "|---|---|---|---|---|---|---|",
18
+ "| Provider | Used | Elapsed | Pace (%/day avg · 24h) | Resets | State | Forecast | Wait |",
19
+ "|---|---|---|---|---|---|---|---|",
18
20
  ...lines,
19
21
  ].join("\n");
20
22
  }
21
- export function renderRecommendationSummary(snapshot) {
23
+ export function renderRecommendationSummary(snapshot, now = new Date(snapshot.asOf)) {
22
24
  const rec = snapshot.recommendation;
23
- return `${rec.use}: ${rec.reason}`;
25
+ const waits = rateLimitWaitLines(shownProviders(snapshot.providers), now);
26
+ return [`${useName(snapshot)}: ${rec.reason}`, ...waits].join("\n");
24
27
  }
25
28
  export function renderModelsMarkdownTable(models) {
26
29
  const lines = models.map((m) => {
@@ -31,7 +34,7 @@ export function renderModelsMarkdownTable(models) {
31
34
  return `| ${esc(name)} | ${leftover} | ${esc(status)} | ${esc(ids)} |`;
32
35
  });
33
36
  return [
34
- "| Provider | Leftover | Status | Models |",
37
+ "| Provider | Leftover | Catalog | Models |",
35
38
  "|---|---|---|---|",
36
39
  ...lines,
37
40
  ].join("\n");
@@ -0,0 +1,38 @@
1
+ export type RateLimitWindow = "five-hour" | "weekly";
2
+ export interface RateLimitWait {
3
+ window: RateLimitWindow;
4
+ label: "5h limit" | "Weekly limit";
5
+ /** Reported finish instant. Null when the provider did not report one. */
6
+ resetsAt: string | null;
7
+ /** Shared clock, e.g. "Thu 18:59" within a week, else "Thu 23 Oct 18:59". */
8
+ until: string | null;
9
+ text: string;
10
+ }
11
+ export interface RateLimitSource {
12
+ exclusionReason?: string | null;
13
+ quota?: {
14
+ weeklyPct?: number | null;
15
+ resetsAt?: string | null;
16
+ fiveHourPct?: number | null;
17
+ /** One-release alias for fiveHourPct. */
18
+ sessionPct?: number | null;
19
+ fiveHourResetsAt?: string | null;
20
+ monthlyPct?: number | null;
21
+ monthlyResetsAt?: string | null;
22
+ monthlyStatus?: "ok" | "exhausted" | null;
23
+ monthlyKind?: "included" | null;
24
+ } | null;
25
+ }
26
+ /** The shared clock: "Thu 18:59" within a week of `nowMs`, else "Thu 23 Oct 18:59". */
27
+ export declare function limitStamp(iso: string, nowMs?: number): string | null;
28
+ /**
29
+ * Short windows that are full while the reset-window quota still has room.
30
+ * A 5h window on any plan, and the week on a plan whose quota resets monthly.
31
+ * A full week on a weekly plan is the quota itself, so it stays with the
32
+ * quota badge. An exhausted included month already blocks the provider.
33
+ */
34
+ export declare function rateLimitWaits(source: RateLimitSource, now: Date): RateLimitWait[];
35
+ /** One sentence per provider that has a short window to wait out. Snapshot order. */
36
+ export declare function rateLimitWaitLines(providers: Array<RateLimitSource & {
37
+ displayName: string;
38
+ }>, now: Date): string[];
@@ -0,0 +1,86 @@
1
+ // A full short window the user has to wait out. Presentation only:
2
+ // pace, forecast, and which provider to use next stay on the reset window.
3
+ import { clockText } from "./time.js";
4
+ /** The shared clock: "Thu 18:59" within a week of `nowMs`, else "Thu 23 Oct 18:59". */
5
+ export function limitStamp(iso, nowMs) {
6
+ return clockText(iso, nowMs);
7
+ }
8
+ function instant(iso) {
9
+ if (!iso)
10
+ return null;
11
+ const ms = Date.parse(iso);
12
+ return Number.isFinite(ms) ? ms : null;
13
+ }
14
+ /** True when the window has not been reported as already finished. */
15
+ function stillOpen(iso, nowMs) {
16
+ const ms = instant(iso);
17
+ return ms === null || ms > nowMs;
18
+ }
19
+ function includedMonth(q) {
20
+ return q.monthlyKind === "included" && typeof q.monthlyPct === "number" && !!q.monthlyResetsAt;
21
+ }
22
+ function monthExhausted(q) {
23
+ return q.monthlyStatus === "exhausted" || (typeof q.monthlyPct === "number" && q.monthlyPct >= 100);
24
+ }
25
+ function waitFor(window, label, iso, nowMs) {
26
+ const resetsAt = instant(iso) === null ? null : iso ?? null;
27
+ const until = resetsAt ? limitStamp(resetsAt, nowMs) : null;
28
+ return {
29
+ window,
30
+ label,
31
+ resetsAt,
32
+ until,
33
+ text: until ? `${label} until ${until}` : `${label} reached`,
34
+ };
35
+ }
36
+ /**
37
+ * Short windows that are full while the reset-window quota still has room.
38
+ * A 5h window on any plan, and the week on a plan whose quota resets monthly.
39
+ * A full week on a weekly plan is the quota itself, so it stays with the
40
+ * quota badge. An exhausted included month already blocks the provider.
41
+ */
42
+ export function rateLimitWaits(source, now) {
43
+ if (source.exclusionReason)
44
+ return [];
45
+ const q = source.quota;
46
+ if (!q)
47
+ return [];
48
+ const nowMs = now.getTime();
49
+ const monthly = includedMonth(q);
50
+ if (monthly && monthExhausted(q))
51
+ return [];
52
+ const weekFull = typeof q.weeklyPct === "number" && q.weeklyPct >= 100;
53
+ if (!monthly && weekFull)
54
+ return [];
55
+ const waits = [];
56
+ const five = q.fiveHourPct ?? q.sessionPct;
57
+ if (typeof five === "number" && five >= 100 && stillOpen(q.fiveHourResetsAt, nowMs)) {
58
+ waits.push(waitFor("five-hour", "5h limit", q.fiveHourResetsAt, nowMs));
59
+ }
60
+ if (monthly && weekFull && stillOpen(q.resetsAt, nowMs)) {
61
+ waits.push(waitFor("weekly", "Weekly limit", q.resetsAt, nowMs));
62
+ }
63
+ waits.sort((a, b) => {
64
+ const am = instant(a.resetsAt);
65
+ const bm = instant(b.resetsAt);
66
+ if (am === null && bm === null)
67
+ return 0;
68
+ if (am === null)
69
+ return 1;
70
+ if (bm === null)
71
+ return -1;
72
+ return am - bm;
73
+ });
74
+ return waits;
75
+ }
76
+ /** One sentence per provider that has a short window to wait out. Snapshot order. */
77
+ export function rateLimitWaitLines(providers, now) {
78
+ const lines = [];
79
+ for (const provider of providers) {
80
+ const waits = rateLimitWaits(provider, now);
81
+ if (waits.length === 0)
82
+ continue;
83
+ lines.push(`${provider.displayName}: ${waits.map((w) => w.text).join(" · ")}`);
84
+ }
85
+ return lines;
86
+ }
@@ -1,8 +1,8 @@
1
- import type { ProviderSnapshot } from "../advisory/types.js";
1
+ import type { Advisory, ProviderSnapshot } from "../advisory/types.js";
2
2
  export type StateWord = "On track" | "Behind pace" | "Ahead of pace" | "Cap risk" | "Watch" | "Measuring" | "Not reporting" | "Monthly exhausted" | "Quota exhausted";
3
3
  export type RailCell = "used" | "tick" | "unused";
4
4
  export type SortKey = "recommended" | "reset-asc" | "reset-desc" | "used-desc" | "used-asc";
5
- export type CompactSuffix = "" | "!" | "~" | "?";
5
+ export type CompactSuffix = "" | "<" | ">" | "~" | "!" | "x" | "?" | "-";
6
6
  export interface Row {
7
7
  id: string;
8
8
  state: StateWord;
@@ -13,6 +13,12 @@ export interface Row {
13
13
  railCells: RailCell[];
14
14
  /** Compact pace pair without units, e.g. "10.6 avg · 0.0 24h". Surfaces label %/day once. */
15
15
  pace: string;
16
+ /**
17
+ * Full short window the user has to wait out, with the date and time it
18
+ * clears. Empty when the reset-window quota is the block, or no short
19
+ * window is full. Never changes `state` or `forecast`.
20
+ */
21
+ wait: string;
16
22
  }
17
23
  export declare const RAIL_CELLS = 20;
18
24
  export declare const SORT_KEYS: SortKey[];
@@ -22,11 +28,29 @@ export declare const SORT_KEYS: SortKey[];
22
28
  * elapsed, and pace read it. Weekly-bound rows fall back to the weekly
23
29
  * fields unchanged; rate-limit windows never drive these figures.
24
30
  */
25
- export declare function isMonthlyBound(ps: ProviderSnapshot): boolean;
31
+ /**
32
+ * The fields the state word and the binding helpers read. Structural, so
33
+ * the dashboard's ProviderView feeds the same table as the CLI snapshot.
34
+ */
35
+ export interface StateSource {
36
+ exclusionReason: string | null;
37
+ advisory: (Pick<Advisory, "bindingWindow" | "bindingRemaining" | "remaining" | "status" | "urgency"> & {
38
+ closeToReset?: boolean;
39
+ aheadOfElapsed?: boolean | null;
40
+ }) | null;
41
+ quota: {
42
+ weeklyPct?: number;
43
+ usedPct?: number;
44
+ monthlyKind?: string;
45
+ monthlyPct?: number;
46
+ monthlyResetsAt?: string;
47
+ } | null;
48
+ }
49
+ export declare function isMonthlyBound(ps: StateSource): boolean;
26
50
  /** Reset instant of the quota window, or null without a quota reading. */
27
51
  export declare function bindingResetsAt(ps: ProviderSnapshot): string | null;
28
52
  /** Used percent of the quota window. Null without a quota reading. */
29
- export declare function bindingUsedPct(ps: ProviderSnapshot): number | null;
53
+ export declare function bindingUsedPct(ps: StateSource): number | null;
30
54
  /**
31
55
  * Binding leftover for a raw quota without an advisory (model catalogs):
32
56
  * the same scarcer-headroom rule the engine applies, so the catalog
@@ -55,9 +79,25 @@ export declare function countdownText(ps: ProviderSnapshot, now: Date): string;
55
79
  export declare function elapsedPct(ps: ProviderSnapshot, now: Date): number | null;
56
80
  export declare function usedPctOf(ps: ProviderSnapshot): number | null;
57
81
  export declare function railCells(ps: ProviderSnapshot, now: Date): RailCell[];
58
- export declare function stateWord(ps: ProviderSnapshot): StateWord;
82
+ export declare function stateWord(ps: StateSource): StateWord;
59
83
  export declare function forecastText(ps: ProviderSnapshot, now: Date): string;
60
- export declare function compactSuffix(ps: ProviderSnapshot): CompactSuffix;
84
+ export declare const COMPACT_LEGEND = "no mark on track, < behind, > ahead, ~ watch, ! cap risk, x exhausted, ? measuring, - not reporting";
85
+ export declare function compactSuffix(ps: StateSource): CompactSuffix;
86
+ /**
87
+ * Providers a human surface lists: the enabled ones, as the dashboard
88
+ * shows them. JSON keeps every provider with its exclusion reason.
89
+ */
90
+ export declare function shownProviders(providers: ProviderSnapshot[]): ProviderSnapshot[];
91
+ /** Display name of the recommended provider, or "none". */
92
+ export declare function useName(snapshot: {
93
+ recommendation: {
94
+ use: string;
95
+ };
96
+ providers: Array<{
97
+ id: string;
98
+ displayName: string;
99
+ }>;
100
+ }): string;
61
101
  export declare function assertValidSortKey(key: string): asserts key is SortKey;
62
102
  export declare function sortProviders(providers: ProviderSnapshot[], key: string, use: string): ProviderSnapshot[];
63
103
  export declare function paceText(ps: ProviderSnapshot, now?: Date): string;
@@ -1,20 +1,14 @@
1
+ import { rateLimitWaits } from "./rate-limit-wait.js";
2
+ import { dayText, durationFromDays, durationText, unusedAtReset } from "./time.js";
1
3
  export const RAIL_CELLS = 20;
2
4
  export const SORT_KEYS = ["recommended", "reset-asc", "reset-desc", "used-desc", "used-asc"];
3
5
  const DAY_MS = 86400000;
4
- const HOUR_MS = 3600000;
5
- const MIN_MS = 60000;
6
6
  function msOf(iso) {
7
7
  if (!iso)
8
8
  return null;
9
9
  const ms = new Date(iso).getTime();
10
10
  return Number.isNaN(ms) ? null : ms;
11
11
  }
12
- /**
13
- * Quota-window resolution, mirroring the dashboard helpers: the advisory
14
- * binding window rations the account, so standalone resets, usage,
15
- * elapsed, and pace read it. Weekly-bound rows fall back to the weekly
16
- * fields unchanged; rate-limit windows never drive these figures.
17
- */
18
12
  export function isMonthlyBound(ps) {
19
13
  return (ps.advisory?.bindingWindow === "monthly" &&
20
14
  ps.quota?.monthlyKind === "included" &&
@@ -93,23 +87,17 @@ export function bindingAvgPace(ps, now) {
93
87
  export function weeklyPctOf(q) {
94
88
  return q?.weeklyPct ?? q?.usedPct;
95
89
  }
96
- // Compact duration: 7d / 12h / 45m. Countdown convention floors; sub-minute
97
- // spans read 1m so a live window never prints 0m.
90
+ // Countdown in the shared floored form ("6d 23h", "5h 12m", "45m").
98
91
  export function fmtDuration(ms) {
99
- if (ms >= 48 * HOUR_MS)
100
- return `${Math.floor(ms / DAY_MS)}d`;
101
- if (ms >= 90 * MIN_MS)
102
- return `${Math.floor(ms / HOUR_MS)}h`;
103
- return `${Math.max(1, Math.floor(ms / MIN_MS))}m`;
92
+ return durationText(ms);
104
93
  }
105
94
  // Short weekday plus calendar date of an ISO instant in the locked English
106
- // copy, e.g. "Tue Sep 15". Pinned to en-US: the sentence it feeds
107
- // ("unused until Tue Sep 15") is English, so a non-English machine must not
95
+ // copy, e.g. "Tue 15 Sep". Pinned to en-US: the sentence it feeds
96
+ // ("unused until Tue 15 Sep") is English, so a non-English machine must not
108
97
  // print localized parts inside it. A bare weekday scans as this coming week,
109
98
  // which misreads a monthly reset sitting weeks out.
110
99
  export function dayOf(iso) {
111
- const when = new Date(iso ?? "");
112
- return `${when.toLocaleDateString("en-US", { weekday: "short" })} ${when.toLocaleDateString("en-US", { day: "numeric", month: "short" })}`;
100
+ return dayText(iso);
113
101
  }
114
102
  export function countdownText(ps, now) {
115
103
  const resetsMs = msOf(bindingResetsAt(ps));
@@ -244,25 +232,31 @@ export function forecastText(ps, now) {
244
232
  text = "Exhausted";
245
233
  }
246
234
  else if (adv.paceSource === "unknown" || adv.burnRate === null) {
247
- text = `Measuring pace; ${Math.round(adv.remaining)}% remains with ${adv.daysLeft.toFixed(1)}d until reset`;
235
+ text = `Measuring pace; ${Math.round(adv.remaining)}% remains with ${durationFromDays(adv.daysLeft)} until reset`;
248
236
  }
249
- else if (adv.status === "watch") {
237
+ else if (adv.status === "at risk" || adv.status === "watch") {
238
+ const word = adv.status === "at risk" ? "cap risk" : "watch";
250
239
  text =
251
240
  adv.daysToExhaust !== null && Number.isFinite(adv.daysToExhaust)
252
- ? `Exhausts in ${adv.daysToExhaust.toFixed(1)}d — watch`
253
- : "Near the cap — watch";
241
+ ? `Exhausts in ${durationFromDays(adv.daysToExhaust)} — ${word}`
242
+ : `Near the cap — ${word}`;
243
+ }
244
+ else if (adv.closeToReset === true) {
245
+ // Same words as the dashboard (LANDS_NEAR_FULL in web PaceBar.tsx).
246
+ text = "Lands near 100% at reset";
254
247
  }
255
- else if (adv.wastePct !== null && adv.wastePct > 0) {
256
- text = `${Math.round(adv.wastePct)}% waste in ${adv.daysLeft.toFixed(1)}d`;
248
+ else if (adv.wastePct !== null && Math.round(adv.wastePct) >= 1) {
249
+ text = unusedAtReset(adv.wastePct, bindingResetsAt(ps), now.getTime());
257
250
  }
258
251
  else {
259
- text = "Exhausts before reset";
252
+ // Same words as the dashboard (NO_SPARE in web PaceBar.tsx).
253
+ text = "No spare quota at 24h pace";
260
254
  }
261
255
  // Engine estimate vocabulary, mirroring the snapshot reason transform.
262
256
  // A monthly quota forecast never carries the weekly estimate flag.
263
257
  if (!isMonthlyBound(ps) && ps.quota?.resetsAtEstimated) {
264
- if (text.includes("waste in"))
265
- text = text.replace("waste in", "estimated waste in");
258
+ if (text.includes("unused at reset"))
259
+ text = text.replace("unused at reset", "unused at estimated reset");
266
260
  else if (text.includes("until reset"))
267
261
  text = text.replace("until reset", "until estimated reset");
268
262
  else if (!text.includes("estimated"))
@@ -270,21 +264,34 @@ export function forecastText(ps, now) {
270
264
  }
271
265
  return text;
272
266
  }
273
- // Compact legend: none = On track; ! = Cap risk; ~ = Watch or Behind/Ahead
274
- // pace or estimated reset; ? = unknown pace or any excluded row.
267
+ // Compact glyph: one per state word, so the statusline never folds two
268
+ // states into one mark. COMPACT_LEGEND is printed in `status --help`.
269
+ const COMPACT_GLYPHS = {
270
+ "On track": "",
271
+ "Behind pace": "<",
272
+ "Ahead of pace": ">",
273
+ Watch: "~",
274
+ "Cap risk": "!",
275
+ "Quota exhausted": "x",
276
+ "Monthly exhausted": "x",
277
+ Measuring: "?",
278
+ "Not reporting": "-",
279
+ };
280
+ export const COMPACT_LEGEND = "no mark on track, < behind, > ahead, ~ watch, ! cap risk, x exhausted, ? measuring, - not reporting";
275
281
  export function compactSuffix(ps) {
276
- if (ps.exclusionReason !== null)
277
- return "?";
278
- const adv = ps.advisory;
279
- if (!adv || adv.paceSource === "unknown")
280
- return "?";
281
- if (adv.status === "at risk")
282
- return "!";
283
- if (adv.status === "watch")
284
- return "~";
285
- if (adv.urgency !== "on track" || (!isMonthlyBound(ps) && ps.quota?.resetsAtEstimated))
286
- return "~";
287
- return "";
282
+ return COMPACT_GLYPHS[stateWord(ps)];
283
+ }
284
+ /**
285
+ * Providers a human surface lists: the enabled ones, as the dashboard
286
+ * shows them. JSON keeps every provider with its exclusion reason.
287
+ */
288
+ export function shownProviders(providers) {
289
+ return providers.filter((p) => p.enabled !== false);
290
+ }
291
+ /** Display name of the recommended provider, or "none". */
292
+ export function useName(snapshot) {
293
+ const use = snapshot.recommendation.use;
294
+ return snapshot.providers.find((p) => p.id === use)?.displayName ?? use;
288
295
  }
289
296
  export function assertValidSortKey(key) {
290
297
  if (!SORT_KEYS.includes(key)) {
@@ -404,5 +411,6 @@ export function buildRow(ps, now) {
404
411
  usedPct: usedPctOf(ps),
405
412
  railCells: railCells(ps, now),
406
413
  pace: paceText(ps, now),
414
+ wait: rateLimitWaits(ps, now).map((w) => w.text).join(" · "),
407
415
  };
408
416
  }