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/dist/tui.js ADDED
@@ -0,0 +1,822 @@
1
+ // tui.tsx
2
+ import { memo as _$memo } from "@opentui/solid";
3
+ import { createComponent as _$createComponent } from "@opentui/solid";
4
+ import { insert as _$insert } from "@opentui/solid";
5
+ import { effect as _$effect } from "@opentui/solid";
6
+ import { insertNode as _$insertNode } from "@opentui/solid";
7
+ import { setProp as _$setProp } from "@opentui/solid";
8
+ import { createElement as _$createElement } from "@opentui/solid";
9
+ import { Plugin } from "@opencode/plugin/tui";
10
+ import { Index, Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js";
11
+
12
+ // core.ts
13
+ import { readFile } from "node:fs/promises";
14
+ import { existsSync } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { join } from "node:path";
17
+ var PROVIDERS = {
18
+ "opencode-go": {
19
+ id: "opencode-go",
20
+ title: "OpenCode Go",
21
+ baseUrl: "https://opencode.ai/zen/go/v1",
22
+ path: "/usage"
23
+ // No dollar budgets: the usage API only reports percentages, and the
24
+ // per-model allowances on the pricing page are reference information shown
25
+ // separately (see GO_MODEL_ALLOWANCE).
26
+ },
27
+ "cline-pass": {
28
+ id: "cline-pass",
29
+ title: "ClinePass",
30
+ baseUrl: "https://api.cline.bot/api/v1",
31
+ path: "/users/me/plan/usage-limits",
32
+ planPath: "/users/me/plan"
33
+ }
34
+ };
35
+ var GO_MODEL_ALLOWANCE = {
36
+ "kimi-k3": {
37
+ go: 15,
38
+ plus: 60
39
+ },
40
+ "qwen3.8-max": {
41
+ go: 15,
42
+ plus: 60
43
+ },
44
+ "grok-4.7": {
45
+ go: 15,
46
+ plus: 60
47
+ },
48
+ "grok-4.6": {
49
+ go: 15,
50
+ plus: 60
51
+ },
52
+ "glm-5.3": {
53
+ go: 15,
54
+ plus: 120
55
+ },
56
+ "glm-5.2": {
57
+ go: 60,
58
+ plus: 180
59
+ },
60
+ "deepseek-v4-pro": {
61
+ go: 15,
62
+ plus: 60
63
+ },
64
+ "kimi-k2.7-code": {
65
+ go: 60,
66
+ plus: 180
67
+ },
68
+ "hy4-preview": {
69
+ go: 30,
70
+ plus: 120
71
+ },
72
+ "gpt-5.6-luna": {
73
+ go: 15,
74
+ plus: 60
75
+ },
76
+ "space-bunny": {
77
+ go: 30,
78
+ plus: 120
79
+ },
80
+ "minimax-m3": {
81
+ go: 60,
82
+ plus: 180
83
+ },
84
+ "mimo-v2.6-pro": {
85
+ go: 15,
86
+ plus: 60
87
+ },
88
+ "mimo-v2.5-pro": {
89
+ go: 15,
90
+ plus: 60
91
+ },
92
+ "minimax-m2.7": {
93
+ go: 60,
94
+ plus: 240
95
+ },
96
+ "claude-haiku-5-5": {
97
+ go: 15,
98
+ plus: 60
99
+ },
100
+ "gpt-6-luna": {
101
+ go: 15,
102
+ plus: 60
103
+ },
104
+ "qwen3.7-plus": {
105
+ go: 60,
106
+ plus: 180
107
+ },
108
+ hy3: {
109
+ go: 60,
110
+ plus: 240
111
+ },
112
+ "qwen3.8-flash": {
113
+ go: 30,
114
+ plus: 90
115
+ },
116
+ "glm-5.3-flash": {
117
+ go: 60,
118
+ plus: 180
119
+ },
120
+ "deepseek-v4-flash-vision-exp": {
121
+ go: 15,
122
+ plus: 60
123
+ },
124
+ "longcat-2.0": {
125
+ go: 60,
126
+ plus: 240
127
+ },
128
+ "deepseek-v4-flash": {
129
+ go: 30,
130
+ plus: 120
131
+ },
132
+ "mimo-v2.6-flash": {
133
+ go: 60,
134
+ plus: 120
135
+ },
136
+ "mimo-v2.5": {
137
+ go: 60,
138
+ plus: 120
139
+ },
140
+ "deepseek-v4.1-flash": {
141
+ go: 80,
142
+ plus: 160
143
+ },
144
+ "muse-spark-1.3-contributor": {
145
+ go: 60,
146
+ plus: 120
147
+ },
148
+ "muse-spark-1.2-contributor": {
149
+ go: 60,
150
+ plus: 120
151
+ },
152
+ "longcat-2.5-preview-free": "free",
153
+ "step-5-preview-free": "free"
154
+ };
155
+ function modelAllowance(modelID) {
156
+ if (!modelID) return void 0;
157
+ return GO_MODEL_ALLOWANCE[modelID];
158
+ }
159
+ var WINDOW_LABEL = {
160
+ hour5: "5 hours",
161
+ weekly: "Weekly",
162
+ monthly: "Monthly"
163
+ };
164
+ function resolveProvider(providerID, options) {
165
+ const base = PROVIDERS[providerID];
166
+ if (!base) return void 0;
167
+ const override = options?.limits?.[providerID];
168
+ if (!override) return base;
169
+ return {
170
+ ...base,
171
+ limits: {
172
+ ...base.limits ?? {},
173
+ ...override
174
+ }
175
+ };
176
+ }
177
+ var WINDOW_ORDER = ["hour5", "weekly", "monthly"];
178
+ var WINDOW_COUNT = WINDOW_ORDER.length;
179
+ function authPaths() {
180
+ const home = homedir();
181
+ const paths = [join(home, ".local", "share", "opencode", "auth.json")];
182
+ if (process.env.XDG_DATA_HOME) paths.push(join(process.env.XDG_DATA_HOME, "opencode", "auth.json"));
183
+ if (process.env.LOCALAPPDATA) paths.push(join(process.env.LOCALAPPDATA, "opencode", "auth.json"));
184
+ if (process.env.APPDATA) paths.push(join(process.env.APPDATA, "opencode", "auth.json"));
185
+ return paths;
186
+ }
187
+ function extractKey(entry) {
188
+ if (!entry) return void 0;
189
+ if (Array.isArray(entry)) {
190
+ for (const item of entry) {
191
+ const key = extractKey(item);
192
+ if (key) return key;
193
+ }
194
+ return void 0;
195
+ }
196
+ if (typeof entry !== "object") return void 0;
197
+ for (const field of ["key", "apiKey", "access", "token"]) {
198
+ const value = entry[field];
199
+ if (typeof value === "string" && value.length > 0) return value;
200
+ }
201
+ return void 0;
202
+ }
203
+ function keyFromCredentials(entries, providerID) {
204
+ const list = Array.isArray(entries) ? entries : Array.isArray(entries?.data) ? entries.data : [];
205
+ const matches = list.filter((entry) => entry?.integrationID === providerID);
206
+ const preferred = matches.find((entry) => entry?.active === true) ?? matches[0];
207
+ return extractKey(preferred?.value);
208
+ }
209
+ async function resolveKey(providerID, fromHost) {
210
+ const envName = `${providerID.toUpperCase().replace(/-/g, "_")}_API_KEY`;
211
+ const fromEnv = process.env[envName];
212
+ if (fromEnv) return fromEnv;
213
+ if (fromHost) {
214
+ try {
215
+ const key = await fromHost(providerID);
216
+ if (key) return key;
217
+ } catch {
218
+ }
219
+ }
220
+ for (const path of authPaths()) {
221
+ try {
222
+ if (!existsSync(path)) continue;
223
+ const store = JSON.parse(await readFile(path, "utf-8"));
224
+ const key = extractKey(store?.[providerID]);
225
+ if (key) return key;
226
+ } catch {
227
+ }
228
+ }
229
+ return void 0;
230
+ }
231
+ function toMs(value) {
232
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
233
+ if (typeof value !== "string") return null;
234
+ const ms = new Date(value).getTime();
235
+ return Number.isFinite(ms) ? ms : null;
236
+ }
237
+ function buildWindow(kind, percent, resetsAt, limits, status) {
238
+ return {
239
+ kind,
240
+ label: WINDOW_LABEL[kind],
241
+ percent,
242
+ limit: limits?.[kind],
243
+ resetsAt,
244
+ status
245
+ };
246
+ }
247
+ var CLINE_CAP_UNIT_USD = 1e-8;
248
+ var capCache = /* @__PURE__ */ new Map();
249
+ var CAP_TTL_MS = 6 * 60 * 60 * 1e3;
250
+ async function fetchPlanCaps(config, key, timeoutMs) {
251
+ if (!config.planPath) return void 0;
252
+ const hit = capCache.get(config.id);
253
+ if (hit && Date.now() - hit.at < CAP_TTL_MS) return hit.caps;
254
+ try {
255
+ const url = config.baseUrl.replace(/\/$/, "") + config.planPath;
256
+ const data = await readJson(url, key, timeoutMs);
257
+ const threshold = data?.data?.plan?.entitlements?.cline_pass?.inferenceCapThreshold;
258
+ if (!threshold) return void 0;
259
+ const caps = {
260
+ hour5: Number(threshold.last5HoursUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
261
+ weekly: Number(threshold.last7daysUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
262
+ monthly: Number(threshold.last30daysUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD
263
+ };
264
+ if (!Object.values(caps).every((n) => Number.isFinite(n) && n > 0)) return void 0;
265
+ capCache.set(config.id, {
266
+ at: Date.now(),
267
+ caps
268
+ });
269
+ return caps;
270
+ } catch {
271
+ return void 0;
272
+ }
273
+ }
274
+ function httpError(status, message) {
275
+ const error = new Error(message);
276
+ error.status = status;
277
+ return error;
278
+ }
279
+ async function readJson(url, key, timeoutMs) {
280
+ const controller = new AbortController();
281
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
282
+ try {
283
+ const res = await fetch(url, {
284
+ headers: {
285
+ Authorization: `Bearer ${key}`,
286
+ Accept: "application/json"
287
+ },
288
+ signal: controller.signal
289
+ });
290
+ if (res.status === 401 || res.status === 403) throw httpError(res.status, "API key rejected");
291
+ if (res.status === 429) throw httpError(429, "rate limited by the usage API");
292
+ if (!res.ok) throw httpError(res.status, `usage API ${res.status}`);
293
+ return await res.json();
294
+ } finally {
295
+ clearTimeout(timer);
296
+ }
297
+ }
298
+ function backoffFor(error, currentMs, baseMs, maxMs = 5 * 6e4) {
299
+ const status = Number(error?.status) || 0;
300
+ const transient = status === 0 || status === 429 || status >= 500 && status < 600;
301
+ if (!transient) return baseMs;
302
+ return Math.min(Math.max(currentMs, baseMs) * 2, maxMs);
303
+ }
304
+ function isTransient(error) {
305
+ const status = Number(error?.status) || 0;
306
+ return status === 0 || status === 429 || status >= 500 && status < 600;
307
+ }
308
+ async function fetchUsage(config, key, timeoutMs = 1e4) {
309
+ const url = config.baseUrl.replace(/\/$/, "") + config.path;
310
+ const data = await readJson(url, key, timeoutMs);
311
+ if (config.id === "cline-pass") {
312
+ const limits = Array.isArray(data?.data?.limits) ? data.data.limits : [];
313
+ const map = {
314
+ five_hour: "hour5",
315
+ weekly: "weekly",
316
+ monthly: "monthly"
317
+ };
318
+ const caps = await fetchPlanCaps(config, key, timeoutMs);
319
+ const windows2 = [];
320
+ for (const kind of WINDOW_ORDER) {
321
+ const hit = limits.find((l) => map[l?.type] === kind);
322
+ if (!hit) continue;
323
+ windows2.push(buildWindow(kind, Number(hit.percentUsed) || 0, toMs(hit.resetsAt), caps ?? config.limits));
324
+ }
325
+ if (windows2.length === 0) throw new Error("usage API returned an unexpected shape");
326
+ return windows2;
327
+ }
328
+ const usage = data?.usage;
329
+ const sources = {
330
+ hour5: usage?.rolling,
331
+ weekly: usage?.weekly,
332
+ monthly: usage?.monthly
333
+ };
334
+ const windows = [];
335
+ for (const kind of WINDOW_ORDER) {
336
+ const src = sources[kind];
337
+ if (!src) continue;
338
+ const status = typeof src.status === "string" ? src.status : void 0;
339
+ windows.push(buildWindow(kind, Number(src.percent) || 0, toMs(src.resetsAt), void 0, status));
340
+ }
341
+ if (windows.length === 0) throw new Error("usage API returned an unexpected shape");
342
+ return windows;
343
+ }
344
+ function goWindowsFromLimits(info) {
345
+ const go = info?.go ?? info?.data?.go;
346
+ if (!go) return void 0;
347
+ const meters = {
348
+ hour5: go.rolling,
349
+ weekly: go.weekly,
350
+ monthly: go.monthly
351
+ };
352
+ const windows = [];
353
+ for (const kind of WINDOW_ORDER) {
354
+ const meter = meters[kind];
355
+ if (!meter) continue;
356
+ windows.push(buildWindow(kind, Number(meter.percent) || 0, toMs(meter.resetsAt), void 0, meter.limited === true ? "limited" : "ok"));
357
+ }
358
+ return windows.length > 0 ? windows : void 0;
359
+ }
360
+ var MINUTE = 6e4;
361
+ var HOUR = 60 * MINUTE;
362
+ var DAY = 24 * HOUR;
363
+ function clampPercent(value) {
364
+ return Math.max(0, Math.min(100, Math.round(value)));
365
+ }
366
+ function formatUsd(value) {
367
+ return `$${value.toFixed(2)}`;
368
+ }
369
+ function usedUsd(window) {
370
+ if (window.limit == null) return void 0;
371
+ return window.percent / 100 * window.limit;
372
+ }
373
+ function rightAlign(value, width) {
374
+ return value.padStart(width);
375
+ }
376
+ function resetText(resetsAt, now) {
377
+ if (resetsAt == null) return "--";
378
+ const remaining = resetsAt - now;
379
+ if (remaining <= 0) return "now";
380
+ if (remaining < HOUR) return `${Math.max(1, Math.floor(remaining / MINUTE))}m`;
381
+ if (remaining < DAY) {
382
+ const h2 = Math.floor(remaining / HOUR);
383
+ const m = Math.floor(remaining % HOUR / MINUTE);
384
+ return m > 0 && h2 < 10 ? `${h2}h${m}m` : `${h2}h`;
385
+ }
386
+ const d = Math.floor(remaining / DAY);
387
+ const h = Math.floor(remaining % DAY / HOUR);
388
+ return h > 0 ? `${d}d ${h}h` : `${d}d`;
389
+ }
390
+ var WARN_AT = 50;
391
+ var DANGER_AT = 80;
392
+ function severity(percent) {
393
+ if (percent >= DANGER_AT) return "danger";
394
+ if (percent >= WARN_AT) return "warn";
395
+ return "ok";
396
+ }
397
+ function isWindowLimited(window) {
398
+ return Boolean(window.status && window.status !== "ok");
399
+ }
400
+ function windowSeverity(window) {
401
+ if (isWindowLimited(window)) return "danger";
402
+ return severity(window.percent);
403
+ }
404
+
405
+ // tui.tsx
406
+ var REFRESH_MS = 3e4;
407
+ var MAX_BACKOFF_MS = 5 * 6e4;
408
+ var STATUS_WIDTH = 4;
409
+ function readPalette(theme) {
410
+ const action = theme?.text?.action?.primary;
411
+ const base = theme?.text?.base;
412
+ return {
413
+ text: base,
414
+ muted: theme?.text?.muted,
415
+ accent: action?.base ?? base,
416
+ // Green / yellow / red usage states come from the theme's semantic feedback
417
+ // colours so they stay consistent with the active theme.
418
+ green: theme?.text?.feedback?.success?.base ?? "#3FB950",
419
+ warn: theme?.text?.feedback?.warning?.base ?? base,
420
+ danger: theme?.text?.feedback?.error?.base ?? base,
421
+ // Use the theme's border colour for the unfilled track: it is guaranteed to
422
+ // contrast with the sidebar panel background (raised.base is the panel
423
+ // colour itself, which made the track invisible).
424
+ track: theme?.border?.base ?? theme?.background?.raised?.base
425
+ };
426
+ }
427
+ function severityColor(palette, window) {
428
+ const level = windowSeverity(window);
429
+ if (level === "danger") return palette.danger;
430
+ if (level === "warn") return palette.warn;
431
+ return palette.green;
432
+ }
433
+ function ProgressBar(props) {
434
+ const pct = () => Math.max(0, Math.min(100, props.percent));
435
+ return (() => {
436
+ var _el$ = _$createElement("box"), _el$2 = _$createElement("box"), _el$3 = _$createElement("box");
437
+ _$insertNode(_el$, _el$2);
438
+ _$insertNode(_el$, _el$3);
439
+ _$setProp(_el$, "width", "100%");
440
+ _$setProp(_el$, "height", 1);
441
+ _$setProp(_el$, "flexDirection", "row");
442
+ _$effect((_p$) => {
443
+ var _v$ = Math.max(pct(), 0.01), _v$2 = props.color, _v$3 = Math.max(100 - pct(), 0.01), _v$4 = props.track;
444
+ _v$ !== _p$.e && (_p$.e = _$setProp(_el$2, "flexGrow", _v$, _p$.e));
445
+ _v$2 !== _p$.t && (_p$.t = _$setProp(_el$2, "backgroundColor", _v$2, _p$.t));
446
+ _v$3 !== _p$.a && (_p$.a = _$setProp(_el$3, "flexGrow", _v$3, _p$.a));
447
+ _v$4 !== _p$.o && (_p$.o = _$setProp(_el$3, "backgroundColor", _v$4, _p$.o));
448
+ return _p$;
449
+ }, {
450
+ e: void 0,
451
+ t: void 0,
452
+ a: void 0,
453
+ o: void 0
454
+ });
455
+ return _el$;
456
+ })();
457
+ }
458
+ function WindowRow(props) {
459
+ const pct = () => clampPercent(props.window.percent);
460
+ const color = () => severityColor(props.palette, props.window);
461
+ const limited = () => isWindowLimited(props.window);
462
+ const resetLabel = createMemo(() => `\u21BB ${resetText(props.window.resetsAt, props.now)}`);
463
+ const amountText = createMemo(() => {
464
+ const used = usedUsd(props.window);
465
+ if (used == null || props.window.limit == null) return "";
466
+ return `${formatUsd(used)} / ${formatUsd(props.window.limit)}`;
467
+ });
468
+ return (() => {
469
+ var _el$4 = _$createElement("box"), _el$5 = _$createElement("box"), _el$6 = _$createElement("box"), _el$7 = _$createElement("text"), _el$9 = _$createElement("text"), _el$0 = _$createElement("box"), _el$1 = _$createElement("text"), _el$10 = _$createElement("box");
470
+ _$insertNode(_el$4, _el$5);
471
+ _$insertNode(_el$4, _el$0);
472
+ _$setProp(_el$4, "flexDirection", "column");
473
+ _$setProp(_el$4, "width", "100%");
474
+ _$setProp(_el$4, "marginTop", 1);
475
+ _$insertNode(_el$5, _el$6);
476
+ _$insertNode(_el$5, _el$9);
477
+ _$setProp(_el$5, "flexDirection", "row");
478
+ _$setProp(_el$5, "width", "100%");
479
+ _$insertNode(_el$6, _el$7);
480
+ _$setProp(_el$6, "flexGrow", 1);
481
+ _$setProp(_el$6, "flexDirection", "row");
482
+ _$insert(_el$7, () => props.window.label);
483
+ _$insert(_el$6, _$createComponent(Show, {
484
+ get when() {
485
+ return limited();
486
+ },
487
+ get children() {
488
+ var _el$8 = _$createElement("text");
489
+ _$insert(_el$8, () => ` ${props.window.status}`);
490
+ _$effect((_$p) => _$setProp(_el$8, "fg", color(), _$p));
491
+ return _el$8;
492
+ }
493
+ }), null);
494
+ _$insert(_el$9, () => rightAlign(`${pct()}%`, 5));
495
+ _$insert(_el$4, _$createComponent(ProgressBar, {
496
+ get percent() {
497
+ return props.window.percent;
498
+ },
499
+ get color() {
500
+ return color();
501
+ },
502
+ get track() {
503
+ return props.palette.track;
504
+ }
505
+ }), _el$0);
506
+ _$insertNode(_el$0, _el$1);
507
+ _$insertNode(_el$0, _el$10);
508
+ _$setProp(_el$0, "flexDirection", "row");
509
+ _$setProp(_el$0, "width", "100%");
510
+ _$insert(_el$1, resetLabel);
511
+ _$setProp(_el$10, "flexGrow", 1);
512
+ _$insert(_el$0, _$createComponent(Show, {
513
+ get when() {
514
+ return amountText() !== "";
515
+ },
516
+ get children() {
517
+ var _el$11 = _$createElement("text");
518
+ _$insert(_el$11, amountText);
519
+ _$effect((_$p) => _$setProp(_el$11, "fg", props.palette.muted, _$p));
520
+ return _el$11;
521
+ }
522
+ }), null);
523
+ _$effect((_p$) => {
524
+ var _v$5 = color(), _v$6 = color(), _v$7 = props.palette.muted;
525
+ _v$5 !== _p$.e && (_p$.e = _$setProp(_el$7, "fg", _v$5, _p$.e));
526
+ _v$6 !== _p$.t && (_p$.t = _$setProp(_el$9, "fg", _v$6, _p$.t));
527
+ _v$7 !== _p$.a && (_p$.a = _$setProp(_el$1, "fg", _v$7, _p$.a));
528
+ return _p$;
529
+ }, {
530
+ e: void 0,
531
+ t: void 0,
532
+ a: void 0
533
+ });
534
+ return _el$4;
535
+ })();
536
+ }
537
+ function UsagePanel(props) {
538
+ const ctx = props.context;
539
+ const palette = createMemo(() => readPalette(ctx.theme));
540
+ const providerID = createMemo(() => ctx.ui.model.current()?.providerID);
541
+ const modelID = createMemo(() => ctx.ui.model.current()?.modelID);
542
+ const config = createMemo(() => {
543
+ const id = providerID();
544
+ return id ? resolveProvider(id, ctx.options) : void 0;
545
+ });
546
+ const allowanceText = createMemo(() => {
547
+ if (providerID() !== "opencode-go") return "";
548
+ const allowance = modelAllowance(modelID());
549
+ if (allowance === "free") return "\u221E";
550
+ if (!allowance) return "\u2014";
551
+ return `$${allowance.go}/$${allowance.plus}`;
552
+ });
553
+ const [windows, setWindows] = createSignal([]);
554
+ const [loading, setLoading] = createSignal(false);
555
+ const [error, setError] = createSignal("");
556
+ const [now, setNow] = createSignal(Date.now());
557
+ const [lastOkAt, setLastOkAt] = createSignal(void 0);
558
+ const [nextRetryAt, setNextRetryAt] = createSignal(void 0);
559
+ const baseMs = Number(props.context?.options?.refreshMs) || REFRESH_MS;
560
+ let pollMs = baseMs;
561
+ let credentialCache;
562
+ const readCredentials = async () => {
563
+ const client = ctx.client;
564
+ if (typeof client?.credential?.list !== "function") return void 0;
565
+ if (credentialCache && Date.now() - credentialCache.at < 6e4) return credentialCache.entries;
566
+ const entries = await client.credential.list();
567
+ credentialCache = {
568
+ at: Date.now(),
569
+ entries
570
+ };
571
+ return entries;
572
+ };
573
+ const keyFromHost = async (id) => keyFromCredentials(await readCredentials(), id);
574
+ const goFromHost = async () => {
575
+ const client = ctx.client;
576
+ const limits = client?.experimental?.usage?.limits;
577
+ if (typeof limits !== "function") return void 0;
578
+ try {
579
+ const location = ctx.location ?? ctx.data?.location?.default?.();
580
+ const result = await limits.call(client.experimental.usage, location ? {
581
+ location
582
+ } : void 0);
583
+ return goWindowsFromLimits(result);
584
+ } catch {
585
+ return void 0;
586
+ }
587
+ };
588
+ const inflight = /* @__PURE__ */ new Set();
589
+ const refresh = async () => {
590
+ const cfg = config();
591
+ if (!cfg || inflight.has(cfg.id)) return;
592
+ inflight.add(cfg.id);
593
+ setLoading(true);
594
+ try {
595
+ let next = cfg.id === "opencode-go" ? await goFromHost() : void 0;
596
+ if (!next) {
597
+ const key = await resolveKey(cfg.id, keyFromHost);
598
+ if (!key) {
599
+ setWindows([]);
600
+ setError("API key not found");
601
+ setNextRetryAt(void 0);
602
+ pollMs = baseMs;
603
+ return;
604
+ }
605
+ next = await fetchUsage(cfg, key);
606
+ }
607
+ if (config()?.id === cfg.id) {
608
+ setWindows(next);
609
+ setError("");
610
+ setLastOkAt(Date.now());
611
+ setNextRetryAt(void 0);
612
+ }
613
+ pollMs = baseMs;
614
+ } catch (err) {
615
+ const message = err?.message ?? "usage API unavailable";
616
+ if (isTransient(err)) {
617
+ pollMs = backoffFor(err, pollMs, baseMs, MAX_BACKOFF_MS);
618
+ setNextRetryAt(Date.now() + pollMs);
619
+ } else {
620
+ pollMs = baseMs;
621
+ setNextRetryAt(void 0);
622
+ }
623
+ setError(message);
624
+ } finally {
625
+ inflight.delete(cfg.id);
626
+ setLoading(inflight.size > 0);
627
+ }
628
+ };
629
+ let pollTimer;
630
+ let tickTimer;
631
+ onMount(() => {
632
+ let cancelled = false;
633
+ const loop = async () => {
634
+ if (cancelled) return;
635
+ await refresh();
636
+ if (cancelled) return;
637
+ pollTimer = setTimeout(loop, pollMs);
638
+ };
639
+ pollTimer = setTimeout(loop, baseMs);
640
+ const scheduleTick = () => {
641
+ const delay = nextRetryAt() !== void 0 ? 1e3 : 6e4 - Date.now() % 6e4;
642
+ tickTimer = setTimeout(() => {
643
+ if (cancelled) return;
644
+ setNow(Date.now());
645
+ scheduleTick();
646
+ }, delay);
647
+ };
648
+ scheduleTick();
649
+ onCleanup(() => {
650
+ cancelled = true;
651
+ clearTimeout(pollTimer);
652
+ clearTimeout(tickTimer);
653
+ });
654
+ });
655
+ createEffect(() => {
656
+ const cfg = config();
657
+ setWindows([]);
658
+ setError("");
659
+ setNextRetryAt(void 0);
660
+ pollMs = baseMs;
661
+ if (cfg) {
662
+ setLastOkAt(void 0);
663
+ void refresh();
664
+ }
665
+ });
666
+ const ageSeconds = () => {
667
+ const at = lastOkAt();
668
+ if (!at) return void 0;
669
+ return Math.max(0, Math.floor((now() - at) / 1e3));
670
+ };
671
+ const isStale = createMemo(() => {
672
+ const s = ageSeconds();
673
+ return s !== void 0 && s * 1e3 > baseMs * 2.5;
674
+ });
675
+ const ageText = createMemo(() => {
676
+ const s = ageSeconds();
677
+ if (s === void 0) return "";
678
+ if (s < 60) return "now";
679
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
680
+ return `${Math.floor(s / 3600)}h`;
681
+ });
682
+ const statusText = createMemo(() => rightAlign(loading() ? "\u22EF" : isStale() ? ageText() : "", STATUS_WIDTH));
683
+ const retryText = createMemo(() => {
684
+ const at = nextRetryAt();
685
+ if (at === void 0) return "";
686
+ return ` \xB7 retry in ${Math.max(0, Math.ceil((at - now()) / 1e3))}s`;
687
+ });
688
+ return _$createComponent(Show, {
689
+ get when() {
690
+ return config();
691
+ },
692
+ children: (cfg) => (() => {
693
+ var _el$12 = _$createElement("box"), _el$13 = _$createElement("box"), _el$14 = _$createElement("box"), _el$15 = _$createElement("text"), _el$16 = _$createElement("text");
694
+ _$insertNode(_el$12, _el$13);
695
+ _$setProp(_el$12, "flexDirection", "column");
696
+ _$setProp(_el$12, "width", "100%");
697
+ _$setProp(_el$12, "marginTop", 1);
698
+ _$insertNode(_el$13, _el$14);
699
+ _$insertNode(_el$13, _el$16);
700
+ _$setProp(_el$13, "flexDirection", "row");
701
+ _$setProp(_el$13, "width", "100%");
702
+ _$setProp(_el$13, "onMouseUp", () => props.toggle());
703
+ _$insertNode(_el$14, _el$15);
704
+ _$setProp(_el$14, "flexGrow", 1);
705
+ _$insert(_el$15, () => `${props.panel.collapsed ? "\u25B8" : "\u25BE"} USAGE \xB7 ${cfg().title}`);
706
+ _$insert(_el$16, statusText);
707
+ _$insert(_el$12, _$createComponent(Show, {
708
+ get when() {
709
+ return !props.panel.collapsed;
710
+ },
711
+ get children() {
712
+ return [_$createComponent(Show, {
713
+ get when() {
714
+ return error();
715
+ },
716
+ get children() {
717
+ var _el$17 = _$createElement("text");
718
+ _$insert(_el$17, () => `${error()}${retryText()}`);
719
+ _$effect((_$p) => _$setProp(_el$17, "fg", palette().danger, _$p));
720
+ return _el$17;
721
+ }
722
+ }), _$createComponent(Show, {
723
+ get when() {
724
+ return _$memo(() => windows().length > 0)() && windows().length < WINDOW_COUNT;
725
+ },
726
+ get children() {
727
+ var _el$18 = _$createElement("text");
728
+ _$insert(_el$18, () => `partial data \xB7 ${windows().length}/${WINDOW_COUNT} windows`);
729
+ _$effect((_$p) => _$setProp(_el$18, "fg", palette().warn, _$p));
730
+ return _el$18;
731
+ }
732
+ }), _$createComponent(Index, {
733
+ get each() {
734
+ return windows();
735
+ },
736
+ children: (w) => _$createComponent(WindowRow, {
737
+ get window() {
738
+ return w();
739
+ },
740
+ get palette() {
741
+ return palette();
742
+ },
743
+ get now() {
744
+ return now();
745
+ }
746
+ })
747
+ }), _$createComponent(Show, {
748
+ get when() {
749
+ return allowanceText() !== "";
750
+ },
751
+ get children() {
752
+ var _el$19 = _$createElement("box"), _el$20 = _$createElement("box"), _el$21 = _$createElement("text"), _el$22 = _$createElement("text");
753
+ _$insertNode(_el$19, _el$20);
754
+ _$insertNode(_el$19, _el$22);
755
+ _$setProp(_el$19, "flexDirection", "row");
756
+ _$setProp(_el$19, "width", "100%");
757
+ _$setProp(_el$19, "marginTop", 1);
758
+ _$insertNode(_el$20, _el$21);
759
+ _$setProp(_el$20, "flexGrow", 1);
760
+ _$insert(_el$21, () => modelID() ?? "");
761
+ _$insert(_el$22, allowanceText);
762
+ _$effect((_p$) => {
763
+ var _v$8 = palette().text, _v$9 = palette().text;
764
+ _v$8 !== _p$.e && (_p$.e = _$setProp(_el$21, "fg", _v$8, _p$.e));
765
+ _v$9 !== _p$.t && (_p$.t = _$setProp(_el$22, "fg", _v$9, _p$.t));
766
+ return _p$;
767
+ }, {
768
+ e: void 0,
769
+ t: void 0
770
+ });
771
+ return _el$19;
772
+ }
773
+ })];
774
+ }
775
+ }), null);
776
+ _$effect((_p$) => {
777
+ var _v$0 = palette().text, _v$1 = isStale() && !loading() ? palette().warn : palette().muted;
778
+ _v$0 !== _p$.e && (_p$.e = _$setProp(_el$15, "fg", _v$0, _p$.e));
779
+ _v$1 !== _p$.t && (_p$.t = _$setProp(_el$16, "fg", _v$1, _p$.t));
780
+ return _p$;
781
+ }, {
782
+ e: void 0,
783
+ t: void 0
784
+ });
785
+ return _el$12;
786
+ })()
787
+ });
788
+ }
789
+ var tui_default = Plugin.define({
790
+ id: "usage-limits",
791
+ setup(context) {
792
+ const [panel, updatePanel] = context.storage.store("usage-limits.panel", {
793
+ initial: {
794
+ collapsed: false
795
+ }
796
+ });
797
+ const toggle = () => void updatePanel((draft) => {
798
+ draft.collapsed = !draft.collapsed;
799
+ });
800
+ context.keymap.layer(() => ({
801
+ mode: "global",
802
+ commands: [{
803
+ id: "usage-limits.toggle",
804
+ title: "Toggle usage panel",
805
+ group: "Usage Limits",
806
+ palette: true,
807
+ run: toggle
808
+ }]
809
+ }));
810
+ return context.ui.slot({
811
+ prepend: "sidebar.content",
812
+ render: () => _$createComponent(UsagePanel, {
813
+ context,
814
+ panel,
815
+ toggle
816
+ })
817
+ });
818
+ }
819
+ });
820
+ export {
821
+ tui_default as default
822
+ };