JavaScript SDK
@smartmemory/sdk-js is the official JavaScript / TypeScript client for the
SmartMemory REST API. It bundles auth (Clerk + API key + cookie SSO), 25 domain
APIs, and a Server-Sent Events subscriber for the progress stream.
Install
npm install @smartmemory/sdk-jsThe package exposes four entry points:
| Import | Use it for |
|---|---|
@smartmemory/sdk-js | Top-level — SmartMemoryClient, all domain APIs |
@smartmemory/sdk-js/core | Framework-agnostic auth + APIs (no React) |
@smartmemory/sdk-js/react | React hooks + provider |
@smartmemory/sdk-js/progress | SSE subscriber for /memory/progress/stream |
Quick start
import { SmartMemoryClient } from '@smartmemory/sdk-js';
const client = new SmartMemoryClient({
mode: 'apiKey',
apiBaseUrl: 'https://api.smartmemory.ai',
apiKey: 'sm_live_...',
});
// Add a memory
const { item_id } = await client.memories.create({
content: 'Project Atlas kicks off Monday.',
memoryType: 'semantic',
});
// Search
const { results } = await client.memories.search('atlas kickoff', { topK: 5 });
// Switch active workspace
client.setTeamId('team_42');Auth modes
AuthCore supports three modes, selected by the mode field:
// 1) API key — server-to-server, no token refresh
new SmartMemoryClient({
mode: 'apiKey',
apiBaseUrl: 'https://api.smartmemory.ai',
apiKey: process.env.SMARTMEMORY_API_KEY,
});
// 2) Clerk — exchanges Clerk JWT for SmartMemory access/refresh tokens
new SmartMemoryClient({
mode: 'clerk',
apiBaseUrl: 'https://api.smartmemory.ai',
endpoints: { refresh: '/auth/refresh' },
});
// 3) SSO with cookie auth — for first-party frontends sharing a cookie domain
new SmartMemoryClient({
mode: 'sso',
apiBaseUrl: 'https://api.smartmemory.ai',
webAppUrl: 'https://app.smartmemory.ai',
useCookieAuth: true,
});In apiKey mode the key is sent as Authorization: Bearer <key>. In clerk /
sso modes, RefreshManager automatically rotates the access token before
expiry. The SDK also forwards the active workspace id as the
X-Workspace-Id header — pulled from tokenManager.getTeamId().
Core memory operations
client.memories (an instance of MemoryAPI) is the main surface for memory
CRUD, search, and ingestion:
// Full pipeline ingestion (entity extraction, enrichment, grounding, evolution)
await client.memories.ingest('Atlas ships in Q3, owned by Priya.', {
profileName: null,
extractorName: 'llm',
});
// Simple add (no pipeline) — use for derived/internal items
await client.memories.create({ content: '...', usePipeline: false });
// Search variants
await client.memories.search('atlas', { topK: 5 });
await client.memories.searchAdvanced('atlas dependencies', {
algorithm: 'query_traversal',
maxResults: 15,
useSSG: true,
});
await client.memories.searchByMetadata('project', 'atlas');
// CRUD
await client.memories.get(itemId);
await client.memories.update(itemId, { content: 'new text', metadata: { tag: 'q3' } });
await client.memories.delete(itemId);
await client.memories.list({ limit: 50, offset: 0, type: 'semantic' });
// Conversation / document ingestion
await client.memories.ingestConversation(turns, { conversationId: 'abc' });
await client.memories.ingestDocument(text, { title: 'Atlas charter' });
// Working context — anchor-aware token-budgeted recall
await client.memories.getWorkingContext(sessionId, 'why did we pick FalkorDB?', {
k: 20,
maxTokens: 4000,
});
// Feedback (Hebbian co-retrieval)
await client.memories.feedback([id1, id2, id3], 'helpful', 'atlas owner?');Domain APIs
Every property on SmartMemoryClient is a thin wrapper over BaseAPI:
| Property | Surface |
|---|---|
memories | Memory CRUD, search, ingestion, lineage, links |
decisions | Decisions lifecycle (create / supersede / contradict) |
graph | Graph reads + Cypher path / neighbour queries |
temporal | Time-travel queries, history, rollback |
pipeline | Pipeline run status, logs |
archive | Conversation archive store / retrieve |
analytics | Bias / topic analytics |
governance | Governance analyses + summaries |
evolution | Manual evolver triggers |
reasoning / reasoningTraces | Reasoning items + recorded traces |
ontology | Ontology read/write |
validation | Schema validation |
procedureMatches / procedureCandidates / procedureDrift | CFS-2/CFS-4 surfaces |
summaries | /memory/summary/* snapshots |
zettelkasten | Zettel links |
agents | Agentic memory profiles |
teams / profiles / subscriptions / usage / tokenUsage | Account surfaces |
insights | Insights dashboards |
authAPI | /auth/* endpoints (login, me, refresh) |
Progress streaming (SSE)
The progress event bus (PLAT-PROGRESS-1) is consumed via the dedicated
/progress subpath. Native EventSource cannot attach custom headers, so the
SDK uses @microsoft/fetch-event-source under the hood.
import { subscribeProgress } from '@smartmemory/sdk-js/progress';
const sub = subscribeProgress({
baseUrl: 'https://api.smartmemory.ai',
token: accessToken,
workspaceId: 'team_42',
// Optional: replay a specific run from sequence 0
// runId: 'run_abc',
// fromSeq: 0,
onEvent: (e) => {
console.log(`[${e.kind}] seq=${e.seq} status=${e.status}`, e.payload);
},
onReconnect: () => console.warn('reconnecting…'),
onError: (err) => console.error('SSE dead', err),
});
// Tear down
sub.close();Three modes are supported:
- Live — no
runId/since→ drip feed of events for the active workspace. - Run replay —
runId+fromSeq=0→ the full event log for a single run. - Scope resume —
since=<redis-stream-id>→ resume after a transient drop.
The subscriber automatically retries up to 3 consecutive failures with
linear-backoff (RETRY_INTERVAL_MS * consecutiveFailures) before calling
onError.
React integration
import {
SmartMemoryProvider,
useSmartMemory,
useAuth,
AuthWrapper,
} from '@smartmemory/sdk-js/react';
function App() {
return (
<SmartMemoryProvider config={{ mode: 'sso', apiBaseUrl: '/api' }}>
<AuthWrapper>
<Dashboard />
</AuthWrapper>
</SmartMemoryProvider>
);
}
function Dashboard() {
const client = useSmartMemory();
const { user, isAuthenticated } = useAuth();
// ...
}AuthWrapper handles bootstrap (AuthCore.bootstrapSession()) and renders the
login flow when unauthenticated. useAuth exposes the auth state plus the
familiar action helpers (logout, refreshToken, setTeamId).
Error handling
All API methods reject with an APIError carrying status and detail
fields:
import { APIError } from '@smartmemory/sdk-js';
try {
await client.memories.get('does-not-exist');
} catch (e) {
if (e instanceof APIError && e.status === 404) {
// ...
}
throw e;
}See also
smart-memory-sdk-js/src/api/MemoryAPI.js— every memory methodsmart-memory-sdk-js/src/auth/AuthCore.js— auth orchestrationsmart-memory-sdk-js/src/progress.ts— SSE wire format- Authentication & multi-tenancy