opencode-usage-limits 0.3.0 → 0.3.2

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-usage-limits",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "type": "module",
5
5
  "description": "Show OpenCode Go and ClinePass subscription usage (5-hour / weekly / monthly) in the OpenCode TUI sidebar.",
6
6
  "license": "MIT",
@@ -26,19 +26,22 @@
26
26
  "exports": {
27
27
  ".": "./index.ts",
28
28
  "./server": "./index.ts",
29
- "./tui": "./tui.tsx"
29
+ "./tui": "./dist/tui.js"
30
30
  },
31
31
  "files": [
32
32
  "index.ts",
33
- "tui.ts",
34
- "tui.tsx",
35
- "core.ts",
33
+ "dist/tui.js",
36
34
  "README.md",
37
35
  "README.en.md",
38
36
  "CHANGELOG.md",
39
37
  "CHANGELOG.en.md",
40
38
  "LICENSE"
41
39
  ],
40
+ "scripts": {
41
+ "build": "node scripts/build.mjs",
42
+ "dev": "node scripts/build.mjs --watch",
43
+ "prepack": "npm run build"
44
+ },
42
45
  "peerDependencies": {
43
46
  "@opencode/plugin": ">=2.0.0",
44
47
  "@opentui/core": ">=0.4.5",
@@ -46,12 +49,24 @@
46
49
  "solid-js": ">=1.9.0"
47
50
  },
48
51
  "peerDependenciesMeta": {
49
- "@opencode/plugin": { "optional": true },
50
- "@opentui/core": { "optional": true },
51
- "@opentui/solid": { "optional": true }
52
+ "@opencode/plugin": {
53
+ "optional": true
54
+ },
55
+ "@opentui/core": {
56
+ "optional": true
57
+ },
58
+ "@opentui/solid": {
59
+ "optional": true
60
+ }
52
61
  },
53
62
  "publishConfig": {
54
63
  "registry": "https://registry.npmjs.org",
55
64
  "access": "public"
65
+ },
66
+ "devDependencies": {
67
+ "@babel/core": "^7.29.13",
68
+ "@babel/preset-typescript": "^7.29.7",
69
+ "babel-preset-solid": "^1.9.16",
70
+ "esbuild": "^0.28.2"
56
71
  }
