@aintandem/context-manager-client
v0.1.0
Published
TypeScript client library for Kai Context Manager - hierarchical memory management for AI applications
Maintainers
Readme
Kai Context Manager - TypeScript Client
A TypeScript client library for the Kai Context Manager, providing hierarchical memory management for AI applications built on top of Mem0.
Features
- Full TypeScript Support - Complete type definitions for all API operations
- Hierarchical Organization - Manage organizations, workspaces, projects, and tasks
- Memory Management - CRUD operations and semantic search for memories
- Document Import - Import and chunk documents automatically
- File Synchronization - Track and sync file changes
- Advanced Features:
- Automatic retry with exponential backoff
- Response caching with TTL
- Batch operations with concurrency control
- Structured logging with configurable levels
- Custom error classes for better error handling
Installation
npm install @kai/context-manager-clientOr with yarn:
yarn add @kai/context-manager-clientQuick Start
import { KaiContextClient, LogLevel } from '@kai/context-manager-client';
// Initialize client
const client = new KaiContextClient({
baseUrl: 'http://localhost:8001',
logging: { level: LogLevel.INFO }
});
// Create hierarchy
const org = await client.hierarchy.createOrganization({
name: 'MyCompany',
folder_path: '/orgs/mycompany'
});
const workspace = await client.hierarchy.createWorkspace({
organization_id: org.id,
name: 'Engineering'
});
const project = await client.hierarchy.createProject({
workspace_id: workspace.id,
name: 'API Server'
});
// Add memory
const memory = await client.memory.add({
content: 'The API uses REST architecture with JSON responses',
scope: 'project',
scope_id: project.id,
memory_type: 'knowledge',
tags: ['api', 'architecture']
});
// Search memories
const results = await client.memory.search({
query: 'What architecture does the API use?',
scope: 'project',
scope_id: project.id,
limit: 10
});
console.log(results.results[0].memory);Configuration
import { KaiContextClient, LogLevel } from '@kai/context-manager-client';
const client = new KaiContextClient({
// API endpoint
baseUrl: 'http://localhost:8001',
// Request timeout (ms)
timeout: 30000,
// Logging configuration
logging: {
level: LogLevel.DEBUG, // DEBUG, INFO, WARN, ERROR, NONE
prefix: '[KaiContext]'
},
// Retry configuration
retry: {
maxRetries: 3,
initialDelay: 1000,
maxDelay: 30000,
backoffFactor: 2
},
// Cache configuration
cache: {
enabled: true,
ttl: 60000, // Cache TTL in ms
maxSize: 100 // Max cache entries
},
// Custom headers
headers: {
'X-Custom-Header': 'value'
}
});API Reference
Hierarchy Management
// Organizations
const org = await client.hierarchy.createOrganization({
name: 'MyCompany',
folder_path: '/path/to/org'
});
const orgData = await client.hierarchy.getOrganization(org.id);
// Workspaces
const workspace = await client.hierarchy.createWorkspace({
organization_id: org.id,
name: 'Engineering',
folder_path: '/path/to/workspace'
});
const workspaces = await client.hierarchy.listWorkspaces(org.id);
// Projects
const project = await client.hierarchy.createProject({
workspace_id: workspace.id,
name: 'API Server',
folder_path: '/path/to/project'
});
const projects = await client.hierarchy.listProjects(workspace.id);
// Tasks
const task = await client.hierarchy.createTask({
project_id: project.id,
name: 'Implement authentication',
description: 'Add JWT authentication',
status: 'pending'
});
const taskData = await client.hierarchy.getTask(task.id);
// Get full context
const context = await client.hierarchy.getContext('project', project.id);Memory Operations
// Add memory
const memory = await client.memory.add({
content: 'Important information',
scope: 'project',
scope_id: project.id,
memory_type: 'knowledge',
visibility: 'workspace',
tags: ['important', 'architecture'],
source: {
type: 'file',
file_path: '/docs/architecture.md',
line_start: 10,
line_end: 20
}
});
// Search memories
const results = await client.memory.search({
query: 'authentication implementation',
scope: 'project',
scope_id: project.id,
limit: 10,
include_inherited: true
});
// List memories
const memories = await client.memory.list({
scope: 'project',
scope_id: project.id,
memory_type: 'knowledge',
tags: ['architecture'],
limit: 50
});
// Get specific memory
const memoryData = await client.memory.get(memory.id);
// Update memory
await client.memory.update(memory.id, {
content: 'Updated information'
});
// Delete memory
await client.memory.delete(memory.id);Document Import
// Import single document
const importResult = await client.import.document({
file_path: '/docs/architecture.md',
scope: 'project',
scope_id: project.id,
memory_type: 'documentation',
visibility: 'workspace',
tags: ['docs'],
chunk_content: true
});
// Import folder of documents
const folderResult = await client.import.documentFolder({
folder_path: '/docs',
scope: 'project',
scope_id: project.id,
recursive: true,
file_extensions: ['.md', '.txt'],
tags: ['documentation']
});
// Import spec file (YAML/JSON)
const specResult = await client.import.spec({
file_path: '/config/api-spec.yaml',
scope: 'project',
scope_id: project.id,
memory_type: 'specification'
});
// Import spec folder
const specFolderResult = await client.import.specFolder({
folder_path: '/specs',
scope: 'project',
scope_id: project.id,
recursive: true
});File Synchronization
// Sync single file
const syncResult = await client.sync.file({
file_path: '/docs/architecture.md',
scope: 'project',
scope_id: project.id,
tags: ['docs']
});
// Sync folder
const syncFolderResult = await client.sync.folder({
folder_path: '/docs',
scope: 'project',
scope_id: project.id,
recursive: true,
file_extensions: ['.md', '.txt']
});
// Check sync status (dry run)
const checkResult = await client.sync.check({
folder_path: '/docs',
scope: 'project',
scope_id: project.id,
recursive: true
});
// Cleanup deleted files
const cleanupResult = await client.sync.cleanup({
scope: 'project',
scope_id: project.id,
folder_path: '/docs'
});
// Get sync statistics
const stats = await client.sync.stats();
// List tracked files
const files = await client.sync.files();Helper Functions
Create Full Hierarchy
import { createFullHierarchy } from '@kai/context-manager-client';
const hierarchy = await createFullHierarchy(client, {
organization: {
name: 'MyCompany',
folder_path: '/orgs/mycompany'
},
workspace: {
name: 'Engineering'
},
project: {
name: 'API Server'
},
task: {
name: 'Add authentication',
description: 'Implement JWT auth'
}
});
// Access created entities
console.log(hierarchy.organization.id);
console.log(hierarchy.workspace.id);
console.log(hierarchy.project.id);
console.log(hierarchy.task?.id);Batch Import Files
import { batchImportFiles } from '@kai/context-manager-client';
const result = await batchImportFiles(
client,
{
files: [
'/docs/file1.md',
'/docs/file2.md',
'/docs/file3.md'
],
scope: 'project',
scope_id: project.id,
tags: ['documentation']
},
(completed, total) => {
console.log(`Progress: ${completed}/${total}`);
}
);
console.log(`Imported ${result.successful} files, ${result.failed} failed`);Batch Sync Files
import { batchSyncFiles } from '@kai/context-manager-client';
const result = await batchSyncFiles(
client,
{
files: ['/docs/file1.md', '/docs/file2.md'],
scope: 'project',
scope_id: project.id
},
(completed, total) => {
console.log(`Syncing: ${completed}/${total}`);
}
);
console.log(`Total changes: ${result.total_changes.memories_updated} updated`);Import with Auto Hierarchy
import { importWithAutoHierarchy } from '@kai/context-manager-client';
const result = await importWithAutoHierarchy(
client,
['/docs/file1.md', '/docs/file2.md'],
{
organization: { name: 'MyCompany' },
workspace: { name: 'Engineering' },
project: { name: 'API Server' }
},
(completed, total) => {
console.log(`Progress: ${completed}/${total}`);
}
);
console.log('Hierarchy:', result.hierarchy);
console.log('Import:', result.import);Error Handling
import {
KaiApiError,
NetworkError,
ValidationError,
TimeoutError
} from '@kai/context-manager-client';
try {
await client.memory.add({ /* ... */ });
} catch (error) {
if (error instanceof KaiApiError) {
console.error('API Error:', error.statusCode, error.message);
console.error('Response:', error.response);
} else if (error instanceof NetworkError) {
console.error('Network Error:', error.message);
} else if (error instanceof TimeoutError) {
console.error('Request timed out');
} else if (error instanceof ValidationError) {
console.error('Validation Error:', error.field, error.message);
}
}Advanced Usage
Custom Batch Processing
import { BatchProcessor } from '@kai/context-manager-client';
const batchProcessor = new BatchProcessor({
concurrency: 5,
stopOnError: false
});
const results = await batchProcessor.process(
items,
async (item) => {
// Process item
return await processItem(item);
},
(completed, total) => {
console.log(`Progress: ${completed}/${total}`);
}
);Cache Management
// Clear all cache
client.clearCache();
// Invalidate specific pattern
client.memory['invalidateCache']('/api/memories');
// Change log level at runtime
import { LogLevel } from '@kai/context-manager-client';
client.setLogLevel(LogLevel.DEBUG);Development
# Install dependencies
npm install
# Build
npm run build
# Test
npm test
# Watch mode
npm run test:watch
# Coverage
npm run test:coverage
# Lint
npm run lint
# Format
npm run formatLicense
MIT
Contributing
Contributions are welcome! Please see the main repository for contribution guidelines.
Support
For issues and questions, please visit the GitHub repository.
