memory

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 13 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

Index

Constants

View Source
const DefaultCompactThreshold = 0.85

DefaultCompactThreshold is the fraction of the token budget at which automatic compaction triggers (85% capacity).

View Source
const DefaultTokenBudget = 100_000

DefaultTokenBudget is the heuristic context budget applied when no explicit limit is configured; it fits typical frontier model windows with headroom reserved for tool schemas and responses.

Variables

This section is empty.

Functions

func DefaultSessionsDir

func DefaultSessionsDir() (string, error)

DefaultSessionsDir resolves ~/.krew/sessions, the canonical transcript storage location.

func EstimateTokens

func EstimateTokens(text string) int

EstimateTokens returns a fast heuristic token count for a text segment. It approximates BPE counts without paying a tokenizer dependency.

func LoadSession

func LoadSession(dir, sessionID string) ([]ai.Message, error)

LoadSession replays a stored transcript as conversation messages in FIFO order. Well-formed records are expected; a corrupt line aborts loading.

func MessageTokens

func MessageTokens(msg ai.Message) int

MessageTokens estimates the token cost of one conversation message, including its tool call payloads.

func RenderTranscriptMarkdown

func RenderTranscriptMarkdown(dir, sessionID string) (string, error)

RenderTranscriptMarkdown loads a stored transcript and renders it as a readable Markdown document with per-role sections. Tool calls appear as fenced request blocks and tool results as fenced output blocks.

func SessionName

func SessionName(prompt string) string

SessionName derives a filesystem-safe transcript name from the first user prompt: lowercased slug words joined with dashes, capped in length.

Types

type Buffer

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

Buffer implements an in-memory sliding-window conversation memory.

func NewBuffer

func NewBuffer(systemPrompt string, maxMessages int) *Buffer

NewBuffer creates a conversation memory buffer with an optional message limit.

func (*Buffer) Add

func (b *Buffer) Add(msgs ...ai.Message)

Add appends one or more messages to the buffer.

func (*Buffer) Clear

func (b *Buffer) Clear()

Clear removes all conversation messages.

func (*Buffer) Compact

func (b *Buffer) Compact(maxMessages int)

Compact trims old messages if estimate exceeds limit, preserving the most recent turns.

func (*Buffer) Len

func (b *Buffer) Len() int

Len returns the count of conversation messages.

func (*Buffer) Messages

func (b *Buffer) Messages() []ai.Message

Messages returns a copy of all conversation messages including system message.

func (*Buffer) RawMessages

func (b *Buffer) RawMessages() []ai.Message

RawMessages returns only the conversation messages without the system prompt.

func (*Buffer) SetSystem

func (b *Buffer) SetSystem(sys string)

SetSystem updates or sets the system prompt.

func (*Buffer) System

func (b *Buffer) System() string

System returns the system prompt.

type Compactor

type Compactor func(ctx context.Context, evicted []ai.Message) (string, error)

Compactor condenses evicted conversation turns into a single checkpoint summary. Implementations typically call an LLM; tests inject closures.

func LLMCompactor

func LLMCompactor(provider ai.Provider, model string) Compactor

LLMCompactor adapts an ai.Provider into a Compactor that compresses evicted turns into a model-generated checkpoint summary in one completion call.

type Memory

type Memory interface {
	Add(msgs ...ai.Message)
	Messages() []ai.Message
	Clear()
	Len() int
	Compact(maxTokens int)
}

Memory manages conversation messages and context compaction.

type SessionInfo

type SessionInfo struct {
	ID       string    `json:"id"`
	ModTime  time.Time `json:"mod_time"`
	Messages int       `json:"messages"`
	Tokens   int       `json:"tokens"`
}

SessionInfo summarises a stored transcript for session listings.

func ListSessions

func ListSessions(dir string) ([]SessionInfo, error)

ListSessions summarises every stored transcript under dir, newest first.

type SessionLog

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

SessionLog appends conversation turns to a JSON Lines transcript file.

func OpenSessionLog

func OpenSessionLog(dir, sessionID string) (*SessionLog, error)

