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(model-hub): preserve gateway auth across backend configs (#1891)

Call White389cc3c48573
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 8dd4a4a91..973036735 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -1490,6 +1490,7 @@ class SessionHandler(BaseHandler):
from modules.agents.model_hub import (
build_claude_hub_env,
claude_setting_sources_for_launch,
+ claude_settings_for_launch,
launch_for_context,
)
@@ -1587,7 +1588,7 @@ class SessionHandler(BaseHandler):
"resume": stored_claude_session_id if stored_claude_session_id else None,
"fork_session": bool(fork_session and stored_claude_session_id),
"extra_args": extra_args,
- "settings": CLAUDE_MEMORY_DISABLED_SETTINGS,
+ "settings": claude_settings_for_launch(CLAUDE_MEMORY_DISABLED_SETTINGS, model_hub_launch),
"setting_sources": claude_setting_sources_for_launch(model_hub_launch),
"skills": [],
"sandbox": CLAUDE_REMOTE_SANDBOX,
diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.py
index 04aceed58..861bcd893 100644
--- a/modules/agents/model_hub.py
+++ b/modules/agents/model_hub.py
@@ -208,13 +208,23 @@ def bind_persisted_launch(context: Any, payload: object) -> ModelHubLaunch | Non
def claude_setting_sources_for_launch(launch: ModelHubLaunch | None) -> list[str]:
if launch is not None and launch.channel == "hub":
- # ~/.claude/settings.json env values override subprocess env. Keep
- # project/local CLAUDE.md loading, but mask the user settings source so
- # persisted native auth cannot bypass the ephemeral gateway injection.
+ # Project/local settings remain available. Connection settings are
+ # pinned separately because HOME can also be the project directory.
return ["project", "local"]
return ["user", "project", "local"]
+def claude_settings_for_launch(base_settings: str, launch: ModelHubLaunch | None) -> str:
+ """Pin Hub connection settings above every native settings source."""
+
+ if launch is None or launch.channel != "hub":
+ return base_settings
+ settings = json.loads(base_settings)
+ settings["env"] = {**settings.get("env", {}), **build_claude_hub_env({}, launch)}
+ settings["apiKeyHelper"] = ""
+ return json.dumps(settings)
+
+
async def resolve_model_hub_launch(
controller: Any,
backend: BackendName,
@@ -307,18 +317,26 @@ def build_claude_hub_env(
return dict(base_env)
if launch.channel == "hub":
if not launch.gateway_base_url or not launch.gateway_token:
- return dict(base_env)
+ raise ModelHubError("engine_down", status=503, turn_outcome=ENGINE_DOWN_TURN_OUTCOME)
+ # The SDK merges overrides over os.environ, so deletion would revive
+ # inherited auth. The same tombstones also mask project/local settings.
+ masked_keys = {
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_CUSTOM_HEADERS",
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
+ "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
+ "CLAUDE_CODE_USE_BEDROCK",
+ "CLAUDE_CODE_USE_VERTEX",
+ "CLAUDE_CODE_USE_FOUNDRY",
+ "CLAUDE_CODE_MAX_CONTEXT_TOKENS",
+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
+ }
result = {
- key: value
+ key: "" if key.startswith("ANTHROPIC_") or key in masked_keys else value
for key, value in base_env.items()
- if not key.startswith("ANTHROPIC_")
- and key
- not in {
- "CLAUDE_CODE_OAUTH_TOKEN",
- "CLAUDE_CODE_MAX_CONTEXT_TOKENS",
- "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
- }
}
+ result.update(dict.fromkeys(masked_keys, ""))
result["ANTHROPIC_BASE_URL"] = launch.gateway_base_url
result["ANTHROPIC_AUTH_TOKEN"] = launch.gateway_token
result["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] = "1"
diff --git a/modules/agents/opencode/caller_context.py b/modules/agents/opencode/caller_context.py
index 3baf53aed..798d337a6 100644
--- a/modules/agents/opencode/caller_context.py
+++ b/modules/agents/opencode/caller_context.py
@@ -5,7 +5,8 @@ cannot live in the server process environment. Instead Avibe installs a tiny
OpenCode plugin that resolves each shell call's OpenCode session id through an
Avibe-managed binding file and injects the AVIBE_* env vars for that call. The
same process-scoped plugin removes OpenCode's native Skill Catalog after its
-system prompt is assembled; Avibe supplies the managed Catalog instead.
+system prompt is assembled and restores exact Hub provider definitions after
+native configuration merging; Avibe owns both projections.
"""
from __future__ import annotations
@@ -72,6 +73,16 @@ function stripNativeSkillCatalog(text) {
}
export const AvibeCallerContextPlugin = async () => ({
+ "config": async (config) => {
+ if (process.env.AVIBE_OPENCODE_MODEL_HUB !== "1") return
+ const overlay = JSON.parse(process.env.OPENCODE_CONFIG_CONTENT || "null")
+ if (!overlay || !overlay.provider || !Array.isArray(overlay.enabled_providers)) {
+ throw new Error("Avibe Model Hub launch config is unavailable")
+ }
+ // OpenCode deep-merges native config, retaining unowned headers and model
+ // transport fields. Replace each Hub provider after that merge instead.
+ config.provider = { ...config.provider, ...structuredClone(overlay.provider) }
+ },
"shell.env": async (input, output) => {
const sessionID = input && typeof input.sessionID === "string" ? input.sessionID : ""
if (!sessionID) return
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index f940c6199..5ab80bab8 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -1844,6 +1844,7 @@ class OpenCodeServerManager:
env["OPENCODE_ENABLE_EXA"] = "1"
env["OPENCODE_DISABLE_EXTERNAL_SKILLS"] = "1"
env.update(server_environment())
+ env["AVIBE_OPENCODE_MODEL_HUB"] = "1" if self._model_hub_overlay_path else "0"
if self._model_hub_overlay_path:
env["OPENCODE_CONFIG"] = self._model_hub_overlay_path
content = self._model_hub_overlay_content
diff --git a/modules/claude_sdk_compat.py b/modules/claude_sdk_compat.py
index 66a7487d0..fddf6ac5f 100644
--- a/modules/claude_sdk_compat.py
+++ b/modules/claude_sdk_compat.py
@@ -2,7 +2,14 @@
from __future__ import annotations
+import json
import logging
+import tempfile
+from contextlib import ExitStack
+from dataclasses import replace
+from pathlib import Path
+
+from config.atomic_io import write_atomic
logger = logging.getLogger(__name__)
@@ -66,6 +73,47 @@ try:
return isinstance(data, dict) and data.get("type") == "rate_limit_event"
class ClaudeSDKClient(_ClaudeSDKClient):
+ def _prepare_launch_settings(self) -> None:
+ if getattr(self, "_launch_settings", None) is not None:
+ return
+ raw = self.options.settings
+ if not raw or not raw.lstrip().startswith("{"):
+ return
+ settings = json.loads(raw)
+ if not settings.get("env"):
+ return
+ # SDK sandbox merging otherwise expands even a settings file back
+ # into argv. Merge here and pass only the private file's path.
+ if self.options.sandbox is not None:
+ settings["sandbox"] = self.options.sandbox
+ resources = ExitStack()
+ self._launch_settings = resources
+ directory = resources.enter_context(tempfile.TemporaryDirectory(prefix="avibe-claude-settings-"))
+ path = Path(directory) / "settings.json"
+ write_atomic(path, json.dumps(settings))
+ resources.callback(setattr, self, "options", self.options)
+ self.options = replace(self.options, settings=str(path), sandbox=None)
+
+ def _close_launch_settings(self) -> None:
+ resources = getattr(self, "_launch_settings", None)
+ if resources is not None:
+ self._launch_settings = None
+ resources.close()
+
+ async def connect(self, prompt=None) -> None:
+ try:
+ self._prepare_launch_settings()
+ await super().connect(prompt)
+ except BaseException:
+ self._close_launch_settings()
+ raise
+
+ async def disconnect(self) -> None:
+ try:
+ await super().disconnect()
+ finally:
+ self._close_launch_settings()
+
async def receive_messages(self):
"""Receive all messages from Claude, tolerating non-fatal SDK event additions."""
if not self._query:
diff --git a/tests/e2e/test_model_hub_backend_settings.py b/tests/e2e/test_model_hub_backend_settings.py
new file mode 100644
index 000000000..692154f2f
--- /dev/null
+++ b/tests/e2e/test_model_hub_backend_settings.py
@@ -0,0 +1,198 @@
+"""Real backend launches keep Model Hub transport ownership."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import shutil
+import subprocess
+import time
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from config.v2_config import ModelHubBackendModelConfig, ModelHubMenuConfig
+from core.handlers.model_hub.identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL
+from modules.agents.model_hub import ModelHubRuntimeRouter
+from modules.agents.opencode.caller_context import PLUGIN_FILENAME, PLUGIN_SOURCE
+from tests.e2e.drivers.model_hub_app import ModelHubTestApp
+from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream
+from tests.e2e.test_model_hub_routing import _request_credential
+from tests.e2e.test_model_hub_runtime import _install_engine, _local_engine_manifest
+from tests.e2e.test_model_hub_sources import SYNTHETIC_API_KEY, _configure_protocol, _create_source
+from tests.scenario_harness.model_hub import (
+ MemoryModelHubStore,
+ ModelHubScenarioAdapter,
+ config_with_sources,
+ fixed_model,
+ service_for,
+ source,
+)
+from vibe.opencode_config import managed_opencode_runtime_config_content
+
+
+pytestmark = pytest.mark.e2e_model_hub
+
+
[email protected]("provider_id", ["native-relay", "avibe_model_hub"])
+def test_codex_native_provider_settings_cannot_change_hub_egress(
+ model_hub_app_factory, mock_llm_upstream, provider_id,
+) -> None:
+ """MH-CODEX-LAUNCH-001: native auth cannot change a Hub turn's egress."""
+ binary = shutil.which("codex")
+ if binary is None:
+ pytest.skip("Codex executable is unavailable")
+ menu_model = fixed_model("codex")
+ routed_model = "upstream-route-model"
+ native_key = "sk-native-provider-fixture"
+
+ def prepare_runtime(app):
+ node = shutil.which("node")
+ if node:
+ app.env["PATH"] += os.pathsep + str(Path(node).parent)
+
+ with MockLLMUpstream() as native, model_hub_app_factory(
+ extra_env={"VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH": _local_engine_manifest()},
+ before_start=prepare_runtime,
+ ) as app:
+ _configure_protocol(native, "openai_responses", models=[{"id": menu_model}])
+ native_settings = app.home / ".codex" / "config.toml"
+ native_settings.parent.mkdir(parents=True, exist_ok=True)
+ native_payload = (
+ 'cli_auth_credentials_store = "file"\n'
+ f'model_provider = "{provider_id}"\n'
+ f'[model_providers.{provider_id}]\n'
+ 'name = "Native relay"\n'
+ f'base_url = "{native.url}/v1"\n'
+ 'wire_api = "responses"\n'
+ f'experimental_bearer_token = "{native_key}"\n'
+ f'http_headers = {{ "Authorization" = "Bearer {native_key}", "x-api-key" = "{native_key}" }}\n'
+ )
+ native_settings.write_text(native_payload)
+ (native_settings.parent / "auth.json").write_text(json.dumps({"OPENAI_API_KEY": native_key}))
+ configured = app.client.post("/api/config", {
+ "agents": {"codex": {"enabled": True, "cli_path": binary}},
+ })
+ assert configured.status == 200, configured.json()
+ _install_engine(app)
+ _configure_protocol(mock_llm_upstream, "openai_responses", models=[{"id": routed_model}])
+ supplied, _ = _create_source(
+ app, mock_llm_upstream, protocol="openai_responses",
+ extra={"base_url": mock_llm_upstream.url + "/v1"},
+ )
+ mode = app.client.patch("/api/models/agents/codex/mode", {"mode": "hub"})
+ assert mode.status == 200, mode.json()
+ chain = app.client.put(f"/api/models/agents/codex/chain?model={menu_model}", {
+ "hops": [{"source_id": supplied["id"], "model_id": routed_model}],
+ })
+ assert chain.status == 200, chain.json()
+ agent = app.client.post("/api/agents", {
+ "name": "codex-hub-settings-e2e", "backend": "codex", "model": menu_model,
+ })
+ assert agent.status == 200, agent.json()
+ project = app.client.post("/api/projects", {
+ "folder_path": str(app.home), "display_name": "Codex Hub settings E2E",
+ })
+ assert project.status == 201, project.json()
+ session = app.client.post("/api/sessions", {
+ "project_id": project.json()["id"], "agent_name": "codex-hub-settings-e2e", "model": menu_model,
+ })
+ assert session.status == 201, session.json()
+ session_id = session.json()["id"]
+ mock_llm_upstream.reset_requests()
+ native.reset_requests()
+ sent = app.client.post(f"/api/sessions/{session_id}/messages", {"text": "hello"})
+ assert sent.status == 202, sent.json()
+ deadline = time.monotonic() + 60
+ while time.monotonic() < deadline:
+ observed = mock_llm_upstream.requests() + native.requests()
+ if any(item["path"] == "/v1/responses" for item in observed):
+ break
+ time.sleep(0.1)
+ assert not [item for item in native.requests() if item["path"] == "/v1/responses"]
+ captured = [item for item in mock_llm_upstream.requests() if item["path"] == "/v1/responses"]
+ assert captured, app.diagnostics()
+ assert all(item["body"]["model"] == routed_model for item in captured)
+ assert all(_request_credential(item) == SYNTHETIC_API_KEY for item in captured)
+ # Codex may append project trust, but must not rewrite native auth.
+ assert native_settings.read_text().startswith(native_payload)
+
+
[email protected]("options_scope", ["provider", "model", "model_headers"])
[email protected]("native_protocol", ["openai_responses", "anthropic"])
+def test_opencode_native_settings_cannot_change_hub_transport(tmp_path, options_scope, native_protocol):
+ """MH-OPENCODE-LAUNCH-001: native config cannot change Hub transport."""
+ binary = shutil.which("opencode")
+ if binary is None:
+ pytest.skip("OpenCode executable is unavailable")
+ model = "hub-settings-model"
+ provider_id = OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL[native_protocol]
+ request_path = "/v1/messages" if native_protocol == "anthropic" else "/v1/responses"
+ provider_npm = "@ai-sdk/anthropic" if native_protocol == "anthropic" else "@ai-sdk/openai"
+ token = "hub-transport-fixture-token"
+ native_key = "native-opencode-fixture-token"
+ runtime = ModelHubTestApp(Path(__file__).resolve().parents[2], tmp_path / "runtime")
+ runtime.home.mkdir(parents=True)
+ Path(runtime.env["TMPDIR"]).mkdir(parents=True)
+ with MockLLMUpstream() as gateway, MockLLMUpstream() as native:
+ _configure_protocol(gateway, native_protocol, models=[{"id": model}])
+ _configure_protocol(native, native_protocol, models=[{"id": model}])
+ config = config_with_sources(
+ [source("src_settings01", [model], vendor="openai", protocol="openai_responses")],
+ backend="opencode", menu_model=model,
+ )
+ config.agents["opencode"].models = [ModelHubBackendModelConfig(
+ id=model, origin="manual", native_protocol=native_protocol,
+ context_window=32000, max_output_tokens=4096,
+ )]
+ config.agents["opencode"].menu = ModelHubMenuConfig(checked=[model])
+ service = service_for(tmp_path, MemoryModelHubStore(config), ModelHubScenarioAdapter())
+ router = ModelHubRuntimeRouter(
+ service=service,
+ turn_gateway=SimpleNamespace(endpoint=AsyncMock(return_value=(gateway.url, token))),
+ overlay_path=tmp_path / "overlay.json",
+ )
+ overlay = asyncio.run(router.prepare_opencode_overlay())
+ assert overlay is not None
+ stale_options = {
+ "baseURL": native.url + "/v1", "apiKey": native_key,
+ "headers": {"Authorization": f"Bearer {native_key}", "x-api-key": native_key},
+ }
+ provider = {"npm": provider_npm, "models": {model: {}}}
+ if options_scope == "provider":
+ provider["options"] = stale_options
+ elif options_scope == "model_headers":
+ provider["models"][model]["headers"] = stale_options["headers"]
+ else:
+ provider["models"][model]["options"] = stale_options
+ native_settings = runtime.home / "opencode.json"
+ native_payload = json.dumps({"$schema": "https://opencode.ai/config.json", "provider": {provider_id: provider}})
+ native_settings.write_text(native_payload)
+ env = {
+ **runtime.env,
+ "OPENCODE_CONFIG": str(overlay.path),
+ "OPENCODE_CONFIG_CONTENT": managed_opencode_runtime_config_content(overlay.content),
+ "OPENCODE_DISABLE_EXTERNAL_SKILLS": "1",
+ "OPENCODE_DISABLE_MODELS_FETCH": "1",
+ "AVIBE_OPENCODE_MODEL_HUB": "1",
+ }
+ plugin = runtime.home / ".config" / "opencode" / "plugins" / PLUGIN_FILENAME
+ plugin.parent.mkdir(parents=True)
+ plugin.write_text(PLUGIN_SOURCE)
+ process = subprocess.Popen(
+ [binary, "run", "--format", "json", "--model", f"{provider_id}/{model}", "hello"],
+ cwd=runtime.home, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True,
+ )
+ try:
+ stdout, stderr = process.communicate(timeout=40)
+ finally:
+ ModelHubTestApp._stop_process(process)
+ assert not [item for item in native.requests() if item["path"] == request_path]
+ captured = [item for item in gateway.requests() if item["path"] == request_path]
+ assert captured, (stdout.decode(), stderr.decode())
+ assert all(_request_credential(item) == token for item in captured), [item["headers"] for item in captured]
+ assert all(item["body"]["model"] == model for item in captured)
+ assert native_settings.read_text() == native_payload
diff --git a/tests/e2e/test_model_hub_routing.py b/tests/e2e/test_model_hub_routing.py
index 767d6bcc3..7f172842f 100644
--- a/tests/e2e/test_model_hub_routing.py
+++ b/tests/e2e/test_model_hub_routing.py
@@ -3,7 +3,10 @@
from __future__ import annotations
import asyncio
+import json
+import time
from datetime import datetime, timezone
+from pathlib import Path
import aiohttp
import pytest
@@ -38,6 +41,97 @@ from tests.scenario_harness.model_hub import (
pytestmark = pytest.mark.e2e_model_hub
[email protected]("settings_scope", ["home", "project", "local"])
+def test_mh_claude_launch_001_settings_cannot_bypass_the_configured_route(
+ model_hub_app_factory, mock_llm_upstream, settings_scope,
+) -> None:
+ """MH-CLAUDE-LAUNCH-001: native settings cannot change a Hub turn's egress."""
+
+ import claude_agent_sdk
+
+ binary = Path(claude_agent_sdk.__file__).parent / "_bundled" / "claude"
+ assert binary.is_file(), "The installed Claude SDK must supply its CLI"
+ menu_model = "claude-opus-5"
+ routed_model = "gpt-6-astra"
+ native_key = "sk-native-claude-settings-fixture"
+ with MockLLMUpstream() as native, _engine_app(model_hub_app_factory) as app:
+ _configure_protocol(native, "anthropic", models=[{"id": menu_model}])
+ cwd = app.home if settings_scope == "home" else app.home / "project"
+ filename = "settings.local.json" if settings_scope == "local" else "settings.json"
+ native_settings = cwd / ".claude" / filename
+ native_payload = json.dumps({"env": {
+ "ANTHROPIC_BASE_URL": native.url,
+ "ANTHROPIC_AUTH_TOKEN": native_key,
+ "ANTHROPIC_API_KEY": native_key,
+ "ANTHROPIC_CUSTOM_HEADERS": f"Authorization: Bearer {native_key}",
+ "CLAUDE_CODE_USE_BEDROCK": "1",
+ "CLAUDE_CODE_USE_VERTEX": "1",
+ "CLAUDE_CODE_USE_FOUNDRY": "1",
+ }})
+ _write(native_settings, native_payload)
+ configured = app.client.post("/api/config", {
+ "agents": {"claude": {"enabled": True, "cli_path": str(binary)}},
+ })
+ assert configured.status == 200, configured.json()
+ _install_engine(app)
+ _configure_protocol(mock_llm_upstream, "openai_responses", models=[{"id": routed_model}])
+ supplied, _ = _create_source(
+ app, mock_llm_upstream, protocol="openai_responses",
+ extra={"base_url": mock_llm_upstream.url + "/v1"},
+ )
+ mode = app.client.patch("/api/models/agents/claude/mode", {"mode": "hub"})
+ assert mode.status == 200, mode.json()
+ chain = app.client.put(f"/api/models/agents/claude/chain?model={menu_model}", {
+ "hops": [{"source_id": supplied["id"], "model_id": routed_model}],
+ })
+ assert chain.status == 200, chain.json()
+ agent = app.client.post("/api/agents", {
+ "name": "claude-hub-settings-e2e", "backend": "claude",
+ "model": menu_model, "system_prompt": "Reply with the supplied response.",
+ })
+ assert agent.status == 200, agent.json()
+ project = app.client.post("/api/projects", {
+ "folder_path": str(cwd), "display_name": "Claude Hub settings E2E",
+ })
+ assert project.status == 201, project.json()
+ session = app.client.post("/api/sessions", {
+ "project_id": project.json()["id"], "agent_name": "claude-hub-settings-e2e",
+ "model": menu_model,
+ })
+ assert session.status == 201, session.json()
+ session_id = session.json()["id"]
+ mock_llm_upstream.reset_requests()
+ native.reset_requests()
+ sent = app.client.post(f"/api/sessions/{session_id}/messages", {"text": "hello"})
+ assert sent.status == 202, sent.json()
+ result = None
+ deadline = time.monotonic() + 60
+ while time.monotonic() < deadline:
+ transcript = app.client.get(f"/api/sessions/{session_id}/messages?tail=1")
+ assert transcript.status == 200, transcript.json()
+ result = next((row for row in transcript.json()["messages"] if row["type"] == "result"), None)
+ if result is not None or any(item["path"].startswith("/v1/messages") for item in native.requests()):
+ break
+ time.sleep(0.1)
+ native_calls = [item for item in native.requests() if item["path"].startswith("/v1/messages")]
+ assert native_calls == [], "Claude bypassed Model Hub using native settings"
+ captured = [item for item in mock_llm_upstream.requests() if item["path"] == "/v1/responses"]
+ assert captured, app.diagnostics()
+ assert all(item["body"]["model"] == routed_model for item in captured)
+ assert all(_request_credential(item) == SYNTHETIC_API_KEY for item in captured)
+ assert result is not None, app.diagnostics()
+ assert result["text"] == "mock response"
+ provenance = app.client.get(f"/api/models/turns/{result['metadata']['turn_id']}/provenance")
+ assert provenance.status == 200, provenance.json()
+ attribution = provenance.json()["provenance"]
+ assert attribution["requested_model_id"] == menu_model
+ assert attribution["outcome"] == "served"
+ assert attribution["served"]["source_id"] == supplied["id"]
+ assert attribution["served"]["configured_model_id"] == routed_model
+ assert attribution["served"]["channel"] == "hub"
+ assert native_settings.read_text() == native_payload
+
+
def _seed_codex_native_login(home) -> None:
_write(
home / ".codex" / "auth.json",
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index ec8ddf7a3..13a4fce1d 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -132,6 +132,7 @@ capabilities:
- tests/e2e/test_model_hub_migration.py
- tests/e2e/test_model_hub_mock_upstream.py
- tests/e2e/test_model_hub_routing.py
+ - tests/e2e/test_model_hub_backend_settings.py
- tests/e2e/test_model_hub_runtime.py
- tests/e2e/test_model_hub_sources.py
- tests/e2e/test_model_hub_usage_events.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 04af7cdeb..198dee075 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -32,6 +32,7 @@ capability:
- tests/e2e/test_model_hub_migration.py
- tests/e2e/test_model_hub_mock_upstream.py
- tests/e2e/test_model_hub_routing.py
+ - tests/e2e/test_model_hub_backend_settings.py
- tests/e2e/test_model_hub_runtime.py
- tests/e2e/test_model_hub_sources.py
- tests/e2e/test_model_hub_usage_events.py
@@ -173,6 +174,24 @@ scenarios:
layer: contract
missing_layer: scenario
test: tests/test_model_hub_injection.py::test_codex_hub_launch_uses_responses_wire_api_and_ephemeral_token
+ - id: MH-CLAUDE-LAUNCH-001
+ name: Claude Hub turns preserve the configured Source and model despite native connection settings
+ status: covered
+ kind: injection
+ layer: e2e
+ test: tests/e2e/test_model_hub_routing.py::test_mh_claude_launch_001_settings_cannot_bypass_the_configured_route
+ - id: MH-CODEX-LAUNCH-001
+ name: Native Codex provider settings preserve the configured Hub Source and upstream model
+ status: covered
+ kind: injection
+ layer: e2e
+ test: tests/e2e/test_model_hub_backend_settings.py::test_codex_native_provider_settings_cannot_change_hub_egress
+ - id: MH-OPENCODE-LAUNCH-001
+ name: Native OpenCode settings preserve the exact Hub provider transport and authentication
+ status: covered
+ kind: injection
+ layer: e2e
+ test: tests/e2e/test_model_hub_backend_settings.py::test_opencode_native_settings_cannot_change_hub_transport
- id: MH-AC29-001
name: A persisted import-shaped Source survives canonical serialization and reload
status: covered
diff --git a/tests/scenarios/model_hub/observations.yaml b/tests/scenarios/model_hub/observations.yaml
index bd1977f98..6bcd09c00 100644
--- a/tests/scenarios/model_hub/observations.yaml
+++ b/tests/scenarios/model_hub/observations.yaml
@@ -1,6 +1,17 @@
version: 2
capability: model_hub
observations:
+ - id: MH-OBS-007
+ source: opencode-1.18.18-codex-0.153.2-local-http-regression-2026-09-06
+ summary: OpenCode inline config deep-merges provider and model headers, allowing native Authorization headers to replace the Hub token even when baseURL and apiKey are pinned. The managed runtime config hook must replace complete Hub provider definitions. Codex native and same-name provider fixtures retained the configured Source credential and upstream model on the wire.
+ affects:
+ - MH-CODEX-LAUNCH-001
+ - MH-OPENCODE-LAUNCH-001
+ - id: MH-OBS-006
+ source: claude-sdk-0.2.93-local-http-regression-2026-09-06
+ summary: Native project and local settings override subprocess environment; when cwd is HOME the user settings file is also a project source. Hub connection settings require a higher-priority launch override, and SDK sandbox merging must not expand credentials into argv.
+ affects:
+ - MH-CLAUDE-LAUNCH-001
- id: MH-OBS-001
source: engine-survey-s1
summary: The adapter owns one Source call while the configured route executor owns cross-Source fallback.
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index ab8932fb0..a51715132 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -236,6 +236,45 @@ def test_session_handler_uses_native_cli_launch_reasoning_catalog(
assert captured["options"].env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "32000"
+def test_session_handler_pins_hub_connection_in_launch_settings(monkeypatch, tmp_path: Path) -> None:
+ import json
+ from modules.agents.model_hub import ModelHubLaunch
+
+ captured = {}
+
+ class Client:
+ def __init__(self, options):
+ captured["options"] = options
+
+ async def connect(self):
+ pass
+
+ class Runtime:
+ async def resolve(self, backend, requested_model, **kwargs):
+ return ModelHubLaunch(
+ backend=backend, channel="hub", requested_model=requested_model,
+ target_model="gpt-6-astra", runtime_model=requested_model,
+ source_id="src_hubsettings", gateway_base_url="http://127.0.0.1:18443/claude",
+ gateway_token="hub-settings-fixture-token",
+ )
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", Client)
+ controller = _Controller(tmp_path)
+ controller.model_hub_runtime = Runtime()
+ controller.settings_manager.get_channel_routing = lambda _: RoutingSettings(model="claude-opus-5")
+ _run_session(SessionHandler(controller), MessageContext(user_id="U123", channel_id="C123"))
+
+ options = captured["options"]
+ settings = json.loads(options.settings)
+ assert settings["env"]["ANTHROPIC_BASE_URL"] == options.env["ANTHROPIC_BASE_URL"]
+ assert settings["env"]["ANTHROPIC_AUTH_TOKEN"] == "hub-settings-fixture-token"
+ assert settings["env"]["ANTHROPIC_API_KEY"] == ""
+ assert settings["autoMemoryEnabled"] is False
+ assert options.setting_sources == ["project", "local"]
+ assert options.extra_args["model"] == "claude-opus-5"
+
+
def test_session_handler_recreates_cached_claude_client_when_catalog_limits_change(
monkeypatch,
tmp_path: Path,
diff --git a/tests/test_claude_sdk_compat.py b/tests/test_claude_sdk_compat.py
index 8dcd7e740..8aa49fed6 100644
--- a/tests/test_claude_sdk_compat.py
+++ b/tests/test_claude_sdk_compat.py
@@ -1,6 +1,8 @@
import asyncio
import builtins
import importlib.util
+import json
+import stat
from pathlib import Path
import pytest
@@ -14,6 +16,84 @@ requires_claude_sdk = pytest.mark.skipif(
)
+@requires_claude_sdk
+async def test_launch_env_stays_out_of_argv_and_is_cleaned_after_disconnect(monkeypatch):
+ from claude_agent_sdk._internal.transport.subprocess_cli import SubprocessCLITransport
+
+ token = "private-launch-settings-token"
+ payload = {"autoMemoryEnabled": False, "env": {"ANTHROPIC_AUTH_TOKEN": token}}
+ options = compat.ClaudeAgentOptions(
+ settings=json.dumps(payload), sandbox={"enabled": False}, cli_path="/fixture/claude",
+ )
+ files = []
+
+ async def connect(client, prompt=None):
+ path = Path(client.options.settings)
+ files.append(path)
+ assert stat.S_IMODE(path.stat().st_mode) == 0o600
+ assert stat.S_IMODE(path.parent.stat().st_mode) == 0o700
+ assert json.loads(path.read_text()) == {**payload, "sandbox": {"enabled": False}}
+ transport = SubprocessCLITransport(prompt="", options=client.options)
+ argv = transport._build_command()
+ assert argv[argv.index("--settings") + 1] == str(path)
+ assert token not in " ".join(argv)
+ assert options.settings == json.dumps(payload)
+ assert options.sandbox == {"enabled": False}
+
+ async def disconnect(client):
+ assert Path(client.options.settings).exists()
+
+ monkeypatch.setattr(compat._ClaudeSDKClient, "connect", connect)
+ monkeypatch.setattr(compat._ClaudeSDKClient, "disconnect", disconnect)
+ client = compat.ClaudeSDKClient(options=options)
+ for _ in range(2):
+ await client.connect()
+ assert files[-1].exists()
+ await client.disconnect()
+ assert not files[-1].parent.exists()
+ assert client.options is options
+ assert files[0] != files[1]
+
+
+@requires_claude_sdk
[email protected]("error", [RuntimeError, asyncio.CancelledError])
[email protected]("stage", ["connect", "disconnect"])
+async def test_launch_settings_cleanup_covers_failure_and_cancellation(monkeypatch, error, stage):
+ options = compat.ClaudeAgentOptions(settings='{"env":{"ANTHROPIC_AUTH_TOKEN":"fixture"}}')
+ files = []
+
+ async def connect(client, prompt=None):
+ files.append(Path(client.options.settings))
+ if stage == "connect":
+ raise error("connect interrupted")
+
+ async def disconnect(client):
+ raise error("disconnect interrupted")
+
+ monkeypatch.setattr(compat._ClaudeSDKClient, "connect", connect)
+ monkeypatch.setattr(compat._ClaudeSDKClient, "disconnect", disconnect)
+ client = compat.ClaudeSDKClient(options=options)
+ with pytest.raises(error):
+ await client.connect()
+ await client.disconnect()
+ assert not files[0].parent.exists()
+ assert client.options is options
+
+
+@requires_claude_sdk
+async def test_launch_settings_preserve_native_options_without_env(monkeypatch):
+ options = compat.ClaudeAgentOptions(settings='{"autoMemoryEnabled":false}', sandbox={"enabled": False})
+
+ async def connect(client, prompt=None):
+ assert client.options is options
+
+ monkeypatch.setattr(compat._ClaudeSDKClient, "connect", connect)
+ await compat.ClaudeSDKClient(options=options).connect()
+
+
class _FakeQuery:
def __init__(self, messages):
self._messages = messages
diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.py
index 492a1bd48..24114da13 100644
--- a/tests/test_model_hub_injection.py
+++ b/tests/test_model_hub_injection.py
@@ -22,6 +22,7 @@ from modules.agents.model_hub import (
bind_launch,
bind_persisted_launch,
claude_setting_sources_for_launch,
+ claude_settings_for_launch,
launch_for_context,
opencode_model_for_overlay,
opencode_requested_model_for_overlay,
@@ -138,10 +139,54 @@ def test_hub_launch_masks_inherited_claude_auth_and_injects_gateway():
assert env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"
assert env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "128000"
assert env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "32000"
- assert "CLAUDE_CODE_OAUTH_TOKEN" not in env
+ assert env["CLAUDE_CODE_OAUTH_TOKEN"] == ""
assert claude_setting_sources_for_launch(launch) == ["project", "local"]
+def test_claude_hub_settings_own_connection_after_native_and_sdk_env_merges():
+ launch = hub_launch()
+ inherited = {
+ "ANTHROPIC_API_KEY": "parent-key",
+ "ANTHROPIC_AUTH_TOKEN": "parent-token",
+ "ANTHROPIC_BASE_URL": "https://parent.example",
+ "ANTHROPIC_CUSTOM_HEADERS": "Authorization: Bearer other-key",
+ "CLAUDE_CODE_OAUTH_TOKEN": "parent-oauth",
+ "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR": "3",
+ "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR": "4",
+ "CLAUDE_CODE_USE_BEDROCK": "1",
+ "CLAUDE_CODE_USE_VERTEX": "1",
+ "CLAUDE_CODE_USE_FOUNDRY": "1",
+ "PATH": "/bin",
+ }
+ settings = json.loads(claude_settings_for_launch('{"autoMemoryEnabled":false}', launch))
+ subprocess_env = {**inherited, **build_claude_hub_env(inherited, launch)}
+ effective_env = {**subprocess_env, **inherited, **settings["env"]}
+
+ assert effective_env["ANTHROPIC_BASE_URL"] == launch.gateway_base_url
+ assert effective_env["ANTHROPIC_AUTH_TOKEN"] == launch.gateway_token
+ for key in inherited.keys() - {"ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "PATH"}:
+ assert effective_env[key] == ""
+ assert effective_env["PATH"] == "/bin"
+ assert settings["autoMemoryEnabled"] is False
+ assert settings["apiKeyHelper"] == ""
+
+
[email protected]("channel", [None, "direct", "native_cli"])
+def test_claude_native_settings_are_unchanged_without_a_hub_launch(channel):
+ settings = '{"autoMemoryEnabled":false}'
+ launch = hub_launch(channel=channel) if channel is not None else None
+ assert claude_settings_for_launch(settings, launch) == settings
+
+
[email protected]("missing", ["gateway_base_url", "gateway_token"])
+def test_claude_hub_launch_cannot_fall_back_to_native_auth(missing):
+ launch = hub_launch(**{missing: None})
+ with pytest.raises(ModelHubError, match="engine_down"):
+ build_claude_hub_env({"ANTHROPIC_AUTH_TOKEN": "native-token"}, launch)
+ with pytest.raises(ModelHubError, match="engine_down"):
+ claude_settings_for_launch("{}", launch)
+
+
def test_native_cli_launch_keeps_auth_and_applies_catalog_limits():
launch = hub_launch(
channel="native_cli",
diff --git a/tests/test_opencode_caller_context.py b/tests/test_opencode_caller_context.py
index 39cffa2a6..b2af22e09 100644
--- a/tests/test_opencode_caller_context.py
+++ b/tests/test_opencode_caller_context.py
@@ -90,6 +90,50 @@ process.stdout.write(JSON.stringify(output.system))
assert json.loads(direct.stdout) == [native, managed]
[email protected]("hub_mode", [True, False])
+def test_plugin_keeps_hub_provider_definitions_exact_after_native_merge(tmp_path, monkeypatch, hub_mode):
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("Node.js is required to execute the OpenCode runtime plugin")
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ plugin = bridge.ensure_plugin_installed().path
+ overlay = {
+ "enabled_providers": ["avibe-openai"],
+ "provider": {"avibe-openai": {
+ "npm": "@ai-sdk/openai",
+ "options": {"baseURL": "http://127.0.0.1:18443/v1", "apiKey": "fixture-token"},
+ "models": {"menu-model": {"id": "menu-model"}},
+ }},
+ }
+ native = {
+ "provider": {
+ "avibe-openai": {
+ "options": {"headers": {"AUTHORIZATION": "stale-key"}},
+ "models": {"menu-model": {"headers": {"x-api-key": "stale-key"}}},
+ "future_transport_field": "unowned",
+ },
+ "user-owned": {"options": {"apiKey": "native-token"}},
+ },
+ "permission": "ask",
+ "agent": {"custom": {"prompt": "Keep native configuration"}},
+ }
+ script = f"""
+import {{ AvibeCallerContextPlugin }} from {json.dumps(plugin.as_uri())}
+const hooks = await AvibeCallerContextPlugin()
+const config = {json.dumps(native)}
+await hooks.config(config)
+process.stdout.write(JSON.stringify(config))
+"""
+ completed = subprocess.run(
+ [node, "--input-type=module", "--eval", script],
+ check=True, capture_output=True, text=True, timeout=10,
+ env={**os.environ, "AVIBE_OPENCODE_MODEL_HUB": "1" if hub_mode else "0",
+ "OPENCODE_CONFIG_CONTENT": json.dumps(overlay)},
+ )
+ expected = {**native, "provider": {**native["provider"], **overlay["provider"]}} if hub_mode else native
+ assert json.loads(completed.stdout) == expected
+
+
def test_bind_session_writes_env_binding(tmp_path: Path, monkeypatch) -> None:
avibe_home = tmp_path / "avibe"
monkeypatch.setenv("AVIBE_HOME", str(avibe_home))
diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.py
index c6498b9d3..fb503eb3f 100644
--- a/tests/test_opencode_server.py
+++ b/tests/test_opencode_server.py
@@ -196,7 +196,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
patch.object(SERVER_MODULE.time, "monotonic", side_effect=[0.0, 0.0, 61.0]),
patch.object(SERVER_MODULE, "server_environment", return_value={}),
patch.object(SERVER_MODULE, "terminate_process_tree", terminate),
- patch.dict(os.environ, {"OPENCODE_CONFIG_CONTENT": user_config}),
+ patch.dict(os.environ, {"OPENCODE_CONFIG_CONTENT": user_config, "AVIBE_OPENCODE_MODEL_HUB": "1"}),
):
with self.assertRaisesRegex(RuntimeError, "failed to start within 60s"):
await manager._start_server()
@@ -208,6 +208,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
terminate_timeout=5,
)
self.assertEqual(manager._clear_pid_file.call_count, 2)
+ self.assertEqual(create_process.await_args.kwargs["env"]["AVIBE_OPENCODE_MODEL_HUB"], "0")
self.assertIsNone(manager._process)
self.assertIsNone(manager._process_loop)
self.assertEqual(
@@ -650,6 +651,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(base_url, "http://127.0.0.1:4096")
prepare_overlay.assert_awaited_once_with()
self.assertEqual(launched["env"]["OPENCODE_CONFIG"], str(overlay.path))
+ self.assertEqual(launched["env"]["AVIBE_OPENCODE_MODEL_HUB"], "1")
inline_config = json.loads(launched["env"]["OPENCODE_CONFIG_CONTENT"])
self.assertEqual(
inline_config["provider"]["avibe-openai"]["models"],