from __future__ import annotations from gateway.core.channels.protocols import TraceBackend class ChannelTraceRouter: """ 与具体 IM 无关:按渠道 user_id 解析 workspace_id,并委托 TraceBackend 与 Agent ``trace_id`` 对齐。 飞书等渠道的入站消息路由见 ``gateway.core.channels.feishu.router.FeishuMessageRouter``。 """ def __init__( self, *, trace_backend: TraceBackend, workspace_prefix: str, default_agent_type: str = "personal_assistant", ) -> None: self._trace = trace_backend self._workspace_prefix = workspace_prefix self._agent_type = default_agent_type def _workspace_id_for_user(self, user_id: str) -> str: return f"{self._workspace_prefix}:{user_id}" async def get_trace_id(self, channel: str, user_id: str, *, create_if_missing: bool = True) -> str: """返回已绑定的 Agent trace_id;不存在时除非 ``create_if_missing=False`` 否则抛错(不再预分配 UUID)。""" tid = await self._trace.get_existing_trace_id(channel, user_id) if tid: return tid if not create_if_missing: raise NotImplementedError("无已绑定 trace_id 且 create_if_missing=False") raise RuntimeError( "尚无已绑定的 Agent trace_id:请先完成一次渠道入站(executor 成功返回后再 bind)。" ) async def create_trace_for_user(self, channel: str, user_id: str) -> str: return await self.get_trace_id(channel, user_id, create_if_missing=True)