@cilow/sdk 0.2.0 → 0.2.1

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.
Files changed (45) hide show
  1. package/README.md +412 -199
  2. package/dist/client.d.mts +224 -0
  3. package/dist/client.d.ts +224 -0
  4. package/dist/client.js +509 -0
  5. package/dist/client.js.map +1 -0
  6. package/dist/client.mjs +505 -0
  7. package/dist/client.mjs.map +1 -0
  8. package/dist/index.d.mts +94 -390
  9. package/dist/index.d.ts +94 -390
  10. package/dist/index.js +745 -350
  11. package/dist/index.js.map +1 -0
  12. package/dist/index.mjs +732 -318
  13. package/dist/index.mjs.map +1 -0
  14. package/dist/providers/langchain.js +821 -0
  15. package/dist/providers/langchain.js.map +1 -0
  16. package/dist/providers/langchain.mjs +816 -0
  17. package/dist/providers/langchain.mjs.map +1 -0
  18. package/dist/providers/openai.js +737 -0
  19. package/dist/providers/openai.js.map +1 -0
  20. package/dist/providers/openai.mjs +732 -0
  21. package/dist/providers/openai.mjs.map +1 -0
  22. package/dist/providers/vercel.js +866 -0
  23. package/dist/providers/vercel.js.map +1 -0
  24. package/dist/providers/vercel.mjs +860 -0
  25. package/dist/providers/vercel.mjs.map +1 -0
  26. package/dist/react/hooks.d.mts +327 -0
  27. package/dist/react/hooks.d.ts +327 -0
  28. package/dist/react/hooks.js +1183 -0
  29. package/dist/react/hooks.js.map +1 -0
  30. package/dist/react/hooks.mjs +1172 -0
  31. package/dist/react/hooks.mjs.map +1 -0
  32. package/dist/types.d.mts +494 -0
  33. package/dist/types.d.ts +494 -0
  34. package/dist/types.js +18 -0
  35. package/dist/types.js.map +1 -0
  36. package/dist/types.mjs +14 -0
  37. package/dist/types.mjs.map +1 -0
  38. package/dist/websocket.d.mts +160 -0
  39. package/dist/websocket.d.ts +160 -0
  40. package/dist/websocket.js +342 -0
  41. package/dist/websocket.js.map +1 -0
  42. package/dist/websocket.mjs +339 -0
  43. package/dist/websocket.mjs.map +1 -0
  44. package/package.json +90 -31
  45. package/LICENSE +0 -21
