opencode-usage-limits 0.3.1 → 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/CHANGELOG.en.md +28 -0
- package/CHANGELOG.md +24 -0
- package/README.en.md +20 -6
- package/README.md +18 -6
- package/dist/tui.js +822 -0
- package/package.json +24 -9
- package/core.ts +0 -449
- package/tui.ts +0 -3
- package/tui.tsx +0 -355
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-usage-limits",
|
|
3
|
-
"version": "0.3.
|
|
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.
|
|
29
|
+
"./tui": "./dist/tui.js"
|
|
30
30
|
},
|
|
31
31
|
"files": [
|
|
32
32
|
"index.ts",
|
|
33
|
-
"tui.
|
|
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": {
|
|
50
|
-
|
|
51
|
-
|
|
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,449 +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 a credential entry. An entry 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
|
-
/**
|
|
157
|
-
* Pick the credential belonging to `providerID` out of the list returned by
|
|
158
|
-
* OpenCode's `credential.list()` API. OpenCode v2 stores credentials in its
|
|
159
|
-
* database rather than in `auth.json`, so this is the authoritative source.
|
|
160
|
-
* The active credential wins; otherwise the first match is used.
|
|
161
|
-
*/
|
|
162
|
-
export function keyFromCredentials(entries: unknown, providerID: string): string | undefined {
|
|
163
|
-
const list = Array.isArray(entries)
|
|
164
|
-
? entries
|
|
165
|
-
: Array.isArray((entries as any)?.data)
|
|
166
|
-
? (entries as any).data
|
|
167
|
-
: []
|
|
168
|
-
const matches = list.filter((entry: any) => entry?.integrationID === providerID)
|
|
169
|
-
const preferred = matches.find((entry: any) => entry?.active === true) ?? matches[0]
|
|
170
|
-
return extractKey(preferred?.value)
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/** Reads a provider key through the host's OpenCode client. */
|
|
174
|
-
export type KeyResolver = (providerID: string) => Promise<string | undefined>
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Resolve the provider API key from the env, the host credential store, or
|
|
178
|
-
* `auth.json`. The host store comes first because OpenCode v2 keeps credentials
|
|
179
|
-
* in its database; `auth.json` remains as a fallback for older installs and for
|
|
180
|
-
* the offline preview script.
|
|
181
|
-
*/
|
|
182
|
-
export async function resolveKey(providerID: string, fromHost?: KeyResolver): Promise<string | undefined> {
|
|
183
|
-
const envName = `${providerID.toUpperCase().replace(/-/g, "_")}_API_KEY`
|
|
184
|
-
const fromEnv = process.env[envName]
|
|
185
|
-
if (fromEnv) return fromEnv
|
|
186
|
-
|
|
187
|
-
if (fromHost) {
|
|
188
|
-
try {
|
|
189
|
-
const key = await fromHost(providerID)
|
|
190
|
-
if (key) return key
|
|
191
|
-
} catch {
|
|
192
|
-
// Host credential API unavailable (older OpenCode, remote server): fall
|
|
193
|
-
// through to the legacy auth store.
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
for (const path of authPaths()) {
|
|
198
|
-
try {
|
|
199
|
-
if (!existsSync(path)) continue
|
|
200
|
-
const store = JSON.parse(await readFile(path, "utf-8"))
|
|
201
|
-
const key = extractKey(store?.[providerID])
|
|
202
|
-
if (key) return key
|
|
203
|
-
} catch {
|
|
204
|
-
// try the next candidate path
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
return undefined
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// ---- API fetching -------------------------------------------------------
|
|
211
|
-
|
|
212
|
-
function toMs(value: unknown): number | null {
|
|
213
|
-
// Provider endpoints return ISO strings; OpenCode's own usage API returns
|
|
214
|
-
// epoch milliseconds.
|
|
215
|
-
if (typeof value === "number") return Number.isFinite(value) ? value : null
|
|
216
|
-
if (typeof value !== "string") return null
|
|
217
|
-
const ms = new Date(value).getTime()
|
|
218
|
-
return Number.isFinite(ms) ? ms : null
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
function buildWindow(
|
|
222
|
-
kind: WindowKind,
|
|
223
|
-
percent: number,
|
|
224
|
-
resetsAt: number | null,
|
|
225
|
-
limits?: Record<WindowKind, number>,
|
|
226
|
-
status?: string,
|
|
227
|
-
): UsageWindow {
|
|
228
|
-
return { kind, label: WINDOW_LABEL[kind], percent, limit: limits?.[kind], resetsAt, status }
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* ClinePass reports plan caps as fixed-point integers. Calibrated against the
|
|
233
|
-
* live API: the sum of `costUsd` over a rolling window matches
|
|
234
|
-
* `percent x cap` in the same unit, and a single ~144k-token request costs
|
|
235
|
-
* ~82,000 units. 1 unit = 1e-8 USD, i.e. $10 / $25 / $50 for 5h / weekly / monthly.
|
|
236
|
-
*/
|
|
237
|
-
export const CLINE_CAP_UNIT_USD = 1e-8
|
|
238
|
-
|
|
239
|
-
const capCache = new Map<string, { at: number; caps: Record<WindowKind, number> }>()
|
|
240
|
-
const CAP_TTL_MS = 6 * 60 * 60 * 1000
|
|
241
|
-
|
|
242
|
-
/**
|
|
243
|
-
* Read the plan's per-window USD caps. Caps change rarely, so they are cached.
|
|
244
|
-
* Caps are a nice-to-have: any failure returns undefined and never fails the
|
|
245
|
-
* usage fetch itself.
|
|
246
|
-
*/
|
|
247
|
-
async function fetchPlanCaps(
|
|
248
|
-
config: ProviderConfig,
|
|
249
|
-
key: string,
|
|
250
|
-
timeoutMs: number,
|
|
251
|
-
): Promise<Record<WindowKind, number> | undefined> {
|
|
252
|
-
if (!config.planPath) return undefined
|
|
253
|
-
const hit = capCache.get(config.id)
|
|
254
|
-
if (hit && Date.now() - hit.at < CAP_TTL_MS) return hit.caps
|
|
255
|
-
try {
|
|
256
|
-
const url = config.baseUrl.replace(/\/$/, "") + config.planPath
|
|
257
|
-
const data = await readJson(url, key, timeoutMs)
|
|
258
|
-
const threshold = data?.data?.plan?.entitlements?.cline_pass?.inferenceCapThreshold
|
|
259
|
-
if (!threshold) return undefined
|
|
260
|
-
const caps: Record<WindowKind, number> = {
|
|
261
|
-
hour5: Number(threshold.last5HoursUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
|
|
262
|
-
weekly: Number(threshold.last7daysUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
|
|
263
|
-
monthly: Number(threshold.last30daysUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
|
|
264
|
-
}
|
|
265
|
-
if (!Object.values(caps).every((n) => Number.isFinite(n) && n > 0)) return undefined
|
|
266
|
-
capCache.set(config.id, { at: Date.now(), caps })
|
|
267
|
-
return caps
|
|
268
|
-
} catch {
|
|
269
|
-
return undefined
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/** HTTP failure carrying the status code so callers can decide on a backoff. */
|
|
274
|
-
function httpError(status: number, message: string): Error {
|
|
275
|
-
const error = new Error(message)
|
|
276
|
-
;(error as any).status = status
|
|
277
|
-
return error
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
async function readJson(url: string, key: string, timeoutMs: number): Promise<any> {
|
|
281
|
-
const controller = new AbortController()
|
|
282
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
283
|
-
try {
|
|
284
|
-
const res = await fetch(url, {
|
|
285
|
-
headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
|
|
286
|
-
signal: controller.signal,
|
|
287
|
-
})
|
|
288
|
-
if (res.status === 401 || res.status === 403) throw httpError(res.status, "API key rejected")
|
|
289
|
-
if (res.status === 429) throw httpError(429, "rate limited by the usage API")
|
|
290
|
-
if (!res.ok) throw httpError(res.status, `usage API ${res.status}`)
|
|
291
|
-
return await res.json()
|
|
292
|
-
} finally {
|
|
293
|
-
clearTimeout(timer)
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
/**
|
|
298
|
-
* Whether a failure is worth retrying with a growing delay, and how long to
|
|
299
|
-
* wait. Rate limits and server errors back off; auth and shape errors do not.
|
|
300
|
-
*/
|
|
301
|
-
export function backoffFor(error: unknown, currentMs: number, baseMs: number, maxMs = 5 * 60_000): number {
|
|
302
|
-
const status = Number((error as any)?.status) || 0
|
|
303
|
-
// A 0 status means a network/abort failure, which is also transient.
|
|
304
|
-
const transient = status === 0 || status === 429 || (status >= 500 && status < 600)
|
|
305
|
-
if (!transient) return baseMs
|
|
306
|
-
return Math.min(Math.max(currentMs, baseMs) * 2, maxMs)
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
/** True when the error is transient (used to label the retry countdown). */
|
|
310
|
-
export function isTransient(error: unknown): boolean {
|
|
311
|
-
const status = Number((error as any)?.status) || 0
|
|
312
|
-
return status === 0 || status === 429 || (status >= 500 && status < 600)
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
/**
|
|
316
|
-
* Fetch the three usage windows for a provider.
|
|
317
|
-
*
|
|
318
|
-
* OpenCode Go reports percentages only; the per-model dollar allowances on the
|
|
319
|
-
* pricing page are reference information and are never converted into "spend".
|
|
320
|
-
* ClinePass reports percentages plus a plan document whose caps ARE real
|
|
321
|
-
* dollars, so its windows carry a limit and the panel can show used / limit.
|
|
322
|
-
*/
|
|
323
|
-
export async function fetchUsage(config: ProviderConfig, key: string, timeoutMs = 10000): Promise<UsageWindow[]> {
|
|
324
|
-
const url = config.baseUrl.replace(/\/$/, "") + config.path
|
|
325
|
-
const data = await readJson(url, key, timeoutMs)
|
|
326
|
-
|
|
327
|
-
if (config.id === "cline-pass") {
|
|
328
|
-
const limits: any[] = Array.isArray(data?.data?.limits) ? data.data.limits : []
|
|
329
|
-
const map: Record<string, WindowKind> = { five_hour: "hour5", weekly: "weekly", monthly: "monthly" }
|
|
330
|
-
const caps = await fetchPlanCaps(config, key, timeoutMs)
|
|
331
|
-
const windows: UsageWindow[] = []
|
|
332
|
-
for (const kind of WINDOW_ORDER) {
|
|
333
|
-
const hit = limits.find((l) => map[l?.type] === kind)
|
|
334
|
-
if (!hit) continue
|
|
335
|
-
windows.push(buildWindow(kind, Number(hit.percentUsed) || 0, toMs(hit.resetsAt), caps ?? config.limits))
|
|
336
|
-
}
|
|
337
|
-
if (windows.length === 0) throw new Error("usage API returned an unexpected shape")
|
|
338
|
-
return windows
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
const usage = data?.usage
|
|
342
|
-
const sources: Record<WindowKind, any> = {
|
|
343
|
-
hour5: usage?.rolling,
|
|
344
|
-
weekly: usage?.weekly,
|
|
345
|
-
monthly: usage?.monthly,
|
|
346
|
-
}
|
|
347
|
-
const windows: UsageWindow[] = []
|
|
348
|
-
for (const kind of WINDOW_ORDER) {
|
|
349
|
-
const src = sources[kind]
|
|
350
|
-
if (!src) continue
|
|
351
|
-
const status = typeof src.status === "string" ? src.status : undefined
|
|
352
|
-
windows.push(buildWindow(kind, Number(src.percent) || 0, toMs(src.resetsAt), undefined, status))
|
|
353
|
-
}
|
|
354
|
-
if (windows.length === 0) throw new Error("usage API returned an unexpected shape")
|
|
355
|
-
return windows
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
/**
|
|
359
|
-
* Map the OpenCode host's own usage payload (`GET /api/experimental/usage/limits`)
|
|
360
|
-
* onto the panel's windows. Newer OpenCode releases expose the Go meters there,
|
|
361
|
-
* which removes the need for a key entirely; older ones do not, so the caller
|
|
362
|
-
* falls back to the provider endpoint above.
|
|
363
|
-
*/
|
|
364
|
-
export function goWindowsFromLimits(info: any): UsageWindow[] | undefined {
|
|
365
|
-
const go = info?.go ?? info?.data?.go
|
|
366
|
-
if (!go) return undefined
|
|
367
|
-
const meters: Record<WindowKind, any> = {
|
|
368
|
-
hour5: go.rolling,
|
|
369
|
-
weekly: go.weekly,
|
|
370
|
-
monthly: go.monthly,
|
|
371
|
-
}
|
|
372
|
-
const windows: UsageWindow[] = []
|
|
373
|
-
for (const kind of WINDOW_ORDER) {
|
|
374
|
-
const meter = meters[kind]
|
|
375
|
-
if (!meter) continue
|
|
376
|
-
windows.push(
|
|
377
|
-
buildWindow(
|
|
378
|
-
kind,
|
|
379
|
-
Number(meter.percent) || 0,
|
|
380
|
-
toMs(meter.resetsAt),
|
|
381
|
-
undefined,
|
|
382
|
-
meter.limited === true ? "limited" : "ok",
|
|
383
|
-
),
|
|
384
|
-
)
|
|
385
|
-
}
|
|
386
|
-
return windows.length > 0 ? windows : undefined
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
// ---- Formatting ---------------------------------------------------------
|
|
390
|
-
|
|
391
|
-
const MINUTE = 60_000
|
|
392
|
-
const HOUR = 60 * MINUTE
|
|
393
|
-
const DAY = 24 * HOUR
|
|
394
|
-
|
|
395
|
-
export function clampPercent(value: number): number {
|
|
396
|
-
return Math.max(0, Math.min(100, Math.round(value)))
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
export function formatUsd(value: number): string {
|
|
400
|
-
return `$${value.toFixed(2)}`
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
export function usedUsd(window: UsageWindow): number | undefined {
|
|
404
|
-
if (window.limit == null) return undefined
|
|
405
|
-
return (window.percent / 100) * window.limit
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
export function rightAlign(value: string, width: number): string {
|
|
409
|
-
return value.padStart(width)
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
/** Compact countdown such as `1h12m`, `5d 4h`, `now`. */
|
|
413
|
-
export function resetText(resetsAt: number | null, now: number): string {
|
|
414
|
-
if (resetsAt == null) return "--"
|
|
415
|
-
const remaining = resetsAt - now
|
|
416
|
-
if (remaining <= 0) return "now"
|
|
417
|
-
if (remaining < HOUR) return `${Math.max(1, Math.floor(remaining / MINUTE))}m`
|
|
418
|
-
if (remaining < DAY) {
|
|
419
|
-
const h = Math.floor(remaining / HOUR)
|
|
420
|
-
const m = Math.floor((remaining % HOUR) / MINUTE)
|
|
421
|
-
return m > 0 && h < 10 ? `${h}h${m}m` : `${h}h`
|
|
422
|
-
}
|
|
423
|
-
const d = Math.floor(remaining / DAY)
|
|
424
|
-
const h = Math.floor((remaining % DAY) / HOUR)
|
|
425
|
-
return h > 0 ? `${d}d ${h}h` : `${d}d`
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
export type Severity = "ok" | "warn" | "danger"
|
|
429
|
-
|
|
430
|
-
/** Percentage thresholds for the green/yellow/red usage colour. */
|
|
431
|
-
export const WARN_AT = 50
|
|
432
|
-
export const DANGER_AT = 80
|
|
433
|
-
|
|
434
|
-
export function severity(percent: number): Severity {
|
|
435
|
-
if (percent >= DANGER_AT) return "danger"
|
|
436
|
-
if (percent >= WARN_AT) return "warn"
|
|
437
|
-
return "ok"
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
/** True when the provider itself reports the window as not usable. */
|
|
441
|
-
export function isWindowLimited(window: UsageWindow): boolean {
|
|
442
|
-
return Boolean(window.status && window.status !== "ok")
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
/** Severity for a window, taking the provider-reported status into account. */
|
|
446
|
-
export function windowSeverity(window: UsageWindow): Severity {
|
|
447
|
-
if (isWindowLimited(window)) return "danger"
|
|
448
|
-
return severity(window.percent)
|
|
449
|
-
}
|
package/tui.ts
DELETED