memory

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 75 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 memory ports the icebath memory system, the MEMORY.md and USER.md stores, providers, curator and journey

Index

Constants

View Source
const (
	AgeOldInk = 0.42
	AgeMidInk = 0.74
	AgeNewInk = 0.95
	AgeMid    = 0.52
)

Age gradient inks, old quiet and recent bright

View Source
const (
	StyleBG     = "bg"
	StyleSkill  = "skill"
	StyleMemory = "memory"
	StyleLabel  = "label"
	StyleDim    = "dim"
)

Style keys consumers map to base colors, the run alpha giving brightness

View Source
const (
	SkillGlyph  = "\u25cf"
	MemoryGlyph = "\u25c6"
)

Legend glyphs of the node shapes

View Source
const (
	SourceBundled = "bundled"
	SourceUser    = "user"
	SourceProject = "project"
)

Discovery sources in precedence order, bundled first so a provider dropped in a tree never shadows a shipped one

View Source
const (
	DefaultMemoryCharLimit = 2200
	DefaultUserCharLimit   = 1375
)

Default character budgets of the two stores

View Source
const (
	ScopeAll     = "all"
	ScopeContext = "context"
	ScopeStrict  = "strict"
)

Scope names a scanner accepts, cumulative from all through context to strict

View Source
const CallerProfileRefusal = "memory_caller_profile_unresolved"

Check code logged when a memory call names no profile or the wrong one

View Source
const CuratorDryRunBanner = "" /* 1305-byte string literal not displayed */

Banner prepended to the review prompt when the curator previews a run without mutating skills

View Source
const CuratorReviewPrompt = "" /* 10428-byte string literal not displayed */

Instructions the forked review agent follows for the umbrella building consolidation pass

View Source
const EntryDelimiter = "\n§\n"

Separator between entries inside MEMORY.md and USER.md

View Source
const (
	ExporterVersion = "icebath sessions export (md/qmd) v1"
)
View Source
const (

	// A process turn free this long runs the one full collection the busy path trims skip
	IdleCollectAfter = 300 * time.Second
)
View Source
const IndicatorGlyph = "\U0001F9E0"

Default mark for recall indicators, providers may use their own brand mark

View Source
const LeadIn = 0.06

Recency of the oldest node, just off zero on the time axis

View Source
const ManagerValuesKey = "memory"

Values key holding the per session Manager

View Source
const MaxScanChars = 65536

Hard cap on scanned text so the advisory scanners stay bounded

View Source
const PatchDropHint = "To drop text inside an entry, patch a longer span that contains it; 'remove' deletes the whole entry."

Hint naming how to drop text inside an entry without losing its siblings

View Source
const PreCompressCheckpointAPIVersion = 2

Checkpoint contract version a provider advertises when every successful pre compress hook is durable

View Source
const RedactionUnavailable = "[redaction-unavailable]"

Marker returned when the redactor itself fails so raw text never leaves the process

View Source
const ReviewAttendedValuesKey = "review_attended"

Values key marking a background review the user explicitly asked for, true means attended

View Source
const SharedInstanceRefusal = "memory_provider_instance_shared"

Check code logged when one provider instance is offered to a second profile

Variables

View Source
var BlockHeaders = map[string]string{
	"memory": "MEMORY (your personal notes)",
	"user":   "USER PROFILE (who the user is)",
}

Block header titles the prompt renderer and compression share to spot a leftover block

View Source
var CuratorHooks struct {
	ReferencedSkillNames func(ctx context.Context, home string) (map[string]bool, error)
	RewriteSkillRefs     func(ctx context.Context, home string, consolidated *jsonutil.Object, pruned []string) (CuratorCronRewriteReport, error)
	UpdateJobs           func(ctx context.Context, home string, update func(jobs []any) (bool, error)) error
	RunReview            func(ctx context.Context, req CuratorReviewRequest) (*CuratorReviewResult, error)
}

CuratorHooks is the cron and agent access the curator reaches, installed by pkg/cron and pkg/agent in init

View Source
var InvisibleChars = map[rune]bool{
	'\u200b': true, '\u200c': true, '\u200d': true, '\u2060': true, '\u2062': true, '\u2063': true, '\u2064': true, '\ufeff': true,
	'\u202a': true, '\u202b': true, '\u202c': true, '\u202d': true, '\u202e': true, '\u2066': true, '\u2067': true, '\u2068': true, '\u2069': true,
}

Invisible and bidirectional code points used in injection attacks

View Source
var MemoryGuidance = BuildMemoryGuidance(true, true, true)

Full guidance with both stores and skill writing available

View Source
var UserProfileGuidance = BuildMemoryGuidance(false, true, true)

Guidance for a session whose only store is the user profile

Functions

func ActiveMemoryProvider

func ActiveMemoryProvider(ctx context.Context, env *tools.Env) string

Active provider name from memory.provider, empty when unset

func AppendManifestEntry

func AppendManifestEntry(outputDir string, session *jsonutil.Object, path, format string) (string, error)

Appends the record of one written export to manifest.jsonl in the directory and returns the manifest path

func ApplyCuratorTransitions

func ApplyCuratorTransitions(ctx context.Context, now time.Time) (*jsonutil.Object, error)

Moves every curator managed skill between active, stale and archived by its latest activity

func ArchiveSkill

func ArchiveSkill(ctx context.Context, env *tools.Env, name string) (bool, string, error)

Moves a curation eligible skill of the env home into the archive, false with the refusal message otherwise

func AxisLabels

func AxisLabels(payload map[string]any) (map[string]string, error)

Start and end dates of a timed graph, oldest and now otherwise

func BuildEdges

func BuildEdges(nodes []*SkillNode) [][2]string

Undirected related skill edges whose endpoints both exist, deduped in first seen order

func BuildLearnPrompt

func BuildLearnPrompt(userRequest string) string

Prompt for an open ended learn request, an empty request meaning the workflow just completed

func BuildLearningGraph

func BuildLearningGraph(ctx context.Context, env *tools.Env) (map[string]any, error)

Learning panel payload of non bundled skills with learning signal plus memory entries as nodes

func BuildLegend

func BuildLegend(payload map[string]any) ([]map[string]any, error)

Skill and memory legend entries with their counts

func BuildMemoryContextBlock

func BuildMemoryContextBlock(rawContext string) string

Prefetched memory wrapped in a fenced block with the system note, empty for blank input

func BuildMemoryGuidance

func BuildMemoryGuidance(memoryEnabled, profileEnabled, skillManageAvailable bool) string

Store and skill write guidance adapted to the enabled stores without widening what belongs in memory

func BuildSummary

func BuildSummary(payload map[string]any) ([]string, error)

Summary lines of learned skills, memories, links, and the busiest day

func BuiltinMemoryStoreFlags

func BuiltinMemoryStoreFlags(ctx context.Context) (bool, bool)

Memory and user profile store flags of the home in ctx

func CatalogInstallHint

func CatalogInstallHint(ctx context.Context, name, category string) string

Install command for a catalog plugin of the category, empty when the in tree catalog lacks it or the lookup fails

func CatalogSource

func CatalogSource(name string) (string, bool)

Live catalog entry name shipping the provider, false when the catalog has no such plugin

func CategoryColorMap

func CategoryColorMap(payload map[string]any) (map[string]string, error)

Evenly spread golden angle hue per skill category, independent of the theme

func CategoryLegend

func CategoryLegend(payload map[string]any, limit int) ([]map[string]any, error)

Colored legend entries of the top categories plus a count of the rest

func ClaimInstance

func ClaimInstance(ctx context.Context, p any, h string) bool

Binds the instance to a home, refused on a multiplexed process when another profile holds it or it is untrackable

func CloneMemoryProviderConfig

func CloneMemoryProviderConfig(sourceDir, profileDir, provider string) (bool, error)

Copies the provider directory and json file from source into the profile owner only, true when anything copied

func ClonedMemoryProvider

func ClonedMemoryProvider(ctx context.Context, profileDir string) string

External provider whose config the profile now carries, empty when nothing was cloned for it

func CmdInsights

func CmdInsights(ctx context.Context, out io.Writer, days int, source string)

Prints the terminal insights report for the home state.db, the no data line when absent and the error line on failure

func ConfiguredMemoryProvider

func ConfiguredMemoryProvider(ctx context.Context, h string) (string, error)

Effective memory.provider of a home, empty when unset, an error when the memory block is not a mapping

func CtxBound

func CtxBound(ctx context.Context) context.Context

