opencode-usage-limits 0.2.1 → 0.3.1

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 CHANGED
@@ -6,6 +6,39 @@ All notable changes to `usage-limits` are documented here. The format is based o
6
6
 
7
7
  [简体中文](./CHANGELOG.md) · [English](./CHANGELOG.en.md)
8
8
 
9
+ ## 0.3.1 - 2026-10-26
10
+
11
+ ### Fixed
12
+
13
+ - **The panel broke once OpenCode v2.1 moved credentials**: v2 migrated login credentials from
14
+ `auth.json` to the `credential` table in `opencode.db`, but the plugin still read `auth.json`, so
15
+ selecting OpenCode Go always showed `API key not found`. Keys are now read through
16
+ `context.client.credential.list()`, with `auth.json` as a fallback only.
17
+ - **Prefer the host usage endpoint**: when the host exposes `GET /api/experimental/usage/limits`,
18
+ OpenCode Go uses that payload directly (no key at all); older releases fall back to the Zen endpoint.
19
+ - `preview.mjs` now reads credentials from `opencode.db` too, so the panel can be verified without the TUI.
20
+
21
+ ## 0.3.0 - 2026-10-13
22
+
23
+ ### Changed
24
+
25
+ - **OpenCode Go now shows percentages only.** The official allowances are **per model** ($15–$80, plus a
26
+ Go Plus tier), so the old flat `$12/$30/$60` no longer holds. Measurement also shows the percentage
27
+ cannot be turned into dollars: 84% monthly corresponded to $49.27 of actual 30-day spend, implying a
28
+ ~$59 allowance rather than $80. The `used / limit` row is therefore gone for Go.
29
+ - **New allowance reference line** at the bottom of the panel, showing the selected model and its
30
+ allowance (`deepseek-v4.1-flash $80/$160`) so you can tell how expensive the model is. The built-in
31
+ table covers the official **31 models**; unknown models show `—` and free models show `∞`. This line is
32
+ purely informational and takes no part in any calculation.
33
+ - The `limits` option is narrowed to a **ClinePass-only fallback** (used when the plan read fails);
34
+ OpenCode Go no longer accepts dollar budgets.
35
+ - **ClinePass is unchanged**: caps are still read live from `/users/me/plan` and `used / limit` stays accurate.
36
+
37
+ ### Fixed
38
+
39
+ - `formatUsd` threw `Cannot read properties of undefined` when a window had no limit; the amount text is
40
+ now computed safely instead of relying on a `<Show>` guard to prevent evaluation.
41
+
9
42
  ## 0.2.1 - 2026-10-06
10
43
 
11
44
  ### Docs
package/CHANGELOG.md CHANGED
@@ -4,6 +4,30 @@
4
4
 
5
5
  [简体中文](./CHANGELOG.md) · [English](./CHANGELOG.en.md)
6
6
 
7
+ ## 0.3.1 - 2026-10-26
8
+
9
+ ### 修复
10
+
11
+ - **OpenCode v2.1+ 凭据迁移导致面板失效**:v2 把登录凭据从 `auth.json` 迁移到 `opencode.db`
12
+ 的 `credential` 表,插件仍只读 `auth.json`,因此选中 OpenCode Go 时固定显示
13
+ `API key not found`。现在优先通过 `context.client.credential.list()` 读取,`auth.json` 仅作兜底。
14
+ - **优先使用宿主用量接口**:宿主提供 `GET /api/experimental/usage/limits` 时,OpenCode Go 直接使用
15
+ 该接口(无需密钥);旧版本自动回退到 Zen 用量接口。
16
+ - `preview.mjs` 同步支持从 `opencode.db` 读取凭据,便于在不启动 TUI 的情况下验证。
17
+
18
+ ## 0.3.0 - 2026-10-13
19
+
20
+ ### 变更
21
+
22
+ - **OpenCode Go 改为只显示百分比**。官方额度已改成**按模型区分**($15–$80,另有 Go Plus 档),原有的统一 `$12/$30/$60` 不再成立。实测进一步表明百分比**不能**换算成美元:月度 84% 对应的 30 天实际花费为 $49.27,反推额度约 $59 而非 $80。因此移除了 Go 窗口的 `已用 / 限额` 行。
23
+ - **新增模型额度参考行**(放在面板底部):显示当前模型与其额度,如 `deepseek-v4.1-flash $80/$160`,用于判断该模型是贵还是便宜。内置官方 **31 个模型**的额度表;未收录的模型显示 `—`,免费模型显示 `∞`。该行**仅作参考,不参与任何计算**。
24
+ - `limits` 配置项收窄为 **ClinePass 专用回退**(套餐上限读取失败时使用);OpenCode Go 不再接受美元额度配置。
25
+ - **ClinePass 行为不变**:额度仍从 `/users/me/plan` 实时读取,`已用 / 限额` 保持准确。
26
+
27
+ ### 修复
28
+
29
+ - 额度缺失时 `formatUsd` 会抛 `Cannot read properties of undefined`;金额文本改为安全求值(不再依赖 `<Show>` 守卫拦住求值)。
30
+
7
31
  ## 0.2.1 - 2026-10-06
