Skip to content

TypeScript API Reference

Reference for @scitrera/memorylayer-sdk 0.2.x. The package is ESM-only and requires Node.js 18+ (or any runtime with a WHATWG fetch).

MemoryLayerClient

Constructor

new MemoryLayerClient(config?: ClientConfig)

ClientConfig:

PropertyTypeDefaultDescription
baseUrlstring"http://localhost:61001"Server URL
apiKeystringundefinedAPI key, sent as Authorization: Bearer <key>
workspaceIdstringundefinedDefault workspace. Sent as the X-Workspace-ID header and used as the fallback workspace_id.
sessionIdstringundefinedActive session ID, sent as the X-Session-ID header
timeoutnumber30000Request timeout in milliseconds
defaultAuthorityAuthorityContextundefinedOn-behalf-of authority applied to every request (see Authority Headers)
maxRetriesnumber3Retries for idempotent requests (GET/HEAD/OPTIONS/PUT/DELETE/PATCH) on 5xx (except 501), 429, and network errors. POST is never retried. 0 disables.
retryBaseDelaynumber500Base delay in ms for exponential backoff (retryBaseDelay * 2^attempt), unless the server sends Retry-After
fetchtypeof fetchglobalThis.fetchCustom fetch implementation, for example to route requests through an Aether transport
import { MemoryLayerClient } from "@scitrera/memorylayer-sdk";
const client = new MemoryLayerClient({
baseUrl: "http://localhost:61001",
apiKey: process.env.MEMORYLAYER_API_KEY,
workspaceId: "my-workspace",
});

Namespaces

PropertyClassSurface
client.skillsSkillsNamespaceSkills
client.mcpServersMcpServersNamespaceMCP server registry
client.kbKnowledgebaseNamespaceKnowledgebase
client.rpgRpgNamespaceRepository Planning Graph

actingFor()

Returns a lightweight OboProxy that sends OBO headers for the given grant and subject on every call. It is synchronous, does not mutate the client, and is safe to use concurrently for different subjects.

actingFor(opts: { grantId: string; subject: { type: string; id: string } }): OboProxy

OboProxy exposes remember(), recall(), reflect(), forWorkspace(workspaceId), and scoped skills and mcpServers namespaces. For other methods, pass authority in the options where they accept it, or use defaultAuthority.

const alice = client.actingFor({ grantId: "g_abc", subject: { type: "user", id: "alice" } });
await alice.forWorkspace("ws_work").recall("preferences");

Memory Operations

remember()

async remember(content: string, options?: RememberOptions): Promise<Memory>

RememberOptions:

PropertyTypeDefaultDescription
typeMemoryType | stringundefinedCognitive memory type
subtypeMemorySubtype | stringundefinedDomain subtype
importancenumber0.5Importance score 0.0-1.0
tagsstring[][]Tags for categorization
metadataRecord<string, unknown>{}Additional metadata
associationsstring[][]Memory IDs to associate with
relationsEntityRelationInput[][]Entity relations to write alongside the memory (requires the server’s entity registry)
contextIdstringundefinedContext within workspace
userIdstringundefinedUser ID to associate
workspaceIdstringclient defaultWorkspace override
authorityAuthorityContextundefinedPer-call OBO authority
const memory = await client.remember("User prefers TypeScript", {
type: MemoryType.SEMANTIC,
subtype: MemorySubtype.PREFERENCE,
importance: 0.8,
tags: ["preferences", "languages"],
});

recall()

async recall(query: string, options?: RecallOptions): Promise<RecallResult>

RecallOptions (omitted properties use server defaults):

