55import uuid
66from collections .abc import Awaitable , Callable
77from datetime import datetime , timezone
8- from typing import TYPE_CHECKING
8+ from typing import TYPE_CHECKING , Any
99
1010import httpx
1111
@@ -21,6 +21,77 @@ class _CheckpointRestoreError(Exception):
2121 pass
2222
2323
24+ def _resolve_restore_server_url (server_url : str | None ) -> str :
25+ """Resolve the checkpoint restore server URL."""
26+ if server_url is not None :
27+ return server_url
28+
29+ from agent_debugger_sdk .config import get_config
30+
31+ config = get_config ()
32+ return config .endpoint or "http://localhost:8000"
33+
34+
35+ async def _fetch_checkpoint_payload (
36+ client : httpx .AsyncClient ,
37+ checkpoint_id : str ,
38+ server_url : str ,
39+ ) -> dict [str , Any ]:
40+ """Fetch and decode checkpoint payload data from the server."""
41+ try :
42+ response = await client .get (f"{ server_url } /api/checkpoints/{ checkpoint_id } " )
43+ response .raise_for_status ()
44+ payload = response .json ()
45+ except httpx .HTTPStatusError as e :
46+ raise _CheckpointRestoreError (
47+ f"Failed to restore checkpoint { checkpoint_id !r} from { server_url } : "
48+ f"{ e .response .status_code } { e .response .reason_phrase } "
49+ ) from e
50+ except httpx .RequestError as e :
51+ raise _CheckpointRestoreError (
52+ f"Network error while restoring checkpoint { checkpoint_id !r} from { server_url } : { e } "
53+ ) from e
54+ except Exception as e :
55+ raise _CheckpointRestoreError (
56+ f"Unexpected error while restoring checkpoint { checkpoint_id !r} from { server_url } : { e } "
57+ ) from e
58+
59+ if not isinstance (payload , dict ):
60+ raise _CheckpointRestoreError (
61+ f"Unexpected checkpoint payload type for { checkpoint_id !r} from { server_url } : "
62+ f"{ type (payload ).__name__ } "
63+ )
64+
65+ return payload
66+
67+
68+ def _build_restored_session (
69+ checkpoint_id : str ,
70+ checkpoint_data : dict [str , Any ],
71+ * ,
72+ session_id : str | None = None ,
73+ label : str = "" ,
74+ ) -> tuple [Session , BaseCheckpointState | None ]:
75+ """Build a restored Session and validated checkpoint state from payload data."""
76+ from agent_debugger_sdk .checkpoints import validate_checkpoint_state
77+
78+ state_dict = checkpoint_data .get ("state" , {})
79+ original_session_id = checkpoint_data .get ("session_id" , "" )
80+
81+ session = Session (
82+ id = session_id or str (uuid .uuid4 ()),
83+ agent_name = label or f"restored from { checkpoint_id [:8 ]} " ,
84+ framework = state_dict .get ("framework" , "custom" ),
85+ config = {
86+ "restored_from_checkpoint" : checkpoint_id ,
87+ "original_session_id" : original_session_id ,
88+ },
89+ )
90+
91+ restored_state = validate_checkpoint_state (state_dict )
92+ return session , restored_state
93+
94+
2495class SessionManager :
2596 """Manage session lifecycle for TraceContext.
2697
@@ -79,48 +150,9 @@ async def restore_from_checkpoint(
79150 Example:
80151 >>> session, state = await SessionManager.restore_from_checkpoint("ckpt_123")
81152 """
82- from agent_debugger_sdk .checkpoints import validate_checkpoint_state
83- from agent_debugger_sdk .config import get_config
153+ resolved_server_url = _resolve_restore_server_url (server_url )
84154
85- if server_url is None :
86- config = get_config ()
87- server_url = config .endpoint or "http://localhost:8000"
88-
89- # Fetch checkpoint data using a temporary client (avoids connection leaks)
90- # All processing happens inside the context manager to ensure checkpoint_data is in scope
91155 async with httpx .AsyncClient () as client :
92- try :
93- response = await client .get (f"{ server_url } /api/checkpoints/{ checkpoint_id } " )
94- response .raise_for_status ()
95- checkpoint_data = response .json ()
96- except httpx .HTTPStatusError as e :
97- raise _CheckpointRestoreError (
98- f"Failed to restore checkpoint { checkpoint_id !r} from { server_url } : "
99- f"{ e .response .status_code } { e .response .reason_phrase } "
100- ) from e
101- except httpx .RequestError as e :
102- raise _CheckpointRestoreError (
103- f"Network error while restoring checkpoint { checkpoint_id !r} from { server_url } : { e } "
104- ) from e
105- except Exception as e :
106- # Catch any other unexpected errors and wrap them
107- raise _CheckpointRestoreError (
108- f"Unexpected error while restoring checkpoint { checkpoint_id !r} from { server_url } : { e } "
109- ) from e
110-
111- # Process the checkpoint data inside the context manager where checkpoint_data is in scope
112- state_dict = checkpoint_data .get ("state" , {})
113- original_session_id = checkpoint_data .get ("session_id" , "" )
114-
115- session = Session (
116- id = session_id or str (uuid .uuid4 ()),
117- agent_name = label or f"restored from { checkpoint_id [:8 ]} " ,
118- framework = state_dict .get ("framework" , "custom" ),
119- config = {
120- "restored_from_checkpoint" : checkpoint_id ,
121- "original_session_id" : original_session_id ,
122- },
123- )
124-
125- restored_state = validate_checkpoint_state (state_dict )
126- return session , restored_state
156+ checkpoint_data = await _fetch_checkpoint_payload (client , checkpoint_id , resolved_server_url )
157+
158+ return _build_restored_session (checkpoint_id , checkpoint_data , session_id = session_id , label = label )
0 commit comments