limitcast 0.16.0 → 0.17.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/README.md +5 -4
- package/bin/limitcast.mjs +48 -0
- package/package.json +1 -1
- package/src/grok.mjs +245 -6
package/README.md
CHANGED
|
@@ -24,7 +24,7 @@ Your recorded Claude Code sessions start at 102.7k tokens before your first mess
|
|
|
24
24
|
- **Capacity report:** `limitcast results` separates recorded consumption by provider, applied protection decisions and historical previews, and estimated Claude context tokens not re-sent relative to a recorded baseline. Calls crossing a week boundary are counted in the period they happened. It also shows lifetime context estimates, forecast replay and next steps. Unknown evidence stays unavailable; controls are not converted into invented saved tokens.
|
|
25
25
|
- **Burn report:** Claude Code, Codex and Grok tokens by day, project, model and session.
|
|
26
26
|
- **Runout forecast (free):** burn rate and the clock time each window runs out.
|
|
27
|
-
- **Local only.** Reads the limit readings Claude Code passes to your status line and the logs Claude Code, Codex and Grok already write. No logins, and your usage data never leaves your machine. No license validation or payment-service connection is required. If you turn on phone or webhook notifications (off by default), each notification's text goes to the service you chose (ntfy.sh or your webhook) and nothing else.
|
|
27
|
+
- **Local only.** Reads the limit readings Claude Code passes to your status line and the logs Claude Code, Codex and Grok already write. No logins, and your usage data never leaves your machine. No license validation or payment-service connection is required. If you turn on phone or webhook notifications (off by default), each notification's text goes to the service you chose (ntfy.sh or your webhook) and nothing else. The one other exception is also off by default: `limitcast grok-usage on` reads the login Grok keeps in `~/.grok/auth.json` and sends it to grok.com, and nowhere else, to ask for your weekly Grok usage (details under Grok below).
|
|
28
28
|
|
|
29
29
|
| | Claude Code | Codex | Grok |
|
|
30
30
|
|---|---|---|---|
|
|
@@ -42,10 +42,10 @@ All features are now free. A guard previously installed in preview mode will enf
|
|
|
42
42
|
## Install
|
|
43
43
|
|
|
44
44
|
```sh
|
|
45
|
-
npm install -g
|
|
45
|
+
npm install -g limitcast # or: brew trust samstull9007/limitcast && brew install samstull9007/limitcast/limitcast
|
|
46
46
|
limitcast onboard # read-only: setup checks and a first useful result
|
|
47
47
|
limitcast install # free: status-line recorder
|
|
48
|
-
limitcast install --guard # also the subagent guard (free
|
|
48
|
+
limitcast install --guard # also the subagent guard (free; holds new subagents when a limit is on pace to run out)
|
|
49
49
|
limitcast doctor
|
|
50
50
|
```
|
|
51
51
|
|
|
@@ -55,7 +55,7 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
|
|
|
55
55
|
|
|
56
56
|
**Codex:** forecasts and reports need no setup (`~/.codex/sessions`, or `$CODEX_HOME/sessions`). With `--guard`, `install` also appends the guard to `~/.codex/hooks.json`, after your existing hooks so the ones you've already trusted keep their trust. Codex runs a new hook only once you approve it: start Codex and accept it. `limitcast doctor` shows whether it's trusted.
|
|
57
57
|
|
|
58
|
-
**Grok:** `report` reads each session's `~/.grok/sessions/*/*/usage.json` and prices Grok models at xAI list prices (the same API-equivalent column as Claude). `install` wraps `[ui.status_line]` in `~/.grok/config.toml` (session model, context % and cost on one line; the limitcast forecast under it). `--guard` writes `~/.grok/hooks/limitcast.json` matching `spawn_subagent`. Grok stores spend, not a % used, so the status line shows `grok 5h $X · 7d $Y` until you set a dollar cap (`limitcast budget grok <usd>`); then `status` forecasts that window and the guard blocks new spawns when it is on pace to run out. `limitcast subagent-model explore grok-4.3` writes `[subagents.models]` (restart Grok). Restart Grok to load the status line and hook.
|
|
58
|
+
**Grok:** `report` reads each session's `~/.grok/sessions/*/*/usage.json` and prices Grok models at xAI list prices (the same API-equivalent column as Claude). `install` wraps `[ui.status_line]` in `~/.grok/config.toml` (session model, context % and cost on one line; the limitcast forecast under it). `--guard` writes `~/.grok/hooks/limitcast.json` matching `spawn_subagent`. Grok stores spend, not a % used, so by default the status line shows `grok 5h $X · 7d $Y` until you set a dollar cap (`limitcast budget grok <usd>`); then `status` forecasts that window and the guard blocks new spawns when it is on pace to run out. For the real weekly %, run `limitcast grok-usage on`: about every 5 minutes limitcast reads the login Grok keeps in `~/.grok/auth.json` and asks grok.com for your billing cycle, the same request Grok Build makes. The login goes only to grok.com (redirects are refused) and is never stored or logged; the readings are kept locally, so `status`, the Grok status line and the guard forecast the weekly window like the Claude and Codex ones, and a weekly dollar cap steps aside for it. `limitcast grok-usage off` stops it, and `doctor` shows the last reading or why there is none (an expired login: run `grok login`). It tracks weekly plans only; a monthly credit plan is reported but not forecast. `limitcast subagent-model explore grok-4.3` writes `[subagents.models]` (restart Grok). Restart Grok to load the status line and hook.
|
|
59
59
|
|
|
60
60
|
## Commands
|
|
61
61
|
|
|
@@ -76,6 +76,7 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
|
|
|
76
76
|
| `limitcast results --html [--out FILE]` | Results, current windows and the burn report on one page, opened in your browser |
|
|
77
77
|
| `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
|
|
78
78
|
| `limitcast doctor [--fix]` | Check the setup, data freshness, this project's auto-memory index (see `memory`), and that Claude Code, Codex and Grok logs are still in a format limitcast reads. Also runs daily in the background and flags problems in the status line (the memory line only shows when you run `doctor` yourself). `--fix` re-installs with the current Node (after a Node upgrade) |
|
|
79
|
+
| `limitcast grok-usage [on\|off]` | Grok's real weekly % used, from grok.com with the login Grok already holds (off by default; see Grok above for exactly what it reads and sends). With no argument it shows the current reading |
|
|
79
80
|
| `limitcast memory [dir]` | Check this project's auto-memory folder (`~/.claude/projects/<project>/memory`): how much of `MEMORY.md` fits in what Claude Code loads each session (the first 200 lines or 25 KB; anything past that is never read), broken links, topic files nothing links to, and files over 150 lines. Read-only. In Claude Code, `/limitcast:memory-audit` takes it from there (stale, contradictory and unlinked notes) and `/limitcast:memory-split` splits an oversized file into a short hub plus topic files |
|
|
80
81
|
| `limitcast report [--days N] [--out FILE]` | Tokens by tool, day, project, model and session; subagent share; and the API-equivalent cost: what the tokens would cost at the API's list prices (Claude and Grok models; a subscription is not billed this way). Prices are in the code as of 2026-10-26; add or change a model in `~/.local/state/limitcast/prices.json` (`{"models": {"claude-opus-4-1": {"input": 15, "output": 75}}}`, dollars per million tokens) |
|
|
81
82
|
| `limitcast report --why [--days N]` | Where your new tokens went: subagents, session starts, cache rebuilds after idle, tool results by tool, model output, and the largest single steps (Claude Code only) |
|
package/bin/limitcast.mjs
CHANGED
|
@@ -30,6 +30,8 @@ import {
|
|
|
30
30
|
getGrokBudget,
|
|
31
31
|
grokConfigPath,
|
|
32
32
|
grokPresent,
|
|
33
|
+
grokQuotaDue,
|
|
34
|
+
grokQuotaEnabled,
|
|
33
35
|
grokSamples,
|
|
34
36
|
grokServers,
|
|
35
37
|
grokSessionLine,
|
|
@@ -37,7 +39,11 @@ import {
|
|
|
37
39
|
grokStartup,
|
|
38
40
|
grokTrimReport,
|
|
39
41
|
grokUsedServers,
|
|
42
|
+
readGrokQuota,
|
|
43
|
+
refreshGrokQuota,
|
|
40
44
|
setGrokBudget,
|
|
45
|
+
setGrokQuota,
|
|
46
|
+
touchGrokQuota,
|
|
41
47
|
undoGrokTrim,
|
|
42
48
|
} from '../src/grok.mjs';
|
|
43
49
|
import { runGuard } from '../src/guard.mjs';
|
|
@@ -89,6 +95,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
89
95
|
limitcast trim [--share] tokens every session loads before you type, and how much you never use
|
|
90
96
|
limitcast trim --codex the same for Codex: AGENTS.md size and MCP servers you haven't used
|
|
91
97
|
limitcast trim --grok the same for Grok: system prompt size and MCP servers you haven't used
|
|
98
|
+
limitcast grok-usage [on|off] Grok's weekly % used, from grok.com with the login Grok holds (off by default)
|
|
92
99
|
limitcast memory [dir] check this project's auto-memory: load cap, broken links, unlinked and oversized files
|
|
93
100
|
limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
|
|
94
101
|
[--share] totals only, safe to post
|
|
@@ -153,6 +160,7 @@ const days = () => {
|
|
|
153
160
|
};
|
|
154
161
|
|
|
155
162
|
if (cmd === 'status') {
|
|
163
|
+
if (grokQuotaEnabled() && grokPresent()) await refreshGrokQuota(now);
|
|
156
164
|
const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS)), ...grokSamples(now)]), now);
|
|
157
165
|
if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2));
|
|
158
166
|
else {
|
|
@@ -164,6 +172,10 @@ if (cmd === 'status') {
|
|
|
164
172
|
console.log(
|
|
165
173
|
`other Claude account (last used ${clock(a.lastSeen)}): ${a.rows.map((f) => `${f.win} ${f.verdict === 'RESET' ? 0 : Math.round(f.pct)}%${f.verdict === 'OK' || f.verdict === 'RESET' ? '' : ` ${f.verdict}`}`).join(' · ')}`,
|
|
166
174
|
);
|
|
175
|
+
const gq = grokQuotaEnabled() ? readGrokQuota() : null;
|
|
176
|
+
if (gq && !gq.ok) console.log(`grok: weekly usage unavailable (${gq.error ?? 'no reading yet'})`);
|
|
177
|
+
else if (gq?.label && gq.label !== 'Weekly')
|
|
178
|
+
console.log(`grok: your plan reports ${gq.label.toLowerCase()} usage (${Math.round(gq.pct ?? 0)}% used), which limitcast does not forecast`);
|
|
167
179
|
const spend = grokSpendLine(now);
|
|
168
180
|
if (spend) console.log(spend);
|
|
169
181
|
else if (existsSync(grokRoot()) && !rows.some((f) => f.src === 'grok'))
|
|
@@ -200,6 +212,15 @@ if (cmd === 'status') {
|
|
|
200
212
|
} catch {
|
|
201
213
|
/* never break the status line */
|
|
202
214
|
}
|
|
215
|
+
try {
|
|
216
|
+
// Grok's weekly % comes from grok.com (opt-in); refresh it in the background so no status line waits on the network.
|
|
217
|
+
if (grokQuotaDue(now)) {
|
|
218
|
+
touchGrokQuota(now);
|
|
219
|
+
spawn(process.execPath, [fileURLToPath(import.meta.url), 'grok-usage', '--refresh'], { detached: true, stdio: 'ignore' }).unref();
|
|
220
|
+
}
|
|
221
|
+
} catch {
|
|
222
|
+
/* never break the status line */
|
|
223
|
+
}
|
|
203
224
|
const sep = args.indexOf('--');
|
|
204
225
|
const wrapped = sep >= 0 ? args.slice(sep + 1) : [];
|
|
205
226
|
const grokOwn = grokSessionLine(feed);
|
|
@@ -517,6 +538,33 @@ if (cmd === 'status') {
|
|
|
517
538
|
if (mem) checks.push(mem);
|
|
518
539
|
for (const c of checks) console.log(`${c.ok ? '✓' : '✗'} ${c.line}`);
|
|
519
540
|
process.exit(checks.every((c) => c.ok) ? 0 : 1);
|
|
541
|
+
} else if (cmd === 'grok-usage') {
|
|
542
|
+
const arg = args.find((a) => !a.startsWith('-'));
|
|
543
|
+
if (args.includes('--refresh')) {
|
|
544
|
+
await refreshGrokQuota(now, { force: true }); // the background refresh the status line starts
|
|
545
|
+
} else if (arg && arg !== 'on' && arg !== 'off') {
|
|
546
|
+
console.log('usage: limitcast grok-usage [on|off]');
|
|
547
|
+
process.exit(2);
|
|
548
|
+
} else if (arg === 'on' && !grokPresent()) {
|
|
549
|
+
console.log('Grok is not installed here (no ~/.grok), so there is no usage to read.');
|
|
550
|
+
process.exit(1);
|
|
551
|
+
} else {
|
|
552
|
+
if (arg) setGrokQuota(arg === 'on');
|
|
553
|
+
if (arg === 'on')
|
|
554
|
+
console.log(
|
|
555
|
+
'Grok weekly usage is on. About every 5 minutes limitcast reads the login Grok keeps in ~/.grok/auth.json and asks grok.com for your usage, the way Grok Build does. The login goes only to grok.com and is never stored or logged. Turn it off: limitcast grok-usage off',
|
|
556
|
+
);
|
|
557
|
+
if (arg === 'off') console.log('Grok weekly usage is off. limitcast no longer reads your Grok login or contacts grok.com.');
|
|
558
|
+
else if (grokQuotaEnabled()) {
|
|
559
|
+
const q = await refreshGrokQuota(now, { force: arg === 'on' });
|
|
560
|
+
console.log(
|
|
561
|
+
q.ok
|
|
562
|
+
? `Grok ${q.label?.toLowerCase()}: ${Math.round(q.pct ?? 0)}% used${q.reset ? `, resets ${new Date(q.reset * 1000).toLocaleString()}` : ''}`
|
|
563
|
+
: `Grok usage unavailable: ${q.error ?? 'no reading yet'}`,
|
|
564
|
+
);
|
|
565
|
+
if (!q.ok) process.exit(1);
|
|
566
|
+
} else console.log('Grok weekly usage is off. Turn it on: limitcast grok-usage on');
|
|
567
|
+
}
|
|
520
568
|
} else if (cmd === 'memory') {
|
|
521
569
|
const dir = args.find((a) => !a.startsWith('-')) ?? memoryDir();
|
|
522
570
|
console.log(memoryReport(scanMemory(dir), dir));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "Stretch your Claude Code plan: measure what every session loads before you type, cut what you never use, and stop runaway subagents before they burn your window.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/grok.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { homedir } from 'node:os';
|
|
|
4
4
|
import { dirname, join } from 'node:path';
|
|
5
5
|
import { codexServers, setEnabled } from './codex.mjs';
|
|
6
6
|
import { windowMs } from './forecast.mjs';
|
|
7
|
-
import { stateDir } from './store.mjs';
|
|
7
|
+
import { KEEP_MS, stateDir } from './store.mjs';
|
|
8
8
|
import { grokRoot } from './usage.mjs';
|
|
9
9
|
|
|
10
10
|
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
@@ -202,21 +202,252 @@ export function grokSpend(now, root = grokRoot()) {
|
|
|
202
202
|
return out;
|
|
203
203
|
}
|
|
204
204
|
|
|
205
|
+
// Grok weekly %, opt-in (`limitcast grok-usage on`). Grok keeps no % on disk, so limitcast asks grok.com the same billing
|
|
206
|
+
// question Grok Build asks, with the login Grok already holds in auth.json. That login is read in this process, sent only to
|
|
207
|
+
// grok.com, and never stored or logged.
|
|
208
|
+
const QUOTA_URL = 'https://grok.com/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig';
|
|
209
|
+
const QUOTA_EVERY_MS = 5 * 60_000;
|
|
210
|
+
const quotaFile = () => join(stateDir(), 'grok-quota.json');
|
|
211
|
+
|
|
212
|
+
/** @typedef {{at:number, ok:boolean, error?:string, label?:string, pct?:number, reset?:number, readings:{t:number, pct:number, reset:number}[]}} QuotaState */
|
|
213
|
+
|
|
214
|
+
export function grokQuotaEnabled() {
|
|
215
|
+
try {
|
|
216
|
+
return JSON.parse(readFileSync(configFile(), 'utf8')).grokQuota === true;
|
|
217
|
+
} catch {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** @param {boolean} on */
|
|
223
|
+
export function setGrokQuota(on) {
|
|
224
|
+
let cfg = {};
|
|
225
|
+
try {
|
|
226
|
+
cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
|
|
227
|
+
} catch {
|
|
228
|
+
/* new */
|
|
229
|
+
}
|
|
230
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
231
|
+
writeFileSync(configFile(), JSON.stringify({ ...cfg, grokQuota: on }));
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** @returns {QuotaState} */
|
|
235
|
+
export function readGrokQuota() {
|
|
236
|
+
try {
|
|
237
|
+
return { at: 0, ok: false, readings: [], ...JSON.parse(readFileSync(quotaFile(), 'utf8')) };
|
|
238
|
+
} catch {
|
|
239
|
+
return { at: 0, ok: false, readings: [] };
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** @param {QuotaState} s */
|
|
244
|
+
function writeGrokQuota(s) {
|
|
245
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
246
|
+
writeFileSync(quotaFile(), JSON.stringify(s));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** True when the feature is on, Grok is installed, and the last attempt is older than the refresh interval. */
|
|
250
|
+
export function grokQuotaDue(now, home = grokHome()) {
|
|
251
|
+
return grokQuotaEnabled() && grokPresent(home) && now - readGrokQuota().at >= QUOTA_EVERY_MS;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Mark an attempt before a background refresh starts, so a burst of status lines starts only one. */
|
|
255
|
+
export function touchGrokQuota(now) {
|
|
256
|
+
writeGrokQuota({ ...readGrokQuota(), at: now });
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Protobuf fields of one message as [field, value, wireType]: varints as numbers, length-delimited as Buffers,
|
|
261
|
+
* fixed32 as its 4 bytes. Stops quietly at a truncated message.
|
|
262
|
+
* @param {Buffer} buf
|
|
263
|
+
* @returns {Generator<[number, any, number]>}
|
|
264
|
+
*/
|
|
265
|
+
function* fields(buf) {
|
|
266
|
+
let pos = 0;
|
|
267
|
+
const varint = () => {
|
|
268
|
+
let r = 0;
|
|
269
|
+
let mul = 1;
|
|
270
|
+
while (pos < buf.length) {
|
|
271
|
+
const b = buf[pos++];
|
|
272
|
+
r += (b & 0x7f) * mul;
|
|
273
|
+
if (!(b & 0x80)) return r;
|
|
274
|
+
mul *= 128;
|
|
275
|
+
}
|
|
276
|
+
return null;
|
|
277
|
+
};
|
|
278
|
+
while (pos < buf.length) {
|
|
279
|
+
const key = varint();
|
|
280
|
+
if (key === null) return;
|
|
281
|
+
const field = Math.floor(key / 8);
|
|
282
|
+
const wire = key % 8;
|
|
283
|
+
if (wire === 0) {
|
|
284
|
+
const v = varint();
|
|
285
|
+
if (v === null) return;
|
|
286
|
+
yield [field, v, 0];
|
|
287
|
+
} else if (wire === 1) {
|
|
288
|
+
if (pos + 8 > buf.length) return;
|
|
289
|
+
pos += 8;
|
|
290
|
+
} else if (wire === 2) {
|
|
291
|
+
const len = varint();
|
|
292
|
+
if (len === null || pos + len > buf.length) return;
|
|
293
|
+
yield [field, buf.subarray(pos, pos + len), 2];
|
|
294
|
+
pos += len;
|
|
295
|
+
} else if (wire === 5) {
|
|
296
|
+
if (pos + 4 > buf.length) return;
|
|
297
|
+
yield [field, buf.subarray(pos, pos + 4), 5];
|
|
298
|
+
pos += 4;
|
|
299
|
+
} else return;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Seconds of a protobuf Timestamp. @param {Buffer} msg */
|
|
304
|
+
const timestamp = (msg) => {
|
|
305
|
+
for (const [f, v, w] of fields(msg)) if (f === 1 && w === 0) return /** @type {number} */ (v);
|
|
306
|
+
return null;
|
|
307
|
+
};
|
|
308
|
+
|
|
205
309
|
/**
|
|
206
|
-
*
|
|
310
|
+
* The billing cycle from a gRPC-web `GetGrokCreditsConfig` reply: % used and the cycle's start and end (epoch seconds).
|
|
311
|
+
* Null when the reply holds no percentage.
|
|
312
|
+
* @param {Uint8Array} body
|
|
313
|
+
* @returns {{pct:number, start:number|null, end:number|null}|null}
|
|
314
|
+
*/
|
|
315
|
+
export function parseGrokBilling(body) {
|
|
316
|
+
const buf = Buffer.from(body);
|
|
317
|
+
for (let pos = 0; pos + 5 <= buf.length; ) {
|
|
318
|
+
const flag = buf[pos];
|
|
319
|
+
const len = buf.readUInt32BE(pos + 1);
|
|
320
|
+
pos += 5;
|
|
321
|
+
if (pos + len > buf.length) return null;
|
|
322
|
+
const payload = buf.subarray(pos, pos + len);
|
|
323
|
+
pos += len;
|
|
324
|
+
if (flag & 0x80) continue; // trailers
|
|
325
|
+
for (const [f, cfg, w] of fields(payload)) {
|
|
326
|
+
if (f !== 1 || w !== 2) continue;
|
|
327
|
+
let pct = null;
|
|
328
|
+
let start = null;
|
|
329
|
+
let end = null;
|
|
330
|
+
for (const [g, v, ww] of fields(cfg)) {
|
|
331
|
+
if (g === 1 && ww === 5) {
|
|
332
|
+
const x = v.readFloatLE(0);
|
|
333
|
+
if (Number.isFinite(x)) pct = Math.min(100, Math.max(0, x));
|
|
334
|
+
} else if (g === 4 && ww === 2) start = timestamp(v);
|
|
335
|
+
else if (g === 5 && ww === 2) end = timestamp(v);
|
|
336
|
+
}
|
|
337
|
+
if (pct !== null) return { pct, start, end };
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Grok's logins from auth.json, the auth.x.ai one first. @param {string} home */
|
|
344
|
+
function grokTokens(home) {
|
|
345
|
+
try {
|
|
346
|
+
const doc = JSON.parse(readFileSync(join(home, 'auth.json'), 'utf8'));
|
|
347
|
+
return Object.entries(doc ?? {})
|
|
348
|
+
.filter(([, v]) => typeof (/** @type {any} */ (v)?.key) === 'string' && /** @type {any} */ (v).key)
|
|
349
|
+
.sort(([a], [b]) => Number(b.includes('auth.x.ai')) - Number(a.includes('auth.x.ai')))
|
|
350
|
+
.map(([, v]) => /** @type {string} */ (/** @type {any} */ (v).key));
|
|
351
|
+
} catch {
|
|
352
|
+
return [];
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* @param {string} token
|
|
358
|
+
* @param {typeof fetch} fetchFn
|
|
359
|
+
*/
|
|
360
|
+
async function askGrok(token, fetchFn) {
|
|
361
|
+
let r;
|
|
362
|
+
try {
|
|
363
|
+
r = await fetchFn(QUOTA_URL, {
|
|
364
|
+
method: 'POST',
|
|
365
|
+
redirect: 'error', // the login must never follow a redirect to another host
|
|
366
|
+
signal: AbortSignal.timeout(8000),
|
|
367
|
+
headers: {
|
|
368
|
+
authorization: `Bearer ${token}`,
|
|
369
|
+
'x-xai-token-auth': 'xai-grok-cli',
|
|
370
|
+
accept: 'application/grpc-web+proto',
|
|
371
|
+
'content-type': 'application/grpc-web+proto',
|
|
372
|
+
'user-agent': 'Grok Build',
|
|
373
|
+
},
|
|
374
|
+
body: new Uint8Array([0, 0, 0, 0, 0]),
|
|
375
|
+
});
|
|
376
|
+
} catch {
|
|
377
|
+
throw new Error('could not reach grok.com');
|
|
378
|
+
}
|
|
379
|
+
if (r.status === 401 || r.status === 403) throw new Error('Grok login expired: run `grok login`');
|
|
380
|
+
if (!r.ok) throw new Error(`grok.com answered HTTP ${r.status}`);
|
|
381
|
+
return parseGrokBilling(new Uint8Array(await r.arrayBuffer()));
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Ask grok.com for the weekly % (at most every 5 minutes unless `force`), keep the reading, and say what happened.
|
|
386
|
+
* Never throws: a failure is recorded in the state for `status` and `doctor`.
|
|
387
|
+
* @param {number} now
|
|
388
|
+
* @param {{force?:boolean, home?:string, fetchFn?:typeof fetch}} [opts]
|
|
389
|
+
* @returns {Promise<QuotaState>}
|
|
390
|
+
*/
|
|
391
|
+
export async function refreshGrokQuota(now, { force = false, home = grokHome(), fetchFn = fetch } = {}) {
|
|
392
|
+
const prev = readGrokQuota();
|
|
393
|
+
if (!force && now - prev.at < QUOTA_EVERY_MS) return prev;
|
|
394
|
+
/** @type {QuotaState} */
|
|
395
|
+
const next = { ...prev, at: now, ok: false };
|
|
396
|
+
delete next.error;
|
|
397
|
+
const tokens = grokTokens(home);
|
|
398
|
+
if (!tokens.length) next.error = 'no Grok login found: run `grok login`';
|
|
399
|
+
for (const token of tokens) {
|
|
400
|
+
try {
|
|
401
|
+
const b = await askGrok(token, fetchFn);
|
|
402
|
+
if (!b) {
|
|
403
|
+
next.error = 'grok.com sent a billing reply limitcast does not recognise';
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
const days = b.start !== null && b.end !== null ? Math.trunc((b.end - b.start) / 86400) : null;
|
|
407
|
+
next.label = days !== null && days >= 6 && days <= 8 ? 'Weekly' : days !== null && days >= 27 && days <= 33 ? 'Monthly' : 'Credits';
|
|
408
|
+
next.ok = true;
|
|
409
|
+
next.pct = b.pct;
|
|
410
|
+
if (b.end !== null) next.reset = b.end;
|
|
411
|
+
delete next.error;
|
|
412
|
+
const last = next.readings[next.readings.length - 1];
|
|
413
|
+
if (next.label === 'Weekly' && b.end !== null && (!last || last.pct !== b.pct || last.reset !== b.end))
|
|
414
|
+
next.readings = [...next.readings, { t: now, pct: b.pct, reset: b.end }];
|
|
415
|
+
break;
|
|
416
|
+
} catch (e) {
|
|
417
|
+
next.error = e instanceof Error ? e.message : 'unknown error';
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
next.readings = next.readings.filter((r) => r.t >= now - KEEP_MS);
|
|
421
|
+
writeGrokQuota(next);
|
|
422
|
+
return next;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** Forecast samples from the recorded weekly readings; none unless the feature is on. @param {number} now @returns {Sample[]} */
|
|
426
|
+
export function grokQuotaSamples(now) {
|
|
427
|
+
if (!grokQuotaEnabled()) return [];
|
|
428
|
+
return readGrokQuota()
|
|
429
|
+
.readings.filter((r) => r.t >= now - KEEP_MS)
|
|
430
|
+
.map((r) => ({ t: r.t, src: 'grok', win: '7d', pct: r.pct, reset: r.reset }));
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Forecast samples for Grok: the real weekly % when `grok-usage` is on, plus spend against the user's dollar cap
|
|
435
|
+
* for the windows with a cap (a weekly cap steps aside for the real %). Empty without either.
|
|
207
436
|
* @param {number} now
|
|
208
437
|
* @param {{root?:string, budget?:ReturnType<typeof getGrokBudget>}} [opts]
|
|
209
438
|
* @returns {Sample[]}
|
|
210
439
|
*/
|
|
211
440
|
export function grokSamples(now, { root = grokRoot(), budget = getGrokBudget() } = {}) {
|
|
212
|
-
|
|
441
|
+
const quota = grokQuotaSamples(now);
|
|
442
|
+
if (!budget) return quota;
|
|
213
443
|
const since = now - windowMs('7d');
|
|
214
444
|
const turns = grokCosts(root, since);
|
|
215
445
|
/** @type {Sample[]} */
|
|
216
|
-
const out = [];
|
|
446
|
+
const out = [...quota];
|
|
217
447
|
for (const win of /** @type {const} */ (['5h', '7d'])) {
|
|
218
448
|
const cap = budget[win];
|
|
219
449
|
if (!(cap > 0)) continue;
|
|
450
|
+
if (win === '7d' && quota.length) continue;
|
|
220
451
|
const start = alignedStart(now, win);
|
|
221
452
|
const reset = (start + windowMs(win)) / 1000;
|
|
222
453
|
let spent = 0;
|
|
@@ -334,10 +565,18 @@ export function grokDoctor(home = grokHome()) {
|
|
|
334
565
|
line: guard ? 'Grok subagent guard installed' : 'Grok subagent guard not installed (optional: `limitcast install --guard`)',
|
|
335
566
|
});
|
|
336
567
|
const budget = getGrokBudget();
|
|
337
|
-
if (
|
|
568
|
+
if (grokQuotaEnabled()) {
|
|
569
|
+
const q = readGrokQuota();
|
|
570
|
+
const ago = q.at ? `${Math.max(0, Math.round((Date.now() - q.at) / 60_000))} min ago` : 'not yet';
|
|
571
|
+
out.push(
|
|
572
|
+
q.ok
|
|
573
|
+
? { ok: true, line: `Grok ${q.label?.toLowerCase() ?? 'usage'}: ${Math.round(q.pct ?? 0)}% used (checked ${ago})` }
|
|
574
|
+
: { ok: false, line: `Grok usage unavailable (checked ${ago}): ${q.error ?? 'no reading yet'}` },
|
|
575
|
+
);
|
|
576
|
+
} else if (guard && !budget)
|
|
338
577
|
out.push({
|
|
339
578
|
ok: true,
|
|
340
|
-
line: 'Grok has no % limit on disk: set a 5-hour dollar cap so the guard can block (`limitcast budget grok <usd>`)',
|
|
579
|
+
line: 'Grok has no % limit on disk: turn on the weekly % with `limitcast grok-usage on`, or set a 5-hour dollar cap so the guard can block (`limitcast budget grok <usd>`)',
|
|
341
580
|
});
|
|
342
581
|
else if (budget)
|
|
343
582
|
out.push({
|