session

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 14, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package session persists JSONL conversations and related session metadata.

Index

Constants

View Source
const (
	ExportMarkdown = "markdown"
	ExportJSON     = "json"
	ExportJSONL    = "jsonl"
	ExportHTML     = "html"
)
View Source
const DefaultCleanupPeriodDays = 30

DefaultCleanupPeriodDays matches Claude Code's default transcript retention.

View Source
const MaxRotatedSessionLogs = 3

MaxRotatedSessionLogs is the number of oversized transcript snapshots kept next to the active session JSONL.

View Source
const MaxSessionJSONLBytes int64 = 5 * 1024 * 1024

MaxSessionJSONLBytes is the active transcript size that triggers rotation.

Variables

View Source
var ErrAllSessionsEmpty = errors.New("all saved sessions are empty")

ErrAllSessionsEmpty reports that saved sessions exist but none contain messages.

View Source
var ErrNoSessions = errors.New("no saved sessions")

ErrNoSessions reports that no saved session files are visible to the store.

View Source
var ErrSessionNotFound = errors.New("session not found")

ErrSessionNotFound reports that a requested saved session does not exist.

Functions

func DefaultExportFilename

func DefaultExportFilename(sess *Session) string

func DefaultExportFilenameForFormat

func DefaultExportFilenameForFormat(sess *Session, format string) string

func IsSessionReferenceAlias

func IsSessionReferenceAlias(reference string) bool

IsSessionReferenceAlias reports whether reference selects the newest session.

func NormalizeExportFormat

func NormalizeExportFormat(format string) (string, error)

func NormalizeSessionTag

func NormalizeSessionTag(tag string) string

NormalizeSessionTag removes invisible Unicode controls and surrounding whitespace before a tag is persisted or rendered in a terminal.

func RenderHTML

func RenderHTML(sess *Session) string

func RenderMarkdown

func RenderMarkdown(sess *Session) string

func ValidateExportOutputPath

func ValidateExportOutputPath(path string) error

func WorkspaceFingerprint

func WorkspaceFingerprint(workspace string) string

Types

type BackfillReport

type BackfillReport struct {
	Kind                  string                   `json:"kind"`
	Action                string                   `json:"action"`
	Status                string                   `json:"status"`
	SessionsScanned       int                      `json:"sessions_scanned"`
	SessionsUpdated       int                      `json:"sessions_updated"`
	InputsAdded           int                      `json:"inputs_added"`
	IdentityUpdates       int                      `json:"identity_updates"`
	SkippedWithInputs     int                      `json:"skipped_with_inputs"`
	SkippedDisabled       int                      `json:"skipped_disabled"`
	BackfilledSessions    []BackfilledSession      `json:"backfilled_sessions,omitempty"`
	SkippedSessionDetails []BackfillSkippedSession `json:"skipped_session_details,omitempty"`
}

type BackfillSkippedSession

type BackfillSkippedSession struct {
	ID     string `json:"id"`
	Reason string `json:"reason"`
}

type BackfilledSession

type BackfilledSession struct {
	ID              string `json:"id"`
	Path            string `json:"path"`
	Inputs          int    `json:"inputs"`
	IdentityUpdated bool   `json:"identity_updated,omitempty"`
}

type ExportedSession

type ExportedSession struct {
	ID       string              `json:"id"`
	Identity SessionIdentity     `json:"identity"`
	Messages []anthropic.Message `json:"messages"`
}

type IdentityPlaceholder

type IdentityPlaceholder struct {
	Field  string `json:"field"`
	Reason string `json:"reason"`
}

type ImportOptions

type ImportOptions struct {
	ID        string
	Overwrite bool
}

type ImportResult

type ImportResult struct {
	Source            string          `json:"source"`
	OriginalSessionID string          `json:"original_session_id,omitempty"`
	SessionID         string          `json:"session_id"`
	Path              string          `json:"path"`
	MessageCount      int             `json:"message_count"`
	Overwritten       bool            `json:"overwritten"`
	Identity          SessionIdentity `json:"identity"`
}

type LookupError

type LookupError struct {
	Err                      error
	Reference                string
	SearchDir                string
	LegacyDir                string
	Workspace                string
	WorkspaceFingerprint     string
	OtherWorkspacePartitions int
	OtherWorkspaceSessions   int
}

LookupError adds workspace-namespace context to session lookup failures while preserving ErrNoSessions and ErrSessionNotFound through errors.Is.

func (LookupError) Error

func (e LookupError) Error() string

func (LookupError) Unwrap

func (e LookupError) Unwrap() error

type PathIsDirectoryError

type PathIsDirectoryError struct {
	Path string
}

func (PathIsDirectoryError) Error

func (e PathIsDirectoryError) Error() string

type PinResult

