session

package
v0.0.0-...-8acab51 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// LegacyDefaultContextTokenBudget was the historical session default before
	// model-aware budgeting was introduced.
	LegacyDefaultContextTokenBudget = 8000
	// DefaultContextTokenBudget is the modern fallback when no explicit session
	// budget override is configured.
	DefaultContextTokenBudget = agentcore.DefaultContextTokens
)

Variables

This section is empty.

Functions

func NormalizeExtractedMemoryForStorage

func NormalizeExtractedMemoryForStorage(extracted string) string

NormalizeExtractedMemoryForStorage cleans extracted session memory so that only durable user/project context is persisted into long-term storage.

func NormalizeMemoryFingerprint

func NormalizeMemoryFingerprint(content string) string

NormalizeMemoryFingerprint returns a canonical form used for dedupe.

func NormalizeTokenBudget

func NormalizeTokenBudget(maxTokens int) int

NormalizeTokenBudget converts config/session budget values into a realistic fallback budget for model-agnostic session contexts.

Types

type CompactionResult

type CompactionResult struct {
	Summary           string        `json:"summary"`
	PreservedMessages int           `json:"preserved_messages"`
	RemovedMessages   int           `json:"removed_messages"`
	TokensBefore      int           `json:"tokens_before"`
	TokensAfter       int           `json:"tokens_after"`
	TokensSaved       int           `json:"tokens_saved"`
	Duration          time.Duration `json:"duration"`
}

CompactionResult holds the result of compaction.

type CompactorMemoryIntegration

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

CompactorMemoryIntegration adds memory refresh capability to SessionCompactor.

func NewCompactorMemoryIntegration

func NewCompactorMemoryIntegration(
	compactor *SessionCompactor,
	memoryRefresher MemoryRefresher,
	llmProvider llm.Provider,
	config MemoryRefreshConfig,
) *CompactorMemoryIntegration

NewCompactorMemoryIntegration creates a new compactor with memory integration.

func (*CompactorMemoryIntegration) CompactWithMemoryRefresh

func (c *CompactorMemoryIntegration) CompactWithMemoryRefresh(ctx context.Context, session *Session) (*CompactionResult, error)

CompactWithMemoryRefresh performs compaction with memory refresh.

func (*CompactorMemoryIntegration) RefreshMemoryBeforeCompaction

func (c *CompactorMemoryIntegration) RefreshMemoryBeforeCompaction(ctx context.Context, session *Session) error

RefreshMemoryBeforeCompaction extracts and saves important information before compaction.

func (*CompactorMemoryIntegration) ShouldCompact

func (c *CompactorMemoryIntegration) ShouldCompact(session *Session) bool

ShouldCompact delegates to the underlying compactor.

func (*CompactorMemoryIntegration) ShouldCompactOnTransition

func (c *CompactorMemoryIntegration) ShouldCompactOnTransition(previousRatio float64, session *Session) bool

ShouldCompactOnTransition returns true only when token usage crosses from below hard threshold into compaction window.

func (*CompactorMemoryIntegration) ShouldRefreshMemory

func (c *CompactorMemoryIntegration) ShouldRefreshMemory(session *Session) bool

ShouldRefreshMemory checks if memory refresh should be triggered (soft threshold).

func (*CompactorMemoryIntegration) ShouldRefreshMemoryOnTransition

func (c *CompactorMemoryIntegration) ShouldRefreshMemoryOnTransition(previousRatio float64, session *Session) bool

ShouldRefreshMemoryOnTransition returns true only when token usage crosses from below soft threshold into the refresh window.

type EndReason

type EndReason string

EndReason indicates why a session ended.

const (
	// EndReasonArchive indicates the session was archived.
	EndReasonArchive EndReason = "archive"
	// EndReasonReset indicates the session was reset.
	EndReasonReset EndReason = "reset"
	// EndReasonDelete indicates the session was deleted.
	EndReasonDelete EndReason = "delete"
	// EndReasonTimeout indicates the session timed out.
	EndReasonTimeout EndReason = "timeout"
	// EndReasonNew indicates a new session was started (via /new command).
	EndReasonNew EndReason = "new"
)

type HookManager

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

HookManager manages session hooks.

func NewHookManager

func NewHookManager() *HookManager

NewHookManager creates a new hook manager.

func (*HookManager) Register

func (m *HookManager) Register(hook SessionHook)

