npm package: @seizn/memory-sdk
Description: Official JavaScript/TypeScript SDK for Seizn Memory API
Author: Seizn
Latest version: 0.1.0

# @seizn/memory-sdk

Official JavaScript/TypeScript SDK for the Seizn Memory API. Store, search, and manage AI memories with semantic search capabilities.

## Installation

```bash
npm install @seizn/memory-sdk
```

```bash
yarn add @seizn/memory-sdk
```

```bash
pnpm add @seizn/memory-sdk
```

## Quick Start

```typescript
import { SeizinClient } from '@seizn/memory-sdk';

// Initialize the client
const client = new SeizinClient({
  apiKey: 'your-api-key',
});

// Add a memory
const memory = await client.add('User prefers dark mode for all applications', {
  memory_type: 'preference',
  namespace: 'user-settings',
});

// Search for relevant memories
const results = await client.search('dark mode preference');
console.log(results);

// Get a specific memory
const retrieved = await client.get(memory.id);

// Update a memory
await client.update(memory.id, {
  content: 'User prefers dark mode with high contrast',
});

// Delete a memory
await client.delete(memory.id);
```

## Configuration

```typescript
const client = new SeizinClient({
  // Required: Your Seizn API key
  apiKey: 'szn_your_api_key',

  // Optional: Custom API base URL (default: https://seizn.com/api)
  baseUrl: 'https://seizn.com/api',

  // Optional: Request timeout in milliseconds (default: 30000)
  timeout: 30000,

  // Optional: Default namespace for all operations
  defaultNamespace: 'my-app',

  // Optional: Number of retry attempts (default: 3)
  maxRetries: 3,

  // Optional: Custom headers
  headers: {
    'X-Custom-Header': 'value',
  },
});
```

## API Reference

### Memory Operations

#### `add(content, options?)`

Add a new memory to the store.

```typescript
const memory = await client.add('Important project decision: use TypeScript', {
  memory_type: 'fact',        // 'fact' | 'preference' | 'experience' | 'relationship' | 'instruction'
  namespace: 'project-notes',
  metadata: {
    project: 'seizn-sdk',
    date: '2024-01-15',
  },
});
```

#### `search(query, options?)`

Search for memories using semantic similarity.

```typescript
const results = await client.search('TypeScript decisions', {
  limit: 10,                  // Maximum results (default: 10)
  threshold: 0.7,             // Minimum similarity (0-1, default: 0.7)
  namespace: 'project-notes',
  memory_type: 'fact',
  metadata_filter: {
    project: 'seizn-sdk',
  },
});

// Results include similarity scores
results.forEach(result => {
  console.log(`${result.content} (${result.similarity.toFixed(2)})`);
});
```

#### `get(id)`

Retrieve a specific memory by ID.

```typescript
const memory = await client.get('mem_abc123');
```

#### `update(id, options)`

Update an existing memory.

```typescript
const updated = await client.update('mem_abc123', {
  content: 'Updated content',
  memory_type: 'instruction',
  metadata: { updated: true },
});
```

#### `delete(id)`

Delete a memory by ID.

```typescript
await client.delete('mem_abc123');
```

#### `list(options?)`

List memories with pagination and filtering.

```typescript
const { data, pagination } = await client.list({
  limit: 20,
  page: 1,
  namespace: 'project-notes',
  memory_type: 'fact',
  sort_by: 'created_at',
  sort_order: 'desc',
});

console.log(`Page ${pagination.page} of ${pagination.total_pages}`);
```

### Namespace Operations

#### `namespace(name)`

Create a namespaced client for scoped operations.

```typescript
const projectNotes = client.namespace('project-notes');

// All operations are scoped to this namespace
await projectNotes.add('Note content');
const results = await projectNotes.search('query');
await projectNotes.clear(); // Delete all memories in namespace
```

#### `listNamespaces()`

List all namespaces.

```typescript
const namespaces = await client.listNamespaces();
namespaces.forEach(ns => {
  console.log(`${ns.name}: ${ns.memory_count} memories`);
});
```

#### `clearNamespace(name)`

Delete all memories in a namespace.

```typescript
const { deleted_count } = await client.clearNamespace('old-project');
console.log(`Deleted ${deleted_count} memories`);
```

### Batch Operations

#### `addMany(memories)`

Add multiple memories at once.

```typescript
const memories = await client.addMany([
  { content: 'First memory', options: { memory_type: 'fact' } },
  { content: 'Second memory', options: { memory_type: 'preference' } },
]);
```

#### `deleteMany(ids)`

Delete multiple memories at once.

```typescript
const { deleted_count } = await client.deleteMany([
  'mem_abc123',
  'mem_def456',
]);
```

### Event Handling

Subscribe to client events for logging, monitoring, or debugging.

```typescript
// Subscribe to events
const unsubscribe = client.on('request', (event) => {
  console.log('Request:', event.config.method, event.config.path);
});

client.on('response', (event) => {
  console.log(`Response: ${event.status} (${event.duration}ms)`);
});

client.on('error', (event) => {
  console.error('Error:', event.error.message);
});

client.on('retry', (event) => {
  console.log(`Retrying (${event.attempt}/${event.maxRetries})`);
});

// Unsubscribe when done
unsubscribe();
```

## Error Handling

The SDK provides specific error classes for different failure scenarios.

```typescript
import {
  SeizinClient,
  SeiznError,
  AuthenticationError,
  ValidationError,
  NotFoundError,
  RateLimitError,
  isSeizinError,
} from '@seizn/memory-sdk';

try {
  await client.add('');
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation failed:', error.message);
  } else if (error instanceof AuthenticationError) {
    console.error('Check your API key');
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after ${error.retryAfter} seconds`);
  } else if (error instanceof NotFoundError) {
    console.error(`${error.resourceType} not found: ${error.resourceId}`);
  } else if (isSeizinError(error)) {
    console.error(`Seizn error (${error.code}): ${error.message}`);
  }
}
```

### Error Classes

| Error Class | Status Code | Description |
|-------------|-------------|-------------|
| `AuthenticationError` | 401 | Invalid API key |
| `ValidationError` | 400 | Invalid request parameters |
| `NotFoundError` | 404 | Resource not found |
| `RateLimitError` | 429 | Rate limit exceeded |
| `ForbiddenError` | 403 | Access denied |
| `QuotaExceededError` | 402 | Usage quota exceeded |
| `ServerError` | 5xx | Server-side error |
| `TimeoutError` | - | Request timeout |
| `NetworkError` | - | Network failure |
| `ConfigurationError` | - | Invalid configuration |

## Memory Types

| Type | Description | Use Cases |
|------|-------------|-----------|
| `fact` | Objective facts, project information | Project configs, API keys location, tech stack |
| `preference` | User preferences | UI preferences, coding style, tools |
| `experience` | Experiences, events, achievements | Milestones, completed tasks, lessons learned |
| `relationship` | Relationship information | Team members, collaborators, contacts |
| `instruction` | Instructions, rules | Coding guidelines, workflow rules |

## TypeScript Support

This SDK is written in TypeScript and provides full type definitions.

```typescript
import type {
  Memory,
  MemoryType,
  AddOptions,
  SearchOptions,
  SearchResult,
  PaginatedResponse,
} from '@seizn/memory-sdk';
```

## Environment Support

- Node.js >= 18.0.0
- Modern browsers (Chrome, Firefox, Safari, Edge)
- Cloudflare Workers
- Deno
- Bun

## License

MIT