@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/claude.js ADDED
@@ -0,0 +1,252 @@
1
+ 'use strict';
2
+
3
+ // Finding and starting the real, unmodified Claude Code binary on every platform.
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
+
11
+ const isWin = process.platform === 'win32';
12
+
13
+ function isExecutable(p) {
14
+ try {
15
+ if (!fs.statSync(p).isFile()) return false;
16
+ if (!isWin) fs.accessSync(p, fs.constants.X_OK);
17
+ return true;
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+
23
+ const samePath = (a, b) => (isWin ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));
24
+
25
+ function findClaude() {
26
+ // A location given in advance only counts while Claude Code is still there: it moves when
27
+ // you switch between the npm and native installs.
28
+ const given = process.env.CLAUDE_NONSTOP_CLAUDE;
29
+ if (given && isExecutable(given)) return given;
30
+ const exts = isWin ? ['.exe', '.cmd', '.bat'] : [''];
31
+ const ownShims = path.join(paths.HOME, 'shims');
32
+ const dirs = (process.env.PATH || process.env.Path || '').split(path.delimiter);
33
+ // Installs that a shell alias points at, which aren't on PATH.
34
+ dirs.push(path.join(os.homedir(), '.claude', 'local'), path.join(os.homedir(), '.local', 'bin'));
35
+ for (const rawDir of dirs) {
36
+ const dir = rawDir.replace(/^"(.*)"$/, '$1');
37
+ // claude-nonstop's own `claude` shim must never be mistaken for Claude Code.
38
+ if (!dir || samePath(dir, ownShims)) continue;
39
+ for (const ext of exts) {
40
+ const candidate = path.join(dir, `claude${ext}`);
41
+ if (!isExecutable(candidate)) continue;
42
+ if (ext === '.cmd') {
43
+ // npm's claude.cmd only forwards to the bundled claude.exe, so run that directly.
44
+ const exe = path.join(dir, 'node_modules', '@anthropic-ai', 'claude-code', 'bin', 'claude.exe');
45
+ if (isExecutable(exe)) return exe;
46
+ }
47
+ return candidate;
48
+ }
49
+ }
50
+ return null;
51
+ }
52
+
53
+ // Windows can't start a .cmd file without cmd.exe, which re-parses the command line.
54
+ // This quotes and escapes each argument the same way cross-spawn does.
55
+ const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
56
+
57
+ function escapeForCmd(arg) {
58
+ let s = String(arg)
59
+ .replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
60
+ .replace(/(?=(\\+?)?)\1$/, '$1$1');
61
+ s = `"${s}"`;
62
+ // Escaped twice: once for cmd.exe, once for the batch file that forwards %*.
63
+ return s.replace(CMD_META, '^$1').replace(CMD_META, '^$1');
64
+ }
65
+
66
+ function command(bin, args) {
67
+ if (isWin && /\.(cmd|bat)$/i.test(bin)) {
68
+ const line = [bin.replace(CMD_META, '^$1'), ...args.map(escapeForCmd)].join(' ');
69
+ return { file: process.env.comspec || 'cmd.exe', args: ['/d', '/s', '/c', `"${line}"`], options: { windowsVerbatimArguments: true } };
70
+ }
71
+ return { file: bin, args, options: {} };
72
+ }
73
+
74
+ function exitCodeOf(code, signal) {
75
+ if (typeof code === 'number') return code;
76
+ return signal ? 128 + (os.constants.signals[signal] || 1) : 1;
77
+ }
78
+
79
+ // Runs Claude Code in this terminal and resolves with its exit code. Ctrl-C belongs to
80
+ // Claude Code, so this process ignores it while Claude Code runs.
81
+ function runInteractive(bin, args, env) {
82
+ return new Promise((resolve) => {
83
+ const c = command(bin, args);
84
+ let child;
85
+ try {
86
+ child = spawn(c.file, c.args, { ...c.options, env, stdio: 'inherit' });
87
+ } catch (err) {
88
+ process.stderr.write(`claude-nonstop: could not start Claude Code: ${err.message}\n`);
89
+ resolve(1);
90
+ return;
91
+ }
92
+ const ignore = () => {};
93
+ const forwardTerm = () => child.kill('SIGTERM');
94
+ const forwardHup = () => child.kill('SIGHUP');
95
+ process.on('SIGINT', ignore);
96
+ process.on('SIGTERM', forwardTerm);
97
+ process.on('SIGHUP', forwardHup);
98
+ const done = (code) => {
99
+ process.removeListener('SIGINT', ignore);
100
+ process.removeListener('SIGTERM', forwardTerm);
101
+ process.removeListener('SIGHUP', forwardHup);
102
+ resolve(code);
103
+ };
104
+ child.on('error', (err) => {
105
+ process.stderr.write(`claude-nonstop: could not start Claude Code: ${err.message}\n`);
106
+ done(1);
107
+ });
108
+ child.on('exit', (code, signal) => done(exitCodeOf(code, signal)));
109
+ });
110
+ }
111
+
112
+ // Like runInteractive, but hands back the child too, so a supervisor can stop it.
113
+ function spawnInteractive(bin, args, env) {
114
+ const c = command(bin, args);
115
+ const child = spawn(c.file, c.args, { ...c.options, env, stdio: 'inherit' });
116
+ const ignore = () => {};
117
+ const forwardTerm = () => child.kill('SIGTERM');
118
+ const forwardHup = () => child.kill('SIGHUP');
119
+ process.on('SIGINT', ignore);
120
+ process.on('SIGTERM', forwardTerm);
121
+ process.on('SIGHUP', forwardHup);
122
+ const exited = new Promise((resolve) => {
123
+ const done = (code) => {
124
+ process.removeListener('SIGINT', ignore);
125
+ process.removeListener('SIGTERM', forwardTerm);
126
+ process.removeListener('SIGHUP', forwardHup);
127
+ resolve(code);
128
+ };
129
+ child.on('error', (err) => {
130
+ process.stderr.write(`claude-nonstop: could not start Claude Code: ${err.message}\n`);
131
+ done(1);
132
+ });
133
+ child.on('exit', (code, signal) => done(exitCodeOf(code, signal)));
134
+ });
135
+ return { child, exited };
136
+ }
137
+
138
+ // Ends a Claude Code session started with spawnInteractive, then puts the terminal back
139
+ // the way a normal exit would leave it (in case Claude Code had no chance to).
140
+ async function stopInteractive({ child, exited }) {
141
+ if (isWin) {
142
+ // Takes Claude Code down with anything it started, e.g. when cmd.exe launched it.
143
+ require('child_process').spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
144
+ } else {
145
+ child.kill('SIGTERM');
146
+ const timer = setTimeout(() => child.kill('SIGKILL'), 3000);
147
+ await exited;
148
+ clearTimeout(timer);
149
+ }
150
+ await exited;
151
+ if (process.stdout.isTTY) {
152
+ // Leave the alternate screen, and turn off mouse, focus, paste and keyboard modes.
153
+ process.stdout.write('\x1b[?1049l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1004l\x1b[?2004l\x1b[<u\x1b[0m\x1b[?25h\r\n');
154
+ }
155
+ if (process.stdin.isTTY) {
156
+ if (isWin) {
157
+ try { process.stdin.setRawMode(false); } catch {}
158
+ } else {
159
+ require('child_process').spawnSync('stty', ['sane'], { stdio: 'inherit' });
160
+ }
161
+ }
162
+ }
163
+
164
+ // Starts Claude Code with piped output; returns the child process.
165
+ function start(bin, args, { env, cwd } = {}) {
166
+ const c = command(bin, args);
167
+ return spawn(c.file, c.args, { ...c.options, env, cwd, windowsHide: true });
168
+ }
169
+
170
+ // Runs Claude Code to completion and collects its output. Never rejects.
171
+ // `notStarted` tells "Claude Code isn't there" apart from Claude Code reporting a problem.
172
+ function capture(bin, args, { env, cwd, timeoutMs = 60000, input = '' } = {}) {
173
+ const why = (err) => (err.code === 'ENOENT' ? `Claude Code wasn't found at ${bin}` : err.message);
174
+ return new Promise((resolve) => {
175
+ let child;
176
+ try {
177
+ child = start(bin, args, { env, cwd });
178
+ } catch (err) {
179
+ resolve({ code: 1, stdout: '', stderr: why(err), notStarted: true });
180
+ return;
181
+ }
182
+ let stdout = '';
183
+ let stderr = '';
184
+ let settled = false;
185
+ let notStarted = false;
186
+ const finish = (code) => {
187
+ if (settled) return;
188
+ settled = true;
189
+ clearTimeout(timer);
190
+ resolve(notStarted ? { code, stdout, stderr, notStarted } : { code, stdout, stderr });
191
+ };
192
+ const timer = setTimeout(() => {
193
+ stderr += `\ntimed out after ${Math.round(timeoutMs / 1000)}s`;
194
+ child.kill();
195
+ }, timeoutMs);
196
+ child.stdout.on('data', (d) => (stdout += d));
197
+ child.stderr.on('data', (d) => (stderr += d));
198
+ child.on('error', (err) => {
199
+ stderr += why(err);
200
+ notStarted = !child.pid;
201
+ finish(1);
202
+ });
203
+ child.on('close', (code, signal) => finish(exitCodeOf(code, signal)));
204
+ child.stdin.on('error', () => {});
205
+ child.stdin.end(input);
206
+ });
207
+ }
208
+
209
+ // Claude Code 2.1.234 added automatic continue after a usage limit, which a single
210
+ // account relies on to pick work up again at the reset.
211
+ const MIN_VERSION = [2, 1, 234];
212
+
213
+ async function version(bin) {
214
+ const r = await capture(bin, ['--version'], { timeoutMs: 20000 });
215
+ const m = /(\d+)\.(\d+)\.(\d+)/.exec(r.stdout || '');
216
+ return m ? m.slice(1).map(Number) : null;
217
+ }
218
+
219
+ function atLeast(v, min = MIN_VERSION) {
220
+ for (let i = 0; i < 3; i++) if (v[i] !== min[i]) return v[i] > min[i];
221
+ return true;
222
+ }
223
+
224
+ // Claude Code refuses bypass-permissions mode when it is running as root. A launch that
225
+ // would ask for that mode is started in the normal mode instead, so the CLI still runs
226
+ // on a server. An explicit mode other than bypass-permissions is left as it was.
227
+ function isRoot() {
228
+ return process.platform !== 'win32' && typeof process.getuid === 'function' && process.getuid() === 0;
229
+ }
230
+
231
+ function withoutRootBypass(args) {
232
+ if (!isRoot()) return args.slice();
233
+ const out = [];
234
+ let mode = null;
235
+ for (let i = 0; i < args.length; i++) {
236
+ const arg = args[i];
237
+ if (arg === '--dangerously-skip-permissions') continue;
238
+ if (arg === '--permission-mode') {
239
+ mode = args[++i];
240
+ continue;
241
+ }
242
+ if (String(arg).startsWith('--permission-mode=')) {
243
+ mode = arg.slice('--permission-mode='.length);
244
+ continue;
245
+ }
246
+ out.push(arg);
247
+ }
248
+ if (!mode || mode === 'bypassPermissions') mode = 'default';
249
+ return ['--permission-mode', mode, ...out];
250
+ }
251
+
252
+ module.exports = { findClaude, command, runInteractive, spawnInteractive, stopInteractive, start, capture, version, atLeast, withoutRootBypass, isRoot, MIN_VERSION };
package/src/cli.js ADDED
@@ -0,0 +1,98 @@
1
+ 'use strict';
2
+
3
+ const pkg = require('../package.json');
4
+
5
+ const HELP = `claude-nonstop ${pkg.version}
6
+ Keeps Claude Code (and Codex, Cursor, any OpenAI-compatible tool) working through plan
7
+ limits: each request goes out on the first of your Claude and ChatGPT accounts and API
8
+ keys with usage left, in the order you choose.
9
+
10
+ Run Claude Code (after \`claude-nonstop setup\`, plain \`claude\` does this too):
11
+ claude-nonstop [claude args] first account or key with usage left
12
+ claude-nonstop --api [claude args] skip subscriptions, use API keys
13
+ claude-nonstop --sub [claude args] subscription accounts only
14
+
15
+ Accounts and keys:
16
+ claude-nonstop ui open the web UI: add, sign in, test, reorder
17
+ claude-nonstop status what's set up, what's in use, and your order
18
+ claude-nonstop move <n> up|down move account or key n in the order
19
+ claude-nonstop pause <n> keep account or key n but stop using it
20
+ claude-nonstop resume <n> use it again
21
+ claude-nonstop keys check every API key
22
+ claude-nonstop keys add [label] save a Claude or OpenAI key (typed hidden, or piped on stdin)
23
+ claude-nonstop keys remove <n> forget key number n
24
+ claude-nonstop accounts list subscription accounts
25
+ claude-nonstop accounts add [label] add a Claude account and sign in to it
26
+ claude-nonstop accounts add [label] --chatgpt add a ChatGPT account (--import-codex takes Codex's sign-in)
27
+ claude-nonstop accounts login <n> sign in again
28
+ claude-nonstop accounts check check which accounts have usage left
29
+ claude-nonstop accounts remove <n> sign out and remove account n
30
+ claude-nonstop connect [codex|cursor] how to point Codex, Cursor or any OpenAI-compatible tool at the gateway
31
+ claude-nonstop desktop set the Claude desktop app up to use your keys
32
+ claude-nonstop connectors list the desktop app's connectors
33
+ claude-nonstop connectors add <name> <https-url> [--no-oauth]
34
+ claude-nonstop connectors remove <name>
35
+ claude-nonstop ssh servers the desktop app's SSH sessions can use, and their tunnels
36
+ claude-nonstop ssh add <host> let SSH sessions on <host> reach the gateway (an ~/.ssh/config name works)
37
+ claude-nonstop ssh remove <host> undo that on <host>
38
+
39
+ Setup:
40
+ claude-nonstop setup everything at once, including the terminal, VS Code, and Cursor
41
+ claude-nonstop service install | uninstall | status
42
+ claude-nonstop shell install | uninstall
43
+ claude-nonstop update install the newest version now (it also updates itself within the hour)
44
+ claude-nonstop uninstall [--purge]
45
+ `;
46
+
47
+ async function main(argv) {
48
+ const [cmd, ...rest] = argv;
49
+ const launch = () => require('./launch');
50
+ const commands = () => require('./commands');
51
+ switch (cmd) {
52
+ case 'run':
53
+ return launch().launch(rest[0] === '--' ? rest.slice(1) : rest);
54
+ case '--':
55
+ return launch().launch(rest);
56
+ case '--api':
57
+ return launch().launch(rest, { mode: 'api' });
58
+ case '--sub':
59
+ return launch().launch(rest, { mode: 'sub' });
60
+ case 'key-helper':
61
+ return launch().keyHelper();
62
+ case 'hook':
63
+ return require('./supervise').hook();
64
+ case 'help':
65
+ case '--help':
66
+ case '-h':
67
+ process.stdout.write(HELP);
68
+ return 0;
69
+ case 'version':
70
+ case '--version':
71
+ case '-v':
72
+ process.stdout.write(`${pkg.version}\n`);
73
+ return 0;
74
+ case 'serve':
75
+ case 'ui':
76
+ case 'status':
77
+ case 'keys':
78
+ case 'accounts':
79
+ case 'move':
80
+ case 'pause':
81
+ case 'resume':
82
+ case 'desktop':
83
+ case 'connect':
84
+ case 'connectors':
85
+ case 'ssh':
86
+ case 'setup':
87
+ case 'service':
88
+ case 'shell':
89
+ case 'update':
90
+ case 'uninstall':
91
+ case 'reset':
92
+ return commands()[cmd](rest);
93
+ default:
94
+ return launch().launch(argv);
95
+ }
96
+ }
97
+
98
+ module.exports = { main, HELP };
package/src/clients.js ADDED
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+
3
+ // Every Claude Code that reads user settings — the terminal, VS Code, Cursor, and any
4
+ // other install — is pointed at this computer's gateway. The gateway then walks your
5
+ // subscription accounts and API keys, the same way it does for the desktop app. The
6
+ // desktop app itself is set up separately (desktop.js).
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const paths = require('./paths');
11
+ const config = require('./config');
12
+ const vault = require('./vault');
13
+ const claude = require('./claude');
14
+ const { readJson, writeJson } = require('./files');
15
+
16
+ const BASE_URL = 'ANTHROPIC_BASE_URL';
17
+ const AUTH_TOKEN = 'ANTHROPIC_AUTH_TOKEN';
18
+ const STATE = path.join(paths.HOME, 'clients.json');
19
+
20
+ function settingsFile() {
21
+ return require('./marketplace').settingsFile();
22
+ }
23
+
24
+ function readSettings() {
25
+ const file = settingsFile();
26
+ if (!fs.existsSync(file)) return { file, current: {} };
27
+ let current;
28
+ try {
29
+ current = JSON.parse(fs.readFileSync(file, 'utf8'));
30
+ } catch {
31
+ return { file, unreadable: true };
32
+ }
33
+ if (!current || typeof current !== 'object' || Array.isArray(current)) return { file, unreadable: true };
34
+ return { file, current };
35
+ }
36
+
37
+ function realTarget(file) {
38
+ try {
39
+ return fs.realpathSync(file);
40
+ } catch {
41
+ return file;
42
+ }
43
+ }
44
+
45
+ function gatewayAddress(cfg) {
46
+ return `http://127.0.0.1:${cfg.port}`;
47
+ }
48
+
49
+ // Writes the gateway address into Claude Code's user settings. Returns what changed.
50
+ // A settings file that isn't valid JSON is left alone.
51
+ function apply(cfg = config.load(), v = vault.loadWithTokens()) {
52
+ const loaded = readSettings();
53
+ if (loaded.unreadable) return { ok: false, reason: 'unreadable', changed: false, permissionChanged: false };
54
+ const current = loaded.current;
55
+ const saved = readJson(STATE, {});
56
+ const env = current.env && typeof current.env === 'object' && !Array.isArray(current.env) ? { ...current.env } : {};
57
+ if (!saved.managed) {
58
+ saved.managed = true;
59
+ saved.env = {
60
+ [BASE_URL]: Object.prototype.hasOwnProperty.call(env, BASE_URL) ? env[BASE_URL] : null,
61
+ [AUTH_TOKEN]: Object.prototype.hasOwnProperty.call(env, AUTH_TOKEN) ? env[AUTH_TOKEN] : null,
62
+ };
63
+ saved.permissionMode = null;
64
+ }
65
+ const address = gatewayAddress(cfg);
66
+ let permissionChanged = false;
67
+ if (claude.isRoot() && current.permissions && current.permissions.defaultMode === 'bypassPermissions') {
68
+ if (!saved.permissionMode) saved.permissionMode = 'bypassPermissions';
69
+ current.permissions = { ...current.permissions, defaultMode: 'default' };
70
+ permissionChanged = true;
71
+ }
72
+ const unchanged = env[BASE_URL] === address && env[AUTH_TOKEN] === v.gatewayToken && !permissionChanged && saved.managed;
73
+ if (unchanged && readJson(STATE, {}).managed) return { ok: true, changed: false, permissionChanged: false, root: claude.isRoot() };
74
+ env[BASE_URL] = address;
75
+ env[AUTH_TOKEN] = v.gatewayToken;
76
+ current.env = env;
77
+ writeJson(STATE, saved);
78
+ writeJson(realTarget(loaded.file), current);
79
+ return { ok: true, changed: true, permissionChanged, root: claude.isRoot() };
80
+ }
81
+
82
+ // Puts back whatever those settings were before setup, then forgets that it managed them.
83
+ function remove() {
84
+ const loaded = readSettings();
85
+ const saved = readJson(STATE, null);
86
+ if (loaded.unreadable) return { ok: false, reason: 'unreadable' };
87
+ if (!saved || !saved.managed) return { ok: true };
88
+ const env = loaded.current.env && typeof loaded.current.env === 'object' && !Array.isArray(loaded.current.env) ? { ...loaded.current.env } : {};
89
+ for (const key of [BASE_URL, AUTH_TOKEN]) {
90
+ const previous = saved.env ? saved.env[key] : null;
91
+ if (previous === undefined || previous === null) delete env[key];
92
+ else env[key] = previous;
93
+ }
94
+ if (Object.keys(env).length) loaded.current.env = env;
95
+ else delete loaded.current.env;
96
+ if (saved.permissionMode && loaded.current.permissions && loaded.current.permissions.defaultMode === 'default') {
97
+ loaded.current.permissions = { ...loaded.current.permissions, defaultMode: saved.permissionMode };
98
+ }
99
+ writeJson(realTarget(loaded.file), loaded.current);
100
+ fs.rmSync(STATE, { force: true });
101
+ return { ok: true };
102
+ }
103
+
104
+ module.exports = { apply, remove, settingsFile, BASE_URL, AUTH_TOKEN };
package/src/codex.js ADDED
@@ -0,0 +1,145 @@
1
+ 'use strict';
2
+
3
+ // Codex (OpenAI's coding agent, the terminal `codex` and the Codex desktop app) is pointed
4
+ // at this computer's gateway through its own configuration file, ~/.codex/config.toml: a
5
+ // model provider named claude-nonstop that speaks the Responses API at the gateway's
6
+ // address with the gateway token, and `model_provider` set to it. Codex then needs no
7
+ // OpenAI sign-in of its own: every request walks your order like Claude Code's do.
8
+ //
9
+ // Only the lines claude-nonstop owns are touched: the top-level `model` and `model_provider`
10
+ // (their earlier values are kept in codex.json and put back on uninstall) and the
11
+ // [model_providers.claude-nonstop] table. Everything else in the file stays as it is.
12
+
13
+ const fs = require('fs');
14
+ const os = require('os');
15
+ const path = require('path');
16
+ const paths = require('./paths');
17
+ const config = require('./config');
18
+ const vault = require('./vault');
19
+ const { readJson, writeJson } = require('./files');
20
+
21
+ const PROVIDER = 'claude-nonstop';
22
+ const STATE = path.join(paths.HOME, 'codex.json');
23
+
24
+ const codexHome = () => process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
25
+ const configFile = () => path.join(codexHome(), 'config.toml');
26
+
27
+ // Whether Codex is on this computer at all: the command, the app, or its own folder.
28
+ function installed() {
29
+ if (fs.existsSync(codexHome())) return true;
30
+ if (process.platform === 'darwin' && (fs.existsSync('/Applications/Codex.app') || fs.existsSync(path.join(os.homedir(), 'Applications', 'Codex.app')))) return true;
31
+ const exts = process.platform === 'win32' ? ['.cmd', '.exe', ''] : [''];
32
+ return (process.env.PATH || '').split(path.delimiter).some((dir) => exts.some((ext) => dir && fs.existsSync(path.join(dir, `codex${ext}`))));
33
+ }
34
+
35
+ const TOP_LEVEL_KEY = /^\s*(model|model_provider)\s*=\s*(.*?)\s*$/;
36
+ const TABLE_HEADER = /^\s*\[/;
37
+ const OUR_TABLE = new RegExp(`^\\s*\\[model_providers\\.(?:"${PROVIDER}"|${PROVIDER})\\]\\s*$`);
38
+
39
+ // The file in three parts: the top-level lines (before the first table), the tables, and
40
+ // our own table taken out of them.
41
+ function split(text) {
42
+ const lines = text.split(/\r?\n/);
43
+ const first = lines.findIndex((l) => TABLE_HEADER.test(l));
44
+ const head = first < 0 ? lines : lines.slice(0, first);
45
+ const rest = first < 0 ? [] : lines.slice(first);
46
+ const tables = [];
47
+ let skipping = false;
48
+ for (const line of rest) {
49
+ if (TABLE_HEADER.test(line)) skipping = OUR_TABLE.test(line);
50
+ if (!skipping) tables.push(line);
51
+ }
52
+ return { head, tables };
53
+ }
54
+
55
+ const unquote = (v) => {
56
+ const s = String(v || '').trim();
57
+ const m = /^"(.*)"$/.exec(s) || /^'(.*)'$/.exec(s);
58
+ return m ? m[1] : s;
59
+ };
60
+
61
+ function ourTable(cfg, v) {
62
+ return [
63
+ `[model_providers.${PROVIDER}]`,
64
+ `name = "${PROVIDER}"`,
65
+ `base_url = "http://127.0.0.1:${cfg.port}/v1"`,
66
+ 'wire_api = "responses"',
67
+ `experimental_bearer_token = "${v.gatewayToken}"`,
68
+ 'requires_openai_auth = false',
69
+ ];
70
+ }
71
+
72
+ // Writes the provider into Codex's configuration. Returns what changed.
73
+ function apply(cfg = config.load(), v = vault.loadWithTokens()) {
74
+ const file = configFile();
75
+ const before = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
76
+ const { head, tables } = split(before);
77
+ const saved = readJson(STATE, {});
78
+ const previous = {};
79
+ const kept = [];
80
+ for (const line of head) {
81
+ const m = TOP_LEVEL_KEY.exec(line);
82
+ if (m) previous[m[1]] = unquote(m[2]);
83
+ else kept.push(line);
84
+ }
85
+ // What Codex had before, remembered the first time it's pointed here (a file already
86
+ // pointing here keeps the earlier memory; one that isn't is a fresh start).
87
+ if (!saved.managed || previous.model_provider !== PROVIDER) {
88
+ saved.managed = true;
89
+ saved.previous = { model: previous.model ?? null, model_provider: previous.model_provider ?? null };
90
+ }
91
+ const model = (cfg.models && cfg.models.openai) || 'gpt-5.5';
92
+ const top = [`model = "${model}"`, `model_provider = "${PROVIDER}"`];
93
+ const trimmedKept = kept.join('\n').replace(/^\s*\n/, '').replace(/\s*$/, '');
94
+ const trimmedTables = tables.join('\n').replace(/^\s*\n/, '').replace(/\s*$/, '');
95
+ const after = [top.join('\n'), trimmedKept, trimmedTables, ourTable(cfg, v).join('\n')].filter(Boolean).join('\n\n') + '\n';
96
+ if (after === before && readJson(STATE, {}).managed) return { ok: true, changed: false, file };
97
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
98
+ writeJson(STATE, saved);
99
+ fs.writeFileSync(file, after, { mode: 0o600 });
100
+ return { ok: true, changed: true, file };
101
+ }
102
+
103
+ // Takes the provider out again and puts back the model lines Codex had before.
104
+ function remove() {
105
+ const file = configFile();
106
+ const saved = readJson(STATE, null);
107
+ if (!fs.existsSync(file)) {
108
+ fs.rmSync(STATE, { force: true });
109
+ return { ok: true, changed: false, file };
110
+ }
111
+ const before = fs.readFileSync(file, 'utf8');
112
+ const { head, tables } = split(before);
113
+ const kept = head.filter((line) => {
114
+ const m = TOP_LEVEL_KEY.exec(line);
115
+ return !(m && (m[1] === 'model_provider' ? unquote(m[2]) === PROVIDER : saved && saved.managed));
116
+ });
117
+ const top = [];
118
+ if (saved && saved.managed && saved.previous) {
119
+ if (saved.previous.model) top.push(`model = "${saved.previous.model}"`);
120
+ if (saved.previous.model_provider) top.push(`model_provider = "${saved.previous.model_provider}"`);
121
+ }
122
+ const trimmedKept = kept.join('\n').replace(/^\s*\n/, '').replace(/\s*$/, '');
123
+ const trimmedTables = tables.join('\n').replace(/^\s*\n/, '').replace(/\s*$/, '');
124
+ const body = [top.join('\n'), trimmedKept, trimmedTables].filter(Boolean).join('\n\n');
125
+ const after = body ? `${body}\n` : '';
126
+ if (after !== before) {
127
+ if (after) fs.writeFileSync(file, after, { mode: 0o600 });
128
+ else fs.rmSync(file, { force: true });
129
+ }
130
+ fs.rmSync(STATE, { force: true });
131
+ return { ok: true, changed: after !== before, file };
132
+ }
133
+
134
+ // Whether Codex's configuration currently points at this gateway.
135
+ function status(cfg = config.load()) {
136
+ const file = configFile();
137
+ if (!fs.existsSync(file)) return { wired: false, file };
138
+ const text = fs.readFileSync(file, 'utf8');
139
+ const { head } = split(text);
140
+ const provider = head.map((l) => TOP_LEVEL_KEY.exec(l)).find((m) => m && m[1] === 'model_provider');
141
+ const wired = Boolean(provider && unquote(provider[2]) === PROVIDER && text.includes(`base_url = "http://127.0.0.1:${cfg.port}/v1"`));
142
+ return { wired, file };
143
+ }
144
+
145
+ module.exports = { PROVIDER, codexHome, configFile, installed, apply, remove, status, split };