Spawner values without its cancellation over a copy of its Python context, as contextvars copy_context gives a thread

func CuratorArchiveAfterDays

func CuratorArchiveAfterDays(ctx context.Context) int

Days of inactivity before a skill is archived

func CuratorBackupEnabled

func CuratorBackupEnabled(ctx context.Context) bool

Snapshot before mutating passes, on unless curator.backup.enabled is false

func CuratorBackupKeep

func CuratorBackupKeep(ctx context.Context) int

Snapshots kept by the prune, at least one

func CuratorConsolidate

func CuratorConsolidate(ctx context.Context) bool

Whether the LLM consolidation pass runs, off by default

func CuratorIntervalHours

func CuratorIntervalHours(ctx context.Context) int

Hours between automatic passes

func CuratorIsEnabled

func CuratorIsEnabled(ctx context.Context) bool

Curator enabled flag, on unless the settings say otherwise

func CuratorIsPaused

func CuratorIsPaused(ctx context.Context) (bool, error)

Whether the persisted state marks the curator paused

func CuratorMinIdleHours

func CuratorMinIdleHours(ctx context.Context) float64

Idle hours a session needs before an automatic pass

func CuratorShouldRunNow

func CuratorShouldRunNow(ctx context.Context, now time.Time) (bool, error)

Enabled, unpaused and one interval past the last run, the first sighting seeds the clock and defers

func CuratorStaleAfterDays

func CuratorStaleAfterDays(ctx context.Context) int

Days of inactivity before a skill turns stale

func DeleteNode

func DeleteNode(ctx context.Context, env *tools.Env, nodeID string) (map[string]any, error)

Archives a skill node or removes a memory entry, a pinned skill refused

func DensityStats

func DensityStats(nodes []*SkillNode, edges [][2]string) map[string]any

Graph density figures over skill nodes and their related edges

func DerivePalette

func DerivePalette(primaryHex string, dark bool) map[string]string

Terminal palette derived from a primary color, memories in primary ink and skills in a muted complement

func DestructiveOps

func DestructiveOps(payload map[string]any) ([]map[string]any, error)

Replace, patch and remove ops of a staged memory payload in single op or batch shape

func DismissProvider

func DismissProvider(ctx context.Context, p Provider)

Gives back a provider that was loaded only to look at it, the guest of a plugin provider stopping when nothing else uses it

func EditNode

func EditNode(ctx context.Context, env *tools.Env, nodeID, content string) (map[string]any, error)

Rewrites a skill SKILL.md or replaces a memory entry, an empty memory body refused

func EraseBuiltinMemory

func EraseBuiltinMemory(ctx context.Context, target string) ([]string, error)

EraseBuiltinMemory deletes the built-in memory files of the target in the home in the context and answers the names of the ones it deleted

func FileSHA256

func FileSHA256(path string) (string, error)

Hex SHA256 of the bytes of a file

func FindProviderDir

func FindProviderDir(ctx context.Context, env *tools.Env, name string) string

Provider directory of a name, bundled, user, then project, empty when none

func FirstThreatMessage

func FirstThreatMessage(content, scope string) string

User facing error for the first threat found in content, empty when clean

func FormatDate

func FormatDate(ts *float64) string

Day, month and year of a timestamp, unknown for missing, zero, or out of range values

func GetSkillRecord

func GetSkillRecord(h, name string) (map[string]any, error)

Backfilled usage record of one skill in a home, fresh defaults when it has none

func HandlePendingSubcommand

func HandlePendingSubcommand(ctx context.Context, env *tools.Env, subsystem string, args []string, opts PendingOptions) (string, bool, error)

Dispatches a memory or skills write approval subcommand, false when the args are not one so the caller falls through

func HexToRGB

func HexToRGB(s string) [3]int

RGB triple of a hex color, three digit shorthand expanded, the Blackwall accent when unparseable

func HostedProviderName

func HostedProviderName(obj any) (string, bool)

Registration name of a memory provider object, false for any value that is not one

func InOwnerHome

func InOwnerHome[T any](bound *BoundScope, fn func(ctx context.Context) T) func(ctx context.Context) T

Runs fn under the owning profile home override, set explicitly so a background worker never relies on the submitter

func InjectMemoryProviderTools

func InjectMemoryProviderTools(ctx context.Context, env *tools.Env, manager *MemoryManager, surface []map[string]any, validNames map[string]bool) ([]map[string]any, map[string]bool, int)

Appends external provider tool schemas to a tool surface, returning the surface, the valid names and the count added

func IsCoreMemoryProvider

func IsCoreMemoryProvider(name string) bool

Reports whether memory.provider selects the built in store rather than an external plugin

func IsTrivialPrompt

func IsTrivialPrompt(text string) bool

True for empty input, slash commands and bare greetings or acknowledgements

func IsUnattendedReview

func IsUnattendedReview(env *tools.Env) bool

True for a background review fork the user did not explicitly ask for

func JourneyCommand

func JourneyCommand(ctx context.Context, env *tools.Env, ns map[string]any, w io.Writer) (int, error)

Runs icebath journey, show, list, delete and edit

func ListCuratorBackups

func ListCuratorBackups(ctx context.Context) ([]*jsonutil.Object, error)

Manifests of every restorable snapshot, newest first

func LiteralPrefix

func LiteralPrefix(pattern string) string

Leading literal characters of a prefix pattern, the text a synthetic token starts with

func LoadCuratorState

func LoadCuratorState(ctx context.Context) (*jsonutil.Object, error)

Curator scheduler state merged over the defaults, underscore keys kept, a decode failure yields the defaults

func LoadSkillUsage

func LoadSkillUsage(h string) map[string]map[string]any

Usage sidecar of a home as plain maps, empty when the file is missing, corrupt or undecodable

func MaskSecret

func MaskSecret(value string, head, tail, floor int, placeholder, empty string) string

Secret masked for display, keeping head and tail once the value clears the floor

func MaybeRunCurator

func MaybeRunCurator(ctx context.Context, idleForSeconds *float64, onSummary func(string)) *jsonutil.Object

Starts a scheduled pass when every gate passes, nil when it did not run or failed

func MemoryCards

func MemoryCards(h string) ([]map[string]any, error)

MEMORY.md then USER.md entries of a home as cards, one per entry the store parses

func MemoryFingerprint

func MemoryFingerprint(entry string) string

Short stable digest of a memory entry text carried in its node id

func MemoryNodeID

func MemoryNodeID(card map[string]any, index int) string

Node id naming the memory source, the occurrence index, and the text fingerprint

func MemoryOff

func MemoryOff(ctx context.Context, out io.Writer) error

Clears memory.provider in config.yaml so only the built-in memory stays active

func MemoryProviderDependencyInputs

func MemoryProviderDependencyInputs(ctx context.Context, env *tools.Env, name string) (map[string]any, *pm.SyncVenvOptions, error)

Manifest of the provider plugin and the extras and candidate members its preparation needs

func MemoryProviderPresent

func MemoryProviderPresent(ctx context.Context, name, h string) bool

True when the provider resolves for the home through bundled or its user plugins

func MemoryProviderToolsEnabled

func MemoryProviderToolsEnabled(ctx context.Context, env *tools.Env, enabled, disabled []string, memoryToolPresent bool) bool

Whether external provider tools are exposed, enabled nil meaning every toolset

func MemoryProviderToolsExposed

func MemoryProviderToolsExposed(ctx context.Context, env *tools.Env, surface []map[string]any) bool

Whether provider tools are exposed on a tool surface, the same gate the provider prompt block uses

func MemoryReset

func MemoryReset(ctx context.Context, out io.Writer, in io.Reader, target string, yes bool) error

Deletes MEMORY.md, USER.md or both from the home memories dir after a typed yes unless yes is set

func MemorySchema

func MemorySchema() *jsonutil.Object

Full OpenAI function schema of the memory tool

func MemoryTool

func MemoryTool(ctx context.Context, env *tools.Env, store *Store, action, target, content, oldText, newText, operations any) (string, error)

Memory tool entry point returning the JSON result, single op or an atomic operations batch, a crash returned as the error it raised

func MigrateAllMemoryHomes

func MigrateAllMemoryHomes(ctx context.Context, say func(string)) ([]string, error)

Installs the configured catalog provider into every profile home missing it, grouped by provider, the enumeration error unhandled

func MixRGB

func MixRGB(a, b [3]int, t float64) [3]int

Channel wise blend of two colors at t, rounded half to even

func NodeDetail

