@lanonasis/mem-intel-sdk 1.0.1 → 1.1.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 (41) hide show
  1. package/dist/core/client.d.ts +28 -7
  2. package/dist/core/client.d.ts.map +1 -1
  3. package/dist/core/index.cjs +251 -13
  4. package/dist/core/index.cjs.map +1 -1
  5. package/dist/core/index.d.ts +1 -0
  6. package/dist/core/index.d.ts.map +1 -1
  7. package/dist/core/index.js +251 -13
  8. package/dist/core/index.js.map +1 -1
  9. package/dist/core/types.d.ts +36 -0
  10. package/dist/core/types.d.ts.map +1 -1
  11. package/dist/index-sdk.d.ts +2 -0
  12. package/dist/index-sdk.d.ts.map +1 -1
  13. package/dist/index.cjs +251 -13
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.js +251 -13
  16. package/dist/index.js.map +1 -1
  17. package/dist/node/index.cjs +251 -13
  18. package/dist/node/index.cjs.map +1 -1
  19. package/dist/node/index.js +251 -13
  20. package/dist/node/index.js.map +1 -1
  21. package/dist/react/hooks/useMemoryIntelligence.d.ts +11 -10
  22. package/dist/react/hooks/useMemoryIntelligence.d.ts.map +1 -1
  23. package/dist/react/index.cjs +251 -13
  24. package/dist/react/index.cjs.map +1 -1
  25. package/dist/react/index.js +251 -13
  26. package/dist/react/index.js.map +1 -1
  27. package/dist/server/index.cjs +272 -27
  28. package/dist/server/index.cjs.map +1 -1
  29. package/dist/server/index.js +272 -27
  30. package/dist/server/index.js.map +1 -1
  31. package/dist/server/mcp-server.d.ts.map +1 -1
  32. package/dist/utils/http-client.d.ts +35 -0
  33. package/dist/utils/http-client.d.ts.map +1 -1
  34. package/dist/utils/index.d.ts +3 -1
  35. package/dist/utils/index.d.ts.map +1 -1
  36. package/dist/utils/response-adapter.d.ts +66 -0
  37. package/dist/utils/response-adapter.d.ts.map +1 -0
  38. package/dist/vue/composables/useMemoryIntelligence.d.ts.map +1 -1
  39. package/dist/vue/index.cjs.map +1 -1
  40. package/dist/vue/index.js.map +1 -1
  41. package/package.json +3 -3
@@ -1,12 +1,33 @@
1
1
  /**
2
2
  * Core Memory Intelligence Client
3
+ * Supports API-first with offline-fallback capability
3
4
  */
4
- import { MemoryIntelligenceConfig, AnalyzePatternsParams, PatternAnalysis, SuggestTagsParams, TagSuggestionsResult, FindRelatedParams, RelatedMemoriesResult, DetectDuplicatesParams, DuplicatesResult, ExtractInsightsParams, InsightsResult, HealthCheckParams, MemoryHealth, QueryMemoriesOptions, MemoryEntry } from "./types.js";
5
+ import { MemoryIntelligenceConfig, AnalyzePatternsParams, PatternAnalysis, SuggestTagsParams, TagSuggestionsResult, FindRelatedParams, RelatedMemoriesResult, DetectDuplicatesParams, DuplicatesResult, ExtractInsightsParams, InsightsResult, HealthCheckParams, MemoryHealth, QueryMemoriesOptions, MemoryEntry, ProcessingMode } from "./types.js";
5
6
  import { HttpClient } from "../utils/http-client.js";
