1111from ..core .connection_manager import connection_manager
1212from ..utils .logger import get_logger
1313from ..utils .jsonrpc import (
14- JSONRPCProtocol ,
15- create_connection_established_message ,
1614 create_tool_not_connected_error ,
1715 create_forward_failed_error ,
1816)
@@ -26,78 +24,6 @@ class WebSocketHandler:
2624 def __init__ (self ):
2725 pass
2826
29- async def handle_tool_connection (
30- self , websocket : WebSocketServerProtocol , path : str
31- ):
32- """处理工具端连接"""
33- try :
34- # 解析URL参数获取agentId
35- agent_id = self ._extract_agent_id (path )
36- if not agent_id :
37- await websocket .close (1008 , "缺少agentId参数" )
38- return
39-
40- # 注册连接
41- await connection_manager .register_tool_connection (agent_id , websocket )
42-
43- # 发送连接确认消息
44- connection_message = create_connection_established_message (
45- agent_id , "工具端连接已建立"
46- )
47- await websocket .send (connection_message )
48-
49- logger .info (f"工具端连接已建立: { agent_id } " )
50-
51- # 处理消息
52- async for message in websocket :
53- await self ._handle_tool_message (agent_id , message )
54-
55- except ConnectionClosed :
56- logger .info (
57- f"工具端连接已关闭: { agent_id if 'agent_id' in locals () else 'unknown' } "
58- )
59- except Exception as e :
60- logger .error (f"处理工具端连接时发生错误: { e } " )
61- finally :
62- if "agent_id" in locals ():
63- await connection_manager .unregister_tool_connection (agent_id )
64-
65- async def handle_robot_connection (
66- self , websocket : WebSocketServerProtocol , path : str
67- ):
68- """处理小智端连接"""
69- try :
70- # 解析URL参数获取agentId
71- agent_id = self ._extract_agent_id (path )
72- if not agent_id :
73- await websocket .close (1008 , "缺少agentId参数" )
74- return
75-
76- # 注册连接
77- await connection_manager .register_robot_connection (agent_id , websocket )
78-
79- # 发送连接确认消息
80- connection_message = create_connection_established_message (
81- agent_id , "小智端连接已建立"
82- )
83- await websocket .send (connection_message )
84-
85- logger .info (f"小智端连接已建立: { agent_id } " )
86-
87- # 处理消息
88- async for message in websocket :
89- await self ._handle_robot_message (agent_id , message )
90-
91- except ConnectionClosed :
92- logger .info (
93- f"小智端连接已关闭: { agent_id if 'agent_id' in locals () else 'unknown' } "
94- )
95- except Exception as e :
96- logger .error (f"处理小智端连接时发生错误: { e } " )
97- finally :
98- if "agent_id" in locals ():
99- await connection_manager .unregister_robot_connection (agent_id )
100-
10127 async def _handle_tool_message (self , agent_id : str , message : str ):
10228 """处理工具端消息"""
10329 try :
0 commit comments