PropertyTypeDefaultDescription
types(MemoryType | string)[][]Filter by memory types
subtypes(MemorySubtype | string)[][]Filter by subtypes
tagsstring[][]Filter by tags
contextIdstringundefinedFilter by context
modeRecallMode | stringserver default (rag)Retrieval mode
toleranceSearchTolerance | stringserver defaultSearch precision
limitnumber10Maximum memories
offsetnumberundefinedResults to skip (pagination)
minRelevancenumberundefinedMinimum relevance 0.0-1.0
recencyWeightnumberundefinedRecency weight 0.0-1.0
includeAssociationsbooleanundefinedInclude linked memories
traverseDepthnumberundefinedMulti-hop graph traversal depth
maxExpansionnumberundefinedMax memories via graph expansion
createdAfter / createdBeforeDateundefinedCreation-time bounds
eventAfter / eventBeforeDateundefinedBounds on the memory’s effective event time
timeOrder"asc" | "desc"undefinedOrder by effective event time (omit to rank by relevance)
includeGlobalbooleanundefinedInclude the _global workspace
includeGlobalUserbooleanundefinedInclude the user-scoped _global_user workspace, filtered by userId
conversationContext{ role: string; content: string }[][]Recent conversation turns for query context
ragThresholdnumberundefinedRAG sufficiency threshold for hybrid mode
detailLevelDetailLevel | stringundefined"abstract", "overview", or "full"
userIdstringundefinedFilter by user
budgetTokensnumberundefinedToken budget for returned memories
includeConfidencebooleantrueReturn retrieval_confidence and confidence_reasons
includeRelationsbooleantrueReturn entity relation_paths
workspaceIdstringclient defaultWorkspace override
authorityAuthorityContextundefinedPer-call OBO authority

Returns: RecallResult

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

reflect()

async reflect(query: string, options?: ReflectOptions): Promise<ReflectResult>

ReflectOptions:

PropertyTypeDefaultDescription
detailLevelDetailLevel | stringundefinedLevel of detail
includeSourcesbooleantrueInclude source memory IDs
depthnumber2Association traversal depth
types / subtypes / tagsarrays[]Filters
contextId / userIdstringundefinedFilters
workspaceIdstringclient defaultWorkspace override
authorityAuthorityContextundefinedPer-call OBO authority

Returns: ReflectResult with reflection, source_memories, confidence?, tokens_processed.

getMemory() / updateMemory() / forget() / decay()

async getMemory(memoryId: string): Promise<Memory>
async updateMemory(memoryId: string, updates: Partial<RememberOptions> & { content?: string }): Promise<Memory>
async forget(memoryId: string, hard?: boolean): Promise<void> // hard defaults to false (soft delete)
async decay(memoryId: string, decayRate?: number): Promise<Memory> // decayRate defaults to 0.1

listMemories()

Browse memories ordered by recency (no vector search).

async listMemories(options?: MemoryListOptions): Promise<MemoryListResponse>

MemoryListOptions: limit, offset, type, subtype, tag (a single tag), contextId. Returns { memories, total_count }.

batchMemories()

async batchMemories(operations: BatchOperation[]): Promise<BatchResult>

The array is sent to the server unchanged as { operations }. The server expects flat operations keyed by op:

import type { BatchOperation } from "@scitrera/memorylayer-sdk";
const result = await client.batchMemories([
{ op: "create", content: "Memory 1", importance: 0.7, tags: ["a"] },
{ op: "update", memory_id: "mem_123", importance: 0.9 },
{ op: "delete", memory_id: "mem_old", hard: false },
] as unknown as BatchOperation[]);

Returns: BatchResult with successful, failed, and per-operation results.


Association Operations

associate() / createAssociation()

async associate(sourceId: string, targetId: string, relationship: RelationshipType, strength?: number): Promise<Association>
async createAssociation(options: AssociationCreateOptions): Promise<Association>

AssociationCreateOptions: sourceId, targetId, relationship, strength? (default 0.5), metadata?. RelationshipType is a string. Use the RELATIONSHIP_TYPES constants or any type from the server ontology.

getAssociations()

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

updateAssociation() / deleteAssociation()

async updateAssociation(memoryId: string, associationId: string, updates: AssociationUpdateOptions): Promise<void>
async deleteAssociation(memoryId: string, associationId: string): Promise<void>

AssociationUpdateOptions: strength?, metadata?. memoryId must be one of the edge’s endpoints, or the server returns 404. The relationship type cannot be changed; delete and recreate the edge instead.

traverseGraph()

