memory

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package memory persists event payloads as generic maps so stores can serialize them uniformly, but runtime and transcript code should interact with the typed payload structs in this file. Each event kind owns its map encoding here so the rest of the runtime never reaches into stringly-typed event data.

Package memory exposes agent memory storage contracts and helpers for persisting and retrieving agent run history. Memory stores record the chronological sequence of messages, tool calls, and results so planners can reference prior turns when generating responses.

Index

Constants

View Source
const (
	// VisibilityUser scopes memory to one resolved user.
	VisibilityUser Visibility = "user"
	// VisibilityShared scopes memory to explicitly shared knowledge.
	VisibilityShared Visibility = "shared"

	// SourceRunEvent identifies entries extracted from transcript events.
	SourceRunEvent SourceKind = "run_event"
	// SourceDirect identifies direct application writes.
	SourceDirect SourceKind = "direct"
	// SourceExternal identifies imported entries from external systems.
	SourceExternal SourceKind = "external"

	// ToolSourceTranscript exposes current-run transcript memory.
	ToolSourceTranscript ToolSource = "transcript"
	// ToolSourceIndexedTranscript exposes indexed raw transcript search.
	ToolSourceIndexedTranscript ToolSource = "indexed_transcript"
	// ToolSourceLongTerm exposes entry-shaped long-term memory search.
	ToolSourceLongTerm ToolSource = "long_term"
)

Variables

This section is empty.

Functions

func FormatEntriesForPrompt added in v1.2.2

func FormatEntriesForPrompt(entries []Entry) string

FormatEntriesForPrompt renders long-term memory entries into stable planner prompt text.

Types

type Annotation

type Annotation struct {
	// Message is the textual annotation provided by the planner or policy engine.
	Message string
	// Labels carries structured metadata associated with the annotation, used for
	// filtering or categorization (e.g., {"severity": "warning"}).
	Labels map[string]string
}

Annotation represents planner-supplied metadata appended during execution. Annotations are typically persisted as EventAnnotation entries.

type AssistantMessageData

type AssistantMessageData struct {
	// Message is the assistant text content.
	Message string
	// Structured carries optional typed assistant output.
	Structured any
}

AssistantMessageData stores a final assistant response payload.

func DecodeAssistantMessageData

func DecodeAssistantMessageData(event Event) (AssistantMessageData, error)

DecodeAssistantMessageData reconstructs typed assistant-message payload data.

func (AssistantMessageData) EventType

func (AssistantMessageData) EventType() EventType

EventType reports the persisted event kind for an assistant message.

func (*AssistantMessageData) FromMap

func (d *AssistantMessageData) FromMap(data any) error

FromMap reconstructs typed assistant-message data from the persisted map shape.

func (AssistantMessageData) ToMap

func (d AssistantMessageData) ToMap() map[string]any

ToMap converts the assistant message payload into its persisted map shape.

type Entry added in v1.2.2

type Entry struct {
	ID        string
	Scope     Scope
	Content   string
	Author    string
	Timestamp time.Time
	Sources   []SourceRef
	Labels    map[string]string
	Metadata  map[string]any
}

Entry is durable long-term memory state.

type Event

type Event struct {
	// Type indicates the category of the event (message, tool call, result, etc.).
	Type EventType
	// Timestamp marks when the event occurred, used for ordering and filtering.
	Timestamp time.Time
	// Data holds the event-specific payload encoded as a generic map for storage.
	// Callers should construct and decode it via the typed helpers in
	// `event_data.go` instead of reaching into string keys directly.
	Data any
	// Labels provides structured metadata for filtering, querying, or policy decisions.
	// Examples: {"role": "user"}, {"tool": "search"}, {"error": "timeout"}.
	Labels map[string]string
}

Event describes a single entry persisted to the memory store. Events form a chronological log of the agent's interactions, tool invocations, and responses.

func NewEvent

func NewEvent(timestamp time.Time, data EventData, labels map[string]string) Event

NewEvent converts typed event data into the persisted Event form.

type EventData

type EventData interface {
	// EventType reports which persisted event kind this payload belongs to.
	EventType() EventType
	// ToMap converts the typed payload into the generic storage representation.
	ToMap() map[string]any
}

EventData describes a typed persisted event payload that can marshal itself into the generic map form stored by memory backends.

type EventType

type EventType string

EventType enumerates persisted memory event categories. Each type corresponds to a different kind of interaction or system event during agent execution.

