scalemax 0.1.56 → 0.1.58

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/README.md CHANGED
@@ -144,7 +144,7 @@ npx scalemax@latest helper-bot --model fable-5 "Help me configure ScaleMax in Cu
144
144
 
145
145
  Recognized setup, repair, and verification requests execute the CLI's allowlisted client operations directly. Requests such as `setup all providers`, `fix Hermes request failed`, `configure Claude Code`, `verify OpenCode`, and `setup vs code roo extension for claude` are handled by the controller before any model request. The controller detects the relevant client, runs a safe installer when the client has one, verifies existing ScaleMax configuration, repairs ScaleMax-managed files when verification fails, re-verifies, and reports each step.
146
146
 
147
- For Claude tool access, run `scalemax claude-tools`, or ask helper-bot to `install GitHub skill tools for Claude Desktop and Claude Code`. Claude Code receives Anthropic's official `example-skills@anthropic-agent-skills` plugin plus public-GitHub read permissions. Claude Desktop/Cowork receives a local MCP server with only three tools: `github_fetch`, `github_tree`, and `github_install_skill`. The MCP server accepts only public GitHub HTTPS hosts, limits downloads, rejects unsafe archive paths and symlinks, refuses to replace an existing skill, and can write only beneath `~/Claude/skills`. It does not expose a general shell, arbitrary URLs, or unrestricted filesystem access. Restart Claude Desktop after installation and use Cowork or Code; a normal Chat tab does not expose local tools.
147
+ For Claude tool access, run `scalemax claude-tools`, or ask helper-bot to `install GitHub skill tools for Claude Desktop and Claude Code`. The same command adds **ScaleMax Connectors** (the apps you connect once at https://dashboard.scalemax.pro/connectors, served as one MCP server at `https://api.scalemax.pro/mcp`): a `ScaleMax Connectors` entry in the `managedMcpServers` of your ScaleMax Claude Desktop third-party profile, and a user-scope `scalemax-connectors` HTTP server in `~/.claude.json` for Claude Code. Both send `Authorization: Bearer <key>` through a small headers helper (`~/.scalemax/connectors-headers.sh`, or `.cmd` on Windows) that reads the key from the private file `~/.scalemax/connectors.key`, so the key is never written into Claude's configuration. It also sets `skipWebFetchPreflight: true` (Desktop profile and `~/.claude/settings.json`) unless you set it yourself. Entries and values you added are never replaced, and `scalemax remove` takes out only what the CLI added. Claude Code receives Anthropic's official `example-skills@anthropic-agent-skills` plugin plus public-GitHub read permissions. Claude Desktop/Cowork receives a local MCP server with only three tools: `github_fetch`, `github_tree`, and `github_install_skill`. The MCP server accepts only public GitHub HTTPS hosts, limits downloads, rejects unsafe archive paths and symlinks, refuses to replace an existing skill, and can write only beneath `~/Claude/skills`. It does not expose a general shell, arbitrary URLs, or unrestricted filesystem access. Restart Claude Desktop after installation and use Cowork or Code; a normal Chat tab does not expose local tools.
148
148
  Only install skills from repositories you trust: a `SKILL.md` is instruction content that Claude may follow after installation, even though the bridge itself cannot execute arbitrary repository code.
149
149
 
150
150
  For Roo Code, helper-bot can install VS Code on Windows with the fixed Microsoft winget package, install the official Roo Code extension, write OpenAI and Claude ScaleMax profiles when the key exposes those families, and verify the import handoff. For DeepSeek V4 Flash, helper-bot creates an agent profile only when authenticated discovery reports `capabilities.tools=true`; otherwise it installs Continue's safe Chat/Edit fallback. For general troubleshooting that cannot be completed by a fixed client action, helper-bot sends a small `gpt-5.4` request grounded with bundled ScaleMax documentation about stored authentication, credit/token base URLs, provider scope, client setup, and common errors. The language model never generates or executes shell commands; only fixed ScaleMax client detection, installation, configuration, verification, and rollback operations are available to the controller.
@@ -172,7 +172,7 @@ For clients without a stable official config file, the installer writes a ScaleM
172
172
 
173
173
  ### Codex
174
174
 
175
- ScaleMax configures the official Codex custom-provider interface in `~/.codex/config.toml` with `wire_api = "responses"`, and stores the selected key in Codex's private `~/.codex/auth.json`. Detection is semantic: unrelated or ChatGPT-authenticated Codex files are not reported as ScaleMax-configured. Only GPT models from the authenticated catalog are eligible (`gpt-5.6-terra` first, or `auto` on an Auto key); a key with no GPT model is told so and Codex is left unchanged. The generated files are private, and verification performs a minimal `/v1/responses` request before reporting success.
175
+ ScaleMax configures the official Codex custom-provider interface in `~/.codex/config.toml` with `wire_api = "responses"`, and stores the selected key in Codex's private `~/.codex/auth.json`. Detection is semantic: unrelated or ChatGPT-authenticated Codex files are not reported as ScaleMax-configured. Only GPT models from the authenticated catalog are eligible (`gpt-5.6-terra` first, or `auto` on an Auto key); a key with no GPT model is told so and Codex is left unchanged. The generated files are private, and verification performs a minimal `/v1/responses` request before reporting success. Setup also adds ScaleMax Connectors as `[mcp_servers.scalemax]` (Streamable HTTP, `https://api.scalemax.pro/mcp`) with an `http_headers_helper` that reads the key from `~/.scalemax/connectors.key`; a `[mcp_servers.scalemax]` table you wrote yourself is left alone, and `scalemax remove` strips only ours.
176
176
 
177
177
  ### Claude Code
178
178
 
@@ -1,16 +1,40 @@
1
1
  import chalk from 'chalk';
2
2
  import { installClaudeGithubTools } from '../configure/claude-tools.js';
3
+ import { CONNECTORS_DASHBOARD_URL } from '../configure/connectors.js';
4
+ import { loadApiKey } from '../utils/keyStore.js';
5
+ import { promptForValidatedKey } from '../utils/installerConfig.js';
3
6
  import { homeDir } from '../utils/paths.js';
7
+ function printConnectors(client, result) {
8
+ if (!result)
9
+ return;
10
+ if (result.configured)
11
+ console.log(chalk.green(`✓ ${client}: ${result.message}.`));
12
+ else
13
+ console.log(chalk.yellow(`! ${client}: ${result.message}`));
14
+ }
4
15
  export async function claudeToolsCommand(home = homeDir()) {
5
- console.log(chalk.dim('Installing bounded public-GitHub tools for Claude Desktop/Cowork and Claude Code…'));
6
- const result = await installClaudeGithubTools('both', home, process.platform, process.env);
16
+ // ScaleMax Connectors authenticate with the ScaleMax key; the key itself is
17
+ // only ever written to a private file that the headers helper reads.
18
+ let apiKey = await loadApiKey(home);
19
+ if (!apiKey && process.stdin.isTTY) {
20
+ console.log(chalk.dim('ScaleMax Connectors use your ScaleMax API key. It is stored privately and never written into Claude\'s config files.'));
21
+ apiKey = await promptForValidatedKey(home, 'Enter your ScaleMax API key:');
22
+ }
23
+ console.log(chalk.dim('Installing bounded public-GitHub tools and ScaleMax Connectors for Claude Desktop/Cowork and Claude Code…'));
24
+ const result = await installClaudeGithubTools('both', home, process.platform, process.env, undefined, { apiKey });
7
25
  if (result.desktop) {
8
26
  console.log(chalk.green(`✓ Claude Desktop MCP verified (${result.desktop.configPaths.length} config${result.desktop.configPaths.length === 1 ? '' : 's'}).`));
9
27
  console.log(chalk.dim(` Tools: github_fetch, github_tree, github_install_skill · destination: ~/Claude/skills`));
28
+ printConnectors('Claude Desktop', result.desktop.connectors);
10
29
  }
11
- if (result.code?.installed)
30
+ if (result.code?.installed) {
12
31
  console.log(chalk.green(`✓ Claude Code ${result.code.message}.`));
32
+ printConnectors('Claude Code', result.code.connectors);
33
+ }
13
34
  else if (result.code)
14
35
  console.log(chalk.yellow(`! ${result.code.message}`));
36
+ if (result.desktop?.connectors.configured || result.code?.connectors?.configured) {
37
+ console.log(chalk.dim(` Connect GitHub, Notion, Linear and more once at ${CONNECTORS_DASHBOARD_URL}; they appear in Claude as "ScaleMax Connectors".`));
38
+ }
15
39
  console.log(chalk.dim('No general shell, arbitrary URL, or unrestricted filesystem tool was granted. Restart Claude Desktop before using the new MCP tools.'));
16
40
  }
@@ -1083,15 +1083,23 @@ export async function executeHelperAction(question, connection, home, clientCata
1083
1083
  : /\bclaude\s+(?:code|cli|terminal)\b/i.test(cleanQuestion) ? 'code' : 'both';
1084
1084
  write(`✓ Stored ${helperBillingMode(connection)} key is authenticated; secrets remain hidden.`);
1085
1085
  write(`→ ${kind === 'verify' ? 'Verifying and reconciling' : 'Installing'} bounded public-GitHub tools for ${toolTarget === 'both' ? 'Claude Desktop/Cowork and Claude Code' : toolTarget === 'desktop' ? 'Claude Desktop/Cowork' : 'Claude Code'}…`);
1086
- const tools = await installClaudeGithubTools(toolTarget, home, connection.platform || process.platform, process.env);
1086
+ const tools = await installClaudeGithubTools(toolTarget, home, connection.platform || process.platform, process.env, undefined, { apiKey: connection.apiKey });
1087
1087
  const completed = [];
1088
1088
  if (tools.desktop) {
1089
1089
  completed.push(`Claude Desktop MCP exposes github_fetch, github_tree, and github_install_skill; installs are confined to ~/Claude/skills`);
1090
1090
  write('✓ Claude Desktop GitHub MCP process and tool catalog verified.');
1091
+ if (tools.desktop.connectors.configured)
1092
+ completed.push(tools.desktop.connectors.message);
1093
+ write(`${tools.desktop.connectors.configured ? '✓' : '!'} ${tools.desktop.connectors.message}`);
1091
1094
  }
1092
1095
  if (tools.code?.installed) {
1093
1096
  completed.push(`Claude Code ${tools.code.message}`);
1094
1097
  write(`✓ Claude Code ${tools.code.message}.`);
1098
+ if (tools.code.connectors) {
1099
+ if (tools.code.connectors.configured)
1100
+ completed.push(tools.code.connectors.message);
1101
+ write(`${tools.code.connectors.configured ? '✓' : '!'} ${tools.code.connectors.message}`);
1102
+ }
1095
1103
  }
1096
1104
  else if (tools.code) {
1097
1105
  write(`! ${tools.code.message}`);
@@ -4,6 +4,7 @@ import { clients } from '../clients.js';
4
4
  import { loadApiKey, loadBaseUrl } from '../utils/keyStore.js';
5
5
  import { homeDir } from '../utils/paths.js';
6
6
  import { removeStatusLine } from '../configure/statusline.js';
7
+ import { removeClaudeConnectors } from '../configure/claude-tools.js';
7
8
  export async function removeCommand(home = homeDir()) {
8
9
  const [apiKey, baseUrl] = await Promise.all([loadApiKey(home), loadBaseUrl(home)]);
9
10
  const failures = [];
@@ -32,6 +33,18 @@ export async function removeCommand(home = homeDir()) {
32
33
  statusSpinner.fail(`Status line remove failed: ${message}`);
33
34
  failures.push(`Status line: ${message}`);
34
35
  }
36
+ // Last: every client's own config is gone by now, so no client still names
37
+ // the ScaleMax Connectors headers helper when its files are deleted.
38
+ const connectorsSpinner = ora('Removing ScaleMax Connectors').start();
39
+ try {
40
+ const res = await removeClaudeConnectors(home, process.platform, process.env);
41
+ connectorsSpinner.succeed(`ScaleMax Connectors: ${res.message}`);
42
+ }
43
+ catch (err) {
44
+ const message = err instanceof Error ? err.message : String(err);
45
+ connectorsSpinner.fail(`ScaleMax Connectors remove failed: ${message}`);
46
+ failures.push(`ScaleMax Connectors: ${message}`);
47
+ }
35
48
  if (failures.length)
36
49
  throw new Error(`${failures.length} client removal(s) failed:\n${failures.map(f => `- ${f}`).join('\n')}`);
37
50
  console.log(chalk.green('✓ ScaleMax-managed client configurations removed or restored; unmanaged files were left unchanged.'));
@@ -8,35 +8,74 @@ export type ClaudeToolsRunner = (command: string, args: string[], options: {
8
8
  env: NodeJS.ProcessEnv;
9
9
  input?: string;
10
10
  }) => Promise<CommandResult>;
11
+ /** Where ScaleMax Connectors (the aggregated MCP server) ended up for one client. */
12
+ export interface ConnectorsSetupResult {
13
+ /** The client now reaches ScaleMax Connectors (our entry, or one the user already had). */
14
+ configured: boolean;
15
+ changed: boolean;
16
+ message: string;
17
+ }
18
+ export interface ClaudeToolsOptions {
19
+ /** The ScaleMax key the connectors helper sends. Without one, connectors are skipped. */
20
+ apiKey?: string;
21
+ }
11
22
  export interface ClaudeDesktopToolsResult {
12
23
  scriptPath: string;
13
24
  configPaths: string[];
14
25
  managedConfigPaths: string[];
15
26
  changed: boolean;
27
+ connectors: ConnectorsSetupResult;
16
28
  }
17
29
  export interface ClaudeCodeToolsResult {
18
30
  installed: boolean;
19
31
  changed: boolean;
20
32
  settingsPath?: string;
21
33
  message: string;
34
+ connectors?: ConnectorsSetupResult;
22
35
  }
23
36
  export interface ClaudeToolsResult {
24
37
  desktop?: ClaudeDesktopToolsResult;
25
38
  code?: ClaudeCodeToolsResult;
26
39
  }
40
+ /** Every Claude Desktop data root this platform can use (for tests and diagnostics). */
41
+ export declare function claudeDesktopConfigRoots(home: string, platform: NodeJS.Platform, env?: NodeJS.ProcessEnv): string[];
27
42
  export declare function claudeDesktopConfigPath(root: string): string;
28
43
  export declare function claudeGithubToolPath(home: string): string;
29
44
  /**
30
45
  * Settings a ScaleMax-gateway Claude Desktop (3P) profile needs for Cowork's
31
46
  * tools to work. Without `coworkEgressAllowedHosts` Cowork and Chat refuse
32
47
  * EVERY Web Fetch (and the sandbox shell reaches no host); tool search keeps
33
- * many connectors from filling the context. An allowlist the user already set
34
- * is left alone.
48
+ * many connectors from filling the context. `skipWebFetchPreflight` stops Code
49
+ * sessions sending every fetched hostname to api.anthropic.com first (and
50
+ * failing every Web Fetch where that host is unreachable). A value the user
51
+ * already set for either of the last two is left alone.
35
52
  */
36
53
  export declare function scaleMaxManagedConfigPatch(current: Record<string, unknown>): Record<string, unknown>;
37
54
  /** Install and verify the bounded public-GitHub MCP server for Claude Desktop/Cowork. */
38
- export declare function installClaudeDesktopGithubTools(home: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv, runner?: ClaudeToolsRunner, nodePath?: string, assetPath?: string): Promise<ClaudeDesktopToolsResult>;
55
+ export declare function installClaudeDesktopGithubTools(home: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv, runner?: ClaudeToolsRunner, nodePath?: string, assetPath?: string, options?: ClaudeToolsOptions): Promise<ClaudeDesktopToolsResult>;
56
+ /** Claude Code's user-scope MCP servers live in ~/.claude.json, not in settings.json. */
57
+ export declare function claudeCodeUserConfigPath(home: string): string;
58
+ /**
59
+ * Add the `scalemax-connectors` HTTP server at user scope. Its Authorization
60
+ * header comes from the headers helper, so ~/.claude.json never holds the key.
61
+ * A server of that name the user configured themselves (for example with
62
+ * `claude mcp add ... --header`) is left alone, and so is our URL under another name.
63
+ */
64
+ export declare function installClaudeCodeConnectors(home: string, platform: NodeJS.Platform, apiKey: string): Promise<ConnectorsSetupResult>;
39
65
  /** Install Anthropic's official skills plugin and safe GitHub-read permissions for Claude Code. */
40
- export declare function installClaudeCodeGithubSkills(home: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv, runner?: ClaudeToolsRunner): Promise<ClaudeCodeToolsResult>;
41
- export declare function installClaudeGithubTools(target: 'desktop' | 'code' | 'both', home: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv, runner?: ClaudeToolsRunner): Promise<ClaudeToolsResult>;
66
+ export declare function installClaudeCodeGithubSkills(home: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv, runner?: ClaudeToolsRunner, options?: ClaudeToolsOptions): Promise<ClaudeCodeToolsResult>;
67
+ export declare function installClaudeGithubTools(target: 'desktop' | 'code' | 'both', home: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv, runner?: ClaudeToolsRunner, options?: ClaudeToolsOptions): Promise<ClaudeToolsResult>;
68
+ export interface ClaudeConnectorsRemovalResult {
69
+ changed: boolean;
70
+ files: string[];
71
+ message: string;
72
+ }
73
+ /**
74
+ * Take out exactly what claude-tools added for ScaleMax Connectors: our
75
+ * managedMcpServers entry in every Claude Desktop profile, our
76
+ * `scalemax-connectors` server in ~/.claude.json, `skipWebFetchPreflight` only
77
+ * where this CLI turned it on, and the helper + key files. Entries, servers and
78
+ * values the user added are kept. Unreadable files are left untouched.
79
+ */
80
+ export declare function removeClaudeConnectors(home: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv): Promise<ClaudeConnectorsRemovalResult>;
42
81
  export {};
@@ -2,8 +2,10 @@ import fs from 'fs-extra';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { execa } from 'execa';
5
- import { atomicWrite, backupFile } from '../utils/fs.js';
5
+ import { atomicWrite, backupFile, captureFileSnapshots, restoreFileSnapshots } from '../utils/fs.js';
6
6
  import { configRoot } from '../utils/paths.js';
7
+ import { clientConfigPath } from './paths.js';
8
+ import { CONNECTORS_CLAUDE_CODE_NAME, CONNECTORS_MCP_URL, claudeCodeConnectorsServer, connectorsHelperPath, connectorsKeyOrThrow, connectorsKeyPath, ensureConnectorsHelper, isOurClaudeCodeConnectorsServer, readConnectorsState, recordSkipWebFetchPreflight, removeConnectorsHelper, withDesktopConnectorsServer, withoutDesktopConnectorsServer, } from './connectors.js';
7
9
  const MCP_SERVER_NAME = 'scalemax-github';
8
10
  const MCP_ASSET = fileURLToPath(new URL('../assets/claude-github-tools.mjs', import.meta.url));
9
11
  const CLAUDE_SKILLS_REPO = 'anthropics/skills';
@@ -33,7 +35,20 @@ function asRecord(value) {
33
35
  }
34
36
  function desktopConfigRoots(home, platform, env) {
35
37
  const root = configRoot(home, platform, env);
36
- return [path.join(root, 'Claude'), path.join(root, 'Claude-3p')];
38
+ const roots = [path.join(root, 'Claude'), path.join(root, 'Claude-3p')];
39
+ if (platform === 'win32') {
40
+ // Claude Desktop 1.5186.0+ keeps its third-party data (configLibrary
41
+ // included) in %LOCALAPPDATA%\Claude-3p, not the Roaming profile. The MSIX
42
+ // installer on Windows 10 virtualises it under Packages\...\LocalCache.
43
+ const local = env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
44
+ const msix = path.join(local, 'Packages', 'Claude_pzs8sxrjxfjjc', 'LocalCache');
45
+ roots.push(path.join(local, 'Claude-3p'), path.join(msix, 'Local', 'Claude-3p'), path.join(msix, 'Roaming', 'Claude-3p'));
46
+ }
47
+ return [...new Set(roots)];
48
+ }
49
+ /** Every Claude Desktop data root this platform can use (for tests and diagnostics). */
50
+ export function claudeDesktopConfigRoots(home, platform, env = {}) {
51
+ return desktopConfigRoots(home, platform, env);
37
52
  }
38
53
  export function claudeDesktopConfigPath(root) {
39
54
  return path.join(root, 'claude_desktop_config.json');
@@ -101,13 +116,17 @@ function isScaleMaxManagedGateway(value) {
101
116
  * Settings a ScaleMax-gateway Claude Desktop (3P) profile needs for Cowork's
102
117
  * tools to work. Without `coworkEgressAllowedHosts` Cowork and Chat refuse
103
118
  * EVERY Web Fetch (and the sandbox shell reaches no host); tool search keeps
104
- * many connectors from filling the context. An allowlist the user already set
105
- * is left alone.
119
+ * many connectors from filling the context. `skipWebFetchPreflight` stops Code
120
+ * sessions sending every fetched hostname to api.anthropic.com first (and
121
+ * failing every Web Fetch where that host is unreachable). A value the user
122
+ * already set for either of the last two is left alone.
106
123
  */
107
124
  export function scaleMaxManagedConfigPatch(current) {
108
125
  const next = { ...current, isLocalDevMcpEnabled: true, toolSearchEnabled: true };
109
126
  if (current.coworkEgressAllowedHosts === undefined)
110
127
  next.coworkEgressAllowedHosts = ['*'];
128
+ if (current.skipWebFetchPreflight === undefined)
129
+ next.skipWebFetchPreflight = true;
111
130
  return next;
112
131
  }
113
132
  async function managedThirdPartyConfigs(roots) {
@@ -147,7 +166,7 @@ async function verifyMcpProcess(scriptPath, nodePath, env, runner) {
147
166
  }
148
167
  }
149
168
  /** Install and verify the bounded public-GitHub MCP server for Claude Desktop/Cowork. */
150
- export async function installClaudeDesktopGithubTools(home, platform = process.platform, env = process.env, runner = defaultRunner, nodePath = process.execPath, assetPath = MCP_ASSET) {
169
+ export async function installClaudeDesktopGithubTools(home, platform = process.platform, env = process.env, runner = defaultRunner, nodePath = process.execPath, assetPath = MCP_ASSET, options = {}) {
151
170
  const roots = await existingDesktopRoots(home, platform, env);
152
171
  const configPaths = roots.map(claudeDesktopConfigPath);
153
172
  const scriptPath = claudeGithubToolPath(home);
@@ -172,16 +191,39 @@ export async function installClaudeDesktopGithubTools(home, platform = process.p
172
191
  },
173
192
  });
174
193
  }
194
+ // ScaleMax Connectors go only into ScaleMax-gateway 3P profiles: the
195
+ // managedMcpServers key exists only in third-party mode.
196
+ const helperPath = connectorsHelperPath(home, platform);
197
+ let connectorsKey;
198
+ let keyProblem;
199
+ if (options.apiKey) {
200
+ try {
201
+ connectorsKey = connectorsKeyOrThrow(options.apiKey);
202
+ }
203
+ catch (error) {
204
+ keyProblem = error instanceof Error ? error.message : String(error);
205
+ }
206
+ }
175
207
  const managedConfigs = [];
208
+ const connectorChanges = [];
176
209
  for (const file of await managedThirdPartyConfigs(roots)) {
177
210
  const current = await parseJsonObject(file);
178
211
  if (!isScaleMaxManagedGateway(current))
179
212
  continue;
180
- managedConfigs.push({ file, current, next: scaleMaxManagedConfigPatch(current) });
213
+ let next = scaleMaxManagedConfigPatch(current);
214
+ if (connectorsKey) {
215
+ const merged = withDesktopConnectorsServer(next, helperPath);
216
+ next = merged.next;
217
+ connectorChanges.push({ file, change: merged.change });
218
+ }
219
+ managedConfigs.push({ file, current, next });
181
220
  }
221
+ const connectorsReady = connectorChanges.some(item => item.change === 'added' || item.change === 'updated' || item.change === 'unchanged');
222
+ const helperSnapshots = connectorsReady ? await captureFileSnapshots([helperPath, connectorsKeyPath(home)]) : [];
182
223
  const oldScript = await fs.readFile(scriptPath, 'utf8').catch(() => undefined);
183
224
  const written = [];
184
225
  let changed = oldScript !== source;
226
+ let connectorsChanged = false;
185
227
  try {
186
228
  await atomicWrite(scriptPath, source, 0o700, platform);
187
229
  await fs.chmod(scriptPath, 0o700).catch(() => undefined);
@@ -189,6 +231,9 @@ export async function installClaudeDesktopGithubTools(home, platform = process.p
189
231
  // launches the server with the signed-in user's OS home; forcing HOME here
190
232
  // can change platform DNS/proxy behavior and is unnecessary for tools/list.
191
233
  await verifyMcpProcess(scriptPath, nodeCommand, env, runner);
234
+ // The helper must exist before any profile names it.
235
+ if (connectorsReady && connectorsKey)
236
+ connectorsChanged = (await ensureConnectorsHelper(home, platform, connectorsKey)).changed;
192
237
  for (const item of [...configs, ...managedConfigs]) {
193
238
  const previous = await fs.readFile(item.file, 'utf8').catch(() => undefined);
194
239
  const next = JSON.stringify(item.next, null, 2) + '\n';
@@ -199,6 +244,8 @@ export async function installClaudeDesktopGithubTools(home, platform = process.p
199
244
  await atomicWrite(item.file, next, 0o600, platform);
200
245
  written.push({ file: item.file, previous });
201
246
  }
247
+ // Only where this run turned it on; remove() turns off exactly these.
248
+ await recordSkipWebFetchPreflight(home, managedConfigs.filter(item => item.current.skipWebFetchPreflight === undefined && item.next.skipWebFetchPreflight === true).map(item => item.file), platform);
202
249
  }
203
250
  catch (error) {
204
251
  for (const item of written.reverse()) {
@@ -211,15 +258,39 @@ export async function installClaudeDesktopGithubTools(home, platform = process.p
211
258
  await fs.remove(scriptPath).catch(() => undefined);
212
259
  else
213
260
  await atomicWrite(scriptPath, oldScript, 0o700, platform).catch(() => undefined);
261
+ await restoreFileSnapshots(helperSnapshots, platform).catch(() => undefined);
214
262
  throw error;
215
263
  }
216
264
  return {
217
265
  scriptPath,
218
266
  configPaths,
219
267
  managedConfigPaths: managedConfigs.map(item => item.file),
220
- changed,
268
+ changed: changed || connectorsChanged,
269
+ connectors: desktopConnectorsSummary(options, keyProblem, managedConfigs.length, connectorChanges, connectorsChanged),
221
270
  };
222
271
  }
272
+ function desktopConnectorsSummary(options, keyProblem, profiles, changes, helperChanged) {
273
+ if (!options.apiKey)
274
+ return { configured: false, changed: false, message: 'ScaleMax Connectors skipped: no ScaleMax API key is stored. Run `npx scalemax@latest login`, then `npx scalemax@latest claude-tools` again.' };
275
+ if (keyProblem)
276
+ return { configured: false, changed: false, message: keyProblem };
277
+ if (!profiles)
278
+ return { configured: false, changed: false, message: 'ScaleMax Connectors need Claude Desktop in third-party mode with the ScaleMax gateway; no such Claude Desktop configuration was found.' };
279
+ const ours = changes.filter(item => item.change === 'added' || item.change === 'updated' || item.change === 'unchanged');
280
+ const edited = changes.some(item => item.change === 'added' || item.change === 'updated');
281
+ const unreadable = changes.filter(item => item.change === 'unreadable').map(item => item.file);
282
+ const kept = changes.filter(item => item.change === 'kept-user-entry').map(item => item.file);
283
+ const notes = [
284
+ ...(kept.length ? [`your own ScaleMax Connectors entry was left unchanged in ${kept.join(', ')}`] : []),
285
+ ...(unreadable.length ? [`managedMcpServers is not a readable JSON array in ${unreadable.join(', ')}, so it was left unchanged`] : []),
286
+ ];
287
+ if (!ours.length)
288
+ return { configured: kept.length > 0, changed: false, message: `ScaleMax Connectors: ${notes.join('; ')}.` };
289
+ const base = edited
290
+ ? `ScaleMax Connectors added to ${ours.length} Claude Desktop profile${ours.length === 1 ? '' : 's'} (${CONNECTORS_MCP_URL})`
291
+ : `ScaleMax Connectors already set up in ${ours.length} Claude Desktop profile${ours.length === 1 ? '' : 's'}`;
292
+ return { configured: true, changed: edited || helperChanged, message: notes.length ? `${base}; ${notes.join('; ')}` : base };
293
+ }
223
294
  function parseJsonArray(text) {
224
295
  try {
225
296
  const value = JSON.parse(text);
@@ -247,18 +318,95 @@ async function writeClaudeCodeGithubPermissions(home, platform) {
247
318
  await atomicWrite(file, content, 0o600, platform);
248
319
  return { file, changed: true };
249
320
  }
321
+ /** Claude Code's user-scope MCP servers live in ~/.claude.json, not in settings.json. */
322
+ export function claudeCodeUserConfigPath(home) {
323
+ return path.join(home, '.claude.json');
324
+ }
325
+ async function fileMode(file) {
326
+ const stat = await fs.stat(file).catch(() => undefined);
327
+ return stat ? stat.mode & 0o777 : undefined;
328
+ }
329
+ /**
330
+ * `skipWebFetchPreflight: true` in ~/.claude/settings.json: Claude Code's
331
+ * WebFetch otherwise asks api.anthropic.com about every domain first, sends it
332
+ * every fetched hostname, and fails every fetch where that host is blocked.
333
+ * A value the user set (true or false) is left alone.
334
+ */
335
+ async function writeClaudeCodeSkipWebFetchPreflight(home, platform) {
336
+ const file = clientConfigPath('claude', home, platform);
337
+ const current = await parseJsonObject(file);
338
+ if (current.skipWebFetchPreflight !== undefined)
339
+ return { file, changed: false };
340
+ await backupFile(file, home);
341
+ await atomicWrite(file, JSON.stringify({ ...current, skipWebFetchPreflight: true }, null, 2) + '\n', (await fileMode(file)) ?? 0o600, platform);
342
+ await recordSkipWebFetchPreflight(home, [file], platform);
343
+ return { file, changed: true };
344
+ }
345
+ /**
346
+ * Add the `scalemax-connectors` HTTP server at user scope. Its Authorization
347
+ * header comes from the headers helper, so ~/.claude.json never holds the key.
348
+ * A server of that name the user configured themselves (for example with
349
+ * `claude mcp add ... --header`) is left alone, and so is our URL under another name.
350
+ */
351
+ export async function installClaudeCodeConnectors(home, platform, apiKey) {
352
+ const key = connectorsKeyOrThrow(apiKey);
353
+ const file = claudeCodeUserConfigPath(home);
354
+ const current = await parseJsonObject(file);
355
+ if (current.mcpServers !== undefined && (!current.mcpServers || typeof current.mcpServers !== 'object' || Array.isArray(current.mcpServers))) {
356
+ return { configured: false, changed: false, message: `ScaleMax Connectors skipped: mcpServers in ${file} is not an object, so it was left unchanged.` };
357
+ }
358
+ const servers = asRecord(current.mcpServers);
359
+ const desired = claudeCodeConnectorsServer(home, platform);
360
+ const existing = servers[CONNECTORS_CLAUDE_CODE_NAME];
361
+ if (existing !== undefined && !isOurClaudeCodeConnectorsServer(existing)) {
362
+ const theirs = asRecord(existing).url === CONNECTORS_MCP_URL;
363
+ return {
364
+ configured: theirs,
365
+ changed: false,
366
+ message: theirs
367
+ ? `ScaleMax Connectors already set up in Claude Code by you (${CONNECTORS_CLAUDE_CODE_NAME}); left unchanged`
368
+ : `ScaleMax Connectors skipped: your own ${CONNECTORS_CLAUDE_CODE_NAME} MCP server in ${file} was left unchanged`,
369
+ };
370
+ }
371
+ const otherName = Object.entries(servers).find(([name, server]) => name !== CONNECTORS_CLAUDE_CODE_NAME && asRecord(server).url === CONNECTORS_MCP_URL)?.[0];
372
+ if (existing === undefined && otherName) {
373
+ return { configured: true, changed: false, message: `ScaleMax Connectors already set up in Claude Code as "${otherName}"; left unchanged` };
374
+ }
375
+ const helper = await ensureConnectorsHelper(home, platform, key);
376
+ if (JSON.stringify(existing) === JSON.stringify(desired)) {
377
+ return { configured: true, changed: helper.changed, message: `ScaleMax Connectors already set up in Claude Code (${CONNECTORS_CLAUDE_CODE_NAME})` };
378
+ }
379
+ await backupFile(file, home);
380
+ const next = { ...current, mcpServers: { ...servers, [CONNECTORS_CLAUDE_CODE_NAME]: desired } };
381
+ await atomicWrite(file, JSON.stringify(next, null, 2) + '\n', (await fileMode(file)) ?? 0o600, platform);
382
+ return { configured: true, changed: true, message: `ScaleMax Connectors added to Claude Code as the ${CONNECTORS_CLAUDE_CODE_NAME} MCP server (${CONNECTORS_MCP_URL})` };
383
+ }
250
384
  /** Install Anthropic's official skills plugin and safe GitHub-read permissions for Claude Code. */
251
- export async function installClaudeCodeGithubSkills(home, platform = process.platform, env = process.env, runner = defaultRunner) {
385
+ export async function installClaudeCodeGithubSkills(home, platform = process.platform, env = process.env, runner = defaultRunner, options = {}) {
252
386
  const commandEnv = { ...env, HOME: home, USERPROFILE: home };
253
387
  const version = await runner('claude', ['--version'], { env: commandEnv });
254
388
  if (version.exitCode !== 0)
255
389
  return { installed: false, changed: false, message: 'Claude Code was not detected; Desktop tools can still be used.' };
256
390
  const permission = await writeClaudeCodeGithubPermissions(home, platform);
391
+ // Local file edits first: they must not depend on the plugin marketplace being reachable.
392
+ const preflight = await writeClaudeCodeSkipWebFetchPreflight(home, platform);
393
+ let connectors;
394
+ if (!options.apiKey) {
395
+ connectors = { configured: false, changed: false, message: 'ScaleMax Connectors skipped: no ScaleMax API key is stored. Run `npx scalemax@latest login`, then `npx scalemax@latest claude-tools` again.' };
396
+ }
397
+ else {
398
+ try {
399
+ connectors = await installClaudeCodeConnectors(home, platform, options.apiKey);
400
+ }
401
+ catch (error) {
402
+ connectors = { configured: false, changed: false, message: `ScaleMax Connectors skipped: ${error instanceof Error ? error.message : String(error)}` };
403
+ }
404
+ }
257
405
  const marketplaces = await runner('claude', ['plugin', 'marketplace', 'list', '--json'], { env: commandEnv });
258
406
  if (marketplaces.exitCode !== 0)
259
407
  throw new Error(`Unable to inspect Claude plugin marketplaces: ${marketplaces.all.trim() || 'Claude returned an error.'}`);
260
408
  const marketplaceInstalled = parseJsonArray(marketplaces.stdout).some(item => item?.repo === CLAUDE_SKILLS_REPO || item?.name === CLAUDE_SKILLS_MARKETPLACE);
261
- let changed = permission.changed;
409
+ let changed = permission.changed || preflight.changed || connectors.changed;
262
410
  if (!marketplaceInstalled) {
263
411
  const add = await runner('claude', ['plugin', 'marketplace', 'add', CLAUDE_SKILLS_REPO], { env: commandEnv });
264
412
  if (add.exitCode !== 0)
@@ -284,13 +432,94 @@ export async function installClaudeCodeGithubSkills(home, platform = process.pla
284
432
  changed,
285
433
  settingsPath: permission.file,
286
434
  message: `verified ${CLAUDE_SKILLS_PLUGIN} and bounded public-GitHub read permissions`,
435
+ connectors,
287
436
  };
288
437
  }
289
- export async function installClaudeGithubTools(target, home, platform = process.platform, env = process.env, runner = defaultRunner) {
438
+ export async function installClaudeGithubTools(target, home, platform = process.platform, env = process.env, runner = defaultRunner, options = {}) {
290
439
  const result = {};
291
440
  if (target === 'desktop' || target === 'both')
292
- result.desktop = await installClaudeDesktopGithubTools(home, platform, env, runner);
441
+ result.desktop = await installClaudeDesktopGithubTools(home, platform, env, runner, undefined, undefined, options);
293
442
  if (target === 'code' || target === 'both')
294
- result.code = await installClaudeCodeGithubSkills(home, platform, env, runner);
443
+ result.code = await installClaudeCodeGithubSkills(home, platform, env, runner, options);
295
444
  return result;
296
445
  }
446
+ async function readJsonObjectOrUndefined(file) {
447
+ if (!(await fs.pathExists(file)))
448
+ return undefined;
449
+ try {
450
+ const value = await fs.readJson(file);
451
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
452
+ }
453
+ catch {
454
+ return undefined;
455
+ }
456
+ }
457
+ async function rewriteJson(file, value, home, platform) {
458
+ await backupFile(file, home);
459
+ await atomicWrite(file, JSON.stringify(value, null, 2) + '\n', (await fileMode(file)) ?? 0o600, platform);
460
+ }
461
+ /**
462
+ * Take out exactly what claude-tools added for ScaleMax Connectors: our
463
+ * managedMcpServers entry in every Claude Desktop profile, our
464
+ * `scalemax-connectors` server in ~/.claude.json, `skipWebFetchPreflight` only
465
+ * where this CLI turned it on, and the helper + key files. Entries, servers and
466
+ * values the user added are kept. Unreadable files are left untouched.
467
+ */
468
+ export async function removeClaudeConnectors(home, platform = process.platform, env = process.env) {
469
+ const files = [];
470
+ const state = await readConnectorsState(home);
471
+ const preflightFiles = new Set(state.skipWebFetchPreflight);
472
+ // Claude Desktop profiles (any profile: the gateway may have changed since setup).
473
+ for (const file of await managedThirdPartyConfigs(desktopConfigRoots(home, platform, env))) {
474
+ const current = await readJsonObjectOrUndefined(file);
475
+ if (!current)
476
+ continue;
477
+ const { next, changed } = withoutDesktopConnectorsServer(current);
478
+ let edited = changed;
479
+ if (preflightFiles.has(file) && next.skipWebFetchPreflight === true) {
480
+ delete next.skipWebFetchPreflight;
481
+ edited = true;
482
+ }
483
+ preflightFiles.delete(file);
484
+ if (!edited)
485
+ continue;
486
+ await rewriteJson(file, next, home, platform);
487
+ files.push(file);
488
+ }
489
+ // Claude Code user-scope server.
490
+ const userConfig = claudeCodeUserConfigPath(home);
491
+ const claudeJson = await readJsonObjectOrUndefined(userConfig);
492
+ if (claudeJson && isOurClaudeCodeConnectorsServer(asRecord(claudeJson.mcpServers)[CONNECTORS_CLAUDE_CODE_NAME])) {
493
+ const servers = { ...asRecord(claudeJson.mcpServers) };
494
+ delete servers[CONNECTORS_CLAUDE_CODE_NAME];
495
+ const next = { ...claudeJson };
496
+ if (Object.keys(servers).length)
497
+ next.mcpServers = servers;
498
+ else
499
+ delete next.mcpServers;
500
+ await rewriteJson(userConfig, next, home, platform);
501
+ files.push(userConfig);
502
+ }
503
+ // skipWebFetchPreflight in the remaining recorded files (Claude Code settings.json).
504
+ for (const file of preflightFiles) {
505
+ const current = await readJsonObjectOrUndefined(file);
506
+ if (!current || current.skipWebFetchPreflight !== true)
507
+ continue;
508
+ const next = { ...current };
509
+ delete next.skipWebFetchPreflight;
510
+ if (Object.keys(next).length)
511
+ await rewriteJson(file, next, home, platform);
512
+ else {
513
+ await backupFile(file, home);
514
+ await fs.remove(file);
515
+ }
516
+ files.push(file);
517
+ }
518
+ const helperRemoved = await removeConnectorsHelper(home);
519
+ const changed = files.length > 0 || helperRemoved;
520
+ return {
521
+ changed,
522
+ files,
523
+ message: changed ? 'removed only the ScaleMax Connectors entries, settings and helper files this CLI added' : 'no ScaleMax Connectors configuration found',
524
+ };
525
+ }
@@ -0,0 +1,36 @@
1
+ import { DetectContext } from '../types/client.js';
2
+ /**
3
+ * Codex inside WSL, seen from Windows.
4
+ *
5
+ * The Codex desktop app runs a WSL project's agent inside the Linux distro,
6
+ * and that agent reads the distro's own ~/.codex -- not C:\Users\<me>\.codex,
7
+ * which is all setup used to write. A customer set up on Windows (2026-11-25)
8
+ * still had his ChatGPT sign-in in the Ubuntu ~/.codex: every message in his
9
+ * WSL project went to ChatGPT and hit that plan's usage limit, and nothing
10
+ * reached ScaleMax.
11
+ *
12
+ * Only distros that already have a ~/.codex are touched: those are the ones
13
+ * Codex runs in. Every failure here (no WSL, a distro that will not start, a
14
+ * file that cannot be written) is a warning: the Windows setup has already
15
+ * succeeded and stays.
16
+ */
17
+ export interface WslCodexHome {
18
+ distro: string;
19
+ /** The distro user's home as Windows sees it, e.g. \\wsl$\Ubuntu\home\me */
20
+ home: string;
21
+ }
22
+ export interface WslDeps {
23
+ /** Runs wsl.exe with these arguments and returns its raw stdout. */
24
+ run(args: string[], timeoutMs: number): Promise<Buffer>;
25
+ /** Windows path of a Linux home inside a distro. */
26
+ windowsPath(distro: string, linuxHome: string): string;
27
+ }
28
+ export declare const defaultWslDeps: WslDeps;
29
+ /** `wsl.exe -l -q` prints UTF-16LE (older builds: the console code page). */
30
+ export declare function parseWslDistroList(raw: Buffer): string[];
31
+ export declare function wslSkipped(ctx: DetectContext): boolean;
32
+ /** WSL distros whose default user already has a ~/.codex. */
33
+ export declare function findWslCodexHomes(ctx: DetectContext, deps?: WslDeps): Promise<{
34
+ homes: WslCodexHome[];
35
+ warnings: string[];
36
+ }>;