type PinResult struct {
	SessionID      string `json:"session_id"`
	Path           string `json:"path"`
	Action         string `json:"action"`
	MessageIndex   int    `json:"message_index"`
	MessageCount   int    `json:"message_count"`
	PinnedMessages []int  `json:"pinned_messages"`
}

PinResult describes a message pin mutation in a saved session.

type PromptEntry

type PromptEntry struct {
	Index     int       `json:"index"`
	Role      string    `json:"role"`
	Time      time.Time `json:"time"`
	Text      string    `json:"text"`
	SessionID string    `json:"session_id"`
}

type PruneOptions

type PruneOptions struct {
	ExcludeID string
	Keep      int
	EmptyOnly bool
	Confirm   bool
}

PruneOptions controls saved-session cleanup.

type PruneReport

type PruneReport struct {
	Kind           string          `json:"kind"`
	Action         string          `json:"action"`
	Status         string          `json:"status"`
	DryRun         bool            `json:"dry_run"`
	Keep           int             `json:"keep,omitempty"`
	EmptyOnly      bool            `json:"empty_only,omitempty"`
	Scanned        int             `json:"scanned"`
	CandidateCount int             `json:"candidate_count"`
	DeletedCount   int             `json:"deleted_count"`
	Candidates     []PrunedSession `json:"candidates,omitempty"`
	Deleted        []PrunedSession `json:"deleted,omitempty"`
}

PruneReport describes a dry-run or confirmed saved-session cleanup.

type PrunedSession

type PrunedSession struct {
	ID           string    `json:"id"`
	Path         string    `json:"path"`
	MessageCount int       `json:"message_count"`
	UpdatedAt    time.Time `json:"updated_at,omitempty"`
	ModifiedAt   time.Time `json:"modified_at,omitempty"`
	Reason       string    `json:"reason"`
}

PrunedSession describes a session selected by cleanup.

type Record

type Record struct {
	Type            string             `json:"type"`
	Time            time.Time          `json:"time"`
	Message         *anthropic.Message `json:"message,omitempty"`
	Identity        *SessionIdentity   `json:"identity,omitempty"`
	Usage           *anthropic.Usage   `json:"usage,omitempty"`
	Input           string             `json:"input,omitempty"`
	SessionID       string             `json:"session_id,omitempty"`
	ParentSessionID string             `json:"parent_session_id,omitempty"`
	BranchName      string             `json:"branch_name,omitempty"`
	MessageIndex    int                `json:"message_index,omitempty"`
	Action          string             `json:"action,omitempty"`
}

type RenameResult

type RenameResult struct {
	OldID        string `json:"old_id"`
	NewID        string `json:"new_id"`
	OldPath      string `json:"old_path"`
	NewPath      string `json:"new_path"`
	MessageCount int    `json:"message_count"`
}

type ReplaceResult

type ReplaceResult struct {
	SessionID         string `json:"session_id"`
	Path              string `json:"path"`
	OriginalMessages  int    `json:"original_messages"`
	RemainingMessages int    `json:"remaining_messages"`
	RemovedMessages   int    `json:"removed_messages"`
}

type RewindResult

type RewindResult struct {
	SessionID         string `json:"session_id"`
	Path              string `json:"path"`
	OriginalMessages  int    `json:"original_messages"`
	RemainingMessages int    `json:"remaining_messages"`
	RemovedMessages   int    `json:"removed_messages"`
}

type Session

type Session struct {
	ID       string
	Messages []anthropic.Message
	Path     string
	Identity SessionIdentity
	Metadata SessionMetadata
}

type SessionIdentity

type SessionIdentity struct {
	Title        string                `json:"title,omitempty"`
	Tag          string                `json:"tag,omitempty"`
	Workspace    string                `json:"workspace,omitempty"`
	Worktree     string                `json:"worktree,omitempty"`
	Purpose      string                `json:"purpose,omitempty"`
	Placeholders []IdentityPlaceholder `json:"placeholders,omitempty"`
}

type SessionMetadata

type SessionMetadata struct {
	CreatedAt       time.Time `json:"created_at,omitempty"`
	UpdatedAt       time.Time `json:"updated_at,omitempty"`
	ModifiedAt      time.Time `json:"modified_at,omitempty"`
	ParentSessionID string    `json:"parent_session_id,omitempty"`
	BranchName      string    `json:"branch_name,omitempty"`
	PinnedMessages  []int     `json:"pinned_messages,omitempty"`
}

type Store

type Store struct {
	Dir                 string
	LegacyDir           string
	Workspace           string
	PersistenceDisabled bool
}

func NewStore

func NewStore(configHome string) *Store

func NewWorkspaceStore

func NewWorkspaceStore(configHome string, workspace string) *Store

func NewWorkspaceStoreWithCleanup

func NewWorkspaceStoreWithCleanup(configHome string, workspace string, cleanupPeriodDays int) (*Store, error)

