chompyy 0.0.0-stage → 0.3.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 (178) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +252 -2
  3. package/THIRD_PARTY_NOTICES.md +59 -0
  4. package/dist/appstate.js +116 -0
  5. package/dist/away.js +314 -0
  6. package/dist/blueprint.js +91 -0
  7. package/dist/board.js +186 -0
  8. package/dist/claudesettings.js +23 -0
  9. package/dist/cli.js +861 -0
  10. package/dist/coldstart.js +207 -0
  11. package/dist/config.js +89 -0
  12. package/dist/costs.js +162 -0
  13. package/dist/duration.js +36 -0
  14. package/dist/gate.js +69 -0
  15. package/dist/history.js +308 -0
  16. package/dist/home.js +34 -0
  17. package/dist/livequota.js +92 -0
  18. package/dist/macapp.js +57 -0
  19. package/dist/pacing.js +189 -0
  20. package/dist/picture.js +117 -0
  21. package/dist/projects.js +114 -0
  22. package/dist/quota.js +153 -0
  23. package/dist/report.js +136 -0
  24. package/dist/review.js +173 -0
  25. package/dist/runner.js +357 -0
  26. package/dist/taste.js +507 -0
  27. package/dist/triggers.js +182 -0
  28. package/dist/vendor/codeburn/claude.js +255 -0
  29. package/dist/vendor/codeburn/security.js +260 -0
  30. package/dist/vendor/codeburn/types.js +1 -0
  31. package/dist/verify.js +131 -0
  32. package/dist/workspace.js +80 -0
  33. package/package.json +48 -4
  34. package/skills/away/SKILL.md +26 -0
  35. package/skills/eat-tokens/SKILL.md +18 -0
  36. package/skills/later/SKILL.md +20 -0
  37. package/skills/taste/SKILL.md +19 -0
  38. package/vendor/diagram-design/LICENSE +21 -0
  39. package/vendor/diagram-design/SKILL.md +399 -0
  40. package/vendor/diagram-design/UPSTREAM.md +18 -0
  41. package/vendor/diagram-design/assets/example-arc-diagram.html +111 -0
  42. package/vendor/diagram-design/assets/example-architecture-containment.html +205 -0
  43. package/vendor/diagram-design/assets/example-architecture-delta.html +193 -0
  44. package/vendor/diagram-design/assets/example-architecture.html +183 -0
  45. package/vendor/diagram-design/assets/example-axonometric-plan-campus.html +108 -0
  46. package/vendor/diagram-design/assets/example-axonometric-plan-coffee-shop.html +121 -0
  47. package/vendor/diagram-design/assets/example-axonometric-plan-warehouse.html +127 -0
  48. package/vendor/diagram-design/assets/example-axonometric-plan.html +114 -0
  49. package/vendor/diagram-design/assets/example-bar.html +129 -0
  50. package/vendor/diagram-design/assets/example-beeswarm.html +384 -0
  51. package/vendor/diagram-design/assets/example-box-plot.html +127 -0
  52. package/vendor/diagram-design/assets/example-bubble.html +147 -0
  53. package/vendor/diagram-design/assets/example-bump.html +142 -0
  54. package/vendor/diagram-design/assets/example-data-flow.html +143 -0
  55. package/vendor/diagram-design/assets/example-datalake.html +269 -0
  56. package/vendor/diagram-design/assets/example-db-schema.html +302 -0
  57. package/vendor/diagram-design/assets/example-dependency.html +224 -0
  58. package/vendor/diagram-design/assets/example-deployment.html +190 -0
  59. package/vendor/diagram-design/assets/example-dp-integration.html +81 -0
  60. package/vendor/diagram-design/assets/example-dp-security-matrix.html +88 -0
  61. package/vendor/diagram-design/assets/example-er.html +202 -0
  62. package/vendor/diagram-design/assets/example-event-modeling.html +64 -0
  63. package/vendor/diagram-design/assets/example-exploded-ai-stack.html +85 -0
  64. package/vendor/diagram-design/assets/example-exploded-keyboard.html +84 -0
  65. package/vendor/diagram-design/assets/example-exploded-phone.html +83 -0
  66. package/vendor/diagram-design/assets/example-exploded-unboxing.html +84 -0
  67. package/vendor/diagram-design/assets/example-exploded.html +83 -0
  68. package/vendor/diagram-design/assets/example-fishbone.html +152 -0
  69. package/vendor/diagram-design/assets/example-flowchart.html +163 -0
  70. package/vendor/diagram-design/assets/example-gantt.html +137 -0
  71. package/vendor/diagram-design/assets/example-heatmap.html +224 -0
  72. package/vendor/diagram-design/assets/example-high-level-vertical.html +325 -0
  73. package/vendor/diagram-design/assets/example-high-level.html +301 -0
  74. package/vendor/diagram-design/assets/example-import-drawio.html +185 -0
  75. package/vendor/diagram-design/assets/example-import-excalidraw.html +70 -0
  76. package/vendor/diagram-design/assets/example-import-mermaid.html +70 -0
  77. package/vendor/diagram-design/assets/example-import-plantuml.html +107 -0
  78. package/vendor/diagram-design/assets/example-it-state.html +128 -0
  79. package/vendor/diagram-design/assets/example-journey.html +148 -0
  80. package/vendor/diagram-design/assets/example-kanban.html +174 -0
  81. package/vendor/diagram-design/assets/example-layers.html +123 -0
  82. package/vendor/diagram-design/assets/example-line.html +111 -0
  83. package/vendor/diagram-design/assets/example-loop.html +100 -0
  84. package/vendor/diagram-design/assets/example-marimekko.html +148 -0
  85. package/vendor/diagram-design/assets/example-medallion.html +159 -0
  86. package/vendor/diagram-design/assets/example-nested.html +136 -0
  87. package/vendor/diagram-design/assets/example-org-chart.html +45 -0
  88. package/vendor/diagram-design/assets/example-polar.html +116 -0
  89. package/vendor/diagram-design/assets/example-process.html +64 -0
  90. package/vendor/diagram-design/assets/example-pyramid.html +119 -0
  91. package/vendor/diagram-design/assets/example-quadrant-consultant.html +166 -0
  92. package/vendor/diagram-design/assets/example-quadrant.html +135 -0
  93. package/vendor/diagram-design/assets/example-radar.html +139 -0
  94. package/vendor/diagram-design/assets/example-requirement-traceability.html +122 -0
  95. package/vendor/diagram-design/assets/example-ridgeline.html +104 -0
  96. package/vendor/diagram-design/assets/example-sankey.html +150 -0
  97. package/vendor/diagram-design/assets/example-sbgn.html +213 -0
  98. package/vendor/diagram-design/assets/example-scatter.html +141 -0
  99. package/vendor/diagram-design/assets/example-sequence-oauth.html +227 -0
  100. package/vendor/diagram-design/assets/example-sequence.html +222 -0
  101. package/vendor/diagram-design/assets/example-service-blueprint.html +185 -0
  102. package/vendor/diagram-design/assets/example-slopegraph.html +119 -0
  103. package/vendor/diagram-design/assets/example-state-lifecycle.html +92 -0
  104. package/vendor/diagram-design/assets/example-state.html +147 -0
  105. package/vendor/diagram-design/assets/example-steps.html +78 -0
  106. package/vendor/diagram-design/assets/example-story-map.html +184 -0
  107. package/vendor/diagram-design/assets/example-streamgraph.html +99 -0
  108. package/vendor/diagram-design/assets/example-swimlane.html +172 -0
  109. package/vendor/diagram-design/assets/example-timeline.html +135 -0
  110. package/vendor/diagram-design/assets/example-tree-block-decomposition.html +151 -0
  111. package/vendor/diagram-design/assets/example-tree.html +173 -0
  112. package/vendor/diagram-design/assets/example-treemap.html +107 -0
  113. package/vendor/diagram-design/assets/example-uml-class.html +188 -0
  114. package/vendor/diagram-design/assets/example-unit-grid.html +141 -0
  115. package/vendor/diagram-design/assets/example-venn.html +110 -0
  116. package/vendor/diagram-design/assets/example-wardley.html +153 -0
  117. package/vendor/diagram-design/assets/example-waterfall.html +129 -0
  118. package/vendor/diagram-design/assets/template-dark.html +99 -0
  119. package/vendor/diagram-design/assets/template.html +100 -0
  120. package/vendor/diagram-design/references/layout-budget.md +103 -0
  121. package/vendor/diagram-design/references/output-spec.md +277 -0
  122. package/vendor/diagram-design/references/primitive-annotation.md +36 -0
  123. package/vendor/diagram-design/references/primitive-sketchy.md +43 -0
  124. package/vendor/diagram-design/references/primitives-core.md +146 -0
  125. package/vendor/diagram-design/references/semantic-patterns.md +154 -0
  126. package/vendor/diagram-design/references/style-guide.md +234 -0
  127. package/vendor/diagram-design/references/type-architecture-delta.md +143 -0
  128. package/vendor/diagram-design/references/type-architecture.md +117 -0
  129. package/vendor/diagram-design/references/type-axonometric-plan.md +83 -0
  130. package/vendor/diagram-design/references/type-bar.md +108 -0
  131. package/vendor/diagram-design/references/type-data-flow.md +371 -0
  132. package/vendor/diagram-design/references/type-db-schema.md +48 -0
  133. package/vendor/diagram-design/references/type-dependency.md +113 -0
  134. package/vendor/diagram-design/references/type-deployment.md +45 -0
  135. package/vendor/diagram-design/references/type-dp-integration.md +407 -0
  136. package/vendor/diagram-design/references/type-dp-security-matrix.md +379 -0
  137. package/vendor/diagram-design/references/type-er.md +25 -0
  138. package/vendor/diagram-design/references/type-event-modeling.md +36 -0
  139. package/vendor/diagram-design/references/type-exploded.md +115 -0
  140. package/vendor/diagram-design/references/type-fishbone.md +75 -0
  141. package/vendor/diagram-design/references/type-flowchart.md +23 -0
  142. package/vendor/diagram-design/references/type-gantt.md +45 -0
  143. package/vendor/diagram-design/references/type-heatmap.md +80 -0
  144. package/vendor/diagram-design/references/type-high-level.md +470 -0
  145. package/vendor/diagram-design/references/type-it-state.md +468 -0
  146. package/vendor/diagram-design/references/type-journey.md +55 -0
  147. package/vendor/diagram-design/references/type-kanban.md +49 -0
  148. package/vendor/diagram-design/references/type-layers.md +26 -0
  149. package/vendor/diagram-design/references/type-line.md +337 -0
  150. package/vendor/diagram-design/references/type-loop.md +223 -0
  151. package/vendor/diagram-design/references/type-medallion.md +356 -0
  152. package/vendor/diagram-design/references/type-nested.md +22 -0
  153. package/vendor/diagram-design/references/type-org-chart.md +44 -0
  154. package/vendor/diagram-design/references/type-polar.md +136 -0
  155. package/vendor/diagram-design/references/type-process.md +490 -0
  156. package/vendor/diagram-design/references/type-pyramid.md +33 -0
  157. package/vendor/diagram-design/references/type-quadrant.md +81 -0
  158. package/vendor/diagram-design/references/type-radar.md +82 -0
  159. package/vendor/diagram-design/references/type-requirement-traceability.md +45 -0
  160. package/vendor/diagram-design/references/type-sankey.md +75 -0
  161. package/vendor/diagram-design/references/type-sbgn.md +80 -0
  162. package/vendor/diagram-design/references/type-scatter.md +276 -0
  163. package/vendor/diagram-design/references/type-sequence.md +130 -0
  164. package/vendor/diagram-design/references/type-service-blueprint.md +103 -0
  165. package/vendor/diagram-design/references/type-state.md +30 -0
  166. package/vendor/diagram-design/references/type-steps.md +180 -0
  167. package/vendor/diagram-design/references/type-story-map.md +46 -0
  168. package/vendor/diagram-design/references/type-swimlane.md +22 -0
  169. package/vendor/diagram-design/references/type-timeline.md +20 -0
  170. package/vendor/diagram-design/references/type-tree.md +24 -0
  171. package/vendor/diagram-design/references/type-treemap.md +137 -0
  172. package/vendor/diagram-design/references/type-uml-class.md +65 -0
  173. package/vendor/diagram-design/references/type-unit-grid.md +63 -0
  174. package/vendor/diagram-design/references/type-venn.md +26 -0
  175. package/vendor/diagram-design/references/type-wardley.md +39 -0
  176. package/vendor/diagram-design/references/type-waterfall.md +75 -0
  177. package/vendor/diagram-design/scripts/self_check.py +1177 -0
  178. package/vendor/diagram-design/scripts/verify_geometry.py +696 -0
