session

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package session provides session persistence for Aixgo agents. Sessions enable agents to maintain conversation history, checkpoint state, and resume from previous interactions.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSessionNotFound is returned when a session doesn't exist.
	ErrSessionNotFound = errors.New("session not found")
	// ErrCheckpointNotFound is returned when a checkpoint doesn't exist.
	ErrCheckpointNotFound = errors.New("checkpoint not found")
	// ErrStorageClosed is returned when operating on a closed storage backend.
	ErrStorageClosed = errors.New("storage backend is closed")
)

Common errors for storage operations.

View Source
var ErrInvalidPathComponent = errors.New("invalid path component: contains path separator or traversal sequence")

ErrInvalidPathComponent is returned when a path component contains unsafe characters.

View Source
var ErrSessionNotInContext = errors.New("session not found in context")

ErrSessionNotInContext is returned when no session is found in context.

Functions

func ContextWithSession

func ContextWithSession(ctx context.Context, sess Session) context.Context

ContextWithSession adds a session to the context.

func IsCheckpointable

func IsCheckpointable(a any) bool

IsCheckpointable checks if an agent implements CheckpointableAgent.

func IsMemoryAware

func IsMemoryAware(a any) bool

IsMemoryAware checks if an agent implements MemoryAwareAgent.

func IsSessionAware

func IsSessionAware(a any) bool

IsSessionAware checks if an agent implements SessionAwareAgent.

Types

type Checkpoint

type Checkpoint struct {
	// ID is the unique checkpoint identifier.
	ID string `json:"id"`
	// SessionID links to the parent session.
	SessionID string `json:"sessionId"`
	// Timestamp is when the checkpoint was created.
	Timestamp time.Time `json:"timestamp"`
	// EntryID is the session entry this checkpoint was created at.
	EntryID string `json:"entryId"`
	// Checksum verifies integrity of entries up to this checkpoint.
	Checksum string `json:"checksum"`
	// Metadata contains optional checkpoint-specific data.
	Metadata map[string]any `json:"metadata,omitempty"`
}

Checkpoint represents a restorable state snapshot. Checkpoints allow resuming a session from a specific point.

type CheckpointConfig

type CheckpointConfig struct {
	// AutoSave enables automatic checkpoint creation.
	AutoSave bool `yaml:"auto_save"`

	// Interval is the auto-save interval (e.g., "5m").
	Interval string `yaml:"interval"`
}

CheckpointConfig holds checkpoint-specific settings.

type CheckpointableAgent

type CheckpointableAgent interface {
	// CreateCheckpoint captures the agent's internal state for later restoration.
	// Returns the state as a map that will be stored in the checkpoint.
	CreateCheckpoint(ctx context.Context) (map[string]any, error)

	// RestoreFromCheckpoint restores the agent's internal state from a checkpoint.
	RestoreFromCheckpoint(ctx context.Context, state map[string]any) error
}

CheckpointableAgent is an optional interface for agents that support creating and restoring from checkpoints with custom state.

type Config

type Config struct {
	// Enabled determines whether sessions are active.
	// Default: true (sessions are enabled by default).
	Enabled bool `yaml:"enabled"`

	// Store specifies the storage backend type.
	// Options: "file", "firestore", "postgres"
	// Default: "file"
	Store string `yaml:"store"`

	// BaseDir is the base directory for file-based storage.
	// Default: ~/.aixgo/sessions
	BaseDir string `yaml:"base_dir"`

	// Checkpoint contains checkpoint configuration.
	Checkpoint CheckpointConfig `yaml:"checkpoint,omitempty"`
}

Config holds session configuration from YAML.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default session configuration.

type CreateOptions

type CreateOptions struct {
	// UserID identifies the user for this session.
	UserID string
	// Metadata contains optional session metadata.
	Metadata map[string]any
}

CreateOptions configures session creation.

type EntryType

type EntryType string

EntryType defines the type of session entry.

