history

package
v0.47.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 14 Imported by: 2 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 history defines conversation storage types and session backends.

Backends include in-memory, file-based, and MySQL implementations via a unified session manager contract.

Package history provides message types and session storage backends for agent conversations.

Index

Constants

View Source
const DefaultMySQLMessagesTableName = "agent_messages"

DefaultMySQLMessagesTableName is the table used by MySQLAppendOnlyMessageStore when no override is provided.

View Source
const DefaultMySQLTableName = "agent_sessions"

DefaultMySQLTableName is the table name used when no WithMySQLTableName option is supplied to NewMySQLSessionManagerWithOptions.

Variables

This section is empty.

Functions

func BackgroundBehaviorSummarizer

func BackgroundBehaviorSummarizer(
	sessionKey string,
	newMessages []Message,
	previousSummary string,
	provider SummaryProvider,
	updateCallback func(sessionKey string, newSummary string) error,
)

BackgroundBehaviorSummarizer fires async summarization for a session. Only newMessages (since last summarization) are sent to the provider, together with the existing previousSummary so the model can do an incremental merge.

func SafeTruncate

func SafeTruncate(msgs []Message, atIndex int) int

SafeTruncate returns an index <= atIndex such that msgs[:result] is a self-contained prefix: it never ends mid tool-call / tool-result group.

The returned prefix satisfies both invariants:

  • no trailing assistant message has unresolved ToolCalls (dangling calls),
  • no trailing tool message lacks its matching assistant (orphan results).

When the input atIndex is already safe, it is returned unchanged. When it is not, the index is walked backward past the offending boundary.

Use this when rewinding a live conversation in place (Regenerate / Continue affordances) — the framework backends use the same helper inside Fork so the two paths share one source of truth for tool-pair safety.

Types

type AsyncTask

type AsyncTask struct {
	TaskID    string `json:"task_id"`
	AgentName string `json:"agent_name"`
	Status    string `json:"status"` // "running", "success", "error", "cancelled", "interrupted"
	Result    string `json:"result,omitempty"`
}

AsyncTask represents a background task managed by the session.

type Compaction added in v0.45.0

type Compaction struct {
	// Summarized is how many messages this record folded into the summary
	// on top of the previous record's. Informational.
	Summarized int `json:"summarized"`
}

Compaction is the payload of a compaction record (see Message.Compaction).

type FileSessionManager

type FileSessionManager struct {
	SystemPrompt    string
	SummaryProvider SummaryProvider // if nil, background summarization is disabled
	// PromptVersion: see InMemSessionManager.PromptVersion. Same semantics.
	PromptVersion string
	// contains filtered or unexported fields
}

FileSessionManager provides file-backed session persistence. Sessions survive server restarts. Each session is stored as a JSON file under storagePath.

func NewFileSessionManager

func NewFileSessionManager(storagePath string, systemPrompt ...string) (*FileSessionManager, error)

NewFileSessionManager creates a file-backed session manager. storagePath is the directory where session JSON files are stored. An optional systemPrompt can be provided; defaults to a generic assistant prompt.

func (*FileSessionManager) AsyncTasks

func (sm *FileSessionManager) AsyncTasks(ctx context.Context, sessionKey string) (map[string]AsyncTask, error)

AsyncTasks returns a copy of the background tasks parked on sessionKey. Lazy-loads from disk via History when the session is not cached.

func (*FileSessionManager) Delete

func (sm *FileSessionManager) Delete(_ context.Context, sessionKey string) error

Delete removes the session from the in-memory cache and deletes the backing JSON file (if configured). Deleting a non-existent session is a no-op.

func (*FileSessionManager) Fork

func (sm *FileSessionManager) Fork(ctx context.Context, sessionKey string, atIndex int) (string, error)

Fork creates a new session whose message history is a copy of the first atIndex messages from sessionKey. The copy is persisted to disk (when a storage path is configured). See SessionManager.Fork for full semantics.

func (*FileSessionManager) History

