Repository navigation
Expand file tree
/
Copy pathopencode-go.mjs
More file actions
607 lines (532 loc) · 20.1 KB
/
Copy pathopencode-go.mjs
File metadata and controls
607 lines (532 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/**
* OpenCode Go usage — live meters for an OpenCode Go subscription
* (opencode.ai/go): the rolling 5-hour, weekly and monthly windows, docked
* above the TUI status bar.
*
* /opencode-go toggle this card
*
* Lives at ~/.hermes/tui-widgets/ — Hermes hot-loads user widgets from
* that directory.
*
* Home: github.com/E-R-Butch/hermes-opencode-go-widget
*
* Two data layers:
* 1. Percent windows — GET https://opencode.ai/zen/go/v1/usage, polled
* live every 60s. Works with an API key alone.
* 2. Dollar meters — the console's micro-cent meters ($used/$limit, cent
* precision). Mirrored into ~/.hermes/opencode-go/console.json by
* fetch_console.mjs, which this card respawns when the cache goes
* stale. That helper only reads the keychain when re-run with
* --extract (session expired); normal refreshes just reuse the cached
* cookie. When no console data exists the card falls back to layer 1.
*
* Key resolution for layer 1, first hit wins:
* $OPENCODE_API_KEY → $OPENCODE_GO_API_KEY → ~/.hermes/.env
* (OPENCODE_GO_API_KEY → OPENCODE_API_KEY) → ~/.local/share/opencode/auth.json
*
* Network: only ever talks to opencode.ai. Failures land as an error phase;
* the card retries every 60s and never crashes the TUI.
*/
const BASE = 'https://opencode.ai'
const USAGE_PATH = '/zen/go/v1/usage'
const UA = 'hermes-opencode-go-widget/1.0'
const POLL_MS = 60_000
const CARD_W = 50
const BAR_W = 12
const RETRY_DELAYS_MS = [800, 1800]
const CONSOLE_MAX_AGE_MS = 6 * 60_000
const CONSOLE_STALE_HINT_MS = 15 * 60_000
const CONSOLE_SPAWN_THROTTLE_MS = 120_000
const ROLLING_KEYS = ['rolling', 'rollingUsage', 'rolling_usage', 'rollingWindow', 'rolling_window', 'fiveHour', 'five_hour']
const WEEKLY_KEYS = ['weekly', 'weeklyUsage', 'weekly_usage', 'weeklyWindow', 'weekly_window']
const MONTHLY_KEYS = ['monthly', 'monthlyUsage', 'monthly_usage', 'monthlyWindow', 'monthly_window']
const PERCENT_KEYS = ['percent', 'usagePercent', 'usedPercent', 'percentUsed', 'usage_percent', 'used_percent', 'utilization']
const USED_KEYS = ['used', 'consumed', 'usedTokens']
const LIMIT_KEYS = ['limit', 'total', 'quota', 'max', 'cap', 'tokenLimit']
const RESET_IN_KEYS = ['resetInSec', 'resetInSeconds', 'resetSeconds', 'reset_sec', 'reset_in_sec', 'resetsInSec', 'resetsInSeconds']
const RESET_AT_KEYS = ['resetsAt', 'resetAt', 'resets_at', 'reset_at', 'nextReset', 'next_reset']
const joinPath = (a, b) => a.replace(/\/+$/, '') + '/' + b
const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null)
/** Tolerant numeric coercion: numbers and numeric strings both count. */
const toNum = v => {
if (typeof v === 'number' && Number.isFinite(v)) return v
if (typeof v === 'string' && v.trim()) {
const parsed = Number(v)
if (Number.isFinite(parsed)) return parsed
}
return null
}
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const hermesHome = () =>
(process.env && process.env.HERMES_HOME && process.env.HERMES_HOME.trim()) ||
joinPath((process.env && process.env.HOME) || '', '.hermes')
const consoleCachePath = () => joinPath(hermesHome(), 'opencode-go/console.json')
const consoleScriptPath = () => joinPath(hermesHome(), 'opencode-go/fetch_console.mjs')
const consoleCookiePath = () => joinPath(hermesHome(), 'opencode-go/console_cookie')
/** Resolve the OpenCode key: env → Hermes .env → OpenCode CLI auth file. */
export async function resolveKey() {
for (const name of ['OPENCODE_API_KEY', 'OPENCODE_GO_API_KEY']) {
try {
const fromEnv = process.env && process.env[name]
if (typeof fromEnv === 'string' && fromEnv.trim()) return fromEnv.trim()
} catch {}
}
const home = (process.env && process.env.HOME) || ''
try {
const fs = await import('node:fs/promises')
const raw = await fs.readFile(joinPath(hermesHome(), '.env'), 'utf8')
for (const name of ['OPENCODE_GO_API_KEY', 'OPENCODE_API_KEY']) {
const match = raw.match(new RegExp('^\\s*(?:export\\s+)?' + name + '\\s*=\\s*(.+?)\\s*$', 'm'))
if (!match) continue
let value = match[1].trim()
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1)
}
if (value.trim()) return value.trim()
}
} catch {}
try {
const fs = await import('node:fs/promises')
const raw = await fs.readFile(joinPath(home, '.local/share/opencode/auth.json'), 'utf8')
const parsed = JSON.parse(raw)
for (const provider of ['opencode-go', 'opencode', 'opencode-zen', 'zen']) {
const key = extractAuthKey(parsed && parsed[provider])
if (key) return key
}
} catch {}
return null
}
/** Pull a key out of an OpenCode CLI auth record — plain API records plus
* the nested zen/go field names OAuth-style records carry. */
function extractAuthKey(record) {
if (!record || typeof record !== 'object') return null
for (const field of ['key', 'apiKey', 'api_key']) {
const value = record[field]
if (typeof value === 'string' && value.trim()) return value.trim()
}
for (const container of [record, record.payload, record.data]) {
if (!container || typeof container !== 'object') continue
for (const field of ['zenApiKey', 'zen_api_key', 'goApiKey', 'go_api_key']) {
const value = container[field]
if (typeof value === 'string' && value.trim()) return value.trim()
}
}
return null
}
async function get(path, key) {
const res = await fetch(BASE + path, {
headers: { Accept: 'application/json', Authorization: 'Bearer ' + key, 'User-Agent': UA },
signal: AbortSignal.timeout(8000)
})
if (!res.ok) {
const error = new Error('HTTP ' + res.status)
error.status = res.status
throw error
}
return res.json()
}
/** GET with retries — the endpoint intermittently 503s; 401/403 never retry. */
async function getRetrying(path, key) {
let lastError = null
for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
try {
return await get(path, key)
} catch (error) {
lastError = error
const status = error && typeof error === 'object' ? error.status : undefined
const retryable = status === undefined ? true : status === 429 || status >= 500
if (!retryable || attempt === RETRY_DELAYS_MS.length) break
await sleep(RETRY_DELAYS_MS[attempt])
}
}
throw lastError instanceof Error ? lastError : new Error(String(lastError))
}
/** Normalize epoch seconds/millis or ISO-8601 text to epoch millis. */
function parseTimestamp(value) {
const parsed = toNum(value)
if (parsed !== null) {
let ms = parsed
if (parsed > 1e12) ms = parsed
else if (parsed > 1e9) ms = parsed * 1000
else return null
const time = new Date(ms).getTime()
return Number.isFinite(time) ? time : null
}
if (typeof value === 'string') {
const time = Date.parse(value)
return Number.isFinite(time) ? time : null
}
return null
}
function parseResetAt(window, now) {
for (const key of RESET_IN_KEYS) {
const seconds = toNum(window[key])
if (seconds !== null && seconds >= 0) return now + seconds * 1000
}
for (const key of RESET_AT_KEYS) {
const parsed = parseTimestamp(window[key])
if (parsed !== null) return parsed
}
return null
}
function parseWindow(window, now) {
if (!window || typeof window !== 'object') return null
let pct = null
for (const key of PERCENT_KEYS) {
const value = toNum(window[key])
if (value !== null) {
pct = value
break
}
}
if (pct === null) {
let used = null
for (const key of USED_KEYS) {
const value = toNum(window[key])
if (value !== null) {
used = value
break
}
}
let limit = null
for (const key of LIMIT_KEYS) {
const value = toNum(window[key])
if (value !== null) {
limit = value
break
}
}
if (used !== null && limit !== null && limit > 0) pct = (used / limit) * 100
}
if (pct === null) return null
if (pct > 0 && pct < 1) pct *= 100
return {
pct: Math.max(0, Math.min(100, pct)),
resetAt: parseResetAt(window, now)
}
}
function firstWindow(node, keys) {
if (!node || typeof node !== 'object') return null
for (const key of keys) {
const value = node[key]
if (value && typeof value === 'object') return value
}
return null
}
function hasWindows(node) {
return !!(firstWindow(node, ROLLING_KEYS) || firstWindow(node, WEEKLY_KEYS) || firstWindow(node, MONTHLY_KEYS))
}
/** Find the object holding the three window records: the payload itself, a
* common envelope (usage/data/result/billing/payload), or a loose one-level
* scan by key name. */
function locateRoot(payload) {
if (!payload || typeof payload !== 'object') return null
if (hasWindows(payload)) return payload
for (const wrapper of ['usage', 'data', 'result', 'billing', 'payload']) {
const inner = payload[wrapper]
if (inner && typeof inner === 'object' && hasWindows(inner)) return inner
}
const loose = {}
let found = false
for (const [key, value] of Object.entries(payload)) {
if (!value || typeof value !== 'object') continue
const lower = String(key).toLowerCase()
if (!loose.rolling && /rolling|hour|5h/.test(lower)) {
loose.rolling = value
found = true
} else if (!loose.weekly && /week/.test(lower)) {
loose.weekly = value
found = true
} else if (!loose.monthly && /month/.test(lower)) {
loose.monthly = value
found = true
}
}
return found ? loose : null
}
/** Pull the three window records into one render-ready snapshot. */
export function summarize(payload, now = Date.now()) {
const data = payload && typeof payload === 'object' ? payload : {}
const root = locateRoot(data)
const planValue =
(root && (root.plan || root.planType || root.plan_type)) || data.plan || data.planType || data.plan_type
const plan = typeof planValue === 'string' && planValue.trim() ? planValue.trim() : null
return {
plan,
rolling: root ? parseWindow(firstWindow(root, ROLLING_KEYS), now) : null,
weekly: root ? parseWindow(firstWindow(root, WEEKLY_KEYS), now) : null,
monthly: root ? parseWindow(firstWindow(root, MONTHLY_KEYS), now) : null
}
}
/** Read + normalize the console cache written by fetch_console.mjs. */
export function summarizeConsole(cache, now = Date.now()) {
if (!cache || typeof cache !== 'object') return null
const fetchedAt = toNum(cache.fetchedAt)
const ageMs = fetchedAt !== null ? now - fetchedAt : null
if (cache.error) return { fetchedAt, ageMs, error: String(cache.error) }
const meters = cache.meters && typeof cache.meters === 'object' ? cache.meters : null
if (!meters) return { fetchedAt, ageMs, error: 'empty' }
const endsAt = parseTimestamp(cache.endsAt)
const window = key => {
const meter = meters[key]
if (!meter || typeof meter !== 'object') return null
const used = toNum(meter.usedMicroCents)
const limit = toNum(meter.limitMicroCents)
if (used === null || limit === null || limit <= 0) return null
return {
usedUSD: used / 1e8,
limitUSD: limit / 1e8,
pct: (used / limit) * 100,
resetAt: parseTimestamp(meter.resetsAt) ?? (key === 'month' ? endsAt : null)
}
}
const fiveHour = window('fiveHour')
const week = window('week')
const month = window('month')
if (!fiveHour && !week && !month) return { fetchedAt, ageMs, error: 'empty' }
return { fetchedAt, ageMs, endsAt, fiveHour, week, month }
}
/** Latest good snapshots — re-opening the card renders instantly while fresh
* polls land in the background. */
let lastSnapshot = null
let lastConsoleSnapshot = null
export async function fetchUsage(key) {
const payload = await getRetrying(USAGE_PATH, key)
const snap = summarize(payload)
lastSnapshot = snap
return snap
}
async function readConsoleCache() {
const fs = await import('node:fs/promises')
const raw = await fs.readFile(consoleCachePath(), 'utf8')
return JSON.parse(raw)
}
/** Spawn the console fetcher when the cache is missing/stale and the card is
* connected (cookie + script present). Fire-and-forget; the next poll picks
* up the refreshed cache. Never spawns for auth-expired — that needs a
* deliberate re-extract. */
let lastConsoleSpawnAt = 0
async function maybeRefreshConsole(consoleSnap) {
const now = Date.now()
if (now - lastConsoleSpawnAt < CONSOLE_SPAWN_THROTTLE_MS) return false
let spawnable
if (!consoleSnap) spawnable = true
else if (consoleSnap.error === 'fetch-failed') spawnable = consoleSnap.ageMs === null || consoleSnap.ageMs > 300_000
else if (consoleSnap.error) spawnable = false
else spawnable = consoleSnap.ageMs === null || consoleSnap.ageMs > CONSOLE_MAX_AGE_MS
if (!spawnable) return false
try {
const fs = await import('node:fs/promises')
await fs.access(consoleScriptPath())
await fs.access(consoleCookiePath())
} catch {
return false
}
lastConsoleSpawnAt = now
try {
const { spawn } = await import('node:child_process')
const child = spawn(process.execPath, [consoleScriptPath()], { detached: true, stdio: 'ignore' })
child.unref()
} catch {
return false
}
return true
}
export function fmtDur(ms) {
if (num(ms) === null || ms <= 0) return '—'
const mins = Math.floor(ms / 60000)
const days = Math.floor(mins / 1440)
const hours = Math.floor((mins % 1440) / 60)
if (days > 0) return days + 'd ' + hours + 'h'
if (hours > 0) return hours + 'h ' + (mins % 60) + 'm'
return mins + 'm'
}
/** ███░░░ gauge — identical output to the SDK's gauge() primitive. */
export function bar(ratio, width) {
const filled = Math.round(Math.max(0, Math.min(1, ratio || 0)) * width)
return '█'.repeat(filled) + '░'.repeat(Math.max(0, width - filled))
}
/** Usage severity for the bar + percent readout — thresholds sit a notch
* early (50/80) so the colour visibly tracks usage across a cycle. */
const WARN_PCT = 50
const ERROR_PCT = 80
const severity = pct => (pct >= ERROR_PCT ? 'error' : pct >= WARN_PCT ? 'warn' : 'ok')
/** Rows of [text, tone] segments — the single source for render and tests. */
export function cardRows(s, now = Date.now()) {
const rows = []
const header = [['⚡ OpenCode', 'primary'], [' · Go', 'muted']]
if (s.plan && !/^go$/i.test(s.plan)) header.push([' · ' + s.plan, 'muted'])
rows.push(header)
const winRow = (label, w) => {
if (!w) return null
const tone = severity(w.pct)
return [
[label.padEnd(5) + ' ', 'label'],
[bar(w.pct / 100, BAR_W), tone],
[' ', 'muted'],
[String(Math.round(w.pct)).padStart(3) + '%', tone],
[' resets ', 'muted'],
[fmtDur(w.resetAt ? w.resetAt - now : null), 'muted']
]
}
const rolling = winRow('5h', s.rolling)
const weekly = winRow('week', s.weekly)
const monthly = winRow('month', s.monthly)
if (rolling) rows.push(rolling)
if (weekly) rows.push(weekly)
if (monthly) rows.push(monthly)
if (!rolling && !weekly && !monthly) rows.push([['no usage windows in response', 'muted']])
return rows
}
/** Dollar rows from the console meters: bar · % · $used/$limit · time left. */
export function consoleCardRows(c, now = Date.now()) {
const rows = [[['⚡ OpenCode', 'primary'], [' · Go', 'muted']]]
const winRow = (label, w) => {
if (!w) return null
const tone = severity(w.pct)
const used = ('$' + w.usedUSD.toFixed(2)).padStart(6)
const cap = '$' + (w.limitUSD % 1 === 0 ? String(w.limitUSD) : w.limitUSD.toFixed(2))
const pair = (used + '/' + cap).padStart(10)
return [
[label.padEnd(5) + ' ', 'label'],
[bar(w.pct / 100, BAR_W), tone],
[' ', 'muted'],
[String(Math.round(w.pct)).padStart(3) + '%', tone],
[' ', 'muted'],
[pair, 'text'],
[' ', 'muted'],
['·' + fmtDur(w.resetAt ? w.resetAt - now : null), 'muted']
]
}
const rolling = winRow('5h', c.fiveHour)
const weekly = winRow('week', c.week)
const monthly = winRow('month', c.month)
if (rolling) rows.push(rolling)
if (weekly) rows.push(weekly)
if (monthly) rows.push(monthly)
if (!rolling && !weekly && !monthly) rows.push([['no console meters available', 'muted']])
return rows
}
/** Prime the console cache at module load so a (re)opened card renders its
* dollars instantly — the module is re-imported on every hot reload. */
try {
const { readFileSync } = await import('node:fs')
lastConsoleSnapshot = summarizeConsole(JSON.parse(readFileSync(consoleCachePath(), 'utf8')))
} catch {}
export default function register(sdk) {
const { Box, Dialog, React, ShimmerRows, Text, defineWidgetApp, h } = sdk
const LOADING_ROWS = [
[5, 12],
[5, 12],
[5, 12],
[5, 16]
]
function DataCard({ t, rows, hint }) {
return h(
Dialog,
{
width: CARD_W,
hint: hint ? h(Text, { color: t.color[hint.tone] || t.color.muted }, hint.text) : undefined
},
rows.map((segments, i) =>
h(
Box,
{ flexDirection: 'row', key: 'r' + i },
segments.map(([text, tone], j) =>
h(Text, { color: t.color[tone] || t.color.text, key: 's' + j }, text)
)
)
)
)
}
function Card({ t }) {
const [snapshot, setSnapshot] = React.useState(lastSnapshot)
const [consoleSnap, setConsoleSnap] = React.useState(lastConsoleSnapshot)
const [problem, setProblem] = React.useState(null)
React.useEffect(() => {
let stopped = false
let timer
let settleTimer
const poll = async () => {
let freshConsole = null
try {
freshConsole = summarizeConsole(await readConsoleCache())
} catch {}
if (freshConsole) {
lastConsoleSnapshot = freshConsole
if (!stopped) setConsoleSnap(freshConsole)
}
const spawned = await maybeRefreshConsole(freshConsole)
if (spawned && !stopped) {
clearTimeout(settleTimer)
settleTimer = setTimeout(() => void poll(), 4000)
}
try {
const key = await resolveKey()
if (!key) {
if (!stopped) setProblem('no API key')
return
}
const fresh = await fetchUsage(key)
if (!stopped) {
setSnapshot(fresh)
setProblem(null)
}
} catch (error) {
if (!stopped) setProblem(error instanceof Error ? error.message : String(error))
}
}
void poll()
timer = setInterval(() => void poll(), POLL_MS)
return () => {
stopped = true
clearInterval(timer)
clearTimeout(settleTimer)
}
}, [])
const now = Date.now()
const consoleOk =
consoleSnap && !consoleSnap.error && (consoleSnap.fiveHour || consoleSnap.week || consoleSnap.month)
if (consoleOk || snapshot) {
const rows = consoleOk ? consoleCardRows(consoleSnap, now) : cardRows(snapshot, now)
let hint = null
if (problem) hint = { text: 'offline — retrying', tone: 'error' }
else if (consoleSnap && consoleSnap.error === 'auth-expired')
hint = { text: 'console session expired', tone: 'error' }
else if (consoleSnap && consoleSnap.error === 'fetch-failed') hint = { text: 'console offline', tone: 'muted' }
else if (consoleOk && consoleSnap.ageMs !== null && consoleSnap.ageMs > CONSOLE_STALE_HINT_MS)
hint = { text: 'console data stale', tone: 'muted' }
return h(DataCard, { t, rows, hint })
}
if (problem) {
return h(
Dialog,
{ width: CARD_W },
h(
Text,
{ color: t.color.error },
'⚠ ' + (problem === 'no API key' ? 'no API key found' : String(problem).slice(0, 48))
),
h(Text, { color: t.color.muted }, 'env → ~/.hermes/.env → opencode auth.json')
)
}
return h(Dialog, { width: CARD_W }, h(ShimmerRows, { rows: LOADING_ROWS, t }))
}
defineWidgetApp({
id: 'opencode-go',
help: 'OpenCode Go usage — 5h / weekly / monthly meters ($ when console-connected)',
mode: 'ambient',
zone: 'dock-bottom',
width: CARD_W,
usage: 'usage: /opencode-go toggle the OpenCode Go usage card',
init() {
return {}
},
reduce(state) {
return state
},
render({ t }) {
return h(Card, { t })
}
})
}