Skip to content

Session

🛈 DocStrings

A managed Claude session wrapping a ClaudeSDKClient.

Not constructed directly — use SessionManager.create_session().

Source code in src/clawd_code_sdk/session.py
class Session:
    """A managed Claude session wrapping a ClaudeSDKClient.

    Not constructed directly — use ``SessionManager.create_session()``.
    """

    def __init__(self, session_id: str, client: ClaudeSDKClient) -> None:
        self._session_id = session_id
        self._client = client
        self._state: SessionState = "created"
        self._turns: list[ConversationTurn] = []
        self._created_at = datetime.now(UTC)
        self._last_activity = self._created_at

    @property
    def session_id(self) -> str:
        return self._session_id

    @property
    def state(self) -> SessionState:
        return self._state

    @property
    def client(self) -> ClaudeSDKClient:
        """Access the underlying client for low-level operations."""
        return self._client

    @property
    def turns(self) -> list[ConversationTurn]:
        """All completed conversation turns in this session."""
        return list(self._turns)

    @property
    def total_cost_usd(self) -> float:
        """Accumulated cost across all turns."""
        return sum(t.cost_usd for t in self._turns if t.cost_usd is not None)

    @property
    def snapshot(self) -> SessionSnapshot:
        """Current metadata snapshot."""
        return SessionSnapshot(
            session_id=self._session_id,
            state=self._state,
            model=self._client.options.model,
            cwd=str(self._client.options.cwd) if self._client.options.cwd else None,
            created_at=self._created_at,
            last_activity=self._last_activity,
            turn_count=len(self._turns),
            total_cost_usd=self.total_cost_usd,
        )

    async def send(self, prompt: str) -> AsyncIterator[Message]:
        """Send a prompt and stream response messages.

        Combines ``client.query()`` + ``client.receive_response()`` into one call.
        Yields every message including the final ``ResultMessage``, then stops.
        The completed ``ConversationTurn`` is appended to ``self.turns``.

        Raises:
            RuntimeError: If the session is not in IDLE state.
        """
        if self._state != "idle":
            msg = (
                f"Cannot send: session {self._session_id!r} is in state "
                f"{self._state!r}, expected 'idle'"
            )
            raise RuntimeError(msg)

        self._state = "responding"
        self._last_activity = datetime.now(UTC)
        collected: list[Message] = []

        completed = False
        sent = False
        try:
            # Shielded (anyio scopes): once the write starts, the prompt is sent, so
            # `sent` tells whether a turn may be running.
            with anyio.CancelScope(shield=True):
                await self._client.query(prompt)
            sent = True
            async for message in self._client.receive_response():
                collected.append(message)
                if isinstance(message, ResultMessage):
                    # Before the yield: a consumer stopping at the result ends a full turn.
                    completed = True
                    turn = _extract_turn(collected, message)
                    self._turns.append(turn)
                    self._last_activity = datetime.now(UTC)
                yield message
            self._state = "idle"
        except Exception:
            self._state = "error"
            raise
        except BaseException:
            # The consumer broke out (GeneratorExit) or was cancelled: stop the turn
            # if it is still running, so the next send() starts from a quiet session.
            if completed or not sent:
                self._state = "idle"
            else:
                self._state = "error"  # unless the turn is wound down below
                with anyio.CancelScope(shield=True):
                    try:
                        await self._finish_interrupted_turn()
                    except Exception:
                        logger.warning("Could not stop the interrupted turn", exc_info=True)
                    else:
                        self._state = "idle"
            raise

    async def _finish_interrupted_turn(self) -> None:
        """Interrupt the running turn and read it to its end (its result message).

        Otherwise the next ``send()`` would receive the rest of this turn.

        Raises:
            TimeoutError: The turn didn't end within ``INTERRUPT_DRAIN_TIMEOUT``.
        """
        await self._client.interrupt()
        with anyio.fail_after(INTERRUPT_DRAIN_TIMEOUT):
            async for message in self._client.receive_response():
                if isinstance(message, ResultMessage):
                    break

    async def send_and_collect(self, prompt: str) -> ConversationTurn:
        """Send a prompt and return the full collected response.

        Convenience for cases where streaming is not needed.

        Raises:
            RuntimeError: If the session is not in IDLE state or no
                ResultMessage was received.
        """
        last_turn_count = len(self._turns)
        async for _ in self.send(prompt):
            pass
        if len(self._turns) <= last_turn_count:
            msg = "No ResultMessage received — response may have been interrupted"
            raise RuntimeError(msg)
        return self._turns[-1]

    async def interrupt(self) -> None:
        """Send interrupt signal to the current response."""
        await self._client.interrupt()

    async def set_model(self, model: str | None = None) -> None:
        """Change the AI model during conversation."""
        await self._client.set_model(model)

    async def set_permission_mode(
        self, mode: PermissionMode
    ) -> SDKControlSetPermissionModeResponse | None:
        """Change permission mode during conversation (returns the mode now in effect)."""
        return await self._client.set_permission_mode(mode)

    async def set_max_thinking_tokens(self, max_thinking_tokens: int) -> None:
        """Set the maximum number of thinking tokens."""
        await self._client.set_max_thinking_tokens(max_thinking_tokens)

    async def close(self) -> None:
        """Disconnect and release resources. Idempotent."""
        if self._state == "disconnected":
            return
        try:
            await self._client.disconnect()
        finally:
            self._state = "disconnected"

