Skip to content

TypeScript API Reference

MemoryLayerClient

Constructor

new MemoryLayerClient(config?: ClientConfig)
interface ClientConfig {
baseUrl?: string; // Default: "http://localhost:61001"
apiKey?: string; // Optional API key
workspaceId?: string; // Default workspace
sessionId?: string; // Auto-include in requests
timeout?: number; // Request timeout in ms (default: 30000)
}
const client = new MemoryLayerClient({
baseUrl: "http://localhost:61001",
apiKey: "your-key",
workspaceId: "ws-123",
});

Memory Operations

remember()

Store a new memory.

async remember(content: string, options?: RememberOptions): Promise<Memory>
interface RememberOptions {
workspaceId?: string;
type?: MemoryType | string;
subtype?: MemorySubtype | string;
importance?: number; // 0.0-1.0, default: 0.5
tags?: string[];
metadata?: Record<string, unknown>;
associations?: string[];
contextId?: string;
}
const memory = await client.remember("User prefers TypeScript", {
type: MemoryType.SEMANTIC,
subtype: MemorySubtype.PREFERENCE,
importance: 0.8,
tags: ["preferences"],
});

recall()

Search memories by semantic query.

async recall(query: string, options?: RecallOptions): Promise<RecallResult>
interface RecallOptions {
workspaceId?: string;
types?: (MemoryType | string)[];
subtypes?: (MemorySubtype | string)[];
tags?: string[];
contextId?: string;
mode?: RecallMode | string;
tolerance?: SearchTolerance | string;
limit?: number; // default: 10
minRelevance?: number; // 0.0-1.0
recencyWeight?: number; // 0.0-1.0
includeAssociations?: boolean;
traverseDepth?: number;
maxExpansion?: number;
createdAfter?: Date;
createdBefore?: Date;
conversationContext?: Array<{ role: string; content: string }>;
ragThreshold?: number;
detailLevel?: DetailLevel | "abstract" | "overview" | "full";
}

Returns: RecallResult

interface RecallResult {
memories: Memory[];
mode_used: RecallMode;
search_latency_ms: number;
total_count: number;
query_tokens: number;
query_rewritten?: string;
token_summary?: {
returned: number;
full_would_be: number;
savings_percent: number;
};
}
const result = await client.recall("coding preferences", {
types: [MemoryType.SEMANTIC],
limit: 5,
minRelevance: 0.7,
});

reflect()

Synthesize insights across memories.

async reflect(query: string, options?: ReflectOptions): Promise<ReflectResult>
interface ReflectOptions {
workspaceId?: string;
detailLevel?: DetailLevel | "abstract" | "overview" | "full";
includeSources?: boolean; // default: true
depth?: number; // default: 2
types?: (MemoryType | string)[];
subtypes?: (MemorySubtype | string)[];
tags?: string[];
contextId?: string;
}

Returns: ReflectResult

interface ReflectResult {
reflection: string;
source_memories: string[];
confidence?: number;
tokens_processed: number;
}

getMemory()

async getMemory(memoryId: string): Promise<Memory>

updateMemory()

async updateMemory(
memoryId: string,
updates: Partial<RememberOptions> & { content?: string }
): Promise<Memory>
const updated = await client.updateMemory("mem-123", {
importance: 0.95,
tags: ["critical"],
});

forget()

async forget(memoryId: string, hard?: boolean): Promise<void>
ParameterTypeDefaultDescription
memoryIdstringrequiredMemory ID
hardbooleanfalsetrue for permanent delete

decay()

async decay(memoryId: string, decayRate?: number): Promise<Memory>
ParameterTypeDefaultDescription
memoryIdstringrequiredMemory ID
decayRatenumber0.1Decay rate 0.0-1.0

traceMemory()

async traceMemory(memoryId: string): Promise<Record<string, unknown>>

Returns provenance information including source resource, category membership, and association chain.

batchMemories()

async batchMemories(operations: BatchOperation[]): Promise<BatchResult>
type BatchOperation =
| { op: "create"; memory: RememberOptions & { content: string } }
| { op: "update"; memory_id: string; updates: Partial<RememberOptions> & { content?: string } }
| { op: "delete"; memory_id: string; hard?: boolean };
interface BatchResult {
results: Array<{
index: number;
success: boolean;
memory?: Memory;
error?: string;
}>;
total_processed: number;
successful: number;
failed: number;
}
const result = await client.batchMemories([
{ op: "create", memory: { content: "Memory 1", importance: 0.7 } },
{ op: "delete", memory_id: "mem-old", hard: false },
]);

Association Operations

associate()

Create a relationship between memories.