async traverseGraph(startMemoryId: string, options?: GraphTraverseOptions): Promise<GraphQueryResult>

GraphTraverseOptions:

PropertyTypeDefaultDescription
relationshipTypesstring[]allFilter by relationship types
relationshipCategoriesRelationshipCategory[]allFilter by category
maxDepthnumber3Maximum hops
direction"outgoing" | "incoming" | "both""both"Traversal direction
minStrengthnumber0.0Minimum edge strength
maxPathsnumber100Maximum paths
maxNodesnumber50Maximum nodes

Returns: GraphQueryResult with paths (each with nodes, edges, total_strength, depth), total_paths, unique_nodes, query_latency_ms.


Entity Registry

These methods require the server’s entity registry. If the server returns 501 for it, they throw EnterpriseRequiredError.

async listEntities(options?: EntityListOptions): Promise<EntityListResponse> // { entities, total_count }
async getEntity(entityId: string, workspaceId?: string): Promise<Entity>
async resolveEntity(name: string, options?: EntityResolveOptions): Promise<EntityResolveResponse> // { resolution }
async mergeEntities(options: EntityMergeOptions): Promise<Entity>
  • EntityListOptions: workspaceId?, status? ("active" or "merged"), limit?.
  • EntityResolveOptions: workspaceId?, entityType? (defaults to "person" on the server).
  • EntityMergeOptions: sourceId, targetId, reason, workspaceId?.

resolveEntity() never creates an entity and throws NotFoundError when nothing matches.


API Tokens

async createToken(options: TokenCreateOptions): Promise<ApiTokenWithSecret>
async listTokens(includeRevoked?: boolean): Promise<ApiToken[]>
async getToken(tokenId: string): Promise<ApiToken>
async revokeToken(tokenId: string): Promise<void>
async deleteToken(tokenId: string): Promise<void>

TokenCreateOptions: name, principalType? (default "User"), workspacePatterns? (default ["*"]), scopes? (default ["*"]), expiresInDays?. The plaintext token on ApiTokenWithSecret is only returned at creation time.


Session Operations

createSession()

async createSession(options?: SessionCreateOptions, autoSetSession?: boolean): Promise<SessionStartResponse>

SessionCreateOptions:

PropertyTypeDefaultDescription
sessionIdstringgeneratedClient-provided session ID
workspaceIdstringclient defaultWorkspace (auto-created if needed)
ttlSecondsnumber3600Time to live (60-86400)
metadataRecord<string, unknown>{}Session metadata
contextIdstringundefinedContext (defaults to _default)
workingMemoryRecord<string, unknown>{}Initial working memory
briefingbooleanfalseInclude a briefing in the response
briefingOptions{ lookbackHours?, detailLevel?, limit? }undefinedBriefing options

autoSetSession defaults to true, which makes the new session the active one. Returns { session, briefing? }.

Other session methods

async getSession(sessionId: string): Promise<Session>
async listSessions(options?: { workspaceId?: string; contextId?: string; includeExpired?: boolean }): Promise<Session[]>
async deleteSession(sessionId: string): Promise<void>
async touchSession(sessionId: string): Promise<Session> // extends the TTL
async setWorkingMemory(sessionId: string, key: string, value: unknown): Promise<void>
async getWorkingMemory(sessionId: string, key?: string): Promise<Record<string, unknown>>
async commitSession(sessionId: string, options?: CommitOptions): Promise<CommitResponse>
setSession(sessionId: string): void
getSessionId(): string | undefined
clearSession(): void

CommitOptions: minImportance? (0.5), deduplicate? (true), categories?, maxMemories? (50). CommitResponse has session_id, memories_extracted, memories_deduplicated, memories_created, breakdown, extraction_time_ms.

Checkpoints, context packs, and deltas

Use these for recovery after context compaction. A checkpoint captures a raw transcript segment. A context pack is a budgeted, rendered bundle for resuming a session, and comes with a cursor. getContextDelta() returns only what changed since that cursor.

async createCheckpoint(sessionId: string, input: {
transcriptSegment: string;
contentHash: string; // SHA-256 of the segment
idempotencyKey: string; // scoped to the session
sourceKind?: string; // default "transcript"
sourceSequence?: number;
sourceBoundary?: number;
}): Promise<SessionCheckpoint>
async getCheckpoint(sessionId: string, checkpointId: string): Promise<SessionCheckpoint>
async getContextPack(sessionId: string, options?: ContextPackOptions): Promise<ContextPack>
async getContextDelta(sessionId: string, cursor: string, budgetTokens?: number): Promise<ContextDelta>

ContextPackOptions: topic, entityIds, entityNames, budgetTokens (default 2048), sectionLimits, includeDirectives, includeWorkingMemory, includeRecentActivity, includeContradictions, includeSandboxSummary, includeCheckpointRecovery.

const pack = await client.getContextPack(session.id, { topic: "auth refactor", budgetTokens: 1500 });
console.log(pack.rendered);
const delta = await client.getContextDelta(session.id, pack.cursor);

getBriefing()

async getBriefing(options?: {
lookbackMinutes?: number;
detailLevel?: string;
limit?: number;
includeMemories?: boolean;
includeContradictions?: boolean;
}): Promise<SessionBriefing>
// Legacy form: lookback in hours (default 24), includeContradictions (default true)
async getBriefing(lookbackHours?: number, includeContradictions?: boolean): Promise<SessionBriefing>

Workspace Operations

async createWorkspace(name: string, settings?: Record<string, unknown>, tags?: string[]): Promise<Workspace>
async getWorkspace(workspaceId?: string): Promise<Workspace>
async listWorkspaces(filter?: { tags?: string[]; match?: "any" | "all" }): Promise<Workspace[]>
async updateWorkspace(workspaceId: string, updates: { name?: string; settings?: Record<string, unknown>; tags?: string[] }): Promise<Workspace>
async getWorkspaceSchema(workspaceId?: string): Promise<WorkspaceSchema> // relationship_types, memory_subtypes, can_customize

Contexts

Contexts are created in, and listed from, the client’s configured workspaceId:

async createContext(name: string, description?: string, settings?: Record<string, unknown>): Promise<Context>
async listContexts(): Promise<Context[]>
async deleteContext(contextId: string, workspaceId?: string): Promise<void>

Export and import

async exportWorkspace(workspaceId?: string, options?: { includeAssociations?: boolean; offset?: number; limit?: number }): Promise<WorkspaceExportData>
async *exportWorkspaceStream(workspaceId?: string, options?: { includeAssociations?: boolean; offset?: number; limit?: number }): AsyncGenerator<Record<string, unknown>>
async importWorkspace(workspaceId: string, data: WorkspaceExportData): Promise<WorkspaceImportResult>
async importWorkspaceStream(workspaceId: string, ndjsonBody: string): Promise<WorkspaceImportResult>

exportWorkspaceStream() yields parsed NDJSON lines with a type of "header", "memory", "association", or "footer". Memory and association payloads are under data. The response is read in full before lines are yielded. WorkspaceImportResult has imported, skipped_duplicates, errors, and details.


Chat Thread Operations

async createThread(options?: ThreadCreateOptions): Promise<ChatThread>
async listThreads(options?: ThreadListOptions): Promise<ChatThread[]>
async listUserThreads(userId: string, options?: UserThreadListOptions): Promise<ChatThread[]>
async getThread(threadId: string, workspaceId?: string): Promise<ChatThread>
async getThreadFull(threadId: string, options?: { workspaceId?; limit?; offset?; order?: "asc" | "desc" }): Promise<ThreadWithMessagesResponse>
async updateThread(threadId: string, updates: ThreadUpdateOptions): Promise<ChatThread>
async deleteThread(threadId: string, workspaceId?: string): Promise<void>
async appendMessages(threadId: string, messages: MessageAppendInput[], workspaceId?: string): Promise<MessagesAppendResponse>
async getMessages(threadId: string, options?: { workspaceId?; limit?; offset?; afterIndex?; order? }): Promise<MessageListResponse>
async deleteMessage(threadId: string, messageId: string, workspaceId?: string): Promise<void>
async decomposeThread(threadId: string, workspaceId?: string): Promise<DecomposeResponse>
  • ThreadCreateOptions: workspaceId, userId, contextId, observerId, subjectId, title, metadata, expiresAt (ISO 8601). There is also a threadId option, but the server ignores it because thread IDs are always server-generated.
  • ThreadListOptions: workspaceId, userId, limit, offset.
  • UserThreadListOptions: ownership? ("user" or "workspace"), scopeFilter? ("web" or "office"), limit?, offset?. listUserThreads() lists a user’s threads across all workspaces.
  • ThreadUpdateOptions: title?, metadata?, workspaceId?.
  • MessageAppendInput: role, content (string or ChatMessageContent[]), metadata?.
  • DecomposeResponse: thread_id, workspace_id, messages_processed, memories_created, from_index, to_index.

