Files
claude-config/bin/claude_code/session.py
T

57 lines
2.1 KiB
Python

import dataclasses
import glob
import os
import pathlib
import shutil
import uuid
from failure import Failure
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
@dataclasses.dataclass(frozen=True)
class Session:
"""Exists while its transcript does."""
id: uuid.UUID
claude_code_transcripts: pathlib.Path
name: str
def session_named(name: str, claude_code_transcripts: pathlib.Path) -> Session:
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=claude_code_transcripts, name=name)
# <claude_code_transcripts>/-home-me-code-log/<session id>.jsonl
def transcript_file(session: Session) -> str | None:
hit = glob.glob(os.path.join(glob.escape(str(session.claude_code_transcripts)), "*", f"{session.id}.jsonl"))
return hit[0] if hit else None
def session_open(session: Session) -> bool:
return transcript_file(session) is not None
# <session id>.jsonl, <session id>/subagents/, and from older Claude Code versions <session id>.superseded-*/ and <session id>.orphaned-*.jsonl
def session_files(transcript: str) -> list[str]:
return sorted(glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*"))
# <session id>/subagents/agent-<agent id>.jsonl, beside <session id>.jsonl
def subagent_transcript(session_transcript: str, agent_id: str) -> str:
return os.path.join(session_transcript.removesuffix(".jsonl"), "subagents", f"agent-{agent_id}.jsonl")
def delete_session(session: Session) -> Failure | None:
path = transcript_file(session)
if path is None:
return None
stem = path.removesuffix(".jsonl")
# The transcript goes last: a failed delete leaves a session that session_open still sees, never a new session with this id beside the old one's files.
for sibling in sorted(session_files(path), key=lambda sibling: sibling == path):
try:
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
except OSError as failure:
return Failure(f"could not delete {sibling}: {failure.strerror or failure}; delete every file and folder matching {stem}*, then run it again; a run before that resumes the finished chunk's session")
return None