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
Remove server-side connectors and the OpenCode connector (CHOO-1322) (#1070)
Christian McDermottf5b81ccc4a89
diff --git a/.env.example b/.env.exampleindex 550641ef1..dccc3f259 100644--- a/.env.example+++ b/.env.example@@ -333,10 +333,10 @@ MATTERMOST_USER_PASSWORD=# ── Outbound URLs ────────────────────────────────────────────────────────────# Private hosts Switch may reach at a URL a tenant or agent supplied (a-# Mattermost server, an OpenCode server, an agent icon): hostnames and CIDRs,-# comma-separated. Every other non-public address is refused. `localhost`-# covers the local-dev Mattermost and an OpenCode server on this machine; the-# standalone compose always adds `mattermost` to whatever is listed here.+# Mattermost server, an agent icon): hostnames and CIDRs, comma-separated.+# Every other non-public address is refused. `localhost` covers the local-dev+# Mattermost; the standalone compose always adds `mattermost` to whatever is+# listed here.OUTBOUND_ALLOWED_PRIVATE_HOSTS=localhost# ── OIDC (optional — MCP OAuth token validation; bring your own IdP) ─────────diff --git a/CLAUDE.md b/CLAUDE.mdindex ac8abc3ce..5542b3edd 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -82,7 +82,7 @@ just test -k "test_name" # run specific test- `clients/` — room participants: `actor.py` (identity, membership, writes: `HumanActor`, `AgentActor`, `SystemActor`) and `consumer.py` (the `Consumer` delivery loop and hooks), subclassed by `CommandConsumer` (`command_consumer.py`) and `WorkspaceConsumer` (`workspace_consumer.py`)- `delivery/` decides who a row is for: `addressing.py` (the rules), `router.py` (`MessageRouter`, which decides every row for every agent in its room as the row is written, in the same transaction) and `recipient.py` (`AgentRecipient`, one agent's decisions and the replies posted on its behalf)- `bridges/` — External integrations- - `agent/` — Agent Bridge (HTTP API, MCP server, server-side connectors); `protocol/agent_core.py` is `AgentCore`, `protocol/agent_connections.py` holds each `AgentConnection`+ - `agent/` — Agent Bridge (HTTP API, MCP server); `protocol/agent_core.py` is `AgentCore`, `protocol/agent_connections.py` holds each `AgentConnection`- `collaboration/` — Collaboration Bridge: one `CollaborationCore` per workspace, driving a `PlatformAdapter` (Slack, Mattermost, Discord, Teams, Telegram)- `resource/` — Resource Bridge (platform resource management)- `gateway/` — Management API for the frontenddiff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex 548532ce7..e8c2d0543 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -475,8 +475,8 @@ none of it is needed to take part in a conversation.so the agent is not still shown under its old label. Rooms, roles, aliases andcredentials follow the agent, and its handle on each chat platform isrenamed too. It is refused for a name in use, one that clashes with an alias- or role in the agent's rooms or a handle on a chat platform, a subagent or a- parent of subagents, and an agent a server connector found. The response+ or role in the agent's rooms or a handle on a chat platform, a subagent, and+ a parent of subagents. The responsecarries `renamed`: `bridge_failures` lists platforms not yet updated (therename stands; each catches up when its bridge next starts) and`templates_mentioning_old_name` lists saved templates still using the old@@ -495,9 +495,8 @@ none of it is needed to take part in a conversation.deleted. It deletes nothing: Switch posts the request in your connectedroom, and only the agent's owner or a workspace admin can carry it out bysending `!delete-agent <name> confirm` within two minutes. Needs "can- manage agents"; refused for yourself, an agent that can manage agents, and- a connector's agent. Confirm with the person asking first, then tell them- what to send.+ manage agents"; refused for yourself and for an agent that can manage+ agents. Confirm with the person asking first, then tell them what to send.**Address by `name`, not `display_name`.** `list_agents` and`get_agent_detail` return both. `name` is the machine identifier and the onlydiff --git a/console/tooling-e2e/surface/exemptions.json b/console/tooling-e2e/surface/exemptions.jsonindex 08048227b..b49e321e7 100644--- a/console/tooling-e2e/surface/exemptions.json+++ b/console/tooling-e2e/surface/exemptions.json@@ -100,7 +100,6 @@"DELETE /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}","DELETE /gateway/collaborations/{bridge_id}/teams/{team_id}","DELETE /gateway/connector-apps/{service}",- "DELETE /gateway/connectors/{connector_id}","DELETE /gateway/documents/{document_id}","DELETE /gateway/management/agents/{agent_id}","DELETE /gateway/management/controllers/{controller_id}",@@ -155,9 +154,6 @@"GET /gateway/collaborations/{bridge_id}/users","GET /gateway/connector-apps","GET /gateway/connector-apps/{service}/impact",- "GET /gateway/connectors",- "GET /gateway/connectors/types",- "GET /gateway/connectors/{connector_id}","GET /gateway/documents","GET /gateway/documents/{document_id}","GET /gateway/documents/{document_id}/rooms",@@ -253,7 +249,6 @@"POST /gateway/collaborations/{bridge_id}/teams/{team_id}","POST /gateway/connector-apps/{service}/check","POST /gateway/connector-apps/{service}/import",- "POST /gateway/connectors","POST /gateway/documents","POST /gateway/hosted-machines/ensure","POST /gateway/hosted-machines/{machine_id}/lifecycle",diff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.jsonindex b2632169c..0c5605645 100644--- a/console/tooling-e2e/surface/server-surface.json+++ b/console/tooling-e2e/surface/server-surface.json@@ -119,11 +119,6 @@"service_connections"]},- {- "route": "DELETE /gateway/connectors/{connector_id}",- "auth": "session",- "flags": []- },{"route": "DELETE /gateway/documents/{document_id}","auth": "session",@@ -435,21 +430,6 @@"service_connections"]},- {- "route": "GET /gateway/connectors",- "auth": "session",- "flags": []- },- {- "route": "GET /gateway/connectors/types",- "auth": "session",- "flags": []- },- {- "route": "GET /gateway/connectors/{connector_id}",- "auth": "session",- "flags": []- },{"route": "GET /gateway/docs","auth": "none",@@ -1030,11 +1010,6 @@"service_connections"]},- {- "route": "POST /gateway/connectors",- "auth": "session",- "flags": []- },{"route": "POST /gateway/documents","auth": "session",diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 6130fe1db..26738bf69 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -2200,8 +2200,8 @@ async def request_agent_deletion(agent_id: str) -> dict[str, Any]:minutes; otherwise it lapses. Confirm with the person asking before youcall this, and tell them what to send.- Refused for an agent of another owner, yourself, an agent that can manage- agents, and one a server connector found.+ Refused for an agent of another owner, yourself, and an agent that can+ manage agents.Args:agent_id: The agent to delete (`id` from `list_agents`).@@ -2262,8 +2262,8 @@ async def update_agent_detail(notes-writer); otherwise the label stays. Rooms, roles, aliases andcredentials follow; its handle on each chat platform is renamedtoo. Refused for a name in use, one that clashes with an alias or- role in its rooms or a handle on a chat platform, a subagent or a- parent of subagents, and an agent a server connector found.+ role in its rooms or a handle on a chat platform, a subagent, and a+ parent of subagents.description: What the agent is for.display_name: Human label shown next to its name; "" clears it.icon_url: An https link to its icon; "" clears it. A server withdiff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex 640d56286..9636f41f3 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -64,10 +64,6 @@ from switch_core.bridges.agent.protocol.types import (ToolCallReport,ToolSpec,)-from switch_core.bridges.agent.registration_bootstrap import (- REGISTRATION_KEY_TYPES,- resolve_registration_owner_id,-)from switch_core.bridges.collaboration.adapter import (AgentIdentity,AgentIdentityConflict,@@ -115,7 +111,7 @@ from switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.user_store import UserStore-from switch_core.db.tenant_lookup import all_tenant_ids, tenant_of_api_key+from switch_core.db.tenant_lookup import all_tenant_idsfrom switch_core.deeplinks import deeplink_for_platformfrom switch_core.events import (LlmCallReport as RoomLlmCallReport,@@ -296,17 +292,6 @@ class AgentDeletionResult:bridge_failures: list[str]-class BootstrapOwnerMisconfiguredError(Exception):- """Raised when the deployment-wide bootstrap key's owner account cannot- be resolved or trusted (see ``registration_bootstrap.py``).-- Deliberately not a ``PermissionError``: the presented token is valid, so- this is a deployment misconfiguration, not a bad credential. A caller- that catches ``PermissionError`` to mean "bad token" must not also catch- this and report the same thing.- """--def _describe_room(room: Room) -> RoomDescriptor:return RoomDescriptor(id=room.id,@@ -438,8 +423,8 @@ class AgentCore:) -> RegistrationResult:"""Register or re-register an agent.- Pass ``owner_id`` directly (gateway flow) or use- ``register_agent_with_token`` to resolve a registration token first.+ The caller resolves ``owner_id``: the gateway from the signed-in+ person, the HTTP registration endpoint from the registration token.``parent_agent_id`` links this agent as a child of another (a ClaudeCode subagent registered under the user's main agent); None for an@@ -610,91 +595,6 @@ class AgentCore:oauth_client_id=oauth_client_id,)- async def register_agent_with_token(- self,- *,- registration_token: str,- name: str,- description: str,- display_name: str | None = None,- connector_type: str,- integration_profile: IntegrationProfile,- tools: list[ToolSpec] | None = None,- models: list[ModelSpec] | None = None,- metadata: dict[str, Any] | None = None,- overwrite: bool = False,- addressing_policy: AddressingPolicy | None = default_agent_policy(),- ) -> RegistrationResult:- """Resolve a registration token to its owner, then register the agent.-- Raises PermissionError if the token does not match a stored ApiKey of- a registration type (see ``registration_bootstrap.REGISTRATION_KEY_TYPES``).- Raises BootstrapOwnerMisconfiguredError if the token is valid but its- bootstrap owner cannot be resolved or trusted — a deployment fault,- not a bad credential, so callers must not conflate it with the- PermissionError above (the detail is logged here, not in the- exception, to match the HTTP registration path's handling of the- same failure).- Raises AgentExistsError if the name is taken and ``overwrite`` is False.-- The token also decides the *tenant* the new agent and its API key land- in, and that is bound here rather than left to the caller. The HTTP- registration endpoint has ``BearerAuthMiddleware`` in front of it doing- the same thing. This path does not: a server-side connector calls it- in-process from ``server_connectors/core.py``, which binds its own- row's tenant around the call (``_register_agent``) — from boot, and- from ``POST /connectors``, where the tenant already bound is the- *requesting operator's*, which is not necessarily the connector's.-- So the binding here is not filling a vacuum; it is overriding whatever- the caller had, with the one thing that is authoritative for these- rows. Bearer authentication later reads ``api_keys.tenant_id`` back as- the source of truth, so a key filed under the wrong tenant would keep- confirming itself on every subsequent call.- """- token_hash = hashlib.sha256(registration_token.encode()).hexdigest()- # Resolving a credential is the read that *produces* a tenant, so it- # cannot be answered under one: doing so is either a tautology or a- # false "invalid token". `key_hash` is one of the two columns- # deliberately left globally unique for exactly this, and the- # exemption (`db/tenant_lookup.py`) turns it into a tenant id. The key- # row itself, and the owner resolution that reads it, are then- # ordinary scoped reads under that tenant.- tenant_id = await tenant_of_api_key(self.session_factory, token_hash)- if tenant_id is None:- raise PermissionError("Invalid registration token")- async with tenant_session(self.session_factory, tenant_id) as session:- key = await self.api_key_store.get_by_hash(session, token_hash)- if key is None or key.type not in REGISTRATION_KEY_TYPES:- raise PermissionError("Invalid registration token")- try:- owner_id = await resolve_registration_owner_id(- session, self.user_store, key- )- except RuntimeError as exc:- logger.error(- "Agent-registration bootstrap owner resolution failed: %s", exc- )- raise BootstrapOwnerMisconfiguredError(- "Agent registration is temporarily unavailable"- ) from exc-- with tenant_scope(tenant_id):- return await self.register_agent(- name=name,- description=description,- display_name=display_name,- connector_type=connector_type,- integration_profile=integration_profile,- tools=tools,- models=models,- metadata=metadata,- owner_id=owner_id,- overwrite=overwrite,- addressing_policy=addressing_policy,- registration_path="bootstrap",- )-async def _create_agent(self,*,@@ -819,8 +719,8 @@ class AgentCore:# rotates credentials and rebuilds the profile, and callers that know# nothing about icons must not wipe one the owner chose.icon_fields = {} if icon_url is None else {"icon_url": icon_url}- # Same for the display name: a connector re-registers on every startup- # and knows nothing about it.+ # Same for the display name: a client that re-registers on every+ # launch knows nothing about it.display_name_fields = ({} if display_name is None else {"display_name": display_name})@@ -1117,8 +1017,7 @@ class AgentCore:unsafe to render (InvalidDisplayName), or no such agent.AgentExistsError: another agent has the name.AgentRenameRefused: a clash in a room or on a platform, or an agent- that cannot be renamed (a subagent, a parent of subagents, or- one a server connector discovered).+ that cannot be renamed (a subagent or a parent of subagents).RuntimeError: no tenant is bound."""(@@ -1256,8 +1155,8 @@ class AgentCore:Raises:PermissionError: the target belongs to another owner.- AgentRenameRefused: the target is the caller itself, an agent that- can manage agents, or one a server connector found.+ AgentRenameRefused: the target is the caller itself, or an agent+ that can manage agents.ValueError: no such agent or room.RuntimeError: deletion requests are not wired in this process."""@@ -1284,11 +1183,6 @@ class AgentCore:"agent cannot ask for it to be deleted. Its owner can delete ""it from the gateway or with `!delete-agent`.")- if (target.metadata_ or {}).get("server_connector_id"):- raise AgentRenameRefused(- f"Agent '{target.name}' was found by a server connector, which "- "would bring it back. Remove it at its source."- )await record_audit_event(session,tenant_id=tenant_id,@@ -1340,11 +1234,6 @@ class AgentCore:async def _check_renamable(self, session: AsyncSession, agent: Agent, new_name: str) -> None:- if (agent.metadata_ or {}).get("server_connector_id"):- raise AgentRenameRefused(- f"Agent '{agent.name}' was found by a server connector, which "- "would bring it back under its old name. Rename it at its source."- )if agent.parent_agent_id is not None:raise AgentRenameRefused(f"Agent '{agent.name}' is a subagent; its name comes from its "diff --git a/core/switch_core/bridges/agent/server_connectors/__init__.py b/core/switch_core/bridges/agent/server_connectors/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/core/switch_core/bridges/agent/server_connectors/base.py b/core/switch_core/bridges/agent/server_connectors/base.pydeleted file mode 100644index a30d1d16f..000000000--- a/core/switch_core/bridges/agent/server_connectors/base.py+++ /dev/null@@ -1,106 +0,0 @@-from __future__ import annotations--from abc import ABC, abstractmethod-from collections.abc import Sequence-from typing import TYPE_CHECKING--from pydantic import BaseModel--from switch_core.bridges.agent.protocol.types import (- CommandPayload,- IntegrationProfile,- MessagePayload,- ModelSpec,- ToolSpec,-)--if TYPE_CHECKING:- from switch_core.bridges.agent.protocol.types import LlmCallReport, ToolCallReport---class ConnectorReporter:- """Callback interface for connectors to send messages and report events.-- Injected by the core per agent handle, keeping connectors- decoupled from the bridge API client.- """-- async def send_message(self, room_id: str, content: str) -> None:- raise NotImplementedError-- async def report_events(- self, room_id: str, events: Sequence[ToolCallReport | LlmCallReport]- ) -> None:- raise NotImplementedError-- async def send_status(self, room_id: str, detail: str) -> None:- raise NotImplementedError-- async def set_typing(self, room_id: str, is_typing: bool) -> None:- raise NotImplementedError---class ServerSideConnectorConfig(BaseModel):- """Base configuration for server-side connectors. Subclassed per connector type."""---class DiscoveredAgent(BaseModel):- """An agent discovered from an external platform."""-- name: str- description: str- integration_profile: IntegrationProfile- tools: list[ToolSpec] = []- models: list[ModelSpec] = []---class ServerSideConnector(ABC):- """Base class for server-side agent connectors.-- Subclasses implement the external-platform-specific logic:- discovering agents, forwarding messages, and managing sessions.- The lifecycle service handles all Switch API communication.- """-- @classmethod- def outbound_urls(cls, connection_config: dict[str, object]) -> list[str]:- """The URLs in this config that Switch connects to.-- Checked against the deployment's `OutboundPolicy` when the connector is- registered and each time it starts.- """- return []-- @abstractmethod- async def start(self) -> None:- """Initialize connection to the external platform."""-- @abstractmethod- async def stop(self) -> None:- """Clean up connection to the external platform."""-- @abstractmethod- async def discover_agents(self) -> list[DiscoveredAgent]:- """Discover available agents on the external platform."""-- @abstractmethod- async def handle_message(- self,- agent_name: str,- room_id: str,- message: MessagePayload,- reporter: ConnectorReporter,- ) -> str | None:- """Handle an addressed message. Return response text, or None if- the connector already sent the response via the reporter."""-- async def handle_context(- self, agent_name: str, room_id: str, message: MessagePayload- ) -> None:- """Inject an unaddressed message as context (no response expected)."""-- @abstractmethod- async def handle_command(- self, agent_name: str, room_id: str, command: CommandPayload- ) -> None:- """Handle a command event."""diff --git a/core/switch_core/bridges/agent/server_connectors/core.py b/core/switch_core/bridges/agent/server_connectors/core.pydeleted file mode 100644index 0ca9ab7c2..000000000--- a/core/switch_core/bridges/agent/server_connectors/core.py+++ /dev/null@@ -1,277 +0,0 @@-from __future__ import annotations--import asyncio-import logging-from collections.abc import Sequence-from typing import TYPE_CHECKING--from switch_core.bridges.agent.protocol.types import (- CommandPayload,- LlmCallReport,- MessagePayload,- ToolCallReport,-)-from switch_core.bridges.agent.server_connectors.base import (- ConnectorReporter,- DiscoveredAgent,- ServerSideConnector,-)-from switch_core.tenant_context import no_tenant, tenant_scope--if TYPE_CHECKING:- from switch_core.bridges.agent.protocol.agent_core import AgentCore--logger = logging.getLogger(__name__)--# Long-poll timeout for the per-agent poll loop. This is the upper bound on-# how long an idle agent goes between heartbeats (touch_heartbeat fires when-# poll_events is (re)entered), so AgentSessionStore.HEARTBEAT_TTL must stay-# comfortably above it or healthy agents flap to "disconnected" between polls.-CONNECTOR_POLL_TIMEOUT_SECONDS = 30---class _AgentHandle:- def __init__(self, agent_id: str, agent_name: str) -> None:- self.agent_id = agent_id- self.agent_name = agent_name- self.task: asyncio.Task[None] | None = None---class _ProtocolReporter(ConnectorReporter):- """Reporter implementation backed by an in-process AgentCore call."""-- def __init__(self, protocol: AgentCore, handle: _AgentHandle) -> None:- self._protocol = protocol- self._handle = handle-- async def send_message(self, room_id: str, content: str) -> None:- await self._protocol.send_message(self._handle.agent_id, room_id, content)-- async def report_events(- self, room_id: str, events: Sequence[ToolCallReport | LlmCallReport]- ) -> None:- await self._protocol.report_events(self._handle.agent_id, room_id, list(events))-- async def send_status(self, room_id: str, detail: str) -> None:- await self._protocol.update_status(self._handle.agent_id, room_id, detail)-- async def set_typing(self, room_id: str, is_typing: bool) -> None:- await self._protocol.set_typing(self._handle.agent_id, room_id, is_typing)---class ConnectorCore:- """Runtime orchestrator for a single server-side connector.-- Discovers agents on the external platform, registers them through the- in-process AgentCore, and runs per-agent poll loops that forward- messages between the connector and Switch.-- Server-side connectors live in the same process as Switch core, so they- do not need HTTP — they call ``AgentCore`` directly. (External- agent integrations are the ones that go over the HTTP agent bridge.)- """-- def __init__(- self,- *,- connector_id: str,- connector_tenant_id: str,- connector_type: str,- connector: ServerSideConnector,- registration_token: str,- protocol: AgentCore,- ) -> None:- self._connector_id = connector_id- # The tenant of the connector's own row. Held, never bound for the- # life of anything: each poll and each event it produces binds it for- # that piece of work and releases it again.- self._connector_tenant_id = connector_tenant_id- self._connector_type = connector_type- self._connector = connector- self._registration_token = registration_token- self._protocol = protocol- self._agents: dict[str, _AgentHandle] = {}-- @property- def connector(self) -> ServerSideConnector:- return self._connector-- async def start(self) -> None:- await self._connector.start()-- discovered = await self._connector.discover_agents()- logger.info(- "Connector %s discovered %d agents",- self._connector_id,- len(discovered),- )-- for agent in discovered:- await self._register_agent(agent)-- logger.info("Started connector core %s", self._connector_id)-- async def stop(self) -> None:- for handle in self._agents.values():- if handle.task and not handle.task.done():- handle.task.cancel()-- await self._connector.stop()- logger.info("Stopped connector core %s", self._connector_id)-- async def delete_agents(self) -> None:- # Removing the connector's agents is one unit of work for its row, so- # it binds that row's tenant here — as registration and each poll do.- for handle in self._agents.values():- try:- with tenant_scope(self._connector_tenant_id):- await self._protocol.delete_agent(agent_id=handle.agent_id)- except Exception:- logger.exception(- "Failed to delete agent %s during connector removal",- handle.agent_id,- )-- def get_agent_names(self) -> list[str]:- return [h.agent_name for h in self._agents.values()]-- # ── internal ─────────────────────────────────────────────────────────-- async def _register_agent(self, agent: DiscoveredAgent) -> None:- # Registering one agent is one unit of work for this connector's row,- # so it binds that row's tenant here rather than inheriting anything.- # `register_agent_with_token` additionally binds the registration- # token's own tenant for the write itself — the same tenant either- # way — see its docstring.- try:- with tenant_scope(self._connector_tenant_id):- result = await self._protocol.register_agent_with_token(- registration_token=self._registration_token,- name=agent.name,- description=agent.description,- connector_type=f"server-side:{self._connector_type}",- integration_profile=agent.integration_profile,- tools=agent.tools,- models=agent.models,- metadata={"server_connector_id": self._connector_id},- overwrite=True,- # A server-side connector agent is a service the- # deployment offers everyone, not one person's assistant;- # it is owned by whoever holds the registration token only- # in the bookkeeping sense. The default policy would- # make it answer to that account alone.- addressing_policy=None,- )- except Exception:- logger.exception(- "Failed to register agent %s from connector %s",- agent.name,- self._connector_id,- )- return-- handle = _AgentHandle(result.agent_id, agent.name)- handle.task = asyncio.create_task(self._poll_loop(handle))- self._agents[result.agent_id] = handle- logger.info(- "Registered agent %s (%s) from connector %s",- agent.name,- result.agent_id,- self._connector_id,- )-- def _reporter(self, handle: _AgentHandle) -> _ProtocolReporter:- return _ProtocolReporter(self._protocol, handle)-- async def _poll_loop(self, handle: _AgentHandle) -> None:- """One agent's long-poll loop.-- `no_tenant` around the loop and `tenant_scope` around each pass: the- loop itself is a task and owns no tenant, while one poll and the- events it returns are one unit of work for this connector's row. The- binding is taken and released per pass, so a loop that has been- running for days is in exactly the same state as one that just- started.- """- logger.info(- "Starting poll loop for agent %s (%s)",- handle.agent_name,- handle.agent_id,- )-- with no_tenant():- while True:- try:- with tenant_scope(self._connector_tenant_id):- await self._poll_once(handle)- except asyncio.CancelledError:- logger.info("Poll loop cancelled for agent %s", handle.agent_name)- return- except Exception:- logger.exception(- "Error in poll loop for agent %s (%s)",- handle.agent_name,- handle.agent_id,- )- await asyncio.sleep(5)-- async def _poll_once(self, handle: _AgentHandle) -> None:- events = await self._protocol.poll_events(- handle.agent_id, timeout=CONNECTOR_POLL_TIMEOUT_SECONDS- )- for event in events:- payload = event.payload-- if isinstance(payload, MessagePayload):- await self._handle_message(handle, event.room_id, payload)- elif isinstance(payload, CommandPayload):- await self._handle_command(handle, event.room_id, payload)-- async def _handle_message(- self,- handle: _AgentHandle,- room_id: str,- payload: MessagePayload,- ) -> None:- if not payload.addressed:- try:- await self._connector.handle_context(- handle.agent_name, room_id, payload- )- except Exception:- logger.exception(- "Connector failed to handle context for agent %s",- handle.agent_name,- )- return-- logger.debug(- "Handling message for agent %s in room %s", handle.agent_name, room_id- )-- reporter = self._reporter(handle)-- try:- response = await self._connector.handle_message(- handle.agent_name, room_id, payload, reporter- )- except Exception:- logger.exception(- "Connector failed to handle message for agent %s", handle.agent_name- )- response = "Sorry, I encountered an error processing your request."-- if response is not None:- try:- await self._protocol.send_message(handle.agent_id, room_id, response)- except Exception:- logger.exception(- "Failed to send response for agent %s in room %s",- handle.agent_name,- room_id,- )-- async def _handle_command(- self, handle: _AgentHandle, room_id: str, payload: CommandPayload- ) -> None:- await self._connector.handle_command(handle.agent_name, room_id, payload)diff --git a/core/switch_core/bridges/agent/server_connectors/lifecycle.py b/core/switch_core/bridges/agent/server_connectors/lifecycle.pydeleted file mode 100644index 2d3678dcd..000000000--- a/core/switch_core/bridges/agent/server_connectors/lifecycle.py+++ /dev/null@@ -1,503 +0,0 @@-"""Every server-side connector, run by the one switch-core process that holds it.--A server-side connector (OpenCode) discovers the agents on its server,-registers them, and long-polls each one's events, answering through the-platform. Run in two processes, every agent is polled twice and every turn-answered twice. So a connector runs in the one process that holds it-(`ownership.py`, kind `SERVER_CONNECTORS`), and is handed over when that-process stops or another should hold it. A connector registered or removed-through one process reaches the others as a `connector.changed` signal-(`signals.py`): the holder of a removed connector stops it, and a new one is-claimed by whichever process should hold it.-"""--from __future__ import annotations--import asyncio-import hashlib-import logging-import secrets-from typing import TYPE_CHECKING--from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker--from switch_core.bridges.agent.protocol.agent_core import AgentCore-from switch_core.bridges.agent.server_connectors.base import (- ServerSideConnector,- ServerSideConnectorConfig,-)-from switch_core.bridges.agent.server_connectors.core import ConnectorCore-from switch_core.db.models import ApiKey, ServerConnector-from switch_core.db.session_scope import tenant_session-from switch_core.db.stores.agent_store import AgentStore-from switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.db.stores.server_connector_store import ServerConnectorStore-from switch_core.db.tenant_lookup import all_tenant_ids, tenant_of_server_connector-from switch_core.keys import Keyring-from switch_core.outbound import OutboundPolicy-from switch_core.telemetry import TelemetryService, emit_safely-from switch_core.tenant_context import no_tenant, tenant_scope--if TYPE_CHECKING:- from switch_core.bridges.agent.server_connectors.signals import ConnectorSignals- from switch_core.ownership import Fence, Ownership--logger = logging.getLogger(__name__)--# The kind of owned work a server-side connector is (`ownership.py`), keyed by-# connector id.-SERVER_CONNECTORS = "connector"---def _connector_kind(connector_type: str) -> str:- """A connector type as the catalogue spells it.-- Registered types are a runtime registry rather than a fixed list, so only- the one Switch ships is named and anything else reports `other`.- """- return connector_type if connector_type == "opencode" else "other"---class ServerSideConnectorLifecycleService:- # Class-level default, as elsewhere: a test may build this without- # `__init__`, and `emit_safely` treats None as "report nothing".- _telemetry: TelemetryService | None = None-- def __init__(- self,- *,- connector_store: ServerConnectorStore,- api_key_store: ApiKeyStore,- protocol: AgentCore,- session_factory: async_sessionmaker[AsyncSession],- telemetry: TelemetryService | None = None,- keyring: Keyring,- outbound_policy: OutboundPolicy,- ownership: Ownership,- ) -> None:- self._connector_store = connector_store- self._agent_store = AgentStore()- self._owned = ownership.kind(- SERVER_CONNECTORS, start=self._take_over, stop=self._hand_over- )- self._signals: ConnectorSignals | None = None- # Why the last take-over of each connector failed to start it, for- # `register` to raise.- self._failed_take_overs: dict[str, Exception] = {}- # Connectors this process has taken over and is still starting. A- # start dials the connector's server and registers each agent it- # finds, so it runs in a task of its own: the ownership takes work- # over one key at a time, and a server slow to answer would hold up- # every other hand-over in this process meanwhile.- self._starting: dict[str, asyncio.Task[None]] = {}- self._api_key_store = api_key_store- self._protocol = protocol- self._session_factory = session_factory- self._telemetry = telemetry- self._keyring = keyring- self._outbound_policy = outbound_policy-- self._connector_registry: dict[str, type[ServerSideConnector]] = {}- self._config_registry: dict[str, type[ServerSideConnectorConfig]] = {}- self._cores: dict[str, ConnectorCore] = {}- # What this process means to be running: the connectors it holds.- # `_cores` alone cannot answer "is anything missing": a connector that- # failed to start never entered it, and the ownership logs each- # failure and steps over it.- self._expected: set[str] = set()-- def use_signals(self, signals: ConnectorSignals) -> None:- """Where a connector registered or removed here is announced, so every- other process applies it (`signals.py`)."""- self._signals = signals-- def _announce(self, connector_id: str) -> None:- if self._signals is not None:- self._signals.changed(connector_id)-- def register_connector_type(- self,- type_name: str,- connector_cls: type[ServerSideConnector],- config_cls: type[ServerSideConnectorConfig],- ) -> None:- self._connector_registry[type_name] = connector_cls- self._config_registry[type_name] = config_cls-- async def start_all(self) -> None:- # Every tenant's active connectors, one tenant at a time — same- # reasoning and same history as- # CollaborationBridgeLifecycleService.start_all, and worse here: this- # one is launched by a bare `create_task` in the lifespan, so when the- # unscoped read it replaces began returning nothing under the runtime- # role, no connector started and nothing said so at any log level.- #- # Nothing is bound around `start`: it reads the connector's own row- # and hands that row's tenant to the core, which binds it per unit of- # work rather than once for the poll loop's life.- connectors: list[ServerConnector] = []- for tenant_id in await all_tenant_ids(self._session_factory):- async with tenant_session(self._session_factory, tenant_id) as session:- # Filtered on the row's own tenant, not left to the policy: on an- # owner connection no policy narrows this read, and the fan-out- # would act on every tenant's rows once per tenant. See- # `db/tenant_lookup.py`, "a fan-out ... filters what it reads back".- connectors.extend(- record- for record in await self._connector_store.get_active(session)- if record.tenant_id == tenant_id- )-- logger.info("Wanting %d server-side connectors", len(connectors))- for record in connectors:- self._owned.want(record.id)- # The ones this process holds start now, each failure logged and- # stepped over; the rest run in the processes that hold them.- await self._owned.settle()-- async def register(- self,- *,- connector_type: str,- display_name: str,- connection_config: dict[str, object],- user_id: str,- ) -> ServerConnector:- connector_cls = self._connector_registry.get(connector_type)- config_cls = self._config_registry.get(connector_type)- if connector_cls is None or config_cls is None:- raise ValueError(f"Unknown connector type: {connector_type}")-- config_cls.model_validate(connection_config)- for url in connector_cls.outbound_urls(connection_config):- await self._outbound_policy.check_url(url)-- plaintext = secrets.token_urlsafe(32)- key_hash = hashlib.sha256(plaintext.encode()).hexdigest()- reg_key = ApiKey(- user_id=user_id,- key_hash=key_hash,- encrypted_key=self._keyring.encrypt(plaintext),- label=f"server-connector:{display_name}",- type="registration",- )-- # Reached only from `POST /connectors`, so the session inherits the- # tenant the auth dependency bound and both rows below land in the- # operator's own — which is the answer, since it is their connector.- # `start` then re-reads the row unscoped to learn that tenant back,- # rather than assuming this one is still bound by then.- async with self._session_factory() as session:- await self._api_key_store.create(session, reg_key)-- record = ServerConnector(- type=connector_type,- display_name=display_name,- connection_config=connection_config, # type: ignore[arg-type]- api_key_id=reg_key.id,- status="active",- )- await self._connector_store.create(session, record)- await session.commit()-- # Before `start`, not after: the rows above are durably committed and- # are the fact this event describes, while `start` is a post-commit- # side effect (decrypting the token, validating the connector's config,- # dialling out) that can raise without undoing the registration. A- # failure there still propagates to the caller unchanged.- emit_safely(- self._telemetry,- "server_connector_registered",- {"connector_kind": _connector_kind(connector_type)},- )-- # Started where it is held: here, or in the process that claims it- # once it hears of it. A start here is waited for, so its failure- # reaches the caller as it did when registering started it directly.- self._owned.want(record.id)- await self._owned.settle()- self._announce(record.id)- starting = self._starting.get(record.id)- if starting is not None:- await asyncio.shield(starting)- failed = self._failed_take_overs.pop(record.id, None)- if failed is not None:- raise failed-- logger.info(- "Registered server-side connector %s (%s): %s (owner: %s)",- record.id,- connector_type,- display_name,- user_id,- )- return record-- async def start(self, connector_id: str) -> None:- # The exemption answers which tenant this connector is in- # (`db/tenant_lookup.py`); the two rows are then read scoped to it.- # Reached both from boot with nothing bound and from an HTTP request- # whose tenant is the caller's, not necessarily the connector's, so- # the tenant is derived here rather than inherited either way. The- # registration key is read in the same scoped session because- # `server_connectors` carries a composite foreign key on- # `(tenant_id, api_key_id)` — it cannot be another tenant's row.- tenant_id = await tenant_of_server_connector(- self._session_factory, connector_id- )- if tenant_id is None:- raise ValueError(f"Connector not found: {connector_id}")- async with tenant_session(self._session_factory, tenant_id) as session:- record = await self._connector_store.get(session, connector_id)- if record is None:- raise ValueError(f"Connector not found: {connector_id}")- reg_key = await self._api_key_store.get(session, record.api_key_id)- if reg_key is None:- raise ValueError(f"Registration key not found: {record.api_key_id}")-- connector_cls = self._connector_registry.get(record.type)- config_cls = self._config_registry.get(record.type)- if connector_cls is None or config_cls is None:- raise ValueError(f"Unknown connector type: {record.type}")-- registration_token = self._keyring.decrypt(reg_key.encrypted_key)-- typed_config = config_cls.model_validate(record.connection_config or {})- # Again at every start: what the host resolves to can have changed- # since the connector was registered.- for url in connector_cls.outbound_urls(record.connection_config or {}):- await self._outbound_policy.check_url(url)- connector = connector_cls( # type: ignore[call-arg]- config=typed_config, outbound_policy=self._outbound_policy- )-- core = ConnectorCore(- connector_id=connector_id,- connector_tenant_id=record.tenant_id,- connector_type=record.type,- connector=connector,- registration_token=registration_token,- protocol=self._protocol,- )- try:- await core.start()- except BaseException:- # Agents it registered before failing, or before being cancelled- # by a hand-over, are already being polled.- await core.stop()- raise- self._cores[connector_id] = core-- async def stop(self, connector_id: str) -> None:- self._expected.discard(connector_id)- core = self._cores.pop(connector_id, None)- if core is None:- return- await core.stop()-- def expected_count(self) -> int:- """Connectors this process means to be running."""- return len(self._expected)-- def running_count(self) -> int:- """Of those, how many actually are.-- Short of `expected_count` is an agent host that is not there, which is- otherwise only a line in the boot log.- """- return sum(1 for connector_id in self._expected if connector_id in self._cores)-- async def stop_all(self) -> None:- starting = list(self._starting.values())- self._starting.clear()- for task in starting:- task.cancel()- await asyncio.gather(*starting, return_exceptions=True)- logger.info("Stopping all %d server-side connectors", len(self._cores))- for connector_id in list(self._cores):- await self.stop(connector_id)-- async def remove(self, connector_id: str) -> None:- """Delete a connector: its agents, its running core, and its row, and- tell the other processes, so the one holding it stops it.-- Scoped to the caller, and checked before anything is torn down. The- session inherits the tenant the request bound (`gateway/auth.py`), so- a connector belonging to another tenant is simply not there — but- `_cores` is a process-wide registry with every tenant's connectors in- it, so tearing down first and deleting second let a caller from the- wrong tenant stop another tenant's connector and delete its agents,- then match zero rows and report success. The read below is what makes- the tenant check happen before the damage rather than after it.-- `ServerConnectorStore.delete` raises when it matches nothing, so the- window between the two — the row deleted underneath us — surfaces as- an error rather than as a second false success.- """- async with self._session_factory() as session:- existing = await self._connector_store.get(session, connector_id)- kind = existing.type if existing is not None else "other"- if existing is None:- raise ValueError(f"Connector not found: {connector_id}")-- core = self._cores.get(connector_id)- if core is not None:- await core.delete_agents()- else:- # Held by another process: its agents are found by their rows.- await self._delete_agents(connector_id, existing.tenant_id)-- # Held here or not, let go of it: no process is to take it over.- await self._owned.drop(connector_id)- await self.stop(connector_id)-- async with self._session_factory() as session:- await self._connector_store.delete(session, connector_id)- await session.commit()- self._announce(connector_id)-- emit_safely(- self._telemetry,- "server_connector_removed",- {"connector_kind": _connector_kind(kind)},- )- logger.info("Removed server-side connector %s", connector_id)-- def get_registered_types(self) -> list[str]:- return list(self._connector_registry.keys())-- def get_config_schema(self, type_name: str) -> dict[str, object]:- config_cls = self._config_registry.get(type_name)- if config_cls is None:- raise ValueError(f"Unknown connector type: {type_name}")- return config_cls.model_json_schema()-- def get_connector_ids(self) -> list[str]:- return list(self._cores.keys())-- async def get_agent_names(self, connector_id: str) -> list[str]:- """The names of the agents the connector registered, read from their- rows in the bound tenant: the same answer from every process, whichever- holds the connector."""- async with self._session_factory() as session:- agents = await self._agent_store.get_by_server_connector(- session, connector_id- )- return [agent.name for agent in agents]-- async def _delete_agents(self, connector_id: str, tenant_id: str) -> None:- with tenant_scope(tenant_id):- async with self._session_factory() as session:- agents = await self._agent_store.get_by_server_connector(- session, connector_id- )- for agent in agents:- try:- await self._protocol.delete_agent(agent_id=agent.id)- except Exception:- logger.exception(- "Failed to delete agent %s during connector removal",- agent.id,- )-- # ── Ownership ────────────────────────────────────────────────────────────-- async def _take_over(self, connector_id: str, fence: Fence) -> None:- """This process now holds the connector: start it here, in the- background (`_starting`)."""- logger.info("Taking over server-side connector %s", connector_id)- self._failed_take_overs.pop(connector_id, None)- self._expected.add(connector_id)- self._starting[connector_id] = asyncio.create_task(- self._start_held(connector_id)- )-- async def _start_held(self, connector_id: str) -> None:- try:- # Whoever's request led to the take-over, the connector acts as- # its own row's tenant (`start`).- with no_tenant():- await self.start(connector_id)- except asyncio.CancelledError:- raise- except Exception as exc:- self._failed_take_overs[connector_id] = exc- logger.exception("Failed to start connector %s", connector_id)- finally:- if self._starting.get(connector_id) is asyncio.current_task():- del self._starting[connector_id]-- async def _hand_over(self, connector_id: str) -> None:- """This process no longer holds the connector: stop it here, starting- or started."""- logger.info("Handing server-side connector %s over", connector_id)- starting = self._starting.pop(connector_id, None)- if starting is not None and not starting.done():- starting.cancel()- await asyncio.gather(starting, return_exceptions=True)- await self.stop(connector_id)-- def holds(self, connector_id: str) -> bool:- """Whether this process holds the connector and runs it."""- return self._owned.fence(connector_id) is not None-- # ── Changes made in other processes ──────────────────────────────────────-- async def reconcile_connector(self, connector_id: str) -> None:- """Bring this process in line with one connector's row, after another- process registered or removed it."""- tenant_id = await tenant_of_server_connector(- self._session_factory, connector_id- )- record: ServerConnector | None = None- if tenant_id is not None:- async with tenant_session(self._session_factory, tenant_id) as session:- record = await self._connector_store.get(session, connector_id)- await self._reconcile_row(connector_id, record)-- async def reconcile_all(self) -> None:- """`reconcile_connector` for every connector stored or wanted here,- reading the rows one tenant at a time."""- rows: dict[str, ServerConnector] = {}- for tenant_id in await all_tenant_ids(self._session_factory):- async with tenant_session(self._session_factory, tenant_id) as session:- rows.update(- (record.id, record)- for record in await self._connector_store.get_active(session)- if record.tenant_id == tenant_id- )- for connector_id in sorted(set(rows) | self._owned.wanted() | set(self._cores)):- try:- await self._reconcile_row(connector_id, rows.get(connector_id))- except Exception:- logger.warning(- "Could not bring server-side connector %s in line with its "- "row; retrying at the next re-check",- connector_id,- exc_info=True,- )-- async def _reconcile_row(- self, connector_id: str, record: ServerConnector | None- ) -> None:- """Wanted where it is new here, so the process that should hold it- claims it; stopped and let go of where it is gone or no longer- active."""- if self._owned.stopping:- return- if record is None or record.status != "active":- if self._owned.wants(connector_id) or connector_id in self._cores:- logger.info(- "Server-side connector %s was removed elsewhere; stopping it",- connector_id,- )- await self._owned.drop(connector_id)- await self.stop(connector_id)- return- if not self._owned.wants(connector_id):- logger.info(- "Server-side connector %s was added elsewhere; wanting it",- connector_id,- )- self._owned.want(connector_id)- await self._owned.settle()diff --git a/core/switch_core/bridges/agent/server_connectors/opencode/__init__.py b/core/switch_core/bridges/agent/server_connectors/opencode/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/core/switch_core/bridges/agent/server_connectors/opencode/client.py b/core/switch_core/bridges/agent/server_connectors/opencode/client.pydeleted file mode 100644index 208730e5f..000000000--- a/core/switch_core/bridges/agent/server_connectors/opencode/client.py+++ /dev/null@@ -1,138 +0,0 @@-from __future__ import annotations--import json-import logging-from collections.abc import AsyncIterator-from contextlib import asynccontextmanager-from typing import Any--import httpx--from switch_core.outbound import OutboundPolicy, guarded_async_client--logger = logging.getLogger(__name__)---class OpenCodeClient:- """HTTP client for the OpenCode server REST API."""-- def __init__(- self,- server_url: str,- username: str,- password: str,- outbound_policy: OutboundPolicy,- ) -> None:- self._outbound_policy = outbound_policy- self._http = guarded_async_client(- outbound_policy,- base_url=server_url.rstrip("/"),- auth=httpx.BasicAuth(username, password),- timeout=300,- )-- async def list_agents(self) -> list[dict[str, Any]]:- """List available agents from the OpenCode server."""- resp = await self._http.get("/agent")- resp.raise_for_status()- return resp.json() # type: ignore[no-any-return]-- async def create_session(self) -> str:- """Create a new session. Returns the session ID."""- resp = await self._http.post("/session", json={})- resp.raise_for_status()- data: dict[str, Any] = resp.json()- return str(data["id"])-- async def send_message(self, session_id: str, content: str) -> str:- """Send a message to a session and wait for the response.-- Returns the text content of the response.- """- resp = await self._http.post(- f"/session/{session_id}/message",- json={"parts": [{"type": "text", "text": content}]},- )- resp.raise_for_status()- data = resp.json()- return _extract_response_text(data)-- async def add_context(self, session_id: str, content: str) -> None:- """Inject a message into the session without triggering a response."""- resp = await self._http.post(- f"/session/{session_id}/message",- json={- "parts": [{"type": "text", "text": content}],- "noReply": True,- },- )- resp.raise_for_status()-- async def prompt_async(- self, session_id: str, content: str, agent_name: str- ) -> None:- """Send a message without waiting for the response."""- resp = await self._http.post(- f"/session/{session_id}/prompt_async",- json={"parts": [{"type": "text", "text": content}], "agent": agent_name},- )- resp.raise_for_status()-- async def respond_permission(- self, session_id: str, permission_id: str, response: str- ) -> None:- """Respond to a permission request raised by the OpenCode server.-- `response` is one of "once", "always", or "reject". Without a reply- the server pauses the session indefinitely waiting for approval.- """- resp = await self._http.post(- f"/session/{session_id}/permissions/{permission_id}",- json={"response": response},- )- resp.raise_for_status()-- @asynccontextmanager- async def subscribe_events(self) -> AsyncIterator[AsyncIterator[dict[str, Any]]]:- """Subscribe to the SSE event stream. Yields parsed events."""- stream_client = guarded_async_client(- self._outbound_policy,- base_url=str(self._http._base_url),- auth=self._http._auth,- timeout=None,- )- try:- async with stream_client.stream(- "GET", "/event", headers={"Accept": "text/event-stream"}- ) as resp:- resp.raise_for_status()- yield _parse_sse(resp)- finally:- await stream_client.aclose()-- async def close(self) -> None:- await self._http.aclose()---def _extract_response_text(data: dict[str, Any]) -> str:- """Extract text content from an OpenCode message response."""- parts = data.get("parts", [])- texts = []- for part in parts:- if isinstance(part, dict) and part.get("type") == "text":- texts.append(part.get("text", ""))- return "\n".join(texts) if texts else ""---async def _parse_sse(resp: httpx.Response) -> AsyncIterator[dict[str, Any]]:- """Parse an SSE stream into typed event dicts."""- data_buf = ""- async for line in resp.aiter_lines():- if line.startswith("data:"):- data_buf += line[5:].strip()- elif line == "" and data_buf:- try:- yield json.loads(data_buf)- except json.JSONDecodeError:- logger.debug("Skipping non-JSON SSE data: %s", data_buf[:100])- data_buf = ""diff --git a/core/switch_core/bridges/agent/server_connectors/opencode/connector.py b/core/switch_core/bridges/agent/server_connectors/opencode/connector.pydeleted file mode 100644index e6e62a676..000000000--- a/core/switch_core/bridges/agent/server_connectors/opencode/connector.py+++ /dev/null@@ -1,312 +0,0 @@-from __future__ import annotations--import logging-import re-import time-import uuid--from pydantic import Field--from switch_core.bridges.agent.protocol.types import (- CommandCapabilities,- CommandPayload,- IntegrationProfile,- MessagePayload,- ToolCallReport,-)-from switch_core.bridges.agent.server_connectors.base import (- ConnectorReporter,- DiscoveredAgent,- ServerSideConnector,- ServerSideConnectorConfig,-)-from switch_core.bridges.agent.server_connectors.opencode.client import OpenCodeClient-from switch_core.outbound import OutboundPolicy--logger = logging.getLogger(__name__)--_SANITIZE_RE = re.compile(r"[^a-z0-9._-]")--# OpenCode pauses a session until a permission request is answered. This-# connector reports tool calls post-hoc and runs no pre-invocation mediation-# (see _INTEGRATION_PROFILE), so permission requests are auto-approved to keep-# the session from blocking. "always" so a given tool/pattern is not re-asked.-_PERMISSION_RESPONSE = "always"--_INTEGRATION_PROFILE = IntegrationProfile(- connection_model="always_on",- message_exchange=True,- pre_invocation_mediation=[],- post_invocation_mediation=[],- event_reporting=["tool_calls"],- # An always-on server-side session can always be reset from the room (the- # connector receives the queued command event and starts a fresh session).- # Compact / interrupt aren't modelled for this connector.- command_capabilities=CommandCapabilities(- reset="always",- compact="unsupported",- interrupt="unsupported",- ),-)---class OpenCodeConnectionConfig(ServerSideConnectorConfig):- server_url: str = Field(title="Server URL")- username: str- password: str = Field(json_schema_extra={"format": "password"})- agent_name_prefix: str = Field(- default="",- title="Agent Name Prefix",- description="Optional prefix for discovered agent names",- )- agent_allowlist: str = Field(- default="",- title="Agent Allowlist",- description="Comma-separated agent names to include (empty = all)",- )- agent_blocklist: str = Field(- default="",- title="Agent Blocklist",- description="Comma-separated agent names to exclude",- )---class OpenCodeConnector(ServerSideConnector):- @classmethod- def outbound_urls(cls, connection_config: dict[str, object]) -> list[str]:- return [str(connection_config["server_url"])]-- def __init__(- self, config: OpenCodeConnectionConfig, outbound_policy: OutboundPolicy- ) -> None:- self._config = config- self._outbound_policy = outbound_policy- self._client: OpenCodeClient | None = None- self._sessions: dict[tuple[str, str], str] = {}- self._agents_names_map: dict[str, str] = {}-- async def start(self) -> None:- self._client = OpenCodeClient(- server_url=self._config.server_url,- username=self._config.username,- password=self._config.password,- outbound_policy=self._outbound_policy,- )-- async def stop(self) -> None:- if self._client is not None:- await self._client.close()- self._client = None- self._sessions.clear()-- @property- def client(self) -> OpenCodeClient:- if self._client is None:- raise RuntimeError("Connector not started — call start() first")- return self._client-- async def discover_agents(self) -> list[DiscoveredAgent]:- raw_agents = await self.client.list_agents()- allowlist = {- n.strip() for n in self._config.agent_allowlist.split(",") if n.strip()- }- blocklist = {- n.strip() for n in self._config.agent_blocklist.split(",") if n.strip()- }-- discovered = []- for agent in raw_agents:- name = agent.get("name", "")- if allowlist and name not in allowlist:- continue- if name in blocklist:- continue- raw_name = self._config.agent_name_prefix + name- sanitized = _SANITIZE_RE.sub("-", raw_name.lower())- if not sanitized or not sanitized[0].isalnum():- sanitized = "agent-" + sanitized- self._agents_names_map[name] = sanitized- discovered.append(- DiscoveredAgent(- name=sanitized,- description=agent.get("description", f"OpenCode agent: {name}"),- integration_profile=_INTEGRATION_PROFILE,- )- )- return discovered-- async def _ensure_session(self, agent_name: str, room_id: str) -> str:- session_key = (agent_name, room_id)- session_id = self._sessions.get(session_key)- if session_id is None:- session_id = await self.client.create_session()- self._sessions[session_key] = session_id- logger.debug(- "Created OpenCode session %s for agent=%s room=%s",- session_id,- agent_name,- room_id,- )- return session_id-- async def handle_message(- self,- agent_name: str,- room_id: str,- message: MessagePayload,- reporter: ConnectorReporter,- ) -> str | None:- session_id = await self._ensure_session(agent_name, room_id)-- oc_agent_name = self._agents_names_map[agent_name]- await reporter.set_typing(room_id, True)- try:- await self.client.prompt_async(session_id, message.body, oc_agent_name)- return await self._stream_response(session_id, room_id, reporter)- except Exception:- logger.warning(- "OpenCode session %s failed, creating new session", session_id- )- session_id = await self.client.create_session()- self._sessions[(agent_name, room_id)] = session_id- await self.client.prompt_async(session_id, message.body, oc_agent_name)- return await self._stream_response(session_id, room_id, reporter)- finally:- await reporter.set_typing(room_id, False)-- async def _stream_response(- self, session_id: str, room_id: str, reporter: ConnectorReporter- ) -> str | None:- """Subscribe to SSE, collect response text and tool calls, report events."""- reported_tool_ids: set[str] = set()- notified_tool_ids: set[str] = set()- sent_text_ids: set[str] = set()- responded_permission_ids: set[str] = set()-- async with self.client.subscribe_events() as events:- async for event in events:- logger.debug("Event received from opencode sse: %s", event)- event_type = event.get("type", "")-- if event_type == "session.idle":- props = event.get("properties", {})- if props.get("sessionID") == session_id:- break-- if event_type == "permission.updated":- props = event.get("properties") or event.get("data", {})- if props.get("sessionID") != session_id:- continue- permission_id = props.get("id", "")- if not permission_id or permission_id in responded_permission_ids:- continue- responded_permission_ids.add(permission_id)- logger.info(- "Auto-approving OpenCode permission %s (%s) for session %s",- permission_id,- props.get("type") or props.get("title", ""),- session_id,- )- try:- await self.client.respond_permission(- session_id, permission_id, _PERMISSION_RESPONSE- )- except Exception:- logger.error(- "Failed to respond to OpenCode permission %s; session "- "may block waiting for approval",- permission_id,- )- continue-- if event_type not in (- "message.part.updated",- "message.part.updated.1",- ):- continue-- props = event.get("properties") or event.get("data", {})- if props.get("sessionID") != session_id:- continue-- part = props.get("part", {})- part_type = part.get("type")-- if part_type == "text" and not part.get("synthetic"):- part_id = part.get("id", "")- text = part.get("text", "")- is_complete = part.get("time", {}).get("end") is not None- if is_complete and text and part_id not in sent_text_ids:- sent_text_ids.add(part_id)- await reporter.send_message(room_id, text)-- elif part_type == "tool":- state = part.get("state", {})- status = state.get("status")- tool_name = part.get("tool", "")- part_id = part.get("id", "")-- if status == "running" and part_id not in notified_tool_ids:- notified_tool_ids.add(part_id)- args = state.get("input", {})- args_str = ", ".join(f"{k}: {v}" for k, v in args.items())- detail = (- f"Running tool: `{tool_name}({args_str})`"- if args_str- else f"Running tool: `{tool_name}`"- )- try:- await reporter.send_status(room_id, detail)- except Exception:- pass-- elif (- status in ("completed", "error")- and part_id not in reported_tool_ids- ):- reported_tool_ids.add(part_id)- time_info = state.get("time", {})- duration_ms = None- if time_info.get("start") and time_info.get("end"):- duration_ms = int(- (time_info["end"] - time_info["start"]) * 1000- )- result = (- state.get("output", "")- if status == "completed"- else state.get("error", "")- )- report = ToolCallReport(- tool_name=tool_name,- arguments=state.get("input", {}),- result=result,- request_id=str(uuid.uuid4()),- timestamp=time.strftime(- "%Y-%m-%dT%H:%M:%SZ", time.gmtime()- ),- duration_ms=duration_ms,- )- try:- await reporter.report_events(room_id, [report])- except Exception:- logger.warning(- "Failed to report tool call event (proceeding)"- )-- return None-- async def handle_context(- self, agent_name: str, room_id: str, message: MessagePayload- ) -> None:- session_key = (agent_name, room_id)- session_id = self._sessions.get(session_key)- if session_id is None:- return- context = f"[{message.sender_name}]: {message.body}"- await self.client.add_context(session_id, context)-- async def handle_command(- self, agent_name: str, room_id: str, command: CommandPayload- ) -> None:- if command.command == "reset":- self._sessions.pop((agent_name, room_id), None)diff --git a/core/switch_core/bridges/agent/server_connectors/signals.py b/core/switch_core/bridges/agent/server_connectors/signals.pydeleted file mode 100644index bcc709e5d..000000000--- a/core/switch_core/bridges/agent/server_connectors/signals.py+++ /dev/null@@ -1,48 +0,0 @@-"""Server-side connectors registered or removed in one process, reaching every other.--A server-side connector runs in the one switch-core process that holds it-(`lifecycle.py`). Registering or removing one is served by whichever process-the request reached, and changed only that process: a connector removed there-went on polling its agents in the holder, and one registered there was run-nowhere else, so another process that should hold it never claimed it.--So a registration or a removal, once committed, announces `connector.changed`-naming the connector. Every other process re-reads the connector's row-(`ServerSideConnectorLifecycleService.reconcile_connector`): wanting a new one,-so the process that should hold it claims it, or stopping and letting go of-one that is gone. A re-read that fails is kept and tried again, and every-connector is re-read when the signal connection comes back and on each-periodic re-check.-"""--from __future__ import annotations--from typing import TYPE_CHECKING, Any--if TYPE_CHECKING:- from switch_core.bridges.agent.server_connectors.lifecycle import (- ServerSideConnectorLifecycleService,- )- from switch_core.signals import SignalBus--CONNECTOR_CHANGED_SIGNAL = "connector.changed"---class ConnectorSignals:- def __init__(- self, *, lifecycle: ServerSideConnectorLifecycleService, bus: SignalBus- ) -> None:- self._bus = bus- self._owed = bus.pending_work("connectors", lifecycle.reconcile_connector)- bus.handle(CONNECTOR_CHANGED_SIGNAL, self._on_changed)- bus.on_resync(lifecycle.reconcile_all)- bus.on_recheck(lifecycle.reconcile_all)- lifecycle.use_signals(self)-- def changed(self, connector_id: str) -> None:- """The connector's row changed and has committed: every other process- re-reads it. This one has already applied the change itself."""- self._bus.publish(CONNECTOR_CHANGED_SIGNAL, connector_id=connector_id)-- def _on_changed(self, signal: dict[str, Any]) -> None:- self._owed.add(signal["connector_id"])diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex 6e3283f63..4799b02ef 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -219,7 +219,7 @@ class SwitchConfig(BaseSettings):jwt_secret_key: str | None = None# Private hosts Switch may reach at a URL a tenant or agent supplied (a- # Mattermost server, an OpenCode server, an agent icon): comma-separated+ # Mattermost server, an agent icon): comma-separated# hostnames and CIDRs. Anything else that is not a public address is# refused. Link-local and metadata addresses are refused even when listed.# See `outbound.py`.@@ -370,9 +370,9 @@ class SwitchConfig(BaseSettings):## It exists because workspace creation is an amplification vector rather# than just a row: `all_tenant_ids()` drives a fan-out per tenant at boot- # and a sweep every few seconds, across clients, collaboration bridges,- # server connectors and rooms. Unbounded self-service creation therefore- # buys steady-state work in the deployment, not storage.+ # and a sweep every few seconds, across clients, collaboration bridges and+ # rooms. Unbounded self-service creation therefore buys steady-state work+ # in the deployment, not storage.## Counts `owner` memberships only, so being invited into someone else's# workspace never spends an allowance the invitee cannot get back. Deploymentdiff --git a/core/switch_core/db/key_rotation.py b/core/switch_core/db/key_rotation.pyindex 1dd0b5994..8915f2b17 100644--- a/core/switch_core/db/key_rotation.py+++ b/core/switch_core/db/key_rotation.py@@ -54,6 +54,8 @@ logger = logging.getLogger(__name__)_ENCRYPTED_JSON_COLUMNS: tuple[tuple[type[Any], str], ...] = ((CollaborationBridge, "connection_config"),+ # Unread since server-side connectors went, but still stored until the+ # table is dropped, so still kept under the current key.(ServerConnector, "connection_config"),)_ENCRYPTED_TEXT_COLUMNS: tuple[tuple[type[Any], str], ...] = (diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 74928165a..d8a0e2c8f 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -1753,6 +1753,10 @@ class MessagingEventReceipt(TenantScoped, Base):# ── Server-Side Connectors ────────────────────────────────────────────────────+# Nothing reads or writes this table any more. It is dropped a release after+# the code that used it went, so a release still running that code during a+# rolling deploy finds it there (`migrations/script.py.mako`). Until then the+# model keeps `create_all` in step with the migrated schema.class ServerConnector(TenantScoped, Base):__tablename__ = "server_connectors"__table_args__ = (diff --git a/core/switch_core/db/session_scope.py b/core/switch_core/db/session_scope.pyindex d23a04025..56f4a1d49 100644--- a/core/switch_core/db/session_scope.py+++ b/core/switch_core/db/session_scope.py@@ -6,10 +6,10 @@ Everything in a request already gets a tenant for free: `gateway/auth.py` andthat session opens from then on, at any depth, with no call site to remember.`tenant_session` is that, for the 157 places that open a session from the-factory with no request behind them — the delivery loop, the collaboration and-server-connector lifecycle services, the startup seeding in `main.py`, the-periodic sweeps. It binds a tenant for the life of one session, and the tenant-is derived from the row the work is acting on: a message delivery binds the+factory with no request behind them — the delivery loop, the collaboration+lifecycle service, the startup seeding in `main.py`, the periodic sweeps. It+binds a tenant for the life of one session, and the tenant is derived from+the row the work is acting on: a message delivery binds theroom's, an inbound bridge event binds the room's or the bridge's, one row outof a sweep binds its own. Never once per long-lived object, and never once pertask — see `tenant_context.no_tenant` for the four ways that went wrong.diff --git a/core/switch_core/db/stores/agent_session_store.py b/core/switch_core/db/stores/agent_session_store.pyindex 5b9b7c4e9..e7d4824e3 100644--- a/core/switch_core/db/stores/agent_session_store.py+++ b/core/switch_core/db/stores/agent_session_store.py@@ -37,13 +37,14 @@ class AgentSessionStore:a schema change."""- # always_on agents (server-side connectors) refresh their heartbeat as a- # side effect of re-entering poll_events, so the gap between beats is- # bounded below by the poll long-poll timeout — 30s for the server- # connector (see CONNECTOR_POLL_TIMEOUT_SECONDS) — and grows further while- # the agent is busy handling an event. 90s gives that 30s cadence ~3x- # headroom so always_on agents stay live across idle long-polls and slow- # event handling, while a genuinely crashed agent still drops within 90s.+ # always_on agents refresh their heartbeat as a side effect of re-entering+ # poll_events (`GET /agents/{id}/events`), so the gap between beats is+ # bounded below by the long-poll timeout the agent asks for (10s unless it+ # says otherwise) and grows further while it is busy handling an event.+ # 90s leaves room for long-polls of up to about 30s plus slow event+ # handling, while a genuinely crashed agent still drops within 90s. A+ # client that asks for a timeout near or past the TTL reads as+ # disconnected between its polls.ALWAYS_ON_TTL = timedelta(seconds=90)# session_addressable agents on the old Claude Code plugin renew their heartbeatdiff --git a/core/switch_core/db/stores/agent_store.py b/core/switch_core/db/stores/agent_store.pyindex aeab82932..d9b647faa 100644--- a/core/switch_core/db/stores/agent_store.py+++ b/core/switch_core/db/stores/agent_store.py@@ -110,18 +110,6 @@ class AgentStore:result = await session.execute(select(Agent))return list(result.scalars().all())- async def get_by_server_connector(- self, session: AsyncSession, connector_id: str- ) -> list[Agent]:- """The agents a server-side connector registered, in the bound tenant:- each carries the connector's id in its metadata."""- result = await session.execute(- select(Agent)- .where(Agent.metadata_["server_connector_id"].astext == connector_id)- .order_by(Agent.name)- )- return list(result.scalars().all())-async def get_by_owner(self, session: AsyncSession, owner_id: str) -> list[Agent]:"""Every agent `owner_id` owns in the bound tenant.diff --git a/core/switch_core/db/stores/server_connector_store.py b/core/switch_core/db/stores/server_connector_store.pydeleted file mode 100644index 86ac7321a..000000000--- a/core/switch_core/db/stores/server_connector_store.py+++ /dev/null@@ -1,52 +0,0 @@-from sqlalchemy import select-from sqlalchemy.ext.asyncio import AsyncSession--from switch_core.db.models import ServerConnector---class ServerConnectorStore:- async def create(- self, session: AsyncSession, connector: ServerConnector- ) -> ServerConnector:- session.add(connector)- await session.flush()- return connector-- async def get(- self, session: AsyncSession, connector_id: str- ) -> ServerConnector | None:- return await session.get(ServerConnector, connector_id)-- async def get_all(self, session: AsyncSession) -> list[ServerConnector]:- result = await session.execute(select(ServerConnector))- return list(result.scalars().all())-- async def get_active(self, session: AsyncSession) -> list[ServerConnector]:- result = await session.execute(- select(ServerConnector).where(ServerConnector.status == "active")- )- return list(result.scalars().all())-- async def update_status(- self, session: AsyncSession, connector_id: str, status: str- ) -> None:- connector = await session.get(ServerConnector, connector_id)- if connector is None:- raise ValueError(f"Connector not found: {connector_id}")- connector.status = status- await session.flush()-- async def delete(self, session: AsyncSession, connector_id: str) -> None:- """Delete the connector, raising when this session cannot see it.-- Matching `update_status` above rather than the silent no-op this used- to be. Row-level security makes "no such connector" and "not this- tenant's connector" the same empty lookup, so returning quietly is not- a harmless idempotent delete — it is the shape a cross-tenant delete- takes, and the caller went on to log a removal that had not happened.- """- connector = await session.get(ServerConnector, connector_id)- if connector is None:- raise ValueError(f"Connector not found: {connector_id}")- await session.delete(connector)- await session.flush()diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.pyindex 899c26b69..ec332fc6a 100644--- a/core/switch_core/db/tenant_lookup.py+++ b/core/switch_core/db/tenant_lookup.py@@ -322,7 +322,10 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (name="tenant_of_server_connector",arguments=("connector_id",),query="SELECT tenant_id FROM server_connectors WHERE id = p_connector_id",- purpose="Same as the bridge, for a server-side connector.",+ purpose=(+ "Same as the bridge, for a server-side connector. Nothing calls it "+ "any more; it goes with `server_connectors`, a release later."+ ),),TenantLookup(name="tenant_of_invitation",diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex 282328c09..19a5fb317 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -8,9 +8,6 @@ from starlette.middleware.sessions import SessionMiddlewarefrom switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer-from switch_core.bridges.agent.server_connectors.lifecycle import (- ServerSideConnectorLifecycleService,-)from switch_core.bridges.collaboration.install_service import (MessagingInstallService,)@@ -33,7 +30,6 @@ from switch_core.db.stores.invitation_store import InvitationStorefrom switch_core.db.stores.join_domain_store import JoinDomainStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStore-from switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStore@@ -47,7 +43,6 @@ from switch_core.gateway.chats import router as chats_routerfrom switch_core.gateway.collaborations import router as collaborations_routerfrom switch_core.gateway.connection_catalog import router as connection_catalog_routerfrom switch_core.gateway.connector_apps import router as connector_apps_router-from switch_core.gateway.connectors import router as connectors_routerfrom switch_core.gateway.dependencies import init_dependenciesfrom switch_core.gateway.documents import router as documents_routerfrom switch_core.gateway.ecosystem import router as ecosystem_router@@ -96,8 +91,6 @@ def create_gateway_app(bridge_store: CollaborationBridgeStore,client_lifecycle: ClientLifecycleService,collab_lifecycle: CollaborationBridgeLifecycleService,- connector_lifecycle: ServerSideConnectorLifecycleService,- connector_store: ServerConnectorStore,event_buffer: EventBuffer,session_factory: async_sessionmaker[AsyncSession],user_store: UserStore,@@ -125,8 +118,6 @@ def create_gateway_app(bridge_store=bridge_store,client_lifecycle=client_lifecycle,collab_lifecycle=collab_lifecycle,- connector_lifecycle=connector_lifecycle,- connector_store=connector_store,event_buffer=event_buffer,session_factory=session_factory,user_store=user_store,@@ -215,7 +206,6 @@ def create_gateway_app(app.include_router(teams_placements_router, prefix="/collaborations", tags=["collaborations"])- app.include_router(connectors_router, prefix="/connectors", tags=["connectors"])app.include_router(api_keys_router, prefix="/api-keys", tags=["api-keys"])app.include_router(references_router, tags=["references"])app.include_router(room_links_router, tags=["linked-rooms"])diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex 9a559598c..eb7203135 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -329,8 +329,8 @@ async def create_bridge(CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)],# Admin-only: a bridge is an unowned, workspace-wide integration holding- # platform secrets, so there is no owner to scope to (unlike connectors,- # whose authz is owner-or-admin) — registering one is an admin action.+ # platform secrets, so there is no owner to scope to — registering one is+ # an admin action.user: Annotated[User, Depends(require_tenant_admin)],) -> BridgeDetail:# A shared bridge runs on this deployment's own app, which is in everydiff --git a/core/switch_core/gateway/connectors.py b/core/switch_core/gateway/connectors.pydeleted file mode 100644index 694597158..000000000--- a/core/switch_core/gateway/connectors.py+++ /dev/null@@ -1,155 +0,0 @@-from __future__ import annotations--import logging-from typing import Annotated--from fastapi import APIRouter, Depends, HTTPException-from sqlalchemy.ext.asyncio import AsyncSession--from switch_core.bridges.agent.server_connectors.lifecycle import (- ServerSideConnectorLifecycleService,-)-from switch_core.db.models import User-from switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.db.stores.server_connector_store import ServerConnectorStore-from switch_core.gateway.auth import get_current_user, get_tenant_is_admin-from switch_core.gateway.dependencies import (- get_api_key_store,- get_connector_lifecycle,- get_connector_store,- get_session,-)-from switch_core.gateway.schemas import (- ConnectorDetail,- ConnectorTypeInfo,- CreateConnectorRequest,-)--logger = logging.getLogger(__name__)--router = APIRouter()--[email protected]("/types")-async def list_connector_types(- connector_lifecycle: Annotated[- ServerSideConnectorLifecycleService, Depends(get_connector_lifecycle)- ],- _user: Annotated[User, Depends(get_current_user)],-) -> list[ConnectorTypeInfo]:- return [- ConnectorTypeInfo(- key=t,- config_schema=connector_lifecycle.get_config_schema(t),- )- for t in connector_lifecycle.get_registered_types()- ]---async def create_connector(- req: CreateConnectorRequest,- connector_lifecycle: Annotated[- ServerSideConnectorLifecycleService, Depends(get_connector_lifecycle)- ],- user: Annotated[User, Depends(get_current_user)],-) -> ConnectorDetail:- try:- record = await connector_lifecycle.register(- connector_type=req.type,- display_name=req.display_name,- connection_config=dict(req.connection_config),- user_id=user.id,- )- except ValueError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc-- return ConnectorDetail(- connector_id=record.id,- connector_type=record.type,- display_name=record.display_name,- status=record.status,- agent_names=await connector_lifecycle.get_agent_names(record.id),- created_at=str(record.created_at),- )---async def list_connectors(- session: Annotated[AsyncSession, Depends(get_session)],- connector_store: Annotated[ServerConnectorStore, Depends(get_connector_store)],- connector_lifecycle: Annotated[- ServerSideConnectorLifecycleService, Depends(get_connector_lifecycle)- ],- _user: Annotated[User, Depends(get_current_user)],-) -> list[ConnectorDetail]:- records = await connector_store.get_all(session)- return [- ConnectorDetail(- connector_id=r.id,- connector_type=r.type,- display_name=r.display_name,- status=r.status,- agent_names=await connector_lifecycle.get_agent_names(r.id),- created_at=str(r.created_at),- )- for r in records- ]--[email protected]("/{connector_id}")-async def get_connector(- connector_id: str,- session: Annotated[AsyncSession, Depends(get_session)],- connector_store: Annotated[ServerConnectorStore, Depends(get_connector_store)],- connector_lifecycle: Annotated[- ServerSideConnectorLifecycleService, Depends(get_connector_lifecycle)- ],- _user: Annotated[User, Depends(get_current_user)],-) -> ConnectorDetail:- record = await connector_store.get(session, connector_id)- if record is None:- raise HTTPException(status_code=404, detail="Connector not found")-- return ConnectorDetail(- connector_id=record.id,- connector_type=record.type,- display_name=record.display_name,- status=record.status,- agent_names=await connector_lifecycle.get_agent_names(record.id),- created_at=str(record.created_at),- )--[email protected]("/{connector_id}")-async def delete_connector(- connector_id: str,- session: Annotated[AsyncSession, Depends(get_session)],- connector_store: Annotated[ServerConnectorStore, Depends(get_connector_store)],- api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],- connector_lifecycle: Annotated[- ServerSideConnectorLifecycleService, Depends(get_connector_lifecycle)- ],- user: Annotated[User, Depends(get_current_user)],- is_admin: Annotated[bool, Depends(get_tenant_is_admin)],-) -> dict[str, bool]:- record = await connector_store.get(session, connector_id)- if record is None:- raise HTTPException(status_code=404, detail="Connector not found")-- reg_key = await api_key_store.get(session, record.api_key_id)- if reg_key is None or reg_key.user_id != user.id:- if not is_admin:- raise HTTPException(- status_code=403, detail="Not authorized to delete this connector"- )- # Not held across removal, which deletes the agents on sessions of its own.- await session.commit()- try:- await connector_lifecycle.remove(connector_id)- except ValueError as exc:- # Deleted between the read above and the removal. `remove` refuses to- # report a removal it did not perform, so the race surfaces as the- # same 404 the read would have given a moment earlier.- raise HTTPException(status_code=404, detail="Connector not found") from exc- return {"ok": True}diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.pyindex b4941a833..0502d1024 100644--- a/core/switch_core/gateway/dependencies.py+++ b/core/switch_core/gateway/dependencies.py@@ -7,9 +7,6 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer-from switch_core.bridges.agent.server_connectors.lifecycle import (- ServerSideConnectorLifecycleService,-)from switch_core.bridges.collaboration.install_service import (MessagingInstallService,)@@ -29,7 +26,6 @@ from switch_core.db.stores.join_domain_store import JoinDomainStorefrom switch_core.db.stores.messaging_install_store import MessagingInstallStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStore-from switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStore@@ -51,8 +47,6 @@ def init_dependencies(bridge_store: CollaborationBridgeStore,client_lifecycle: ClientLifecycleService,collab_lifecycle: CollaborationBridgeLifecycleService,- connector_lifecycle: ServerSideConnectorLifecycleService,- connector_store: ServerConnectorStore,event_buffer: EventBuffer,session_factory: Any,user_store: UserStore,@@ -77,8 +71,6 @@ def init_dependencies(_state["bridge_store"] = bridge_store_state["client_lifecycle"] = client_lifecycle_state["collab_lifecycle"] = collab_lifecycle- _state["connector_lifecycle"] = connector_lifecycle- _state["connector_store"] = connector_store_state["event_buffer"] = event_buffer_state["session_factory"] = session_factory_state["user_store"] = user_store@@ -221,14 +213,6 @@ def get_budget_store() -> BudgetStore:return _state["budget_store"] # type: ignore[no-any-return]-def get_connector_lifecycle() -> ServerSideConnectorLifecycleService:- return _state["connector_lifecycle"] # type: ignore[no-any-return]---def get_connector_store() -> ServerConnectorStore:- return _state["connector_store"] # type: ignore[no-any-return]--def get_template_store() -> TemplateStore:return _state["template_store"] # type: ignore[no-any-return]diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 7a2c6c1af..7891067e9 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -796,29 +796,6 @@ class LinkedIdentity(BaseModel):external_username: str-# ── Server-Side Connectors ──────────────────────────────────────────────────---class ConnectorTypeInfo(BaseModel):- key: str- config_schema: dict[str, Any]---class CreateConnectorRequest(BaseModel):- type: str- display_name: str- connection_config: dict[str, object]---class ConnectorDetail(BaseModel):- connector_id: str- connector_type: str- display_name: str- status: str- agent_names: list[str]- created_at: str--# ── Auth ─────────────────────────────────────────────────────────────────────diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 787571c8b..d8a7ce95e 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -46,14 +46,6 @@ from switch_core.bridges.agent.registration_bootstrap import (RETIRED_KEY_TYPE,ensure_bootstrap_owner,)-from switch_core.bridges.agent.server_connectors.lifecycle import (- ServerSideConnectorLifecycleService,-)-from switch_core.bridges.agent.server_connectors.opencode.connector import (- OpenCodeConnectionConfig,- OpenCodeConnector,-)-from switch_core.bridges.agent.server_connectors.signals import ConnectorSignalsfrom switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.bridge_signals import BridgeSignalsfrom switch_core.bridges.collaboration.discord.adapter import (@@ -165,7 +157,6 @@ from switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_link_store import RoomLinkStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStore-from switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.service_app_credential_store import ServiceAppCredentialStorefrom switch_core.db.stores.service_connection_store import ServiceConnectionStorefrom switch_core.db.stores.switch_core_process_store import SwitchCoreProcessStore@@ -774,7 +765,6 @@ async def run(config: SwitchConfig, process_id: str) -> None:agent_event_listener = AgentEventListener(lambda: create_unpooled_engine(config), event_buffer)- connector_store = ServerConnectorStore()# ── Product telemetry ────────────────────────────────────────────────────# Before the services that report through it, switched on or not.@@ -1061,22 +1051,6 @@ async def run(config: SwitchConfig, process_id: str) -> None:# connection the handler saw start.connections.set_close_listener(protocol.sessions.on_close)- # ── Server-side connector lifecycle ─────────────────────────────────────- connector_lifecycle = ServerSideConnectorLifecycleService(- connector_store=connector_store,- api_key_store=api_key_store,- protocol=protocol,- session_factory=session_factory,- keyring=config.keyring,- telemetry=telemetry,- outbound_policy=config.outbound_policy,- ownership=ownership,- )- ConnectorSignals(lifecycle=connector_lifecycle, bus=signal_bus)- connector_lifecycle.register_connector_type(- "opencode", OpenCodeConnector, OpenCodeConnectionConfig- )-# ── Messaging app installs ──────────────────────────────────────────────# Registration is the feature flag. An installer exists for a platform when# this deployment holds that platform's app credentials, and the whole@@ -1216,8 +1190,6 @@ async def run(config: SwitchConfig, process_id: str) -> None:bridge_store=bridge_store,client_lifecycle=client_lifecycle,collab_lifecycle=collab_lifecycle,- connector_lifecycle=connector_lifecycle,- connector_store=connector_store,event_buffer=event_buffer,session_factory=session_factory,user_store=user_store,@@ -1328,14 +1300,12 @@ async def run(config: SwitchConfig, process_id: str) -> None:bridges_running_by_platform=collab_lifecycle.running_by_platform,bridges_configured=collab_lifecycle.expected_count,consumers_running=client_lifecycle.running_count,- connectors_running=connector_lifecycle.running_count,- connectors_configured=connector_lifecycle.expected_count,agents_connected=connections.live_agents_by_transport,pool_stats=lambda: pool_stats(engine, pool_watermark),room_cache_stats=room_cache.stats,)- # ── Lifespan: start server-side connectors once HTTP is serving ────────+ # ── Lifespan ──────────────────────────────────────────────────────────────original_lifespan = agent_bridge_app.router.lifespan_context# A service is issued only where this server is set up for it, as its@@ -1392,7 +1362,6 @@ async def run(config: SwitchConfig, process_id: str) -> None:process_id=process_id,db_server_engine=lambda: create_unpooled_engine(config),)- asyncio.create_task(connector_lifecycle.start_all())sweep_task = asyncio.create_task(_runtime_state_sweep_loop(protocol))retention_task = asyncio.create_task(_agent_event_retention_loop(session_factory, event_buffer)@@ -1583,7 +1552,6 @@ async def run(config: SwitchConfig, process_id: str) -> None:connections.controllers,client_lifecycle,collab_lifecycle,- connector_lifecycle,provisioning,discord_gateway,teams_app,@@ -2134,7 +2102,6 @@ async def _shutdown(controllers: ControllerPresence,client_lifecycle: ClientLifecycleService,collab_lifecycle: CollaborationBridgeLifecycleService,- connector_lifecycle: ServerSideConnectorLifecycleService,provisioning: Provisioning,discord_gateway: DiscordGatewayClient | None,teams_app: TeamsSharedApp | None,@@ -2157,11 +2124,10 @@ async def _shutdown(# uvicorn runs that only once every connection has closed, and a stream# still open when the process is killed would mean it never runs. Every# other process reads this one's machines offline from here, and has taken- # over the consumers, bridges and connectors it owned, so the sockets close- # straight after and their clients reconnect to a process that holds them.+ # over the consumers and bridges it owned, so the sockets close straight+ # after and their clients reconnect to a process that holds them.await release()server.should_exit = True- await connector_lifecycle.stop_all()await collab_lifecycle.stop_all()# The API log-in of a process that did not hold the socket; the socket# itself was closed with the rest of the owned work in `release`. `stop`diff --git a/core/switch_core/observability/bootstrap.py b/core/switch_core/observability/bootstrap.pyindex afa713ab1..59c156fb1 100644--- a/core/switch_core/observability/bootstrap.py+++ b/core/switch_core/observability/bootstrap.py@@ -22,7 +22,6 @@ from switch_core.logging_context import LogContextFilterfrom switch_core.observability.catalogue import (AGENTS_CONNECTED,BRIDGES_RUNNING,- CONNECTORS_RUNNING,CONSUMERS_RUNNING,DB_POOL_IN_USE,DB_POOL_OVERFLOW,@@ -37,7 +36,6 @@ from switch_core.observability.health import (HealthMonitor,agent_event_listener_check,bridges_check,- connectors_check,database_check,message_listener_check,session_activity_listener_check,@@ -94,8 +92,6 @@ class RuntimeProbes:bridges_running_by_platform: Callable[[], Mapping[str, int]]bridges_configured: Callable[[], int]consumers_running: Callable[[], int]- connectors_running: Callable[[], int]- connectors_configured: Callable[[], int]# Agents per (transport, client); see# `AgentConnectionRegistry.live_agents_by_transport`.agents_connected: Callable[[], Mapping[tuple[str, str], int]]@@ -158,7 +154,6 @@ def _state_readings(probes: RuntimeProbes) -> Callable[[], Iterator[GaugeReadingfloat(running),{"bridge": "collaboration", "platform": platform},)- yield GaugeReading(CONNECTORS_RUNNING, float(probes.connectors_running()), {})stats = probes.pool_stats()if stats is not None:@@ -203,7 +198,6 @@ def start_observability(),signal_bus_check(probes.signal_bus_connected, listeners_gate),bridges_check(probes.bridges_running, probes.bridges_configured),- connectors_check(probes.connectors_running, probes.connectors_configured),],interval_seconds=HEALTH_REFRESH_INTERVAL_SECONDS,)diff --git a/core/switch_core/observability/catalogue.py b/core/switch_core/observability/catalogue.pyindex 436670b65..60f934816 100644--- a/core/switch_core/observability/catalogue.py+++ b/core/switch_core/observability/catalogue.py@@ -524,14 +524,6 @@ CONSUMERS_RUNNING = _spec("another platform) run no loop and are not counted. A collaboration ""bridge's workspace consumer counts under switch.bridges.running.",)-CONNECTORS_RUNNING = _spec(- "switch.connectors.running",- "gauge",- "{connector}",- "Server-side connectors running. Started fire-and-forget with each failure "- "logged and stepped over, so one short of the configured count is a dead "- "agent host nothing else reports.",-)# ── Service tokens ───────────────────────────────────────────────────────────# `connector` is a catalog slug ("unknown" for a name the catalog does not@@ -674,7 +666,6 @@ CATALOGUE: dict[str, MetricSpec] = {AGENT_CONNECTIONS_OPENED,AGENTS_CONNECTED,CONSUMERS_RUNNING,- CONNECTORS_RUNNING,SERVICE_TOKEN_REQUESTS,RUNTIME_MEMORY_RSS,RUNTIME_CPU_SECONDS,diff --git a/core/switch_core/observability/health.py b/core/switch_core/observability/health.pyindex cb24ddd92..bea893ee6 100644--- a/core/switch_core/observability/health.py+++ b/core/switch_core/observability/health.py@@ -232,34 +232,6 @@ def bridges_check(return HealthCheck(name="bridges", gates_readiness=False, probe=probe)-def connectors_check(- running: Callable[[], int], configured: Callable[[], int]-) -> HealthCheck:- """Whether every server-side connector this process meant to run is running.-- Started fire-and-forget, with each failure logged and stepped over, so one- that never came up is a dead agent host with no other trace. Reported,- never gating.- """-- async def probe() -> CheckOutcome:- live = running()- expected = configured()- if live >= expected:- return CheckOutcome(name="connectors", healthy=True, detail="")- return CheckOutcome(- name="connectors",- healthy=False,- detail=(- f"{expected - live} of {expected} server-side connector(s) are "- "not running. The agents they host are unreachable; the boot "- "log names which failed and why."- ),- )-- return HealthCheck(name="connectors", gates_readiness=False, probe=probe)--class HealthMonitor:"""Runs the checks on an interval and holds the latest answer."""diff --git a/core/switch_core/outbound.py b/core/switch_core/outbound.pyindex 34b4dd75a..b83bc22ee 100644--- a/core/switch_core/outbound.py+++ b/core/switch_core/outbound.py@@ -1,14 +1,14 @@"""Outbound requests to URLs a tenant or an agent chose.-A Mattermost server URL, an OpenCode server URL or an agent's icon is fetched-by Switch from inside the network it runs in. Unchecked, such a URL can name a-service on that network or the cloud instance-metadata endpoint, and the-request carries whatever credentials go with it.+A Mattermost server URL or an agent's icon is fetched by Switch from inside+the network it runs in. Unchecked, such a URL can name a service on that+network or the cloud instance-metadata endpoint, and the request carries+whatever credentials go with it.`OutboundPolicy` decides which addresses may be reached: any public address,plus the private hosts and networks an operator lists in`OUTBOUND_ALLOWED_PRIVATE_HOSTS` (a bundled Mattermost, a tailnet server, a-local OpenCode in development). Link-local addresses, which include the+server on `localhost` in development). Link-local addresses, which include themetadata endpoints, are refused even when listed.The check is made on the resolved addresses, not on the hostname, so a public@@ -54,8 +54,8 @@ _HOSTNAME_RE = re.compile(_DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}# httpx's own defaults, which its pool gets and a bare httpcore pool does not:-# httpcore's are 10 connections with idle ones kept forever, and an OpenCode-# session holds a connection for minutes at a time.+# httpcore's are 10 connections with idle ones kept forever, which the service+# broker's client, shared for the life of the process, would never shed._POOL_LIMITS = httpx.Limits(max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0)diff --git a/core/switch_core/ownership.py b/core/switch_core/ownership.pyindex 85a252beb..730775d73 100644--- a/core/switch_core/ownership.py+++ b/core/switch_core/ownership.py@@ -3,8 +3,8 @@Several switch-core processes share one database, and some work must run inexactly one of them: a client's consumer, such as the admin's, which answerscommands and posts warnings; a collaboration bridge's platform connection and-the consumer that posts to the platform; a server-side connector polling its-agents. Run in two processes, every such effect happens twice.+the consumer that posts to the platform. Run in two processes, every such+effect happens twice.Each piece of work is a kind and a key ("client" and a client id). A processwants the keys it could run, and runs those it owns. Which process owns a keydiff --git a/core/switch_core/process_lease.py b/core/switch_core/process_lease.pyindex 4594cbaa6..2d233e87a 100644--- a/core/switch_core/process_lease.py+++ b/core/switch_core/process_lease.py@@ -13,10 +13,9 @@ within `LEASE_TTL` and not stopped. One write per process per renewal, howevermany connections it holds.The work that must run once (a client's consumer, a bridge's platform-connection, a server-side connector) is owned through `ownership.py`, whose-leases are valid only while their holder's process lease is held, and which-stops its work when this process can no longer be sure its own is-(`surely_held`).+connection) is owned through `ownership.py`, whose leases are valid only while+their holder's process lease is held, and which stops its work when this+process can no longer be sure its own is (`surely_held`).The lease also records the ids of the keys the process can read, which aprocess starting with a new front key checks (`db/key_rotation.py`).diff --git a/core/switch_core/telemetry/catalogue.py b/core/switch_core/telemetry/catalogue.pyindex a992c0237..c72786820 100644--- a/core/switch_core/telemetry/catalogue.py+++ b/core/switch_core/telemetry/catalogue.py@@ -536,9 +536,6 @@ CATALOGUE: Mapping[str, Mapping[str, PropertyType]] = {"reference_detached_from_room": {"reference_type": REFERENCE_TYPE},"document_detached_from_room": {},"package_detached_from_room": {},- # Switch reaching out to an agent host, rather than one connecting in.- "server_connector_registered": {"connector_kind": one_of("opencode", "other")},- "server_connector_removed": {"connector_kind": one_of("opencode", "other")},# Configured, not connected. Many of these and few `bridge_connected` is a# deployment whose setup is failing."connector_configured": {diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex e392fb029..36b55c0e0 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -37,6 +37,10 @@ from testcontainers.postgres import PostgresContainer# Importing models registers every table on Base.metadata for create_all.import switch_core.db.models # noqa: F401+from switch_core.bridges.agent.api.handlers import (+ _resolve_registration_user_id,+ registration_path,+)from switch_core.bridges.agent.api_key_cache import ApiKeyCachefrom switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.protocol.agent_core import AgentCore@@ -317,16 +321,27 @@ class Harness:self, name: str, token: str) -> RegistrationResult:"""Register the way a standalone agent does: with a bearer token- presented to `POST /agents`, resolved here directly against the- protocol service rather than over real HTTP."""- result = await self.protocol.register_agent_with_token(- registration_token=token,+ presented to `POST /agents`, its owner resolved by the endpoint's own+ dependency rather than over real HTTP.++ The tenant is the harness's, tenant zero, which is where the bootstrap+ key lives; binding the token's own tenant is `BearerAuthMiddleware`'s+ part, covered by `test_bearer_auth_tenant_binding.py`."""+ async with self.session_factory() as session: # type: ignore[operator]+ owner_id = await _resolve_registration_user_id(+ authorization=f"Bearer {token}",+ session=session,+ api_key_store=ApiKeyStore(),+ protocol=self.protocol,+ )+ result = await self.protocol.register_agent(name=name,description=f"integration test agent {name}",connector_type="test",integration_profile=_PROFILE,+ owner_id=owner_id,overwrite=True,- addressing_policy=None,+ registration_path=registration_path(),)self._registered.append(result.agent_id)return resultdiff --git a/core/tests/integration/test_registration_bootstrap_scope.py b/core/tests/integration/test_registration_bootstrap_scope.pyindex 77a602303..1ec0beda0 100644--- a/core/tests/integration/test_registration_bootstrap_scope.py+++ b/core/tests/integration/test_registration_bootstrap_scope.py@@ -9,8 +9,8 @@ deployment secret to bring up their own agent got an agent that could bypassdeployment, not just their own.This test registers an agent the same way a standalone agent does — presenting-REGISTRATION_TOKEN to `register_agent_with_token` — and proves the resulting-agent is owned by a dedicated, non-admin account instead.+REGISTRATION_TOKEN to `POST /agents` — and proves the resulting agent is owned+by a dedicated, non-admin account instead."""from __future__ import annotationsdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_bootstrap.py b/core/tests/switch_core/bridges/agent/api/test_registration_owner.pysimilarity index 62%rename from core/tests/switch_core/bridges/agent/protocol/test_register_with_token_bootstrap.pyrename to core/tests/switch_core/bridges/agent/api/test_registration_owner.pyindex 2cdbccfed..bb6034443 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_bootstrap.py+++ b/core/tests/switch_core/bridges/agent/api/test_registration_owner.py@@ -1,4 +1,4 @@-"""`register_agent_with_token` must not let a shared secret act as admin.+"""Registering over HTTP must not let a shared secret act as admin.Before this fix, the deployment-wide AGENT_REGISTRATION_TOKEN was seeded as a`"registration"`-type key owned by the admin user, so every agent registered@@ -6,6 +6,9 @@ through it inherited the admin's authority (`_resolve_acting_identity` readsthe owner's `role` straight off the `User` row). A `"bootstrap"`-type key nowresolves to a dedicated, non-admin owner instead — this proves it, and thata non-registration key (an agent's own) can no longer be replayed as one.++`_resolve_registration_user_id` is the dependency `POST /agents` resolves its+owner through; the agent is then registered for whoever it answers."""from __future__ import annotations@@ -13,17 +16,21 @@ from __future__ import annotationsimport hashlibimport pytest+from fastapi import HTTPExceptionfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.bridges.agent.api.handlers import _resolve_registration_user_id+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.registration_bootstrap import (BOOTSTRAP_KEY_TYPE,ensure_bootstrap_owner,)from switch_core.db.models import ApiKey, User+from switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.user_store import UserStorefrom tests.switch_core.bridges.agent.protocol.registration_harness import (- PROFILE,make_service,+ register,)@@ -55,7 +62,19 @@ async def _make_key(await session.commit()-class TestBootstrapTokenRegistration:+async def _owner_for(+ session_factory: async_sessionmaker[AsyncSession], svc: AgentCore, token: str+) -> str:+ async with session_factory() as session:+ return await _resolve_registration_user_id(+ authorization=f"Bearer {token}",+ session=session,+ api_key_store=ApiKeyStore(),+ protocol=svc,+ )+++class TestRegistrationOwner:async def test_bootstrap_token_owns_the_agent_as_the_bootstrap_account(self, session_factory: async_sessionmaker[AsyncSession]) -> None:@@ -71,17 +90,13 @@ class TestBootstrapTokenRegistration:key_type=BOOTSTRAP_KEY_TYPE,)- result = await svc.register_agent_with_token(- registration_token="shared-secret",- name="colleague-agent",- description="d",- connector_type="test",- integration_profile=PROFILE,- addressing_policy=None,+ owner_id = await _owner_for(session_factory, svc, "shared-secret")+ agent_id = await register(+ svc, "colleague-agent", owner_id, addressing_policy=None)async with session_factory() as session:- agent = await svc.agent_store.get(session, result.agent_id)+ agent = await svc.agent_store.get(session, agent_id)assert agent is not Noneassert agent.owner_id == bootstrap_owner.idassert agent.owner_id != admin_id@@ -99,19 +114,7 @@ class TestBootstrapTokenRegistration:session_factory, user_id=owner_id, token="personal", key_type="registration")- result = await svc.register_agent_with_token(- registration_token="personal",- name="personal-agent",- description="d",- connector_type="test",- integration_profile=PROFILE,- addressing_policy=None,- )-- async with session_factory() as session:- agent = await svc.agent_store.get(session, result.agent_id)- assert agent is not None- assert agent.owner_id == owner_id+ assert await _owner_for(session_factory, svc, "personal") == owner_idasync def test_an_agent_key_cannot_be_replayed_as_a_registration_token(self, session_factory: async_sessionmaker[AsyncSession]@@ -125,11 +128,24 @@ class TestBootstrapTokenRegistration:key_type="agent",)- with pytest.raises(PermissionError):- await svc.register_agent_with_token(- registration_token="leaked-agent-key",- name="should-not-exist",- description="d",- connector_type="test",- integration_profile=PROFILE,- )+ with pytest.raises(HTTPException) as refused:+ await _owner_for(session_factory, svc, "leaked-agent-key")+ assert refused.value.status_code == 401++ async def test_a_bootstrap_key_with_no_trusted_owner_is_unavailable_not_invalid(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The token is valid, so a 401 would send its holder off to fix a+ credential that is fine; what is wrong is the deployment."""+ svc = make_service(session_factory)+ admin_id = await _make_admin(session_factory)+ await _make_key(+ session_factory,+ user_id=admin_id,+ token="shared-secret",+ key_type=BOOTSTRAP_KEY_TYPE,+ )++ with pytest.raises(HTTPException) as refused:+ await _owner_for(session_factory, svc, "shared-secret")+ assert refused.value.status_code == 503diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py b/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.pyindex 3810f03cc..f58e8c82b 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py@@ -2,9 +2,6 @@from __future__ import annotations-import hashlib-from types import SimpleNamespace-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.addressing import (@@ -14,40 +11,13 @@ from switch_core.addressing import (parse_policy,)from switch_core.bridges.agent.protocol.agent_core import AgentCore-from switch_core.db.models import TENANT_ZERO_ID, ApiKeyfrom tests.switch_core.bridges.agent.protocol.registration_harness import (- PROFILE,make_owner,make_service,register,)-async def _seed_registration_key(- session_factory: async_sessionmaker[AsyncSession], owner_id: str, token: str-) -> None:- """A real `api_keys` row for `token`.-- `register_agent_with_token` resolves the token's tenant through- `tenant_of_api_key` — a `SECURITY DEFINER` SQL function reading the real- table — before it ever reaches `svc.api_key_store`, which these tests- stub (`_stub_key`) to control the row `register_agent_with_token` sees- once the tenant is known. Stubbing the store cannot stand in for this- row too: the tenant lookup has no store to intercept.- """- async with session_factory() as session:- session.add(- ApiKey(- user_id=owner_id,- key_hash=hashlib.sha256(token.encode()).hexdigest(),- encrypted_key="enc",- label="reg",- type="registration",- )- )- await session.commit()--async def _policy_of(svc: AgentCore,session_factory: async_sessionmaker[AsyncSession],@@ -135,8 +105,8 @@ class TestRegistrationDefaultPolicy:async def test_no_policy_leaves_the_agent_open(self, session_factory: async_sessionmaker[AsyncSession]) -> None:- # A service the deployment offers everyone (a server-side connector- # agent) is owned by someone only in the bookkeeping sense.+ # An agent the deployment offers everyone is owned by someone only in+ # the bookkeeping sense.svc = make_service(session_factory)owner_id = await make_owner(session_factory)agent_id = await register(svc, "shared", owner_id, addressing_policy=None)@@ -164,69 +134,3 @@ class TestRegistrationDefaultPolicy:assert again == agent_idraw = await _policy_of(svc, session_factory, agent_id)assert raw == {"rules": [{"users": ["ext-3"], "agents": []}]}---class TestRegisterWithTokenPassesThrough:- async def test_token_registration_uses_the_default_policy(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- svc = make_service(session_factory)- owner_id = await make_owner(session_factory)- await _seed_registration_key(session_factory, owner_id, "tok")- captured: dict[str, object] = {}-- async def _register_agent(**kwargs: object) -> object:- captured.update(kwargs)- return SimpleNamespace(agent_id="a1", api_key="k", oauth_client_id=None)-- svc.register_agent = _register_agent # type: ignore[assignment, method-assign]- svc.api_key_store = SimpleNamespace( # type: ignore[assignment]- get_by_hash=_stub_key(owner_id)- )-- await svc.register_agent_with_token(- registration_token="tok",- name="tokenised",- description="d",- connector_type="test",- integration_profile=PROFILE,- )- assert captured["addressing_policy"] == default_agent_policy()-- async def test_token_registration_forwards_the_overrides(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- svc = make_service(session_factory)- owner_id = await make_owner(session_factory)- await _seed_registration_key(session_factory, owner_id, "tok")- captured: dict[str, object] = {}-- async def _register_agent(**kwargs: object) -> object:- captured.update(kwargs)- return SimpleNamespace(agent_id="a1", api_key="k", oauth_client_id=None)-- svc.register_agent = _register_agent # type: ignore[assignment, method-assign]- svc.api_key_store = SimpleNamespace( # type: ignore[assignment]- get_by_hash=_stub_key(owner_id)- )-- await svc.register_agent_with_token(- registration_token="tok",- name="tokenised",- description="d",- connector_type="test",- integration_profile=PROFILE,- addressing_policy=owner_only_policy(["dispatcher"]),- )- assert captured["addressing_policy"] == owner_only_policy(["dispatcher"])---def _stub_key(owner_id: str): # type: ignore[no-untyped-def]- async def _get_by_key(_session: AsyncSession, _token: str) -> object:- # Carries a `tenant_id` because registration binds the token's tenant- # for the write it delegates to — see `register_agent_with_token`.- return SimpleNamespace(- user_id=owner_id, type="registration", tenant_id=TENANT_ZERO_ID- )-- return _get_by_keydiff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.py b/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.pyindex 4344f4410..01e7f9f49 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.py@@ -5,8 +5,8 @@ Two things are load-bearing here. First, that the Matrix client keeps thecoming back from a platform by matching `sender_name`, so a human name on theclient would make an agent re-import its own messages as a stranger and appearin the room twice. Second, that a re-registration which says nothing about the-icon or the display name keeps both — server-side connectors re-register with-`overwrite=True` on every startup.+icon or the display name keeps both — a client that re-registers with+`overwrite=True` on every launch knows nothing about either."""from __future__ import annotations@@ -95,8 +95,8 @@ class TestReregistrationKeepsWhatItWasNotTold:async def test_omitting_both_preserves_icon_and_display_name(self, session_factory: async_sessionmaker[AsyncSession]) -> None:- # A server-side connector re-registers with overwrite=True on every- # startup and knows nothing about either field.+ # A client that re-registers with overwrite=True on every launch+ # knows nothing about either field.svc = make_service(session_factory)owner_id = await make_owner(session_factory)agent_id = await register(diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_tenant.py b/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_tenant.pydeleted file mode 100644index c424d5986..000000000--- a/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_tenant.py+++ /dev/null@@ -1,135 +0,0 @@-"""`register_agent_with_token` puts the new agent in the *token's* tenant.--This is the registration path with nothing in front of it: a server-side-connector registers its discovered agents from a startup task-(`server_connectors/core.py`), where there is no request and so no bound-tenant. The HTTP path has `BearerAuthMiddleware` binding one; this one has to-bind it itself, from the same source of truth — `api_keys.tenant_id`.--Getting it wrong is not a transient mistake. The rows written here are what a-later bearer request is authenticated against, and that request reads-`api_keys.tenant_id` back to decide the tenant — so an agent registered into-tenant zero by fallback stays there, and keeps confirming itself.-"""--from __future__ import annotations--import hashlib--import pytest-from sqlalchemy import select-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker--from switch_core.db.models import TENANT_ZERO_ID, Agent, ApiKey, Client, Tenant, User-from switch_core.tenant_context import current_tenant_id-from tests.switch_core.bridges.agent.protocol.registration_harness import (- PROFILE,- make_service,-)--TENANT_B = "register-token-tenant-b"---async def _seed_token(- session_factory: async_sessionmaker[AsyncSession],- *,- token: str,- tenant_id: str,-) -> None:- async with session_factory() as session:- if tenant_id != TENANT_ZERO_ID:- session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))- await session.flush()- user = User(name="minter", email=f"minter-{tenant_id}@test", role="user")- session.add(user)- await session.flush()- session.add(- ApiKey(- tenant_id=tenant_id,- user_id=user.id,- key_hash=hashlib.sha256(token.encode()).hexdigest(),- encrypted_key="irrelevant",- label="registration",- type="registration",- )- )- await session.commit()---class TestRegistrationTokenDecidesTheTenant:- async def test_the_agent_and_its_credentials_land_in_the_tokens_tenant(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _seed_token(session_factory, token="reg-tok", tenant_id=TENANT_B)- svc = make_service(session_factory)-- result = await svc.register_agent_with_token(- registration_token="reg-tok",- name="connector-agent",- description="discovered by a connector",- connector_type="server-side:test",- integration_profile=PROFILE,- addressing_policy=None,- )-- async with session_factory() as session:- agent = await session.get(Agent, result.agent_id)- assert agent is not None- assert agent.tenant_id == TENANT_B-- key = await session.get(ApiKey, agent.api_key_id)- assert key is not None- assert key.tenant_id == TENANT_B-- client = await session.get(Client, agent.client_id)- assert client is not None- assert client.tenant_id == TENANT_B-- @pytest.mark.no_ambient_tenant- async def test_nothing_stays_bound_after_registration_returns(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _seed_token(session_factory, token="reg-tok", tenant_id=TENANT_B)- svc = make_service(session_factory)-- assert current_tenant_id() is None- await svc.register_agent_with_token(- registration_token="reg-tok",- name="another-agent",- description="d",- connector_type="server-side:test",- integration_profile=PROFILE,- addressing_policy=None,- )- assert current_tenant_id() is None-- async def test_no_row_falls_back_to_tenant_zero(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- """The failure mode this exists to prevent, stated as an assertion:- the `TenantScoped` default silently produces tenant zero, so a- registration that bound nothing would leave rows there and look fine.- """- await _seed_token(session_factory, token="reg-tok", tenant_id=TENANT_B)- svc = make_service(session_factory)-- await svc.register_agent_with_token(- registration_token="reg-tok",- name="zero-check-agent",- description="d",- connector_type="server-side:test",- integration_profile=PROFILE,- addressing_policy=None,- )-- async with session_factory() as session:- stray_agents = await session.execute(- select(Agent.name).where(Agent.tenant_id == TENANT_ZERO_ID)- )- stray_keys = await session.execute(- select(ApiKey.label).where(- ApiKey.tenant_id == TENANT_ZERO_ID, ApiKey.type == "agent"- )- )- assert stray_agents.scalars().all() == []- assert stray_keys.scalars().all() == []diff --git a/core/tests/switch_core/bridges/agent/protocol/test_rename_agent.py b/core/tests/switch_core/bridges/agent/protocol/test_rename_agent.pyindex db1c2aa62..d03729219 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_rename_agent.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_rename_agent.py@@ -541,20 +541,6 @@ class TestRefusals:agent_id=parent_id, new_name="other", display_name=None)- async def test_a_server_connector_agent(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- svc = _service(session_factory, _FakeAdapter())- owner = await make_owner(session_factory)- agent_id = await register(- svc, "found", owner, metadata={"server_connector_id": "c1"}- )-- with pytest.raises(AgentRenameRefused, match="server connector"):- await svc.rename_agent(- agent_id=agent_id, new_name="other", display_name=None- )-async def test_no_tenant(self, session_factory: async_sessionmaker[AsyncSession]) -> None:diff --git a/core/tests/switch_core/bridges/agent/protocol/test_request_agent_deletion.py b/core/tests/switch_core/bridges/agent/protocol/test_request_agent_deletion.pyindex 08878fd8c..e47815e07 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_request_agent_deletion.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_request_agent_deletion.py@@ -135,17 +135,6 @@ class TestRefused:)assert lifecycle.posted == []- async def test_a_server_connector_agent(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- svc, _lifecycle, _owner, caller, target, room_id = await _setup(session_factory)- await _set(session_factory, target, metadata_={"server_connector_id": "c1"})-- with pytest.raises(AgentRenameRefused, match="server connector"):- await svc.request_agent_deletion(- caller_agent_id=caller, target_agent_id=target, room_id=room_id- )-async def test_another_owners_agent(self, session_factory: async_sessionmaker[AsyncSession]) -> None:diff --git a/core/tests/switch_core/bridges/agent/server_connectors/__init__.py b/core/tests/switch_core/bridges/agent/server_connectors/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/core/tests/switch_core/bridges/agent/server_connectors/opencode/__init__.py b/core/tests/switch_core/bridges/agent/server_connectors/opencode/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/core/tests/switch_core/bridges/agent/server_connectors/opencode/test_connector.py b/core/tests/switch_core/bridges/agent/server_connectors/opencode/test_connector.pydeleted file mode 100644index b9bb1c6ad..000000000--- a/core/tests/switch_core/bridges/agent/server_connectors/opencode/test_connector.py+++ /dev/null@@ -1,202 +0,0 @@-from __future__ import annotations--from collections.abc import AsyncIterator-from contextlib import asynccontextmanager-from typing import Any--from switch_core.bridges.agent.server_connectors.base import ConnectorReporter-from switch_core.bridges.agent.server_connectors.opencode.connector import (- OpenCodeConnectionConfig,- OpenCodeConnector,-)-from switch_core.outbound import OutboundPolicy--SESSION_ID = "sess-1"-ROOM_ID = "room-1"---class _FakeReporter(ConnectorReporter):- def __init__(self) -> None:- self.messages: list[str] = []- self.statuses: list[str] = []- self.events: list[Any] = []-- async def send_message(self, room_id: str, content: str) -> None:- self.messages.append(content)-- async def report_events(self, room_id: str, events: Any) -> None:- self.events.extend(events)-- async def send_status(self, room_id: str, detail: str) -> None:- self.statuses.append(detail)-- async def set_typing(self, room_id: str, is_typing: bool) -> None:- pass---class _FakeClient:- """Stands in for OpenCodeClient, replaying a scripted SSE event stream."""-- def __init__(self, events: list[dict[str, Any]]) -> None:- self._events = events- self.permission_responses: list[tuple[str, str, str]] = []-- @asynccontextmanager- async def subscribe_events(self) -> AsyncIterator[AsyncIterator[dict[str, Any]]]:- async def _gen() -> AsyncIterator[dict[str, Any]]:- for event in self._events:- yield event-- yield _gen()-- async def respond_permission(- self, session_id: str, permission_id: str, response: str- ) -> None:- self.permission_responses.append((session_id, permission_id, response))---class _FailingPermissionClient(_FakeClient):- """A client whose permission reply always fails."""-- async def respond_permission(- self, session_id: str, permission_id: str, response: str- ) -> None:- raise RuntimeError("opencode unreachable")---def _connector_with(- events: list[dict[str, Any]],- client: _FakeClient | None = None,-) -> tuple[OpenCodeConnector, _FakeClient]:- config = OpenCodeConnectionConfig(- server_url="http://localhost", username="u", password="p"- )- connector = OpenCodeConnector(config, OutboundPolicy.parse("localhost"))- client = client or _FakeClient(events)- connector._client = client # type: ignore[assignment]- return connector, client---async def test_permission_request_is_auto_approved() -> None:- events = [- {- "type": "permission.updated",- "properties": {- "id": "perm-1",- "sessionID": SESSION_ID,- "type": "bash",- },- },- {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},- ]- connector, client = _connector_with(events)- reporter = _FakeReporter()-- await connector._stream_response(SESSION_ID, ROOM_ID, reporter)-- assert client.permission_responses == [(SESSION_ID, "perm-1", "always")]---async def test_permission_for_other_session_is_ignored() -> None:- events = [- {- "type": "permission.updated",- "properties": {"id": "perm-x", "sessionID": "other-session"},- },- {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},- ]- connector, client = _connector_with(events)-- await connector._stream_response(SESSION_ID, ROOM_ID, _FakeReporter())-- assert client.permission_responses == []---async def test_permission_responded_only_once() -> None:- perm = {- "type": "permission.updated",- "properties": {"id": "perm-1", "sessionID": SESSION_ID},- }- events = [- perm,- perm,- {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},- ]- connector, client = _connector_with(events)-- await connector._stream_response(SESSION_ID, ROOM_ID, _FakeReporter())-- assert client.permission_responses == [(SESSION_ID, "perm-1", "always")]---async def test_permission_event_read_from_data_key() -> None:- """Some OpenCode builds carry the payload under `data` rather than `properties`."""- events = [- {- "type": "permission.updated",- "data": {"id": "perm-1", "sessionID": SESSION_ID},- },- {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},- ]- connector, client = _connector_with(events)-- await connector._stream_response(SESSION_ID, ROOM_ID, _FakeReporter())-- assert client.permission_responses == [(SESSION_ID, "perm-1", "always")]---async def test_permission_reply_failure_does_not_break_the_stream() -> None:- events = [- {- "type": "permission.updated",- "properties": {"id": "perm-1", "sessionID": SESSION_ID},- },- {- "type": "message.part.updated",- "properties": {- "sessionID": SESSION_ID,- "part": {- "type": "text",- "id": "text-1",- "text": "done",- "time": {"end": 1},- },- },- },- {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},- ]- connector, _ = _connector_with(events, client=_FailingPermissionClient(events))- reporter = _FakeReporter()-- await connector._stream_response(SESSION_ID, ROOM_ID, reporter)-- assert reporter.messages == ["done"]---async def test_text_part_still_relayed_after_permission() -> None:- events = [- {- "type": "permission.updated",- "properties": {"id": "perm-1", "sessionID": SESSION_ID},- },- {- "type": "message.part.updated",- "properties": {- "sessionID": SESSION_ID,- "part": {- "type": "text",- "id": "text-1",- "text": "done",- "time": {"end": 1},- },- },- },- {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},- ]- connector, client = _connector_with(events)- reporter = _FakeReporter()-- await connector._stream_response(SESSION_ID, ROOM_ID, reporter)-- assert client.permission_responses == [(SESSION_ID, "perm-1", "always")]- assert reporter.messages == ["done"]diff --git a/core/tests/switch_core/bridges/agent/server_connectors/test_connector_ownership.py b/core/tests/switch_core/bridges/agent/server_connectors/test_connector_ownership.pydeleted file mode 100644index 071bf8955..000000000--- a/core/tests/switch_core/bridges/agent/server_connectors/test_connector_ownership.py+++ /dev/null@@ -1,371 +0,0 @@-"""A server-side connector runs in the one process that holds it.--Against real PostgreSQL, two "processes" on one database, each with its own-signal bus, process lease, ownership and connector lifecycle, wired as `main`-wires them. The connector's server here (`_Server`) records which copies of-the connector are connected to it, so a test can say the connector, and so-each of its agents' poll loops, runs in one process at a time.-"""--from __future__ import annotations--import asyncio-import uuid-from collections.abc import AsyncIterator, Callable-from dataclasses import dataclass-from types import SimpleNamespace-from typing import Any, ClassVar--import pytest-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine-from sqlalchemy.pool import NullPool--from switch_core.bridges.agent.protocol.types import (- CommandPayload,- IntegrationProfile,- MessagePayload,-)-from switch_core.bridges.agent.server_connectors.base import (- ConnectorReporter,- DiscoveredAgent,- ServerSideConnector,- ServerSideConnectorConfig,-)-from switch_core.bridges.agent.server_connectors.lifecycle import (- ServerSideConnectorLifecycleService,-)-from switch_core.bridges.agent.server_connectors.signals import ConnectorSignals-from switch_core.db.models import ApiKey, ServerConnector, User-from switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.db.stores.ownership_lease_store import OwnershipLeaseStore-from switch_core.db.stores.server_connector_store import ServerConnectorStore-from switch_core.db.stores.switch_core_process_store import SwitchCoreProcessStore-from switch_core.keys import Keyring-from switch_core.outbound import OutboundPolicy-from switch_core.ownership import Ownership-from switch_core.process_lease import ProcessLease-from switch_core.signals import SignalBus-from tests.ownership import process_lease_on-from tests.switch_core.test_room_wide_mention_wakes_no_agent import _make_agent--TIMEOUT = 10.0-KIND = "fake-server"-KEYRING = Keyring.parse("test:" + "x" * 40, legacy_secret=None)---class _Server:- """The agent server every copy of the connector talks to."""-- def __init__(self) -> None:- self.connected: list[_Connector] = []---class _Config(ServerSideConnectorConfig):- pass---class _Connector(ServerSideConnector):- server: ClassVar[_Server]-- def __init__(self, *, config: _Config, outbound_policy: OutboundPolicy) -> None:- self.config = config-- async def start(self) -> None:- self.server.connected.append(self)-- async def stop(self) -> None:- self.server.connected.remove(self)-- async def discover_agents(self) -> list[DiscoveredAgent]:- return [- DiscoveredAgent(- name="helper",- description="",- integration_profile=IntegrationProfile(- connection_model="always_on",- message_exchange=True,- pre_invocation_mediation=[],- post_invocation_mediation=[],- event_reporting=[],- ),- )- ]-- async def handle_message(- self,- agent_name: str,- room_id: str,- message: MessagePayload,- reporter: ConnectorReporter,- ) -> str | None:- return None-- async def handle_command(- self, agent_name: str, room_id: str, command: CommandPayload- ) -> None:- return None---class _Protocol:- """`AgentCore` as far as a connector reaches it: its agents register,- then long-poll for events that never come."""-- def __init__(self) -> None:- self.deleted: list[str] = []-- async def register_agent_with_token(self, **_: Any) -> Any:- return SimpleNamespace(agent_id=f"agent-{uuid.uuid4().hex[:8]}")-- async def poll_events(self, agent_id: str, timeout: int) -> list[Any]:- await asyncio.sleep(3600)- return []-- async def delete_agent(self, *, agent_id: str) -> None:- self.deleted.append(agent_id)---@dataclass-class _Process:- lease: ProcessLease- ownership: Ownership- bus: SignalBus- connectors: ServerSideConnectorLifecycleService- protocol: _Protocol- lease_task: asyncio.Task[None]- stopped: bool = False-- async def stop(self) -> None:- """Shut down as `main` does: owned work first, then the rest."""- if self.stopped:- return- self.stopped = True- await self.ownership.stop()- await self.lease.stop()- await self.connectors.stop_all()- self.lease_task.cancel()- await asyncio.gather(self.lease_task, return_exceptions=True)- await self.bus.stop()---async def _process(- postgres_url: str, session_factory: async_sessionmaker[AsyncSession]-) -> _Process:- lease = process_lease_on(session_factory)- await lease.renew()- bus = SignalBus(- session_factory,- lambda: create_async_engine(postgres_url, poolclass=NullPool),- process_id=lease.process_id,- )- ownership = Ownership(- lease=lease,- session_factory=session_factory,- bus=bus,- store=OwnershipLeaseStore(),- processes=SwitchCoreProcessStore(),- )- protocol = _Protocol()- connectors = ServerSideConnectorLifecycleService(- connector_store=ServerConnectorStore(),- api_key_store=ApiKeyStore(),- protocol=protocol, # type: ignore[arg-type]- session_factory=session_factory,- keyring=KEYRING,- outbound_policy=OutboundPolicy.parse(""),- ownership=ownership,- )- connectors.register_connector_type(KIND, _Connector, _Config)- ConnectorSignals(lifecycle=connectors, bus=bus)- await bus.start()- await asyncio.wait_for(bus.connected.wait(), TIMEOUT)- return _Process(- lease=lease,- ownership=ownership,- bus=bus,- connectors=connectors,- protocol=protocol,- lease_task=asyncio.create_task(lease.run()),- )---def server() -> _Server:- server = _Server()- _Connector.server = server- return server---@dataclass-class _Stored:- connector_id: str- user_id: str---async def stored(session_factory: async_sessionmaker[AsyncSession]) -> _Stored:- """A connector registered before the processes start, with its- registration key, and one agent it registered before."""- async with session_factory() as session:- user = User(name="owner", email="owner@test", role="user", password_hash="x")- session.add(user)- await session.flush()- key = ApiKey(- user_id=user.id,- key_hash=f"hash-{uuid.uuid4().hex}",- encrypted_key=KEYRING.encrypt("registration-token"),- label="server-connector:test",- type="registration",- )- session.add(key)- await session.flush()- connector = ServerConnector(- type=KIND,- display_name="Fake",- connection_config={},- api_key_id=key.id,- status="active",- )- session.add(connector)- await session.flush()- agent = await _make_agent(session, f"helper-{uuid.uuid4().hex[:6]}")- agent.metadata_ = {"server_connector_id": connector.id}- await session.commit()- return _Stored(connector_id=connector.id, user_id=user.id)---async def two(- postgres_url: str,- session_factory: async_sessionmaker[AsyncSession],- server: _Server,- stored: _Stored,-) -> AsyncIterator[tuple[_Process, _Process]]:- """Two processes booted once the connector is stored, as after a deploy."""- processes: list[_Process] = []- try:- for _ in range(2):- process = await _process(postgres_url, session_factory)- processes.append(process)- # As `main` boots: the first balance, then the connectors wanted.- await process.ownership.start()- await process.connectors.start_all()- # The first balance of each cannot see the other; balance once more- # now that both leases are there, as the interval would.- for process in processes:- await process.ownership.balance()- yield processes[0], processes[1]- finally:- for process in processes:- await process.stop()---def _holder(- two: tuple[_Process, _Process], connector_id: str-) -> tuple[_Process, _Process]:- a, b = two- holders = [p for p in (a, b) if p.connectors.holds(connector_id)]- assert len(holders) == 1- return (a, b) if holders[0] is a else (b, a)---async def _eventually(check: Callable[[], bool]) -> None:- async with asyncio.timeout(TIMEOUT):- while not check():- await asyncio.sleep(0.02)---class TestOneProcessRunsIt:- async def test_the_connector_runs_in_the_process_that_holds_it(- self, two: tuple[_Process, _Process], server: _Server, stored: _Stored- ) -> None:- holder, other = _holder(two, stored.connector_id)-- # A connector taken over starts in a task of its own.- await _eventually(lambda: holder.connectors.running_count() == 1)- assert len(server.connected) == 1- assert other.connectors.running_count() == 0- assert other.connectors.expected_count() == 0-- async def test_every_process_names_its_agents(- self, two: tuple[_Process, _Process], stored: _Stored- ) -> None:- for process in two:- names = await process.connectors.get_agent_names(stored.connector_id)- assert len(names) == 1 and names[0].startswith("helper-")-- async def test_when_its_process_stops_the_other_runs_it(- self, two: tuple[_Process, _Process], server: _Server, stored: _Stored- ) -> None:- holder, other = _holder(two, stored.connector_id)-- await _eventually(lambda: holder.connectors.running_count() == 1)- await holder.stop()- await other.ownership.balance()-- assert other.connectors.holds(stored.connector_id)- await _eventually(lambda: other.connectors.running_count() == 1)- assert len(server.connected) == 1---class TestChangesMadeElsewhere:- async def test_one_registered_through_either_process_runs_once(- self, two: tuple[_Process, _Process], server: _Server, stored: _Stored- ) -> None:- a, _ = two-- added = await a.connectors.register(- connector_type=KIND,- display_name="Second",- connection_config={},- user_id=stored.user_id,- )-- await _eventually(lambda: len(server.connected) == 2)- holders = [p for p in two if p.connectors.holds(added.id)]- assert len(holders) == 1- await asyncio.sleep(0.3)- assert len(server.connected) == 2-- async def test_one_removed_through_the_other_process_stops_and_takes_its_agents(- self, two: tuple[_Process, _Process], server: _Server, stored: _Stored- ) -> None:- holder, other = _holder(two, stored.connector_id)- await _eventually(lambda: len(server.connected) == 1)-- await other.connectors.remove(stored.connector_id)-- await _eventually(lambda: server.connected == [])- assert not holder.connectors.holds(stored.connector_id)- assert len(other.protocol.deleted) == 1---class TestASlowServer:- async def test_it_holds_up_no_other_work_while_its_connector_starts(- self,- two: tuple[_Process, _Process],- server: _Server,- stored: _Stored,- monkeypatch: pytest.MonkeyPatch,- ) -> None:- """A connector's start dials its server. One that hangs is taken over- and left starting in its own task: the next balance, and the- hand-over of anything else, go on meanwhile."""- holder, other = _holder(two, stored.connector_id)- await _eventually(lambda: len(server.connected) == 1)- release = asyncio.Event()-- async def hanging_start(self: _Connector) -> None:- await release.wait()- self.server.connected.append(self)-- monkeypatch.setattr(_Connector, "start", hanging_start)- await holder.stop()- async with asyncio.timeout(TIMEOUT):- await other.ownership.balance()- # Balancing again does not wait on the start either.- await other.ownership.balance()- assert other.connectors.holds(stored.connector_id)- assert other.connectors.running_count() == 0-- release.set()- await _eventually(lambda: other.connectors.running_count() == 1)diff --git a/core/tests/switch_core/bridges/agent/server_connectors/test_connector_tenant_binding.py b/core/tests/switch_core/bridges/agent/server_connectors/test_connector_tenant_binding.pydeleted file mode 100644index 91c7060e5..000000000--- a/core/tests/switch_core/bridges/agent/server_connectors/test_connector_tenant_binding.py+++ /dev/null@@ -1,152 +0,0 @@-"""A server-side connector acts as its own row's tenant (CHOO-2623).--A connector runs in-process and calls `AgentCore` directly, so unlike an-external agent there is no bearer token in front of it to resolve a tenant-from. Its own row is the answer, and `ServerSideConnectorLifecycleService.start`-reads it unscoped — from boot with nothing bound, and from an HTTP request-with the caller's tenant bound, which is not necessarily the connector's.--What the runtime then does with it is the point of these tests: the poll loop-is a long-lived task, so it unbinds for its lifetime and binds per pass,-rather than binding once and holding it for days.-"""--from __future__ import annotations--import asyncio-from typing import Any-from unittest.mock import MagicMock--import pytest--from switch_core.bridges.agent.protocol.types import (- IntegrationProfile,-)-from switch_core.bridges.agent.server_connectors.base import DiscoveredAgent-from switch_core.bridges.agent.server_connectors.core import ConnectorCore-from switch_core.tenant_context import current_tenant_id, tenant_scope--CONNECTOR_TENANT = "tenant-connector"-CALLER_TENANT = "tenant-caller"---def _core(protocol: Any, connector: Any) -> ConnectorCore:- return ConnectorCore(- connector_id="connector-1",- connector_tenant_id=CONNECTOR_TENANT,- connector_type="opencode",- connector=connector,- registration_token="tok",- protocol=protocol,- )---class TestThePollLoop:- async def test_it_binds_per_pass_and_holds_nothing_between_them(self) -> None:- seen: list[str | None] = []- between: list[str | None] = []-- class _Protocol:- async def poll_events(self, agent_id: str, timeout: int) -> list[Any]:- seen.append(current_tenant_id())- if len(seen) >= 3:- raise asyncio.CancelledError- return []-- core = _core(_Protocol(), MagicMock())- handle = MagicMock()- handle.agent_id = "agent-1"- handle.agent_name = "agent"-- # Created from a context that has no business deciding how the- # connector acts, exactly as `restart` from a gateway request would.- with tenant_scope(CALLER_TENANT):- task = asyncio.create_task(core._poll_loop(handle))- await task- between.append(current_tenant_id())-- assert seen == [CONNECTOR_TENANT] * 3, (- "a poll ran under something other than the connector's own tenant"- )- assert between == [CALLER_TENANT], (- "the loop's unbinding escaped it and cleared its creator's context"- )-- async def test_a_failing_pass_leaves_nothing_bound_for_the_next(self) -> None:- """The loop logs and sleeps past an error. The tenant must not survive- the exception into the retry, or a pass that raised would decide what- the next one reads."""- seen: list[str | None] = []- inside_sleep: list[str | None] = []- real_sleep = asyncio.sleep-- async def _sleep(delay: float) -> None:- inside_sleep.append(current_tenant_id())- await real_sleep(0)-- class _Protocol:- async def poll_events(self, agent_id: str, timeout: int) -> list[Any]:- seen.append(current_tenant_id())- if len(seen) >= 2:- raise asyncio.CancelledError- raise RuntimeError("boom")-- core = _core(_Protocol(), MagicMock())- handle = MagicMock()- handle.agent_id = "agent-1"- handle.agent_name = "agent"-- with pytest.MonkeyPatch.context() as patch:- patch.setattr(- "switch_core.bridges.agent.server_connectors.core.asyncio.sleep",- _sleep,- )- await core._poll_loop(handle)-- assert seen == [CONNECTOR_TENANT, CONNECTOR_TENANT]- assert inside_sleep == [None], (- "the failed pass's tenant was still bound over the backoff"- )---async def test_registering_an_agent_binds_the_connectors_tenant() -> None:- """`register_agent_with_token` re-derives the tenant from the token for- the write itself, but everything else `register_agent` touches — the- client, the identity fan-out — runs under whatever is bound here, and- `start` is reached from boot with nothing bound."""- seen: list[str | None] = []-- class _Protocol:- async def register_agent_with_token(self, **kwargs: Any) -> Any:- seen.append(current_tenant_id())- return MagicMock(agent_id="agent-1")-- class _Connector:- async def start(self) -> None:- return None-- async def stop(self) -> None:- return None-- async def discover_agents(self) -> list[DiscoveredAgent]:- return [- DiscoveredAgent(- name="worker",- description="d",- integration_profile=IntegrationProfile(- connection_model="session_passive",- message_exchange=True,- pre_invocation_mediation=[],- post_invocation_mediation=[],- event_reporting=[],- ),- tools=[],- models=[],- )- ]-- core = _core(_Protocol(), _Connector())- await core.start()- await core.stop()-- assert seen == [CONNECTOR_TENANT]diff --git a/core/tests/switch_core/bridges/agent/server_connectors/test_lifecycle_remove_tenant.py b/core/tests/switch_core/bridges/agent/server_connectors/test_lifecycle_remove_tenant.pydeleted file mode 100644index 244c3e154..000000000--- a/core/tests/switch_core/bridges/agent/server_connectors/test_lifecycle_remove_tenant.py+++ /dev/null@@ -1,204 +0,0 @@-"""Removing a server-side connector is scoped, and says so (CHOO-2623).--`remove()` was the one lifecycle verb the tenant rework did not reach. It-opened a raw session — which inherits the requesting operator's tenant — and-handed it to a store `delete` that returned quietly when it matched nothing.-Under the policies those two make a specific, silent failure: a tenant-A-operator deleting a tenant-B connector matched zero rows and the service-logged "Removed server-side connector <id>".--Two halves, both tested here against the role the policies actually apply to-(`rls_harness.restricted` — the plain fixture connects as the tables' owner-and would pass whether or not a single policy existed):--- the delete refuses to report a removal it did not perform;-- and it refuses *before* the teardown, because `_cores` is a process-wide- registry holding every tenant's connectors. Tearing down first meant a- caller from the wrong tenant stopped another tenant's connector and deleted- its agents, and only then failed to delete the row.-"""--from __future__ import annotations--import logging--import pytest-from sqlalchemy import insert, select-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker--from switch_core.bridges.agent.server_connectors.lifecycle import (- ServerSideConnectorLifecycleService,-)-from switch_core.db.models import (- TENANT_ZERO_ID,- ApiKey,- ServerConnector,- Tenant,- User,-)-from switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.db.stores.server_connector_store import ServerConnectorStore-from switch_core.keys import Keyring-from switch_core.outbound import OutboundPolicy-from switch_core.tenant_context import tenant_scope-from tests.ownership import SoleOwner--pytestmark = pytest.mark.no_ambient_tenant--TENANT_B = "11111111-1111-1111-1111-111111111111"---class _SpyCore:- """Stands in for a running `ConnectorCore` and records being torn down."""-- def __init__(self) -> None:- self.deleted_agents = False- self.stopped = False-- async def delete_agents(self) -> None:- self.deleted_agents = True-- async def stop(self) -> None:- self.stopped = True---async def _seed_connector(- owner_factory: async_sessionmaker[AsyncSession], tenant_id: str-) -> str:- """A connector in `tenant_id`, written as the owner so the fixture itself- needs no tenant of its own."""- async with owner_factory() as session:- if tenant_id != TENANT_ZERO_ID:- session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))- await session.flush()- user = User(name=tenant_id, email=f"{tenant_id}@x.test", role="user")- session.add(user)- await session.flush()- await session.execute(- insert(ApiKey.__table__).values(- id=f"key-{tenant_id}",- tenant_id=tenant_id,- user_id=user.id,- key_hash=f"hash-{tenant_id}",- encrypted_key="enc",- label="server-connector:test",- type="registration",- )- )- await session.execute(- insert(ServerConnector.__table__).values(- id=f"connector-{tenant_id}",- tenant_id=tenant_id,- type="test-type",- display_name="Test Connector",- connection_config={},- api_key_id=f"key-{tenant_id}",- status="active",- )- )- await session.commit()- return f"connector-{tenant_id}"---def _service(- session_factory: async_sessionmaker[AsyncSession],-) -> ServerSideConnectorLifecycleService:- return ServerSideConnectorLifecycleService(- connector_store=ServerConnectorStore(),- api_key_store=ApiKeyStore(),- protocol=None, # type: ignore[arg-type]- session_factory=session_factory,- keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None),- outbound_policy=OutboundPolicy.parse(""),- ownership=SoleOwner(),- )---async def _still_there(- owner_factory: async_sessionmaker[AsyncSession], connector_id: str-) -> bool:- async with owner_factory() as session:- row = (- await session.execute(- select(ServerConnector.id).where(ServerConnector.id == connector_id)- )- ).first()- return row is not None---class TestRemovingAnotherTenantsConnector:- async def test_it_raises_rather_than_reporting_a_removal(- self, rls_harness, caplog: pytest.LogCaptureFixture- ) -> None:- connector_id = await _seed_connector(rls_harness.owner, TENANT_B)- service = _service(rls_harness.restricted)-- with caplog.at_level(logging.INFO, logger=service.__module__):- with tenant_scope(TENANT_ZERO_ID):- with pytest.raises(ValueError, match="Connector not found"):- await service.remove(connector_id)-- assert await _still_there(rls_harness.owner, connector_id)- assert not any(- "Removed server-side connector" in r.getMessage() for r in caplog.records- ), "reported a removal that did not happen"-- async def test_it_does_not_tear_the_connector_down_first(self, rls_harness) -> None:- """`_cores` spans tenants, so an authorization failure discovered- after the teardown is a cross-tenant outage with a 500 attached."""- connector_id = await _seed_connector(rls_harness.owner, TENANT_B)- service = _service(rls_harness.restricted)- core = _SpyCore()- service._cores[connector_id] = core # type: ignore[assignment]-- with tenant_scope(TENANT_ZERO_ID):- with pytest.raises(ValueError):- await service.remove(connector_id)-- assert not core.deleted_agents- assert not core.stopped- assert service._cores[connector_id] is core---class TestRemovingYourOwn:- async def test_it_deletes_the_row_and_tears_the_core_down(- self, rls_harness- ) -> None:- connector_id = await _seed_connector(rls_harness.owner, TENANT_B)- service = _service(rls_harness.restricted)- core = _SpyCore()- service._cores[connector_id] = core # type: ignore[assignment]-- with tenant_scope(TENANT_B):- await service.remove(connector_id)-- assert not await _still_there(rls_harness.owner, connector_id)- assert core.deleted_agents- assert core.stopped- assert connector_id not in service._cores-- async def test_removing_it_twice_is_an_error_not_a_shrug(self, rls_harness) -> None:- """The second call has nothing to delete, and saying so is the whole- point: "matched nothing" is also what a cross-tenant delete looks- like, so it cannot be treated as success anywhere."""- connector_id = await _seed_connector(rls_harness.owner, TENANT_B)- service = _service(rls_harness.restricted)-- with tenant_scope(TENANT_B):- await service.remove(connector_id)- with pytest.raises(ValueError, match="Connector not found"):- await service.remove(connector_id)---class TestTheStore:- async def test_delete_raises_on_a_row_this_session_cannot_see(- self, rls_harness- ) -> None:- connector_id = await _seed_connector(rls_harness.owner, TENANT_B)-- with tenant_scope(TENANT_ZERO_ID):- async with rls_harness.restricted() as session:- with pytest.raises(ValueError, match="Connector not found"):- await ServerConnectorStore().delete(session, connector_id)-- assert await _still_there(rls_harness.owner, connector_id)diff --git a/core/tests/switch_core/db/stores/test_agent_session_store.py b/core/tests/switch_core/db/stores/test_agent_session_store.pyindex 3274b3b64..25bde2cea 100644--- a/core/tests/switch_core/db/stores/test_agent_session_store.py+++ b/core/tests/switch_core/db/stores/test_agent_session_store.py@@ -5,9 +5,6 @@ from datetime import UTC, datetime, timedeltafrom sqlalchemy import updatefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.server_connectors.core import (- CONNECTOR_POLL_TIMEOUT_SECONDS,-)from switch_core.db.models import (Agent,AgentSession,@@ -18,6 +15,10 @@ from switch_core.db.models import ()from switch_core.db.stores.agent_session_store import AgentSessionStore+# The idle long-poll `ALWAYS_ON_TTL` is sized for: an always_on agent's+# heartbeat is as old as this between two polls with nothing to deliver.+_IDLE_LONG_POLL = timedelta(seconds=30)+async def _make_agent(session: AsyncSession, name: str) -> Agent:"""Minimal User → ApiKey → Client → Agent chain (agent_sessions FK)."""@@ -86,28 +87,17 @@ async def _age_room_heartbeat(class TestLiveness:- def test_ttl_exceeds_connector_poll_cadence(self) -> None:- """Regression guard for the always_on flapping bug: the liveness- window must stay above the connector's long-poll timeout, otherwise a- healthy agent reads "disconnected" between heartbeats. Keep generous- headroom for event-handling time on top of the idle cadence."""- assert AgentSessionStore.ALWAYS_ON_TTL > timedelta(- seconds=CONNECTOR_POLL_TIMEOUT_SECONDS- )-async def test_heartbeat_at_idle_poll_cadence_stays_live(self, session_factory: async_sessionmaker[AsyncSession]) -> None:- """A heartbeat as old as the idle connector poll cadence (30s) must- still count as live — this is the false-negative the bug produced when+ """A heartbeat as old as the idle long-poll (30s) must still count as+ live — this is the false-negative the bug produced whenTTL (18s) was below the 30s cadence."""store = AgentSessionStore()async with session_factory() as session:agent = await _make_agent(session, "always-on-idle")await store.touch_heartbeat(session, agent.id, None)- await _age_heartbeat(- session, agent.id, timedelta(seconds=CONNECTOR_POLL_TIMEOUT_SECONDS)- )+ await _age_heartbeat(session, agent.id, _IDLE_LONG_POLL)await session.commit()live = await store.get_live_agent_ids(session, [agent.id], None)diff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.pyindex 8acae20bd..96f8f0951 100644--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py@@ -72,8 +72,7 @@ _ALLOWED_MODULES = {# policy, the same shape as service-token upkeep above."switch_core.gateway.connector_apps",# The runtime-state sweep reads every tenant's stale rows, one tenant at a- # time; `register_agent_with_token` resolves a registration credential by- # its globally unique hash, which is the read that produces a tenant.+ # time."switch_core.bridges.agent.protocol.agent_core",# Each process keeps a copy of every other process's agent connections, so# its periodic pass over the recorded rows reads every tenant's: enumerate@@ -109,11 +108,10 @@ _ALLOWED_MODULES = {# `tenants_of_cloud_machine`, and each one's row on the machine is then# read with that workspace bound."switch_core.db.stores.hosted_machine_store",- # Enumerating tenants at boot, and starting one bridge or one connector by- # id from a context bound to somebody else's tenant.+ # Enumerating tenants at boot, and starting one bridge by id from a+ # context bound to somebody else's tenant."switch_core.clients.client_lifecycle_service","switch_core.bridges.collaboration.lifecycle_service",- "switch_core.bridges.agent.server_connectors.lifecycle",# `_room_tenant`'s fallback: which tenant is this room in, asked when the# answer is not already cached alongside the channel mapping."switch_core.bridges.collaboration.collaboration_core",@@ -172,7 +170,6 @@ _RAW_SESSION_FACTORY_MODULES = {"switch_core.bridges.agent.commands","switch_core.bridges.collaboration.collaboration_core","switch_core.bridges.collaboration.lifecycle_service",- "switch_core.bridges.agent.server_connectors.lifecycle","switch_core.delivery.recipient","switch_core.clients.command_consumer","switch_core.clients.client_lifecycle_service",diff --git a/core/tests/switch_core/gateway/test_app_route_mounting.py b/core/tests/switch_core/gateway/test_app_route_mounting.pyindex 17567ceba..f9c7a3ed3 100644--- a/core/tests/switch_core/gateway/test_app_route_mounting.py+++ b/core/tests/switch_core/gateway/test_app_route_mounting.py@@ -26,8 +26,6 @@ def _app(**overrides: object) -> object:bridge_store=MagicMock(),client_lifecycle=MagicMock(),collab_lifecycle=MagicMock(),- connector_lifecycle=MagicMock(),- connector_store=MagicMock(),event_buffer=MagicMock(),session_factory=MagicMock(),user_store=MagicMock(),diff --git a/core/tests/switch_core/gateway/test_connectors.py b/core/tests/switch_core/gateway/test_connectors.pydeleted file mode 100644index a1b19b58d..000000000--- a/core/tests/switch_core/gateway/test_connectors.py+++ /dev/null@@ -1,160 +0,0 @@-from __future__ import annotations--import pytest-from fastapi import HTTPException-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker--from switch_core.db.models import ApiKey, ServerConnector, User-from switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.db.stores.server_connector_store import ServerConnectorStore-from switch_core.db.stores.user_store import UserStore-from switch_core.gateway.connectors import delete_connector--_USER_STORE = UserStore()---async def _is_admin(session: AsyncSession, user: User) -> bool:- """The bit `get_tenant_is_admin` hands the route, resolved the same way."""- return await _USER_STORE.administers(session, user)---class _StubLifecycle:- """Records remove() calls so we can assert whether deletion happened."""-- def __init__(self) -> None:- self.removed: list[str] = []-- async def remove(self, connector_id: str) -> None:- self.removed.append(connector_id)---async def _make_user(session: AsyncSession, *, role: str) -> User:- user = User(name=f"{role}-user", email=f"{role}-{_uuid_suffix()}@x.test", role=role)- session.add(user)- await session.flush()- return user---_counter = 0---def _uuid_suffix() -> str:- global _counter- _counter += 1- return str(_counter)---async def _make_connector(session: AsyncSession, *, owner: User) -> ServerConnector:- key = ApiKey(- user_id=owner.id,- key_hash=f"hash-{_uuid_suffix()}",- encrypted_key="enc",- label="server-connector:test",- type="registration",- )- session.add(key)- await session.flush()-- connector = ServerConnector(- type="test-type",- display_name="Test Connector",- connection_config={},- api_key_id=key.id,- status="active",- )- session.add(connector)- await session.flush()- return connector---class TestDeleteConnectorAuthorization:- async def test_non_owner_non_admin_is_forbidden(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- owner = await _make_user(session, role="user")- other = await _make_user(session, role="user")- connector = await _make_connector(session, owner=owner)- await session.commit()-- lifecycle = _StubLifecycle()- with pytest.raises(HTTPException) as exc:- await delete_connector(- connector_id=connector.id,- session=session,- connector_store=ServerConnectorStore(),- api_key_store=ApiKeyStore(),- connector_lifecycle=lifecycle, # type: ignore[arg-type]- user=other,- is_admin=await _is_admin(session, other),- )-- assert exc.value.status_code == 403- assert lifecycle.removed == []-- async def test_owner_can_delete(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- owner = await _make_user(session, role="user")- connector = await _make_connector(session, owner=owner)- await session.commit()-- lifecycle = _StubLifecycle()- result = await delete_connector(- connector_id=connector.id,- session=session,- connector_store=ServerConnectorStore(),- api_key_store=ApiKeyStore(),- connector_lifecycle=lifecycle, # type: ignore[arg-type]- user=owner,- is_admin=await _is_admin(session, owner),- )-- assert result == {"ok": True}- assert lifecycle.removed == [connector.id]-- async def test_admin_can_delete_others_connector(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- owner = await _make_user(session, role="user")- admin = await _make_user(session, role="admin")- connector = await _make_connector(session, owner=owner)- await session.commit()-- lifecycle = _StubLifecycle()- result = await delete_connector(- connector_id=connector.id,- session=session,- connector_store=ServerConnectorStore(),- api_key_store=ApiKeyStore(),- connector_lifecycle=lifecycle, # type: ignore[arg-type]- user=admin,- is_admin=await _is_admin(session, admin),- )-- assert result == {"ok": True}- assert lifecycle.removed == [connector.id]-- async def test_missing_connector_is_not_found(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- user = await _make_user(session, role="user")- await session.commit()-- lifecycle = _StubLifecycle()- with pytest.raises(HTTPException) as exc:- await delete_connector(- connector_id="does-not-exist",- session=session,- connector_store=ServerConnectorStore(),- api_key_store=ApiKeyStore(),- connector_lifecycle=lifecycle, # type: ignore[arg-type]- user=user,- is_admin=await _is_admin(session, user),- )-- assert exc.value.status_code == 404- assert lifecycle.removed == []diff --git a/core/tests/switch_core/observability/test_bootstrap.py b/core/tests/switch_core/observability/test_bootstrap.pyindex 4ad9a7e15..bcaac15e4 100644--- a/core/tests/switch_core/observability/test_bootstrap.py+++ b/core/tests/switch_core/observability/test_bootstrap.py@@ -77,8 +77,6 @@ def _probes(**overrides) -> RuntimeProbes:bridges_running_by_platform=lambda: {"slack": 1, "mattermost": 1},bridges_configured=lambda: 2,consumers_running=lambda: 5,- connectors_running=lambda: 2,- connectors_configured=lambda: 2,agents_connected=lambda: {("websocket", "agent-runtime"): 2,("websocket", "unknown"): 1,@@ -185,7 +183,6 @@ async def test_an_endpoint_installs_the_registry_and_reports_state(monkeypatch):("websocket", "unknown"): 1.0,}assert values["switch.consumers.running"] == 5.0- assert values["switch.connectors.running"] == 2.0assert values["switch.db.pool.in_use"] == 4.0assert values["switch.db.pool.size"] == 30.0diff --git a/core/tests/switch_core/observability/test_connection_metrics.py b/core/tests/switch_core/observability/test_connection_metrics.pyindex 8b79389a7..5f11b48bb 100644--- a/core/tests/switch_core/observability/test_connection_metrics.py+++ b/core/tests/switch_core/observability/test_connection_metrics.py@@ -163,8 +163,6 @@ def _probes(agents_connected: Any) -> RuntimeProbes:bridges_running_by_platform=lambda: {},bridges_configured=lambda: 0,consumers_running=lambda: 0,- connectors_running=lambda: 0,- connectors_configured=lambda: 0,agents_connected=agents_connected,pool_stats=lambda: None,room_cache_stats=lambda: RoomCacheStats(bytes=0, rooms=0, rows=0),diff --git a/core/tests/switch_core/observability/test_health.py b/core/tests/switch_core/observability/test_health.pyindex bd5918ada..80f6914ea 100644--- a/core/tests/switch_core/observability/test_health.py+++ b/core/tests/switch_core/observability/test_health.py@@ -9,7 +9,6 @@ from switch_core.observability.health import (HealthMonitor,agent_event_listener_check,bridges_check,- connectors_check,message_listener_check,session_activity_listener_check,signal_bus_check,@@ -195,25 +194,6 @@ async def test_run_forever_keeps_going_after_a_broken_refresh(monkeypatch):assert monitor.current().ready is True-async def test_connectors_check_counts_the_missing_ones():- """They start fire-and-forget, so a failure is otherwise one boot-log line."""- check = connectors_check(running=lambda: 1, configured=lambda: 3)- outcome = await check.probe()-- assert outcome.healthy is False- assert "2 of 3" in outcome.detail- # The rest of Switch serves fine without one, and emptying the Service- # would not bring it back.- assert check.gates_readiness is False---async def test_connectors_check_is_healthy_when_none_are_configured():- check = connectors_check(running=lambda: 0, configured=lambda: 0)- assert (await check.probe()).healthy is True--@pytest.mark.asyncioasync def test_session_activity_listener_check_follows_the_connection():connected = [True]diff --git a/core/tests/switch_core/session_activity/test_publisher.py b/core/tests/switch_core/session_activity/test_publisher.pyindex d02697b67..45cf07091 100644--- a/core/tests/switch_core/session_activity/test_publisher.py+++ b/core/tests/switch_core/session_activity/test_publisher.py@@ -672,7 +672,15 @@ async def test_a_restart_redraws_running_turns_but_not_ones_already_shown_ended(try:await _turn(service, bridged.room_id, "running", 1, turn_id="turn-1")await _turn(service, bridged.room_id, "running", 1, turn_id="turn-2")- await platform.wait_until(lambda: len(_turns(platform)) == 2)+ # Turns, not draws: turn-1 drawn before turn-2 started is redrawn to+ # name turn-2 in its stop control, a third draw that can land in the+ # same poll as the second.+ await platform.wait_until(+ lambda: (+ {d.content.turn.turn_id for d in _turns(platform)}+ == {"turn-1", "turn-2"}+ )+ )await _turn(service, bridged.room_id, "completed", 2, turn_id="turn-1")await platform.wait_until(lambda: any(d.content.turn.status == "completed" for d in _turns(platform))diff --git a/core/tests/switch_core/test_main_release.py b/core/tests/switch_core/test_main_release.pyindex b5d32da77..13a61bc49 100644--- a/core/tests/switch_core/test_main_release.py+++ b/core/tests/switch_core/test_main_release.py@@ -1,8 +1,7 @@"""A process shutting down hands over the work it owns before its lease goes.The other processes may take over a process's owned work (a client's-consumer, a bridge's connection, a server-side connector) as soon as its-lease reads as stopped. So the lease is marked stopped only after that work+consumer, a bridge's connection) as soon as its lease reads as stopped. So the lease is marked stopped only after that workhas stopped here; if it cannot be stopped, the lease is left to lapse on itsown, which gives the work time to end before anyone else starts it."""diff --git a/core/tests/switch_core/test_main_teams_app.py b/core/tests/switch_core/test_main_teams_app.pyindex bb83befa0..753a88f91 100644--- a/core/tests/switch_core/test_main_teams_app.py+++ b/core/tests/switch_core/test_main_teams_app.py@@ -111,7 +111,6 @@ async def test_the_apps_client_is_closed_only_after_the_bridges_stop(controllers=_Controllers(), # type: ignore[arg-type]client_lifecycle=_Stoppable("clients"), # type: ignore[arg-type]collab_lifecycle=_Lifecycle(calls), # type: ignore[arg-type]- connector_lifecycle=_Stoppable("connectors"), # type: ignore[arg-type]provisioning=_Stoppable("provisioning"), # type: ignore[arg-type]discord_gateway=None,teams_app=_TeamsApp(), # type: ignore[arg-type]@@ -199,7 +198,6 @@ async def test_shutdown_drains_before_it_closes_anything(controllers=_Controllers(), # type: ignore[arg-type]client_lifecycle=_Stoppable("clients"), # type: ignore[arg-type]collab_lifecycle=_Lifecycle(calls), # type: ignore[arg-type]- connector_lifecycle=_Stoppable("connectors"), # type: ignore[arg-type]provisioning=_Stoppable("provisioning"), # type: ignore[arg-type]discord_gateway=None,teams_app=None,diff --git a/core/tests/switch_core/test_outbound_fetch_sites.py b/core/tests/switch_core/test_outbound_fetch_sites.pyindex a2c3f9b72..e6000dee2 100644--- a/core/tests/switch_core/test_outbound_fetch_sites.py+++ b/core/tests/switch_core/test_outbound_fetch_sites.py@@ -1,7 +1,6 @@"""Each place Switch fetches a URL a tenant or agent chose goes through the-outbound policy: bridge and connector configs when stored and started, the-Mattermost driver's redirects, the Mattermost icon fetch, and Slack file-downloads."""+outbound policy: bridge configs when stored and started, the Mattermost+driver's redirects, the Mattermost icon fetch, and Slack file downloads."""from __future__ import annotations@@ -18,13 +17,6 @@ from aiohttp import webfrom mattermostdriver import Driverfrom mattermostdriver.exceptions import ResourceNotFound-from switch_core.bridges.agent.server_connectors.lifecycle import (- ServerSideConnectorLifecycleService,-)-from switch_core.bridges.agent.server_connectors.opencode.connector import (- OpenCodeConnectionConfig,- OpenCodeConnector,-)from switch_core.bridges.collaboration import mattermostfrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,@@ -45,7 +37,6 @@ from switch_core.bridges.collaboration.slack.adapter import (from switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.room_store import RoomStore-from switch_core.keys import Keyringfrom switch_core.outbound import OutboundPolicy, OutboundURLRefusedfrom tests.ownership import SoleOwner@@ -140,33 +131,6 @@ class TestBridgeConfigs:)-class TestConnectorConfigs:- async def test_registering_a_private_server_url_is_refused(self) -> None:- service = ServerSideConnectorLifecycleService(- connector_store=MagicMock(),- api_key_store=MagicMock(),- protocol=MagicMock(),- session_factory=MagicMock(),- keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None),- outbound_policy=OutboundPolicy.parse(""),- ownership=SoleOwner(),- )- service.register_connector_type(- "opencode", OpenCodeConnector, OpenCodeConnectionConfig- )- with pytest.raises(OutboundURLRefused):- await service.register(- connector_type="opencode",- display_name="Internal",- connection_config={- "server_url": "http://10.0.0.5:4096",- "username": "u",- "password": "p",- },- user_id="user-1",- )--class _Handler(BaseHTTPRequestHandler):def _reply(self, status: int, body: dict[str, Any], **headers: str) -> None:payload = json.dumps(body).encode()diff --git a/core/tests/switch_core/transport/test_postgres_transport.py b/core/tests/switch_core/transport/test_postgres_transport.pyindex dac846099..b7860958d 100644--- a/core/tests/switch_core/transport/test_postgres_transport.py+++ b/core/tests/switch_core/transport/test_postgres_transport.py@@ -135,11 +135,14 @@ async def _watched_room(transport: PostgresTransport) -> str:`receive_forever` resolves memberships against the database before itsubscribes, so a test that sends immediately after starting it would race- the subscription rather than test anything.+ the subscription rather than test anything. A room enters `_watching` when+ it is claimed, before those reads, and `_cursors` only once it is+ subscribed, so the cursor is what this waits for."""for _ in range(200):- if transport._watching:- return next(iter(transport._watching))+ for room_id in transport._watching:+ if room_id in transport._cursors:+ return room_idawait asyncio.sleep(0.01)raise AssertionError("the transport never started watching a room")diff --git a/core/tests/synthetic/generate_synthetic_db.py b/core/tests/synthetic/generate_synthetic_db.pyindex 851f14022..a14785780 100644--- a/core/tests/synthetic/generate_synthetic_db.py+++ b/core/tests/synthetic/generate_synthetic_db.py@@ -116,13 +116,11 @@ PACKAGE_DOCUMENTS = 20# Tables that were empty (or a single bootstrap row) in the measured# production shape. Kept at that order of magnitude rather than invented,# and held fixed regardless of --scale-factor: a bigger deployment does not-# have more feature-flag rows or more "the one active package" rows, these-# are singleton config tables rather than volume tables.+# have more "the one active package" rows, these are singleton config tables+# rather than volume tables.PACKAGES = 1ROOM_PACKAGES = 1ROOM_DOCUMENTS = 1-SERVER_CONNECTORS = 1-FEATURE_FLAGS = 1_WORDS = ["lorem",@@ -324,8 +322,6 @@ async def generate(dsn: str, scale: float) -> None:packages_n = PACKAGESroom_packages_n = ROOM_PACKAGESroom_documents_n = ROOM_DOCUMENTS- server_connectors_n = SERVER_CONNECTORS- feature_flags_n = FEATURE_FLAGSpool = IdPool()t0 = time.monotonic()@@ -1025,29 +1021,6 @@ async def generate(dsn: str, scale: float) -> None:[(room_ids[0], document_ids[0])] if room_documents_n else [],)- # ── server_connectors / feature_flags ────────────────────────────- await _copy(- conn,- "server_connectors",- ["id", "type", "display_name", "api_key_id", "status"],- [- (- _rand_id("connector", i),- "resource",- f"Synthetic Connector {i}",- api_key_ids[0],- "active",- )- for i in range(server_connectors_n)- ],- )- await _copy(- conn,- "feature_flags",- ["key", "enabled"],- [("synthetic-flag", True)] if feature_flags_n else [],- )-elapsed = time.monotonic() - t0print(f"Generated synthetic database in {elapsed:.1f}s.")finally:diff --git a/deploy/observability/README.md b/deploy/observability/README.mdindex 65690f766..d974a8060 100644--- a/deploy/observability/README.md+++ b/deploy/observability/README.md@@ -125,6 +125,6 @@ own counters show one total. Pick the deployment with `env` and `service`. Itneeds a build that tags points with `pod_name`; earlier builds show oneunsplit series.-`dashboard.json` sums per-pod gauges (consumers, connectors, pool, memory) so+`dashboard.json` sums per-pod gauges (consumers, pool, memory) soits totals stay totals with several pods, and the pool-saturation monitoralerts per pod, since one pod can exhaust its pool while the others idle.diff --git a/deploy/observability/dashboard.json b/deploy/observability/dashboard.jsonindex 4f68f5e04..5c0997923 100644--- a/deploy/observability/dashboard.json+++ b/deploy/observability/dashboard.json@@ -661,26 +661,7 @@"layout": {"x": 0,"y": 47,- "width": 6,- "height": 4- }- },- {- "definition": {- "type": "timeseries",- "title": "Server-side connectors running",- "show_legend": true,- "requests": [- {- "q": "sum:switch.connectors.running{$env,$service}",- "display_type": "line"- }- ]- },- "layout": {- "x": 6,- "y": 47,- "width": 6,+ "width": 12,"height": 4}},diff --git a/deploy/observability/monitors.json b/deploy/observability/monitors.jsonindex 972fcef0e..779c56c0a 100644--- a/deploy/observability/monitors.json+++ b/deploy/observability/monitors.json@@ -261,24 +261,6 @@"include_tags": true}},- {- "name": "[Switch] a server-side connector is not running",- "type": "metric alert",- "query": "min(last_10m):min:switch.health.check{service:switch-core,check:connectors} < 1",- "message": "A server-side connector this deployment is configured to run is not running.\n\nThe agents it hosts are unreachable \u2014 they will not answer in any room and nothing else reports it, because connectors are started fire-and-forget at boot and each failure is logged and stepped over.\n\nThe boot log names which one and why. It does not retry, so it needs restarting rather than waiting.\n\n@REPLACE-WITH-NOTIFICATION-HANDLE",- "tags": [- "service:switch-core",- "team:switch"- ],- "options": {- "notify_no_data": false,- "renotify_interval": 120,- "thresholds": {- "critical": 1- },- "include_tags": true- }- },{"name": "[Switch] the database pool is refusing connections","type": "metric alert",diff --git a/deploy/observability/multi-pod-dashboard.json b/deploy/observability/multi-pod-dashboard.jsonindex 1870b6cf4..bfa670b8f 100644--- a/deploy/observability/multi-pod-dashboard.json+++ b/deploy/observability/multi-pod-dashboard.json@@ -106,7 +106,7 @@{"definition": {"type": "timeseries",- "title": "Consumers and connectors running, by pod",+ "title": "Consumers running, by pod","show_legend": true,"legend_layout": "auto","requests": [@@ -116,11 +116,6 @@"data_source": "metrics","name": "q0","query": "sum:switch.consumers.running{$env,$service,$pod_name} by {pod_name}"- },- {- "data_source": "metrics",- "name": "q1",- "query": "sum:switch.connectors.running{$env,$service,$pod_name} by {pod_name}"}],"response_format": "timeseries",@@ -128,9 +123,6 @@"formulas": [{"formula": "q0"- },- {- "formula": "q1"}]}diff --git a/deploy/remote/helm/switch/README.md b/deploy/remote/helm/switch/README.mdindex a8cdebafe..74d4d1f92 100644--- a/deploy/remote/helm/switch/README.md+++ b/deploy/remote/helm/switch/README.md@@ -160,9 +160,8 @@ example), leave `tls.enabled` false and annotate.**switch-core can run more than one replica.** `switchCore.replicaCount` setshow many. Shared state lives in the database: replicas signal each other through-Postgres notifications, and each bridge's listener and outbound relay, each-server connector and each command reader is owned by one replica at a time-through a lease. That includes the shared Discord gateway connection of the+Postgres notifications, and each bridge's listener and outbound relay and each+command reader is owned by one replica at a time through a lease. That includes the shared Discord gateway connection of thedistributed Discord app, whose Discord bridges run beside it on the samereplica, and each Teams bridge's Graph subscriptions, which only the replicaholding the bridge makes and renews. Any replica can hold any client'sdiff --git a/deploy/remote/helm/switch/templates/switch-core/deployment.yaml b/deploy/remote/helm/switch/templates/switch-core/deployment.yamlindex 7ffcd8f98..f07f6d4e7 100644--- a/deploy/remote/helm/switch/templates/switch-core/deployment.yaml+++ b/deploy/remote/helm/switch/templates/switch-core/deployment.yaml@@ -18,7 +18,7 @@ metadata:{{- include "switch.selectorLabels" (dict "Release" .Release "component" "switch-core") | nindent 4 }}spec:replicas: {{ .Values.switchCore.replicaCount }}- # Each bridge, connector and reader is held by one pod at a time through a+ # Each bridge and reader is held by one pod at a time through a# lease in Postgres, so two pods side by side during a roll do not both run# it: the old pod hands its work over on SIGTERM, and the new one takes it# over. One replica still uses Recreate, because switch-core sizes itsdiff --git a/deploy/remote/helm/switch/templates/switch-core/pdb.yaml b/deploy/remote/helm/switch/templates/switch-core/pdb.yamlindex 1a22aa7b2..1550381d9 100644--- a/deploy/remote/helm/switch/templates/switch-core/pdb.yaml+++ b/deploy/remote/helm/switch/templates/switch-core/pdb.yaml@@ -1,7 +1,7 @@{{- $pdb := .Values.switchCore.podDisruptionBudget }}{{- if and (gt (int .Values.switchCore.replicaCount) 1) $pdb.enabled }}# Keeps a node drain or cluster upgrade from evicting every switch-core pod at-# once. A pod evicted here hands its bridges, connectors and readers to the+# once. A pod evicted here hands its bridges and readers to the# pods still running, the same as on a roll.apiVersion: policy/v1kind: PodDisruptionBudgetdiff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex 51ea65516..852a8d46f 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -427,7 +427,7 @@ switchCore:# The package's SHA-256, 64 lowercase hex characters.sha256: ""# Private hosts switch-core may reach at a URL a tenant or agent supplied —- # a Mattermost server, an OpenCode server, an agent icon. Hostnames or CIDRs.+ # a Mattermost server, an agent icon. Hostnames or CIDRs.# Anything else that is not a public address is refused, and link-local and# cloud metadata addresses are refused even when listed. The bundled# Mattermost (mattermost.enabled) is added automatically.@@ -664,13 +664,13 @@ switchCore:# default.port: 8081# How many switch-core pods to run. Every pod serves the API and holds client- # connections. Each bridge's listener and outbound relay, each server- # connector and each command reader runs on one pod at a time, through- # leases in the database, and each message is routed to its agents as it is- # written, so any pod can take any request. So does the deployment's shared- # Discord gateway connection (the distributed Discord app), with its Discord- # bridges on the same pod, and each Teams bridge's Graph subscriptions, made- # and renewed by the pod that holds the bridge.+ # connections. Each bridge's listener and outbound relay and each command+ # reader runs on one pod at a time, through leases in the database, and+ # each message is routed to its agents as it is written, so any pod can take+ # any request. So does the deployment's shared Discord gateway connection+ # (the distributed Discord app), with its Discord bridges on the same pod,+ # and each Teams bridge's Graph subscriptions, made and renewed by the pod+ # that holds the bridge.## One replica is replaced (Recreate): the old pod stops before the new one# starts, so an upgrade has a short outage. More than one rolls (see@@ -701,7 +701,7 @@ switchCore:topologyKey: kubernetes.io/hostnamewhenUnsatisfiable: ScheduleAnyway# How long the kubelet waits after SIGTERM before killing the pod. On SIGTERM- # switch-core hands the bridges, connectors and readers it owns to the other+ # switch-core hands the bridges and readers it owns to the other# pods (up to 10s), releases its lease (up to 1s), keeps serving for 5s while# the Service stops routing to it (only with more than one replica), stops# the bridges it still runs (giving one still starting up to 5s) and givesdiff --git a/docs/design/service-connections-v1.md b/docs/design/service-connections-v1.mdindex b295465a7..2f53df812 100644--- a/docs/design/service-connections-v1.md+++ b/docs/design/service-connections-v1.md@@ -10,9 +10,9 @@ foundation: see [`service-connections-v2.md`](service-connections-v2.md).The target contract is `controller-contract-v1.md`; its §5 is amended alongsidethis spec, and the deviations are listed below.-"Connector" already means something else in Core (`agents.connector_type`,-`bridges/agent/server_connectors/`), so this feature says **service** and-**service connection** throughout: in tables, routes, code and screens.+"Connector" already means something else in Core (`agents.connector_type`),+so this feature says **service** and **service connection** throughout: in+tables, routes, code and screens.## Shapediff --git a/docs/old/ARCHITECTURE.md b/docs/old/ARCHITECTURE.mdindex 52df1b2d1..1469a8883 100644--- a/docs/old/ARCHITECTURE.md+++ b/docs/old/ARCHITECTURE.md@@ -95,7 +95,6 @@ flowchart LR| Component | Where | Responsibility ||-----------|-------|----------------|| Agent Bridge | `bridges/agent/` | Server-side entry point for agents: HTTP API + MCP server, event delivery, mediation, moderation. |-| Server-side connectors | `bridges/agent/server_connectors/` | Switch-hosted connectors that drive an external agent host (e.g. OpenCode) from the server, rather than the agent connecting in. Registered by type at startup and managed via `/gateway/connectors`. || Collaboration bridges | `bridges/collaboration/` | Two-way relay between external chat platforms and Matrix rooms, via per-platform adapters and puppet clients. || Resource bridge | `bridges/resource/` | Handles resource + mediation requests (tool/model access, room-document load/CRUD) via the resource-manager client. || Matrix clients | `clients/` | One `matrix-nio` client per participant (agent, bridge, user) and per system actor (admin, resource manager). |@@ -153,8 +152,6 @@ The relational schema is defined invisibility. Four built-in types (Google Drive, Confluence, GitHub, Jira) shipin code rather than as rows and win any slug collision.- **CollaborationBridge** — configured external chat bridges.-- **ServerConnector** — a Switch-hosted connector driving an external agent host- (e.g. OpenCode) from the server, rather than the agent connecting in.- **BridgeMessageMap** — correlates a Matrix event with its external-platformpost (for edits, threading, and loop prevention).- **Tool** / **Model** / **Skill** — capabilities attached to agents, consulted@@ -420,7 +417,6 @@ A quick index for navigation:| Token encryption | `core/switch_core/crypto.py` || Agent Bridge (API, MCP, protocol, auth, commands) | `core/switch_core/bridges/agent/` || Agent operation registry | `core/switch_core/bridges/agent/operations/` |-| Server-side connectors | `core/switch_core/bridges/agent/server_connectors/` || Collaboration bridges (adapters, core, lifecycle) | `core/switch_core/bridges/collaboration/` || Resource bridge | `core/switch_core/bridges/resource/` || Matrix clients | `core/switch_core/clients/` |diff --git a/docs/old/LOCAL_DEVELOPMENT.md b/docs/old/LOCAL_DEVELOPMENT.mdindex 6c0942142..3f8f3ca2b 100644--- a/docs/old/LOCAL_DEVELOPMENT.md+++ b/docs/old/LOCAL_DEVELOPMENT.md@@ -94,10 +94,10 @@ start the gateway frontend — you run both of those yourself, in their ownterminals, so each gets hot-reload while you work. `just down` stops thestack; `just reset` also wipes its volumes (Postgres data included).-switch-core refuses to connect to a private address at a URL a bridge or-connector config names, unless `OUTBOUND_ALLOWED_PRIVATE_HOSTS` lists it. The-`.env.example` default, `localhost`, covers the local Mattermost and an OpenCode-server on your machine. An `.env` from before that setting existed lacks it, and+switch-core refuses to connect to a private address at a URL a bridge config+names, unless `OUTBOUND_ALLOWED_PRIVATE_HOSTS` lists it. The `.env.example`+default, `localhost`, covers the local Mattermost. An `.env` from before that+setting existed lacks it, andthe Mattermost bridge then refuses to start with a message naming the variable:add the line from `.env.example`.diff --git a/docs/old/multi-tenancy-phase2-tenants.md b/docs/old/multi-tenancy-phase2-tenants.mdindex bbdf7d088..e9b53b783 100644--- a/docs/old/multi-tenancy-phase2-tenants.md+++ b/docs/old/multi-tenancy-phase2-tenants.md@@ -201,9 +201,9 @@ this phase must prove it has removed.**Creating a workspace is bounded, because it is an amplification vectorrather than a row.** `all_tenant_ids()` drives a fan-out per tenant at boot and-a sweep every few seconds, across clients, collaboration bridges, server-connectors and rooms, so unbounded self-service creation buys steady-state work-in the deployment, not storage. `GATEWAY_MAX_WORKSPACES_PER_USER` is both the+a sweep every few seconds, across clients, collaboration bridges and rooms, so+unbounded self-service creation buys steady-state work in the deployment, not+storage. `GATEWAY_MAX_WORKSPACES_PER_USER` is both thecap and the gate: at the limit `POST /tenants` is a 403, and `0` closes theroute outright. It counts workspaces a person has *created*(`users.workspaces_created`), not ones they own: ownership can be handed to adiff --git a/docs/old/observability.md b/docs/old/observability.mdindex 0b216c766..319b055f6 100644--- a/docs/old/observability.md+++ b/docs/old/observability.md@@ -270,9 +270,6 @@ handled in a way that leaves no trace.on a platform where the app routinely sits in them (a shared Telegram botwith Group Privacy off). Counted instead of logged, so the drops that arereal losses — a bridge down, a migration's window — keep their own errors.-- **`switch.connectors.running`** — connectors start fire-and-forget, each- failure logged and stepped over, so one that never came up is a dead agent- host nothing else reports.If you add another place that catches an exception to keep something alive,this is the list it belongs on.diff --git a/docs/old/telemetry-events.md b/docs/old/telemetry-events.mdindex e90e0e679..0c0bce8f7 100644--- a/docs/old/telemetry-events.md+++ b/docs/old/telemetry-events.md@@ -770,8 +770,6 @@ This is what each carries.| `room_role_defined` | `exclusive` (boolean) || `room_role_deleted` | none || `room_users_added` | `user_count` (number) |-| `server_connector_registered` | `connector_kind` (`opencode` \| `other`) |-| `server_connector_removed` | `connector_kind` (`opencode` \| `other`) || `connector_configured` | `bridge_platform`; `is_preconfigured` (boolean) || `invitation_sent` | `delivery` (`sent` \| `not_configured` \| `failed` \| `not_requested`) || `invitation_accepted` | `age_hours` (number) |@@ -1073,7 +1071,6 @@ reason.as it connecting. `is_preconfigured` separates the setup step's ownconnector from one a person added. Many of these and few `bridge_connected` is a deploymentwhose setup is failing, and only the pair shows it.-- `server_connector_registered` / `server_connector_removed`.**Deliberately not reported**, so the boundary is stated rather thandiscovered: edits that change a setting rather than create or removediff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 3f8844981..f12187c1d 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -745,64 +745,6 @@ export async function registerOtherAgent(return (await res.json()) as RegisterResult;}-// ── Connectors ──────────────────────────────────────────────────────────────--export interface ConnectorTypeConfigSchema {- type: string;- properties: Record<- string,- {- type?: string;- title?: string;- description?: string;- default?: unknown;- format?: string;- }- >;- required?: string[];-}--export interface ConnectorTypeInfo {- key: string;- config_schema: ConnectorTypeConfigSchema;-}--export interface ConnectorResult {- connector_id: string;- connector_type: string;- display_name: string;- status: string;- agent_names: string[];- created_at: string;-}--export async function fetchConnectorTypes(): Promise<ConnectorTypeInfo[] | null> {- return fetchJson<ConnectorTypeInfo[]>("/connectors/types");-}--export async function createConnector(- type: string,- displayName: string,- connectionConfig: Record<string, unknown>,-): Promise<ConnectorResult> {- const res = await fetch(`${BASE}/connectors`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({- type,- display_name: displayName,- connection_config: connectionConfig,- }),- });- if (!res.ok) {- const body = await res.json().catch(() => null);- const detail = body?.detail ?? `${res.status} ${res.statusText}`;- throw new Error(detail);- }- return (await res.json()) as ConnectorResult;-}-// ── API Keys ─────────────────────────────────────────────────────────────────export interface ApiKeyDetail {@@ -859,9 +801,24 @@ export async function deleteApiKey(keyId: string): Promise<boolean> {// ── Collaborations ───────────────────────────────────────────────────────────+export interface BridgeConfigSchema {+ type: string;+ properties: Record<+ string,+ {+ type?: string;+ title?: string;+ description?: string;+ default?: unknown;+ format?: string;+ }+ >;+ required?: string[];+}+export interface BridgeTypeInfo {key: string;- config_schema: ConnectorTypeConfigSchema;+ config_schema: BridgeConfigSchema;// Whether this platform can create channels at all. Fixed per platform.channel_creation_supported: boolean;}diff --git a/gateway/src/data/hooks.ts b/gateway/src/data/hooks.tsindex a652b1bdc..33b8afe99 100644--- a/gateway/src/data/hooks.ts+++ b/gateway/src/data/hooks.ts@@ -13,7 +13,6 @@ import {type BridgeDetail,type BridgeTypeInfo,type ExternalUserSummary,- type ConnectorTypeInfo,type DocumentDetail,type DocumentSummary,type InboundLinkedRoomDetail,@@ -43,7 +42,6 @@ import {fetchBridges,fetchBridgeTypes,fetchBridgeUsers,- fetchConnectorTypes,fetchDocumentRooms,fetchDocuments,fetchInboundLinkedRooms,@@ -227,10 +225,6 @@ export function useUsers(): UseQueryResult<UserInfo[]> {return useQuery(fetchUsers);}-export function useConnectorTypes(): UseQueryResult<ConnectorTypeInfo[]> {- return useQuery(fetchConnectorTypes);-}-export function useApiKeys(): UseQueryResult<ApiKeyDetail[]> {return useQuery(fetchApiKeys);}diff --git a/gateway/src/pages/agents/RegisterAgentDialog.tsx b/gateway/src/pages/agents/RegisterAgentDialog.tsxindex 5e254cb27..ce57e412c 100644--- a/gateway/src/pages/agents/RegisterAgentDialog.tsx+++ b/gateway/src/pages/agents/RegisterAgentDialog.tsx@@ -16,15 +16,12 @@ import {} from "@mui/material";import { useCallback, useState } from "react";import {- type ConnectorResult,- type ConnectorTypeConfigSchema,type KnownAgentType,type RegisterResult,- createConnector,registerKnownAgent,registerOtherAgent,} from "../../data/api";-import { useConnectorTypes, useKnownAgentTypes } from "../../data/hooks";+import { useKnownAgentTypes } from "../../data/hooks";import { extractDefaults, renderOptionFields } from "./optionFields";interface Props {@@ -33,7 +30,7 @@ interface Props {onRegistered: () => void;}-type SelectedKind = "known" | "connector" | "other" | null;+type SelectedKind = "known" | "other" | null;const OTHER_KEY = "__other__";@@ -43,10 +40,10 @@ export default function RegisterAgentDialog({onRegistered,}: Props) {const { data: knownTypes } = useKnownAgentTypes();- const { data: connectorTypes } = useConnectorTypes();const [selectedKey, setSelectedKey] = useState("");- const [selectedKind, setSelectedKind] = useState<SelectedKind>(null);+ const selectedKind: SelectedKind =+ selectedKey === "" ? null : selectedKey === OTHER_KEY ? "other" : "known";// Known agent / Other fieldsconst [name, setName] = useState("");@@ -57,33 +54,21 @@ export default function RegisterAgentDialog({Record<string, unknown>>({});- // Connector fields- const [displayName, setDisplayName] = useState("");- const [connectorConfig, setConnectorConfig] = useState<Record<string, string>>(- {},- );-const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);const [agentResult, setAgentResult] = useState<RegisterResult | null>(null);- const [connectorResult, setConnectorResult] =- useState<ConnectorResult | null>(null);const [copied, setCopied] = useState<string | null>(null);- const hasResult = agentResult !== null || connectorResult !== null;+ const hasResult = agentResult !== null;const reset = useCallback(() => {setSelectedKey("");- setSelectedKind(null);setName("");setDescription("");setKnownAgentOptions({});- setDisplayName("");- setConnectorConfig({});setSubmitting(false);setError(null);setAgentResult(null);- setConnectorResult(null);setCopied(null);}, []);@@ -96,19 +81,10 @@ export default function RegisterAgentDialog({const handleTypeChange = useCallback((value: string) => {setSelectedKey(value);- let kind: SelectedKind;- if (value === OTHER_KEY) {- kind = "other";- } else {- const isKnown = knownTypes?.some((t) => t.key === value);- kind = isKnown ? "known" : "connector";- }- setSelectedKind(kind);- setConnectorConfig({});// Seed type-specific options with their schema defaults so unchecking a// box explicitly sets `false` rather than dropping the field.- if (kind === "known") {+ if (value !== OTHER_KEY) {const spec = knownTypes?.find((t) => t.key === value);setKnownAgentOptions(extractDefaults(spec?.options_schema));} else {@@ -118,26 +94,7 @@ export default function RegisterAgentDialog({[knownTypes],);- const selectedConnectorType = connectorTypes?.find(- (c) => c.key === selectedKey,- );- const configSchema: ConnectorTypeConfigSchema | null =- selectedKind === "connector" && selectedConnectorType- ? selectedConnectorType.config_schema- : null;-- const canSubmit =- selectedKind === "known"- ? selectedKey && name- : selectedKind === "other"- ? name- : selectedKind === "connector"- ? selectedKey &&- displayName &&- (configSchema?.required ?? []).every(- (field) => connectorConfig[field]?.trim(),- )- : false;+ const canSubmit = selectedKind !== null && name !== "";const handleSubmit = useCallback(async () => {if (!canSubmit) return;@@ -145,25 +102,16 @@ export default function RegisterAgentDialog({setError(null);try {- if (selectedKind === "known") {- const res = await registerKnownAgent(- selectedKey,- name,- description,- knownAgentOptions,- );- setAgentResult(res);- } else if (selectedKind === "other") {- const res = await registerOtherAgent(name, description);- setAgentResult(res);- } else {- const config: Record<string, string> = {};- for (const [key, value] of Object.entries(connectorConfig)) {- if (value) config[key] = value;- }- const res = await createConnector(selectedKey, displayName, config);- setConnectorResult(res);- }+ const res =+ selectedKind === "known"+ ? await registerKnownAgent(+ selectedKey,+ name,+ description,+ knownAgentOptions,+ )+ : await registerOtherAgent(name, description);+ setAgentResult(res);} catch (err) {setError(err instanceof Error ? err.message : "Registration failed.");} finally {@@ -176,8 +124,6 @@ export default function RegisterAgentDialog({name,description,knownAgentOptions,- displayName,- connectorConfig,]);const handleCopy = useCallback((value: string, label: string) => {@@ -202,7 +148,6 @@ export default function RegisterAgentDialog({);const hasKnown = knownTypes && knownTypes.length > 0;- const hasConnectors = connectorTypes && connectorTypes.length > 0;const copyAdornment = (value: string, label: string) => (<InputAdornment position="end">@@ -271,31 +216,6 @@ export default function RegisterAgentDialog({/>)}</>- ) : connectorResult ? (- <>- <Alert severity="success">- Connector created. Agents are being discovered and registered- automatically.- </Alert>- <TextField- label="Connector ID"- value={connectorResult.connector_id}- fullWidth- slotProps={{ input: { readOnly: true } }}- />- <TextField- label="Display Name"- value={connectorResult.display_name}- fullWidth- slotProps={{ input: { readOnly: true } }}- />- <TextField- label="Status"- value={connectorResult.status}- fullWidth- slotProps={{ input: { readOnly: true } }}- />- </>) : (<>{error && <Alert severity="error">{error}</Alert>}@@ -320,21 +240,13 @@ export default function RegisterAgentDialog({{t.key}</MenuItem>))}- {hasConnectors && (- <ListSubheader>Server Connectors</ListSubheader>- )}- {(connectorTypes ?? []).map((c) => (- <MenuItem key={c.key} value={c.key}>- {c.key}- </MenuItem>- ))}<ListSubheader>Other</ListSubheader><MenuItem value={OTHER_KEY}>External agent</MenuItem></TextField>- {(selectedKind === "known" || selectedKind === "other") && (+ {selectedKind !== null && (<><TextFieldlabel="Name"@@ -360,49 +272,6 @@ export default function RegisterAgentDialog({)}</>)}-- {selectedKind === "connector" && (- <>- <TextField- label="Display Name"- value={displayName}- onChange={(e) => setDisplayName(e.target.value)}- fullWidth- required- />- {configSchema &&- Object.entries(configSchema.properties).map(- ([field, prop]) => {- const isRequired =- configSchema.required?.includes(field) ?? false;- const label =- prop.title ??- field- .replace(/_/g, " ")- .replace(/\b\w/g, (c) => c.toUpperCase());- return (- <TextField- key={field}- label={label}- type={- prop.format === "password" ? "password" : "text"- }- value={connectorConfig[field] ?? ""}- onChange={(e) =>- setConnectorConfig((prev) => ({- ...prev,- [field]: e.target.value,- }))- }- fullWidth- required={isRequired}- helperText={prop.description}- />- );- },- )}- </>- )}</>)}</Stack>diff --git a/scripts/e2e_surface.py b/scripts/e2e_surface.pyindex 2ab645604..a7c217cfe 100644--- a/scripts/e2e_surface.py+++ b/scripts/e2e_surface.py@@ -90,8 +90,6 @@ _COLLABORATORS = ("bridge_store","client_lifecycle","collab_lifecycle",- "connector_lifecycle",- "connector_store","event_buffer","session_factory","user_store",