Skip to content

Feature: Add higher-level session management APIs #458

@jsham042

Description

@jsham042

Problem

Session management in the SDK is not intuitive. The SDK is a thin wrapper around the CLI, delegating session lifecycle to it, which makes session management opaque for SDK users.

Current State

The SDK provides:

  1. Session ID in results - ResultMessage.session_id and StreamEvent.session_id
  2. Resume sessions - resume: str option
  3. Continue last session - continue_conversation: bool
  4. Fork sessions - fork_session: bool
  5. File checkpointing - enable_file_checkpointing + rewind_files()

Issues

  1. Session IDs must be provided or discovered after the fact - No auto-generation with immediate return of the ID
  2. Unclear storage location - Where session data is stored and how to access it is undocumented
  3. Session only "exists" after first message - You don't know if a session is valid until after sending a message
  4. No session listing - Cannot query existing sessions

Workaround

Implement custom session management:

class Session:
    """
    Structure:
        sessions/<session_id>/
        ├── .claude/          # Symlink to project's .claude/ (for skills)
        ├── messages.jsonl    # Full message history
        ├── metadata.json     # Session stats (turns, tokens, cost)
        └── sandbox/          # Agent's file workspace
    """

    def __init__(self, session_id: str, root_dir: Path, project_root: Path):
        self.session_id = session_id
        # ... manual setup

    def exists(self) -> bool:
        return self.messages_file.exists()

    def create(self) -> None:
        self.path.mkdir(parents=True, exist_ok=True)
        # ... manual directory structure creation

Proposed Solution

Add session lifecycle APIs:

# Option 1: Auto-generate session ID
async with ClaudeSDKClient() as client:
    session = await client.create_session()  # Returns Session object
    print(session.id)       # "abc-123-def" (auto-generated)
    print(session.path)     # Where data is stored
    print(session.exists)   # True

# Option 2: Explicit with validation
session = await client.get_or_create_session("my-session-id")

# Session listing
sessions = await client.list_sessions()
for s in sessions:
    print(f"{s.id}: {s.num_turns} turns, ${s.total_cost_usd:.4f}")

# Session object with useful properties
session.messages      # Access to history
session.metadata      # Stats, timestamps
session.transcript    # Path to transcript file

Additional Suggestions

  1. Document session storage - Where the CLI stores sessions, what format
  2. Session metadata access - Expose turn count, cost, timestamps before querying
  3. Session cleanup APIs - Delete old sessions, prune by age/size

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions