chompyy 0.5.0 → 0.6.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.
Files changed (154) hide show
  1. package/README.md +11 -0
  2. package/dist/agentlimits.js +77 -0
  3. package/dist/agentusage.js +96 -0
  4. package/dist/appstate.js +63 -3
  5. package/dist/away.js +44 -5
  6. package/dist/blueprint.js +3 -7
  7. package/dist/board.js +1 -0
  8. package/dist/cli.js +263 -5
  9. package/dist/codexquota.js +106 -0
  10. package/dist/codexusage.js +10 -0
  11. package/dist/config.js +2 -0
  12. package/dist/context.js +30 -0
  13. package/dist/costs.js +1 -0
  14. package/dist/demon.js +20 -0
  15. package/dist/label.js +33 -0
  16. package/dist/menu.js +17 -0
  17. package/dist/nightcap.js +60 -0
  18. package/dist/nudge.js +47 -18
  19. package/dist/pacing.js +16 -1
  20. package/dist/questions.js +71 -0
  21. package/dist/recap.js +74 -0
  22. package/dist/receipt.js +48 -0
  23. package/dist/recipe.js +79 -0
  24. package/dist/stamps.js +14 -0
  25. package/dist/triggers.js +5 -0
  26. package/dist/usage.js +21 -1
  27. package/dist/vendor/codeburn/antigravity.js +309 -0
  28. package/dist/vendor/codeburn/codex.js +429 -0
  29. package/dist/vendor/codeburn/copilot.js +292 -0
  30. package/dist/vendor/codeburn/gemini.js +195 -0
  31. package/dist/vendor/codeburn/grokbot.js +182 -0
  32. package/dist/vendor/codeburn/kimi.js +178 -0
  33. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  34. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  35. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  36. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  37. package/dist/vendor/codeburn/src/act/types.js +37 -0
  38. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  39. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  40. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  41. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  42. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  43. package/dist/vendor/codeburn/src/classifier.js +209 -0
  44. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  45. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  46. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  47. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  48. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  49. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  50. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  51. package/dist/vendor/codeburn/src/config.js +145 -0
  52. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  53. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  54. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  55. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  56. package/dist/vendor/codeburn/src/currency.js +189 -0
  57. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  58. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  59. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  60. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  61. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  62. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  63. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  64. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  65. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  66. package/dist/vendor/codeburn/src/format.js +118 -0
  67. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  68. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  69. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  70. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  71. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  72. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  73. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  74. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  75. package/dist/vendor/codeburn/src/models.js +1879 -0
  76. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  77. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  78. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  79. package/dist/vendor/codeburn/src/parser.js +6953 -0
  80. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  81. package/dist/vendor/codeburn/src/plans.js +135 -0
  82. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  83. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  84. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  85. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  86. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  87. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  88. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  89. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  90. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  91. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  92. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  93. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  94. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  95. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  96. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  97. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  98. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  99. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  100. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  101. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  102. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  103. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  104. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  105. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  106. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  107. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  108. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  109. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  110. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  111. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  112. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  113. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  114. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  115. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  116. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  117. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  118. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  119. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  120. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  121. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  122. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  123. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  124. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  125. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  126. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  127. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  128. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  129. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  130. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  131. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  132. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  133. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  134. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  135. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  136. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  137. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  138. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  139. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  140. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  141. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  142. package/dist/vendor/codeburn/src/session-output.js +139 -0
  143. package/dist/vendor/codeburn/src/session-population.js +30 -0
  144. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  145. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  146. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  147. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  148. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  149. package/dist/vendor/codeburn/src/types.js +16 -0
  150. package/dist/vendor/codeburn/src/work-units.js +126 -0
  151. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  152. package/dist/vendor/codeburn/src/wsl.js +198 -0
  153. package/dist/vendor/codeburn/src/yield.js +666 -0
  154. package/package.json +1 -1
