Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): complete OpenCode Gateway turns (#1878)
Call Whited5bd8d1cda7c
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 783c314b7..c5f83479c 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -109,9 +109,10 @@ _CALLER_CONTEXT_ENV_SNAPSHOT_KEY = "opencode_caller_context_env"_MANAGED_SKILL_PROJECT_BASE_SNAPSHOT_KEY = "opencode_managed_skill_project_base"_MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY = "opencode_managed_skill_builtin_snapshot"_STATUS_RECONCILIATION_FAILURE_LIMIT = 3-# OpenCode returns 204 after forking prompt work, before that worker necessarily-# registers the session as busy.-_ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS = 5.0+# A successful prompt_async response transfers ownership to a forked worker,+# but does not prove that worker will publish its first message. Keep this+# handoff bounded independently of the optional whole-turn timeout.+_ASYNC_PROMPT_ACCEPTED_ACTIVITY_TIMEOUT_SECONDS = 120.0# OpenCode can report idle just before the completed assistant message becomes# visible through the message-list endpoint._ASYNC_PROMPT_RESULT_CONFIRMATION_TIMEOUT_SECONDS = 5.0@@ -162,7 +163,8 @@ class _OpenCodeSteerState:closing: bool = Falseawaiting_after_message_ids: set[str] | None = Noneawaiting_user_text: str | None = None- awaiting_start_confirmation_deadline: float | None = None+ awaiting_prompt_accepted: bool = False+ awaiting_prompt_activity_deadline: float | None = Noneawaiting_active_status_observed: bool = Falseawaiting_result_confirmation_deadline: float | None = Noneidle_reconciliation_message: str = ""@@ -364,7 +366,8 @@ class _SteeringAwareOpenCodeServer:def _clear_awaiting_reconciliation(self) -> None:self._state.awaiting_after_message_ids = Noneself._state.awaiting_user_text = None- self._state.awaiting_start_confirmation_deadline = None+ self._state.awaiting_prompt_accepted = False+ self._state.awaiting_prompt_activity_deadline = Noneself._state.awaiting_active_status_observed = Falseself._state.awaiting_result_confirmation_deadline = None@@ -531,6 +534,8 @@ class _SteeringAwareOpenCodeServer:< 0))+ if not inserted_user_missing:+ self._state.awaiting_active_status_observed = Truelast_message_id = (messages[-1].get("info", {}).get("id")if messages@@ -540,8 +545,7 @@ class _SteeringAwareOpenCodeServer:inserted_user_missingand final_snapshotand last_message_id in awaiting- and self._state.awaiting_start_confirmation_deadline- is None+ and not self._state.awaiting_prompt_accepted):self._clear_awaiting_reconciliation()self._state.closing = True@@ -564,16 +568,7 @@ class _SteeringAwareOpenCodeServer:if has_final_insert_result:self._state.closing = Truereturn messages- start_deadline = (- self._state.awaiting_start_confirmation_deadline- )- if (- start_deadline is not None- and not self._state.awaiting_active_status_observed- and time.monotonic() < start_deadline- ):- wait_for_insert = True- elif self._state.awaiting_active_status_observed:+ if self._state.awaiting_active_status_observed:result_deadline = (self._state.awaiting_result_confirmation_deadline)@@ -593,6 +588,31 @@ class _SteeringAwareOpenCodeServer:name="NativeSessionEndedBeforeResult",message=self._idle_reconciliation_error_text(),)+ elif self._state.awaiting_prompt_accepted:+ # A successful prompt_async response transfers+ # ownership before OpenCode must publish a+ # message or mark the session busy.+ activity_deadline = (+ self._state.awaiting_prompt_activity_deadline+ )+ if activity_deadline is None:+ activity_deadline = (+ time.monotonic()+ + _ASYNC_PROMPT_ACCEPTED_ACTIVITY_TIMEOUT_SECONDS+ )+ self._state.awaiting_prompt_activity_deadline = (+ activity_deadline+ )+ if time.monotonic() < activity_deadline:+ wait_for_insert = True+ else:+ self._clear_awaiting_reconciliation()+ return self._terminal_reconciliation_failure(+ session_id,+ messages,+ name="NativeSessionEndedBeforeResult",+ message=self._idle_reconciliation_error_text(),+ )else:self._clear_awaiting_reconciliation()return self._terminal_reconciliation_failure(@@ -660,12 +680,17 @@ class _SteeringAwareOpenCodeServer:if snapshot_ids is not None:self._state.awaiting_after_message_ids = set(snapshot_ids)self._state.awaiting_user_text = prompt_text or None- self._state.awaiting_start_confirmation_deadline = (- time.monotonic() + _ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS- )+ self._state.awaiting_prompt_accepted = False+ self._state.awaiting_prompt_activity_deadline = Noneself._state.awaiting_active_status_observed = Falseself._state.awaiting_result_confirmation_deadline = Noneawait self._server.prompt_async(*args, **{k: v for k, v in kwargs.items() if k != "awaiting_after_ids"})+ if snapshot_ids is not None:+ self._state.awaiting_prompt_accepted = True+ self._state.awaiting_prompt_activity_deadline = (+ time.monotonic()+ + _ASYNC_PROMPT_ACCEPTED_ACTIVITY_TIMEOUT_SECONDS+ )async def abort_session(self, *args, **kwargs) -> bool:async with self._state.lock:@@ -1673,9 +1698,10 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):baseline_message_ids=set(baseline_message_ids),awaiting_after_message_ids=set(baseline_message_ids),awaiting_user_text=prompt_text,- awaiting_start_confirmation_deadline=(+ awaiting_prompt_accepted=True,+ awaiting_prompt_activity_deadline=(time.monotonic()- + _ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS+ + _ASYNC_PROMPT_ACCEPTED_ACTIVITY_TIMEOUT_SECONDS),idle_reconciliation_message=self._idle_reconciliation_message(display_model_dict,@@ -2054,14 +2080,16 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):except (asyncio.TimeoutError, TimeoutError, aiohttp.ClientConnectionError):state.awaiting_after_message_ids = before_insertstate.awaiting_user_text = request.text- state.awaiting_start_confirmation_deadline = None+ state.awaiting_prompt_accepted = False+ state.awaiting_prompt_activity_deadline = Nonestate.awaiting_active_status_observed = Falseraisestate.awaiting_after_message_ids = before_insertstate.awaiting_user_text = request.text- state.awaiting_start_confirmation_deadline = (+ state.awaiting_prompt_accepted = True+ state.awaiting_prompt_activity_deadline = (time.monotonic()- + _ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS+ + _ASYNC_PROMPT_ACCEPTED_ACTIVITY_TIMEOUT_SECONDS)state.awaiting_active_status_observed = Falseawait asyncio.sleep(_STEER_POST_WRITE_STATUS_SETTLE_SECONDS)diff --git a/tests/e2e/drivers/mock_llm_upstream.py b/tests/e2e/drivers/mock_llm_upstream.pyindex 3b650a237..4fec75afb 100644--- a/tests/e2e/drivers/mock_llm_upstream.py+++ b/tests/e2e/drivers/mock_llm_upstream.py@@ -151,6 +151,15 @@ OPENCODE_V4_S4_VARIANT_FIXTURES = {"output_config": {"effort": "high"},},},+ "responses_to_openai_chat": {+ "protocol": "openai_chat",+ "frontend_protocol": "openai_responses",+ "stored_model": "deepseek-v3.2",+ "variant": {"reasoningEffort": "high"},+ "upstream_fragment": {+ "reasoning_effort": "high",+ },+ },}CAPTURED_HEADER_NAMES = ("accept",diff --git a/tests/e2e/test_model_hub_mock_upstream.py b/tests/e2e/test_model_hub_mock_upstream.pyindex 112af44ee..2172b91c7 100644--- a/tests/e2e/test_model_hub_mock_upstream.py+++ b/tests/e2e/test_model_hub_mock_upstream.py@@ -250,7 +250,9 @@ def _send_through_opencode_gateway_engine(native_protocol: str,stored_model: str,variant: dict[str, Any],-) -> dict[str, Any]:+ prompt_start_delay_seconds: float = 0,+ require_terminal_result: bool = False,+) -> tuple[dict[str, Any], dict[str, Any] | None]:binary = shutil.which("opencode")if binary is None:pytest.skip("OpenCode executable is unavailable")@@ -259,11 +261,11 @@ def _send_through_opencode_gateway_engine(if native_protocol == "anthropic"else "deepseek-v3.2")- upstream_path = (- "/v1/messages"- if upstream_protocol == "anthropic"- else "/v1/responses"- )+ upstream_path = {+ "anthropic": "/v1/messages",+ "openai_responses": "/v1/responses",+ "openai_chat": "/v1/chat/completions",+ }[upstream_protocol]with _engine_app(model_hub_app_factory) as app:configured = app.client.post("/api/config",@@ -378,6 +380,17 @@ def _send_through_opencode_gateway_engine(},)assert agent.status == 200, agent.json()+ if prompt_start_delay_seconds > 0:+ plugin_dir = app.runtime_root / ".opencode" / "plugins"+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "delay-prompt.js").write_text(+ "export const DelayPrompt = async () => ({\n"+ ' "chat.message": async () => {\n'+ f" await Bun.sleep({prompt_start_delay_seconds * 1000});\n"+ " },\n"+ "});\n",+ encoding="utf-8",+ )project = app.client.post("/api/projects",{@@ -412,8 +425,9 @@ def _send_through_opencode_gateway_engine({"text": "hello"},)assert sent.status == 202, sent.json()- deadline = time.monotonic() + 30+ deadline = time.monotonic() + 60captured: list[dict[str, Any]] = []+ result: dict[str, Any] | None = Nonewhile time.monotonic() < deadline:captured = [request@@ -422,10 +436,29 @@ def _send_through_opencode_gateway_engine(and "You are a title generator"not in json.dumps(request["body"], sort_keys=True)]- if captured:+ if require_terminal_result:+ transcript = app.client.get(+ f"/api/sessions/{session.json()['id']}/messages?tail=1"+ )+ assert transcript.status == 200, transcript.json()+ result = next(+ (+ row+ for row in reversed(transcript.json()["messages"])+ if row["type"] == "result"+ ),+ None,+ )+ if captured and (result is not None or not require_terminal_result):breaktime.sleep(0.1)assert len(captured) == 1, app.diagnostics()+ if require_terminal_result:+ assert result is not None, app.diagnostics()+ assert result["text"] == "mock response", {+ "result": result,+ "diagnostics": app.diagnostics(),+ }overlay = json.loads((app.avibe_home@@ -484,7 +517,7 @@ def _send_through_opencode_gateway_engine(assert set(live_providers["avibe-anthropic"]["models"]) == {"claude-opus-5"}- return captured[0]["body"]+ return captured[0]["body"], result@pytest.mark.parametrize(@@ -524,16 +557,63 @@ def test_opencode_v4_s4_variant_shapes_are_frozen_against_mock_capture(mock_llm_upstream,fixture: dict[str, Any],) -> None:- captured_body = _send_through_opencode_gateway_engine(+ captured_body, _ = _send_through_opencode_gateway_engine(+ model_hub_app_factory,+ mock_llm_upstream,+ upstream_protocol=fixture["protocol"],+ native_protocol=fixture["frontend_protocol"],+ stored_model=fixture["stored_model"],+ variant=fixture["variant"],+ )++ assert captured_body["model"] == fixture["stored_model"]+ for key, value in fixture["upstream_fragment"].items():+ assert captured_body.get(key) == value, captured_body+++def test_opencode_responses_turn_completes_through_openai_chat_upstream(+ model_hub_app_factory,+ mock_llm_upstream,+) -> None:+ fixture = OPENCODE_V4_S4_VARIANT_FIXTURES["responses_to_openai_chat"]++ captured_body, result = _send_through_opencode_gateway_engine(+ model_hub_app_factory,+ mock_llm_upstream,+ upstream_protocol=fixture["protocol"],+ native_protocol=fixture["frontend_protocol"],+ stored_model=fixture["stored_model"],+ variant=fixture["variant"],+ require_terminal_result=True,+ )++ assert captured_body["model"] == fixture["stored_model"]+ assert result is not None+ assert result["text"] == "mock response"+ for key, value in fixture["upstream_fragment"].items():+ assert captured_body.get(key) == value, captured_body+++def test_opencode_anthropic_turn_waits_for_accepted_prompt_worker(+ model_hub_app_factory,+ mock_llm_upstream,+) -> None:+ fixture = OPENCODE_V4_S4_VARIANT_FIXTURES["anthropic_same_protocol"]++ captured_body, result = _send_through_opencode_gateway_engine(model_hub_app_factory,mock_llm_upstream,upstream_protocol=fixture["protocol"],native_protocol=fixture["frontend_protocol"],stored_model=fixture["stored_model"],variant=fixture["variant"],+ prompt_start_delay_seconds=6.5,+ require_terminal_result=True,)assert captured_body["model"] == fixture["stored_model"]+ assert result is not None+ assert result["text"] == "mock response"for key, value in fixture["upstream_fragment"].items():assert captured_body.get(key) == value, captured_bodydiff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.pyindex ce9c0d951..19f386093 100644--- a/tests/test_agent_steering.py+++ b/tests/test_agent_steering.py@@ -647,8 +647,9 @@ async def test_opencode_steers_existing_runner_without_abort_or_new_turn() -> Noassert receipt.outcome is SteerOutcome.ACCEPTEDstate = agent._steering_states[primary.base_session_id]assert state.awaiting_user_text == STEER_TEXT- assert state.awaiting_start_confirmation_deadline is not None- assert state.awaiting_start_confirmation_deadline > time.monotonic()+ assert state.awaiting_prompt_accepted is True+ assert state.awaiting_prompt_activity_deadline is not None+ assert state.awaiting_prompt_activity_deadline > time.monotonic()assert state.awaiting_active_status_observed is Falseassert server.prompt_calls == [{@@ -694,7 +695,8 @@ async def test_opencode_keeps_reconciliation_armed_after_post_write_idle() -> Noassert receipt.reason == "native_turn_start_pending"assert state.awaiting_user_text == STEER_TEXTassert state.awaiting_after_message_ids == {"primary-user"}- assert state.awaiting_start_confirmation_deadline is not None+ assert state.awaiting_prompt_accepted is True+ assert state.awaiting_prompt_activity_deadline is not Noneassert server.abort_calls == []finally:await _cancel_tasks(gate_task)@@ -1045,8 +1047,9 @@ async def test_opencode_coordinator_error_aborts_through_steering_owner(await poll_started.wait()state = agent._steering_states[primary.base_session_id]assert state.awaiting_user_text == primary.message- assert state.awaiting_start_confirmation_deadline is not None- assert state.awaiting_start_confirmation_deadline > time.monotonic()+ assert state.awaiting_prompt_accepted is True+ assert state.awaiting_prompt_activity_deadline is not None+ assert state.awaiting_prompt_activity_deadline > time.monotonic()assert state.awaiting_active_status_observed is Falsetarget = ActiveSteerTarget(runtime_key=primary.base_session_id,@@ -1497,7 +1500,7 @@ async def test_opencode_regular_turn_streams_snapshot_while_busy() -> None:state = agent._steering_states[primary.base_session_id]state.awaiting_after_message_ids = {"baseline-user"}state.awaiting_user_text = "primary"- state.awaiting_start_confirmation_deadline = time.monotonic() + 5.0+ state.awaiting_prompt_accepted = Truepoll_server = _SteeringAwareOpenCodeServer(server, state)try:intermediate = await asyncio.wait_for(@@ -1552,7 +1555,7 @@ async def test_opencode_regular_turn_waits_for_unconfirmed_start() -> None:state = agent._steering_states[primary.base_session_id]state.awaiting_after_message_ids = {"primary-user"}state.awaiting_user_text = "primary"- state.awaiting_start_confirmation_deadline = time.monotonic() + 5.0+ state.awaiting_prompt_accepted = Truepoll_server = _SteeringAwareOpenCodeServer(server, state)poll_task = Nonetry:@@ -1733,7 +1736,7 @@ async def test_opencode_retry_keeps_completed_error_snapshots_gated() -> None:state = agent._steering_states[primary.base_session_id]state.awaiting_after_message_ids = set()state.awaiting_user_text = "primary"- state.awaiting_start_confirmation_deadline = time.monotonic() + 5.0+ state.awaiting_prompt_accepted = Truepoll_server = _SteeringAwareOpenCodeServer(server, state)poll_task = Nonetry:@@ -1977,7 +1980,7 @@ async def test_opencode_accepted_prompt_waits_for_delayed_busy_registration() ->state.baseline_message_ids = {"primary-assistant"}state.awaiting_after_message_ids = {"primary-assistant"}state.awaiting_user_text = "follow-up"- state.awaiting_start_confirmation_deadline = time.monotonic() + 1+ state.awaiting_prompt_accepted = Truepoll_server = _SteeringAwareOpenCodeServer(server, state)try:messages = await asyncio.wait_for(@@ -2030,7 +2033,7 @@ async def test_opencode_idle_waits_for_delayed_terminal_message_visibility() ->state = agent._steering_states[primary.base_session_id]state.awaiting_after_message_ids = set()state.awaiting_user_text = "follow-up"- state.awaiting_start_confirmation_deadline = time.monotonic() - 1+ state.awaiting_prompt_accepted = Truepoll_server = _SteeringAwareOpenCodeServer(server, state)try:intermediate = await asyncio.wait_for(@@ -2058,23 +2061,65 @@ async def test_opencode_idle_waits_for_delayed_terminal_message_visibility() ->@pytest.mark.anyio-async def test_opencode_accepted_prompt_idle_start_timeout_is_terminal() -> None:+async def test_opencode_accepted_prompt_stays_owned_until_delayed_result() -> None:primary = _primary_request(backend="opencode")gate_task = await _held_task()- server = _OpenCodeServer(- messages=[- {- "info": {"id": "follow-up-user", "role": "user"},- "parts": [{"type": "text", "text": "follow-up"}],- }- ],- status={"type": "idle"},- )++ class _DelayedAcceptedPromptServer(_OpenCodeServer):+ async def list_messages(self, session_id: str, directory: str) -> list[dict]:+ if self.list_calls == 1:+ self.messages.extend(+ [+ {+ "info": {"id": "follow-up-user", "role": "user"},+ "parts": [{"type": "text", "text": "follow-up"}],+ },+ {+ "info": {+ "id": "follow-up-assistant",+ "role": "assistant",+ "time": {"completed": 2},+ "finish": "stop",+ },+ "parts": [{"type": "text", "text": "answered"}],+ },+ ]+ )+ return await super().list_messages(session_id, directory)++ server = _DelayedAcceptedPromptServer(status={"type": "idle"})+ agent = _opencode_agent(primary, gate_task, server)+ state = agent._steering_states[primary.base_session_id]+ state.awaiting_after_message_ids = set()+ state.awaiting_user_text = "follow-up"+ state.awaiting_prompt_accepted = True+ poll_server = _SteeringAwareOpenCodeServer(server, state)+ try:+ messages = await asyncio.wait_for(+ poll_server.list_messages("opencode-session", primary.working_path),+ timeout=1,+ )++ assert messages[-1]["info"]["id"] == "follow-up-assistant"+ assert state.terminal_status_failure_messages is None+ assert state.awaiting_after_message_ids is None+ assert state.closing is True+ assert server.list_calls == 2+ finally:+ await _cancel_tasks(gate_task)+++async def test_opencode_accepted_prompt_without_activity_is_bounded() -> None:+ primary = _primary_request(backend="opencode")+ gate_task = await _held_task()+ server = _OpenCodeServer(status={"type": "idle"})agent = _opencode_agent(primary, gate_task, server)state = agent._steering_states[primary.base_session_id]state.awaiting_after_message_ids = set()state.awaiting_user_text = "follow-up"- state.awaiting_start_confirmation_deadline = time.monotonic() - 1+ state.awaiting_prompt_accepted = True+ state.awaiting_prompt_activity_deadline = time.monotonic() - 1poll_server = _SteeringAwareOpenCodeServer(server, state)try:messages = await poll_server.list_messages(diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex a3bb96652..0de336426 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -15,6 +15,7 @@ from contextlib import contextmanagerfrom http.server import BaseHTTPRequestHandler, HTTPServerfrom pathlib import Pathfrom types import SimpleNamespace+from urllib.parse import urlsplitimport pytestimport yaml@@ -1506,7 +1507,7 @@ def test_config_generation_is_private_and_never_logs_secrets(assert payload["openai-compatibility"][0]["api-key-entries"][0]["api-key"] == ("upstream-secret-value")assert {entry["base-url"] for entry in payload["openai-compatibility"]- } == {"https://api.example.test/v1", "https://api.deepseek.com"}+ } == {"https://api.example.test/v1", "https://api.deepseek.com/v1"}assert len(payload["codex-api-key"]) == 2assert {entry["base-url"] for entry in payload["codex-api-key"]} == {"https://api.openai.com/v1"}responses_entry = next(@@ -1835,6 +1836,56 @@ def test_api_key_vendor_catalog_populates_runtime_official_base_urls(assert client_module._OFFICIAL_BASE_URLS[vendor] == expected_base_url+ ("base_url", "expected_base_url"),+ [+ ("https://relay.example.test", "https://relay.example.test/v1"),+ (+ "https://relay.example.test/custom/root?tenant=one",+ "https://relay.example.test/custom/root?tenant=one",+ ),+ ],+)+def test_openai_compatibility_engine_base_url_uses_configured_api_root(+ tmp_path: Path,+ base_url: str,+ expected_base_url: str,+) -> None:+ store = EngineStateStore(tmp_path / "state")+ instance_dir, runtime_secrets = store.prepare_instance("install-1")+ credential_ref = store.store_api_key(+ "secret",+ vendor="custom",+ protocol="openai_chat",+ base_url=base_url,+ )+ store.sync_sources(+ [+ _binding(+ credential_ref,+ source_id="src_custom123",+ vendor="custom",+ protocol="openai_chat",+ base_url=base_url,+ )+ ]+ )+ config_path = instance_dir / "config.yaml"++ write_engine_config(+ config_path,+ host="127.0.0.1",+ port=18231,+ auth_dir=store.auth_dir,+ runtime_secrets=runtime_secrets,+ sources=store.list_sources(),+ state_store=store,+ )++ payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))+ assert payload["openai-compatibility"][0]["base-url"] == expected_base_url++@pytest.mark.parametrize(("vendor", "protocol", "expected_base_url"),API_KEY_VENDOR_RUNTIME_CASES,@@ -1885,7 +1936,10 @@ def test_catalog_owned_api_key_sources_without_explicit_base_url_sync_and_write_if protocol == "openai_responses":assert payload["codex-api-key"][0]["base-url"] == expected_base_urlreturn- assert payload["openai-compatibility"][0]["base-url"] == expected_base_url+ expected_engine_base_url = expected_base_url+ if not urlsplit(expected_engine_base_url).path.rstrip("/"):+ expected_engine_base_url = f"{expected_engine_base_url.rstrip('/')}/v1"+ assert payload["openai-compatibility"][0]["base-url"] == expected_engine_base_urldef test_state_removes_secret_bearing_configs_on_upgrade_and_revocation(tmp_path: Path) -> None:diff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.pyindex 3ee272912..fe959d75a 100644--- a/vibe/model_hub_runtime/config.py+++ b/vibe/model_hub_runtime/config.py@@ -2,10 +2,12 @@ from __future__ import annotationsfrom pathlib import Pathfrom typing import Any, Iterable+from urllib.parse import urlsplitimport yamlfrom config.atomic_io import write_atomic+from config.v2_config import normalize_model_hub_base_urlfrom vibe.model_hub_runtime.api_key_vendors import official_api_key_base_urlfrom vibe.model_hub_runtime.state import EngineStateError, EngineStateStore, RuntimeSecrets, SourceRecord@@ -114,11 +116,21 @@ def _append_source(payload: dict[str, Any], source: SourceRecord, store: EngineSbase_url = official_api_key_base_url(source.vendor)if not base_url:raise EngineStateError("OpenAI-compatible source requires a base URL")+ normalized_base_url = normalize_model_hub_base_url(base_url)+ assert normalized_base_url is not None+ if not urlsplit(normalized_base_url).path.rstrip("/"):+ # CLIProxyAPI appends /chat/completions; Source origins use the+ # standard /v1 endpoint root used by discovery and probes.+ normalized_base_url = normalize_model_hub_base_url(+ normalized_base_url,+ append_path="/v1",+ )+ assert normalized_base_url is not Nonepayload.setdefault("openai-compatibility", []).append({"name": source.prefix,"prefix": source.prefix,- "base-url": base_url,+ "base-url": normalized_base_url,"api-key-entries": [{"api-key": api_key}],"models": models,}