@@ -0,0 +1,860 @@
1
+ import { tool } from 'ai';
2
+ import { z } from 'zod';
3
+
4
+ // src/providers/vercel.ts
5
+
6
+ // src/client.ts
7
+ async function fetchWithRetry(url, options, config) {
8
+ const controller = new AbortController();
9
+ const timeoutId = setTimeout(() => controller.abort(), config.timeout);
10
+ let lastError = null;
11
+ for (let attempt = 0; attempt <= config.retries; attempt++) {
12
+ try {
13
+ const response = await fetch(url, {
14
+ ...options,
15
+ signal: controller.signal
16
+ });
17
+ clearTimeout(timeoutId);
18
+ if (!response.ok) {
19
+ const errorBody = await response.text();
20
+ let apiError;
21
+ try {
22
+ apiError = JSON.parse(errorBody);
23
+ } catch {
24
+ apiError = {
25
+ code: `HTTP_${response.status}`,
26
+ message: errorBody || response.statusText
27
+ };
28
+ }
29
+ throw new CilowApiError(apiError.message, apiError.code, response.status, apiError.details);
30
+ }
31
+ return response;
32
+ } catch (error) {
33
+ lastError = error;
34
+ if (error instanceof CilowApiError) {
35
+ throw error;
36
+ }
37
+ if (config.debug) {
38
+ console.warn(`Cilow API request failed (attempt ${attempt + 1}/${config.retries + 1}):`, error);
39
+ }
40
+ if (attempt < config.retries) {
41
+ await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempt) * 100));
42
+ }
43
+ }
44
+ }
45
+ clearTimeout(timeoutId);
46
+ throw lastError || new Error("Request failed");
47
+ }
48
+ var CilowApiError = class extends Error {
49
+ constructor(message, code, statusCode, details) {
50
+ super(message);
51
+ this.code = code;
52
+ this.statusCode = statusCode;
53
+ this.details = details;
54
+ this.name = "CilowApiError";
55
+ }
56
+ };
57
+ var CilowClient = class {
58
+ constructor(config) {
59
+ this.baseUrl = config.apiUrl.replace(/\/$/, "");
60
+ this.apiKey = config.apiKey;
61
+ this.timeout = config.timeout ?? 3e4;
62
+ this.retries = config.retries ?? 3;
63
+ this.debug = config.debug ?? false;
64
+ const authHeaders = this.apiKey.startsWith("cilow_") ? { "X-API-Key": this.apiKey } : { Authorization: `Bearer ${this.apiKey}` };
65
+ this.headers = {
66
+ "Content-Type": "application/json",
67
+ ...authHeaders,
68
+ ...config.headers
69
+ };
70
+ }
71
+ /**
72
+ * Make an API request
73
+ */
74
+ async request(method, path, body, queryParams) {
75
+ let url = `${this.baseUrl}${path}`;
76
+ if (queryParams) {
77
+ const params = new URLSearchParams();
78
+ for (const [key, value] of Object.entries(queryParams)) {
79
+ if (value !== void 0) {
80
+ params.append(key, String(value));
81
+ }
82
+ }
83
+ const queryString = params.toString();
84
+ if (queryString) {
85
+ url += `?${queryString}`;
86
+ }
87
+ }
88
+ if (this.debug) {
89
+ console.log(`Cilow API: ${method} ${url}`);
90
+ }
91
+ const response = await fetchWithRetry(
92
+ url,
93
+ {
94
+ method,
95
+ headers: this.headers,
96
+ body: body ? JSON.stringify(body) : void 0
97
+ },
98
+ { timeout: this.timeout, retries: this.retries, debug: this.debug }
99
+ );
100
+ const text = await response.text();
101
+ if (!text) {
102
+ return void 0;
103
+ }
104
+ return JSON.parse(text);
105
+ }
106
+ // ===========================================================================
107
+ // Simple API (remember, recall, forget)
108
+ // ===========================================================================
109
+ /**
110
+ * Store a memory (simple API)
111
+ *
112
+ * @param content - The content to remember
113
+ * @param options - Optional configuration
114
+ * @returns The created memory ID
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * await cilow.remember("User prefers dark mode", {
119
+ * tags: ["preference"],
120
+ * userId: "user-123"
121
+ * });
122
+ * ```
123
+ */
124
+ async remember(content, options) {
125
+ const response = await this.request("POST", "/api/v1/memory/add", {
126
+ content,
127
+ tags: options?.tags ?? [],
128
+ user_id: options?.userId,
129
+ session_id: options?.sessionId,
130
+ metadata: options?.metadata,
131
+ type: options?.tier
132
+ });
133
+ return response.memory_id || response.id || "";
134
+ }
135
+ /**
136
+ * Search memories (simple API)
137
+ *
138
+ * @param query - Search query text
139
+ * @param options - Search options
140
+ * @returns Array of search results
141
+ *
142
+ * @example
143
+ * ```typescript
144
+ * const memories = await cilow.recall("user preferences", {
145
+ * limit: 10,
146
+ * tags: ["preference"]
147
+ * });
148
+ * ```
149
+ */
150
+ async recall(query, options) {
151
+ const response = await this.request("POST", "/api/v1/memory/search", {
152
+ query,
153
+ limit: options?.limit ?? 10,
154
+ min_score: options?.minRelevance ?? 0.3,
155
+ tags: options?.tags,
156
+ user_id: options?.userId
157
+ });
158
+ return (response.results ?? []).map((r) => ({
159
+ memory: {
160
+ id: r.memory_id,
161
+ content: r.content,
162
+ tags: r.tags ?? [],
163
+ tier: "hot",
164
+ status: "active",
165
+ accessCount: 0,
166
+ tokenCount: Math.ceil(r.content.length / 4),
167
+ metadata: {},
168
+ createdAt: r.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
169
+ updatedAt: r.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
170
+ lastAccessedAt: (/* @__PURE__ */ new Date()).toISOString()
171
+ },
172
+ score: r.similarity,
173
+ highlights: []
174
+ }));
175
+ }
176
+ /**
177
+ * Delete memories (simple API)
178
+ *
179
+ * @param filter - Filter criteria for deletion
180
+ * @returns Number of memories deleted
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * // Delete by tags
185
+ * await cilow.forget({ tags: ["temporary"] });
186
+ *
187
+ * // Delete by user
188
+ * await cilow.forget({ userId: "user-123" });
189
+ *
190
+ * // Delete specific memory
191
+ * await cilow.forget({ memoryId: "mem-abc" });
192
+ * ```
193
+ */
194
+ async forget(filter) {
195
+ if (filter.memoryId) {
196
+ await this.deleteMemory(filter.memoryId);
197
+ return 1;
198
+ }
199
+ const response = await this.request("DELETE", "/api/v1/memories/bulk", {
200
+ filter_tags: filter.tags,
201
+ user_id: filter.userId,
202
+ session_id: filter.sessionId,
203
+ older_than: filter.olderThan
204
+ });
205
+ return response.deleted ?? 0;
206
+ }
207
+ // ===========================================================================
208
+ // Memory CRUD Operations
209
+ // ===========================================================================
210
+ /**
211
+ * Create a new memory
212
+ */
213
+ async createMemory(content, options) {
214
+ return this.request("POST", "/api/v1/memories", {
215
+ content,
216
+ tags: options?.tags ?? [],
217
+ user_id: options?.userId,
218
+ session_id: options?.sessionId,
219
+ metadata: options?.metadata,
220
+ tier: options?.tier
221
+ });
222
+ }
223
+ /**
224
+ * Get a memory by ID
225
+ */
226
+ async getMemory(memoryId) {
227
+ return this.request("GET", `/api/v1/memories/${memoryId}`);
228
+ }
229
+ /**
230
+ * Update a memory
231
+ */
232
+ async updateMemory(memoryId, updates) {
233
+ return this.request("PATCH", `/api/v1/memories/${memoryId}`, {
234
+ content: updates.content,
235
+ tags: updates.tags,
236
+ metadata: updates.metadata,
237
+ tier: updates.tier
238
+ });
239
+ }
240
+ /**
241
+ * Delete a memory
242
+ */
243
+ async deleteMemory(memoryId) {
244
+ await this.request("DELETE", `/api/v1/memories/${memoryId}`);
245
+ }
246
+ /**
247
+ * List memories with pagination
248
+ */
249
+ async listMemories(options) {
250
+ const response = await this.request(
251
+ "GET",
252
+ "/api/v1/memory/list",
253
+ void 0,
254
+ {
255
+ limit: options?.limit ?? 20,
256
+ offset: options?.offset ?? 0,
257
+ user_id: options?.userId,
258
+ session_id: options?.sessionId,
259
+ tags: options?.tags?.join(","),
260
+ type: options?.tier
261
+ }
262
+ );
263
+ const items = (response.memories ?? []).map((m) => ({
264
+ id: m.memory_id || m.id || "",
265
+ content: m.content,
266
+ tags: m.tags ?? [],
267
+ createdAt: m.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
268
+ tier: m.type || "hot"
269
+ }));
270
+ const limit = options?.limit ?? 20;
271
+ const offset = options?.offset ?? 0;
272
+ const total = response.total ?? items.length;
273
+ return {
274
+ items,
275
+ total,
276
+ limit,
277
+ offset,
278
+ hasMore: offset + items.length < total
279
+ };
280
+ }
281
+ // ===========================================================================
282
+ // Search Operations
283
+ // ===========================================================================
284
+ /**
285
+ * Search memories with full options
286
+ */
287
+ async searchMemories(query) {
288
+ const response = await this.request("POST", "/api/v1/memories/search", {
289
+ text: query.text,
290
+ limit: query.limit ?? 10,
291
+ min_relevance: query.minRelevance ?? 0.3,
292
+ filter_tags: query.tags,
293
+ user_id: query.userId,
294
+ session_id: query.sessionId,
295
+ tier: query.tier,
296
+ created_after: query.createdAfter,
297
+ created_before: query.createdBefore,
298
+ include_archived: query.includeArchived,
299
+ mode: query.mode ?? "hybrid"
300
+ });
301
+ return response.results ?? [];
302
+ }
303
+ /**
304
+ * Advanced search with reranking and boosts
305
+ */
306
+ async advancedSearch(query) {
307
+ const response = await this.request("POST", "/api/v1/memories/search/advanced", {
308
+ text: query.text,
309
+ limit: query.limit ?? 10,
310
+ min_relevance: query.minRelevance ?? 0.3,
311
+ filter_tags: query.tags,
312
+ required_tags: query.requiredTags,
313
+ excluded_tags: query.excludedTags,
314
+ user_id: query.userId,
315
+ session_id: query.sessionId,
316
+ recency_boost: query.recencyBoost,
317
+ frequency_boost: query.frequencyBoost,
318
+ metadata_filters: query.metadataFilters,
319
+ reranker: query.reranker
320
+ });
321
+ return response.results ?? [];
322
+ }
323
+ /**
324
+ * Get context for AI applications
325
+ */
326
+ async getContext(query, options) {
327
+ const maxTokens = options?.maxTokens ?? 4e3;
328
+ const tokensPerChar = 0.25;
329
+ const results = await this.searchMemories({
330
+ text: query,
331
+ limit: 30,
332
+ minRelevance: 0.3,
333
+ userId: options?.userId,
334
+ tags: options?.tags
335
+ });
336
+ let context = "";
337
+ let estimatedTokens = 0;
338
+ const memoryIds = [];
339
+ const scores = [];
340
+ for (const result of results) {
341
+ const memoryText = `[Relevance: ${(result.score * 100).toFixed(0)}%]
342
+ ${result.memory.content}
343
+
344
+ `;
345
+ const memoryTokens = Math.ceil(memoryText.length * tokensPerChar);
346
+ if (estimatedTokens + memoryTokens > maxTokens) break;
347
+ context += memoryText;
348
+ estimatedTokens += memoryTokens;
349
+ memoryIds.push(result.memory.id);
350
+ scores.push(result.score);
351
+ }
352
+ return {
353
+ context: context.trim(),
354
+ memoriesUsed: memoryIds.length,
355
+ estimatedTokens,
356
+ memoryIds,
357
+ scores
358
+ };
359
+ }
360
+ // ===========================================================================
361
+ // Conversation Operations
362
+ // ===========================================================================
363
+ /**
364
+ * Store a conversation turn
365
+ */
366
+ async storeConversation(turn) {
367
+ const content = `User: ${turn.userMessage}
368
+
369
+ Assistant: ${turn.assistantResponse}`;
370
+ const tags = ["conversation"];
371
+ if (turn.sessionId) {
372
+ tags.push(`session:${turn.sessionId}`);
373
+ }
374
+ return this.remember(content, {
375
+ tags,
376
+ userId: turn.userId,
377
+ sessionId: turn.sessionId,
378
+ metadata: {
379
+ type: "conversation",
380
+ ...turn.metadata
381
+ }
382
+ });
383
+ }
384
+ /**
385
+ * Get conversation history for a session
386
+ */
387
+ async getConversationHistory(sessionId, options) {
388
+ const response = await this.listMemories({
389
+ sessionId,
390
+ tags: ["conversation"],
391
+ limit: options?.limit ?? 50,
392
+ offset: options?.offset ?? 0
393
+ });
394
+ return response.items;
395
+ }
396
+ // ===========================================================================
397
+ // Graph Operations
398
+ // ===========================================================================
399
+ /**
400
+ * Get a graph node
401
+ */
402
+ async getGraphNode(nodeId) {
403
+ return this.request("GET", `/api/v1/graph/nodes/${nodeId}`);
404
+ }
405
+ /**
406
+ * Create a graph node
407
+ */
408
+ async createGraphNode(type, name, properties) {
409
+ return this.request("POST", "/api/v1/graph/nodes", {
410
+ type,
411
+ name,
412
+ properties: properties ?? {}
413
+ });
414
+ }
415
+ /**
416
+ * Create a graph edge
417
+ */
418
+ async createGraphEdge(sourceId, targetId, type, properties) {
419
+ return this.request("POST", "/api/v1/graph/edges", {
420
+ source_id: sourceId,
421
+ target_id: targetId,
422
+ type,
423
+ properties: properties ?? {}
424
+ });
425
+ }
426
+ /**
427
+ * Traverse the graph from a starting node
428
+ */
429
+ async traverseGraph(options) {
430
+ return this.request("POST", "/api/v1/graph/traverse", {
431
+ start_node_id: options.startNodeId,
432
+ max_depth: options.maxDepth ?? 3,
433
+ relationship_types: options.relationshipTypes,
434
+ limit: options.limit ?? 100,
435
+ direction: options.direction ?? "both"
436
+ });
437
+ }
438
+ /**
439
+ * Get related nodes for a memory
440
+ */
441
+ async getRelatedNodes(memoryId) {
442
+ const response = await this.request(
443
+ "GET",
444
+ `/api/v1/memories/${memoryId}/related-nodes`
445
+ );
446
+ return response.nodes ?? [];
447
+ }
448
+ // ===========================================================================
449
+ // Statistics & Admin
450
+ // ===========================================================================
451
+ /**
452
+ * Get memory statistics
453
+ */
454
+ async getStats() {
455
+ return this.request("GET", "/api/v1/stats");
456
+ }
457
+ /**
458
+ * Get all tags with counts
459
+ */
460
+ async getTags() {
461
+ const response = await this.request("GET", "/api/v1/tags");
462
+ return response.tags ?? [];
463
+ }
464
+ /**
465
+ * Get user statistics
466
+ */
467
+ async getUserStats(userId) {
468
+ return this.request("GET", `/api/v1/users/${userId}/stats`);
469
+ }
470
+ /**
471
+ * Health check
472
+ */
473
+ async healthCheck() {
474
+ return this.request("GET", "/health");
475
+ }
476
+ // ===========================================================================
477
+ // Batch Operations
478
+ // ===========================================================================
479
+ /**
480
+ * Batch create memories
481
+ */
482
+ async batchCreate(items) {
483
+ const response = await this.request("POST", "/api/v1/memories/batch", {
484
+ memories: items.map((item) => ({
485
+ content: item.content,
486
+ tags: item.options?.tags ?? [],
487
+ user_id: item.options?.userId,
488
+ session_id: item.options?.sessionId,
489
+ metadata: item.options?.metadata
490
+ }))
491
+ });
492
+ return response.ids ?? [];
493
+ }
494
+ /**
495
+ * Batch delete memories
496
+ */
497
+ async batchDelete(memoryIds) {
498
+ const response = await this.request("DELETE", "/api/v1/memories/batch", {
499
+ ids: memoryIds
500
+ });
501
+ return response.deleted ?? 0;
502
+ }
503
+ };
504
+
505
+ // src/providers/vercel.ts
506
+ var searchMemoriesSchema = z.object({
507
+ query: z.string().describe("The search query to find relevant memories"),
508
+ limit: z.number().optional().describe("Maximum results to return (default: 10)"),
509
+ minRelevance: z.number().optional().describe("Minimum relevance score 0-1 (default: 0.3)"),
510
+ tags: z.array(z.string()).optional().describe("Filter by specific tags"),
511
+ userId: z.string().optional().describe("User ID to scope the search")
512
+ });
513
+ var addMemorySchema = z.object({
514
+ content: z.string().describe("The content to remember"),
515
+ tags: z.array(z.string()).optional().describe("Tags to categorize the memory"),
516
+ userId: z.string().optional().describe("User ID to associate"),
517
+ metadata: z.record(z.any()).optional().describe("Additional metadata")
518
+ });
519
+ var getContextSchema = z.object({
520
+ query: z.string().describe("Query to find relevant context"),
521
+ maxTokens: z.number().optional().describe("Maximum tokens to return (default: 2000)"),
522
+ userId: z.string().optional().describe("User ID to scope context")
523
+ });
524
+ var rememberConversationSchema = z.object({
525
+ userMessage: z.string().describe("The user's message"),
526
+ assistantResponse: z.string().describe("The assistant's response"),
527
+ sessionId: z.string().optional().describe("Session ID for grouping"),
528
+ userId: z.string().optional().describe("User ID"),
529
+ topic: z.string().optional().describe("Topic or category")
530
+ });
531
+ var forgetMemorySchema = z.object({
532
+ memoryId: z.string().optional().describe("Memory ID to delete"),
533
+ tags: z.array(z.string()).optional().describe("Delete memories with these tags"),
534
+ userId: z.string().optional().describe("Delete memories for this user")
535
+ });
536
+ var emptySchema = z.object({});
537
+ function createCilowTools(config) {
538
+ const client = new CilowClient(config);
539
+ const defaultUserId = config.defaultUserId;
540
+ const defaultSessionId = config.defaultSessionId;
541
+ const defaultLimit = config.defaultSearchLimit ?? 10;
542
+ const defaultMinRelevance = config.defaultMinRelevance ?? 0.3;
543
+ return {
544
+ /**
545
+ * Search through stored memories
546
+ */
547
+ searchMemories: tool({
548
+ description: "Search through stored memories using semantic similarity. Use this to recall information from past conversations or stored knowledge.",
549
+ parameters: searchMemoriesSchema,
550
+ execute: async (params) => {
551
+ const { query, limit, minRelevance, tags, userId } = params;
552
+ try {
553
+ const results = await client.recall(query, {
554
+ limit: limit ?? defaultLimit,
555
+ minRelevance: minRelevance ?? defaultMinRelevance,
556
+ tags,
557
+ userId: userId ?? defaultUserId
558
+ });
559
+ return {
560
+ success: true,
561
+ count: results.length,
562
+ memories: results.map((r) => ({
563
+ content: r.memory.content,
564
+ score: r.score,
565
+ tags: r.memory.tags,
566
+ createdAt: r.memory.createdAt
567
+ }))
568
+ };
569
+ } catch (error) {
570
+ return {
571
+ success: false,
572
+ error: error.message,
573
+ memories: []
574
+ };
575
+ }
576
+ }
577
+ }),
578
+ /**
579
+ * Store a new memory
580
+ */
581
+ addMemory: tool({
582
+ description: "Store a new memory for future retrieval. Use this to save important information, user preferences, or insights.",
583
+ parameters: addMemorySchema,
584
+ execute: async (params) => {
585
+ const { content, tags, userId, metadata } = params;
586
+ try {
587
+ const memoryId = await client.remember(content, {
588
+ tags,
589
+ userId: userId ?? defaultUserId,
590
+ metadata
591
+ });
592
+ return {
593
+ success: true,
594
+ memoryId,
595
+ message: "Memory stored successfully"
596
+ };
597
+ } catch (error) {
598
+ return {
599
+ success: false,
600
+ error: error.message
601
+ };
602
+ }
603
+ }
604
+ }),
605
+ /**
606
+ * Get context for a conversation
607
+ */
608
+ getContext: tool({
609
+ description: "Retrieve relevant context from memories based on a query. Returns formatted context for including in prompts.",
610
+ parameters: getContextSchema,
611
+ execute: async (params) => {
612
+ const { query, maxTokens = 2e3, userId } = params;
613
+ try {
614
+ const context = await client.getContext(query, {
615
+ maxTokens,
616
+ userId: userId ?? defaultUserId
617
+ });
618
+ return {
619
+ success: true,
620
+ context: context.context,
621
+ memoriesUsed: context.memoriesUsed,
622
+ estimatedTokens: context.estimatedTokens
623
+ };
624
+ } catch (error) {
625
+ return {
626
+ success: false,
627
+ error: error.message,
628
+ context: ""
629
+ };
630
+ }
631
+ }
632
+ }),
633
+ /**
634
+ * Store a conversation turn
635
+ */
636
+ rememberConversation: tool({
637
+ description: "Store a conversation exchange (user message and assistant response) for future context.",
638
+ parameters: rememberConversationSchema,
639
+ execute: async (params) => {
640
+ const { userMessage, assistantResponse, sessionId, userId, topic } = params;
641
+ try {
642
+ const memoryId = await client.storeConversation({
643
+ userMessage,
644
+ assistantResponse,
645
+ sessionId: sessionId ?? defaultSessionId,
646
+ userId: userId ?? defaultUserId ?? "anonymous",
647
+ metadata: topic ? { topic } : void 0
648
+ });
649
+ return {
650
+ success: true,
651
+ memoryId,
652
+ message: "Conversation stored"
653
+ };
654
+ } catch (error) {
655
+ return {
656
+ success: false,
657
+ error: error.message
658
+ };
659
+ }
660
+ }
661
+ }),
662
+ /**
663
+ * Delete a memory
664
+ */
665
+ forgetMemory: tool({
666
+ description: "Delete a specific memory by ID or filter criteria.",
667
+ parameters: forgetMemorySchema,
668
+ execute: async (params) => {
669
+ const { memoryId, tags, userId } = params;
670
+ try {
671
+ const count = await client.forget({
672
+ memoryId,
673
+ tags,
674
+ userId: userId ?? defaultUserId
675
+ });
676
+ return {
677
+ success: true,
678
+ deletedCount: count,
679
+ message: `Deleted ${count} memory(ies)`
680
+ };
681
+ } catch (error) {
682
+ return {
683
+ success: false,
684
+ error: error.message
685
+ };
686
+ }
687
+ }
688
+ }),
689
+ /**
690
+ * Get memory statistics
691
+ */
692
+ getMemoryStats: tool({
693
+ description: "Get statistics about stored memories.",
694
+ parameters: emptySchema,
695
+ execute: async (_params) => {
696
+ try {
697
+ const stats = await client.getStats();
698
+ return {
699
+ success: true,
700
+ stats: {
701
+ totalMemories: stats.totalMemories,
702
+ hotMemories: stats.hotMemories,
703
+ warmMemories: stats.warmMemories,
704
+ coldMemories: stats.coldMemories,
705
+ totalTokens: stats.totalTokens,
706
+ averageTokensPerMemory: stats.averageTokensPerMemory
707
+ }
708
+ };
709
+ } catch (error) {
710
+ return {
711
+ success: false,
712
+ error: error.message
713
+ };
714
+ }
715
+ }
716
+ }),
717
+ /**
718
+ * List all tags
719
+ */
720
+ listTags: tool({
721
+ description: "List all memory tags and their usage counts.",
722
+ parameters: emptySchema,
723
+ execute: async (_params) => {
724
+ try {
725
+ const tags = await client.getTags();
726
+ return {
727
+ success: true,
728
+ tags: tags.map((t) => ({ tag: t.tag, count: t.count })),
729
+ totalTags: tags.length
730
+ };
731
+ } catch (error) {
732
+ return {
733
+ success: false,
734
+ error: error.message
735
+ };
736
+ }
737
+ }
738
+ })
739
+ };
740
+ }
741
+ function createCilowContext(config) {
742
+ const client = new CilowClient(config);
743
+ const defaultUserId = config.defaultUserId;
744
+ const defaultMaxTokens = config.maxTokens ?? 4e3;
745
+ return async function getContext(query, options) {
746
+ return client.getContext(query, {
747
+ maxTokens: options?.maxTokens ?? defaultMaxTokens,
748
+ userId: options?.userId ?? defaultUserId,
749
+ tags: options?.tags
750
+ });
751
+ };
752
+ }
753
+ function buildSystemPromptWithContext(basePrompt, context) {
754
+ if (!context.context || context.memoriesUsed === 0) {
755
+ return basePrompt;
756
+ }
757
+ return `${basePrompt}
758
+
759
+ ## Relevant Information from Memory (${context.memoriesUsed} items)
760
+
761
+ ${context.context}
762
+
763
+ ---
764
+
765
+ Use the above context when relevant to provide informed and personalized responses.`;
766
+ }
767
+ function createContextMiddleware(config) {
768
+ const getContext = createCilowContext(config);
769
+ return async function withMemory(messages, options) {
770
+ if (messages.length === 0) return messages;
771
+ const lastUserMessage = [...messages].reverse().find((m) => m.role === "user");
772
+ if (!lastUserMessage) return messages;
773
+ const context = await getContext(lastUserMessage.content, options);
774
+ if (!context.context || context.memoriesUsed === 0) {
775
+ return messages;
776
+ }
777
+ const systemIndex = messages.findIndex((m) => m.role === "system");
778
+ if (systemIndex >= 0) {
779
+ const updatedMessages = [...messages];
780
+ updatedMessages[systemIndex] = {
781
+ ...messages[systemIndex],
782
+ content: buildSystemPromptWithContext(messages[systemIndex].content, context)
783
+ };
784
+ return updatedMessages;
785
+ } else {
786
+ return [
787
+ {
788
+ role: "system",
789
+ content: `## Relevant Context from Memory
790
+
791
+ ${context.context}
792
+
793
+ Use this context when relevant to answer the user's question.`
794
+ },
795
+ ...messages
796
+ ];
797
+ }
798
+ };
799
+ }
800
+ var CilowMemoryProvider = class {
801
+ constructor(config) {
802
+ this.client = new CilowClient(config);
803
+ this.userId = config.defaultUserId;
804
+ this.sessionId = config.defaultSessionId;
805
+ this.defaultTags = config.defaultTags ?? [];
806
+ this.tokenBudget = config.tokenBudget ?? 4e3;
807
+ }
808
+ setUserId(userId) {
809
+ this.userId = userId;
810
+ }
811
+ setSessionId(sessionId) {
812
+ this.sessionId = sessionId;
813
+ }
814
+ async search(query, options) {
815
+ return this.client.recall(query, {
816
+ ...options,
817
+ userId: this.userId
818
+ });
819
+ }
820
+ async getContext(query, options) {
821
+ const result = await this.client.getContext(query, {
822
+ maxTokens: options?.maxTokens ?? this.tokenBudget,
823
+ userId: this.userId
824
+ });
825
+ return result.context;
826
+ }
827
+ async store(content, options) {
828
+ const tags = [...this.defaultTags, ...options?.tags ?? []];
829
+ if (this.sessionId) {
830
+ tags.push(`session:${this.sessionId}`);
831
+ }
832
+ return this.client.remember(content, {
833
+ tags,
834
+ userId: this.userId,
835
+ metadata: options?.metadata
836
+ });
837
+ }
838
+ async storeConversation(userMessage, assistantResponse) {
839
+ return this.client.storeConversation({
840
+ userMessage,
841
+ assistantResponse,
842
+ userId: this.userId ?? "anonymous",
843
+ sessionId: this.sessionId
844
+ });
845
+ }
846
+ async getSystemPrompt(basePrompt, query, options) {
847
+ const context = await this.client.getContext(query, {
848
+ maxTokens: options?.maxContextTokens ?? 2e3,
849
+ userId: this.userId
850
+ });
851
+ return buildSystemPromptWithContext(basePrompt, context);
852
+ }
853
+ async getStats() {
854
+ return this.client.getStats();
855
+ }
856
+ };
857
+
858
+ export { CilowMemoryProvider, buildSystemPromptWithContext, createCilowContext, createCilowTools, createContextMiddleware };
859
+ //# sourceMappingURL=vercel.mjs.map
860
+ //# sourceMappingURL=vercel.mjs.map