opencode-usage-insights 0.2.0 → 0.3.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.
@@ -1763,9 +1763,128 @@ function periodsOf(rows, granularity, otherRows = []) {
1763
1763
  return [...byKey.values()].sort((left, right) => left.at - right.at);
1764
1764
  }
1765
1765
 
1766
+ // src/quota.ts
1767
+ var QUOTA_VIEW = "go";
1768
+ var QUOTA_POLL_MS = 60000;
1769
+ var DEFAULT_QUOTA_NAME = "OpenCode Go";
1770
+ var DAY_MS = 24 * 60 * 60 * 1000;
1771
+ var MIN_FORECAST_ELAPSED_MS = 30 * 60 * 1000;
1772
+ function quotaNameOf(explicit, providerName) {
1773
+ const custom = explicit?.trim();
1774
+ if (custom !== undefined && custom !== "")
1775
+ return custom;
1776
+ const provider = providerName?.trim();
1777
+ if (provider !== undefined && provider !== "")
1778
+ return provider;
1779
+ return DEFAULT_QUOTA_NAME;
1780
+ }
1781
+ function finite2(value) {
1782
+ return typeof value === "number" && Number.isFinite(value);
1783
+ }
1784
+ function clamp(value, minimum, maximum) {
1785
+ return Math.min(maximum, Math.max(minimum, value));
1786
+ }
1787
+ function previousCycleStart(endAt) {
1788
+ if (!finite2(endAt))
1789
+ return endAt;
1790
+ const end = new Date(endAt);
1791
+ const year = end.getUTCFullYear();
1792
+ const month = end.getUTCMonth();
1793
+ const day = end.getUTCDate();
1794
+ const start = new Date(Date.UTC(year, month - 1, 1, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds()));
1795
+ const lastDay = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).getUTCDate();
1796
+ start.setUTCDate(Math.min(day, lastDay));
1797
+ return start.getTime();
1798
+ }
1799
+ function forecastMonthly(meter, now) {
1800
+ const endAt = finite2(meter.resetsAt) ? meter.resetsAt : now;
1801
+ const startAt = previousCycleStart(endAt);
1802
+ const total = Math.max(1, endAt - startAt);
1803
+ const elapsedMs = clamp(now - startAt, 0, total);
1804
+ const remainingMs = Math.max(0, endAt - now);
1805
+ const percent = clamp(finite2(meter.percent) ? meter.percent : 0, 0, 100);
1806
+ const reached = meter.limited === true || percent >= 100;
1807
+ const ratePerDay = !reached && elapsedMs >= MIN_FORECAST_ELAPSED_MS && percent > 0 ? percent / (elapsedMs / DAY_MS) : 0;
1808
+ const projectedPercent = reached ? 100 : ratePerDay > 0 ? percent + ratePerDay * (remainingMs / DAY_MS) : percent;
1809
+ const rawExhaustAt = !reached && ratePerDay > 0 && percent < 100 ? now + (100 - percent) / ratePerDay * DAY_MS : undefined;
1810
+ const exhaustAt = rawExhaustAt !== undefined && rawExhaustAt < endAt ? rawExhaustAt : undefined;
1811
+ const willExhaust = exhaustAt !== undefined;
1812
+ const available = !reached && now < endAt && (elapsedMs >= MIN_FORECAST_ELAPSED_MS || percent === 0);
1813
+ return {
1814
+ startAt,
1815
+ endAt,
1816
+ elapsedMs,
1817
+ remainingMs,
1818
+ ratePerDay,
1819
+ projectedPercent,
1820
+ ...exhaustAt !== undefined ? { exhaustAt } : {},
1821
+ reached,
1822
+ available,
1823
+ willExhaust
1824
+ };
1825
+ }
1826
+ function quotaBar(percent, width = 10) {
1827
+ const value = clamp(finite2(percent) ? percent : 0, 0, 100);
1828
+ const cells = Math.max(1, Math.round(width));
1829
+ const filled = value >= 100 ? cells : value <= 0 ? 0 : Math.min(cells, Math.max(1, Math.round(value / 100 * cells)));
1830
+ return `[${"#".repeat(filled)}${"-".repeat(cells - filled)}]`;
1831
+ }
1832
+ function formatRenewal(at, timeZone) {
1833
+ if (!finite2(at))
1834
+ return "\u2013";
1835
+ try {
1836
+ return new Intl.DateTimeFormat("en-GB", {
1837
+ day: "2-digit",
1838
+ month: "short",
1839
+ year: "numeric",
1840
+ hour: "2-digit",
1841
+ minute: "2-digit",
1842
+ hour12: false,
1843
+ ...timeZone !== undefined ? { timeZone } : {}
1844
+ }).format(new Date(at)).replace(/,/g, "");
1845
+ } catch {
1846
+ return "\u2013";
1847
+ }
1848
+ }
1849
+ function formatRenewalCompact(at, timeZone) {
1850
+ if (!finite2(at))
1851
+ return "\u2013";
1852
+ try {
1853
+ return new Intl.DateTimeFormat("en-GB", {
1854
+ day: "2-digit",
1855
+ month: "short",
1856
+ hour: "2-digit",
1857
+ minute: "2-digit",
1858
+ hour12: false,
1859
+ ...timeZone !== undefined ? { timeZone } : {}
1860
+ }).format(new Date(at)).replace(/,/g, "");
1861
+ } catch {
1862
+ return "\u2013";
1863
+ }
1864
+ }
1865
+ function formatCountdown(at, now) {
1866
+ const remaining = at - now;
1867
+ if (!finite2(remaining))
1868
+ return "\u2013";
1869
+ if (remaining <= 0)
1870
+ return "due";
1871
+ return formatDuration(remaining);
1872
+ }
1873
+ function quotaStatus(quota) {
1874
+ const limited = [];
1875
+ if (quota.rolling.limited || quota.rolling.percent >= 100)
1876
+ limited.push("5-hour");
1877
+ if (quota.weekly.limited || quota.weekly.percent >= 100)
1878
+ limited.push("weekly");
1879
+ if (quota.monthly.limited || quota.monthly.percent >= 100)
1880
+ limited.push("monthly");
1881
+ return limited.length === 0 ? "active" : `${limited.join(" / ")} limit reached`;
1882
+ }
1883
+
1766
1884
  // src/panel-data.ts