@@ -0,0 +1,301 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ // Live Cursor quota via the app's own usage-summary endpoint (ported from the
3
+ // menubar's CursorSubscriptionService.swift):
4
+ //
5
+ // - GET https://cursor.com/api/usage-summary
6
+ // Authenticated with the session cookie Cursor itself sends
7
+ // (WorkosCursorSessionToken=<userId>%3A%3A<jwt>), not a bearer header.
8
+ //
9
+ // Credential: the access token the Cursor app already keeps in its own VS Code
10
+ // state database, under the ItemTable key `cursorAuth/accessToken`, opened
11
+ // read-only. Nothing is copied and nothing is written; CodeBurn never refreshes
12
+ // the session, so an expired token is terminal until the user signs in again.
13
+ // Cursor 3.27 stores that token as `cursor-safe-storage:v1:` (Chromium v10).
14
+ // That blob is not an expired login: unlock it with the Cursor Safe Storage
15
+ // keychain item, then apply the same JWT checks as a plaintext token.
16
+ import { createDecipheriv, pbkdf2Sync } from 'node:crypto';
17
+ import { existsSync } from 'node:fs';
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import { quotaRequestSignal, readKeychainPassword, sanitizeError } from './security.js';
21
+ const USAGE_ENDPOINT = 'https://cursor.com/api/usage-summary';
22
+ const ACCESS_TOKEN_KEY = 'cursorAuth/accessToken';
23
+ const SOURCE_FOOTER = ['Source: Cursor app'];
24
+ const SIGNED_OUT_FOOTER = ['Sign in to the Cursor app, then click Retry.'];
25
+ const EXPIRED_FOOTER = ['The Cursor app session is expired or invalid. Sign in again, then click Retry.'];
26
+ const REJECTED_FOOTER = ['Cursor rejected the current app session. Sign in again, then click Retry.'];
27
+ const UNREADABLE_FOOTER = ["Could not read the Cursor app's local session data. Quit and reopen Cursor, then click Retry."];
28
+ const RATE_LIMITED_FOOTER = ['Cursor rate-limited the quota request.'];
29
+ const UNAVAILABLE_FOOTER = ['Cursor is temporarily unavailable.'];
30
+ const PARSE_FOOTER = ['Cursor returned an unrecognized quota response.'];
31
+ const SAFE_STORAGE_PREFIX = 'cursor-safe-storage:';
32
+ const SAFE_STORAGE_SERVICE = 'Cursor Safe Storage';
33
+ // Cursor 3.27's account is "Cursor Key". Older Electron builds used "Cursor".
34
+ // No service-only lookup: after a Deny it finds the same item and asks again.
35
+ const SAFE_STORAGE_ACCOUNTS = ['Cursor Key', 'Cursor'];
36
+ /** Cursor is an Electron app, so its state database follows the VS Code layout
37
+ * of whichever platform it runs on. */
38
+ export function cursorDatabasePath(platform = process.platform, home = os.homedir()) {
39
+ if (platform === 'darwin') {
40
+ return path.join(home, 'Library', 'Application Support', 'Cursor', 'User', 'globalStorage', 'state.vscdb');
41
+ }
42
+ if (platform === 'win32') {
43
+ return path.join(home, 'AppData', 'Roaming', 'Cursor', 'User', 'globalStorage', 'state.vscdb');
44
+ }
45
+ return path.join(home, '.config', 'Cursor', 'User', 'globalStorage', 'state.vscdb');
46
+ }
47
+ /**
48
+ * Read-only lookup of one row in Cursor's state database. The sqlite driver is
49
+ * imported lazily so a machine without Cursor never loads it.
50
+ */
51
+ export async function cursorAccessTokenFromDatabase(databasePath) {
52
+ if (!existsSync(databasePath))
53
+ return null;
54
+ const { blobToText, openDatabase } = await import('../sqlite.js');
55
+ const db = openDatabase(databasePath);
56
+ try {
57
+ const rows = db.query('SELECT CAST(value AS BLOB) AS value FROM ItemTable WHERE key = ? LIMIT 1', [ACCESS_TOKEN_KEY]);
58
+ const value = blobToText(rows[0]?.value).trim();
59
+ return value.length > 0 ? value : null;
60
+ }
61
+ finally {
62
+ db.close();
63
+ }
64
+ }
65
+ // Resolved per call so a caller can change the platform the path is derived
66
+ // from without reloading the module.
67
+ function defaultDeps() {
68
+ return {
69
+ fetch: globalThis.fetch,
70
+ databasePath: cursorDatabasePath(),
71
+ loadAccessToken: cursorAccessTokenFromDatabase,
72
+ now: Date.now,
73
+ readKeychain: (service, accounts) => readKeychainPassword(service, accounts),
74
+ };
75
+ }
76
+ /** Only macOS has a keychain prompt to allow; elsewhere CodeBurn cannot open the session yet. */
77
+ export function cursorLockedMessage(platform = process.platform) {
78
+ if (platform === 'darwin')
79
+ return 'Cursor encrypted its app session. Run codeburn import cursor --sync, then allow the Cursor Safe Storage keychain prompt.';
80
+ return `Cursor encrypted its app session, which CodeBurn cannot unlock on ${platform === 'win32' ? 'Windows' : 'Linux'} yet.`;
81
+ }
82
+ export function isCursorSafeStorageToken(token) {
83
+ return token.startsWith(SAFE_STORAGE_PREFIX);
84
+ }
85
+ /**
86
+ * Chromium safe-storage v10: PBKDF2-HMAC-SHA1(password, "saltysalt", 1003, 16)
87
+ * and AES-128-CBC with a 16-space IV. Returns the plaintext JWT, or null when
88
+ * the blob is not v1/v10 or the password does not open it.
89
+ */
90
+ export function decryptCursorSafeStorage(token, password) {
91
+ if (!isCursorSafeStorageToken(token))
92
+ return token;
93
+ const rest = token.slice(SAFE_STORAGE_PREFIX.length);
94
+ const sep = rest.indexOf(':');
95
+ if (sep < 0 || rest.slice(0, sep) !== 'v1')
96
+ return null;
97
+ const blob = Buffer.from(rest.slice(sep + 1), 'base64');
98
+ if (blob.length < 4 || blob.subarray(0, 3).toString('utf8') !== 'v10')
99
+ return null;
100
+ try {
101
+ // `security -w` appends a newline. The shared keychain reader keeps it for
102
+ // callers whose secret is line-wrapped JSON; AES will not open with it.
103
+ const key = pbkdf2Sync(Buffer.from(password.trim(), 'utf8'), 'saltysalt', 1003, 16, 'sha1');
104
+ const iv = Buffer.alloc(16, 0x20);
105
+ const decipher = createDecipheriv('aes-128-cbc', key, iv);
106
+ const plain = Buffer.concat([decipher.update(blob.subarray(3)), decipher.final()]).toString('utf8').trim();
107
+ return plain.length > 0 ? plain : null;
108
+ }
109
+ catch {
110
+ return null;
111
+ }
112
+ }
113
+ export async function unwrapCursorStoredToken(token, readKeychain) {
114
+ if (!isCursorSafeStorageToken(token))
115
+ return { token };
116
+ const key = await readKeychain(SAFE_STORAGE_SERVICE, SAFE_STORAGE_ACCOUNTS);
117
+ if (key.status !== 'found')
118
+ return { locked: true };
119
+ const jwt = decryptCursorSafeStorage(token, key.value);
120
+ return jwt ? { token: jwt } : { locked: true };
121
+ }
122
+ function empty(connection, footerLines = []) {
123
+ return { provider: 'cursor', connection, primary: null, details: [], planLabel: null, footerLines };
124
+ }
125
+ function num(value) {
126
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
127
+ }
128
+ /** Provider-reported percentages are 0..100 and never negative; a value above
129
+ * the limit clamps rather than overflowing the bar. */
130
+ function providerPercent(value) {
131
+ const parsed = num(value);
132
+ if (parsed === null || parsed < 0)
133
+ return null;
134
+ return Math.min(1, parsed / 100);
135
+ }
136
+ function ratio(used, limit) {
137
+ const usedValue = num(used);
138
+ const limitValue = num(limit);
139
+ if (usedValue === null || limitValue === null || usedValue < 0 || limitValue <= 0)
140
+ return null;
141
+ return Math.min(1, Math.max(0, usedValue / limitValue));
142
+ }
143
+ function resetsAt(value) {
144
+ if (typeof value !== 'string' || !value.trim())
145
+ return null;
146
+ const parsed = Date.parse(value);
147
+ return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;
148
+ }
149
+ function planLabel(value) {
150
+ if (typeof value !== 'string' || !value.trim())
151
+ return null;
152
+ const raw = value.trim();
153
+ const known = {
154
+ pro: 'Pro', pro_plus: 'Pro Plus', 'pro plus': 'Pro Plus', business: 'Business',
155
+ enterprise: 'Enterprise', hobby: 'Hobby', free: 'Hobby', ultra: 'Ultra',
156
+ };
157
+ return known[raw.toLowerCase()] ?? raw;
158
+ }
159
+ /** `null` when the payload carries no usable percentage. */
160
+ export function decodeCursorUsage(body) {
161
+ const data = body && typeof body === 'object' ? body : {};
162
+ const plan = data.individualUsage?.plan;
163
+ const overall = data.individualUsage?.overall;
164
+ const pooled = data.teamUsage?.pooled;
165
+ const teamOnDemand = data.teamUsage?.onDemand;
166
+ const auto = providerPercent(plan?.autoPercentUsed);
167
+ const api = providerPercent(plan?.apiPercentUsed);
168
+ // A capacity gauge must surface the pool that is about to run out, so the
169
+ // fallback takes the worse of the two rather than averaging them.
170
+ const monthly = providerPercent(plan?.totalPercentUsed)
171
+ ?? (auto !== null && api !== null ? Math.max(auto, api) : api ?? auto)
172
+ ?? ratio(plan?.used, plan?.limit)
173
+ ?? ratio(overall?.used, overall?.limit)
174
+ ?? ratio(pooled?.used, pooled?.limit)
175
+ ?? (data.isUnlimited === true ? 0 : null);
176
+ // Enterprise team seats report no individual meter; the team on-demand
177
+ // meter is the only structured used/limit pair in their payload.
178
+ const teamOnDemandPercent = teamOnDemand?.enabled === false ? null : ratio(teamOnDemand?.used, teamOnDemand?.limit);
179
+ const primaryPercent = monthly ?? teamOnDemandPercent;
180
+ if (primaryPercent === null)
181
+ return null;
182
+ const reset = resetsAt(data.billingCycleEnd);
183
+ const primary = { label: monthly === null ? 'Team on-demand' : 'Monthly', percent: primaryPercent, resetsAt: reset };
184
+ const details = [primary];
185
+ if (auto !== null)
186
+ details.push({ label: 'Auto', percent: auto, resetsAt: reset });
187
+ if (api !== null)
188
+ details.push({ label: 'API', percent: api, resetsAt: reset });
189
+ const onDemand = data.individualUsage?.onDemand;
190
+ const onDemandPercent = onDemand?.enabled === false ? null : ratio(onDemand?.used, onDemand?.limit);
191
+ if (onDemandPercent !== null)
192
+ details.push({ label: 'On-demand', percent: onDemandPercent, resetsAt: reset });
193
+ const teamPercent = ratio(pooled?.used, pooled?.limit);
194
+ if (teamPercent !== null)
195
+ details.push({ label: 'Team pool', percent: teamPercent, resetsAt: reset });
196
+ if (monthly !== null && teamOnDemandPercent !== null)
197
+ details.push({ label: 'Team on-demand', percent: teamOnDemandPercent, resetsAt: reset });
198
+ return {
199
+ provider: 'cursor', connection: 'connected',
200
+ primary, details,
201
+ planLabel: planLabel(data.membershipType),
202
+ footerLines: SOURCE_FOOTER,
203
+ };
204
+ }
205
+ function decodeBase64Url(value) {
206
+ const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
207
+ const padded = base64 + '='.repeat((4 - base64.length % 4) % 4);
208
+ try {
209
+ return Buffer.from(padded, 'base64').toString('utf8');
210
+ }
211
+ catch {
212
+ return null;
213
+ }
214
+ }
215
+ export function cursorTokenClaims(token) {
216
+ const parts = token.split('.');
217
+ if (parts.length !== 3)
218
+ return null;
219
+ const payload = decodeBase64Url(parts[1]);
220
+ if (payload === null)
221
+ return null;
222
+ let claims;
223
+ try {
224
+ claims = JSON.parse(payload);
225
+ }
226
+ catch {
227
+ return null;
228
+ }
229
+ if (typeof claims.sub !== 'string')
230
+ return null;
231
+ return { sub: claims.sub, exp: num(claims.exp) };
232
+ }
233
+ /**
234
+ * Cursor's web session is the JWT plus the user id encoded inside it. Anything
235
+ * that is not a live three-part token with a usable subject is an expired or
236
+ * invalid session, never a request worth making.
237
+ */
238
+ export function cursorSessionCookie(token, now) {
239
+ const claims = cursorTokenClaims(token);
240
+ if (claims === null)
241
+ return null;
242
+ const userId = claims.sub.split('|').filter(part => part.length > 0).pop();
243
+ if (!userId || !/^[A-Za-z0-9._-]+$/.test(userId))
244
+ return null;
245
+ const expiresAt = claims.exp;
246
+ // 60s skew, matching the menubar: a token about to die is already useless.
247
+ if (expiresAt === null || expiresAt * 1000 - now <= 60_000)
248
+ return null;
249
+ return `WorkosCursorSessionToken=${userId}%3A%3A${token}`;
250
+ }
251
+ export async function fetchCursorQuota(options = {}) {
252
+ const deps = { ...defaultDeps(), ...options };
253
+ let token;
254
+ try {
255
+ token = (await deps.loadAccessToken(deps.databasePath))?.trim() || null;
256
+ }
257
+ catch (error) {
258
+ // Cursor holding a write lock, or a database this build cannot open, is a
259
+ // local condition that clears itself; never a signed-out user.
260
+ console.warn(`Cursor quota unavailable: ${sanitizeError(error)}`);
261
+ return { quota: empty('transientFailure', UNREADABLE_FOOTER) };
262
+ }
263
+ if (!token)
264
+ return { quota: empty('disconnected', SIGNED_OUT_FOOTER) };
265
+ // Keychain consent is user-initiated, as for Claude: only a caller that says so may raise the prompt.
266
+ if (isCursorSafeStorageToken(token) && !options.allowKeychain)
267
+ return { quota: empty('terminalFailure', [cursorLockedMessage()]) };
268
+ const unwrapped = await unwrapCursorStoredToken(token, deps.readKeychain);
269
+ if ('locked' in unwrapped)
270
+ return { quota: empty('terminalFailure', [cursorLockedMessage()]) };
271
+ const cookie = cursorSessionCookie(unwrapped.token, deps.now());
272
+ if (cookie === null)
273
+ return { quota: empty('terminalFailure', EXPIRED_FOOTER) };
274
+ try {
275
+ const response = await deps.fetch(USAGE_ENDPOINT, {
276
+ method: 'GET', signal: quotaRequestSignal(options.signal),
277
+ headers: { Accept: 'application/json', Cookie: cookie, 'User-Agent': 'CodeBurn' },
278
+ });
279
+ if (response.status === 401 || response.status === 403)
280
+ return { quota: empty('terminalFailure', REJECTED_FOOTER) };
281
+ if (response.status === 429) {
282
+ const raw = response.headers.get('Retry-After');
283
+ const seconds = raw === null ? NaN : Number(raw);
284
+ return {
285
+ quota: { ...empty('transientFailure', RATE_LIMITED_FOOTER), rateLimited: true },
286
+ retryAfterSeconds: Math.max(Number.isFinite(seconds) ? Math.ceil(seconds) : 300, 60),
287
+ };
288
+ }
289
+ if (response.status >= 500)
290
+ return { quota: empty('transientFailure', UNAVAILABLE_FOOTER) };
291
+ if (!response.ok)
292
+ return { quota: empty('transientFailure', PARSE_FOOTER) };
293
+ // Never log the body - it carries account data.
294
+ const quota = decodeCursorUsage(await response.json());
295
+ return { quota: quota ?? empty('transientFailure', PARSE_FOOTER) };
296
+ }
297
+ catch (error) {
298
+ console.warn(`Cursor quota unavailable: ${sanitizeError(error)}`);
299
+ return { quota: empty('transientFailure') };
300
+ }
301
+ }
@@ -0,0 +1,299 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { execFile } from 'node:child_process';
3
+ import { chmodSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
4
+ import { lstat, open } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
8
+ const execFileAsync = promisify(execFile);
9
+ // The macOS keychain prompt (first read of an item `security` is not yet trusted
10
+ // for) blocks until the user answers. Give them time to click Allow before we
11
+ // give up - the old 10s kill fired while the dialog was still open and got
12
+ // misread as "disconnected".
13
+ export const KEYCHAIN_TIMEOUT_MS = 90_000;
14
+ // `security -w` hex-encodes password data it can't hand back as a clean C-string
15
+ // (Claude Code line-wraps its JSON blob, which triggers this). Real credential
16
+ // JSON always contains non-hex characters like '{' and '"', so an all-hex,
17
+ // even-length payload is unambiguously a hex dump we must decode.
18
+ function decodeKeychainValue(raw) {
19
+ const trimmed = raw.trim();
20
+ if (trimmed.length >= 2 && trimmed.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(trimmed)) {
21
+ return Buffer.from(trimmed, 'hex').toString('utf8');
22
+ }
23
+ return raw;
24
+ }
25
+ // exit 44 / "could not be found" is a genuine miss. A Deny (exit 128, "User
26
+ // canceled") and our own timer firing while the dialog waited are the user's
27
+ // answer to a prompt. Anything else (interaction not allowed, I/O, a kill or
28
+ // crash we did not cause) means access wasn't granted, but showed no prompt,
29
+ // so the next candidate is tried.
30
+ function classifyKeychainError(error, timedOut) {
31
+ if (timedOut)
32
+ return 'unanswered';
33
+ const err = error;
34
+ const code = typeof err.code === 'number' || typeof err.code === 'string' ? Number(err.code) : undefined;
35
+ const text = `${err.stderr ?? ''} ${err.message ?? ''}`.toLowerCase();
36
+ if (code === 44 || text.includes('could not be found') || text.includes('specified item could not be found')) {
37
+ return 'notFound';
38
+ }
39
+ if (code === 128 || text.includes('user canceled'))
40
+ return 'denied';
41
+ return 'other';
42
+ }
43
+ // Items (service plus account) the user refused in this process. A CLI process
44
+ // is one user action, so this holds for exactly that action and is never
45
+ // written anywhere.
46
+ const refusedThisRun = new Map();
47
+ /**
48
+ * Reads a generic-password keychain item via the Apple-signed `/usr/bin/security`
49
+ * (which the item's `apple-tool:` partition trusts, avoiding the partition-list
50
+ * prompt on already-consented items). Tries each account candidate in order
51
+ * (`null` = service-only) and stops at a Deny or an unanswered prompt: a later
52
+ * candidate can match the same item, and asking again is a second prompt the
53
+ * user already answered. The refusal is kept for the rest of the process: a
54
+ * later read skips that account (and the service-only lookup, which can match
55
+ * it) without a prompt. Never returns or logs the secret to any caller but the
56
+ * direct one.
57
+ */
58
+ export async function readKeychainPassword(service, accounts = [null], exec = execFileAsync) {
59
+ if (process.platform !== 'darwin')
60
+ return { status: 'notFound' };
61
+ let denied = false;
62
+ let refusal;
63
+ for (const account of accounts) {
64
+ const item = JSON.stringify([service, account]);
65
+ const remembered = refusedThisRun.get(item);
66
+ if (remembered) {
67
+ refusal = remembered;
68
+ continue;
69
+ }
70
+ const args = ['find-generic-password', '-s', service, ...(account ? ['-a', account] : []), '-w'];
71
+ const controller = new AbortController();
72
+ let timedOut = false;
73
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, KEYCHAIN_TIMEOUT_MS);
74
+ try {
75
+ const { stdout } = await exec('/usr/bin/security', args, { signal: controller.signal, maxBuffer: 64 * 1024 });
76
+ if (stdout && stdout.trim())
77
+ return { status: 'found', value: decodeKeychainValue(stdout) };
78
+ }
79
+ catch (error) {
80
+ const kind = classifyKeychainError(error, timedOut);
81
+ if (kind === 'denied' || kind === 'unanswered') {
82
+ refusedThisRun.set(item, kind);
83
+ // A later service-only lookup can match the refused item and ask again.
84
+ refusedThisRun.set(JSON.stringify([service, null]), kind);
85
+ return { status: 'accessDenied', reason: kind };
86
+ }
87
+ if (kind === 'other')
88
+ denied = true;
89
+ }
90
+ finally {
91
+ clearTimeout(timer);
92
+ }
93
+ }
94
+ if (refusal)
95
+ return { status: 'accessDenied', reason: refusal };
96
+ return denied ? { status: 'accessDenied' } : { status: 'notFound' };
97
+ }
98
+ export function sanitizeError(error) {
99
+ const raw = error instanceof Error ? error.message : String(error);
100
+ return raw
101
+ .replace(/\0/g, '')
102
+ .replace(/Bearer\s+[^\s,;"']+/gi, '[REDACTED]')
103
+ .replace(/sk-ant-[A-Za-z0-9_-]+/gi, '[REDACTED]')
104
+ .replace(/sk-[A-Za-z0-9_-]+/gi, '[REDACTED]')
105
+ // Google (ya29.) and GitHub (gho_/ghu_/ghp_) OAuth token shapes used by
106
+ // the Gemini/Copilot quota providers.
107
+ .replace(/ya29\.[A-Za-z0-9._-]+/g, '[REDACTED]')
108
+ .replace(/gh[opusr]_[A-Za-z0-9_]+/g, '[REDACTED]')
109
+ .replace(/eyJ[A-Za-z0-9._-]+/g, '[REDACTED]')
110
+ .slice(0, 240);
111
+ }
112
+ function assertSafeMode(stats, filePath) {
113
+ if (!stats.isFile())
114
+ throw new Error(`Credential path is not a regular file: ${filePath}`);
115
+ // POSIX mode bits are meaningless for Windows ACLs, where stats.mode would
116
+ // otherwise reject every credential file.
117
+ if (process.platform !== 'win32' && (stats.mode & 0o077) !== 0)
118
+ throw new Error(`Credential file permissions are too broad: ${filePath}`);
119
+ }
120
+ export async function readSecureFile(filePath, maxBytes = 64 * 1024) {
121
+ let before;
122
+ try {
123
+ before = await lstat(filePath);
124
+ }
125
+ catch (error) {
126
+ if (error.code === 'ENOENT')
127
+ return null;
128
+ throw error;
129
+ }
130
+ if (before.isSymbolicLink())
131
+ throw new Error(`Refusing symbolic link: ${filePath}`);
132
+ assertSafeMode(before, filePath);
133
+ if (before.size > maxBytes)
134
+ throw new Error(`Credential file exceeds ${maxBytes} bytes: ${filePath}`);
135
+ const handle = await open(filePath, constants.O_RDONLY | NOFOLLOW);
136
+ try {
137
+ const after = await handle.stat();
138
+ assertSafeMode(after, filePath);
139
+ if (after.dev !== before.dev || after.ino !== before.ino)
140
+ throw new Error(`Credential file changed while opening: ${filePath}`);
141
+ if (after.size > maxBytes)
142
+ throw new Error(`Credential file exceeds ${maxBytes} bytes: ${filePath}`);
143
+ return await handle.readFile({ encoding: 'utf8' });
144
+ }
145
+ finally {
146
+ await handle.close();
147
+ }
148
+ }
149
+ /** Synchronous twin of {@link readSecureFile}, for the rotation path that must
150
+ * not yield to the event loop between reading and writing a credential. */
151
+ export function readSecureFileSync(filePath, maxBytes = 64 * 1024) {
152
+ let before;
153
+ try {
154
+ before = lstatSync(filePath);
155
+ }
156
+ catch (error) {
157
+ if (error.code === 'ENOENT')
158
+ return null;
159
+ throw error;
160
+ }
161
+ if (before.isSymbolicLink())
162
+ throw new Error(`Refusing symbolic link: ${filePath}`);
163
+ assertSafeMode(before, filePath);
164
+ if (before.size > maxBytes)
165
+ throw new Error(`Credential file exceeds ${maxBytes} bytes: ${filePath}`);
166
+ const fd = openSync(filePath, constants.O_RDONLY | NOFOLLOW);
167
+ try {
168
+ const after = fstatSync(fd);
169
+ assertSafeMode(after, filePath);
170
+ if (after.dev !== before.dev || after.ino !== before.ino)
171
+ throw new Error(`Credential file changed while opening: ${filePath}`);
172
+ if (after.size > maxBytes)
173
+ throw new Error(`Credential file exceeds ${maxBytes} bytes: ${filePath}`);
174
+ return readFileSync(fd, { encoding: 'utf8' });
175
+ }
176
+ finally {
177
+ closeSync(fd);
178
+ }
179
+ }
180
+ // Rewrite a credential with exactly the owner-only permissions it already had,
181
+ // so a refreshed token neither widens the file the user chose nor drops a
182
+ // tighter mode like 0o400. Group or world bits (or Windows, where mode bits are
183
+ // not the access control) mean there is nothing safe to copy: use owner rw.
184
+ function privateModeFor(filePath) {
185
+ if (process.platform === 'win32')
186
+ return 0o600;
187
+ try {
188
+ const stats = lstatSync(filePath);
189
+ if (!stats.isFile())
190
+ return 0o600;
191
+ const mode = stats.mode & 0o777;
192
+ return mode !== 0 && (mode & 0o077) === 0 ? mode : 0o600;
193
+ }
194
+ catch {
195
+ return 0o600;
196
+ }
197
+ }
198
+ /**
199
+ * Writes a credential file atomically and synchronously. Synchronous on
200
+ * purpose: a caller holding a freshly rotated token has to get it onto disk
201
+ * without an await for an abort, a timeout or a `process.exit` to land in.
202
+ */
203
+ export function atomicWriteSecureFileSync(filePath, contents) {
204
+ const mode = privateModeFor(filePath);
205
+ const dir = path.dirname(filePath);
206
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
207
+ const tempPath = path.join(dir, `.${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`);
208
+ try {
209
+ const fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, mode);
210
+ try {
211
+ writeFileSync(fd, contents, 'utf8');
212
+ fsyncSync(fd);
213
+ }
214
+ finally {
215
+ closeSync(fd);
216
+ }
217
+ if (process.platform !== 'win32')
218
+ chmodSync(tempPath, mode);
219
+ renameSync(tempPath, filePath);
220
+ }
221
+ catch (error) {
222
+ try {
223
+ unlinkSync(tempPath);
224
+ }
225
+ catch { /* nothing to clean up */ }
226
+ throw error;
227
+ }
228
+ }
229
+ /// How long a quota request, including a token grant, is given to answer.
230
+ export const QUOTA_REQUEST_TIMEOUT_MS = 30_000;
231
+ export function quotaRequestSignal(parent) {
232
+ const timeout = AbortSignal.timeout(QUOTA_REQUEST_TIMEOUT_MS);
233
+ return parent ? AbortSignal.any([parent, timeout]) : timeout;
234
+ }
235
+ /// Refreshes that have left this machine and whose result is not yet on disk.
236
+ ///
237
+ /// A token grant retires the refresh token in the credential file the instant
238
+ /// the server accepts it, so the window between the POST and the rewritten file
239
+ /// is one where quitting costs the user their login. Nothing cancels that
240
+ /// window - the request deliberately ignores the caller's abort signal - but a
241
+ /// `process.exit` will still cut through it, so any command that exits outright
242
+ /// has to drain this first.
243
+ const outstandingCredentialWrites = new Set();
244
+ /// Past this an exit stops waiting. It has to outlast the request it is waiting
245
+ /// on, or the guard expires while the very case it was built for is still in
246
+ /// flight: a grant answering at twenty seconds is exactly the slow reply that
247
+ /// costs the user their login. Derived from the request timeout rather than
248
+ /// written as a number, so the two cannot drift apart, plus a margin for the
249
+ /// write that follows the reply.
250
+ export const CREDENTIAL_DRAIN_TIMEOUT_MS = QUOTA_REQUEST_TIMEOUT_MS + 5_000;
251
+ /** Registers a rotation for {@link awaitCredentialWrites} to wait on. Returns
252
+ * the same promise, so a caller can keep awaiting it exactly as before. */
253
+ export function trackCredentialWrite(work) {
254
+ // Swallowed here only: the tracked copy exists to be waited on, and the
255
+ // caller still sees the original promise's rejection.
256
+ const settled = work.then(() => undefined, () => undefined);
257
+ outstandingCredentialWrites.add(settled);
258
+ void settled.then(() => { outstandingCredentialWrites.delete(settled); });
259
+ return work;
260
+ }
261
+ export function pendingCredentialWrites() {
262
+ return outstandingCredentialWrites.size;
263
+ }
264
+ /** Waits for every registered rotation to reach disk, up to `timeoutMs`. Safe
265
+ * to call when there is nothing outstanding, which is the usual case. */
266
+ export async function awaitCredentialWrites(timeoutMs = CREDENTIAL_DRAIN_TIMEOUT_MS) {
267
+ if (outstandingCredentialWrites.size === 0)
268
+ return;
269
+ let timer;
270
+ const expired = new Promise(resolve => {
271
+ timer = setTimeout(() => resolve('timeout'), timeoutMs);
272
+ timer.unref?.();
273
+ });
274
+ try {
275
+ // Looped rather than snapshotted once: a 401 retry can start a second
276
+ // rotation while the first is still draining.
277
+ while (outstandingCredentialWrites.size > 0) {
278
+ const drained = Promise.all([...outstandingCredentialWrites]).then(() => 'drained');
279
+ if (await Promise.race([drained, expired]) === 'timeout') {
280
+ // Giving up here can retire a login, so it is said out loud rather than
281
+ // left for the user to discover the next time a provider asks them to
282
+ // sign in again.
283
+ process.stderr.write('codeburn: a provider login was still being refreshed after '
284
+ + `${Math.round(timeoutMs / 1000)}s and was not saved. `
285
+ + 'If that provider signs you out, sign in again with its own CLI.\n');
286
+ return;
287
+ }
288
+ }
289
+ }
290
+ finally {
291
+ if (timer)
292
+ clearTimeout(timer);
293
+ }
294
+ }
295
+ export function fraction(value) {
296
+ if (typeof value !== 'number' || !Number.isFinite(value))
297
+ return null;
298
+ return Math.min(1, Math.max(0, value / 100));
299
+ }
@@ -0,0 +1 @@
1
+ export {};