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:
| Property | Type | Default | Description |
|---|---|---|---|
baseUrl | string | "http://localhost:61001" | Server URL |
apiKey | string | undefined | API key, sent as Authorization: Bearer <key> |
workspaceId | string | undefined | Default workspace. Sent as the X-Workspace-ID header and used as the fallback workspace_id. |
sessionId | string | undefined | Active session ID, sent as the X-Session-ID header |
timeout | number | 30000 | Request timeout in milliseconds |
defaultAuthority | AuthorityContext | undefined | On-behalf-of authority applied to every request (see Authority Headers) |
maxRetries | number | 3 | Retries for idempotent requests (GET/HEAD/OPTIONS/PUT/DELETE/PATCH) on 5xx (except 501), 429, and network errors. POST is never retried. 0 disables. |
retryBaseDelay | number | 500 | Base delay in ms for exponential backoff (retryBaseDelay * 2^attempt), unless the server sends Retry-After |
fetch | typeof fetch | globalThis.fetch | Custom 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
| Property | Class | Surface |
|---|---|---|
client.skills | SkillsNamespace | Skills |
client.mcpServers | McpServersNamespace | MCP server registry |
client.kb | KnowledgebaseNamespace | Knowledgebase |
client.rpg | RpgNamespace | Repository 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 } }): OboProxyOboProxy 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:
| Property | Type | Default | Description |
|---|---|---|---|
type | MemoryType | string | undefined | Cognitive memory type |
subtype | MemorySubtype | string | undefined | Domain subtype |
importance | number | 0.5 | Importance score 0.0-1.0 |
tags | string[] | [] | Tags for categorization |
metadata | Record<string, unknown> | {} | Additional metadata |
associations | string[] | [] | Memory IDs to associate with |
relations | EntityRelationInput[] | [] | Entity relations to write alongside the memory (requires the server’s entity registry) |
contextId | string | undefined | Context within workspace |
userId | string | undefined | User ID to associate |
workspaceId | string | client default | Workspace override |
authority | AuthorityContext | undefined | Per-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):
| Property | Type | Default | Description |
|---|---|---|---|
types | (MemoryType | string)[] | [] | Filter by memory types |
subtypes | (MemorySubtype | string)[] | [] | Filter by subtypes |
tags | string[] | [] | Filter by tags |
contextId | string | undefined | Filter by context |
mode | RecallMode | string | server default (rag) | Retrieval mode |
tolerance | SearchTolerance | string | server default | Search precision |
limit | number | 10 | Maximum memories |
offset | number | undefined | Results to skip (pagination) |
minRelevance | number | undefined | Minimum relevance 0.0-1.0 |
recencyWeight | number | undefined | Recency weight 0.0-1.0 |
includeAssociations | boolean | undefined | Include linked memories |
traverseDepth | number | undefined | Multi-hop graph traversal depth |
maxExpansion | number | undefined | Max memories via graph expansion |
createdAfter / createdBefore | Date | undefined | Creation-time bounds |
eventAfter / eventBefore | Date | undefined | Bounds on the memory’s effective event time |
timeOrder | "asc" | "desc" | undefined | Order by effective event time (omit to rank by relevance) |
includeGlobal | boolean | undefined | Include the _global workspace |
includeGlobalUser | boolean | undefined | Include the user-scoped _global_user workspace, filtered by userId |
conversationContext | { role: string; content: string }[] | [] | Recent conversation turns for query context |
ragThreshold | number | undefined | RAG sufficiency threshold for hybrid mode |
detailLevel | DetailLevel | string | undefined | "abstract", "overview", or "full" |
userId | string | undefined | Filter by user |
budgetTokens | number | undefined | Token budget for returned memories |
includeConfidence | boolean | true | Return retrieval_confidence and confidence_reasons |
includeRelations | boolean | true | Return entity relation_paths |
workspaceId | string | client default | Workspace override |
authority | AuthorityContext | undefined | Per-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:
| Property | Type | Default | Description |
|---|---|---|---|
detailLevel | DetailLevel | string | undefined | Level of detail |
includeSources | boolean | true | Include source memory IDs |
depth | number | 2 | Association traversal depth |
types / subtypes / tags | arrays | [] | Filters |
contextId / userId | string | undefined | Filters |
workspaceId | string | client default | Workspace override |
authority | AuthorityContext | undefined | Per-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.1listMemories()
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:
| Property | Type | Default | Description |
|---|---|---|---|
relationshipTypes | string[] | all | Filter by relationship types |
relationshipCategories | RelationshipCategory[] | all | Filter by category |
maxDepth | number | 3 | Maximum hops |
direction | "outgoing" | "incoming" | "both" | "both" | Traversal direction |
minStrength | number | 0.0 | Minimum edge strength |
maxPaths | number | 100 | Maximum paths |
maxNodes | number | 50 | Maximum 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:
| Property | Type | Default | Description |
|---|---|---|---|
sessionId | string | generated | Client-provided session ID |
workspaceId | string | client default | Workspace (auto-created if needed) |
ttlSeconds | number | 3600 | Time to live (60-86400) |
metadata | Record<string, unknown> | {} | Session metadata |
contextId | string | undefined | Context (defaults to _default) |
workingMemory | Record<string, unknown> | {} | Initial working memory |
briefing | boolean | false | Include a briefing in the response |
briefingOptions | { lookbackHours?, detailLevel?, limit? } | undefined | Briefing 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 TTLasync 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): voidgetSessionId(): string | undefinedclearSession(): voidCommitOptions: 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_customizeContexts
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 athreadIdoption, 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(stringorChatMessageContent[]),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.
| Method | Signature | Returns |
|---|---|---|
list | (options?: SkillListOptions): workspaceId, scope, name, tags, enabled, includeShadowed, authority | Skill[] |
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)
| Method | Signature | Returns |
|---|---|---|
list | (options?: McpServerListOptions): workspaceId, userId, name, transport, enabled, limit, offset, authority | McpServer[] |
get | (serverId, authority?) | McpServer |
create | (options: McpServerCreateOptions): name, transport, command, args, env, url, headers, description, metadata, source_mode, enabled, workspaceId, userId, authority | McpServer |
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.
| Method | Signature | Returns |
|---|---|---|
get | () | Knowledgebase |
generate | (options?: KBGenerateOptions): workspaceId, contextId, includeRpg, maxCommunities, maxGodNodes, regenerate | Knowledgebase |
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.
| Method | Signature |
|---|---|
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 featureOther 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.