async associate(
sourceId: string,
targetId: string,
relationship: RelationshipType,
strength?: number
): Promise<Association>
ParameterTypeDefaultDescription
sourceIdstringrequiredSource memory ID
targetIdstringrequiredTarget memory ID
relationshipRelationshipTyperequiredRelationship type string
strengthnumber0.5Strength 0.0-1.0
const assoc = await client.associate(
"mem-123", "mem-456",
RELATIONSHIP_TYPES.SOLVES, 0.9
);

createAssociation()

Create a relationship with full options including metadata.

async createAssociation(options: AssociationCreateOptions): Promise<Association>
interface AssociationCreateOptions {
sourceId: string;
targetId: string;
relationship: string;
strength?: number; // default: 0.5
metadata?: Record<string, unknown>;
}

getAssociations()

async getAssociations(
memoryId: string,
direction?: "outgoing" | "incoming" | "both"
): Promise<Association[]>
ParameterTypeDefaultDescription
memoryIdstringrequiredMemory ID
directionstring"both"Filter direction

traverseGraph()

Traverse the knowledge graph from a starting memory.

async traverseGraph(
startMemoryId: string,
options?: GraphTraverseOptions
): Promise<GraphQueryResult>
interface GraphTraverseOptions {
relationshipTypes?: string[];
relationshipCategories?: RelationshipCategory[];
maxDepth?: number; // default: 3
direction?: "outgoing" | "incoming" | "both"; // default: "both"
minStrength?: number; // default: 0.0
maxPaths?: number; // default: 100
maxNodes?: number; // default: 50
}
interface GraphQueryResult {
paths: GraphPath[];
total_paths: number;
unique_nodes: string[];
query_latency_ms: number;
}
interface GraphPath {
nodes: string[];
edges: Association[];
total_strength: number;
depth: number;
}
const result = await client.traverseGraph("mem-123", {
relationshipTypes: [RELATIONSHIP_TYPES.CAUSES],
maxDepth: 3,
direction: "both",
});

Session Operations

createSession()

async createSession(
options?: SessionCreateOptions,
autoSetSession?: boolean
): Promise<SessionStartResponse>
interface SessionCreateOptions {
sessionId?: string;
workspaceId?: string;
ttlSeconds?: number; // default: 3600
metadata?: Record<string, unknown>;
contextId?: string;
workingMemory?: Record<string, unknown>;
briefing?: boolean; // default: false
briefingOptions?: {
lookbackHours?: number;
detailLevel?: string;
limit?: number;
};
}
interface SessionStartResponse {
session: Session;
briefing?: SessionBriefing;
}
ParameterTypeDefaultDescription
optionsSessionCreateOptions{}Session options
autoSetSessionbooleantrueAuto-set as active session

listSessions()

async listSessions(options?: {
workspaceId?: string;
contextId?: string;
includeExpired?: boolean;
}): Promise<Session[]>

getSession()

async getSession(sessionId: string): Promise<Session>

setSession() / getSessionId() / clearSession()

setSession(sessionId: string): void
getSessionId(): string | undefined
clearSession(): void

These are synchronous helpers that manage the active session ID. When set, the session ID is sent as the X-Session-ID header on all requests.

setWorkingMemory()

async setWorkingMemory(
sessionId: string,
key: string,
value: unknown
): Promise<void>

getWorkingMemory()

async getWorkingMemory(
sessionId: string,
key?: string
): Promise<Record<string, unknown>>

If key is provided, returns only that key’s value. Otherwise returns all working memory.

commitSession()

async commitSession(
sessionId: string,
options?: CommitOptions
): Promise<CommitResponse>
interface CommitOptions {
minImportance?: number; // default: 0.5
deduplicate?: boolean; // default: true
categories?: string[];
maxMemories?: number; // default: 50
}
interface CommitResponse {
session_id: string;
memories_extracted: number;
memories_deduplicated: number;
memories_created: number;
breakdown: Record<string, number>;
extraction_time_ms: number;
}

touchSession()

Extend session TTL.

async touchSession(sessionId: string, ttlSeconds?: number): Promise<Session>

deleteSession()

async deleteSession(sessionId: string): Promise<void>

Workspace Operations

createWorkspace()

async createWorkspace(
name: string,
settings?: Record<string, unknown>
): Promise<Workspace>

getWorkspace()

async getWorkspace(workspaceId?: string): Promise<Workspace>

Uses the client’s default workspaceId if not provided.

listWorkspaces()

async listWorkspaces(): Promise<Workspace[]>

updateWorkspace()

