codemax-pro 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +65 -16
  2. package/index.js +484 -363
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,12 +1,10 @@
1
1
  # ⚡ codemax-pro
2
2
 
3
- The Official 1-Command Setup Tool for **CodeMax** (`api.codemax.pro`).
3
+ The official one-command setup tool for **CodeMax** (`api.codemax.pro`).
4
4
 
5
- Automatically configures **Claude Code CLI**, **VS Code Extension**, and **Claude Desktop App** with high-speed Anthropic-compatible endpoints in under 5 seconds.
5
+ Configures **Claude Code CLI**, the **VS Code extension**, and the **Claude Desktop app** in a few seconds.
6
6
 
7
- ## 🚀 Quick Start
8
-
9
- Run this single command in your terminal:
7
+ ## 🚀 Quick start
10
8
 
11
9
  ```bash
12
10
  npx codemax-pro
@@ -18,25 +16,76 @@ Or pass your API key directly:
18
16
  npx codemax-pro sk-cp-your-key-here
19
17
  ```
20
18
 
19
+ Re-run it any time to update your key.
20
+
21
21
  ---
22
22
 
23
- ## 🛠️ What it Configures:
23
+ ## 🛠️ What it configures
24
24
 
25
- 1. **Validates your CodeMax API key** against `api.codemax.pro`
26
- 2. **Configures Claude Code CLI & VS Code** (`~/.claude/settings.json`)
27
- 3. **Configures Claude Desktop App** (`claude_desktop_config.json`)
28
- 4. **Installs Claude Code CLI globally** if missing (`@anthropic-ai/claude-code`)
29
- 5. **Auto-bypasses onboarding** (`~/.claude.json`)
25
+ 1. **Validates your API key** against `api.codemax.pro` before changing anything
26
+ 2. **Claude Code CLI + VS Code extension** — `~/.claude/settings.json`
27
+ 3. **Claude Desktop** — third-party inference, provider `gateway`
28
+ 4. **Installs Claude Code CLI** if it is missing (`@anthropic-ai/claude-code`)
29
+ 5. Clears stale settings left by older versions
30
30
 
31
31
  ---
32
32
 
