session

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BranchInfo

type BranchInfo struct {
	Name        string    `json:"name"`        // Human-readable branch name
	Description string    `json:"description"` // Branch description
	IsMain      bool      `json:"is_main"`     // Whether this is the main branch
	IsMerged    bool      `json:"is_merged"`   // Whether this branch was merged back
	MergedFrom  []string  `json:"merged_from"` // List of branch IDs that were merged
	CreatedAt   time.Time `json:"created_at"`
	CreatedBy   string    `json:"created_by"` // What created this branch (user, system, auto)
}

BranchInfo contains metadata about a branch

type Cache

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

Cache implements an LRU cache with TTL for sessions

func NewCache

func NewCache(config CacheConfig) *Cache

NewCache creates a new session cache

func (*Cache) Clear

func (c *Cache) Clear()

Clear removes all entries from the cache

func (*Cache) Close

func (c *Cache) Close()

Close stops the cleanup routine

func (*Cache) Contains

func (c *Cache) Contains(key string) bool

Contains checks if a key exists in the cache

func (*Cache) Delete

func (c *Cache) Delete(key string)

Delete removes a session from the cache

func (*Cache) Get

func (c *Cache) Get(key string) (*Session, bool)

Get retrieves a session from cache

func (*Cache) GetNewest

func (c *Cache) GetNewest() (*CachedSession, bool)

GetNewest returns the newest cached session

func (*Cache) GetOldest

func (c *Cache) GetOldest() (*CachedSession, bool)

GetOldest returns the oldest cached session

func (*Cache) GetSession

func (c *Cache) GetSession(key string) (*Session, bool)

GetSession retrieves cached session without updating access time

func (*Cache) HitRate

func (c *Cache) HitRate() float64

HitRate returns the cache hit rate as a percentage

func (*Cache) Keys

func (c *Cache) Keys() []string

Keys returns all keys in the cache

func (*Cache) PruneByAccessCount

func (c *Cache) PruneByAccessCount(minAccessCount int) int

PruneByAccessCount removes sessions with access count below threshold

func (*Cache) PruneBySize

func (c *Cache) PruneBySize(maxTotalSize int) int

PruneBySize removes sessions until total size is under the limit

func (*Cache) RefreshTTL

func (c *Cache) RefreshTTL(key string, ttl time.Duration) bool

RefreshTTL refreshes the TTL for a cached session

func (*Cache) Set

func (c *Cache) Set(key string, session *Session)

Set adds or updates a session in the cache

func (*Cache) SetWithTTL

func (c *Cache) SetWithTTL(key string, session *Session, ttl time.Duration)

SetWithTTL adds or updates a session with a specific TTL

func (*Cache) Size

func (c *Cache) Size() int

Size returns the current number of cached sessions

func (*Cache) Stats

func (c *Cache) Stats() CacheStats

Stats returns cache statistics

type CacheConfig

type CacheConfig struct {
	MaxSize      int           // Maximum number of sessions to cache
	DefaultTTL   time.Duration // Default TTL for cache entries
	CleanupIntvl time.Duration // Interval for cleanup routine
}

CacheConfig configures the session cache

func DefaultCacheConfig

func DefaultCacheConfig() CacheConfig

DefaultCacheConfig returns default cache configuration

type CacheStats

type CacheStats struct {
	Hits        int64
	Misses      int64
	Evictions   int64
	Expirations int64
	Size        int
	MaxSize     int
}

CacheStats contains cache statistics

type CachedSession

type CachedSession struct {
	Session      *Session
	AccessCount  int
	CreatedAt    time.Time
	LastAccessed time.Time
	ExpiresAt    time.Time
	Size         int // Estimated size in bytes
}

CachedSession represents a cached session with metadata

type Manager

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

Manager 会话管理器

func NewManager

func NewManager(baseDir string) (*Manager, error)

NewManager 创建会话管理器

func (*Manager) Delete

func (m *Manager) Delete(key string) error

Delete 删除会话

func (*Manager) GetOrCreate

func (m *Manager) GetOrCreate(key string) (*Session, error)

GetOrCreate 获取或创建会话

func (*Manager) List

func (m *Manager) List() ([]string, error)

List 列出所有会话

func (*Manager) Save

func (m *Manager) Save(session *Session) error

Save 保存会话

type Media

type Media struct {
	Type     string `json:"type"`             // image, video, audio, document
	URL      string `json:"url"`              // 文件URL
	Base64   string `json:"base64,omitempty"` // Base64编码内容
	MimeType string `json:"mimetype"`         // MIME类型
}

