import { P as ProviderConfig, e as ProviderType, f as Plugin, g as StoredPluginConfig, a as AgentData, S as StorageAdapter, A as AgentConfig, h as AgentFile, R as RAGMetrics, i as RAGDocument, I as IngestOptions, j as IngestResult, B as BulkOperation, k as BulkResult, U as URLSource, l as URLIngestResult, b as ThreadData, T as ThreadConfig, M as MessageRole, c as MessageAttachment, d as MessageData, C as ClientConfig, m as ChatRequest, n as ChatResponse, o as StreamCallbacks, p as RAGPlugin, q as ToolPlugin, r as MiddlewarePlugin, s as AnalyticsPlugin, t as RequestTrackingData, u as ResponseTrackingData, E as ErrorTrackingData, v as Tool, w as RAGContext } from './index-BajTtLGW.mjs'; export { W as AgentNotFoundError, V as AgentSDKError, y as BasePlugin, K as DataTransform, F as IngestDocumentProgress, z as IngestPlanDocument, D as IngestPlanInfo, H as IngestProgressEvent, G as IngestProgressPhase, L as IngestionSchedule, Z as InvalidConfigError, N as PerformanceTimings, Q as PluginRegistryInterface, Y as ProviderNotFoundError, x as RAGConfig, X as ThreadNotFoundError, O as TokenMetrics, J as URLSourceAuth } from './index-BajTtLGW.mjs'; import * as ai from 'ai'; import { LanguageModel, UserModelMessage, AssistantModelMessage, Schema, ToolSet } from 'ai'; export { MemoryStorage } from './storage/MemoryStorage.mjs'; /** * Provider factory for creating language model instances * Supports OpenAI, Anthropic, Google, and Hugging Face providers via Vercel AI SDK */ declare class ProviderFactory { private config; private modelCache; constructor(config: ProviderConfig); /** * Get a language model for the specified provider and model * Uses dynamic imports for edge runtime compatibility */ getModel(provider: ProviderType, modelName: string): Promise; /** * Check if a provider is configured */ isProviderConfigured(provider: ProviderType): boolean; /** * Get list of configured providers */ getConfiguredProviders(): ProviderType[]; /** * Clear the model cache */ clearCache(): void; } /** * Common model names for quick reference * Updated: February 2026 */ declare const Models: { readonly OpenAI: { readonly GPT5: "gpt-5"; readonly GPT5_MINI: "gpt-5-mini"; readonly GPT4O: "gpt-4o"; readonly GPT4O_MINI: "gpt-4o-mini"; readonly O1: "o1"; readonly O1_MINI: "o1-mini"; }; readonly Anthropic: { readonly CLAUDE_4_OPUS: "claude-opus-4-20250514"; readonly CLAUDE_4_SONNET: "claude-sonnet-4-20250514"; readonly CLAUDE_37_SONNET: "claude-3-7-sonnet-latest"; readonly CLAUDE_35_SONNET: "claude-3-5-sonnet-latest"; readonly CLAUDE_35_HAIKU: "claude-3-5-haiku-latest"; }; readonly Google: { readonly GEMINI_2_FLASH: "gemini-2.0-flash"; readonly GEMINI_2_FLASH_LITE: "gemini-2.0-flash-lite"; readonly GEMINI_15_PRO: "gemini-1.5-pro"; readonly GEMINI_15_FLASH: "gemini-1.5-flash"; }; readonly HuggingFace: { readonly META_LLAMA_70B: "meta-llama/Llama-3.3-70B-Instruct"; readonly META_LLAMA_8B: "meta-llama/Meta-Llama-3.1-8B-Instruct"; readonly MISTRAL_NEMO: "mistralai/Mistral-Nemo-Instruct-2407"; readonly QWEN_72B: "Qwen/Qwen2.5-72B-Instruct"; readonly PHI_4: "microsoft/phi-4"; }; }; /** * Plugin Registry for serializing/deserializing plugins * * Plugins are runtime objects that can't be stored in a database. * This registry enables: * 1. Storing serializable plugin configurations in MongoDB * 2. Reinstantiating plugins from stored config when loading agents */ /** * Factory function that creates a plugin instance from config */ type PluginFactory = (config: Record) => T | Promise; /** * Resolves environment variable references in config values * Format: "${ENV_VAR_NAME}" or "${ENV_VAR_NAME:default_value}" * * @example * resolveEnvVars({ apiKey: "${OPENAI_API_KEY}" }) * // Returns: { apiKey: "sk-..." } (actual env value) * * @example * resolveEnvVars({ timeout: "${TIMEOUT:5000}" }) * // Returns: { timeout: "5000" } (default if env not set) */ declare function resolveEnvVars(config: Record): Record; /** * Global plugin registry for managing plugin factories * * @example * // Register a plugin factory * pluginRegistry.register('@snap-agent/rag-ecommerce', (config) => * new EcommerceRAGPlugin(config) * ); * * // Later, instantiate from stored config * const plugin = await pluginRegistry.instantiate({ * type: 'rag', * name: '@snap-agent/rag-ecommerce', * config: { mongoUri: '${MONGO_URI}', voyageApiKey: '${VOYAGE_API_KEY}' } * }); */ declare class PluginRegistry { private registrations; /** * Register a plugin factory * * @param name - Unique plugin identifier (e.g., "@snap-agent/rag-ecommerce") * @param factory - Function that creates plugin instance from config * @param defaultConfig - Optional default configuration values */ register(name: string, factory: PluginFactory, defaultConfig?: Record): void; /** * Unregister a plugin factory */ unregister(name: string): boolean; /** * Check if a plugin is registered */ isRegistered(name: string): boolean; /** * Get all registered plugin names */ getRegisteredPlugins(): string[]; /** * Instantiate a plugin from stored configuration * * @param storedConfig - Serialized plugin configuration from database * @returns Plugin instance * @throws Error if plugin is not registered */ instantiate(storedConfig: StoredPluginConfig): Promise; /** * Instantiate multiple plugins from stored configurations * * @param storedConfigs - Array of serialized plugin configurations * @returns Array of plugin instances (skips disabled plugins) */ instantiateAll(storedConfigs: StoredPluginConfig[]): Promise; /** * Extract serializable configuration from a plugin instance * Requires the plugin to implement getConfig() method * * @param plugin - Plugin instance * @returns Stored plugin configuration */ extractConfig(plugin: Plugin & { getConfig?: () => Record; }): StoredPluginConfig; /** * Extract configurations from multiple plugins */ extractAllConfigs(plugins: Array Record; }>): StoredPluginConfig[]; } /** * Default global plugin registry instance * Use this for simple setups, or create your own PluginRegistry for isolation */ declare const pluginRegistry: PluginRegistry; /** * Create an env var reference for use in stored plugin configs * * @example * const config = { * apiKey: envRef('OPENAI_API_KEY'), * timeout: envRef('TIMEOUT', '5000'), * }; */ declare function envRef(envVarName: string, defaultValue?: string): string; type AIMessage$1 = UserModelMessage | AssistantModelMessage; /** Optional system prompt builder (e.g. chat security sandwich with RAG ordering). */ type BuildSystemPromptFn = (ctx: { instructions: string; ragContexts: string[]; }) => string; interface AgentGenerateOptions { useRAG?: boolean; ragFilters?: Record; threadId?: string; /** Authenticated user behind the turn; threaded into analytics records. */ userId?: string; /** Maximum number of tool-call round-trips before returning. Default: 5 */ maxToolSteps?: number; /** When set, replaces default instructions + RAG concatenation. */ buildSystemPrompt?: BuildSystemPromptFn; /** When true, tools are not passed to the provider. */ disableTools?: boolean; /** * RAG metrics override for analytics. Use when RAG is retrieved outside the * SDK pipeline (e.g. the host prefetches context and passes `useRAG: false`): * the provided fields are merged over the SDK-computed base so the tracked * `rag` metric reflects the real retrieval instead of an empty one. */ ragInfo?: Partial; } /** * Agent class representing an AI agent with persistent state */ declare class Agent { private data; private storage; private providerFactory; private pluginManager; constructor(data: AgentData, storage: StorageAdapter, providerFactory: ProviderFactory); /** * Create a new agent * * If plugins are provided, their configurations will be extracted (if they implement getConfig()) * and stored in the database for later reinstantiation. */ static create(config: AgentConfig, storage: StorageAdapter, providerFactory: ProviderFactory): Promise; /** * Load an existing agent by ID * * Plugins can be attached in three ways (in order of priority): * 1. Direct plugins array - runtime plugin instances passed directly * 2. Plugin registry - reinstantiate from stored configs using registered factories * 3. No plugins - agent loads without plugin functionality * * @param agentId - The agent ID to load * @param storage - Storage adapter * @param providerFactory - Provider factory * @param options - Either: * - Plugin[] array (legacy, for backwards compatibility) * - Options object with plugins and/or registry */ static load(agentId: string, storage: StorageAdapter, providerFactory: ProviderFactory, options?: Plugin[] | { /** Direct plugin instances to attach */ plugins?: Plugin[]; /** Registry to reinstantiate plugins from stored configs */ registry?: PluginRegistry; }): Promise; /** * Update agent properties */ update(updates: Partial): Promise; /** * Delete this agent */ delete(): Promise; /** * Add files to the agent */ addFiles(files: AgentFile[]): Promise; /** * Generate a text response with optional plugin support */ generateResponse(messages: AIMessage$1[], options?: AgentGenerateOptions & { output?: { mode: 'json'; } | { mode: 'object'; schema: Schema; }; }): Promise<{ text: string; parsed?: T; metadata?: Record; }>; /** * Stream a text response with optional plugin support */ streamResponse(messages: AIMessage$1[], onChunk: (chunk: string) => void, onComplete?: (fullText: string, metadata?: Record) => void | Promise, onError?: (error: Error) => void | Promise, options?: AgentGenerateOptions): Promise; /** * Get agent ID */ get id(): string; /** * Get agent name */ get name(): string; /** * Get agent instructions */ get instructions(): string; /** * Get agent provider */ get provider(): string; /** * Get agent model */ get model(): string; /** * Get all plugins attached to this agent */ get plugins(): Plugin[]; /** * Add a plugin to this agent */ addPlugin(plugin: Plugin): void; /** * Remove a plugin by name */ removePlugin(pluginName: string): void; /** * Get all agent data */ toJSON(): AgentData; /** * Ingest documents into RAG plugins * Documents will be ingested into all RAG plugins that support ingestion */ ingestDocuments(documents: RAGDocument[], options?: IngestOptions): Promise; /** * Update a document in RAG plugins */ updateDocument(id: string, document: Partial, options?: IngestOptions): Promise; /** * Delete documents from RAG plugins */ deleteDocuments(ids: string | string[], options?: IngestOptions): Promise; /** * Perform bulk operations on RAG plugins */ bulkDocumentOperations(operations: BulkOperation[], options?: IngestOptions): Promise; /** * Ingest documents from a URL source (CSV, JSON, XML, API) * Supports authentication, scheduling, and data transformation */ ingestFromUrl(source: URLSource, options?: IngestOptions): Promise; /** * Handle webhook payload for real-time document updates * Useful for product inventory updates, price changes, etc. */ handleWebhook(payload: any, source: string, options?: IngestOptions): Promise; } type AIMessage = UserModelMessage | AssistantModelMessage; /** * Thread class representing a conversation thread */ declare class Thread { private data; private storage; constructor(data: ThreadData, storage: StorageAdapter); /** * Create a new thread */ static create(config: ThreadConfig, storage: StorageAdapter): Promise; /** * Load an existing thread by ID */ static load(threadId: string, storage: StorageAdapter): Promise; /** * Update thread properties */ update(updates: Partial): Promise; /** * Delete this thread */ delete(): Promise; /** * Add a message to the thread */ addMessage(role: MessageRole, content: string, attachments?: MessageAttachment[], metadata?: Record): Promise; /** * Get messages from this thread */ getMessages(limit?: number): Promise; /** * Get conversation context for AI (formatted for Vercel AI SDK) */ getConversationContext(maxMessages?: number): Promise; /** * Update thread name */ updateName(name: string): Promise; /** * Update pending status */ updatePendingStatus(isPending: boolean): Promise; /** * Get thread ID */ get id(): string; /** * Get thread name */ get name(): string | undefined; /** * Get agent ID */ get agentId(): string; /** * Get messages (cached from last load) */ get messages(): MessageData[]; /** * Check if thread is pending */ get isPending(): boolean; /** * Get all thread data */ toJSON(): ThreadData; } /** * Main SDK Client for managing AI agents and conversations */ declare class AgentClient { private storage; private providerFactory; private providers; private pluginRegistry?; constructor(config: ClientConfig); private validateConfig; /** * Create a new agent */ createAgent(config: Omit & { provider?: AgentConfig['provider']; }): Promise; /** * Get an agent by ID * * Plugin loading priority: * 1. Direct plugins array passed to this method * 2. Plugin registry (if configured) - reinstantiates from stored configs * 3. No plugins * * @param agentId - The agent ID to load * @param options - Either Plugin[] for backwards compatibility, or options object */ getAgent(agentId: string, options?: Plugin[] | { /** Direct plugin instances to attach (highest priority) */ plugins?: Plugin[]; /** Override the client's registry for this call */ registry?: PluginRegistry; }): Promise; /** * List agents for a user */ listAgents(userId: string, organizationId?: string): Promise; /** * Delete an agent */ deleteAgent(agentId: string): Promise; /** * Create a new thread */ createThread(config: ThreadConfig): Promise; /** * Get a thread by ID */ getThread(threadId: string | undefined): Promise; /** * List threads by user or agent */ listThreads(filters: { userId?: string; agentId?: string; organizationId?: string; }): Promise; /** * Delete a thread */ deleteThread(threadId: string): Promise; /** * Send a message and get a response (non-streaming) */ chat(request: ChatRequest): Promise; /** * Send a message and stream the response */ chatStream(request: ChatRequest, callbacks: StreamCallbacks): Promise; /** * Generate a name for a thread based on its first message */ generateThreadName(firstMessage: string): Promise; /** * Get list of configured providers */ getConfiguredProviders(): ProviderType[]; /** * Check if a provider is configured */ isProviderConfigured(provider: string): boolean; } /** * Plugin Manager * Manages and orchestrates plugin execution for agents */ declare class PluginManager { private plugins; constructor(plugins?: Plugin[]); getRAGPlugins(): RAGPlugin[]; getToolPlugins(): ToolPlugin[]; /** * Convert all tool plugins into an AI SDK ToolSet ready for generateText/streamText. * Returns undefined when no tool plugins are registered (so the LLM call * omits the tools parameter entirely). */ getAISDKTools(): ToolSet | undefined; getMiddlewarePlugins(): MiddlewarePlugin[]; getAnalyticsPlugins(): AnalyticsPlugin[]; getAllPlugins(): Plugin[]; /** * Execute all RAG plugins and merge their contexts * Returns an array of context strings, one per plugin */ executeRAG(message: string, options: { agentId: string; threadId?: string; filters?: Record; metadata?: Record; }): Promise<{ contexts: string[]; allMetadata: Record[]; }>; /** * Execute all middleware plugins before request */ executeBeforeRequest(messages: any[], context: { agentId: string; threadId?: string; }): Promise<{ messages: any[]; metadata?: any; }>; /** * Execute all middleware plugins after response */ executeAfterResponse(response: string, context: { agentId: string; threadId?: string; metadata?: any; }): Promise<{ response: string; metadata?: any; }>; /** * Track request in all analytics plugins */ trackRequest(data: { agentId: string; threadId?: string; userId?: string; correlationId?: string; message: string; timestamp: Date; }): Promise; /** * Track response in all analytics plugins */ trackResponse(data: { agentId: string; threadId?: string; response: string; latency: number; tokensUsed?: number; timestamp: Date; }): Promise; /** * Track request (extended) in all analytics plugins that support it */ trackRequestExtended(data: RequestTrackingData): Promise; /** * Track response (extended) in all analytics plugins that support it */ trackResponseExtended(data: ResponseTrackingData): Promise; /** * Track an error in all analytics plugins that support it */ trackError(data: ErrorTrackingData): Promise; /** * Check if any plugins of a specific type exist */ hasPluginsOfType(type: Plugin['type']): boolean; /** * Get plugin by name */ getPluginByName(name: string): Plugin | undefined; } /** * Convert a single SnapAgent Tool definition into an AI SDK tool object. * * The AI SDK expects `inputSchema` to be a Schema (Zod or jsonSchema wrapper). * Our Tool interface uses a plain JSON Schema object for `parameters`, so we * wrap it with `jsonSchema()` and map it to `inputSchema`. */ declare function convertTool(snapTool: Tool): { description: string; inputSchema: ai.Schema; execute: (args: any) => Promise; }; /** * Convert an array of ToolPlugin instances into an AI SDK ToolSet. * * The ToolSet is a `Record` keyed by tool name, which is the * format that `generateText()` and `streamText()` expect. * * @example * ```ts * const plugins: ToolPlugin[] = [weatherPlugin, calculatorPlugin]; * const tools = convertToolPlugins(plugins); * // tools = { get_weather: AISdkTool, calculate: AISdkTool } * * const result = await generateText({ model, messages, tools }); * ``` */ declare function convertToolPlugins(plugins: ToolPlugin[]): ToolSet; /** * Configuration for the default RAG plugin */ interface DefaultRAGConfig { /** * API key for the embedding provider */ embeddingProviderApiKey: string; /** * Embedding provider to use * @default 'openai' */ embeddingProvider?: 'openai'; /** * OpenAI embedding model * @default 'text-embedding-3-small' */ embeddingModel?: string; /** * Number of results to return from search * @default 5 */ limit?: number; } /** * Default RAG Plugin * * A minimal, zero-config RAG plugin that provides basic document storage, * embedding generation, and semantic search capabilities. * * Features: * - In-memory vector storage (for simplicity) * - OpenAI embeddings * - Cosine similarity search * - Simple ingestion and retrieval * * For production use cases with advanced features (attribute extraction, * rescoring, reranking, etc.), use specialized plugins like @snap-agent/rag-ecommerce */ declare class DefaultRAGPlugin implements RAGPlugin { name: string; type: "rag"; private config; private documents; constructor(config: DefaultRAGConfig); /** * Retrieve context for a message using semantic search */ retrieveContext(message: string, options: { agentId: string; threadId?: string; filters?: Record; metadata?: Record; }): Promise; /** * Ingest documents into the RAG system */ ingest(documents: RAGDocument[], options?: IngestOptions): Promise; /** * Update a single document */ update(id: string, document: Partial, options?: IngestOptions): Promise; /** * Delete document(s) by ID */ delete(ids: string | string[], options?: IngestOptions): Promise; /** * Generate embedding using OpenAI */ private generateEmbedding; /** * Calculate cosine similarity between two vectors */ private cosineSimilarity; /** * Get statistics about stored documents */ getStats(): Record; /** * Clear all documents for an agent */ clearAgent(agentId: string): void; /** * Clear all documents */ clearAll(): void; } declare function createClient(config: ClientConfig): AgentClient; export { Agent, AgentClient, AgentConfig, AgentData, AgentFile, type AgentGenerateOptions, AnalyticsPlugin, type BuildSystemPromptFn, BulkOperation, BulkResult, ChatRequest, ChatResponse, ClientConfig, type DefaultRAGConfig, DefaultRAGPlugin, ErrorTrackingData, IngestOptions, IngestResult, MessageAttachment, MessageData, MessageRole, MiddlewarePlugin, Models, Plugin, type PluginFactory, PluginManager, PluginRegistry, ProviderConfig, ProviderFactory, ProviderType, RAGContext, RAGDocument, RAGMetrics, RAGPlugin, RequestTrackingData, ResponseTrackingData, StorageAdapter, StoredPluginConfig, StreamCallbacks, Thread, ThreadConfig, ThreadData, Tool, ToolPlugin, URLIngestResult, URLSource, convertTool, convertToolPlugins, createClient, envRef, pluginRegistry, resolveEnvVars };