Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

merge: origin/litellm_internal_staging into litellm_lite_claude_apikeyhelper_conflict

mateo-berriab9dc7541165
diff --cc litellm/proxy/client/cli/commands/auth.py
index a0bf9254bbc,24b1c766664..4f704afe9d6
--- a/litellm/proxy/client/cli/commands/auth.py
+++ b/litellm/proxy/client/cli/commands/auth.py
@@@ -41,10 -40,16 +41,16 @@@ from litellm.litellm_core_utils.cli_tok
)
from .claude_settings import (
- CLAUDE_SETTINGS_PATH,
- CONFIGURE_STATE_PATH,
- SETTINGS_FILE_OWNERS,
+ STARTING_MODEL_ROLE,
+ ApiKeyHelper,
ClaudeSettingsError,
+ KeepModel,
+ claude_settings_path,
+ configure_claude_settings,
++ configure_state_path,
+ refuse_while_owned,
+ resolve_api_key_helper,
+ settings_file_owners,
- write_claude_settings,
)
from .pkce_login import (
Http,
@@@ -779,14 -784,23 +785,24 @@@ def _render_and_prompt_for_team_selecti
def _configure_claude_code(base_url: str) -> None:
- """Point Claude Code at base_url by patching the settings.json it reads."""
- """Point Claude Code at base_url by patching ~/.claude/settings.json, undoable with `lite unconfigure claude`."""
++ """Point Claude Code at base_url by patching the settings.json it reads, undoable with `lite unconfigure claude`."""
+ settings_path: Final = claude_settings_path(os.environ)
try:
- write_claude_settings(base_url, settings_path, settings_file_owners(settings_path))
+ configure_claude_settings(
+ base_url,
+ ApiKeyHelper(resolve_api_key_helper(base_url)),
+ KeepModel(),
- CLAUDE_SETTINGS_PATH,
- CONFIGURE_STATE_PATH,
- SETTINGS_FILE_OWNERS,
++ settings_path,
++ configure_state_path(settings_path),
++ settings_file_owners(settings_path),
+ )
except ClaudeSettingsError as e:
raise click.ClickException(f"Logged in, but could not configure Claude Code: {e}")
- click.echo(f"\nConfigured Claude Code: {CLAUDE_SETTINGS_PATH} now routes through {base_url.rstrip('/')}.")
+ click.echo(f"\nConfigured Claude Code: {settings_path} now routes through {base_url.rstrip('/')}.")
- click.echo("Your other Claude Code settings were left untouched. Restart Claude Code to pick this up.")
+ click.echo(
+ "Your other Claude Code settings were left untouched. Restart Claude Code to pick this up. "
+ f"Undo with `lite unconfigure claude`; `lite configure claude --model` sets {STARTING_MODEL_ROLE}."
+ )
def _finish_login(base_url: str, api_key: str, config_claude: bool, stored: SecretSave) -> None:
@@@ -855,6 -869,11 +871,12 @@@ def login(ctx: click.Context, config_cl
ctx_obj: Final[CliContextObj] = ctx.obj
base_url: Final = ctx_obj["base_url"]
+ if config_claude:
++ settings_path: Final = claude_settings_path(os.environ)
+ try:
- refuse_while_owned(CLAUDE_SETTINGS_PATH, SETTINGS_FILE_OWNERS)
++ refuse_while_owned(settings_path, settings_file_owners(settings_path))
+ except ClaudeSettingsError as e:
+ raise click.ClickException(f"Cannot configure Claude Code, so not logging in: {e}")
try:
if pkce:
diff --cc litellm/proxy/client/cli/commands/claude_settings.py
index 793728b0350,bd9cf85dc59..d0ee507f0b2
--- a/litellm/proxy/client/cli/commands/claude_settings.py
+++ b/litellm/proxy/client/cli/commands/claude_settings.py
@@@ -28,11 -41,30 +41,31 @@@ ENABLE_TOOL_SEARCH_KEY: Final = "ENABLE
ENABLE_TOOL_SEARCH_VALUE: Final = "true"
ENABLE_GATEWAY_MODEL_DISCOVERY_KEY: Final = "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"
ENABLE_GATEWAY_MODEL_DISCOVERY_VALUE: Final = "1"
+ ANTHROPIC_DEFAULT_MODEL_ENV_KEYS: Final = (
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
+ "ANTHROPIC_DEFAULT_OPUS_MODEL",
+ "ANTHROPIC_DEFAULT_FABLE_MODEL",
+ )
+ OWNED_ENV_KEYS: Final = (
+ ENABLE_TOOL_SEARCH_KEY,
+ ENABLE_GATEWAY_MODEL_DISCOVERY_KEY,
+ ANTHROPIC_BASE_URL_KEY,
+ ANTHROPIC_AUTH_TOKEN_KEY,
+ ANTHROPIC_API_KEY_KEY,
+ )
+ OWNED_TOP_LEVEL_KEYS: Final = (API_KEY_HELPER_KEY, MODEL_KEY)
+ OWNED_PATHS: Final = (*(f"{ENV_KEY}.{key}" for key in OWNED_ENV_KEYS), *OWNED_TOP_LEVEL_KEYS)
+ _CREDENTIAL_ENV_KEYS: Final = frozenset((ANTHROPIC_API_KEY_KEY, ANTHROPIC_AUTH_TOKEN_KEY))
+ _CREDENTIAL_PATHS: Final = (*(f"{ENV_KEY}.{key}" for key in sorted(_CREDENTIAL_ENV_KEYS)), API_KEY_HELPER_KEY)
+ _BASE_URL_PATH: Final = f"{ENV_KEY}.{ANTHROPIC_BASE_URL_KEY}"
+ STARTING_MODEL_ROLE: Final = "the /model picker's default row, the model Claude Code starts on"
CLAUDE_SETTINGS_PATH: Final = Path.home() / ".claude" / "settings.json"
+CLAUDE_CONFIG_DIR_ENV: Final = "CLAUDE_CONFIG_DIR"
BACKUP_PATH: Final = Path.home() / ".litellm" / "claude_settings_backup.json"
AUTOROUTE_BACKUP_PATH: Final = Path.home() / ".litellm" / "autorouter" / "claude_settings_backup.json"
+ CONFIGURE_STATE_PATH: Final = Path.home() / ".litellm" / "claude_configure_state.json"
@dataclass(frozen=True, slots=True)
@@@ -56,17 -88,100 +89,127 @@@ class ClaudeSettingsError(Exception)
"""Raised for any user-actionable failure while reading or writing Claude Code settings."""
+def claude_settings_path(environ: Mapping[str, str]) -> Path:
+ """The settings.json Claude Code reads: under CLAUDE_CONFIG_DIR when set, else ~/.claude/settings.json."""
+ config_dir: Final = environ.get(CLAUDE_CONFIG_DIR_ENV, "")
+ if not config_dir:
+ return CLAUDE_SETTINGS_PATH
+ return Path(config_dir).expanduser() / "settings.json"
+
+
++def _is_default_settings_file(settings_path: Path) -> bool:
++ return settings_path.resolve() == CLAUDE_SETTINGS_PATH.resolve()
++
++
+def settings_file_owners(settings_path: Path) -> tuple[SettingsFileOwner, ...]:
+ """The commands whose backups guard settings_path: `lite up` and `lite autoroute up` only ever manage the default file."""
- return SETTINGS_FILE_OWNERS if settings_path.resolve() == CLAUDE_SETTINGS_PATH.resolve() else ()
++ return SETTINGS_FILE_OWNERS if _is_default_settings_file(settings_path) else ()
++
++
++def configure_state_path(settings_path: Path) -> Path:
++ """The receipt describing settings_path: the default file keeps CONFIGURE_STATE_PATH, and any other file
++ (a CLAUDE_CONFIG_DIR) gets its own beside it, keyed by its resolved path, so two settings files never
++ share one undo record."""
++ if _is_default_settings_file(settings_path):
++ return CONFIGURE_STATE_PATH
++ digest: Final = hashlib.sha256(str(settings_path.resolve()).encode()).hexdigest()
++ return CONFIGURE_STATE_PATH.parent / CONFIGURE_STATE_PATH.stem / f"{digest}.json"
++
++
+ @dataclass(frozen=True, slots=True)
+ class StaticToken:
+ """A long-lived virtual key, written into env.ANTHROPIC_AUTH_TOKEN."""
+
+ token: str
+
+
+ @dataclass(frozen=True, slots=True)
+ class ApiKeyHelper:
+ """A `lite auth print-token` command Claude Code runs per request, so a login renews in place."""
+
+ command: str
+
+
+ ClaudeCredential: TypeAlias = StaticToken | ApiKeyHelper
+
+
+ @dataclass(frozen=True, slots=True)
+ class KeepModel:
+ """Leave the top-level `model` as it is, the user's or an earlier configure's (a re-login)."""
+
+
+ @dataclass(frozen=True, slots=True)
+ class UnpinModel:
+ """Let go of a `model` an earlier configure pinned; one the user set themselves stays."""
+
+
+ @dataclass(frozen=True, slots=True)
+ class StartOn:
+ """Pin the top-level `model`, the row Claude Code starts on."""
+
+ model: str
+
+
+ ModelChoice: TypeAlias = KeepModel | UnpinModel | StartOn
+
+
+ class OwnedValue(BaseModel):
+ """What one key held at a moment in time; `present=False` is an absent key, not a null one."""
+
+ model_config = ConfigDict(frozen=True)
+
+ present: bool
+ value: JsonValue = None
+
+
+ class ConfigureReceipt(BaseModel):
+ """What `lite configure claude` found and what it owns, keyed by dotted path (`env.X` or a top-level key).
+
+ Ownership moves only by a write: `written` fingerprints the keys some configure changed, at the
+ value it wrote; a repeat configure refreshes a fingerprint only for a key its merge changed and
+ carries the earlier one otherwise, so a key the user edited in between stops matching and is left
+ alone. `previous` is what each key held before configure took it over; a repeat keeps the earlier
+ snapshot while the key still holds our value and snapshots afresh otherwise, so whatever the
+ repeat displaces is what comes back. `endpoints` is the ANTHROPIC_BASE_URL each credential slot
+ was captured beside, so a credential is only ever put back next to the server it was issued for.
+ No fingerprint is a second copy of a token.
+ """
+
+ model_config = ConfigDict(frozen=True)
+
+ file_existed: bool
+ env_present: bool
+ env_was_object: bool
+ previous: Mapping[str, OwnedValue]
+ written: Mapping[str, str]
+ endpoints: Mapping[str, OwnedValue]
+
+
+ @dataclass(frozen=True, slots=True)
+ class WithheldCredential:
+ """A credential left removed: captured beside `endpoint`, while the restored file points elsewhere."""
+
+ key: str
+ endpoint: str
+
+
+ @dataclass(frozen=True, slots=True)
+ class UnconfigureOutcome:
+ """Keys whose value unconfigure changed back, keys the user changed since and so were left as they
+ are, credentials withheld (the receipt is kept for them, so a later unconfigure can finish once the
+ URL points back), and whether no settings file remains."""
+
+ restored: tuple[str, ...]
+ kept: tuple[str, ...]
+ withheld: tuple[WithheldCredential, ...] = ()
+ file_removed: bool = False
+
+
+ @dataclass(frozen=True, slots=True)
+ class _Claim:
+ previous: OwnedValue
+ written: str | None
+ endpoint: OwnedValue | None
def load_json_or_empty(path: Path) -> dict[str, JsonValue]:
@@@ -135,50 -325,214 +353,227 @@@ def resolve_api_key_helper(base_url: st
return " ".join(quote(token) for token in (lite_path, "--base-url", base_url, "auth", "print-token"))
+def lite_api_key_helper_configured(base_url: str, settings_path: Path) -> bool:
+ """Whether settings_path already carries the apiKeyHelper `lite login --config-claude` writes for base_url.
+
+ Only an exact match counts: a helper for another proxy, a hand-written one, or
+ settings that cannot be read leave the caller on the env-token path.
+ """
+ try:
+ configured_helper: Final = load_json_or_empty(settings_path).get(API_KEY_HELPER_KEY)
+ return configured_helper == resolve_api_key_helper(base_url.rstrip("/"))
+ except ClaudeSettingsError:
+ return False
+
+
- def write_claude_settings(base_url: str, settings_path: Path, owners: Sequence[SettingsFileOwner]) -> None:
- """Persistently point Claude Code at base_url, preserving every unrelated setting.
+ def _owned(container: Mapping[str, JsonValue], key: str) -> OwnedValue:
+ return OwnedValue(present=key in container, value=container.get(key))
+
+
+ def _fingerprint(owned: OwnedValue) -> str:
+ return hashlib.sha256(json.dumps(owned.model_dump(mode="json"), sort_keys=True).encode()).hexdigest()
+
+
+ def _env(settings: Mapping[str, JsonValue]) -> Mapping[str, JsonValue]:
+ raw_env: Final = settings.get(ENV_KEY)
+ return raw_env if isinstance(raw_env, dict) else MappingProxyType({})
+
+
+ def _lookup(settings: Mapping[str, JsonValue], path: str) -> OwnedValue:
+ section, _, key = path.rpartition(".")
+ return _owned(_env(settings) if section else settings, key)
+
+
+ def _with_key(container: Mapping[str, JsonValue], key: str, owned: OwnedValue) -> Mapping[str, JsonValue]:
+ return dict( # mutable-ok: JSON document handed to json.dump, which rejects a read-only mapping
+ chain(((k, v) for k, v in container.items() if k != key), ((key, owned.value),) if owned.present else ())
+ )
- Refuses while any owner holds a backup: each restores its backup when it
- stops, which would silently undo this write.
+
+ def _with(settings: Mapping[str, JsonValue], path: str, owned: OwnedValue) -> Mapping[str, JsonValue]:
+ """`settings` with the key at `path` set (or removed when `owned` is absent); nothing else changes."""
+ section, _, key = path.rpartition(".")
+ if not section:
+ return _with_key(settings, key, owned)
+ return _with_key(settings, section, OwnedValue(present=True, value=_with_key(_env(settings), key, owned)))
+
+
+ def _with_all(settings: Mapping[str, JsonValue], updates: Mapping[str, OwnedValue]) -> Mapping[str, JsonValue]:
+ return reduce(lambda acc, item: _with(acc, *item), updates.items(), settings)
+
+
+ def _ours(settings: Mapping[str, JsonValue], path: str, receipt: ConfigureReceipt) -> bool:
+ """Whether the key still holds what a configure wrote (a key no configure ever changed is never ours)."""
+ return receipt.written.get(path) == _fingerprint(_lookup(settings, path))
+
+
+ def _claim(
+ path: str,
+ current: Mapping[str, JsonValue],
+ merged: Mapping[str, JsonValue],
+ earlier: ConfigureReceipt | None,
+ url_now: OwnedValue,
+ ) -> _Claim:
+ """What this configure records for one key; see ConfigureReceipt for the rules."""
+ before, after = _lookup(current, path), _lookup(merged, path)
+ carried: Final = earlier if earlier is not None and _ours(current, path, earlier) else None
+ return _Claim(
+ previous=before if carried is None else carried.previous.get(path, before),
+ written=_fingerprint(after) if before != after else (None if earlier is None else earlier.written.get(path)),
+ endpoint=None
+ if path not in _CREDENTIAL_PATHS
+ else (url_now if carried is None else carried.endpoints.get(path, url_now)),
+ )
+
+
+ def _receipt(
+ current: Mapping[str, JsonValue],
+ merged: Mapping[str, JsonValue],
+ earlier: ConfigureReceipt | None,
+ file_exists: bool,
+ ) -> ConfigureReceipt:
+ url_now: Final = _lookup(current, _BASE_URL_PATH)
+ claims: Final = MappingProxyType({path: _claim(path, current, merged, earlier, url_now) for path in OWNED_PATHS})
+ return ConfigureReceipt(
+ file_existed=file_exists if earlier is None else earlier.file_existed,
+ env_present=ENV_KEY in current if earlier is None else earlier.env_present,
+ env_was_object=isinstance(current.get(ENV_KEY), dict) if earlier is None else earlier.env_was_object,
+ previous=MappingProxyType({path: claim.previous for path, claim in claims.items()}),
+ written=MappingProxyType({path: claim.written for path, claim in claims.items() if claim.written is not None}),
+ endpoints=MappingProxyType(
+ {path: claim.endpoint for path, claim in claims.items() if claim.endpoint is not None}
+ ),
+ )
+
+
+ def read_configure_receipt(state_path: Path) -> ConfigureReceipt | None:
+ if not state_path.exists():
+ return None
+ try:
+ return ConfigureReceipt.model_validate_json(state_path.read_bytes())
+ except (OSError, ValidationError) as e:
+ raise ClaudeSettingsError(
+ f"{state_path} is not a readable `lite configure claude` receipt ({e}). "
+ "Remove it and edit Claude Code's settings by hand if they still point at the proxy."
+ ) from e
+
+
+ def configure_claude_settings(
+ base_url: str,
+ credential: ClaudeCredential,
+ model: ModelChoice,
+ settings_path: Path,
+ state_path: Path,
+ owners: Sequence[SettingsFileOwner],
+ commit: Callable[[str, str], None] = commit_staged_json,
+ ) -> None:
+ """Persistently route Claude Code through base_url, recording how to undo it.
+
+ Both files are staged before either is committed, so a full disk or a read-only directory fails
+ before anything changes. The two commits are still two renames: a receipt rename that fails
+ discards the staged settings, and a settings rename that fails after the receipt landed puts the
+ earlier receipt back (or removes the new one), so the receipt on disk never describes settings
+ that were not written. `model`: StartOn pins the starting model, UnpinModel lets go of a pin an
+ earlier configure made (never of the user's own), KeepModel leaves it alone (a re-login).
"""
- for owner in owners:
- if owner.backup_path.exists():
+ refuse_while_owned(settings_path, owners)
+ current: Final = load_json_or_empty(settings_path)
+ _env_object(current, settings_path)
+ earlier: Final = read_configure_receipt(state_path)
+ existing: Final = (
+ _with(current, MODEL_KEY, earlier.previous[MODEL_KEY])
+ if isinstance(model, UnpinModel) and earlier is not None and _ours(current, MODEL_KEY, earlier)
+ else current
+ )
+ merged: Final = merge_claude_settings(
+ existing, base_url, credential, model.model if isinstance(model, StartOn) else None
+ )
+ receipt: Final = _receipt(current, merged, earlier, settings_path.exists())
+ target: Final = _write_target(settings_path)
+ try:
+ ensure_private_dir(state_path.parent)
+ except OSError as e:
+ raise ClaudeSettingsError(f"Could not write {state_path}: {e}") from e
+ staged_receipt: Final = _stage(state_path, receipt.model_dump(mode="json"))
+ try:
+ staged_settings: Final = _stage(target, merged)
+ except ClaudeSettingsError:
+ discard_staged_json(staged_receipt)
+ raise
+ _land(state_path, staged_receipt, (staged_settings,), commit)
+ try:
+ _land(target, staged_settings, commit=commit)
+ except ClaudeSettingsError as settings_error:
+ try:
+ _land(state_path, None if earlier is None else _stage(state_path, earlier.model_dump(mode="json")))
+ except ClaudeSettingsError as receipt_error:
raise ClaudeSettingsError(
- f"`{owner.start_command}` is currently managing {settings_path} (backup at "
- f"{owner.backup_path}) and will restore it when it stops. "
- f"Run `{owner.stop_command}` first, then retry."
- )
- normalized_base_url: Final = base_url.rstrip("/")
- api_key_helper: Final = resolve_api_key_helper(normalized_base_url)
- existing: Final = load_json_or_empty(settings_path)
- raw_env: Final = existing.get(ENV_KEY)
- if raw_env is not None and not isinstance(raw_env, dict):
+ f"{settings_error} The receipt at {state_path} now describes settings that were not written and "
+ f"could not be put back either ({receipt_error}); remove it before retrying."
+ ) from settings_error
+ raise
+
+
+ def _endpoint_text(endpoint: OwnedValue) -> str:
+ if not endpoint.present:
+ return f"no {ANTHROPIC_BASE_URL_KEY} (Anthropic's default endpoint)"
+ return endpoint.value if isinstance(endpoint.value, str) else json.dumps(endpoint.value)
+
+
+ def unconfigure_claude_settings(
+ settings_path: Path, state_path: Path, owners: Sequence[SettingsFileOwner]
+ ) -> UnconfigureOutcome:
+ """Undo `lite configure claude`: put back every key still holding what configure wrote, leave the
+ rest alone, and withhold a credential the restored file would send to a different server than it
+ was issued for (the receipt stays, owning only those slots, so a later unconfigure can finish)."""
+ refuse_while_owned(settings_path, owners)
+ receipt: Final = read_configure_receipt(state_path)
+ if receipt is None:
raise ClaudeSettingsError(
- f'{settings_path} has a non-object "{ENV_KEY}" value, which this would discard. '
- "Fix or remove it, then retry."
+ f"Claude Code is not configured by `lite configure claude` (no receipt at {state_path}); nothing to undo."
)
- merged: Final = merge_claude_settings(existing, normalized_base_url, api_key_helper)
- # os.replace() swaps the symlink itself for a regular file, silently detaching a
- # settings.json that is symlinked into a dotfiles repo. There is no backup to undo
- # that here, unlike `lite up`, so write through to the link's target instead.
- target: Final = settings_path.resolve() if settings_path.is_symlink() else settings_path
+ current: Final = load_json_or_empty(settings_path)
+ _env_object(current, settings_path)
+ ours: Final = tuple(path for path in receipt.written if _ours(current, path, receipt))
+ kept: Final = tuple(path for path in receipt.written if path not in ours and _lookup(current, path).present)
+ put_back: Final = _with_all(current, MappingProxyType({path: receipt.previous[path] for path in ours}))
+ url_after: Final = _lookup(put_back, _BASE_URL_PATH)
+ withheld: Final = tuple(
+ WithheldCredential(path, _endpoint_text(receipt.endpoints[path]))
+ for path in _CREDENTIAL_PATHS
+ if path in ours and receipt.previous[path].present and receipt.endpoints[path] != url_after
+ )
+ absent: Final = OwnedValue(present=False)
+ trimmed: Final = _with_all(put_back, MappingProxyType({item.key: absent for item in withheld}))
+ settings: Final = (
+ trimmed
+ if _env(trimmed) or receipt.env_was_object
+ else _with_key(trimmed, ENV_KEY, OwnedValue(present=receipt.env_present, value=None))
+ )
+ target: Final = _write_target(settings_path)
+ file_removed: Final = not settings and not (receipt.file_existed and target.exists())
+ kept_receipt: Final = ( # mutable-ok: pydantic serializes the update as given and rejects a mappingproxy
+ receipt.model_copy(update={"written": {item.key: _fingerprint(absent) for item in withheld}})
+ if withheld
+ else None
+ )
+ staged_settings: Final = None if file_removed else _stage(target, settings)
try:
- write_private_json(str(target), merged)
- except OSError as e:
- raise ClaudeSettingsError(f"Could not write {target}: {e}") from e
+ staged_receipt: Final = (
+ None if kept_receipt is None else _stage(state_path, kept_receipt.model_dump(mode="json"))
+ )
+ except ClaudeSettingsError:
+ if staged_settings is not None:
+ discard_staged_json(staged_settings)
+ raise
+ _land(target, staged_settings, (staged_receipt,))
+ _land(state_path, staged_receipt)
+ return UnconfigureOutcome(
+ restored=tuple(path for path in ours if _lookup(current, path) != _lookup(settings, path)),
+ kept=kept,
+ withheld=withheld,
+ file_removed=file_removed,
+ )
__all__ = (
@@@ -187,21 -543,37 +584,42 @@@
"API_KEY_HELPER_KEY",
"AUTOROUTE_BACKUP_PATH",
"BACKUP_PATH",
+ "CLAUDE_CONFIG_DIR_ENV",
"CLAUDE_SETTINGS_PATH",
+ "CONFIGURE_STATE_PATH",
"ENABLE_GATEWAY_MODEL_DISCOVERY_KEY",
"ENABLE_GATEWAY_MODEL_DISCOVERY_VALUE",
"ENABLE_TOOL_SEARCH_KEY",
"ENABLE_TOOL_SEARCH_VALUE",
"ENV_KEY",
+ "MODEL_KEY",
+ "OWNED_ENV_KEYS",
+ "OWNED_PATHS",
+ "OWNED_TOP_LEVEL_KEYS",
"SETTINGS_FILE_OWNERS",
+ "STARTING_MODEL_ROLE",
+ "ApiKeyHelper",
+ "ClaudeCredential",
"ClaudeSettingsError",
+ "ConfigureReceipt",
+ "KeepModel",
+ "ModelChoice",
+ "OwnedValue",
"SettingsFileOwner",
+ "StartOn",
+ "StaticToken",
+ "UnconfigureOutcome",
+ "UnpinModel",
+ "WithheldCredential",
+ "claude_settings_path",
+ "configure_claude_settings",
++ "configure_state_path",
+ "lite_api_key_helper_configured",
"load_json_or_empty",
"merge_claude_settings",
+ "read_configure_receipt",
+ "refuse_while_owned",
"resolve_api_key_helper",
+ "settings_file_owners",
- "write_claude_settings",
+ "unconfigure_claude_settings",
)
diff --cc litellm/proxy/client/cli/commands/configure.py
index 00000000000,f3a98a48476..83fbd323924
mode 000000,100644..100644
--- a/litellm/proxy/client/cli/commands/configure.py
+++ b/litellm/proxy/client/cli/commands/configure.py
@@@ -1,0 -1,252 +1,262 @@@
+ """`lite configure claude` and `lite unconfigure claude`: persistent Claude Code wiring, undoable."""
+
++import os
+ import re
+ import sys
+ from collections.abc import Callable, Sequence
+ from pathlib import Path
+ from typing import Final
+
+ import click
+ from InquirerPy import inquirer
+ from InquirerPy.base.control import Choice
+
+ from .auth import CliContextObj, context_secret_vault, get_stored_api_key
+ from .claude_settings import (
- CLAUDE_SETTINGS_PATH,
- CONFIGURE_STATE_PATH,
- SETTINGS_FILE_OWNERS,
+ STARTING_MODEL_ROLE,
+ ApiKeyHelper,
+ ClaudeCredential,
+ ClaudeSettingsError,
+ ModelChoice,
+ StartOn,
+ StaticToken,
+ UnconfigureOutcome,
+ UnpinModel,
++ claude_settings_path,
+ configure_claude_settings,
++ configure_state_path,
+ refuse_while_owned,
+ resolve_api_key_helper,
++ settings_file_owners,
+ unconfigure_claude_settings,
+ )
+ from .pi import ListingFailure, PiSyncError, fetch_model_ids
+ from .up import ensure_fresh_login
+
+ _LISTED_MODELS_SHOWN: Final = 20
+ _CLAUDE_TARGET: Final = "claude"
+ _TARGETS: Final = ((_CLAUDE_TARGET, "Claude Code (CLI)"),)
+ _KEEP_DEFAULT_MODEL: Final = "Keep Claude Code's own default"
+ _CLAUDE_CODE_PICKER_FILTER: Final = re.compile(r"claude|anthropic", re.IGNORECASE)
+ _MODEL_OPTION_HELP: Final = (
+ f"Proxy model to set as {STARTING_MODEL_ROLE}. Must be listed on /v1/models for the key; without it, "
+ "Claude Code keeps its own default and a pin an earlier configure made is let go of. Nothing pins Claude "
+ "Code's sub-agent or background tiers; `lite autoroute up` is the mode that does."
+ )
+
+
+ def resolve_credential(ctx: click.Context, api_key: str | None) -> tuple[ClaudeCredential, str]:
+ """The credential to write and the key to check the proxy with.
+
+ An explicit key (--api-key, `lite --api-key`, LITELLM_PROXY_API_KEY) is long-lived and goes
+ into settings.json as a static token. Without one, the stored `lite login` credential is used
+ the way `lite login --config-claude` uses it, through apiKeyHelper, since it expires within a
+ day and renews in place there; a missing or stale login is refreshed first, as `lite up` does.
+ """
+ ctx_obj: Final[CliContextObj] = ctx.obj
+ explicit: Final = api_key or (None if ctx_obj.get("api_key_from_token_file") else ctx_obj.get("api_key"))
+ if explicit:
+ return StaticToken(explicit), explicit
+ base_url: Final = ctx_obj["base_url"]
+ ensure_fresh_login(ctx)
+ stored: Final = get_stored_api_key(expected_base_url=base_url, vault=context_secret_vault(ctx))
+ if not stored:
+ raise ClaudeSettingsError("Login did not produce a usable token.")
+ return ApiKeyHelper(resolve_api_key_helper(base_url)), stored
+
+
+ def _start(ctx: click.Context, api_key: str | None) -> tuple[ClaudeCredential, tuple[str, ...]]:
+ """Every configure path begins the same way: the local ownership check first, so a `lite up`
+ session is refused before any login prompt or request, then the credential, then the listing."""
++ settings_path: Final = claude_settings_path(os.environ)
+ try:
- refuse_while_owned(CLAUDE_SETTINGS_PATH, SETTINGS_FILE_OWNERS)
++ refuse_while_owned(settings_path, settings_file_owners(settings_path))
+ credential, key = resolve_credential(ctx, api_key)
+ except ClaudeSettingsError as e:
+ raise click.ClickException(str(e))
+ return credential, _listed_models(ctx.obj["base_url"], key)
+
+
+ def _listing_error(base_url: str, error: PiSyncError) -> str:
+ """The hint that fits how the listing failed: only an unreachable proxy gets the "is it running" question."""
+ if error.kind is ListingFailure.REJECTED:
+ return f"LiteLLM rejected your key (HTTP {error.status}). Run `lite login` to refresh it, or pass a valid --api-key."
+ if error.kind is ListingFailure.UNREACHABLE:
+ return f"{error.message} Is the proxy at {base_url} running, and is --base-url (or LITELLM_PROXY_URL) correct?"
+ if error.kind is ListingFailure.EMPTY:
+ return f"{error.message} Claude Code would have nothing to run; give the key access to at least one model."
+ return f"{error.message} The proxy at {base_url} answered, so check that it is a LiteLLM proxy and is healthy."
+
+
+ def _listed_models(base_url: str, key: str) -> tuple[str, ...]:
+ listed: Final = fetch_model_ids(base_url, key)
+ if isinstance(listed, PiSyncError):
+ raise click.ClickException(_listing_error(base_url, listed))
+ return listed
+
+
+ def _model_choice(model: str | None) -> ModelChoice:
+ return StartOn(model) if model is not None else UnpinModel()
+
+
+ def _apply_claude(ctx: click.Context, credential: ClaudeCredential, listed: Sequence[str], model: str | None) -> None:
+ ctx_obj: Final[CliContextObj] = ctx.obj
+ base_url: Final = ctx_obj["base_url"]
+ if model is not None and model not in listed:
+ shown: Final = ", ".join(listed[:_LISTED_MODELS_SHOWN])
+ more: Final = f", and {len(listed) - _LISTED_MODELS_SHOWN} more" if len(listed) > _LISTED_MODELS_SHOWN else ""
+ raise click.ClickException(
+ f"{model!r} is not served by {base_url} for this key. /v1/models lists: {shown}{more}."
+ )
++ settings_path: Final = claude_settings_path(os.environ)
+ try:
+ configure_claude_settings(
- base_url, credential, _model_choice(model), CLAUDE_SETTINGS_PATH, CONFIGURE_STATE_PATH, SETTINGS_FILE_OWNERS
++ base_url,
++ credential,
++ _model_choice(model),
++ settings_path,
++ configure_state_path(settings_path),
++ settings_file_owners(settings_path),
+ )
+ except ClaudeSettingsError as e:
+ raise click.ClickException(str(e))
+ in_picker: Final = sum(1 for listed_model in listed if _CLAUDE_CODE_PICKER_FILTER.search(listed_model))
- click.echo(f"Configured Claude Code: {CLAUDE_SETTINGS_PATH} now routes through {base_url}.")
++ click.echo(f"Configured Claude Code: {settings_path} now routes through {base_url}.")
+ click.echo(
+ "Credential: your virtual key, stored in the file as ANTHROPIC_AUTH_TOKEN."
+ if isinstance(credential, StaticToken)
+ else "Credential: your `lite login`, read through apiKeyHelper on every request, so a later login renews it."
+ )
+ click.echo(
+ f"Starting model: {model} ({STARTING_MODEL_ROLE}); switch any time with /model."
+ if model is not None
+ else "Starting model: not pinned (Claude Code's default, or a model you set yourself); switch with /model, or "
+ "pass --model to start on a proxy model."
+ )
+ click.echo(
+ f"/model will list {in_picker} of the proxy's {len(listed)} models (Claude Code shows only ids containing "
+ "'claude' or 'anthropic')."
+ )
+ click.echo("Start `claude` from any terminal. Undo with `lite unconfigure claude`.")
- if isinstance(credential, StaticToken) and CLAUDE_SETTINGS_PATH.is_symlink():
++ if isinstance(credential, StaticToken) and settings_path.is_symlink():
+ click.echo(
- f"Note: {CLAUDE_SETTINGS_PATH} is a symlink to {CLAUDE_SETTINGS_PATH.resolve()}, so your key now lives in "
++ f"Note: {settings_path} is a symlink to {settings_path.resolve()}, so your key now lives in "
+ "that file; keep it out of version control.",
+ err=True,
+ )
+
+
+ def _pick_targets() -> tuple[str, ...]:
+ picked: Final = inquirer.checkbox(
+ message="Which agents should route through LiteLLM?",
+ choices=[Choice(value, name=label, enabled=True) for value, label in _TARGETS],
+ validate=lambda chosen: len(chosen) > 0,
+ invalid_message="Pick at least one.",
+ ).execute()
+ return tuple(str(value) for value in picked)
+
+
+ def _pick_model(listed: Sequence[str]) -> str | None:
+ picked: Final = inquirer.fuzzy(
+ message="Model Claude Code starts on (type to filter; /model switches any time):",
+ choices=[_KEEP_DEFAULT_MODEL, *listed],
+ ).execute()
+ return None if picked == _KEEP_DEFAULT_MODEL else str(picked)
+
+
+ def interactive_configure(
+ ctx: click.Context,
+ pick_targets: Callable[[], tuple[str, ...]] = _pick_targets,
+ pick_model: Callable[[Sequence[str]], str | None] = _pick_model,
+ ) -> None:
+ """`lite configure` with no agent named: ask which agents to wire and which model to pin."""
+ targets: Final = pick_targets()
+ if _CLAUDE_TARGET not in targets:
+ return
+ credential, listed = _start(ctx, None)
+ _apply_claude(ctx, credential, listed, pick_model(listed))
+
+
+ @click.group(name="configure", invoke_without_command=True)
+ @click.pass_context
+ def configure_group(ctx: click.Context) -> None:
+ """Persistently route a coding agent through your LiteLLM proxy.
+
+ With no agent named, asks which agents to wire and which proxy model to pin.
+ """
+ if ctx.invoked_subcommand is not None:
+ return
+ if not sys.stdin.isatty():
+ raise click.ClickException(
+ "`lite configure` asks questions, so it needs a terminal. Non-interactively, run "
+ "`lite configure claude --api-key <key> --model <model>`."
+ )
+ interactive_configure(ctx)
+
+
+ @click.group(name="unconfigure")
+ def unconfigure_group() -> None:
+ """Undo `lite configure` for a coding agent."""
+
+
+ @configure_group.command(name="claude")
+ @click.option(
+ "--api-key",
+ "api_key",
+ default=None,
+ help="Long-lived LiteLLM virtual key written into Claude Code's settings. Defaults to the `lite --api-key` / "
+ "LITELLM_PROXY_API_KEY value; with neither, your `lite login` credential is used through apiKeyHelper.",
+ )
+ @click.option("--model", default=None, help=_MODEL_OPTION_HELP)
+ @click.pass_context
+ def configure_claude(ctx: click.Context, api_key: str | None, model: str | None) -> None:
+ """Route every Claude Code session through your LiteLLM proxy until `lite unconfigure claude`.
+
+ Patches ~/.claude/settings.json in place: the proxy URL, your credential (a virtual key as a
+ static token, or your `lite login` through apiKeyHelper), and gateway model discovery so
+ /model lists the proxy's models; --model picks the one Claude Code starts on. Every other
+ setting is kept, and what changed is recorded so `lite unconfigure claude` can put it back.
+ Assumes the proxy is already running.
+ """
+ credential, listed = _start(ctx, api_key)
+ _apply_claude(ctx, credential, listed, model)
+
+
+ @unconfigure_group.command(name="claude")
+ def unconfigure_claude() -> None:
+ """Return Claude Code's settings to what they were before `lite configure claude`.
+
+ Also undoes `lite login --config-claude`. Only keys still holding what configure wrote are
+ put back; anything you changed since is left as it is and named in the output.
+ """
++ settings_path: Final = claude_settings_path(os.environ)
++ state_path: Final = configure_state_path(settings_path)
+ try:
- outcome: Final = unconfigure_claude_settings(CLAUDE_SETTINGS_PATH, CONFIGURE_STATE_PATH, SETTINGS_FILE_OWNERS)
++ outcome: Final = unconfigure_claude_settings(settings_path, state_path, settings_file_owners(settings_path))
+ except ClaudeSettingsError as e:
+ raise click.ClickException(str(e))
- _report_unconfigure(CLAUDE_SETTINGS_PATH, CONFIGURE_STATE_PATH, outcome)
++ _report_unconfigure(settings_path, state_path, outcome)
+
+
+ def _report_unconfigure(settings_path: Path, state_path: Path, outcome: UnconfigureOutcome) -> None:
+ """Say what unconfigure did, naming only keys whose value it changed."""
+ if outcome.file_removed:
+ click.echo(
+ f"No settings file remains at {settings_path}; it held nothing but `lite configure claude`'s own keys."
+ )
+ elif outcome.restored:
+ click.echo(f"Restored in {settings_path}: {', '.join(outcome.restored)}.")
+ else:
+ click.echo(f"Nothing in {settings_path} was still ours to restore.")
+ if outcome.kept:
+ click.echo(f"Left as you changed them since: {', '.join(outcome.kept)}.")
+ if outcome.withheld:
+ click.echo(
+ "Left removed, since the file now points at a different server than they were issued for: "
+ + "; ".join(f"{item.key} (captured with {item.endpoint})" for item in outcome.withheld)
+ + f". They stay in {state_path}: point env.ANTHROPIC_BASE_URL back and run `lite unconfigure claude` "
+ "again to put them back, or delete that file to drop them."
+ )
+
+
+ __all__ = ("configure_group", "interactive_configure", "resolve_credential", "unconfigure_group")
diff --cc tests/test_litellm/proxy/client/cli/test_auth_commands.py
index d3e6d8f66ef,7d5cb61c062..1f314e0c9d8
--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py
+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py
@@@ -6,7 -6,7 +6,6 @@@ from pathlib import Pat
from unittest.mock import Mock, patch
--
import pytest
from click.testing import CliRunner
@@@ -27,6 -27,7 +26,7 @@@ from litellm.proxy.client.cli.commands.
print_token,
whoami,
)
-from litellm.proxy.client.cli.commands import auth as auth_module
++from litellm.proxy.client.cli.commands import claude_settings as claude_settings_module
from litellm.proxy.client.cli.commands.claude_settings import SettingsFileOwner
@@@ -84,7 -85,7 +84,7 @@@ class TestPollingErrorSurfacing
}
with patch("requests.get", return_value=mock_response) as mock_get, patch("time.sleep"):
-- with pytest.raises(ValueError, match='Your litellm CLI is out of date and uses a login flow') as exc_info:
++ with pytest.raises(ValueError, match="Your litellm CLI is out of date and uses a login flow") as exc_info:
_poll_for_ready_data("http://test/sso/cli/poll/sk-legacy")
assert mock_get.call_count == 1
@@@ -151,7 -152,7 +151,7 @@@ class TestStartCliSsoFlowErrors
mock_response.status_code = 404
with patch("requests.post", return_value=mock_response):
-- with pytest.raises(ValueError, match='Either --base-url is wrong, or the proxy is older than') as exc_info:
++ with pytest.raises(ValueError, match="Either --base-url is wrong, or the proxy is older than") as exc_info:
_start_cli_sso_flow("https://old-proxy.example.com")
message = str(exc_info.value)
@@@ -167,7 -168,7 +167,7 @@@
mock_response.json.return_value = {"detail": "Too many CLI login attempts. Try again later."}
with patch("requests.post", return_value=mock_response):
-- with pytest.raises(ValueError, match='Too many CLI login attempts\\. Try again later\\.') as exc_info:
++ with pytest.raises(ValueError, match="Too many CLI login attempts\\. Try again later\\.") as exc_info:
_start_cli_sso_flow("https://test.example.com")
assert "HTTP 429" in str(exc_info.value)
@@@ -183,7 -184,7 +183,7 @@@
mock_response.text = "<html>Sign in to corporate VPN</html>"
with patch("requests.post", return_value=mock_response):
-- with pytest.raises(ValueError, match='A proxy, load balancer, or auth gateway in front of') as exc_info:
++ with pytest.raises(ValueError, match="A proxy, load balancer, or auth gateway in front of") as exc_info:
_start_cli_sso_flow("https://test.example.com")
message = str(exc_info.value)
@@@ -197,7 -198,7 +197,7 @@@
from litellm.proxy.client.cli.commands.auth import _start_cli_sso_flow
with patch("requests.post", side_effect=requests.ConnectionError("Connection refused")):
-- with pytest.raises(ValueError, match='Connection refused\\. Check that the proxy is running') as exc_info:
++ with pytest.raises(ValueError, match="Connection refused\\. Check that the proxy is running") as exc_info:
_start_cli_sso_flow("https://unreachable.example.com")
message = str(exc_info.value)
@@@ -584,13 -585,13 +584,9 @@@ class TestLogoutCommand
assert "could not be checked" in result.output
assert DISABLE_KEYRING_ENV_VAR in result.output
-- def test_logout_warns_when_the_keychain_refuses_to_release_the_entry(
-- self, isolated_home, secret_vault_factory
-- ):
++ def test_logout_warns_when_the_keychain_refuses_to_release_the_entry(self, isolated_home, secret_vault_factory):
"""A locked keychain leaves a live credential behind that the user believes is gone."""
-- vault = secret_vault_factory(
-- blob=_secret_blob("https://test.example.com", "sk-stored"), erasable=False
-- )
++ vault = secret_vault_factory(blob=_secret_blob("https://test.example.com", "sk-stored"), erasable=False)
_write_token_file(isolated_home, key=None)
result = self.runner.invoke(logout, obj={"secret_vault": vault})
@@@ -1210,9 -1211,9 +1206,7 @@@ class TestKeychainBackedCommands
assert str(token_file) in result.output
assert json.loads(token_file.read_text())["key"] == "sk-minted"
-- def test_login_points_a_user_missing_the_keyring_package_at_the_install(
-- self, isolated_home, secret_vault_factory
-- ):
++ def test_login_points_a_user_missing_the_keyring_package_at_the_install(self, isolated_home, secret_vault_factory):
"""`lite` ships with every install, the keyring package only with the cli extra. Telling
that user their machine has no keychain sends them looking for a problem they do not have."""
result = self._login(secret_vault_factory(available=False, failure=KeyringNotInstalled()))
@@@ -1223,9 -1224,9 +1217,7 @@@
assert "No OS keychain available" not in result.output
assert json.loads(token_file.read_text())["key"] == "sk-minted"
-- def test_login_keeps_the_credential_when_the_backend_keeps_nothing(
-- self, isolated_home, secret_vault_factory
-- ):
++ def test_login_keeps_the_credential_when_the_backend_keeps_nothing(self, isolated_home, secret_vault_factory):
"""A backend that accepts writes and stores nothing must not be reported as keychain
storage, because the file is then told to drop the only remaining copy."""
result = self._login(secret_vault_factory(discards=True))
@@@ -1236,9 -1237,9 +1228,7 @@@
assert "keyring --enable" in result.output
assert json.loads(token_file.read_text())["key"] == "sk-minted"
-- def test_login_names_the_kill_switch_instead_of_blaming_the_machine(
-- self, isolated_home, secret_vault_factory
-- ):
++ def test_login_names_the_kill_switch_instead_of_blaming_the_machine(self, isolated_home, secret_vault_factory):
result = self._login(secret_vault_factory(available=False, failure=KeyringDisabled()))
assert result.exit_code == 0
@@@ -1297,9 -1298,9 +1287,7 @@@
assert "could not be read" in result.output
assert "lite login" in result.output
-- def test_whoami_does_not_call_a_credential_it_cannot_read_authenticated(
-- self, isolated_home, secret_vault_factory
-- ):
++ def test_whoami_does_not_call_a_credential_it_cannot_read_authenticated(self, isolated_home, secret_vault_factory):
"""A login whose secret is stuck in an unreachable keychain authenticates nothing. Leading
with "Authenticated" and a token age reads as a working session, and sends the user looking
for the problem somewhere other than the keychain the notice underneath names."""
@@@ -1316,9 -1317,9 +1304,7 @@@
assert "the credential cannot be read" in result.output
assert "could not be read" in result.output
-- def test_whoami_names_the_kill_switch_rather_than_a_missing_package(
-- self, isolated_home, secret_vault_factory
-- ):
++ def test_whoami_names_the_kill_switch_rather_than_a_missing_package(self, isolated_home, secret_vault_factory):
"""Every unreachable keychain used to be described as a locked one needing the keyring
package installed. Someone who set the kill switch has the package and an unlocked keychain,
so that advice sends them to fix two things that were never wrong."""
@@@ -1330,9 -1331,9 +1316,7 @@@
assert DISABLE_KEYRING_ENV_VAR in result.output
assert "pip install" not in result.output
-- def test_print_token_points_an_install_without_keyring_at_the_package(
-- self, isolated_home, secret_vault_factory
-- ):
++ def test_print_token_points_an_install_without_keyring_at_the_package(self, isolated_home, secret_vault_factory):
_write_token_file(isolated_home, key=None)
vault = secret_vault_factory(available=False, failure=KeyringNotInstalled())
obj = {"base_url": "https://test.example.com", "secret_vault": vault}
@@@ -1398,10 -1399,11 +1382,22 @@@ class TestLoginConfigClaude
def setup_method(self):
self.runner = CliRunner()
- def _run_login(self, tmp_path, args, base_url="https://test.example.com", *, config_dir_env=None):
- def _run_login(self, tmp_path, monkeypatch, args, base_url="https://test.example.com"):
-- settings_path = tmp_path / "claude" / "settings.json"
- monkeypatch.setattr(auth_module, "CLAUDE_SETTINGS_PATH", settings_path)
- monkeypatch.setattr(auth_module, "CONFIGURE_STATE_PATH", tmp_path / "claude_configure_state.json")
++ def _isolate_default_settings(self, tmp_path, monkeypatch):
++ """The default file, its `lite up` backup and its configure receipt all live under tmp_path."""
backup_path = tmp_path / "claude_settings_backup.json"
++ monkeypatch.setattr(
++ claude_settings_module, "SETTINGS_FILE_OWNERS", (SettingsFileOwner(backup_path, "lite up", "lite down"),)
++ )
++ monkeypatch.setattr(
++ claude_settings_module, "CLAUDE_SETTINGS_PATH", tmp_path / "default-home" / ".claude" / "settings.json"
++ )
++ monkeypatch.setattr(claude_settings_module, "CONFIGURE_STATE_PATH", tmp_path / "claude_configure_state.json")
++ return backup_path
++
++ def _run_login(self, tmp_path, monkeypatch, args, base_url="https://test.example.com", *, config_dir_env=None):
++ settings_path = tmp_path / "claude" / "settings.json"
++ backup_path = self._isolate_default_settings(tmp_path, monkeypatch)
+ env = {"CLAUDE_CONFIG_DIR": str(settings_path.parent)} if config_dir_env is None else config_dir_env
poll_response = Mock()
poll_response.status_code = 200
poll_response.json.return_value = {
@@@ -1417,24 -1419,20 +1413,16 @@@
patch("requests.get", return_value=poll_response),
patch("litellm.proxy.client.cli.commands.auth.save_cli_token"),
patch("litellm.proxy.client.cli.interface.show_commands"),
-- patch(
- "litellm.proxy.client.cli.commands.claude_settings.SETTINGS_FILE_OWNERS",
- "litellm.proxy.client.cli.commands.auth.SETTINGS_FILE_OWNERS",
-- (SettingsFileOwner(backup_path, "lite up", "lite down"),),
- ),
- patch(
- "litellm.proxy.client.cli.commands.claude_settings.CLAUDE_SETTINGS_PATH",
- tmp_path / "default-home" / ".claude" / "settings.json",
-- ),
patch(
"litellm.proxy.client.cli.commands.claude_settings.shutil.which",
return_value="/usr/local/bin/lite",
),
):
- result = self.runner.invoke(login, args, obj={"base_url": base_url})
+ result = self.runner.invoke(login, args, obj={"base_url": base_url}, env=env)
return result, settings_path, backup_path
- def test_default_login_does_not_touch_claude_settings(self, tmp_path):
- result, settings_path, _backup_path = self._run_login(tmp_path, [])
+ def test_default_login_does_not_touch_claude_settings(self, tmp_path, monkeypatch):
+ result, settings_path, _backup_path = self._run_login(tmp_path, monkeypatch, [])
assert result.exit_code == 0
assert "Login successful!" in result.output
@@@ -1449,9 -1447,11 +1437,11 @@@
assert written["env"]["ANTHROPIC_BASE_URL"] == "https://test.example.com"
assert written["env"]["ENABLE_TOOL_SEARCH"] == "true"
assert written["apiKeyHelper"] == "/usr/local/bin/lite --base-url https://test.example.com auth print-token"
- assert "Configured Claude Code" in result.output
+ assert f"Configured Claude Code: {settings_path} now routes through https://test.example.com." in result.output
+ assert "pins a proxy model for every tier" not in result.output
+ assert "the model Claude Code starts on" in result.output
- def test_flag_preserves_unrelated_settings_on_an_existing_file(self, tmp_path):
+ def test_flag_preserves_unrelated_settings_on_an_existing_file(self, tmp_path, monkeypatch):
settings_path = tmp_path / "claude" / "settings.json"
settings_path.parent.mkdir(parents=True)
settings_path.write_text(json.dumps({"theme": "dark", "env": {"KEEP": "me"}}))
@@@ -1463,46 -1463,23 +1453,57 @@@
assert written["theme"] == "dark"
assert written["env"]["KEEP"] == "me"
- def test_flag_refuses_while_lite_up_holds_the_default_settings_file(self, tmp_path):
- default_settings_path = tmp_path / "default-home" / ".claude" / "settings.json"
- (tmp_path / "claude_settings_backup.json").write_text("{}")
-
- result, _settings_path, _backup_path = self._run_login(
- tmp_path, ["--config-claude"], config_dir_env={"CLAUDE_CONFIG_DIR": ""}
- def test_refuses_before_logging_in_while_lite_up_holds_the_settings(self, tmp_path, monkeypatch):
- # The local precondition comes first: no browser, no token stored, no "Login successful!".
- backup_path = tmp_path / "claude_settings_backup.json"
- backup_path.write_text("{}")
- monkeypatch.setattr(auth_module, "CLAUDE_SETTINGS_PATH", tmp_path / "claude" / "settings.json")
- monkeypatch.setattr(
- auth_module, "SETTINGS_FILE_OWNERS", (SettingsFileOwner(backup_path, "lite up", "lite down"),)
-- )
-
++ def _run_login_refused_before_the_sso_flow(self, tmp_path, monkeypatch, config_dir):
++ self._isolate_default_settings(tmp_path, monkeypatch).write_text("{}")
+ with patch("requests.post") as post, patch("webbrowser.open") as browser:
- result = self.runner.invoke(login, ["--config-claude"], obj={"base_url": "https://test.example.com"})
++ result = self.runner.invoke(
++ login,
++ ["--config-claude"],
++ obj={"base_url": "https://test.example.com"},
++ env={"CLAUDE_CONFIG_DIR": config_dir},
++ )
assert result.exit_code != 0
- assert "Login successful!" in result.output
+ assert "not logging in" in result.output and "lite down" in result.output
+ assert "`lite up` is currently managing" in result.output
- assert "Run `lite down` first" in result.output
- assert not default_settings_path.exists()
+ assert "Login successful!" not in result.output
+ post.assert_not_called()
+ browser.assert_not_called()
++ assert not (tmp_path / "default-home" / ".claude" / "settings.json").exists()
+
- def test_flag_refuses_while_lite_up_holds_the_default_file_reached_through_a_symlinked_config_dir(self, tmp_path):
++ def test_refuses_before_logging_in_while_lite_up_holds_the_default_settings_file(self, tmp_path, monkeypatch):
++ self._run_login_refused_before_the_sso_flow(tmp_path, monkeypatch, config_dir="")
++
++ def test_refuses_before_logging_in_while_lite_up_holds_the_default_file_reached_through_a_symlink(
++ self, tmp_path, monkeypatch
++ ):
+ default_config_dir = tmp_path / "default-home" / ".claude"
+ default_config_dir.mkdir(parents=True)
+ alias = tmp_path / "claude-alias"
+ alias.symlink_to(default_config_dir, target_is_directory=True)
- (tmp_path / "claude_settings_backup.json").write_text("{}")
-
- result, _settings_path, _backup_path = self._run_login(
- tmp_path, ["--config-claude"], config_dir_env={"CLAUDE_CONFIG_DIR": str(alias)}
- )
+
- assert result.exit_code != 0
- assert "`lite up` is currently managing" in result.output
- assert not (default_config_dir / "settings.json").exists()
++ self._run_login_refused_before_the_sso_flow(tmp_path, monkeypatch, config_dir=str(alias))
+
- def test_flag_writes_an_alternate_config_dir_even_while_lite_up_holds_the_default_file(self, tmp_path):
++ def test_flag_writes_an_alternate_config_dir_even_while_lite_up_holds_the_default_file(self, tmp_path, monkeypatch):
+ (tmp_path / "claude_settings_backup.json").write_text("{}")
+
- result, settings_path, _backup_path = self._run_login(tmp_path, ["--config-claude"])
++ result, settings_path, _backup_path = self._run_login(tmp_path, monkeypatch, ["--config-claude"])
+
+ assert result.exit_code == 0, result.output
+ written = json.loads(settings_path.read_text())
+ assert written["apiKeyHelper"] == "/usr/local/bin/lite --base-url https://test.example.com auth print-token"
+ assert f"Configured Claude Code: {settings_path} now routes through https://test.example.com." in result.output
+
- def test_settings_failure_is_reported_without_claiming_login_failed(self, tmp_path):
++ def test_flag_keeps_a_config_dir_receipt_apart_from_the_default_file_receipt(self, tmp_path, monkeypatch):
++ result, settings_path, _backup_path = self._run_login(tmp_path, monkeypatch, ["--config-claude"])
++
++ assert result.exit_code == 0, result.output
++ default_receipt = tmp_path / "claude_configure_state.json"
++ assert not default_receipt.exists()
++ receipts = list((tmp_path / "claude_configure_state").glob("*.json"))
++ assert len(receipts) == 1
++ assert json.loads(receipts[0].read_text())["file_existed"] is False
+
+ def test_settings_failure_is_reported_without_claiming_login_failed(self, tmp_path, monkeypatch):
settings_path = tmp_path / "claude" / "settings.json"
settings_path.parent.mkdir(parents=True)
settings_path.write_text("not json at all {{{")
@@@ -1896,7 -1873,7 +1897,10 @@@ class TestPkcePrintToken
assert result.stdout == ""
assert sum(len(session.posts) for session in _FakeSession.instances) == 1
assert result.output.count("Could not renew the key") == 1
-- assert "Could not renew the key: token request failed with 400: the refresh token was already used" in result.output
++ assert (
++ "Could not renew the key: token request failed with 400: the refresh token was already used"
++ in result.output
++ )
assert "Key expired. Run 'lite login --pkce' again." in result.output
save.assert_not_called()
diff --cc tests/test_litellm/proxy/client/cli/test_claude_settings.py
index 0ff92567abc,9072fe26b00..fc2d98f2264
--- a/tests/test_litellm/proxy/client/cli/test_claude_settings.py
+++ b/tests/test_litellm/proxy/client/cli/test_claude_settings.py
@@@ -10,17 -10,25 +11,30 @@@ from click.testing import CliRunne
from litellm.litellm_core_utils.cli_token_utils import CliTokenRecord
from litellm.proxy.client.cli import cli
+ from litellm.litellm_core_utils.private_json import commit_staged_json
from litellm.proxy.client.cli.commands.claude_settings import (
+ ANTHROPIC_DEFAULT_MODEL_ENV_KEYS,
AUTOROUTE_BACKUP_PATH,
BACKUP_PATH,
+ CLAUDE_SETTINGS_PATH,
++ CONFIGURE_STATE_PATH,
+ OWNED_ENV_KEYS,
+ OWNED_TOP_LEVEL_KEYS,
SETTINGS_FILE_OWNERS,
+ ApiKeyHelper,
ClaudeSettingsError,
+ KeepModel,
SettingsFileOwner,
+ StartOn,
+ StaticToken,
+ UnpinModel,
+ claude_settings_path,
+ configure_claude_settings,
++ configure_state_path,
+ lite_api_key_helper_configured,
+ merge_claude_settings,
resolve_api_key_helper,
- write_claude_settings,
+ unconfigure_claude_settings,
)
@@@ -363,57 -390,451 +396,562 @@@ class TestDoesNotDestroyUserOwnedStruct
assert json.loads(settings_path.read_text())["env"] == "not-an-object"
+class TestClaudeSettingsPath:
+ def test_defaults_to_the_home_settings_file(self):
+ assert claude_settings_path({}) == CLAUDE_SETTINGS_PATH
+ assert claude_settings_path({"CLAUDE_CONFIG_DIR": ""}) == CLAUDE_SETTINGS_PATH
+
+ def test_follows_claude_config_dir_like_claude_code_does(self, tmp_path):
+ assert claude_settings_path({"CLAUDE_CONFIG_DIR": str(tmp_path)}) == tmp_path / "settings.json"
+
+ def test_expands_a_tilde_in_claude_config_dir(self):
+ assert claude_settings_path({"CLAUDE_CONFIG_DIR": "~/.claude-work"}) == (
+ Path.home() / ".claude-work" / "settings.json"
+ )
+
+
++class TestConfigureStatePath:
++ """Each settings file gets its own undo receipt: the default file keeps the long-standing path, and
++ a CLAUDE_CONFIG_DIR file gets one keyed by its resolved location, so `lite unconfigure claude`
++ under one config dir never restores the other file's history."""
++
++ @pytest.fixture
++ def default_paths(self, tmp_path):
++ default_settings = tmp_path / "home" / ".claude" / "settings.json"
++ default_state = tmp_path / "home" / ".litellm" / "claude_configure_state.json"
++ with (
++ patch(f"{CLAUDE_SETTINGS_MODULE}.CLAUDE_SETTINGS_PATH", default_settings),
++ patch(f"{CLAUDE_SETTINGS_MODULE}.CONFIGURE_STATE_PATH", default_state),
++ ):
++ yield default_settings, default_state
++
++ def test_the_default_file_keeps_the_default_receipt(self, default_paths):
++ default_settings, default_state = default_paths
++ assert configure_state_path(default_settings) == default_state
++
++ def test_a_symlink_alias_of_the_default_file_shares_its_receipt(self, default_paths):
++ default_settings, default_state = default_paths
++ default_settings.parent.mkdir(parents=True)
++ alias = default_settings.parent.parent / "claude-alias"
++ alias.symlink_to(default_settings.parent, target_is_directory=True)
++ assert configure_state_path(alias / "settings.json") == default_state
++
++ def test_another_settings_file_gets_a_receipt_of_its_own_beside_the_default_one(self, default_paths, tmp_path):
++ _default_settings, default_state = default_paths
++ work_state = configure_state_path(tmp_path / "work" / "settings.json")
++ play_state = configure_state_path(tmp_path / "play" / "settings.json")
++ assert work_state != default_state and play_state != default_state
++ assert work_state != play_state
++ assert work_state.parent == play_state.parent == default_state.parent / "claude_configure_state"
++ assert work_state == configure_state_path(tmp_path / "work" / "settings.json")
++
++ def test_configure_and_unconfigure_under_a_config_dir_leave_the_default_receipt_alone(
++ self, default_paths, tmp_path, lite_on_path
++ ):
++ _default_settings, default_state = default_paths
++ work_settings = tmp_path / "work" / "settings.json"
++ work_state = configure_state_path(work_settings)
++ configure_claude_settings(
++ "https://proxy.example.com",
++ ApiKeyHelper(resolve_api_key_helper("https://proxy.example.com")),
++ KeepModel(),
++ work_settings,
++ work_state,
++ (),
++ )
++ assert work_state.exists() and not default_state.exists()
++ outcome = unconfigure_claude_settings(work_settings, work_state, ())
++ assert outcome.file_removed and not work_settings.exists()
++ assert not work_state.exists()
++
++
+class TestLiteApiKeyHelperConfigured:
+ def _settings(self, tmp_path, payload):
+ settings_path = tmp_path / "settings.json"
+ settings_path.write_text(payload)
+ return settings_path
+
+ def test_recognises_the_helper_lite_login_wrote_for_this_proxy(self, tmp_path, lite_on_path):
+ settings_path = tmp_path / "settings.json"
- write_claude_settings("https://proxy.example.com/", settings_path, ())
++ _helper_configure("https://proxy.example.com/", settings_path, (), tmp_path / "state.json")
+
+ assert lite_api_key_helper_configured("https://proxy.example.com/", settings_path) is True
+ assert lite_api_key_helper_configured("https://proxy.example.com", settings_path) is True
+
+ def test_a_helper_for_another_proxy_does_not_count(self, tmp_path, lite_on_path):
+ settings_path = tmp_path / "settings.json"
- write_claude_settings("https://other.example.com", settings_path, ())
++ _helper_configure("https://other.example.com", settings_path, (), tmp_path / "state.json")
+
+ assert lite_api_key_helper_configured("https://proxy.example.com", settings_path) is False
+
+ def test_a_hand_written_helper_does_not_count(self, tmp_path, lite_on_path):
+ settings_path = self._settings(tmp_path, json.dumps({"apiKeyHelper": "cat ~/.my-proxy-key"}))
+
+ assert lite_api_key_helper_configured("https://proxy.example.com", settings_path) is False
+
+ def test_missing_or_helperless_settings_do_not_count(self, tmp_path, lite_on_path):
+ assert lite_api_key_helper_configured("https://proxy.example.com", tmp_path / "absent.json") is False
+ helperless = json.dumps({"env": {"ANTHROPIC_BASE_URL": "https://proxy.example.com"}})
+ settings_path = self._settings(tmp_path, helperless)
+ assert lite_api_key_helper_configured("https://proxy.example.com", settings_path) is False
+
+ def test_unreadable_settings_fall_back_to_false(self, tmp_path, lite_on_path):
+ settings_path = self._settings(tmp_path, "{not json")
+
+ assert lite_api_key_helper_configured("https://proxy.example.com", settings_path) is False
+
+ def test_lite_missing_from_path_falls_back_to_false(self, tmp_path):
+ helper = "/usr/local/bin/lite --base-url https://proxy.example.com auth print-token"
+ settings_path = self._settings(tmp_path, json.dumps({"apiKeyHelper": helper}))
+ with patch(f"{CLAUDE_SETTINGS_MODULE}.shutil.which", return_value=None):
+ assert lite_api_key_helper_configured("https://proxy.example.com", settings_path) is False
++
++
+ class TestMergeClaudeSettings:
+ """One merge for every way Claude Code gets wired: `lite up`, `lite login --config-claude`,
+ `lite configure claude` and `lite autoroute up`."""
+
+ def test_a_static_token_lands_in_env_and_the_helper_slot_is_cleared(self):
+ settings = {"apiKeyHelper": "/usr/local/bin/lite auth print-token", "env": {"ANTHROPIC_API_KEY": "leaked"}}
+ merged = merge_claude_settings(settings, "http://127.0.0.1:4000/", StaticToken("token-abc"))
+ assert merged["env"]["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:4000"
+ assert merged["env"]["ANTHROPIC_AUTH_TOKEN"] == "token-abc"
+ assert merged["env"]["ENABLE_TOOL_SEARCH"] == "true"
+ assert merged["env"]["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"
+ assert "ANTHROPIC_API_KEY" not in merged["env"]
+ assert "apiKeyHelper" not in merged
+ assert "model" not in merged
+ assert not any(key in merged["env"] for key in ANTHROPIC_DEFAULT_MODEL_ENV_KEYS)
+
+ def test_a_helper_lands_top_level_and_the_static_slots_are_cleared(self):
+ settings = {"env": {"ANTHROPIC_AUTH_TOKEN": "sk-old", "ANTHROPIC_API_KEY": "leaked"}}
+ merged = merge_claude_settings(settings, "http://127.0.0.1:4000", ApiKeyHelper("lite auth print-token"))
+ assert merged["apiKeyHelper"] == "lite auth print-token"
+ assert "ANTHROPIC_AUTH_TOKEN" not in merged["env"] and "ANTHROPIC_API_KEY" not in merged["env"]
+
+ def test_keeps_existing_switch_values_and_unrelated_keys_without_mutating_the_input(self):
+ settings = {"theme": "dark", "env": {"SOME_OTHER_VAR": "value", "ENABLE_TOOL_SEARCH": "false"}}
+ merged = merge_claude_settings(settings, "http://127.0.0.1:4000", StaticToken("token-abc"))
+ assert merged["theme"] == "dark"
+ assert merged["env"]["SOME_OTHER_VAR"] == "value"
+ assert merged["env"]["ENABLE_TOOL_SEARCH"] == "false"
+ assert settings == {"theme": "dark", "env": {"SOME_OTHER_VAR": "value", "ENABLE_TOOL_SEARCH": "false"}}
+
+ def test_a_default_model_sets_only_the_row_claude_code_starts_on(self):
+ merged = merge_claude_settings(
+ {}, "http://127.0.0.1:4000", StaticToken("token-abc"), default_model="claude-auto"
+ )
+ assert merged["model"] == "claude-auto"
+ assert not any(key in merged["env"] for key in ANTHROPIC_DEFAULT_MODEL_ENV_KEYS)
+
+ def test_a_tier_model_forces_every_claude_code_tier_as_autoroute_needs(self):
+ # Router's auto-router registry is keyed by the literal requested model string with no
+ # wildcard resolution, so `lite autoroute up` overrides the env var each tier reads.
+ settings = {"env": {"ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-opus-4-8"}}
+ merged = merge_claude_settings(
+ settings, "http://127.0.0.1:4000", StaticToken("token-abc"), tier_model="autorouter"
+ )
+ assert {merged["env"][key] for key in ANTHROPIC_DEFAULT_MODEL_ENV_KEYS} == {"autorouter"}
+ assert "model" not in merged
+
+ def test_touches_exactly_the_declared_owned_keys(self):
+ # The receipt and unconfigure restore exactly OWNED_*_KEYS, so a key the merge writes outside
+ # that table would be written by configure and never undone.
+ settings = {
+ "theme": "dark",
+ "permissions": {"allow": ["Bash"]},
+ "env": {"KEEP_ME": "1", "ANTHROPIC_API_KEY": "old", "ENABLE_TOOL_SEARCH": "false"},
+ "apiKeyHelper": "old-helper",
+ "model": "old-model",
+ }
+ for credential in (StaticToken("token-abc"), ApiKeyHelper("helper")):
+ merged = merge_claude_settings(settings, "http://127.0.0.1:4000", credential, default_model="claude-auto")
+ changed_top_level = {key for key in set(settings) | set(merged) if settings.get(key) != merged.get(key)}
+ assert changed_top_level - {"env"} <= set(OWNED_TOP_LEVEL_KEYS)
+ changed_env = {
+ key
+ for key in set(settings["env"]) | set(merged["env"])
+ if settings["env"].get(key) != merged["env"].get(key)
+ }
+ assert changed_env <= set(OWNED_ENV_KEYS)
+ assert merged["permissions"] == {"allow": ["Bash"]}
+ assert merged["env"]["KEEP_ME"] == "1"
+
+
+ PROXY = "http://127.0.0.1:4000"
+ ANTHROPIC = "https://api.anthropic.com"
+ HELPER = ApiKeyHelper("lite auth print-token")
+ ORIGINAL = {
+ "theme": "dark",
+ "permissions": {"allow": ["Bash"]},
+ "env": {"KEEP_ME": "1", "ANTHROPIC_API_KEY": "sk-ant-mine", "ANTHROPIC_BASE_URL": ANTHROPIC},
+ "apiKeyHelper": "/usr/local/bin/lite auth print-token",
+ "model": "claude-opus-5",
+ }
+
+
+ def _set(path, value):
+ """A user edit: set (or with `_ABSENT`, remove) the key at a dotted path in the settings file."""
+
+ def edit(settings):
+ section, _, key = path.rpartition(".")
+ container = settings.setdefault(section, {}) if section else settings
+ if value is _ABSENT:
+ container.pop(key, None)
+ else:
+ container[key] = value
+ return settings
+
+ return edit
+
+
+ _ABSENT = object()
+
+
+ class _Rig:
+ """One settings file plus receipt under tmp_path, driven through the public functions only."""
+
+ def __init__(self, tmp_path, initial):
+ self.settings = tmp_path / "claude" / "settings.json"
+ self.state = tmp_path / "state" / "claude_configure_state.json"
+ if initial is not None:
+ self.settings.parent.mkdir(parents=True)
+ self.settings.write_text(json.dumps(initial))
+
+ def read(self):
+ return json.loads(self.settings.read_text()) if self.settings.exists() else None
+
+ def configure(self, credential=StaticToken("sk-virtual-key"), model=StartOn("claude-auto"), **kwargs):
+ configure_claude_settings(PROXY, credential, model, self.settings, self.state, (), **kwargs)
+
+ def edit(self, *edits):
+ settings = self.read()
+ for apply in edits:
+ settings = apply(settings)
+ self.settings.write_text(json.dumps(settings))
+
+ def unconfigure(self):
+ return unconfigure_claude_settings(self.settings, self.state, ())
+
+
+ # Each row: initial file, steps (configure kwargs dicts or edit callables) between the first configure
+ # and unconfigure, the expected file afterwards, and the expected outcome fields. Sequences that used
+ # to be one test each; the receipt's rules are what make them all come out right.
+ UNDO_SCENARIOS = {
+ "plain round trip": (ORIGINAL, [], ORIGINAL, {"kept": ()}),
+ "no file before": (None, [], None, {"file_removed": True}),
+ "no env before": ({"theme": "dark"}, [], {"theme": "dark"}, {}),
+ "null env before": ({"theme": "dark", "env": None}, [], {"theme": "dark", "env": None}, {}),
+ "empty env before": ({"theme": "dark", "env": {}}, [], {"theme": "dark", "env": {}}, {}),
+ "user edits stay and are named": (
+ ORIGINAL,
+ [_set("env.ENABLE_TOOL_SEARCH", "false"), _set("model", "claude-sonnet-4-6")],
+ {**ORIGINAL, "env": {**ORIGINAL["env"], "ENABLE_TOOL_SEARCH": "false"}, "model": "claude-sonnet-4-6"},
+ {"kept": {"env.ENABLE_TOOL_SEARCH", "model"}, "withheld": ()},
+ ),
+ "user filled an env configure created": (None, [_set("env.MY_VAR", "mine")], {"env": {"MY_VAR": "mine"}}, {}),
+ "user deleted the file": (None, [lambda s: None], None, {"file_removed": True, "restored": (), "kept": ()}),
+ "user removed our key: neither restored nor kept": (
+ ORIGINAL,
+ [_set("env.ANTHROPIC_AUTH_TOKEN", _ABSENT)],
+ ORIGINAL,
+ {"not_restored": {"env.ANTHROPIC_AUTH_TOKEN"}, "kept": ()},
+ ),
+ "restored names only what changed": (
+ {"model": "claude-opus-5"},
+ [],
+ {"model": "claude-opus-5"},
+ {
+ "restored": {
+ "env.ANTHROPIC_BASE_URL",
+ "env.ENABLE_TOOL_SEARCH",
+ "env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY",
+ "apiKeyHelper",
+ },
+ "kept": (),
+ },
+ {"credential": HELPER, "model": KeepModel()},
+ ),
+ "repeat across credential kinds keeps the first snapshot": (
+ ORIGINAL,
+ [
+ {"credential": HELPER, "model": UnpinModel()},
+ {"credential": StaticToken("sk-rotated"), "model": StartOn("claude-sonnet-4-6")},
+ ],
+ ORIGINAL,
+ {},
+ ),
+ "repeat without a model lets go of our pin, user had none": ({}, [{"model": UnpinModel()}], {}, {}),
+ "repeat without a model lets go of our pin, user had one": (
+ {"model": "claude-opus-5"},
+ [{"model": UnpinModel()}],
+ {"model": "claude-opus-5"},
+ {},
+ ),
+ "re-login keeps our pin": (None, [{"credential": HELPER, "model": KeepModel()}], None, {"file_removed": True}),
+ "edit between configures survives an unpin repeat": (
+ ORIGINAL,
+ [
+ _set("model", "my-favourite"),
+ _set("env.ENABLE_TOOL_SEARCH", "false"),
+ {"credential": HELPER, "model": UnpinModel()},
+ ],
+ {**ORIGINAL, "env": {**ORIGINAL["env"], "ENABLE_TOOL_SEARCH": "false"}, "model": "my-favourite"},
+ {"kept": {"env.ENABLE_TOOL_SEARCH", "model"}},
+ ),
+ "edit between configures survives a re-login": (
+ ORIGINAL,
+ [
+ _set("model", "my-favourite"),
+ _set("env.ENABLE_TOOL_SEARCH", "false"),
+ {"credential": HELPER, "model": KeepModel()},
+ ],
+ {**ORIGINAL, "env": {**ORIGINAL["env"], "ENABLE_TOOL_SEARCH": "false"}, "model": "my-favourite"},
+ {"kept": {"env.ENABLE_TOOL_SEARCH", "model"}},
+ ),
+ "edit between configures: a same-model repeat displaces it, so it is what comes back": (
+ ORIGINAL,
+ [_set("model", "my-favourite"), _set("env.ENABLE_TOOL_SEARCH", "false"), {"credential": HELPER}],
+ {**ORIGINAL, "env": {**ORIGINAL["env"], "ENABLE_TOOL_SEARCH": "false"}, "model": "my-favourite"},
+ {"kept": {"env.ENABLE_TOOL_SEARCH"}, "restored_includes": {"model"}},
+ ),
+ "base URL changed since: credentials withheld, receipt kept": (
+ ORIGINAL,
+ [_set("env.ANTHROPIC_BASE_URL", "http://other-proxy:4000")],
+ {**ORIGINAL, "env": {"KEEP_ME": "1", "ANTHROPIC_BASE_URL": "http://other-proxy:4000"}, "apiKeyHelper": _ABSENT},
+ {
+ "withheld": {("env.ANTHROPIC_API_KEY", ANTHROPIC), ("apiKeyHelper", ANTHROPIC)},
+ "kept": {"env.ANTHROPIC_BASE_URL"},
+ "receipt_kept": True,
+ },
+ ),
+ "base URL changed and back: judged against the URL the restored file holds": (
+ ORIGINAL,
+ [_set("env.ANTHROPIC_BASE_URL", ANTHROPIC)],
+ ORIGINAL,
+ {"withheld": ()},
+ ),
+ "credential captured beside no URL goes back only beside no URL": (
+ {"env": {"ANTHROPIC_API_KEY": "sk-default-endpoint"}},
+ [_set("env.ANTHROPIC_BASE_URL", "http://other-proxy:4000")],
+ {"env": {"ANTHROPIC_BASE_URL": "http://other-proxy:4000"}},
+ {
+ "withheld": {("env.ANTHROPIC_API_KEY", "no ANTHROPIC_BASE_URL (Anthropic's default endpoint)")},
+ "receipt_kept": True,
+ },
+ ),
+ "restored document empty while a credential is withheld: file goes, receipt stays": (
+ None,
+ [
+ _set("env.ANTHROPIC_API_KEY", "sk-user"),
+ {"credential": HELPER, "model": KeepModel()},
+ _set("env.ANTHROPIC_BASE_URL", _ABSENT),
+ ],
+ None,
+ {"withheld": {("env.ANTHROPIC_API_KEY", PROXY)}, "file_removed": True, "receipt_kept": True},
+ {"credential": HELPER, "model": KeepModel()},
+ ),
+ "a credential the user changed is kept, never also withheld": (
+ ORIGINAL,
+ [_set("env.ANTHROPIC_BASE_URL", "http://other-proxy:4000"), _set("apiKeyHelper", "/opt/mine/helper")],
+ {
+ **ORIGINAL,
+ "env": {"KEEP_ME": "1", "ANTHROPIC_BASE_URL": "http://other-proxy:4000"},
+ "apiKeyHelper": "/opt/mine/helper",
+ },
+ {
+ "withheld": {("env.ANTHROPIC_API_KEY", ANTHROPIC)},
+ "kept": {"env.ANTHROPIC_BASE_URL", "apiKeyHelper"},
+ "receipt_kept": True,
+ },
+ ),
+ }
+
+
+ def _expected_file(expected):
+ if expected is None:
+ return None
+ return {k: v for k, v in expected.items() if v is not _ABSENT}
+
+
+ class TestConfigureAndUnconfigure:
+ """`configure_claude_settings` records how to undo itself; `unconfigure_claude_settings` undoes only that."""
+
+ @pytest.mark.parametrize("scenario", UNDO_SCENARIOS.values(), ids=UNDO_SCENARIOS.keys())
+ def test_undo_matrix(self, tmp_path, scenario):
+ initial, steps, expected, outcome_expectations, *first = scenario
+ rig = _Rig(tmp_path, initial)
+ rig.configure(**(first[0] if first else {}))
+ for step in steps:
+ if isinstance(step, dict):
+ rig.configure(**step)
+ elif rig.settings.exists() and step(json.loads(rig.settings.read_text())) is None:
+ rig.settings.unlink()
+ else:
+ rig.edit(step)
+
+ outcome = rig.unconfigure()
+
+ assert rig.read() == _expected_file(expected)
+ assert rig.state.exists() == outcome_expectations.get("receipt_kept", False)
+ for field, want in outcome_expectations.items():
+ if field == "withheld":
+ assert {(item.key, item.endpoint) for item in outcome.withheld} == set(want)
+ elif field == "not_restored":
+ assert not set(want) & set(outcome.restored) and not set(want) & set(outcome.kept)
+ elif field == "restored_includes":
+ assert set(want) <= set(outcome.restored)
+ elif field in ("restored", "kept"):
+ assert set(getattr(outcome, field)) == set(want)
+ elif field != "receipt_kept":
+ assert getattr(outcome, field) == want
+ assert not {item.key for item in outcome.withheld} & set(outcome.kept)
+
+ def test_configure_writes_owner_only_and_the_receipt_never_holds_the_key(self, tmp_path):
+ rig = _Rig(tmp_path, ORIGINAL)
+ rig.configure(credential=StaticToken("sk-virtual-key-never-on-disk-twice"))
+ configured = rig.read()
+ assert configured["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-virtual-key-never-on-disk-twice"
+ assert configured["env"]["ANTHROPIC_BASE_URL"] == PROXY and configured["model"] == "claude-auto"
+ assert "ANTHROPIC_API_KEY" not in configured["env"] and "apiKeyHelper" not in configured
+ assert stat.S_IMODE(rig.settings.stat().st_mode) == 0o600 == stat.S_IMODE(rig.state.stat().st_mode)
+ assert "sk-virtual-key-never-on-disk-twice" not in rig.state.read_text()
+
+ def test_withheld_credentials_come_back_once_the_url_points_at_their_server_again(self, tmp_path):
+ # The kept receipt owns only the withheld slots: the second unconfigure restores exactly those.
+ rig = _Rig(tmp_path, ORIGINAL)
+ rig.configure()
+ rig.edit(_set("env.ANTHROPIC_BASE_URL", "http://other-proxy:4000"))
+ rig.unconfigure()
+ rig.edit(_set("env.ANTHROPIC_BASE_URL", ANTHROPIC), _set("theme", "light"))
+ outcome = rig.unconfigure()
+ assert rig.read() == {**ORIGINAL, "theme": "light"}
+ assert set(outcome.restored) == {"env.ANTHROPIC_API_KEY", "apiKeyHelper"}
+ assert outcome.kept == () and outcome.withheld == () and not rig.state.exists()
+
+ @pytest.mark.parametrize(
+ ("path", "value", "repeat_credential"),
+ [
+ ("env.ANTHROPIC_API_KEY", "sk-user-added-later", HELPER),
+ ("env.ANTHROPIC_AUTH_TOKEN", "sk-users-own-token", HELPER),
+ ("apiKeyHelper", "/opt/mine/helper", StaticToken("sk-rotated")),
+ ],
+ ids=["user-adds-api-key", "user-replaces-our-token", "user-sets-own-helper"],
+ )
+ def test_a_credential_the_user_set_between_two_configures_is_what_comes_back(
+ self, tmp_path, path, value, repeat_credential
+ ):
+ # The repeat's merge clears the slot, so the displaced value is snapshotted and is what returns;
+ # it was set while the file pointed at the proxy, so it returns once the file points there again.
+ rig = _Rig(tmp_path, {"theme": "dark"})
+ rig.configure(credential=HELPER, model=KeepModel())
+ rig.edit(_set(path, value))
+ rig.configure(credential=repeat_credential, model=KeepModel())
+ assert not _lookup(rig.read(), path)
+
+ outcome = rig.unconfigure()
+ assert [(item.key, item.endpoint) for item in outcome.withheld] == [(path, PROXY)]
+ assert rig.read() == {"theme": "dark"} and rig.state.exists()
+ rig.settings.write_text(json.dumps({"theme": "dark", "env": {"ANTHROPIC_BASE_URL": PROXY}}))
+ outcome = rig.unconfigure()
+ assert _lookup(rig.read(), path) == value
+ assert outcome.restored == (path,) and outcome.withheld == () and not rig.state.exists()
+
+ def test_a_receipt_commit_that_fails_leaves_no_staged_token_behind(self, tmp_path):
+ rig = _Rig(tmp_path, {})
+
+ def commit_receipt_fails(staged, path):
+ if path == str(rig.state):
+ os.unlink(staged)
+ raise OSError("receipt rename failed")
+ commit_staged_json(staged, path)
+
+ with pytest.raises(ClaudeSettingsError, match=r"Could not write .*receipt rename failed"):
+ rig.configure(credential=StaticToken("sk-never-left-in-a-temp-file"), commit=commit_receipt_fails)
+ assert not list(rig.settings.parent.glob(".tmp-*")) and not list(rig.state.parent.glob(".tmp-*"))
+ assert rig.read() == {} and not rig.state.exists()
+
+ @pytest.mark.parametrize("configured_before", [False, True], ids=["first-configure", "repeat-configure"])
+ def test_a_settings_commit_that_fails_after_the_receipt_landed_puts_the_receipt_back(
+ self, tmp_path, configured_before
+ ):
+ # The two renames are not atomic: a settings rename that fails after the receipt landed must
+ # not leave a receipt describing settings that were never written.
+ rig = _Rig(tmp_path, ORIGINAL)
+ if configured_before:
+ rig.configure()
+ receipt_before = rig.state.read_text() if configured_before else None
+ settings_before = rig.settings.read_text()
+
+ def commit_settings_fails(staged, path):
+ if path == str(rig.settings):
+ os.unlink(staged)
+ raise OSError("rename failed")
+ commit_staged_json(staged, path)
+
+ with pytest.raises(ClaudeSettingsError, match="rename failed"):
+ rig.configure(credential=StaticToken("sk-rotated"), commit=commit_settings_fails)
+ assert rig.settings.read_text() == settings_before
+ assert (rig.state.read_text() if rig.state.exists() else None) == receipt_before
+ if configured_before:
+ rig.unconfigure()
+ assert rig.read() == ORIGINAL
+
+ def test_a_failed_repeat_configure_leaves_the_earlier_undo_intact(self, tmp_path):
+ rig = _Rig(tmp_path, ORIGINAL)
+ rig.configure()
+ receipt_before = rig.state.read_text()
+ rig.settings.parent.chmod(0o500)
+ try:
+ with pytest.raises(ClaudeSettingsError, match="Could not write"):
+ rig.configure(credential=StaticToken("sk-rotated"))
+ finally:
+ rig.settings.parent.chmod(0o700)
+ assert rig.state.read_text() == receipt_before and not list(rig.state.parent.glob(".tmp-*"))
+ assert rig.read()["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-virtual-key"
+ rig.unconfigure()
+ assert rig.read() == ORIGINAL
+
+ def test_unconfigure_reports_a_receipt_it_cannot_remove_as_a_settings_error(self, tmp_path):
+ rig = _Rig(tmp_path, ORIGINAL)
+ rig.configure()
+ rig.state.parent.chmod(0o500)
+ try:
+ with pytest.raises(ClaudeSettingsError, match="Could not remove"):
+ rig.unconfigure()
+ finally:
+ rig.state.parent.chmod(0o700)
+
+ def test_configure_writes_through_a_symlinked_settings_file(self, tmp_path):
+ target = tmp_path / "dotfiles" / "settings.json"
+ target.parent.mkdir()
+ target.write_text(json.dumps({"theme": "dark"}))
+ link = tmp_path / "settings.json"
+ link.symlink_to(target)
+ configure_claude_settings(PROXY, StaticToken("sk-virtual-key"), UnpinModel(), link, tmp_path / "state.json", ())
+ assert link.is_symlink()
+ assert json.loads(target.read_text())["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-virtual-key"
+
+ @pytest.mark.parametrize("operation", ["configure", "unconfigure"])
+ def test_refuses_while_a_temporary_owner_holds_a_backup(self, paths, tmp_path, operation):
+ settings_path, backup_path = paths
+ backup_path.write_text("{}")
+ owners = _owners(backup_path)
+ state = tmp_path / "state.json"
+ attempt = (
+ (lambda: configure_claude_settings(PROXY, StaticToken("k"), UnpinModel(), settings_path, state, owners))
+ if operation == "configure"
+ else (lambda: unconfigure_claude_settings(settings_path, state, owners))
+ )
+ with pytest.raises(ClaudeSettingsError, match="lite down"):
+ attempt()
+ assert not settings_path.exists()
+
+ def test_unconfigure_without_a_receipt_is_an_error_not_a_silent_no_op(self, tmp_path):
+ with pytest.raises(ClaudeSettingsError, match="nothing to undo"):
+ _Rig(tmp_path, None).unconfigure()
+
+
+ def _lookup(settings, path):
+ section, _, key = path.rpartition(".")
+ return (settings.get(section) or {}).get(key) if section else settings.get(key)
diff --cc tests/test_litellm/proxy/client/cli/test_configure_commands.py
index 00000000000,1631ba7f49e..a1808383982
mode 000000,100644..100644
--- a/tests/test_litellm/proxy/client/cli/test_configure_commands.py
+++ b/tests/test_litellm/proxy/client/cli/test_configure_commands.py
@@@ -1,0 -1,331 +1,360 @@@
+ import json
+ import os
+ import stat
+
+ import click
+ import pytest
+ import requests
+ import responses
+ from click.testing import CliRunner
+
+ from litellm.proxy.client.cli import cli
++from litellm.proxy.client.cli.commands import claude_settings as claude_settings_module
+ from litellm.proxy.client.cli.commands import configure as configure_module
+ from litellm.proxy.client.cli.commands.claude_settings import SettingsFileOwner
+ from litellm.proxy.client.cli.commands.configure import configure_claude, configure_group, interactive_configure
+
+ PROXY = "http://proxy.test:4000"
+ VALID_KEY = "sk-virtual-key"
+ LISTED_MODELS = ("claude-auto", "gpt-5.6-luna")
+
+
+ def _mock_models():
+ responses.get(
+ f"{PROXY}/v1/models",
+ json={"data": [{"id": model, "object": "model"} for model in LISTED_MODELS]},
+ match=[responses.matchers.header_matcher({"Authorization": f"Bearer {VALID_KEY}"})],
+ )
+ responses.get(f"{PROXY}/v1/models", status=401)
+
+
+ @pytest.fixture
+ def paths(monkeypatch, tmp_path):
++ """The default settings file, reached the way Claude Code reaches it: CLAUDE_CONFIG_DIR names its directory."""
+ settings_path = tmp_path / "claude" / "settings.json"
+ state_path = tmp_path / "litellm" / "claude_configure_state.json"
- monkeypatch.setattr(configure_module, "CLAUDE_SETTINGS_PATH", settings_path)
- monkeypatch.setattr(configure_module, "CONFIGURE_STATE_PATH", state_path)
++ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(settings_path.parent))
++ monkeypatch.setattr(claude_settings_module, "CLAUDE_SETTINGS_PATH", settings_path)
++ monkeypatch.setattr(claude_settings_module, "CONFIGURE_STATE_PATH", state_path)
+ return settings_path, state_path
+
+
+ @pytest.fixture
+ def lite_on_path(monkeypatch, tmp_path):
+ """A real `lite` executable on PATH, so the apiKeyHelper command resolves without patching."""
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ lite = bin_dir / "lite"
+ lite.write_text("#!/bin/sh\nexit 0\n")
+ lite.chmod(lite.stat().st_mode | stat.S_IXUSR)
+ monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}")
+ return str(lite)
+
+
+ @pytest.fixture
+ def runner():
+ return CliRunner()
+
+
+ @pytest.fixture
+ def lite_up_backup(monkeypatch, tmp_path):
+ """A `lite up` session holding its backup, the local precondition every settings write refuses on."""
+ backup = tmp_path / "claude_settings_backup.json"
+ backup.write_text("{}")
- monkeypatch.setattr(configure_module, "SETTINGS_FILE_OWNERS", (SettingsFileOwner(backup, "lite up", "lite down"),))
++ monkeypatch.setattr(
++ claude_settings_module, "SETTINGS_FILE_OWNERS", (SettingsFileOwner(backup, "lite up", "lite down"),)
++ )
+ return backup
+
+
+ def _configure(runner, *args):
+ return runner.invoke(cli, ["--base-url", PROXY, "configure", "claude", *args])
+
+
+ class TestConfigureClaudeWithAVirtualKey:
+ @responses.activate
+ def test_writes_settings_and_reports_without_echoing_the_key(self, runner, paths):
+ _mock_models()
+ settings_path, state_path = paths
+ result = _configure(runner, "--api-key", VALID_KEY, "--model", "claude-auto")
+ assert result.exit_code == 0, result.output
+ written = json.loads(settings_path.read_text())
+ assert written["env"]["ANTHROPIC_BASE_URL"] == PROXY
+ assert written["env"]["ANTHROPIC_AUTH_TOKEN"] == VALID_KEY
+ assert written["env"]["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"
+ assert written["model"] == "claude-auto"
+ assert "ANTHROPIC_DEFAULT_SONNET_MODEL" not in written["env"]
+ assert state_path.exists()
+ assert VALID_KEY not in result.output
+ assert "Starting model: claude-auto" in result.output
+ assert "1 of the proxy's 2 models" in result.output
+ assert "lite unconfigure claude" in result.output
+ assert len(responses.calls) == 1
+
+ @responses.activate
+ def test_takes_the_key_from_the_global_option_and_keeps_claude_codes_default(self, runner, paths):
+ _mock_models()
+ settings_path, _ = paths
+ result = runner.invoke(cli, ["--base-url", PROXY, "--api-key", VALID_KEY, "configure", "claude"])
+ assert result.exit_code == 0, result.output
+ written = json.loads(settings_path.read_text())
+ assert written["env"]["ANTHROPIC_AUTH_TOKEN"] == VALID_KEY
+ assert "model" not in written
+ assert "Starting model: not pinned" in result.output
+
+ @responses.activate
+ def test_refuses_a_model_the_proxy_does_not_list(self, runner, paths):
+ _mock_models()
+ settings_path, _ = paths
+ result = _configure(runner, "--api-key", VALID_KEY, "--model", "claude-nope")
+ assert result.exit_code != 0
+ assert "'claude-nope' is not served" in result.output
+ assert "claude-auto, gpt-5.6-luna" in result.output
+ assert not settings_path.exists()
+
+ @responses.activate
+ def test_refuses_a_key_the_proxy_rejects(self, runner, paths):
+ _mock_models()
+ settings_path, _ = paths
+ result = _configure(runner, "--api-key", "sk-wrong")
+ assert result.exit_code != 0
+ assert "rejected your key (HTTP 401)" in result.output
+ assert not settings_path.exists()
+
+ @responses.activate
+ @pytest.mark.parametrize(
+ ("mock", "expected", "unexpected"),
+ [
+ (
+ lambda: responses.get(f"{PROXY}/v1/models", body=requests.ConnectionError("refused")),
+ "Is the proxy at",
+ "answered",
+ ),
+ (
+ lambda: responses.get(f"{PROXY}/v1/models", status=500),
+ "The proxy at http://proxy.test:4000 answered",
+ "Is the proxy at",
+ ),
+ (
+ lambda: responses.get(f"{PROXY}/v1/models", body="<html>not json</html>"),
+ "answered, so check that it is a LiteLLM proxy",
+ "Is the proxy at",
+ ),
+ (
+ lambda: responses.get(f"{PROXY}/v1/models", json={"data": []}),
+ "Claude Code would have nothing to run",
+ "Is the proxy at",
+ ),
+ ],
+ ids=["unreachable", "http-500", "non-json-body", "empty-list"],
+ )
+ def test_the_listing_hint_matches_how_the_listing_failed(self, runner, paths, mock, expected, unexpected):
+ # Only a proxy that never answered gets the "is it running" question; a 500, a non-JSON body or an
+ # empty list prove it is up, and the hint says so instead.
+ mock()
+ settings_path, _ = paths
+ result = _configure(runner, "--api-key", VALID_KEY)
+ assert result.exit_code != 0
+ assert expected in result.output and unexpected not in result.output
+ assert not settings_path.exists()
+
+ @responses.activate
+ @pytest.mark.parametrize("entry", ["virtual-key", "login", "interactive"])
+ def test_refuses_while_lite_up_holds_a_backup_before_any_login_or_request(
+ self, runner, paths, monkeypatch, lite_up_backup, entry
+ ):
+ _mock_models()
+
+ def login_must_not_run(ctx):
+ raise AssertionError("the local precondition must be checked before a login is attempted")
+
+ monkeypatch.setattr(configure_module, "ensure_fresh_login", login_must_not_run)
+ if entry == "interactive":
+ ctx = click.Context(configure_group, obj={"base_url": PROXY, "api_key": None})
+ with pytest.raises(click.ClickException, match="lite down"):
+ interactive_configure(ctx, pick_targets=lambda: ("claude",), pick_model=lambda listed: None)
+ else:
+ args = ["--api-key", VALID_KEY] if entry == "virtual-key" else []
+ result = runner.invoke(configure_claude, args, obj={"base_url": PROXY, "api_key": None})
+ assert result.exit_code != 0 and "lite down" in result.output
+ assert len(responses.calls) == 0
+ assert not paths[0].exists()
+
+ @responses.activate
+ def test_says_so_when_the_key_is_written_through_a_symlink(self, runner, paths, tmp_path):
+ _mock_models()
+ settings_path, _ = paths
+ target = tmp_path / "dotfiles" / "settings.json"
+ target.parent.mkdir()
+ target.write_text("{}")
+ settings_path.parent.mkdir(parents=True)
+ settings_path.symlink_to(target)
+ result = _configure(runner, "--api-key", VALID_KEY)
+ assert result.exit_code == 0, result.output
+ assert "keep it out of version control" in result.output
+ assert json.loads(target.read_text())["env"]["ANTHROPIC_AUTH_TOKEN"] == VALID_KEY
+
+
+ class TestConfigureClaudeWithTheLogin:
+ def _stored_login(self, monkeypatch):
+ monkeypatch.setattr(configure_module, "ensure_fresh_login", lambda ctx: None)
+ monkeypatch.setattr(configure_module, "get_stored_api_key", lambda expected_base_url, vault: VALID_KEY)
+
+ @responses.activate
+ def test_uses_the_login_through_the_helper_and_writes_no_secret(self, runner, paths, monkeypatch, lite_on_path):
+ _mock_models()
+ self._stored_login(monkeypatch)
+ settings_path, _ = paths
+ result = runner.invoke(
+ configure_claude,
+ ["--model", "claude-auto"],
+ obj={"base_url": PROXY, "api_key": VALID_KEY, "api_key_from_token_file": True},
+ )
+ assert result.exit_code == 0, result.output
+ written = json.loads(settings_path.read_text())
+ assert written["apiKeyHelper"] == f"{lite_on_path} --base-url {PROXY} auth print-token"
+ assert "ANTHROPIC_AUTH_TOKEN" not in written["env"]
+ assert written["model"] == "claude-auto"
+ assert VALID_KEY not in settings_path.read_text()
+ assert "read through apiKeyHelper" in result.output
+
+ @responses.activate
+ def test_an_explicit_key_still_wins_over_a_stored_login(self, runner, paths, monkeypatch, lite_on_path):
+ _mock_models()
+ self._stored_login(monkeypatch)
+ settings_path, _ = paths
+ result = runner.invoke(
+ configure_claude,
+ ["--api-key", VALID_KEY],
+ obj={"base_url": PROXY, "api_key": "sk-login-jwt", "api_key_from_token_file": True},
+ )
+ assert result.exit_code == 0, result.output
+ written = json.loads(settings_path.read_text())
+ assert written["env"]["ANTHROPIC_AUTH_TOKEN"] == VALID_KEY and "apiKeyHelper" not in written
+
+
+ class TestInteractiveConfigure:
+ @responses.activate
+ def test_asks_for_targets_and_a_starting_model_then_configures(self, paths):
+ _mock_models()
+ settings_path, _ = paths
+ asked = {}
+
+ def pick_model(listed):
+ asked["listed"] = tuple(listed)
+ return "claude-auto"
+
+ ctx = click.Context(
+ configure_group, obj={"base_url": PROXY, "api_key": VALID_KEY, "api_key_from_token_file": False}
+ )
+ interactive_configure(ctx, pick_targets=lambda: ("claude",), pick_model=pick_model)
+ assert asked["listed"] == LISTED_MODELS
+ assert json.loads(settings_path.read_text())["model"] == "claude-auto"
+
+ def test_does_nothing_when_claude_code_is_not_picked(self, paths):
+ settings_path, _ = paths
+ ctx = click.Context(
+ configure_group, obj={"base_url": PROXY, "api_key": VALID_KEY, "api_key_from_token_file": False}
+ )
+ interactive_configure(ctx, pick_targets=lambda: (), pick_model=lambda listed: None)
+ assert not settings_path.exists()
+
+ def test_bare_configure_without_a_terminal_names_the_non_interactive_command(self, runner, paths):
+ result = runner.invoke(cli, ["--base-url", PROXY, "configure"])
+ assert result.exit_code != 0
+ assert "lite configure claude --api-key" in result.output
+
+
+ class TestUnconfigureClaude:
+ @responses.activate
+ def test_restores_the_original_file_and_removes_the_receipt(self, runner, paths):
+ _mock_models()
+ settings_path, state_path = paths
+ settings_path.parent.mkdir(parents=True)
+ original = {"theme": "dark", "model": "claude-opus-5"}
+ settings_path.write_text(json.dumps(original))
+ assert _configure(runner, "--api-key", VALID_KEY, "--model", "claude-auto").exit_code == 0
+
+ result = runner.invoke(cli, ["unconfigure", "claude"])
+ assert result.exit_code == 0, result.output
+ assert json.loads(settings_path.read_text()) == original
+ assert not state_path.exists()
+ assert "Restored in" in result.output and "model" in result.output
+ assert "ANTHROPIC_API_KEY" not in result.output, "a key that never existed was not restored"
+
+ @responses.activate
+ def test_a_file_only_configure_created_is_reported_removed_not_restored(self, runner, paths):
+ _mock_models()
+ settings_path, _ = paths
+ assert _configure(runner, "--api-key", VALID_KEY).exit_code == 0
+ result = runner.invoke(cli, ["unconfigure", "claude"])
+ assert result.exit_code == 0, result.output
+ assert not settings_path.exists()
+ assert "No settings file remains" in result.output and "Restored" not in result.output
+
+ @responses.activate
+ def test_says_when_nothing_was_still_ours_and_names_what_it_kept(self, runner, paths):
+ _mock_models()
+ settings_path, _ = paths
+ settings_path.parent.mkdir(parents=True)
+ settings_path.write_text(json.dumps({"theme": "dark"}))
+ assert _configure(runner, "--api-key", VALID_KEY, "--model", "claude-auto").exit_code == 0
+ edited = json.loads(settings_path.read_text())
+ edited["env"] = {key: f"{value}-edited" for key, value in edited["env"].items()}
+ edited["model"] = "mine"
+ settings_path.write_text(json.dumps(edited))
+ result = runner.invoke(cli, ["unconfigure", "claude"])
+ assert result.exit_code == 0, result.output
+ assert "Nothing in" in result.output and "was still ours to restore" in result.output
+ assert "Left as you changed them since:" in result.output and "model" in result.output
+
+ @responses.activate
+ def test_names_the_server_a_withheld_credential_was_captured_with_and_keeps_the_receipt(self, runner, paths):
+ _mock_models()
+ settings_path, state_path = paths
+ settings_path.parent.mkdir(parents=True)
+ settings_path.write_text(
+ json.dumps({"env": {"ANTHROPIC_BASE_URL": "https://api.anthropic.com", "ANTHROPIC_API_KEY": "sk-ant"}})
+ )
+ assert _configure(runner, "--api-key", VALID_KEY).exit_code == 0
+ edited = json.loads(settings_path.read_text())
+ edited["env"]["ANTHROPIC_BASE_URL"] = "http://other-proxy:4000"
+ settings_path.write_text(json.dumps(edited))
+ result = runner.invoke(cli, ["unconfigure", "claude"])
+ assert result.exit_code == 0, result.output
+ assert "env.ANTHROPIC_API_KEY (captured with https://api.anthropic.com)" in result.output
+ assert str(state_path) in result.output and state_path.exists()
+ assert "sk-ant" not in result.output
+
+ def test_refuses_while_lite_up_holds_a_backup(self, runner, paths, lite_up_backup):
+ result = runner.invoke(cli, ["unconfigure", "claude"])
+ assert result.exit_code != 0 and "lite down" in result.output
+
++ @responses.activate
++ def test_a_config_dir_is_configured_and_undone_apart_from_the_default_file(
++ self, runner, paths, monkeypatch, tmp_path, lite_up_backup
++ ):
++ _mock_models()
++ default_settings, default_state = paths
++ work_dir = tmp_path / "claude-work"
++ work_dir.mkdir()
++ original = {"theme": "dark"}
++ (work_dir / "settings.json").write_text(json.dumps(original))
++ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(work_dir))
++
++ configured = _configure(runner, "--api-key", VALID_KEY, "--model", "claude-auto")
++ assert configured.exit_code == 0, configured.output
++ assert f"Configured Claude Code: {work_dir / 'settings.json'}" in configured.output
++ assert json.loads((work_dir / "settings.json").read_text())["env"]["ANTHROPIC_AUTH_TOKEN"] == VALID_KEY
++ assert not default_settings.exists() and not default_state.exists()
++
++ undone = runner.invoke(cli, ["unconfigure", "claude"])
++ assert undone.exit_code == 0, undone.output
++ assert json.loads((work_dir / "settings.json").read_text()) == original
++ assert not default_settings.exists() and not default_state.exists()
++ assert runner.invoke(cli, ["unconfigure", "claude"]).exit_code != 0, "the receipt is gone with the undo"
++
+ def test_without_a_receipt_it_fails_loudly(self, runner, paths):
+ result = runner.invoke(cli, ["unconfigure", "claude"])
+ assert result.exit_code != 0
+ assert "nothing to undo" in result.output