Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(agent-bridge,gateway): disclose versions on authenticated surfaces (CHOO-1865)
Louis Amaudruzf30ee71689d7
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.pyindex 9c26129c2..ab743425d 100644--- a/core/switch_core/bridges/agent/api/handlers.py+++ b/core/switch_core/bridges/agent/api/handlers.py@@ -78,10 +78,11 @@ from switch_core.bridges.agent.dependencies import (get_session,)from switch_core.bridges.agent.protocol.connections import (- PROTOCOL_VERSION,+ ClientDeclaration,ConnectionError_,DeliveryFilter,NoStreamAttachedError,+ ProtocolVersionError,RoomOccupiedError,Scope,UnknownConnectionError,@@ -94,6 +95,7 @@ from switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.feature_flag_store import FeatureFlagStorefrom switch_core.feature_flags import is_known_flagfrom switch_core.gateway.known_agents import KNOWN_AGENTS+from switch_core.version import switch_core_versionlogger = logging.getLogger(__name__)@@ -632,7 +634,10 @@ async def poll_events(event_filter: Annotated[str, Query(alias="filter")] = "all",start_from: Annotated[str, Query()] = "head",spawn_capable: Annotated[bool, Query()] = False,- protocol_version: Annotated[int, Query(alias="protocol")] = PROTOCOL_VERSION,+ protocol_version: Annotated[int | None, Query(alias="protocol")] = None,+ protocol_accepts: Annotated[int | None, Query()] = None,+ client: Annotated[str | None, Query()] = None,+ client_version: Annotated[str | None, Query()] = None,rooms: Annotated[str | None, Query()] = None,last_event_id: Annotated[str | None, Header(alias="last-event-id")] = None,) -> EventResponse | Response:@@ -642,6 +647,12 @@ async def poll_events(the client's cursor, then live delivery. Anything else falls back to thelong poll, which is served from the same buffer so the two cannot divergewhile both exist.++ The four declaration parameters are all optional and all default to None,+ meaning *unknown* (CHOO-1865). `protocol` previously defaulted to the+ server's own value, so a client that said nothing was read as having+ agreed — and since no shipped client sent it, the check had never once+ fired. Absent now records as unknown, and still connects."""if accept and "text/event-stream" in accept:return await _open_event_stream(@@ -652,7 +663,12 @@ async def poll_events(event_filter=event_filter,start_from=start_from,spawn_capable=spawn_capable,- protocol_version=protocol_version,+ declaration=ClientDeclaration(+ speaks=protocol_version,+ accepts=protocol_accepts,+ artifact=client,+ version=client_version,+ ),rooms=rooms,last_event_id=last_event_id,)@@ -695,7 +711,7 @@ async def _open_event_stream(event_filter: str,start_from: str,spawn_capable: bool,- protocol_version: int,+ declaration: ClientDeclaration,rooms: str | None,last_event_id: str | None,) -> StreamingResponse:@@ -726,8 +742,27 @@ async def _open_event_stream(delivery_filter=cast(DeliveryFilter, event_filter),spawn_capable=spawn_capable,cursor=cursor,- protocol_version=protocol_version,+ declaration=declaration,)+ except ProtocolVersionError as exc:+ # The refused client never receives a connection_state frame, so this+ # body is the only chance to tell it what the server speaks. Structured+ # rather than a bare string so the runtime can act on it instead of+ # showing the user a sentence to parse (CHOO-1865).+ raise HTTPException(+ status_code=409,+ detail={+ "message": str(exc),+ "contract": "agent-protocol",+ "server": {+ "version": switch_core_version(),+ "speaks": exc.server_speaks,+ "accepts": exc.server_accepts,+ },+ "client": {"speaks": exc.client_speaks, "accepts": exc.client_accepts},+ "remedy": exc.remedy,+ },+ ) from excexcept ConnectionError_ as exc:raise HTTPException(status_code=409, detail=str(exc)) from excdiff --git a/core/switch_core/bridges/agent/api/version_routes.py b/core/switch_core/bridges/agent/api/version_routes.pynew file mode 100644index 000000000..ad9dd1835--- /dev/null+++ b/core/switch_core/bridges/agent/api/version_routes.py@@ -0,0 +1,40 @@+"""Authenticated version disclosure on the agent bridge (CHOO-1865).++Nothing about the server's version is reachable without authenticating. An+exact release string maps directly to known CVEs, and Switch is deployed+publicly by people we will never meet.++This endpoint is for diagnostics, periodic checks and bug reports; it is not on+the critical path. A connecting agent already learns the server's ranges from+the first frame of its event stream, and a refused one learns them from the 409+body — both authenticated, and both arriving without an extra call.++Disclosure is scoped to the caller's credential by *where the route lives*+rather than by inspecting the credential: this app authenticates agents, so it+answers for `agent-protocol` and nothing else. The gateway serves its own at+`/gateway/version` behind its own session cookie.+"""++from __future__ import annotations++from typing import Annotated, Any++from fastapi import APIRouter, Depends++from switch_core.bridges.agent.auth import get_agent_from_scope+from switch_core.db.models import Agent+from switch_core.version import server_declaration++router = APIRouter()++[email protected]("/version")+async def get_version(+ _agent: Annotated[Agent, Depends(get_agent_from_scope)],+) -> dict[str, Any]:+ """What this switch-core is, and what it speaks to agents.++ `version` is null when switch-core cannot read its own version. Null means+ unknown; a client must render it as such rather than as current.+ """+ return server_declaration("agent-protocol")diff --git a/core/switch_core/bridges/agent/app.py b/core/switch_core/bridges/agent/app.pyindex 8a6c452cf..a440c675b 100644--- a/core/switch_core/bridges/agent/app.py+++ b/core/switch_core/bridges/agent/app.py@@ -8,6 +8,7 @@ from fastapi.responses import JSONResponsefrom switch_core.bridges.agent.api.handlers import router as api_routerfrom switch_core.bridges.agent.api.operations import router as operations_router+from switch_core.bridges.agent.api.version_routes import router as version_routerfrom switch_core.bridges.agent.auth import BearerAuthMiddlewarefrom switch_core.bridges.agent.deeplink import router as deeplink_routerfrom switch_core.bridges.agent.dependencies import init_dependencies@@ -135,6 +136,7 @@ def create_agent_bridge_app(app.include_router(api_router, prefix="/agents", tags=["api"])app.include_router(operations_router)app.include_router(deeplink_router, tags=["deeplink"])+ app.include_router(version_router, tags=["version"])app.state.config = configdiff --git a/core/switch_core/bridges/agent/protocol/connections.py b/core/switch_core/bridges/agent/protocol/connections.pyindex 03938ad0b..c68bb2599 100644--- a/core/switch_core/bridges/agent/protocol/connections.py+++ b/core/switch_core/bridges/agent/protocol/connections.py@@ -29,6 +29,8 @@ from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom typing import Literal+from switch_core.contracts import contract_range+logger = logging.getLogger(__name__)Scope = Literal["single", "all"]@@ -40,10 +42,17 @@ DeliveryFilter = Literal["all", "addressed"]HEARTBEAT_INTERVAL_SECONDS = 2.0HEARTBEAT_TTL_SECONDS = 6.0-# Refuse a client that speaks a different protocol rather than degrading in-# ways neither side can see. The runtime lives on the user's machine and Switch-# moves independently.-PROTOCOL_VERSION = 1+# Refuse a client that cannot meet this server's protocol rather than degrading+# in ways neither side can see. The runtime lives on the user's machine and+# Switch moves independently.+#+# Both numbers come from contracts.yaml, the one place a human declares them+# (CHOO-1865). PROTOCOL_VERSION is the newest revision this server implements;+# PROTOCOL_ACCEPTS is the oldest it still handles. They are equal today, and+# the range is what compatibility is judged on so that they need not stay so.+_SERVER_AGENT_PROTOCOL = contract_range("agent-protocol", "switch-core")+PROTOCOL_VERSION = _SERVER_AGENT_PROTOCOL.speaks+PROTOCOL_ACCEPTS = _SERVER_AGENT_PROTOCOL.accepts# Upper bound on simultaneous connections per agent. Runaway growth becomes a# visible error instead of quiet resource creep.@@ -99,13 +108,76 @@ def evicted_session_warning(room_id: str, evicted_connection_id: str) -> str:)+@dataclass(frozen=True)+class ClientDeclaration:+ """What a client said about itself when it opened a connection (CHOO-1865).++ Every field is optional, because a client built before this existed says+ nothing at all. That has to record as *unknown* rather than as a default:+ a default is indistinguishable from an answer, and the whole point is to+ know which clients we cannot account for.++ `speaks` and `accepts` are the client's `agent-protocol` range. `artifact`+ and `version` say which released thing is connecting and where it is —+ they are reported, never judged, since a semver says nothing about+ compatibility.+ """++ speaks: int | None = None+ accepts: int | None = None+ artifact: str | None = None+ version: str | None = None++ @property+ def declares_protocol(self) -> bool:+ return self.speaks is not None++ @property+ def protocol_floor(self) -> int | None:+ """The oldest revision the client handles.++ A client that sends only `speaks` is declaring a single revision, so+ its floor is that same number — which is exactly how the original+ exact-match check behaved.+ """+ if self.speaks is None:+ return None+ return self.accepts if self.accepts is not None else self.speaks++ def as_dict(self) -> dict[str, object]:+ """The declaration as recorded and reported. Absent stays null."""+ return {+ "speaks": self.speaks,+ "accepts": self.protocol_floor,+ "artifact": self.artifact,+ "version": self.version,+ }++class ProtocolVersionError(ConnectionError_):- def __init__(self, requested: int) -> None:+ """A client's declared agent-protocol range cannot meet this server's.++ Carries both ranges, and names which side is behind. A refusal that only+ says "no" leaves the user guessing which thing to update, and guessing+ wrong means downgrading the peer that was already right.+ """++ def __init__(self, *, client_speaks: int, client_accepts: int) -> None:+ remedy = (+ "update the Switch agent runtime"+ if client_speaks < PROTOCOL_ACCEPTS+ else "update switch-core"+ )super().__init__(- f"protocol version {requested} is not supported (server speaks "- f"{PROTOCOL_VERSION}); update the Switch agent runtime"+ f"this client speaks agent-protocol {client_accepts}-{client_speaks} "+ f"and the server speaks {PROTOCOL_ACCEPTS}-{PROTOCOL_VERSION}; the "+ f"ranges do not overlap, so {remedy}")- self.requested = requested+ self.client_speaks = client_speaks+ self.client_accepts = client_accepts+ self.server_speaks = PROTOCOL_VERSION+ self.server_accepts = PROTOCOL_ACCEPTS+ self.remedy = remedyclass TooManyConnectionsError(ConnectionError_):@@ -140,6 +212,9 @@ class Connection:# has been replaced and stop writing.stream_generation: int = 0closed_reason: str | None = None+ # What the client said about itself on connect (CHOO-1865). Defaults to an+ # empty declaration, which means unknown — never "current".+ declaration: ClientDeclaration = field(default_factory=lambda: ClientDeclaration())wake: asyncio.Event = field(default_factory=asyncio.Event)def is_alive(self, now: float) -> bool:@@ -169,7 +244,7 @@ class ConnectionRegistry:delivery_filter: DeliveryFilter,spawn_capable: bool,cursor: int,- protocol_version: int,+ declaration: ClientDeclaration,) -> Connection:"""Open a connection, or reattach to one the client already owns.@@ -178,9 +253,21 @@ class ConnectionRegistry:live id takes it over — "the same client returning" and "the sameclient duplicated" are indistinguishable, and takeover is right forboth.++ A client that declares an `agent-protocol` range with no overlap is+ refused. A client that declares nothing is recorded as unknown and+ connects: unknown is not incompatible, and refusing on silence would+ lock out every client built before it could speak up."""- if protocol_version != PROTOCOL_VERSION:- raise ProtocolVersionError(protocol_version)+ floor = declaration.protocol_floor+ if declaration.speaks is not None and floor is not None:+ overlaps = (+ floor <= PROTOCOL_VERSION and PROTOCOL_ACCEPTS <= declaration.speaks+ )+ if not overlaps:+ raise ProtocolVersionError(+ client_speaks=declaration.speaks, client_accepts=floor+ )existing = self._by_id.get(connection_id)if existing is not None:@@ -195,6 +282,10 @@ class ConnectionRegistry:existing.closed_reason = Noneexisting.stream_attached = Trueexisting.stream_generation += 1+ # A reattach can come from an upgraded client, so the declaration+ # is replaced rather than kept. The connection outlives the socket;+ # what is on the other end of it need not.+ existing.declaration = declarationlogger.info("[CONN] reattached agent=%s connection=%s scope=%s generation=%s",agent_id,@@ -219,16 +310,23 @@ class ConnectionRegistry:last_beat=now,opened_at=now,stream_attached=True,+ declaration=declaration,)self._by_id[connection_id] = connowned.add(connection_id)logger.info(- "[CONN] opened agent=%s connection=%s scope=%s filter=%s spawn=%s",+ "[CONN] opened agent=%s connection=%s scope=%s filter=%s spawn=%s "+ "client=%s version=%s protocol=%s",agent_id,connection_id,scope,delivery_filter,spawn_capable,+ declaration.artifact or "unknown",+ declaration.version or "unknown",+ f"{floor}-{declaration.speaks}"+ if declaration.declares_protocol+ else "unknown",)return conndiff --git a/core/switch_core/bridges/agent/protocol/stream.py b/core/switch_core/bridges/agent/protocol/stream.pyindex 4cb964b28..0a5d7b07e 100644--- a/core/switch_core/bridges/agent/protocol/stream.py+++ b/core/switch_core/bridges/agent/protocol/stream.py@@ -28,6 +28,7 @@ from switch_core.bridges.agent.protocol.event_buffer import (CursorExpiredError,EventBuffer,)+from switch_core.version import server_declarationlogger = logging.getLogger(__name__)@@ -51,6 +52,16 @@ def _frame(event: str, data: dict[str, Any], *, seq: int | None = None) -> bytesdef _connection_state(conn: Connection) -> dict[str, Any]:+ """The first frame of every stream, and where the server declares itself.++ Version disclosure rides this frame rather than an endpoint of its own+ (CHOO-1865): the stream is already authenticated, and nothing about the+ server's version is reachable without authenticating. `protocol` stays as+ it was — clients read it today — and equals the server's `speaks`.++ `server.version` is null when switch-core cannot read its own version.+ Null means unknown and must be rendered as such, never as current.+ """return {"connection_id": conn.id,"agent_id": conn.agent_id,@@ -61,6 +72,11 @@ def _connection_state(conn: Connection) -> dict[str, Any]:"cursor": conn.cursor,"protocol": PROTOCOL_VERSION,"heartbeat_interval_seconds": 2.0,+ "server": server_declaration("agent-protocol"),+ # Echoed back so a client can see what the server understood it to+ # have said — a declaration that silently failed to parse is worse+ # than one never sent, because both sides think it landed.+ "client": conn.declaration.as_dict(),}diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.pyindex 705164176..94749a3a2 100644--- a/core/switch_core/gateway/auth_routes.py+++ b/core/switch_core/gateway/auth_routes.py@@ -21,14 +21,55 @@ from switch_core.gateway.schemas import (AuthConfigResponse,CreateUserRequest,LoginRequest,+ ServerDeclaration,+ SessionUserResponse,UserResponse,)+from switch_core.version import server_declarationlogger = logging.getLogger(__name__)router = APIRouter()+def _gateway_declaration() -> ServerDeclaration:+ return ServerDeclaration.model_validate(server_declaration("gateway-api"))+++def _session_response(user: User) -> SessionUserResponse:+ """An authenticated session, carrying what the server is (CHOO-1865).++ Every response that establishes or confirms a session says so, which means+ a client learns the server's ranges on the call it already makes. The+ authentication surface is frozen and excluded from `gateway-api`, so this+ is the one path that cannot itself be the thing that broke.+ """+ return SessionUserResponse(+ id=user.id,+ name=user.name,+ email=user.email,+ role=user.role,+ created_at=str(user.created_at),+ server=_gateway_declaration(),+ )++[email protected]("/version")+async def get_version(+ _user: Annotated[User, Depends(get_current_user)],+) -> ServerDeclaration:+ """What this switch-core is, and what it speaks to first-party UI clients.++ Authenticated, and scoped to this credential: a gateway session sees+ `gateway-api` and nothing else. `db-schema` is internal to switch-core and+ appears in no externally facing response at all.++ Diagnostics only — a client already receives this on every session+ response, so it never needs an extra call to stay informed.+ """+ return _gateway_declaration()++@router.post("/auth/login")async def login(req: LoginRequest,@@ -36,7 +77,7 @@ async def login(session: Annotated[AsyncSession, Depends(get_session)],user_store: Annotated[UserStore, Depends(get_user_store)],config: Annotated[SwitchConfig, Depends(get_config)],-) -> UserResponse:+) -> SessionUserResponse:if not config.gateway_password_login_enabled:raise HTTPException(status_code=403, detail="Password login is disabled")@@ -47,13 +88,7 @@ async def login(set_session_cookie(response, user, config.jwt_secret_key, config.gateway_cookie_secure)- return UserResponse(- id=user.id,- name=user.name,- email=user.email,- role=user.role,- created_at=str(user.created_at),- )+ return _session_response(user)@router.post("/auth/refresh")@@ -61,7 +96,7 @@ async def refresh(response: Response,user: Annotated[User, Depends(get_current_user)],config: Annotated[SwitchConfig, Depends(get_config)],-) -> UserResponse:+) -> SessionUserResponse:# Re-mint the switch_auth cookie from the still-valid session so an active# client renews before expiry without re-authenticating — provider-agnostic# (works for password and OIDC users alike, since it re-issues from the User@@ -71,13 +106,7 @@ async def refresh(set_session_cookie(response, user, config.jwt_secret_key, config.gateway_cookie_secure)- return UserResponse(- id=user.id,- name=user.name,- email=user.email,- role=user.role,- created_at=str(user.created_at),- )+ return _session_response(user)@router.post("/auth/logout")@@ -102,14 +131,8 @@ async def auth_config(@router.get("/auth/me")async def me(user: Annotated[User, Depends(get_current_user)],-) -> UserResponse:- return UserResponse(- id=user.id,- name=user.name,- email=user.email,- role=user.role,- created_at=str(user.created_at),- )+) -> SessionUserResponse:+ return _session_response(user)@router.get("/users")diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex cf2de62a3..8b2cf63e2 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -498,11 +498,47 @@ class CreateUserRequest(BaseModel):class AuthConfigResponse(BaseModel):# Read unauthenticated by the login page to decide which login methods to# show. `oidc_provider_label` is the button text (e.g. "Okta").+ #+ # Nothing version-related may be added here: this is the one gateway+ # response served without a session, and version disclosure is+ # authenticated everywhere (CHOO-1865).password_login_enabled: booloidc_enabled: booloidc_provider_label: str | None+class ContractRangeResponse(BaseModel):+ """The revisions of one contract this server implements and still handles."""++ speaks: int+ accepts: int+++class ServerDeclaration(BaseModel):+ """What switch-core says about itself to an authenticated client.++ `version` is null when switch-core cannot read its own version. Null means+ unknown and must be rendered as such — never as current.+ """++ version: str | None+ contracts: dict[str, ContractRangeResponse]+++class SessionUserResponse(UserResponse):+ """The authenticated user, plus what the server is (CHOO-1865).++ The server's declaration rides the session response rather than sitting on+ an endpoint of its own, because the authentication surface is deliberately+ frozen — never versioned, permanently backward-compatible, and excluded+ from `gateway-api`. That makes it the one path guaranteed to work, so a+ client can always get far enough in to be told what is wrong. A compat+ check must not depend on the thing whose compatibility is in question.+ """++ server: ServerDeclaration++# ── References ──────────────────────────────────────────────────────────────diff --git a/core/switch_core/version.py b/core/switch_core/version.pyindex 9650a55dc..a03376df8 100644--- a/core/switch_core/version.py+++ b/core/switch_core/version.py@@ -20,11 +20,19 @@ import loggingfrom functools import lru_cachefrom importlib.metadata import PackageNotFoundErrorfrom importlib.metadata import version as distribution_version+from typing import Any++from switch_core.contracts import contract_rangelogger = logging.getLogger(__name__)DISTRIBUTION_NAME = "switch-core"+# Internal to switch-core: it describes the database this process talks to, and+# no external client can act on it. Excluded from every externally facing+# response as a rule the code enforces rather than one reviewers must remember.+INTERNAL_CONTRACTS = frozenset({"db-schema"})+@lru_cache(maxsize=1)def switch_core_version() -> str | None:@@ -45,3 +53,31 @@ def switch_core_version() -> str | None:DISTRIBUTION_NAME,)return None+++def server_declaration(*contracts: str) -> dict[str, Any]:+ """What this server says about itself, for the named contracts only.++ Every caller passes just the contracts its credential entitles it to see,+ so an agent token never learns about the gateway and vice versa. Version+ disclosure is authenticated everywhere; there is no anonymous surface.++ `version` is null when switch-core cannot read its own version. Null means+ unknown and must be rendered as such — never as current.+ """+ leaking = INTERNAL_CONTRACTS.intersection(contracts)+ if leaking:+ raise ValueError(+ f"{sorted(leaking)} are internal to switch-core and must not appear "+ "in a response to any external client"+ )+ return {+ "version": switch_core_version(),+ "contracts": {+ name: {+ "speaks": contract_range(name, "switch-core").speaks,+ "accepts": contract_range(name, "switch-core").accepts,+ }+ for name in contracts+ },+ }diff --git a/core/tests/switch_core/bridges/agent/api/test_beat_cursor_clamp.py b/core/tests/switch_core/bridges/agent/api/test_beat_cursor_clamp.pyindex ad94138d6..b7030486e 100644--- a/core/tests/switch_core/bridges/agent/api/test_beat_cursor_clamp.py+++ b/core/tests/switch_core/bridges/agent/api/test_beat_cursor_clamp.py@@ -20,6 +20,7 @@ from switch_core.bridges.agent.api.handlers import connection_beatfrom switch_core.bridges.agent.api.schemas import ConnectionBeatRequestfrom switch_core.bridges.agent.protocol.connections import (PROTOCOL_VERSION,+ ClientDeclaration,ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer@@ -59,7 +60,7 @@ def _connect(protocol: _Protocol, cursor: int = 0) -> Any:delivery_filter="all",spawn_capable=False,cursor=cursor,- protocol_version=PROTOCOL_VERSION,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),)conn.stream_attached = Truereturn conndiff --git a/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py b/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.pyindex 7cedef2c0..bc468d4cb 100644--- a/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py+++ b/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py@@ -16,7 +16,9 @@ from starlette.responses import StreamingResponsefrom switch_core.bridges.agent.api.handlers import _resolve_start_cursor, poll_eventsfrom switch_core.bridges.agent.protocol.connections import (+ PROTOCOL_ACCEPTS,PROTOCOL_VERSION,+ ClientDeclaration,ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer@@ -55,6 +57,9 @@ async def _call(protocol: _Protocol, **kw: Any) -> Any:"start_from": "head","spawn_capable": False,"protocol_version": PROTOCOL_VERSION,+ "protocol_accepts": None,+ "client": None,+ "client_version": None,"rooms": None,"last_event_id": None,}@@ -121,7 +126,98 @@ async def test_an_incompatible_protocol_version_is_refused() -> None:)assert excinfo.value.status_code == 409- assert "update the Switch agent runtime" in excinfo.value.detail+ # A client ahead of the server means the server is what is behind. The+ # original wording always blamed the runtime, which would have sent the+ # user to downgrade the side that was already right.+ assert excinfo.value.detail["remedy"] == "update switch-core"+++async def test_the_refusal_body_carries_both_ranges() -> None:+ """The refused client never gets a connection_state frame.++ So the 409 is the only place it can learn what the server speaks, and it+ is structured rather than a sentence to parse (CHOO-1865).+ """+ protocol = _Protocol()+ with pytest.raises(HTTPException) as excinfo:+ await _call(+ protocol,+ accept="text/event-stream",+ connection_id="c1",+ protocol_version=PROTOCOL_VERSION + 1,+ )++ detail = excinfo.value.detail+ assert detail["contract"] == "agent-protocol"+ assert detail["server"]["speaks"] == PROTOCOL_VERSION+ assert detail["server"]["accepts"] == PROTOCOL_ACCEPTS+ assert detail["client"] == {+ "speaks": PROTOCOL_VERSION + 1,+ "accepts": PROTOCOL_VERSION + 1,+ }+ assert detail["message"]+++async def test_a_client_that_declares_nothing_connects_and_records_unknown() -> None:+ """Part 1 refuses nobody on silence.++ The parameter used to default to the server's own value, so a silent+ client read as having agreed — and since no shipped client sent it, the+ check had never fired at all. Absent must mean unknown, and unknown must+ still connect.+ """+ protocol = _Protocol()+ await _call(+ protocol,+ accept="text/event-stream",+ connection_id="c1",+ protocol_version=None,+ )++ conn = protocol.connections.get("c1")+ assert conn is not None+ assert conn.declaration == ClientDeclaration()+ assert conn.declaration.declares_protocol is False+++async def test_a_declared_client_is_recorded_in_full() -> None:+ protocol = _Protocol()+ await _call(+ protocol,+ accept="text/event-stream",+ connection_id="c1",+ protocol_version=PROTOCOL_VERSION,+ protocol_accepts=PROTOCOL_ACCEPTS,+ client="agent-runtime",+ client_version="0.1.5",+ )++ conn = protocol.connections.get("c1")+ assert conn is not None+ assert conn.declaration == ClientDeclaration(+ speaks=PROTOCOL_VERSION,+ accepts=PROTOCOL_ACCEPTS,+ artifact="agent-runtime",+ version="0.1.5",+ )+++async def test_an_older_client_inside_the_server_range_is_accepted() -> None:+ """Overlap, not equality, is the test.++ The two numbers are equal today, so this pins the behaviour before a+ future bump makes it observable.+ """+ protocol = _Protocol()+ await _call(+ protocol,+ accept="text/event-stream",+ connection_id="c1",+ protocol_version=PROTOCOL_VERSION,+ protocol_accepts=max(PROTOCOL_ACCEPTS - 1, 1),+ )++ assert protocol.connections.get("c1") is not None# ── Start cursor ────────────────────────────────────────────────────────────@@ -188,7 +284,7 @@ class TestDeclaringARoomAtOpenTakesOver:delivery_filter="all",spawn_capable=False,cursor=0,- protocol_version=PROTOCOL_VERSION,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),)protocol.connections.claim_room(incumbent, "room-1")diff --git a/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.py b/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.pyindex bd488c93a..d145613fa 100644--- a/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.py+++ b/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.py@@ -22,6 +22,7 @@ from switch_core.bridges.agent.operations.definitions import ()from switch_core.bridges.agent.protocol.connections import (PROTOCOL_VERSION,+ ClientDeclaration,ConnectionRegistry,)@@ -48,7 +49,7 @@ def _open(registry: ConnectionRegistry, connection_id: str) -> Any:delivery_filter="all",spawn_capable=False,cursor=0,- protocol_version=PROTOCOL_VERSION,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),)diff --git a/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py b/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.pyindex 422806a66..938d37c63 100644--- a/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py+++ b/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py@@ -28,6 +28,7 @@ from switch_core.bridges.agent.operations.definitions import ()from switch_core.bridges.agent.protocol.connections import (PROTOCOL_VERSION,+ ClientDeclaration,ConnectionRegistry,NoStreamAttachedError,)@@ -49,7 +50,7 @@ def _open(registry: ConnectionRegistry, connection_id: str, agent_id: str = AGENdelivery_filter="all",spawn_capable=False,cursor=0,- protocol_version=PROTOCOL_VERSION,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),)diff --git a/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.py b/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.pyindex 970f5865b..e0a15d1b1 100644--- a/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.py+++ b/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.py@@ -28,6 +28,7 @@ from switch_core.bridges.agent.operations.callctx import (from switch_core.bridges.agent.operations.context import init_operations_protocolfrom switch_core.bridges.agent.protocol.connections import (PROTOCOL_VERSION,+ ClientDeclaration,ConnectionRegistry,)@@ -122,7 +123,7 @@ def _open(registry: ConnectionRegistry, connection_id: str):delivery_filter="all",spawn_capable=False,cursor=0,- protocol_version=PROTOCOL_VERSION,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_connections.py b/core/tests/switch_core/bridges/agent/protocol/test_connections.pyindex 699b66669..0bf89eb47 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_connections.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_connections.py@@ -9,7 +9,9 @@ import pytestfrom switch_core.bridges.agent.protocol.connections import (HEARTBEAT_TTL_SECONDS,MAX_CONNECTIONS_PER_AGENT,+ PROTOCOL_ACCEPTS,PROTOCOL_VERSION,+ ClientDeclaration,ConnectionRegistry,NoStreamAttachedError,ProtocolVersionError,@@ -41,7 +43,7 @@ def _open(delivery_filter=delivery_filter, # type: ignore[arg-type]spawn_capable=spawn_capable,cursor=cursor,- protocol_version=PROTOCOL_VERSION,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),)@@ -81,10 +83,99 @@ def test_incompatible_protocol_is_refused() -> None:delivery_filter="all",spawn_capable=False,cursor=0,- protocol_version=PROTOCOL_VERSION + 1,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION + 1),)+def _open_declaring(+ registry: ConnectionRegistry, declaration: ClientDeclaration, *, cid: str = "c1"+):+ return registry.open(+ agent_id=AGENT,+ connection_id=cid,+ scope="single",+ delivery_filter="all",+ spawn_capable=False,+ cursor=0,+ declaration=declaration,+ )+++def test_a_client_that_declares_nothing_is_admitted_as_unknown() -> None:+ """Unknown is not incompatible.++ Refusing on silence would lock out every client built before there was+ anything to say, and Part 1 of CHOO-1865 refuses nobody.+ """+ registry = ConnectionRegistry()+ conn = _open_declaring(registry, ClientDeclaration())++ assert conn.declaration.declares_protocol is False+ assert conn.declaration.protocol_floor is None+++def test_a_client_declaring_only_speaks_is_read_as_a_single_revision() -> None:+ """Which is exactly how the original exact-match check behaved."""+ declaration = ClientDeclaration(speaks=PROTOCOL_VERSION)++ assert declaration.protocol_floor == PROTOCOL_VERSION+++def test_overlapping_ranges_are_admitted() -> None:+ registry = ConnectionRegistry()+ conn = _open_declaring(+ registry,+ ClientDeclaration(speaks=PROTOCOL_VERSION + 3, accepts=PROTOCOL_ACCEPTS),+ )++ assert conn is not None+++def test_a_client_whose_ceiling_is_below_the_server_floor_is_refused() -> None:+ registry = ConnectionRegistry()+ with pytest.raises(ProtocolVersionError) as excinfo:+ _open_declaring(+ registry,+ ClientDeclaration(+ speaks=PROTOCOL_ACCEPTS - 1, accepts=PROTOCOL_ACCEPTS - 1+ ),+ )++ # The client is behind, so the client is what should move.+ assert excinfo.value.remedy == "update the Switch agent runtime"+++def test_a_client_whose_floor_is_above_the_server_ceiling_is_refused() -> None:+ registry = ConnectionRegistry()+ with pytest.raises(ProtocolVersionError) as excinfo:+ _open_declaring(+ registry,+ ClientDeclaration(+ speaks=PROTOCOL_VERSION + 1, accepts=PROTOCOL_VERSION + 1+ ),+ )++ # The server is behind, so naming the runtime would send the user to+ # downgrade the side that was already right.+ assert excinfo.value.remedy == "update switch-core"+++def test_a_reattach_replaces_the_declaration() -> None:+ """The connection outlives the socket; what is on the other end need not.++ A client can be upgraded and reattach to the same connection id.+ """+ registry = ConnectionRegistry()+ _open_declaring(+ registry, ClientDeclaration(speaks=PROTOCOL_VERSION, version="1.0.0")+ )+ conn = _open_declaring(+ registry, ClientDeclaration(speaks=PROTOCOL_VERSION, version="1.1.0")+ )++ assert conn.declaration.version == "1.1.0"++def test_connection_cap_is_enforced_loudly() -> None:registry = ConnectionRegistry()for i in range(MAX_CONNECTIONS_PER_AGENT):diff --git a/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py b/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.pyindex 2f972e8a7..c73c99632 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py@@ -23,6 +23,7 @@ from typing import Anyfrom switch_core.bridges.agent.protocol.connections import (PROTOCOL_VERSION,+ ClientDeclaration,ConnectionRegistry,)from switch_core.bridges.agent.protocol.service import ProtocolService@@ -102,7 +103,7 @@ def _connected(room: str | None) -> ConnectionRegistry:delivery_filter="all",spawn_capable=False,cursor=0,- protocol_version=PROTOCOL_VERSION,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),)if room:registry.claim_room(conn, room)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_statuses.py b/core/tests/switch_core/bridges/agent/protocol/test_statuses.pyindex 278f5ba95..1ba84e763 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_statuses.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_statuses.py@@ -5,6 +5,7 @@ from typing import Anyfrom switch_core.bridges.agent.protocol.connections import (PROTOCOL_VERSION,+ ClientDeclaration,ConnectionRegistry,)from switch_core.bridges.agent.protocol.statuses import compute_agent_statuses@@ -42,7 +43,7 @@ def _registry(delivery_filter="all",spawn_capable=spawn_capable,cursor=0,- protocol_version=PROTOCOL_VERSION,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),)if room is not None:registry.claim_room(conn, room)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_stream.py b/core/tests/switch_core/bridges/agent/protocol/test_stream.pyindex 0dff4793f..3779a6722 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_stream.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_stream.py@@ -8,10 +8,13 @@ from typing import Anyimport pytest+from switch_core import version as version_modulefrom switch_core.bridges.agent.protocol import stream as stream_modulefrom switch_core.bridges.agent.protocol.connections import (HEARTBEAT_TTL_SECONDS,+ PROTOCOL_ACCEPTS,PROTOCOL_VERSION,+ ClientDeclaration,ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer@@ -75,7 +78,7 @@ def _open(registry: ConnectionRegistry, **kw: Any):"delivery_filter": "all","spawn_capable": False,"cursor": 0,- "protocol_version": PROTOCOL_VERSION,+ "declaration": ClientDeclaration(speaks=PROTOCOL_VERSION),}params.update(kw)return registry.open(**params)@@ -97,6 +100,91 @@ async def test_first_frame_is_the_connection_state() -> None:assert data["protocol"] == PROTOCOL_VERSION+async def test_the_first_frame_declares_the_server(monkeypatch) -> None:+ """Version disclosure rides this frame, not an endpoint of its own.++ The stream is already authenticated, and nothing about the server's+ version is reachable without authenticating (CHOO-1865).+ """+ monkeypatch.setattr(version_module, "switch_core_version", lambda: "9.9.9")+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ ((_, data),) = await _take(stream, 1)++ assert data["server"] == {+ "version": "9.9.9",+ "contracts": {+ "agent-protocol": {+ "speaks": PROTOCOL_VERSION,+ "accepts": PROTOCOL_ACCEPTS,+ }+ },+ }+++async def test_an_unreadable_server_version_is_null_not_a_placeholder(+ monkeypatch,+) -> None:+ """Null means unknown. A placeholder would read as a version we chose."""+ monkeypatch.setattr(version_module, "switch_core_version", lambda: None)+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ ((_, data),) = await _take(stream, 1)++ assert data["server"]["version"] is None+++async def test_the_first_frame_echoes_what_the_client_declared() -> None:+ """So a declaration that failed to parse cannot pass unnoticed.++ Both sides otherwise believe it landed, which is worse than never having+ sent it.+ """+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(+ registry,+ declaration=ClientDeclaration(+ speaks=PROTOCOL_VERSION,+ accepts=PROTOCOL_ACCEPTS,+ artifact="agent-runtime",+ version="0.1.5",+ ),+ )++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ ((_, data),) = await _take(stream, 1)++ assert data["client"] == {+ "speaks": PROTOCOL_VERSION,+ "accepts": PROTOCOL_ACCEPTS,+ "artifact": "agent-runtime",+ "version": "0.1.5",+ }+++async def test_an_undeclared_client_is_echoed_as_all_null() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry, declaration=ClientDeclaration())++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ ((_, data),) = await _take(stream, 1)++ assert data["client"] == {+ "speaks": None,+ "accepts": None,+ "artifact": None,+ "version": None,+ }++async def test_catch_up_then_live_delivery() -> None:registry = ConnectionRegistry()buffer = EventBuffer()@@ -272,7 +360,7 @@ async def test_two_connections_receive_the_same_event(scope: str) -> None:delivery_filter="all",spawn_capable=False,cursor=0,- protocol_version=PROTOCOL_VERSION,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),)registry.claim_room(session, ROOM_A)@@ -283,7 +371,7 @@ async def test_two_connections_receive_the_same_event(scope: str) -> None:delivery_filter="all",spawn_capable=False,cursor=0,- protocol_version=PROTOCOL_VERSION,+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),)registry.claim_room(other_agent, ROOM_A)diff --git a/core/tests/switch_core/bridges/agent/test_version_is_not_public.py b/core/tests/switch_core/bridges/agent/test_version_is_not_public.pynew file mode 100644index 000000000..8c946faa2--- /dev/null+++ b/core/tests/switch_core/bridges/agent/test_version_is_not_public.py@@ -0,0 +1,42 @@+"""Version disclosure is authenticated on every surface (CHOO-1865).++An exact release string maps directly to known CVEs, and Switch is deployed+publicly by people we will never meet. The rule is easy to break by accident —+adding one prefix to an allowlist is a one-line change — so it is pinned here+rather than left to review.+"""++from __future__ import annotations++import pytest++from switch_core.bridges.agent.auth import PUBLIC_PATH_PREFIXES, _is_public_path+++ "path",+ ["/version", "/gateway/version", "/agents/a1/events"],+)+def test_version_bearing_paths_are_not_in_the_public_allowlist(path: str) -> None:+ # /gateway is allowlisted as a whole because the gateway runs its own+ # cookie auth rather than the bearer middleware — it is not unauthenticated.+ assert path not in PUBLIC_PATH_PREFIXES+++def test_the_agent_bridge_version_endpoint_requires_authentication() -> None:+ assert _is_public_path("/version") is False+++def test_the_unauthenticated_allowlist_has_not_grown() -> None:+ """A new public prefix must be a deliberate change, reviewed on purpose.++ Whoever adds one should have to update this test and say why in the commit+ — particularly for anything that could carry a version.+ """+ assert set(PUBLIC_PATH_PREFIXES) == {+ "/health",+ "/.well-known",+ "/oauth",+ "/gateway",+ "/deeplink",+ }diff --git a/core/tests/switch_core/test_version.py b/core/tests/switch_core/test_version.pyindex 5bcf6837f..6e350b873 100644--- a/core/tests/switch_core/test_version.py+++ b/core/tests/switch_core/test_version.py@@ -11,7 +11,7 @@ from pathlib import Pathimport pytestfrom switch_core import version as version_module-from switch_core.version import switch_core_version+from switch_core.version import server_declaration, switch_core_versionPYPROJECT = Path(__file__).resolve().parents[2] / "pyproject.toml"@@ -61,3 +61,38 @@ def test_warns_when_the_version_cannot_be_read(with caplog.at_level(logging.WARNING, logger=version_module.__name__):switch_core_version()assert any(record.levelno == logging.WARNING for record in caplog.records)+++# ── Disclosure ───────────────────────────────────────────────────────────────+++def test_a_declaration_carries_only_the_contracts_asked_for() -> None:+ """Least disclosure: a credential sees its own contract and no others."""+ declared = server_declaration("agent-protocol")++ assert set(declared["contracts"]) == {"agent-protocol"}+ assert declared["contracts"]["agent-protocol"].keys() == {"speaks", "accepts"}+++def test_a_declaration_reports_an_unknown_version_as_null(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(version_module, "switch_core_version", lambda: None)++ assert server_declaration("agent-protocol")["version"] is None+++def test_db_schema_cannot_be_disclosed() -> None:+ """Internal to switch-core, and no external client can act on it.++ Enforced here rather than left to reviewers to remember, because the cost+ of forgetting is a permanent leak in a public deployment.+ """+ with pytest.raises(ValueError, match="internal to switch-core"):+ server_declaration("db-schema")+++def test_db_schema_cannot_ride_alongside_a_public_contract() -> None:+ """The likelier mistake than asking for it alone."""+ with pytest.raises(ValueError, match="internal to switch-core"):+ server_declaration("gateway-api", "db-schema")