Memory API
Public exports of @cogitator-ai/memory with their signatures, from memory adapters, embeddings, hybrid search and context building to facts, memory items, sessions and knowledge graphs.
Every adapter method returns a MemoryResult<T> ({ success: true, data } | { success: false, error }). Check result.success, or use unwrap():
import { InMemoryAdapter, unwrap } from '@cogitator-ai/memory';
const memory = new InMemoryAdapter();
await memory.connect();
const thread = unwrap(await memory.createThread('agent-1', { topic: 'billing' }));
await memory.addEntry({
threadId: thread.id,
message: { role: 'user', content: 'Hello' },
tokenCount: 2,
});
const entries = unwrap(await memory.getEntries({ threadId: thread.id, limit: 20 }));| Export | Signature | Purpose |
|---|---|---|
unwrap | unwrap<T>(result: MemoryResult<T>): T | The data, or throws Error(result.error) |
Memory Adapters
All conversation adapters implement MemoryAdapter:
| Method | Signature |
|---|---|
connect | connect(): Promise<MemoryResult<void>> |
disconnect | disconnect(): Promise<MemoryResult<void>> |
createThread | createThread(agentId: string, metadata?: Record<string, unknown>, threadId?: string): Promise<MemoryResult<Thread>> |
getThread | getThread(threadId: string): Promise<MemoryResult<Thread | null>> |
updateThread | updateThread(threadId: string, metadata: Record<string, unknown>): Promise<MemoryResult<Thread>> |
deleteThread | deleteThread(threadId: string): Promise<MemoryResult<void>> |
addEntry | addEntry(entry: NewMemoryEntry): Promise<MemoryResult<MemoryEntry>> (an entry without seq and formatVersion, plus id? (a caller-given id, letters, digits, _ and -, refused when the adapter keeps it already), parentId?, activate?, createdAt?) |
getEntries | getEntries(options: MemoryQueryOptions): Promise<MemoryResult<MemoryEntry[]>> ({ threadId, limit?, before?, after?, includeToolCalls?, types? }), every branch |
getEntry | getEntry(entryId: string): Promise<MemoryResult<MemoryEntry | null>> |
deleteEntry | deleteEntry(entryId: string): Promise<MemoryResult<void>> |
clearThread | clearThread(threadId: string): Promise<MemoryResult<void>> |
healthCheck? | healthCheck(): Promise<MemoryResult<void>>, connectivity check for server readiness probes |
getPath? | getPath(options: PathQueryOptions): Promise<MemoryResult<MemoryEntry[]>> ({ threadId, leafId?, limit?, before?, types?, includeToolCalls? }), one branch |
rewind? | rewind(threadId: string, toEntryId: string): Promise<MemoryResult<Thread>>, the active leaf back along its branch |
checkout? | checkout(threadId: string, entryId: string): Promise<MemoryResult<Thread>>, any branch active |
forkThread? | forkThread(threadId: string, atEntryId: string, newThreadId?: string): Promise<MemoryResult<Thread>>, a branch copied into a new thread listed in the origin's metadata.memoryForks, without its paused run |
redactEntry? | redactEntry(entryId: string, redaction: EntryRedaction): Promise<MemoryResult<MemoryEntry | null>>, what the entry said becomes [redacted] in place, null for a missing entry, an event entry refused |
The branch methods, redactEntry and healthCheck are optional on the interface, and every built-in adapter implements them. Custom adapters can implement healthCheck(): Promise<MemoryResult<void>> to participate in server readiness checks. Adapters without healthCheck report unchecked and do not fail readiness. deleteEntry splices the entry out of its branch. See Threads as Trees.
| Export | Constructor | Also implements | Notes |
|---|---|---|---|
InMemoryAdapter | new InMemoryAdapter(config?: InMemoryAdapterConfig) | MemoryItemAdapter | Process memory, maxEntries per thread (default 10000), stats getter |
RedisAdapter | new RedisAdapter(config: RedisAdapterConfig) | MemoryItemAdapter | url or host/port, or cluster, ttl (seconds, default 0: no expiry, never for items), keyPrefix |
PostgresAdapter | new PostgresAdapter(config: PostgresAdapterConfig) | MemoryItemAdapter, FactAdapter, EmbeddingAdapter, KeywordSearchAdapter | connectionString, schema?, poolSize?, pgvector, setVectorDimensions(n) |
SQLiteAdapter | new SQLiteAdapter(config: SQLiteAdapterConfig) | MemoryItemAdapter | path (':memory:' allowed), walMode (default true) |
MongoDBAdapter | new MongoDBAdapter(config: MongoDBAdapterConfig) | MemoryItemAdapter | uri, database (default cogitator), collectionPrefix (default memory_) |
BaseMemoryAdapter | abstract class | - | Base for your own adapter |
ChangeReportingMemoryAdapter | abstract class | - | Base that reports changes through onChange |
BranchingMemoryAdapter | abstract class | - | Base that gives getPath, rewind, checkout and forkThread on top of setActiveLeaf |
redactedEntry, REDACTED_TEXT | redactedEntry(entry: MemoryEntry, redaction: EntryRedaction): MemoryEntry | undefined, '[redacted]' | - | The entry as redactEntry leaves it, undefined for an event entry, for an adapter of your own |
FORKS_KEY | 'memoryForks' | - | The thread metadata key forkThread lists a thread's forks under, which cascades follow to the copies |
MEMORY_USERS_KEY | 'memoryUserIds' | - | The thread metadata key runs list the users who wrote in a thread under, which deleteUser reads |
createMemoryAdapter | createMemoryAdapter(config: MemoryAdapterConfigUnion): Promise<MemoryAdapter> | - | Adapter from { provider: 'memory' | 'redis' | 'postgres' | 'sqlite' | 'mongodb', … }, not connected yet |
The adapter configs take provider plus the fields above; inside CogitatorConfig.memory the same fields go under inMemory, redis, postgres, sqlite or mongodb without provider. See Memory Adapters.
Facts and Embeddings
| Interface | Methods |
|---|---|
FactAdapter | addFact(fact), getFacts(agentId, category?), updateFact(factId, updates), deleteFact(factId), searchFacts(agentId, query) |
MemoryItemAdapter | putItem(item), getItem(itemId), findItems(filter: MemoryItemFilter), deleteItems(itemIds), putEntity(entity), findEntities(filter: MemoryEntityFilter), deleteEntities(entityIds) |
EmbeddingAdapter | addEmbedding(embedding), search(options: SemanticSearchOptions) → (Embedding & { score })[], deleteEmbedding(id), deleteBySource(sourceId) |
KeywordSearchAdapter | keywordSearch(options: KeywordSearchOptions): Promise<MemoryResult<SearchResult[]>> |
| Export | Constructor | Implements |
|---|---|---|
QdrantAdapter | new QdrantAdapter(config: QdrantAdapterConfig) | EmbeddingAdapter (+ connect/disconnect); dimensions required, url default http://localhost:6333, collection default cogitator |
InMemoryEmbeddingAdapter | new InMemoryEmbeddingAdapter() | EmbeddingAdapter, KeywordSearchAdapter; size, clear() |
createEmbeddingAdapter | createEmbeddingAdapter(config: QdrantAdapterConfig): Promise<ConnectableEmbeddingAdapter> | — |
Embedding Services
EmbeddingService: embed(text): Promise<number[]>, embedBatch(texts): Promise<number[][]>, dimensions, model.
| Export | Constructor | Default model | Default dimensions |
|---|---|---|---|
OpenAIEmbeddingService | new OpenAIEmbeddingService({ apiKey, model?, baseUrl?, dimensions? }) | text-embedding-3-small | per model (1536 for 3-small) |
OllamaEmbeddingService | new OllamaEmbeddingService({ model?, baseUrl?, dimensions? }?) | nomic-embed-text | per model (768 for nomic) |
GoogleEmbeddingService | new GoogleEmbeddingService({ apiKey, model?, baseUrl?, dimensions? }) | gemini-embedding-001 | 3072 |
createEmbeddingService | createEmbeddingService(config: EmbeddingServiceConfig): EmbeddingService | — | — |
See Embeddings.
Search
| Export | Signature | Purpose |
|---|---|---|
HybridSearch | new HybridSearch(config: { embeddingAdapter; embeddingService; keywordAdapter?; defaultWeights? }) | Vector + BM25 search fused with RRF |
hybrid.search | search(options: SearchOptions): Promise<MemoryResult<SearchResult[]>> ({ query, strategy: 'vector' | 'keyword' | 'hybrid', weights?, limit?, threshold?, filter? }) | Run a search |
hybrid.indexDocument / removeDocument / clearIndex / indexSize | (id, content), (id), (), getter | The built-in BM25 index, used when no keywordAdapter is given |
BM25Index | new BM25Index(config?: { k1?; b?; tokenizer? }) — addDocument, addDocuments, removeDocument, search(query, limit?), getDocument, clear, size | Keyword index |
reciprocalRankFusion | reciprocalRankFusion(resultSets: { id }[][], weights: number[], config?: { k? }): Map<string, number> | RRF scores (k default 60) |
fuseSearchResults | fuseSearchResults(vector: SearchResult[], keyword: SearchResult[], weights: HybridSearchWeights, config?): SearchResult[] | Merge two result lists |
tokenize, getTermFrequency | tokenize(text, config?: { lowercase?; removeStopwords?; minLength? }): string[] | Tokenizer used by BM25 |
PostgresAdapter keeps each fact as a memory item of its own slot fact:<id>: updateFact with new content supersedes the current item and keeps the old statement in the fact's history, deleteFact deletes the fact with its history, and a fact without evidence comes back without evidence. MemoryItemAdapter only stores: findItems returns items oldest recorded first, leaves out those let go (expiredAt not after now) unless includeExpired, and filters by scope in the storage: visibleTo keeps the items a scope sees (each of user, project and thread absent on the item or the same), scope the items of exactly that scope. See Memory Items.
defaultWeights is { bm25: 0.4, vector: 0.6 }. See Hybrid Search.
Context Building and Tokens
| Export | Signature | Purpose |
|---|---|---|
ContextBuilder | new ContextBuilder(config: ContextBuilderConfig, deps: ContextBuilderDeps) | Assemble history, facts, semantic and graph context within a token budget |
builder.build | build(options: BuildContextOptions): Promise<BuiltContext> | Messages plus memoryContext, partitions, dropped, errors and warnings |
formatTurnContext | formatTurnContext(blocks: readonly string[]): string | undefined | The turn context text a context ends with, from texts of your own (none when all empty) |
withoutTurnContext | withoutTurnContext(text: string): string | The input of a message sent with a turn context, the <memory_context> part cut off |
extendTurnContext | extendTurnContext(text: string, block: string): string | text with block added to the turn context in front of it, or a new one there |
markTurnEnds | markTurnEnds(history: Message[]): Message[] | Cache breakpoints at the end of a history and of the turn before its last one |
ContextAssembler | new ContextAssembler(partitions?: Partial<Record<ContextPartition, ContextPartitionBudget>>) - assemble(budget, candidates), budgetOf(partition) | Share a token budget among partitions |
DEFAULT_PARTITIONS | Readonly<Record<ContextPartition, ContextPartitionBudget>> | The partition budgets a config sets none for |
fitInOrder | fitInOrder<T>(blocks: AssemblyBlock<T>[], budget: number): FitResult<T> | The default fit: blocks in order while they fit, skipping one that does not |
countTokens | countTokens(text: string): number | Token estimate |
countMessageTokens, countMessagesTokens | (message: Message), (messages: Message[]) | Token estimates for messages, with tool calls and images |
countEntryTokens, countToolCallsTokens | (entry: MemoryEntry), (toolCalls: ToolCall[]) | Recount a stored entry, estimate tool calls |
truncateToTokens | truncateToTokens(text: string, maxTokens: number): string | Cut text to a token budget |
BuildContextOptions is { threadId, agentId, memoryAgentId?, userId?, systemPrompt?, currentInput?, maxTokens?, reserveTokens?, leafId?, pinned?, index?, brief? }. memoryAgentId is the id the agent's memory items are kept under, agentId by default (a Cogitator run passes the agent's configured id, else its name). maxTokens is this build's budget in place of the builder's, such as the context window of the model it is built for, and reserveTokens the room it keeps for the answer in place of the builder's. leafId is the entry the history ends at (the thread's active branch by default, none for null). pinned (a list), index and brief are texts of the partitions of the same names.
BuiltContext.messages is one system message (the system prompt, pinned, index), the compaction summary and the history with cacheBreakpoint: true on its last message and on the last message of the turn before (markTurnEnds), then a user message with memoryContext (the brief, facts, search results and graph context) when there is any. partitions holds the tokens each partition took, the input (final) included, and tokenCount the tokens of the context without it. The result's dropped (DroppedContext) lists the history entries, facts, search results and graph nodes left out, with their token count, and blocks, every left out block as a DroppedBlock with its partition, reason (budget, duplicate, not-selected or oversized), tokens and sourceId. With the relevant and hybrid strategies its entries include those the selection passed over, not only those the budget had no room for. See Context Building.
ContextBuilderConfig is { maxTokens?, strategy: 'recent' | 'relevant' | 'hybrid', reserveTokens?, includeSystemPrompt?, includeFacts?, includeSemanticContext?, includeGraphContext?, graphContextOptions?, partitions? }, and ContextBuilderDeps is { memoryAdapter, factAdapter?, memoryItems?, reranker?, embeddingAdapter?, embeddingService?, graphContextBuilder?, messageIndex?, observations? }. With observations (a MemoryObservations) a turn whose input names an entity, or that recalls one of its items, gets up to three observations next to the facts. With memoryItems (a MemoryItems) the facts partition holds the items the run's agent, user and thread see that hold now, one state per slot, in place of factAdapter's facts.
ContextAssembler.assemble<T>(budget, candidates: PartitionCandidates<T>[]) fills the partitions it is given, required ones first, then the others by their shares of what those leave, and recent last, and returns an Assembly<T>: kept blocks and tokens per partition, the dropped blocks and the tokens used. A PartitionCandidates<T> is { partition, blocks: AssemblyBlock<T>[], fit?, demand? }, where fit(blocks, budget) returns a FitResult<T> ({ kept, dropped, tokens? }) for a partition whose blocks are not in order of importance, and demand is the tokens it needs when its blocks do not say. An AssemblyBlock<T> is { value, tokens, text?, sourceId? }: blocks with text are left out as duplicate when a block a more lasting partition kept holds all of their text, word for word. A share outside 0 to 1, or shares of the partitions that are not required adding up to more than 1, throws. BuildContextOptions, Assembly, AssemblyBlock, FitResult and PartitionCandidates are exported as types.
Core Facts, Sessions, Compaction
| Export | Signature | Purpose |
|---|---|---|
CoreFactsStore | new CoreFactsStore(config: ({ path: string } | { db }) & { scope?: MemoryItemScope }): initialize, set, get, getAll, delete, getHistory, formatForPrompt, close | Key-value facts about a user in SQLite, kept as memory items of the slots core:<key>, with history |
SessionManager | new SessionManager(adapter: MemoryAdapter, options?: { compaction?: CompactionService; indexRefreshInterval?: number }): getOrCreate, get, update, archive, list, delete, incrementMessageCount, compact | Channel sessions per user and channel |
CompactionService | new CompactionService(config: { adapter: MemoryAdapter; summarize: SummarizeFn }): compact(sessionId, config), chapterAtoms(window, config, options?), applySummary(…) | Replace old entries with a summary |
compactedHistory | compactedHistory(path: readonly MemoryEntry[]): MemoryEntry[] | The conversation of a branch read with HISTORY_ENTRY_TYPES: the latest compaction's summary, the entries it kept and everything after |
readCompactedHistory | readCompactedHistory(memory, { threadId, leafId?, includeToolCalls? }): Promise<MemoryResult<MemoryEntry[]>> | The same conversation, read in pages back only to where the latest compaction goes on from |
CompactionConfig is { strategy, keepRecent, keepRecentTokens?, threshold?, messageThreshold?, chapterTokens?, chaptersPerArc?, arcsPerSaga?, summaryModel?, summaryPrompt? }: a thread is compacted once it holds threshold tokens or messageThreshold entries (at least one is required). strategy is 'hierarchical' | 'summary' | 'sliding-window' | 'hybrid'. The hierarchical strategy keeps the newest keepRecentTokens tokens of whole turns (else keepRecent entries), cuts what is new since the last compaction into chapters of chapterTokens (default 4000) and folds them into arcs (chaptersPerArc, default 4) and a saga (arcsPerSaga, default 4). Its compaction entry has event.levels (CompactionLevels) and the handoff as its message, and it is not written when it would lose an open control atom of the summary before it. chapterAtoms(window, config, { own?, open? }) returns the checked atoms (CompactionAtom[]) of one window of entries, the structural ones taken from own and the summarizer told the open items it may close. See Hierarchical Compaction. SummarizeFn is (messages: Message[], options?: SummarizeOptions) => Promise<string>, where SummarizeOptions is { model?: string; prompt?: string; maxTokens?: number }, model and prompt filled from summaryModel / summaryPrompt of the CompactionConfig passed to compact(), and maxTokens the tokens the answer may take (extraction and compaction chapters ask for 8000), which a Cogitator's summarizers pass to the backend.
Memory Items
| Export | Signature | Purpose |
|---|---|---|
MemoryItems | new MemoryItems(config: { adapter: MemoryItemAdapter; activationConfidence?: number; shadow?: boolean; now?: () => Date }) | Memory items with their rules (merge, supersession, activation, scopes, time) over any MemoryItemAdapter. With shadow every item is written suggested and weakens no other opinion |
items.write | write(items: readonly NewMemoryItem[]): Promise<MemoryItem[]> | Writes in order (one agent's writes one after another within a process), settles the timeline of every slot it writes, and returns the items as kept |
items.query | query(query: MemoryItemQuery): Promise<MemoryItem[]> | Items the scope sees that hold now, by default (active and superseded, which state holds read from the times, filtered by scope in the storage), oldest recorded first |
items.history | history(scope: MemoryItemScope, slot: string): Promise<MemoryItem[]> | Every item of a slot, current and closed, by validFrom |
items.activate | activate(itemId: string): Promise<MemoryItem> | A suggested item made active, closing what it follows. Keeps metadata.activatedAt |
items.markStale, items.expire, items.purge | markStale(itemIds, because?: Record<string, unknown>, onlyFrom?: readonly MemoryItemStatus[]), expire(itemIds, at?: Date), purge(itemIds), markStale returning the ids it marked (Promise<string[]>), the others Promise<void> | Mark as no longer trusted, let go (kept, keeping its place in the timeline), delete for good. None of them reopens a closed state. because is kept in the items' metadata.staleBecause, and with onlyFrom an item whose status is no longer one of those is left as it is. |
items.reviseEvidence | reviseEvidence(itemIds, keep: (evidence: Evidence) => boolean): Promise<string[]> | Keeps of each item's evidence the pieces keep takes, such as when the entries the rest quote were deleted, and returns the ids of the items it changed |
items.get, items.link, items.statusFor | get(itemId): Promise<MemoryItem | null>, link(scope, name, seenAt?, type?): Promise<MemoryEntity>, statusFor(item): 'active' | 'suggested' | One item, the entity a name stands for among those the scope sees (made in the scope when new, no aliases added), the status an item would get |
DEFAULT_ACTIVATION_CONFIDENCE | 0.7 | Confidence a user item with quotes that hold, or a system item, needs to become active |
OPINION_GAIN, OPINION_LOSS | 0.1, 0.2 | What an opinion said again with quotes that hold gains, and what one a less trusted source contradicts loses |
normalizeName, slotOf | normalizeName(text: string): string, slotOf(subject: string, attribute: string): string | Names and content as memory compares them, and the slot <subject>:<attribute> |
sameValue | sameValue(a: string, b: string): boolean | Whether two values of a slot are the same: the same text, spacing aside, case and signs counting |
visibleIn | visibleIn(item: Pick<MemoryItem, 'scope'>, scope: MemoryItemScope): boolean | Whether a run of scope sees the item |
isMemoryItemAdapter | isMemoryItemAdapter<T extends object>(adapter: T): adapter is T & MemoryItemAdapter | Whether a store keeps memory items, as every built-in one does |
matchesItemFilter, matchesEntityFilter, entityNames, byRecorded | (item, filter, now?), (entity, filter), (entity), (a, b) | For a store of your own that filters in process: the filters, every normalized name of an entity, the order |
resolveTime | resolveTime(expression: TimeExpression, sessionAt: Date, timeZone?: string): MemoryItemTime | The interval time words name, start inclusive and end exclusive, in an IANA time zone (UTC by default) |
calendarDate | calendarDate(instant: Date, timeZone: string): { year; month; day } | The calendar date of an instant in a time zone |
isTimeZone | isTimeZone(timeZone: string): boolean | Whether a string is an IANA time zone the runtime knows, such as Europe/Lisbon |
sameValue | sameValue(a: string, b: string): boolean | Whether two values of a slot are the same value: equal up to spaces, case and signs count |
MemoryExtractor | new MemoryExtractor(config: { items: MemoryItems; summarize: SummarizeFn; model?: string; prompt?: string; windowTokens?: number }): extract(entries, context, progress?: { onWindow?, skip?, beforeWindow?, beforeWrite? }), read(window, context) | Items extracted from entries, one model call per window of windowTokens (default 4000, answers up to 8000 tokens), checked and written. onWindow(own, items) hears of each window once written, skip(error, own, index) may go on without a window that failed, beforeWindow(own) returning false stops before a window's model call, beforeWrite(items) returns the items of a window to write. An answer cut inside its array keeps the finished items and is continued up to 4 times |
parseExtraction | parseExtraction(answer: string, window: readonly MemoryEntry[], context: MemoryExtractionContext): NewMemoryItem[] | undefined | The checked items of an extraction model's answer (a null, blank or unfitting field read as absent, an unfitting item left out), undefined when it holds no JSON array. The array is found past text and brackets around it, and the finished items of a cut one are kept |
EXTRACTION_CONTINUATIONS, extractionContinuationPrompt | 4, extractionContinuationPrompt(count: number, last: string): string | Times read asks the model to go on after an answer its length limit cut, and what it asks, naming the items read and the last one |
ExtractionAnswerError, WindowError | class extends Error (window), class extends ExtractionAnswerError (own) | The model answered a window three times with no JSON array, and the same error from extract with the entries that window was the first to read |
trustOfEntry | trustOfEntry(entry: MemoryEntry, userId?: string): MemoryItemTrust | The trust of what an entry says, by who wrote it: web for a tool whose name says it fetches pages, and model for a user message another user wrote (metadata.userId other than userId). An extracted item takes the least trusted of its entries whose quotes hold |
EXTRACTION_PROMPT, sessionLine | string, sessionLine(sessionAt: Date, timeZone?: string): string | The extraction model's instructions, and the line that dates the session |
MemoryExtractionContext is { scope: MemoryItemScope; sessionAt?: Date; timeZone?: string }: whose memory the items go to, the date relative dates are resolved from when an item quotes no entry (the time of the window's last entry by default, an item that quotes one is dated by the first entry it quotes) and the time zone (UTC by default). A TimeExpression is { text; date?; relative?: { unit: 'day' | 'week' | 'month' | 'year'; amount }; weekday?: { day: Weekday; amount } }. MemoryItemsConfig, MemoryExtractorConfig, MemoryExtractionContext, TimeExpression and Weekday are exported as types, and the item types (MemoryItem, NewMemoryItem, MemoryItemQuery, MemoryEntity, MemoryItemAdapter, ...) come from @cogitator-ai/types, see Memory Items.
Retrieval
| Export | Signature | Purpose |
|---|---|---|
MemoryRetriever | new MemoryRetriever(): retrieve(request: RetrievalRequest): Promise<Retrieval> | The search of Recall: turns and memory items for an input, one ranked list. It keeps a BM25 index of each thread between calls |
analyzeQuery | analyzeQuery(input: string, anchor: Date, timeZone?: string): QueryAnalysis | Reads a turn without a model: whether it is worth searching (retrieve), its kind (QueryType: temporal, update, aggregate, preference, general), the time it names resolved from anchor, and its terms |
timeExpressionOf | timeExpressionOf(text: string, today?: { year; month; day }): TimeExpression | undefined | The time words of a text, such as yesterday or 3 weeks ago, for resolveTime |
MIN_COSINE, RELATIVE_COSINE | 0.45, 0.6 | The bars a turn or an item found by its vector must clear: an absolute cosine, and a share of the best one |
RetrievalRequest is { input; anchor; timeZone?; history; held?; cosines?; items?; itemAdapter?; scope?; itemCosines?; agentIds? }: the turn, when it is asked, the thread's entries oldest first, the entries the context holds anyway, the cosines of entries from a vector search, the memory items to search with their store and scope, a function giving the cosines of the items found, and more agent ids whose items the turn sees. Retrieval is { analysis; hits }, each hit { kind: 'entry'; hit: RetrievedEntry } (with its neighbors) or { kind: 'item'; hit: RetrievedItem }, best first. The memory search tools of @cogitator-ai/core rank with it, see Agent Memory Tools.
Memory Files
| Export | Signature | Purpose |
|---|---|---|
MemoryFiles | new MemoryFiles(config: { adapter: MemoryFileAdapter; now?: () => Date }) | Memory files of a store, read and changed as the memory tool does it, every change a version |
files.run | run(access: MemoryFileAccess, command: MemoryFileCommand): Promise<string> | Runs a command of the memory tool, the answer as the model reads it |
files.view, files.create, files.delete, files.rename | view(access, path, range?), create(access, path, text), delete(access, path), rename(access, oldPath, newPath), each Promise<string> | The commands one by one |
files.strReplace, files.insert | strReplace(access, path, oldText, newText, expectedSha256?), insert(access, path, line, text, expectedSha256?), each Promise<string> | Edits that fail when the file's sha256 is no longer expectedSha256 |
files.list, files.read, files.history | list(access, directory?): Promise<MemoryFile[]>, read(access, path): Promise<MemoryFile | undefined>, history(access, path): Promise<MemoryFileVersion[]> | The files the access sees by path, one file, every version of one oldest first |
files.redact | redact(access, paths: readonly string[], reason?: string, options?: { everyScope?: boolean }): Promise<number> | Replaces the content of every version of the files, and of those under them, with REDACTED_CONTENT ([redacted]), following the file's own history across renames, every scope of the agent with everyScope, returning how many versions it redacted |
files.index | index(access, maxChars?: number): Promise<string | undefined> | The list of files for a run's context, 2000 characters at most by default |
files.put | put(access, path, text, expectedSha256?: string | null): Promise<string> | A whole file written, created when it does not exist, for code that keeps a file of its own. Fails when the file no longer stands at expectedSha256 (null for a file that must not exist yet), returns the new sha256 |
MemoryFileError | class extends Error | A command refused, with the message the model reads |
MAX_FILE_BYTES | 1_048_576 | The most bytes a memory file holds |
memoryPath, MEMORY_ROOT | memoryPath(path: string): string, '/memories' | A path as memory keeps it, or a MemoryFileError for one outside /memories |
isMemoryFileAdapter | isMemoryFileAdapter(candidate: unknown): candidate is MemoryFileAdapter | Whether a store keeps memory files, as every built-in one does |
sha256Of, fileKeyOf, matchesFileFilter, byFileVersion, fileHeads | (content), (scope, path), (version, filter), (a, b), (versions, place?) | For a store of your own: the hash of a content, the key a scope and a path keep their versions under, the filter in process, the order versions are found in |
MemoryFileAccess is { scope: MemoryItemScope; visibleTo?: MemoryItemScope; place?: MemoryFilePlace; readOnly?: boolean; reserved?: readonly string[]; author?: MemoryFileAuthor; observe?: (path: string, sha256: string | null) => void } and MemoryFilePlace is { threadId; pathIds: ReadonlySet<string>; entryId? }, the branch of a thread a run stands on. MemoryFile is { path; content; sha256; size; version }. MemoryFileCommand is one of the commands of the memory tool, as Anthropic's memory_20250818 tool sends them. MemoryFileAdapter, MemoryFileVersion, MemoryFileFilter, MemoryFileHeadFilter and MEMORY_FILE_CONFLICT come from @cogitator-ai/types. See Memory Files. reserved lists paths no change of the access may touch, nor anything under them, a rename into one included (<path> is kept by memory itself and is read-only here), while they are viewed as usual.
Between Runs
| Export | Signature | Purpose |
| ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| MemoryBriefer | new MemoryBriefer(options: { summarize: SummarizeFn; maxCards?: number; maxTokens?: number; prompt?: string }): brief(input: string, sources: readonly BriefSource[]): Promise<BriefCard[]> | Cards for a turn from what memory found for it, each quoting its source, kept only when the quote holds (Pre-Turn Brief). maxCards from 1 to 4 (default 4), maxTokens 600 by default |
| parseBrief, briefBlock | parseBrief(answer: string, sources: readonly BriefSource[], maxCards?: number): BriefCard[], briefBlock(cards): string \| undefined | The cards of a model's answer that stand, and the block a turn's memory context gets, marked as a hint |
| BRIEF_PROMPT, MAX_BRIEF_CARDS | string, 4 | The brief prompt, with {maxCards}, and the most cards a brief holds |
| MemoryObservations | new MemoryObservations(options: { files: MemoryFiles; items: MemoryItems; itemAdapter: MemoryItemAdapter }) | Observations of entities as memory files (Observations) |
| observations.refresh | refresh(scope: MemoryItemScope, options: { summarize; maxEntities?; minItems?; maxTokens?; prompt? }): Promise<{ written: MemoryObservation[]; deleted: string[] }> | Writes again the observations of the scope whose facts changed, at most maxEntities (3), and deletes those whose entity has fewer than minItems (3) facts that hold |
| observations.read | read(visibleTo: MemoryItemScope): Promise<MemoryObservation[]> | Every observation a run of the scope sees |
| parseObservation, parseObservationAnswer, namedIn | (file), (answer, known), (text, name) | Read an observation file (undefined for one a model wrote), keep the statements of an answer that stand on known items, and tell whether a text names an entity as words of its own |
| OBSERVATIONS_DIRECTORY, OBSERVATION_PROMPT | '/memories/observations', string | Where observations are kept, and their prompt |
| MemoryConsolidator | new MemoryConsolidator(options: { items: MemoryItems; itemAdapter: MemoryItemAdapter; files?: MemoryFiles }) | Consolidation of one scope's memory (Consolidation) |
| consolidator.dedupe | dedupe(scope, options: { summarize; since?: Date; maxChanges?: number; maxSubjects?: number; prompt?; maxTokens? }): Promise<{ stale: StaleMark[]; complete: boolean; through?: Date }> | Marks as stale the items of exactly the scope that repeat or contradict another one, never one more trusted than the item kept, at most maxChanges (10) items and maxSubjects (10) subjects, those whose newest item is oldest first. complete is false when a cap stopped it, and through then says it looked at every subject whose newest item was recorded up to then, so a later dedupe goes on since it |
| consolidator.foldLessons | foldLessons(scope, options: { summarize; mode?: 'apply' \| 'shadow'; prompt?; maxTokens? }): Promise<PlaybookChange \. Lessons go by when they were activated, else recorded, so one activated after a fold is still folded, on the newest playbook version memory or a person wrote | undefined> | Folds new active lessons, never one from a tool or a page, oldest first and 20 a fold, into the playbook in at most three edits, or into the draft with shadow, undefined when there was nothing to fold |
| consolidator.promotePlaybook, consolidator.readPlaybook | promotePlaybook(scope): Promise<boolean>, readPlaybook(visibleTo): Promise<MemoryFile \| undefined>, refusing a draft a model wrote | Makes the draft the playbook when the playbook did not change since, and reads the playbook |
| parsePlaybook, playbookFile, parsePlaybookEdits, applyPlaybookEdits | (content), (playbook), (answer, rules, known), (rules, edits) | Read and write the playbook file, keep the edits of an answer that stand, and make them |
| PLAYBOOK_PATH, PLAYBOOK_DRAFT_PATH, MAX_PLAYBOOK_EDITS, MAX_PLAYBOOK_RULES, DEDUPE_PROMPT, PLAYBOOK_PROMPT | '/memories/playbook.md', '/memories/playbook.next.md', 3, 60, string, string | The playbook, its draft, its limits and the prompts of a pass |
| MEMORY_RESERVED_PATHS | readonly string[]: PLAYBOOK_PATH, PLAYBOOK_DRAFT_PATH, OBSERVATIONS_DIRECTORY | The paths memory writes itself, which the memory tool reserves (MemoryFileAccess.reserved) |
BriefSource is { ref; text; date? }, ref being turn:<id> or item:<id>. MemoryObservation is { entityId; name; aliases; path; text; itemIds; basedOn; file }, basedOn being the fingerprint of the items it was written from. PlaybookEdit is { add; lessons } or { replace; with; lessons }, Playbook is { rules; through?; draftOf? } and PlaybookChange is { path; edits; lessonIds }.
Knowledge Graphs
| Export | Signature | Purpose |
|---|---|---|
PostgresGraphAdapter | new PostgresGraphAdapter(config: { pool; schema?; vectorDimensions? }) — call initialize() | GraphAdapter on Postgres (pass a pg pool) |
SQLiteGraphAdapter | new SQLiteGraphAdapter(config: { path: string; walMode?: boolean }) — initialize(), close() | GraphAdapter on SQLite |
LLMEntityExtractor | new LLMEntityExtractor(backend: LLMBackend, config: { model: string; minConfidence?; maxEntitiesPerText?; maxRelationsPerText? }) or new LLMEntityExtractor(backend: LLMBackendMinimal, config?: { model?; minConfidence?; maxEntitiesPerText?; maxRelationsPerText? }) — extract(text, context?), extractBatch | Entities and relations from text |
GraphInferenceEngine | new GraphInferenceEngine(graphAdapter: GraphAdapter, useDefaultRules?: boolean) — registerRule, removeRule, getRules, enableRule, disableRule, infer(agentId, options?), materialize(edges) | Rule-based edge inference |
GraphContextBuilder | new GraphContextBuilder(graphAdapter, embeddingService?, config?: GraphContextBuilderConfig) — buildContext(agentId, input, options?) | Graph context for prompts |
GraphAdapter methods: addNode, getNode, getNodeByName, updateNode, deleteNode, queryNodes, searchNodesSemantic, addEdge, getEdge, getEdgesBetween, updateEdge, deleteEdge, queryEdges, traverse, findShortestPath, getNeighbors, mergeNodes, clearGraph, getGraphStats — all returning MemoryResult. See Knowledge Graphs.
Lineage
| Export | Signature | Purpose |
|---|---|---|
verifyEvidence | verifyEvidence(evidence: Evidence, entry: MemoryEntry): EvidenceStatus | Whether the quote is in the entry or its tool result |
verifyEvidenceInMemory | verifyEvidenceInMemory(memory: Pick<MemoryAdapter, 'getEntry'>, evidence: readonly Evidence[]): Promise<MemoryResult<{ status; evidence: CheckedEvidence[] }>> | Check each piece against its stored entry |
evidenceOnPath | evidenceOnPath(evidence: readonly Evidence[], pathIds: ReadonlySet<string>): boolean | Whether every piece that names an entry lies on a branch |
EvidenceStatus is 'verified' | 'suggested', CheckedEvidence is an Evidence with its status. Evidence and EvidenceStatus come from @cogitator-ai/types. See Lineage.
Cascades
| Export | Signature | Purpose |
|---|---|---|
MemoryCascade | new MemoryCascade(options: MemoryCascadeOptions), MemoryCascadeOptions being { memory; items?; files?; graph?; facts?; embeddings?; now? } | Lineage cascades over the stores it is given: what stands on entries goes with them |
cascade.deleteEntries | deleteEntries(entryIds: readonly string[], who: CascadeAgents): Promise<MemoryCascadeReport> | Deletes the entries, a user message with its replies unless keepReplies, their copies in forks, and everything that stands on them |
cascade.redactEntries | redactEntries(entryIds: readonly string[], redaction: EntryRedaction, who: CascadeAgents): Promise<MemoryCascadeReport> | Redacts the entries, their replies and their copies in forks in place (redactEntry, an event entry deleted and listed in entries.deleted) and takes away what stands on them. Throws when the adapter cannot redact |
cascade.deleteThread | deleteThread(threadId: string, who: CascadeAgents): Promise<MemoryCascadeReport> | The thread with what stands on its entries and the copies of them in its forks, the items and entities kept for the thread alone purged and its memory file versions redacted (their files then deleted) |
cascade.deleteUser | deleteUser(userId: string, who: CascadeAgents): Promise<MemoryCascadeReport> | Every thread whose metadata.userId is the user whole, the user's messages in threads that list the user in metadata.memoryUserIds with their replies, the items and entities of the user's scope purged and its file versions redacted (their files then deleted), and the facts, graph nodes and edges and embeddings with that metadata.userId deleted. Lists every thread |
cascade.rewind | rewind(threadId: string, toEntryId: string, who: CascadeAgents, options?: { dryRun?: boolean }): Promise<MemoryCascadeReport> | MemoryAdapter.rewind, the items that stood only on the entries after toEntryId marked stale (staleBecause: { reason: 'rewound', threadId, toEntryId, at }) before the thread moves, so a failed one can be made again, a thread at toEntryId already left as it is. dryRun changes nothing and reports the items that would go stale. Throws without branch methods |
CascadeAgents is { agentIds: readonly string[]; keepReplies?: boolean }, the memory ids whose items, files, facts and graph to go through. A cascade reads no metadata.memoryAgentIds and drops no paused runs, a Cogitator does both. Derived memory goes before the entries, so a cascade that fails part of the way can be made again, and it looks for derived memory again once the entries went. A memory file whose version in front a cascade redacted is then deleted, and the entities no item is about any more are deleted after items are purged. MemoryCascadeReport is { entries: { deleted; redacted }; threads; threadsChanged; summaries; items: { purged; trimmed; stale }; entities; facts: { deleted; trimmed }; graph: { nodes; edges; trimmed }; fileVersions; playbookRules }, ids of what changed in each store (threads deleted, threadsChanged the threads that lost or had redacted some of their entries) and the count of playbook rules taken out. See Forgetting, Redacting and Rewinding.
Zod Schemas
For validating configuration: MemoryProviderSchema, InMemoryConfigSchema, RedisConfigSchema, PostgresConfigSchema, SQLiteConfigSchema, MongoDBConfigSchema, QdrantConfigSchema, MemoryAdapterConfigSchema, ContextStrategySchema, ContextBuilderConfigSchema, EmbeddingProviderSchema, OpenAIEmbeddingConfigSchema, OllamaEmbeddingConfigSchema, GoogleEmbeddingConfigSchema, EmbeddingServiceConfigSchema, and the knowledge-graph schemas (GraphNodeSchema, GraphEdgeSchema, ExtractionResultSchema, TraversalOptionsSchema, KnowledgeGraphConfigSchema, …).
Types
Re-exported from @cogitator-ai/types:
interface Thread {
id: string;
agentId: string;
metadata: Record<string, unknown>; // metadata.userId: the owning user
createdAt: Date;
updatedAt: Date;
activeLeafId?: string; // the entry the active branch ends at, absent with no entries
}
interface MemoryEntry {
id: string;
threadId: string;
message: Message;
toolCalls?: ToolCall[];
toolResults?: ToolResult[];
tokenCount: number;
createdAt: Date;
metadata?: Record<string, unknown>;
type?: MemoryEntryType; // 'message' when absent
parentId?: string | null; // the entry before it on its branch, null for the first
seq?: number; // order the thread's entries were added in
event?: Record<string, unknown>; // payload of an event entry
formatVersion?: number; // MEMORY_ENTRY_FORMAT (2) for entries written now
}
type MemoryEntryType =
| 'message'
| 'tool_result'
| 'model_change'
| 'compaction'
| 'approval'
| 'interrupt'
| 'label'
| 'custom';
interface PathQueryOptions {
threadId: string;
leafId?: string; // default: the active leaf
limit?: number; // the newest entries of the branch
before?: string; // only entries before this one, to page back
types?: readonly MemoryEntryType[] | 'all'; // default: CONVERSATION_ENTRY_TYPES
includeToolCalls?: boolean;
}
interface Fact {
id: string;
agentId: string;
content: string;
category: string;
confidence: number;
source: 'user' | 'inferred' | 'system';
createdAt: Date;
updatedAt: Date;
expiresAt?: Date;
metadata?: Record<string, unknown>; // metadata.userId: only in that user's context
evidence?: Evidence[]; // what it stands on, see Lineage
}
interface Embedding {
id: string;
sourceId: string;
sourceType: 'message' | 'fact' | 'document';
vector: number[];
content: string;
createdAt: Date;
metadata?: Record<string, unknown>;
}
interface SearchResult {
id: string;
sourceId: string;
sourceType: Embedding['sourceType'];
content: string;
score: number;
vectorScore?: number;
keywordScore?: number;
metadata?: Record<string, unknown>;
}MemoryEntryType, PathQueryOptions, NewMemoryEntry, Evidence and EvidenceStatus are re-exported here, CompactionEvent, the hierarchical compaction types (CompactionAtom, CompactionAtomKind, CompactionNode, CompactionLevels), CONVERSATION_ENTRY_TYPES (['message', 'tool_result']), MEMORY_ENTRY_FORMAT and the context types ContextPartition, ContextPartitionBudget, DroppedReason and DroppedBlock come from @cogitator-ai/types. HISTORY_ENTRY_TYPES (['message', 'tool_result', 'compaction']) is exported here. Also re-exported: the adapter configs, MemoryQueryOptions, SemanticSearchOptions, SearchOptions, SearchFilter, HybridSearchConfig, ContextBuilderConfig, BuiltContext, DroppedContext, MemoryConfig, the graph types (GraphNode, GraphEdge, TraversalOptions, InferenceRule, …) and the session types (Session, SessionFilter, CompactionConfig, CompactionResult; the interface is exported as ISessionManager).