Skip to content

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

Record the agents a run of a known template creates

Simon Flack00b1ef1eba69
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index 6130fe1db..cc97e6dbb 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -60,6 +60,7 @@ from switch_core.db.stores.template_store import TemplateStore
from switch_core.feature_flags import AGENT_MANAGEMENT, SWITCH_BUDDY
from switch_core.rooms_yaml import GroupSpec, template_json_schema
from switch_core.template_guide import TEMPLATE_GUIDE
+from switch_core.template_installs import InstallSource, record_install, source_of
from switch_core.template_runs import (
LISTEN_TIMEOUT_SECONDS,
AgentsNotCreated,
@@ -1599,7 +1600,9 @@ async def create_room_from_yaml(
"""
async with _refusals_reported("create_room_from_yaml"):
if is_v2_text(yaml):
- return await _run_document(yaml, inputs, {}, template_name=None)
+ return await _run_document(
+ yaml, inputs, {}, template_name=None, source=None
+ )
return await _provision_as_agent(
yaml, inputs, template_name=None, new_agents=[], room_addressing={}
)
@@ -1934,7 +1937,13 @@ async def run_template(
async with protocol.session_factory() as session:
template = await _agent_templates().load(session, acting, template_id)
content, name = template.content, template.name
- return await _run_document(content, inputs, agents or {}, template_name=name)
+ return await _run_document(
+ content,
+ inputs,
+ agents or {},
+ template_name=name,
+ source=source_of(template),
+ )
async def _run_document(
@@ -1943,9 +1952,11 @@ async def _run_document(
filled: dict[str, str],
*,
template_name: str | None,
+ source: InstallSource | None,
) -> dict[str, Any]:
"""Work a template's agents and rooms out of its document and create
- them, as the calling agent."""
+ them, as the calling agent. With a `source`, the agents it creates are
+ recorded as that template's install, to be updated from it."""
protocol = get_protocol()
acting = await _acting_for()
rooms_yaml = protocol.room_yaml_service()
@@ -1967,13 +1978,26 @@ async def _run_document(
builtins=builtins,
machines=await _owners_machines(),
)
- return await _provision_as_agent(
+ result = await _provision_as_agent(
plan.document,
plan.inputs or None,
template_name=template_name,
new_agents=plan.new_agents,
room_addressing=plan.room_addressing,
)
+ if source is not None:
+ await record_install(
+ protocol.session_factory,
+ require_tenant_id(),
+ owner_id=acting.owner.id,
+ source=source,
+ document=content,
+ inputs=inputs or {},
+ builtins=builtins,
+ plans=plan.new_agents,
+ created=result.get("created_agents") or [],
+ )
+ return result
async def _owners_machines() -> list[dict[str, Any]] | None:
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index 615091076..cdcd62dc4 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -19,17 +19,21 @@ from switch_core.bridges.collaboration.models import (
ChannelType,
RetireOutcome,
)
+from switch_core.config import SwitchConfig
from switch_core.db.models import Room, RoomGroup, User, require_tenant_id
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.room_group_store import RoomGroupStore
from switch_core.db.stores.room_store import RoomStore
+from switch_core.db.stores.template_store import TemplateStore
from switch_core.db.stores.user_store import UserStore
+from switch_core.feature_flags import AGENT_MANAGEMENT, SWITCH_BUDDY
from switch_core.gateway.auth import get_current_user, get_tenant_is_admin
from switch_core.gateway.dependencies import (
current_telemetry,
get_bridge_store,
get_collab_lifecycle,
+ get_config,
get_external_user_store,
get_protocol,
get_room_group_store,
@@ -37,6 +41,7 @@ from switch_core.gateway.dependencies import (
get_room_store,
get_room_yaml_service,
get_session,
+ get_template_store,
get_user_store,
)
from switch_core.gateway.schemas import (
@@ -59,6 +64,7 @@ from switch_core.gateway.schemas import (
RoomUpdateRequest,
RoomUsersRequest,
)
+from switch_core.gateway.templates import readable_template
from switch_core.room_service import RoleSpec, RoomCreateConfig, RoomService
from switch_core.rooms_yaml import (
GroupProvisionResult,
@@ -68,6 +74,7 @@ from switch_core.rooms_yaml import (
template_json_schema,
)
from switch_core.telemetry import emit_safely
+from switch_core.template_installs import record_install, vouched_source
from switch_core.template_runs import (
LISTEN_TIMEOUT_SECONDS,
AgentsNotCreated,
@@ -626,6 +633,11 @@ class TemplateDocumentRunBody(BaseModel):
# Existing agents standing in for slots that allow it: {slot: agent name}.
filled: dict[str, str] = Field(default_factory=dict)
template_name: str
+ # The template the document is, by id, when it is one. The run is
+ # recorded as that template's install only when the document is exactly
+ # the template's; a Switch Console that does not send it still has a run
+ # of an official template recognised by its document.
+ template_id: str | None = None
@router.post("/from-template-document", status_code=201, response_model=None)
@@ -633,6 +645,9 @@ async def run_template_document(
body: TemplateDocumentRunBody,
rooms_yaml: Annotated[RoomYamlService, Depends(get_room_yaml_service)],
protocol: Annotated[AgentCore, Depends(get_protocol)],
+ session: Annotated[AsyncSession, Depends(get_session)],
+ template_store: Annotated[TemplateStore, Depends(get_template_store)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> dict[str, Any] | JSONResponse:
@@ -641,7 +656,23 @@ async def run_template_document(
the caller's machines), checks everything, creates the agents, then the
rooms. For a ``version: 2`` document, whose conditions and references
only the server resolves. Answers as ``from-template``.
+
+ The agents a run of a known template creates are recorded as its
+ install (``template_installs``), so a later revision can update them.
"""
+ loaded = (
+ await readable_template(
+ body.template_id, session, template_store, user, is_admin, config
+ )
+ if body.template_id is not None
+ else None
+ )
+ source = vouched_source(
+ body.template,
+ loaded,
+ agent_management=config.feature_flags[AGENT_MANAGEMENT],
+ switch_buddy=config.feature_flags[SWITCH_BUDDY],
+ )
inputs = body.inputs or {}
try:
if is_v2_text(body.template):
@@ -666,7 +697,7 @@ async def run_template_document(
return _refused_run(error)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
- return await _run_as_person(
+ result = await _run_as_person(
rooms_yaml,
protocol,
user,
@@ -677,6 +708,19 @@ async def run_template_document(
template_name=body.template_name,
room_addressing=plan.room_addressing,
)
+ if source is not None and isinstance(result, dict):
+ await record_install(
+ protocol.session_factory,
+ require_tenant_id(),
+ owner_id=user.id,
+ source=source,
+ document=body.template,
+ inputs=inputs,
+ builtins=builtins,
+ plans=plan.new_agents,
+ created=result["created_agents"],
+ )
+ return result
async def _run_as_person(
diff --git a/core/switch_core/gateway/templates.py b/core/switch_core/gateway/templates.py
index d4cc767d8..220e55609 100644
--- a/core/switch_core/gateway/templates.py
+++ b/core/switch_core/gateway/templates.py
@@ -164,6 +164,21 @@ def _official_or_none(
return template
+async def readable_template(
+ template_id: str,
+ session: AsyncSession,
+ store: TemplateStore,
+ user: User,
+ is_admin: bool,
+ config: SwitchConfig,
+) -> Template | OfficialTemplate:
+ """A template the caller may read, official or saved; 404 otherwise."""
+ official = _official_or_none(template_id, config)
+ if official is not None:
+ return official
+ return await _load_for("read", session, store, template_id, user, is_admin)
+
+
def _refuse_official(template_id: str) -> None:
if is_official(template_id):
raise HTTPException(
diff --git a/core/switch_core/template_installs.py b/core/switch_core/template_installs.py
index 9dcbdd111..e97e6b2b3 100644
--- a/core/switch_core/template_installs.py
+++ b/core/switch_core/template_installs.py
@@ -16,13 +16,31 @@ from __future__ import annotations
import hashlib
import json
-from typing import Any
+import logging
+from collections.abc import Sequence
+from dataclasses import dataclass
+from typing import Any, Literal
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.agent_templates import plan_template
+from switch_core.db.models import Template
+from switch_core.db.session_scope import tenant_session
+from switch_core.db.stores.template_install_store import (
+ NewInstallResource,
+ TemplateInstallStore,
+)
+from switch_core.official_templates import (
+ OfficialTemplate,
+ is_official,
+ official_templates,
+)
from switch_core.providers.registry import provider_ids
from switch_core.template_runs import NewAgentPlan
from switch_core.template_v2 import compile_v2, is_v2_text
+logger = logging.getLogger(__name__)
+
AGENT_FIELDS: tuple[str, ...] = (
"instructions",
"description",
@@ -91,3 +109,102 @@ def render_agents(
plan = plan_template(text, {}, inputs, builtins=builtins, machines=machines)
keys = resource_keys(text, inputs, builtins)
return {key_of(agent, keys): agent_fields(agent) for agent in plan.new_agents}
+
+
+@dataclass(frozen=True)
+class InstallSource:
+ """Where a run's document came from, as the server knows it: never
+ taken from what a caller says, only from a template it loaded itself."""
+
+ source: Literal["official", "saved"]
+ template_id: str
+ template_name: str
+ revision: int
+
+
+def source_of(template: OfficialTemplate | Template) -> InstallSource:
+ return InstallSource(
+ source="official" if is_official(template.id) else "saved",
+ template_id=template.id,
+ template_name=template.name,
+ revision=template.version,
+ )
+
+
+def vouched_source(
+ document: str,
+ loaded: OfficialTemplate | Template | None,
+ *,
+ agent_management: bool,
+ switch_buddy: bool,
+) -> InstallSource | None:
+ """The source of a document a caller sent to run: the template it says
+ the document is (`loaded`, read by the server with the caller's own
+ access), when the document is exactly that template's; else an official
+ template whose document it is word for word, which is how a run from a
+ Switch Console too old to say is still recognised. None when it is
+ neither: a document the caller wrote or changed has no source to update
+ it from."""
+ if loaded is not None:
+ return source_of(loaded) if loaded.content == document else None
+ for official in official_templates(agent_management, switch_buddy):
+ if official.content == document:
+ return source_of(official)
+ return None
+
+
+async def record_install(
+ session_factory: async_sessionmaker[AsyncSession],
+ tenant_id: str,
+ *,
+ owner_id: str,
+ source: InstallSource,
+ document: str,
+ inputs: dict[str, Any],
+ builtins: dict[str, str],
+ plans: Sequence[NewAgentPlan],
+ created: Sequence[dict[str, Any]],
+) -> None:
+ """Record that a run of `source` created these agents, with what it set
+ on each. A run that created no agent records nothing.
+
+ The agents exist whatever happens here, so a failure to record is not
+ the run's failure: it is logged as an error, and those agents simply get
+ no updates.
+ """
+ agent_ids = {str(agent["name"]): str(agent["agent_id"]) for agent in created}
+ made = [plan for plan in plans if plan.name in agent_ids]
+ if not made:
+ return
+ try:
+ keys = resource_keys(document, inputs, builtins)
+ async with tenant_session(session_factory, tenant_id) as session:
+ await TemplateInstallStore().create(
+ session,
+ owner_id=owner_id,
+ source=source.source,
+ template_id=source.template_id,
+ template_name=source.template_name,
+ revision=source.revision,
+ inputs=inputs,
+ builtins=builtins,
+ resources=[
+ NewInstallResource(
+ key=key_of(plan, keys),
+ agent_id=agent_ids[plan.name],
+ room_id=None,
+ fingerprints=fingerprints(agent_fields(plan)),
+ )
+ for plan in made
+ ],
+ )
+ await session.commit()
+ except Exception:
+ logger.error(
+ "Could not record that %s (revision %s) created agents %s: they "
+ "will not be updated from it",
+ source.template_id,
+ source.revision,
+ sorted(agent_ids.values()),
+ exc_info=True,
+ )
diff --git a/core/tests/switch_core/bridges/agent/operations/test_template_managed_agents.py b/core/tests/switch_core/bridges/agent/operations/test_template_managed_agents.py
index 7f15d32f0..badd63776 100644
--- a/core/tests/switch_core/bridges/agent/operations/test_template_managed_agents.py
+++ b/core/tests/switch_core/bridges/agent/operations/test_template_managed_agents.py
@@ -36,6 +36,9 @@ from switch_core.bridges.agent.protocol.agent_management import (
NewManagedAgent,
)
from switch_core.db.models import Agent, Room, Template
+from switch_core.db.stores.template_install_store import TemplateInstallStore
+from switch_core.official_templates import current_revision
+from switch_core.template_installs import fingerprint
from switch_core.template_runs import AgentsNotCreated, RunUndone
from tests.switch_core.bridges.agent.operations.conftest import _make_agent
@@ -880,3 +883,51 @@ async def test_users_with_no_messaging_app_are_refused_before_any_agent(managed)
with pytest.raises(ValueError, match="on no messaging app"):
await _as(managed["agent_id"], run_template, template_id=template_id)
assert managed["management"].created == []
+
+
+async def _install_of(env: dict[str, Any], template_id: str) -> Any:
+ store = TemplateInstallStore()
+ async with env["session_factory"]() as session:
+ installs = await store.of_template(session, template_id)
+ return [(i, await store.resources(session, i.id)) for i in installs]
+
+
+async def test_switch_buddy_run_by_an_agent_is_recorded_as_its_install(managed):
+ result = await _as(
+ managed["agent_id"],
+ run_template,
+ template_id="official:switch-buddy",
+ inputs={"agent_name": "switch-buddy-max"},
+ )
+
+ ((install, (resource,)),) = await _install_of(managed, "official:switch-buddy")
+ assert (install.source, install.owner_id, install.revision) == (
+ "official",
+ managed["user_id"],
+ current_revision("switch-buddy"),
+ )
+ assert resource.key == "buddy"
+ assert resource.agent_id == result["created_agents"][0]["agent_id"]
+
+
+async def test_a_saved_template_run_by_an_agent_is_recorded_at_its_version(managed):
+ template_id = await _stored(
+ managed,
+ "agent:\n"
+ " name: helper\n"
+ " description: Helps.\n"
+ " instructions: Help.\n"
+ " provider: claude\n"
+ " machine: laptop\n"
+ " directory: /srv/helper\n",
+ kind="agent",
+ )
+
+ await _as(managed["agent_id"], run_template, template_id=template_id)
+
+ ((install, (resource,)),) = await _install_of(managed, template_id)
+ assert (install.source, install.revision) == ("saved", 1)
+ assert resource.key == "helper"
+ assert resource.fingerprints["instructions"] == fingerprint("Help.")
diff --git a/core/tests/switch_core/management/harness.py b/core/tests/switch_core/management/harness.py
index 595b86098..a3cf646bf 100644
--- a/core/tests/switch_core/management/harness.py
+++ b/core/tests/switch_core/management/harness.py
@@ -60,6 +60,7 @@ from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.db.stores.room_role_store import RoomRoleStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.switch_core_process_store import SwitchCoreProcessStore
+from switch_core.db.stores.template_store import TemplateStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway import dependencies as gw_deps
from switch_core.gateway.auth import create_jwt
@@ -291,10 +292,14 @@ def build_harness(
)
gateway_app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()
gateway_app.dependency_overrides[gw_deps.get_protocol] = lambda: protocol
+ gateway_app.dependency_overrides[gw_deps.get_template_store] = lambda: (
+ TemplateStore()
+ )
gateway_app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
keyring=TEST_KEYRING,
gateway_tenant_choice_enabled=False,
third_party_avatars_enabled=third_party_avatars,
+ feature_flags={"agent_management": True, "switch_buddy": True},
)
agent_app.mount("/gateway", gateway_app)
agent_app.add_middleware(
diff --git a/core/tests/switch_core/management/test_agent_operations.py b/core/tests/switch_core/management/test_agent_operations.py
index 0d067399f..6ba48c5d3 100644
--- a/core/tests/switch_core/management/test_agent_operations.py
+++ b/core/tests/switch_core/management/test_agent_operations.py
@@ -35,11 +35,18 @@ from switch_core.db.models import (
Client,
ServiceGrant,
Template,
+ TemplateInstall,
User,
)
+from switch_core.db.stores.template_install_store import TemplateInstallStore
from switch_core.gateway import dependencies as gw_deps
from switch_core.gateway import rooms as gateway_rooms
from switch_core.gateway.rooms import router as rooms_router
+from switch_core.official_templates import (
+ current_revision,
+ official_template,
+ revisions,
+)
from tests.switch_core.connections.github_seed import connect_github
from tests.switch_core.management.harness import (
TEST_KEYRING,
@@ -1532,3 +1539,159 @@ class TestTheConsoleRunsAVersion2Template:
body = response.json()
assert {p["code"] for p in body["problems"]} == {"machine_unresolved"}
assert "claude is not signed in on laptop" in body["detail"]
+
+
+async def _installs(harness: Harness, template_id: str) -> list[Any]:
+ async with harness.session_factory() as session:
+ installs = await TemplateInstallStore().of_template(session, template_id)
+ return [
+ (install, await TemplateInstallStore().resources(session, install.id))
+ for install in installs
+ ]
+
+
+def _buddy_document() -> str:
+ buddy = official_template("official:switch-buddy", True, switch_buddy=True)
+ assert buddy is not None
+ return buddy.content
+
+
[email protected]("_short_listen")
+class TestARunOfAKnownTemplateIsRecorded:
+ """`POST /gateway/rooms/from-template-document` records the agents a run
+ of a template it can vouch for created, to be updated from it later:
+ the template the request names when the document is exactly that one,
+ or an official template whose document it is word for word."""
+
+ @pytest.fixture(autouse=True)
+ def _rooms(self, harness: Harness) -> None:
+ harness.gateway_app.include_router(rooms_router, prefix="/rooms")
+ harness.gateway_app.dependency_overrides[gw_deps.get_room_yaml_service] = (
+ lambda: _NoRooms()
+ )
+
+ async def _run(
+ self,
+ harness: Harness,
+ client: httpx.AsyncClient,
+ owner: User,
+ document: str,
+ **extra: Any,
+ ) -> httpx.Response:
+ controller = await enroll_console(harness, client, owner, name="laptop")
+ await _online(client, controller)
+ return await client.post(
+ "/gateway/rooms/from-template-document",
+ json={"template": document, "template_name": "t", **extra},
+ cookies=cookies_for(owner),
+ )
+
+ async def test_switch_buddy_is_recorded_from_its_document_alone(
+ self, harness: Harness, client: httpx.AsyncClient
+ ) -> None:
+ owner = await add_member(harness.session_factory, "ada")
+
+ response = await self._run(
+ harness,
+ client,
+ owner,
+ _buddy_document(),
+ inputs={"agent_name": "switch-buddy-ada", "provider": "claude"},
+ )
+
+ assert response.status_code == 201, response.text
+ ((install, resources),) = await _installs(harness, "official:switch-buddy")
+ (created,) = response.json()["created_agents"]
+ assert (install.source, install.owner_id, install.revision) == (
+ "official",
+ owner.id,
+ current_revision("switch-buddy"),
+ )
+ assert install.inputs["agent_name"] == "switch-buddy-ada"
+ (resource,) = resources
+ assert (resource.key, resource.agent_id) == ("buddy", created["agent_id"])
+ assert (
+ resource.fingerprints
+ == revisions.recorded("switch-buddy")[-1]["agents"]["buddy"]
+ )
+
+ async def test_a_saved_template_named_by_id_is_recorded_at_its_version(
+ self, harness: Harness, client: httpx.AsyncClient
+ ) -> None:
+ owner = await add_member(harness.session_factory, "ada")
+ async with harness.session_factory() as session:
+ template = Template(
+ owner_id=owner.id,
+ name="helper",
+ description="d",
+ kind="agent",
+ content=DOCUMENT_TEMPLATE,
+ version=3,
+ )
+ session.add(template)
+ await session.commit()
+
+ response = await self._run(
+ harness, client, owner, DOCUMENT_TEMPLATE, template_id=template.id
+ )
+
+ assert response.status_code == 201, response.text
+ ((install, resources),) = await _installs(harness, template.id)
+ assert (install.source, install.template_name, install.revision) == (
+ "saved",
+ "helper",
+ 3,
+ )
+ assert [r.key for r in resources] == ["helper"]
+
+ async def test_a_document_changed_from_the_template_it_names_is_not_recorded(
+ self, harness: Harness, client: httpx.AsyncClient
+ ) -> None:
+ owner = await add_member(harness.session_factory, "ada")
+
+ response = await self._run(
+ harness,
+ client,
+ owner,
+ _buddy_document().replace("Your assistant", "My assistant"),
+ inputs={"agent_name": "switch-buddy-ada", "provider": "claude"},
+ template_id="official:switch-buddy",
+ )
+
+ assert response.status_code == 201, response.text
+ assert await _installs(harness, "official:switch-buddy") == []
+
+ async def test_a_document_of_no_known_template_is_not_recorded(
+ self, harness: Harness, client: httpx.AsyncClient
+ ) -> None:
+ owner = await add_member(harness.session_factory, "ada")
+
+ response = await self._run(harness, client, owner, DOCUMENT_TEMPLATE)
+
+ assert response.status_code == 201, response.text
+ async with harness.session_factory() as session:
+ assert (await session.execute(select(TemplateInstall))).first() is None
+
+ async def test_a_template_the_caller_cannot_read_is_not_found(
+ self, harness: Harness, client: httpx.AsyncClient
+ ) -> None:
+ owner = await add_member(harness.session_factory, "ada")
+ other = await add_member(harness.session_factory, "bob")
+ async with harness.session_factory() as session:
+ template = Template(
+ owner_id=other.id,
+ name="private",
+ description="d",
+ kind="agent",
+ content=DOCUMENT_TEMPLATE,
+ read_visibility="private",
+ )
+ session.add(template)
+ await session.commit()
+
+ response = await self._run(
+ harness, client, owner, DOCUMENT_TEMPLATE, template_id=template.id
+ )
+
+ assert response.status_code == 404, response.text
+ assert await _agent_row(harness, "helper") is None
diff --git a/core/tests/switch_core/test_template_installs.py b/core/tests/switch_core/test_template_installs.py
new file mode 100644
index 000000000..884173b66
--- /dev/null
+++ b/core/tests/switch_core/test_template_installs.py
@@ -0,0 +1,122 @@
+"""What a template sets on its agents, and where a run's document came from."""
+
+from __future__ import annotations
+
+import logging
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from switch_core.db.models import Template
+from switch_core.official_templates import official_template
+from switch_core.template_installs import (
+ InstallSource,
+ fingerprint,
+ record_install,
+ render_agents,
+ vouched_source,
+)
+
+
+def _buddy() -> Any:
+ buddy = official_template("official:switch-buddy", True, switch_buddy=True)
+ assert buddy is not None
+ return buddy
+
+
+def test_equal_values_have_equal_fingerprints_and_none_is_a_value():
+ assert fingerprint("a") == fingerprint("a")
+ assert fingerprint("a") != fingerprint("b")
+ assert fingerprint(None) != fingerprint("") != fingerprint("null")
+
+
+def test_an_official_document_is_recognised_word_for_word():
+ source = vouched_source(
+ _buddy().content, None, agent_management=True, switch_buddy=True
+ )
+ assert source == InstallSource(
+ "official", "official:switch-buddy", "switch-buddy", _buddy().version
+ )
+
+
+def test_an_official_document_is_not_recognised_where_it_is_not_served():
+ assert (
+ vouched_source(
+ _buddy().content, None, agent_management=True, switch_buddy=False
+ )
+ is None
+ )
+
+
+def test_a_changed_document_has_no_source_even_naming_its_template():
+ changed = _buddy().content + "\n# mine\n"
+ assert (
+ vouched_source(changed, None, agent_management=True, switch_buddy=True) is None
+ )
+ assert (
+ vouched_source(changed, _buddy(), agent_management=True, switch_buddy=True)
+ is None
+ )
+
+
+def test_a_saved_template_is_the_source_of_its_own_document():
+ saved = Template(
+ id="t-1", owner_id="u", name="helper", description="", kind="agent"
+ )
+ saved.content = "agent: {}\n"
+ saved.version = 4
+ assert vouched_source(
+ "agent: {}\n", saved, agent_management=True, switch_buddy=True
+ ) == InstallSource("saved", "t-1", "helper", 4)
+
+
+def test_agents_are_rendered_by_their_template_key():
+ rendered = render_agents(_buddy().content, {"agent_name": "switch-buddy-a"}, {})
+ assert list(rendered) == ["buddy"]
+ assert rendered["buddy"]["icon_url"] is not None
+ assert rendered["buddy"]["instructions"]
+
+
+async def test_a_failure_to_record_is_logged_and_the_run_stands(caplog):
+ def broken() -> Any:
+ raise RuntimeError("database gone")
+
+ plan = SimpleNamespace(
+ name="switch-buddy-a",
+ instructions="i",
+ description="d",
+ icon_url=None,
+ display_name=None,
+ )
+ with caplog.at_level(logging.ERROR):
+ await record_install(
+ broken, # type: ignore[arg-type]
+ "tenant",
+ owner_id="u",
+ source=InstallSource("official", "official:switch-buddy", "b", 1),
+ document="agent: {}\n",
+ inputs={},
+ builtins={},
+ plans=[plan], # type: ignore[list-item]
+ created=[{"name": "switch-buddy-a", "agent_id": "a-1"}],
+ )
+ assert "will not be updated" in caplog.text
+
+
[email protected]("created", [[], [{"name": "someone", "agent_id": "x"}]])
+async def test_a_run_that_created_none_of_its_agents_records_nothing(created):
+ def untouched() -> Any:
+ raise AssertionError("nothing should be written")
+
+ await record_install(
+ untouched, # type: ignore[arg-type]
+ "tenant",
+ owner_id="u",
+ source=InstallSource("official", "official:switch-buddy", "b", 1),
+ document="agent: {}\n",
+ inputs={},
+ builtins={},
+ plans=[SimpleNamespace(name="switch-buddy-a")], # type: ignore[list-item]
+ created=created,
+ )