57
- }
72
+ }
package/core.ts DELETED
@@ -1,380 +0,0 @@
1
- // Shared logic for the usage-limits TUI plugin.
2
- // No JSX here so it can also be imported by the preview script.
3
- import { readFile } from "node:fs/promises"
4
- import { existsSync } from "node:fs"
5
- import { homedir } from "node:os"
6
- import { join } from "node:path"
7
-
8
- export type WindowKind = "hour5" | "weekly" | "monthly"
9
-
10
- export interface UsageWindow {
11
- kind: WindowKind
12
- label: string
13
- percent: number
14
- /** USD budget for this window; OpenCode Go uses fixed budgets, ClinePass reads them from the plan. */
15
- limit?: number
16
- /** Epoch ms when the window resets, or null when unknown. */
17
- resetsAt: number | null
18
- /** Provider-reported window status (OpenCode Go only), e.g. "ok". */
19
- status?: string
20
- }
21
-
22
- export interface ProviderConfig {
23
- id: string
24
- title: string
25
- baseUrl: string
26
- path: string
27
- /** Endpoint exposing the plan's per-window USD caps, when the provider has one. */
28
- planPath?: string
29
- /** Dollar budgets per window (OpenCode Go only). */
30
- limits?: Record<WindowKind, number>
31
- }
32
-
33
- export const PROVIDERS: Record<string, ProviderConfig> = {
34
- "opencode-go": {
35
- id: "opencode-go",
36
- title: "OpenCode Go",
37
- baseUrl: "https://opencode.ai/zen/go/v1",
38
- path: "/usage",
39
- // No dollar budgets: the usage API only reports percentages, and the
40
- // per-model allowances on the pricing page are reference information shown
41
- // separately (see GO_MODEL_ALLOWANCE).
42
- },
43
- "cline-pass": {
44
- id: "cline-pass",
45
- title: "ClinePass",
46
- baseUrl: "https://api.cline.bot/api/v1",
47
- path: "/users/me/plan/usage-limits",
48
- planPath: "/users/me/plan",
49
- },
50
- }
51
-
52
- export type PlanTier = "go" | "plus"
53
-
54
- /**
55
- * Monthly allowance per OpenCode Go model, by plan tier, taken from the
56
- * official usage table at https://opencode.ai/zh/go.
57
- *
58
- * Reference only: it is displayed as "how expensive is this model", never used
59
- * to derive spend. The usage API reports percentages and says nothing about
60
- * which model an allowance belongs to, so converting a percentage into dollars
61
- * would be guesswork.
62
- */
63
- export const GO_MODEL_ALLOWANCE: Record<string, Record<PlanTier, number> | "free"> = {
64
- "kimi-k3": { go: 15, plus: 60 },
65
- "qwen3.8-max": { go: 15, plus: 60 },
66
- "grok-4.7": { go: 15, plus: 60 },
67
- "grok-4.6": { go: 15, plus: 60 },
68
- "glm-5.3": { go: 15, plus: 120 },
69
- "glm-5.2": { go: 60, plus: 180 },
70
- "deepseek-v4-pro": { go: 15, plus: 60 },
71
- "kimi-k2.7-code": { go: 60, plus: 180 },
72
- "hy4-preview": { go: 30, plus: 120 },
73
- "gpt-5.6-luna": { go: 15, plus: 60 },
74
- "space-bunny": { go: 30, plus: 120 },
75
- "minimax-m3": { go: 60, plus: 180 },
76
- "mimo-v2.6-pro": { go: 15, plus: 60 },
77
- "mimo-v2.5-pro": { go: 15, plus: 60 },
78
- "minimax-m2.7": { go: 60, plus: 240 },
79
- "claude-haiku-5-5": { go: 15, plus: 60 },
80
- "gpt-6-luna": { go: 15, plus: 60 },
81
- "qwen3.7-plus": { go: 60, plus: 180 },
82
- hy3: { go: 60, plus: 240 },
83
- "qwen3.8-flash": { go: 30, plus: 90 },
84
- "glm-5.3-flash": { go: 60, plus: 180 },
85
- "deepseek-v4-flash-vision-exp": { go: 15, plus: 60 },
86
- "longcat-2.0": { go: 60, plus: 240 },
87
- "deepseek-v4-flash": { go: 30, plus: 120 },
88
- "mimo-v2.6-flash": { go: 60, plus: 120 },
89
- "mimo-v2.5": { go: 60, plus: 120 },
90
- "deepseek-v4.1-flash": { go: 80, plus: 160 },
91
- "muse-spark-1.3-contributor": { go: 60, plus: 120 },
92
- "muse-spark-1.2-contributor": { go: 60, plus: 120 },
93
- "longcat-2.5-preview-free": "free",
94
- "step-5-preview-free": "free",
95
- }
96
-
97
- /** Allowance of an OpenCode Go model, or undefined when it is not in the table. */
98
- export function modelAllowance(modelID: string | undefined): Record<PlanTier, number> | "free" | undefined {
99
- if (!modelID) return undefined
100
- return GO_MODEL_ALLOWANCE[modelID]
101
- }
102
-
103
- const WINDOW_LABEL: Record<WindowKind, string> = {
104
- hour5: "5 hours",
105
- weekly: "Weekly",
106
- monthly: "Monthly",
107
- }
108
-
109
- /** Provider configuration with any user-supplied limit overrides applied. */
110
- export function resolveProvider(providerID: string, options?: any): ProviderConfig | undefined {
111
- const base = PROVIDERS[providerID]
112
- if (!base) return undefined
113
- const override = options?.limits?.[providerID]
114
- if (!override) return base
115
- return { ...base, limits: { ...(base.limits ?? {}), ...override } as Record<WindowKind, number> }
116
- }
117
-
118
- const WINDOW_ORDER: WindowKind[] = ["hour5", "weekly", "monthly"]
119
-
120
- /** Number of windows a complete reading contains. */
121
- export const WINDOW_COUNT = WINDOW_ORDER.length
122
-
123
- // ---- API key resolution -------------------------------------------------
124
-
125
- function authPaths(): string[] {
126
- const home = homedir()
127
- const paths = [join(home, ".local", "share", "opencode", "auth.json")]
128
- if (process.env.XDG_DATA_HOME) paths.push(join(process.env.XDG_DATA_HOME, "opencode", "auth.json"))
129
- if (process.env.LOCALAPPDATA) paths.push(join(process.env.LOCALAPPDATA, "opencode", "auth.json"))
130
- if (process.env.APPDATA) paths.push(join(process.env.APPDATA, "opencode", "auth.json"))
131
- return paths
132
- }
133
-
134
- /**
135
- * Pull an API key out of an auth-store entry. The store may hold a single
136
- * credential object, or an array of them when several accounts/connections
137
- * exist for one provider; in that case the first usable key wins.
138
- */
139
- function extractKey(entry: any): string | undefined {
140
- if (!entry) return undefined
141
- if (Array.isArray(entry)) {
142
- for (const item of entry) {
143
- const key = extractKey(item)
144
- if (key) return key
145
- }
146
- return undefined
147
- }
148
- if (typeof entry !== "object") return undefined
149
- for (const field of ["key", "apiKey", "access", "token"]) {
150
- const value = entry[field]
151
- if (typeof value === "string" && value.length > 0) return value
152
- }
153
- return undefined
154
- }
155
-
156
- /** Resolve the provider API key from the env or OpenCode's auth store. */
157
- export async function resolveKey(providerID: string): Promise<string | undefined> {
158
- const envName = `${providerID.toUpperCase().replace(/-/g, "_")}_API_KEY`
159
- const fromEnv = process.env[envName]
160
- if (fromEnv) return fromEnv
161
-
162
- for (const path of authPaths()) {
163
- try {
164
- if (!existsSync(path)) continue
165
- const store = JSON.parse(await readFile(path, "utf-8"))
166
- const key = extractKey(store?.[providerID])
167
- if (key) return key
168
- } catch {
169
- // try the next candidate path
170
- }
171
- }
172
- return undefined
173
- }
174
-
175
- // ---- API fetching -------------------------------------------------------
176
-
177
- function toMs(value: unknown): number | null {
178
- if (typeof value !== "string") return null
179
- const ms = new Date(value).getTime()
180
- return Number.isFinite(ms) ? ms : null
181
- }
182
-
183
- function buildWindow(
184
- kind: WindowKind,
185
- percent: number,
186
- resetsAt: number | null,
187
- limits?: Record<WindowKind, number>,
188
- status?: string,
189
- ): UsageWindow {
190
- return { kind, label: WINDOW_LABEL[kind], percent, limit: limits?.[kind], resetsAt, status }
191
- }
192
-
193
- /**
194
- * ClinePass reports plan caps as fixed-point integers. Calibrated against the
195
- * live API: the sum of `costUsd` over a rolling window matches
196
- * `percent x cap` in the same unit, and a single ~144k-token request costs
197
- * ~82,000 units. 1 unit = 1e-8 USD, i.e. $10 / $25 / $50 for 5h / weekly / monthly.
198
- */
199
- export const CLINE_CAP_UNIT_USD = 1e-8
200
-
201
- const capCache = new Map<string, { at: number; caps: Record<WindowKind, number> }>()
202
- const CAP_TTL_MS = 6 * 60 * 60 * 1000
203
-
204
- /**
205
- * Read the plan's per-window USD caps. Caps change rarely, so they are cached.
206
- * Caps are a nice-to-have: any failure returns undefined and never fails the
207
- * usage fetch itself.
208
- */
209
- async function fetchPlanCaps(
210
- config: ProviderConfig,
211
- key: string,
212
- timeoutMs: number,
213
- ): Promise<Record<WindowKind, number> | undefined> {
214
- if (!config.planPath) return undefined
215
- const hit = capCache.get(config.id)
216
- if (hit && Date.now() - hit.at < CAP_TTL_MS) return hit.caps
217
- try {
218
- const url = config.baseUrl.replace(/\/$/, "") + config.planPath
219
- const data = await readJson(url, key, timeoutMs)
220
- const threshold = data?.data?.plan?.entitlements?.cline_pass?.inferenceCapThreshold
221
- if (!threshold) return undefined
222
- const caps: Record<WindowKind, number> = {
223
- hour5: Number(threshold.last5HoursUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
224
- weekly: Number(threshold.last7daysUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
225
- monthly: Number(threshold.last30daysUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
226
- }
227
- if (!Object.values(caps).every((n) => Number.isFinite(n) && n > 0)) return undefined
228
- capCache.set(config.id, { at: Date.now(), caps })
229
- return caps
230
- } catch {
231
- return undefined
232
- }
233
- }
234
-
235
- /** HTTP failure carrying the status code so callers can decide on a backoff. */
236
- function httpError(status: number, message: string): Error {
237
- const error = new Error(message)
238
- ;(error as any).status = status
239
- return error
240
- }
241
-
242
- async function readJson(url: string, key: string, timeoutMs: number): Promise<any> {
243
- const controller = new AbortController()
244
- const timer = setTimeout(() => controller.abort(), timeoutMs)
245
- try {
246
- const res = await fetch(url, {
247
- headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
248
- signal: controller.signal,
249
- })
250
- if (res.status === 401 || res.status === 403) throw httpError(res.status, "API key rejected")
251
- if (res.status === 429) throw httpError(429, "rate limited by the usage API")
252
- if (!res.ok) throw httpError(res.status, `usage API ${res.status}`)
253
- return await res.json()
254
- } finally {
255
- clearTimeout(timer)
256
- }
257
- }
258
-
259
- /**
260
- * Whether a failure is worth retrying with a growing delay, and how long to
261
- * wait. Rate limits and server errors back off; auth and shape errors do not.
262
- */
263
- export function backoffFor(error: unknown, currentMs: number, baseMs: number, maxMs = 5 * 60_000): number {
264
- const status = Number((error as any)?.status) || 0
265
- // A 0 status means a network/abort failure, which is also transient.
266
- const transient = status === 0 || status === 429 || (status >= 500 && status < 600)
267
- if (!transient) return baseMs
268
- return Math.min(Math.max(currentMs, baseMs) * 2, maxMs)
269
- }
270
-
271
- /** True when the error is transient (used to label the retry countdown). */
272
- export function isTransient(error: unknown): boolean {
273
- const status = Number((error as any)?.status) || 0
274
- return status === 0 || status === 429 || (status >= 500 && status < 600)
275
- }
276
-
277
- /**
278
- * Fetch the three usage windows for a provider.
279
- *
280
- * OpenCode Go reports percentages only; the per-model dollar allowances on the
281
- * pricing page are reference information and are never converted into "spend".
282
- * ClinePass reports percentages plus a plan document whose caps ARE real
283
- * dollars, so its windows carry a limit and the panel can show used / limit.
284
- */
285
- export async function fetchUsage(config: ProviderConfig, key: string, timeoutMs = 10000): Promise<UsageWindow[]> {
286
- const url = config.baseUrl.replace(/\/$/, "") + config.path
287
- const data = await readJson(url, key, timeoutMs)
288
-
289
- if (config.id === "cline-pass") {
290
- const limits: any[] = Array.isArray(data?.data?.limits) ? data.data.limits : []
291
- const map: Record<string, WindowKind> = { five_hour: "hour5", weekly: "weekly", monthly: "monthly" }
292
- const caps = await fetchPlanCaps(config, key, timeoutMs)
293
- const windows: UsageWindow[] = []
294
- for (const kind of WINDOW_ORDER) {
295
- const hit = limits.find((l) => map[l?.type] === kind)
296
- if (!hit) continue
297
- windows.push(buildWindow(kind, Number(hit.percentUsed) || 0, toMs(hit.resetsAt), caps ?? config.limits))
298
- }
299
- if (windows.length === 0) throw new Error("usage API returned an unexpected shape")
300
- return windows
301
- }
302
-
303
- const usage = data?.usage
304
- const sources: Record<WindowKind, any> = {
305
- hour5: usage?.rolling,
306
- weekly: usage?.weekly,
307
- monthly: usage?.monthly,
308
- }
309
- const windows: UsageWindow[] = []
310
- for (const kind of WINDOW_ORDER) {
311
- const src = sources[kind]
312
- if (!src) continue
313
- const status = typeof src.status === "string" ? src.status : undefined
314
- windows.push(buildWindow(kind, Number(src.percent) || 0, toMs(src.resetsAt), undefined, status))
315
- }
316
- if (windows.length === 0) throw new Error("usage API returned an unexpected shape")
317
- return windows
318
- }
319
-
320
- // ---- Formatting ---------------------------------------------------------
321
-
322
- const MINUTE = 60_000
323
- const HOUR = 60 * MINUTE
324
- const DAY = 24 * HOUR
325
-
326
- export function clampPercent(value: number): number {
327
- return Math.max(0, Math.min(100, Math.round(value)))
328
- }
329
-
330
- export function formatUsd(value: number): string {
331
- return `$${value.toFixed(2)}`
332
- }
333
-
334
- export function usedUsd(window: UsageWindow): number | undefined {
335
- if (window.limit == null) return undefined
336
- return (window.percent / 100) * window.limit
337
- }
338
-
339
- export function rightAlign(value: string, width: number): string {
340
- return value.padStart(width)
341
- }
342
-
343
- /** Compact countdown such as `1h12m`, `5d 4h`, `now`. */
344
- export function resetText(resetsAt: number | null, now: number): string {
345
- if (resetsAt == null) return "--"
346
- const remaining = resetsAt - now
347
- if (remaining <= 0) return "now"
348
- if (remaining < HOUR) return `${Math.max(1, Math.floor(remaining / MINUTE))}m`
349
- if (remaining < DAY) {
350
- const h = Math.floor(remaining / HOUR)
351
- const m = Math.floor((remaining % HOUR) / MINUTE)
352
- return m > 0 && h < 10 ? `${h}h${m}m` : `${h}h`
353
- }
354
- const d = Math.floor(remaining / DAY)
355
- const h = Math.floor((remaining % DAY) / HOUR)
356
- return h > 0 ? `${d}d ${h}h` : `${d}d`
357
- }
358
-
359
- export type Severity = "ok" | "warn" | "danger"
360
-
361
- /** Percentage thresholds for the green/yellow/red usage colour. */
362
- export const WARN_AT = 50
363
- export const DANGER_AT = 80
364
-
365
- export function severity(percent: number): Severity {
366
- if (percent >= DANGER_AT) return "danger"
367
- if (percent >= WARN_AT) return "warn"
368
- return "ok"
369
- }
370
-
371
- /** True when the provider itself reports the window as not usable. */
372
- export function isWindowLimited(window: UsageWindow): boolean {
373
- return Boolean(window.status && window.status !== "ok")
374
- }
375
-
376
- /** Severity for a window, taking the provider-reported status into account. */
377
- export function windowSeverity(window: UsageWindow): Severity {
378
- if (isWindowLimited(window)) return "danger"
379
- return severity(window.percent)
380
- }
package/tui.ts DELETED
@@ -1,3 +0,0 @@
1
- // Discovery entrypoint: OpenCode looks for `tui.ts`/`tui.tsx` in a plugin
2
- // directory. This re-export keeps both names working.
3
- export { default } from "./tui.tsx"