func (sm *FileSessionManager) History(_ context.Context, sessionKey string) ([]Message, error)

History returns the session history, injecting system prompt + behavior summary. On cache miss, it attempts to load from disk (storagePath/<sessionKey>.json). The error return is part of the SessionManager contract; this backend degrades to "empty session" on disk errors rather than propagating them, matching the documented best-effort semantics.

func (*FileSessionManager) PurgeDeletedBefore

func (sm *FileSessionManager) PurgeDeletedBefore(ctx context.Context, before time.Time) (int, error)

PurgeDeletedBefore hard-deletes every soft-deleted session whose DeletedAt is strictly older than `before`.

func (*FileSessionManager) Query

func (sm *FileSessionManager) Query(_ context.Context, prefix string, opts SessionQueryOpts) ([]SessionMeta, error)

Query lists sessions stored on disk under storagePath. Result includes in-memory sessions that have not been persisted yet. See SessionManager.Query for full semantics. Linear in session count — for products with tens of thousands of sessions, prefer the MySQL backend.

func (*FileSessionManager) Restore

func (sm *FileSessionManager) Restore(ctx context.Context, sessionKey string) error

Restore clears the tombstone in-memory and persists the wrapper.

func (*FileSessionManager) SaveAsyncTasks

func (sm *FileSessionManager) SaveAsyncTasks(ctx context.Context, sessionKey string, tasks map[string]AsyncTask) error

SaveAsyncTasks atomically updates the in-memory cache and persists the wrapper to disk.

func (*FileSessionManager) SaveHistory

func (sm *FileSessionManager) SaveHistory(ctx context.Context, sessionKey string, msgs []Message) error

SaveHistory atomically updates the in-memory cache and persists the wrapper to disk. Combines what used to be SetHistory + Save into a single atomic operation. Triggers background summarization when configured.

func (*FileSessionManager) SetTitle

func (sm *FileSessionManager) SetTitle(ctx context.Context, sessionKey string, title string) error

SetTitle implements agent.SessionTitler. The title is persisted to the session's JSON sidecar so it survives process restarts. Empty title clears any previously-recorded label. Setting a title before SaveHistory creates only the in-memory entry; once a session is persisted the title is folded in on every persist via the wrapper.

func (*FileSessionManager) SoftDelete

func (sm *FileSessionManager) SoftDelete(ctx context.Context, sessionKey string) error

SoftDelete tombstones the session in-memory and persists the wrapper.

func (*FileSessionManager) UpdateBehaviorSummary

func (sm *FileSessionManager) UpdateBehaviorSummary(sessionKey string, newSummary string) error

UpdateBehaviorSummary is the callback used by BackgroundBehaviorSummarizer.

func (*FileSessionManager) WithPromptVersion

func (sm *FileSessionManager) WithPromptVersion(version string) *FileSessionManager

WithPromptVersion sets the prompt version tag and returns the manager for fluent chaining.

type InMemSessionManager

type InMemSessionManager struct {
	SystemPrompt    string
	SummaryProvider SummaryProvider // if nil, background summarization is disabled

	// PromptVersion, when non-empty, prepends a `<!-- prompt-version:V -->`
	// marker to the system message returned by GetHistory. The marker is
	// HTML-comment so LLMs ignore it; operators can grep storage to audit
	// which prompt version each session is running. Bump the version when
	// editing prompt rules to make the propagation auditable.
	PromptVersion string

	// TTL is the idle expiry duration per session (0 = never expire).
	// A session is evicted when it has not been read or written for TTL duration.
	// Call StartCleanup to activate background eviction.
	TTL time.Duration
	// contains filtered or unexported fields
}

InMemSessionManager is a thread-safe in-memory session store with optional TTL eviction.

func NewInMemSessionManager

func NewInMemSessionManager(systemPrompt ...string) *InMemSessionManager

NewInMemSessionManager creates a new in-memory session manager. An optional systemPrompt can be provided; defaults to a generic assistant prompt.

