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