8
32
 
9
33
  ### 文档
package/README.en.md CHANGED
@@ -33,19 +33,22 @@ Monthly 60%
33
33
  - **Two usage sources**: OpenCode Go and ClinePass, switched automatically by the current model.
34
34
  - **Three windows**: rolling 5 hours / weekly / monthly, with percentage, bar and reset countdown.
35
35
  - **Green / yellow / red**: < 50% green, 50–79% yellow, ≥ 80% red (thresholds live in `core.ts`).
36
- - **Spend display**: OpenCode Go shows `used / limit` ($12 / $30 / $60); ClinePass reads its caps live from `/users/me/plan`.
36
+ - **Spend display**: ClinePass shows `used / limit` (caps read live from `/users/me/plan`, $10 / $25 / $50);
37
+ OpenCode Go shows percentages only, with the selected model's allowance (e.g. `$80/$160`) noted at the bottom
38
+ as a reference.
37
39
  - **Collapsible**: click the title row to collapse to a single line; the state is persisted.
38
40
  - **Unobtrusive**: nothing is rendered for any other provider, so it never takes up space.
39
41
  - **Rate-limit backoff**: 429 / 5xx / network failures back off exponentially (capped at 5 minutes) and show `retry in Ns`.
40
42
  - **Stale-data warning**: once a reading is older than ~75 seconds (2.5 polling intervals) the title row
41
43
  shows its age in yellow; while the data is fresh nothing is shown, so there is no constant noise.
42
- - **Key safety**: the API key is read live from OpenCode's `auth.json`; the plugin stores nothing.
44
+ - **Key safety**: the API key is read live through OpenCode's credential API (v2 keeps credentials in
45
+ its database), with `auth.json` as a fallback; the plugin stores nothing.
43
46
 
44
47
  ## Supported sources
45
48
 
46
49
  | Provider ID | Name | Usage endpoint | Spend shown |
47
50
  | --- | --- | --- | --- |