func (*InMemSessionManager) AsyncTasks

func (m *InMemSessionManager) AsyncTasks(_ context.Context, sessionKey string) (map[string]AsyncTask, error)

AsyncTasks returns a copy of the background tasks parked on sessionKey. InMem never fails on read; error is always nil.

func (*InMemSessionManager) Delete

func (m *InMemSessionManager) Delete(_ context.Context, sessionKey string) error

Delete removes all in-memory state for sessionKey. Deleting a non-existent session is a no-op.

func (*InMemSessionManager) Fork

func (m *InMemSessionManager) Fork(_ context.Context, sessionKey string, atIndex int) (string, error)

Fork creates a new session that is a deep copy of the first atIndex messages from sessionKey. The behavior summary is copied; async tasks are not. See SessionManager.Fork for full semantics.

func (*InMemSessionManager) History

func (m *InMemSessionManager) History(_ context.Context, sessionKey string) ([]Message, error)

History returns the persisted message log for sessionKey. InMem never fails on read, so the error return is always nil; it is part of the SessionManager contract for backends that can fail (MySQL, File).

func (*InMemSessionManager) PurgeDeletedBefore

func (m *InMemSessionManager) PurgeDeletedBefore(_ context.Context, before time.Time) (int, error)

PurgeDeletedBefore hard-deletes every soft-deleted session whose DeletedAt is strictly older than `before`.

func (*InMemSessionManager) Query

Query returns metadata for sessions whose key starts with prefix. See SessionManager.Query for full semantics.

func (*InMemSessionManager) Restore

func (m *InMemSessionManager) Restore(_ context.Context, sessionKey string) error

Restore clears the tombstone set by SoftDelete.

func (*InMemSessionManager) SaveAsyncTasks

func (m *InMemSessionManager) SaveAsyncTasks(_ context.Context, sessionKey string, tasks map[string]AsyncTask) error

SaveAsyncTasks atomically replaces the async task snapshot for sessionKey.

func (*InMemSessionManager) SaveHistory

func (m *InMemSessionManager) SaveHistory(_ context.Context, sessionKey string, msgs []Message) error

SaveHistory atomically replaces the persisted log with msgs. InMem owns the copy of msgs (callers may continue to mutate their slice). When a SummaryProvider is configured and the new message count crosses the background-summarization threshold, this also fires the async summarizer goroutine — same trigger point that the old Save() used to own.

func (*InMemSessionManager) SetTitle

func (m *InMemSessionManager) SetTitle(_ context.Context, sessionKey string, title string) error

SetTitle implements agent.SessionTitler. Empty title clears any previously-recorded label. Recording a title for a session not yet seen is permitted — the title is retained and joined to the session record once it is created (matches the typical "title fires off concurrently with the first turn" event-handler flow).

func (*InMemSessionManager) SoftDelete

func (m *InMemSessionManager) SoftDelete(_ context.Context, sessionKey string) error

SoftDelete tombstones sessionKey. See SessionManager.SoftDelete.

func (*InMemSessionManager) StartCleanup

func (m *InMemSessionManager) StartCleanup(ctx context.Context, interval time.Duration) *InMemSessionManager

StartCleanup starts a background goroutine that evicts sessions idle for longer than TTL. It runs at the given interval. The goroutine stops when ctx is cancelled. Returns the manager for fluent chaining:

sm := history.NewInMemSessionManager("...").
    WithTTL(30 * time.Minute).
    StartCleanup(ctx, 5 * time.Minute)

No-op if TTL == 0.

func (*InMemSessionManager) UpdateBehaviorSummary

func (m *InMemSessionManager) UpdateBehaviorSummary(sessionKey string, newSummary string) error

UpdateBehaviorSummary is the callback used by BackgroundBehaviorSummarizer to inject long-term memory

func (*InMemSessionManager) WithPromptVersion

func (m *InMemSessionManager) WithPromptVersion(version string) *InMemSessionManager

