@umer-jahangier/claude-nonstop 0.0.0-stage → 1.16.2
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 +417 -2
- package/bin/claude-nonstop.js +14 -0
- package/package.json +51 -4
- package/src/accounts.js +288 -0
- package/src/chatgpt-models.js +64 -0
- package/src/checks.js +66 -0
- package/src/classify.js +21 -0
- package/src/claude.js +252 -0
- package/src/cli.js +98 -0
- package/src/clients.js +104 -0
- package/src/codex.js +145 -0
- package/src/commands.js +841 -0
- package/src/config.js +60 -0
- package/src/connectorcheck.js +88 -0
- package/src/desktop.js +267 -0
- package/src/desktopadvice.js +111 -0
- package/src/directory.json +7197 -0
- package/src/elevate.js +39 -0
- package/src/events.js +43 -0
- package/src/files.js +54 -0
- package/src/gateway.js +976 -0
- package/src/hosts.js +46 -0
- package/src/hostsfile.js +68 -0
- package/src/http.js +65 -0
- package/src/keys.js +81 -0
- package/src/keystore.js +141 -0
- package/src/launch.js +233 -0
- package/src/marketplace.js +52 -0
- package/src/openai-auth.js +249 -0
- package/src/paths.js +25 -0
- package/src/prompt.js +66 -0
- package/src/providers.js +168 -0
- package/src/relay.js +78 -0
- package/src/server.js +285 -0
- package/src/service.js +208 -0
- package/src/shell.js +119 -0
- package/src/ssh.js +163 -0
- package/src/state.js +76 -0
- package/src/supervise.js +377 -0
- package/src/system.js +105 -0
- package/src/tls.js +260 -0
- package/src/translate/chat.js +150 -0
- package/src/translate/index.js +52 -0
- package/src/translate/ir.js +140 -0
- package/src/translate/messages.js +333 -0
- package/src/translate/responses.js +495 -0
- package/src/translate/sse.js +44 -0
- package/src/ui/index.html +3206 -0
- package/src/ui.js +623 -0
- package/src/update.js +122 -0
- package/src/usage.js +147 -0
- package/src/vault.js +68 -0
- package/src/winpath.js +48 -0
package/src/accounts.js
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Subscription accounts. The first is your normal Claude Code login. Each extra Claude
|
|
4
|
+
// account is its own Claude Code config folder (CLAUDE_CONFIG_DIR, the documented way to
|
|
5
|
+
// stay signed in to several accounts). Signing in always goes through Claude Code's own
|
|
6
|
+
// `claude auth login`, and the login stays in Claude Code's credential store.
|
|
7
|
+
//
|
|
8
|
+
// A ChatGPT account (kind 'chatgpt', provider 'openai') is signed in the way Codex does it
|
|
9
|
+
// (openai-auth.js) and its sign-in lives in the vault. It's checked with one tiny request.
|
|
10
|
+
|
|
11
|
+
const crypto = require('crypto');
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const os = require('os');
|
|
14
|
+
const path = require('path');
|
|
15
|
+
const paths = require('./paths');
|
|
16
|
+
const claude = require('./claude');
|
|
17
|
+
const state = require('./state');
|
|
18
|
+
const { readJson, writeJson, ensureHome } = require('./files');
|
|
19
|
+
|
|
20
|
+
// Linked from your main config folder, so every account shares one history, one set of
|
|
21
|
+
// settings, plugins and skills, and `claude -c` resumes a conversation from any account.
|
|
22
|
+
const SHARED_DIRS = ['projects', 'file-history', 'todos', 'plans', 'shell-snapshots', 'agents', 'commands', 'skills', 'plugins', 'output-styles', 'hooks'];
|
|
23
|
+
const ALWAYS_SHARED = new Set(['projects', 'file-history', 'todos']);
|
|
24
|
+
const SHARED_FILES = ['settings.json', 'CLAUDE.md', 'keybindings.json'];
|
|
25
|
+
// Copied once into a new account so it skips onboarding and keeps your MCP servers and trusted folders.
|
|
26
|
+
const SEEDED_SETTINGS = ['hasCompletedOnboarding', 'theme', 'mcpServers', 'projects', 'editorMode', 'autoUpdates'];
|
|
27
|
+
|
|
28
|
+
const mainConfigDir = () => process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
|
|
29
|
+
const mainStateFile = () =>
|
|
30
|
+
process.env.CLAUDE_CONFIG_DIR ? path.join(process.env.CLAUDE_CONFIG_DIR, '.claude.json') : path.join(os.homedir(), '.claude.json');
|
|
31
|
+
|
|
32
|
+
function exists(p) {
|
|
33
|
+
try {
|
|
34
|
+
fs.lstatSync(p);
|
|
35
|
+
return true;
|
|
36
|
+
} catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isLink(p) {
|
|
42
|
+
try {
|
|
43
|
+
return fs.lstatSync(p).isSymbolicLink();
|
|
44
|
+
} catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// macOS and Linux link the shared files. Windows needs admin rights for file links, so
|
|
50
|
+
// it copies them instead and refreshes the copies before every launch.
|
|
51
|
+
function syncSharedFiles(dir) {
|
|
52
|
+
const main = mainConfigDir();
|
|
53
|
+
for (const name of SHARED_FILES) {
|
|
54
|
+
const src = path.join(main, name);
|
|
55
|
+
const dst = path.join(dir, name);
|
|
56
|
+
if (!fs.existsSync(src)) continue;
|
|
57
|
+
try {
|
|
58
|
+
if (process.platform === 'win32') fs.copyFileSync(src, dst);
|
|
59
|
+
else if (!exists(dst)) fs.symlinkSync(src, dst);
|
|
60
|
+
} catch {}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function linkShared(dir) {
|
|
65
|
+
const main = mainConfigDir();
|
|
66
|
+
for (const name of SHARED_DIRS) {
|
|
67
|
+
const src = path.join(main, name);
|
|
68
|
+
const dst = path.join(dir, name);
|
|
69
|
+
if (exists(dst)) continue;
|
|
70
|
+
if (!exists(src)) {
|
|
71
|
+
if (!ALWAYS_SHARED.has(name)) continue;
|
|
72
|
+
fs.mkdirSync(src, { recursive: true });
|
|
73
|
+
}
|
|
74
|
+
// Directory junctions need no admin rights on Windows.
|
|
75
|
+
fs.symlinkSync(src, dst, process.platform === 'win32' ? 'junction' : 'dir');
|
|
76
|
+
}
|
|
77
|
+
syncSharedFiles(dir);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function seedSettings(dir) {
|
|
81
|
+
const main = readJson(mainStateFile(), {});
|
|
82
|
+
const seed = {};
|
|
83
|
+
for (const name of SEEDED_SETTINGS) if (name in main) seed[name] = main[name];
|
|
84
|
+
writeJson(path.join(dir, '.claude.json'), seed);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function createProfile(label) {
|
|
88
|
+
ensureHome();
|
|
89
|
+
const id = `acct-${crypto.randomBytes(4).toString('hex')}`;
|
|
90
|
+
const configDir = path.join(paths.PROFILES, id);
|
|
91
|
+
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
92
|
+
linkShared(configDir);
|
|
93
|
+
seedSettings(configDir);
|
|
94
|
+
return { id, label, kind: 'profile', configDir, enabled: true };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const isChatgpt = (account) => account && account.kind === 'chatgpt';
|
|
98
|
+
|
|
99
|
+
// A ChatGPT account: no config folder, its sign-in is in the vault (openai-auth.js).
|
|
100
|
+
function createChatgpt(label) {
|
|
101
|
+
ensureHome();
|
|
102
|
+
return { id: `gpt-${crypto.randomBytes(4).toString('hex')}`, label, kind: 'chatgpt', provider: 'openai', enabled: true };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Does a ChatGPT account have usage left right now? One tiny request to the Codex backend.
|
|
106
|
+
async function probeChatgpt(account, cfg = require('./config').load()) {
|
|
107
|
+
const openaiAuth = require('./openai-auth');
|
|
108
|
+
const providers = require('./providers');
|
|
109
|
+
const { request } = require('./http');
|
|
110
|
+
let creds;
|
|
111
|
+
try {
|
|
112
|
+
creds = await openaiAuth.current(account.id);
|
|
113
|
+
} catch (err) {
|
|
114
|
+
const result = { ok: false, reason: `sign-in could not be renewed: ${err.message}` };
|
|
115
|
+
state.recordAccount(account.id, result);
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
if (!creds) {
|
|
119
|
+
const result = { ok: false, reason: 'not signed in' };
|
|
120
|
+
state.recordAccount(account.id, result);
|
|
121
|
+
return result;
|
|
122
|
+
}
|
|
123
|
+
const wanted = (cfg.models && cfg.models.openai) || providers.openai.defaultModel;
|
|
124
|
+
const model = await require('./chatgpt-models').pick(wanted, account.id, creds, cfg, { force: true });
|
|
125
|
+
const body = JSON.stringify({ model, input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Reply with OK' }] }], instructions: 'Reply with OK.', store: false, stream: true, max_output_tokens: 16 });
|
|
126
|
+
const r = await request(`${providers.openai.chatgptUpstream(cfg)}/responses`, {
|
|
127
|
+
method: 'POST',
|
|
128
|
+
headers: { ...providers.openai.accountHeaders(creds), 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) },
|
|
129
|
+
body,
|
|
130
|
+
timeoutMs: 60000,
|
|
131
|
+
});
|
|
132
|
+
const detail = providers.openai.errorMessage(r.body) || (r.status ? `HTTP ${r.status}` : r.body);
|
|
133
|
+
let result;
|
|
134
|
+
if (r.status >= 200 && r.status < 300) result = { ok: true, reason: '' };
|
|
135
|
+
else if (r.status === 429) result = { ok: false, reason: `usage limit reached: ${detail}` };
|
|
136
|
+
else if (r.status === 401 || r.status === 403) result = { ok: false, reason: `sign-in refused: ${detail}` };
|
|
137
|
+
else result = { ok: false, reason: detail };
|
|
138
|
+
state.recordAccount(account.id, result);
|
|
139
|
+
const u = providers.openai.usageFromHeaders(r.headers || {});
|
|
140
|
+
if (u) state.recordUsage(account.id, { ...u, at: Date.now() });
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// The environment Claude Code runs with for an account.
|
|
145
|
+
function env(account, base = process.env) {
|
|
146
|
+
const out = { ...base };
|
|
147
|
+
delete out.ANTHROPIC_API_KEY;
|
|
148
|
+
delete out.ANTHROPIC_AUTH_TOKEN;
|
|
149
|
+
delete out.ANTHROPIC_BASE_URL;
|
|
150
|
+
if (account.kind === 'profile') {
|
|
151
|
+
out.CLAUDE_CONFIG_DIR = account.configDir;
|
|
152
|
+
delete out.CLAUDE_CODE_OAUTH_TOKEN;
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const PROBE_ARGS = [
|
|
158
|
+
'-p',
|
|
159
|
+
'Reply with OK',
|
|
160
|
+
'--model',
|
|
161
|
+
'haiku',
|
|
162
|
+
'--output-format',
|
|
163
|
+
'json',
|
|
164
|
+
'--no-session-persistence',
|
|
165
|
+
'--strict-mcp-config',
|
|
166
|
+
'--settings',
|
|
167
|
+
'{"disableAllHooks":true}',
|
|
168
|
+
];
|
|
169
|
+
|
|
170
|
+
function lastLine(text) {
|
|
171
|
+
return String(text || '').trim().split(/\r?\n/).filter(Boolean).pop() || '';
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Claude Code prints JSON either pretty-printed across many lines (`auth status`) or as
|
|
175
|
+
// one line, sometimes after other output. Try the whole text, then the last {...} block,
|
|
176
|
+
// then each line from the end.
|
|
177
|
+
function parseJsonOutput(stdout) {
|
|
178
|
+
const text = String(stdout || '').trim();
|
|
179
|
+
const attempts = [text];
|
|
180
|
+
const start = text.lastIndexOf('\n{');
|
|
181
|
+
if (start >= 0) attempts.push(text.slice(start + 1));
|
|
182
|
+
attempts.push(...text.split(/\r?\n/).reverse());
|
|
183
|
+
for (const candidate of attempts) {
|
|
184
|
+
try {
|
|
185
|
+
const value = JSON.parse(candidate);
|
|
186
|
+
if (value && typeof value === 'object') return value;
|
|
187
|
+
} catch {}
|
|
188
|
+
}
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Does this account have usage left right now? One tiny Haiku request against its plan,
|
|
193
|
+
// run from claude-nonstop's own folder so it loads no project config and leaves no
|
|
194
|
+
// conversation behind for `claude -c` to pick up.
|
|
195
|
+
async function probe(account, bin) {
|
|
196
|
+
if (isChatgpt(account)) return probeChatgpt(account);
|
|
197
|
+
ensureHome();
|
|
198
|
+
// User settings may point Claude Code at the gateway, and on a root server they may
|
|
199
|
+
// force bypass-permissions. A probe has to reach this account's own sign-in.
|
|
200
|
+
const args = claude.withoutRootBypass([...PROBE_ARGS, '--setting-sources', 'project,local']);
|
|
201
|
+
const r = await claude.capture(bin, args, { env: env(account), cwd: paths.HOME, timeoutMs: 120000 });
|
|
202
|
+
const parsed = parseJsonOutput(r.stdout);
|
|
203
|
+
const result =
|
|
204
|
+
parsed && parsed.is_error === false
|
|
205
|
+
? { ok: true, reason: '' }
|
|
206
|
+
: { ok: false, reason: (parsed && String(parsed.result || '')) || lastLine(r.stderr) || lastLine(r.stdout) || `claude exited with code ${r.code}` };
|
|
207
|
+
state.recordAccount(account.id, result);
|
|
208
|
+
return result;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// A plan limit (session, weekly, usage): not a passing "rate limit" on a burst of requests.
|
|
212
|
+
const isLimitReason = (reason) => /usage limit|session limit|weekly limit|limit reached|hit your|out of (extra )?usage/i.test(reason || '') && !/would exceed your account's rate limit/i.test(reason || '');
|
|
213
|
+
|
|
214
|
+
function findEmail(value) {
|
|
215
|
+
if (!value || typeof value !== 'object') return null;
|
|
216
|
+
for (const [k, v] of Object.entries(value)) {
|
|
217
|
+
if (/email/i.test(k) && typeof v === 'string' && v.includes('@')) return v;
|
|
218
|
+
const nested = findEmail(v);
|
|
219
|
+
if (nested) return nested;
|
|
220
|
+
}
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function status(account, bin) {
|
|
225
|
+
if (isChatgpt(account)) {
|
|
226
|
+
const creds = require('./openai-auth').stored(account.id);
|
|
227
|
+
return { loggedIn: Boolean(creds), email: creds ? creds.email : null, method: 'chatgpt', plan: creds ? creds.plan : null };
|
|
228
|
+
}
|
|
229
|
+
ensureHome();
|
|
230
|
+
const r = await claude.capture(bin, ['auth', 'status', '--json'], { env: env(account), cwd: paths.HOME, timeoutMs: 30000 });
|
|
231
|
+
// Without Claude Code there's no telling whether the account is signed in, so don't say it isn't.
|
|
232
|
+
if (r.notStarted) return { loggedIn: null, email: null, error: lastLine(r.stderr) };
|
|
233
|
+
const parsed = parseJsonOutput(r.stdout);
|
|
234
|
+
if (!parsed) return { loggedIn: false, email: null, error: lastLine(r.stderr) || lastLine(r.stdout) };
|
|
235
|
+
return { loggedIn: Boolean(parsed.loggedIn), email: findEmail(parsed), method: parsed.authMethod || null };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const LOGIN_ARGS = ['auth', 'login', '--claudeai'];
|
|
239
|
+
|
|
240
|
+
function logout(account, bin) {
|
|
241
|
+
ensureHome();
|
|
242
|
+
return claude.capture(bin, ['auth', 'logout'], { env: env(account), cwd: paths.HOME, timeoutMs: 30000 });
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Deletes an extra account: signs it out (which revokes its login), removes the links to
|
|
246
|
+
// your shared history without touching what they point at, then removes its folder.
|
|
247
|
+
async function remove(account, bin) {
|
|
248
|
+
if (isChatgpt(account)) {
|
|
249
|
+
require('./openai-auth').forget(account.id);
|
|
250
|
+
state.forgetAccount(account.id);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (account.kind !== 'profile') throw new Error('the main account can only be turned off, not removed');
|
|
254
|
+
const rel = path.relative(paths.PROFILES, account.configDir);
|
|
255
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) throw new Error('refusing to delete a folder outside claude-nonstop profiles');
|
|
256
|
+
if (bin) await logout(account, bin);
|
|
257
|
+
if (fs.existsSync(account.configDir)) {
|
|
258
|
+
for (const name of fs.readdirSync(account.configDir)) {
|
|
259
|
+
const p = path.join(account.configDir, name);
|
|
260
|
+
if (!isLink(p)) continue;
|
|
261
|
+
try {
|
|
262
|
+
fs.unlinkSync(p);
|
|
263
|
+
} catch {
|
|
264
|
+
fs.rmdirSync(p); // Windows junctions
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
fs.rmSync(account.configDir, { recursive: true, force: true });
|
|
268
|
+
}
|
|
269
|
+
state.forgetAccount(account.id);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
module.exports = {
|
|
273
|
+
mainConfigDir,
|
|
274
|
+
createProfile,
|
|
275
|
+
createChatgpt,
|
|
276
|
+
isChatgpt,
|
|
277
|
+
probeChatgpt,
|
|
278
|
+
syncSharedFiles,
|
|
279
|
+
env,
|
|
280
|
+
probe,
|
|
281
|
+
status,
|
|
282
|
+
remove,
|
|
283
|
+
logout,
|
|
284
|
+
isLimitReason,
|
|
285
|
+
parseJsonOutput,
|
|
286
|
+
LOGIN_ARGS,
|
|
287
|
+
PROBE_ARGS,
|
|
288
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The models a ChatGPT sign-in may use through the Codex backend. The backend serves only
|
|
4
|
+
// the models on its own list (asked for with the Codex client version it knows), and that
|
|
5
|
+
// list changes with no notice; a name from anywhere else is refused with "not supported when
|
|
6
|
+
// using Codex with a ChatGPT account". So the gateway asks each account for its list, keeps
|
|
7
|
+
// it for a while, and sends a listed model: the one asked for when it's there, else the
|
|
8
|
+
// account's own first choice.
|
|
9
|
+
|
|
10
|
+
const config = require('./config');
|
|
11
|
+
const state = require('./state');
|
|
12
|
+
const providers = require('./providers');
|
|
13
|
+
const { request } = require('./http');
|
|
14
|
+
|
|
15
|
+
const FRESH_MS = 60 * 60000;
|
|
16
|
+
const cache = new Map(); // account id -> { at, models: [{ slug, name, priority }] }
|
|
17
|
+
|
|
18
|
+
const NOT_SUPPORTED = /not supported when using Codex with a ChatGPT account/i;
|
|
19
|
+
const isModelRefusal = (status, text) => status === 400 && NOT_SUPPORTED.test(text || '');
|
|
20
|
+
|
|
21
|
+
function parse(body) {
|
|
22
|
+
const j = JSON.parse(body);
|
|
23
|
+
const list = (Array.isArray(j.models) ? j.models : [])
|
|
24
|
+
.filter((m) => m && typeof m.slug === 'string' && m.visibility !== 'hide')
|
|
25
|
+
.map((m) => ({ slug: m.slug, name: m.display_name || m.slug, priority: Number(m.priority) || 0 }))
|
|
26
|
+
.sort((a, b) => a.priority - b.priority);
|
|
27
|
+
if (!list.length) throw new Error('no models in the answer');
|
|
28
|
+
return list;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// The account's list, fetched when there's none or it's old (or when `force`).
|
|
32
|
+
async function list(accountId, creds, cfg = config.load(), { force = false } = {}) {
|
|
33
|
+
const had = cache.get(accountId);
|
|
34
|
+
if (had && !force && Date.now() - had.at < FRESH_MS) return had.models;
|
|
35
|
+
const r = await request(`${providers.openai.chatgptUpstream(cfg)}/models?client_version=${providers.CODEX_VERSION}`, {
|
|
36
|
+
headers: { ...providers.openai.accountHeaders(creds), accept: 'application/json' },
|
|
37
|
+
timeoutMs: 20000,
|
|
38
|
+
});
|
|
39
|
+
if (r.status !== 200) throw new Error(providers.openai.errorMessage(r.body) || `HTTP ${r.status}`);
|
|
40
|
+
const models = parse(r.body);
|
|
41
|
+
cache.set(accountId, { at: Date.now(), models });
|
|
42
|
+
state.recordChatgptModels(accountId, models.map((m) => m.slug));
|
|
43
|
+
return models;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// The model to send for this account: `wanted` when the backend lists it, else the first on
|
|
47
|
+
// the list. Without a list (the backend didn't answer), `wanted` goes as is.
|
|
48
|
+
async function pick(wanted, accountId, creds, cfg = config.load(), opts) {
|
|
49
|
+
let models;
|
|
50
|
+
try {
|
|
51
|
+
models = await list(accountId, creds, cfg, opts);
|
|
52
|
+
} catch {
|
|
53
|
+
return wanted;
|
|
54
|
+
}
|
|
55
|
+
if (models.some((m) => m.slug === wanted)) return wanted;
|
|
56
|
+
const preferred = cfg.models && cfg.models.chatgpt;
|
|
57
|
+
if (preferred && models.some((m) => m.slug === preferred)) return preferred;
|
|
58
|
+
return models[0].slug;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const known = (accountId) => (cache.get(accountId) || {}).models || null;
|
|
62
|
+
const forget = (accountId) => cache.delete(accountId);
|
|
63
|
+
|
|
64
|
+
module.exports = { list, pick, known, forget, isModelRefusal, parse, FRESH_MS };
|
package/src/checks.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Keeps every account's and key's status known without anyone pressing Check. The gateway
|
|
4
|
+
// checks everything when it starts, the web page asks for a check whenever it opens, and a
|
|
5
|
+
// new key or a freshly signed-in account is checked straight away. A line that is already
|
|
6
|
+
// being checked isn't checked twice, and open pages are told when a check starts and ends.
|
|
7
|
+
|
|
8
|
+
const config = require('./config');
|
|
9
|
+
const vault = require('./vault');
|
|
10
|
+
const keys = require('./keys');
|
|
11
|
+
const accounts = require('./accounts');
|
|
12
|
+
const state = require('./state');
|
|
13
|
+
const claude = require('./claude');
|
|
14
|
+
const events = require('./events');
|
|
15
|
+
const relay = require('./relay');
|
|
16
|
+
const usage = require('./usage');
|
|
17
|
+
|
|
18
|
+
const running = new Map();
|
|
19
|
+
|
|
20
|
+
function once(id, work) {
|
|
21
|
+
if (running.has(id)) return running.get(id);
|
|
22
|
+
const done = Promise.resolve()
|
|
23
|
+
.then(work)
|
|
24
|
+
.catch(() => null)
|
|
25
|
+
.finally(() => {
|
|
26
|
+
running.delete(id);
|
|
27
|
+
events.notify('checks', { id, checking: false });
|
|
28
|
+
});
|
|
29
|
+
running.set(id, done);
|
|
30
|
+
events.notify('checks', { id, checking: true });
|
|
31
|
+
return done;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// The probe also renews the account's sign-in token, so its usage is read right after.
|
|
35
|
+
const account = (a, bin = claude.findClaude()) =>
|
|
36
|
+
accounts.isChatgpt(a)
|
|
37
|
+
? once(a.id, () => accounts.probeChatgpt(a))
|
|
38
|
+
: bin
|
|
39
|
+
? once(a.id, async () => {
|
|
40
|
+
const r = await accounts.probe(a, bin);
|
|
41
|
+
await usage.refresh(a).catch(() => null);
|
|
42
|
+
return r;
|
|
43
|
+
})
|
|
44
|
+
: Promise.resolve(null);
|
|
45
|
+
const key = (entry, cfg = config.load()) => once(entry.id, () => keys.check(entry, cfg));
|
|
46
|
+
|
|
47
|
+
// A result counts as known when it gave a clear answer: usage left or a limit for an
|
|
48
|
+
// account, works or used up for a key. Anything else (no network yet, say) is tried again.
|
|
49
|
+
const known = (c) => Boolean(c && (c.ok || accounts.isLimitReason(c.reason) || c.verdict === 'ok' || c.verdict === 'used-up'));
|
|
50
|
+
const fresh = (c, freshMs) => known(c) && Date.now() - c.at < freshMs;
|
|
51
|
+
|
|
52
|
+
// Checks every account and key that isn't paused, except those with a clear answer from the
|
|
53
|
+
// last `freshMs`. Returns once all the checks it started have finished.
|
|
54
|
+
function all({ freshMs = 0 } = {}) {
|
|
55
|
+
const cfg = config.load();
|
|
56
|
+
const s = state.load();
|
|
57
|
+
const bin = claude.findClaude();
|
|
58
|
+
return Promise.all([
|
|
59
|
+
...cfg.accounts.filter((a) => a.enabled !== false && !fresh(s.accounts[a.id], freshMs)).map((a) => account(a, bin)),
|
|
60
|
+
...vault.load().keys.filter((k) => !relay.isPaused(cfg, 'key', k) && !fresh(s.keys[k.id], freshMs)).map((k) => key(k, cfg)),
|
|
61
|
+
]);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const checking = () => [...running.keys()];
|
|
65
|
+
|
|
66
|
+
module.exports = { all, account, key, checking };
|
package/src/classify.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// What one answer from the Claude API means for the key that got it:
|
|
4
|
+
// 'ok' the key works
|
|
5
|
+
// 'used-up' the key itself is the problem (out of credit, past its spend limit,
|
|
6
|
+
// revoked): move to the next key. It's checked again after the cooldown,
|
|
7
|
+
// in case you topped it up.
|
|
8
|
+
// 'keep' the problem isn't this key (a malformed request, Anthropic overloaded,
|
|
9
|
+
// you're offline): stay on it, because switching keys wouldn't help.
|
|
10
|
+
function classifyResponse(status, body) {
|
|
11
|
+
if (status >= 200 && status < 300) return 'ok';
|
|
12
|
+
if (status === 401 || status === 402 || status === 403) return 'used-up';
|
|
13
|
+
if (status === 400) return /credit balance|usage limit|spend limit/i.test(String(body)) ? 'used-up' : 'keep';
|
|
14
|
+
// 429 (rate limited) stays on the key: Claude Code already retries it with backoff, and
|
|
15
|
+
// keys in the same organization share one rate limit, so switching wouldn't help. If your
|
|
16
|
+
// keys belong to separate organizations, returning 'used-up' for 429 here spreads the
|
|
17
|
+
// load across them instead (the key comes back after the cooldown).
|
|
18
|
+
return 'keep';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
module.exports = { classifyResponse };
|