client property

Access the underlying client for low-level operations.

snapshot property

snapshot: SessionSnapshot

Current metadata snapshot.

total_cost_usd property

total_cost_usd: float

Accumulated cost across all turns.

turns property

turns: list[ConversationTurn]

All completed conversation turns in this session.

close async

close() -> None

Disconnect and release resources. Idempotent.

Source code in src/clawd_code_sdk/session.py
async def close(self) -> None:
    """Disconnect and release resources. Idempotent."""
    if self._state == "disconnected":
        return
    try:
        await self._client.disconnect()
    finally:
        self._state = "disconnected"

interrupt async

interrupt() -> None

Send interrupt signal to the current response.

Source code in src/clawd_code_sdk/session.py
async def interrupt(self) -> None:
    """Send interrupt signal to the current response."""
    await self._client.interrupt()

send async

send(prompt: str) -> AsyncIterator[Message]

Send a prompt and stream response messages.

Combines client.query() + client.receive_response() into one call. Yields every message including the final ResultMessage, then stops. The completed ConversationTurn is appended to self.turns.

Raises:

Type Description
RuntimeError

If the session is not in IDLE state.

Source code in src/clawd_code_sdk/session.py
async def send(self, prompt: str) -> AsyncIterator[Message]:
    """Send a prompt and stream response messages.

    Combines ``client.query()`` + ``client.receive_response()`` into one call.
    Yields every message including the final ``ResultMessage``, then stops.
    The completed ``ConversationTurn`` is appended to ``self.turns``.

    Raises:
        RuntimeError: If the session is not in IDLE state.
    """
    if self._state != "idle":
        msg = (
            f"Cannot send: session {self._session_id!r} is in state "
            f"{self._state!r}, expected 'idle'"
        )
        raise RuntimeError(msg)

    self._state = "responding"
    self._last_activity = datetime.now(UTC)
    collected: list[Message] = []

    completed = False
    sent = False
    try:
        # Shielded (anyio scopes): once the write starts, the prompt is sent, so
        # `sent` tells whether a turn may be running.
        with anyio.CancelScope(shield=True):
            await self._client.query(prompt)
        sent = True
        async for message in self._client.receive_response():
            collected.append(message)
            if isinstance(message, ResultMessage):
                # Before the yield: a consumer stopping at the result ends a full turn.
                completed = True
                turn = _extract_turn(collected, message)
                self._turns.append(turn)
                self._last_activity = datetime.now(UTC)
            yield message
        self._state = "idle"
    except Exception:
        self._state = "error"
        raise
    except BaseException:
        # The consumer broke out (GeneratorExit) or was cancelled: stop the turn
        # if it is still running, so the next send() starts from a quiet session.
        if completed or not sent:
            self._state = "idle"
        else:
            self._state = "error"  # unless the turn is wound down below
            with anyio.CancelScope(shield=True):
                try:
                    await self._finish_interrupted_turn()
                except Exception:
                    logger.warning("Could not stop the interrupted turn", exc_info=True)
                else:
                    self._state = "idle"
        raise

send_and_collect async

send_and_collect(prompt: str) -> ConversationTurn

Send a prompt and return the full collected response.

Convenience for cases where streaming is not needed.

Raises:

Type Description
RuntimeError

If the session is not in IDLE state or no ResultMessage was received.

Source code in src/clawd_code_sdk/session.py
async def send_and_collect(self, prompt: str) -> ConversationTurn:
    """Send a prompt and return the full collected response.

    Convenience for cases where streaming is not needed.

    Raises:
        RuntimeError: If the session is not in IDLE state or no
            ResultMessage was received.
    """
    last_turn_count = len(self._turns)
    async for _ in self.send(prompt):
        pass
    if len(self._turns) <= last_turn_count:
        msg = "No ResultMessage received — response may have been interrupted"
        raise RuntimeError(msg)
    return self._turns[-1]

set_max_thinking_tokens async

set_max_thinking_tokens(max_thinking_tokens: int) -> None

Set the maximum number of thinking tokens.

Source code in src/clawd_code_sdk/session.py
async def set_max_thinking_tokens(self, max_thinking_tokens: int) -> None:
    """Set the maximum number of thinking tokens."""
    await self._client.set_max_thinking_tokens(max_thinking_tokens)

set_model async

set_model(model: str | None = None) -> None

Change the AI model during conversation.

Source code in src/clawd_code_sdk/session.py
async def set_model(self, model: str | None = None) -> None:
    """Change the AI model during conversation."""
    await self._client.set_model(model)

set_permission_mode async

set_permission_mode(mode: PermissionMode) -> SDKControlSetPermissionModeResponse | None

Change permission mode during conversation (returns the mode now in effect).

Source code in src/clawd_code_sdk/session.py
async def set_permission_mode(
    self, mode: PermissionMode
) -> SDKControlSetPermissionModeResponse | None:
    """Change permission mode during conversation (returns the mode now in effect)."""
    return await self._client.set_permission_mode(mode)

:fa-brands-github: Show source on GitHub