@cilow/sdk 0.2.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.
package/dist/index.js ADDED
@@ -0,0 +1,482 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AuthenticationError: () => AuthenticationError,
24
+ CilowClient: () => CilowClient,
25
+ CilowError: () => CilowError,
26
+ ConnectionError: () => ConnectionError,
27
+ NotFoundError: () => NotFoundError,
28
+ RateLimitError: () => RateLimitError,
29
+ ValidationError: () => ValidationError
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // src/errors.ts
34
+ var CilowError = class _CilowError extends Error {
35
+ constructor(message, statusCode, details) {
36
+ super(message);
37
+ this.name = "CilowError";
38
+ this.statusCode = statusCode;
39
+ this.details = details;
40
+ Object.setPrototypeOf(this, _CilowError.prototype);
41
+ }
42
+ };
43
+ var ConnectionError = class _ConnectionError extends CilowError {
44
+ constructor(message, details) {
45
+ super(message, void 0, details);
46
+ this.name = "ConnectionError";
47
+ Object.setPrototypeOf(this, _ConnectionError.prototype);
48
+ }
49
+ };
50
+ var AuthenticationError = class _AuthenticationError extends CilowError {
51
+ constructor(message = "Invalid API key or unauthorized", details) {
52
+ super(message, 401, details);
53
+ this.name = "AuthenticationError";
54
+ Object.setPrototypeOf(this, _AuthenticationError.prototype);
55
+ }
56
+ };
57
+ var NotFoundError = class _NotFoundError extends CilowError {
58
+ constructor(message = "Resource not found", details) {
59
+ super(message, 404, details);
60
+ this.name = "NotFoundError";
61
+ Object.setPrototypeOf(this, _NotFoundError.prototype);
62
+ }
63
+ };
64
+ var ValidationError = class _ValidationError extends CilowError {
65
+ constructor(message = "Validation error", details) {
66
+ super(message, 422, details);
67
+ this.name = "ValidationError";
68
+ Object.setPrototypeOf(this, _ValidationError.prototype);
69
+ }
70
+ };
71
+ var RateLimitError = class _RateLimitError extends CilowError {
72
+ constructor(message = "Rate limit exceeded", retryAfter, details) {
73
+ super(message, 429, details);
74
+ this.name = "RateLimitError";
75
+ this.retryAfter = retryAfter;
76
+ Object.setPrototypeOf(this, _RateLimitError.prototype);
77
+ }
78
+ };
79
+
80
+ // src/client.ts
81
+ function toCamelCase(obj) {
82
+ if (Array.isArray(obj)) {
83
+ return obj.map((item) => toCamelCase(item));
84
+ }
85
+ if (obj !== null && typeof obj === "object") {
86
+ return Object.entries(obj).reduce((acc, [key, value]) => {
87
+ const camelKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
88
+ acc[camelKey] = toCamelCase(value);
89
+ return acc;
90
+ }, {});
91
+ }
92
+ return obj;
93
+ }
94
+ function toSnakeCase(obj) {
95
+ if (Array.isArray(obj)) {
96
+ return obj.map((item) => toSnakeCase(item));
97
+ }
98
+ if (obj !== null && typeof obj === "object") {
99
+ return Object.entries(obj).reduce((acc, [key, value]) => {
100
+ const snakeKey = key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
101
+ acc[snakeKey] = toSnakeCase(value);
102
+ return acc;
103
+ }, {});
104
+ }
105
+ return obj;
106
+ }
107
+ var CilowClient = class {
108
+ constructor(config = {}) {
109
+ this.baseUrl = (config.baseUrl ?? "http://localhost:8080").replace(/\/$/, "");
110
+ this.apiKey = config.apiKey;
111
+ this.accessToken = config.accessToken;
112
+ this.timeout = config.timeout ?? 3e4;
113
+ }
114
+ /**
115
+ * Set the JWT access token for Bearer authentication
116
+ */
117
+ setAccessToken(token) {
118
+ this.accessToken = token;
119
+ }
120
+ /**
121
+ * Make API request with error handling
122
+ */
123
+ async request(method, endpoint, data, useAuth = true) {
124
+ const url = `${this.baseUrl}/api/v1${endpoint}`;
125
+ const headers = {
126
+ "Content-Type": "application/json"
127
+ };
128
+ if (useAuth) {
129
+ if (this.apiKey) {
130
+ headers["X-API-Key"] = this.apiKey;
131
+ }
132
+ if (this.accessToken) {
133
+ headers["Authorization"] = `Bearer ${this.accessToken}`;
134
+ }
135
+ }
136
+ const controller = new AbortController();
137
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
138
+ try {
139
+ const response = await fetch(url, {
140
+ method,
141
+ headers,
142
+ body: data ? JSON.stringify(toSnakeCase(data)) : void 0,
143
+ signal: controller.signal
144
+ });
145
+ clearTimeout(timeoutId);
146
+ if (!response.ok) {
147
+ const errorText = await response.text();
148
+ switch (response.status) {
149
+ case 401:
150
+ throw new AuthenticationError("Invalid API key or unauthorized");
151
+ case 404:
152
+ throw new NotFoundError(`Resource not found: ${endpoint}`);
153
+ case 422:
154
+ throw new ValidationError(`Validation error: ${errorText}`);
155
+ case 429:
156
+ const retryAfter = response.headers.get("Retry-After");
157
+ throw new RateLimitError(
158
+ "Rate limit exceeded",
159
+ retryAfter ? parseInt(retryAfter, 10) : void 0
160
+ );
161
+ default:
162
+ throw new CilowError(`API error ${response.status}: ${errorText}`, response.status);
163
+ }
164
+ }
165
+ const json = await response.json();
166
+ return toCamelCase(json);
167
+ } catch (error) {
168
+ clearTimeout(timeoutId);
169
+ if (error instanceof CilowError) {
170
+ throw error;
171
+ }
172
+ if (error instanceof Error) {
173
+ if (error.name === "AbortError") {
174
+ throw new ConnectionError("Request timeout");
175
+ }
176
+ throw new ConnectionError(`Failed to connect to Cilow API: ${error.message}`);
177
+ }
178
+ throw new ConnectionError("Unknown error occurred");
179
+ }
180
+ }
181
+ // ===========================================================================
182
+ // Health & Status
183
+ // ===========================================================================
184
+ /**
185
+ * Check API server health
186
+ */
187
+ async healthCheck() {
188
+ const response = await fetch(`${this.baseUrl}/health`);
189
+ const json = await response.json();
190
+ return toCamelCase(json);
191
+ }
192
+ // ===========================================================================
193
+ // Memory Operations
194
+ // ===========================================================================
195
+ /**
196
+ * Add a new memory to the system
197
+ */
198
+ async addMemory(options) {
199
+ const response = await this.request("POST", "/memory/add", options);
200
+ return response.memoryId;
201
+ }
202
+ /**
203
+ * Get a memory by ID
204
+ */
205
+ async getMemory(memoryId, userId) {
206
+ const endpoint = userId ? `/memory/${memoryId}?user_id=${userId}` : `/memory/${memoryId}`;
207
+ return this.request("GET", endpoint);
208
+ }
209
+ /**
210
+ * Update an existing memory
211
+ */
212
+ async updateMemory(memoryId, options) {
213
+ return this.request("PUT", `/memory/${memoryId}`, options);
214
+ }
215
+ /**
216
+ * Delete a memory
217
+ */
218
+ async deleteMemory(memoryId) {
219
+ await this.request("DELETE", `/memory/${memoryId}`);
220
+ return true;
221
+ }
222
+ /**
223
+ * Search memories with semantic similarity
224
+ */
225
+ async searchMemories(options) {
226
+ const response = await this.request(
227
+ "POST",
228
+ "/memory/search",
229
+ options
230
+ );
231
+ return Array.isArray(response) ? response : response.memories ?? [];
232
+ }
233
+ /**
234
+ * Get memory system statistics
235
+ */
236
+ async getMemoryStats() {
237
+ return this.request("GET", "/memory/stats");
238
+ }
239
+ /**
240
+ * List memories with pagination
241
+ */
242
+ async listMemories(options) {
243
+ const params = new URLSearchParams();
244
+ if (options?.limit) params.set("limit", options.limit.toString());
245
+ if (options?.offset) params.set("offset", options.offset.toString());
246
+ if (options?.tags) params.set("tags", options.tags.join(","));
247
+ if (options?.userId) params.set("user_id", options.userId);
248
+ const endpoint = params.toString() ? `/memory/list?${params}` : "/memory/list";
249
+ const response = await this.request("GET", endpoint);
250
+ return Array.isArray(response) ? response : response.memories ?? [];
251
+ }
252
+ // ===========================================================================
253
+ // Vector Operations
254
+ // ===========================================================================
255
+ /**
256
+ * Store a vector embedding directly
257
+ */
258
+ async storeVector(options) {
259
+ const response = await this.request(
260
+ "POST",
261
+ "/vectors",
262
+ options
263
+ );
264
+ return response.vectorId ?? response.id ?? "";
265
+ }
266
+ /**
267
+ * Search for similar vectors
268
+ */
269
+ async searchVectors(options) {
270
+ const response = await this.request("POST", "/vectors/search", options);
271
+ return response;
272
+ }
273
+ /**
274
+ * Get a vector by ID
275
+ */
276
+ async getVector(vectorId) {
277
+ return this.request("GET", `/vectors/${vectorId}`);
278
+ }
279
+ /**
280
+ * Delete a vector
281
+ */
282
+ async deleteVector(vectorId) {
283
+ await this.request("DELETE", `/vectors/${vectorId}`);
284
+ return true;
285
+ }
286
+ // ===========================================================================
287
+ // Graph Operations
288
+ // ===========================================================================
289
+ /**
290
+ * Query the knowledge graph with natural language
291
+ */
292
+ async queryGraph(query, limit = 10) {
293
+ const response = await this.request(
294
+ "POST",
295
+ "/graph/query",
296
+ { query, limit }
297
+ );
298
+ return Array.isArray(response) ? response : response.results ?? [];
299
+ }
300
+ /**
301
+ * Add a node to the knowledge graph
302
+ */
303
+ async addGraphNode(options) {
304
+ const response = await this.request(
305
+ "POST",
306
+ "/graph/nodes",
307
+ options
308
+ );
309
+ return response.nodeId ?? response.id ?? "";
310
+ }
311
+ /**
312
+ * Get a graph node by ID
313
+ */
314
+ async getGraphNode(nodeId) {
315
+ return this.request("GET", `/graph/nodes/${nodeId}`);
316
+ }
317
+ /**
318
+ * Delete a graph node
319
+ */
320
+ async deleteGraphNode(nodeId) {
321
+ await this.request("DELETE", `/graph/nodes/${nodeId}`);
322
+ return true;
323
+ }
324
+ /**
325
+ * Get knowledge graph statistics
326
+ */
327
+ async getGraphStats() {
328
+ return this.request("GET", "/graph/stats");
329
+ }
330
+ // ===========================================================================
331
+ // Agent Operations
332
+ // ===========================================================================
333
+ /**
334
+ * Create a new AI agent
335
+ */
336
+ async createAgent(options) {
337
+ const response = await this.request("POST", "/agents/create", {
338
+ name: options.name,
339
+ type: options.agentType ?? "react",
340
+ config: options.config
341
+ });
342
+ return response.agentId;
343
+ }
344
+ /**
345
+ * Get agent details
346
+ */
347
+ async getAgent(agentId) {
348
+ return this.request("GET", `/agents/${agentId}`);
349
+ }
350
+ /**
351
+ * Execute a task with an AI agent
352
+ */
353
+ async executeTask(agentId, options) {
354
+ return this.request("POST", `/agents/${agentId}/execute`, options);
355
+ }
356
+ // ===========================================================================
357
+ // Fact Extraction
358
+ // ===========================================================================
359
+ /**
360
+ * Extract facts from content using intelligent extraction
361
+ */
362
+ async extractFacts(content, sourceContext) {
363
+ const response = await this.request("POST", "/memory/extract", {
364
+ content,
365
+ sourceContext
366
+ });
367
+ return response.facts ?? [];
368
+ }
369
+ // ===========================================================================
370
+ // Authentication Operations
371
+ // ===========================================================================
372
+ /**
373
+ * Register a new user account
374
+ */
375
+ async register(email, password, name) {
376
+ const response = await this.request(
377
+ "POST",
378
+ "/auth/register",
379
+ { email, password, name },
380
+ false
381
+ );
382
+ this.accessToken = response.accessToken;
383
+ return response;
384
+ }
385
+ /**
386
+ * Login with email and password
387
+ */
388
+ async login(email, password) {
389
+ const response = await this.request(
390
+ "POST",
391
+ "/auth/login",
392
+ { email, password },
393
+ false
394
+ );
395
+ this.accessToken = response.accessToken;
396
+ return response;
397
+ }
398
+ /**
399
+ * Refresh the current access token
400
+ */
401
+ async refreshToken() {
402
+ const response = await this.request("POST", "/auth/refresh");
403
+ this.accessToken = response.accessToken;
404
+ return response;
405
+ }
406
+ /**
407
+ * Get the currently authenticated user
408
+ */
409
+ async getCurrentUser() {
410
+ return this.request("GET", "/auth/me");
411
+ }
412
+ /**
413
+ * Logout and invalidate current session
414
+ */
415
+ async logout() {
416
+ await this.request("POST", "/auth/logout");
417
+ this.accessToken = void 0;
418
+ return true;
419
+ }
420
+ /**
421
+ * Create a new API key for programmatic access
422
+ */
423
+ async createApiKey(options) {
424
+ const response = await this.request("POST", "/auth/api-keys", options);
425
+ return {
426
+ keyId: response.keyId ?? response.id ?? "",
427
+ name: response.name,
428
+ key: response.apiKey ?? response.key,
429
+ permissions: response.permissions ?? [],
430
+ expiresAt: response.expiresAt,
431
+ isActive: true
432
+ };
433
+ }
434
+ /**
435
+ * List all API keys for the current user
436
+ */
437
+ async listApiKeys() {
438
+ const response = await this.request("GET", "/auth/api-keys");
439
+ return Array.isArray(response) ? response : response.keys ?? [];
440
+ }
441
+ /**
442
+ * Revoke an API key
443
+ */
444
+ async revokeApiKey(keyId) {
445
+ await this.request("DELETE", `/auth/api-keys/${keyId}`);
446
+ return true;
447
+ }
448
+ /**
449
+ * List all active sessions for the current user
450
+ */
451
+ async listSessions() {
452
+ const response = await this.request(
453
+ "GET",
454
+ "/auth/sessions"
455
+ );
456
+ return Array.isArray(response) ? response : response.sessions ?? [];
457
+ }
458
+ /**
459
+ * Revoke a specific session
460
+ */
461
+ async revokeSession(sessionId) {
462
+ await this.request("DELETE", `/auth/sessions/${sessionId}`);
463
+ return true;
464
+ }
465
+ /**
466
+ * Revoke all sessions except the current one
467
+ */
468
+ async revokeAllSessions() {
469
+ await this.request("DELETE", "/auth/sessions");
470
+ return true;
471
+ }
472
+ };
473
+ // Annotate the CommonJS export names for ESM import in node:
474
+ 0 && (module.exports = {
475
+ AuthenticationError,
476
+ CilowClient,
477
+ CilowError,
478
+ ConnectionError,
479
+ NotFoundError,
480
+ RateLimitError,
481
+ ValidationError
482
+ });