scalemax 0.1.55 → 0.1.57
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 +2 -2
- package/dist/commands/claude-tools.js +27 -3
- package/dist/commands/helper-bot.js +9 -1
- package/dist/commands/remove.js +13 -0
- package/dist/configure/claude-tools.d.ts +44 -5
- package/dist/configure/claude-tools.js +241 -12
- package/dist/configure/codex.d.ts +9 -2
- package/dist/configure/codex.js +125 -19
- package/dist/configure/connectors.d.ts +71 -0
- package/dist/configure/connectors.js +277 -0
- package/dist/configure/opencode.js +4 -1
- package/dist/index.js +2 -2
- package/package.json +1 -1
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
|
-
|
|
6
|
-
|
|
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}`);
|
package/dist/commands/remove.js
CHANGED
|
@@ -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.
|
|
34
|
-
*
|
|
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
|
-
|
|
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.
|
|
105
|
-
*
|
|
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
|
-
|
|
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
|
+
}
|
|
@@ -6,7 +6,13 @@ export interface CodexVerificationResult {
|
|
|
6
6
|
configPath: string;
|
|
7
7
|
authPath: string;
|
|
8
8
|
}
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Who owns the `scalemax` MCP server: nobody, this CLI (our URL AND our
|
|
11
|
+
* headers helper), or the user (anything else, e.g. a table set up by hand
|
|
12
|
+
* with `bearer_token_env_var`, or an inline/dotted definition).
|
|
13
|
+
*/
|
|
14
|
+
export declare function codexConnectorsOwnership(existing: string): 'absent' | 'ours' | 'user';
|
|
15
|
+
export declare function mergeCodexConfig(existing: string, baseUrl: string, model?: string, authHash?: string, keyHash?: string, connectorsTable?: string): string;
|
|
10
16
|
/**
|
|
11
17
|
* Take ScaleMax OUT of a config.toml, keeping everything else the user has --
|
|
12
18
|
* including what Codex or the user added after setup (trusted projects,
|
|
@@ -16,7 +22,8 @@ export declare function mergeCodexConfig(existing: string, baseUrl: string, mode
|
|
|
16
22
|
* Codex rewrite that drops comments still leaves `model_provider = "scalemax"`
|
|
17
23
|
* and the `[model_providers.scalemax]` table, and those must go. The three
|
|
18
24
|
* top-level keys are removed only while ScaleMax is still the provider; if the
|
|
19
|
-
* user switched provider after setup they are the user's.
|
|
25
|
+
* user switched provider after setup they are the user's. The ScaleMax
|
|
26
|
+
* Connectors table goes only when it is ours (our URL and our helper).
|
|
20
27
|
*/
|
|
21
28
|
export declare function stripScaleMaxCodexConfig(existing: string): {
|
|
22
29
|
text: string;
|
package/dist/configure/codex.js
CHANGED
|
@@ -7,6 +7,7 @@ import { atomicWrite, backupFile, captureFileSnapshots, listBackups, restoreFile
|
|
|
7
7
|
import { GENERATED_HEADER } from '../constants.js';
|
|
8
8
|
import { commandExists } from '../utils/exec.js';
|
|
9
9
|
import { codexModel, codexModelIds, sameModelId } from './models.js';
|
|
10
|
+
import { CONNECTORS_CODEX_NAME, CONNECTORS_MCP_URL, codexConnectorsTable, connectorsHelperPath, connectorsKeyOrThrow, connectorsKeyPath, ensureConnectorsHelper, isConnectorsHelperReference, } from './connectors.js';
|
|
10
11
|
const id = 'codex';
|
|
11
12
|
const name = 'Codex';
|
|
12
13
|
const provider = 'scalemax';
|
|
@@ -47,10 +48,13 @@ function codexCanUse(ctx, configured) {
|
|
|
47
48
|
return configured === selectedModel(ctx);
|
|
48
49
|
return codexModelIds(ctx).some(id => sameModelId(id, configured));
|
|
49
50
|
}
|
|
50
|
-
function
|
|
51
|
+
function scalemaxCodexTop(model, authHash, keyHash) {
|
|
51
52
|
const authMarker = authHash ? `${managedAuthHashPrefix}${authHash}\n` : '';
|
|
52
53
|
const keyMarker = keyHash ? `${managedKeyHashPrefix}${keyHash}\n` : '';
|
|
53
|
-
return `# ${GENERATED_HEADER}\n${authMarker}${keyMarker}model = "${model}"\nmodel_provider = "${provider}"\nmodel_reasoning_effort = "${reasoningEffort}"\n${modelsComment}\n
|
|
54
|
+
return `# ${GENERATED_HEADER}\n${authMarker}${keyMarker}model = "${model}"\nmodel_provider = "${provider}"\nmodel_reasoning_effort = "${reasoningEffort}"\n${modelsComment}\n`;
|
|
55
|
+
}
|
|
56
|
+
function scalemaxProviderTable(baseUrl) {
|
|
57
|
+
return `[model_providers.${provider}]\nname = "ScaleMax"\nbase_url = "${baseUrl}"\nwire_api = "responses"\nrequires_openai_auth = true\n`;
|
|
54
58
|
}
|
|
55
59
|
/** A line setup writes as a comment. Never user content, and never preserved. */
|
|
56
60
|
function isManagedCommentLine(line) {
|
|
@@ -62,20 +66,83 @@ function isManagedCommentLine(line) {
|
|
|
62
66
|
function isScaleMaxProviderSection(section) {
|
|
63
67
|
return section === `model_providers.${provider}` || section.startsWith(`model_providers.${provider}.`);
|
|
64
68
|
}
|
|
65
|
-
|
|
66
|
-
|
|
69
|
+
// ScaleMax Connectors: `[mcp_servers.scalemax]`. Its subtables
|
|
70
|
+
// (`[mcp_servers.scalemax.tools.<tool>]`, where Codex keeps per-tool approvals)
|
|
71
|
+
// are kept across setup and go with the table on remove.
|
|
72
|
+
const mcpTable = `mcp_servers.${CONNECTORS_CODEX_NAME}`;
|
|
73
|
+
/** `[mcp_servers."scalemax"]` and `[ mcp_servers . scalemax ]` name the same table. */
|
|
74
|
+
function normalizeSection(section) {
|
|
75
|
+
return section.split('.').map(part => part.trim().replace(/^"([^"]*)"$/, '$1').replace(/^'([^']*)'$/, '$1')).join('.');
|
|
76
|
+
}
|
|
77
|
+
function isConnectorsSection(section) {
|
|
78
|
+
const name = normalizeSection(section);
|
|
79
|
+
return name === mcpTable || name.startsWith(`${mcpTable}.`);
|
|
80
|
+
}
|
|
81
|
+
function tomlBasicString(raw) {
|
|
82
|
+
try {
|
|
83
|
+
return JSON.parse(raw);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Who owns the `scalemax` MCP server: nobody, this CLI (our URL AND our
|
|
91
|
+
* headers helper), or the user (anything else, e.g. a table set up by hand
|
|
92
|
+
* with `bearer_token_env_var`, or an inline/dotted definition).
|
|
93
|
+
*/
|
|
94
|
+
export function codexConnectorsOwnership(existing) {
|
|
67
95
|
let section = '';
|
|
68
|
-
let
|
|
96
|
+
let seen = false;
|
|
97
|
+
let url;
|
|
98
|
+
let helper;
|
|
69
99
|
for (const raw of existing.split(/\r?\n/)) {
|
|
70
100
|
const line = raw.trim();
|
|
71
101
|
const sectionMatch = line.match(/^\[([^\]]+)\]$/);
|
|
72
102
|
if (sectionMatch) {
|
|
73
103
|
section = sectionMatch[1];
|
|
74
|
-
|
|
75
|
-
|
|
104
|
+
if (normalizeSection(section) === mcpTable)
|
|
105
|
+
seen = true;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const name = normalizeSection(section);
|
|
109
|
+
if (name === mcpTable) {
|
|
110
|
+
const value = line.match(/^(url|http_headers_helper)\s*=\s*("(?:[^"\\]|\\.)*")\s*(?:#.*)?$/);
|
|
111
|
+
if (value?.[1] === 'url')
|
|
112
|
+
url = tomlBasicString(value[2]);
|
|
113
|
+
if (value?.[1] === 'http_headers_helper')
|
|
114
|
+
helper = tomlBasicString(value[2]);
|
|
115
|
+
}
|
|
116
|
+
// `scalemax = { ... }` under [mcp_servers], or a dotted key at the top level.
|
|
117
|
+
if (name === 'mcp_servers' && new RegExp(`^["']?${CONNECTORS_CODEX_NAME}["']?\\s*[.=]`).test(line))
|
|
118
|
+
return 'user';
|
|
119
|
+
if (!section && new RegExp(`^mcp_servers\\s*\\.\\s*["']?${CONNECTORS_CODEX_NAME}["']?\\s*[.=]`).test(line))
|
|
120
|
+
return 'user';
|
|
121
|
+
}
|
|
122
|
+
if (!seen)
|
|
123
|
+
return 'absent';
|
|
124
|
+
return url === CONNECTORS_MCP_URL && isConnectorsHelperReference(helper) ? 'ours' : 'user';
|
|
125
|
+
}
|
|
126
|
+
export function mergeCodexConfig(existing, baseUrl, model = fallbackModel, authHash, keyHash, connectorsTable) {
|
|
127
|
+
const connectors = codexConnectorsOwnership(existing);
|
|
128
|
+
// The user's own top-level keys stay ABOVE the first table header. Kept
|
|
129
|
+
// after `[model_providers.scalemax]` they would silently become keys of
|
|
130
|
+
// that table (and the next one setup writes).
|
|
131
|
+
const top = [];
|
|
132
|
+
const tables = [];
|
|
133
|
+
let section = '';
|
|
134
|
+
let skip = false;
|
|
135
|
+
for (const raw of existing.split(/\r?\n/)) {
|
|
136
|
+
const line = raw.trim();
|
|
137
|
+
const sectionMatch = line.match(/^\[\[?([^\]]+)\]\]?$/);
|
|
138
|
+
if (sectionMatch) {
|
|
139
|
+
section = sectionMatch[1];
|
|
140
|
+
// Our `[mcp_servers.scalemax]` is rewritten; its subtables are kept.
|
|
141
|
+
skip = isScaleMaxProviderSection(section) || (connectors === 'ours' && normalizeSection(section) === mcpTable);
|
|
142
|
+
if (skip)
|
|
76
143
|
continue;
|
|
77
144
|
}
|
|
78
|
-
if (
|
|
145
|
+
if (skip)
|
|
79
146
|
continue;
|
|
80
147
|
if (!section && managedTopLevelKey.test(line))
|
|
81
148
|
continue;
|
|
@@ -83,10 +150,12 @@ export function mergeCodexConfig(existing, baseUrl, model = fallbackModel, authH
|
|
|
83
150
|
// setup stacked one more copy of it into the preserved tail.
|
|
84
151
|
if (isManagedCommentLine(line))
|
|
85
152
|
continue;
|
|
86
|
-
|
|
153
|
+
(section ? tables : top).push(raw);
|
|
87
154
|
}
|
|
88
|
-
const
|
|
89
|
-
|
|
155
|
+
const userTop = top.join('\n').trim();
|
|
156
|
+
const userTables = tables.join('\n').trim();
|
|
157
|
+
const mcp = connectorsTable && connectors !== 'user' ? `\n${connectorsTable}` : '';
|
|
158
|
+
return `${scalemaxCodexTop(model, authHash, keyHash)}${userTop ? `${userTop}\n` : ''}\n${scalemaxProviderTable(baseUrl)}${mcp}${userTables ? `\n${userTables}\n` : ''}`;
|
|
90
159
|
}
|
|
91
160
|
/**
|
|
92
161
|
* Take ScaleMax OUT of a config.toml, keeping everything else the user has --
|
|
@@ -97,13 +166,15 @@ export function mergeCodexConfig(existing, baseUrl, model = fallbackModel, authH
|
|
|
97
166
|
* Codex rewrite that drops comments still leaves `model_provider = "scalemax"`
|
|
98
167
|
* and the `[model_providers.scalemax]` table, and those must go. The three
|
|
99
168
|
* top-level keys are removed only while ScaleMax is still the provider; if the
|
|
100
|
-
* user switched provider after setup they are the user's.
|
|
169
|
+
* user switched provider after setup they are the user's. The ScaleMax
|
|
170
|
+
* Connectors table goes only when it is ours (our URL and our helper).
|
|
101
171
|
*/
|
|
102
172
|
export function stripScaleMaxCodexConfig(existing) {
|
|
103
173
|
const lines = existing.split(/\r?\n/);
|
|
174
|
+
const connectorsOurs = codexConnectorsOwnership(existing) === 'ours';
|
|
104
175
|
let section = '';
|
|
105
176
|
let topProvider;
|
|
106
|
-
let found =
|
|
177
|
+
let found = connectorsOurs;
|
|
107
178
|
for (const raw of lines) {
|
|
108
179
|
const line = raw.trim();
|
|
109
180
|
const sectionMatch = line.match(/^\[([^\]]+)\]$/);
|
|
@@ -134,7 +205,7 @@ export function stripScaleMaxCodexConfig(existing) {
|
|
|
134
205
|
const sectionMatch = line.match(/^\[([^\]]+)\]$/);
|
|
135
206
|
if (sectionMatch) {
|
|
136
207
|
section = sectionMatch[1];
|
|
137
|
-
skip = isScaleMaxProviderSection(section);
|
|
208
|
+
skip = isScaleMaxProviderSection(section) || (connectorsOurs && isConnectorsSection(section));
|
|
138
209
|
if (skip)
|
|
139
210
|
continue;
|
|
140
211
|
}
|
|
@@ -307,6 +378,25 @@ async function removeCodexAuth(file, ctx, ownership) {
|
|
|
307
378
|
message: original ? 'removed the ScaleMax key and restored your previous sign-in' : 'removed the ScaleMax key',
|
|
308
379
|
};
|
|
309
380
|
}
|
|
381
|
+
/**
|
|
382
|
+
* ScaleMax Connectors are optional for Codex itself, so problems are warnings:
|
|
383
|
+
* a missing table (config from an older CLI), or a helper / key file that is
|
|
384
|
+
* gone or holds a different key than the one being verified.
|
|
385
|
+
*/
|
|
386
|
+
async function codexConnectorsWarnings(configText, ctx) {
|
|
387
|
+
const ownership = codexConnectorsOwnership(configText);
|
|
388
|
+
if (ownership === 'user')
|
|
389
|
+
return [];
|
|
390
|
+
if (ownership === 'absent')
|
|
391
|
+
return ['ScaleMax Connectors are not set up for Codex. Run `npx scalemax@latest update` to add them.'];
|
|
392
|
+
const helper = connectorsHelperPath(ctx.home, ctx.platform);
|
|
393
|
+
if (!(await fs.pathExists(helper)))
|
|
394
|
+
return [`The ScaleMax Connectors headers helper ${helper} is missing. Run \`npx scalemax@latest update\`.`];
|
|
395
|
+
const key = await fs.readFile(connectorsKeyPath(ctx.home), 'utf8').catch(() => '');
|
|
396
|
+
if (key.trim() !== ctx.apiKey.trim())
|
|
397
|
+
return ['ScaleMax Connectors in Codex use a different ScaleMax key than this one. Run `npx scalemax@latest update` to use this key.'];
|
|
398
|
+
return [];
|
|
399
|
+
}
|
|
310
400
|
export async function verifyCodexConfiguration(ctx) {
|
|
311
401
|
const configPath = codexConfigPath(ctx.home);
|
|
312
402
|
const authPath = codexAuthPath(ctx.home);
|
|
@@ -355,6 +445,7 @@ export async function verifyCodexConfiguration(ctx) {
|
|
|
355
445
|
errors.push('Codex auth.json missing auth_mode="apikey"');
|
|
356
446
|
if (auth.OPENAI_API_KEY !== ctx.apiKey)
|
|
357
447
|
errors.push('Codex auth.json missing the selected ScaleMax API key');
|
|
448
|
+
warnings.push(...await codexConnectorsWarnings(configText, ctx));
|
|
358
449
|
for (const file of [configPath, authPath]) {
|
|
359
450
|
try {
|
|
360
451
|
if (!(await modeIsPrivate(file, ctx.platform)))
|
|
@@ -435,7 +526,9 @@ export async function configure(ctx) {
|
|
|
435
526
|
const configPath = codexConfigPath(ctx.home);
|
|
436
527
|
const authPath = codexAuthPath(ctx.home);
|
|
437
528
|
const backups = [];
|
|
438
|
-
|
|
529
|
+
// The ScaleMax Connectors helper and key file are part of this attempt: a
|
|
530
|
+
// verification failure rolls them back with config.toml and auth.json.
|
|
531
|
+
const snapshots = await captureFileSnapshots([configPath, authPath, connectorsHelperPath(ctx.home, ctx.platform), connectorsKeyPath(ctx.home)]);
|
|
439
532
|
const originalConfig = snapshots.find(snapshot => snapshot.file === configPath)?.content || '';
|
|
440
533
|
const originalAuth = snapshots.find(snapshot => snapshot.file === authPath)?.content || '';
|
|
441
534
|
await fs.ensureDir(path.dirname(configPath));
|
|
@@ -445,12 +538,25 @@ export async function configure(ctx) {
|
|
|
445
538
|
}
|
|
446
539
|
catch { }
|
|
447
540
|
const nextAuth = codexAuth(ctx.apiKey, existingAuth);
|
|
448
|
-
|
|
449
|
-
|
|
541
|
+
// A key the helper cannot print safely just means no connectors; the model setup still proceeds.
|
|
542
|
+
let connectorsKey;
|
|
543
|
+
try {
|
|
544
|
+
connectorsKey = connectorsKeyOrThrow(ctx.apiKey);
|
|
545
|
+
}
|
|
546
|
+
catch {
|
|
547
|
+
connectorsKey = undefined;
|
|
548
|
+
}
|
|
549
|
+
const connectorsWanted = connectorsKey !== undefined && codexConnectorsOwnership(originalConfig) !== 'user';
|
|
550
|
+
const nextConfig = mergeCodexConfig(originalConfig, ctx.baseUrl, selectedModel(ctx), contentSha256(nextAuth), contentSha256(ctx.apiKey), connectorsWanted ? codexConnectorsTable(ctx.home, ctx.platform) : undefined);
|
|
551
|
+
const filesChanged = originalConfig !== nextConfig || originalAuth !== nextAuth;
|
|
552
|
+
let changed = filesChanged;
|
|
450
553
|
const alreadyManaged = originalConfig.includes(GENERATED_HEADER);
|
|
451
554
|
let verification;
|
|
452
555
|
try {
|
|
453
|
-
|
|
556
|
+
// The helper must exist before config.toml names it.
|
|
557
|
+
if (connectorsWanted && connectorsKey)
|
|
558
|
+
changed = (await ensureConnectorsHelper(ctx.home, ctx.platform, connectorsKey)).changed || changed;
|
|
559
|
+
if (filesChanged) {
|
|
454
560
|
// Preserve only the first pre-ScaleMax pair. Repeated setup must never
|
|
455
561
|
// make a generated credential the "original" restored by remove().
|
|
456
562
|
if (!alreadyManaged) {
|
|
@@ -472,7 +578,7 @@ export async function configure(ctx) {
|
|
|
472
578
|
throw new Error(`Codex configuration verification failed:\n${verification.errors.map(e => `- ${e}`).join('\n')}`);
|
|
473
579
|
}
|
|
474
580
|
catch (error) {
|
|
475
|
-
if (changed) {
|
|
581
|
+
if (changed || connectorsWanted) {
|
|
476
582
|
try {
|
|
477
583
|
await restoreFileSnapshots(snapshots, ctx.platform);
|
|
478
584
|
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ScaleMax Connectors: ONE remote MCP server (Streamable HTTP) that re-exposes
|
|
3
|
+
* every app the customer connected once at the dashboard. It authenticates
|
|
4
|
+
* with the customer's ScaleMax key as `Authorization: Bearer <key>`.
|
|
5
|
+
*
|
|
6
|
+
* The key never goes into a client's config file. Each client gets a small
|
|
7
|
+
* headers helper that prints the header from a private key file:
|
|
8
|
+
* Claude Desktop managedMcpServers[].headersHelper (absolute executable path)
|
|
9
|
+
* Claude Code mcpServers.<name>.headersHelper (shell command)
|
|
10
|
+
* Codex mcp_servers.<name>.http_headers_helper (shell command: sh -c / cmd /C)
|
|
11
|
+
* Re-running setup with a new key only rewrites the key file.
|
|
12
|
+
*/
|
|
13
|
+
export declare const CONNECTORS_MCP_URL = "https://api.scalemax.pro/mcp";
|
|
14
|
+
export declare const CONNECTORS_DASHBOARD_URL = "https://dashboard.scalemax.pro/connectors";
|
|
15
|
+
export declare const CONNECTORS_DESKTOP_NAME = "ScaleMax Connectors";
|
|
16
|
+
export declare const CONNECTORS_CLAUDE_CODE_NAME = "scalemax-connectors";
|
|
17
|
+
export declare const CONNECTORS_CODEX_NAME = "scalemax";
|
|
18
|
+
/** Desktop re-runs the helper on this schedule and on any 401/403; the key is long-lived. */
|
|
19
|
+
export declare const CONNECTORS_HELPER_TTL_SEC = 3600;
|
|
20
|
+
export declare function connectorsKeyPath(home: string): string;
|
|
21
|
+
export declare function connectorsHelperPath(home: string, platform: NodeJS.Platform): string;
|
|
22
|
+
export declare function connectorsStatePath(home: string): string;
|
|
23
|
+
/** True when a helper value (path or shell command) points at the helper this CLI writes. */
|
|
24
|
+
export declare function isConnectorsHelperReference(value: unknown): boolean;
|
|
25
|
+
/** The helper script. It reads the key file at run time, so the key is never part of the script. */
|
|
26
|
+
export declare function connectorsHelperScript(keyFile: string, platform: NodeJS.Platform): string;
|
|
27
|
+
/**
|
|
28
|
+
* The helper as a shell command for Claude Code's `headersHelper`.
|
|
29
|
+
* Unix: the quoted script path. Windows: Claude Code's helper shell is not
|
|
30
|
+
* fixed (cmd, Git Bash or PowerShell), so — like the Claude Code apiKeyHelper
|
|
31
|
+
* this CLI writes — go through `powershell -NoProfile -Command`, which all three
|
|
32
|
+
* run the same way.
|
|
33
|
+
*/
|
|
34
|
+
export declare function claudeCodeConnectorsHelperCommand(home: string, platform: NodeJS.Platform): string;
|
|
35
|
+
/** The helper as a shell command for Codex's `http_headers_helper` (`sh -c` / `cmd.exe /Q /D /C`). */
|
|
36
|
+
export declare function codexConnectorsHelperCommand(home: string, platform: NodeJS.Platform): string;
|
|
37
|
+
/** Validate the key for the helper files without ever echoing it. */
|
|
38
|
+
export declare function connectorsKeyOrThrow(apiKey: string): string;
|
|
39
|
+
/** Write (or refresh) the private key file and the helper script. Returns whether either changed. */
|
|
40
|
+
export declare function ensureConnectorsHelper(home: string, platform: NodeJS.Platform, apiKey: string): Promise<{
|
|
41
|
+
changed: boolean;
|
|
42
|
+
helperPath: string;
|
|
43
|
+
keyPath: string;
|
|
44
|
+
}>;
|
|
45
|
+
/** Remove the key file, both helper variants and the ownership record. */
|
|
46
|
+
export declare function removeConnectorsHelper(home: string): Promise<boolean>;
|
|
47
|
+
interface ConnectorsState {
|
|
48
|
+
managedBy: string;
|
|
49
|
+
skipWebFetchPreflight: string[];
|
|
50
|
+
}
|
|
51
|
+
export declare function readConnectorsState(home: string): Promise<ConnectorsState>;
|
|
52
|
+
export declare function recordSkipWebFetchPreflight(home: string, files: string[], platform: NodeJS.Platform): Promise<void>;
|
|
53
|
+
export type ConnectorsEntryChange = 'added' | 'updated' | 'unchanged' | 'kept-user-entry' | 'unreadable';
|
|
54
|
+
export declare function desktopConnectorsEntry(helperPath: string): Record<string, unknown>;
|
|
55
|
+
/** Our Desktop entry: our name, and our URL or our helper. */
|
|
56
|
+
export declare function isOurDesktopConnectorsEntry(value: unknown): boolean;
|
|
57
|
+
/** Add (or refresh) our entry; keep every entry the user has, in order. */
|
|
58
|
+
export declare function withDesktopConnectorsServer(current: Record<string, unknown>, helperPath: string): {
|
|
59
|
+
next: Record<string, unknown>;
|
|
60
|
+
change: ConnectorsEntryChange;
|
|
61
|
+
};
|
|
62
|
+
/** Take out only our entry. The key goes away only when ours was the last entry. */
|
|
63
|
+
export declare function withoutDesktopConnectorsServer(current: Record<string, unknown>): {
|
|
64
|
+
next: Record<string, unknown>;
|
|
65
|
+
changed: boolean;
|
|
66
|
+
};
|
|
67
|
+
export declare function claudeCodeConnectorsServer(home: string, platform: NodeJS.Platform): Record<string, unknown>;
|
|
68
|
+
/** Ours: our URL and our helper. A server the user added by hand (static header) is theirs. */
|
|
69
|
+
export declare function isOurClaudeCodeConnectorsServer(value: unknown): boolean;
|
|
70
|
+
export declare function codexConnectorsTable(home: string, platform: NodeJS.Platform): string;
|
|
71
|
+
export {};
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import fs from 'fs-extra';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { atomicWrite } from '../utils/fs.js';
|
|
4
|
+
import { sanitizeApiKey } from '../utils/apiKey.js';
|
|
5
|
+
/**
|
|
6
|
+
* ScaleMax Connectors: ONE remote MCP server (Streamable HTTP) that re-exposes
|
|
7
|
+
* every app the customer connected once at the dashboard. It authenticates
|
|
8
|
+
* with the customer's ScaleMax key as `Authorization: Bearer <key>`.
|
|
9
|
+
*
|
|
10
|
+
* The key never goes into a client's config file. Each client gets a small
|
|
11
|
+
* headers helper that prints the header from a private key file:
|
|
12
|
+
* Claude Desktop managedMcpServers[].headersHelper (absolute executable path)
|
|
13
|
+
* Claude Code mcpServers.<name>.headersHelper (shell command)
|
|
14
|
+
* Codex mcp_servers.<name>.http_headers_helper (shell command: sh -c / cmd /C)
|
|
15
|
+
* Re-running setup with a new key only rewrites the key file.
|
|
16
|
+
*/
|
|
17
|
+
export const CONNECTORS_MCP_URL = 'https://api.scalemax.pro/mcp';
|
|
18
|
+
export const CONNECTORS_DASHBOARD_URL = 'https://dashboard.scalemax.pro/connectors';
|
|
19
|
+
export const CONNECTORS_DESKTOP_NAME = 'ScaleMax Connectors';
|
|
20
|
+
export const CONNECTORS_CLAUDE_CODE_NAME = 'scalemax-connectors';
|
|
21
|
+
export const CONNECTORS_CODEX_NAME = 'scalemax';
|
|
22
|
+
/** Desktop re-runs the helper on this schedule and on any 401/403; the key is long-lived. */
|
|
23
|
+
export const CONNECTORS_HELPER_TTL_SEC = 3600;
|
|
24
|
+
// ScaleMax keys are `sm_` plus URL-safe characters. Anything outside this set
|
|
25
|
+
// could break the JSON the helpers print or the batch file that echoes it.
|
|
26
|
+
const KEY_SHAPE = /^[A-Za-z0-9._~+/=-]+$/;
|
|
27
|
+
// Our helper, whichever platform wrote it. Used to recognise our own entries.
|
|
28
|
+
const OUR_HELPER = /[\\/]\.scalemax[\\/]connectors-headers\.(?:sh|cmd)\b/;
|
|
29
|
+
const MANAGED_BY = 'ScaleMax CLI';
|
|
30
|
+
export function connectorsKeyPath(home) {
|
|
31
|
+
return path.join(home, '.scalemax', 'connectors.key');
|
|
32
|
+
}
|
|
33
|
+
export function connectorsHelperPath(home, platform) {
|
|
34
|
+
return path.join(home, '.scalemax', platform === 'win32' ? 'connectors-headers.cmd' : 'connectors-headers.sh');
|
|
35
|
+
}
|
|
36
|
+
export function connectorsStatePath(home) {
|
|
37
|
+
return path.join(home, '.scalemax', 'connectors-state.json');
|
|
38
|
+
}
|
|
39
|
+
/** True when a helper value (path or shell command) points at the helper this CLI writes. */
|
|
40
|
+
export function isConnectorsHelperReference(value) {
|
|
41
|
+
return typeof value === 'string' && OUR_HELPER.test(value);
|
|
42
|
+
}
|
|
43
|
+
function shSingleQuote(value) {
|
|
44
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
45
|
+
}
|
|
46
|
+
/** The helper script. It reads the key file at run time, so the key is never part of the script. */
|
|
47
|
+
export function connectorsHelperScript(keyFile, platform) {
|
|
48
|
+
if (platform === 'win32') {
|
|
49
|
+
// A literal % in a batch file is written %%. Windows paths cannot contain ".
|
|
50
|
+
const file = keyFile.replace(/%/g, '%%');
|
|
51
|
+
return [
|
|
52
|
+
'@echo off',
|
|
53
|
+
'rem ScaleMax managed configuration: ScaleMax Connectors headers helper.',
|
|
54
|
+
'rem Prints the Authorization header for the ScaleMax Connectors MCP server.',
|
|
55
|
+
'rem The key is read from a private file at run time and is never stored here.',
|
|
56
|
+
'setlocal EnableExtensions DisableDelayedExpansion',
|
|
57
|
+
'set "SCALEMAX_CONNECTORS_KEY="',
|
|
58
|
+
`if exist "${file}" set /p SCALEMAX_CONNECTORS_KEY=<"${file}"`,
|
|
59
|
+
'if not defined SCALEMAX_CONNECTORS_KEY (',
|
|
60
|
+
' echo ScaleMax Connectors: no ScaleMax key found. Run npx scalemax@latest claude-tools 1>&2',
|
|
61
|
+
' exit /b 1',
|
|
62
|
+
')',
|
|
63
|
+
'echo {"Authorization":"Bearer %SCALEMAX_CONNECTORS_KEY%"}',
|
|
64
|
+
'',
|
|
65
|
+
].join('\r\n');
|
|
66
|
+
}
|
|
67
|
+
return [
|
|
68
|
+
'#!/bin/sh',
|
|
69
|
+
'# ScaleMax managed configuration: ScaleMax Connectors headers helper.',
|
|
70
|
+
'# Prints the Authorization header for the ScaleMax Connectors MCP server.',
|
|
71
|
+
'# The key is read from a private file at run time and is never stored here.',
|
|
72
|
+
`key_file=${shSingleQuote(keyFile)}`,
|
|
73
|
+
"key=''",
|
|
74
|
+
'[ -r "$key_file" ] && IFS= read -r key < "$key_file"',
|
|
75
|
+
'case "$key" in',
|
|
76
|
+
" ''|*[!A-Za-z0-9._~+/=-]*)",
|
|
77
|
+
" echo 'ScaleMax Connectors: no valid ScaleMax key found. Run npx scalemax@latest claude-tools' >&2",
|
|
78
|
+
' exit 1 ;;',
|
|
79
|
+
'esac',
|
|
80
|
+
`printf '{"Authorization":"Bearer %s"}\\n' "$key"`,
|
|
81
|
+
'',
|
|
82
|
+
].join('\n');
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The helper as a shell command for Claude Code's `headersHelper`.
|
|
86
|
+
* Unix: the quoted script path. Windows: Claude Code's helper shell is not
|
|
87
|
+
* fixed (cmd, Git Bash or PowerShell), so — like the Claude Code apiKeyHelper
|
|
88
|
+
* this CLI writes — go through `powershell -NoProfile -Command`, which all three
|
|
89
|
+
* run the same way.
|
|
90
|
+
*/
|
|
91
|
+
export function claudeCodeConnectorsHelperCommand(home, platform) {
|
|
92
|
+
const helper = connectorsHelperPath(home, platform);
|
|
93
|
+
if (platform === 'win32')
|
|
94
|
+
return `powershell -NoProfile -Command "& '${helper.replace(/'/g, "''")}'"`;
|
|
95
|
+
return shSingleQuote(helper);
|
|
96
|
+
}
|
|
97
|
+
/** The helper as a shell command for Codex's `http_headers_helper` (`sh -c` / `cmd.exe /Q /D /C`). */
|
|
98
|
+
export function codexConnectorsHelperCommand(home, platform) {
|
|
99
|
+
const helper = connectorsHelperPath(home, platform);
|
|
100
|
+
if (platform === 'win32')
|
|
101
|
+
return `"${helper}"`;
|
|
102
|
+
return shSingleQuote(helper);
|
|
103
|
+
}
|
|
104
|
+
/** Validate the key for the helper files without ever echoing it. */
|
|
105
|
+
export function connectorsKeyOrThrow(apiKey) {
|
|
106
|
+
const key = sanitizeApiKey(apiKey);
|
|
107
|
+
if (!key || !KEY_SHAPE.test(key))
|
|
108
|
+
throw new Error('The ScaleMax API key has an unexpected format, so ScaleMax Connectors were not configured.');
|
|
109
|
+
return key;
|
|
110
|
+
}
|
|
111
|
+
/** Write (or refresh) the private key file and the helper script. Returns whether either changed. */
|
|
112
|
+
export async function ensureConnectorsHelper(home, platform, apiKey) {
|
|
113
|
+
const key = connectorsKeyOrThrow(apiKey);
|
|
114
|
+
const keyPath = connectorsKeyPath(home);
|
|
115
|
+
const helperPath = connectorsHelperPath(home, platform);
|
|
116
|
+
const script = connectorsHelperScript(keyPath, platform);
|
|
117
|
+
const dir = path.dirname(keyPath);
|
|
118
|
+
await fs.ensureDir(dir, 0o700);
|
|
119
|
+
await fs.chmod(dir, 0o700).catch(() => undefined);
|
|
120
|
+
let changed = false;
|
|
121
|
+
// No trailing newline: `set /p` and `read -r` both take the whole file.
|
|
122
|
+
if ((await fs.readFile(keyPath, 'utf8').catch(() => undefined)) !== key) {
|
|
123
|
+
await atomicWrite(keyPath, key, 0o600, platform);
|
|
124
|
+
changed = true;
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
await fs.chmod(keyPath, 0o600).catch(() => undefined);
|
|
128
|
+
}
|
|
129
|
+
if ((await fs.readFile(helperPath, 'utf8').catch(() => undefined)) !== script) {
|
|
130
|
+
await atomicWrite(helperPath, script, 0o700, platform);
|
|
131
|
+
changed = true;
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
await fs.chmod(helperPath, 0o700).catch(() => undefined);
|
|
135
|
+
}
|
|
136
|
+
return { changed, helperPath, keyPath };
|
|
137
|
+
}
|
|
138
|
+
async function removeRegularFile(file) {
|
|
139
|
+
const stat = await fs.lstat(file).catch(() => undefined);
|
|
140
|
+
if (!stat)
|
|
141
|
+
return false;
|
|
142
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
143
|
+
throw new Error(`Refusing to remove non-regular ScaleMax file: ${file}`);
|
|
144
|
+
await fs.remove(file);
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
/** Remove the key file, both helper variants and the ownership record. */
|
|
148
|
+
export async function removeConnectorsHelper(home) {
|
|
149
|
+
let removed = false;
|
|
150
|
+
for (const file of [
|
|
151
|
+
connectorsKeyPath(home),
|
|
152
|
+
path.join(home, '.scalemax', 'connectors-headers.sh'),
|
|
153
|
+
path.join(home, '.scalemax', 'connectors-headers.cmd'),
|
|
154
|
+
connectorsStatePath(home),
|
|
155
|
+
]) {
|
|
156
|
+
if (await removeRegularFile(file))
|
|
157
|
+
removed = true;
|
|
158
|
+
}
|
|
159
|
+
return removed;
|
|
160
|
+
}
|
|
161
|
+
export async function readConnectorsState(home) {
|
|
162
|
+
try {
|
|
163
|
+
const value = await fs.readJson(connectorsStatePath(home));
|
|
164
|
+
const files = Array.isArray(value?.skipWebFetchPreflight) ? value.skipWebFetchPreflight.filter((item) => typeof item === 'string') : [];
|
|
165
|
+
return { managedBy: MANAGED_BY, skipWebFetchPreflight: files };
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return { managedBy: MANAGED_BY, skipWebFetchPreflight: [] };
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
export async function recordSkipWebFetchPreflight(home, files, platform) {
|
|
172
|
+
if (!files.length)
|
|
173
|
+
return;
|
|
174
|
+
const state = await readConnectorsState(home);
|
|
175
|
+
const next = [...new Set([...state.skipWebFetchPreflight, ...files])];
|
|
176
|
+
if (next.length === state.skipWebFetchPreflight.length)
|
|
177
|
+
return;
|
|
178
|
+
await fs.ensureDir(path.dirname(connectorsStatePath(home)), 0o700);
|
|
179
|
+
await atomicWrite(connectorsStatePath(home), JSON.stringify({ managedBy: MANAGED_BY, skipWebFetchPreflight: next }, null, 2) + '\n', 0o600, platform);
|
|
180
|
+
}
|
|
181
|
+
export function desktopConnectorsEntry(helperPath) {
|
|
182
|
+
return {
|
|
183
|
+
name: CONNECTORS_DESKTOP_NAME,
|
|
184
|
+
transport: 'http',
|
|
185
|
+
url: CONNECTORS_MCP_URL,
|
|
186
|
+
headersHelper: helperPath,
|
|
187
|
+
headersHelperTtlSec: CONNECTORS_HELPER_TTL_SEC,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
function asRecord(value) {
|
|
191
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
192
|
+
}
|
|
193
|
+
/** Our Desktop entry: our name, and our URL or our helper. */
|
|
194
|
+
export function isOurDesktopConnectorsEntry(value) {
|
|
195
|
+
const entry = asRecord(value);
|
|
196
|
+
return entry.name === CONNECTORS_DESKTOP_NAME && (entry.url === CONNECTORS_MCP_URL || isConnectorsHelperReference(entry.headersHelper));
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* managedMcpServers is a whole JSON document in one key: a native array in the
|
|
200
|
+
* local configuration file, or the same array encoded as a string (the portable
|
|
201
|
+
* form a profile uses). Read either, and write back in the encoding found.
|
|
202
|
+
*/
|
|
203
|
+
function readManagedServers(value) {
|
|
204
|
+
if (value === undefined)
|
|
205
|
+
return { servers: [], encoding: 'array' };
|
|
206
|
+
if (Array.isArray(value))
|
|
207
|
+
return { servers: [...value], encoding: 'array' };
|
|
208
|
+
if (typeof value === 'string') {
|
|
209
|
+
if (!value.trim())
|
|
210
|
+
return { servers: [], encoding: 'string' };
|
|
211
|
+
try {
|
|
212
|
+
const parsed = JSON.parse(value);
|
|
213
|
+
if (Array.isArray(parsed))
|
|
214
|
+
return { servers: parsed, encoding: 'string' };
|
|
215
|
+
}
|
|
216
|
+
catch { /* unreadable: leave it alone */ }
|
|
217
|
+
}
|
|
218
|
+
return undefined;
|
|
219
|
+
}
|
|
220
|
+
function writeManagedServers(servers, encoding) {
|
|
221
|
+
return encoding === 'string' ? JSON.stringify(servers) : servers;
|
|
222
|
+
}
|
|
223
|
+
function sameJson(a, b) {
|
|
224
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
225
|
+
}
|
|
226
|
+
/** Add (or refresh) our entry; keep every entry the user has, in order. */
|
|
227
|
+
export function withDesktopConnectorsServer(current, helperPath) {
|
|
228
|
+
const parsed = readManagedServers(current.managedMcpServers);
|
|
229
|
+
if (!parsed)
|
|
230
|
+
return { next: current, change: 'unreadable' };
|
|
231
|
+
const desired = desktopConnectorsEntry(helperPath);
|
|
232
|
+
const servers = parsed.servers;
|
|
233
|
+
const named = servers.findIndex(server => asRecord(server).name === CONNECTORS_DESKTOP_NAME);
|
|
234
|
+
if (named >= 0) {
|
|
235
|
+
if (!isOurDesktopConnectorsEntry(servers[named]))
|
|
236
|
+
return { next: current, change: 'kept-user-entry' };
|
|
237
|
+
if (sameJson(servers[named], desired))
|
|
238
|
+
return { next: current, change: 'unchanged' };
|
|
239
|
+
servers[named] = desired;
|
|
240
|
+
return { next: { ...current, managedMcpServers: writeManagedServers(servers, parsed.encoding) }, change: 'updated' };
|
|
241
|
+
}
|
|
242
|
+
// The user already deployed this server under a name of their own.
|
|
243
|
+
if (servers.some(server => asRecord(server).url === CONNECTORS_MCP_URL))
|
|
244
|
+
return { next: current, change: 'kept-user-entry' };
|
|
245
|
+
servers.push(desired);
|
|
246
|
+
return { next: { ...current, managedMcpServers: writeManagedServers(servers, parsed.encoding) }, change: 'added' };
|
|
247
|
+
}
|
|
248
|
+
/** Take out only our entry. The key goes away only when ours was the last entry. */
|
|
249
|
+
export function withoutDesktopConnectorsServer(current) {
|
|
250
|
+
const parsed = readManagedServers(current.managedMcpServers);
|
|
251
|
+
if (!parsed || current.managedMcpServers === undefined)
|
|
252
|
+
return { next: current, changed: false };
|
|
253
|
+
const kept = parsed.servers.filter(server => !isOurDesktopConnectorsEntry(server));
|
|
254
|
+
if (kept.length === parsed.servers.length)
|
|
255
|
+
return { next: current, changed: false };
|
|
256
|
+
const next = { ...current };
|
|
257
|
+
if (kept.length)
|
|
258
|
+
next.managedMcpServers = writeManagedServers(kept, parsed.encoding);
|
|
259
|
+
else
|
|
260
|
+
delete next.managedMcpServers;
|
|
261
|
+
return { next, changed: true };
|
|
262
|
+
}
|
|
263
|
+
// ---------------------------------------------------------------------------
|
|
264
|
+
// Claude Code user-scope MCP server (~/.claude.json mcpServers).
|
|
265
|
+
export function claudeCodeConnectorsServer(home, platform) {
|
|
266
|
+
return { type: 'http', url: CONNECTORS_MCP_URL, headersHelper: claudeCodeConnectorsHelperCommand(home, platform) };
|
|
267
|
+
}
|
|
268
|
+
/** Ours: our URL and our helper. A server the user added by hand (static header) is theirs. */
|
|
269
|
+
export function isOurClaudeCodeConnectorsServer(value) {
|
|
270
|
+
const server = asRecord(value);
|
|
271
|
+
return server.url === CONNECTORS_MCP_URL && isConnectorsHelperReference(server.headersHelper);
|
|
272
|
+
}
|
|
273
|
+
// ---------------------------------------------------------------------------
|
|
274
|
+
// Codex config.toml table.
|
|
275
|
+
export function codexConnectorsTable(home, platform) {
|
|
276
|
+
return `[mcp_servers.${CONNECTORS_CODEX_NAME}]\nurl = "${CONNECTORS_MCP_URL}"\nhttp_headers_helper = ${JSON.stringify(codexConnectorsHelperCommand(home, platform))}\ntool_timeout_sec = 90\n`;
|
|
277
|
+
}
|
|
@@ -24,9 +24,12 @@ function providerConfig(ctx) {
|
|
|
24
24
|
tool_call: modelSupportsTools(ctx, modelId),
|
|
25
25
|
limit: {
|
|
26
26
|
context: metadata?.context_window || (modelId.startsWith('claude-') ? 200000 : 128000),
|
|
27
|
+
// The catalog's own output cap. A flat 4096 for every non-Opus model
|
|
28
|
+
// cut DeepSeek V4.1 Flash (393k) replies off at 4k in OpenCode; the
|
|
29
|
+
// gateway enforces the catalog figure, so publishing it is safe.
|
|
27
30
|
output: hasLargeOutputCap(modelId)
|
|
28
31
|
? Math.min(metadata?.max_output_tokens || 128000, 128000)
|
|
29
|
-
:
|
|
32
|
+
: metadata?.max_output_tokens || 4096
|
|
30
33
|
}
|
|
31
34
|
}];
|
|
32
35
|
}));
|
package/dist/index.js
CHANGED
|
@@ -53,7 +53,7 @@ function printHelp(command) {
|
|
|
53
53
|
console.log('Usage: scalemax fix-roo [--undo]\n\nFix Roo Code tasks stuck at "API Request…" on recent VS Code versions ("Could not find ripgrep binary").\nPatches the installed Roo Code extension in your home folder (VS Code, Insiders, Cursor, Windsurf,\nVSCodium, Trae, Kiro, and remote servers) so it finds VS Code\'s relocated ripgrep. The VS Code app\nitself is not changed. The original extension file is kept next to it as extension.js.scalemax-orig.\nReload VS Code (Developer: Reload Window) afterwards.\n\n --undo Restore the original Roo Code extension files');
|
|
54
54
|
return;
|
|
55
55
|
}
|
|
56
|
-
const details = { update: 'Revalidate the API key and reconfigure every detected client.', remove: 'Restore backups or remove only ScaleMax-managed client configuration.', doctor: 'Validate the API key and verify detected client configuration.', models: 'List models available to the stored API key.', login: 'Store or replace the ScaleMax API key.', logout: 'Remove the locally stored ScaleMax API key.', 'claude-tools': 'Install and verify bounded public-GitHub skill tools for Claude Desktop/Cowork and Claude Code.' };
|
|
56
|
+
const details = { update: 'Revalidate the API key and reconfigure every detected client.', remove: 'Restore backups or remove only ScaleMax-managed client configuration.', doctor: 'Validate the API key and verify detected client configuration.', models: 'List models available to the stored API key.', login: 'Store or replace the ScaleMax API key.', logout: 'Remove the locally stored ScaleMax API key.', 'claude-tools': 'Install and verify bounded public-GitHub skill tools and ScaleMax Connectors (apps you connect at dashboard.scalemax.pro/connectors) for Claude Desktop/Cowork and Claude Code.' };
|
|
57
57
|
if (command && details[command]) {
|
|
58
58
|
console.log(`Usage: scalemax ${command}\n\n${details[command]}`);
|
|
59
59
|
return;
|
|
@@ -71,7 +71,7 @@ Commands:
|
|
|
71
71
|
scalemax balance Show remaining balance and how to renew
|
|
72
72
|
scalemax statusline Show your balance in Claude Code's status line
|
|
73
73
|
scalemax helper-bot Execute setup actions or open the ScaleMax Helper
|
|
74
|
-
scalemax claude-tools Install
|
|
74
|
+
scalemax claude-tools Install GitHub skill tools and ScaleMax Connectors for Claude
|
|
75
75
|
scalemax fix-roo Fix Roo Code stuck at "API Request…" (recent VS Code)
|
|
76
76
|
scalemax update Reconfigure detected clients
|
|
77
77
|
scalemax remove Remove ScaleMax-generated configs
|