/** * Plugin system for extending agent capabilities */ interface BasePlugin { name: string; type: 'rag' | 'tool' | 'middleware' | 'analytics'; priority?: number; /** * Optional: Return serializable configuration for persistence * Used by PluginRegistry to store plugin config in database * Should NOT include sensitive values - use env var references instead * * @example * getConfig() { * return { * mongoUri: '${MONGO_URI}', // Reference to env var * embeddingModel: 'voyage-3-lite', // Safe to store * limit: 10, * }; * } */ getConfig?(): Record; } interface RAGContext { content: string; sources?: Array<{ id: string; title?: string; score?: number; type?: string; [key: string]: any; }>; metadata?: Record; } /** * Document to be ingested into RAG system */ interface RAGDocument { id: string; content: string; metadata?: Record; } /** * Result of an ingestion operation */ interface IngestResult { success: boolean; indexed: number; failed: number; errors?: Array<{ id: string; error: string; }>; metadata?: Record; } /** * Per-document row in the ingest plan (chunk counts before any embedding). */ interface IngestPlanDocument { documentId: string; chunkCount: number; } /** * Emitted once after all documents are chunked in memory, before embeddings run. * Use this to size progress bars (global and per-document). */ interface IngestPlanInfo { totalChunks: number; documents: IngestPlanDocument[]; } /** Progress for a single document in a snapshot (chunks done vs planned total). */ interface IngestDocumentProgress { chunksDone: number; chunksTotal: number; } /** * `embedding` — about to call the embedding provider for this chunk. * `stored` — chunk was written to storage; `processedGlobal` counts this chunk. */ type IngestProgressPhase = 'embedding' | 'stored'; /** * Fine-grained ingest progress (implemented by DocsRAGPlugin; other RAG plugins may ignore). */ interface IngestProgressEvent { phase: IngestProgressPhase; documentId: string; /** 0-based index of the chunk within the document */ chunkIndex: number; chunksInDocument: number; /** Chunks fully persisted so far in this ingest call (only advances on `stored`) */ processedGlobal: number; totalGlobal: number; /** Snapshot: every documentId from the plan with done/total counts */ byDocument: Record; } /** * Options for ingestion operations */ interface IngestOptions { agentId?: string; batchSize?: number; skipExisting?: boolean; overwrite?: boolean; /** * Called once after chunking all documents, before any embedding. * DocsRAGPlugin (and optionally others) may invoke this. */ onIngestPlan?: (plan: IngestPlanInfo) => void | Promise; /** * Called around each chunk: `embedding` before the provider call, `stored` after persistence. * On `stored`, `processedGlobal` increases by 1. */ onIngestProgress?: (event: IngestProgressEvent) => void | Promise; [key: string]: any; } /** * Options for bulk operations * For 'insert': document with full RAGDocument required * For 'update': document with Partial optional * For 'delete': document not needed */ type BulkOperation = { type: 'insert'; id: string; document: RAGDocument; } | { type: 'update'; id: string; document?: Partial; } | { type: 'delete'; id: string; document?: never; }; interface BulkResult { success: boolean; inserted: number; updated: number; deleted: number; failed: number; errors?: Array<{ id: string; operation: string; error: string; }>; } /** * Authentication configuration for URL-based ingestion */ type URLSourceAuth = { type: 'bearer'; token: string; } | { type: 'basic'; username: string; password: string; } | { type: 'api-key'; header: string; key: string; } | { type: 'custom'; headers: Record; }; /** * Configuration for transforming external data to RAGDocuments */ interface DataTransform { documentPath?: string; fieldMapping?: { id?: string; content?: string; [key: string]: string | undefined; }; customTransform?: (data: any) => RAGDocument[]; } /** * Schedule configuration for recurring ingestion */ interface IngestionSchedule { cron?: string; interval?: number; timezone?: string; } /** * URL source configuration for data ingestion */ interface URLSource { url: string; type: 'json' | 'csv' | 'xml' | 'api'; auth?: URLSourceAuth; transform?: DataTransform; schedule?: IngestionSchedule; headers?: Record; timeout?: number; metadata?: Record; } /** * Result of URL-based ingestion */ interface URLIngestResult extends IngestResult { sourceUrl: string; fetchedAt: Date; documentsFetched: number; scheduleId?: string; } interface RAGPlugin extends BasePlugin { type: 'rag'; /** * Retrieve contextual information for a message */ retrieveContext(message: string, options: { agentId: string; threadId?: string; filters?: Record; metadata?: Record; }): Promise; /** * Optional: Format the context for the LLM * If not provided, RAGContext.content will be used directly */ formatContext?(context: RAGContext): string; /** * Optional: Ingest documents into the RAG system * Allows plugins to provide their own indexing logic */ ingest?(documents: RAGDocument[], options?: IngestOptions): Promise; /** * Optional: Ingest documents from a URL source * Supports CSV, JSON, XML, and API endpoints with authentication and scheduling */ ingestFromUrl?(source: URLSource, options?: IngestOptions): Promise; /** * Optional: Handle webhook payloads for real-time updates * Useful for product updates, inventory changes, etc. */ handleWebhook?(payload: any, source: string, options?: IngestOptions): Promise; /** * Optional: Update a single document */ update?(id: string, document: Partial, options?: IngestOptions): Promise; /** * Optional: Delete document(s) by ID */ delete?(ids: string | string[], options?: IngestOptions): Promise; /** * Optional: Bulk operations for efficient batch processing */ bulk?(operations: BulkOperation[], options?: IngestOptions): Promise; } interface Tool { name: string; description: string; parameters: Record; execute: (args: any) => Promise; } interface ToolPlugin extends BasePlugin { type: 'tool'; getTools(): Tool[]; } interface MiddlewarePlugin extends BasePlugin { type: 'middleware'; beforeRequest?(messages: any[], context: { agentId: string; threadId?: string; }): Promise<{ messages: any[]; metadata?: any; }>; afterResponse?(response: string, context: { agentId: string; threadId?: string; metadata?: any; }): Promise<{ response: string; metadata?: any; }>; } /** * Performance timing breakdown */ interface PerformanceTimings { total: number; llmApiTime?: number; ragRetrievalTime?: number; pluginExecutionTime?: number; dbQueryTime?: number; timeToFirstToken?: number; timeToLastToken?: number; queueTime?: number; } /** * RAG-specific metrics */ interface RAGMetrics { enabled: boolean; documentsRetrieved?: number; vectorSearchTime?: number; embeddingTime?: number; cacheHit?: boolean; avgSimilarityScore?: number; rerankTime?: number; contextLength?: number; contextTokens?: number; sourcesCount?: number; } /** * Token and cost metrics */ interface TokenMetrics { promptTokens: number; completionTokens: number; totalTokens: number; estimatedCost?: number; embeddingTokens?: number; embeddingCost?: number; } /** * Request tracking data (extended) */ interface RequestTrackingData { agentId: string; threadId?: string; userId?: string; organizationId?: string; /** Links the request/response/error records of a single agent turn. */ correlationId?: string; message: string; messageLength: number; timestamp: Date; model?: string; provider?: string; } /** * Response tracking data (extended) */ interface ResponseTrackingData { agentId: string; threadId?: string; userId?: string; organizationId?: string; /** Links the request/response/error records of a single agent turn. */ correlationId?: string; response: string; responseLength: number; timestamp: Date; timings: PerformanceTimings; tokens: TokenMetrics; rag?: RAGMetrics; success: boolean; errorType?: string; errorMessage?: string; status?: 'success' | 'error' | 'blocked'; level?: 'info' | 'warning' | 'error'; warningReasons?: string[]; component?: 'llm' | 'rag' | 'plugin' | 'database' | 'network' | 'moderation'; model?: string; provider?: string; } /** * Error tracking data */ interface ErrorTrackingData { agentId: string; threadId?: string; userId?: string; /** Links the request/response/error records of a single agent turn. */ correlationId?: string; timestamp: Date; errorType: string; errorMessage: string; errorCode?: string; isRetryable?: boolean; component?: 'llm' | 'rag' | 'plugin' | 'database' | 'network'; } interface AnalyticsPlugin extends BasePlugin { type: 'analytics'; /** * Track incoming request (basic - for backwards compatibility) */ trackRequest(data: { agentId: string; threadId?: string; userId?: string; correlationId?: string; message: string; timestamp: Date; }): Promise; /** * Track response (basic - for backwards compatibility) */ trackResponse(data: { agentId: string; threadId?: string; response: string; latency: number; tokensUsed?: number; timestamp: Date; }): Promise; /** * Track request with extended data (optional) */ trackRequestExtended?(data: RequestTrackingData): Promise; /** * Track response with extended metrics (optional) */ trackResponseExtended?(data: ResponseTrackingData): Promise; /** * Track errors (optional) */ trackError?(data: ErrorTrackingData): Promise; /** * Get aggregated metrics (optional) */ getMetrics?(options?: { agentId?: string; startDate?: Date; endDate?: Date; groupBy?: 'hour' | 'day' | 'week' | 'month'; }): Promise>; } type Plugin = RAGPlugin | ToolPlugin | MiddlewarePlugin | AnalyticsPlugin; /** * Serializable plugin configuration stored in database * Used to reinstantiate plugins when loading agents */ interface StoredPluginConfig { /** * Plugin type (rag, middleware, analytics, tool) */ type: Plugin['type']; /** * Unique plugin identifier (e.g., "@snap-agent/rag-ecommerce") * Used to look up the factory function in the registry */ name: string; /** * Serializable configuration for the plugin * Use env var references for sensitive values: "${ENV_VAR_NAME}" */ config: Record; /** * Plugin priority (lower = executed first) */ priority?: number; /** * Whether this plugin is enabled */ enabled?: boolean; } type ProviderType = 'openai' | 'anthropic' | 'google' | 'huggingface'; interface ProviderConfig { openai?: { apiKey: string; }; anthropic?: { apiKey: string; }; google?: { apiKey: string; }; huggingface?: { apiKey: string; }; } /** * RAG configuration for zero-config RAG setup */ interface RAGConfig { /** * Enable RAG with default plugin */ enabled: boolean; /** * API key for embedding provider * If not provided, will use the provider's API key from ClientConfig */ embeddingProviderApiKey?: string; /** * Embedding provider to use * @default 'openai' */ embeddingProvider?: 'openai'; /** * Embedding model to use * @default 'text-embedding-3-small' */ embeddingModel?: string; /** * Number of results to return * @default 5 */ limit?: number; } interface AgentConfig { name: string; description?: string; instructions: string; provider: ProviderType; model: string; userId: string; metadata?: Record; organizationId?: string; phone?: string; plugins?: Plugin[]; pluginConfigs?: StoredPluginConfig[]; rag?: RAGConfig; } interface AgentData extends AgentConfig { id: string; createdAt: Date; updatedAt: Date; files: AgentFile[]; } interface AgentFile { fileId: string; filename: string; addedAt: Date; } interface ThreadConfig { agentId: string; userId: string; name?: string; metadata?: Record; organizationId?: string; endUserId?: string; } interface ThreadData extends ThreadConfig { id: string; createdAt: Date; updatedAt: Date; messages: MessageData[]; isPendingThread: boolean; } type MessageRole = 'user' | 'assistant' | 'system'; interface MessageData { id: string; role: MessageRole; content: string; timestamp: Date; metadata?: Record; attachments?: MessageAttachment[]; } interface MessageAttachment { fileId: string; filename: string; contentType: string; size: number; } interface ChatRequest { threadId: string; message: string; attachments?: MessageAttachment[]; useRAG?: boolean; ragFilters?: Record; contextLength?: number; emptyResponsePolicy?: 'allow' | 'error'; } interface ChatResponse { reply: string; messageId: string; threadId: string; timestamp: Date; metadata?: Record; usage?: { promptTokens: number; completionTokens: number; totalTokens: number; }; } interface StreamCallbacks { onChunk: (chunk: string) => void; onComplete: (fullResponse: string, metadata?: Record) => void | Promise; onError: (error: Error) => void | Promise; } interface StorageAdapter { createAgent(config: AgentConfig): Promise; getAgent(agentId: string): Promise; updateAgent(agentId: string, updates: Partial): Promise; deleteAgent(agentId: string): Promise; listAgents(userId: string, organizationId?: string): Promise; createThread(config: ThreadConfig): Promise; getThread(threadId: string): Promise; updateThread(threadId: string, updates: Partial): Promise; deleteThread(threadId: string): Promise; listThreads(filters: { userId?: string; agentId?: string; organizationId?: string; }): Promise; addMessage(threadId: string, role: MessageRole, content: string, attachments?: MessageAttachment[], metadata?: Record): Promise; getMessages(threadId: string, limit?: number): Promise; getConversationContext(threadId: string, maxMessages?: number): Promise>; } /** * Plugin registry for reinstantiating plugins from stored configs * Import from '@snap-agent/core' or create your own instance */ interface PluginRegistryInterface { instantiateAll(storedConfigs: StoredPluginConfig[]): Promise; isRegistered(name: string): boolean; } interface ClientConfig { storage: StorageAdapter; providers: ProviderConfig; /** * Optional plugin registry for automatic plugin reinstantiation * When provided, agents loaded with getAgent() will automatically * reinstantiate their plugins from stored configurations */ pluginRegistry?: PluginRegistryInterface; } declare class AgentSDKError extends Error { constructor(message: string); } declare class AgentNotFoundError extends AgentSDKError { constructor(agentId: string); } declare class ThreadNotFoundError extends AgentSDKError { constructor(threadId: string); } declare class ProviderNotFoundError extends AgentSDKError { constructor(provider: string); } declare class InvalidConfigError extends AgentSDKError { constructor(message: string); } export { type AgentConfig as A, type BulkOperation as B, type ClientConfig as C, type IngestPlanInfo as D, type ErrorTrackingData as E, type IngestDocumentProgress as F, type IngestProgressPhase as G, type IngestProgressEvent as H, type IngestOptions as I, type URLSourceAuth as J, type DataTransform as K, type IngestionSchedule as L, type MessageRole as M, type PerformanceTimings as N, type TokenMetrics as O, type ProviderConfig as P, type PluginRegistryInterface as Q, type RAGMetrics as R, type StorageAdapter as S, type ThreadConfig as T, type URLSource as U, AgentSDKError as V, AgentNotFoundError as W, ThreadNotFoundError as X, ProviderNotFoundError as Y, InvalidConfigError as Z, type AgentData as a, type ThreadData as b, type MessageAttachment as c, type MessageData as d, type ProviderType as e, type Plugin as f, type StoredPluginConfig as g, type AgentFile as h, type RAGDocument as i, type IngestResult as j, type BulkResult as k, type URLIngestResult as l, type ChatRequest as m, type ChatResponse as n, type StreamCallbacks as o, type RAGPlugin as p, type ToolPlugin as q, type MiddlewarePlugin as r, type AnalyticsPlugin as s, type RequestTrackingData as t, type ResponseTrackingData as u, type Tool as v, type RAGContext as w, type RAGConfig as x, type BasePlugin as y, type IngestPlanDocument as z };