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
feat(model-hub): run keyless Exa searches behind the flag (KEX-2) (#2956)
Call White8488e694d229
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex 142575d31..7adc0828b 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -654,13 +654,17 @@ class EngineAdapter(Protocol):source_id: str,vendor: str,service_id: str,- credential_ref: str,+ credential_ref: str | None,request: Mapping[str, Any],*,on_sent: Callable[[], Awaitable[None] | None] | None = None,) -> SearchResponse:"""Make exactly one catalog-host search request from Model Hub custody.+ ``credential_ref`` is an opaque custody handle for credentialed Sources;+ it is ``None`` for the built-in keyless MCP Source. In both cases the+ adapter owns the transport and never exposes secret material.+``on_sent`` fires once after the connection (including TLS) is ready andimmediately before aiohttp writes this request. A callback failure stopsthe request before any request bytes are sent. An async callback isdiff --git a/core/handlers/model_hub/search_chain.py b/core/handlers/model_hub/search_chain.pyindex eb0d7dbc0..c3e9c053b 100644--- a/core/handlers/model_hub/search_chain.py+++ b/core/handlers/model_hub/search_chain.py@@ -15,6 +15,7 @@ from config.v2_config import (KEYLESS_EXA_ACTIVE,KEYLESS_EXA_SOURCE_ID,ModelHubSourceStateConfig,+ is_keyless_exa_source,model_hub_keyless_exa_source,model_hub_search_service,)@@ -216,6 +217,24 @@ class SearchChain:return Failure(self.say("modelHub.hostedTools.noSearchSource"), None)async def service_attempt(self, slot, source, catalog):+ loop = asyncio.get_running_loop()+ attempt_deadline = loop.time() + max(0.0, min(ATTEMPT_SECONDS, self.deadline - loop.time()))+ if is_keyless_exa_source(source):+ remaining = max(0.0, attempt_deadline - loop.time())+ try:+ await asyncio.wait_for(self.owner._keyless_exa_attempt_lock.acquire(), timeout=remaining)+ except asyncio.TimeoutError:+ return None, {+ "source_id": slot.source_id, "label": source.display_name[:64],+ "kind": "service", "outcome": "skipped", "skipped": "unavailable",+ }+ try:+ return await self._service_attempt_locked(slot, source, catalog, attempt_deadline=attempt_deadline)+ finally:+ self.owner._keyless_exa_attempt_lock.release()+ return await self._service_attempt_locked(slot, source, catalog, attempt_deadline=attempt_deadline)++ async def _service_attempt_locked(self, slot, source, catalog, *, attempt_deadline: float):from .service import _ExecutorAttemptowner = self.owner@@ -244,7 +263,7 @@ class SearchChain:health_generation = owner._latest_source_attempt_generation.get(source.id)cooldown_generation = owner._service_cooldowns.generation(source, slot.model_id)else:- health_generation = owner._reserve_settlement_generation(source.id, source=source)+ health_generation = None if is_keyless_exa_source(source) else owner._reserve_settlement_generation(source.id, source=source)cooldown_generation = owner._service_cooldowns.advance(source, slot.model_id)async def on_sent():@@ -282,7 +301,7 @@ class SearchChain:task = asyncio.create_task(invoke())try:- await asyncio.wait_for(asyncio.shield(task), timeout=max(0.0, min(ATTEMPT_SECONDS, self.deadline - asyncio.get_running_loop().time())))+ await asyncio.wait_for(asyncio.shield(task), timeout=max(0.0, attempt_deadline - asyncio.get_running_loop().time()))except asyncio.TimeoutError:timed_out = Truetask.cancel()@@ -343,14 +362,16 @@ class SearchChain:superseded = Falseasync with owner._mutation_lock:previous = await asyncio.to_thread(owner.store.load)- current = next((s for s in previous.sources if s.id == source.id), None)- identity_current = current is not None and source_identity(current) == source_identity(source)- health_current = identity_current and owner._settlement_current(current, health_generation)+ keyless_source = is_keyless_exa_source(source)+ current = source if keyless_source else next((s for s in previous.sources if s.id == source.id), None)+ identity_current = keyless_source or (current is not None and source_identity(current) == source_identity(source))+ health_current = not keyless_source and identity_current and owner._settlement_current(current, health_generation)cooldown_current = identity_current and owner._service_cooldowns.current(current, slot.model_id, cooldown_generation)writes_health = result.blocker is not None or result.authenticatedwrites_cooldown = result.cooling or result.record["status"] == "completed"- superseded = health_generation is not None and (- (writes_health and not health_current) or (writes_cooldown and not cooldown_current)+ superseded = (+ (health_generation is not None and writes_health and not health_current)+ or (cooldown_generation is not None and writes_cooldown and not cooldown_current))if cooldown_current:owner._service_cooldowns.settle(current, slot.model_id, cooldown_generation, result, response, ended_at)diff --git a/core/handlers/model_hub/search_services.py b/core/handlers/model_hub/search_services.pyindex 81b8f29d5..7dd3837c2 100644--- a/core/handlers/model_hub/search_services.py+++ b/core/handlers/model_hub/search_services.py@@ -9,12 +9,14 @@ from __future__ import annotationsimport jsonimport math+import refrom dataclasses import dataclass-from datetime import datetime, timedelta+from datetime import datetime, timedelta, timezonefrom typing import Any, Callable, Mappingfrom urllib.parse import urlsplitfrom config.v2_config import (+ KEYLESS_EXA_SERVICE_ID,KEYLESS_EXA_SOURCE_ID,ModelHubConfig,ModelHubSourceConfig,@@ -36,6 +38,104 @@ BLOCKERS = {}+_KEYLESS_RATE_LIMIT_RE = re.compile(+ r"(?:rate[- ]?limit|too many requests).{0,160}(?:exceeded|retry|minute|hour|day|free|mcp)?",+ re.IGNORECASE,+)+_KEYLESS_REFUSAL_TAGS = frozenset({"PROHIBITED_CONTENT", "CONTENT_FILTER_ERROR"})+_KEYLESS_TEXT_CONTENT_TYPE_FIELD = "type"+_KEYLESS_TEXT_CONTENT_TYPE = "text"+++def _keyless_mcp_content(body: Mapping[str, Any]) -> tuple[dict[str, Any], Mapping[str, Any] | None]:+ result = body.get("result")+ if not isinstance(result, Mapping):+ return dict(body), None+ content: Any = result.get("structuredContent")+ if not isinstance(content, Mapping):+ raw_content = result.get("content")+ if isinstance(raw_content, list):+ first_candidate: Mapping[str, Any] | None = None+ for item in raw_content[:8]:+ if not isinstance(item, Mapping) or item.get(_KEYLESS_TEXT_CONTENT_TYPE_FIELD) != _KEYLESS_TEXT_CONTENT_TYPE:+ continue+ text = item.get("text")+ if not isinstance(text, str) or len(text) > 2 * 1024 * 1024:+ continue+ try:+ candidate = json.loads(text)+ except (ValueError, RecursionError):+ continue+ if not isinstance(candidate, Mapping):+ continue+ first_candidate = first_candidate or candidate+ if "results" in candidate:+ content = candidate+ break+ if not isinstance(content, Mapping):+ content = first_candidate+ if not isinstance(content, Mapping):+ return dict(body), result+ normalized = dict(content)+ metadata = result.get("_meta")+ if isinstance(metadata, Mapping):+ normalized["_meta"] = dict(metadata)+ if result.get("isError") is True:+ normalized["_mcp_is_error"] = True+ return normalized, result+++def _keyless_nested_values(value: Any, *, depth: int = 0):+ if depth > 5:+ return+ if isinstance(value, Mapping):+ for key, item in value.items():+ yield str(key), item+ yield from _keyless_nested_values(item, depth=depth + 1)+ elif isinstance(value, list):+ for item in value[:16]:+ yield from _keyless_nested_values(item, depth=depth + 1)+++def _keyless_rate_limited(status: int | None, body: Mapping[str, Any] | None) -> bool:+ if status == 429 or not isinstance(body, Mapping):+ return status == 429+ for key, value in _keyless_nested_values(body):+ if key.lower() in {"ai.exa/ratelimited", "ratelimited"} and value is True:+ return True+ error_shaped = body.get("error") is not None or body.get("_mcp_is_error") is True+ if not error_shaped:+ result = body.get("result")+ error_shaped = isinstance(result, Mapping) and result.get("isError") is True+ if not error_shaped:+ return False+ for key, value in _keyless_nested_values(body):+ if key.lower() in {"message", "detail", "text"} and isinstance(value, str):+ if _KEYLESS_RATE_LIMIT_RE.search(value[:512]):+ return True+ return False+++def _keyless_refused(body: Mapping[str, Any] | None) -> bool:+ if not isinstance(body, Mapping):+ return False+ return any(+ key.lower() in {"tag", "code", "type"} and isinstance(value, str)+ and value.upper() in _KEYLESS_REFUSAL_TAGS+ for key, value in _keyless_nested_values(body)+ )+++def _rate_limit_reset_deadline(value: str | None, received_at: datetime) -> datetime | None:+ if not isinstance(value, str) or len(value) > 32 or not value.isascii() or not value.isdecimal():+ return None+ try:+ deadline = datetime.fromtimestamp(int(value) / 1000, tz=timezone.utc)+ except (OverflowError, OSError, ValueError):+ return None+ return deadline if deadline >= received_at else None++def _path(value: Any, path: str) -> Any:for key in path.split("."):value = value.get(key) if isinstance(value, Mapping) else None@@ -88,6 +188,10 @@ def map_response(except (ValueError, UnicodeError, RecursionError):passstatus = response.http_status+ keyless = service.get("service_id") == KEYLESS_EXA_SERVICE_ID+ mcp_result: Mapping[str, Any] | None = None+ if keyless and isinstance(body, Mapping):+ body, mcp_result = _keyless_mcp_content(body)mapping = service["result"]rows = _path(body, mapping["results"])sources: list[dict[str, str]] = []@@ -107,7 +211,9 @@ def map_response(value = _path(row, mapping[field])if field == "snippet" and isinstance(value, list):# Exa's highlights, in rank order, never its page text.- value = "\n".join(part[:bound] for part in value[:bound] if isinstance(part, str))+ value = ("\n\n" if keyless else "\n").join(+ part[:bound] for part in value[:bound] if isinstance(part, str)+ )if isinstance(value, str):item[field] = value[:bound]sources.append(item)@@ -121,6 +227,20 @@ def map_response(code = "service_balance"elif status in codes["limit"]:code = "service_limit"+ elif keyless and _keyless_rate_limited(status, body if isinstance(body, Mapping) else None):+ code = "service_rate_limited"+ elif keyless and _keyless_refused(body if isinstance(body, Mapping) else None):+ code = "service_refused"+ elif keyless and (+ (isinstance(body, Mapping) and body.get("error") is not None)+ or (mcp_result is not None and mcp_result.get("isError") is True)+ ):+ code = "service_unavailable"+ elif keyless and status in service["service_refused_statuses"]:+ # Exa's catalog status set is shared with credentialed Exa. For the+ # keyless path, only the explicit content-filter tags above are a+ # refusal; an unrecognized HTTP error is an unavailable service.+ code = "service_unavailable"elif status == 200:if not isinstance(rows, list) or (rows and not sources):code = "service_unreadable"@@ -139,6 +259,13 @@ def map_response(if code == "service_refused":# Keep only bounded/redacted provider diagnostics, never a raw response body.error = body.get("error") if isinstance(body, dict) else None+ if error is None and mcp_result is not None:+ error = mcp_result.get("error")+ if error is None and mcp_result.get("isError") is True:+ content = mcp_result.get("content")+ if isinstance(content, list):+ error = next((item.get("text") for item in content[:8]+ if isinstance(item, Mapping) and isinstance(item.get("text"), str)), None)message = error.get("message") if isinstance(error, dict) else errormessage = message if isinstance(message, str) else body.get("message") if isinstance(body, dict) else Noneif not isinstance(message, str) and isinstance(body, dict):@@ -157,7 +284,11 @@ def map_response(billing = service["billing"]billable, uncertain = False, False- if sent:+ if sent and keyless:+ # Keyless Exa's service is free: attempts still enter usage.requests,+ # but never become billable or carry a provider cost estimate.+ billable, uncertain = False, False+ elif sent:if status == 200:if not billing["nonempty_only"]:billable = True@@ -186,7 +317,7 @@ def map_response(return ServiceResult(record, cost, billable, uncertain,authenticated=status == 200 or code in {"service_balance", "service_limit"},- blocker=BLOCKERS.get(code), cooling=code in {"service_unavailable", "service_unreadable"},+ blocker=BLOCKERS.get(code), cooling=code in {"service_unavailable", "service_unreadable", "service_rate_limited"},reported_usd=reported,)@@ -249,9 +380,13 @@ class ServiceCooldowns:if result.cooling:state.failures = min(state.failures + 1, 5)advice = None- if response.http_status in {429, 503}:- value = next((v for k, v in response.headers.items() if k.lower() == "retry-after"), None)- advice = retry_after_deadline(value, response.response_received_at or now)+ received_at = response.response_received_at or now+ value = next((v for k, v in response.headers.items() if k.lower() == "retry-after"), None)+ advice = retry_after_deadline(value, received_at)+ reset = next((v for k, v in response.headers.items() if k.lower() == "x-ratelimit-reset"), None)+ reset_deadline = _rate_limit_reset_deadline(reset, received_at)+ if reset_deadline is not None and (advice is None or reset_deadline > advice):+ advice = reset_deadlinestate.until = advice if advice is not None else now + timedelta(seconds=min(30 * 2 ** (state.failures - 1), 300))elif result.record["status"] == "completed":state.failures = 0diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 55023efee..baa37c7c7 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -1605,6 +1605,7 @@ class ModelHubService:self._search_trial_identities: dict[str, tuple] = {}self._search_reenable_checks: dict[str, asyncio.Task] = {}self._service_cooldowns = ServiceCooldowns()+ self._keyless_exa_attempt_lock = asyncio.Lock()self._next_settlement_generation = PRE_ATTEMPT_SETTLEMENT_GENERATIONself._latest_source_attempt_generation: dict[str, int] = {}self._source_attempt_identities: dict[str, tuple | None] = {}diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex 142575d31..7adc0828b 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -654,13 +654,17 @@ class EngineAdapter(Protocol):source_id: str,vendor: str,service_id: str,- credential_ref: str,+ credential_ref: str | None,request: Mapping[str, Any],*,on_sent: Callable[[], Awaitable[None] | None] | None = None,) -> SearchResponse:"""Make exactly one catalog-host search request from Model Hub custody.+ ``credential_ref`` is an opaque custody handle for credentialed Sources;+ it is ``None`` for the built-in keyless MCP Source. In both cases the+ adapter owns the transport and never exposes secret material.+``on_sent`` fires once after the connection (including TLS) is ready andimmediately before aiohttp writes this request. A callback failure stopsthe request before any request bytes are sent. An async callback isdiff --git a/tests/test_model_hub_keyless_exa.py b/tests/test_model_hub_keyless_exa.pynew file mode 100644index 000000000..980a132b5--- /dev/null+++ b/tests/test_model_hub_keyless_exa.py@@ -0,0 +1,263 @@+"""Hermetic KEX-2 coverage: MCP lifecycle and keyless Exa outcomes."""++from __future__ import annotations++import json+from contextlib import asynccontextmanager+from datetime import datetime, timedelta, timezone++from aiohttp import web+import pytest++from core.handlers.model_hub.adapter import SearchResponse+from core.handlers.model_hub.search_services import ServiceCooldowns, map_response+from config.v2_config import model_hub_keyless_exa_source+from vibe.model_hub_runtime.api_key_vendors import search_service+from vibe.model_hub_runtime.keyless_exa_mcp import KeylessExaMcpClient+++NOW = datetime(2026, 10, 24, 6, 0, tzinfo=timezone.utc)+SERVICE = search_service("exa-mcp", "search")+assert SERVICE is not None+++def _rpc(request_id: int, result: object) -> dict:+ return {"jsonrpc": "2.0", "id": request_id, "result": result}+++def _tool_schema(*, missing: str | None = None) -> dict:+ properties = {+ "query": {"type": "string"},+ "numResults": {"type": "integer"},+ "enableHighlights": {"type": "boolean"},+ "highlightsMaxCharacters": {"type": "integer"},+ "textMaxCharacters": {"type": "integer"},+ "objective": {"type": "string"},+ }+ properties.pop(missing, None)+ return {+ "name": "web_search_advanced_exa",+ "inputSchema": {"type": "object", "properties": properties},+ }+++@asynccontextmanager+async def _mcp_stub(+ *,+ missing: str | None = None,+ sse: bool = False,+ stale_tools_once: bool = False,+ invalid_init_once: bool = False,+ notification_status: int | None = None,+):+ calls: list[dict] = []+ state = {"session": "stub-session-1", "stale_tools": stale_tools_once, "invalid_init": invalid_init_once}++ async def handle(request: web.Request) -> web.StreamResponse:+ payload = await request.json()+ calls.append({"headers": dict(request.headers), "payload": payload})+ method = payload["method"]+ request_id = payload.get("id")+ if method == "initialize":+ protocol = "1999-01-01" if state["invalid_init"] else "2025-06-18"+ state["invalid_init"] = False+ return web.json_response(+ _rpc(request_id, {+ "protocolVersion": protocol,+ "capabilities": {"tools": {"listChanged": True}},+ "serverInfo": {"name": "stub-exa", "version": "1"},+ }),+ headers={"Mcp-Session-Id": state["session"]},+ )+ if method == "notifications/initialized":+ if notification_status is not None:+ return web.Response(status=notification_status, headers={"Mcp-Session-Id": state["session"]})+ return web.Response(status=202, headers={"Mcp-Session-Id": state["session"]})+ if method == "tools/list":+ if state["stale_tools"]:+ state["stale_tools"] = False+ return web.json_response({"error": {"message": "MCP session not found"}}, status=404)+ return web.json_response(_rpc(request_id, {"tools": [_tool_schema(missing=missing)]}))+ if method == "tools/call":+ result = {+ "content": [{"type": "text", "text": json.dumps({+ "results": [{+ "url": "https://example.test/result",+ "title": "Example result",+ "highlights": ["A highlight", "Another highlight"],+ "text": "This must never be surfaced",+ "publishedDate": "2026-10-23",+ }],+ })}],+ }+ body = json.dumps(_rpc(request_id, result), separators=(",", ":"))+ if sse:+ return web.Response(+ body=f"event: message\ndata: {body}\n\n".encode(),+ content_type="text/event-stream",+ )+ return web.json_response(_rpc(request_id, result))+ raise AssertionError(method)++ app = web.Application()+ app.router.add_post("/mcp", handle)+ runner = web.AppRunner(app, handler_cancellation=True)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ try:+ yield f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}/mcp", calls+ finally:+ await runner.cleanup()++[email protected]("sse", [False, True], ids=["json", "sse"])+async def test_keyless_mcp_negotiates_once_adapts_live_schema_and_maps_highlights(sse: bool) -> None:+ """KEX-2: one session sends only advertised search controls and maps highlights, not text."""+ async with _mcp_stub(sse=sse) as (endpoint, calls):+ client = KeylessExaMcpClient(endpoint=endpoint, client_version="test")+ sent: list[bool] = []+ response = await client.search(+ {+ "type": "auto",+ "query": "avibe",+ "numResults": 3,+ "enableHighlights": True,+ "highlightsMaxCharacters": 1000,+ "textMaxCharacters": 1,+ },+ on_sent=lambda: sent.append(True),+ )++ assert [call["payload"]["method"] for call in calls] == [+ "initialize", "notifications/initialized", "tools/list", "tools/call",+ ]+ assert calls[0]["headers"]["User-Agent"] == "Avibe/test"+ assert calls[0]["headers"]["x-exa-source"] == "avibe"+ assert calls[0]["payload"]["params"]["clientInfo"] == {"name": "avibe", "version": "test"}+ assert calls[-1]["payload"]["params"]["arguments"] == {+ "query": "avibe",+ "numResults": 3,+ "enableHighlights": True,+ "highlightsMaxCharacters": 1000,+ "textMaxCharacters": 1,+ }+ assert sent == [True]+ mapped = map_response(SERVICE, response, sent=True, results=3, say=lambda key, **_: key)+ assert mapped.record == {+ "status": "completed",+ "sources": [{+ "url": "https://example.test/result",+ "title": "Example result",+ "snippet": "A highlight\n\nAnother highlight",+ "page_age": "2026-10-23",+ }],+ }+ assert mapped.cost is not None and mapped.cost.usd == 0+ assert not mapped.billable and not mapped.uncertain+++async def test_keyless_mcp_does_not_continue_after_initialized_transport_error() -> None:+ """KEX-2: notification transport failures stop the handshake before tools/list."""+ async with _mcp_stub(notification_status=500) as (endpoint, calls):+ response = await KeylessExaMcpClient(endpoint=endpoint).search({"query": "avibe"})+ assert response.http_status == 500+ assert [call["payload"]["method"] for call in calls] == ["initialize", "notifications/initialized"]+++async def test_keyless_mcp_discards_session_after_invalid_initialization() -> None:+ """KEX-2: a failed handshake cannot authorize a later search on the stale session."""+ async with _mcp_stub(invalid_init_once=True) as (endpoint, calls):+ client = KeylessExaMcpClient(endpoint=endpoint)+ first = await client.search({"query": "first"})+ second = await client.search({"query": "second", "numResults": 1, "enableHighlights": True, "textMaxCharacters": 1})+ assert first.error == "connection"+ assert second.http_status == 200+ assert [call["payload"]["method"] for call in calls] == [+ "initialize", "initialize", "notifications/initialized", "tools/list", "tools/call",+ ]+++async def test_keyless_mcp_refreshes_tools_schema_for_each_search_on_one_session() -> None:+ """KEX-2: a reused session still refreshes tools/list before every admitted search."""+ async with _mcp_stub() as (endpoint, calls):+ client = KeylessExaMcpClient(endpoint=endpoint, client_version="test")+ arguments = {"query": "avibe", "numResults": 1, "enableHighlights": True, "textMaxCharacters": 1}+ await client.search(arguments)+ await client.search(arguments)+ assert [call["payload"]["method"] for call in calls] == [+ "initialize", "notifications/initialized", "tools/list", "tools/call", "tools/list", "tools/call",+ ]+++async def test_keyless_mcp_replays_one_stale_pre_tool_session_without_double_counting_admission() -> None:+ """KEX-2: session-not-found before tools/call reinitializes and invokes admission once."""+ async with _mcp_stub(stale_tools_once=True) as (endpoint, calls):+ client = KeylessExaMcpClient(endpoint=endpoint, client_version="test")+ admitted: list[bool] = []+ response = await client.search(+ {"query": "avibe", "numResults": 1, "enableHighlights": True, "textMaxCharacters": 1},+ on_sent=lambda: admitted.append(True),+ )+ assert response.http_status == 200+ assert admitted == [True]+ assert [call["payload"]["method"] for call in calls] == [+ "initialize", "notifications/initialized", "tools/list",+ "initialize", "notifications/initialized", "tools/list", "tools/call",+ ]+++async def test_keyless_mcp_rejects_a_schema_without_text_bound_before_tools_call() -> None:+ """KEX-2: a missing required highlight/text control is unavailable without sending a call."""+ async with _mcp_stub(missing="textMaxCharacters") as (endpoint, calls):+ response = await KeylessExaMcpClient(endpoint=endpoint).search({"query": "avibe", "numResults": 3})+ assert response.error == "invalid_endpoint"+ assert [call["payload"]["method"] for call in calls] == [+ "initialize", "notifications/initialized", "tools/list",+ ]+++ "status,body,headers,expected",+ [+ (429, {"error": {"message": "slow down"}}, {"Retry-After": "7"}, "service_rate_limited"),+ (200, {"jsonrpc": "2.0", "id": 1, "result": {"_meta": {"ai.exa/rateLimited": True}, "content": []}}, {}, "service_rate_limited"),+ (200, {"jsonrpc": "2.0", "id": 1, "result": {"isError": True, "content": [{"type": "text", "text": "Free MCP rate limit exceeded"}]}}, {}, "service_rate_limited"),+ (200, {"jsonrpc": "2.0", "id": 1, "error": {"code": -32000, "message": "Unauthorized"}}, {}, "service_unavailable"),+ (401, {"error": {"code": -32000, "message": "Unauthorized"}}, {}, "service_unavailable"),+ (200, {"jsonrpc": "2.0", "id": 1, "error": {"code": "PROHIBITED_CONTENT", "message": "blocked"}}, {}, "service_refused"),+ (403, {"html": "access denied"}, {}, "service_unavailable"),+ ],+)+def test_keyless_outcome_table_never_reports_a_credential_error(status, body, headers, expected) -> None:+ """KEX-2: only approved rate-limit signals cool the service; ambiguous -32000 is unavailable."""+ response = SearchResponse(status, headers, json.dumps(body).encode(), response_received_at=NOW)+ result = map_response(SERVICE, response, sent=True, results=3, say=lambda key, **_: key)+ assert result.record["error_code"] == expected+ assert result.record["error_code"] != "service_key_invalid"+ assert result.cost is not None and result.cost.usd == 0+ assert not result.billable and not result.uncertain+ assert result.cooling is (expected == "service_rate_limited" or expected == "service_unavailable")+++def test_keyless_cooldown_prefers_later_epoch_millisecond_reset() -> None:+ """KEX-2: X-RateLimit-Reset is absolute Unix milliseconds, not a delay."""+ source = model_hub_keyless_exa_source()+ cooldowns = ServiceCooldowns()+ generation = cooldowns.advance(source, "exa/mcp")+ later = NOW + timedelta(seconds=90)+ result = map_response(+ SERVICE,+ SearchResponse(429, {"Retry-After": "5", "X-RateLimit-Reset": str(int(later.timestamp() * 1000))}, b"{}", response_received_at=NOW),+ sent=True,+ results=3,+ say=lambda key, **_: key,+ )+ assert cooldowns.settle(source, "exa/mcp", generation, result, SearchResponse(429, {"Retry-After": "5", "X-RateLimit-Reset": str(int(later.timestamp() * 1000))}, b"{}", response_received_at=NOW), NOW)+ assert cooldowns.until(source, "exa/mcp", NOW) == laterdiff --git a/tests/test_model_hub_search_chain.py b/tests/test_model_hub_search_chain.pyindex 6fc77986f..74de2e494 100644--- a/tests/test_model_hub_search_chain.py+++ b/tests/test_model_hub_search_chain.py@@ -19,7 +19,7 @@ from config.v2_config import (ModelHubConfig, ModelHubSourceStateConfig,model_hub_keyless_exa_source,)-from core.handlers.model_hub import hosted_tools+from core.handlers.model_hub import hosted_tools, search_chainfrom core.handlers.model_hub.adapter import SearchCredentialCheck, SearchResponsefrom core.handlers.model_hub.capability_evidence import EvidenceFeaturefrom tests.test_model_hub_api import _service@@ -313,6 +313,136 @@ async def test_skip_precedence_terminal_reason_and_attempts_without_execution(tm_hosted_result("web_search", result)+async def test_keyless_producer_writes_request_only_zero_cost_usage(tmp_path, monkeypatch):+ """KEX-2: an admitted keyless call records one request, zero billable requests and zero cost."""+ service = owner(+ tmp_path,+ ("exa",),+ web={+ "enabled": True,+ "executor_order": [KEYLESS_EXA_SOURCE_ID],+ "executor_order_kinds": {KEYLESS_EXA_SOURCE_ID: "service"},+ "services": {KEYLESS_EXA_SOURCE_ID: {"enabled": True, "results": 3}},+ },+ )+ monkeypatch.setattr(hosted_tools, "KEYLESS_EXA_ACTIVE", True)+ monkeypatch.setattr(search_chain, "KEYLESS_EXA_ACTIVE", True)+ body = {"jsonrpc": "2.0", "id": 1, "result": {"content": [{"type": "text", "text": json.dumps({+ "results": [{"url": "https://example.test/keyless", "title": "Keyless", "highlights": ["excerpt"]}],+ })}]}}+ calls = answers(monkeypatch, service, wire(body=body))+ result = await run(service)+ assert calls == [(KEYLESS_EXA_SOURCE_ID, "exa-mcp", KEYLESS_EXA_SERVICE_ID, None, {+ "type": "auto", "query": "query", "numResults": 3,+ "enableHighlights": True, "highlightsMaxCharacters": 1000, "textMaxCharacters": 1,+ })]+ assert result["record"]["attempts"] == [{+ "source_id": KEYLESS_EXA_SOURCE_ID, "label": "Exa (free)", "kind": "service",+ "outcome": "completed", "cost": {"basis": "list", "usd": 0},+ }]+ usage = summary(service)+ assert usage["services"][0]["requests"] == 1+ assert usage["services"][0]["billable_requests"] == 0+++async def test_keyless_rate_limit_settles_service_cooldown_without_persisted_source(tmp_path, monkeypatch):+ """KEX-2: synthetic keyless identity still owns the in-memory service cooldown."""+ service = owner(+ tmp_path,+ (),+ web={+ "enabled": True,+ "executor_order": [KEYLESS_EXA_SOURCE_ID],+ "executor_order_kinds": {KEYLESS_EXA_SOURCE_ID: "service"},+ "services": {KEYLESS_EXA_SOURCE_ID: {"enabled": True, "results": 3}},+ },+ )+ monkeypatch.setattr(hosted_tools, "KEYLESS_EXA_ACTIVE", True)+ monkeypatch.setattr(search_chain, "KEYLESS_EXA_ACTIVE", True)+ calls = answers(monkeypatch, service, wire(429, {"error": {"message": "slow down"}}, headers={"Retry-After": "60"}))+ first = await run(service)+ second = await run(service)+ assert len(calls) == 1+ assert first["record"]["attempts"][0]["error_code"] == "service_rate_limited"+ assert second["record"]["attempts"] == [{+ "source_id": KEYLESS_EXA_SOURCE_ID, "label": "Exa (free)", "kind": "service",+ "outcome": "skipped", "skipped": "cooling",+ "retry_at": (NOW + timedelta(seconds=60)).isoformat().replace("+00:00", "Z"),+ }]+ assert _web(service)["executor_candidates"][0]["cooldown_until"] == (NOW + timedelta(seconds=60)).isoformat().replace("+00:00", "Z")+++async def test_keyless_overlapping_searches_settle_rate_limit_before_next_admission(tmp_path, monkeypatch):+ """KEX-2: a queued keyless turn cannot invalidate the active cooldown generation."""+ service = owner(+ tmp_path,+ (),+ web={+ "enabled": True,+ "executor_order": [KEYLESS_EXA_SOURCE_ID],+ "executor_order_kinds": {KEYLESS_EXA_SOURCE_ID: "service"},+ "services": {KEYLESS_EXA_SOURCE_ID: {"enabled": True, "results": 3}},+ },+ )+ monkeypatch.setattr(hosted_tools, "KEYLESS_EXA_ACTIVE", True)+ monkeypatch.setattr(search_chain, "KEYLESS_EXA_ACTIVE", True)+ entered = asyncio.Event()+ release = asyncio.Event()+ calls = []++ async def search(source_id, vendor, service_id, credential_ref, request, *, on_sent):+ calls.append((source_id, service_id))+ await on_sent()+ if len(calls) == 1:+ entered.set()+ await release.wait()+ return wire(429, {"error": {"message": "slow down"}}, headers={"Retry-After": "60"})+ raise AssertionError("queued keyless search reached the adapter")++ monkeypatch.setattr(service.adapter, "search", search, raising=False)+ active = asyncio.create_task(run(service))+ await entered.wait()+ queued = asyncio.create_task(run(service))+ await asyncio.sleep(0)+ release.set()+ first, second = await asyncio.gather(active, queued)+ assert calls == [(KEYLESS_EXA_SOURCE_ID, KEYLESS_EXA_SERVICE_ID)]+ assert first["record"]["attempts"][0]["error_code"] == "service_rate_limited"+ assert second["record"]["attempts"][0]["skipped"] == "cooling"+++async def test_keyless_queued_waiter_times_out_before_admission(tmp_path, monkeypatch):+ """KEX-2: lock wait consumes the attempt budget and never sends a keyless request."""+ service = owner(+ tmp_path,+ (),+ web={+ "enabled": True,+ "executor_order": [KEYLESS_EXA_SOURCE_ID],+ "executor_order_kinds": {KEYLESS_EXA_SOURCE_ID: "service"},+ "services": {KEYLESS_EXA_SOURCE_ID: {"enabled": True, "results": 3}},+ },+ )+ monkeypatch.setattr(hosted_tools, "KEYLESS_EXA_ACTIVE", True)+ monkeypatch.setattr(search_chain, "KEYLESS_EXA_ACTIVE", True)+ monkeypatch.setattr(search_chain, "ATTEMPT_SECONDS", 0.01)+ await service._keyless_exa_attempt_lock.acquire()+ calls = answers(monkeypatch, service, wire())+ try:+ result = await run(service)+ finally:+ service._keyless_exa_attempt_lock.release()+ assert calls == []+ assert result["record"]["attempts"] == [{+ "source_id": KEYLESS_EXA_SOURCE_ID, "label": "Exa (free)", "kind": "service",+ "outcome": "skipped", "skipped": "unavailable",+ }]++@pytest.mark.asyncioasync def test_keyless_retry_branch_accepts_the_synthetic_source_while_flag_is_off(tmp_path):"""KEX-1: a downgraded reader can clear a built-in cooldown without a Source row or network call."""diff --git a/ui/src/components/settings/models/SearchServiceParts.tsx b/ui/src/components/settings/models/SearchServiceParts.tsxindex bae7abfe6..def2a64e1 100644--- a/ui/src/components/settings/models/SearchServiceParts.tsx+++ b/ui/src/components/settings/models/SearchServiceParts.tsx@@ -67,10 +67,11 @@ export const SearchCandidateStatus: React.FC<{export const SearchServiceNotes: React.FC<{ vendor?: HostedSearchServiceVendor }> = ({ vendor }) => {const { t } = useTranslation();+ const keyless = vendor?.id === 'exa-mcp';return <div className="model-hub-tool-note flex flex-col gap-2">- <p>{vendor ? t('settings.models.searchServices.queryVendor', { vendor: vendor.name }) : t('settings.models.searchServices.queryDestination')}</p>+ <p>{keyless ? t('settings.models.searchServices.keylessQueryDestination') : vendor ? t('settings.models.searchServices.queryVendor', { vendor: vendor.name }) : t('settings.models.searchServices.queryDestination')}</p><p>{t('settings.models.searchServices.placement')}</p>- <p className="flex items-start gap-2"><LockKeyhole className="mt-0.5 size-3.5 shrink-0" aria-hidden />{t('settings.models.searchServices.custody')}</p>+ <p className="flex items-start gap-2"><LockKeyhole className="mt-0.5 size-3.5 shrink-0" aria-hidden />{t(keyless ? 'settings.models.searchServices.keylessCustody' : 'settings.models.searchServices.custody')}</p></div>;};diff --git a/ui/src/components/settings/models/SearchServices.test.tsx b/ui/src/components/settings/models/SearchServices.test.tsxindex 50dd7d327..fea29e5c9 100644--- a/ui/src/components/settings/models/SearchServices.test.tsx+++ b/ui/src/components/settings/models/SearchServices.test.tsx@@ -16,6 +16,7 @@ import { createSourceCollectionReadAuthority } from './collectionReadAuthority';import { ApiCallError, modelsApi } from './modelsApi';import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';import { readyRegion } from './regionRead';+import { keylessExaSource } from './searchServices';import { ACTIVE_SEARCH, KEYLESS_ACTIVE_SEARCH, SEARCH_SOURCES } from './searchServices.fixtures';import { SourceDetailPanel } from './SourceDetailPanel';import { SourcesCard } from './SourcesCard';@@ -23,8 +24,8 @@ import { ToolsTab } from './ToolsTab';import type { HostedServiceExecutorCandidate, HostedWebSearchToolStatus, Source, UsageReport } from './types';const wrap = (element: React.ReactElement, lng = 'en') => <I18nextProvider i18n={i18n.cloneInstance({ lng })}><ToastProvider>{element}</ToastProvider></I18nextProvider>;-const tab = (tool = ACTIVE_SEARCH) => {- const onSave = vi.fn();+const tab = (tool = ACTIVE_SEARCH, save = vi.fn()) => {+ const onSave = save;const onOpenService = vi.fn();const onRetryService = vi.fn();const onAddService = vi.fn();@@ -79,7 +80,7 @@ describe('search service activation and mixed order', () => {<SourcesCard read={readyRegion(SEARCH_SOURCES)} onRetry={vi.fn()} onOpenSource={vi.fn()} onAddApiKey={vi.fn()} onAddSubscription={vi.fn()} searchTool={ACTIVE_SEARCH} onAddSearchService={vi.fn()} /></>, lng));expect(screen.getByText(locale.t('settings.models.searchServices.subtitle'))).toBeTruthy();- expect(screen.getAllByRole('switch')).toHaveLength(2);+ expect(screen.getAllByRole('switch')).toHaveLength(2 + ACTIVE_SEARCH.executor_candidates.filter((candidate) => candidate.kind === 'service').length);expect(screen.getByRole('heading', { name: locale.t('settings.models.searchServices.order') })).toBeTruthy();expect(screen.getByRole('button', { name: locale.t('settings.models.searchServices.addProvider') })).toBeTruthy();expect(screen.getByRole('button', { name: locale.t('settings.models.searchServices.add') })).toBeTruthy();@@ -124,6 +125,7 @@ describe('search service activation and mixed order', () => {tab(KEYLESS_ACTIVE_SEARCH);expect(screen.getByText('Exa (free)')).toBeTruthy();expect(screen.getByText('Free')).toBeTruthy();+ expect(screen.getByText(/IP rate-limited/)).toBeTruthy();const { onOpenSource } = addDialog(KEYLESS_ACTIVE_SEARCH);expect(screen.getByText('Free; IP rate-limited')).toBeTruthy();expect(screen.queryByRole('button', { name: 'Add Exa (free)' })).toBeNull();@@ -131,6 +133,21 @@ describe('search service activation and mixed order', () => {expect(onOpenSource).toHaveBeenCalledWith('src_exakeyless');});+ it('saves the built-in keyless Exa row switch without opening credential actions', async () => {+ const onSave = vi.fn();+ tab(KEYLESS_ACTIVE_SEARCH, onSave);+ await userEvent.click(within(document.querySelector('[data-executor="src_exakeyless"]') as HTMLElement).getByRole('switch', { name: 'Use for web search' }));+ expect(onSave).toHaveBeenCalledWith('web_search', { services: { src_exakeyless: { enabled: false } } });+ });++ it('opens the built-in keyless detail without key or removal actions', () => {+ detail(keylessExaSource(KEYLESS_ACTIVE_SEARCH.executor_candidates[0], KEYLESS_ACTIVE_SEARCH.service_vendors?.[0]), KEYLESS_ACTIVE_SEARCH);+ expect(screen.getByText('mcp.exa.ai')).toBeTruthy();+ expect(screen.getByText('Free')).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Replace key' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Remove' })).toBeNull();+ });+it('keeps keyboard focus on a usable arrow when the last movable row is followed by disabled Sources', async () => {const view = tab();await userEvent.click(screen.getByRole('button', { name: 'Move Exa down' }));diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex 4392a80e8..0a1c2ed28 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -13,7 +13,7 @@ import { useToast } from '@/context/ToastContext';import { cn } from '@/lib/utils';import { AddApiKeyDialog } from './AddApiKeyDialog';import { AddSearchServiceDialog } from './AddSearchServiceDialog';-import { searchServicesActive, webSearchTool } from './searchServices';+import { searchServicesActive, webSearchTool, KEYLESS_EXA_SOURCE_ID, keylessExaSource } from './searchServices';import { BackendModelCatalogDialog, type CatalogFocus } from './BackendModelCatalogDialog';import { OAuthConnectDialog } from './OAuthConnectDialog';import { GatewayModule } from './GatewayModule';@@ -1202,7 +1202,10 @@ export const SettingsModelsPage: React.FC = () => {// its own stale treatment and Retry, and raises the page's refresh toast.}}, [selectSource, showToast, t]);- const selectedSource = sources.find((source) => source.id === selectedSourceId) ?? null;+ const selectedSource = sources.find((source) => source.id === selectedSourceId)+ ?? (selectedSourceId === KEYLESS_EXA_SOURCE_ID+ ? { ...keylessExaSource(), display_name: t('settings.models.searchServices.vendorName.exa-mcp') as string }+ : null);// Read while the tab is open, or while a Source's detail shows its capability// chips, and again when that Source changes: an edit can change its identity,// which drops its evidence on the server.diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxindex edf76857b..829ebcd3b 100644--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -23,6 +23,7 @@ import type {} from './mutationSettlement';import { GuardGapList } from './GuardGapList';import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, repairAction, type RepairKind } from './repair';+import { keylessExaSource } from './searchServices';import { ACTIVE_SEARCH, SEARCH_SOURCES } from './searchServices.fixtures';import { SourceDetailPanel } from './SourceDetailPanel';import {@@ -220,6 +221,17 @@ afterEach(() => {});describe('SourceDetailPanel', () => {+ it('keeps keyless Exa in service-only mode while the hosted-tools read is unread', () => {+ render(+ <I18nextProvider i18n={i18n}>+ <CommittedPanel source={keylessExaSource()} hostedTools={unreadRegion()} serviceView trackMutation={immediateTrack} onReauth={noReauth} />+ </I18nextProvider>,+ );+ expect(screen.getByText(i18n.t('settings.models.searchServices.keylessEndpoint'))).toBeTruthy();+ expect(screen.queryByRole('button', { name: /Manage|管理/ })).toBeNull();+ expect(screen.queryByRole('button', { name: /Remove source|移除供应商/ })).toBeNull();+ });+it.each(['en', 'zh'])('hides endpoint, key and domain-derived metadata with one header control in %s', async (lng) => {const locale = i18n.cloneInstance({ lng });const { container } = render(<I18nextProvider i18n={locale}>diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxindex 9e5622f8e..6212a78c5 100644--- a/ui/src/components/settings/models/SourceDetailPanel.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -19,7 +19,7 @@ import { GuardDialog } from './GuardDialog';import { GuardImpact } from './GuardImpact';import { HostedCapabilityChips } from './HostedCapabilityChips';import { modelCapabilities } from './hostedTools';-import { searchServicesActive, serviceVendorForSource, webSearchTool } from './searchServices';+import { searchServicesActive, serviceVendorForSource, webSearchTool, KEYLESS_EXA_SOURCE_ID } from './searchServices';import { SearchServiceSettings, SearchVendorGlyph } from './SearchServiceParts';import { confirmGuardPlan, sendAgreed, unansweredRefusal } from './guardedWrite';import { ModelHubInfoHint } from './ModelHubInfoHint';@@ -246,8 +246,9 @@ export const SourceDetailPanel: React.FC<{}): null;const searchTool = webSearchTool(capabilityStatus);+ const keylessExa = source.id === KEYLESS_EXA_SOURCE_ID;const serviceVendor = serviceVendorForSource(searchTool, source.id);- const serviceDetail = Boolean(serviceVendor && (source.protocol === 'search' || serviceView));+ const serviceDetail = keylessExa || Boolean(serviceVendor && (source.protocol === 'search' || serviceView));// Usage, like the Tools rows, waits for the read to list this Source as a search service.const serviceCandidate = searchServicesActive(searchTool)&& Boolean(searchTool?.executor_candidates.some((row) => row.kind === 'service' && row.source_id === source.id));@@ -805,16 +806,18 @@ export const SourceDetailPanel: React.FC<{const providerLabel = providerCopyKey ? t(providerCopyKey) : providerIdentity;const protocolLabel = t(PROTOCOL_COPY_KEYS[source.protocol]);const interfaceLabel = detailsHidden ? protocolLabel : `${providerLabel} · ${protocolLabel}`;- const credentialLabel = source.kind === 'api_key'- ? t('settings.models.sourceDetail.metadata.apiKey')- : t('settings.models.sourceDetail.metadata.account');+ const credentialLabel = keylessExa+ ? t('settings.models.searchServices.noSetup')+ : source.kind === 'api_key'+ ? t('settings.models.sourceDetail.metadata.apiKey')+ : t('settings.models.sourceDetail.metadata.account');const credentialValue = source.kind === 'api_key'? source.masked_credential: source.account_label;const lastFetched = source.last_discovered_at? formatRelativeTime(source.last_discovered_at, t): t('settings.models.sourceDetail.metadata.neverFetched');- const testable = source.kind === 'api_key' && source.protocol !== 'search' && source.supply_channel === 'hub';+ const testable = !keylessExa && source.kind === 'api_key' && source.protocol !== 'search' && source.supply_channel === 'hub';const usageSummary = adoptedBackends.length > 0? t('settings.models.sourceDetail.usageSummary', { count: source.models.length, backends: adoptedBackends.join(i18n.language.startsWith('zh') ? '、' : ', ') }): t('settings.models.gateway.modelCount', { count: source.models.length });@@ -827,6 +830,7 @@ export const SourceDetailPanel: React.FC<{<div className="flex min-w-0 flex-col gap-1"><h2 ref={headingRef} tabIndex={-1} className="text-lg font-bold text-foreground">{source.display_name}</h2><p className="model-hub-tool-note">{t(source.protocol === 'search' ? 'settings.models.searchServices.noModels' : 'settings.models.searchServices.modelsAndSearch')}</p>+ {keylessExa && <p className="model-hub-tool-note">{t('settings.models.searchServices.keylessEndpoint')}</p>}</div></header><div className="min-h-0 flex-1 overflow-y-auto">@@ -840,19 +844,19 @@ export const SourceDetailPanel: React.FC<{</div>}{source.trial_pending && <p className="model-hub-tool-note px-5 pt-3">{t('settings.models.searchServices.trialPending')}</p>}<section className="flex flex-col gap-3 border-b border-border px-5 py-4">- <h3 className="font-semibold text-foreground">{t('settings.models.sourceDetail.metadata.apiKey')}</h3>+ <h3 className="font-semibold text-foreground">{keylessExa ? t('settings.models.searchServices.noSetup') : t('settings.models.sourceDetail.metadata.apiKey')}</h3>{source.protocol === 'search' ? <div className="flex flex-wrap items-center gap-3">{credentialValue && <SourcePrivateValue value={credentialValue} className="font-mono" />}- <Button variant="outline" size="sm" disabled={busy} onClick={() => setReplacingKey(true)}>{t('settings.models.searchServices.replaceKey')}</Button>+ {!keylessExa && <Button variant="outline" size="sm" disabled={busy} onClick={() => setReplacingKey(true)}>{t('settings.models.searchServices.replaceKey')}</Button>}</div> : <><p className="model-hub-tool-note">{t('settings.models.searchServices.sharedKey', { source: source.display_name })}</p><Button variant="outline" size="sm" className="self-start" onClick={() => { onManageSource?.(); setReplacingKey(true); }}>{t('settings.models.searchServices.manageSource')}</Button></>}</section>{searchSettings}- <p className="model-hub-tool-note px-5 py-4">{t('settings.models.searchServices.custody')}</p>+ <p className="model-hub-tool-note px-5 py-4">{t(keylessExa ? 'settings.models.searchServices.keylessCustody' : 'settings.models.searchServices.custody')}</p></div>- {source.protocol === 'search' && <footer className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-5 py-4">+ {source.protocol === 'search' && !keylessExa && <footer className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-5 py-4"><p className="model-hub-tool-note">{t('settings.models.searchServices.removeNote')}</p><Button variant="outline" size="sm" className="text-destructive-ink" disabled={busy} onClick={beginDelete}>{t('settings.models.sourceDetail.row.remove')}</Button></footer>}@@ -872,9 +876,11 @@ export const SourceDetailPanel: React.FC<{{(source.base_url || credentialValue) && <SourcePrivacyToggle />}</section><dl className="model-hub-source-metadata grid shrink-0 grid-cols-2 gap-x-5 gap-y-3 border-b border-border bg-background px-5 py-3 sm:grid-cols-4">- <div className="min-w-0"><dt>{t('settings.models.sourceDetail.metadata.endpoint')}</dt><dd className="truncate font-mono">{source.base_url- ? <SourcePrivateValue value={source.base_url} />- : t('settings.models.sourceDetail.metadata.officialEndpoint')}</dd></div>+ <div className="min-w-0"><dt>{t('settings.models.sourceDetail.metadata.endpoint')}</dt><dd className="truncate font-mono">{keylessExa+ ? t('settings.models.searchServices.keylessEndpoint')+ : source.base_url+ ? <SourcePrivateValue value={source.base_url} />+ : t('settings.models.sourceDetail.metadata.officialEndpoint')}</dd></div><div className="min-w-0"><dt>{credentialLabel}</dt><dd className="font-mono">{credentialValue? <SourcePrivateValue value={credentialValue} />: '—'}</dd></div>diff --git a/ui/src/components/settings/models/ToolsTab.tsx b/ui/src/components/settings/models/ToolsTab.tsxindex 2ee306004..5f6360ae5 100644--- a/ui/src/components/settings/models/ToolsTab.tsx+++ b/ui/src/components/settings/models/ToolsTab.tsx@@ -280,9 +280,15 @@ const ExecutorOrder: React.FC<{ tool: HostedSearchToolStatus; lookup: SourceLook{candidate.kind === 'service' ? <button type="button" data-search-source={candidate.source_id} className="truncate text-left font-semibold text-foreground hover:underline" onClick={(event) => onOpenService?.(candidate.source_id, event.currentTarget)}>{name}</button> : <span className="truncate font-semibold text-foreground">{name}</span>}<span className={cn('model-hub-pill border', candidate.kind === 'service' ? ACCENT_PILL.cyan : ACCENT_PILL.muted)}>{t(candidate.kind === 'service' ? 'settings.models.searchServices.kind' : 'settings.models.searchServices.modelKind')}</span><SearchCandidateStatus candidate={candidate} tool={activeWeb} source={source} />+ {candidate.kind === 'service' && <ToggleSwitch+ enabled={candidate.settings.enabled}+ disabled={pending}+ label={t('settings.models.searchServices.use') as string}+ onClick={() => onSave('web_search', { services: { [candidate.source_id]: { enabled: !candidate.settings.enabled } } })}+ />}</div><span className="model-hub-tool-note">{candidate.kind === 'service'- ? t(source?.protocol === 'search' ? 'settings.models.searchServices.resultCount' : 'settings.models.searchServices.sharedKeyResults', { count: candidate.settings.results, source: name })+ ? <>{t(source?.protocol === 'search' ? 'settings.models.searchServices.resultCount' : 'settings.models.searchServices.sharedKeyResults', { count: candidate.settings.results, source: name })}{vendor?.id === 'exa-mcp' && vendor.free_tier ? ` · ${t('settings.models.searchServices.freeTier')}` : null}</>: <span className="font-mono">{candidate.model_id}</span>}</span>{candidate.kind === 'service' && candidate.cooldown_until !== null && <Button variant="outline" size="xs" className="self-start" disabled={pending} onClick={() => onRetryService?.(candidate.source_id)}>{t('settings.models.searchServices.retry')}</Button>}</div>@@ -539,6 +545,7 @@ type ServiceActions = {const WebSearchServices: React.FC<{ tool: HostedWebSearchToolStatus; lookup: SourceLookup; pending: boolean; onSave: Save } & ServiceActions> = ({ tool, lookup, pending, onSave, onAddService, onOpenService, onRetryService }) => {const { t, i18n } = useTranslation();const noServices = !tool.service_vendors?.some((vendor) => vendor.source_ids.length > 0);+ const hasKeyless = tool.service_vendors?.some((vendor) => vendor.id === 'exa-mcp') === true;return <div className="flex flex-col gap-4 border-t border-border p-4"><div className="flex items-center justify-between gap-4 rounded-lg border border-border bg-background p-3"><div className="flex min-w-0 flex-col gap-1"><h4 className="font-semibold text-foreground">{t('settings.models.searchServices.preferNative')}</h4><p className="model-hub-tool-note">{t(tool.prefer_native ? 'settings.models.searchServices.nativeOn' : 'settings.models.searchServices.nativeOff')}</p></div>@@ -546,9 +553,10 @@ const WebSearchServices: React.FC<{ tool: HostedWebSearchToolStatus; lookup: Sou</div><ExecutorOrder tool={tool} lookup={lookup} pending={pending} onSave={onSave} onOpenService={onOpenService} onRetryService={onRetryService} />{noServices && <p className="model-hub-tool-note">{t('settings.models.searchServices.empty', { prices: formatNameList((tool.service_vendors ?? []).map((vendor) => t('settings.models.searchServices.vendorPrice', { vendor: vendor.name, usd: formatSmallUsd(vendor.price.usd_per_1k) })), i18n.language) })}</p>}+ {hasKeyless && <p className="model-hub-tool-note">{t('settings.models.searchServices.keylessQueryDestination')}</p>}<div className="flex flex-wrap items-center justify-between gap-3"><Button variant={noServices ? 'default' : 'outline'} size="sm" disabled={pending} onClick={(event) => onAddService?.(event.currentTarget)}><Plus aria-hidden />{t('settings.models.searchServices.add')}</Button>- <p className="model-hub-tool-note flex items-start gap-2"><LockKeyhole className="mt-0.5 size-3.5 shrink-0" aria-hidden />{t('settings.models.searchServices.custody')}</p>+ <p className="model-hub-tool-note flex items-start gap-2"><LockKeyhole className="mt-0.5 size-3.5 shrink-0" aria-hidden />{t(hasKeyless ? 'settings.models.searchServices.keylessCustody' : 'settings.models.searchServices.custody')}</p></div></div>;};diff --git a/ui/src/components/settings/models/searchServices.ts b/ui/src/components/settings/models/searchServices.tsindex 7d24c4d4f..817d0aba2 100644--- a/ui/src/components/settings/models/searchServices.ts+++ b/ui/src/components/settings/models/searchServices.ts@@ -1,4 +1,23 @@-import type { HostedSearchServiceVendor, HostedToolsStatus, HostedWebSearchToolStatus } from './types';+import type { HostedSearchServiceVendor, HostedToolsStatus, HostedWebSearchToolStatus, Source, SourceState } from './types';++export const KEYLESS_EXA_SOURCE_ID = 'src_exakeyless';+export const KEYLESS_EXA_VENDOR_ID = 'exa-mcp';++export const keylessExaSource = (candidate?: HostedWebSearchToolStatus['executor_candidates'][number], vendor?: HostedSearchServiceVendor): Source => ({+ id: KEYLESS_EXA_SOURCE_ID,+ kind: 'api_key',+ vendor: KEYLESS_EXA_VENDOR_ID,+ display_name: vendor?.name ?? 'Exa (free)',+ protocol: 'search',+ supply_channel: 'hub',+ billing: 'metered',+ state: (candidate?.kind === 'service' ? candidate.state : undefined) ?? ({ status: 'active' } satisfies SourceState),+ last_discovered_at: null,+ models: [],+ base_url: null,+ credential_ref: null,+ masked_credential: null,+});/** One read signal across Tools, Sources and detail; S2b-2 activates service reads and execution together. */export const searchServicesActive = (tool: HostedWebSearchToolStatus | null | undefined): boolean =>diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 4ddc98d5d..33522a0c0 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2546,6 +2546,9 @@"priceDate": "API list price · {{date}}","priceNote": "Prices are the catalog's dated API list prices. Free allowances, plans and actual bills may differ.","custody": "Search service keys stay with the gateway, like other provider keys. They are never passed to the model or Agent.",+ "keylessQueryDestination": "Queries go directly from this Avibe runtime to Exa (mcp.exa.ai); Exa can see the connection's IP.",+ "keylessEndpoint": "mcp.exa.ai",+ "keylessCustody": "Exa (free) needs no key; no key is given to the model or Agent.","queryDestination": "Queries are sent to the service that runs the search.","queryVendor": "Search queries are sent to {{vendor}}.","placement": "A new search service joins before the model executors, including in a saved order. Change the order in Tools → Web search.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 658036668..e94e5c43a 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2546,6 +2546,9 @@"priceDate": "API 标价 · {{date}}","priceNote": "价格为目录标注日期的 API 标价,免费额度、套餐与实际账单可能不同。","custody": "搜索服务的密钥和其他供应商一样由网关保管,不会交给模型或 Agent。",+ "keylessQueryDestination": "查询会从此 Avibe 运行时直接发送到 Exa(mcp.exa.ai);Exa 可以看到该连接的 IP。",+ "keylessEndpoint": "mcp.exa.ai",+ "keylessCustody": "Exa(免费)无需密钥,也不会把密钥交给模型或 Agent。","queryDestination": "搜索词会发送给执行搜索的服务。","queryVendor": "搜索词会发送给 {{vendor}}。","placement": "新增搜索服务会排在模型代搜之前,已保存的顺序也一样;可在 工具 › 网页搜索 中调整顺序。",diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex b3d826e9e..c13ac7741 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -17,8 +17,12 @@ from enum import Enumfrom typing import Any, Awaitable, Callable, Literal, Mapping, Sequence, TypeVarimport aiohttp--from config.v2_config import normalize_model_hub_base_url+import config.v2_config as model_hub_config+from config.v2_config import (+ KEYLESS_EXA_SERVICE_ID,+ KEYLESS_EXA_SOURCE_ID,+ normalize_model_hub_base_url,+)from core.agent_core.ai._common import PROVIDER_SILENCE_TIMEOUT_Sfrom core.handlers.model_hub.adapter import (DiscoveredModel,@@ -69,6 +73,7 @@ from vibe.model_hub_runtime.api_key_vendors import (search_service,validate_api_key_auth_scheme,)+from vibe.model_hub_runtime.keyless_exa_mcp import KeylessExaMcpClientfrom vibe.model_hub_runtime.installer import (INSTALL_ALREADY_RUNNING_REASON,INSTALL_PLATFORM_UNSUPPORTED_REASON,@@ -153,7 +158,7 @@ _SEARCH_BODY_MAX_BYTES = 8 * 1024 * 1024_SEARCH_TIMEOUT_SECONDS = 30.0_SEARCH_CHECK_TIMEOUT_SECONDS = 10.0_SEARCH_CHECK_CONNECT_TIMEOUT_SECONDS = 5.0-_SEARCH_RESPONSE_HEADERS = frozenset({"content-type", "retry-after", "date", "content-length"})+_SEARCH_RESPONSE_HEADERS = frozenset({"content-type", "retry-after", "x-ratelimit-reset", "date", "content-length"})async def _read_bounded_search_body(content: Any) -> tuple[bytes | None, bool]:@@ -1513,6 +1518,7 @@ class CLIProxyEngineAdapter:self._oauth_flows: dict[str, _OAuthFlow] = {}self._active_oauth_providers: set[str] = set()self._oauth_lock = threading.RLock()+ self._keyless_exa_client = KeylessExaMcpClient()async def install(self) -> EngineStatus:await self.recover_installation()@@ -2250,11 +2256,22 @@ class CLIProxyEngineAdapter:source_id: str,vendor: str,service_id: str,- credential_ref: str,+ credential_ref: str | None,request: Mapping[str, Any],*,on_sent: Callable[[], Awaitable[None] | None] | None = None,) -> SearchResponse:+ if service_id == KEYLESS_EXA_SERVICE_ID:+ if (+ not model_hub_config.KEYLESS_EXA_ACTIVE+ or source_id != KEYLESS_EXA_SOURCE_ID+ or vendor != "exa-mcp"+ ):+ return SearchResponse(None, {}, None, "invalid_endpoint")+ service = search_service(vendor, "search")+ if service is None or service.get("service_id") != service_id:+ return SearchResponse(None, {}, None, "invalid_endpoint")+ return await self._keyless_exa_client.search(request, on_sent=on_sent)service = search_service(vendor, "search" if vendor in {"tavily", "exa"} else "openai_chat")if service is None or service.get("service_id") != service_id:return SearchResponse(None, {}, None, "invalid_endpoint")diff --git a/vibe/model_hub_runtime/keyless_exa_mcp.py b/vibe/model_hub_runtime/keyless_exa_mcp.pynew file mode 100644index 000000000..57d836040--- /dev/null+++ b/vibe/model_hub_runtime/keyless_exa_mcp.py@@ -0,0 +1,415 @@+"""Small, reusable MCP session for keyless Exa services.++The session is deliberately transport-only: it knows how to negotiate MCP,+adapt a live tool schema, and return one bounded JSON-RPC response. Search+mapping, service outcomes, cooldowns, and usage remain owned by Model Hub.+"""++from __future__ import annotations++import asyncio+import inspect+import json+import time+from dataclasses import dataclass+from datetime import datetime, timezone+from typing import Any, Awaitable, Callable, Mapping++import aiohttp++from core.handlers.model_hub.adapter import SearchResponse+from vibe import __version__ as AVIBE_VERSION+++KEYLESS_EXA_ENDPOINT = "https://mcp.exa.ai/mcp?tools=web_search_advanced_exa,web_fetch_exa"+KEYLESS_EXA_SEARCH_TOOL = "web_search_advanced_exa"+MCP_PROTOCOL_VERSION = "2025-06-18"+MCP_SESSION_HEADER = "Mcp-Session-Id"+_MAX_BODY_BYTES = 8 * 1024 * 1024+_TIMEOUT_SECONDS = 30.0+_CONNECT_TIMEOUT_SECONDS = 5.0+_REQUIRED_SEARCH_FIELDS = frozenset({"query", "numResults", "enableHighlights", "textMaxCharacters"})+++@dataclass(frozen=True)+class _Exchange:+ status: int | None+ headers: Mapping[str, str]+ body: bytes | None+ error: str = ""+ sent: bool = False+ received_at: datetime | None = None+ messages: tuple[Mapping[str, Any], ...] = ()+ request_id: int | None = None+++def _parse_messages(body: bytes | None) -> tuple[Mapping[str, Any], ...]:+ if not body:+ return ()+ try:+ text = body.decode("utf-8")+ except UnicodeDecodeError:+ return ()+ stripped = text.strip()+ candidates: list[str] = []+ if stripped.startswith("{") or stripped.startswith("["):+ candidates.append(stripped)+ else:+ data_lines: list[str] = []+ for line in text.splitlines():+ if line.startswith("data:"):+ value = line[5:].lstrip()+ if value and value != "[DONE]":+ data_lines.append(value)+ elif not line and data_lines:+ candidates.append("\n".join(data_lines))+ data_lines = []+ if data_lines:+ candidates.append("\n".join(data_lines))+ messages: list[Mapping[str, Any]] = []+ for candidate in candidates:+ try:+ value = json.loads(candidate)+ except (json.JSONDecodeError, RecursionError):+ continue+ values = value if isinstance(value, list) else [value]+ messages.extend(item for item in values if isinstance(item, Mapping))+ return tuple(messages)+++async def _read_bounded(content: Any) -> tuple[bytes | None, bool]:+ chunks: list[bytes] = []+ total = 0+ async for chunk in content.iter_chunked(64 * 1024):+ data = bytes(chunk)+ total += len(data)+ if total > _MAX_BODY_BYTES:+ return None, True+ chunks.append(data)+ return b"".join(chunks), False+++def _matching_message(messages: tuple[Mapping[str, Any], ...], request_id: int) -> Mapping[str, Any] | None:+ return next((message for message in messages if message.get("id") == request_id), None)+++def _session_not_found(exchange: _Exchange) -> bool:+ if exchange.status != 404:+ return False+ text = (exchange.body or b"")[:1024].decode("utf-8", "ignore").lower()+ return "session" in text and "not found" in text+++def _tool_properties(tool: Mapping[str, Any], *, require_search_controls: bool = False) -> Mapping[str, Any] | None:+ schema = tool.get("inputSchema")+ if not isinstance(schema, Mapping):+ return None+ properties = schema.get("properties")+ if not isinstance(properties, Mapping):+ return None+ if require_search_controls and not _REQUIRED_SEARCH_FIELDS.issubset(properties):+ return None+ return properties+++class KeylessExaMcpClient:+ """One serialized MCP session, reusable by Exa search and future fetch."""++ def __init__(+ self,+ *,+ endpoint: str = KEYLESS_EXA_ENDPOINT,+ client_version: str = AVIBE_VERSION,+ timeout_seconds: float = _TIMEOUT_SECONDS,+ connect_timeout_seconds: float = _CONNECT_TIMEOUT_SECONDS,+ ) -> None:+ self.endpoint = endpoint+ self.client_version = client_version+ self.timeout_seconds = timeout_seconds+ self.connect_timeout_seconds = connect_timeout_seconds+ self._lock = asyncio.Lock()+ self._session_id: str | None = None+ self._protocol_version: str | None = None+ self._tools: dict[str, Mapping[str, Any]] | None = None+ self._next_id = 0++ def _request_id(self) -> int:+ self._next_id += 1+ return self._next_id++ def _clear_session(self) -> None:+ self._session_id = None+ self._protocol_version = None+ self._tools = None++ def _observe_notifications(self, messages: tuple[Mapping[str, Any], ...]) -> None:+ if any(message.get("method") == "notifications/tools/list_changed" for message in messages):+ self._tools = None++ async def _request(+ self,+ method: str,+ params: Mapping[str, Any] | None,+ *,+ deadline: float,+ on_sent: Callable[[], Awaitable[None] | None] | None = None,+ notification: bool = False,+ ) -> _Exchange:+ if time.monotonic() >= deadline:+ return _Exchange(None, {}, None, "timeout")+ request_id = None if notification else self._request_id()+ payload: dict[str, Any] = {"jsonrpc": "2.0", "method": method}+ if request_id is not None:+ payload["id"] = request_id+ if params is not None:+ payload["params"] = dict(params)+ headers = {+ "Accept": "application/json, text/event-stream",+ "Content-Type": "application/json",+ "MCP-Protocol-Version": MCP_PROTOCOL_VERSION,+ "User-Agent": f"Avibe/{self.client_version}",+ "X-Avibe-Client": "avibe",+ "x-exa-source": "avibe",+ }+ if self._session_id is not None:+ headers[MCP_SESSION_HEADER] = self._session_id+ callback_called = False+ response_status: int | None = None+ response_headers: dict[str, str] = {}+ response_received_at: datetime | None = None++ timeout_total = max(0.001, deadline - time.monotonic())+ timeout = aiohttp.ClientTimeout(+ total=timeout_total,+ connect=min(self.connect_timeout_seconds, timeout_total),+ )++ class McpRequest(aiohttp.ClientRequest):+ async def send(self, conn):+ nonlocal callback_called+ if not callback_called and on_sent is not None:+ admission = on_sent()+ if inspect.isawaitable(admission):+ await admission+ callback_called = True+ return await super().send(conn)++ try:+ async with aiohttp.ClientSession(+ timeout=timeout,+ trust_env=False,+ request_class=McpRequest,+ ) as session:+ async with session.post(+ self.endpoint,+ headers=headers,+ json=payload,+ allow_redirects=False,+ ) as response:+ response_status = response.status+ response_received_at = datetime.now(timezone.utc)+ response_headers = {+ name: value+ for name, value in response.headers.items()+ if name.lower() in {+ "content-type", "retry-after", "x-ratelimit-reset", "mcp-session-id", "date", "content-length",+ }+ }+ body, too_large = await _read_bounded(response.content)+ if too_large:+ return _Exchange(+ response_status, response_headers, None, "body_too_large", callback_called,+ response_received_at, request_id=request_id,+ )+ messages = await asyncio.to_thread(_parse_messages, body)+ if request_id is not None and not messages and body:+ # Preserve malformed/opaque errors for the service mapper.+ return _Exchange(+ response_status, response_headers, body, "", callback_called,+ response_received_at, request_id=request_id,+ )+ return _Exchange(+ response_status, response_headers, body, "", callback_called,+ response_received_at, messages, request_id,+ )+ except asyncio.CancelledError:+ return _Exchange(+ response_status, response_headers, None, "cancelled", callback_called, response_received_at,+ )+ except asyncio.TimeoutError:+ return _Exchange(+ response_status, response_headers, None, "timeout", callback_called, response_received_at,+ )+ except (aiohttp.ClientError, OSError, ValueError):+ return _Exchange(+ response_status, response_headers, None, "connection", callback_called, response_received_at,+ )++ async def _initialize(self, *, deadline: float) -> _Exchange:+ request_id = self._next_id + 1+ exchange = await self._request(+ "initialize",+ {+ "protocolVersion": MCP_PROTOCOL_VERSION,+ "capabilities": {},+ "clientInfo": {"name": "avibe", "version": self.client_version},+ },+ deadline=deadline,+ )+ if exchange.status is not None:+ session_id = next((value for name, value in exchange.headers.items() if name.lower() == MCP_SESSION_HEADER.lower()), None)+ if session_id:+ self._session_id = session_id+ message = _matching_message(exchange.messages, request_id)+ result = message.get("result") if isinstance(message, Mapping) else None+ protocol = result.get("protocolVersion") if isinstance(result, Mapping) else None+ if exchange.status != 200 or not isinstance(result, Mapping) or protocol != MCP_PROTOCOL_VERSION:+ self._clear_session()+ if exchange.status == 200 and exchange.messages and not exchange.error:+ return _Exchange(+ exchange.status, exchange.headers, exchange.body, "connection", exchange.sent,+ exchange.received_at, exchange.messages, exchange.request_id,+ )+ return exchange+ self._protocol_version = protocol+ initialized = await self._request(+ "notifications/initialized",+ None,+ deadline=deadline,+ notification=True,+ )+ if _session_not_found(initialized):+ self._clear_session()+ if initialized.error or initialized.status is None or initialized.status >= 400:+ self._clear_session()+ return initialized+ return exchange++ async def _list_tools(self, *, deadline: float) -> _Exchange | None:+ request_id = self._next_id + 1+ exchange = await self._request("tools/list", {}, deadline=deadline)+ self._observe_notifications(exchange.messages)+ if _session_not_found(exchange):+ return exchange+ message = _matching_message(exchange.messages, request_id)+ result = message.get("result") if isinstance(message, Mapping) else None+ raw_tools = result.get("tools") if isinstance(result, Mapping) else None+ if exchange.status != 200 or not isinstance(raw_tools, list):+ return exchange+ tools = {+ str(tool.get("name")): tool+ for tool in raw_tools+ if isinstance(tool, Mapping) and isinstance(tool.get("name"), str)+ }+ self._tools = tools+ return None++ @staticmethod+ def _adapt_arguments(properties: Mapping[str, Any], arguments: Mapping[str, Any]) -> dict[str, Any] | None:+ # The live schema is authoritative. Unknown catalog defaults never cross+ # the MCP boundary, while a missing required search control is rejected+ # before any tools/call bytes are sent.+ return {name: value for name, value in arguments.items() if name in properties}++ async def call_tool(+ self,+ tool_name: str,+ arguments: Mapping[str, Any],+ *,+ on_sent: Callable[[], Awaitable[None] | None] | None = None,+ ) -> SearchResponse:+ """Call one live-schema MCP tool; retry one stale session before the call."""+ async with self._lock:+ deadline = time.monotonic() + self.timeout_seconds+ last: _Exchange | None = None+ sent_callback_called = False++ async def admit_once() -> None:+ nonlocal sent_callback_called+ if sent_callback_called or on_sent is None:+ return+ admission = on_sent()+ if inspect.isawaitable(admission):+ await admission+ sent_callback_called = True++ for _ in range(2):+ if self._session_id is None:+ initialized = await self._initialize(deadline=deadline)+ last = initialized+ if _session_not_found(initialized):+ self._clear_session()+ continue+ if initialized.error or initialized.status != 200 or self._session_id is None:+ return await self._as_search_response(initialized)+ listed = await self._list_tools(deadline=deadline)+ if listed is not None:+ last = listed+ if _session_not_found(listed):+ self._clear_session()+ continue+ return await self._as_search_response(listed)+ tool = (self._tools or {}).get(tool_name)+ properties = _tool_properties(+ tool,+ require_search_controls=tool_name == KEYLESS_EXA_SEARCH_TOOL,+ ) if isinstance(tool, Mapping) else None+ if properties is None:+ return SearchResponse(None, {}, None, "invalid_endpoint")+ adapted = self._adapt_arguments(properties, arguments)+ if adapted is None:+ return SearchResponse(None, {}, None, "invalid_endpoint")+ called = await self._request(+ "tools/call",+ {"name": tool_name, "arguments": adapted},+ deadline=deadline,+ on_sent=admit_once,+ )+ last = called+ self._observe_notifications(called.messages)+ if _session_not_found(called):+ self._clear_session()+ continue+ return await self._as_search_response(called)+ return await self._as_search_response(last or _Exchange(None, {}, None, "connection"))++ async def search(+ self,+ arguments: Mapping[str, Any],+ *,+ on_sent: Callable[[], Awaitable[None] | None] | None = None,+ ) -> SearchResponse:+ return await self.call_tool(KEYLESS_EXA_SEARCH_TOOL, arguments, on_sent=on_sent)++ @staticmethod+ async def _as_search_response(exchange: _Exchange) -> SearchResponse:+ body = exchange.body+ error = exchange.error+ if exchange.request_id is not None:+ message = _matching_message(exchange.messages, exchange.request_id)+ if message is not None:+ body = await asyncio.to_thread(+ lambda: json.dumps(message, separators=(",", ":")).encode("utf-8")+ )+ elif exchange.messages:+ body = None+ error = error or "connection"+ # Normalize SSE to the matching JSON-RPC envelope so the core mapper has+ # one bounded representation for both MCP transport modes.+ elif exchange.messages:+ body = await asyncio.to_thread(+ lambda: json.dumps(exchange.messages[-1], separators=(",", ":")).encode("utf-8")+ )+ if not error and exchange.status is not None and 300 <= exchange.status < 400:+ error = "redirect"+ return SearchResponse(+ exchange.status,+ exchange.headers,+ body,+ error,+ on_sent_fired=exchange.sent,+ response_received_at=exchange.received_at,+ )+++__all__ = ["KEYLESS_EXA_ENDPOINT", "KEYLESS_EXA_SEARCH_TOOL", "KeylessExaMcpClient"]