import type { AssistantContent, UserContent, CoreMessage } from '../_types/@internal_ai-sdk-v4@0.0.98/dist/index.js';
import type { MastraDBMessage } from '../agent/message-list/index.js';
import type { AgentSignalType } from '../agent/signals.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 { ErrorProcessor, ErrorProcessorOrWorkflow, InputProcessor, OutputProcessor, InputProcessorOrWorkflow, OutputProcessorOrWorkflow } from '../processors/index.js';
import type { RequestContext } from '../request-context/index.js';
import type { MastraCompositeStore, StorageListMessagesInput, StorageListThreadsInput, StorageListThreadsOutput, StorageCloneThreadInput, StorageCloneThreadOutput, StorageCopyThreadOutput } 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 { CheckThreadFGAOptions } from './thread-fga.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;
    /** Configured embedder output dimension; when set, the dimension probe is skipped. */
    protected readonly embeddingDimension?: number;
    protected threadConfig: MemoryConfigInternal;
    private readonly hasExplicitLastMessages;
    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;
    /**
     * Internal method used by an Agent to record that it resolved this memory, so
     * missing-storage diagnostics can name the agent when the memory has no
     * attached Mastra instance. When several agents share one memory the name is
     * left out, since the failing access cannot be attributed to a single agent.
     * @internal
     */
    __registerAgent(agentName: string): void;
    /**
     * Delete a thread's live event stream from the registered Mastra pubsub.
     * Call after the thread itself is deleted: nothing else ever clears an
     * open-ended thread topic, so without this it lingers until the pubsub's
     * idle TTL (or forever, if the pubsub has none). Best-effort; no-op when
     * no Mastra instance is registered.
     */
    protected clearThreadStream(threadId: string, resourceId?: string): Promise<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?;
    /**
     * Determine the embedder's output dimension: the configured `embeddingDimension` when set,
     * otherwise probe the embedder. The probe 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.
     */
    /**
     * True when the attached vector store produces the embeddings itself, so this Memory sends it
     * text. False whenever an embedder is configured, which keeps the client-side path intact.
     */
    protected get isSelfEmbedding(): boolean;
    /**
     * `semanticRecall.maxChunkChars` from this instance's own options. Per-request memory options
     * can't change it: they arrive from API callers, and a tiny value would cost one embedding and
     * one vector row per character. Chunk boundaries also decide row ids, so they must stay fixed
     * for an index.
     */
    protected get configuredMaxChunkChars(): number | undefined;
    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>;
        /**
         * The run's record of messages already written to the semantic recall index, from
         * `MessageList.getEmbeddedMessages()`. Messages recorded with the same text are not embedded
         * again, and newly embedded ones are added. Agent runs pass it through the save queue;
         * direct callers omit it.
         *
         * @internal
         */
        embeddedMessages?: Map<string, string>;
    }): 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;
        /** @deprecated Use hideSignals: [] to include all, or ['reactive', 'system-reminder'] to hide reminders. */
        includeSystemReminders?: boolean;
        /** true hides all recognized signals, false includes all, or select exact stored types with an array. Overrides includeSystemReminders. */
        hideSignals?: boolean | AgentSignalType[];
        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 update an existing thread
     * @param id - The thread ID to update
     * @param title - The new title for the thread
     * @param metadata - The new metadata for the thread
     * @param memoryConfig - Optional memory config
     * @returns Promise resolving to the updated thread
     */
    abstract updateThread({ id, title, metadata, memoryConfig, }: {
        id: string;
        title?: string;
        metadata?: Record<string, unknown>;
        memoryConfig?: MemoryConfigInternal;
    }): Promise<StorageThreadType>;
    /**
     * Helper method to delete a thread
     * @param threadId - the id of the thread to delete
     */
    abstract deleteThread(threadId: string): Promise<void>;
    /**
     * Resolve once all background work this memory started has finished.
     *
     * Some memory work continues after an agent run returns, and it writes to storage.
     * Callers that own the storage connection should await this before closing it,
     * otherwise background statements can race the close.
     *
     * ```ts
     * await agent.generate('hello', { memory: { thread, resource } });
     * await memory.settled();
     * await store.close();
     * ```
     *
     * Implementations that do no background work can leave this as a no-op.
     */
    settled(): 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: CheckThreadFGAOptions): 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>;
    /**
     * Whether `mergeWorkingMemory` is available (atomic merge supported by storage).
     */
    supportsAtomicWorkingMemoryMerge(): Promise<boolean>;
    /**
     * Atomically deep-merges a partial JSON object into resource-scoped working memory.
     * Implementations without atomic merge support throw.
     */
    mergeWorkingMemory(_: {
        threadId: string;
        resourceId?: string;
        workingMemory: string | Record<string, unknown>;
        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;
    }>;
    protected createMemoryTokenCounter(): {
        countMessage(message: MastraDBMessage): number;
    } | undefined;
    /**
     * 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 error processors for this memory instance.
     * An agent appends these to its resolved `errorProcessors`, so memory can recover from failed
     * model calls (for example, a request rejected for exceeding the context window) without the
     * user registering a processor. They are kept when a call overrides `errorProcessors`.
     * @param configuredProcessors - Error processors already resolved for the agent (for deduplication)
     * @returns Error processors for this memory instance. The base implementation contributes none.
     */
    getErrorProcessors(_configuredProcessors?: ErrorProcessorOrWorkflow[], _context?: RequestContext): Promise<ErrorProcessor[]>;
    /**
     * 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>;
    /**
     * Copies a thread and its messages to a new thread without returning the message
     * payloads. Prefer this over `cloneThread` when only the new thread id is needed
     * (e.g. forking), so large threads never have to be loaded into memory.
     * @param args - Clone parameters including source thread ID and optional filtering options
     * @returns Promise resolving to the new thread and the source→new message id map
     */
    copyThread(args: StorageCloneThreadInput): Promise<StorageCopyThreadOutput>;
    /**
     * Reassign a thread and all of its messages to a different resource.
     * Preserves the thread's `createdAt`. Performs no ownership authorization.
     * @param args - The thread to reassign and the resource that should own it.
     * @returns Promise resolving to the updated thread
     */
    updateThreadResourceId(_args: {
        threadId: string;
        resourceId: string;
        memoryConfig?: MemoryConfigInternal;
    }): Promise<StorageThreadType>;
    /**
     * 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