Register registers a hook.

func (*HookManager) TriggerSessionEnd

func (m *HookManager) TriggerSessionEnd(ctx context.Context, session *Session, reason EndReason)

TriggerSessionEnd triggers all hooks for session end.

type InMemorySessionStore

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

InMemorySessionStore implements SessionStore using in-memory storage.

func NewInMemorySessionStore

func NewInMemorySessionStore(maxTokens int) *InMemorySessionStore

NewInMemorySessionStore creates a new InMemorySessionStore.

func (*InMemorySessionStore) Archive

func (s *InMemorySessionStore) Archive(id SessionID) error

func (*InMemorySessionStore) Close

func (s *InMemorySessionStore) Close() error

func (*InMemorySessionStore) Delete

func (s *InMemorySessionStore) Delete(id SessionID) error

func (*InMemorySessionStore) List

func (s *InMemorySessionStore) List(filter SessionFilter) ([]*Session, error)

func (*InMemorySessionStore) Load

func (s *InMemorySessionStore) Load(id SessionID) (*Session, error)

func (*InMemorySessionStore) Save

func (s *InMemorySessionStore) Save(session *Session) error

type MemoryRefreshConfig

type MemoryRefreshConfig struct {
	// Enabled enables memory refresh before compaction.
	Enabled bool `json:"enabled" yaml:"enabled"`
	// SoftThresholdRatio triggers memory refresh (e.g., 0.6 = 60% of max tokens).
	SoftThresholdRatio float64 `json:"soft_threshold_ratio" yaml:"soft_threshold_ratio"`
	// SystemPrompt for extracting important information.
	SystemPrompt string `json:"system_prompt" yaml:"system_prompt"`
	// MaxExtractTokens limits the extraction response.
	MaxExtractTokens int `json:"max_extract_tokens" yaml:"max_extract_tokens"`
}

MemoryRefreshConfig holds configuration for memory refresh before compaction.

func DefaultMemoryRefreshConfig

func DefaultMemoryRefreshConfig() MemoryRefreshConfig

DefaultMemoryRefreshConfig returns default configuration.

type MemoryRefresher

type MemoryRefresher interface {
	// RefreshMemory stores already-extracted important information.
	RefreshMemory(ctx context.Context, extracted string, sessionID string) error
}

MemoryRefresher interface for memory integration during compaction.

type SQLiteSessionStore

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

SQLiteSessionStore implements SessionStore using SQLite.

func NewSQLiteSessionStore

func NewSQLiteSessionStore(dbPath string, maxTokens int) (*SQLiteSessionStore, error)

NewSQLiteSessionStore creates a new SQLiteSessionStore.

func (*SQLiteSessionStore) Archive

func (s *SQLiteSessionStore) Archive(id SessionID) error

Archive archives a session.

func (*SQLiteSessionStore) Close

func (s *SQLiteSessionStore) Close() error

Close closes the database connection.

func (*SQLiteSessionStore) Delete

func (s *SQLiteSessionStore) Delete(id SessionID) error

Delete deletes a session from the database.

func (*SQLiteSessionStore) List

func (s *SQLiteSessionStore) List(filter SessionFilter) ([]*Session, error)

List lists sessions matching the filter.

func (*SQLiteSessionStore) Load

func (s *SQLiteSessionStore) Load(id SessionID) (*Session, error)

Load loads a session from the database.

func (*SQLiteSessionStore) Save

func (s *SQLiteSessionStore) Save(session *Session) error

Save saves a session to the database.

type Session

type Session struct {
	ID           SessionID                    `json:"id"`
	Context      *context.ConversationContext `json:"-"`
	Metadata     SessionMetadata              `json:"metadata"`
	State        SessionState                 `json:"state"`
	CreatedAt    time.Time                    `json:"created_at"`
	UpdatedAt    time.Time                    `json:"updated_at"`
	LastActiveAt time.Time                    `json:"last_active_at"`
	CompactedAt  *time.Time                   `json:"compacted_at,omitempty"`
	// contains filtered or unexported fields
}

Session represents a conversation session.

func NewSession

func NewSession(id SessionID, maxTokens int) *Session

NewSession creates a new session.

func (*Session) AddMessage

func (s *Session) AddMessage(msg context.Message)

AddMessage adds a message to the session.

func (*Session) AddTag

func (s *Session) AddTag(tag string)

