cc-provider-switcher 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +194 -0
  3. package/dist/cli.js +669 -0
  4. package/package.json +51 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cc-provider-switcher contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,194 @@
1
+ # cc-provider-switcher
2
+
3
+ [![npm version](https://img.shields.io/npm/v/cc-provider-switcher.svg)](https://www.npmjs.com/package/cc-provider-switcher)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
5
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D22-brightgreen)](https://nodejs.org)
6
+
7
+ Switch Claude Code between AI providers with one command.
8
+
9
+ ```sh
10
+ ccs deepseek # switch to DeepSeek
11
+ ccs minimax china # switch to MiniMax (China region)
12
+ ccs status # show current provider
13
+ ```
14
+
15
+ ---
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npm install -g cc-provider-switcher
21
+ ```
22
+
23
+ Or use without installing:
24
+
25
+ ```sh
26
+ npx cc-provider-switcher deepseek
27
+ ```
28
+
29
+ ---
30
+
31
+ ## Quick start
32
+
33
+ 1. **Install:** `npm i -g cc-provider-switcher`
34
+ 2. **Add API keys:** `ccs config`
35
+ 3. **Switch provider:** `ccs deepseek`
36
+ 4. **Check status:** `ccs status`
37
+
38
+ ---
39
+
40
+ ## Commands
41
+
42
+ | Command | Description |
43
+ |---------|-------------|
44
+ | `ccs <provider> [region]` | Switch Claude Code to a provider (user-level) |
45
+ | `ccs project <provider> [region]` | Switch for current project only |
46
+ | `ccs list` | List all available providers |
47
+ | `ccs status` | Show current provider, model, and API key |
48
+ | `ccs config` | Interactive API key setup |
49
+ | `ccs reset` | Remove ccs-managed settings |
50
+ | `ccs reset --project` | Reset project-level settings |
51
+ | `ccs reset --all` | Reset both user and project settings |
52
+ | `ccs doctor` | Diagnose environment issues |
53
+ | `ccs account save <name>` | Save current Claude credentials |
54
+ | `ccs account switch <name>` | Restore saved credentials |
55
+ | `ccs account list` | List saved credential profiles |
56
+ | `ccs account delete <name>` | Delete a saved profile |
57
+
58
+ ---
59
+
60
+ ## Providers
61
+
62
+ | Name | Key | Aliases | Regions |
63
+ |------|-----|---------|---------|
64
+ | DeepSeek | `deepseek` | `ds` | global |
65
+ | MiniMax | `minimax` | `mm` | global, china |
66
+ | Kimi | `kimi` | `kimi2` | global, china |
67
+ | Qwen | `qwen` | — | global, china |
68
+ | GLM | `glm` | `glm5` | global, china |
69
+ | Seed/Doubao | `seed` | `doubao` | global |
70
+ | StepFun | `stepfun` | `sf` | global |
71
+ | OpenRouter | `openrouter` | `or` | global |
72
+ | Claude (Anthropic) | `claude` | `anthropic`, `sonnet` | global |
73
+
74
+ ---
75
+
76
+ ## Configuration
77
+
78
+ ### API keys
79
+
80
+ Run `ccs config` for interactive setup, or set environment variables:
81
+
82
+ ```sh
83
+ export DEEPSEEK_API_KEY=sk-...
84
+ export MINIMAX_API_KEY=eyJ...
85
+ export KIMI_API_KEY=sk-...
86
+ ```
87
+
88
+ Config file: `~/.ccs/config.json` (permissions: `0600`)
89
+
90
+ ```json
91
+ {
92
+ "keys": {
93
+ "deepseek": "sk-...",
94
+ "minimax": "eyJ..."
95
+ },
96
+ "defaults": {
97
+ "region": "global"
98
+ }
99
+ }
100
+ ```
101
+
102
+ ### Override model IDs
103
+
104
+ Update model IDs without waiting for a release:
105
+
106
+ ```json
107
+ {
108
+ "providerOverrides": {
109
+ "deepseek": {
110
+ "defaultModel": "deepseek-v4"
111
+ }
112
+ }
113
+ }
114
+ ```
115
+
116
+ ### What ccs writes
117
+
118
+ ccs modifies only the `env` block in Claude Code settings. It never touches other fields (permissions, hooks, etc.).
119
+
120
+ **User-level:** `~/.claude/settings.json`
121
+ **Project-level:** `.claude/settings.local.json`
122
+
123
+ ```json
124
+ {
125
+ "env": {
126
+ "ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
127
+ "ANTHROPIC_AUTH_TOKEN": "sk-...",
128
+ "ANTHROPIC_MODEL": "deepseek-chat",
129
+ "ANTHROPIC_DEFAULT_SONNET_MODEL": "deepseek-chat",
130
+ "ANTHROPIC_DEFAULT_OPUS_MODEL": "deepseek-chat",
131
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL": "deepseek-chat",
132
+ "CLAUDE_CODE_SUBAGENT_MODEL": "deepseek-chat"
133
+ },
134
+ "ccsManaged": true
135
+ }
136
+ ```
137
+
138
+ ---
139
+
140
+ ## Multi-account management
141
+
142
+ Save and restore Claude Pro credentials:
143
+
144
+ ```sh
145
+ ccs account save work # save current credentials as "work"
146
+ ccs account save personal # save as "personal"
147
+ ccs account switch work # restore "work" credentials
148
+ ccs account list # list all saved accounts
149
+ ccs account delete personal # delete "personal"
150
+ ```
151
+
152
+ Credentials are stored in `~/.ccs/accounts/` with `0600` permissions.
153
+
154
+ ---
155
+
156
+ ## Adding providers
157
+
158
+ Add an entry to `src/providers/providers.json` and submit a PR:
159
+
160
+ ```json
161
+ {
162
+ "myprovider": {
163
+ "name": "My Provider",
164
+ "baseUrl": "https://api.myprovider.com/anthropic",
165
+ "defaultModel": "my-model-v1",
166
+ "aliases": ["mp"],
167
+ "keyEnvVar": "MYPROVIDER_API_KEY",
168
+ "models": {
169
+ "sonnet": "my-model-v1",
170
+ "opus": "my-model-v1",
171
+ "haiku": "my-model-v1"
172
+ }
173
+ }
174
+ }
175
+ ```
176
+
177
+ ---
178
+
179
+ ## vs. claude-code-switch
180
+
181
+ | | cc-provider-switcher | claude-code-switch |
182
+ |--|--|--|
183
+ | Distribution | npm (no install script) | bash script |
184
+ | Provider definitions | JSON registry | hardcoded functions |
185
+ | Adding providers | JSON entry | copy-paste bash function |
186
+ | Model IDs | User-overridable | Hardcoded |
187
+ | Tests | Vitest suite | None |
188
+ | Settings method | Direct `settings.json` write | `eval` + env vars |
189
+
190
+ ---
191
+
192
+ ## License
193
+
194
+ MIT
package/dist/cli.js ADDED
@@ -0,0 +1,669 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { program } from "commander";
5
+
6
+ // src/types.ts
7
+ import { z } from "zod";
8
+ var ProviderSchema = z.object({
9
+ name: z.string(),
10
+ baseUrl: z.string().url(),
11
+ defaultModel: z.string(),
12
+ aliases: z.array(z.string()),
13
+ keyEnvVar: z.string(),
14
+ models: z.object({
15
+ sonnet: z.string(),
16
+ opus: z.string(),
17
+ haiku: z.string()
18
+ }),
19
+ regions: z.record(z.string(), z.string()).optional(),
20
+ optional: z.boolean().optional()
21
+ });
22
+ var ProviderRegistrySchema = z.object({
23
+ providers: z.record(z.string(), ProviderSchema)
24
+ });
25
+ var UserConfigSchema = z.object({
26
+ keys: z.record(z.string(), z.string()).default({}),
27
+ defaults: z.object({
28
+ region: z.string().optional()
29
+ }).default({}),
30
+ providerOverrides: z.record(z.string(), z.record(z.string(), z.unknown())).default({})
31
+ });
32
+ var AccountSnapshotSchema = z.object({
33
+ credentials: z.unknown(),
34
+ savedAt: z.string()
35
+ });
36
+
37
+ // src/providers/providers.json
38
+ var providers_default = {
39
+ providers: {
40
+ deepseek: {
41
+ name: "DeepSeek",
42
+ baseUrl: "https://api.deepseek.com/anthropic",
43
+ defaultModel: "deepseek-chat",
44
+ aliases: ["ds"],
45
+ keyEnvVar: "DEEPSEEK_API_KEY",
46
+ models: { sonnet: "deepseek-chat", opus: "deepseek-chat", haiku: "deepseek-chat" }
47
+ },
48
+ minimax: {
49
+ name: "MiniMax",
50
+ baseUrl: "https://api.minimax.io/anthropic",
51
+ defaultModel: "MiniMax-M2.5",
52
+ aliases: ["mm"],
53
+ keyEnvVar: "MINIMAX_API_KEY",
54
+ regions: {
55
+ global: "https://api.minimax.io/anthropic",
56
+ china: "https://api.minimaxi.com/anthropic"
57
+ },
58
+ models: { sonnet: "MiniMax-M2.5", opus: "MiniMax-M2.5", haiku: "MiniMax-M2.5" }
59
+ },
60
+ claude: {
61
+ name: "Claude (Anthropic)",
62
+ baseUrl: "https://api.anthropic.com/",
63
+ defaultModel: "claude-sonnet-4-5-20250929",
64
+ aliases: ["anthropic", "sonnet"],
65
+ keyEnvVar: "CLAUDE_API_KEY",
66
+ optional: true,
67
+ models: {
68
+ sonnet: "claude-sonnet-4-5-20250929",
69
+ opus: "claude-opus-4-6",
70
+ haiku: "claude-haiku-4-5-20251001"
71
+ }
72
+ },
73
+ kimi: {
74
+ name: "Kimi",
75
+ baseUrl: "https://api.moonshot.ai/anthropic",
76
+ defaultModel: "kimi-k2.5",
77
+ aliases: ["kimi2"],
78
+ keyEnvVar: "KIMI_API_KEY",
79
+ regions: {
80
+ global: "https://api.moonshot.ai/anthropic",
81
+ china: "https://api.moonshot.cn/anthropic"
82
+ },
83
+ models: { sonnet: "kimi-k2.5", opus: "kimi-k2.5", haiku: "kimi-k2.5" }
84
+ },
85
+ qwen: {
86
+ name: "Qwen",
87
+ baseUrl: "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic",
88
+ defaultModel: "qwen3-max-2026-01-23",
89
+ aliases: [],
90
+ keyEnvVar: "QWEN_API_KEY",
91
+ regions: {
92
+ global: "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic",
93
+ china: "https://coding.dashscope.aliyuncs.com/apps/anthropic"
94
+ },
95
+ models: {
96
+ sonnet: "qwen3-max-2026-01-23",
97
+ opus: "qwen3-max-2026-01-23",
98
+ haiku: "qwen3-max-2026-01-23"
99
+ }
100
+ },
101
+ glm: {
102
+ name: "GLM",
103
+ baseUrl: "https://api.z.ai/api/anthropic",
104
+ defaultModel: "glm-5",
105
+ aliases: ["glm5"],
106
+ keyEnvVar: "GLM_API_KEY",
107
+ regions: {
108
+ global: "https://api.z.ai/api/anthropic",
109
+ china: "https://open.bigmodel.cn/api/anthropic"
110
+ },
111
+ models: { sonnet: "glm-5", opus: "glm-5", haiku: "glm-5" }
112
+ },
113
+ seed: {
114
+ name: "Seed/Doubao",
115
+ baseUrl: "https://ark.cn-beijing.volces.com/api/coding",
116
+ defaultModel: "ark-code-latest",
117
+ aliases: ["doubao"],
118
+ keyEnvVar: "ARK_API_KEY",
119
+ models: {
120
+ sonnet: "ark-code-latest",
121
+ opus: "ark-code-latest",
122
+ haiku: "ark-code-latest"
123
+ }
124
+ },
125
+ stepfun: {
126
+ name: "StepFun",
127
+ baseUrl: "https://api.stepfun.ai/v1/anthropic",
128
+ defaultModel: "step-3.5-flash",
129
+ aliases: ["sf"],
130
+ keyEnvVar: "STEPFUN_API_KEY",
131
+ models: {
132
+ sonnet: "step-3.5-flash",
133
+ opus: "step-3.5-flash",
134
+ haiku: "step-3.5-flash"
135
+ }
136
+ },
137
+ openrouter: {
138
+ name: "OpenRouter",
139
+ baseUrl: "https://openrouter.ai/api",
140
+ defaultModel: "anthropic/claude-sonnet-4.5",
141
+ aliases: ["or"],
142
+ keyEnvVar: "OPENROUTER_API_KEY",
143
+ models: {
144
+ sonnet: "anthropic/claude-sonnet-4.5",
145
+ opus: "anthropic/claude-opus-4.6",
146
+ haiku: "anthropic/claude-haiku-4.5"
147
+ }
148
+ }
149
+ }
150
+ };
151
+
152
+ // src/providers/registry.ts
153
+ function loadRegistry() {
154
+ return ProviderRegistrySchema.parse(providers_default);
155
+ }
156
+ function resolveProvider(nameOrAlias, userConfig) {
157
+ const registry = loadRegistry();
158
+ const key = nameOrAlias.toLowerCase();
159
+ if (registry.providers[key]) {
160
+ return toResolved(key, applyOverrides(key, registry.providers[key], userConfig));
161
+ }
162
+ for (const [name, provider] of Object.entries(registry.providers)) {
163
+ if (provider.aliases.map((a) => a.toLowerCase()).includes(key)) {
164
+ return toResolved(name, applyOverrides(name, provider, userConfig));
165
+ }
166
+ }
167
+ const available = Object.entries(registry.providers).flatMap(([name, p]) => [name, ...p.aliases]).join(", ");
168
+ throw new Error(`Unknown provider "${nameOrAlias}". Available: ${available}`);
169
+ }
170
+ function toResolved(key, provider) {
171
+ return { ...provider, registryKey: key };
172
+ }
173
+ function applyOverrides(name, provider, userConfig) {
174
+ if (!userConfig?.providerOverrides?.[name]) return provider;
175
+ return { ...provider, ...userConfig.providerOverrides[name] };
176
+ }
177
+ function resolveBaseUrl(provider, region) {
178
+ if (region && provider.regions?.[region]) return provider.regions[region];
179
+ return provider.baseUrl;
180
+ }
181
+ function getApiKey(provider, userConfig) {
182
+ const envVal = process.env[provider.keyEnvVar];
183
+ if (envVal) return envVal;
184
+ return userConfig?.keys?.[provider.registryKey] ?? null;
185
+ }
186
+
187
+ // src/config/user-config.ts
188
+ import readline from "readline";
189
+
190
+ // src/utils/paths.ts
191
+ import os from "os";
192
+ import path from "path";
193
+ var CCS_DIR = path.join(os.homedir(), ".ccs");
194
+ var CCS_CONFIG_FILE = path.join(CCS_DIR, "config.json");
195
+ var CCS_ACCOUNTS_DIR = path.join(CCS_DIR, "accounts");
196
+ var CLAUDE_DIR = path.join(os.homedir(), ".claude");
197
+ var CLAUDE_SETTINGS_FILE = path.join(CLAUDE_DIR, "settings.json");
198
+ var CLAUDE_CREDENTIALS_FILE = path.join(CLAUDE_DIR, ".credentials.json");
199
+ function getProjectSettingsPath() {
200
+ return path.join(process.cwd(), ".claude", "settings.local.json");
201
+ }
202
+
203
+ // src/utils/fs.ts
204
+ import fs from "fs/promises";
205
+ import path2 from "path";
206
+ async function ensureDir(dirPath) {
207
+ await fs.mkdir(dirPath, { recursive: true });
208
+ }
209
+ async function writeFileAtomically(filePath, data, mode = 420) {
210
+ const dir = path2.dirname(filePath);
211
+ await ensureDir(dir);
212
+ const tmp = path2.join(dir, `.ccs-tmp-${process.pid}-${Date.now()}`);
213
+ await fs.writeFile(tmp, data, { mode });
214
+ await fs.rename(tmp, filePath);
215
+ }
216
+ async function readJsonFile(filePath, schema) {
217
+ try {
218
+ const raw = await fs.readFile(filePath, "utf-8");
219
+ const parsed = JSON.parse(raw);
220
+ if (schema) return schema.parse(parsed);
221
+ return parsed;
222
+ } catch {
223
+ return null;
224
+ }
225
+ }
226
+ async function writeJsonFile(filePath, data, mode = 420) {
227
+ await writeFileAtomically(filePath, JSON.stringify(data, null, 2), mode);
228
+ }
229
+
230
+ // src/config/user-config.ts
231
+ var DEFAULT_CONFIG = {
232
+ keys: {},
233
+ defaults: {},
234
+ providerOverrides: {}
235
+ };
236
+ async function loadUserConfig(configPath = CCS_CONFIG_FILE) {
237
+ const raw = await readJsonFile(configPath);
238
+ if (!raw) return { ...DEFAULT_CONFIG };
239
+ try {
240
+ return UserConfigSchema.parse(raw);
241
+ } catch {
242
+ throw new Error(`Invalid config at ${configPath}. Delete it or run "ccs config" to reconfigure.`);
243
+ }
244
+ }
245
+ async function saveUserConfig(config, configPath = CCS_CONFIG_FILE) {
246
+ await writeJsonFile(configPath, config, 384);
247
+ }
248
+ async function initConfig(configPath = CCS_CONFIG_FILE) {
249
+ const registry = loadRegistry();
250
+ const current = await loadUserConfig(configPath);
251
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
252
+ const question = (prompt) => new Promise((resolve) => rl.question(prompt, resolve));
253
+ console.log("Configure API keys for each provider (leave blank to skip):\n");
254
+ for (const [key, provider] of Object.entries(registry.providers)) {
255
+ if (provider.optional) continue;
256
+ const existing = current.keys[key] ? ` [${maskKey(current.keys[key])}]` : "";
257
+ const answer = await question(`${provider.name}${existing}: `);
258
+ if (answer.trim()) current.keys[key] = answer.trim();
259
+ }
260
+ rl.close();
261
+ await saveUserConfig(current, configPath);
262
+ console.log(`
263
+ Config saved to ${configPath}`);
264
+ }
265
+ function maskKey(key) {
266
+ if (key.length <= 8) return "***";
267
+ return key.slice(0, 4) + "..." + key.slice(-4);
268
+ }
269
+
270
+ // src/config/claude-settings.ts
271
+ import fs2 from "fs/promises";
272
+ import path3 from "path";
273
+ import * as commentJson from "comment-json";
274
+ var CCS_MANAGED_KEY = "ccsManaged";
275
+ var ENV_KEYS = [
276
+ "ANTHROPIC_BASE_URL",
277
+ "ANTHROPIC_AUTH_TOKEN",
278
+ "ANTHROPIC_MODEL",
279
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
280
+ "ANTHROPIC_DEFAULT_OPUS_MODEL",
281
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
282
+ "CLAUDE_CODE_SUBAGENT_MODEL"
283
+ ];
284
+ async function readSettings(filePath) {
285
+ try {
286
+ const raw = await fs2.readFile(filePath, "utf-8");
287
+ try {
288
+ return commentJson.parse(raw);
289
+ } catch {
290
+ return JSON.parse(raw);
291
+ }
292
+ } catch {
293
+ return {};
294
+ }
295
+ }
296
+ async function writeSettings(filePath, settings) {
297
+ await ensureDir(path3.dirname(filePath));
298
+ await writeFileAtomically(filePath, JSON.stringify(settings, null, 2));
299
+ }
300
+ async function applyEnvBlock(filePath, envBlock) {
301
+ const settings = await readSettings(filePath);
302
+ const env = { ...settings.env ?? {} };
303
+ for (const [k, v] of Object.entries(envBlock)) {
304
+ if (v !== void 0) env[k] = v;
305
+ }
306
+ settings.env = env;
307
+ settings[CCS_MANAGED_KEY] = true;
308
+ await writeSettings(filePath, settings);
309
+ }
310
+ async function readUserSettings(filePath = CLAUDE_SETTINGS_FILE) {
311
+ return readSettings(filePath);
312
+ }
313
+ async function writeUserSettings(envBlock, filePath = CLAUDE_SETTINGS_FILE) {
314
+ await applyEnvBlock(filePath, envBlock);
315
+ }
316
+ async function readProjectSettings(filePath = getProjectSettingsPath()) {
317
+ return readSettings(filePath);
318
+ }
319
+ async function writeProjectSettings(envBlock, filePath = getProjectSettingsPath()) {
320
+ await applyEnvBlock(filePath, envBlock);
321
+ }
322
+ async function clearManagedSettings(scope, userSettingsPath = CLAUDE_SETTINGS_FILE, projectSettingsPath = getProjectSettingsPath()) {
323
+ const paths = [];
324
+ if (scope === "user" || scope === "all") paths.push(userSettingsPath);
325
+ if (scope === "project" || scope === "all") paths.push(projectSettingsPath);
326
+ for (const p of paths) {
327
+ const settings = await readSettings(p);
328
+ if (!settings.env) continue;
329
+ for (const key of ENV_KEYS) delete settings.env[key];
330
+ delete settings[CCS_MANAGED_KEY];
331
+ await writeSettings(p, settings);
332
+ }
333
+ }
334
+
335
+ // src/utils/display.ts
336
+ import chalk from "chalk";
337
+ function success(msg) {
338
+ console.log(chalk.green("\u2713 " + msg));
339
+ }
340
+ function error(msg) {
341
+ console.error(chalk.red("\u2717 " + msg));
342
+ }
343
+ function info(msg) {
344
+ console.log(chalk.cyan("\u2139 " + msg));
345
+ }
346
+ function maskKey2(key) {
347
+ if (key.length <= 8) return "***";
348
+ return key.slice(0, 4) + "..." + key.slice(-4);
349
+ }
350
+ function table(rows) {
351
+ const maxKey = Math.max(...rows.map(([k]) => k.length));
352
+ for (const [key, val] of rows) {
353
+ console.log(chalk.bold(key.padEnd(maxKey + 2)) + val);
354
+ }
355
+ }
356
+
357
+ // src/commands/switch.ts
358
+ async function doSwitch(providerName, region, scope) {
359
+ const userConfig = await loadUserConfig();
360
+ const provider = resolveProvider(providerName, userConfig);
361
+ const baseUrl = resolveBaseUrl(provider, region);
362
+ const apiKey = getApiKey(provider, userConfig);
363
+ if (!apiKey && !provider.optional) {
364
+ error(
365
+ `No API key for ${provider.name}. Set ${provider.keyEnvVar} or run "ccs config".`
366
+ );
367
+ process.exit(1);
368
+ }
369
+ const envBlock = {
370
+ ANTHROPIC_BASE_URL: baseUrl,
371
+ ANTHROPIC_AUTH_TOKEN: apiKey ?? "",
372
+ ANTHROPIC_MODEL: provider.defaultModel,
373
+ ANTHROPIC_DEFAULT_SONNET_MODEL: provider.models.sonnet,
374
+ ANTHROPIC_DEFAULT_OPUS_MODEL: provider.models.opus,
375
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: provider.models.haiku,
376
+ CLAUDE_CODE_SUBAGENT_MODEL: provider.models.sonnet
377
+ };
378
+ if (scope === "project") {
379
+ await writeProjectSettings(envBlock);
380
+ success(`Switched to ${provider.name} (project-level)`);
381
+ } else {
382
+ await writeUserSettings(envBlock);
383
+ success(`Switched to ${provider.name} (user-level)`);
384
+ }
385
+ info(`Base URL: ${baseUrl}`);
386
+ info(`Model: ${provider.defaultModel}`);
387
+ if (apiKey) info(`Key: ${maskKey2(apiKey)}`);
388
+ }
389
+ function registerSwitchCommand(program2) {
390
+ program2.argument("<provider>", "Provider name or alias").argument("[region]", "Optional region (global, china, etc.)").action(async (provider, region) => {
391
+ await doSwitch(provider, region, "user");
392
+ });
393
+ program2.command("project <provider> [region]").description("Switch provider for current project only").action(async (provider, region) => {
394
+ await doSwitch(provider, region, "project");
395
+ });
396
+ }
397
+
398
+ // src/commands/status.ts
399
+ function registerStatusCommand(program2) {
400
+ program2.command("status").description("Show current provider, model, and key status").action(async () => {
401
+ const [userSettings, projectSettings] = await Promise.all([
402
+ readUserSettings(),
403
+ readProjectSettings()
404
+ ]);
405
+ const registry = loadRegistry();
406
+ for (const [scope, settings] of [
407
+ ["User", userSettings],
408
+ ["Project", projectSettings]
409
+ ]) {
410
+ const env = settings.env ?? {};
411
+ const baseUrl = env["ANTHROPIC_BASE_URL"];
412
+ if (!baseUrl) continue;
413
+ const providerEntry = Object.entries(registry.providers).find(
414
+ ([, p]) => baseUrl.startsWith(p.baseUrl)
415
+ );
416
+ const providerName = providerEntry ? providerEntry[1].name : "Unknown";
417
+ const model = env["ANTHROPIC_MODEL"] ?? "unknown";
418
+ const key = env["ANTHROPIC_AUTH_TOKEN"] ?? "";
419
+ console.log(`
420
+ ${scope} settings:`);
421
+ table([
422
+ ["Provider", providerName],
423
+ ["Base URL", baseUrl],
424
+ ["Model", model],
425
+ ["API Key", key ? maskKey2(key) : "(not set)"]
426
+ ]);
427
+ }
428
+ const hasAny = userSettings.env?.["ANTHROPIC_BASE_URL"] || projectSettings.env?.["ANTHROPIC_BASE_URL"];
429
+ if (!hasAny) {
430
+ info('No provider configured. Run "ccs <provider>" to switch.');
431
+ }
432
+ });
433
+ }
434
+
435
+ // src/commands/list.ts
436
+ import chalk2 from "chalk";
437
+ function registerListCommand(program2) {
438
+ program2.command("list").description("List all available providers").action(() => {
439
+ const registry = loadRegistry();
440
+ const providers = Object.entries(registry.providers);
441
+ console.log(chalk2.bold("\nAvailable providers:\n"));
442
+ console.log(
443
+ chalk2.dim(
444
+ "Name".padEnd(14) + "Aliases".padEnd(18) + "Default Model".padEnd(32) + "Regions"
445
+ )
446
+ );
447
+ console.log(chalk2.dim("\u2500".repeat(80)));
448
+ for (const [key, provider] of providers) {
449
+ const aliases = [key, ...provider.aliases].join(", ");
450
+ const regions = provider.regions ? Object.keys(provider.regions).join(", ") : "global";
451
+ console.log(
452
+ chalk2.green(provider.name.padEnd(14)) + aliases.padEnd(18) + provider.defaultModel.padEnd(32) + chalk2.dim(regions)
453
+ );
454
+ }
455
+ console.log();
456
+ });
457
+ }
458
+
459
+ // src/commands/config.ts
460
+ function registerConfigCommand(program2) {
461
+ program2.command("config").description("Interactive setup: configure API keys for providers").action(async () => {
462
+ try {
463
+ await initConfig();
464
+ } catch (err) {
465
+ error(String(err));
466
+ process.exit(1);
467
+ }
468
+ });
469
+ }
470
+
471
+ // src/commands/reset.ts
472
+ import readline2 from "readline";
473
+ function registerResetCommand(program2) {
474
+ program2.command("reset").description("Remove ccs-managed provider settings").option("--project", "Reset project-level settings only").option("--all", "Reset both user and project settings").action(async (opts) => {
475
+ const scope = opts.all ? "all" : opts.project ? "project" : "user";
476
+ const desc = scope === "all" ? "user + project" : scope;
477
+ const confirmed = await confirm(`Remove ccs-managed settings (${desc})?`);
478
+ if (!confirmed) {
479
+ info("Cancelled.");
480
+ return;
481
+ }
482
+ await clearManagedSettings(scope);
483
+ success(`Cleared ${desc} settings.`);
484
+ });
485
+ }
486
+ function confirm(prompt) {
487
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
488
+ return new Promise((resolve) => {
489
+ rl.question(`${prompt} [y/N] `, (answer) => {
490
+ rl.close();
491
+ resolve(answer.trim().toLowerCase() === "y");
492
+ });
493
+ });
494
+ }
495
+
496
+ // src/commands/doctor.ts
497
+ import fs3 from "fs/promises";
498
+ import chalk3 from "chalk";
499
+ function registerDoctorCommand(program2) {
500
+ program2.command("doctor").description("Diagnose common configuration issues").action(async () => {
501
+ const checks = [];
502
+ const nodeVersion = process.versions.node;
503
+ const [major] = nodeVersion.split(".").map(Number);
504
+ checks.push({
505
+ label: `Node.js version (${nodeVersion})`,
506
+ pass: major >= 22,
507
+ detail: major < 22 ? "ccs requires Node.js >=22" : void 0
508
+ });
509
+ let claudeDirExists = false;
510
+ try {
511
+ await fs3.access(CLAUDE_DIR);
512
+ claudeDirExists = true;
513
+ } catch {
514
+ }
515
+ checks.push({
516
+ label: `Claude Code directory (~/.claude/)`,
517
+ pass: claudeDirExists,
518
+ detail: claudeDirExists ? void 0 : "Not found. Is Claude Code installed?"
519
+ });
520
+ let configValid = true;
521
+ let configDetail;
522
+ try {
523
+ await loadUserConfig();
524
+ } catch (err) {
525
+ configValid = false;
526
+ configDetail = String(err);
527
+ }
528
+ checks.push({ label: "ccs config file", pass: configValid, detail: configDetail });
529
+ let hasKey = false;
530
+ try {
531
+ const config = await loadUserConfig();
532
+ hasKey = Object.keys(config.keys).length > 0;
533
+ } catch {
534
+ }
535
+ checks.push({
536
+ label: "At least one API key configured",
537
+ pass: hasKey,
538
+ detail: hasKey ? void 0 : 'Run "ccs config" to add API keys.'
539
+ });
540
+ console.log("\nccs doctor\n");
541
+ for (const check of checks) {
542
+ const icon = check.pass ? chalk3.green("\u2713") : chalk3.red("\u2717");
543
+ console.log(` ${icon} ${check.label}`);
544
+ if (check.detail) console.log(` ${chalk3.dim(check.detail)}`);
545
+ }
546
+ console.log();
547
+ const failed = checks.filter((c) => !c.pass);
548
+ if (failed.length === 0) {
549
+ console.log(chalk3.green("All checks passed.\n"));
550
+ } else {
551
+ console.log(chalk3.yellow(`${failed.length} issue(s) found.
552
+ `));
553
+ process.exit(1);
554
+ }
555
+ });
556
+ }
557
+
558
+ // src/commands/account.ts
559
+ import readline3 from "readline";
560
+
561
+ // src/accounts/account-manager.ts
562
+ import fs4 from "fs/promises";
563
+ import path4 from "path";
564
+ async function saveAccount(name, credentialsPath = CLAUDE_CREDENTIALS_FILE, accountsDir = CCS_ACCOUNTS_DIR) {
565
+ let credentials;
566
+ try {
567
+ const raw = await fs4.readFile(credentialsPath, "utf-8");
568
+ credentials = JSON.parse(raw);
569
+ } catch {
570
+ throw new Error(`Cannot read credentials at ${credentialsPath}. Are you logged in to Claude?`);
571
+ }
572
+ await ensureDir(accountsDir);
573
+ const snapshot = { credentials, savedAt: (/* @__PURE__ */ new Date()).toISOString() };
574
+ await writeJsonFile(path4.join(accountsDir, `${name}.json`), snapshot, 384);
575
+ }
576
+ async function switchAccount(name, credentialsPath = CLAUDE_CREDENTIALS_FILE, accountsDir = CCS_ACCOUNTS_DIR) {
577
+ const accountPath = path4.join(accountsDir, `${name}.json`);
578
+ const snapshot = await readJsonFile(accountPath);
579
+ if (!snapshot) throw new Error(`Account "${name}" not found.`);
580
+ await ensureDir(path4.dirname(credentialsPath));
581
+ await writeJsonFile(credentialsPath, snapshot.credentials, 384);
582
+ }
583
+ async function listAccounts(accountsDir = CCS_ACCOUNTS_DIR) {
584
+ try {
585
+ const files = await fs4.readdir(accountsDir);
586
+ const accounts = [];
587
+ for (const file of files) {
588
+ if (!file.endsWith(".json")) continue;
589
+ const raw = await readJsonFile(path4.join(accountsDir, file));
590
+ accounts.push({ name: file.replace(/\.json$/, ""), savedAt: raw?.savedAt ?? "" });
591
+ }
592
+ return accounts.sort((a, b) => a.name.localeCompare(b.name));
593
+ } catch {
594
+ return [];
595
+ }
596
+ }
597
+ async function deleteAccount(name, accountsDir = CCS_ACCOUNTS_DIR) {
598
+ const accountPath = path4.join(accountsDir, `${name}.json`);
599
+ try {
600
+ await fs4.unlink(accountPath);
601
+ } catch {
602
+ throw new Error(`Account "${name}" not found.`);
603
+ }
604
+ }
605
+
606
+ // src/commands/account.ts
607
+ function registerAccountCommand(program2) {
608
+ const account = program2.command("account").description("Manage Claude Pro account credentials");
609
+ account.command("save <name>").description("Save current Claude credentials as a named profile").action(async (name) => {
610
+ try {
611
+ await saveAccount(name);
612
+ success(`Account "${name}" saved.`);
613
+ } catch (err) {
614
+ error(String(err));
615
+ process.exit(1);
616
+ }
617
+ });
618
+ account.command("switch <name>").description("Switch to a saved account profile").action(async (name) => {
619
+ try {
620
+ await switchAccount(name);
621
+ success(`Switched to account "${name}".`);
622
+ } catch (err) {
623
+ error(String(err));
624
+ process.exit(1);
625
+ }
626
+ });
627
+ account.command("list").description("List all saved account profiles").action(async () => {
628
+ const accounts = await listAccounts();
629
+ if (accounts.length === 0) {
630
+ info('No saved accounts. Run "ccs account save <name>" to save one.');
631
+ return;
632
+ }
633
+ table(accounts.map((a) => [a.name, a.savedAt]));
634
+ });
635
+ account.command("delete <name>").description("Delete a saved account profile").action(async (name) => {
636
+ const confirmed = await confirm2(`Delete account "${name}"?`);
637
+ if (!confirmed) {
638
+ info("Cancelled.");
639
+ return;
640
+ }
641
+ try {
642
+ await deleteAccount(name);
643
+ success(`Account "${name}" deleted.`);
644
+ } catch (err) {
645
+ error(String(err));
646
+ process.exit(1);
647
+ }
648
+ });
649
+ }
650
+ function confirm2(prompt) {
651
+ const rl = readline3.createInterface({ input: process.stdin, output: process.stdout });
652
+ return new Promise((resolve) => {
653
+ rl.question(`${prompt} [y/N] `, (answer) => {
654
+ rl.close();
655
+ resolve(answer.trim().toLowerCase() === "y");
656
+ });
657
+ });
658
+ }
659
+
660
+ // src/cli.ts
661
+ program.name("ccs").description("Switch Claude Code between AI providers").version("0.1.0");
662
+ registerListCommand(program);
663
+ registerStatusCommand(program);
664
+ registerConfigCommand(program);
665
+ registerResetCommand(program);
666
+ registerDoctorCommand(program);
667
+ registerAccountCommand(program);
668
+ registerSwitchCommand(program);
669
+ program.parse();
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "cc-provider-switcher",
3
+ "version": "0.1.0",
4
+ "description": "Switch Claude Code between AI providers with one command",
5
+ "type": "module",
6
+ "bin": {
7
+ "ccs": "./dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "default": "./dist/cli.js"
17
+ }
18
+ },
19
+ "engines": {
20
+ "node": ">=22"
21
+ },
22
+ "scripts": {
23
+ "build": "tsup",
24
+ "dev": "tsx src/cli.ts",
25
+ "test": "vitest run",
26
+ "test:watch": "vitest",
27
+ "prepublishOnly": "npm run build"
28
+ },
29
+ "keywords": [
30
+ "claude-code",
31
+ "ai",
32
+ "provider",
33
+ "switcher",
34
+ "cli"
35
+ ],
36
+ "license": "MIT",
37
+ "dependencies": {
38
+ "chalk": "^5.6.2",
39
+ "commander": "^15.0.0",
40
+ "comment-json": "^5.0.0",
41
+ "zod": "^4.4.3"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^26.0.1",
45
+ "memfs": "^4.57.8",
46
+ "tsup": "^8.5.1",
47
+ "tsx": "^4.22.4",
48
+ "typescript": "^6.0.3",
49
+ "vitest": "^4.1.9"
50
+ }
51
+ }