session

package
v0.1.0-p8a.2 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LifecycleNever    = "never"
	LifecycleCalendar = "calendar"
	LifecycleIdle     = "idle"
	LifecycleMaxAge   = "max_age"
)
View Source
const ScopeVersionV1 = 1

ScopeVersionV1 is the first structured session-scope schema version.

View Source
const ScopeVersionV2 = 2

ScopeVersionV2 adds stable route-scope and lifecycle-epoch provenance.

Variables

This section is empty.

Functions

func BuildLegacyDirectAliases

func BuildLegacyDirectAliases(agentID, channel, account, peerID string) []string

func BuildLegacyMainAlias

func BuildLegacyMainAlias(agentID string) string

func BuildLegacyPeerAlias

func BuildLegacyPeerAlias(agentID, channel, peerKind, peerID string) string

func BuildMainSessionKey

func BuildMainSessionKey(agentID string) string

BuildMainSessionKey returns the canonical opaque main-session key for an agent. The corresponding legacy alias remains available via BuildLegacyMainAlias for compatibility and migration logic.

func BuildOpaqueSessionKey

func BuildOpaqueSessionKey(alias string) string

BuildOpaqueSessionKey returns a stable opaque session key derived from a canonical alias string. The alias remains available through metadata for compatibility and migration purposes.

func BuildSessionKey

func BuildSessionKey(scope SessionScope) string

BuildSessionKey returns the current opaque key for a structured session scope.

func CanonicalScopeSignature

func CanonicalScopeSignature(scope SessionScope) string

CanonicalScopeSignature returns a stable serialized representation of scope.

func CanonicalSessionIdentityID

func CanonicalSessionIdentityID(channel, rawID string, identityLinks map[string][]string) string

CanonicalSessionIdentityID collapses an identity using identity_links when possible, then returns a normalized lowercase identifier.

func IsExplicitSessionKey

func IsExplicitSessionKey(key string) bool

func IsLegacyAgentSessionKey

func IsLegacyAgentSessionKey(key string) bool

func IsOpaqueSessionKey

func IsOpaqueSessionKey(key string) bool

IsOpaqueSessionKey returns true when the key matches the current opaque session-key format.

func ResolveAgentID

func ResolveAgentID(store any, sessionKey string) string

ResolveAgentID returns the routed agent ID associated with a session. It prefers structured session scope metadata when available and falls back to legacy agent-scoped session keys for compatibility.

Types

type Allocation

type Allocation struct {
	Scope          SessionScope
	RouteScopeKey  string
	SessionKey     string
	SessionAliases []string
	MainSessionKey string
	MainAliases    []string
}

Allocation contains the concrete session keys selected for a routed turn. The current implementation intentionally preserves the legacy session-key layout while moving key construction out of the router.

func AllocateRouteSession

func AllocateRouteSession(input AllocationInput) Allocation

AllocateRouteSession maps a route decision onto a structured scope and the current opaque session-key format.

type AllocationInput

type AllocationInput struct {
	AgentID       string
	Context       bus.InboundContext
	SessionPolicy routing.SessionPolicy
}

AllocationInput contains the routing result and peer context needed to derive the session keys for a turn.

type ErrorAwareHistoryReader

type ErrorAwareHistoryReader interface {
	GetHistoryWithError(sessionKey string) ([]providers.Message, error)
}

ErrorAwareHistoryReader allows recovery paths to distinguish a failed write from a write that became durable before reporting an error.

type HistoryRevisionProvider

type HistoryRevisionProvider interface {
	GetHistoryRevision(sessionKey string) (memory.HistoryRevision, error)
}

HistoryRevisionProvider exposes a cheap identity for the canonical history. Context caches use it to avoid rereading unchanged histories at startup.

type JSONLBackend

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

JSONLBackend adapts a memory.Store into the SessionStore interface. Write errors are logged rather than returned, matching the fire-and-forget contract of SessionManager that the agent loop relies on.

