@cilow/sdk 0.2.1 → 0.3.0

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