The TypeScript SDK does not send an ownership field, so threads get the server default ("user").


Context Environment Operations

All context environment methods run in the sandbox of the active session (set sessionId or call createSession() first). See the Context Environment guide.

async contextExec(code: string, options?: { resultVar?; returnResult?; maxReturnChars? }): Promise<ContextExecResult>
async contextInspect(options?: { variable?; previewChars? }): Promise<ContextInspectResult>
async contextLoad(varName: string, query: string, options?: { limit?; types?; tags?; minRelevance?; includeEmbeddings? }): Promise<ContextLoadResult>
async contextInject(key: string, value: unknown, options?: { parseJson? }): Promise<ContextInjectResult>
async contextQuery(prompt: string, variables: string[], options?: { maxContextChars?; resultVar? }): Promise<ContextQueryResult>
async contextRlm(goal: string, options?: { memoryQuery?; memoryLimit?; maxIterations?; variables?; resultVar?; detailLevel? }): Promise<ContextRlmResult>
async contextStatus(): Promise<ContextStatusResult>
async contextCheckpoint(): Promise<void>
async contextCleanup(): Promise<void>

contextRlm() detailLevel is "brief", "standard", or "detailed".


Documents

If the server returns 501 because document ingestion is not available, these methods throw EnterpriseRequiredError.

async uploadDocument(file: Blob | File, filename: string, options?: DocumentUploadOptions): Promise<DocumentUploadResponse>
async listDocuments(options?: { status?: string; limit?: number; offset?: number }): Promise<DocumentListResponse>
async getDocument(documentId: string): Promise<DocumentInfo>
async deleteDocument(documentId: string, deleteMemories?: boolean): Promise<void>
async reprocessDocument(documentId: string, options?: Partial<DocumentUploadOptions>): Promise<JobInfo>
async searchDocumentPages(query: string, options?: { limit?: number; docIds?: string[] }): Promise<PageSearchResponse>
async getDocumentPages(documentId: string): Promise<PageListResponse>
async getPageImage(documentId: string, pageId: string): Promise<Blob>
async getJob(jobId: string): Promise<JobInfo>
async listJobs(options?: { status?: string; limit?: number }): Promise<{ jobs: JobInfo[] }>
async cancelJob(jobId: string): Promise<void>

DocumentUploadOptions: targetContextId, chunkingStrategy, chunkSize, chunkOverlap, importance, retainOriginal. See Document Ingestion.

Datasets

async uploadDataset(file: Blob | File, filename: string, options?: DatasetUploadOptions): Promise<DatasetUploadResponse>
async listDatasets(options?: { status?: string; limit?: number; offset?: number }): Promise<DatasetListResponse>
async getDataset(datasetId: string): Promise<DatasetInfo>
async deleteDataset(datasetId: string, deleteMemories?: boolean): Promise<void>
async getDatasetMemories(datasetId: string): Promise<DatasetMemoriesResponse>
async queryDatasetSlice(datasetId: string, options?: DatasetSliceOptions): Promise<DatasetSliceResult>
async getDatasetJob(jobId: string): Promise<DatasetJobInfo>
async listDatasetJobs(options?: { status?: string; limit?: number }): Promise<{ jobs: DatasetJobInfo[] }>
async cancelDatasetJob(jobId: string): Promise<void>

