@byokit/usage 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/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ - Read subscription usage windows per provider and per account, with last-good readings and bounded provider reads.
6
+
7
+ ## 0.1.0
8
+
9
+ - Read subscription usage windows per provider and per account, with last-good readings and bounded provider reads.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,25 @@
1
+ # @byokit/usage
2
+
3
+ Read subscription usage windows per provider and per account on Node 22.18 or later. Crewhouse can show each member's room, v1 design can meter a payer's plan, and fleet apps can compare account readings. The app chooses an account and supplies labels; this kit makes no choice and estimates no cost.
4
+
5
+ ```ts
6
+ import { usage } from '@byokit/usage';
7
+ const reader = usage({ stateDir: '/app/state/usage' });
8
+ const source = { provider: 'codex' as const, bin: '/app/bin/codex', home: '/app/sign-ins/alice' };
9
+ const reading = await reader.read(source);
10
+ for (const window of reading.windows) console.log(window.kind, 100 - window.usedPercent);
11
+ ```
12
+
13
+ The Node-only `.` entry exports `usage`, `UsageError`, types, `claudeWindows`, `codexWindows`, `goWindows`, `zaiWindows`, `words`, and `usageWords`. There is no portable entry and no dependency on accounts. `./testing` exports `fakeFetch`, `fakeCodex`, and `usageContract(make, { test? })` (or a test function directly).
14
+
15
+ Sources are `{ provider: 'codex', bin, home, env? }`, `{ provider: 'opencode', key }`, or `{ provider: 'zai', key }`. Paths must be absolute; removed or empty keys mean disconnected. Claude plan-token adapters stay in the host: the host's own Source reads its payload and calls `claudeWindows(raw)`. This package opens no Claude files, sends no Claude headers, and refreshes no sign-in.
16
+
17
+ `read(source, { nowMs? })` resolves `{ provider, windows, at, code? }`. Remaining room is `100 - usedPercent`; reset times are provider epoch seconds, even outside a plausible clock-display range. `lastKnown(source, { nowMs? })` returns the stored reading only within 24 hours while connected. `connected(source)` and `account(source)` are synchronous; the latter is a salted fingerprint for a host's collection memo. Only bad sources reject with `UsageError` (`code: 'bad-source'`). Failures retain a last-good reading and its original timestamp, with a code explaining the failed update. A good read has no code. Reads have a 60-second floor, per-account concurrent deduplication and a 429 backoff of at least five minutes. `UsageOptions.now` supplies the default clock; a per-call clock overrides it. An injected `fetch` wins; otherwise global fetch is resolved on each read.
18
+
19
+ Parsers consume Claude's usage/statusline payload, the Go `usage` member, the Z.ai `data.limits` member, or the Codex app-server result (`CodexRateLimitResult`). They carry provider names, normalized kind, percent used, optional duration, reset time, separate limit name and limited flag. Codex windows preserve critical-limit ordering and the eight-window cap. Raw endpoint dialects stay behind this typed surface.
20
+
21
+ Isolation: the kit reads only the sign-in folder the app passes and spawns only the Codex binary the app passes by absolute path. It discovers no paths and reads no environment variables. The spawn uses an argv array and an environment built from nothing plus the host's `env` and `CODEX_HOME=home`; pass PATH and HOME explicitly when the binary needs them. Tokens never enter logs, errors or readings. Maps hold fingerprints, never raw secrets. The kit reads only `home/auth.json` for Codex identity and writes only `stateDir/plans-v1.json` (0700 directory, 0600 file, atomic rename, 256 KB cap). `salt` defaults to `byokit/usage/account`; a migrating host may preserve its previous salt and stateDir. Legacy stores from before per-account storage are not supported.
22
+
23
+ The undocumented provider endpoints are fixed to `https://opencode.ai/zen/go/v1/usage` and `https://api.z.ai/api/monitor/usage/quota/limit`, with Bearer keys passed by the host, `accept: application/json`, and redirects rejected. HTTP reads have a 10-second deadline and 64 KB body cap. Codex runs `app-server`, initializes the client and calls `account/rateLimits/read`, with a 20-second deadline, 64 KB stdout cap and SIGTERM followed by SIGKILL after one second. No telemetry or credential write-back.
24
+
25
+ Tests run the contract with recorded, sanitized payloads and fakes only, behind the repository's egress guard. Real endpoints and real sign-in folders are never run by the suite. `usageContract` takes a bench with `usage`, `source`, `expected`, `nowMs`, `restart`, optional `cleanup`, and optional scripted `fake` (`fail`, `disconnect`, `calls`). Scripted-failure cases skip without the fake seam.
@@ -0,0 +1,6 @@
1
+ import { type Usage, type UsageOptions } from './types.ts';
2
+ export * from './types.ts';
3
+ export { claudeWindows, codexWindows, goWindows, zaiWindows, type CodexRateLimitResult } from './windows.ts';
4
+ export { WORDS, words, usageWords, type WordKey } from './words.ts';
5
+ /** One reader owns per-account backoff and concurrent-read deduplication. */
6
+ export declare function usage(options: UsageOptions): Usage;
package/dist/index.js ADDED
@@ -0,0 +1,119 @@
1
+ import { accessSync, constants, statSync } from 'node:fs';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { codexUsage, providerGet } from "./providers.js";
4
+ import { fingerprint, readJson, store } from "./store.js";
5
+ import { codexWindows, goWindows, record, zaiWindows } from "./windows.js";
6
+ import { UsageError } from "./types.js";
7
+ export * from "./types.js";
8
+ export { claudeWindows, codexWindows, goWindows, zaiWindows } from "./windows.js";
9
+ export { WORDS, words, usageWords } from "./words.js";
10
+ const validText = (v) => typeof v === 'string' && !v.includes('\0');
11
+ function validate(source) {
12
+ if (!record(source))
13
+ throw new UsageError();
14
+ if (source.provider === 'codex') {
15
+ if (!validText(source.bin) || !isAbsolute(source.bin) || !validText(source.home) || !isAbsolute(source.home))
16
+ throw new UsageError();
17
+ if (source.env !== undefined && (!record(source.env) || Object.entries(source.env).some(([k, v]) => !k || k.includes('=') || !validText(k) || !validText(v))))
18
+ throw new UsageError();
19
+ }
20
+ else if (!['opencode', 'zai'].includes(source.provider) || !validText(source.key) || source.key.length > 16384)
21
+ throw new UsageError();
22
+ }
23
+ /** One reader owns per-account backoff and concurrent-read deduplication. */
24
+ export function usage(options) {
25
+ if (!validText(options.stateDir) || !isAbsolute(options.stateDir))
26
+ throw new UsageError();
27
+ const disk = store(options.stateDir);
28
+ const fp = fingerprint(options.salt ?? 'byokit/usage/account');
29
+ const backoff = new Map();
30
+ const inFlight = new Map();
31
+ const attempts = new Map();
32
+ const now = (opts) => opts?.nowMs ?? (options.now ?? Date.now)();
33
+ function connected(source) {
34
+ validate(source);
35
+ if (source.provider !== 'codex')
36
+ return source.key.trim() !== '';
37
+ try {
38
+ accessSync(source.bin, constants.X_OK);
39
+ return statSync(source.bin).isFile();
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ function account(source) {
46
+ validate(source);
47
+ if (source.provider !== 'codex')
48
+ return source.key.trim() ? fp(source.provider, source.key) : undefined;
49
+ const raw = readJson(join(source.home, 'auth.json'), 64 * 1024);
50
+ const tokens = record(raw) && record(raw.tokens) ? raw.tokens : undefined;
51
+ const value = typeof tokens?.account_id === 'string' ? tokens.account_id : `codex-home\0${source.home}`;
52
+ return value !== '' && value.length <= 16384 ? fp('codex', value) : undefined;
53
+ }
54
+ const windows = (source, raw) => source.provider === 'codex' ? codexWindows(raw) : source.provider === 'opencode' ? goWindows(raw) : zaiWindows(raw);
55
+ function lastKnown(source, opts) {
56
+ if (!connected(source))
57
+ return undefined;
58
+ const key = account(source);
59
+ if (!key)
60
+ return undefined;
61
+ const stored = disk.get(source.provider, key);
62
+ const clock = now(opts);
63
+ if (!stored || clock < stored.at || clock - stored.at > 86_400_000)
64
+ return undefined;
65
+ const rows = windows(source, stored.raw);
66
+ return rows.length ? { provider: source.provider, windows: rows, at: stored.at } : undefined;
67
+ }
68
+ async function read(source, opts) {
69
+ validate(source);
70
+ const clock = now(opts);
71
+ const empty = (code) => ({ provider: source.provider, windows: [], at: clock, code });
72
+ if (!connected(source))
73
+ return empty('not-connected');
74
+ const key = account(source);
75
+ if (!key)
76
+ return empty('not-connected');
77
+ const identity = `${source.provider}\0${key}`;
78
+ const previous = lastKnown(source, { nowMs: clock });
79
+ if (previous && clock - previous.at < 60_000)
80
+ return previous;
81
+ if ((backoff.get(identity) ?? 0) > clock)
82
+ return previous ? { ...previous, code: 'rate-limited' } : empty('rate-limited');
83
+ const pending = inFlight.get(identity);
84
+ if (pending)
85
+ return pending;
86
+ const attempt = attempts.get(identity);
87
+ if (attempt && clock >= attempt.at && clock - attempt.at < 60_000)
88
+ return previous ? { ...previous, code: attempt.answer.code } : empty(attempt.answer.code ?? 'unavailable');
89
+ const task = (async () => {
90
+ let answer;
91
+ try {
92
+ answer = source.provider === 'codex' ? await codexUsage(source) : await providerGet(source, options.fetch ?? globalThis.fetch, clock);
93
+ }
94
+ catch {
95
+ answer = { code: 'unavailable' };
96
+ }
97
+ if (answer.until !== undefined)
98
+ backoff.set(identity, answer.until);
99
+ const rows = windows(source, answer.raw);
100
+ if (!answer.code && !rows.length)
101
+ answer = { code: 'incomplete' };
102
+ // Do not keep a source key or a raw payload in a retry map.
103
+ attempts.set(identity, { at: clock, answer: { code: answer.code } });
104
+ if (rows.length && !answer.code) {
105
+ disk.put(source.provider, key, { at: clock, raw: answer.raw });
106
+ return { provider: source.provider, windows: rows, at: clock };
107
+ }
108
+ return previous ? { ...previous, code: answer.code } : empty(answer.code ?? 'unavailable');
109
+ })();
110
+ inFlight.set(identity, task);
111
+ try {
112
+ return await task;
113
+ }
114
+ finally {
115
+ inFlight.delete(identity);
116
+ }
117
+ }
118
+ return { read, lastKnown, connected, account };
119
+ }
@@ -0,0 +1,12 @@
1
+ import type { Code, Source } from './types.ts';
2
+ export interface Answer {
3
+ raw?: unknown;
4
+ code?: Code;
5
+ until?: number;
6
+ }
7
+ export declare function providerGet(source: Extract<Source, {
8
+ key: string;
9
+ }>, fetcher: typeof fetch, nowMs: number): Promise<Answer>;
10
+ export declare function codexUsage(source: Extract<Source, {
11
+ provider: 'codex';
12
+ }>): Promise<Answer>;
@@ -0,0 +1,109 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { record } from "./windows.js";
3
+ export async function providerGet(source, fetcher, nowMs) {
4
+ const controller = new AbortController();
5
+ const timer = setTimeout(() => controller.abort(), 10_000);
6
+ try {
7
+ const url = source.provider === 'opencode' ? 'https://opencode.ai/zen/go/v1/usage' : 'https://api.z.ai/api/monitor/usage/quota/limit';
8
+ const response = await fetcher(url, { headers: { accept: 'application/json', authorization: `Bearer ${source.key}` }, redirect: 'error', signal: controller.signal });
9
+ if (response.status === 429) {
10
+ const retry = response.headers.get('retry-after');
11
+ const seconds = Number(retry);
12
+ const delay = retry !== null && Number.isFinite(seconds) ? seconds * 1000 : Date.parse(retry ?? '') - nowMs;
13
+ controller.abort();
14
+ return { code: 'rate-limited', until: nowMs + Math.max(300_000, Number.isFinite(delay) ? delay : 0) };
15
+ }
16
+ if (response.status !== 200) {
17
+ controller.abort();
18
+ return { code: response.status === 401 ? 'auth' : response.status === 403 ? 'no-plan' : 'unavailable' };
19
+ }
20
+ if (!response.body)
21
+ return { code: 'incomplete' };
22
+ const chunks = [];
23
+ let size = 0;
24
+ const reader = response.body.getReader();
25
+ for (;;) {
26
+ const { value: chunk, done } = await reader.read();
27
+ if (done)
28
+ break;
29
+ size += chunk.byteLength;
30
+ if (size > 64 * 1024) {
31
+ controller.abort();
32
+ return { code: 'incomplete' };
33
+ }
34
+ chunks.push(chunk);
35
+ }
36
+ let raw;
37
+ try {
38
+ raw = JSON.parse(Buffer.concat(chunks).toString('utf8'));
39
+ }
40
+ catch {
41
+ return { code: 'incomplete' };
42
+ }
43
+ if (!record(raw))
44
+ return { code: 'incomplete' };
45
+ if (source.provider === 'zai' && raw.success === false)
46
+ return { code: 'no-plan' };
47
+ return { raw: source.provider === 'opencode' ? raw.usage : record(raw.data) ? raw.data.limits : undefined };
48
+ }
49
+ catch {
50
+ return { code: 'unavailable' };
51
+ }
52
+ finally {
53
+ clearTimeout(timer);
54
+ }
55
+ }
56
+ export function codexUsage(source) {
57
+ return new Promise((resolve) => {
58
+ const child = spawn(source.bin, ['app-server'], { env: { ...source.env, CODEX_HOME: source.home }, stdio: ['pipe', 'pipe', 'ignore'] });
59
+ let buffer = '';
60
+ let bytes = 0;
61
+ let settled = false;
62
+ let escalation;
63
+ const finish = (answer) => {
64
+ if (settled)
65
+ return;
66
+ settled = true;
67
+ clearTimeout(timer);
68
+ if (child.exitCode === null && child.signalCode === null) {
69
+ child.kill('SIGTERM');
70
+ escalation = setTimeout(() => { if (child.exitCode === null && child.signalCode === null)
71
+ child.kill('SIGKILL'); }, 1000);
72
+ }
73
+ resolve(answer);
74
+ };
75
+ const timer = setTimeout(() => finish({ code: 'unavailable' }), 20_000);
76
+ child.once('error', () => finish({ code: 'unavailable' }));
77
+ child.once('close', () => { clearTimeout(escalation); finish({ code: 'unavailable' }); });
78
+ child.stdin.on('error', () => finish({ code: 'unavailable' }));
79
+ child.stdout.setEncoding('utf8');
80
+ child.stdout.on('data', (chunk) => {
81
+ if (settled)
82
+ return;
83
+ bytes += Buffer.byteLength(chunk);
84
+ buffer += chunk;
85
+ if (bytes > 64 * 1024) {
86
+ finish({ code: 'incomplete' });
87
+ return;
88
+ }
89
+ for (;;) {
90
+ const newline = buffer.indexOf('\n');
91
+ if (newline < 0)
92
+ break;
93
+ const line = buffer.slice(0, newline);
94
+ buffer = buffer.slice(newline + 1);
95
+ try {
96
+ const message = JSON.parse(line);
97
+ if (!record(message))
98
+ continue;
99
+ if (message.id === 1)
100
+ child.stdin.write(`${JSON.stringify({ id: 2, method: 'account/rateLimits/read', params: {} })}\n`);
101
+ if (message.id === 2)
102
+ finish(record(message.result) ? { raw: message.result } : { code: 'incomplete' });
103
+ }
104
+ catch { /* Non-JSON output is bounded and ignored. */ }
105
+ }
106
+ });
107
+ child.stdin.write(`${JSON.stringify({ id: 1, method: 'initialize', params: { clientInfo: { name: 'byokit', version: '1' } } })}\n`);
108
+ });
109
+ }
@@ -0,0 +1,12 @@
1
+ import type { Provider } from './types.ts';
2
+ export interface Stored {
3
+ at: number;
4
+ raw: unknown;
5
+ }
6
+ /** Bounded regular files only; do not follow credential or state symlinks. */
7
+ export declare function readJson(file: string, cap: number): unknown;
8
+ export declare function fingerprint(salt: string): (provider: Provider, value: string) => string;
9
+ export declare function store(stateDir: string): {
10
+ get: (id: Provider, fp: string) => Stored | undefined;
11
+ put(id: Provider, fp: string, reading: Stored): void;
12
+ };
package/dist/store.js ADDED
@@ -0,0 +1,93 @@
1
+ import { createHash, randomUUID, scryptSync } from 'node:crypto';
2
+ import { chmodSync, closeSync, fstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync, constants } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { record } from "./windows.js";
5
+ /** Bounded regular files only; do not follow credential or state symlinks. */
6
+ export function readJson(file, cap) {
7
+ let fd;
8
+ try {
9
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
10
+ const stat = fstatSync(fd);
11
+ if (!stat.isFile() || stat.size > cap)
12
+ return undefined;
13
+ const body = Buffer.alloc(cap + 1);
14
+ let length = 0;
15
+ while (length <= cap) {
16
+ const count = readSync(fd, body, length, cap + 1 - length, null);
17
+ if (!count)
18
+ break;
19
+ length += count;
20
+ }
21
+ return length <= cap ? JSON.parse(body.subarray(0, length).toString('utf8')) : undefined;
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ finally {
27
+ if (fd !== undefined)
28
+ closeSync(fd);
29
+ }
30
+ }
31
+ export function fingerprint(salt) {
32
+ const memo = new Map();
33
+ return (provider, value) => {
34
+ const key = createHash('sha256').update(`${provider}\0${value}`).digest('hex');
35
+ let fp = memo.get(key);
36
+ if (!fp) {
37
+ fp = scryptSync(value, `${salt}/${provider}`, 32, { N: 16384, r: 8, p: 1 }).toString('hex');
38
+ if (memo.size >= 32)
39
+ memo.clear();
40
+ memo.set(key, fp);
41
+ }
42
+ return fp;
43
+ };
44
+ }
45
+ export function store(stateDir) {
46
+ const path = join(stateDir, 'plans-v1.json');
47
+ function load() {
48
+ const saved = readJson(path, 256 * 1024);
49
+ const plans = {};
50
+ if (!record(saved) || !record(saved.plans))
51
+ return plans;
52
+ for (const id of ['claude', 'codex', 'opencode', 'zai']) {
53
+ const entries = saved.plans[id];
54
+ if (!record(entries))
55
+ continue;
56
+ const readings = Object.create(null);
57
+ for (const [fp, r] of Object.entries(entries)) {
58
+ if (/^[a-f0-9]{64}$/.test(fp) && record(r) && typeof r.at === 'number' && Number.isFinite(r.at))
59
+ readings[fp] = { at: r.at, raw: r.raw };
60
+ }
61
+ plans[id] = readings;
62
+ }
63
+ return plans;
64
+ }
65
+ return {
66
+ get: (id, fp) => load()[id]?.[fp],
67
+ put(id, fp, reading) {
68
+ const temporary = `${path}.${randomUUID()}.tmp`;
69
+ try {
70
+ const plans = load();
71
+ const entries = plans[id] ?? {};
72
+ if (reading.at < (entries[fp]?.at ?? -Infinity))
73
+ return;
74
+ entries[fp] = reading;
75
+ plans[id] = entries;
76
+ const body = JSON.stringify({ plans });
77
+ if (Buffer.byteLength(body) > 256 * 1024)
78
+ return;
79
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
80
+ chmodSync(stateDir, 0o700);
81
+ writeFileSync(temporary, body, { mode: 0o600, flag: 'wx' });
82
+ renameSync(temporary, path);
83
+ }
84
+ catch { /* Persistence failure never exposes provider data as an error. */ }
85
+ finally {
86
+ try {
87
+ unlinkSync(temporary);
88
+ }
89
+ catch { /* already renamed or never created */ }
90
+ }
91
+ },
92
+ };
93
+ }
@@ -0,0 +1,20 @@
1
+ import type { Reading, Source, Usage } from '../types.ts';
2
+ export type UsageContractTestFn = (name: string, fn: (t: {
3
+ skip(message?: string): void;
4
+ }) => void | Promise<void>) => unknown;
5
+ export interface UsageContractBench {
6
+ usage: Usage;
7
+ source: Source;
8
+ expected: Reading['windows'];
9
+ nowMs: number;
10
+ restart(): Usage;
11
+ fake?: {
12
+ fail(): void;
13
+ disconnect(): void;
14
+ calls(): number;
15
+ };
16
+ cleanup?(): void | Promise<void>;
17
+ }
18
+ export declare function usageContract(make: () => UsageContractBench | Promise<UsageContractBench>, options?: {
19
+ test?: UsageContractTestFn;
20
+ } | UsageContractTestFn): void;
@@ -0,0 +1,47 @@
1
+ import { test as nodeTest } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ export function usageContract(make, options = {}) {
4
+ const test = typeof options === 'function' ? options : options.test ?? nodeTest;
5
+ test('usage contract: concurrent reads, freshness floor and restart keep one account reading', async () => {
6
+ const b = await make();
7
+ try {
8
+ const [a, duplicate] = await Promise.all([b.usage.read(b.source, { nowMs: b.nowMs }), b.usage.read(b.source, { nowMs: b.nowMs })]);
9
+ assert.deepEqual(a.windows, b.expected);
10
+ assert.deepEqual(a, duplicate);
11
+ assert.equal(a.code, undefined);
12
+ const count = b.fake?.calls();
13
+ assert.deepEqual(await b.usage.read(b.source, { nowMs: b.nowMs + 59_999 }), a);
14
+ if (count !== undefined) {
15
+ assert.equal(count, 1);
16
+ assert.equal(b.fake.calls(), count);
17
+ }
18
+ assert.deepEqual(b.restart().lastKnown(b.source, { nowMs: b.nowMs + 60_000 }), a);
19
+ assert.equal(b.restart().lastKnown(b.source, { nowMs: b.nowMs + 86_400_001 }), undefined);
20
+ }
21
+ finally {
22
+ await b.cleanup?.();
23
+ }
24
+ });
25
+ test('usage contract: failed reads stand on the last good reading only while connected', async (t) => {
26
+ const b = await make();
27
+ try {
28
+ if (!b.fake) {
29
+ t.skip('Requires scripted failure and disconnect.');
30
+ return;
31
+ }
32
+ const a = await b.usage.read(b.source, { nowMs: b.nowMs });
33
+ b.fake.fail();
34
+ const failed = await b.usage.read(b.source, { nowMs: b.nowMs + 60_000 });
35
+ assert.deepEqual(failed.windows, a.windows);
36
+ assert.equal(failed.at, a.at);
37
+ assert.ok(failed.code);
38
+ b.fake.disconnect();
39
+ assert.equal(b.usage.connected(b.source), false);
40
+ assert.equal(b.usage.lastKnown(b.source, { nowMs: b.nowMs + 61_000 }), undefined);
41
+ assert.equal((await b.usage.read(b.source, { nowMs: b.nowMs + 61_000 })).code, 'not-connected');
42
+ }
43
+ finally {
44
+ await b.cleanup?.();
45
+ }
46
+ });
47
+ }
@@ -0,0 +1,37 @@
1
+ export { usageContract, type UsageContractBench, type UsageContractTestFn } from './contract.ts';
2
+ export interface FakeAnswer {
3
+ status?: number;
4
+ body?: unknown;
5
+ retryAfter?: string;
6
+ text?: string;
7
+ }
8
+ /** Deterministic HTTP responses, never an endpoint. Calls preserve the exact request. */
9
+ export declare function fakeFetch(initial?: FakeAnswer[]): {
10
+ fetch: typeof globalThis.fetch;
11
+ calls: {
12
+ url: string;
13
+ init?: RequestInit;
14
+ }[];
15
+ push: (...answers: FakeAnswer[]) => void;
16
+ };
17
+ export interface FakeCodexScript {
18
+ raw?: unknown;
19
+ corrupt?: boolean;
20
+ flood?: boolean;
21
+ hang?: boolean;
22
+ ignoreTerm?: boolean;
23
+ }
24
+ export interface FakeCodex {
25
+ bin: string;
26
+ script(value: FakeCodexScript): void;
27
+ invocations(): {
28
+ argv: string[];
29
+ env: Record<string, string>;
30
+ requests: unknown[];
31
+ }[];
32
+ }
33
+ /** Writes a fake app-server only under the caller's scratch directory. */
34
+ export declare function fakeCodex(options: {
35
+ dir: string;
36
+ raw?: unknown;
37
+ }): FakeCodex;
@@ -0,0 +1,48 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ export { usageContract } from "./contract.js";
4
+ /** Deterministic HTTP responses, never an endpoint. Calls preserve the exact request. */
5
+ export function fakeFetch(initial = []) {
6
+ const queue = [...initial];
7
+ const calls = [];
8
+ const fetch = async (url, init) => {
9
+ calls.push({ url: String(url), init });
10
+ const answer = queue.shift() ?? { status: 503 };
11
+ return new Response(answer.text ?? JSON.stringify(answer.body ?? {}), { status: answer.status ?? 200,
12
+ headers: answer.retryAfter === undefined ? {} : { 'retry-after': answer.retryAfter } });
13
+ };
14
+ return { fetch, calls, push: (...answers) => { queue.push(...answers); } };
15
+ }
16
+ /** Writes a fake app-server only under the caller's scratch directory. */
17
+ export function fakeCodex(options) {
18
+ mkdirSync(options.dir, { recursive: true });
19
+ const bin = join(options.dir, 'codex');
20
+ const script = join(options.dir, 'script.json');
21
+ const log = join(options.dir, 'calls.jsonl');
22
+ writeFileSync(script, JSON.stringify({ raw: options.raw }));
23
+ writeFileSync(log, '');
24
+ writeFileSync(bin, `#!${process.execPath}
25
+ const fs = require('node:fs');
26
+ const config = JSON.parse(fs.readFileSync(${JSON.stringify(script)}, 'utf8'));
27
+ const call = { argv: process.argv.slice(2), env: process.env, requests: [] };
28
+ if (config.ignoreTerm) process.on('SIGTERM', () => {});
29
+ let buffer = '';
30
+ process.stdin.setEncoding('utf8');
31
+ process.stdin.on('data', chunk => {
32
+ buffer += chunk;
33
+ for (;;) {
34
+ const i = buffer.indexOf('\\n'); if (i < 0) break;
35
+ const request = JSON.parse(buffer.slice(0, i)); buffer = buffer.slice(i + 1);
36
+ call.requests.push(request);
37
+ if (request.id === 1) console.log(JSON.stringify({ id: 1, result: {} }));
38
+ if (request.id === 2) {
39
+ fs.appendFileSync(${JSON.stringify(log)}, JSON.stringify(call) + '\\n');
40
+ if (config.hang) continue;
41
+ if (config.flood) { console.log('x'.repeat(65537)); continue; }
42
+ console.log(config.corrupt ? JSON.stringify({ id: 2, result: null }) : JSON.stringify({ id: 2, result: config.raw }));
43
+ }
44
+ }
45
+ });
46
+ `, { mode: 0o755 });
47
+ return { bin, script: (value) => writeFileSync(script, JSON.stringify(value)), invocations: () => readFileSync(log, 'utf8').split('\n').filter(Boolean).map((s) => JSON.parse(s)) };
48
+ }
@@ -0,0 +1,51 @@
1
+ export type Provider = 'claude' | 'codex' | 'opencode' | 'zai';
2
+ /** Claude's credential adapter belongs to the host; only its parser ships here. */
3
+ export type Source = {
4
+ provider: 'codex';
5
+ bin: string;
6
+ home: string;
7
+ env?: Record<string, string>;
8
+ } | {
9
+ provider: 'opencode';
10
+ key: string;
11
+ } | {
12
+ provider: 'zai';
13
+ key: string;
14
+ };
15
+ export type Kind = 'session' | 'weekly' | 'monthly' | 'rolling' | 'custom';
16
+ export type Window = {
17
+ provider: Provider;
18
+ kind: Kind;
19
+ limit?: string;
20
+ usedPercent: number;
21
+ minutes?: number;
22
+ resetsAt?: number;
23
+ limited?: boolean;
24
+ };
25
+ export type Code = 'not-connected' | 'expired' | 'auth' | 'no-plan' | 'rate-limited' | 'unavailable' | 'incomplete';
26
+ export type Reading = {
27
+ provider: Provider;
28
+ windows: Window[];
29
+ at: number;
30
+ code?: Code;
31
+ };
32
+ export type ReadOptions = {
33
+ nowMs?: number;
34
+ };
35
+ export type UsageOptions = {
36
+ stateDir: string;
37
+ salt?: string;
38
+ fetch?: typeof fetch;
39
+ now?: () => number;
40
+ };
41
+ export interface Usage {
42
+ read(source: Source, options?: ReadOptions): Promise<Reading>;
43
+ lastKnown(source: Source, options?: ReadOptions): Reading | undefined;
44
+ connected(source: Source): boolean;
45
+ account(source: Source): string | undefined;
46
+ }
47
+ export declare class UsageError extends Error {
48
+ readonly code = "bad-source";
49
+ name: string;
50
+ constructor();
51
+ }
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ export class UsageError extends Error {
2
+ code = 'bad-source';
3
+ name = 'UsageError';
4
+ constructor() { super('The app supplied an invalid usage source.'); }
5
+ }
@@ -0,0 +1,14 @@
1
+ import type { Window } from './types.ts';
2
+ export declare const record: (v: unknown) => v is Record<string, unknown>;
3
+ /** Accepts both the statusline envelope and the provider's usage payload. */
4
+ export declare function claudeWindows(raw: unknown): Window[];
5
+ /** Accepts the `usage` member; monthly length is deliberately absent. */
6
+ export declare function goWindows(raw: unknown): Window[];
7
+ /** Accepts the `data.limits` member; unknown bucket sizes are skipped. */
8
+ export declare function zaiWindows(raw: unknown): Window[];
9
+ /** Typed pass-through of the app-server rate-limit result. */
10
+ export interface CodexRateLimitResult {
11
+ rateLimitsByLimitId?: Record<string, unknown>;
12
+ rateLimits?: unknown;
13
+ }
14
+ export declare function codexWindows(result: CodexRateLimitResult | undefined): Window[];
@@ -0,0 +1,55 @@
1
+ export const record = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
2
+ const obj = (v) => record(v) ? v : {};
3
+ function window(provider, kind, used, minutes, resetsAt, limited = false, limit) {
4
+ if (typeof used !== 'number' || !Number.isFinite(used))
5
+ return [];
6
+ return [{ provider, kind, usedPercent: Math.max(0, Math.min(100, used)),
7
+ ...(minutes !== undefined && Number.isFinite(minutes) && minutes > 0 ? { minutes } : {}),
8
+ ...(Number.isFinite(resetsAt) ? { resetsAt } : {}), ...(limited ? { limited: true } : {}), ...(limit ? { limit } : {}) }];
9
+ }
10
+ /** Accepts both the statusline envelope and the provider's usage payload. */
11
+ export function claudeWindows(raw) {
12
+ const source = obj(obj(raw).rate_limits ?? raw);
13
+ return ['five_hour', 'seven_day'].flatMap((id) => {
14
+ const w = obj(source[id]);
15
+ return window('claude', id === 'five_hour' ? 'session' : 'weekly', Number.isFinite(w.utilization) ? w.utilization : w.used_percentage, id === 'five_hour' ? 300 : 10080, typeof w.resets_at === 'number' ? w.resets_at : Date.parse(String(w.resets_at)) / 1000);
16
+ });
17
+ }
18
+ /** Accepts the `usage` member; monthly length is deliberately absent. */
19
+ export function goWindows(raw) {
20
+ return ['rolling', 'weekly', 'monthly'].flatMap((kind) => {
21
+ const w = obj(obj(raw)[kind]);
22
+ if (typeof w.percent !== 'number' || w.percent < 0 || !['ok', 'rate-limited'].includes(String(w.status)))
23
+ return [];
24
+ return window('opencode', kind, w.percent, kind === 'monthly' ? undefined : kind === 'weekly' ? 10080 : 300, Date.parse(String(w.resetsAt)) / 1000, w.status === 'rate-limited');
25
+ });
26
+ }
27
+ /** Accepts the `data.limits` member; unknown bucket sizes are skipped. */
28
+ export function zaiWindows(raw) {
29
+ return (Array.isArray(raw) ? raw : []).flatMap((value) => {
30
+ const w = obj(value);
31
+ const key = `${w.unit}:${w.number}`;
32
+ if (key !== '3:5' && key !== '6:1')
33
+ return [];
34
+ return window('zai', key === '3:5' ? 'session' : 'weekly', w.percentage, key === '3:5' ? 300 : 10080, Number(w.nextResetTime) / 1000);
35
+ });
36
+ }
37
+ export function codexWindows(result) {
38
+ const limits = Object.values(obj(result?.rateLimitsByLimitId));
39
+ if (!limits.length && result?.rateLimits !== undefined)
40
+ limits.push(result.rateLimits);
41
+ const groups = limits.flatMap((raw) => {
42
+ if (!record(raw))
43
+ return [];
44
+ const name = String(raw.limitName ?? raw.limitId ?? 'Codex').replace(/[^\x20-\x7e]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 80) || 'Codex';
45
+ const rows = ['primary', 'secondary'].flatMap((key) => {
46
+ const w = obj(raw[key]);
47
+ const m = typeof w.windowDurationMins === 'number' && w.windowDurationMins > 0 && Number.isFinite(w.windowDurationMins) ? w.windowDurationMins : undefined;
48
+ return window('codex', m === 300 ? 'session' : m === 10080 ? 'weekly' : m === 43200 ? 'monthly' : 'custom', w.usedPercent, m, typeof w.resetsAt === 'number' ? w.resetsAt : undefined, false, name.toLowerCase() === 'codex' ? undefined : name);
49
+ }).sort((a, b) => (a.minutes ?? 0) - (b.minutes ?? 0));
50
+ return rows.length ? [rows] : [];
51
+ });
52
+ const chosen = groups.flat().sort((a, b) => b.usedPercent - a.usedPercent).slice(0, 8);
53
+ return groups.map((rows, ordinal) => ({ rows: rows.filter((w) => chosen.includes(w)), ordinal }))
54
+ .filter((g) => g.rows.length).sort((a, b) => Math.max(...b.rows.map((w) => w.usedPercent)) - Math.max(...a.rows.map((w) => w.usedPercent)) || a.ordinal - b.ordinal).flatMap((g) => g.rows);
55
+ }
@@ -0,0 +1,8 @@
1
+ import WORDS from './words.json' with { type: 'json' };
2
+ import type { Code } from './types.ts';
3
+ export { WORDS };
4
+ export type WordKey = keyof typeof WORDS;
5
+ export declare const words: (key: WordKey, vars?: Record<string, string>) => string;
6
+ export declare const usageWords: (code: Code, vars: {
7
+ name: string;
8
+ }) => string;
package/dist/words.js ADDED
@@ -0,0 +1,4 @@
1
+ import WORDS from './words.json' with { type: 'json' };
2
+ export { WORDS };
3
+ export const words = (key, vars = {}) => WORDS[key].replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`);
4
+ export const usageWords = (code, vars) => words(`code.${code}`, vars);
@@ -0,0 +1,9 @@
1
+ {
2
+ "code.not-connected": "{name} isn't signed in on this computer.",
3
+ "code.expired": "{name} needs a fresh sign-in in its own app.",
4
+ "code.auth": "{name} turned this sign-in down. Sign in again in its own app.",
5
+ "code.no-plan": "This {name} account has no plan with limits.",
6
+ "code.rate-limited": "{name} asked us to wait. Showing the last reading.",
7
+ "code.unavailable": "{name} didn't answer. Trying again shortly.",
8
+ "code.incomplete": "{name} answered in a way we can't read yet."
9
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@byokit/usage",
3
+ "version": "0.1.0",
4
+ "description": "Read subscription usage windows per provider and account.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/umeranjum17/byokit.git",
10
+ "directory": "packages/usage"
11
+ },
12
+ "engines": {
13
+ "node": ">=22.18"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ },
20
+ "./testing": {
21
+ "types": "./dist/testing/index.d.ts",
22
+ "default": "./dist/testing/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE",
29
+ "CHANGELOG.md"
30
+ ],
31
+ "scripts": {
32
+ "prepack": "tsc -b && node ../../scripts/fix-words-dts.cjs"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ }
37
+ }