async updateWorkspace(
workspaceId: string,
updates: { name?: string; settings?: Record<string, unknown> }
): Promise<Workspace>

getWorkspaceSchema()

async getWorkspaceSchema(workspaceId?: string): Promise<WorkspaceSchema>
interface WorkspaceSchema {
relationship_types: string[];
memory_subtypes: string[];
can_customize: boolean;
}

createContext()

async createContext(
name: string,
description?: string,
settings?: Record<string, unknown>
): Promise<Context>

Requires workspaceId to be set on the client.

listContexts()

async listContexts(): Promise<Context[]>

Requires workspaceId to be set on the client.

exportWorkspace()

Export workspace memories and associations.

async exportWorkspace(
workspaceId?: string,
options?: { includeAssociations?: boolean; offset?: number; limit?: number }
): Promise<WorkspaceExportData>
interface WorkspaceExportData {
version: string;
exported_at: string;
workspace_id: string;
total_memories: number;
total_associations: number;
memories: Array<Record<string, unknown>>;
associations: Array<Record<string, unknown>>;
}

exportWorkspaceStream()

Export as streaming NDJSON (for large workspaces).

async *exportWorkspaceStream(
workspaceId?: string,
options?: { includeAssociations?: boolean; offset?: number; limit?: number }
): AsyncGenerator<Record<string, unknown>>

Yields: Parsed JSON objects with type field ("header", "memory", "association", "footer").

for await (const line of client.exportWorkspaceStream("ws-123")) {
if (line.type === "memory") {
console.log(line.data.content);
}
}

importWorkspace()

async importWorkspace(
workspaceId: string,
data: WorkspaceExportData
): Promise<WorkspaceImportResult>
interface WorkspaceImportResult {
imported: number;
skipped_duplicates: number;
errors: number;
details: string[];
}

importWorkspaceStream()

Import from raw NDJSON string.

async importWorkspaceStream(
workspaceId: string,
ndjsonBody: string
): Promise<WorkspaceImportResult>

Briefing

getBriefing()

async getBriefing(
optionsOrLookbackHours?: number | {
lookbackMinutes?: number;
detailLevel?: string;
limit?: number;
includeMemories?: boolean;
includeContradictions?: boolean;
},
includeContradictions?: boolean
): Promise<SessionBriefing>

Accepts either an options object (preferred) or legacy positional arguments for backward compatibility.

// Preferred: options object
const briefing = await client.getBriefing({
lookbackMinutes: 120,
detailLevel: "full",
limit: 20,
});
// Legacy: positional arguments
const briefing = await client.getBriefing(24, true);

Chat Thread Operations

createThread()

async createThread(options?: ThreadCreateOptions): Promise<ChatThread>
interface ThreadCreateOptions {
threadId?: string;
workspaceId?: string;
userId?: string;
contextId?: string;
observerId?: string;
subjectId?: string;
title?: string;
metadata?: Record<string, unknown>;
expiresAt?: string; // ISO 8601 timestamp
}

listThreads()

async listThreads(options?: ThreadListOptions): Promise<ChatThread[]>
interface ThreadListOptions {
workspaceId?: string;
userId?: string;
limit?: number; // default: 50
offset?: number;
}

getThread()

async getThread(threadId: string, workspaceId?: string): Promise<ChatThread>

getThreadFull()

Get thread with messages inlined.

async getThreadFull(
threadId: string,
options?: {
workspaceId?: string;
limit?: number;
offset?: number;
order?: "asc" | "desc";
}
): Promise<ThreadWithMessagesResponse>
interface ThreadWithMessagesResponse {
thread: ChatThread;
messages: ChatMessage[];
total_messages: number;
}

deleteThread()

async deleteThread(threadId: string, workspaceId?: string): Promise<void>

appendMessages()

async appendMessages(
threadId: string,
messages: MessageAppendInput[],
workspaceId?: string
): Promise<MessagesAppendResponse>
interface MessageAppendInput {
role: string;
content: string | ChatMessageContent[];
metadata?: Record<string, unknown>;
}
interface MessagesAppendResponse {
messages: ChatMessage[];
thread_id: string;
new_message_count: number;
}

getMessages()

async getMessages(
threadId: string,
options?: {
workspaceId?: string;
limit?: number;
offset?: number;
afterIndex?: number;
order?: "asc" | "desc";
}
): Promise<MessageListResponse>
interface MessageListResponse {
messages: ChatMessage[];
thread_id: string;
total_count: number;
}

decomposeThread()

Trigger memory decomposition for unprocessed messages.

async decomposeThread(
threadId: string,
workspaceId?: string
): Promise<DecomposeResponse>
interface DecomposeResponse {
thread_id: string;
workspace_id: string;
messages_processed: number;
memories_created: number;
from_index: number;
to_index: number;
}