WithPromptVersion sets the prompt version tag and returns the manager for fluent chaining. See InMemSessionManager.PromptVersion for the observability contract.

func (*InMemSessionManager) WithTTL

WithTTL sets the idle TTL and returns the manager for fluent chaining.

type MediaPart

type MediaPart struct {
	Type PartType `json:"type"`
	Text string   `json:"text,omitempty"`
	MIME string   `json:"mime,omitempty"` // e.g. "image/png"; required for non-text parts
	URL  string   `json:"url,omitempty"`  // https://, http://, or data: URI
	Data []byte   `json:"data,omitempty"` // raw bytes; JSON-marshals as base64
}

MediaPart is a typed chunk of a multimodal message.

Usage rules:

  • Type=="text": only Text is read.
  • Type=="image": MIME is required; populate exactly one of URL or Data. URL may be an https:// URL or a data: URI. Data is raw bytes and will be base64-encoded by the adapter for providers that require it.

The zero value is invalid — callers should use NewTextPart / NewImagePartURL / NewImagePartBytes for safety.

func NewImagePartBytes

func NewImagePartBytes(mime string, data []byte) MediaPart

NewImagePartBytes constructs an image part from raw bytes. The adapter layer base64-encodes when the provider expects base64 and synthesizes a data: URI when the provider expects a URL.

func NewImagePartURL

func NewImagePartURL(mime, url string) MediaPart

NewImagePartURL constructs an image part referencing a remote URL (https) or a data: URI. mime is a best-effort hint; providers that derive MIME from the URL ignore it.

func NewTextPart

func NewTextPart(text string) MediaPart

NewTextPart constructs a text-only MediaPart.

type Message

type Message struct {
	Role       string      `json:"role"`
	Content    string      `json:"content"`
	Parts      []MediaPart `json:"parts,omitempty"`        // optional multimodal parts (images, richer text)
	ToolCallID string      `json:"tool_call_id,omitempty"` // for role:"tool" result messages
	ToolCalls  []ToolCall  `json:"tool_calls,omitempty"`   // for role:"assistant" messages with tool calls
	IsError    bool        `json:"is_error,omitempty"`     // true when a tool execution failed

	// IsInlineResult is set on a role:"tool" message whose tool implements
	// tools.InlineRenderer with InlineResult()=true (e.g. generate_image,
	// generate_video). The agent loop already streamed the content inline
	// during the live turn, so render layers that filter out tool rows on
	// resume should special-case IsInlineResult — fold it back into the
	// preceding assistant message — rather than dropping it. Stable signal
	// across tool names; adopters no longer need a hand-curated allowlist.
	IsInlineResult bool `json:"is_inline_result,omitempty"`

	// CorrelationID is the opaque per-dispatch ID the agent loop generated
	// for this tool call (newToolCallID) and streamed live on the matching
	// ToolCallEvent.ID / ToolProgressEvent.ToolCallID. ToolCallID above holds
	// the provider's tool-call ID, which is load-bearing for tool_use /
	// tool_result adjacency but is NOT what live events expose (and which some
	// providers reuse across parallel same-name calls). CorrelationID gives
	// adopters a single stable handle to re-match a live-rendered artifact card
	// to its tool row after a session reload. Empty for pre-correlation
	// sessions and for non-tool messages.
	CorrelationID string `json:"correlation_id,omitempty"`

	// CacheHint requests that LLM adapters mark this message as a prompt-cache
	// breakpoint when the underlying provider supports it. The Anthropic
	// adapter translates CacheHint=true into `cache_control:{type:"ephemeral"}`
	// on the corresponding content block, which is cached for ~5 minutes and
	// cuts input-token cost ~90% on cached portions of subsequent requests.
	// Providers without a prompt-cache API (OpenAI/Gemini auto-cache server-side)
	// ignore this flag — it is always safe to set.
	CacheHint bool `json:"cache_hint,omitempty"`

	// Compaction is set on a compaction record: a role:"system" message the
	// agent loop inserts when it condenses older turns. A record stands in
	// for every conversation message before it: Content is their summary,
	// folding in any earlier record. Those messages stay in history at
	// full fidelity; the loop only leaves them out of the requests it
	// builds. Because a record is located by position rather than by
	// index, trimming history from the front or truncating it after the
	// record cannot make it point at the wrong place. Render layers can
	// show it as a "conversation condensed" divider or skip it with the
	// other system rows.
	Compaction *Compaction `json:"compaction,omitempty"`
}

