opencode-statboard 2.10.29 → 2.10.30

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.10.29",
3
+ "version": "2.10.30",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/index.html CHANGED
@@ -230,6 +230,12 @@
230
230
  </div>
231
231
  </details>
232
232
 
233
+ <!-- 1b. OpenRouter quota (key-level remaining credits & free-tier RPD) -->
234
+ <details class="tool-section" open id="sec-quota">
235
+ <summary><h2 data-i18n="openrouterQuota">OpenRouter Quota</h2><span class="scope-tag" id="tag-quota"></span></summary>
236
+ <div id="quota-body" style="padding:8px 0;font-size:12px;color:var(--muted)"></div>
237
+ </details>
238
+
233
239
  <!-- 2. TREND — bucket count follows the scope -->
234
240
  <details class="tool-section" open id="sec-trend">
235
241
  <summary><h2 data-i18n="trend">TREND</h2><span class="scope-tag" id="tag-trend"></span></summary>
@@ -402,6 +408,7 @@ const STRINGS = {
402
408
  kindProxyTip: 'borrowed price from another provider (estimate)',
403
409
  kindOpenrouter: 'openrouter',
404
410
  kindOpenrouterTip: 'live OpenRouter list price for the paid twin',
411
+ openrouterQuota: 'OpenRouter Quota',
405
412
  kindPartialTip: 'part of the usage priced, rest not in catalog',
406
413
  kindUnpricedTip: 'not in catalog — market/saved unknown',
407
414
  legacyAgent: 'legacy',
@@ -450,6 +457,7 @@ const STRINGS = {
450
457
  kindProxyTip: '借用其他供應商牌價(代估)',
451
458
  kindOpenrouter: 'openrouter',
452
459
  kindOpenrouterTip: 'OpenRouter 即時牌價(同級付費版)',
460
+ openrouterQuota: 'OpenRouter 額度',
453
461
  kindPartialTip: '部分用量有牌價,其餘查無',
454
462
  kindUnpricedTip: '目錄查無 — 市價/節省未知',
455
463
  legacyAgent: '舊版',
@@ -742,6 +750,34 @@ function renderPricing(rep) {
742
750
  $('pricing-empty').textContent = prov.length ? '' : t('noData');
743
751
  }
744
752
 
753
+ function fmtUsd(v) { if (v == null) return EM; return '$' + Number(v).toFixed(4); }
754
+ function renderQuota(q) {
755
+ const body = $('quota-body');
756
+ if (!q || !q.ok) { body.textContent = q && q.error ? q.error : t('noData'); return; }
757
+ const rows = (q.accounts || []).map((a) => {
758
+ if (a.error) return '<div style="color:var(--err)">' + esc(a.label) + ': ' + esc(a.error) + '</div>';
759
+ const free = a.freeModelDaily || {};
760
+ const rem = a.remainingUsd != null ? fmtUsd(a.remainingUsd) : EM;
761
+ const used = fmtUsd(a.usedUsd || 0);
762
+ const lim = a.limitUsd != null ? fmtUsd(a.limitUsd) : 'unlimited';
763
+ const pct = (a.limitUsd && a.limitUsd > 0) ? Math.round(((a.usedUsd || 0) / a.limitUsd) * 100) : null;
764
+ const freeLine = free.limit != null
765
+ ? 'free RPD ' + fmt(free.used) + '/' + fmt(free.limit) + ' (left ' + fmt(free.remaining) + ')'
766
+ : '';
767
+ const bud = a.budgetRemaining != null ? 'budget left ' + fmtUsd(a.budgetRemaining) + (a.budgetResetInterval ? ' (resets ' + a.budgetResetInterval + ')' : '') : '';
768
+ return '<div style="margin-bottom:6px"><b>' + esc(a.label) + '</b>'
769
+ + ' remaining ' + rem + ' / ' + lim + (pct != null ? ' (' + pct + '% used)' : '')
770
+ + ' used ' + used + (a.isFreeTier ? ' [free tier]' : '')
771
+ + (freeLine ? '<br>&nbsp;&nbsp;' + freeLine : '')
772
+ + (bud ? '<br>&nbsp;&nbsp;' + bud : '')
773
+ + '</div>';
774
+ }).join('');
775
+ body.innerHTML = rows + '<div style="color:var(--muted);font-size:10px;margin-top:4px">reset 00:00 UTC = 08:00 TW · cached 5 min</div>';
776
+ }
777
+ async function loadQuota() {
778
+ try { const r = await fetch('/api/openrouter-quota?_=' + Date.now(), { cache: 'no-store' }); const j = await r.json(); renderQuota(j); } catch (e) { $('quota-body').textContent = 'load failed: ' + e.message; }
779
+ }
780
+
745
781
  // ---- trend (buckets follow scope; newest day leftmost) -----------------
746
782
  function renderTrend(data) {
747
783
  if (!data || !data.labels || !data.labels.length) {
@@ -980,6 +1016,7 @@ function renderAll() {
980
1016
  renderTrend(tr || null);
981
1017
  renderHeatmap(heatmapTrend);
982
1018
  renderTools(lastTools);
1019
+ if (!window.__quotaLoaded) { window.__quotaLoaded = true; loadQuota(); }
983
1020
  }
984
1021
 
985
1022
  // ---- data loading ------------------------------------------------------
package/server.js CHANGED
@@ -1513,6 +1513,11 @@ const server = http.createServer(async (req, res) => {
1513
1513
  }
1514
1514
  respond({ ok: true, path: dbPath, files, totalSize, pragma });
1515
1515
  } catch (e) { respond({ ok: false, error: e.message }); }
1516
+ } else if (u === '/api/openrouter-quota') {
1517
+ try {
1518
+ const q = await fetchOpenRouterQuota();
1519
+ respond(q);
1520
+ } catch (e) { respond({ ok: false, error: e.message, accounts: [] }); }
1516
1521
  } else if (u === '/') {
1517
1522
  loadIndexHtml((err, data) => {
1518
1523
  if (err) {
@@ -1535,7 +1540,63 @@ const server = http.createServer(async (req, res) => {
1535
1540
  // signal handlers). `bin` points straight at this file, so a normal
1536
1541
  // `opencode-dashboard` run always has require.main === module.
1537
1542
  if (require.main !== module) {
1538
- module.exports = {
1543
+ // ---- OpenRouter quota (key-level remaining credits & free-tier RPD) ------
1544
+ const OR_KEY_FILE = path.join(process.env.USERPROFILE || process.env.HOME || '', '.thumb-secrets', 'openrouter-keys.txt');
1545
+ const OR_QUOTA_TTL = 5 * 60 * 1000;
1546
+ let orQuotaCache = { at: 0, data: null };
1547
+
1548
+ function readOpenRouterKeys() {
1549
+ const keys = [];
1550
+ for (const name of ['OPENROUTER_API_KEY', 'OPENROUTER_API_KEY_PRIMARY', 'OPENROUTER_API_KEY_FREE']) {
1551
+ const v = process.env[name];
1552
+ if (v) keys.push({ label: name.replace('OPENROUTER_API_KEY_', '').replace('OPENROUTER_API_KEY', 'PRIMARY'), key: v.trim() });
1553
+ }
1554
+ if (keys.length === 0) {
1555
+ try {
1556
+ const lines = fs.readFileSync(OR_KEY_FILE, 'utf8').split(/\r?\n/);
1557
+ for (const line of lines) {
1558
+ const m = line.match(/^OPENROUTER_KEY_(\w+)\s*=\s*(sk-or-v1-[a-f0-9]+)/);
1559
+ if (m) keys.push({ label: m[1], key: m[2] });
1560
+ }
1561
+ } catch (_) { /* no file: skip */ }
1562
+ }
1563
+ const seen = new Set();
1564
+ return keys.filter((k) => { if (seen.has(k.key)) return false; seen.add(k.key); return true; });
1565
+ }
1566
+
1567
+ async function fetchOpenRouterQuota() {
1568
+ const now = Date.now();
1569
+ if (orQuotaCache.data && now - orQuotaCache.at < OR_QUOTA_TTL) return orQuotaCache.data;
1570
+ const keys = readOpenRouterKeys();
1571
+ if (keys.length === 0) return { ok: false, error: 'no keys found', accounts: [] };
1572
+ const accounts = [];
1573
+ for (const { label, key } of keys) {
1574
+ try {
1575
+ const r = await fetch('https://openrouter.ai/api/v1/key', { headers: { Authorization: 'Bearer ' + key } });
1576
+ if (!r.ok) { accounts.push({ label, error: 'HTTP ' + r.status }); continue; }
1577
+ const j = await r.json();
1578
+ const d = j.data || {};
1579
+ const eb = d.effective_budget || {};
1580
+ accounts.push({
1581
+ label, limitUsd: d.limit != null ? d.limit : null, usedUsd: d.usage || 0,
1582
+ remainingUsd: d.limit_remaining != null ? d.limit_remaining : null,
1583
+ dailyUsed: d.usage_daily || 0, weeklyUsed: d.usage_weekly || 0, monthlyUsed: d.usage_monthly || 0,
1584
+ isFreeTier: !!d.is_free_tier, expiresAt: d.expires_at || null,
1585
+ freeModelDaily: d.free_model_daily_requests || null,
1586
+ budgetScope: eb.scope || null, budgetLimit: eb.limit_usd != null ? eb.limit_usd : null,
1587
+ budgetSpend: eb.spend_usd != null ? eb.spend_usd : null,
1588
+ budgetRemaining: eb.remaining_usd != null ? eb.remaining_usd : null,
1589
+ budgetResetInterval: eb.reset_interval || null, budgetResetsAt: eb.resets_at || null,
1590
+ fetchedAt: now,
1591
+ });
1592
+ } catch (e) { accounts.push({ label, error: String(e && e.message || e) }); }
1593
+ }
1594
+ const result = { ok: true, accounts, fetchedAt: now, resetUtc: '00:00 UTC (08:00 TW)' };
1595
+ orQuotaCache = { at: now, data: result };
1596
+ return result;
1597
+ }
1598
+
1599
+ module.exports = {
1539
1600
  buildAttrBundle,
1540
1601
  serializeBundle,
1541
1602
  reviveBundle,
package/tui-dashboard.js CHANGED
@@ -40,6 +40,7 @@ const I18N = {
40
40
  cost: 'Cost',
41
41
  marketValue: 'Market Value',
42
42
  saved: 'Saved',
43
+ openrouterQuota: 'OpenRouter Quota',
43
44
  avgCostDay: 'Avg Cost/Day',
44
45
  avgTokensDay: 'Avg Tokens/Day',
45
46
  projectHeader: '{Project:<45} {Sessions:>10} {Tokens:>18} {Cost:>14}',
@@ -77,7 +78,8 @@ const I18N = {
77
78
  total: '總計',
78
79
  cost: '成本',
79
80
  marketValue: '市場價值',
80
- saved: '節省',
81
+ saved: 'Saved',
82
+ openrouterQuota: 'OpenRouter 額度',
81
83
  avgCostDay: '日均成本',
82
84
  avgTokensDay: '日均Token',
83
85
  projectHeader: '{專案:<45} {會話:>10} {Token:>18} {成本:>14}',
@@ -117,6 +119,7 @@ const I18N = {
117
119
  cost: 'Cost',
118
120
  marketValue: 'Market Value',
119
121
  saved: 'Saved',
122
+ openrouterQuota: 'OpenRouter Quota',
120
123
  avgCostDay: 'Avg Cost/Day',
121
124
  avgTokensDay: 'Avg Tokens/Day',
122
125
  projectHeader: '{Project:<45} {Sessions:>10} {Tokens:>18} {Cost:>14}',
@@ -259,6 +262,9 @@ class TUIServer {
259
262
  // Parse trend
260
263
  const trendData = trend.trend || trend;
261
264
 
265
+ // Quota (fire and forget, cached server-side 5 min)
266
+ this.fetchData('/api/openrouter-quota').then(q => { this.quota = q; }).catch(() => {});
267
+
262
268
  // Handle overview.sessions being a number or object
263
269
  const sessionsValue = overview.sessions;
264
270
  const sessionsObj = typeof sessionsValue === 'number'
@@ -530,6 +536,21 @@ class TUIServer {
530
536
  '{bold}' + t('avgCostDay') + ':{/bold} ' + this.formatCost(cost.avgCostPerDay || 0),
531
537
  '{bold}' + t('avgTokensDay') + ':{/bold} ' + this.formatNumber(cost.avgTokensPerDay || 0)
532
538
  ];
539
+ if (this.quota && this.quota.ok && this.quota.accounts && this.quota.accounts.length) {
540
+ lines.push('');
541
+ lines.push('{bold}' + t('openrouterQuota') + ':{/bold}');
542
+ for (const a of this.quota.accounts) {
543
+ if (a.error) { lines.push(' ' + a.label + ': ' + a.error); continue; }
544
+ const free = a.freeModelDaily || {};
545
+ const rem = a.remainingUsd != null ? this.formatCost(a.remainingUsd) : '—';
546
+ const lim = a.limitUsd != null ? this.formatCost(a.limitUsd) : 'unlimited';
547
+ const used = this.formatCost(a.usedUsd || 0);
548
+ const freeLine = free.limit != null ? ('free RPD ' + free.used + '/' + free.limit + ' (left ' + free.remaining + ')') : '';
549
+ lines.push(' ' + a.label + ': ' + rem + ' / ' + lim + ' (used ' + used + ')' + (a.isFreeTier ? ' [free]' : ''));
550
+ if (freeLine) lines.push(' ' + freeLine);
551
+ }
552
+ lines.push(' {gray-fg}reset 00:00 UTC = 08:00 TW{/gray-fg}');
553
+ }
533
554
  return this.fillScreen(lines);
534
555
  }
535
556