From 92f3539943adac9fb32f3c80aeeea20a0185b9ef Mon Sep 17 00:00:00 2001 From: Michael Gasperini Date: Tue, 17 Nov 2026 18:46:34 +0100 Subject: [PATCH 1/2] fix(adapter): start on first use and report which adapter answered The adapter was started at import, so every process that merely loaded the plugin (the admission probe, `hermes plugins validate`, a linter) bound a loopback port and then exited, leaving the listener behind. The next process could not reuse that port, bound the following one, and every process reported a different base URL; a loopback URL captured from one process pointed at an adapter that another process owned. Start the adapter on first use instead: `runtime_base_url()` and `fetch_models()` resolve it, `register()` no longer starts one. Each process now owns exactly the adapter it reports. A refused request is also invisible today: Meta's 403 reaches the caller as a generic "authentication failed" and the adapter only logged at debug when a rule fired. Add the pieces that make the seam diagnosable: - `GET /__muse_adapter/health` returns adapter_version, pid, port, passthrough and upstream, and `python muse_adapter.py --health ` queries it, so a port held by another process or by an older plugin is distinguishable; - every relayed response carries `x-muse-adapter: `; - a response with status 400 or above logs one warning line with method, path, status, adapter version, port, pid and the rules that fired, never a body or a credential. ADAPTER_VERSION stays at 3: no wire rule changed. Refs #20 --- ADAPTER_CONTRACT.md | 14 +++ CHANGELOG.md | 22 +++++ README.md | 19 ++++ __init__.py | 39 +++++--- muse_adapter.py | 113 +++++++++++++++++++++- tests/test_muse_adapter.py | 155 +++++++++++++++++++++++++++++++ tests/test_muse_code_provider.py | 24 ++++- 7 files changed, 369 insertions(+), 17 deletions(-) diff --git a/ADAPTER_CONTRACT.md b/ADAPTER_CONTRACT.md index d5d2351..3b726bf 100644 --- a/ADAPTER_CONTRACT.md +++ b/ADAPTER_CONTRACT.md @@ -130,3 +130,17 @@ retry is logged as `gate refused; retried with all N tools aliased`. - Offline: the adapter unit and proxy tests in each repository, against a fake upstream. - Live: start the adapter against `https://api.meta.ai`, send a request with a colliding tool name, and require HTTP 200 with the original name restored in the response. + +## Diagnostics (outside the wire rules) + +`GET /__muse_adapter/health` answers before the relay rules with +`{adapter_version, pid, port, passthrough, upstream}`, and every relayed response carries +`x-muse-adapter: `. Both exist so a caller can tell whether a captured request +went through an adapter at all and, when it did, whether that adapter is the one this process +started: a port can be held by an adapter from an older plugin, by another process, or by +something unrelated. + +These additions do not change any rule above, so `ADAPTER_VERSION` stays at 3. A refused request +(HTTP 400 or above) also logs one line at the host's warning level with the method, path, status, +adapter version, port, pid and the rules that fired. Neither the log line nor the health answer +carries a request body, a response body, or a credential. diff --git a/CHANGELOG.md b/CHANGELOG.md index 45c04a9..2b2c6fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,28 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- The loopback wire adapter starts on first use instead of at import. Loading the plugin without + running inference (the admission probe, `hermes plugins validate`, a linter) no longer binds a + port, and `register()` no longer starts one either. Those probes exit immediately and used to + leave the listener behind, so the next process bound the following port and every process + reported a different base URL. +- `runtime_base_url()` resolves the adapter on demand, so a process that never imported the plugin + at startup still gets its own loopback adapter when Hermes resolves the credential. + +### Added + +- `GET /__muse_adapter/health` reports `adapter_version`, `pid`, `port`, `passthrough` and + `upstream`, and `python muse_adapter.py --health ` queries it. An adapter that cannot answer + belongs to another process or to a plugin older than this release, which is what makes a stale + loopback port diagnosable. +- Every relayed response carries `x-muse-adapter: `. +- A refused request (status 400 or above) logs one warning line with the method, path, upstream + status, adapter version, port and pid, and the rules that fired. No body and no credential. + ## [0.6.4] - 2026-11-12 ### Fixed diff --git a/README.md b/README.md index 2d42747..3ee0b5b 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,25 @@ Signing in again cannot remove a client restriction (the key is not expired). Us the subscription, or a separate pay-as-you-go Meta Model API key for other clients, subject to Meta's terms. +### Requests fail with "authentication failed" + +On hosts older than 0.23 a refused request and a bad key reach the user with the same +`authentication failed` text: the 403 `client_attestation_denied` is not classified separately +until 0.23. Do not re-login first; check which adapter answered. + +The adapter starts on first use, and every process owns its own instance, so a loopback port +reported by one process is not necessarily the one in use now. Ask the port directly: + +```bash +python muse_adapter.py --health http://127.0.0.1:43219/v1 +``` + +It prints `adapter_version`, `pid`, `port`, `passthrough` and `upstream`, or says that no adapter +answered. A port held by an adapter without this answer belongs to another process or to an older +plugin, and that process is not the one serving the request. Every relayed response also +carries `x-muse-adapter: `, and each refused request logs one warning line with the method, +path, upstream status, adapter version, port and pid, but no body and no credential. + ### The gateway keeps the old key Since 0.6.4 the provider reads the cache when Hermes resolves the credential, so a completed login diff --git a/__init__.py b/__init__.py index ec5e937..6fffb24 100644 --- a/__init__.py +++ b/__init__.py @@ -126,11 +126,16 @@ def _adapter_base_url() -> str: imports and registrations reuse the same server. If no loopback port can be bound, keep the direct endpoint (the pre-0.6 behavior) and warn: only the exception type is logged, never credentials or payloads. + + Called lazily, never at import: a short-lived process that only loads the + plugin (the admission probe, ``hermes plugins validate``, a linter) must not + bind a loopback port. Each process owns its adapter on the first free port, + so an adapter left behind by another process is never adopted as this one's. """ if _start_adapter is None: return DEFAULT_BASE_URL try: - adapter = _start_adapter(log=logger.debug) + adapter = _start_adapter(log=logger.debug, error_log=logger.warning) except Exception as error: # noqa: BLE001 - a bind failure must not break import logger.warning( "Muse Code wire adapter unavailable (%s); using %s directly", @@ -151,14 +156,15 @@ def _refresh_base_url() -> None: def register(ctx) -> None: """PluginManager entry point (also required by `hermes plugins validate`). - Provider registration already happened at import; re-read the cache so - a login that completed after import is picked up, and retry the wire - adapter in case the first bind failed. Stdlib-only, so the admission probe - can run it in a bare interpreter. + Provider registration already happened at import; re-read the cache so a + login that completed after import is picked up. The wire adapter is started + on first use (``runtime_base_url``) rather than here: validation and + admission probes run this hook in a bare interpreter that then exits, and + an adapter started here would outlive the probe on a loopback port. Stdlib + only, so those probes can still run it. """ if _HERMES_AVAILABLE: _ensure_subscription_key() - _refresh_base_url() # Meta Model API (Muse) wire vocabulary, vendored from Hermes core @@ -254,10 +260,12 @@ def runtime_base_url( Runtime credential resolution only reads this hook, so without the override ``base_url`` is never consulted: requests go straight to - ``api.meta.ai`` and Meta answers 403. ``register()`` keeps - ``self.base_url`` on the adapter, or on the direct endpoint when the - adapter could not bind. + ``api.meta.ai`` and Meta answers 403. Resolution is also the first + moment the adapter is actually needed, so it starts here (idempotent + per process) instead of at import; ``self.base_url`` then holds that + adapter's URL, or the direct endpoint when no port could be bound. """ + _refresh_base_url() return self.base_url or None def resolve_api_key_secret(self) -> tuple[str, str] | None: @@ -287,8 +295,12 @@ def fetch_models( timeout: float = 8.0, ) -> list[str] | None: _ensure_subscription_key() + # The catalog probe is a real upstream call: resolve the adapter + # first so discovery does not bypass it. Until the adapter starts, + # base_url is the direct endpoint, not the loopback URL. + _refresh_base_url() live = super().fetch_models( - api_key=api_key, base_url=base_url, timeout=timeout + api_key=api_key, base_url=base_url or self.base_url, timeout=timeout ) if live is None: return None @@ -320,9 +332,10 @@ def build_api_kwargs_extras( description="Muse chat models billed to the local Muse Code monthly login", signup_url="https://github.com/TheStreamCode/hermes-muse-code#login-once", env_vars=(ENV_VAR,), - # Loopback wire adapter in front of api.meta.ai; DEFAULT_BASE_URL when - # the adapter could not bind and the provider runs direct. - base_url=_adapter_base_url(), + # Loopback wire adapter in front of api.meta.ai; started on first + # resolution (see runtime_base_url), DEFAULT_BASE_URL until then or when + # no port could be bound and the provider runs direct. + base_url=DEFAULT_BASE_URL, auth_type="api_key", auth_handler=_auth_handler, classify_api_error=_classify_client_restriction, diff --git a/muse_adapter.py b/muse_adapter.py index 42056ef..495779a 100644 --- a/muse_adapter.py +++ b/muse_adapter.py @@ -104,6 +104,11 @@ # Ports tried in order, so a persisted base URL stays stable across restarts. DEFAULT_PORTS = (43219, 43220, 43221, 43222) +# Diagnostic endpoint. It answers before the relay rules, so a caller can tell +# which adapter owns a port: this process' adapter, a stale one from an older +# plugin, or something else entirely. Not part of the wire contract. +HEALTH_PATH = "/__muse_adapter/health" + _JsonRecord = dict[str, Any] @@ -412,6 +417,7 @@ class _AdapterConfig: upstream: str passthrough: bool log: Callable[[str], None] | None + error_log: Callable[[str], None] | None = None class _AdapterServer(http.server.ThreadingHTTPServer): @@ -443,6 +449,22 @@ def _log(config: _AdapterConfig, message: str) -> None: pass +def _log_error(config: _AdapterConfig, message: str) -> None: + """Report a failed request at the host's warning level. + + A refused request must be visible without the caller turning on debug + logging: Meta's errors reach the caller as a bare "authentication failed", + and this line is the only place that records the upstream status and which + adapter answered. It never carries request or response bodies. + """ + if config.error_log is None: + return + try: + config.error_log(message) + except Exception: # noqa: BLE001 - diagnostics must never break a request + pass + + class _AdapterHandler(http.server.BaseHTTPRequestHandler): """One proxied request: adapt the request, relay the answer, restore names.""" @@ -462,8 +484,31 @@ def handle_expect_100(self) -> bool: return True def do_GET(self) -> None: # noqa: N802 - stdlib handler naming + if urllib.parse.urlsplit(self.path).path == HEALTH_PATH: + self._serve_health() + return self._handle() + def _serve_health(self) -> None: + """Report which adapter this is, without touching upstream or credentials.""" + config: _AdapterConfig = self.server.config # type: ignore[attr-defined] + payload = json.dumps( + { + "adapter_version": ADAPTER_VERSION, + "pid": os.getpid(), + "port": int(self.server.server_address[1]), # type: ignore[attr-defined] + "passthrough": config.passthrough, + "upstream": config.upstream, + }, + separators=(",", ":"), + ).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(payload))) + self.send_header("x-muse-adapter", str(ADAPTER_VERSION)) + self.end_headers() + self.wfile.write(payload) + def do_POST(self) -> None: # noqa: N802 - stdlib handler naming self._handle() @@ -484,7 +529,7 @@ def _handle(self) -> None: self.close_connection = True except Exception as error: # noqa: BLE001 - one bad request must not kill the server config: _AdapterConfig = self.server.config # type: ignore[attr-defined] - _log(config, f"muse-code adapter error: {type(error).__name__}: {error}") + _log_error(config, f"muse-code adapter error: {type(error).__name__}: {error}") if not self._headers_sent: payload = json.dumps(_ADAPTER_ERROR).encode("utf-8") try: @@ -650,7 +695,18 @@ def send(payload: bytes) -> Any: raw_headers = getattr(upstream, "headers", None) headers = raw_headers if raw_headers is not None else {} content_type = str(headers.get("content-type") or "").lower() - if notes: + if int(status) >= 400: + # One line per refused request, at warning level: the caller only + # sees the provider's generic message, so this is the record of + # which adapter answered and what upstream returned. + rules = ", ".join(notes) if notes else "no rule fired" + _log_error( + config, + f"muse-code adapter: {method} {pathname} {status}" + f" | v{ADAPTER_VERSION} port={int(self.server.server_address[1])}" # type: ignore[attr-defined] + f" pid={os.getpid()} | {rules}", + ) + elif notes: _log( config, f"muse-code adapter: {method} {pathname} {status} | {', '.join(notes)}", @@ -730,6 +786,9 @@ def _send_upstream_headers(self, status: int, headers: Any) -> None: self._headers_sent = True def _write_upstream_headers(self, headers: Any) -> None: + # Identify the adapter on every relayed answer, so a captured response + # says whether the loopback hop happened and which version shaped it. + self.send_header("x-muse-adapter", str(ADAPTER_VERSION)) for name, value in headers.items(): if name.lower() in _RESPONSE_SKIP: continue @@ -831,6 +890,7 @@ def start_adapter( upstream: str | None = None, ports: Iterable[int] | None = None, log: Callable[[str], None] | None = None, + error_log: Callable[[str], None] | None = None, passthrough: bool | None = None, ) -> RunningAdapter: """Start the loopback adapter, or return the one already running. @@ -841,6 +901,11 @@ def start_adapter( registrations never start a duplicate server; a call with different options stops the previous adapter and replaces it. + ``log`` receives the per-request diagnostic line; ``error_log`` receives the + same shape for refused requests and defaults to ``log``. Neither callback is + part of the identity key: an already-running adapter keeps the callbacks it + was started with. + ``passthrough`` defaults to ``MUSE_CODE_ADAPTER=off``: the proxy stays in place, the wire rules are skipped. """ @@ -861,6 +926,7 @@ def start_adapter( upstream=resolved_upstream, passthrough=resolved_passthrough, log=log, + error_log=error_log if error_log is not None else log, ) server: _AdapterServer | None = None last_error: OSError | None = None @@ -903,3 +969,46 @@ def stop_adapter() -> None: active = state.active if active is not None: active.close() + + +def _main(argv: list[str]) -> int: + """Ask a listening adapter which build it is: ``--health ``.""" + import argparse + + parser = argparse.ArgumentParser( + prog="muse_adapter", + description="Diagnostics for the local Muse Code wire adapter.", + ) + parser.add_argument( + "--health", + metavar="URL", + help=f"query an adapter, e.g. http://127.0.0.1:43219/v1 (GET {HEALTH_PATH})", + ) + args = parser.parse_args(argv) + if not args.health: + parser.print_help() + return 2 + + origin = args.health.strip().rstrip("/") + if origin.endswith("/v1"): + origin = origin[: -len("/v1")] + url = origin + HEALTH_PATH + try: + with urllib.request.urlopen(url, timeout=5) as response: + payload = json.loads(response.read().decode("utf-8")) + header = response.headers.get("x-muse-adapter") + except Exception as error: # noqa: BLE001 - this command reports, it does not raise + print( + f"no Muse Code adapter answered at {url} ({type(error).__name__}: {error})", + file=sys.stderr, + ) + return 1 + + if header is not None and str(payload.get("adapter_version")) != str(header): + payload["header_version"] = header + print(json.dumps(payload, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(_main(sys.argv[1:])) diff --git a/tests/test_muse_adapter.py b/tests/test_muse_adapter.py index f5b3f89..f260f2b 100644 --- a/tests/test_muse_adapter.py +++ b/tests/test_muse_adapter.py @@ -7,7 +7,9 @@ import http.server import importlib.util import json +import os import socket +import subprocess import sys import threading import urllib.error @@ -607,3 +609,156 @@ def test_a_busy_candidate_port_falls_through_to_the_next_one(): running.close() finally: blocker.close() + + +def _health_url(base_url): + return base_url.rsplit("/v1", 1)[0] + adapter.HEALTH_PATH + + +def test_health_reports_which_adapter_owns_the_port(monkeypatch): + """A port can hold this process' adapter, an older one, or something else. + + Without this answer a failing request gives no way to tell the three apart. + """ + monkeypatch.delenv(adapter.PASSTHROUGH_ENV_VAR, raising=False) + running = adapter.start_adapter(ports=(0,)) + try: + with urllib.request.urlopen(_health_url(running.base_url), timeout=5) as response: + payload = json.loads(response.read().decode("utf-8")) + assert response.headers.get("x-muse-adapter") == str(adapter.ADAPTER_VERSION) + assert payload == { + "adapter_version": adapter.ADAPTER_VERSION, + "pid": os.getpid(), + "port": running.port, + "passthrough": False, + "upstream": adapter.DEFAULT_UPSTREAM, + } + finally: + running.close() + + +def test_a_foreign_listener_on_the_first_port_is_not_adopted(): + """No process ever reuses another process' adapter as its own.""" + blocker = socket.socket() + blocker.bind(("127.0.0.1", 0)) + blocker.listen(1) + busy = blocker.getsockname()[1] + try: + running = adapter.start_adapter(ports=(busy, 0)) + try: + assert running.port != busy + with urllib.request.urlopen(_health_url(running.base_url), timeout=5) as response: + payload = json.loads(response.read().decode("utf-8")) + assert payload["pid"] == os.getpid() + assert payload["port"] == running.port + finally: + running.close() + finally: + blocker.close() + + +def test_relayed_responses_carry_the_adapter_version_header(): + """A captured response says whether the loopback hop happened.""" + + def respond(record, handler): + payload = json.dumps({"ok": True}).encode("utf-8") + handler.send_response(200) + handler.send_header("Content-Type", "application/json") + handler.send_header("Content-Length", str(len(payload))) + handler.end_headers() + handler.wfile.write(payload) + + upstream = _FakeUpstream(respond) + running = adapter.start_adapter(upstream=upstream.origin, ports=(0,)) + try: + with _post(f"{running.base_url}/responses", {"model": "muse-spark-1.3"}) as response: + assert response.headers.get("x-muse-adapter") == str(adapter.ADAPTER_VERSION) + assert json.load(response) == {"ok": True} + finally: + running.close() + upstream.close() + + +def test_a_refused_request_is_logged_once_with_status_and_port(monkeypatch): + """Meta's refusal reaches the caller as a bare message; this line is the record.""" + monkeypatch.delenv(adapter.PASSTHROUGH_ENV_VAR, raising=False) + lines = [] + + def respond(record, handler): + payload = json.dumps( + { + "error": { + "code": "client_attestation_denied", + "message": "secret-body-marker", + } + } + ).encode("utf-8") + handler.send_response(403) + handler.send_header("Content-Type", "application/json") + handler.send_header("Content-Length", str(len(payload))) + handler.end_headers() + handler.wfile.write(payload) + + upstream = _FakeUpstream(respond) + running = adapter.start_adapter( + upstream=upstream.origin, ports=(0,), error_log=lines.append + ) + try: + with pytest.raises(urllib.error.HTTPError) as refusal: + _post( + f"{running.base_url}/responses", + { + "model": "muse-spark-1.3", + "tools": [{"type": "function", "name": "read_file"}], + }, + ) + assert refusal.value.code == 403 + finally: + running.close() + upstream.close() + + assert len(lines) == 1 + line = lines[0] + assert "403" in line + assert f"v{adapter.ADAPTER_VERSION}" in line + assert f"port={running.port}" in line + assert f"pid={os.getpid()}" in line + assert "secret-body-marker" not in line + assert "LLM|sentinel" not in line + + +def test_the_health_cli_reports_a_listening_adapter(): + running = adapter.start_adapter(ports=(0,)) + try: + completed = subprocess.run( + [sys.executable, str(ADAPTER_FILE), "--health", running.base_url], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + finally: + running.close() + + assert completed.returncode == 0, completed.stderr + payload = json.loads(completed.stdout) + assert payload["port"] == running.port + assert payload["adapter_version"] == adapter.ADAPTER_VERSION + + +def test_the_health_cli_reports_a_dead_port_instead_of_raising(): + probe = socket.socket() + probe.bind(("127.0.0.1", 0)) + dead = probe.getsockname()[1] + probe.close() + + completed = subprocess.run( + [sys.executable, str(ADAPTER_FILE), "--health", f"http://127.0.0.1:{dead}/v1"], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + + assert completed.returncode == 1 + assert "no Muse Code adapter answered" in completed.stderr diff --git a/tests/test_muse_code_provider.py b/tests/test_muse_code_provider.py index 2e3deaa..cc46732 100644 --- a/tests/test_muse_code_provider.py +++ b/tests/test_muse_code_provider.py @@ -119,8 +119,17 @@ def test_provider_registered_with_expected_wiring(tmp_path, monkeypatch): monkeypatch.setenv("MUSE_CODE_SUB_CREDENTIALS", str(tmp_path / "cache.json")) module, registered = _load_plugin() profile = registered["muse-code"] + # The adapter starts on first resolution, not at import: loading the plugin + # must not bind a loopback port that a short-lived probe process would orphan. + assert profile.base_url == module.DEFAULT_BASE_URL + state = getattr(sys, "_muse_code_adapter_state_v1", None) + assert state is None or state.active is None # Inference goes through the loopback wire adapter, not the direct endpoint. - assert re.fullmatch(r"http://127\.0\.0\.1:\d+/v1", profile.base_url) + resolved = profile.runtime_base_url( + api_key="LLM|k", default=module.DEFAULT_BASE_URL, env_url="" + ) + assert re.fullmatch(r"http://127\.0\.0\.1:\d+/v1", resolved) + assert profile.base_url == resolved assert module.DEFAULT_BASE_URL == "https://api.meta.ai/v1" assert profile.api_mode == "codex_responses" assert profile.auth_type == "api_key" @@ -253,7 +262,11 @@ def test_base_url_uses_the_loopback_adapter(tmp_path, monkeypatch): monkeypatch.setenv("MUSE_CODE_SUB_CREDENTIALS", str(tmp_path / "c.json")) monkeypatch.setenv("META_BASE_URL", "https://attacker.test/v1") _, registered = _load_plugin() - base_url = registered["muse-code"].base_url + profile = registered["muse-code"] + profile.runtime_base_url( + api_key="LLM|k", default="https://api.meta.ai/v1", env_url="https://attacker.test/v1" + ) + base_url = profile.base_url assert re.fullmatch(r"http://127\.0\.0\.1:\d+/v1", base_url) assert "attacker.test" not in base_url @@ -307,6 +320,13 @@ def test_repeated_imports_reuse_one_adapter(tmp_path, monkeypatch): monkeypatch.setenv("MUSE_CODE_SUB_CREDENTIALS", str(tmp_path / "c.json")) _, first = _load_plugin() _, second = _load_plugin() + resolved_first = first["muse-code"].runtime_base_url( + api_key="LLM|k", default="https://api.meta.ai/v1", env_url="" + ) + resolved_second = second["muse-code"].runtime_base_url( + api_key="LLM|k", default="https://api.meta.ai/v1", env_url="" + ) + assert resolved_first == resolved_second assert first["muse-code"].base_url == second["muse-code"].base_url From ae7d70aa17cafca061025f0078255825fa8491ab Mon Sep 17 00:00:00 2001 From: Michael Gasperini Date: Tue, 17 Nov 2026 19:33:01 +0100 Subject: [PATCH 2/2] fix(review): keep model discovery off the adapter and harden health Review pass on #21: - `fetch_models` no longer starts the adapter. Discovery is a GET, which the adapter relays untouched, and Meta serves `/v1/models` directly with a subscription key, so binding a port for it only adds a socket to a short-lived process. It also avoided a subtle change: passing `base_url=... or self.base_url` would have made core's own base URL look "custom" to the base implementation once the profile base URL moved to the loopback URL. - The "import does not bind" assertion is now order-independent: it records the active adapter before loading the plugin and requires it to be unchanged, instead of assuming no adapter is running in the test process. - `GET /__muse_adapter/health` tolerates a caller that hangs up mid-response, like the relay path already does. Refs #20 --- __init__.py | 9 ++++----- muse_adapter.py | 5 ++++- tests/test_muse_code_provider.py | 6 ++++-- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/__init__.py b/__init__.py index 6fffb24..d09751c 100644 --- a/__init__.py +++ b/__init__.py @@ -295,12 +295,11 @@ def fetch_models( timeout: float = 8.0, ) -> list[str] | None: _ensure_subscription_key() - # The catalog probe is a real upstream call: resolve the adapter - # first so discovery does not bypass it. Until the adapter starts, - # base_url is the direct endpoint, not the loopback URL. - _refresh_base_url() + # Discovery is a GET, which the adapter relays untouched, and Meta + # serves /v1/models directly (verified with a subscription key), so + # it does not need the loopback hop or a port binding. live = super().fetch_models( - api_key=api_key, base_url=base_url or self.base_url, timeout=timeout + api_key=api_key, base_url=base_url, timeout=timeout ) if live is None: return None diff --git a/muse_adapter.py b/muse_adapter.py index 495779a..d625d9e 100644 --- a/muse_adapter.py +++ b/muse_adapter.py @@ -507,7 +507,10 @@ def _serve_health(self) -> None: self.send_header("Content-Length", str(len(payload))) self.send_header("x-muse-adapter", str(ADAPTER_VERSION)) self.end_headers() - self.wfile.write(payload) + try: + self.wfile.write(payload) + except (BrokenPipeError, ConnectionResetError): + self.close_connection = True def do_POST(self) -> None: # noqa: N802 - stdlib handler naming self._handle() diff --git a/tests/test_muse_code_provider.py b/tests/test_muse_code_provider.py index cc46732..fca24db 100644 --- a/tests/test_muse_code_provider.py +++ b/tests/test_muse_code_provider.py @@ -117,13 +117,15 @@ def fake(request, timeout=None): def test_provider_registered_with_expected_wiring(tmp_path, monkeypatch): monkeypatch.setenv("MUSE_CODE_SUB_CREDENTIALS", str(tmp_path / "cache.json")) + before = getattr(sys, "_muse_code_adapter_state_v1", None) + before_active = getattr(before, "active", None) module, registered = _load_plugin() profile = registered["muse-code"] # The adapter starts on first resolution, not at import: loading the plugin # must not bind a loopback port that a short-lived probe process would orphan. + after_active = getattr(getattr(sys, "_muse_code_adapter_state_v1", None), "active", None) + assert after_active is before_active assert profile.base_url == module.DEFAULT_BASE_URL - state = getattr(sys, "_muse_code_adapter_state_v1", None) - assert state is None or state.active is None # Inference goes through the loopback wire adapter, not the direct endpoint. resolved = profile.runtime_base_url( api_key="LLM|k", default=module.DEFAULT_BASE_URL, env_url=""