Message represents a single message in a chat conversation. It supports all standard roles: "system", "user", "assistant", and "tool".

Multimodal input is expressed through Parts: when len(Parts) > 0, LLM provider adapters iterate Parts instead of (or in addition to) Content. When Parts is empty, adapters fall back to the plain-text Content path — so every existing caller and test continues to work unchanged.

The fallback is only for an empty Parts. An adapter that cannot render a populated Parts must fail rather than quietly answer from Content: a caller that sent an image and got back a fluent, well-formed reply has no way to tell that the model never saw it, and nothing in the logs distinguishes that from success. Such an adapter should also report ImageInput=false through agent.CapabilityProvider so consumers that need vision can reject it at construction instead of mid-run.

type MessageStore

type MessageStore interface {
	// Save persists messages for sessionKey. knownPersistedCount is the
	// count returned by the previous Save (or by Load on a fresh load) —
	// implementations use it as a hint to skip rewriting messages already
	// on disk. If the slice is shorter than knownPersistedCount the store
	// must treat the change as a truncation and remove the orphan tail.
	// Returns the new persisted count (typically len(messages)).
	Save(ctx context.Context, sessionKey string, messages []Message, knownPersistedCount int) (int, error)
	// Load returns every message persisted for sessionKey, in order.
	Load(ctx context.Context, sessionKey string) ([]Message, error)
	// Delete removes every message stored for sessionKey. No-op if none exist.
	Delete(ctx context.Context, sessionKey string) error
}

MessageStore is an optional persistence layer for session messages, decoupled from session metadata. The default MySQLSessionManager keeps messages inside the JSON column on the same row as behavior/async tasks (whole-blob storage, simple but writes the entire history on every turn). Pass WithMySQLMessageStore to flip to a per-row store — MySQLAppendOnlyMessageStore is the canonical implementation; integrators can plug in their own (DynamoDB, Redis Streams, S3, etc.).

Hot-path note: implementations should support the knownPersistedCount hint so per-turn cost is O(new messages) rather than O(total session).

type MockSummaryProvider

type MockSummaryProvider struct{}

MockSummaryProvider is a stub for tests — no API key required.

func (*MockSummaryProvider) SummarizeBehaviors

func (m *MockSummaryProvider) SummarizeBehaviors(_ context.Context, _ []Message, previous string) (string, error)

type MySQLAppendOnlyMessageStore

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

MySQLAppendOnlyMessageStore stores each message as its own row keyed by (session_key, idx). Per-turn writes touch only the new rows, sidestepping the JSON-column row-size cap that bites long sessions when messages live inside a single blob.

Schema:

CREATE TABLE agent_messages (
    session_key VARCHAR(255) NOT NULL,
    idx         INT UNSIGNED NOT NULL,
    payload     JSON NOT NULL,
    created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (session_key, idx),
    INDEX idx_session_created (session_key, created_at)
)

The store is safe for concurrent calls but does NOT lock per-session — callers should serialize Save calls per-session if they need strict ordering across goroutines (the SessionManager already does).

func NewMySQLAppendOnlyMessageStore

func NewMySQLAppendOnlyMessageStore(db *sql.DB, tableName string) (*MySQLAppendOnlyMessageStore, error)

NewMySQLAppendOnlyMessageStore constructs the store and runs the idempotent CREATE TABLE statement. tableName is validated against SQL identifier rules; pass "" to use DefaultMySQLMessagesTableName.

func (*MySQLAppendOnlyMessageStore) Delete

