class ProfiledAgent:
"""Dispatch events to profile-specific engines while preserving pending-action ownership."""
def __init__(self, engines: Mapping[str, Any], router: ProfileRouter) -> None:
if set(engines) != set(router._profiles):
raise ValueError("profile engines must exactly match configured profiles")
for profile_id, engine in engines.items():
namespace = getattr(engine, "session_namespace", None)
if namespace is not None and namespace != profile_id:
raise ValueError(f"profile {profile_id!r} must use session namespace {profile_id!r}")
self._engines = dict(engines)
self.router = router
async def run(self, event: Any) -> None:
await self._engines[self.router.profile_for_event(event)].run(event)
async def handle_card_action(self, event: Any) -> dict[str, Any]:
engine = await self._engine_for_pending(event, "__approval__", "approvals")
return await engine.handle_card_action(event)
async def resume_authorization(self, authorization_id: str, *, user: Mapping[str, Any] | None = None) -> str:
engine = await self._engine_for_authorization(authorization_id)
return await engine.resume_authorization(authorization_id, user=user)
async def _finalize(self, event: Any, text: str) -> None:
"""Keep framework-level denials and errors in the originating profile's chat."""
await self._engines[self.router.profile_for_event(event)]._finalize(event, text)
async def _engine_for_pending(self, event: Any, value_key: str, store_name: str) -> Any:
body = getattr(event, "body", None) or {}
value = ((body.get("action") or {}).get("value") or {}) if isinstance(body, Mapping) else {}
pending_id = value.get(value_key) if isinstance(value, Mapping) else None
if pending_id:
for engine in self._engines.values():
pending = await getattr(engine, store_name).get(str(pending_id))
if pending is not None:
return self._engines[self.router.profile_for_session(pending.session_id)]
return self._engines[self.router.profile_for_event(event)]
async def _engine_for_authorization(self, authorization_id: str) -> Any:
for engine in self._engines.values():
pending = await engine.authorizations.get(authorization_id)
if pending is not None:
return self._engines[self.router.profile_for_session(pending.session_id)]
return self._engines[self.router.default_profile]