33
- ## 🌐 Supported Models:
34
- - `claude-sonnet-5` (Fastest flagship general intelligence)
35
- - `claude-opus-5` (Extreme architectural & complex coding)
36
- - `claude-haiku-4.5` (Ultra-fast turnaround)
37
- - `claude-fable-5` (Extended reasoning & deep problem solving)
33
+ ## 🖥️ About the Claude Desktop app
34
+
35
+ The desktop app is not the CLI. It does not read `~/.claude/settings.json`, and setting
36
+ `ANTHROPIC_BASE_URL` as an environment variable has no effect on it — it is its own application and
37
+ talks to whichever inference endpoint it is configured with.
38
+
39
+ So this tool uses Anthropic's supported **third-party inference** mode, with the provider set to
40
+ `gateway` and pointed at `api.codemax.pro`. It writes to both places the app looks:
41
+
42
+ | Platform | Written to |
43
+ | --- | --- |
44
+ | Windows | `HKCU\SOFTWARE\Policies\Claude` **and** `%LOCALAPPDATA%\Claude-3p\configLibrary\` |
45
+ | macOS | `~/Library/Application Support/Claude-3p/configLibrary/` |
46
+ | Linux | `~/.config/Claude-3p/configLibrary/` |
47
+
48
+ Alongside the endpoint and key it sets the model list, the credential header, the sandbox egress
49
+ allowlist (so tools that fetch from the network keep working), and turns off the WebFetch domain
50
+ preflight — without that last one the app checks every fetched domain against a host this setup
51
+ never otherwise contacts, which fails on a restricted network.
52
+
53
+ > ### ⚠️ Quit the desktop app fully, then reopen it
54
+ > Its configuration is read **once, at launch**. Closing the window leaves the process running, so
55
+ > a reopened window keeps the old settings and it looks like setup did not work. Quit from the
56
+ > system tray (Windows) or the menu bar (macOS) first.
57
+
58
+ ---
59
+
60
+ ## 🌐 Models
61
+
62
+ | Model | Best for |
63
+ | --- | --- |
64
+ | `claude-opus-5` | Complex architecture and hard coding problems |
65
+ | `claude-fable-5` | Extended reasoning, long-running work |
66
+ | `claude-sonnet-5` | Fast, capable general-purpose work |
67
+ | `claude-haiku-4-5` | Quick turnarounds and background tasks |
68
+
69
+ Legacy model names (`claude-opus-4-8`, `claude-sonnet-4-6`, `claude-3-5-sonnet` and friends) are
70
+ accepted too and map onto the current lineup.
71
+
72
+ ---
73
+
74
+ ## 🩹 Troubleshooting
75
+
76
+ **The desktop model picker is empty.** The app was not restarted, or a machine-wide policy is
77
+ overriding your user settings — on Windows, a policy under `HKLM\SOFTWARE\Policies\Claude` makes the
78
+ app ignore the per-user one entirely. The setup tool warns when it finds one.
79
+
80
+ **Requests fail with 401 in the desktop app.** Re-run `npx codemax-pro` with your key; the stored
81
+ credential may be from a rotated key.
82
+
83
+ **The CLI works but the desktop app does not.** They read completely different configuration. Check
84
+ the desktop app under **Help → Troubleshooting → Copy Managed Configuration Report**, which lists
85
+ which keys were detected and where they were read from, with secrets redacted.
38
86
 
39
87
  ---
40
88
 
41
89
  ## 📖 License
90
+
42
91
  MIT © [CodeMax](https://codemax.pro)
package/index.js CHANGED
@@ -1,363 +1,484 @@
1
- #!/usr/bin/env node
2
-
3
- const fs = require("fs");
4
- const path = require("path");
5
- const { execSync } = require("child_process");
6
- const readline = require("readline");
7
- const crypto = require("crypto");
8
-
9
- const API_ENDPOINT = "https://api.codemax.pro";
10
-
11
- // ── Colors ──
12
- const c = {
13
- reset: "\x1b[0m",
14
- bold: "\x1b[1m",
15
- dim: "\x1b[2m",
16
- cyan: "\x1b[36m",
17
- green: "\x1b[32m",
18
- yellow: "\x1b[33m",
19
- red: "\x1b[31m",
20
- gray: "\x1b[90m",
21
- white: "\x1b[97m",
22
- };
23
-
24
- const log = (msg) => console.log(msg);
25
- const ok = (msg) => log(` ${c.green}✓ ${msg}${c.reset}`);
26
- const warn = (msg) => log(` ${c.yellow}⚠ ${msg}${c.reset}`);
27
- const fail = (msg) => log(` ${c.red}✗ ${msg}${c.reset}`);
28
- const info = (msg) => log(` ${c.cyan}${msg}${c.reset}`);
29
- const gray = (msg) => log(` ${c.gray}${msg}${c.reset}`);
30
-
31
- function ask(question) {
32
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
33
- return new Promise((resolve) => {
34
- rl.question(question, (answer) => {
35
- rl.close();
36
- resolve(answer.trim());
37
- });
38
- });
39
- }
40
-
41
- function readJson(filePath) {
42
- try {
43
- if (fs.existsSync(filePath)) {
44
- const raw = fs.readFileSync(filePath, "utf8").trim();
45
- if (!raw) return {};
46
- return JSON.parse(raw);
47
- }
48
- } catch { }
49
- return {};
50
- }
51
-
52
- function writeJson(filePath, data) {
53
- const dir = path.dirname(filePath);
54
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
55
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf8");
56
- }
57
-
58
- function run(cmd) {
59
- try {
60
- return execSync(cmd, { encoding: "utf8", stdio: "pipe" }).trim();
61
- } catch {
62
- return null;
63
- }
64
- }
65
-
66
- function which(cmd) {
67
- try {
68
- const r = execSync(process.platform === "win32" ? `where ${cmd}` : `which ${cmd}`, {
69
- encoding: "utf8",
70
- stdio: "pipe",
71
- }).trim();
72
- return r ? true : false;
73
- } catch {
74
- return false;
75
- }
76
- }
77
-
78
- async function validateKey(apiKey) {
79
- const body = JSON.stringify({
80
- model: "claude-haiku-4.5",
81
- max_tokens: 10,
82
- messages: [{ role: "user", content: "Hi" }],
83
- });
84
-
85
- try {
86
- const res = await fetch(`${API_ENDPOINT}/v1/messages`, {
87
- method: "POST",
88
- headers: {
89
- "Content-Type": "application/json",
90
- "x-api-key": apiKey,
91
- "anthropic-version": "2023-06-01",
92
- },
93
- body,
94
- signal: AbortSignal.timeout(30000),
95
- });
96
-
97
- if (res.ok) return { valid: true };
98
- if (res.status === 429) return { valid: true, rateLimit: true };
99
- if (res.status === 401 || res.status === 403) return { valid: false, reason: "Invalid API key" };
100
- if (res.status === 402) return { valid: false, reason: "No remaining balance" };
101
- return { valid: false, reason: `Server returned ${res.status}` };
102
- } catch (e) {
103
- return { valid: false, reason: e.message, network: true };
104
- }
105
- }
106
-
107
- function configureClaudeDesktop3P(home, apiKey) {
108
- const isWin = process.platform === "win32";
109
- const isMac = process.platform === "darwin";
110
-
111
- // 1. Target Claude-3p/configLibrary
112
- const baseDir = isWin
113
- ? path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "Claude-3p")
114
- : isMac
115
- ? path.join(home, "Library", "Application Support", "Claude-3p")
116
- : path.join(home, ".config", "Claude-3p");
117
-
118
- const configLibDir = path.join(baseDir, "configLibrary");
119
- if (!fs.existsSync(configLibDir)) {
120
- fs.mkdirSync(configLibDir, { recursive: true });
121
- }
122
-
123
- const metaPath = path.join(configLibDir, "_meta.json");
124
- let meta = readJson(metaPath);
125
- if (!meta.entries) meta.entries = [];
126
-
127
- let profileId = meta.appliedId;
128
- if (!profileId || !fs.existsSync(path.join(configLibDir, `${profileId}.json`))) {
129
- profileId = crypto.randomUUID ? crypto.randomUUID() : `codemax-${Date.now()}`;
130
- meta.appliedId = profileId;
131
- meta.entries.push({ id: profileId, name: "CodeMax Gateway" });
132
- }
133
-
134
- const profilePath = path.join(configLibDir, `${profileId}.json`);
135
- const profileData = {
136
- inferenceGatewayBaseUrl: API_ENDPOINT,
137
- inferenceGatewayApiKey: apiKey,
138
- inferenceProvider: "gateway",
139
- inferenceCredentialKind: "static",
140
- };
141
-
142
- writeJson(profilePath, profileData);
143
- writeJson(metaPath, meta);
144
-
145
- // 2. Target developer_settings.json
146
- const devSettingsPath = path.join(baseDir, "developer_settings.json");
147
- const devSettings = readJson(devSettingsPath);
148
- devSettings.allowDevTools = true;
149
- writeJson(devSettingsPath, devSettings);
150
-
151
- // 3. Target claude_desktop_config.json for MCP fallback
152
- const desktopConfigPath = isWin
153
- ? path.join(process.env.APPDATA || path.join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json")
154
- : isMac
155
- ? path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json")
156
- : path.join(home, ".config", "Claude", "claude_desktop_config.json");
157
-
158
- const desktopConfig = readJson(desktopConfigPath);
159
- if (!desktopConfig.env) desktopConfig.env = {};
160
- Object.assign(desktopConfig.env, {
161
- ANTHROPIC_BASE_URL: API_ENDPOINT,
162
- ANTHROPIC_AUTH_TOKEN: apiKey,
163
- ANTHROPIC_API_KEY: apiKey,
164
- });
165
- writeJson(desktopConfigPath, desktopConfig);
166
-
167
- return profilePath;
168
- }
169
-
170
- async function main() {
171
- log("");
172
- log(` ${c.cyan}╔══════════════════════════════════════════╗${c.reset}`);
173
- log(` ${c.cyan}║ ${c.bold}CodeMax Setup${c.reset}${c.cyan} ║${c.reset}`);
174
- log(` ${c.cyan}╚══════════════════════════════════════════╝${c.reset}`);
175
- log("");
176
-
177
- const home = process.env.HOME || process.env.USERPROFILE;
178
- if (!home) {
179
- fail("Cannot determine home directory");
180
- process.exit(1);
181
- }
182
-
183
- // ── Get API Key ──
184
- let apiKey = process.argv[2] || "";
185
- if (!apiKey) {
186
- log(` ${c.white}Enter your CodeMax API key${c.reset}`);
187
- gray("Get it from your admin or codemax.pro");
188
- log("");
189
- apiKey = await ask(` ${c.white}API Key: ${c.reset}`);
190
- log("");
191
- }
192
-
193
- if (!apiKey || apiKey.length < 5) {
194
- fail("No valid API key provided. Exiting.");
195
- process.exit(1);
196
- }
197
-
198
- // ── [1/5] Validate API Key ──
199
- info("[1/5] Validating API key...");
200
- const result = await validateKey(apiKey);
201
-
202
- if (result.valid) {
203
- if (result.rateLimit) {
204
- warn("API key valid but rate-limited. Continuing setup...");
205
- } else {
206
- ok("API key is valid!");
207
- ok("Connected to CodeMax");
208
- }
209
- } else if (result.network) {
210
- warn(`Could not reach server: ${result.reason}`);
211
- const cont = await ask(` ${c.yellow}Continue anyway? (y/n): ${c.reset}`);
212
- if (cont.toLowerCase() !== "y") process.exit(1);
213
- } else {
214
- fail(result.reason);
215
- gray("Make sure you're using a valid CodeMax API key (sk-cp-...)");
216
- process.exit(1);
217
- }
218
- log("");
219
-
220
- // ── [2/5] Check Node.js ──
221
- info("[2/5] Checking Node.js...");
222
- const nodeVer = run("node --version");
223
- if (nodeVer) {
224
- ok(`Node.js ${nodeVer} found`);
225
- } else {
226
- fail("Node.js not found. Install from https://nodejs.org");
227
- process.exit(1);
228
- }
229
- log("");
230
-
231
- // ── [3/5] Configure Claude Code CLI & VS Code settings ──
232
- info("[3/5] Configuring Claude Code CLI & VS Code...");
233
- const settingsPath = path.join(home, ".claude", "settings.json");
234
- try {
235
- const settings = readJson(settingsPath);
236
- if (!settings.env) settings.env = {};
237
-
238
- Object.assign(settings.env, {
239
- ANTHROPIC_AUTH_TOKEN: apiKey,
240
- ANTHROPIC_BASE_URL: API_ENDPOINT,
241
- CLAUDE_CODE_OAUTH_TOKEN: apiKey,
242
- CLAUDE_CODE_SUBSCRIPTION_TYPE: "max",
243
- CLAUDE_CODE_REMOTE: "1",
244
- });
245
-
246
- const removeVars = [
247
- "ANTHROPIC_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "ANTHROPIC_DEFAULT_MODEL",
248
- "ANTHROPIC_REASONING_MODEL",
249
- "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL",
250
- "ANTHROPIC_DEFAULT_HAIKU_MODEL",
251
- ];
252
- for (const v of removeVars) delete settings.env[v];
253
- delete settings.model;
254
-
255
- writeJson(settingsPath, settings);
256
- ok("Claude Code CLI & VS Code Extension configured");
257
- } catch (e) {
258
- fail(`Failed: ${e.message}`);
259
- }
260
- log("");
261
-
262
- // ── [4/5] Configure Claude Desktop App (Third-Party Inference Gateway) ──
263
- info("[4/5] Configuring Claude Desktop App (Inference Gateway)...");
264
- try {
265
- const configuredPath = configureClaudeDesktop3P(home, apiKey);
266
- ok("Claude Desktop Third-Party Gateway configured");
267
- gray(` Config: ${configuredPath}`);
268
- } catch (e) {
269
- warn(`Could not auto-configure Claude Desktop: ${e.message}`);
270
- }
271
- log("");
272
-
273
- // ── Clean up any stale MCP config from prior installs ──
274
- const claudeJsonPath = path.join(home, ".claude.json");
275
- try {
276
- const claudeJson = readJson(claudeJsonPath);
277
- let mutated = false;
278
- if (claudeJson.mcpServers && claudeJson.mcpServers.CodeMax) {
279
- delete claudeJson.mcpServers.CodeMax;
280
- mutated = true;
281
- }
282
- if (mutated) {
283
- if (claudeJson.mcpServers && Object.keys(claudeJson.mcpServers).length === 0) {
284
- delete claudeJson.mcpServers;
285
- }
286
- claudeJson.hasCompletedOnboarding = true;
287
- writeJson(claudeJsonPath, claudeJson);
288
- } else if (!fs.existsSync(claudeJsonPath)) {
289
- writeJson(claudeJsonPath, { hasCompletedOnboarding: true });
290
- }
291
- } catch { /* non-critical */ }
292
-
293
- // ── Clear stale env vars (Windows only) ──
294
- if (process.platform === "win32") {
295
- const staleVars = [
296
- "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL",
297
- "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL",
298
- "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL",
299
- "ANTHROPIC_DEFAULT_HAIKU_MODEL", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
300
- ];
301
- for (const v of staleVars) {
302
- run(`REG delete "HKCU\\Environment" /v ${v} /f`);
303
- }
304
- }
305
-
306
- // ── [5/5] Install Claude Code CLI ──
307
- info("[5/5] Checking Claude Code CLI...");
308
- if (which("claude")) {
309
- ok("Claude Code CLI already installed");
310
- } else {
311
- info("Installing Claude Code CLI...");
312
- const cliResult = run("npm install -g @anthropic-ai/claude-code");
313
- if (cliResult !== null) {
314
- ok("Claude Code CLI installed!");
315
- } else {
316
- warn("Auto-install failed. Run: npm install -g @anthropic-ai/claude-code");
317
- }
318
- }
319
-
320
- // ── Done ──
321
- log("");
322
- log(` ${c.green}╔══════════════════════════════════════════╗${c.reset}`);
323
- log(` ${c.green}║ ${c.bold}✓ Setup complete!${c.reset}${c.green} ║${c.reset}`);
324
- log(` ${c.green}╚══════════════════════════════════════════╝${c.reset}`);
325
- log("");
326
- log(` ${c.white}What was configured:${c.reset}`);
327
- gray(` • API key validated ✓`);
328
- gray(` • Claude Code CLI & VS Code Extension (~/.claude/settings.json)`);
329
- gray(` • Claude Desktop App (Gateway Inference in Claude-3p/configLibrary)`);
330
- gray(` • Claude Code CLI Environment`);
331
- log("");
332
- log(` ${c.gray}╭───────────────────────────────────────╮${c.reset}`);
333
- log(` ${c.gray}│ Gateway: api.codemax.pro │${c.reset}`);
334
- log(` ${c.gray}│ Key: ${apiKey.substring(0, 8)}... │${c.reset}`);
335
- log(` ${c.gray}╰───────────────────────────────────────╯${c.reset}`);
336
- log("");
337
- gray("Restart Claude Code / VS Code / Claude Desktop to apply.");
338
- gray("Re-run anytime to update your key.");
339
- log("");
340
-
341
- // Ask to launch
342
- if (which("claude")) {
343
- const launch = await ask(` ${c.white}Launch Claude Code now? (y/n): ${c.reset}`);
344
- if (launch.toLowerCase() === "y" || launch === "") {
345
- log("");
346
- info("🚀 Launching Claude Code...");
347
- log(` ${c.gray}════════════════════════════════════${c.reset}`);
348
- log("");
349
- try {
350
- execSync("claude", { stdio: "inherit" });
351
- } catch { }
352
- } else {
353
- log("");
354
- log(` ${c.white}To start later, open any terminal and type: claude${c.reset}`);
355
- log("");
356
- }
357
- }
358
- }
359
-
360
- main().catch((e) => {
361
- fail(`Unexpected error: ${e.message}`);
362
- process.exit(1);
363
- });
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { execSync } = require("child_process");
6
+ const readline = require("readline");
7
+ const crypto = require("crypto");
8
+
9
+ const API_ENDPOINT = "https://api.codemax.pro";
10
+
11
+ // ── Colors ──
12
+ const c = {
13
+ reset: "\x1b[0m",
14
+ bold: "\x1b[1m",
15
+ dim: "\x1b[2m",
16
+ cyan: "\x1b[36m",
17
+ green: "\x1b[32m",
18
+ yellow: "\x1b[33m",
19
+ red: "\x1b[31m",
20
+ gray: "\x1b[90m",
21
+ white: "\x1b[97m",
22
+ };
23
+
24
+ const log = (msg) => console.log(msg);
25
+ const ok = (msg) => log(` ${c.green}✓ ${msg}${c.reset}`);
26
+ const warn = (msg) => log(` ${c.yellow}⚠ ${msg}${c.reset}`);
27
+ const fail = (msg) => log(` ${c.red}✗ ${msg}${c.reset}`);
28
+ const info = (msg) => log(` ${c.cyan}${msg}${c.reset}`);
29
+ const gray = (msg) => log(` ${c.gray}${msg}${c.reset}`);
30
+
31
+ function ask(question) {
32
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
33
+ return new Promise((resolve) => {
34
+ rl.question(question, (answer) => {
35
+ rl.close();
36
+ resolve(answer.trim());
37
+ });
38
+ });
39
+ }
40
+
41
+ function readJson(filePath) {
42
+ try {
43
+ if (fs.existsSync(filePath)) {
44
+ const raw = fs.readFileSync(filePath, "utf8").trim();
45
+ if (!raw) return {};
46
+ return JSON.parse(raw);
47
+ }
48
+ } catch { }
49
+ return {};
50
+ }
51
+
52
+ function writeJson(filePath, data) {
53
+ const dir = path.dirname(filePath);
54
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
55
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf8");
56
+ }
57
+
58
+ function run(cmd) {
59
+ try {
60
+ return execSync(cmd, { encoding: "utf8", stdio: "pipe" }).trim();
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ function which(cmd) {
67
+ try {
68
+ const r = execSync(process.platform === "win32" ? `where ${cmd}` : `which ${cmd}`, {
69
+ encoding: "utf8",
70
+ stdio: "pipe",
71
+ }).trim();
72
+ return r ? true : false;
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+
78
+ async function validateKey(apiKey) {
79
+ const body = JSON.stringify({
80
+ model: "claude-haiku-4.5",
81
+ max_tokens: 10,
82
+ messages: [{ role: "user", content: "Hi" }],
83
+ });
84
+
85
+ try {
86
+ const res = await fetch(`${API_ENDPOINT}/v1/messages`, {
87
+ method: "POST",
88
+ headers: {
89
+ "Content-Type": "application/json",
90
+ "x-api-key": apiKey,
91
+ "anthropic-version": "2023-06-01",
92
+ },
93
+ body,
94
+ signal: AbortSignal.timeout(30000),
95
+ });
96
+
97
+ if (res.ok) return { valid: true };
98
+ if (res.status === 429) return { valid: true, rateLimit: true };
99
+ if (res.status === 401 || res.status === 403) return { valid: false, reason: "Invalid API key" };
100
+ if (res.status === 402) return { valid: false, reason: "No remaining balance" };
101
+ return { valid: false, reason: `Server returned ${res.status}` };
102
+ } catch (e) {
103
+ return { valid: false, reason: e.message, network: true };
104
+ }
105
+ }
106
+
107
+ /* ── Claude Desktop, third-party inference ───────────────────────────────────
108
+ *
109
+ * Claude Desktop does NOT read ~/.claude/settings.json, and it does not shell out to the CLI —
110
+ * it is its own app and talks to its configured inference endpoint directly. Setting
111
+ * ANTHROPIC_BASE_URL for it, in any file or as an environment variable, does nothing. The
112
+ * supported route is Anthropic's documented "third-party inference" mode with `inferenceProvider`
113
+ * set to `gateway`, which is exactly what this API already is: the Messages API with streaming
114
+ * and tool use.
115
+ *
116
+ * Two surfaces carry that configuration, and this writes BOTH because they fail differently:
117
+ *
118
+ * 1. OS policy store — the documented, stable surface. On Windows that is the registry under
119
+ * HKCU\SOFTWARE\Policies\Claude with every value a REG_SZ, even booleans and JSON.
120
+ * 2. The app's own local config library. Undocumented in shape, but it is what the in-app
121
+ * "Apply locally" button writes, so it is what makes the setting visible in the UI.
122
+ *
123
+ * The policy store wins if the two ever disagree, which is the right way round.
124
+ */
125
+ const DESKTOP_MODELS = [
126
+ { name: "claude-opus-5" },
127
+ { name: "claude-fable-5" },
128
+ { name: "claude-sonnet-5" },
129
+ { name: "claude-haiku-4-5-20251001" },
130
+ ];
131
+
132
+ /* What the agent's own tools may reach from inside the sandbox — a separate, stricter boundary
133
+ * than the machine's firewall: an unlisted host is refused even when the machine itself can reach
134
+ * it, and the default is nothing at all except the API endpoint.
135
+ *
136
+ * "*" rather than a curated list, deliberately. A first attempt named the usual suspects — GitHub,
137
+ * npm, PyPI, MDN — which is fine right up until someone pastes a link to a blog post, a vendor's
138
+ * docs, or their own staging site, and the fetch fails with no obvious cause. A developer tool
139
+ * cannot know in advance which host the next question is about, and this matches what the same
140
+ * tools do outside this setup.
141
+ *
142
+ * An organisation that wants the sandbox locked down should replace this with its own list; that
143
+ * is a deployment policy decision, and it belongs with whoever manages those machines rather than
144
+ * baked into a one-command installer. */
145
+ const EGRESS_HOSTS = ["*"];
146
+
147
+ function desktopPolicyValues(apiKey) {
148
+ return {
149
+ inferenceProvider: "gateway",
150
+ inferenceGatewayBaseUrl: API_ENDPOINT,
151
+ inferenceGatewayApiKey: apiKey,
152
+ inferenceCredentialKind: "static",
153
+ // This API authenticates with the x-api-key header, as the Messages API does. The key
154
+ // defaults to "bearer", so leaving it out sends the credential in a header this endpoint
155
+ // does not read, and every request comes back 401.
156
+ inferenceGatewayAuthScheme: "x-api-key",
157
+ // Given explicitly rather than left to discovery. The picker's auto-discovery keeps only
158
+ // model IDs it recognises as Claude, so a gateway that renamed anything would show an
159
+ // empty picker with no error to explain it. Full IDs also let the app skip the
160
+ // /v1/models round trip at launch.
161
+ inferenceModels: JSON.stringify(DESKTOP_MODELS),
162
+ // Without this, WebFetch asks api.anthropic.com whether each domain is allowed before
163
+ // fetching it — a hard dependency on a host this deployment otherwise never touches, and
164
+ // one that fails closed on a restricted network.
165
+ skipWebFetchPreflight: "true",
166
+ coworkEgressAllowedHosts: JSON.stringify(EGRESS_HOSTS),
167
+ // Product analytics only. Off because leaving it on also adds api.anthropic.com to the
168
+ // sandbox allowlist so usage telemetry can be delivered from inside it. Crash reporting
169
+ // (disableEssentialTelemetry) is deliberately left ALONE — turning that off opts you into
170
+ // a manual support model where nobody can see failures on your machine.
171
+ disableNonessentialTelemetry: "true",
172
+ };
173
+ }
174
+
175
+ /* .reg escaping: backslashes and quotes are doubled/escaped, and the JSON values here contain
176
+ * plenty of both. Built as a file and imported rather than passed to `reg add`, because the
177
+ * command-line form loses quotes inside JSON to cmd's own parsing and silently stores a
178
+ * truncated value. */
179
+ function writeWindowsPolicy(values) {
180
+ const esc = (s) => String(s).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
181
+ const lines = [
182
+ "Windows Registry Editor Version 5.00",
183
+ "",
184
+ "[HKEY_CURRENT_USER\\SOFTWARE\\Policies\\Claude]",
185
+ ...Object.entries(values).map(([k, v]) => `"${k}"="${esc(v)}"`),
186
+ "",
187
+ ];
188
+ const tmp = path.join(process.env.TEMP || process.env.TMP || ".", `codemax-3p-${Date.now()}.reg`);
189
+ // UTF-16LE with a BOM is what reg.exe expects for a v5 file; UTF-8 imports as mojibake.
190
+ fs.writeFileSync(tmp, "" + lines.join("\r\n"), "utf16le");
191
+ const imported = run(`reg import "${tmp}"`) !== null;
192
+ try { fs.unlinkSync(tmp); } catch { /* temp file, ignore */ }
193
+ return imported;
194
+ }
195
+
196
+ function machinePolicyPresent() {
197
+ // A machine policy makes the app ignore the per-user one ENTIRELY, so writing HKCU under it
198
+ // looks like it worked and changes nothing. Worth saying out loud rather than debugging later.
199
+ return run('reg query "HKLM\\SOFTWARE\\Policies\\Claude" /v inferenceProvider') !== null;
200
+ }
201
+
202
+ function configureClaudeDesktop3P(home, apiKey) {
203
+ const isWin = process.platform === "win32";
204
+ const isMac = process.platform === "darwin";
205
+ const values = desktopPolicyValues(apiKey);
206
+ const written = [];
207
+
208
+ if (isWin) {
209
+ if (machinePolicyPresent()) {
210
+ warn("A machine-wide Claude policy exists (HKLM) — it overrides the per-user one.");
211
+ gray(" Ask whoever manages this device to apply the gateway settings there.");
212
+ }
213
+ if (writeWindowsPolicy(values)) written.push("HKCU\\SOFTWARE\\Policies\\Claude");
214
+ }
215
+
216
+ const baseDir = isWin
217
+ ? path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "Claude-3p")
218
+ : isMac
219
+ ? path.join(home, "Library", "Application Support", "Claude-3p")
220
+ : path.join(home, ".config", "Claude-3p");
221
+
222
+ const configLibDir = path.join(baseDir, "configLibrary");
223
+ if (!fs.existsSync(configLibDir)) fs.mkdirSync(configLibDir, { recursive: true });
224
+
225
+ const metaPath = path.join(configLibDir, "_meta.json");
226
+ const meta = readJson(metaPath);
227
+ if (!Array.isArray(meta.entries)) meta.entries = [];
228
+
229
+ let profileId = meta.appliedId;
230
+ if (!profileId || !fs.existsSync(path.join(configLibDir, `${profileId}.json`))) {
231
+ profileId = crypto.randomUUID ? crypto.randomUUID() : `codemax-${Date.now()}`;
232
+ meta.appliedId = profileId;
233
+ if (!meta.entries.some((e) => e && e.id === profileId)) {
234
+ meta.entries.push({ id: profileId, name: "CodeMax Gateway" });
235
+ }
236
+ }
237
+
238
+ // The local profile takes real types; only the OS policy store requires strings.
239
+ const profilePath = path.join(configLibDir, `${profileId}.json`);
240
+ writeJson(profilePath, {
241
+ ...values,
242
+ inferenceModels: DESKTOP_MODELS,
243
+ coworkEgressAllowedHosts: EGRESS_HOSTS,
244
+ skipWebFetchPreflight: true,
245
+ disableNonessentialTelemetry: true,
246
+ });
247
+ writeJson(metaPath, meta);
248
+ written.push(profilePath);
249
+
250
+ const devSettingsPath = path.join(baseDir, "developer_settings.json");
251
+ const devSettings = readJson(devSettingsPath);
252
+ devSettings.allowDevTools = true;
253
+ writeJson(devSettingsPath, devSettings);
254
+
255
+ /* Previous versions also wrote an `env` block into claude_desktop_config.json. That file
256
+ * configures MCP servers; nothing in it selects an inference endpoint, so those keys sat
257
+ * there doing nothing while looking like the thing that made this work. Removed, and any
258
+ * leftovers are cleaned up below so a re-run does not leave the key lying in a file the app
259
+ * hands to MCP server processes. */
260
+ const desktopConfigPath = isWin
261
+ ? path.join(process.env.APPDATA || path.join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json")
262
+ : isMac
263
+ ? path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json")
264
+ : path.join(home, ".config", "Claude", "claude_desktop_config.json");
265
+ try {
266
+ if (fs.existsSync(desktopConfigPath)) {
267
+ const dc = readJson(desktopConfigPath);
268
+ if (dc.env) {
269
+ for (const k of ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"]) delete dc.env[k];
270
+ if (Object.keys(dc.env).length === 0) delete dc.env;
271
+ writeJson(desktopConfigPath, dc);
272
+ }
273
+ }
274
+ } catch { /* best effort */ }
275
+
276
+ return written;
277
+ }
278
+
279
+ async function main() {
280
+ log("");
281
+ log(` ${c.cyan}╔══════════════════════════════════════════╗${c.reset}`);
282
+ log(` ${c.cyan}║ ${c.bold}CodeMax Setup${c.reset}${c.cyan} ║${c.reset}`);
283
+ log(` ${c.cyan}╚══════════════════════════════════════════╝${c.reset}`);
284
+ log("");
285
+
286
+ const home = process.env.HOME || process.env.USERPROFILE;
287
+ if (!home) {
288
+ fail("Cannot determine home directory");
289
+ process.exit(1);
290
+ }
291
+
292
+ // ── Get API Key ──
293
+ let apiKey = process.argv[2] || "";
294
+ if (!apiKey) {
295
+ log(` ${c.white}Enter your CodeMax API key${c.reset}`);
296
+ gray("Get it from your admin or codemax.pro");
297
+ log("");
298
+ apiKey = await ask(` ${c.white}API Key: ${c.reset}`);
299
+ log("");
300
+ }
301
+
302
+ if (!apiKey || apiKey.length < 5) {
303
+ fail("No valid API key provided. Exiting.");
304
+ process.exit(1);
305
+ }
306
+
307
+ // ── [1/5] Validate API Key ──
308
+ info("[1/5] Validating API key...");
309
+ const result = await validateKey(apiKey);
310
+
311
+ if (result.valid) {
312
+ if (result.rateLimit) {
313
+ warn("API key valid but rate-limited. Continuing setup...");
314
+ } else {
315
+ ok("API key is valid!");
316
+ ok("Connected to CodeMax");
317
+ }
318
+ } else if (result.network) {
319
+ warn(`Could not reach server: ${result.reason}`);
320
+ const cont = await ask(` ${c.yellow}Continue anyway? (y/n): ${c.reset}`);
321
+ if (cont.toLowerCase() !== "y") process.exit(1);
322
+ } else {
323
+ fail(result.reason);
324
+ gray("Make sure you're using a valid CodeMax API key (sk-cp-...)");
325
+ process.exit(1);
326
+ }
327
+ log("");
328
+
329
+ // ── [2/5] Check Node.js ──
330
+ info("[2/5] Checking Node.js...");
331
+ const nodeVer = run("node --version");
332
+ if (nodeVer) {
333
+ ok(`Node.js ${nodeVer} found`);
334
+ } else {
335
+ fail("Node.js not found. Install from https://nodejs.org");
336
+ process.exit(1);
337
+ }
338
+ log("");
339
+
340
+ // ── [3/5] Configure Claude Code CLI & VS Code settings ──
341
+ info("[3/5] Configuring Claude Code CLI & VS Code...");
342
+ const settingsPath = path.join(home, ".claude", "settings.json");
343
+ try {
344
+ const settings = readJson(settingsPath);
345
+ if (!settings.env) settings.env = {};
346
+
347
+ /* These five belong together and were established by testing against the CLI. Removing
348
+ * any one of them changes behaviour in a way that is easy to miss, because nothing
349
+ * errors — it just quietly settles on different defaults. Treat them as a set. */
350
+ Object.assign(settings.env, {
351
+ ANTHROPIC_AUTH_TOKEN: apiKey,
352
+ ANTHROPIC_BASE_URL: API_ENDPOINT,
353
+ CLAUDE_CODE_OAUTH_TOKEN: apiKey,
354
+ CLAUDE_CODE_SUBSCRIPTION_TYPE: "max",
355
+ CLAUDE_CODE_REMOTE: "1",
356
+ });
357
+
358
+ const removeVars = [
359
+ "ANTHROPIC_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "ANTHROPIC_DEFAULT_MODEL",
360
+ "ANTHROPIC_REASONING_MODEL",
361
+ "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL",
362
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
363
+ ];
364
+ for (const v of removeVars) delete settings.env[v];
365
+ delete settings.model;
366
+
367
+ writeJson(settingsPath, settings);
368
+ ok("Claude Code CLI & VS Code Extension configured");
369
+ } catch (e) {
370
+ fail(`Failed: ${e.message}`);
371
+ }
372
+ log("");
373
+
374
+ // ── [4/5] Configure Claude Desktop App (Third-Party Inference Gateway) ──
375
+ info("[4/5] Configuring Claude Desktop App (Inference Gateway)...");
376
+ try {
377
+ const written = configureClaudeDesktop3P(home, apiKey);
378
+ if (written.length) {
379
+ ok("Claude Desktop third-party inference configured");
380
+ for (const w of written) gray(` ${w}`);
381
+ } else {
382
+ warn("Claude Desktop config could not be written — is the app installed?");
383
+ }
384
+ } catch (e) {
385
+ warn(`Could not auto-configure Claude Desktop: ${e.message}`);
386
+ }
387
+ log("");
388
+
389
+ // ── Clean up any stale MCP config from prior installs ──
390
+ const claudeJsonPath = path.join(home, ".claude.json");
391
+ try {
392
+ const claudeJson = readJson(claudeJsonPath);
393
+ let mutated = false;
394
+ if (claudeJson.mcpServers && claudeJson.mcpServers.CodeMax) {
395
+ delete claudeJson.mcpServers.CodeMax;
396
+ mutated = true;
397
+ }
398
+ if (mutated) {
399
+ if (claudeJson.mcpServers && Object.keys(claudeJson.mcpServers).length === 0) {
400
+ delete claudeJson.mcpServers;
401
+ }
402
+ claudeJson.hasCompletedOnboarding = true;
403
+ writeJson(claudeJsonPath, claudeJson);
404
+ } else if (!fs.existsSync(claudeJsonPath)) {
405
+ writeJson(claudeJsonPath, { hasCompletedOnboarding: true });
406
+ }
407
+ } catch { /* non-critical */ }
408
+
409
+ // ── Clear stale env vars (Windows only) ──
410
+ if (process.platform === "win32") {
411
+ const staleVars = [
412
+ "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL",
413
+ "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL",
414
+ "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL",
415
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
416
+ ];
417
+ for (const v of staleVars) {
418
+ run(`REG delete "HKCU\\Environment" /v ${v} /f`);
419
+ }
420
+ }
421
+
422
+ // ── [5/5] Install Claude Code CLI ──
423
+ info("[5/5] Checking Claude Code CLI...");
424
+ if (which("claude")) {
425
+ ok("Claude Code CLI already installed");
426
+ } else {
427
+ info("Installing Claude Code CLI...");
428
+ const cliResult = run("npm install -g @anthropic-ai/claude-code");
429
+ if (cliResult !== null) {
430
+ ok("Claude Code CLI installed!");
431
+ } else {
432
+ warn("Auto-install failed. Run: npm install -g @anthropic-ai/claude-code");
433
+ }
434
+ }
435
+
436
+ // ── Done ──
437
+ log("");
438
+ log(` ${c.green}╔══════════════════════════════════════════╗${c.reset}`);
439
+ log(` ${c.green}║ ${c.bold}✓ Setup complete!${c.reset}${c.green} ║${c.reset}`);
440
+ log(` ${c.green}╚══════════════════════════════════════════╝${c.reset}`);
441
+ log("");
442
+ log(` ${c.white}What was configured:${c.reset}`);
443
+ gray(` • API key validated ✓`);
444
+ gray(` • Claude Code CLI & VS Code Extension (~/.claude/settings.json)`);
445
+ gray(` • Claude Desktop — third-party inference, provider "gateway"`);
446
+ gray(` models, x-api-key auth, sandbox egress list, WebFetch preflight off`);
447
+ log("");
448
+ log(` ${c.white}Claude Desktop needs a full restart, not just a closed window:${c.reset}`);
449
+ gray(` • Quit it from the system tray / menu bar, then open it again.`);
450
+ gray(` • Config is read once at launch, so a window reopened from a running`);
451
+ gray(` process keeps the old settings and looks like this did not work.`);
452
+ log("");
453
+ log(` ${c.gray}╭───────────────────────────────────────╮${c.reset}`);
454
+ log(` ${c.gray}│ Gateway: api.codemax.pro │${c.reset}`);
455
+ log(` ${c.gray}│ Key: ${apiKey.substring(0, 8)}... │${c.reset}`);
456
+ log(` ${c.gray}╰───────────────────────────────────────╯${c.reset}`);
457
+ log("");
458
+ gray("Restart Claude Code / VS Code / Claude Desktop to apply.");
459
+ gray("Re-run anytime to update your key.");
460
+ log("");
461
+
462
+ // Ask to launch
463
+ if (which("claude")) {
464
+ const launch = await ask(` ${c.white}Launch Claude Code now? (y/n): ${c.reset}`);
465
+ if (launch.toLowerCase() === "y" || launch === "") {
466
+ log("");
467
+ info("🚀 Launching Claude Code...");
468
+ log(` ${c.gray}════════════════════════════════════${c.reset}`);
469
+ log("");
470
+ try {
471
+ execSync("claude", { stdio: "inherit" });
472
+ } catch { }
473
+ } else {
474
+ log("");
475
+ log(` ${c.white}To start later, open any terminal and type: claude${c.reset}`);
476
+ log("");
477
+ }
478
+ }
479
+ }
480
+
481
+ main().catch((e) => {
482
+ fail(`Unexpected error: ${e.message}`);
483
+ process.exit(1);
484
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codemax-pro",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "One-command setup for CodeMax — configures Claude Code CLI, VS Code extension, and Claude Desktop automatically",
5
5
  "main": "index.js",
6
6
  "bin": {