@mastra/core
Version:
Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.
343 lines • 15 kB
TypeScript
import type { AssistantContent, UserContent, CoreMessage } from '../_types/@internal_ai-sdk-v4/dist/index.js';
import type { MastraDBMessage } from '../agent/message-list/index.js';
import type { MastraFGAPermissionInput } from '../auth/ee/index.js';
import { MastraBase } from '../base.js';
import type { EmbeddingModelId } from '../llm/model/index.js';
import type { Mastra } from '../mastra/index.js';
import type { ObservabilityContext } from '../observability/index.js';
import type { InputProcessor, OutputProcessor, InputProcessorOrWorkflow, OutputProcessorOrWorkflow } from '../processors/index.js';
import type { RequestContext } from '../request-context/index.js';
import type { MastraCompositeStore, StorageListMessagesInput, StorageListThreadsInput, StorageListThreadsOutput, StorageCloneThreadInput, StorageCloneThreadOutput } from '../storage/index.js';
import type { ToolAction } from '../tools/index.js';
import type { IdGeneratorContext } from '../types/index.js';
import type { MastraEmbeddingModel, MastraEmbeddingOptions, MastraVector } from '../vector/index.js';
import type { SharedMemoryConfig, StorageThreadType, MemoryConfig, MemoryConfigInternal, MastraMessageV1, WorkingMemoryTemplate, MessageDeleteInput, SerializedMemoryConfig } from './types.js';
export type MemoryProcessorOpts = {
systemMessage?: string;
memorySystemMessage?: string;
newMessages?: CoreMessage[];
};
/**
* Interface for message processors that can filter or transform messages
* before they're sent to the LLM.
*/
export declare abstract class MemoryProcessor extends MastraBase {
/**
* Process a list of messages and return a filtered or transformed list.
* @param messages The messages to process
* @returns The processed messages
*/
process(messages: CoreMessage[], _opts: MemoryProcessorOpts): CoreMessage[] | Promise<CoreMessage[]>;
}
export declare const memoryDefaultOptions: {
lastMessages: number;
semanticRecall: false;
generateTitle: false;
workingMemory: {
enabled: false;
template: string;
};
};
export { filterSystemReminderMessages, isSystemReminderMessage } from './system-reminders.js';
/**
* Abstract base class for implementing conversation memory systems.
*
* Key features:
* - Thread-based conversation organization with resource association
* - Optional vector database integration for semantic similarity search
* - Working memory templates for structured conversation state
* - Handles memory processors to manipulate messages before they are sent to the LLM
*/
export declare abstract class MastraMemory extends MastraBase {
#private;
/**
* Unique identifier for the memory instance.
* If not provided, defaults to a static name 'default-memory'.
*/
readonly id: string;
MAX_CONTEXT_TOKENS?: number;
protected _storage?: MastraCompositeStore;
vector?: MastraVector;
embedder?: MastraEmbeddingModel<string>;
embedderOptions?: MastraEmbeddingOptions;
protected threadConfig: MemoryConfigInternal;
constructor(config: {
id?: string;
name: string;
} & SharedMemoryConfig);
/**
* Internal method used by Mastra to register itself with the memory.
* @param mastra The Mastra instance.
* @internal
*/
__registerMastra(mastra: Mastra): void;
protected _hasOwnStorage: boolean;
get hasOwnStorage(): boolean;
get storage(): MastraCompositeStore;
setStorage(storage: MastraCompositeStore): void;
setVector(vector: MastraVector): void;
setEmbedder(embedder: EmbeddingModelId | MastraEmbeddingModel<string>, embedderOptions?: MastraEmbeddingOptions): void;
/**
* Get a system message to inject into the conversation.
* This will be called before each conversation turn.
* Implementations can override this to inject custom system messages.
*/
getSystemMessage(_input: {
threadId: string;
resourceId?: string;
memoryConfig?: MemoryConfigInternal;
}): Promise<string | null>;
/**
* Get tools that should be available to the agent.
* This will be called when converting tools for the agent.
* Implementations can override this to provide additional tools.
*/
listTools(_config?: MemoryConfig): Record<string, ToolAction<any, any, any, any, any>>;
/**
* Cached promise for the embedding dimension probe.
* Stored as a promise to deduplicate concurrent calls.
*/
private _embeddingDimensionPromise?;
/**
* Probe the embedder to determine its actual output dimension.
* The result is cached so subsequent calls are free.
*/
protected getEmbeddingDimension(): Promise<number | undefined>;
/**
* Get the index name for semantic recall embeddings.
* This is used to ensure consistency between the Memory class and SemanticRecall processor.
*/
protected getEmbeddingIndexName(dimensions?: number): string;
protected createEmbeddingIndex(dimensions?: number, config?: MemoryConfigInternal): Promise<{
indexName: string;
}>;
getMergedThreadConfig(config?: MemoryConfigInternal): MemoryConfigInternal;
estimateTokens(text: string): number;
/**
* Retrieves a specific thread by its ID
* @param threadId - The unique identifier of the thread
* @returns Promise resolving to the thread or null if not found
*/
abstract getThreadById({ threadId }: {
threadId: string;
}): Promise<StorageThreadType | null>;
/**
* Lists threads with optional filtering by resourceId and metadata.
* This method supports:
* - Optional resourceId filtering (not required)
* - Metadata filtering with AND logic (all key-value pairs must match)
* - Pagination via `page` / `perPage`, optional ordering via `orderBy`
*
* @param args.filter - Optional filters for resourceId and/or metadata
* @param args.filter.resourceId - Optional resource ID to filter by
* @param args.filter.metadata - Optional metadata key-value pairs to filter by (AND logic)
* @param args.page - Zero-indexed page number for pagination (defaults to 0)
* @param args.perPage - Number of items per page, or false to fetch all (defaults to 100)
* @param args.orderBy - Optional sorting configuration with `field` and `direction`
* @returns Promise resolving to paginated thread results with metadata
*
* @example
* ```typescript
* // Filter by resourceId only
* await memory.listThreads({ filter: { resourceId: 'user-123' } });
*
* // Filter by metadata only
* await memory.listThreads({ filter: { metadata: { category: 'support' } } });
*
* // Filter by both
* await memory.listThreads({
* filter: {
* resourceId: 'user-123',
* metadata: { priority: 'high', status: 'open' }
* }
* });
* ```
*/
abstract listThreads(args: StorageListThreadsInput): Promise<StorageListThreadsOutput>;
/**
* Saves or updates a thread
* @param thread - The thread data to save
* @returns Promise resolving to the saved thread
*/
abstract saveThread({ thread, memoryConfig, }: {
thread: StorageThreadType;
memoryConfig?: MemoryConfigInternal;
}): Promise<StorageThreadType>;
/**
* Saves messages to a thread
* @param messages - Array of messages to save
* @returns Promise resolving to the saved messages
*/
abstract saveMessages(args: {
messages: MastraDBMessage[];
memoryConfig?: MemoryConfig | undefined;
observabilityContext?: Partial<ObservabilityContext>;
}): Promise<{
messages: MastraDBMessage[];
usage?: {
tokens: number;
};
}>;
/**
* Retrieves messages for a specific thread with optional semantic recall
* @param threadId - The unique identifier of the thread
* @param resourceId - Optional resource ID for validation
* @param vectorSearchString - Optional search string for semantic recall
* @param config - Optional memory configuration
* @returns Promise resolving to array of messages in mastra-db format
*/
abstract recall(args: StorageListMessagesInput & {
threadConfig?: MemoryConfigInternal;
vectorSearchString?: string;
includeSystemReminders?: boolean;
observabilityContext?: Partial<ObservabilityContext>;
}): Promise<{
messages: MastraDBMessage[];
usage?: {
tokens: number;
};
total: number;
page: number;
perPage: number | false;
hasMore: boolean;
}>;
/**
* Helper method to create a new thread
* @param title - Optional title for the thread
* @param metadata - Optional metadata for the thread
* @returns Promise resolving to the created thread
*/
createThread({ threadId, resourceId, title, metadata, memoryConfig, saveThread, }: {
resourceId: string;
threadId?: string;
title?: string;
metadata?: Record<string, unknown>;
memoryConfig?: MemoryConfigInternal;
saveThread?: boolean;
}): Promise<StorageThreadType>;
/**
* Helper method to delete a thread
* @param threadId - the id of the thread to delete
*/
abstract deleteThread(threadId: string): Promise<void>;
/**
* Helper method to add a single message to a thread
* @param threadId - The thread to add the message to
* @param content - The message content
* @param role - The role of the message sender
* @param type - The type of the message
* @param toolNames - Optional array of tool names that were called
* @param toolCallArgs - Optional array of tool call arguments
* @param toolCallIds - Optional array of tool call ids
* @returns Promise resolving to the saved message
* @deprecated use saveMessages instead
*/
addMessage(_params: {
threadId: string;
resourceId: string;
config?: MemoryConfigInternal;
content: UserContent | AssistantContent;
role: 'user' | 'assistant';
type: 'text' | 'tool-call' | 'tool-result';
toolNames?: string[];
toolCallArgs?: Record<string, unknown>[];
toolCallIds?: string[];
}): Promise<MastraMessageV1>;
/**
* Generates a unique identifier
* @param context - Optional context information for deterministic ID generation
* @returns A unique string ID
*/
generateId(context?: IdGeneratorContext): string;
/**
* Static helper to check FGA authorization for thread access.
* Can be called from HTTP handlers and agent execution paths.
*/
static checkThreadFGA(options: {
mastra?: Mastra;
user: Record<string, unknown>;
threadId: string;
resourceId?: string;
requestContext?: RequestContext;
permission?: MastraFGAPermissionInput;
}): Promise<void>;
/**
* Retrieves working memory for a specific thread
* @param threadId - The unique identifier of the thread
* @param resourceId - The unique identifier of the resource
* @param memoryConfig - Optional memory configuration
* @returns Promise resolving to working memory data or null if not found
*/
abstract getWorkingMemory({ threadId, resourceId, memoryConfig, }: {
threadId: string;
resourceId?: string;
memoryConfig?: MemoryConfigInternal;
}): Promise<string | null>;
/**
* Get working memory template
* @param threadId - Thread ID
* @param resourceId - Resource ID
* @returns Promise resolving to working memory template or null if not found
*/
abstract getWorkingMemoryTemplate({ memoryConfig, }: {
memoryConfig?: MemoryConfigInternal;
}): Promise<WorkingMemoryTemplate | null>;
abstract updateWorkingMemory({ threadId, resourceId, workingMemory, memoryConfig, observabilityContext, }: {
threadId: string;
resourceId?: string;
workingMemory: string;
memoryConfig?: MemoryConfigInternal;
observabilityContext?: Partial<ObservabilityContext>;
}): Promise<void>;
/**
* @warning experimental! can be removed or changed at any time
*/
abstract __experimental_updateWorkingMemoryVNext({ threadId, resourceId, workingMemory, searchString, memoryConfig, }: {
threadId: string;
resourceId?: string;
workingMemory: string;
searchString?: string;
memoryConfig?: MemoryConfigInternal;
}): Promise<{
success: boolean;
reason: string;
}>;
/**
* Get input processors for this memory instance
* This allows Memory to be used as a ProcessorProvider in Agent's inputProcessors array.
* @param configuredProcessors - Processors already configured by the user (for deduplication)
* @returns Array of input processors configured for this memory instance
*/
getInputProcessors(configuredProcessors?: InputProcessorOrWorkflow[], context?: RequestContext): Promise<InputProcessor[]>;
/**
* Get output processors for this memory instance
* This allows Memory to be used as a ProcessorProvider in Agent's outputProcessors array.
* @param configuredProcessors - Processors already configured by the user (for deduplication)
* @returns Array of output processors configured for this memory instance
*
* Note: We intentionally do NOT check readOnly here. The readOnly check happens at execution time
* in each processor's processOutputResult method. This allows proper isolation when agents share
* a RequestContext - each agent's readOnly setting is respected when its processors actually run,
* not when processors are resolved (which may happen before the agent sets its MastraMemory context).
* See: https://github.com/mastra-ai/mastra/issues/11651
*/
getOutputProcessors(configuredProcessors?: OutputProcessorOrWorkflow[], context?: RequestContext): Promise<OutputProcessor[]>;
abstract deleteMessages(messageIds: MessageDeleteInput, observabilityContext?: Partial<ObservabilityContext>): Promise<void>;
/**
* Clones a thread with all its messages to a new thread
* @param args - Clone parameters including source thread ID and optional filtering options
* @returns Promise resolving to the cloned thread and copied messages
*/
abstract cloneThread(args: StorageCloneThreadInput): Promise<StorageCloneThreadOutput>;
/**
* Get serializable configuration for this memory instance
* @returns Serializable memory configuration
*/
getConfig(): SerializedMemoryConfig;
/**
* Serialize observational memory config to a JSON-safe representation.
* Model references that aren't string IDs are dropped (non-serializable).
*/
private serializeObservationalMemory;
}
//# sourceMappingURL=memory.d.ts.map