func NodeDetail(ctx context.Context, env *tools.Env, nodeID string) (map[string]any, error)

Current content of a node for an edit prefill, the full SKILL.md or the raw memory entry

func NormalizeToolSchema

func NormalizeToolSchema(schema any) (map[string]any, bool)

Bare function tool with a resolvable name, unwrapping the OpenAI function wrapper

func NoteAgentClosed

func NoteAgentClosed()

Re-arms the idle collection after an agent closed, even within one quiet period

func NotifyMemoryProvider

func NotifyMemoryProvider(ctx context.Context, profileDir string, call func(ctx context.Context, p Provider) error)

NotifyMemoryProvider runs call on the memory provider the config of a profile selects with that profile's home and its own secrets bound, best effort so a failing provider never fails the create or rename that called it

func ParkedProviderNotice

func ParkedProviderNotice(ctx context.Context, env *tools.Env, name string) (string, bool)

User facing reason a configured provider is not loading because plugins.disabled parks it, false when not parked

func ParseEntries

func ParseEntries(raw string) []string

Stripped non empty entries split on the full delimiter so a bare section sign survives

func ParseNodeKind

func ParseNodeKind(nodeID string) string

Memory for memory node ids, skill for everything else

func PrefixPatterns

func PrefixPatterns() []string

Every built in and plugin secret prefix pattern the matcher runs in registration order, the corpus egress callers test against

func PrepareMemoryProviderDependencies

func PrepareMemoryProviderDependencies(ctx context.Context, env *tools.Env, name string) (map[string]any, string, error)

Syncs the provider's dependency union, installed or restart_required, empty when nothing needed preparing

func PrepareMemoryProviderDependenciesForPlugin

func PrepareMemoryProviderDependenciesForPlugin(ctx context.Context, env *tools.Env, name string) error

Prepares a provider's dependency union for the plugin installer, the readiness status dropped

func ProfileMemoryProvider

func ProfileMemoryProvider(ctx context.Context, profileDir string) string

External memory provider a profile's settings name, empty when it names none

func ProviderDirForHome

func ProviderDirForHome(h, name string) (string, bool)

Provider directory a name resolves to in a home, false when the loader cannot resolve it

func PruneInactiveMemoryProviderSkills

func PruneInactiveMemoryProviderSkills(ctx context.Context, env *tools.Env, activeProvider string)

Retracts tracked skills that no longer belong to the active provider under the home in effect

func PruneOldSnapshots

func PruneOldSnapshots(ctx context.Context) []string

Applies curator.backup.keep without taking a snapshot

func RGBToHex

func RGBToHex(c [3]float64) string

Upper case hex color of an RGB triple, channels clamped and truncated

func ReadEntriesFile

func ReadEntriesFile(path string) []string

Entries of a memory file, empty on any read failure, for read only callers

func RecencyInk

func RecencyInk(rec float64) float64

Ink alpha of a recency ratio along the age gradient

func RedactForEgress

func RedactForEgress(text string) string

Text scrubbed for a remote reader with the bearer sweep applied, never raw on failure

func RedactForProvider

func RedactForProvider(values ...any) []any

Values scrubbed for a provider, every token the scrub masked anywhere masked everywhere

func RedactSensitiveText

func RedactSensitiveText(text string, opts RedactOptions) string

Text with every credential shape masked, the force path every egress boundary runs

func RedactSessionData

func RedactSessionData(session *jsonutil.Object) *jsonutil.Object

Copy of a session export with secrets redacted from its messages and segments

func RefusedToolMessage

func RefusedToolMessage(toolName string) string

What the model sees for a refused memory tool call, without check names or home paths

func RegisterProvider

func RegisterProvider(reg ProviderRegistration)

Adds a provider to the registry, a bundled name registered twice keeps the first

func RenderFrames

func RenderFrames(payload map[string]any, cols, rows, frames int) (map[string]any, error)

Full play through from reveal zero to one plus the static legend, buckets, and summary

func RenderGraph

func RenderGraph(payload map[string]any, cols, rows int, reveal float64) (map[string]any, error)

One timeline frame at a reveal fraction with category colored bars, markers, and the trajectory

func RenderSessionMarkdown

func RenderSessionMarkdown(session *jsonutil.Object, format string, includeVerification bool) (string, error)

Renders an exported session as Markdown or QMD text, with a body digest unless verification is left out

func ReportMissingMemoryProvider

func ReportMissingMemoryProvider(ctx context.Context, name string, say func(string)) error

Tells the user how to install a configured provider that resolved nowhere, once per process per home and name

func RewriteMemoryQuery

func RewriteMemoryQuery(ctx context.Context, userMessage string) (rewritten string)

RewriteMemoryQuery turns the latest user message into one retrieval question for a memory provider, empty to keep the message itself as the query

func RollbackCuratorSnapshot

func RollbackCuratorSnapshot(ctx context.Context, backupID string) (bool, string, string)

Restores the skills tree from a snapshot after a safety snapshot, undoing the staging on failure

func RunCuratorReview

func RunCuratorReview(ctx context.Context, opts CuratorRunOptions) (*jsonutil.Object, error)

One curator pass, deterministic transitions then the optional LLM fork, recording state and a report

func SafeSessionFilename

func SafeSessionFilename(session *jsonutil.Object, format string) (string, error)

Deterministic path safe file name of a session export, the id followed by a slug of the title

func SanitizeContext

func SanitizeContext(text string) string

Strips fence tags, injected context blocks and system notes from provider output

func SaveCuratorState

func SaveCuratorState(ctx context.Context, data *jsonutil.Object)

Writes the curator state sorted and indented, logging instead of failing

func ScanForThreats

func ScanForThreats(content, scope string) ([]string, error)

Pattern ids matched in content for a scope, invisible code points reported as invisible_unicode_U+XXXX

func SetCuratorPaused

func SetCuratorPaused(ctx context.Context, paused bool) error

Persists the paused flag on top of the current state

func SnapshotSkills

func SnapshotSkills(ctx context.Context, reason string, protect map[string]bool) (string, bool, error)

Takes a tar.gz snapshot of the skills tree and prunes old ones, empty when skipped or failed

func SummarizeCuratorBackups

func SummarizeCuratorBackups(ctx context.Context) (string, error)

Table of curator snapshots for the CLI

func TrimMemory

func TrimMemory(ctx context.Context, env *tools.Env, opts TrimOptions) (released bool)

Collects and releases free heap pages, true only when pages were released, cooldown and kill switch returning false

func TrimMemoryWhenIdle

func TrimMemoryWhenIdle(ctx context.Context, env *tools.Env, reason string, clock QuietClock) bool

Timer lane trim, allocator release only plus one full collection per quiet period past the idle threshold

func TurnOffProvider

func TurnOffProvider(ctx context.Context) error

TurnOffProvider clears the provider of the home in the context, so only the built-in memory stays in use

func UnregisterProviders

func UnregisterProviders(source, homeDir string)

Removes external registrations of a source and home, the inverse of RegisterProvider that tests retract their providers with

func VerifyExportFile

func VerifyExportFile(path string, session *jsonutil.Object) (bool, string, error)

Whether an export file still matches its digest and names the session and message count, with the reason

func WriteSessionMarkdown

func WriteSessionMarkdown(session *jsonutil.Object, outputDir, format string, force bool) (string, error)

Writes the Markdown or QMD export of a session into the directory and returns its path

Types

type BaseProvider

type BaseProvider struct{}

Optional hook defaults so a provider overrides only what it opts into

func (BaseProvider) BackupPaths

func (BaseProvider) BackupPaths() ([]string, error)

func (BaseProvider) CheckpointAPIVersion

func (BaseProvider) CheckpointAPIVersion() int

func (BaseProvider) ConfigSchema

func (BaseProvider) ConfigSchema() []map[string]any

func (BaseProvider) HandleToolCall

func (BaseProvider) HandleToolCall(ctx context.Context, toolName string, args map[string]any, opts ToolCallOptions) (string, error)

Refuses every tool, the manager fills in the provider name

func (BaseProvider) IdentitySignature

func (BaseProvider) IdentitySignature(ctx context.Context) map[string]any

func (BaseProvider) OnDelegation

func (BaseProvider) OnDelegation(ctx context.Context, task, result string, opts DelegationOptions) error

func (BaseProvider) OnMemoryWrite

func (BaseProvider) OnMemoryWrite(ctx context.Context, action, target, content string, metadata map[string]any) error

func (BaseProvider) OnPreCompress

func (BaseProvider) OnPreCompress(ctx context.Context, messages []map[string]any, requireCheckpoint bool) (string, error)

