Skip to content

TypeScript Quick Start

This guide walks through the core operations of the MemoryLayer TypeScript SDK.

Prerequisites

  • Node.js 18+
  • MemoryLayer server running (memorylayer serve)

Install the SDK

Terminal window
npm install @scitrera/memorylayer-sdk

Connect to the Server

import { MemoryLayerClient } from "@scitrera/memorylayer-sdk";
const client = new MemoryLayerClient({
baseUrl: "http://localhost:61001",
apiKey: "your-api-key",
workspaceId: "my-workspace",
});

Remember (Store Memories)

import { MemoryType, MemorySubtype } from "@scitrera/memorylayer-sdk";
// Basic storage
const memory = await client.remember("Fixed authentication bug in login flow");
// With options
const memory = await client.remember(
"Implemented retry logic with exponential backoff",
{
type: MemoryType.PROCEDURAL,
subtype: MemorySubtype.CODE_PATTERN,
importance: 0.9,
tags: ["retry", "error-handling"],
metadata: {
file: "src/api/client.ts",
author: "alice@example.com",
},
contextId: "project-alpha",
}
);

Recall (Search Memories)

import { RecallMode, SearchTolerance, DetailLevel } from "@scitrera/memorylayer-sdk";
// Simple recall
const result = await client.recall("How do we handle retries?");
// Advanced recall with filters
const result = await client.recall("authentication patterns", {
types: [MemoryType.PROCEDURAL, MemoryType.SEMANTIC],
subtypes: [MemorySubtype.CODE_PATTERN],
tags: ["auth"],
limit: 10,
minRelevance: 0.6,
recencyWeight: 0.3,
tolerance: SearchTolerance.MODERATE,
includeAssociations: true,
traverseDepth: 2,
maxExpansion: 20,
mode: RecallMode.RAG,
detailLevel: DetailLevel.FULL,
createdAfter: new Date("2025-01-01"),
});
for (const memory of result.memories) {
console.log(`${memory.content} (score: ${memory.relevance_score})`);
}

Reflect (Synthesize Insights)

const reflection = await client.reflect(
"What patterns have we learned about error handling?",
{
detailLevel: DetailLevel.FULL,
depth: 3,
types: [MemoryType.PROCEDURAL],
includeSources: true,
}
);
console.log(reflection.reflection);
console.log(`Based on ${reflection.source_memories.length} memories`);

Memory Management

// Get a specific memory
const memory = await client.getMemory("mem-123");
// Update a memory
const updated = await client.updateMemory("mem-123", {
content: "Updated content",
importance: 0.95,
tags: ["critical", "security"],
});
// Soft delete (archive)
await client.forget("mem-123");
// Hard delete (permanent)
await client.forget("mem-123", true);
// Apply decay
const decayed = await client.decay("mem-123", 0.1);
// Trace provenance
const trace = await client.traceMemory("mem-123");

Associations (Knowledge Graph)

import { RELATIONSHIP_TYPES } from "@scitrera/memorylayer-sdk";
// Create a relationship
const association = await client.associate(
"mem-problem-123",
"mem-solution-456",
RELATIONSHIP_TYPES.SOLVES,
0.9
);
// Or with full options
const association = await client.createAssociation({
sourceId: "mem-problem-123",
targetId: "mem-solution-456",
relationship: RELATIONSHIP_TYPES.SOLVES,
strength: 0.9,
metadata: { context: "debugging session" },
});
// Get all associations for a memory
const associations = await client.getAssociations("mem-123", "both");
for (const assoc of associations) {
console.log(`${assoc.source_id} --${assoc.relationship}--> ${assoc.target_id}`);
}
// Traverse the knowledge graph
const result = await client.traverseGraph("mem-123", {
relationshipTypes: [RELATIONSHIP_TYPES.CAUSES, RELATIONSHIP_TYPES.LEADS_TO],
maxDepth: 3,
direction: "both",
minStrength: 0.5,
maxPaths: 100,
maxNodes: 50,
});
for (const path of result.paths) {
console.log(`Path (depth ${path.depth}): ${path.nodes.join(" -> ")}`);
}

Session Management

// Create a session (auto-sets as active session)
const { session, briefing } = await client.createSession({
workspaceId: "my-workspace",
ttlSeconds: 3600,
contextId: "project-alpha",
briefing: true,
briefingOptions: {
lookbackHours: 24,
detailLevel: "overview",
},
});
// Session ID is automatically included in subsequent requests
// Or set it manually:
client.setSession(session.id);
// Store working memory
await client.setWorkingMemory(session.id, "current_task", {
description: "Debugging auth",
file: "auth.py",
});
// Retrieve working memory
const memory = await client.getWorkingMemory(session.id, "current_task");
// Retrieve all working memory
const allMemory = await client.getWorkingMemory(session.id);
// Extend session TTL
await client.touchSession(session.id);
// Commit to long-term storage
const commitResult = await client.commitSession(session.id, {
minImportance: 0.5,
deduplicate: true,
maxMemories: 50,
categories: ["decisions", "preferences"],
});
console.log(`Created ${commitResult.memories_created} memories`);
// List sessions
const sessions = await client.listSessions({
workspaceId: "my-workspace",
includeExpired: false,
});
// Delete session
await client.deleteSession(session.id);
// Clear session from client
client.clearSession();

Session Briefing

Get a summary of recent activity:

// With options object
const briefing = await client.getBriefing({
lookbackMinutes: 120,
detailLevel: "full",
limit: 20,
includeMemories: true,
includeContradictions: true,
});
console.log(briefing.workspace_summary);
for (const activity of briefing.recent_activity) {
console.log(`${activity.timestamp}: ${activity.summary}`);
}
// Legacy: with lookback hours
const briefing = await client.getBriefing(24, true);

Workspace Management

// Create a workspace
const workspace = await client.createWorkspace("My Project", {
embedding_model: "text-embedding-3-small",
default_importance: 0.5,
});
// Get workspace details
const workspace = await client.getWorkspace("ws-123");
// List all workspaces
const workspaces = await client.listWorkspaces();
// Update workspace
const updated = await client.updateWorkspace("ws-123", {
name: "New Name",
settings: { key: "value" },
});
// Get workspace schema
const schema = await client.getWorkspaceSchema("ws-123");
console.log(schema.relationship_types);
console.log(schema.memory_subtypes);

Contexts

Contexts provide logical grouping within a workspace:

// Create a context
const context = await client.createContext(
"project-alpha",
"Memories for Project Alpha",
{ custom_setting: true }
);
// List contexts
const contexts = await client.listContexts();

Batch Operations

const result = await client.batchMemories([
{ op: "create", memory: { content: "Memory 1", importance: 0.7 } },
{ op: "create", memory: { content: "Memory 2", importance: 0.8 } },
{ op: "update", memory_id: "mem-123", updates: { importance: 0.9 } },
{ op: "delete", memory_id: "mem-old", hard: false },
]);
console.log(`Successful: ${result.successful}, Failed: ${result.failed}`);

Export and Import

// Export workspace data
const data = await client.exportWorkspace("ws-123", {
includeAssociations: true,
});
console.log(`Exported ${data.total_memories} memories`);
// Stream export for large workspaces
for await (const line of client.exportWorkspaceStream("ws-123")) {
if (line.type === "memory") {
console.log(`Memory: ${line.data.content}`);
}
}
// Import into another workspace
const result = await client.importWorkspace("ws-target", data);
console.log(`Imported ${result.imported} memories`);

Chat Threads

Chat threads store conversation history and can decompose messages into memories:

// Create a thread
const thread = await client.createThread({
userId: "user-123",
title: "Debugging Session",
contextId: "project-alpha",
});
// Append messages
const messages = await client.appendMessages(thread.id, [
{ role: "user", content: "How do I fix the auth bug?" },
{ role: "assistant", content: "Check the token validation logic." },
]);
// Retrieve messages
const msgs = await client.getMessages(thread.id, { limit: 50 });
// Get thread with all messages
const full = await client.getThreadFull(thread.id);
// Decompose messages into memories
const result = await client.decomposeThread(thread.id);
console.log(`Created ${result.memories_created} memories`);
// List and delete threads
const threads = await client.listThreads({ limit: 20 });
await client.deleteThread(thread.id);

Context Environment

The context environment provides a server-side Python sandbox for executing code, querying LLMs, and running autonomous reasoning loops over memories.

Setup

Context environments are session-scoped. Create a session first:

const { session } = await client.createSession({
workspaceId: "my-workspace",
});

Load and Analyze Memories

// Load memories into the sandbox
await client.contextLoad("project_memories", "architecture decisions", {
limit: 50,
minRelevance: 0.5,
});
// Run code against loaded memories
const result = await client.contextExec(`
decisions = [m for m in project_memories if m.get('subtype') == 'decision']
summary = f"Found {len(decisions)} architecture decisions"
`, { resultVar: "summary" });
console.log(result.result);

Query LLM with Sandbox Context

const answer = await client.contextQuery(
"What are the key architecture decisions and their rationale?",
["decisions"]
);
console.log(answer.response);

Inspect Sandbox State

const state = await client.contextInspect();
console.log(state.variables);
const detail = await client.contextInspect({
variable: "decisions",
previewChars: 500,
});

Autonomous Reasoning (RLM)

const result = await client.contextRlm(
"Identify recurring error patterns and recommend fixes",
{
memoryQuery: "errors bugs fixes",
maxIterations: 10,
detailLevel: "standard",
}
);
console.log(result.result);
console.log(`Completed in ${result.iterations} iterations`);

Cleanup

await client.contextCleanup();

Error Handling

import {
MemoryLayerError,
AuthenticationError,
AuthorizationError,
NotFoundError,
ValidationError,
RateLimitError,
EnterpriseRequiredError,
} from "@scitrera/memorylayer-sdk";
try {
await client.getMemory("mem-123");
} catch (error) {
if (error instanceof NotFoundError) {
console.error("Memory not found");
} else if (error instanceof AuthenticationError) {
console.error("Invalid API key");
} else if (error instanceof AuthorizationError) {
console.error("Access denied");
} else if (error instanceof ValidationError) {
console.error("Validation failed:", error.details);
} else if (error instanceof RateLimitError) {
console.error("Rate limited");
} else if (error instanceof EnterpriseRequiredError) {
console.error(`Enterprise feature required: ${error.feature}`);
} else if (error instanceof MemoryLayerError) {
console.error(`Error ${error.statusCode}: ${error.message}`);
}
}