const (
	// EntryTypeMessage represents a conversation message.
	EntryTypeMessage EntryType = "message"
	// EntryTypeCheckpoint represents a state checkpoint.
	EntryTypeCheckpoint EntryType = "checkpoint"
	// EntryTypeMetadata represents session metadata updates.
	EntryTypeMetadata EntryType = "metadata"
)

type FileBackend

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

FileBackend implements StorageBackend using JSONL files. Storage layout:

~/.aixgo/sessions/
  └── <agent-name>/
      ├── sessions.json          # Session index
      ├── <session-id>.jsonl     # Session entries
      └── checkpoints/
          └── <checkpoint-id>.json

func NewFileBackend

func NewFileBackend(baseDir string) (*FileBackend, error)

NewFileBackend creates a new file-based storage backend. If baseDir is empty, uses ~/.aixgo/sessions.

func (*FileBackend) AppendEntry

func (f *FileBackend) AppendEntry(ctx context.Context, sessionID string, entry *SessionEntry) error

AppendEntry adds an entry to a session (append-only).

func (*FileBackend) Close

func (f *FileBackend) Close() error

Close releases any resources held by the backend.

func (*FileBackend) DeleteSession

func (f *FileBackend) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession removes a session and all its entries.

func (*FileBackend) ListSessions

func (f *FileBackend) ListSessions(ctx context.Context, agentName string, opts ListOptions) ([]*SessionMetadata, error)

ListSessions returns sessions for an agent matching the filter options.

func (*FileBackend) LoadCheckpoint

func (f *FileBackend) LoadCheckpoint(ctx context.Context, checkpointID string) (*Checkpoint, error)

LoadCheckpoint retrieves a checkpoint by ID.

func (*FileBackend) LoadEntries

func (f *FileBackend) LoadEntries(ctx context.Context, sessionID string) ([]*SessionEntry, error)

LoadEntries retrieves all entries for a session in order.

func (*FileBackend) LoadSession

func (f *FileBackend) LoadSession(ctx context.Context, sessionID string) (*SessionMetadata, error)

LoadSession retrieves session metadata by ID.

func (*FileBackend) SaveCheckpoint

func (f *FileBackend) SaveCheckpoint(ctx context.Context, checkpoint *Checkpoint) error

SaveCheckpoint stores a checkpoint.

func (*FileBackend) SaveSession

func (f *FileBackend) SaveSession(ctx context.Context, meta *SessionMetadata) error

SaveSession creates or updates session metadata.

type ListOptions

type ListOptions struct {
	// UserID filters sessions by user.
	UserID string
	// Limit caps the number of results.
	Limit int
	// Offset skips the first N results.
	Offset int
}

ListOptions provides filtering for session listing.

type Manager

type Manager interface {
	// Create creates a new session for an agent.
	Create(ctx context.Context, agentName string, opts CreateOptions) (Session, error)

	// Get retrieves an existing session by ID.
	// Returns ErrSessionNotFound if the session doesn't exist.
	Get(ctx context.Context, sessionID string) (Session, error)

	// GetOrCreate returns an existing session or creates a new one.
	// If userID is provided, it looks for existing sessions for that user.
	GetOrCreate(ctx context.Context, agentName, userID string) (Session, error)

	// List returns sessions for an agent matching the filter options.
	List(ctx context.Context, agentName string, opts ListOptions) ([]*SessionMetadata, error)

	// Delete removes a session and all its data.
	Delete(ctx context.Context, sessionID string) error

	// Close releases resources held by the manager.
	Close() error
}

Manager manages session lifecycle. Manager is safe for concurrent use.

func NewManager

func NewManager(backend StorageBackend) Manager

NewManager creates a new session manager with the given storage backend.

type MemoryAwareAgent

type MemoryAwareAgent interface {
	// SetMemory provides the agent with access to long-term memory.
	// Called before execution when sessions are enabled.
	SetMemory(ctx context.Context, memory MemoryReader) error
}

MemoryAwareAgent is an optional interface for agents that want direct access to long-term memory during execution.

type MemoryEntry

type MemoryEntry struct {
	Key       string
	Value     string
	Timestamp string
	Source    string
}

