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
fix(commands): a typed !retry is held to the same rules as Retry
raullopez-sandboxd35ca52b25f6
diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.pyindex c8bb0f598..c54bd67f7 100644--- a/core/switch_core/bridges/agent/commands.py+++ b/core/switch_core/bridges/agent/commands.py@@ -7,6 +7,8 @@ from collections.abc import Awaitable, Callablefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Literal, cast+from sqlalchemy import select+from switch_core.agent_display_name import (agent_label,agent_label_with_identifier,@@ -17,7 +19,7 @@ from switch_core.aliases import (check_alias_collisions,validate_alias_format,)-from switch_core.authz import Principal, require_manage+from switch_core.authz import Principal, administers_tenant, require_managefrom switch_core.bridges.agent.protocol.agent_core import (AgentExistsError,AgentRenameRefused,@@ -31,9 +33,21 @@ from switch_core.bridges.agent.protocol.types import (from switch_core.clients.admin_messages import AdminMessageTypefrom switch_core.clients.mentions import mention_tokens as _mention_tokensfrom switch_core.db.audit import AuditAction, record_audit_event-from switch_core.db.models import CollaborationBridge, Room, User, require_tenant_id+from switch_core.db.models import (+ Agent,+ CollaborationBridge,+ Message,+ Room,+ User,+ require_tenant_id,+)from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_runtime_state_store import AgentRuntimeStateStore+from switch_core.db.stores.session_activity_store import (+ RETRYABLE_TURN_STATUSES,+ AgentSessionActivityStore,+)+from switch_core.db.stores.user_store import UserStorefrom switch_core.delivery.addressing import AddressingResolverfrom switch_core.events import CommandEventfrom switch_core.transport import RoomRef@@ -43,7 +57,6 @@ if TYPE_CHECKING:from switch_core.clients.command_consumer import CommandConsumerfrom switch_core.clients.room_meta import RoomMeta- from switch_core.db.models import Agentfrom switch_core.delivery.recipient import AgentRecipientlogger = logging.getLogger(__name__)@@ -453,6 +466,68 @@ class ControlDecision:answer: Callable[[], Awaitable[None]] | None+async def _retry_refusal(+ client: AgentRecipient,+ room_id: str,+ event: CommandEvent,+ agent: Agent,+ message_id: str,+) -> str | None:+ """Why a typed `!retry` may not run, or None: the rules Switch Console's+ Retry is held to (`ChatService._require_retryable`), whichever way the+ command arrives. The message must be in this room, sent by whoever asks+ or asked by someone who manages the room, and the agent's turn for it+ must have ended in an error or been interrupted."""+ async with client.session_factory() as session:+ message = (+ await session.execute(+ select(Message).where(+ Message.room_id == room_id, Message.transport_event_id == message_id+ )+ )+ ).scalar_one_or_none()+ if message is None:+ return "Could not retry: that message is not in this room."+ if message.sender_id != event.user_id and not await _manages_room(+ client, session, room_id, event.user_id+ ):+ return (+ "Could not retry: only whoever sent that message, or someone who "+ "manages the room, can retry it."+ )+ turn = await AgentSessionActivityStore().turn_for_message(+ session, agent.id, room_id, message_id+ )+ if turn is None or turn.status not in RETRYABLE_TURN_STATUSES:+ return (+ f"Could not retry: {agent.name} has no failed or interrupted turn for "+ "that message."+ )+ return None+++async def _manages_room(+ client: AgentRecipient, session: AsyncSession, room_id: str, sender: str+) -> bool:+ """Whether the Switch user behind `sender` owns the room or administers+ the tenant."""+ principal = await client._addressing.resolve_sender(session, sender)+ if principal is None or principal.kind != "user":+ return False+ room = await session.get(Room, room_id)+ users = UserStore()+ for user_id in principal.user_ids:+ if room is not None and room.owner_id == user_id:+ return True+ user = await session.get(User, user_id)+ role = await users.tenant_role(session, client.tenant_id, user_id)+ if user is not None and administers_tenant(+ is_operator=user.role == "admin", tenant_role=role+ ):+ return True+ return False++async def _decide_control_command(client: AgentRecipient,room: RoomRef,@@ -497,8 +572,14 @@ async def _decide_control_command(f"Could not send {command}: the room command has no stable message ID.")target = retry_target(event.args) if command == "retry" else None- if command == "retry" and target is None:- return say("Could not retry: the command names no message to run again.")+ if command == "retry":+ if target is None:+ return say(+ "Could not retry: the command names no message to run again."+ )+ refusal = await _retry_refusal(client, meta.room_id, event, agent, target)+ if refusal is not None:+ return say(refusal)frame = room_control_frame(agent_id=agent.id,session_id=placed,diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.pyindex 68cc3fd0b..1b7946875 100644--- a/core/switch_core/chats/service.py+++ b/core/switch_core/chats/service.py@@ -85,6 +85,7 @@ from switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.session_activity_store import (+ RETRYABLE_TURN_STATUSES,AgentSessionActivityStore,ApprovalRequestStore,)@@ -1838,6 +1839,13 @@ class ChatService:"NOTHING_TO_RETRY",f"{agent.name} took no turn for that message, so there is nothing to retry.",)+ if turn.status not in RETRYABLE_TURN_STATUSES:+ raise ChatError(+ 409,+ "NOTHING_TO_RETRY",+ f"{agent.name}'s turn for that message did not fail and was not "+ "interrupted, so there is nothing to retry.",+ )async def warm(self, tenant_id: str, user: User, room_id: str, *, agent_id: strdiff --git a/core/switch_core/db/stores/session_activity_store.py b/core/switch_core/db/stores/session_activity_store.pyindex 7e1a9e570..39bfb53a1 100644--- a/core/switch_core/db/stores/session_activity_store.py+++ b/core/switch_core/db/stores/session_activity_store.py@@ -25,6 +25,8 @@ if TYPE_CHECKING:from sqlalchemy.ext.asyncio import AsyncSessionTURN_ITEM_ID = "turn"+# The ends a turn can be run again from: it failed, or it was stopped.+RETRYABLE_TURN_STATUSES = frozenset({"error", "interrupted"})class ApprovalRequestStore:diff --git a/core/tests/switch_core/bridges/agent/test_control_commands.py b/core/tests/switch_core/bridges/agent/test_control_commands.pyindex bf202df0c..eb1f698c3 100644--- a/core/tests/switch_core/bridges/agent/test_control_commands.py+++ b/core/tests/switch_core/bridges/agent/test_control_commands.py@@ -491,6 +491,10 @@ async def test_a_controller_backed_agent_is_relayed_a_retry_of_the_message(client = _client(reply, command_level="unsupported", enqueue=[])client._connections = registry+ async def _retryable(*_a: Any) -> None:+ return None++ monkeypatch.setattr(commands, "_retry_refusal", _retryable)event = _event("retry")event.args = "@agent $m1"await _cmd_retry(client, SimpleNamespace(room_id="!m:server"), event, False)diff --git a/core/tests/switch_core/bridges/agent/test_retry_command_checks.py b/core/tests/switch_core/bridges/agent/test_retry_command_checks.pynew file mode 100644index 000000000..f95ac1df3--- /dev/null+++ b/core/tests/switch_core/bridges/agent/test_retry_command_checks.py@@ -0,0 +1,119 @@+"""A typed `!retry @agent <message>` is held to the rules Switch Console's+Retry is: the message is in the room, whoever asks sent it or manages the+room, and the agent's turn for it failed or was interrupted."""++from __future__ import annotations++from datetime import UTC, datetime+from types import SimpleNamespace++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent import commands+from switch_core.chats import MEMBER_CLIENT_TYPE+from switch_core.db.models import (+ AgentSessionActivityItem,+ Client,+ Message,+ Room,+ User,+)+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.external_user_store import ExternalUserStore+from switch_core.db.stores.room_role_store import RoomRoleStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.delivery.addressing import AddressingResolver+from tests.switch_core.gateway.agent_route_harness import add_agent++TENANT = "00000000-0000-0000-0000-000000000000"+++async def _member(session: AsyncSession, name: str) -> tuple[User, Client]:+ user = User(name=name, email=f"{name}@example.invalid", role="user")+ session.add(user)+ await session.flush()+ client = Client(+ transport_user_id=f"@member-{name}:test",+ display_name=name,+ type=MEMBER_CLIENT_TYPE,+ user_id=user.id,+ )+ session.add(client)+ await session.flush()+ return user, client+++async def test_a_typed_retry_meets_the_consoles_rules(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ owner, owner_client = await _member(session, "owner")+ _, sender = await _member(session, "sender")+ _, stranger = await _member(session, "stranger")+ agent = await add_agent(session, name="helper", owner_id=owner.id)+ room = Room(+ transport_room_id="!r:test", name="r", description="", owner_id=owner.id+ )+ session.add(room)+ await session.flush()+ session.add(+ Message(+ room_id=room.id,+ seq=1,+ transport_event_id="$m1",+ sender_id=sender.transport_user_id,+ sender_client_id=sender.id,+ event_type="m.room.message",+ body="@helper plan",+ content={"body": "@helper plan"},+ )+ )+ session.add(+ AgentSessionActivityItem(+ agent_id=agent.id,+ session_id="s1",+ turn_id="t1",+ item_id="turn",+ kind="turn",+ revision=1,+ status="error",+ title="Turn",+ text="",+ room_id=room.id,+ message_id="$m1",+ occurred_at=datetime.now(UTC),+ )+ )+ await session.commit()++ client = SimpleNamespace(+ session_factory=session_factory,+ tenant_id=TENANT,+ _addressing=AddressingResolver(+ room_store=RoomStore(),+ room_role_store=RoomRoleStore(),+ client_store=ClientStore(),+ agent_store=AgentStore(),+ external_user_store=ExternalUserStore(),+ live_connection_ids=set,+ ),+ )++ async def refusal(asker: Client, message_id: str = "$m1") -> str | None:+ event = SimpleNamespace(user_id=asker.transport_user_id)+ return await commands._retry_refusal(client, room.id, event, agent, message_id) # type: ignore[arg-type]++ assert await refusal(sender) is None+ assert await refusal(owner_client) is None+ assert "only whoever sent" in (await refusal(stranger) or "")+ assert "not in this room" in (await refusal(sender, "$nowhere") or "")++ async with session_factory() as session:+ row = await session.get(+ AgentSessionActivityItem, (TENANT, agent.id, "s1", "t1", "turn")+ )+ assert row is not None+ row.status = "completed"+ await session.commit()+ assert "no failed or interrupted turn" in (await refusal(sender) or "")diff --git a/core/tests/switch_core/gateway/test_chats_controls.py b/core/tests/switch_core/gateway/test_chats_controls.pyindex e95207778..a2c22b4c6 100644--- a/core/tests/switch_core/gateway/test_chats_controls.py+++ b/core/tests/switch_core/gateway/test_chats_controls.py@@ -274,3 +274,25 @@ async def test_a_retry_is_for_the_sender_or_a_manager_and_posts_once(other = await _retry(chats, chats.alice, room_id, agent, "k2", "$other")assert other.status_code == 409assert _code(other) == "REQUEST_REUSED"+++async def test_only_a_failed_or_interrupted_turn_is_retried(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ sent = await chats.send(chats.alice, room_id, "m1", "@helper plan a picnic")+ message_id = sent.json()["messages"][0]["messageId"]+ await _turn_for(chats, agent, room_id, message_id)+ for index, status in enumerate(("running", "completed")):+ async with chats.factory() as session:+ await session.execute(+ update(AgentSessionActivityItem)+ .where(AgentSessionActivityItem.turn_id == "t1")+ .values(status=status)+ )+ await session.commit()+ refused = await _retry(+ chats, chats.alice, room_id, agent, f"k{index}", message_id+ )+ assert refused.status_code == 409+ assert _code(refused) == "NOTHING_TO_RETRY"+ assert await _commands(chats, room_id) == []