func (s *MySQLAppendOnlyMessageStore) Delete(ctx context.Context, sessionKey string) error

Delete removes every row for sessionKey.

func (*MySQLAppendOnlyMessageStore) Load

func (s *MySQLAppendOnlyMessageStore) Load(ctx context.Context, sessionKey string) ([]Message, error)

Load returns every message for sessionKey, ordered by idx.

func (*MySQLAppendOnlyMessageStore) Save

func (s *MySQLAppendOnlyMessageStore) Save(ctx context.Context, sessionKey string, messages []Message, knownPersistedCount int) (int, error)

Save writes messages[knownPersistedCount:] as new rows, then UPDATEs the last already-persisted row to absorb any in-place mutation (LLM streaming attaches tool_calls to an assistant message after the row is first created — without the upsert that edit would be lost). Implements truncation: when len(messages) < knownPersistedCount the orphan rows at the tail are deleted.

type MySQLOption

type MySQLOption func(*mysqlOptions)

MySQLOption configures a MySQLSessionManager at construction time.

func WithMySQLMessageStore

func WithMySQLMessageStore(store MessageStore) MySQLOption

WithMySQLMessageStore plugs an alternate MessageStore into the manager. When set, messages are persisted via the store (typically a MySQLAppendOnlyMessageStore) instead of the JSON column. The session row still carries behavior summary, async tasks, and timestamps.

func WithMySQLPromptVersion

func WithMySQLPromptVersion(version string) MySQLOption

WithMySQLPromptVersion is the option-style constructor variant for setting the prompt version tag at construction. Pass to NewMySQLSessionManagerWithOptions.

func WithMySQLTableName

func WithMySQLTableName(name string) MySQLOption

WithMySQLTableName overrides the default "agent_sessions" table name. Useful when multiple agents share a single database and need isolated tables (e.g. "chatbot_sessions", "boa_sessions"). The name must match the standard SQL identifier format: [A-Za-z_][A-Za-z0-9_]*.

type MySQLSessionManager

type MySQLSessionManager struct {
	SystemPrompt    string
	SummaryProvider SummaryProvider // if nil, background summarization is disabled
	// PromptVersion: see InMemSessionManager.PromptVersion. Same semantics.
	PromptVersion string
	// MessageStore, when non-nil, replaces the JSON-column message
	// persistence path with per-row storage. See WithMySQLMessageStore.
	MessageStore MessageStore
	// contains filtered or unexported fields
}

MySQLSessionManager implements SessionManager using MySQL for persistence. History survives server restarts. Optionally supports background behavior summarization.

func NewMySQLSessionManager

func NewMySQLSessionManager(db *sql.DB, systemPrompt ...string) (*MySQLSessionManager, error)

NewMySQLSessionManager creates a MySQL-backed session manager using the default table name "agent_sessions". For multi-tenant deployments where multiple agents share one database, use NewMySQLSessionManagerWithOptions with WithMySQLTableName. An optional systemPrompt can be provided; defaults to a generic assistant prompt.

func NewMySQLSessionManagerWithOptions

func NewMySQLSessionManagerWithOptions(db *sql.DB, systemPrompt string, opts ...MySQLOption) (*MySQLSessionManager, error)

NewMySQLSessionManagerWithOptions creates a MySQL-backed session manager with explicit configuration options. Pass WithMySQLTableName to override the default table name.

func (*MySQLSessionManager) AsyncTasks

func (sm *MySQLSessionManager) AsyncTasks(ctx context.Context, sessionKey string) (map[string]AsyncTask, error)

AsyncTasks returns a copy of the background tasks parked on sessionKey. Reads from the in-memory cache when present, otherwise lazy-loads from MySQL.

func (*MySQLSessionManager) Delete

func (sm *MySQLSessionManager) Delete(ctx context.Context, sessionKey string) error

Delete removes the session from the in-memory cache and deletes the corresponding row from the agent_sessions table. Deleting a non-existent session is a no-op. When a MessageStore is plugged in, its rows are dropped too so no orphan messages survive.

