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
Let owners and workspace admins transfer what they own (#1001)
Abel Dantas2274ca2c2c98
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 60c356f8a..0230d199b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -129,6 +129,15 @@ version of their own to them without also giving them a release of their own.workspace, with the same refusals as deleting your own. Administratoraccounts and your own account are refused, and every attempt is recorded inthe server audit log with its outcome.+- **Transfer ownership.** The owner, or a workspace admin, can hand an agent,+ room, package, reference, reference type, library document or template to+ another member of the workspace (`POST /ownership/transfer`, and a Transfer+ ownership action on the detail pages). Each transfer is audited. An agent+ that uses its owner's service connections, is managed on its owner's+ machine, can manage agents, has sub-agents or signs in with its own OAuth+ client is refused; any other agent gets a new API key that only the new+ owner can see, so it has to be reconnected. Chats and room documents are not+ transferable.- **The gateway says what the caller may change in a room.** Rooms, in thelist (`GET /rooms`) and in a room's detail, carry `can_write`,`can_manage` and `can_unlink`. Each room a reference, document or packagediff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.jsonindex eefc2fedf..a55606160 100644--- a/console/tooling-e2e/surface/server-surface.json+++ b/console/tooling-e2e/surface/server-surface.json@@ -1284,6 +1284,11 @@"auth": "session","flags": []},+ {+ "route": "POST /gateway/ownership/transfer",+ "auth": "session",+ "flags": []+ },{"route": "POST /gateway/packages","auth": "session",diff --git a/core/switch_core/accounts/transfer.py b/core/switch_core/accounts/transfer.pynew file mode 100644index 000000000..b2532b0b1--- /dev/null+++ b/core/switch_core/accounts/transfer.py@@ -0,0 +1,326 @@+"""Handing something a person owns to another member of the same workspace.++The current owner, or a workspace admin, may hand an agent, room, package,+reference, reference type, library document or template to anyone who is a+member of the workspace now. Everything else about the thing stays as it was.++An agent carries more than an owner id, so it is refused where the owner id is+not the whole of what ties it to its owner, and the refusal says what to undo+first:++- service access (`service_grants`) is made with the owner's own connections,+ so keeping it would let the new owner's agent act with the previous owner's+ accounts;+- a managed agent runs on its owner's machine, with their provider sign-ins;+- an agent that may manage agents acts on its owner's machines;+- an agent with sub-agents, or a sub-agent, is one of a family registered+ together from one session;+- an agent that signs in with an OAuth client of its own holds a credential+ this module does not rotate;+- an agent a server-side connector runs is registered again by that+ connector, under its own owner, whenever the server starts.++What is left is the agent's API key, which its owner can reveal. It is+re-issued to the new owner, so a copy the previous owner holds stops working.+The agent's open connections authenticated with the old key, so their rows go+in the same transaction, and the caller ends them in every process once it has+committed (`AgentConnectionRegistry.agent_key_reissued`): the agent has to be+reconnected with the new key.++The thing's row is locked before anything is checked and held until the caller+commits, so two transfers of the same thing take turns, and the second is+judged on the owner the first left. The new owner's membership row is locked+too, as removing a member locks it (`gateway/tenants.py`), so a member being+removed cannot be handed an agent between the removal's check and its commit.+"""++from __future__ import annotations++import hashlib+import secrets+from dataclasses import dataclass+from typing import TYPE_CHECKING, Literal, cast, get_args++from sqlalchemy import select++from switch_core.authz import Principal, can_manage+from switch_core.db.audit import AuditAction, record_audit_event+from switch_core.db.models import (+ Agent,+ AgentDefinition,+ ApiKey,+ Document,+ Package,+ Reference,+ ReferenceType,+ Room,+ ServiceGrant,+ Template,+ TenantMember,+)+from switch_core.db.stores.agent_connection_store import AgentConnectionStore++if TYPE_CHECKING:+ from sqlalchemy.ext.asyncio import AsyncSession++ from switch_core.keys import Keyring++TransferKind = Literal[+ "agent",+ "room",+ "package",+ "reference",+ "reference_type",+ "document",+ "template",+]+TRANSFER_KINDS: tuple[str, ...] = get_args(TransferKind)++_LABELS: dict[str, str] = {+ "agent": "agent",+ "room": "room",+ "package": "package",+ "reference": "reference",+ "reference_type": "reference type",+ "document": "document",+ "template": "template",+}++Owned = Agent | Room | Package | Reference | ReferenceType | Document | Template+++class TransferRefused(Exception):+ """The transfer cannot happen; `status` is the HTTP status that says why,+ and the message is for the person who asked."""++ def __init__(self, status: int, message: str) -> None:+ super().__init__(message)+ self.status = status+++@dataclass(frozen=True)+class Transferred:+ kind: str+ resource_id: str+ previous_owner_id: str | None+ new_owner_id: str+ # The hash of the agent key that stopped working, for the caller to drop+ # from its cache once this has committed. None for anything but an agent.+ retired_key_hash: str | None+++async def _load(+ session: AsyncSession, tenant_id: str, kind: str, resource_id: str+) -> Owned | None:+ if kind == "reference_type":+ return await session.get(+ ReferenceType,+ (tenant_id, resource_id),+ with_for_update=True,+ populate_existing=True,+ )+ models: dict[str, type[Agent | Room | Package | Reference | Document | Template]]+ models = {+ "agent": Agent,+ "room": Room,+ "package": Package,+ "reference": Reference,+ "document": Document,+ "template": Template,+ }+ row = cast(+ Owned | None,+ await session.get(+ models[kind], resource_id, with_for_update=True, populate_existing=True+ ),+ )+ # The policy already hides another tenant's row; this says so in Python+ # too, for a connection the policy does not apply to.+ if row is None or row.tenant_id != tenant_id:+ return None+ return row+++async def _refuse_agent(session: AsyncSession, tenant_id: str, agent: Agent) -> None:+ services = sorted(+ await session.scalars(+ select(ServiceGrant.service).where(+ ServiceGrant.tenant_id == tenant_id, ServiceGrant.agent_id == agent.id+ )+ )+ )+ if services:+ raise TransferRefused(+ 409,+ "This agent uses its owner's own connections to "+ f"{', '.join(services)}. Remove its service access first; the new "+ "owner can then grant their own.",+ )+ managed = await session.scalar(+ select(AgentDefinition.id).where(+ AgentDefinition.tenant_id == tenant_id, AgentDefinition.agent_id == agent.id+ )+ )+ if managed is not None:+ raise TransferRefused(+ 409,+ "This agent is managed on its owner's machine, with their sign-ins, "+ "and can't be transferred.",+ )+ if agent.can_manage_agents:+ raise TransferRefused(+ 409,+ "This agent can manage its owner's agents. Turn that off first.",+ )+ child = await session.scalar(+ select(Agent.id).where(+ Agent.tenant_id == tenant_id, Agent.parent_agent_id == agent.id+ )+ )+ if agent.parent_agent_id is not None or child is not None:+ raise TransferRefused(+ 409,+ "This agent is part of a family of sub-agents, which can't be transferred.",+ )+ if agent.oauth_client_id is not None:+ raise TransferRefused(+ 409,+ "This agent signs in with an OAuth client of its own and can't be "+ "transferred.",+ )+ if (agent.metadata_ or {}).get("server_connector_id"):+ raise TransferRefused(+ 409,+ "This agent is run by a server connector, which registers it again "+ "under its own owner whenever the server starts, so it can't be "+ "transferred.",+ )+++async def _refuse(+ session: AsyncSession,+ tenant_id: str,+ kind: str,+ resource: Owned,+ new_owner_id: str,+) -> None:+ if isinstance(resource, Agent):+ await _refuse_agent(session, tenant_id, resource)+ elif isinstance(resource, Room):+ if resource.metadata_ is not None and "chat_operation_id" in resource.metadata_:+ raise TransferRefused(409, "A chat can't be transferred.")+ elif isinstance(resource, Document):+ if resource.room_id is not None:+ raise TransferRefused(+ 409,+ "This document belongs to a room. Only library documents can be "+ "transferred.",+ )+ elif isinstance(resource, Template):+ clash = await session.scalar(+ select(Template.id).where(+ Template.owner_id == new_owner_id, Template.name == resource.name+ )+ )+ if clash is not None:+ raise TransferRefused(+ 409,+ f"The new owner already has a template named {resource.name}. "+ "Rename one of them first.",+ )+++async def _reissue_agent_key(+ session: AsyncSession, agent: Agent, new_owner_id: str, keyring: Keyring+) -> str:+ """Give the agent's key to `new_owner_id` as a new secret; return the+ retired one's hash."""+ key = await session.get(ApiKey, agent.api_key_id)+ if key is None:+ raise RuntimeError(f"Agent {agent.id} has no API key row {agent.api_key_id}")+ retired = key.key_hash+ plaintext = secrets.token_urlsafe(32)+ key.key_hash = hashlib.sha256(plaintext.encode()).hexdigest()+ key.encrypted_key = keyring.encrypt(plaintext)+ key.user_id = new_owner_id+ return retired+++async def transfer_ownership(+ session: AsyncSession,+ *,+ tenant_id: str,+ kind: str,+ resource_id: str,+ new_owner_id: str,+ caller: Principal,+ keyring: Keyring,+) -> Transferred:+ """Make `new_owner_id` the owner, on `session`, with its audit event; the+ caller commits, and for an agent then ends its connections+ (`AgentConnectionRegistry.agent_key_reissued`). Raises `TransferRefused`+ and changes nothing otherwise."""+ if kind not in TRANSFER_KINDS:+ raise TransferRefused(+ 400,+ f"Unknown kind {kind!r}; expected one of {', '.join(TRANSFER_KINDS)}.",+ )+ label = _LABELS[kind]+ resource = await _load(session, tenant_id, kind, resource_id)+ if resource is None:+ raise TransferRefused(404, f"No such {label} in this workspace.")+ previous = resource.owner_id+ if not can_manage(caller, previous):+ raise TransferRefused(+ 403,+ f"Only the {label}'s owner or a workspace admin can transfer it.",+ )+ membership = await session.get(+ TenantMember,+ (tenant_id, new_owner_id),+ with_for_update=True,+ populate_existing=True,+ )+ if membership is None:+ raise TransferRefused(+ 400, "The new owner must be a current member of this workspace."+ )+ if previous == new_owner_id:+ raise TransferRefused(400, f"They already own this {label}.")+ if new_owner_id == caller.id:+ # An admin taking someone's agent would also take its key.+ raise TransferRefused(+ 403,+ f"You can't transfer someone else's {label} to yourself. "+ "Ask its owner to transfer it to you.",+ )+ await _refuse(session, tenant_id, kind, resource, new_owner_id)++ retired: str | None = None+ if isinstance(resource, Agent):+ retired = await _reissue_agent_key(session, resource, new_owner_id, keyring)+ await AgentConnectionStore().delete_agent(+ session, tenant_id=tenant_id, agent_id=resource.id+ )+ resource.owner_id = new_owner_id+ await session.flush()+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=caller.id,+ action=AuditAction.OWNERSHIP_TRANSFERRED,+ target_type=kind,+ target_id=resource_id,+ details={+ "from": previous,+ "to": new_owner_id,+ "agent_key_reissued": retired is not None,+ },+ )+ return Transferred(+ kind=kind,+ resource_id=resource_id,+ previous_owner_id=previous,+ new_owner_id=new_owner_id,+ retired_key_hash=retired,+ )diff --git a/core/switch_core/bridges/agent/protocol/agent_connections.py b/core/switch_core/bridges/agent/protocol/agent_connections.pyindex 2ea7a9347..ed377d76f 100644--- a/core/switch_core/bridges/agent/protocol/agent_connections.py+++ b/core/switch_core/bridges/agent/protocol/agent_connections.py@@ -558,6 +558,20 @@ def connection_transport(conn: AgentConnection) -> str:#: client that reopens is refused: its key names no agent any more.AGENT_DELETED = Closure(code="closed", message="the agent was deleted", room_id=None)+#: How an agent's connections end when its key is re-issued, as handing the+#: agent to a new owner does. Its connections authenticated with the old key+#: once, when they opened, so they would otherwise outlive it. A client that+#: reopens with the old key is refused.+KEY_REISSUED = Closure(+ code="closed",+ message="the agent's key was re-issued; reconnect with the new key",+ room_id=None,+)++#: Why an agent's connections were ended by deleting their rows, by the name a+#: signal carries to the other processes (`connection_rows.py`).+ENDINGS: dict[str, Closure] = {"deleted": AGENT_DELETED, "key_reissued": KEY_REISSUED}+class ConnectionRows(Protocol):"""Where a registry records its connections, so that every switch-core@@ -581,9 +595,10 @@ class ConnectionRows(Protocol):"""Read the agent's connections again from the rows."""...- async def agent_deleted(self, agent_id: str) -> None:- """The agent was deleted, and its rows with it: end what this process- holds of it, and have every other process read its rows again."""+ async def agent_ended(self, agent_id: str, ending: str) -> None:+ """The agent's rows were deleted, with the agent or on its own+ (`ENDINGS` names why): end what this process holds of it, and have+ every other process read its rows again."""...def closed(self, conn: AgentConnection) -> None:@@ -618,6 +633,9 @@ class AgentConnectionRegistry:# and two room-claim failures — and a sixth added later would silently# report nothing. The registry stays unaware of what the callback does.self._on_close: Callable[[AgentConnection], None] = lambda conn: None+ # Called with the id of an agent whose connections another process+ # ended (`set_ended_elsewhere_listener`).+ self._on_ended_elsewhere: Callable[[str], None] = lambda agent_id: Noneself._by_id: dict[str, AgentConnection] = {}self._by_agent: dict[str, set[str]] = {}self._slot_locks: dict[str, tuple[asyncio.Lock, int]] = {}@@ -843,6 +861,19 @@ class AgentConnectionRegistry:"""self._on_close = listener+ def set_ended_elsewhere_listener(self, listener: Callable[[str], None]) -> None:+ """Register a callback for an agent whose connections another process+ ended, called as soon as this process is told, before it reads the+ agent's rows. The wiring drops the agent's cached keys with it, so a+ client of an agent whose key was re-issued cannot reopen here on a key+ this process still remembers. One listener, set once at wiring time;+ it must not raise."""+ self._on_ended_elsewhere = listener++ def ended_elsewhere(self, agent_id: str) -> None:+ """Another process ended this agent's connections (`connection_rows.py`)."""+ self._on_ended_elsewhere(agent_id)+def _forget(self, connection_id: str) -> AgentConnection | None:conn = self._by_id.pop(connection_id, None)if conn is None:@@ -1387,11 +1418,22 @@ class AgentConnectionRegistry:holds (`apply_rows`): this one at once, and the others when told. Aregistry that records nothing closes the connections it holds."""+ await self._end_agent(agent_id, "deleted")++ async def agent_key_reissued(self, agent_id: str) -> None:+ """End the connections of an agent whose key was re-issued, here and+ in every other process, as `agent_deleted` does. The caller deleted+ their rows with the old key (`AgentConnectionStore.delete_agent`), so+ each process closes what it holds when it reads them, even one that+ missed being told."""+ await self._end_agent(agent_id, "key_reissued")++ async def _end_agent(self, agent_id: str, ending: str) -> None:if self._rows is not None:- await self._rows.agent_deleted(agent_id)+ await self._rows.agent_ended(agent_id, ending)returnfor cid in list(self._by_agent.get(agent_id, ())):- self.close(cid, AGENT_DELETED)+ self.close(cid, ENDINGS[ending])# ------------------------------------------------------------------# Keeping the copies of other processes' connections@@ -1474,18 +1516,24 @@ class AgentConnectionRegistry:self._released = Nonedef apply_rows(- self, agent_id: str, tenant_id: str, rows: AgentSlotRows, process_id: str+ self,+ agent_id: str,+ tenant_id: str,+ rows: AgentSlotRows,+ process_id: str,+ row_gone: Closure,) -> list[AgentConnection]:"""Make this agent's connections what the rows say.A connection held here that another process (or a later incarnation)has taken over is closed `taken_over`, so its stream tells its client.- One whose row was written and is gone is closed too: deleting the- agent deletes its rows. Copies of other processes' connections are- replaced by what is live now. Claims and placements are set from the- rows, and a connection held here whose rooms changed is woken, so its- stream reports the change and a session waiting for its first room- starts reading. Returns the connections closed as taken over.+ One whose row was written and is gone is closed too, with `row_gone`:+ deleting the agent deletes its rows, and so does re-issuing its key.+ Copies of other processes' connections are replaced by what is live+ now. Claims and placements are set from the rows, and a connection+ held here whose rooms changed is woken, so its stream reports the+ change and a session waiting for its first room starts reading.+ Returns the connections closed as taken over.The rows are never older than what this process holds of the agent(`connection_rows.py` reads them under its slots, or leaves an agent@@ -1500,7 +1548,7 @@ class AgentConnectionRegistry:# Recorded once (`tenant_id` is set when its row is written),# and the row is gone since.if conn.tenant_id is not None:- self.close(conn.id, AGENT_DELETED)+ self.close(conn.id, row_gone)continueif row.closed:continuediff --git a/core/switch_core/bridges/agent/protocol/connection_rows.py b/core/switch_core/bridges/agent/protocol/connection_rows.pyindex 12420ac2a..34e5fe918 100644--- a/core/switch_core/bridges/agent/protocol/connection_rows.py+++ b/core/switch_core/bridges/agent/protocol/connection_rows.py@@ -26,8 +26,9 @@ After each write the other processes are told to look, over the `SignalBus`holding a connection that lost a room is told which, so it can send`room_released`. A connection whose row now names another process or a laterincarnation was taken over, and its holder closes it `taken_over`. One whose-row is gone was its agent's, deleted since, and its holder closes it too: told-by the process that deleted the agent, or on its next read of every tenant.+row is gone was ended, with its agent or because the agent's key was re-issued,+and its holder closes it too: told by the process that ended it, with why, or+on its next read of every tenant.Liveness is the holding process's lease: a row counts while it is not closedand its process's lease is held. A lost signal costs a delay, never a wrong@@ -59,6 +60,8 @@ from datetime import timedeltafrom typing import TYPE_CHECKING, Anyfrom switch_core.bridges.agent.protocol.agent_connections import (+ AGENT_DELETED,+ ENDINGS,AgentConnection,AgentConnectionRegistry,Closure,@@ -112,8 +115,8 @@ WATCH_SECONDS = RENEW_INTERVAL_SECONDSRELAY_KEPT = timedelta(seconds=60)# Room kept in every signal for what it carries beside its list of beats or-# released rooms: its kind, the sending process's id, and the tenant and agent-# a `changed` signal names, about 250 bytes at most.+# released rooms: its kind, the sending process's id, and the tenant, agent and+# ending a `changed` signal names, about 280 bytes at most._SIGNAL_ENVELOPE_BYTES = 400_EMPTY = AgentSlotRows(connections={}, stored_claims={}, stored_placements={})@@ -175,6 +178,11 @@ class SharedConnections:# took off connections held here, to be told once the read is in.self._changes_owed = bus.pending_work("agent connections", self._read_owed)self._released_owed: dict[tuple[str, str], list[Released]] = {}+ # Why another process ended an agent's connections by deleting their+ # rows (`ENDINGS`), by agent id, for the read that finds them gone to+ # tell their clients. A pass that finds them gone untold says the agent+ # was deleted.+ self._endings: dict[str, str] = {}# Agents, by (tenant id, agent id), with session commands relayed to# this process and not yet taken.self._relays_owed = bus.pending_work(@@ -295,7 +303,7 @@ class SharedConnections:raiseself._bump(agent_id)if opened or slots_after != slots_recorded or released:- self._publish_changed(tenant_id, agent_id, released)+ self._publish_changed(tenant_id, agent_id, released, ending=None)async def refresh(self, agent_id: str) -> None:tenant_id = current_tenant_id()@@ -306,19 +314,20 @@ class SharedConnections:)await self._refresh(tenant_id, agent_id)- async def agent_deleted(self, agent_id: str) -> None:+ async def agent_ended(self, agent_id: str, ending: str) -> None:tenant_id = current_tenant_id()if tenant_id is None:raise RuntimeError(f"Agent {agent_id}'s connections are recorded in its tenant, and ""none is bound")- # Its rows went with it, so there is nothing to read: what this- # process holds of the agent is made what no rows say, which closes- # the connections held here and drops the copies of the others'.+ # Its rows are gone, so there is nothing to read: what this process+ # holds of the agent is made what no rows say, which closes the+ # connections held here and drops the copies of the others'.async with self._registry.slots(agent_id):+ self._endings[agent_id] = endingself._apply(agent_id, tenant_id, _EMPTY)- self._publish_changed(tenant_id, agent_id, [])+ self._publish_changed(tenant_id, agent_id, [], ending=ending)def closed(self, conn: AgentConnection) -> None:if conn.tenant_id is None or conn.closure is None:@@ -362,8 +371,10 @@ class SharedConnections:)def _apply(self, agent_id: str, tenant_id: str, rows: AgentSlotRows) -> None:+ ending = self._endings.pop(agent_id, None)+ gone = AGENT_DELETED if ending is None else ENDINGS[ending]for conn in self._registry.apply_rows(- agent_id, tenant_id, rows, self.process_id+ agent_id, tenant_id, rows, self.process_id, gone):logger.info("[CONN] agent=%s connection=%s generation=%s was taken over by "@@ -448,6 +459,17 @@ class SharedConnections:def _on_changed(self, signal: dict[str, Any]) -> None:key = (signal["tenant_id"], signal["agent_id"])+ ending = signal.get("ending")+ if ending is not None:+ self._registry.ended_elsewhere(signal["agent_id"])+ if ending in ENDINGS:+ self._endings[signal["agent_id"]] = ending+ elif ending is not None:+ # From a newer process, during a rolling deploy: the read still+ # closes the connections, saying the agent was deleted.+ logger.warning(+ "Unknown connection ending %r for agent %s", ending, signal["agent_id"]+ )self._released_owed.setdefault(key, []).extend(Released(connection_id=entry[0], room_id=entry[1], session_id=entry[2])for entry in signal.get("released", [])@@ -502,13 +524,22 @@ class SharedConnections:)def _publish_changed(- self, tenant_id: str, agent_id: str, released: list[Released]+ self,+ tenant_id: str,+ agent_id: str,+ released: list[Released],+ *,+ ending: str | None,) -> None:entries = [[r.connection_id, r.room_id, r.session_id] for r in released]# Sent with no rooms released too: the change is what is announced.for chunk in payload_chunks(entries, _SIGNAL_ENVELOPE_BYTES) or [[]]:self._bus.publish(- CHANGED_SIGNAL, tenant_id=tenant_id, agent_id=agent_id, released=chunk+ CHANGED_SIGNAL,+ tenant_id=tenant_id,+ agent_id=agent_id,+ released=chunk,+ ending=ending,)# ── Lifecycle ─────────────────────────────────────────────────────────@@ -560,7 +591,9 @@ class SharedConnections:await session.commit()unwritten_closes.remove(close)if written:- self._publish_changed(close.tenant_id, close.agent_id, [])+ self._publish_changed(+ close.tenant_id, close.agent_id, [], ending=None+ )for relay in relays:async with tenant_session(self._session_factory, relay.tenant_iddiff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pyindex c38ba9057..d99660ba4 100644--- a/core/switch_core/db/audit.py+++ b/core/switch_core/db/audit.py@@ -72,6 +72,7 @@ class AuditAction(StrEnum):WORKSPACE_SERVICE_ENABLED = "workspace_service.enabled"WORKSPACE_SERVICE_DISABLED = "workspace_service.disabled"WORKSPACE_SERVICE_CLEARED = "workspace_service.cleared"+ OWNERSHIP_TRANSFERRED = "ownership.transferred"class OrganizationAuditAction(StrEnum):diff --git a/core/switch_core/db/stores/agent_connection_store.py b/core/switch_core/db/stores/agent_connection_store.pyindex 870362e98..8ede92432 100644--- a/core/switch_core/db/stores/agent_connection_store.py+++ b/core/switch_core/db/stores/agent_connection_store.py@@ -383,6 +383,21 @@ class AgentConnectionStore:)return True+ async def delete_agent(+ self, session: AsyncSession, *, tenant_id: str, agent_id: str+ ) -> None:+ """Delete every connection row of an agent that stays, with their+ claims and placements, so every process ends the connections when it+ reads them (`AgentConnectionRegistry.agent_key_reissued`). Under the+ agent's slot lock, so no move lands between."""+ await self.lock_agent(session, agent_id)+ await session.execute(+ delete(AgentConnectionRecord).where(+ AgentConnectionRecord.tenant_id == tenant_id,+ AgentConnectionRecord.agent_id == agent_id,+ )+ )+async def add_relay(self,session: AsyncSession,diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex 3731aba6e..7cb9c0f0c 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -66,6 +66,7 @@ from switch_core.gateway.organization_services import (router as organization_services_router,)from switch_core.gateway.organizations import router as organizations_router+from switch_core.gateway.ownership import router as ownership_routerfrom switch_core.gateway.packages import router as packages_routerfrom switch_core.gateway.providers import router as providers_routerfrom switch_core.gateway.references import router as references_router@@ -246,6 +247,7 @@ def create_gateway_app(app.include_router(documents_router, tags=["documents"])app.include_router(packages_router, tags=["packages"])app.include_router(templates_router, tags=["templates"])+ app.include_router(ownership_router, tags=["ownership"])app.include_router(template_runs_router, tags=["templates"])app.include_router(ecosystem_router, prefix="/ecosystem", tags=["ecosystem"])app.include_router(trust_settings_router, tags=["trust-settings"])diff --git a/core/switch_core/gateway/ownership.py b/core/switch_core/gateway/ownership.pynew file mode 100644index 000000000..8035e7425--- /dev/null+++ b/core/switch_core/gateway/ownership.py@@ -0,0 +1,114 @@+"""Handing an owned thing to another member of the workspace.++One route for every kind, because the rule is the same for all of them: the+current owner or a workspace admin, to a current member of this workspace.+What differs per kind lives in `accounts/transfer.py`.+"""++from __future__ import annotations++import logging+from typing import Annotated++from fastapi import APIRouter, Depends, HTTPException+from pydantic import BaseModel+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.accounts.transfer import TransferRefused, transfer_ownership+from switch_core.authz import Principal+from switch_core.bridges.agent.protocol.agent_core import AgentCore+from switch_core.chats.service import ChatService+from switch_core.config import SwitchConfig+from switch_core.db.models import User, require_tenant_id, room_agents+from switch_core.gateway.auth import get_current_user, get_tenant_is_admin+from switch_core.gateway.chats import get_chat_service+from switch_core.gateway.dependencies import get_config, get_protocol, get_session++logger = logging.getLogger(__name__)++router = APIRouter()+++class OwnershipTransferRequest(BaseModel):+ kind: str+ id: str+ new_owner_id: str+++class OwnershipTransferResponse(BaseModel):+ kind: str+ id: str+ owner_id: str+ # True for an agent: its API key was re-issued to the new owner, and the+ # agent has to be reconnected with it.+ agent_key_reissued: bool++[email protected]("/ownership/transfer")+async def transfer(+ req: OwnershipTransferRequest,+ session: Annotated[AsyncSession, Depends(get_session)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],+ chat_service: Annotated[ChatService, Depends(get_chat_service)],+ config: Annotated[SwitchConfig, Depends(get_config)],+) -> OwnershipTransferResponse:+ """Make another current member of this workspace the owner of an agent,+ room, package, reference, reference type, library document or template.++ `kind` is one of `agent`, `room`, `package`, `reference`,+ `reference_type`, `document`, `template`; `id` is the thing's id, or the+ slug for a reference type. A refusal is the status and message from+ `TransferRefused`, and changes nothing.+ """+ tenant_id = require_tenant_id()+ try:+ done = await transfer_ownership(+ session,+ tenant_id=tenant_id,+ kind=req.kind,+ resource_id=req.id,+ new_owner_id=req.new_owner_id,+ caller=Principal(user.id, is_admin),+ keyring=config.keyring,+ )+ except TransferRefused as refused:+ await session.rollback()+ raise HTTPException(status_code=refused.status, detail=str(refused)) from None+ rooms: list[str] = []+ if done.kind == "agent":+ rooms = list(+ await session.scalars(+ select(room_agents.c.room_id).where(+ room_agents.c.agent_id == done.resource_id+ )+ )+ )+ await session.commit()++ if done.retired_key_hash is not None:+ protocol.api_key_cache.invalidate(done.retired_key_hash)+ protocol.api_key_cache.invalidate_agent(done.resource_id)+ # Its connections authenticated with the old key when they opened.+ # After the key is dropped, so a client told cannot open another.+ await protocol.connections.agent_key_reissued(done.resource_id)+ # A chat membership held only because its holder owned this agent goes+ # with the ownership.+ for room_id in rooms:+ await chat_service.sync_room(tenant_id, room_id)+ logger.info(+ "%s moved %s %s from %s to %s",+ user.id,+ done.kind,+ done.resource_id,+ done.previous_owner_id,+ done.new_owner_id,+ )+ return OwnershipTransferResponse(+ kind=done.kind,+ id=done.resource_id,+ owner_id=done.new_owner_id,+ agent_key_reissued=done.retired_key_hash is not None,+ )diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex e46529dee..36dbab64b 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -1404,13 +1404,20 @@ async def remove_member(enough, including by mistake, that it must not be the thing that makes anirreversible call about shared infrastructure. An admin who hits thisdeletes those agents deliberately, with the agent in front of them, then- removes the member. The 409 says exactly that and nothing more: there is- no route that reassigns an agent's owner in this phase, so offering- reassignment as the way out would send an admin looking for a button that- does not exist.+ removes the member, or hands them to someone else first+ (`POST /ownership/transfer`, which refuses an agent still tied to its+ owner's own connections or machine)."""_require_bound_tenant(tenant_id)- membership = await session.get(TenantMember, (tenant_id, user_id))+ # Locked until the removal commits, as handing the member something locks+ # it (`accounts/transfer.py`), so no agent reaches them after the check+ # below finds none.+ membership = await session.get(+ TenantMember,+ (tenant_id, user_id),+ with_for_update=True,+ populate_existing=True,+ )if membership is None:raise HTTPException(status_code=404, detail="Not a member of this tenant")await _refuse_organization_admin(session, user_store, tenant_id, user_id)@@ -1425,8 +1432,8 @@ async def remove_member(raise HTTPException(status_code=409,detail=(- "Cannot remove: this member owns agents in this tenant — "- f"delete them first: {names}"+ "Cannot remove: this member owns agents in this workspace. "+ f"Transfer or delete them first: {names}"),)diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 60188ec0f..564b1f4fc 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -1129,6 +1129,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:# Every close reports, whichever of the five paths did it — and only for a# connection the handler saw start.connections.set_close_listener(protocol.sessions.on_close)+ connections.set_ended_elsewhere_listener(protocol.api_key_cache.invalidate_agent)# ── Messaging app installs ──────────────────────────────────────────────# Registration is the feature flag. An installer exists for a platform whendiff --git a/core/tests/switch_core/accounts/test_ownership_transfer.py b/core/tests/switch_core/accounts/test_ownership_transfer.pynew file mode 100644index 000000000..d1d3ec511--- /dev/null+++ b/core/tests/switch_core/accounts/test_ownership_transfer.py@@ -0,0 +1,603 @@+"""Handing an owned thing to another member of the workspace.++Against a real database, as the rest of `accounts/`: what a transfer must not+carry over is held in other tables, and the refusals read them.+"""++from __future__ import annotations++import asyncio+import uuid+from types import SimpleNamespace++import httpx+import pytest+from fastapi import FastAPI+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.accounts.transfer import TransferRefused, transfer_ownership+from switch_core.authz import Principal+from switch_core.bridges.agent.protocol.agent_connections import (+ KEY_REISSUED,+ AgentConnection,+ AgentConnectionRegistry,+ ClientDeclaration,+)+from switch_core.bridges.agent.protocol.positions import OWN_EVENTS+from switch_core.db.models import (+ TENANT_ZERO_ID,+ Agent,+ AgentConnectionRecord,+ ApiKey,+ AuditEvent,+ Document,+ Package,+ Reference,+ Room,+ ServiceConnection,+ ServiceGrant,+ Template,+ TenantMember,+ User,+)+from switch_core.db.session_scope import tenant_session+from switch_core.gateway import dependencies as gw_deps+from switch_core.gateway.auth import get_current_user, get_tenant_is_admin+from switch_core.gateway.ownership import router as ownership_router+from tests.conftest import TEST_KEYRING+from tests.switch_core.accounts.test_account_deletion import _agent, _member, _user+from tests.switch_core.gateway.test_tenant_api_routes import (+ TENANT_A,+ _app,+ _client,+ _make_agent_with_key,+ _make_member,+ _make_tenant,+ _token,+)++# Long enough for a statement that is not waiting on a lock to have finished.+_BLOCKED_SECONDS = 0.5+++def _reference(owner: User, *, write_visibility: str = "private") -> Reference:+ return Reference(+ owner_id=owner.id,+ read_visibility="public",+ write_visibility=write_visibility,+ type="url",+ name=f"ref-{uuid.uuid4().hex[:6]}",+ description="",+ instructions="",+ value={"url": "https://example.test"},+ )+++async def _people(session: AsyncSession) -> tuple[User, User, User]:+ owner = await _user(session, "owner")+ member = await _user(session, "member")+ admin = await _user(session, "admin-member")+ await _member(session, TENANT_ZERO_ID, owner, "member")+ await _member(session, TENANT_ZERO_ID, member, "member")+ await _member(session, TENANT_ZERO_ID, admin, "admin")+ return owner, member, admin+++async def _transfer(+ session: AsyncSession, kind: str, resource_id: str, to: User, by: Principal+) -> None:+ await transfer_ownership(+ session,+ tenant_id=TENANT_ZERO_ID,+ kind=kind,+ resource_id=resource_id,+ new_owner_id=to.id,+ caller=by,+ keyring=TEST_KEYRING,+ )+++async def test_the_owner_hands_a_reference_to_a_member_and_it_is_audited(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ reference = _reference(owner)+ session.add(reference)+ await session.commit()++ await _transfer(+ session, "reference", reference.id, member, Principal(owner.id, False)+ )+ await session.commit()++ assert (+ await session.scalar(+ select(Reference.owner_id).where(Reference.id == reference.id)+ )+ ) == member.id+ event = await session.scalar(+ select(AuditEvent).where(AuditEvent.target_id == reference.id)+ )+ assert event is not None+ assert event.action == "ownership.transferred"+ assert event.actor_user_id == owner.id+ assert event.details == {+ "from": owner.id,+ "to": member.id,+ "agent_key_reissued": False,+ }+++async def test_a_writer_who_is_not_the_owner_is_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ reference = _reference(owner, write_visibility="public")+ session.add(reference)+ await session.commit()++ with pytest.raises(TransferRefused) as refused:+ await _transfer(+ session, "reference", reference.id, member, Principal(member.id, False)+ )+ assert refused.value.status == 403+ assert "owner or a workspace admin" in str(refused.value)+++async def test_an_admin_may_hand_over_someone_elses_package(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, member, admin = await _people(session)+ package = Package(+ owner_id=owner.id,+ read_visibility="public",+ write_visibility="private",+ name="kit",+ description="",+ instructions="",+ )+ session.add(package)+ await session.commit()++ await _transfer(+ session, "package", package.id, member, Principal(admin.id, True)+ )+ await session.commit()+ assert (+ await session.scalar(+ select(Package.owner_id).where(Package.id == package.id)+ )+ ) == member.id+++async def test_someone_outside_the_workspace_cannot_receive_it(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, _, _ = await _people(session)+ outsider = await _user(session, "outsider")+ reference = _reference(owner)+ session.add(reference)+ await session.commit()++ with pytest.raises(TransferRefused) as refused:+ await _transfer(+ session, "reference", reference.id, outsider, Principal(owner.id, False)+ )+ assert refused.value.status == 400+ assert "current member of this workspace" in str(refused.value)+++async def test_an_agent_moves_with_a_new_key_its_new_owner_holds(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ agent = await _agent(session, TENANT_ZERO_ID, owner, "helper")+ await session.commit()+ key = await session.get(ApiKey, agent.api_key_id)+ assert key is not None+ old_hash = key.key_hash++ done = await transfer_ownership(+ session,+ tenant_id=TENANT_ZERO_ID,+ kind="agent",+ resource_id=agent.id,+ new_owner_id=member.id,+ caller=Principal(owner.id, False),+ keyring=TEST_KEYRING,+ )+ await session.commit()++ assert done.retired_key_hash == old_hash+ await session.refresh(key)+ await session.refresh(agent)+ assert agent.owner_id == member.id+ assert key.user_id == member.id+ assert key.key_hash != old_hash+++async def test_an_agent_using_its_owners_connections_is_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ agent = await _agent(session, TENANT_ZERO_ID, owner, "helper")+ session.add(+ ServiceConnection(+ user_id=owner.id,+ service="github",+ status="active",+ consent="read",+ granted_scopes=[],+ account_id="1001",+ external_identity="owner",+ encrypted_secret="x",+ secret_revision=1,+ )+ )+ await session.flush()+ session.add(+ ServiceGrant(+ agent_id=agent.id,+ owner_id=owner.id,+ service="github",+ access="read",+ tool_mode="allow",+ tools=[],+ resources={},+ account_id="1001",+ created_by=owner.id,+ )+ )+ await session.commit()++ with pytest.raises(TransferRefused) as refused:+ await _transfer(+ session, "agent", agent.id, member, Principal(owner.id, False)+ )+ assert refused.value.status == 409+ assert "github" in str(refused.value)+ owner_id, agent_id = owner.id, agent.id+ await session.rollback()+ assert (+ await session.scalar(select(Agent.owner_id).where(Agent.id == agent_id))+ ) == owner_id+++async def test_an_agent_that_may_manage_agents_is_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ agent = await _agent(session, TENANT_ZERO_ID, owner, "manager")+ agent.can_manage_agents = True+ await session.commit()++ with pytest.raises(TransferRefused) as refused:+ await _transfer(+ session, "agent", agent.id, member, Principal(owner.id, False)+ )+ assert "manage its owner's agents" in str(refused.value)+++async def test_a_template_name_the_new_owner_already_uses_is_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ mine = Template(+ owner_id=owner.id, name="same", description="", kind="room", content="x"+ )+ theirs = Template(+ owner_id=member.id, name="same", description="", kind="room", content="y"+ )+ session.add_all([mine, theirs])+ await session.commit()++ with pytest.raises(TransferRefused) as refused:+ await _transfer(+ session, "template", mine.id, member, Principal(owner.id, False)+ )+ assert refused.value.status == 409+ assert "already has a template named same" in str(refused.value)+++async def test_a_room_document_and_a_chat_are_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ chat = Room(+ transport_room_id=f"!{uuid.uuid4().hex}:test",+ name="Chat",+ description="",+ owner_id=owner.id,+ created_by=owner.id,+ metadata_={"chat_operation_id": "op"},+ )+ session.add(chat)+ await session.flush()+ document = Document(+ owner_id=owner.id,+ room_id=chat.id,+ read_visibility="public",+ write_visibility="private",+ name="notes",+ description="",+ instructions="",+ content="",+ )+ session.add(document)+ await session.commit()++ with pytest.raises(TransferRefused) as chat_refused:+ await _transfer(+ session, "room", chat.id, member, Principal(owner.id, False)+ )+ assert "chat can't be transferred" in str(chat_refused.value)+ with pytest.raises(TransferRefused) as document_refused:+ await _transfer(+ session, "document", document.id, member, Principal(owner.id, False)+ )+ assert "Only library documents" in str(document_refused.value)+++async def test_an_unknown_kind_is_refused() -> None:+ with pytest.raises(TransferRefused) as refused:+ await transfer_ownership(+ None, # type: ignore[arg-type]+ tenant_id=TENANT_ZERO_ID,+ kind="workspace",+ resource_id="x",+ new_owner_id="y",+ caller=Principal("z", True),+ keyring=TEST_KEYRING,+ )+ assert refused.value.status == 400+++async def test_an_admin_may_not_take_someone_elses_package_for_themselves(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, _member, admin = await _people(session)+ package = Package(+ owner_id=owner.id,+ read_visibility="public",+ write_visibility="private",+ name="kit",+ description="",+ instructions="",+ )+ session.add(package)+ await session.commit()++ with pytest.raises(TransferRefused) as refused:+ await _transfer(+ session, "package", package.id, admin, Principal(admin.id, True)+ )+ assert "to yourself" in str(refused.value)+++async def test_a_server_connectors_agent_is_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ agent = await _agent(session, TENANT_ZERO_ID, owner, "connector-agent")+ agent.metadata_ = {"server_connector_id": "connector-1"}+ await session.commit()++ with pytest.raises(TransferRefused) as refused:+ await _transfer(+ session, "agent", agent.id, member, Principal(owner.id, False)+ )+ assert refused.value.status == 409+ assert "server connector" in str(refused.value)+++async def test_an_agents_connection_rows_go_with_its_old_key(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Its connections authenticated with the old key; with their rows gone,+ every process that holds one ends it."""+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ agent = await _agent(session, TENANT_ZERO_ID, owner, "connected")+ session.add(+ AgentConnectionRecord(+ id="conn-1",+ agent_id=agent.id,+ process_id="some-process",+ incarnation=1,+ scope="single",+ delivery_filter="addressed",+ spawn_capable=False,+ transport="websocket",+ )+ )+ await session.commit()++ await _transfer(session, "agent", agent.id, member, Principal(owner.id, False))+ await session.commit()++ assert (+ await session.scalar(+ select(AgentConnectionRecord.id).where(+ AgentConnectionRecord.agent_id == agent.id+ )+ )+ ) is None+++def _ownership_app(+ session_factory: async_sessionmaker[AsyncSession],+ caller: User,+ connections: AgentConnectionRegistry,+) -> FastAPI:+ async def _session_dep():+ async with session_factory() as session:+ yield session++ async def _sync_room(_tenant_id: str, _room_id: str) -> None:+ pass++ app = FastAPI()+ app.include_router(ownership_router)+ app.state.chat_service = SimpleNamespace(sync_room=_sync_room)+ overrides = app.dependency_overrides+ overrides[gw_deps.get_session] = _session_dep+ overrides[get_current_user] = lambda: caller+ overrides[get_tenant_is_admin] = lambda: False+ overrides[gw_deps.get_config] = lambda: SimpleNamespace(keyring=TEST_KEYRING)+ overrides[gw_deps.get_protocol] = lambda: SimpleNamespace(+ api_key_cache=SimpleNamespace(+ invalidate=lambda key_hash: None, invalidate_agent=lambda agent_id: None+ ),+ connections=connections,+ )+ return app+++async def _open(connections: AgentConnectionRegistry, agent_id: str) -> AgentConnection:+ async with connections.slots(agent_id):+ async with connections.recorded(agent_id):+ return connections.open(+ agent_id=agent_id,+ connection_id="conn-1",+ scope="single",+ delivery_filter="addressed",+ spawn_capable=False,+ position={OWN_EVENTS: 0},+ declaration=ClientDeclaration(speaks=None),+ expected_generation=None,+ )+++async def test_the_route_ends_the_agents_open_connections(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ agent = await _agent(session, TENANT_ZERO_ID, owner, "live")+ await session.commit()+ agent_id, member_id = agent.id, member.id+ connections = AgentConnectionRegistry()+ conn = await _open(connections, agent_id)++ app = _ownership_app(session_factory, owner, connections)+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://test"+ ) as client:+ response = await client.post(+ "/ownership/transfer",+ json={"kind": "agent", "id": agent_id, "new_owner_id": member_id},+ )+ assert response.status_code == 200, response.text+ assert conn.closure == KEY_REISSUED+ assert not connections.is_live(agent_id)+++async def test_two_transfers_of_one_agent_take_turns(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """The second waits for the first, then is judged on the owner the first+ left: its caller no longer owns the agent."""+ async with session_factory() as session:+ owner, first, second = await _people(session)+ agent = await _agent(session, TENANT_ZERO_ID, owner, "contested")+ await session.commit()+ owner_id, first_id, agent_id = owner.id, first.id, agent.id++ async with session_factory() as one, session_factory() as two:+ await _transfer(one, "agent", agent_id, first, Principal(owner_id, False))+ racing = asyncio.create_task(+ _transfer(two, "agent", agent_id, second, Principal(owner_id, False))+ )+ await asyncio.sleep(_BLOCKED_SECONDS)+ assert not racing.done()+ await one.commit()+ with pytest.raises(TransferRefused) as refused:+ await racing+ assert refused.value.status == 403++ async with session_factory() as session:+ assert (+ await session.scalar(select(Agent.owner_id).where(Agent.id == agent_id))+ ) == first_id+++async def test_a_transfer_waits_for_a_removal_of_its_new_owner(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """A removal holding the membership row: the transfer finds no member once+ it commits."""+ async with session_factory() as session:+ owner, member, _ = await _people(session)+ agent = await _agent(session, TENANT_ZERO_ID, owner, "pending")+ await session.commit()+ owner_id, member_id, agent_id = owner.id, member.id, agent.id++ async with session_factory() as removal, session_factory() as session:+ membership = await removal.get(+ TenantMember, (TENANT_ZERO_ID, member_id), with_for_update=True+ )+ await removal.delete(membership)+ await removal.flush()+ racing = asyncio.create_task(+ _transfer(session, "agent", agent_id, member, Principal(owner_id, False))+ )+ await asyncio.sleep(_BLOCKED_SECONDS)+ assert not racing.done()+ await removal.commit()+ with pytest.raises(TransferRefused) as refused:+ await racing+ assert refused.value.status == 400+ assert "current member" in str(refused.value)+++async def test_a_removal_waits_for_a_transfer_to_the_member(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """A transfer under way to the member: the removal, once it commits, finds+ the agent they now own and refuses."""+ await _make_tenant(session_factory, TENANT_A)+ owner_id = await _make_member(+ session_factory, name="giver", tenant_id=TENANT_A, role="admin"+ )+ member_id = await _make_member(+ session_factory, name="taker", tenant_id=TENANT_A, role="member"+ )+ agent_id, agent_name, _ = await _make_agent_with_key(+ session_factory, tenant_id=TENANT_A, owner_id=owner_id+ )++ async with tenant_session(session_factory, TENANT_A) as transfer:+ await transfer_ownership(+ transfer,+ tenant_id=TENANT_A,+ kind="agent",+ resource_id=agent_id,+ new_owner_id=member_id,+ caller=Principal(owner_id, False),+ keyring=TEST_KEYRING,+ )+ token = _token(owner_id, "[email protected]", TENANT_A)+ async with _client(_app(session_factory), token) as client:+ racing = asyncio.create_task(+ client.delete(f"/tenants/{TENANT_A}/members/{member_id}")+ )+ await asyncio.sleep(_BLOCKED_SECONDS)+ assert not racing.done()+ await transfer.commit()+ response = await racing+ assert response.status_code == 409, response.text+ assert agent_name in response.json()["detail"]+ async with session_factory() as session:+ assert await session.get(TenantMember, (TENANT_A, member_id)) is not Nonediff --git a/core/tests/switch_core/bridges/agent/protocol/test_connections_across_processes.py b/core/tests/switch_core/bridges/agent/protocol/test_connections_across_processes.pyindex 099566270..b40c5bce9 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_connections_across_processes.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_connections_across_processes.py@@ -37,6 +37,7 @@ from switch_core.bridges.agent.api.schemas import ()from switch_core.bridges.agent.protocol.agent_connections import (HEARTBEAT_TTL_SECONDS,+ KEY_REISSUED,PROTOCOL_VERSION,AgentConnection,AgentConnectionRegistry,@@ -1100,6 +1101,74 @@ async def _delete_agent_row(session_factory: SessionFactory) -> None:await session.commit()+async def _end_agent_rows(session_factory: SessionFactory) -> None:+ """Delete the agent's connection rows and keep the agent, as handing it to+ a new owner does when it re-issues the agent's key."""+ async with session_factory() as session:+ await AgentConnectionStore().delete_agent(+ session, tenant_id=TENANT_ZERO_ID, agent_id=AGENT+ )+ await session.commit()+++class TestAnAgentWhoseKeyWasReissued:+ """The agent stays, but its connections authenticated with the old key+ when they opened. They end wherever their sockets are held."""++ async def test_reissued_through_the_other_process_its_connection_closes(+ self,+ processes: tuple[Process, Process],+ session_factory: SessionFactory,+ ) -> None:+ a, b = processes+ told: list[str] = []+ a.registry.set_ended_elsewhere_listener(told.append)+ conn = await _open(a)+ await _eventually(lambda: b.registry.is_live(AGENT))++ await _end_agent_rows(session_factory)+ with tenant_scope(TENANT_ZERO_ID):+ await b.registry.agent_key_reissued(AGENT)++ await _eventually(lambda: conn.closure is not None)+ assert conn.closure == KEY_REISSUED+ assert told == [AGENT]+ assert not a.registry.is_live(AGENT)+ assert not b.registry.is_live(AGENT)+ async with session_factory() as session:+ assert await session.get(Agent, AGENT) is not None++ async def test_a_holder_never_told_closes_it_on_its_next_pass(+ self,+ processes: tuple[Process, Process],+ session_factory: SessionFactory,+ ) -> None:+ a, _ = processes+ conn = await _open(a)++ await _end_agent_rows(session_factory)+ await a.shared.reload_all()++ assert conn.closure is not None+ assert conn.closure.code == "closed"+ assert not a.registry.is_live(AGENT)++ async def test_the_agent_reconnects_afterwards(+ self,+ processes: tuple[Process, Process],+ session_factory: SessionFactory,+ ) -> None:+ a, b = processes+ await _open(a)+ await _end_agent_rows(session_factory)+ with tenant_scope(TENANT_ZERO_ID):+ await a.registry.agent_key_reissued(AGENT)+ assert not a.registry.is_live(AGENT)++ await _open(b)+ await _eventually(lambda: a.registry.is_live(AGENT))++class TestADeletedAgent:"""Deleting an agent deletes its connections' rows. Its connections endwherever their sockets are held, not only in the process deleting it."""diff --git a/gateway/src/components/TransferOwnershipSection.test.ts b/gateway/src/components/TransferOwnershipSection.test.tsnew file mode 100644index 000000000..7c09bd05e--- /dev/null+++ b/gateway/src/components/TransferOwnershipSection.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from "vitest";+import type { Member } from "../data/api";+import { transferCandidates } from "./TransferOwnershipSection";++const member = (user_id: string): Member => ({ user_id }) as Member;++describe("transferCandidates", () => {+ const members = [member("owner"), member("admin"), member("other")];++ it("leaves out the owner when the owner transfers", () => {+ expect(transferCandidates(members, "owner", "owner").map((m) => m.user_id)).toEqual([+ "admin",+ "other",+ ]);+ });++ it("leaves out an admin transferring someone else's thing", () => {+ expect(transferCandidates(members, "owner", "admin").map((m) => m.user_id)).toEqual(["other"]);+ });+});diff --git a/gateway/src/components/TransferOwnershipSection.tsx b/gateway/src/components/TransferOwnershipSection.tsxnew file mode 100644index 000000000..d49c7443f--- /dev/null+++ b/gateway/src/components/TransferOwnershipSection.tsx@@ -0,0 +1,207 @@+import SwapHoriz from "@mui/icons-material/SwapHoriz";+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogContentText,+ DialogTitle,+ MenuItem,+ Select,+ Stack,+ Typography,+} from "@mui/material";+import { useEffect, useState } from "react";+import { useAuth } from "../data/AuthContext";+import { type Member, type OwnershipKind, fetchMembers, transferOwnership } from "../data/api";++interface Props {+ kind: OwnershipKind;+ resourceId: string;+ resourceLabel: string;+ ownerId: string | null;+ onTransferred: () => void;+}++const LABELS: Record<OwnershipKind, string> = {+ agent: "agent",+ room: "room",+ package: "package",+ reference: "reference",+ reference_type: "reference type",+ document: "document",+ template: "template",+};++/** Who the thing can go to: anyone in the workspace but its owner and the+ * caller. An admin handing over someone else's thing can't take it for+ * themselves; the server refuses that too. */+export function transferCandidates(+ members: Member[],+ ownerId: string | null,+ callerId: string | null,+): Member[] {+ return members.filter((m) => m.user_id !== ownerId && m.user_id !== callerId);+}++/** Hands the thing to another member of this workspace. The server decides+ * who may and refuses what can't be moved; its message is shown as is. */+export default function TransferOwnershipSection({+ kind,+ resourceId,+ resourceLabel,+ ownerId,+ onTransferred,+}: Props) {+ const [open, setOpen] = useState(false);++ return (+ <Stack spacing={1}>+ <Typography variant="overline" sx={{ display: "block" }}>+ Ownership+ </Typography>+ <Button+ variant="outlined"+ startIcon={<SwapHoriz />}+ onClick={() => setOpen(true)}+ sx={{ alignSelf: "flex-start" }}+ >+ Transfer ownership+ </Button>+ {open && (+ <TransferOwnershipDialog+ kind={kind}+ resourceId={resourceId}+ resourceLabel={resourceLabel}+ ownerId={ownerId}+ onClose={() => setOpen(false)}+ onTransferred={() => {+ setOpen(false);+ onTransferred();+ }}+ />+ )}+ </Stack>+ );+}++interface DialogProps {+ kind: OwnershipKind;+ /** The thing's id, or the slug for a reference type. */+ resourceId: string;+ resourceLabel: string;+ ownerId: string | null;+ onClose: () => void;+ onTransferred: () => void;+}++/** The transfer itself, for a page's section or a table row's action. */+export function TransferOwnershipDialog({+ kind,+ resourceId,+ resourceLabel,+ ownerId,+ onClose,+ onTransferred,+}: DialogProps) {+ const { session, user } = useAuth();+ const tenantId = session?.tenant?.id;+ const [members, setMembers] = useState<Member[] | null>(null);+ const [recipient, setRecipient] = useState("");+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const label = LABELS[kind];++ useEffect(() => {+ if (!tenantId) return;+ let cancelled = false;+ fetchMembers(tenantId)+ .then((found) => {+ if (!cancelled) setMembers(found);+ })+ .catch((e) => {+ if (!cancelled) setError(e instanceof Error ? e.message : "Could not load members");+ });+ return () => {+ cancelled = true;+ };+ }, [tenantId]);++ const close = () => {+ if (submitting) return;+ onClose();+ };++ const submit = async () => {+ setSubmitting(true);+ setError(null);+ try {+ await transferOwnership(kind, resourceId, recipient);+ onTransferred();+ } catch (e) {+ setError(e instanceof Error ? e.message : "The transfer failed");+ } finally {+ setSubmitting(false);+ }+ };++ const candidates = transferCandidates(members ?? [], ownerId, user?.id ?? null);++ return (+ <Dialog open onClose={close} fullWidth maxWidth="xs">+ <DialogTitle>Transfer {label}</DialogTitle>+ <DialogContent>+ <DialogContentText sx={{ mb: 2 }}>+ Make another member of this workspace the owner of <b>{resourceLabel}</b>.+ </DialogContentText>+ {kind === "agent" && (+ <Alert severity="warning" sx={{ mb: 2 }}>+ The agent gets a new API key that only the new owner can see. It stops+ working with the old key until it is reconnected.+ </Alert>+ )}+ {members === null && !error ? (+ <CircularProgress size={20} />+ ) : (+ <Select+ fullWidth+ size="small"+ displayEmpty+ value={recipient}+ onChange={(e) => setRecipient(e.target.value)}+ aria-label="New owner"+ >+ <MenuItem value="" disabled>+ Choose a member+ </MenuItem>+ {candidates.map((m) => (+ <MenuItem key={m.user_id} value={m.user_id}>+ {m.name} ({m.email})+ </MenuItem>+ ))}+ </Select>+ )}+ {error && (+ <Alert severity="error" sx={{ mt: 2 }}>+ {error}+ </Alert>+ )}+ </DialogContent>+ <DialogActions>+ <Button onClick={close} disabled={submitting}>+ Cancel+ </Button>+ <Button+ variant="contained"+ onClick={submit}+ disabled={submitting || recipient === ""}+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}+ >+ Transfer+ </Button>+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 8db0b20df..251ef6748 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -1216,6 +1216,36 @@ export async function fetchMembers(tenantId: string): Promise<Member[]> {return jsonRequest<Member[]>(`/tenants/${encodeURIComponent(tenantId)}/members`, "GET");}+export type OwnershipKind =+ | "agent"+ | "room"+ | "package"+ | "reference"+ | "reference_type"+ | "document"+ | "template";++export interface OwnershipTransferResult {+ kind: OwnershipKind;+ id: string;+ owner_id: string;+ // An agent's API key is re-issued to its new owner, who has to reconnect it.+ agent_key_reissued: boolean;+}++// The current owner or a workspace admin, to a current member of the workspace.+export async function transferOwnership(+ kind: OwnershipKind,+ id: string,+ newOwnerId: string,+): Promise<OwnershipTransferResult> {+ return jsonRequest<OwnershipTransferResult>("/ownership/transfer", "POST", {+ kind,+ id,+ new_owner_id: newOwnerId,+ });+}+export async function updateMemberRole(tenantId: string,userId: string,diff --git a/gateway/src/pages/agents/AgentDetailPage.tsx b/gateway/src/pages/agents/AgentDetailPage.tsxindex 13b137583..ec1c25304 100644--- a/gateway/src/pages/agents/AgentDetailPage.tsx+++ b/gateway/src/pages/agents/AgentDetailPage.tsx@@ -1,4 +1,5 @@import ArrowBack from "@mui/icons-material/ArrowBack";+import TransferOwnershipSection from "../../components/TransferOwnershipSection";import EditOutlined from "@mui/icons-material/EditOutlined";import {Alert,@@ -78,7 +79,7 @@ function StatusDot({ color, title }: { color: string; title?: string }) {export default function AgentDetailPage() {const { agentId } = useParams<{ agentId: string }>();const navigate = useNavigate();- const { user } = useAuth();+ const { user, canAdminTenant } = useAuth();const { data: agent, loading, error, refetch } = useAgent(agentId);const [renameOpen, setRenameOpen] = useState(false);const [renameNotice, setRenameNotice] = useState<{@@ -192,6 +193,18 @@ export default function AgentDetailPage() {onUpdated={refetch}/>{isOwner && <ServiceAccessSection agent={agent} onAgentUpdated={refetch} />}+ {(isOwner || canAdminTenant) && (+ <>+ <Divider />+ <TransferOwnershipSection+ kind="agent"+ resourceId={agent.id}+ resourceLabel={agent.name}+ ownerId={agent.owner_id}+ onTransferred={refetch}+ />+ </>+ )}<Divider /><SessionsSection sessions={agent.sessions} /><Divider />diff --git a/gateway/src/pages/resources/DocumentDetailPage.tsx b/gateway/src/pages/resources/DocumentDetailPage.tsxindex c9117d313..4aa6d4c6c 100644--- a/gateway/src/pages/resources/DocumentDetailPage.tsx+++ b/gateway/src/pages/resources/DocumentDetailPage.tsx@@ -1,4 +1,5 @@import ArrowBack from "@mui/icons-material/ArrowBack";+import TransferOwnershipSection from "../../components/TransferOwnershipSection";import DeleteOutline from "@mui/icons-material/DeleteOutline";import {Alert,@@ -112,6 +113,14 @@ export default function DocumentDetailPage() {/>{canMutate && (<>+ <Divider />+ <TransferOwnershipSection+ kind="document"+ resourceId={id}+ resourceLabel={doc.name || id}+ ownerId={doc.owner_id}+ onTransferred={() => navigate(0)}+ /><Divider /><DangerSection onDelete={() => setDeleteOpen(true)} /></>diff --git a/gateway/src/pages/resources/PackageDetailPage.tsx b/gateway/src/pages/resources/PackageDetailPage.tsxindex 009704e57..74957ed88 100644--- a/gateway/src/pages/resources/PackageDetailPage.tsx+++ b/gateway/src/pages/resources/PackageDetailPage.tsx@@ -1,4 +1,5 @@import ArrowBack from "@mui/icons-material/ArrowBack";+import TransferOwnershipSection from "../../components/TransferOwnershipSection";import DeleteOutline from "@mui/icons-material/DeleteOutline";import {Alert,@@ -111,6 +112,14 @@ export default function PackageDetailPage() {/>{canMutate && (<>+ <Divider />+ <TransferOwnershipSection+ kind="package"+ resourceId={id}+ resourceLabel={pkg.name || id}+ ownerId={pkg.owner_id}+ onTransferred={() => navigate(0)}+ /><Divider /><DangerSection onDelete={() => setDeleteOpen(true)} /></>diff --git a/gateway/src/pages/resources/ReferenceDetailPage.tsx b/gateway/src/pages/resources/ReferenceDetailPage.tsxindex 643c38599..fca3b9698 100644--- a/gateway/src/pages/resources/ReferenceDetailPage.tsx+++ b/gateway/src/pages/resources/ReferenceDetailPage.tsx@@ -1,4 +1,5 @@import ArrowBack from "@mui/icons-material/ArrowBack";+import TransferOwnershipSection from "../../components/TransferOwnershipSection";import DeleteOutline from "@mui/icons-material/DeleteOutline";import {Alert,@@ -123,6 +124,14 @@ export default function ReferenceDetailPage() {/>{canMutate && (<>+ <Divider />+ <TransferOwnershipSection+ kind="reference"+ resourceId={id}+ resourceLabel={ref.name || id}+ ownerId={ref.owner_id}+ onTransferred={() => navigate(0)}+ /><Divider /><DangerSection onDelete={() => setDeleteOpen(true)} /></>diff --git a/gateway/src/pages/resources/ReferenceTypesTab.tsx b/gateway/src/pages/resources/ReferenceTypesTab.tsxindex 233077b21..bbf4a7516 100644--- a/gateway/src/pages/resources/ReferenceTypesTab.tsx+++ b/gateway/src/pages/resources/ReferenceTypesTab.tsx@@ -1,5 +1,6 @@import DeleteOutline from "@mui/icons-material/DeleteOutline";import EditOutlined from "@mui/icons-material/EditOutlined";+import SwapHoriz from "@mui/icons-material/SwapHoriz";import {Alert,Box,@@ -18,6 +19,7 @@ import {import type { GridColDef } from "@mui/x-data-grid";import { useEffect, useMemo, useState } from "react";import DataTable from "../../components/DataTable";+import { TransferOwnershipDialog } from "../../components/TransferOwnershipSection";import { AccessChip, AccessSelect } from "../../components/AccessControls";import {deleteReferenceType,@@ -67,6 +69,7 @@ export default function ReferenceTypesTab({ refreshKey }: Props) {} = useOwnedReferenceTypes();const [editing, setEditing] = useState<ReferenceTypeDetail | null>(null);const [deleting, setDeleting] = useState<ReferenceTypeDetail | null>(null);+ const [transferring, setTransferring] = useState<ReferenceTypeDetail | null>(null);useEffect(() => {refetchVisible();@@ -147,7 +150,7 @@ export default function ReferenceTypesTab({ refreshKey }: Props) {{field: "actions",headerName: "",- width: 96,+ width: 128,sortable: false,filterable: false,renderCell: ({ row }) =>@@ -160,6 +163,13 @@ export default function ReferenceTypesTab({ refreshKey }: Props) {><EditOutlined fontSize="small" /></IconButton>+ <IconButton+ size="small"+ onClick={() => setTransferring(row.detail)}+ aria-label={`Transfer ${row.display_name}`}+ >+ <SwapHoriz fontSize="small" />+ </IconButton><IconButtonsize="small"onClick={() => setDeleting(row.detail)}@@ -200,6 +210,19 @@ export default function ReferenceTypesTab({ refreshKey }: Props) {}}/>)}+ {transferring && (+ <TransferOwnershipDialog+ kind="reference_type"+ resourceId={transferring.type}+ resourceLabel={transferring.display_name}+ ownerId={transferring.owner_id}+ onClose={() => setTransferring(null)}+ onTransferred={() => {+ setTransferring(null);+ refreshBoth();+ }}+ />+ )}{deleting && (<DeleteReferenceTypeDialogreferenceType={deleting}diff --git a/gateway/src/pages/resources/TemplateDetailPage.tsx b/gateway/src/pages/resources/TemplateDetailPage.tsxindex c12c1298d..24413e388 100644--- a/gateway/src/pages/resources/TemplateDetailPage.tsx+++ b/gateway/src/pages/resources/TemplateDetailPage.tsx@@ -1,4 +1,5 @@import ArrowBack from "@mui/icons-material/ArrowBack";+import TransferOwnershipSection from "../../components/TransferOwnershipSection";import ContentCopy from "@mui/icons-material/ContentCopy";import DeleteOutline from "@mui/icons-material/DeleteOutline";import Download from "@mui/icons-material/Download";@@ -118,6 +119,14 @@ export default function TemplateDetailPage() {/>{canManage && (<>+ <Divider />+ <TransferOwnershipSection+ kind="template"+ resourceId={id}+ resourceLabel={template.name || id}+ ownerId={template.owner_id}+ onTransferred={() => navigate(0)}+ /><Divider /><DangerSection onDelete={() => setDeleteOpen(true)} /></>diff --git a/gateway/src/pages/rooms/RoomDetailPage.tsx b/gateway/src/pages/rooms/RoomDetailPage.tsxindex 078826ea5..378e41824 100644--- a/gateway/src/pages/rooms/RoomDetailPage.tsx+++ b/gateway/src/pages/rooms/RoomDetailPage.tsx@@ -1,4 +1,5 @@import AddIcon from "@mui/icons-material/Add";+import TransferOwnershipSection from "../../components/TransferOwnershipSection";import ArchiveOutlined from "@mui/icons-material/ArchiveOutlined";import ArrowBack from "@mui/icons-material/ArrowBack";import Close from "@mui/icons-material/Close";@@ -161,6 +162,14 @@ export default function RoomDetailPage() {)}{canManage && (<>+ <Divider />+ <TransferOwnershipSection+ kind="room"+ resourceId={room.id}+ resourceLabel={room.name}+ ownerId={room.owner_id}+ onTransferred={refetch}+ /><Divider /><DangerSection room={room} onDeleted={() => navigate("/rooms")} /></>