codemax-pro 1.2.0 → 1.3.0

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 (4) hide show
  1. package/README.md +70 -40
  2. package/index.js +277 -481
  3. package/lib.js +447 -0
  4. package/package.json +3 -2
package/index.js CHANGED
@@ -1,481 +1,277 @@
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
- /* Hosts the agent's own web tools may reach from inside the sandbox. This is a separate, stricter
133
- * boundary than the machine's firewall: an unlisted host is refused even when the machine can
134
- * reach it. Web SEARCH does not need anything here — search runs server-side and arrives as part
135
- * of the response — but WebFetch, npm, pip and git all run on the device and do. */
136
- const EGRESS_HOSTS = [
137
- "api.codemax.pro",
138
- "github.com", "raw.githubusercontent.com", "objects.githubusercontent.com",
139
- "gist.github.com", "codeload.github.com",
140
- "registry.npmjs.org", "npmjs.com", "www.npmjs.com",
141
- "pypi.org", "files.pythonhosted.org",
142
- "crates.io", "static.crates.io",
143
- "proxy.golang.org", "sum.golang.org",
144
- "developer.mozilla.org", "stackoverflow.com", "api.stackexchange.com",
145
- ];
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
- Object.assign(settings.env, {
348
- ANTHROPIC_AUTH_TOKEN: apiKey,
349
- ANTHROPIC_BASE_URL: API_ENDPOINT,
350
- CLAUDE_CODE_OAUTH_TOKEN: apiKey,
351
- CLAUDE_CODE_SUBSCRIPTION_TYPE: "max",
352
- CLAUDE_CODE_REMOTE: "1",
353
- });
354
-
355
- const removeVars = [
356
- "ANTHROPIC_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "ANTHROPIC_DEFAULT_MODEL",
357
- "ANTHROPIC_REASONING_MODEL",
358
- "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL",
359
- "ANTHROPIC_DEFAULT_HAIKU_MODEL",
360
- ];
361
- for (const v of removeVars) delete settings.env[v];
362
- delete settings.model;
363
-
364
- writeJson(settingsPath, settings);
365
- ok("Claude Code CLI & VS Code Extension configured");
366
- } catch (e) {
367
- fail(`Failed: ${e.message}`);
368
- }
369
- log("");
370
-
371
- // ── [4/5] Configure Claude Desktop App (Third-Party Inference Gateway) ──
372
- info("[4/5] Configuring Claude Desktop App (Inference Gateway)...");
373
- try {
374
- const written = configureClaudeDesktop3P(home, apiKey);
375
- if (written.length) {
376
- ok("Claude Desktop third-party inference configured");
377
- for (const w of written) gray(` ${w}`);
378
- } else {
379
- warn("Claude Desktop config could not be written — is the app installed?");
380
- }
381
- } catch (e) {
382
- warn(`Could not auto-configure Claude Desktop: ${e.message}`);
383
- }
384
- log("");
385
-
386
- // ── Clean up any stale MCP config from prior installs ──
387
- const claudeJsonPath = path.join(home, ".claude.json");
388
- try {
389
- const claudeJson = readJson(claudeJsonPath);
390
- let mutated = false;
391
- if (claudeJson.mcpServers && claudeJson.mcpServers.CodeMax) {
392
- delete claudeJson.mcpServers.CodeMax;
393
- mutated = true;
394
- }
395
- if (mutated) {
396
- if (claudeJson.mcpServers && Object.keys(claudeJson.mcpServers).length === 0) {
397
- delete claudeJson.mcpServers;
398
- }
399
- claudeJson.hasCompletedOnboarding = true;
400
- writeJson(claudeJsonPath, claudeJson);
401
- } else if (!fs.existsSync(claudeJsonPath)) {
402
- writeJson(claudeJsonPath, { hasCompletedOnboarding: true });
403
- }
404
- } catch { /* non-critical */ }
405
-
406
- // ── Clear stale env vars (Windows only) ──
407
- if (process.platform === "win32") {
408
- const staleVars = [
409
- "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL",
410
- "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL",
411
- "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL",
412
- "ANTHROPIC_DEFAULT_HAIKU_MODEL", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
413
- ];
414
- for (const v of staleVars) {
415
- run(`REG delete "HKCU\\Environment" /v ${v} /f`);
416
- }
417
- }
418
-
419
- // ── [5/5] Install Claude Code CLI ──
420
- info("[5/5] Checking Claude Code CLI...");
421
- if (which("claude")) {
422
- ok("Claude Code CLI already installed");
423
- } else {
424
- info("Installing Claude Code CLI...");
425
- const cliResult = run("npm install -g @anthropic-ai/claude-code");
426
- if (cliResult !== null) {
427
- ok("Claude Code CLI installed!");
428
- } else {
429
- warn("Auto-install failed. Run: npm install -g @anthropic-ai/claude-code");
430
- }
431
- }
432
-
433
- // ── Done ──
434
- log("");
435
- log(` ${c.green}╔══════════════════════════════════════════╗${c.reset}`);
436
- log(` ${c.green}║ ${c.bold}✓ Setup complete!${c.reset}${c.green} ║${c.reset}`);
437
- log(` ${c.green}╚══════════════════════════════════════════╝${c.reset}`);
438
- log("");
439
- log(` ${c.white}What was configured:${c.reset}`);
440
- gray(` • API key validated ✓`);
441
- gray(` • Claude Code CLI & VS Code Extension (~/.claude/settings.json)`);
442
- gray(` • Claude Desktop — third-party inference, provider "gateway"`);
443
- gray(` models, x-api-key auth, sandbox egress list, WebFetch preflight off`);
444
- log("");
445
- log(` ${c.white}Claude Desktop needs a full restart, not just a closed window:${c.reset}`);
446
- gray(` • Quit it from the system tray / menu bar, then open it again.`);
447
- gray(` • Config is read once at launch, so a window reopened from a running`);
448
- gray(` process keeps the old settings and looks like this did not work.`);
449
- log("");
450
- log(` ${c.gray}╭───────────────────────────────────────╮${c.reset}`);
451
- log(` ${c.gray}│ Gateway: api.codemax.pro │${c.reset}`);
452
- log(` ${c.gray}│ Key: ${apiKey.substring(0, 8)}... │${c.reset}`);
453
- log(` ${c.gray}╰───────────────────────────────────────╯${c.reset}`);
454
- log("");
455
- gray("Restart Claude Code / VS Code / Claude Desktop to apply.");
456
- gray("Re-run anytime to update your key.");
457
- log("");
458
-
459
- // Ask to launch
460
- if (which("claude")) {
461
- const launch = await ask(` ${c.white}Launch Claude Code now? (y/n): ${c.reset}`);
462
- if (launch.toLowerCase() === "y" || launch === "") {
463
- log("");
464
- info("🚀 Launching Claude Code...");
465
- log(` ${c.gray}════════════════════════════════════${c.reset}`);
466
- log("");
467
- try {
468
- execSync("claude", { stdio: "inherit" });
469
- } catch { }
470
- } else {
471
- log("");
472
- log(` ${c.white}To start later, open any terminal and type: claude${c.reset}`);
473
- log("");
474
- }
475
- }
476
- }
477
-
478
- main().catch((e) => {
479
- fail(`Unexpected error: ${e.message}`);
480
- process.exit(1);
481
- });
1
+ #!/usr/bin/env node
2
+
3
+ /* CodeMax setup for Claude Code and Claude Desktop.
4
+ *
5
+ * codemax-pro [key] configure everything
6
+ * codemax-pro doctor report what is actually configured, and what is fighting it
7
+ * codemax-pro reset remove what this tool set, and nothing else
8
+ *
9
+ * The three commands share one description of every location (lib.js) on purpose: when setup,
10
+ * doctor and reset each carry their own idea of where things live, reset starts leaving behind
11
+ * things doctor never learned to look for. */
12
+
13
+ 'use strict';
14
+
15
+ const readline = require('readline');
16
+ const L = require('./lib');
17
+
18
+ const c = {
19
+ reset: '\x1b[0m', bold: '\x1b[1m', dim: '\x1b[2m',
20
+ cyan: '\x1b[36m', green: '\x1b[32m', yellow: '\x1b[33m', red: '\x1b[31m',
21
+ gray: '\x1b[90m', white: '\x1b[97m',
22
+ };
23
+ const NO_COLOR = !!process.env.NO_COLOR || !process.stdout.isTTY;
24
+ const p = (s = '') => console.log(NO_COLOR ? String(s).replace(/\x1b\[[0-9;]*m/g, '') : s);
25
+ const ok = (m) => p(` ${c.green}✓${c.reset} ${m}`);
26
+ const bad = (m) => p(` ${c.red}✗${c.reset} ${m}`);
27
+ const warn = (m) => p(` ${c.yellow}!${c.reset} ${m}`);
28
+ const step = (m) => p(`\n${c.cyan}${m}${c.reset}`);
29
+ const dim = (m) => p(` ${c.gray}${m}${c.reset}`);
30
+
31
+ function ask(q) {
32
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
33
+ return new Promise((res) => rl.question(q, (a) => { rl.close(); res(a.trim()); }));
34
+ }
35
+
36
+ function header() {
37
+ p('');
38
+ p(` ${c.bold}CodeMax${c.reset} ${c.gray}·${c.reset} ${L.API_ENDPOINT}`);
39
+ }
40
+
41
+ // ─── doctor ──────────────────────────────────────────────────────────────────
42
+
43
+ /* Reads only. Its value is naming the failures that produce no error anywhere: a machine-wide
44
+ * policy that silently outranks the per-user one, an environment variable that outranks the
45
+ * settings file, and an app still running with the configuration it read at launch. Each of those
46
+ * looks exactly like "the installer did not work" from the outside. */
47
+ async function doctor() {
48
+ header();
49
+ let problems = 0;
50
+
51
+ step('Claude Code CLI');
52
+ const cli = L.readCliState();
53
+ if (!cli.exists) {
54
+ warn('not configured — no settings file');
55
+ dim(cli.file);
56
+ problems++;
57
+ } else {
58
+ const pointed = cli.baseUrl === L.API_ENDPOINT;
59
+ (pointed ? ok : bad)(`endpoint ${cli.baseUrl || '(not set)'}`);
60
+ if (!pointed) problems++;
61
+ (cli.key ? ok : bad)(`key ${L.redact(cli.key)}`);
62
+ if (!cli.key) problems++;
63
+ if (cli.defaultModelVars.length === 3) ok('default model settings present');
64
+ else warn(`default model settings incomplete (${cli.defaultModelVars.length}/3) — the default may not be Opus 5`);
65
+ if (cli.stalePresent.length) { warn(`stale variables present: ${cli.stalePresent.join(', ')}`); problems++; }
66
+ if (cli.pinnedModel) { warn(`a model is pinned in settings ("${cli.pinnedModel}") — this adds a duplicate picker entry`); problems++; }
67
+ dim(cli.file);
68
+ }
69
+
70
+ const info = L.claudeCliInfo();
71
+ if (info.installed) {
72
+ ok(`claude CLI installed${info.version ? ` ${info.version}` : ''}`);
73
+ if (!info.version && info.at) dim(info.at);
74
+ } else warn('claude CLI not found — run: npm install -g @anthropic-ai/claude-code');
75
+
76
+ step('Claude Desktop');
77
+ const d = L.readDesktopState();
78
+ if (L.IS_WIN) {
79
+ if (d.policy && d.policy.provider === 'gateway' && d.policy.baseUrl === L.API_ENDPOINT) {
80
+ ok(`policy gateway → ${d.policy.baseUrl}`);
81
+ ok(`auth ${d.policy.authScheme || '(default — expect 401)'}`);
82
+ if (d.policy.authScheme !== 'x-api-key') problems++;
83
+ let n = 0; try { n = JSON.parse(d.policy.models || '[]').length; } catch { /* */ }
84
+ (n ? ok : bad)(`models ${n} configured`);
85
+ if (!n) problems++;
86
+ ok(`fetch egress ${d.policy.egress || '(none)'}, preflight ${d.policy.skipPreflight === 'true' ? 'off' : 'ON — needs an external host'}`);
87
+ } else {
88
+ bad('policy not set');
89
+ problems++;
90
+ }
91
+ if (d.machinePolicy) {
92
+ bad('a machine-wide policy exists and OVERRIDES everything above');
93
+ dim(`${L.paths.winMachinePolicy} — whoever manages this device must set it there instead`);
94
+ problems++;
95
+ }
96
+ }
97
+ if (d.profile) { ok(`local profile written`); dim(d.profile.file); }
98
+ else { warn('no local profile — the app may not show these settings in its own UI'); }
99
+
100
+ step('Conflicts');
101
+ const conflicts = L.readEnvConflicts();
102
+ if (!conflicts.length) ok('no environment variables competing with the settings file');
103
+ else {
104
+ for (const v of conflicts) bad(`${v.name} = ${v.value} (${v.scope}) — this OUTRANKS the settings file`);
105
+ dim('run `codemax-pro` again to clear the persisted ones');
106
+ problems += conflicts.length;
107
+ }
108
+
109
+ step('Connection');
110
+ const key = cli.key || (d.policy && d.policy.key) || (d.profile && d.profile.inferenceGatewayApiKey);
111
+ if (!key) { bad('no key found to test'); problems++; }
112
+ else {
113
+ const r = await L.checkKey(key);
114
+ if (r.ok) ok(`endpoint reachable, key accepted ${r.ms}ms${r.note ? ` (${r.note})` : ''}`);
115
+ else { bad(`${r.reason} ${r.ms}ms`); problems++; }
116
+ }
117
+
118
+ p('');
119
+ if (problems === 0) {
120
+ p(` ${c.green}Everything checks out.${c.reset}`);
121
+ p(` ${c.gray}If the desktop app still behaves as before, it is still running with the${c.reset}`);
122
+ p(` ${c.gray}configuration it read at launch — quit it from the tray, then reopen.${c.reset}`);
123
+ } else {
124
+ p(` ${c.yellow}${problems} thing${problems > 1 ? 's' : ''} to look at, listed above.${c.reset}`);
125
+ }
126
+ p('');
127
+ return problems === 0 ? 0 : 1;
128
+ }
129
+
130
+ // ─── reset ───────────────────────────────────────────────────────────────────
131
+
132
+ async function reset(opts) {
133
+ header();
134
+ step('Reset');
135
+ p(` ${c.gray}Removes only what this tool set. Anything else in those files stays.${c.reset}`);
136
+ if (!opts.yes) {
137
+ const a = await ask(`\n Continue? ${c.gray}(y/N)${c.reset} `);
138
+ if (a.toLowerCase() !== 'y') { p('\n Cancelled.\n'); return 0; }
139
+ }
140
+ const removed = L.resetAll();
141
+ p('');
142
+ if (!removed.length) ok('nothing to remove — no CodeMax settings found');
143
+ else for (const r of removed) ok(`removed ${r}`);
144
+ p('');
145
+ p(` ${c.gray}Restart Claude Code and quit Claude Desktop from the tray to apply.${c.reset}`);
146
+ p('');
147
+ return 0;
148
+ }
149
+
150
+ // ─── setup ───────────────────────────────────────────────────────────────────
151
+
152
+ async function setup(opts) {
153
+ header();
154
+
155
+ let key = opts.key || process.env.CODEMAX_API_KEY || '';
156
+ if (!key) {
157
+ if (opts.yes) { bad('no key given, and --yes means nothing can be asked'); return 1; }
158
+ p('');
159
+ p(` ${c.white}Paste your CodeMax API key${c.reset} ${c.gray}(from codemax.pro)${c.reset}`);
160
+ key = await ask(' › ');
161
+ }
162
+ if (!key || key.length < 8) { p(''); bad('that does not look like a key'); p(''); return 1; }
163
+
164
+ step('Checking the key');
165
+ const check = await L.checkKey(key);
166
+ if (check.ok) ok(`accepted ${check.ms}ms${check.note ? ` (${check.note})` : ''}`);
167
+ else if (check.network) {
168
+ warn(`could not reach the endpoint: ${check.reason}`);
169
+ if (!opts.yes) {
170
+ const a = await ask(` Configure anyway? ${c.gray}(y/N)${c.reset} `);
171
+ if (a.toLowerCase() !== 'y') { p(''); return 1; }
172
+ }
173
+ } else { bad(check.reason); p(''); return 1; }
174
+
175
+ const want = (t) => !opts.only || opts.only === t;
176
+
177
+ if (want('cli')) {
178
+ step('Claude Code CLI and VS Code');
179
+ const r = L.configureCli(key);
180
+ ok(r.file);
181
+ if (r.backup) dim(`previous settings kept at ${r.backup}`);
182
+ }
183
+
184
+ if (want('desktop')) {
185
+ step('Claude Desktop');
186
+ const r = L.configureDesktop(key);
187
+ if (!r.written.length) warn('nothing could be written — is the app installed?');
188
+ for (const w of r.written) ok(w);
189
+ if (r.machinePolicy) {
190
+ warn('a machine-wide policy exists and overrides what was just written');
191
+ dim(`${L.paths.winMachinePolicy} — ask whoever manages this device to set it there`);
192
+ }
193
+ }
194
+
195
+ const cleaned = L.cleanLegacy();
196
+ if (cleaned.length) {
197
+ step('Cleaned up');
198
+ for (const r of cleaned) dim(r);
199
+ }
200
+
201
+ if (want('cli') && !L.claudeCliInfo().installed) {
202
+ step('Installing Claude Code CLI');
203
+ if (L.sh('npm install -g @anthropic-ai/claude-code') !== null) ok('installed');
204
+ else warn('could not install — run: npm install -g @anthropic-ai/claude-code');
205
+ }
206
+
207
+ /* Verifying after writing, not before. The check above proved the key works; this proves the
208
+ * configuration that was just written is the configuration a client will read. */
209
+ step('Verifying');
210
+ const after = L.readCliState();
211
+ if (!want('cli')) dim('skipped — CLI was not configured this run');
212
+ else if (after.baseUrl === L.API_ENDPOINT && after.key) ok('settings file reads back correctly');
213
+ else bad('settings file did not read back as expected — run `codemax-pro doctor`');
214
+
215
+ const conflicts = L.readEnvConflicts();
216
+ if (conflicts.length) {
217
+ for (const v of conflicts) warn(`${v.name} is set (${v.scope}) and outranks the settings file`);
218
+ } else ok('nothing competing with the settings file');
219
+
220
+ p('');
221
+ p(` ${c.green}Done.${c.reset}`);
222
+ p('');
223
+ p(` ${c.white}Claude Desktop must be quit from the tray, not just closed.${c.reset}`);
224
+ p(` ${c.gray}It reads its configuration once at launch, so a window reopened from a${c.reset}`);
225
+ p(` ${c.gray}running process keeps the old settings and looks like this did not work.${c.reset}`);
226
+ p('');
227
+ p(` ${c.gray}Check anything at any time: ${c.reset}codemax-pro doctor`);
228
+ p('');
229
+ return 0;
230
+ }
231
+
232
+ // ─── entry ───────────────────────────────────────────────────────────────────
233
+
234
+ function help() {
235
+ p(`
236
+ ${c.bold}codemax-pro${c.reset} ${c.gray}· setup for Claude Code and Claude Desktop${c.reset}
237
+
238
+ ${c.white}codemax-pro${c.reset} [key] configure everything
239
+ ${c.white}codemax-pro doctor${c.reset} report what is configured, and what is fighting it
240
+ ${c.white}codemax-pro reset${c.reset} remove what this tool set
241
+
242
+ ${c.gray}--yes${c.reset} never prompt
243
+ ${c.gray}--only cli|desktop${c.reset} configure one surface only
244
+
245
+ ${c.gray}The key can also come from CODEMAX_API_KEY.${c.reset}
246
+ `);
247
+ }
248
+
249
+ async function main() {
250
+ const argv = process.argv.slice(2);
251
+ const opts = { yes: false, only: null, key: '' };
252
+ const rest = [];
253
+ for (let i = 0; i < argv.length; i++) {
254
+ const a = argv[i];
255
+ if (a === '--yes' || a === '-y') opts.yes = true;
256
+ else if (a === '--only') opts.only = (argv[++i] || '').toLowerCase();
257
+ else if (a.startsWith('--only=')) opts.only = a.slice(7).toLowerCase();
258
+ else if (a === '--help' || a === '-h') { help(); return 0; }
259
+ else rest.push(a);
260
+ }
261
+ if (opts.only && !['cli', 'desktop'].includes(opts.only)) {
262
+ bad(`--only takes "cli" or "desktop", not "${opts.only}"`);
263
+ return 1;
264
+ }
265
+
266
+ const cmd = (rest[0] || '').toLowerCase();
267
+ if (cmd === 'doctor') return doctor();
268
+ if (cmd === 'reset') return reset(opts);
269
+ if (cmd === 'help') { help(); return 0; }
270
+ // Anything else is treated as the key, so `codemax-pro sk-cp-…` keeps working.
271
+ opts.key = rest[0] || '';
272
+ return setup(opts);
273
+ }
274
+
275
+ main()
276
+ .then((code) => process.exit(code || 0))
277
+ .catch((e) => { p(''); bad(e.message); p(''); process.exit(1); });