session

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSessionNotFound is returned when a session is not found
	ErrSessionNotFound = errors.New("session not found")

	// ErrMessageNotFound is returned when a message is not found
	ErrMessageNotFound = errors.New("message not found")

	// ErrInvalidSessionID is returned when a session ID is invalid
	ErrInvalidSessionID = errors.New("invalid session ID")

	// ErrInvalidMessageID is returned when a message ID is invalid
	ErrInvalidMessageID = errors.New("invalid message ID")

	// ErrInvalidStatus is returned when a session status is invalid
	ErrInvalidStatus = errors.New("invalid session status")

	// ErrInvalidRole is returned when a message role is invalid
	ErrInvalidRole = errors.New("invalid message role")

	// ErrEmptySessionName is returned when session name is empty
	ErrEmptySessionName = errors.New("session name cannot be empty")

	// ErrEmptyMessageContent is returned when message content is empty
	ErrEmptyMessageContent = errors.New("message content cannot be empty")

	// ErrSessionDeleted is returned when operating on a deleted session
	ErrSessionDeleted = errors.New("session is deleted")

	// ErrInvalidExportFormat is returned when export format is invalid
	ErrInvalidExportFormat = errors.New("invalid export format")

	// ErrInvalidImportData is returned when import data is invalid
	ErrInvalidImportData = errors.New("invalid import data")

	// ErrCircularReference is returned when a message references itself as parent
	ErrCircularReference = errors.New("circular reference detected in message thread")

	// ErrEmptySearchQuery is returned when search query is empty
	ErrEmptySearchQuery = errors.New("search query cannot be empty")

	// ErrSearchLimitExceeded is returned when search limit exceeds maximum
	ErrSearchLimitExceeded = errors.New("search limit exceeds maximum allowed (1000)")

	// ErrInvalidDateRange is returned when date range is invalid
	ErrInvalidDateRange = errors.New("invalid date range: date_from must be before date_to")
)

Common session errors

Functions

func DetectCodeLanguage

func DetectCodeLanguage(content string) string

DetectCodeLanguage attempts to detect the programming language from code content

func FormatCodeBlock

func FormatCodeBlock(content, language string) string

FormatCodeBlock formats a code block for markdown

func MarshalMetadata

func MarshalMetadata(metadata map[string]any) (string, error)

MarshalMetadata marshals metadata map to JSON string

func MarshalSettings

func MarshalSettings(settings map[string]any) (string, error)

MarshalSettings marshals settings map to JSON string

func UnmarshalMetadata

func UnmarshalMetadata(data string) (map[string]any, error)

UnmarshalMetadata unmarshals JSON string to metadata map

func UnmarshalSettings

func UnmarshalSettings(data string) (map[string]any, error)

UnmarshalSettings unmarshals JSON string to settings map

Types

type ExportData

type ExportData struct {
	Session  *Session
	Messages []*Message
	Metadata ExportMetadata
}

ExportData represents the data passed to templates

type ExportFormat

type ExportFormat string

ExportFormat represents the format for session export

const (
	// ExportFormatJSON exports session as JSON
	ExportFormatJSON ExportFormat = "json"

	// ExportFormatMarkdown exports session as Markdown
	ExportFormatMarkdown ExportFormat = "markdown"

	// ExportFormatHTML exports session as HTML
	ExportFormatHTML ExportFormat = "html"

	// ExportFormatText exports session as plain text
	ExportFormatText ExportFormat = "text"
)

func (ExportFormat) IsValid

func (f ExportFormat) IsValid() bool

IsValid checks if an export format is valid

type ExportMetadata

type ExportMetadata struct {
	ExportedAt   time.Time
	ExporterName string
	ExporterVer  string
	MessageCount int
	TotalTokens  int64
	FirstMessage time.Time
	LastMessage  time.Time
	Provider     string
}

ExportMetadata contains export-specific metadata

type Exporter

type Exporter struct {
	// contains filtered or unexported fields
}

Exporter handles session export operations

func NewExporter

func NewExporter(options *ExporterOptions) *Exporter

NewExporter creates a new Exporter instance

func (*Exporter) ExportToFile

func (e *Exporter) ExportToFile(filePath string, format ExportFormat, session *Session, messages []*Message) error

ExportToFile exports session to a file with the specified format

func (*Exporter) ExportToHTML

func (e *Exporter) ExportToHTML(w io.Writer, session *Session, messages []*Message) error

ExportToHTML exports session to HTML format

func (*Exporter) ExportToJSON

func (e *Exporter) ExportToJSON(w io.Writer, session *Session, messages []*Message) error

ExportToJSON exports session to JSON format

func (*Exporter) ExportToJSONWithContext