func NewJSONLBackend

func NewJSONLBackend(store memory.Store) *JSONLBackend

NewJSONLBackend wraps a memory.Store for use as a SessionStore.

func (*JSONLBackend) AddFullMessage

func (b *JSONLBackend) AddFullMessage(sessionKey string, msg providers.Message)

func (*JSONLBackend) AddFullMessageWithError

func (b *JSONLBackend) AddFullMessageWithError(sessionKey string, msg providers.Message) error

func (*JSONLBackend) AddMessage

func (b *JSONLBackend) AddMessage(sessionKey, role, content string)

func (*JSONLBackend) AddMessageWithError

func (b *JSONLBackend) AddMessageWithError(sessionKey, role, content string) error

func (*JSONLBackend) AppendTurnMessage

func (b *JSONLBackend) AppendTurnMessage(
	ctx context.Context,
	sessionKey string,
	msg providers.Message,
) error

func (*JSONLBackend) ClearSession

func (b *JSONLBackend) ClearSession(ctx context.Context, sessionKey string) error

func (*JSONLBackend) Close

func (b *JSONLBackend) Close() error

Close releases resources held by the underlying store.

func (*JSONLBackend) EnsureSessionMetadata

func (b *JSONLBackend) EnsureSessionMetadata(sessionKey string, scope *SessionScope, aliases []string)

EnsureSessionMetadata persists scope and alias metadata for a session.

func (*JSONLBackend) GetHistory

func (b *JSONLBackend) GetHistory(key string) []providers.Message

func (*JSONLBackend) GetHistoryRevision

func (b *JSONLBackend) GetHistoryRevision(sessionKey string) (memory.HistoryRevision, error)

GetHistoryRevision returns the canonical history identity when supported by the underlying store.

func (*JSONLBackend) GetHistoryWithError

func (b *JSONLBackend) GetHistoryWithError(key string) ([]providers.Message, error)

func (*JSONLBackend) GetSessionScope

func (b *JSONLBackend) GetSessionScope(sessionKey string) *SessionScope

GetSessionScope reads structured scope metadata for a session key or alias.

func (*JSONLBackend) GetSummary

func (b *JSONLBackend) GetSummary(key string) string

func (*JSONLBackend) ListSessions

func (b *JSONLBackend) ListSessions() []string

ListSessions returns all known session keys.

func (*JSONLBackend) ReadTurnHistory

func (b *JSONLBackend) ReadTurnHistory(ctx context.Context, sessionKey string) ([]providers.Message, error)

func (*JSONLBackend) ReplaceTurnHistory

func (b *JSONLBackend) ReplaceTurnHistory(
	ctx context.Context,
	sessionKey string,
	history []providers.Message,
) error

func (*JSONLBackend) ResolveSessionKey

func (b *JSONLBackend) ResolveSessionKey(sessionKey string) string

ResolveSessionKey maps aliases onto their canonical session key when the underlying store supports structured metadata. Unknown aliases fall back to the original input so existing callers remain compatible.

func (*JSONLBackend) RestoreTurnSnapshot

func (b *JSONLBackend) RestoreTurnSnapshot(
	ctx context.Context,
	sessionKey string,
	history []providers.Message,
	summary string,
) error

func (*JSONLBackend) Save

func (b *JSONLBackend) Save(key string) error

Save persists session state. Since the JSONL store fsyncs every write immediately, the data is already durable. Save runs compaction to reclaim space from logically truncated messages (no-op when there are none).

func (*JSONLBackend) SetHistory

func (b *JSONLBackend) SetHistory(key string, history []providers.Message)

func (*JSONLBackend) SetSummary

func (b *JSONLBackend) SetSummary(key, summary string)

func (*JSONLBackend) TruncateHistory

func (b *JSONLBackend) TruncateHistory(key string, keepLast int)

type LifecyclePolicy

