Skip to content

SessionManager

🛈 DocStrings

Manages multiple concurrent Claude SDK sessions.

Usage::

async with SessionManager() as manager:
    s1 = await manager.create_session("coding", options=opts)
    turn = await s1.send_and_collect("Explain this codebase")
    print(turn.text)

    s2 = await manager.create_session("review", options=opts, prompt="Review my PR")
    async for msg in s2.send("What issues did you find?"):
        ...
Source code in src/clawd_code_sdk/session.py
class SessionManager:
    """Manages multiple concurrent Claude SDK sessions.

    Usage::

        async with SessionManager() as manager:
            s1 = await manager.create_session("coding", options=opts)
            turn = await s1.send_and_collect("Explain this codebase")
            print(turn.text)

            s2 = await manager.create_session("review", options=opts, prompt="Review my PR")
            async for msg in s2.send("What issues did you find?"):
                ...
    """

    def __init__(self, *, max_concurrent_sessions: int | None = None) -> None:
        """Initialize the session manager.

        Args:
            max_concurrent_sessions: Optional cap on simultaneous connected
                sessions. ``create_session`` raises if exceeded.
        """
        self._sessions: dict[str, Session] = {}
        self._max_concurrent_sessions = max_concurrent_sessions

    # ── Session lifecycle ────────────────────────────────────────

    async def create_session(
        self,
        session_id: str | None = None,
        *,
        options: ClaudeAgentOptions | None = None,
        transport: Transport | None = None,
        prompt: str | None = None,
        connect: bool = True,
    ) -> Session:
        """Create and optionally connect a new session.

        Args:
            session_id: Explicit ID, or auto-generated UUID if None.
            options: Session-specific options.
            transport: Optional custom transport.
            prompt: If provided, sent as the initial prompt on connect.
            connect: If True (default), connect immediately.

        Raises:
            ValueError: If session_id already exists.
            RuntimeError: If max_concurrent_sessions would be exceeded.
        """
        sid = session_id or uuid.uuid4().hex
        if sid in self._sessions:
            msg = f"Session {sid!r} already exists"
            raise ValueError(msg)

        if self._max_concurrent_sessions is not None:
            active_count = sum(
                1
                for s in self._sessions.values()
                if s.state in ("idle", "responding", "connecting")
            )
            if active_count >= self._max_concurrent_sessions:
                msg = f"Maximum concurrent sessions ({self._max_concurrent_sessions}) reached"
                raise RuntimeError(msg)

        client = ClaudeSDKClient(options=options, transport=transport)
        session = Session(sid, client)
        self._sessions[sid] = session

        if connect:
            session._state = "connecting"
            try:
                await client.connect()
                if prompt:
                    await client.query(prompt)
                session._state = "idle"
                session._last_activity = datetime.now(UTC)
            except Exception:
                session._state = "error"
                raise

        return session

    async def resume_session(
        self,
        session_id: str,
        *,
        options: ClaudeAgentOptions | None = None,
        transport: Transport | None = None,
    ) -> Session:
        """Resume a previously persisted session by ID.

        Sets ``session`` to a :class:`ResumeSession` config on the options,
        then connects.

        Args:
            session_id: The session ID to resume.
            options: Session-specific options (``session`` is set automatically).
            transport: Optional custom transport.

        Raises:
            ValueError: If session_id already exists in this manager.
        """
        from clawd_code_sdk.models.options import ResumeSession

        base = options or Opts()
        merged = replace(base, session=ResumeSession(session_id=session_id))
        return await self.create_session(
            session_id=session_id,
            options=merged,
            transport=transport,
        )

    # ── Session access ───────────────────────────────────────────

    def get_session(self, session_id: str) -> Session:
        """Get a session by ID.

        Raises:
            KeyError: If session_id not found.
        """
        try:
            return self._sessions[session_id]
        except KeyError:
            msg = f"Session {session_id!r} not found"
            raise KeyError(msg) from None

    def __getitem__(self, session_id: str) -> Session:
        """Alias for ``get_session()``."""
        return self.get_session(session_id)

    def __contains__(self, session_id: str) -> bool:
        return session_id in self._sessions

    def __len__(self) -> int:
        return len(self._sessions)

    def __iter__(self) -> Iterator[str]:
        """Iterate over session IDs."""
        return iter(self._sessions)

    @property
    def sessions(self) -> dict[str, Session]:
        """All sessions (any state). Returns a copy."""
        return dict(self._sessions)

    @property
    def active_sessions(self) -> dict[str, Session]:
        """Sessions in IDLE or RESPONDING state."""
        return {sid: s for sid, s in self._sessions.items() if s.state in ("idle", "responding")}

    # ── Cleanup ──────────────────────────────────────────────────

    async def close_session(self, session_id: str) -> None:
        """Close and remove a specific session.

        Raises:
            KeyError: If session_id not found.
        """
        session = self.get_session(session_id)
        await session.close()
        del self._sessions[session_id]

    async def close_all(self) -> None:
        """Close all sessions, concurrently. Errors during individual closes are suppressed."""
        sessions = list(self._sessions.values())
        await asyncio.gather(*(s.close() for s in sessions), return_exceptions=True)
        self._sessions.clear()

    # ── Aggregate stats ──────────────────────────────────────────

    @property
    def total_cost_usd(self) -> float:
        """Sum of costs across all sessions."""
        return sum(s.total_cost_usd for s in self._sessions.values())

    def snapshots(self) -> dict[str, SessionSnapshot]:
        """Snapshots of all sessions."""
        return {sid: s.snapshot for sid, s in self._sessions.items()}

    # ── Context manager ──────────────────────────────────────────

    async def __aenter__(self) -> Self:
        return self

    async def __aexit__(self, *args: object) -> None:
        await self.close_all()