func (BaseProvider) OnProfileCreated

func (BaseProvider) OnProfileCreated(ctx context.Context, profileName, home string) error

func (BaseProvider) OnProfileRenamed

func (BaseProvider) OnProfileRenamed(ctx context.Context, oldName, newName, home string) error

func (BaseProvider) OnSessionEnd

func (BaseProvider) OnSessionEnd(ctx context.Context, messages []map[string]any) error

func (BaseProvider) OnSessionSwitch

func (BaseProvider) OnSessionSwitch(ctx context.Context, newSessionID string, opts SessionSwitchOptions) error

func (BaseProvider) OnTurnStart

func (BaseProvider) OnTurnStart(ctx context.Context, turnNumber int, message string, opts TurnOptions) error

func (BaseProvider) Prefetch

func (BaseProvider) Prefetch(ctx context.Context, query, sessionID string) (string, error)

func (BaseProvider) QueuePrefetch

func (BaseProvider) QueuePrefetch(ctx context.Context, query, sessionID string) error

func (BaseProvider) RecallStatus

func (BaseProvider) RecallStatus(ctx context.Context) (*RecallStatus, error)

func (BaseProvider) SaveConfig

func (BaseProvider) SaveConfig(values map[string]any, icebathHome string) error

func (BaseProvider) Shutdown

func (BaseProvider) Shutdown(ctx context.Context) error

func (BaseProvider) SyncTurn

func (BaseProvider) SyncTurn(ctx context.Context, userContent, assistantContent string, opts SyncOptions) error

func (BaseProvider) SystemPromptBlock

func (BaseProvider) SystemPromptBlock(ctx context.Context) (string, error)

func (BaseProvider) UnavailableReason

func (BaseProvider) UnavailableReason(ctx context.Context) string

type BoundScope

type BoundScope struct {
	Home          string
	AgentIdentity string
	HomeKey       string
}

BoundScope is the profile a memory manager was initialized for, its home key resolved once

func NewBoundScope

func NewBoundScope(icebathHome, agentIdentity string) *BoundScope

Records the bound home and identity with the home key resolved up front

type ByteRoverProvider

type ByteRoverProvider struct {
	BaseProvider
	// contains filtered or unexported fields
}

ByteRover persistent memory through the brv CLI

func NewByteRoverProvider

func NewByteRoverProvider(ctx context.Context, env *tools.Env, config map[string]any) *ByteRoverProvider

Provider over config, the memory.byterover block when config is nil

func (*ByteRoverProvider) Available

func (p *ByteRoverProvider) Available(ctx context.Context) bool

Whether the brv CLI is installed, no network

func (*ByteRoverProvider) ConfigSchema

func (p *ByteRoverProvider) ConfigSchema() []map[string]any

func (*ByteRoverProvider) HandleToolCall

func (p *ByteRoverProvider) HandleToolCall(ctx context.Context, toolName string, args map[string]any, opts ToolCallOptions) (string, error)

One of the brv tools, a missing required argument refused before the CLI runs

func (*ByteRoverProvider) Initialize

func (p *ByteRoverProvider) Initialize(ctx context.Context, sessionID string, opts InitOptions) error

Binds the context tree to the profile the manager names

func (*ByteRoverProvider) Name

func (p *ByteRoverProvider) Name() string

func (*ByteRoverProvider) OnMemoryWrite

func (p *ByteRoverProvider) OnMemoryWrite(ctx context.Context, action, target, content string, metadata map[string]any) error

Mirrors built in memory adds and replaces into ByteRover

func (*ByteRoverProvider) OnPreCompress

func (p *ByteRoverProvider) OnPreCompress(ctx context.Context, messages []map[string]any, requireCheckpoint bool) (string, error)

Curates the last ten user and assistant messages before compression discards them

func (*ByteRoverProvider) Prefetch

func (p *ByteRoverProvider) Prefetch(ctx context.Context, query, sessionID string) (string, error)

Synchronous brv query so context is ready before the first model call

func (*ByteRoverProvider) Shutdown

func (p *ByteRoverProvider) Shutdown(ctx context.Context) error

Waits for the last turn curate to finish

func (*ByteRoverProvider) SyncTurn

func (p *ByteRoverProvider) SyncTurn(ctx context.Context, userContent, assistantContent string, opts SyncOptions) error

Curates a substantive turn in the background after the previous curate finished

func (*ByteRoverProvider) SystemPromptBlock

func (p *ByteRoverProvider) SystemPromptBlock(ctx context.Context) (string, error)

func (*ByteRoverProvider) ToolSchemas

func (p *ByteRoverProvider) ToolSchemas(ctx context.Context) ([]map[string]any, error)

type ContextThread

type ContextThread struct {
	Name string
	// contains filtered or unexported fields
}

Background job that runs under its spawner context values

func SpawnContextThread

func SpawnContextThread(ctx context.Context, name string, fn func(ctx context.Context)) *ContextThread

Unstarted job running fn under the spawner profile scope, every provider background job goes through it

func (*ContextThread) Alive

func (t *ContextThread) Alive() bool

True between start and completion

func (*ContextThread) Join

func (t *ContextThread) Join(timeout time.Duration)

Waits for completion up to timeout, forever when timeout is negative, immediately for an unstarted job

func (*ContextThread) Start

func (t *ContextThread) Start()

Starts the job once

type CuratorArgs

type CuratorArgs struct {
	Skill        string
	Skills       []string
	DryRun       bool
	Background   bool
	Synchronous  bool
	Consolidate  bool
	AllUnmanaged bool
	Yes          bool
	List         bool
	Compact      bool
	JSON         bool
	Days         *int
	Reason       string
	EntryID      string
	BackupID     string
	Limit        int
	Sort         string
	Provenance   string
}

CuratorArgs holds every flag and positional of the curator subcommands

type CuratorCLI

type CuratorCLI struct {
	Out io.Writer
	Err io.Writer
	In  *bufio.Reader
	Now func() time.Time
}

CuratorCLI runs the curator subcommands against a console

func NewCuratorCLI

func NewCuratorCLI(out, errw io.Writer, in io.Reader) *CuratorCLI

Curator subcommand runner over the given streams

func (*CuratorCLI) Run

func (c *CuratorCLI) Run(ctx context.Context, sub string, a CuratorArgs) (int, error)

Dispatches one curator subcommand and returns its exit code

type CuratorCronRewrite

type CuratorCronRewrite struct {
	JobID   any
	JobName any
	Before  []string
	After   []string
	Mapped  *jsonutil.Object
	Dropped []string
}

CuratorCronRewrite is one cron job whose skill references a curator pass rewrote

type CuratorCronRewriteReport

type CuratorCronRewriteReport struct {
	Rewrites    []CuratorCronRewrite
	JobsUpdated int
	JobsScanned int
}

CuratorCronRewriteReport is the cron rewrite_skill_refs result

type CuratorReviewRequest

type CuratorReviewRequest struct {
	Prompt              string
	Model               string
	Provider            string
	Route               *provider.Route
	RequestOverrides    map[string]any
	ReasoningConfig     map[string]any
	EnabledToolsets     []string
	MaxIterations       int
	Platform            string
	WriteOrigin         string
	QuietMode           bool
	SkipContextFiles    bool
	SkipMemory          bool
	MemoryAgentContext  string
	MemoryNudgeInterval int
	SkillNudgeInterval  int
	ACPCommand          string
	ACPArgs             []string
	CredentialPool      *provider.Pool
}

CuratorReviewRequest carries every AIAgent argument the curator review fork is built with

type CuratorReviewResult

type CuratorReviewResult struct {
	Conversation any
	Messages     []any
}

CuratorReviewResult is what the review fork returned and the session messages it recorded

type CuratorRunOptions

type CuratorRunOptions struct {
	OnSummary   func(string)
	Synchronous bool
	DryRun      bool
	Consolidate *bool
}

CuratorRunOptions are the run_curator_review keyword arguments

type DelegationOptions

type DelegationOptions struct {
	ChildSessionID string
}

Child session of a completed delegation

type DiscoveredProvider

type DiscoveredProvider struct {
	Name        string
	Description string
	Available   bool
}

Discovered provider with its manifest description and availability

func DiscoverMemoryProviders

func DiscoverMemoryProviders(ctx context.Context, env *tools.Env) []DiscoveredProvider

Every provider as name, description and availability, the first source winning a name collision

type DrainState