func (*MySQLSessionManager) Fork

func (sm *MySQLSessionManager) Fork(ctx context.Context, sessionKey string, atIndex int) (string, error)

Fork creates a new session whose message history is a copy of the first atIndex messages from sessionKey. The copy is persisted by inserting a new row in agent_sessions. See SessionManager.Fork for full semantics.

func (*MySQLSessionManager) History

func (sm *MySQLSessionManager) History(ctx context.Context, sessionKey string) ([]Message, error)

History returns the persisted message log for sessionKey. Reads from the in-memory cache when present; otherwise loads from MySQL (or the MessageStore when configured). Disk/decoding errors are logged and the method degrades to "system-only" history rather than failing the loop — the error return is reserved for unrecoverable infrastructure errors that callers should propagate.

func (*MySQLSessionManager) PurgeDeletedBefore

func (sm *MySQLSessionManager) PurgeDeletedBefore(ctx context.Context, before time.Time) (int, error)

PurgeDeletedBefore hard-deletes every soft-deleted row whose deleted_at is strictly older than `before`. Returns the count purged.

func (*MySQLSessionManager) Query

func (sm *MySQLSessionManager) Query(ctx context.Context, prefix string, opts SessionQueryOpts) ([]SessionMeta, error)

Query lists sessions whose key starts with prefix. See SessionManager.Query for full semantics. Backed by `WHERE session_key LIKE ?` with the prefix LIKE-escaped — `_` and `%` in the prefix are treated literally.

func (*MySQLSessionManager) Restore

func (sm *MySQLSessionManager) Restore(ctx context.Context, sessionKey string) error

Restore clears deleted_at on the row.

func (*MySQLSessionManager) SaveAsyncTasks

func (sm *MySQLSessionManager) SaveAsyncTasks(ctx context.Context, sessionKey string, tasks map[string]AsyncTask) error

SaveAsyncTasks atomically updates the in-memory cache and persists the row to MySQL.

func (*MySQLSessionManager) SaveHistory

func (sm *MySQLSessionManager) SaveHistory(ctx context.Context, sessionKey string, msgs []Message) error

SaveHistory atomically updates the in-memory cache and persists the row to MySQL (and to the MessageStore when configured). Triggers background summarization when the configured threshold is crossed.

func (*MySQLSessionManager) SetTitle

func (sm *MySQLSessionManager) SetTitle(ctx context.Context, sessionKey string, title string) error

SetTitle implements agent.SessionTitler. Updates the session row's title column. Empty title is stored as NULL so Query returns it as "". Calling SetTitle for a session that does not yet have a row is a no-op — the title is meaningful only alongside persisted history, and the typical caller (post-EventTypeSessionCreated handler) runs after the first SaveHistory.

func (*MySQLSessionManager) SoftDelete

func (sm *MySQLSessionManager) SoftDelete(ctx context.Context, sessionKey string) error

SoftDelete sets deleted_at = NOW() on the row and evicts the cache. Reads (GetHistory / Query without IncludeDeleted) treat the session as missing while the row stays behind for Restore.

func (*MySQLSessionManager) UpdateBehaviorSummary

func (sm *MySQLSessionManager) UpdateBehaviorSummary(sessionKey string, newSummary string) error

UpdateBehaviorSummary is the callback used by BackgroundBehaviorSummarizer.

type PartType

type PartType string

PartType enumerates the kinds of content a MediaPart can hold.

Video and audio are intentionally omitted. Anthropic accepts neither in a message, and Gemini video requires Files-API upload semantics that do not fit the simple inline model. Video remains on the tool path via media_analyze; audio goes through pkg/audio, whose Transcriber converts it to text before it reaches a message.

Transcribing rather than embedding is also the cheaper shape for anything long. History is re-sent on every LLM call in a session, so audio carried as a message part is re-uploaded on every subsequent turn — a one-hour recording would be billed again on each turn of the conversation about it.

