Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Carry packages through room templates, and list them in the room commands (#984)

Abel Dantas970cd428b7bf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fb82824ed..9749a14b1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,6 +44,15 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
+#### Added
+- **Templates carry packages.** A room in a template takes `packages:`, a list
+ of packages that already exist, by `id` or by `name`, attached when the room
+ is created. The person running the template must be able to attach each one
+ by hand; a package that is missing, ambiguous or not theirs stops the run
+ before the room exists. A template never creates or changes a package.
+ Capturing a room (`GET /rooms/{id}/yaml`) now lists its packages by `id`,
+ so a room built again from its capture gets them back (#910).
+
#### Changed
- **Following the conversation is described the same way everywhere, and the
chart can turn it on.** The feature added in 0.31.0 is off unless
@@ -64,6 +73,13 @@ version of their own to them without also giving them a release of their own.
answer, otherwise the agent's owner if they may answer, otherwise nobody.
It never mentions more than one person, even when the policy lets anyone
answer. Cards at the top of a channel mention whoever asked, as before.
+- **`!list-references` and `!list-documents` include what packages bring.**
+ They listed only what was attached to the room directly, so a room whose
+ references all came from a package answered "No references in this room."
+ while its agents were sent them. Items from attached packages now follow
+ the direct ones, each marked with the package it comes from (for example
+ `(github, via Payments service context)`); an item attached both ways is
+ listed once, as direct (#911).
- **The template guide agents read now covers a room's `roles:`,
`references:` and `docs:`.** All three already worked in a room resource
and appear when a room is captured, but the guide stopped at `aliases:`, so
diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.py
index 27f03b212..12023e1ef 100644
--- a/core/switch_core/bridges/agent/commands.py
+++ b/core/switch_core/bridges/agent/commands.py
@@ -1609,6 +1609,34 @@ async def _cmd_roles(
await _reply(client, room, event, "\n".join(lines))
+async def _package_sources(
+ client: AgentRecipient,
+ session: AsyncSession,
+ room_id: str,
+ kind: Literal["reference", "document"],
+) -> dict[str, list[str]]:
+ """Each item the room's packages bring, to the names of the packages that
+ bring it. An agent in the room is sent every one of them, so they are
+ listed whoever asks."""
+ sources: dict[str, list[str]] = {}
+ for pkg in await client._package_store.list_for_room(session, room_id):
+ if kind == "reference":
+ ids = await client._package_store.list_reference_ids_for_package(
+ session, pkg.id
+ )
+ else:
+ ids = await client._package_store.list_document_ids_for_package(
+ session, pkg.id
+ )
+ for item_id in ids:
+ sources.setdefault(item_id, []).append(pkg.name)
+ return sources
+
+
+def _via(package_names: list[str]) -> str:
+ return "via " + ", ".join(package_names)
+
+
async def _cmd_list_documents(
client: AgentRecipient,
room: RoomRef,
@@ -1621,7 +1649,14 @@ async def _cmd_list_documents(
return
async with client.session_factory() as session:
- docs = await client._document_store.list_for_room(session, meta.room_id)
+ direct = await client._document_store.list_for_room(session, meta.room_id)
+ sources = await _package_sources(client, session, meta.room_id, "document")
+ direct_ids = {d.id for d in direct}
+ fetched = await client._document_store.get_many(
+ session, [i for i in sources if i not in direct_ids]
+ )
+ by_id = {d.id: d for d in fetched}
+ docs = [*direct, *(by_id[i] for i in sources if i in by_id)]
if not docs:
await _reply(client, room, event, "No internal documents in this room.")
return
@@ -1634,6 +1669,7 @@ async def _cmd_list_documents(
lines = ["**Internal documents in this room:**"]
for d in docs:
scope = " _(room-scoped)_" if d.room_id is not None else ""
+ via = f" _({_via(sources[d.id])})_" if d.id not in direct_ids else ""
creator = ""
if d.created_by_agent_id:
agent = await client._agent_store.get(session, d.created_by_agent_id)
@@ -1650,7 +1686,7 @@ async def _cmd_list_documents(
else:
url = f"{client._frontend_base_url}/resources/documents/{d.id}"
name_md = f"[{d.name}]({url})"
- lines.append(f"- {name_md}{scope}{desc}{creator}")
+ lines.append(f"- {name_md}{scope}{via}{desc}{creator}")
await _reply(client, room, event, "\n".join(lines))
@@ -1667,7 +1703,17 @@ async def _cmd_list_references(
return
async with client.session_factory() as session:
- refs = await client._reference_store.list_for_room(session, meta.room_id)
+ direct = await client._reference_store.list_for_room(session, meta.room_id)
+ sources = await _package_sources(client, session, meta.room_id, "reference")
+ direct_ids = {r.id for r in direct}
+ from_packages = []
+ for ref_id in sources:
+ if ref_id in direct_ids:
+ continue
+ ref = await client._reference_store.get(session, ref_id)
+ if ref is not None:
+ from_packages.append(ref)
+ refs = [*direct, *from_packages]
if not refs:
await _reply(client, room, event, "No references in this room.")
@@ -1686,7 +1732,10 @@ async def _cmd_list_references(
else:
url = f"{client._frontend_base_url}/resources/references/{ref.id}"
name_md = f"[{ref.name}]({url})"
- lines.append(f"- {name_md} _({ref.type})_{desc}")
+ kind = (
+ ref.type if ref.id in direct_ids else f"{ref.type}, {_via(sources[ref.id])}"
+ )
+ lines.append(f"- {name_md} _({kind})_{desc}")
await _reply(client, room, event, "\n".join(lines))
diff --git a/core/switch_core/delivery/recipient.py b/core/switch_core/delivery/recipient.py
index 3ce10db65..8030d0f64 100644
--- a/core/switch_core/delivery/recipient.py
+++ b/core/switch_core/delivery/recipient.py
@@ -106,6 +106,7 @@ if TYPE_CHECKING:
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.document_store import DocumentStore
from switch_core.db.stores.external_user_store import ExternalUserStore
+ from switch_core.db.stores.package_store import PackageStore
from switch_core.db.stores.reference_store import ReferenceStore
from switch_core.db.stores.room_role_store import RoomRoleStore
from switch_core.db.stores.room_store import RoomStore
@@ -181,6 +182,7 @@ class RecipientServices:
room_store: RoomStore
document_store: DocumentStore
reference_store: ReferenceStore
+ package_store: PackageStore
agent_session_store: AgentSessionStore
room_role_store: RoomRoleStore
external_user_store: ExternalUserStore
@@ -494,6 +496,7 @@ class AgentRecipient:
self._room_store = services.room_store
self._document_store = services.document_store
self._reference_store = services.reference_store
+ self._package_store = services.package_store
self._agent_session_store = services.agent_session_store
self._room_role_store = services.room_role_store
self._external_user_store = services.external_user_store
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index 2e52d08f5..615091076 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -795,6 +795,7 @@ async def export_room_yaml(
agents: Annotated[bool, Query()] = True,
users: Annotated[bool, Query()] = True,
references: Annotated[bool, Query()] = True,
+ packages: Annotated[bool, Query()] = True,
docs: Annotated[bool, Query()] = True,
roles: Annotated[bool, Query()] = True,
) -> Response:
@@ -806,6 +807,7 @@ async def export_room_yaml(
agents=agents,
users=users,
references=references,
+ packages=packages,
docs=docs,
roles=roles,
)
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index 93f72f7fa..ff9276268 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -813,6 +813,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:
room_store=room_store,
document_store=document_store,
reference_store=reference_store,
+ package_store=package_store,
agent_session_store=agent_session_store,
room_role_store=room_role_store,
external_user_store=external_user_store,
diff --git a/core/switch_core/rooms_yaml.py b/core/switch_core/rooms_yaml.py
index 4ce907f5a..f194c6da0 100644
--- a/core/switch_core/rooms_yaml.py
+++ b/core/switch_core/rooms_yaml.py
@@ -408,6 +408,28 @@ ExternalReferenceEntry = (
)
+# A package in a room spec is always one that exists: a template attaches
+# packages but never defines or changes one, so there is no inline shape.
+
+
+class ExistingPackageById(BaseModel):
+ """Attach an existing package by id (exact, unambiguous)."""
+
+ model_config = {"extra": "forbid"}
+ id: str
+
+
+class ExistingPackageByName(BaseModel):
+ """Attach an existing package by name (resolved over the caller's owned +
+ public packages; ambiguity is an error)."""
+
+ model_config = {"extra": "forbid"}
+ name: str
+
+
+PackageEntry = ExistingPackageById | ExistingPackageByName
+
+
class DocSpec(BaseModel):
name: str
description: str
@@ -428,6 +450,7 @@ class RoomSpec(BaseModel):
users: list[str] = []
roles: list[RoleSpec] = []
references: list[ExternalReferenceEntry] = []
+ packages: list[PackageEntry] = []
docs: list[DocSpec] = []
# Agent name to the alias it can be addressed by in this room.
aliases: dict[str, str] | None = None
@@ -503,6 +526,7 @@ class ProvisionResult(BaseModel):
room_id: str
room_name: str
attached_reference_ids: list[str] = []
+ attached_package_ids: list[str] = []
created_reference_ids: list[str] = []
created_document_ids: list[str] = []
role_names: list[str] = []
@@ -1007,6 +1031,9 @@ class RoomYamlService:
attached_ref_ids, inline_refs = await self._resolve_references(
spec.references, user_id=user_id, is_admin=is_admin
)
+ attached_package_ids = await self._resolve_packages(
+ spec.packages, user_id=user_id, is_admin=is_admin
+ )
config = RoomCreateConfig(
name=spec.name,
@@ -1031,6 +1058,7 @@ class RoomYamlService:
write_visibility=spec.write_visibility,
roles=spec.roles or None,
reference_ids=attached_ref_ids or None,
+ package_ids=attached_package_ids or None,
aliases=spec.aliases,
)
result = await self._rooms.create_room(config)
@@ -1064,6 +1092,7 @@ class RoomYamlService:
room_id=room_id,
room_name=result.room.name,
attached_reference_ids=attached_ref_ids,
+ attached_package_ids=attached_package_ids,
created_reference_ids=created_ref_ids,
created_document_ids=created_doc_ids,
role_names=[r.name for r in spec.roles],
@@ -1232,6 +1261,44 @@ class RoomYamlService:
inline.append(entry)
return attached_ids, inline
+ async def _resolve_packages(
+ self, entries: list[PackageEntry], *, user_id: str, is_admin: bool
+ ) -> list[str]:
+ """Resolve the packages to attach up front, failing loud on a missing,
+ ambiguous or unreadable one, so the room is not created without it.
+ Attaching needs read access, as it does by hand."""
+ attached_ids: list[str] = []
+ async with self._session_factory() as session:
+ visible = await self._resources.list_packages_for_user(session, user_id)
+ by_name: dict[str, list[str]] = {}
+ for pkg in visible:
+ by_name.setdefault(pkg.name, []).append(pkg.id)
+ for entry in entries:
+ if isinstance(entry, ExistingPackageById):
+ try:
+ await self._resources.get_package_for_user(
+ session, entry.id, user_id, is_admin=is_admin
+ )
+ except PermissionError as e:
+ raise PermissionError(
+ f"Cannot attach package {entry.id!r}: {e}"
+ ) from e
+ attached_ids.append(entry.id)
+ else:
+ matches = by_name.get(entry.name, [])
+ if not matches:
+ raise ValueError(
+ f"No package named {entry.name!r} is accessible"
+ )
+ if len(matches) > 1:
+ raise ValueError(
+ f"Ambiguous package name {entry.name!r}: "
+ f"{len(matches)} matches; attach by 'id' instead"
+ )
+ attached_ids.append(matches[0])
+ # A package named twice (by id and by name, say) is attached once.
+ return list(dict.fromkeys(attached_ids))
+
async def _create_inline_references(
self,
room_id: str,
@@ -1415,14 +1482,17 @@ class RoomYamlService:
agents: bool = True,
users: bool = True,
references: bool = True,
+ packages: bool = True,
docs: bool = True,
roles: bool = True,
) -> str:
"""Read a live room back into the import surface and dump it to YAML.
- References export as attach-by-``id``. Only room-scoped documents are
- exported (as inline docs) — they are the only docs the import surface
- can recreate. Each section can be dropped via its toggle.
+ References and packages export as attach-by-``id``. Only room-scoped
+ documents are exported (as inline docs): they are the only docs the
+ import surface can recreate. A package's own references and documents
+ are not exported, since attaching the package brings them. Each
+ section can be dropped via its toggle.
"""
async with self._session_factory() as session:
room = await self._room_store.get(session, room_id)
@@ -1499,6 +1569,11 @@ class RoomYamlService:
if refs:
data["references"] = [{"id": r.id} for r in refs]
+ if packages:
+ pkgs = await self._resources.list_room_packages(session, room.id)
+ if pkgs:
+ data["packages"] = [{"id": p.id} for p in pkgs]
+
if docs:
room_docs = await self._resources.list_room_documents(session, room.id)
scoped = [d for d in room_docs if d.room_id == room.id]
diff --git a/core/switch_core/template_guide.py b/core/switch_core/template_guide.py
index 8ceaca61d..189f1bea9 100644
--- a/core/switch_core/template_guide.py
+++ b/core/switch_core/template_guide.py
@@ -119,6 +119,8 @@ existing agent may stand in for it.
value: {urls: [...]}}]
docs: [{name, description, instructions, content}]
aliases: {agent key or name: alias} # @alias addresses it in this room
+ packages: [{id: package id} or {name: package name}] # packages that
+ # exist, attached as they are
kickoff: text # posted once the room exists
group: <group key> # when the template has a group
@@ -152,7 +154,8 @@ references by id:
Without bridge the room goes on the server's default messaging app; users
needs one (make them depend on it: [{if: "{bridge}", value: [...]},
-{value: []}]). Several rooms go in one group.
+{value: []}]). Several rooms go in one group. packages must be ones the
+deployer can attach by hand; a missing or ambiguous one stops the run.
## A group (type: group)
diff --git a/core/tests/benchmarks/server.py b/core/tests/benchmarks/server.py
index 42f541a4b..a3278a1c6 100644
--- a/core/tests/benchmarks/server.py
+++ b/core/tests/benchmarks/server.py
@@ -519,6 +519,7 @@ async def _serve(
room_store=session_env.room_store,
document_store=session_env.document_store,
reference_store=session_env.reference_store,
+ package_store=session_env.package_store,
agent_session_store=session_env.agent_session_store,
room_role_store=session_env.room_role_store,
external_user_store=session_env.external_user_store,
diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.py
index 48cb77a91..e392fb029 100644
--- a/core/tests/integration/conftest.py
+++ b/core/tests/integration/conftest.py
@@ -614,6 +614,7 @@ async def harness(
room_store=session_env.room_store,
document_store=session_env.document_store,
reference_store=session_env.reference_store,
+ package_store=session_env.package_store,
agent_session_store=session_env.agent_session_store,
room_role_store=session_env.room_role_store,
external_user_store=session_env.external_user_store,
diff --git a/core/tests/routing.py b/core/tests/routing.py
index 87bcd84b9..ad1725f98 100644
--- a/core/tests/routing.py
+++ b/core/tests/routing.py
@@ -49,6 +49,7 @@ from switch_core.db.stores.document_store import DocumentStore
from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.media_store import MediaStore
from switch_core.db.stores.message_store import MessageStore
+from switch_core.db.stores.package_store import PackageStore
from switch_core.db.stores.reference_store import ReferenceStore
from switch_core.db.stores.room_role_store import RoomRoleStore
from switch_core.db.stores.room_store import RoomStore
@@ -210,6 +211,7 @@ def router_on(
room_store=RoomStore(),
document_store=DocumentStore(),
reference_store=ReferenceStore(),
+ package_store=PackageStore(),
agent_session_store=AgentSessionStore(),
room_role_store=RoomRoleStore(),
external_user_store=ExternalUserStore(),
diff --git a/core/tests/switch_core/bridges/agent/test_commands_display_names.py b/core/tests/switch_core/bridges/agent/test_commands_display_names.py
index 8daa5bd14..b96d2e930 100644
--- a/core/tests/switch_core/bridges/agent/test_commands_display_names.py
+++ b/core/tests/switch_core/bridges/agent/test_commands_display_names.py
@@ -102,6 +102,12 @@ def _build_client(
async def _list_for_room(_session, _room_id): # type: ignore[no-untyped-def]
return list(documents or [])
+ async def _get_many(_session, _ids): # type: ignore[no-untyped-def]
+ return []
+
+ async def _no_packages(_session, _room_id): # type: ignore[no-untyped-def]
+ return []
+
async def _fresh_agent(_session): # type: ignore[no-untyped-def]
return this_agent
@@ -117,7 +123,10 @@ def _build_client(
_room_role_store=SimpleNamespace(
list_roles=_list_roles, live_holders_for_room=_live_holders_for_room
),
- _document_store=SimpleNamespace(list_for_room=_list_for_room),
+ _document_store=SimpleNamespace(
+ list_for_room=_list_for_room, get_many=_get_many
+ ),
+ _package_store=SimpleNamespace(list_for_room=_no_packages),
_connections=SimpleNamespace(live_connection_ids=lambda: set()),
)
return client, posted
diff --git a/core/tests/switch_core/bridges/agent/test_commands_list_resources.py b/core/tests/switch_core/bridges/agent/test_commands_list_resources.py
new file mode 100644
index 000000000..38dfad586
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/test_commands_list_resources.py
@@ -0,0 +1,171 @@
+"""`!list-references` and `!list-documents` list what the room's packages bring
+as well as what is attached to the room directly, since agents in the room
+are sent both."""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from typing import Any
+
+from switch_core.bridges.agent.commands import (
+ _cmd_list_documents,
+ _cmd_list_references,
+)
+
+
+def _ref(ref_id: str, name: str, type_: str = "github") -> SimpleNamespace:
+ return SimpleNamespace(id=ref_id, name=name, type=type_, description="")
+
+
+def _doc(doc_id: str, name: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ id=doc_id,
+ name=name,
+ description="",
+ room_id=None,
+ created_by_agent_id=None,
+ )
+
+
+def _build_client(
+ *,
+ direct_refs: Sequence[Any] = (),
+ direct_docs: Sequence[Any] = (),
+ packages: Sequence[tuple[str, list[Any], list[Any]]] = (),
+) -> tuple[SimpleNamespace, list[str]]:
+ """A fake client for a room with `direct_*` attached to it and `packages`
+ given as (name, references, documents)."""
+ posted: list[str] = []
+ pkgs = [
+ SimpleNamespace(id=f"pkg-{i}", name=name, refs=refs, docs=docs)
+ for i, (name, refs, docs) in enumerate(packages)
+ ]
+ all_refs = {r.id: r for r in direct_refs}
+ all_docs = {d.id: d for d in direct_docs}
+ for p in pkgs:
+ all_refs.update({r.id: r for r in p.refs})
+ all_docs.update({d.id: d for d in p.docs})
+ by_pkg = {p.id: p for p in pkgs}
+
+ @asynccontextmanager
+ async def _session_factory(): # type: ignore[no-untyped-def]
+ yield SimpleNamespace()
+
+ async def _resolve_room_meta(_room_id: str) -> SimpleNamespace:
+ return SimpleNamespace(room_id="room-1", name="Feature room")
+
+ async def _send_message(_room_id, body, **_kw): # type: ignore[no-untyped-def]
+ posted.append(body)
+
+ async def _refs_for_room(_session, _room_id): # type: ignore[no-untyped-def]
+ return list(direct_refs)
+
+ async def _ref_get(_session, ref_id): # type: ignore[no-untyped-def]
+ return all_refs.get(ref_id)
+
+ async def _docs_for_room(_session, _room_id): # type: ignore[no-untyped-def]
+ return list(direct_docs)
+
+ async def _docs_get_many(_session, ids): # type: ignore[no-untyped-def]
+ # Reversed, as the store promises no order.
+ return [all_docs[i] for i in reversed(ids) if i in all_docs]
+
+ async def _pkgs_for_room(_session, _room_id): # type: ignore[no-untyped-def]
+ return list(pkgs)
+
+ async def _pkg_ref_ids(_session, pkg_id): # type: ignore[no-untyped-def]
+ return [r.id for r in by_pkg[pkg_id].refs]
+
+ async def _pkg_doc_ids(_session, pkg_id): # type: ignore[no-untyped-def]
+ return [d.id for d in by_pkg[pkg_id].docs]
+
+ client = SimpleNamespace(
+ session_factory=_session_factory,
+ _resolve_room_meta=_resolve_room_meta,
+ send_message=_send_message,
+ reply_command=_send_message,
+ _frontend_base_url=None,
+ _reference_store=SimpleNamespace(list_for_room=_refs_for_room, get=_ref_get),
+ _document_store=SimpleNamespace(
+ list_for_room=_docs_for_room, get_many=_docs_get_many
+ ),
+ _package_store=SimpleNamespace(
+ list_for_room=_pkgs_for_room,
+ list_reference_ids_for_package=_pkg_ref_ids,
+ list_document_ids_for_package=_pkg_doc_ids,
+ ),
+ _agent_store=SimpleNamespace(get=None),
+ )
+ return client, posted
+
+
+_ROOM = SimpleNamespace(room_id="!r:x")
+
+
+def _event(command: str) -> SimpleNamespace:
+ return SimpleNamespace(command=command, args="", thread_id=None)
+
+
+class TestListReferences:
+ async def test_lists_a_reference_that_only_a_package_brings(self) -> None:
+ client, posted = _build_client(
+ packages=[("Payments service context", [_ref("r1", "payments-repo")], [])]
+ )
+ await _cmd_list_references(client, _ROOM, _event("list-references"), False)
+ assert posted == [
+ "**References in this room:**\n"
+ "- **payments-repo** _(github, via Payments service context)_"
+ ]
+
+ async def test_direct_first_and_an_item_in_both_shown_once_as_direct(
+ self,
+ ) -> None:
+ shared = _ref("r1", "shared-repo")
+ client, posted = _build_client(
+ direct_refs=[shared],
+ packages=[
+ ("Pkg A", [shared, _ref("r2", "a-repo")], []),
+ ("Pkg B", [_ref("r2", "a-repo"), _ref("r3", "b-board", "jira")], []),
+ ],
+ )
+ await _cmd_list_references(client, _ROOM, _event("list-references"), False)
+ assert posted[0].splitlines() == [
+ "**References in this room:**",
+ "- **shared-repo** _(github)_",
+ "- **a-repo** _(github, via Pkg A, Pkg B)_",
+ "- **b-board** _(jira, via Pkg B)_",
+ ]
+
+ async def test_none_from_either_source(self) -> None:
+ client, posted = _build_client(packages=[("Empty", [], [])])
+ await _cmd_list_references(client, _ROOM, _event("list-references"), False)
+ assert posted == ["No references in this room."]
+
+
+class TestListDocuments:
+ async def test_lists_documents_packages_bring_after_direct_ones(self) -> None:
+ shared = _doc("d1", "Runbook")
+ client, posted = _build_client(
+ direct_docs=[shared],
+ packages=[
+ (
+ "Payments service context",
+ [],
+ [shared, _doc("d2", "Glossary"), _doc("d3", "Oncall")],
+ )
+ ],
+ )
+ await _cmd_list_documents(client, _ROOM, _event("list-documents"), False)
+ assert posted[0].splitlines() == [
+ "**Internal documents in this room:**",
+ "- **Runbook**",
+ "- **Glossary** _(via Payments service context)_",
+ "- **Oncall** _(via Payments service context)_",
+ ]
+
+ async def test_none_from_either_source(self) -> None:
+ client, posted = _build_client()
+ await _cmd_list_documents(client, _ROOM, _event("list-documents"), False)
+ assert posted == ["No internal documents in this room."]
diff --git a/core/tests/switch_core/test_rooms_yaml.py b/core/tests/switch_core/test_rooms_yaml.py
index 9cb6273eb..3b7790a21 100644
--- a/core/tests/switch_core/test_rooms_yaml.py
+++ b/core/tests/switch_core/test_rooms_yaml.py
@@ -38,6 +38,7 @@ from switch_core.db.models import (
RoomRole,
User,
room_agents,
+ room_packages,
room_references,
)
from switch_core.db.stores.agent_store import AgentStore
@@ -53,6 +54,8 @@ from switch_core.db.stores.room_role_store import RoomRoleStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.room_service import RoomCreateConfig, RoomCreateResult
from switch_core.rooms_yaml import (
+ ExistingPackageById,
+ ExistingPackageByName,
ExistingReferenceById,
GroupSpec,
ParamSpec,
@@ -141,6 +144,10 @@ class FakeRoomService:
await session.execute(
insert(room_references).values(room_id=room.id, reference_id=rid)
)
+ for pid in config.package_ids or []:
+ await session.execute(
+ insert(room_packages).values(room_id=room.id, package_id=pid)
+ )
await session.commit()
return RoomCreateResult(room=room, failed_attachments=[])
@@ -569,6 +576,199 @@ async def test_provision_ambiguous_reference_name_fails(env):
await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+async def _make_package(
+ env, name: str, *, owner_id: str | None = None, read_visibility: str = "private"
+) -> str:
+ async with env["session_factory"]() as session:
+ pkg = await env["resource_service"].create_package(
+ session,
+ owner_id=owner_id or env["user_id"],
+ read_visibility=read_visibility,
+ write_visibility="private",
+ name=name,
+ description="d",
+ instructions="i",
+ )
+ await session.commit()
+ return pkg.id
+
+
+async def _room_package_ids(env, room_id: str) -> list[str]:
+ async with env["session_factory"]() as session:
+ rows = await session.execute(
+ select(room_packages.c.package_id).where(room_packages.c.room_id == room_id)
+ )
+ return list(rows.scalars().all())
+
+
+async def _other_user(env) -> str:
+ async with env["session_factory"]() as session:
+ other = User(name="mallory", email="[email protected]", role="member")
+ session.add(other)
+ await session.commit()
+ return other.id
+
+
+def test_parse_packages_by_id_and_by_name(env):
+ spec, _ = _svc(env).parse(
+ """
+ room:
+ name: "R"
+ description: "d"
+ packages:
+ - { id: "pkg-1" }
+ - { name: "Payments context" }
+ """
+ )
+ assert spec.packages == [
+ ExistingPackageById(id="pkg-1"),
+ ExistingPackageByName(name="Payments context"),
+ ]
+
+
+def test_parse_package_entry_refuses_an_inline_definition(env):
+ with pytest.raises(ValueError, match="Invalid room spec"):
+ _svc(env).parse(
+ """
+ room:
+ name: "R"
+ description: "d"
+ packages:
+ - { name: "New", description: "d", instructions: "i" }
+ """
+ )
+
+
+async def test_provision_attaches_packages_by_id_and_by_name(env):
+ by_id = await _make_package(env, "By id")
+ by_name = await _make_package(env, "Payments context")
+
+ spec, _ = _svc(env).parse(
+ f"""
+ room:
+ name: "With packages"
+ description: "d"
+ packages:
+ - {{ id: "{by_id}" }}
+ - {{ name: "Payments context" }}
+ """
+ )
+ result = await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+
+ assert result.attached_package_ids == [by_id, by_name]
+ assert result.failed_attachments == []
+ assert sorted(await _room_package_ids(env, result.room_id)) == sorted(
+ [by_id, by_name]
+ )
+
+
+async def test_provision_attaches_a_public_package_of_another_user_by_name(env):
+ other = await _other_user(env)
+ pkg_id = await _make_package(
+ env, "Shared context", owner_id=other, read_visibility="public"
+ )
+ spec, _ = _svc(env).parse(
+ """
+ room:
+ name: "R"
+ description: "d"
+ packages:
+ - { name: "Shared context" }
+ """
+ )
+ result = await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+ assert result.attached_package_ids == [pkg_id]
+
+
+async def test_provision_unknown_package_id_fails_before_the_room_exists(env):
+ spec, _ = _svc(env).parse(
+ """
+ room:
+ name: "No such package"
+ description: "d"
+ packages:
+ - { id: "does-not-exist" }
+ """
+ )
+ with pytest.raises(ValueError, match="Package not found: does-not-exist"):
+ await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+
+ async with env["session_factory"]() as session:
+ rooms = (
+ (await session.execute(select(Room).where(Room.name == "No such package")))
+ .scalars()
+ .all()
+ )
+ assert rooms == []
+
+
+async def test_provision_unknown_package_name_fails(env):
+ spec, _ = _svc(env).parse(
+ """
+ room:
+ name: "R"
+ description: "d"
+ packages:
+ - { name: "no such package" }
+ """
+ )
+ with pytest.raises(ValueError, match="No package named 'no such package'"):
+ await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+
+
+async def test_provision_private_package_of_another_user_fails(env):
+ """A template attaches only what its runner could attach by hand: another
+ user's private package is refused by id and invisible by name."""
+ other = await _other_user(env)
+ pkg_id = await _make_package(env, "Secret context", owner_id=other)
+
+ by_id, _ = _svc(env).parse(
+ f"""
+ room:
+ name: "R"
+ description: "d"
+ packages:
+ - {{ id: "{pkg_id}" }}
+ """
+ )
+ with pytest.raises(PermissionError, match=f"Cannot attach package '{pkg_id}'"):
+ await _svc(env).provision(by_id, user_id=env["user_id"], is_admin=False)
+
+ by_name, _ = _svc(env).parse(
+ """
+ room:
+ name: "R"
+ description: "d"
+ packages:
+ - { name: "Secret context" }
+ """
+ )
+ with pytest.raises(ValueError, match="No package named 'Secret context'"):
+ await _svc(env).provision(by_name, user_id=env["user_id"], is_admin=False)
+
+
+async def test_provision_ambiguous_package_name_fails(env):
+ await _make_package(env, "dup")
+ await _make_package(env, "dup")
+ spec, _ = _svc(env).parse(
+ """
+ room:
+ name: "R"
+ description: "d"
+ packages:
+ - { name: "dup" }
+ """
+ )
+ with pytest.raises(ValueError, match="Ambiguous package name 'dup'"):
+ await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+
+
@pytest.mark.asyncio
async def test_provision_duplicate_doc_name_is_best_effort(env):
spec, _ = _svc(env).parse(
@@ -649,6 +849,32 @@ async def test_export_round_trips_within_import_surface(env):
assert reparsed.docs[0].content == "line1\nline2"
+async def test_export_emits_packages_and_round_trips(env):
+ pkg_id = await _make_package(env, "Payments context")
+ spec, _ = _svc(env).parse(
+ """
+ room:
+ name: "Packaged"
+ description: "d"
+ packages:
+ - { name: "Payments context" }
+ """
+ )
+ result = await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+
+ yaml_text = await _svc(env).export(result.room_id)
+ assert yaml.safe_load(yaml_text)["room"]["packages"] == [{"id": pkg_id}]
+
+ reparsed, _ = _svc(env).parse(yaml_text)
+ assert reparsed.packages == [ExistingPackageById(id=pkg_id)]
+ again = await _svc(env).provision(reparsed, user_id=env["user_id"], is_admin=False)
+ assert await _room_package_ids(env, again.room_id) == [pkg_id]
+
+ without = await _svc(env).export(result.room_id, packages=False)
+ assert "packages" not in yaml.safe_load(without)["room"]
+
+
@pytest.mark.asyncio
async def test_export_toggles_drop_sections(env):
spec, _ = _svc(env).parse(
diff --git a/core/tests/switch_core/test_template_v2.py b/core/tests/switch_core/test_template_v2.py
index aa28ac3ad..48e542abc 100644
--- a/core/tests/switch_core/test_template_v2.py
+++ b/core/tests/switch_core/test_template_v2.py
@@ -8,6 +8,7 @@ import pytest
import yaml
from switch_core.agent_templates import agent_slots, plan_template, template_kind
+from switch_core.rooms_yaml import ExistingPackageById, ExistingPackageByName, RoomSpec
from switch_core.template_lint import lint_template
from switch_core.template_v2 import TemplateError, compile_v2, holds
@@ -112,6 +113,30 @@ def test_a_reference_to_a_resource_that_is_off_is_refused():
_compiled({}, text)
+def test_a_rooms_packages_pass_through_to_the_room_block():
+ text = """\
+version: 2
+params:
+ context: { type: string, default: Payments context }
+resources:
+ work:
+ type: room
+ name: Work
+ description: d
+ packages: [{id: pkg-1}, {name: "{context}"}]
+"""
+ compiled = compile_v2(text, {}, {"$creator": "ada"})
+ doc = yaml.safe_load(compiled.document)
+ assert doc["room"]["packages"] == [{"id": "pkg-1"}, {"name": "{context}"}]
+ room = RoomSpec.model_validate(
+ {**doc["room"], "packages": [{"id": "pkg-1"}, {"name": "Payments context"}]}
+ )
+ assert room.packages == [
+ ExistingPackageById(id="pkg-1"),
+ ExistingPackageByName(name="Payments context"),
+ ]
+
+
def test_several_rooms_need_a_group_and_links_name_rooms_by_key():
text = """\
version: 2
diff --git a/docs/TEMPLATES.md b/docs/TEMPLATES.md
index df6aedcd4..f56f895b5 100644
--- a/docs/TEMPLATES.md
+++ b/docs/TEMPLATES.md
@@ -439,6 +439,7 @@ room:
users: [ usernames ]
roles: [ ... ]
references: [ ... ]
+ packages: [ {id: package id} or {name: package name} ]
docs: [ ... ]
aliases: { agent name: alias }
```
@@ -465,6 +466,13 @@ by their username on the room's messaging app; `{$creator}` puts the
deployer in. Without `bridge:` the room is created on the server's default
messaging app; on a server with none, it is a Switch-only room.
+`packages:` attaches packages that already exist, by `id` or by `name`; a
+template never creates or changes one. The deployer must be able to read
+each package, as when attaching it by hand, and a name must match exactly
+one package they own or that is public. A package that is missing, ambiguous
+or not theirs to attach stops the run before the room is created. An
+exported room lists its packages by `id`.
+
## Groups
```yaml
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index b57a44c42..0fe9b913d 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -338,6 +338,7 @@ export interface ProvisionResult {
room_id: string;
room_name: string;
attached_reference_ids: string[];
+ attached_package_ids: string[];
created_reference_ids: string[];
created_document_ids: string[];
role_names: string[];