11"""File-based implementation of session manager."""
22
33import logging
4- from typing import TYPE_CHECKING , Any , Optional
4+ from typing import TYPE_CHECKING , Any , List
5+ from uuid import uuid4
56
67from ..agent .state import AgentState
78from ..handlers .callback_handler import CompositeCallbackHandler
89from ..types .content import Message
9- from .exceptions import SessionException
10- from .file_session_dao import FileSessionDAO
10+ from ..types .exceptions import SessionException
1111from .session_dao import SessionDAO
1212from .session_manager import SessionManager
1313from .session_models import Session , SessionAgent , SessionMessage , SessionType
@@ -28,13 +28,13 @@ class AgentSessionManager(SessionManager):
2828 def __init__ (
2929 self ,
3030 session_id : str ,
31- session_dao : Optional [ SessionDAO ] = None ,
31+ session_dao : SessionDAO ,
3232 ):
3333 """Initialize the FileSessionManager."""
34- self .session_dao = session_dao or FileSessionDAO ()
34+ self .session_dao = session_dao
3535 self .session_id = session_id
3636
37- def append_message_to_agent_session (self , agent : "Agent" , message : Message ) -> None :
37+ def append_message (self , agent : "Agent" , message : Message ) -> None :
3838 """Append a message to the agent's session.
3939
4040 Args:
@@ -56,7 +56,7 @@ def append_message_to_agent_session(self, agent: "Agent", message: Message) -> N
5656 ),
5757 )
5858
59- def initialize_agent (self , agent : "Agent" ) -> None :
59+ def initialize (self , agent : "Agent" ) -> None :
6060 """Restore agent data from the current session.
6161
6262 Args:
@@ -65,20 +65,33 @@ def initialize_agent(self, agent: "Agent") -> None:
6565 Raises:
6666 SessionException: If restore operation fails
6767 """
68- if agent .id is None :
69- raise ValueError ("`agent.id` must be set before initializing session." )
70-
7168 try :
7269 # Try to read existing session
7370 session = self .session_dao .read_session (self .session_id )
7471
72+ if agent .id is None :
73+ agents : List [SessionAgent ] = self .session_dao .list_agents (self .session_id )
74+ if len (agents ) == 0 :
75+ agent_id = str (uuid4 ())
76+ if len (agents ) == 1 :
77+ agent_id = agents [0 ].agent_id
78+ logger .debug (
79+ "session_id=<%s> | agent_id=<%s> | Restoring agent data from session" , self .session_id , agent_id
80+ )
81+ else :
82+ raise ValueError (
83+ "If there is more than one agent in a session, agent.agent_id must be set manually."
84+ )
85+ else :
86+ if agent .id not in [agent .agent_id for agent in self .session_dao .list_agents (self .session_id )]:
87+ raise ValueError (f"Agent { agent .id } not found in session { self .session_id } " )
88+ agent_id = agent .id
89+
7590 if session .session_type != SessionType .AGENT :
7691 raise ValueError (f"Invalid session type: { session .session_type } " )
7792
78- if agent .id not in [agent .agent_id for agent in self .session_dao .list_agents (self .session_id )]:
79- raise ValueError (f"Agent { agent .id } not found in session { self .session_id } " )
80-
8193 # Initialize agent
94+ agent .id = agent_id
8295 agent .messages = [
8396 session_message .to_message ()
8497 for session_message in self .session_dao .list_messages (self .session_id , agent .id )
@@ -87,8 +100,12 @@ def initialize_agent(self, agent: "Agent") -> None:
87100
88101 except SessionException :
89102 # Session doesn't exist, create new one
90- logger .debug ("Session not found, creating new session" )
103+ logger .debug ("session_id=<%s> | Session not found, creating new session" )
91104 # Session doesn't exist, create new one
105+ if agent .id is None :
106+ agent_id = str (uuid4 ())
107+ logger .debug ("agent_id=<%s> | Creating agent_id for agent since none was set." , agent_id )
108+ agent .id = agent_id
92109 session = Session (session_id = self .session_id , session_type = SessionType .AGENT )
93110 session_agent = SessionAgent (
94111 agent_id = agent .id ,
@@ -110,7 +127,7 @@ def session_callback(**kwargs: Any) -> None:
110127 # Handle message persistence
111128 if "message" in kwargs :
112129 message = kwargs ["message" ]
113- self .append_message_to_agent_session (kwargs ["agent" ], message )
130+ self .append_message (kwargs ["agent" ], message )
114131 except Exception as e :
115132 logger .error ("Persistence operation failed" , e )
116133
0 commit comments