Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(agent-bridge): record what each client declared, durably (CHOO-1865)

Louis Amaudruz1d7f99d9609e
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index ab743425d..99f9d955d 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -766,6 +766,10 @@ async def _open_event_stream(
except ConnectionError_ as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
+ # After the connection is open, so a bookkeeping failure can never be the
+ # reason an agent could not connect.
+ await protocol.record_client_declaration(agent.id, declaration)
+
# Rooms are claimed before the stream starts, not after it opens. A client
# reconnecting already knows which room it was in; making it re-subscribe
# afterwards would race the catch-up, and buffered events for that room
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 4f9239390..0b86a787c 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -6,6 +6,7 @@ import re
import secrets
import uuid
from collections.abc import Sequence
+from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from nio import (
@@ -25,7 +26,10 @@ from switch_core.bridges.agent.protocol.agent_detail import (
list_agent_summaries,
reparent_agent,
)
-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry
+from switch_core.bridges.agent.protocol.connections import (
+ ClientDeclaration,
+ ConnectionRegistry,
+)
from switch_core.bridges.agent.protocol.event_buffer import EventBuffer
from switch_core.bridges.agent.protocol.statuses import compute_agent_statuses
from switch_core.bridges.agent.protocol.types import (
@@ -451,6 +455,50 @@ class ProtocolService:
exc_info=True,
)
+ async def record_client_declaration(
+ self, agent_id: str, declaration: ClientDeclaration
+ ) -> None:
+ """Persist what a client last said about itself (CHOO-1865).
+
+ Connections live in memory, so what is running right now dies with the
+ process. This is the durable half, and the reason it belongs in Part 1
+ at all: raising an `accepts` floor is a decision made offline, and it
+ can only be made safely against a record of what is actually deployed.
+ Without it the question "what would this break?" has no answer but a
+ guess.
+
+ Last write wins, per agent. Nothing acts on it yet.
+
+ A failure here is logged and swallowed: this is bookkeeping about a
+ connection, and losing a version record must never stop an agent
+ connecting. It is logged at warning because a persistently silent
+ recorder would leave the same blind spot as a client that never
+ declared, and that must not pass unnoticed.
+ """
+ if not declaration.declares_protocol and declaration.version is None:
+ return
+
+ record = declaration.as_dict()
+ record["recorded_at"] = datetime.now(UTC).isoformat()
+ try:
+ async with self.session_factory() as session:
+ agent = await self.agent_store.get(session, agent_id)
+ if agent is None:
+ return
+ metadata = (
+ dict(agent.metadata_) if isinstance(agent.metadata_, dict) else {}
+ )
+ metadata["client_declaration"] = record
+ await self.agent_store.update(session, agent_id, metadata_=metadata)
+ await session.commit()
+ except Exception:
+ logger.warning(
+ "Could not record the client declaration for agent %s; it will "
+ "read as unknown until the next connect",
+ agent_id,
+ exc_info=True,
+ )
+
async def update_agent(
self,
agent_id: str,
diff --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.py
index bc468d4cb..2b2017948 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
@@ -31,6 +31,12 @@ class _Protocol:
self.event_buffer = EventBuffer()
self.connections = ConnectionRegistry()
self.polled = False
+ self.recorded: list[tuple[str, ClientDeclaration]] = []
+
+ async def record_client_declaration(
+ self, agent_id: str, declaration: ClientDeclaration
+ ) -> None:
+ self.recorded.append((agent_id, declaration))
async def poll_events(self, agent_id: str, timeout: float) -> list[Any]:
self.polled = True
@@ -192,14 +198,36 @@ async def test_a_declared_client_is_recorded_in_full() -> None:
client_version="0.1.5",
)
- conn = protocol.connections.get("c1")
- assert conn is not None
- assert conn.declaration == ClientDeclaration(
+ declared = ClientDeclaration(
speaks=PROTOCOL_VERSION,
accepts=PROTOCOL_ACCEPTS,
artifact="agent-runtime",
version="0.1.5",
)
+ conn = protocol.connections.get("c1")
+ assert conn is not None
+ assert conn.declaration == declared
+ # Also persisted, since connections die with the process and an accepts
+ # floor is raised offline against what is actually deployed.
+ assert protocol.recorded == [(AGENT_ID, declared)]
+
+
+async def test_a_refused_client_is_not_recorded() -> None:
+ """Recording happens after the connection opens.
+
+ A bookkeeping failure must never be why an agent could not connect, and a
+ client we refused is not one we are running.
+ """
+ protocol = _Protocol()
+ with pytest.raises(HTTPException):
+ await _call(
+ protocol,
+ accept="text/event-stream",
+ connection_id="c1",
+ protocol_version=PROTOCOL_VERSION + 1,
+ )
+
+ assert protocol.recorded == []
async def test_an_older_client_inside_the_server_range_is_accepted() -> None:
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.py b/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.py
new file mode 100644
index 000000000..d8b4b3ac8
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.py
@@ -0,0 +1,176 @@
+"""Persisting what a client last said about itself (CHOO-1865).
+
+Connections live in memory, so what is running right now dies with the process.
+This is the durable half — and the reason it is in Part 1 at all: raising an
+`accepts` floor is a decision made offline, and it can only be made safely
+against a record of what is actually deployed.
+"""
+
+from __future__ import annotations
+
+import logging
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from switch_core.bridges.agent.protocol.connections import ClientDeclaration
+from switch_core.bridges.agent.protocol.service import ProtocolService
+
+AGENT_ID = "agent-1"
+
+
+class _Session:
+ def __init__(self) -> None:
+ self.committed = False
+
+ async def commit(self) -> None:
+ self.committed = True
+
+
+class _AgentStore:
+ """Just enough of AgentStore to observe what would be written."""
+
+ def __init__(
+ self, metadata: dict[str, Any] | None, *, missing: bool = False
+ ) -> None:
+ self.agent = (
+ None if missing else SimpleNamespace(id=AGENT_ID, metadata_=metadata)
+ )
+ self.updates: list[dict[str, Any]] = []
+
+ async def get(self, session: Any, agent_id: str) -> Any:
+ return self.agent
+
+ async def update(self, session: Any, agent_id: str, **kwargs: Any) -> None:
+ self.updates.append(kwargs)
+
+
+def _service(store: _AgentStore) -> ProtocolService:
+ """A ProtocolService with only the two collaborators this path touches.
+
+ Constructed without __init__ on purpose: the real one wires two dozen
+ dependencies, none of which this method uses, and threading them all
+ through would test the fixture rather than the behaviour.
+ """
+ service = ProtocolService.__new__(ProtocolService)
+ session = _Session()
+
+ @asynccontextmanager
+ async def factory():
+ yield session
+
+ service.session_factory = factory # type: ignore[assignment]
+ service.agent_store = store # type: ignore[assignment]
+ return service
+
+
+async def test_a_declaration_is_written_to_agent_metadata() -> None:
+ store = _AgentStore({})
+ await _service(store).record_client_declaration(
+ AGENT_ID,
+ ClientDeclaration(
+ speaks=1, accepts=1, artifact="agent-runtime", version="0.1.5"
+ ),
+ )
+
+ (update,) = store.updates
+ recorded = update["metadata_"]["client_declaration"]
+ assert recorded["speaks"] == 1
+ assert recorded["accepts"] == 1
+ assert recorded["artifact"] == "agent-runtime"
+ assert recorded["version"] == "0.1.5"
+
+
+async def test_the_record_is_timestamped() -> None:
+ """Otherwise a declaration from a year ago reads like one from today.
+
+ Deciding whether a floor is safe to raise depends on whether anything is
+ still on the old revision, which is a question about *when*.
+ """
+ store = _AgentStore({})
+ await _service(store).record_client_declaration(
+ AGENT_ID, ClientDeclaration(speaks=1, version="0.1.5")
+ )
+
+ (update,) = store.updates
+ assert update["metadata_"]["client_declaration"]["recorded_at"]
+
+
+async def test_existing_metadata_is_preserved() -> None:
+ """Agent.metadata_ is shared with known_agent_options and others."""
+ store = _AgentStore({"known_agent_options": {"repo_dir": "/w"}})
+ await _service(store).record_client_declaration(
+ AGENT_ID, ClientDeclaration(speaks=1, version="0.1.5")
+ )
+
+ (update,) = store.updates
+ assert update["metadata_"]["known_agent_options"] == {"repo_dir": "/w"}
+
+
+async def test_a_client_that_declared_nothing_writes_nothing() -> None:
+ """Unknown is the absence of a record, not a record saying unknown.
+
+ Writing one would make a silent client indistinguishable from one that
+ connected and answered.
+ """
+ store = _AgentStore({})
+ await _service(store).record_client_declaration(AGENT_ID, ClientDeclaration())
+
+ assert store.updates == []
+
+
+async def test_a_client_declaring_only_its_version_is_still_recorded() -> None:
+ """The artifact version is worth having even with no protocol range."""
+ store = _AgentStore({})
+ await _service(store).record_client_declaration(
+ AGENT_ID, ClientDeclaration(version="0.1.5")
+ )
+
+ (update,) = store.updates
+ assert update["metadata_"]["client_declaration"]["version"] == "0.1.5"
+
+
+async def test_a_missing_agent_writes_nothing() -> None:
+ store = _AgentStore(None, missing=True)
+ await _service(store).record_client_declaration(
+ AGENT_ID, ClientDeclaration(speaks=1, version="0.1.5")
+ )
+
+ assert store.updates == []
+
+
+async def test_a_write_failure_is_warned_about_but_not_raised(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Losing a version record must never stop an agent connecting.
+
+ Warned rather than swallowed silently: a persistently failing recorder
+ leaves the same blind spot as a client that never declared, and that must
+ not pass unnoticed.
+ """
+ store = _AgentStore({})
+
+ async def _boom(session: Any, agent_id: str, **kwargs: Any) -> None:
+ raise RuntimeError("database is on fire")
+
+ store.update = _boom # type: ignore[assignment]
+
+ with caplog.at_level(logging.WARNING):
+ await _service(store).record_client_declaration(
+ AGENT_ID, ClientDeclaration(speaks=1, version="0.1.5")
+ )
+
+ assert any(record.levelno == logging.WARNING for record in caplog.records)
+
+
+async def test_the_latest_declaration_replaces_the_previous_one() -> None:
+ """Last write wins: an upgraded client is not a second client."""
+ store = _AgentStore({"client_declaration": {"version": "0.1.4", "speaks": 1}})
+ await _service(store).record_client_declaration(
+ AGENT_ID, ClientDeclaration(speaks=1, version="0.1.5")
+ )
+
+ (update,) = store.updates
+ assert update["metadata_"]["client_declaration"]["version"] == "0.1.5"