opencode-usage-limits 0.3.1 → 0.3.3

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/tui.tsx DELETED
@@ -1,355 +0,0 @@
1
- /** @jsxImportSource @opentui/solid */
2
- import { Plugin } from "@opencode/plugin/tui"
3
- import { Index, Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js"
4
- import {
5
- WINDOW_COUNT,
6
- backoffFor,
7
- clampPercent,
8
- fetchUsage,
9
- formatUsd,
10
- goWindowsFromLimits,
11
- isTransient,
12
- isWindowLimited,
13
- keyFromCredentials,
14
- modelAllowance,
15
- resetText,
16
- resolveKey,
17
- resolveProvider,
18
- rightAlign,
19
- usedUsd,
20
- windowSeverity,
21
- type UsageWindow,
22
- } from "./core.ts"
23
-
24
- const REFRESH_MS = 30_000
25
- const MAX_BACKOFF_MS = 5 * 60_000
26
- /** Fixed width of the title row's right-hand status cell (spinner or age). */
27
- const STATUS_WIDTH = 4
28
-
29
- type Palette = {
30
- text: any
31
- muted: any
32
- accent: any
33
- green: any
34
- warn: any
35
- danger: any
36
- track: any
37
- }
38
-
39
- function readPalette(theme: any): Palette {
40
- const action = theme?.text?.action?.primary
41
- const base = theme?.text?.base
42
- return {
43
- text: base,
44
- muted: theme?.text?.muted,
45
- accent: action?.base ?? base,
46
- // Green / yellow / red usage states come from the theme's semantic feedback
47
- // colours so they stay consistent with the active theme.
48
- green: theme?.text?.feedback?.success?.base ?? "#3FB950",
49
- warn: theme?.text?.feedback?.warning?.base ?? base,
50
- danger: theme?.text?.feedback?.error?.base ?? base,
51
- // Use the theme's border colour for the unfilled track: it is guaranteed to
52
- // contrast with the sidebar panel background (raised.base is the panel
53
- // colour itself, which made the track invisible).
54
- track: theme?.border?.base ?? theme?.background?.raised?.base,
55
- }
56
- }
57
-
58
- function severityColor(palette: Palette, window: UsageWindow) {
59
- const level = windowSeverity(window)
60
- if (level === "danger") return palette.danger
61
- if (level === "warn") return palette.warn
62
- return palette.green
63
- }
64
-
65
- function ProgressBar(props: { percent: number; color: any; track: any }) {
66
- const pct = () => Math.max(0, Math.min(100, props.percent))
67
- return (
68
- <box width="100%" height={1} flexDirection="row">
69
- <box flexGrow={Math.max(pct(), 0.01)} backgroundColor={props.color} />
70
- <box flexGrow={Math.max(100 - pct(), 0.01)} backgroundColor={props.track} />
71
- </box>
72
- )
73
- }
74
-
75
- function WindowRow(props: { window: UsageWindow; palette: Palette; now: number }) {
76
- const pct = () => clampPercent(props.window.percent)
77
- const color = () => severityColor(props.palette, props.window)
78
- const limited = () => isWindowLimited(props.window)
79
- // Memoised so the ticking clock only writes to the DOM when the rendered text
80
- // actually changes (Solid memos compare with ===).
81
- const resetLabel = createMemo(() => `↻ ${resetText(props.window.resetsAt, props.now)}`)
82
- // Only providers with a real dollar cap (ClinePass) have one; computing this
83
- // here keeps the Show guard from being the only thing preventing a crash on
84
- // an undefined amount.
85
- const amountText = createMemo(() => {
86
- const used = usedUsd(props.window)
87
- if (used == null || props.window.limit == null) return ""
88
- return `${formatUsd(used)} / ${formatUsd(props.window.limit)}`
89
- })
90
-
91
- return (
92
- <box flexDirection="column" width="100%" marginTop={1}>
93
- <box flexDirection="row" width="100%">
94
- <box flexGrow={1} flexDirection="row">
95
- <text fg={color()}>{props.window.label}</text>
96
- <Show when={limited()}>
97
- <text fg={color()}>{` ${props.window.status}`}</text>
98
- </Show>
99
- </box>
100
- <text fg={color()}>{rightAlign(`${pct()}%`, 5)}</text>
101
- </box>
102
- <ProgressBar percent={props.window.percent} color={color()} track={props.palette.track} />
103
- <box flexDirection="row" width="100%">
104
- <text fg={props.palette.muted}>{resetLabel()}</text>
105
- <box flexGrow={1} />
106
- <Show when={amountText() !== ""}>
107
- <text fg={props.palette.muted}>{amountText()}</text>
108
- </Show>
109
- </box>
110
- </box>
111
- )
112
- }
113
-
114
- function UsagePanel(props: { context: any; panel: any; toggle: () => void }) {
115
- const ctx = props.context
116
- const palette = createMemo<Palette>(() => readPalette(ctx.theme))
117
- const providerID = createMemo<string | undefined>(() => ctx.ui.model.current()?.providerID)
118
- const modelID = createMemo<string | undefined>(() => ctx.ui.model.current()?.modelID)
119
- const config = createMemo(() => {
120
- const id = providerID()
121
- return id ? resolveProvider(id, ctx.options) : undefined
122
- })
123
-
124
- // How expensive the selected model is, shown as a reference line under the
125
- // windows. Purely informational: the usage API reports percentages only.
126
- const allowanceText = createMemo(() => {
127
- if (providerID() !== "opencode-go") return ""
128
- const allowance = modelAllowance(modelID())
129
- if (allowance === "free") return "∞"
130
- if (!allowance) return "—"
131
- return `$${allowance.go}/$${allowance.plus}`
132
- })
133
-
134
- const [windows, setWindows] = createSignal<UsageWindow[]>([])
135
- const [loading, setLoading] = createSignal(false)
136
- const [error, setError] = createSignal("")
137
- const [now, setNow] = createSignal(Date.now())
138
- const [lastOkAt, setLastOkAt] = createSignal<number | undefined>(undefined)
139
- const [nextRetryAt, setNextRetryAt] = createSignal<number | undefined>(undefined)
140
-
141
- const baseMs = Number(props.context?.options?.refreshMs) || REFRESH_MS
142
- let pollMs = baseMs
143
-
144
- // OpenCode v2 keeps credentials in its database, so read them through the
145
- // host API first and only fall back to auth.json. The list is briefly cached:
146
- // polling runs every 30s and a key rotation need not be picked up instantly.
147
- let credentialCache: { at: number; entries: unknown } | undefined
148
- const readCredentials = async () => {
149
- const client = ctx.client as any
150
- if (typeof client?.credential?.list !== "function") return undefined
151
- if (credentialCache && Date.now() - credentialCache.at < 60_000) return credentialCache.entries
152
- const entries = await client.credential.list()
153
- credentialCache = { at: Date.now(), entries }
154
- return entries
155
- }
156
- const keyFromHost = async (id: string) => keyFromCredentials(await readCredentials(), id)
157
-
158
- // Newer OpenCode releases expose the Go meters themselves. Use them when the
159
- // host has the endpoint, so this provider needs no key at all; older releases
160
- // return undefined and fall back to the provider endpoint below.
161
- const goFromHost = async (): Promise<UsageWindow[] | undefined> => {
162
- const client = ctx.client as any
163
- const limits = client?.experimental?.usage?.limits
164
- if (typeof limits !== "function") return undefined
165
- try {
166
- const location = ctx.location ?? ctx.data?.location?.default?.()
167
- const result = await limits.call(client.experimental.usage, location ? { location } : undefined)
168
- return goWindowsFromLimits(result)
169
- } catch {
170
- return undefined
171
- }
172
- }
173
-
174
- // Guard per provider: if the user switches providers while a request is
175
- // still in flight, the new provider's request must fire immediately instead
176
- // of waiting for the next poll. Stale responses are dropped by the
177
- // `config()?.id === cfg.id` check below, so they cannot pollute the panel.
178
- const inflight = new Set<string>()
179
- const refresh = async () => {
180
- const cfg = config()
181
- if (!cfg || inflight.has(cfg.id)) return
182
- inflight.add(cfg.id)
183
- setLoading(true)
184
- try {
185
- let next = cfg.id === "opencode-go" ? await goFromHost() : undefined
186
- if (!next) {
187
- const key = await resolveKey(cfg.id, keyFromHost)
188
- if (!key) {
189
- setWindows([])
190
- setError("API key not found")
191
- setNextRetryAt(undefined)
192
- pollMs = baseMs
193
- return
194
- }
195
- next = await fetchUsage(cfg, key)
196
- }
197
- if (config()?.id === cfg.id) {
198
- setWindows(next)
199
- setError("")
200
- setLastOkAt(Date.now())
201
- setNextRetryAt(undefined)
202
- }
203
- pollMs = baseMs
204
- } catch (err: any) {
205
- const message = err?.message ?? "usage API unavailable"
206
- if (isTransient(err)) {
207
- // Rate limits and network/server failures back off instead of hammering
208
- // the endpoint on every tick.
209
- pollMs = backoffFor(err, pollMs, baseMs, MAX_BACKOFF_MS)
210
- setNextRetryAt(Date.now() + pollMs)
211
- } else {
212
- pollMs = baseMs
213
- setNextRetryAt(undefined)
214
- }
215
- setError(message)
216
- } finally {
217
- inflight.delete(cfg.id)
218
- setLoading(inflight.size > 0)
219
- }
220
- }
221
-
222
- let pollTimer: any
223
- let tickTimer: any
224
- onMount(() => {
225
- let cancelled = false
226
- const loop = async () => {
227
- if (cancelled) return
228
- await refresh()
229
- if (cancelled) return
230
- pollTimer = setTimeout(loop, pollMs)
231
- }
232
- pollTimer = setTimeout(loop, baseMs)
233
-
234
- // The countdown only ever shows minute precision, so tick on minute
235
- // boundaries instead of every second. While a retry countdown is on screen
236
- // tick every second so the remaining seconds stay live.
237
- const scheduleTick = () => {
238
- const delay = nextRetryAt() !== undefined ? 1000 : 60_000 - (Date.now() % 60_000)
239
- tickTimer = setTimeout(() => {
240
- if (cancelled) return
241
- setNow(Date.now())
242
- scheduleTick()
243
- }, delay)
244
- }
245
- scheduleTick()
246
-
247
- onCleanup(() => {
248
- cancelled = true
249
- clearTimeout(pollTimer)
250
- clearTimeout(tickTimer)
251
- })
252
- })
253
-
254
- createEffect(() => {
255
- const cfg = config()
256
- setWindows([])
257
- setError("")
258
- setNextRetryAt(undefined)
259
- pollMs = baseMs
260
- if (cfg) {
261
- setLastOkAt(undefined)
262
- void refresh()
263
- }
264
- })
265
-
266
- // Age of the reading currently on screen, and whether it is older than two
267
- // polling intervals (i.e. the panel is showing stale data after a failure).
268
- const ageSeconds = () => {
269
- const at = lastOkAt()
270
- if (!at) return undefined
271
- return Math.max(0, Math.floor((now() - at) / 1000))
272
- }
273
- const isStale = createMemo(() => {
274
- const s = ageSeconds()
275
- return s !== undefined && s * 1000 > baseMs * 2.5
276
- })
277
- // Minute precision: the label stays identical between ticks, and the memo
278
- // stops Solid from rewriting the text node every time the clock advances.
279
- const ageText = createMemo(() => {
280
- const s = ageSeconds()
281
- if (s === undefined) return ""
282
- if (s < 60) return "now"
283
- if (s < 3600) return `${Math.floor(s / 60)}m`
284
- return `${Math.floor(s / 3600)}h`
285
- })
286
- // Only surface the age once the reading is actually stale: while the data is
287
- // fresh the cell stays blank so the title row carries no noise. The spinner
288
- // keeps using the same fixed-width cell, so it never shifts the layout.
289
- const statusText = createMemo(() => rightAlign(loading() ? "⋯" : isStale() ? ageText() : "", STATUS_WIDTH))
290
- const retryText = createMemo(() => {
291
- const at = nextRetryAt()
292
- if (at === undefined) return ""
293
- return ` · retry in ${Math.max(0, Math.ceil((at - now()) / 1000))}s`
294
- })
295
-
296
- return (
297
- <Show when={config()}>
298
- {(cfg) => (
299
- <box flexDirection="column" width="100%" marginTop={1}>
300
- <box flexDirection="row" width="100%" onMouseUp={() => props.toggle()}>
301
- <box flexGrow={1}>
302
- <text fg={palette().text}>{`${props.panel.collapsed ? "▸" : "▾"} USAGE · ${cfg().title}`}</text>
303
- </box>
304
- <text fg={isStale() && !loading() ? palette().warn : palette().muted}>{statusText()}</text>
305
- </box>
306
- <Show when={!props.panel.collapsed}>
307
- <Show when={error()}>
308
- <text fg={palette().danger}>{`${error()}${retryText()}`}</text>
309
- </Show>
310
- <Show when={windows().length > 0 && windows().length < WINDOW_COUNT}>
311
- <text fg={palette().warn}>{`partial data · ${windows().length}/${WINDOW_COUNT} windows`}</text>
312
- </Show>
313
- <Index each={windows()}>{(w) => <WindowRow window={w()} palette={palette()} now={now()} />}</Index>
314
- <Show when={allowanceText() !== ""}>
315
- <box flexDirection="row" width="100%" marginTop={1}>
316
- <box flexGrow={1}>
317
- <text fg={palette().text}>{modelID() ?? ""}</text>
318
- </box>
319
- <text fg={palette().text}>{allowanceText()}</text>
320
- </box>
321
- </Show>
322
- </Show>
323
- </box>
324
- )}
325
- </Show>
326
- )
327
- }
328
-
329
- export default Plugin.define({
330
- id: "usage-limits",
331
- setup(context) {
332
- const [panel, updatePanel] = context.storage.store("usage-limits.panel", {
333
- initial: { collapsed: false },
334
- })
335
- const toggle = () => void updatePanel((draft: any) => { draft.collapsed = !draft.collapsed })
336
-
337
- context.keymap.layer(() => ({
338
- mode: "global",
339
- commands: [
340
- {
341
- id: "usage-limits.toggle",
342
- title: "Toggle usage panel",
343
- group: "Usage Limits",
344
- palette: true,
345
- run: toggle,
346
- },
347
- ],
348
- }))
349
-
350
- return context.ui.slot({
351
- prepend: "sidebar.content",
352
- render: () => <UsagePanel context={context} panel={panel} toggle={toggle} />,
353
- })
354
- },
355
- })