@bazilio-san/glm-cc 1.0.20 → 1.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,11 @@
1
1
  # @bazilio-san/glm-cc
2
2
 
3
- CLI tool for running Claude with custom GLM model configuration.
3
+ CLI tool for running Claude Code against a GLM-compatible API endpoint.
4
+
5
+ `glm` is a thin wrapper: it exports a handful of environment variables and then
6
+ tail-calls `claude` directly, with no Node process left in between. That matters
7
+ on Windows, where an intermediate process would break the parent terminal's
8
+ ConPty session and with it Claude Code's raw keyboard input.
4
9
 
5
10
  ## Installation
6
11
 
@@ -8,9 +13,12 @@ CLI tool for running Claude with custom GLM model configuration.
8
13
  npm install -g @bazilio-san/glm-cc
9
14
  ```
10
15
 
16
+ No runtime dependencies — the package is plain Node.js plus two shell scripts.
17
+
11
18
  ## Usage
12
19
 
13
- All arguments are passed through to `claude`, so you can use `glm` as a drop-in replacement:
20
+ All arguments are passed through to `claude`, so you can use `glm` as a drop-in
21
+ replacement:
14
22
 
15
23
  ```bash
16
24
  glm # launch claude interactively
@@ -24,23 +32,77 @@ glm mcp serve # claude mcp serve
24
32
  ### glm-specific commands
25
33
 
26
34
  ```bash
27
- glm -c # interactive configuration (alias: --glm-config)
28
- glm --glm-show # show current settings
29
- glm --glm-version # show glm version
35
+ glm -c # configuration menu (alias: --glm-config)
36
+ glm --glm-show # print the current settings
37
+ glm --glm-doctor # check the key, the endpoint and the models
38
+ glm --glm-version # print the glm version
39
+ glm --glm-help # list these flags
30
40
  ```
31
41
 
42
+ `-c` is consumed by glm and never reaches `claude`, so `claude -c`
43
+ (continue the previous session) is not available through `glm`.
44
+
32
45
  ## Configuration
33
46
 
34
- The tool stores configuration in `~/.glm-claude-code.json`.
47
+ Running `glm -c` opens an arrow-key menu that can:
48
+
49
+ - **Pick the API endpoint** — Z.AI Global, Z.AI China (BigModel), or any other
50
+ Anthropic-compatible URL you type in.
51
+ - **Set the API key** and verify it against the endpoint before saving. A
52
+ rejected key, an unreachable server and an HTTP error are reported separately,
53
+ so you can tell a wrong key from a network problem.
54
+ - **Choose the models** — keep the defaults, pick from the list of models your
55
+ key can actually use (fetched live from the provider), or type model ids by
56
+ hand. The `[1m]` suffix that unlocks a 1M-token context window and the
57
+ matching auto-compact threshold are derived from the model, not typed in.
58
+ - **Tune the advanced settings** — request timeout, non-essential traffic,
59
+ auto-compact window.
60
+ - **Run a health check** — configuration files, `claude` and `git` on PATH, key
61
+ validity, whether the selected models exist on the server, and whether
62
+ anything else on the machine would override what glm exports.
63
+ - **Remove the glm configuration** — deletes glm's own two files and nothing
64
+ else.
65
+
66
+ The first `glm` run starts the same wizard automatically when no configuration
67
+ exists yet.
68
+
69
+ ### Files
70
+
71
+ glm owns exactly two files and modifies nothing else:
72
+
73
+ | File | Purpose |
74
+ | --- | --- |
75
+ | `~/.glm-claude-code.json` | source of truth, edited through `glm -c` |
76
+ | `~/.glm-claude-code.env` | flat `KEY=VALUE` sidecar read by the launcher at every start |
77
+
78
+ **Claude Code's own configuration is never written to.** `~/.claude/settings.json`
79
+ and `~/.claude.json` are left alone; the health check reads `settings.json` only
80
+ to warn you when its `env` block would silently override glm's values, and tells
81
+ you to edit that file yourself.
82
+
83
+ ### Managed variables
84
+
85
+ | Variable | Default | Meaning |
86
+ | --- | --- | --- |
87
+ | `ANTHROPIC_BASE_URL` | `https://api.z.ai/api/anthropic` | API endpoint |
88
+ | `ANTHROPIC_AUTH_TOKEN` | — | bearer token sent with every request |
89
+ | `ANTHROPIC_DEFAULT_SONNET_MODEL` | `glm-5.3[1m]` | model for ordinary work |
90
+ | `ANTHROPIC_DEFAULT_OPUS_MODEL` | `glm-5.3[1m]` | model for the strongest tier |
91
+ | `ANTHROPIC_DEFAULT_HAIKU_MODEL` | `glm-5.3-flash[1m]` | model for cheap background tasks |
92
+ | `API_TIMEOUT_MS` | `3000000` | how long to wait for one reply (50 minutes) |
93
+ | `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | `1` | switch off optional telemetry |
94
+ | `CLAUDE_CODE_AUTO_COMPACT_WINDOW` | `1048576` | token count at which history is compacted |
95
+
96
+ Defaults only apply to settings you have never set; existing values are kept as
97
+ they are.
35
98
 
36
- Supported settings:
37
- - `ANTHROPIC_BASE_URL` — API endpoint (default: `https://api.z.ai/api/anthropic`)
38
- - `ANTHROPIC_AUTH_TOKEN` — primary auth token
39
- - `ANTHROPIC_DEFAULT_HAIKU_MODEL` — default Haiku model (default: `glm-4.5-air`)
40
- - `ANTHROPIC_DEFAULT_SONNET_MODEL` — default Sonnet model (default: `glm-5.1`)
41
- - `ANTHROPIC_DEFAULT_OPUS_MODEL` — default Opus model (default: `glm-5.1`)
99
+ ## What is out of scope
42
100
 