Context Environment Operations

All context environment methods require an active session (call setSession() or createSession() first).

contextExec()

Execute Python code in the session’s sandbox.

async contextExec(code: string, options?: ContextExecOptions): Promise<ContextExecResult>
interface ContextExecOptions {
resultVar?: string;
returnResult?: boolean; // default: true
maxReturnChars?: number;
}
interface ContextExecResult {
output: string;
result?: unknown;
error?: string;
variables_changed: string[];
}

contextInspect()

async contextInspect(options?: ContextInspectOptions): Promise<ContextInspectResult>
interface ContextInspectOptions {
variable?: string;
previewChars?: number;
}
interface ContextInspectResult {
variables: Record<string, { type: string; preview: string }>;
variable_count: number;
}

contextLoad()

Load memories into the sandbox as a variable.

async contextLoad(
varName: string,
query: string,
options?: ContextLoadOptions
): Promise<ContextLoadResult>
interface ContextLoadOptions {
limit?: number;
types?: string[];
tags?: string[];
minRelevance?: number;
includeEmbeddings?: boolean;
}
interface ContextLoadResult {
var: string;
count: number;
query: string;
}

contextInject()

Inject a value into the sandbox state.

async contextInject(
key: string,
value: unknown,
options?: ContextInjectOptions
): Promise<ContextInjectResult>
interface ContextInjectOptions {
parseJson?: boolean;
}
interface ContextInjectResult {
key: string;
type: string;
}

contextQuery()

Send sandbox variables and a prompt to the server-side LLM.

async contextQuery(
prompt: string,
variables: string[],
options?: ContextQueryOptions
): Promise<ContextQueryResult>
interface ContextQueryOptions {
maxContextChars?: number;
resultVar?: string;
}
interface ContextQueryResult {
response: string;
tokens_used: number;
variables_included: string[];
}

contextRlm()

Run a Recursive Language Model (RLM) reasoning loop.

async contextRlm(goal: string, options?: ContextRlmOptions): Promise<ContextRlmResult>
interface ContextRlmOptions {
memoryQuery?: string;
memoryLimit?: number;
maxIterations?: number;
variables?: string[];
resultVar?: string;
detailLevel?: "brief" | "standard" | "detailed";
}
interface ContextRlmResult {
result: string;
iterations: number;
trace: Array<Record<string, unknown>>;
memories_loaded?: number;
}

contextStatus()

async contextStatus(): Promise<ContextStatusResult>
interface ContextStatusResult {
active: boolean;
variable_count: number;
variables: Record<string, string>;
execution_count: number;
memory_bytes?: number;
}

contextCheckpoint()

Checkpoint sandbox state for persistence (enterprise deployments).

async contextCheckpoint(): Promise<void>

contextCleanup()

Clean up and remove the sandbox environment.

async contextCleanup(): Promise<void>

Enums

MemoryType

enum MemoryType {
EPISODIC = "episodic",
SEMANTIC = "semantic",
PROCEDURAL = "procedural",
WORKING = "working",
}

MemorySubtype

enum MemorySubtype {
SOLUTION = "solution",
PROBLEM = "problem",
CODE_PATTERN = "code_pattern",
FIX = "fix",
ERROR = "error",
WORKFLOW = "workflow",
PREFERENCE = "preference",
DECISION = "decision",
PROFILE = "profile",
ENTITY = "entity",
EVENT = "event",
DIRECTIVE = "directive",
INFERENCE = "inference",
}

RecallMode

enum RecallMode {
RAG = "rag", // Active: vector similarity + graph traversal
LLM = "llm", // Deprecated: query rewriting + LLM-driven retrieval
HYBRID = "hybrid", // Deprecated: RAG-first, fall back to LLM
}

LLM and HYBRID are deprecated. Use RAG for recall and the Context Environment with contextRlm() when you need LLM-driven analysis over memories.

SearchTolerance

enum SearchTolerance {
LOOSE = "loose",
MODERATE = "moderate",
STRICT = "strict",
}

DetailLevel

enum DetailLevel {
ABSTRACT = "abstract",
OVERVIEW = "overview",
FULL = "full",
}

RelationshipCategory

enum RelationshipCategory {
CAUSAL = "causal",
SOLUTION = "solution",
CONTEXT = "context",
LEARNING = "learning",
SIMILARITY = "similarity",
WORKFLOW = "workflow",
QUALITY = "quality",
}

RELATIONSHIP_TYPES

