cc-provider-switcher 0.4.0 → 0.6.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 (3) hide show
  1. package/README.md +87 -4
  2. package/dist/cli.js +650 -102
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -77,10 +77,14 @@ ccs seed
77
77
  |---------|-------------|
78
78
  | `ccs <provider> [region]` | Switch Claude Code to a provider (user-level) |
79
79
  | `ccs project <provider> [region]` | Switch for current project only |
80
- | `ccs <provider> --model <id>` | Use one model ID for sonnet/opus/haiku (also works with `project`) |
80
+ | `ccs run <provider> [region]` | Start Claude Code with a provider in this terminal only, without changing any settings file. Put claude's own flags after `--`: `ccs run glm -- --resume` |
81
+ | `ccs test <provider> [region]` | Send one short request for each model ID to check that the key, base URL and model IDs work. The provider bills these requests |
82
+ | `ccs <provider> --model <id>` | Use one model ID for sonnet/opus/haiku (also works with `project`, `run` and `test`) |
81
83
  | `ccs list` | List all available providers |
82
84
  | `ccs status` | Show current provider, model, and API key |
83
85
  | `ccs config` | Interactive API key setup |
86
+ | `ccs provider add <name> <baseUrl> -m <id>` | Add a custom provider: an Anthropic-compatible endpoint that ccs does not ship with |
87
+ | `ccs provider remove <name>` | Remove a custom provider. Its stored API key stays in the config file |
84
88
  | `ccs reset` | Remove ccs-managed settings and return to Claude Code's native default |
85
89
  | `ccs reset --project` | Reset project-level settings |
86
90
  | `ccs reset --all` | Reset both user and project settings |
@@ -90,6 +94,10 @@ ccs seed
90
94
  | `ccs account list` | List saved credential profiles |
91
95
  | `ccs account delete <name>` | Delete a saved profile |
92
96
 
97
+ A `ccs run` session uses its provider even when `ccs <provider>` or `ccs project` set a different one; other sessions keep theirs. `ccs status` does not show a `ccs run` session.
98
+
99
+ In `ccs test`, a model passes when the provider answers with HTTP 200. Qwen's Coding Plan terms ban automated and non-interactive calls and say a key used that way can be blocked. They don't say whether one test request counts. So for Qwen, `ccs test` prints a warning and asks before it sends anything. `--accept` sends without asking. Without a terminal and without `--accept`, `ccs test` sends nothing.
100
+
93
101
  ---
94
102
 
95
103
  ## Providers