43
- If any setting is missing, the tool will automatically prompt for it on first run.
101
+ MCP servers and the plugin marketplace are not managed here. Both live in Claude
102
+ Code's own configuration (`~/.claude.json` and the plugin store) rather than in
103
+ environment variables, so managing them would mean writing to files glm
104
+ deliberately keeps its hands off. Use `claude mcp …` and `claude plugin …` for
105
+ those.
44
106
 
45
107
  ## License
46
108
 
package/bin/glm-config.js CHANGED
@@ -1,118 +1,100 @@
1
1
  #!/usr/bin/env node
2
- // Config UI + env file generator for @bazilio-san/glm-cc.
3
- // Invoked only when the user runs:
4
- // glm --glm-config | -c → interactive reconfiguration
5
- // glm --glm-show → print current config
6
- // glm --glm-version → print glm version
7
- // Or internally by glm.cmd / glm.sh on first launch (--setup) to populate
8
- // the KEY=VALUE env sidecar file from the JSON config.
2
+ // Configuration front-end for @bazilio-san/glm-cc.
9
3
  //
10
- // CRITICAL: this node process must NOT stay alive during `claude` execution.
11
- // The whole point of 1.0.20 is that glm's entry point is a shell script that
12
- // sets env vars and tail-calls claude directly, without a Node intermediate
13
- // process that would break the parent PTY's ConPty session propagation.
4
+ // Invoked when the user runs:
5
+ // glm -c | --glm-config → interactive configuration menu
6
+ // glm --glm-show → print the current settings
7
+ // glm --glm-doctor → health check
8
+ // glm --glm-version → print the glm version
9
+ // glm --glm-help → list the glm-specific flags
10
+ // Or internally by glm.cmd / glm.sh on first launch (--setup) to create
11
+ // ~/.glm-claude-code.env from ~/.glm-claude-code.json.
12
+ //
13
+ // CRITICAL: this Node process must NOT stay alive while `claude` runs. glm's
14
+ // entry point is a shell script that sets the environment variables and then
15
+ // tail-calls claude directly; a Node process sitting in between would break
16
+ // the parent terminal's ConPty session and with it Claude Code's raw keyboard
17
+ // input. Everything here therefore finishes and exits before claude starts.
14
18
 
15
- import path from 'node:path';
16
- import os from 'node:os';
17
- import fs from 'node:fs';
18
- import readline from 'node:readline';
19
19
  import { createRequire } from 'node:module';
