Skip to content

replay

Class info

🛈 DocStrings

Replay Claude Code sessions from stored JSONL transcripts.

Reassembles stored JSONL entries into SDK Message types, enabling consumers to process historical sessions with the same code that handles live streams. Storage and wire formats share the same content block types, so no conversion is needed at the block level.

The storage format saves one entry per content block, chained via parentUuid. This module preserves that granularity: each stored assistant entry becomes one AssistantMessage with a single content block, matching the live wire behavior (where --include-partial-messages yields one AssistantMessage per content block as it completes).

When include_stream_events=True, synthetic StreamEvent messages are injected around each content block to reproduce the structural envelope of a live stream. Each text/thinking block gets a single delta containing the full content (since token-level deltas are not preserved in storage).

Not reconstructible from storage
  • Token-level streaming granularity (deltas are synthetic, one per block).
  • InitSystemMessage(init): Session initialization metadata (tools, model, etc.).
  • RateLimitMessage: Rate limit events are transient.

Partially reconstructible (with include_result=True): - ResultMessage: Synthetic messages are emitted at each turn boundary. Token usage (deduplicated) and error status are available. Cost (total_cost_usd), duration (duration_ms, duration_api_ms), and model_usage are not stored and are set to zero/None.

Example::

from pathlib import Path
from clawd_code_sdk.models.content_blocks import TextBlock, ToolUseBlock
from clawd_code_sdk.models.messages import AssistantMessage, StreamEvent, UserMessage
from clawd_code_sdk.storage.replay import replay_session

for message in replay_session(
    Path("~/.claude/projects/-proj/session.jsonl"),
    include_stream_events=True,
):
    match message:
        case StreamEvent(event=event) if event.type == "content_block_delta":
            delta = event.delta
            if hasattr(delta, "text"):
                print(delta.text, end="", flush=True)
        case AssistantMessage(content=blocks):
            pass  # Already handled via deltas
        case UserMessage(content=str() as text):
            print(f"User: {text}")

replay_entries

replay_entries(
    entries: Iterable[ClaudeJSONLEntry],
    *,
    include_progress: bool = False,
    include_stream_events: bool = False,
    include_summaries: bool = False,
    include_result: bool = False,
    exclude_sidechains: bool = False,
    leaf_uuid: str | None = None,
) -> Iterator[Message]

Replay stored JSONL entries as wire-format Messages.

Yields UserMessage and AssistantMessage in file order, preserving the one-entry-per-content-block granularity of the storage format.

Parameters:

Name Type Description Default
entries Iterable[ClaudeJSONLEntry]

JSONL entries to replay (from read_session or similar).

required
include_progress bool

If True, also yield ToolProgressMessage for tool_progress entries.

False
include_stream_events bool

If True, inject synthetic StreamEvent messages (message_start/stop, content_block_start/delta/stop) around each content block. Each text/thinking block gets a single delta with the full content. Useful for consumers that expect the full stream envelope structure.

False
include_summaries bool

If True, yield summary entries as synthetic UserMessage instances (with isSynthetic=True) at their file-order position.

False
include_result bool

If True, emit a synthetic ResultMessage at the end of each conversational turn. The synthetic message includes deduplicated token usage and error status from storage. Fields not available in storage (total_cost_usd, duration_ms, duration_api_ms) are set to zero/None.

False
exclude_sidechains bool

If True, skip entries marked as sidechain (internal Claude Code context-retrieval calls).

False
leaf_uuid str | None

If set, resolve the conversation thread by walking parent_uuid chains from this leaf to the root (through attachment and system entries, recovering parallel tool calls; see :func:~clawd_code_sdk.storage.chain.resolve_chain). Only entries on that chain are replayed. If None, file order is used.

None

Yields:

Type Description
Message

Wire-format Message objects (UserMessage, AssistantMessage,

Message

StreamEvent, ResultMessage, and optionally ToolProgressMessage).

