Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(claude): separate credential type from endpoint (#1181)
Call White050b41a4cc38
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex bc384d7a1..f69463d14 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -163,11 +163,18 @@ scenarios:backend: codextest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_legacy_codex_thread_rebinds_once_after_api_key_endpoint_switch- id: AUTH-SETUP-904- name: Claude relay key uses bearer auth after switching from OAuth+ name: Claude explicit auth token remains selected after switching from OAuthstatus: coveredkind: historical_regressionlayer: scenariobackend: claude- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_claude_oauth_to_relay_key_reaches_next_turn_with_bearer_auth+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_claude_oauth_to_explicit_auth_token_reaches_next_turn+ - id: AUTH-SETUP-905+ name: Claude API key probe drops a stale inherited auth token after switching from OAuth+ status: covered+ kind: historical_regression+ layer: scenario+ backend: claude+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_claude_oauth_to_api_key_probe_drops_stale_auth_tokennext_priority:- AUTH-SETUP-301diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 966b3aff5..87bc36ea2 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -20,15 +20,21 @@ from config.v2_config import (SlackConfig,V2Config,)+from core.agent_auth_service import AgentAuthServicefrom core.handlers.model_hub.service import ModelHubErrorfrom modules.agents.codex.agent import CodexAgentfrom tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcessfrom tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStepfrom tests.scenario_harness.model_hub_native_oauth import NativeOAuthScenarioHarness-from vibe.api import get_claude_auth, save_claude_auth+from vibe.api import (+ get_claude_auth,+ save_claude_auth,+ test_backend_auth_async as probe_backend_auth_async,+)from vibe.claude_config import (build_claude_subprocess_env,materialize_claude_subprocess_env,+ read_claude_settings_env,)@@ -72,8 +78,14 @@ class _CodexProviderBindingSessions:return "ses-provider"+class _ReloadingV2ConfigController:+ @property+ def config(self):+ return V2Config.load()++class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):- async def test_claude_oauth_to_relay_key_reaches_next_turn_with_bearer_auth(self):+ async def test_claude_oauth_to_explicit_auth_token_reaches_next_turn(self):"""Scenario: AUTH-SETUP-904"""state_dir = tempfile.TemporaryDirectory()self.addCleanup(state_dir.cleanup)@@ -109,11 +121,12 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):def capture_oauth_state(current):current.before_switch = get_claude_auth()- def save_relay_key(current):+ def save_auth_token(current):current.save_result = save_claude_auth({"auth_mode": "api_key","api_key": "relay-secret",+ "credential_type": "auth_token","base_url": "https://relay.example/v1",})@@ -154,12 +167,13 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):await runner.run(ScenarioStep("confirm_oauth_is_active", capture_oauth_state),- ScenarioStep("save_relay_key", save_relay_key),+ ScenarioStep("save_auth_token", save_auth_token),ScenarioStep("launch_next_turn", capture_next_turn_env),)self.assertEqual(harness.before_switch["active_auth_mode"], "oauth")self.assertEqual(harness.save_result["active_auth_mode"], "api_key")+ self.assertEqual(harness.save_result["credential_type"], "auth_token")self.assertEqual(harness.save_result["settings_env_key_var"],"ANTHROPIC_AUTH_TOKEN",@@ -186,7 +200,147 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):)ScenarioExpect.step_history(runner,- ["confirm_oauth_is_active", "save_relay_key", "launch_next_turn"],+ ["confirm_oauth_is_active", "save_auth_token", "launch_next_turn"],+ )++ async def test_claude_oauth_to_api_key_probe_drops_stale_auth_token(self):+ """Scenario: AUTH-SETUP-905"""+ state_dir = tempfile.TemporaryDirectory()+ self.addCleanup(state_dir.cleanup)+ home = Path(state_dir.name)+ claude_home = home / ".claude"+ claude_home.mkdir()+ credentials_path = claude_home / ".credentials.json"+ credentials_path.write_text(+ json.dumps(+ {+ "claudeAiOauth": {+ "accessToken": "oauth-access",+ "refreshToken": "oauth-refresh",+ }+ }+ ),+ encoding="utf-8",+ )+ probe_cli = home / "claude-probe"+ probe_cli.write_text(+ f"""#!{sys.executable}+import os+import sys++expected = (+ sys.argv[1:] == ["-p", "Hi"]+ and os.environ.get("ANTHROPIC_API_KEY") == "relay-api-key"+ and "ANTHROPIC_AUTH_TOKEN" not in os.environ+ and os.environ.get("ANTHROPIC_BASE_URL") == "https://ai.coinsummer.com"+)+if not expected:+ print("unexpected Claude probe environment")+ raise SystemExit(7)+print("relay-probe-ok")+""",+ encoding="utf-8",+ )+ probe_cli.chmod(0o755)++ harness = AuthSetupScenarioHarness()+ runner = ScenarioRunner(harness)+ service = AgentAuthService(_ReloadingV2ConfigController())+ cleanup_calls = []+ restart_calls = []++ def clear_oauth(cleanup_service=None):+ cleanup_calls.append(cleanup_service)+ credentials_path.unlink()+ return {"ok": True}++ def restart_backend(name, *, metadata=None):+ restart_calls.append((name, metadata))+ return {"ok": True, "message": "refreshed"}++ def capture_oauth_state(current):+ current.before_switch = get_claude_auth()++ def save_api_key(current):+ current.save_result = save_claude_auth(+ {+ "auth_mode": "api_key",+ "api_key": "relay-api-key",+ "credential_type": "api_key",+ "base_url": "https://ai.coinsummer.com",+ }+ )++ async def run_connection_probe(current):+ current.test_result = await probe_backend_auth_async("claude")++ with (+ patch.dict(+ os.environ,+ {+ "AVIBE_HOME": str(home / ".avibe"),+ "CLAUDE_CONFIG_DIR": str(claude_home),+ "ANTHROPIC_API_KEY": "stale-parent-api-key",+ "ANTHROPIC_AUTH_TOKEN": "stale-parent-auth-token",+ "ANTHROPIC_BASE_URL": "https://stale-parent.example",+ },+ ),+ patch("vibe.api._get_oauth_service", return_value=service),+ patch(+ "vibe.api._clear_claude_oauth_credentials_after_api_key_save",+ side_effect=clear_oauth,+ ),+ patch("vibe.api.restart_backend", side_effect=restart_backend),+ patch("vibe.api._read_claude_cli_oauth_signed_in", return_value=None),+ ):+ config = V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd=str(home)),+ agents=AgentsConfig(),+ )+ config.agents.claude.auth_mode = "oauth"+ config.agents.claude.auth_mode_set = True+ config.agents.claude.cli_path = str(probe_cli)+ config.save()++ await runner.run(+ ScenarioStep("confirm_oauth_is_active", capture_oauth_state),+ ScenarioStep("save_api_key", save_api_key),+ ScenarioStep("test_connection", run_connection_probe),+ )+ harness.saved_settings_env = read_claude_settings_env()++ self.assertEqual(harness.before_switch["active_auth_mode"], "oauth")+ self.assertEqual(harness.save_result["active_auth_mode"], "api_key")+ self.assertEqual(harness.save_result["credential_type"], "api_key")+ self.assertEqual(+ harness.save_result["settings_env_key_var"],+ "ANTHROPIC_API_KEY",+ )+ self.assertEqual(+ harness.saved_settings_env,+ {+ "ANTHROPIC_API_KEY": "relay-api-key",+ "ANTHROPIC_BASE_URL": "https://ai.coinsummer.com",+ },+ )+ self.assertTrue(harness.test_result["ok"])+ self.assertEqual(harness.test_result["excerpt"], "relay-probe-ok")+ self.assertEqual(cleanup_calls, [service])+ self.assertEqual(+ restart_calls,+ [+ (+ "claude",+ {"reason": "save_claude_auth", "source": "ui_api"},+ )+ ],+ )+ ScenarioExpect.step_history(+ runner,+ ["confirm_oauth_is_active", "save_api_key", "test_connection"],)async def test_legacy_codex_thread_rebinds_once_after_api_key_endpoint_switch(self):diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.pyindex 88e3e666c..7432bcb24 100644--- a/tests/test_settings_disk_fallback.py+++ b/tests/test_settings_disk_fallback.py@@ -408,6 +408,7 @@ def test_claude_settings_json_auth_token_surfaces_in_get_claude_auth(assert masked.endswith("738a")assert "xxxxxxxx" not in masked # plaintext middle must not leakassert state["base_url"] == "https://ai-relay.chainbot.io"+ assert state["credential_type"] == "auth_token"assert state["active_auth_mode"] == "api_key"# settings.json alone is not a *conflict*; it's only a conflict when# BOTH V2Config and settings.json carry a key.@@ -506,10 +507,11 @@ def test_claude_settings_json_takes_precedence_over_legacy_v2config(assert masked is not Noneassert masked.endswith("ings")assert state["base_url"] == "https://v2config.example.io"+ assert state["credential_type"] == "api_key"assert state["settings_conflict"] is False-def test_save_claude_relay_auth_writes_bearer_token_and_clears_v2_secret(+def test_save_claude_explicit_auth_token_clears_v2_secret(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,claude_restart_calls: list[dict],@@ -543,6 +545,7 @@ def test_save_claude_relay_auth_writes_bearer_token_and_clears_v2_secret({"auth_mode": "api_key","api_key": "sk-ant-new-settings-key",+ "credential_type": "auth_token","base_url": "https://relay.example.invalid",})@@ -608,6 +611,7 @@ def test_save_claude_auth_reports_partial_when_oauth_cleanup_fails({"auth_mode": "api_key","api_key": "sk-ant-new-settings-key",+ "credential_type": "auth_token","base_url": "https://relay.example.invalid",})@@ -665,6 +669,7 @@ def test_save_claude_auth_restores_pending_oauth_backup_before_writing_new_key({"auth_mode": "api_key","api_key": "sk-new-key",+ "credential_type": "auth_token","base_url": "https://new-relay.example.invalid",})@@ -679,9 +684,14 @@ def test_save_claude_auth_restores_pending_oauth_backup_before_writing_new_key(@pytest.mark.parametrize("base_url",- [None, "https://api.anthropic.com", "https://api.anthropic.com/"],+ [+ None,+ "https://api.anthropic.com",+ "https://api.anthropic.com/",+ "https://relay.example.invalid",+ ],)-def test_save_claude_direct_auth_writes_anthropic_api_key(+def test_save_claude_explicit_api_key_is_independent_from_base_url(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,claude_restart_calls: list[dict],@@ -710,6 +720,7 @@ def test_save_claude_direct_auth_writes_anthropic_api_key({"auth_mode": "api_key","api_key": "sk-ant-direct-key",+ "credential_type": "api_key","base_url": base_url,})@@ -731,7 +742,7 @@ def test_save_claude_direct_auth_writes_anthropic_api_key(]-def test_save_claude_base_url_update_switches_header_without_retyping_key(+def test_save_claude_base_url_update_preserves_credential_type(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,claude_restart_calls: list[dict],@@ -767,9 +778,10 @@ def test_save_claude_base_url_update_switches_header_without_retyping_key(})- assert relay_result["settings_env_key_var"] == "ANTHROPIC_AUTH_TOKEN"+ assert relay_result["settings_env_key_var"] == "ANTHROPIC_API_KEY"+ assert relay_result["credential_type"] == "api_key"assert read_claude_settings_env() == {- "ANTHROPIC_AUTH_TOKEN": "sk-ant-preserved",+ "ANTHROPIC_API_KEY": "sk-ant-preserved","ANTHROPIC_BASE_URL": "https://relay.example.invalid",}@@ -785,6 +797,75 @@ def test_save_claude_base_url_update_switches_header_without_retyping_key(assert len(claude_restart_calls) == 2+def test_save_claude_credential_type_switch_reuses_stored_value(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ claude_restart_calls: list[dict],+) -> None:+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)+ monkeypatch.setattr(+ "vibe.api._clear_claude_oauth_credentials_after_api_key_save",+ lambda _service=None: {"ok": True},+ )+ _write_claude_settings(+ tmp_path,+ {+ "ANTHROPIC_API_KEY": "shared-credential",+ "ANTHROPIC_BASE_URL": "https://relay.example.invalid",+ },+ )++ from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config+ from vibe.api import save_claude_auth+ from vibe.claude_config import read_claude_settings_env++ config = V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ )+ config.agents.claude.auth_mode = "api_key"+ config.agents.claude.auth_mode_set = True+ config.save()++ result = save_claude_auth(+ {+ "auth_mode": "api_key",+ "credential_type": "auth_token",+ }+ )++ assert result["credential_type"] == "auth_token"+ assert result["settings_env_key_var"] == "ANTHROPIC_AUTH_TOKEN"+ assert read_claude_settings_env() == {+ "ANTHROPIC_AUTH_TOKEN": "shared-credential",+ "ANTHROPIC_BASE_URL": "https://relay.example.invalid",+ }+ assert len(claude_restart_calls) == 1+++def test_save_claude_auth_rejects_unknown_credential_type() -> None:+ from vibe.api import save_claude_auth++ for invalid_type in ("automatic", ["api_key"]):+ result = save_claude_auth(+ {+ "auth_mode": "api_key",+ "api_key": "credential",+ "credential_type": invalid_type,+ }+ )++ assert result == {+ "ok": False,+ "message": "Choose either API key or auth token for the Claude Code credential.",+ }++def test_save_claude_auth_keeps_settings_token_over_legacy_v2_key(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,diff --git a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx b/ui/src/components/settings/providers/ClaudeProviderConfig.tsxindex b073e2f5d..1016f4d94 100644--- a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx+++ b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx@@ -26,7 +26,11 @@ import { SegmentedRadio } from '../shared/SegmentedRadio';import { useBackendRuntime } from '../shared/useBackendRuntime';import { useOAuthFlowLock } from '../shared/useOAuthFlowLock';import { useApi } from '@/context/ApiContext';-import type { ClaudeAuthMode, ClaudeAuthState } from '@/context/ApiContext';+import type {+ ClaudeAuthMode,+ ClaudeAuthState,+ ClaudeCredentialType,+} from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';import { errorMessage } from '@/lib/errorMessage';@@ -59,11 +63,14 @@ export const ClaudeProviderConfig: React.FC<{// saved key as a read-only mask (``sk-ant-•••cd34``) with a pencil to// replace it; true = empty editable input ready for a fresh secret.const [editingKey, setEditingKey] = useState(false);+ const [credentialType, setCredentialType] = useState<ClaudeCredentialType>('api_key');const [baseUrl, setBaseUrl] = useState('');// Snapshot the last loaded/saved auth-mode + base_url so we can hide// the Save button when nothing has changed (page feedback: no-op// Save buttons are noise).const [savedAuthMode, setSavedAuthMode] = useState<ClaudeAuthMode>('oauth');+ const [savedCredentialType, setSavedCredentialType] =+ useState<ClaudeCredentialType>('api_key');const [savedBaseUrl, setSavedBaseUrl] = useState('');// Freeze the auth-mode segmented radio while the OAuth panel is mid-// handshake. Shared with Codex / OpenCode via ``useOAuthFlowLock``.@@ -89,9 +96,12 @@ export const ClaudeProviderConfig: React.FC<{const initialMode =data.active_auth_mode !== 'none' ? data.active_auth_mode : data.auth_mode;const initialBase = data.base_url || '';+ const initialCredentialType = data.credential_type || 'api_key';setAuthMode(initialMode);+ setCredentialType(initialCredentialType);setBaseUrl(initialBase);setSavedAuthMode(initialMode);+ setSavedCredentialType(initialCredentialType);setSavedBaseUrl(initialBase);// The masked preview lives in ``authState.api_key_masked``;// ``apiKey`` stays empty until the user clicks "Replace".@@ -119,6 +129,15 @@ export const ClaudeProviderConfig: React.FC<{[t]);+ const credentialTypeOptions = useMemo(+ () =>+ [+ { id: 'api_key' as const, label: t('settings.backends.claudeCredentialTypeApiKey') },+ { id: 'auth_token' as const, label: t('settings.backends.claudeCredentialTypeAuthToken') },+ ] as const,+ [t]+ );+const apiKeyStatus = authState?.has_api_key? t('settings.backends.claudeApiKeyConfigured', { length: authState.api_key_length }): t('settings.backends.claudeApiKeyMissing');@@ -144,6 +163,9 @@ export const ClaudeProviderConfig: React.FC<{}const fresh = await api.getClaudeAuth();setAuthState(fresh);+ const freshCredentialType = fresh.credential_type || 'api_key';+ setCredentialType(freshCredentialType);+ setSavedCredentialType(freshCredentialType);setBaseUrl(fresh.base_url || '');setSavedBaseUrl(fresh.base_url || '');setApiKey('');@@ -176,6 +198,7 @@ export const ClaudeProviderConfig: React.FC<{api_key: authMode === 'api_key' ? (apiKey || undefined) : null,};if (authMode === 'api_key') {+ payload.credential_type = credentialType;payload.base_url = baseUrl.trim() || null;}const result = await api.saveClaudeAuth(payload as any);@@ -187,9 +210,12 @@ export const ClaudeProviderConfig: React.FC<{const nextMode =result.active_auth_mode !== 'none' ? result.active_auth_mode : result.auth_mode;const nextBase = result.base_url || '';+ const nextCredentialType = result.credential_type || credentialType;setAuthMode(nextMode);+ setCredentialType(nextCredentialType);setBaseUrl(nextBase);setSavedAuthMode(nextMode);+ setSavedCredentialType(nextCredentialType);setSavedBaseUrl(nextBase);setApiKey('');setEditingKey(false);@@ -250,7 +276,7 @@ export const ClaudeProviderConfig: React.FC<{<CheckCircle2 className="size-3" />{authState.active_auth_mode === 'oauth'? t('settings.backends.activeAuthOauth')- : t('settings.backends.activeAuthApiKey')}+ : t('settings.backends.claudeActiveAuthCredential')}</Badge>)}{authState?.active_auth_mode === 'none' && (@@ -313,9 +339,27 @@ export const ClaudeProviderConfig: React.FC<{{authMode === 'api_key' && (<>+ <div className="flex flex-col gap-2">+ <Label className="text-xs font-medium uppercase text-muted">+ {t('settings.backends.claudeCredentialTypeLabel')}+ </Label>+ <SegmentedRadio+ value={credentialType}+ onChange={setCredentialType}+ options={credentialTypeOptions}+ ariaLabel={t('settings.backends.claudeCredentialTypeLabel') as string}+ disabled={authSaving}+ />+ <p className="text-[12px] leading-relaxed text-muted">+ {credentialType === 'api_key'+ ? t('settings.backends.claudeCredentialTypeApiKeyHint')+ : t('settings.backends.claudeCredentialTypeAuthTokenHint')}+ </p>+ </div>+<div className="flex flex-col gap-2"><Label htmlFor="claude-api-key" className="text-xs font-medium uppercase text-muted">- {t('settings.backends.claudeApiKeyLabel')}+ {t('settings.backends.claudeCredentialValueLabel')}</Label>{authState?.has_api_key && !editingKey ? (// Same masked-preview affordance the Codex page uses;@@ -366,7 +410,11 @@ export const ClaudeProviderConfig: React.FC<{type="password"autoComplete="off"spellCheck={false}- placeholder={t('settings.backends.claudeApiKeyPlaceholder') as string}+ placeholder={t(+ credentialType === 'api_key'+ ? 'settings.backends.claudeApiKeyPlaceholder'+ : 'settings.backends.claudeAuthTokenPlaceholder'+ ) as string}value={apiKey}onChange={(e) => setApiKey(e.target.value)}className="pl-9 font-mono"@@ -461,6 +509,7 @@ export const ClaudeProviderConfig: React.FC<{{authMode === 'api_key' && (() => {const dirty =authMode !== savedAuthMode ||+ credentialType !== savedCredentialType ||apiKey.trim().length > 0 ||baseUrl.trim() !== savedBaseUrl.trim();if (!dirty) return null;diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex abb37bc2c..dfce06d9b 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1772,6 +1772,7 @@ export type CodexAuthSaveResult = CodexAuthState & {};export type ClaudeAuthMode = 'oauth' | 'api_key';+export type ClaudeCredentialType = 'api_key' | 'auth_token';// Claude Code reads ``~/.claude/settings.json`` at launch and its ``env``// block wins over inherited process env. avibe therefore writes@@ -1800,6 +1801,7 @@ export type ClaudeAuthState = {settings_env_has_key: boolean;settings_env_key_length: number;settings_env_key_var: 'ANTHROPIC_API_KEY' | 'ANTHROPIC_AUTH_TOKEN' | null;+ credential_type: ClaudeCredentialType | null;settings_env_base_url: string | null;settings_conflict: boolean;message?: string;@@ -1808,6 +1810,7 @@ export type ClaudeAuthState = {export type ClaudeAuthPayload = {auth_mode: ClaudeAuthMode;api_key?: string | null;+ credential_type?: ClaudeCredentialType;base_url?: string | null;};diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex c00b82f85..6472dc6e7 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -387,8 +387,8 @@"claudeAuthModeLabel": "Authentication mode","claudeAuthModeOauth": "Sign in with Claude","claudeAuthModeOauthHint": "Use your Anthropic account to authorize Claude Code. Avibe stops managing the API key while this is selected.",- "claudeAuthModeApiKey": "Anthropic API key",- "claudeAuthModeApiKeyHint": "Saving updates Claude Code's own `settings.json` env block so the CLI uses this key directly.",+ "claudeAuthModeApiKey": "Claude Code credential",+ "claudeAuthModeApiKeyHint": "Choose the native Claude Code variable that carries this value. Claude Code derives the request header from that variable; the Base URL only selects the endpoint.","claudeOauthSignedIn": "Claude is signed in.","claudeOauthPanelTitle": "Sign in with your Anthropic account","claudeOauthPanelSubtitle": "Open the authorization URL below, approve access, then paste the callback code Anthropic shows you.",@@ -396,17 +396,23 @@"claudeCallbackCodeLabel": "Authorization code","claudeCallbackCodePlaceholder": "code#state","claudeCallbackCodeHint": "Anthropic shows a value like `abc123#xyz`. Paste it here exactly — Avibe forwards it to Claude Code.",- "claudeApiKeyLabel": "API key",+ "claudeCredentialTypeLabel": "Claude Code variable",+ "claudeCredentialTypeApiKey": "ANTHROPIC_API_KEY · x-api-key",+ "claudeCredentialTypeAuthToken": "ANTHROPIC_AUTH_TOKEN · Authorization: Bearer",+ "claudeCredentialTypeApiKeyHint": "Claude Code sends this value in the x-api-key header. The Base URL does not change this selection.",+ "claudeCredentialTypeAuthTokenHint": "Claude Code sends this value in the Authorization: Bearer header. The Base URL does not change this selection.",+ "claudeCredentialValueLabel": "Credential value","claudeApiKeyPlaceholder": "sk-ant-...",- "claudeApiKeyConfigured": "A key of length {{length}} is currently stored.",- "claudeApiKeyMissing": "No API key stored yet.",+ "claudeAuthTokenPlaceholder": "Token or API key from your gateway",+ "claudeApiKeyConfigured": "A credential of length {{length}} is currently stored.",+ "claudeApiKeyMissing": "No API credential stored yet.","claudeBaseUrlLabel": "Base URL (optional)","claudeBaseUrlPlaceholder": "https://api.anthropic.com",- "claudeBaseUrlHint": "Leave empty to use Anthropic's default endpoint. Compatible relays (e.g. Bedrock proxies, AWS endpoints) accept their own URL here.",+ "claudeBaseUrlHint": "Leave empty to use Anthropic's default endpoint. This only selects the endpoint; it does not select a variable or header.","claudeBaseUrlReset": "Reset to default","claudeSettingsConflictTitle": "Legacy Avibe key will be migrated","claudeSettingsConflictBody": "Saving updates `{{var}}` in {{path}} and clears the old Avibe copy.",- "claudeInfoHint": "Saving writes Claude Code's `settings.json` env values and refreshes Avibe's cached Claude sessions. The next request uses the selected authentication mode.",+ "claudeInfoHint": "Saving writes the selected native credential variable and Base URL to Claude Code's `settings.json`, then refreshes Avibe's cached Claude sessions.","claudeSave": "Save and refresh Claude","claudeSaving": "Saving…","claudeSaveSuccess": "Claude auth saved and runtime refreshed",@@ -453,12 +459,13 @@"testConnectionRawOutputLabel": "Raw output","activeAuthOauth": "Active: OAuth","activeAuthApiKey": "Active: API Key",+ "claudeActiveAuthCredential": "Active: Credential","activeAuthNone": "Not signed in","replaceApiKey": "Replace","claudeApiKeyRemove": "Remove key",- "claudeApiKeyRemoveConfirm": "Remove the stored Anthropic API key? OAuth credentials are left untouched.",- "claudeApiKeyRemoved": "Stored Anthropic API key removed.",- "claudeApiKeyRemoveFailed": "Could not remove API key: {{detail}}",+ "claudeApiKeyRemoveConfirm": "Remove the stored Claude API credential? OAuth credentials are left untouched.",+ "claudeApiKeyRemoved": "Stored Claude API credential removed.",+ "claudeApiKeyRemoveFailed": "Could not remove API credential: {{detail}}","codexApiKeyRemove": "Remove key","codexApiKeyRemoveConfirm": "Remove the stored OpenAI API key from auth.json? Codex will fall back to OAuth tokens if present, or sit unconfigured if not.","codexApiKeyRemoved": "Stored OpenAI API key removed.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 75cbcec81..5b51a24d6 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -387,8 +387,8 @@"claudeAuthModeLabel": "认证方式","claudeAuthModeOauth": "Claude 账号登录","claudeAuthModeOauthHint": "使用 Anthropic 账号授权 Claude Code。选中此项后,Avibe 不再管理 API Key。",- "claudeAuthModeApiKey": "Anthropic API Key",- "claudeAuthModeApiKeyHint": "保存后会直接更新 Claude Code 自己的 `settings.json` env 配置,CLI 会使用这里的 Key。",+ "claudeAuthModeApiKey": "Claude Code 凭据",+ "claudeAuthModeApiKeyHint": "选择承载该值的 Claude Code 原生变量。Claude Code 会根据这个变量生成请求 Header;Base URL 只决定请求地址。","claudeOauthSignedIn": "Claude 已登录。","claudeOauthPanelTitle": "使用 Anthropic 账号登录","claudeOauthPanelSubtitle": "打开下方授权链接、批准访问,然后粘贴 Anthropic 返回给你的回调码。",@@ -396,17 +396,23 @@"claudeCallbackCodeLabel": "授权码","claudeCallbackCodePlaceholder": "code#state","claudeCallbackCodeHint": "Anthropic 会展示类似 `abc123#xyz` 的值,请原样粘贴到这里。Avibe 会把它转交给 Claude Code 完成登录。",- "claudeApiKeyLabel": "API Key",+ "claudeCredentialTypeLabel": "Claude Code 变量",+ "claudeCredentialTypeApiKey": "ANTHROPIC_API_KEY · x-api-key",+ "claudeCredentialTypeAuthToken": "ANTHROPIC_AUTH_TOKEN · Authorization: Bearer",+ "claudeCredentialTypeApiKeyHint": "Claude Code 会将该值放到 x-api-key Header;Base URL 不会改变这个选择。",+ "claudeCredentialTypeAuthTokenHint": "Claude Code 会将该值放到 Authorization: Bearer Header;Base URL 不会改变这个选择。",+ "claudeCredentialValueLabel": "凭据值","claudeApiKeyPlaceholder": "sk-ant-...",- "claudeApiKeyConfigured": "当前已保存一份长度为 {{length}} 的 Key。",- "claudeApiKeyMissing": "尚未保存 API Key。",+ "claudeAuthTokenPlaceholder": "中转服务提供的 Token 或 API Key",+ "claudeApiKeyConfigured": "当前已保存一份长度为 {{length}} 的凭据。",+ "claudeApiKeyMissing": "尚未保存 API 凭据。","claudeBaseUrlLabel": "Base URL(可选)","claudeBaseUrlPlaceholder": "https://api.anthropic.com",- "claudeBaseUrlHint": "留空则使用 Anthropic 默认地址;兼容中转(如 Bedrock 代理、AWS Endpoint)可在此填写自定义地址。",+ "claudeBaseUrlHint": "留空则使用 Anthropic 默认地址。这里只决定请求地址,不会自动选择变量或 Header。","claudeBaseUrlReset": "恢复默认","claudeSettingsConflictTitle": "旧的 Avibe Key 将被迁移","claudeSettingsConflictBody": "保存会更新 {{path}} 里的 `{{var}}`,并清除旧的 Avibe 副本。",- "claudeInfoHint": "保存会写入 Claude Code 的 `settings.json` env 配置,并刷新 Avibe 缓存的 Claude 会话。下一次请求会使用所选认证方式。",+ "claudeInfoHint": "保存会把所选原生凭据变量和 Base URL 写入 Claude Code 的 `settings.json`,并刷新 Avibe 缓存的 Claude 会话。","claudeSave": "保存并刷新 Claude","claudeSaving": "保存中…","claudeSaveSuccess": "Claude 认证已保存,运行时已刷新",@@ -453,12 +459,13 @@"testConnectionRawOutputLabel": "原始输出","activeAuthOauth": "当前:OAuth","activeAuthApiKey": "当前:API Key",+ "claudeActiveAuthCredential": "当前:API 凭据","activeAuthNone": "未登录","replaceApiKey": "替换","claudeApiKeyRemove": "移除 Key",- "claudeApiKeyRemoveConfirm": "确定要移除已保存的 Anthropic API Key 吗?OAuth 凭据不会受影响。",- "claudeApiKeyRemoved": "已移除 Anthropic API Key。",- "claudeApiKeyRemoveFailed": "移除 API Key 失败:{{detail}}",+ "claudeApiKeyRemoveConfirm": "确定要移除已保存的 Claude API 凭据吗?OAuth 凭据不会受影响。",+ "claudeApiKeyRemoved": "已移除 Claude API 凭据。",+ "claudeApiKeyRemoveFailed": "移除 API 凭据失败:{{detail}}","codexApiKeyRemove": "移除 Key","codexApiKeyRemoveConfirm": "确定要从 auth.json 移除已保存的 OpenAI API Key 吗?如果有 OAuth 凭据,Codex 会回落到 OAuth;否则会变成未配置状态。","codexApiKeyRemoved": "已移除 OpenAI API Key。",diff --git a/vibe/api.py b/vibe/api.pyindex 7c620bac1..7412a1777 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -8359,18 +8359,7 @@ def restart_backend(name: str, *, metadata: Optional[dict[str, Any]] = None) ->_VALID_AUTH_MODES = {"oauth", "api_key"}-_ANTHROPIC_API_HOST = "api.anthropic.com"---def _claude_uses_bearer_auth(base_url: str | None) -> bool:- """Return whether Claude should send the credential as a bearer token."""- if not base_url:- return False- try:- hostname = urllib.parse.urlsplit(base_url).hostname- except ValueError:- return True- return (hostname or "").lower() != _ANTHROPIC_API_HOST+_VALID_CLAUDE_CREDENTIAL_TYPES = {"api_key", "auth_token"}def _mask_api_key(api_key: str | None) -> str | None:@@ -9195,6 +9184,11 @@ def get_claude_auth() -> dict:"settings_env_has_key": bool(disk_state.get("settings_env_has_key")),"settings_env_key_length": int(disk_state.get("settings_env_key_length") or 0),"settings_env_key_var": disk_state.get("settings_env_key_var"),+ "credential_type": (+ disk_state.get("credential_type")+ if settings_key+ else ("api_key" if configured_key else None)+ ),"settings_env_base_url": disk_state.get("settings_env_base_url"),"settings_conflict": settings_conflict,}@@ -9207,15 +9201,16 @@ def save_claude_auth(payload: dict) -> dict:not carry the API key because Claude Code's ``settings.json`` env blockwins at launch anyway.- Empty ``api_key`` while in ``api_key`` mode is treated as "keep the- stored key" — same UX promise as Codex — so callers can PATCH the- base URL without re-typing the secret. An empty key with no stored- fallback is rejected.+ ``credential_type`` selects Claude Code's native credential variable:+ ``api_key`` writes ``ANTHROPIC_API_KEY`` and ``auth_token`` writes+ ``ANTHROPIC_AUTH_TOKEN``. The Base URL is independent and never changes+ that selection. When callers omit ``credential_type``, an existing+ settings variable is preserved; new and legacy credentials default to+ ``api_key`` for backwards compatibility.- Claude Code uses different headers for direct Anthropic API keys and- gateway credentials. Direct keys are stored as ``ANTHROPIC_API_KEY``- (``x-api-key``), while a non-Anthropic Base URL stores the same user-facing- credential as ``ANTHROPIC_AUTH_TOKEN`` (``Authorization: Bearer``).+ Empty ``api_key`` while in ``api_key`` mode means "keep the stored+ credential", so callers can update the Base URL or credential type without+ re-typing the secret. An empty value with no stored fallback is rejected."""if not isinstance(payload, dict):return {"ok": False, "message": "Payload must be an object"}@@ -9229,6 +9224,19 @@ def save_claude_auth(payload: dict) -> dict:return {"ok": False, "message": "api_key must be a string"}api_key = raw_api_key.strip() if isinstance(raw_api_key, str) else None+ raw_credential_type = payload.get("credential_type")+ if (+ raw_credential_type is not None+ and (+ not isinstance(raw_credential_type, str)+ or raw_credential_type not in _VALID_CLAUDE_CREDENTIAL_TYPES+ )+ ):+ return {+ "ok": False,+ "message": backend_t("error.claudeCredentialTypeInvalid"),+ }+# Three-state ``base_url`` payload semantics (matches Codex/OpenCode):# absent key → keep stored value; null/blank → clear; non-blank → set.base_url_present = "base_url" in payload@@ -9241,45 +9249,43 @@ def save_claude_auth(payload: dict) -> dict:if base_url_change == "":base_url_change = None- settings_auth_token = None- if auth_mode == "api_key" and not api_key:- # Reuse the live Claude settings key for base-URL-only updates.- # Fall back to legacy V2Config only for older installs that have- # not yet been migrated through this save path.+ settings_env: dict[str, str] = {}+ existing_credential_type: str | None = None+ existing_credential: str | None = None+ if auth_mode == "api_key":try:from vibe.claude_config import (- read_claude_api_key_from_settings,+ read_claude_credential_from_settings,read_claude_settings_env,)- api_key = read_claude_api_key_from_settings()- if not api_key:- env = read_claude_settings_env()- token = env.get("ANTHROPIC_AUTH_TOKEN")- settings_auth_token = token if isinstance(token, str) and token.strip() else None+ settings_env = read_claude_settings_env()+ existing_credential_type, existing_credential = (+ read_claude_credential_from_settings()+ )except Exception:- api_key = None- settings_auth_token = None- if not api_key and not settings_auth_token:- with CONFIG_LOCK:- try:- existing = load_config()- stored = getattr(getattr(existing, "agents", None), "claude", None)- api_key = getattr(stored, "api_key", None) or None- except Exception:- pass- if not api_key and not settings_auth_token:+ settings_env = {}++ credential_type = None+ if auth_mode == "api_key":+ credential_type = raw_credential_type or existing_credential_type or "api_key"+ credential = api_key or existing_credential++ if auth_mode == "api_key" and not credential:+ # Fall back to legacy V2Config only for older installs that have not+ # yet migrated their credential into Claude Code settings.+ with CONFIG_LOCK:+ try:+ existing = load_config()+ stored = getattr(getattr(existing, "agents", None), "claude", None)+ credential = getattr(stored, "api_key", None) or None+ except Exception:+ pass+ if not credential:return {"ok": False, "message": "api_key is required when auth_mode='api_key'"}effective_base_url = base_url_change if base_url_present else Noneif not base_url_present and auth_mode == "api_key":- settings_env = {}- try:- from vibe.claude_config import read_claude_settings_env-- settings_env = read_claude_settings_env()- except Exception:- settings_env = {}existing_base = settings_env.get("ANTHROPIC_BASE_URL")if isinstance(existing_base, str) and existing_base.strip():effective_base_url = existing_base.strip()@@ -9297,19 +9303,17 @@ def save_claude_auth(payload: dict) -> dict:from vibe.claude_config import apply_claude_authtry:- credential = api_key or settings_auth_token- use_auth_token = _claude_uses_bearer_auth(effective_base_url)apply_claude_auth(auth_mode=auth_mode,api_key=(credential- if auth_mode == "api_key" and not use_auth_token+ if auth_mode == "api_key" and credential_type == "api_key"else None),base_url=effective_base_url if auth_mode == "api_key" else None,auth_token=(credential- if auth_mode == "api_key" and use_auth_token+ if auth_mode == "api_key" and credential_type == "auth_token"else None),)diff --git a/vibe/claude_config.py b/vibe/claude_config.pyindex 466c53fc5..32478f8bb 100644--- a/vibe/claude_config.py+++ b/vibe/claude_config.py@@ -38,10 +38,9 @@ MANAGED_ENV_VALUES = {}# Keys we recognise inside ``~/.claude/settings.json``'s ``env`` block.-# ``ANTHROPIC_API_KEY`` is the SDK's documented variable; relay setups-# (e.g. Cloudflare-fronted gateways like ai-relay) prefer-# ``ANTHROPIC_AUTH_TOKEN``. We surface both so a hand-edited config-# doesn't silently invalidate the Settings UI.+# Claude Code assigns header semantics from the selected variable, independently+# from ``ANTHROPIC_BASE_URL``. Avibe preserves that native distinction instead+# of inferring a credential type from the endpoint hostname.RELEVANT_ENV_KEYS = ("ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN",@@ -292,9 +291,10 @@ def apply_claude_auth() -> Dict[str, Any]:"""Persist Claude auth into ``settings.json``.- In ``api_key`` mode the caller selects exactly one credential variable:- ``ANTHROPIC_API_KEY`` for Anthropic's direct ``x-api-key`` header or- ``ANTHROPIC_AUTH_TOKEN`` for a gateway's ``Authorization: Bearer`` header.+ In ``api_key`` mode the caller selects exactly one native Claude Code+ credential variable: ``ANTHROPIC_API_KEY`` or ``ANTHROPIC_AUTH_TOKEN``.+ Claude Code owns the resulting request headers; ``ANTHROPIC_BASE_URL``+ does not affect which variable Avibe persists.``oauth`` mode removes all Anthropic credential/base-url overrides from theenv block and leaves Claude's OAuth credentials untouched. Both modesupsert Avibe's non-secret Claude Code env defaults.@@ -411,26 +411,32 @@ def read_claude_auth_state(home: Path | None = None) -> Dict[str, Any]:if "ANTHROPIC_API_KEY" in env_blockelse ("ANTHROPIC_AUTH_TOKEN" if "ANTHROPIC_AUTH_TOKEN" in env_block else None)),+ "credential_type": (+ "api_key"+ if "ANTHROPIC_API_KEY" in env_block+ else ("auth_token" if "ANTHROPIC_AUTH_TOKEN" in env_block else None)+ ),"settings_env_base_url": settings_base,}-def read_claude_api_key_from_settings(home: Path | None = None) -> Optional[str]:- """Return ``settings.json``'s ``ANTHROPIC_API_KEY`` if it has one.-- Used as a fallback when the UI sends a base-URL-only update: V2Config- may be stale (older installs lacked ``api_key``), but the CLI still- picks up whatever is in ``settings.json``. Prefer that over silently- blanking the live key.+def read_claude_credential_from_settings(+ home: Path | None = None,+) -> tuple[str | None, str | None]:+ """Return Claude Code's selected credential type and value.- Restricted to ``ANTHROPIC_API_KEY`` on purpose. ``ANTHROPIC_AUTH_TOKEN``- is the bearer-token relay variant and must not be returned through a helper- whose callers assume ``x-api-key`` semantics. ``save_claude_auth`` reads- the bearer token separately, preserves the credential, and chooses the- header from the effective Base URL.+ The credential variable is authoritative. Base URL-only edits must preserve+ it exactly, because Claude Code treats ``ANTHROPIC_API_KEY`` and+ ``ANTHROPIC_AUTH_TOKEN`` as distinct inputs."""env_block = read_claude_settings_env(home)- return env_block.get("ANTHROPIC_API_KEY")+ api_key = env_block.get("ANTHROPIC_API_KEY")+ if api_key:+ return "api_key", api_key+ auth_token = env_block.get("ANTHROPIC_AUTH_TOKEN")+ if auth_token:+ return "auth_token", auth_token+ return None, Nonedef build_claude_subprocess_env(@@ -452,7 +458,7 @@ def build_claude_subprocess_env(OAuth in Settings but their shell exports ``ANTHROPIC_API_KEY``, theClaude CLI silently keeps API-key auth and never reachesClaude Code's OAuth credential store. Stripping both ``ANTHROPIC_API_KEY``- and ``ANTHROPIC_AUTH_TOKEN`` (header-semantics switch) in OAuth mode+ and ``ANTHROPIC_AUTH_TOKEN`` (both native credential inputs) in OAuth modemakes the Settings toggle authoritative.``force_oauth=True`` is the escape hatch for callers that ARE thediff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex e75cc2dbd..344069000 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -289,6 +289,7 @@"streamTurnInProgress": "⚠️ A reply is already streaming for this session — wait for it to finish, then try again.","sessionReset": "Session error detected. Session has been reset. Please try your message again.","sessionConnectionLost": "Connection to Claude was lost. Please try your message again.",+ "claudeCredentialTypeInvalid": "Choose either API key or auth token for the Claude Code credential.","claudeSessionNotFound": "Claude Code could not find the historical session `{sessionId}` in the current working directory:\n`{path}`\n\nClaude Code sessions are scoped to a working directory. This usually means the conversation was resumed after switching workdirs, or the local Claude Code session data changed. Switch back to the original working directory to continue that session, or start a new Claude Code session from the current directory.","sessionGeneric": "An error occurred: {error}","resultAttachmentUploadFailed": "Failed to upload attachment. Want me to split the result into multiple messages?",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 4ddcf6763..518d17775 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -289,6 +289,7 @@"streamTurnInProgress": "⚠️ 这个会话已经有一条回复在生成中,请等它完成后再试。","sessionReset": "检测到会话错误。会话已重置,请重试。","sessionConnectionLost": "与 Claude 的连接已断开,请重试。",+ "claudeCredentialTypeInvalid": "Claude Code 凭据类型只能选择 API Key 或 Auth Token。","claudeSessionNotFound": "Claude Code 在当前工作目录下找不到历史会话 `{sessionId}`:\n`{path}`\n\nClaude Code 的会话和工作目录相关。通常是恢复会话后切换了工作目录,或本地 Claude Code 会话数据发生变化。请切回原来的工作目录继续该会话,或在当前目录开始一个新的 Claude Code 会话。","sessionGeneric": "发生错误:{error}","resultAttachmentUploadFailed": "附件上传失败。要我改成拆分成多条消息发送吗?",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 60bb9fc95..8d2ef3ceb 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -5590,7 +5590,8 @@ def backend_claude_auth_get():def backend_claude_auth_post():"""Persist Claude auth and refresh cached Claude SDK sessions.- Body: ``{auth_mode: 'oauth'|'api_key', api_key?: string, base_url?: string}``.+ Body: ``{auth_mode: 'oauth'|'api_key', api_key?: string,+ credential_type?: 'api_key'|'auth_token', base_url?: string}``.Secrets live in Claude Code's own settings; V2Config records the selectedmode, and the controller rolls its Claude runtime state after the write."""