opencode-account-quota 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JoelChinoP
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ # opencode-account-quota
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/opencode-account-quota)](https://www.npmjs.com/package/opencode-account-quota) [![license](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
4
+
5
+ OpenCode plugin to check how much quota each connected account has left, get a notice when one runs low, and keep a route order of accounts. Open it with `/quota`.
6
+
7
+ ![Claude Code usage in the /quota modal](docs/claude.png)
8
+
9
+ > Status: 0.1.0. Tested with OpenCode 2.3.2, 2.4.1 and 2.4.2. ChatGPT and Claude Code readings are experimental and use unofficial endpoints that may change.
10
+
11
+ ## What it shows
12
+
13
+ | Account | Data | Default |
14
+ |---|---|---|
15
+ | DeepSeek | Balance per currency (official balance API) and a low-balance notice | On |
16
+ | ChatGPT (OpenAI OAuth) | 5 h and weekly usage of the Codex plan | Off: `experimentalCodexUsage` |
17
+ | Claude Code | 5 h and weekly usage of the single Claude Code profile (`claude -p /usage`) | Off: `experimentalClaudeUsage` |
18
+
19
+ `—` means no data, never zero usage. `●` marks the account in use.
20
+
21
+ The plugin does not switch accounts and does not touch credentials: logging in and changing accounts stay in OpenCode (`/connect`). Only your preferences (route order, notice thresholds) are saved; readings stay in memory. Opening the modal does not query any provider: press `r` to refresh the selected account or `a` for all of them.
22
+
23
+ ## Screenshots
24
+
25
+ | ChatGPT (experimental, stale data) | DeepSeek balance |
26
+ |---|---|
27
+ | ![ChatGPT usage marked Experimental and Stale](docs/chatgpt.png) | ![DeepSeek balance with low-balance notice](docs/deepseek.png) |
28
+
29
+ **Route order** — accounts by preference, with a preview of the next turn:
30
+
31
+ ![Route order with next-turn preview](docs/route-order.png)
32
+
33
+ Screenshots use sample accounts and values.
34
+
35
+ ## Keys
36
+
37
+ | Screen | Keys |
38
+ |---|---|
39
+ | Accounts | `r` Refresh · `a` Refresh all · `o` Route order · `m` Balance notice · `esc` Close |
40
+ | Route order | `a` Add account · `Enter` Edit (model, effort, account, move, remove) · `o` Options · `s` Save · `esc` Discard |
41
+
42
+ ## Install
43
+
44
+ ```sh
45
+ opencode plugin add opencode-account-quota
46
+ ```
47
+
48
+ Or add it to `opencode.json` / `opencode.jsonc` yourself, with options:
49
+
50
+ ```jsonc
51
+ {
52
+ "$schema": "https://opencode.ai/config.json",
53
+ "plugins": [
54
+ {
55
+ "package": "opencode-account-quota@^0.1.0",
56
+ "options": {
57
+ "experimentalCodexUsage": false,
58
+ "experimentalClaudeUsage": false,
59
+ // Seconds ChatGPT and Claude Code usage stays fresh: integer 1–3600, default 150.
60
+ "usageFreshnessSeconds": 150
61
+ }
62
+ }
63
+ ]
64
+ }
65
+ ```
66
+
67
+ OpenCode installs the package and reloads plugins on save; then run `/quota` (or `Account quota and routing` from `Ctrl+P`). A range such as `@^0.1.0` updates itself within it; a bare name stays on the installed version until `opencode plugin update`.
68
+
69
+ Without npm, from GitHub: `github:JoelChinoP/opencode-account-quota` (or `#v0.1.0` to pin a tag).
70
+
71
+ Claude Code usage runs the `claude` binary from `PATH`, or `OPENCODE_CLAUDE_PATH` if set.
72
+
73
+ ## Development
74
+
75
+ No dependencies are needed to run the tests:
76
+
77
+ ```sh
78
+ node --test
79
+ ```
80
+
81
+ ## License
82
+
83
+ [MIT](LICENSE)
package/claude.js ADDED
@@ -0,0 +1,351 @@
1
+ // Claude Code plan usage (E02; S25, S26). EXPERIMENTAL and off by default. The passive part: the server watches it only with
2
+ // the plugin option `experimentalClaudeUsage: true`. In OpenCode 2.4.1 the claude-agent adapter keeps the last
3
+ // `rate_limit_event` the Agent SDK sent during a step in that step's provider metadata, and the core copies the
4
+ // metadata under the provider's own key to `session.step.ended` as `native` ({ rateLimit }): opaque replay data of
5
+ // the provider, not an API. Nothing in the passive part reads the network, a token, a keychain, SQLite or a file of the Claude Code
6
+ // profile, nor sends a prompt or /usage: it only reads what the user's own turns already produced. The figures belong
7
+ // to the one Claude Code profile OpenCode uses (~/.claude), never to the alias of its connection: OpenCode does not
8
+ // verify which account that profile is signed in to, and the CLI can switch accounts without OpenCode knowing.
9
+ // The one exception is the manual reader at the end (createUsageReader): on an explicit `r` or `a`, it runs the official
10
+ // `claude` binary once with the prompt `/usage` and reads its structured `usage_report` (Agent SDK SDKUsageReport).
11
+ import { spawn } from "node:child_process"
12
+ import { accessSync, constants, mkdtempSync, rmSync, statSync } from "node:fs"
13
+ import { homedir, tmpdir } from "node:os"
14
+ import { delimiter, join, resolve } from "node:path"
15
+ import { isRecord, isRef } from "./inventory.js"
16
+ import { isNumber, isTime, validSample } from "./rules.js"
17
+
18
+ export const INTEGRATION = "claude-agent"
19
+ export const SOURCE = "claude-turns"
20
+ // The step end does not name its provider; the step start does (`model.providerID`), with the same message ID.
21
+ export const STEP_EVENTS = ["session.step.started", "session.step.ended"]
22
+
23
+ const HOUR = 3_600_000
24
+ // Plan windows by the SDK's `rateLimitType` (Agent SDK RateLimitInfo: five_hour, seven_day, seven_day_opus,
25
+ // seven_day_sonnet, overage). A model-family window has no exact model selection to bind to (the DTO scope is
26
+ // "general" or provider/model#variant, and access is never inferred from a model name) and overage is not a plan
27
+ // window: both are ignored, like any type not listed here.
28
+ const WINDOWS = new Map([["five_hour", { window: "5h", span: 5 * HOUR }], ["seven_day", { window: "weekly", span: 168 * HOUR }]])
29
+ const SKEW = 5_000
30
+ // The oldest step end used: an attribution bound, not a freshness. The checks below look at the inventory and the profile
31
+ // folder when the event is handled, so they vouch only for a step that just ended. It stays 5 min whatever
32
+ // `usageFreshnessSeconds` says (rules.js): a long freshness must not attribute hour-old steps to today's profile, and a
33
+ // short one must not drop a step delivered a little late (recorded, it shows its age, Stale if past the freshness).
34
+ const LATE = 5 * 60_000
35
+ const KEEP = 256
36
+
37
+ // `rate_limit_info` → one sample per window, or undefined. Documented (Agent SDK RateLimitInfo): `rateLimitType`,
38
+ // `utilization` (fraction 0–1 used) and `resetsAt` (Unix seconds). Observed in OpenCode 2.4.1's own recordings
39
+ // (Claude Code 2.1.301–2.1.326, SDK 0.3.301): `unifiedWindows[type]` = { utilization, resetsAt } and no top-level
40
+ // utilization. A window without a utilization has no figure (never 0). A utilization outside 0–1, a reset that is not
41
+ // a time after the observation and within the window's own span (plus an hour of clock skew), or two different values
42
+ // for one window drop that window.
43
+ export function parseRateLimit(info, observedAt) {
44
+ if (!isRecord(info) || !isTime(observedAt)) return undefined
45
+ const found = new Map()
46
+ const dropped = new Set()
47
+ const consider = (type, utilization, resetsAt) => {
48
+ const spec = WINDOWS.get(type)
49
+ if (!spec || utilization === undefined || utilization === null) return
50
+ const at = resetsAt === undefined || resetsAt === null ? undefined : isNumber(resetsAt) ? resetsAt * 1000 : NaN
51
+ const valid = isNumber(utilization) && utilization >= 0 && utilization <= 1 &&
52
+ (at === undefined || (isTime(at) && at > observedAt && at <= observedAt + spec.span + HOUR))
53
+ if (!valid) {
54
+ dropped.add(spec.window)
55
+ return
56
+ }
57
+ const sample = { window: spec.window, scope: "general", observedAt, used: Number((utilization * 100).toFixed(6)),
58
+ ...(at !== undefined ? { resetsAt: at } : {}) }
59
+ const prior = found.get(spec.window)
60
+ if (prior && (prior.used !== sample.used || prior.resetsAt !== sample.resetsAt)) dropped.add(spec.window)
61
+ found.set(spec.window, sample)
62
+ }
63
+ if (typeof info.rateLimitType === "string") consider(info.rateLimitType, info.utilization, info.resetsAt)
64
+ if (isRecord(info.unifiedWindows)) {
65
+ for (const [type, entry] of Object.entries(info.unifiedWindows)) if (isRecord(entry)) consider(type, entry.utilization, entry.resetsAt)
66
+ }
67
+ const samples = [...found.values()].filter((s) => !dropped.has(s.window))
68
+ return samples.length > 0 ? samples : undefined
69
+ }
70
+
71
+ // The folders Claude Code runs with for claude-agent, derived as OpenCode 2.4.1 does (claude/query-options.ts,
72
+ // `configDirs` and `withoutDefaultFolder`): the provider setting `configDir` (a path or a list; `~/` expanded, then
73
+ // resolved); without it, the folder Claude Code defaults to (CLAUDE_CONFIG_DIR, else ~/.claude).
74
+ export function profileDirs(configDir, { env = process.env, home = homedir() } = {}) {
75
+ const dirs = (Array.isArray(configDir) ? configDir : [configDir]).filter((item) => typeof item === "string")
76
+ .map((item) => resolve(item.startsWith("~/") ? join(home, item.slice(2)) : item))
77
+ if (dirs.length > 0) return dirs
78
+ const own = env?.CLAUDE_CONFIG_DIR
79
+ return [resolve(typeof own === "string" && own !== "" ? own : join(home, ".claude"))]
80
+ }
81
+
82
+ // The one profile this source vouches for: a single folder, ~/.claude. Another folder, or several (OpenCode rotates
83
+ // between them when one hits a limit, so a step may have run on any of them), is not it.
84
+ export function isDefaultProfile(configDir, system = {}) {
85
+ const dirs = profileDirs(configDir, system)
86
+ return dirs.length === 1 && dirs[0] === join(system.home ?? homedir(), ".claude")
87
+ }
88
+
89
+ // The saved claude-agent logins of a native inventory listing, every one of them (a login the DTO would not list
90
+ // still makes the profile ambiguous).
91
+ export function loginsOf(listed) {
92
+ const info = Array.isArray(listed) ? listed.find((item) => item?.id === INTEGRATION) : undefined
93
+ return Array.isArray(info?.connections) ? info.connections.filter((row) => row?.type === "credential") : []
94
+ }
95
+
96
+ // The saved Claude Code login when it is the only one and needs no sign-in; otherwise undefined.
97
+ export function soleRow(rows) {
98
+ const row = Array.isArray(rows) && rows.length === 1 ? rows[0] : undefined
99
+ return row?.type === "credential" && isRef(row.id) && row.method === "external" && row.status?.status !== "needs_auth" ? row : undefined
100
+ }
101
+
102
+ // Where a step ran: the event's own location when it carries one; OpenCode 2.4.1 delivers session events without it
103
+ // (observed in the HOST lab), so then the session's, a local read of its metadata. Unknown: undefined.
104
+ async function stepLocation(ctx, event, sessionID) {
105
+ const own = event.location?.directory
106
+ if (typeof own === "string" && own !== "") return { directory: own }
107
+ const directory = (await ctx.session.get({ sessionID }))?.location?.directory
108
+ return typeof directory === "string" && directory !== "" ? { directory } : undefined
109
+ }
110
+
111
+ // The connection a sample is attributed to, read when a step ends: the only saved claude-agent login, signed in, of a
112
+ // provider that runs the ~/.claude profile alone in the location that ran the step. No reference when there are none
113
+ // or several, when the inventory, the location or the provider settings cannot be read, or for another profile.
114
+ async function soleConnection(ctx, event, sessionID, system) {
115
+ try {
116
+ const row = soleRow(loginsOf((await ctx.integration.list())?.data))
117
+ const location = row && (await stepLocation(ctx, event, sessionID))
118
+ if (!location) return undefined
119
+ const provider = (await ctx.provider.get({ providerID: INTEGRATION, location }))?.data
120
+ return isDefaultProfile(provider?.settings?.configDir, system) ? row.id : undefined
121
+ } catch {
122
+ return undefined
123
+ }
124
+ }
125
+
126
+ // What makes the Claude data unattributable until the next turn: a credential event of claude-agent, or an
127
+ // integration update (it names no integration, so it may be this one).
128
+ export const invalidates = (event) => event?.type === "integration.updated" ||
129
+ ((event?.type === "credential.updated" || event?.type === "credential.switched") && event.data?.integrationID === INTEGRATION)
130
+
131
+ // Shared by every location instance of the server: steps known to run on claude-agent, events already handled (each
132
+ // instance receives the same event) and a generation that rises whenever the Claude data is invalidated.
133
+ export const createState = () => ({ steps: new Map(), seen: new Set(), generation: 0 })
134
+
135
+ const keep = (collection, key, value) => {
136
+ if (collection instanceof Map) collection.set(key, value)
137
+ else collection.add(key)
138
+ if (collection.size > KEEP) collection.delete(collection.keys().next().value)
139
+ }
140
+
141
+ // The user's own turns, read as they end. Returns true when samples were recorded. A step end is used only if its
142
+ // start named claude-agent, it is recent (ended less than LATE ago) and it carries a known window; its samples go to
143
+ // the single profile's connection, all checked before anything is stored. An invalidation while the checks run
144
+ // discards it.
145
+ export function createTurns({ state, cache, now = Date.now, system }) {
146
+ return async function observe(ctx, event) {
147
+ if (!isRecord(event) || !isRef(event.id) || !STEP_EVENTS.includes(event.type) || state.seen.has(event.id)) return false
148
+ keep(state.seen, event.id)
149
+ const data = isRecord(event.data) ? event.data : {}
150
+ if (!isRef(data.sessionID) || !isRef(data.assistantMessageID)) return false
151
+ const key = JSON.stringify([data.sessionID, data.assistantMessageID])
152
+ if (event.type === "session.step.started") {
153
+ if (data.model?.providerID === INTEGRATION) keep(state.steps, key, true)
154
+ else state.steps.delete(key)
155
+ return false
156
+ }
157
+ if (!state.steps.delete(key)) return false
158
+ const at = now()
159
+ if (!isTime(event.created) || event.created > at + SKEW || at - event.created >= LATE) return false
160
+ const samples = parseRateLimit(isRecord(data.native) ? data.native.rateLimit : undefined, Math.min(event.created, at))
161
+ if (!samples) return false
162
+ const generation = state.generation
163
+ const connectionID = await soleConnection(ctx, event, data.sessionID, system)
164
+ if (!connectionID || generation !== state.generation) return false
165
+ const ref = { integrationID: INTEGRATION, connectionID, source: SOURCE }
166
+ const all = samples.map((sample) => ({ ...sample, ...ref }))
167
+ if (!all.every(validSample)) return false
168
+ return all.map((sample) => cache.record(sample)).some(Boolean)
169
+ }
170
+ }
171
+
172
+ // ---- Manual `/usage` reader -----------------------------------------------------------------------------------------
173
+ // Claude Code answers `/usage` locally (a slash command, no model turn) and, for a claude.ai plan login, attaches
174
+ // `usage_report` (SDKUsageReport, experimental) to the assistant message that carries the text. The process runs
175
+ // without settings, hooks, MCP servers or tools, in a new empty folder removed afterwards; it inherits the environment
176
+ // like OpenCode's claude-agent does and gets no new secret. Nothing here reads a credential, token or keychain.
177
+ export const USAGE_SOURCE = "claude-usage"
178
+ export const USAGE_ARGS = Object.freeze(["-p", "/usage", "--output-format", "stream-json", "--verbose", "--setting-sources", "",
179
+ "--strict-mcp-config", "--tools", "", "--no-session-persistence"])
180
+ const USAGE_WINDOWS = new Map([["session", WINDOWS.get("five_hour")], ["weekly_all", WINDOWS.get("seven_day")]])
181
+ const MAX_OUTPUT = 1_048_576
182
+ const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/
183
+ const usageFailure = (reason) => ({ reason })
184
+
185
+ // The binary OpenCode 2.4.1 runs for claude-agent (claude/io.ts): OPENCODE_CLAUDE_PATH, else `claude` on the PATH.
186
+ export function claudeBinary(env = process.env) {
187
+ if (typeof env?.OPENCODE_CLAUDE_PATH === "string" && env.OPENCODE_CLAUDE_PATH !== "") return env.OPENCODE_CLAUDE_PATH
188
+ for (const dir of String(env?.PATH ?? "").split(delimiter)) {
189
+ if (dir === "") continue
190
+ const file = join(dir, "claude")
191
+ try {
192
+ accessSync(file, constants.X_OK)
193
+ if (statSync(file).isFile()) return file
194
+ } catch {}
195
+ }
196
+ return undefined
197
+ }
198
+
199
+ // The environment claude-agent gives Claude Code for the ~/.claude profile (query-options.ts): the process's own, with
200
+ // CLAUDE_CONFIG_DIR set to the configured folder only when the environment already sets it (withoutDefaultFolder), and
201
+ // without CLAUDE_CODE_SIMPLE (OpenCode clears it). No credential or setting of the provider is added.
202
+ export function usageEnv(configDir, { env = process.env, home = homedir() } = {}) {
203
+ const out = { ...env }
204
+ delete out.CLAUDE_CODE_SIMPLE
205
+ if (configDir !== undefined && env.CLAUDE_CONFIG_DIR !== undefined) out.CLAUDE_CONFIG_DIR = profileDirs(configDir, { env, home })[0]
206
+ return out
207
+ }
208
+
209
+ const tokensIn = (usage) => isRecord(usage) && Object.entries(usage).some(([key, value]) => /tokens$/.test(key) && isNumber(value) && value > 0)
210
+ const spent = (value) => isNumber(value) && value > 0
211
+
212
+ // Stream-json lines → { samples } ([] when Claude Code has no plan rows) or { reason }. Exactly one `usage_report` is
213
+ // required, and nothing may show a model turn: tokens or a cost above 0, a partial-stream event or an error result.
214
+ export function parseUsageReport(text, observedAt) {
215
+ const messages = []
216
+ for (const line of String(text).split("\n")) {
217
+ if (line.trim() === "") continue
218
+ try {
219
+ messages.push(JSON.parse(line))
220
+ } catch {
221
+ return { reason: "invalid" }
222
+ }
223
+ }
224
+ if (!messages.every(isRecord)) return { reason: "invalid" }
225
+ const results = messages.filter((m) => m.type === "result")
226
+ const result = results.length === 1 ? results[0] : undefined
227
+ const model = messages.some((m) => m.type === "stream_event" || (m.type === "assistant" && tokensIn(m.message?.usage))) ||
228
+ spent(result?.total_cost_usd) || tokensIn(result?.usage) ||
229
+ (isRecord(result?.modelUsage) && Object.values(result.modelUsage).some((u) => tokensIn(u) || spent(u?.costUSD)))
230
+ const reports = messages.filter((m) => m.type === "assistant" && m.usage_report !== undefined).map((m) => m.usage_report)
231
+ if (model || reports.some((r) => isRecord(r) && spent(r.session?.total_cost_usd))) return { reason: "model" }
232
+ if (!result || result.is_error === true || reports.length !== 1 || !isRecord(reports[0])) return { reason: "invalid" }
233
+ const limits = reports[0].rate_limits === null ? null : isRecord(reports[0].rate_limits) ? reports[0].rate_limits.limits : undefined
234
+ if (limits === null) return { samples: [] }
235
+ if (!Array.isArray(limits)) return { reason: "invalid" }
236
+ const found = new Map()
237
+ const dropped = new Set()
238
+ for (const row of limits) {
239
+ const spec = isRecord(row) ? USAGE_WINDOWS.get(row.kind) : undefined
240
+ if (!spec) continue
241
+ const at = row.resets_at === null || row.resets_at === undefined ? undefined
242
+ : typeof row.resets_at === "string" && ISO.test(row.resets_at) ? Date.parse(row.resets_at) : NaN
243
+ const valid = isNumber(row.percent) && row.percent >= 0 && row.percent <= 100 &&
244
+ (at === undefined || (isTime(at) && at > observedAt - SKEW && at <= observedAt + spec.span + HOUR))
245
+ if (!valid) {
246
+ dropped.add(spec.window)
247
+ continue
248
+ }
249
+ const sample = { window: spec.window, scope: "general", observedAt, used: row.percent, ...(at !== undefined ? { resetsAt: at } : {}) }
250
+ const prior = found.get(spec.window)
251
+ if (prior && (prior.used !== sample.used || prior.resetsAt !== sample.resetsAt)) dropped.add(spec.window)
252
+ found.set(spec.window, sample)
253
+ }
254
+ return { samples: [...found.values()].filter((s) => !dropped.has(s.window)) }
255
+ }
256
+
257
+ // One run of `claude -p /usage`: bounded stdout, stderr discarded, killed (with its process group) on timeout or when
258
+ // the plugin unloads; its new folder is removed once the process has exited.
259
+ function runUsage({ launch, bin, env, timeout, signal, temp }) {
260
+ const cwd = mkdtempSync(join(temp, "account-quota-usage-"))
261
+ return new Promise((done, fail) => {
262
+ let child
263
+ let size = 0
264
+ let reason
265
+ let timer
266
+ const chunks = []
267
+ const stop = (why) => {
268
+ reason ??= why
269
+ try {
270
+ process.kill(-child.pid, "SIGKILL")
271
+ } catch {
272
+ try { child.kill("SIGKILL") } catch {}
273
+ }
274
+ }
275
+ // Only the server's unload aborts this, and schedule() then records nothing: "cancelled" is not in the RPC contract.
276
+ const onAbort = () => stop("cancelled")
277
+ let settled = false
278
+ const finish = (code) => {
279
+ if (settled) return
280
+ settled = true
281
+ clearTimeout(timer)
282
+ signal.removeEventListener("abort", onAbort)
283
+ rmSync(cwd, { recursive: true, force: true })
284
+ if (reason) fail(usageFailure(reason))
285
+ else if (code !== 0) fail(usageFailure("exit"))
286
+ else done(Buffer.concat(chunks).toString("utf8"))
287
+ }
288
+ try {
289
+ child = launch(bin, [...USAGE_ARGS], { cwd, env, stdio: ["ignore", "pipe", "ignore"], detached: true, windowsHide: true })
290
+ } catch {
291
+ rmSync(cwd, { recursive: true, force: true })
292
+ fail(usageFailure("missing"))
293
+ return
294
+ }
295
+ timer = setTimeout(() => stop("timeout"), timeout)
296
+ if (signal.aborted) onAbort()
297
+ else signal.addEventListener("abort", onAbort, { once: true })
298
+ child.stdout?.on("data", (chunk) => {
299
+ size += chunk.length
300
+ if (size > MAX_OUTPUT) stop("too-large")
301
+ else chunks.push(chunk)
302
+ })
303
+ child.on("error", () => {
304
+ reason ??= "missing"
305
+ finish()
306
+ })
307
+ child.on("close", finish)
308
+ })
309
+ }
310
+
311
+ let usageRunning = false
312
+
313
+ // The manual reader of claude-agent. It runs only with the attribution of the passive source (one saved login, signed
314
+ // in, the single ~/.claude profile, no credentials in the provider settings); otherwise it fails without a process.
315
+ // `launch` (the process launcher), `system` ({ env, home, tmp }) and `timeout` stand in for the real ones in tests.
316
+ export function createUsageReader({ launch = spawn, system = {}, now = Date.now, timeout = 20_000 } = {}) {
317
+ return {
318
+ source: USAGE_SOURCE,
319
+ // Only an explicit Refresh: never when the panel opens, on load, at a turn end or on a timer.
320
+ manual: true,
321
+ bound: true,
322
+ // No plan rows (`rate_limits: null`) is a read without data, not a failure.
323
+ empty: true,
324
+ async read({ ctx, connection, signal }) {
325
+ const env = system.env ?? process.env
326
+ const home = system.home ?? homedir()
327
+ let settings
328
+ try {
329
+ if (soleRow(loginsOf((await ctx.integration.list())?.data))?.id !== connection?.id) throw usageFailure("profile")
330
+ settings = (await ctx.provider.get({ providerID: INTEGRATION }))?.data?.settings ?? {}
331
+ } catch (error) {
332
+ throw typeof error?.reason === "string" ? error : usageFailure("profile")
333
+ }
334
+ const own = ["apiKey", "authToken", "baseURL"].some((key) => settings?.[key] !== undefined)
335
+ if (own || !isDefaultProfile(settings?.configDir, { env, home })) throw usageFailure("profile")
336
+ const bin = claudeBinary(env)
337
+ if (!bin) throw usageFailure("missing")
338
+ if (usageRunning) throw usageFailure("busy")
339
+ usageRunning = true
340
+ let text
341
+ try {
342
+ text = await runUsage({ launch, bin, env: usageEnv(settings?.configDir, { env, home }), timeout, signal, temp: system.tmp ?? tmpdir() })
343
+ } finally {
344
+ usageRunning = false
345
+ }
346
+ const parsed = parseUsageReport(text, now())
347
+ if (parsed.reason) throw usageFailure(parsed.reason)
348
+ return parsed.samples
349
+ },
350
+ }
351
+ }
package/codex.js ADDED
@@ -0,0 +1,87 @@
1
+ // Codex legacy usage (E06; S18–S20). EXPERIMENTAL and off by default. GET https://chatgpt.com/backend-api/wham/usage
2
+ // is the internal ChatGPT usage endpoint that OpenCode Quota v6.3.0 reads: not a public API, and no authorization for
3
+ // this use is claimed. The server enables it only with the plugin option `experimentalCodexUsage: true` and reads only
4
+ // on an explicit Refresh of one saved connection, active or not: `r` on the selected account, or `a` (Refresh all),
5
+ // which asks once per eligible connection. Reading never switches the active account. The login itself must
6
+ // say it is Codex legacy through its native methodID and name its ChatGPT account; its token stays in memory for this
7
+ // one request. No redirects, bounded time and body, one fixed destination, explicit failures without the body or token.
8
+ import { failure, get } from "./deepseek.js"
9
+ import { isNumber, isTime } from "./rules.js"
10
+
11
+ const ENDPOINT = "https://chatgpt.com/backend-api/wham/usage"
12
+ // Native OpenCode method IDs of the two Codex legacy logins (`/connect` → OpenAI → Codex browser / device code).
13
+ // Sign in with ChatGPT (`chatgpt-token-sharing`), API keys and any other or missing method are never read.
14
+ const LEGACY = new Set(["chatgpt-browser", "chatgpt-headless"])
15
+ // Windows are named by their duration, never by their position in the response.
16
+ const WINDOWS = new Map([[18_000, "5h"], [604_800, "weekly"]])
17
+
18
+ // What the stored login says about itself: a Codex legacy method and the ChatGPT account it belongs to. Nothing is
19
+ // inferred from the label, the generic "oauth" method or the token's content.
20
+ function legacy(login) {
21
+ const account = login?.metadata?.accountID
22
+ if (login?.type !== "oauth" || !LEGACY.has(login.methodID)) return undefined
23
+ if (typeof account !== "string" || account === "" || account.length > 200) return undefined
24
+ if (typeof login.access !== "string" || login.access === "") return undefined
25
+ return { methodID: login.methodID, account, access: login.access, expires: login.expires }
26
+ }
27
+
28
+ // `rate_limit.primary_window` / `secondary_window`: `used_percent` 0–100 and `limit_window_seconds`, with the reset
29
+ // from `reset_at` (epoch seconds) or else `reset_after_seconds`. Unknown durations are ignored; a duration seen twice
30
+ // with different values, or a reset field that is not a valid time, is ambiguous and dropped. No window, no sample.
31
+ export function parseUsage(text, observedAt) {
32
+ let data
33
+ try {
34
+ data = JSON.parse(text)
35
+ } catch {
36
+ return undefined
37
+ }
38
+ const found = new Map()
39
+ const ambiguous = new Set()
40
+ for (const w of [data?.rate_limit?.primary_window, data?.rate_limit?.secondary_window]) {
41
+ const window = WINDOWS.get(w?.limit_window_seconds)
42
+ if (!window) continue
43
+ const used = w.used_percent
44
+ const resetsAt = w.reset_at != null ? (isNumber(w.reset_at) ? w.reset_at * 1000 : NaN)
45
+ : w.reset_after_seconds != null ? (isNumber(w.reset_after_seconds) && w.reset_after_seconds >= 0 ? observedAt + w.reset_after_seconds * 1000 : NaN)
46
+ : undefined
47
+ if (!isNumber(used) || used < 0 || used > 100 || (resetsAt !== undefined && !isTime(resetsAt))) {
48
+ ambiguous.add(window)
49
+ continue
50
+ }
51
+ const sample = { window, scope: "general", observedAt, used, ...(resetsAt !== undefined ? { resetsAt } : {}) }
52
+ const prior = found.get(window)
53
+ if (prior && (prior.used !== used || prior.resetsAt !== sample.resetsAt)) ambiguous.add(window)
54
+ found.set(window, sample)
55
+ }
56
+ const samples = [...found.values()].filter((s) => !ambiguous.has(s.window))
57
+ return samples.length > 0 ? samples : undefined
58
+ }
59
+
60
+ // `send` is the transport: fetch in the product, a double in tests and in the HOST lab. Never a URL.
61
+ export function createCodexReader({ send = (...args) => globalThis.fetch(...args), now = Date.now, timeout = 5_000 } = {}) {
62
+ return {
63
+ source: "codex-usage",
64
+ // Only an explicit Refresh: never when the panel opens, at a turn end or on load.
65
+ manual: true,
66
+ // Bound to one login: the server checks that the reference is still listed the same way when its turn in the
67
+ // queue comes (before resolving) and after the answer; this reader checks the login behind it (method, account).
68
+ bound: true,
69
+ async read({ connection, resolve, signal }) {
70
+ if (connection?.method !== "oauth") throw failure("login") // an API key is not even resolved
71
+ const login = legacy(await resolve())
72
+ if (!login) throw failure("login")
73
+ if (isNumber(login.expires) && login.expires <= now()) throw failure("auth")
74
+ const text = await get(send, ENDPOINT, { Authorization: `Bearer ${login.access}`, "ChatGPT-Account-Id": login.account, Accept: "application/json" },
75
+ { signal, timeout, now })
76
+ // The observation time is taken once the body has been read.
77
+ const samples = parseUsage(text, now())
78
+ if (!samples) throw failure("invalid")
79
+ // A re-login or another account under the same reference while the request was out makes the answer ambiguous;
80
+ // so does a reference that no longer resolves (removed) or cannot be checked.
81
+ if (signal.aborted) throw failure("network")
82
+ const after = legacy(await resolve().catch(() => undefined))
83
+ if (after?.methodID !== login.methodID || after.account !== login.account) throw failure("changed")
84
+ return samples
85
+ },
86
+ }
87
+ }
package/deepseek.js ADDED
@@ -0,0 +1,102 @@
1
+ // DeepSeek balance (B06; S09). The only destination is the official endpoint; the key resolved by OpenCode for
2
+ // this one connection stays in memory for this request. No redirects, bounded time and body, explicit failures
3
+ // that never carry the response body or the key. The server schedules reads (sharing, limit, backoff).
4
+ import { isCurrency, isDecimal } from "./rules.js"
5
+
6
+ const ENDPOINT = "https://api.deepseek.com/user/balance"
7
+ const MAX_BODY = 64 * 1024
8
+
9
+ export const failure = (reason, retryAfter) => ({ reason, ...(Number.isFinite(retryAfter) ? { retryAfter } : {}) })
10
+
11
+ // Shared with codex.js: Retry-After in ms and a size-bounded, strict UTF-8 body.
12
+ export function retryAfter(header, now) {
13
+ const value = header?.trim()
14
+ if (!value) return undefined
15
+ if (/^\d{1,6}$/.test(value)) return Number(value) * 1000
16
+ const at = Date.parse(value)
17
+ return Number.isFinite(at) ? Math.max(0, at - now) : undefined
18
+ }
19
+
20
+ export async function boundedText(response) {
21
+ const reader = response.body?.getReader()
22
+ if (!reader) return ""
23
+ const chunks = []
24
+ let size = 0
25
+ for (;;) {
26
+ const { done, value } = await reader.read()
27
+ if (done) break
28
+ size += value.byteLength
29
+ if (size > MAX_BODY) {
30
+ await reader.cancel().catch(() => {})
31
+ throw failure("too-large")
32
+ }
33
+ chunks.push(value)
34
+ }
35
+ const all = new Uint8Array(size)
36
+ let offset = 0
37
+ for (const chunk of chunks) {
38
+ all.set(chunk, offset)
39
+ offset += chunk.byteLength
40
+ }
41
+ return new TextDecoder("utf-8", { fatal: true }).decode(all)
42
+ }
43
+
44
+ // `is_available` and every currency/total as documented; amounts stay decimal strings. Missing currency or
45
+ // amount is "invalid", never zero.
46
+ export function parseBalance(text) {
47
+ let data
48
+ try {
49
+ data = JSON.parse(text)
50
+ } catch {
51
+ return undefined
52
+ }
53
+ const infos = data?.balance_infos
54
+ if (typeof data?.is_available !== "boolean" || !Array.isArray(infos) || infos.length === 0 || infos.length > 8) return undefined
55
+ const balances = infos.map((info) => ({ currency: info?.currency, total: info?.total_balance }))
56
+ if (!balances.every((b) => isCurrency(b.currency) && isDecimal(b.total))) return undefined
57
+ if (new Set(balances.map((b) => b.currency)).size !== balances.length) return undefined
58
+ return { available: data.is_available, balances }
59
+ }
60
+
61
+ // Shared with codex.js: one GET to the single `url` its reader passes, no redirects, bounded time and body. Resolves to
62
+ // the text of a 200; anything else throws an explicit failure that never carries the body or the credential.
63
+ // `statuses` maps the reader's own codes to reasons, checked after a redirect and 401 and before 429.
64
+ export async function get(send, url, headers, { signal, timeout, now, statuses = {} }) {
65
+ const timer = AbortSignal.timeout(timeout)
66
+ const reason = () => (timer.aborted ? "timeout" : "network")
67
+ let response
68
+ try {
69
+ response = await send(url, { method: "GET", redirect: "manual", signal: AbortSignal.any([signal, timer]), headers })
70
+ } catch {
71
+ throw failure(reason())
72
+ }
73
+ try {
74
+ const status = response.status
75
+ if ((status >= 300 && status < 400) || response.type === "opaqueredirect") throw failure("redirect")
76
+ if (status === 401) throw failure("auth")
77
+ if (Object.hasOwn(statuses, status)) throw failure(statuses[status])
78
+ if (status === 429) throw failure("rate-limit", retryAfter(response.headers?.get("retry-after"), now()))
79
+ if (status !== 200) throw failure("http")
80
+ return await boundedText(response)
81
+ } catch (error) {
82
+ throw typeof error?.reason === "string" ? error : failure(error instanceof TypeError ? "invalid" : reason())
83
+ } finally {
84
+ if (!response.bodyUsed && !response.body?.locked) response.body?.cancel().catch(() => {})
85
+ }
86
+ }
87
+
88
+ // `send` is the transport: fetch in the product, a double in tests and in the HOST lab. Never a URL.
89
+ export function createDeepseekReader({ send = (...args) => globalThis.fetch(...args), now = Date.now, timeout = 5_000 } = {}) {
90
+ return {
91
+ source: "deepseek-balance",
92
+ async read({ resolve, signal }) {
93
+ const credential = await resolve()
94
+ if (credential?.type !== "key" || typeof credential.key !== "string" || credential.key === "") throw failure("auth")
95
+ const text = await get(send, ENDPOINT, { Authorization: `Bearer ${credential.key}`, Accept: "application/json" },
96
+ { signal, timeout, now, statuses: { 402: "balance" } })
97
+ const parsed = parseBalance(text)
98
+ if (!parsed) throw failure("invalid")
99
+ return { window: "balance", scope: "general", observedAt: now(), ...parsed }
100
+ },
101
+ }
102
+ }
package/index.js ADDED
@@ -0,0 +1,12 @@
1
+ import { createUsageReader } from "./claude.js"
2
+ import { createCodexReader } from "./codex.js"
3
+ import { createDeepseekReader } from "./deepseek.js"
4
+ import { contract } from "./rpc.js"
5
+ import { createPlugin } from "./server.js"
6
+
7
+ // Shipped server entry. Readers are fixed in code by their tasks; none is configurable at runtime. The Codex legacy
8
+ // reader is experimental and exists only with the plugin option `experimentalCodexUsage: true` (off by default).
9
+ // Claude's passive usage (server.js, claude.js) and its manual `/usage` reader exist only with
10
+ // `experimentalClaudeUsage: true` (off by default).
11
+ export default createPlugin({ contract, readers: { deepseek: createDeepseekReader() }, experimental: { openai: createCodexReader() },
12
+ claude: createUsageReader() })