chompyy 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +179 -2
- package/THIRD_PARTY_NOTICES.md +31 -0
- package/dist/appstate.js +75 -0
- package/dist/away.js +225 -0
- package/dist/blueprint.js +91 -0
- package/dist/board.js +156 -0
- package/dist/cli.js +479 -0
- package/dist/config.js +54 -0
- package/dist/duration.js +36 -0
- package/dist/gate.js +40 -0
- package/dist/home.js +34 -0
- package/dist/livequota.js +78 -0
- package/dist/macapp.js +57 -0
- package/dist/projects.js +114 -0
- package/dist/quota.js +127 -0
- package/dist/report.js +119 -0
- package/dist/review.js +130 -0
- package/dist/runner.js +97 -0
- package/dist/vendor/codeburn/claude.js +255 -0
- package/dist/vendor/codeburn/security.js +260 -0
- package/dist/vendor/codeburn/types.js +1 -0
- package/dist/workspace.js +80 -0
- package/package.json +47 -4
- package/skills/away/SKILL.md +26 -0
- package/skills/eat-tokens/SKILL.md +18 -0
- package/skills/later/SKILL.md +20 -0
- package/skills/taste/SKILL.md +16 -0
package/dist/review.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// After a run: what changed, what the agent asks, and keep / undo (spec §5.7).
|
|
2
|
+
// Every git card works on its own branch, so undo is just removing that branch.
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
import { existsSync, readFileSync, readdirSync, rmSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { commitLeftovers, gitRoot, uncommittedWork } from './workspace.js';
|
|
7
|
+
function git(cwd, args) {
|
|
8
|
+
return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
9
|
+
}
|
|
10
|
+
function ran(card) {
|
|
11
|
+
if (!card.run)
|
|
12
|
+
throw new Error(`Card #${card.id} hasn't run yet.`);
|
|
13
|
+
return card.run;
|
|
14
|
+
}
|
|
15
|
+
/** The question itself: up to the first "?", else the first sentence. Never cut mid-sentence. */
|
|
16
|
+
function questionPart(text) {
|
|
17
|
+
const q = text.indexOf('?');
|
|
18
|
+
if (q !== -1)
|
|
19
|
+
return text.slice(0, q + 1);
|
|
20
|
+
const dot = text.search(/[.!](\s|$)/);
|
|
21
|
+
return dot !== -1 ? text.slice(0, dot + 1) : text;
|
|
22
|
+
}
|
|
23
|
+
/** Top-level items from QUESTIONS.md, as whole questions, at most `max`. */
|
|
24
|
+
export function firstQuestions(markdown, max = 2) {
|
|
25
|
+
return markdown
|
|
26
|
+
.split('\n')
|
|
27
|
+
.filter((line) => /^(\d+\.|[-*])\s+/.test(line)) // top level only, not indented sub-points
|
|
28
|
+
.map((line) => questionPart(line.replace(/^(\d+\.|[-*])\s+/, '').replace(/\*\*|__|`/g, '').trim()))
|
|
29
|
+
.filter(Boolean)
|
|
30
|
+
.slice(0, max);
|
|
31
|
+
}
|
|
32
|
+
/** Wrap text at word boundaries so long questions fold onto the next line instead of being cut. */
|
|
33
|
+
export function wrap(text, width) {
|
|
34
|
+
const lines = [];
|
|
35
|
+
let line = '';
|
|
36
|
+
for (const word of text.split(/\s+/)) {
|
|
37
|
+
if (line && line.length + 1 + word.length > width) {
|
|
38
|
+
lines.push(line);
|
|
39
|
+
line = word;
|
|
40
|
+
}
|
|
41
|
+
else
|
|
42
|
+
line = line ? `${line} ${word}` : word;
|
|
43
|
+
}
|
|
44
|
+
if (line)
|
|
45
|
+
lines.push(line);
|
|
46
|
+
return lines;
|
|
47
|
+
}
|
|
48
|
+
export function questionsOf(card) {
|
|
49
|
+
const path = card.run ? join(card.run.workdir, 'QUESTIONS.md') : '';
|
|
50
|
+
return path && existsSync(path) ? firstQuestions(readFileSync(path, 'utf8')) : [];
|
|
51
|
+
}
|
|
52
|
+
/** Files the run changed: from the branch for git cards, from the folder for draft cards. */
|
|
53
|
+
export function changedFiles(card) {
|
|
54
|
+
const run = card.run;
|
|
55
|
+
if (!run || !existsSync(run.workdir))
|
|
56
|
+
return [];
|
|
57
|
+
try {
|
|
58
|
+
if (run.branch) {
|
|
59
|
+
const root = gitRoot(card.cwd);
|
|
60
|
+
if (!root)
|
|
61
|
+
return [];
|
|
62
|
+
return git(root, ['diff', '--name-only', `HEAD...${run.branch}`]).split('\n').filter(Boolean);
|
|
63
|
+
}
|
|
64
|
+
return readdirSync(run.workdir, { recursive: true, withFileTypes: true })
|
|
65
|
+
.filter((d) => d.isFile())
|
|
66
|
+
.map((d) => join(d.parentPath ?? run.workdir, d.name).slice(run.workdir.length + 1));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export function diffCard(card) {
|
|
73
|
+
const run = ran(card);
|
|
74
|
+
if (!run.branch)
|
|
75
|
+
return `Card #${card.id} ran in a draft folder, not a git repo. Its files are in ${run.workdir}`;
|
|
76
|
+
const root = gitRoot(card.cwd);
|
|
77
|
+
if (!root)
|
|
78
|
+
throw new Error(`${card.cwd} is no longer a git repo.`);
|
|
79
|
+
return git(root, ['diff', '--stat', '--patch', `HEAD...${run.branch}`]) || 'No changes on the branch.';
|
|
80
|
+
}
|
|
81
|
+
function removeWorktree(root, card) {
|
|
82
|
+
const run = ran(card);
|
|
83
|
+
if (existsSync(run.workdir))
|
|
84
|
+
git(root, ['worktree', 'remove', '--force', run.workdir]);
|
|
85
|
+
}
|
|
86
|
+
/** Merge the card's branch into the repo's current branch, then tidy up the worktree. */
|
|
87
|
+
export function keepCard(card) {
|
|
88
|
+
const run = ran(card);
|
|
89
|
+
if (!run.branch)
|
|
90
|
+
return `Card #${card.id} ran in a draft folder; copy what you want from ${run.workdir}`;
|
|
91
|
+
const root = gitRoot(card.cwd);
|
|
92
|
+
if (!root)
|
|
93
|
+
throw new Error(`${card.cwd} is no longer a git repo.`);
|
|
94
|
+
if (git(root, ['status', '--porcelain'])) {
|
|
95
|
+
throw new Error(`${root} has uncommitted changes. Commit or set them aside first, then run keep again.`);
|
|
96
|
+
}
|
|
97
|
+
commitLeftovers({ kind: 'worktree', dir: run.workdir }, card); // older runs may have left work uncommitted
|
|
98
|
+
const loose = uncommittedWork(run.workdir);
|
|
99
|
+
if (loose.length) {
|
|
100
|
+
throw new Error(`The card's folder has uncommitted work that keep would lose: ${loose.slice(0, 5).join(', ')}. Commit it in ${run.workdir} first.`);
|
|
101
|
+
}
|
|
102
|
+
const into = git(root, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
103
|
+
try {
|
|
104
|
+
git(root, ['merge', '--no-ff', '-m', `Keep Chompyy card #${card.id}: ${card.title}`, run.branch]);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
try {
|
|
108
|
+
git(root, ['merge', '--abort']);
|
|
109
|
+
}
|
|
110
|
+
catch { }
|
|
111
|
+
throw new Error(`${run.branch} conflicts with ${into}: another card or your own work changed the same lines. Nothing was changed. Run it again on top of the latest with \`chompyy redo ${card.id}\` (or merge by hand: git -C ${root} merge ${run.branch}).`);
|
|
112
|
+
}
|
|
113
|
+
removeWorktree(root, card);
|
|
114
|
+
git(root, ['branch', '-d', run.branch]);
|
|
115
|
+
return `Kept #${card.id}: merged ${run.branch} into ${into}. Undo it with \`git -C ${root} reset --hard HEAD~1\`.`;
|
|
116
|
+
}
|
|
117
|
+
/** Throw the run away: remove the worktree and branch (or the draft folder). */
|
|
118
|
+
export function undoCard(card) {
|
|
119
|
+
const run = ran(card);
|
|
120
|
+
if (!run.branch) {
|
|
121
|
+
rmSync(run.workdir, { recursive: true, force: true });
|
|
122
|
+
return `Undone #${card.id}: removed the draft folder.`;
|
|
123
|
+
}
|
|
124
|
+
const root = gitRoot(card.cwd);
|
|
125
|
+
if (!root)
|
|
126
|
+
throw new Error(`${card.cwd} is no longer a git repo.`);
|
|
127
|
+
removeWorktree(root, card);
|
|
128
|
+
git(root, ['branch', '-D', run.branch]);
|
|
129
|
+
return `Undone #${card.id}: removed branch ${run.branch}. Your own branches were never touched.`;
|
|
130
|
+
}
|
package/dist/runner.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// The one seam: something that runs a prompt headless. ClaudeRunner wraps `claude -p`;
|
|
2
|
+
// tests pass a fake.
|
|
3
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
4
|
+
export function claudeArgs(req) {
|
|
5
|
+
const args = ['-p', '--output-format', 'text', '--no-session-persistence'];
|
|
6
|
+
if (req.model)
|
|
7
|
+
args.push('--model', req.model);
|
|
8
|
+
if (req.maxTurns)
|
|
9
|
+
args.push('--max-turns', String(req.maxTurns));
|
|
10
|
+
if (req.tools !== undefined)
|
|
11
|
+
args.push('--tools', req.tools);
|
|
12
|
+
if (req.permissionMode)
|
|
13
|
+
args.push('--permission-mode', req.permissionMode);
|
|
14
|
+
if (req.permissionPrompts)
|
|
15
|
+
args.push('--permission-prompts', req.permissionPrompts);
|
|
16
|
+
if (req.allowedTools?.length)
|
|
17
|
+
args.push('--allowedTools', ...req.allowedTools);
|
|
18
|
+
if (req.disallowedTools?.length)
|
|
19
|
+
args.push('--disallowedTools', ...req.disallowedTools);
|
|
20
|
+
if (req.settings)
|
|
21
|
+
args.push('--settings', JSON.stringify(req.settings));
|
|
22
|
+
if (req.extraArgs?.length)
|
|
23
|
+
args.push(...req.extraArgs);
|
|
24
|
+
return args;
|
|
25
|
+
}
|
|
26
|
+
/** Process groups of agents still running, so Ctrl-C on chompyy stops them too. */
|
|
27
|
+
const active = new Set();
|
|
28
|
+
let handlersInstalled = false;
|
|
29
|
+
function stopActiveOnExit() {
|
|
30
|
+
if (handlersInstalled)
|
|
31
|
+
return;
|
|
32
|
+
handlersInstalled = true;
|
|
33
|
+
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
34
|
+
process.once(signal, () => {
|
|
35
|
+
for (const pid of active) {
|
|
36
|
+
try {
|
|
37
|
+
process.kill(-pid, 'SIGTERM');
|
|
38
|
+
}
|
|
39
|
+
catch { }
|
|
40
|
+
}
|
|
41
|
+
process.exit(130);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export class ClaudeRunner {
|
|
46
|
+
bin;
|
|
47
|
+
constructor(bin = 'claude') {
|
|
48
|
+
this.bin = bin;
|
|
49
|
+
}
|
|
50
|
+
run(req) {
|
|
51
|
+
const started = Date.now();
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
|
+
// The prompt goes in on stdin: no argument-length limits, nothing in `ps`.
|
|
54
|
+
// Own process group, so a timeout also stops commands the agent started (tests, builds).
|
|
55
|
+
const child = spawn(this.bin, claudeArgs(req), { cwd: req.cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: true, env: { ...process.env, ...req.env } });
|
|
56
|
+
stopActiveOnExit();
|
|
57
|
+
if (child.pid)
|
|
58
|
+
active.add(child.pid);
|
|
59
|
+
const killAll = (signal) => {
|
|
60
|
+
try {
|
|
61
|
+
if (child.pid)
|
|
62
|
+
process.kill(-child.pid, signal);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
child.kill(signal);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
let output = '';
|
|
69
|
+
let stderr = '';
|
|
70
|
+
let timedOut = false;
|
|
71
|
+
child.stdout.on('data', (d) => (output += d.toString()));
|
|
72
|
+
child.stderr.on('data', (d) => (stderr += d.toString()));
|
|
73
|
+
const timer = setTimeout(() => {
|
|
74
|
+
timedOut = true;
|
|
75
|
+
killAll('SIGTERM');
|
|
76
|
+
setTimeout(() => killAll('SIGKILL'), 5000).unref();
|
|
77
|
+
}, req.timeoutMs);
|
|
78
|
+
const done = (exitCode) => {
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
if (child.pid)
|
|
81
|
+
active.delete(child.pid);
|
|
82
|
+
resolve({ exitCode, output, stderr, timedOut, durationMs: Date.now() - started });
|
|
83
|
+
};
|
|
84
|
+
child.on('error', (err) => {
|
|
85
|
+
stderr += String(err);
|
|
86
|
+
done(null);
|
|
87
|
+
});
|
|
88
|
+
child.on('close', (code) => done(code));
|
|
89
|
+
child.stdin.on('error', () => { }); // child may exit before reading
|
|
90
|
+
child.stdin.end(req.prompt);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export function claudeAvailable(bin = 'claude') {
|
|
95
|
+
const r = spawnSync(bin, ['--version'], { stdio: 'ignore', timeout: 10_000 });
|
|
96
|
+
return r.status === 0;
|
|
97
|
+
}
|
|
@@ -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
|
+
}
|