npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kognitivedev/core

v0.2.28

Published

Memory orchestrator and Kognitive registry for AI agents

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/core

Overview

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