AddTag adds a tag to the session.

func (*Session) Clear

func (s *Session) Clear()

Clear clears all messages but keeps the system prompt.

func (*Session) GetCustomData

func (s *Session) GetCustomData(key string) (string, bool)

GetCustomData returns custom data.

func (*Session) GetMessages

func (s *Session) GetMessages() []context.Message

GetMessages returns all messages in the session.

func (*Session) GetState

func (s *Session) GetState() SessionState

GetState returns the session state.

func (*Session) GetSummary

func (s *Session) GetSummary() string

GetSummary returns the session summary.

func (*Session) GetTags

func (s *Session) GetTags() []string

GetTags returns all tags.

func (*Session) GetTitle

func (s *Session) GetTitle() string

GetTitle returns the session title.

func (*Session) Info

func (s *Session) Info() SessionInfo

Info returns session information.

func (*Session) IsActive

func (s *Session) IsActive() bool

IsActive returns true if the session is active.

func (*Session) MaxTokens

func (s *Session) MaxTokens() int

MaxTokens returns the maximum token limit.

func (*Session) RemoveTag

func (s *Session) RemoveTag(tag string)

RemoveTag removes a tag from the session.

func (*Session) SetCustomData

func (s *Session) SetCustomData(key, value string)

SetCustomData sets custom data.

func (*Session) SetState

func (s *Session) SetState(state SessionState)

SetState sets the session state.

func (*Session) SetSummary

func (s *Session) SetSummary(summary string)

SetSummary sets the session summary (from compaction).

func (*Session) SetSystemPrompt

func (s *Session) SetSystemPrompt(prompt string)

SetSystemPrompt sets the system prompt.

func (*Session) SetTitle

func (s *Session) SetTitle(title string)

SetTitle sets the session title.

func (*Session) TokenCount

func (s *Session) TokenCount() int

TokenCount returns the current token count.

func (*Session) TokenUsageRatio

func (s *Session) TokenUsageRatio() float64

TokenUsageRatio returns the ratio of used tokens to max tokens.

type SessionCompactor

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

SessionCompactor handles session compaction with summarization.

func NewSessionCompactor

func NewSessionCompactor(provider llm.Provider, cfg config.SessionCompactionConfig) *SessionCompactor

NewSessionCompactor creates a new SessionCompactor.

func (*SessionCompactor) Compact

func (c *SessionCompactor) Compact(session *Session) (*CompactionResult, error)

Compact compacts a session by summarizing old messages.

func (*SessionCompactor) CompactWithCustomPrompt

func (c *SessionCompactor) CompactWithCustomPrompt(session *Session, prompt string) (*CompactionResult, error)

CompactWithCustomPrompt compacts with a custom summarization prompt.

func (*SessionCompactor) ShouldCompact

func (c *SessionCompactor) ShouldCompact(session *Session) bool

ShouldCompact returns true if the session should be compacted.

type SessionFilter

type SessionFilter struct {
	AgentID       string
	ChannelID     string
	PeerID        string
	State         *SessionState
	CreatedAfter  *time.Time
	CreatedBefore *time.Time
	Limit         int
	Offset        int
}

SessionFilter for querying sessions.

type SessionHook

type SessionHook interface {
	// OnSessionEnd is called when a session ends (archive or reset).
	OnSessionEnd(ctx context.Context, session *Session, reason EndReason) error
}

SessionHook defines a hook that can be triggered on session events.

type SessionID

type SessionID struct {
	AgentID   string `json:"agent_id"`
	ChannelID string `json:"channel_id"`
	PeerID    string `json:"peer_id"`
	ThreadID  string `json:"thread_id,omitempty"`
}

SessionID uniquely identifies a session.

func ParseSessionID

func ParseSessionID(s string) (SessionID, error)

ParseSessionID parses a session ID string.

func (SessionID) String

func (s SessionID) String() string

String returns the string representation of SessionID.

type SessionInfo

