Cogitator
API Reference

Memory API

Public exports of @cogitator-ai/memory — memory adapters, embeddings, hybrid search, context building, facts, sessions and knowledge graphs — with their signatures.

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 }));
ExportSignaturePurpose
unwrapunwrap<T>(result: MemoryResult<T>): TThe data, or throws Error(result.error)

Memory Adapters

All conversation adapters implement MemoryAdapter:

MethodSignature
connectconnect(): Promise<MemoryResult<void>>
disconnectdisconnect(): Promise<MemoryResult<void>>
createThreadcreateThread(agentId: string, metadata?: Record<string, unknown>, threadId?: string): Promise<MemoryResult<Thread>>
getThreadgetThread(threadId: string): Promise<MemoryResult<Thread | null>>
updateThreadupdateThread(threadId: string, metadata: Record<string, unknown>): Promise<MemoryResult<Thread>>
deleteThreaddeleteThread(threadId: string): Promise<MemoryResult<void>>
addEntryaddEntry(entry: Omit<MemoryEntry, 'id' | 'createdAt'>): Promise<MemoryResult<MemoryEntry>>
getEntriesgetEntries(options: MemoryQueryOptions): Promise<MemoryResult<MemoryEntry[]>> ({ threadId, limit?, before?, after?, includeToolCalls? })
getEntrygetEntry(entryId: string): Promise<MemoryResult<MemoryEntry | null>>
deleteEntrydeleteEntry(entryId: string): Promise<MemoryResult<void>>
clearThreadclearThread(threadId: string): Promise<MemoryResult<void>>
ExportConstructorAlso implementsNotes
InMemoryAdapternew InMemoryAdapter(config?: InMemoryAdapterConfig)—Process memory; maxEntries (default 10000); stats getter
RedisAdapternew RedisAdapter(config: RedisAdapterConfig)—url or host/port, or cluster; ttl (default 86400 s), keyPrefix
PostgresAdapternew PostgresAdapter(config: PostgresAdapterConfig)FactAdapter, EmbeddingAdapter, KeywordSearchAdapterconnectionString, schema?, poolSize?; pgvector; setVectorDimensions(n)
SQLiteAdapternew SQLiteAdapter(config: SQLiteAdapterConfig)—path (':memory:' allowed), walMode (default true)
MongoDBAdapternew MongoDBAdapter(config: MongoDBAdapterConfig)—uri, database (default cogitator), collectionPrefix (default memory_)
BaseMemoryAdapterabstract class—Base for your own adapter
createMemoryAdaptercreateMemoryAdapter(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

InterfaceMethods
FactAdapteraddFact(fact), getFacts(agentId, category?), updateFact(factId, updates), deleteFact(factId), searchFacts(agentId, query)
EmbeddingAdapteraddEmbedding(embedding), search(options: SemanticSearchOptions) → (Embedding & { score })[], deleteEmbedding(id), deleteBySource(sourceId)
KeywordSearchAdapterkeywordSearch(options: KeywordSearchOptions): Promise<MemoryResult<SearchResult[]>>
ExportConstructorImplements
QdrantAdapternew QdrantAdapter(config: QdrantAdapterConfig)EmbeddingAdapter (+ connect/disconnect); dimensions required, url default http://localhost:6333, collection default cogitator
InMemoryEmbeddingAdapternew InMemoryEmbeddingAdapter()EmbeddingAdapter, KeywordSearchAdapter; size, clear()
createEmbeddingAdaptercreateEmbeddingAdapter(config: QdrantAdapterConfig): Promise<ConnectableEmbeddingAdapter>—

Embedding Services

EmbeddingService: embed(text): Promise<number[]>, embedBatch(texts): Promise<number[][]>, dimensions, model.

ExportConstructorDefault modelDefault dimensions
OpenAIEmbeddingServicenew OpenAIEmbeddingService({ apiKey, model?, baseUrl?, dimensions? })text-embedding-3-smallper model (1536 for 3-small)
OllamaEmbeddingServicenew OllamaEmbeddingService({ model?, baseUrl?, dimensions? }?)nomic-embed-textper model (768 for nomic)
GoogleEmbeddingServicenew GoogleEmbeddingService({ apiKey, model?, baseUrl?, dimensions? })gemini-embedding-0013072
createEmbeddingServicecreateEmbeddingService(config: EmbeddingServiceConfig): EmbeddingService——

See Embeddings.

ExportSignaturePurpose
HybridSearchnew HybridSearch(config: { embeddingAdapter; embeddingService; keywordAdapter?; defaultWeights? })Vector + BM25 search fused with RRF
hybrid.searchsearch(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), (), getterThe built-in BM25 index, used when no keywordAdapter is given
BM25Indexnew BM25Index(config?: { k1?; b?; tokenizer? }) — addDocument, addDocuments, removeDocument, search(query, limit?), getDocument, clear, sizeKeyword index
reciprocalRankFusionreciprocalRankFusion(resultSets: { id }[][], weights: number[], config?: { k? }): Map<string, number>RRF scores (k default 60)
fuseSearchResultsfuseSearchResults(vector: SearchResult[], keyword: SearchResult[], weights: HybridSearchWeights, config?): SearchResult[]Merge two result lists
tokenize, getTermFrequencytokenize(text, config?: { lowercase?; removeStopwords?; minLength? }): string[]Tokenizer used by BM25

defaultWeights is { bm25: 0.4, vector: 0.6 }. See Hybrid Search.

Context Building and Tokens

ExportSignaturePurpose
ContextBuildernew ContextBuilder(config: ContextBuilderConfig, deps: ContextBuilderDeps)Assemble history, facts, semantic and graph context within a token budget
builder.buildbuild(options: { threadId; agentId; userId?; systemPrompt?; currentInput? }): Promise<BuiltContext>Messages plus metadata
countTokenscountTokens(text: string): numberToken estimate
countMessageTokens, countMessagesTokens(message: Message), (messages: Message[])Token estimates for messages
truncateToTokenstruncateToTokens(text: string, maxTokens: number): stringCut text to a token budget

ContextBuilderConfig is { maxTokens, strategy: 'recent' | 'relevant' | 'hybrid', reserveTokens?, includeSystemPrompt?, includeFacts?, includeSemanticContext?, includeGraphContext?, graphContextOptions? }; ContextBuilderDeps is { memoryAdapter, factAdapter?, embeddingAdapter?, embeddingService?, graphContextBuilder? }.

Core Facts, Sessions, Compaction

ExportSignaturePurpose
CoreFactsStorenew CoreFactsStore(config: { path: string } | { db }) — initialize, set, get, getAll, delete, getHistory, formatForPrompt, closeKey-value facts about a user in SQLite, with history
SessionManagernew SessionManager(adapter: MemoryAdapter, options?: { compaction?: CompactionService }) — getOrCreate, get, update, archive, list, delete, incrementMessageCount, compactChannel sessions per user and channel
CompactionServicenew CompactionService(config: { adapter: MemoryAdapter; summarize: SummarizeFn }) — compact(sessionId, config), applySummary(…)Replace old entries with a summary

SummarizeFn is (messages: Message[], options?: SummarizeOptions) => Promise<string>, where SummarizeOptions is { model?: string; prompt?: string }, filled from summaryModel / summaryPrompt of the CompactionConfig passed to compact().

Knowledge Graphs

ExportSignaturePurpose
PostgresGraphAdapternew PostgresGraphAdapter(config: { pool; schema?; vectorDimensions? }) — call initialize()GraphAdapter on Postgres (pass a pg pool)
SQLiteGraphAdapternew SQLiteGraphAdapter(config: { path: string; walMode?: boolean }) — initialize(), close()GraphAdapter on SQLite
LLMEntityExtractornew LLMEntityExtractor(backend: LLMBackend, config: { model: string; minConfidence?; maxEntitiesPerText?; maxRelationsPerText? }) or new LLMEntityExtractor(backend: LLMBackendMinimal, config?: { model?; minConfidence?; maxEntitiesPerText?; maxRelationsPerText? }) — extract(text, context?), extractBatchEntities and relations from text
GraphInferenceEnginenew GraphInferenceEngine(graphAdapter: GraphAdapter, useDefaultRules?: boolean) — registerRule, removeRule, getRules, enableRule, disableRule, infer(agentId, options?), materialize(edges)Rule-based edge inference
GraphContextBuildernew 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.

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;
}

interface MemoryEntry {
  id: string;
  threadId: string;
  message: Message;
  toolCalls?: ToolCall[];
  toolResults?: ToolResult[];
  tokenCount: number;
  createdAt: Date;
  metadata?: Record<string, unknown>;
}

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
}

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>;
}

Also re-exported: the adapter configs, MemoryQueryOptions, SemanticSearchOptions, SearchOptions, SearchFilter, HybridSearchConfig, ContextBuilderConfig, BuiltContext, MemoryConfig, the graph types (GraphNode, GraphEdge, TraversalOptions, InferenceRule, …) and the session types (Session, SessionFilter, CompactionConfig, CompactionResult; the interface is exported as ISessionManager).

On this page