48
- | `opencode-go` | [OpenCode Go](https://opencode.ai/docs/go) | `GET https://opencode.ai/zen/go/v1/usage` | Yes ($12 / $30 / $60) |
51
+ | `opencode-go` | [OpenCode Go](https://opencode.ai/zh/go) | `GET https://opencode.ai/zen/go/v1/usage` | No (percentages only; the model's allowance is noted at the bottom) |
49
52
  | `cline-pass` | [ClinePass](https://docs.cline.bot/getting-started/clinepass) | `GET https://api.cline.bot/api/v1/users/me/plan/usage-limits` | Yes (plan caps read live from `/users/me/plan`) |
50
53
 
51
54
  > Cline's public documentation is at [Cline API](https://docs.cline.bot/api/overview).
@@ -84,8 +87,8 @@ opencode plugin add github:GamingNowEdward/opencode-usage-limits
84
87
  }
85
88
  ```
86
89
 
87
- CLI plugins run inside the local TUI process, so they can read `auth.json` and reach the network
88
- directly, and they stay active even when the CLI is connected to a remote server. See the
90
+ CLI plugins run inside the local TUI process, so they can call OpenCode's credential API and reach
91
+ the network directly, and they stay active even when the CLI is connected to a remote server. See the
89
92
  [CLI plugin documentation](https://opencode.ai/v2/docs/build/plugins/cli).
90
93
 
91
94
  ## Usage
@@ -99,7 +102,7 @@ directly, and they stay active even when the CLI is connected to a remote server
99
102
  | Option | Type | Default | Description |
100
103
  | --- | --- | --- | --- |
101
104
  | `refreshMs` | number | `30000` | Polling interval in milliseconds |
102
- | `limits` | object | — | Overrides the built-in budgets, e.g. `{ "opencode-go": { "monthly": 100 } }` |
105
+ | `limits` | object | — | ClinePass fallback only, used when the plan read fails, e.g. `{ "cline-pass": { "hour5": 10, "weekly": 25, "monthly": 50 } }` |
103
106
 
104
107
  Thresholds and colours live in the source: `WARN_AT` / `DANGER_AT` in `core.ts`, `readPalette` in `tui.tsx`.
105
108
 
@@ -109,10 +112,16 @@ In `setup()` the plugin does three things:
109
112
 
110
113
  1. **Registers a sidebar slot**: `context.ui.slot({ prepend: "sidebar.content", ... })`.
111
114
  2. **Reads the current model**: `context.ui.model.current()?.providerID` (reactive).
112
- 3. **Fetches usage per provider**: resolves the key from `auth.json`, calls the usage endpoint with
113
- `Authorization: Bearer`, polls every 30 seconds and ticks the countdown every second.
115
+ 3. **Fetches usage per provider**: resolves the key through `context.client.credential.list()`
116
+ (OpenCode v2's authoritative store), calls the usage endpoint with `Authorization: Bearer`,
117
+ polls every 30 seconds and ticks the countdown every second.
114
118
 
115
- Key resolution order: the `<PROVIDER>_API_KEY` environment variable → `~/.local/share/opencode/auth.json`.
119
+ Key resolution order: the `<PROVIDER>_API_KEY` environment variable →
120
+ `context.client.credential.list()` → `~/.local/share/opencode/auth.json`. OpenCode v2 keeps login
121
+ credentials in the `credential` table of `opencode.db`; `auth.json` is the legacy path only.
122
+
123
+ When the host exposes `GET /api/experimental/usage/limits`, OpenCode Go uses that payload directly
124
+ and needs no key at all.
116
125
 
117
126
  ## File layout
118
127
 
@@ -140,6 +149,15 @@ node preview.mjs cline-pass # a single source
140
149
  1. Make sure the current model belongs to `opencode-go` or `cline-pass`.
141
150
  2. Plugin files **hot reload on save** — no restart needed. Only adding or removing an imported file requires restarting the TUI.
142
151
  3. Check the log: `~/.local/share/opencode/log/opencode.log`, filter by `role=cli` and `plugin`.
152
+ 4. If the panel shows **API key not found**, check the login first:
153
+
154
+ ```sh
155
+ opencode auth list
156
+ ```
157
+
158
+ When it says `stored` but the panel still fails, the host release is too old to expose the
159
+ credential API. As a workaround, set the `<PROVIDER>_API_KEY` environment variable (for example
160
+ `OPENCODE_GO_API_KEY`) and restart the TUI.
143
161
 
144
162
  ## See also
145
163
 
package/README.md CHANGED
@@ -33,18 +33,19 @@ Monthly 60%
33
33
  - **两个用量来源**:OpenCode Go、ClinePass,按当前模型自动切换。
34
34
  - **三个窗口**:5 小时滚动 / 周 / 月,含百分比、进度条、重置倒计时。
35
35
  - **绿黄红提醒**:< 50% 绿、50–79% 黄、≥ 80% 红(阈值见 `core.ts`)。
36
- - **金额显示**:OpenCode Go 显示 `已用 / 限额`($12 / $30 / $60);ClinePass 的限额从 `/users/me/plan` 实时读取。
36
+ - **金额显示**:ClinePass 显示 `已用 / 限额`(限额从 `/users/me/plan` 实时读取,$10 / $25 / $50);OpenCode Go 只显示百分比,并在**底部**标注当前模型的额度(如 `$80/$160`)供参考。
37
37
  - **整体折叠**:点标题行收起,只留一行;状态持久化,重启保持。
38
38
  - **不打扰**:选中其他 provider 时**完全不渲染**,不占空间。
39
39
  - **限流退避**:遇 429 / 5xx / 网络失败自动指数退避(最长 5 分钟),并显示 `retry in Ns`。
40
40
  - **数据过期提示**:数据变旧(超过约 75 秒,即 2.5 个轮询间隔)时,标题行才显示年龄并变黄;平时不显示,不产生噪音。
41
- - **密钥安全**:从 OpenCode 的 `auth.json` 实时读取,插件不存储任何凭据。
41
+ - **密钥安全**:通过 OpenCode 的凭据 API 实时读取(v2 把凭据存在自己的数据库中),
42
+ `auth.json` 仅作兜底;插件不存储任何凭据。
42
43
 
43
44
  ## 支持的数据源
44
45
 
45
46
  | Provider ID | 名称 | 用量接口 | 显示金额 |
46
47
  | --- | --- | --- | --- |
47
- | `opencode-go` | [OpenCode Go](https://opencode.ai/docs/go) | `GET https://opencode.ai/zen/go/v1/usage` | 是($12 / $30 / $60) |
48
+ | `opencode-go` | [OpenCode Go](https://opencode.ai/zh/go) | `GET https://opencode.ai/zen/go/v1/usage` | 否(只显示百分比;底部标注当前模型额度) |
48
49
  | `cline-pass` | [ClinePass](https://docs.cline.bot/getting-started/clinepass) | `GET https://api.cline.bot/api/v1/users/me/plan/usage-limits` | 是(从 `/users/me/plan` 实时读取套餐上限) |
49
50
 
50
51
  > Cline 的公开文档见 [Cline API](https://docs.cline.bot/api/overview)。
@@ -82,7 +83,7 @@ opencode plugin add github:GamingNowEdward/opencode-usage-limits
82
83
  }
83
84
  ```
84
85
 
85
- CLI 插件在本地 TUI 进程内运行,因此可以直接读取 `auth.json` 与访问网络;它也会在连接
86
+ CLI 插件在本地 TUI 进程内运行,因此可以调用 OpenCode 的凭据 API 与访问网络;它也会在连接
86
87
  远程 server 时保持可用。详见 [CLI 插件文档](https://opencode.ai/v2/docs/build/plugins/cli)。
87
88
 
88
89
  ## 使用
@@ -96,7 +97,7 @@ CLI 插件在本地 TUI 进程内运行,因此可以直接读取 `auth.json`
96
97
  | 选项 | 类型 | 默认 | 说明 |
97
98
  | --- | --- | --- | --- |
98
99
  | `refreshMs` | number | `30000` | 轮询间隔(毫秒) |
99
- | `limits` | object | — | 覆盖内置额度,如 `{ "opencode-go": { "monthly": 100 } }` |
100
+ | `limits` | object | — | 仅作 ClinePass 的回退:套餐上限读取失败时使用,如 `{ "cline-pass": { "hour5": 10, "weekly": 25, "monthly": 50 } }` |
100
101
 
101
102
  配色阈值写在源码中:`core.ts` 的 `WARN_AT` / `DANGER_AT`,`tui.tsx` 的 `readPalette`。
102
103
 
@@ -106,10 +107,15 @@ CLI 插件在本地 TUI 进程内运行,因此可以直接读取 `auth.json`
106
107
 
107
108
  1. **注册侧边栏 slot**:`context.ui.slot({ prepend: "sidebar.content", ... })`。
108
109
  2. **读取当前模型**:`context.ui.model.current()?.providerID`(响应式)。
109
- 3. **按 provider 拉取用量**:从 `auth.json` 取密钥,带 `Authorization: Bearer` 请求用量接口,
110
- 30 秒轮询一次,1 秒刷新倒计时。
110
+ 3. **按 provider 拉取用量**:通过 `context.client.credential.list()` 取密钥(OpenCode v2 的
111
+ 权威来源),带 `Authorization: Bearer` 请求用量接口,30 秒轮询一次,1 秒刷新倒计时。
111
112
 
112
- 密钥解析顺序:环境变量 `<PROVIDER>_API_KEY` → `~/.local/share/opencode/auth.json`。
113
+ 密钥解析顺序:环境变量 `<PROVIDER>_API_KEY` → `context.client.credential.list()` →
114
+ `~/.local/share/opencode/auth.json`。OpenCode v2 把登录凭据存在 `opencode.db` 的 `credential`
115
+ 表中,`auth.json` 只是旧版兼容路径。
116
+
117
+ 若宿主版本提供 `GET /api/experimental/usage/limits`,OpenCode Go 会直接使用该接口返回的用量,
118
+ 完全不需要密钥。
113
119
 
114
120
  ## 文件结构
115
121
 
@@ -137,6 +143,14 @@ node preview.mjs cline-pass # 只预览一个
137
143
  1. 确认当前模型属于 `opencode-go` 或 `cline-pass`。
138
144
  2. 插件文件**保存即热重载**,无需重启;只有新增/删除被 import 的文件时才需退出 TUI 重进。
139
145
  3. 查看日志:`~/.local/share/opencode/log/opencode.log`,筛 `role=cli` 与 `plugin`。
146
+ 4. 面板显示 **API key not found** 时,先确认登录状态:
147
+
148
+ ```sh
149
+ opencode auth list
150
+ ```
151
+
152
+ 若已显示 `stored` 但面板仍报错,说明宿主版本过旧,无法通过凭据 API 读取密钥;
153
+ 可临时设置环境变量 `<PROVIDER>_API_KEY`(如 `OPENCODE_GO_API_KEY`)后重启 TUI。
140
154
 
141
155
  ## 相关
142
156
 
package/core.ts CHANGED
@@ -36,7 +36,9 @@ export const PROVIDERS: Record<string, ProviderConfig> = {
36
36
  title: "OpenCode Go",
37
37
  baseUrl: "https://opencode.ai/zen/go/v1",
38
38
  path: "/usage",
39
- limits: { hour5: 12, weekly: 30, monthly: 60 },
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).
40
42
  },
41
43
  "cline-pass": {
42
44
  id: "cline-pass",
@@ -47,6 +49,57 @@ export const PROVIDERS: Record<string, ProviderConfig> = {
47
49
  },
48
50
  }
49
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
+
50
103
  const WINDOW_LABEL: Record<WindowKind, string> = {
51
104
  hour5: "5 hours",
52
105
  weekly: "Weekly",
@@ -79,7 +132,7 @@ function authPaths(): string[] {
79
132
  }
80
133
 
81
134
  /**
82
- * Pull an API key out of an auth-store entry. The store may hold a single
135
+ * Pull an API key out of a credential entry. An entry may hold a single
83
136
  * credential object, or an array of them when several accounts/connections
84
137
  * exist for one provider; in that case the first usable key wins.
85
138
  */
@@ -100,12 +153,47 @@ function extractKey(entry: any): string | undefined {
100
153
  return undefined
101
154
  }
102
155
 
103
- /** Resolve the provider API key from the env or OpenCode's auth store. */
104
- export async function resolveKey(providerID: string): Promise<string | undefined> {
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> {
105
183
  const envName = `${providerID.toUpperCase().replace(/-/g, "_")}_API_KEY`
106
184
  const fromEnv = process.env[envName]
107
185
  if (fromEnv) return fromEnv
108
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
+
109
197
  for (const path of authPaths()) {
110
198
  try {
111
199
  if (!existsSync(path)) continue
@@ -122,6 +210,9 @@ export async function resolveKey(providerID: string): Promise<string | undefined
122
210
  // ---- API fetching -------------------------------------------------------
123
211
 
124
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
125
216
  if (typeof value !== "string") return null
126
217
  const ms = new Date(value).getTime()
127
218
  return Number.isFinite(ms) ? ms : null
@@ -223,8 +314,11 @@ export function isTransient(error: unknown): boolean {
223
314
 
224
315
  /**
225
316
  * Fetch the three usage windows for a provider.
226
- * OpenCode Go reports percentages and we map them onto its $12/$30/$60 budgets.
227
- * ClinePass reports percentages only, so no dollar amount is shown.
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.
228
322
  */
229
323
  export async function fetchUsage(config: ProviderConfig, key: string, timeoutMs = 10000): Promise<UsageWindow[]> {
230
324
  const url = config.baseUrl.replace(/\/$/, "") + config.path
@@ -255,12 +349,43 @@ export async function fetchUsage(config: ProviderConfig, key: string, timeoutMs
255
349
  const src = sources[kind]
256
350
  if (!src) continue
257
351
  const status = typeof src.status === "string" ? src.status : undefined
258
- windows.push(buildWindow(kind, Number(src.percent) || 0, toMs(src.resetsAt), config.limits, status))
352
+ windows.push(buildWindow(kind, Number(src.percent) || 0, toMs(src.resetsAt), undefined, status))
259
353
  }
260
354
  if (windows.length === 0) throw new Error("usage API returned an unexpected shape")
261
355
  return windows
262
356
  }
263
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
+
264
389
  // ---- Formatting ---------------------------------------------------------
265
390
 
266
391
  const MINUTE = 60_000
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-usage-limits",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
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",
package/tui.tsx CHANGED
@@ -7,8 +7,11 @@ import {
7
7
  clampPercent,
8
8
  fetchUsage,
9
9
  formatUsd,
10
+ goWindowsFromLimits,
10
11
  isTransient,
11
12
  isWindowLimited,
13
+ keyFromCredentials,
14
+ modelAllowance,
12
15
  resetText,
13
16
  resolveKey,
14
17
  resolveProvider,
@@ -72,12 +75,18 @@ function ProgressBar(props: { percent: number; color: any; track: any }) {
72
75
  function WindowRow(props: { window: UsageWindow; palette: Palette; now: number }) {
73
76
  const pct = () => clampPercent(props.window.percent)
74
77
  const color = () => severityColor(props.palette, props.window)
75
- const used = () => usedUsd(props.window)
76
- const hasAmount = () => used() != null && props.window.limit != null
77
78
  const limited = () => isWindowLimited(props.window)
78
79
  // Memoised so the ticking clock only writes to the DOM when the rendered text
79
80
  // actually changes (Solid memos compare with ===).
80
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
+ })
81
90
 
82
91
  return (
83
92
  <box flexDirection="column" width="100%" marginTop={1}>
@@ -94,8 +103,8 @@ function WindowRow(props: { window: UsageWindow; palette: Palette; now: number }
94
103
  <box flexDirection="row" width="100%">
95
104
  <text fg={props.palette.muted}>{resetLabel()}</text>
96
105
  <box flexGrow={1} />
97
- <Show when={hasAmount()}>
98
- <text fg={props.palette.muted}>{`${formatUsd(used() as number)} / ${formatUsd(props.window.limit as number)}`}</text>
106
+ <Show when={amountText() !== ""}>
107
+ <text fg={props.palette.muted}>{amountText()}</text>
99
108
  </Show>
100
109
  </box>
101
110
  </box>
@@ -106,11 +115,22 @@ function UsagePanel(props: { context: any; panel: any; toggle: () => void }) {
106
115
  const ctx = props.context
107
116
  const palette = createMemo<Palette>(() => readPalette(ctx.theme))
108
117
  const providerID = createMemo<string | undefined>(() => ctx.ui.model.current()?.providerID)
118
+ const modelID = createMemo<string | undefined>(() => ctx.ui.model.current()?.modelID)
109
119
  const config = createMemo(() => {
110
120
  const id = providerID()
111
121
  return id ? resolveProvider(id, ctx.options) : undefined
112
122
  })
113
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
+
114
134
  const [windows, setWindows] = createSignal<UsageWindow[]>([])
115
135
  const [loading, setLoading] = createSignal(false)
116
136
  const [error, setError] = createSignal("")
@@ -121,6 +141,36 @@ function UsagePanel(props: { context: any; panel: any; toggle: () => void }) {
121
141
  const baseMs = Number(props.context?.options?.refreshMs) || REFRESH_MS
122
142
  let pollMs = baseMs
123
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
+
124
174
  // Guard per provider: if the user switches providers while a request is
125
175
  // still in flight, the new provider's request must fire immediately instead
126
176
  // of waiting for the next poll. Stale responses are dropped by the
@@ -132,14 +182,18 @@ function UsagePanel(props: { context: any; panel: any; toggle: () => void }) {
132
182
  inflight.add(cfg.id)
133
183
  setLoading(true)
134
184
  try {
135
- const key = await resolveKey(cfg.id)
136
- if (!key) {
137
- setWindows([])
138
- setError("API key not found")
139
- setNextRetryAt(undefined)
140
- return
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)
141
196
  }
142
- const next = await fetchUsage(cfg, key)
143
197
  if (config()?.id === cfg.id) {
144
198
  setWindows(next)
145
199
  setError("")
@@ -257,6 +311,14 @@ function UsagePanel(props: { context: any; panel: any; toggle: () => void }) {
257
311
  <text fg={palette().warn}>{`partial data · ${windows().length}/${WINDOW_COUNT} windows`}</text>
258
312
  </Show>
259
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>
260
322
  </Show>
261
323
  </box>
262
324
  )}