type SessionInfo struct {
	ID           string     `json:"id"`
	AgentID      string     `json:"agent_id"`
	ChannelID    string     `json:"channel_id"`
	PeerID       string     `json:"peer_id"`
	ThreadID     string     `json:"thread_id,omitempty"`
	State        string     `json:"state"`
	Title        string     `json:"title,omitempty"`
	Summary      string     `json:"summary,omitempty"`
	MessageCount int        `json:"message_count"`
	TokenCount   int        `json:"token_count"`
	MaxTokens    int        `json:"max_tokens"`
	TokenUsage   float64    `json:"token_usage"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
	LastActiveAt time.Time  `json:"last_active_at"`
	CompactedAt  *time.Time `json:"compacted_at,omitempty"`
}

SessionInfo represents session information for API responses.

type SessionManager

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

SessionManager manages sessions with isolation and persistence.

func NewSessionManager

func NewSessionManager(cfg config.SessionConfig, store SessionStore, compactor *SessionCompactor) *SessionManager

NewSessionManager creates a new SessionManager.

func (*SessionManager) AddMessage

func (m *SessionManager) AddMessage(id SessionID, msg ctxpkg.Message) error

AddMessage adds a message to a session.

func (*SessionManager) Archive

func (m *SessionManager) Archive(id SessionID) error

Archive archives a session.

func (*SessionManager) Compact

func (m *SessionManager) Compact(id SessionID) (*CompactionResult, error)

Compact compacts a session.

func (*SessionManager) Delete

func (m *SessionManager) Delete(id SessionID) error

Delete deletes a session.

func (*SessionManager) Get

func (m *SessionManager) Get(id SessionID) (*Session, bool)

Get gets a session by ID.

func (*SessionManager) GetMessages

func (m *SessionManager) GetMessages(id SessionID) ([]ctxpkg.Message, error)

GetMessages gets all messages from a session.

func (*SessionManager) GetOrCreate

func (m *SessionManager) GetOrCreate(id SessionID) (*Session, error)

GetOrCreate gets an existing session or creates a new one.

func (*SessionManager) List

func (m *SessionManager) List(filter SessionFilter) ([]*Session, error)

List lists sessions matching the filter.

func (*SessionManager) NewSession

func (m *SessionManager) NewSession(id SessionID) (*Session, error)

NewSession starts a new session, saving the current one to memory first. This is triggered by the /new command.

func (*SessionManager) Recover

func (m *SessionManager) Recover() error

Recover recovers sessions from persistence.

func (*SessionManager) RegisterHook

func (m *SessionManager) RegisterHook(hook SessionHook)

RegisterHook registers a session hook.

func (*SessionManager) Reset

func (m *SessionManager) Reset(id SessionID) error

Reset resets a session (clears messages but keeps system prompt).

func (*SessionManager) SetCompactorMemoryIntegration

func (m *SessionManager) SetCompactorMemoryIntegration(integration *CompactorMemoryIntegration)

SetCompactorMemoryIntegration attaches memory-refresh integration to the normal compaction path. Nil disables memory refresh integration.

func (*SessionManager) Stats

Stats returns session manager statistics.

func (*SessionManager) Stop

func (m *SessionManager) Stop() error

Stop stops the session manager.

type SessionManagerStats

type SessionManagerStats struct {
	TotalSessions    int `json:"total_sessions"`
	ActiveSessions   int `json:"active_sessions"`
	IdleSessions     int `json:"idle_sessions"`
	ArchivedSessions int `json:"archived_sessions"`
	TotalMessages    int `json:"total_messages"`
	TotalTokens      int `json:"total_tokens"`
}

SessionManagerStats holds session manager statistics.

type SessionMetadata

type SessionMetadata struct {
	Title           string            `json:"title,omitempty"`
	Summary         string            `json:"summary,omitempty"`
	Tags            []string          `json:"tags,omitempty"`
	CustomData      map[string]string `json:"custom_data,omitempty"`
	MessageCount    int               `json:"message_count"`
	TokenCount      int               `json:"token_count"`
	CompactionCount int               `json:"compaction_count"`
}

SessionMetadata holds session metadata.

type SessionState

type SessionState int

SessionState represents session lifecycle state.

const (
	SessionStateActive SessionState = iota
	SessionStateIdle
	SessionStateCompacting
	SessionStateSuspended
	SessionStateArchived
)

func (SessionState) String

func (s SessionState) String() string

String returns the string representation of SessionState.

type SessionStore

type SessionStore interface {
	Save(session *Session) error
	Load(id SessionID) (*Session, error)
	Delete(id SessionID) error
	List(filter SessionFilter) ([]*Session, error)
	Archive(id SessionID) error
	Close() error
}

SessionStore interface for session persistence.

Jump to

Keyboard shortcuts

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