Go API Reference
Reference for github.com/scitrera/memorylayer/memorylayer-sdk-go v0.2.x (package memorylayer) and its companion aether module.
import memorylayer "github.com/scitrera/memorylayer/memorylayer-sdk-go"Conventions
- Every method takes a
context.Contextfirst. Cancellation and deadlines propagate to the transport. - Optional parameters go in an
...Optionsstruct whose zero value is valid. Empty fields are not sent, so the server applies its defaults. - Pointer fields (
*bool,*int,*float64,*string) distinguish “unset” from a zero value. Set them withmemorylayer.Ptr(v). - Methods that accept a workspace fall back to the client’s default (
WithWorkspaceID) when it is empty. - Many options structs carry an
Authority *AuthorityContextfor a per-call on-behalf-of grant.
Client Construction
func NewClient(opts ...Option) (*Client, error)func (c *Client) Close() error| Option | Default | Description |
|---|---|---|
WithBaseURL(url string) | DefaultBaseURL ("http://localhost:61001") | Server URL. The SDK appends /v1. Used only by the default HTTP transport. |
WithAPIKey(key string) | none | Sent as Authorization: Bearer <key> |
WithWorkspaceID(id string) | none | Default workspace ID |
WithSessionID(id string) | none | Initial active session, sent as X-Session-ID |
WithTimeout(d time.Duration) | 30s | Per-request timeout for the default HTTP transport (ignored with WithHTTPClient or WithTransport) |
WithMaxRetries(n int) | 3 | Retries for idempotent requests (GET/HEAD/PUT/DELETE/PATCH/OPTIONS, plus POST with an Idempotency-Key) on 429/500/502/503/504 and network errors, honoring Retry-After. 0 disables. HTTP transport only. |
WithHTTPClient(hc *http.Client) | new client | Custom *http.Client (TLS, proxies, shared pool) |
WithTransport(t Transport) | HTTP transport | Replace the transport, e.g. with the Aether transport |
WithDefaultAuthority(a *AuthorityContext) | none | OBO authority applied to every request that does not override it |
A Client is safe for concurrent use. Close() releases the transport’s resources (idle HTTP connections).
Session helpers
func (c *Client) SetSession(sessionID string)func (c *Client) ClearSession()func (c *Client) SessionID() stringfunc (c *Client) WorkspaceID() stringNamespaces
| Field | Type | Surface |
|---|---|---|
client.Skills | *SkillsAPI | Skills |
client.McpServers | *McpServersAPI | MCP servers |
client.Kb | *KnowledgebaseAPI | Knowledgebase |
client.Rpg | *RpgAPI | Repository Planning Graph |
client.PromptNotes | *PromptNotesAPI | Revisioned resources |
client.AgentSpecifications | *AgentSpecificationsAPI | Revisioned resources |
client.RefinementRecords | *RefinementRecordsAPI | Revisioned resources |
client.WorkspaceViews | *WorkspaceViewsAPI | Revisioned resources |
On-Behalf-Of (OBO)
type PrincipalRef struct { Type string ID string}
type AuthorityContext struct { GrantID string Subject *PrincipalRef // nil = direct authority; non-nil = on behalf of Subject}
func (c *Client) ActingFor(grantID string, subject *PrincipalRef) *OBOProxyfunc (c *Client) ForWorkspace(workspaceID string) *OBOProxyOBOProxy is a lightweight view over the client that binds an authority and/or a default workspace without mutating the shared client. It provides Remember, Recall, Reflect, AppendMessages, DeleteMessage, ActingFor, ForWorkspace, and scoped namespaces through Skills(), McpServers(), and Kb(). For any other method, call the client directly and set Authority in the options.
The client sends authority as X-Aether-Grant-ID, X-Aether-Authority-Mode (on_behalf_of or direct), X-Aether-Subject-Type, and X-Aether-Subject-ID headers. The Aether transport converts these into the proxy’s structured authorization envelope. Precedence: per-call Authority, then the proxy’s bound authority, then WithDefaultAuthority.
alice := client.ActingFor("g_abc", &memorylayer.PrincipalRef{Type: "user", ID: "alice"})res, err := alice.ForWorkspace("ws_work").Recall(ctx, "preferences", memorylayer.RecallOptions{})Memories
func (c *Client) Remember(ctx context.Context, content string, opts RememberOptions) (*Memory, error)func (c *Client) Recall(ctx context.Context, query string, opts RecallOptions) (*RecallResult, error)func (c *Client) Reflect(ctx context.Context, query string, opts ReflectOptions) (*ReflectResult, error)func (c *Client) GetMemory(ctx context.Context, memoryID string, opts ...GetMemoryOptions) (*Memory, error)func (c *Client) UpdateMemory(ctx context.Context, memoryID string, opts UpdateMemoryOptions) (*Memory, error)func (c *Client) Forget(ctx context.Context, memoryID string, hard bool) errorfunc (c *Client) Decay(ctx context.Context, memoryID string, decayRate float64) (*Memory, error)func (c *Client) ListMemories(ctx context.Context, opts ListMemoriesOptions) (*RecallResult, error)func (c *Client) IterateMemories(ctx context.Context, pageSize int, opts ListMemoriesOptions, fn func(Memory) error) errorfunc (c *Client) BatchMemories(ctx context.Context, operations []map[string]any) (map[string]any, error)RememberOptions
| Field | Type | Description |
|---|---|---|
Type | MemoryType | Cognitive memory type |
Subtype | string | Domain subtype, e.g. string(MemorySubtypePreference) |
Importance | float64 | 0.0-1.0. A zero value is sent as 0.5; use .WithImportance(0) to send an explicit zero. |
Tags | []string | Tags |
Metadata | map[string]any | Metadata |
ContextID | string | Context within the workspace |
UserID | string | Associated user |
WorkspaceID | string | Workspace override |
Relations | []EntityRelationInput | Entity relations to write alongside the memory (requires the server’s entity registry) |
Authority | *AuthorityContext | Per-call OBO |
RecallOptions
| Field | Type | Description |
|---|---|---|
Types / Subtypes / Tags | slices | Filters |
Mode | RecallMode | RecallModeRAG, RecallModeLLM, RecallModeHybrid (or any server mode string) |
Limit | int | Max results (default 10 when <= 0) |
Offset | *int | Results to skip |
MinRelevance / RecencyWeight | *float64 | Ranking controls |
Tolerance | SearchTolerance | loose, moderate, strict |
IncludeAssociations | *bool | Include linked memories |
TraverseDepth / MaxExpansion | *int | Graph expansion controls |
CreatedAfter / CreatedBefore | string | ISO 8601 creation-time bounds |
EventAfter / EventBefore | string | ISO 8601 bounds on the effective event time |
TimeOrder | string | "asc" or "desc" by event time (empty = by relevance) |
IncludeGlobal / IncludeGlobalUser | *bool | Include _global / _global_user workspaces |
UserID / WorkspaceID | string | Scope |
BudgetTokens | *int | Token budget for returned memories |
IncludeConfidence / IncludeRelations | *bool | Confidence and entity relation paths |
Authority | *AuthorityContext | Per-call OBO |
RecallResult has Memories, TotalCount, QueryTokens, SearchLatencyMs, RetrievalConfidence, ConfidenceReasons, BudgetSummary, GenerationSummary, and RelationPaths.
Other memory options
ReflectOptions:MaxTokens(default 500),IncludeSources *bool(default true),Authority.GetMemoryOptions:WorkspaceID,IncludeDeleted,Authority.UpdateMemoryOptions:Content *string,Importance *float64,Tags,Metadata. Nil fields are left unchanged.ListMemoriesOptions:Limit(default 50),Offset,Type,Subtype,Tag,ContextID,Authority.TotalCounton the result is the page size, not a grand total.IterateMemoriesclampspageSizeto 1-200 and callsfnfor every memory. Return a non-nil error fromfnto stop.
BatchMemories sends the operations unchanged. Each is a flat map with "op" set to "create", "update", or "delete":
res, err := client.BatchMemories(ctx, []map[string]any{ {"op": "create", "content": "Memory 1", "importance": 0.7}, {"op": "update", "memory_id": "mem_123", "pinned": true}, {"op": "delete", "memory_id": "mem_old", "hard": false},})Versioned (conditional) memories
Keyed semantic memories with optimistic concurrency. Mutations send an Idempotency-Key. Create sends If-None-Match: *; replace, delete, and restore send If-Match with the memory’s ETag.
func (c *Client) CreateMemoryVersioned(ctx context.Context, input SemanticMemoryCreateInput, opts MemoryMutationOptions) (*MemoryMutationResult, error)func (c *Client) ReplaceSemanticMemory(ctx context.Context, memoryID string, input SemanticMemoryReplaceInput, opts MemoryMutationOptions) (*MemoryMutationResult, error)func (c *Client) DeleteMemoryVersioned(ctx context.Context, memoryID string, opts MemoryMutationOptions) (*MemoryMutationResult, error)func (c *Client) RestoreMemoryVersioned(ctx context.Context, memoryID string, opts MemoryMutationOptions) (*MemoryMutationResult, error)func (c *Client) MemoryHistory(ctx context.Context, memoryID string, opts MemoryHistoryOptions) (*MemoryRevisionPage, error)SemanticMemoryCreateInput:LogicalKey,Content,Type,Subtype,Tags,Metadata,RefinementMetadata,Pinned,UserID,Scope.MemoryMutationOptions:WorkspaceID,IdempotencyKey,ETag,Authority.MemoryMutationResult:Memory,Replayed(true when the idempotency key matched an earlier call),ETag.MemoryHistoryreturns revisions newest first, paginated withLimit/PageToken.
A stale ETag returns *PreconditionFailedError (412), and a missing conditional header returns *PreconditionRequiredError (428).
Associations
func (c *Client) Associate(ctx context.Context, sourceID, targetID string, relationship RelationshipType, opts AssociateOptions) (*Association, error)func (c *Client) GetAssociations(ctx context.Context, memoryID, direction string) ([]Association, error)func (c *Client) UpdateAssociation(ctx context.Context, memoryID, associationID string, opts UpdateAssociationOptions) (bool, error)func (c *Client) DeleteAssociation(ctx context.Context, memoryID, associationID string, authority *AuthorityContext) (bool, error)func (c *Client) TraverseGraph(ctx context.Context, memoryID string, opts TraverseGraphOptions) (map[string]any, error)AssociateOptions:Strength(a zero value is sent as0.5; use.WithStrength(v)for an explicit value),Metadata.directionis"outgoing","incoming", or"both"(the default when empty).UpdateAssociation/DeleteAssociationreturnfalse, nilwhen the association is not found.memoryIDmust be one of the edge’s endpoints.UpdateAssociationOptionshasStrength *float64,Metadata, andAuthority.TraverseGraphOptions:MaxDepth(default 2),RelationshipTypes,Direction(default"both"),MinStrength,WorkspaceID,Authority. The result map haspaths,total_paths,unique_nodes, andquery_latency_ms.
Entities
These methods require the server’s entity registry. If the server returns 501 for it, they return *EnterpriseRequiredError.
func (c *Client) ListEntities(ctx context.Context, opts ListEntitiesOptions) ([]Entity, error)func (c *Client) GetEntity(ctx context.Context, entityID, workspaceID string, authority *AuthorityContext) (*Entity, error)func (c *Client) ResolveEntity(ctx context.Context, name, entityType, workspaceID string, authority *AuthorityContext) (*EntityResolution, error)func (c *Client) MergeEntities(ctx context.Context, sourceID, targetID, reason, workspaceID string, authority *AuthorityContext) (*Entity, error)ListEntitiesOptions: Status ("active" or "merged"), Limit (default 100), WorkspaceID, Authority. ResolveEntity never creates an entity and returns nil, nil when nothing matches.
API Tokens
func (c *Client) CreateToken(ctx context.Context, name string, opts CreateTokenOptions) (*TokenCreateResult, error)func (c *Client) ListTokens(ctx context.Context, includeRevoked bool, authority *AuthorityContext) ([]TokenInfo, error)func (c *Client) GetToken(ctx context.Context, tokenID string, authority *AuthorityContext) (*TokenInfo, error)func (c *Client) RevokeToken(ctx context.Context, tokenID string, authority *AuthorityContext) errorfunc (c *Client) DeleteToken(ctx context.Context, tokenID string, authority *AuthorityContext) errorCreateTokenOptions: PrincipalType (default "User"), WorkspacePatterns (default ["*"]), Scopes (default ["*"]), ExpiresInDays *int, Authority. TokenCreateResult embeds TokenInfo and adds the plaintext Token, which is only returned once.
Sessions
func (c *Client) CreateSession(ctx context.Context, opts CreateSessionOptions) (*Session, error)func (c *Client) GetSession(ctx context.Context, sessionID string) (*Session, error)func (c *Client) ListSessions(ctx context.Context, opts ListSessionsOptions) ([]map[string]any, error)func (c *Client) DeleteSession(ctx context.Context, sessionID string) errorfunc (c *Client) TouchSession(ctx context.Context, sessionID string) (map[string]any, error)func (c *Client) SetContext(ctx context.Context, sessionID, key string, value any, ttlSeconds int) errorfunc (c *Client) GetContext(ctx context.Context, sessionID string, keys []string) (map[string]any, error)func (c *Client) CommitSession(ctx context.Context, sessionID string, opts CommitSessionOptions) (map[string]any, error)func (c *Client) GetBriefing(ctx context.Context, opts GetBriefingOptions) (*SessionBriefing, error)CreateSessionOptions:TTLSeconds(default 3600),WorkspaceID(auto-created if needed),ContextID. The new session becomes the client’s active session unless you call.NoAutoSetSession()on the options.SetContext:ttlSeconds <= 0means no per-key TTL.CommitSessionOptions:MinImportance(default 0.5; use.WithMinImportance(v)for an explicit zero),Deduplicate *bool(default true),Categories,MaxMemories(default 50).GetBriefingOptions:LookbackMinutes(default 60),LookbackHours(deprecated),DetailLevel("abstract","overview","full"),Limit(default 10),IncludeMemories *bool,IncludeContradictions *bool.
Checkpoints, context packs, and deltas
func (c *Client) CreateCheckpoint(ctx context.Context, sessionID, transcriptSegment string, opts CreateCheckpointOptions) (*SessionCheckpoint, error)func (c *Client) GetCheckpoint(ctx context.Context, sessionID, checkpointID string) (*SessionCheckpoint, error)func (c *Client) GetContextPack(ctx context.Context, sessionID string, opts ContextPackOptions) (*ContextPack, error)func (c *Client) GetContextDelta(ctx context.Context, sessionID, cursor string, budgetTokens int) (*ContextDelta, error)CreateCheckpointOptions:ContentHash(SHA-256 of the segment),IdempotencyKey(scoped to the session),SourceKind,SourceSequence *int,SourceBoundary *int.ContextPackOptions:Topic,EntityIDs,EntityNames,BudgetTokens(default 2048),SectionLimits, and*booltogglesIncludeDirectives,IncludeWorkingMemory,IncludeRecentActivity,IncludeContradictions,IncludeSandboxSummary,IncludeCheckpointRecovery.ContextPackhasRendered,Items,OpenThreads,UnresolvedContradictions,BudgetSummary,GenerationSummary,Cursor, andDegradationNotices.ContextDeltahasRendered,Items,Cursor,HasMore, and the summaries. Passpack.CursortoGetContextDeltato fetch only what changed since then.budgetTokens <= 0uses 2048.
Packs and deltas enforce the requested token budget and return stored content; they do not generate new prose.
Workspaces
func (c *Client) CreateWorkspace(ctx context.Context, name string, tags []string) (*Workspace, error)func (c *Client) ListWorkspaces(ctx context.Context, tags []string, match string) ([]Workspace, error)func (c *Client) GetWorkspace(ctx context.Context, workspaceID string) (*Workspace, error)func (c *Client) UpdateWorkspace(ctx context.Context, workspaceID string, opts UpdateWorkspaceOptions) (*Workspace, error)func (c *Client) GetWorkspaceSchema(ctx context.Context, workspaceID string) (map[string]any, error)func (c *Client) CreateContext(ctx context.Context, workspaceID, name, description string, settings map[string]any) (map[string]any, error)func (c *Client) ListContexts(ctx context.Context, workspaceID string) ([]map[string]any, error)func (c *Client) DeleteContext(ctx context.Context, contextID, workspaceID string) errorfunc (c *Client) ExportWorkspace(ctx context.Context, opts ExportWorkspaceOptions) (*WorkspaceExport, error)func (c *Client) ExportWorkspaceStream(ctx context.Context, opts ExportWorkspaceOptions, fn func(map[string]any) error) errorfunc (c *Client) ImportWorkspace(ctx context.Context, workspaceID string, data any) (map[string]any, error)func (c *Client) ImportWorkspaceStream(ctx context.Context, workspaceID string, lines []map[string]any) (map[string]any, error)ListWorkspaces:matchis"all"(every tag) or"any".UpdateWorkspaceOptions:Name *string,Settings,Tags.ExportWorkspaceOptions:WorkspaceID,IncludeAssociations *bool(default true),Offset,Limit(0 = all).ExportWorkspaceStreamcallsfnfor each NDJSON line (header,memory,association,footer).
Chat Threads
func (c *Client) CreateThread(ctx context.Context, opts CreateThreadOptions) (*ChatThread, error)func (c *Client) ListThreads(ctx context.Context, opts ListThreadsOptions) ([]ChatThread, error)func (c *Client) ListUserThreads(ctx context.Context, userID string, opts ListUserThreadsOptions) ([]ChatThread, error)func (c *Client) GetThread(ctx context.Context, threadID, workspaceID string) (*ChatThread, error)func (c *Client) GetThreadFull(ctx context.Context, threadID string, opts GetThreadFullOptions) (*ChatThreadWithMessages, error)func (c *Client) UpdateThread(ctx context.Context, threadID string, opts UpdateThreadOptions) (*ChatThread, error)func (c *Client) DeleteThread(ctx context.Context, threadID, workspaceID string) errorfunc (c *Client) AppendMessages(ctx context.Context, threadID string, messages []map[string]any, opts AppendMessagesOptions) ([]ChatMessage, error)func (c *Client) GetMessages(ctx context.Context, threadID string, opts GetMessagesOptions) ([]ChatMessage, error)func (c *Client) DeleteMessage(ctx context.Context, threadID, messageID string, opts DeleteMessageOptions) (bool, error)func (c *Client) DecomposeThread(ctx context.Context, threadID, workspaceID string) (*DecompositionResult, error)Ownership: with Ownership "user" (the default), the thread is stored under UserChatHomeWorkspace ("_user_chat"). The caller’s workspace is recorded on each appended message’s metadata under MessageMetaAppWorkspaceKey ("app_workspace"). Use "workspace" for workspace-scoped storage.
CreateThreadOptions:WorkspaceID,UserID,ContextID,ObserverID,SubjectID,Title,Metadata,ExpiresAt(ISO 8601),Scope,Ownership,ParentThread(creates a sub-thread that inherits the parent’s workspace and ownership),Authority.ThreadIDalso exists, but the server ignores it because thread IDs are always server-generated.ListThreadsOptions:WorkspaceID,UserID,Limit(50),Offset,ScopeFilter,OwnershipFilter,ParentThread. An emptyParentThreadlists top-level threads only; setting it lists that thread’s children.ListUserThreadsOptions:Ownership(default"user"),ScopeFilter,Limit,Offset.GetThreadFullOptions/GetMessagesOptions:WorkspaceID,Limit(100),Offset,Order("asc"/"desc"), plusAfterIndex *intandAuthorityonGetMessagesOptions.AppendMessagesOptions:WorkspaceID,Ownership,Authority. Each message map needsroleandcontent.DeleteMessagereturnsfalse, nilif the message does not exist.ChatMessage.Contentis aMessageContent, which holds either text or content blocks (IsText()).
Context Environment
Runs in the sandbox of the active session. See the Context Environment guide.
func (c *Client) ContextExec(ctx context.Context, code string, opts ContextExecOptions) (map[string]any, error)func (c *Client) ContextInspect(ctx context.Context, variable string, previewChars int) (map[string]any, error)func (c *Client) ContextLoad(ctx context.Context, varName, query string, opts ContextLoadOptions) (map[string]any, error)func (c *Client) ContextInject(ctx context.Context, key string, value any, parseJSON bool) (map[string]any, error)func (c *Client) ContextQuery(ctx context.Context, prompt string, variables []string, opts ContextQueryOptions) (map[string]any, error)func (c *Client) ContextRLM(ctx context.Context, goal string, opts ContextRLMOptions) (map[string]any, error)func (c *Client) ContextStatus(ctx context.Context) (map[string]any, error)func (c *Client) ContextCheckpoint(ctx context.Context) errorfunc (c *Client) ContextCleanup(ctx context.Context) errorDefaults: ContextExecOptions.MaxReturnChars 10000, ReturnResult true. previewChars is 200 when <= 0. ContextLoadOptions.Limit is 50. ContextRLMOptions has MemoryLimit 100, MaxIterations 10, and DetailLevel "standard" (also "brief" or "detailed").
Documents
If the server returns 501 because the feature is not available, these methods return *EnterpriseRequiredError.
func (c *Client) UploadDocument(ctx context.Context, fileData []byte, filename string, opts UploadDocumentOptions) (*DocumentInfo, *JobInfo, error)func (c *Client) ListDocuments(ctx context.Context, opts ListDocumentsOptions) ([]DocumentInfo, int, error)func (c *Client) GetDocument(ctx context.Context, documentID string) (*DocumentInfo, error)func (c *Client) DeleteDocument(ctx context.Context, documentID string, deleteMemories bool) errorfunc (c *Client) ReprocessDocument(ctx context.Context, documentID string, opts ReprocessDocumentOptions) (*JobInfo, error)func (c *Client) SearchDocumentPages(ctx context.Context, query string, limit int, docIDs []string) (*PageSearchResult, error)func (c *Client) GetDocumentPages(ctx context.Context, documentID string) ([]DocumentPage, error)func (c *Client) GetPageImage(ctx context.Context, documentID, pageID string) ([]byte, error)func (c *Client) GetJob(ctx context.Context, jobID string) (*JobInfo, error)func (c *Client) ListJobs(ctx context.Context, status string, limit int) ([]JobInfo, error)func (c *Client) CancelJob(ctx context.Context, jobID string) errorUploadDocumentOptions: TargetContextID ("_default"), ChunkingStrategy ("page"), ChunkSize (4096), ChunkOverlap (200), Importance (0.5; .WithImportance(v) for an explicit value), RetainOriginal *bool (true). ListDocumentsOptions adds WorkspaceID, DocumentType, CreatedAfter, CreatedBefore, and Authority filters. See Document Ingestion.
Datasets
func (c *Client) UploadDataset(ctx context.Context, fileData []byte, filename string, opts UploadDatasetOptions) (*DatasetInfo, *DatasetJobInfo, error)func (c *Client) ListDatasets(ctx context.Context, opts ListDatasetsOptions) ([]DatasetInfo, int, error)func (c *Client) GetDataset(ctx context.Context, datasetID string) (*DatasetInfo, error)func (c *Client) DeleteDataset(ctx context.Context, datasetID string, deleteMemories bool) errorfunc (c *Client) GetDatasetMemories(ctx context.Context, datasetID string) ([]map[string]any, error)func (c *Client) QueryDatasetSlice(ctx context.Context, datasetID string, opts QueryDatasetSliceOptions) (*DatasetSliceResult, error)func (c *Client) GetDatasetJob(ctx context.Context, jobID string) (*DatasetJobInfo, error)func (c *Client) ListDatasetJobs(ctx context.Context, status string, limit int) ([]DatasetJobInfo, error)func (c *Client) CancelDatasetJob(ctx context.Context, jobID string) errorQueryDatasetSliceOptions: SQL (read-only), Columns, Filters, OrderBy, Descending, Limit (100), Offset. See Dataset Management.
Skills
client.Skills (*SkillsAPI). See Skills & MCP Servers.
| Method | Signature |
|---|---|
List | (ctx, opts ListSkillsOptions) ([]SkillModel, error). Options: Scope, Name, Tags, Enabled *bool, IncludeShadowed, IncludeAddenda, WorkspaceID, Authority |
Get / GetWithOptions | (ctx, skillID, authority) / (ctx, skillID, SkillGetOptions) returns *SkillModel |
GetManifest / GetManifestWithOptions | returns the rendered SKILL.md as a string |
GetFile | (ctx, skillID, path) ([]byte, error) |
ListFiles | (ctx, skillID, authority) ([]map[string]any, error) |
Save | (ctx, name, description string, opts SaveSkillOptions) (*SkillModel, error). Creates or updates by name. Options: Body, Files, Scope ("workspace"), SourceMode ("server"), WorkspaceID, UserID, Version, License, Compatibility, AllowedTools, Metadata, Authority |
Delete | (ctx, skillID, authority) error |
Resolve / ResolveWithOptions | (ctx, name, query, workspaceID, authority) (*SkillResolution, error). Returns Skill (by name) or Skills (by query) |
Pull | (ctx, name, outDir, workspaceID) (string, error) writes outDir/<name>/ |
Push | (ctx, skillDir, scope, sourceMode, workspaceID) (*SkillModel, error) |
Materialize | (ctx, targetDir, scope, workspaceID) ([]string, error) pulls every visible skill |
CreateVersioned / ReplaceManifest / DeleteVersioned / Restore / History | Conditional, revisioned manifest writes (ETag + idempotency key), like versioned memories |
ParseSkillFolder(path string) (*SkillManifest, []SkillFile, error) parses a local skill directory.
MCP Servers
client.McpServers (*McpServersAPI).
| Method | Signature |
|---|---|
List | (ctx, ListMcpServersOptions) ([]McpServerModel, error). Options: Transport, Enabled, Name, UserID, Limit (100), Offset, WorkspaceID, Authority |
Get | (ctx, serverID, authority) (*McpServerModel, error) |
Create | (ctx, name, transport string, CreateMcpServerOptions) (*McpServerModel, error). Options: Command, Args, Env, URL, Headers, Description, Metadata, SourceMode, Enabled, WorkspaceID, UserID, Authority |
Update | (ctx, serverID, UpdateMcpServerOptions) (*McpServerModel, error) |
Delete | (ctx, serverID, authority) error |
Resolve | (ctx, name, workspaceID, authority) (*McpServerModel, error) |
PushJSON | (ctx, jsonPath, scope, sourceMode, workspaceID, userID, authority) ([]McpServerModel, error) imports a .mcp.json file |
PullJSON | (ctx, outPath, workspaceID, userID, transport string, enabled *bool, authority) error writes a .mcp.json file |
Knowledgebase
client.Kb (*KnowledgebaseAPI). If the server returns 501 for the knowledgebase, these methods return *EnterpriseRequiredError.
| Method | Signature |
|---|---|
Get | (ctx, KbGetOptions) (*KbMetadata, error) |
ListArticles | (ctx, KbListArticlesOptions) ([]KbArticle, error) |
GetArticle | (ctx, articleID, workspaceID, authority) (*KbArticle, error) |
Generate | (ctx, KbGenerateOptions) (*KbMetadata, error). Options: WorkspaceID, Regenerate, MaxCommunities *int, MaxGodNodes *int, IncludeRPG, ContextID, Authority |
ExportVault | (ctx, workspaceID, authority) ([]byte, error) returns an Obsidian-compatible vault zip |
GetGraphAnalysis | (ctx, workspaceID, contextID, authority) (*KbGraphAnalysis, error) |
GetCommunity | (ctx, communityID int, workspaceID, authority) (*KbCommunity, error) |
Repository Planning Graph
client.Rpg (*RpgAPI), for the RPG server plugin. See Repository Planning Graph.
| Method | Signature |
|---|---|
Sync | (ctx, nodes []RpgNodeInput, edges []RpgEdgeInput, RpgSyncOptions) (*RpgSyncResult, error) |
GetSubgraph | (ctx, RpgSubgraphOptions) (*RpgSubgraph, error) |
Search | (ctx, query, RpgSearchOptions) (*RpgSearchResult, error) |
GetStatus | (ctx, contextID, authority) (*RpgStatus, error) |
ListOverlays / DeleteOverlay | (ctx, authority) / (ctx, contextID, authority) |
ListNodes | (ctx, RpgListNodesOptions) (*RpgNodeList, error) |
DeleteNodes / DeleteEdges | (ctx, nodeIDs, contextID, authority) / (ctx, associationIDs, authority) |
GetMergedSubgraph | (ctx, overlayContext, baseContext, path string, depth int, authority) |
GetConflicts / GetSymbolConflicts | (ctx, taskID, authority) / (ctx, taskIDA, taskIDB, authority) |
Maintenance | (ctx, RpgMaintenanceOperation, authority): RpgMaintenanceValidate, RpgMaintenanceCleanup, RpgMaintenanceStatistics, … |
Enrich | (ctx, RpgEnrichOptions) (*RpgEnrichmentResult, error) |
Revisioned Resources
These namespaces expose typed, revisioned server resources. They are currently available only in the Go SDK. Mutations use the same conditional-write model as versioned memories: an IdempotencyKey, If-None-Match: * on create, and the current ETag on replace, delete, and restore. Each mutation result carries the resource, Replayed, and the new ETag.
| Namespace | Methods | Resource |
|---|---|---|
client.PromptNotes | Create, Replace, Delete, Restore, Get, List, History | PromptNote: a keyed prompt supplement (Key, Title, Content, Enabled, Metadata) |
client.AgentSpecifications | Create, Replace, Delete, Restore, Get, List, History | AgentSpecification: a reusable subagent definition (Key, Name, Description, Instructions, Model, MaxTurns, AllowedTools, DeniedTools, Skills, MCPServers, PermissionMode, …) |
client.RefinementRecords | Create, Get, List | RefinementRecord: an append-only audit record of a proposal, decision, application, or rollback |
client.WorkspaceViews | Create, Replace, Delete, Restore, Get, List, History, plus CreateObservation, ReplaceObservation, DeleteObservation, RestoreObservation, GetObservation, ListObservations, ObservationHistory | WorkspaceView: a durable checkout, worktree, snapshot, or overlay, with state published by observers |
res, err := client.PromptNotes.Create(ctx, memorylayer.PromptNoteCreateInput{ Key: "style-guide", Title: "Code style", Content: "Prefer table-driven tests.",}, memorylayer.PromptNoteMutationOptions{IdempotencyKey: "create-style-guide"})
_, err = client.PromptNotes.Replace(ctx, res.Note.ID, memorylayer.PromptNoteReplaceInput{ /* ... */ }, memorylayer.PromptNoteMutationOptions{IdempotencyKey: "edit-1", ETag: res.ETag})Types and Constants
Enums (string types)
| Type | Constants |
|---|---|
MemoryType | MemoryTypeEpisodic, MemoryTypeSemantic, MemoryTypeProcedural, MemoryTypeWorking |
MemorySubtype | MemorySubtypeSolution, Problem, CodePattern, Fix, Error, Workflow, Preference, Decision, Directive, Profile, Entity, Event, Inference (each prefixed MemorySubtype) |
RecallMode | RecallModeRAG, RecallModeLLM, RecallModeHybrid |
SearchTolerance | SearchToleranceLoose, SearchToleranceModerate, SearchToleranceStrict |
RelationshipCategory | RelationshipCategoryHierarchical, Causal, Temporal, Similarity, Learning, Reference, Solution, Context, Workflow, Quality |
RelationshipType | RelationshipCauses, RelationshipSolves, RelationshipSimilarTo, RelationshipDependsOn, … (the same 26 common types as the Python SDK). Any ontology string can be converted with memorylayer.RelationshipType("part_of"). |
The server also accepts RecallMode("agentic"), an iterative LLM-controlled retrieval loop provided by MemoryLayer Enterprise.
Constants
| Constant | Value |
|---|---|
DefaultBaseURL | "http://localhost:61001" |
Version | "0.2.0" |
UserChatHomeWorkspace | "_user_chat" |
MessageMetaAppWorkspaceKey | "app_workspace" |
Key models
Memory includes ID, LogicalKey, WorkspaceID, Content, Type, Subtype, Importance, Tags, Metadata, RefinementMetadata, CreatedAt, UpdatedAt, Pinned, Status, Revision, ETag, DeletedAt, and recall-only fields such as RelevanceScore, BoostedScore, and SourceScope. Optional fields are pointers. Timestamps are time.Time.
Other models: Association, Session, SessionCheckpoint, ContextPack, ContextDelta, Workspace, Entity, EntityResolution, TokenInfo, ChatThread (with Ownership and ParentThread), ChatMessage, DecompositionResult, and the document/dataset models.
Errors
Every API failure is one of these types. Each embeds *APIError, which exposes Message and StatusCode:
| Type | Status |
|---|---|
*AuthenticationError | 401 |
*AuthorizationError | 403 |
*NotFoundError | 404, and 501 on endpoints not flagged as Enterprise features |
*ConflictError | 409 |
*PreconditionFailedError | 412 (stale ETag) |
*PreconditionRequiredError | 428 (missing conditional or idempotency header) |
*ValidationError | 422 |
*RateLimitError | 429 |
*EnterpriseRequiredError | 501 on an Enterprise feature. Feature names the capability. |
*ServerError | other 5xx |
*APIError | any other 4xx |
Helpers: IsNotFound(err) and IsEnterpriseRequired(err). To match another type, use errors.As with that specific type:
var rl *memorylayer.RateLimitErrorif errors.As(err, &rl) { log.Printf("rate limited (%d): %s", rl.StatusCode, rl.Message)}The typed errors do not implement Unwrap, so errors.As(err, &apiErr) with an *APIError target only matches the untyped 4xx case. Match the specific type instead.
*EnterpriseRequiredError means the server returned 501 because the feature needs MemoryLayer Enterprise, the open-source (AGPL-3.0) production edition. Transport-level failures (DNS, connection refused, context cancellation) are returned as the underlying Go error, not an *APIError.
Aether Transport
The companion module github.com/scitrera/memorylayer/memorylayer-sdk-go/aether routes every request through an existing Aether connection (ProxyHTTP) instead of a direct HTTP call. It is a separate Go module so that HTTP-only callers don’t pull in the Aether SDK’s gRPC dependencies. It is released in lockstep with the core module (memorylayer-sdk-go/aether/v0.2.0) and builds on the Aether Go SDK v0.2.3.
go get github.com/scitrera/memorylayer/memorylayer-sdk-go/aetherimport ( aethersdk "github.com/scitrera/aether/sdk/go/aether" memorylayer "github.com/scitrera/memorylayer/memorylayer-sdk-go" mlaether "github.com/scitrera/memorylayer/memorylayer-sdk-go/aether")
agent, err := aethersdk.NewAgentClient(aethersdk.AgentOptions{ ClientOptions: aethersdk.ClientOptions{ServerAddr: "localhost:50051"}, Workspace: "default", Implementation: "my-service", Specifier: "worker-1",})if err != nil { log.Fatal(err)}if err := agent.Connect(ctx); err != nil { log.Fatal(err)}defer agent.Close()
transport := mlaether.NewTransport(agent, mlaether.WithTarget(mlaether.DefaultTarget))
client, err := memorylayer.NewClient( memorylayer.WithTransport(transport), memorylayer.WithAPIKey("..."), memorylayer.WithWorkspaceID("ws_123"),)func NewTransport(client ProxyClient, opts ...Option) *TransportProxyClient is any value with the Aether SDK’s ProxyHTTP method. Both *aethersdk.AgentClient and *aethersdk.ServiceClient satisfy it.
| Option | Default | Description |
|---|---|---|
WithTarget(topic string) | DefaultTarget ("sv::memorylayer") | Service topic. The bare topic lets Aether route to any available instance; use sv::memorylayer::<specifier> to pin one. |
WithBackend(name string) | none | Pin requests to a named terminator backend (its allow-list still applies) |
WithTimeout(d time.Duration) | 30s | Applied as a context deadline when the caller’s context has none |
WithBasePath(path string) | "/v1" | API version prefix, matching the terminator’s allowed paths |
Behavior:
- The transport extracts the
X-Aether-*authority headers and sends them as the proxy’s structuredAuthorizationContext, soActingForand per-callAuthoritywork end to end. Strict-mode terminators strip inboundX-Aether-*headers, so this envelope is the only reliable OBO channel. WithBaseURL,WithTimeout,WithHTTPClient, andWithMaxRetrieson the client do not apply when a custom transport is installed.- The transport does not own the Aether connection. Its
Close()is a no-op, and you close the Aether client yourself.
See Server -> Aether Transport for the server side and Python SDK -> Aether Transport for the Python equivalent.
Custom transports
Any type that implements memorylayer.Transport can be installed with WithTransport:
type Transport interface { RoundTrip(ctx context.Context, req *Request) (*Response, error) Close() error}Request.Path is relative to the API root (for example /memories). The transport is responsible for mounting it under /v1. Response.Body is fully buffered. Return a non-nil error only for transport-level failures; the client maps HTTP status codes to typed errors itself.