session

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 16 Imported by: 1 module, 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 the persistence model of sessions: sessions, session messages and the store interface.

It only describes what is stored and where, not how runs work; when to store and what to store is up to the runner. A custom storage backend only needs to depend on this package.

Index

Constants

View Source
const (
	SourceUserInput = "user_input"
	SourceSystem    = "system"
	SourceAgent     = "agent"
	SourceTool      = "tool"

	KindNormal     = "normal"
	KindToolResult = "tool_result"
	// KindTaskResult is the result notice sent back to the session when a background task (sub-agent, background command and so on) ends; Details is a tool.Task.
	KindTaskResult = "task_result"
)

Common Source and Kind values. Both are free-form strings; the business layer may use its own values.

Variables

View Source
var (
	// ErrNotFound means the session, or a message it should hold, does not exist.
	ErrNotFound = errors.New("session: not found")
	// ErrExists means a session that must be new already exists.
	ErrExists = errors.New("session: already exists")
)

Functions

func Fork added in v0.3.0

func Fork(ctx context.Context, store Store, srcID string, dst Session, before *Message) error

Fork creates the session dst from the session srcID, which is left unchanged: a branch of the conversation.

With before nil, dst gets all of srcID's messages. Otherwise before is a message the user typed into srcID, and dst gets the messages preceding it, without the business context stored as part of the same input (Message.InputStartID); running dst with new input then edits that message. Messages keep their IDs, so summaries in the copied part still apply. Background tasks and queued messages of srcID stay with it.

dst.ForkOf and dst.ForkAt are filled in. The store must implement Forker, or Fork returns an error wrapping errors.ErrUnsupported; it returns ErrExists when dst already exists.

Types

type Compaction added in v0.3.0

type Compaction struct {
	// FirstKeptID is the first message kept after the summary; earlier messages no longer enter the model context.
	FirstKeptID string `json:"first_kept_id"`
	// Reason says how the compaction was triggered.
	Reason CompactionReason `json:"reason"`
	// EstimatedTokensBefore is the estimated context usage before the compaction.
	EstimatedTokensBefore int `json:"estimated_tokens_before"`
	// Usage is the tokens spent generating the summary.
	Usage chat.Usage `json:"usage,omitzero"`
}

Compaction describes one compaction: the messages before FirstKeptID are replaced by the summary carrying it.

type CompactionReason added in v0.3.0

type CompactionReason string

CompactionReason says how a compaction was triggered.

const (
	// CompactionAuto is the routine check before a run and after each turn, which compacts when the context is nearly full.
	CompactionAuto CompactionReason = "auto"
	// CompactionOverflow means the model already failed because the context was exceeded.
	CompactionOverflow CompactionReason = "overflow"
	// CompactionManual means the caller asked for it, through runner.Runner.Compact.
	CompactionManual CompactionReason = "manual"
)

type FileStore added in v0.3.0

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

FileStore is a Store keeping sessions as files in one directory, for local development and single-process use. Each session has a metadata file <hex ID>.json and a message file <hex ID>.jsonl with one Message per line, only ever appended to. File names are the hex of the session ID, so any ID up to 120 bytes is safe on any file system.

A complete line is the unit of recovery: after a crash, a partly written last line is ignored and cut off by the next append, and of a batch only the messages written in full are kept. Every append is synced to disk. Sessions are locked within the process only; several processes must not share a directory. Message.Details goes through JSON, so it reads back as JSON values (map[string]any and so on), not as its original type.

func NewFileStore added in v0.3.0

func NewFileStore(dir string) (*FileStore, error)

NewFileStore creates a FileStore in dir, creating the directory when it does not exist.

func (*FileStore) AppendMessages added in v0.3.0

func (s *FileStore) AppendMessages(_ context.Context, sessionID string, messages ...Message) error

func (*FileStore) EnsureSession added in v0.3.0

func (s *FileStore) EnsureSession(_ context.Context, session Session) error

func (*FileStore) ForkSession added in v0.3.0

func (s *FileStore) ForkSession(_ context.Context, dst Session, srcID, cutID string) error

ForkSession implements Forker. The prefix is copied into a temporary file under the source's lock, which is released before the new session is locked, so two forks never wait on each other; the metadata is published last.

func (*FileStore) GetSession added in v0.3.0

func (s *FileStore) GetSession(_ context.Context, sessionID string) (Session, error)