type LifecyclePolicy struct {
	Strategy    string
	Period      string
	Timezone    string
	IdleTimeout time.Duration
	MaxAge      time.Duration
}

func (LifecyclePolicy) NormalizedStrategy

func (p LifecyclePolicy) NormalizedStrategy() string

type MetadataAwareSessionStore

type MetadataAwareSessionStore interface {
	EnsureSessionMetadata(sessionKey string, scope *SessionScope, aliases []string)
	ResolveSessionKey(sessionKey string) string
	GetSessionScope(sessionKey string) *SessionScope
}

MetadataAwareSessionStore exposes structured session metadata operations.

type ParsedLegacySessionKey

type ParsedLegacySessionKey struct {
	AgentID string
	Rest    string
}

func ParseLegacyAgentSessionKey

func ParseLegacyAgentSessionKey(sessionKey string) *ParsedLegacySessionKey

type Session

type Session struct {
	Key             string              `json:"key"`
	Messages        []providers.Message `json:"messages"`
	Summary         string              `json:"summary,omitempty"`
	Created         time.Time           `json:"created"`
	Updated         time.Time           `json:"updated"`
	HistoryRevision uint64              `json:"history_revision,omitempty"`
}

type SessionEpoch

type SessionEpoch struct {
	Strategy string    `json:"strategy"`
	ID       string    `json:"id"`
	Start    time.Time `json:"start"`
}

func CalendarEpoch

func CalendarEpoch(policy LifecyclePolicy, now time.Time) (SessionEpoch, error)

type SessionManager

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

func NewSessionManager

func NewSessionManager(storage string) *SessionManager

func (*SessionManager) AddFullMessage

func (sm *SessionManager) AddFullMessage(sessionKey string, msg providers.Message)

AddFullMessage adds a complete message with tool calls and tool call ID to the session. This is used to save the full conversation flow including tool calls and tool results.

func (*SessionManager) AddFullMessageWithError

func (sm *SessionManager) AddFullMessageWithError(sessionKey string, msg providers.Message) error

func (*SessionManager) AddMessage

func (sm *SessionManager) AddMessage(sessionKey, role, content string)

func (*SessionManager) AddMessageWithError

func (sm *SessionManager) AddMessageWithError(sessionKey, role, content string) error

func (*SessionManager) AppendTurnMessage

func (sm *SessionManager) AppendTurnMessage(
	ctx context.Context,
	sessionKey string,
	msg providers.Message,
) error

func (*SessionManager) ClearSession

func (sm *SessionManager) ClearSession(ctx context.Context, sessionKey string) error

func (*SessionManager) Close

func (sm *SessionManager) Close() error

Close is a no-op for the in-memory SessionManager; it satisfies the SessionStore interface so callers can release resources uniformly.

func (*SessionManager) GetHistory

func (sm *SessionManager) GetHistory(key string) []providers.Message

func (*SessionManager) GetHistoryRevision

func (sm *SessionManager) GetHistoryRevision(key string) (memory.HistoryRevision, error)

GetHistoryRevision returns the monotonic logical history revision persisted with legacy sessions. Wall-clock timestamps are not mutation identities: multiple writes may observe the same clock tick.

func (*SessionManager) GetHistoryWithError

func (sm *SessionManager) GetHistoryWithError(key string) ([]providers.Message, error)

func (*SessionManager) GetOrCreate

func (sm *SessionManager) GetOrCreate(key string) *Session

func (*SessionManager) GetSummary

func (sm *SessionManager) GetSummary(key string) string

func (*SessionManager) ListSessions

func (sm *SessionManager) ListSessions() []string

func (*SessionManager) ReadTurnHistory

func (sm *SessionManager) ReadTurnHistory(
	ctx context.Context,
	sessionKey string,
) ([]providers.Message, error)

func (*SessionManager) ReplaceTurnHistory

func (sm *SessionManager) ReplaceTurnHistory(
	ctx context.Context,
	sessionKey string,
	history []providers.Message,
) error

