@snap-agent/core 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # SnapAgent
2
2
 
3
- **The AI Agent SDK that runs everywhere.** A TypeScript-first SDK for building stateful AI agents with multi-provider support (OpenAI, Anthropic, Google). Extensible via plugins. Edge-runtime compatible.
3
+ **The AI Agent SDK that runs everywhere.** A TypeScript-first SDK for building stateful AI agents with multi-provider support. Extensible via plugins. Edge-runtime compatible.
4
4
 
5
5
  ## Why SnapAgent?
6
6
 
@@ -10,6 +10,7 @@
10
10
  | **Bundle Size** | ~63 KB | ~150 KB | ~2 MB+ |
11
11
  | **Multi-Provider** | OpenAI, Anthropic, Google | OpenAI only | ✅ |
12
12
  | **Plugin Architecture** | RAG, Tools, Middleware, Analytics | Tools only | Chains |
13
+ | **Plugin Persistence** | ✅ Registry pattern | ❌ | ❌ |
13
14
  | **Persistent Storage** | Upstash, MongoDB, Memory | In-memory only | Via integrations |
14
15
  | **Zero-Config RAG** | Built-in | Manual | Manual |
15
16
 
@@ -18,6 +19,7 @@
18
19
  - **Multi-Provider** — Switch between OpenAI, Anthropic, and Google seamlessly
19
20
  - **Edge Runtime** — Deploy to Cloudflare Workers, Vercel Edge, Deno Deploy
20
21
  - **Plugin Architecture** — Extend with RAG, tools, middleware, and analytics plugins
22
+ - **Plugin Persistence** — Plugins survive server restarts via the Plugin Registry
21
23
  - **Persistent Storage** — Upstash Redis (edge), MongoDB (server), or bring your own
22
24
  - **Zero-Config RAG** — Add semantic search with one line of config
23
25
  - **Stateful Threads** — Automatic conversation history management
@@ -201,12 +203,45 @@ SnapAgent is built around a powerful plugin system. Extend your agents with any
201
203
  | **Middleware Plugins** | Intercept and transform requests/responses | Rate limiting, content moderation, logging |
202
204
  | **Analytics Plugins** | Track usage and performance | Monitoring, billing, optimization |
203
205
 
204
- ### Combining Multiple Plugins
206
+ ### Understanding Plugin Types
207
+
208
+ All extensions are added to the `plugins` array, but they serve different purposes:
209
+
210
+ ```
211
+ ┌─────────────────────────────────────────────────────────────────┐
212
+ │ plugins: [...] │
213
+ ├─────────────────────────────────────────────────────────────────┤
214
+ │ │
215
+ │ MIDDLEWARES (run first, intercept requests) │
216
+ │ ├── RateLimiter → Abuse prevention (100 req/min) │
217
+ │ ├── TokenBudget → Cost control ($10/day) │
218
+ │ ├── ContentModeration → Block harmful content │
219
+ │ └── SlackNotifications → Alert on errors │
220
+ │ │
221
+ │ PLUGINS (enhance agent capabilities) │
222
+ │ ├── EcommerceRAGPlugin → Product search knowledge │
223
+ │ ├── DocsRAGPlugin → Documentation knowledge │
224
+ │ └── CustomTools → Callable functions │
225
+ │ │
226
+ │ ANALYTICS (run last, track everything) │
227
+ │ ├── SnapAgentAnalytics → Full metrics suite │
228
+ │ └── ConsoleAnalytics → Dev-friendly logging │
229
+ │ │
230
+ └─────────────────────────────────────────────────────────────────┘
231
+ ```
232
+
233
+ **Execution order is handled automatically** via the `priority` field:
234
+ - Middlewares: priority 1-100 (run first)
235
+ - RAG/Tools: priority 100-150
236
+ - Analytics: priority 200+ (run last)
237
+
238
+ ### Combining Plugins and Middlewares
205
239
 