func (*FileStore) ListMessages added in v0.3.0

func (s *FileStore) ListMessages(_ context.Context, sessionID string) ([]Message, error)

type Forker added in v0.3.0

type Forker interface {
	// ForkSession creates the session dst holding the messages of the session srcID that precede the message cutID, or all
	// of them when cutID is empty, in order, with their IDs and every field but SessionID, which becomes dst.ID.
	// It returns ErrExists when dst already exists and ErrNotFound when srcID or cutID does not. It is atomic: when it fails,
	// dst does not exist.
	ForkSession(ctx context.Context, dst Session, srcID, cutID string) error
}

Forker is an optional interface for stores that can fork a session, which Fork requires.

A store wrapped by another type (for logging, metrics and so on) only keeps it when the wrapper forwards it.

type MemoryStore

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

MemoryStore is an in-memory Store, suited to tests and lightweight single-process use.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore creates an in-memory session store.

func (*MemoryStore) AppendMessages

func (s *MemoryStore) AppendMessages(_ context.Context, sessionID string, messages ...Message) error

func (*MemoryStore) EnsureSession

func (s *MemoryStore) EnsureSession(_ context.Context, session Session) error

func (*MemoryStore) ForkSession added in v0.3.0

func (s *MemoryStore) ForkSession(_ context.Context, dst Session, srcID, cutID string) error

ForkSession implements Forker.

func (*MemoryStore) GetSession

func (s *MemoryStore) GetSession(_ context.Context, sessionID string) (Session, error)

func (*MemoryStore) ListMessages

func (s *MemoryStore) ListMessages(_ context.Context, sessionID string) ([]Message, error)

func (*MemoryStore) ListTail added in v0.2.3

func (s *MemoryStore) ListTail(_ context.Context, sessionID string) ([]Message, error)

ListTail implements TailLister.

type Message

type Message struct {
	ID        string      `json:"id"`
	SessionID string      `json:"session_id"`
	Type      MessageType `json:"type"`
	// RunID is the run during which the message was written to history, for retrieving all messages of a run.
	// Background task results written directly to history while the session is idle belong to no run and have an empty RunID.
	RunID string `json:"run_id,omitempty"`
	// ChatMessage is the single source of the message content. User messages, business context and summaries only use its Content;
	// assistant and tool messages are the raw messages produced by the model, with thinking, tool calls, signatures and usage, replayed as is.
	ChatMessage chat.Message `json:"chat_message"`

	// Visible reports whether the message should be shown to the user.
	Visible bool `json:"visible"`
	// Source and Kind describe where the message came from and what it is, for the business layer to classify; the framework does not depend on their values.
	Source string `json:"source"`
	Kind   string `json:"kind"`
	Scope  Scope  `json:"scope"`
	// Details is structured data attached by the business layer and never sent to the model.
	Details any `json:"details,omitempty"`

	// InputStartID is set on a user message stored with persistent business context ahead of it, as one input of
	// runner.Runner.Start: the ID of the first of those messages, so Fork leaves out the context with the input.
	InputStartID string `json:"input_start_id,omitempty"`

	// Compaction is set on summary messages only and describes the compaction that wrote them.
	Compaction *Compaction `json:"compaction,omitempty"`
	CreatedAt  time.Time   `json:"created_at"`
}

Message is a complete session message, as persisted and shown in a UI.

func CloneMessages

func CloneMessages(in []Message) []Message

CloneMessages returns a copy of a list of messages, each made by Message.Clone.

func Compacted added in v0.3.0

func Compacted(all []Message) []Message

Compacted returns the messages the latest compaction replaced, the part of all that Tail leaves out, without the earlier summaries among them: their content is the messages themselves.

func ContextMessage

func ContextMessage(content []chat.ContentBlock, base Message) Message

ContextMessage creates a business context message, taking the other fields from base.

func DisplayMessages

func DisplayMessages(messages []Message) []Message

DisplayMessages returns the messages to show to the user (those with Visible set).

func FromChat

func FromChat(msg chat.Message) Message

FromChat turns an assistant or tool message produced by the model into a session message. An assistant message is visible only when it has displayable text; tool results are hidden by default.

func SummaryMessage

func SummaryMessage(summary string, c Compaction) Message

SummaryMessage creates a summary message written by the compaction c.