func (*SessionManager) RestoreTurnSnapshot

func (sm *SessionManager) RestoreTurnSnapshot(
	ctx context.Context,
	sessionKey string,
	history []providers.Message,
	summary string,
) error

func (*SessionManager) Save

func (sm *SessionManager) Save(key string) error

func (*SessionManager) SetHistory

func (sm *SessionManager) SetHistory(key string, history []providers.Message)

SetHistory updates the messages of a session.

func (*SessionManager) SetSummary

func (sm *SessionManager) SetSummary(key string, summary string)

func (*SessionManager) TruncateHistory

func (sm *SessionManager) TruncateHistory(key string, keepLast int)

type SessionScope

type SessionScope struct {
	Version       int               `json:"version"`
	AgentID       string            `json:"agent_id"`
	Channel       string            `json:"channel"`
	Account       string            `json:"account"`
	Dimensions    []string          `json:"dimensions"`
	Values        map[string]string `json:"values"`
	RouteScopeKey string            `json:"route_scope_key,omitempty"`
	Epoch         *SessionEpoch     `json:"epoch,omitempty"`
}

SessionScope describes the semantic session partition selected for a turn.

func ApplyEpoch

func ApplyEpoch(routeScope SessionScope, routeScopeKey string, epoch SessionEpoch) SessionScope

func CloneScope

func CloneScope(scope *SessionScope) *SessionScope

CloneScope returns a deep copy of scope.

type SessionStore

type SessionStore interface {
	TurnJournal
	TurnHistoryStore
	TurnSnapshotStore

	// AddMessage appends a simple role/content message to the session.
	AddMessage(sessionKey, role, content string)
	// AddFullMessage appends a complete message including tool calls.
	AddFullMessage(sessionKey string, msg providers.Message)
	// GetHistory returns the full message history for the session.
	GetHistory(key string) []providers.Message
	// GetSummary returns the conversation summary, or "" if none.
	GetSummary(key string) string
	// SetSummary replaces the conversation summary.
	SetSummary(key, summary string)
	// SetHistory replaces the full message history.
	SetHistory(key string, history []providers.Message)
	// TruncateHistory keeps only the last keepLast messages.
	TruncateHistory(key string, keepLast int)
	// Save persists any pending state to durable storage.
	Save(key string) error
	// ListSessions returns all known session keys.
	ListSessions() []string
	// Close releases resources held by the store.
	Close() error
}

SessionStore defines the persistence operations used by the agent loop. Both SessionManager (legacy JSON backend) and JSONLBackend satisfy this interface, allowing the storage layer to be swapped without touching the agent loop code.

Compatibility writes (Add*, Set*, Truncate*) remain fire-and-forget for passive and administrative callers. Turn-critical writes must use the embedded TurnJournal contract.

type TurnHistoryStore

type TurnHistoryStore interface {
	ReadTurnHistory(ctx context.Context, sessionKey string) ([]providers.Message, error)
	ReplaceTurnHistory(ctx context.Context, sessionKey string, history []providers.Message) error
	ClearSession(ctx context.Context, sessionKey string) error
}

TurnHistoryStore owns contextual, error-aware replacements of canonical history and complete session clears. Active turn and administrative paths that depend on the mutation succeeding must use this contract.

type TurnJournal

type TurnJournal interface {
	AppendTurnMessage(ctx context.Context, sessionKey string, msg providers.Message) error
}

TurnJournal is the durability boundary for messages that determine whether a turn may start, execute an external side effect, or report success. A nil result means the complete message is durably owned by the canonical store.

type TurnSnapshotStore

type TurnSnapshotStore interface {
	RestoreTurnSnapshot(
		ctx context.Context,
		sessionKey string,
		history []providers.Message,
		summary string,
	) error
}

TurnSnapshotStore restores the canonical pre-turn state when execution is aborted before any external side effect may have started.

Jump to

Keyboard shortcuts

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