DatasetUploadOptions: name, targetContextId, importance, sampleRows, detectTimeSeries, generateSummaries. DatasetSliceOptions: sql (SELECT only; the table is named data), columns, filters, orderBy, descending, limit (100), offset (0). See Dataset Management.


Skills (client.skills)

See Skills & MCP Servers.

MethodSignatureReturns
list(options?: SkillListOptions): workspaceId, scope, name, tags, enabled, includeShadowed, authoritySkill[]
get(skillId)Skill
getManifest(skillId)string (rendered SKILL.md)
listFiles / getFile / deleteFile(skillId) / (skillId, filePath) / (skillId, filePath)SkillFile[] / SkillFile / void
save / push(manifest: SkillManifest)Skill (create or update by name)
delete(skillId)void
resolve(options?: { name?, query?, scopeHint?, authority? })Skill | null
pull(skillId){ skill, files }
materialize(targetDir, options?: { workspaceId?, scope?, enabled?, reconcile? })void. Writes each skill’s SKILL.md and files. reconcile: true also prunes stale skill directories. Node.js only.
withAuthority(authority, workspaceId?)scoped SkillsNamespace

parseSkillFolder(dir) (Node.js only) parses a local skill directory into { manifest, files }.

MCP Servers (client.mcpServers)

MethodSignatureReturns
list(options?: McpServerListOptions): workspaceId, userId, name, transport, enabled, limit, offset, authorityMcpServer[]
get(serverId, authority?)McpServer
create(options: McpServerCreateOptions): name, transport, command, args, env, url, headers, description, metadata, source_mode, enabled, workspaceId, userId, authorityMcpServer
update(serverId, options?: McpServerUpdateOptions)McpServer
delete(serverId, authority?)void
resolve(options: { name, workspaceId?, authority? })McpServer | null
import(doc: McpJsonDocument, options?: { workspaceId?, userId?, sourceMode? }, authority?)McpServerImportResult (imported, updated, skipped, errors)
export(options?: { workspaceId? }, authority?)McpJsonDocument (a .mcp.json-shaped { mcpServers }; secrets are masked)
withAuthority(authority, workspaceId?)scoped McpServersNamespace

Knowledgebase (client.kb)

If the server returns 501 for the knowledgebase, these methods throw EnterpriseRequiredError. Each method takes an optional trailing authority argument.

MethodSignatureReturns
get()Knowledgebase
generate(options?: KBGenerateOptions): workspaceId, contextId, includeRpg, maxCommunities, maxGodNodes, regenerateKnowledgebase
listArticles(options?: { articleType?, limit?, offset? })KBArticle[]
getArticle(articleId)KBArticle
exportVault()ArrayBuffer (Obsidian-compatible vault zip)
getGraphAnalysis()GraphAnalysis | null
getCommunity(communityId: number)GraphCommunity
withAuthority(authority)scoped KnowledgebaseNamespace

Repository Planning Graph (client.rpg)

Client for the RPG server plugin (memorylayer-server-rpg). See Repository Planning Graph.

MethodSignature
sync(nodes: RpgNodeInput[], edges: RpgEdgeInput[], options?: { fullSync?, sourceCommit?, contextId?, taskId? })
getSubgraph(options: { path?, nodeId?, depth?, nodeTypes?, relationshipTypes?, contextId?, maxNodes? })
search(query, options?: { nodeTypes?, limit?, contextId? })
getStatus(contextId?)
listOverlays / deleteOverlay() / (contextId)
listNodes(options?: { nodeType?, contextId?, limit? })
deleteNodes / deleteEdges(nodeIds, contextId = "rpg") / (associationIds)
getMergedSubgraph(overlayContext, options?: { baseContext?, path?, depth? })
getConflicts / getSymbolConflicts(taskId) / (taskIdA, taskIdB)
maintenance(operation: RpgMaintenanceOperation)
enrich(options?: { contextId?, phases?, async? })
withAuthority(authority) returns a scoped RpgNamespace

Enums and Constants

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", // Vector similarity search + graph traversal (server default)
LLM = "llm", // LLM-driven retrieval with query rewriting
HYBRID = "hybrid", // RAG first, LLM fallback
}