@@ -196,11 +204,51 @@ To make it permanent, override all four model fields (overrides replace `models`
196
204
 
197
205
  Use the "API Model Identifier" shown in LM Studio. Set the context length to 32k or more.
198
206
 
207
+ ### Custom providers
208
+
209
+ A custom provider is an Anthropic-compatible endpoint that ccs does not ship with, such as your own proxy or a LiteLLM or vLLM server. Add one with a command, then use it like a built-in provider:
210
+
211
+ ```sh
212
+ ccs provider add myproxy https://proxy.example.com -m my-model
213
+ ccs test myproxy
214
+ ccs myproxy
215
+ ```
216
+
217
+ `provider add` adds one entry to `~/.ccs/config.json`. Your keys and other settings stay as they are. The command does not take an API key, because every local user can read process arguments. Set `CCS_MYPROXY_API_KEY` or run `ccs config`.
218
+
219
+ You can also write the entry by hand. Only `baseUrl` and `models.sonnet` are required:
220
+
221
+ ```json
222
+ {
223
+ "customProviders": {
224
+ "myproxy": {
225
+ "baseUrl": "https://proxy.example.com",
226
+ "models": { "sonnet": "my-model" }
227
+ }
228
+ }
229
+ }
230
+ ```
231
+
232
+ Fields you leave out get these values:
233
+
234
+ - `name`: the entry's key (`myproxy`)
235
+ - `models.opus`, `models.haiku` and `defaultModel`: the value of `models.sonnet`
236
+ - `keyEnvVar`: `CCS_<NAME>_API_KEY`, with `-` changed to `_`
237
+ - `aliases`: none
238
+
239
+ The optional fields from [Adding providers](#adding-providers) work here too: `aliases`, `regions`, `supportedCapabilities` and `thinkingNote`, plus `testNote`, a warning `ccs test` prints before it sends anything. For a server that needs no key, set `"keyOptional": true`.
240
+
241
+ Names and aliases use lowercase letters, digits, `-` and `_`. A name or alias can't match a built-in provider or alias, a ccs command (`list`, `test`, `provider` and the rest), or `claude`, `anthropic` and `sonnet`. To change a built-in provider, use `providerOverrides`.
242
+
243
+ If the config file is not valid JSON, or a custom entry has a wrong field, every ccs command stops with one line that names the file and the field. No command writes to the file until you fix it.
244
+
245
+ `ccs provider remove myproxy` deletes the entry and keeps `keys.myproxy`, because many providers show a key only once. Delete the key from the file if you no longer need it. While it is there, `ccs provider add myproxy` refuses to run, so the old key never goes to a new URL.
246
+
199
247
  ### What ccs writes
200
248
 
201
249
  ccs modifies only the `env` block in Claude Code settings. It never touches other fields (permissions, hooks, etc.).
202
250
 
203
- **User-level:** `~/.claude/settings.json`
251
+ **User-level:** `~/.claude/settings.json`, or `settings.json` in the `CLAUDE_CONFIG_DIR` folder when that variable is set
204
252
  **Project-level:** `.claude/settings.local.json`
205
253
 
206
254
  ```json
@@ -235,13 +283,48 @@ ccs account list # list all saved accounts
235
283
  ccs account delete personal # delete "personal"
236
284
  ```
237
285
 
238
- Credentials are stored in `~/.ccs/accounts/` with `0600` permissions.
286
+ ccs reads and writes the login where Claude Code keeps it:
287
+
288
+ - macOS: the `Claude Code-credentials` item in the login Keychain. With `CLAUDE_CONFIG_DIR` set, Claude Code adds a hash of that value to the item name, and ccs uses the same name.
289
+ - Linux and Windows: `~/.claude/.credentials.json`, or `.credentials.json` in the `CLAUDE_CONFIG_DIR` folder
290
+
291
+ A profile also saves the `oauthAccount` block (the account email and organization) from `~/.claude.json`, or from `.claude.json` in the `CLAUDE_CONFIG_DIR` folder. `switch` writes it back.
292
+
293
+ ccs keeps profiles in `~/.ccs/accounts/` with `0600` permissions.
294
+
295
+ Quit every Claude Code session before you run `ccs account switch`, then start Claude Code again. A session left open can write its old login back when it refreshes its token.
296
+
297
+ Claude Code refreshes the login after you save it, so `switch` first copies the current login into the profile with the same account and organization. If no profile matches, `switch` stops and changes nothing. Run `ccs account save <name>` first.
298
+
299
+ ### When a provider is active
300
+
301
+ While a provider is active, Claude Code does not use your `/login` account. `ccs <provider>` writes `ANTHROPIC_AUTH_TOKEN`, and Claude Code ranks that token above the login. `ccs account switch` still swaps the saved login, and Claude Code uses it again once you remove the provider with `ccs reset`.
302
+
303
+ `ccs status` shows the account you are logged in to and the credential Claude Code will use. When that credential is not the login, `ccs status` and `ccs account switch` say where it comes from and how to remove it. `ccs account list` puts a `*` next to the profile you are logged in with.
304
+
305
+ With a provider active and a login saved, Claude Code shows "Both ANTHROPIC_AUTH_TOKEN and /login managed key set · auth may not work as expected". This is expected: requests go to the provider with its token. Run `ccs reset` to go back to the login.
306
+
307
+ ### Separate config folders
308
+
309
+ When `CLAUDE_CONFIG_DIR` is set, Claude Code reads its settings and login from that folder. Run ccs with the same value and it uses the folder too: `ccs <provider>`, `ccs reset`, `ccs status`, `ccs doctor` and `ccs account` read and write the files and the Keychain item that belong to it. `ccs status` prints the folder on a `Config dir` line.
310
+
311
+ ```sh
312
+ export CLAUDE_CONFIG_DIR=~/.claude-work
313
+ ccs deepseek
314
+ claude
315
+ ```
316
+
317
+ Write the value the same way each time. Claude Code builds the Keychain item name from the exact text, so on macOS `~/.claude-work` and `~/.claude-work/` hold two separate logins.
318
+
319
+ Saved profiles in `~/.ccs/accounts/` are shared by all folders, and `ccs account switch` writes a profile into the folder that is active. If one profile is active in two folders at the same time, both use the same login, and a token refresh in one folder may sign the other one out.
320
+
321
+ ccs does not handle Claude Code's opt-in Windows Credential Manager storage.
239
322
 
240
323
  ---
241
324
 
242
325
  ## Adding providers
243
326
 
244
- Add an entry to `src/providers/providers.json` and submit a PR:
327
+ To use a provider only on your machine, add it as a [custom provider](#custom-providers). To ship it with ccs, add an entry to `src/providers/providers.json` and submit a PR:
245
328
 
246
329
  ```json
247
330
  {
package/dist/cli.js CHANGED
@@ -20,17 +20,38 @@ var ProviderSchema = z.object({
20
20
  }),
21
21
  regions: z.record(z.string(), z.string()).optional(),
22
22
  supportedCapabilities: z.array(z.string()).optional(),
23
- thinkingNote: z.string().optional()
23
+ thinkingNote: z.string().optional(),
24
+ testNote: z.string().optional()
24
25
  });
25
26
  var ProviderRegistrySchema = z.object({
26
27
  providers: z.record(z.string(), ProviderSchema)
27
28
  });
29
+ var PROVIDER_NAME = z.string().regex(/^[a-z0-9][a-z0-9_-]*$/, 'use lowercase letters, digits, "-" and "_", starting with a letter or digit');
30
+ var CustomProviderSchema = z.object({
31
+ name: z.string().optional(),
32
+ // http(s) only: a bare "localhost:1234" passes a plain URL check and then fails every request.
33
+ baseUrl: z.url({ protocol: /^https?$/ }),
34
+ defaultModel: z.string().optional(),
35
+ aliases: z.array(PROVIDER_NAME).default([]),
36
+ keyEnvVar: z.string().optional(),
37
+ keyOptional: z.boolean().optional(),
38
+ models: z.object({
39
+ sonnet: z.string(),
40
+ opus: z.string().optional(),
41
+ haiku: z.string().optional()
42
+ }),
43
+ regions: z.record(z.string(), z.url({ protocol: /^https?$/ })).optional(),
44
+ supportedCapabilities: z.array(z.string()).optional(),
45
+ thinkingNote: z.string().optional(),
46
+ testNote: z.string().optional()
47
+ });
28
48
  var UserConfigSchema = z.object({
29
49
  keys: z.record(z.string(), z.string()).default({}),
30
50
  defaults: z.object({
31
51
  region: z.string().optional()
32
52
  }).default({}),
33
- providerOverrides: z.record(z.string(), z.record(z.string(), z.unknown())).default({})
53
+ providerOverrides: z.record(z.string(), z.record(z.string(), z.unknown())).default({}),
54
+ customProviders: z.record(PROVIDER_NAME, CustomProviderSchema).optional()
34
55
  });
35
56
  var AccountSnapshotSchema = z.object({
36
57
  credentials: z.unknown(),
@@ -93,7 +114,8 @@ var providers_default = {
93
114
  haiku: "qwen3.7-plus"
94
115
  },
95
116
  supportedCapabilities: ["effort", "thinking"],
96
- thinkingNote: "Supports thinking_budget for token-level control"
117
+ thinkingNote: "Supports thinking_budget for token-level control",
118
+ testNote: "Qwen's Coding Plan terms ban automated and non-interactive calls and say a key used that way can be blocked. They don't say whether one test request counts."
97
119
  },
98
120
  glm: {
99
121
  name: "GLM",
@@ -167,21 +189,77 @@ var providers_default = {
167
189
  };
168
190
 
169
191
  // src/providers/registry.ts
192
+ var CLAUDE_NATIVE_NAMES = /* @__PURE__ */ new Set(["claude", "anthropic", "sonnet"]);
193
+ var COMMAND_NAMES = /* @__PURE__ */ new Set([
194
+ "list",
195
+ "status",
196
+ "config",
197
+ "reset",
198
+ "doctor",
199
+ "account",
200
+ "run",
201
+ "test",
202
+ "project",
203
+ "provider",
204
+ "help"
205
+ ]);
170
206
  function loadRegistry() {
171
207
  return ProviderRegistrySchema.parse(providers_default);
172
208
  }
209
+ function customProvider(key, entry) {
210
+ const sonnet = entry.models.sonnet;
211
+ return {
212
+ ...entry,
213
+ name: entry.name ?? key,
214
+ defaultModel: entry.defaultModel ?? sonnet,
215
+ // CCS_ prefix: a plain <NAME>_API_KEY may hold a key for another service, which ccs would then send to this URL.
216
+ keyEnvVar: entry.keyEnvVar ?? `CCS_${key.toUpperCase().replace(/-/g, "_")}_API_KEY`,
217
+ models: { sonnet, opus: entry.models.opus ?? sonnet, haiku: entry.models.haiku ?? sonnet }
218
+ };
219
+ }
220
+ function allProviders(userConfig) {
221
+ const custom = Object.entries(userConfig?.customProviders ?? {}).map(([key, entry]) => [
222
+ key,
223
+ customProvider(key, entry)
224
+ ]);
225
+ return { ...loadRegistry().providers, ...Object.fromEntries(custom) };
226
+ }
227
+ function findNameClash(custom) {
228
+ const builtin = /* @__PURE__ */ new Map();
229
+ for (const [key, p] of Object.entries(loadRegistry().providers)) {
230
+ for (const n of [key, ...p.aliases]) builtin.set(n.toLowerCase(), key);
231
+ }
232
+ const seen = /* @__PURE__ */ new Map();
233
+ const envVars = /* @__PURE__ */ new Map();
234
+ for (const [key, entry] of Object.entries(custom)) {
235
+ const where = `custom provider "${key}"`;
236
+ const envVar = customProvider(key, entry).keyEnvVar;
237
+ if (envVars.has(envVar)) return `${where}: key variable ${envVar} is also used by custom provider "${envVars.get(envVar)}"`;
238
+ envVars.set(envVar, key);
239
+ for (const n of /* @__PURE__ */ new Set([key, ...entry.aliases])) {
240
+ if (builtin.has(n)) {
241
+ return `${where}: "${n}" is taken by the built-in provider "${builtin.get(n)}" (use providerOverrides to change a built-in)`;
242
+ }
243
+ if (COMMAND_NAMES.has(n)) return `${where}: "${n}" is a ccs command`;
244
+ if (CLAUDE_NATIVE_NAMES.has(n)) return `${where}: "${n}" is reserved for Claude Code's native default`;
245
+ if (seen.has(n)) return `${where}: "${n}" is already used by custom provider "${seen.get(n)}"`;
246
+ seen.set(n, key);
247
+ }
248
+ }
249
+ return null;
250
+ }
173
251
  function resolveProvider(nameOrAlias, userConfig) {
174
- const registry = loadRegistry();
252
+ const providers = allProviders(userConfig);
175
253
  const key = nameOrAlias.toLowerCase();
176
- if (registry.providers[key]) {
177
- return toResolved(key, applyOverrides(key, registry.providers[key], userConfig));
254
+ if (Object.hasOwn(providers, key)) {
255
+ return toResolved(key, applyOverrides(key, providers[key], userConfig));
178
256
  }
179
- for (const [name, provider] of Object.entries(registry.providers)) {
257
+ for (const [name, provider] of Object.entries(providers)) {
180
258
  if (provider.aliases.map((a) => a.toLowerCase()).includes(key)) {
181
259
  return toResolved(name, applyOverrides(name, provider, userConfig));
182
260
  }
183
261
  }
184
- const available = Object.entries(registry.providers).flatMap(([name, p]) => [name, ...p.aliases]).join(", ");
262
+ const available = Object.entries(providers).flatMap(([name, p]) => [name, ...p.aliases]).join(", ");
185
263
  throw new Error(`Unknown provider "${nameOrAlias}". Available: ${available}`);
186
264
  }
187
265
  function toResolved(key, provider) {
@@ -205,6 +283,7 @@ function withModel(provider, model) {
205
283
  }
206
284
 
207
285
  // src/config/user-config.ts
286
+ import fs2 from "fs/promises";
208
287
  import readline from "readline";
209
288
 
210
289
  // src/utils/paths.ts
@@ -213,12 +292,17 @@ import path from "path";
213
292
  var CCS_DIR = path.join(os.homedir(), ".ccs");
214
293
  var CCS_CONFIG_FILE = path.join(CCS_DIR, "config.json");
215
294
  var CCS_ACCOUNTS_DIR = path.join(CCS_DIR, "accounts");
216
- var CLAUDE_DIR = path.join(os.homedir(), ".claude");
295
+ var CLAUDE_CONFIG_DIR = process.env.CLAUDE_CONFIG_DIR || void 0;
296
+ var CLAUDE_DIR = CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), ".claude");
217
297
  var CLAUDE_SETTINGS_FILE = path.join(CLAUDE_DIR, "settings.json");
218
298
  var CLAUDE_CREDENTIALS_FILE = path.join(CLAUDE_DIR, ".credentials.json");
299
+ var CLAUDE_GLOBAL_CONFIG_FILE = path.join(CLAUDE_CONFIG_DIR ?? os.homedir(), ".claude.json");
219
300
  function getProjectSettingsPath() {
220
301
  return path.join(process.cwd(), ".claude", "settings.local.json");
221
302
  }
303
+ function getSharedProjectSettingsPath() {
304
+ return path.join(process.cwd(), ".claude", "settings.json");
305
+ }
222
306
 
223
307
  // src/utils/fs.ts
224
308
  import fs from "fs/promises";
@@ -253,31 +337,88 @@ var DEFAULT_CONFIG = {
253
337
  defaults: {},
254
338
  providerOverrides: {}
255
339
  };
256
- async function loadUserConfig(configPath = CCS_CONFIG_FILE) {
257
- const raw = await readJsonFile(configPath);
258
- if (!raw) return { ...DEFAULT_CONFIG };
340
+ async function readRawConfig(configPath) {
341
+ let text;
259
342
  try {
260
- return UserConfigSchema.parse(raw);
261
- } catch {
262
- throw new Error(`Invalid config at ${configPath}. Delete it or run "ccs config" to reconfigure.`);
343
+ text = await fs2.readFile(configPath, "utf-8");
344
+ } catch (err) {
345
+ if (err.code === "ENOENT") return null;
346
+ throw new Error(`Cannot read config at ${configPath}: ${err.message}`);
347
+ }
348
+ try {
349
+ return { raw: JSON.parse(text), text };
350
+ } catch (err) {
351
+ const at = /line \d+ column \d+/.exec(err.message)?.[0];
352
+ throw new Error(`Config at ${configPath} is not valid JSON${at ? ` (${at})` : ""}. Fix it by hand.`);
263
353
  }
264
354
  }
265
- async function saveUserConfig(config, configPath = CCS_CONFIG_FILE) {
266
- await writeJsonFile(configPath, config, 384);
355
+ function formatIssues(error2) {
356
+ return error2.issues.map((i) => {
357
+ const message = i.code === "invalid_key" ? i.issues.map((n) => n.message).join(", ") : i.message;
358
+ return (i.path.length ? `${i.path.map(String).join(".")}: ` : "") + message;
359
+ }).join("; ");
360
+ }
361
+ function parseConfig(raw, prefix) {
362
+ const result = UserConfigSchema.safeParse(raw);
363
+ if (!result.success) throw new Error(`${prefix}: ${formatIssues(result.error)}`);
364
+ const clash = findNameClash(result.data.customProviders ?? {});
365
+ if (clash) throw new Error(`${prefix}: ${clash}`);
366
+ return result.data;
367
+ }
368
+ async function loadUserConfig(configPath = CCS_CONFIG_FILE) {
369
+ const file = await readRawConfig(configPath);
370
+ if (!file) return { ...DEFAULT_CONFIG };
371
+ return parseConfig(file.raw, `Invalid config at ${configPath}`);
372
+ }
373
+ async function updateUserConfig(mutate, configPath) {
374
+ const file = await readRawConfig(configPath);
375
+ const raw = file?.raw ?? {};
376
+ parseConfig(raw, `Invalid config at ${configPath}`);
377
+ mutate(raw);
378
+ const config = parseConfig(raw, "Not saved");
379
+ const newline = file?.text.endsWith("\n") ? "\n" : "";
380
+ await writeFileAtomically(configPath, JSON.stringify(raw, null, 2) + newline, 384);
381
+ return config;
382
+ }
383
+ async function addCustomProvider(name, baseUrl, model, configPath = CCS_CONFIG_FILE) {
384
+ return updateUserConfig((raw) => {
385
+ const custom = raw.customProviders ??= {};
386
+ if (Object.hasOwn(custom, name)) {
387
+ throw new Error(`Custom provider "${name}" already exists in ${configPath}. Remove it first, or edit it there.`);
388
+ }
389
+ for (const field of ["keys", "providerOverrides"]) {
390
+ if (Object.hasOwn(raw[field] ?? {}, name)) {
391
+ throw new Error(`${configPath} still has ${field}.${name} from an earlier provider. Delete it there first, so it is not sent to the new URL.`);
392
+ }
393
+ }
394
+ custom[name] = { baseUrl, models: { sonnet: model, opus: model, haiku: model } };
395
+ }, configPath);
396
+ }
397
+ async function removeCustomProvider(name, configPath = CCS_CONFIG_FILE) {
398
+ let keptKey = false;
399
+ await updateUserConfig((raw) => {
400
+ const custom = raw.customProviders;
401
+ if (!custom || !Object.hasOwn(custom, name)) throw new Error(`No custom provider "${name}" in ${configPath}.`);
402
+ delete custom[name];
403
+ keptKey = Object.hasOwn(raw.keys ?? {}, name);
404
+ }, configPath);
405
+ return { keptKey };
267
406
  }
268
407
  async function initConfig(configPath = CCS_CONFIG_FILE) {
269
- const registry = loadRegistry();
270
408
  const current = await loadUserConfig(configPath);
271
409
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
272
410
  const question = (prompt) => new Promise((resolve) => rl.question(prompt, resolve));
273
411
  console.log("Configure API keys for each provider (leave blank to skip):\n");
274
- for (const [key, provider] of Object.entries(registry.providers)) {
412
+ const answers = {};
413
+ for (const [key, provider] of Object.entries(allProviders(current))) {
275
414
  const existing = current.keys[key] ? ` [${maskKey(current.keys[key])}]` : "";
276
415
  const answer = await question(`${provider.name}${existing}: `);
277
- if (answer.trim()) current.keys[key] = answer.trim();
416
+ if (answer.trim()) answers[key] = answer.trim();
278
417
  }
279
418
  rl.close();
280
- await saveUserConfig(current, configPath);
419
+ await updateUserConfig((raw) => {
420
+ raw.keys = { ...raw.keys, ...answers };
421
+ }, configPath);
281
422
  console.log(`
282
423
  Config saved to ${configPath}`);
283
424
  }
@@ -287,7 +428,7 @@ function maskKey(key) {
287
428
  }
288
429
 
289
430
  // src/config/claude-settings.ts
290
- import fs2 from "fs/promises";
431
+ import fs3 from "fs/promises";
291
432
  import path3 from "path";
292
433
  import * as commentJson from "comment-json";
293
434
  var CCS_MANAGED_KEY = "ccsManaged";
@@ -305,7 +446,7 @@ var ENV_KEYS = [
305
446
  ];
306
447
  async function readSettings(filePath) {
307
448
  try {
308
- const raw = await fs2.readFile(filePath, "utf-8");
449
+ const raw = await fs3.readFile(filePath, "utf-8");
309
450
  try {
310
451
  return commentJson.parse(raw);
311
452
  } catch {
@@ -360,12 +501,16 @@ async function clearManagedSettings(scope, userSettingsPath = CLAUDE_SETTINGS_FI
360
501
 
361
502
  // src/utils/display.ts
362
503
  import chalk from "chalk";
504
+ import readline2 from "readline";
363
505
  function success(msg) {
364
506
  console.log(chalk.green("\u2713 " + msg));
365
507
  }
366
508
  function error(msg) {
367
509
  console.error(chalk.red("\u2717 " + msg));
368
510
  }
511
+ function warn(msg) {
512
+ console.warn(chalk.yellow("\u26A0 " + msg));
513
+ }
369
514
  function info(msg) {
370
515
  console.log(chalk.cyan("\u2139 " + msg));
371
516
  }
@@ -379,15 +524,19 @@ function table(rows) {
379
524
  console.log(chalk.bold(key.padEnd(maxKey + 2)) + val);
380
525
  }
381
526
  }
527
+ function confirm(prompt) {
528
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
529
+ return new Promise((resolve) => {
530
+ rl.on("close", () => resolve(false));
531
+ rl.question(`${prompt} [y/N] `, (answer) => {
532
+ resolve(answer.trim().toLowerCase() === "y");
533
+ rl.close();
534
+ });
535
+ });
536
+ }
382
537
 
383
538
  // src/commands/switch.ts
384
- var CLAUDE_NATIVE_NAMES = /* @__PURE__ */ new Set(["claude", "anthropic", "sonnet"]);
385
- async function doSwitch(providerName, region, scope, model) {
386
- if (CLAUDE_NATIVE_NAMES.has(providerName.toLowerCase())) {
387
- info("Claude is Claude Code's native default \u2014 there is nothing to switch to.");
388
- info('Run "ccs reset" to clear provider overrides and return to it.');
389
- return;
390
- }
539
+ async function buildEnvBlock(providerName, region, model) {
391
540
  const userConfig = await loadUserConfig();
392
541
  const resolved = resolveProvider(providerName, userConfig);
393
542
  const provider = model ? withModel(resolved, model) : resolved;
@@ -412,6 +561,15 @@ async function doSwitch(providerName, region, scope, model) {
412
561
  ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES: caps,
413
562
  ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES: caps
414
563
  };
564
+ return { provider, baseUrl, apiKey, envBlock };
565
+ }
566
+ async function doSwitch(providerName, region, scope, model) {
567
+ if (CLAUDE_NATIVE_NAMES.has(providerName.toLowerCase())) {
568
+ info("Claude is Claude Code's native default \u2014 there is nothing to switch to.");
569
+ info('Run "ccs reset" to clear provider overrides and return to it.');
570
+ return;
571
+ }
572
+ const { provider, baseUrl, apiKey, envBlock } = await buildEnvBlock(providerName, region, model);
415
573
  if (scope === "project") {
416
574
  await writeProjectSettings(envBlock);
417
575
  success(`Switched to ${provider.name} (project-level)`);
@@ -433,14 +591,98 @@ function registerSwitchCommand(program2) {
433
591
  });
434
592
  }
435
593
 
594
+ // src/config/auth-source.ts
595
+ import path4 from "path";
596
+ var CLOUD_FLAGS = ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY"];
597
+ var PRECEDENCE = [
598
+ ...CLOUD_FLAGS,
599
+ "ANTHROPIC_AUTH_TOKEN",
600
+ "ANTHROPIC_API_KEY",
601
+ "apiKeyHelper",
602
+ "CLAUDE_CODE_OAUTH_TOKEN",
603
+ "ANTHROPIC_PROFILE",
604
+ // Federation counts only together with ANTHROPIC_ORGANIZATION_ID.
605
+ "ANTHROPIC_FEDERATION_RULE_ID"
606
+ ];
607
+ var USER_SCOPE_ONLY = /* @__PURE__ */ new Set(["CLAUDE_CODE_OAUTH_TOKEN"]);
608
+ var ORIGIN_LABEL = {
609
+ shell: "your shell",
610
+ user: CLAUDE_CONFIG_DIR ? CLAUDE_SETTINGS_FILE : "~/.claude/settings.json",
611
+ shared: ".claude/settings.json",
612
+ local: ".claude/settings.local.json"
613
+ };
614
+ function resolveAuthSource(layers) {
615
+ const highestFirst = [...layers].reverse();
616
+ const lookup = (name) => {
617
+ for (const layer of highestFirst) {
618
+ if (USER_SCOPE_ONLY.has(name) && (layer.from === "shared" || layer.from === "local")) continue;
619
+ const value = name === "apiKeyHelper" ? layer.apiKeyHelper : layer.env?.[name];
620
+ if (value === void 0) continue;
621
+ const on = CLOUD_FLAGS.includes(name) ? typeof value === "string" && /^(1|true|yes|on)$/i.test(value) : typeof value === "string" && value !== "";
622
+ return on ? { name, from: layer.from } : void 0;
623
+ }
624
+ return void 0;
625
+ };
626
+ for (const name of PRECEDENCE) {
627
+ const source = lookup(name);
628
+ if (!source) continue;
629
+ if (name === "ANTHROPIC_FEDERATION_RULE_ID" && !lookup("ANTHROPIC_ORGANIZATION_ID")) continue;
630
+ return source;
631
+ }
632
+ return void 0;
633
+ }
634
+ async function readAuthState(claudeConfigPath = CLAUDE_GLOBAL_CONFIG_FILE) {
635
+ const sharedPath = getSharedProjectSettingsPath();
636
+ const sharedIsUser = path4.resolve(sharedPath) === path4.resolve(CLAUDE_SETTINGS_FILE);
637
+ const [user, shared, local, config] = await Promise.all([
638
+ readUserSettings(),
639
+ sharedIsUser ? {} : readProjectSettings(sharedPath),
640
+ readProjectSettings(getProjectSettingsPath()),
641
+ readJsonFile(claudeConfigPath)
642
+ ]);
643
+ const source = resolveAuthSource([
644
+ { from: "shell", env: process.env },
645
+ { ...user, from: "user" },
646
+ { ...shared, from: "shared" },
647
+ { ...local, from: "local" }
648
+ ]);
649
+ const account = config?.oauthAccount;
650
+ return { account: account && typeof account === "object" ? account : void 0, source };
651
+ }
652
+ function describeAuthSource(source) {
653
+ const text = `${source.name} from ${ORIGIN_LABEL[source.from]}`;
654
+ return source.name === "ANTHROPIC_API_KEY" ? `${text} (once approved in Claude Code)` : text;
655
+ }
656
+ function loginOverrideWarning(source) {
657
+ let fix;
658
+ if (source.from === "shell") fix = `unset ${source.name} in your shell`;
659
+ else if (source.name === "ANTHROPIC_AUTH_TOKEN" && source.from === "user") fix = 'run "ccs reset"';
660
+ else if (source.name === "ANTHROPIC_AUTH_TOKEN" && source.from === "local") fix = 'run "ccs reset --project"';
661
+ else fix = `remove ${source.name} from ${ORIGIN_LABEL[source.from]}`;
662
+ return `Claude Code uses ${describeAuthSource(source)}, not your /login account. To use the login, ${fix}.`;
663
+ }
664
+
436
665
  // src/commands/status.ts
666
+ function providerFor(baseUrl, providers) {
667
+ let best;
668
+ let bestLength = -1;
669
+ for (const p of providers) {
670
+ for (const url of [p.baseUrl, ...Object.values(p.regions ?? {})]) {
671
+ if (baseUrl.startsWith(url) && url.length > bestLength) {
672
+ best = p;
673
+ bestLength = url.length;
674
+ }
675
+ }
676
+ }
677
+ return best;
678
+ }
437
679
  function registerStatusCommand(program2) {
438
680
  program2.command("status").description("Show current provider, model, and key status").action(async () => {
439
681
  const [userSettings, projectSettings] = await Promise.all([
440
682
  readUserSettings(),
441
683
  readProjectSettings()
442
684
  ]);
443
- const registry = loadRegistry();
685
+ const providers = Object.values(allProviders(await loadUserConfig()));
444
686
  for (const [scope, settings] of [
445
687
  ["User", userSettings],
446
688
  ["Project", projectSettings]
@@ -448,10 +690,7 @@ function registerStatusCommand(program2) {
448
690
  const env = settings.env ?? {};
449
691
  const baseUrl = env["ANTHROPIC_BASE_URL"];
450
692
  if (!baseUrl) continue;
451
- const providerEntry = Object.entries(registry.providers).find(
452
- ([, p]) => baseUrl.startsWith(p.baseUrl)
453
- );
454
- const providerName = providerEntry ? providerEntry[1].name : "Unknown";
693
+ const providerName = providerFor(baseUrl, providers)?.name ?? "Unknown";
455
694
  const model = env["ANTHROPIC_MODEL"] ?? "unknown";
456
695
  const key = env["ANTHROPIC_AUTH_TOKEN"] ?? "";
457
696
  console.log(`
@@ -470,6 +709,16 @@ ${scope} settings:`);
470
709
  if (!hasAny) {
471
710
  info('No provider configured. Run "ccs <provider>" to switch.');
472
711
  }
712
+ const { account, source } = await readAuthState();
713
+ const email = typeof account?.emailAddress === "string" ? account.emailAddress : void 0;
714
+ const org = typeof account?.organizationName === "string" ? account.organizationName : void 0;
715
+ console.log("\nClaude account:");
716
+ table([
717
+ ...CLAUDE_CONFIG_DIR ? [["Config dir", `${CLAUDE_CONFIG_DIR} (CLAUDE_CONFIG_DIR)`]] : [],
718
+ ["Login", email ? org ? `${email} (${org})` : email : "not logged in"],
719
+ ["Credential", source ? describeAuthSource(source) : email ? "/login" : "none"]
720
+ ]);
721
+ if (source && email) warn(loginOverrideWarning(source));
473
722
  });
474
723
  }
475
724
 
@@ -482,25 +731,33 @@ function thinkingIndicator(key, caps) {
482
731
  if (caps.includes("thinking")) return "on/off";
483
732
  return "";
484
733
  }
485
- function registerListCommand(program2) {
486
- program2.command("list").description("List all available providers").action(() => {
487
- const registry = loadRegistry();
488
- const providers = Object.entries(registry.providers);
489
- console.log(chalk2.bold("\nAvailable providers:\n"));
734
+ function printRows(title, providers) {
735
+ console.log(chalk2.bold(`
736
+ ${title}
737
+ `));
738
+ console.log(
739
+ chalk2.dim(
740
+ "Name".padEnd(14) + "Aliases".padEnd(18) + "Default Model".padEnd(32) + "Thinking".padEnd(12) + "Regions"
741
+ )
742
+ );
743
+ console.log(chalk2.dim("\u2500".repeat(90)));
744
+ for (const [key, provider] of providers) {
745
+ const aliases = [key, ...provider.aliases].join(", ");
746
+ const regions = provider.regions ? Object.keys(provider.regions).join(", ") : "global";
747
+ const thinking = thinkingIndicator(key, provider.supportedCapabilities);
490
748
  console.log(
491
- chalk2.dim(
492
- "Name".padEnd(14) + "Aliases".padEnd(18) + "Default Model".padEnd(32) + "Thinking".padEnd(12) + "Regions"
493
- )
749
+ chalk2.green(provider.name.padEnd(14)) + aliases.padEnd(18) + provider.defaultModel.padEnd(32) + chalk2.cyan(thinking.padEnd(12)) + chalk2.dim(regions)
494
750
  );
495
- console.log(chalk2.dim("\u2500".repeat(90)));
496
- for (const [key, provider] of providers) {
497
- const aliases = [key, ...provider.aliases].join(", ");
498
- const regions = provider.regions ? Object.keys(provider.regions).join(", ") : "global";
499
- const thinking = thinkingIndicator(key, provider.supportedCapabilities);
500
- console.log(
501
- chalk2.green(provider.name.padEnd(14)) + aliases.padEnd(18) + provider.defaultModel.padEnd(32) + chalk2.cyan(thinking.padEnd(12)) + chalk2.dim(regions)
502
- );
503
- }
751
+ }
752
+ }
753
+ function registerListCommand(program2) {
754
+ program2.command("list").description("List all available providers").action(async () => {
755
+ const userConfig = await loadUserConfig();
756
+ const builtin = loadRegistry().providers;
757
+ const all = Object.entries(allProviders(userConfig));
758
+ printRows("Available providers:", all.filter(([key]) => key in builtin));
759
+ const custom = all.filter(([key]) => !(key in builtin));
760
+ if (custom.length) printRows("Custom providers (~/.ccs/config.json):", custom);
504
761
  console.log();
505
762
  });
506
763
  }
@@ -508,17 +765,11 @@ function registerListCommand(program2) {
508
765
  // src/commands/config.ts
509
766
  function registerConfigCommand(program2) {
510
767
  program2.command("config").description("Interactive setup: configure API keys for providers").action(async () => {
511
- try {
512
- await initConfig();
513
- } catch (err) {
514
- error(String(err));
515
- process.exit(1);
516
- }
768
+ await initConfig();
517
769
  });
518
770
  }
519
771
 
520
772
  // src/commands/reset.ts
521
- import readline2 from "readline";
522
773
  function registerResetCommand(program2) {
523
774
  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) => {
524
775
  const scope = opts.all ? "all" : opts.project ? "project" : "user";
@@ -532,18 +783,9 @@ function registerResetCommand(program2) {
532
783
  success(`Cleared ${desc} settings.`);
533
784
  });
534
785
  }
535
- function confirm(prompt) {
536
- const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
537
- return new Promise((resolve) => {
538
- rl.question(`${prompt} [y/N] `, (answer) => {
539
- rl.close();
540
- resolve(answer.trim().toLowerCase() === "y");
541
- });
542
- });
543
- }
544
786
 
545
787
  // src/commands/doctor.ts
546
- import fs3 from "fs/promises";
788
+ import fs4 from "fs/promises";
547
789
  import chalk3 from "chalk";
548
790
  function registerDoctorCommand(program2) {
549
791
  program2.command("doctor").description("Diagnose common configuration issues").action(async () => {
@@ -552,17 +794,17 @@ function registerDoctorCommand(program2) {
552
794
  const [major] = nodeVersion.split(".").map(Number);
553
795
  checks.push({
554
796
  label: `Node.js version (${nodeVersion})`,
555
- pass: major >= 22,
556
- detail: major < 22 ? "ccs requires Node.js >=22" : void 0
797
+ pass: major >= 20,
798
+ detail: major < 20 ? "ccs requires Node.js >=20" : void 0
557
799
  });
558
800
  let claudeDirExists = false;
559
801
  try {
560
- await fs3.access(CLAUDE_DIR);
802
+ await fs4.access(CLAUDE_DIR);
561
803
  claudeDirExists = true;
562
804
  } catch {
563
805
  }
564
806
  checks.push({
565
- label: `Claude Code directory (~/.claude/)`,
807
+ label: `Claude Code directory (${CLAUDE_CONFIG_DIR ? `${CLAUDE_CONFIG_DIR}, from CLAUDE_CONFIG_DIR` : "~/.claude/"})`,
566
808
  pass: claudeDirExists,
567
809
  detail: claudeDirExists ? void 0 : "Not found. Is Claude Code installed?"
568
810
  });
@@ -604,39 +846,159 @@ function registerDoctorCommand(program2) {
604
846
  });
605
847
  }
606
848
 
607
- // src/commands/account.ts
608
- import readline3 from "readline";
849
+ // src/accounts/account-manager.ts
850
+ import fs6 from "fs/promises";
851
+ import path5 from "path";
852
+
853
+ // src/accounts/credential-store.ts
854
+ import fs5 from "fs/promises";
855
+ import os2 from "os";
856
+ import { createHash } from "crypto";
857
+ import { spawnSync } from "child_process";
858
+ function fileStore(filePath) {
859
+ return {
860
+ where: filePath,
861
+ async read() {
862
+ try {
863
+ return await fs5.readFile(filePath, "utf-8");
864
+ } catch {
865
+ return null;
866
+ }
867
+ },
868
+ async write(data) {
869
+ await writeFileAtomically(filePath, data, 384);
870
+ }
871
+ };
872
+ }
873
+ var KEYCHAIN_SERVICE = "Claude Code-credentials";
874
+ var KEYCHAIN_NOT_FOUND = 44;
875
+ var SECURITY_LINE_LIMIT = 4032;
876
+ function keychainAccount() {
877
+ let name;
878
+ try {
879
+ name = process.env.USER || os2.userInfo().username;
880
+ } catch {
881
+ return "claude-code-user";
882
+ }
883
+ return /^[a-zA-Z0-9._-]+$/.test(name) ? name : "claude-code-user";
884
+ }
885
+ function keychainService(configDir = CLAUDE_CONFIG_DIR) {
886
+ if (!configDir) return KEYCHAIN_SERVICE;
887
+ const hash = createHash("sha256").update(configDir.normalize("NFC")).digest("hex").slice(0, 8);
888
+ return `${KEYCHAIN_SERVICE}-${hash}`;
889
+ }
890
+ function keychainStore(service = keychainService(), account = keychainAccount()) {
891
+ return {
892
+ where: `macOS Keychain item "${service}"`,
893
+ async read() {
894
+ const res = spawnSync("security", ["find-generic-password", "-a", account, "-s", service, "-w"], {
895
+ encoding: "utf-8"
896
+ });
897
+ if (res.status === KEYCHAIN_NOT_FOUND) return null;
898
+ if (res.status !== 0) {
899
+ throw new Error(`Keychain read failed (security exit ${res.status}): ${res.stderr.trim()}`);
900
+ }
901
+ return res.stdout.trim();
902
+ },
903
+ async write(data) {
904
+ const hex = Buffer.from(data, "utf-8").toString("hex");
905
+ const line = `add-generic-password -U -a "${account}" -s "${service}" -X "${hex}"
906
+ `;
907
+ const res = line.length <= SECURITY_LINE_LIMIT ? spawnSync("security", ["-i"], { input: line, encoding: "utf-8" }) : spawnSync("security", ["add-generic-password", "-U", "-a", account, "-s", service, "-X", hex], {
908
+ encoding: "utf-8"
909
+ });
910
+ if (res.status !== 0) {
911
+ throw new Error(`Keychain write failed (security exit ${res.status}): ${res.stderr.trim()}`);
912
+ }
913
+ }
914
+ };
915
+ }
916
+ function defaultCredentialStore(platform = process.platform) {
917
+ const file = fileStore(CLAUDE_CREDENTIALS_FILE);
918
+ if (platform !== "darwin") return file;
919
+ const keychain = keychainStore();
920
+ return {
921
+ where: `${keychain.where} or ${file.where}`,
922
+ async read() {
923
+ return await keychain.read() ?? await file.read();
924
+ },
925
+ write: keychain.write
926
+ };
927
+ }
609
928
 
610
929
  // src/accounts/account-manager.ts
611
- import fs4 from "fs/promises";
612
- import path4 from "path";
613
- async function saveAccount(name, credentialsPath = CLAUDE_CREDENTIALS_FILE, accountsDir = CCS_ACCOUNTS_DIR) {
930
+ async function saveAccount(name, store = defaultCredentialStore(), accountsDir = CCS_ACCOUNTS_DIR, claudeConfigPath = CLAUDE_GLOBAL_CONFIG_FILE) {
931
+ const raw = await store.read();
614
932
  let credentials;
615
933
  try {
616
- const raw = await fs4.readFile(credentialsPath, "utf-8");
617
- credentials = JSON.parse(raw);
934
+ credentials = JSON.parse(raw ?? "");
618
935
  } catch {
619
- throw new Error(`Cannot read credentials at ${credentialsPath}. Are you logged in to Claude?`);
936
+ throw new Error(`Cannot read credentials from ${store.where}. Are you logged in to Claude?`);
620
937
  }
938
+ const claudeConfig = await readJsonFile(claudeConfigPath);
621
939
  await ensureDir(accountsDir);
622
- const snapshot = { credentials, savedAt: (/* @__PURE__ */ new Date()).toISOString() };
623
- await writeJsonFile(path4.join(accountsDir, `${name}.json`), snapshot, 384);
940
+ const snapshot = {
941
+ credentials,
942
+ oauthAccount: claudeConfig?.oauthAccount,
943
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
944
+ };
945
+ await writeJsonFile(path5.join(accountsDir, `${name}.json`), snapshot, 384);
624
946
  }
625
- async function switchAccount(name, credentialsPath = CLAUDE_CREDENTIALS_FILE, accountsDir = CCS_ACCOUNTS_DIR) {
626
- const accountPath = path4.join(accountsDir, `${name}.json`);
947
+ async function switchAccount(name, store = defaultCredentialStore(), accountsDir = CCS_ACCOUNTS_DIR, claudeConfigPath = CLAUDE_GLOBAL_CONFIG_FILE) {
948
+ const accountPath = path5.join(accountsDir, `${name}.json`);
627
949
  const snapshot = await readJsonFile(accountPath);
628
950
  if (!snapshot) throw new Error(`Account "${name}" not found.`);
629
- await ensureDir(path4.dirname(credentialsPath));
630
- await writeJsonFile(credentialsPath, snapshot.credentials, 384);
951
+ const claudeConfig = await readJsonFile(claudeConfigPath);
952
+ await saveBackCurrent(store, accountsDir, claudeConfig?.oauthAccount);
953
+ await store.write(JSON.stringify(snapshot.credentials));
954
+ if (snapshot.oauthAccount === void 0 || !claudeConfig) return;
955
+ claudeConfig.oauthAccount = snapshot.oauthAccount;
956
+ await writeJsonFile(claudeConfigPath, claudeConfig, 384);
631
957
  }
632
- async function listAccounts(accountsDir = CCS_ACCOUNTS_DIR) {
958
+ async function saveBackCurrent(store, accountsDir, currentAccount) {
959
+ let credentials;
633
960
  try {
634
- const files = await fs4.readdir(accountsDir);
961
+ credentials = JSON.parse(await store.read() ?? "");
962
+ } catch {
963
+ return;
964
+ }
965
+ const id = accountId(currentAccount);
966
+ if (!id) return;
967
+ for (const { name } of await listAccounts(accountsDir)) {
968
+ const file = path5.join(accountsDir, `${name}.json`);
969
+ const saved = await readJsonFile(file);
970
+ if (saved && accountId(saved.oauthAccount) === id) {
971
+ const snapshot = {
972
+ credentials,
973
+ oauthAccount: currentAccount,
974
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
975
+ };
976
+ await writeJsonFile(file, snapshot, 384);
977
+ return;
978
+ }
979
+ }
980
+ const email = currentAccount.emailAddress ?? id;
981
+ throw new Error(
982
+ `The current login (${email}) is not saved in any profile and would be lost. Run "ccs account save <name>" first.`
983
+ );
984
+ }
985
+ function accountId(oauthAccount) {
986
+ const a = oauthAccount;
987
+ return typeof a?.accountUuid === "string" ? `${a.accountUuid}/${String(a.organizationUuid)}` : void 0;
988
+ }
989
+ async function listAccounts(accountsDir = CCS_ACCOUNTS_DIR, claudeConfigPath = CLAUDE_GLOBAL_CONFIG_FILE) {
990
+ const current = accountId((await readJsonFile(claudeConfigPath))?.oauthAccount);
991
+ try {
992
+ const files = await fs6.readdir(accountsDir);
635
993
  const accounts = [];
636
994
  for (const file of files) {
637
995
  if (!file.endsWith(".json")) continue;
638
- const raw = await readJsonFile(path4.join(accountsDir, file));
639
- accounts.push({ name: file.replace(/\.json$/, ""), savedAt: raw?.savedAt ?? "" });
996
+ const raw = await readJsonFile(path5.join(accountsDir, file));
997
+ accounts.push({
998
+ name: file.replace(/\.json$/, ""),
999
+ savedAt: raw?.savedAt ?? "",
1000
+ active: current !== void 0 && accountId(raw?.oauthAccount) === current
1001
+ });
640
1002
  }
641
1003
  return accounts.sort((a, b) => a.name.localeCompare(b.name));
642
1004
  } catch {
@@ -644,9 +1006,9 @@ async function listAccounts(accountsDir = CCS_ACCOUNTS_DIR) {
644
1006
  }
645
1007
  }
646
1008
  async function deleteAccount(name, accountsDir = CCS_ACCOUNTS_DIR) {
647
- const accountPath = path4.join(accountsDir, `${name}.json`);
1009
+ const accountPath = path5.join(accountsDir, `${name}.json`);
648
1010
  try {
649
- await fs4.unlink(accountPath);
1011
+ await fs6.unlink(accountPath);
650
1012
  } catch {
651
1013
  throw new Error(`Account "${name}" not found.`);
652
1014
  }
@@ -668,6 +1030,8 @@ function registerAccountCommand(program2) {
668
1030
  try {
669
1031
  await switchAccount(name);
670
1032
  success(`Switched to account "${name}".`);
1033
+ const { source } = await readAuthState();
1034
+ if (source) warn(loginOverrideWarning(source));
671
1035
  } catch (err) {
672
1036
  error(String(err));
673
1037
  process.exit(1);
@@ -679,10 +1043,10 @@ function registerAccountCommand(program2) {
679
1043
  info('No saved accounts. Run "ccs account save <name>" to save one.');
680
1044
  return;
681
1045
  }
682
- table(accounts.map((a) => [a.name, a.savedAt]));
1046
+ table(accounts.map((a) => [(a.active ? "* " : " ") + a.name, a.savedAt]));
683
1047
  });
684
1048
  account.command("delete <name>").description("Delete a saved account profile").action(async (name) => {
685
- const confirmed = await confirm2(`Delete account "${name}"?`);
1049
+ const confirmed = await confirm(`Delete account "${name}"?`);
686
1050
  if (!confirmed) {
687
1051
  info("Cancelled.");
688
1052
  return;
@@ -696,19 +1060,196 @@ function registerAccountCommand(program2) {
696
1060
  }
697
1061
  });
698
1062
  }
699
- function confirm2(prompt) {
700
- const rl = readline3.createInterface({ input: process.stdin, output: process.stdout });
701
- return new Promise((resolve) => {
702
- rl.question(`${prompt} [y/N] `, (answer) => {
703
- rl.close();
704
- resolve(answer.trim().toLowerCase() === "y");
1063
+
1064
+ // src/commands/run.ts
1065
+ import { spawn } from "child_process";
1066
+ import fs7 from "fs/promises";
1067
+ import { rmSync } from "fs";
1068
+ import os3 from "os";
1069
+ import path6 from "path";
1070
+ function splitClaudeArgs(argv2) {
1071
+ const i = argv2.indexOf("--");
1072
+ if (argv2[2] !== "run" || i === -1) return { argv: argv2, claudeArgs: [] };
1073
+ return { argv: argv2.slice(0, i), claudeArgs: argv2.slice(i + 1) };
1074
+ }
1075
+ async function doRun(providerName, region, model, claudeArgs2) {
1076
+ if (CLAUDE_NATIVE_NAMES.has(providerName.toLowerCase())) {
1077
+ info(`Claude is Claude Code's native default. Run "claude" directly.`);
1078
+ return;
1079
+ }
1080
+ const { provider, envBlock } = await buildEnvBlock(providerName, region, model);
1081
+ const dir = await fs7.mkdtemp(path6.join(os3.tmpdir(), "ccs-run-"));
1082
+ const cleanup = () => rmSync(dir, { recursive: true, force: true });
1083
+ const settingsPath = path6.join(dir, "settings.json");
1084
+ try {
1085
+ await fs7.writeFile(settingsPath, JSON.stringify({ env: envBlock }), { mode: 384 });
1086
+ } catch (err) {
1087
+ cleanup();
1088
+ throw err;
1089
+ }
1090
+ const child = spawn("claude", ["--settings", settingsPath, ...claudeArgs2], { stdio: "inherit" });
1091
+ child.on("spawn", () => info(`Starting Claude Code with ${provider.name} (this session only)`));
1092
+ const ignore = () => {
1093
+ };
1094
+ const forward = (signal) => child.kill(signal);
1095
+ process.on("SIGINT", ignore);
1096
+ process.on("SIGTERM", forward);
1097
+ process.on("SIGHUP", forward);
1098
+ child.on("error", (err) => {
1099
+ cleanup();
1100
+ if (err.code === "ENOENT") {
1101
+ error("claude was not found on PATH. Install Claude Code: https://code.claude.com/docs/en/setup");
1102
+ } else {
1103
+ error(`Could not start claude: ${err.message}`);
1104
+ }
1105
+ process.exit(1);
1106
+ });
1107
+ child.on("exit", (code, signal) => {
1108
+ cleanup();
1109
+ if (signal) {
1110
+ process.removeAllListeners(signal);
1111
+ process.kill(process.pid, signal);
1112
+ return;
1113
+ }
1114
+ process.exit(code ?? 1);
1115
+ });
1116
+ }
1117
+ function registerRunCommand(program2, claudeArgs2) {
1118
+ program2.command("run <provider> [region]").description("Start Claude Code with a provider for this session only (claude args go after --)").option("-m, --model <id>", "Use this model ID for all of sonnet/opus/haiku").action(async (provider, region, opts) => {
1119
+ await doRun(provider, region, opts.model, claudeArgs2);
1120
+ });
1121
+ }
1122
+
1123
+ // src/commands/test.ts
1124
+ import chalk4 from "chalk";
1125
+ var TIMEOUT_MS = 6e4;
1126
+ var MAX_TOKENS = 256;
1127
+ function messagesUrl(baseUrl) {
1128
+ return (baseUrl.endsWith("/") ? baseUrl : baseUrl + "/") + "v1/messages?beta=true";
1129
+ }
1130
+ function errorMessage(text) {
1131
+ let msg = text;
1132
+ try {
1133
+ const body = JSON.parse(text);
1134
+ msg = body?.error?.message ?? body?.message ?? body?.msg ?? text;
1135
+ } catch {
1136
+ }
1137
+ msg = String(msg).replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
1138
+ return msg.length > 200 ? msg.slice(0, 200) + "..." : msg;
1139
+ }
1140
+ function statusReason(status) {
1141
+ if (status === 401 || status === 403) return `key rejected (HTTP ${status})`;
1142
+ if (status === 404) return "model or URL not found (HTTP 404)";
1143
+ if (status === 429) return "rate limited or out of quota (HTTP 429)";
1144
+ return `HTTP ${status}`;
1145
+ }
1146
+ function networkReason(err, url, providerName) {
1147
+ const e = err;
1148
+ if (e.name === "TimeoutError") return `no answer within ${TIMEOUT_MS / 1e3}s`;
1149
+ const code = e.cause?.code;
1150
+ if (code === "ECONNREFUSED") {
1151
+ const local = isLocal(url);
1152
+ return `connection refused by ${url.host}` + (local ? `. Is the ${providerName} server running?` : "");
1153
+ }
1154
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return `DNS lookup failed for ${url.hostname}`;
1155
+ if (code === "UND_ERR_CONNECT_TIMEOUT") return `could not connect to ${url.host} (timeout)`;
1156
+ return `request failed: ${e.cause?.message ?? e.message}`;
1157
+ }
1158
+ function isLocal(url) {
1159
+ return ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
1160
+ }
1161
+ async function checkModel(url, apiKey, model, providerName) {
1162
+ const started = Date.now();
1163
+ try {
1164
+ const res = await fetch(url, {
1165
+ method: "POST",
1166
+ headers: {
1167
+ authorization: `Bearer ${apiKey}`,
1168
+ "anthropic-version": "2023-06-01",
1169
+ "content-type": "application/json"
1170
+ },
1171
+ body: JSON.stringify({ model, max_tokens: MAX_TOKENS, messages: [{ role: "user", content: "Reply with OK." }] }),
1172
+ signal: AbortSignal.timeout(TIMEOUT_MS)
705
1173
  });
1174
+ const text = await res.text();
1175
+ if (res.ok) return { ok: true, reason: `${((Date.now() - started) / 1e3).toFixed(1)}s` };
1176
+ const msg = errorMessage(apiKey.length > 8 ? text.split(apiKey).join("***") : text);
1177
+ return { ok: false, reason: statusReason(res.status) + (msg ? `: ${msg}` : "") };
1178
+ } catch (err) {
1179
+ return { ok: false, reason: networkReason(err, new URL(url), providerName) };
1180
+ }
1181
+ }
1182
+ async function doTest(providerName, region, opts) {
1183
+ if (CLAUDE_NATIVE_NAMES.has(providerName.toLowerCase())) {
1184
+ info("Claude is Claude Code's native default. There is no provider to test.");
1185
+ return;
1186
+ }
1187
+ const { provider, baseUrl, apiKey } = await buildEnvBlock(providerName, region, opts.model);
1188
+ if (provider.testNote) {
1189
+ warn(provider.testNote);
1190
+ if (!opts.accept) {
1191
+ if (!process.stdin.isTTY) {
1192
+ error("No request sent. Pass --accept to send it without asking.");
1193
+ process.exit(1);
1194
+ }
1195
+ if (!await confirm("Send anyway?")) {
1196
+ info("No request sent.");
1197
+ process.exit(1);
1198
+ }
1199
+ }
1200
+ }
1201
+ const roles = /* @__PURE__ */ new Map();
1202
+ for (const [role, id] of Object.entries(provider.models)) roles.set(id, [...roles.get(id) ?? [], role]);
1203
+ const url = messagesUrl(baseUrl);
1204
+ const count = roles.size;
1205
+ const cost = isLocal(new URL(url)) ? " to a local server" : ", billed by the provider";
1206
+ info(`Testing ${provider.name} at ${baseUrl}: ${count} request${count === 1 ? "" : "s"}${cost}`);
1207
+ const ids = [...roles.keys()];
1208
+ const results = await Promise.all(ids.map((id) => checkModel(url, apiKey, id, provider.name)));
1209
+ ids.forEach((id, i) => {
1210
+ const { ok, reason } = results[i];
1211
+ const icon = ok ? chalk4.green("\u2713") : chalk4.red("\u2717");
1212
+ console.log(` ${icon} ${id} (${roles.get(id).join(", ")}) ${reason}`);
1213
+ });
1214
+ if (results.some((r) => !r.ok)) process.exit(1);
1215
+ }
1216
+ function registerTestCommand(program2) {
1217
+ program2.command("test <provider> [region]").description("Send one paid request per model ID to check the key, base URL and model IDs").option("-m, --model <id>", "Test only this model ID").option("--accept", "Send without asking when the provider warns about its terms").action(async (provider, region, opts) => {
1218
+ await doTest(provider, region, opts);
1219
+ });
1220
+ }
1221
+
1222
+ // src/commands/provider.ts
1223
+ function builtinKey(name) {
1224
+ for (const [key, p] of Object.entries(loadRegistry().providers)) {
1225
+ if (key === name || p.aliases.map((a) => a.toLowerCase()).includes(name)) return key;
1226
+ }
1227
+ }
1228
+ function registerProviderCommand(program2) {
1229
+ const provider = program2.command("provider").description("Add or remove custom providers");
1230
+ provider.command("add <name> <baseUrl>").description("Add a custom Anthropic-compatible provider").requiredOption("-m, --model <id>", "Model ID for sonnet, opus and haiku").action(async (name, baseUrl, opts) => {
1231
+ const key = name.toLowerCase();
1232
+ const config = await addCustomProvider(key, baseUrl, opts.model);
1233
+ const added = resolveProvider(key, config);
1234
+ success(`Added custom provider "${key}" (${baseUrl}, model ${opts.model})`);
1235
+ info(`API key: set ${added.keyEnvVar} or run "ccs config". Then run "ccs test ${key}".`);
1236
+ });
1237
+ provider.command("remove <name>").description("Remove a custom provider").action(async (name) => {
1238
+ const key = name.toLowerCase();
1239
+ const builtin = builtinKey(key);
1240
+ if (builtin) throw new Error(`"${key}" is the built-in provider "${builtin}". Only custom providers can be removed.`);
1241
+ const { keptKey } = await removeCustomProvider(key);
1242
+ success(`Removed custom provider "${key}"`);
1243
+ if (keptKey) {
1244
+ info(`Its API key stays in ${CCS_CONFIG_FILE} under keys.${key}. Delete it there if you no longer need it; adding "${key}" again is refused while it is there.`);
1245
+ }
706
1246
  });
707
1247
  }
708
1248
 
709
1249
  // src/cli.ts
710
1250
  var require2 = createRequire(import.meta.url);
711
1251
  var { version } = require2("../package.json");
1252
+ program.enablePositionalOptions();
712
1253
  program.name("ccs").description("Switch Claude Code between AI providers").version(version);
713
1254
  registerListCommand(program);
714
1255
  registerStatusCommand(program);
@@ -716,5 +1257,12 @@ registerConfigCommand(program);
716
1257
  registerResetCommand(program);
717
1258
  registerDoctorCommand(program);
718
1259
  registerAccountCommand(program);
1260
+ var { argv, claudeArgs } = splitClaudeArgs(process.argv);
1261
+ registerRunCommand(program, claudeArgs);
1262
+ registerTestCommand(program);
1263
+ registerProviderCommand(program);
719
1264
  registerSwitchCommand(program);
720
- program.parse();
1265
+ program.parseAsync(argv).catch((err) => {
1266
+ error(err instanceof Error ? err.message : String(err));
1267
+ process.exit(1);
1268
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-provider-switcher",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Switch Claude Code between AI providers with one command",
5
5
  "type": "module",
6
6
  "bin": {