66import asyncio
77import json
88import time
9- from typing import Dict , Set , Optional , Any
9+ from typing import Dict , Any
1010from websockets .server import WebSocketServerProtocol
1111from websockets .exceptions import ConnectionClosed
1212from ..utils .logger import get_logger
@@ -18,102 +18,118 @@ class ConnectionManager:
1818 """连接管理器"""
1919
2020 def __init__ (self ):
21- # 工具端连接: {userId : websocket}
21+ # 工具端连接: {agentId : websocket}
2222 self .tool_connections : Dict [str , WebSocketServerProtocol ] = {}
23- # 小智端连接: {userId : websocket}
23+ # 小智端连接: {agentId : websocket}
2424 self .robot_connections : Dict [str , WebSocketServerProtocol ] = {}
25- # 连接时间戳: {userId : timestamp}
25+ # 连接时间戳: {agentId : timestamp}
2626 self .connection_timestamps : Dict [str , float ] = {}
2727 # 连接锁
2828 self ._lock = asyncio .Lock ()
2929
3030 async def register_tool_connection (
31- self , user_id : str , websocket : WebSocketServerProtocol
31+ self , agent_id : str , websocket : WebSocketServerProtocol
3232 ):
3333 """注册工具端连接"""
3434 async with self ._lock :
3535 # 如果已存在连接,先关闭旧连接
36- if user_id in self .tool_connections :
37- old_websocket = self .tool_connections [user_id ]
36+ if agent_id in self .tool_connections :
37+ old_websocket = self .tool_connections [agent_id ]
3838 try :
3939 await old_websocket .close (1000 , "新连接替换" )
4040 except Exception as e :
4141 logger .warning (f"关闭旧工具端连接失败: { e } " )
4242
43- self .tool_connections [user_id ] = websocket
44- self .connection_timestamps [user_id ] = time .time ()
45- logger .info (f"工具端连接已注册: { user_id } " )
43+ self .tool_connections [agent_id ] = websocket
44+ self .connection_timestamps [agent_id ] = time .time ()
45+ logger .info (f"工具端连接已注册: { agent_id } " )
4646
4747 async def register_robot_connection (
48- self , user_id : str , websocket : WebSocketServerProtocol
48+ self , agent_id : str , websocket : WebSocketServerProtocol
4949 ):
5050 """注册小智端连接"""
5151 async with self ._lock :
5252 # 如果已存在连接,先关闭旧连接
53- if user_id in self .robot_connections :
54- old_websocket = self .robot_connections [user_id ]
53+ if agent_id in self .robot_connections :
54+ old_websocket = self .robot_connections [agent_id ]
5555 try :
5656 await old_websocket .close (1000 , "新连接替换" )
5757 except Exception as e :
5858 logger .warning (f"关闭旧机器人连接失败: { e } " )
5959
60- self .robot_connections [user_id ] = websocket
61- self .connection_timestamps [user_id ] = time .time ()
62- logger .info (f"小智端连接已注册: { user_id } " )
60+ self .robot_connections [agent_id ] = websocket
61+ self .connection_timestamps [agent_id ] = time .time ()
62+ logger .info (f"小智端连接已注册: { agent_id } " )
6363
64- async def unregister_tool_connection (self , user_id : str ):
64+ async def unregister_tool_connection (self , agent_id : str ):
6565 """注销工具端连接"""
6666 async with self ._lock :
67- if user_id in self .tool_connections :
68- del self .tool_connections [user_id ]
69- if user_id in self .connection_timestamps :
70- del self .connection_timestamps [user_id ]
71- logger .info (f"工具端连接已注销: { user_id } " )
67+ if agent_id in self .tool_connections :
68+ del self .tool_connections [agent_id ]
69+ if agent_id in self .connection_timestamps :
70+ del self .connection_timestamps [agent_id ]
71+ logger .info (f"工具端连接已注销: { agent_id } " )
7272
73- async def unregister_robot_connection (self , user_id : str ):
73+ async def unregister_robot_connection (self , agent_id : str ):
7474 """注销小智端连接"""
7575 async with self ._lock :
76- if user_id in self .robot_connections :
77- del self .robot_connections [user_id ]
78- if user_id in self .connection_timestamps :
79- del self .connection_timestamps [user_id ]
80- logger .info (f"小智端连接已注销: { user_id } " )
76+ if agent_id in self .robot_connections :
77+ del self .robot_connections [agent_id ]
78+ if agent_id in self .connection_timestamps :
79+ del self .connection_timestamps [agent_id ]
80+ logger .info (f"小智端连接已注销: { agent_id } " )
8181
82- async def forward_to_tool (self , user_id : str , message : Any ) -> bool :
82+ async def forward_to_tool (self , agent_id : str , message : Any ) -> bool :
8383 """转发消息给工具端"""
8484 async with self ._lock :
85- if user_id not in self .tool_connections :
86- logger .warning (f"工具端连接不存在: { user_id } " )
85+ if agent_id not in self .tool_connections :
86+ logger .warning (f"工具端连接不存在: { agent_id } " )
8787 return False
8888
89- websocket = self .tool_connections [user_id ]
89+ websocket = self .tool_connections [agent_id ]
9090 try :
91- await websocket .send_text (message )
92- logger .debug (f"消息已转发给工具端 { user_id } : { message [:100 ]} ..." )
91+ # 确保消息是字符串格式
92+ if isinstance (message , dict ):
93+ message_str = json .dumps (message , ensure_ascii = False )
94+ elif isinstance (message , str ):
95+ message_str = message
96+ else :
97+ message_str = str (message )
98+
99+ await websocket .send_text (message_str )
100+ logger .debug (f"消息已转发给工具端 { agent_id } : { message_str [:100 ]} ..." )
93101 return True
94102 except ConnectionClosed :
95- logger .warning (f"工具端连接已关闭: { user_id } " )
96- await self .unregister_tool_connection (user_id )
103+ logger .warning (f"工具端连接已关闭: { agent_id } " )
104+ await self .unregister_tool_connection (agent_id )
97105 return False
98106 except Exception as e :
99107 logger .error (f"转发消息给工具端失败: { e } " )
100108 return False
101109
102- async def forward_to_robot (self , user_id : str , message : Any ) -> bool :
110+ async def forward_to_robot (self , agent_id : str , message : Any ) -> bool :
103111 """转发消息给小智端"""
104112 async with self ._lock :
105- if user_id not in self .robot_connections :
106- logger .warning (f"小智端连接不存在: { user_id } " )
113+ if agent_id not in self .robot_connections :
114+ logger .warning (f"小智端连接不存在: { agent_id } " )
107115 return False
108116
109- websocket = self .robot_connections [user_id ]
117+ websocket = self .robot_connections [agent_id ]
110118 try :
111- await websocket .send_text (message )
112- logger .debug (f"消息已转发给小智端 { user_id } : { message [:100 ]} ..." )
119+ # 确保消息是字符串格式
120+ if isinstance (message , dict ):
121+ message_str = json .dumps (message , ensure_ascii = False )
122+ elif isinstance (message , str ):
123+ message_str = message
124+ else :
125+ message_str = str (message )
126+
127+ await websocket .send_text (message_str )
128+ logger .debug (f"消息已转发给小智端 { agent_id } : { message_str [:100 ]} ..." )
113129 return True
114130 except ConnectionClosed :
115- logger .warning (f"小智端连接已关闭: { user_id } " )
116- await self .unregister_robot_connection (user_id )
131+ logger .warning (f"小智端连接已关闭: { agent_id } " )
132+ await self .unregister_robot_connection (agent_id )
117133 return False
118134 except Exception as e :
119135 logger .error (f"转发消息给小智端失败: { e } " )
@@ -128,27 +144,27 @@ def get_connection_stats(self) -> Dict[str, Any]:
128144 + len (self .robot_connections ),
129145 }
130146
131- def is_tool_connected (self , user_id : str ) -> bool :
147+ def is_tool_connected (self , agent_id : str ) -> bool :
132148 """检查工具端是否已连接"""
133- return user_id in self .tool_connections
149+ return agent_id in self .tool_connections
134150
135- def is_robot_connected (self , user_id : str ) -> bool :
151+ def is_robot_connected (self , agent_id : str ) -> bool :
136152 """检查小智端是否已连接"""
137- return user_id in self .robot_connections
153+ return agent_id in self .robot_connections
138154
139155 async def cleanup_inactive_connections (self , timeout_seconds : int = 300 ):
140156 """清理不活跃的连接"""
141157 current_time = time .time ()
142158 async with self ._lock :
143159 inactive_users = []
144- for user_id , timestamp in self .connection_timestamps .items ():
160+ for agent_id , timestamp in self .connection_timestamps .items ():
145161 if current_time - timestamp > timeout_seconds :
146- inactive_users .append (user_id )
162+ inactive_users .append (agent_id )
147163
148- for user_id in inactive_users :
149- logger .info (f"清理不活跃连接: { user_id } " )
150- await self .unregister_tool_connection (user_id )
151- await self .unregister_robot_connection (user_id )
164+ for agent_id in inactive_users :
165+ logger .info (f"清理不活跃连接: { agent_id } " )
166+ await self .unregister_tool_connection (agent_id )
167+ await self .unregister_robot_connection (agent_id )
152168
153169
154170# 全局连接管理器实例
0 commit comments