Session Management
The Claude Code SDK provides session management capabilities for handling conversation state, persistence, and resumption. This guide covers how sessions are created, managed, persisted to files, and resumed within the SDK.Session Architecture
The Claude Code SDK implements a file-based session management system that handles conversation persistence and state restoration.Session File Structure
Sessions are persisted to the local filesystem in a structured format:Session Metadata Format
Thesessions.json
file stores metadata about all sessions:
Session Transcript Format
Session transcripts are stored as JSONL (JSON Lines) files, with each line representing a message or event:- User messages: Input from the user
- Assistant messages: Responses from Claude
- Checkpoints: Saved states in the conversation (e.g., after completing a task)
- Tool use: Records of when tools were invoked and their results
Session Lifecycle
Creation and Initialization
When a session starts, the SDK performs several initialization steps:- Generate Session ID: Creates a unique identifier for the session
- Create Project Directory: Sets up the project-specific storage location
- Initialize Transcript File: Creates an empty JSONL file for the conversation
- Store Initial Metadata: Records session creation time and configuration
Getting the Session ID
The session ID is provided in the initial system message when you start a conversation. You can capture it for later use:Session State Persistence
The SDK automatically persists session state to disk:- After each message exchange: The transcript is updated
- On tool invocations: Tool use and results are recorded
- At checkpoints: Important conversation states are marked
- On session end: Final state is saved