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