20
20
 
21
+ import { ENV_PATH, JSON_PATH, isComplete, missingKeys, refreshEnv, load } from './lib/config.js';
22
+ import { runDoctor, runMainMenu, runSetup, showConfig } from './lib/wizard.js';
23
+ import { c, write } from './lib/ui.js';
24
+
21
25
  const require = createRequire(import.meta.url);
22
26
  const pkg = require('../package.json');
23
27
 
24
- const JSON_PATH = path.join(os.homedir(), '.glm-claude-code.json');
25
- const ENV_PATH = path.join(os.homedir(), '.glm-claude-code.env');
26
-
27
- const FIELDS = [
28
- { key: 'ANTHROPIC_BASE_URL', label: 'Anthropic Base URL', default: 'https://api.z.ai/api/anthropic' },
29
- { key: 'ANTHROPIC_AUTH_TOKEN', label: 'Anthropic Auth Token', default: '' },
30
- { key: 'ANTHROPIC_DEFAULT_HAIKU_MODEL', label: 'Default Haiku model', default: 'glm-4.5-air' },
31
- { key: 'ANTHROPIC_DEFAULT_SONNET_MODEL', label: 'Default Sonnet model', default: 'glm-5.1' },
32
- { key: 'ANTHROPIC_DEFAULT_OPUS_MODEL', label: 'Default Opus model', default: 'glm-5.1' },
33
- ];
34
-
35
- function loadJson () {
36
- try { return JSON.parse(fs.readFileSync(JSON_PATH, 'utf-8')); } catch { return {}; }
37
- }
38
-
39
- function saveJson (config) {
40
- fs.writeFileSync(JSON_PATH, JSON.stringify(config, null, 2), 'utf-8');
28
+ function printHelp () {
29
+ write('');
30
+ write(c.bold(`glm v${pkg.version}`));
31
+ write(c.gray(' Runs Claude Code against a GLM-compatible API endpoint.'));
32
+ write('');
33
+ write(c.bold('glm-specific flags'));
34
+ write(` ${'-c, --glm-config'.padEnd(20)} open the configuration menu`);
35
+ write(` ${'--glm-show'.padEnd(20)} print the current settings`);
36
+ write(` ${'--glm-doctor'.padEnd(20)} check the key, the endpoint and the models`);
37
+ write(` ${'--glm-version'.padEnd(20)} print the glm version`);
38
+ write(` ${'--glm-help'.padEnd(20)} this list`);
39
+ write('');
40
+ write(c.gray(' Every other argument is passed straight through to `claude`,'));
41
+ write(c.gray(' so `glm -p "hello"` and `glm mcp serve` behave as usual.'));
42
+ write(c.gray(' Note that -c is taken by glm and never reaches claude.'));
43
+ write('');
44
+ write(c.bold('Files glm owns'));
45
+ write(c.gray(` ${JSON_PATH}`));
46
+ write(c.gray(` ${ENV_PATH}`));
47
+ write(c.gray(' Claude Code\'s own configuration is never modified.'));
48
+ write('');
41
49
  }
42
50
 
43
- function saveEnv (config) {
44
- const header = '# Generated by @bazilio-san/glm-cc. Edit via `glm --glm-config`.';
45
- const body = FIELDS.map(f => `${f.key}=${config[f.key] ?? ''}`).join('\n');
46
- fs.writeFileSync(ENV_PATH, `${header}\n${body}\n`, 'utf-8');
47
- }
48
-
49
- function saveBoth (config) {
50
- saveJson(config);
51
- saveEnv(config);
52
- }
53
-
54
- function ask (rl, q) {
55
- return new Promise(resolve => rl.question(q, resolve));
56
- }
51
+ async function main () {
52
+ const args = process.argv.slice(2);
53
+ const has = (flag) => args.includes(flag);
57
54
 
58
- async function runInteractive (fieldsToAsk) {
59
- const config = loadJson();
60
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
61
- console.log('\nConfiguration (press Enter to keep current value):\n');
62
- for (const field of fieldsToAsk) {
63
- const current = config[field.key] || field.default;
64
- const hint = current ? ` [\x1b[32m${current}\x1b[0m]` : '';
65
- const answer = await ask(rl, `${field.label}${hint}: `);
66
- config[field.key] = answer.trim() !== '' ? answer.trim() : current;
55
+ if (has('--glm-version')) {
56
+ write(`glm v${pkg.version}`);
57
+ return 0;
67
58
  }
68
- rl.close();
69
- saveBoth(config);
70
- console.log(`\nSaved:\n ${JSON_PATH}\n ${ENV_PATH}\n`);
71
- return config;
72
- }
73
59
 
74
- function show (config) {
75
- console.log(`\nConfig: ${JSON_PATH}`);
76
- console.log(`Env: ${ENV_PATH}\n`);
77
- for (const f of FIELDS) {
78
- const v = config[f.key];
79
- console.log(` ${f.key} = ${v != null && v !== '' ? v : '(not set)'}`);
60
+ if (has('--glm-help')) {
61
+ printHelp();
62
+ return 0;
80
63
  }
81
- console.log('');
82
- }
83
-
84
- async function main () {
85
- const args = process.argv.slice(2);
86
64
 
87
- if (args.includes('--glm-version')) {
88
- console.log(`glm v${pkg.version}`);
89
- return;
90
- }
91
- if (args.includes('--glm-show')) {
92
- show(loadJson());
93
- return;
65
+ if (has('--glm-show')) {
66
+ showConfig();
67
+ return 0;
94
68
  }
95
- if (args.includes('--glm-config') || args.includes('-c')) {
96
- await runInteractive(FIELDS);
97
- return;
69
+
70
+ if (has('--glm-doctor')) {
71
+ const healthy = await runDoctor();
72
+ return healthy ? 0 : 1;
98
73
  }
99
- if (args.includes('--setup')) {
100
- // Invoked by glm.cmd / glm.sh when ~/.glm-claude-code.env is missing.
101
- // If JSON exists and is complete → just regenerate .env, no prompts.
102
- // Otherwise prompt only for missing fields.
103
- const config = loadJson();
104
- const missing = FIELDS.filter(f => !config[f.key]);
105
- if (missing.length === 0) {
106
- saveEnv(config);
107
- } else {
108
- console.log('Some glm settings are missing. Please fill them in:\n');
109
- await runInteractive(missing);
74
+
75
+ if (has('--setup')) {
76
+ // Called by glm.cmd / glm.sh when ~/.glm-claude-code.env is missing.
77
+ // A complete JSON just needs the sidecar rewritten; anything else means
78
+ // the user has to answer the setup questions.
79
+ const config = load();
80
+ if (isComplete(config)) {
81
+ refreshEnv();
82
+ return 0;
110
83
  }
111
- return;
84
+ const reason = Object.keys(config).length === 0
85
+ ? 'No glm configuration found yet.'
86
+ : `Some settings are missing: ${missingKeys(config).join(', ')}`;
87
+ const result = await runSetup(pkg.version, { reason });
88
+ return result ? 0 : 1;
112
89
  }
113
90
 
114
- // Fallback: invoked directly → treat as full reconfiguration.
115
- await runInteractive(FIELDS);
91
+ await runMainMenu(pkg.version);
92
+ return 0;
116
93
  }
117
94
 
118
- main().catch(err => { console.error(err.message); process.exit(1); });
95
+ main()
96
+ .then((code) => { process.exit(code); })
97
+ .catch((error) => {
98
+ write(c.red(`glm: ${error?.message || error}`));
99
+ process.exit(1);
100
+ });
package/bin/glm.cmd CHANGED
@@ -15,7 +15,7 @@ set "GLM_ARGS=%*"
15
15
 
16
16
  rem --- glm-specific flags are delegated to the node helper ----------------
17
17
  set "GLM_PAD= %GLM_ARGS% "
18
- echo.%GLM_PAD%| findstr /I /C:" --glm-config " /C:" --glm-show " /C:" --glm-version " /C:" -c " >nul
18
+ echo.%GLM_PAD%| findstr /I /C:" --glm-config " /C:" --glm-show " /C:" --glm-doctor " /C:" --glm-version " /C:" --glm-help " /C:" -c " >nul
19
19
  if not errorlevel 1 (
20
20
  node "%~dp0glm-config.js" %*
21
21
  exit /b %errorlevel%
package/bin/glm.sh CHANGED
@@ -18,7 +18,7 @@ GLM_ENV_FILE="${HOME}/.glm-claude-code.env"
18
18
 
19
19
  # --- glm-specific flags delegate to the node helper -----------------------
20
20
  case " $* " in
21
- *" --glm-config "*|*" -c "*|*" --glm-show "*|*" --glm-version "*)
21
+ *" --glm-config "*|*" -c "*|*" --glm-show "*|*" --glm-doctor "*|*" --glm-version "*|*" --glm-help "*)
22
22
  exec node "${GLM_BIN_DIR}/glm-config.js" "$@"
23
23
  ;;
24
24
  esac
package/bin/lib/api.js ADDED
@@ -0,0 +1,92 @@
1
+ // Talks to the provider's model-list route, which doubles as a key check:
2
+ // a 401 means the key is wrong, a network failure means the endpoint is
3
+ // unreachable, and a successful reply carries the list of usable model ids.
4
+
5
+ import { modelsUrlFor } from './models.js';
6
+
7
+ const TIMEOUT_MS = 30_000;
8
+
9
+ async function getJson (url, apiKey) {
10
+ const controller = new AbortController();
11
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
12
+ try {
13
+ const response = await fetch(url, {
14
+ method: 'GET',
15
+ headers: {
16
+ Authorization: `Bearer ${apiKey}`,
17
+ 'Content-Type': 'application/json',
18
+ },
19
+ signal: controller.signal,
20
+ });
21
+ let body = null;
22
+ try {
23
+ body = await response.json();
24
+ } catch {
25
+ body = null;
26
+ }
27
+ return { response, body };
28
+ } finally {
29
+ clearTimeout(timer);
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Check that the key works against the given endpoint.
35
+ * Returns { valid, reason, message } where reason is one of
36
+ * 'invalid_key' | 'unreachable' | 'bad_endpoint' | 'http_error'.
37
+ */
38
+ export async function validateApiKey (apiKey, baseUrl) {
39
+ const url = modelsUrlFor(baseUrl);
40
+ if (!url) {
41
+ return { valid: false, reason: 'bad_endpoint', message: `Cannot derive a model-list URL from ${baseUrl}` };
42
+ }
43
+
44
+ try {
45
+ const { response } = await getJson(url, apiKey);
46
+ if (response.status === 401 || response.status === 403) {
47
+ return { valid: false, reason: 'invalid_key', message: 'The server rejected this API key' };
48
+ }
49
+ if (response.ok) return { valid: true };
50
+ return {
51
+ valid: false,
52
+ reason: 'http_error',
53
+ message: `Server answered HTTP ${response.status} ${response.statusText}`.trim(),
54
+ };
55
+ } catch (error) {
56
+ const timedOut = error instanceof Error && error.name === 'AbortError';
57
+ return {
58
+ valid: false,
59
+ reason: 'unreachable',
60
+ message: timedOut ? `No answer within ${TIMEOUT_MS / 1000} seconds` : String(error?.message || error),
61
+ };
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Fetch the model ids available on this plan.
67
+ * Returns { models } on success, or { error } describing what went wrong.
68
+ */
69
+ export async function listModels (apiKey, baseUrl) {
70
+ const url = modelsUrlFor(baseUrl);
71
+ if (!url) return { error: `Cannot derive a model-list URL from ${baseUrl}` };
72
+
73
+ try {
74
+ const { response, body } = await getJson(url, apiKey);
75
+ if (response.status === 401 || response.status === 403) {
76
+ return { error: 'The server rejected this API key' };
77
+ }
78
+ if (!response.ok) return { error: `Server answered HTTP ${response.status}` };
79
+
80
+ const rows = Array.isArray(body?.data) ? body.data : null;
81
+ if (!rows) return { error: 'The server replied in an unexpected shape' };
82
+
83
+ const models = rows
84
+ .map(row => (typeof row === 'string' ? row : row?.id))
85
+ .filter(id => typeof id === 'string' && id.length > 0);
86
+
87
+ return models.length > 0 ? { models } : { error: 'The server returned an empty model list' };
88
+ } catch (error) {
89
+ const timedOut = error instanceof Error && error.name === 'AbortError';
90
+ return { error: timedOut ? `No answer within ${TIMEOUT_MS / 1000} seconds` : String(error?.message || error) };
91
+ }
92
+ }
@@ -0,0 +1,190 @@
1
+ // Storage layer for the glm configuration.
2
+ //
3
+ // Two files, both in the user's home directory and both owned entirely by glm:
4
+ // ~/.glm-claude-code.json source of truth, human-readable, edited by `glm -c`
5
+ // ~/.glm-claude-code.env flat KEY=VALUE sidecar that glm.cmd / glm.sh read
6
+ // at every launch without starting Node
7
+ //
8
+ // Claude Code's own files (~/.claude/settings.json, ~/.claude.json) are never
9
+ // read for writing and never modified: glm only ever exports environment
10
+ // variables into the process it launches.
11
+
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+
16
+ export const JSON_PATH = path.join(os.homedir(), '.glm-claude-code.json');
17
+ export const ENV_PATH = path.join(os.homedir(), '.glm-claude-code.env');
18
+
19
+ /**
20
+ * Every variable glm knows how to manage, in the order they are written to the
21
+ * env file. `label` is what the user sees; `secret` values are masked on screen.
22
+ */
23
+ export const FIELDS = [
24
+ {
25
+ key: 'ANTHROPIC_BASE_URL',
26
+ label: 'API endpoint',
27
+ describe: 'Anthropic-compatible server Claude Code talks to',
28
+ default: 'https://api.z.ai/api/anthropic',
29
+ required: true,
30
+ },
31
+ {
32
+ key: 'ANTHROPIC_AUTH_TOKEN',
33
+ label: 'API key',
34
+ describe: 'Bearer token sent with every request',
35
+ default: '',
36
+ required: true,
37
+ secret: true,
38
+ },
39
+ {
40
+ key: 'ANTHROPIC_DEFAULT_SONNET_MODEL',
41
+ label: 'Main model (Sonnet slot)',
42
+ describe: 'Model used for ordinary work',
43
+ default: 'glm-5.3[1m]',
44
+ required: true,
45
+ },
46
+ {
47
+ key: 'ANTHROPIC_DEFAULT_OPUS_MODEL',
48
+ label: 'Main model (Opus slot)',
49
+ describe: 'Model used when Claude Code asks for its strongest model',
50
+ default: 'glm-5.3[1m]',
51
+ required: true,
52
+ },
53
+ {
54
+ key: 'ANTHROPIC_DEFAULT_HAIKU_MODEL',
55
+ label: 'Small model (Haiku slot)',
56
+ describe: 'Model used for cheap background tasks',
57
+ default: 'glm-5.3-flash[1m]',
58
+ required: true,
59
+ },
60
+ {
61
+ key: 'API_TIMEOUT_MS',
62
+ label: 'Request timeout',
63
+ describe: 'Milliseconds Claude Code waits for a reply before giving up',
64
+ default: '3000000',
65
+ required: false,
66
+ },
67
+ {
68
+ key: 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC',
69
+ label: 'Non-essential traffic',
70
+ describe: 'Set to 1 to switch off optional telemetry and update pings',
71
+ default: '1',
72
+ required: false,
73
+ },
74
+ {
75
+ key: 'CLAUDE_CODE_AUTO_COMPACT_WINDOW',
76
+ label: 'Auto-compact window',
77
+ describe: 'Token count at which the conversation gets compacted',
78
+ default: '1048576',
79
+ required: false,
80
+ },
81
+ ];
82
+
83
+ export const DEFAULTS = Object.fromEntries(FIELDS.map(f => [f.key, f.default]));
84
+ export const REQUIRED_KEYS = FIELDS.filter(f => f.required).map(f => f.key);
85
+
86
+ export function fieldFor (key) {
87
+ return FIELDS.find(f => f.key === key) || null;
88
+ }
89
+
90
+ /** Read the stored configuration. Missing or broken file yields an empty object. */
91
+ export function load () {
92
+ try {
93
+ const parsed = JSON.parse(fs.readFileSync(JSON_PATH, 'utf-8'));
94
+ return parsed && typeof parsed === 'object' ? parsed : {};
95
+ } catch {
96
+ return {};
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Stored values with defaults filled in for anything the user has never set.
102
+ *
103
+ * A key stored as an empty string is not "unset" — it is an explicit "do not
104
+ * export this variable at all", so the default must not creep back in.
105
+ */
106
+ export function effective (config = load()) {
107
+ const merged = { ...DEFAULTS };
108
+ for (const [key, value] of Object.entries(config)) {
109
+ if (value != null) merged[key] = String(value);
110
+ }
111
+ return merged;
112
+ }
113
+
114
+ export function isComplete (config = load()) {
115
+ return REQUIRED_KEYS.every(key => {
116
+ const value = config[key] ?? DEFAULTS[key];
117
+ return value != null && String(value).trim() !== '';
118
+ });
119
+ }
120
+
121
+ export function missingKeys (config = load()) {
122
+ return REQUIRED_KEYS.filter(key => {
123
+ const value = config[key] ?? DEFAULTS[key];
124
+ return value == null || String(value).trim() === '';
125
+ });
126
+ }
127
+
128
+ function writeJson (config) {
129
+ // Keep a stable key order so the file stays reviewable in a diff.
130
+ const ordered = {};
131
+ for (const field of FIELDS) {
132
+ if (config[field.key] != null) ordered[field.key] = String(config[field.key]);
133
+ }
134
+ for (const [key, value] of Object.entries(config)) {
135
+ if (!(key in ordered) && value != null) ordered[key] = String(value);
136
+ }
137
+ fs.writeFileSync(JSON_PATH, `${JSON.stringify(ordered, null, 2)}\n`, 'utf-8');
138
+ }
139
+
140
+ function writeEnv (config) {
141
+ const values = effective(config);
142
+ const header = [
143
+ // Plain ASCII only: cmd.exe reads this file under whatever code page the
144
+ // console happens to be using.
145
+ '# Generated by @bazilio-san/glm-cc - do not edit by hand.',
146
+ '# Change these values with `glm -c`.',
147
+ '# Read by bin/glm.cmd and bin/glm.sh, then exported into `claude`.',
148
+ ];
149
+ const body = FIELDS
150
+ // An empty value means "leave this variable unset" rather than "set it to
151
+ // an empty string", so those lines are omitted entirely.
152
+ .filter(field => String(values[field.key] ?? '').trim() !== '')
153
+ .map(field => `${field.key}=${values[field.key]}`);
154
+ fs.writeFileSync(ENV_PATH, `${[...header, ...body].join('\n')}\n`, 'utf-8');
155
+ }
156
+
157
+ /** Persist to both files at once — they must never drift apart. */
158
+ export function save (config) {
159
+ writeJson(config);
160
+ writeEnv(config);
161
+ }
162
+
163
+ /** Regenerate only the env sidecar from the stored JSON. */
164
+ export function refreshEnv () {
165
+ writeEnv(load());
166
+ }
167
+
168
+ /** Delete both files. Returns the paths that actually existed. */
169
+ export function removeAll () {
170
+ const removed = [];
171
+ for (const file of [JSON_PATH, ENV_PATH]) {
172
+ if (fs.existsSync(file)) {
173
+ fs.unlinkSync(file);
174
+ removed.push(file);
175
+ }
176
+ }
177
+ return removed;
178
+ }
179
+
180
+ export function exists () {
181
+ return fs.existsSync(JSON_PATH);
182
+ }
183
+
184
+ /** Show only the first and last few characters of a secret. */
185
+ export function maskSecret (value) {
186
+ if (!value) return '';
187
+ const s = String(value);
188
+ if (s.length <= 10) return `${s.slice(0, 2)}${'•'.repeat(Math.max(2, s.length - 2))}`;
189
+ return `${s.slice(0, 4)}${'•'.repeat(8)}${s.slice(-4)}`;
190
+ }