@mastra/core
Version:
Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.
221 lines • 11 kB
TypeScript
import type { MastraMessageContentV2 } from '../../../agent/index.js';
import type { MastraDBMessage, StorageThreadType } from '../../../memory/types.js';
import type { StorageResourceType, ThreadOrderBy, ThreadSortDirection, StorageListMessagesInput, StorageListMessagesByResourceIdInput, StorageListMessagesOutput, StorageListThreadsInput, StorageListThreadsOutput, StorageOrderBy, StorageCloneThreadInput, StorageCloneThreadOutput, ObservationalMemoryRecord, ObservationalMemoryHistoryOptions, CreateObservationalMemoryInput, UpdateActiveObservationsInput, UpdateBufferedObservationsInput, UpdateBufferedReflectionInput, SwapBufferedToActiveInput, SwapBufferedToActiveResult, SwapBufferedReflectionToActiveInput, CreateReflectionGenerationInput, UpdateObservationalMemoryConfigInput } from '../../types.js';
import { StorageDomain } from '../base.js';
export declare abstract class MemoryStorage extends StorageDomain {
/**
* Whether this storage adapter supports Observational Memory.
* Adapters that implement OM methods should set this to true.
* Defaults to false for backwards compatibility with custom adapters.
*/
readonly supportsObservationalMemory?: boolean;
constructor();
abstract getThreadById({ threadId, resourceId, }: {
threadId: string;
resourceId?: string;
}): Promise<StorageThreadType | null>;
abstract saveThread({ thread }: {
thread: StorageThreadType;
}): Promise<StorageThreadType>;
abstract updateThread({ id, title, metadata, }: {
id: string;
title: string;
metadata: Record<string, unknown>;
}): Promise<StorageThreadType>;
abstract deleteThread({ threadId }: {
threadId: string;
}): Promise<void>;
abstract listMessages(args: StorageListMessagesInput): Promise<StorageListMessagesOutput>;
/**
* List messages by resource ID only (across all threads).
* Used by Observational Memory and LongMemEval for resource-scoped queries.
*
* @param args - Resource ID and pagination/filtering options
* @returns Paginated list of messages for the resource
*/
listMessagesByResourceId(_args: StorageListMessagesByResourceIdInput): Promise<StorageListMessagesOutput>;
abstract listMessagesById({ messageIds }: {
messageIds: string[];
}): Promise<{
messages: MastraDBMessage[];
}>;
abstract saveMessages(args: {
messages: MastraDBMessage[];
}): Promise<{
messages: MastraDBMessage[];
}>;
abstract updateMessages(args: {
messages: (Partial<Omit<MastraDBMessage, 'createdAt'>> & {
id: string;
content?: {
metadata?: MastraMessageContentV2['metadata'];
content?: MastraMessageContentV2['content'];
};
})[];
}): Promise<MastraDBMessage[]>;
deleteMessages(_messageIds: string[]): Promise<void>;
/**
* List threads with optional filtering by resourceId and metadata.
*
* @param args - Filter, pagination, and ordering options
* @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)
* @returns Paginated list of threads matching the filters
*/
abstract listThreads(args: StorageListThreadsInput): Promise<StorageListThreadsOutput>;
/**
* Clone a thread and its messages to create a new independent thread.
* The cloned thread will have clone metadata stored in its metadata field.
*
* @param args - Clone configuration options
* @returns The newly created thread and the cloned messages
*/
cloneThread(_args: StorageCloneThreadInput): Promise<StorageCloneThreadOutput>;
getResourceById(_: {
resourceId: string;
}): Promise<StorageResourceType | null>;
saveResource(_: {
resource: StorageResourceType;
}): Promise<StorageResourceType>;
updateResource(_: {
resourceId: string;
workingMemory?: string;
metadata?: Record<string, unknown>;
}): Promise<StorageResourceType>;
protected parseOrderBy(orderBy?: StorageOrderBy, defaultDirection?: ThreadSortDirection): {
field: ThreadOrderBy;
direction: ThreadSortDirection;
};
/**
* Get the current observational memory record for a thread/resource.
* Returns the most recent active record.
*/
getObservationalMemory(_threadId: string | null, _resourceId: string): Promise<ObservationalMemoryRecord | null>;
/**
* Get observational memory history (previous generations).
* Returns records in reverse chronological order (newest first).
*/
getObservationalMemoryHistory(_threadId: string | null, _resourceId: string, _limit?: number, _options?: ObservationalMemoryHistoryOptions): Promise<ObservationalMemoryRecord[]>;
/**
* Create a new observational memory record.
* Called when starting observations for a new thread/resource.
*/
initializeObservationalMemory(_input: CreateObservationalMemoryInput): Promise<ObservationalMemoryRecord>;
/**
* Update active observations.
* Called when observations are created and immediately activated (no buffering).
*/
updateActiveObservations(_input: UpdateActiveObservationsInput): Promise<void>;
/**
* Update buffered observations.
* Called when observations are created asynchronously via `bufferTokens`.
*/
updateBufferedObservations(_input: UpdateBufferedObservationsInput): Promise<void>;
/**
* Swap buffered observations to active.
* Atomic operation that:
* 1. Appends bufferedObservations → activeObservations (based on activationRatio)
* 2. Moves activated bufferedMessageIds → observedMessageIds
* 3. Keeps remaining buffered content if activationRatio < 100
* 4. Updates lastObservedAt
*
* Returns info about what was activated for UI feedback.
*/
swapBufferedToActive(_input: SwapBufferedToActiveInput): Promise<SwapBufferedToActiveResult>;
/**
* Create a new generation from a reflection.
* Creates a new record with:
* - originType: 'reflection'
* - activeObservations containing the reflection
* - generationCount incremented from the current record
*/
createReflectionGeneration(_input: CreateReflectionGenerationInput): Promise<ObservationalMemoryRecord>;
/**
* Update buffered reflection (async reflection in progress).
* Called when reflection runs asynchronously via `bufferTokens`.
*/
updateBufferedReflection(_input: UpdateBufferedReflectionInput): Promise<void>;
/**
* Swap buffered reflection to active observations.
* Creates a new generation where activeObservations = bufferedReflection + unreflected observations.
* The `tokenCount` in input is the processor-computed token count for the combined content.
*/
swapBufferedReflectionToActive(_input: SwapBufferedReflectionToActiveInput): Promise<ObservationalMemoryRecord>;
/**
* Set the isReflecting flag.
*/
setReflectingFlag(_id: string, _isReflecting: boolean): Promise<void>;
/**
* Set the isObserving flag.
*/
setObservingFlag(_id: string, _isObserving: boolean): Promise<void>;
/**
* Set the isBufferingObservation flag and update lastBufferedAtTokens.
* Called when async observation buffering starts (true) or ends/fails (false).
* @param id - Record ID
* @param isBuffering - Whether buffering is in progress
* @param lastBufferedAtTokens - The pending token count at which this buffer was triggered (only set when isBuffering=true)
*/
setBufferingObservationFlag(_id: string, _isBuffering: boolean, _lastBufferedAtTokens?: number): Promise<void>;
/**
* Set the isBufferingReflection flag.
* Called when async reflection buffering starts (true) or ends/fails (false).
*/
setBufferingReflectionFlag(_id: string, _isBuffering: boolean): Promise<void>;
/**
* Insert a fully-formed observational memory record.
* Used by thread cloning to copy OM state with remapped IDs.
*/
insertObservationalMemoryRecord(_record: ObservationalMemoryRecord): Promise<void>;
/**
* Clear all observational memory for a thread/resource.
* Removes all records and history.
*/
clearObservationalMemory(_threadId: string | null, _resourceId: string): Promise<void>;
/**
* Set the pending message token count.
* Called at the end of each OM processing step to persist the current
* context window token count so the UI can display it on page load.
*/
setPendingMessageTokens(_id: string, _tokenCount: number): Promise<void>;
/**
* Update the config of an existing observational memory record.
* The provided config is deep-merged into the record's existing config.
*/
updateObservationalMemoryConfig(_input: UpdateObservationalMemoryConfigInput): Promise<void>;
/**
* Deep-merge two plain objects. Available for subclasses to merge
* partial config overrides into existing record configs.
*/
protected deepMergeConfig(target: Record<string, unknown>, source: Record<string, unknown>): Record<string, unknown>;
/**
* Validates metadata keys to prevent SQL injection attacks and prototype pollution.
* Keys must start with a letter or underscore, followed by alphanumeric characters or underscores.
* @param metadata - The metadata object to validate
* @throws Error if any key contains invalid characters or is a disallowed key
*/
protected validateMetadataKeys(metadata: Record<string, unknown> | undefined): void;
/**
* Validates pagination parameters and returns safe offset.
* @param page - Page number (0-indexed)
* @param perPage - Items per page (0 is allowed and returns empty results)
* @throws Error if page is negative, perPage is negative/invalid, or offset would overflow
*/
protected validatePagination(page: number, perPage: number): void;
/**
* Validates pagination input before normalization.
* Use this when accepting raw perPageInput (number | false) from callers.
*
* When perPage is false (fetch all), page must be 0 since pagination is disabled.
* When perPage is a number, delegates to validatePagination for full validation.
*
* @param page - Page number (0-indexed)
* @param perPageInput - Items per page as number, or false to fetch all results
* @throws Error if perPageInput is false and page !== 0
* @throws Error if perPageInput is invalid (not false or a non-negative safe integer)
* @throws Error if page is invalid or offset would overflow
*/
protected validatePaginationInput(page: number, perPageInput: number | false): void;
}
//# sourceMappingURL=base.d.ts.map