Source code in src/clawd_code_sdk/storage/replay.py
def replay_entries(
    entries: Iterable[ClaudeJSONLEntry],
    *,
    include_progress: bool = False,
    include_stream_events: bool = False,
    include_summaries: bool = False,
    include_result: bool = False,
    exclude_sidechains: bool = False,
    leaf_uuid: str | None = None,
) -> Iterator[Message]:
    """Replay stored JSONL entries as wire-format Messages.

    Yields UserMessage and AssistantMessage in file order, preserving
    the one-entry-per-content-block granularity of the storage format.

    Args:
        entries: JSONL entries to replay (from read_session or similar).
        include_progress: If True, also yield ToolProgressMessage for
            tool_progress entries.
        include_stream_events: If True, inject synthetic StreamEvent
            messages (message_start/stop, content_block_start/delta/stop)
            around each content block. Each text/thinking block gets a
            single delta with the full content. Useful for consumers that
            expect the full stream envelope structure.
        include_summaries: If True, yield summary entries as synthetic
            UserMessage instances (with ``isSynthetic=True``) at their
            file-order position.
        include_result: If True, emit a synthetic ``ResultMessage`` at
            the end of each conversational turn. The synthetic message
            includes deduplicated token usage and error status from
            storage. Fields not available in storage (``total_cost_usd``,
            ``duration_ms``, ``duration_api_ms``) are set to zero/None.
        exclude_sidechains: If True, skip entries marked as sidechain
            (internal Claude Code context-retrieval calls).
        leaf_uuid: If set, resolve the conversation thread by walking
            parent_uuid chains from this leaf to the root (through attachment
            and system entries, recovering parallel tool calls; see
            :func:`~clawd_code_sdk.storage.chain.resolve_chain`). Only entries
            on that chain are replayed. If None, file order is used.

    Yields:
        Wire-format Message objects (UserMessage, AssistantMessage,
        StreamEvent, ResultMessage, and optionally ToolProgressMessage).
    """
    if leaf_uuid is not None:
        entries = resolve_chain(entries, leaf_uuid=leaf_uuid)
    if exclude_sidechains:
        entries = _filter_sidechains(entries)
    if include_stream_events:
        yield from _replay_with_stream_events(
            entries,
            include_progress=include_progress,
            include_summaries=include_summaries,
            include_result=include_result,
        )
    else:
        yield from _replay_basic(
            entries,
            include_progress=include_progress,
            include_summaries=include_summaries,
            include_result=include_result,
        )

replay_session

replay_session(
    session_path: Path,
    *,
    include_progress: bool = False,
    include_stream_events: bool = False,
    include_summaries: bool = False,
    include_result: bool = False,
    exclude_sidechains: bool = False,
    leaf_uuid: str | None = None,
) -> Iterator[Message]

Replay a stored session file as wire-format Messages.

Reads a JSONL session file and yields its entries converted to wire-format Message objects. The sequence matches what a live receive_messages() call would produce, minus token-level deltas and terminal events (RateLimitMessage). When include_result=True, a synthetic ResultMessage is emitted at each turn boundary with whatever data is available in storage.

Parameters:

Name Type Description Default
session_path Path

Path to the .jsonl session file.

required
include_progress bool

If True, also yield ToolProgressMessage entries.

False
include_stream_events bool

If True, inject synthetic StreamEvent messages around each content block (see :func:replay_entries).

False
include_summaries bool

If True, include summary entries.

False
include_result bool

If True, emit synthetic ResultMessage at each turn boundary (see :func:replay_entries).

False
exclude_sidechains bool

If True, skip sidechain entries.

False
leaf_uuid str | None

If set, resolve the thread from this leaf UUID.

None

Yields:

Type Description
Message

Wire-format Message objects in conversation order.

Source code in src/clawd_code_sdk/storage/replay.py
def replay_session(
    session_path: Path,
    *,
    include_progress: bool = False,
    include_stream_events: bool = False,
    include_summaries: bool = False,
    include_result: bool = False,
    exclude_sidechains: bool = False,
    leaf_uuid: str | None = None,
) -> Iterator[Message]:
    """Replay a stored session file as wire-format Messages.

    Reads a JSONL session file and yields its entries converted to
    wire-format Message objects. The sequence matches what a live
    ``receive_messages()`` call would produce, minus token-level deltas
    and terminal events (RateLimitMessage). When ``include_result=True``,
    a synthetic ``ResultMessage`` is emitted at each turn boundary with
    whatever data is available in storage.

    Args:
        session_path: Path to the .jsonl session file.
        include_progress: If True, also yield ToolProgressMessage entries.
        include_stream_events: If True, inject synthetic StreamEvent
            messages around each content block (see :func:`replay_entries`).
        include_summaries: If True, include summary entries.
        include_result: If True, emit synthetic ResultMessage at each
            turn boundary (see :func:`replay_entries`).
        exclude_sidechains: If True, skip sidechain entries.
        leaf_uuid: If set, resolve the thread from this leaf UUID.

    Yields:
        Wire-format Message objects in conversation order.
    """
    entries = read_session(session_path)
    yield from replay_entries(
        entries,
        include_progress=include_progress,
        include_stream_events=include_stream_events,
        include_summaries=include_summaries,
        include_result=include_result,
        exclude_sidechains=exclude_sidechains,
        leaf_uuid=leaf_uuid,
    )