7
+ import { UsageInfo, TierInfo } from "../utils/response-adapter.js";
8
+ export interface IntelligenceResponse<T> {
9
+ data: T;
10
+ usage?: UsageInfo;
11
+ tier_info?: TierInfo;
12
+ fromCache?: boolean;
13
+ }
6
14
  export declare class MemoryIntelligenceClient {
7
15
  private httpClient;
8
16
  private defaultResponseFormat;
17
+ private processingMode;
9
18
  constructor(config: MemoryIntelligenceConfig);
19
+ /**
20
+ * Get the current processing mode
21
+ */
22
+ getProcessingMode(): ProcessingMode;
23
+ /**
24
+ * Check if cache is enabled (for offline-fallback mode)
25
+ */
26
+ isCacheEnabled(): boolean;
27
+ /**
28
+ * Clear the response cache
29
+ */
30
+ clearCache(): void;
10
31
  /**
11
32
  * Get HTTP client for direct API access
12
33
  */
@@ -18,26 +39,26 @@ export declare class MemoryIntelligenceClient {
18
39
  /**
19
40
  * Analyze usage patterns and trends in memory collection
20
41
  */
21
- analyzePatterns(params: AnalyzePatternsParams): Promise<PatternAnalysis>;
42
+ analyzePatterns(params: AnalyzePatternsParams): Promise<IntelligenceResponse<PatternAnalysis>>;
22
43
  /**
23
44
  * Get AI-powered tag suggestions for a memory
24
45
  */
25
- suggestTags(params: SuggestTagsParams): Promise<TagSuggestionsResult>;
46
+ suggestTags(params: SuggestTagsParams): Promise<IntelligenceResponse<TagSuggestionsResult>>;
26
47
  /**
27
48
  * Find semantically related memories using vector similarity
28
49
  */
29
- findRelated(params: FindRelatedParams): Promise<RelatedMemoriesResult>;
50
+ findRelated(params: FindRelatedParams): Promise<IntelligenceResponse<RelatedMemoriesResult>>;
30
51
  /**
31
52
  * Detect potential duplicate memories
32
53
  */
33
- detectDuplicates(params: DetectDuplicatesParams): Promise<DuplicatesResult>;
54
+ detectDuplicates(params: DetectDuplicatesParams): Promise<IntelligenceResponse<DuplicatesResult>>;
34
55
  /**
35
56
  * Extract insights and patterns from memories
36
57
  */
37
- extractInsights(params: ExtractInsightsParams): Promise<InsightsResult>;
58
+ extractInsights(params: ExtractInsightsParams): Promise<IntelligenceResponse<InsightsResult>>;
38
59
  /**
39
60
  * Check the health and organization quality of memories
40
61
  */
41
- healthCheck(params: HealthCheckParams): Promise<MemoryHealth>;
62
+ healthCheck(params: HealthCheckParams): Promise<IntelligenceResponse<MemoryHealth>>;
42
63
  }
43
64
  //# sourceMappingURL=client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/core/client.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EACL,wBAAwB,EACxB,qBAAqB,EACrB,eAAe,EACf,iBAAiB,EACjB,oBAAoB,EACpB,iBAAiB,EACjB,qBAAqB,EACrB,sBAAsB,EACtB,gBAAgB,EAChB,qBAAqB,EACrB,cAAc,EACd,iBAAiB,EACjB,YAAY,EACZ,oBAAoB,EACpB,WAAW,EACZ,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAIrD,qBAAa,wBAAwB;IACnC,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,q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// src/utils/response-adapter.ts
46
+ function adaptEdgeFunctionResponse(httpResponse) {
47
+ if (httpResponse.error) {
48
+ return {
49
+ status: httpResponse.status,
50
+ error: httpResponse.error
51
+ };
52
+ }
53
+ const envelope = httpResponse.data;
54
+ if (!envelope) {
55
+ return {
56
+ status: httpResponse.status,
57
+ error: {
58
+ message: "Empty response from server",
59
+ code: "EMPTY_RESPONSE"
60
+ }
61
+ };
62
+ }
63
+ if (!envelope.success && envelope.error) {
64
+ return {
65
+ status: httpResponse.status,
66
+ error: envelope.error,
67
+ usage: envelope.usage,
68
+ tier_info: envelope.tier_info
69
+ };
70
+ }
71
+ return {
72
+ status: httpResponse.status,
73
+ data: envelope.data,
74
+ usage: envelope.usage,
75
+ tier_info: envelope.tier_info
76
+ };
77
+ }
78
+ function isEdgeFunctionEnvelope(data) {
79
+ if (typeof data !== "object" || data === null) {
80
+ return false;
81
+ }
82
+ const obj = data;
83
+ return "success" in obj && typeof obj.success === "boolean";
84
+ }
85
+ function adaptResponse(httpResponse) {
86
+ if (httpResponse.error) {
87
+ return {
88
+ status: httpResponse.status,
89
+ error: httpResponse.error
90
+ };
91
+ }
92
+ const responseData = httpResponse.data;
93
+ if (isEdgeFunctionEnvelope(responseData)) {
94
+ return adaptEdgeFunctionResponse({
95
+ status: httpResponse.status,
96
+ data: responseData
97
+ });
98
+ }
99
+ return {
100
+ status: httpResponse.status,
101
+ data: responseData
102
+ };
103
+ }
104
+ var ResponseCache = class {
105
+ cache = /* @__PURE__ */ new Map();
106
+ ttl;
107
+ constructor(ttlMs = 3e5) {
108
+ this.ttl = ttlMs;
109
+ }
110
+ generateKey(endpoint, params) {
111
+ const paramStr = params ? JSON.stringify(params) : "";
112
+ return `${endpoint}:${paramStr}`;
113
+ }
114
+ set(endpoint, data, params) {
115
+ const key = this.generateKey(endpoint, params);
116
+ this.cache.set(key, {
117
+ data,
118
+ timestamp: Date.now(),
119
+ endpoint,
120
+ params
121
+ });
122
+ }
123
+ get(endpoint, params) {
124
+ const key = this.generateKey(endpoint, params);
125
+ const entry = this.cache.get(key);
126
+ if (!entry) {
127
+ return null;
128
+ }
129
+ if (Date.now() - entry.timestamp > this.ttl) {
130
+ this.cache.delete(key);
131
+ return null;
132
+ }
133
+ return entry.data;
134
+ }
135
+ clear() {
136
+ this.cache.clear();
137
+ }
138
+ /**
139
+ * Clean up expired entries
140
+ */
141
+ cleanup() {
142
+ const now = Date.now();
143
+ for (const [key, entry] of this.cache.entries()) {
144
+ if (now - entry.timestamp > this.ttl) {
145
+ this.cache.delete(key);
146
+ }
147
+ }
148
+ }
149
+ };
150
+
45
151
  // src/utils/http-client.ts
46
152
  var HttpClient = class {
47
153
  apiUrl;
48
154
  apiKey;
49
155
  timeout;
50
156
  headers;
157
+ processingMode;
158
+ cache;
51
159
  constructor(config) {
52
160
  if (!config.apiKey) {
53
161
  throw new ConfigurationError("API key is required");
@@ -60,11 +168,35 @@ var HttpClient = class {
60
168
  this.apiUrl = config.apiUrl.replace(/\/$/, "");
61
169
  this.apiKey = config.apiKey;
62
170
  this.timeout = config.timeout || 3e4;
171
+ this.processingMode = config.processingMode || "api";
63
172
  this.headers = {
64
173
  "Content-Type": "application/json",
65
174
  "X-API-Key": this.apiKey,
66
175
  ...config.headers
67
176
  };
177
+ if (config.enableCache !== false && this.processingMode === "offline-fallback") {
178
+ this.cache = new ResponseCache(config.cacheTTL || 3e5);
179
+ } else {
180
+ this.cache = null;
181
+ }
182
+ }
183
+ /**
184
+ * Get the current processing mode
185
+ */
186
+ getProcessingMode() {
187
+ return this.processingMode;
188
+ }
189
+ /**
190
+ * Check if cache is enabled
191
+ */
192
+ isCacheEnabled() {
193
+ return this.cache !== null;
194
+ }
195
+ /**
196
+ * Clear the response cache
197
+ */
198
+ clearCache() {
199
+ this.cache?.clear();
68
200
  }
69
201
  async request(method, endpoint, data) {
70
202
  const url = `${this.apiUrl}${endpoint}`;
@@ -124,6 +256,43 @@ var HttpClient = class {
124
256
  };
125
257
  }
126
258
  }
259
+ /**
260
+ * Enhanced request that handles Edge Function envelope format
261
+ * and supports offline-fallback caching
262
+ */
263
+ async enhancedRequest(method, endpoint, data) {
264
+ const cacheKey = data ? JSON.stringify(data) : void 0;
265
+ const rawResponse = await this.request(method, endpoint, data);
266
+ if (rawResponse.error?.code === "NETWORK_ERROR" || rawResponse.error?.code === "TIMEOUT") {
267
+ if (this.processingMode === "offline-fallback" && this.cache) {
268
+ const cached = this.cache.get(endpoint, cacheKey ? JSON.parse(cacheKey) : void 0);
269
+ if (cached) {
270
+ return {
271
+ status: 200,
272
+ data: cached,
273
+ fromCache: true
274
+ };
275
+ }
276
+ }
277
+ return {
278
+ status: rawResponse.status,
279
+ error: rawResponse.error,
280
+ fromCache: false
281
+ };
282
+ }
283
+ const adapted = adaptResponse(rawResponse);
284
+ if (!adapted.error && adapted.data && this.cache) {
285
+ this.cache.set(endpoint, adapted.data, cacheKey ? JSON.parse(cacheKey) : void 0);
286
+ }
287
+ return {
288
+ status: adapted.status,
289
+ data: adapted.data,
290
+ error: adapted.error,
291
+ usage: adapted.usage,
292
+ tier_info: adapted.tier_info,
293
+ fromCache: false
294
+ };
295
+ }
127
296
  async get(endpoint) {
128
297
  return this.request("GET", endpoint);
129
298
  }
@@ -139,6 +308,22 @@ var HttpClient = class {
139
308
  async delete(endpoint) {
140
309
  return this.request("DELETE", endpoint);
141
310
  }
311
+ // Enhanced methods with Edge Function envelope support
312
+ async getEnhanced(endpoint) {
313
+ return this.enhancedRequest("GET", endpoint);
314
+ }
315
+ async postEnhanced(endpoint, data) {
316
+ return this.enhancedRequest("POST", endpoint, data);
317
+ }
318
+ async putEnhanced(endpoint, data) {
319
+ return this.enhancedRequest("PUT", endpoint, data);
320
+ }
321
+ async patchEnhanced(endpoint, data) {
322
+ return this.enhancedRequest("PATCH", endpoint, data);
323
+ }
324
+ async deleteEnhanced(endpoint) {
325
+ return this.enhancedRequest("DELETE", endpoint);
326
+ }
142
327
  };
143
328
 
144
329
  // src/core/client.ts
@@ -146,20 +331,43 @@ var DEFAULT_API_URL = "https://api.lanonasis.com/api/v1";
146
331
  var MemoryIntelligenceClient = class {
147
332
  httpClient;
148
333
  defaultResponseFormat;
334
+ processingMode;
149
335
  constructor(config) {
150
336
  if (!config.apiKey) {
151
337
  throw new ConfigurationError(
152
338
  "Missing required configuration: apiKey is required (format: lano_xxxxxxxxxx)"
153
339
  );
154
340
  }
341
+ this.processingMode = config.processingMode || "api";
155
342
  this.httpClient = new HttpClient({
156
343
  apiUrl: config.apiUrl || DEFAULT_API_URL,
157
344
  apiKey: config.apiKey,
158
345
  timeout: config.timeout,
159
- headers: config.headers
346
+ headers: config.headers,
347
+ processingMode: this.processingMode,
348
+ enableCache: config.enableCache,
349
+ cacheTTL: config.cacheTTL
160
350
  });
161
351
  this.defaultResponseFormat = config.responseFormat || "markdown";
162
352
  }
353
+ /**
354
+ * Get the current processing mode
355
+ */
356
+ getProcessingMode() {
357
+ return this.processingMode;
358
+ }
359
+ /**
360
+ * Check if cache is enabled (for offline-fallback mode)
361
+ */
362
+ isCacheEnabled() {
363
+ return this.httpClient.isCacheEnabled();
364
+ }
365
+ /**
366
+ * Clear the response cache
367
+ */
368
+ clearCache() {
369
+ this.httpClient.clearCache();
370
+ }
163
371
  /**
164
372
  * Get HTTP client for direct API access
165
373
  */
@@ -191,7 +399,7 @@ var MemoryIntelligenceClient = class {
191
399
  * Analyze usage patterns and trends in memory collection
192
400
  */
193
401
  async analyzePatterns(params) {
194
- const response = await this.httpClient.post(
402
+ const response = await this.httpClient.postEnhanced(
195
403
  "/intelligence/analyze-patterns",
196
404
  {
197
405
  ...params,
@@ -201,13 +409,18 @@ var MemoryIntelligenceClient = class {
201
409
  if (response.error) {
202
410
  throw new DatabaseError(`Failed to analyze patterns: ${response.error.message}`);
203
411
  }
204
- return response.data;
412
+ return {
413
+ data: response.data,
414
+ usage: response.usage,
415
+ tier_info: response.tier_info,
416
+ fromCache: response.fromCache
417
+ };
205
418
  }
206
419
  /**
207
420
  * Get AI-powered tag suggestions for a memory
208
421
  */
209
422
  async suggestTags(params) {
210
- const response = await this.httpClient.post(
423
+ const response = await this.httpClient.postEnhanced(
211
424
  "/intelligence/suggest-tags",
212
425
  {
213
426
  ...params,
@@ -217,13 +430,18 @@ var MemoryIntelligenceClient = class {
217
430
  if (response.error) {
218
431
  throw new DatabaseError(`Failed to suggest tags: ${response.error.message}`);
219
432
  }
220
- return response.data;
433
+ return {
434
+ data: response.data,
435
+ usage: response.usage,
436
+ tier_info: response.tier_info,
437
+ fromCache: response.fromCache
438
+ };
221
439
  }
222
440
  /**
223
441
  * Find semantically related memories using vector similarity
224
442
  */
225
443
  async findRelated(params) {
226
- const response = await this.httpClient.post(
444
+ const response = await this.httpClient.postEnhanced(
227
445
  "/intelligence/find-related",
228
446
  {
229
447
  ...params,
@@ -233,13 +451,18 @@ var MemoryIntelligenceClient = class {
233
451
  if (response.error) {
234
452
  throw new DatabaseError(`Failed to find related memories: ${response.error.message}`);
235
453
  }
236
- return response.data;
454
+ return {
455
+ data: response.data,
456
+ usage: response.usage,
457
+ tier_info: response.tier_info,
458
+ fromCache: response.fromCache
459
+ };
237
460
  }
238
461
  /**
239
462
  * Detect potential duplicate memories
240
463
  */
241
464
  async detectDuplicates(params) {
242
- const response = await this.httpClient.post(
465
+ const response = await this.httpClient.postEnhanced(
243
466
  "/intelligence/detect-duplicates",
244
467
  {
245
468
  ...params,
@@ -249,13 +472,18 @@ var MemoryIntelligenceClient = class {
249
472
  if (response.error) {
250
473
  throw new DatabaseError(`Failed to detect duplicates: ${response.error.message}`);
251
474
  }
252
- return response.data;
475
+ return {
476
+ data: response.data,
477
+ usage: response.usage,
478
+ tier_info: response.tier_info,
479
+ fromCache: response.fromCache
480
+ };
253
481
  }
254
482
  /**
255
483
  * Extract insights and patterns from memories
256
484
  */
257
485
  async extractInsights(params) {
258
- const response = await this.httpClient.post(
486
+ const response = await this.httpClient.postEnhanced(
259
487
  "/intelligence/extract-insights",
260
488
  {
261
489
  ...params,
@@ -265,13 +493,18 @@ var MemoryIntelligenceClient = class {
265
493
  if (response.error) {
266
494
  throw new DatabaseError(`Failed to extract insights: ${response.error.message}`);
267
495
  }
268
- return response.data;
496
+ return {
497
+ data: response.data,
498
+ usage: response.usage,
499
+ tier_info: response.tier_info,
500
+ fromCache: response.fromCache
501
+ };
269
502
  }
270
503
  /**
271
504
  * Check the health and organization quality of memories
272
505
  */
273
506
  async healthCheck(params) {
274
- const response = await this.httpClient.post(
507
+ const response = await this.httpClient.postEnhanced(
275
508
  "/intelligence/health-check",
276
509
  {
277
510
  ...params,
@@ -281,7 +514,12 @@ var MemoryIntelligenceClient = class {
281
514
  if (response.error) {
282
515
  throw new DatabaseError(`Failed to check health: ${response.error.message}`);
283
516
  }
284
- return response.data;
517
+ return {
518
+ data: response.data,
519
+ usage: response.usage,
520
+ tier_info: response.tier_info,
521
+ fromCache: response.fromCache
522
+ };
285
523
  }
286
524
  };
287
525
  var ResponseFormat = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/errors.ts","../../src/utils/http-client.ts","../../src/core/client.ts","../../src/core/types.ts"],"names":["z"],"mappings":";;;;;AAIO,IAAM,uBAAA,GAAN,cAAsC,KAAA,CAAM;AAAA,EACjD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AAAA,EACd;AACF;AAEO,IAAM,kBAAA,GAAN,cAAiC,uBAAA,CAAwB;AAAA,EAC9D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AAAA,EACd;AACF;AAEO,IAAM,mBAAA,GAAN,cAAkC,uBAAA,CAAwB;AAAA,EAC/D,YAAY,QAAA,EAAkB;AAC5B,IAAA,KAAA,CAAM,CAAA,kBAAA,EAAqB,QAAQ,CAAA,CAAE,CAAA;AACrC,IAAA,IAAA,CAAK,IAAA,GAAO,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AAEA,IAAA,IAAI,SAAS,KAAA,EAAO;AAClB,MAAA,MAAM,IAAI,aAAA,CAAc,CAAA,4BAAA,EAA+B,QAAA,CAAS,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,IACjF;AAEA,IAAA,OAAO,QAAA,CAAS,IAAA;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,YAAY,MAAA,EAAkD;AAClE,IAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,UAAA,CAAW,IAAA;AAAA,MACrC,4BAAA;AAAA,MACA;AAAA,QACE,GAAG,MAAA;AAAA,QACH,cAAA,EAAgB,MAAA,CAAO,cAAA,IAAkB,IAAA,CAAK;AAAA;AAChD,KACF;AAEA,IAAA,IAAI,SAAS,KAAA,EAAO;AAClB,MAAA,MAAM,IAAI,aAAA,CAAc,CAAA,wBAAA,EAA2B,QAAA,CAAS,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,IAC7E;AAEA,IAAA,OAAO,QAAA,CAAS,IAAA;AAAA,EAClB;AACF;AC/LO,IAAM,cAAA,GAAiB;AAAA,EAC5B,IAAA,EAAM,MAAA;AAAA,EACN,QAAA,EAAU;AACZ;AAKO,IAAM,UAAA,GAAaA,MAAE,IAAA,CAAK;AAAA,EAC/B,SAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAC","file":"index.cjs","sourcesContent":["/**\n * SDK-specific error classes\n */\n\nexport class MemoryIntelligenceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MemoryIntelligenceError\";\n }\n}\n\nexport class ConfigurationError extends MemoryIntelligenceError {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigurationError\";\n }\n}\n\nexport class MemoryNotFoundError extends MemoryIntelligenceError {\n constructor(memoryId: string) {\n super(`Memory not found: ${memoryId}`);\n this.name = \"MemoryNotFoundError\";\n }\n}\n\nexport class DatabaseError extends MemoryIntelligenceError {\n constructor(message: string, public originalError?: Error) {\n super(message);\n this.name = \"DatabaseError\";\n }\n}\n\nexport class EmbeddingError extends MemoryIntelligenceError {\n constructor(message: string, public originalError?: Error) {\n super(message);\n this.name = \"EmbeddingError\";\n }\n}\n\nexport class ValidationError extends MemoryIntelligenceError {\n constructor(message: string) {\n super(message);\n this.name = \"ValidationError\";\n }\n}\n","/**\n * HTTP client for Lanonasis API\n */\n\nimport { ConfigurationError } from \"../core/errors.js\";\n\nexport interface HttpClientConfig {\n apiUrl: string;\n apiKey: string;\n timeout?: number;\n headers?: Record<string, string>;\n}\n\nexport interface ApiResponse<T = any> {\n data?: T;\n error?: {\n message: string;\n code?: string;\n };\n status: number;\n}\n\nexport class HttpClient {\n private apiUrl: string;\n private apiKey: string;\n private timeout: number;\n private headers: Record<string, string>;\n\n constructor(config: HttpClientConfig) {\n if (!config.apiKey) {\n throw new ConfigurationError(\"API key is required\");\n }\n\n if (!config.apiKey.startsWith(\"lano_\")) {\n throw new ConfigurationError(\n \"Invalid API key format. API key should start with 'lano_'\"\n );\n }\n\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\"); // Remove trailing slash\n this.apiKey = config.apiKey;\n this.timeout = config.timeout || 30000;\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"X-API-Key\": this.apiKey,\n ...config.headers,\n };\n }\n\n private async request<T>(\n method: string,\n endpoint: string,\n data?: any\n ): Promise<ApiResponse<T>> {\n const url = `${this.apiUrl}${endpoint}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const options: RequestInit = {\n method,\n headers: this.headers,\n signal: controller.signal,\n };\n\n if (data && (method === \"POST\" || method === \"PUT\" || method === \"PATCH\")) {\n options.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, options);\n clearTimeout(timeoutId);\n\n const responseData = await response.json() as any;\n\n if (!response.ok) {\n return {\n status: response.status,\n error: {\n message: responseData?.message || responseData?.error || \"Request failed\",\n code: responseData?.code,\n },\n };\n }\n\n return {\n status: response.status,\n data: responseData as T,\n };\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n return {\n status: 408,\n error: {\n message: `Request timeout after ${this.timeout}ms`,\n code: \"TIMEOUT\",\n },\n };\n }\n\n return {\n status: 0,\n error: {\n message: error.message,\n code: \"NETWORK_ERROR\",\n },\n };\n }\n\n return {\n status: 0,\n error: {\n message: \"Unknown error occurred\",\n code: \"UNKNOWN_ERROR\",\n },\n };\n }\n }\n\n async get<T>(endpoint: string): Promise<ApiResponse<T>> {\n return this.request<T>(\"GET\", endpoint);\n }\n\n async post<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"POST\", endpoint, data);\n }\n\n async put<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"PUT\", endpoint, data);\n }\n\n async patch<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"PATCH\", endpoint, data);\n }\n\n async delete<T>(endpoint: string): Promise<ApiResponse<T>> {\n return this.request<T>(\"DELETE\", endpoint);\n }\n}\n","/**\n * Core Memory Intelligence Client\n */\n\nimport {\n MemoryIntelligenceConfig,\n AnalyzePatternsParams,\n PatternAnalysis,\n SuggestTagsParams,\n TagSuggestionsResult,\n FindRelatedParams,\n RelatedMemoriesResult,\n DetectDuplicatesParams,\n DuplicatesResult,\n ExtractInsightsParams,\n InsightsResult,\n HealthCheckParams,\n MemoryHealth,\n QueryMemoriesOptions,\n MemoryEntry,\n} from \"./types.js\";\nimport { ConfigurationError, DatabaseError } from \"./errors.js\";\nimport { HttpClient } from \"../utils/http-client.js\";\n\nconst DEFAULT_API_URL = \"https://api.lanonasis.com/api/v1\";\n\nexport class MemoryIntelligenceClient {\n private httpClient: HttpClient;\n private defaultResponseFormat: \"json\" | \"markdown\";\n\n constructor(config: MemoryIntelligenceConfig) {\n // Validate configuration\n if (!config.apiKey) {\n throw new ConfigurationError(\n \"Missing required configuration: apiKey is required (format: lano_xxxxxxxxxx)\"\n );\n }\n\n this.httpClient = new HttpClient({\n apiUrl: config.apiUrl || DEFAULT_API_URL,\n apiKey: config.apiKey,\n timeout: config.timeout,\n headers: config.headers,\n });\n\n this.defaultResponseFormat = config.responseFormat || \"markdown\";\n }\n\n /**\n * Get HTTP client for direct API access\n */\n public getHttpClient(): HttpClient {\n return this.httpClient;\n }\n\n /**\n * Query memories from the API\n */\n public async queryMemories(\n userId: string,\n options: QueryMemoriesOptions = {}\n ): Promise<MemoryEntry[]> {\n const { type, limit = 100, offset = 0 } = options;\n\n const params = new URLSearchParams({\n user_id: userId,\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (type) {\n params.append(\"type\", type);\n }\n\n const response = await this.httpClient.get<{ memories: MemoryEntry[] }>(\n `/intelligence/memories?${params.toString()}`\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to query memories: ${response.error.message}`);\n }\n\n return response.data?.memories || [];\n }\n\n /**\n * Analyze usage patterns and trends in memory collection\n */\n async analyzePatterns(params: AnalyzePatternsParams): Promise<PatternAnalysis> {\n const response = await this.httpClient.post<PatternAnalysis>(\n \"/intelligence/analyze-patterns\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to analyze patterns: ${response.error.message}`);\n }\n\n return response.data!;\n }\n\n /**\n * Get AI-powered tag suggestions for a memory\n */\n async suggestTags(params: SuggestTagsParams): Promise<TagSuggestionsResult> {\n const response = await this.httpClient.post<TagSuggestionsResult>(\n \"/intelligence/suggest-tags\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to suggest tags: ${response.error.message}`);\n }\n\n return response.data!;\n }\n\n /**\n * Find semantically related memories using vector similarity\n */\n async findRelated(params: FindRelatedParams): Promise<RelatedMemoriesResult> {\n const response = await this.httpClient.post<RelatedMemoriesResult>(\n \"/intelligence/find-related\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to find related memories: ${response.error.message}`);\n }\n\n return response.data!;\n }\n\n /**\n * Detect potential duplicate memories\n */\n async detectDuplicates(params: DetectDuplicatesParams): Promise<DuplicatesResult> {\n const response = await this.httpClient.post<DuplicatesResult>(\n \"/intelligence/detect-duplicates\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to detect duplicates: ${response.error.message}`);\n }\n\n return response.data!;\n }\n\n /**\n * Extract insights and patterns from memories\n */\n async extractInsights(params: ExtractInsightsParams): Promise<InsightsResult> {\n const response = await this.httpClient.post<InsightsResult>(\n \"/intelligence/extract-insights\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to extract insights: ${response.error.message}`);\n }\n\n return response.data!;\n }\n\n /**\n * Check the health and organization quality of memories\n */\n async healthCheck(params: HealthCheckParams): Promise<MemoryHealth> {\n const response = await this.httpClient.post<MemoryHealth>(\n \"/intelligence/health-check\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to check health: ${response.error.message}`);\n }\n\n return response.data!;\n }\n}\n","/**\n * Type definitions for Memory Intelligence SDK\n */\n\nimport { z } from \"zod\";\n\n// Response format enum\nexport const ResponseFormat = {\n JSON: \"json\",\n MARKDOWN: \"markdown\",\n} as const;\n\nexport type ResponseFormatType = (typeof ResponseFormat)[keyof typeof ResponseFormat];\n\n// Memory type enum\nexport const MemoryType = z.enum([\n \"context\",\n \"project\",\n \"knowledge\",\n \"reference\",\n \"personal\",\n \"workflow\",\n]);\n\nexport type MemoryTypeValue = z.infer<typeof MemoryType>;\n\n// Configuration interface\nexport interface MemoryIntelligenceConfig {\n apiUrl?: string; // Lanonasis API URL (default: https://api.lanonasis.com/api/v1)\n apiKey: string; // Lanonasis API key (format: lano_xxxxxxxxxx)\n timeout?: number; // Request timeout in milliseconds (default: 30000)\n responseFormat?: ResponseFormatType;\n headers?: Record<string, string>; // Custom headers\n}\n\n// Tool parameter interfaces\nexport interface AnalyzePatternsParams {\n userId: string;\n timeRangeDays?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface SuggestTagsParams {\n memoryId: string;\n userId: string;\n maxSuggestions?: number;\n includeExistingTags?: boolean;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface FindRelatedParams {\n memoryId: string;\n userId: string;\n limit?: number;\n similarityThreshold?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface DetectDuplicatesParams {\n userId: string;\n similarityThreshold?: number;\n maxPairs?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface ExtractInsightsParams {\n userId: string;\n topic?: string;\n memoryType?: MemoryTypeValue;\n maxMemories?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface HealthCheckParams {\n userId: string;\n responseFormat?: ResponseFormatType;\n}\n\n// Tool result interfaces\nexport interface PatternAnalysis {\n total_memories: number;\n memories_by_type: Record<string, number>;\n memories_by_day_of_week: Record<string, number>;\n peak_creation_hours: number[];\n average_content_length: number;\n most_common_tags: Array<{ tag: string; count: number }>;\n creation_velocity: {\n daily_average: number;\n trend: \"increasing\" | \"stable\" | \"decreasing\";\n };\n insights: string[];\n}\n\nexport interface TagSuggestion {\n tag: string;\n confidence: number;\n reasoning: string;\n}\n\nexport interface TagSuggestionsResult {\n memory_id: string;\n existing_tags: string[];\n suggestions: TagSuggestion[];\n context: {\n memory_type: string;\n related_memories_analyzed: number;\n };\n}\n\nexport interface RelatedMemory {\n id: string;\n title: string;\n type: string;\n similarity_score: number;\n shared_tags: string[];\n content_preview: string;\n}\n\nexport interface RelatedMemoriesResult {\n source_memory: {\n id: string;\n title: string;\n type: string;\n };\n related_memories: RelatedMemory[];\n total_found: number;\n}\n\nexport interface DuplicatePair {\n memory_1: {\n id: string;\n title: string;\n created_at: string;\n };\n memory_2: {\n id: string;\n title: string;\n created_at: string;\n };\n similarity_score: number;\n recommendation: \"keep_newer\" | \"keep_older\" | \"merge\" | \"review_manually\";\n reasoning: string;\n}\n\nexport interface DuplicatesResult {\n total_memories_analyzed: number;\n duplicate_pairs_found: number;\n duplicate_pairs: DuplicatePair[];\n estimated_storage_savings: string;\n}\n\nexport interface Insight {\n category: \"pattern\" | \"learning\" | \"opportunity\" | \"risk\" | \"action_item\";\n title: string;\n description: string;\n confidence: number;\n supporting_memories: string[];\n}\n\nexport interface InsightsResult {\n total_memories_analyzed: number;\n insights: Insight[];\n summary: string;\n topic_filter?: string;\n type_filter?: string;\n}\n\nexport interface MemoryHealth {\n user_id: string;\n health_score: number;\n metrics: {\n total_memories: number;\n memories_with_embeddings: number;\n embedding_coverage_percentage: number;\n memories_with_tags: number;\n tagging_percentage: number;\n average_tags_per_memory: number;\n memories_by_type: Record<string, number>;\n };\n issues: string[];\n recommendations: string[];\n analysis_date: string;\n}\n\n// Memory entry interface (from database)\nexport interface MemoryEntry {\n id: string;\n user_id: string;\n title: string;\n content: string;\n type: MemoryTypeValue;\n tags?: string[];\n metadata?: Record<string, any>;\n embedding?: number[];\n created_at: string;\n updated_at: string;\n}\n\n// Query options for internal use\nexport interface QueryMemoriesOptions {\n type?: string;\n limit?: number;\n offset?: number;\n includeEmbeddings?: boolean;\n}\n"]}
1
+ {"version":3,"sources":["../../src/core/errors.ts","../../src/utils/response-adapter.ts","../../src/utils/http-client.ts","../../src/core/client.ts","../../src/core/types.ts"],"names":["z"],"mappings":";;;;;AAIO,IAAM,uBAAA,GAAN,cAAsC,KAAA,CAAM;AAAA,EACjD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AAAA,EACd;AACF;AAEO,IAAM,kBAAA,GAAN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A,CAAc,CAAA,4BAAA,EAA+B,QAAA,CAAS,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,IACjF;AAEA,IAAA,OAAO;AAAA,MACL,MAAM,QAAA,CAAS,IAAA;AAAA,MACf,OAAO,QAAA,CAAS,KAAA;AAAA,MAChB,WAAW,QAAA,CAAS,SAAA;AAAA,MACpB,WAAW,QAAA,CAAS;AAAA,KACtB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,YAAY,MAAA,EAAwE;AACxF,IAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,UAAA,CAAW,YAAA;AAAA,MACrC,4BAAA;AAAA,MACA;AAAA,QACE,GAAG,MAAA;AAAA,QACH,cAAA,EAAgB,MAAA,CAAO,cAAA,IAAkB,IAAA,CAAK;AAAA;AAChD,KACF;AAEA,IAAA,IAAI,SAAS,KAAA,EAAO;AAClB,MAAA,MAAM,IAAI,aAAA,CAAc,CAAA,wBAAA,EAA2B,QAAA,CAAS,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,IAC7E;AAEA,IAAA,OAAO;AAAA,MACL,MAAM,QAAA,CAAS,IAAA;AAAA,MACf,OAAO,QAAA,CAAS,KAAA;AAAA,MAChB,WAAW,QAAA,CAAS,SAAA;AAAA,MACpB,WAAW,QAAA,CAAS;AAAA,KACtB;AAAA,EACF;AACF;AClQO,IAAM,cAAA,GAAiB;AAAA,EAC5B,IAAA,EAAM,MAAA;AAAA,EACN,QAAA,EAAU;AACZ;AAKO,IAAM,UAAA,GAAaA,MAAE,IAAA,CAAK;AAAA,EAC/B,SAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAC","file":"index.cjs","sourcesContent":["/**\n * SDK-specific error classes\n */\n\nexport class MemoryIntelligenceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MemoryIntelligenceError\";\n }\n}\n\nexport class ConfigurationError extends MemoryIntelligenceError {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigurationError\";\n }\n}\n\nexport class MemoryNotFoundError extends MemoryIntelligenceError {\n constructor(memoryId: string) {\n super(`Memory not found: ${memoryId}`);\n this.name = \"MemoryNotFoundError\";\n }\n}\n\nexport class DatabaseError extends MemoryIntelligenceError {\n constructor(message: string, public originalError?: Error) {\n super(message);\n this.name = \"DatabaseError\";\n }\n}\n\nexport class EmbeddingError extends MemoryIntelligenceError {\n constructor(message: string, public originalError?: Error) {\n super(message);\n this.name = \"EmbeddingError\";\n }\n}\n\nexport class ValidationError extends MemoryIntelligenceError {\n constructor(message: string) {\n super(message);\n this.name = \"ValidationError\";\n }\n}\n","/**\n * Response Adapter for Edge Function envelope format\n * Handles the transition between direct API responses and Edge Function wrapped responses\n */\n\nimport { EdgeFunctionResponse } from \"../core/types.js\";\nimport { ApiResponse } from \"./http-client.js\";\n\nexport interface UsageInfo {\n tokens_used: number;\n cost_usd: number;\n cached: boolean;\n}\n\nexport interface TierInfo {\n tier: string;\n usage_remaining: number;\n}\n\nexport interface UnwrappedResponse<T> {\n data?: T;\n error?: {\n message: string;\n code?: string;\n };\n usage?: UsageInfo;\n tier_info?: TierInfo;\n status: number;\n}\n\n/**\n * Adapts Edge Function envelope response to SDK internal format\n * Edge Functions return: { success, data, error, usage, tier_info }\n * SDK expects: { data, error, status }\n */\nexport function adaptEdgeFunctionResponse<T>(\n httpResponse: ApiResponse<EdgeFunctionResponse<T>>\n): UnwrappedResponse<T> {\n // If HTTP request itself failed\n if (httpResponse.error) {\n return {\n status: httpResponse.status,\n error: httpResponse.error,\n };\n }\n\n const envelope = httpResponse.data;\n\n // If no envelope data (shouldn't happen)\n if (!envelope) {\n return {\n status: httpResponse.status,\n error: {\n message: \"Empty response from server\",\n code: \"EMPTY_RESPONSE\",\n },\n };\n }\n\n // If Edge Function returned an error\n if (!envelope.success && envelope.error) {\n return {\n status: httpResponse.status,\n error: envelope.error,\n usage: envelope.usage,\n tier_info: envelope.tier_info,\n };\n }\n\n // Successful response\n return {\n status: httpResponse.status,\n data: envelope.data,\n usage: envelope.usage,\n tier_info: envelope.tier_info,\n };\n}\n\n/**\n * Checks if a response appears to be an Edge Function envelope\n */\nexport function isEdgeFunctionEnvelope(data: unknown): data is EdgeFunctionResponse<unknown> {\n if (typeof data !== \"object\" || data === null) {\n return false;\n }\n\n const obj = data as Record<string, unknown>;\n return \"success\" in obj && typeof obj.success === \"boolean\";\n}\n\n/**\n * Smart adapter that detects response format and adapts accordingly\n * Supports both direct API responses and Edge Function envelopes\n */\nexport function adaptResponse<T>(\n httpResponse: ApiResponse<T | EdgeFunctionResponse<T>>\n): UnwrappedResponse<T> {\n // If HTTP request itself failed\n if (httpResponse.error) {\n return {\n status: httpResponse.status,\n error: httpResponse.error,\n };\n }\n\n const responseData = httpResponse.data;\n\n // Check if it's an Edge Function envelope\n if (isEdgeFunctionEnvelope(responseData)) {\n return adaptEdgeFunctionResponse({\n status: httpResponse.status,\n data: responseData as EdgeFunctionResponse<T>,\n });\n }\n\n // Direct API response (legacy format)\n return {\n status: httpResponse.status,\n data: responseData as T,\n };\n}\n\n/**\n * Cache entry for offline fallback support\n */\nexport interface CacheEntry<T> {\n data: T;\n timestamp: number;\n endpoint: string;\n params?: Record<string, unknown>;\n}\n\n/**\n * Simple in-memory cache for offline fallback\n */\nexport class ResponseCache {\n private cache: Map<string, CacheEntry<unknown>> = new Map();\n private ttl: number;\n\n constructor(ttlMs: number = 300000) { // Default 5 minutes\n this.ttl = ttlMs;\n }\n\n private generateKey(endpoint: string, params?: Record<string, unknown>): string {\n const paramStr = params ? JSON.stringify(params) : \"\";\n return `${endpoint}:${paramStr}`;\n }\n\n set<T>(endpoint: string, data: T, params?: Record<string, unknown>): void {\n const key = this.generateKey(endpoint, params);\n this.cache.set(key, {\n data,\n timestamp: Date.now(),\n endpoint,\n params,\n });\n }\n\n get<T>(endpoint: string, params?: Record<string, unknown>): T | null {\n const key = this.generateKey(endpoint, params);\n const entry = this.cache.get(key);\n\n if (!entry) {\n return null;\n }\n\n // Check if expired\n if (Date.now() - entry.timestamp > this.ttl) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.data as T;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Clean up expired entries\n */\n cleanup(): void {\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now - entry.timestamp > this.ttl) {\n this.cache.delete(key);\n }\n }\n }\n}\n","/**\n * HTTP client for Lanonasis API\n * Supports Edge Function envelope format with caching for offline fallback\n */\n\nimport { ConfigurationError } from \"../core/errors.js\";\nimport { EdgeFunctionResponse, ProcessingMode } from \"../core/types.js\";\nimport { adaptResponse, ResponseCache, UsageInfo, TierInfo } from \"./response-adapter.js\";\n\nexport interface HttpClientConfig {\n apiUrl: string;\n apiKey: string;\n timeout?: number;\n headers?: Record<string, string>;\n processingMode?: ProcessingMode;\n enableCache?: boolean;\n cacheTTL?: number;\n}\n\nexport interface ApiResponse<T = any> {\n data?: T;\n error?: {\n message: string;\n code?: string;\n };\n status: number;\n}\n\nexport interface EnhancedApiResponse<T = any> extends ApiResponse<T> {\n usage?: UsageInfo;\n tier_info?: TierInfo;\n fromCache?: boolean;\n}\n\nexport class HttpClient {\n private apiUrl: string;\n private apiKey: string;\n private timeout: number;\n private headers: Record<string, string>;\n private processingMode: ProcessingMode;\n private cache: ResponseCache | null;\n\n constructor(config: HttpClientConfig) {\n if (!config.apiKey) {\n throw new ConfigurationError(\"API key is required\");\n }\n\n if (!config.apiKey.startsWith(\"lano_\")) {\n throw new ConfigurationError(\n \"Invalid API key format. API key should start with 'lano_'\"\n );\n }\n\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\"); // Remove trailing slash\n this.apiKey = config.apiKey;\n this.timeout = config.timeout || 30000;\n this.processingMode = config.processingMode || \"api\";\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"X-API-Key\": this.apiKey,\n ...config.headers,\n };\n\n // Initialize cache for offline-fallback mode\n if (config.enableCache !== false && this.processingMode === \"offline-fallback\") {\n this.cache = new ResponseCache(config.cacheTTL || 300000);\n } else {\n this.cache = null;\n }\n }\n\n /**\n * Get the current processing mode\n */\n getProcessingMode(): ProcessingMode {\n return this.processingMode;\n }\n\n /**\n * Check if cache is enabled\n */\n isCacheEnabled(): boolean {\n return this.cache !== null;\n }\n\n /**\n * Clear the response cache\n */\n clearCache(): void {\n this.cache?.clear();\n }\n\n private async request<T>(\n method: string,\n endpoint: string,\n data?: any\n ): Promise<ApiResponse<T>> {\n const url = `${this.apiUrl}${endpoint}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const options: RequestInit = {\n method,\n headers: this.headers,\n signal: controller.signal,\n };\n\n if (data && (method === \"POST\" || method === \"PUT\" || method === \"PATCH\")) {\n options.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, options);\n clearTimeout(timeoutId);\n\n const responseData = await response.json() as any;\n\n if (!response.ok) {\n return {\n status: response.status,\n error: {\n message: responseData?.message || responseData?.error || \"Request failed\",\n code: responseData?.code,\n },\n };\n }\n\n return {\n status: response.status,\n data: responseData as T,\n };\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n return {\n status: 408,\n error: {\n message: `Request timeout after ${this.timeout}ms`,\n code: \"TIMEOUT\",\n },\n };\n }\n\n return {\n status: 0,\n error: {\n message: error.message,\n code: \"NETWORK_ERROR\",\n },\n };\n }\n\n return {\n status: 0,\n error: {\n message: \"Unknown error occurred\",\n code: \"UNKNOWN_ERROR\",\n },\n };\n }\n }\n\n /**\n * Enhanced request that handles Edge Function envelope format\n * and supports offline-fallback caching\n */\n private async enhancedRequest<T>(\n method: string,\n endpoint: string,\n data?: any\n ): Promise<EnhancedApiResponse<T>> {\n const cacheKey = data ? JSON.stringify(data) : undefined;\n\n // Try API request first\n const rawResponse = await this.request<EdgeFunctionResponse<T> | T>(method, endpoint, data);\n\n // Handle network errors with offline fallback\n if (rawResponse.error?.code === \"NETWORK_ERROR\" || rawResponse.error?.code === \"TIMEOUT\") {\n if (this.processingMode === \"offline-fallback\" && this.cache) {\n const cached = this.cache.get<T>(endpoint, cacheKey ? JSON.parse(cacheKey) : undefined);\n if (cached) {\n return {\n status: 200,\n data: cached,\n fromCache: true,\n };\n }\n }\n // No cache available, return original error\n return {\n status: rawResponse.status,\n error: rawResponse.error,\n fromCache: false,\n };\n }\n\n // Adapt response (handles both direct and envelope formats)\n const adapted = adaptResponse<T>(rawResponse);\n\n // Cache successful responses for offline fallback\n if (!adapted.error && adapted.data && this.cache) {\n this.cache.set(endpoint, adapted.data, cacheKey ? JSON.parse(cacheKey) : undefined);\n }\n\n return {\n status: adapted.status,\n data: adapted.data,\n error: adapted.error,\n usage: adapted.usage,\n tier_info: adapted.tier_info,\n fromCache: false,\n };\n }\n\n async get<T>(endpoint: string): Promise<ApiResponse<T>> {\n return this.request<T>(\"GET\", endpoint);\n }\n\n async post<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"POST\", endpoint, data);\n }\n\n async put<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"PUT\", endpoint, data);\n }\n\n async patch<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"PATCH\", endpoint, data);\n }\n\n async delete<T>(endpoint: string): Promise<ApiResponse<T>> {\n return this.request<T>(\"DELETE\", endpoint);\n }\n\n // Enhanced methods with Edge Function envelope support\n\n async getEnhanced<T>(endpoint: string): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"GET\", endpoint);\n }\n\n async postEnhanced<T>(endpoint: string, data?: any): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"POST\", endpoint, data);\n }\n\n async putEnhanced<T>(endpoint: string, data?: any): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"PUT\", endpoint, data);\n }\n\n async patchEnhanced<T>(endpoint: string, data?: any): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"PATCH\", endpoint, data);\n }\n\n async deleteEnhanced<T>(endpoint: string): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"DELETE\", endpoint);\n }\n}\n","/**\n * Core Memory Intelligence Client\n * Supports API-first with offline-fallback capability\n */\n\nimport {\n MemoryIntelligenceConfig,\n AnalyzePatternsParams,\n PatternAnalysis,\n SuggestTagsParams,\n TagSuggestionsResult,\n FindRelatedParams,\n RelatedMemoriesResult,\n DetectDuplicatesParams,\n DuplicatesResult,\n ExtractInsightsParams,\n InsightsResult,\n HealthCheckParams,\n MemoryHealth,\n QueryMemoriesOptions,\n MemoryEntry,\n ProcessingMode,\n} from \"./types.js\";\nimport { ConfigurationError, DatabaseError } from \"./errors.js\";\nimport { HttpClient } from \"../utils/http-client.js\";\nimport { UsageInfo, TierInfo } from \"../utils/response-adapter.js\";\n\nconst DEFAULT_API_URL = \"https://api.lanonasis.com/api/v1\";\n\nexport interface IntelligenceResponse<T> {\n data: T;\n usage?: UsageInfo;\n tier_info?: TierInfo;\n fromCache?: boolean;\n}\n\nexport class MemoryIntelligenceClient {\n private httpClient: HttpClient;\n private defaultResponseFormat: \"json\" | \"markdown\";\n private processingMode: ProcessingMode;\n\n constructor(config: MemoryIntelligenceConfig) {\n // Validate configuration\n if (!config.apiKey) {\n throw new ConfigurationError(\n \"Missing required configuration: apiKey is required (format: lano_xxxxxxxxxx)\"\n );\n }\n\n this.processingMode = config.processingMode || \"api\";\n\n this.httpClient = new HttpClient({\n apiUrl: config.apiUrl || DEFAULT_API_URL,\n apiKey: config.apiKey,\n timeout: config.timeout,\n headers: config.headers,\n processingMode: this.processingMode,\n enableCache: config.enableCache,\n cacheTTL: config.cacheTTL,\n });\n\n this.defaultResponseFormat = config.responseFormat || \"markdown\";\n }\n\n /**\n * Get the current processing mode\n */\n getProcessingMode(): ProcessingMode {\n return this.processingMode;\n }\n\n /**\n * Check if cache is enabled (for offline-fallback mode)\n */\n isCacheEnabled(): boolean {\n return this.httpClient.isCacheEnabled();\n }\n\n /**\n * Clear the response cache\n */\n clearCache(): void {\n this.httpClient.clearCache();\n }\n\n /**\n * Get HTTP client for direct API access\n */\n public getHttpClient(): HttpClient {\n return this.httpClient;\n }\n\n /**\n * Query memories from the API\n */\n public async queryMemories(\n userId: string,\n options: QueryMemoriesOptions = {}\n ): Promise<MemoryEntry[]> {\n const { type, limit = 100, offset = 0 } = options;\n\n const params = new URLSearchParams({\n user_id: userId,\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (type) {\n params.append(\"type\", type);\n }\n\n const response = await this.httpClient.get<{ memories: MemoryEntry[] }>(\n `/intelligence/memories?${params.toString()}`\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to query memories: ${response.error.message}`);\n }\n\n return response.data?.memories || [];\n }\n\n /**\n * Analyze usage patterns and trends in memory collection\n */\n async analyzePatterns(params: AnalyzePatternsParams): Promise<IntelligenceResponse<PatternAnalysis>> {\n const response = await this.httpClient.postEnhanced<PatternAnalysis>(\n \"/intelligence/analyze-patterns\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to analyze patterns: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Get AI-powered tag suggestions for a memory\n */\n async suggestTags(params: SuggestTagsParams): Promise<IntelligenceResponse<TagSuggestionsResult>> {\n const response = await this.httpClient.postEnhanced<TagSuggestionsResult>(\n \"/intelligence/suggest-tags\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to suggest tags: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Find semantically related memories using vector similarity\n */\n async findRelated(params: FindRelatedParams): Promise<IntelligenceResponse<RelatedMemoriesResult>> {\n const response = await this.httpClient.postEnhanced<RelatedMemoriesResult>(\n \"/intelligence/find-related\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to find related memories: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Detect potential duplicate memories\n */\n async detectDuplicates(params: DetectDuplicatesParams): Promise<IntelligenceResponse<DuplicatesResult>> {\n const response = await this.httpClient.postEnhanced<DuplicatesResult>(\n \"/intelligence/detect-duplicates\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to detect duplicates: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Extract insights and patterns from memories\n */\n async extractInsights(params: ExtractInsightsParams): Promise<IntelligenceResponse<InsightsResult>> {\n const response = await this.httpClient.postEnhanced<InsightsResult>(\n \"/intelligence/extract-insights\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to extract insights: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Check the health and organization quality of memories\n */\n async healthCheck(params: HealthCheckParams): Promise<IntelligenceResponse<MemoryHealth>> {\n const response = await this.httpClient.postEnhanced<MemoryHealth>(\n \"/intelligence/health-check\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to check health: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n}\n","/**\n * Type definitions for Memory Intelligence SDK\n */\n\nimport { z } from \"zod\";\n\n// Response format enum\nexport const ResponseFormat = {\n JSON: \"json\",\n MARKDOWN: \"markdown\",\n} as const;\n\nexport type ResponseFormatType = (typeof ResponseFormat)[keyof typeof ResponseFormat];\n\n// Memory type enum\nexport const MemoryType = z.enum([\n \"context\",\n \"project\",\n \"knowledge\",\n \"reference\",\n \"personal\",\n \"workflow\",\n]);\n\nexport type MemoryTypeValue = z.infer<typeof MemoryType>;\n\n// Processing mode for SDK operations\nexport type ProcessingMode = 'api' | 'offline-fallback';\n\n// Configuration interface\nexport interface MemoryIntelligenceConfig {\n apiUrl?: string; // Lanonasis API URL (default: https://api.lanonasis.com/api/v1)\n apiKey: string; // Lanonasis API key (format: lano_xxxxxxxxxx)\n timeout?: number; // Request timeout in milliseconds (default: 30000)\n responseFormat?: ResponseFormatType;\n headers?: Record<string, string>; // Custom headers\n\n /**\n * Processing mode for intelligence operations\n * - 'api': Always use Lanonasis API endpoints (default)\n * - 'offline-fallback': Use API, fall back to cached/local data if unreachable\n * @default 'api'\n */\n processingMode?: ProcessingMode;\n\n /**\n * Enable caching of API responses for offline fallback\n * Only used when processingMode is 'offline-fallback'\n * @default true\n */\n enableCache?: boolean;\n\n /**\n * Cache TTL in milliseconds (default: 5 minutes)\n * @default 300000\n */\n cacheTTL?: number;\n}\n\n// API response wrapper from Edge Functions\nexport interface EdgeFunctionResponse<T> {\n success: boolean;\n data?: T;\n error?: {\n message: string;\n code?: string;\n };\n usage?: {\n tokens_used: number;\n cost_usd: number;\n cached: boolean;\n };\n tier_info?: {\n tier: string;\n usage_remaining: number;\n };\n}\n\n// Tool parameter interfaces\nexport interface AnalyzePatternsParams {\n userId: string;\n timeRangeDays?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface SuggestTagsParams {\n memoryId: string;\n userId: string;\n maxSuggestions?: number;\n includeExistingTags?: boolean;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface FindRelatedParams {\n memoryId: string;\n userId: string;\n limit?: number;\n similarityThreshold?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface DetectDuplicatesParams {\n userId: string;\n similarityThreshold?: number;\n maxPairs?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface ExtractInsightsParams {\n userId: string;\n topic?: string;\n memoryType?: MemoryTypeValue;\n maxMemories?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface HealthCheckParams {\n userId: string;\n responseFormat?: ResponseFormatType;\n}\n\n// Tool result interfaces\nexport interface PatternAnalysis {\n total_memories: number;\n memories_by_type: Record<string, number>;\n memories_by_day_of_week: Record<string, number>;\n peak_creation_hours: number[];\n average_content_length: number;\n most_common_tags: Array<{ tag: string; count: number }>;\n creation_velocity: {\n daily_average: number;\n trend: \"increasing\" | \"stable\" | \"decreasing\";\n };\n insights: string[];\n}\n\nexport interface TagSuggestion {\n tag: string;\n confidence: number;\n reasoning: string;\n}\n\nexport interface TagSuggestionsResult {\n memory_id: string;\n existing_tags: string[];\n suggestions: TagSuggestion[];\n context: {\n memory_type: string;\n related_memories_analyzed: number;\n };\n}\n\nexport interface RelatedMemory {\n id: string;\n title: string;\n type: string;\n similarity_score: number;\n shared_tags: string[];\n content_preview: string;\n}\n\nexport interface RelatedMemoriesResult {\n source_memory: {\n id: string;\n title: string;\n type: string;\n };\n related_memories: RelatedMemory[];\n total_found: number;\n}\n\nexport interface DuplicatePair {\n memory_1: {\n id: string;\n title: string;\n created_at: string;\n };\n memory_2: {\n id: string;\n title: string;\n created_at: string;\n };\n similarity_score: number;\n recommendation: \"keep_newer\" | \"keep_older\" | \"merge\" | \"review_manually\";\n reasoning: string;\n}\n\nexport interface DuplicatesResult {\n total_memories_analyzed: number;\n duplicate_pairs_found: number;\n duplicate_pairs: DuplicatePair[];\n estimated_storage_savings: string;\n}\n\nexport interface Insight {\n category: \"pattern\" | \"learning\" | \"opportunity\" | \"risk\" | \"action_item\";\n title: string;\n description: string;\n confidence: number;\n supporting_memories: string[];\n}\n\nexport interface InsightsResult {\n total_memories_analyzed: number;\n insights: Insight[];\n summary: string;\n topic_filter?: string;\n type_filter?: string;\n}\n\nexport interface MemoryHealth {\n user_id: string;\n health_score: number;\n metrics: {\n total_memories: number;\n memories_with_embeddings: number;\n embedding_coverage_percentage: number;\n memories_with_tags: number;\n tagging_percentage: number;\n average_tags_per_memory: number;\n memories_by_type: Record<string, number>;\n };\n issues: string[];\n recommendations: string[];\n analysis_date: string;\n}\n\n// Memory entry interface (from database)\nexport interface MemoryEntry {\n id: string;\n user_id: string;\n title: string;\n content: string;\n type: MemoryTypeValue;\n tags?: string[];\n metadata?: Record<string, any>;\n embedding?: number[];\n created_at: string;\n updated_at: string;\n}\n\n// Query options for internal use\nexport interface QueryMemoriesOptions {\n type?: string;\n limit?: number;\n offset?: number;\n includeEmbeddings?: boolean;\n}\n"]}
@@ -2,6 +2,7 @@
2
2
  * Core module barrel export
3
3
  */
4
4
  export { MemoryIntelligenceClient } from "./client.js";
5
+ export type { IntelligenceResponse } from "./client.js";
5
6
  export * from "./types.js";
6
7
  export * from "./errors.js";
7
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACxD,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC"}