Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat: scoped agent-addressing permissions (CHOO-1585) (#59)
Louis Amaudruz9390b02a725d
diff --git a/connectors/claude-code-plugin/.claude-plugin/plugin.json b/connectors/claude-code-plugin/.claude-plugin/plugin.jsonindex f2eb9b019..d6e00b0f3 100644--- a/connectors/claude-code-plugin/.claude-plugin/plugin.json+++ b/connectors/claude-code-plugin/.claude-plugin/plugin.json@@ -1,5 +1,5 @@{"name": "switch-connector",- "version": "0.1.14",+ "version": "0.1.15","description": "Connect Claude Code to a Switch platform instance as a participating agent"}\ No newline at end of filediff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.mdindex 350de1fed..1635b7015 100644--- a/connectors/claude-code-plugin/skills/switch/SKILL.md+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md@@ -131,6 +131,13 @@ If your `instructions` indicate you have task capabilities:3. Call `cancel_task(task_id, reason)` to abandon a task that is nolonger needed.+ Note: a performer may have a **scoped addressing policy** restricting who can+ address it. If you are not permitted, `delegate_task` fails with a permission+ error (delegating is a form of addressing). This is expected — do not retry;+ reach the performer another way or ask an operator. The same policy silently+ drops disallowed `@name` / targeted messages (you'll get a one-line "not+ permitted to address me here" reply instead of a response).+- **Accepting** (`can_accept=true`):1. On a `task_delegate` event, call `accept_task(task_id)` to move it to`ongoing`.diff --git a/core/switch_core/addressing.py b/core/switch_core/addressing.pynew file mode 100644index 000000000..1958f6b7b--- /dev/null+++ b/core/switch_core/addressing.py@@ -0,0 +1,148 @@+"""Scoped agent-addressing permissions (CHOO-1585).++Controls WHO may *address* an agent — i.e. cause it to receive a message it is+expected to respond to (an `@name` / `@alias` / `@role` mention, a targeted+message, or a task delegation). By default any room participant can address any+agent; this module adds an opt-in allow-list model per agent.++Model:+ - Each agent carries an `AddressingPolicy`: an ordered list of allow-rules.+ - A rule constrains four dimensions of the *incoming* addressing attempt:+ * `rooms` — the room the message is in+ * `room_groups` — the group that room belongs to (``None`` if ungrouped)+ * `users` — matched when the sender is a human+ * `agents` — matched when the sender is another agent+ - Each dimension is either ``"*"`` (any), or an explicit list of ids. An+ empty list ``[]`` is the "none" value: it matches nothing. The sender is+ exactly one kind (user XOR agent), so a rule that should admit only humans+ sets ``agents: []`` and vice-versa.+ - A rule *allows* an attempt when the context matches (room AND group) AND+ the sender matches (its own kind's dimension). Addressing is permitted when+ **any** rule allows it.++Defaults / precedence (agreed on CHOO-1585):+ - An agent with **no rules** preserves today's behaviour: anyone may address+ it (allow-all). Enforcement only kicks in once at least one rule exists.+ - With rules present it is **deny-by-default**: only attempts matching a rule+ are permitted.++This module is deliberately pure (no DB, no I/O) so it is trivially testable+and reusable from the receive path, the protocol service, and the gateway.+"""++from __future__ import annotations++from typing import Literal++from pydantic import BaseModel, field_validator++SenderKind = Literal["user", "agent"]++ANY = "*"++# A dimension is "*" (any) or an explicit list of ids ([] = none / match nothing).+Dimension = str | list[str]+++class AddressingRule(BaseModel):+ """One allow-rule. An attempt is allowed when it matches this rule on all+ four dimensions (see module docstring). Each dimension defaults to ``"*"``+ (unconstrained); note that leaving ``users``/``agents`` at ``"*"`` admits+ that whole sender kind — set the one you want to exclude to ``[]``."""++ rooms: Dimension = ANY+ room_groups: Dimension = ANY+ users: Dimension = ANY+ agents: Dimension = ANY++ @field_validator("rooms", "room_groups", "users", "agents")+ @classmethod+ def _valid_dimension(cls, value: Dimension) -> Dimension:+ if value == ANY:+ return value+ if isinstance(value, list) and all(isinstance(v, str) for v in value):+ return value+ raise ValueError(f'dimension must be "*" or a list of ids, got {value!r}')++ def _matches(+ self,+ *,+ room_id: str,+ group_id: str | None,+ sender_kind: SenderKind,+ sender_id: str,+ ) -> bool:+ if not _dim_contains(self.rooms, room_id):+ return False+ if not _dim_contains(self.room_groups, group_id):+ return False+ sender_dim = self.users if sender_kind == "user" else self.agents+ return _dim_contains(sender_dim, sender_id)+++class AddressingPolicy(BaseModel):+ """An agent's addressing allow-list. Empty ``rules`` → allow-all."""++ rules: list[AddressingRule] = []++ def is_open(self) -> bool:+ """True when the policy imposes no restriction (no rules)."""+ return not self.rules++ def allows(+ self,+ *,+ room_id: str,+ group_id: str | None,+ sender_kind: SenderKind,+ sender_id: str,+ ) -> bool:+ """Whether an addressing attempt from this sender, in this room, is+ permitted. Allow-all when the policy is open; otherwise permitted iff+ at least one rule matches."""+ if self.is_open():+ return True+ return any(+ rule._matches(+ room_id=room_id,+ group_id=group_id,+ sender_kind=sender_kind,+ sender_id=sender_id,+ )+ for rule in self.rules+ )+++def _dim_contains(dimension: Dimension, value: str | None) -> bool:+ """Whether a single dimension admits ``value``. ``"*"`` admits anything;+ a list admits only its members; ``None`` (e.g. an ungrouped room) is admitted+ only by ``"*"``."""+ if dimension == ANY:+ return True+ if value is None:+ return False+ return value in dimension+++def parse_policy(raw: dict | None) -> AddressingPolicy:+ """Build a policy from a stored JSONB blob (``None`` → open policy)."""+ if not raw:+ return AddressingPolicy()+ return AddressingPolicy.model_validate(raw)+++def can_address(+ policy: AddressingPolicy,+ *,+ room_id: str,+ group_id: str | None,+ sender_kind: SenderKind,+ sender_id: str,+) -> bool:+ """Convenience free function mirroring :meth:`AddressingPolicy.allows`."""+ return policy.allows(+ room_id=room_id,+ group_id=group_id,+ sender_kind=sender_kind,+ sender_id=sender_id,+ )diff --git a/core/switch_core/bridges/agent/protocol/agent_detail.py b/core/switch_core/bridges/agent/protocol/agent_detail.pyindex 512282964..80acfe48c 100644--- a/core/switch_core/bridges/agent/protocol/agent_detail.py+++ b/core/switch_core/bridges/agent/protocol/agent_detail.py@@ -15,6 +15,7 @@ from typing import Any, castfrom sqlalchemy.ext.asyncio import AsyncSession+from switch_core.addressing import AddressingPolicyfrom switch_core.bridges.agent.protocol.statuses import compute_agent_statusesfrom switch_core.db.models import Agent, AgentSessionfrom switch_core.db.stores.agent_session_store import AgentSessionStore@@ -212,6 +213,12 @@ async def assemble_agent_detail(for child in child_agents]+ addressing_policy = (+ AddressingPolicy.model_validate(agent.addressing_policy)+ if isinstance(agent.addressing_policy, dict)+ else None+ )+return AgentDetail(**summary.model_dump(),agent_type=agent.agent_type,@@ -225,6 +232,7 @@ async def assemble_agent_detail(rooms=memberships,sessions=sessions,children=children,+ addressing_policy=addressing_policy,)diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex 7c308a2fc..7a1dec1a9 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -15,6 +15,7 @@ from nio import ()from sqlalchemy import func, select+from switch_core.addressing import can_address, parse_policyfrom switch_core.aliases import check_alias_collisions, validate_alias_formatfrom switch_core.authz import Action, Principal, require, require_managefrom switch_core.bridges.agent.protocol.agent_detail import (@@ -1395,11 +1396,29 @@ class ProtocolService:async with self.session_factory() as session:performer = await self.agent_store.get(session, performer_id)+ room_row = await self.room_store.get(session, room.id)if performer is None:raise ValueError(f"Performer agent not found: {performer_id}")await self.require_room_member(performer_id, room_id)+ # Scoped addressing policy (CHOO-1585): delegating a task addresses the+ # performer, so it is subject to the same allow-list as a message. Unlike+ # the message path (which demotes to unaddressed) a task is explicit, so a+ # denied delegation fails loud rather than silently vanishing.+ performer_policy = parse_policy(performer.addressing_policy)+ if not performer_policy.is_open() and not can_address(+ performer_policy,+ room_id=room.id,+ group_id=room_row.group_id if room_row is not None else None,+ sender_kind="agent",+ sender_id=requester_id,+ ):+ raise PermissionError(+ f"Agent {requester_id} is not permitted to address "+ f"{performer.name} in this room."+ )+async with self.session_factory() as session:task = Task(room_id=room.id,diff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.pyindex bbb1921c8..a64ccc9c2 100644--- a/core/switch_core/clients/agent_client.py+++ b/core/switch_core/clients/agent_client.py@@ -12,7 +12,9 @@ from nio import (RoomMessageMedia,RoomMessageText,)+from sqlalchemy.ext.asyncio import AsyncSession+from switch_core.addressing import SenderKind, can_address, parse_policyfrom switch_core.bridges.agent.commands import (AGENT_GREETINGS,COMMANDS_BY_NAME,@@ -56,6 +58,7 @@ from switch_core.db.stores.agent_session_store import AgentSessionStorefrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.document_store import DocumentStore+from switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.reference_store import ReferenceStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStore@@ -120,6 +123,16 @@ _CONNECTED_NOT_LIVE_MESSAGE = ()+# Posted (once, guarded by AUTO_REPLY_FLAG) when a sender tags this agent but+# the agent's scoped addressing policy (CHOO-1585) does not permit that sender+# to address it here. The message is demoted to unaddressed room chatter; this+# reply is the sender's only feedback that the attempt was rejected.+_ADDRESSING_DENIED_MESSAGE = (+ "You're not permitted to direct messages to me in this room — my operator "+ "has restricted who can address me here."+)++# Shown to an agent addressed here while it holds a role in THIS room but the# session that assumed the role has hopped away to other room(s) (the lease# still routes here). `room_names` lists where that session is now active.@@ -150,6 +163,7 @@ class AgentClient(ClientBase[ClientConfig]):reference_store: ReferenceStore,agent_session_store: AgentSessionStore,room_role_store: RoomRoleStore,+ external_user_store: ExternalUserStore,request_tracker: RequestTracker,resource_request_tracker: ResourceRequestTracker,frontend_base_url: str | None,@@ -164,6 +178,7 @@ class AgentClient(ClientBase[ClientConfig]):self._reference_store = reference_storeself._agent_session_store = agent_session_storeself._room_role_store = room_role_store+ self._external_user_store = external_user_storeself._request_tracker = request_trackerself._resource_request_tracker = resource_request_trackerself._frontend_base_url = (@@ -276,6 +291,10 @@ class AgentClient(ClientBase[ClientConfig]):reply_thread_root = thread_id if thread_id is not None else event.event_id+ is_addressed = await self._gate_addressed(+ room, event, meta, reply_thread_root, is_addressed+ )+if is_addressed:triggered_by_auto_reply = bool(event.source.get("content", {}).get(AUTO_REPLY_FLAG)@@ -362,6 +381,11 @@ class AgentClient(ClientBase[ClientConfig]):if relates.get("rel_type") == "m.thread":thread_id = relates.get("event_id")+ reply_thread_root = thread_id if thread_id is not None else event.event_id+ is_addressed = await self._gate_addressed(+ room, event, meta, reply_thread_root, is_addressed+ )+agent_event = AgentEvent(type="message",room_id=meta.room_id,@@ -798,6 +822,110 @@ class AgentClient(ClientBase[ClientConfig]):return Truereturn await self._is_mentioned_via_role(event, meta.room_id)+ async def _resolve_sender_principal(+ self, session: AsyncSession, matrix_user_id: str+ ) -> tuple[SenderKind, str] | None:+ """Resolve a Matrix sender to an addressing principal.++ Maps the sender's mxid to its Client, then to either an Agent (an+ agent-to-agent attempt) or an ExternalUser (a human on a bridge).+ Returns ``None`` when the sender has no such record — an+ unresolvable identity that a restricted agent should not trust.+ """+ client = await self.client_store.get_by_matrix_user_id(session, matrix_user_id)+ if client is None:+ return None+ agent = await self._agent_store.get_by_client_id(session, client.id)+ if agent is not None:+ return ("agent", agent.id)+ external_user = await self._external_user_store.get_by_client_id(+ session, client.id+ )+ if external_user is not None:+ return ("user", external_user.id)+ return None++ async def _addressing_allowed(self, event: RoomMessage, meta: RoomMeta) -> bool:+ """Whether the message's sender may address this agent, per the agent's+ scoped addressing policy (CHOO-1585).++ An agent with no policy is open to anyone (today's behaviour), so this+ returns True without a DB round-trip. With a policy set it is+ deny-by-default: an unresolvable sender is rejected (fail-closed).+ """+ agent = await self._fresh_agent()+ policy = parse_policy(agent.addressing_policy)+ if policy.is_open():+ return True+ async with self.session_factory() as session:+ principal = await self._resolve_sender_principal(session, event.sender)+ room = await self._room_store.get(session, meta.room_id)+ if principal is None:+ logger.warning(+ "Addressing denied for %s: unresolvable sender %s in room %s",+ self.agent.name,+ event.sender,+ meta.room_id,+ )+ return False+ sender_kind, sender_id = principal+ group_id = room.group_id if room is not None else None+ allowed = can_address(+ policy,+ room_id=meta.room_id,+ group_id=group_id,+ sender_kind=sender_kind,+ sender_id=sender_id,+ )+ if not allowed:+ logger.warning(+ "Addressing denied for %s: %s %s not permitted in room %s",+ self.agent.name,+ sender_kind,+ sender_id,+ meta.room_id,+ )+ return allowed++ async def _gate_addressed(+ self,+ room: MatrixRoom,+ event: RoomMessage,+ meta: RoomMeta,+ reply_thread_root: str,+ is_addressed: bool,+ ) -> bool:+ """Apply the scoped addressing policy to a would-be-addressed message.++ When the message tags this agent but the sender is not permitted by the+ agent's policy, demote it to unaddressed room chatter and (once, guarded+ by AUTO_REPLY_FLAG so two agents can't ping-pong) reply to the sender+ explaining they can't address it here. Returns the effective addressed+ flag. Zero cost for the common case: only messages that already tag this+ agent are ever checked, and open policies short-circuit.+ """+ if not is_addressed:+ return False+ if await self._addressing_allowed(event, meta):+ return True+ triggered_by_auto_reply = bool(+ event.source.get("content", {}).get(AUTO_REPLY_FLAG)+ )+ if not triggered_by_auto_reply:+ handle = self._sender_handle(event)+ msg = _ADDRESSING_DENIED_MESSAGE+ already_tagged = _mention_regex(handle).search(msg) is not None+ body = msg if already_tagged else f"@{handle} {msg}"+ await self.send_message(+ room.room_id,+ body,+ format="markdown",+ mentions=[event.sender],+ thread_root_id=reply_thread_root,+ extra_content={AUTO_REPLY_FLAG: True},+ )+ return False+def _args_tag_my_name(self, text: str) -> bool:"""True when `text` contains our own `@name` at a full-token boundary(so a name that is a prefix of a longer one is not falsely matched)."""diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 4b8b12bf9..72a5b9c80 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -120,6 +120,11 @@ class Agent(Base):Text, ForeignKey("agents.id", ondelete="SET NULL"), nullable=True)oauth_client_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ # Scoped agent-addressing permissions (CHOO-1585). NULL preserves today's+ # open behaviour (anyone may address the agent); a stored policy is a+ # `switch_core.addressing.AddressingPolicy` blob (an allow-list of rules+ # over room / room-group / user / agent). See that module for the model.+ addressing_policy: Mapped[dict | None] = mapped_column(JSONB, nullable=True)metadata_: Mapped[dict | None] = mapped_column("metadata", JSONB, nullable=True)created_at: Mapped[str] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=Falsediff --git a/core/switch_core/db/stores/client_store.py b/core/switch_core/db/stores/client_store.pyindex 7538ef1f6..7c6d10307 100644--- a/core/switch_core/db/stores/client_store.py+++ b/core/switch_core/db/stores/client_store.py@@ -12,6 +12,14 @@ class ClientStore:async def get(self, session: AsyncSession, client_id: str) -> Client | None:return await session.get(Client, client_id)+ async def get_by_matrix_user_id(+ self, session: AsyncSession, matrix_user_id: str+ ) -> Client | None:+ result = await session.execute(+ select(Client).where(Client.matrix_user_id == matrix_user_id)+ )+ return result.scalar_one_or_none()+async def get_by_type(self, session: AsyncSession, client_type: str) -> list[Client]:diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.pyindex 78a6b6888..e3d53b797 100644--- a/core/switch_core/gateway/agents.py+++ b/core/switch_core/gateway/agents.py@@ -43,6 +43,7 @@ from switch_core.gateway.schemas import (RegisterKnownSubagentsRequest,RegisterKnownSubagentsResponse,RegisterOtherAgentRequest,+ UpdateAddressingPolicyRequest,UpdateAgentOptionsRequest,)from switch_core.gateway.subagent_registration import derive_subagent_registrations@@ -374,6 +375,56 @@ async def register_other_agent()[email protected]("/{agent_id}/addressing-policy")+async def update_addressing_policy(+ agent_id: str,+ req: UpdateAddressingPolicyRequest,+ session: Annotated[AsyncSession, Depends(get_session)],+ agent_store: Annotated[AgentStore, Depends(get_agent_store)],+ room_store: Annotated[RoomStore, Depends(get_room_store)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ protocol: Annotated[ProtocolService, Depends(get_protocol)],+ user: Annotated[User, Depends(get_current_user)],+) -> AgentDetail:+ """Set or clear an agent's scoped addressing policy (CHOO-1585).++ ``policy: null`` clears it (the agent becomes open to anyone). Only the+ agent's owner (or an admin) may change it.+ """+ agent = await agent_store.get(session, agent_id)+ if agent is None:+ raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")++ try:+ require_manage(Principal(user.id, user.role == "admin"), agent.owner_id)+ except PermissionError:+ raise HTTPException(+ status_code=403,+ detail="Only the agent's owner or an admin can change its addressing policy.",+ )++ stored = req.policy.model_dump() if req.policy is not None else None+ await agent_store.update(session, agent_id, addressing_policy=stored)+ await session.commit()++ logger.info(+ "Updated addressing policy for agent %s (%d rules) by user %s",+ agent.name,+ len(req.policy.rules) if req.policy is not None else 0,+ user.name,+ )++ return await assemble_agent_detail(+ session,+ agent=agent,+ agent_store=agent_store,+ room_store=room_store,+ user_store=user_store,+ agent_session_store=protocol.agent_session_store,+ room_role_store=protocol.room_role_store,+ )++# Declared after the literal GET routes (e.g. /known-types) so those are matched# first; otherwise this path-parameter route would capture them.@router.get("/{agent_id}")diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 87bb9e235..7fd815c73 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -4,6 +4,8 @@ from typing import Anyfrom pydantic import BaseModel+from switch_core.addressing import AddressingPolicy+# ── Rooms ─────────────────────────────────────────────────────────────────────@@ -281,6 +283,17 @@ class AgentDetail(AgentSummary):rooms: list[AgentRoomMembership]sessions: list[AgentSessionDetail]children: list[AgentSummary]+ # Scoped agent-addressing permissions (CHOO-1585). null → open (anyone may+ # address the agent); otherwise the allow-list that governs who can.+ addressing_policy: AddressingPolicy | None = None+++class UpdateAddressingPolicyRequest(BaseModel):+ """Set (or clear) an agent's scoped addressing policy.++ ``policy: null`` clears it — the agent becomes open to anyone again."""++ policy: AddressingPolicy | None = Noneclass KnownAgentType(BaseModel):diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 5dc7be891..1545b13e9 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -197,6 +197,7 @@ async def run() -> None:reference_store=reference_store,agent_session_store=agent_session_store,room_role_store=room_role_store,+ external_user_store=external_user_store,request_tracker=request_tracker,resource_request_tracker=resource_request_tracker,frontend_base_url=config.frontend_base_url,diff --git a/core/switch_core/migrations/versions/e4f5a6b7c8d9_add_addressing_policy_to_agents.py b/core/switch_core/migrations/versions/e4f5a6b7c8d9_add_addressing_policy_to_agents.pynew file mode 100644index 000000000..7cd0f0bcc--- /dev/null+++ b/core/switch_core/migrations/versions/e4f5a6b7c8d9_add_addressing_policy_to_agents.py@@ -0,0 +1,30 @@+"""add addressing_policy to agents (CHOO-1585)++Revision ID: e4f5a6b7c8d9+Revises: d3e4f5a6b7c8+Create Date: 2026-07-24 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++# revision identifiers, used by Alembic.+revision: str = "e4f5a6b7c8d9"+down_revision: str | None = "d3e4f5a6b7c8"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column(+ "agents",+ sa.Column("addressing_policy", postgresql.JSONB(), nullable=True),+ )+++def downgrade() -> None:+ op.drop_column("agents", "addressing_policy")diff --git a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.pynew file mode 100644index 000000000..2f7c4bdfb--- /dev/null+++ b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py@@ -0,0 +1,167 @@+from __future__ import annotations++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.types import AgentStatus+from switch_core.db.models import Agent, ApiKey, Client, Room, User+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.task_store import TaskStore+++def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:+ svc = object.__new__(ProtocolService)+ svc.session_factory = session_factory # type: ignore[attr-defined]+ svc.agent_store = AgentStore() # type: ignore[attr-defined]+ svc.room_store = RoomStore() # type: ignore[attr-defined]+ svc.task_store = TaskStore() # type: ignore[attr-defined]+ # No live matrix client → delegate_task skips the custom-event send.+ svc.client_lifecycle = _NoClients() # type: ignore[attr-defined]++ async def _status(_agent_id: str, _room_id: str) -> AgentStatus:+ return AgentStatus.NO_SESSION++ svc.get_agent_status = _status # type: ignore[attr-defined]+ return svc+++class _NoClients:+ def get_by_agent_id(self, _agent_id: str) -> None:+ return None+++async def _make_user(session: AsyncSession, name: str) -> User:+ user = User(name=name, email=f"{name}@test", role="user", password_hash="x")+ session.add(user)+ await session.flush()+ return user+++async def _make_agent(+ session: AsyncSession,+ name: str,+ *,+ owner_id: str,+ addressing_policy: dict | None = None,+) -> Agent:+ api_key = ApiKey(+ user_id=owner_id,+ key_hash=f"hash-{name}",+ encrypted_key="enc",+ label=name,+ type="agent",+ )+ client = Client(+ matrix_user_id=f"@{name}:test",+ display_name=name,+ type="agent",+ password="x",+ )+ session.add_all([api_key, client])+ await session.flush()+ agent = Agent(+ name=name,+ description=f"{name} desc",+ agent_type="session_addressable",+ connector_type="external",+ integration_profile={"connection_model": "session_passive"},+ client_id=client.id,+ api_key_id=api_key.id,+ owner_id=owner_id,+ addressing_policy=addressing_policy,+ )+ session.add(agent)+ await session.flush()+ return agent+++async def _make_room(+ session: AsyncSession, room_store: RoomStore, agent_ids: list[str]+) -> Room:+ room = Room(matrix_room_id="!room:test", name="Room", description="d")+ session.add(room)+ await session.flush()+ await room_store.add_agents(session, room.id, agent_ids)+ return room+++class TestDelegateAddressingGate:+ async def test_denied_delegation_raises(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _service(session_factory)+ async with session_factory() as session:+ owner = await _make_user(session, "owner")+ requester = await _make_agent(session, "req", owner_id=owner.id)+ # Performer only accepts a DIFFERENT agent, so `req` is not permitted.+ performer = await _make_agent(+ session,+ "perf",+ owner_id=owner.id,+ addressing_policy={+ "rules": [{"agents": ["someone-else"], "users": []}]+ },+ )+ room = await _make_room(+ session, svc.room_store, [requester.id, performer.id]+ )+ await session.commit()+ req_id, perf_id, room_id = requester.id, performer.id, room.id++ with pytest.raises(PermissionError, match="not permitted to address"):+ await svc.delegate_task(req_id, room_id, perf_id, "do it", "details")++ # Nothing was created — the gate fires before the Task row.+ async with session_factory() as session:+ tasks = await svc.task_store.get_by_room(session, room_id)+ assert tasks == []++ async def test_permitted_delegation_succeeds(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _service(session_factory)+ async with session_factory() as session:+ owner = await _make_user(session, "owner")+ requester = await _make_agent(session, "req", owner_id=owner.id)+ performer = await _make_agent(+ session,+ "perf",+ owner_id=owner.id,+ addressing_policy={"rules": [{"agents": ["req"], "users": []}]},+ )+ # Rule targets the requester by id — patch after we know the id.+ room = await _make_room(+ session, svc.room_store, [requester.id, performer.id]+ )+ await session.commit()+ req_id, perf_id, room_id = requester.id, performer.id, room.id++ async with session_factory() as session:+ await svc.agent_store.update(+ session,+ perf_id,+ addressing_policy={"rules": [{"agents": [req_id], "users": []}]},+ )+ await session.commit()++ result = await svc.delegate_task(req_id, room_id, perf_id, "do it", "details")+ assert result.task_id++ async def test_open_policy_allows_delegation(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _service(session_factory)+ async with session_factory() as session:+ owner = await _make_user(session, "owner")+ requester = await _make_agent(session, "req", owner_id=owner.id)+ performer = await _make_agent(session, "perf", owner_id=owner.id)+ room = await _make_room(+ session, svc.room_store, [requester.id, performer.id]+ )+ await session.commit()+ req_id, perf_id, room_id = requester.id, performer.id, room.id++ result = await svc.delegate_task(req_id, room_id, perf_id, "do it", "details")+ assert result.task_iddiff --git a/core/tests/switch_core/clients/test_addressing_enforcement.py b/core/tests/switch_core/clients/test_addressing_enforcement.pynew file mode 100644index 000000000..c69d8a2d2--- /dev/null+++ b/core/tests/switch_core/clients/test_addressing_enforcement.py@@ -0,0 +1,221 @@+from __future__ import annotations++from contextlib import asynccontextmanager+from types import SimpleNamespace++from switch_core.clients.agent_client import (+ _ADDRESSING_DENIED_MESSAGE,+ AUTO_REPLY_FLAG,+ AgentClient,+)+++@asynccontextmanager+async def _session_factory(): # type: ignore[no-untyped-def]+ yield object()+++def _meta(room_id: str = "room-1") -> SimpleNamespace:+ return SimpleNamespace(room_id=room_id)+++def _event(+ sender: str = "@u:switch.local", auto_reply: bool = False+) -> SimpleNamespace:+ content: dict = {"sender_name": "human"}+ if auto_reply:+ content[AUTO_REPLY_FLAG] = True+ return SimpleNamespace(+ sender=sender,+ body="@fixer help",+ source={"content": content},+ event_id="$evt",+ )+++class TestResolveSenderPrincipal:+ """mxid → Client → Agent (agent sender) or ExternalUser (human sender)."""++ def _client(self, *, client, agent, external_user) -> SimpleNamespace: # type: ignore[no-untyped-def]+ async def _get_by_mxid(_session, _mxid): # type: ignore[no-untyped-def]+ return client++ async def _agent_by_client(_session, _cid): # type: ignore[no-untyped-def]+ return agent++ async def _ext_by_client(_session, _cid): # type: ignore[no-untyped-def]+ return external_user++ return SimpleNamespace(+ client_store=SimpleNamespace(get_by_matrix_user_id=_get_by_mxid),+ _agent_store=SimpleNamespace(get_by_client_id=_agent_by_client),+ _external_user_store=SimpleNamespace(get_by_client_id=_ext_by_client),+ )++ async def test_agent_sender(self) -> None:+ client = self._client(+ client=SimpleNamespace(id="c1"),+ agent=SimpleNamespace(id="agent-7"),+ external_user=None,+ )+ result = await AgentClient._resolve_sender_principal(+ client, object(), "@a:switch.local"+ )+ assert result == ("agent", "agent-7")++ async def test_human_sender(self) -> None:+ client = self._client(+ client=SimpleNamespace(id="c1"),+ agent=None,+ external_user=SimpleNamespace(id="ext-3"),+ )+ result = await AgentClient._resolve_sender_principal(+ client, object(), "@u:switch.local"+ )+ assert result == ("user", "ext-3")++ async def test_unknown_client_is_none(self) -> None:+ client = self._client(client=None, agent=None, external_user=None)+ result = await AgentClient._resolve_sender_principal(+ client, object(), "@ghost:switch.local"+ )+ assert result is None++ async def test_client_with_no_agent_or_external_user_is_none(self) -> None:+ # A Client that is neither an agent nor a bridged human (e.g. a system+ # client) does not resolve to an addressing principal.+ client = self._client(+ client=SimpleNamespace(id="c1"), agent=None, external_user=None+ )+ result = await AgentClient._resolve_sender_principal(+ client, object(), "@system:switch.local"+ )+ assert result is None+++def _allowed_client(+ *,+ policy: dict | None,+ principal: tuple[str, str] | None,+ group_id: str | None = None,+) -> SimpleNamespace:+ """Fake client for _addressing_allowed: the agent carries `policy`, the+ sender resolves to `principal`, and the room has `group_id`."""++ agent = SimpleNamespace(name="fixer", addressing_policy=policy)++ async def _fresh_agent(): # type: ignore[no-untyped-def]+ return agent++ async def _resolve(_session, _mxid): # type: ignore[no-untyped-def]+ return principal++ async def _get_room(_session, _room_id): # type: ignore[no-untyped-def]+ return SimpleNamespace(group_id=group_id)++ return SimpleNamespace(+ agent=agent,+ _fresh_agent=_fresh_agent,+ session_factory=_session_factory,+ _resolve_sender_principal=_resolve,+ _room_store=SimpleNamespace(get=_get_room),+ )+++class TestAddressingAllowed:+ async def test_open_policy_allows_without_lookup(self) -> None:+ # No policy → open; must not even need a resolvable sender.+ client = _allowed_client(policy=None, principal=None)+ assert await AgentClient._addressing_allowed(client, _event(), _meta()) is True++ async def test_permitted_sender(self) -> None:+ policy = {"rules": [{"users": ["ext-3"], "agents": []}]}+ client = _allowed_client(policy=policy, principal=("user", "ext-3"))+ assert await AgentClient._addressing_allowed(client, _event(), _meta()) is True++ async def test_denied_sender(self) -> None:+ policy = {"rules": [{"users": ["ext-3"], "agents": []}]}+ client = _allowed_client(policy=policy, principal=("user", "someone-else"))+ assert await AgentClient._addressing_allowed(client, _event(), _meta()) is False++ async def test_unresolvable_sender_fails_closed(self) -> None:+ # A restricted agent must not be addressable by an unresolvable sender.+ policy = {"rules": [{"users": ["ext-3"], "agents": []}]}+ client = _allowed_client(policy=policy, principal=None)+ assert await AgentClient._addressing_allowed(client, _event(), _meta()) is False++ async def test_group_scoped_policy(self) -> None:+ policy = {"rules": [{"room_groups": ["g1"], "agents": []}]}+ allowed = _allowed_client(+ policy=policy, principal=("user", "u1"), group_id="g1"+ )+ denied = _allowed_client(policy=policy, principal=("user", "u1"), group_id="g2")+ assert await AgentClient._addressing_allowed(allowed, _event(), _meta()) is True+ assert await AgentClient._addressing_allowed(denied, _event(), _meta()) is False+++def _gate_client(*, allowed: bool) -> SimpleNamespace:+ """Fake client for _gate_addressed: records any auto-reply sent."""+ sent: list[dict] = []++ async def _addressing_allowed(_event, _meta): # type: ignore[no-untyped-def]+ return allowed++ async def _send_message(room_id, body, **kwargs): # type: ignore[no-untyped-def]+ sent.append({"room_id": room_id, "body": body, **kwargs})++ def _sender_handle(_event): # type: ignore[no-untyped-def]+ return "human"++ client = SimpleNamespace(+ _addressing_allowed=_addressing_allowed,+ send_message=_send_message,+ _sender_handle=_sender_handle,+ )+ client.sent = sent # type: ignore[attr-defined]+ return client+++def _room() -> SimpleNamespace:+ return SimpleNamespace(room_id="!matrix:switch.local")+++class TestGateAddressed:+ async def test_not_addressed_short_circuits(self) -> None:+ client = _gate_client(allowed=False)+ result = await AgentClient._gate_addressed(+ client, _room(), _event(), _meta(), "$root", False+ )+ assert result is False+ assert client.sent == [] # no reply for an untagged message++ async def test_allowed_stays_addressed(self) -> None:+ client = _gate_client(allowed=True)+ result = await AgentClient._gate_addressed(+ client, _room(), _event(), _meta(), "$root", True+ )+ assert result is True+ assert client.sent == []++ async def test_denied_demotes_and_replies(self) -> None:+ client = _gate_client(allowed=False)+ result = await AgentClient._gate_addressed(+ client, _room(), _event(), _meta(), "$root", True+ )+ assert result is False+ assert len(client.sent) == 1+ reply = client.sent[0]+ assert _ADDRESSING_DENIED_MESSAGE in reply["body"]+ assert reply["body"].startswith("@human")+ # Guarded so a denied auto-reply can't re-trigger another one.+ assert reply["extra_content"] == {AUTO_REPLY_FLAG: True}+ assert reply["thread_root_id"] == "$root"++ async def test_denied_auto_reply_does_not_ping_pong(self) -> None:+ # If the tagging message was itself an auto-reply, do not reply again.+ client = _gate_client(allowed=False)+ result = await AgentClient._gate_addressed(+ client, _room(), _event(auto_reply=True), _meta(), "$root", True+ )+ assert result is False+ assert client.sent == []diff --git a/core/tests/switch_core/clients/test_no_session_reply_threading.py b/core/tests/switch_core/clients/test_no_session_reply_threading.pyindex ab0554e54..2db474b38 100644--- a/core/tests/switch_core/clients/test_no_session_reply_threading.py+++ b/core/tests/switch_core/clients/test_no_session_reply_threading.py@@ -39,6 +39,16 @@ def _fake_self(async def _compute_addressed(_event: object, _meta: object) -> bool:return True # addressed → the offline auto-reply path runs+ async def _gate_addressed(+ _room: object,+ _event: object,+ _meta: object,+ _reply_thread_root: str,+ is_addressed: bool,+ ) -> bool:+ # No addressing policy in these tests — pass the addressed flag through.+ return is_addressed+async def _is_available(_room_id: str) -> bool:return False # no live session → triggers the auto-reply@@ -49,6 +59,7 @@ def _fake_self(agent=SimpleNamespace(id="agent-1", name="cc-bug-fixing"),_resolve_room_meta=_resolve_room_meta,_compute_addressed=_compute_addressed,+ _gate_addressed=_gate_addressed,_is_available=_is_available,_reply_when_unavailable_here=_reply_when_unavailable_here,send_message=send_message,diff --git a/core/tests/switch_core/test_addressing.py b/core/tests/switch_core/test_addressing.pynew file mode 100644index 000000000..f8c00df86--- /dev/null+++ b/core/tests/switch_core/test_addressing.py@@ -0,0 +1,141 @@+from __future__ import annotations++import pytest+from pydantic import ValidationError++from switch_core.addressing import (+ AddressingPolicy,+ AddressingRule,+ can_address,+ parse_policy,+)+++def _allows(policy: AddressingPolicy, **kw: object) -> bool:+ defaults = dict(room_id="room-1", group_id=None, sender_kind="user", sender_id="u1")+ defaults.update(kw)+ return can_address(policy, **defaults) # type: ignore[arg-type]+++class TestOpenPolicy:+ """No rules → open: anyone may address (today's behaviour, preserved)."""++ def test_empty_policy_allows_everyone(self) -> None:+ policy = AddressingPolicy()+ assert policy.is_open() is True+ assert _allows(policy, sender_kind="user", sender_id="anyone") is True+ assert _allows(policy, sender_kind="agent", sender_id="any-agent") is True++ def test_parse_none_is_open(self) -> None:+ assert parse_policy(None).is_open() is True++ def test_parse_empty_dict_is_open(self) -> None:+ assert parse_policy({}).is_open() is True++ def test_policy_with_rules_is_not_open(self) -> None:+ policy = AddressingPolicy(rules=[AddressingRule()])+ assert policy.is_open() is False+++class TestDenyByDefault:+ """With rules present, only matching attempts are permitted."""++ def test_wildcard_rule_allows_all(self) -> None:+ # A single all-"*" rule is equivalent to open, but explicitly so.+ policy = AddressingPolicy(rules=[AddressingRule()])+ assert _allows(policy, sender_kind="user", sender_id="u1") is True+ assert _allows(policy, sender_kind="agent", sender_id="a1") is True++ def test_non_matching_room_denied(self) -> None:+ policy = AddressingPolicy(rules=[AddressingRule(rooms=["room-9"])])+ assert _allows(policy, room_id="room-1") is False+ assert _allows(policy, room_id="room-9") is True+++class TestSenderKinds:+ """`users` matches human senders; `agents` matches agent senders. The two+ are independent: an empty list on one kind excludes it entirely."""++ def test_users_only_excludes_agents(self) -> None:+ # owner-only shape: allow one human, no agents.+ policy = AddressingPolicy(rules=[AddressingRule(users=["owner"], agents=[])])+ assert _allows(policy, sender_kind="user", sender_id="owner") is True+ assert _allows(policy, sender_kind="user", sender_id="someone") is False+ assert _allows(policy, sender_kind="agent", sender_id="owner") is False++ def test_agents_only_excludes_users(self) -> None:+ policy = AddressingPolicy(rules=[AddressingRule(users=[], agents=["a1"])])+ assert _allows(policy, sender_kind="agent", sender_id="a1") is True+ assert _allows(policy, sender_kind="agent", sender_id="a2") is False+ assert _allows(policy, sender_kind="user", sender_id="a1") is False++ def test_empty_subset_matches_nothing(self) -> None:+ # A rule with both sender dimensions empty admits no one.+ policy = AddressingPolicy(rules=[AddressingRule(users=[], agents=[])])+ assert _allows(policy, sender_kind="user", sender_id="u1") is False+ assert _allows(policy, sender_kind="agent", sender_id="a1") is False+++class TestRoomAndGroupScoping:+ def test_room_subset(self) -> None:+ policy = AddressingPolicy(rules=[AddressingRule(rooms=["r1", "r2"])])+ assert _allows(policy, room_id="r1") is True+ assert _allows(policy, room_id="r3") is False++ def test_group_subset(self) -> None:+ policy = AddressingPolicy(rules=[AddressingRule(room_groups=["g1"])])+ assert _allows(policy, group_id="g1") is True+ assert _allows(policy, group_id="g2") is False++ def test_ungrouped_room_only_matches_wildcard_group(self) -> None:+ # group_id None (ungrouped room) is admitted by "*" but not by a subset.+ wildcard = AddressingPolicy(rules=[AddressingRule(room_groups="*")])+ subset = AddressingPolicy(rules=[AddressingRule(room_groups=["g1"])])+ assert _allows(wildcard, group_id=None) is True+ assert _allows(subset, group_id=None) is False++ def test_room_and_group_are_conjunctive(self) -> None:+ # Both must match within a single rule.+ policy = AddressingPolicy(+ rules=[AddressingRule(rooms=["r1"], room_groups=["g1"])]+ )+ assert _allows(policy, room_id="r1", group_id="g1") is True+ assert _allows(policy, room_id="r1", group_id="g2") is False+ assert _allows(policy, room_id="r2", group_id="g1") is False+++class TestMultipleRules:+ def test_any_rule_permits(self) -> None:+ # Two rules: humans in r1, or agent a1 anywhere.+ policy = AddressingPolicy(+ rules=[+ AddressingRule(rooms=["r1"], agents=[]),+ AddressingRule(agents=["a1"], users=[]),+ ]+ )+ assert _allows(policy, room_id="r1", sender_kind="user", sender_id="u1") is True+ assert (+ _allows(policy, room_id="r2", sender_kind="user", sender_id="u1") is False+ )+ assert (+ _allows(policy, room_id="r2", sender_kind="agent", sender_id="a1") is True+ )+ assert (+ _allows(policy, room_id="r2", sender_kind="agent", sender_id="a2") is False+ )+++class TestValidation:+ def test_rejects_bad_dimension_scalar(self) -> None:+ with pytest.raises(ValidationError):+ AddressingRule(rooms="everyone") # type: ignore[arg-type]++ def test_rejects_non_string_ids(self) -> None:+ with pytest.raises(ValidationError):+ AddressingRule(users=[1, 2]) # type: ignore[list-item]++ def test_roundtrips_through_dict(self) -> None:+ policy = AddressingPolicy(+ rules=[AddressingRule(rooms=["r1"], users=["u1"], agents=[])]+ )+ assert parse_policy(policy.model_dump()) == policydiff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.tsindex 5766413ea..8b40b5952 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts@@ -10,6 +10,7 @@ import { sshConnectionIdForHost } from '@main/core/locations/location-transport'import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';import type { AgentProviderKind } from '@shared/core/switch-servers/switch-servers';import type {+ AddressingPolicy,AddServerParams,AgentDefaults,AgentVerifyResult,@@ -19,6 +20,8 @@ import type {ProvisionRemoteAgentParams,RemoteAgentRoom,RemoteAgentSummary,+ RemoteExternalUser,+ RemoteRoomGroup,RemoteRoomRole,RemoteRoomSummary,RenameServerParams,@@ -32,15 +35,19 @@ import { createRPCController } from '@shared/lib/ipc/rpc';import { type LoginError, oidcLogin, passwordLogin } from './auth';import {agentExistsOnServer,+ fetchAddressingPolicy,fetchAgentDetail,fetchAgentRooms,fetchAgents,+ fetchAllExternalUsers,fetchAuthConfig,fetchMe,+ fetchRoomGroups,fetchRoomRoles,fetchRooms,GatewayError,registerKnownAgent,+ updateAddressingPolicy,} from './gateway-client';import { openAuthenticatedGatewayPage } from './gateway-web';import {@@ -209,6 +216,25 @@ export const switchServersController = createRPCController({listRoomRoles: async (params: { serverId: string; roomId: string }): Promise<RemoteRoomRole[]> =>fetchRoomRoles(await requireServer(params.serverId), params.roomId),+ listRemoteRoomGroups: async (serverId: string): Promise<RemoteRoomGroup[]> =>+ fetchRoomGroups(await requireServer(serverId)),++ listRemoteExternalUsers: async (serverId: string): Promise<RemoteExternalUser[]> =>+ fetchAllExternalUsers(await requireServer(serverId)),++ getAddressingPolicy: async (params: {+ serverId: string;+ agentId: string;+ }): Promise<AddressingPolicy | null> =>+ fetchAddressingPolicy(await requireServer(params.serverId), params.agentId),++ updateAddressingPolicy: async (params: {+ serverId: string;+ agentId: string;+ policy: AddressingPolicy | null;+ }): Promise<void> =>+ updateAddressingPolicy(await requireServer(params.serverId), params.agentId, params.policy),+verifyAgent: async (params: {serverId: string;agentId: string;diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.tsindex 10bf7ffa2..bf9a76696 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts@@ -1,6 +1,9 @@import type {+ AddressingPolicy,RemoteAgentRoom,RemoteAgentSummary,+ RemoteExternalUser,+ RemoteRoomGroup,RemoteRoomRole,RemoteRoomSummary,SwitchAuthConfig,@@ -391,6 +394,69 @@ export async function setAutoSession(await updateKnownAgentOptions(server, agentId, { ...options, auto_session: enabled });}+/**+ * Fetch an agent's scoped addressing policy (CHOO-1585) from `GET /agents/{id}`.+ * Returns null when the agent is open (no policy set).+ */+export async function fetchAddressingPolicy(+ server: SwitchServer,+ agentId: string+): Promise<AddressingPolicy | null> {+ const res = await gatewayFetch(server, `/agents/${encodeURIComponent(agentId)}`, {+ authenticated: true,+ });+ const json = (await res.json()) as {+ addressing_policy?: AddressingPolicy | null;+ };+ return json.addressing_policy ?? null;+}++/**+ * Set (or clear, with `policy = null`) an agent's addressing policy+ * (`PUT /agents/{id}/addressing-policy`). Only the agent's owner (or an admin)+ * may change it; a non-owner request surfaces as a `GatewayError`.+ */+export async function updateAddressingPolicy(+ server: SwitchServer,+ agentId: string,+ policy: AddressingPolicy | null+): Promise<void> {+ await gatewayFetch(server, `/agents/${encodeURIComponent(agentId)}/addressing-policy`, {+ authenticated: true,+ method: 'PUT',+ body: { policy },+ });+}++/** List a server's room groups (`GET /room-groups`), for the addressing-rule+ * room-group selector. */+export async function fetchRoomGroups(server: SwitchServer): Promise<RemoteRoomGroup[]> {+ const res = await gatewayFetch(server, '/room-groups', { authenticated: true });+ const json = (await res.json()) as Array<{ id: string; name: string }>;+ return json.map((g) => ({ id: g.id, name: g.name }));+}++/**+ * Union of external (bridged human) users across every bridge on the server+ * (`GET /collaborations`, then each bridge's `/users`). The addressing policy's+ * `users` dimension keys off these ExternalUser ids.+ */+export async function fetchAllExternalUsers(server: SwitchServer): Promise<RemoteExternalUser[]> {+ const bridgesRes = await gatewayFetch(server, '/collaborations', { authenticated: true });+ const bridges = (await bridgesRes.json()) as Array<{ bridge_id: string }>;+ const byId = new Map<string, RemoteExternalUser>();+ for (const bridge of bridges) {+ const res = await gatewayFetch(+ server,+ `/collaborations/${encodeURIComponent(bridge.bridge_id)}/users`,+ { authenticated: true }+ );+ const users = (await res.json()) as Array<{ id: string; external_username: string }>;+ for (const u of users) byId.set(u.id, { id: u.id, username: u.external_username });+ }+ return [...byId.values()];+}+/** A gateway child agent (e.g. a Claude Code subagent) of some parent agent. */export type RemoteChildAgent = {id: string;diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex e6921dd8a..836c6a7a3 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -8,6 +8,7 @@ import type {} from '@renderer/features/locations/stores/agent-onboarding-types';import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';+import { policyHasDeadRule } from '@renderer/features/switch-servers/addressing-policy-editor';import type { ServerVerifyState } from '@renderer/features/switch-servers/agent-server-picker';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { toast } from '@renderer/lib/hooks/use-toast';@@ -203,6 +204,7 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocisMissingSwitchAgent &&!isChecking &&configureForm.isValid &&+ !policyHasDeadRule(configureForm.addressingPolicy) &&!!pickState.serverId &&!!pickState.providerId &&remoteRunValid &&@@ -216,6 +218,7 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocisMissingRemoteAgent &&!isChecking &&remoteConfigureForm.isValid &&+ !policyHasDeadRule(remoteConfigureForm.addressingPolicy) &&!!pickState.serverId &&!!pickState.providerId &&trimmedRemoteDir.length > 0 &&@@ -400,6 +403,13 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocsetSubmitState('idle');return;}+ if (configureForm.addressingPolicy !== null) {+ await rpc.switchServers.updateAddressingPolicy({+ serverId: pickState.serverId,+ agentId: result.agentId,+ policy: configureForm.addressingPolicy,+ });+ }// Credentials are now written to .claude/settings.local.json, so the// create path re-detects the agent and verifies it on the server, and the// selected subagents can be registered under the just-created parent.@@ -446,6 +456,13 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocsetSubmitState('idle');return;}+ if (remoteConfigureForm.addressingPolicy !== null) {+ await rpc.switchServers.updateAddressingPolicy({+ serverId: pickState.serverId,+ agentId: result.agentId,+ policy: remoteConfigureForm.addressingPolicy,+ });+ }// Credentials are now written to the remote dir's .claude/settings.local.json,// so the create path (createRemoteLocation) re-detects the agent over SSH and// verifies it on the server, and the selected subagents can be registereddiff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsxindex 1995a20a0..861e4fe29 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx@@ -1,7 +1,13 @@+import { useQuery } from '@tanstack/react-query';import { CircleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect, useId } from 'react';+import {+ AddressingPolicyEditor,+ type OptionItem,+} from '@renderer/features/switch-servers/addressing-policy-editor';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { rpc } from '@renderer/lib/ipc';import { Button } from '@renderer/lib/ui/button';import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';@@ -49,6 +55,44 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({const servers = switchServersStore.servers;+ // Selector data for the addressing-policy editor, scoped to the chosen server.+ const roomsQuery = useQuery({+ queryKey: ['remote-rooms', serverId],+ queryFn: () => rpc.switchServers.listRemoteRooms(serverId as string),+ enabled: serverId !== null,+ });+ const groupsQuery = useQuery({+ queryKey: ['remote-room-groups', serverId],+ queryFn: () => rpc.switchServers.listRemoteRoomGroups(serverId as string),+ enabled: serverId !== null,+ });+ const usersQuery = useQuery({+ queryKey: ['remote-external-users', serverId],+ queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId as string),+ enabled: serverId !== null,+ });+ const agentsQuery = useQuery({+ queryKey: ['remote-agents', serverId],+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId as string),+ enabled: serverId !== null,+ });+ const roomOptions: OptionItem[] = (roomsQuery.data ?? []).map((r) => ({+ id: r.id,+ label: r.name,+ }));+ const groupOptions: OptionItem[] = (groupsQuery.data ?? []).map((g) => ({+ id: g.id,+ label: g.name,+ }));+ const userOptions: OptionItem[] = (usersQuery.data ?? []).map((u) => ({+ id: u.id,+ label: u.username,+ }));+ const agentOptions: OptionItem[] = (agentsQuery.data ?? []).map((a) => ({+ id: a.id,+ label: a.name,+ }));+if (servers.length === 0) {return (<div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs text-foreground-muted">@@ -186,6 +230,22 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({/></label></Field>++ <Field>+ <FieldLabel>Who can address this agent</FieldLabel>+ <span className="text-xs text-foreground-muted">+ Restrict who may @mention, target, or delegate tasks to the agent. Defaults to open+ (anyone in the room). You can change this later from the agent's settings.+ </span>+ <AddressingPolicyEditor+ value={form.addressingPolicy}+ onChange={form.setAddressingPolicy}+ rooms={roomOptions}+ roomGroups={groupOptions}+ users={userOptions}+ agents={agentOptions}+ />+ </Field></FieldGroup>);});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.tsindex 65d5cd1d4..7c5677685 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts@@ -2,7 +2,10 @@ import { useQuery } from '@tanstack/react-query';import { useEffect, useState } from 'react';import { rpc } from '@renderer/lib/ipc';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import type { AgentProviderKind } from '@shared/core/switch-servers/switch-servers';+import type {+ AddressingPolicy,+ AgentProviderKind,+} from '@shared/core/switch-servers/switch-servers';import { basenameFromAnyPath } from '@shared/path-name';/** Switch agent-name charset, enforced server-side too: lowercase letters,@@ -62,6 +65,9 @@ export function useConfigureAgentForm(dir: string, defaultAutoApprove: boolean)const [notifyUser, setNotifyUser] = useState('');const [autoSession, setAutoSession] = useState(true);const [autoApprove, setAutoApprove] = useState(defaultAutoApprove);+ // Scoped addressing policy (CHOO-1585). null = open (default); set to restrict+ // who can address the new agent. Applied via a follow-up PUT after creation.+ const [addressingPolicy, setAddressingPolicy] = useState<AddressingPolicy | null>(null);const trimmedDir = dir.trim();// suggestAgentDefaults derives name/description from the directory basename and@@ -106,6 +112,8 @@ export function useConfigureAgentForm(dir: string, defaultAutoApprove: boolean)setAutoSession,autoApprove,setAutoApprove,+ addressingPolicy,+ setAddressingPolicy,isValid,};}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsxnew file mode 100644index 000000000..76e5e7569--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx@@ -0,0 +1,145 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { useState } from 'react';+import {+ AddressingPolicyEditor,+ type OptionItem,+ policyHasDeadRule,+} from '@renderer/features/switch-servers/addressing-policy-editor';+import { rpc } from '@renderer/lib/ipc';+import { Button } from '@renderer/lib/ui/button';+import { Field, FieldDescription, FieldTitle } from '@renderer/lib/ui/field';+import { log } from '@renderer/utils/logger';+import type { AddressingPolicy } from '@shared/core/switch-servers/switch-servers';++/**+ * Per-Switch-agent scoped addressing policy (CHOO-1585) — who may address the+ * agent (@mention, targeted message, task delegation). One editor per+ * Switch-linked agent in the location; hidden when the location has none.+ */+export function AddressingPolicySettingsSection({ locationId }: { locationId: string }) {+ const { data: agents } = useQuery({+ queryKey: ['location-agents', locationId],+ queryFn: () => rpc.agents.getAgents(locationId),+ });++ const switchAgents = (agents ?? []).filter((a) => a.serverId && a.switchAgentId);+ if (switchAgents.length === 0) return null;++ return (+ <Field>+ <FieldTitle>Who can address this agent</FieldTitle>+ <FieldDescription className="text-foreground-muted">+ Restrict who may @mention, target, or delegate tasks to the agent. Open means any room+ participant can; restricted permits only senders matching a rule.+ </FieldDescription>+ <div className="flex flex-col gap-4">+ {switchAgents.map((agent) => (+ <AddressingPolicyRow+ key={agent.id}+ serverId={agent.serverId as string}+ agentId={agent.switchAgentId as string}+ agentName={agent.name}+ showName={switchAgents.length > 1}+ />+ ))}+ </div>+ </Field>+ );+}++function AddressingPolicyRow({+ serverId,+ agentId,+ agentName,+ showName,+}: {+ serverId: string;+ agentId: string;+ agentName: string;+ showName: boolean;+}) {+ const queryClient = useQueryClient();+ const [draft, setDraft] = useState<AddressingPolicy | null>(null);+ const [dirty, setDirty] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const policyKey = ['agent-addressing-policy', serverId, agentId];+ const { data: saved } = useQuery({+ queryKey: policyKey,+ queryFn: () => rpc.switchServers.getAddressingPolicy({ serverId, agentId }),+ });+ const rooms = useQuery({+ queryKey: ['remote-rooms', serverId],+ queryFn: () => rpc.switchServers.listRemoteRooms(serverId),+ });+ const groups = useQuery({+ queryKey: ['remote-room-groups', serverId],+ queryFn: () => rpc.switchServers.listRemoteRoomGroups(serverId),+ });+ const users = useQuery({+ queryKey: ['remote-external-users', serverId],+ queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId),+ });+ const remoteAgents = useQuery({+ queryKey: ['remote-agents', serverId],+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId),+ });++ // Until the user edits, show the saved policy; once dirty, show the draft.+ const value = dirty ? draft : (saved ?? null);++ const mutation = useMutation({+ mutationFn: (policy: AddressingPolicy | null) =>+ rpc.switchServers.updateAddressingPolicy({ serverId, agentId, policy }),+ onSuccess: (_result, policy) => {+ queryClient.setQueryData(policyKey, policy);+ setDirty(false);+ setError(null);+ },+ onError: (err) => {+ setError(err instanceof Error ? err.message : 'Failed to save policy');+ log.error('Failed to update addressing policy', { agentId, error: err });+ },+ });++ const roomOptions: OptionItem[] = (rooms.data ?? []).map((r) => ({ id: r.id, label: r.name }));+ const groupOptions: OptionItem[] = (groups.data ?? []).map((g) => ({ id: g.id, label: g.name }));+ const userOptions: OptionItem[] = (users.data ?? []).map((u) => ({+ id: u.id,+ label: u.username,+ }));+ const agentOptions: OptionItem[] = (remoteAgents.data ?? []).map((a) => ({+ id: a.id,+ label: a.name,+ }));+ // Prefer the registered Switch agent name over the local directory basename.+ const displayName = agentOptions.find((o) => o.id === agentId)?.label ?? agentName;++ return (+ <div className="flex flex-col gap-2 rounded-md border border-border p-3">+ {showName && <span className="text-sm font-medium">{displayName}</span>}+ <AddressingPolicyEditor+ value={value}+ onChange={(next) => {+ setDraft(next);+ setDirty(true);+ }}+ rooms={roomOptions}+ roomGroups={groupOptions}+ users={userOptions}+ agents={agentOptions}+ disabled={mutation.isPending}+ />+ {error && <span className="text-destructive text-xs">{error}</span>}+ <div>+ <Button+ size="sm"+ disabled={!dirty || mutation.isPending || policyHasDeadRule(value)}+ onClick={() => mutation.mutate(value)}+ >+ Save policy+ </Button>+ </div>+ </div>+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsxindex 981fe4ee9..48fea441f 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsx@@ -18,39 +18,56 @@ export function AutoApproveSettingsSection({ locationId }: { locationId: stringqueryFn: () => rpc.agents.getAgents(locationId),});- if ((agents ?? []).length === 0) return null;+ const list = agents ?? [];+ if (list.length === 0) return null;+ // Single-agent locations don't need the (directory-derived) agent name label —+ // the section title identifies the setting, so the toggle sits inline with it.+ const single = list.length === 1 ? list[0] : null;return (<Field>- <FieldTitle>Bypass permissions</FieldTitle>+ <div className="flex items-center justify-between gap-3">+ <FieldTitle>Bypass permissions</FieldTitle>+ {single && (+ <AutoApproveSwitch+ agentId={single.id}+ enabled={single.autoApprove}+ locationId={locationId}+ />+ )}+ </div><FieldDescription className="text-foreground-muted">When on, switchdash starts this agent's sessions with permission prompts bypassed (theprovider's auto-approve flag). Off by default; turn it on only for agents you trust torun unattended.</FieldDescription>- <div className="flex flex-col gap-2">- {(agents ?? []).map((agent) => (- <AutoApproveRow- key={agent.id}- agentId={agent.id}- agentName={agent.name}- enabled={agent.autoApprove}- locationId={locationId}- />- ))}- </div>+ {!single && (+ <div className="flex flex-col gap-2">+ {list.map((agent) => (+ <div+ key={agent.id}+ className="flex items-center justify-between gap-3 rounded-md border border-border px-2 py-1.5"+ >+ <span className="truncate text-sm">{agent.name}</span>+ <AutoApproveSwitch+ agentId={agent.id}+ enabled={agent.autoApprove}+ locationId={locationId}+ />+ </div>+ ))}+ </div>+ )}</Field>);}-function AutoApproveRow({+function AutoApproveSwitch({agentId,- agentName,enabled,locationId,}: {agentId: string;- agentName: string;enabled: boolean;locationId: string;}) {@@ -69,13 +86,10 @@ function AutoApproveRow({});return (- <div className="flex items-center justify-between gap-3 rounded-md border border-border px-2 py-1.5">- <span className="truncate text-sm">{agentName}</span>- <Switch- checked={enabled}- disabled={mutation.isPending}- onCheckedChange={(checked) => mutation.mutate(checked)}- />- </div>+ <Switch+ checked={enabled}+ disabled={mutation.isPending}+ onCheckedChange={(checked) => mutation.mutate(checked)}+ />);}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-session-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-session-settings-section.tsxindex d18cb72c2..a4450d1e4 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-session-settings-section.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-session-settings-section.tsx@@ -1,5 +1,6 @@import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { useState } from 'react';+import { useRemoteAgentName } from '@renderer/features/switch-servers/use-remote-agent-name';import { rpc } from '@renderer/lib/ipc';import { Field, FieldDescription, FieldTitle } from '@renderer/lib/ui/field';import { Switch } from '@renderer/lib/ui/switch';@@ -20,25 +21,58 @@ export function AutoSessionSettingsSection({ locationId }: { locationId: stringconst switchAgents = (agents ?? []).filter((a) => a.serverId && a.switchAgentId);if (switchAgents.length === 0) return null;+ // The agent name only disambiguates when a location has more than one agent;+ // for the common single-agent case the section title already identifies it, so+ // the toggle sits inline with the title instead of in a redundant named row.+ const single = switchAgents.length === 1 ? switchAgents[0] : null;return (<Field>- <FieldTitle>Auto-create a session on notify</FieldTitle>+ <div className="flex items-center justify-between gap-3">+ <FieldTitle>Auto-create a session on notify</FieldTitle>+ {single && <AutoSessionSwitch agentId={single.id} />}+ </div><FieldDescription className="text-foreground-muted">When on, switchdash watches this agent's Switch rooms and automatically starts asession — connected to the room and ready to reply — whenever it's addressed with nosession running.</FieldDescription>- <div className="flex flex-col gap-2">- {switchAgents.map((agent) => (- <AutoSessionRow key={agent.id} agentId={agent.id} agentName={agent.name} />- ))}- </div>+ {!single && (+ <div className="flex flex-col gap-2">+ {switchAgents.map((agent) => (+ <div+ key={agent.id}+ className="flex items-center justify-between gap-3 rounded-md border border-border px-2 py-1.5"+ >+ <AgentLabel+ serverId={agent.serverId as string}+ switchAgentId={agent.switchAgentId as string}+ fallback={agent.name}+ />+ <AutoSessionSwitch agentId={agent.id} />+ </div>+ ))}+ </div>+ )}</Field>);}-function AutoSessionRow({ agentId, agentName }: { agentId: string; agentName: string }) {+/** Renders an agent's registered Switch name (not the directory basename). */+function AgentLabel({+ serverId,+ switchAgentId,+ fallback,+}: {+ serverId: string;+ switchAgentId: string;+ fallback: string;+}) {+ const name = useRemoteAgentName(serverId, switchAgentId, fallback);+ return <span className="truncate text-sm">{name}</span>;+}++function AutoSessionSwitch({ agentId }: { agentId: string }) {const queryClient = useQueryClient();const [pending, setPending] = useState(false);@@ -65,13 +99,10 @@ function AutoSessionRow({ agentId, agentName }: { agentId: string; agentName: st});return (- <div className="flex items-center justify-between gap-3 rounded-md border border-border px-2 py-1.5">- <span className="truncate text-sm">{agentName}</span>- <Switch- checked={enabled === true}- disabled={isLoading || pending}- onCheckedChange={(checked) => mutation.mutate(checked)}- />- </div>+ <Switch+ checked={enabled === true}+ disabled={isLoading || pending}+ onCheckedChange={(checked) => mutation.mutate(checked)}+ />);}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsxindex 74e2efa7a..a37f3ab9a 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx@@ -1,4 +1,5 @@import { observer } from 'mobx-react-lite';+import { AddressingPolicySettingsSection } from '@renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section';import { AutoApproveSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-approve-settings-section';import { AutoSessionSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-session-settings-section';import { SubagentAutoSessionSettingsSection } from '@renderer/features/locations/components/settings-view/sections/subagent-auto-session-settings-section';@@ -31,6 +32,7 @@ export const SettingsPanel = observer(function SettingsPanel() {<><AutoSessionSettingsSection locationId={locationId} /><AutoApproveSettingsSection locationId={locationId} />+ <AddressingPolicySettingsSection locationId={locationId} /></>)}</div>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsxnew file mode 100644index 000000000..fe5c24dee--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsx@@ -0,0 +1,454 @@+import { Trash2, X } from 'lucide-react';+import { useState } from 'react';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import { Input } from '@renderer/lib/ui/input';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@renderer/lib/ui/select';+import type {+ AddressingDimension,+ AddressingPolicy,+ AddressingRule,+} from '@shared/core/switch-servers/switch-servers';++export type OptionItem = { id: string; label: string };++type DimKey = 'rooms' | 'room_groups' | 'users' | 'agents';++const EMPTY_RULE: AddressingRule = { rooms: '*', room_groups: '*', users: '*', agents: '*' };++/** A "Specific" dimension with an empty list matches nobody. */+function matchesNobody(dim: AddressingDimension): boolean {+ return dim !== '*' && dim.length === 0;+}++/**+ * Why a rule can never match (so it would silently never apply), or null when it+ * is effective. A context dimension (rooms / room groups) that matches nobody+ * kills the rule outright; the sender is dead only when BOTH users and agents+ * match nobody (an empty list on just one kind is the intentional "none").+ */+function deadRuleReason(rule: AddressingRule): string | null {+ if (matchesNobody(rule.rooms)) return 'Rooms is Specific but empty — this rule never applies.';+ if (matchesNobody(rule.room_groups)) {+ return 'Room groups is Specific but empty — this rule never applies.';+ }+ if (matchesNobody(rule.users) && matchesNobody(rule.agents)) {+ return 'Both Users and Agents are empty — no sender can match, so this rule never applies.';+ }+ return null;+}++/** Whether a policy contains any rule that can never match. Callers disable Save+ * so an inert rule can't be persisted silently. */+export function policyHasDeadRule(policy: AddressingPolicy | null): boolean {+ return policy !== null && policy.rules.some((r) => deadRuleReason(r) !== null);+}++/**+ * Controlled editor for an agent's scoped addressing policy (CHOO-1585). A null+ * value means "open" (anyone may address the agent); a policy value restricts to+ * senders matching a rule. Option lists (rooms / room groups / users / agents)+ * are supplied by the parent so this component stays presentational and reusable+ * across the settings page and the creation modal.+ */+export function AddressingPolicyEditor({+ value,+ onChange,+ rooms,+ roomGroups,+ users,+ agents,+ disabled = false,+}: {+ value: AddressingPolicy | null;+ onChange: (next: AddressingPolicy | null) => void;+ rooms: OptionItem[];+ roomGroups: OptionItem[];+ users: OptionItem[];+ agents: OptionItem[];+ disabled?: boolean;+}) {+ const restricted = value !== null;+ const rules = value?.rules ?? [];+ // Which rule (by index) is currently open for editing. Loaded rules start+ // collapsed (shown as a read-only summary); a freshly added rule opens for+ // editing. Only one rule is edited at a time.+ const [editingIndex, setEditingIndex] = useState<number | null>(null);++ const optionsFor = (key: DimKey): OptionItem[] => {+ if (key === 'rooms') return rooms;+ if (key === 'room_groups') return roomGroups;+ if (key === 'users') return users;+ return agents;+ };++ const setRules = (next: AddressingRule[]) => onChange({ rules: next });+ const updateRule = (index: number, next: AddressingRule) =>+ setRules(rules.map((r, i) => (i === index ? next : r)));++ const addRule = () => {+ setRules([...rules, EMPTY_RULE]);+ setEditingIndex(rules.length);+ };+ const removeRule = (index: number) => {+ setRules(rules.filter((_r, i) => i !== index));+ setEditingIndex((prev) =>+ prev === null || prev === index ? null : prev > index ? prev - 1 : prev+ );+ };++ return (+ <div className="flex flex-col gap-3">+ <Select+ value={restricted ? 'restricted' : 'open'}+ onValueChange={(next) => onChange(next === 'restricted' ? { rules } : null)}+ disabled={disabled}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="open">Open — anyone in the room can address it</SelectItem>+ <SelectItem value="restricted">Restricted — only matching rules</SelectItem>+ </SelectContent>+ </Select>++ {restricted && (+ <div className="flex flex-col gap-3">+ {rules.length === 0 && (+ <p className="text-destructive text-xs">+ No rules — a restricted policy with no rules means nobody can address this agent. Add+ a rule or switch back to Open.+ </p>+ )}+ {rules.map((rule, index) =>+ index === editingIndex ? (+ <div+ key={index}+ className="border-primary/50 flex flex-col gap-2 rounded-md border bg-background-2/40 p-2"+ >+ <div className="flex items-center justify-between">+ <span className="text-sm font-medium">Editing rule {index + 1}</span>+ {!disabled && (+ <Button+ variant="ghost"+ size="icon-sm"+ onClick={() => removeRule(index)}+ aria-label="Remove rule"+ >+ <Trash2 className="size-4" />+ </Button>+ )}+ </div>+ <DimensionRow+ label="Rooms"+ value={rule.rooms}+ options={optionsFor('rooms')}+ allowNone={false}+ disabled={disabled}+ onChange={(rooms) => updateRule(index, { ...rule, rooms })}+ />+ <DimensionRow+ label="Room groups"+ value={rule.room_groups}+ options={optionsFor('room_groups')}+ allowNone={false}+ disabled={disabled}+ onChange={(room_groups) => updateRule(index, { ...rule, room_groups })}+ />+ <DimensionRow+ label="Users"+ value={rule.users}+ options={optionsFor('users')}+ allowNone+ disabled={disabled}+ onChange={(users) => updateRule(index, { ...rule, users })}+ />+ <DimensionRow+ label="Agents"+ value={rule.agents}+ options={optionsFor('agents')}+ allowNone+ disabled={disabled}+ onChange={(agents) => updateRule(index, { ...rule, agents })}+ />+ {deadRuleReason(rule) !== null && (+ <p className="text-destructive text-xs">{deadRuleReason(rule)}</p>+ )}+ {!disabled && (+ <div className="flex justify-end">+ <Button+ size="sm"+ disabled={deadRuleReason(rule) !== null}+ onClick={() => setEditingIndex(null)}+ >+ Apply rule+ </Button>+ </div>+ )}+ </div>+ ) : (+ <RuleSummary+ key={index}+ index={index}+ rule={rule}+ rooms={rooms}+ roomGroups={roomGroups}+ users={users}+ agents={agents}+ disabled={disabled}+ onEdit={() => setEditingIndex(index)}+ onRemove={() => removeRule(index)}+ />+ )+ )}+ {!disabled && (+ <div>+ <Button+ variant="outline"+ size="sm"+ disabled={editingIndex !== null}+ onClick={addRule}+ >+ Add rule+ </Button>+ </div>+ )}+ </div>+ )}+ </div>+ );+}++/** Human-readable summary of one dimension for the collapsed rule view. */+function dimLabel(dim: AddressingDimension, options: OptionItem[]): string {+ if (dim === '*') return 'any';+ if (dim.length === 0) return 'none';+ return dim.map((id) => options.find((o) => o.id === id)?.label ?? id).join(', ');+}++/** Collapsed, read-only view of an applied rule — makes it obvious the rule is+ * set up (vs the bordered/highlighted editing view). */+function RuleSummary({+ index,+ rule,+ rooms,+ roomGroups,+ users,+ agents,+ disabled,+ onEdit,+ onRemove,+}: {+ index: number;+ rule: AddressingRule;+ rooms: OptionItem[];+ roomGroups: OptionItem[];+ users: OptionItem[];+ agents: OptionItem[];+ disabled: boolean;+ onEdit: () => void;+ onRemove: () => void;+}) {+ const dead = deadRuleReason(rule);+ return (+ <div className="flex items-start justify-between gap-2 rounded-md border border-border p-2">+ <div className="flex min-w-0 flex-col gap-0.5">+ <span className="text-sm font-medium">Rule {index + 1}</span>+ <div className="flex flex-col gap-0.5 text-xs text-foreground-muted">+ <span>+ <span className="font-medium">Rooms:</span> {dimLabel(rule.rooms, rooms)}+ </span>+ <span>+ <span className="font-medium">Room groups:</span>{' '}+ {dimLabel(rule.room_groups, roomGroups)}+ </span>+ <span>+ <span className="font-medium">Users:</span> {dimLabel(rule.users, users)}+ </span>+ <span>+ <span className="font-medium">Agents:</span> {dimLabel(rule.agents, agents)}+ </span>+ </div>+ {dead !== null && <span className="text-destructive text-xs">{dead}</span>}+ </div>+ {!disabled && (+ <div className="flex shrink-0 items-center gap-1">+ <Button variant="outline" size="sm" onClick={onEdit}>+ Edit+ </Button>+ <Button variant="ghost" size="icon-sm" onClick={onRemove} aria-label="Remove rule">+ <Trash2 className="size-4" />+ </Button>+ </div>+ )}+ </div>+ );+}++type DimMode = 'any' | 'specific' | 'none';++function initialMode(value: AddressingDimension, allowNone: boolean): DimMode {+ if (value === '*') return 'any';+ if (value.length === 0) return allowNone ? 'none' : 'specific';+ return 'specific';+}++/**+ * One dimension of a rule. `allowNone` adds an explicit "None" mode for the+ * dimensions where excluding a whole sender kind is meaningful (users, agents);+ * context dimensions (rooms, room groups) only offer Any / Specific. The mode is+ * tracked locally so "None" and an in-progress empty "Specific" (both `[]` in+ * the model) stay distinguishable in the UI.+ */+function DimensionRow({+ label,+ value,+ options,+ allowNone,+ disabled,+ onChange,+}: {+ label: string;+ value: AddressingDimension;+ options: OptionItem[];+ allowNone: boolean;+ disabled: boolean;+ onChange: (next: AddressingDimension) => void;+}) {+ const [search, setSearch] = useState('');+ const [mode, setMode] = useState<DimMode>(() => initialMode(value, allowNone));+ const ids = value === '*' ? [] : value;++ const changeMode = (next: DimMode) => {+ setMode(next);+ if (next === 'any') onChange('*');+ else if (next === 'none') onChange([]);+ else onChange(ids); // 'specific' — keep any current ids+ };++ const labelFor = (id: string) => options.find((o) => o.id === id)?.label ?? id;+ const addId = (id: string) => {+ if (!ids.includes(id)) onChange([...ids, id]);+ };+ const removeId = (id: string) => onChange(ids.filter((x) => x !== id));++ // Manual free-text entry: add the typed value. If it matches a known option's+ // label (case-insensitive), store that option's id instead of the raw text.+ const addManual = () => {+ const raw = search.trim();+ if (!raw) return;+ const byLabel = options.find((o) => o.label.toLowerCase() === raw.toLowerCase());+ addId(byLabel ? byLabel.id : raw);+ setSearch('');+ };++ const needle = search.trim().toLowerCase();+ const matches = needle+ ? options.filter((o) => !ids.includes(o.id) && o.label.toLowerCase().includes(needle))+ : [];+ // Offer "add manual" only when the typed text isn't already an option or selected.+ const canAddManual =+ needle.length > 0 &&+ !ids.includes(search.trim()) &&+ !options.some((o) => o.label.toLowerCase() === needle || o.id.toLowerCase() === needle);++ return (+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-2">+ <span className="w-24 text-xs font-medium text-foreground-muted">{label}</span>+ <Select value={mode} onValueChange={(m) => changeMode(m as DimMode)} disabled={disabled}>+ <SelectTrigger className="h-7 w-32">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="any">Any</SelectItem>+ <SelectItem value="specific">Specific</SelectItem>+ {allowNone && <SelectItem value="none">None</SelectItem>}+ </SelectContent>+ </Select>+ {mode === 'specific' && ids.length > 0 && (+ <span className="text-xs text-foreground-muted">{ids.length} selected</span>+ )}+ </div>+ {mode === 'specific' && (+ <div className="ml-24 flex flex-col gap-2 rounded-md border border-border p-2">+ {/* Selected entries as chips, so a configured rule is obvious at a glance. */}+ {ids.length > 0 ? (+ <div className="flex flex-wrap gap-1">+ {ids.map((id) => (+ <Badge key={id} variant="secondary" className="gap-1 pr-1">+ <span className="max-w-[180px] truncate">{labelFor(id)}</span>+ {!disabled && (+ <button+ type="button"+ aria-label={`Remove ${labelFor(id)}`}+ className="hover:bg-muted rounded-sm"+ onClick={() => removeId(id)}+ >+ <X className="size-3" />+ </button>+ )}+ </Badge>+ ))}+ </div>+ ) : (+ <span className="text-xs text-foreground-muted">+ None selected yet — search to pick, or type a value and press Enter.+ </span>+ )}+ <Input+ placeholder={`Search or type a ${label.toLowerCase()} value…`}+ value={search}+ disabled={disabled}+ onChange={(e) => setSearch(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && canAddManual) {+ e.preventDefault();+ addManual();+ }+ }}+ className="h-7"+ />+ {needle.length > 0 && (+ <div className="flex max-h-40 flex-col gap-0.5 overflow-y-auto">+ {matches.map((opt) => (+ <button+ key={opt.id}+ type="button"+ disabled={disabled}+ className="hover:text-accent-foreground rounded-sm px-1.5 py-1 text-left text-sm hover:bg-background-quaternary-1"+ onClick={() => {+ addId(opt.id);+ setSearch('');+ }}+ >+ <span className="truncate">{opt.label}</span>+ </button>+ ))}+ {canAddManual && (+ <button+ type="button"+ disabled={disabled}+ className="hover:text-accent-foreground rounded-sm px-1.5 py-1 text-left text-sm text-foreground-muted hover:bg-background-quaternary-1"+ onClick={addManual}+ >+ + Add “{search.trim()}”+ </button>+ )}+ {matches.length === 0 && !canAddManual && (+ <span className="px-1.5 py-1 text-xs text-foreground-muted">No matches.</span>+ )}+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/use-remote-agent-name.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/use-remote-agent-name.tsnew file mode 100644index 000000000..7b5706858--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/use-remote-agent-name.ts@@ -0,0 +1,25 @@+import { useQuery } from '@tanstack/react-query';+import { rpc } from '@renderer/lib/ipc';++/**+ * The agent's registered Switch name (e.g. `claude-code.my-repo.me`), resolved+ * from the gateway. Prefer this over the local `Agent.name`, which is only the+ * working-directory basename and does not identify the agent. Falls back to+ * `fallback` while loading or when the agent can't be resolved.+ */+export function useRemoteAgentName(+ serverId: string | null,+ switchAgentId: string | null,+ fallback: string+): string {+ const query = useQuery({+ queryKey: ['remote-agent-name', serverId, switchAgentId],+ queryFn: () =>+ rpc.switchServers.getRemoteAgent({+ serverId: serverId as string,+ agentId: switchAgentId as string,+ }),+ enabled: serverId !== null && switchAgentId !== null,+ });+ return query.data?.name ?? fallback;+}diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.tsindex 026d1c974..c3a0d8d10 100644--- a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -168,6 +168,39 @@ export type RemoteAgentRoom = {roomRole: string | null;};+/** A room group on a server (mirrors the gateway `RoomGroupDetail`). Used to+ * scope an addressing rule by room group. */+export type RemoteRoomGroup = {+ id: string;+ name: string;+};++/** A bridged (external) human identity on a server. The `users` dimension of an+ * addressing policy keys off these ids. */+export type RemoteExternalUser = {+ id: string;+ username: string;+};++/**+ * Scoped agent-addressing permissions (CHOO-1585). Each dimension is "*" (any)+ * or an explicit id list ([] = none). A policy with no rules — or a null policy+ * on the agent — means it is open to anyone. `users` ids are ExternalUser ids;+ * `agents` ids are agent ids. Mirrors the gateway/core `AddressingPolicy`.+ */+export type AddressingDimension = '*' | string[];++export type AddressingRule = {+ rooms: AddressingDimension;+ room_groups: AddressingDimension;+ users: AddressingDimension;+ agents: AddressingDimension;+};++export type AddressingPolicy = {+ rules: AddressingRule[];+};+/*** Result of checking whether an agent exists on a chosen server.* `found` — the server owns the agent. `not-found` — it doesn't (wrong serverdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex fcd671e7b..1bec25478 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -188,6 +188,15 @@ Matrix through it. `AgentClient`observes the room over Matrix sync, decides whether the message addresses itsagent (by `@name`, room alias, or a held role), and enqueues an `AgentEvent`.+An agent may carry a **scoped addressing policy** (`Agent.addressing_policy`, see+[`addressing.py`](../core/switch_core/addressing.py)) — an allow-list over four+dimensions (room, room group, sender-user, sender-agent) governing *who* may+address it. With no policy an agent is open to any room participant (today's+behaviour). When a policy is set and the sender is not permitted, `AgentClient`+demotes the message to unaddressed room chatter and posts a one-shot reply to the+sender; `delegate_task` (an explicit, tracked addressing vector) instead fails+loud with a `PermissionError`. Configured via `PUT /agents/{id}/addressing-policy`.+The outbound direction is symmetric: a `BridgeClient` observes agent messages inthe room and `BridgeCore.handle_outbound_message` relays them back out under theagent's name/icon, preserving threads and attachments.diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex aeda42bd6..67c34a834 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -88,6 +88,24 @@ export interface AgentDetail extends AgentSummary {rooms: AgentRoomMembership[];sessions: AgentSessionDetail[];children: AgentSummary[];+ addressing_policy: AddressingPolicy | null;+}++// Scoped agent-addressing permissions (CHOO-1585). Each dimension is "*" (any)+// or an explicit id list ([] = none). A policy with no rules (or a null+// addressing_policy) means the agent is open to anyone. `users` ids are+// ExternalUser ids (bridged human identities); `agents` ids are agent ids.+export type AddressingDimension = "*" | string[];++export interface AddressingRule {+ rooms: AddressingDimension;+ room_groups: AddressingDimension;+ users: AddressingDimension;+ agents: AddressingDimension;+}++export interface AddressingPolicy {+ rules: AddressingRule[];}export interface BridgeDetail {@@ -505,6 +523,17 @@ export async function deleteAgent(agentId: string): Promise<boolean> {return res?.ok ?? false;}+export async function updateAgentAddressingPolicy(+ agentId: string,+ policy: AddressingPolicy | null,+): Promise<AgentDetail> {+ return jsonRequest<AgentDetail>(+ `/agents/${agentId}/addressing-policy`,+ "PUT",+ { policy },+ );+}+export async function fetchKnownAgentTypes(): Promise<KnownAgentType[] | null> {return fetchJson<KnownAgentType[]>("/agents/known-types");}@@ -723,6 +752,23 @@ export async function fetchBridgeUsers();}+// Union of external (bridged human) users across every bridge. Used by the+// addressing-policy editor, whose `users` dimension keys off ExternalUser ids.+export async function fetchAllExternalUsers(): Promise<+ ExternalUserSummary[] | null+> {+ const bridges = await fetchBridges();+ if (bridges === null) return null;+ const perBridge = await Promise.all(+ bridges.map((b) => fetchBridgeUsers(b.bridge_id)),+ );+ const byId = new Map<string, ExternalUserSummary>();+ for (const users of perBridge) {+ for (const u of users ?? []) byId.set(u.id, u);+ }+ return [...byId.values()];+}+export async function deleteBridge(bridgeId: string): Promise<boolean> {const res = await fetchJson<{ ok: boolean }>(`/collaborations/${bridgeId}`, {method: "DELETE",diff --git a/gateway/src/data/hooks.ts b/gateway/src/data/hooks.tsindex afc8b435c..5a05d9317 100644--- a/gateway/src/data/hooks.ts+++ b/gateway/src/data/hooks.ts@@ -25,6 +25,7 @@ import {fetchAgent,fetchAgents,fetchApiKeys,+ fetchAllExternalUsers,fetchBridges,fetchBridgeTypes,fetchBridgeUsers,@@ -146,6 +147,10 @@ export function useBridgeUsers(return useQuery(fetcher);}+export function useAllExternalUsers(): UseQueryResult<ExternalUserSummary[]> {+ return useQuery(fetchAllExternalUsers);+}+export function useKnownAgentTypes(): UseQueryResult<KnownAgentType[]> {return useQuery(fetchKnownAgentTypes);}diff --git a/gateway/src/pages/agents/AddressingPolicySection.tsx b/gateway/src/pages/agents/AddressingPolicySection.tsxnew file mode 100644index 000000000..c1d527a21--- /dev/null+++ b/gateway/src/pages/agents/AddressingPolicySection.tsx@@ -0,0 +1,384 @@+import {+ Alert,+ Autocomplete,+ Box,+ Button,+ CircularProgress,+ FormControlLabel,+ IconButton,+ Paper,+ Radio,+ RadioGroup,+ Stack,+ TextField,+ ToggleButton,+ ToggleButtonGroup,+ Typography,+} from "@mui/material";+import DeleteOutline from "@mui/icons-material/DeleteOutline";+import { useMemo, useState } from "react";+import {+ type AddressingDimension,+ type AddressingPolicy,+ type AddressingRule,+ type AgentDetail,+ updateAgentAddressingPolicy,+} from "../../data/api";+import {+ useAgents,+ useAllExternalUsers,+ useRoomGroups,+ useRooms,+} from "../../data/hooks";++// A pickable option for one of the four dimensions.+interface Option {+ id: string;+ label: string;+}++// Working (editable) shape of one dimension: "any" is the "*" wildcard,+// "specific" carries an explicit id list, and "none" ([]) matches nobody.+// "none" is only offered for the sender dimensions (users / agents), where+// excluding a whole sender kind is meaningful.+type DimMode = "any" | "specific" | "none";+interface DimState {+ mode: DimMode;+ ids: string[];+}+interface RuleState {+ rooms: DimState;+ room_groups: DimState;+ users: DimState;+ agents: DimState;+}++function toDimState(value: AddressingDimension, allowNone: boolean): DimState {+ if (value === "*") return { mode: "any", ids: [] };+ if (value.length === 0) {+ return { mode: allowNone ? "none" : "specific", ids: [] };+ }+ return { mode: "specific", ids: value };+}++function fromDimState(state: DimState): AddressingDimension {+ if (state.mode === "any") return "*";+ if (state.mode === "none") return [];+ return state.ids;+}++function toRuleState(rule: AddressingRule): RuleState {+ return {+ rooms: toDimState(rule.rooms, false),+ room_groups: toDimState(rule.room_groups, false),+ users: toDimState(rule.users, true),+ agents: toDimState(rule.agents, true),+ };+}++function fromRuleState(state: RuleState): AddressingRule {+ return {+ rooms: fromDimState(state.rooms),+ room_groups: fromDimState(state.room_groups),+ users: fromDimState(state.users),+ agents: fromDimState(state.agents),+ };+}++// A rule that can never match (so it would silently never apply): a context+// dimension set to Specific-but-empty, or both sender dimensions matching nobody.+function dimMatchesNobody(state: DimState): boolean {+ return state.mode === "none" || (state.mode === "specific" && state.ids.length === 0);+}+function ruleIsDead(rule: RuleState): boolean {+ return (+ dimMatchesNobody(rule.rooms) ||+ dimMatchesNobody(rule.room_groups) ||+ (dimMatchesNobody(rule.users) && dimMatchesNobody(rule.agents))+ );+}++const EMPTY_RULE: RuleState = {+ rooms: { mode: "any", ids: [] },+ room_groups: { mode: "any", ids: [] },+ users: { mode: "any", ids: [] },+ agents: { mode: "any", ids: [] },+};++function DimensionField({+ label,+ help,+ state,+ options,+ allowNone,+ disabled,+ onChange,+}: {+ label: string;+ help: string;+ state: DimState;+ options: Option[];+ allowNone: boolean;+ disabled: boolean;+ onChange: (next: DimState) => void;+}) {+ const selected = options.filter((o) => state.ids.includes(o.id));+ // Ids that no longer resolve to a known option (e.g. a deleted room) are still+ // shown as raw chips so the operator can see and remove them.+ const unknownIds = state.ids.filter(+ (id) => !options.some((o) => o.id === id),+ );++ return (+ <Box>+ <Stack direction="row" alignItems="center" spacing={1} mb={0.5}>+ <Typography variant="body2" sx={{ fontWeight: 600, minWidth: 100 }}>+ {label}+ </Typography>+ <ToggleButtonGroup+ size="small"+ exclusive+ value={state.mode}+ disabled={disabled}+ onChange={(_e, mode: DimMode | null) => {+ if (mode) onChange({ ...state, mode });+ }}+ >+ <ToggleButton value="any">Any</ToggleButton>+ <ToggleButton value="specific">Specific</ToggleButton>+ {allowNone && <ToggleButton value="none">None</ToggleButton>}+ </ToggleButtonGroup>+ </Stack>+ {state.mode === "specific" && (+ <Autocomplete+ multiple+ freeSolo+ size="small"+ disabled={disabled}+ options={options}+ getOptionLabel={(o) => (typeof o === "string" ? o : o.label)}+ value={[+ ...selected,+ ...unknownIds.map((id) => ({ id, label: `${id} (manual)` })),+ ]}+ isOptionEqualToValue={(a, b) => a.id === b.id}+ onChange={(_e, next) =>+ onChange({+ ...state,+ ids: next.map((o) => (typeof o === "string" ? o.trim() : o.id)),+ })+ }+ renderInput={(params) => (+ <TextField+ {...params}+ placeholder="search or type a value…"+ helperText={`${help} Type a value and press Enter to add it manually.`}+ />+ )}+ />+ )}+ </Box>+ );+}++export default function AddressingPolicySection({+ agent,+ canEdit,+ onUpdated,+}: {+ agent: AgentDetail;+ canEdit: boolean;+ onUpdated: () => void;+}) {+ const initialRestricted = !!agent.addressing_policy;+ const initialRules: RuleState[] = (agent.addressing_policy?.rules ?? []).map(+ toRuleState,+ );++ const [restricted, setRestricted] = useState(initialRestricted);+ const [rules, setRules] = useState<RuleState[]>(initialRules);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const { data: rooms } = useRooms();+ const { data: groups } = useRoomGroups();+ const { data: agents } = useAgents();+ const { data: users } = useAllExternalUsers();++ const roomOptions: Option[] = useMemo(+ () => (rooms ?? []).map((r) => ({ id: r.id, label: r.name })),+ [rooms],+ );+ const groupOptions: Option[] = useMemo(+ () => (groups ?? []).map((g) => ({ id: g.id, label: g.name })),+ [groups],+ );+ const agentOptions: Option[] = useMemo(+ () => (agents ?? []).map((a) => ({ id: a.id, label: a.name })),+ [agents],+ );+ const userOptions: Option[] = useMemo(+ () => (users ?? []).map((u) => ({ id: u.id, label: u.external_username })),+ [users],+ );++ const desired: AddressingPolicy | null = restricted+ ? { rules: rules.map(fromRuleState) }+ : null;+ const dirty =+ JSON.stringify(desired) !==+ JSON.stringify(agent.addressing_policy ?? null);+ const hasDeadRule = restricted && rules.some(ruleIsDead);++ const handleSave = async () => {+ setSaving(true);+ setError(null);+ try {+ await updateAgentAddressingPolicy(agent.id, desired);+ onUpdated();+ } catch (e) {+ setError(e instanceof Error ? e.message : "Failed to save policy");+ } finally {+ setSaving(false);+ }+ };++ const updateRule = (index: number, next: RuleState) =>+ setRules((prev) => prev.map((r, i) => (i === index ? next : r)));++ return (+ <Stack spacing={2}>+ <Box>+ <Typography variant="subtitle2" color="text.secondary">+ Addressing policy+ </Typography>+ <Typography variant="caption" color="text.secondary">+ Controls who may address this agent (@mention, targeted message, or task+ delegation). Open means any room participant can; restricted permits only+ senders matching an allow-rule.+ </Typography>+ </Box>++ <RadioGroup+ value={restricted ? "restricted" : "open"}+ onChange={(e) => setRestricted(e.target.value === "restricted")}+ >+ <FormControlLabel+ value="open"+ disabled={!canEdit}+ control={<Radio size="small" />}+ label="Open — anyone in the room can address this agent"+ />+ <FormControlLabel+ value="restricted"+ disabled={!canEdit}+ control={<Radio size="small" />}+ label="Restricted — only senders matching a rule below"+ />+ </RadioGroup>++ {restricted && (+ <Stack spacing={2}>+ {rules.length === 0 && (+ <Alert severity="warning">+ No rules — with a restricted policy and no rules, nobody can address+ this agent. Add a rule or switch back to Open.+ </Alert>+ )}+ {rules.map((rule, index) => (+ <Paper key={index} variant="outlined" sx={{ p: 2, borderRadius: 2 }}>+ <Stack direction="row" alignItems="center" mb={1}>+ <Typography variant="body2" sx={{ fontWeight: 600, flexGrow: 1 }}>+ Rule {index + 1}+ </Typography>+ {canEdit && (+ <IconButton+ size="small"+ onClick={() =>+ setRules((prev) => prev.filter((_r, i) => i !== index))+ }+ aria-label="Remove rule"+ >+ <DeleteOutline fontSize="small" />+ </IconButton>+ )}+ </Stack>+ <Stack spacing={1.5}>+ <DimensionField+ label="Rooms"+ help="Rooms this rule applies in."+ state={rule.rooms}+ options={roomOptions}+ allowNone={false}+ disabled={!canEdit}+ onChange={(rooms) => updateRule(index, { ...rule, rooms })}+ />+ <DimensionField+ label="Room groups"+ help="Groups of the room the message is in."+ state={rule.room_groups}+ options={groupOptions}+ allowNone={false}+ disabled={!canEdit}+ onChange={(room_groups) =>+ updateRule(index, { ...rule, room_groups })+ }+ />+ <DimensionField+ label="Users"+ help="Human (bridged) senders this rule admits."+ state={rule.users}+ options={userOptions}+ allowNone+ disabled={!canEdit}+ onChange={(users) => updateRule(index, { ...rule, users })}+ />+ <DimensionField+ label="Agents"+ help="Agent senders this rule admits."+ state={rule.agents}+ options={agentOptions}+ allowNone+ disabled={!canEdit}+ onChange={(agents) => updateRule(index, { ...rule, agents })}+ />+ {ruleIsDead(rule) && (+ <Alert severity="warning">+ This rule can never match (an empty Specific/None dimension+ excludes everyone), so it will never apply.+ </Alert>+ )}+ </Stack>+ </Paper>+ ))}+ {canEdit && (+ <Box>+ <Button+ size="small"+ variant="outlined"+ onClick={() => setRules((prev) => [...prev, { ...EMPTY_RULE }])}+ >+ Add rule+ </Button>+ </Box>+ )}+ </Stack>+ )}++ {error && <Alert severity="error">{error}</Alert>}++ {canEdit && (+ <Box>+ <Button+ variant="contained"+ disabled={!dirty || saving || hasDeadRule}+ onClick={handleSave}+ startIcon={saving ? <CircularProgress size={16} /> : undefined}+ >+ Save policy+ </Button>+ </Box>+ )}+ </Stack>+ );+}diff --git a/gateway/src/pages/agents/AgentDetailPage.tsx b/gateway/src/pages/agents/AgentDetailPage.tsxindex 10a720d91..1a095886b 100644--- a/gateway/src/pages/agents/AgentDetailPage.tsx+++ b/gateway/src/pages/agents/AgentDetailPage.tsx@@ -22,6 +22,7 @@ import {} from "../../data/api";import { useAuth } from "../../data/AuthContext";import { useAgent, useKnownAgentTypes } from "../../data/hooks";+import AddressingPolicySection from "./AddressingPolicySection";import { extractDefaults, renderOptionFields } from "./optionFields";// Presence of an agent within a room — mirrors the room detail page so the two@@ -124,6 +125,12 @@ export default function AgentDetailPage() {</>)}<Divider />+ <AddressingPolicySection+ agent={agent}+ canEdit={isOwner}+ onUpdated={refetch}+ />+ <Divider /><SessionsSection sessions={agent.sessions} /><Divider /><RoomsSection rooms={agent.rooms} />