func (e *Exporter) ExportToJSONWithContext(ctx context.Context, w io.Writer, session *Session, messages []*Message) error

ExportToJSONWithContext exports session to JSON with context support

func (*Exporter) ExportToMarkdown

func (e *Exporter) ExportToMarkdown(w io.Writer, session *Session, messages []*Message) error

ExportToMarkdown exports session to Markdown format

func (*Exporter) ExportWithTemplate

func (e *Exporter) ExportWithTemplate(w io.Writer, templatePath string, session *Session, messages []*Message) error

ExportWithTemplate exports session using a custom template

type ExporterOptions

type ExporterOptions struct {
	// TemplateDir is the directory containing custom templates
	TemplateDir string

	// IncludeMetadata controls whether to include detailed metadata in exports
	IncludeMetadata bool

	// PrettyPrint controls JSON formatting
	PrettyPrint bool
}

ExporterOptions holds configuration for the exporter

type ListOption

type ListOption func(*ListOptions)

ListOption is a functional option for configuring ListOptions

func WithLimit

func WithLimit(limit int64) ListOption

WithLimit sets the maximum number of sessions to return

func WithOffset

func WithOffset(offset int64) ListOption

WithOffset sets the offset for pagination

func WithSortBy

func WithSortBy(sortBy string) ListOption

WithSortBy sets the field to sort by

func WithStatus

func WithStatus(status SessionStatus) ListOption

WithStatus filters sessions by status

type ListOptions

type ListOptions struct {
	Status SessionStatus
	Limit  int64
	Offset int64
	SortBy string
}

ListOptions contains options for listing sessions

func ApplyListOptions

func ApplyListOptions(opts ...ListOption) *ListOptions

ApplyListOptions applies functional options to ListOptions

func DefaultListOptions

func DefaultListOptions() *ListOptions

DefaultListOptions returns default list options

type Manager

type Manager interface {
	// Session operations
	CreateSession(ctx context.Context, session *Session) error
	GetSession(ctx context.Context, id string) (*Session, error)
	GetSessionSummary(ctx context.Context, id string) (*SessionSummary, error)
	ListSessions(ctx context.Context, opts ...ListOption) ([]*Session, error)
	UpdateSession(ctx context.Context, session *Session) error
	DeleteSession(ctx context.Context, id string) error
	ArchiveSession(ctx context.Context, id string) error
	HardDeleteSession(ctx context.Context, id string) error

	// Message operations
	AddMessage(ctx context.Context, message *Message) error
	GetMessage(ctx context.Context, id string) (*Message, error)
	GetMessages(ctx context.Context, sessionID string) ([]*Message, error)
	GetMessagesPaginated(ctx context.Context, sessionID string, limit, offset int64) ([]*Message, error)
	GetConversationThread(ctx context.Context, messageID string) ([]*Message, error)
	UpdateMessage(ctx context.Context, message *Message) error
	DeleteMessage(ctx context.Context, id string) error

	// Search operations
	SearchSessions(ctx context.Context, query string, opts ...SearchOption) ([]*Session, error)
	SearchMessages(ctx context.Context, sessionID string, query string, opts ...SearchOption) ([]*Message, error)

	// Statistics operations
	GetSessionMessageCount(ctx context.Context, sessionID string) (int64, error)
	GetTotalTokensUsed(ctx context.Context, sessionID string) (int64, error)

	// Export/Import operations
	ExportSession(ctx context.Context, sessionID string, format ExportFormat, w io.Writer) error
	ImportSession(ctx context.Context, r io.Reader) (*Session, error)

	// Utility operations
	TouchSession(ctx context.Context, id string) error
	Close() error
}

Manager defines the interface for session management operations

type Message

type Message struct {
	ID           string         `json:"id"`
	SessionID    string         `json:"session_id"`
	Role         MessageRole    `json:"role"`
	Content      string         `json:"content"`
	Timestamp    time.Time      `json:"timestamp"`
	ParentID     *string        `json:"parent_id,omitempty"`
	TokensUsed   *int64         `json:"tokens_used,omitempty"`
	Model        *string        `json:"model,omitempty"`
	FinishReason *string        `json:"finish_reason,omitempty"`
	Metadata     map[string]any `json:"metadata,omitempty"`
}

Message represents a conversation message

type MessageRole

type MessageRole string

MessageRole represents the role of a message

const (
	// RoleUser represents a user message
	RoleUser MessageRole = "user"

	// RoleAssistant represents an assistant message
	RoleAssistant MessageRole = "assistant"

	// RoleSystem represents a system message
	RoleSystem MessageRole = "system"

	// RoleTool represents a tool message
	RoleTool MessageRole = "tool"
)

