|
3 | 3 | import inspect |
4 | 4 | import logging |
5 | 5 | import sys |
6 | | -from collections.abc import Awaitable, Callable |
| 6 | +from collections.abc import Awaitable, Callable, Mapping |
7 | 7 | from dataclasses import dataclass |
8 | 8 | from typing import Any, Literal, cast |
9 | 9 |
|
10 | | -from typing_extensions import Never |
| 10 | +from typing_extensions import Never, NotRequired, TypedDict |
11 | 11 |
|
12 | 12 | from agent_framework import Content |
13 | 13 |
|
14 | 14 | from .._agents import SupportsAgentRun |
15 | 15 | from .._sessions import AgentSession |
16 | 16 | from .._types import AgentResponse, AgentResponseUpdate, Message, ResponseStream |
| 17 | +from ..exceptions import WorkflowCheckpointException |
17 | 18 | from ._agent_utils import prepare_agent_run_args, resolve_agent_id, resolve_executor_kwargs |
18 | 19 | from ._const import INTERNAL_SOURCE_ID, WORKFLOW_RUN_KWARGS_KEY |
19 | 20 | from ._executor import Executor, handler |
|
30 | 31 | logger = logging.getLogger(__name__) |
31 | 32 |
|
32 | 33 |
|
| 34 | +class AgentSessionCheckpointState(TypedDict): |
| 35 | + """Serialized :class:`~agent_framework.AgentSession` payload (``AgentSession.to_dict()``). |
| 36 | +
|
| 37 | + ``state`` holds session-local data. When the session uses service-side storage, |
| 38 | + local ``state`` may be incomplete relative to the remote conversation. |
| 39 | + """ |
| 40 | + |
| 41 | + type: NotRequired[str] |
| 42 | + session_id: str |
| 43 | + service_session_id: NotRequired[str | None] |
| 44 | + state: NotRequired[dict[str, Any]] |
| 45 | + |
| 46 | + |
| 47 | +class AgentExecutorCheckpointState(TypedDict, total=False): |
| 48 | + """Public schema for state saved and restored by :class:`AgentExecutor`. |
| 49 | +
|
| 50 | + Stored under ``WorkflowCheckpoint.state["_executor_state"][executor_id]``. |
| 51 | +
|
| 52 | + ``on_checkpoint_save`` always writes every key below. Restore accepts partial |
| 53 | + mappings for backward compatibility: missing keys reset to empty defaults. |
| 54 | + Unknown keys are ignored so newer writers remain readable by older runtimes. |
| 55 | +
|
| 56 | + Compatibility: |
| 57 | + - Add fields as ``total=False`` / ``NotRequired`` and treat absence as default. |
| 58 | + - Do not rename or change the meaning of existing keys without a migration path. |
| 59 | + - Custom executors should define their own TypedDict (or equivalent) and validate |
| 60 | + types in ``on_checkpoint_restore``; prefer |
| 61 | + :class:`~agent_framework.exceptions.WorkflowCheckpointException` for malformed data. |
| 62 | +
|
| 63 | + Keys: |
| 64 | + cache: Messages buffered between runs before the next agent invocation. |
| 65 | + full_conversation: Prior inputs plus assistant/tool outputs after the last run. |
| 66 | + agent_session: Serialized session payload (:class:`AgentSessionCheckpointState`). |
| 67 | + pending_agent_requests: In-flight agent-owned user-input requests by request id. |
| 68 | + pending_responses_to_agent: Queued content responses waiting to be sent to the agent. |
| 69 | + """ |
| 70 | + |
| 71 | + cache: list[Message] |
| 72 | + full_conversation: list[Message] |
| 73 | + agent_session: AgentSessionCheckpointState |
| 74 | + pending_agent_requests: dict[str, Content] |
| 75 | + pending_responses_to_agent: list[Content] |
| 76 | + |
| 77 | + |
| 78 | +def _validate_agent_executor_checkpoint_state(state: Mapping[str, Any]) -> None: |
| 79 | + """Raise :class:`WorkflowCheckpointException` when checkpoint payload types are wrong.""" |
| 80 | + if not isinstance(state, Mapping): |
| 81 | + raise WorkflowCheckpointException( |
| 82 | + f"AgentExecutor checkpoint state must be a mapping, got {type(state).__name__}." |
| 83 | + ) |
| 84 | + |
| 85 | + list_keys = ("cache", "full_conversation", "pending_responses_to_agent") |
| 86 | + for key in list_keys: |
| 87 | + if key in state and state[key] is not None and not isinstance(state[key], list): |
| 88 | + raise WorkflowCheckpointException( |
| 89 | + f"AgentExecutor checkpoint field '{key}' must be a list, got {type(state[key]).__name__}." |
| 90 | + ) |
| 91 | + |
| 92 | + if "pending_agent_requests" in state and state["pending_agent_requests"] is not None: |
| 93 | + if not isinstance(state["pending_agent_requests"], dict): |
| 94 | + raise WorkflowCheckpointException( |
| 95 | + "AgentExecutor checkpoint field 'pending_agent_requests' must be a dict, " |
| 96 | + f"got {type(state['pending_agent_requests']).__name__}." |
| 97 | + ) |
| 98 | + |
| 99 | + if "agent_session" in state and state["agent_session"] is not None: |
| 100 | + if not isinstance(state["agent_session"], dict): |
| 101 | + raise WorkflowCheckpointException( |
| 102 | + "AgentExecutor checkpoint field 'agent_session' must be a dict, " |
| 103 | + f"got {type(state['agent_session']).__name__}." |
| 104 | + ) |
| 105 | + |
| 106 | + |
33 | 107 | def _accepts_runtime_tools(agent: SupportsAgentRun) -> bool: |
34 | 108 | """Return whether the agent run surface accepts a tools keyword.""" |
35 | 109 | try: |
@@ -347,32 +421,41 @@ async def _cancel_pending_request( |
347 | 421 | await self._resume_with_pending_responses(ctx) |
348 | 422 |
|
349 | 423 | @override |
350 | | - async def on_checkpoint_save(self) -> dict[str, Any]: |
| 424 | + async def on_checkpoint_save(self) -> AgentExecutorCheckpointState: |
351 | 425 | """Capture current executor state for checkpointing. |
352 | 426 |
|
353 | 427 | NOTE: if the session uses service-side storage, the full session state |
354 | 428 | may not be serialized locally. |
355 | 429 |
|
356 | 430 | Returns: |
357 | | - Dict containing serialized cache and session state |
| 431 | + :class:`AgentExecutorCheckpointState` with cache, conversation, session, |
| 432 | + and pending request/response fields. |
358 | 433 | """ |
359 | 434 | serialized_session = self._session.to_dict() |
360 | 435 |
|
361 | | - return { |
362 | | - "cache": self._cache, |
363 | | - "full_conversation": self._full_conversation, |
364 | | - "agent_session": serialized_session, |
365 | | - "pending_agent_requests": self._pending_agent_requests, |
366 | | - "pending_responses_to_agent": self._pending_responses_to_agent, |
367 | | - } |
| 436 | + return AgentExecutorCheckpointState( |
| 437 | + cache=self._cache, |
| 438 | + full_conversation=self._full_conversation, |
| 439 | + agent_session=serialized_session, |
| 440 | + pending_agent_requests=self._pending_agent_requests, |
| 441 | + pending_responses_to_agent=self._pending_responses_to_agent, |
| 442 | + ) |
368 | 443 |
|
369 | 444 | @override |
370 | | - async def on_checkpoint_restore(self, state: dict[str, Any]) -> None: |
| 445 | + async def on_checkpoint_restore(self, state: AgentExecutorCheckpointState | dict[str, Any]) -> None: |
371 | 446 | """Restore executor state from checkpoint. |
372 | 447 |
|
373 | 448 | Args: |
374 | | - state: Checkpoint data dict |
| 449 | + state: Checkpoint payload matching :class:`AgentExecutorCheckpointState` |
| 450 | + (or a compatible mapping). Missing known keys use empty defaults; |
| 451 | + unknown keys are ignored. |
| 452 | +
|
| 453 | + Raises: |
| 454 | + WorkflowCheckpointException: If ``state`` is not a mapping or a known |
| 455 | + field has an incompatible type. |
375 | 456 | """ |
| 457 | + _validate_agent_executor_checkpoint_state(state) |
| 458 | + |
376 | 459 | cache_payload = state.get("cache") |
377 | 460 | self._cache = cache_payload or [] |
378 | 461 |
|
|
0 commit comments