@@ -0,0 +1,182 @@
1
+ // Triggers (spec §5.2): start an away run on its own in the last hour before a 5-hour reset, or at your bedtime.
2
+ // `chompyy tick` checks them; `chompyy triggers on` installs a macOS LaunchAgent that runs the tick every
3
+ // 5 minutes. Nothing fires until you turn triggers on. The budget gate still decides every card.
4
+ import { execFileSync } from 'node:child_process';
5
+ import { existsSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { dirname, join } from 'node:path';
8
+ import { budgetGate } from './gate.js';
9
+ import { homePath, readJson, writeJson } from './home.js';
10
+ import { windowView } from './quota.js';
11
+ const statePath = () => homePath('triggers.json');
12
+ export const loadTriggerState = () => readJson(statePath(), { fired: [] });
13
+ export function markFired(key, now, why) {
14
+ const s = loadTriggerState();
15
+ s.fired = [...s.fired.filter((k) => k !== key), key].slice(-50);
16
+ s.lastTickAt = now.toISOString();
17
+ s.lastDecision = why;
18
+ writeJson(statePath(), s);
19
+ }
20
+ export function noteTick(now, why) {
21
+ writeJson(statePath(), { ...loadTriggerState(), lastTickAt: now.toISOString(), lastDecision: why });
22
+ }
23
+ /** "23:30" → minutes after midnight; throws on anything else. */
24
+ export function parseClock(text) {
25
+ const m = text.trim().match(/^(\d{1,2}):(\d{2})$/);
26
+ if (!m || Number(m[1]) > 23 || Number(m[2]) > 59)
27
+ throw new Error(`Bedtime must look like 23:30, not "${text}".`);
28
+ return Number(m[1]) * 60 + Number(m[2]);
29
+ }
30
+ /** If `now` is within the bedtime window, the local date the bedtime started on (handles windows past midnight). */
31
+ export function bedtimeKey(now, bedtime, windowMin) {
32
+ const start = parseClock(bedtime);
33
+ const minutes = now.getHours() * 60 + now.getMinutes();
34
+ let since = minutes - start;
35
+ const day = new Date(now);
36
+ if (since < 0) {
37
+ since += 24 * 60; // bedtime was yesterday evening
38
+ day.setDate(day.getDate() - 1);
39
+ }
40
+ if (since >= windowMin)
41
+ return null;
42
+ const pad = (n) => String(n).padStart(2, '0');
43
+ return `bedtime:${day.getFullYear()}-${pad(day.getMonth() + 1)}-${pad(day.getDate())}`;
44
+ }
45
+ /** Leave this much before the reset so the last card isn't cut off by a fresh window. */
46
+ const RESET_MARGIN_MS = 2 * 60_000;
47
+ const MIN_RUN_MS = 10 * 60_000;
48
+ /** Should a trigger start an away run now? Pure: the tick reads state, this decides. */
49
+ export function decideTrigger(now, snap, config, fired, approved, awayRunning) {
50
+ if (awayRunning)
51
+ return { fire: false, why: 'an away run is already going' };
52
+ if (approved === 0)
53
+ return { fire: false, why: 'no approved cards' };
54
+ const gate = budgetGate(snap, config, now);
55
+ if (!gate.ok)
56
+ return { fire: false, why: `gate closed: ${gate.reasons.join('; ')}` };
57
+ const five = windowView(snap?.fiveHour, now);
58
+ if (!five.known)
59
+ return { fire: false, why: '5h window unknown' };
60
+ const untilReset = five.msLeft - RESET_MARGIN_MS;
61
+ if (config.lastHourTrigger && five.msLeft <= 60 * 60_000) {
62
+ const key = `last-hour:${five.resetsAt}`;
63
+ if (fired.includes(key))
64
+ return { fire: false, why: 'last-hour already ran for this window' };
65
+ if (five.leftPct < config.lastHourMinLeftPct)
66
+ return { fire: false, why: `last hour, but only ${Math.round(five.leftPct)}% left (under ${config.lastHourMinLeftPct}%)` };
67
+ if (untilReset < MIN_RUN_MS)
68
+ return { fire: false, why: 'too close to the reset to finish a card' };
69
+ return { fire: true, kind: 'last-hour', durationMs: untilReset, key, why: `last hour before the reset with ${Math.round(five.leftPct)}% left` };
70
+ }
71
+ if (config.bedtime) {
72
+ const key = bedtimeKey(now, config.bedtime, config.bedtimeWindowMin);
73
+ if (key) {
74
+ if (fired.includes(key))
75
+ return { fire: false, why: 'bedtime already ran tonight' };
76
+ if (untilReset < MIN_RUN_MS)
77
+ return { fire: false, why: 'too close to the reset to finish a card' };
78
+ return { fire: true, kind: 'bedtime', durationMs: untilReset, key, why: `bedtime, ${Math.round(five.leftPct)}% of the window left` };
79
+ }
80
+ }
81
+ return { fire: false, why: 'no trigger due' };
82
+ }
83
+ // ---------- the away lock (a trigger and a manual away must not run the same cards) ----------
84
+ export function lockPath() {
85
+ return homePath('away.lock');
86
+ }
87
+ function alive(pid) {
88
+ try {
89
+ process.kill(pid, 0);
90
+ return true;
91
+ }
92
+ catch (err) {
93
+ return err.code === 'EPERM';
94
+ }
95
+ }
96
+ /** The pid of a running away, or null. A lock left by a dead process doesn't count. */
97
+ export function awayRunning() {
98
+ const lock = readJson(lockPath(), null);
99
+ return lock?.pid && lock.pid !== process.pid && alive(lock.pid) ? lock.pid : null;
100
+ }
101
+ /** Take the lock or throw. Returns a release function. */
102
+ export function takeAwayLock(now, why) {
103
+ const other = awayRunning();
104
+ if (other)
105
+ throw new Error(`Another away run is going (pid ${other}). Wait for it, or stop it first.`);
106
+ writeJson(lockPath(), { pid: process.pid, at: now.toISOString(), why });
107
+ return () => {
108
+ const lock = readJson(lockPath(), null);
109
+ if (lock?.pid === process.pid)
110
+ rmSync(lockPath(), { force: true });
111
+ };
112
+ }
113
+ // ---------- LaunchAgent ----------
114
+ export const AGENT_LABEL = 'dev.chompyy.tick';
115
+ export function agentPath() {
116
+ return join(homedir(), 'Library', 'LaunchAgents', `${AGENT_LABEL}.plist`);
117
+ }
118
+ const xml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
119
+ export function launchAgentPlist(opts) {
120
+ const env = Object.entries(opts.env)
121
+ .map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}</string>`)
122
+ .join('\n');
123
+ return `<?xml version="1.0" encoding="UTF-8"?>
124
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
125
+ <plist version="1.0">
126
+ <dict>
127
+ <key>Label</key><string>${AGENT_LABEL}</string>
128
+ <key>ProgramArguments</key>
129
+ <array>
130
+ <string>${xml(opts.node)}</string>
131
+ <string>${xml(opts.script)}</string>
132
+ <string>tick</string>
133
+ </array>
134
+ <key>StartInterval</key><integer>${opts.intervalSec ?? 300}</integer>
135
+ <key>RunAtLoad</key><false/>
136
+ <key>StandardOutPath</key><string>${xml(opts.log)}</string>
137
+ <key>StandardErrorPath</key><string>${xml(opts.log)}</string>
138
+ <key>EnvironmentVariables</key>
139
+ <dict>
140
+ ${env}
141
+ </dict>
142
+ </dict>
143
+ </plist>
144
+ `;
145
+ }
146
+ function launchctl(args) {
147
+ execFileSync('launchctl', args, { stdio: 'ignore' });
148
+ }
149
+ /** Install (or reinstall) the LaunchAgent that runs `chompyy tick` every 5 minutes. */
150
+ export function installAgent() {
151
+ if (process.platform !== 'darwin')
152
+ throw new Error('Triggers run from a macOS LaunchAgent; on other systems, run `chompyy tick` from cron every 5 minutes.');
153
+ const path = agentPath();
154
+ const env = { PATH: process.env.PATH ?? '/usr/bin:/bin' };
155
+ if (process.env.CHOMPYY_HOME)
156
+ env.CHOMPYY_HOME = process.env.CHOMPYY_HOME;
157
+ if (process.env.HOME)
158
+ env.HOME = process.env.HOME;
159
+ mkdirSync(dirname(path), { recursive: true });
160
+ writeFileSync(path, launchAgentPlist({ node: process.execPath, script: process.argv[1], log: homePath('tick.log'), env }));
161
+ const domain = `gui/${process.getuid?.() ?? 501}`;
162
+ try {
163
+ launchctl(['bootout', `${domain}/${AGENT_LABEL}`]);
164
+ }
165
+ catch { }
166
+ launchctl(['bootstrap', domain, path]);
167
+ return path;
168
+ }
169
+ export function uninstallAgent() {
170
+ const path = agentPath();
171
+ if (!existsSync(path))
172
+ return false;
173
+ try {
174
+ launchctl(['bootout', `gui/${process.getuid?.() ?? 501}/${AGENT_LABEL}`]);
175
+ }
176
+ catch { }
177
+ rmSync(path, { force: true });
178
+ return true;
179
+ }
180
+ export function agentInstalled() {
181
+ return existsSync(agentPath());
182
+ }
@@ -0,0 +1,255 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fraction, quotaRequestSignal, readKeychainPassword, readSecureFile, sanitizeError } from './security.js';
6
+ const ENDPOINT = 'https://api.anthropic.com/api/oauth/usage';
7
+ const KEYCHAIN_SERVICE = 'Claude Code-credentials';
8
+ const EXPIRED_FOOTER = ['Claude Code login expired. Run Claude Code once, then refresh.'];
9
+ const REFUSED_FOOTER = {
10
+ denied: ['Keychain access to the Claude Code login was denied.'],
11
+ unanswered: ['The Keychain prompt for the Claude Code login was not answered.'],
12
+ };
13
+ const defaults = {
14
+ fetch: globalThis.fetch,
15
+ readFile: readSecureFile,
16
+ now: Date.now,
17
+ };
18
+ /** The first config dir in the CLI's order (src/providers/claude.ts): CLAUDE_CONFIG_DIRS,
19
+ * CLAUDE_CONFIG_DIR, the menubar's `claudeConfigDirs` in config.json, ~/.claude. Read here
20
+ * because bridge-handlers, which has a config reader, imports the quota module. */
21
+ export function claudeConfigDir(env = process.env, home = os.homedir()) {
22
+ const expand = (dir) => path.resolve(dir === '~' ? home : dir.startsWith('~/') || dir.startsWith('~\\') ? path.join(home, dir.slice(2)) : dir);
23
+ const multi = (env.CLAUDE_CONFIG_DIRS ?? '').split(path.delimiter).map(dir => dir.trim()).find(dir => dir.length > 0);
24
+ if (multi)
25
+ return expand(multi);
26
+ if (env.CLAUDE_CONFIG_DIR)
27
+ return expand(env.CLAUDE_CONFIG_DIR);
28
+ let dirs;
29
+ try {
30
+ dirs = JSON.parse(readFileSync(path.join(home, '.config', 'codeburn', 'config.json'), 'utf8')).claudeConfigDirs;
31
+ }
32
+ catch { /* no config: ~/.claude */ }
33
+ const first = Array.isArray(dirs) ? dirs.find((dir) => typeof dir === 'string' && dir.trim().length > 0) : undefined;
34
+ return first ? expand(first.trim()) : path.join(home, '.claude');
35
+ }
36
+ /** Claude Code keeps the login of any config dir but ~/.claude under its own Keychain
37
+ * item, suffixed with the first 8 hex chars of the SHA-256 of the dir's NFC path. */
38
+ export function claudeKeychainService(configDir) {
39
+ if (path.resolve(configDir) === path.resolve(os.homedir(), '.claude'))
40
+ return KEYCHAIN_SERVICE;
41
+ return `${KEYCHAIN_SERVICE}-${createHash('sha256').update(configDir.normalize('NFC')).digest('hex').slice(0, 8)}`;
42
+ }
43
+ function empty(connection, footerLines = []) {
44
+ return { provider: 'claude', connection, primary: null, details: [], planLabel: null, footerLines };
45
+ }
46
+ function parseCredential(raw) {
47
+ const clean = raw.replace(/\r/g, '').replace(/\n[ \t]*/g, '');
48
+ const oauth = JSON.parse(clean).claudeAiOauth;
49
+ if (!oauth || typeof oauth.accessToken !== 'string' || oauth.accessToken.length === 0)
50
+ return null;
51
+ return {
52
+ accessToken: oauth.accessToken,
53
+ expiresAt: typeof oauth.expiresAt === 'number' ? oauth.expiresAt : undefined,
54
+ rateLimitTier: typeof oauth.rateLimitTier === 'string' ? oauth.rateLimitTier : undefined,
55
+ subscriptionType: typeof oauth.subscriptionType === 'string' ? oauth.subscriptionType : undefined,
56
+ };
57
+ }
58
+ async function credentialFromFile(deps) {
59
+ const raw = await deps.readFile(deps.credentialPath, 64 * 1024);
60
+ return raw ? parseCredential(raw) : null;
61
+ }
62
+ /**
63
+ * Re-read whichever store the credential came from. On macOS the credential
64
+ * usually lives in the Keychain and no file exists at all, so re-reading the
65
+ * file could never see the token Claude Code has since renewed - and the
66
+ * desktop app never writes that Keychain item itself. A denied Keychain on a
67
+ * re-read needs no state of its own: the first read already decided whether
68
+ * that store is reachable.
69
+ */
70
+ async function credentialFrom(source, deps) {
71
+ if (source === 'file')
72
+ return credentialFromFile(deps);
73
+ const outcome = await deps.keychain();
74
+ return outcome.status === 'found' ? parseCredential(outcome.value) : null;
75
+ }
76
+ /**
77
+ * What a credential the endpoint will not honour, and which its own store cannot
78
+ * replace, should be reported as. An expired login is terminal: nothing but a
79
+ * fresh `claude` run can clear it, and a transient failure would leave the quota
80
+ * card holding the last connected numbers (`stabilizeQuota` in Plans.tsx) as
81
+ * though they were current. A credential still within its life is a real blip
82
+ * and keeps its backoff.
83
+ */
84
+ function unrecoverable(credential, deps) {
85
+ const expired = credential.expiresAt !== undefined && credential.expiresAt <= deps.now();
86
+ // An expired login is connectable here the way Kimi's and Gemini's are: the
87
+ // Plans card turns that flag into the reconnect affordance that clears it.
88
+ return expired ? { ...empty('terminalFailure', EXPIRED_FOOTER), connectable: true } : empty('transientFailure');
89
+ }
90
+ export async function readClaudeKeychain(service) {
91
+ // Claude Code has written the item under both `$USER` (2.1.x) and the older
92
+ // hardcoded "agentseal" account; a user-scoped miss must fall through to the
93
+ // service-only lookup rather than reporting disconnected.
94
+ const user = process.env.USER;
95
+ return readKeychainPassword(service, user ? [user, null] : [null]);
96
+ }
97
+ function windowOf(label, value) {
98
+ if (!value || typeof value !== 'object')
99
+ return null;
100
+ const row = value;
101
+ const percent = fraction(row.utilization);
102
+ if (percent === null)
103
+ return null;
104
+ const resetsAt = typeof row.resets_at === 'string' && !Number.isNaN(Date.parse(row.resets_at))
105
+ ? new Date(row.resets_at).toISOString() : null;
106
+ return { label, percent, resetsAt };
107
+ }
108
+ export function planLabel(credential) {
109
+ const subscriptionType = credential.subscriptionType?.toLowerCase() ?? '';
110
+ const tier = credential.rateLimitTier?.toLowerCase() ?? '';
111
+ const multiplier = tier.match(/max[_-]?(\d+)x/)?.[1];
112
+ const hasMax = tier.includes('max');
113
+ if (subscriptionType === 'team' || (subscriptionType === '' && tier.includes('team'))) {
114
+ return hasMax ? 'Team Premium' : 'Team';
115
+ }
116
+ if (subscriptionType === 'enterprise' || (subscriptionType === '' && tier.includes('enterprise'))) {
117
+ return hasMax ? 'Enterprise Premium' : 'Enterprise';
118
+ }
119
+ if (tier.includes('ultra'))
120
+ return 'Ultra';
121
+ if (multiplier === '20')
122
+ return 'Ultra';
123
+ if (multiplier)
124
+ return `Max ${multiplier}x`;
125
+ if (subscriptionType === 'max' || hasMax)
126
+ return 'Max';
127
+ if (subscriptionType === 'pro' || tier.includes('pro')) {
128
+ return 'Pro';
129
+ }
130
+ const readable = tier.replace(/^default_claude_/, '').replace(/_/g, ' ');
131
+ return readable ? readable[0].toUpperCase() + readable.slice(1) : 'Subscription';
132
+ }
133
+ export function decodeClaudeUsage(body, credential) {
134
+ const data = body && typeof body === 'object' ? body : {};
135
+ const five = windowOf('5-hour', data.five_hour);
136
+ const weekly = windowOf('Weekly', data.seven_day);
137
+ const opus = windowOf('Weekly · Opus', data.seven_day_opus);
138
+ const sonnet = windowOf('Weekly · Sonnet', data.seven_day_sonnet);
139
+ const scoped = [];
140
+ if (Array.isArray(data.limits)) {
141
+ for (const item of data.limits) {
142
+ if (!item || typeof item !== 'object')
143
+ continue;
144
+ const row = item;
145
+ const display = row.scope?.model?.display_name;
146
+ const percent = fraction(row.percent);
147
+ if (row.kind !== 'weekly_scoped' || typeof display !== 'string' || percent === null)
148
+ continue;
149
+ const resetsAt = typeof row.resets_at === 'string' && !Number.isNaN(Date.parse(row.resets_at))
150
+ ? new Date(row.resets_at).toISOString() : null;
151
+ scoped.push({ label: `Weekly · ${display}`, percent, resetsAt });
152
+ }
153
+ }
154
+ return {
155
+ provider: 'claude', connection: 'connected', primary: weekly,
156
+ details: [five, weekly, opus, sonnet].filter((row) => row !== null).concat(scoped),
157
+ planLabel: planLabel(credential), footerLines: [],
158
+ };
159
+ }
160
+ async function request(token, deps, parent) {
161
+ return deps.fetch(ENDPOINT, {
162
+ method: 'GET', signal: quotaRequestSignal(parent),
163
+ headers: {
164
+ Authorization: `Bearer ${token}`,
165
+ Accept: 'application/json',
166
+ 'anthropic-beta': 'oauth-2025-04-20',
167
+ 'User-Agent': 'chompyy/0.1 (+https://github.com/BranchWork-HQ/Chompyy)',
168
+ },
169
+ });
170
+ }
171
+ /** Identifies a login without storing any part of its token, so a 429 block can
172
+ * be dropped once the user logs in again instead of being waited out. */
173
+ export function claudeCredentialKey(accessToken) {
174
+ return createHash('sha256').update(accessToken).digest('hex').slice(0, 16);
175
+ }
176
+ /** The key of the file login, read silently. Null for a Keychain-only login,
177
+ * which a background poll may not read; a forced refresh clears the block anyway. */
178
+ export async function currentClaudeCredentialKey(configDir) {
179
+ try {
180
+ const raw = await readSecureFile(path.join(configDir, '.credentials.json'), 64 * 1024);
181
+ const credential = raw ? parseCredential(raw) : null;
182
+ return credential ? claudeCredentialKey(credential.accessToken) : null;
183
+ }
184
+ catch {
185
+ return null;
186
+ }
187
+ }
188
+ export async function fetchClaudeQuota(options = {}) {
189
+ const configDir = options.configDir ?? path.join(os.homedir(), '.claude');
190
+ const deps = { ...defaults, credentialPath: path.join(configDir, '.credentials.json'), keychain: () => readClaudeKeychain(claudeKeychainService(configDir)), ...options };
191
+ try {
192
+ let credential = await credentialFromFile(deps);
193
+ let source = 'file';
194
+ // A file left from before Claude Code moved the login into the Keychain keeps an
195
+ // expired token: the Keychain's login wins, and without one the file still answers.
196
+ const fileExpired = credential?.expiresAt !== undefined && credential.expiresAt <= deps.now();
197
+ if ((!credential || fileExpired) && options.allowKeychain && process.platform === 'darwin') {
198
+ const outcome = await deps.keychain();
199
+ if (outcome.status === 'accessDenied')
200
+ return { quota: empty('accessDenied', outcome.reason ? REFUSED_FOOTER[outcome.reason] : []) };
201
+ const fromKeychain = outcome.status === 'found' ? parseCredential(outcome.value) : null;
202
+ if (fromKeychain) {
203
+ credential = fromKeychain;
204
+ source = 'keychain';
205
+ }
206
+ }
207
+ // A Claude Code 2.x login lives only in the macOS keychain: no credentials
208
+ // file at all. Since a background poll never reads the keychain, "no file"
209
+ // is not evidence of being logged out — say we have not looked yet, and let
210
+ // the card offer the forced check.
211
+ if (!credential) {
212
+ return { quota: empty(!options.allowKeychain && process.platform === 'darwin' ? 'keychainUnchecked' : 'disconnected') };
213
+ }
214
+ // Nor is an expired file, which a Keychain login may have replaced: the card
215
+ // keeps whatever the last forced check found.
216
+ if (fileExpired && !options.allowKeychain && process.platform === 'darwin')
217
+ return { quota: empty('keychainUnchecked') };
218
+ let response;
219
+ // A keychain read can raise a macOS prompt, so a keychain credential is only
220
+ // re-read after the endpoint has actually rejected it.
221
+ if (source === 'file' && credential.expiresAt !== undefined && credential.expiresAt - deps.now() <= 5 * 60_000) {
222
+ const reread = await credentialFromFile(deps);
223
+ if (!reread || reread.accessToken === credential.accessToken)
224
+ return { quota: unrecoverable(credential, deps) };
225
+ credential = reread;
226
+ }
227
+ response = await request(credential.accessToken, deps, options.signal);
228
+ if (response.status === 401) {
229
+ const reread = await credentialFrom(source, deps);
230
+ if (!reread || reread.accessToken === credential.accessToken)
231
+ return { quota: unrecoverable(credential, deps) };
232
+ credential = reread;
233
+ response = await request(credential.accessToken, deps, options.signal);
234
+ }
235
+ if (response.status === 429) {
236
+ let hint;
237
+ try {
238
+ hint = (await response.json()).retry_after;
239
+ }
240
+ catch {
241
+ hint = undefined;
242
+ }
243
+ const parsed = typeof hint === 'number' ? hint : typeof hint === 'string' ? Number(hint) : NaN;
244
+ return { quota: empty('transientFailure'), retryAfterSeconds: Math.max(Number.isFinite(parsed) ? parsed : 300, 60), credentialKey: claudeCredentialKey(credential.accessToken) };
245
+ }
246
+ if (!response.ok)
247
+ return { quota: { ...empty(response.status >= 400 && response.status < 500 ? 'terminalFailure' : 'transientFailure'), ...(response.status === 401 || response.status === 403 ? { connectable: true } : {}) } };
248
+ return { quota: decodeClaudeUsage(await response.json(), credential) };
249
+ }
250
+ catch (error) {
251
+ // Deliberately sanitize before the only diagnostic sink. Tokens are never returned.
252
+ console.warn(`Claude quota unavailable: ${sanitizeError(error)}`);
253
+ return { quota: empty('transientFailure') };
254
+ }
255
+ }