MemoryEntry represents a single memory item.

type MemoryReader

type MemoryReader interface {
	// Read retrieves a value from memory by key.
	Read(ctx context.Context, key string) (string, error)

	// Search performs semantic search over memory.
	Search(ctx context.Context, query string, limit int) ([]MemoryEntry, error)

	// List returns all memory keys.
	List(ctx context.Context) ([]string, error)
}

MemoryReader provides read access to agent memory. This is a subset of the full memory manager for safety.

type RedisBackend

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

RedisBackend implements StorageBackend using Redis. It provides distributed session storage suitable for multi-node deployments.

func NewRedisBackend

func NewRedisBackend(cfg RedisConfig) (*RedisBackend, error)

NewRedisBackend creates a new Redis storage backend.

func NewRedisBackendFromClient

func NewRedisBackendFromClient(client *redis.Client, prefix string, ttl time.Duration) *RedisBackend

NewRedisBackendFromClient creates a Redis backend from an existing client. This is useful for testing with miniredis.

func (*RedisBackend) AppendEntry

func (b *RedisBackend) AppendEntry(ctx context.Context, sessionID string, entry *SessionEntry) error

AppendEntry adds an entry to a session.

func (*RedisBackend) Close

func (b *RedisBackend) Close() error

Close releases resources held by the backend.

func (*RedisBackend) DeleteSession

func (b *RedisBackend) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession removes a session and all its data.

func (*RedisBackend) ListSessions

func (b *RedisBackend) ListSessions(ctx context.Context, agentName string, opts ListOptions) ([]*SessionMetadata, error)

ListSessions returns sessions for an agent matching filter options.

func (*RedisBackend) LoadCheckpoint

func (b *RedisBackend) LoadCheckpoint(ctx context.Context, checkpointID string) (*Checkpoint, error)

LoadCheckpoint retrieves a checkpoint by ID.

func (*RedisBackend) LoadEntries

func (b *RedisBackend) LoadEntries(ctx context.Context, sessionID string) ([]*SessionEntry, error)

LoadEntries retrieves all entries for a session in order.

func (*RedisBackend) LoadSession

func (b *RedisBackend) LoadSession(ctx context.Context, sessionID string) (*SessionMetadata, error)

LoadSession retrieves session metadata by ID.

func (*RedisBackend) Ping

func (b *RedisBackend) Ping(ctx context.Context) error

Ping checks if the Redis connection is alive.

func (*RedisBackend) SaveCheckpoint

func (b *RedisBackend) SaveCheckpoint(ctx context.Context, checkpoint *Checkpoint) error

SaveCheckpoint stores a checkpoint.

func (*RedisBackend) SaveSession

func (b *RedisBackend) SaveSession(ctx context.Context, meta *SessionMetadata) error

SaveSession creates or updates session metadata.

type RedisConfig

type RedisConfig struct {
	// Addr is the Redis server address (host:port).
	Addr string
	// Password is the Redis password (optional).
	Password string
	// DB is the Redis database number.
	DB int
	// Prefix is the key prefix for all session keys (default: "aixgo:session:").
	Prefix string
	// SessionTTL is the session expiry duration (0 = never expire).
	SessionTTL time.Duration
	// PoolSize is the connection pool size (default: 10).
	PoolSize int
}

RedisConfig holds Redis connection configuration.

type Session

type Session interface {
	// ID returns the unique session identifier.
	ID() string

	// AgentName returns the name of the agent this session belongs to.
	AgentName() string

	// UserID returns the user identifier (may be empty).
	UserID() string

	// AppendMessage adds a message to the session history.
	AppendMessage(ctx context.Context, msg *agent.Message) error

	// GetMessages retrieves all messages in the session.
	GetMessages(ctx context.Context) ([]*agent.Message, error)

	// Checkpoint creates a restorable state snapshot.
	Checkpoint(ctx context.Context) (*Checkpoint, error)

	// Restore reverts the session to a previous checkpoint.
	Restore(ctx context.Context, checkpointID string) error

	// Close releases any resources held by the session.
	Close(ctx context.Context) error
}