const (
	// EventUserMessage records an end-user utterance or input message.
	EventUserMessage EventType = "user_message"

	// EventAssistantMessage records an assistant response or output message.
	EventAssistantMessage EventType = "assistant_message"

	// EventToolCall records a tool invocation request, including the tool name
	// and arguments passed to it.
	EventToolCall EventType = "tool_call"

	// EventToolResult records the outcome of a tool invocation, including the
	// return value or error.
	EventToolResult EventType = "tool_result"

	// EventPlannerNote records planner-generated notes, thoughts, or reasoning
	// steps emitted during plan generation.
	EventPlannerNote EventType = "planner_note"

	// EventThinking records provider-issued reasoning blocks (plaintext+signature or
	// redacted bytes). These reconstruct as the head of assistant messages that
	// contain tool_use when thinking mode is enabled.
	EventThinking EventType = "thinking"
)

type IngestEventsInput added in v1.2.2

type IngestEventsInput struct {
	Scope        Scope
	AgentID      string
	SessionID    string
	RunID        string
	StartOrdinal int
	Events       []Event
	Labels       map[string]string
	Metadata     map[string]any
}

IngestEventsInput asks a service to extract entries from event deltas.

type IngestResult added in v1.2.2

type IngestResult struct {
	Entries   []Entry
	Skipped   int
	Truncated bool
}

IngestResult reports entries written by an ingest call.

type IngestRunInput added in v1.2.2

type IngestRunInput struct {
	Scope     Scope
	AgentID   string
	SessionID string
	RunID     string
	Events    []Event
	Labels    map[string]string
	Metadata  map[string]any
}

IngestRunInput asks a service to extract entries from a completed run.

type PlannerNoteData

type PlannerNoteData struct {
	// Note is the planner annotation text.
	Note string
}

PlannerNoteData stores planner-generated annotations.

func DecodePlannerNoteData

func DecodePlannerNoteData(event Event) (PlannerNoteData, error)

DecodePlannerNoteData reconstructs typed planner-note payload data.

func (PlannerNoteData) EventType

func (PlannerNoteData) EventType() EventType

EventType reports the persisted event kind for a planner note.

func (*PlannerNoteData) FromMap

func (d *PlannerNoteData) FromMap(data any) error

FromMap reconstructs typed planner-note data from the persisted map shape.

func (PlannerNoteData) ToMap

func (d PlannerNoteData) ToMap() map[string]any

ToMap converts the planner note payload into its persisted map shape.

type PutEntryInput added in v1.2.2

type PutEntryInput struct {
	Scope     Scope
	Content   string
	Author    string
	Timestamp time.Time
	Sources   []SourceRef
	Labels    map[string]string
	Metadata  map[string]any
}

PutEntryInput writes a direct long-term memory entry.

type Query added in v1.2.2

type Query struct {
	AgentID   string
	RunID     string
	SessionID string
	Labels    map[string]string
	Types     []EventType
	Limit     int
}

Query filters memory events. AgentID and RunID scope stores that can address those dimensions directly; SessionID is matched from event labels.

type QueryResult added in v1.2.2

type QueryResult struct {
	Events    []Event
	Truncated bool
}

QueryResult contains matching memory events in chronological order.

func QueryEvents added in v1.2.2

func QueryEvents(events []Event, query Query) QueryResult

QueryEvents filters events in memory using query labels, event types, session, and limit. Returned events are chronological and defensively copied.

type Reader

type Reader interface {
	// Events returns all events in chronological order.
	Events() []Event

	// FilterByType returns events matching the given type, preserving chronological order.
	FilterByType(t EventType) []Event

	// Latest returns the most recent event of the given type. The boolean return
	// indicates whether an event was found (false if no events of that type exist).
	Latest(t EventType) (Event, bool)
}

Reader provides read-only access to a snapshot, used by planners to query prior turns. Implementations typically wrap a Snapshot and provide convenience methods for filtering and lookup.

type RetryHintData added in v1.0.1

type RetryHintData struct {
	Reason             string
	Tool               tools.Ident
	RestrictToTool     bool
	MissingFields      []string
	ExampleInput       map[string]any
	PriorInput         map[string]any
	ClarifyingQuestion string
	Message            string
}

RetryHintData stores the durable retry guidance associated with a tool result without importing planner types into the memory package.

type Scope added in v1.2.2

type Scope struct {
	Namespace  string
	UserID     string
	Visibility Visibility
}

Scope routes durable memory entries and queries.

type ScopeInput added in v1.2.2

type ScopeInput struct {
	AgentID    string
	SessionID  string
	RunID      string
	Visibility Visibility
	Labels     map[string]string
	Payload    map[string]any
}

ScopeInput carries runtime context used to resolve a memory scope.

type ScopeResolver added in v1.2.2

type ScopeResolver interface {
	ResolveMemoryScope(ctx context.Context, input ScopeInput) (Scope, error)
}

ScopeResolver derives tenant and user routing for runtime-owned memory calls.

