TypeScript SDK
The official TypeScript/JavaScript client for SharedMemory.
npm install @sharedmemory/sdk
Authenticate with Authorization: Bearer sm_…. Prefer secrets from Settings → API Keys (sm_org_rw_…, sm_proj_rw_…). sm_agent_… keys are created with agent profiles; sm_live_… is returned by sm login.
Quick Start
import { SharedMemory } from '@sharedmemory/sdk';
const memory = new SharedMemory({
apiKey: 'sm_org_rw_...',
volumeId: 'your-project-id',
});
// Store a memory
await memory.remember('The user prefers dark mode');
// Query memories
const result = await memory.query('user preferences');
console.log(result.answer, result.sources);
// Chat (RAG + LLM answer) — the default way to interact
const answer = await memory.chat('What are the user preferences?');
console.log(answer.answer, answer.sources, answer.citations);
Configuration
interface SharedMemoryConfig {
apiKey: string; // Required. Bearer secret (typically sm_org_rw_… / sm_proj_rw_… from dashboard API Keys)
baseUrl?: string; // Default: https://api.sharedmemory.ai
volumeId?: string; // Default project (volume) for all calls
agentName?: string; // Agent name for attribution (default: "sdk-agent")
timeout?: number; // Request timeout in ms (default: 30000)
userId?: string; // Scope memories to a specific user
agentId?: string; // Scope memories to a specific agent
appId?: string; // App identifier for scoping
sessionId?: string; // Default session ID
}
Methods
remember(content, opts?) / add(content, opts?)
Store a memory in the knowledge base. add is a deprecated alias for remember. The pipeline will classify, guard-check, extract entities, and build the graph automatically.
const result = await memory.remember('John works at Acme Corp as CTO', {
memoryType: 'factual', // factual | preference | event | relationship | technical
source: 'onboarding', // free-form source label
volumeId: 'override-id', // override the default volume
});
Returns:
interface MemoryResult {
status: string; // "approved" | "rejected" | "merged"
reason: string; // Why the guard approved/rejected
confidence: number; // 0-1 confidence score
memory_id: string; // UUID of the stored memory
}
query(query, opts?) / search(query, opts?)
Query memories by semantic similarity. search and recall are deprecated aliases for query. Returns matching memories from vector search plus related knowledge graph facts.
const result = await memory.query('What does John do?', {
volumeId: 'override-id',
limit: 10,
rerank: true,
});
Returns:
interface RecallResult {
answer: string;
sources: Array<{
id: string;
content: string;
score: number;
}>;
graph_facts: Array<{
source: string;
type: string;
target: string;
}>;
}
chat(query, opts?)
Ask a question and get an LLM-generated answer grounded in your memories. Uses the full RAG pipeline: retrieval → reranking → LLM generation → citations.
const result = await memory.chat('What does John do at Acme?', {
limit: 10,
dateFrom: '2024-01-01',
});
console.log(result.answer); // LLM-generated answer
console.log(result.sources); // memories used
console.log(result.citations); // verified citations
Returns:
interface ChatResult {
answer: string;
sources: Array<{
memory_id: string;
content: string;
score: number;
memory_type?: string;
category?: string;
}>;
citations: Array<{
source_index: number;
text: string;
}>;
}
get(memoryId)
Retrieve a single memory by ID.
const mem = await memory.get('memory-uuid');
update(memoryId, content)
Update the content of an existing memory.
await memory.update('memory-uuid', 'Updated fact about John');
delete(memoryId)
Delete a memory by ID.
await memory.delete('memory-uuid');
rememberMany(items, opts?)
Store multiple memories in a single batch call.
await memory.rememberMany([
{ content: 'Alice is VP of Engineering' },
{ content: 'Bob manages the frontend team' },
]);
deleteMany(memoryIds, opts?)
Batch delete up to 100 memories in a single request.
const result = await memory.deleteMany(['mem-id-1', 'mem-id-2']);
// { status: 'deleted', deleted: 2, total: 2 }
updateMany(updates, opts?)
Batch update up to 100 memories in a single request. Re-embeds each memory.
const result = await memory.updateMany([
{ memoryId: 'mem-id-1', content: 'Updated fact about Alice' },
{ memoryId: 'mem-id-2', content: 'Updated fact about Bob', metadata: { source: 'hr' } },
]);
// { total: 2, results: [{ memory_id: '...', status: 'updated' }, ...] }
feedback(memoryId, feedback)
Submit feedback on a memory's relevance.
await memory.feedback('memory-uuid', { feedback: 'POSITIVE', feedback_reason: 'Very relevant' });
history(memoryId)
Get the audit trail for a specific memory.
const trail = await memory.history('memory-uuid');
console.log(trail.memory, trail.history, trail.feedback);
getContext(opts?)
Get an optimized context block for LLM prompting.
const ctx = await memory.getContext({ volumeId: 'your-volume-id', templateId: 'conversational' });
console.log(ctx.context);
getEntity(name, opts?)
Get everything SharedMemory knows about a specific entity (person, project, concept).
const entity = await memory.getEntity('John Smith');
console.log(entity.summary);
console.log(entity.facts); // string[]
console.log(entity.relationships); // { entity, type, description? }[]
Returns:
interface Entity {
name: string;
type: string;
summary: string;
facts: string[];
relationships: Array<{
entity: string;
type: string;
description?: string;
}>;
}
searchEntities(query, opts?)
Search entities in the knowledge graph by name.
const entities = await memory.searchEntities('React', { limit: 5 });
Returns: Entity[]
getGraph(opts?)
Get the full knowledge graph for a volume.
const graph = await memory.getGraph();
console.log(graph.entities); // all entities
console.log(graph.relationships); // all relationships
listVolumes()
List all volumes the agent has access to.
const volumes = await memory.listVolumes();
subscribe(opts)
Subscribe to real-time updates via WebSocket. Receive events when memories are added, entities change, or other agents come online.
const sub = memory.subscribe({
volumeId: 'my-volume',
onMemory: (event) => {
console.log('New memory:', event);
},
onActivity: (event) => {
console.log('Activity:', event.title);
},
onPresence: (event) => {
console.log('Agent presence:', event);
},
});
// Later: clean up
sub.close();
Activity event shape:
interface ActivityEvent {
event_id: string;
volume_id: string;
actor_type: string;
actor_id: string;
actor_name: string;
event_type: string;
title: string;
detail: Record<string, any>;
created_at: string;
}
Error Handling
All methods throw on HTTP errors. Wrap calls in try/catch:
try {
await memory.remember('some fact');
} catch (err) {
console.error(err.message); // "HTTP 429" or "content too long"
}
Webhooks
Register persistent HTTP webhooks to receive events when memories are created or flagged.
// Subscribe to webhook events
const hook = await memory.webhookSubscribe({
url: 'https://my-server.com/webhook',
events: ['memory.approved', 'memory.flagged'],
secret: 'my-signing-secret', // optional — HMAC-SHA256 signature
});
// Unsubscribe
await memory.webhookUnsubscribe({ url: 'https://my-server.com/webhook' });
Webhook payloads include an X-SharedMemory-Signature header (HMAC-SHA256 of the body) if a secret was provided. Deliveries are retried up to 3 times with exponential backoff.
Sessions
Track conversation sessions with automatic summarization.
// Start a session
await memory.startSession('session-abc', { volumeId: 'my-vol' });
// ... write memories with sessionId throughout the conversation ...
// End session — auto-summarizes session memories into long-term storage
await memory.endSession('session-abc', { autoSummarize: true });
// Get session details
const session = await memory.getSession('session-abc');
// List sessions
const sessions = await memory.listSessions({ status: 'active', limit: 20 });
Export / Import
Bulk export and import memories for backup or migration.
// Export all memories + graph triples
const data = await memory.exportMemories({ format: 'json', includeGraph: true });
console.log(data.total_memories, data.total_graph_triples);
// Import memories into a volume
await memory.importMemories([
{ content: 'Alice is VP of Engineering', memoryType: 'factual' },
{ content: 'Bob manages frontend', memoryType: 'factual' },
]);
Structured Extraction
Extract structured data from text using predefined JSON schemas.
// Create an extraction schema
await memory.createExtractionSchema({
name: 'person_info',
jsonSchema: {
type: 'object',
properties: {
name: { type: 'string' },
role: { type: 'string' },
company: { type: 'string' },
},
},
});
// List schemas
const schemas = await memory.listExtractionSchemas();
// Extract data from text
const extracted = await memory.extract(
'John Smith is the CTO of Acme Corp',
'schema-id',
);
Agent Management — memory.agents
Manage agent profiles programmatically (requires a user-scoped or org-level key):
// List agents for an org
const agents = await memory.agents.list({ orgId: 'org-id' });
// Create an agent
const { agent, api_key } = await memory.agents.create({
orgId: 'org-id',
projectId: 'project-id',
name: 'my-agent',
systemPrompt: 'You are a helpful assistant.',
});
console.log(api_key); // sm_agent_... — save this!
// Get agent details
const a = await memory.agents.get('agent-id');
// Update an agent
await memory.agents.update('agent-id', { name: 'renamed-agent' });
// Rotate API key
const { api_key: newKey } = await memory.agents.rotateKey('agent-id');
// Delete (deactivate) an agent
await memory.agents.delete('agent-id');
Organization Management — memory.orgs
// List your organizations
const orgs = await memory.orgs.list();
// Get org details
const org = await memory.orgs.get('org-id');
// List org members
const members = await memory.orgs.members('org-id');
// Apply a promo code
await memory.orgs.applyPromo('org-id', 'EARLYBUILDER');
Environment Variables
The TypeScript SDK does not read environment variables — all config is passed via the constructor. For server-side usage, load your env vars and pass them explicitly:
const memory = new SharedMemory({
apiKey: process.env.SHAREDMEMORY_API_KEY!,
baseUrl: process.env.SHAREDMEMORY_API_URL,
volumeId: process.env.SHAREDMEMORY_VOLUME_ID,
});