@lanonasis/memory-client 1.0.1 → 2.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.
@@ -0,0 +1,647 @@
1
+ import { CoreMemoryClient } from '../core/client';
2
+ import { exec, execSync } from 'child_process';
3
+ import { promisify } from 'util';
4
+
5
+ /**
6
+ * Core Utilities for Memory Client
7
+ * Browser-safe, no Node.js dependencies
8
+ */
9
+ /**
10
+ * Safely parse JSON with detailed error reporting
11
+ * Prevents scattered try/catch blocks throughout the codebase
12
+ */
13
+ function safeJsonParse(input) {
14
+ try {
15
+ const data = JSON.parse(input);
16
+ return { success: true, data };
17
+ }
18
+ catch (error) {
19
+ const message = error instanceof Error
20
+ ? error.message
21
+ : 'Unknown JSON parse error';
22
+ return { success: false, error: `Invalid JSON: ${message}` };
23
+ }
24
+ }
25
+ /**
26
+ * Create a standardized error response from various error sources
27
+ */
28
+ function createErrorResponse(message, code = 'API_ERROR', statusCode, details) {
29
+ return {
30
+ code,
31
+ message,
32
+ statusCode,
33
+ details,
34
+ timestamp: new Date().toISOString()
35
+ };
36
+ }
37
+
38
+ /**
39
+ * CLI Integration Module for Memory Client SDK
40
+ *
41
+ * Provides intelligent CLI detection and MCP channel utilization
42
+ * when @lanonasis/cli v1.5.2+ is available in the environment
43
+ *
44
+ * IMPORTANT: This file imports Node.js modules and should only be used in Node.js environments
45
+ */
46
+ const execAsync = promisify(exec);
47
+ /**
48
+ * CLI Detection and Integration Service
49
+ */
50
+ class CLIIntegration {
51
+ constructor() {
52
+ this.cliInfo = null;
53
+ this.detectionPromise = null;
54
+ }
55
+ /**
56
+ * Detect if CLI is available and get its capabilities
57
+ */
58
+ async detectCLI() {
59
+ // Return cached result if already detected
60
+ if (this.cliInfo) {
61
+ return this.cliInfo;
62
+ }
63
+ // Return existing promise if detection is in progress
64
+ if (this.detectionPromise) {
65
+ return this.detectionPromise;
66
+ }
67
+ // Start new detection
68
+ this.detectionPromise = this.performDetection();
69
+ this.cliInfo = await this.detectionPromise;
70
+ return this.cliInfo;
71
+ }
72
+ async performDetection() {
73
+ try {
74
+ // Check if onasis/lanonasis CLI is available
75
+ let versionOutput = '';
76
+ try {
77
+ const { stdout } = await execAsync('onasis --version 2>/dev/null', { timeout: 5000 });
78
+ versionOutput = stdout;
79
+ }
80
+ catch {
81
+ // Try lanonasis if onasis fails
82
+ const { stdout } = await execAsync('lanonasis --version 2>/dev/null', { timeout: 5000 });
83
+ versionOutput = stdout;
84
+ }
85
+ const version = versionOutput.trim();
86
+ // Verify it's v1.5.2 or higher for Golden Contract support
87
+ const versionMatch = version.match(/(\d+)\.(\d+)\.(\d+)/);
88
+ if (!versionMatch) {
89
+ return { available: false };
90
+ }
91
+ const [, major, minor, patch] = versionMatch.map(Number);
92
+ const isCompatible = major > 1 || (major === 1 && minor > 5) || (major === 1 && minor === 5 && patch >= 2);
93
+ if (!isCompatible) {
94
+ return {
95
+ available: true,
96
+ version,
97
+ mcpAvailable: false,
98
+ authenticated: false
99
+ };
100
+ }
101
+ // Check MCP availability
102
+ let mcpAvailable = false;
103
+ try {
104
+ await execAsync('onasis mcp status --output json 2>/dev/null || lanonasis mcp status --output json 2>/dev/null', {
105
+ timeout: 3000
106
+ });
107
+ mcpAvailable = true;
108
+ }
109
+ catch {
110
+ // MCP not available or not configured
111
+ }
112
+ // Check authentication status
113
+ let authenticated = false;
114
+ try {
115
+ const { stdout: authOutput } = await execAsync('onasis auth status --output json 2>/dev/null || lanonasis auth status --output json 2>/dev/null', {
116
+ timeout: 3000
117
+ });
118
+ const parseResult = safeJsonParse(authOutput);
119
+ if (parseResult.success) {
120
+ authenticated = parseResult.data.authenticated === true;
121
+ }
122
+ }
123
+ catch {
124
+ // Authentication check failed
125
+ }
126
+ return {
127
+ available: true,
128
+ version,
129
+ mcpAvailable,
130
+ authenticated
131
+ };
132
+ }
133
+ catch {
134
+ return { available: false };
135
+ }
136
+ }
137
+ /**
138
+ * Execute CLI command and return parsed JSON result
139
+ */
140
+ async executeCLICommand(command, options = {}) {
141
+ const cliInfo = await this.detectCLI();
142
+ if (!cliInfo.available) {
143
+ return { error: createErrorResponse('CLI not available', 'API_ERROR') };
144
+ }
145
+ if (!cliInfo.authenticated) {
146
+ return { error: createErrorResponse('CLI not authenticated. Run: onasis login', 'AUTH_ERROR', 401) };
147
+ }
148
+ try {
149
+ const timeout = options.timeout || 30000;
150
+ const outputFormat = options.outputFormat || 'json';
151
+ const verbose = options.verbose ? '--verbose' : '';
152
+ // Determine which CLI command to use (prefer onasis for Golden Contract)
153
+ const cliCmd = await this.getPreferredCLICommand();
154
+ const fullCommand = `${cliCmd} ${command} --output ${outputFormat} ${verbose}`.trim();
155
+ const { stdout, stderr } = await execAsync(fullCommand, {
156
+ timeout,
157
+ maxBuffer: 1024 * 1024 // 1MB buffer
158
+ });
159
+ if (stderr && stderr.trim()) {
160
+ console.warn('CLI warning:', stderr);
161
+ }
162
+ if (outputFormat === 'json') {
163
+ const parseResult = safeJsonParse(stdout);
164
+ if (parseResult.success) {
165
+ return { data: parseResult.data };
166
+ }
167
+ return { error: createErrorResponse(parseResult.error, 'VALIDATION_ERROR', 400) };
168
+ }
169
+ return { data: stdout };
170
+ }
171
+ catch (error) {
172
+ if (error instanceof Error && error.message.includes('timeout')) {
173
+ return { error: createErrorResponse('CLI command timeout', 'TIMEOUT_ERROR', 408) };
174
+ }
175
+ return {
176
+ error: createErrorResponse(error instanceof Error ? error.message : 'CLI command failed', 'API_ERROR')
177
+ };
178
+ }
179
+ }
180
+ /**
181
+ * Get preferred CLI command (onasis for Golden Contract, fallback to lanonasis)
182
+ */
183
+ async getPreferredCLICommand() {
184
+ try {
185
+ execSync('which onasis', { stdio: 'ignore', timeout: 1000 });
186
+ return 'onasis';
187
+ }
188
+ catch {
189
+ return 'lanonasis';
190
+ }
191
+ }
192
+ /**
193
+ * Memory operations via CLI
194
+ */
195
+ async createMemoryViaCLI(title, content, options = {}) {
196
+ const { memoryType = 'context', tags = [], topicId } = options;
197
+ let command = `memory create --title "${title}" --content "${content}" --memory-type ${memoryType}`;
198
+ if (tags.length > 0) {
199
+ command += ` --tags "${tags.join(',')}"`;
200
+ }
201
+ if (topicId) {
202
+ command += ` --topic-id "${topicId}"`;
203
+ }
204
+ return this.executeCLICommand(command);
205
+ }
206
+ async listMemoriesViaCLI(options = {}) {
207
+ let command = 'memory list';
208
+ if (options.limit) {
209
+ command += ` --limit ${options.limit}`;
210
+ }
211
+ if (options.memoryType) {
212
+ command += ` --memory-type ${options.memoryType}`;
213
+ }
214
+ if (options.tags && options.tags.length > 0) {
215
+ command += ` --tags "${options.tags.join(',')}"`;
216
+ }
217
+ if (options.sortBy) {
218
+ command += ` --sort-by ${options.sortBy}`;
219
+ }
220
+ return this.executeCLICommand(command);
221
+ }
222
+ async searchMemoriesViaCLI(query, options = {}) {
223
+ let command = `memory search "${query}"`;
224
+ if (options.limit) {
225
+ command += ` --limit ${options.limit}`;
226
+ }
227
+ if (options.memoryTypes && options.memoryTypes.length > 0) {
228
+ command += ` --memory-types "${options.memoryTypes.join(',')}"`;
229
+ }
230
+ return this.executeCLICommand(command);
231
+ }
232
+ /**
233
+ * Health check via CLI
234
+ */
235
+ async healthCheckViaCLI() {
236
+ return this.executeCLICommand('health');
237
+ }
238
+ /**
239
+ * MCP-specific operations
240
+ */
241
+ async getMCPStatus() {
242
+ const cliInfo = await this.detectCLI();
243
+ if (!cliInfo.mcpAvailable) {
244
+ return { error: createErrorResponse('MCP not available via CLI', 'API_ERROR') };
245
+ }
246
+ return this.executeCLICommand('mcp status');
247
+ }
248
+ async listMCPTools() {
249
+ const cliInfo = await this.detectCLI();
250
+ if (!cliInfo.mcpAvailable) {
251
+ return { error: createErrorResponse('MCP not available via CLI', 'API_ERROR') };
252
+ }
253
+ return this.executeCLICommand('mcp tools');
254
+ }
255
+ /**
256
+ * Authentication operations
257
+ */
258
+ async getAuthStatus() {
259
+ return this.executeCLICommand('auth status');
260
+ }
261
+ /**
262
+ * Check if specific CLI features are available
263
+ */
264
+ async getCapabilities() {
265
+ const cliInfo = await this.detectCLI();
266
+ return {
267
+ cliAvailable: cliInfo.available,
268
+ version: cliInfo.version,
269
+ mcpSupport: cliInfo.mcpAvailable || false,
270
+ authenticated: cliInfo.authenticated || false,
271
+ goldenContract: cliInfo.available && this.isGoldenContractCompliant(cliInfo.version)
272
+ };
273
+ }
274
+ isGoldenContractCompliant(version) {
275
+ if (!version)
276
+ return false;
277
+ const versionMatch = version.match(/(\d+)\.(\d+)\.(\d+)/);
278
+ if (!versionMatch)
279
+ return false;
280
+ const [, major, minor, patch] = versionMatch.map(Number);
281
+ return major > 1 || (major === 1 && minor > 5) || (major === 1 && minor === 5 && patch >= 2);
282
+ }
283
+ /**
284
+ * Force refresh CLI detection
285
+ */
286
+ async refresh() {
287
+ this.cliInfo = null;
288
+ this.detectionPromise = null;
289
+ return this.detectCLI();
290
+ }
291
+ /**
292
+ * Get cached CLI info without re-detection
293
+ */
294
+ getCachedInfo() {
295
+ return this.cliInfo;
296
+ }
297
+ }
298
+ // Singleton instance for convenient access
299
+ const cliIntegration = new CLIIntegration();
300
+
301
+ /**
302
+ * Enhanced Memory Client with CLI Integration
303
+ *
304
+ * Intelligently routes requests through CLI v1.5.2+ when available,
305
+ * with fallback to direct API for maximum compatibility and performance
306
+ *
307
+ * IMPORTANT: This file uses Node.js-specific features (process.env) and should only be used in Node.js environments
308
+ */
309
+ /**
310
+ * Enhanced Memory Client with intelligent CLI/API routing
311
+ */
312
+ class EnhancedMemoryClient {
313
+ createDefaultCapabilities() {
314
+ return {
315
+ cliAvailable: false,
316
+ mcpSupport: false,
317
+ authenticated: false,
318
+ goldenContract: false
319
+ };
320
+ }
321
+ constructor(config) {
322
+ this.capabilities = null;
323
+ // Merge config with defaults, ensuring all required fields are present
324
+ // Spread config first, then apply defaults only for undefined values
325
+ const mergedConfig = {
326
+ ...config,
327
+ preferCLI: config.preferCLI ?? true,
328
+ enableMCP: config.enableMCP ?? true,
329
+ cliDetectionTimeout: config.cliDetectionTimeout ?? 5000,
330
+ fallbackToAPI: config.fallbackToAPI ?? true,
331
+ minCLIVersion: config.minCLIVersion ?? '1.5.2',
332
+ verbose: config.verbose ?? false,
333
+ timeout: config.timeout ?? 30000,
334
+ apiUrl: config.apiUrl || 'https://api.lanonasis.com',
335
+ apiKey: config.apiKey || process.env.LANONASIS_API_KEY || '',
336
+ authToken: config.authToken || '',
337
+ headers: config.headers || {}
338
+ };
339
+ this.config = mergedConfig;
340
+ this.directClient = new CoreMemoryClient(config);
341
+ this.cliIntegration = new CLIIntegration();
342
+ }
343
+ /**
344
+ * Initialize the client and detect capabilities
345
+ */
346
+ async initialize() {
347
+ try {
348
+ const detectionPromise = this.cliIntegration.getCapabilities();
349
+ const capabilities = this.config.cliDetectionTimeout > 0
350
+ ? await Promise.race([
351
+ detectionPromise,
352
+ new Promise((resolve) => {
353
+ setTimeout(() => resolve(null), this.config.cliDetectionTimeout);
354
+ })
355
+ ])
356
+ : await detectionPromise;
357
+ if (capabilities) {
358
+ this.capabilities = capabilities;
359
+ if (this.config.verbose && capabilities.cliAvailable && !capabilities.authenticated) {
360
+ const suggestedCommand = capabilities.goldenContract ? 'onasis login' : 'lanonasis login';
361
+ console.warn(`CLI detected but not authenticated. Run '${suggestedCommand}' to enable enhanced SDK features.`);
362
+ }
363
+ }
364
+ else {
365
+ this.capabilities = this.createDefaultCapabilities();
366
+ if (this.config.verbose) {
367
+ console.warn(`CLI detection timed out after ${this.config.cliDetectionTimeout}ms. Falling back to API mode.`);
368
+ }
369
+ }
370
+ }
371
+ catch (error) {
372
+ if (this.config.verbose) {
373
+ console.warn('CLI detection failed:', error);
374
+ }
375
+ this.capabilities = this.createDefaultCapabilities();
376
+ }
377
+ }
378
+ /**
379
+ * Get current capabilities
380
+ */
381
+ async getCapabilities() {
382
+ if (!this.capabilities) {
383
+ await this.initialize();
384
+ }
385
+ if (!this.capabilities) {
386
+ this.capabilities = this.createDefaultCapabilities();
387
+ }
388
+ return this.capabilities;
389
+ }
390
+ /**
391
+ * Determine if operation should use CLI
392
+ */
393
+ async shouldUseCLI() {
394
+ const capabilities = await this.getCapabilities();
395
+ return (this.config.preferCLI &&
396
+ capabilities.cliAvailable &&
397
+ capabilities.authenticated &&
398
+ capabilities.goldenContract);
399
+ }
400
+ /**
401
+ * Execute operation with intelligent routing
402
+ */
403
+ async executeOperation(operation, cliOperation, apiOperation) {
404
+ const useCLI = await this.shouldUseCLI();
405
+ const capabilities = await this.getCapabilities();
406
+ if (useCLI) {
407
+ try {
408
+ const result = await cliOperation();
409
+ if (result.error && this.config.fallbackToAPI) {
410
+ console.warn(`CLI ${operation} failed, falling back to API:`, result.error);
411
+ const apiResult = await apiOperation();
412
+ return {
413
+ ...apiResult,
414
+ source: 'api',
415
+ mcpUsed: false
416
+ };
417
+ }
418
+ return {
419
+ ...result,
420
+ source: 'cli',
421
+ mcpUsed: capabilities.mcpSupport
422
+ };
423
+ }
424
+ catch (error) {
425
+ if (this.config.fallbackToAPI) {
426
+ console.warn(`CLI ${operation} error, falling back to API:`, error);
427
+ const apiResult = await apiOperation();
428
+ return {
429
+ ...apiResult,
430
+ source: 'api',
431
+ mcpUsed: false
432
+ };
433
+ }
434
+ return {
435
+ error: createErrorResponse(error instanceof Error ? error.message : `CLI ${operation} failed`, 'API_ERROR'),
436
+ source: 'cli',
437
+ mcpUsed: false
438
+ };
439
+ }
440
+ }
441
+ else {
442
+ const result = await apiOperation();
443
+ return {
444
+ ...result,
445
+ source: 'api',
446
+ mcpUsed: false
447
+ };
448
+ }
449
+ }
450
+ // Enhanced API Methods
451
+ /**
452
+ * Health check with intelligent routing
453
+ */
454
+ async healthCheck() {
455
+ return this.executeOperation('health check', () => this.cliIntegration.healthCheckViaCLI(), () => this.directClient.healthCheck());
456
+ }
457
+ /**
458
+ * Create memory with CLI/API routing
459
+ */
460
+ async createMemory(memory) {
461
+ return this.executeOperation('create memory', () => this.cliIntegration.createMemoryViaCLI(memory.title, memory.content, {
462
+ memoryType: memory.memory_type,
463
+ tags: memory.tags,
464
+ topicId: memory.topic_id
465
+ }), () => this.directClient.createMemory(memory));
466
+ }
467
+ /**
468
+ * List memories with intelligent routing
469
+ */
470
+ async listMemories(options = {}) {
471
+ return this.executeOperation('list memories', () => this.cliIntegration.listMemoriesViaCLI({
472
+ limit: options.limit,
473
+ memoryType: options.memory_type,
474
+ tags: options.tags,
475
+ sortBy: options.sort
476
+ }), () => this.directClient.listMemories(options));
477
+ }
478
+ /**
479
+ * Search memories with MCP enhancement when available
480
+ */
481
+ async searchMemories(request) {
482
+ return this.executeOperation('search memories', () => this.cliIntegration.searchMemoriesViaCLI(request.query, {
483
+ limit: request.limit,
484
+ memoryTypes: request.memory_types
485
+ }), () => this.directClient.searchMemories(request));
486
+ }
487
+ /**
488
+ * Get memory by ID (API only for now)
489
+ */
490
+ async getMemory(id) {
491
+ // CLI doesn't have get by ID yet, use API
492
+ const result = await this.directClient.getMemory(id);
493
+ return {
494
+ ...result,
495
+ source: 'api',
496
+ mcpUsed: false
497
+ };
498
+ }
499
+ /**
500
+ * Update memory (API only for now)
501
+ */
502
+ async updateMemory(id, updates) {
503
+ // CLI doesn't have update yet, use API
504
+ const result = await this.directClient.updateMemory(id, updates);
505
+ return {
506
+ ...result,
507
+ source: 'api',
508
+ mcpUsed: false
509
+ };
510
+ }
511
+ /**
512
+ * Delete memory (API only for now)
513
+ */
514
+ async deleteMemory(id) {
515
+ // CLI doesn't have delete yet, use API
516
+ const result = await this.directClient.deleteMemory(id);
517
+ return {
518
+ ...result,
519
+ source: 'api',
520
+ mcpUsed: false
521
+ };
522
+ }
523
+ // Topic Operations (API only for now)
524
+ async createTopic(topic) {
525
+ const result = await this.directClient.createTopic(topic);
526
+ return { ...result, source: 'api', mcpUsed: false };
527
+ }
528
+ async getTopics() {
529
+ const result = await this.directClient.getTopics();
530
+ return { ...result, source: 'api', mcpUsed: false };
531
+ }
532
+ async getTopic(id) {
533
+ const result = await this.directClient.getTopic(id);
534
+ return { ...result, source: 'api', mcpUsed: false };
535
+ }
536
+ async updateTopic(id, updates) {
537
+ const result = await this.directClient.updateTopic(id, updates);
538
+ return { ...result, source: 'api', mcpUsed: false };
539
+ }
540
+ async deleteTopic(id) {
541
+ const result = await this.directClient.deleteTopic(id);
542
+ return { ...result, source: 'api', mcpUsed: false };
543
+ }
544
+ /**
545
+ * Get memory statistics
546
+ */
547
+ async getMemoryStats() {
548
+ const result = await this.directClient.getMemoryStats();
549
+ return { ...result, source: 'api', mcpUsed: false };
550
+ }
551
+ // Utility Methods
552
+ /**
553
+ * Force CLI re-detection
554
+ */
555
+ async refreshCLIDetection() {
556
+ this.capabilities = null;
557
+ await this.cliIntegration.refresh();
558
+ await this.initialize();
559
+ }
560
+ /**
561
+ * Get authentication status from CLI
562
+ */
563
+ async getAuthStatus() {
564
+ try {
565
+ const result = await this.cliIntegration.getAuthStatus();
566
+ return { ...result, source: 'cli', mcpUsed: false };
567
+ }
568
+ catch (error) {
569
+ return {
570
+ error: createErrorResponse(error instanceof Error ? error.message : 'Auth status check failed', 'API_ERROR'),
571
+ source: 'cli',
572
+ mcpUsed: false
573
+ };
574
+ }
575
+ }
576
+ /**
577
+ * Get MCP status when available
578
+ */
579
+ async getMCPStatus() {
580
+ const capabilities = await this.getCapabilities();
581
+ if (!capabilities.mcpSupport) {
582
+ return {
583
+ error: createErrorResponse('MCP not available', 'API_ERROR'),
584
+ source: 'cli',
585
+ mcpUsed: false
586
+ };
587
+ }
588
+ try {
589
+ const result = await this.cliIntegration.getMCPStatus();
590
+ return { ...result, source: 'cli', mcpUsed: true };
591
+ }
592
+ catch (error) {
593
+ return {
594
+ error: createErrorResponse(error instanceof Error ? error.message : 'MCP status check failed', 'API_ERROR'),
595
+ source: 'cli',
596
+ mcpUsed: false
597
+ };
598
+ }
599
+ }
600
+ /**
601
+ * Update authentication for both CLI and API client
602
+ */
603
+ setAuthToken(token) {
604
+ this.directClient.setAuthToken(token);
605
+ }
606
+ setApiKey(apiKey) {
607
+ this.directClient.setApiKey(apiKey);
608
+ }
609
+ clearAuth() {
610
+ this.directClient.clearAuth();
611
+ }
612
+ /**
613
+ * Update configuration
614
+ */
615
+ updateConfig(updates) {
616
+ this.config = { ...this.config, ...updates };
617
+ this.directClient.updateConfig(updates);
618
+ }
619
+ /**
620
+ * Get configuration summary
621
+ */
622
+ getConfigSummary() {
623
+ return {
624
+ apiUrl: this.config.apiUrl,
625
+ preferCLI: this.config.preferCLI,
626
+ enableMCP: this.config.enableMCP,
627
+ capabilities: this.capabilities || undefined
628
+ };
629
+ }
630
+ }
631
+ /**
632
+ * Factory function to create an enhanced memory client
633
+ */
634
+ async function createNodeMemoryClient(config) {
635
+ const client = new EnhancedMemoryClient(config);
636
+ await client.initialize();
637
+ return client;
638
+ }
639
+ /**
640
+ * Synchronous factory function (initialization happens on first API call)
641
+ */
642
+ function createEnhancedMemoryClient(config) {
643
+ return new EnhancedMemoryClient(config);
644
+ }
645
+
646
+ export { CLIIntegration, EnhancedMemoryClient, cliIntegration, createEnhancedMemoryClient, createNodeMemoryClient };
647
+ //# sourceMappingURL=index.js.map