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): centralize Claude env composition + persist OpenCode baseURL

cyh5673d75687e2
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 11b23c6ad..fde7240df 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -639,10 +639,13 @@ class AgentAuthService:
if not os.path.exists(working_path):
os.makedirs(working_path, exist_ok=True)
- claude_env = {}
- for key in os.environ:
- if key.startswith("ANTHROPIC_") or key.startswith("CLAUDE_"):
- claude_env[key] = os.environ[key]
+ # Reuse the session-handler env composition so the auth_mode /
+ # api_key / base_url overrides apply uniformly. Without this, an
+ # OAuth-mode user with ``ANTHROPIC_API_KEY`` in their shell would
+ # still get the key into the control-channel SDK client.
+ from vibe.claude_config import build_claude_subprocess_env
+
+ claude_env = build_claude_subprocess_env(getattr(self.controller.config, "claude", None))
should_force_sandbox = getattr(session_handler, "_should_force_claude_sandbox", None)
if callable(should_force_sandbox) and should_force_sandbox():
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index de296bc33..8bb5fdb7e 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -559,24 +559,12 @@ class SessionHandler(BaseHandler):
if len(claude_stderr_lines) > 40:
del claude_stderr_lines[:-40]
- # Collect Anthropic-related environment variables to pass to Claude
- claude_env = {}
- for key in os.environ:
- if key.startswith("ANTHROPIC_") or key.startswith("CLAUDE_"):
- claude_env[key] = os.environ[key]
- # V2Config-driven overrides win over ambient shell env: the user
- # opted in to these via Settings → Backends, so they should beat a
- # stale ``ANTHROPIC_API_KEY`` exported in the parent shell.
- claude_cfg = getattr(self.config, "claude", None)
- if claude_cfg is not None:
- auth_mode = getattr(claude_cfg, "auth_mode", "oauth")
- if auth_mode == "api_key":
- configured_key = (getattr(claude_cfg, "api_key", None) or "").strip()
- if configured_key:
- claude_env["ANTHROPIC_API_KEY"] = configured_key
- configured_base = (getattr(claude_cfg, "base_url", None) or "").strip()
- if configured_base:
- claude_env["ANTHROPIC_BASE_URL"] = configured_base
+ # V2Config-driven Anthropic env composition, centralised so the
+ # control-channel client (``agent_auth_service``) cannot drift
+ # away from this site's auth_mode handling.
+ from vibe.claude_config import build_claude_subprocess_env
+
+ claude_env = build_claude_subprocess_env(getattr(self.config, "claude", None))
if self._should_force_claude_sandbox():
claude_env["IS_SANDBOX"] = "1"
logger.info("Detected Claude bypassPermissions running as root; forcing IS_SANDBOX=1 for Claude subprocess")
diff --git a/tests/test_claude_subprocess_env.py b/tests/test_claude_subprocess_env.py
new file mode 100644
index 000000000..15be8732a
--- /dev/null
+++ b/tests/test_claude_subprocess_env.py
@@ -0,0 +1,122 @@
+"""Unit tests for ``build_claude_subprocess_env``.
+
+This helper centralises the Anthropic / Claude env composition for both
+the one-shot CLI launch path (``core/handlers/session_handler.py``) and
+the control-channel SDK client path (``core/agent_auth_service.py``).
+
+Without this single source of truth, a future env-injection site can
+silently drift back into the bug Codex flagged in PR #282 round 3:
+``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` leaking through even
+though the user picked ``auth_mode = oauth`` in Settings.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from vibe.claude_config import build_claude_subprocess_env
+
+
+def _cfg(**kwargs) -> SimpleNamespace:
+ """Build the minimal duck-typed V2Config.claude block the helper reads."""
+ return SimpleNamespace(**kwargs)
+
+
+def test_oauth_strips_inherited_api_key_and_auth_token() -> None:
+ env = {
+ "ANTHROPIC_API_KEY": "sk-leaked",
+ "ANTHROPIC_AUTH_TOKEN": "bearer-leaked",
+ "ANTHROPIC_BASE_URL": "https://shell.example",
+ "CLAUDE_CONFIG_DIR": "/keep",
+ "PATH": "/dropped",
+ }
+ out = build_claude_subprocess_env(_cfg(auth_mode="oauth"), 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 out["CLAUDE_CONFIG_DIR"] == "/keep"
+ assert "PATH" not in out
+
+
+def test_api_key_mode_injects_configured_key_and_drops_bearer() -> None:
+ env = {
+ "ANTHROPIC_API_KEY": "sk-stale",
+ "ANTHROPIC_AUTH_TOKEN": "bearer-stale",
+ }
+ out = build_claude_subprocess_env(
+ _cfg(auth_mode="api_key", api_key="sk-new"),
+ base_env=env,
+ )
+ assert out["ANTHROPIC_API_KEY"] == "sk-new"
+ # An explicit api_key + an inherited AUTH_TOKEN would let the SDK
+ # pick the wrong Authorization header; the helper must drop the
+ # token so the api_key wins unambiguously.
+ assert "ANTHROPIC_AUTH_TOKEN" not in out
+
+
+def test_api_key_mode_without_configured_key_keeps_inherited() -> None:
+ # 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.
+ env = {"ANTHROPIC_API_KEY": "sk-from-shell"}
+ out = build_claude_subprocess_env(
+ _cfg(auth_mode="api_key", api_key=""),
+ base_env=env,
+ )
+ assert out["ANTHROPIC_API_KEY"] == "sk-from-shell"
+
+
+def test_base_url_override_overrides_inherited() -> None:
+ env = {"ANTHROPIC_BASE_URL": "https://shell.example"}
+ out = build_claude_subprocess_env(
+ _cfg(auth_mode="oauth", base_url="https://relay.example/v1"),
+ base_env=env,
+ )
+ assert out["ANTHROPIC_BASE_URL"] == "https://relay.example/v1"
+
+
+def test_base_url_blank_does_not_override_inherited() -> None:
+ env = {"ANTHROPIC_BASE_URL": "https://shell.example"}
+ out = build_claude_subprocess_env(
+ _cfg(auth_mode="oauth", base_url=" "),
+ base_env=env,
+ )
+ assert out["ANTHROPIC_BASE_URL"] == "https://shell.example"
+
+
+def test_no_config_returns_inherited_subset() -> None:
+ env = {
+ "ANTHROPIC_API_KEY": "sk-shell",
+ "CLAUDE_CONFIG_DIR": "/dir",
+ "PATH": "/skip",
+ }
+ out = build_claude_subprocess_env(None, base_env=env)
+ assert out == {
+ "ANTHROPIC_API_KEY": "sk-shell",
+ "CLAUDE_CONFIG_DIR": "/dir",
+ }
+
+
+ "auth_mode",
+ ["", "unknown", None],
+)
+def test_unknown_auth_mode_leaves_inherited_unchanged(auth_mode) -> None:
+ # The helper only acts on the two known modes. Anything else (legacy
+ # configs, future modes, missing field) falls through with the
+ # inherited env preserved — preferable to silently stripping vars on
+ # configs we don't understand.
+ env = {"ANTHROPIC_API_KEY": "sk-shell", "ANTHROPIC_AUTH_TOKEN": "bearer"}
+ out = build_claude_subprocess_env(_cfg(auth_mode=auth_mode), base_env=env)
+ assert out["ANTHROPIC_API_KEY"] == "sk-shell"
+ assert out["ANTHROPIC_AUTH_TOKEN"] == "bearer"
+
+
+def test_oauth_with_no_inherited_keys_returns_clean_env() -> None:
+ env = {"PATH": "/x"}
+ out = build_claude_subprocess_env(_cfg(auth_mode="oauth"), base_env=env)
+ assert out == {}
diff --git a/tests/test_opencode_provider_base_url.py b/tests/test_opencode_provider_base_url.py
new file mode 100644
index 000000000..a1bff069d
--- /dev/null
+++ b/tests/test_opencode_provider_base_url.py
@@ -0,0 +1,154 @@
+"""Unit tests for the OpenCode provider ``baseURL`` config helpers.
+
+The Settings → Backends → OpenCode page exposes a Base URL input per
+provider; without these helpers the input is a no-op because OpenCode's
+own ``PUT /auth/{provider_id}`` endpoint has no field for it. These
+tests pin the round-trip (upsert → read → remove) and the prune
+behaviour so a future refactor cannot silently regress the UI back into
+"save success, value lost on reload" — the bug Codex flagged in
+``PR #282`` round 3.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from vibe.opencode_config import (
+ get_opencode_config_paths,
+ read_opencode_provider_base_url,
+ remove_opencode_provider_base_url,
+ upsert_opencode_provider_base_url,
+ upsert_opencode_provider_api_key,
+)
+
+
+def _read_config(path: Path) -> dict:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def test_upsert_base_url_writes_canonical_path(tmp_path: Path) -> None:
+ target = upsert_opencode_provider_base_url(
+ "openai",
+ "https://ai-relay.example/v1",
+ home=tmp_path,
+ )
+ assert target == get_opencode_config_paths(tmp_path)[0]
+ config = _read_config(target)
+ assert config["provider"]["openai"]["options"]["baseURL"] == "https://ai-relay.example/v1"
+ assert config["$schema"] == "https://opencode.ai/config.json"
+
+
+def test_upsert_base_url_coexists_with_api_key(tmp_path: Path) -> None:
+ upsert_opencode_provider_api_key("openai", "sk-xxx", home=tmp_path)
+ upsert_opencode_provider_base_url("openai", "https://gw.example/v1", home=tmp_path)
+ config = _read_config(get_opencode_config_paths(tmp_path)[0])
+ options = config["provider"]["openai"]["options"]
+ assert options["apiKey"] == "sk-xxx"
+ assert options["baseURL"] == "https://gw.example/v1"
+
+
+def test_upsert_base_url_overrides_previous_value(tmp_path: Path) -> None:
+ upsert_opencode_provider_base_url("openai", "https://old.example/v1", home=tmp_path)
+ upsert_opencode_provider_base_url("openai", "https://new.example/v1", home=tmp_path)
+ config = _read_config(get_opencode_config_paths(tmp_path)[0])
+ assert config["provider"]["openai"]["options"]["baseURL"] == "https://new.example/v1"
+
+
+def test_read_base_url_returns_none_when_unset(tmp_path: Path) -> None:
+ # No config file yet → nothing to read.
+ assert read_opencode_provider_base_url("openai", home=tmp_path) is None
+
+ # Config exists but provider does not.
+ upsert_opencode_provider_api_key("anthropic", "sk-anth", home=tmp_path)
+ assert read_opencode_provider_base_url("openai", home=tmp_path) is None
+
+
+def test_read_base_url_returns_persisted_value(tmp_path: Path) -> None:
+ upsert_opencode_provider_base_url(
+ "openai",
+ "https://ai-relay.example/v1",
+ home=tmp_path,
+ )
+ assert (
+ read_opencode_provider_base_url("openai", home=tmp_path)
+ == "https://ai-relay.example/v1"
+ )
+
+
+def test_remove_base_url_prunes_empty_options(tmp_path: Path) -> None:
+ upsert_opencode_provider_base_url("openai", "https://gw.example/v1", home=tmp_path)
+ remove_opencode_provider_base_url("openai", home=tmp_path)
+
+ config = _read_config(get_opencode_config_paths(tmp_path)[0])
+ # With both apiKey and baseURL gone, the provider block prunes
+ # itself; with no provider blocks left, the ``provider`` key is
+ # dropped entirely. The ``$schema`` planted by upsert stays.
+ assert "provider" not in config
+ assert config.get("$schema") == "https://opencode.ai/config.json"
+
+
+def test_remove_base_url_preserves_api_key(tmp_path: Path) -> None:
+ upsert_opencode_provider_api_key("openai", "sk-xxx", home=tmp_path)
+ upsert_opencode_provider_base_url("openai", "https://gw.example/v1", home=tmp_path)
+ remove_opencode_provider_base_url("openai", home=tmp_path)
+
+ config = _read_config(get_opencode_config_paths(tmp_path)[0])
+ options = config["provider"]["openai"]["options"]
+ assert options == {"apiKey": "sk-xxx"}
+
+
+def test_remove_base_url_is_idempotent(tmp_path: Path) -> None:
+ upsert_opencode_provider_base_url("openai", "https://gw.example/v1", home=tmp_path)
+ remove_opencode_provider_base_url("openai", home=tmp_path)
+ # Second call must be a no-op rather than raise.
+ remove_opencode_provider_base_url("openai", home=tmp_path)
+ assert read_opencode_provider_base_url("openai", home=tmp_path) is None
+
+
+ "base_url_value",
+ [" ", ""],
+)
+def test_read_base_url_ignores_blank_values(tmp_path: Path, base_url_value: str) -> None:
+ # Write a value that contains no useful content; the helper should
+ # treat it as "not configured" so the UI does not show whitespace as
+ # the persisted override.
+ upsert_opencode_provider_base_url("openai", "https://x.example", home=tmp_path)
+ target = get_opencode_config_paths(tmp_path)[0]
+ config = _read_config(target)
+ config["provider"]["openai"]["options"]["baseURL"] = base_url_value
+ target.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
+ assert read_opencode_provider_base_url("openai", home=tmp_path) is None
+
+
+def test_remove_then_reupsert_round_trip(tmp_path: Path) -> None:
+ # Once ``remove`` has pruned the entire ``provider`` block (the only
+ # provider had its last option removed), a subsequent ``upsert`` has
+ # to scaffold the JSON structure back from scratch — exercise that
+ # path so a future refactor doesn't regress to a KeyError.
+ upsert_opencode_provider_base_url("openai", "https://old.example", home=tmp_path)
+ remove_opencode_provider_base_url("openai", home=tmp_path)
+ upsert_opencode_provider_base_url("openai", "https://new.example", home=tmp_path)
+ assert (
+ read_opencode_provider_base_url("openai", home=tmp_path)
+ == "https://new.example"
+ )
+
+
+def test_remove_one_provider_keeps_other_untouched(tmp_path: Path) -> None:
+ upsert_opencode_provider_base_url("openai", "https://a.example", home=tmp_path)
+ upsert_opencode_provider_base_url("anthropic", "https://b.example", home=tmp_path)
+ upsert_opencode_provider_api_key("anthropic", "sk-anth", home=tmp_path)
+
+ remove_opencode_provider_base_url("openai", home=tmp_path)
+
+ config = _read_config(get_opencode_config_paths(tmp_path)[0])
+ assert "openai" not in config.get("provider", {})
+ # Anthropic still has both apiKey and baseURL untouched.
+ assert config["provider"]["anthropic"]["options"] == {
+ "apiKey": "sk-anth",
+ "baseURL": "https://b.example",
+ }
diff --git a/tests/test_save_opencode_provider_auth.py b/tests/test_save_opencode_provider_auth.py
new file mode 100644
index 000000000..1f19b4479
--- /dev/null
+++ b/tests/test_save_opencode_provider_auth.py
@@ -0,0 +1,201 @@
+"""Contract tests for ``save_opencode_provider_auth`` payload parsing.
+
+These pin the three-state semantics for the optional ``base_url`` field
+that Codex flagged in PR #282 round 3:
+
+ * key absent → leave the stored value untouched
+ * key present + blank → clear the stored value
+ * key present + non-blank → upsert (after http(s):// validation)
+
+Without these, re-saving just the API key would silently wipe the
+``baseURL`` override.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any, List, Tuple
+
+import pytest
+
+from vibe import api
+
+
+class _FakeServer:
+ """Stand-in for the OpenCode HTTP daemon used by the save flow.
+
+ The real ``set_api_key_auth`` PUTs to the OpenCode HTTP server; we
+ only need it to succeed so the JSON-write side effects fire.
+ """
+
+ def __init__(self) -> None:
+ self.set_calls: List[Tuple[str, str]] = []
+ self.closes: int = 0
+
+ async def set_api_key_auth(self, provider_id: str, api_key: str) -> None:
+ self.set_calls.append((provider_id, api_key))
+
+ async def close_http_session(self, loop) -> None: # type: ignore[override]
+ self.closes += 1
+
+
+def fake_save_env(monkeypatch, tmp_path):
+ """Wire ``save_opencode_provider_auth`` to a temp HOME + fake server."""
+ server = _FakeServer()
+
+ async def _fake_get_server():
+ return server
+
+ monkeypatch.setattr(api, "_opencode_get_server", _fake_get_server)
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
+ return server, tmp_path
+
+
+def _save(provider_id: str, payload: dict) -> dict:
+ return api.save_opencode_provider_auth(provider_id, payload)
+
+
+def test_base_url_absent_leaves_existing_value_untouched(fake_save_env) -> None:
+ from vibe.opencode_config import (
+ read_opencode_provider_base_url,
+ upsert_opencode_provider_base_url,
+ )
+
+ server, home = fake_save_env
+ upsert_opencode_provider_base_url("openai", "https://existing.example", home=home)
+
+ # Caller re-saves just the api_key: this used to wipe baseURL because
+ # the server treated "absent" the same as "empty".
+ result = _save("openai", {"api_key": "sk-new"})
+ assert result == {"ok": True}
+ assert ("openai", "sk-new") in server.set_calls
+ assert (
+ read_opencode_provider_base_url("openai", home=home)
+ == "https://existing.example"
+ )
+
+
+def test_base_url_explicit_empty_clears_stored_value(fake_save_env) -> None:
+ from vibe.opencode_config import (
+ read_opencode_provider_base_url,
+ upsert_opencode_provider_base_url,
+ )
+
+ server, home = fake_save_env
+ upsert_opencode_provider_base_url("openai", "https://stale.example", home=home)
+
+ result = _save("openai", {"api_key": "sk-new", "base_url": ""})
+ assert result == {"ok": True}
+ assert read_opencode_provider_base_url("openai", home=home) is None
+
+
+def test_base_url_explicit_whitespace_clears_stored_value(fake_save_env) -> None:
+ from vibe.opencode_config import (
+ read_opencode_provider_base_url,
+ upsert_opencode_provider_base_url,
+ )
+
+ server, home = fake_save_env
+ upsert_opencode_provider_base_url("openai", "https://stale.example", home=home)
+
+ result = _save("openai", {"api_key": "sk-new", "base_url": " "})
+ assert result == {"ok": True}
+ assert read_opencode_provider_base_url("openai", home=home) is None
+
+
+def test_base_url_persists_when_provided(fake_save_env) -> None:
+ from vibe.opencode_config import read_opencode_provider_base_url
+
+ server, home = fake_save_env
+ result = _save(
+ "openai",
+ {"api_key": "sk-new", "base_url": "https://relay.example/v1"},
+ )
+ assert result == {"ok": True}
+ assert (
+ read_opencode_provider_base_url("openai", home=home)
+ == "https://relay.example/v1"
+ )
+
+
+ "bad_value",
+ [
+ "relay.example",
+ "ftp://relay.example",
+ "javascript:alert(1)",
+ "//relay.example",
+ ],
+)
+def test_base_url_must_be_http_or_https(fake_save_env, bad_value) -> None:
+ server, home = fake_save_env
+ result = _save(
+ "openai",
+ {"api_key": "sk-new", "base_url": bad_value},
+ )
+ assert result["ok"] is False
+ assert "http://" in result["message"] and "https://" in result["message"]
+ # The daemon call must not fire for a rejected payload.
+ assert server.set_calls == []
+
+
+def test_base_url_must_be_string(fake_save_env) -> None:
+ server, _ = fake_save_env
+ result = _save("openai", {"api_key": "sk-new", "base_url": 123})
+ assert result["ok"] is False
+ assert "string" in result["message"].lower()
+ assert server.set_calls == []
+
+
+def test_base_url_null_clears_stored_value(fake_save_env) -> None:
+ from vibe.opencode_config import (
+ read_opencode_provider_base_url,
+ upsert_opencode_provider_base_url,
+ )
+
+ server, home = fake_save_env
+ upsert_opencode_provider_base_url("openai", "https://stale.example", home=home)
+ result = _save("openai", {"api_key": "sk-new", "base_url": None})
+ assert result == {"ok": True}
+ assert read_opencode_provider_base_url("openai", home=home) is None
+
+
+def test_missing_api_key_rejected_before_any_side_effect(fake_save_env) -> None:
+ server, _ = fake_save_env
+ result = _save("openai", {"base_url": "https://x.example"})
+ assert result["ok"] is False
+ assert "api_key" in result["message"]
+ assert server.set_calls == []
+
+
+def test_base_url_persist_failure_surfaces_to_caller(monkeypatch, tmp_path) -> None:
+ """If the JSON write blows up after the daemon call succeeds, the
+ response must say so — silently returning ``ok: True`` is the exact
+ "save success, value lost on reload" bug we're fixing.
+ """
+
+ from vibe import opencode_config
+
+ server = _FakeServer()
+
+ async def _fake_get_server():
+ return server
+
+ monkeypatch.setattr(api, "_opencode_get_server", _fake_get_server)
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
+
+ def _explode(*args, **kwargs):
+ raise RuntimeError("disk full")
+
+ monkeypatch.setattr(opencode_config, "upsert_opencode_provider_base_url", _explode)
+
+ result = _save(
+ "openai",
+ {"api_key": "sk-new", "base_url": "https://relay.example/v1"},
+ )
+ assert result["ok"] is False
+ assert "disk full" in result["message"]
+ # Daemon call happened — the partial state is documented in the
+ # error message so the UI can prompt the user.
+ assert ("openai", "sk-new") in server.set_calls
diff --git a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
index 398ce4c07..aa2435434 100644
--- a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
+++ b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
@@ -340,7 +340,15 @@ export const SettingsOpencodeProviderPage: React.FC = () => {
setExpandedId(provider.id);
setEditByProvider((prev) => {
if (prev[provider.id]) return prev;
- return { ...prev, [provider.id]: emptyEdit() };
+ // Pre-populate baseUrl from the persisted opencode.json override so
+ // the input round-trips: open card → see existing value → edit →
+ // save. Leaving it blank on every open would let a re-save wipe the
+ // value because the form is the only baseURL signal we forward.
+ const seeded = emptyEdit();
+ if (provider.base_url) {
+ seeded.baseUrl = provider.base_url;
+ }
+ return { ...prev, [provider.id]: seeded };
});
};
@@ -381,9 +389,17 @@ export const SettingsOpencodeProviderPage: React.FC = () => {
});
return;
}
+ // The Base URL field is the only signal the form sends for the
+ // ``provider.<id>.options.baseURL`` override in ``opencode.json``.
+ // Forwarding the trimmed value verbatim — including the empty
+ // string for "clear" — is critical: if we dropped to ``undefined``
+ // for blanks, the server would interpret it as "leave unchanged"
+ // and a user who removed the value in the form would silently keep
+ // the old override on disk.
+ const baseUrl = state.baseUrl.trim();
updateEdit(provider.id, { saving: true, error: null });
try {
- const result = await api.setOpencodeProviderAuth(provider.id, key);
+ const result = await api.setOpencodeProviderAuth(provider.id, key, baseUrl);
if (!result.ok) {
updateEdit(provider.id, {
saving: false,
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 6b2e2fe91..088546028 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -26,7 +26,11 @@ export type ApiContextType = {
getClaudeAuth: () => Promise<ClaudeAuthState>;
saveClaudeAuth: (payload: ClaudeAuthPayload) => Promise<ClaudeAuthSaveResult>;
getOpencodeProviders: () => Promise<OpencodeProviderListResult>;
- setOpencodeProviderAuth: (providerId: string, apiKey: string) => Promise<OpencodeMutationResult>;
+ setOpencodeProviderAuth: (
+ providerId: string,
+ apiKey: string,
+ baseUrl?: string,
+ ) => Promise<OpencodeMutationResult>;
deleteOpencodeProviderAuth: (providerId: string) => Promise<OpencodeMutationResult>;
setOpencodeDefaultProvider: (providerId: string) => Promise<OpencodeMutationResult>;
slackAuthTest: (botToken: string, proxyUrl?: string) => Promise<any>;
@@ -143,6 +147,12 @@ export type CodexAuthState = {
has_chatgpt_tokens: boolean;
credentials_store: CodexCredentialsStore;
file_store_active: boolean;
+ // True when Codex is in keyring-preferred mode and disk shows no
+ // key/tokens — the live auth may live in the OS keychain (we cannot
+ // portably read it). UI must not claim "no key configured" in that
+ // case; it should prompt the user to choose a mode (saving will pin
+ // file storage so subsequent reads work).
+ auth_mode_uncertain?: boolean;
message?: string;
};
@@ -204,6 +214,10 @@ export type OpencodeProvider = {
local: boolean;
models: string[];
default_model: string | null;
+ // Optional ``baseURL`` override persisted in opencode.json. Surfaced so
+ // the Settings page can pre-populate the Base URL input with the last
+ // saved value instead of starting empty on every reload.
+ base_url?: string | null;
};
export type OpencodeProviderListResult = {
@@ -315,8 +329,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getClaudeAuth: () => getJson('/backend/claude/auth'),
saveClaudeAuth: (payload) => postJson('/backend/claude/auth', payload),
getOpencodeProviders: () => getJson('/backend/opencode/providers'),
- setOpencodeProviderAuth: (providerId, apiKey) =>
- postJson(`/backend/opencode/provider/${encodeURIComponent(providerId)}/auth`, { api_key: apiKey }),
+ setOpencodeProviderAuth: (providerId, apiKey, baseUrl) =>
+ // Forward ``base_url`` only when the caller passed something
+ // (including an explicit empty string for "clear"); omitting it
+ // entirely tells the server to leave the stored value untouched,
+ // which is the right default for callers that don't care about
+ // the base-URL override.
+ postJson(`/backend/opencode/provider/${encodeURIComponent(providerId)}/auth`, {
+ api_key: apiKey,
+ ...(baseUrl !== undefined ? { base_url: baseUrl } : {}),
+ }),
deleteOpencodeProviderAuth: (providerId) =>
deleteJson(`/backend/opencode/provider/${encodeURIComponent(providerId)}/auth`),
setOpencodeDefaultProvider: (providerId) =>
diff --git a/vibe/api.py b/vibe/api.py
index 2b9b95cf4..18b004a86 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -10,7 +10,7 @@ import time
import urllib.request
import uuid
from pathlib import Path
-from typing import Dict, List, Optional
+from typing import Any, Dict, List, Optional
from config import paths
from config.v2_config import CONFIG_LOCK, V2Config
@@ -2113,6 +2113,16 @@ def get_codex_auth() -> dict:
# warning even when the store is already ``file``.
"credentials_store": disk_state.get("credentials_store") or "auto",
"file_store_active": bool(disk_state.get("file_store_active")),
+ # Surface "we can't read your key — it may live in the OS
+ # keychain" so the UI doesn't claim "no key configured" when
+ # Codex is in keyring-preferred mode and we have no disk
+ # evidence. We suppress the flag when V2Config has a stored
+ # ``auth_mode`` (the user already saved through our flow), since
+ # we then know the mode and the next save will pin file storage.
+ "auth_mode_uncertain": (
+ bool(disk_state.get("auth_mode_uncertain"))
+ and configured_mode not in _VALID_AUTH_MODES
+ ),
}
@@ -2460,6 +2470,31 @@ async def _get_opencode_providers_async() -> dict:
except Exception:
pass
+ # Pre-load the user-config base-URL overrides once so we can attach
+ # them to each row without re-parsing the JSON file per provider.
+ try:
+ from vibe.opencode_config import load_first_opencode_user_config
+
+ opencode_probe = await asyncio.to_thread(
+ load_first_opencode_user_config, logger_instance=logger
+ )
+ except Exception as exc:
+ logger.debug("Could not read opencode.json for baseURL pre-population: %s", exc)
+ opencode_probe = None
+ base_url_index: dict = {}
+ if opencode_probe is not None and isinstance(opencode_probe.config, dict):
+ provider_block = opencode_probe.config.get("provider")
+ if isinstance(provider_block, dict):
+ for pid_key, pid_config in provider_block.items():
+ if not isinstance(pid_config, dict):
+ continue
+ options = pid_config.get("options")
+ if not isinstance(options, dict):
+ continue
+ candidate = options.get("baseURL")
+ if isinstance(candidate, str) and candidate.strip():
+ base_url_index[pid_key] = candidate.strip()
+
out_providers = []
for pid, entry in all_providers.items():
if not isinstance(entry, dict):
@@ -2497,6 +2532,7 @@ async def _get_opencode_providers_async() -> dict:
"local": local,
"models": model_ids,
"default_model": default_model,
+ "base_url": base_url_index.get(pid),
}
)
@@ -2518,7 +2554,22 @@ def get_opencode_providers() -> dict:
return {"ok": False, "message": str(exc)}
-async def _save_opencode_provider_auth_async(provider_id: str, api_key: str) -> dict:
+# Sentinel used by ``save_opencode_provider_auth`` to distinguish three
+# states of the optional ``base_url`` field:
+# * key absent from payload → ``_BASE_URL_UNCHANGED`` (no-op)
+# * key present, value blank → ``None`` (clear stored)
+# * key present, value non-blank → ``str`` (upsert)
+# Without this, a payload like ``{"api_key": "..."}`` (re-saving just
+# the API key) would silently wipe the stored ``baseURL`` because the
+# server cannot tell "omitted" from "explicitly empty".
+_BASE_URL_UNCHANGED: object = object()
+
+
+async def _save_opencode_provider_auth_async(
+ provider_id: str,
+ api_key: str,
+ base_url: Any = _BASE_URL_UNCHANGED,
+) -> dict:
server = await _opencode_get_server()
if server is None:
return {"ok": False, "message": "OpenCode is disabled in V2Config"}
@@ -2527,19 +2578,74 @@ async def _save_opencode_provider_auth_async(provider_id: str, api_key: str) ->
await server.set_api_key_auth(provider_id, api_key)
finally:
await server.close_http_session(loop=request_loop)
- # Also clean the legacy ``opencode.json`` provider block so the UI
- # source of truth (OpenCode's own auth store) wins on next launch.
+
+ # Two-source-of-truth pruning: drop the legacy ``opencode.json``
+ # ``apiKey`` entry now that the daemon's auth store owns the key.
+ # This is best-effort: a JSON-write failure here is non-fatal because
+ # the daemon already has the key.
+ from vibe.opencode_config import (
+ remove_opencode_provider_api_key,
+ remove_opencode_provider_base_url,
+ upsert_opencode_provider_base_url,
+ )
+
try:
- from vibe.opencode_config import remove_opencode_provider_api_key
+ await asyncio.to_thread(
+ remove_opencode_provider_api_key, provider_id, logger_instance=logger
+ )
+ except Exception as exc:
+ logger.debug("Legacy opencode.json apiKey cleanup skipped for %s: %s", provider_id, exc)
+
+ # ``baseURL`` is different: OpenCode's auth endpoint has no field for
+ # it, so this write is the *only* place it gets persisted. A silent
+ # failure would surface as "save success, value lost on reload" — the
+ # exact UX bug Codex flagged. Surface those errors to the caller so
+ # the UI can show a useful message.
+ if base_url is _BASE_URL_UNCHANGED:
+ return {"ok": True}
- await asyncio.to_thread(remove_opencode_provider_api_key, provider_id, logger_instance=logger)
+ try:
+ if base_url:
+ await asyncio.to_thread(
+ upsert_opencode_provider_base_url,
+ provider_id,
+ base_url,
+ logger_instance=logger,
+ )
+ else:
+ await asyncio.to_thread(
+ remove_opencode_provider_base_url,
+ provider_id,
+ logger_instance=logger,
+ )
except Exception as exc:
- logger.debug("Legacy opencode.json cleanup skipped for %s: %s", provider_id, exc)
+ logger.warning(
+ "OpenCode base_url persist failed for %s: %s", provider_id, exc, exc_info=True
+ )
+ return {
+ "ok": False,
+ "message": (
+ "API key saved, but base URL persistence failed: "
+ f"{exc}"
+ ),
+ }
return {"ok": True}
def save_opencode_provider_auth(provider_id: str, payload: dict) -> dict:
- """Persist a single OpenCode provider's API key via the live daemon."""
+ """Persist a single OpenCode provider's API key (and optional base URL).
+
+ The api key is forwarded to OpenCode's own ``PUT /auth`` endpoint so
+ the daemon's auth store remains the source of truth. The optional
+ ``base_url`` override is persisted into ``opencode.json`` because
+ OpenCode's auth endpoint has no field for it — without this fan-out
+ the Settings UI's Base URL input would be a no-op.
+
+ ``base_url`` field semantics in the payload:
+ * absent → leave the stored value untouched
+ * empty / whitespace → clear the stored value
+ * non-empty string → upsert (must start with http:// or https://)
+ """
if not isinstance(provider_id, str) or not provider_id.strip():
return {"ok": False, "message": "provider_id is required"}
if not isinstance(payload, dict):
@@ -2548,8 +2654,30 @@ def save_opencode_provider_auth(provider_id: str, payload: dict) -> dict:
if not isinstance(raw_key, str) or not raw_key.strip():
return {"ok": False, "message": "api_key is required"}
api_key = raw_key.strip()
+
+ base_url: Any = _BASE_URL_UNCHANGED
+ if "base_url" in payload:
+ raw_base_url = payload.get("base_url")
+ if raw_base_url is None:
+ base_url = None
+ elif isinstance(raw_base_url, str):
+ candidate = raw_base_url.strip()
+ if not candidate:
+ base_url = None
+ else:
+ if not candidate.lower().startswith(("http://", "https://")):
+ return {
+ "ok": False,
+ "message": "base_url must start with http:// or https://",
+ }
+ base_url = candidate
+ else:
+ return {"ok": False, "message": "base_url must be a string"}
+
try:
- return asyncio.run(_save_opencode_provider_auth_async(provider_id.strip(), api_key))
+ return asyncio.run(
+ _save_opencode_provider_auth_async(provider_id.strip(), api_key, base_url)
+ )
except Exception as exc:
logger.warning("OpenCode set-auth failed for %s: %s", provider_id, exc, exc_info=True)
return {"ok": False, "message": str(exc)}
diff --git a/vibe/claude_config.py b/vibe/claude_config.py
index ccc3d83cb..6c9b070b3 100644
--- a/vibe/claude_config.py
+++ b/vibe/claude_config.py
@@ -154,3 +154,58 @@ def read_claude_api_key_from_settings(home: Path | None = None) -> Optional[str]
"""
env_block = read_claude_settings_env(home)
return env_block.get("ANTHROPIC_API_KEY")
+
+
+def build_claude_subprocess_env(
+ claude_cfg: Any,
+ base_env: Optional[Dict[str, str]] = None,
+) -> Dict[str, str]:
+ """Build the env dict passed to every Claude subprocess / SDK client.
+
+ 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.
+
+ The ``auth_mode`` toggle is the load-bearing piece — if a user picks
+ OAuth in Settings but their shell exports ``ANTHROPIC_API_KEY``, the
+ Claude CLI silently keeps API-key auth and never reaches
+ ``~/.claude/credentials.json``. Stripping both ``ANTHROPIC_API_KEY``
+ and ``ANTHROPIC_AUTH_TOKEN`` (header-semantics switch) in OAuth mode
+ makes the Settings toggle authoritative.
+
+ Centralising the logic prevents the next env-var path (control
+ client, future MCP launch, etc.) from forgetting the strip and
+ re-introducing the same bug.
+ """
+
+ env_source = base_env if base_env is not None else os.environ
+ claude_env: Dict[str, str] = {}
+ for key, value in env_source.items():
+ if key.startswith("ANTHROPIC_") or key.startswith("CLAUDE_"):
+ claude_env[key] = value
+
+ if claude_cfg is None:
+ return claude_env
+
+ auth_mode = getattr(claude_cfg, "auth_mode", "oauth")
+ if auth_mode == "oauth":
+ # OAuth means Claude Code reads credentials from
+ # ``~/.claude/credentials.json``; any inherited API-key / bearer-
+ # token var would suppress that path. Strip both.
+ claude_env.pop("ANTHROPIC_API_KEY", None)
+ claude_env.pop("ANTHROPIC_AUTH_TOKEN", None)
+ elif auth_mode == "api_key":
+ configured_key = (getattr(claude_cfg, "api_key", None) or "").strip()
+ if configured_key:
+ claude_env["ANTHROPIC_API_KEY"] = configured_key
+ # 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)
+
+ configured_base = (getattr(claude_cfg, "base_url", None) or "").strip()
+ if configured_base:
+ claude_env["ANTHROPIC_BASE_URL"] = configured_base
+
+ return claude_env
diff --git a/vibe/opencode_config.py b/vibe/opencode_config.py
index 2dfb401d8..0f37e2d49 100644
--- a/vibe/opencode_config.py
+++ b/vibe/opencode_config.py
@@ -479,3 +479,127 @@ def remove_opencode_provider_api_key(
probe.path.parent.mkdir(parents=True, exist_ok=True)
probe.path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
return probe.path
+
+
+def upsert_opencode_provider_base_url(
+ provider_id: str,
+ base_url: str,
+ *,
+ home: Path | None = None,
+ logger_instance: Optional[logging.Logger] = None,
+) -> Path:
+ """Persist a provider's custom ``baseURL`` into ``opencode.json``.
+
+ OpenCode's own auth endpoint (``PUT /auth/{provider_id}``) only stores
+ the API key; the per-provider ``baseURL`` lives in the user config
+ under ``provider.<id>.options.baseURL`` (the standard Vercel AI SDK
+ field name, capital URL). The Settings UI surfaces a Base URL input,
+ so we mirror the api-key helper to write that field through.
+ """
+
+ active_logger = logger_instance or logger
+ probe = load_first_opencode_user_config(home=home, logger_instance=active_logger)
+
+ if probe.path is not None and probe.config is not None:
+ config = probe.config
+ target_path = probe.path
+ elif probe.existing_paths:
+ raise ValueError("Existing OpenCode config could not be parsed")
+ else:
+ config = {}
+ target_path = get_opencode_config_paths(home)[0]
+
+ provider_map = config.setdefault("provider", {})
+ if not isinstance(provider_map, dict):
+ raise ValueError("OpenCode config field 'provider' is not an object")
+
+ provider_config = provider_map.setdefault(provider_id, {})
+ if not isinstance(provider_config, dict):
+ raise ValueError(f"OpenCode provider '{provider_id}' config is not an object")
+
+ options = provider_config.setdefault("options", {})
+ if not isinstance(options, dict):
+ raise ValueError(f"OpenCode provider '{provider_id}' options are not an object")
+
+ options["baseURL"] = base_url
+ if "$schema" not in config:
+ config["$schema"] = "https://opencode.ai/config.json"
+
+ target_path.parent.mkdir(parents=True, exist_ok=True)
+ target_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
+ return target_path
+
+
+def remove_opencode_provider_base_url(
+ provider_id: str,
+ *,
+ home: Path | None = None,
+ logger_instance: Optional[logging.Logger] = None,
+) -> Optional[Path]:
+ """Drop a provider's custom ``baseURL`` from ``opencode.json``.
+
+ Mirrors :func:`remove_opencode_provider_api_key`: prunes empty
+ ``options`` / provider / ``provider`` blocks so the file does not
+ accumulate empty scaffolding once every override is cleared.
+ """
+
+ active_logger = logger_instance or logger
+ probe = load_first_opencode_user_config(home=home, logger_instance=active_logger)
+
+ if probe.path is None or probe.config is None:
+ return None
+
+ config = probe.config
+ provider_map = config.get("provider")
+ if not isinstance(provider_map, dict):
+ return probe.path
+
+ provider_config = provider_map.get(provider_id)
+ if not isinstance(provider_config, dict):
+ return probe.path
+
+ options = provider_config.get("options")
+ if isinstance(options, dict):
+ options.pop("baseURL", None)
+ if not options:
+ provider_config.pop("options", None)
+
+ if not provider_config:
+ provider_map.pop(provider_id, None)
+
+ if not provider_map:
+ config.pop("provider", None)
+
+ probe.path.parent.mkdir(parents=True, exist_ok=True)
+ probe.path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
+ return probe.path
+
+
+def read_opencode_provider_base_url(
+ provider_id: str,
+ *,
+ home: Path | None = None,
+ logger_instance: Optional[logging.Logger] = None,
+) -> Optional[str]:
+ """Return the persisted ``baseURL`` for a provider, if any.
+
+ Used by the providers-listing endpoint so the Settings UI can
+ pre-populate the Base URL input with the user's last saved value
+ instead of starting empty on every reload.
+ """
+
+ active_logger = logger_instance or logger
+ probe = load_first_opencode_user_config(home=home, logger_instance=active_logger)
+ if probe.config is None:
+ return None
+ provider_map = probe.config.get("provider")
+ if not isinstance(provider_map, dict):
+ return None
+ provider_config = provider_map.get(provider_id)
+ if not isinstance(provider_config, dict):
+ return None
+ options = provider_config.get("options")
+ if not isinstance(options, dict):
+ return None
+ value = options.get("baseURL")
+ return value if isinstance(value, str) and value.strip() else None