codemax-pro 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +1 -1
  2. package/index.js +4 -1
  3. package/lib.js +487 -480
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -46,7 +46,7 @@ Claude Code CLI
46
46
  Claude Desktop
47
47
  ✓ policy gateway → https://api.codemax.pro
48
48
  ✓ auth x-api-key
49
- ✓ models 4 configured
49
+ ✓ models 4 configured, 3 at 1M
50
50
 
51
51
  Conflicts
52
52
  ✓ no environment variables competing with the settings file
package/index.js CHANGED
@@ -92,7 +92,10 @@ async function doctor() {
92
92
  if (scheme !== 'x-api-key') problems++;
93
93
  const n = Array.isArray(prof.inferenceModels) ? prof.inferenceModels.length : 0;
94
94
  const oneM = Array.isArray(prof.inferenceModels) ? prof.inferenceModels.filter((m) => m && m.supports1m).length : 0;
95
- (n ? ok : bad)(`models ${n} configured${oneM ? `, ${oneM} with a 1M option` : ''}`);
95
+ // A 1M model without `prefer1m` shows twice in the picker (200K and 1M) — say so rather than
96
+ // report a count that does not match what the customer sees.
97
+ const twice = Array.isArray(prof.inferenceModels) ? prof.inferenceModels.filter((m) => m && m.supports1m && !m.prefer1m).length : 0;
98
+ (n ? ok : bad)(`models ${n} configured${oneM ? `, ${oneM} at 1M` : ''}${twice ? ` (${twice} also listed at 200K — re-run setup)` : ''}`);
96
99
  if (!n) problems++;
97
100
  ok(`fetch egress ${JSON.stringify(prof.coworkEgressAllowedHosts || [])}, preflight ${prof.skipWebFetchPreflight ? 'off' : 'ON'}`);
98
101
  dim(prof.file);
package/lib.js CHANGED
@@ -1,480 +1,487 @@
1
- 'use strict';
2
-
3
- /* Everything the CLI does, minus the talking. index.js owns argument parsing and output; this file
4
- * owns the facts — where configuration lives, what is currently in it, and how to change it.
5
- *
6
- * Split out because the three commands need the same answers: setup writes what doctor reads and
7
- * reset removes. Sharing one description of each location is what keeps them from drifting, which
8
- * is how a `reset` ends up leaving something behind that `doctor` never looks for. */
9
-
10
- const fs = require('fs');
11
- const os = require('os');
12
- const path = require('path');
13
- const crypto = require('crypto');
14
- const { execSync } = require('child_process');
15
-
16
- const API_ENDPOINT = 'https://api.codemax.pro';
17
-
18
- const IS_WIN = process.platform === 'win32';
19
- const IS_MAC = process.platform === 'darwin';
20
- const HOME = process.env.HOME || process.env.USERPROFILE || os.homedir();
21
-
22
- /* The tiers this endpoint serves. Written out rather than discovered so the desktop model picker
23
- * is populated even before the app has talked to the endpoint once.
24
- *
25
- * `supports1m` adds a second picker entry for that model, labelled as the 1M context window. It is
26
- * an assertion the app cannot check: claim it on a model the endpoint will not take a 1M request
27
- * for, and every request made from that entry fails at inference time — so it is set per model
28
- * against what each one actually advertises, not switched on across the board.
29
- *
30
- * Haiku is deliberately absent from that list: it serves a 200K window (operator, 2026-10-25: there is no
31
- * official 1M Haiku), and giving it a 1M entry would offer the customer something that cannot work. */
32
- /* 🔴 These must be the ids `GET /v1/models` advertises TODAY, not the ones that merely still work.
33
- * Every legacy id folds in at the router, so shipping `claude-opus-5` here broke nothing and was
34
- * therefore invisible — the picker simply showed names the product had stopped using, contradicting
35
- * the site and the tier. Checked against production before each release:
36
- * curl -s https://api.codemax.pro/v1/models | jq -r '.data[].id' */
37
- const MODELS = [
38
- { name: 'claude-opus-5-5', supports1m: true },
39
- { name: 'claude-fable-5-1', supports1m: true },
40
- { name: 'claude-sonnet-5-5', supports1m: true },
41
- { name: 'claude-haiku-5-5' },
42
- ];
43
-
44
- /* What the agent's own tools may reach from inside the sandbox — a stricter boundary than the
45
- * machine's firewall, whose default is nothing at all beyond the API endpoint.
46
- *
47
- * "*" deliberately. A curated list of the usual developer hosts reads as the careful choice and
48
- * behaves as the wrong one: the moment somebody pastes a link to a blog post, a vendor's docs or
49
- * their own staging site, the fetch fails with nothing to explain why. A tool cannot know in
50
- * advance which host the next question is about. An organisation that wants the sandbox locked
51
- * down should set its own list — that is a deployment policy decision, not an installer default. */
52
- const EGRESS_HOSTS = ['*'];
53
-
54
- /* Variables set on ~/.claude/settings.json. The last three belong together and were established by
55
- * testing: remove any one and behaviour changes quietly, with nothing erroring — it simply settles
56
- * on different defaults. Treat them as a set. */
57
- function cliEnvVars(apiKey) {
58
- return {
59
- ANTHROPIC_AUTH_TOKEN: apiKey,
60
- ANTHROPIC_BASE_URL: API_ENDPOINT,
61
- CLAUDE_CODE_OAUTH_TOKEN: apiKey,
62
- CLAUDE_CODE_SUBSCRIPTION_TYPE: 'max',
63
- CLAUDE_CODE_REMOTE: '1',
64
- };
65
- }
66
-
67
- /* Left over from other setups, and actively harmful here: each one pins a model and produces a
68
- * duplicate entry in the picker. Removed on every run, not just the first. */
69
- const STALE_CLI_VARS = [
70
- 'ANTHROPIC_MODEL', 'ANTHROPIC_DEFAULT_MODEL', 'ANTHROPIC_REASONING_MODEL',
71
- 'CLAUDE_CODE_SUBAGENT_MODEL', 'ANTHROPIC_SMALL_FAST_MODEL',
72
- 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL',
73
- ];
74
-
75
- function desktopValues(apiKey) {
76
- return {
77
- inferenceProvider: 'gateway',
78
- inferenceGatewayBaseUrl: API_ENDPOINT,
79
- inferenceGatewayApiKey: apiKey,
80
- inferenceCredentialKind: 'static',
81
- // This endpoint reads the x-api-key header. The key defaults to "bearer", so omitting it
82
- // sends the credential in a header nothing reads and every request returns 401.
83
- inferenceGatewayAuthScheme: 'x-api-key',
84
- // Given explicitly rather than discovered: the picker keeps only model IDs it recognises,
85
- // so anything unexpected produces an empty picker with no error to explain it. Full IDs
86
- // also let the app skip a round trip at launch.
87
- inferenceModels: JSON.stringify(MODELS),
88
- // Without this the fetch tool asks a third-party host whether each domain is permitted
89
- // before fetching it — a dependency this setup otherwise never has, which fails closed on
90
- // a restricted network.
91
- skipWebFetchPreflight: 'true',
92
- coworkEgressAllowedHosts: JSON.stringify(EGRESS_HOSTS),
93
- // Product analytics. Off because leaving it on also widens the sandbox allowlist to carry
94
- // it. Crash reporting is deliberately NOT touched — disabling that trades away anyone's
95
- // ability to see failures on this machine.
96
- disableNonessentialTelemetry: 'true',
97
- };
98
- }
99
-
100
- // ── Paths ────────────────────────────────────────────────────────────────────
101
-
102
- const paths = {
103
- cliSettings: () => path.join(HOME, '.claude', 'settings.json'),
104
- claudeJson: () => path.join(HOME, '.claude.json'),
105
- desktopBase: () => (IS_WIN
106
- ? path.join(process.env.LOCALAPPDATA || path.join(HOME, 'AppData', 'Local'), 'Claude-3p')
107
- : IS_MAC
108
- ? path.join(HOME, 'Library', 'Application Support', 'Claude-3p')
109
- : path.join(HOME, '.config', 'Claude-3p')),
110
- configLibrary: () => path.join(paths.desktopBase(), 'configLibrary'),
111
- winPolicy: 'HKCU\\SOFTWARE\\Policies\\Claude',
112
- winMachinePolicy: 'HKLM\\SOFTWARE\\Policies\\Claude',
113
- };
114
-
115
- // ── Small helpers ────────────────────────────────────────────────────────────
116
-
117
- function sh(cmd) {
118
- try { return execSync(cmd, { encoding: 'utf8', stdio: 'pipe' }).trim(); } catch { return null; }
119
- }
120
-
121
- function readJson(file) {
122
- try {
123
- if (!fs.existsSync(file)) return null;
124
- const raw = fs.readFileSync(file, 'utf8').trim();
125
- return raw ? JSON.parse(raw) : {};
126
- } catch { return null; }
127
- }
128
-
129
- /* Writes through a temp file in the same directory, then renames. A half-written settings.json is
130
- * worse than an unchanged one: the app cannot parse it, and the user is left with a broken client
131
- * and no obvious cause. Rename is atomic on both platforms when source and target share a volume. */
132
- function writeJson(file, data) {
133
- const dir = path.dirname(file);
134
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
135
- const tmp = path.join(dir, `.${path.basename(file)}.tmp-${process.pid}`);
136
- fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');
137
- fs.renameSync(tmp, file);
138
- }
139
-
140
- /* Kept next to the original with a fixed name, so a re-run overwrites its own backup rather than
141
- * littering, and the user can always find the one file to restore. */
142
- function backup(file) {
143
- try {
144
- if (!fs.existsSync(file)) return null;
145
- const dest = `${file}.codemax-backup`;
146
- fs.copyFileSync(file, dest);
147
- return dest;
148
- } catch { return null; }
149
- }
150
-
151
- const redact = (s) => (typeof s === 'string' && s.length > 12 ? `${s.slice(0, 10)}…${s.slice(-4)}` : s ? '••••' : '(none)');
152
-
153
- // ── The endpoint ─────────────────────────────────────────────────────────────
154
-
155
- /* A real request, not a HEAD or a ping. Whether the key can complete a message is the only
156
- * question that matters, and the cheap checks all pass in situations where that one fails. */
157
- async function checkKey(apiKey, timeoutMs = 30000) {
158
- const body = JSON.stringify({
159
- model: 'claude-haiku-5-5',
160
- max_tokens: 8,
161
- messages: [{ role: 'user', content: 'hi' }],
162
- });
163
- const started = Date.now();
164
- try {
165
- const res = await fetch(`${API_ENDPOINT}/v1/messages`, {
166
- method: 'POST',
167
- headers: { 'content-type': 'application/json', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
168
- body,
169
- signal: AbortSignal.timeout(timeoutMs),
170
- });
171
- const ms = Date.now() - started;
172
- /* Drain the body even though nothing here reads it. An unread response keeps its
173
- * connection in fetch's pool, the pool keeps a libuv handle alive, and exiting while that
174
- * handle is mid-teardown aborts the process with
175
- * `Assertion failed: !(handle->flags & UV_HANDLE_CLOSING)`. Seen on Windows: the whole
176
- * report printed correctly and then the process crashed, which reads as a broken tool. */
177
- try { await res.arrayBuffer(); } catch { /* body already gone; nothing to release */ }
178
- if (res.ok) return { ok: true, ms };
179
- // Rate limiting proves the key is real and accepted; it is not a setup failure.
180
- if (res.status === 429) return { ok: true, ms, note: 'rate limited right now' };
181
- if (res.status === 401 || res.status === 403) return { ok: false, ms, reason: 'key rejected' };
182
- if (res.status === 402) return { ok: false, ms, reason: 'no remaining balance' };
183
- return { ok: false, ms, reason: `endpoint returned ${res.status}` };
184
- } catch (e) {
185
- return { ok: false, ms: Date.now() - started, reason: e.message, network: true };
186
- }
187
- }
188
-
189
- // ── Reading current state (doctor) ───────────────────────────────────────────
190
-
191
- function readCliState() {
192
- const file = paths.cliSettings();
193
- const json = readJson(file);
194
- const env = (json && json.env) || {};
195
- return {
196
- file,
197
- exists: !!json,
198
- baseUrl: env.ANTHROPIC_BASE_URL || null,
199
- key: env.ANTHROPIC_AUTH_TOKEN || null,
200
- defaultModelVars: ['CLAUDE_CODE_OAUTH_TOKEN', 'CLAUDE_CODE_SUBSCRIPTION_TYPE', 'CLAUDE_CODE_REMOTE']
201
- .filter((k) => env[k]),
202
- stalePresent: STALE_CLI_VARS.filter((k) => env[k]),
203
- pinnedModel: json && json.model ? json.model : null,
204
- };
205
- }
206
-
207
- function readDesktopState() {
208
- const out = { policy: null, profile: null, machinePolicy: false };
209
-
210
- if (IS_WIN) {
211
- const q = sh(`reg query "${paths.winPolicy}"`);
212
- if (q) {
213
- const grab = (name) => {
214
- const m = q.match(new RegExp(`${name}\\s+REG_SZ\\s+([^\\r\\n]*)`));
215
- return m ? m[1].trim() : null;
216
- };
217
- out.policy = {
218
- provider: grab('inferenceProvider'),
219
- baseUrl: grab('inferenceGatewayBaseUrl'),
220
- key: grab('inferenceGatewayApiKey'),
221
- authScheme: grab('inferenceGatewayAuthScheme'),
222
- models: grab('inferenceModels'),
223
- egress: grab('coworkEgressAllowedHosts'),
224
- skipPreflight: grab('skipWebFetchPreflight'),
225
- };
226
- }
227
- // A machine policy makes the app ignore the per-user one ENTIRELY, so a correct HKCU write
228
- // changes nothing and looks like it worked. Worth naming rather than debugging later.
229
- out.machinePolicy = sh(`reg query "${paths.winMachinePolicy}" /v inferenceProvider`) !== null;
230
- }
231
-
232
- const meta = readJson(path.join(paths.configLibrary(), '_meta.json'));
233
- if (meta && meta.appliedId) {
234
- const p = path.join(paths.configLibrary(), `${meta.appliedId}.json`);
235
- const prof = readJson(p);
236
- if (prof) out.profile = { file: p, ...prof };
237
- }
238
- return out;
239
- }
240
-
241
- /* An environment variable beats the settings file, so a stale one silently sends the CLI somewhere
242
- * else while the file on disk looks perfect. This is the single most confusing failure in this
243
- * setup, and it is invisible unless something goes looking for it. */
244
- function readEnvConflicts() {
245
- const names = ['ANTHROPIC_BASE_URL', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_MODEL'];
246
- const found = [];
247
- for (const n of names) {
248
- if (process.env[n]) found.push({ name: n, value: n.includes('URL') || n.includes('MODEL') ? process.env[n] : redact(process.env[n]), scope: 'this shell' });
249
- }
250
- if (IS_WIN) {
251
- for (const n of names) {
252
- const q = sh(`reg query "HKCU\\Environment" /v ${n}`);
253
- if (q) {
254
- const m = q.match(new RegExp(`${n}\\s+REG_[A-Z_]+\\s+([^\\r\\n]*)`));
255
- found.push({ name: n, value: n.includes('URL') || n.includes('MODEL') ? (m ? m[1].trim() : '?') : '••••', scope: 'persisted (Windows)' });
256
- }
257
- }
258
- }
259
- return found;
260
- }
261
-
262
- /* Three ways to look, because running it is not a reliable test.
263
- *
264
- * `claude --version` succeeds in a normal terminal and FAILS through execSync on Windows: Node
265
- * shells out to cmd.exe, whose PATH does not necessarily include npm's global bin directory. The
266
- * first version of this reported "not installed" on a machine where the CLI was installed and
267
- * working — a diagnostic that invents problems is worse than no diagnostic, because the person
268
- * reading it goes and fixes something that was never broken.
269
- *
270
- * So: try running it, then ask the shell where it is, then look where npm puts it. Finding the
271
- * binary without a version is still "installed". */
272
- function claudeCliInfo() {
273
- const v = sh('claude --version');
274
- if (v) return { installed: true, version: v };
275
-
276
- const located = sh(IS_WIN ? 'where claude' : 'which claude');
277
- if (located) return { installed: true, version: null, at: located.split(/\r?\n/)[0].trim() };
278
-
279
- const root = sh('npm prefix -g');
280
- if (root) {
281
- for (const rel of IS_WIN ? ['claude.cmd', 'claude.ps1', 'claude'] : ['bin/claude']) {
282
- const candidate = path.join(root, rel);
283
- if (fs.existsSync(candidate)) return { installed: true, version: null, at: candidate };
284
- }
285
- }
286
- return { installed: false, version: null };
287
- }
288
-
289
- // ── Writing (setup) ──────────────────────────────────────────────────────────
290
-
291
- function configureCli(apiKey) {
292
- const file = paths.cliSettings();
293
- const bak = backup(file);
294
- const json = readJson(file) || {};
295
- if (!json.env) json.env = {};
296
- Object.assign(json.env, cliEnvVars(apiKey));
297
- for (const k of STALE_CLI_VARS) delete json.env[k];
298
- // Not the same thing as the env vars: this creates a separate kind of pinned entry.
299
- delete json.model;
300
- writeJson(file, json);
301
- return { file, backup: bak };
302
- }
303
-
304
- const escReg = (s) => String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
305
-
306
- /* Built as a .reg file and imported rather than passed to `reg add`. The command-line form loses
307
- * quotes inside JSON values to cmd's own parsing and stores a truncated value that imports
308
- * cleanly — which surfaces much later as an empty model picker with nothing to explain it. */
309
- function writeWinPolicy(values) {
310
- const lines = [
311
- 'Windows Registry Editor Version 5.00', '',
312
- `[HKEY_CURRENT_USER\\SOFTWARE\\Policies\\Claude]`,
313
- ...Object.entries(values).map(([k, v]) => `"${k}"="${escReg(v)}"`),
314
- '',
315
- ];
316
- const tmp = path.join(os.tmpdir(), `codemax-3p-${process.pid}.reg`);
317
- let error = null;
318
- try {
319
- // UTF-16LE with a BOM is what reg.exe expects for a v5 file; UTF-8 imports as mojibake.
320
- fs.writeFileSync(tmp, '' + lines.join('\r\n'), 'utf16le');
321
- execSync(`reg import "${tmp}"`, { encoding: 'utf8', stdio: 'pipe' });
322
- } catch (e) {
323
- /* Captured rather than swallowed. The first version returned a bare false here, so a failed
324
- * import was indistinguishable from "not attempted" — and what the user saw afterwards was
325
- * a report saying "policy not set" with nothing anywhere explaining why. */
326
- error = String((e && (e.stderr || e.message)) || 'unknown').trim().split(/\r?\n/)[0];
327
- }
328
- try { fs.unlinkSync(tmp); } catch { /* temp */ }
329
-
330
- // Trust the registry, not the exit code: confirm the value is actually readable back.
331
- const verified = sh(`reg query "${paths.winPolicy}" /v inferenceProvider`) !== null;
332
- return { ok: verified, error: verified ? null : (error || 'reg import reported success but the value is not readable back') };
333
- }
334
-
335
- function configureDesktop(apiKey) {
336
- const values = desktopValues(apiKey);
337
- const written = [];
338
- let machinePolicy = false;
339
- let policyError = null;
340
-
341
- if (IS_WIN) {
342
- machinePolicy = sh(`reg query "${paths.winMachinePolicy}" /v inferenceProvider`) !== null;
343
- const r = writeWinPolicy(values);
344
- if (r.ok) written.push(paths.winPolicy);
345
- else policyError = r.error;
346
- }
347
-
348
- const dir = paths.configLibrary();
349
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
350
- const metaPath = path.join(dir, '_meta.json');
351
- const meta = readJson(metaPath) || {};
352
- if (!Array.isArray(meta.entries)) meta.entries = [];
353
- let id = meta.appliedId;
354
- if (!id || !fs.existsSync(path.join(dir, `${id}.json`))) {
355
- id = crypto.randomUUID ? crypto.randomUUID() : `codemax-${Date.now()}`;
356
- meta.appliedId = id;
357
- if (!meta.entries.some((e) => e && e.id === id)) meta.entries.push({ id, name: 'CodeMax Gateway' });
358
- }
359
- const profile = path.join(dir, `${id}.json`);
360
- // The local profile takes real types; only the OS policy store requires everything as strings.
361
- writeJson(profile, {
362
- ...values,
363
- inferenceModels: MODELS,
364
- coworkEgressAllowedHosts: EGRESS_HOSTS,
365
- skipWebFetchPreflight: true,
366
- disableNonessentialTelemetry: true,
367
- });
368
- writeJson(metaPath, meta);
369
- written.push(profile);
370
-
371
- const dev = path.join(paths.desktopBase(), 'developer_settings.json');
372
- const devJson = readJson(dev) || {};
373
- devJson.allowDevTools = true;
374
- writeJson(dev, devJson);
375
-
376
- return { written, machinePolicy, policyError };
377
- }
378
-
379
- /* Older versions put an `env` block in claude_desktop_config.json and an MCP server entry in
380
- * .claude.json. Neither ever selected an inference endpoint — the first configures MCP servers,
381
- * the second is unrelated — so they sat there doing nothing while looking like the thing that made
382
- * this work. Cleaned on every run, because the key should not be left lying in a file the app
383
- * hands to MCP server processes. */
384
- function cleanLegacy() {
385
- const removed = [];
386
-
387
- const dcPath = IS_WIN
388
- ? path.join(process.env.APPDATA || path.join(HOME, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json')
389
- : IS_MAC
390
- ? path.join(HOME, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
391
- : path.join(HOME, '.config', 'Claude', 'claude_desktop_config.json');
392
- const dc = readJson(dcPath);
393
- if (dc && dc.env) {
394
- let touched = false;
395
- for (const k of ['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY']) {
396
- if (k in dc.env) { delete dc.env[k]; touched = true; }
397
- }
398
- if (touched) {
399
- if (Object.keys(dc.env).length === 0) delete dc.env;
400
- writeJson(dcPath, dc);
401
- removed.push(`${dcPath} (stale env block)`);
402
- }
403
- }
404
-
405
- const cj = readJson(paths.claudeJson());
406
- if (cj && cj.mcpServers && cj.mcpServers.CodeMax) {
407
- delete cj.mcpServers.CodeMax;
408
- if (Object.keys(cj.mcpServers).length === 0) delete cj.mcpServers;
409
- cj.hasCompletedOnboarding = true;
410
- writeJson(paths.claudeJson(), cj);
411
- removed.push(`${paths.claudeJson()} (old MCP entry)`);
412
- } else if (!cj) {
413
- writeJson(paths.claudeJson(), { hasCompletedOnboarding: true });
414
- }
415
-
416
- // A persisted variable outranks the settings file, so leaving one behind quietly overrides
417
- // everything written above.
418
- if (IS_WIN) {
419
- for (const v of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_MODEL',
420
- 'ANTHROPIC_SMALL_FAST_MODEL', 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL',
421
- 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC']) {
422
- if (sh(`reg query "HKCU\\Environment" /v ${v}`)) {
423
- sh(`REG delete "HKCU\\Environment" /v ${v} /f`);
424
- removed.push(`Windows environment variable ${v}`);
425
- }
426
- }
427
- }
428
- return removed;
429
- }
430
-
431
- // ── Removing (reset) ─────────────────────────────────────────────────────────
432
-
433
- /* Removes only what this tool set. Other people's settings in the same files are left exactly as
434
- * they are — a reset that takes the whole file with it is not a reset, it is data loss. */
435
- function resetAll() {
436
- const removed = [];
437
-
438
- const file = paths.cliSettings();
439
- const json = readJson(file);
440
- if (json && json.env) {
441
- let touched = false;
442
- for (const k of Object.keys(cliEnvVars('x'))) {
443
- if (k in json.env) { delete json.env[k]; touched = true; }
444
- }
445
- if (touched) {
446
- if (Object.keys(json.env).length === 0) delete json.env;
447
- backup(file);
448
- writeJson(file, json);
449
- removed.push(`${file} (CodeMax variables only)`);
450
- }
451
- }
452
-
453
- if (IS_WIN && sh(`reg query "${paths.winPolicy}"`)) {
454
- sh(`reg delete "${paths.winPolicy}" /f`);
455
- removed.push(paths.winPolicy);
456
- }
457
-
458
- const metaPath = path.join(paths.configLibrary(), '_meta.json');
459
- const meta = readJson(metaPath);
460
- if (meta && meta.appliedId) {
461
- const p = path.join(paths.configLibrary(), `${meta.appliedId}.json`);
462
- const prof = readJson(p);
463
- // Only ours. Another profile in the same library belongs to whoever put it there.
464
- if (prof && prof.inferenceGatewayBaseUrl === API_ENDPOINT) {
465
- try { fs.unlinkSync(p); removed.push(p); } catch { /* */ }
466
- delete meta.appliedId;
467
- meta.entries = (meta.entries || []).filter((e) => !e || e.name !== 'CodeMax Gateway');
468
- writeJson(metaPath, meta);
469
- }
470
- }
471
- return removed;
472
- }
473
-
474
- module.exports = {
475
- API_ENDPOINT, MODELS, EGRESS_HOSTS, IS_WIN, IS_MAC, HOME,
476
- paths, sh, readJson, writeJson, backup, redact,
477
- checkKey, readCliState, readDesktopState, readEnvConflicts, claudeCliInfo,
478
- configureCli, configureDesktop, cleanLegacy, resetAll,
479
- cliEnvVars, desktopValues, STALE_CLI_VARS,
480
- };
1
+ 'use strict';
2
+
3
+ /* Everything the CLI does, minus the talking. index.js owns argument parsing and output; this file
4
+ * owns the facts — where configuration lives, what is currently in it, and how to change it.
5
+ *
6
+ * Split out because the three commands need the same answers: setup writes what doctor reads and
7
+ * reset removes. Sharing one description of each location is what keeps them from drifting, which
8
+ * is how a `reset` ends up leaving something behind that `doctor` never looks for. */
9
+
10
+ const fs = require('fs');
11
+ const os = require('os');
12
+ const path = require('path');
13
+ const crypto = require('crypto');
14
+ const { execSync } = require('child_process');
15
+
16
+ const API_ENDPOINT = 'https://api.codemax.pro';
17
+
18
+ const IS_WIN = process.platform === 'win32';
19
+ const IS_MAC = process.platform === 'darwin';
20
+ const HOME = process.env.HOME || process.env.USERPROFILE || os.homedir();
21
+
22
+ /* The tiers this endpoint serves. Written out rather than discovered so the desktop model picker
23
+ * is populated even before the app has talked to the endpoint once.
24
+ *
25
+ * `supports1m` adds a second picker entry for that model, labelled as the 1M context window. It is
26
+ * an assertion the app cannot check: claim it on a model the endpoint will not take a 1M request
27
+ * for, and every request made from that entry fails at inference time — so it is set per model
28
+ * against what each one actually advertises, not switched on across the board.
29
+ *
30
+ * Haiku is deliberately absent from that list: it serves a 200K window (operator, 2026-10-25: there is no
31
+ * official 1M Haiku), and giving it a 1M entry would offer the customer something that cannot work.
32
+ *
33
+ * `prefer1m` ("Only show the 1M option") collapses that pair back to ONE entry, which the app then
34
+ * requests as the 1M variant. Without it every 1M model appeared twice — once at 200K and once at 1M —
35
+ * so the picker showed seven entries for four tiers (operator, 2026-11-04: exactly four, the three 1M
36
+ * and Haiku at 200K). Listing only the `[1m]` spelling does not achieve this: the app folds that back
37
+ * into `supports1m` on the plain id and offers both again. Desktop releases older than the field
38
+ * ignore it and simply keep showing both, so it degrades to the old behaviour rather than breaking. */
39
+ /* 🔴 These must be the ids `GET /v1/models` advertises TODAY, not the ones that merely still work.
40
+ * Every legacy id folds in at the router, so shipping `claude-opus-5` here broke nothing and was
41
+ * therefore invisible — the picker simply showed names the product had stopped using, contradicting
42
+ * the site and the tier. Checked against production before each release:
43
+ * curl -s https://api.codemax.pro/v1/models | jq -r '.data[].id' */
44
+ const MODELS = [
45
+ { name: 'claude-opus-5-5', supports1m: true, prefer1m: true },
46
+ { name: 'claude-fable-5-1', supports1m: true, prefer1m: true },
47
+ { name: 'claude-sonnet-5-5', supports1m: true, prefer1m: true },
48
+ { name: 'claude-haiku-5-5' },
49
+ ];
50
+
51
+ /* What the agent's own tools may reach from inside the sandbox — a stricter boundary than the
52
+ * machine's firewall, whose default is nothing at all beyond the API endpoint.
53
+ *
54
+ * "*" deliberately. A curated list of the usual developer hosts reads as the careful choice and
55
+ * behaves as the wrong one: the moment somebody pastes a link to a blog post, a vendor's docs or
56
+ * their own staging site, the fetch fails with nothing to explain why. A tool cannot know in
57
+ * advance which host the next question is about. An organisation that wants the sandbox locked
58
+ * down should set its own list — that is a deployment policy decision, not an installer default. */
59
+ const EGRESS_HOSTS = ['*'];
60
+
61
+ /* Variables set on ~/.claude/settings.json. The last three belong together and were established by
62
+ * testing: remove any one and behaviour changes quietly, with nothing erroring — it simply settles
63
+ * on different defaults. Treat them as a set. */
64
+ function cliEnvVars(apiKey) {
65
+ return {
66
+ ANTHROPIC_AUTH_TOKEN: apiKey,
67
+ ANTHROPIC_BASE_URL: API_ENDPOINT,
68
+ CLAUDE_CODE_OAUTH_TOKEN: apiKey,
69
+ CLAUDE_CODE_SUBSCRIPTION_TYPE: 'max',
70
+ CLAUDE_CODE_REMOTE: '1',
71
+ };
72
+ }
73
+
74
+ /* Left over from other setups, and actively harmful here: each one pins a model and produces a
75
+ * duplicate entry in the picker. Removed on every run, not just the first. */
76
+ const STALE_CLI_VARS = [
77
+ 'ANTHROPIC_MODEL', 'ANTHROPIC_DEFAULT_MODEL', 'ANTHROPIC_REASONING_MODEL',
78
+ 'CLAUDE_CODE_SUBAGENT_MODEL', 'ANTHROPIC_SMALL_FAST_MODEL',
79
+ 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL',
80
+ ];
81
+
82
+ function desktopValues(apiKey) {
83
+ return {
84
+ inferenceProvider: 'gateway',
85
+ inferenceGatewayBaseUrl: API_ENDPOINT,
86
+ inferenceGatewayApiKey: apiKey,
87
+ inferenceCredentialKind: 'static',
88
+ // This endpoint reads the x-api-key header. The key defaults to "bearer", so omitting it
89
+ // sends the credential in a header nothing reads and every request returns 401.
90
+ inferenceGatewayAuthScheme: 'x-api-key',
91
+ // Given explicitly rather than discovered: the picker keeps only model IDs it recognises,
92
+ // so anything unexpected produces an empty picker with no error to explain it. Full IDs
93
+ // also let the app skip a round trip at launch.
94
+ inferenceModels: JSON.stringify(MODELS),
95
+ // Without this the fetch tool asks a third-party host whether each domain is permitted
96
+ // before fetching it — a dependency this setup otherwise never has, which fails closed on
97
+ // a restricted network.
98
+ skipWebFetchPreflight: 'true',
99
+ coworkEgressAllowedHosts: JSON.stringify(EGRESS_HOSTS),
100
+ // Product analytics. Off because leaving it on also widens the sandbox allowlist to carry
101
+ // it. Crash reporting is deliberately NOT touched — disabling that trades away anyone's
102
+ // ability to see failures on this machine.
103
+ disableNonessentialTelemetry: 'true',
104
+ };
105
+ }
106
+
107
+ // ── Paths ────────────────────────────────────────────────────────────────────
108
+
109
+ const paths = {
110
+ cliSettings: () => path.join(HOME, '.claude', 'settings.json'),
111
+ claudeJson: () => path.join(HOME, '.claude.json'),
112
+ desktopBase: () => (IS_WIN
113
+ ? path.join(process.env.LOCALAPPDATA || path.join(HOME, 'AppData', 'Local'), 'Claude-3p')
114
+ : IS_MAC
115
+ ? path.join(HOME, 'Library', 'Application Support', 'Claude-3p')
116
+ : path.join(HOME, '.config', 'Claude-3p')),
117
+ configLibrary: () => path.join(paths.desktopBase(), 'configLibrary'),
118
+ winPolicy: 'HKCU\\SOFTWARE\\Policies\\Claude',
119
+ winMachinePolicy: 'HKLM\\SOFTWARE\\Policies\\Claude',
120
+ };
121
+
122
+ // ── Small helpers ────────────────────────────────────────────────────────────
123
+
124
+ function sh(cmd) {
125
+ try { return execSync(cmd, { encoding: 'utf8', stdio: 'pipe' }).trim(); } catch { return null; }
126
+ }
127
+
128
+ function readJson(file) {
129
+ try {
130
+ if (!fs.existsSync(file)) return null;
131
+ const raw = fs.readFileSync(file, 'utf8').trim();
132
+ return raw ? JSON.parse(raw) : {};
133
+ } catch { return null; }
134
+ }
135
+
136
+ /* Writes through a temp file in the same directory, then renames. A half-written settings.json is
137
+ * worse than an unchanged one: the app cannot parse it, and the user is left with a broken client
138
+ * and no obvious cause. Rename is atomic on both platforms when source and target share a volume. */
139
+ function writeJson(file, data) {
140
+ const dir = path.dirname(file);
141
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
142
+ const tmp = path.join(dir, `.${path.basename(file)}.tmp-${process.pid}`);
143
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');
144
+ fs.renameSync(tmp, file);
145
+ }
146
+
147
+ /* Kept next to the original with a fixed name, so a re-run overwrites its own backup rather than
148
+ * littering, and the user can always find the one file to restore. */
149
+ function backup(file) {
150
+ try {
151
+ if (!fs.existsSync(file)) return null;
152
+ const dest = `${file}.codemax-backup`;
153
+ fs.copyFileSync(file, dest);
154
+ return dest;
155
+ } catch { return null; }
156
+ }
157
+
158
+ const redact = (s) => (typeof s === 'string' && s.length > 12 ? `${s.slice(0, 10)}…${s.slice(-4)}` : s ? '••••' : '(none)');
159
+
160
+ // ── The endpoint ─────────────────────────────────────────────────────────────
161
+
162
+ /* A real request, not a HEAD or a ping. Whether the key can complete a message is the only
163
+ * question that matters, and the cheap checks all pass in situations where that one fails. */
164
+ async function checkKey(apiKey, timeoutMs = 30000) {
165
+ const body = JSON.stringify({
166
+ model: 'claude-haiku-5-5',
167
+ max_tokens: 8,
168
+ messages: [{ role: 'user', content: 'hi' }],
169
+ });
170
+ const started = Date.now();
171
+ try {
172
+ const res = await fetch(`${API_ENDPOINT}/v1/messages`, {
173
+ method: 'POST',
174
+ headers: { 'content-type': 'application/json', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
175
+ body,
176
+ signal: AbortSignal.timeout(timeoutMs),
177
+ });
178
+ const ms = Date.now() - started;
179
+ /* Drain the body even though nothing here reads it. An unread response keeps its
180
+ * connection in fetch's pool, the pool keeps a libuv handle alive, and exiting while that
181
+ * handle is mid-teardown aborts the process with
182
+ * `Assertion failed: !(handle->flags & UV_HANDLE_CLOSING)`. Seen on Windows: the whole
183
+ * report printed correctly and then the process crashed, which reads as a broken tool. */
184
+ try { await res.arrayBuffer(); } catch { /* body already gone; nothing to release */ }
185
+ if (res.ok) return { ok: true, ms };
186
+ // Rate limiting proves the key is real and accepted; it is not a setup failure.
187
+ if (res.status === 429) return { ok: true, ms, note: 'rate limited right now' };
188
+ if (res.status === 401 || res.status === 403) return { ok: false, ms, reason: 'key rejected' };
189
+ if (res.status === 402) return { ok: false, ms, reason: 'no remaining balance' };
190
+ return { ok: false, ms, reason: `endpoint returned ${res.status}` };
191
+ } catch (e) {
192
+ return { ok: false, ms: Date.now() - started, reason: e.message, network: true };
193
+ }
194
+ }
195
+
196
+ // ── Reading current state (doctor) ───────────────────────────────────────────
197
+
198
+ function readCliState() {
199
+ const file = paths.cliSettings();
200
+ const json = readJson(file);
201
+ const env = (json && json.env) || {};
202
+ return {
203
+ file,
204
+ exists: !!json,
205
+ baseUrl: env.ANTHROPIC_BASE_URL || null,
206
+ key: env.ANTHROPIC_AUTH_TOKEN || null,
207
+ defaultModelVars: ['CLAUDE_CODE_OAUTH_TOKEN', 'CLAUDE_CODE_SUBSCRIPTION_TYPE', 'CLAUDE_CODE_REMOTE']
208
+ .filter((k) => env[k]),
209
+ stalePresent: STALE_CLI_VARS.filter((k) => env[k]),
210
+ pinnedModel: json && json.model ? json.model : null,
211
+ };
212
+ }
213
+
214
+ function readDesktopState() {
215
+ const out = { policy: null, profile: null, machinePolicy: false };
216
+
217
+ if (IS_WIN) {
218
+ const q = sh(`reg query "${paths.winPolicy}"`);
219
+ if (q) {
220
+ const grab = (name) => {
221
+ const m = q.match(new RegExp(`${name}\\s+REG_SZ\\s+([^\\r\\n]*)`));
222
+ return m ? m[1].trim() : null;
223
+ };
224
+ out.policy = {
225
+ provider: grab('inferenceProvider'),
226
+ baseUrl: grab('inferenceGatewayBaseUrl'),
227
+ key: grab('inferenceGatewayApiKey'),
228
+ authScheme: grab('inferenceGatewayAuthScheme'),
229
+ models: grab('inferenceModels'),
230
+ egress: grab('coworkEgressAllowedHosts'),
231
+ skipPreflight: grab('skipWebFetchPreflight'),
232
+ };
233
+ }
234
+ // A machine policy makes the app ignore the per-user one ENTIRELY, so a correct HKCU write
235
+ // changes nothing and looks like it worked. Worth naming rather than debugging later.
236
+ out.machinePolicy = sh(`reg query "${paths.winMachinePolicy}" /v inferenceProvider`) !== null;
237
+ }
238
+
239
+ const meta = readJson(path.join(paths.configLibrary(), '_meta.json'));
240
+ if (meta && meta.appliedId) {
241
+ const p = path.join(paths.configLibrary(), `${meta.appliedId}.json`);
242
+ const prof = readJson(p);
243
+ if (prof) out.profile = { file: p, ...prof };
244
+ }
245
+ return out;
246
+ }
247
+
248
+ /* An environment variable beats the settings file, so a stale one silently sends the CLI somewhere
249
+ * else while the file on disk looks perfect. This is the single most confusing failure in this
250
+ * setup, and it is invisible unless something goes looking for it. */
251
+ function readEnvConflicts() {
252
+ const names = ['ANTHROPIC_BASE_URL', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_MODEL'];
253
+ const found = [];
254
+ for (const n of names) {
255
+ if (process.env[n]) found.push({ name: n, value: n.includes('URL') || n.includes('MODEL') ? process.env[n] : redact(process.env[n]), scope: 'this shell' });
256
+ }
257
+ if (IS_WIN) {
258
+ for (const n of names) {
259
+ const q = sh(`reg query "HKCU\\Environment" /v ${n}`);
260
+ if (q) {
261
+ const m = q.match(new RegExp(`${n}\\s+REG_[A-Z_]+\\s+([^\\r\\n]*)`));
262
+ found.push({ name: n, value: n.includes('URL') || n.includes('MODEL') ? (m ? m[1].trim() : '?') : '••••', scope: 'persisted (Windows)' });
263
+ }
264
+ }
265
+ }
266
+ return found;
267
+ }
268
+
269
+ /* Three ways to look, because running it is not a reliable test.
270
+ *
271
+ * `claude --version` succeeds in a normal terminal and FAILS through execSync on Windows: Node
272
+ * shells out to cmd.exe, whose PATH does not necessarily include npm's global bin directory. The
273
+ * first version of this reported "not installed" on a machine where the CLI was installed and
274
+ * working — a diagnostic that invents problems is worse than no diagnostic, because the person
275
+ * reading it goes and fixes something that was never broken.
276
+ *
277
+ * So: try running it, then ask the shell where it is, then look where npm puts it. Finding the
278
+ * binary without a version is still "installed". */
279
+ function claudeCliInfo() {
280
+ const v = sh('claude --version');
281
+ if (v) return { installed: true, version: v };
282
+
283
+ const located = sh(IS_WIN ? 'where claude' : 'which claude');
284
+ if (located) return { installed: true, version: null, at: located.split(/\r?\n/)[0].trim() };
285
+
286
+ const root = sh('npm prefix -g');
287
+ if (root) {
288
+ for (const rel of IS_WIN ? ['claude.cmd', 'claude.ps1', 'claude'] : ['bin/claude']) {
289
+ const candidate = path.join(root, rel);
290
+ if (fs.existsSync(candidate)) return { installed: true, version: null, at: candidate };
291
+ }
292
+ }
293
+ return { installed: false, version: null };
294
+ }
295
+
296
+ // ── Writing (setup) ──────────────────────────────────────────────────────────
297
+
298
+ function configureCli(apiKey) {
299
+ const file = paths.cliSettings();
300
+ const bak = backup(file);
301
+ const json = readJson(file) || {};
302
+ if (!json.env) json.env = {};
303
+ Object.assign(json.env, cliEnvVars(apiKey));
304
+ for (const k of STALE_CLI_VARS) delete json.env[k];
305
+ // Not the same thing as the env vars: this creates a separate kind of pinned entry.
306
+ delete json.model;
307
+ writeJson(file, json);
308
+ return { file, backup: bak };
309
+ }
310
+
311
+ const escReg = (s) => String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
312
+
313
+ /* Built as a .reg file and imported rather than passed to `reg add`. The command-line form loses
314
+ * quotes inside JSON values to cmd's own parsing and stores a truncated value that imports
315
+ * cleanly — which surfaces much later as an empty model picker with nothing to explain it. */
316
+ function writeWinPolicy(values) {
317
+ const lines = [
318
+ 'Windows Registry Editor Version 5.00', '',
319
+ `[HKEY_CURRENT_USER\\SOFTWARE\\Policies\\Claude]`,
320
+ ...Object.entries(values).map(([k, v]) => `"${k}"="${escReg(v)}"`),
321
+ '',
322
+ ];
323
+ const tmp = path.join(os.tmpdir(), `codemax-3p-${process.pid}.reg`);
324
+ let error = null;
325
+ try {
326
+ // UTF-16LE with a BOM is what reg.exe expects for a v5 file; UTF-8 imports as mojibake.
327
+ fs.writeFileSync(tmp, '' + lines.join('\r\n'), 'utf16le');
328
+ execSync(`reg import "${tmp}"`, { encoding: 'utf8', stdio: 'pipe' });
329
+ } catch (e) {
330
+ /* Captured rather than swallowed. The first version returned a bare false here, so a failed
331
+ * import was indistinguishable from "not attempted" — and what the user saw afterwards was
332
+ * a report saying "policy not set" with nothing anywhere explaining why. */
333
+ error = String((e && (e.stderr || e.message)) || 'unknown').trim().split(/\r?\n/)[0];
334
+ }
335
+ try { fs.unlinkSync(tmp); } catch { /* temp */ }
336
+
337
+ // Trust the registry, not the exit code: confirm the value is actually readable back.
338
+ const verified = sh(`reg query "${paths.winPolicy}" /v inferenceProvider`) !== null;
339
+ return { ok: verified, error: verified ? null : (error || 'reg import reported success but the value is not readable back') };
340
+ }
341
+
342
+ function configureDesktop(apiKey) {
343
+ const values = desktopValues(apiKey);
344
+ const written = [];
345
+ let machinePolicy = false;
346
+ let policyError = null;
347
+
348
+ if (IS_WIN) {
349
+ machinePolicy = sh(`reg query "${paths.winMachinePolicy}" /v inferenceProvider`) !== null;
350
+ const r = writeWinPolicy(values);
351
+ if (r.ok) written.push(paths.winPolicy);
352
+ else policyError = r.error;
353
+ }
354
+
355
+ const dir = paths.configLibrary();
356
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
357
+ const metaPath = path.join(dir, '_meta.json');
358
+ const meta = readJson(metaPath) || {};
359
+ if (!Array.isArray(meta.entries)) meta.entries = [];
360
+ let id = meta.appliedId;
361
+ if (!id || !fs.existsSync(path.join(dir, `${id}.json`))) {
362
+ id = crypto.randomUUID ? crypto.randomUUID() : `codemax-${Date.now()}`;
363
+ meta.appliedId = id;
364
+ if (!meta.entries.some((e) => e && e.id === id)) meta.entries.push({ id, name: 'CodeMax Gateway' });
365
+ }
366
+ const profile = path.join(dir, `${id}.json`);
367
+ // The local profile takes real types; only the OS policy store requires everything as strings.
368
+ writeJson(profile, {
369
+ ...values,
370
+ inferenceModels: MODELS,
371
+ coworkEgressAllowedHosts: EGRESS_HOSTS,
372
+ skipWebFetchPreflight: true,
373
+ disableNonessentialTelemetry: true,
374
+ });
375
+ writeJson(metaPath, meta);
376
+ written.push(profile);
377
+
378
+ const dev = path.join(paths.desktopBase(), 'developer_settings.json');
379
+ const devJson = readJson(dev) || {};
380
+ devJson.allowDevTools = true;
381
+ writeJson(dev, devJson);
382
+
383
+ return { written, machinePolicy, policyError };
384
+ }
385
+
386
+ /* Older versions put an `env` block in claude_desktop_config.json and an MCP server entry in
387
+ * .claude.json. Neither ever selected an inference endpoint — the first configures MCP servers,
388
+ * the second is unrelated — so they sat there doing nothing while looking like the thing that made
389
+ * this work. Cleaned on every run, because the key should not be left lying in a file the app
390
+ * hands to MCP server processes. */
391
+ function cleanLegacy() {
392
+ const removed = [];
393
+
394
+ const dcPath = IS_WIN
395
+ ? path.join(process.env.APPDATA || path.join(HOME, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json')
396
+ : IS_MAC
397
+ ? path.join(HOME, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
398
+ : path.join(HOME, '.config', 'Claude', 'claude_desktop_config.json');
399
+ const dc = readJson(dcPath);
400
+ if (dc && dc.env) {
401
+ let touched = false;
402
+ for (const k of ['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY']) {
403
+ if (k in dc.env) { delete dc.env[k]; touched = true; }
404
+ }
405
+ if (touched) {
406
+ if (Object.keys(dc.env).length === 0) delete dc.env;
407
+ writeJson(dcPath, dc);
408
+ removed.push(`${dcPath} (stale env block)`);
409
+ }
410
+ }
411
+
412
+ const cj = readJson(paths.claudeJson());
413
+ if (cj && cj.mcpServers && cj.mcpServers.CodeMax) {
414
+ delete cj.mcpServers.CodeMax;
415
+ if (Object.keys(cj.mcpServers).length === 0) delete cj.mcpServers;
416
+ cj.hasCompletedOnboarding = true;
417
+ writeJson(paths.claudeJson(), cj);
418
+ removed.push(`${paths.claudeJson()} (old MCP entry)`);
419
+ } else if (!cj) {
420
+ writeJson(paths.claudeJson(), { hasCompletedOnboarding: true });
421
+ }
422
+
423
+ // A persisted variable outranks the settings file, so leaving one behind quietly overrides
424
+ // everything written above.
425
+ if (IS_WIN) {
426
+ for (const v of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_MODEL',
427
+ 'ANTHROPIC_SMALL_FAST_MODEL', 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL',
428
+ 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC']) {
429
+ if (sh(`reg query "HKCU\\Environment" /v ${v}`)) {
430
+ sh(`REG delete "HKCU\\Environment" /v ${v} /f`);
431
+ removed.push(`Windows environment variable ${v}`);
432
+ }
433
+ }
434
+ }
435
+ return removed;
436
+ }
437
+
438
+ // ── Removing (reset) ─────────────────────────────────────────────────────────
439
+
440
+ /* Removes only what this tool set. Other people's settings in the same files are left exactly as
441
+ * they are — a reset that takes the whole file with it is not a reset, it is data loss. */
442
+ function resetAll() {
443
+ const removed = [];
444
+
445
+ const file = paths.cliSettings();
446
+ const json = readJson(file);
447
+ if (json && json.env) {
448
+ let touched = false;
449
+ for (const k of Object.keys(cliEnvVars('x'))) {
450
+ if (k in json.env) { delete json.env[k]; touched = true; }
451
+ }
452
+ if (touched) {
453
+ if (Object.keys(json.env).length === 0) delete json.env;
454
+ backup(file);
455
+ writeJson(file, json);
456
+ removed.push(`${file} (CodeMax variables only)`);
457
+ }
458
+ }
459
+
460
+ if (IS_WIN && sh(`reg query "${paths.winPolicy}"`)) {
461
+ sh(`reg delete "${paths.winPolicy}" /f`);
462
+ removed.push(paths.winPolicy);
463
+ }
464
+
465
+ const metaPath = path.join(paths.configLibrary(), '_meta.json');
466
+ const meta = readJson(metaPath);
467
+ if (meta && meta.appliedId) {
468
+ const p = path.join(paths.configLibrary(), `${meta.appliedId}.json`);
469
+ const prof = readJson(p);
470
+ // Only ours. Another profile in the same library belongs to whoever put it there.
471
+ if (prof && prof.inferenceGatewayBaseUrl === API_ENDPOINT) {
472
+ try { fs.unlinkSync(p); removed.push(p); } catch { /* */ }
473
+ delete meta.appliedId;
474
+ meta.entries = (meta.entries || []).filter((e) => !e || e.name !== 'CodeMax Gateway');
475
+ writeJson(metaPath, meta);
476
+ }
477
+ }
478
+ return removed;
479
+ }
480
+
481
+ module.exports = {
482
+ API_ENDPOINT, MODELS, EGRESS_HOSTS, IS_WIN, IS_MAC, HOME,
483
+ paths, sh, readJson, writeJson, backup, redact,
484
+ checkKey, readCliState, readDesktopState, readEnvConflicts, claudeCliInfo,
485
+ configureCli, configureDesktop, cleanLegacy, resetAll,
486
+ cliEnvVars, desktopValues, STALE_CLI_VARS,
487
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codemax-pro",
3
- "version": "1.4.1",
3
+ "version": "1.4.2",
4
4
  "description": "Setup for CodeMax — configures Claude Code CLI, VS Code, and Claude Desktop, with a doctor and reset",
5
5
  "main": "index.js",
6
6
  "bin": {