func (MessageRole) IsValid

func (r MessageRole) IsValid() bool

IsValid checks if a message role is valid

type SQLiteManager

type SQLiteManager struct {
	// contains filtered or unexported fields
}

SQLiteManager implements the Manager interface using SQLite database

func NewSQLiteManager

func NewSQLiteManager(db *database.DB) *SQLiteManager

NewSQLiteManager creates a new SQLiteManager instance

func (*SQLiteManager) AddMessage

func (m *SQLiteManager) AddMessage(ctx context.Context, message *Message) error

AddMessage adds a new message to a session

func (*SQLiteManager) ArchiveSession

func (m *SQLiteManager) ArchiveSession(ctx context.Context, id string) error

ArchiveSession archives a session by setting status to 'archived'

func (*SQLiteManager) Close

func (m *SQLiteManager) Close() error

Close closes the database connection

func (*SQLiteManager) CreateSession

func (m *SQLiteManager) CreateSession(ctx context.Context, session *Session) error

CreateSession creates a new session

func (*SQLiteManager) DeleteMessage

func (m *SQLiteManager) DeleteMessage(ctx context.Context, id string) error

DeleteMessage deletes a message

func (*SQLiteManager) DeleteSession

func (m *SQLiteManager) DeleteSession(ctx context.Context, id string) error

DeleteSession soft-deletes a session by setting status to 'deleted'

func (*SQLiteManager) ExportSession

func (m *SQLiteManager) ExportSession(ctx context.Context, sessionID string, format ExportFormat, w io.Writer) error

ExportSession exports a session to the specified format

func (*SQLiteManager) GetConversationThread

func (m *SQLiteManager) GetConversationThread(ctx context.Context, messageID string) ([]*Message, error)

GetConversationThread retrieves all messages in a conversation thread

func (*SQLiteManager) GetMessage

func (m *SQLiteManager) GetMessage(ctx context.Context, id string) (*Message, error)

GetMessage retrieves a message by ID

func (*SQLiteManager) GetMessages

func (m *SQLiteManager) GetMessages(ctx context.Context, sessionID string) ([]*Message, error)

GetMessages retrieves all messages for a session

func (*SQLiteManager) GetMessagesPaginated

func (m *SQLiteManager) GetMessagesPaginated(ctx context.Context, sessionID string, limit, offset int64) ([]*Message, error)

GetMessagesPaginated retrieves messages for a session with pagination

func (*SQLiteManager) GetSession

func (m *SQLiteManager) GetSession(ctx context.Context, id string) (*Session, error)

GetSession retrieves a session by ID

func (*SQLiteManager) GetSessionMessageCount

func (m *SQLiteManager) GetSessionMessageCount(ctx context.Context, sessionID string) (int64, error)

GetSessionMessageCount returns the number of messages in a session

func (*SQLiteManager) GetSessionSummary

func (m *SQLiteManager) GetSessionSummary(ctx context.Context, id string) (*SessionSummary, error)

GetSessionSummary retrieves a session with message count and total tokens

func (*SQLiteManager) GetTotalTokensUsed

func (m *SQLiteManager) GetTotalTokensUsed(ctx context.Context, sessionID string) (int64, error)

GetTotalTokensUsed returns the total tokens used in a session

func (*SQLiteManager) HardDeleteSession

func (m *SQLiteManager) HardDeleteSession(ctx context.Context, id string) error

HardDeleteSession permanently deletes a session and all its messages

func (*SQLiteManager) ImportSession

func (m *SQLiteManager) ImportSession(ctx context.Context, r io.Reader) (*Session, error)

ImportSession imports a session from JSON format

func (*SQLiteManager) ListSessions

func (m *SQLiteManager) ListSessions(ctx context.Context, opts ...ListOption) ([]*Session, error)

ListSessions lists sessions with optional filters

func (*SQLiteManager) OptimizeSearchIndex

func (m *SQLiteManager) OptimizeSearchIndex(ctx context.Context) error

OptimizeSearchIndex optimizes the FTS5 search index

func (*SQLiteManager) RebuildSearchIndex

func (m *SQLiteManager) RebuildSearchIndex(ctx context.Context) error

RebuildSearchIndex rebuilds the FTS5 search index

func (*SQLiteManager) SearchAllMessages

func (m *SQLiteManager) SearchAllMessages(ctx context.Context, opts *SearchOptions) (*SearchResultSet, error)

SearchAllMessages performs full-text search across all conversation messages

func (*SQLiteManager) SearchMessages

func (m *SQLiteManager) SearchMessages(ctx context.Context, sessionID string, query string, opts ...SearchOption) ([]*Message, error)

