@kognitivedev/core
v0.2.28
Published
Memory orchestrator and Kognitive registry for AI agents
Maintainers
Readme
@kognitivedev/core
Core package for the Kognitive memory system. Provides domain entities, storage adapters, and orchestrators for managing AI agent memory.
Installation
npm install @kognitivedev/coreOverview
This package provides the foundational building blocks for a persistent memory layer that enables AI agents to remember user information across conversations.
Key Concepts
Memory Scopes
Memories are categorized into three scopes:
| Scope | Description |
|-------|-------------|
| USER_FACT | Persistent user information (preferences, background, interests) |
| USER_STATE | Temporary/changing user states (mood, current activity, recent events) |
| AGENT_HEURISTIC | Agent-specific learned behaviors and interaction patterns |
API Reference
Domain Entities
Memory
Represents a single memory entry.
interface Memory {
id: string;
userId: string;
agentId: string;
scope: MemoryScope; // "USER_FACT" | "USER_STATE" | "AGENT_HEURISTIC"
topicKey?: string | null;
content: string;
baseImportance: number;
deadlineAt?: Date | null;
createdAt: Date;
updatedAt: Date;
isDeleted: boolean;
}ConversationLog
Stores conversation history for memory extraction.
interface ConversationLog {
id: string;
userId: string;
agentId: string;
sessionId: string;
uniqId: string; // Format: `${agentId}_${userId}_${sessionId}`
messages: any[];
processed: boolean;
createdAt: Date;
}MemorySnapshot
Cached memory context for injection into prompts.
interface MemorySnapshot {
id: string;
userId: string;
agentId: string;
systemBlock: string | null;
userContextBlock: string | null;
createdAt: Date;
}Storage Adapter
Implement the StorageAdapter interface to connect to your database:
interface StorageAdapter {
// Conversation logs
getPendingLogs(userId: string, agentId: string, sessionId: string, limit?: number): Promise<ConversationLog[]>;
markLogsProcessed(logIds: string[]): Promise<void>;
logConversation(log: Omit<ConversationLog, "id" | "createdAt" | "processed" | "uniqId">): Promise<void>;
// Memories
getMemories(userId: string, agentId: string): Promise<Memory[]>;
createMemory(memory: Omit<Memory, "id" | "createdAt" | "updatedAt" | "isDeleted">): Promise<void>;
updateMemory(id: string, update: Partial<Memory>): Promise<void>;
deleteMemory(id: string): Promise<void>; // soft delete
// Snapshots
getLatestSnapshot(userId: string, agentId: string): Promise<MemorySnapshot | null>;
saveSnapshot(snapshot: Omit<MemorySnapshot, "id" | "createdAt">): Promise<void>;
// Transactions
runTransaction(cb: (txAdapter: StorageAdapter) => Promise<void>): Promise<void>;
}Agent Adapter
Implement the AgentAdapter interface for LLM-based memory extraction and management:
interface AgentAdapter {
extract(events: any[]): Promise<ExtractionResult>;
manage(candidates: any[], existingMemories: Memory[]): Promise<ManagerResult>;
}ExtractionResult
interface ExtractionResult {
candidates: {
scope: MemoryScope;
topicKey: string;
content: string;
baseImportance: number;
deadlineDays: number | null;
}[];
}ManagerResult
interface ManagerResult {
createOperations: Array<MemoryOperation & { action: "CREATE" }>;
updateOperations: Array<MemoryOperation & { action: "UPDATE" }>;
deleteOperations: Array<MemoryOperation & { action: "DELETE" }>;
}Memory Orchestrators
MemoryOrchestrator (Basic)
Simple orchestrator for processing conversation logs and managing memories.
import { MemoryOrchestrator } from "@kognitivedev/core";
const orchestrator = new MemoryOrchestrator(storageAdapter, agentAdapter);
// Process pending logs and update memories
await orchestrator.runProcessingLoop(userId, agentId, sessionId);EnhancedMemoryOrchestrator (Recommended)
Feature-rich orchestrator with caching, logging, and retry logic.
import {
EnhancedMemoryOrchestrator,
ConsoleLogger,
InMemoryCacheAdapter
} from "@kognitivedev/core";
const orchestrator = new EnhancedMemoryOrchestrator({
storage: storageAdapter,
agent: agentAdapter,
logger: new ConsoleLogger("[MyApp]"),
cache: new InMemoryCacheAdapter(),
cacheTtlSeconds: 120
});
// Process and cache
await orchestrator.runProcessingLoop(userId, agentId, sessionId);
// Get cached snapshot
const snapshot = await orchestrator.getSnapshot(userId, agentId);Utilities
flattenManagerResult
Utility to flatten manager results into a single array of operations.
import { flattenManagerResult } from "@kognitivedev/core";
const operations = flattenManagerResult(manageResult);
// Returns: MemoryOperation[]Logging & Caching
Logger Interface
Implement for custom logging:
interface Logger {
debug(message: string, data?: Record<string, any>): void;
info(message: string, data?: Record<string, any>): void;
warn(message: string, data?: Record<string, any>): void;
error(message: string, error?: Error, data?: Record<string, any>): void;
}ConsoleLogger
Built-in console logger implementation:
const logger = new ConsoleLogger("[MyPrefix]");CacheAdapter Interface
Implement for custom caching:
interface CacheAdapter {
get<T>(key: string): Promise<T | null>;
set<T>(key: string, value: T, ttlSeconds?: number): Promise<void>;
delete(key: string): Promise<void>;
}InMemoryCacheAdapter
Built-in in-memory cache implementation:
const cache = new InMemoryCacheAdapter();Complete Example
import {
EnhancedMemoryOrchestrator,
StorageAdapter,
AgentAdapter,
ConsoleLogger,
InMemoryCacheAdapter
} from "@kognitivedev/core";
// 1. Implement your storage adapter (connect to MongoDB, PostgreSQL, etc.)
const storage: StorageAdapter = {
// ... implement all methods
};
// 2. Implement your agent adapter (LLM-based extraction/management)
const agent: AgentAdapter = {
async extract(events) {
// Use LLM to extract memory candidates from conversation
return { candidates: [] };
},
async manage(candidates, existing) {
// Use LLM to decide create/update/delete operations
return {
createOperations: [],
updateOperations: [],
deleteOperations: []
};
}
};
// 3. Create orchestrator
const orchestrator = new EnhancedMemoryOrchestrator({
storage,
agent,
logger: new ConsoleLogger(),
cache: new InMemoryCacheAdapter(),
cacheTtlSeconds: 60
});
// 4. Process memories after conversations
await orchestrator.runProcessingLoop("user-123", "agent-abc", "session-xyz");
// 5. Get memory snapshot for prompt injection
const snapshot = await orchestrator.getSnapshot("user-123", "agent-abc");
console.log(snapshot?.userContextBlock);
console.log(snapshot?.systemBlock);License
MIT