func Tail added in v0.2.3

func Tail(all []Message) []Message

Tail returns the messages still used after the latest compaction: from the first message the latest summary keeps (Compaction.FirstKeptID) to the end, or from that summary when the kept message is not found. Without a summary it returns all.

func UserMessage

func UserMessage(content []chat.ContentBlock, details any) Message

UserMessage creates a user input message.

func (Message) Clone

func (m Message) Clone() Message

Clone returns a copy of the message that can be changed without affecting m; content bytes are shared, see chat.ContentBlock.

func (Message) Content

func (m Message) Content() []chat.ContentBlock

Content returns the content blocks of the message.

func (Message) Text

func (m Message) Text() string

Text returns the display text of the message: text blocks only, media as placeholders, no thinking or tool calls.

func (Message) Transcript added in v0.3.0

func (m Message) Transcript() string

Transcript returns the message as plain text for a model to read, such as in a summary request: text blocks, media as placeholders and tool calls as [tool call name arguments], without thinking.

type MessageType

type MessageType string

MessageType is the kind of a session message. It is not the same as ChatMessage.Role, the role used when sending to the model: business context and summaries are sent to the model with the user role.

const (
	TypeUser      MessageType = "user"
	TypeAssistant MessageType = "assistant"
	TypeTool      MessageType = "tool"
	// TypeContext is business context injected for the model, not something the user said.
	TypeContext MessageType = "context"
	// TypeSummary is a summary produced by compaction; it replaces the history before Compaction.FirstKeptID in the model context.
	TypeSummary MessageType = "summary"
)

type Scope

type Scope string

Scope is the lifetime of a message in the session.

const (
	// ScopeRun messages only enter the model context of one run and are not stored, such as temporary context.
	ScopeRun Scope = "run"
	// ScopePersistent messages are stored and stay visible to later runs.
	ScopePersistent Scope = "persistent"
)

type Session

type Session struct {
	ID string
	// ParentID is the parent session that spawned this one. Each sub-agent task is stored in a session of its own;
	// it is not a conversation the user created, and listings of the user's sessions should usually exclude it.
	ParentID string
	// ForkOf and ForkAt are set on a session made by Fork: the session it was forked from, and the user message that was
	// left out there, to be replaced by new input; ForkAt is empty when the whole session was copied.
	ForkOf    string
	ForkAt    string
	CreatedAt time.Time
}

Session holds session metadata.

type Store

type Store interface {
	// EnsureSession creates the session if it does not exist and does nothing otherwise.
	EnsureSession(ctx context.Context, session Session) error
	GetSession(ctx context.Context, sessionID string) (Session, error)
	// AppendMessages appends messages in order. Message IDs are generated by the caller and unique within a session; the
	// same ID can appear in other sessions, as Fork copies messages with their IDs.
	// The runner calls it with a ctx that has no cancellation or deadline (messages already produced must still be written
	// after a run is canceled); an implementation that needs to bound write time should set its own timeout.
	// A batch need not be atomic: an interrupted write may keep its first messages only, which replay tolerates.
	AppendMessages(ctx context.Context, sessionID string, messages ...Message) error
	// ListMessages returns all messages the store keeps for the session, in append order, including those compaction
	// replaced. The framework never deletes messages; whether old ones are purged is up to the application, and tools that
	// read history (such as history.Tool) then only find what is kept.
	ListMessages(ctx context.Context, sessionID string) ([]Message, error)
}

Store is the session store interface, which can be backed by a database and so on. Its methods are called concurrently for many sessions. It does not gain methods: further capabilities are optional interfaces such as TailLister. The storetest package checks an implementation.

type TailLister added in v0.2.3

type TailLister interface {
	// ListTail returns what Tail returns for the session's messages, in append order.
	ListTail(ctx context.Context, sessionID string) ([]Message, error)
}

TailLister is an optional interface for stores that can read a session without the part compaction has replaced. The runner uses it when the store implements it and falls back to ListMessages otherwise, so it only saves reading: a long session is then loaded from its latest summary instead of from its first message.

A store wrapped by another type (for logging, metrics and so on) only keeps it when the wrapper forwards it.

Directories

Path Synopsis
Package storetest checks that a session.Store implementation behaves as the runner expects.
Package storetest checks that a session.Store implementation behaves as the runner expects.

Jump to

Keyboard shortcuts

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