A part whose type an adapter cannot render fails the request with agent.ErrUnrenderablePart rather than being dropped.

const (
	// PartText is a plain-text fragment. Equivalent to the Content string when
	// used alone; useful when interleaved with image parts.
	PartText PartType = "text"
	// PartImage is an image. MIME must be set (e.g. "image/png", "image/jpeg").
	// Exactly one of URL or Data should be populated.
	PartImage PartType = "image"
)

type Session

type Session struct {
	Key        string               `json:"key"`
	Messages   []Message            `json:"messages"`
	AsyncTasks map[string]AsyncTask `json:"async_tasks,omitempty"`
}

Session represents a chat session with its full message history.

type SessionMeta

type SessionMeta struct {
	Key          string    `json:"key"`
	UpdatedAt    time.Time `json:"updated_at"`
	MessageCount int       `json:"message_count"`
	// Title is the human-readable label attached to the session via
	// SessionTitler.SetTitle (typically produced by builtin.GenerateTitle
	// on the first turn). Empty when the backend has none. Backends without
	// the SessionTitler capability always return "".
	Title     string     `json:"title,omitempty"`
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
}

SessionMeta is the lightweight per-session shape returned by SessionManager.Query. Backends populate every field except DeletedAt (non-nil only for soft-deleted sessions surfaced via SessionQueryOpts.IncludeDeleted) and Title (empty until a caller records one via the SessionTitler capability).

type SessionMetaOrder

type SessionMetaOrder string

SessionMetaOrder controls the sort key used by SessionManager.Query.

const (
	// SessionMetaOrderRecent sorts by UpdatedAt descending (default — the
	// shape every "list my sessions" sidebar wants out of the box).
	SessionMetaOrderRecent SessionMetaOrder = "updated_at_desc"
	// SessionMetaOrderOldest sorts by UpdatedAt ascending. Useful for
	// audit / archival flows that want chronological order.
	SessionMetaOrderOldest SessionMetaOrder = "updated_at_asc"
	// SessionMetaOrderKey sorts lexicographically by Key. Useful for
	// stable pagination when UpdatedAt may collide at second resolution.
	SessionMetaOrderKey SessionMetaOrder = "key_asc"
)

type SessionQueryOpts

type SessionQueryOpts struct {
	Limit          int              // 0 = no limit
	Offset         int              // pagination cursor
	OrderBy        SessionMetaOrder // "" defaults to SessionMetaOrderRecent
	IncludeDeleted bool             // include soft-deleted sessions
}

SessionQueryOpts configures SessionManager.Query. Zero values are safe defaults: Limit=0 means "no limit", OrderBy="" means recent-first, IncludeDeleted=false filters soft-deleted sessions out.

type SummaryProvider

type SummaryProvider interface {
	SummarizeBehaviors(ctx context.Context, newMessages []Message, previousSummary string) (string, error)
}

SummaryProvider represents a very cheap LLM model (e.g., gemini-1.5-flash / gpt-4o-mini) exclusively tasked with finding long-term patterns in user requests.

previousSummary is the existing behavioral profile (empty string on first call). The implementation should merge new evidence from newMessages into previousSummary rather than rebuilding from scratch, saving tokens and preserving accumulated knowledge.

type ToolCall

type ToolCall struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"` // raw JSON string
	// ProviderMeta is opaque provider state for this call that must be sent
	// back unchanged with it (for example Gemini's thought signature).
	// Bounded by the provider (a few hundred bytes per call); nil otherwise.
	ProviderMeta []byte `json:"provider_meta,omitempty"`
}

ToolCall represents a tool invocation declared by the assistant.

Directories

Path Synopsis
Package historyfake provides a test-friendly SessionManager fake for consumers writing agent-integration tests without standing up a real session backend.
Package historyfake provides a test-friendly SessionManager fake for consumers writing agent-integration tests without standing up a real session backend.

Jump to

Keyboard shortcuts

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