session

package
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package session defines durable session lifecycle and run metadata primitives.

A Session is the first-class conversational container. Runs must always belong to a session. Session lifecycle is explicit: sessions are created and ended independently of run/workflow lifecycle.

Index

Constants

View Source
const (
	// StatusActive indicates the session is open for new runs.
	StatusActive SessionStatus = "active"
	// StatusEnded indicates the session is terminal and must not accept new runs.
	StatusEnded SessionStatus = "ended"

	// RunStatusPending indicates a run is admitted for submission or awaiting execution.
	RunStatusPending RunStatus = "pending"
	// RunStatusRunning indicates the run is actively executing.
	RunStatusRunning RunStatus = "running"
	// RunStatusPaused indicates the run is waiting for external input (pause/await).
	RunStatusPaused RunStatus = "paused"
	// RunStatusCompleted indicates the run finished successfully.
	RunStatusCompleted RunStatus = "completed"
	// RunStatusFailed indicates the run failed permanently.
	RunStatusFailed RunStatus = "failed"
	// RunStatusCanceled indicates the run was canceled externally.
	RunStatusCanceled RunStatus = "canceled"
)

Variables

View Source
var (
	// ErrSessionNotFound indicates a session does not exist in the store.
	ErrSessionNotFound = errors.New("session not found")
	// ErrSessionEnded indicates a session exists but is ended.
	ErrSessionEnded = errors.New("session ended")
	// ErrRunNotFound indicates run metadata does not exist in the store.
	ErrRunNotFound = errors.New("run not found")
	// ErrParentRunIDRequired indicates a child-link operation is missing parent run ID.
	ErrParentRunIDRequired = errors.New("parent run id is required")
	// ErrChildRunIDRequired indicates a child-link operation is missing child run ID.
	ErrChildRunIDRequired = errors.New("child run id is required")
	// ErrChildAgentIDRequired indicates a child-link operation is missing child agent ID.
	ErrChildAgentIDRequired = errors.New("child agent id is required")
	// ErrChildSessionIDRequired indicates a child-link operation is missing child session ID.
	ErrChildSessionIDRequired = errors.New("child session id is required")
	// ErrChildStatusRequired indicates a child-link operation is missing child run status.
	ErrChildStatusRequired = errors.New("child status is required")
	// ErrRunSessionMismatch indicates parent and child runs belong to different sessions.
	ErrRunSessionMismatch = errors.New("parent and child runs must belong to the same session")
	// ErrRunSessionImmutable indicates an existing run was assigned to a different session.
	ErrRunSessionImmutable = errors.New("run session id is immutable")
	// ErrRunAlreadyExists indicates a run ID is already reserved by another attempt.
	ErrRunAlreadyExists = errors.New("run already exists")
)
View Source
var ErrContinuationNotFound = errors.New("continuation not found")

ErrContinuationNotFound identifies a missing continuation in a session.

Functions

func EncodeContinuation added in v2.1.0

func EncodeContinuation(next Continuation) ([]byte, error)

EncodeContinuation returns the deterministic body used for idempotency checks.

func IsTerminalRunStatus added in v2.1.0

func IsTerminalRunStatus(status RunStatus) bool

IsTerminalRunStatus reports whether status permanently closes a run.

func ResolvePromptRefs

func ResolvePromptRefs(ctx context.Context, store Store, runID string) ([]prompt.PromptRef, error)

ResolvePromptRefs returns the unique prompt refs used by a run and all of its descendant child runs.

Contract:

  • runID must be non-empty.
  • ErrRunNotFound is returned when the root run does not exist.
  • Prompt refs are deduplicated by (prompt_id, version) with first-seen order.
func ValidateChildRunLink(parentRunID string, child RunMeta) error

ValidateChildRunLink validates required identifiers for Store.LinkChildRun input.

func ValidateRunReservation added in v2.1.0

func ValidateRunReservation(run RunMeta, attemptID string) error

ValidateRunReservation validates the identity and initial state for a run start reservation.

Types

type AdvanceOutcome added in v2.1.0

type AdvanceOutcome string

AdvanceOutcome describes an atomic compare-and-swap of the session head.

const (
	// Published means this invocation inserted the body and advanced the head.
	Published AdvanceOutcome = "published"
	// AlreadyPublished means an identical body was committed, even if the head moved.
	AlreadyPublished AdvanceOutcome = "already"
	// Conflict means this ID exists with a different body.
	Conflict AdvanceOutcome = "conflict"
	// Superseded means another run advanced the expected head.
	Superseded AdvanceOutcome = "superseded"
)

type Carried added in v2.1.0

type Carried struct {
	Entry index.MessageEntry `json:"entry"`
	Bytes *runstore.Hash     `json:"bytes"`
}

Carried retains provenance and only the bytes actually rendered at sealing.

type Continuation added in v2.1.0

type Continuation struct {
	ID         string          `json:"id"`
	Prev       *string         `json:"prev"`
	Pos        int             `json:"pos"`
	Checkpoint *runstore.Hash  `json:"checkpoint"`
	Pins       []Carried       `json:"pins"`
	UserIndex  []Carried       `json:"user_index"`
	Tail       []Carried       `json:"tail"`
	Visible    []runstore.Hash `json:"visible"`
}

Continuation is the immutable, rendered carry of one completed root run. ID is the run ID; Prev and Pos identify its place in the session chain.

type ContinuationStore added in v2.1.0

type ContinuationStore interface {
	AdvanceContinuation(context.Context, string, *string, Continuation) (AdvanceOutcome, error)
	LoadContinuationHead(context.Context, string) (*Continuation, error)
	LoadContinuation(context.Context, string, string) (Continuation, error)
}