mode also accepts plain strings. The server additionally defines "agentic", an iterative LLM-controlled retrieval loop provided by MemoryLayer Enterprise.

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

RelationshipType is an alias for string. RELATIONSHIP_TYPES provides constants for common types:

const RELATIONSHIP_TYPES = {
// Causal
CAUSES, TRIGGERS, LEADS_TO, PREVENTS,
// Solution
SOLVES, ADDRESSES, ALTERNATIVE_TO, IMPROVES,
// Context
OCCURS_IN, APPLIES_TO, WORKS_WITH, REQUIRES,
// Learning
BUILDS_ON, CONTRADICTS, CONFIRMS, SUPERSEDES,
// Similarity
SIMILAR_TO, VARIANT_OF, RELATED_TO,
// Workflow
FOLLOWS, DEPENDS_ON, ENABLES, BLOCKS,
// Quality
EFFECTIVE_FOR, PREFERRED_OVER, DEPRECATED_BY,
// Hierarchical
PART_OF, CONTAINS, INSTANCE_OF, SUBTYPE_OF,
// Temporal
PRECEDES, CONCURRENT_WITH,
} as const; // values are the snake_case strings, e.g. SOLVES = "solves"

Use getWorkspaceSchema() to list every relationship type the server supports.


Interfaces

Only the most-used fields are listed. Server responses use snake_case field names.

Memory

interface Memory {
id: string;
workspace_id: string;
tenant_id: string;
context_id: string;
user_id?: string;
session_id?: string;
content: string;
content_hash: string;
type: MemoryType;
subtype?: MemorySubtype;
importance: number;
tags: string[];
metadata: Record<string, unknown>;
abstract?: string;
overview?: string;
access_count: number;
last_accessed_at?: string;
decay_factor: number;
created_at: string;
updated_at: string;
archived_at?: string;
deleted_at?: string;
// Populated on recall results
relevance_score?: number;
boosted_score?: number;
source_scope?: string;
match_signals?: string[];
// Populated when remember() was called with relations
relation_write_result?: EntityRelationWriteResult;
}

RecallResult

interface RecallResult {
memories: Memory[];
total_count: number;
mode_used: RecallMode;
search_latency_ms: number;
query_tokens: number;
query_rewritten?: string;
sufficiency_reached?: boolean;
retrieval_confidence: "strong" | "moderate" | "weak";
confidence_reasons: string[];
budget_summary?: BudgetSummary; // requested, used, estimator, truncated_items, omitted_items
generation_summary?: GenerationSummary; // policy, calls, input_tokens, output_tokens
relation_paths: EntityRelationPath[];
}

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>;
tags: string[];
created_at: string;
updated_at: string;
}

Entity

interface Entity {
id: string;
workspace_id: string;
entity_type: "person" | "org" | "project" | "place" | "concept" | "event" | string;
canonical_name: string;
normalized_name: string;
aliases: string[];
confidence: number;
provenance: Record<string, unknown>;
representative_memory_id?: string | null;
status: string;
merged_into?: string | null;
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;
}

AuthorityContext

interface PrincipalRef { type: string; id: string; }
interface AuthorityContext { grantId: string; subject: PrincipalRef; }

Exceptions

MemoryLayerError // Base class: message, statusCode?, details?
├── AuthenticationError // 401
├── AuthorizationError // 403
├── NotFoundError // 404 (also 501 on non-Enterprise endpoints)
├── ValidationError // 400 / 422, with details
├── RateLimitError // 429, with retryAfter (seconds)
└── EnterpriseRequiredError // 501 on an Enterprise-only feature, with feature

Other HTTP errors (including 5xx after retries are exhausted) throw a plain MemoryLayerError with statusCode set. Network failures and timeouts also throw MemoryLayerError.

EnterpriseRequiredError means the server returned 501 because the feature needs MemoryLayer Enterprise, the open-source (AGPL-3.0) production edition. feature names the capability. Its statusCode property is 404, not the 501 the server sent, so check with instanceof.