type DrainState struct {
	Status              string
	AbandonedWrites     int
	AbandonedPrefetches int
	ActiveTasks         int
}

Outcome of the most recent bounded shutdown drain

type ExportExistsError

type ExportExistsError struct{ Path string }

ExportExistsError is the FileExistsError of an export file that is already there, its text the path

func (*ExportExistsError) Error

func (e *ExportExistsError) Error() string

func (*ExportExistsError) Is

func (e *ExportExistsError) Is(target error) bool

Lets the error match fs.ErrExist

type InitOptions

type InitOptions struct {
	Home               string
	Platform           string
	AgentContext       string
	AgentIdentity      string
	AgentWorkspace     string
	AgentID            string
	ParentSessionID    string
	SessionTitle       string
	SessionTitleSource string
	Cwd                string
	UserID             string
	UserIDAlt          string
	UserName           string
	ChatID             string
	ChatName           string
	ChatType           string
	ThreadID           string
	GatewaySessionKey  string
	Warn               func(string)
	Status             func(string)
}

Scoping values a provider binds to once at agent startup

type InsightsActivity

type InsightsActivity struct {
	ByDay       []InsightsDayCount
	ByHour      []InsightsHourCount
	BusiestDay  InsightsDayCount
	BusiestHour InsightsHourCount
	ActiveDays  int
	MaxStreak   int
}

Session counts by weekday and hour with the active day streak

type InsightsDayCount

type InsightsDayCount struct {
	Day   string
	Count int
}

Sessions started on one weekday

type InsightsEngine

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

Session history analytics over the session store

func NewInsightsEngine

func NewInsightsEngine(conn *sql.DB) *InsightsEngine

Engine over an open SQLite connection, unpinning the partial index and the local surface clause when the schema lacks them

func OpenInsightsEngine

func OpenInsightsEngine(db InsightsStore) (*InsightsEngine, error)

Engine on a read connection of the session store file that Close releases

func (*InsightsEngine) Close

func (e *InsightsEngine) Close() error

Releases the read connection the engine opened itself

func (*InsightsEngine) FormatGateway

func (e *InsightsEngine) FormatGateway(r *InsightsReport) string

Shorter report rendered for messaging platforms

func (*InsightsEngine) FormatTerminal

func (e *InsightsEngine) FormatTerminal(r *InsightsReport) string

Report rendered for the terminal

func (*InsightsEngine) Generate

func (e *InsightsEngine) Generate(ctx context.Context, days int, source string) (*InsightsReport, error)

Complete report for the last days days, optionally filtered by source platform

func (*InsightsEngine) GetUsageBreakdown

func (e *InsightsEngine) GetUsageBreakdown(ctx context.Context, days int, source string) (*InsightsUsageBreakdown, error)

Tool and skill analytics without a full report

type InsightsHourCount

type InsightsHourCount struct {
	Hour  int
	Count int
}

Sessions started in one hour of the day

type InsightsModel

type InsightsModel struct {
	Model                                                        string
	Sessions                                                     int
	InputTokens, OutputTokens, CacheReadTokens, CacheWriteTokens InsightsNum
	ReasoningTokens, TotalTokens, APICalls, ToolCalls            InsightsNum
	Cost, ActualCost                                             float64
	CostStatus                                                   string
	HasPricing                                                   bool
}

Usage and cost of one model across the window

type InsightsNum

type InsightsNum struct {
	I     int64
	F     float64
	Float bool
}

Python int or float result of summing stored cells, float once any operand was a float

func (InsightsNum) Value

func (n InsightsNum) Value() float64

Numeric value as a float64

type InsightsOverview

type InsightsOverview struct {
	TotalSessions                                                                    int
	TotalMessages, TotalToolCalls                                                    InsightsNum
	TotalInputTokens, TotalOutputTokens, TotalCacheReadTokens, TotalCacheWriteTokens int64
	TotalTokens                                                                      int64
	EstimatedCost, ActualCost                                                        float64
	TotalHours, AvgSessionDuration, AvgMessagesPerSession, AvgTokensPerSession       float64
	UserMessages, AssistantMessages, ToolMessages                                    InsightsNum
	DateRangeStart, DateRangeEnd                                                     *float64
	ModelsWithPricing, ModelsWithoutPricing                                          []string
	UnknownCostSessions, IncludedCostSessions                                        int
}

Report totals, averages, cost buckets and date range

type InsightsPlatform

type InsightsPlatform struct {
	Platform                                                     string
	Sessions                                                     int
	Messages                                                     InsightsNum
	InputTokens, OutputTokens, CacheReadTokens, CacheWriteTokens InsightsNum
	TotalTokens, ToolCalls                                       InsightsNum
}

Usage of one source platform across the window

type InsightsReport

type InsightsReport struct {
	Days         int
	SourceFilter string
	Empty        bool
	GeneratedAt  float64
	Overview     *InsightsOverview
	Models       []InsightsModel
	Platforms    []InsightsPlatform
	Tools        []InsightsTool
	Skills       InsightsSkills
	Activity     *InsightsActivity
	TopSessions  []InsightsTopSession
}

Insights report over a window of days, Empty with zero sections when no session matched

type InsightsSkill

type InsightsSkill struct {
	Skill                              string
	ViewCount, ManageCount, TotalCount int64
	Percentage                         float64
	LastUsedAt                         any
}

Loads and edits of one skill with its latest use

type InsightsSkills

type InsightsSkills struct {
	TotalSkillLoads, TotalSkillEdits, TotalSkillActions int64
	DistinctSkillsUsed                                  int
	TopSkills                                           []InsightsSkill
}

Skill usage summary and ranked skills

type InsightsStore

type InsightsStore interface {
	Path() string
}

Session store an engine reads through its database file

type InsightsTool

type InsightsTool struct {
	Tool       any
	Count      int64
	Percentage float64
}

Calls of one tool and its share of all tool calls

type InsightsTopSession

type InsightsTopSession struct {
	Label, SessionID, Value, Date string
}

One notable session with its formatted metric

type InsightsUsageBreakdown

type InsightsUsageBreakdown struct {
	Tools  []InsightsTool
	Skills InsightsSkills
}

Tool and skill sections of a report computed on their own

type LoadOptions

type LoadOptions struct {
	RegisterSkills bool
	// Records a plugin skill the provider registered so switching providers can retract it
	TrackSkill func(qualifiedName string)
}

How a provider load runs, skills register only for the configured active provider

type Manager

type Manager interface {
	Store() *Store
	NotifyMemoryToolWrite(result string, args map[string]any, taskID, toolCallID string)
}

Manager is the per session memory surface the memory tool writes through and mirrors to

func ManagerFor

func ManagerFor(ctx context.Context, env *tools.Env) Manager

Session Manager from the environment, registering a store only manager when the host registered none

func NewStoreManager

func NewStoreManager(store *Store) Manager

NewStoreManager wraps a built in store as a Manager without external providers

type MemoryInstallFunc

type MemoryInstallFunc func(name string) (map[string]any, error)

Install function bound to one home, the error stands for a raised install exception

type MemoryManager

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

Built in store plus at most one external provider, one failing provider never blocking another

func NewMemoryManager

func NewMemoryManager(ctx context.Context, env *tools.Env, store *Store) *MemoryManager

Manager over the session store with the default external prefetch bound

func NewMemoryManagerWithTimeout

func NewMemoryManagerWithTimeout(ctx context.Context, env *tools.Env, store *Store, prefetchTimeout time.Duration) (*MemoryManager, error)

Manager with an explicit external prefetch bound, an error when the bound is not positive

func (*MemoryManager) AddProvider

func (m *MemoryManager) AddProvider(ctx context.Context, p Provider) error

Registers a provider, builtin always accepted and only one external, schemas loaded before any state changes

func (*MemoryManager) BuildSystemPrompt

func (m *MemoryManager) BuildSystemPrompt(ctx context.Context) string

Every provider's non empty system prompt block joined by blank lines

func (*MemoryManager) BuildWriteMetadata

func (m *MemoryManager) BuildWriteMetadata(taskID, toolCallID string) map[string]any

Provenance metadata for external provider mirrors with empty values dropped

func (*MemoryManager) ClaimTeardown

func (m *MemoryManager) ClaimTeardown(sessionEnd bool) bool

Claims extraction and shutdown, the first claimer winning and session end callers allowed to claim again

func (*MemoryManager) CommitSessionBoundaryAsync

func (m *MemoryManager) CommitSessionBoundaryAsync(ctx context.Context, messages []map[string]any, newSessionID, parentSessionID, reason string)

