UNPKG

@mastra/core

Version:
416 lines • 21.4 kB
import type { MastraMessageContentV2 } from '../../../agent/index.js'; import type { MastraDBMessage, StorageThreadType } from '../../../memory/types.js'; import type { RunFence } from '../../run-fencing.js'; import type { StorageResourceType, ThreadOrderBy, ThreadSortDirection, StorageListMessagesInput, StorageListMessagesByResourceIdInput, StorageListMessagesOutput, StorageListThreadsInput, StorageListThreadsOutput, StorageOrderBy, StorageCloneThreadInput, StorageCloneThreadOutput, StorageCopyThreadOutput, ObservationalMemoryRecord, ObservationalMemoryHistoryOptions, CreateObservationalMemoryInput, UpdateActiveObservationsInput, UpdateActiveObservationsResult, UpdateBufferedObservationsInput, UpdateBufferedObservationsResult, 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; /** Supports groupId, generation bounds, and ordering in OM history queries. */ readonly supportsObservationalMemoryHistorySearch?: boolean; /** * Whether this adapter's `updateThread` treats an omitted `title`/`metadata` * as "leave that column untouched" (partial update). * * Adapters compiled before partial updates existed require both fields and * may write `NULL` into the title column when it is omitted. They won't set * this flag, so `patchThread` backfills the current title for them. * Adapters that implement partial updates must set this to true. */ readonly supportsPartialThreadUpdate?: boolean; /** Whether `listThreads` loads and sorts all matching threads before slicing a page. */ readonly listThreadsPaginatesInMemory?: boolean; /** * Whether this adapter implements `mergeResourceWorkingMemory` as an atomic * read-merge-write that is safe across processes. */ readonly supportsAtomicWorkingMemoryMerge?: boolean; private threadMetadataUpdateQueues; constructor(); abstract getThreadById({ threadId, resourceId, }: { threadId: string; resourceId?: string; }): Promise<StorageThreadType | null>; /** * Whether this adapter implements run fencing: `raiseRunFence`, * `retireRunFence`, and rejecting the writes listed below when their fence is no longer the run's * current fence, atomically with the write. A write's fence is its `fence` * argument, otherwise the one `resolveRunFence()` returns. * * Fenced: `saveThread`, `updateThread`, `patchThread`, * `updateThreadMetadata`, `saveMessages`, `updateMessages`, * `deleteMessages` and `updateResource`. Observational memory writes that * change observations or reflections, and `mergeResourceWorkingMemory` on * adapters that set `supportsAtomicWorkingMemoryMerge`, are fenced through * `resolveRunFence()` only. * * Not fenced: `deleteThread`, `copyThread`, `cloneThread`, * `updateThreadResourceId`, `saveResource`, and observational memory flags, * pending token counts and record initialization. * * Memory fences are raised only for runs claimed in a workflows store that * supports run fencing, so supporting it here has no effect on its own. * * A rejected write throws a `RunFenceConflictError` itself, not wrapped in * another error, and writes nothing. * * Adapters that return true must pass the run-fencing conformance suite. * An adapter that has to probe its backend to know returns a promise, and * rejects when the probe fails: it must never answer false and later true. */ supportsRunFencing(): boolean | Promise<boolean>; /** * Make `fence` the run's current fence in this domain, unless the domain * already holds a newer generation for the run. Returns whether `fence` is * current afterwards. Called once a run is claimed in the workflows domain, * so that writes from older claims are rejected here too. Clears the * fence's `retiredAt` whenever it writes, so a fence raised again is not * pruned while its execution runs. */ raiseRunFence(_fence: RunFence): Promise<boolean>; /** * Mark `fence` as retired once the execution holding it has settled, by * setting `retiredAt` from the store's clock. Only takes effect while * `fence` is still the run's current fence, so a late retire cannot mark a * newer execution's fence. Returns whether it took effect. Retiring does not * change which writes are accepted; it only makes the fence eligible for * `memory.runFences` retention. */ retireRunFence(_fence: RunFence): Promise<boolean>; abstract saveThread({ thread, fence }: { thread: StorageThreadType; fence?: RunFence; }): Promise<StorageThreadType>; /** * Update a thread's title and/or metadata. * * `title` and `metadata` are each optional and independent: omitting one * leaves that column untouched rather than blanking it. Callers that only * need to change metadata (working memory, for example) must omit `title` * instead of reading the thread and passing its title back, because a title * generated between that read and this write would be silently overwritten. */ abstract updateThread({ id, title, metadata, fence, }: { id: string; title?: string; metadata?: Record<string, unknown>; fence?: RunFence; }): Promise<StorageThreadType>; /** * Partial-update a thread's title and/or metadata, tolerating adapters that * predate partial `updateThread` support. * * Adapters that declare `supportsPartialThreadUpdate` receive the arguments * as-is (omitted fields are left untouched). For legacy adapters — whose * `updateThread` writes both columns unconditionally and would blank or * `NULL` an omitted title — the current values are read and backfilled * first. That restores the legacy adapter's previous behavior (including * its title-clobbering race) instead of crashing on a NOT NULL constraint. * * Callers that only change metadata should use this instead of calling * `updateThread` directly. */ patchThread({ id, title, metadata, fence, }: { id: string; title?: string; metadata?: Record<string, unknown>; fence?: RunFence; }): Promise<StorageThreadType>; /** * Serializes a metadata read-modify-write for one thread within this storage instance. * Transaction-capable adapters may override this to provide cross-process atomicity. */ updateThreadMetadata({ id, resourceId, update, fence, }: { id: string; resourceId?: string; update: (thread: StorageThreadType) => Record<string, unknown> | undefined; fence?: RunFence; }): Promise<StorageThreadType | null>; 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[]; fence?: RunFence; }): Promise<{ messages: MastraDBMessage[]; }>; abstract updateMessages(args: { messages: (Partial<Omit<MastraDBMessage, 'createdAt'>> & { id: string; content?: { metadata?: MastraMessageContentV2['metadata']; content?: MastraMessageContentV2['content']; }; })[]; fence?: RunFence; }): Promise<MastraDBMessage[]>; deleteMessages(_messageIds: string[], _options?: { fence?: RunFence; }): 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>; /** * Copy a thread and its messages to a new independent thread without returning * the message payloads. Adapters should copy rows inside the store (e.g. * `INSERT … SELECT`) or stream them in pages so the whole thread never sits on * the Node heap. The new thread carries clone metadata in its metadata field. * * Adapters that only override `cloneThread` get this for free; the payloads it * returns are discarded. * * @param args - Clone configuration options * @returns The newly created thread and the source→new message id map */ copyThread(args: StorageCloneThreadInput): Promise<StorageCopyThreadOutput>; /** * Clone a thread and its messages to create a new independent thread and return * the cloned messages. Defaults to `copyThread` followed by reading the new * thread's messages back, so adapters only need to implement `copyThread`. * * @param args - Clone configuration options * @returns The newly created thread and the cloned messages */ cloneThread(args: StorageCloneThreadInput): Promise<StorageCloneThreadOutput>; /** * Reassign a thread and all of its messages to a different resource. * * Unlike a plain `saveThread`, this preserves the thread's `createdAt` and moves the * `resourceId` of every message row so the thread and its history stay consistent under * the new owner. Same-resource calls are a no-op. Callers are responsible for authorizing * the reassignment; this method performs no ownership checks. * * @param args.threadId - The thread to reassign. * @param args.resourceId - The resource that should own the thread after the call. * @returns The updated thread. */ updateThreadResourceId({ threadId, resourceId, }: { threadId: string; resourceId: string; }): Promise<StorageThreadType>; getResourceById(_: { resourceId: string; }): Promise<StorageResourceType | null>; saveResource(_: { resource: StorageResourceType; }): Promise<StorageResourceType>; updateResource(_: { resourceId: string; workingMemory?: string; metadata?: Record<string, unknown>; fence?: RunFence; }): Promise<StorageResourceType>; /** * Atomically replaces a resource's working memory with `merge(existing)`. * The read and write happen under a lock held across processes, so concurrent * merges never lose each other's changes. Creates the resource if missing. * Adapters that support this must set `supportsAtomicWorkingMemoryMerge`. */ mergeResourceWorkingMemory(_: { resourceId: string; merge: (existing: string | undefined) => string; }): 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). * * Adapters that implement {@link commitActiveObservations} throw here when the write is not * applied, so a caller that only awaits this method can't mistake a rejected write for a * committed one. Use {@link commitActiveObservations} to get the outcome instead. */ updateActiveObservations(_input: UpdateActiveObservationsInput): Promise<void>; /** * Write active observations and report whether they were written. * * Never writes to a superseded record (`{ applied: false, reason: 'retired' }`), and when * `expectedActiveObservations` is given, writes only if the stored text still equals it * (`{ applied: false, reason: 'conflict' }` otherwise). The cursor never moves backward. * * The default delegates to {@link updateActiveObservations} and reports the write as applied, * which keeps adapters that predate this method working unchanged. */ commitActiveObservations(input: UpdateActiveObservationsInput): Promise<UpdateActiveObservationsResult>; /** * Update buffered observations. * Called when observations are created asynchronously via `bufferTokens`. * * Use {@link appendBufferedObservations} to learn where the chunk was stored, or whether it * was skipped. */ updateBufferedObservations(_input: UpdateBufferedObservationsInput): Promise<void>; /** * Append a buffered observation chunk and report where it was stored. * * Appends to the head generation (a superseded `id` is redirected to the head). Skips the * append when the head already holds a chunk with the same `cycleId` or the chunk is wholly * covered by the head's cursor; see {@link UpdateBufferedObservationsResult}. * * The default delegates to {@link updateBufferedObservations} and reports the chunk as stored * on `input.id`, which keeps adapters that predate this method working unchanged. */ appendBufferedObservations(input: UpdateBufferedObservationsInput): Promise<UpdateBufferedObservationsResult>; /** * 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 * * Activates a prefix of the **stored** chunk list (`bufferedChunks` only overrides per-chunk * token weights), never moves the cursor backward, and returns `retired: true` without * writing when the target record was superseded. * * 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 * * See {@link CreateReflectionGenerationInput} for how the stored record (not the snapshot) * decides the carried state, and how superseded or rewritten records are handled. */ 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. * Buffered observation chunks and buffering state move to the new generation, as in * `createReflectionGeneration`. If `currentRecord` was superseded, nothing is created and * the head is returned. */ 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) * * A superseded `id` is redirected to the head generation. */ 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. * A superseded `id` is redirected to the head generation. */ 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