206
240
  ```typescript
207
241
  import { createClient, MemoryStorage } from '@snap-agent/core';
208
242
  import { EcommerceRAGPlugin } from '@snap-agent/rag-ecommerce';
209
243
  import { RateLimiter } from '@snap-agent/middleware-ratelimit';
244
+ import { TokenBudget } from '@snap-agent/middleware-budget';
210
245
  import { SlackNotifications } from '@snap-agent/middleware-slack';
211
246
  import { ConsoleAnalytics } from '@snap-agent/analytics-console';
212
247
 
@@ -217,27 +252,35 @@ const agent = await client.createAgent({
217
252
  model: 'gpt-4o',
218
253
  userId: 'user-123',
219
254
  plugins: [
220
- // RAG: Search product catalog
221
- new EcommerceRAGPlugin({
222
- mongoUri: process.env.MONGODB_URI!,
223
- openaiApiKey: process.env.OPENAI_API_KEY!,
224
- tenantId: 'my-store',
225
- }),
226
-
227
- // Middleware: Rate limiting
228
- new RateLimiter({
255
+ // ─────────────────────────────────────────────────────────────
256
+ // MIDDLEWARES: Request/response interception (run first)
257
+ // ─────────────────────────────────────────────────────────────
258
+ new RateLimiter({ // Abuse prevention
229
259
  maxRequests: 100,
230
260
  windowMs: 60000,
231
261
  }),
232
-
233
- // Middleware: Slack alerts on errors
234
- new SlackNotifications({
262
+ new TokenBudget({ // Cost control
263
+ maxCostPerPeriod: 10.00,
264
+ period: 'day',
265
+ }),
266
+ new SlackNotifications({ // Error alerts
235
267
  webhookUrl: process.env.SLACK_WEBHOOK!,
236
- onError: true,
268
+ triggers: { onError: true },
237
269
  }),
238
-
239
- // Analytics: Log everything
240
- new ConsoleAnalytics(),
270
+
271
+ // ─────────────────────────────────────────────────────────────
272
+ // PLUGINS: Agent capabilities (RAG, tools)
273
+ // ─────────────────────────────────────────────────────────────
274
+ new EcommerceRAGPlugin({ // Product knowledge
275
+ mongoUri: process.env.MONGODB_URI!,
276
+ openaiApiKey: process.env.OPENAI_API_KEY!,
277
+ tenantId: 'my-store',
278
+ }),
279
+
280
+ // ─────────────────────────────────────────────────────────────
281
+ // ANALYTICS: Tracking and monitoring (run last)
282
+ // ─────────────────────────────────────────────────────────────
283
+ new ConsoleAnalytics({ level: 'standard' }),
241
284
  ],
242
285
  });
243
286
  ```
@@ -278,19 +321,230 @@ class CustomAnalytics implements AnalyticsPlugin {
278
321
  }