Queues old session extraction then provider rebinding as one serialized task

func (*MemoryManager) DescribeRecall

func (m *MemoryManager) DescribeRecall(ctx context.Context) string

Deterministic recall indicator line, empty when no provider injected anything

func (*MemoryManager) FlushPending

func (m *MemoryManager) FlushPending(timeout time.Duration) bool

Blocks until queued work drained, false on timeout, a negative timeout waiting forever

func (*MemoryManager) GetAllToolNames

func (m *MemoryManager) GetAllToolNames() map[string]bool

Names of every routed provider tool

func (*MemoryManager) GetAllToolSchemas

func (m *MemoryManager) GetAllToolSchemas(ctx context.Context) []map[string]any

Deduplicated provider tool schemas with reserved core names skipped

func (*MemoryManager) GetProvider

func (m *MemoryManager) GetProvider(name string) Provider

Provider registered under name, nil when none

func (*MemoryManager) HandleToolCall

func (m *MemoryManager) HandleToolCall(ctx context.Context, toolName string, args map[string]any, callerGSK string) string

Routes a tool call to its provider as the calling profile, returning a JSON string

func (*MemoryManager) HasTool

func (m *MemoryManager) HasTool(toolName string) bool

Whether a provider routes this tool

func (*MemoryManager) InitializeAll

func (m *MemoryManager) InitializeAll(ctx context.Context, sessionID string, opts InitOptions)

Binds every provider to the profile home, refusing an instance another profile already bound

func (*MemoryManager) InitializeForAgent

func (m *MemoryManager) InitializeForAgent(ctx context.Context, sessionID string, opts InitOptions, say func(string)) bool

Initializes for an agent build, true while an external provider is still served, say told about dropped ones

func (*MemoryManager) NotifyMemoryToolWrite

func (m *MemoryManager) NotifyMemoryToolWrite(result string, args map[string]any, taskID, toolCallID string)

Mirrors a memory tool call as the session home that owns this manager

func (*MemoryManager) NotifyMemoryToolWriteContext

func (m *MemoryManager) NotifyMemoryToolWriteContext(ctx context.Context, toolResult any, toolArgs map[string]any, buildMetadata func() map[string]any)

Mirrors a memory tool call to external providers with provenance from buildMetadata

func (*MemoryManager) OnDelegation

func (m *MemoryManager) OnDelegation(ctx context.Context, task, result string, opts DelegationOptions)

Parent side observation of a completed delegation on every provider

func (*MemoryManager) OnMemoryWrite

func (m *MemoryManager) OnMemoryWrite(ctx context.Context, action, target, content string, metadata map[string]any)

Mirrors a built in memory tool write to external providers, the builtin source skipped

func (*MemoryManager) OnPreCompress

func (m *MemoryManager) OnPreCompress(ctx context.Context, messages, evidenceMessages []map[string]any, requireCheckpoint bool, checkpointAPIVersion int) (string, error)

Notifies providers before compression and returns their combined summary prompt text

func (*MemoryManager) OnSessionEnd

func (m *MemoryManager) OnSessionEnd(ctx context.Context, messages []map[string]any)

End of session extraction on every provider

func (*MemoryManager) OnSessionSwitch

func (m *MemoryManager) OnSessionSwitch(ctx context.Context, newSessionID string, opts SessionSwitchOptions)

Tells providers the session id rotated without teardown

func (*MemoryManager) OnTurnStart

func (m *MemoryManager) OnTurnStart(ctx context.Context, turnNumber int, message string, opts TurnOptions)

Per turn tick to every provider with the turn author

func (*MemoryManager) PrefetchAll

func (m *MemoryManager) PrefetchAll(ctx context.Context, query, sessionID string) string

Merged prefetch context from every provider, failures non fatal

func (*MemoryManager) Providers

func (m *MemoryManager) Providers() []Provider

Registered providers in order

func (*MemoryManager) QueuePrefetchAll

func (m *MemoryManager) QueuePrefetchAll(ctx context.Context, query, sessionID string)

Queues a background prefetch on every provider for the next turn

func (*MemoryManager) ReleaseSoft

func (m *MemoryManager) ReleaseSoft(ctx context.Context)

Stops provider writers without session end extraction, flushing first

func (*MemoryManager) SetProvenance

func (m *MemoryManager) SetProvenance(p WriteProvenance)

Records the provenance the agent stamps on mirrored writes

func (*MemoryManager) ShutdownAll

func (m *MemoryManager) ShutdownAll(ctx context.Context)

Drains the background worker within its bound, then shuts providers down in reverse order

func (*MemoryManager) ShutdownDrainState

func (m *MemoryManager) ShutdownDrainState() DrainState

Snapshot of the most recent bounded shutdown drain

func (*MemoryManager) Store

func (m *MemoryManager) Store() *Store

Built in store the memory tool writes through

func (*MemoryManager) SupportsPreCompressCheckpoint

func (m *MemoryManager) SupportsPreCompressCheckpoint(apiVersion int) bool

Whether an active provider guarantees the checkpoint contract at apiVersion or newer

func (*MemoryManager) SyncAll

func (m *MemoryManager) SyncAll(ctx context.Context, userContent, assistantContent string, opts SyncOptions)

Syncs a completed turn to every provider on the background worker with all egress scrubbed

type MemorySetup

type MemorySetup struct {
	Env     *tools.Env
	Console *cliui.Console
	Stderr  io.Writer
	// contains filtered or unexported fields
}

MemorySetup runs icebath memory setup and status for one home on one console

func NewMemorySetup

func NewMemorySetup(env *tools.Env, console *cliui.Console, stderr io.Writer) *MemorySetup

Setup runner bound to the env home with the real picker, prompts, installer and config writer

func (*MemorySetup) CmdSetup

func (m *MemorySetup) CmdSetup(ctx context.Context) error

Interactive provider picker and schema walk that saves activation, provider config and secrets

func (*MemorySetup) CmdSetupProvider

func (m *MemorySetup) CmdSetupProvider(ctx context.Context, name string) error

Setup for one named provider without the picker

func (*MemorySetup) CmdStatus

func (m *MemorySetup) CmdStatus(ctx context.Context) error

Prints the built in store flags, memory tool gate, active provider config and installed plugins

func (*MemorySetup) Configure

func (m *MemorySetup) Configure(ctx context.Context, name string, values map[string]string) error

Configure sets a provider up from the values given by setting and makes it the one new sessions use: its dependencies are installed, its own setup runs when it brings one, else every setting that counts takes its value, a setting left empty keeping what it has

func (*MemorySetup) Overview

func (m *MemorySetup) Overview(ctx context.Context) (*OverviewView, error)

Overview is the state of memory for the home: the built-in stores, the provider in use and every provider that can be set up with its settings

func (*MemorySetup) Run

func (m *MemorySetup) Run(ctx context.Context, subcommand, provider string) (int, error)

Routes icebath memory setup and status, exit code 1 when dependency preparation fails

type MemorySnapshot

type MemorySnapshot struct {
	RSSKiB       *int
	RSSAnonKiB   *int
	ThreadCount  int
	HistoryBytes *int
}

Process memory telemetry for trim logs, resident sizes on Linux only

func CollectMemorySnapshot

func CollectMemorySnapshot(historyBytes *int) MemorySnapshot

Lightweight process memory telemetry, history bytes recorded when given and not negative

type MutateFunc

type MutateFunc func(entries []string, limit int) Mutation

MutateFunc computes a mutation from the entries reread under the lock and the target limit

type Mutation

type Mutation struct {
	Result  *Result
	Entries []string
	Message string
	Extra   *jsonutil.Object
}

Mutation is a closure outcome, a passthrough result or new entries to persist with a message

type NotHandledError

type NotHandledError struct {
	Provider string
	Tool     string
}

Default tool call refusal of a provider that exposes no such tool

func (*NotHandledError) Error

func (e *NotHandledError) Error() string

type OverviewView

type OverviewView struct {
	// Provider new sessions use, empty for the built-in memory alone
	Provider                                       string
	MemoryEnabled, UserProfileEnabled, ToolEnabled bool
	// Whether the plugin of the provider in use is installed, and whether the provider is ready with what it needs
	Installed, Ready bool
	// Why the provider in use is not ready, or why its plugin is turned off
	Problem   string
	Providers []ProviderView
}

OverviewView is the state of memory for one home: the built-in stores, the provider in use and every provider that can be set up

type PendingOptions

