Skip to content

helpers

Class info

🛈 DocStrings

Claude Code storage provider.

See ARCHITECTURE.md for detailed documentation of the storage format.

count_session_messages

count_session_messages(session_path: Path) -> int

Count user/assistant messages in a session without full validation.

Only parses JSON to check the 'type' field, skipping Pydantic validation.

Parameters:

Name Type Description Default
session_path Path

Path to the JSONL session file

required

Returns:

Type Description
int

Number of user/assistant message entries

Source code in src/clawd_code_sdk/storage/helpers.py
def count_session_messages(session_path: Path) -> int:
    """Count user/assistant messages in a session without full validation.

    Only parses JSON to check the 'type' field, skipping Pydantic validation.

    Args:
        session_path: Path to the JSONL session file

    Returns:
        Number of user/assistant message entries
    """
    count = 0
    with session_path.open("r", encoding="utf-8") as f:
        for line in f:
            stripped = line.strip()
            if not stripped:
                continue
            try:
                data = anyenv.load_json(stripped, return_type=dict)
                if data.get("type") in ("user", "assistant"):
                    count += 1
            except anyenv.JsonLoadError:
                pass
    return count

decode_project_path

decode_project_path(encoded: str) -> str

Decode a Claude project path back to filesystem path (best effort).

The encoding is lossy ('-', '.', '_' and '/' all become '-'), so this is only a guess; prefer the cwd recorded in the session's entries.

Example: -home-user-project -> /home/user/project

Source code in src/clawd_code_sdk/storage/helpers.py
def decode_project_path(encoded: str) -> str:
    """Decode a Claude project path back to filesystem path (best effort).

    The encoding is lossy ('-', '.', '_' and '/' all become '-'), so this is only
    a guess; prefer the ``cwd`` recorded in the session's entries.

    Example: -home-user-project -> /home/user/project
    """
    encoded = encoded.removeprefix("-")
    return "/" + encoded.replace("-", "/")

encode_project_path

encode_project_path(path: str) -> str

Encode a project path to Claude's format (see :func:path_to_claude_dir_name).

Example: /home/user/.config/project -> -home-user--config-project

Source code in src/clawd_code_sdk/storage/helpers.py
def encode_project_path(path: str) -> str:
    """Encode a project path to Claude's format (see :func:`path_to_claude_dir_name`).

    Example: /home/user/.config/project -> -home-user--config-project
    """
    return path_to_claude_dir_name(path)

extract_title

extract_title(session_path: Path, max_chars: int = 60) -> str | None

Extract a display title from a session file without parsing all of it.

Reads only the head and tail of the file. Preference order: the last user-set title (custom-title), the last AI-generated title (ai-title), a legacy summary entry, then the first meaningful user prompt.

Parameters:

Name Type Description Default
session_path Path

Path to the JSONL session file

required
max_chars int

Maximum characters for title (truncates with '...')

60

Returns:

Type Description
str | None

Extracted title or None if no suitable content found

Source code in src/clawd_code_sdk/storage/helpers.py
def extract_title(session_path: Path, max_chars: int = 60) -> str | None:
    """Extract a display title from a session file without parsing all of it.

    Reads only the head and tail of the file. Preference order: the last
    user-set title (``custom-title``), the last AI-generated title
    (``ai-title``), a legacy ``summary`` entry, then the first meaningful
    user prompt.

    Args:
        session_path: Path to the JSONL session file
        max_chars: Maximum characters for title (truncates with '...')

    Returns:
        Extracted title or None if no suitable content found
    """
    from clawd_code_sdk._internal.sessions import (
        _extract_first_prompt_from_head,
        _extract_last_json_string_field,
        _read_session_lite,
    )

    lite = _read_session_lite(session_path)
    if lite is None:
        return None
    head, tail = lite.head, lite.tail
    # Only legacy summary entries: other entry types carry a "summary" key too.
    summary_line = next((ln for ln in head.split("\n") if ln.startswith('{"type":"summary"')), "")
    title = (
        _extract_last_json_string_field(tail, "customTitle")
        or _extract_last_json_string_field(head, "customTitle")
        or _extract_last_json_string_field(tail, "aiTitle")
        or _extract_last_json_string_field(head, "aiTitle")
        or _extract_last_json_string_field(summary_line, "summary")
        or _extract_first_prompt_from_head(head).split("\n")[0].strip()
    )
    if not title:
        return None
    return title[:max_chars] + "..." if len(title) > max_chars else title

get_claude_data_dir

get_claude_data_dir() -> Path

Get the Claude Code data directory ($CLAUDE_CONFIG_DIR, default ~/.claude).