OpenSessionLog opens (creating when needed) the transcript for sessionID under dir in append mode. Callers must Close the log; every Append is flushed to disk immediately.

func StartSession

func StartSession(dir, prompt string) (*SessionLog, string, error)

StartSession derives a unique transcript name from the first user prompt (slug summary with -2, -3… suffixes on collision) and opens its log. The caller must Close the returned log.

func (*SessionLog) Append

func (l *SessionLog) Append(msgs ...ai.Message) error

Append writes one JSONL line per message and flushes both to disk.

func (*SessionLog) Close

func (l *SessionLog) Close() error

Close flushes and releases the transcript file. Append after Close fails.

func (*SessionLog) Path

func (l *SessionLog) Path() string

Path returns the transcript file location.

type SessionRecord

type SessionRecord struct {
	Time    int64      `json:"time"` // Unix nanoseconds, UTC
	Message ai.Message `json:"message"`
}

SessionRecord is one JSONL transcript line: a message with its append time.

type TokenBuffer

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

TokenBuffer implements Memory with token-accounted sliding-window eviction and automatic checkpoint compaction. It permanently preserves the system prompt, the initial user goal, and the most recent turns. Older turns are evicted and, when a Compactor is configured, compressed into one checkpoint summary asynchronously.

func NewTokenBuffer

func NewTokenBuffer(systemPrompt string, opts ...TokenBufferOption) *TokenBuffer

NewTokenBuffer builds a token-aware sliding-window memory.

func (*TokenBuffer) Add

func (b *TokenBuffer) Add(msgs ...ai.Message)

Add appends messages, captures the initial goal, and evicts or compacts whenever the buffer reaches the configured capacity threshold.

func (*TokenBuffer) Clear

func (b *TokenBuffer) Clear()

Clear removes all conversation state except the system prompt and invalidates any in-flight compaction results; completed rewrites are discarded by their generation check, so Clear never blocks on a user supplied Compactor.

func (*TokenBuffer) Compact

func (b *TokenBuffer) Compact(budget int)

Compact forces token-based eviction to fit the given heuristic token budget, bypassing the capacity threshold. It satisfies the Memory interface.

func (*TokenBuffer) Len

func (b *TokenBuffer) Len() int

Len returns the count of survived conversation messages (goal excluded).

func (*TokenBuffer) Messages

func (b *TokenBuffer) Messages() []ai.Message

Messages returns a copy of the send-ready context: system prompt, checkpoint summaries, the initial goal, and surviving turns in FIFO order.

func (*TokenBuffer) RawMessages

func (b *TokenBuffer) RawMessages() []ai.Message

RawMessages returns only the captured goal and surviving turns, without the system prompt or checkpoint blocks.

func (*TokenBuffer) SetSystem

func (b *TokenBuffer) SetSystem(sys string)

SetSystem updates or sets the system prompt.

func (*TokenBuffer) System

func (b *TokenBuffer) System() string

System returns the system prompt.

func (*TokenBuffer) Tokens

func (b *TokenBuffer) Tokens() int

Tokens reports the current heuristic token estimate of all content the buffer keeps (system prompt, checkpoints, goal, and turns).

func (*TokenBuffer) Wait

func (b *TokenBuffer) Wait()

Wait blocks until every in-flight background compaction has settled.

type TokenBufferOption

type TokenBufferOption func(*TokenBuffer)

TokenBufferOption customises a TokenBuffer at construction.

func WithCompactThreshold

func WithCompactThreshold(f float64) TokenBufferOption

WithCompactThreshold overrides the compaction trigger fraction.

func WithCompactor

func WithCompactor(c Compactor) TokenBufferOption

WithCompactor installs the summarizer invoked when eviction occurs.

func WithKeepTurns

func WithKeepTurns(n int) TokenBufferOption

WithKeepTurns sets how many most-recent messages are always preserved during eviction. Non-positive values fall back to 12.

func WithMaxTokens

func WithMaxTokens(maxTokens int) TokenBufferOption

WithMaxTokens sets the total heuristic token budget. Non-positive values fall back to DefaultTokenBudget.

Jump to

Keyboard shortcuts

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