NewWorkspaceStoreWithCleanup opens a workspace store and applies transcript retention.

func (*Store) Append

func (s *Store) Append(id string, msg anthropic.Message) error

func (*Store) AppendInput

func (s *Store) AppendInput(id string, input string) error

func (*Store) AppendPromptHistoryDisabled

func (s *Store) AppendPromptHistoryDisabled(id string) error

func (*Store) AppendWithUsage

func (s *Store) AppendWithUsage(id string, msg anthropic.Message, usage *anthropic.Usage) error

func (*Store) ApplyCleanupPeriodDays

func (s *Store) ApplyCleanupPeriodDays(days int) error

ApplyCleanupPeriodDays removes expired transcripts or disables persistence when days is zero.

func (*Store) BackfillPromptHistory

func (s *Store) BackfillPromptHistory() (BackfillReport, error)

func (*Store) Create

func (s *Store) Create(id string) (*Session, error)

func (*Store) CreateWithIdentity

func (s *Store) CreateWithIdentity(id string, identity SessionIdentity) (*Session, error)

func (*Store) Delete

func (s *Store) Delete(id string) error

func (*Store) Exists

func (s *Store) Exists(id string) (bool, error)

func (*Store) Export

func (s *Store) Export(id string, format string) ([]byte, *Session, error)

func (*Store) Fork

func (s *Store) Fork(id string, branchName string) (*Session, error)

func (*Store) Identity

func (s *Store) Identity(id string) (SessionIdentity, error)

func (*Store) Import

func (s *Store) Import(path string, opts ImportOptions) (ImportResult, error)

func (*Store) LatestAnyID

func (s *Store) LatestAnyID() (string, error)

LatestAnyID returns the newest visible session, including empty transcripts.

func (*Store) LatestID

func (s *Store) LatestID() (string, error)

LatestID returns the newest visible session that contains at least one message.

func (*Store) LatestIDExcluding

func (s *Store) LatestIDExcluding(excludeID string) (string, error)

LatestIDExcluding returns the newest non-empty session other than excludeID.

func (*Store) LatestSessionExcluding

func (s *Store) LatestSessionExcluding(excludeID string) (*Session, error)

LatestSessionExcluding returns the newest non-empty session, falling back to sibling workspace namespaces when the current namespace has no usable match.

func (*Store) List

func (s *Store) List() ([]Session, error)

func (*Store) Open

func (s *Store) Open(id string) (*Session, error)

func (*Store) OpenExisting

func (s *Store) OpenExisting(id string) (*Session, error)

func (*Store) PinMessage

func (s *Store) PinMessage(id string, index int) (PinResult, error)

PinMessage marks the zero-based message index as pinned for the session.

func (*Store) PromptHistory

func (s *Store) PromptHistory(id string) ([]PromptEntry, error)

func (*Store) Prune

func (s *Store) Prune(opts PruneOptions) (PruneReport, error)

Prune selects saved sessions for cleanup and deletes them only when Confirm is true.

func (*Store) RemoveAll

func (s *Store) RemoveAll() error

RemoveAll deletes all transcript files visible to the store.

func (*Store) RemoveOlderThan

func (s *Store) RemoveOlderThan(cutoff time.Time) error

RemoveOlderThan deletes transcript files whose modified time is older than cutoff.

func (*Store) Rename

func (s *Store) Rename(oldID string, newID string) (RenameResult, error)

func (*Store) RepairSessionIdentities

func (s *Store) RepairSessionIdentities() (BackfillReport, error)

func (*Store) ReplaceMessages

func (s *Store) ReplaceMessages(sess *Session, messages []anthropic.Message) (ReplaceResult, error)

func (*Store) Rewind

func (s *Store) Rewind(id string, removeMessages int) (RewindResult, error)

func (*Store) SetTag

func (s *Store) SetTag(id string, tag string) (SessionIdentity, error)

SetTag replaces or clears the searchable tag attached to a saved session.

func (*Store) UnpinMessage

func (s *Store) UnpinMessage(id string, index int) (PinResult, error)

UnpinMessage removes a pin from the zero-based message index.

func (*Store) UpdateIdentity

func (s *Store) UpdateIdentity(id string, update SessionIdentity) (SessionIdentity, error)

func (*Store) Usage

func (s *Store) Usage(id string) ([]UsageEntry, error)

type UsageEntry

type UsageEntry struct {
	MessageIndex int             `json:"message_index"`
	Time         time.Time       `json:"time"`
	SessionID    string          `json:"session_id"`
	Usage        anthropic.Usage `json:"usage"`
}

type WorkspaceMismatchError

type WorkspaceMismatchError struct {
	Expected string
	Actual   string
	Path     string
}

WorkspaceMismatchError reports an explicitly bound session from another workspace.

func (WorkspaceMismatchError) Error

func (e WorkspaceMismatchError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL