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; see Installation)

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);
// Browse without vector search
const page = await client.listMemories({ limit: 20, tag: "auth" });

Temporal Recall

Filter and order by when events happened rather than when memories were stored:

const timeline = await client.recall("production incidents", {
eventAfter: new Date("2026-09-01"),
eventBefore: new Date("2026-09-30"),
timeOrder: "asc",
});

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}`);
}
// Adjust or remove an edge
await client.updateAssociation("mem-problem-123", association.id, { strength: 0.95 });
await client.deleteAssociation("mem-problem-123", association.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();

Checkpoints and Context Packs

Checkpoints capture raw transcript segments for recovery after context compaction. A context pack is a budgeted summary for resuming a session. A delta returns only what changed since the pack’s cursor:

import { createHash } from "node:crypto";
const segment = "user: fix the login bug\nassistant: looking at auth.ts...";
await client.createCheckpoint(session.id, {
transcriptSegment: segment,
contentHash: createHash("sha256").update(segment).digest("hex"),
idempotencyKey: "turn-42",
});
const pack = await client.getContextPack(session.id, { topic: "login bug", budgetTokens: 1500 });
console.log(pack.rendered);
const delta = await client.getContextDelta(session.id, pack.cursor);

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 (optional settings and discovery tags)
const workspace = await client.createWorkspace("My Project", {}, ["knowledge"]);
// Get workspace details
const workspace = await client.getWorkspace("ws-123");
// List all workspaces, or filter by tag
const workspaces = await client.listWorkspaces();
const knowledge = await client.listWorkspaces({ tags: ["knowledge"], match: "any" });
// 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

The server expects flat operations keyed by op. The 0.2.0 BatchOperation type nests fields differently, so cast the array (see batchMemories()):

import type { BatchOperation } from "@scitrera/memorylayer-sdk";
const result = await client.batchMemories([
{ op: "create", content: "Memory 1", importance: 0.7 },
{ op: "create", content: "Memory 2", importance: 0.8 },
{ op: "update", memory_id: "mem-123", importance: 0.9 },
{ op: "delete", memory_id: "mem-old", hard: false },
] as unknown as BatchOperation[]);
console.log(`Successful: ${result.successful}, Failed: ${result.failed}`);

Entities

When the server’s entity registry is enabled:

const { entities } = await client.listEntities({ limit: 50 });
const { resolution } = await client.resolveEntity("Bob", { entityType: "person" });
console.log(resolution.entity.canonical_name, resolution.matched_via);
const survivor = await client.mergeEntities({
sourceId: "ent_dup",
targetId: "ent_main",
reason: "same person",
});

On-Behalf-Of Requests

const alice = client.actingFor({
grantId: "grant_abc",
subject: { type: "user", id: "alice" },
});
await alice.remember("Alice prefers dark mode");
const prefs = await alice.recall("UI preferences");

See Authority Headers for details.

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`);
// Rename, list, and delete threads
await client.updateThread(thread.id, { title: "Auth bug fix" });
const threads = await client.listUserThreads("user-123");
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) {
// Server returned 501: the feature needs MemoryLayer Enterprise
console.error(`${error.feature} is not available on this server`);
} else if (error instanceof MemoryLayerError) {
console.error(`Error ${error.statusCode}: ${error.message}`);
}
}