Media 媒体文件

type Message

type Message struct {
	Role       string                 `json:"role"` // user, assistant, system, tool
	Content    string                 `json:"content"`
	Media      []Media                `json:"media,omitempty"`
	Timestamp  time.Time              `json:"timestamp"`
	Metadata   map[string]interface{} `json:"metadata,omitempty"`
	ToolCallID string                 `json:"tool_call_id,omitempty"` // For tool role
	ToolCalls  []ToolCall             `json:"tool_calls,omitempty"`   // For assistant role
}

Message 消息

type PruneConfig

type PruneConfig struct {
	Strategy           PruneStrategy
	MaxTotalSessions   int
	MaxTotalMessages   int
	MaxTotalTokens     int
	DefaultMessageTTL  time.Duration
	DMPreserveCount    int // Minimum messages to preserve in DM
	GroupPreserveCount int // Minimum messages to preserve in group
}

PruneConfig configures session pruning behavior

func DefaultPruneConfig

func DefaultPruneConfig() PruneConfig

DefaultPruneConfig returns default pruning configuration

type PruneStats

type PruneStats struct {
	TotalPrunes     int64
	MessagesPruned  int64
	SessionsPruned  int64
	TokensReclaimed int64
	LastPruneAt     time.Time
}

PruneStats contains pruning statistics

type PruneStrategy

type PruneStrategy string

PruneStrategy defines how sessions should be pruned

const (
	// PruneStrategyLRU removes least recently used sessions
	PruneStrategyLRU PruneStrategy = "lru"
	// PruneStrategyLFU removes least frequently used sessions
	PruneStrategyLFU PruneStrategy = "lfu"
	// PruneStrategyTTL removes sessions past their TTL
	PruneStrategyTTL PruneStrategy = "ttl"
	// PruneStrategySemantic uses semantic similarity to deduplicate
	PruneStrategySemantic PruneStrategy = "semantic"
	// PruneStrategySize removes largest sessions first
	PruneStrategySize PruneStrategy = "size"
)

type Pruner

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

Pruner manages session pruning operations

func NewPruner

func NewPruner(manager *Manager, config PruneConfig) *Pruner

NewPruner creates a new session pruner

func (*Pruner) Cleanup

func (p *Pruner) Cleanup() error

Cleanup removes expired data and optimizes storage

func (*Pruner) CompactSession

func (p *Pruner) CompactSession(sessionKey string) error

CompactSession compacts a session by summarizing older messages

func (*Pruner) EstimateMessages

func (p *Pruner) EstimateMessages(sessionKey string) int

EstimateTokens estimates the token count for messages

func (*Pruner) GetConfig

func (p *Pruner) GetConfig() PruneConfig

GetConfig returns the current prune configuration

func (*Pruner) GetStats

func (p *Pruner) GetStats() PruneStats

GetStats returns pruning statistics

func (*Pruner) PruneByType

func (p *Pruner) PruneByType(sessionKey string, isDM bool) error

PruneByType prunes messages based on session type (DM vs Group)

func (*Pruner) PruneMessages

func (p *Pruner) PruneMessages(sessionKey string, preserveCount int) error

PruneMessages prunes messages within a session based on TTL

func (*Pruner) PruneMessagesByTTL

func (p *Pruner) PruneMessagesByTTL(sessionKey string) error

PruneMessagesByTTL prunes messages based on their time-to-live

func (*Pruner) PruneSessions

func (p *Pruner) PruneSessions() error

PruneSessions prunes sessions based on the configured strategy

func (*Pruner) SetConfig

func (p *Pruner) SetConfig(config PruneConfig)

SetConfig updates the prune configuration

func (*Pruner) ShouldCompact

func (p *Pruner) ShouldCompact(sessionKey string, estimatedTokens int) bool

ShouldCompact determines if a session should be compacted

type Session