SearchMessages searches for messages within a session by content

func (*SQLiteManager) SearchSessions

func (m *SQLiteManager) SearchSessions(ctx context.Context, query string, opts ...SearchOption) ([]*Session, error)

SearchSessions searches for sessions by name or ID

func (*SQLiteManager) TouchSession

func (m *SQLiteManager) TouchSession(ctx context.Context, id string) error

TouchSession updates the session's updated_at timestamp

func (*SQLiteManager) UpdateMessage

func (m *SQLiteManager) UpdateMessage(ctx context.Context, message *Message) error

UpdateMessage updates an existing message

func (*SQLiteManager) UpdateSession

func (m *SQLiteManager) UpdateSession(ctx context.Context, session *Session) error

UpdateSession updates an existing session

type SearchOption

type SearchOption func(*SearchOptions)

SearchOption is a functional option for configuring SearchOptions

func WithQuery

func WithQuery(query string) SearchOption

WithQuery sets the search query

func WithSearchLimit

func WithSearchLimit(limit int64) SearchOption

WithSearchLimit sets the maximum number of results

func WithSearchOffset

func WithSearchOffset(offset int64) SearchOption

WithSearchOffset sets the offset for search pagination

type SearchOptions

type SearchOptions struct {
	Query  string
	Limit  int64
	Offset int64
	// FTS5 full-text search options
	DateFrom *time.Time // Filter messages from this date
	DateTo   *time.Time // Filter messages until this date
	Provider string     // Filter by provider/model (e.g., "claude", "gpt")
}

SearchOptions contains options for searching

func ApplySearchOptions

func ApplySearchOptions(opts ...SearchOption) *SearchOptions

ApplySearchOptions applies functional options to SearchOptions

func DefaultSearchOptions

func DefaultSearchOptions() *SearchOptions

DefaultSearchOptions returns default search options

func DefaultSearchOptionsWithQuery

func DefaultSearchOptionsWithQuery(query string) *SearchOptions

DefaultSearchOptionsWithQuery returns default search options with a query

func (*SearchOptions) Validate

func (opts *SearchOptions) Validate() error

Validate validates search options

type SearchResult

type SearchResult struct {
	Message        Message       `json:"message"`
	SessionName    string        `json:"session_name"`
	SessionStatus  SessionStatus `json:"session_status"`
	Snippet        string        `json:"snippet"`         // HTML snippet with highlighted matches
	RelevanceScore float64       `json:"relevance_score"` // BM25 relevance score
}

SearchResult represents a single search result with context snippet

type SearchResultSet

type SearchResultSet struct {
	Results    []SearchResult `json:"results"`
	TotalCount int64          `json:"total_count"`
	Query      string         `json:"query"`
	Limit      int64          `json:"limit"`
	Offset     int64          `json:"offset"`
}

SearchResultSet contains search results and metadata

type Session

type Session struct {
	ID          string         `json:"id"`
	Name        string         `json:"name"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	Status      SessionStatus  `json:"status"`
	Model       *string        `json:"model,omitempty"`
	Temperature *float64       `json:"temperature,omitempty"`
	MaxTokens   *int64         `json:"max_tokens,omitempty"`
	Settings    map[string]any `json:"settings,omitempty"`
}

Session represents a conversation session

type SessionError

type SessionError struct {
	Op      string // Operation that failed
	Err     error  // Underlying error
	Context string // Additional context
}

SessionError wraps errors with additional context

func NewSessionError

func NewSessionError(op string, err error, context string) *SessionError

NewSessionError creates a new SessionError

func (*SessionError) Error

func (e *SessionError) Error() string

Error implements the error interface

func (*SessionError) Unwrap

func (e *SessionError) Unwrap() error

Unwrap implements error unwrapping

type SessionExport

type SessionExport struct {
	Session  Session   `json:"session"`
	Messages []Message `json:"messages"`
}

SessionExport represents an exported session

type SessionStatus

type SessionStatus string

SessionStatus represents the status of a session

const (
	// StatusActive represents an active session
	StatusActive SessionStatus = "active"

	// StatusArchived represents an archived session
	StatusArchived SessionStatus = "archived"

	// StatusDeleted represents a deleted session (soft delete)
	StatusDeleted SessionStatus = "deleted"
)

func (SessionStatus) IsValid

func (s SessionStatus) IsValid() bool

IsValid checks if a session status is valid

type SessionSummary

type SessionSummary struct {
	Session
	MessageCount int64 `json:"message_count"`
	TotalTokens  int64 `json:"total_tokens,omitempty"`
}

SessionSummary represents a session with summary information

Jump to

Keyboard shortcuts

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