type PendingOptions struct {
	MemoryStore *Store
	ApplySkill  func(payload map[string]any) string
	SetMode     func(enabled bool) error
}

PendingOptions binds the store memory approvals apply to, the staged skill replayer and the gate setter

type PluginCLICommand

type PluginCLICommand struct {
	Name        string
	Help        string
	Description string
	Setup       func(cmd *cobra.Command)
	Handler     func(cmd *cobra.Command, args []string) error
	Plugin      string
}

CLI command contributed by the active memory provider

func DiscoverPluginCLICommands

func DiscoverPluginCLICommands(ctx context.Context, env *tools.Env) []PluginCLICommand

CLI commands of the active memory provider only, at most one

type PluginSkillRegistry

type PluginSkillRegistry interface {
	FindPluginSkill(qualifiedName string) (string, bool)
	RemovePluginSkill(qualifiedName string)
}

Plugin skill lookups used to resolve and retract provider skills

type Provider

type Provider interface {
	// Short identifier such as builtin, byterover or retaindb
	Name() string
	// Configured, credentialed and ready, config and dependencies only with no network
	Available(ctx context.Context) bool
	// User facing hint for the provider unavailable warning
	UnavailableReason(ctx context.Context) string
	// Binds connections, stores and threads to the profile once at agent startup
	Initialize(ctx context.Context, sessionID string, opts InitOptions) error
	// Static system prompt text, empty to skip
	SystemPromptBlock(ctx context.Context) (string, error)
	// Formatted recall context for the upcoming turn, fast and cached
	Prefetch(ctx context.Context, query, sessionID string) (string, error)
	// Background recall after a turn that the next prefetch consumes
	QueuePrefetch(ctx context.Context, query, sessionID string) error
	// What the most recent prefetch injected, nil for no indicator
	RecallStatus(ctx context.Context) (*RecallStatus, error)
	// Persists a completed turn without blocking
	SyncTurn(ctx context.Context, userContent, assistantContent string, opts SyncOptions) error
	// Function calling schemas with name, description and parameters
	ToolSchemas(ctx context.Context) ([]map[string]any, error)
	// Handles one of the provider tools, returning a JSON string
	HandleToolCall(ctx context.Context, toolName string, args map[string]any, opts ToolCallOptions) (string, error)
	// Flushes queues and closes connections
	Shutdown(ctx context.Context) error
	// Per turn tick naming the turn author
	OnTurnStart(ctx context.Context, turnNumber int, message string, opts TurnOptions) error
	// Identity mapping values that bust a cached gateway agent when they change
	IdentitySignature(ctx context.Context) map[string]any
	// End of session extraction at real session boundaries
	OnSessionEnd(ctx context.Context, messages []map[string]any) error
	// Rebinds per session state after a session id rotation
	OnSessionSwitch(ctx context.Context, newSessionID string, opts SessionSwitchOptions) error
	// Insights from messages about to be compressed, fed into the summary prompt
	OnPreCompress(ctx context.Context, messages []map[string]any, requireCheckpoint bool) (string, error)
	// Advertised pre compress checkpoint contract version
	CheckpointAPIVersion() int
	// Parent side observation of a completed delegation
	OnDelegation(ctx context.Context, task, result string, opts DelegationOptions) error
	// Setup fields for icebath memory setup
	ConfigSchema() []map[string]any
	// Writes non secret setup values to the provider native config
	SaveConfig(values map[string]any, icebathHome string) error
	// Mirrors a built in memory tool write, previous_content in metadata for replace and remove
	OnMemoryWrite(ctx context.Context, action, target, content string, metadata map[string]any) error
	// Absolute paths of provider state outside the home for backup and import, the error a failing provider raised
	BackupPaths() ([]string, error)
	// A profile whose config selects this provider was created, home its directory, the place to set up per profile provider state
	OnProfileCreated(ctx context.Context, profileName, home string) error
	// A profile whose config selects this provider was renamed, home its new directory, the place to re-key what is stored under the old name
	OnProfileRenamed(ctx context.Context, oldName, newName, home string) error
}

One pluggable memory backend driven by the memory manager

func LoadMemoryProvider

func LoadMemoryProvider(ctx context.Context, env *tools.Env, name string) Provider

Loads a provider by name, nil when unknown, parked or failing, skills registering only for the active provider

func LoadMemoryProviderWithSkills

func LoadMemoryProviderWithSkills(ctx context.Context, env *tools.Env, name string, registerSkills bool) Provider

Loads a provider by name with an explicit skill registration choice

type ProviderCLI

type ProviderCLI struct {
	Setup   func(cmd *cobra.Command)
	Handler func(cmd *cobra.Command, args []string) error
}

CLI subcommand the active memory provider contributes, Setup adds flags and Handler runs it

type ProviderFieldView

type ProviderFieldView struct {
	Key, Label string
	// Value in force, the stored one or else the default, never that of a secret
	Value  string
	Secret bool
	// Whether the secret already holds a value in the environment
	SecretSet bool
	// Only values the setting takes, empty for free text
	Choices []string
	// Where a key for the setting is handed out
	URL string
	// Settings that must hold these values for this one to count
	When map[string]string
}

ProviderFieldView is one setting a memory provider asks for

type ProviderRegistration

type ProviderRegistration struct {
	Name   string
	Source string
	// Provider directory of a non bundled source, its base name one of the disabled list spellings
	Dir string
	// Home whose plugins directory supplied a user source provider
	Home string
	// Extra names a plugins disabled list may use, such as the manifest name
	Spellings []string
	// Raw plugin.yaml text, the description read from it
	Manifest string
	New      func(ctx context.Context, env *tools.Env, opts LoadOptions) (Provider, error)
	CLI      *ProviderCLI
}

One discoverable memory provider, bundled ones compiled in and external ones installed by the plugin host

func FindProvider

func FindProvider(ctx context.Context, env *tools.Env, name string) *ProviderRegistration

Registration a name resolves to, bundled then user, then project

func (*ProviderRegistration) Description

func (r *ProviderRegistration) Description() string

Description from the plugin manifest, empty when absent or unreadable

type ProviderScope

type ProviderScope struct {
	Home          string
	AgentIdentity string
}

ProviderScope is the profile a memory provider call runs for

func CallerScope

func CallerScope(ctx context.Context, bound *BoundScope, label string) (ProviderScope, bool)

Provider scope naming the calling profile, false when the call or hook must be refused

type ProviderView

type ProviderView struct {
	Name string
	// The provider new sessions use
	Active bool
	// Brings a setup of its own that takes the place of its settings
	OwnSetup bool
	Fields   []ProviderFieldView
}

ProviderView is one memory provider that can be set up

type QuietClock

type QuietClock interface {
	QuietPeriod() (quietFor time.Duration, quietSince time.Time, ok bool)
}

Process wide quiet clock of the review idle queue, ok false while a turn runs or before the first turn ends

type RecallStatus

type RecallStatus struct {
	ProviderLabel string
	Count         int
	Glyph         string
}

What the last prefetch injected, a zero count meaning content without a discrete count

func NewRecallStatus

func NewRecallStatus(providerLabel string, count int) *RecallStatus

Recall status carrying the default indicator glyph

type Recency

type Recency struct {
	Rec   map[string]float64
	Timed bool
	MinTS *float64
	MaxTS *float64
}

Recency ratio of every node, timed graphs by timestamp and untimed graphs by ordinal position

func ComputeRecency

func ComputeRecency(nodes []map[string]any) Recency

Recency of nodes along the time axis

type RedactOptions

type RedactOptions struct {
	CodeFile             bool
	FileRead             bool
	SecretFile           bool
	RedactURLCredentials bool
}

Options of one redaction pass

type Result

type Result struct {
	Data         *jsonutil.Object
	FailureClass string
}

Result is one store response plus the closed failure class the shared metric reads

func ApplyMemoryPending

func ApplyMemoryPending(ctx context.Context, payload map[string]any, store *Store) (Result, error)

Replays a staged write bypassing the gate, destructive ops applying only to their pinned entry

func NewFailure

func NewFailure(message, class string) Result

NewFailure builds an error response for closures passed to Mutate

func (Result) Get

func (r Result) Get(key string) any

Value of one response key, nil when the response or the key is absent

func (Result) Success

func (r Result) Success() bool

Reports whether the response carries a truthy success flag

type RetainDBProvider

type RetainDBProvider struct {
	BaseProvider
	// contains filtered or unexported fields
}

RetainDB cloud memory with a durable queue, semantic search, dialectic synthesis and shared files

func NewRetainDBProvider

