@bazilio-san/glm-cc 1.0.19 → 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
 
@@ -0,0 +1,100 @@
1
+ #!/usr/bin/env node
2
+ // Configuration front-end for @bazilio-san/glm-cc.
3
+ //
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.
18
+
19
+ import { createRequire } from 'node:module';
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
+
25
+ const require = createRequire(import.meta.url);
26
+ const pkg = require('../package.json');
27
+
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('');
49
+ }
50
+
51
+ async function main () {
52
+ const args = process.argv.slice(2);
53
+ const has = (flag) => args.includes(flag);
54
+
55
+ if (has('--glm-version')) {
56
+ write(`glm v${pkg.version}`);
57
+ return 0;
58
+ }
59
+
60
+ if (has('--glm-help')) {
61
+ printHelp();
62
+ return 0;
63
+ }
64
+
65
+ if (has('--glm-show')) {
66
+ showConfig();
67
+ return 0;
68
+ }
69
+
70
+ if (has('--glm-doctor')) {
71
+ const healthy = await runDoctor();
72
+ return healthy ? 0 : 1;
73
+ }
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;
83
+ }
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;
89
+ }
90
+
91
+ await runMainMenu(pkg.version);
92
+ return 0;
93
+ }
94
+
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 ADDED
@@ -0,0 +1,45 @@
1
+ :; SCRIPT="$(readlink -f "$0" 2>/dev/null || echo "$0")"; exec "$(dirname "$SCRIPT")/glm.sh" "$@"
2
+ @echo off
3
+ rem -------------------------------------------------------------------------
4
+ rem glm — launch claude with GLM env vars. Runs as a pure cmd.exe script so
5
+ rem that no intermediate node process sits between the caller (PTY / terminal)
6
+ rem and claude.exe. Critical for parent-PTY scenarios where the ConPty session
7
+ rem must reach claude directly for Ink-based raw-keyboard input to work.
8
+ rem
9
+ rem First line is a bash/batch polyglot:
10
+ rem bash : `:` = no-op, `;` separator, `exec` replaces shell with glm.sh
11
+ rem cmd : `:;` = malformed label, skipped silently
12
+ rem -------------------------------------------------------------------------
13
+
14
+ set "GLM_ARGS=%*"
15
+
16
+ rem --- glm-specific flags are delegated to the node helper ----------------
17
+ set "GLM_PAD= %GLM_ARGS% "
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
+ if not errorlevel 1 (
20
+ node "%~dp0glm-config.js" %*
21
+ exit /b %errorlevel%
22
+ )
23
+
24
+ rem --- First-time setup if env file is missing ----------------------------
25
+ set "GLM_ENV_FILE=%USERPROFILE%\.glm-claude-code.env"
26
+ if not exist "%GLM_ENV_FILE%" (
27
+ node "%~dp0glm-config.js" --setup
28
+ if errorlevel 1 exit /b 1
29
+ if not exist "%GLM_ENV_FILE%" (
30
+ echo glm: setup did not produce %GLM_ENV_FILE% 1>&2
31
+ exit /b 1
32
+ )
33
+ )
34
+
35
+ rem --- Load env vars from KEY=VALUE file ----------------------------------
36
+ rem Note: with `tokens=1,*` the second token is %%L (letter after %%K),
37
+ rem not %%V — `for /f` names extra tokens sequentially by letter.
38
+ for /f "usebackq eol=# tokens=1,* delims==" %%K in ("%GLM_ENV_FILE%") do (
39
+ set "%%K=%%L"
40
+ )
41
+
42
+ rem --- Tail-call claude directly. `claude.exe` becomes a child of the
43
+ rem outer (PTY-attached) cmd.exe process, not of any node intermediate.
44
+ claude %*
45
+ exit /b %errorlevel%
package/bin/glm.sh ADDED
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env bash
2
+ # glm — launch claude with GLM env vars (POSIX/Unix side).
3
+ # Kept as a pure shell script (no node intermediate) so the parent terminal's
4
+ # TTY reaches claude directly. Counterpart of bin/glm.cmd on Windows.
5
+
6
+ set -e
7
+
8
+ # Resolve real script dir (follow symlinks — npm links bin -> bin/glm.cmd → .sh via polyglot)
9
+ _glm_src="${BASH_SOURCE[0]:-$0}"
10
+ if command -v readlink >/dev/null 2>&1; then
11
+ _glm_real="$(readlink -f "$_glm_src" 2>/dev/null || echo "$_glm_src")"
12
+ else
13
+ _glm_real="$_glm_src"
14
+ fi
15
+ GLM_BIN_DIR="$(cd "$(dirname "$_glm_real")" && pwd)"
16
+
17
+ GLM_ENV_FILE="${HOME}/.glm-claude-code.env"
18
+
19
+ # --- glm-specific flags delegate to the node helper -----------------------
20
+ case " $* " in
21
+ *" --glm-config "*|*" -c "*|*" --glm-show "*|*" --glm-doctor "*|*" --glm-version "*|*" --glm-help "*)
22
+ exec node "${GLM_BIN_DIR}/glm-config.js" "$@"
23
+ ;;
24
+ esac
25
+
26
+ # --- First-time setup -----------------------------------------------------
27
+ if [ ! -f "$GLM_ENV_FILE" ]; then
28
+ node "${GLM_BIN_DIR}/glm-config.js" --setup
29
+ if [ ! -f "$GLM_ENV_FILE" ]; then
30
+ echo "glm: setup did not produce $GLM_ENV_FILE" >&2
31
+ exit 1
32
+ fi
33
+ fi
34
+
35
+ # --- Load env vars and tail-call claude -----------------------------------
36
+ set -a
37
+ # shellcheck disable=SC1090
38
+ . "$GLM_ENV_FILE"
39
+ set +a
40
+
41
+ exec claude "$@"
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
+ }
@@ -0,0 +1,97 @@
1
+ // Model and endpoint registry.
2
+ //
3
+ // Two things are derived from a model id and cannot be guessed by Claude Code
4
+ // on its own:
5
+ // * the `[1m]` suffix, which Claude Code requires to unlock a 1M-token
6
+ // context window;
7
+ // * CLAUDE_CODE_AUTO_COMPACT_WINDOW, the token count at which Claude Code
8
+ // starts compacting the conversation history.
9
+ // Both come out of the context-window table below.
10
+
11
+ export const ENDPOINTS = [
12
+ {
13
+ id: 'global',
14
+ label: 'Z.AI Global',
15
+ baseUrl: 'https://api.z.ai/api/anthropic',
16
+ modelsUrl: 'https://api.z.ai/api/coding/paas/v4/models',
17
+ apiKeysUrl: 'https://z.ai/manage-apikey/apikey-list',
18
+ },
19
+ {
20
+ id: 'china',
21
+ label: 'Z.AI China (BigModel)',
22
+ baseUrl: 'https://open.bigmodel.cn/api/anthropic',
23
+ modelsUrl: 'https://open.bigmodel.cn/api/coding/paas/v4/models',
24
+ apiKeysUrl: 'https://bigmodel.cn/usercenter/proj-mgmt/apikeys',
25
+ },
26
+ ];
27
+
28
+ export function findEndpoint (baseUrl) {
29
+ return ENDPOINTS.find(e => e.baseUrl === baseUrl) || null;
30
+ }
31
+
32
+ /**
33
+ * Where to ask for the model list / validate a key for a given Anthropic base
34
+ * URL. Known endpoints are looked up; a custom URL is mapped by swapping the
35
+ * `/api/anthropic` tail, and failing that by falling back to the host root.
36
+ */
37
+ export function modelsUrlFor (baseUrl) {
38
+ const known = findEndpoint(baseUrl);
39
+ if (known) return known.modelsUrl;
40
+ if (!baseUrl) return null;
41
+ try {
42
+ if (baseUrl.endsWith('/api/anthropic')) {
43
+ return `${baseUrl.slice(0, -'/api/anthropic'.length)}/api/coding/paas/v4/models`;
44
+ }
45
+ return `${new URL(baseUrl).origin}/api/coding/paas/v4/models`;
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
51
+ /** Known model id -> context window in tokens. */
52
+ export const MODEL_CONTEXT_WINDOWS = {
53
+ 'glm-5.3-flash': 1_048_576,
54
+ 'glm-5.3': 1_048_576,
55
+ 'glm-5.2': 1_048_576,
56
+ 'glm-5.1': 200_000,
57
+ 'glm-5': 200_000,
58
+ 'glm-5-turbo': 204_800,
59
+ 'glm-4.7': 200_000,
60
+ 'glm-4.6': 200_000,
61
+ 'glm-4.5': 128_000,
62
+ 'glm-4.5-air': 128_000,
63
+ };
64
+
65
+ /** Safe context window for a model id that is not in the table. */
66
+ export const FALLBACK_CONTEXT_WINDOW = 200_000;
67
+
68
+ /** Claude Code needs this suffix to open a 1M-token context window. */
69
+ const ONE_MILLION_SUFFIX = /\[1m\]$/i;
70
+
71
+ export function stripSuffix (model) {
72
+ return model ? String(model).replace(ONE_MILLION_SUFFIX, '') : '';
73
+ }
74
+
75
+ export function contextWindowFor (model) {
76
+ const key = stripSuffix(model).toLowerCase();
77
+ return MODEL_CONTEXT_WINDOWS[key] ?? FALLBACK_CONTEXT_WINDOW;
78
+ }
79
+
80
+ /** Append `[1m]` when the model's context window reaches one million tokens. */
81
+ export function formatForClaudeCode (model) {
82
+ const bare = stripSuffix(model);
83
+ if (!bare) return bare;
84
+ return contextWindowFor(bare) >= 1_000_000 ? `${bare}[1m]` : bare;
85
+ }
86
+
87
+ export function formatTokens (n) {
88
+ return Number(n).toLocaleString('en-US');
89
+ }
90
+
91
+ /** Human-readable context size, e.g. "1,048,576 tokens (1M)". */
92
+ export function describeContext (model) {
93
+ const size = contextWindowFor(model);
94
+ const known = Object.prototype.hasOwnProperty.call(MODEL_CONTEXT_WINDOWS, stripSuffix(model).toLowerCase());
95
+ const short = size >= 1_000_000 ? ' (1M)' : '';
96
+ return `${formatTokens(size)} tokens${short}${known ? '' : ', assumed'}`;
97
+ }