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
Tell an agent when it was not brought fully up to its template
Simon Flack836aa6b7d769
diff --git a/console/packages/agent-providers/src/host/room-prompt.test.ts b/console/packages/agent-providers/src/host/room-prompt.test.tsindex 1d34d6886..f383b5db2 100644--- a/console/packages/agent-providers/src/host/room-prompt.test.ts+++ b/console/packages/agent-providers/src/host/room-prompt.test.ts@@ -46,6 +46,21 @@ describe('a room command', () => {expect(text(opened, false)).not.toContain('Hi, I am your buddy.');});+ it('tells what Switch has to say before the message, outside its markers, on every message', () => {+ const noticed = {+ ...event,+ payload: { ...event.payload, switch_notice: 'Your template has a new revision.' },+ };+ for (const first of [true, false]) {+ const said = text(noticed, first);+ expect(said).toContain('[Switch] Your template has a new revision.');+ expect(said.indexOf('Your template has a new revision.')).toBeLessThan(+ said.indexOf('BEGIN SWITCH MESSAGE')+ );+ }+ expect(text(event)).not.toContain('new revision');+ });+it("says the sender's role in the workspace, as the server read it", () => {const fromMember = { ...event, payload: { ...event.payload, sender_role: 'member' } };expect(text(fromMember)).toContain('[Switch] Owner (workspace member) addressed you');diff --git a/console/packages/agent-providers/src/host/room-prompt.ts b/console/packages/agent-providers/src/host/room-prompt.tsindex 5cccc5c7c..dbc3ea40d 100644--- a/console/packages/agent-providers/src/host/room-prompt.ts+++ b/console/packages/agent-providers/src/host/room-prompt.ts@@ -33,6 +33,8 @@ export const roomMessageSchema = z.object({.default([]),opening_message: z.string().nullish(),sender_role: z.enum(['owner', 'admin', 'member']).nullish(),+ /** What Switch tells the agent before this message, until it reads about it; absent for nothing. */+ switch_notice: z.string().nullish(),}),missed: z.object({ count: z.number().int().nonnegative().nullable(), reason: z.string().nullable() })@@ -186,8 +188,11 @@ export function roomCommand(input: {// Read by the server as the message arrived, so it outranks anything said earlier.const senderRole = payload.sender_role ? ` (workspace ${payload.sender_role})` : '';const opening = input.firstOfConversation ? (payload.opening_message ?? null) : null;+ // Written by the server, never by a room participant, so it sits outside the message's markers.+ const notice = payload.switch_notice ? `[Switch] ${payload.switch_notice}\n\n` : '';const text =(input.preface === null ? '' : `${input.preface}\n\n`) ++ notice +(opening === null ? '' : `${openingNote(opening)}\n\n`) +`[Switch] ${senderName}${senderRole} addressed you in room ${input.roomId} (message_id ${payload.message_id}, thread_id ${payload.thread_id ?? 'none'}):\n` +`BEGIN SWITCH MESSAGE ${marker}\n` +diff --git a/console/packages/agent-providers/src/host/shared-host.test.ts b/console/packages/agent-providers/src/host/shared-host.test.tsindex 4763c1f1b..9c38a9eb7 100644--- a/console/packages/agent-providers/src/host/shared-host.test.ts+++ b/console/packages/agent-providers/src/host/shared-host.test.ts@@ -488,7 +488,7 @@ it('tells a running conversation once that its instructions changed, across restconst edited = await restart(first, 'Speak plainly.');expect(await answer(edited, 2, 'and now?')).toMatch(- /^\[Switch\] Your agent instructions were changed by your owner\.[\s\S]*BEGIN AGENT INSTRUCTIONS\nSpeak plainly\.\nEND AGENT INSTRUCTIONS\n\n\[Switch\] A Person addressed you/+ /^\[Switch\] Your agent instructions were changed, by your owner or by Switch[\s\S]*BEGIN AGENT INSTRUCTIONS\nSpeak plainly\.\nEND AGENT INSTRUCTIONS\n\n\[Switch\] A Person addressed you/);expect(await answer(edited, 3, 'again')).not.toContain('instructions were changed');diff --git a/console/packages/agent-providers/src/host/told-instructions.ts b/console/packages/agent-providers/src/host/told-instructions.tsindex e23f5d3a5..41cb4e2f6 100644--- a/console/packages/agent-providers/src/host/told-instructions.ts+++ b/console/packages/agent-providers/src/host/told-instructions.ts@@ -31,9 +31,9 @@ export async function recordToldInstructions(root: string, instructions: string)/** What a running conversation is told when its agent's instructions change. */export function instructionsChangedNote(instructions: string): string {if (instructions.trim() === '')- return '[Switch] Your agent instructions were removed by your owner. From now on, follow no agent-specific instructions; the ones you were given earlier no longer apply.';+ return '[Switch] Your agent instructions were removed. From now on, follow no agent-specific instructions; the ones you were given earlier no longer apply.';return (- '[Switch] Your agent instructions were changed by your owner. From now on, follow these instead of the ones you were given earlier:\n' ++ '[Switch] Your agent instructions were changed, by your owner or by Switch bringing you up to a new revision of your template. From now on, follow these instead of the ones you were given earlier:\n' +'BEGIN AGENT INSTRUCTIONS\n' +`${instructions}\n` +'END AGENT INSTRUCTIONS'diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex 548532ce7..5a9ac2480 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -897,6 +897,22 @@ ui-avatars.com is not accepted.repositories, refuses with what is missing. Link the agent's Connections tabfor it instead.+## Your template's new revisions++An agent created from an official template, such as switch-buddy, is brought+up to each new revision of it when the server starts: whatever nobody had+changed follows the template. What somebody changed, and any permission the+template would set differently, is left as it is. When that happens a+`[Switch]` notice before your next message says so.++- **`get_template_status`** — how you differ from your template's current+ revision: each value that differs (yours and the recommended one), and each+ permission it sets differently. Call it when the notice asks. Then tell your+ owner, in a few lines, what they would gain and what they would lose by+ taking the template's version, and let them decide: they make any change+ themselves on your page in Switch Console, since you cannot change your own+ settings. Offer long text as a file rather than pasting it.+## Room roles (assumable)A room can define **room-scoped roles** — named, assumable instruction bundles@@ -1093,6 +1109,7 @@ Every Switch tool you call in normal operation, one line each.- `create_agent` — create an agent for your owner on one of their machines. Confirm with the user first.- `list_managed_agents` — your owner's managed agents and whether each is up.- `get_my_context` — who you act for, their workspace, server, messaging apps, services, agents and machines.+- `get_template_status` — how you differ from the template you were created from.- `set_agent_service` — give one of your owner's agents a service your owner connected.- `remove_agent_service` — take an agent's access to a service away.- `list_reference_types` — the Reference types and their value schemas.diff --git a/core/switch_core/bridges/agent/operations/__init__.py b/core/switch_core/bridges/agent/operations/__init__.pyindex 9d2b667f6..2fe075b4f 100644--- a/core/switch_core/bridges/agent/operations/__init__.py+++ b/core/switch_core/bridges/agent/operations/__init__.py@@ -15,6 +15,9 @@ from switch_core.bridges.agent.operations import (from switch_core.bridges.agent.operations import (my_context as _my_context, # noqa: E402,F401)+from switch_core.bridges.agent.operations import (+ template_status as _template_status, # noqa: E402,F401+)from switch_core.bridges.agent.operations.registry import (Operation,all_operations,diff --git a/core/switch_core/bridges/agent/operations/template_status.py b/core/switch_core/bridges/agent/operations/template_status.pynew file mode 100644index 000000000..fb6aa1884--- /dev/null+++ b/core/switch_core/bridges/agent/operations/template_status.py@@ -0,0 +1,125 @@+"""`get_template_status`: how an agent differs from the template it was+created from.++When a new revision of an official template reaches the server, the values+nobody changed on the agents it created follow it (see+``management/template_updates.py``). What somebody changed, and the+permissions the template would set differently, stay as they are; the agent+is left a notice to ask here, and to tell its owner what they would gain and+lose by taking the template's version. Reading clears the notice.+"""++from __future__ import annotations++from dataclasses import asdict+from typing import Any++from sqlalchemy import select++from switch_core.bridges.agent.operations.context import get_agent_id, get_protocol+from switch_core.bridges.agent.operations.registry import operation+from switch_core.db.models import Agent, AgentDefinition, require_tenant_id+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.template_install_store import TemplateInstallStore+from switch_core.feature_flags import AGENT_MANAGEMENT, SWITCH_BUDDY+from switch_core.official_templates import official_template+from switch_core.template_installs import (+ AGENT_FIELDS,+ Differs,+ agent_fields,+ agent_values,+ held_permissions,+ render_plans,+)++_STORE = TemplateInstallStore()+++@operation+async def get_template_status() -> dict[str, Any]:+ """How you differ from the template you were created from, such as+ switch-buddy's.++ Call it when Switch tells you your template has a new revision. Switch+ already brought up to it everything nobody had changed; what is listed+ here is what it left alone. Tell your owner, in a few lines, what they+ would gain and what they would lose by taking the template's version of+ each, and let them decide: they make any change themselves, on your page+ in Switch Console (you cannot change your own settings). Offer the full+ text when it is long rather than pasting it into the chat.++ Returns:+ {template, installed_revision, current_revision, differs,+ permissions}. `template` is {id, name, source}, or null when you were+ not created from a template Switch can update you from (the other+ fields are then absent).+ `differs` lists each of your values that differs from what the+ template's current revision sets, {field, yours, recommended}:+ `field` is "instructions", "description", "icon_url" or+ "display_name". `permissions` lists each permission the template+ sets differently, {setting, yours, recommended}: `setting` is+ "can_manage_agents" or "addressing"; Switch never changes these for+ you. Both are empty when you match the template.+ """+ protocol = get_protocol()+ agent_id = get_agent_id()+ async with tenant_session(protocol.session_factory, require_tenant_id()) as session:+ found = await _STORE.for_agent(session, agent_id)+ if found is None:+ return {"template": None}+ install, resource = found+ template = {+ "id": install.template_id,+ "name": install.template_name,+ "source": install.source,+ }+ official = official_template(+ install.template_id,+ protocol.config.feature_flags[AGENT_MANAGEMENT],+ protocol.config.feature_flags[SWITCH_BUDDY],+ )+ agent = await session.get(Agent, agent_id)+ row = (+ await session.execute(+ select(AgentDefinition).where(+ AgentDefinition.tenant_id == require_tenant_id(),+ AgentDefinition.agent_id == agent_id,+ )+ )+ ).scalar_one_or_none()+ await _STORE.set_notice(session, resource.id, None)+ await session.commit()+ if official is None or agent is None:+ # A saved template, or one this server no longer serves: nothing to+ # compare against.+ return {+ "template": template,+ "installed_revision": install.revision,+ "current_revision": None,+ "differs": [],+ "permissions": [],+ }+ plan = render_plans(official.content, install.inputs, install.builtins).get(+ resource.key+ )+ if plan is None:+ return {+ "template": template,+ "installed_revision": install.revision,+ "current_revision": official.version,+ "differs": [],+ "permissions": [],+ }+ yours = agent_values(agent, row)+ recommended = agent_fields(plan)+ return {+ "template": template,+ "installed_revision": install.revision,+ "current_revision": official.version,+ "differs": [+ asdict(Differs(name, yours[name], recommended[name]))+ for name in AGENT_FIELDS+ if name in yours and yours[name] != recommended[name]+ ],+ "permissions": [asdict(held) for held in held_permissions(plan, agent)],+ }diff --git a/core/switch_core/bridges/agent/protocol/message_events.py b/core/switch_core/bridges/agent/protocol/message_events.pyindex cf664af37..1c07d6862 100644--- a/core/switch_core/bridges/agent/protocol/message_events.py+++ b/core/switch_core/bridges/agent/protocol/message_events.py@@ -51,6 +51,7 @@ def message_event(attachments: list[AttachmentRef] | None = None,opening_message: str | None = None,sender_role: str | None = None,+ switch_notice: str | None = None,) -> AgentEvent:"""Build the `message` event the agent receives, with any attached files.@@ -85,6 +86,7 @@ def message_event(attachments=attachments or [],opening_message=opening_message,sender_role=sender_role,+ switch_notice=switch_notice,),)diff --git a/core/switch_core/bridges/agent/protocol/types.py b/core/switch_core/bridges/agent/protocol/types.pyindex 8bf665169..277b5f654 100644--- a/core/switch_core/bridges/agent/protocol/types.py+++ b/core/switch_core/bridges/agent/protocol/types.py@@ -239,6 +239,10 @@ class MessagePayload(BaseModel):# arrived: "owner", "admin" or "member". None for an agent, the platform,# or a person no Switch user has claimed.sender_role: str | None = None+ # What Switch has to tell the agent before this message, such as that+ # its template has a new revision it was not brought fully up to; told+ # with every message until the agent reads about it. None for nothing.+ switch_notice: str | None = Noneclass CommandPayload(BaseModel):diff --git a/core/switch_core/db/stores/template_install_store.py b/core/switch_core/db/stores/template_install_store.pyindex 78ba994d7..167acca20 100644--- a/core/switch_core/db/stores/template_install_store.py+++ b/core/switch_core/db/stores/template_install_store.py@@ -169,15 +169,24 @@ class TemplateInstallStore:.values(notice=notice))- async def notice_for_agent(- self, session: AsyncSession, agent_id: str- ) -> str | None:- """What Switch has to tell an agent about its template, if anything."""- return (- await session.execute(- select(TemplateInstallResource.notice).where(- TemplateInstallResource.tenant_id == require_tenant_id(),- TemplateInstallResource.agent_id == agent_id,- )+ async def notices_for_agents(+ self, session: AsyncSession, agent_ids: list[str]+ ) -> dict[str, str]:+ """What Switch has to tell each of these agents about its template,+ for those it has something to tell."""+ if not agent_ids:+ return {}+ rows = await session.execute(+ select(+ TemplateInstallResource.agent_id, TemplateInstallResource.notice+ ).where(+ TemplateInstallResource.tenant_id == require_tenant_id(),+ TemplateInstallResource.agent_id.in_(agent_ids),+ TemplateInstallResource.notice.is_not(None),)- ).scalar_one_or_none()+ )+ return {+ agent_id: notice+ for agent_id, notice in rows.tuples()+ if agent_id is not None and notice is not None+ }diff --git a/core/switch_core/delivery/recipient.py b/core/switch_core/delivery/recipient.pyindex 230486e4e..1d29c8b7d 100644--- a/core/switch_core/delivery/recipient.py+++ b/core/switch_core/delivery/recipient.py@@ -191,6 +191,15 @@ class RecipientServices:message_telemetry: MessageTelemetry+class SwitchNotices(Protocol):+ """What Switch has to tell each agent of a room before its next message,+ read once for every agent in the room."""++ async def switch_notice(+ self, session: AsyncSession, agent_id: str+ ) -> str | None: ...++class ClientNames(Protocol):"""Who a member of a room is, by the id they post under: the one read anarrival's own event needs, which the router makes once for every agent in@@ -481,6 +490,7 @@ class AgentRecipient:addressing: AddressingResolver,budget_guard: BudgetGuard,clients: ClientNames,+ notices: SwitchNotices,cloud_waking_notices: set[tuple[str, int]],) -> None:self.actor = actor@@ -510,6 +520,7 @@ class AgentRecipient:self._addressing = addressingself._budget_guard = budget_guardself._clients = clients+ self._notices = notices# The "machine is waking" notices this process has posted for the# agent, by room and machine start, so the messages that follow the# first one wait with it instead of each saying so again.@@ -592,8 +603,9 @@ class AgentRecipient:if addressedelse None)+ notice = await self._switch_notice(session) if addressed else Noneown_event = _message_own_event(- meta, event, thread_id, self.agent.id, sender_role+ meta, event, thread_id, self.agent.id, sender_role, notice)async def after(row: InboundEvent) -> None:@@ -662,9 +674,10 @@ class AgentRecipient:await self._after_follow_up(row)sender_role = await self._sender_role(session, event.sender, event.content)+ notice = await self._switch_notice(session)return Delivery(own_event=_message_own_event(- meta, event, event.thread_root_id, self.agent.id, sender_role+ meta, event, event.thread_root_id, self.agent.id, sender_role, notice),after=after,)@@ -825,6 +838,7 @@ class AgentRecipient:if gate.addressedelse None)+ switch_notice = await self._switch_notice(session) if gate.addressed else Nonedef own_event(row: InboundEvent) -> OwnEvent:parts = written(row)@@ -851,6 +865,7 @@ class AgentRecipient:],opening_message=opening,sender_role=sender_role,+ switch_notice=switch_notice,)if logger.isEnabledFor(logging.DEBUG):logger.debug(@@ -1709,6 +1724,13 @@ class AgentRecipient:message=IncomingMessage(sender="", body=text),)+ async def _switch_notice(self, session: AsyncSession) -> str | None:+ """What Switch has to tell the agent before its next message: that+ its template has a revision it was not brought fully up to+ (`management/template_updates.py`). Told with every message until the+ agent reads how it differs (`get_template_status`)."""+ return await self._notices.switch_notice(session, self.agent.id)+async def _sender_role(self, session: AsyncSession, sender: str, content: Mapping[str, object]) -> str | None:@@ -1782,6 +1804,7 @@ def _message_own_event(thread_id: str | None,agent_id: str,sender_role: str | None,+ switch_notice: str | None,) -> Callable[[InboundEvent], OwnEvent]:"""How an agent's own event for a message is built once the message iswritten."""@@ -1806,6 +1829,7 @@ def _message_own_event(thread_id=thread_id,opening_message=opening_message_for(meta, agent_id),sender_role=sender_role,+ switch_notice=switch_notice,)# Serialising runs once per agent per message, so only when it will# be seen.diff --git a/core/switch_core/delivery/router.py b/core/switch_core/delivery/router.pyindex 326fa2d0c..72109c137 100644--- a/core/switch_core/delivery/router.py+++ b/core/switch_core/delivery/router.py@@ -90,6 +90,7 @@ from switch_core.db.models import ()from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.room_store import follow_ups_enabled_in, main_agent_in+from switch_core.db.stores.template_install_store import TemplateInstallStorefrom switch_core.delivery.addressing import AddressingResolver, SenderPrincipalfrom switch_core.delivery.conversation import (ConversationMessage,@@ -150,6 +151,9 @@ GROUP_SWEEP_SECONDS = 5.0_COMMAND_EVENT = "com.switch.command"+_INSTALLS = TemplateInstallStore()++class RoomReads:"""What deciding one row reads about its room, read once and shared byevery agent the row is decided for.@@ -190,6 +194,7 @@ class RoomReads:self._claims: dict[str, list[str]] = {}self._standings: list[BudgetStanding] | None = Noneself._clients: dict[str, Client | None] = {}+ self._notices: dict[str, str] | None = Noneself.addressing = _RoomAddressing(self, services=services, client_store=client_store)@@ -375,6 +380,15 @@ class RoomReads:)return self._standings+ async def switch_notice(self, session: AsyncSession, agent_id: str) -> str | None:+ """What Switch has to tell an agent before its next message (see+ `TemplateInstallResource.notice`), read for every agent member at once."""+ if self._notices is None:+ self._notices = await _INSTALLS.notices_for_agents(+ session, [member.agent.id for member in self.members]+ )+ return self._notices.get(agent_id)+async def get_by_transport_user_id(self, session: AsyncSession, transport_user_id: str) -> Client | None:@@ -1259,6 +1273,7 @@ class MessageRouter:addressing=reads.addressing,budget_guard=reads.budget_guard,clients=reads,+ notices=reads,cloud_waking_notices=self._cloud_waking.setdefault(member.agent.id, set()),)diff --git a/core/switch_core/management/template_updates.py b/core/switch_core/management/template_updates.pyindex e615c0c0a..36be6af04 100644--- a/core/switch_core/management/template_updates.py+++ b/core/switch_core/management/template_updates.py@@ -29,14 +29,12 @@ from __future__ import annotationsimport loggingimport refrom collections.abc import Sequence-from dataclasses import dataclass-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKINGfrom sqlalchemy import select, updatefrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.agent_detail import addressing_policy_forfrom switch_core.db.models import (Agent,AgentDefinition,@@ -60,10 +58,14 @@ from switch_core.official_templates import ()from switch_core.template_installs import (AGENT_FIELDS,+ Held,+ agent_fields,+ agent_values,fingerprint,+ held_permissions,render_plans,)-from switch_core.template_runs import TEMPLATE_ADDRESSING, NewAgentPlan+from switch_core.template_runs import NewAgentPlanif TYPE_CHECKING:from switch_core.bridges.agent.protocol.agent_core import AgentCore@@ -76,72 +78,10 @@ BUDDY_KEY = "buddy"_BUDDY_NAME = re.compile(r"^switch-buddy(-[a-z0-9._-]+)?$")-@dataclass(frozen=True)-class Held:- """A permission the template's current revision sets differently from- the agent's own, which no update changes."""-- setting: str- yours: Any- recommended: Any---@dataclass(frozen=True)-class Differs:- """A value somebody changed from what the template set, with what the- template's current revision would set instead."""-- field: str- yours: str | None- recommended: str | None--class LostRace(Exception):"""Something changed the agent between it being read and written."""-def agent_values(agent: Agent, row: AgentDefinition | None) -> dict[str, str | None]:- """An agent's own values of the fields a template sets; no- ``instructions`` for an agent with no managed definition."""- values: dict[str, str | None] = {- "description": agent.description,- "icon_url": agent.icon_url,- "display_name": agent.display_name,- }- if row is not None:- values["instructions"] = str(row.definition.get("instructions") or "")- return values---def plan_values(plan: NewAgentPlan) -> dict[str, str | None]:- return {- "instructions": plan.instructions,- "description": plan.description,- "icon_url": plan.icon_url,- "display_name": plan.display_name,- }---def held_permissions(plan: NewAgentPlan, agent: Agent) -> list[Held]:- """The permissions `plan` sets that differ from the agent's own."""- held: list[Held] = []- if plan.can_manage_agents != agent.can_manage_agents:- held.append(- Held("can_manage_agents", agent.can_manage_agents, plan.can_manage_agents)- )- choice = TEMPLATE_ADDRESSING.get(plan.addressing)- if choice is not None and addressing_policy_for(choice) != agent.addressing_policy:- held.append(Held("addressing", _addressing_word(agent), choice))- return held---def _addressing_word(agent: Agent) -> str:- for choice in TEMPLATE_ADDRESSING.values():- if addressing_policy_for(choice) == agent.addressing_policy:- return choice- return "custom"--def notice_text(template: OfficialTemplate,updated: Sequence[str],@@ -394,7 +334,7 @@ class TemplateUpdates:if agent is None:returncurrent = agent_values(agent, row)- new = plan_values(plan)+ new = agent_fields(plan)changes: dict[str, str | None] = {}differs: list[str] = []fingerprints = dict(resource.fingerprints)diff --git a/core/switch_core/template_installs.py b/core/switch_core/template_installs.pyindex d8df44146..632b7c22d 100644--- a/core/switch_core/template_installs.py+++ b/core/switch_core/template_installs.py@@ -24,7 +24,8 @@ from typing import Any, Literalfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.agent_templates import plan_template-from switch_core.db.models import Template+from switch_core.bridges.agent.protocol.agent_detail import addressing_policy_for+from switch_core.db.models import Agent, AgentDefinition, Templatefrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.template_install_store import (NewInstallResource,@@ -36,7 +37,7 @@ from switch_core.official_templates import (official_templates,)from switch_core.providers.registry import provider_ids-from switch_core.template_runs import NewAgentPlan+from switch_core.template_runs import TEMPLATE_ADDRESSING, NewAgentPlanfrom switch_core.template_v2 import compile_v2, is_v2_textlogger = logging.getLogger(__name__)@@ -219,3 +220,56 @@ async def record_install(sorted(agent_ids.values()),exc_info=True,)+++@dataclass(frozen=True)+class Held:+ """A permission the template's current revision sets differently from+ the agent's own, which no update changes."""++ setting: str+ yours: Any+ recommended: Any+++@dataclass(frozen=True)+class Differs:+ """A value somebody changed from what the template set, with what the+ template's current revision would set instead."""++ field: str+ yours: str | None+ recommended: str | None+++def agent_values(agent: Agent, row: AgentDefinition | None) -> dict[str, str | None]:+ """An agent's own values of the fields a template sets; no+ ``instructions`` for an agent with no managed definition."""+ values: dict[str, str | None] = {+ "description": agent.description,+ "icon_url": agent.icon_url,+ "display_name": agent.display_name,+ }+ if row is not None:+ values["instructions"] = str(row.definition.get("instructions") or "")+ return values+++def held_permissions(plan: NewAgentPlan, agent: Agent) -> list[Held]:+ """The permissions `plan` sets that differ from the agent's own."""+ held: list[Held] = []+ if plan.can_manage_agents != agent.can_manage_agents:+ held.append(+ Held("can_manage_agents", agent.can_manage_agents, plan.can_manage_agents)+ )+ choice = TEMPLATE_ADDRESSING.get(plan.addressing)+ if choice is not None and addressing_policy_for(choice) != agent.addressing_policy:+ held.append(Held("addressing", _addressing_word(agent), choice))+ return held+++def _addressing_word(agent: Agent) -> str:+ for choice in TEMPLATE_ADDRESSING.values():+ if addressing_policy_for(choice) == agent.addressing_policy:+ return choice+ return "custom"diff --git a/core/tests/switch_core/bridges/agent/protocol/test_controller_presence.py b/core/tests/switch_core/bridges/agent/protocol/test_controller_presence.pyindex d79f14bd5..cf303efd2 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_controller_presence.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_controller_presence.py@@ -629,6 +629,11 @@ def _addressing_client(return Nonens._sender_role = _sender_role++ async def _no_notice(*_args: Any) -> None:+ return None++ ns._switch_notice = _no_noticens._report_addressed = lambda *_a, **_k: Nonens._triggered_by_auto_reply = AgentRecipient._triggered_by_auto_replyns.actor = SimpleNamespace(send_message=sent)diff --git a/core/tests/switch_core/delivery/test_no_session_reply_threading.py b/core/tests/switch_core/delivery/test_no_session_reply_threading.pyindex 64dbf40f9..c05b9f9f1 100644--- a/core/tests/switch_core/delivery/test_no_session_reply_threading.py+++ b/core/tests/switch_core/delivery/test_no_session_reply_threading.py@@ -77,6 +77,9 @@ def _fake_self() -> str | None:return None+ async def _no_notice(_session: object) -> None:+ return None+ns = SimpleNamespace(agent=SimpleNamespace(id="agent-1", name="cc-bug-fixing"),tenant_id=TENANT_ZERO_ID,@@ -88,6 +91,7 @@ def _fake_self(_fresh_agent=_fresh_agent,_gate_addressed=_gate_addressed,_sender_role=_sender_role,+ _switch_notice=_no_notice,_is_available=_is_available,_reply_when_unavailable_here=_reply_when_unavailable_here,_triggered_by_auto_reply=AgentRecipient._triggered_by_auto_reply,diff --git a/core/tests/switch_core/delivery/test_switch_notice.py b/core/tests/switch_core/delivery/test_switch_notice.pynew file mode 100644index 000000000..5c200a51d--- /dev/null+++ b/core/tests/switch_core/delivery/test_switch_notice.py@@ -0,0 +1,74 @@+"""What Switch has to tell an agent rides on the next message it receives,+until the agent reads about it: read once for every agent of the room."""++from __future__ import annotations++from types import SimpleNamespace++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.protocol.message_events import message_event+from switch_core.db.stores.template_install_store import TemplateInstallStore+from switch_core.delivery.recipient import AgentRecipient+from switch_core.transport.types import InboundMessage+from tests.switch_core.db.stores.test_template_install_store import _agent, _install++_STORE = TemplateInstallStore()+++async def test_notices_are_read_for_the_agents_that_have_one(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ noticed = await _agent(session, "switch-buddy-max")+ quiet = await _agent(session, "switch-buddy-zoe")+ plain = await _agent(session, "helper")+ install = await _install(session, noticed)+ await _install(session, quiet)+ (resource,) = await _STORE.resources(session, install.id)+ await _STORE.set_notice(session, resource.id, "New revision.")++ assert await _STORE.notices_for_agents(+ session, [noticed.id, quiet.id, plain.id]+ ) == {noticed.id: "New revision."}+ assert await _STORE.notices_for_agents(session, []) == {}+++async def test_the_recipient_asks_the_room_s_reads_for_its_own_notice() -> None:+ asked: list[str] = []++ class Reads:+ async def switch_notice(self, _session: object, agent_id: str) -> str:+ asked.append(agent_id)+ return "New revision."++ recipient = SimpleNamespace(agent=SimpleNamespace(id="a-1"), _notices=Reads())++ assert (+ await AgentRecipient._switch_notice(recipient, None) # type: ignore[arg-type]+ == "New revision."+ )+ assert asked == ["a-1"]+++def test_the_notice_rides_on_the_message() -> None:+ event = message_event(+ room_id="room-1",+ bridge_id=None,+ channel_type="direct",+ event=InboundMessage(+ room_id="room-1",+ event_id="$1",+ sender="@max:test",+ timestamp=1,+ body="hi",+ sender_name="max",+ ),+ addressed=True,+ sender_name="max",+ body="hi",+ thread_id=None,+ switch_notice="New revision.",+ )++ assert event.payload.switch_notice == "New revision." # type: ignore[union-attr]diff --git a/core/tests/switch_core/management/test_template_updates.py b/core/tests/switch_core/management/test_template_updates.pyindex cf302665b..12fcbf924 100644--- a/core/tests/switch_core/management/test_template_updates.py+++ b/core/tests/switch_core/management/test_template_updates.py@@ -16,6 +16,12 @@ from sqlalchemy import select, updatefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.operations import context as op_context+from switch_core.bridges.agent.operations import template_status+from switch_core.bridges.agent.operations.callctx import (+ CallContext,+ reset_call_context,+ set_call_context,+)from switch_core.db.models import (TENANT_ZERO_ID,Agent,@@ -55,6 +61,10 @@ def _short_listen(monkeypatch: pytest.MonkeyPatch) -> None:@pytest.fixturedef harness(session_factory: async_sessionmaker[AsyncSession]) -> Iterator[Harness]:harness = build_harness(session_factory)+ harness.protocol.config.feature_flags = { # type: ignore[attr-defined]+ "agent_management": True,+ "switch_buddy": True,+ }previous = op_context._protocolop_context.init_operations_protocol(harness.protocol)harness.gateway_app.include_router(rooms_router, prefix="/rooms")@@ -332,3 +342,58 @@ async def test_an_agent_not_named_as_a_buddy_is_never_taken_for_one(await _forget_install(harness, agent_id)assert await _updates(harness).record_existing_buddies(TENANT_ZERO_ID) == 0+++async def test_the_agent_reads_how_it_differs_and_is_no_longer_told(+ harness: Harness, client: httpx.AsyncClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ owner = await add_member(harness.session_factory, "ada")+ agent_id = await _create_buddy(harness, client, owner, "switch-buddy-ada")+ await _owner_edits_instructions(harness, agent_id, "Mine, all mine.")+ install, _ = await _install(harness, agent_id)+ new = _next_revision(can_manage_agents=False)+ await _updates(harness).update_install(TENANT_ZERO_ID, new, install)+ monkeypatch.setattr(template_status, "official_template", lambda *a: new)++ status = await _as(agent_id, template_status.get_template_status)++ assert status["template"] == {+ "id": BUDDY_ID,+ "name": "switch-buddy",+ "source": "official",+ }+ assert (status["installed_revision"], status["current_revision"]) == (+ new.version,+ new.version,+ )+ ((differs),) = status["differs"]+ assert differs["field"] == "instructions"+ assert differs["yours"] == "Mine, all mine."+ assert "(revised)" in differs["recommended"]+ assert status["permissions"] == [+ {"setting": "can_manage_agents", "yours": True, "recommended": False}+ ]+ _, resource = await _install(harness, agent_id)+ assert resource.notice is None+++async def test_an_agent_from_no_template_has_no_status(+ harness: Harness, client: httpx.AsyncClient+) -> None:+ owner = await add_member(harness.session_factory, "ada")+ agent_id = await _create_buddy(harness, client, owner, "switch-buddy-ada")+ await _forget_install(harness, agent_id)++ assert await _as(agent_id, template_status.get_template_status) == {+ "template": None+ }+++async def _as(agent_id: str, fn: Any, **kwargs: Any) -> Any:+ token = set_call_context(+ CallContext(agent_id=agent_id, session_key=None, session=None)+ )+ try:+ return await fn(**kwargs)+ finally:+ reset_call_context(token)