func NewRetainDBProvider(env *tools.Env) *RetainDBProvider

Uninitialized provider bound to the session environment

func (*RetainDBProvider) Available

func (p *RetainDBProvider) Available(ctx context.Context) bool

Whether the scoped API key is set

func (*RetainDBProvider) ConfigSchema

func (p *RetainDBProvider) ConfigSchema() []map[string]any

func (*RetainDBProvider) HandleToolCall

func (p *RetainDBProvider) HandleToolCall(ctx context.Context, toolName string, args map[string]any, opts ToolCallOptions) (string, error)

One RetainDB tool as a JSON string, a client failure returned as a tool error

func (*RetainDBProvider) Initialize

func (p *RetainDBProvider) Initialize(ctx context.Context, sessionID string, opts InitOptions) error

Binds client, queue and identity to the profile the manager names and seeds identity from SOUL.md

func (*RetainDBProvider) Name

func (p *RetainDBProvider) Name() string

func (*RetainDBProvider) OnMemoryWrite

func (p *RetainDBProvider) OnMemoryWrite(ctx context.Context, action, target, content string, metadata map[string]any) error

Mirrors built in memory adds to RetainDB

func (*RetainDBProvider) Prefetch

func (p *RetainDBProvider) Prefetch(ctx context.Context, query, sessionID string) (string, error)

Consumes the prefetched results as one context block

func (*RetainDBProvider) QueuePrefetch

func (p *RetainDBProvider) QueuePrefetch(ctx context.Context, query, sessionID string) error

Fires context, dialectic and self model prefetches in the background for the next prefetch to consume

func (*RetainDBProvider) Shutdown

func (p *RetainDBProvider) Shutdown(ctx context.Context) error

Waits for prefetches, then drains and stops the write queue

func (*RetainDBProvider) SyncTurn

func (p *RetainDBProvider) SyncTurn(ctx context.Context, userContent, assistantContent string, opts SyncOptions) error

Queues the turn for asynchronous ingest

func (*RetainDBProvider) SystemPromptBlock

func (p *RetainDBProvider) SystemPromptBlock(ctx context.Context) (string, error)

func (*RetainDBProvider) ToolSchemas

func (p *RetainDBProvider) ToolSchemas(ctx context.Context) ([]map[string]any, error)

type SessionSwitchOptions

type SessionSwitchOptions struct {
	ParentSessionID string
	Reset           bool
	Rewound         bool
	Reason          string
}

Session id rotation without teardown, Reset only for a genuinely new conversation, Rewound for a truncated transcript

type SetupRefusal

type SetupRefusal struct{ Message string }

SetupRefusal is a memory change refused for what was asked or for what its preparation found

func (*SetupRefusal) Error

func (e *SetupRefusal) Error() string

type SkillNode

type SkillNode struct {
	Name     string
	Category string
	Source   string
	// Epoch seconds as int64, or an integral float64 beyond the int64 range, nil when unknown
	Timestamp any
	UseCount  int
	State     string
	CreatedBy any
	Pinned    bool
	Related   []string
}

One learned or bundled skill as the learning graph sees it

func BuildSkillNodes

func BuildSkillNodes(roots []SkillRoot, usage map[string]map[string]any, isExternal func(path string) bool) ([]*SkillNode, error)

Skill nodes from each root in order, the first root to name a skill keeping it

type SkillRoot

type SkillRoot struct {
	Source string
	Dir    string
	FS     fs.FS
}

Skill tree the graph walks, an embedded tree when FS is set and a directory on disk otherwise

type Store

type Store struct {
	Dir                string
	MemoryCharLimit    int
	UserCharLimit      int
	MemoryEnabled      bool
	UserProfileEnabled bool
	Log                *slog.Logger
	// contains filtered or unexported fields
}

Store is the bounded file backed curated memory, MEMORY.md and USER.md, one per session

func LoadOnDiskStore

func LoadOnDiskStore(ctx context.Context, env *tools.Env) (*Store, error)

Fresh on disk store with the home's limits and flags for contexts with no live agent

func NewStore

func NewStore(dir string, memoryCharLimit, userCharLimit int, memoryEnabled, userProfileEnabled bool) *Store

NewStore returns an unloaded store rooted at the memories directory

func (*Store) Add

func (s *Store) Add(ctx context.Context, target, content string) (Result, error)

Appends a new entry, refusing empty, poisoned or over budget content

func (*Store) ApplyBatch

func (s *Store) ApplyBatch(ctx context.Context, target string, operations []map[string]any) (Result, error)

Applies add, patch and remove ops atomically against the final budget, all or nothing

func (*Store) CharLimit

func (s *Store) CharLimit(target string) int

Character limit of the target

func (*Store) Entries

func (s *Store) Entries(target string) []string

Live entries of the target

func (*Store) FormatForSystemPrompt

func (s *Store) FormatForSystemPrompt(target string) string

Frozen load time block for the system prompt, empty when the target has no entries

func (*Store) LoadFromDisk

func (s *Store) LoadFromDisk(ctx context.Context) error

Loads both files deduplicated and freezes the prompt snapshot with threat hits replaced by a placeholder

func (*Store) Mutate

func (s *Store) Mutate(ctx context.Context, target string, fn MutateFunc, skipDrift bool) (Result, error)

Mutate locks, rereads, runs fn, applies the drift guard, persists and returns the success response

func (*Store) Patch

func (s *Store) Patch(ctx context.Context, target, oldText, newText string, matchedEntry any) (Result, error)

Replaces one span inside the matched entry and keeps the rest of the entry verbatim

func (*Store) PathFor

func (s *Store) PathFor(target string) string

File path of the target store

func (*Store) Remove

func (s *Store) Remove(ctx context.Context, target, oldText string, matchedEntry any) (Result, error)

Removes the entry old_text selects

func (*Store) Replace

func (s *Store) Replace(ctx context.Context, target, oldText, newContent string, matchedEntry any) (Result, error)

Overwrites the whole entry old_text selects with new content

func (*Store) ResetConsolidationFailures

func (s *Store) ResetConsolidationFailures()

Clears the per turn consolidation failure count at a turn boundary

func (*Store) ResolveBatchEntries

func (s *Store) ResolveBatchEntries(ctx context.Context, target string, operations []map[string]any) (Result, error)

Dry run of ApplyBatch under the lock returning the full entry each op selects now

func (*Store) ResolveEntry

func (s *Store) ResolveEntry(ctx context.Context, target, oldText, verb string) (Result, error)

Full entry old_text selects now, read under the lock, or the error the direct edit would return

func (*Store) TargetEnabled

func (s *Store) TargetEnabled(target string) bool

Whether built in writes to the target are enabled in config

func (*Store) Usage

func (s *Store) Usage(target string) string

Current and limit characters of the target formatted with separators

type StreamingContextScrubber

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

StreamingContextScrubber drops memory context spans that straddle streaming deltas, one per response

func NewStreamingContextScrubber

func NewStreamingContextScrubber() *StreamingContextScrubber

NewStreamingContextScrubber returns a scrubber at a block boundary outside any span

func (*StreamingContextScrubber) Feed

func (s *StreamingContextScrubber) Feed(text string) string

Visible portion of text, holding a possible partial tag tail for the next call

func (*StreamingContextScrubber) Flush

func (s *StreamingContextScrubber) Flush() string

Held back tail at end of stream, discarded inside an unterminated span

func (*StreamingContextScrubber) Reset

func (s *StreamingContextScrubber) Reset()

Clears span state and the held tail for a new top level response

type SyncOptions

type SyncOptions struct {
	SessionID  string
	Messages   []map[string]any
	TurnAuthor map[string]any
}

Optional values of one completed turn

type ToolCallOptions

type ToolCallOptions struct {
	Home          string
	AgentIdentity string
	CallerGSK     string
}

Profile a provider tool call runs for

type TrimOptions

type TrimOptions struct {
	Force         bool
	Reason        string
	Cooldown      *float64
	AllocatorOnly bool
}

Tunes one trim, AllocatorOnly skipping the explicit full collection and Cooldown overriding the configured one

type TurnOptions

type TurnOptions struct {
	AuthorID    string
	AuthorName  string
	AuthorIsBot bool
}

Who wrote this turn, empty id and name when nobody did

type WriteProvenance

type WriteProvenance struct {
	WriteOrigin     string
	WriteContext    string
	SessionID       string
	ParentSessionID string
	Platform        string
}

Provenance an agent stamps on mirrored memory writes

Jump to

Keyboard shortcuts

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