npm package: @metamemory/sdk
Description: Official TypeScript SDK for MetaMemory - An intelligent memory system with meta-learning capabilities for AI agents
Author: MetaMemory Team
Latest version: 1.0.0

# MetaMemory TypeScript SDK

[![npm version](https://img.shields.io/npm/v/@metamemory/sdk.svg)](https://www.npmjs.com/package/@metamemory/sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
[![Test Coverage](https://img.shields.io/badge/coverage-91.33%25-brightgreen.svg)](./KNOWN_ISSUES.md)

Official TypeScript SDK for [MetaMemory](https://github.com/metamemoryai/metamemory) - An intelligent memory system with meta-learning capabilities for AI agents.

## ✨ Features

- 🎯 **Dual Mode Support**: HTTP Client or Local Engine
- 🔍 **Advanced Search**: Semantic, temporal, emotional, and hybrid strategies
- 🧠 **Meta-Learning**: Automatic pattern recognition and strategy optimization
- 📦 **Batch Operations**: Efficient bulk memory management
- 🔄 **Retry Logic**: Built-in exponential backoff
- 🛡️ **Type-Safe**: Full TypeScript support with 100% type coverage
- ✅ **Well-Tested**: 91%+ test coverage with 261 passing tests
- 🌳 **Tree-Shakeable**: Import only what you need

## 📦 Installation

```bash
npm install @metamemory/sdk
# or
yarn add @metamemory/sdk
# or
pnpm add @metamemory/sdk
```

## 🚀 Quick Start

### HTTP Client Mode

Perfect for production deployments with a hosted MetaMemory API.

```typescript
import { MetaMemoryClient } from '@metamemory/sdk';

const client = new MetaMemoryClient({
  mode: 'http',
  apiKey: 'your-api-key',
  baseUrl: 'https://api.metamemory.tech',
  timeout: 30000,
  retries: 3,
});

// Create a memory
const memory = await client.createMemory({
  content: 'Important meeting notes from Q4 planning',
  userId: 'user-123',
  metadata: { category: 'work', priority: 'high' },
  emotionalTags: [{ emotion: 'excitement', intensity: 0.8 }],
});

// Search memories
const results = await client.searchMemories({
  query: 'Q4 planning',
  strategy: 'semantic',
  topK: 10,
  minSimilarity: 0.7,
});
```

### Local Engine Mode

Perfect for development or when you need direct database access.

```typescript
import { MetaMemoryEngine } from '@metamemory/sdk';

const engine = new MetaMemoryEngine({
  mode: 'local',
  database: {
    url: process.env.DATABASE_URL,
    maxConnections: 10,
  },
  openai: {
    apiKey: process.env.OPENAI_API_KEY,
    embeddingModel: 'text-embedding-3-large',
    embeddingDimensions: 2048,
  },
  pinecone: {
    apiKey: process.env.PINECONE_API_KEY,
    environment: 'us-west1-gcp',
    indexName: 'metamemory',
  },
  redis: {
    url: process.env.REDIS_URL,
  },
});

await engine.initialize();

// Same API as HTTP client
const memory = await engine.createMemory({...});
const results = await engine.searchMemories({...});

await engine.shutdown(); // Clean up resources
```

## 📚 Core Concepts

### Memory Operations

```typescript
// Create
const memory = await client.createMemory({
  content: 'Meeting notes',
  userId: 'user-123',
  metadata: { project: 'alpha' },
});

// Read
const retrieved = await client.getMemory(memory.id);

// Update
const updated = await client.updateMemory(memory.id, {
  content: 'Updated meeting notes',
  metadata: { project: 'alpha', status: 'reviewed' },
});

// Delete
await client.deleteMemory(memory.id);

// Batch operations
const memories = await client.batchCreateMemories([
  { content: 'Memory 1', userId: 'user-123' },
  { content: 'Memory 2', userId: 'user-123' },
]);
```

### Search Strategies

#### 1. Semantic Search (Vector Similarity)

```typescript
const results = await client.searchMemories({
  query: 'project deadlines',
  strategy: 'semantic',
  topK: 10,
  minSimilarity: 0.75,
});
```

#### 2. Temporal Search (Recency-Biased)

```typescript
const results = await client.searchMemories({
  query: 'recent updates',
  strategy: 'temporal',
  topK: 10,
  recencyWeight: 0.8, // Prioritize recent memories
});
```

#### 3. Emotional Search

```typescript
const results = await client.searchMemories({
  query: 'positive feedback',
  strategy: 'emotional',
  topK: 10,
  targetEmotions: ['joy', 'excitement'],
  minIntensity: 0.6,
});
```

#### 4. Hybrid Search (Multi-Strategy)

```typescript
const results = await client.searchMemories({
  query: 'important updates',
  strategy: 'hybrid',
  topK: 10,
  strategies: ['semantic', 'temporal'],
});
```

### Meta-Learning

MetaMemory automatically learns patterns from your memory usage.

```typescript
// Get learned rules
const rules = await client.getRules({ minConfidence: 0.8 });

// Analyze patterns
const analysis = await client.analyzePatterns({ minPatterns: 10 });

// Get strategy recommendations
const recommendation = await client.getStrategyRecommendation({
  query: 'find recent documents',
  metadata: { category: 'research' },
});

// System statistics
const stats = await client.getStatistics();
console.log(`Total memories: ${stats.totalMemories}`);
console.log(`Average search latency: ${stats.averageSearchLatencyMs}ms`);
```

## 📖 API Reference

### MetaMemoryClient / MetaMemoryEngine

Both classes implement the same unified interface (`IMetaMemory`), so you can switch between modes without changing your code.

#### Memory Operations

| Method | Description |
|--------|-------------|
| `createMemory(input)` | Create a single memory |
| `getMemory(id)` | Retrieve memory by ID |
| `updateMemory(id, input)` | Update existing memory |
| `deleteMemory(id)` | Delete a memory |
| `batchCreateMemories(inputs)` | Create multiple memories |
| `batchUpdateMemories(updates)` | Update multiple memories |
| `batchDeleteMemories(ids)` | Delete multiple memories |
| `getRecentMemories(options)` | Get recent memories (paginated) |
| `getMemoryCount(filters)` | Count memories |
| `getMemoriesByEmotion(emotion, options)` | Filter by emotion |

#### Search Operations

| Method | Description |
|--------|-------------|
| `searchMemories(query)` | Search with any strategy |

#### Meta-Learning Operations

| Method | Description |
|--------|-------------|
| `getRules(filters)` | Get learned rules |
| `getMostUsedRules(limit)` | Get most frequently used rules |
| `analyzePatterns(options)` | Analyze memory patterns |
| `getStatistics()` | Get system statistics |
| `cleanup(options)` | Clean up old data |

#### Strategy Recommendations

| Method | Description |
|--------|-------------|
| `getStrategyRecommendation(context)` | Get context-based recommendation |
| `getQueryTypeRecommendation(queryType)` | Get query-type recommendation |
| `getEmotionalRecommendation(emotion)` | Get emotion-based recommendation |

## 🔧 Configuration

### HTTP Client Configuration

```typescript
interface HttpClientConfig {
  mode: 'http';
  apiKey: string;              // Required: Your API key
  baseUrl?: string;            // Optional: Default 'https://api.metamemory.tech'
  timeout?: number;            // Optional: Default 30000ms
  retries?: number;            // Optional: Default 3
  logging?: {
    level?: 'debug' | 'info' | 'warn' | 'error';
    pretty?: boolean;
  };
}
```

### Local Engine Configuration

```typescript
interface LocalEngineConfig {
  mode: 'local';
  database: {
    url: string;               // PostgreSQL connection URL
    maxConnections?: number;   // Optional: Default 10
    logging?: boolean;         // Optional: Default false
  };
  openai: {
    apiKey: string;            // OpenAI API key
    model?: string;            // Optional: Default 'gpt-4'
    embeddingModel?: string;   // Optional: Default 'text-embedding-3-large'
    embeddingDimensions?: number; // Optional: Default 2048
  };
  pinecone: {
    apiKey: string;            // Pinecone API key
    environment: string;       // e.g., 'us-west1-gcp'
    indexName: string;         // Your Pinecone index name
  };
  redis?: {
    url: string;               // Redis connection URL
    ttl?: number;              // Optional: Cache TTL in seconds
  };
  logging?: {
    level?: 'debug' | 'info' | 'warn' | 'error';
    pretty?: boolean;
  };
  debug?: boolean;             // Optional: Enable debug mode
}
```

## 📂 Examples

Check out the [`examples/`](./examples) directory for complete working examples:

- **HTTP Client**
  - [Basic Usage](./examples/http-client/basic-usage.ts)
  - [Advanced Search](./examples/http-client/advanced-search.ts)

- **Local Engine**
  - [Basic Usage](./examples/local-engine/basic-usage.ts)
  - [Configuration Patterns](./examples/local-engine/configuration.ts)

See the [Examples README](./examples/README.md) for setup instructions.

## 🧪 Testing

This SDK has comprehensive test coverage:

- **261 passing tests** (5 intentionally skipped)
- **91.33% code coverage**
- **100% type coverage**

```bash
# Run tests
npm test

# Run tests once
npm run test:run

# With coverage report
npm run test:coverage

# Run integration tests (requires Docker)
docker-compose -f docker-compose.test.yml up -d
npm run test:run -- tests/integration/
```

## 🏗️ Architecture

### Hybrid Design

The SDK supports two modes that share the same API:

```
┌─────────────────────────────────────┐
│      MetaMemory SDK                 │
├─────────────────────────────────────┤
│  ┌──────────────┐  ┌─────────────┐ │
│  │ HTTP Client  │  │Local Engine │ │
│  │   Mode       │  │   Mode      │ │
│  └──────┬───────┘  └──────┬──────┘ │
│         └────────┬─────────┘        │
│                  │                  │
│          ┌───────▼────────┐        │
│          │ Unified API    │        │
│          │ (IMetaMemory)  │        │
│          └────────────────┘        │
├─────────────────────────────────────┤
│    Shared Types & Utilities         │
└─────────────────────────────────────┘
```

### Bundle Sizes

- **HTTP Client**: ~50 KB (tree-shakeable)
- **Local Engine**: ~3 MB (includes metamemory core)
- **Tree-shaking**: Import only what you need

```typescript
// Import specific mode (smaller bundle)
import { MetaMemoryClient } from '@metamemory/sdk/client';
import { MetaMemoryEngine } from '@metamemory/sdk/engine';

// Or import both
import { MetaMemoryClient, MetaMemoryEngine } from '@metamemory/sdk';
```

## 🐛 Known Issues

See [KNOWN_ISSUES.md](./KNOWN_ISSUES.md) for a list of known limitations and their workarounds.

## 🗺️ Roadmap

### v1.0.0 (Current) ✅
- ✅ HTTP Client & Local Engine modes
- ✅ All search strategies
- ✅ Meta-learning capabilities
- ✅ Comprehensive test coverage

### v1.1.0 (Planned)
- [ ] Browser support
- [ ] Streaming responses
- [ ] Request middleware hooks
- [ ] Custom embedding models

### v1.2.0 (Future)
- [ ] React hooks
- [ ] Vue composables
- [ ] Real-time updates (WebSockets)

### v2.0.0 (Future)
- [ ] GraphQL client option
- [ ] Offline support
- [ ] Multi-tenancy

## 🤝 Contributing

We welcome contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.

## 📄 License

MIT License - see [LICENSE](./LICENSE) file for details.

## 🔗 Links

- [MetaMemory Core](https://github.com/metamemoryai/metamemory)
- [Documentation](./docs/)
- [Examples](./examples/)
- [Issue Tracker](https://github.com/metamemoryai/sdk/issues)
- [Changelog](./CHANGELOG.md)

## 💬 Support

- 📧 Email: support@metamemory.tech
- 💬 Discord: [Join our community](https://discord.gg/metamemory)
- 🐛 Issues: [GitHub Issues](https://github.com/metamemoryai/sdk/issues)

---

Made with ❤️ by the MetaMemory team