type ScopeResolverFunc added in v1.2.2

type ScopeResolverFunc func(ctx context.Context, input ScopeInput) (Scope, error)

ScopeResolverFunc adapts a function to ScopeResolver.

func (ScopeResolverFunc) ResolveMemoryScope added in v1.2.2

func (f ScopeResolverFunc) ResolveMemoryScope(ctx context.Context, input ScopeInput) (Scope, error)

ResolveMemoryScope calls f(ctx, input).

type SearchHit added in v1.2.2

type SearchHit struct {
	Entry       Entry
	Score       float64
	Snippet     string
	MatchedRefs []SourceRef
}

SearchHit is one query-time match.

type SearchQuery added in v1.2.2

type SearchQuery struct {
	Scope  Scope
	Query  string
	Labels map[string]string
	Limit  int
}

SearchQuery filters long-term memory entries.

type SearchResult added in v1.2.2

type SearchResult struct {
	Hits      []SearchHit
	Truncated bool
}

SearchResult contains ranked long-term memory hits.

type Searcher added in v1.2.2

type Searcher interface {
	Query(ctx context.Context, query Query) (QueryResult, error)
}

Searcher provides indexed or cross-run memory lookup without changing the append/load Store contract.

type SearcherFunc added in v1.2.2

type SearcherFunc func(ctx context.Context, query Query) (QueryResult, error)

SearcherFunc adapts a function to Searcher.

func (SearcherFunc) Query added in v1.2.2

func (f SearcherFunc) Query(ctx context.Context, query Query) (QueryResult, error)

Query calls f(ctx, query).

type Service added in v1.2.2

type Service interface {
	IngestRun(ctx context.Context, input IngestRunInput) (IngestResult, error)
	IngestEvents(ctx context.Context, input IngestEventsInput) (IngestResult, error)
	PutEntry(ctx context.Context, input PutEntryInput) (Entry, error)
	Search(ctx context.Context, query SearchQuery) (SearchResult, error)
}

Service stores and searches long-term memory entries. It is separate from Store, which persists raw run transcripts.

type Snapshot

type Snapshot struct {
	// AgentID identifies the agent that produced this run.
	AgentID string
	// RunID identifies the workflow run associated with this snapshot.
	RunID string
	// Events lists the chronological memory events persisted so far, ordered by
	// Timestamp ascending. Empty if the run has no history yet.
	Events []Event
	// Meta carries implementation-defined metadata such as database cursors,
	// version numbers, or sync tokens. Planners should not rely on these fields.
	Meta map[string]any
}

Snapshot captures the durable state of a run at a point in time. Snapshots are immutable once returned by LoadRun; concurrent writes create new snapshots.

type SourceKind added in v1.2.2

type SourceKind string

SourceKind describes where a long-term memory entry came from.

type SourceRef added in v1.2.2

type SourceRef struct {
	Kind           SourceKind
	AgentID        string
	SessionID      string
	RunID          string
	EventOrdinal   int
	EventHash      string
	ToolCallID     string
	ExternalID     string
	IdempotencyKey string
}

SourceRef identifies source material used to produce an entry.

type Store

type Store interface {
	// LoadRun retrieves the snapshot for the given agent and run. Returns an empty
	// snapshot (not an error) if the run doesn't exist yet, allowing callers to
	// treat absence as empty history. Returns an error only for storage failures
	// or connectivity issues.
	LoadRun(ctx context.Context, agentID, runID string) (Snapshot, error)

	// AppendEvents appends events to the run's history. Events should be written
	// atomically if the backend supports it. Returns an error if the write fails.
	// Implementations may deduplicate or reject events based on timestamps or IDs.
	AppendEvents(ctx context.Context, agentID, runID string, events ...Event) error
}

Store persists agent run history so planners and tooling can inspect prior turns. Implementations must be thread-safe and handle concurrent reads/writes to the same run. Production deployments typically use a durable backend (MongoDB, DynamoDB, etc.); see features/memory/mongo for an example.

type ThinkingData

type ThinkingData struct {
	// Text is the plaintext reasoning content.
	Text string
	// Signature is the provider-issued signature for plaintext reasoning.
	Signature string
	// Redacted holds opaque redacted reasoning bytes.
	Redacted []byte
	// ContentIndex is the provider content block index.
	ContentIndex int
	// Final reports whether the provider finalized this block.
	Final bool
}

ThinkingData stores provider-issued reasoning blocks for exact replay.

func DecodeThinkingData

func DecodeThinkingData(event Event) (ThinkingData, error)

DecodeThinkingData reconstructs typed thinking-block payload data.

func (ThinkingData) EventType

func (ThinkingData) EventType() EventType

