@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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +417 -2
  3. package/bin/claude-nonstop.js +14 -0
  4. package/package.json +51 -4
  5. package/src/accounts.js +288 -0
  6. package/src/chatgpt-models.js +64 -0
  7. package/src/checks.js +66 -0
  8. package/src/classify.js +21 -0
  9. package/src/claude.js +252 -0
  10. package/src/cli.js +98 -0
  11. package/src/clients.js +104 -0
  12. package/src/codex.js +145 -0
  13. package/src/commands.js +841 -0
  14. package/src/config.js +60 -0
  15. package/src/connectorcheck.js +88 -0
  16. package/src/desktop.js +267 -0
  17. package/src/desktopadvice.js +111 -0
  18. package/src/directory.json +7197 -0
  19. package/src/elevate.js +39 -0
  20. package/src/events.js +43 -0
  21. package/src/files.js +54 -0
  22. package/src/gateway.js +976 -0
  23. package/src/hosts.js +46 -0
  24. package/src/hostsfile.js +68 -0
  25. package/src/http.js +65 -0
  26. package/src/keys.js +81 -0
  27. package/src/keystore.js +141 -0
  28. package/src/launch.js +233 -0
  29. package/src/marketplace.js +52 -0
  30. package/src/openai-auth.js +249 -0
  31. package/src/paths.js +25 -0
  32. package/src/prompt.js +66 -0
  33. package/src/providers.js +168 -0
  34. package/src/relay.js +78 -0
  35. package/src/server.js +285 -0
  36. package/src/service.js +208 -0
  37. package/src/shell.js +119 -0
  38. package/src/ssh.js +163 -0
  39. package/src/state.js +76 -0
  40. package/src/supervise.js +377 -0
  41. package/src/system.js +105 -0
  42. package/src/tls.js +260 -0
  43. package/src/translate/chat.js +150 -0
  44. package/src/translate/index.js +52 -0
  45. package/src/translate/ir.js +140 -0
  46. package/src/translate/messages.js +333 -0
  47. package/src/translate/responses.js +495 -0
  48. package/src/translate/sse.js +44 -0
  49. package/src/ui/index.html +3206 -0
  50. package/src/ui.js +623 -0
  51. package/src/update.js +122 -0
  52. package/src/usage.js +147 -0
  53. package/src/vault.js +68 -0
  54. package/src/winpath.js +48 -0
