session

package
v0.0.52 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExpandShortID added in v0.0.52

func ExpandShortID(shortID string) string

ExpandShortID converts a short ID to a SQL LIKE pattern for prefix matching. Example: "240115-1430" -> "20240115-1430%"

func GetDBPath

func GetDBPath() (string, error)

GetDBPath returns the path to the sessions database.

func GetDataDir

func GetDataDir() (string, error)

GetDataDir returns the XDG data directory for term-llm. Uses $XDG_DATA_HOME if set, otherwise ~/.local/share

func NewID

func NewID() string

NewID generates a unique session ID using a timestamp prefix and random suffix. Format: YYYYMMDD-HHMMSS-RANDOM (e.g., "20240115-143052-a1b2c3") This format:

  • Sorts chronologically by default
  • Is human-readable for debugging
  • Has enough randomness to prevent collisions

func ParseIDTime

func ParseIDTime(id string) time.Time

ParseIDTime extracts the timestamp from a session ID. Returns zero time if parsing fails.

func ShortID

func ShortID(id string) string

ShortID returns a shortened version of the session ID for display. Example: "20240115-143052-a1b2c3" -> "240115-1430"

func TruncateSummary

func TruncateSummary(content string) string

TruncateSummary returns the first line of content, truncated to 100 chars.

Types

type Config

type Config struct {
	Enabled    bool `mapstructure:"enabled"`      // Master switch
	MaxAgeDays int  `mapstructure:"max_age_days"` // Auto-delete after N days (0=never)
	MaxCount   int  `mapstructure:"max_count"`    // Keep at most N sessions (0=unlimited)
}

Config holds session storage configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default session configuration.

type ListOptions

type ListOptions struct {
	Provider string        // Filter by provider
	Model    string        // Filter by model
	Status   SessionStatus // Filter by status
	Tag      string        // Filter by tag (substring match)
	Limit    int           // Max results (0 = use default)
	Offset   int           // Pagination offset
	Archived bool          // Include archived sessions
}

ListOptions configures session listing.

type LoggingStore added in v0.0.41

type LoggingStore struct {
	Store
	// contains filtered or unexported fields
}

