@lanonasis/memory-client 1.0.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.
@@ -0,0 +1,1031 @@
1
+ import { exec, execSync } from 'child_process';
2
+ import { promisify } from 'util';
3
+ import { z } from 'zod';
4
+
5
+ /**
6
+ * Memory Client class for interacting with the Memory as a Service API
7
+ */
8
+ class MemoryClient {
9
+ constructor(config) {
10
+ this.config = {
11
+ timeout: 30000,
12
+ useGateway: true,
13
+ ...config
14
+ };
15
+ this.baseHeaders = {
16
+ 'Content-Type': 'application/json',
17
+ 'User-Agent': '@lanonasis/memory-client/1.0.0',
18
+ ...config.headers
19
+ };
20
+ // Set authentication headers
21
+ if (config.authToken) {
22
+ this.baseHeaders['Authorization'] = `Bearer ${config.authToken}`;
23
+ }
24
+ else if (config.apiKey) {
25
+ this.baseHeaders['X-API-Key'] = config.apiKey;
26
+ }
27
+ }
28
+ /**
29
+ * Make an HTTP request to the API
30
+ */
31
+ async request(endpoint, options = {}) {
32
+ // Handle gateway vs direct API URL formatting
33
+ const baseUrl = this.config.apiUrl.includes('/api')
34
+ ? this.config.apiUrl.replace('/api', '')
35
+ : this.config.apiUrl;
36
+ const url = `${baseUrl}/api/v1${endpoint}`;
37
+ try {
38
+ const controller = new AbortController();
39
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
40
+ const response = await fetch(url, {
41
+ headers: { ...this.baseHeaders, ...options.headers },
42
+ signal: controller.signal,
43
+ ...options,
44
+ });
45
+ clearTimeout(timeoutId);
46
+ let data;
47
+ const contentType = response.headers.get('content-type');
48
+ if (contentType && contentType.includes('application/json')) {
49
+ data = await response.json();
50
+ }
51
+ else {
52
+ data = await response.text();
53
+ }
54
+ if (!response.ok) {
55
+ return {
56
+ error: data?.error || `HTTP ${response.status}: ${response.statusText}`
57
+ };
58
+ }
59
+ return { data };
60
+ }
61
+ catch (error) {
62
+ if (error instanceof Error && error.name === 'AbortError') {
63
+ return { error: 'Request timeout' };
64
+ }
65
+ return {
66
+ error: error instanceof Error ? error.message : 'Network error'
67
+ };
68
+ }
69
+ }
70
+ /**
71
+ * Test the API connection and authentication
72
+ */
73
+ async healthCheck() {
74
+ return this.request('/health');
75
+ }
76
+ // Memory Operations
77
+ /**
78
+ * Create a new memory
79
+ */
80
+ async createMemory(memory) {
81
+ return this.request('/memory', {
82
+ method: 'POST',
83
+ body: JSON.stringify(memory)
84
+ });
85
+ }
86
+ /**
87
+ * Get a memory by ID
88
+ */
89
+ async getMemory(id) {
90
+ return this.request(`/memory/${encodeURIComponent(id)}`);
91
+ }
92
+ /**
93
+ * Update an existing memory
94
+ */
95
+ async updateMemory(id, updates) {
96
+ return this.request(`/memory/${encodeURIComponent(id)}`, {
97
+ method: 'PUT',
98
+ body: JSON.stringify(updates)
99
+ });
100
+ }
101
+ /**
102
+ * Delete a memory
103
+ */
104
+ async deleteMemory(id) {
105
+ return this.request(`/memory/${encodeURIComponent(id)}`, {
106
+ method: 'DELETE'
107
+ });
108
+ }
109
+ /**
110
+ * List memories with optional filtering and pagination
111
+ */
112
+ async listMemories(options = {}) {
113
+ const params = new URLSearchParams();
114
+ Object.entries(options).forEach(([key, value]) => {
115
+ if (value !== undefined && value !== null) {
116
+ if (Array.isArray(value)) {
117
+ params.append(key, value.join(','));
118
+ }
119
+ else {
120
+ params.append(key, String(value));
121
+ }
122
+ }
123
+ });
124
+ const queryString = params.toString();
125
+ const endpoint = queryString ? `/memory?${queryString}` : '/memory';
126
+ return this.request(endpoint);
127
+ }
128
+ /**
129
+ * Search memories using semantic search
130
+ */
131
+ async searchMemories(request) {
132
+ return this.request('/memory/search', {
133
+ method: 'POST',
134
+ body: JSON.stringify(request)
135
+ });
136
+ }
137
+ /**
138
+ * Bulk delete multiple memories
139
+ */
140
+ async bulkDeleteMemories(memoryIds) {
141
+ return this.request('/memory/bulk/delete', {
142
+ method: 'POST',
143
+ body: JSON.stringify({ memory_ids: memoryIds })
144
+ });
145
+ }
146
+ // Topic Operations
147
+ /**
148
+ * Create a new topic
149
+ */
150
+ async createTopic(topic) {
151
+ return this.request('/topics', {
152
+ method: 'POST',
153
+ body: JSON.stringify(topic)
154
+ });
155
+ }
156
+ /**
157
+ * Get all topics
158
+ */
159
+ async getTopics() {
160
+ return this.request('/topics');
161
+ }
162
+ /**
163
+ * Get a topic by ID
164
+ */
165
+ async getTopic(id) {
166
+ return this.request(`/topics/${encodeURIComponent(id)}`);
167
+ }
168
+ /**
169
+ * Update a topic
170
+ */
171
+ async updateTopic(id, updates) {
172
+ return this.request(`/topics/${encodeURIComponent(id)}`, {
173
+ method: 'PUT',
174
+ body: JSON.stringify(updates)
175
+ });
176
+ }
177
+ /**
178
+ * Delete a topic
179
+ */
180
+ async deleteTopic(id) {
181
+ return this.request(`/topics/${encodeURIComponent(id)}`, {
182
+ method: 'DELETE'
183
+ });
184
+ }
185
+ /**
186
+ * Get user memory statistics
187
+ */
188
+ async getMemoryStats() {
189
+ return this.request('/memory/stats');
190
+ }
191
+ // Utility Methods
192
+ /**
193
+ * Update authentication token
194
+ */
195
+ setAuthToken(token) {
196
+ this.baseHeaders['Authorization'] = `Bearer ${token}`;
197
+ delete this.baseHeaders['X-API-Key'];
198
+ }
199
+ /**
200
+ * Update API key
201
+ */
202
+ setApiKey(apiKey) {
203
+ this.baseHeaders['X-API-Key'] = apiKey;
204
+ delete this.baseHeaders['Authorization'];
205
+ }
206
+ /**
207
+ * Clear authentication
208
+ */
209
+ clearAuth() {
210
+ delete this.baseHeaders['Authorization'];
211
+ delete this.baseHeaders['X-API-Key'];
212
+ }
213
+ /**
214
+ * Update configuration
215
+ */
216
+ updateConfig(updates) {
217
+ this.config = { ...this.config, ...updates };
218
+ if (updates.headers) {
219
+ this.baseHeaders = { ...this.baseHeaders, ...updates.headers };
220
+ }
221
+ }
222
+ /**
223
+ * Get current configuration (excluding sensitive data)
224
+ */
225
+ getConfig() {
226
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
227
+ const { apiKey, authToken, ...safeConfig } = this.config;
228
+ return safeConfig;
229
+ }
230
+ }
231
+ /**
232
+ * Factory function to create a new Memory Client instance
233
+ */
234
+ function createMemoryClient(config) {
235
+ return new MemoryClient(config);
236
+ }
237
+
238
+ /**
239
+ * CLI Integration Module for Memory Client SDK
240
+ *
241
+ * Provides intelligent CLI detection and MCP channel utilization
242
+ * when @lanonasis/cli v1.5.2+ is available in the environment
243
+ */
244
+ const execAsync = promisify(exec);
245
+ /**
246
+ * CLI Detection and Integration Service
247
+ */
248
+ class CLIIntegration {
249
+ constructor() {
250
+ this.cliInfo = null;
251
+ this.detectionPromise = null;
252
+ }
253
+ /**
254
+ * Detect if CLI is available and get its capabilities
255
+ */
256
+ async detectCLI() {
257
+ // Return cached result if already detected
258
+ if (this.cliInfo) {
259
+ return this.cliInfo;
260
+ }
261
+ // Return existing promise if detection is in progress
262
+ if (this.detectionPromise) {
263
+ return this.detectionPromise;
264
+ }
265
+ // Start new detection
266
+ this.detectionPromise = this.performDetection();
267
+ this.cliInfo = await this.detectionPromise;
268
+ return this.cliInfo;
269
+ }
270
+ async performDetection() {
271
+ try {
272
+ // Check if onasis/lanonasis CLI is available
273
+ let versionOutput = '';
274
+ try {
275
+ const { stdout } = await execAsync('onasis --version 2>/dev/null', { timeout: 5000 });
276
+ versionOutput = stdout;
277
+ }
278
+ catch {
279
+ // Try lanonasis if onasis fails
280
+ const { stdout } = await execAsync('lanonasis --version 2>/dev/null', { timeout: 5000 });
281
+ versionOutput = stdout;
282
+ }
283
+ const version = versionOutput.trim();
284
+ // Verify it's v1.5.2 or higher for Golden Contract support
285
+ const versionMatch = version.match(/(\d+)\.(\d+)\.(\d+)/);
286
+ if (!versionMatch) {
287
+ return { available: false };
288
+ }
289
+ const [, major, minor, patch] = versionMatch.map(Number);
290
+ const isCompatible = major > 1 || (major === 1 && minor > 5) || (major === 1 && minor === 5 && patch >= 2);
291
+ if (!isCompatible) {
292
+ return {
293
+ available: true,
294
+ version,
295
+ mcpAvailable: false,
296
+ authenticated: false
297
+ };
298
+ }
299
+ // Check MCP availability
300
+ let mcpAvailable = false;
301
+ try {
302
+ await execAsync('onasis mcp status --output json 2>/dev/null || lanonasis mcp status --output json 2>/dev/null', {
303
+ timeout: 3000
304
+ });
305
+ mcpAvailable = true;
306
+ }
307
+ catch {
308
+ // MCP not available or not configured
309
+ }
310
+ // Check authentication status
311
+ let authenticated = false;
312
+ try {
313
+ const { stdout: authOutput } = await execAsync('onasis auth status --output json 2>/dev/null || lanonasis auth status --output json 2>/dev/null', {
314
+ timeout: 3000
315
+ });
316
+ const authStatus = JSON.parse(authOutput);
317
+ authenticated = authStatus.authenticated === true;
318
+ }
319
+ catch {
320
+ // Authentication check failed
321
+ }
322
+ return {
323
+ available: true,
324
+ version,
325
+ mcpAvailable,
326
+ authenticated
327
+ };
328
+ }
329
+ catch {
330
+ return { available: false };
331
+ }
332
+ }
333
+ /**
334
+ * Execute CLI command and return parsed JSON result
335
+ */
336
+ async executeCLICommand(command, options = {}) {
337
+ const cliInfo = await this.detectCLI();
338
+ if (!cliInfo.available) {
339
+ return { error: 'CLI not available' };
340
+ }
341
+ if (!cliInfo.authenticated) {
342
+ return { error: 'CLI not authenticated. Run: onasis login' };
343
+ }
344
+ try {
345
+ const timeout = options.timeout || 30000;
346
+ const outputFormat = options.outputFormat || 'json';
347
+ const verbose = options.verbose ? '--verbose' : '';
348
+ // Determine which CLI command to use (prefer onasis for Golden Contract)
349
+ const cliCmd = await this.getPreferredCLICommand();
350
+ const fullCommand = `${cliCmd} ${command} --output ${outputFormat} ${verbose}`.trim();
351
+ const { stdout, stderr } = await execAsync(fullCommand, {
352
+ timeout,
353
+ maxBuffer: 1024 * 1024 // 1MB buffer
354
+ });
355
+ if (stderr && stderr.trim()) {
356
+ console.warn('CLI warning:', stderr);
357
+ }
358
+ if (outputFormat === 'json') {
359
+ try {
360
+ const result = JSON.parse(stdout);
361
+ return { data: result };
362
+ }
363
+ catch (parseError) {
364
+ return { error: `Failed to parse CLI JSON output: ${parseError instanceof Error ? parseError.message : 'Unknown error'}` };
365
+ }
366
+ }
367
+ return { data: stdout };
368
+ }
369
+ catch (error) {
370
+ if (error instanceof Error && error.message.includes('timeout')) {
371
+ return { error: 'CLI command timeout' };
372
+ }
373
+ return {
374
+ error: error instanceof Error ? error.message : 'CLI command failed'
375
+ };
376
+ }
377
+ }
378
+ /**
379
+ * Get preferred CLI command (onasis for Golden Contract, fallback to lanonasis)
380
+ */
381
+ async getPreferredCLICommand() {
382
+ try {
383
+ execSync('which onasis', { stdio: 'ignore', timeout: 1000 });
384
+ return 'onasis';
385
+ }
386
+ catch {
387
+ return 'lanonasis';
388
+ }
389
+ }
390
+ /**
391
+ * Memory operations via CLI
392
+ */
393
+ async createMemoryViaCLI(title, content, options = {}) {
394
+ const { memoryType = 'context', tags = [], topicId } = options;
395
+ let command = `memory create --title "${title}" --content "${content}" --memory-type ${memoryType}`;
396
+ if (tags.length > 0) {
397
+ command += ` --tags "${tags.join(',')}"`;
398
+ }
399
+ if (topicId) {
400
+ command += ` --topic-id "${topicId}"`;
401
+ }
402
+ return this.executeCLICommand(command);
403
+ }
404
+ async listMemoriesViaCLI(options = {}) {
405
+ let command = 'memory list';
406
+ if (options.limit) {
407
+ command += ` --limit ${options.limit}`;
408
+ }
409
+ if (options.memoryType) {
410
+ command += ` --memory-type ${options.memoryType}`;
411
+ }
412
+ if (options.tags && options.tags.length > 0) {
413
+ command += ` --tags "${options.tags.join(',')}"`;
414
+ }
415
+ if (options.sortBy) {
416
+ command += ` --sort-by ${options.sortBy}`;
417
+ }
418
+ return this.executeCLICommand(command);
419
+ }
420
+ async searchMemoriesViaCLI(query, options = {}) {
421
+ let command = `memory search "${query}"`;
422
+ if (options.limit) {
423
+ command += ` --limit ${options.limit}`;
424
+ }
425
+ if (options.memoryTypes && options.memoryTypes.length > 0) {
426
+ command += ` --memory-types "${options.memoryTypes.join(',')}"`;
427
+ }
428
+ return this.executeCLICommand(command);
429
+ }
430
+ /**
431
+ * Health check via CLI
432
+ */
433
+ async healthCheckViaCLI() {
434
+ return this.executeCLICommand('health');
435
+ }
436
+ /**
437
+ * MCP-specific operations
438
+ */
439
+ async getMCPStatus() {
440
+ const cliInfo = await this.detectCLI();
441
+ if (!cliInfo.mcpAvailable) {
442
+ return { error: 'MCP not available via CLI' };
443
+ }
444
+ return this.executeCLICommand('mcp status');
445
+ }
446
+ async listMCPTools() {
447
+ const cliInfo = await this.detectCLI();
448
+ if (!cliInfo.mcpAvailable) {
449
+ return { error: 'MCP not available via CLI' };
450
+ }
451
+ return this.executeCLICommand('mcp tools');
452
+ }
453
+ /**
454
+ * Authentication operations
455
+ */
456
+ async getAuthStatus() {
457
+ return this.executeCLICommand('auth status');
458
+ }
459
+ /**
460
+ * Check if specific CLI features are available
461
+ */
462
+ async getCapabilities() {
463
+ const cliInfo = await this.detectCLI();
464
+ return {
465
+ cliAvailable: cliInfo.available,
466
+ version: cliInfo.version,
467
+ mcpSupport: cliInfo.mcpAvailable || false,
468
+ authenticated: cliInfo.authenticated || false,
469
+ goldenContract: cliInfo.available && this.isGoldenContractCompliant(cliInfo.version)
470
+ };
471
+ }
472
+ isGoldenContractCompliant(version) {
473
+ if (!version)
474
+ return false;
475
+ const versionMatch = version.match(/(\d+)\.(\d+)\.(\d+)/);
476
+ if (!versionMatch)
477
+ return false;
478
+ const [, major, minor, patch] = versionMatch.map(Number);
479
+ return major > 1 || (major === 1 && minor > 5) || (major === 1 && minor === 5 && patch >= 2);
480
+ }
481
+ /**
482
+ * Force refresh CLI detection
483
+ */
484
+ async refresh() {
485
+ this.cliInfo = null;
486
+ this.detectionPromise = null;
487
+ return this.detectCLI();
488
+ }
489
+ /**
490
+ * Get cached CLI info without re-detection
491
+ */
492
+ getCachedInfo() {
493
+ return this.cliInfo;
494
+ }
495
+ }
496
+
497
+ /**
498
+ * Enhanced Memory Client with CLI Integration
499
+ *
500
+ * Intelligently routes requests through CLI v1.5.2+ when available,
501
+ * with fallback to direct API for maximum compatibility and performance
502
+ */
503
+ /**
504
+ * Enhanced Memory Client with intelligent CLI/API routing
505
+ */
506
+ class EnhancedMemoryClient {
507
+ createDefaultCapabilities() {
508
+ return {
509
+ cliAvailable: false,
510
+ mcpSupport: false,
511
+ authenticated: false,
512
+ goldenContract: false
513
+ };
514
+ }
515
+ constructor(config) {
516
+ this.capabilities = null;
517
+ this.config = {
518
+ preferCLI: true,
519
+ enableMCP: true,
520
+ cliDetectionTimeout: 5000,
521
+ fallbackToAPI: true,
522
+ minCLIVersion: '1.5.2',
523
+ verbose: false,
524
+ timeout: 30000,
525
+ useGateway: true,
526
+ apiKey: config.apiKey || process.env.LANONASIS_API_KEY || '',
527
+ authToken: config.authToken || '',
528
+ headers: config.headers || {},
529
+ ...config
530
+ };
531
+ this.directClient = new MemoryClient(config);
532
+ this.cliIntegration = new CLIIntegration();
533
+ }
534
+ /**
535
+ * Initialize the client and detect capabilities
536
+ */
537
+ async initialize() {
538
+ try {
539
+ const detectionPromise = this.cliIntegration.getCapabilities();
540
+ const capabilities = this.config.cliDetectionTimeout > 0
541
+ ? await Promise.race([
542
+ detectionPromise,
543
+ new Promise((resolve) => {
544
+ setTimeout(() => resolve(null), this.config.cliDetectionTimeout);
545
+ })
546
+ ])
547
+ : await detectionPromise;
548
+ if (capabilities) {
549
+ this.capabilities = capabilities;
550
+ if (this.config.verbose && capabilities.cliAvailable && !capabilities.authenticated) {
551
+ const suggestedCommand = capabilities.goldenContract ? 'onasis login' : 'lanonasis login';
552
+ console.warn(`CLI detected but not authenticated. Run '${suggestedCommand}' to enable enhanced SDK features.`);
553
+ }
554
+ }
555
+ else {
556
+ this.capabilities = this.createDefaultCapabilities();
557
+ if (this.config.verbose) {
558
+ console.warn(`CLI detection timed out after ${this.config.cliDetectionTimeout}ms. Falling back to API mode.`);
559
+ }
560
+ }
561
+ }
562
+ catch (error) {
563
+ if (this.config.verbose) {
564
+ console.warn('CLI detection failed:', error);
565
+ }
566
+ this.capabilities = this.createDefaultCapabilities();
567
+ }
568
+ }
569
+ /**
570
+ * Get current capabilities
571
+ */
572
+ async getCapabilities() {
573
+ if (!this.capabilities) {
574
+ await this.initialize();
575
+ }
576
+ return this.capabilities;
577
+ }
578
+ /**
579
+ * Determine if operation should use CLI
580
+ */
581
+ async shouldUseCLI() {
582
+ const capabilities = await this.getCapabilities();
583
+ return (this.config.preferCLI &&
584
+ capabilities.cliAvailable &&
585
+ capabilities.authenticated &&
586
+ capabilities.goldenContract);
587
+ }
588
+ /**
589
+ * Execute operation with intelligent routing
590
+ */
591
+ async executeOperation(operation, cliOperation, apiOperation) {
592
+ const useCLI = await this.shouldUseCLI();
593
+ const capabilities = await this.getCapabilities();
594
+ if (useCLI) {
595
+ try {
596
+ const result = await cliOperation();
597
+ if (result.error && this.config.fallbackToAPI) {
598
+ console.warn(`CLI ${operation} failed, falling back to API:`, result.error);
599
+ const apiResult = await apiOperation();
600
+ return {
601
+ ...apiResult,
602
+ source: 'api',
603
+ mcpUsed: false
604
+ };
605
+ }
606
+ return {
607
+ ...result,
608
+ source: 'cli',
609
+ mcpUsed: capabilities.mcpSupport
610
+ };
611
+ }
612
+ catch (error) {
613
+ if (this.config.fallbackToAPI) {
614
+ console.warn(`CLI ${operation} error, falling back to API:`, error);
615
+ const apiResult = await apiOperation();
616
+ return {
617
+ ...apiResult,
618
+ source: 'api',
619
+ mcpUsed: false
620
+ };
621
+ }
622
+ return {
623
+ error: error instanceof Error ? error.message : `CLI ${operation} failed`,
624
+ source: 'cli',
625
+ mcpUsed: false
626
+ };
627
+ }
628
+ }
629
+ else {
630
+ const result = await apiOperation();
631
+ return {
632
+ ...result,
633
+ source: 'api',
634
+ mcpUsed: false
635
+ };
636
+ }
637
+ }
638
+ // Enhanced API Methods
639
+ /**
640
+ * Health check with intelligent routing
641
+ */
642
+ async healthCheck() {
643
+ return this.executeOperation('health check', () => this.cliIntegration.healthCheckViaCLI(), () => this.directClient.healthCheck());
644
+ }
645
+ /**
646
+ * Create memory with CLI/API routing
647
+ */
648
+ async createMemory(memory) {
649
+ return this.executeOperation('create memory', () => this.cliIntegration.createMemoryViaCLI(memory.title, memory.content, {
650
+ memoryType: memory.memory_type,
651
+ tags: memory.tags,
652
+ topicId: memory.topic_id
653
+ }), () => this.directClient.createMemory(memory));
654
+ }
655
+ /**
656
+ * List memories with intelligent routing
657
+ */
658
+ async listMemories(options = {}) {
659
+ return this.executeOperation('list memories', () => this.cliIntegration.listMemoriesViaCLI({
660
+ limit: options.limit,
661
+ memoryType: options.memory_type,
662
+ tags: options.tags,
663
+ sortBy: options.sort
664
+ }), () => this.directClient.listMemories(options));
665
+ }
666
+ /**
667
+ * Search memories with MCP enhancement when available
668
+ */
669
+ async searchMemories(request) {
670
+ return this.executeOperation('search memories', () => this.cliIntegration.searchMemoriesViaCLI(request.query, {
671
+ limit: request.limit,
672
+ memoryTypes: request.memory_types
673
+ }), () => this.directClient.searchMemories(request));
674
+ }
675
+ /**
676
+ * Get memory by ID (API only for now)
677
+ */
678
+ async getMemory(id) {
679
+ // CLI doesn't have get by ID yet, use API
680
+ const result = await this.directClient.getMemory(id);
681
+ return {
682
+ ...result,
683
+ source: 'api',
684
+ mcpUsed: false
685
+ };
686
+ }
687
+ /**
688
+ * Update memory (API only for now)
689
+ */
690
+ async updateMemory(id, updates) {
691
+ // CLI doesn't have update yet, use API
692
+ const result = await this.directClient.updateMemory(id, updates);
693
+ return {
694
+ ...result,
695
+ source: 'api',
696
+ mcpUsed: false
697
+ };
698
+ }
699
+ /**
700
+ * Delete memory (API only for now)
701
+ */
702
+ async deleteMemory(id) {
703
+ // CLI doesn't have delete yet, use API
704
+ const result = await this.directClient.deleteMemory(id);
705
+ return {
706
+ ...result,
707
+ source: 'api',
708
+ mcpUsed: false
709
+ };
710
+ }
711
+ // Topic Operations (API only for now)
712
+ async createTopic(topic) {
713
+ const result = await this.directClient.createTopic(topic);
714
+ return { ...result, source: 'api', mcpUsed: false };
715
+ }
716
+ async getTopics() {
717
+ const result = await this.directClient.getTopics();
718
+ return { ...result, source: 'api', mcpUsed: false };
719
+ }
720
+ async getTopic(id) {
721
+ const result = await this.directClient.getTopic(id);
722
+ return { ...result, source: 'api', mcpUsed: false };
723
+ }
724
+ async updateTopic(id, updates) {
725
+ const result = await this.directClient.updateTopic(id, updates);
726
+ return { ...result, source: 'api', mcpUsed: false };
727
+ }
728
+ async deleteTopic(id) {
729
+ const result = await this.directClient.deleteTopic(id);
730
+ return { ...result, source: 'api', mcpUsed: false };
731
+ }
732
+ /**
733
+ * Get memory statistics
734
+ */
735
+ async getMemoryStats() {
736
+ const result = await this.directClient.getMemoryStats();
737
+ return { ...result, source: 'api', mcpUsed: false };
738
+ }
739
+ // Utility Methods
740
+ /**
741
+ * Force CLI re-detection
742
+ */
743
+ async refreshCLIDetection() {
744
+ this.capabilities = null;
745
+ await this.cliIntegration.refresh();
746
+ await this.initialize();
747
+ }
748
+ /**
749
+ * Get authentication status from CLI
750
+ */
751
+ async getAuthStatus() {
752
+ try {
753
+ const result = await this.cliIntegration.getAuthStatus();
754
+ return { ...result, source: 'cli', mcpUsed: false };
755
+ }
756
+ catch (error) {
757
+ return {
758
+ error: error instanceof Error ? error.message : 'Auth status check failed',
759
+ source: 'cli',
760
+ mcpUsed: false
761
+ };
762
+ }
763
+ }
764
+ /**
765
+ * Get MCP status when available
766
+ */
767
+ async getMCPStatus() {
768
+ const capabilities = await this.getCapabilities();
769
+ if (!capabilities.mcpSupport) {
770
+ return {
771
+ error: 'MCP not available',
772
+ source: 'cli',
773
+ mcpUsed: false
774
+ };
775
+ }
776
+ try {
777
+ const result = await this.cliIntegration.getMCPStatus();
778
+ return { ...result, source: 'cli', mcpUsed: true };
779
+ }
780
+ catch (error) {
781
+ return {
782
+ error: error instanceof Error ? error.message : 'MCP status check failed',
783
+ source: 'cli',
784
+ mcpUsed: false
785
+ };
786
+ }
787
+ }
788
+ /**
789
+ * Update authentication for both CLI and API client
790
+ */
791
+ setAuthToken(token) {
792
+ this.directClient.setAuthToken(token);
793
+ }
794
+ setApiKey(apiKey) {
795
+ this.directClient.setApiKey(apiKey);
796
+ }
797
+ clearAuth() {
798
+ this.directClient.clearAuth();
799
+ }
800
+ /**
801
+ * Update configuration
802
+ */
803
+ updateConfig(updates) {
804
+ this.config = { ...this.config, ...updates };
805
+ this.directClient.updateConfig(updates);
806
+ }
807
+ /**
808
+ * Get configuration summary
809
+ */
810
+ getConfigSummary() {
811
+ return {
812
+ apiUrl: this.config.apiUrl,
813
+ preferCLI: this.config.preferCLI,
814
+ enableMCP: this.config.enableMCP,
815
+ capabilities: this.capabilities || undefined
816
+ };
817
+ }
818
+ }
819
+ /**
820
+ * Factory function to create an enhanced memory client
821
+ */
822
+ async function createEnhancedMemoryClient(config) {
823
+ const client = new EnhancedMemoryClient(config);
824
+ await client.initialize();
825
+ return client;
826
+ }
827
+
828
+ /**
829
+ * Configuration utilities for Memory Client SDK
830
+ * Provides smart defaults and environment detection for CLI/MCP integration
831
+ */
832
+ /**
833
+ * Environment detection utilities
834
+ */
835
+ const Environment = {
836
+ isNode: typeof globalThis !== 'undefined' && 'process' in globalThis && globalThis.process?.versions?.node,
837
+ isBrowser: typeof window !== 'undefined',
838
+ isVSCode: typeof globalThis !== 'undefined' && 'vscode' in globalThis,
839
+ isCursor: typeof globalThis !== 'undefined' && 'cursor' in globalThis,
840
+ isWindsurf: typeof globalThis !== 'undefined' && 'windsurf' in globalThis,
841
+ get isIDE() {
842
+ return this.isVSCode || this.isCursor || this.isWindsurf;
843
+ },
844
+ get supportsCLI() {
845
+ return Boolean(this.isNode && !this.isBrowser);
846
+ }
847
+ };
848
+ /**
849
+ * Create smart configuration with environment-aware defaults
850
+ */
851
+ function createSmartConfig(baseConfig, options = {}) {
852
+ const defaults = {
853
+ preferCLI: Environment.supportsCLI,
854
+ minCLIVersion: '1.5.2',
855
+ enableMCP: true,
856
+ cliDetectionTimeout: 3000,
857
+ verbose: false
858
+ };
859
+ const config = { ...defaults, ...options };
860
+ return {
861
+ ...baseConfig,
862
+ preferCLI: config.preferCLI,
863
+ minCLIVersion: config.minCLIVersion,
864
+ enableMCP: config.enableMCP,
865
+ cliDetectionTimeout: config.cliDetectionTimeout,
866
+ verbose: config.verbose,
867
+ // Smart API configuration with environment detection
868
+ apiUrl: baseConfig.apiUrl || (process?.env?.NODE_ENV === 'development'
869
+ ? 'http://localhost:3001'
870
+ : 'https://api.lanonasis.com'),
871
+ // Default timeout based on environment
872
+ timeout: baseConfig.timeout || (Environment.isIDE ? 10000 : 15000)
873
+ };
874
+ }
875
+ /**
876
+ * Preset configurations for common scenarios
877
+ */
878
+ const ConfigPresets = {
879
+ /**
880
+ * Development configuration with local API and CLI preference
881
+ */
882
+ development: (apiKey) => createSmartConfig({
883
+ apiUrl: 'http://localhost:3001',
884
+ apiKey,
885
+ timeout: 30000
886
+ }, {
887
+ preferCLI: true,
888
+ verbose: true
889
+ }),
890
+ /**
891
+ * Production configuration optimized for performance
892
+ */
893
+ production: (apiKey) => createSmartConfig({
894
+ apiUrl: 'https://api.lanonasis.com',
895
+ apiKey,
896
+ timeout: 15000
897
+ }, {
898
+ preferCLI: Environment.supportsCLI,
899
+ verbose: false
900
+ }),
901
+ /**
902
+ * IDE extension configuration with MCP prioritization
903
+ */
904
+ ideExtension: (apiKey) => createSmartConfig({
905
+ apiUrl: 'https://api.lanonasis.com',
906
+ apiKey,
907
+ timeout: 10000
908
+ }, {
909
+ preferCLI: true,
910
+ enableMCP: true,
911
+ cliDetectionTimeout: 2000
912
+ }),
913
+ /**
914
+ * Browser-only configuration (no CLI support)
915
+ */
916
+ browserOnly: (apiKey) => createSmartConfig({
917
+ apiUrl: 'https://api.lanonasis.com',
918
+ apiKey,
919
+ timeout: 15000
920
+ }, {
921
+ preferCLI: false,
922
+ enableMCP: false
923
+ }),
924
+ /**
925
+ * CLI-first configuration for server environments
926
+ */
927
+ serverCLI: (apiKey) => createSmartConfig({
928
+ apiUrl: 'https://api.lanonasis.com',
929
+ apiKey,
930
+ timeout: 20000
931
+ }, {
932
+ preferCLI: true,
933
+ enableMCP: true,
934
+ verbose: false
935
+ })
936
+ };
937
+ /**
938
+ * Migration helper for existing MemoryClient users
939
+ */
940
+ function migrateToEnhanced(existingConfig, enhancementOptions = {}) {
941
+ return createSmartConfig(existingConfig, {
942
+ preferCLI: Environment.supportsCLI,
943
+ ...enhancementOptions
944
+ });
945
+ }
946
+
947
+ /**
948
+ * Memory types supported by the service
949
+ */
950
+ const MEMORY_TYPES = ['context', 'project', 'knowledge', 'reference', 'personal', 'workflow'];
951
+ /**
952
+ * Memory status values
953
+ */
954
+ const MEMORY_STATUSES = ['active', 'archived', 'draft', 'deleted'];
955
+ /**
956
+ * Validation schemas using Zod
957
+ */
958
+ const createMemorySchema = z.object({
959
+ title: z.string().min(1).max(500),
960
+ content: z.string().min(1).max(50000),
961
+ summary: z.string().max(1000).optional(),
962
+ memory_type: z.enum(MEMORY_TYPES).default('context'),
963
+ topic_id: z.string().uuid().optional(),
964
+ project_ref: z.string().max(100).optional(),
965
+ tags: z.array(z.string().min(1).max(50)).max(20).default([]),
966
+ metadata: z.record(z.unknown()).optional()
967
+ });
968
+ const updateMemorySchema = z.object({
969
+ title: z.string().min(1).max(500).optional(),
970
+ content: z.string().min(1).max(50000).optional(),
971
+ summary: z.string().max(1000).optional(),
972
+ memory_type: z.enum(MEMORY_TYPES).optional(),
973
+ status: z.enum(MEMORY_STATUSES).optional(),
974
+ topic_id: z.string().uuid().nullable().optional(),
975
+ project_ref: z.string().max(100).nullable().optional(),
976
+ tags: z.array(z.string().min(1).max(50)).max(20).optional(),
977
+ metadata: z.record(z.unknown()).optional()
978
+ });
979
+ const searchMemorySchema = z.object({
980
+ query: z.string().min(1).max(1000),
981
+ memory_types: z.array(z.enum(MEMORY_TYPES)).optional(),
982
+ tags: z.array(z.string()).optional(),
983
+ topic_id: z.string().uuid().optional(),
984
+ project_ref: z.string().optional(),
985
+ status: z.enum(MEMORY_STATUSES).default('active'),
986
+ limit: z.number().int().min(1).max(100).default(20),
987
+ threshold: z.number().min(0).max(1).default(0.7)
988
+ });
989
+ const createTopicSchema = z.object({
990
+ name: z.string().min(1).max(100),
991
+ description: z.string().max(500).optional(),
992
+ color: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional(),
993
+ icon: z.string().max(50).optional(),
994
+ parent_topic_id: z.string().uuid().optional()
995
+ });
996
+
997
+ /**
998
+ * @lanonasis/memory-client
999
+ *
1000
+ * Memory as a Service (MaaS) Client SDK for Lanonasis
1001
+ * Intelligent memory management with semantic search capabilities
1002
+ */
1003
+ // Main client
1004
+ // Constants
1005
+ const VERSION = '1.0.0';
1006
+ const CLIENT_NAME = '@lanonasis/memory-client';
1007
+ // Environment detection
1008
+ const isBrowser = typeof window !== 'undefined';
1009
+ const isNode = typeof globalThis !== 'undefined' && 'process' in globalThis && globalThis.process?.versions?.node;
1010
+ // Default configurations for different environments
1011
+ const defaultConfigs = {
1012
+ development: {
1013
+ apiUrl: 'http://localhost:3001',
1014
+ timeout: 30000,
1015
+ useGateway: false
1016
+ },
1017
+ production: {
1018
+ apiUrl: 'https://api.lanonasis.com',
1019
+ timeout: 15000,
1020
+ useGateway: true
1021
+ },
1022
+ gateway: {
1023
+ apiUrl: 'https://api.lanonasis.com',
1024
+ timeout: 10000,
1025
+ useGateway: true
1026
+ }
1027
+ };
1028
+ // Utility functions will be added in a future version to avoid circular imports
1029
+
1030
+ export { CLIENT_NAME, CLIIntegration, ConfigPresets, EnhancedMemoryClient, Environment, MEMORY_STATUSES, MEMORY_TYPES, MemoryClient, VERSION, createEnhancedMemoryClient, createMemoryClient, createMemorySchema, createSmartConfig, createTopicSchema, defaultConfigs, isBrowser, isNode, migrateToEnhanced, searchMemorySchema, updateMemorySchema };
1031
+ //# sourceMappingURL=index.esm.js.map