Source code in src/clawd_code_sdk/storage/helpers.py
def get_claude_data_dir() -> Path:
    """Get the Claude Code data directory (``$CLAUDE_CONFIG_DIR``, default ``~/.claude``)."""
    from clawd_code_sdk._internal.sessions import _get_claude_config_home_dir

    return _get_claude_config_home_dir()

get_claude_projects_dir

get_claude_projects_dir() -> Path

Get the Claude Code projects directory path.

Source code in src/clawd_code_sdk/storage/helpers.py
def get_claude_projects_dir() -> Path:
    """Get the Claude Code projects directory path."""
    return get_claude_data_dir() / "projects"

get_latest_session

get_latest_session(project_path: str) -> Path | None

Get the path for the most recent session file for given project if existing.

Source code in src/clawd_code_sdk/storage/helpers.py
def get_latest_session(project_path: str) -> Path | None:
    """Get the path for the most recent session file for given project if existing."""
    sessions = list_project_session_files(project_path)
    return sessions[0] if sessions else None

list_project_session_files

list_project_session_files(project_path: str) -> list[Path]

List all session files for given project path, sorted by modification time (newest first).

Source code in src/clawd_code_sdk/storage/helpers.py
def list_project_session_files(project_path: str) -> list[Path]:
    """List all session files for given project path, sorted by modification time (newest first)."""
    projects_dir = get_claude_projects_dir()
    project_dir_name = path_to_claude_dir_name(project_path)
    project_dir = projects_dir / project_dir_name

    if not project_dir.exists():
        return []

    sessions = list(project_dir.glob("*.jsonl"))
    return sorted(sessions, key=lambda p: p.stat().st_mtime, reverse=True)

path_to_claude_dir_name

path_to_claude_dir_name(project_path: str) -> str

Convert a filesystem path to Claude Code's project directory name.

Claude Code replaces every non-alphanumeric character with '-', so '/home/user/my.project' becomes '-home-user-my-project'. Names longer than 200 characters are truncated and get a hash suffix.

Parameters:

Name Type Description Default
project_path str

The filesystem path

required

Returns:

Type Description
str

The Claude Code directory name format

Source code in src/clawd_code_sdk/storage/helpers.py
def path_to_claude_dir_name(project_path: str) -> str:
    """Convert a filesystem path to Claude Code's project directory name.

    Claude Code replaces every non-alphanumeric character with '-', so
    '/home/user/my.project' becomes '-home-user-my-project'. Names longer than
    200 characters are truncated and get a hash suffix.

    Args:
        project_path: The filesystem path

    Returns:
        The Claude Code directory name format
    """
    from clawd_code_sdk._internal.sessions import _sanitize_path

    return _sanitize_path(project_path)

read_session

read_session(session_path: Path) -> list[ClaudeJSONLEntry]

Read all entries from a session file.

Source code in src/clawd_code_sdk/storage/helpers.py
def read_session(session_path: Path) -> list[ClaudeJSONLEntry]:
    """Read all entries from a session file."""
    entries: list[ClaudeJSONLEntry] = []
    if not session_path.exists():
        return entries

    from clawd_code_sdk.storage.models import ClaudeUnknownEntry

    adapter = _entry_adapter()
    # Bytes, not text: the JSON parser takes bytes, so decoding every line first is wasted work.
    with _gc_paused(), session_path.open("rb") as f:
        for raw_line in f:
            if not raw_line.strip():
                continue
            try:
                data = anyenv.load_json(raw_line, return_type=dict)
                entry = adapter.validate_python(data)
                entries.append(entry)
            except (anyenv.JsonLoadError, TypeError) as e:  # TypeError: not an object
                msg = "Failed to parse JSONL line (path: %s, error: %s, raw_line: %s)"
                logger.warning(msg, str(session_path), str(e), raw_line.decode(errors="replace"))
            except ValidationError as e:
                # A known type that doesn't match its model (a new field shape, say):
                # keep the line as an unknown entry instead of losing it.
                msg = "Failed to validate JSONL entry, keeping it unparsed (path: %s, error: %s)"
                logger.warning(msg, str(session_path), str(e))
                if isinstance(data.get("type"), str):
                    entries.append(ClaudeUnknownEntry.model_validate(data))
    return entries

write_entry

write_entry(session_path: Path, entry: ClaudeJSONLEntry) -> None

Append an entry to a session file.

Source code in src/clawd_code_sdk/storage/helpers.py
def write_entry(session_path: Path, entry: ClaudeJSONLEntry) -> None:
    """Append an entry to a session file."""
    session_path.parent.mkdir(parents=True, exist_ok=True)
    with session_path.open("a", encoding="utf-8") as f:
        f.write(_entry_to_json(entry) + "\n")