@agentium/core. Read the memory guide for setup and behavior, or return to the package reference.
A ? marks an optional field. These are declarations for lookup; run the examples in the linked guide. Follow related-type links for Agentium types and source links for imported dependency types.
computeCompositeScore
Source/**
* Compute a composite score blending semantic similarity, recency, and importance.
* All inputs are normalized to 0-1. Returns a value between 0 and 1.
*/
export declare function computeCompositeScore(opts: {
semanticSimilarity?: number;
createdAt: Date;
importance?: number;
weights?: Partial<ScoringWeights>;
halfLifeDays?: number;
}): number;
ScoringWeights.
ConsolidateOptions
Sourceexport interface ConsolidateOptions {
userId: string;
model: ModelProvider;
similarityThreshold?: number;
}
ModelProvider.
ContextBudgetConfig
Sourceexport interface ContextBudgetConfig {
/** Maximum total tokens for the memory context string. */
maxTokens?: number;
/** Priority weights for each section (higher = gets more token budget). */
priorities?: Partial<Record<string, number>>;
}
Correction
Source/**
* A structured record of a human correcting an agent's output.
*
* Unlike a `Learning` (free-text insight), a Correction captures exactly
* WHAT was wrong and WHAT it should have been — field-level, anchored to
* the run that produced the mistake. Corrections are embedded and retrieved
* at inference time so the same mistake is not repeated.
*/
export interface Correction {
id: string;
/** Agent whose output was corrected. */
agentName: string;
/** Run that produced the corrected output (RunOutput.runId). */
runId?: string;
sessionId?: string;
/**
* The original input that produced the corrected output. When present,
* the correction can be replayed as a regression eval case (see
* `toEvalCases()`).
*/
originalInput?: string;
/** The specific field/aspect corrected, e.g. "chargeCode", "allocation". */
field?: string;
/** What the agent produced. */
originalValue: string;
/** What it should have been. */
correctedValue: string;
/** Human explanation of why — this is what generalizes to future runs. */
reason?: string;
/**
* Groups corrections by the real-world entity they apply to,
* e.g. a vendor ID or customer code. Enables per-entity accuracy stats.
*/
entityKey?: string;
tags: string[];
/**
* Defaults to "agent" — a correction to an agent's output is workflow
* knowledge that should benefit every user of that agent.
*/
scope?: LearningScope;
userId?: string;
tenantId?: string;
createdAt: Date;
}
CorrectionsConfig
Sourceexport interface CorrectionsConfig {
/** Vector store for semantic search over past corrections. Required. */
vectorStore: VectorStore;
/** Collection name in the vector store. Default: "agentium_corrections" */
collection?: string;
/** Number of relevant corrections to inject into context. Default: 3 */
topK?: number;
/**
* Relevance floor (0–1) — matches below this similarity are never injected
* into context. Recommended: 0.3–0.5 with real embeddings. Default: no floor.
*/
minScore?: number;
/**
* When a correction is recorded, automatically invalidate unverified
* (llm-extracted) learnings that semantically collide with it at or above
* `contradictionThreshold` similarity. Human-authored learnings are never
* auto-invalidated. Default: true.
*/
invalidateContradicted?: boolean;
/** Similarity threshold for contradiction invalidation. Default: 0.85 */
contradictionThreshold?: number;
}
VectorStore.
CorrectionStats
Sourceexport interface CorrectionStats {
total: number;
byEntityKey: Record<string, number>;
byField: Record<string, number>;
}
CorrectionStore
Sourceexport declare class CorrectionStore {
constructor(vectorStore: VectorStore, storage: StorageDriver, config?: {
collection?: string;
topK?: number;
/** Relevance floor for retrieval — matches below this score are dropped. */
minScore?: number;
/** Called after every successful record — used to emit events. */
onRecorded?: (correction: Correction) => void;
});
recordCorrection(correction: Omit<Correction, "id" | "createdAt" | "tags"> & {
tags?: string[];
}): Promise<Correction>;
searchCorrections(query: string, opts?: {
topK?: number;
userId?: string;
agentName?: string;
tenantId?: string;
entityKey?: string;
}): Promise<Correction[]>;
getCorrection(id: string): Promise<Correction | null>;
deleteCorrection(id: string): Promise<void>;
/** List corrections from KV storage, optionally filtered. Used for stats/audit. */
listCorrections(opts?: {
agentName?: string;
entityKey?: string;
since?: Date;
}): Promise<Correction[]>;
/**
* Convert corrections with a recorded `originalInput` into regression eval
* cases: replaying `input` against the agent should now produce
* `expected` (the corrected value). Feed these to `@agentium/eval`'s
* EvalSuite with a `contains` scorer to verify the learning loop works.
*/
toEvalCases(opts?: {
agentName?: string;
entityKey?: string;
since?: Date;
}): Promise<Array<{
input: string;
expected: string;
field?: string;
correctionId: string;
}>>;
/**
* Repair dual-write drift: re-index any KV correction missing from the
* vector store. Returns the number of re-indexed records.
*/
reconcile(): Promise<number>;
/** Aggregate correction counts — the raw material for accuracy dashboards. */
getStats(opts?: {
agentName?: string;
since?: Date;
}): Promise<CorrectionStats>;
getContextString(currentInput?: string, opts?: {
userId?: string;
agentName?: string;
tenantId?: string;
}): Promise<string>;
getTools(): ToolDef[];
}
Correction, CorrectionStats, StorageDriver, ToolDef, VectorStore.
Curator
Sourceexport declare class Curator {
constructor(storage: StorageDriver, stores: CuratorStores);
/**
* Repair dual-write drift across the vector-backed stores (learnings,
* corrections). KV records missing from the vector index — e.g. after a
* crash between the two writes — are re-embedded and re-indexed.
*
* Run periodically (e.g. on a schedule alongside prune/consolidate).
* Returns the number of repaired records per store.
*/
reconcile(): Promise<{
learnings: number;
corrections: number;
}>;
/**
* Remove entries older than `maxAgeDays` from all enabled stores.
* Returns the total number of entries pruned.
*/
prune(options: PruneOptions): Promise<number>;
/**
* Remove duplicate facts for a user by comparing normalized text.
* Returns the number of duplicates removed.
*/
deduplicate(options: {
userId: string;
}): Promise<number>;
/**
* Use an LLM to identify and merge semantically similar facts for a user.
* Goes beyond exact-text dedup: "Likes dark mode" + "Prefers dark themes" → single fact.
* Returns the number of facts merged.
*/
consolidate(options: ConsolidateOptions): Promise<number>;
/**
* Clear all memory data for a specific user and/or agent.
*/
clearAll(options: {
userId?: string;
agentName?: string;
}): Promise<void>;
}
ConsolidateOptions, CuratorStores, PruneOptions, StorageDriver.
CuratorStores
Sourceexport interface CuratorStores {
userFacts?: UserFacts | null;
userProfile?: UserProfile | null;
entityMemory?: EntityMemory | null;
decisionLog?: DecisionLog | null;
learnedKnowledge?: LearnedKnowledge | null;
correctionStore?: CorrectionStore | null;
}
CorrectionStore, DecisionLog, EntityMemory, LearnedKnowledge, UserFacts, UserProfile.
Decision
Sourceexport interface Decision {
id: string;
decision: string;
reasoning: string;
decisionType: string;
context?: string;
alternatives?: string[];
confidence?: number;
importance?: number;
outcome?: string;
outcomeQuality?: "good" | "bad" | "neutral";
agentName: string;
sessionId?: string;
createdAt: Date;
}
DecisionConfig
Sourceexport interface DecisionConfig {
/** Maximum recent decisions injected into context. Default: 5 */
maxContextDecisions?: number;
}
DecisionLog
Sourceexport declare class DecisionLog {
constructor(storage: StorageDriver, config?: {
maxContextDecisions?: number;
});
logDecision(agentName: string, decision: Omit<Decision, "id" | "agentName" | "createdAt">): Promise<Decision>;
recordOutcome(agentName: string, decisionId: string, outcome: string, quality?: "good" | "bad" | "neutral"): Promise<void>;
getDecisions(agentName: string, limit?: number, sessionId?: string): Promise<Decision[]>;
searchDecisions(agentName: string, query: string, sessionId?: string): Promise<Decision[]>;
clear(agentName: string): Promise<void>;
getContextString(agentName: string, sessionId?: string): Promise<string>;
getTools(): ToolDef[];
logToolCallAsDecision(agentName: string, toolName: string, args: unknown, sessionId?: string): Promise<void>;
}
Decision, StorageDriver, ToolDef.
Entity
Sourceexport interface Entity {
entityId: string;
entityType: string;
name: string;
description?: string;
properties: Record<string, unknown>;
facts: EntityFact[];
events: EntityEvent[];
relationships: EntityRelationship[];
createdAt: Date;
updatedAt: Date;
}
EntityEvent, EntityFact, EntityRelationship.
EntityConfig
Sourceexport interface EntityConfig {
/** Namespace for entity scoping. Supports hierarchical paths like "org/team/project". Default: "global" */
namespace?: string;
}
EntityEvent
Sourceexport interface EntityEvent {
id: string;
event: string;
date?: string;
importance?: number;
validFrom: Date;
invalidatedAt?: Date;
createdAt: Date;
}
EntityFact
Sourceexport interface EntityFact {
id: string;
fact: string;
importance?: number;
validFrom: Date;
invalidatedAt?: Date;
createdAt: Date;
}
EntityMemory
Sourceexport declare class EntityMemory {
constructor(storage: StorageDriver, config?: {
model?: ModelProvider;
namespace?: string;
});
getEntity(userId: string, entityId: string): Promise<Entity | null>;
listEntities(userId: string): Promise<Entity[]>;
upsertEntity(userId: string, entity: Partial<Entity> & {
name: string;
entityType: string;
}): Promise<Entity>;
addFact(userId: string, entityId: string, fact: string): Promise<void>;
addEvent(userId: string, entityId: string, event: string, date?: string): Promise<void>;
deleteEntity(userId: string, entityId: string): Promise<void>;
clear(userId: string): Promise<void>;
getContextString(userId: string | undefined, currentInput?: string): Promise<string>;
getTools(): ToolDef[];
extractEntities(userId: string | undefined, messages: ChatMessage[], fallbackModel?: ModelProvider): Promise<void>;
}
ChatMessage, Entity, ModelProvider, StorageDriver, ToolDef.
EntityRelationship
Sourceexport interface EntityRelationship {
targetEntityId: string;
type: string;
description?: string;
}
FileMemory
Source/**
* Tiny always-on memory files (MEMORY.md / USER.md).
* Hard character caps — overflow returns an error so the agent must consolidate.
*/
export declare class FileMemory {
constructor(config?: FileMemoryConfig);
getEntries(target: FileMemoryTarget, owner: string): Promise<string[]>;
add(target: FileMemoryTarget, owner: string, content: string): Promise<{
ok: true;
} | {
ok: false;
error: string;
usage: string;
current_entries: string[];
}>;
replace(target: FileMemoryTarget, owner: string, oldText: string, content: string): Promise<{
ok: true;
} | {
ok: false;
error: string;
}>;
remove(target: FileMemoryTarget, owner: string, oldText: string): Promise<{
ok: true;
} | {
ok: false;
error: string;
}>;
getContextString(owner: {
userId?: string;
agentName: string;
}): Promise<string>;
getTools(): ToolDef[];
}
FileMemoryConfig, FileMemoryTarget, ToolDef.
FileMemoryConfig
Sourceexport interface FileMemoryConfig {
storage?: StorageDriver;
memoryCharLimit?: number;
userCharLimit?: number;
}
StorageDriver.
FileMemoryTarget
Sourceexport type FileMemoryTarget = "memory" | "user";
GraphMemory
Sourceexport declare class GraphMemory {
constructor(config: GraphMemoryConfig);
initialize(): Promise<void>;
getStore(): GraphStore;
getContextString(currentInput?: string, userId?: string): Promise<string>;
extractFromConversation(userId: string | undefined, messages: ChatMessage[], fallbackModel?: ModelProvider): Promise<void>;
getTools(): ToolDef[];
}
ChatMessage, GraphMemoryConfig, GraphStore, ModelProvider, ToolDef.
GraphMemoryConfig
Sourceexport interface GraphMemoryConfig {
graphStore: GraphStore;
model?: ModelProvider;
autoExtract?: boolean;
maxContextNodes?: number;
}
GraphStore, ModelProvider.
GraphMemoryFeatureConfig
Sourceexport interface GraphMemoryFeatureConfig {
/** Graph store backend for knowledge graph. */
store: GraphStore;
/** Automatically extract entities and relationships from conversations. Default: true */
autoExtract?: boolean;
/** Maximum number of graph nodes in context. Default: 10 */
maxContextNodes?: number;
}
GraphStore.
isAncestor
Source/**
* Returns true if `parent` is an ancestor of (or equal to) `child` in
* a hierarchical "/" separated namespace.
*
* isAncestor("org", "org/team/project") → true
* isAncestor("org/team", "org/other") → false
*/
export declare function isAncestor(parent: string, child: string): boolean;
LearnedKnowledge
Sourceexport declare class LearnedKnowledge {
constructor(vectorStore: VectorStore, storage: StorageDriver, config?: {
model?: ModelProvider;
collection?: string;
topK?: number;
minScore?: number;
});
saveLearning(learning: Omit<Learning, "id" | "createdAt">): Promise<Learning>;
/**
* Search learnings visible to the caller. Vector matches are post-filtered
* by `canSee()` — vector backends don't all support metadata predicates, so
* we over-fetch and filter in-process.
*/
searchLearnings(query: string, opts?: {
topK?: number;
userId?: string;
agentName?: string;
tenantId?: string;
/** Override the store-level relevance floor for this search. */
minScore?: number;
}): Promise<Learning[]>;
getLearning(id: string): Promise<Learning | null>;
deleteLearning(id: string): Promise<void>;
/**
* Invalidate a learning: removed from the vector index (never retrieved
* again) but kept in KV storage for audit, marked with `invalidatedAt`
* and optionally the ID of what superseded it.
*/
invalidateLearning(id: string, supersededBy?: string): Promise<boolean>;
/**
* Invalidate unverified (llm-extracted) learnings that semantically collide
* with new authoritative knowledge — e.g. a human correction. Only items at
* or above `threshold` similarity AND with `source: "llm-extracted"` are
* invalidated; human-authored learnings are never auto-invalidated.
*
* Returns the IDs of invalidated learnings.
*/
invalidateContradicted(query: string, opts: {
supersededBy?: string;
threshold?: number;
agentName?: string;
tenantId?: string;
userId?: string;
}): Promise<string[]>;
/**
* Prune stale learnings to keep retrieval sharp as volume grows.
*
* Conservative by default:
* - Only `"llm-extracted"` (unverified) learnings are age-pruned — human
* knowledge (`"manual"`, `"human-correction"`) is kept unless explicitly
* included via `sources`.
* - Pre-v2.5 records with no `source` tag are NOT pruned unless
* `includeUntagged` is set.
* - Invalidated learnings older than the cutoff are always purged (their
* audit value decays; they're already excluded from retrieval).
*
* Returns the number of learnings removed.
*/
pruneLearnings(opts: {
maxAgeDays: number;
/** Provenance tiers eligible for age-pruning. Default: ["llm-extracted"] */
sources?: LearningSource[];
/** Also age-prune pre-v2.5 records that have no source tag. Default: false */
includeUntagged?: boolean;
/** Purge invalidated learnings older than the cutoff. Default: true */
purgeInvalidated?: boolean;
/** Only prune learnings belonging to this agent (agent-scoped). */
agentName?: string;
/** Only prune learnings belonging to this user (user-scoped). */
userId?: string;
}): Promise<number>;
/**
* Repair dual-write drift: re-index any active KV learning that is missing
* from the vector store (e.g. after a crash between the two writes).
* Returns the number of re-indexed records.
*/
reconcile(): Promise<number>;
getContextString(currentInput?: string, opts?: {
userId?: string;
agentName?: string;
tenantId?: string;
}): Promise<string>;
getTools(): ToolDef[];
extractLearnings(messages: ChatMessage[], fallbackModel?: ModelProvider, userId?: string): Promise<void>;
}
ChatMessage, Learning, LearningSource, ModelProvider, StorageDriver, ToolDef, VectorStore.
Learning
Sourceexport interface Learning {
id: string;
title: string;
content: string;
context: string;
tags: string[];
namespace: string;
importance?: number;
/** Defaults to "user" when omitted (backward-compat for pre-v2.3 data). */
scope?: LearningScope;
/** Provenance tier. Missing on pre-v2.5 data (rendered without a trust marker). */
source?: LearningSource;
/** Run that produced this learning, when known. */
sourceRunId?: string;
/** Supporting quote from the conversation (grounded extraction). */
evidence?: string;
/** Set when superseded/invalidated — invalidated learnings are never retrieved. */
invalidatedAt?: Date;
/** ID of the correction or learning that superseded this one. */
supersededBy?: string;
userId?: string;
agentName?: string;
tenantId?: string;
createdAt: Date;
}
LearningSource.
LearningsConfig
Sourceexport interface LearningsConfig {
/** Vector store for semantic search over learned insights. Required. */
vectorStore: VectorStore;
/** Collection name in the vector store. Default: "agentium_learnings" */
collection?: string;
/** Number of relevant learnings to inject into context. Default: 3 */
topK?: number;
/**
* Relevance floor (0–1) — matches below this similarity are never injected
* into context. Prevents weak matches from polluting the prompt.
* Recommended: 0.3–0.5 with real embeddings. Default: no floor.
*/
minScore?: number;
}
VectorStore.
LearningSource
Source/**
* Provenance of a learning — determines how much the agent should trust it.
*
* - `"human-correction"` derived from an explicit human correction (highest trust)
* - `"manual"` saved programmatically by application code
* - `"llm-extracted"` auto-extracted by an LLM from conversation (lowest trust —
* rendered as [unverified] in context)
*/
export type LearningSource = "human-correction" | "manual" | "llm-extracted";
MemoryManager
Sourceexport declare class MemoryManager {
readonly sessionManager: SessionManager;
readonly curator: Curator;
constructor(config: UnifiedMemoryConfig);
ensureReady(): Promise<void>;
getOrCreateSession(sessionId: string, userId?: string): Promise<Session>;
appendMessages(sessionId: string, messages: ChatMessage[], agentModel?: ModelProvider): Promise<{
overflow: ChatMessage[];
}>;
getHistory(sessionId: string, limit?: number): Promise<ChatMessage[]>;
updateState(sessionId: string, patch: Record<string, unknown>): Promise<void>;
buildContext(sessionId: string, userId?: string, currentInput?: string, agentName?: string): Promise<string>;
/**
* Runs every background memory extraction (user facts, profile, entities,
* learnings, graph, procedures).
*
* Returns a Promise that resolves once every extraction has completed. The
* Agent fires this without awaiting (to keep run() latency low), but callers
* that need to inspect memory immediately after a turn can `await` it.
*/
afterRun(_sessionId: string, userId: string | undefined, messages: ChatMessage[], agentModel?: ModelProvider, agentName?: string,
/** IANA timezone for date-anchored extraction. Falls back to UTC. */
timezone?: string): Promise<void>;
/**
* Wait for every in-flight background extraction (user facts, profile,
* entities, learnings, graph, procedures) to settle.
*
* Useful in tests, demos, and graceful-shutdown paths where you want to be
* sure all extractions for prior turns are persisted before reading or
* exiting. Normal agent.run() callers do NOT need this — extraction runs in
* the background and is best-effort.
*/
awaitExtractions(): Promise<void>;
/**
* Store a piece of information. Dispatches to the appropriate store based on context:
* user-scoped facts when userId is provided, entities otherwise.
*/
remember(content: string, opts?: {
userId?: string;
scope?: string;
importance?: number;
}): Promise<void>;
/**
* Recall memories matching a query. Searches across all enabled stores,
* applies composite scoring, and returns ranked results.
*/
recall(query: string, opts?: {
userId?: string;
topK?: number;
scope?: string;
}): Promise<ScoredMemory[]>;
/**
* Record a human correction of an agent's output as a first-class,
* structured event. The correction is embedded into the vector store and
* retrieved at inference time on future relevant runs.
*
* Self-corrective side effect (unless disabled via
* `corrections.invalidateContradicted: false`): unverified (llm-extracted)
* learnings that semantically collide with the correction are invalidated —
* the human correction supersedes them.
*
* Requires `corrections` to be configured on the memory config.
*/
recordCorrection(correction: Omit<Correction, "id" | "createdAt" | "tags"> & {
tags?: string[];
}): Promise<Correction>;
/**
* Remove memories matching the given criteria. Returns count of items removed.
*/
forget(opts: {
userId?: string;
factId?: string;
entityId?: string;
scope?: string;
}): Promise<number>;
getTools(): ToolDef[];
getUserFacts(): UserFacts | null;
getUserProfile(): UserProfile | null;
getEntityMemory(): EntityMemory | null;
getDecisionLog(): DecisionLog | null;
getLearnedKnowledge(): LearnedKnowledge | null;
getCorrectionStore(): CorrectionStore | null;
getSummaries(): Summaries | null;
getGraphMemory(): GraphMemory | null;
getProcedureMemory(): ProcedureMemory | null;
getMaxTokens(): number | undefined;
getMaxMessages(): number;
}
ChatMessage, Correction, CorrectionStore, Curator, DecisionLog, EntityMemory, GraphMemory, LearnedKnowledge, ModelProvider, ProcedureMemory, ScoredMemory, Session.
MemoryScope
Sourceexport interface MemoryScope {
path: string;
}
Procedure
Sourceexport interface Procedure {
id: string;
trigger: string;
description: string;
steps: ProcedureStep[];
successCount: number;
lastUsed: Date;
createdAt: Date;
/** Defaults to "user" when omitted (backward-compat for pre-v2.3 data). */
scope?: ProcedureScope;
/** Set when scope === "user". */
userId?: string;
/** Set when scope === "agent". */
agentName?: string;
/** Set when scope === "tenant". */
tenantId?: string;
}
ProcedureStep.
ProcedureMemory
Sourceexport declare class ProcedureMemory {
constructor(storage: StorageDriver, config?: ProcedureMemoryConfig);
/**
* Return every procedure visible to the caller — the union of their personal
* scope, the procedures saved against their current agent, and the tenant's
* shared procedures.
*/
getProcedures(caller?: {
userId?: string;
agentName?: string;
tenantId?: string;
}): Promise<Procedure[]>;
getProcedure(scope: ProcedureScope, owner: string | undefined, id: string): Promise<Procedure | null>;
/**
* Save a procedure at the chosen scope. The caller is responsible for
* supplying the right owner identifier for that scope.
*/
saveProcedure(proc: Omit<Procedure, "id" | "createdAt" | "successCount" | "lastUsed">): Promise<Procedure>;
suggestProcedure(caller: {
userId?: string;
agentName?: string;
tenantId?: string;
}, input: string): Promise<Procedure | null>;
getContextString(currentInput?: string, caller?: {
userId?: string;
agentName?: string;
tenantId?: string;
}): Promise<string>;
extractProcedures(userId: string | undefined, messages: ChatMessage[], fallbackModel?: ModelProvider): Promise<void>;
getTools(): ToolDef[];
/**
* Clear procedures. With no `caller` provided this wipes the legacy
* unscoped namespace only — used by curator maintenance. To wipe a
* specific scope, pass `{ scope, owner }`.
*/
clear(opts?: {
scope?: ProcedureScope;
owner?: string;
} | string): Promise<void>;
}
ChatMessage, ModelProvider, Procedure, ProcedureMemoryConfig, StorageDriver, ToolDef.
ProcedureMemoryConfig
Sourceexport interface ProcedureMemoryConfig {
maxProcedures?: number;
model?: ModelProvider;
}
ModelProvider.
ProceduresConfig
Sourceexport interface ProceduresConfig {
/** Maximum stored procedures. Default: 50 */
maxProcedures?: number;
}
ProcedureStep
Sourceexport interface ProcedureStep {
toolName: string;
argsSnapshot: Record<string, unknown>;
resultSummary: string;
}
PruneOptions
Sourceexport interface PruneOptions {
maxAgeDays: number;
userId?: string;
agentName?: string;
}
recencyDecay
Source/**
* Exponential decay based on age. Returns a value between 0 and 1.
* Half-life determines how quickly older items lose relevance.
*/
export declare function recencyDecay(createdAt: Date, halfLifeDays?: number): number;
resolveScope
Source/**
* Expand a scope path into all ancestor paths (inclusive).
*
* resolveScope("org/team/project") → ["org", "org/team", "org/team/project"]
*/
export declare function resolveScope(scope: string): string[];
scopeMatches
Source/**
* Check whether a stored namespace matches a query scope —
* a stored item at "org/team" is visible to queries for "org/team" or "org/team/project".
*/
export declare function scopeMatches(storedScope: string, queryScope: string): boolean;
ScoredMemory
Sourceexport interface ScoredMemory {
content: string;
score: number;
source: string;
}
ScoringWeights
Sourceexport interface ScoringWeights {
semantic: number;
recency: number;
importance: number;
}
Summaries
Sourceexport declare class Summaries {
constructor(storage: StorageDriver, config?: {
model?: ModelProvider;
maxCount?: number;
maxTokens?: number;
});
summarize(sessionId: string, messages: ChatMessage[], fallbackModel?: ModelProvider): Promise<void>;
getSummaries(sessionId: string): Promise<string[]>;
/**
* Returns the most recent summaries within the token budget. The newest
* summaries carry the most context for the current turn — older ones drop off
* first. Pass `currentInput` to opportunistically boost summaries that share
* keywords with the user's message (cheap relevance heuristic).
*/
getContextString(sessionId: string, currentInput?: string): Promise<string>;
clear(sessionId: string): Promise<void>;
}
ChatMessage, ModelProvider, StorageDriver.
SummaryConfig
Sourceexport interface SummaryConfig {
/** Maximum number of summaries kept per session (oldest pruned first). Default: 10 */
maxCount?: number;
/** Token budget for summary context injected into the system prompt. Default: 2000 */
maxTokens?: number;
}
SummaryEntry
Sourceexport interface SummaryEntry {
key: string;
summary: string;
createdAt: Date;
}
UnifiedMemoryConfig
Sourceexport interface UnifiedMemoryConfig {
/** Storage backend shared by all memory subsystems. */
storage: StorageDriver;
/** Maximum messages kept in session history. Oldest are trimmed first. Default: 50 */
maxMessages?: number;
/** Maximum context window tokens for history. History is auto-trimmed to fit. */
maxTokens?: number;
/**
* Long-term conversation summaries. Auto-summarizes overflow messages.
* ON by default. Pass `false` to disable, `true` for defaults, or a config object.
*/
summaries?: boolean | SummaryConfig;
/**
* User fact extraction — "user prefers dark mode", "lives in Mumbai".
* OFF by default. Pass `true` for defaults, or a config object.
*/
userFacts?: boolean | UserFactsConfig;
/**
* Structured user profile — name, role, timezone, language, custom fields.
* OFF by default. Pass `true` for defaults, or a config object.
*/
userProfile?: boolean | UserProfileConfig;
/**
* Entity memory — companies, people, projects extracted from conversations.
* OFF by default. Pass `true` for defaults, or a config object.
*/
entities?: boolean | EntityConfig;
/**
* Decision audit trail — what the agent decided and why.
* OFF by default. Pass `true` for defaults, or a config object.
*/
decisions?: boolean | DecisionConfig;
/**
* Learned knowledge — vector-backed insights from interactions.
* OFF by default. Pass a config with a vectorStore to enable.
*/
learnings?: LearningsConfig;
/**
* Correction capture — structured records of humans correcting agent
* output, embedded and retrieved at inference time so mistakes are not
* repeated. OFF by default. Pass a config with a vectorStore to enable.
*/
corrections?: CorrectionsConfig;
/**
* Knowledge graph — entity-relationship graph with traversal and temporal awareness.
* OFF by default. Pass a config with a GraphStore to enable.
*/
graph?: GraphMemoryConfig;
/**
* Procedural memory — records successful tool-call workflows for reuse.
* OFF by default. Pass `true` for defaults, or a config object.
*/
procedures?: boolean | ProceduresConfig;
/**
* Token budget allocation for context building.
* Controls how memory context is distributed across sections.
*/
contextBudget?: ContextBudgetConfig;
/**
* Separate (cheaper) model used for all background extraction operations.
* Falls back to the agent's primary model if not set.
*/
model?: ModelProvider;
/**
* IANA timezone (e.g. "Asia/Kolkata") used to anchor date-relative extraction
* ("today", "yesterday"). Falls back to UTC when omitted. Always set this in
* production — otherwise users near midnight get wrong dates extracted.
*/
timezone?: string;
/**
* Tenant identifier — when set, learnings and procedures saved with
* `scope: "tenant"` are visible to every user/agent under this tenant.
* Required for tenant-scoped reads to return anything.
*/
tenantId?: string;
/**
* Optional event bus — when supplied, memory extraction failures and
* other framework events are emitted here so they can be wired into
* observability (OpenTelemetry, Langfuse, Prometheus, etc.).
*/
eventBus?: EventBus;
}
ContextBudgetConfig, CorrectionsConfig, DecisionConfig, EntityConfig, EventBus, GraphMemoryFeatureConfig, LearningsConfig, ModelProvider, ProceduresConfig, StorageDriver, SummaryConfig, UserFactsConfig.
UserFact
Sourceexport interface UserFact {
id: string;
fact: string;
/** Topic categories derived during extraction (e.g. "preference", "location"). */
topics: string[];
/**
* Canonical short identifier for the aspect this fact describes, e.g.
* "birthday", "location", "role", "company", "interest:scifi".
* Used to automatically supersede prior facts about the same aspect when
* the extractor LLM forgets to set `supersedes` explicitly.
*/
subject?: string;
/** The user message that triggered this fact. */
input?: string;
/** Importance score from 0 to 1 assigned during extraction. */
importance?: number;
/** When this fact became valid. */
validFrom: Date;
/** Set when this fact was invalidated (either superseded or forgotten). */
invalidatedAt?: Date;
/**
* Why this fact was invalidated:
* - "superseded": a newer fact about the same subject replaced it (auto or explicit). It is just outdated.
* - "forgotten": the user explicitly asked to delete it. It must never be restated.
* Undefined on legacy data — `getContextString` uses a subject-based heuristic as a fallback.
*/
invalidationReason?: "superseded" | "forgotten";
createdAt: Date;
source: "auto" | "manual";
}
UserFacts
Sourceexport declare class UserFacts {
constructor(storage: StorageDriver, config?: {
model?: ModelProvider;
maxFacts?: number;
});
getFacts(userId: string): Promise<UserFact[]>;
addFacts(userId: string, facts: Array<{
fact: string;
subject?: string;
topics?: string[];
importance?: number;
supersedes?: string;
}>, source?: "auto" | "manual", input?: string): Promise<void>;
removeFact(userId: string, factId: string): Promise<void>;
/**
* Invalidate (soft-delete) every active fact whose text matches any of
* the provided strings. Matching is case-insensitive on the trimmed text.
* Used for user-initiated "forget X" instructions.
*/
forgetByText(userId: string, factTexts: string[]): Promise<number>;
clear(userId: string): Promise<void>;
/**
* @param userId
* @param maxFacts soft cap on facts surfaced in the prompt (default 20).
* Excess facts are dropped from the bottom after sorting by (importance, recency).
*/
getContextString(userId: string, maxFacts?: number): Promise<string>;
getActiveFacts(userId: string): Promise<UserFact[]>;
asTool(config?: {
name?: string;
description?: string;
}): ToolDef;
extractAndStore(userId: string, messages: ChatMessage[], fallbackModel?: ModelProvider,
/** IANA timezone of the user, e.g. "Asia/Kolkata". Falls back to UTC. */
timezone?: string): Promise<void>;
}
ChatMessage, ModelProvider, StorageDriver, ToolDef, UserFact.
UserFactsConfig
Sourceexport interface UserFactsConfig {
/** Maximum number of facts stored per user. Default: 100 */
maxFacts?: number;
}
UserProfile
Sourceexport declare class UserProfile {
constructor(storage: StorageDriver, config?: {
model?: ModelProvider;
customFields?: string[];
});
getProfile(userId: string): Promise<UserProfileData | null>;
updateProfile(userId: string, patch: Partial<UserProfileData>): Promise<UserProfileData>;
clear(userId: string): Promise<void>;
getContextString(userId: string): Promise<string>;
asTool(): ToolDef;
extractAndUpdate(userId: string, messages: ChatMessage[], fallbackModel?: ModelProvider): Promise<void>;
}
ChatMessage, ModelProvider, StorageDriver, ToolDef, UserProfileData.
UserProfileConfig
Sourceexport interface UserProfileConfig {
/** Additional custom fields to track beyond the built-in ones (name, role, etc.). */
customFields?: string[];
}
UserProfileData
Sourceexport interface UserProfileData {
name?: string;
preferredName?: string;
role?: string;
company?: string;
location?: string;
timezone?: string;
language?: string;
custom: Record<string, unknown>;
updatedAt: Date;
}
Supporting types
These local shapes appear in public signatures but are not named exports of this entrypoint.LearningScope
/**
* Scope of a stored learning — controls who can read it back.
*
* - `"user"` (default) only the user that saved it sees it.
* - `"agent"` every user of this agent / role sees it. Use for workflow knowledge
* like "invoice reconciliation patterns" or "common refund triggers".
* - `"tenant"` every user/agent in the tenant sees it. Org-wide policies.
* - `"global"` truly cross-tenant (rare — usually only for built-in defaults).
*
* When searching, the caller passes the scope identifiers they're authorized
* for (their `userId`, current `agentName`, current `tenantId`) and the union
* of accessible scopes is returned.
*/
export type LearningScope = "user" | "agent" | "tenant" | "global";
ProcedureScope
/**
* Procedure scope — same hierarchy as LearnedKnowledge.
* Auto-extracted procedures default to "user". The agent can use scope="agent"
* for shared workflow templates (e.g. "invoice reconciliation").
*/
export type ProcedureScope = "user" | "agent" | "tenant" | "global";