Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(backends): isolate cli upgrades and claude auth config

cyh71161a1d69dd
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 11b897262..493fca339 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -1675,6 +1675,17 @@ class AgentAuthService:
logout_ok, logout_error = await self._run_utility_command(binary, "logout")
else:
logout_ok, logout_error = await self._run_utility_command(binary, "auth", "logout")
+ try:
+ from vibe.claude_config import apply_claude_auth
+
+ await asyncio.to_thread(
+ apply_claude_auth,
+ auth_mode="oauth",
+ api_key=None,
+ base_url=None,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Failed to clear Claude settings env during logout: %s", exc)
try:
config = getattr(self.controller, "config", None)
@@ -2481,6 +2492,18 @@ class AgentAuthService:
stub controller exposes a non-savable config object.
"""
try:
+ if backend == "claude" and auth_mode == "oauth":
+ try:
+ from vibe.claude_config import apply_claude_auth
+
+ await asyncio.to_thread(
+ apply_claude_auth,
+ auth_mode="oauth",
+ api_key=None,
+ base_url=None,
+ )
+ except Exception as err: # noqa: BLE001
+ logger.warning("Failed to clear Claude settings env after OAuth flow: %s", err)
config = getattr(self.controller, "config", None)
target = getattr(getattr(config, "agents", None), backend, None)
saver = getattr(config, "save", None) if config is not None else None
diff --git a/docs/plans/backend-cli-config-upgrades.md b/docs/plans/backend-cli-config-upgrades.md
new file mode 100644
index 000000000..1de09cc84
--- /dev/null
+++ b/docs/plans/backend-cli-config-upgrades.md
@@ -0,0 +1,40 @@
+# Backend CLI config and upgrade isolation
+
+## Problem
+
+Two backend-management paths have drifted away from the actual backend ownership boundaries:
+
+1. Claude Code API-key auth is stored in Vibe Remote V2Config and injected as environment variables. Claude Code also reads `~/.claude/settings.json` and layers `env` on top of the inherited process env, so the saved Vibe Remote key may not be the effective key. The correct source of truth is Claude Code's own settings file.
+2. Backend CLI install/upgrade runs synchronously in the UI request path. A slow or stuck CLI update can block a server worker. Backend CLI updates should be independent backend jobs, not main Vibe Remote lifecycle operations.
+
+## Design
+
+### Claude auth source of truth
+
+- Make `vibe.claude_config` able to atomically upsert/remove `env.ANTHROPIC_API_KEY`, `env.ANTHROPIC_AUTH_TOKEN`, and `env.ANTHROPIC_BASE_URL` in Claude's `settings.json`.
+- Change Claude auth read/write APIs so `settings.json` is authoritative for key/base-url state.
+- Keep V2Config fields only as migration cleanup / UI intent metadata. New saves must not persist the key in V2Config.
+- Keep OAuth mode explicit: remove Anthropic key/base-url entries from `settings.json`, set V2Config intent to OAuth, and keep existing OAuth credentials untouched.
+- Since Claude is per-request, saving Claude auth only needs controller/runtime config refresh, not Vibe Remote main-service restart.
+
+### Other backends
+
+- Codex remains correct structurally: auth writes go to `~/.codex/auth.json` plus `~/.codex/config.toml`; V2Config is only an intent/cache layer.
+- OpenCode remains correct structurally: provider keys go through OpenCode auth APIs / auth store; baseURL lives in OpenCode user config because OpenCode has no auth API field for it.
+
+### Backend CLI upgrades
+
+- Introduce an in-process backend install/upgrade job manager with job IDs, status, output, timeout handling, and child-process cleanup.
+- `POST /agent/<backend>/install` starts a background job and returns immediately. Existing install/upgrade command planning remains shared so behavior stays consistent.
+- Add `GET /agent/<backend>/install/<job_id>` for polling and optional latest-job lookup by backend.
+- On success, invalidate version cache and persist any newly detected CLI path. Do not restart Vibe Remote main service.
+- For backend runtime adoption after upgrade:
+ - Codex/OpenCode: request backend runtime refresh only, because they have persistent backend daemons.
+ - Claude: invalidate/probe version cache only; there is no backend daemon to restart.
+
+## Validation
+
+- Unit tests for Claude settings.json read/write, including overwriting stale env values and clearing OAuth mode.
+- API tests for Claude save behavior proving V2Config no longer stores the key.
+- API tests for async backend install job lifecycle, success, timeout cleanup, and non-blocking initial response shape.
+- Focused lint/test run on touched Python files and affected UI build/type check if frontend API shape changes.
diff --git a/tests/test_claude_subprocess_env.py b/tests/test_claude_subprocess_env.py
index 15be8732a..f321ffa98 100644
--- a/tests/test_claude_subprocess_env.py
+++ b/tests/test_claude_subprocess_env.py
@@ -24,6 +24,12 @@ def _cfg(**kwargs) -> SimpleNamespace:
return SimpleNamespace(**kwargs)
+def _empty_claude_home(tmp_path, monkeypatch) -> None:
+ claude_home = tmp_path / ".claude"
+ claude_home.mkdir()
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))
+
+
def test_oauth_strips_inherited_api_key_and_auth_token() -> None:
env = {
"ANTHROPIC_API_KEY": "sk-leaked",
@@ -32,17 +38,18 @@ def test_oauth_strips_inherited_api_key_and_auth_token() -> None:
"CLAUDE_CONFIG_DIR": "/keep",
"PATH": "/dropped",
}
- out = build_claude_subprocess_env(_cfg(auth_mode="oauth"), base_env=env)
+ out = build_claude_subprocess_env(_cfg(auth_mode="oauth", auth_mode_set=True), base_env=env)
assert "ANTHROPIC_API_KEY" not in out
assert "ANTHROPIC_AUTH_TOKEN" not in out
- # Non-credential ANTHROPIC_/CLAUDE_ vars and unrelated keys behave
- # as before: inherit only the namespaced ones, never PATH.
- assert out["ANTHROPIC_BASE_URL"] == "https://shell.example"
+ assert "ANTHROPIC_BASE_URL" not in out
+ # Non-credential CLAUDE_ vars and unrelated keys behave as before:
+ # inherit only the namespaced ones, never PATH.
assert out["CLAUDE_CONFIG_DIR"] == "/keep"
assert "PATH" not in out
-def test_api_key_mode_injects_configured_key_and_drops_bearer() -> None:
+def test_api_key_mode_injects_configured_key_and_drops_bearer(tmp_path, monkeypatch) -> None:
+ _empty_claude_home(tmp_path, monkeypatch)
env = {
"ANTHROPIC_API_KEY": "sk-stale",
"ANTHROPIC_AUTH_TOKEN": "bearer-stale",
@@ -58,7 +65,29 @@ def test_api_key_mode_injects_configured_key_and_drops_bearer() -> None:
assert "ANTHROPIC_AUTH_TOKEN" not in out
-def test_api_key_mode_without_configured_key_keeps_inherited() -> None:
+def test_api_key_mode_preserves_settings_json_auth_token_semantics(
+ tmp_path, monkeypatch
+) -> None:
+ claude_home = tmp_path / ".claude"
+ claude_home.mkdir()
+ (claude_home / "settings.json").write_text(
+ '{"env":{"ANTHROPIC_AUTH_TOKEN":"bearer-settings","ANTHROPIC_BASE_URL":"https://relay.example"}}',
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))
+
+ out = build_claude_subprocess_env(
+ _cfg(auth_mode="api_key", api_key="", auth_mode_set=True),
+ base_env={"ANTHROPIC_API_KEY": "sk-shell-stale"},
+ )
+
+ assert "ANTHROPIC_API_KEY" not in out
+ assert out["ANTHROPIC_AUTH_TOKEN"] == "bearer-settings"
+ assert out["ANTHROPIC_BASE_URL"] == "https://relay.example"
+
+
+def test_api_key_mode_without_configured_key_keeps_inherited(tmp_path, monkeypatch) -> None:
+ _empty_claude_home(tmp_path, monkeypatch)
# If the user picked api_key mode but left the field blank, fall
# back to whatever the shell exported; this matches the existing
# session_handler semantics before the auth_mode toggle existed.
@@ -70,10 +99,11 @@ def test_api_key_mode_without_configured_key_keeps_inherited() -> None:
assert out["ANTHROPIC_API_KEY"] == "sk-from-shell"
-def test_base_url_override_overrides_inherited() -> None:
+def test_base_url_override_overrides_inherited(tmp_path, monkeypatch) -> None:
+ _empty_claude_home(tmp_path, monkeypatch)
env = {"ANTHROPIC_BASE_URL": "https://shell.example"}
out = build_claude_subprocess_env(
- _cfg(auth_mode="oauth", base_url="https://relay.example/v1"),
+ _cfg(auth_mode="api_key", api_key="sk-test", base_url="https://relay.example/v1"),
base_env=env,
)
assert out["ANTHROPIC_BASE_URL"] == "https://relay.example/v1"
diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.py
index 5fdb4f405..1624f6372 100644
--- a/tests/test_settings_disk_fallback.py
+++ b/tests/test_settings_disk_fallback.py
@@ -132,12 +132,11 @@ def test_claude_settings_json_auth_token_surfaces_in_get_claude_auth(
assert state["settings_conflict"] is False
-def test_claude_v2config_takes_precedence_over_settings_json(
+def test_claude_settings_json_takes_precedence_over_legacy_v2config(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
- """When V2Config also has a key, that wins for display purposes
- (it's what we'd inject at launch). settings.json being present
- elevates ``settings_conflict`` so the UI can warn the user."""
+ """settings.json wins over legacy V2Config because Claude Code layers
+ it on top of inherited env at launch."""
_write_claude_settings(
tmp_path,
{"ANTHROPIC_API_KEY": "sk-stale-key-from-settings"},
@@ -162,10 +161,55 @@ def test_claude_v2config_takes_precedence_over_settings_json(
from vibe.api import get_claude_auth
state = get_claude_auth()
- assert state["api_key_source"] == "v2config"
+ assert state["api_key_source"] == "settings_json"
masked = state["api_key_masked"]
assert masked is not None
- # Mask preserves the trailing 4 characters of the V2Config key.
- assert masked.endswith("nfig")
+ assert masked.endswith("ings")
assert state["base_url"] == "https://v2config.example.io"
- assert state["settings_conflict"] is True
+ assert state["settings_conflict"] is False
+
+
+def test_save_claude_auth_writes_settings_json_and_clears_v2_secret(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))
+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
+
+ from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config
+ from vibe.api import get_claude_auth, save_claude_auth
+
+ cfg = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ )
+ cfg.agents.claude.auth_mode = "api_key"
+ cfg.agents.claude.api_key = "sk-old-v2-key"
+ cfg.agents.claude.base_url = "https://old.example.invalid"
+ cfg.save()
+
+ result = save_claude_auth(
+ {
+ "auth_mode": "api_key",
+ "api_key": "sk-ant-new-settings-key",
+ "base_url": "https://relay.example.invalid",
+ }
+ )
+
+ assert result["ok"] is True
+ settings = json.loads((tmp_path / ".claude" / "settings.json").read_text())
+ assert settings["env"]["ANTHROPIC_API_KEY"] == "sk-ant-new-settings-key"
+ assert settings["env"]["ANTHROPIC_BASE_URL"] == "https://relay.example.invalid"
+
+ saved = V2Config.load()
+ assert saved.agents.claude.api_key is None
+ assert saved.agents.claude.base_url is None
+ assert saved.agents.claude.auth_mode == "api_key"
+ assert saved.agents.claude.auth_mode_set is True
+
+ state = get_claude_auth()
+ assert state["api_key_source"] == "settings_json"
+ assert state["base_url"] == "https://relay.example.invalid"
diff --git a/tests/test_ui_server_install.py b/tests/test_ui_server_install.py
index b75c249a6..09571a49d 100644
--- a/tests/test_ui_server_install.py
+++ b/tests/test_ui_server_install.py
@@ -21,7 +21,11 @@ def _save_setup_host_config(host: str) -> None:
def test_install_agent_allows_same_origin_request(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_setup_host_config("192.168.2.3")
- monkeypatch.setattr(api, "install_agent", lambda name: {"ok": True, "name": name, "path": "/usr/local/bin/claude"})
+ monkeypatch.setattr(
+ api,
+ "start_agent_install_job",
+ lambda name: {"ok": True, "job_id": "job-1", "backend": name, "status": "running"},
+ )
client = app.test_client()
response = client.post(
@@ -32,12 +36,13 @@ def test_install_agent_allows_same_origin_request(monkeypatch, tmp_path):
assert response.status_code == 200
assert response.get_json()["ok"] is True
+ assert response.get_json()["status"] == "running"
def test_install_agent_rejects_cross_origin_request(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_setup_host_config("192.168.2.3")
- monkeypatch.setattr(api, "install_agent", lambda name: {"ok": True, "name": name})
+ monkeypatch.setattr(api, "start_agent_install_job", lambda name: {"ok": True, "name": name})
client = app.test_client()
headers = csrf_headers(client, "http://192.168.2.3:15131")
@@ -54,7 +59,7 @@ def test_install_agent_rejects_cross_origin_request(monkeypatch, tmp_path):
def test_install_agent_rejects_missing_csrf_token(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- monkeypatch.setattr(api, "install_agent", lambda name: {"ok": True, "name": name})
+ monkeypatch.setattr(api, "start_agent_install_job", lambda name: {"ok": True, "name": name})
client = app.test_client()
response = client.post(
@@ -69,7 +74,7 @@ def test_install_agent_rejects_missing_csrf_token(monkeypatch, tmp_path):
def test_install_agent_rejects_missing_origin(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
- monkeypatch.setattr(api, "install_agent", lambda name: {"ok": True, "name": name})
+ monkeypatch.setattr(api, "start_agent_install_job", lambda name: {"ok": True, "name": name})
client = app.test_client()
response = client.post(
@@ -79,3 +84,29 @@ def test_install_agent_rejects_missing_origin(monkeypatch, tmp_path):
assert response.status_code == 403
assert response.get_json()["message"] == "Forbidden: missing origin header"
+
+
+def test_install_agent_status_allows_poll(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_setup_host_config("192.168.2.3")
+ monkeypatch.setattr(
+ api,
+ "get_agent_install_job",
+ lambda job_id, backend=None: {
+ "ok": True,
+ "job_id": job_id,
+ "backend": backend,
+ "status": "succeeded",
+ "path": "/usr/local/bin/claude",
+ },
+ )
+
+ client = app.test_client()
+ response = client.get(
+ "/agent/claude/install/job-1",
+ headers=csrf_headers(client, "http://192.168.2.3:15131"),
+ base_url="http://192.168.2.3:15131",
+ )
+
+ assert response.status_code == 200
+ assert response.get_json()["status"] == "succeeded"
diff --git a/ui/src/components/settings/SettingsClaudeProviderPage.tsx b/ui/src/components/settings/SettingsClaudeProviderPage.tsx
index 1b6333041..d0af0eb06 100644
--- a/ui/src/components/settings/SettingsClaudeProviderPage.tsx
+++ b/ui/src/components/settings/SettingsClaudeProviderPage.tsx
@@ -160,9 +160,6 @@ export const SettingsClaudeProviderPage: React.FC = () => {
const onSaveAuth = async () => {
setAuthSaving(true);
try {
- // Omit base_url when in OAuth mode so toggling auth_mode does not
- // clear a relay URL the user configured in api_key mode — the
- // backend treats "absent" as "preserve stored value".
const payload: Record<string, unknown> = {
auth_mode: authMode,
api_key: authMode === 'api_key' ? (apiKey || undefined) : null,
@@ -418,15 +415,10 @@ export const SettingsClaudeProviderPage: React.FC = () => {
</>
)}
- {/* The settings.json conflict warning + Info hint only
- speak to the API-key flow (where saving collides with
- a hand-edited ``env`` block, or writes into V2Config).
- Showing them under OAuth is just clutter. */}
+ {/* Kept defensively for legacy states where V2Config still
+ carries a key before the next save migrates it. New saves
+ overwrite Claude's own settings.json directly. */}
{authMode === 'api_key' && authState?.settings_conflict && (
- // Claude Code applies its own ``env`` block on top of inherited
- // env, so a hand-edited ``settings.json`` will override the
- // V2Config-injected key at launch. Warn loudly — silently
- // letting a saved key be ignored is the worst outcome.
<div className="flex items-start gap-2 rounded-lg border border-gold/30 bg-gold/[0.08] px-3 py-2.5">
<AlertTriangle className="mt-0.5 size-3.5 shrink-0 text-gold" />
<div className="flex flex-col gap-1">
@@ -479,7 +471,7 @@ export const SettingsClaudeProviderPage: React.FC = () => {
{/* Connectivity probe — matches design.pen cdTest2 panel.
Works in both OAuth and API-key modes because the underlying
``claude -p "Hi"`` subprocess inherits whichever auth source
- V2Config selects at launch. */}
+ Claude Code reads at launch. */}
{!authLoading && <BackendTestPanel backend={BACKEND_ID} />}
</div>
)}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 579c9158b..bb0ee0b24 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -140,6 +140,8 @@ export type InstallResult = {
message: string;
output: string | null;
path?: string | null;
+ job_id?: string;
+ status?: 'running' | 'succeeded' | 'failed';
};
export type BackendRuntimeInfo = {
@@ -240,18 +242,10 @@ export type CodexAuthSaveResult = CodexAuthState & {
export type ClaudeAuthMode = 'oauth' | 'api_key';
-// Claude's auth surface differs structurally from Codex: V2Config is the
-// sole writer (no disk-side ``apply_claude_auth``) and the CLI inherits
-// env vars per request rather than via a persistent daemon. We still
-// inspect ``~/.claude/settings.json`` so the UI can warn when a
-// hand-edited ``env`` block would override the V2Config-injected key at
-// launch (Claude Code layers settings.json env on top of inherited env).
-// Which on-disk source the live API key came from. ``v2config`` means
-// the user (or a prior save) put it in Vibe Remote's V2Config and we
-// inject it as ``ANTHROPIC_API_KEY`` at launch. ``settings_json`` means
-// ``~/.claude/settings.json``'s ``env`` block already carries the key —
-// the live CLI reads it directly and our V2Config is empty (typically a
-// pre-existing setup that predates our Settings UI). ``null`` = no key.
+// Claude Code reads ``~/.claude/settings.json`` at launch and its ``env``
+// block wins over inherited process env. Vibe Remote therefore writes
+// API-key auth into that file directly; ``v2config`` only appears for
+// legacy installs that have not yet been migrated by the next save.
export type ClaudeApiKeySource = 'v2config' | 'settings_json' | null;
export type ClaudeAuthState = {
@@ -466,6 +460,32 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return res.json();
};
+ const sleep = (ms: number) => new Promise((resolve) => window.setTimeout(resolve, ms));
+
+ const startAndPollAgentInstall = async (name: string): Promise<InstallResult> => {
+ const started = await postJson(`/agent/${encodeURIComponent(name)}/install`, {});
+ const jobId = typeof started?.job_id === 'string' ? started.job_id : null;
+ if (!jobId) return started;
+
+ const deadline = Date.now() + 310_000;
+ let last = started;
+ while (Date.now() < deadline) {
+ await sleep(1000);
+ last = await getJson(
+ `/agent/${encodeURIComponent(name)}/install/${encodeURIComponent(jobId)}`,
+ );
+ if (last?.status === 'succeeded' || last?.status === 'failed') {
+ return last;
+ }
+ }
+ return {
+ ...last,
+ ok: false,
+ status: 'failed',
+ message: last?.message || t('backendLifecycle.upgradeFailed'),
+ };
+ };
+
// ``useMemo`` is load-bearing here, not a perf tweak. Without it,
// ``ApiProvider`` produces a fresh ``value`` object on every render
// — including the renders triggered by ToastProvider's state
@@ -505,7 +525,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
deleteBindCode: (code) => apiFetch(`/api/bind-codes/${encodeURIComponent(code)}`, { method: 'DELETE' }).then(r => r.json()),
getFirstBindCode: () => getJson('/api/setup/first-bind-code'),
detectCli: (binary) => getJson(`/cli/detect?binary=${encodeURIComponent(binary)}`),
- installAgent: (name) => postJson(`/agent/${encodeURIComponent(name)}/install`, {}),
+ installAgent: (name) => startAndPollAgentInstall(name),
getBackendRuntime: (name) => getJson(`/backend/${encodeURIComponent(name)}/runtime`),
restartBackend: (name) => postJson(`/backend/${encodeURIComponent(name)}/restart`, {}),
getCodexAuth: () => getJson('/backend/codex/auth'),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 335f86982..b755ed9ed 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -145,7 +145,7 @@
"claudeAuthModeOauth": "Sign in with Claude",
"claudeAuthModeOauthHint": "Use your Anthropic account to authorize Claude Code. Vibe Remote stops managing the API key while this is selected.",
"claudeAuthModeApiKey": "Anthropic API key",
- "claudeAuthModeApiKeyHint": "Vibe Remote injects this key into Claude Code via `ANTHROPIC_API_KEY` at launch. Switch to Claude sign-in if you prefer not to manage a key here.",
+ "claudeAuthModeApiKeyHint": "Saving updates Claude Code's own `settings.json` env block so the CLI uses this key directly.",
"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.",
@@ -161,9 +161,9 @@
"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.",
"claudeBaseUrlReset": "Reset to default",
- "claudeSettingsConflictTitle": "Claude settings.json overrides this key",
- "claudeSettingsConflictBody": "Claude Code layers `env` blocks from {{path}} on top of inherited environment variables. The `{{var}}` value in that file will win at launch unless you remove or update it.",
- "claudeInfoHint": "Saving here writes the key into Vibe Remote's V2 config so Claude Code receives it as `ANTHROPIC_API_KEY` (or `ANTHROPIC_AUTH_TOKEN`) on the next request. Claude restarts per request, so no daemon restart is needed.",
+ "claudeSettingsConflictTitle": "Legacy Vibe Remote key will be migrated",
+ "claudeSettingsConflictBody": "Saving updates `{{var}}` in {{path}} and clears the old Vibe Remote copy.",
+ "claudeInfoHint": "Saving here writes Claude Code's `settings.json` env values. Claude relaunches per request, so no Vibe Remote restart is needed.",
"claudeSave": "Save Claude auth",
"claudeSaving": "Saving…",
"claudeSaveSuccess": "Claude auth saved",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 401c1b4cc..85531c69b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -145,7 +145,7 @@
"claudeAuthModeOauth": "Claude 账号登录",
"claudeAuthModeOauthHint": "使用 Anthropic 账号授权 Claude Code。选中此项后,Vibe Remote 不再管理 API Key。",
"claudeAuthModeApiKey": "Anthropic API Key",
- "claudeAuthModeApiKeyHint": "Vibe Remote 会在每次启动 Claude Code 时通过 `ANTHROPIC_API_KEY` 注入下方的 Key。若不想在此处管理 Key,可切换到 Claude 账号登录。",
+ "claudeAuthModeApiKeyHint": "保存后会直接更新 Claude Code 自己的 `settings.json` env 配置,CLI 会使用这里的 Key。",
"claudeOauthSignedIn": "Claude 已登录。",
"claudeOauthPanelTitle": "使用 Anthropic 账号登录",
"claudeOauthPanelSubtitle": "打开下方授权链接、批准访问,然后粘贴 Anthropic 返回给你的回调码。",
@@ -161,9 +161,9 @@
"claudeBaseUrlPlaceholder": "https://api.anthropic.com",
"claudeBaseUrlHint": "留空则使用 Anthropic 默认地址;兼容中转(如 Bedrock 代理、AWS Endpoint)可在此填写自定义地址。",
"claudeBaseUrlReset": "恢复默认",
- "claudeSettingsConflictTitle": "Claude settings.json 中的 env 会覆盖此处保存的 Key",
- "claudeSettingsConflictBody": "Claude Code 启动时会把 {{path}} 中的 `env` 块叠加到继承到的环境变量之上,文件内 `{{var}}` 的值会优先生效,除非你删除或更新它。",
- "claudeInfoHint": "保存后会写入 Vibe Remote 的 V2 配置,下次请求时通过 `ANTHROPIC_API_KEY`(或 `ANTHROPIC_AUTH_TOKEN`)传给 Claude Code。Claude 每次请求独立启动,无需重启常驻进程。",
+ "claudeSettingsConflictTitle": "旧的 Vibe Remote Key 将被迁移",
+ "claudeSettingsConflictBody": "保存会更新 {{path}} 里的 `{{var}}`,并清除旧的 Vibe Remote 副本。",
+ "claudeInfoHint": "保存后会写入 Claude Code 的 `settings.json` env 配置。Claude 每次请求独立启动,无需重启 Vibe Remote。",
"claudeSave": "保存 Claude 认证",
"claudeSaving": "保存中…",
"claudeSaveSuccess": "Claude 认证已保存",
diff --git a/vibe/api.py b/vibe/api.py
index 4d24cdc0e..d34b8a877 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -52,6 +52,7 @@ from modules.agents.catalog import (
supports_web_oauth,
)
from modules.agents.subagent_router import list_codex_subagents
+from core.process_isolation import isolated_subprocess_kwargs, signal_process_tree, KILL_SIGNAL
logger = logging.getLogger(__name__)
@@ -1601,6 +1602,114 @@ def claude_models() -> dict:
return {"ok": True, "models": options, "reasoning_options": reasoning_options}
+_AGENT_INSTALL_JOB_LOCK = threading.Lock()
+_AGENT_INSTALL_JOBS: dict[str, dict] = {}
+_AGENT_INSTALL_LATEST_BY_BACKEND: dict[str, str] = {}
+_AGENT_INSTALL_JOB_TTL_SECONDS = 3600.0
+
+
+def _prune_agent_install_jobs(now: float | None = None) -> None:
+ timestamp = now or time.time()
+ stale = [
+ job_id
+ for job_id, job in _AGENT_INSTALL_JOBS.items()
+ if job.get("finished_at") and timestamp - float(job.get("finished_at") or 0) > _AGENT_INSTALL_JOB_TTL_SECONDS
+ ]
+ for job_id in stale:
+ job = _AGENT_INSTALL_JOBS.pop(job_id, None)
+ backend = job.get("backend") if isinstance(job, dict) else None
+ if isinstance(backend, str) and _AGENT_INSTALL_LATEST_BY_BACKEND.get(backend) == job_id:
+ _AGENT_INSTALL_LATEST_BY_BACKEND.pop(backend, None)
+
+
+def start_agent_install_job(name: str) -> dict:
+ """Start backend CLI install/upgrade in a background job.
+
+ The UI request path must not run package-manager subprocesses directly:
+ npm/curl/brew can hang or take minutes, and backend CLI failures should
+ not affect the Vibe Remote main service. The worker still uses the same
+ install/upgrade implementation as the CLI card used before; only the
+ execution boundary changes.
+ """
+ if not is_agent_backend(name):
+ return {"ok": False, "message": f"Unknown agent: {name}"}
+
+ job_id = uuid.uuid4().hex
+ now = time.time()
+ job = {
+ "ok": True,
+ "job_id": job_id,
+ "backend": name,
+ "status": "running",
+ "message": "Upgrade started",
+ "output": "",
+ "path": None,
+ "started_at": now,
+ "finished_at": None,
+ }
+ with _AGENT_INSTALL_JOB_LOCK:
+ _prune_agent_install_jobs(now)
+ _AGENT_INSTALL_JOBS[job_id] = job
+ _AGENT_INSTALL_LATEST_BY_BACKEND[name] = job_id
+
+ def _worker() -> None:
+ try:
+ result = install_agent(name)
+ if result.get("ok") and name != "claude" and supports_runtime_refresh(name):
+ try:
+ result["restart"] = restart_backend(name)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "Backend refresh after %s install job failed: %s",
+ name,
+ exc,
+ )
+ result["restart"] = {"ok": False, "message": str(exc)}
+ ok = bool(result.get("ok"))
+ status = "succeeded" if ok else "failed"
+ with _AGENT_INSTALL_JOB_LOCK:
+ current = _AGENT_INSTALL_JOBS.get(job_id)
+ if current is not None:
+ current.update(result)
+ current["ok"] = ok
+ current["status"] = status
+ current["finished_at"] = time.time()
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Agent install job failed for %s: %s", name, exc, exc_info=True)
+ with _AGENT_INSTALL_JOB_LOCK:
+ current = _AGENT_INSTALL_JOBS.get(job_id)
+ if current is not None:
+ current.update(
+ {
+ "ok": False,
+ "status": "failed",
+ "message": str(exc),
+ "output": None,
+ "finished_at": time.time(),
+ }
+ )
+
+ threading.Thread(
+ target=_worker,
+ daemon=True,
+ name=f"vibe-agent-install-{name}-{job_id[:8]}",
+ ).start()
+ return dict(job)
+
+
+def get_agent_install_job(job_id: str | None = None, *, backend: str | None = None) -> dict:
+ """Return the latest state for a background backend install job."""
+ with _AGENT_INSTALL_JOB_LOCK:
+ _prune_agent_install_jobs()
+ resolved_job_id = (job_id or "").strip()
+ if not resolved_job_id and backend:
+ resolved_job_id = _AGENT_INSTALL_LATEST_BY_BACKEND.get(backend.strip()) or ""
+ job = _AGENT_INSTALL_JOBS.get(resolved_job_id)
+ if not job:
+ return {"ok": False, "error": "job_not_found"}
+ return dict(job)
+
+
def install_agent(name: str) -> dict:
"""Install (or upgrade) an agent CLI tool.
@@ -1744,13 +1853,24 @@ def _run_install_command(
try:
logger.info("%s agent %s with command: %s", label, name, cmd)
command_env = _command_env_for(cmd[0] if cmd and os.path.isabs(cmd[0]) else None)
- result = subprocess.run(
+ process = subprocess.Popen(
cmd,
- capture_output=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
text=True,
- timeout=300, # 5 minute timeout
env=command_env,
+ **isolated_subprocess_kwargs(),
)
+ try:
+ stdout, stderr = process.communicate(timeout=300) # 5 minute timeout
+ except subprocess.TimeoutExpired:
+ logger.error("Agent %s %s timed out", name, mode)
+ signal_process_tree(process, KILL_SIGNAL, logger, f"{name} {mode}")
+ stdout, stderr = process.communicate(timeout=10)
+ output = (stdout or "") + ("\n" + stderr if stderr else "")
+ output = truncate_output(output.strip())
+ return {"ok": False, "message": f"{mode.capitalize()} timed out", "output": output or None}
+ result = subprocess.CompletedProcess(cmd, process.returncode, stdout, stderr)
output = result.stdout + ("\n" + result.stderr if result.stderr else "")
output = truncate_output(output.strip())
if result.returncode == 0:
@@ -1812,9 +1932,6 @@ def _run_install_command(
"message": f"{mode.capitalize()} failed (exit code {result.returncode})",
"output": output,
}
- except subprocess.TimeoutExpired:
- logger.error("Agent %s %s timed out", name, mode)
- return {"ok": False, "message": f"{mode.capitalize()} timed out", "output": None}
except Exception as e:
logger.error("Agent %s %s error: %s", name, mode, e)
return {"ok": False, "message": str(e), "output": None}
@@ -2590,11 +2707,10 @@ def remove_backend_api_key(backend: str) -> dict:
``agents.codex.api_key`` is also cleared and ``auth_mode`` is
flipped to ``oauth``. Triggers ``restart_backend('codex')`` so
the persistent daemon reloads.
- - **Claude**: V2Config is the sole writer; we clear
- ``agents.claude.api_key`` + ``base_url`` and flip ``auth_mode``
- to ``oauth``. ``~/.claude/credentials.json`` (the OAuth token
- file) is left alone. No daemon to restart — Claude relaunches
- per request.
+ - **Claude**: remove Anthropic env overrides from Claude's
+ ``settings.json``, clear legacy V2Config ``api_key`` / ``base_url``
+ cache fields, and flip ``auth_mode`` to ``oauth``.
+ ``~/.claude/credentials.json`` (the OAuth token file) is left alone.
"""
backend = (backend or "").strip().lower()
if backend not in {"claude", "codex"}:
@@ -2613,6 +2729,14 @@ def remove_backend_api_key(backend: str) -> dict:
except Exception as exc: # noqa: BLE001
logger.error("apply_codex_auth(oauth) during remove-key failed: %s", exc, exc_info=True)
return {"ok": False, "error": "remove_failed", "detail": str(exc)}
+ elif backend == "claude":
+ from vibe.claude_config import apply_claude_auth
+
+ try:
+ apply_claude_auth(auth_mode="oauth", api_key=None, base_url=None)
+ except Exception as exc: # noqa: BLE001
+ logger.error("apply_claude_auth(oauth) during remove-key failed: %s", exc, exc_info=True)
+ return {"ok": False, "error": "remove_failed", "detail": str(exc)}
# Clear V2Config api_key for both backends.
try:
@@ -2941,20 +3065,17 @@ def get_claude_auth() -> dict:
Claude differs from Codex in two structural ways:
- 1. We never write to ``~/.claude/settings.json``. V2Config is the sole
- writer; the Claude CLI subprocess inherits ``ANTHROPIC_*`` vars
- from the env we set in ``session_handler.py`` at launch time.
+ 1. ``~/.claude/settings.json`` is the source of truth for API-key
+ env overrides because Claude Code layers that file on top of the
+ inherited process env at launch.
2. OAuth tokens minted by ``claude login`` live in the OS keychain,
which we cannot portably inspect. The "OAuth signed in" signal is
therefore inferred from "no API key is configured" — the UI shows
a hint pointing users at ``claude login`` if they need to switch.
- We still inspect ``settings.json`` because the user (or their tooling)
- may have put ``ANTHROPIC_AUTH_TOKEN`` / ``ANTHROPIC_BASE_URL`` there.
- When that happens *and* V2Config also has a key, settings.json wins
- at launch (Claude Code applies its ``env`` block on top of inherited
- env). The UI surfaces a warning so users aren't confused by stale
- keys silently overriding what they just saved.
+ Legacy V2Config keys are read only as a migration fallback so old
+ installs still render their current state before the next save moves
+ the key into Claude's own settings file.
"""
from vibe.claude_config import (
read_claude_auth_state,
@@ -2982,14 +3103,10 @@ def get_claude_auth() -> dict:
configured_key = configured_key.strip() if isinstance(configured_key, str) else ""
configured_base = configured_base.strip() if isinstance(configured_base, str) else ""
- # Effective values surface to the UI. V2Config wins when populated
- # (that's what we'd write next), else fall back to whatever the
- # running CLI actually inherits from ``settings.json``. This is the
- # difference between "no key configured" (truly empty) and "key lives
- # in settings.json from a hand-edit or older tool" (looks empty in
- # V2Config but actually drives the live CLI).
- effective_key = configured_key or settings_key
- effective_base = configured_base or settings_base
+ # settings.json wins: it is the file Claude Code itself layers on top
+ # of inherited env. V2Config is a legacy fallback only.
+ effective_key = settings_key or configured_key
+ effective_base = settings_base or configured_base
has_api_key = bool(effective_key)
if configured_mode in _VALID_AUTH_MODES:
@@ -2999,12 +3116,7 @@ def get_claude_auth() -> dict:
else:
auth_mode = "oauth"
- # ``settings_conflict`` keeps the original meaning: BOTH V2Config and
- # settings.json have a key, in which case settings.json wins at launch
- # (Claude Code layers ``env`` on top of inherited env). The new
- # "settings.json is sole source" case is not a conflict — it's just
- # the effective value and we now render it instead of blanking out.
- settings_conflict = bool(disk_state.get("settings_env_has_key")) and bool(configured_key)
+ settings_conflict = False
# ``active_auth_mode`` reflects what the running CLI is actually using
# at launch.
@@ -3022,10 +3134,10 @@ def get_claude_auth() -> dict:
# Which storage the live API key came from — helps the UI explain the
# state ("Key configured in settings.json"). Plaintext never leaves
# the server; only the mask is forwarded.
- if configured_key:
- api_key_source = "v2config"
- elif settings_key:
+ if settings_key:
api_key_source = "settings_json"
+ elif configured_key:
+ api_key_source = "v2config"
else:
api_key_source = None
@@ -3050,12 +3162,11 @@ def get_claude_auth() -> dict:
def save_claude_auth(payload: dict) -> dict:
- """Persist Claude auth into V2Config.
+ """Persist Claude auth into Claude Code's own ``settings.json``.
- No disk writes — V2Config is the source of truth and
- ``session_handler.py`` injects the resulting env vars at each
- one-shot CLI launch. Claude is a per-request subprocess so there is
- no daemon to restart; the *next* user message picks up the change.
+ V2Config records only non-secret intent/legacy cleanup state. It must
+ not carry the API key because Claude Code's ``settings.json`` env block
+ wins 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
@@ -3086,29 +3197,71 @@ 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 stored key for base-URL-only updates. Unlike Codex we
- # have no live-disk fallback (V2Config is sole writer), so we
- # only consult ``settings.json`` for legacy installs where the
- # user pre-configured the relay there and never re-typed the
- # secret into the Settings UI.
+ # 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.
+ try:
+ from vibe.claude_config import (
+ read_claude_api_key_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
+ except Exception:
+ api_key = None
+ settings_auth_token = None
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:
- api_key = None
- if not api_key:
- try:
- from vibe.claude_config import read_claude_api_key_from_settings
-
- api_key = read_claude_api_key_from_settings()
+ api_key = api_key or getattr(stored, "api_key", None) or None
except Exception:
- api_key = None
- if not api_key:
+ pass
+ if not api_key and not settings_auth_token:
return {"ok": False, "message": "api_key is required when auth_mode='api_key'"}
+ effective_base_url = base_url_change if base_url_present else None
+ if 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()
+ else:
+ with CONFIG_LOCK:
+ try:
+ existing = load_config()
+ stored = getattr(getattr(existing, "agents", None), "claude", None)
+ effective_base_url = getattr(stored, "base_url", None) or None
+ except Exception:
+ effective_base_url = None
+
+ from vibe.claude_config import apply_claude_auth
+
+ try:
+ apply_claude_auth(
+ auth_mode=auth_mode,
+ api_key=api_key if auth_mode == "api_key" else None,
+ base_url=effective_base_url if auth_mode == "api_key" else None,
+ auth_token=settings_auth_token if auth_mode == "api_key" else None,
+ )
+ except ValueError as exc:
+ return {"ok": False, "message": str(exc)}
+ except OSError as exc:
+ logger.error("Failed to write Claude settings.json: %s", exc, exc_info=True)
+ return {"ok": False, "message": f"Failed to write Claude settings: {exc}"}
+
with CONFIG_LOCK:
try:
config = load_config()
@@ -3121,21 +3274,10 @@ def save_claude_auth(payload: dict) -> dict:
# have never been through this save path keep the flag at its
# ``False`` default and continue to inherit shell env vars.
config.agents.claude.auth_mode_set = True
- config.agents.claude.api_key = api_key if auth_mode == "api_key" else None
- if base_url_present:
- config.agents.claude.base_url = base_url_change
- elif auth_mode == "oauth":
- # Switching to OAuth: drop any stored relay base_url even when
- # the UI omitted the field (the OAuth tab hides it). Without
- # this, ``build_claude_subprocess_env`` keeps exporting
- # ``ANTHROPIC_BASE_URL`` on every launch, so OAuth traffic
- # gets routed through the api-key-only relay and is rejected
- # with 401 — same root pattern as the Codex relay-pointer fix
- # in ``apply_codex_auth`` (commit 28efd8b).
- config.agents.claude.base_url = None
- # else: keep whatever is already stored (omitted payload key) for
- # the api_key branch — the user may be doing a key-only update
- # against a previously-saved relay.
+ # Secrets and endpoint overrides live in Claude's own settings.json.
+ # Clear legacy cache fields so future reads do not have two writers.
+ config.agents.claude.api_key = None
+ config.agents.claude.base_url = None
config.save()
# Claude is one-shot per request — no daemon to restart. Return a
diff --git a/vibe/claude_config.py b/vibe/claude_config.py
index 6edca409b..c876cf5f9 100644
--- a/vibe/claude_config.py
+++ b/vibe/claude_config.py
@@ -1,24 +1,16 @@
-"""Helpers for inspecting Claude Code's on-disk configuration.
+"""Helpers for reading and writing Claude Code's on-disk configuration.
-Unlike Codex, Claude Code's API-key auth is realized purely via environment
-variables — the Anthropic SDK honors ``ANTHROPIC_API_KEY`` (or
-``ANTHROPIC_AUTH_TOKEN`` for relay setups) and ``ANTHROPIC_BASE_URL`` at
-invocation time. ``core/handlers/session_handler.py`` already injects these
-from ``V2Config.agents.claude`` before each one-shot CLI launch.
+Claude Code applies the ``env`` block in ``~/.claude/settings.json`` when it
+launches, and that block wins over inherited process environment. Vibe Remote
+therefore treats that file as the source of truth for Claude API-key auth
+instead of storing secrets in V2Config and hoping env injection wins.
-That means V2Config is our sole *writer*; we do **not** mutate
-``~/.claude/settings.json``. But the Claude CLI itself reads that file at
-launch and applies its ``env`` block on top of the inherited env — so a
-hand-edited ``env.ANTHROPIC_AUTH_TOKEN`` there will override whatever we
-just injected. The Settings UI needs to surface that conflict instead of
-silently letting the user save a value that won't take effect.
+This module owns the narrow settings.json mutation surface:
-This module is therefore read-only:
-
-- ``read_claude_settings_env(...)`` returns whichever ``ANTHROPIC_*`` keys
- are present in ``~/.claude/settings.json`` so the UI can warn the user.
-- ``read_claude_auth_state(...)`` rolls that up into the user-visible
- shape consumed by ``vibe.api.get_claude_auth``.
+- ``apply_claude_auth(...)`` upserts or removes Anthropic env vars in
+ ``settings.json``.
+- ``read_claude_settings_env(...)`` reports the live on-disk state without
+ leaking secrets beyond the current process.
OAuth tokens minted by ``claude login`` live in the macOS keychain (or
the OS-specific equivalent), not on disk. We have no portable way to
@@ -124,6 +116,74 @@ def _load_settings(path: Path) -> Dict[str, Any]:
return {}
+def _atomic_write(path: Path, content: str, *, mode: int = 0o600) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(path.suffix + ".tmp")
+ tmp.write_text(content, encoding="utf-8")
+ try:
+ os.replace(tmp, path)
+ finally:
+ if tmp.exists():
+ try:
+ tmp.unlink()
+ except OSError: # pragma: no cover - best effort cleanup
+ pass
+ try:
+ path.chmod(mode)
+ except OSError as exc: # pragma: no cover - non-POSIX
+ logger.debug("chmod %s failed: %s", path, exc)
+
+
+def apply_claude_auth(
+ *,
+ auth_mode: str,
+ api_key: Optional[str],
+ base_url: Optional[str],
+ auth_token: Optional[str] = None,
+ home: Path | None = None,
+) -> Dict[str, Any]:
+ """Persist Claude auth into ``settings.json``.
+
+ ``api_key`` mode writes ``env.ANTHROPIC_API_KEY`` and removes
+ ``ANTHROPIC_AUTH_TOKEN`` so header semantics cannot conflict. ``oauth``
+ mode removes all Anthropic credential/base-url overrides from the env
+ block and leaves Claude's OAuth credentials untouched.
+ """
+ if auth_mode not in {"oauth", "api_key"}:
+ raise ValueError(f"Unsupported claude auth_mode: {auth_mode!r}")
+ if auth_mode == "api_key" and not (api_key or auth_token):
+ raise ValueError("api_key is required when auth_mode='api_key'")
+
+ path = get_claude_settings_path(home)
+ settings = _load_settings(path)
+ if not isinstance(settings, dict):
+ settings = {}
+ env_block = settings.setdefault("env", {})
+ if not isinstance(env_block, dict):
+ env_block = {}
+ settings["env"] = env_block
+
+ if auth_mode == "api_key":
+ if api_key:
+ env_block["ANTHROPIC_API_KEY"] = api_key.strip()
+ env_block.pop("ANTHROPIC_AUTH_TOKEN", None)
+ elif auth_token:
+ env_block["ANTHROPIC_AUTH_TOKEN"] = auth_token.strip()
+ env_block.pop("ANTHROPIC_API_KEY", None)
+ if base_url:
+ env_block["ANTHROPIC_BASE_URL"] = base_url.strip()
+ else:
+ env_block.pop("ANTHROPIC_BASE_URL", None)
+ else:
+ for key in RELEVANT_ENV_KEYS:
+ env_block.pop(key, None)
+ if not env_block:
+ settings.pop("env", None)
+
+ _atomic_write(path, json.dumps(settings, indent=2) + "\n", mode=0o600)
+ return {"settings_path": str(path)}
+
+
def read_claude_settings_env(home: Path | None = None) -> Dict[str, str]:
"""Extract Anthropic-relevant env vars from ``~/.claude/settings.json``.
@@ -210,8 +270,9 @@ def build_claude_subprocess_env(
Both ``core/handlers/session_handler.py`` (one-shot CLI launches) and
``core/agent_auth_service.py`` (control-channel SDK clients) need the
same Anthropic/Claude env composition: inherit relevant vars from the
- parent process, then let V2Config's ``auth_mode`` / ``api_key`` /
- ``base_url`` overrides win.
+ parent process, then let explicit V2Config intent decide whether to
+ strip stale inherited vars. API-key material itself now comes from
+ Claude's own ``settings.json``; V2Config keys are legacy fallback only.
The ``auth_mode`` toggle is the load-bearing piece — if a user picks
OAuth in Settings but their shell exports ``ANTHROPIC_API_KEY``, the
@@ -246,6 +307,10 @@ def build_claude_subprocess_env(
auth_mode = getattr(claude_cfg, "auth_mode", "oauth") if claude_cfg is not None else "oauth"
configured_key_raw = (getattr(claude_cfg, "api_key", None) or "").strip() if claude_cfg is not None else ""
configured_base = (getattr(claude_cfg, "base_url", None) or "").strip() if claude_cfg is not None else ""
+ settings_env = read_claude_settings_env()
+ settings_api_key = settings_env.get("ANTHROPIC_API_KEY") or ""
+ settings_auth_token = settings_env.get("ANTHROPIC_AUTH_TOKEN") or ""
+ settings_base = settings_env.get("ANTHROPIC_BASE_URL") or ""
# ``auth_mode_set`` is False on V2 configs that predate the Settings
# → Backends → Claude page (or that the user has simply never
# opened). On those installs the user is running on shell-exported
@@ -272,13 +337,22 @@ def build_claude_subprocess_env(
claude_env.pop("ANTHROPIC_BASE_URL", None)
# else: legacy install — preserve inherited env vars verbatim.
elif auth_mode == "api_key":
- if configured_key_raw:
+ if auth_mode_set:
+ claude_env.pop("ANTHROPIC_API_KEY", None)
+ claude_env.pop("ANTHROPIC_AUTH_TOKEN", None)
+ claude_env.pop("ANTHROPIC_BASE_URL", None)
+ if settings_api_key:
+ claude_env["ANTHROPIC_API_KEY"] = settings_api_key
+ claude_env.pop("ANTHROPIC_AUTH_TOKEN", None)
+ elif settings_auth_token:
+ claude_env["ANTHROPIC_AUTH_TOKEN"] = settings_auth_token
+ claude_env.pop("ANTHROPIC_API_KEY", None)
+ elif configured_key_raw:
claude_env["ANTHROPIC_API_KEY"] = configured_key_raw
- # When we set an explicit API key, drop any inherited bearer
- # token so the SDK can't pick the wrong Authorization header.
claude_env.pop("ANTHROPIC_AUTH_TOKEN", None)
- if configured_base:
- claude_env["ANTHROPIC_BASE_URL"] = configured_base
+ effective_base = settings_base or configured_base
+ if effective_base and auth_mode != "oauth":
+ claude_env["ANTHROPIC_BASE_URL"] = effective_base
return claude_env
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index e307e1c60..c30327677 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1836,10 +1836,23 @@ def agent_install(name):
from vibe import api
- result = api.install_agent(name)
+ result = api.start_agent_install_job(name)
return jsonify(result)
[email protected]("/agent/<name>/install/<job_id>", methods=["GET"])
+def agent_install_status(name, job_id):
+ """Poll a background agent CLI install/upgrade job."""
+ if name not in _ALLOWED_BACKENDS:
+ return jsonify({"ok": False, "message": f"Unknown agent: {name}"}), 400
+
+ from vibe import api
+
+ result = api.get_agent_install_job(job_id, backend=name)
+ status = 404 if not result.get("ok") and result.get("error") == "job_not_found" else 200
+ return jsonify(result), status
+
+
_ALLOWED_BACKENDS = set(AGENT_BACKENDS)