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(agents): list_all_rooms pages and matches names
raullopez-sandbox855b2859b329
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex ec3483088..d5d7528d3 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -426,7 +426,10 @@ none of it is needed to take part in a conversation.- **`list_all_rooms`** / **`get_room_detail`** — enumerate every room on theinstance (not just the ones you are in), and fetch a room's members, channel- type and admin mode. `get_room_detail` also returns the room's assumable+ type and admin mode. `list_all_rooms` answers a page at a time,+ `{rooms, next_cursor}`: pass `next_cursor` back as `cursor` for the next page+ (null on the last), `limit` for its size (default 100, at most 500), and+ `name_contains` to match a name in any case. `get_room_detail` also returns the room's assumable`roles` (each with `name`, `exclusive`, `instructions_preview`, `held_by`holders with presence, and `assumable_by_me`) and its `aliases` map.- **`list_agents`** — every agent on the instance, as opposed to@@ -1072,7 +1075,7 @@ Every Switch tool you call in normal operation, one line each.- `edit_role` — change a role's instructions or exclusivity.- `delete_role` — remove a role and any lease on it.- `list_linked_rooms` — refresh this room's outbound pointers.-- `list_all_rooms` — every room on the instance, not just yours.+- `list_all_rooms` — every room on the instance, not just yours, a page at a time.- `get_room_detail` — one room's members, channel type, roles, aliases.- `list_bridges` — the collaboration bridges available for new rooms.- `create_room` — provision a room. Confirm with the user first.diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 2a7b1cc02..a967be102 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -1463,31 +1463,50 @@ async def add_users_to_room(room_id: str, user_names: list[str]) -> dict[str, An@operation-async def list_all_rooms(include_archived: bool = False) -> list[dict[str, Any]]:+async def list_all_rooms(+ include_archived: bool = False,+ name_contains: str | None = None,+ limit: int = 100,+ cursor: str | None = None,+) -> dict[str, Any]:"""List every room on this Switch instance (not just rooms this agent- is a member of). Use `list_rooms` instead to see only the rooms this- agent is assigned to.+ is a member of), a page at a time, oldest first. Use `list_rooms` instead+ to see only the rooms this agent is assigned to.Args:include_archived: When false (default), archived rooms are omitted.Set true to also include archived rooms (each carries`archived: true`).+ name_contains: Only rooms whose name contains this text, in any case.+ limit: Rooms per page, 1 to 500 (default 100).+ cursor: The `next_cursor` of the previous page, to read the next one.+ Pass the same `include_archived` and `name_contains` with it.Returns:- List of {room_id, name, description, archived} dicts.+ `{"rooms": [{room_id, name, description, archived}, ...],+ "next_cursor"}`; `next_cursor` is null on the last page."""agent_id = get_agent_id()protocol = get_protocol()- rooms = await protocol.list_all_rooms(agent_id, include_archived=include_archived)- return [- {- "room_id": r.id,- "name": r.name,- "description": r.description,- "archived": r.archived_at is not None,- }- for r in rooms- ]+ rooms, next_cursor = await protocol.list_all_rooms(+ agent_id,+ include_archived=include_archived,+ name_contains=name_contains,+ limit=limit,+ cursor=cursor,+ )+ return {+ "rooms": [+ {+ "room_id": r.id,+ "name": r.name,+ "description": r.description,+ "archived": r.archived_at is not None,+ }+ for r in rooms+ ],+ "next_cursor": next_cursor,+ }@operationdiff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex 691240bcb..4ca938067 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -1,6 +1,8 @@from __future__ import annotations+import base64import hashlib+import jsonimport loggingimport reimport secrets@@ -172,6 +174,25 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+LIST_ALL_ROOMS_MAX = 500+++def _encode_room_cursor(created_at: datetime | str, room_id: str) -> str:+ stamp = created_at.isoformat() if isinstance(created_at, datetime) else created_at+ raw = json.dumps([stamp, room_id]).encode()+ return base64.urlsafe_b64encode(raw).decode()+++def _decode_room_cursor(cursor: str) -> tuple[datetime, str]:+ """A `list_all_rooms` cursor's position. It only says where a page starts+ in this tenant's own rooms, so a cursor from elsewhere moves a page and+ reveals nothing."""+ try:+ created_at, room_id = json.loads(base64.urlsafe_b64decode(cursor.encode()))+ return datetime.fromisoformat(created_at), str(room_id)+ except (ValueError, TypeError) as exc:+ raise ValueError("cursor is not one list_all_rooms returned") from exc+# \A and \Z rather than ^ and $: Python's $ also matches before a single# trailing newline, which would let an identifier carry a line break.@@ -3667,17 +3688,32 @@ class AgentCore:await session.commit()async def list_all_rooms(- self, agent_id: str, *, include_archived: bool = False- ) -> list[Room]:- """List all rooms (moderation only).-- Archived rooms are excluded unless `include_archived` is set.- """+ self,+ agent_id: str,+ *,+ include_archived: bool,+ name_contains: str | None,+ limit: int,+ cursor: str | None,+ ) -> tuple[list[Room], str | None]:+ """One page of every room, oldest first, and the cursor for the next+ page (None on the last). Archived rooms are excluded unless+ `include_archived` is set."""+ if not 1 <= limit <= LIST_ALL_ROOMS_MAX:+ raise ValueError(f"limit must be between 1 and {LIST_ALL_ROOMS_MAX}")async with self.session_factory() as session:- rooms = await self.room_store.get_all(- session, include_archived=include_archived+ rooms = await self.room_store.page_all(+ session,+ include_archived=include_archived,+ name_contains=name_contains,+ limit=limit + 1,+ after=_decode_room_cursor(cursor) if cursor is not None else None,)- return rooms+ if len(rooms) <= limit:+ return rooms, None+ rooms = rooms[:limit]+ last = rooms[-1]+ return rooms, _encode_room_cursor(last.created_at, last.id)async def list_room_groups(self, agent_id: str) -> list[dict[str, Any]]:"""List every room group on the instance, with room counts and paths.diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.pyindex 5796413dc..330ddc1c2 100644--- a/core/switch_core/db/stores/room_store.py+++ b/core/switch_core/db/stores/room_store.py@@ -2,8 +2,18 @@ from collections.abc import Collectionfrom dataclasses import dataclassfrom datetime import UTC, datetime-from sqlalchemy import ColumnElement, delete, exists, insert, or_, select, update+from sqlalchemy import (+ ColumnElement,+ delete,+ exists,+ insert,+ literal,+ or_,+ select,+ update,+)from sqlalchemy import func as sa_func+from sqlalchemy import tuple_ as sa_tuplefrom sqlalchemy.dialects.postgresql import insert as pg_insertfrom sqlalchemy.ext.asyncio import AsyncSession@@ -229,6 +239,30 @@ class RoomStore:result = await session.execute(stmt)return list(result.scalars().all())+ async def page_all(+ self,+ session: AsyncSession,+ *,+ include_archived: bool,+ name_contains: str | None,+ limit: int,+ after: tuple[datetime, str] | None,+ ) -> list[Room]:+ """Up to `limit` rooms after the `(created_at, id)` position `after`,+ oldest first, whose name contains `name_contains` (any case)."""+ stmt = select(Room)+ if not include_archived:+ stmt = stmt.where(Room.archived_at.is_(None))+ if name_contains:+ stmt = stmt.where(Room.name.icontains(name_contains, autoescape=True))+ if after is not None:+ stmt = stmt.where(+ sa_tuple(Room.created_at, Room.id)+ > sa_tuple(literal(after[0]), literal(after[1]))+ )+ stmt = stmt.order_by(Room.created_at, Room.id).limit(limit)+ return list((await session.execute(stmt)).scalars().all())+async def list_readable(self,session: AsyncSession,diff --git a/core/tests/switch_core/bridges/agent/test_list_all_rooms_paging.py b/core/tests/switch_core/bridges/agent/test_list_all_rooms_paging.pynew file mode 100644index 000000000..64019d844--- /dev/null+++ b/core/tests/switch_core/bridges/agent/test_list_all_rooms_paging.py@@ -0,0 +1,97 @@+"""`list_all_rooms` pages every room oldest first by an opaque cursor, and can+match a name in any case. Real Postgres."""++from __future__ import annotations++import base64+from datetime import UTC, datetime, timedelta+from types import SimpleNamespace++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.protocol.agent_core import AgentCore+from switch_core.db.models import Room+from switch_core.db.stores.room_store import RoomStore++_START = datetime(2026, 1, 1, tzinfo=UTC)+++async def _rooms(session_factory: async_sessionmaker[AsyncSession]) -> list[str]:+ names = ["Alpha", "beta", "Gamma alpha", "delta", "ALPHA two", "old alpha"]+ async with session_factory() as session:+ rooms = [+ Room(+ transport_room_id=f"!{index}:test",+ name=name,+ description="",+ # Two rooms share a moment, so the id has to break the tie.+ created_at=_START + timedelta(minutes=min(index, 4)),+ archived_at=_START if name == "old alpha" else None,+ )+ for index, name in enumerate(names)+ ]+ session.add_all(rooms)+ await session.commit()+ return [room.id for room in rooms]+++def _list(session_factory: async_sessionmaker[AsyncSession], **kwargs: object):+ protocol = SimpleNamespace(session_factory=session_factory, room_store=RoomStore())+ defaults: dict[str, object] = {+ "include_archived": False,+ "name_contains": None,+ "limit": 100,+ "cursor": None,+ }+ return AgentCore.list_all_rooms(protocol, "agent-1", **{**defaults, **kwargs}) # type: ignore[arg-type]+++async def test_pages_walk_every_room_once_in_order(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ await _rooms(session_factory)+ seen: list[str] = []+ cursor = None+ pages = 0+ while True:+ rooms, cursor = await _list(session_factory, limit=2, cursor=cursor)+ seen.extend(room.name for room in rooms)+ pages += 1+ if cursor is None:+ break+ assert pages == 3+ assert sorted(seen) == sorted(+ ["Alpha", "beta", "Gamma alpha", "delta", "ALPHA two"]+ )+ assert seen[:4] == ["Alpha", "beta", "Gamma alpha", "delta"]++ everything, last = await _list(session_factory, include_archived=True)+ assert last is None and len(everything) == 6+++async def test_a_name_filter_matches_in_any_case(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ await _rooms(session_factory)+ rooms, cursor = await _list(session_factory, name_contains="alpha")+ assert {room.name for room in rooms} == {"Alpha", "Gamma alpha", "ALPHA two"}+ assert cursor is None+ archived_too, _ = await _list(+ session_factory, name_contains="ALPHA", include_archived=True+ )+ assert "old alpha" in {room.name for room in archived_too}+ none, cursor = await _list(session_factory, name_contains="no such room")+ assert (none, cursor) == ([], None)+++async def test_a_bad_cursor_or_limit_is_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ await _rooms(session_factory)+ for cursor in ("not-a-cursor", base64.urlsafe_b64encode(b'{"x": 1}').decode()):+ with pytest.raises(ValueError, match="cursor"):+ await _list(session_factory, cursor=cursor)+ for limit in (0, 501):+ with pytest.raises(ValueError, match="limit"):+ await _list(session_factory, limit=limit)