active_sessions property

active_sessions: dict[str, Session]

Sessions in IDLE or RESPONDING state.

sessions property

sessions: dict[str, Session]

All sessions (any state). Returns a copy.

total_cost_usd property

total_cost_usd: float

Sum of costs across all sessions.

__getitem__

__getitem__(session_id: str) -> Session

Alias for get_session().

Source code in src/clawd_code_sdk/session.py
def __getitem__(self, session_id: str) -> Session:
    """Alias for ``get_session()``."""
    return self.get_session(session_id)

__init__

__init__(*, max_concurrent_sessions: int | None = None) -> None

Initialize the session manager.

Parameters:

Name Type Description Default
max_concurrent_sessions int | None

Optional cap on simultaneous connected sessions. create_session raises if exceeded.

None
Source code in src/clawd_code_sdk/session.py
def __init__(self, *, max_concurrent_sessions: int | None = None) -> None:
    """Initialize the session manager.

    Args:
        max_concurrent_sessions: Optional cap on simultaneous connected
            sessions. ``create_session`` raises if exceeded.
    """
    self._sessions: dict[str, Session] = {}
    self._max_concurrent_sessions = max_concurrent_sessions

__iter__

__iter__() -> Iterator[str]

Iterate over session IDs.

Source code in src/clawd_code_sdk/session.py
def __iter__(self) -> Iterator[str]:
    """Iterate over session IDs."""
    return iter(self._sessions)

close_all async

close_all() -> None

Close all sessions, concurrently. Errors during individual closes are suppressed.

Source code in src/clawd_code_sdk/session.py
async def close_all(self) -> None:
    """Close all sessions, concurrently. Errors during individual closes are suppressed."""
    sessions = list(self._sessions.values())
    await asyncio.gather(*(s.close() for s in sessions), return_exceptions=True)
    self._sessions.clear()

close_session async

close_session(session_id: str) -> None

Close and remove a specific session.

Raises:

Type Description
KeyError

If session_id not found.

Source code in src/clawd_code_sdk/session.py
async def close_session(self, session_id: str) -> None:
    """Close and remove a specific session.

    Raises:
        KeyError: If session_id not found.
    """
    session = self.get_session(session_id)
    await session.close()
    del self._sessions[session_id]

create_session async

create_session(
    session_id: str | None = None,
    *,
    options: ClaudeAgentOptions | None = None,
    transport: Transport | None = None,
    prompt: str | None = None,
    connect: bool = True,
) -> Session

Create and optionally connect a new session.

Parameters:

Name Type Description Default
session_id str | None

Explicit ID, or auto-generated UUID if None.

None
options ClaudeAgentOptions | None

Session-specific options.

None
transport Transport | None

Optional custom transport.

None
prompt str | None

If provided, sent as the initial prompt on connect.

None
connect bool

If True (default), connect immediately.

True

Raises:

Type Description
ValueError

If session_id already exists.

RuntimeError

If max_concurrent_sessions would be exceeded.

Source code in src/clawd_code_sdk/session.py
async def create_session(
    self,
    session_id: str | None = None,
    *,
    options: ClaudeAgentOptions | None = None,
    transport: Transport | None = None,
    prompt: str | None = None,
    connect: bool = True,
) -> Session:
    """Create and optionally connect a new session.

    Args:
        session_id: Explicit ID, or auto-generated UUID if None.
        options: Session-specific options.
        transport: Optional custom transport.
        prompt: If provided, sent as the initial prompt on connect.
        connect: If True (default), connect immediately.

    Raises:
        ValueError: If session_id already exists.
        RuntimeError: If max_concurrent_sessions would be exceeded.
    """
    sid = session_id or uuid.uuid4().hex
    if sid in self._sessions:
        msg = f"Session {sid!r} already exists"
        raise ValueError(msg)

    if self._max_concurrent_sessions is not None:
        active_count = sum(
            1
            for s in self._sessions.values()
            if s.state in ("idle", "responding", "connecting")
        )
        if active_count >= self._max_concurrent_sessions:
            msg = f"Maximum concurrent sessions ({self._max_concurrent_sessions}) reached"
            raise RuntimeError(msg)

    client = ClaudeSDKClient(options=options, transport=transport)
    session = Session(sid, client)
    self._sessions[sid] = session

    if connect:
        session._state = "connecting"
        try:
            await client.connect()
            if prompt:
                await client.query(prompt)
            session._state = "idle"
            session._last_activity = datetime.now(UTC)
        except Exception:
            session._state = "error"
            raise

    return session

get_session

get_session(session_id: str) -> Session

Get a session by ID.

Raises:

Type Description
KeyError

If session_id not found.

Source code in src/clawd_code_sdk/session.py
def get_session(self, session_id: str) -> Session:
    """Get a session by ID.

    Raises:
        KeyError: If session_id not found.
    """
    try:
        return self._sessions[session_id]
    except KeyError:
        msg = f"Session {session_id!r} not found"
        raise KeyError(msg) from None

resume_session async

resume_session(
    session_id: str,
    *,
    options: ClaudeAgentOptions | None = None,
    transport: Transport | None = None,
) -> Session

Resume a previously persisted session by ID.

Sets session to a :class:ResumeSession config on the options, then connects.

Parameters:

Name Type Description Default
session_id str

The session ID to resume.

required
options ClaudeAgentOptions | None

Session-specific options (session is set automatically).

None
transport Transport | None

Optional custom transport.

None

Raises:

Type Description
ValueError

If session_id already exists in this manager.

Source code in src/clawd_code_sdk/session.py
async def resume_session(
    self,
    session_id: str,
    *,
    options: ClaudeAgentOptions | None = None,
    transport: Transport | None = None,
) -> Session:
    """Resume a previously persisted session by ID.

    Sets ``session`` to a :class:`ResumeSession` config on the options,
    then connects.

    Args:
        session_id: The session ID to resume.
        options: Session-specific options (``session`` is set automatically).
        transport: Optional custom transport.

    Raises:
        ValueError: If session_id already exists in this manager.
    """
    from clawd_code_sdk.models.options import ResumeSession

    base = options or Opts()
    merged = replace(base, session=ResumeSession(session_id=session_id))
    return await self.create_session(
        session_id=session_id,
        options=merged,
        transport=transport,
    )

snapshots

snapshots() -> dict[str, SessionSnapshot]

Snapshots of all sessions.

Source code in src/clawd_code_sdk/session.py
def snapshots(self) -> dict[str, SessionSnapshot]:
    """Snapshots of all sessions."""
    return {sid: s.snapshot for sid, s in self._sessions.items()}

:fa-brands-github: Show source on GitHub