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.
package/dist/index.js CHANGED
@@ -45,7 +45,7 @@ var PanelLineSchema = {
45
45
  var PanelSettingsSchema = {
46
46
  type: "object",
47
47
  properties: {
48
- view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"] },
48
+ view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db", "go"] },
49
49
  range: { type: "string", enum: ["session", "today", "7d", "30d", "all"] },
50
50
  sort: { type: "string", maxLength: 40 },
51
51
  sortDesc: { type: "boolean" },
@@ -2349,9 +2349,128 @@ function periodsOf(rows, granularity, otherRows = []) {
2349
2349
  return [...byKey.values()].sort((left, right) => left.at - right.at);
2350
2350
  }
2351
2351
 
2352
+ // src/quota.ts
2353
+ var QUOTA_VIEW = "go";
2354
+ var QUOTA_POLL_MS = 60000;
2355
+ var DEFAULT_QUOTA_NAME = "OpenCode Go";
2356
+ var DAY_MS = 24 * 60 * 60 * 1000;
2357
+ var MIN_FORECAST_ELAPSED_MS = 30 * 60 * 1000;
2358
+ function quotaNameOf(explicit, providerName) {
2359
+ const custom = explicit?.trim();
2360
+ if (custom !== undefined && custom !== "")
2361
+ return custom;
2362
+ const provider = providerName?.trim();
2363
+ if (provider !== undefined && provider !== "")
2364
+ return provider;
2365
+ return DEFAULT_QUOTA_NAME;
2366
+ }
2367
+ function finite2(value) {
2368
+ return typeof value === "number" && Number.isFinite(value);
2369
+ }
2370
+ function clamp(value, minimum, maximum) {
2371
+ return Math.min(maximum, Math.max(minimum, value));
2372
+ }
2373
+ function previousCycleStart(endAt) {
2374
+ if (!finite2(endAt))
2375
+ return endAt;
2376
+ const end = new Date(endAt);
2377
+ const year = end.getUTCFullYear();
2378
+ const month = end.getUTCMonth();
2379
+ const day = end.getUTCDate();
2380
+ const start = new Date(Date.UTC(year, month - 1, 1, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds()));
2381
+ const lastDay = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).getUTCDate();
2382
+ start.setUTCDate(Math.min(day, lastDay));
2383
+ return start.getTime();
2384
+ }
2385
+ function forecastMonthly(meter, now) {
2386
+ const endAt = finite2(meter.resetsAt) ? meter.resetsAt : now;
2387
+ const startAt = previousCycleStart(endAt);
2388
+ const total = Math.max(1, endAt - startAt);
2389
+ const elapsedMs = clamp(now - startAt, 0, total);
2390
+ const remainingMs = Math.max(0, endAt - now);
2391
+ const percent = clamp(finite2(meter.percent) ? meter.percent : 0, 0, 100);
2392
+ const reached = meter.limited === true || percent >= 100;
2393
+ const ratePerDay = !reached && elapsedMs >= MIN_FORECAST_ELAPSED_MS && percent > 0 ? percent / (elapsedMs / DAY_MS) : 0;
2394
+ const projectedPercent = reached ? 100 : ratePerDay > 0 ? percent + ratePerDay * (remainingMs / DAY_MS) : percent;
2395
+ const rawExhaustAt = !reached && ratePerDay > 0 && percent < 100 ? now + (100 - percent) / ratePerDay * DAY_MS : undefined;
2396
+ const exhaustAt = rawExhaustAt !== undefined && rawExhaustAt < endAt ? rawExhaustAt : undefined;
2397
+ const willExhaust = exhaustAt !== undefined;
2398
+ const available = !reached && now < endAt && (elapsedMs >= MIN_FORECAST_ELAPSED_MS || percent === 0);
2399
+ return {
2400
+ startAt,
2401
+ endAt,
2402
+ elapsedMs,
2403
+ remainingMs,
2404
+ ratePerDay,
2405
+ projectedPercent,
2406
+ ...exhaustAt !== undefined ? { exhaustAt } : {},
2407
+ reached,
2408
+ available,
2409
+ willExhaust
2410
+ };
2411
+ }
2412
+ function quotaBar(percent, width = 10) {
2413
+ const value = clamp(finite2(percent) ? percent : 0, 0, 100);
2414
+ const cells = Math.max(1, Math.round(width));
2415
+ const filled = value >= 100 ? cells : value <= 0 ? 0 : Math.min(cells, Math.max(1, Math.round(value / 100 * cells)));
2416
+ return `[${"#".repeat(filled)}${"-".repeat(cells - filled)}]`;
2417
+ }
2418
+ function formatRenewal(at, timeZone) {
2419
+ if (!finite2(at))
2420
+ return "\u2013";
2421
+ try {
2422
+ return new Intl.DateTimeFormat("en-GB", {
2423
+ day: "2-digit",
2424
+ month: "short",
2425
+ year: "numeric",
2426
+ hour: "2-digit",
2427
+ minute: "2-digit",
2428
+ hour12: false,
2429
+ ...timeZone !== undefined ? { timeZone } : {}
2430
+ }).format(new Date(at)).replace(/,/g, "");
2431
+ } catch {
2432
+ return "\u2013";
2433
+ }
2434
+ }
2435
+ function formatRenewalCompact(at, timeZone) {
2436
+ if (!finite2(at))
2437
+ return "\u2013";
2438
+ try {
2439
+ return new Intl.DateTimeFormat("en-GB", {
2440
+ day: "2-digit",
2441
+ month: "short",
2442
+ hour: "2-digit",
2443
+ minute: "2-digit",
2444
+ hour12: false,
2445
+ ...timeZone !== undefined ? { timeZone } : {}
2446
+ }).format(new Date(at)).replace(/,/g, "");
2447
+ } catch {
2448
+ return "\u2013";
2449
+ }
2450
+ }
2451
+ function formatCountdown(at, now) {
2452
+ const remaining = at - now;
2453
+ if (!finite2(remaining))
2454
+ return "\u2013";
2455
+ if (remaining <= 0)
2456
+ return "due";
2457
+ return formatDuration(remaining);
2458
+ }
2459
+ function quotaStatus(quota) {
2460
+ const limited = [];
2461
+ if (quota.rolling.limited || quota.rolling.percent >= 100)
2462
+ limited.push("5-hour");
2463
+ if (quota.weekly.limited || quota.weekly.percent >= 100)
2464
+ limited.push("weekly");
2465
+ if (quota.monthly.limited || quota.monthly.percent >= 100)
2466
+ limited.push("monthly");
2467
+ return limited.length === 0 ? "active" : `${limited.join(" / ")} limit reached`;
2468
+ }
2469
+
2352
2470
  // src/panel-data.ts
2353
2471
  var PANEL_NAME = "usage-insights";
2354
2472
  var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
2473
+ var CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW];
2355
2474
  var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
2356
2475
  var GRANULARITIES = ["day", "week", "month"];
2357
2476
  var SORT_KEYS = {
@@ -2376,13 +2495,13 @@ function nextSort(view, current, step) {
2376
2495
  return keys[0];
2377
2496
  return keys[(index + step + keys.length) % keys.length];
2378
2497
  }
2379
- function parseArgs(input) {
2498
+ function parseArgs(input, views = CLIENT_VIEWS) {
2380
2499
  const parsed = {};
2381
2500
  for (const token of (input ?? "").split(/\s+/)) {
2382
2501
  const value = token.trim().toLowerCase();
2383
2502
  if (value === "")
2384
2503
  continue;
2385
- if (PANEL_VIEWS.includes(value))
2504
+ if (views.includes(value))
2386
2505
  parsed.view = value;
2387
2506
  else if (RANGE_KEYS.includes(value))
2388
2507
  parsed.range = value;
@@ -2419,10 +2538,10 @@ var DEFAULT_SETTINGS = {
2419
2538
  modelID: "",
2420
2539
  providerID: ""
2421
2540
  };
2422
- function sanitizeSettings(raw) {
2541
+ function sanitizeSettings(raw, views = CLIENT_VIEWS) {
2423
2542
  const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
2424
2543
  return {
2425
- view: PANEL_VIEWS.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
2544
+ view: views.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
2426
2545
  range: RANGE_KEYS.includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,
2427
2546
  sort: typeof settings.sort === "string" ? settings.sort : DEFAULT_SETTINGS.sort,
2428
2547
  sortDesc: settings.sortDesc === true,
@@ -2579,25 +2698,28 @@ function usageBuckets(usage) {
2579
2698
  hit: prompt > 0 ? usage.cached / prompt : undefined
2580
2699
  };
2581
2700
  }
2582
- function viewBar(view, width = 200) {
2701
+ function viewBar(view, width = 200, views = CLIENT_VIEWS) {
2583
2702
  const key = (index) => String((index + 1) % 10);
2584
- const full = PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
2585
- const candidates = [full, PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
2703
+ const full = views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
2704
+ const candidates = [full, views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
2586
2705
  for (const parts of candidates) {
2587
2706
  const text = parts.join(" ");
2588
2707
  if (text.length <= width)
2589
2708
  return { text, tone: "muted" };
2590
2709
  }
2591
- return { text: `[${PANEL_VIEWS.indexOf(view) + 1} ${view}] \xB7 1-9 or [ ] to switch`, tone: "muted" };
2710
+ const index = views.indexOf(view);
2711
+ return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
2592
2712
  }
2593
2713
  function keysFor(of) {
2714
+ if (of === QUOTA_VIEW)
2715
+ return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
2594
2716
  if (of === "db")
2595
- 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";
2717
+ 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";
2596
2718
  if (of === "periods")
2597
- 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";
2719
+ 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";
2598
2720
  if (of === "turns")
2599
- return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2600
- 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";
2721
+ return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2722
+ 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";
2601
2723
  }
2602
2724
  function filterSummary(filters) {
2603
2725
  const parts = [];
@@ -2614,7 +2736,7 @@ function helpLines(width) {
2614
2736
  const lines = [
2615
2737
  { text: "keys", tone: HEADER_TONE },
2616
2738
  { text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
2617
- { text: " 1-9 [ ] choose a view \xB7 cycle views (9 is db)" },
2739
+ { text: " 1-9 0 [ ] choose a view \xB7 cycle views (9 is db, 0 is go)" },
2618
2740
  { text: " t shift+t previous / next range" },
2619
2741
  { text: " s shift+s cycle sort column \xB7 reverse" },
2620
2742
  { text: " b periods bucket: day \u2192 week \u2192 month" },
@@ -2623,6 +2745,13 @@ function helpLines(width) {
2623
2745
  { text: " r re-read the database \xB7 f full screen \xB7 escape close" },
2624
2746
  { text: " e db: backfill list-price estimates for the $0 steps" },
2625
2747
  { text: "" },
2748
+ { text: "go quota \xB7 the host's OpenCode Go allowance", tone: HEADER_TONE },
2749
+ { text: " rolling the 5-hour window \xB7 weekly \xB7 monthly" },
2750
+ { text: " forecast the monthly percentage at its reset, from the" },
2751
+ { text: " cycle's average pace (not a sample history)" },
2752
+ { text: " renews the monthly reset reported by the host" },
2753
+ { text: " the plugin reads the host's local usage-limits endpoint;" },
2754
+ { text: " it never reads your API key and never talks to the Console." },
2626
2755
  { text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
2627
2756
  { text: " prompt everything the provider saw: cached + fresh + writes" },
2628
2757
  { text: " in the uncached part: fresh input + cache writes" },
@@ -2657,6 +2786,101 @@ function helpLines(width) {
2657
2786
  ];
2658
2787
  return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2659
2788
  }
2789
+ function quotaMeterLine(label, meter, now) {
2790
+ const state = meter.limited || meter.percent >= 100 ? "rate-limited" : `${Math.round(meter.percent)}% used`;
2791
+ const countdown = formatCountdown(meter.resetsAt, now);
2792
+ return {
2793
+ text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} \xB7 ${countdown === "due" ? "resets due" : `resets in ${countdown}`}`,
2794
+ tone: meter.limited || meter.percent >= 100 ? "warning" : "base"
2795
+ };
2796
+ }
2797
+ function goQuotaLines(state, options) {
2798
+ const { now, width, loading, error } = options;
2799
+ const name = options.name?.trim() || DEFAULT_QUOTA_NAME;
2800
+ const lines = [];
2801
+ const push = (text, tone = "base") => {
2802
+ lines.push({ text, tone });
2803
+ };
2804
+ if (state === undefined) {
2805
+ if (error !== undefined && error !== "")
2806
+ push(`Go quota unavailable: ${error}`, "warning");
2807
+ else if (loading === true)
2808
+ push("reading OpenCode Go quota\u2026", "muted");
2809
+ else
2810
+ push("OpenCode Go quota is unavailable", "muted");
2811
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2812
+ }
2813
+ if (state.kind === "none") {
2814
+ push(name, "accent");
2815
+ push(state.reason === "console" ? "Connect OpenCode Console with /connect to see your Go allowance." : "This workspace has no active OpenCode Go subscription.", "muted");
2816
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2817
+ }
2818
+ const quota = state.quota;
2819
+ const workspace = quota.workspace?.name ?? quota.workspace?.id ?? "workspace";
2820
+ const status = quotaStatus(quota);
2821
+ const forecast = forecastMonthly(quota.monthly, now);
2822
+ push(`${name} \xB7 ${workspace}`, "accent");
2823
+ push(`status ${status}`, status === "active" ? "base" : "warning");
2824
+ lines.push(quotaMeterLine("rolling", quota.rolling, now));
2825
+ lines.push(quotaMeterLine("weekly", quota.weekly, now));
2826
+ lines.push(quotaMeterLine("monthly", quota.monthly, now));
2827
+ push("");
2828
+ if (forecast.reached || quota.monthly.limited) {
2829
+ push(`forecast monthly limit reached \xB7 renews ${formatRenewal(quota.monthly.resetsAt)}`, "warning");
2830
+ } else if (now >= forecast.endAt) {
2831
+ push("forecast monthly reset due \xB7 refresh", "warning");
2832
+ } else if (!forecast.available) {
2833
+ push("forecast too early in the cycle to project a monthly pace", "muted");
2834
+ } else if (quota.monthly.percent === 0) {
2835
+ push("forecast no monthly usage yet this cycle", "muted");
2836
+ } else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {
2837
+ push(`forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} \xB7 ${formatDuration(forecast.exhaustAt - now)} from now \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`, "warning");
2838
+ } else {
2839
+ const projected = Math.min(999, Math.round(forecast.projectedPercent));
2840
+ const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent));
2841
+ push(`forecast ~${projected}% at reset \xB7 ${headroom}% headroom \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`);
2842
+ }
2843
+ const renewal = formatRenewal(quota.monthly.resetsAt);
2844
+ const countdown = formatCountdown(quota.monthly.resetsAt, now);
2845
+ push(`renews ${renewal} \xB7 ${countdown === "due" ? "renewal due" : `in ${countdown}`}`, "muted");
2846
+ if (quota.workspace?.usageURL !== undefined)
2847
+ push(`console ${quota.workspace.usageURL}`, "muted");
2848
+ const age = Math.max(0, now - quota.observedAt);
2849
+ push(`updated ${age < 1000 ? "just now" : `${formatDuration(age)} ago`}`, "muted");
2850
+ if (loading === true)
2851
+ push("refreshing\u2026", "muted");
2852
+ if (error !== undefined && error !== "")
2853
+ push(`quota refresh failed: ${error}`, "warning");
2854
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2855
+ }
2856
+ function goSidebarLines(state, now, width, name = DEFAULT_QUOTA_NAME) {
2857
+ if (state?.kind !== "ok" || width <= 0)
2858
+ return [];
2859
+ const quota = state.quota;
2860
+ const status = quotaStatus(quota);
2861
+ const forecast = forecastMonthly(quota.monthly, now);
2862
+ const base = `5h ${Math.round(quota.rolling.percent)}% \xB7 week ${Math.round(quota.weekly.percent)}% \xB7 month ${Math.round(quota.monthly.percent)}%`;
2863
+ const baseTone = status !== "active" || quota.monthly.percent >= 80 ? "warning" : "base";
2864
+ let forecastText = "forecast too early";
2865
+ let forecastTone = "muted";
2866
+ if (forecast.reached || quota.monthly.limited) {
2867
+ forecastText = "monthly limit reached";
2868
+ forecastTone = "warning";
2869
+ } else if (forecast.willExhaust) {
2870
+ forecastText = "limit before renewal";
2871
+ forecastTone = "warning";
2872
+ } else if (forecast.available && quota.monthly.percent > 0) {
2873
+ forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`;
2874
+ } else if (forecast.available && quota.monthly.percent === 0) {
2875
+ forecastText = "forecast no usage yet";
2876
+ }
2877
+ return [
2878
+ { text: truncate(name, width), tone: "accent" },
2879
+ { text: truncate(base, width), tone: baseTone },
2880
+ { text: truncate(forecastText, width), tone: forecastTone },
2881
+ { text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: "muted" }
2882
+ ];
2883
+ }
2660
2884
  function usagePairs(usage, estimates = true) {
2661
2885
  if (usage === undefined)
2662
2886
  return [];
@@ -3399,6 +3623,13 @@ function build(request) {
3399
3623
  }
3400
3624
  case "db":
3401
3625
  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);
3626
+ case "go":
3627
+ return [
3628
+ {
3629
+ text: "OpenCode Go quota is read by the TUI and Desktop from the host; it is not stored in this database.",
3630
+ tone: "muted"
3631
+ }
3632
+ ];
3402
3633
  case "turns": {
3403
3634
  const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
3404
3635
  const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
@@ -3754,7 +3985,7 @@ class ServiceError extends Error {
3754
3985
  this.code = code;
3755
3986
  }
3756
3987
  }
3757
- function clamp(value, minimum, maximum) {
3988
+ function clamp2(value, minimum, maximum) {
3758
3989
  if (!Number.isFinite(value))
3759
3990
  return minimum;
3760
3991
  return Math.min(maximum, Math.max(minimum, Math.round(value)));
@@ -3823,7 +4054,7 @@ function createService(db, options) {
3823
4054
  }
3824
4055
  function turnHistory(input) {
3825
4056
  const handle = db();
3826
- const width = clamp(input.width, 20, 120);
4057
+ const width = clamp2(input.width, 20, 120);
3827
4058
  const limit = clampTurnsLimit(input.limit);
3828
4059
  const summary = sessionSummaryLines(overview(handle, undefined, { sessionID: input.sessionID }), width, options.pricing);
3829
4060
  const history = sidebarLines(turns(handle, { sessionID: input.sessionID, limit }), {
@@ -3852,7 +4083,7 @@ function createService(db, options) {
3852
4083
  function prune(input) {
3853
4084
  requireMaintenance();
3854
4085
  requireConfirm(input.confirm);
3855
- const days = clamp(input.days, 1, MAX_DAYS);
4086
+ const days = clamp2(input.days, 1, MAX_DAYS);
3856
4087
  return writeDb(options.path, (handle) => pruneOlderThan(handle, Date.now() - days * DAY2));
3857
4088
  }
3858
4089
  function wipe(input) {
@@ -4350,4 +4581,4 @@ export {
4350
4581
  src_default as default
4351
4582
  };
4352
4583
 
4353
- //# debugId=15B300D932EB268164756E2164756E21
4584
+ //# debugId=81E9F82B0FBCADEE64756E2164756E21