Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Let a template's room params name only rooms the runner can see (#1029)
Abel Dantas1d25add8194d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex edc22e759..4155b0a3e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -78,6 +78,11 @@ version of their own to them without also giving them a release of their own.its warning names the service and the time until which they may keepworking: up to an hour for Google Workspace, and up to eight hours forAtlassian, whose tokens cannot be asked for shorter.+- **A template's room params name only rooms its runner can see.** A room+ param checked its value against every room on the server, and `$first` or+ a list of candidates could settle on someone else's private room. That told+ the runner the room existed and could write its name into their new room.+ Now a room the runner cannot read reads as missing.#### Added- **The `[CONN]` log lines say when a client fell back to the event stream.**diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 4b2dc31b6..2bc9a6806 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -19,6 +19,7 @@ from typing import Anyfrom switch_core.agent_refusals import AgentRefused, record_refusalfrom switch_core.agent_template_ops import ActingFor, AgentTemplatesfrom switch_core.agent_templates import plan_template+from switch_core.authz import Principalfrom switch_core.bridges.agent.api.handlers import parse_timestamp_msfrom switch_core.bridges.agent.operations.agent_management import (management_permission,@@ -58,7 +59,7 @@ from switch_core.clients.agent_admin import DELETE_CONFIRM_SECONDSfrom switch_core.db.models import CollaborationBridge, User, require_tenant_idfrom switch_core.db.stores.template_store import TemplateStorefrom switch_core.feature_flags import AGENT_MANAGEMENT, SWITCH_BUDDY-from switch_core.rooms_yaml import GroupSpec, template_json_schema+from switch_core.rooms_yaml import GroupSpec, RoomReader, template_json_schemafrom switch_core.template_guide import TEMPLATE_GUIDEfrom switch_core.template_installs import InstallSource, record_install, source_offrom switch_core.template_runs import (@@ -1699,12 +1700,14 @@ async def _provision_as_agent(return {"created_agents": _created_view(created)}rooms_yaml = protocol.room_yaml_service()- inputs = await rooms_yaml.resolve_defaults(yaml, inputs)+ # As the owner without admin reach, plus the rooms the agent is in.+ reader = RoomReader(Principal(owner.id, False), agent_id=agent.id)+ inputs = await rooms_yaml.resolve_defaults(yaml, inputs, reader=reader)builtins = await rooms_yaml.builtins_for(user_id=owner.id, name=owner.name, email=owner.email, text=yaml, inputs=inputs)parsed = rooms_yaml.parse_template(yaml, inputs=inputs, builtins=builtins)- await rooms_yaml.check_entity_params(parsed)+ await rooms_yaml.check_entity_params(parsed, reader=reader)await rooms_yaml.check_bridges(parsed)room_specs = ([(r, r.kickoff) for r in parsed.spec.rooms]@@ -1963,7 +1966,13 @@ async def _run_document(if is_v2_text(content):# A version 2 condition may read a messaging app or room param# whose value is the first candidate the server has.- inputs = await rooms_yaml.resolve_defaults(content, inputs)+ inputs = await rooms_yaml.resolve_defaults(+ content,+ inputs,+ reader=RoomReader(+ Principal(acting.owner.id, False), agent_id=acting.agent.id+ ),+ )builtins = await rooms_yaml.builtins_for(user_id=acting.owner.id,name=acting.owner.name,diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.pyindex cdcd62dc4..c604df9a0 100644--- a/core/switch_core/gateway/rooms.py+++ b/core/switch_core/gateway/rooms.py@@ -70,6 +70,7 @@ from switch_core.rooms_yaml import (GroupProvisionResult,GroupSpec,ProvisionResult,+ RoomReader,RoomYamlService,template_json_schema,)@@ -481,12 +482,13 @@ async def create_room_from_yaml(text = (await request.body()).decode("utf-8")inputs = Nonetemplate_name = None- inputs = await rooms_yaml.resolve_defaults(text, inputs)+ reader = RoomReader(Principal(user.id, is_admin))+ inputs = await rooms_yaml.resolve_defaults(text, inputs, reader=reader)builtins = await rooms_yaml.builtins_for(user_id=user.id, name=user.name, email=user.email, text=text, inputs=inputs)parsed = rooms_yaml.parse_template(text, inputs=inputs, builtins=builtins)- await rooms_yaml.check_entity_params(parsed)+ await rooms_yaml.check_entity_params(parsed, reader=reader)if isinstance(parsed.spec, GroupSpec):return await rooms_yaml.provision_group(parsed.spec,@@ -676,7 +678,14 @@ async def run_template_document(inputs = body.inputs or {}try:if is_v2_text(body.template):- inputs = await rooms_yaml.resolve_defaults(body.template, inputs) or {}+ inputs = (+ await rooms_yaml.resolve_defaults(+ body.template,+ inputs,+ reader=RoomReader(Principal(user.id, is_admin)),+ )+ or {}+ )builtins = await rooms_yaml.builtins_for(user_id=user.id,name=user.name,@@ -748,7 +757,8 @@ async def _run_as_person(parsed = Nonebuiltins: dict[str, str] = {}if document is not None:- inputs = await rooms_yaml.resolve_defaults(document, inputs)+ reader = RoomReader(Principal(user.id, is_admin))+ inputs = await rooms_yaml.resolve_defaults(document, inputs, reader=reader)builtins = await rooms_yaml.builtins_for(user_id=user.id,name=user.name,@@ -759,7 +769,7 @@ async def _run_as_person(parsed = rooms_yaml.parse_template(document, inputs=inputs, builtins=builtins)- await rooms_yaml.check_entity_params(parsed)+ await rooms_yaml.check_entity_params(parsed, reader=reader)await rooms_yaml.check_bridges(parsed)checked = await creator.check(tenant_id, user.id, plans)created = await creator.create(tenant_id, user.id, checked)diff --git a/core/switch_core/rooms_yaml.py b/core/switch_core/rooms_yaml.pyindex f194c6da0..daf227eba 100644--- a/core/switch_core/rooms_yaml.py+++ b/core/switch_core/rooms_yaml.py@@ -40,6 +40,7 @@ import yamlfrom pydantic import BaseModel, Field, TypeAdapter, ValidationError, model_validatorfrom switch_core.agent_runs import AgentOrigin, kickoff_fingerprint+from switch_core.authz import Principal, canfrom switch_core.bridges.collaboration.models import ChannelTypefrom switch_core.bridges.resource.registry import validate_reference_valuefrom switch_core.clients.actor import SystemActor@@ -78,6 +79,18 @@ PLACEHOLDER_RE = re.compile(r"\{(\$?[A-Za-z_][A-Za-z0-9_]*)\}")# bridge's display name, a room's name, a platform username.ENTITY_PARAM_TYPES = ("agent", "bridge", "room", "user")++@dataclass(frozen=True)+class RoomReader:+ """Who a template runs as, which decides the rooms its `room` params may+ name: the rooms `principal` may read, plus the rooms `agent_id` is in when+ an agent runs it. Any other room reads as missing, so a template cannot+ confirm or fill in the name of a room its runner cannot see."""++ principal: Principal+ agent_id: str | None = None++# Param types that say how an agent the template creates runs: the coding# agent that runs it, where it runs (`location`, a Console answer: this# computer or an SSH host; `machine`, one of the owner's machines on the@@ -752,7 +765,9 @@ class RoomYamlService:# ── Entity params ─────────────────────────────────────────────────────- async def check_entity_params(self, parsed: ParsedTemplate) -> None:+ async def check_entity_params(+ self, parsed: ParsedTemplate, *, reader: RoomReader+ ) -> None:"""Every entity-typed param must name something this server has.Raises ``ValueError`` in the ``param 'x': ...`` form the Console maps@@ -797,7 +812,7 @@ class RoomYamlService:f"param {param!r}: messaging app {value!r} is not running")if "room" in wanted:- rooms = {r.name for r in await self._room_store.get_all(session)}+ rooms = set(await self._readable_room_names(session, reader))for param, value in wanted["room"]:if value not in rooms:raise ValueError(@@ -831,13 +846,14 @@ class RoomYamlService:)async def resolve_defaults(- self, text: str, inputs: dict[str, Any] | None+ self, text: str, inputs: dict[str, Any] | None, *, reader: RoomReader) -> dict[str, Any] | None:"""Turn each list default into an input, for params sent no value.The candidates are tried in order and the first one the server haswins: a bridge by display name, an agent or room by name, ``$first``- for the default messaging app or the first agent or room by name. A+ for the default messaging app or the first agent or room by name. Only+ rooms `reader` may name count (see ``RoomReader``). Achain with no hit leaves the param as it was, for ``resolve_params``to report. Runs before ``builtins_for``, because the bridge decideswhich messaging app ``{$creator}`` is looked up on. A document that@@ -873,7 +889,7 @@ class RoomYamlService:names: dict[str, list[str]] = {}for name, spec in chains.items():if spec.type not in names:- names[spec.type] = await self._names_of(session, spec.type)+ names[spec.type] = await self._names_of(session, spec.type, reader)have = names[spec.type]for candidate in spec.default: # type: ignore[union-attr]if candidate == FIRST and have:@@ -884,7 +900,9 @@ class RoomYamlService:breakreturn filled if filled != given else inputs- async def _names_of(self, session: AsyncSession, param_type: str) -> list[str]:+ async def _names_of(+ self, session: AsyncSession, param_type: str, reader: RoomReader+ ) -> list[str]:"""What the server has of one entity type, the ``$first`` one first."""if param_type == "bridge":active = [@@ -901,7 +919,27 @@ class RoomYamlService:)if param_type == "agent":return sorted(a.name for a in await self._agent_store.get_all(session))- return sorted(r.name for r in await self._room_store.get_all(session))+ return sorted(await self._readable_room_names(session, reader))++ async def _readable_room_names(+ self, session: AsyncSession, reader: RoomReader+ ) -> list[str]:+ """Names of the rooms `reader` may name in a `room` param."""+ member_of = (+ {+ r.id+ for r in await self._room_store.get_rooms_for_agent(+ session, reader.agent_id+ )+ }+ if reader.agent_id is not None+ else set()+ )+ return [+ r.name+ for r in await self._room_store.get_all(session)+ if r.id in member_of or can(reader.principal, "read", r)+ ]async def builtins_for(self,diff --git a/core/tests/switch_core/management/test_agent_operations.py b/core/tests/switch_core/management/test_agent_operations.pyindex 73e74026e..d07b225ea 100644--- a/core/tests/switch_core/management/test_agent_operations.py+++ b/core/tests/switch_core/management/test_agent_operations.py@@ -1215,7 +1215,7 @@ class _NoRooms:return {"$creator": kwargs["name"], "$creator_email": kwargs["email"]}async def resolve_defaults(- self, text: str, inputs: dict[str, Any] | None+ self, text: str, inputs: dict[str, Any] | None, **kwargs: Any) -> dict[str, Any] | None:return inputsdiff --git a/core/tests/switch_core/test_rooms_yaml.py b/core/tests/switch_core/test_rooms_yaml.pyindex 3b7790a21..a3f1e4159 100644--- a/core/tests/switch_core/test_rooms_yaml.py+++ b/core/tests/switch_core/test_rooms_yaml.py@@ -19,6 +19,7 @@ import yamlfrom sqlalchemy import insert, selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.authz import Principalfrom switch_core.bridges.resource.service import ResourceServicefrom switch_core.clients.actor import SystemActorfrom switch_core.clients.admin_messages import OnBehalfOf@@ -59,6 +60,7 @@ from switch_core.rooms_yaml import (ExistingReferenceById,GroupSpec,ParamSpec,+ RoomReader,RoomYamlService,interpolate,resolve_params,@@ -231,6 +233,11 @@ def _svc(env) -> RoomYamlService:return env["svc"]+def _reader(env) -> RoomReader:+ """Alice, a member, running a template herself."""+ return RoomReader(Principal(env["user_id"], False))++def test_parse_minimal(env):spec, _ = _svc(env).parse("""@@ -1809,14 +1816,18 @@ async def test_resolve_defaults_walks_each_chain_in_order(env):)svc = _svc(env)- filled = await svc.resolve_defaults(CHAIN_TEXT, None)+ filled = await svc.resolve_defaults(CHAIN_TEXT, None, reader=_reader(env))assert filled == {"bridge": "Slack", "helper": "claude-code.alice"}- kept = await svc.resolve_defaults(CHAIN_TEXT, {"bridge": "Mattermost"})+ kept = await svc.resolve_defaults(+ CHAIN_TEXT, {"bridge": "Mattermost"}, reader=_reader(env)+ )assert kept == {"bridge": "Mattermost", "helper": "claude-code.alice"}named = CHAIN_TEXT.replace("[Teams, $first]", "[Mattermost, $first]")- assert (await svc.resolve_defaults(named, None))["bridge"] == "Mattermost"+ assert (await svc.resolve_defaults(named, None, reader=_reader(env)))[+ "bridge"+ ] == "Mattermost"async def test_a_chain_with_no_hit_is_reported_as_missing(env):@@ -1825,7 +1836,7 @@ async def test_a_chain_with_no_hit_is_reported_as_missing(env):'room:\n name: n\n description: d\n bridge: "{bridge}"\n')svc = _svc(env)- assert await svc.resolve_defaults(text, None) is None+ assert await svc.resolve_defaults(text, None, reader=_reader(env)) is Nonewith pytest.raises(ValueError, match="none of the candidates listed for bridge"):svc.parse_template(text)@@ -1874,7 +1885,7 @@ async def test_an_unset_optional_entity_param_passes_the_entity_check(env):'room:\n name: n\n description: d\n bridge: "{bridge}"\n')assert "bridge" not in parsed.values- await svc.check_entity_params(parsed)+ await svc.check_entity_params(parsed, reader=_reader(env))async def test_a_chain_resolves_over_an_input_sent_as_null(env):@@ -1889,7 +1900,9 @@ async def test_a_chain_resolves_over_an_input_sent_as_null(env):"params:\n app:\n type: bridge\n default: [Slack, $first]\n"'room:\n name: n\n description: d\n bridge: "{app}"\n')- assert await _svc(env).resolve_defaults(text, {"app": None}) == {"app": "Slack"}+ assert await _svc(env).resolve_defaults(+ text, {"app": None}, reader=_reader(env)+ ) == {"app": "Slack"}def test_an_optional_bridge_left_empty_lands_on_the_default_app(env):@@ -2010,11 +2023,11 @@ async def test_check_entity_params_agent_must_exist(env):ok = svc.parse_template(_entity_template("agent"), inputs={"pick": "claude-code.alice"})- await svc.check_entity_params(ok)+ await svc.check_entity_params(ok, reader=_reader(env))bad = svc.parse_template(_entity_template("agent"), inputs={"pick": "nobody"})with pytest.raises(ValueError, match=r"param 'pick': no agent named 'nobody'"):- await svc.check_entity_params(bad)+ await svc.check_entity_params(bad, reader=_reader(env))@pytest.mark.asyncio@@ -2028,13 +2041,13 @@ async def test_check_entity_params_bridge_must_exist_and_run(env):external_username="someone",)ok = svc.parse_template(_entity_template("bridge"), inputs={"pick": "Slack"})- await svc.check_entity_params(ok)+ await svc.check_entity_params(ok, reader=_reader(env))bad = svc.parse_template(_entity_template("bridge"), inputs={"pick": "Teams"})with pytest.raises(ValueError, match=r"param 'pick': no messaging app named 'Teams'"):- await svc.check_entity_params(bad)+ await svc.check_entity_params(bad, reader=_reader(env))async with env["session_factory"]() as session:bridge = (await session.execute(select(CollaborationBridge))).scalar_one()@@ -2044,7 +2057,7 @@ async def test_check_entity_params_bridge_must_exist_and_run(env):with pytest.raises(ValueError, match=r"param 'pick': messaging app 'Slack' is not running"):- await svc.check_entity_params(stopped)+ await svc.check_entity_params(stopped, reader=_reader(env))@pytest.mark.asyncio@@ -2054,11 +2067,11 @@ async def test_check_entity_params_room_must_exist(env):await svc.provision(spec, user_id=env["user_id"], is_admin=False)ok = svc.parse_template(_entity_template("room"), inputs={"pick": "ops"})- await svc.check_entity_params(ok)+ await svc.check_entity_params(ok, reader=_reader(env))bad = svc.parse_template(_entity_template("room"), inputs={"pick": "nowhere"})with pytest.raises(ValueError, match=r"param 'pick': no room named 'nowhere'"):- await svc.check_entity_params(bad)+ await svc.check_entity_params(bad, reader=_reader(env))@pytest.mark.asyncio@@ -2075,12 +2088,12 @@ async def test_check_entity_params_user_resolves_on_the_rooms_bridge(env):text = _entity_template("user", extra_room=' bridge: "Slack"\n')ok = svc.parse_template(text, inputs={"pick": "bob"})- await svc.check_entity_params(ok)+ await svc.check_entity_params(ok, reader=_reader(env))assert env["rooms"].bridge_user_lookups == [(bridge_id, ["bob"])]bad = svc.parse_template(text, inputs={"pick": "eve"})with pytest.raises(ValueError, match=r"param 'pick': no user named 'eve'"):- await svc.check_entity_params(bad)+ await svc.check_entity_params(bad, reader=_reader(env))@pytest.mark.asyncio@@ -2089,7 +2102,7 @@ async def test_check_entity_params_user_needs_a_bridge(env):svc = _svc(env)parsed = svc.parse_template(_entity_template("user"), inputs={"pick": "bob"})with pytest.raises(ValueError, match=r"param 'pick': a user can only be looked up"):- await svc.check_entity_params(parsed)+ await svc.check_entity_params(parsed, reader=_reader(env))@pytest.mark.asyncio@@ -2100,7 +2113,7 @@ async def test_check_entity_params_ignores_plain_params(env):"params:\n label:\n type: string\nroom:\n name: '{label}'\n description: d\n",inputs={"label": "anything"},)- await svc.check_entity_params(parsed)+ await svc.check_entity_params(parsed, reader=_reader(env))# ── group parse ─────────────────────────────────────────────────────────────@@ -2381,7 +2394,7 @@ rooms:inputs={"pick": "nobody"},)with pytest.raises(ValueError, match="param 'pick': no agent named 'nobody'"):- await svc.check_entity_params(parsed)+ await svc.check_entity_params(parsed, reader=_reader(env))@pytest.mark.asyncio@@ -2508,3 +2521,116 @@ async def test_export_parameterize_round_trip(env):reparsed_default, _ = _svc(env).parse(parameterized)assert reparsed_default.name == "Capture me"+++# ── room params name only rooms the runner can see ──────────────────────────+++async def _seed_room(+ session_factory: async_sessionmaker[AsyncSession],+ name: str,+ *,+ owner_id: str | None = None,+ public: bool = False,+ agent_id: str | None = None,+) -> str:+ """A room owned by `owner_id`, or by a new user bob when absent."""+ visibility = "public" if public else "private"+ async with session_factory() as session:+ if owner_id is None:+ tag = uuid.uuid4().hex[:6]+ bob = User(name=f"bob-{tag}", email=f"bob-{tag}@example.com", role="member")+ session.add(bob)+ await session.flush()+ owner_id = bob.id+ room = Room(+ transport_room_id=f"!{uuid.uuid4().hex}:test.local",+ name=name,+ description="d",+ channel_type="channel_public" if public else "channel_private",+ owner_id=owner_id,+ read_visibility=visibility,+ write_visibility=visibility,+ )+ session.add(room)+ await session.flush()+ if agent_id is not None:+ await session.execute(+ insert(room_agents).values(room_id=room.id, agent_id=agent_id)+ )+ await session.commit()+ return room.id+++ROOM_CHAIN = (+ "params:\n target:\n type: room\n default: [{chain}]\n"+ "room:\n name: n\n description: 'about {{target}}'\n"+)+++async def test_first_room_skips_rooms_the_runner_cannot_read(env):+ """`$first` would otherwise hand alice the name of bob's private room,+ which sorts first, and write it into her new room."""+ await _seed_room(env["session_factory"], "AAA Acquisition")+ await _seed_room(env["session_factory"], "Mine", owner_id=env["user_id"])+ text = ROOM_CHAIN.format(chain="$first")++ filled = await _svc(env).resolve_defaults(text, None, reader=_reader(env))++ assert filled == {"target": "Mine"}+++async def test_a_room_chain_skips_a_name_the_runner_cannot_read(env):+ """A chain must not confirm a private room exists by settling on it."""+ await _seed_room(env["session_factory"], "Layoffs Q1")+ await _seed_room(env["session_factory"], "Town hall", public=True)+ text = ROOM_CHAIN.format(chain="Layoffs Q1, Town hall")++ filled = await _svc(env).resolve_defaults(text, None, reader=_reader(env))++ assert filled == {"target": "Town hall"}+++async def test_someone_elses_private_room_reads_as_missing(env):+ """The refusal is word for word the one for a room that does not exist,+ so a guessed name confirms nothing."""+ await _seed_room(env["session_factory"], "Layoffs Q1")+ svc = _svc(env)+ messages = []+ for name in ("Layoffs Q1", "Layoffs Q2"):+ parsed = svc.parse_template(_entity_template("room"), inputs={"pick": name})+ with pytest.raises(ValueError) as refused:+ await svc.check_entity_params(parsed, reader=_reader(env))+ messages.append(str(refused.value).replace(name, "<name>"))++ assert messages[0] == messages[1]+++async def test_an_admin_may_name_any_room(env):+ await _seed_room(env["session_factory"], "Layoffs Q1")+ svc = _svc(env)+ parsed = svc.parse_template(_entity_template("room"), inputs={"pick": "Layoffs Q1"})++ await svc.check_entity_params(+ parsed, reader=RoomReader(Principal(env["user_id"], True))+ )+++async def test_an_agent_may_name_a_private_room_it_is_in(env):+ """An agent runs a template as its owner, and also sees its own rooms,+ as `list_all_rooms` does."""+ async with env["session_factory"]() as session:+ agent = (+ await session.execute(+ select(Agent).where(Agent.name == "claude-code.alice")+ )+ ).scalar_one()+ await _seed_room(env["session_factory"], "Ops", agent_id=agent.id)+ svc = _svc(env)+ parsed = svc.parse_template(_entity_template("room"), inputs={"pick": "Ops"})++ with pytest.raises(ValueError, match="no room named 'Ops'"):+ await svc.check_entity_params(parsed, reader=_reader(env))+ await svc.check_entity_params(+ parsed, reader=RoomReader(Principal(env["user_id"], False), agent_id=agent.id)+ )