Session represents an active agent session. Sessions are safe for concurrent use.

func MustSessionFromContext

func MustSessionFromContext(ctx context.Context) Session

MustSessionFromContext retrieves a session from context and panics if not found. Prefer SessionFromContext with explicit error handling in production code.

func SessionFromContext

func SessionFromContext(ctx context.Context) (Session, bool)

SessionFromContext retrieves a session from the context. Returns the session and true if found, or nil and false if not present.

type SessionAwareAgent

type SessionAwareAgent interface {
	// ExecuteWithSession performs execution with access to session context.
	// The session provides access to conversation history and memory.
	ExecuteWithSession(ctx context.Context, input *agent.Message, sess Session) (*agent.Message, error)
}

SessionAwareAgent is an optional interface that agents can implement to support session-aware execution. Agents that don't implement this interface will still work with sessions via the runtime's CallWithSession, but won't have access to session history during execution.

type SessionEntry

type SessionEntry struct {
	// ID is the unique identifier for this entry.
	ID string `json:"id"`
	// ParentID links to the previous entry (for future branching support).
	ParentID string `json:"parentId,omitempty"`
	// Timestamp is when the entry was created.
	Timestamp time.Time `json:"timestamp"`
	// Type indicates what kind of entry this is.
	Type EntryType `json:"type"`
	// Data contains the entry payload.
	Data map[string]any `json:"data"`
}

SessionEntry represents a single entry in the session log. Entries are append-only and immutable once written.

type SessionKey

type SessionKey struct{}

SessionKey is the context key for storing sessions. Following the RuntimeKey pattern from internal/agent/types.go.

type SessionMetadata

type SessionMetadata struct {
	// ID is the unique session identifier.
	ID string `json:"id"`
	// AgentName is the name of the agent this session belongs to.
	AgentName string `json:"agentName"`
	// UserID identifies the user (optional).
	UserID string `json:"userId,omitempty"`
	// CreatedAt is when the session was created.
	CreatedAt time.Time `json:"createdAt"`
	// UpdatedAt is when the session was last modified.
	UpdatedAt time.Time `json:"updatedAt"`
	// MessageCount is the number of messages in the session.
	MessageCount int `json:"messageCount"`
	// CurrentLeaf is the ID of the current leaf entry (for future branching).
	CurrentLeaf string `json:"currentLeaf,omitempty"`
}

SessionMetadata holds session summary information. This is stored separately for quick listing without loading all entries.

type StorageBackend

type StorageBackend interface {
	// SaveSession creates or updates session metadata.
	SaveSession(ctx context.Context, meta *SessionMetadata) error

	// LoadSession retrieves session metadata by ID.
	// Returns ErrSessionNotFound if the session doesn't exist.
	LoadSession(ctx context.Context, sessionID string) (*SessionMetadata, error)

	// DeleteSession removes a session and all its entries.
	DeleteSession(ctx context.Context, sessionID string) error

	// ListSessions returns sessions for an agent matching the filter options.
	ListSessions(ctx context.Context, agentName string, opts ListOptions) ([]*SessionMetadata, error)

	// AppendEntry adds an entry to a session (append-only).
	AppendEntry(ctx context.Context, sessionID string, entry *SessionEntry) error

	// LoadEntries retrieves all entries for a session in order.
	LoadEntries(ctx context.Context, sessionID string) ([]*SessionEntry, error)

	// SaveCheckpoint stores a checkpoint.
	SaveCheckpoint(ctx context.Context, checkpoint *Checkpoint) error

	// LoadCheckpoint retrieves a checkpoint by ID.
	// Returns ErrCheckpointNotFound if the checkpoint doesn't exist.
	LoadCheckpoint(ctx context.Context, checkpointID string) (*Checkpoint, error)

	// Close releases any resources held by the backend.
	Close() error
}

StorageBackend abstracts session persistence. Implementations must be safe for concurrent use.

Jump to

Keyboard shortcuts

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