chompyy 0.5.0 → 0.7.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 +14 -1
- package/dist/advice.js +98 -1
- package/dist/agentlimits.js +77 -0
- package/dist/agentusage.js +96 -0
- package/dist/approvals.js +129 -0
- package/dist/appstate.js +73 -3
- package/dist/away.js +48 -5
- package/dist/blueprint.js +3 -7
- package/dist/board.js +1 -0
- package/dist/cli.js +343 -18
- package/dist/codexquota.js +106 -0
- package/dist/codexusage.js +10 -0
- package/dist/config.js +2 -0
- package/dist/context.js +30 -0
- package/dist/costs.js +41 -2
- package/dist/demon.js +20 -0
- package/dist/detect.js +38 -6
- package/dist/didwork.js +26 -0
- package/dist/label.js +33 -0
- package/dist/menu.js +17 -0
- package/dist/nightcap.js +72 -0
- package/dist/nudge.js +70 -24
- package/dist/pacing.js +16 -1
- package/dist/punchcard.js +39 -0
- package/dist/questions.js +71 -0
- package/dist/recap.js +74 -0
- package/dist/receipt.js +48 -0
- package/dist/recipe.js +79 -0
- package/dist/savings.js +111 -0
- package/dist/stamps.js +14 -0
- package/dist/suggest.js +15 -5
- package/dist/triggers.js +5 -0
- package/dist/usage.js +21 -1
- package/dist/vendor/codeburn/antigravity.js +309 -0
- package/dist/vendor/codeburn/codex.js +429 -0
- package/dist/vendor/codeburn/copilot.js +292 -0
- package/dist/vendor/codeburn/gemini.js +195 -0
- package/dist/vendor/codeburn/grokbot.js +182 -0
- package/dist/vendor/codeburn/kimi.js +178 -0
- package/dist/vendor/codeburn/shims/chalk.js +14 -0
- package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
- package/dist/vendor/codeburn/src/act/backup.js +83 -0
- package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
- package/dist/vendor/codeburn/src/act/types.js +37 -0
- package/dist/vendor/codeburn/src/bash-utils.js +204 -0
- package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
- package/dist/vendor/codeburn/src/cache-dir.js +26 -0
- package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
- package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
- package/dist/vendor/codeburn/src/classifier.js +209 -0
- package/dist/vendor/codeburn/src/claude-identity.js +223 -0
- package/dist/vendor/codeburn/src/codex-cache.js +377 -0
- package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
- package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
- package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
- package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
- package/dist/vendor/codeburn/src/compare-stats.js +405 -0
- package/dist/vendor/codeburn/src/config.js +145 -0
- package/dist/vendor/codeburn/src/content-utils.js +56 -0
- package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
- package/dist/vendor/codeburn/src/context-tree.js +664 -0
- package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
- package/dist/vendor/codeburn/src/currency.js +189 -0
- package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
- package/dist/vendor/codeburn/src/cursor-import.js +402 -0
- package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
- package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
- package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
- package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
- package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
- package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
- package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
- package/dist/vendor/codeburn/src/format.js +118 -0
- package/dist/vendor/codeburn/src/fs-utils.js +270 -0
- package/dist/vendor/codeburn/src/git-origin.js +334 -0
- package/dist/vendor/codeburn/src/granular-history.js +328 -0
- package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
- package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
- package/dist/vendor/codeburn/src/live-sessions.js +358 -0
- package/dist/vendor/codeburn/src/math-utils.js +8 -0
- package/dist/vendor/codeburn/src/menubar-json.js +294 -0
- package/dist/vendor/codeburn/src/models.js +1879 -0
- package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
- package/dist/vendor/codeburn/src/optimize.js +4110 -0
- package/dist/vendor/codeburn/src/parse-workers.js +219 -0
- package/dist/vendor/codeburn/src/parser.js +6955 -0
- package/dist/vendor/codeburn/src/path-privacy.js +26 -0
- package/dist/vendor/codeburn/src/plans.js +135 -0
- package/dist/vendor/codeburn/src/pr-signals.js +132 -0
- package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
- package/dist/vendor/codeburn/src/provider-issues.js +30 -0
- package/dist/vendor/codeburn/src/providers/amp.js +286 -0
- package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
- package/dist/vendor/codeburn/src/providers/claude.js +551 -0
- package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
- package/dist/vendor/codeburn/src/providers/cline.js +63 -0
- package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
- package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
- package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
- package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
- package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
- package/dist/vendor/codeburn/src/providers/crush.js +226 -0
- package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
- package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
- package/dist/vendor/codeburn/src/providers/devin.js +569 -0
- package/dist/vendor/codeburn/src/providers/droid.js +324 -0
- package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
- package/dist/vendor/codeburn/src/providers/forge.js +245 -0
- package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
- package/dist/vendor/codeburn/src/providers/goose.js +252 -0
- package/dist/vendor/codeburn/src/providers/grok.js +581 -0
- package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
- package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
- package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
- package/dist/vendor/codeburn/src/providers/index.js +360 -0
- package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
- package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
- package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
- package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
- package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
- package/dist/vendor/codeburn/src/providers/mux.js +242 -0
- package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
- package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
- package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
- package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
- package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
- package/dist/vendor/codeburn/src/providers/pi.js +429 -0
- package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
- package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
- package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
- package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
- package/dist/vendor/codeburn/src/providers/types.js +5 -0
- package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
- package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
- package/dist/vendor/codeburn/src/providers/warp.js +575 -0
- package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
- package/dist/vendor/codeburn/src/providers/zed.js +187 -0
- package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
- package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
- package/dist/vendor/codeburn/src/quota/claude.js +244 -0
- package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
- package/dist/vendor/codeburn/src/quota/security.js +299 -0
- package/dist/vendor/codeburn/src/quota/types.js +1 -0
- package/dist/vendor/codeburn/src/scan-facts.js +99 -0
- package/dist/vendor/codeburn/src/session-cache.js +3040 -0
- package/dist/vendor/codeburn/src/session-count-label.js +14 -0
- package/dist/vendor/codeburn/src/session-output.js +139 -0
- package/dist/vendor/codeburn/src/session-population.js +30 -0
- package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
- package/dist/vendor/codeburn/src/sqlite.js +528 -0
- package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
- package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
- package/dist/vendor/codeburn/src/token-estimate.js +5 -0
- package/dist/vendor/codeburn/src/types.js +16 -0
- package/dist/vendor/codeburn/src/work-units.js +126 -0
- package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
- package/dist/vendor/codeburn/src/wsl.js +198 -0
- package/dist/vendor/codeburn/src/yield.js +666 -0
- package/dist/wastechecks.js +233 -0
- package/package.json +1 -1
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
// Live GitHub Copilot quota via the editor plugins' internal usage endpoint.
|
|
2
|
+
//
|
|
3
|
+
// - GET https://api.github.com/copilot_internal/user
|
|
4
|
+
// Headers mirror observed GitHub Copilot client traffic (Editor-Version /
|
|
5
|
+
// Editor-Plugin-Version / X-Github-Api-Version). This is an INTERNAL, UNDOCUMENTED
|
|
6
|
+
// API that may drift without notice; every failure must degrade to the
|
|
7
|
+
// normal connection states and never crash the panel.
|
|
8
|
+
//
|
|
9
|
+
// The host is not fixed. GitHub Enterprise Cloud with data residency puts an
|
|
10
|
+
// enterprise on its own hostname (`<tenant>.ghe.com`) whose API lives at
|
|
11
|
+
// `api.<tenant>.ghe.com`, so the credential carries the host it was read from
|
|
12
|
+
// and the endpoint follows it. A host we cannot derive an endpoint for fails
|
|
13
|
+
// naming that host rather than sending the credential to api.github.com
|
|
14
|
+
// (#1286). Self-hosted GitHub Enterprise Server is out of scope.
|
|
15
|
+
//
|
|
16
|
+
// Credential: the GitHub OAuth token already on disk from a signed-in Copilot
|
|
17
|
+
// plugin - hosts.json (keyed by host) falling back to apps.json (keyed by app
|
|
18
|
+
// name). The plugins write those under ~/.config/github-copilot on macOS and
|
|
19
|
+
// Linux but under %LOCALAPPDATA%\github-copilot on Windows, so the directory
|
|
20
|
+
// is resolved per platform. Read-only; no new storage.
|
|
21
|
+
import os from 'node:os';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import { fraction, quotaRequestSignal, readSecureFile, sanitizeError } from './security.js';
|
|
24
|
+
export const COPILOT_DEFAULT_HOST = 'github.com';
|
|
25
|
+
export const COPILOT_DEFAULT_API_HOST = 'api.github.com';
|
|
26
|
+
const ENTERPRISE_CLOUD_SUFFIX = '.ghe.com';
|
|
27
|
+
const USAGE_PATH = '/copilot_internal/user';
|
|
28
|
+
const HEADERS = {
|
|
29
|
+
Accept: 'application/json',
|
|
30
|
+
'Editor-Version': 'vscode/1.96.2',
|
|
31
|
+
'Editor-Plugin-Version': 'copilot-chat/0.26.7',
|
|
32
|
+
'User-Agent': 'GitHubCopilotChat/0.26.7',
|
|
33
|
+
'X-Github-Api-Version': '2025-04-01',
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Bare lowercased hostname: tolerates whitespace, a scheme, a path, userinfo
|
|
37
|
+
* and a port, because these keys are written by several different clients.
|
|
38
|
+
*/
|
|
39
|
+
export function normalizeCopilotHost(raw) {
|
|
40
|
+
let host = (raw ?? '').trim().toLowerCase();
|
|
41
|
+
if (!host)
|
|
42
|
+
return null;
|
|
43
|
+
const scheme = host.indexOf('://');
|
|
44
|
+
if (scheme !== -1)
|
|
45
|
+
host = host.slice(scheme + 3);
|
|
46
|
+
host = host.split('/')[0] ?? '';
|
|
47
|
+
const at = host.lastIndexOf('@');
|
|
48
|
+
if (at !== -1)
|
|
49
|
+
host = host.slice(at + 1);
|
|
50
|
+
host = host.split(':')[0] ?? '';
|
|
51
|
+
return host || null;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* API host serving Copilot quota for a credential's GitHub host, or null when
|
|
55
|
+
* this build cannot address it. A null `host` means the source carried none,
|
|
56
|
+
* which is dotcom.
|
|
57
|
+
*/
|
|
58
|
+
export function copilotAPIHost(host) {
|
|
59
|
+
const normalized = normalizeCopilotHost(host);
|
|
60
|
+
if (!normalized)
|
|
61
|
+
return COPILOT_DEFAULT_API_HOST;
|
|
62
|
+
// A URL delimiter that survives normalization would move the request off the
|
|
63
|
+
// host the suffix check approved: `evil.com?.ghe.com` ends in `.ghe.com` but
|
|
64
|
+
// builds a URL whose host is `api.evil.com`, which would then receive the
|
|
65
|
+
// Authorization header.
|
|
66
|
+
if (!/^[a-z0-9.-]+$/.test(normalized))
|
|
67
|
+
return null;
|
|
68
|
+
if (normalized === COPILOT_DEFAULT_HOST || normalized === COPILOT_DEFAULT_API_HOST)
|
|
69
|
+
return COPILOT_DEFAULT_API_HOST;
|
|
70
|
+
if (normalized.endsWith(ENTERPRISE_CLOUD_SUFFIX) && normalized.length > ENTERPRISE_CLOUD_SUFFIX.length) {
|
|
71
|
+
return normalized.startsWith('api.') ? normalized : `api.${normalized}`;
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
export function copilotUsageEndpoint(host) {
|
|
76
|
+
const apiHost = copilotAPIHost(host);
|
|
77
|
+
return apiHost ? `https://${apiHost}${USAGE_PATH}` : null;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Picks the host to query out of the hosts a credential file lists; a null
|
|
81
|
+
* entry stands for a source with no host of its own, i.e. dotcom. One entry is
|
|
82
|
+
* unambiguous and is used as-is even when unsupported, so the failure can name
|
|
83
|
+
* the host the user signed in to. With several, dotcom wins (what every
|
|
84
|
+
* non-enterprise client writes), else the first `.ghe.com` tenant in sorted
|
|
85
|
+
* order, so the pick is stable from one read to the next.
|
|
86
|
+
*/
|
|
87
|
+
export function preferredCopilotHost(hosts) {
|
|
88
|
+
const normalized = hosts.map(host => normalizeCopilotHost(host) ?? COPILOT_DEFAULT_HOST);
|
|
89
|
+
if (normalized.length === 0)
|
|
90
|
+
return null;
|
|
91
|
+
if (normalized.length === 1)
|
|
92
|
+
return normalized[0] ?? null;
|
|
93
|
+
if (normalized.includes(COPILOT_DEFAULT_HOST))
|
|
94
|
+
return COPILOT_DEFAULT_HOST;
|
|
95
|
+
const enterprise = normalized.filter(host => host.endsWith(ENTERPRISE_CLOUD_SUFFIX)).sort();
|
|
96
|
+
return enterprise[0] ?? normalized.slice().sort()[0] ?? null;
|
|
97
|
+
}
|
|
98
|
+
const CREDENTIAL_FILES = ['hosts.json', 'apps.json'];
|
|
99
|
+
/**
|
|
100
|
+
* apps.json keys look like `github.com:Iv1.<app id>` on the newer plugins and
|
|
101
|
+
* like a bare app name ("Visual Studio Code") on the older ones; only the
|
|
102
|
+
* former carries a host.
|
|
103
|
+
*/
|
|
104
|
+
function hostFromAppsKey(key) {
|
|
105
|
+
// A scheme ("https://acme.ghe.com:Iv1.x") would otherwise split at its own colon.
|
|
106
|
+
const scheme = /^[a-z]+:\/\//i.exec(key);
|
|
107
|
+
const rest = scheme ? key.slice(scheme[0].length) : key;
|
|
108
|
+
const separator = rest.search(/[:/]/);
|
|
109
|
+
if (separator === -1 && !scheme)
|
|
110
|
+
return null;
|
|
111
|
+
const candidate = separator === -1 ? rest : rest.slice(0, separator);
|
|
112
|
+
return candidate.includes('.') ? candidate : null;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Where the signed-in Copilot plugins keep hosts.json / apps.json. Windows has
|
|
116
|
+
* no ~/.config: the plugins follow the platform convention and write under
|
|
117
|
+
* %LOCALAPPDATA%. The XDG path stays as a second candidate there, because a
|
|
118
|
+
* token copied in from a POSIX-style shell (Git Bash, an MSYS home) lands in
|
|
119
|
+
* it and is just as valid.
|
|
120
|
+
*/
|
|
121
|
+
export function copilotConfigDirs(platform = process.platform, env = process.env, home = os.homedir()) {
|
|
122
|
+
const xdg = path.join(home, '.config', 'github-copilot');
|
|
123
|
+
if (platform !== 'win32')
|
|
124
|
+
return [xdg];
|
|
125
|
+
const localAppData = env['LOCALAPPDATA']?.trim() || path.join(home, 'AppData', 'Local');
|
|
126
|
+
return [path.join(localAppData, 'github-copilot'), xdg];
|
|
127
|
+
}
|
|
128
|
+
// Resolved per call rather than once at import so a caller (and the tests) can
|
|
129
|
+
// change the platform or the environment the paths are derived from.
|
|
130
|
+
function defaultDeps() {
|
|
131
|
+
return { fetch: globalThis.fetch, configDirs: copilotConfigDirs(), readFile: readSecureFile };
|
|
132
|
+
}
|
|
133
|
+
function empty(connection, footerLines = []) {
|
|
134
|
+
return { provider: 'copilot', connection, primary: null, details: [], planLabel: null, footerLines };
|
|
135
|
+
}
|
|
136
|
+
const hostKey = (credential) => normalizeCopilotHost(credential.host) ?? COPILOT_DEFAULT_HOST;
|
|
137
|
+
/**
|
|
138
|
+
* Reads the `oauth_token` entries out of a credential map, the one
|
|
139
|
+
* `preferredCopilotHost` picks first and the rest after it, so a refused token
|
|
140
|
+
* does not hide another host's login. Each token stays paired with the host of
|
|
141
|
+
* its own entry. Keys are visited in sorted order, making the order stable.
|
|
142
|
+
*/
|
|
143
|
+
function credentialsFromMap(raw, hostForKey) {
|
|
144
|
+
const map = JSON.parse(raw);
|
|
145
|
+
const entries = [];
|
|
146
|
+
for (const key of Object.keys(map).sort()) {
|
|
147
|
+
const token = map[key]?.oauth_token;
|
|
148
|
+
if (typeof token !== 'string' || !token)
|
|
149
|
+
continue;
|
|
150
|
+
entries.push({ token, host: hostForKey(key), key });
|
|
151
|
+
}
|
|
152
|
+
const preferred = preferredCopilotHost(entries.map(entry => entry.host));
|
|
153
|
+
const first = entries.find(entry => hostKey(entry) === preferred);
|
|
154
|
+
return first ? [first, ...entries.filter(entry => entry !== first)] : entries;
|
|
155
|
+
}
|
|
156
|
+
async function credentialsFromFile(dir, name, deps) {
|
|
157
|
+
try {
|
|
158
|
+
const raw = await deps.readFile(path.join(dir, name), 64 * 1024);
|
|
159
|
+
if (!raw)
|
|
160
|
+
return [];
|
|
161
|
+
// hosts.json is keyed by GitHub host, apps.json by "<host>:<app id>".
|
|
162
|
+
return credentialsFromMap(raw, name === 'hosts.json' ? key => key : hostFromAppsKey);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
// A malformed or unreadable file falls through to the next candidate.
|
|
166
|
+
return [];
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function windowOf(label, snapshot) {
|
|
170
|
+
if (!snapshot || typeof snapshot !== 'object')
|
|
171
|
+
return null;
|
|
172
|
+
const row = snapshot;
|
|
173
|
+
// The API reports percent REMAINING (0..100); windows render percent USED.
|
|
174
|
+
const rawRemaining = row.percent_remaining ?? row.percentRemaining;
|
|
175
|
+
const remaining = fraction(typeof rawRemaining === 'number' ? rawRemaining : NaN);
|
|
176
|
+
if (remaining === null)
|
|
177
|
+
return null;
|
|
178
|
+
// A plan without this quota reports entitlement 0 and 0% remaining, which
|
|
179
|
+
// would render as 100% used; unlimited windows have no meaningful percent.
|
|
180
|
+
if (row.entitlement === 0 || row.unlimited === true)
|
|
181
|
+
return null;
|
|
182
|
+
// Round away float dust from the 1-remaining subtraction (1-0.7 !== 0.3).
|
|
183
|
+
return { label, percent: Number((1 - remaining).toFixed(6)), resetsAt: null };
|
|
184
|
+
}
|
|
185
|
+
function planLabel(value) {
|
|
186
|
+
if (typeof value !== 'string' || !value.trim())
|
|
187
|
+
return null;
|
|
188
|
+
const lower = value.trim().toLowerCase();
|
|
189
|
+
const known = {
|
|
190
|
+
free: 'Free', individual: 'Individual', pro: 'Pro', business: 'Business',
|
|
191
|
+
enterprise: 'Enterprise', for_educators: 'Educators', 'for-educators': 'Educators',
|
|
192
|
+
};
|
|
193
|
+
return known[lower] ?? lower.replace(/(^|[_-])\w/g, match => match.replace(/[_-]/, ' ').toUpperCase());
|
|
194
|
+
}
|
|
195
|
+
export function decodeCopilotUsage(body, apiHost = COPILOT_DEFAULT_API_HOST) {
|
|
196
|
+
const data = body && typeof body === 'object' ? body : {};
|
|
197
|
+
// Field names have shipped both camelCase and snake_case; read each alias
|
|
198
|
+
// rather than trusting one spelling.
|
|
199
|
+
const snapshots = data.quota_snapshots ?? data.quotaSnapshots;
|
|
200
|
+
const premium = windowOf('Premium requests', snapshots?.premium_interactions ?? snapshots?.premiumInteractions);
|
|
201
|
+
const chat = windowOf('Chat', snapshots?.chat);
|
|
202
|
+
const details = [premium, chat].filter((row) => row !== null);
|
|
203
|
+
return {
|
|
204
|
+
provider: 'copilot', connection: 'connected', primary: premium ?? chat,
|
|
205
|
+
details,
|
|
206
|
+
planLabel: planLabel(data.copilot_plan ?? data.copilotPlan),
|
|
207
|
+
// Name the endpoint when it is not dotcom, so an enterprise tenant can see
|
|
208
|
+
// which host answered.
|
|
209
|
+
footerLines: apiHost === COPILOT_DEFAULT_API_HOST ? [] : [`Source: ${apiHost}`],
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function unsupportedHostFooter(host) {
|
|
213
|
+
return `Copilot quota is not available for the GitHub host ${host}. `
|
|
214
|
+
+ 'CodeBurn can read github.com and GitHub Enterprise Cloud (*.ghe.com) hosts.';
|
|
215
|
+
}
|
|
216
|
+
async function request(credential, endpoint, deps, parent) {
|
|
217
|
+
return deps.fetch(endpoint, {
|
|
218
|
+
method: 'GET', signal: quotaRequestSignal(parent),
|
|
219
|
+
headers: { ...HEADERS, Authorization: `token ${credential.token}` },
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
export async function fetchCopilotQuota(options = {}) {
|
|
223
|
+
const deps = { ...defaultDeps(), ...options };
|
|
224
|
+
let apiHost = COPILOT_DEFAULT_API_HOST;
|
|
225
|
+
try {
|
|
226
|
+
const found = [];
|
|
227
|
+
for (const dir of deps.configDirs) {
|
|
228
|
+
for (const name of CREDENTIAL_FILES) {
|
|
229
|
+
for (const credential of await credentialsFromFile(dir, name, deps)) {
|
|
230
|
+
found.push({ dir, name, credential, endpoint: copilotUsageEndpoint(credential.host) });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (found.length === 0)
|
|
235
|
+
return { quota: empty('disconnected') };
|
|
236
|
+
// A host we cannot address, or a token the API refuses, must not hide a
|
|
237
|
+
// working login in the next entry, file or folder.
|
|
238
|
+
const usable = found.filter(entry => entry.endpoint !== null);
|
|
239
|
+
if (usable.length === 0) {
|
|
240
|
+
// Never retried against api.github.com: that endpoint does not honour an
|
|
241
|
+
// enterprise credential and must not receive it.
|
|
242
|
+
return { quota: empty('terminalFailure', [unsupportedHostFooter(hostKey(found[0].credential))]) };
|
|
243
|
+
}
|
|
244
|
+
const refused = (value) => value.status === 401 || value.status === 403;
|
|
245
|
+
const reread = async (entry) => (await credentialsFromFile(entry.dir, entry.name, deps)).find(value => value.key === entry.credential.key);
|
|
246
|
+
// The same login copied into several entries is sent once per run.
|
|
247
|
+
const tried = new Set();
|
|
248
|
+
const attempt = (credential) => `${hostKey(credential)} ${credential.token}`;
|
|
249
|
+
// null: the last token got a 401 and the disk held no newer one.
|
|
250
|
+
let response = null;
|
|
251
|
+
for (const entry of usable) {
|
|
252
|
+
let credential = entry.credential;
|
|
253
|
+
if (tried.has(attempt(credential))) {
|
|
254
|
+
// Already refused this run; only a rotation since the read makes it worth a request.
|
|
255
|
+
credential = await reread(entry);
|
|
256
|
+
if (!credential || tried.has(attempt(credential)))
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
apiHost = copilotAPIHost(credential.host) ?? apiHost;
|
|
260
|
+
tried.add(attempt(credential));
|
|
261
|
+
response = await request(credential, entry.endpoint, deps, options.signal);
|
|
262
|
+
if (!refused(response))
|
|
263
|
+
break;
|
|
264
|
+
// An active editor session rotates this token; re-read once before
|
|
265
|
+
// giving up so we don't report a failure the disk already fixed.
|
|
266
|
+
const rotated = await reread(entry);
|
|
267
|
+
if (!rotated || tried.has(attempt(rotated))) {
|
|
268
|
+
if (response.status === 401)
|
|
269
|
+
response = null;
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
tried.add(attempt(rotated));
|
|
273
|
+
response = await request(rotated, entry.endpoint, deps, options.signal);
|
|
274
|
+
if (!refused(response))
|
|
275
|
+
break;
|
|
276
|
+
}
|
|
277
|
+
if (!response)
|
|
278
|
+
return { quota: empty('transientFailure') };
|
|
279
|
+
if (response.status === 429) {
|
|
280
|
+
const raw = response.headers.get('Retry-After');
|
|
281
|
+
const seconds = raw === null ? NaN : Number(raw);
|
|
282
|
+
return { quota: empty('transientFailure'), retryAfterSeconds: Math.max(Number.isFinite(seconds) ? Math.ceil(seconds) : 300, 60) };
|
|
283
|
+
}
|
|
284
|
+
if (!response.ok)
|
|
285
|
+
return { quota: { ...empty(response.status >= 400 && response.status < 500 ? 'terminalFailure' : 'transientFailure'), ...(response.status === 401 || response.status === 403 ? { connectable: true } : {}) } };
|
|
286
|
+
return { quota: decodeCopilotUsage(await response.json(), apiHost) };
|
|
287
|
+
}
|
|
288
|
+
catch (error) {
|
|
289
|
+
console.warn(`Copilot quota unavailable from ${apiHost}: ${sanitizeError(error)}`);
|
|
290
|
+
return { quota: empty('transientFailure') };
|
|
291
|
+
}
|
|
292
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Live Gemini quota via the OAuth-backed Code Assist APIs the Gemini CLI
|
|
2
|
+
// itself calls, derived from the Google Code Assist client flow and the CLI's
|
|
3
|
+
// own traffic:
|
|
4
|
+
//
|
|
5
|
+
// - POST https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist
|
|
6
|
+
// body { metadata: { ideType: 'GEMINI_CLI', pluginType: 'GEMINI' } }
|
|
7
|
+
// → tier (plan label), cloudaicompanionProject (quota project)
|
|
8
|
+
// - POST https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota
|
|
9
|
+
// body { project } (or {} when unknown) → per-model quota buckets
|
|
10
|
+
// - POST https://oauth2.googleapis.com/token (only when the stored token is
|
|
11
|
+
// stale and GEMINI_OAUTH_CLIENT_ID/GEMINI_OAUTH_CLIENT_SECRET are set;
|
|
12
|
+
// the refreshed token stays in memory — the Gemini CLI owns its file)
|
|
13
|
+
//
|
|
14
|
+
// Credential: the Gemini CLI's own ~/.gemini/oauth_creds.json, read-only.
|
|
15
|
+
import os from 'node:os';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { fraction, quotaRequestSignal, readSecureFile, sanitizeError } from './security.js';
|
|
18
|
+
const CODE_ASSIST_ENDPOINT = 'https://cloudcode-pa.googleapis.com/v1internal';
|
|
19
|
+
const TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';
|
|
20
|
+
const defaults = {
|
|
21
|
+
fetch: globalThis.fetch,
|
|
22
|
+
credentialPath: path.join(os.homedir(), '.gemini', 'oauth_creds.json'),
|
|
23
|
+
readFile: readSecureFile,
|
|
24
|
+
now: Date.now,
|
|
25
|
+
};
|
|
26
|
+
function empty(connection, footerLines = []) {
|
|
27
|
+
return { provider: 'gemini', connection, primary: null, details: [], planLabel: null, footerLines };
|
|
28
|
+
}
|
|
29
|
+
function parseCredential(raw) {
|
|
30
|
+
const parsed = JSON.parse(raw);
|
|
31
|
+
if (!parsed || typeof parsed.access_token !== 'string' || parsed.access_token.length === 0)
|
|
32
|
+
return null;
|
|
33
|
+
return parsed;
|
|
34
|
+
}
|
|
35
|
+
async function credentialFromFile(deps) {
|
|
36
|
+
const raw = await deps.readFile(deps.credentialPath, 64 * 1024);
|
|
37
|
+
return raw ? parseCredential(raw) : null;
|
|
38
|
+
}
|
|
39
|
+
// Client credentials live inside the installed Gemini CLI bundle; scanning the
|
|
40
|
+
// install is out of scope here, so only the CLI's documented env overrides are
|
|
41
|
+
// honored. Without them an expired token is used as-is and a 401 degrades.
|
|
42
|
+
function clientCredentials() {
|
|
43
|
+
const clientId = process.env['GEMINI_OAUTH_CLIENT_ID'];
|
|
44
|
+
const clientSecret = process.env['GEMINI_OAUTH_CLIENT_SECRET'];
|
|
45
|
+
return clientId && clientSecret ? { clientId, clientSecret } : null;
|
|
46
|
+
}
|
|
47
|
+
async function refresh(credential, deps, signal) {
|
|
48
|
+
const client = clientCredentials();
|
|
49
|
+
const refreshToken = credential.refresh_token;
|
|
50
|
+
if (!client || !refreshToken)
|
|
51
|
+
return null;
|
|
52
|
+
const body = new URLSearchParams({
|
|
53
|
+
client_id: client.clientId,
|
|
54
|
+
client_secret: client.clientSecret,
|
|
55
|
+
refresh_token: refreshToken,
|
|
56
|
+
grant_type: 'refresh_token',
|
|
57
|
+
});
|
|
58
|
+
const response = await deps.fetch(TOKEN_ENDPOINT, { method: 'POST', signal: quotaRequestSignal(signal), body });
|
|
59
|
+
if (!response.ok)
|
|
60
|
+
return null;
|
|
61
|
+
const next = await response.json();
|
|
62
|
+
return typeof next.access_token === 'string' && next.access_token ? next.access_token : null;
|
|
63
|
+
}
|
|
64
|
+
// The `hd` claim (hosted domain) separates Google Workspace logins from
|
|
65
|
+
// personal ones, matching the provider's tier labels.
|
|
66
|
+
function workspaceClaim(idToken) {
|
|
67
|
+
if (!idToken)
|
|
68
|
+
return false;
|
|
69
|
+
const [, payload] = idToken.split('.');
|
|
70
|
+
if (!payload)
|
|
71
|
+
return false;
|
|
72
|
+
try {
|
|
73
|
+
const json = JSON.parse(Buffer.from(payload.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
|
|
74
|
+
return typeof json.hd === 'string' && json.hd.length > 0;
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function tierLabel(body, credential) {
|
|
81
|
+
// paidTier wins whenever present; otherwise whatever tier the account sits on.
|
|
82
|
+
const raw = body.paidTier?.name ?? body.currentTier?.name ?? body.currentTier?.id;
|
|
83
|
+
if (typeof raw !== 'string' || !raw.trim())
|
|
84
|
+
return null;
|
|
85
|
+
const lower = raw.trim().toLowerCase();
|
|
86
|
+
if (lower === 'standard-tier')
|
|
87
|
+
return 'Paid';
|
|
88
|
+
if (lower === 'legacy-tier')
|
|
89
|
+
return 'Legacy';
|
|
90
|
+
if (lower.includes('free') && workspaceClaim(credential.id_token))
|
|
91
|
+
return 'Workspace';
|
|
92
|
+
if (lower.includes('free'))
|
|
93
|
+
return 'Free';
|
|
94
|
+
return raw.trim();
|
|
95
|
+
}
|
|
96
|
+
function windowOf(bucket) {
|
|
97
|
+
const modelId = bucket.modelId;
|
|
98
|
+
const remaining = fraction(typeof bucket.remainingFraction === 'number' ? bucket.remainingFraction * 100 : NaN);
|
|
99
|
+
if (typeof modelId !== 'string' || !modelId || remaining === null)
|
|
100
|
+
return null;
|
|
101
|
+
const resetTime = bucket.resetTime;
|
|
102
|
+
const resetsAt = typeof resetTime === 'string' && !Number.isNaN(Date.parse(resetTime))
|
|
103
|
+
? new Date(resetTime).toISOString() : null;
|
|
104
|
+
return { label: modelId, percent: 1 - remaining, resetsAt };
|
|
105
|
+
}
|
|
106
|
+
export function decodeGeminiUsage(body) {
|
|
107
|
+
const data = body && typeof body === 'object' ? body : {};
|
|
108
|
+
const buckets = Array.isArray(data.buckets) ? data.buckets : [];
|
|
109
|
+
const details = buckets
|
|
110
|
+
.filter((bucket) => Boolean(bucket) && typeof bucket === 'object')
|
|
111
|
+
.map(windowOf)
|
|
112
|
+
.filter((window) => window !== null)
|
|
113
|
+
.sort((a, b) => b.percent - a.percent);
|
|
114
|
+
return {
|
|
115
|
+
provider: 'gemini', connection: 'connected',
|
|
116
|
+
primary: details[0] ?? null,
|
|
117
|
+
details,
|
|
118
|
+
planLabel: null,
|
|
119
|
+
footerLines: [],
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
async function post(token, path, payload, deps, parent) {
|
|
123
|
+
return deps.fetch(`${CODE_ASSIST_ENDPOINT}:${path}`, {
|
|
124
|
+
method: 'POST', signal: quotaRequestSignal(parent),
|
|
125
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json', 'User-Agent': 'chompyy/0.1 (+https://github.com/BranchWork-HQ/Chompyy)' },
|
|
126
|
+
body: JSON.stringify(payload),
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
// Google flags retired consumer tiers (June 2026 shutdown of individual/AI
|
|
130
|
+
// Pro/Ultra OAuth access) with these sentinels instead of ordinary errors.
|
|
131
|
+
function migrationFooter(body) {
|
|
132
|
+
const error = body && typeof body === 'object' ? body.error : null;
|
|
133
|
+
const status = typeof error?.status === 'string' ? error.status : '';
|
|
134
|
+
const message = typeof error?.message === 'string' ? error.message : '';
|
|
135
|
+
const deprecated = status === 'UNSUPPORTED_CLIENT' || message.includes('IneligibleTierError');
|
|
136
|
+
return deprecated ? ['Google retired Gemini CLI OAuth for this account tier — use Antigravity.'] : [];
|
|
137
|
+
}
|
|
138
|
+
export async function fetchGeminiQuota(options = {}) {
|
|
139
|
+
const deps = { ...defaults, ...options };
|
|
140
|
+
try {
|
|
141
|
+
let credential = await credentialFromFile(deps);
|
|
142
|
+
if (!credential)
|
|
143
|
+
return { quota: empty('disconnected') };
|
|
144
|
+
if ((credential.expiry_date ?? Infinity) - deps.now() <= 5 * 60_000) {
|
|
145
|
+
const accessToken = await refresh(credential, deps, options.signal);
|
|
146
|
+
if (accessToken)
|
|
147
|
+
credential = { ...credential, access_token: accessToken };
|
|
148
|
+
}
|
|
149
|
+
const token = credential.access_token;
|
|
150
|
+
let response = await post(token, 'loadCodeAssist', { metadata: { ideType: 'GEMINI_CLI', pluginType: 'GEMINI' } }, deps, options.signal);
|
|
151
|
+
if (response.status === 401) {
|
|
152
|
+
const reread = await credentialFromFile(deps);
|
|
153
|
+
// Gemini has no keychain and no in-process refresh without the CLI's env
|
|
154
|
+
// overrides, so a 401 whose re-read token is unchanged is an expired login
|
|
155
|
+
// only the Gemini CLI can fix — a terminal, actionable state (matching the
|
|
156
|
+
// menubar's .tokenExpired), never an open-ended "waiting".
|
|
157
|
+
if (!reread || reread.access_token === credential.access_token) {
|
|
158
|
+
return { quota: { ...empty('terminalFailure', ['Gemini login expired. Run the Gemini CLI once to refresh, then try again.']), connectable: true } };
|
|
159
|
+
}
|
|
160
|
+
credential = reread;
|
|
161
|
+
response = await post(credential.access_token, 'loadCodeAssist', { metadata: { ideType: 'GEMINI_CLI', pluginType: 'GEMINI' } }, deps, options.signal);
|
|
162
|
+
}
|
|
163
|
+
if (response.status === 429) {
|
|
164
|
+
const raw = response.headers.get('Retry-After');
|
|
165
|
+
const seconds = raw === null ? NaN : Number(raw);
|
|
166
|
+
return { quota: empty('transientFailure'), retryAfterSeconds: Math.max(Number.isFinite(seconds) ? Math.ceil(seconds) : 300, 60) };
|
|
167
|
+
}
|
|
168
|
+
// Retired-tier sentinels ride inside the JSON error body of a non-200
|
|
169
|
+
// response, so parse before branching on status.
|
|
170
|
+
const assist = await response.json().catch(() => ({}));
|
|
171
|
+
const migration = migrationFooter(assist);
|
|
172
|
+
if (migration.length > 0)
|
|
173
|
+
return { quota: empty('terminalFailure', migration) };
|
|
174
|
+
if (!response.ok)
|
|
175
|
+
return { quota: { ...empty(response.status >= 400 && response.status < 500 ? 'terminalFailure' : 'transientFailure'), ...(response.status === 401 || response.status === 403 ? { connectable: true } : {}) } };
|
|
176
|
+
const project = typeof assist.cloudaicompanionProject === 'string' && assist.cloudaicompanionProject
|
|
177
|
+
? assist.cloudaicompanionProject : undefined;
|
|
178
|
+
const quotaResponse = await post(credential.access_token, 'retrieveUserQuota', project ? { project } : {}, deps, options.signal);
|
|
179
|
+
if (quotaResponse.status === 429) {
|
|
180
|
+
const raw = quotaResponse.headers.get('Retry-After');
|
|
181
|
+
const seconds = raw === null ? NaN : Number(raw);
|
|
182
|
+
return { quota: empty('transientFailure'), retryAfterSeconds: Math.max(Number.isFinite(seconds) ? Math.ceil(seconds) : 300, 60) };
|
|
183
|
+
}
|
|
184
|
+
if (!quotaResponse.ok) {
|
|
185
|
+
return { quota: { ...empty(quotaResponse.status >= 400 && quotaResponse.status < 500 ? 'terminalFailure' : 'transientFailure'), ...(quotaResponse.status === 401 || quotaResponse.status === 403 ? { connectable: true } : {}) } };
|
|
186
|
+
}
|
|
187
|
+
const quota = decodeGeminiUsage(await quotaResponse.json());
|
|
188
|
+
quota.planLabel = tierLabel(assist, credential);
|
|
189
|
+
return { quota };
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
console.warn(`Gemini quota unavailable: ${sanitizeError(error)}`);
|
|
193
|
+
return { quota: empty('transientFailure') };
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Live Grok Bot weekly allowance (ported from src/quota/grokbot.ts, which the
|
|
2
|
+
// CLI uses, and from the menubar's GrokBotSubscriptionService.swift):
|
|
3
|
+
//
|
|
4
|
+
// - POST https://api2.cursor.sh/aiserver.v1.DashboardService/GetSandUsageStatus
|
|
5
|
+
// Connect-RPC, empty JSON body, `Authorization: Bearer <cursor token>`.
|
|
6
|
+
// Response: usagePercent (0..100), nextResetTimestampUtc,
|
|
7
|
+
// hasNonZeroIncludedLimit, usesPooledEnterpriseAllowance, grokPlanLabel.
|
|
8
|
+
//
|
|
9
|
+
// Credential: the Cursor IDE's OWN access token, unencrypted in its VS Code
|
|
10
|
+
// state database under `cursorAuth/accessToken`, opened read-only. Grok Bot
|
|
11
|
+
// keeps its own copy of the same Cursor session in Electron safe storage, which
|
|
12
|
+
// CodeBurn never decrypts, so this reading is Grok Bot's only while the Cursor
|
|
13
|
+
// app is signed into the account Grok Bot uses.
|
|
14
|
+
import { existsSync } from 'node:fs';
|
|
15
|
+
import os from 'node:os';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { quotaRequestSignal, sanitizeError } from './security.js';
|
|
18
|
+
const USAGE_ENDPOINT = 'https://api2.cursor.sh/aiserver.v1.DashboardService/GetSandUsageStatus';
|
|
19
|
+
const ACCESS_TOKEN_KEY = 'cursorAuth/accessToken';
|
|
20
|
+
const SOURCE_FOOTER = ['Source: Cursor dashboard (the account the Cursor app is signed into)'];
|
|
21
|
+
const SIGNED_OUT_FOOTER = ['Sign in to the Cursor app with the account Grok Bot uses, then Refresh.'];
|
|
22
|
+
const REJECTED_FOOTER = ['Cursor rejected the current app session. Sign in again, then Refresh.'];
|
|
23
|
+
const UNREADABLE_FOOTER = ["Could not read the Cursor app's local session data. Quit and reopen Cursor, then Refresh."];
|
|
24
|
+
const RATE_LIMITED_FOOTER = ['Cursor rate-limited the quota request.'];
|
|
25
|
+
const UNAVAILABLE_FOOTER = ['Grok Bot quota is temporarily unavailable.'];
|
|
26
|
+
const PARSE_FOOTER = ['Cursor returned an unrecognized Grok Bot quota response.'];
|
|
27
|
+
const NO_ALLOWANCE_FOOTER = ['This account has no included Grok Bot allowance.'];
|
|
28
|
+
const POOLED_FOOTER = ['Grok Bot usage is drawn from a pooled enterprise allowance, which has no per-account reading.'];
|
|
29
|
+
/** Cursor is an Electron app, so its state database follows the VS Code layout
|
|
30
|
+
* of whichever platform it runs on. */
|
|
31
|
+
export function cursorDatabasePath(platform = process.platform, home = os.homedir()) {
|
|
32
|
+
if (platform === 'darwin') {
|
|
33
|
+
return path.join(home, 'Library', 'Application Support', 'Cursor', 'User', 'globalStorage', 'state.vscdb');
|
|
34
|
+
}
|
|
35
|
+
if (platform === 'win32') {
|
|
36
|
+
return path.join(home, 'AppData', 'Roaming', 'Cursor', 'User', 'globalStorage', 'state.vscdb');
|
|
37
|
+
}
|
|
38
|
+
return path.join(home, '.config', 'Cursor', 'User', 'globalStorage', 'state.vscdb');
|
|
39
|
+
}
|
|
40
|
+
/** The app is a normal drag-install, so either Applications folder counts;
|
|
41
|
+
* `~/.grokbot` is its data root, which survives a moved bundle. */
|
|
42
|
+
export function grokbotInstalled(platform = process.platform, home = os.homedir(), systemApplications = '/Applications') {
|
|
43
|
+
const bundles = platform === 'darwin'
|
|
44
|
+
? [path.join(systemApplications, 'Grok Bot.app'), path.join(home, 'Applications', 'Grok Bot.app')]
|
|
45
|
+
: [];
|
|
46
|
+
return [...bundles, path.join(home, '.grokbot')].some(existsSync);
|
|
47
|
+
}
|
|
48
|
+
/** Read-only lookup of one row in Cursor's state database. `node:sqlite` is
|
|
49
|
+
* imported lazily so a machine without Cursor never loads it. */
|
|
50
|
+
export async function cursorAccessTokenFromDatabase(databasePath) {
|
|
51
|
+
if (!existsSync(databasePath))
|
|
52
|
+
return null;
|
|
53
|
+
// @ts-ignore node:sqlite is in Node 22.5+, newer than Chompyy's @types/node
|
|
54
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
55
|
+
const db = new DatabaseSync(databasePath, { readOnly: true });
|
|
56
|
+
try {
|
|
57
|
+
// Cursor is usually running and holding a write lock; without this a read
|
|
58
|
+
// gets SQLITE_BUSY at once. Wait it out the same 1s the CLI opener does.
|
|
59
|
+
db.exec?.('PRAGMA busy_timeout = 1000');
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// Best effort. Some Node sqlite builds may not expose exec on DatabaseSync.
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
const rows = db.prepare('SELECT value FROM ItemTable WHERE key = ? LIMIT 1').all(ACCESS_TOKEN_KEY);
|
|
66
|
+
const value = rows[0]?.['value'];
|
|
67
|
+
const text = typeof value === 'string'
|
|
68
|
+
? value
|
|
69
|
+
: value instanceof Uint8Array ? new TextDecoder('utf-8', { fatal: false }).decode(value) : '';
|
|
70
|
+
return text.trim().length > 0 ? text.trim() : null;
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
db.close();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function defaults() {
|
|
77
|
+
return {
|
|
78
|
+
fetch: globalThis.fetch,
|
|
79
|
+
databasePath: cursorDatabasePath(),
|
|
80
|
+
loadAccessToken: cursorAccessTokenFromDatabase,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function empty(connection, footerLines = []) {
|
|
84
|
+
return { provider: 'grokbot', connection, primary: null, details: [], planLabel: null, footerLines };
|
|
85
|
+
}
|
|
86
|
+
function resetsAt(value) {
|
|
87
|
+
if (typeof value !== 'string' || !value.trim())
|
|
88
|
+
return null;
|
|
89
|
+
const parsed = Date.parse(value);
|
|
90
|
+
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;
|
|
91
|
+
}
|
|
92
|
+
function nonEmpty(value) {
|
|
93
|
+
if (typeof value !== 'string')
|
|
94
|
+
return null;
|
|
95
|
+
const trimmed = value.trim();
|
|
96
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
97
|
+
}
|
|
98
|
+
/** `null` when the payload carries no usable percentage; the two sentinels
|
|
99
|
+
* mirror the app's own refusals, which show no reading on a pooled enterprise
|
|
100
|
+
* allowance or a zero included limit. */
|
|
101
|
+
export function decodeGrokbotUsage(body) {
|
|
102
|
+
const data = body && typeof body === 'object' ? body : {};
|
|
103
|
+
if (data['usesPooledEnterpriseAllowance'] === true)
|
|
104
|
+
return 'pooled';
|
|
105
|
+
if (data['hasNonZeroIncludedLimit'] === false)
|
|
106
|
+
return 'noAllowance';
|
|
107
|
+
const raw = data['usagePercent'];
|
|
108
|
+
if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 0)
|
|
109
|
+
return null;
|
|
110
|
+
const window = {
|
|
111
|
+
label: 'Weekly usage',
|
|
112
|
+
percent: Math.min(1, raw / 100),
|
|
113
|
+
resetsAt: resetsAt(data['nextResetTimestampUtc']),
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
provider: 'grokbot',
|
|
117
|
+
connection: 'connected',
|
|
118
|
+
primary: window,
|
|
119
|
+
details: [window],
|
|
120
|
+
planLabel: nonEmpty(data['grokPlanLabel']),
|
|
121
|
+
footerLines: SOURCE_FOOTER,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
export async function fetchGrokbotQuota(options = {}) {
|
|
125
|
+
const deps = { ...defaults(), ...options };
|
|
126
|
+
let token;
|
|
127
|
+
try {
|
|
128
|
+
token = (await deps.loadAccessToken(deps.databasePath))?.trim() || null;
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
// Cursor holding a write lock, or a database this build cannot open, is a
|
|
132
|
+
// local condition that clears itself; never a signed-out user.
|
|
133
|
+
console.warn(`Grok Bot quota unavailable: ${sanitizeError(error)}`);
|
|
134
|
+
return { quota: empty('transientFailure', UNREADABLE_FOOTER) };
|
|
135
|
+
}
|
|
136
|
+
if (!token)
|
|
137
|
+
return { quota: empty('disconnected', SIGNED_OUT_FOOTER) };
|
|
138
|
+
try {
|
|
139
|
+
const response = await deps.fetch(USAGE_ENDPOINT, {
|
|
140
|
+
method: 'POST',
|
|
141
|
+
body: '{}',
|
|
142
|
+
signal: quotaRequestSignal(options.signal),
|
|
143
|
+
headers: {
|
|
144
|
+
Authorization: `Bearer ${token}`,
|
|
145
|
+
'Content-Type': 'application/json',
|
|
146
|
+
Accept: 'application/json',
|
|
147
|
+
'connect-protocol-version': '1',
|
|
148
|
+
'User-Agent': 'chompyy/0.1 (+https://github.com/BranchWork-HQ/Chompyy)',
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
if (response.status === 401 || response.status === 403)
|
|
152
|
+
return { quota: { ...empty('terminalFailure', REJECTED_FOOTER), connectable: true } };
|
|
153
|
+
if (response.status === 429) {
|
|
154
|
+
const raw = response.headers.get('Retry-After');
|
|
155
|
+
const seconds = raw === null ? NaN : Number(raw);
|
|
156
|
+
return {
|
|
157
|
+
quota: { ...empty('transientFailure', RATE_LIMITED_FOOTER), rateLimited: true },
|
|
158
|
+
retryAfterSeconds: Math.max(Number.isFinite(seconds) ? Math.ceil(seconds) : 300, 60),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
if (response.status >= 500)
|
|
162
|
+
return { quota: empty('transientFailure', UNAVAILABLE_FOOTER) };
|
|
163
|
+
if (!response.ok)
|
|
164
|
+
return { quota: empty('transientFailure', PARSE_FOOTER) };
|
|
165
|
+
// Never log the body - it carries account data.
|
|
166
|
+
const decoded = decodeGrokbotUsage(await response.json());
|
|
167
|
+
// Terminal, not disconnected: the account is signed in and answering, it
|
|
168
|
+
// simply has no per-account reading, so Plans shows the reason rather than
|
|
169
|
+
// the "sign in to Cursor" affordance.
|
|
170
|
+
if (decoded === 'pooled')
|
|
171
|
+
return { quota: empty('terminalFailure', POOLED_FOOTER) };
|
|
172
|
+
if (decoded === 'noAllowance')
|
|
173
|
+
return { quota: empty('terminalFailure', NO_ALLOWANCE_FOOTER) };
|
|
174
|
+
if (decoded === null)
|
|
175
|
+
return { quota: empty('transientFailure', PARSE_FOOTER) };
|
|
176
|
+
return { quota: decoded };
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
console.warn(`Grok Bot quota unavailable: ${sanitizeError(error)}`);
|
|
180
|
+
return { quota: empty('transientFailure') };
|
|
181
|
+
}
|
|
182
|
+
}
|