LoggingStore wraps a Store and logs errors instead of silently discarding them. This preserves the best-effort semantics (operations don't fail the caller) while providing visibility into persistence issues.

func NewLoggingStore added in v0.0.41

func NewLoggingStore(store Store, warnFunc WarnFunc) *LoggingStore

NewLoggingStore creates a new LoggingStore wrapper. The warnFunc is called when persistence operations fail.

func (*LoggingStore) AddMessage added in v0.0.41

func (s *LoggingStore) AddMessage(ctx context.Context, sessionID string, msg *Message) error

AddMessage wraps Store.AddMessage with error logging.

func (*LoggingStore) Create added in v0.0.41

func (s *LoggingStore) Create(ctx context.Context, sess *Session) error

Create wraps Store.Create with error logging.

func (*LoggingStore) IncrementUserTurns added in v0.0.41

func (s *LoggingStore) IncrementUserTurns(ctx context.Context, id string) error

IncrementUserTurns wraps Store.IncrementUserTurns with error logging.

func (*LoggingStore) SetCurrent added in v0.0.41

func (s *LoggingStore) SetCurrent(ctx context.Context, sessionID string) error

SetCurrent wraps Store.SetCurrent with error logging.

func (*LoggingStore) Update added in v0.0.41

func (s *LoggingStore) Update(ctx context.Context, sess *Session) error

Update wraps Store.Update with error logging.

func (*LoggingStore) UpdateMetrics added in v0.0.41

func (s *LoggingStore) UpdateMetrics(ctx context.Context, id string, llmTurns, toolCalls, inputTokens, outputTokens int) error

UpdateMetrics wraps Store.UpdateMetrics with error logging.

func (*LoggingStore) UpdateStatus added in v0.0.41

func (s *LoggingStore) UpdateStatus(ctx context.Context, id string, status SessionStatus) error

UpdateStatus wraps Store.UpdateStatus with error logging.

type Message

type Message struct {
	ID          int64      `json:"id"`
	SessionID   string     `json:"session_id"`
	Role        llm.Role   `json:"role"`
	Parts       []llm.Part `json:"parts"`        // Full parts array
	TextContent string     `json:"text_content"` // Extracted text for display/FTS
	DurationMs  int64      `json:"duration_ms,omitempty"`
	CreatedAt   time.Time  `json:"created_at"`
	Sequence    int        `json:"sequence"`
}

Message represents a message in a session. The Parts field stores the full llm.Message.Parts as JSON to preserve tool calls and results exactly.

func NewMessage

func NewMessage(sessionID string, msg llm.Message, sequence int) *Message

NewMessage creates a new Message from an llm.Message with the given session ID and sequence.

func (*Message) ExtractTextContent

func (m *Message) ExtractTextContent() string

ExtractTextContent extracts and concatenates all text parts from the message.

func (*Message) PartsJSON

func (m *Message) PartsJSON() (string, error)

PartsJSON returns the Parts field serialized to JSON for database storage.

func (*Message) SetPartsFromJSON

func (m *Message) SetPartsFromJSON(data string) error

SetPartsFromJSON deserializes JSON into the Parts field.

func (*Message) ToLLMMessage

func (m *Message) ToLLMMessage() llm.Message

ToLLMMessage converts a Message back to an llm.Message.

type NoopStore

type NoopStore struct{}

NoopStore is a no-op implementation of Store used when sessions are disabled. It silently discards all writes and returns empty results for reads.

func (*NoopStore) AddMessage

func (s *NoopStore) AddMessage(ctx context.Context, sessionID string, msg *Message) error

func (*NoopStore) ClearCurrent

func (s *NoopStore) ClearCurrent(ctx context.Context) error

func (*NoopStore) Close

func (s *NoopStore) Close() error

func (*NoopStore) Create

func (s *NoopStore) Create(ctx context.Context, sess *Session) error

func (*NoopStore) Delete

func (s *NoopStore) Delete(ctx context.Context, id string) error

func (*NoopStore) Get

func (s *NoopStore) Get(ctx context.Context, id string) (*Session, error)

func (*NoopStore) GetByPrefix added in v0.0.52

func (s *NoopStore) GetByPrefix(ctx context.Context, prefix string) (*Session, error)

func (*NoopStore) GetCurrent

func (s *NoopStore) GetCurrent(ctx context.Context) (*Session, error)

func (*NoopStore) GetMessages

func (s *NoopStore) GetMessages(ctx context.Context, sessionID string, limit, offset int) ([]Message, error)

func (*NoopStore) IncrementUserTurns added in v0.0.41

func (s *NoopStore) IncrementUserTurns(ctx context.Context, id string) error

func (*NoopStore) List

func (s *NoopStore) List(ctx context.Context, opts ListOptions) ([]SessionSummary, error)

func (*NoopStore) Search

func (s *NoopStore) Search(ctx context.Context, query string, limit int) ([]SearchResult, error)

func (*NoopStore) SetCurrent

func (s *NoopStore) SetCurrent(ctx context.Context, sessionID string) error

func (*NoopStore) Update

func (s *NoopStore) Update(ctx context.Context, sess *Session) error

func (*NoopStore) UpdateMetrics added in v0.0.41

func (s *NoopStore) UpdateMetrics(ctx context.Context, id string, llmTurns, toolCalls, inputTokens, outputTokens int) error

func (*NoopStore) UpdateStatus added in v0.0.41

func (s *NoopStore) UpdateStatus(ctx context.Context, id string, status SessionStatus) error

type SQLiteStore

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

SQLiteStore implements Store using SQLite.

func NewSQLiteStore

func NewSQLiteStore(cfg Config) (*SQLiteStore, error)

NewSQLiteStore creates a new SQLite-based session store.

func (*SQLiteStore) AddMessage

func (s *SQLiteStore) AddMessage(ctx context.Context, sessionID string, msg *Message) error

AddMessage adds a message to a session. If msg.Sequence < 0, the sequence number is auto-allocated atomically.

func (*SQLiteStore) ClearCurrent

func (s *SQLiteStore) ClearCurrent(ctx context.Context) error

ClearCurrent removes the current session marker.

func (*SQLiteStore) Close

func (s *SQLiteStore) Close() error

Close closes the database connection.

func (*SQLiteStore) Create

func (s *SQLiteStore) Create(ctx context.Context, sess *Session) error

Create inserts a new session.

func (*SQLiteStore) Delete

func (s *SQLiteStore) Delete(ctx context.Context, id string) error

Delete removes a session and its messages.

func (*SQLiteStore) Get

func (s *SQLiteStore) Get(ctx context.Context, id string) (*Session, error)

Get retrieves a session by ID.

func (*SQLiteStore) GetByPrefix added in v0.0.52

func (s *SQLiteStore) GetByPrefix(ctx context.Context, prefix string) (*Session, error)

GetByPrefix retrieves a session by exact ID or by short ID prefix match. If an exact match is found, it is returned. Otherwise, the short ID is expanded to a SQL LIKE pattern and the most recent matching session is returned.

func (*SQLiteStore) GetCurrent

func (s *SQLiteStore) GetCurrent(ctx context.Context) (*Session, error)

GetCurrent retrieves the current session.

func (*SQLiteStore) GetMessages

func (s *SQLiteStore) GetMessages(ctx context.Context, sessionID string, limit, offset int) ([]Message, error)

GetMessages retrieves messages for a session.

func (*SQLiteStore) IncrementUserTurns added in v0.0.41

func (s *SQLiteStore) IncrementUserTurns(ctx context.Context, id string) error

IncrementUserTurns increments the user turn count.

func (*SQLiteStore) List

func (s *SQLiteStore) List(ctx context.Context, opts ListOptions) ([]SessionSummary, error)

List returns sessions matching the options.

func (*SQLiteStore) Search

func (s *SQLiteStore) Search(ctx context.Context, query string, limit int) ([]SearchResult, error)

Search finds sessions containing the query text using FTS5.

func (*SQLiteStore) SetCurrent

func (s *SQLiteStore) SetCurrent(ctx context.Context, sessionID string) error

SetCurrent marks a session as the current one.

func (*SQLiteStore) Update

func (s *SQLiteStore) Update(ctx context.Context, sess *Session) error

Update modifies an existing session.

func (*SQLiteStore) UpdateMetrics added in v0.0.41

func (s *SQLiteStore) UpdateMetrics(ctx context.Context, id string, llmTurns, toolCalls, inputTokens, outputTokens int) error

UpdateMetrics updates just the metrics fields (used for incremental saves).

func (*SQLiteStore) UpdateStatus added in v0.0.41

func (s *SQLiteStore) UpdateStatus(ctx context.Context, id string, status SessionStatus) error

UpdateStatus updates just the session status.

type SearchResult

type SearchResult struct {
	SessionID   string    `json:"session_id"`
	MessageID   int64     `json:"message_id"`
	SessionName string    `json:"session_name"`
	Summary     string    `json:"summary"`
	Snippet     string    `json:"snippet"` // Matched text snippet
	Provider    string    `json:"provider"`
	Model       string    `json:"model"`
	CreatedAt   time.Time `json:"created_at"`
}

SearchResult represents a search match.

type Session

type Session struct {
	ID         string    `json:"id"`
	Name       string    `json:"name,omitempty"`
	Summary    string    `json:"summary,omitempty"` // First user message or auto-generated
	Provider   string    `json:"provider"`
	Model      string    `json:"model"`
	CWD        string    `json:"cwd,omitempty"` // Working directory at session start
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
	Archived   bool      `json:"archived,omitempty"`
	ParentID   string    `json:"parent_id,omitempty"`   // For session branching
	IsSubagent bool      `json:"is_subagent,omitempty"` // True if this is a subagent session

	// Session settings (restored on resume unless overridden)
	Search bool   `json:"search,omitempty"` // Web search enabled
	Tools  string `json:"tools,omitempty"`  // Enabled tools (comma-separated)
	MCP    string `json:"mcp,omitempty"`    // Enabled MCP servers (comma-separated)

	// Session metrics
	UserTurns    int           `json:"user_turns,omitempty"`    // Number of user messages
	LLMTurns     int           `json:"llm_turns,omitempty"`     // Number of LLM API round-trips
	ToolCalls    int           `json:"tool_calls,omitempty"`    // Total tool executions
	InputTokens  int           `json:"input_tokens,omitempty"`  // Total input tokens used
	OutputTokens int           `json:"output_tokens,omitempty"` // Total output tokens used
	Status       SessionStatus `json:"status,omitempty"`        // Session status
	Tags         string        `json:"tags,omitempty"`          // Comma-separated tags
}

Session represents a chat session stored in the database.

type SessionStatus added in v0.0.41

type SessionStatus string

SessionStatus represents the current state of a session.

const (
	StatusActive      SessionStatus = "active"      // Session is open/current (may or may not be streaming)
	StatusComplete    SessionStatus = "complete"    // Session finished normally
	StatusError       SessionStatus = "error"       // Session ended with an error
	StatusInterrupted SessionStatus = "interrupted" // Session was cancelled by user
)

type SessionSummary

type SessionSummary struct {
	ID           string        `json:"id"`
	Name         string        `json:"name,omitempty"`
	Summary      string        `json:"summary,omitempty"`
	Provider     string        `json:"provider"`
	Model        string        `json:"model"`
	MessageCount int           `json:"message_count"`
	UserTurns    int           `json:"user_turns,omitempty"`
	LLMTurns     int           `json:"llm_turns,omitempty"`
	ToolCalls    int           `json:"tool_calls,omitempty"`
	InputTokens  int           `json:"input_tokens,omitempty"`
	OutputTokens int           `json:"output_tokens,omitempty"`
	Status       SessionStatus `json:"status,omitempty"`
	Tags         string        `json:"tags,omitempty"`
	CreatedAt    time.Time     `json:"created_at"`
	UpdatedAt    time.Time     `json:"updated_at"`
}

SessionSummary is a lightweight view of a session for listing.

type Store

type Store interface {
	// Session CRUD
	Create(ctx context.Context, s *Session) error
	Get(ctx context.Context, id string) (*Session, error)
	GetByPrefix(ctx context.Context, prefix string) (*Session, error)
	Update(ctx context.Context, s *Session) error
	Delete(ctx context.Context, id string) error

	// Listing and search
	List(ctx context.Context, opts ListOptions) ([]SessionSummary, error)
	Search(ctx context.Context, query string, limit int) ([]SearchResult, error)

	// Message operations - stores full llm.Message with Parts
	AddMessage(ctx context.Context, sessionID string, msg *Message) error
	GetMessages(ctx context.Context, sessionID string, limit, offset int) ([]Message, error)

	// Metrics operations (for incremental session saving)
	UpdateMetrics(ctx context.Context, id string, llmTurns, toolCalls, inputTokens, outputTokens int) error
	UpdateStatus(ctx context.Context, id string, status SessionStatus) error
	IncrementUserTurns(ctx context.Context, id string) error

	// Current session tracking (for auto-resume)
	SetCurrent(ctx context.Context, sessionID string) error
	GetCurrent(ctx context.Context) (*Session, error)
	ClearCurrent(ctx context.Context) error

	// Lifecycle
	Close() error
}

Store is the interface for session persistence.

func NewStore

func NewStore(cfg Config) (Store, error)

NewStore creates a new Store based on the configuration. If sessions are disabled, returns a no-op store.

type WarnFunc added in v0.0.41

type WarnFunc func(format string, args ...any)

WarnFunc is a function that logs warnings.

Jump to

Keyboard shortcuts

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