type Session struct {
	Key       string                 `json:"key"`
	Messages  []Message              `json:"messages"`
	CreatedAt time.Time              `json:"created_at"`
	UpdatedAt time.Time              `json:"updated_at"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
	// contains filtered or unexported fields
}

Session 会话

func (*Session) AddMessage

func (s *Session) AddMessage(msg Message)

AddMessage 添加消息

func (*Session) Clear

func (s *Session) Clear()

Clear 清空消息

func (*Session) GetHistory

func (s *Session) GetHistory(maxMessages int) []Message

GetHistory 获取历史消息

func (*Session) GetHistorySafe added in v0.3.1

func (s *Session) GetHistorySafe(maxMessages int) []Message

GetHistorySafe 获取历史消息,确保不会在工具调用中间截断 这样可以保证消息的完整性和顺序

type SessionDiff

type SessionDiff struct {
	ID1             string    `json:"id1"`
	ID2             string    `json:"id2"`
	Messages1       int       `json:"messages1"`
	Messages2       int       `json:"messages2"`
	AddedMessages   int       `json:"added_messages"`
	RemovedMessages int       `json:"removed_messages"`
	AddedContent    []Message `json:"added_content,omitempty"`
	RemovedContent  []Message `json:"removed_content,omitempty"`
}

SessionDiff represents differences between two sessions

type SessionNode

type SessionNode struct {
	ID         string      `json:"id"`
	Session    *Session    `json:"session"`
	ParentID   string      `json:"parent_id,omitempty"`
	ChildIDs   []string    `json:"child_ids,omitempty"`
	BranchInfo *BranchInfo `json:"branch_info,omitempty"`
	CreatedAt  time.Time   `json:"created_at"`
}

SessionNode represents a node in the session tree

type SessionTree

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

SessionTree manages a tree structure of sessions with branching

func NewSessionTree

func NewSessionTree(rootSession *Session) (*SessionTree, error)

NewSessionTree creates a new session tree

func (*SessionTree) CompareSessions

func (t *SessionTree) CompareSessions(id1, id2 string) (*SessionDiff, error)

CompareSessions compares two sessions and returns differences

func (*SessionTree) CountNodes

func (t *SessionTree) CountNodes() int

CountNodes returns the total number of nodes

func (*SessionTree) CreateBranch

func (t *SessionTree) CreateBranch(parentID string, branchSession *Session, branchName string, createdBy string) (string, error)

CreateBranch creates a new branch from the current session state

func (*SessionTree) DeleteNode

func (t *SessionTree) DeleteNode(id string, recursive bool) error

DeleteNode removes a node and its subtree

func (*SessionTree) FindNodesByBranchName

func (t *SessionTree) FindNodesByBranchName(name string) []*SessionNode

FindNodesByBranchName finds nodes with matching branch name

func (*SessionTree) GetBranches

func (t *SessionTree) GetBranches() []*SessionNode

GetBranches returns all branches (non-main nodes)

func (*SessionTree) GetChildren

func (t *SessionTree) GetChildren(id string) ([]*SessionNode, error)

GetChildren returns all children of a node

func (*SessionTree) GetMaxDepth

func (t *SessionTree) GetMaxDepth() int

GetMaxDepth returns the maximum branch depth

func (*SessionTree) GetNode

func (t *SessionTree) GetNode(id string) (*SessionNode, error)

GetNode retrieves a node by ID

func (*SessionTree) GetPath

func (t *SessionTree) GetPath(id string) ([]*SessionNode, error)

GetPath returns the path from root to the specified node

func (*SessionTree) GetRoot

func (t *SessionTree) GetRoot() (*SessionNode, error)

GetRoot returns the root node

func (*SessionTree) GetStatistics

func (t *SessionTree) GetStatistics() *TreeStatistics

GetStatistics returns statistics about the session tree

func (*SessionTree) ListNodes

func (t *SessionTree) ListNodes() []*SessionNode

ListNodes returns all nodes in the tree

func (*SessionTree) MergeBranch

func (t *SessionTree) MergeBranch(branchID string) error

MergeBranch merges a branch back into its parent

func (*SessionTree) SetMaxDepth

func (t *SessionTree) SetMaxDepth(depth int)

SetMaxDepth sets the maximum branch depth

func (*SessionTree) SwitchBranch

func (t *SessionTree) SwitchBranch(fromID, toID string) (*Session, error)

SwitchBranch switches the active branch to a different branch

type ToolCall

type ToolCall struct {
	ID     string                 `json:"id"`
	Name   string                 `json:"name"`
	Params map[string]interface{} `json:"params"`
}

ToolCall 工具调用

type TreeStatistics

type TreeStatistics struct {
	TotalNodes  int `json:"total_nodes"`
	MaxDepth    int `json:"max_depth"`
	ActualDepth int `json:"actual_depth"`
	BranchCount int `json:"branch_count"`
	MergedCount int `json:"merged_count"`
}

TreeStatistics contains statistics about the session tree

Jump to

Keyboard shortcuts

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