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
Read an agent's membership only before it says something (CHOO-3667)
Abel Dantascffe7f812c22
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5fd9c4fe4..6cc25cf8e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -233,6 +233,11 @@ version of their own to them without also giving them a release of their own.group whose subgroup would move up next to a namesake is refused too, andthe dashboard now shows why. Names can no longer contain `/` or be blank.Existing duplicates are left as they are and can be reached by id.+- **A message addressed to a connected agent no longer reads the agent's+ membership after it commits.** That read stops an agent removed from the+ room in the meantime from saying anything there, and a connected agent has+ nothing to say about a message addressed to it, so the read is now made only+ before a refusal or an offline notice is posted, or a machine woken.#### Fixed- **On Slack, the 👀 and the activity card no longer arrive after the agent'sdiff --git a/core/switch_core/delivery/recipient.py b/core/switch_core/delivery/recipient.pyindex bc33e718a..4ac8de8c0 100644--- a/core/switch_core/delivery/recipient.py+++ b/core/switch_core/delivery/recipient.py@@ -162,11 +162,18 @@ class Delivery:`named` says whether a rule named the agent (its name, its alias here, arole it holds, a direct room), before its addressing policy and budgetwere applied: the router asks whether a message named anybody at all.++ `checks_membership` says that `after` asks whether the agent is still a+ member of the room itself, right before it would say or wake anything+ (`AgentRecipient.still_member`), so the router does not ask before running+ it. A message addressed to a connected agent leaves only a report to make,+ and asking first was a read for every agent a message was for."""own_event: Callable[[InboundEvent], OwnEvent] | Noneafter: Callable[[InboundEvent], Awaitable[None]] | Nonenamed: bool = False+ checks_membership: bool = FalseNOTHING = Delivery(own_event=None, after=None)@@ -542,6 +549,20 @@ class AgentRecipient:"""return self.agent+ async def _still_here(self, row: InboundEvent) -> bool:+ """`still_member`, saying in the log that what the row left the agent+ to say is not said when it is not."""+ if await self.still_member():+ return True+ logger.info(+ "Agent %s was taken out of room %s after row %s was decided; "+ "what the row left it to say is not said",+ self.agent.name,+ self._meta.room_id,+ row.event_id,+ )+ return False+async def still_member(self) -> bool:"""Whether the agent is a member of the room now, read when the worka row left it (`Delivery.after`, `greet`) is about to run.@@ -622,6 +643,7 @@ class AgentRecipient:own_event=own_event if addressed else None,after=after if addressed or refusal is not None else None,named=named,+ checks_membership=True,)async def decide_follow_up(@@ -723,15 +745,25 @@ class AgentRecipient:its own that is closed before anything is posted: posting is a writeof its own, and holding a connection across it is how a pool slotends up idle in a transaction.++ Whether the agent is still a member of the room is asked only before+ something would be said or a machine woken, since a connected agent+ leaves nothing to say (`Delivery.checks_membership`)."""meta = self._metaagent_live = Falseunavailable: str | None = None+ member = Falseif addressed and not self._triggered_by_auto_reply(event):async with self.session_factory() as session:agent = await self._fresh_agent(session)agent_live = await self._is_available(session, agent, meta.room_id)- if not agent_live:+ if not agent_live:+ # The reply may wake the agent's cloud machine.+ if not await self._still_here(event):+ return+ member = True+ async with self.session_factory() as session:unavailable = await self._reply_when_unavailable_here(session, agent, meta, self._sender_handle(event))@@ -741,6 +773,10 @@ class AgentRecipient:meta, event, agent_live=agent_live, has_attachment=False)+ if refusal is None and unavailable is None:+ return+ if not member and not await self._still_here(event):+ returnif refusal is not None:await self._post_auto_reply(self._room.room_id, event, refusal, reply_thread_rootdiff --git a/core/switch_core/delivery/router.py b/core/switch_core/delivery/router.pyindex ad0c74434..911e1fdcb 100644--- a/core/switch_core/delivery/router.py+++ b/core/switch_core/delivery/router.py@@ -590,7 +590,15 @@ class Routed:for recipient, delivery in plan.deliveries:if delivery.after is not None:work.append(- (recipient.agent.name, _bind(recipient, delivery.after, row))+ (+ recipient.agent.name,+ _bind(+ recipient,+ delivery.after,+ row,+ checks_membership=delivery.checks_membership,+ ),+ ))if plan.arrival is not None:arrival = plan.arrival@@ -611,13 +619,16 @@ def _bind(recipient: AgentRecipient,after: Callable[[InboundEvent], Awaitable[None]],row: InboundEvent,+ *,+ checks_membership: bool = False,) -> Callable[[], Awaitable[None]]:"""The work `row` left the agent, run as the agent once the row hascommitted, and only while the agent is still a member of the room- (`AgentRecipient.still_member`)."""+ (`AgentRecipient.still_member`), which work that `checks_membership`+ asks itself before it says anything."""async def run() -> None:- if not await recipient.still_member():+ if not checks_membership and not await recipient.still_member():logger.info("Agent %s was taken out of room %s after row %s was decided; ""what the row left it to say is not said",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 cf303efd2..368777dd6 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@@ -634,6 +634,11 @@ def _addressing_client(return Nonens._switch_notice = _no_notice++ async def _still_here(_row: object) -> bool:+ return True # still a member of ROOM, so its replies are posted++ ns._still_here = _still_herens._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 c05b9f9f1..7650a9d36 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@@ -80,6 +80,9 @@ def _fake_self(async def _no_notice(_session: object) -> None:return None+ async def _still_here(_row: object) -> bool:+ return True # still a member of the room, so the reply is posted+ns = SimpleNamespace(agent=SimpleNamespace(id="agent-1", name="cc-bug-fixing"),tenant_id=TENANT_ZERO_ID,@@ -97,6 +100,7 @@ def _fake_self(_triggered_by_auto_reply=AgentRecipient._triggered_by_auto_reply,actor=SimpleNamespace(send_message=send_message),_report_addressed=lambda *a, **k: None,+ _still_here=_still_here,)# Exercise the real sender-tagging and auto-reply helpers.ns._sender_handle = AgentRecipient._sender_handle.__get__(ns)diff --git a/core/tests/switch_core/delivery/test_router_sessions.py b/core/tests/switch_core/delivery/test_router_sessions.pyindex a277fed2d..8edcbeec8 100644--- a/core/tests/switch_core/delivery/test_router_sessions.py+++ b/core/tests/switch_core/delivery/test_router_sessions.py@@ -21,6 +21,11 @@ from typing import Anyimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.bridges.agent.protocol.agent_connections import (+ PROTOCOL_VERSION,+ ClientDeclaration,+)+from switch_core.bridges.agent.protocol.positions import OWN_EVENTSfrom switch_core.db.models import Agent, Client, Roomfrom switch_core.db.stores.room_store import RoomStorefrom switch_core.delivery.recipient import AgentRecipient@@ -207,3 +212,46 @@ class TestWritingAMessage:assert (scope.taken, scope.peak) == (1, 1)assert len(await own_events(session_factory, agents["a3"][0].id)) == 1+++class TestAfterTheWrite:+ async def test_a_message_for_a_connected_agent_asks_nothing_more(+ self,+ monkeypatch: pytest.MonkeyPatch,+ session_factory: async_sessionmaker[AsyncSession],+ ) -> None:+ """A connected agent has nothing to say about a message addressed to+ it, so nothing asks whether it is still in the room once the message+ has committed: that is asked only before an agent says or wakes+ something (`Delivery.checks_membership`)."""+ process = process_on(session_factory)+ room = await make_room(session_factory)+ louisa = await make_person(session_factory, "louisa")+ await add_member(session_factory, room, louisa)+ agent, client = await make_agent(session_factory, "member")+ await add_member(session_factory, room, client, agent=agent)+ process.connections.open(+ agent_id=agent.id,+ connection_id="c1",+ scope="single",+ delivery_filter="all",+ spawn_capable=False,+ position={OWN_EVENTS: 0},+ declaration=ClientDeclaration(speaks=PROTOCOL_VERSION),+ expected_generation=None,+ )+ asked: list[str] = []+ still_member = AgentRecipient.still_member++ async def recording(self: AgentRecipient) -> bool:+ asked.append(self.agent.id)+ return await still_member(self)++ monkeypatch.setattr(AgentRecipient, "still_member", recording)++ await process.say(room, "@member can you look at this", sender=louisa)+ await process.idle()++ assert len(await own_events(session_factory, agent.id)) == 1+ assert asked == []+ assert [r["agent_live"] for r in process.telemetry.addressed] == [True]