EventType reports the persisted event kind for a thinking block.

func (*ThinkingData) FromMap

func (d *ThinkingData) FromMap(data any) error

FromMap reconstructs typed thinking data from the persisted map shape.

func (ThinkingData) ToMap

func (d ThinkingData) ToMap() map[string]any

ToMap converts the thinking payload into its persisted map shape.

type ToolCallData

type ToolCallData struct {
	// ToolCallID uniquely identifies the invocation.
	ToolCallID string
	// ParentToolCallID links nested tool calls to their parent.
	ParentToolCallID string
	// ToolName is the canonical tool identifier.
	ToolName tools.Ident
	// PayloadJSON is the canonical JSON encoding of the tool input.
	PayloadJSON rawjson.Message
	// Queue is the activity queue where execution was scheduled.
	Queue string
	// ExpectedChildrenTotal records the expected number of child calls.
	ExpectedChildrenTotal int
}

ToolCallData stores the persisted form of a scheduled tool invocation.

func DecodeToolCallData

func DecodeToolCallData(event Event) (ToolCallData, error)

DecodeToolCallData reconstructs typed tool-call payload data.

func (ToolCallData) EventType

func (ToolCallData) EventType() EventType

EventType reports the persisted event kind for a tool call.

func (*ToolCallData) FromMap

func (d *ToolCallData) FromMap(data any) error

FromMap reconstructs typed tool-call data from the persisted map shape.

func (ToolCallData) Input

func (d ToolCallData) Input() (any, error)

Input decodes the canonical tool-call payload into a plain JSON-compatible value.

func (ToolCallData) ToMap

func (d ToolCallData) ToMap() map[string]any

ToMap converts the tool call payload into its persisted map shape.

type ToolResultData

type ToolResultData struct {
	// ToolCallID uniquely identifies the invocation.
	ToolCallID string
	// ParentToolCallID links nested tool calls to their parent.
	ParentToolCallID string
	// ToolName is the canonical tool identifier.
	ToolName tools.Ident
	// ResultJSON is the canonical JSON encoding of the successful result.
	ResultJSON rawjson.Message
	// ServerData carries server-only tool result data that must not be sent to models.
	ServerData rawjson.Message
	// Preview is the already-rendered user-facing result summary.
	Preview string
	// Bounds describes bounded-result metadata when present.
	Bounds *agent.Bounds
	// Duration is the wall-clock tool execution time.
	Duration time.Duration
	// Telemetry carries structured execution metrics when present.
	Telemetry *telemetry.ToolTelemetry
	// RetryHint carries structured repair guidance for failed tool calls.
	RetryHint *RetryHintData
	// ErrorMessage is the plain-text tool failure message.
	ErrorMessage string
	// Artifacts contains persisted artifact references associated with the result.
	Artifacts []artifact.Ref
}

ToolResultData stores the persisted form of a completed tool invocation.

func DecodeToolResultData

func DecodeToolResultData(event Event) (ToolResultData, error)

DecodeToolResultData reconstructs typed tool-result payload data.

func (ToolResultData) EventType

func (ToolResultData) EventType() EventType

EventType reports the persisted event kind for a tool result.

func (*ToolResultData) FromMap

func (d *ToolResultData) FromMap(data any) error

FromMap reconstructs typed tool-result data from the persisted map shape.

func (ToolResultData) ToMap

func (d ToolResultData) ToMap() map[string]any

ToMap converts the tool result payload into its persisted map shape.

type ToolSource added in v1.2.2

type ToolSource string

ToolSource selects which memory tools a generated memory toolset exposes.

type UserMessageData

type UserMessageData struct {
	// Message is the user-visible text content.
	Message string
	// Structured carries optional typed user payloads.
	Structured any
}

UserMessageData stores a durable end-user message payload when runtimes choose to persist user utterances.

func DecodeUserMessageData

func DecodeUserMessageData(event Event) (UserMessageData, error)

DecodeUserMessageData reconstructs typed user-message payload data.

func (UserMessageData) EventType

func (UserMessageData) EventType() EventType

EventType reports the persisted event kind for a user message.

func (*UserMessageData) FromMap

func (d *UserMessageData) FromMap(data any) error

FromMap reconstructs typed user-message data from the persisted map shape.

func (UserMessageData) ToMap

func (d UserMessageData) ToMap() map[string]any

ToMap converts the user message payload into its persisted map shape.

type Visibility added in v1.2.2

type Visibility string

Visibility controls whether memory is user-private or explicitly shared.

Directories

Path Synopsis
Package inmem provides an in-memory implementation of memory.Store for testing and local development.
Package inmem provides an in-memory implementation of memory.Store for testing and local development.

Jump to

Keyboard shortcuts

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