ContinuationStore persists immutable continuation bodies and a session head. Implementations compare deterministic JSON bodies by ID before checking the expected head. Inserting the body and moving the head must be atomic.

type RunMeta

type RunMeta struct {
	// AgentID identifies which agent processed the run.
	AgentID string
	// RunID is the durable workflow run identifier.
	RunID string
	// SessionID associates related runs (e.g., chat sessions).
	SessionID string
	// Status indicates the current lifecycle state.
	Status RunStatus
	// StartedAt records when the run began.
	StartedAt time.Time
	// UpdatedAt records when the run metadata was last updated.
	UpdatedAt time.Time
	// Labels stores caller- or policy-provided labels.
	Labels map[string]string
	// PromptRefs captures the unique prompt versions rendered during the run.
	//
	// The runtime appends to this slice when it observes PromptRendered hook
	// events, de-duplicating by (prompt_id, version). This enables downstream
	// consumers to correlate run outcomes with the exact prompt versions that
	// were used without re-scanning the run event log.
	PromptRefs []prompt.PromptRef
	// ChildRunIDs captures direct child runs linked from this run.
	//
	// Child runs are produced by agent-as-tool execution. Consumers that need
	// full prompt attribution should walk this graph to include descendants.
	ChildRunIDs []string
	// Metadata stores implementation-specific metadata (e.g., error codes).
	Metadata map[string]any
}

RunMeta captures persistent metadata associated with a run execution.

type RunStatus

type RunStatus string

RunStatus represents the lifecycle state of a run.

type Session

type Session struct {
	// ID is the durable identifier of the session.
	ID string
	// Status is the current session lifecycle state.
	Status SessionStatus
	// CreatedAt records when the session was created.
	CreatedAt time.Time
	// EndedAt is set when the session is ended.
	EndedAt *time.Time
}

Session captures durable session lifecycle state.

Contract: - Session IDs are stable and caller-provided (typically owned by an application). - Sessions are created explicitly (CreateSession) and ended explicitly (EndSession). - Ended sessions are terminal: new runs must not start under an ended session.

type SessionStatus

type SessionStatus string

SessionStatus represents the lifecycle state of a session.

type Store

type Store interface {
	// CreateSession creates (or returns) an active session.
	//
	// Contract:
	// - Idempotent for active sessions: returns the existing session.
	// - Returns ErrSessionEnded when the session exists but is terminal.
	CreateSession(ctx context.Context, sessionID string, createdAt time.Time) (Session, error)
	// LoadSession loads an existing session.
	// Returns ErrSessionNotFound when the session does not exist.
	LoadSession(ctx context.Context, sessionID string) (Session, error)
	// EndSession ends a session and returns its terminal state.
	// Idempotent: ending an already-ended session returns the stored session.
	EndSession(ctx context.Context, sessionID string, endedAt time.Time) (Session, error)

	// UpsertRun inserts or updates run metadata.
	//
	// New runs require an existing active session. Existing runs may receive
	// terminal updates after their session ends, but their SessionID is immutable.
	// Once a run reaches a terminal status, later updates may enrich its metadata
	// but must not change or reopen that terminal status.
	// Returns ErrSessionNotFound, ErrSessionEnded, or ErrRunSessionImmutable
	// when those ownership invariants are violated.
	UpsertRun(ctx context.Context, run RunMeta) error
	// ReserveRun creates pending metadata for one start attempt. A repeated
	// reservation by the same attempt, run agent, session, and parent is
	// idempotent and preserves stored state; another owner or identity for the
	// same run ID receives ErrRunAlreadyExists. When parentRunID is non-empty,
	// child creation and parent linkage are atomic. New reservations require an
	// active session.
	ReserveRun(ctx context.Context, run RunMeta, attemptID, parentRunID string) error
	// RejectRun marks a still-pending run failed only when attemptID owns its
	// reservation. Missing, differently owned, or non-pending runs are unchanged.
	RejectRun(ctx context.Context, runID, attemptID string) error
	// LinkChildRun links a child run to a parent run atomically.
	//
	// Contract:
	// - parentRunID and child identifiers must be non-empty.
	// - The parent run must already exist, otherwise ErrRunNotFound is returned.
	// - Parent and child runs must belong to the same session.
	// - Child linkage is idempotent (duplicate links are ignored).
	// - Replaying an already committed link is a no-op after session end;
	//   creating a child or committing a new link requires an active session.
	// - The implementation must ensure no observer can observe a linked child ID
	//   without a corresponding child run record.
	LinkChildRun(ctx context.Context, parentRunID string, child RunMeta) error
	// LoadRun loads run metadata. Returns ErrRunNotFound when missing.
	LoadRun(ctx context.Context, runID string) (RunMeta, error)
	// ListRunsBySession lists runs for the given session. When statuses is
	// non-empty, only runs whose status matches one of the provided values
	// are returned.
	ListRunsBySession(ctx context.Context, sessionID string, statuses []RunStatus) ([]RunMeta, error)
}

Store persists session lifecycle state and run metadata.

Store implementations must be durable: failures are surfaced to callers so workflows can fail fast when session/run metadata is unavailable.

Directories

Path Synopsis
Package inmem provides an in-memory implementation of session.Store.
Package inmem provides an in-memory implementation of session.Store.
Package sessiontest provides executable continuation-store conformance checks.
Package sessiontest provides executable continuation-store conformance checks.

Jump to

Keyboard shortcuts

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