package/src/gateway.js ADDED
@@ -0,0 +1,976 @@
1
+ 'use strict';
2
+
3
+ // The local gateway, at http://127.0.0.1:43117/v1/*. It takes requests in three formats
4
+ // (translate/index.js) and sends each one out on the first line in your order that can
5
+ // answer, whatever service that line is on:
6
+ //
7
+ // An Anthropic line: a Claude subscription sign-in (the request goes out as Claude Code,
8
+ // which that sign-in requires) or a Claude API key (as plain API: every Claude Code
9
+ // signal is dropped from the headers and the system prompt, so API credit covers it).
10
+ //
11
+ // An OpenAI line: a ChatGPT subscription sign-in (the request goes to the Codex backend,
12
+ // as Codex, which that sign-in requires) or an OpenAI API key (plain API).
13
+ //
14
+ // A request whose format matches the line's service goes through as it came; one that
15
+ // doesn't is translated on the way out and the answer translated on the way back, so Claude
16
+ // Code can run on a ChatGPT account and Codex on a Claude one. A request for a model from
17
+ // the other service's family goes to that line's default model (`models` in config.json).
18
+ //
19
+ // Two kinds of request keep their old meaning: a terminal Claude Code session on API keys
20
+ // names its keys (x-claude-nonstop-keys), and a request already signed in to a Claude.ai
21
+ // account (a subscription token as its bearer) passes straight through to Anthropic.
22
+
23
+ const crypto = require('crypto');
24
+ const http = require('http');
25
+ const https = require('https');
26
+ const providers = require('./providers');
27
+ const translate = require('./translate');
28
+ const relay = require('./relay');
29
+ const events = require('./events');
30
+ const state = require('./state');
31
+ const accounts = require('./accounts');
32
+ const usage = require('./usage');
33
+ const openaiAuth = require('./openai-auth');
34
+ const chatgptModels = require('./chatgpt-models');
35
+ const { log } = require('./files');
36
+
37
+ // What a Claude subscription sign-in needs to be accepted: Claude Code's identity and betas.
38
+ const CLI_USER_AGENT = 'claude-cli/2.1.310 (external, cli)';
39
+ const OAUTH_BETA = 'oauth-2025-04-20';
40
+ // A subscription sign-in accepts only Claude Code's own requests: the system prompt has to
41
+ // begin with this line, or Anthropic answers 429 "Error". Claude Code's requests carry it;
42
+ // the desktop app's startup probe doesn't, so the gateway puts it first when it's missing.
43
+ const CLAUDE_CODE_SYSTEM = "You are Claude Code, Anthropic's official CLI for Claude.";
44
+ const ANTHROPIC_VERSION = '2026-10-21';
45
+
46
+ // Accounts refused for a passing rate limit, by id: skipped until this time (ms).
47
+ const busyUntil = new Map();
48
+ const MAX_BODY = 64 * 1024 * 1024;
49
+ const MAX_ERROR_BODY = 4 * 1024 * 1024;
50
+ const KEYS_HEADER = 'x-claude-nonstop-keys';
51
+ // A terminal Claude Code session on one account line (a ChatGPT account, which has no Claude
52
+ // Code sign-in of its own) names it: "account:<id>".
53
+ const LINE_HEADER = 'x-claude-nonstop-line';
54
+ // Hop-by-hop headers and the client's own credentials never go upstream.
55
+ const DROP_REQUEST = new Set([
56
+ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
57
+ 'te', 'trailer', 'transfer-encoding', 'upgrade', 'host', 'content-length',
58
+ 'accept-encoding', 'authorization', 'x-api-key', KEYS_HEADER, LINE_HEADER,
59
+ ]);
60
+ // The client's own identity, replaced by the line's on every request.
61
+ const IDENTITY = new Set(['user-agent', 'x-app', 'originator', 'session_id', 'chatgpt-account-id', 'openai-beta', 'openai-organization', 'openai-project', 'x-stainless-lang', 'x-stainless-package-version', 'x-stainless-os', 'x-stainless-arch', 'x-stainless-runtime', 'x-stainless-runtime-version', 'x-stainless-retry-count', 'x-stainless-timeout', 'x-stainless-helper-method']);
62
+ // Only hop-by-hop headers are dropped from a request on a Claude.ai sign-in; the sign-in stays.
63
+ const DROP_PASSTHROUGH = new Set([
64
+ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
65
+ 'te', 'trailer', 'transfer-encoding', 'upgrade', 'host', 'content-length',
66
+ 'accept-encoding', KEYS_HEADER, LINE_HEADER,
67
+ ]);
68
+ const DROP_RESPONSE = new Set([
69
+ 'connection', 'keep-alive', 'transfer-encoding', 'content-length',
70
+ ]);
71
+ const agents = {
72
+ 'http:': new http.Agent({ keepAlive: true }),
73
+ 'https:': new https.Agent({ keepAlive: true }),
74
+ };
75
+
76
+ function keysFor(req, cfg, all) {
77
+ const order = relay.keyOrder(cfg, all);
78
+ const named = req.headers[KEYS_HEADER];
79
+ if (!named) return order;
80
+ const ids = new Set(String(named).split(',').map((s) => s.trim()).filter(Boolean));
81
+ return order.filter((k) => ids.has(k.id));
82
+ }
83
+
84
+ function sameToken(given, expected) {
85
+ if (!given || !expected) return false;
86
+ const a = Buffer.from(String(given));
87
+ const b = Buffer.from(String(expected));
88
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
89
+ }
90
+
91
+ function clientToken(req) {
92
+ const auth = String(req.headers.authorization || '');
93
+ return req.headers['x-api-key'] ||
94
+ (/^bearer /i.test(auth) ? auth.slice(7).trim() : '');
95
+ }
96
+
97
+ // A Claude.ai subscription sign-in (Claude Code's OAuth token), not the gateway token.
98
+ const isAccountToken = (token) => /^sk-ant-oat/.test(String(token || ''));
99
+
100
+ // A terminal Claude Code session names the keys or the account it runs on; the desktop app sends no such header.
101
+ const isSession = (req) => Boolean(req.headers[KEYS_HEADER] || req.headers[LINE_HEADER]);
102
+
103
+ // The account line a session named, if any.
104
+ function lineFor(req, cfg) {
105
+ const named = String(req.headers[LINE_HEADER] || '').trim();
106
+ const m = /^account:(.+)$/.exec(named);
107
+ if (!m) return null;
108
+ const account = cfg.accounts.find((a) => a.id === m[1] && a.enabled !== false);
109
+ return account ? [{ kind: 'account', item: account }] : [];
110
+ }
111
+
112
+ // Whether the client speaks OpenAI's formats, for the few answers the gateway writes itself
113
+ // before it has seen a body (the model list, an error on a path it doesn't know).
114
+ const speaksOpenAI = (req) => !req.headers['anthropic-version'] && !req.headers['x-api-key'] && /^\/v1\/(chat|responses|models)/.test(req.url || '');
115
+
116
+ function sendJson(res, status, body) {
117
+ const text = JSON.stringify(body);
118
+ res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(text) });
119
+ res.end(text);
120
+ }
121
+
122
+ // An error in the client's own format. `format` may be a translate format or null.
123
+ function sendError(res, status, type, message, format = null) {
124
+ sendJson(res, status, translate.errorBody(format || 'messages', type, message));
125
+ }
126
+
127
+ function readBody(stream, limit) {
128
+ return new Promise((resolve, reject) => {
129
+ const chunks = [];
130
+ let size = 0;
131
+ let settled = false;
132
+ stream.on('data', (chunk) => {
133
+ if (settled) return;
134
+ size += chunk.length;
135
+ if (size > limit) {
136
+ settled = true;
137
+ reject(new Error('too large'));
138
+ stream.destroy();
139
+ return;
140
+ }
141
+ chunks.push(chunk);
142
+ });
143
+ stream.on('end', () => {
144
+ if (settled) return;
145
+ settled = true;
146
+ resolve(Buffer.concat(chunks));
147
+ });
148
+ stream.on('error', (error) => {
149
+ if (settled) return;
150
+ settled = true;
151
+ reject(error);
152
+ });
153
+ stream.on('close', () => {
154
+ if (settled) return;
155
+ settled = true;
156
+ reject(new Error('request stream closed early'));
157
+ });
158
+ });
159
+ }
160
+
161
+ function splitBetas(value) {
162
+ return [...new Set(String(value || '').split(',').map((b) => b.trim()).filter(Boolean))];
163
+ }
164
+
165
+ // The client's headers without its identity, credentials or Claude Code's betas.
166
+ function stripped(headers) {
167
+ const out = {};
168
+ for (const [name, value] of Object.entries(headers)) {
169
+ const lower = name.toLowerCase();
170
+ if (!DROP_REQUEST.has(lower) && !IDENTITY.has(lower)) out[lower] = value;
171
+ }
172
+ const betas = splitBetas(out['anthropic-beta']).filter((b) => !/^oauth-/i.test(b) && !/^claude-code(?:-|$)/i.test(b));
173
+ if (betas.length) out['anthropic-beta'] = betas.join(',');
174
+ else delete out['anthropic-beta'];
175
+ out['accept-encoding'] = 'identity';
176
+ return out;
177
+ }
178
+
179
+ // The headers for a request going out on an Anthropic line: Anthropic's own headers from
180
+ // the client when it spoke Anthropic's format, bare essentials otherwise.
181
+ function anthropicBase(headers, sameFormat) {
182
+ const out = sameFormat ? stripped(headers) : { 'accept-encoding': 'identity' };
183
+ out['content-type'] = 'application/json';
184
+ if (!out['anthropic-version']) out['anthropic-version'] = ANTHROPIC_VERSION;
185
+ return out;
186
+ }
187
+
188
+ // Claude Code's identity on a request going out on a subscription sign-in: the CLI user
189
+ // agent, x-app and the OAuth beta, which is what Claude Code itself sends on an account
190
+ // (the claude-code beta is refused there).
191
+ function claudeAccountHeaders(headers, sameFormat, token, length, { asClaudeCode = true } = {}) {
192
+ const out = anthropicBase(headers, sameFormat);
193
+ out['anthropic-beta'] = [OAUTH_BETA, ...splitBetas(out['anthropic-beta'])].join(',');
194
+ if (asClaudeCode) {
195
+ out['user-agent'] = CLI_USER_AGENT;
196
+ out['x-app'] = 'cli';
197
+ }
198
+ out.authorization = `Bearer ${token}`;
199
+ out['content-length'] = String(length);
200
+ return out;
201
+ }
202
+
203
+ // Headers for a request going out on a Claude API key: an ordinary API request, with no
204
+ // client identity at all, so it's billed as plain API use.
205
+ function claudeKeyHeaders(headers, sameFormat, key, length) {
206
+ const out = anthropicBase(headers, sameFormat);
207
+ out['x-api-key'] = key;
208
+ out['content-length'] = String(length);
209
+ return out;
210
+ }
211
+
212
+ // Headers for a request going out on an OpenAI API key.
213
+ function openaiKeyHeaders(headers, sameFormat, key, length) {
214
+ const out = sameFormat ? stripped(headers) : { 'accept-encoding': 'identity' };
215
+ delete out['anthropic-version'];
216
+ delete out['anthropic-beta'];
217
+ out['content-type'] = 'application/json';
218
+ out.authorization = `Bearer ${key}`;
219
+ out['content-length'] = String(length);
220
+ return out;
221
+ }
222
+
223
+ // Headers for a request going out on a ChatGPT sign-in: Codex's identity, nothing of the client's.
224
+ function chatgptHeaders(creds, length) {
225
+ return { ...providers.openai.accountHeaders(creds), 'content-type': 'application/json', 'accept-encoding': 'identity', 'content-length': String(length) };
226
+ }
227
+
228
+ // --------------------------------------------------------------- bodies
229
+
230
+ function parseJson(body) {
231
+ try {
232
+ const json = JSON.parse(body.toString('utf8'));
233
+ return json && typeof json === 'object' && !Array.isArray(json) ? json : null;
234
+ } catch {
235
+ return null;
236
+ }
237
+ }
238
+
239
+ // Which client sent a request. Codex (and any other client of OpenAI's formats) is never
240
+ // reshaped as Claude Code: its own instructions and tools are what its model must follow.
241
+ // Claude Code and the Claude desktop app speak Anthropic's format.
242
+ function clientOf(req, inbound) {
243
+ const agent = String(req.headers['user-agent'] || '') + String(req.headers.originator || '');
244
+ if (inbound === 'responses' || /codex/i.test(agent)) return 'codex';
245
+ if (inbound === 'chat') return 'openai';
246
+ return 'claude';
247
+ }
248
+
249
+ // A Claude.ai sign-in answers 429 to any request whose system prompt doesn't open with
250
+ // Claude Code's identity line as a block of its own (tried live: headers don't matter). For
251
+ // a client that isn't Claude Code the line is still sent, alone, followed by a note that it's
252
+ // only the connection's and the client's own instructions, so its model keeps to them.
253
+ const NOT_CLAUDE_CODE = 'The line above is required by the API connection only. Your actual identity, role, instructions and tools are the ones below: follow them, use only the tools provided, and do not describe yourself as Claude Code.';
254
+
255
+ function asSignInBody(body) {
256
+ const json = parseJson(body);
257
+ if (!json || !json.messages) return body;
258
+ const sys = typeof json.system === 'string' ? [{ type: 'text', text: json.system }] : Array.isArray(json.system) ? json.system : [];
259
+ json.system = [{ type: 'text', text: CLAUDE_CODE_SYSTEM }, { type: 'text', text: NOT_CLAUDE_CODE }, ...sys.filter((b) => b && b.text)];
260
+ return Buffer.from(JSON.stringify(json));
261
+ }
262
+
263
+ // The request body as Claude Code would send it on a sign-in: the system prompt opens with
264
+ // Claude Code's identity line. Left alone when it already does, or isn't a JSON body.
265
+ function asClaudeCodeBody(body) {
266
+ const json = parseJson(body);
267
+ if (!json || !json.messages) return body;
268
+ const block = { type: 'text', text: CLAUDE_CODE_SYSTEM };
269
+ const sys = json.system;
270
+ if (typeof sys === 'string') {
271
+ if (sys.startsWith(CLAUDE_CODE_SYSTEM)) return body;
272
+ json.system = sys ? [block, { type: 'text', text: sys }] : CLAUDE_CODE_SYSTEM;
273
+ } else if (Array.isArray(sys)) {
274
+ const first = sys[0];
275
+ if (first && typeof first.text === 'string' && first.text.startsWith(CLAUDE_CODE_SYSTEM)) return body;
276
+ json.system = [block, ...sys];
277
+ } else {
278
+ json.system = CLAUDE_CODE_SYSTEM;
279
+ }
280
+ return Buffer.from(JSON.stringify(json));
281
+ }
282
+
283
+ // The request body as an ordinary API request: Anthropic also reads Claude Code's identity
284
+ // from the system prompt, and bills it as Claude Code (which much API credit doesn't cover,
285
+ // so the key answers 400 "credit balance is too low"). Two blocks do it: the billing header
286
+ // Claude Code puts first, and a block that is exactly its identity line ("You are Claude
287
+ // Code, ..." or the Agent SDK's). The billing header is dropped (it says nothing to the
288
+ // model); the identity line is kept, joined to the text after it, where it no longer marks
289
+ // the request. Left alone when there's nothing to change, or it isn't a JSON body.
290
+ const BILLING_HEADER = /^x-anthropic-billing-header:/i;
291
+ const IDENTITY_LINE = /^You are (?:Claude Code|a Claude agent)\b[^\n]*\bAnthropic's\b[^\n]*\.$/;
292
+
293
+ function asPlainApiBody(body) {
294
+ const json = parseJson(body);
295
+ if (!json || json.system === undefined) return body;
296
+ const sys = json.system;
297
+ if (typeof sys === 'string') {
298
+ if (!IDENTITY_LINE.test(sys)) return body;
299
+ json.system = `${sys}\n`;
300
+ return Buffer.from(JSON.stringify(json));
301
+ }
302
+ if (!Array.isArray(sys)) return body;
303
+ const isText = (b) => b && b.type === 'text' && typeof b.text === 'string';
304
+ let changed = false;
305
+ const out = [];
306
+ for (const block of sys) {
307
+ if (isText(block) && BILLING_HEADER.test(block.text)) {
308
+ changed = true;
309
+ continue;
310
+ }
311
+ out.push(block);
312
+ }
313
+ for (let i = 0; i < out.length; i++) {
314
+ const block = out[i];
315
+ if (!isText(block) || !IDENTITY_LINE.test(block.text)) continue;
316
+ changed = true;
317
+ const next = out[i + 1];
318
+ if (isText(next)) {
319
+ out.splice(i, 2, { ...next, text: `${block.text}\n\n${next.text}` });
320
+ } else {
321
+ out[i] = { ...block, text: `${block.text}\n` };
322
+ }
323
+ }
324
+ if (!changed) return body;
325
+ json.system = out;
326
+ return Buffer.from(JSON.stringify(json));
327
+ }
328
+
329
+ // The model a line answers a request with: the one asked for when it's from the line's own
330
+ // service, else the line's default (an alias in `modelAliases` is applied first).
331
+ function modelFor(requested, provider, cfg) {
332
+ const aliases = cfg.modelAliases || {};
333
+ const model = aliases[requested] || requested;
334
+ if (translate.ir.family(model) === provider.id) return model;
335
+ return (cfg.models && cfg.models[provider.id]) || provider.defaultModel;
336
+ }
337
+
338
+ // A Responses-API body for an OpenAI line, out of the client's own Responses request:
339
+ // the model mapped, nothing stored upstream, and (on a ChatGPT sign-in) always streamed, as
340
+ // the Codex backend requires. Fields the backend wouldn't take are dropped.
341
+ function asResponsesBody(json, model, { chatgpt }) {
342
+ const out = { ...json, model, store: false };
343
+ if (chatgpt) {
344
+ out.stream = true;
345
+ // The backend takes input only as a list of items.
346
+ if (typeof out.input === 'string') out.input = [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: out.input }] }];
347
+ delete out.previous_response_id;
348
+ delete out.service_tier;
349
+ delete out.safety_identifier;
350
+ delete out.user;
351
+ delete out.metadata;
352
+ delete out.max_tool_calls;
353
+ delete out.truncation;
354
+ delete out.background;
355
+ // Sampling settings are refused too (tried live): the backend uses the model's own.
356
+ delete out.temperature;
357
+ delete out.top_p;
358
+ const include = new Set([...(Array.isArray(out.include) ? out.include : []), 'reasoning.encrypted_content']);
359
+ out.include = [...include];
360
+ // Cached answers of another provider's reasoning can't be read here.
361
+ if (Array.isArray(out.input)) out.input = out.input.filter((i) => !(i && i.type === 'reasoning' && !i.encrypted_content));
362
+ }
363
+ return Buffer.from(JSON.stringify(out));
364
+ }
365
+
366
+ // --------------------------------------------------------------- lines
367
+
368
+ // A Claude account the gateway can use right now: on, signed in, and not seen at its limit
369
+ // in the last while. Returns its token, or null with why not.
370
+ // A Claude.ai sign-in good for at least another minute.
371
+ const fresh = (creds) => Boolean(creds && (!creds.expiresAt || creds.expiresAt > Date.now() + 60000));
372
+
373
+ const limitedRecently = (account, cfg) => {
374
+ const recent = state.load().accounts[account.id];
375
+ return recent && !recent.ok && accounts.isLimitReason(recent.reason) && Date.now() - recent.at < cfg.accountRecheckMinutes * 60000 ? recent.reason : null;
376
+ };
377
+
378
+ // An account's sign-in token, renewed first when it has expired. The gateway only reads
379
+ // tokens; Claude Code renews them when it runs. On a computer where nothing else runs Claude
380
+ // Code under an account (a server, say), its token would stay expired and the account would
381
+ // be passed over for good, so the gateway runs Claude Code's quick usage check under that
382
+ // account, which renews the token the normal way, and reads it again.
383
+ async function claudeToken(account, cfg) {
384
+ const limited = limitedRecently(account, cfg);
385
+ if (limited) return { token: null, why: limited };
386
+ let creds = usage.readCredentials(account);
387
+ if (!creds) return { token: null, why: 'no sign-in token found' };
388
+ if (!fresh(creds)) {
389
+ log(`gateway: ${account.label}: sign-in token expired, renewing it`);
390
+ await require('./checks').account(account);
391
+ const nowLimited = limitedRecently(account, cfg);
392
+ if (nowLimited) return { token: null, why: nowLimited };
393
+ creds = usage.readCredentials(account);
394
+ if (!fresh(creds)) return { token: null, why: 'sign-in token expired and could not be renewed (sign in to this account again)' };
395
+ }
396
+ return { token: creds.token, why: '' };
397
+ }
398
+
399
+ // Keeps every Claude.ai sign-in alive: one about to expire is renewed through Claude Code's
400
+ // one-word usage check, so a request never waits for it and no account needs signing in
401
+ // again. Paused accounts and accounts at their limit are kept alive too: Claude Code renews
402
+ // the sign-in before it asks, even when the answer is a limit. Nothing is spent on a
403
+ // sign-in that still has time left, so each account costs about one tiny request per
404
+ // sign-in lifetime (a few a day). ChatGPT sign-ins renew themselves (openai-auth.js).
405
+ async function renewExpiring(cfg) {
406
+ for (const account of cfg.accounts) {
407
+ if (accounts.isChatgpt(account)) continue;
408
+ const creds = usage.readCredentials(account);
409
+ if (creds && creds.expiresAt && creds.expiresAt < Date.now() + 10 * 60000) {
410
+ log(`gateway: ${account.label}: sign-in token expires soon, renewing it`);
411
+ await require('./checks').account(account);
412
+ }
413
+ }
414
+ }
415
+
416
+ // A ChatGPT account the gateway can use right now, with a sign-in good for a while.
417
+ async function chatgptCredentials(account, cfg) {
418
+ const recent = state.load().accounts[account.id];
419
+ if (recent && !recent.ok && accounts.isLimitReason(recent.reason) && Date.now() - recent.at < cfg.accountRecheckMinutes * 60000) {
420
+ return { creds: null, why: recent.reason };
421
+ }
422
+ try {
423
+ const creds = await openaiAuth.current(account.id);
424
+ if (!creds) return { creds: null, why: 'not signed in' };
425
+ return { creds, why: '' };
426
+ } catch (err) {
427
+ return { creds: null, why: `sign-in could not be renewed: ${err.message}` };
428
+ }
429
+ }
430
+
431
+ // Keeps every Claude.ai sign-in alive: one about to expire is renewed through Claude Code's
432
+ // one-word usage check, so a request never waits for it and no account needs signing in
433
+ // again. Paused accounts and accounts at their limit are kept alive too: Claude Code renews
434
+ // the sign-in before it asks, even when the answer is a limit. Nothing is spent on a
435
+ // sign-in that still has time left, so each account costs about one tiny request per
436
+ // sign-in lifetime (a few a day).
437
+ async function renewExpiring(cfg) {
438
+ for (const account of cfg.accounts) {
439
+ const creds = usage.readCredentials(account);
440
+ if (creds && creds.expiresAt && creds.expiresAt < Date.now() + 10 * 60000) {
441
+ log(`gateway: ${account.label}: sign-in token expires soon, renewing it`);
442
+ await require('./checks').account(account);
443
+ }
444
+ }
445
+ }
446
+
447
+ // Headers for a request on a Claude.ai sign-in: exactly as sent, sign-in and identity included.
448
+ function passthroughHeaders(headers, length) {
449
+ const out = {};
450
+ for (const [name, value] of Object.entries(headers)) {
451
+ const lower = name.toLowerCase();
452
+ if (!DROP_PASSTHROUGH.has(lower)) out[lower] = value;
453
+ }
454
+ out['accept-encoding'] = 'identity';
455
+ if (length !== undefined && length !== null) out['content-length'] = String(length);
456
+ return out;
457
+ }
458
+
459
+ function responseHeaders(headers, length) {
460
+ const out = {};
461
+ for (const [name, value] of Object.entries(headers)) {
462
+ if (!DROP_RESPONSE.has(name.toLowerCase())) out[name] = value;
463
+ }
464
+ if (length !== undefined) out['content-length'] = String(length);
465
+ return out;
466
+ }
467
+
468
+ function forward(url, method, body, headers) {
469
+ return new Promise((resolve) => {
470
+ let target;
471
+ try {
472
+ target = new URL(url);
473
+ } catch (error) {
474
+ resolve({ error });
475
+ return;
476
+ }
477
+ const lib = target.protocol === 'https:' ? https :
478
+ target.protocol === 'http:' ? http : null;
479
+ if (!lib) {
480
+ resolve({ error: new Error(`Unsupported protocol: ${target.protocol}`) });
481
+ return;
482
+ }
483
+ let settled = false;
484
+ const finish = (value) => {
485
+ if (settled) return;
486
+ settled = true;
487
+ resolve(value);
488
+ };
489
+ const upstream = lib.request(target, { method, headers, agent: agents[target.protocol] }, (res) => finish({ res, upstream }));
490
+ upstream.on('error', (error) => finish({ error }));
491
+ upstream.end(body.length ? body : undefined);
492
+ });
493
+ }
494
+
495
+ // A request on a Claude.ai sign-in, sent to Anthropic exactly as it came and answered as is.
496
+ async function passthrough(cfg, req, res, body) {
497
+ const { res: upRes, upstream, error } = await forward(`${cfg.upstream}${req.url}`, req.method, body, passthroughHeaders(req.headers, body.length));
498
+ if (error) {
499
+ log(`gateway: upstream connection failed: ${error.message}`);
500
+ if (!res.destroyed && !res.headersSent) {
501
+ sendError(res, 502, 'api_error',
502
+ `claude-nonstop gateway could not reach ${cfg.upstream}: ${error.message}`);
503
+ }
504
+ return;
505
+ }
506
+ log(`gateway: Claude.ai account request passed through (HTTP ${upRes.statusCode})`);
507
+ pipe(res, upRes, upstream);
508
+ }
509
+
510
+ function pipe(res, upRes, upstream) {
511
+ if (res.destroyed || res.headersSent) {
512
+ upstream.destroy();
513
+ return;
514
+ }
515
+ res.writeHead(upRes.statusCode, responseHeaders(upRes.headers));
516
+ upRes.pipe(res);
517
+ res.on('close', () => {
518
+ if (!res.writableFinished) upstream.destroy();
519
+ });
520
+ }
521
+
522
+ // Hands an upstream answer to the client in the client's own format. Same format and the
523
+ // same streaming either side: the bytes go through untouched. Otherwise the answer is read
524
+ // (whole, or event by event) and written again as the client asked.
525
+ function deliver(res, upRes, upstream, { inbound, wire, clientStream, upstreamStream, model, includeUsage, toolKinds = {} }) {
526
+ if (inbound === wire && clientStream === upstreamStream) {
527
+ pipe(res, upRes, upstream);
528
+ return;
529
+ }
530
+ if (res.destroyed || res.headersSent) {
531
+ upstream.destroy();
532
+ return;
533
+ }
534
+ res.on('close', () => {
535
+ if (!res.writableFinished) upstream.destroy();
536
+ });
537
+ const headers = { 'cache-control': 'no-cache' };
538
+ const requestId = upRes.headers['request-id'] || upRes.headers['x-request-id'];
539
+ if (requestId) headers['request-id'] = String(requestId);
540
+ if (!upstreamStream) {
541
+ // A whole answer came back; the client gets it whole or as a stream of its own format.
542
+ readBody(upRes, MAX_BODY).then((buf) => {
543
+ const json = parseJson(buf);
544
+ if (!json) {
545
+ sendError(res, 502, 'api_error', 'claude-nonstop gateway: the answer could not be read.', inbound);
546
+ return;
547
+ }
548
+ const answer = translate.readAnswer(wire, json);
549
+ if (!clientStream) {
550
+ sendJson(res, 200, translate.writeAnswer(inbound, answer, { model, toolKinds }));
551
+ return;
552
+ }
553
+ res.writeHead(200, { ...headers, 'content-type': 'text/event-stream; charset=utf-8' });
554
+ const write = translate.streamWriter(inbound, { model, includeUsage, toolKinds });
555
+ for (const event of translate.ir.eventsOf(answer)) res.write(write(event));
556
+ res.end();
557
+ }).catch(() => {
558
+ if (!res.headersSent) sendError(res, 502, 'api_error', 'claude-nonstop gateway: the answer could not be read.', inbound);
559
+ else res.end();
560
+ });
561
+ return;
562
+ }
563
+ const read = translate.streamReader(wire);
564
+ if (clientStream) {
565
+ res.writeHead(200, { ...headers, 'content-type': 'text/event-stream; charset=utf-8' });
566
+ const write = translate.streamWriter(inbound, { model, includeUsage, toolKinds });
567
+ let stopped = false;
568
+ upRes.on('data', (chunk) => {
569
+ for (const event of read(chunk)) {
570
+ if (event.type === 'stop' || event.type === 'error') stopped = true;
571
+ res.write(write(event));
572
+ }
573
+ });
574
+ upRes.on('end', () => {
575
+ if (!stopped) res.write(write({ type: 'stop', stopReason: 'end_turn' }));
576
+ res.end();
577
+ });
578
+ upRes.on('error', () => {
579
+ if (!stopped) res.write(write({ type: 'error', message: 'the upstream stream ended early' }));
580
+ res.end();
581
+ });
582
+ return;
583
+ }
584
+ // The client wanted the whole answer; the upstream only streams.
585
+ const collect = translate.ir.collector();
586
+ collect.push({ type: 'start', id: null, model });
587
+ upRes.on('data', (chunk) => {
588
+ for (const event of read(chunk)) collect.push(event);
589
+ });
590
+ const finish = () => {
591
+ const { answer, error } = collect.result();
592
+ if (error && !answer.content.length) {
593
+ sendError(res, 502, 'api_error', error.message, inbound);
594
+ return;
595
+ }
596
+ sendJson(res, 200, translate.writeAnswer(inbound, answer, { model, toolKinds }));
597
+ };
598
+ upRes.on('end', finish);
599
+ upRes.on('error', finish);
600
+ }
601
+
602
+ // --------------------------------------------------------------- the model list
603
+
604
+ // Every model the lines in use can answer for, in the client's own list format. Answered by
605
+ // the gateway itself: the lists are well known, and asking a line would spend its attention.
606
+ // The models on offer, the service of the line in use first: a tool that reads this list
607
+ // shows that service's models at the top.
608
+ function sendModels(req, res, cfg, allKeys) {
609
+ const active = relay.active(cfg, allKeys);
610
+ const used = new Set(active.map((l) => providers.of(l.item).id));
611
+ const ids = used.size ? [...used] : ['anthropic'];
612
+ const first = active.length ? providers.of(active[0].item).id : 'anthropic';
613
+ const models = [];
614
+ for (const id of [first, ...['anthropic', 'openai'].filter((x) => x !== first)]) if (ids.includes(id)) models.push(...providers.byId(id).models.map(([m, name]) => [m, name, id]));
615
+ // What each ChatGPT sign-in's backend listed last.
616
+ const seen = new Set(models.map((m) => m[0]));
617
+ for (const a of cfg.accounts) {
618
+ if (a.kind !== 'chatgpt' || a.enabled === false) continue;
619
+ for (const m of chatgptModels.known(a.id) || []) if (!seen.has(m.slug) && seen.add(m.slug)) models.push([m.slug, m.name, 'openai']);
620
+ }
621
+ sendJson(res, 200, translate.modelList(speaksOpenAI(req) ? 'openai' : 'messages', models));
622
+ }
623
+
624
+ // --------------------------------------------------------------- the walk
625
+
626
+ async function handle(req, res, ctx) {
627
+ const { cfg, vault } = ctx.current();
628
+ const token = clientToken(req);
629
+ const account = isAccountToken(token);
630
+ const inbound = translate.detect(req);
631
+ if (!account && !sameToken(token, vault.gatewayToken)) {
632
+ sendError(res, 401, 'authentication_error',
633
+ 'claude-nonstop gateway: missing or invalid gateway token.', speaksOpenAI(req) ? 'responses' : null);
634
+ return;
635
+ }
636
+
637
+ let body;
638
+ try {
639
+ body = await readBody(req, MAX_BODY);
640
+ } catch (error) {
641
+ if (res.destroyed) return;
642
+ sendError(res, error.message === 'too large' ? 413 : 400,
643
+ error.message === 'too large' ? 'request_too_large' : 'invalid_request_error',
644
+ error.message === 'too large'
645
+ ? 'claude-nonstop gateway: request body too large.'
646
+ : 'claude-nonstop gateway: could not read request body.', inbound);
647
+ return;
648
+ }
649
+
650
+ // Signed in to a Claude.ai account: no key is spent, the request goes out as it came.
651
+ if (account) {
652
+ await passthrough(cfg, req, res, body);
653
+ return;
654
+ }
655
+
656
+ if (inbound === 'models') {
657
+ sendModels(req, res, cfg, vault.keys);
658
+ return;
659
+ }
660
+
661
+ // Terminal Claude Code sessions on API keys name their keys; everything else walks the
662
+ // whole order, accounts included.
663
+ const desktop = !isSession(req);
664
+
665
+ // A request the gateway doesn't translate (token counting, say) goes out as it came, on
666
+ // the first Anthropic line.
667
+ if (!inbound) {
668
+ await rawAnthropic(req, res, ctx, body, desktop);
669
+ return;
670
+ }
671
+
672
+ const json = parseJson(body);
673
+ if (!json) {
674
+ sendError(res, 400, 'invalid_request_error', 'claude-nonstop gateway: the request body is not JSON.', inbound);
675
+ return;
676
+ }
677
+ let parsed;
678
+ try {
679
+ parsed = translate.readRequest(inbound, json);
680
+ } catch (err) {
681
+ sendError(res, 400, 'invalid_request_error', `claude-nonstop gateway: could not read the request: ${err.message}`, inbound);
682
+ return;
683
+ }
684
+ const clientStream = Boolean(json.stream);
685
+ const requested = String(json.model || '');
686
+ const client = clientOf(req, inbound);
687
+ // How the client declared each tool, so the answer's tool calls go back the same way.
688
+ const toolKinds = inbound === 'responses' ? translate.FORMATS.responses.toolKinds(parsed) : {};
689
+
690
+ const lines = [];
691
+ const named = lineFor(req, cfg);
692
+ if (named) lines.push(...named);
693
+ else if (desktop) {
694
+ for (const group of relay.groups(cfg, vault.keys)) {
695
+ if (group.kind === 'account') lines.push({ kind: 'account', item: group.account });
696
+ else for (const key of group.keys) lines.push({ kind: 'key', item: key });
697
+ }
698
+ } else {
699
+ for (const key of keysFor(req, cfg, vault.keys)) lines.push({ kind: 'key', item: key });
700
+ }
701
+
702
+ let attempted = 0;
703
+ // Seconds until an account refused only for a burst can be tried again.
704
+ let busy = 0;
705
+ let cooled = 0;
706
+ let lastError = '';
707
+ const fail = (status, type, message) => {
708
+ if (!res.destroyed && !res.headersSent) sendError(res, status, type, message, inbound);
709
+ };
710
+
711
+ for (const line of lines) {
712
+ const { item } = line;
713
+ if (line.kind === 'account' && (busyUntil.get(item.id) || 0) > Date.now()) {
714
+ busy = Math.max(busy, Math.ceil((busyUntil.get(item.id) - Date.now()) / 1000));
715
+ log(`gateway: ${item.label}: rate limited for a few seconds; trying the next line`);
716
+ continue;
717
+ }
718
+ const provider = providers.of(item);
719
+ const wire = provider.wire;
720
+ const model = modelFor(requested, provider, cfg);
721
+ const sameFormat = inbound === wire && model === requested;
722
+ const chatgpt = line.kind === 'account' && provider.id === 'openai';
723
+ const upstreamStream = chatgpt ? true : clientStream;
724
+ const label = item.label;
725
+
726
+ // ---- what goes out, and where
727
+ let outBody;
728
+ let url;
729
+ let headers;
730
+ let creds = null;
731
+ let chatgptModel = model;
732
+ // Whatever format it came in, a request to the Codex backend is shaped the same way.
733
+ const chatgptBody = (m) => asResponsesBody(inbound === 'responses' ? json : translate.writeRequest('responses', { ...parsed, stream: true }, { model: m, store: false, stream: true, includeEncrypted: true }), m, { chatgpt: true });
734
+ if (line.kind === 'account' && provider.id === 'anthropic') {
735
+ const { token: t, why } = await claudeToken(item, cfg);
736
+ if (!t) {
737
+ log(`gateway: ${label}: ${why}; trying the next line`);
738
+ continue;
739
+ }
740
+ const messagesBody = sameFormat ? body : Buffer.from(JSON.stringify(translate.writeRequest('messages', parsed, { model })));
741
+ outBody = client === 'claude' ? asClaudeCodeBody(messagesBody) : asSignInBody(messagesBody);
742
+ url = `${cfg.upstream}/v1/messages`;
743
+ headers = claudeAccountHeaders(req.headers, sameFormat, t, outBody.length, { asClaudeCode: client === 'claude' });
744
+ } else if (chatgpt) {
745
+ const r = await chatgptCredentials(item, cfg);
746
+ if (!r.creds) {
747
+ log(`gateway: ${label}: ${r.why}; trying the next line`);
748
+ continue;
749
+ }
750
+ creds = r.creds;
751
+ // The Codex backend takes only the models on its own list for this account.
752
+ chatgptModel = await chatgptModels.pick(model, item.id, creds, cfg);
753
+ outBody = chatgptBody(chatgptModel);
754
+ url = `${providers.openai.chatgptUpstream(cfg)}/responses`;
755
+ headers = chatgptHeaders(creds, outBody.length);
756
+ } else if (line.kind === 'key') {
757
+ if (state.isCoolingDown(item.id, cfg.cooldownMinutes)) {
758
+ cooled++;
759
+ continue;
760
+ }
761
+ attempted++;
762
+ if (provider.id === 'anthropic') {
763
+ outBody = asPlainApiBody(sameFormat ? body : Buffer.from(JSON.stringify(translate.writeRequest('messages', parsed, { model }))));
764
+ url = `${cfg.upstream}/v1/messages`;
765
+ headers = claudeKeyHeaders(req.headers, sameFormat, item.key, outBody.length);
766
+ } else {
767
+ // A Responses request for the model it named goes to OpenAI exactly as it came.
768
+ outBody = inbound === 'responses' ? (sameFormat ? body : asResponsesBody(json, model, { chatgpt: false })) : Buffer.from(JSON.stringify(translate.writeRequest('responses', parsed, { model, store: false })));
769
+ url = `${providers.openai.upstream(cfg)}/responses`;
770
+ headers = openaiKeyHeaders(req.headers, sameFormat, item.key, outBody.length);
771
+ }
772
+ } else {
773
+ continue;
774
+ }
775
+
776
+ // ---- send it, once more after renewing a ChatGPT sign-in that was refused
777
+ let upRes;
778
+ let upstream;
779
+ for (let attempt = 0; ; attempt++) {
780
+ const r = await forward(url, 'POST', outBody, headers);
781
+ if (r.error) {
782
+ log(`gateway: upstream connection failed: ${r.error.message}`);
783
+ fail(502, 'api_error', `claude-nonstop gateway could not reach ${new URL(url).origin}: ${r.error.message}`);
784
+ return;
785
+ }
786
+ upRes = r.res;
787
+ upstream = r.upstream;
788
+ if (chatgpt && upRes.statusCode === 400 && attempt === 0) {
789
+ // The backend's model list may have changed since it was last asked: ask again,
790
+ // and send the request once more with a model it lists now.
791
+ const text = (await readBody(upRes, MAX_ERROR_BODY).catch(() => Buffer.alloc(0))).toString('utf8');
792
+ if (chatgptModels.isModelRefusal(400, text)) {
793
+ const again = await chatgptModels.pick(model, item.id, creds, cfg, { force: true });
794
+ if (again !== chatgptModel) {
795
+ log(`gateway: ${label}: the ChatGPT backend no longer lists ${chatgptModel}; sending ${again} instead`);
796
+ chatgptModel = again;
797
+ outBody = chatgptBody(chatgptModel);
798
+ headers = chatgptHeaders(creds, outBody.length);
799
+ continue;
800
+ }
801
+ }
802
+ // Not a model problem, or nothing better to send: hand the answer on as it is.
803
+ upstream.destroy();
804
+ fail(400, 'invalid_request_error', `${label}: ${provider.errorMessage(text) || text || 'HTTP 400'}`);
805
+ return;
806
+ }
807
+ if (chatgpt && upRes.statusCode === 401 && attempt === 0) {
808
+ upstream.destroy();
809
+ try {
810
+ creds = await openaiAuth.refresh(item.id);
811
+ headers = chatgptHeaders(creds, outBody.length);
812
+ continue;
813
+ } catch (err) {
814
+ state.recordAccount(item.id, { ok: false, reason: `sign-in refused: ${err.message}` });
815
+ log(`gateway: ${label}: sign-in refused and could not be renewed (${err.message}); trying the next line`);
816
+ events.emit('switch', { accountId: item.id, label, status: 401, detail: err.message });
817
+ upRes = null;
818
+ }
819
+ }
820
+ break;
821
+ }
822
+ if (!upRes) continue;
823
+
824
+ // ---- what the answer means for the line
825
+ const status = upRes.statusCode;
826
+ const ref = line.kind === 'account' ? { accountId: item.id, label } : { keyId: item.id, label };
827
+ if (line.kind === 'account' && (status === 429 || status === 401 || status === 403)) {
828
+ const errBody = await readBody(upRes, MAX_ERROR_BODY).catch(() => Buffer.alloc(0));
829
+ const text = errBody.toString('utf8');
830
+ const detail = provider.errorMessage(text) || `HTTP ${status}`;
831
+ // A usage limit says so; any other 429 is a passing refusal, so the account isn't set aside for it.
832
+ const limited = status === 429 && (provider.id === 'openai'
833
+ ? providers.openai.isLimit(status, text, upRes.headers)
834
+ : accounts.isLimitReason(detail) || /rejected/i.test(String(upRes.headers['anthropic-ratelimit-unified-status'] || '')));
835
+ // "would exceed your account's rate limit" is a short burst refusal, not the plan
836
+ // running out: that account is only skipped for this request and the next few seconds.
837
+ if (status === 429 && !limited) {
838
+ const wait = Math.min(60, Math.max(5, Number(upRes.headers['retry-after']) || 10));
839
+ busyUntil.set(item.id, Date.now() + wait * 1000);
840
+ busy = Math.max(busy, wait);
841
+ }
842
+ if (status !== 429 || limited) {
843
+ state.recordAccount(item.id, { ok: false, reason: limited ? `usage limit reached: ${detail}` : `sign-in refused: ${detail}` });
844
+ }
845
+ if (chatgpt) recordChatgptUsage(item, upRes.headers);
846
+ log(`gateway: ${label} unavailable (HTTP ${status}: ${detail}); trying the next line`);
847
+ events.emit('switch', { ...ref, status, detail });
848
+ continue;
849
+ }
850
+ if (line.kind === 'key' && status >= 400) {
851
+ const errBody = await readBody(upRes, MAX_ERROR_BODY).catch(() => Buffer.alloc(0));
852
+ const text = errBody.toString('utf8');
853
+ if (provider.classify(status, text) === 'used-up') {
854
+ const detail = provider.errorMessage(text);
855
+ lastError = detail;
856
+ state.recordKey(item.id, { verdict: 'used-up', status, detail });
857
+ log(`gateway: API key "${label}" unavailable (HTTP ${status}); trying next key`);
858
+ events.emit('switch', { ...ref, status, detail });
859
+ continue;
860
+ }
861
+ events.emit('request', { ...ref, status, path: req.url });
862
+ if (res.destroyed || res.headersSent) return;
863
+ // The error in the client's format, with the provider's message.
864
+ if (inbound === wire) {
865
+ res.writeHead(status, responseHeaders(upRes.headers, errBody.length));
866
+ res.end(errBody);
867
+ } else {
868
+ sendError(res, status, status === 400 ? 'invalid_request_error' : status === 429 ? 'rate_limit_error' : 'api_error', provider.errorMessage(text) || `HTTP ${status} from ${provider.name}`, inbound);
869
+ }
870
+ return;
871
+ }
872
+ if (status >= 400) {
873
+ // An account's other refusals (a malformed request, say) are the client's to see.
874
+ const errBody = await readBody(upRes, MAX_ERROR_BODY).catch(() => Buffer.alloc(0));
875
+ events.emit('request', { ...ref, status, path: req.url });
876
+ if (res.destroyed || res.headersSent) return;
877
+ if (inbound === wire) {
878
+ res.writeHead(status, responseHeaders(upRes.headers, errBody.length));
879
+ res.end(errBody);
880
+ } else {
881
+ sendError(res, status, status === 400 ? 'invalid_request_error' : 'api_error', provider.errorMessage(errBody.toString('utf8')) || `HTTP ${status} from ${provider.name}`, inbound);
882
+ }
883
+ return;
884
+ }
885
+
886
+ // ---- it answered
887
+ if (line.kind === 'account') {
888
+ if (state.load().accounts[item.id]?.ok === false) state.recordAccount(item.id, { ok: true, reason: '' });
889
+ ctx.noteAccountInUse(item, { desktop });
890
+ if (chatgpt) recordChatgptUsage(item, upRes.headers);
891
+ } else {
892
+ ctx.noteKeyInUse(item, { desktop });
893
+ }
894
+ events.emit('request', { ...ref, status, path: req.url });
895
+ log(`gateway: ${inbound} request went out on ${line.kind === 'key' ? `API key "${label}"` : label}${model !== requested ? ` as ${model}` : ''} (HTTP ${status})`);
896
+ deliver(res, upRes, upstream, { inbound, wire, clientStream, upstreamStream, model: requested || model, includeUsage: Boolean(parsed.includeUsage), toolKinds });
897
+ return;
898
+ }
899
+
900
+ if (busy) {
901
+ // Only a passing rate limit stood in the way: answer like the service does, so the client
902
+ // waits and retries by itself instead of stopping on a billing error.
903
+ log(`gateway: every line is busy or out; accounts rate limited for ${busy}s, asking the client to retry`);
904
+ if (!res.destroyed && !res.headersSent) {
905
+ res.setHeader('retry-after', String(busy));
906
+ sendError(res, 429, 'rate_limit_error', `claude-nonstop: your accounts are rate limited for a few seconds; retrying in ${busy}s.`, inbound);
907
+ }
908
+ return;
909
+ }
910
+ events.emit('exhausted', {});
911
+ const reason = desktop
912
+ ? 'no subscription account has usage left and no API key has credit right now. Add an account or top up a key in the web UI, or sign in to Claude.ai in the desktop app.'
913
+ : named
914
+ ? `${named.length ? `${named[0].item.label} has no usage left right now` : 'that account is gone or paused'}.`
915
+ : !lines.length
916
+ ? 'no API key matched this session.'
917
+ : !attempted
918
+ ? `every API key is used up (${cooled} cooling down).`
919
+ : 'every API key is used up for this request.';
920
+ log(`gateway: request exhausted every line; attempted=${attempted}, coolingDown=${cooled}`);
921
+ fail(402, 'billing_error', `claude-nonstop: ${reason}` + (lastError ? ` Last upstream error: ${lastError}` : ''));
922
+ }
923
+
924
+ // Codex's rate-limit headers come with every answer from the Codex backend; they're this
925
+ // account's usage readout.
926
+ function recordChatgptUsage(account, headers) {
927
+ const u = providers.openai.usageFromHeaders(headers);
928
+ if (!u) return;
929
+ state.recordUsage(account.id, { ...u, at: Date.now() });
930
+ events.notify('usage', { id: account.id });
931
+ }
932
+
933
+ // A request on a path the gateway doesn't translate, sent as it came on the first Anthropic
934
+ // line (an account for the desktop app, a key for everyone).
935
+ async function rawAnthropic(req, res, ctx, body, desktop) {
936
+ const { cfg, vault } = ctx.current();
937
+ const lines = [];
938
+ if (desktop) {
939
+ for (const group of relay.groups(cfg, vault.keys)) {
940
+ if (group.kind === 'account') lines.push({ kind: 'account', item: group.account });
941
+ else for (const key of group.keys) lines.push({ kind: 'key', item: key });
942
+ }
943
+ } else {
944
+ for (const key of keysFor(req, cfg, vault.keys)) lines.push({ kind: 'key', item: key });
945
+ }
946
+ for (const line of lines.filter((l) => providers.of(l.item).id === 'anthropic')) {
947
+ const { item } = line;
948
+ let outBody;
949
+ let headers;
950
+ if (line.kind === 'account') {
951
+ const { token } = await claudeToken(item, cfg);
952
+ if (!token) continue;
953
+ outBody = asClaudeCodeBody(body);
954
+ headers = claudeAccountHeaders(req.headers, true, token, outBody.length);
955
+ } else {
956
+ if (state.isCoolingDown(item.id, cfg.cooldownMinutes)) continue;
957
+ outBody = asPlainApiBody(body);
958
+ headers = claudeKeyHeaders(req.headers, true, item.key, outBody.length);
959
+ }
960
+ const { res: upRes, upstream, error } = await forward(`${cfg.upstream}${req.url}`, req.method, outBody, headers);
961
+ if (error) {
962
+ if (!res.destroyed && !res.headersSent) sendError(res, 502, 'api_error', `claude-nonstop gateway could not reach ${cfg.upstream}: ${error.message}`);
963
+ return;
964
+ }
965
+ if (upRes.statusCode === 401 || upRes.statusCode === 403 || (upRes.statusCode === 429 && line.kind === 'account')) {
966
+ upstream.destroy();
967
+ continue;
968
+ }
969
+ log(`gateway: ${req.method} ${req.url.split('?')[0]} went out on ${item.label} (HTTP ${upRes.statusCode})`);
970
+ pipe(res, upRes, upstream);
971
+ return;
972
+ }
973
+ if (!res.destroyed && !res.headersSent) sendError(res, 402, 'billing_error', 'claude-nonstop: no Anthropic line could take this request.');
974
+ }
975
+
976
+ module.exports = { handle, claudeToken, renewExpiring, sameToken, sendError, readBody, isAccountToken, asPlainApiBody, asClaudeCodeBody, asSignInBody, clientOf, modelFor, KEYS_HEADER, LINE_HEADER };