@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,1172 @@
1
+ import { createContext, useState, useMemo, useEffect, useContext, useCallback } from 'react';
2
+ import { jsx } from 'react/jsx-runtime';
3
+
4
+ // src/react/hooks.tsx
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/websocket.ts
506
+ var CilowWebSocket = class {
507
+ constructor(config) {
508
+ this.ws = null;
509
+ this.state = "disconnected";
510
+ this.reconnectCount = 0;
511
+ this.heartbeatTimer = null;
512
+ this.reconnectTimer = null;
513
+ this.messageQueue = [];
514
+ this.subscriptions = [];
515
+ this.listeners = /* @__PURE__ */ new Map();
516
+ this.allListeners = /* @__PURE__ */ new Set();
517
+ const httpUrl = config.apiUrl.replace(/\/$/, "");
518
+ this.wsUrl = config.wsUrl ?? httpUrl.replace(/^http/, "ws") + "/ws";
519
+ this.apiKey = config.apiKey;
520
+ this.reconnectAttempts = config.reconnectAttempts ?? 5;
521
+ this.reconnectDelay = config.reconnectDelay ?? 1e3;
522
+ this.heartbeatInterval = config.heartbeatInterval ?? 3e4;
523
+ this.messageQueueSize = config.messageQueueSize ?? 100;
524
+ }
525
+ /**
526
+ * Get current connection state
527
+ */
528
+ get connectionState() {
529
+ return this.state;
530
+ }
531
+ /**
532
+ * Check if connected
533
+ */
534
+ get isConnected() {
535
+ return this.state === "connected";
536
+ }
537
+ /**
538
+ * Connect to the WebSocket server
539
+ */
540
+ async connect() {
541
+ if (this.state === "connected" || this.state === "connecting") {
542
+ return;
543
+ }
544
+ this.state = "connecting";
545
+ this.emitStatusEvent("connecting");
546
+ return new Promise((resolve, reject) => {
547
+ try {
548
+ const url = new URL(this.wsUrl);
549
+ url.searchParams.set("token", this.apiKey);
550
+ this.ws = new WebSocket(url.toString());
551
+ this.ws.onopen = () => {
552
+ this.state = "connected";
553
+ this.reconnectCount = 0;
554
+ this.emitStatusEvent("connected");
555
+ this.startHeartbeat();
556
+ this.flushMessageQueue();
557
+ this.resubscribe();
558
+ resolve();
559
+ };
560
+ this.ws.onclose = (event) => {
561
+ this.handleClose(event);
562
+ };
563
+ this.ws.onerror = (error) => {
564
+ if (this.state === "connecting") {
565
+ reject(new Error("WebSocket connection failed"));
566
+ }
567
+ this.handleError(error);
568
+ };
569
+ this.ws.onmessage = (event) => {
570
+ this.handleMessage(event);
571
+ };
572
+ } catch (error) {
573
+ this.state = "disconnected";
574
+ reject(error);
575
+ }
576
+ });
577
+ }
578
+ /**
579
+ * Disconnect from the WebSocket server
580
+ */
581
+ disconnect() {
582
+ this.stopHeartbeat();
583
+ this.clearReconnectTimer();
584
+ if (this.ws) {
585
+ this.ws.onclose = null;
586
+ this.ws.close(1e3, "Client disconnect");
587
+ this.ws = null;
588
+ }
589
+ this.state = "disconnected";
590
+ this.emitStatusEvent("disconnected", "Client initiated disconnect");
591
+ }
592
+ /**
593
+ * Subscribe to events with optional filter
594
+ */
595
+ subscribe(filter) {
596
+ if (filter) {
597
+ this.subscriptions.push(filter);
598
+ }
599
+ if (this.isConnected) {
600
+ this.sendSubscription(filter);
601
+ }
602
+ }
603
+ /**
604
+ * Unsubscribe from events
605
+ */
606
+ unsubscribe(filter) {
607
+ if (filter) {
608
+ this.subscriptions = this.subscriptions.filter(
609
+ (s) => s.userId !== filter.userId || s.sessionId !== filter.sessionId || JSON.stringify(s.tags) !== JSON.stringify(filter.tags)
610
+ );
611
+ } else {
612
+ this.subscriptions = [];
613
+ }
614
+ if (this.isConnected) {
615
+ this.send({
616
+ type: "unsubscribe",
617
+ filter
618
+ });
619
+ }
620
+ }
621
+ /**
622
+ * Add event listener for specific event type
623
+ */
624
+ on(eventType, listener) {
625
+ if (!this.listeners.has(eventType)) {
626
+ this.listeners.set(eventType, /* @__PURE__ */ new Set());
627
+ }
628
+ this.listeners.get(eventType).add(listener);
629
+ return () => {
630
+ this.listeners.get(eventType)?.delete(listener);
631
+ };
632
+ }
633
+ /**
634
+ * Add listener for all events
635
+ */
636
+ onAny(listener) {
637
+ this.allListeners.add(listener);
638
+ return () => {
639
+ this.allListeners.delete(listener);
640
+ };
641
+ }
642
+ /**
643
+ * Remove event listener
644
+ */
645
+ off(eventType, listener) {
646
+ this.listeners.get(eventType)?.delete(listener);
647
+ }
648
+ /**
649
+ * Remove all listeners for an event type
650
+ */
651
+ offAll(eventType) {
652
+ if (eventType) {
653
+ this.listeners.delete(eventType);
654
+ } else {
655
+ this.listeners.clear();
656
+ this.allListeners.clear();
657
+ }
658
+ }
659
+ /**
660
+ * Listen for memory created events
661
+ */
662
+ onMemoryCreated(listener) {
663
+ return this.on("memory.created", listener);
664
+ }
665
+ /**
666
+ * Listen for memory updated events
667
+ */
668
+ onMemoryUpdated(listener) {
669
+ return this.on("memory.updated", listener);
670
+ }
671
+ /**
672
+ * Listen for memory deleted events
673
+ */
674
+ onMemoryDeleted(listener) {
675
+ return this.on("memory.deleted", listener);
676
+ }
677
+ /**
678
+ * Listen for memory tier changed events
679
+ */
680
+ onMemoryTierChanged(listener) {
681
+ return this.on("memory.tier_changed", listener);
682
+ }
683
+ /**
684
+ * Listen for graph node created events
685
+ */
686
+ onGraphNodeCreated(listener) {
687
+ return this.on("graph.node_created", listener);
688
+ }
689
+ /**
690
+ * Listen for graph edge created events
691
+ */
692
+ onGraphEdgeCreated(listener) {
693
+ return this.on("graph.edge_created", listener);
694
+ }
695
+ /**
696
+ * Listen for connection status changes
697
+ */
698
+ onConnectionStatus(listener) {
699
+ return this.on("connection.status", listener);
700
+ }
701
+ /**
702
+ * Wait for specific event (one-time)
703
+ */
704
+ once(eventType, timeout) {
705
+ return new Promise((resolve, reject) => {
706
+ const timeoutId = timeout ? setTimeout(() => {
707
+ unsubscribe();
708
+ reject(new Error(`Timeout waiting for event: ${eventType}`));
709
+ }, timeout) : null;
710
+ const unsubscribe = this.on(eventType, (event) => {
711
+ if (timeoutId) clearTimeout(timeoutId);
712
+ unsubscribe();
713
+ resolve(event);
714
+ });
715
+ });
716
+ }
717
+ // ===========================================================================
718
+ // Private Methods
719
+ // ===========================================================================
720
+ send(message) {
721
+ const data = JSON.stringify(message);
722
+ if (this.isConnected && this.ws) {
723
+ this.ws.send(data);
724
+ } else {
725
+ if (this.messageQueue.length >= this.messageQueueSize) {
726
+ this.messageQueue.shift();
727
+ }
728
+ this.messageQueue.push(data);
729
+ }
730
+ }
731
+ sendSubscription(filter) {
732
+ this.send({
733
+ type: "subscribe",
734
+ filter: filter ?? {}
735
+ });
736
+ }
737
+ resubscribe() {
738
+ for (const filter of this.subscriptions) {
739
+ this.sendSubscription(filter);
740
+ }
741
+ }
742
+ flushMessageQueue() {
743
+ while (this.messageQueue.length > 0 && this.isConnected && this.ws) {
744
+ const message = this.messageQueue.shift();
745
+ if (message) {
746
+ this.ws.send(message);
747
+ }
748
+ }
749
+ }
750
+ handleMessage(event) {
751
+ try {
752
+ const data = JSON.parse(event.data);
753
+ this.emit(data);
754
+ } catch (error) {
755
+ console.error("Failed to parse WebSocket message:", error);
756
+ }
757
+ }
758
+ handleClose(event) {
759
+ this.stopHeartbeat();
760
+ if (event.code === 1e3) {
761
+ this.state = "disconnected";
762
+ this.emitStatusEvent("disconnected", "Connection closed normally");
763
+ return;
764
+ }
765
+ if (this.reconnectCount < this.reconnectAttempts) {
766
+ this.state = "reconnecting";
767
+ this.emitStatusEvent("reconnecting", `Reconnecting (attempt ${this.reconnectCount + 1}/${this.reconnectAttempts})`);
768
+ this.scheduleReconnect();
769
+ } else {
770
+ this.state = "disconnected";
771
+ this.emitStatusEvent("disconnected", "Max reconnection attempts reached");
772
+ }
773
+ }
774
+ handleError(_error) {
775
+ console.error("WebSocket error occurred");
776
+ }
777
+ scheduleReconnect() {
778
+ this.clearReconnectTimer();
779
+ const delay = this.reconnectDelay * Math.pow(2, this.reconnectCount);
780
+ this.reconnectCount++;
781
+ this.reconnectTimer = setTimeout(async () => {
782
+ try {
783
+ await this.connect();
784
+ } catch {
785
+ }
786
+ }, delay);
787
+ }
788
+ clearReconnectTimer() {
789
+ if (this.reconnectTimer) {
790
+ clearTimeout(this.reconnectTimer);
791
+ this.reconnectTimer = null;
792
+ }
793
+ }
794
+ startHeartbeat() {
795
+ this.stopHeartbeat();
796
+ this.heartbeatTimer = setInterval(() => {
797
+ if (this.isConnected) {
798
+ this.send({ type: "ping" });
799
+ }
800
+ }, this.heartbeatInterval);
801
+ }
802
+ stopHeartbeat() {
803
+ if (this.heartbeatTimer) {
804
+ clearInterval(this.heartbeatTimer);
805
+ this.heartbeatTimer = null;
806
+ }
807
+ }
808
+ emit(event) {
809
+ const typeListeners = this.listeners.get(event.type);
810
+ if (typeListeners) {
811
+ for (const listener of typeListeners) {
812
+ try {
813
+ listener(event);
814
+ } catch (error) {
815
+ console.error("Error in event listener:", error);
816
+ }
817
+ }
818
+ }
819
+ for (const listener of this.allListeners) {
820
+ try {
821
+ listener(event);
822
+ } catch (error) {
823
+ console.error("Error in event listener:", error);
824
+ }
825
+ }
826
+ }
827
+ emitStatusEvent(status, reason) {
828
+ const event = {
829
+ type: "connection.status",
830
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
831
+ status: status === "connecting" ? "reconnecting" : status,
832
+ reason
833
+ };
834
+ this.emit(event);
835
+ }
836
+ };
837
+ var CilowContext = createContext(null);
838
+ function CilowProvider({
839
+ children,
840
+ userId: initialUserId,
841
+ sessionId: initialSessionId,
842
+ enableWebSocket = false,
843
+ ...config
844
+ }) {
845
+ const [userId, setUserId] = useState(initialUserId);
846
+ const [sessionId, setSessionId] = useState(initialSessionId);
847
+ const [isConnected, setIsConnected] = useState(false);
848
+ const client = useMemo(() => new CilowClient(config), [config.apiUrl, config.apiKey]);
849
+ const ws = useMemo(() => {
850
+ if (!enableWebSocket) return null;
851
+ return new CilowWebSocket(config);
852
+ }, [enableWebSocket, config.apiUrl, config.apiKey]);
853
+ useEffect(() => {
854
+ if (!ws) return;
855
+ const connectWs = async () => {
856
+ try {
857
+ await ws.connect();
858
+ setIsConnected(true);
859
+ } catch (error) {
860
+ console.error("Failed to connect WebSocket:", error);
861
+ }
862
+ };
863
+ connectWs();
864
+ const unsubscribe = ws.onConnectionStatus((event) => {
865
+ setIsConnected(event.status === "connected");
866
+ });
867
+ return () => {
868
+ unsubscribe();
869
+ ws.disconnect();
870
+ };
871
+ }, [ws]);
872
+ useEffect(() => {
873
+ if (!ws || !userId) return;
874
+ ws.subscribe({ userId });
875
+ }, [ws, userId]);
876
+ const value = useMemo(
877
+ () => ({
878
+ client,
879
+ ws,
880
+ userId,
881
+ sessionId,
882
+ setUserId,
883
+ setSessionId,
884
+ isConnected
885
+ }),
886
+ [client, ws, userId, sessionId, isConnected]
887
+ );
888
+ return /* @__PURE__ */ jsx(CilowContext.Provider, { value, children });
889
+ }
890
+ function useCilow() {
891
+ const context = useContext(CilowContext);
892
+ if (!context) {
893
+ throw new Error("useCilow must be used within a CilowProvider");
894
+ }
895
+ return context;
896
+ }
897
+ function useMemory() {
898
+ const { client, userId, sessionId } = useCilow();
899
+ const [isLoading, setIsLoading] = useState(false);
900
+ const [error, setError] = useState(null);
901
+ const remember = useCallback(
902
+ async (content, options) => {
903
+ setIsLoading(true);
904
+ setError(null);
905
+ try {
906
+ const memoryId = await client.remember(content, {
907
+ ...options,
908
+ userId: options?.userId ?? userId,
909
+ sessionId: options?.sessionId ?? sessionId
910
+ });
911
+ return memoryId;
912
+ } catch (err) {
913
+ const error2 = err instanceof Error ? err : new Error(String(err));
914
+ setError(error2);
915
+ throw error2;
916
+ } finally {
917
+ setIsLoading(false);
918
+ }
919
+ },
920
+ [client, userId, sessionId]
921
+ );
922
+ const forget = useCallback(
923
+ async (filter) => {
924
+ setIsLoading(true);
925
+ setError(null);
926
+ try {
927
+ const count = await client.forget({
928
+ ...filter,
929
+ userId
930
+ });
931
+ return count;
932
+ } catch (err) {
933
+ const error2 = err instanceof Error ? err : new Error(String(err));
934
+ setError(error2);
935
+ throw error2;
936
+ } finally {
937
+ setIsLoading(false);
938
+ }
939
+ },
940
+ [client, userId]
941
+ );
942
+ const getMemory = useCallback(
943
+ async (memoryId) => {
944
+ setIsLoading(true);
945
+ setError(null);
946
+ try {
947
+ return await client.getMemory(memoryId);
948
+ } catch (err) {
949
+ const error2 = err instanceof Error ? err : new Error(String(err));
950
+ setError(error2);
951
+ throw error2;
952
+ } finally {
953
+ setIsLoading(false);
954
+ }
955
+ },
956
+ [client]
957
+ );
958
+ return { remember, forget, getMemory, isLoading, error };
959
+ }
960
+ function useRecall() {
961
+ const { client, userId } = useCilow();
962
+ const [data, setData] = useState([]);
963
+ const [isLoading, setIsLoading] = useState(false);
964
+ const [error, setError] = useState(null);
965
+ const search = useCallback(
966
+ async (query, options) => {
967
+ setIsLoading(true);
968
+ setError(null);
969
+ try {
970
+ const results = await client.recall(query, {
971
+ ...options,
972
+ userId
973
+ });
974
+ setData(results);
975
+ } catch (err) {
976
+ const error2 = err instanceof Error ? err : new Error(String(err));
977
+ setError(error2);
978
+ setData([]);
979
+ } finally {
980
+ setIsLoading(false);
981
+ }
982
+ },
983
+ [client, userId]
984
+ );
985
+ const clear = useCallback(() => {
986
+ setData([]);
987
+ setError(null);
988
+ }, []);
989
+ return { data, search, clear, isLoading, error };
990
+ }
991
+ function useMemorySubscription(options) {
992
+ const { ws, isConnected } = useCilow();
993
+ const [latestEvent, setLatestEvent] = useState(null);
994
+ const [events, setEvents] = useState([]);
995
+ useEffect(() => {
996
+ if (!ws) return;
997
+ const unsubscribers = [];
998
+ const handleEvent = (event) => {
999
+ setLatestEvent(event);
1000
+ setEvents((prev) => [...prev, event]);
1001
+ };
1002
+ const eventTypes = options?.eventTypes ?? [
1003
+ "memory.created",
1004
+ "memory.updated",
1005
+ "memory.deleted"
1006
+ ];
1007
+ for (const eventType of eventTypes) {
1008
+ if (eventType === "memory.created") {
1009
+ unsubscribers.push(ws.onMemoryCreated(handleEvent));
1010
+ } else if (eventType === "memory.updated") {
1011
+ unsubscribers.push(ws.onMemoryUpdated(handleEvent));
1012
+ } else if (eventType === "memory.deleted") {
1013
+ unsubscribers.push(ws.onMemoryDeleted(handleEvent));
1014
+ }
1015
+ }
1016
+ if (options?.userId || options?.sessionId || options?.tags) {
1017
+ ws.subscribe({
1018
+ userId: options.userId,
1019
+ sessionId: options.sessionId,
1020
+ tags: options.tags
1021
+ });
1022
+ }
1023
+ return () => {
1024
+ unsubscribers.forEach((unsub) => unsub());
1025
+ };
1026
+ }, [ws, options?.userId, options?.sessionId, options?.tags, options?.eventTypes]);
1027
+ const clearEvents = useCallback(() => {
1028
+ setEvents([]);
1029
+ setLatestEvent(null);
1030
+ }, []);
1031
+ return { latestEvent, events, isConnected, clearEvents };
1032
+ }
1033
+ function useMemoryContext() {
1034
+ const { client, userId } = useCilow();
1035
+ const [context, setContext] = useState("");
1036
+ const [memoriesUsed, setMemoriesUsed] = useState(0);
1037
+ const [isLoading, setIsLoading] = useState(false);
1038
+ const [error, setError] = useState(null);
1039
+ const getContext = useCallback(
1040
+ async (query, options) => {
1041
+ setIsLoading(true);
1042
+ setError(null);
1043
+ try {
1044
+ const result = await client.getContext(query, {
1045
+ ...options,
1046
+ userId
1047
+ });
1048
+ setContext(result.context);
1049
+ setMemoriesUsed(result.memoriesUsed);
1050
+ return { context: result.context, memoriesUsed: result.memoriesUsed };
1051
+ } catch (err) {
1052
+ const error2 = err instanceof Error ? err : new Error(String(err));
1053
+ setError(error2);
1054
+ throw error2;
1055
+ } finally {
1056
+ setIsLoading(false);
1057
+ }
1058
+ },
1059
+ [client, userId]
1060
+ );
1061
+ const clearContext = useCallback(() => {
1062
+ setContext("");
1063
+ setMemoriesUsed(0);
1064
+ }, []);
1065
+ return { getContext, context, memoriesUsed, clearContext, isLoading, error };
1066
+ }
1067
+ function useMemoryStats() {
1068
+ const { client } = useCilow();
1069
+ const [stats, setStats] = useState(null);
1070
+ const [isLoading, setIsLoading] = useState(false);
1071
+ const [error, setError] = useState(null);
1072
+ const refresh = useCallback(async () => {
1073
+ setIsLoading(true);
1074
+ setError(null);
1075
+ try {
1076
+ const newStats = await client.getStats();
1077
+ setStats(newStats);
1078
+ } catch (err) {
1079
+ const error2 = err instanceof Error ? err : new Error(String(err));
1080
+ setError(error2);
1081
+ } finally {
1082
+ setIsLoading(false);
1083
+ }
1084
+ }, [client]);
1085
+ useEffect(() => {
1086
+ refresh();
1087
+ }, [refresh]);
1088
+ return { stats, refresh, isLoading, error };
1089
+ }
1090
+ function useConversation() {
1091
+ const { client, userId, sessionId } = useCilow();
1092
+ const [isLoading, setIsLoading] = useState(false);
1093
+ const [error, setError] = useState(null);
1094
+ const [storedCount, setStoredCount] = useState(0);
1095
+ const storeConversation = useCallback(
1096
+ async (userMessage, assistantResponse, metadata) => {
1097
+ setIsLoading(true);
1098
+ setError(null);
1099
+ try {
1100
+ const memoryId = await client.storeConversation({
1101
+ userMessage,
1102
+ assistantResponse,
1103
+ userId: userId ?? "anonymous",
1104
+ sessionId,
1105
+ metadata
1106
+ });
1107
+ setStoredCount((c) => c + 1);
1108
+ return memoryId;
1109
+ } catch (err) {
1110
+ const error2 = err instanceof Error ? err : new Error(String(err));
1111
+ setError(error2);
1112
+ throw error2;
1113
+ } finally {
1114
+ setIsLoading(false);
1115
+ }
1116
+ },
1117
+ [client, userId, sessionId]
1118
+ );
1119
+ return { storeConversation, storedCount, isLoading, error };
1120
+ }
1121
+ function useDebounce(value, delay) {
1122
+ const [debouncedValue, setDebouncedValue] = useState(value);
1123
+ useEffect(() => {
1124
+ const timer = setTimeout(() => setDebouncedValue(value), delay);
1125
+ return () => clearTimeout(timer);
1126
+ }, [value, delay]);
1127
+ return debouncedValue;
1128
+ }
1129
+ function useDebouncedSearch(options) {
1130
+ const { client, userId } = useCilow();
1131
+ const [query, setQuery] = useState("");
1132
+ const [results, setResults] = useState([]);
1133
+ const [isLoading, setIsLoading] = useState(false);
1134
+ const [error, setError] = useState(null);
1135
+ const debouncedQuery = useDebounce(query, options?.delay ?? 300);
1136
+ const minLength = options?.minLength ?? 2;
1137
+ const limit = options?.limit ?? 10;
1138
+ useEffect(() => {
1139
+ if (debouncedQuery.length < minLength) {
1140
+ setResults([]);
1141
+ return;
1142
+ }
1143
+ const search = async () => {
1144
+ setIsLoading(true);
1145
+ setError(null);
1146
+ try {
1147
+ const searchResults = await client.recall(debouncedQuery, {
1148
+ limit,
1149
+ userId
1150
+ });
1151
+ setResults(searchResults);
1152
+ } catch (err) {
1153
+ const error2 = err instanceof Error ? err : new Error(String(err));
1154
+ setError(error2);
1155
+ setResults([]);
1156
+ } finally {
1157
+ setIsLoading(false);
1158
+ }
1159
+ };
1160
+ search();
1161
+ }, [debouncedQuery, client, userId, limit, minLength]);
1162
+ const clear = useCallback(() => {
1163
+ setQuery("");
1164
+ setResults([]);
1165
+ setError(null);
1166
+ }, []);
1167
+ return { query, setQuery, results, clear, isLoading, error };
1168
+ }
1169
+
1170
+ export { CilowProvider, useCilow, useConversation, useDebounce, useDebouncedSearch, useMemory, useMemoryContext, useMemoryStats, useMemorySubscription, useRecall };
1171
+ //# sourceMappingURL=hooks.mjs.map
1172
+ //# sourceMappingURL=hooks.mjs.map