279
322
  ```
280
323
 
281
- ### Available Plugins
324
+ ### Plugin Persistence with Plugin Registry
325
+
326
+ Plugins are runtime objects (classes with methods, database connections, etc.) that can't be directly saved to a database. The **Plugin Registry** solves this by:
327
+
328
+ 1. Storing serializable plugin configurations in your database
329
+ 2. Automatically reinstantiating plugins when you load an agent after a process restart
330
+
331
+ #### Why Plugin Persistence Matters
332
+
333
+ Without the Plugin Registry, you'd lose all plugins when:
334
+ - Your server restarts
335
+ - A request is routed to a different server instance
336
+ - You load an agent from the database in a new process
337
+
338
+ #### Setting Up the Plugin Registry
339
+
340
+ ```typescript
341
+ import {
342
+ createClient,
343
+ PluginRegistry,
344
+ MongoDBStorage
345
+ } from '@snap-agent/core';
346
+ import { EcommerceRAGPlugin } from '@snap-agent/rag-ecommerce';
347
+ import { RateLimiter } from '@snap-agent/middleware-ratelimit';
348
+
349
+ // 1. Create and configure the registry
350
+ const registry = new PluginRegistry();
351
+
352
+ // 2. Register plugin factories (plugin name → factory function)
353
+ registry.register('@snap-agent/rag-ecommerce', (config) =>
354
+ new EcommerceRAGPlugin(config)
355
+ );
356
+
357
+ registry.register('@snap-agent/middleware-ratelimit', (config) =>
358
+ new RateLimiter(config)
359
+ );
360
+
361
+ // 3. Create client with registry
362
+ const client = createClient({
363
+ storage: new MongoDBStorage(process.env.MONGODB_URI!),
364
+ providers: { openai: { apiKey: process.env.OPENAI_API_KEY! } },
365
+ pluginRegistry: registry, // ← Enable automatic plugin reinstantiation
366
+ });
367
+ ```
368
+
369
+ #### Making Plugins Persistable
370
+
371
+ For a plugin's configuration to be saved, it must implement the `getConfig()` method:
372
+
373
+ ```typescript
374
+ class MyRAGPlugin implements RAGPlugin {
375
+ type = 'rag' as const;
376
+ name = '@myorg/my-rag-plugin'; // Unique identifier
377
+
378
+ private config: MyPluginConfig;
379
+
380
+ constructor(config: MyPluginConfig) {
381
+ this.config = config;
382
+ }
383
+
384
+ // Return serializable configuration
385
+ // Use env var references for sensitive values!
386
+ getConfig() {
387
+ return {
388
+ // Safe: Use env var reference (not the actual secret)
389
+ apiKey: '${MY_API_KEY}',
390
+ mongoUri: '${MONGODB_URI}',
391
+
392
+ // Safe: Non-sensitive values stored directly
393
+ embeddingModel: this.config.embeddingModel,
394
+ limit: this.config.limit,
395
+ };
396
+ }
397
+
398
+ async retrieveContext(message: string, options: any) {
399
+ // ... implementation
400
+ }
401
+ }
402
+ ```
403
+
404
+ #### Environment Variable References
405
+
406
+ Store sensitive values (API keys, connection strings) as environment variable references instead of actual values:
407
+
408
+ ```typescript
409
+ // ✅ GOOD: Environment variable references (safe to store in DB)
410
+ getConfig() {
411
+ return {
412
+ openaiKey: '${OPENAI_API_KEY}', // Required env var
413
+ timeout: '${TIMEOUT:5000}', // With default value
414
+ mongoUri: '${MONGODB_URI}',
415
+ };
416
+ }
417
+
418
+ // ❌ BAD: Actual secrets (never store in database!)
419
+ getConfig() {
420
+ return {
421
+ openaiKey: 'sk-actual-secret-key', // Don't do this!
422
+ };
423
+ }
424
+ ```
425
+
426
+ The `envRef()` helper makes this cleaner:
427
+
428
+ ```typescript
429
+ import { envRef } from '@snap-agent/core';
430
+
431
+ getConfig() {
432
+ return {
433
+ apiKey: envRef('OPENAI_API_KEY'), // Required
434
+ timeout: envRef('TIMEOUT', '5000'), // With default
435
+ };
436
+ }
437
+ ```
438
+
439
+ #### Complete Example: Persistent Agents
440
+
441
+ ```typescript
442
+ import { createClient, PluginRegistry, MongoDBStorage, envRef } from '@snap-agent/core';
443
+ import { EcommerceRAGPlugin } from '@snap-agent/rag-ecommerce';
444
+
445
+ // Setup registry
446
+ const registry = new PluginRegistry();
447
+ registry.register('@snap-agent/rag-ecommerce', (config) =>
448
+ new EcommerceRAGPlugin(config)
449
+ );
450
+
451
+ const client = createClient({
452
+ storage: new MongoDBStorage(process.env.MONGODB_URI!),
453
+ providers: { openai: { apiKey: process.env.OPENAI_API_KEY! } },
454
+ pluginRegistry: registry,
455
+ });
456
+
457
+ // ═══════════════════════════════════════════════════════════════════════════
458
+ // INITIAL SETUP (run once)
459
+ // ═══════════════════════════════════════════════════════════════════════════
460
+
461
+ const agent = await client.createAgent({
462
+ name: 'Shopping Assistant',
463
+ instructions: 'Help customers find products.',
464
+ provider: 'openai',
465
+ model: 'gpt-4o',
466
+ userId: 'user-123',
467
+ plugins: [
468
+ new EcommerceRAGPlugin({
469
+ mongoUri: process.env.MONGODB_URI!,
470
+ voyageApiKey: process.env.VOYAGE_API_KEY!,
471
+ tenantId: 'my-store',
472
+ }),
473
+ ],
474
+ });
475
+
476
+ console.log('Agent created:', agent.id);
477
+ // Plugin config is automatically extracted and saved to MongoDB!
478
+
479
+ // ═══════════════════════════════════════════════════════════════════════════
480
+ // AFTER SERVER RESTART (plugins automatically reinstantiated)
481
+ // ═══════════════════════════════════════════════════════════════════════════
482
+
483
+ // Later, in a different process or after restart:
484
+ const loadedAgent = await client.getAgent('agent-123');
485
+
486
+ // ✅ Plugins are automatically reinstantiated from stored config!
487
+ // The registry looked up '@snap-agent/rag-ecommerce' and called its factory
488
+ // with the stored config (env vars resolved at runtime)
489
+
490
+ const response = await client.chat({
491
+ threadId: 'thread-456',
492
+ message: 'Find me a red dress under $100',
493
+ useRAG: true, // RAG plugin works!
494
+ });
495
+ ```
496
+
497
+ #### Plugin Loading Priority
498
+
499
+ When loading an agent, plugins are resolved in this order:
500
+
501
+ 1. **Direct plugins** (highest priority) — Plugins passed to `getAgent()`
502
+ 2. **Registry** — Reinstantiate from stored configs using registered factories
503
+ 3. **None** — Agent loads without plugins
504
+
505
+ ```typescript
506
+ // Priority 1: Direct plugins (override stored configs)
507
+ const agent = await client.getAgent('agent-123', {
508
+ plugins: [new CustomPlugin()], // Uses this, ignores stored configs
509
+ });
510
+
511
+ // Priority 2: Use registry (automatic from client config)
512
+ const agent = await client.getAgent('agent-123');
513
+ // Uses registry to reinstantiate from stored configs
514
+
515
+ // Priority 3: Override registry for this call
516
+ const agent = await client.getAgent('agent-123', {
517
+ registry: differentRegistry,
518
+ });
519
+ ```
520
+
521
+ ### Available Packages
522
+
523
+ **RAG Plugins** — Add knowledge to your agents:
524
+
525
+ | Package | Description | Links |
526
+ |---------|-------------|-------|
527
+ | `@snap-agent/rag-ecommerce` | E-commerce product search with attribute extraction | [npm](https://www.npmjs.com/package/@snap-agent/rag-ecommerce) · [github](https://github.com/vilo-hq/snap-agent/tree/main/plugins/rag/ecommerce) |
528
+ | `@snap-agent/rag-docs` | General documentation search | [github](https://github.com/vilo-hq/snap-agent/tree/main/plugins/rag/docs) |
529
+
530
+ **Middlewares** — Intercept requests/responses:
531
+
532
+ | Package | Description | Links |
533
+ |---------|-------------|-------|
534
+ | `@snap-agent/middleware-ratelimit` | Abuse prevention (100 req/min) | [github](https://github.com/vilo-hq/snap-agent/tree/main/middlewares/ratelimit) |
535
+ | `@snap-agent/middleware-budget` | Cost control ($10/day limits) | [github](https://github.com/vilo-hq/snap-agent/tree/main/middlewares/budget) |
536
+ | `@snap-agent/middleware-slack` | Slack notifications | [github](https://github.com/vilo-hq/snap-agent/tree/main/middlewares/slack) |
537
+ | `@snap-agent/middleware-discord` | Discord notifications | [github](https://github.com/vilo-hq/snap-agent/tree/main/middlewares/discord) |
538
+ | `@snap-agent/middleware-webhooks` | Custom HTTP webhooks | [github](https://github.com/vilo-hq/snap-agent/tree/main/middlewares/webhooks) |
539
+ | `@snap-agent/middleware-moderation` | Content moderation | [github](https://github.com/vilo-hq/snap-agent/tree/main/middlewares/moderation) |
540
+
541
+ **Analytics** — Track usage and performance:
542
+
543
+ | Package | Description | Links |
544
+ |---------|-------------|-------|
545
+ | `@snap-agent/analytics` | Full metrics suite (performance, cost, RAG, errors) | [github](https://github.com/vilo-hq/snap-agent/tree/main/plugins/analytics/core) |
546
+ | `@snap-agent/analytics-console` | Dev-friendly console logging | [github](https://github.com/vilo-hq/snap-agent/tree/main/plugins/analytics/console) |
282
547
 
283
- | Package | Description |
284
- |---------|-------------|
285
- | `@snap-agent/rag-ecommerce` | E-commerce product search with attribute extraction |
286
- | `@snap-agent/rag-support` | Support ticket and documentation search |
287
- | `@snap-agent/rag-docs` | General documentation search |
288
- | `@snap-agent/middleware-ratelimit` | Request rate limiting |
289
- | `@snap-agent/middleware-moderation` | Content moderation |
290
- | `@snap-agent/middleware-slack` | Slack notifications |
291
- | `@snap-agent/middleware-discord` | Discord notifications |
292
- | `@snap-agent/middleware-webhooks` | Custom webhook notifications |
293
- | `@snap-agent/analytics-console` | Console logging analytics |
294
548
 
295
549
  ## Zero-Config RAG
296
550
 
@@ -603,6 +857,7 @@ See [EDGE_RUNTIME.md](./EDGE_RUNTIME.md) for complete documentation.
603
857
  | Edge Compatible | ✅ | ❌ | ❌ | ✅ |
604
858
  | Multi-Provider | ✅ | OpenAI only | ✅ | ✅ |
605
859
  | Plugin Architecture | RAG, Tools, Middleware | Tools only | Chains | No |
860
+ | Plugin Persistence | ✅ Registry pattern | ❌ | ❌ | N/A |
606
861
  | Persistent Storage | Upstash, MongoDB | In-memory | Via integrations | No |
607
862
  | Zero-Config RAG | ✅ | ❌ | ❌ | ❌ |
608
863
  | Agent Management | ✅ | ✅ | Complex | No |
@@ -620,6 +875,6 @@ Contributions are welcome! Please open an issue or submit a pull request on [Git
620
875
  MIT © ViloTech
621
876
 
622
877
  ## Support
623
-
878
+ - [Vilo](https://vilotech.co)
624
879
  - [GitHub Issues](https://github.com/vilo-hq/snap-agent/issues)
625
880
 
@@ -51,7 +51,8 @@ var MongoDBStorage = class {
51
51
  createdAt: /* @__PURE__ */ new Date(),
52
52
  updatedAt: /* @__PURE__ */ new Date(),
53
53
  files: [],
54
- metadata: config.metadata || {}
54
+ metadata: config.metadata || {},
55
+ pluginConfigs: config.pluginConfigs || []
55
56
  };
56
57
  const result = await collection.insertOne(doc);
57
58
  return result.insertedId.toString();
@@ -234,7 +235,8 @@ var MongoDBStorage = class {
234
235
  createdAt: doc.createdAt,
235
236
  updatedAt: doc.updatedAt,
236
237
  files: doc.files,
237
- metadata: doc.metadata
238
+ metadata: doc.metadata,
239
+ pluginConfigs: doc.pluginConfigs
238
240
  };
239
241
  }
240
242
  threadDocToData(doc) {
@@ -5,6 +5,21 @@ interface BasePlugin {
5
5
  name: string;
6
6
  type: 'rag' | 'tool' | 'middleware' | 'analytics';
7
7
  priority?: number;
8
+ /**
9
+ * Optional: Return serializable configuration for persistence
10
+ * Used by PluginRegistry to store plugin config in database
11
+ * Should NOT include sensitive values - use env var references instead
12
+ *
13
+ * @example
14
+ * getConfig() {
15
+ * return {
16
+ * mongoUri: '${MONGO_URI}', // Reference to env var
17
+ * embeddingModel: 'voyage-3-lite', // Safe to store
18
+ * limit: 10,
19
+ * };
20
+ * }
21
+ */
22
+ getConfig?(): Record<string, any>;
8
23
  }
9
24
  interface RAGContext {
10
25
  content: string;
@@ -342,6 +357,34 @@ interface AnalyticsPlugin extends BasePlugin {
342
357
  }): Promise<Record<string, any>>;
343
358
  }
344
359
  type Plugin = RAGPlugin | ToolPlugin | MiddlewarePlugin | AnalyticsPlugin;
360
+ /**
361
+ * Serializable plugin configuration stored in database
362
+ * Used to reinstantiate plugins when loading agents
363
+ */
364
+ interface StoredPluginConfig {
365
+ /**
366
+ * Plugin type (rag, middleware, analytics, tool)
367
+ */
368
+ type: Plugin['type'];
369
+ /**
370
+ * Unique plugin identifier (e.g., "@snap-agent/rag-ecommerce")
371
+ * Used to look up the factory function in the registry
372
+ */
373
+ name: string;
374
+ /**
375
+ * Serializable configuration for the plugin
376
+ * Use env var references for sensitive values: "${ENV_VAR_NAME}"
377
+ */
378
+ config: Record<string, any>;
379
+ /**
380
+ * Plugin priority (lower = executed first)
381
+ */
382
+ priority?: number;
383
+ /**
384
+ * Whether this plugin is enabled
385
+ */
386
+ enabled?: boolean;
387
+ }
345
388
 
346
389
  type ProviderType = 'openai' | 'anthropic' | 'google';
347
390
  interface ProviderConfig {
@@ -395,6 +438,7 @@ interface AgentConfig {
395
438
  organizationId?: string;
396
439
  phone?: string;
397
440
  plugins?: Plugin[];
441
+ pluginConfigs?: StoredPluginConfig[];
398
442
  rag?: RAGConfig;
399
443
  }
400
444
  interface AgentData extends AgentConfig {
@@ -485,9 +529,23 @@ interface StorageAdapter {
485
529
  content: string;
486
530
  }>>;
487
531
  }
532
+ /**
533
+ * Plugin registry for reinstantiating plugins from stored configs
534
+ * Import from '@snap-agent/core' or create your own instance
535
+ */
536
+ interface PluginRegistryInterface {
537
+ instantiateAll(storedConfigs: StoredPluginConfig[]): Promise<Plugin[]>;
538
+ isRegistered(name: string): boolean;
539
+ }
488
540
  interface ClientConfig {
489
541
  storage: StorageAdapter;
490
542
  providers: ProviderConfig;
543
+ /**
544
+ * Optional plugin registry for automatic plugin reinstantiation
545
+ * When provided, agents loaded with getAgent() will automatically
546
+ * reinstantiate their plugins from stored configurations
547
+ */
548
+ pluginRegistry?: PluginRegistryInterface;
491
549
  }
492
550
  declare class AgentSDKError extends Error {
493
551
  constructor(message: string);
@@ -677,4 +735,4 @@ declare class UpstashStorage implements StorageAdapter {
677
735
  }>;
678
736
  }
679
737
 
680
- export { type AgentData as A, type BulkOperation as B, type ClientConfig as C, AgentSDKError as D, type ErrorTrackingData as E, AgentNotFoundError as F, ThreadNotFoundError as G, ProviderNotFoundError as H, type IngestOptions as I, InvalidConfigError as J, MongoDBStorage as K, MemoryStorage as L, type MessageRole as M, UpstashStorage as N, type MongoDBStorageConfig as O, type ProviderConfig as P, type UpstashStorageConfig as Q, type RAGDocument as R, type StorageAdapter as S, type ThreadData as T, type URLSource as U, type ProviderType as a, type AgentConfig as b, type AgentFile as c, type Plugin as d, type IngestResult as e, type BulkResult as f, type URLIngestResult as g, type ThreadConfig as h, type MessageAttachment as i, type MessageData as j, type ChatRequest as k, type ChatResponse as l, type StreamCallbacks as m, type RAGPlugin as n, type ToolPlugin as o, type MiddlewarePlugin as p, type AnalyticsPlugin as q, type RAGContext as r, type RAGConfig as s, type BasePlugin as t, type Tool as u, type PerformanceTimings as v, type RAGMetrics as w, type TokenMetrics as x, type RequestTrackingData as y, type ResponseTrackingData as z };
738
+ export { type AgentData as A, type BulkOperation as B, type ClientConfig as C, type DataTransform as D, type TokenMetrics as E, type RequestTrackingData as F, type ResponseTrackingData as G, type ErrorTrackingData as H, type IngestOptions as I, type PluginRegistryInterface as J, AgentSDKError as K, AgentNotFoundError as L, type MessageRole as M, ThreadNotFoundError as N, ProviderNotFoundError as O, type ProviderConfig as P, InvalidConfigError as Q, type RAGDocument as R, type StoredPluginConfig as S, type ThreadData as T, type URLSource as U, MongoDBStorage as V, MemoryStorage as W, UpstashStorage as X, type MongoDBStorageConfig as Y, type UpstashStorageConfig as Z, type ProviderType as a, type Plugin as b, type StorageAdapter as c, type AgentConfig as d, type AgentFile as e, type IngestResult as f, type BulkResult as g, type URLIngestResult as h, type ThreadConfig as i, type MessageAttachment as j, type MessageData as k, type ChatRequest as l, type ChatResponse as m, type StreamCallbacks as n, type RAGPlugin as o, type ToolPlugin as p, type MiddlewarePlugin as q, type AnalyticsPlugin as r, type RAGContext as s, type RAGConfig as t, type BasePlugin as u, type URLSourceAuth as v, type IngestionSchedule as w, type Tool as x, type PerformanceTimings as y, type RAGMetrics as z };
@@ -5,6 +5,21 @@ interface BasePlugin {
5
5
  name: string;
6
6
  type: 'rag' | 'tool' | 'middleware' | 'analytics';
7
7
  priority?: number;
8
+ /**
9
+ * Optional: Return serializable configuration for persistence
10
+ * Used by PluginRegistry to store plugin config in database
11
+ * Should NOT include sensitive values - use env var references instead
12
+ *
13
+ * @example
14
+ * getConfig() {
15
+ * return {
16
+ * mongoUri: '${MONGO_URI}', // Reference to env var
17
+ * embeddingModel: 'voyage-3-lite', // Safe to store
18
+ * limit: 10,
19
+ * };
20
+ * }
21
+ */
22
+ getConfig?(): Record<string, any>;
8
23
  }
9
24
  interface RAGContext {
10
25
  content: string;
@@ -342,6 +357,34 @@ interface AnalyticsPlugin extends BasePlugin {
342
357
  }): Promise<Record<string, any>>;
343
358
  }
344
359
  type Plugin = RAGPlugin | ToolPlugin | MiddlewarePlugin | AnalyticsPlugin;
360
+ /**
361
+ * Serializable plugin configuration stored in database
362
+ * Used to reinstantiate plugins when loading agents
363
+ */
364
+ interface StoredPluginConfig {
365
+ /**
366
+ * Plugin type (rag, middleware, analytics, tool)
367
+ */
368
+ type: Plugin['type'];
369
+ /**
370
+ * Unique plugin identifier (e.g., "@snap-agent/rag-ecommerce")
371
+ * Used to look up the factory function in the registry
372
+ */
373
+ name: string;
374
+ /**
375
+ * Serializable configuration for the plugin
376
+ * Use env var references for sensitive values: "${ENV_VAR_NAME}"
377
+ */
378
+ config: Record<string, any>;
379
+ /**
380
+ * Plugin priority (lower = executed first)
381
+ */
382
+ priority?: number;
383
+ /**
384
+ * Whether this plugin is enabled
385
+ */
386
+ enabled?: boolean;
387
+ }
345
388
 
346
389
  type ProviderType = 'openai' | 'anthropic' | 'google';
347
390
  interface ProviderConfig {
@@ -395,6 +438,7 @@ interface AgentConfig {
395
438
  organizationId?: string;
396
439
  phone?: string;
397
440
  plugins?: Plugin[];
441
+ pluginConfigs?: StoredPluginConfig[];
398
442
  rag?: RAGConfig;
399
443
  }
400
444
  interface AgentData extends AgentConfig {
@@ -485,9 +529,23 @@ interface StorageAdapter {
485
529
  content: string;
486
530
  }>>;
487
531
  }
532
+ /**
533
+ * Plugin registry for reinstantiating plugins from stored configs
534
+ * Import from '@snap-agent/core' or create your own instance
535
+ */
536
+ interface PluginRegistryInterface {
537
+ instantiateAll(storedConfigs: StoredPluginConfig[]): Promise<Plugin[]>;
538
+ isRegistered(name: string): boolean;
539
+ }
488
540
  interface ClientConfig {
489
541
  storage: StorageAdapter;
490
542
  providers: ProviderConfig;
543
+ /**
544
+ * Optional plugin registry for automatic plugin reinstantiation
545
+ * When provided, agents loaded with getAgent() will automatically
546
+ * reinstantiate their plugins from stored configurations
547
+ */
548
+ pluginRegistry?: PluginRegistryInterface;
491
549
  }
492
550
  declare class AgentSDKError extends Error {
493
551
  constructor(message: string);
@@ -677,4 +735,4 @@ declare class UpstashStorage implements StorageAdapter {
677
735
  }>;
678
736
  }
679
737
 
680
- export { type AgentData as A, type BulkOperation as B, type ClientConfig as C, AgentSDKError as D, type ErrorTrackingData as E, AgentNotFoundError as F, ThreadNotFoundError as G, ProviderNotFoundError as H, type IngestOptions as I, InvalidConfigError as J, MongoDBStorage as K, MemoryStorage as L, type MessageRole as M, UpstashStorage as N, type MongoDBStorageConfig as O, type ProviderConfig as P, type UpstashStorageConfig as Q, type RAGDocument as R, type StorageAdapter as S, type ThreadData as T, type URLSource as U, type ProviderType as a, type AgentConfig as b, type AgentFile as c, type Plugin as d, type IngestResult as e, type BulkResult as f, type URLIngestResult as g, type ThreadConfig as h, type MessageAttachment as i, type MessageData as j, type ChatRequest as k, type ChatResponse as l, type StreamCallbacks as m, type RAGPlugin as n, type ToolPlugin as o, type MiddlewarePlugin as p, type AnalyticsPlugin as q, type RAGContext as r, type RAGConfig as s, type BasePlugin as t, type Tool as u, type PerformanceTimings as v, type RAGMetrics as w, type TokenMetrics as x, type RequestTrackingData as y, type ResponseTrackingData as z };
738
+ export { type AgentData as A, type BulkOperation as B, type ClientConfig as C, type DataTransform as D, type TokenMetrics as E, type RequestTrackingData as F, type ResponseTrackingData as G, type ErrorTrackingData as H, type IngestOptions as I, type PluginRegistryInterface as J, AgentSDKError as K, AgentNotFoundError as L, type MessageRole as M, ThreadNotFoundError as N, ProviderNotFoundError as O, type ProviderConfig as P, InvalidConfigError as Q, type RAGDocument as R, type StoredPluginConfig as S, type ThreadData as T, type URLSource as U, MongoDBStorage as V, MemoryStorage as W, UpstashStorage as X, type MongoDBStorageConfig as Y, type UpstashStorageConfig as Z, type ProviderType as a, type Plugin as b, type StorageAdapter as c, type AgentConfig as d, type AgentFile as e, type IngestResult as f, type BulkResult as g, type URLIngestResult as h, type ThreadConfig as i, type MessageAttachment as j, type MessageData as k, type ChatRequest as l, type ChatResponse as m, type StreamCallbacks as n, type RAGPlugin as o, type ToolPlugin as p, type MiddlewarePlugin as q, type AnalyticsPlugin as r, type RAGContext as s, type RAGConfig as t, type BasePlugin as u, type URLSourceAuth as v, type IngestionSchedule as w, type Tool as x, type PerformanceTimings as y, type RAGMetrics as z };