type RelationshipType = string;
const RELATIONSHIP_TYPES = {
// Causal
CAUSES: "causes",
TRIGGERS: "triggers",
LEADS_TO: "leads_to",
PREVENTS: "prevents",
// Solution
SOLVES: "solves",
ADDRESSES: "addresses",
ALTERNATIVE_TO: "alternative_to",
IMPROVES: "improves",
// Context
OCCURS_IN: "occurs_in",
APPLIES_TO: "applies_to",
WORKS_WITH: "works_with",
REQUIRES: "requires",
// Learning
BUILDS_ON: "builds_on",
CONTRADICTS: "contradicts",
CONFIRMS: "confirms",
SUPERSEDES: "supersedes",
// Similarity
SIMILAR_TO: "similar_to",
VARIANT_OF: "variant_of",
RELATED_TO: "related_to",
// Workflow
FOLLOWS: "follows",
DEPENDS_ON: "depends_on",
ENABLES: "enables",
BLOCKS: "blocks",
// Quality
EFFECTIVE_FOR: "effective_for",
PREFERRED_OVER: "preferred_over",
DEPRECATED_BY: "deprecated_by",
// Hierarchical
PART_OF: "part_of",
CONTAINS: "contains",
INSTANCE_OF: "instance_of",
SUBTYPE_OF: "subtype_of",
// Temporal
PRECEDES: "precedes",
CONCURRENT_WITH: "concurrent_with",
} as const;

60+ relationship types in 11 categories:

  • Hierarchical: parent_of, child_of, part_of, contains, instance_of, subtype_of
  • Causal: causes, triggers, leads_to, prevents, and more
  • Temporal: precedes, concurrent_with, follows_temporally
  • Similarity: similar_to, variant_of, related_to, analogous_to
  • Learning: builds_on, contradicts, confirms, supersedes, and more
  • Refinement: refines, abstracts, specializes, generalizes
  • Reference: references, referenced_by
  • Solution: solves, addresses, alternative_to, improves, and more
  • Context: occurs_in, applies_to, works_with, requires, and more
  • Workflow: follows, depends_on, enables, blocks, and more
  • Quality: effective_for, preferred_over, deprecated_by, and more

Use getWorkspaceSchema() to list all available relationship types.


Interfaces

Memory

interface Memory {
id: string;
workspace_id: string;
tenant_id: string;
context_id: string;
user_id?: string;
content: string;
content_hash: string;
type: MemoryType;
subtype?: MemorySubtype;
importance: number;
tags: string[];
metadata: Record<string, unknown>;
abstract?: string;
overview?: string;
session_id?: string;
embedding?: number[];
access_count: number;
last_accessed_at?: string;
decay_factor: number;
source_scope?: string;
relevance_score?: number;
boosted_score?: number;
archived_at?: string;
created_at: string;
updated_at: string;
}

Association

interface Association {
id: string;
workspace_id: string;
source_id: string;
target_id: string;
relationship: string;
strength: number;
metadata: Record<string, unknown>;
created_at: string;
}

Session

interface Session {
id: string;
workspace_id: string;
tenant_id: string;
context_id: string;
user_id?: string;
working_memory: Record<string, unknown>;
metadata: Record<string, unknown>;
expires_at: string;
created_at: string;
}

Workspace

interface Workspace {
id: string;
tenant_id: string;
name: string;
settings: Record<string, unknown>;
created_at: string;
updated_at: string;
}

ChatThread

interface ChatThread {
id: string;
workspace_id: string;
tenant_id: string;
user_id?: string;
context_id: string;
observer_id?: string;
subject_id?: string;
title?: string;
metadata: Record<string, unknown>;
message_count: number;
last_decomposed_at?: string;
last_decomposed_index: number;
expires_at?: string;
created_at: string;
updated_at: string;
}

ChatMessage

interface ChatMessage {
id: string;
thread_id: string;
message_index: number;
role: string;
content: string | ChatMessageContent[];
metadata: Record<string, unknown>;
created_at: string;
}
interface ChatMessageContent {
type: string;
text?: string;
data?: Record<string, unknown>;
}

Exceptions

MemoryLayerError // Base error class
├── AuthenticationError // 401 - Invalid API key
├── AuthorizationError // 403 - Access denied
├── NotFoundError // 404 - Resource not found
├── ValidationError // 400/422 - Invalid request (has .details)
├── EnterpriseRequiredError // 501 - Enterprise feature required (has .feature)
└── RateLimitError // 429 - Rate limited

All errors have these properties:

PropertyTypeDescription
messagestringError message
statusCodenumberHTTP status code

ValidationError also has a details property. EnterpriseRequiredError has a feature property.