@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
@@ -0,0 +1,841 @@
1
+ 'use strict';
2
+
3
+ // The management commands: everything except launching Claude Code.
4
+
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+ const { spawn } = require('child_process');
9
+ const paths = require('./paths');
10
+ const config = require('./config');
11
+ const vault = require('./vault');
12
+ const keys = require('./keys');
13
+ const relay = require('./relay');
14
+ const accounts = require('./accounts');
15
+ const state = require('./state');
16
+ const claude = require('./claude');
17
+ const keystore = require('./keystore');
18
+ const desktop = require('./desktop');
19
+ const marketplace = require('./marketplace');
20
+ const hostsfile = require('./hostsfile');
21
+ const system = require('./system');
22
+ const tls = require('./tls');
23
+ const service = require('./service');
24
+ const shell = require('./shell');
25
+ const clients = require('./clients');
26
+ const codex = require('./codex');
27
+ const prompt = require('./prompt');
28
+ const openaiAuth = require('./openai-auth');
29
+ const providers = require('./providers');
30
+ const { gatewayRunning, gatewayUrl } = require('./launch');
31
+ const { FRIENDLY_HOST } = require('./hosts');
32
+ const { ensureHome, readJson, log } = require('./files');
33
+ const pkg = require('../package.json');
34
+
35
+ const out = (line = '') => process.stdout.write(`${line}\n`);
36
+ const say = (message) => process.stderr.write(`claude-nonstop: ${message}\n`);
37
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
38
+
39
+ function ago(at) {
40
+ const m = Math.max(0, Math.round((Date.now() - at) / 60000));
41
+ if (m === 0) return 'just now';
42
+ if (m < 60) return `${m} min ago`;
43
+ return `${Math.round(m / 60)} h ago`;
44
+ }
45
+
46
+ function describeKeyCheck(c) {
47
+ if (!c) return 'not checked yet';
48
+ const detail = c.detail ? `: ${c.detail}` : '';
49
+ if (c.verdict === 'ok') return 'works';
50
+ if (c.verdict === 'used-up') return `used up (HTTP ${c.status}${detail})`;
51
+ return `kept, the problem isn't this key (${c.status ? `HTTP ${c.status}` : 'no answer'}${detail})`;
52
+ }
53
+
54
+ function describeAccountCheck(c, u) {
55
+ const used = u && u.session ? `; ${require('./usage').describe(u)}` : '';
56
+ if (!c) return `not checked yet${used}`;
57
+ return `${c.ok ? 'had usage left' : c.reason} (${ago(c.at)})${used}`;
58
+ }
59
+
60
+ function requireClaude() {
61
+ const bin = claude.findClaude();
62
+ if (!bin) throw new Error("can't find Claude Code (the `claude` command). Install it from https://code.claude.com/docs/en/setup");
63
+ return bin;
64
+ }
65
+
66
+ // Finds an item by its number in the list (1-based) or by its label.
67
+ function pickItem(list, ref, noun) {
68
+ const n = Number(ref);
69
+ const item = Number.isInteger(n) && n >= 1 ? list[n - 1] : list.find((x) => x.label.toLowerCase() === String(ref || '').toLowerCase());
70
+ if (!item) throw new Error(`no ${noun} "${ref || ''}". See the numbers with \`claude-nonstop status\`.`);
71
+ return item;
72
+ }
73
+
74
+ function openBrowser(url) {
75
+ const opts = { detached: true, stdio: 'ignore', windowsHide: true };
76
+ if (process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return false;
77
+ try {
78
+ const cmd =
79
+ process.platform === 'darwin'
80
+ ? ['open', [url]]
81
+ : process.platform === 'win32'
82
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
83
+ : ['xdg-open', [url]];
84
+ const child = spawn(cmd[0], cmd[1], opts);
85
+ child.on('error', () => {});
86
+ child.unref();
87
+ return true;
88
+ } catch {
89
+ return false;
90
+ }
91
+ }
92
+
93
+ async function ensureServer(cfg) {
94
+ if (await gatewayRunning(cfg)) return true;
95
+ service.startDetached();
96
+ for (let i = 0; i < 60; i++) {
97
+ await sleep(100);
98
+ if (await gatewayRunning(cfg)) return true;
99
+ }
100
+ return false;
101
+ }
102
+
103
+ // ---------------------------------------------------------------- serve / ui / status
104
+
105
+ async function serve(args) {
106
+ const cfg = config.load();
107
+ if (await gatewayRunning(cfg)) {
108
+ if (!args.includes('--background')) say(`already running on ${gatewayUrl(cfg)}`);
109
+ return 0;
110
+ }
111
+ if (args.includes('--background')) {
112
+ service.startDetached();
113
+ return 0;
114
+ }
115
+ try {
116
+ marketplace.ensure();
117
+ } catch {}
118
+ try {
119
+ await require('./server').serve();
120
+ } catch (err) {
121
+ if (err.code === 'EADDRINUSE') {
122
+ say(`port ${cfg.port} is used by another program. Set a different "port" in ${paths.CONFIG}.`);
123
+ return 1;
124
+ }
125
+ throw err;
126
+ }
127
+ say(`gateway and web UI running on ${gatewayUrl(cfg)} (Ctrl-C stops them)`);
128
+ return new Promise(() => {});
129
+ }
130
+
131
+ async function ui(args = []) {
132
+ ensureHome();
133
+ const cfg = config.load();
134
+ const v = vault.loadWithTokens();
135
+ if (!(await ensureServer(cfg))) {
136
+ say(`couldn't start the local server; details are in ${paths.GATEWAY_LOG}`);
137
+ return 1;
138
+ }
139
+ const url = `${uiUrl(cfg)}/auth?t=${encodeURIComponent(v.uiToken)}`;
140
+ if (!args.includes('--no-open') && openBrowser(url)) out(`Opened the claude-nonstop web UI. If no browser window appeared, open:\n ${url}`);
141
+ else out(`Open the claude-nonstop web UI at:\n ${url}`);
142
+ return 0;
143
+ }
144
+
145
+ // The web UI's address, as the running server reported it: http://claude-nonstop.localhost
146
+ // when it could take port 80, otherwise the same name with the gateway's port.
147
+ function uiUrl(cfg) {
148
+ const info = readJson(paths.SERVER, null);
149
+ return (info && info.uiUrl) || `http://${FRIENDLY_HOST}:${cfg.port}`;
150
+ }
151
+
152
+ async function status() {
153
+ ensureHome();
154
+ const cfg = config.load();
155
+ const v = vault.loadWithTokens();
156
+ const s = state.load();
157
+ const running = await gatewayRunning(cfg);
158
+ out(`claude-nonstop ${pkg.version}`);
159
+ const bin = claude.findClaude();
160
+ const cv = bin ? await claude.version(bin) : null;
161
+ const note = cv && !claude.atLeast(cv) ? ', update it with `claude update` so sessions continue by themselves after limits' : '';
162
+ out(` Claude Code ${bin ? `${bin}${cv ? ` (${cv.join('.')}${note})` : ''}` : 'not found'}`);
163
+ out(` Secrets encrypted, key in ${keystore.describe()}`);
164
+ out(` Gateway ${running ? `running on ${gatewayUrl(cfg)}` : 'not running'}${service.status().installed ? ', starts at login' : ''}`);
165
+ if (running) out(` Web UI ${uiUrl(cfg)} (open it with \`claude-nonstop ui\`)`);
166
+ out(` Updates ${cfg.autoUpdate === false ? 'off' : 'install themselves'}`);
167
+ out(` claude shortcut ${shell.status().installed ? 'on' : 'off'}`);
168
+ const d = desktop.status(desktop.settings(cfg, v));
169
+ out(` Desktop app ${!d.installed ? 'not installed' : d.automatic ? 'set up to use the gateway' : 'not set up yet (run `claude-nonstop desktop`)'}`);
170
+ out(` Codex ${!codex.installed() ? 'not installed' : codex.status(cfg).wired ? 'set up to use the gateway (no OpenAI sign-in needed)' : 'not set up yet (run `claude-nonstop connect codex`)'}`);
171
+ // Where a new terminal session starts: the cable's line, else the first line in your order
172
+ // with usage left. The gateway serves the desktop app from the API keys in that order.
173
+ const usable = (l) => (l.type === 'account' ? !(s.accounts[l.item.id] && !s.accounts[l.item.id].ok) : !state.isCoolingDown(l.item.id, cfg.cooldownMinutes));
174
+ const next = relay.active(cfg, v.keys).find(usable);
175
+ out(` Sessions start on ${next ? `${next.item.label}${next.type === 'key' ? ' (API key)' : ''}${cfg.pinned ? ' (the cable)' : ''}` : 'nothing with usage left'}`);
176
+ out(` Last session ${s.current ? `${s.current} (${ago(s.currentAt)})` : 'none yet'}`);
177
+ out('');
178
+ out('Your accounts and API keys, tried in this order:');
179
+ relay.lines(cfg, v.keys).forEach((l, i) => out(` ${describeLine(cfg, s, l, i)}`));
180
+ if (!v.keys.length) out(' (no API keys yet. Add some with `claude-nonstop ui` or `claude-nonstop keys add`.)');
181
+ out('');
182
+ out('Change the order with `claude-nonstop move <n> up|down`, or drag lines in `claude-nonstop ui`.');
183
+ return 0;
184
+ }
185
+
186
+ function describeLine(cfg, s, l, i) {
187
+ const paused = relay.isPaused(cfg, l.type, l.item) ? ' (paused)' : '';
188
+ const p = providers.of(l.item);
189
+ const what = l.type === 'account'
190
+ ? `${l.item.label} (${accounts.isChatgpt(l.item) ? 'ChatGPT account' : 'Claude account'})${paused}: ${describeAccountCheck(s.accounts[l.item.id], s.usage[l.item.id])}`
191
+ : `${l.item.label} (${p.name} API key ${keys.mask(l.item.key)})${paused}: ${describeKeyCheck(s.keys[l.item.id])}`;
192
+ return `${i + 1}. ${what}`;
193
+ }
194
+
195
+ // ---------------------------------------------------------------- the relay order
196
+
197
+ // `move <n> up|down`, `pause <n>`, `resume <n>`: n is a line's number in `status` or its name.
198
+ function pickLine(ref) {
199
+ const all = relay.lines(config.load(), vault.loadWithTokens().keys);
200
+ const n = Number(ref);
201
+ const line = Number.isInteger(n) && n >= 1 ? all[n - 1] : all.find((l) => l.item.label.toLowerCase() === String(ref || '').toLowerCase());
202
+ if (!line) throw new Error(`no account or key "${ref || ''}". See the numbers with \`claude-nonstop status\`.`);
203
+ return line;
204
+ }
205
+
206
+ function moveCommand([ref, direction] = []) {
207
+ if (direction !== 'up' && direction !== 'down') {
208
+ say('usage: claude-nonstop move <n> up|down');
209
+ return 1;
210
+ }
211
+ const line = pickLine(ref);
212
+ const all = vault.load().keys;
213
+ config.update((c) => (c.order = relay.moved(c, all, line.type, line.item.id, direction)));
214
+ const v = vault.loadWithTokens();
215
+ const cfg = config.load();
216
+ const s = state.load();
217
+ out('Your accounts and API keys, tried in this order:');
218
+ relay.lines(cfg, v.keys).forEach((l, i) => out(` ${describeLine(cfg, s, l, i)}`));
219
+ return 0;
220
+ }
221
+
222
+ function pauseCommand(paused, [ref] = []) {
223
+ const line = pickLine(ref);
224
+ config.update((c) => {
225
+ if (line.type === 'account') c.accounts.find((a) => a.id === line.item.id).enabled = !paused;
226
+ else c.pausedKeys = [...(c.pausedKeys || []).filter((k) => k !== line.item.id), ...(paused ? [line.item.id] : [])];
227
+ });
228
+ out(paused ? `${line.item.label} is paused. It stays saved but isn't used until you resume it.` : `${line.item.label} is back in use.`);
229
+ return 0;
230
+ }
231
+
232
+ // ---------------------------------------------------------------- keys
233
+
234
+ async function checkAllKeys() {
235
+ const v = vault.loadWithTokens();
236
+ const cfg = config.load();
237
+ if (!v.keys.length) {
238
+ out('No API keys yet. Add one with `claude-nonstop keys add` or `claude-nonstop ui`.');
239
+ return 0;
240
+ }
241
+ out('API keys, tried top to bottom:');
242
+ for (const [i, entry] of v.keys.entries()) {
243
+ const check = await keys.check(entry, cfg);
244
+ out(` ${i + 1}. ${entry.label.padEnd(16)} ${keys.mask(entry.key).padEnd(20)} ${describeKeyCheck(check)}`);
245
+ }
246
+ return 0;
247
+ }
248
+
249
+ async function addKey(label) {
250
+ const key = await prompt.secret('Paste your Claude or OpenAI API key (it stays hidden): ');
251
+ const problem = keys.problemWith(key);
252
+ if (problem) {
253
+ say(`can't save it: ${problem}`);
254
+ return 1;
255
+ }
256
+ let entry;
257
+ try {
258
+ entry = vault.update((v) => {
259
+ if (v.keys.some((k) => k.id === keys.fingerprint(key))) throw new Error('that key is already saved');
260
+ const created = keys.newEntry(key, label.trim().slice(0, 60), v.keys.length + 1);
261
+ v.keys.push(created);
262
+ return created;
263
+ });
264
+ } catch (err) {
265
+ say(err.message);
266
+ return 1;
267
+ }
268
+ log(`added API key "${entry.label}"`);
269
+ const check = await keys.check(entry, config.load());
270
+ out(`Saved "${entry.label}" (${keys.mask(key)}): ${describeKeyCheck(check)}`);
271
+ return 0;
272
+ }
273
+
274
+ function removeKey(ref) {
275
+ const entry = pickItem(vault.load().keys, ref, 'key');
276
+ vault.update((v) => {
277
+ v.keys = v.keys.filter((k) => k.id !== entry.id);
278
+ });
279
+ state.forgetKey(entry.id);
280
+ out(`Removed "${entry.label}".`);
281
+ return 0;
282
+ }
283
+
284
+ function keysCommand([sub, ...rest] = []) {
285
+ if (!sub || sub === 'list' || sub === 'check') return checkAllKeys();
286
+ if (sub === 'add') return addKey(rest.join(' '));
287
+ if (sub === 'remove' || sub === 'rm') return removeKey(rest[0]);
288
+ say(`unknown command: keys ${sub}`);
289
+ return 1;
290
+ }
291
+
292
+ // ---------------------------------------------------------------- accounts
293
+
294
+ async function listAccounts() {
295
+ const cfg = config.load();
296
+ const bin = claude.findClaude();
297
+ const s = state.load();
298
+ out('Subscription accounts, tried in this order:');
299
+ for (const [i, a] of cfg.accounts.entries()) {
300
+ const login = bin || accounts.isChatgpt(a) ? await accounts.status(a, bin) : { loggedIn: null, error: 'Claude Code was not found' };
301
+ const who = login.loggedIn ? `signed in${login.email ? ` as ${login.email}` : ''}${login.plan ? ` (${login.plan})` : ''}` : login.loggedIn === false ? 'not signed in' : `sign-in not checked (${login.error})`;
302
+ out(` ${i + 1}. ${a.label} (${accounts.isChatgpt(a) ? 'ChatGPT' : 'Claude'})${a.enabled === false ? ' (off)' : ''}: ${who}; ${describeAccountCheck(s.accounts[a.id], s.usage[a.id])}`);
303
+ }
304
+ out('');
305
+ out('Add one with `claude-nonstop accounts add "Work"` (a Claude account) or `claude-nonstop accounts add "Work" --chatgpt`, or in `claude-nonstop ui`.');
306
+ return 0;
307
+ }
308
+
309
+ // Signs in to a ChatGPT account: OpenAI's own page in the browser, caught by openai-auth.js.
310
+ async function signInChatgpt(account) {
311
+ const login = await openaiAuth.startLogin(account.id);
312
+ out(`Sign in to "${account.label}" in the browser window that opens (OpenAI's own sign-in page).`);
313
+ if (!openBrowser(login.url)) out(`Open this address in a browser:\n ${login.url}`);
314
+ else out(`No window? Open this address:\n ${login.url}`);
315
+ let creds;
316
+ try {
317
+ creds = await login.done;
318
+ } catch (err) {
319
+ say(`sign-in didn't finish: ${err.message}. Try again with \`claude-nonstop accounts login ${account.label}\`.`);
320
+ return 1;
321
+ }
322
+ state.forgetAccount(account.id);
323
+ const check = await accounts.probeChatgpt(account);
324
+ out(`Signed in to "${account.label}"${creds.email ? ` as ${creds.email}` : ''}${creds.plan ? ` (${creds.plan})` : ''}: ${check.ok ? 'it has usage left' : check.reason}`);
325
+ return 0;
326
+ }
327
+
328
+ async function signIn(account, bin) {
329
+ if (accounts.isChatgpt(account)) return signInChatgpt(account);
330
+ out(`Sign in to "${account.label}" in the browser window that opens (Anthropic's own sign-in page).`);
331
+ const code = await claude.runInteractive(bin, accounts.LOGIN_ARGS, accounts.env(account));
332
+ state.forgetAccount(account.id);
333
+ if (code !== 0) {
334
+ say(`sign-in didn't finish. Try again with \`claude-nonstop accounts login ${account.label}\`.`);
335
+ return code;
336
+ }
337
+ const check = await accounts.probe(account, bin);
338
+ out(`Signed in to "${account.label}": ${check.ok ? 'it has usage left' : check.reason}`);
339
+ return 0;
340
+ }
341
+
342
+ async function accountsCommand([sub, ...rest] = []) {
343
+ if (!sub || sub === 'list') return listAccounts();
344
+ const cfg = config.load();
345
+ if (sub === 'add') {
346
+ const flags = new Set(rest.filter((a) => a.startsWith('--')));
347
+ const label = rest.filter((a) => !a.startsWith('--')).join(' ').trim().slice(0, 60) || `Account ${cfg.accounts.length + 1}`;
348
+ if (flags.has('--chatgpt') || flags.has('--openai') || flags.has('--codex') || flags.has('--import-codex')) {
349
+ const account = accounts.createChatgpt(label);
350
+ config.update((c) => c.accounts.push(account));
351
+ log(`added ChatGPT account "${account.label}"`);
352
+ if (flags.has('--import-codex')) {
353
+ try {
354
+ const creds = openaiAuth.importCodexAuth(account.id);
355
+ const check = await accounts.probeChatgpt(account);
356
+ out(`Added "${account.label}" with Codex's sign-in${creds.email ? ` (${creds.email})` : ''}: ${check.ok ? 'it has usage left' : check.reason}`);
357
+ return 0;
358
+ } catch (err) {
359
+ config.update((c) => (c.accounts = c.accounts.filter((a) => a.id !== account.id)));
360
+ say(err.message);
361
+ return 1;
362
+ }
363
+ }
364
+ return signInChatgpt(account);
365
+ }
366
+ const bin = requireClaude();
367
+ const account = accounts.createProfile(label);
368
+ config.update((c) => c.accounts.push(account));
369
+ log(`added account "${account.label}"`);
370
+ return signIn(account, bin);
371
+ }
372
+ if (sub === 'login') {
373
+ const account = pickItem(cfg.accounts, rest[0] || '1', 'account');
374
+ return signIn(account, accounts.isChatgpt(account) ? null : requireClaude());
375
+ }
376
+ if (sub === 'check') {
377
+ const bin = cfg.accounts.some((a) => a.enabled !== false && !accounts.isChatgpt(a)) ? requireClaude() : claude.findClaude();
378
+ for (const a of cfg.accounts.filter((x) => x.enabled !== false)) {
379
+ const r = await accounts.probe(a, bin);
380
+ out(` ${a.label}: ${r.ok ? 'has usage left' : r.reason}`);
381
+ }
382
+ return 0;
383
+ }
384
+ if (sub === 'on' || sub === 'off') {
385
+ const account = pickItem(cfg.accounts, rest[0], 'account');
386
+ config.update((c) => {
387
+ c.accounts.find((a) => a.id === account.id).enabled = sub === 'on';
388
+ });
389
+ out(`${account.label} is ${sub}.`);
390
+ return 0;
391
+ }
392
+ if (sub === 'remove' || sub === 'rm') {
393
+ const account = pickItem(cfg.accounts, rest[0], 'account');
394
+ if (account.kind !== 'profile' && !accounts.isChatgpt(account)) {
395
+ say('the main account is your normal Claude Code login. Turn it off with `claude-nonstop accounts off 1` instead.');
396
+ return 1;
397
+ }
398
+ if (!(await prompt.confirm(`Sign out of "${account.label}" and remove it?`, false))) return 0;
399
+ await accounts.remove(account, claude.findClaude());
400
+ config.update((c) => {
401
+ c.accounts = c.accounts.filter((a) => a.id !== account.id);
402
+ });
403
+ out(`Removed "${account.label}".`);
404
+ return 0;
405
+ }
406
+ say(`unknown command: accounts ${sub}`);
407
+ return 1;
408
+ }
409
+
410
+ // ---------------------------------------------------------------- other tools
411
+
412
+ // How to point other tools at the gateway: Codex (the Responses API), Cursor and anything
413
+ // else that takes an OpenAI-compatible base address, and Claude Code itself.
414
+ function connectCommand(args = []) {
415
+ ensureHome();
416
+ const cfg = config.load();
417
+ const v = vault.loadWithTokens();
418
+ const url = gatewayUrl(cfg);
419
+ const show = (name) => !args.length || args.includes(name);
420
+ out(`Gateway address ${url}`);
421
+ out(`Gateway token ${v.gatewayToken}`);
422
+ out('Any account or API key in your order can answer any of these tools; a request for a model');
423
+ out(`from the other service goes to that line's default (${cfg.models.anthropic} / ${cfg.models.openai}).`);
424
+ if (show('codex')) {
425
+ out('');
426
+ if (codex.installed() && !args.includes('--print')) {
427
+ const c = codex.apply(cfg, v);
428
+ out(`Codex: ${c.changed ? 'now set up' : 'already set up'} in ${c.file}. Run \`codex\` (or open the Codex app) as usual; it needs no OpenAI sign-in.`);
429
+ out('The lines it holds, if you want to add them to another Codex by hand:');
430
+ } else out('Codex CLI: add this to ~/.codex/config.toml, then run `codex` as usual:');
431
+ out('');
432
+ out(` model = "${cfg.models.openai}"`);
433
+ out(' model_provider = "claude-nonstop"');
434
+ out('');
435
+ out(' [model_providers.claude-nonstop]');
436
+ out(' name = "claude-nonstop"');
437
+ out(` base_url = "${url}/v1"`);
438
+ out(' wire_api = "responses"');
439
+ out(` experimental_bearer_token = "${v.gatewayToken}"`);
440
+ out(' requires_openai_auth = false');
441
+ }
442
+ if (show('cursor')) {
443
+ out('');
444
+ out('Cursor: Settings → Models → turn on "Override OpenAI Base URL" and enter');
445
+ out(` Base URL ${url}/v1`);
446
+ out(` API key ${v.gatewayToken}`);
447
+ out(" (Cursor's own-key mode is a limited path: its Tab completions and some agent features stay off.)");
448
+ }
449
+ if (show('openai') || show('other')) {
450
+ out('');
451
+ out('Any other OpenAI-compatible tool:');
452
+ out(` OPENAI_BASE_URL=${url}/v1 OPENAI_API_KEY=${v.gatewayToken}`);
453
+ }
454
+ if (show('claude')) {
455
+ out('');
456
+ out('Claude Code and the Claude desktop app are set up by `claude-nonstop setup`; by hand:');
457
+ out(` ANTHROPIC_BASE_URL=${url} ANTHROPIC_AUTH_TOKEN=${v.gatewayToken}`);
458
+ }
459
+ return 0;
460
+ }
461
+
462
+ // ---------------------------------------------------------------- desktop
463
+
464
+ // Sets the desktop app up through its documented managed settings and says what happened.
465
+ // The web page runs this with --quiet and reads only the exit code.
466
+ function setUpDesktop(quiet) {
467
+ const cfg = config.load();
468
+ const v = vault.loadWithTokens();
469
+ const want = desktop.settings(cfg, v);
470
+ const tell = quiet ? () => {} : out;
471
+ if (process.env.CLAUDE_NONSTOP_DESKTOP_MANAGED === '0') return 'manual';
472
+ if (!desktop.appInstalled()) {
473
+ tell("- The Claude desktop app isn't installed. Run `claude-nonstop desktop` after installing it (claude.com/download).");
474
+ return 'missing';
475
+ }
476
+ if (desktop.applied(want)) {
477
+ tell('- The Claude desktop app is set up. On its sign-in screen, pick the third-party option to run on your API keys, or Claude.ai for your subscription.');
478
+ return 'done';
479
+ }
480
+ if (process.platform === 'darwin') {
481
+ if (!desktop.macProfile(want)) return 'manual';
482
+ tell('- Claude desktop app: System Settings just opened. Double-click "claude-nonstop for the Claude desktop app", click Install, then quit and reopen the app.');
483
+ return 'profile';
484
+ }
485
+ if (system.apply({ hosts: false, desktopSettings: want }).desktop) {
486
+ tell('- The Claude desktop app is set up. Quit and reopen it, then pick the third-party option on its sign-in screen to run on your API keys.');
487
+ return 'done';
488
+ }
489
+ tell("! The Claude desktop app wasn't set up (the administrator prompt was declined). Run `claude-nonstop desktop` to try again.");
490
+ return 'declined';
491
+ }
492
+
493
+ function desktopCommand(args = []) {
494
+ ensureHome();
495
+ const quiet = args.includes('--quiet');
496
+ const outcome = setUpDesktop(quiet);
497
+ if (outcome === 'done' || outcome === 'profile') return 0;
498
+ if (quiet) return 1;
499
+ const cfg = config.load();
500
+ const v = vault.loadWithTokens();
501
+ const file = desktop.write(cfg, v);
502
+ out('');
503
+ out(outcome === 'manual' ? 'To run the Claude desktop app on your API keys through claude-nonstop:' : 'To set it up by hand instead:');
504
+ desktop.STEPS.forEach((step, i) => out(` ${i + 1}. ${step}`));
505
+ out(` Gateway base URL ${gatewayUrl(cfg)}`);
506
+ out(` Gateway API key ${v.gatewayToken}`);
507
+ out(' Auth scheme Bearer');
508
+ out(` (also saved in ${file})`);
509
+ return 0;
510
+ }
511
+
512
+ // Connectors for the desktop app in third-party mode, where its own Add button is hidden.
513
+ function connectorsCommand(args = []) {
514
+ ensureHome();
515
+ const [sub, ...rest] = args;
516
+ const list = () => config.load().desktopConnectors || [];
517
+ if (sub === 'add') {
518
+ const noAuth = rest.includes('--no-oauth');
519
+ const [name, url] = rest.filter((a) => a !== '--no-oauth');
520
+ if (!name || !url) {
521
+ say('usage: claude-nonstop connectors add <name> <https-url> [--no-oauth]');
522
+ return 1;
523
+ }
524
+ let entry;
525
+ try {
526
+ entry = desktop.connector(name, url, { oauth: !noAuth });
527
+ } catch (err) {
528
+ say(err.message);
529
+ return 1;
530
+ }
531
+ config.update((c) => {
532
+ c.desktopConnectors = [...(c.desktopConnectors || []).filter((e) => e.name.toLowerCase() !== name.toLowerCase()), entry];
533
+ });
534
+ out(`Added the connector ${name} (${entry.url}).`);
535
+ } else if (sub === 'remove') {
536
+ const name = rest.join(' ');
537
+ if (!list().some((e) => e.name.toLowerCase() === name.toLowerCase())) {
538
+ say(`there is no connector called ${name || '""'}. \`claude-nonstop connectors\` lists them.`);
539
+ return 1;
540
+ }
541
+ config.update((c) => {
542
+ c.desktopConnectors = c.desktopConnectors.filter((e) => e.name.toLowerCase() !== name.toLowerCase());
543
+ });
544
+ out(`Removed the connector ${name}.`);
545
+ } else {
546
+ const all = list();
547
+ if (!all.length) out('No connectors yet. Add one with `claude-nonstop connectors add <name> <https-url>`.');
548
+ for (const e of all) out(` ${e.name} ${e.url}${e.oauth ? '' : ' (no sign-in)'}`);
549
+ out('Connectors show in the Claude desktop app when it runs on your API keys. On Claude.ai sign-in, use its own Connectors page.');
550
+ return 0;
551
+ }
552
+ if (setUpDesktop(false) === 'manual') out('Run `claude-nonstop desktop` to give the desktop app the new list.');
553
+ return 0;
554
+ }
555
+
556
+ // ---------------------------------------------------------------- setup / service / shell
557
+
558
+ function optionValue(args, name) {
559
+ const i = args.indexOf(name);
560
+ return i >= 0 ? args[i + 1] : undefined;
561
+ }
562
+
563
+ // Brings an older Claude Code up to the version that continues by itself after a usage
564
+ // limit, with Claude Code's own updater.
565
+ async function keepClaudeCurrent(bin) {
566
+ const v = await claude.version(bin);
567
+ if (!v || claude.atLeast(v)) return;
568
+ out(`- Updating Claude Code ${v.join('.')}, so sessions continue by themselves after a usage limit...`);
569
+ const r = await claude.capture(bin, ['update'], { timeoutMs: 300000 });
570
+ const after = await claude.version(bin);
571
+ if (after && claude.atLeast(after)) out(`- Claude Code is now ${after.join('.')}.`);
572
+ else out(`! Couldn't update Claude Code (${(r.stderr || r.stdout).trim().split('\n').pop() || `exit ${r.code}`}). Run \`claude update\` to get automatic continue after limits.`);
573
+ }
574
+
575
+ async function setup(args = []) {
576
+ const yes = args.includes('--yes') || args.includes('-y');
577
+ ensureHome();
578
+ const v = vault.loadWithTokens();
579
+ out(`- Secrets are stored encrypted; the encryption key is in ${keystore.describe()}.`);
580
+ const bin = claude.findClaude();
581
+ if (!bin) out('! Claude Code was not found. Install it (https://code.claude.com/docs/en/setup), then run `claude-nonstop setup` again.');
582
+ else await keepClaudeCurrent(bin);
583
+ if (!args.includes('--no-system') && !process.env.CI) {
584
+ // One admin prompt covers the short address and, on Windows and Linux, the desktop app.
585
+ const desktopSettings = args.includes('--no-desktop') ? null : desktop.settings(config.load(), v);
586
+ const done = system.apply({ hosts: !args.includes('--no-hosts'), desktopSettings });
587
+ if (done.hosts) {
588
+ const secure = tls.setup();
589
+ out(`- The web page is at ${secure ? 'https' : 'http'}://${hostsfile.PRIMARY} (also ${hostsfile.NAMES[1]})${secure ? ', with a certificate this computer trusts' : ''}.`);
590
+ } else {
591
+ out(`- The web page is at http://${FRIENDLY_HOST}. For the short address ${hostsfile.PRIMARY}, run \`claude-nonstop setup\` again and allow the change.`);
592
+ }
593
+ if (desktopSettings) setUpDesktop(false);
594
+ }
595
+ if (!args.includes('--no-service')) {
596
+ try {
597
+ out(`- The gateway starts whenever you log in: ${service.install()}`);
598
+ } catch (err) {
599
+ out(`! Couldn't set the gateway to start at login (${err.message}). \`claude-nonstop ui\` starts it when needed.`);
600
+ }
601
+ }
602
+ desktop.write(config.load(), v);
603
+ const plugins = marketplace.ensure();
604
+ if (plugins === 'added') out("- Anthropic's plugin marketplace is listed in Claude Code's settings, so plugins work the same in the desktop app.");
605
+ else if (plugins === 'unreadable') out(`! ${marketplace.settingsFile()} isn't valid JSON, so Anthropic's plugin marketplace wasn't added. Fix the file and run \`claude-nonstop setup\` again.`);
606
+ if (!args.includes('--no-shell')) {
607
+ if (yes || (await prompt.confirm('Make plain `claude` go through claude-nonstop in your terminals?', true))) {
608
+ try {
609
+ const changed = shell.install({ binDir: optionValue(args, '--bin-dir') });
610
+ out(`- Plain \`claude\` now goes through claude-nonstop (updated ${changed.join(', ') || 'nothing'}). Open a new terminal to use it.`);
611
+ } catch (err) {
612
+ out(`! Couldn't set up the \`claude\` shortcut: ${err.message}. Use \`claude-nonstop\` in place of \`claude\`.`);
613
+ }
614
+ }
615
+ }
616
+ const wired = clients.apply(config.load(), v);
617
+ if (wired.ok) out('- Claude Code in the terminal, VS Code, and Cursor sends its requests through the local gateway.');
618
+ else out(`! Couldn't point Claude Code at the gateway (${wired.reason}). Fix ${clients.settingsFile()} and run \`claude-nonstop setup\` again.`);
619
+ if (wired.permissionChanged) out('- Running as root, so bypass-permissions mode was turned off. Claude Code refuses to start in that mode as root.');
620
+ if (codex.installed()) {
621
+ try {
622
+ const c = codex.apply(config.load(), v);
623
+ out(`- Codex (the \`codex\` command and the Codex app) sends its requests through the local gateway too, so it needs no OpenAI sign-in (${c.file}).`);
624
+ } catch (err) {
625
+ out(`! Couldn't point Codex at the gateway: ${err.message}. Run \`claude-nonstop connect codex\` to see the lines to add by hand.`);
626
+ }
627
+ }
628
+ out('');
629
+ out('Next: add your subscription accounts and API keys in the web UI.');
630
+ if (!args.includes('--no-open')) return ui([]);
631
+ out('Open it any time with `claude-nonstop ui`.');
632
+ return 0;
633
+ }
634
+
635
+ function serviceCommand([sub] = []) {
636
+ if (sub === 'install') {
637
+ out(`The gateway now starts whenever you log in: ${service.install()}`);
638
+ return 0;
639
+ }
640
+ if (sub === 'uninstall') {
641
+ service.uninstall();
642
+ out('The gateway no longer starts at login, and has been stopped.');
643
+ return 0;
644
+ }
645
+ out(service.status().installed ? 'The gateway starts at login.' : "The gateway doesn't start at login. Turn it on with `claude-nonstop service install`.");
646
+ return 0;
647
+ }
648
+
649
+ function shellCommand(args = []) {
650
+ const [sub] = args;
651
+ if (sub === 'install') {
652
+ const changed = shell.install({ binDir: optionValue(args, '--bin-dir') });
653
+ out(`Plain \`claude\` now goes through claude-nonstop (updated ${changed.join(', ') || 'nothing'}). Open a new terminal to use it.`);
654
+ return 0;
655
+ }
656
+ if (sub === 'uninstall') {
657
+ shell.uninstall();
658
+ out('Plain `claude` is back to normal in new terminals.');
659
+ return 0;
660
+ }
661
+ out(shell.status().installed ? 'Plain `claude` goes through claude-nonstop.' : 'Plain `claude` runs Claude Code directly. Change that with `claude-nonstop shell install`.');
662
+ return 0;
663
+ }
664
+
665
+ // ---------------------------------------------------------------- update
666
+
667
+ async function updateCommand() {
668
+ const result = await require('./update').checkAndInstall();
669
+ if (!result.updated) {
670
+ out(result.note || `claude-nonstop ${result.version} is the latest version.`);
671
+ return 0;
672
+ }
673
+ out(`Updated claude-nonstop ${result.from} → ${result.version}.`);
674
+ if (service.status().installed) {
675
+ try {
676
+ service.install();
677
+ out('The gateway restarted on the new version.');
678
+ } catch (err) {
679
+ say(`the gateway didn't restart (${err.message}); it picks up the new version at your next login.`);
680
+ }
681
+ }
682
+ return 0;
683
+ }
684
+
685
+ // ---------------------------------------------------------------- uninstall / reset
686
+
687
+ function removeData() {
688
+ keystore.removeMasterKey();
689
+ for (const file of [paths.VAULT, paths.CONFIG, paths.STATE, paths.SERVER, paths.DESKTOP_CONFIG, paths.LOG, `${paths.LOG}.1`, paths.GATEWAY_LOG]) {
690
+ fs.rmSync(file, { force: true });
691
+ }
692
+ fs.rmSync(paths.PROFILES, { recursive: true, force: true });
693
+ }
694
+
695
+ async function uninstall(args = []) {
696
+ const purge = args.includes('--purge');
697
+ service.uninstall();
698
+ out('- The gateway is stopped and no longer starts at login.');
699
+ shell.uninstall();
700
+ out('- Plain `claude` runs Claude Code directly again (in new terminals).');
701
+ if (clients.remove().ok) out('- Claude Code in the terminal, VS Code, and Cursor no longer uses the local gateway.');
702
+ if (codex.remove().changed) out('- Codex no longer uses the local gateway; its earlier model settings are back.');
703
+ if (system.remove().hosts) out(`- The short address ${hostsfile.PRIMARY} and the desktop app's settings are removed from this computer.`);
704
+ else out(`! Couldn't remove the ${hostsfile.PRIMARY} lines from ${hostsfile.hostsPath()} (it needs administrator rights). They're harmless; delete them by hand if you like.`);
705
+ tls.uninstall();
706
+ out('- The local certificate is deleted and no longer trusted.');
707
+ if (process.platform === 'darwin' && fs.existsSync(desktop.PROFILE)) {
708
+ out('- To undo the desktop app setup, remove "claude-nonstop for the Claude desktop app" in System Settings → General → Device Management.');
709
+ fs.rmSync(desktop.PROFILE, { force: true });
710
+ }
711
+ if (purge) {
712
+ const bin = claude.findClaude();
713
+ for (const account of config.load().accounts.filter((a) => a.kind === 'profile')) {
714
+ try {
715
+ await accounts.remove(account, bin);
716
+ } catch {}
717
+ }
718
+ removeData();
719
+ out('- Your saved keys, accounts and settings are deleted.');
720
+ }
721
+ // Installed by install.sh / install.ps1: remove the app and its launcher too.
722
+ const appDir = path.join(paths.HOME, 'app');
723
+ if (paths.APP_SCRIPT.startsWith(appDir + path.sep)) {
724
+ if (process.platform === 'win32') {
725
+ const binDir = path.join(paths.HOME, 'bin');
726
+ try {
727
+ require('./winpath').removeFromUserPath(binDir);
728
+ } catch {}
729
+ // claude-nonstop.cmd is still running this command, and cmd.exe complains if the file
730
+ // disappears under it, so the folders are removed a moment after this process exits.
731
+ const line = `ping -n 3 127.0.0.1 >nul & rmdir /s /q "${appDir}" & rmdir /s /q "${binDir}"${purge ? ` & rmdir "${paths.HOME}"` : ''}`;
732
+ spawn(process.env.comspec || 'cmd.exe', ['/d', '/s', '/c', `"${line}"`], {
733
+ detached: true,
734
+ stdio: 'ignore',
735
+ windowsHide: true,
736
+ windowsVerbatimArguments: true,
737
+ }).unref();
738
+ } else {
739
+ fs.rmSync(path.join(os.homedir(), '.local', 'bin', 'claude-nonstop'), { force: true });
740
+ fs.rmSync(appDir, { recursive: true, force: true });
741
+ }
742
+ out('- The claude-nonstop app is removed.');
743
+ } else {
744
+ out('- Installed with npm? Finish with: npm uninstall -g @umer-jahangier/claude-nonstop');
745
+ }
746
+ if (purge) {
747
+ try {
748
+ fs.rmdirSync(paths.HOME); // only succeeds once nothing is left in it
749
+ } catch {}
750
+ } else {
751
+ out(`Your saved keys are still in ${paths.HOME} (encrypted). \`claude-nonstop uninstall --purge\` deletes them.`);
752
+ }
753
+ return 0;
754
+ }
755
+
756
+ async function reset(args = []) {
757
+ if (!args.includes('--yes') && !(await prompt.confirm('Delete every saved API key and start a fresh vault? (accounts stay signed in)', false))) return 0;
758
+ keystore.removeMasterKey();
759
+ for (const file of [paths.VAULT, paths.STATE, paths.DESKTOP_CONFIG]) fs.rmSync(file, { force: true });
760
+ vault.loadWithTokens();
761
+ out('Started a fresh vault. Add your API keys again with `claude-nonstop ui`. The desktop app needs the new file from `claude-nonstop desktop`.');
762
+ return 0;
763
+ }
764
+
765
+ // ---------------------------------------------------------------- ssh
766
+
767
+ // Servers the desktop app's SSH sessions can use (ssh.js explains the tunnel).
768
+ function sshCommand([sub, host] = []) {
769
+ ensureHome();
770
+ const ssh = require('./ssh');
771
+ if (!sub || sub === 'list') {
772
+ const cfg = config.load();
773
+ if (!cfg.sshHosts.length) {
774
+ out('No servers set up for SSH sessions. Add one with `claude-nonstop ssh add <host>`.');
775
+ return 0;
776
+ }
777
+ const live = readJson(paths.SSH_STATUS, { tunnels: [] }).tunnels;
778
+ out(`The desktop app reaches the gateway at ${ssh.gatewayUrl(cfg)}, on this computer and through a tunnel on:`);
779
+ for (const h of cfg.sshHosts) {
780
+ const t = live.find((x) => x.host === h);
781
+ out(` ${h} ${t ? (t.state === 'up' ? 'tunnel up' : t.state === 'down' ? `tunnel down: ${t.why}` : 'connecting') : 'tunnel not open (is the gateway running?)'}`);
782
+ }
783
+ return 0;
784
+ }
785
+ if ((sub !== 'add' && sub !== 'remove') || !host) {
786
+ out('Usage: claude-nonstop ssh [add|remove] <host>');
787
+ return 1;
788
+ }
789
+ if (!ssh.validHost(host)) {
790
+ out(`! ${host} isn't a host name ssh can use.`);
791
+ return 1;
792
+ }
793
+ if (sub === 'add') {
794
+ if (!ssh.available()) {
795
+ out('! The gateway needs its HTTPS certificate and the claude.nonstop name first: run `claude-nonstop setup`.');
796
+ return 1;
797
+ }
798
+ out(`Setting up ${host}: the claude.nonstop name and the gateway's certificate authority…`);
799
+ const r = ssh.prepare(host);
800
+ if (!r.ok) {
801
+ out(`! ${host} wasn't set up: ${r.why}.`);
802
+ return 1;
803
+ }
804
+ config.update((cfg) => {
805
+ if (!cfg.sshHosts.includes(host)) cfg.sshHosts.push(host);
806
+ });
807
+ out(`- ${host} is set up. The gateway keeps a tunnel open to it while it runs.`);
808
+ } else {
809
+ const r = ssh.unprepare(host);
810
+ if (!r.ok) out(`! ${host} couldn't be cleaned up (${r.why}); it's removed here anyway.`);
811
+ config.update((cfg) => {
812
+ cfg.sshHosts = cfg.sshHosts.filter((h) => h !== host);
813
+ });
814
+ out(`- ${host} is removed.`);
815
+ }
816
+ // The gateway URL the desktop app needs changes with the first host added or the last removed.
817
+ desktop.write(config.load(), vault.loadWithTokens());
818
+ setUpDesktop(false);
819
+ return 0;
820
+ }
821
+
822
+ module.exports = {
823
+ connect: connectCommand,
824
+ serve,
825
+ ui,
826
+ status,
827
+ keys: keysCommand,
828
+ accounts: accountsCommand,
829
+ move: moveCommand,
830
+ pause: (args) => pauseCommand(true, args),
831
+ resume: (args) => pauseCommand(false, args),
832
+ desktop: desktopCommand,
833
+ connectors: connectorsCommand,
834
+ ssh: sshCommand,
835
+ setup,
836
+ service: serviceCommand,
837
+ shell: shellCommand,
838
+ update: updateCommand,
839
+ uninstall,
840
+ reset,
841
+ };