@umer-jahangier/claude-nonstop 0.0.0-stage → 1.16.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +417 -2
- package/bin/claude-nonstop.js +14 -0
- package/package.json +51 -4
- package/src/accounts.js +288 -0
- package/src/chatgpt-models.js +64 -0
- package/src/checks.js +66 -0
- package/src/classify.js +21 -0
- package/src/claude.js +252 -0
- package/src/cli.js +98 -0
- package/src/clients.js +104 -0
- package/src/codex.js +145 -0
- package/src/commands.js +841 -0
- package/src/config.js +60 -0
- package/src/connectorcheck.js +88 -0
- package/src/desktop.js +267 -0
- package/src/desktopadvice.js +111 -0
- package/src/directory.json +7197 -0
- package/src/elevate.js +39 -0
- package/src/events.js +43 -0
- package/src/files.js +54 -0
- package/src/gateway.js +976 -0
- package/src/hosts.js +46 -0
- package/src/hostsfile.js +68 -0
- package/src/http.js +65 -0
- package/src/keys.js +81 -0
- package/src/keystore.js +141 -0
- package/src/launch.js +233 -0
- package/src/marketplace.js +52 -0
- package/src/openai-auth.js +249 -0
- package/src/paths.js +25 -0
- package/src/prompt.js +66 -0
- package/src/providers.js +168 -0
- package/src/relay.js +78 -0
- package/src/server.js +285 -0
- package/src/service.js +208 -0
- package/src/shell.js +119 -0
- package/src/ssh.js +163 -0
- package/src/state.js +76 -0
- package/src/supervise.js +377 -0
- package/src/system.js +105 -0
- package/src/tls.js +260 -0
- package/src/translate/chat.js +150 -0
- package/src/translate/index.js +52 -0
- package/src/translate/ir.js +140 -0
- package/src/translate/messages.js +333 -0
- package/src/translate/responses.js +495 -0
- package/src/translate/sse.js +44 -0
- package/src/ui/index.html +3206 -0
- package/src/ui.js +623 -0
- package/src/update.js +122 -0
- package/src/usage.js +147 -0
- package/src/vault.js +68 -0
- package/src/winpath.js +48 -0
package/src/config.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Non-secret settings, editable in the web UI. Accounts here are only a label and a
|
|
4
|
+
// Claude Code config folder; their logins stay in Claude Code's own credential store.
|
|
5
|
+
|
|
6
|
+
const paths = require('./paths');
|
|
7
|
+
const { readJson, writeJson } = require('./files');
|
|
8
|
+
|
|
9
|
+
const DEFAULTS = {
|
|
10
|
+
port: 43117,
|
|
11
|
+
cooldownMinutes: 30, // a used-up key is re-checked after this long, in case you topped it up
|
|
12
|
+
accountRecheckMinutes: 10, // an account that hit its limit is skipped this long before re-checking
|
|
13
|
+
helperTtlMs: 120000, // how often a CLI session without the gateway asks for a key again
|
|
14
|
+
probeModel: 'claude-haiku-5-5', // cheapest model, used for the 1-token key checks
|
|
15
|
+
upstream: 'https://api.anthropic.com',
|
|
16
|
+
autoUpdate: true, // the gateway installs new releases by itself
|
|
17
|
+
desktopStrictSandbox: false, // keep the desktop app's Code sessions to an allowlist of sites
|
|
18
|
+
desktopConnectors: [], // MCP servers the desktop app lists as connectors in third-party mode
|
|
19
|
+
desktopAccount: 'default', // the account the desktop app signs in to with Claude.ai
|
|
20
|
+
desktopAlerts: true, // say when to switch the desktop app between that account and API keys
|
|
21
|
+
// The model a line answers with when the request asked for one from the other service.
|
|
22
|
+
models: { anthropic: 'claude-sonnet-5-5', openai: 'gpt-5.5' },
|
|
23
|
+
modelAliases: {}, // requested model name -> the one to use, applied before the family check
|
|
24
|
+
// The desktop app's SSH sessions reach the gateway through a reverse tunnel: on each host
|
|
25
|
+
// named here, the server's 127.0.0.1:sshTunnelPort leads back to this computer's (ssh.js).
|
|
26
|
+
sshTunnelPort: 43118,
|
|
27
|
+
sshHosts: [],
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const DEFAULT_ACCOUNT = { id: 'default', label: 'Main account', kind: 'default', enabled: true };
|
|
31
|
+
|
|
32
|
+
function load() {
|
|
33
|
+
const saved = readJson(paths.CONFIG, {});
|
|
34
|
+
const cfg = { ...DEFAULTS, ...saved };
|
|
35
|
+
cfg.models = { ...DEFAULTS.models, ...(saved.models || {}) };
|
|
36
|
+
cfg.sshHosts = Array.isArray(saved.sshHosts) ? saved.sshHosts : [];
|
|
37
|
+
cfg.accounts = Array.isArray(saved.accounts) && saved.accounts.length ? saved.accounts : [{ ...DEFAULT_ACCOUNT }];
|
|
38
|
+
if (process.env.CLAUDE_NONSTOP_PORT) cfg.port = Number(process.env.CLAUDE_NONSTOP_PORT);
|
|
39
|
+
if (process.env.CLAUDE_NONSTOP_UPSTREAM) cfg.upstream = process.env.CLAUDE_NONSTOP_UPSTREAM;
|
|
40
|
+
cfg.upstream = cfg.upstream.replace(/\/+$/, '');
|
|
41
|
+
return cfg;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function save(cfg) {
|
|
45
|
+
const saved = readJson(paths.CONFIG, {});
|
|
46
|
+
const out = { ...cfg };
|
|
47
|
+
// Values that came from environment overrides are not written back.
|
|
48
|
+
if (process.env.CLAUDE_NONSTOP_PORT) out.port = saved.port ?? DEFAULTS.port;
|
|
49
|
+
if (process.env.CLAUDE_NONSTOP_UPSTREAM) out.upstream = saved.upstream ?? DEFAULTS.upstream;
|
|
50
|
+
writeJson(paths.CONFIG, out);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function update(change) {
|
|
54
|
+
const cfg = load();
|
|
55
|
+
const result = change(cfg);
|
|
56
|
+
save(cfg);
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { DEFAULTS, load, save, update };
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// How a remote MCP server signs users in, found the way the Claude desktop app finds it:
|
|
4
|
+
// ask the server, follow its protected-resource metadata to its authorization server, and
|
|
5
|
+
// read that server's metadata. Returns { auth, issuer }:
|
|
6
|
+
// 'oauth' the app can register itself (dynamic client registration): just works
|
|
7
|
+
// 'needs-client' sign-in needs an OAuth client registered with the provider (a Client ID)
|
|
8
|
+
// 'none' no sign-in at all
|
|
9
|
+
// 'no-metadata' asks for sign-in but publishes no OAuth metadata the app can use
|
|
10
|
+
// 'redirects' / 'unreachable' the address isn't the server's final https address
|
|
11
|
+
|
|
12
|
+
const TIMEOUT = 12000;
|
|
13
|
+
|
|
14
|
+
async function get(url, init = {}) {
|
|
15
|
+
const ctl = new AbortController();
|
|
16
|
+
const t = setTimeout(() => ctl.abort(), TIMEOUT);
|
|
17
|
+
try {
|
|
18
|
+
return await fetch(url, { redirect: 'manual', ...init, signal: ctl.signal, headers: { 'user-agent': 'claude-nonstop connector check', ...(init.headers || {}) } });
|
|
19
|
+
} finally {
|
|
20
|
+
clearTimeout(t);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function json(url) {
|
|
25
|
+
try {
|
|
26
|
+
const r = await get(url, { headers: { accept: 'application/json' } });
|
|
27
|
+
if (!r.ok) return null;
|
|
28
|
+
return await r.json();
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const wellKnown = (base, name) => {
|
|
35
|
+
const u = new URL(base);
|
|
36
|
+
const p = u.pathname.replace(/\/$/, '');
|
|
37
|
+
return p ? [`${u.origin}/.well-known/${name}${p}`, `${u.origin}/.well-known/${name}`] : [`${u.origin}/.well-known/${name}`];
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
async function authServerMeta(issuer) {
|
|
41
|
+
for (const url of [...wellKnown(issuer, 'oauth-authorization-server'), ...wellKnown(issuer, 'openid-configuration')]) {
|
|
42
|
+
const m = await json(url);
|
|
43
|
+
if (m && (m.authorization_endpoint || m.token_endpoint)) return m;
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const transportFor = (url) => (/\/sse\/?$/.test(new URL(url).pathname) ? 'sse' : 'http');
|
|
49
|
+
|
|
50
|
+
async function check(url, transport = transportFor(url)) {
|
|
51
|
+
let r;
|
|
52
|
+
try {
|
|
53
|
+
r = transport === 'sse'
|
|
54
|
+
? await get(url, { headers: { accept: 'text/event-stream' } })
|
|
55
|
+
: await get(url, {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
|
|
58
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'claude-nonstop', version: '1' } } }),
|
|
59
|
+
});
|
|
60
|
+
} catch {
|
|
61
|
+
return { auth: 'unreachable', issuer: null };
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
if (r.body) r.body.cancel();
|
|
65
|
+
} catch {}
|
|
66
|
+
if (r.status >= 300 && r.status < 400) return { auth: 'redirects', issuer: null };
|
|
67
|
+
if (r.status !== 401 && r.status !== 403) return { auth: r.status < 500 ? 'none' : 'unreachable', issuer: null };
|
|
68
|
+
let resource = null;
|
|
69
|
+
const hint = (r.headers.get('www-authenticate') || '').match(/resource_metadata="([^"]+)"/);
|
|
70
|
+
if (hint) resource = await json(hint[1]);
|
|
71
|
+
if (!resource) for (const u of wellKnown(url, 'oauth-protected-resource')) if ((resource = await json(u))) break;
|
|
72
|
+
const declared = resource && Array.isArray(resource.authorization_servers) && resource.authorization_servers[0];
|
|
73
|
+
const meta = await authServerMeta(declared || new URL(url).origin);
|
|
74
|
+
if (!meta) return { auth: 'no-metadata', issuer: null };
|
|
75
|
+
return { auth: meta.registration_endpoint ? 'oauth' : 'needs-client', issuer: meta.issuer || declared || new URL(url).origin };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// A few directory entries carry a credential in their address (an API key as a query value).
|
|
79
|
+
// Those aren't republished: the key is the provider's to hand out, and secret scanning
|
|
80
|
+
// rightly refuses it.
|
|
81
|
+
function carriesCredential(url) {
|
|
82
|
+
for (const [name, value] of new URL(url).searchParams) {
|
|
83
|
+
if (/key|token|secret|auth|signature|tracker/i.test(name) || /^[A-Za-z0-9_-]{24,}$/.test(value)) return true;
|
|
84
|
+
}
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
module.exports = { check, transportFor, carriesCredential };
|
package/src/desktop.js
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The Claude desktop app runs on your subscription accounts and API keys through
|
|
4
|
+
// claude-nonstop's gateway in its third-party mode (gateway.js walks your order), and its
|
|
5
|
+
// sign-in screen keeps a plain Claude.ai sign-in one click away. Anthropic documents where the app reads that mode's settings
|
|
6
|
+
// (claude.com/docs/third-party/claude-desktop/configuration-format):
|
|
7
|
+
// Windows registry policy, HKLM\SOFTWARE\Policies\Claude (written in the admin prompt)
|
|
8
|
+
// Linux /etc/claude-desktop/managed-settings.json, root-owned (written in the admin prompt)
|
|
9
|
+
// macOS a configuration profile for com.anthropic.claudefordesktop. macOS lets only
|
|
10
|
+
// the user approve a profile, so setup opens it in System Settings: one click.
|
|
11
|
+
// Settings take effect the next time the app starts.
|
|
12
|
+
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const os = require('os');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
const crypto = require('crypto');
|
|
17
|
+
const { spawn, spawnSync } = require('child_process');
|
|
18
|
+
const paths = require('./paths');
|
|
19
|
+
const { writeJson } = require('./files');
|
|
20
|
+
const { psQuote, shQuote } = require('./elevate');
|
|
21
|
+
|
|
22
|
+
const DOMAIN = 'com.anthropic.claudefordesktop';
|
|
23
|
+
const LINUX_FILE = '/etc/claude-desktop/managed-settings.json';
|
|
24
|
+
const WIN_KEY = 'HKLM\\SOFTWARE\\Policies\\Claude';
|
|
25
|
+
const PROFILE = path.join(paths.HOME, 'claude-nonstop-desktop.mobileconfig');
|
|
26
|
+
|
|
27
|
+
function settings(cfg, v) {
|
|
28
|
+
return {
|
|
29
|
+
inferenceProvider: 'gateway',
|
|
30
|
+
// With SSH hosts set up, a name the app doesn't take for loopback, so its SSH sessions
|
|
31
|
+
// can start; it still leads here, and through a tunnel on each server (ssh.js).
|
|
32
|
+
inferenceGatewayBaseUrl: require('./ssh').inUse(cfg) ? require('./ssh').gatewayUrl(cfg) : `http://127.0.0.1:${cfg.port}`,
|
|
33
|
+
inferenceGatewayApiKey: v.gatewayToken,
|
|
34
|
+
inferenceGatewayAuthScheme: 'bearer',
|
|
35
|
+
// Third-party mode keeps its own history, so turn on Anthropic's import: Settings →
|
|
36
|
+
// Import & export brings over your claude.ai chats and the Code and Cowork sessions
|
|
37
|
+
// already on this computer, and a new chat offers it when it finds earlier sessions.
|
|
38
|
+
claudeAiImport: JSON.stringify({ enabled: true, automatic3pImport: true, bannerBehavior: 'detect' }),
|
|
39
|
+
// In third-party mode the app limits Code sessions to an allowlist of sites (strict
|
|
40
|
+
// sandbox mode) unless this list contains "*". This is your own computer, so by default
|
|
41
|
+
// sessions reach any site, as in a normal install. Settings → Strict sandbox restores it.
|
|
42
|
+
...(cfg.desktopStrictSandbox ? {} : { coworkEgressAllowedHosts: JSON.stringify(['*']) }),
|
|
43
|
+
// Third-party mode leaves the built-in browser and desktop extensions off unless they
|
|
44
|
+
// are switched on, so Code sessions get the same browser pane and extensions as before.
|
|
45
|
+
builtinBrowserEnabled: 'true',
|
|
46
|
+
isDesktopExtensionEnabled: 'true',
|
|
47
|
+
// This list is an allowlist: a marketplace not on it is gone from the app. Third-party
|
|
48
|
+
// mode also hides the claude.ai connector directory and the button for adding your own.
|
|
49
|
+
// So the list names Anthropic's own plugin marketplace, as in a normal install, and the
|
|
50
|
+
// official connector directory as a plugin marketplace in Directory → Organization: one
|
|
51
|
+
// plugin per connector, built from claude.com/connectors (scripts/build-marketplace.js).
|
|
52
|
+
// The app re-fetches both by itself.
|
|
53
|
+
allowedPluginMarketplaces: JSON.stringify([OFFICIAL_MARKETPLACE, CONNECTOR_MARKETPLACE]),
|
|
54
|
+
// Connectors added with `claude-nonstop connectors add` show for everyone, always.
|
|
55
|
+
...(connectors(cfg).length ? { managedMcpServers: JSON.stringify(connectors(cfg)) } : {}),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const OFFICIAL_MARKETPLACE = { source: 'github', repo: 'anthropics/claude-plugins-official', expectedName: 'claude-plugins-official' };
|
|
60
|
+
const CONNECTOR_MARKETPLACE = { source: 'github', repo: 'umer-jahangier/claude-nonstop', path: 'connectors', expectedName: 'nonstop-connectors' };
|
|
61
|
+
|
|
62
|
+
const connectors = (cfg) => (Array.isArray(cfg.desktopConnectors) ? cfg.desktopConnectors : []);
|
|
63
|
+
|
|
64
|
+
// A connector entry the app accepts: a remote server by URL, signing in through OAuth
|
|
65
|
+
// unless it needs no sign-in.
|
|
66
|
+
function connector(name, url, { oauth = true } = {}) {
|
|
67
|
+
if (!name || !/^[\w .-]{1,64}$/.test(name)) throw new Error('a connector name is letters, numbers, spaces, dots, dashes or underscores, up to 64 characters');
|
|
68
|
+
let parsed;
|
|
69
|
+
try {
|
|
70
|
+
parsed = new URL(url);
|
|
71
|
+
} catch {
|
|
72
|
+
throw new Error(`${url} isn't a URL`);
|
|
73
|
+
}
|
|
74
|
+
if (parsed.protocol !== 'https:') throw new Error('the desktop app only connects to https:// servers');
|
|
75
|
+
return { name, transport: 'http', url: parsed.href, ...(oauth ? { oauth: true } : {}) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Every key claude-nonstop may write, so one it no longer wants is removed, not left behind.
|
|
79
|
+
const MANAGED_KEYS = ['inferenceProvider', 'inferenceGatewayBaseUrl', 'inferenceGatewayApiKey', 'inferenceGatewayAuthScheme', 'claudeAiImport', 'coworkEgressAllowedHosts', 'builtinBrowserEnabled', 'isDesktopExtensionEnabled', 'allowedPluginMarketplaces', 'managedMcpServers'];
|
|
80
|
+
|
|
81
|
+
// A copy of the settings as JSON, for typing into the app's window by hand if ever needed.
|
|
82
|
+
function write(cfg, v) {
|
|
83
|
+
writeJson(paths.DESKTOP_CONFIG, settings(cfg, v));
|
|
84
|
+
return paths.DESKTOP_CONFIG;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const STEPS = [
|
|
88
|
+
'In the Claude desktop app, open Help → Troubleshooting → Enable Developer Mode.',
|
|
89
|
+
'Open Developer → Configure Third-Party Inference…, choose Gateway, and enter the three values below.',
|
|
90
|
+
'Click Apply Changes, then Save & Restart.',
|
|
91
|
+
];
|
|
92
|
+
|
|
93
|
+
const managedOff = () => process.env.CLAUDE_NONSTOP_DESKTOP_MANAGED === '0';
|
|
94
|
+
|
|
95
|
+
// Whether the Claude desktop app is (or has been) on this computer.
|
|
96
|
+
function appInstalled() {
|
|
97
|
+
const home = os.homedir();
|
|
98
|
+
const candidates = process.platform === 'darwin'
|
|
99
|
+
? ['/Applications/Claude.app', path.join(home, 'Applications', 'Claude.app')]
|
|
100
|
+
: process.platform === 'win32'
|
|
101
|
+
? [path.join(process.env.LOCALAPPDATA || '', 'AnthropicClaude'), path.join(process.env.APPDATA || '', 'Claude'), path.join(process.env.LOCALAPPDATA || '', 'Claude-3p')]
|
|
102
|
+
: ['/usr/bin/claude-desktop', '/opt/Claude', path.join(home, '.config', 'Claude')];
|
|
103
|
+
return candidates.some((p) => p && fs.existsSync(p));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Whether the desktop app is open right now. When it can't tell, it says yes. On a Mac the
|
|
107
|
+
// match is the app itself, not Claude Code's lowercase helper app with a similar path.
|
|
108
|
+
function appRunning() {
|
|
109
|
+
try {
|
|
110
|
+
if (process.platform === 'win32') {
|
|
111
|
+
const r = spawnSync('tasklist', ['/FI', 'IMAGENAME eq claude.exe', '/NH'], { encoding: 'utf8', windowsHide: true });
|
|
112
|
+
return r.status !== 0 || /claude\.exe/i.test(r.stdout);
|
|
113
|
+
}
|
|
114
|
+
const r = spawnSync('ps', ['-axo', 'args'], { encoding: 'utf8' });
|
|
115
|
+
if (r.status !== 0) return true;
|
|
116
|
+
return process.platform === 'darwin' ? /\/Claude\.app\/Contents\/MacOS\/Claude(\s|$)/m.test(r.stdout) : /claude-desktop/i.test(r.stdout);
|
|
117
|
+
} catch {
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// The settings the app reads today from the documented managed location, if any.
|
|
123
|
+
function current() {
|
|
124
|
+
try {
|
|
125
|
+
if (process.platform === 'darwin') {
|
|
126
|
+
const user = os.userInfo().username;
|
|
127
|
+
for (const file of [`/Library/Managed Preferences/${user}/${DOMAIN}.plist`, `/Library/Managed Preferences/${DOMAIN}.plist`]) {
|
|
128
|
+
if (!fs.existsSync(file)) continue;
|
|
129
|
+
const r = spawnSync('plutil', ['-convert', 'json', '-o', '-', file], { encoding: 'utf8' });
|
|
130
|
+
if (r.status === 0) return JSON.parse(r.stdout);
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
if (process.platform === 'win32') {
|
|
135
|
+
const r = spawnSync('reg.exe', ['query', WIN_KEY], { encoding: 'utf8', windowsHide: true });
|
|
136
|
+
if (r.status !== 0) return null;
|
|
137
|
+
const out = {};
|
|
138
|
+
for (const line of r.stdout.split(/\r?\n/)) {
|
|
139
|
+
const m = line.match(/^\s+(\S+)\s+REG_SZ\s+(.*)$/);
|
|
140
|
+
if (m) out[m[1]] = m[2].trim();
|
|
141
|
+
}
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
return JSON.parse(fs.readFileSync(LINUX_FILE, 'utf8'));
|
|
145
|
+
} catch {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// The web page asks often; reading the managed settings means running a tool, so keep the
|
|
151
|
+
// answer for a few seconds.
|
|
152
|
+
let cached = { at: 0, value: null };
|
|
153
|
+
function currentCached() {
|
|
154
|
+
if (Date.now() - cached.at > 5000) cached = { at: Date.now(), value: current() };
|
|
155
|
+
return cached.value;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function applied(want, { fresh = false } = {}) {
|
|
159
|
+
if (fresh) cached.at = 0;
|
|
160
|
+
const have = currentCached();
|
|
161
|
+
return Boolean(have && MANAGED_KEYS.every((k) => String(have[k] ?? '') === String(want[k] ?? '')));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// What system.js should do in its admin prompt to put the settings in place (Windows and
|
|
165
|
+
// Linux), or null when they're already there, the app isn't installed, or it's macOS.
|
|
166
|
+
function managedChange(want) {
|
|
167
|
+
if (managedOff() || process.platform === 'darwin' || !appInstalled() || applied(want, { fresh: true })) return null;
|
|
168
|
+
if (process.platform === 'win32') {
|
|
169
|
+
const key = 'HKLM:\\SOFTWARE\\Policies\\Claude';
|
|
170
|
+
const values = Object.entries(want).map(([k, value]) => `New-ItemProperty -Path ${psQuote(key)} -Name ${psQuote(k)} -Value ${psQuote(value)} -PropertyType String -Force | Out-Null`);
|
|
171
|
+
const stale = MANAGED_KEYS.filter((k) => !(k in want)).map((k) => `Remove-ItemProperty -Path ${psQuote(key)} -Name ${psQuote(k)} -ErrorAction SilentlyContinue`);
|
|
172
|
+
return { ps: [`New-Item -Path ${psQuote(key)} -Force | Out-Null`, ...values, ...stale].join('; ') };
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
file: { text: `${JSON.stringify(want, null, 2)}\n`, target: LINUX_FILE },
|
|
176
|
+
sh: (staged) => `mkdir -p /etc/claude-desktop && chown root:root /etc/claude-desktop && chmod 755 /etc/claude-desktop && cp ${shQuote(staged)} ${LINUX_FILE} && chown root:root ${LINUX_FILE} && chmod 644 ${LINUX_FILE}`,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function managedRemoval() {
|
|
181
|
+
if (process.platform === 'darwin' || !current()) return null;
|
|
182
|
+
if (process.platform === 'win32') {
|
|
183
|
+
const key = 'HKLM:\\SOFTWARE\\Policies\\Claude';
|
|
184
|
+
return { ps: MANAGED_KEYS.map((n) => `Remove-ItemProperty -Path ${psQuote(key)} -Name ${psQuote(n)} -ErrorAction SilentlyContinue`).join('; ') };
|
|
185
|
+
}
|
|
186
|
+
return { sh: () => `rm -f ${LINUX_FILE}` };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
190
|
+
|
|
191
|
+
// macOS: writes the configuration profile and opens it, which takes the user to System
|
|
192
|
+
// Settings to approve it. Returns the profile's path, or null when nothing is needed.
|
|
193
|
+
function macProfile(want, { open = true } = {}) {
|
|
194
|
+
if (managedOff() || process.platform !== 'darwin' || !appInstalled() || applied(want, { fresh: true })) return null;
|
|
195
|
+
const keys = Object.entries(want).map(([k, value]) => ` <key>${xml(k)}</key>\n <string>${xml(value)}</string>`).join('\n');
|
|
196
|
+
const profile = `<?xml version="1.0" encoding="UTF-8"?>
|
|
197
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
198
|
+
<plist version="1.0">
|
|
199
|
+
<dict>
|
|
200
|
+
<key>PayloadContent</key>
|
|
201
|
+
<array>
|
|
202
|
+
<dict>
|
|
203
|
+
<key>PayloadType</key>
|
|
204
|
+
<string>${DOMAIN}</string>
|
|
205
|
+
<key>PayloadIdentifier</key>
|
|
206
|
+
<string>dev.claude-nonstop.desktop.settings</string>
|
|
207
|
+
<key>PayloadUUID</key>
|
|
208
|
+
<string>${crypto.randomUUID().toUpperCase()}</string>
|
|
209
|
+
<key>PayloadVersion</key>
|
|
210
|
+
<integer>1</integer>
|
|
211
|
+
<key>PayloadDisplayName</key>
|
|
212
|
+
<string>Claude desktop app: claude-nonstop gateway</string>
|
|
213
|
+
${keys}
|
|
214
|
+
</dict>
|
|
215
|
+
</array>
|
|
216
|
+
<key>PayloadDisplayName</key>
|
|
217
|
+
<string>claude-nonstop for the Claude desktop app</string>
|
|
218
|
+
<key>PayloadDescription</key>
|
|
219
|
+
<string>Lets the Claude desktop app run on your API keys through claude-nonstop on this computer. Your Claude.ai subscription stays one click away on the app's sign-in screen. Remove this profile any time to undo it.</string>
|
|
220
|
+
<key>PayloadIdentifier</key>
|
|
221
|
+
<string>dev.claude-nonstop.desktop</string>
|
|
222
|
+
<key>PayloadOrganization</key>
|
|
223
|
+
<string>claude-nonstop</string>
|
|
224
|
+
<key>PayloadScope</key>
|
|
225
|
+
<string>User</string>
|
|
226
|
+
<key>PayloadType</key>
|
|
227
|
+
<string>Configuration</string>
|
|
228
|
+
<key>PayloadUUID</key>
|
|
229
|
+
<string>${crypto.randomUUID().toUpperCase()}</string>
|
|
230
|
+
<key>PayloadVersion</key>
|
|
231
|
+
<integer>1</integer>
|
|
232
|
+
</dict>
|
|
233
|
+
</plist>
|
|
234
|
+
`;
|
|
235
|
+
fs.writeFileSync(PROFILE, profile, { mode: 0o600 });
|
|
236
|
+
if (open) {
|
|
237
|
+
detached('open', [PROFILE]);
|
|
238
|
+
setTimeout(() => detached('open', ['x-apple.systempreferences:com.apple.Profiles-Settings.extension']), 1200).unref();
|
|
239
|
+
}
|
|
240
|
+
return PROFILE;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Where things stand, for the web page and `claude-nonstop status`.
|
|
244
|
+
function status(want) {
|
|
245
|
+
return {
|
|
246
|
+
file: paths.DESKTOP_CONFIG,
|
|
247
|
+
installed: appInstalled(),
|
|
248
|
+
automatic: Boolean(want) && applied(want),
|
|
249
|
+
method: process.platform === 'darwin' ? 'profile' : process.platform === 'win32' ? 'registry' : 'file',
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function detached(cmd, args) {
|
|
254
|
+
try {
|
|
255
|
+
spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref();
|
|
256
|
+
} catch {}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Shows the file in Finder / Explorer / the Linux file manager.
|
|
260
|
+
function reveal(file = paths.DESKTOP_CONFIG) {
|
|
261
|
+
if (process.platform === 'darwin') detached('open', ['-R', file]);
|
|
262
|
+
else if (process.platform === 'win32') detached('explorer.exe', [`/select,${file}`]);
|
|
263
|
+
else detached('xdg-open', [paths.HOME]);
|
|
264
|
+
return { ok: true };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
module.exports = { settings, connector, write, status, reveal, STEPS, appInstalled, appRunning, applied, managedChange, managedRemoval, macProfile, PROFILE };
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Says when to switch the Claude desktop app between your Claude.ai account and API keys.
|
|
4
|
+
// The app signs in to one Claude.ai account by itself, and claude-nonstop can't move it
|
|
5
|
+
// between accounts: subscription sign-ins belong to Anthropic's own apps. What it can do is
|
|
6
|
+
// watch that account the way it watches the others, and tell you when a switch helps:
|
|
7
|
+
// 'to-keys' the account hit its limit, and an API key can take over
|
|
8
|
+
// 'wait' the account hit its limit, and no API key can take over either
|
|
9
|
+
// 'to-account' the account has usage again while the app is running on API keys
|
|
10
|
+
// The advice shows on the web page, and each new piece of it as a notification.
|
|
11
|
+
|
|
12
|
+
const { spawn } = require('child_process');
|
|
13
|
+
const config = require('./config');
|
|
14
|
+
const vault = require('./vault');
|
|
15
|
+
const state = require('./state');
|
|
16
|
+
const accounts = require('./accounts');
|
|
17
|
+
const relay = require('./relay');
|
|
18
|
+
const desktop = require('./desktop');
|
|
19
|
+
const checks = require('./checks');
|
|
20
|
+
const events = require('./events');
|
|
21
|
+
const { log } = require('./files');
|
|
22
|
+
|
|
23
|
+
// The app counts as running on API keys while the gateway has served it in this long.
|
|
24
|
+
const ON_KEYS_MS = 30 * 60000;
|
|
25
|
+
// While the app is open, its account is checked at most this often (tests shorten it).
|
|
26
|
+
const checkEvery = () => Number(process.env.CLAUDE_NONSTOP_DESKTOP_CHECK_MS) || 10 * 60000;
|
|
27
|
+
|
|
28
|
+
const accountFor = (cfg) => cfg.accounts.find((a) => a.id === (cfg.desktopAccount || 'default')) || null;
|
|
29
|
+
|
|
30
|
+
// The advice for now, from what's already known; null when there's nothing to switch.
|
|
31
|
+
function advice(cfg = config.load(), s = state.load(), now = Date.now()) {
|
|
32
|
+
const account = accountFor(cfg);
|
|
33
|
+
const check = account && s.accounts[account.id];
|
|
34
|
+
if (!check) return null;
|
|
35
|
+
const onKeys = Boolean(s.desktop && now - s.desktop.at < ON_KEYS_MS);
|
|
36
|
+
if (!check.ok && accounts.isLimitReason(check.reason)) {
|
|
37
|
+
// Already on API keys: there's nothing to switch. If those run out too, the page says so.
|
|
38
|
+
if (onKeys) return null;
|
|
39
|
+
const keyFree = relay.keyOrder(cfg, vault.load().keys).some((k) => !state.isCoolingDown(k.id, cfg.cooldownMinutes));
|
|
40
|
+
return { kind: keyFree ? 'to-keys' : 'wait', account: account.label, reason: check.reason };
|
|
41
|
+
}
|
|
42
|
+
// "Switch back" only after the account was seen at its limit: an app you simply run on
|
|
43
|
+
// API keys isn't nagged about an account it never left.
|
|
44
|
+
return check.ok && onKeys && s.desktopLimitedAt ? { kind: 'to-account', account: account.label } : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function message(a) {
|
|
48
|
+
if (a.kind === 'to-keys') return `${a.account} reached its limit. To keep going in the Claude desktop app, switch it to the third-party option (your API keys) on its sign-in screen.`;
|
|
49
|
+
if (a.kind === 'wait') return `${a.account} reached its limit, and no API key has credit that covers Claude Code. The desktop app can carry on when the limit resets.`;
|
|
50
|
+
return `${a.account} has usage again. Switch the Claude desktop app back to Claude.ai to stop spending API credit.`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const appleString = (s) => `"${String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
54
|
+
|
|
55
|
+
function notify(text) {
|
|
56
|
+
if (process.env.CLAUDE_NONSTOP_NO_NOTIFY === '1') return;
|
|
57
|
+
const run = (cmd, args) => {
|
|
58
|
+
try {
|
|
59
|
+
spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true }).on('error', () => {}).unref();
|
|
60
|
+
} catch {}
|
|
61
|
+
};
|
|
62
|
+
if (process.platform === 'darwin') run('osascript', ['-e', `display notification ${appleString(text)} with title "claude-nonstop"`]);
|
|
63
|
+
else if (process.platform === 'linux') run('notify-send', ['claude-nonstop', text]);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// One look: check the account if its answer is old and the app is open, then save the
|
|
67
|
+
// advice and announce it if it changed. Returns the advice.
|
|
68
|
+
async function tick({ notifier = notify } = {}) {
|
|
69
|
+
const cfg = config.load();
|
|
70
|
+
const before = state.load().desktopAdvice;
|
|
71
|
+
if (cfg.desktopAlerts === false || !desktop.appInstalled()) {
|
|
72
|
+
if (before) state.setDesktopAdvice(null);
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
const account = accountFor(cfg);
|
|
76
|
+
const last = account && state.load().accounts[account.id];
|
|
77
|
+
if (account && (!last || Date.now() - last.at > checkEvery()) && desktop.appRunning()) await checks.account(account);
|
|
78
|
+
const now = advice(cfg);
|
|
79
|
+
if (now && now.kind !== 'to-account' && !state.load().desktopLimitedAt) state.setDesktopLimited(Date.now());
|
|
80
|
+
if ((now && now.kind) !== (before && before.kind)) {
|
|
81
|
+
// Once the app has left the keys again after a "switch back", the episode is over.
|
|
82
|
+
if (!now && before && before.kind === 'to-account') state.setDesktopLimited(null);
|
|
83
|
+
state.setDesktopAdvice(now && { ...now, at: Date.now(), said: false });
|
|
84
|
+
events.notify('desktop-advice', { kind: now ? now.kind : null });
|
|
85
|
+
if (now) log(`desktop app: ${now.kind} (${now.account})`);
|
|
86
|
+
}
|
|
87
|
+
// Each piece of advice is said once, and only while the app is open to act on it.
|
|
88
|
+
const current = state.load().desktopAdvice;
|
|
89
|
+
if (current && !current.said && desktop.appRunning()) {
|
|
90
|
+
state.setDesktopAdvice({ ...current, said: true });
|
|
91
|
+
notifier(message(current));
|
|
92
|
+
}
|
|
93
|
+
return now;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Runs in the gateway: a look now and then, and right after any account check finishes.
|
|
97
|
+
function start() {
|
|
98
|
+
let running = false;
|
|
99
|
+
const look = () => {
|
|
100
|
+
if (running) return;
|
|
101
|
+
running = true;
|
|
102
|
+
tick()
|
|
103
|
+
.catch((err) => log(`desktop app: advice failed: ${err.message}`))
|
|
104
|
+
.finally(() => (running = false));
|
|
105
|
+
};
|
|
106
|
+
setInterval(look, Math.min(checkEvery(), 60000)).unref();
|
|
107
|
+
events.bus.on('event', (e) => e.type === 'checks' && !e.checking && setTimeout(look, 500).unref());
|
|
108
|
+
look();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
module.exports = { advice, message, tick, start };
|