@euraika-bert/claude-model-router 0.1.6 → 0.1.7
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 +22 -10
- package/files/configure.mjs +17 -0
- package/files/kimi-router.mjs +43 -13
- package/files/models-sync.mjs +2 -1
- package/files/secrets.mjs +1 -0
- package/files/update-check.mjs +1 -1
- package/install.ps1 +2 -1
- package/install.sh +2 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,6 +10,7 @@ Available through `/model`, each only for the providers you have a key or login
|
|
|
10
10
|
- **Qwen 3.8/3.7 Max**, **DeepSeek V4 Pro**, **DeepSeek V4.1 Flash** and **GLM 5.3** with 1M context, through Alibaba Cloud Bailian (token plan, region `ap-southeast-1`).
|
|
11
11
|
- **GPT 6 Astra**, **GPT 6.1 Terra**, **GPT 6.1 Sol** and **GPT 5.6 Luna** through your ChatGPT account (the Codex CLI login).
|
|
12
12
|
- **MiniMax M3.1 Flash** and **MiniMax M3** with 1M context, through a MiniMax M Plan API key.
|
|
13
|
+
- **GLM 5.3** and **GLM 5.3 Flash** with 1M context, through a Z.ai GLM Coding Plan API key (as `zai/glm-5.3[1m]` and `zai/glm-5.3-flash[1m]`).
|
|
13
14
|
- **Auto-added models** from the Mistral, Kimi and ChatGPT/Codex catalogs; see [Automatic model sync](#automatic-model-sync).
|
|
14
15
|
|
|
15
16
|
## Quick start
|
|
@@ -51,6 +52,7 @@ Claude Code sends its API requests to `http://127.0.0.1:8765`. The router reads
|
|
|
51
52
|
| `qwen*`, `deepseek*`, `glm*` (e.g. `qwen3.8-max[1m]`, `deepseek-v4-pro[1m]`, `glm-5.3[1m]`), except `zai-glm-*` and IDs from the Mistral catalog | `token-plan.ap-southeast-1.maas.aliyuncs.com/apps/anthropic` | Bailian token-plan API key (macOS Keychain, Linux key file, Windows DPAPI file) |
|
|
52
53
|
| `gpt-*` (e.g. `gpt-6-astra`, `gpt-6.1-sol`) | `chatgpt.com/backend-api/codex/responses` | ChatGPT OAuth login of the Codex CLI (`~/.codex/auth.json`, `codex login`), refreshed automatically |
|
|
53
54
|
| `MiniMax-*` (e.g. `MiniMax-M3.1-Flash[1m]`, `MiniMax-M3[1m]`) | `api.minimax.io/anthropic` | MiniMax M Plan API key (macOS Keychain, Linux key file, Windows DPAPI file) |
|
|
55
|
+
| `zai/*` (e.g. `zai/glm-5.3[1m]`, `zai/glm-5.3-flash[1m]`) | `api.z.ai/api/anthropic` (`zai/` and `[1m]` stripped) | Z.ai GLM Coding Plan API key (macOS Keychain, Linux key file, Windows DPAPI file) |
|
|
54
56
|
| All other models | `api.anthropic.com` | Your existing Claude Code login, forwarded unchanged |
|
|
55
57
|
|
|
56
58
|
**Claude models.** Claude Code treats an `ANTHROPIC_BASE_URL` that does not point to `api.anthropic.com` as a third-party gateway and then shows a built-in, outdated model list, for example Fable 5.1 instead of Fable 5.2. The router forwards Claude requests unchanged, so the installer sets `_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL=1`. Claude Code then fetches the current model list from Anthropic itself, and new Claude models show up in `/model` on their own.
|
|
@@ -59,13 +61,15 @@ Claude Code sends its API requests to `http://127.0.0.1:8765`. The router reads
|
|
|
59
61
|
|
|
60
62
|
**MiniMax.** This route uses MiniMax's Anthropic-compatible endpoint (M Plan) and works like the Aliyun route: requests are forwarded 1:1 with the key as a Bearer token and the `[1m]` suffix is stripped (MiniMax itself rejects it: `unknown model`). The host can be overridden with `MINIMAX_ANTHROPIC_HOST` (the path is fixed at `/anthropic`). The catalog (`/v1/models`) also lists retired M2.x models and no context sizes, so MiniMax models are not synced automatically; curate them in `files/configure.mjs` after a real test.
|
|
61
63
|
|
|
64
|
+
**Z.ai.** This route uses the Anthropic-compatible endpoint of the Z.ai GLM Coding Plan and works like the MiniMax route. Z.ai uses the same model IDs as the Aliyun route (`glm-5.3`), so in `/model` they carry a `zai/` prefix; the router strips it, together with `[1m]`, before forwarding. The host can be overridden with `ZAI_ANTHROPIC_HOST` (the path is fixed at `/api/anthropic`).
|
|
65
|
+
|
|
62
66
|
**Mistral and GLM.** The router translates Anthropic Messages to and from Mistral's OpenAI-compatible format, including streaming, images, tool calls and the effort level. Each Mistral model accepts a different set of `reasoning_effort` values, or none at all. When a request is rejected, the router reads the accepted values from the error message and retries with the closest one. What it learns this way is remembered until the router restarts.
|
|
63
67
|
|
|
64
68
|
**ChatGPT/Codex.** The router translates to the OpenAI Responses API of the Codex backend, following the request shape of the Codex CLI: the effort level you pick, the model's encrypted reasoning carried across tool calls, and a stable session for the prompt cache. The backend only supports streaming; non-streaming requests are streamed internally and returned as one message. The login (`~/.codex/auth.json`) is refreshed before it expires: 5 minutes ahead, one refresh at a time, written atomically. Which models your account offers is listed in the Codex catalog; the router adds them automatically. Class mapping: astra = Fable, sol = Opus, terra = Sonnet, luna = Haiku. The Codex models have 272k context (the 6.1 models 500k), not 1M. They are therefore listed in `/model` without `[1m]`, with `autoCompactWindow` at 95% of the context, the same way the Codex CLI counts.
|
|
65
69
|
|
|
66
70
|
**Prompt caching.** Claude Code puts a billing header in the system prompt that changes on every request. Anthropic ignores it for caching, but other providers would treat it as prompt text and miss their cache on every turn, so the router removes it on all non-Anthropic routes. Cached tokens are reported to Claude Code the way Anthropic does (not counted twice).
|
|
67
71
|
|
|
68
|
-
**Tools.** Dynamic `ToolSearch` tools go to all routes. MCP tools that Claude Code sends as `tool_addition` blocks are turned into regular `tools` entries for Kimi, Aliyun and
|
|
72
|
+
**Tools.** Dynamic `ToolSearch` tools go to all routes. MCP tools that Claude Code sends as `tool_addition` blocks are turned into regular `tools` entries for Kimi, Aliyun, MiniMax and Z.ai. Tools without an `input_schema` (e.g. the `advisor` tool) get an explicit empty schema; MiniMax rejects them otherwise with `function parameters is empty (2013)`.
|
|
69
73
|
|
|
70
74
|
**Quota failover.** When a provider hits its usage limit (HTTP 429/402, or 403 with a quota message such as `AccessDenied.Unpurchased` or `Throttling`), the router retries the request on a model of the same class at another provider, never at Anthropic:
|
|
71
75
|
|
|
@@ -74,6 +78,7 @@ Claude Code sends its API requests to `http://127.0.0.1:8765`. The router reads
|
|
|
74
78
|
- Mistral → `qwen3.8-max` → `k3.1-pro`
|
|
75
79
|
- ChatGPT → `qwen3.8-max` → `zai-glm-5-3`
|
|
76
80
|
- MiniMax → `qwen3.8-max` → `k3.1-pro`
|
|
81
|
+
- Z.ai → `zai-glm-5-3` (same model via Mistral) → `glm-5.3` (Aliyun) → `k3.1-pro`
|
|
77
82
|
|
|
78
83
|
Providers without a key or login are skipped in the chain. A provider that returned a quota error is skipped for 5 minutes and then tried again automatically. If the last model in the chain fails too, Claude Code gets that error. Switches are logged (`Quota limit on ...; switching to ...`): on macOS and Linux in `~/.claude/logs/kimi-router.error.log`, on Windows in `%USERPROFILE%\.claude\logs\kimi-router.log`.
|
|
79
84
|
|
|
@@ -116,6 +121,7 @@ What the sync does:
|
|
|
116
121
|
- **Qwen, DeepSeek and GLM via Aliyun:** a Bailian token-plan API key for region `ap-southeast-1`.
|
|
117
122
|
- **ChatGPT (GPT models):** the Codex CLI with an active login via `codex login` (ChatGPT account).
|
|
118
123
|
- **MiniMax (M Plan):** a MiniMax M Plan API key from [platform.minimax.io](https://platform.minimax.io/console/plan).
|
|
124
|
+
- **Z.ai (GLM Coding Plan):** a GLM Coding Plan API key from [z.ai](https://z.ai/manage-apikey/apikey-list).
|
|
119
125
|
|
|
120
126
|
## Install and update via npm (macOS, Linux, Windows)
|
|
121
127
|
|
|
@@ -141,8 +147,8 @@ The installer:
|
|
|
141
147
|
|
|
142
148
|
1. copies the router files to `~/.claude/` and a backup copy to `~/.local/share/claude-model-router/`;
|
|
143
149
|
2. installs the recovery command as `~/.local/bin/claude-model-router-setup`;
|
|
144
|
-
3. asks for your Mistral API key, Aliyun token-plan key
|
|
145
|
-
4. detects which providers are usable: the Keychain items `claude-code-mistral`/`claude-code-aliyun`/`claude-code-minimax`, `kimi login` and `codex login`;
|
|
150
|
+
3. asks for your Mistral API key, Aliyun token-plan key, MiniMax M Plan key and Z.ai GLM Coding Plan key with a hidden prompt if they are not in the Keychain yet (Enter = skip);
|
|
151
|
+
4. detects which providers are usable: the Keychain items `claude-code-mistral`/`claude-code-aliyun`/`claude-code-minimax`/`claude-code-zai`, `kimi login` and `codex login`;
|
|
146
152
|
5. backs up `~/.claude/settings.json` to `~/.claude/backups/` and writes only the settings of those providers; entries of providers without a login are removed;
|
|
147
153
|
6. installs and starts `com.bert.claude-kimi-router` as a LaunchAgent, and shows which providers were skipped and how to enable them.
|
|
148
154
|
|
|
@@ -151,7 +157,7 @@ Then restart Claude Code and open `/model`. To add a provider later: set up the
|
|
|
151
157
|
Non-interactive install:
|
|
152
158
|
|
|
153
159
|
```bash
|
|
154
|
-
MISTRAL_API_KEY='...' ALIYUN_API_KEY='...' MINIMAX_API_KEY='...' ./install.sh
|
|
160
|
+
MISTRAL_API_KEY='...' ALIYUN_API_KEY='...' MINIMAX_API_KEY='...' ZAI_API_KEY='...' ./install.sh
|
|
155
161
|
```
|
|
156
162
|
|
|
157
163
|
These variables can end up in your shell history, so the hidden interactive prompt is preferred.
|
|
@@ -168,7 +174,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1
|
|
|
168
174
|
|
|
169
175
|
The Windows install does the same as `install.sh`, with these differences:
|
|
170
176
|
|
|
171
|
-
- **Keys:** the Mistral, Aliyun and
|
|
177
|
+
- **Keys:** the Mistral, Aliyun, MiniMax and Z.ai keys are stored DPAPI-encrypted in `%LOCALAPPDATA%\claude-model-router\` (`claude-code-mistral.dpapi`, `claude-code-aliyun.dpapi`, `claude-code-minimax.dpapi`, `claude-code-zai.dpapi`). Only your Windows account can decrypt them.
|
|
172
178
|
- **Router:** runs as the scheduled task `claude-model-router`, started at logon. A hidden PowerShell loop (`%USERPROFILE%\.claude\kimi-router-run.ps1`) restarts the router within 2 seconds after a crash. A window may flash briefly at logon.
|
|
173
179
|
- **Log:** stdout and stderr go to one file: `%USERPROFILE%\.claude\logs\kimi-router.log`.
|
|
174
180
|
- **Reinstall:** a new install stops the running router; the loop restarts it right away with the new files.
|
|
@@ -179,7 +185,7 @@ Kimi and ChatGPT/Codex work as soon as `kimi login` and `codex login` put their
|
|
|
179
185
|
Non-interactive install:
|
|
180
186
|
|
|
181
187
|
```powershell
|
|
182
|
-
$env:MISTRAL_API_KEY = '...'; $env:ALIYUN_API_KEY = '...'; $env:MINIMAX_API_KEY = '...'
|
|
188
|
+
$env:MISTRAL_API_KEY = '...'; $env:ALIYUN_API_KEY = '...'; $env:MINIMAX_API_KEY = '...'; $env:ZAI_API_KEY = '...'
|
|
183
189
|
powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1
|
|
184
190
|
```
|
|
185
191
|
|
|
@@ -189,7 +195,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1
|
|
|
189
195
|
|
|
190
196
|
Use the npm command or the same `./install.sh` as on macOS. On Linux these things differ:
|
|
191
197
|
|
|
192
|
-
- **Keys:** each key is a separate file with mode `600` in `~/.config/claude-model-router/` (`claude-code-mistral`, `claude-code-aliyun`, `claude-code-minimax`; respects `XDG_CONFIG_HOME`). Linux has no keychain a background service can always reach; the Codex and Kimi logins store their tokens the same way.
|
|
198
|
+
- **Keys:** each key is a separate file with mode `600` in `~/.config/claude-model-router/` (`claude-code-mistral`, `claude-code-aliyun`, `claude-code-minimax`, `claude-code-zai`; respects `XDG_CONFIG_HOME`). Linux has no keychain a background service can always reach; the Codex and Kimi logins store their tokens the same way.
|
|
193
199
|
- **Service:** a systemd user service `claude-model-router.service` in `~/.config/systemd/user/`. It starts when you log in. To run the router without a login session too (e.g. over SSH): `loginctl enable-linger $USER`.
|
|
194
200
|
- **Logs:** the same files as on macOS, in `~/.claude/logs/`.
|
|
195
201
|
- **Restart:** `systemctl --user restart claude-model-router`.
|
|
@@ -221,7 +227,7 @@ On Windows: `Invoke-RestMethod http://127.0.0.1:8765/__health`.
|
|
|
221
227
|
The response includes:
|
|
222
228
|
|
|
223
229
|
- `version`, `latestVersion` and `updateAvailable` (the installed version and the latest on npm);
|
|
224
|
-
- `kimiLoginAvailable`, `mistralLoginAvailable`, `aliyunLoginAvailable`, `codexLoginAvailable` and `
|
|
230
|
+
- `kimiLoginAvailable`, `mistralLoginAvailable`, `aliyunLoginAvailable`, `codexLoginAvailable`, `minimaxLoginAvailable` and `zaiLoginAvailable`;
|
|
225
231
|
- `modelSync`, with `syncedAt`, the number of models and any errors per provider, `pickerManaged` (the auto-added entries) and `probeFailures`.
|
|
226
232
|
|
|
227
233
|
Then check in Claude Code:
|
|
@@ -250,6 +256,11 @@ The parser for Mistral effort values has its own check: `node test/mistral-effor
|
|
|
250
256
|
- Linux: `~/.config/claude-model-router/claude-code-minimax` (mode `600`);
|
|
251
257
|
- Windows: `claude-code-minimax.dpapi`;
|
|
252
258
|
- or the `MINIMAX_API_KEY` environment variable of the router process.
|
|
259
|
+
- **Z.ai (GLM Coding Plan):**
|
|
260
|
+
- macOS: Keychain item `claude-code-zai`;
|
|
261
|
+
- Linux: `~/.config/claude-model-router/claude-code-zai` (mode `600`);
|
|
262
|
+
- Windows: `claude-code-zai.dpapi`;
|
|
263
|
+
- or the `ZAI_API_KEY` environment variable of the router process.
|
|
253
264
|
- **ChatGPT/Codex:** the Codex CLI's OAuth login in `~/.codex/auth.json`. The router refreshes the token via `auth.openai.com` and writes it back atomically.
|
|
254
265
|
- **Claude:** the router stores no Anthropic token; incoming authentication is only forwarded to `api.anthropic.com`.
|
|
255
266
|
- The router keeps keys in memory for 5 minutes. On Windows it decrypts them through Windows PowerShell, which slows the first request after those 5 minutes slightly (not measured).
|
|
@@ -271,6 +282,7 @@ The parser for Mistral effort values has its own check: `node test/mistral-effor
|
|
|
271
282
|
- **macOS, end to end (17 November 2026):** all 23 models with available quota in `/model` (Codex 9, Mistral 12, MiniMax 2) pass non-streaming, streaming and a tool round trip through the router (`x-router-probe: 1`), plus real Claude Code sessions on Claude Haiku, Mistral Medium, GLM 5.3, DeepSeek, MiniMax M3.1-Flash and GPT 6.1 Terra/Sol.
|
|
272
283
|
- **Linux (17 November 2026):** tested on Ubuntu 22.04 with real systemd, in an isolated `HOME`: install and service, plus real requests and Claude Code sessions for Mistral, ChatGPT/Codex and MiniMax. Not tested: Kimi and Aliyun (quota exhausted) and a machine without `enable-linger`.
|
|
273
284
|
- **MiniMax (13 November 2026):** fully tested for `MiniMax-M3.1-Flash[1m]` and `MiniMax-M3[1m]`. The first attempt failed in real sessions with `function parameters is empty (2013)`: Claude Code sends tools without `input_schema` (e.g. `advisor`) and MiniMax rejects them after conversion; the router now gives such tools an explicit empty schema.
|
|
285
|
+
- **Z.ai (19 November 2026):** `zai/glm-5.3[1m]` and `zai/glm-5.3-flash[1m]` pass non-streaming tool use (including a tool without `input_schema`), streaming after a tool result (`message_stop`) and real `claude -p` sessions with the Read tool. Context: a needle-in-a-haystack prompt of 995,517 tokens is answered correctly by both models; about 1.05M is rejected with `400 [1261] prompt is too long`. Prompt caching works: a repeated 52k prompt is read 99.9% from cache, and three-turn Claude Code sessions read 34–37k tokens from cache per turn (about 91%). Tool calling: parallel calls (3 at once) with their results, streamed `tool_use` (`input_json_delta` reassembles to valid JSON), MCP tools sent as `tool_addition`, and a six-turn `claude -p` bug-fix task (Write, Bash, Edit, Bash) all work. Z.ai ignores a forced `tool_choice` (`tool` or `any`; also directly upstream, with or without thinking) and answers with text; Claude Code normally uses `auto`.
|
|
274
286
|
- **Kimi and Aliyun:** not retested with real requests after the recent changes, because both quotas were exhausted; the Aliyun quota resets on 5 December 2026, 16:00 UTC. New Kimi catalog models are added automatically once their test passes.
|
|
275
287
|
- **Windows:** only tested in a container. Not yet proven on real Windows: DPAPI encryption, Windows PowerShell 5.1, registering the scheduled task, the hidden window, Claude Code on Windows, the login locations of `kimi login` and `codex login`, and the npm `upgrade` command.
|
|
276
288
|
|
|
@@ -322,11 +334,11 @@ The macOS Keychain items and the Kimi and Codex logins stay in place unless you
|
|
|
322
334
|
- `install.sh` — install and recovery on macOS and Linux.
|
|
323
335
|
- `install.ps1` — install on Windows.
|
|
324
336
|
- `files/configure.mjs` — writes the router settings into `settings.json` for the providers with a key or login; used by both installers.
|
|
325
|
-
- `files/kimi-router.mjs` — the localhost router: model routing, Kimi, Aliyun and
|
|
337
|
+
- `files/kimi-router.mjs` — the localhost router: model routing, Kimi, Aliyun, MiniMax and Z.ai forwarding, quota failover and `/__health`.
|
|
326
338
|
- `files/kimi-oauth.mjs` — Kimi OAuth token refresh with shared credentials.
|
|
327
339
|
- `files/mistral.mjs` — translation between Anthropic and Mistral, including the `reasoning_effort` fallback.
|
|
328
340
|
- `files/codex.mjs` — ChatGPT/Codex route: OAuth refresh from `~/.codex/auth.json` and translation between Anthropic Messages and the OpenAI Responses API.
|
|
329
|
-
- `files/secrets.mjs` — reads the Mistral, Aliyun and
|
|
341
|
+
- `files/secrets.mjs` — reads the Mistral, Aliyun, MiniMax and Z.ai keys from the macOS Keychain, a DPAPI file (Windows) or a mode-`600` file (Linux).
|
|
330
342
|
- `files/models-sync.mjs` — automatic sync of the Mistral, Kimi and Codex catalogs, plus the login check per provider.
|
|
331
343
|
- `files/update-check.mjs` — version number and daily update check (via `/__health`); with `--session-notice`, the notice for the SessionStart hook.
|
|
332
344
|
- `files/com.bert.claude-kimi-router.plist` — LaunchAgent configuration (macOS).
|
package/files/configure.mjs
CHANGED
|
@@ -9,6 +9,7 @@ const PROVIDERS = {
|
|
|
9
9
|
mistral: ['Mistral (incl. GLM via Mistral)', 'enter a Mistral API key in the installer'],
|
|
10
10
|
aliyun: ['Aliyun (Qwen/DeepSeek/GLM)', 'enter an Aliyun token-plan key in the installer'],
|
|
11
11
|
minimax: ['MiniMax (M Plan)', 'enter a MiniMax M Plan API key in the installer'],
|
|
12
|
+
zai: ['Z.ai (GLM Coding Plan)', 'enter a Z.ai GLM Coding Plan API key in the installer'],
|
|
12
13
|
kimi: ['Kimi', 'kimi login'],
|
|
13
14
|
codex: ['ChatGPT/Codex', 'codex login'],
|
|
14
15
|
};
|
|
@@ -159,6 +160,22 @@ const curated = [
|
|
|
159
160
|
behavesAs: 'claude-opus-5-5',
|
|
160
161
|
modelSettings: oneMillion,
|
|
161
162
|
},
|
|
163
|
+
{
|
|
164
|
+
provider: 'zai',
|
|
165
|
+
model: 'zai/glm-5.3[1m]',
|
|
166
|
+
label: 'GLM 5.3 (Z.ai)',
|
|
167
|
+
description: 'GLM 5.3 via the Z.ai GLM Coding Plan with 1M context',
|
|
168
|
+
behavesAs: 'claude-opus-5-5',
|
|
169
|
+
modelSettings: { effortLevel: 'max', autoCompactWindow: 1000000 },
|
|
170
|
+
},
|
|
171
|
+
{
|
|
172
|
+
provider: 'zai',
|
|
173
|
+
model: 'zai/glm-5.3-flash[1m]',
|
|
174
|
+
label: 'GLM 5.3 Flash (Z.ai)',
|
|
175
|
+
description: 'GLM 5.3 Flash via the Z.ai GLM Coding Plan with 1M context',
|
|
176
|
+
behavesAs: 'claude-sonnet-5-5',
|
|
177
|
+
modelSettings: oneMillion,
|
|
178
|
+
},
|
|
162
179
|
];
|
|
163
180
|
// Match on the base ID so a renamed variant (e.g. a dropped [1m] suffix) replaces the old entry,
|
|
164
181
|
// and drop curated entries of providers that are not (or no longer) set up.
|
package/files/kimi-router.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import https from 'node:https';
|
|
|
3
3
|
import zlib from 'node:zlib';
|
|
4
4
|
import { getKimiAccessToken } from './kimi-oauth.mjs';
|
|
5
5
|
import { forwardMistral, isQuotaError } from './mistral.mjs';
|
|
6
|
-
import { getAliyunKey, getMiniMaxKey } from './secrets.mjs';
|
|
6
|
+
import { getAliyunKey, getMiniMaxKey, getZaiKey } from './secrets.mjs';
|
|
7
7
|
import { forwardCodex, isCodexQuotaError, codexLoginAvailable as checkCodexLogin, REASONING_SIGNATURE_PREFIX } from './codex.mjs';
|
|
8
8
|
import { syncedProviderOf, startModelSync, syncStatus, hasLogin } from './models-sync.mjs';
|
|
9
9
|
import { startUpdateCheck, updateStatus } from './update-check.mjs';
|
|
@@ -62,6 +62,13 @@ const MINIMAX_MODELS = new Set([
|
|
|
62
62
|
const isMiniMaxModel = (model) =>
|
|
63
63
|
MINIMAX_MODELS.has(model) || /^MiniMax-[A-Za-z0-9.-]+(\[1m\])?$/.test(model || '');
|
|
64
64
|
|
|
65
|
+
// Z.ai GLM Coding Plan, Anthropic-compatible endpoint (api.z.ai/api/anthropic). Its model IDs
|
|
66
|
+
// (glm-5.3, glm-5.3-flash) collide with the Aliyun route, so the picker uses a `zai/` prefix,
|
|
67
|
+
// stripped together with [1m] before forwarding.
|
|
68
|
+
const ZAI_HOST = process.env.ZAI_ANTHROPIC_HOST || 'api.z.ai';
|
|
69
|
+
const ZAI_MODELS = new Set(['zai/glm-5.3', 'zai/glm-5.3[1m]', 'zai/glm-5.3-flash', 'zai/glm-5.3-flash[1m]']);
|
|
70
|
+
const isZaiModel = (model) => /^zai\/[A-Za-z0-9.-]+(\[1m\])?$/.test(model || '');
|
|
71
|
+
|
|
65
72
|
// ChatGPT (Codex) route: gpt-* models via the Codex backend with the ChatGPT OAuth login.
|
|
66
73
|
// Family hierarchy per the Codex model catalog: astra (fable-class) > sol (opus-class)
|
|
67
74
|
// > terra (sonnet-class) > luna (haiku-class).
|
|
@@ -102,6 +109,7 @@ const providerOf = (model) => {
|
|
|
102
109
|
if (isAliyunModel(model)) return 'aliyun';
|
|
103
110
|
if (isCodexModel(model)) return 'codex';
|
|
104
111
|
if (isMiniMaxModel(model)) return 'minimax';
|
|
112
|
+
if (isZaiModel(model)) return 'zai';
|
|
105
113
|
return 'anthropic';
|
|
106
114
|
};
|
|
107
115
|
|
|
@@ -112,6 +120,7 @@ const FALLBACK_CHAINS = {
|
|
|
112
120
|
mistral: ['qwen3.8-max', 'k3.1-pro'],
|
|
113
121
|
codex: ['qwen3.8-max', 'zai-glm-5-3'],
|
|
114
122
|
minimax: ['qwen3.8-max', 'k3.1-pro'],
|
|
123
|
+
zai: ['zai-glm-5-3', 'glm-5.3', 'k3.1-pro'], // same model via Mistral, then Aliyun
|
|
115
124
|
};
|
|
116
125
|
|
|
117
126
|
const fallbackCandidates = (provider) =>
|
|
@@ -177,6 +186,7 @@ function sendAs(req, res, body, model, onQuotaError) {
|
|
|
177
186
|
kimi: providerOf(model) === 'kimi',
|
|
178
187
|
aliyun: providerOf(model) === 'aliyun',
|
|
179
188
|
minimax: providerOf(model) === 'minimax',
|
|
189
|
+
zai: providerOf(model) === 'zai',
|
|
180
190
|
onQuotaError,
|
|
181
191
|
});
|
|
182
192
|
}
|
|
@@ -223,7 +233,9 @@ function requestModel(body) {
|
|
|
223
233
|
// sendWithFailover awaits this to decide whether a quota error occurred and a
|
|
224
234
|
// fallback attempt is needed.
|
|
225
235
|
function forward(req, res, body, route) {
|
|
226
|
-
const { kimi = false, aliyun = false, minimax = false, onQuotaError } = route;
|
|
236
|
+
const { kimi = false, aliyun = false, minimax = false, zai = false, onQuotaError } = route;
|
|
237
|
+
const thirdParty = kimi || aliyun || minimax || zai;
|
|
238
|
+
const routeName = kimi ? 'Kimi' : aliyun ? 'Aliyun' : minimax ? 'MiniMax' : zai ? 'Z.ai' : 'Anthropic';
|
|
227
239
|
// A missing Kimi/Aliyun login throws inside runForward; reject so the caller answers with a 503
|
|
228
240
|
// instead of an unhandled rejection crashing the router (and every other open stream).
|
|
229
241
|
return new Promise((resolve, reject) => {
|
|
@@ -247,7 +259,7 @@ function forward(req, res, body, route) {
|
|
|
247
259
|
delete headers[name];
|
|
248
260
|
}
|
|
249
261
|
|
|
250
|
-
if (
|
|
262
|
+
if (thirdParty && body.length > 0) {
|
|
251
263
|
const payload = JSON.parse(body.toString('utf8'));
|
|
252
264
|
// ToolSearch/DeferredToolPlaceholder are no longer stripped: verified that Aliyun, Kimi
|
|
253
265
|
// and Mistral all accept these tool definitions and emit valid tool_use calls for them
|
|
@@ -334,18 +346,33 @@ function forward(req, res, body, route) {
|
|
|
334
346
|
}
|
|
335
347
|
}
|
|
336
348
|
|
|
349
|
+
if (zai) {
|
|
350
|
+
headers.authorization = `Bearer ${getZaiKey()}`;
|
|
351
|
+
delete headers['x-api-key'];
|
|
352
|
+
if (body.length > 0) {
|
|
353
|
+
const payload = JSON.parse(body.toString('utf8'));
|
|
354
|
+
if (typeof payload.model === 'string') {
|
|
355
|
+
payload.model = payload.model.replace(/^zai\//, '').replace(/\[1m\]$/, '');
|
|
356
|
+
body = Buffer.from(JSON.stringify(payload));
|
|
357
|
+
headers['content-length'] = body.length;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
337
362
|
const upstream = https.request(
|
|
338
363
|
{
|
|
339
|
-
hostname: aliyun ? ALIYUN_HOST : kimi ? 'api.kimi.com' : minimax ? MINIMAX_HOST : 'api.anthropic.com',
|
|
364
|
+
hostname: aliyun ? ALIYUN_HOST : kimi ? 'api.kimi.com' : minimax ? MINIMAX_HOST : zai ? ZAI_HOST : 'api.anthropic.com',
|
|
340
365
|
port: 443,
|
|
341
|
-
path: aliyun
|
|
366
|
+
path: aliyun
|
|
367
|
+
? `${ALIYUN_PATH_PREFIX}${req.url}`
|
|
368
|
+
: kimi ? `/coding${req.url}` : minimax ? `/anthropic${req.url}` : zai ? `/api/anthropic${req.url}` : req.url,
|
|
342
369
|
method: req.method,
|
|
343
370
|
headers,
|
|
344
371
|
},
|
|
345
372
|
(response) => {
|
|
346
373
|
// Quota errors (429/402, or 403 with a quota body) are detected before anything
|
|
347
374
|
// is streamed to the client; the response body is buffered for the check.
|
|
348
|
-
if (
|
|
375
|
+
if (thirdParty && [402, 403, 429].includes(response.statusCode)) {
|
|
349
376
|
const chunks = [];
|
|
350
377
|
response.on('data', (chunk) => chunks.push(chunk));
|
|
351
378
|
response.on('end', () => {
|
|
@@ -358,7 +385,7 @@ function forward(req, res, body, route) {
|
|
|
358
385
|
else if (enc.includes('br')) text = zlib.brotliDecompressSync(raw).toString('utf8');
|
|
359
386
|
else if (enc.includes('deflate')) text = zlib.inflateSync(raw).toString('utf8');
|
|
360
387
|
} catch {}
|
|
361
|
-
console.error(`${
|
|
388
|
+
console.error(`${routeName} HTTP ${response.statusCode}: ${text}`);
|
|
362
389
|
if (onQuotaError && isQuotaError(response.statusCode, text)) {
|
|
363
390
|
onQuotaError();
|
|
364
391
|
resolve();
|
|
@@ -370,7 +397,7 @@ function forward(req, res, body, route) {
|
|
|
370
397
|
});
|
|
371
398
|
return;
|
|
372
399
|
}
|
|
373
|
-
if (
|
|
400
|
+
if (thirdParty && response.statusCode >= 400) {
|
|
374
401
|
const chunks = [];
|
|
375
402
|
response.on('data', (chunk) => chunks.push(chunk));
|
|
376
403
|
response.on('end', () => {
|
|
@@ -383,7 +410,7 @@ function forward(req, res, body, route) {
|
|
|
383
410
|
else if (enc.includes('br')) text = zlib.brotliDecompressSync(raw).toString('utf8');
|
|
384
411
|
else if (enc.includes('deflate')) text = zlib.inflateSync(raw).toString('utf8');
|
|
385
412
|
} catch {}
|
|
386
|
-
console.error(`${
|
|
413
|
+
console.error(`${routeName} HTTP ${response.statusCode}: ${text}`);
|
|
387
414
|
// Log top-level payload keys to identify rejected request shapes.
|
|
388
415
|
try {
|
|
389
416
|
const payload = JSON.parse(body.toString('utf8'));
|
|
@@ -408,10 +435,10 @@ function forward(req, res, body, route) {
|
|
|
408
435
|
// Mid-stream upstream aborts (before message_stop) surface in Claude Code as
|
|
409
436
|
// "Connection lost mid-response" — log them so the cause is traceable.
|
|
410
437
|
response.on('error', (err) => {
|
|
411
|
-
console.error(`${
|
|
438
|
+
console.error(`${routeName} response stream error: ${err.code || err.message}`);
|
|
412
439
|
});
|
|
413
440
|
response.on('aborted', () => {
|
|
414
|
-
console.error(`${
|
|
441
|
+
console.error(`${routeName} response stream aborted mid-response`);
|
|
415
442
|
});
|
|
416
443
|
},
|
|
417
444
|
);
|
|
@@ -419,8 +446,7 @@ function forward(req, res, body, route) {
|
|
|
419
446
|
upstream.on('error', (err) => {
|
|
420
447
|
// Log the actual cause: ECONNRESET/ETIMEDOUT mid-stream is otherwise invisible
|
|
421
448
|
// (Claude Code shows "Connection lost mid-response" with no router-side trace).
|
|
422
|
-
|
|
423
|
-
console.error(`${route} upstream error: ${err.code || err.message}`);
|
|
449
|
+
console.error(`${routeName} upstream error: ${err.code || err.message}`);
|
|
424
450
|
if (!res.headersSent) {
|
|
425
451
|
sendJson(res, 502, { error: 'Upstream request failed' }, resolve);
|
|
426
452
|
} else {
|
|
@@ -462,11 +488,14 @@ const server = http.createServer(async (req, res) => {
|
|
|
462
488
|
codexLoginType: 'ChatGPT OAuth (Codex CLI)',
|
|
463
489
|
minimaxLoginAvailable,
|
|
464
490
|
minimaxHost: MINIMAX_HOST,
|
|
491
|
+
zaiLoginAvailable: hasLogin('zai'),
|
|
492
|
+
zaiHost: ZAI_HOST,
|
|
465
493
|
kimiModels: [...KIMI_MODELS],
|
|
466
494
|
mistralModels: [...MISTRAL_MODELS],
|
|
467
495
|
aliyunModels: [...ALIYUN_MODELS],
|
|
468
496
|
codexModels: [...CODEX_MODELS],
|
|
469
497
|
minimaxModels: [...MINIMAX_MODELS],
|
|
498
|
+
zaiModels: [...ZAI_MODELS],
|
|
470
499
|
claudeModels: 'passed through to Anthropic',
|
|
471
500
|
modelSync: syncStatus(),
|
|
472
501
|
});
|
|
@@ -505,6 +534,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
505
534
|
: 'Mistral API key unavailable; rerun the router installer to add it',
|
|
506
535
|
codex: 'ChatGPT/Codex login unavailable; run "codex login"',
|
|
507
536
|
minimax: 'MiniMax (M Plan) API key unavailable; rerun the router installer to add it',
|
|
537
|
+
zai: 'Z.ai (GLM Coding Plan) API key unavailable; rerun the router installer to add it',
|
|
508
538
|
}[provider] || 'Request could not be forwarded',
|
|
509
539
|
});
|
|
510
540
|
}
|
package/files/models-sync.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import fs from 'node:fs';
|
|
|
7
7
|
import os from 'node:os';
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { getKimiAccessToken, credentialPath as kimiCredentialPath } from './kimi-oauth.mjs';
|
|
10
|
-
import { getAliyunKey, getMiniMaxKey, getMistralKey } from './secrets.mjs';
|
|
10
|
+
import { getAliyunKey, getMiniMaxKey, getMistralKey, getZaiKey } from './secrets.mjs';
|
|
11
11
|
import { getAccessToken as getCodexAccessToken, readAuth as readCodexAuth } from './codex.mjs';
|
|
12
12
|
|
|
13
13
|
const HOME = os.homedir(); // %USERPROFILE% on Windows, where HOME is usually unset
|
|
@@ -41,6 +41,7 @@ const LOGIN_CHECKS = {
|
|
|
41
41
|
mistral: () => getMistralKey().length > 0,
|
|
42
42
|
aliyun: () => getAliyunKey().length > 0,
|
|
43
43
|
minimax: () => getMiniMaxKey().length > 0,
|
|
44
|
+
zai: () => getZaiKey().length > 0,
|
|
44
45
|
kimi: () => fs.statSync(kimiCredentialPath()).size > 0,
|
|
45
46
|
codex: () => Boolean(readCodexAuth().tokens?.access_token),
|
|
46
47
|
};
|
package/files/secrets.mjs
CHANGED
|
@@ -53,3 +53,4 @@ function getSecret(service, envVar) {
|
|
|
53
53
|
export const getMistralKey = () => getSecret('claude-code-mistral', 'MISTRAL_API_KEY');
|
|
54
54
|
export const getAliyunKey = () => getSecret('claude-code-aliyun', 'ALIYUN_API_KEY');
|
|
55
55
|
export const getMiniMaxKey = () => getSecret('claude-code-minimax', 'MINIMAX_API_KEY');
|
|
56
|
+
export const getZaiKey = () => getSecret('claude-code-zai', 'ZAI_API_KEY');
|
package/files/update-check.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
|
|
7
|
-
export const VERSION = '0.1.
|
|
7
|
+
export const VERSION = '0.1.7'; // keep equal to package.json (test/usage.test.mjs checks it)
|
|
8
8
|
const PACKAGE = '@euraika-bert/claude-model-router';
|
|
9
9
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
10
10
|
let latestVersion = null;
|
package/install.ps1
CHANGED
|
@@ -35,7 +35,8 @@ function Save-Key([string]$Service, [string]$EnvVar, [string]$Prompt) {
|
|
|
35
35
|
Save-Key 'claude-code-mistral' 'MISTRAL_API_KEY' 'Mistral API key'
|
|
36
36
|
Save-Key 'claude-code-aliyun' 'ALIYUN_API_KEY' 'Aliyun Bailian API key (token plan)'
|
|
37
37
|
Save-Key 'claude-code-minimax' 'MINIMAX_API_KEY' 'MiniMax M Plan API key'
|
|
38
|
-
|
|
38
|
+
Save-Key 'claude-code-zai' 'ZAI_API_KEY' 'Z.ai GLM Coding Plan API key'
|
|
39
|
+
Remove-Item Env:MISTRAL_API_KEY, Env:ALIYUN_API_KEY, Env:MINIMAX_API_KEY, Env:ZAI_API_KEY -ErrorAction SilentlyContinue
|
|
39
40
|
|
|
40
41
|
$env:ROUTER_NODE = $node # stable path for the SessionStart hook (nvm-windows symlinks resolve to versioned dirs)
|
|
41
42
|
& $node (Join-Path $Files 'configure.mjs')
|
package/install.sh
CHANGED
|
@@ -119,7 +119,8 @@ store_key() { # <service> <env var> <prompt>
|
|
|
119
119
|
store_key claude-code-mistral MISTRAL_API_KEY 'Mistral API key'
|
|
120
120
|
store_key claude-code-aliyun ALIYUN_API_KEY 'Aliyun Bailian API key (token plan)'
|
|
121
121
|
store_key claude-code-minimax MINIMAX_API_KEY 'MiniMax M Plan API key'
|
|
122
|
-
|
|
122
|
+
store_key claude-code-zai ZAI_API_KEY 'Z.ai GLM Coding Plan API key'
|
|
123
|
+
unset MISTRAL_API_KEY ALIYUN_API_KEY MINIMAX_API_KEY ZAI_API_KEY
|
|
123
124
|
|
|
124
125
|
ROUTER_NODE="$NODE_BIN" "$NODE_BIN" "$SOURCE_DIR/configure.mjs"
|
|
125
126
|
chmod 600 "$SETTINGS"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@euraika-bert/claude-model-router",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"description": "Local router that adds Kimi, Mistral/GLM, Aliyun Qwen/DeepSeek, ChatGPT/Codex and MiniMax models to Claude Code without replacing the built-in Claude models (macOS, Linux, Windows).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|