1767
1885
  var PANEL_NAME = "usage-insights";
1768
1886
  var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
1887
+ var CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW];
1769
1888
  var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
1770
1889
  var GRANULARITIES = ["day", "week", "month"];
1771
1890
  var SORT_KEYS = {
@@ -1790,13 +1909,13 @@ function nextSort(view, current, step) {
1790
1909
  return keys[0];
1791
1910
  return keys[(index + step + keys.length) % keys.length];
1792
1911
  }
1793
- function parseArgs(input) {
1912
+ function parseArgs(input, views = CLIENT_VIEWS) {
1794
1913
  const parsed = {};
1795
1914
  for (const token of (input ?? "").split(/\s+/)) {
1796
1915
  const value = token.trim().toLowerCase();
1797
1916
  if (value === "")
1798
1917
  continue;
1799
- if (PANEL_VIEWS.includes(value))
1918
+ if (views.includes(value))
1800
1919
  parsed.view = value;
1801
1920
  else if (RANGE_KEYS.includes(value))
1802
1921
  parsed.range = value;
@@ -1833,10 +1952,10 @@ var DEFAULT_SETTINGS = {
1833
1952
  modelID: "",
1834
1953
  providerID: ""
1835
1954
  };
1836
- function sanitizeSettings(raw) {
1955
+ function sanitizeSettings(raw, views = CLIENT_VIEWS) {
1837
1956
  const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
1838
1957
  return {
1839
- view: PANEL_VIEWS.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
1958
+ view: views.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
1840
1959
  range: RANGE_KEYS.includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,
1841
1960
  sort: typeof settings.sort === "string" ? settings.sort : DEFAULT_SETTINGS.sort,
1842
1961
  sortDesc: settings.sortDesc === true,
@@ -1993,25 +2112,28 @@ function usageBuckets(usage) {
1993
2112
  hit: prompt > 0 ? usage.cached / prompt : undefined
1994
2113
  };
1995
2114
  }
1996
- function viewBar(view, width = 200) {
2115
+ function viewBar(view, width = 200, views = CLIENT_VIEWS) {
1997
2116
  const key = (index) => String((index + 1) % 10);
1998
- const full = PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
1999
- const candidates = [full, PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
2117
+ const full = views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
2118
+ const candidates = [full, views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
2000
2119
  for (const parts of candidates) {
2001
2120
  const text = parts.join(" ");
2002
2121
  if (text.length <= width)
2003
2122
  return { text, tone: "muted" };
2004
2123
  }
2005
- return { text: `[${PANEL_VIEWS.indexOf(view) + 1} ${view}] \xB7 1-9 or [ ] to switch`, tone: "muted" };
2124
+ const index = views.indexOf(view);
2125
+ return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
2006
2126
  }
2007
2127
  function keysFor(of) {
2128
+ if (of === QUOTA_VIEW)
2129
+ return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
2008
2130
  if (of === "db")
2009
- return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
2131
+ return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 0 view \xB7 ? help";
2010
2132
  if (of === "periods")
2011
- return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2133
+ return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2012
2134
  if (of === "turns")
2013
- return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2014
- return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2135
+ return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2136
+ return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2015
2137
  }
2016
2138
  function filterSummary(filters) {
2017
2139
  const parts = [];
@@ -2028,7 +2150,7 @@ function helpLines(width) {
2028
2150
  const lines = [
2029
2151
  { text: "keys", tone: HEADER_TONE },
2030
2152
  { text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
2031
- { text: " 1-9 [ ] choose a view \xB7 cycle views (9 is db)" },
2153
+ { text: " 1-9 0 [ ] choose a view \xB7 cycle views (9 is db, 0 is go)" },
2032
2154
  { text: " t shift+t previous / next range" },
2033
2155
  { text: " s shift+s cycle sort column \xB7 reverse" },
2034
2156
  { text: " b periods bucket: day \u2192 week \u2192 month" },
@@ -2037,6 +2159,13 @@ function helpLines(width) {
2037
2159
  { text: " r re-read the database \xB7 f full screen \xB7 escape close" },
2038
2160
  { text: " e db: backfill list-price estimates for the $0 steps" },
2039
2161
  { text: "" },
2162
+ { text: "go quota \xB7 the host's OpenCode Go allowance", tone: HEADER_TONE },
2163
+ { text: " rolling the 5-hour window \xB7 weekly \xB7 monthly" },
2164
+ { text: " forecast the monthly percentage at its reset, from the" },
2165
+ { text: " cycle's average pace (not a sample history)" },
2166
+ { text: " renews the monthly reset reported by the host" },
2167
+ { text: " the plugin reads the host's local usage-limits endpoint;" },
2168
+ { text: " it never reads your API key and never talks to the Console." },
2040
2169
  { text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
2041
2170
  { text: " prompt everything the provider saw: cached + fresh + writes" },
2042
2171
  { text: " in the uncached part: fresh input + cache writes" },
@@ -2071,6 +2200,101 @@ function helpLines(width) {
2071
2200
  ];
2072
2201
  return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2073
2202
  }
2203
+ function quotaMeterLine(label, meter, now) {
2204
+ const state = meter.limited || meter.percent >= 100 ? "rate-limited" : `${Math.round(meter.percent)}% used`;
2205
+ const countdown = formatCountdown(meter.resetsAt, now);
2206
+ return {
2207
+ text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} \xB7 ${countdown === "due" ? "resets due" : `resets in ${countdown}`}`,
2208
+ tone: meter.limited || meter.percent >= 100 ? "warning" : "base"
2209
+ };
2210
+ }
2211
+ function goQuotaLines(state, options) {
2212
+ const { now, width, loading, error } = options;
2213
+ const name = options.name?.trim() || DEFAULT_QUOTA_NAME;
2214
+ const lines = [];
2215
+ const push = (text, tone = "base") => {
2216
+ lines.push({ text, tone });
2217
+ };
2218
+ if (state === undefined) {
2219
+ if (error !== undefined && error !== "")
2220
+ push(`Go quota unavailable: ${error}`, "warning");
2221
+ else if (loading === true)
2222
+ push("reading OpenCode Go quota\u2026", "muted");
2223
+ else
2224
+ push("OpenCode Go quota is unavailable", "muted");
2225
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2226
+ }
2227
+ if (state.kind === "none") {
2228
+ push(name, "accent");
2229
+ push(state.reason === "console" ? "Connect OpenCode Console with /connect to see your Go allowance." : "This workspace has no active OpenCode Go subscription.", "muted");
2230
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2231
+ }
2232
+ const quota = state.quota;
2233
+ const workspace = quota.workspace?.name ?? quota.workspace?.id ?? "workspace";
2234
+ const status = quotaStatus(quota);
2235
+ const forecast = forecastMonthly(quota.monthly, now);
2236
+ push(`${name} \xB7 ${workspace}`, "accent");
2237
+ push(`status ${status}`, status === "active" ? "base" : "warning");
2238
+ lines.push(quotaMeterLine("rolling", quota.rolling, now));
2239
+ lines.push(quotaMeterLine("weekly", quota.weekly, now));
2240
+ lines.push(quotaMeterLine("monthly", quota.monthly, now));
2241
+ push("");
2242
+ if (forecast.reached || quota.monthly.limited) {
2243
+ push(`forecast monthly limit reached \xB7 renews ${formatRenewal(quota.monthly.resetsAt)}`, "warning");
2244
+ } else if (now >= forecast.endAt) {
2245
+ push("forecast monthly reset due \xB7 refresh", "warning");
2246
+ } else if (!forecast.available) {
2247
+ push("forecast too early in the cycle to project a monthly pace", "muted");
2248
+ } else if (quota.monthly.percent === 0) {
2249
+ push("forecast no monthly usage yet this cycle", "muted");
2250
+ } else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {
2251
+ push(`forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} \xB7 ${formatDuration(forecast.exhaustAt - now)} from now \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`, "warning");
2252
+ } else {
2253
+ const projected = Math.min(999, Math.round(forecast.projectedPercent));
2254
+ const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent));
2255
+ push(`forecast ~${projected}% at reset \xB7 ${headroom}% headroom \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`);
2256
+ }
2257
+ const renewal = formatRenewal(quota.monthly.resetsAt);
2258
+ const countdown = formatCountdown(quota.monthly.resetsAt, now);
2259
+ push(`renews ${renewal} \xB7 ${countdown === "due" ? "renewal due" : `in ${countdown}`}`, "muted");
2260
+ if (quota.workspace?.usageURL !== undefined)
2261
+ push(`console ${quota.workspace.usageURL}`, "muted");
2262
+ const age = Math.max(0, now - quota.observedAt);
2263
+ push(`updated ${age < 1000 ? "just now" : `${formatDuration(age)} ago`}`, "muted");
2264
+ if (loading === true)
2265
+ push("refreshing\u2026", "muted");
2266
+ if (error !== undefined && error !== "")
2267
+ push(`quota refresh failed: ${error}`, "warning");
2268
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2269
+ }
2270
+ function goSidebarLines(state, now, width, name = DEFAULT_QUOTA_NAME) {
2271
+ if (state?.kind !== "ok" || width <= 0)
2272
+ return [];
2273
+ const quota = state.quota;
2274
+ const status = quotaStatus(quota);
2275
+ const forecast = forecastMonthly(quota.monthly, now);
2276
+ const base = `5h ${Math.round(quota.rolling.percent)}% \xB7 week ${Math.round(quota.weekly.percent)}% \xB7 month ${Math.round(quota.monthly.percent)}%`;
2277
+ const baseTone = status !== "active" || quota.monthly.percent >= 80 ? "warning" : "base";
2278
+ let forecastText = "forecast too early";
2279
+ let forecastTone = "muted";
2280
+ if (forecast.reached || quota.monthly.limited) {
2281
+ forecastText = "monthly limit reached";
2282
+ forecastTone = "warning";
2283
+ } else if (forecast.willExhaust) {
2284
+ forecastText = "limit before renewal";
2285
+ forecastTone = "warning";
2286
+ } else if (forecast.available && quota.monthly.percent > 0) {
2287
+ forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`;
2288
+ } else if (forecast.available && quota.monthly.percent === 0) {
2289
+ forecastText = "forecast no usage yet";
2290
+ }
2291
+ return [
2292
+ { text: truncate(name, width), tone: "accent" },
2293
+ { text: truncate(base, width), tone: baseTone },
2294
+ { text: truncate(forecastText, width), tone: forecastTone },
2295
+ { text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: "muted" }
2296
+ ];
2297
+ }
2074
2298
  function usagePairs(usage, estimates = true) {
2075
2299
  if (usage === undefined)
2076
2300
  return [];
@@ -2813,6 +3037,13 @@ function build(request) {
2813
3037
  }
2814
3038
  case "db":
2815
3039
  return request.database === undefined ? [{ text: "the database location is unavailable to this panel", tone: "warning" }] : dbLines({ info: request.database, busy: request.busy, now, estimates }, width);
3040
+ case "go":
3041
+ return [
3042
+ {
3043
+ text: "OpenCode Go quota is read by the TUI and Desktop from the host; it is not stored in this database.",
3044
+ tone: "muted"
3045
+ }
3046
+ ];
2816
3047
  case "turns": {
2817
3048
  const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
2818
3049
  const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
@@ -3242,7 +3473,7 @@ class ServiceError extends Error {
3242
3473
  this.code = code;
3243
3474
  }
3244
3475
  }
3245
- function clamp(value, minimum, maximum) {
3476
+ function clamp2(value, minimum, maximum) {
3246
3477
  if (!Number.isFinite(value))
3247
3478
  return minimum;
3248
3479
  return Math.min(maximum, Math.max(minimum, Math.round(value)));
@@ -3311,7 +3542,7 @@ function createService(db, options) {
3311
3542
  }
3312
3543
  function turnHistory(input) {
3313
3544
  const handle = db();
3314
- const width = clamp(input.width, 20, 120);
3545
+ const width = clamp2(input.width, 20, 120);
3315
3546
  const limit = clampTurnsLimit(input.limit);
3316
3547
  const summary = sessionSummaryLines(overview(handle, undefined, { sessionID: input.sessionID }), width, options.pricing);
3317
3548
  const history = sidebarLines(turns(handle, { sessionID: input.sessionID, limit }), {
@@ -3340,7 +3571,7 @@ function createService(db, options) {
3340
3571
  function prune(input) {
3341
3572
  requireMaintenance();
3342
3573
  requireConfirm(input.confirm);
3343
- const days = clamp(input.days, 1, MAX_DAYS);
3574
+ const days = clamp2(input.days, 1, MAX_DAYS);
3344
3575
  return writeDb(options.path, (handle) => pruneOlderThan(handle, Date.now() - days * DAY2));
3345
3576
  }
3346
3577
  function wipe(input) {
@@ -3463,4 +3694,4 @@ scope.onmessage = (event) => {
3463
3694
  }
3464
3695
  };
3465
3696
 
3466
- //# debugId=BFDB9404BB86848D64756E2164756E21
3697
+ //# debugId=008189B5EA042DE564756E2164756E21