@soulcraft/brainy 1.5.0 → 2.0.1

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 (141) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/LICENSE +2 -2
  3. package/README.md +200 -595
  4. package/bin/brainy-interactive.js +564 -0
  5. package/bin/brainy-ts.js +18 -0
  6. package/bin/brainy.js +672 -81
  7. package/dist/augmentationPipeline.d.ts +48 -220
  8. package/dist/augmentationPipeline.js +60 -508
  9. package/dist/augmentationRegistry.d.ts +22 -31
  10. package/dist/augmentationRegistry.js +28 -79
  11. package/dist/augmentations/apiServerAugmentation.d.ts +108 -0
  12. package/dist/augmentations/apiServerAugmentation.js +502 -0
  13. package/dist/augmentations/batchProcessingAugmentation.d.ts +95 -0
  14. package/dist/augmentations/batchProcessingAugmentation.js +567 -0
  15. package/dist/augmentations/brainyAugmentation.d.ts +153 -0
  16. package/dist/augmentations/brainyAugmentation.js +145 -0
  17. package/dist/augmentations/cacheAugmentation.d.ts +105 -0
  18. package/dist/augmentations/cacheAugmentation.js +238 -0
  19. package/dist/augmentations/conduitAugmentations.d.ts +54 -156
  20. package/dist/augmentations/conduitAugmentations.js +156 -1082
  21. package/dist/augmentations/connectionPoolAugmentation.d.ts +62 -0
  22. package/dist/augmentations/connectionPoolAugmentation.js +316 -0
  23. package/dist/augmentations/defaultAugmentations.d.ts +53 -0
  24. package/dist/augmentations/defaultAugmentations.js +88 -0
  25. package/dist/augmentations/entityRegistryAugmentation.d.ts +126 -0
  26. package/dist/augmentations/entityRegistryAugmentation.js +386 -0
  27. package/dist/augmentations/indexAugmentation.d.ts +117 -0
  28. package/dist/augmentations/indexAugmentation.js +284 -0
  29. package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +152 -0
  30. package/dist/augmentations/intelligentVerbScoringAugmentation.js +554 -0
  31. package/dist/augmentations/metricsAugmentation.d.ts +202 -0
  32. package/dist/augmentations/metricsAugmentation.js +291 -0
  33. package/dist/augmentations/monitoringAugmentation.d.ts +94 -0
  34. package/dist/augmentations/monitoringAugmentation.js +227 -0
  35. package/dist/augmentations/neuralImport.d.ts +50 -117
  36. package/dist/augmentations/neuralImport.js +255 -629
  37. package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +52 -0
  38. package/dist/augmentations/requestDeduplicatorAugmentation.js +162 -0
  39. package/dist/augmentations/serverSearchAugmentations.d.ts +43 -22
  40. package/dist/augmentations/serverSearchAugmentations.js +125 -72
  41. package/dist/augmentations/storageAugmentation.d.ts +54 -0
  42. package/dist/augmentations/storageAugmentation.js +93 -0
  43. package/dist/augmentations/storageAugmentations.d.ts +96 -0
  44. package/dist/augmentations/storageAugmentations.js +182 -0
  45. package/dist/augmentations/synapseAugmentation.d.ts +156 -0
  46. package/dist/augmentations/synapseAugmentation.js +312 -0
  47. package/dist/augmentations/walAugmentation.d.ts +108 -0
  48. package/dist/augmentations/walAugmentation.js +515 -0
  49. package/dist/brainyData.d.ts +404 -130
  50. package/dist/brainyData.js +1331 -853
  51. package/dist/chat/BrainyChat.d.ts +16 -8
  52. package/dist/chat/BrainyChat.js +60 -32
  53. package/dist/chat/ChatCLI.d.ts +1 -1
  54. package/dist/chat/ChatCLI.js +6 -6
  55. package/dist/cli/catalog.d.ts +3 -3
  56. package/dist/cli/catalog.js +116 -70
  57. package/dist/cli/commands/core.d.ts +61 -0
  58. package/dist/cli/commands/core.js +348 -0
  59. package/dist/cli/commands/neural.d.ts +25 -0
  60. package/dist/cli/commands/neural.js +508 -0
  61. package/dist/cli/commands/utility.d.ts +37 -0
  62. package/dist/cli/commands/utility.js +276 -0
  63. package/dist/cli/index.d.ts +7 -0
  64. package/dist/cli/index.js +167 -0
  65. package/dist/cli/interactive.d.ts +164 -0
  66. package/dist/cli/interactive.js +542 -0
  67. package/dist/cortex/neuralImport.js +5 -5
  68. package/dist/critical/model-guardian.js +11 -4
  69. package/dist/embeddings/lightweight-embedder.d.ts +23 -0
  70. package/dist/embeddings/lightweight-embedder.js +136 -0
  71. package/dist/embeddings/universal-memory-manager.d.ts +38 -0
  72. package/dist/embeddings/universal-memory-manager.js +206 -0
  73. package/dist/embeddings/worker-embedding.d.ts +7 -0
  74. package/dist/embeddings/worker-embedding.js +77 -0
  75. package/dist/embeddings/worker-manager.d.ts +28 -0
  76. package/dist/embeddings/worker-manager.js +162 -0
  77. package/dist/examples/basicUsage.js +7 -7
  78. package/dist/graph/pathfinding.d.ts +78 -0
  79. package/dist/graph/pathfinding.js +393 -0
  80. package/dist/hnsw/hnswIndex.d.ts +13 -0
  81. package/dist/hnsw/hnswIndex.js +35 -0
  82. package/dist/hnsw/hnswIndexOptimized.d.ts +1 -0
  83. package/dist/hnsw/hnswIndexOptimized.js +3 -0
  84. package/dist/index.d.ts +9 -11
  85. package/dist/index.js +21 -11
  86. package/dist/indices/fieldIndex.d.ts +76 -0
  87. package/dist/indices/fieldIndex.js +357 -0
  88. package/dist/mcp/brainyMCPAdapter.js +3 -2
  89. package/dist/mcp/mcpAugmentationToolset.js +11 -17
  90. package/dist/neural/embeddedPatterns.d.ts +41 -0
  91. package/dist/neural/embeddedPatterns.js +4044 -0
  92. package/dist/neural/naturalLanguageProcessor.d.ts +94 -0
  93. package/dist/neural/naturalLanguageProcessor.js +317 -0
  94. package/dist/neural/naturalLanguageProcessorStatic.d.ts +64 -0
  95. package/dist/neural/naturalLanguageProcessorStatic.js +151 -0
  96. package/dist/neural/neuralAPI.d.ts +255 -0
  97. package/dist/neural/neuralAPI.js +612 -0
  98. package/dist/neural/patternLibrary.d.ts +101 -0
  99. package/dist/neural/patternLibrary.js +313 -0
  100. package/dist/neural/patterns.d.ts +27 -0
  101. package/dist/neural/patterns.js +68 -0
  102. package/dist/neural/staticPatternMatcher.d.ts +35 -0
  103. package/dist/neural/staticPatternMatcher.js +153 -0
  104. package/dist/scripts/precomputePatternEmbeddings.d.ts +19 -0
  105. package/dist/scripts/precomputePatternEmbeddings.js +100 -0
  106. package/dist/storage/adapters/fileSystemStorage.d.ts +5 -0
  107. package/dist/storage/adapters/fileSystemStorage.js +20 -0
  108. package/dist/storage/adapters/s3CompatibleStorage.d.ts +5 -0
  109. package/dist/storage/adapters/s3CompatibleStorage.js +16 -0
  110. package/dist/storage/enhancedClearOperations.d.ts +83 -0
  111. package/dist/storage/enhancedClearOperations.js +345 -0
  112. package/dist/storage/storageFactory.js +31 -27
  113. package/dist/triple/TripleIntelligence.d.ts +134 -0
  114. package/dist/triple/TripleIntelligence.js +548 -0
  115. package/dist/types/augmentations.d.ts +45 -344
  116. package/dist/types/augmentations.js +5 -2
  117. package/dist/types/brainyDataInterface.d.ts +20 -10
  118. package/dist/types/graphTypes.d.ts +46 -0
  119. package/dist/types/graphTypes.js +16 -2
  120. package/dist/utils/BoundedRegistry.d.ts +29 -0
  121. package/dist/utils/BoundedRegistry.js +54 -0
  122. package/dist/utils/embedding.js +20 -3
  123. package/dist/utils/hybridModelManager.js +10 -5
  124. package/dist/utils/metadataFilter.d.ts +33 -19
  125. package/dist/utils/metadataFilter.js +58 -23
  126. package/dist/utils/metadataIndex.d.ts +37 -6
  127. package/dist/utils/metadataIndex.js +427 -64
  128. package/dist/utils/requestDeduplicator.d.ts +10 -0
  129. package/dist/utils/requestDeduplicator.js +24 -0
  130. package/dist/utils/unifiedCache.d.ts +103 -0
  131. package/dist/utils/unifiedCache.js +311 -0
  132. package/package.json +40 -125
  133. package/scripts/ensure-models.js +108 -0
  134. package/scripts/prepare-models.js +387 -0
  135. package/OFFLINE_MODELS.md +0 -56
  136. package/dist/intelligence/neuralEngine.d.ts +0 -207
  137. package/dist/intelligence/neuralEngine.js +0 -706
  138. package/dist/utils/modelLoader.d.ts +0 -32
  139. package/dist/utils/modelLoader.js +0 -219
  140. package/dist/utils/modelManager.d.ts +0 -77
  141. package/dist/utils/modelManager.js +0 -219
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Request Deduplicator Augmentation
3
+ *
4
+ * Prevents duplicate concurrent requests to improve performance by 3x
5
+ * Automatically deduplicates identical operations
6
+ */
7
+ import { BaseAugmentation } from './brainyAugmentation.js';
8
+ interface DeduplicatorConfig {
9
+ enabled?: boolean;
10
+ ttl?: number;
11
+ maxSize?: number;
12
+ }
13
+ export declare class RequestDeduplicatorAugmentation extends BaseAugmentation {
14
+ name: string;
15
+ timing: "around";
16
+ operations: ("search" | "searchText" | "searchByNounTypes" | "findSimilar" | "get")[];
17
+ priority: number;
18
+ private pendingRequests;
19
+ private config;
20
+ private cleanupInterval?;
21
+ constructor(config?: DeduplicatorConfig);
22
+ protected onInitialize(): Promise<void>;
23
+ shouldExecute(operation: string, params: any): boolean;
24
+ execute<T = any>(operation: string, params: any, next: () => Promise<T>): Promise<T>;
25
+ /**
26
+ * Create a unique key for the request based on operation and parameters
27
+ */
28
+ private createRequestKey;
29
+ /**
30
+ * Serialize parameters to a consistent string
31
+ */
32
+ private serializeParams;
33
+ /**
34
+ * Clean up expired requests
35
+ */
36
+ private cleanup;
37
+ /**
38
+ * Get statistics about request deduplication
39
+ */
40
+ getStats(): {
41
+ activePendingRequests: number;
42
+ totalDeduplicationHits: number;
43
+ memoryUsage: string;
44
+ efficiency: string;
45
+ };
46
+ /**
47
+ * Force clear all pending requests (for testing)
48
+ */
49
+ clear(): void;
50
+ protected onShutdown(): Promise<void>;
51
+ }
52
+ export {};
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Request Deduplicator Augmentation
3
+ *
4
+ * Prevents duplicate concurrent requests to improve performance by 3x
5
+ * Automatically deduplicates identical operations
6
+ */
7
+ import { BaseAugmentation } from './brainyAugmentation.js';
8
+ export class RequestDeduplicatorAugmentation extends BaseAugmentation {
9
+ constructor(config = {}) {
10
+ super();
11
+ this.name = 'RequestDeduplicator';
12
+ this.timing = 'around';
13
+ this.operations = ['search', 'searchText', 'searchByNounTypes', 'findSimilar', 'get'];
14
+ this.priority = 50; // Performance optimization
15
+ this.pendingRequests = new Map();
16
+ this.config = {
17
+ enabled: config.enabled ?? true,
18
+ ttl: config.ttl ?? 5000, // 5 second default
19
+ maxSize: config.maxSize ?? 1000
20
+ };
21
+ }
22
+ async onInitialize() {
23
+ if (this.config.enabled) {
24
+ this.log('Request deduplicator initialized for 3x performance boost');
25
+ // Start cleanup interval
26
+ this.cleanupInterval = setInterval(() => {
27
+ this.cleanup();
28
+ }, this.config.ttl);
29
+ }
30
+ else {
31
+ this.log('Request deduplicator disabled');
32
+ }
33
+ }
34
+ shouldExecute(operation, params) {
35
+ // Only execute if enabled and for read operations that benefit from deduplication
36
+ return this.config.enabled && (operation === 'search' ||
37
+ operation === 'searchText' ||
38
+ operation === 'searchByNounTypes' ||
39
+ operation === 'findSimilar' ||
40
+ operation === 'get');
41
+ }
42
+ async execute(operation, params, next) {
43
+ if (!this.config.enabled) {
44
+ return next();
45
+ }
46
+ // Create a unique key for this request
47
+ const key = this.createRequestKey(operation, params);
48
+ // Check if we already have this request pending
49
+ const existing = this.pendingRequests.get(key);
50
+ if (existing) {
51
+ existing.count++;
52
+ this.log(`Deduplicating request: ${key} (${existing.count} total)`);
53
+ return existing.promise;
54
+ }
55
+ // Execute the request and cache the promise
56
+ const promise = next();
57
+ this.pendingRequests.set(key, {
58
+ promise,
59
+ timestamp: Date.now(),
60
+ count: 1
61
+ });
62
+ // Clean up when done
63
+ promise.finally(() => {
64
+ // Use setTimeout to allow other concurrent requests to use the result
65
+ setTimeout(() => {
66
+ this.pendingRequests.delete(key);
67
+ }, 100);
68
+ });
69
+ return promise;
70
+ }
71
+ /**
72
+ * Create a unique key for the request based on operation and parameters
73
+ */
74
+ createRequestKey(operation, params) {
75
+ // Create a stable string representation of the operation and params
76
+ const paramsKey = this.serializeParams(params);
77
+ return `${operation}:${paramsKey}`;
78
+ }
79
+ /**
80
+ * Serialize parameters to a consistent string
81
+ */
82
+ serializeParams(params) {
83
+ if (!params)
84
+ return 'null';
85
+ if (typeof params === 'string' || typeof params === 'number') {
86
+ return String(params);
87
+ }
88
+ if (Array.isArray(params)) {
89
+ // For arrays, create a hash-like representation
90
+ if (params.length > 100) {
91
+ // For large arrays (like vectors), use length + first/last elements
92
+ return `[${params.length}:${params[0]}...${params[params.length - 1]}]`;
93
+ }
94
+ return `[${params.join(',')}]`;
95
+ }
96
+ if (typeof params === 'object') {
97
+ // Sort keys for consistent serialization
98
+ const keys = Object.keys(params).sort();
99
+ const keyValues = keys.map(key => `${key}:${this.serializeParams(params[key])}`);
100
+ return `{${keyValues.join(',')}}`;
101
+ }
102
+ return String(params);
103
+ }
104
+ /**
105
+ * Clean up expired requests
106
+ */
107
+ cleanup() {
108
+ const now = Date.now();
109
+ const expired = [];
110
+ for (const [key, request] of this.pendingRequests) {
111
+ if (now - request.timestamp > this.config.ttl) {
112
+ expired.push(key);
113
+ }
114
+ }
115
+ for (const key of expired) {
116
+ this.pendingRequests.delete(key);
117
+ }
118
+ // Also enforce max size
119
+ if (this.pendingRequests.size > this.config.maxSize) {
120
+ const entries = Array.from(this.pendingRequests.entries())
121
+ .sort(([, a], [, b]) => a.timestamp - b.timestamp); // Oldest first
122
+ // Remove oldest entries
123
+ const toRemove = entries.slice(0, entries.length - this.config.maxSize);
124
+ for (const [key] of toRemove) {
125
+ this.pendingRequests.delete(key);
126
+ }
127
+ }
128
+ if (expired.length > 0) {
129
+ this.log(`Cleaned up ${expired.length} expired requests`);
130
+ }
131
+ }
132
+ /**
133
+ * Get statistics about request deduplication
134
+ */
135
+ getStats() {
136
+ const requests = Array.from(this.pendingRequests.values());
137
+ const totalRequests = requests.reduce((sum, req) => sum + req.count, 0);
138
+ const actualRequests = requests.length;
139
+ const savedRequests = totalRequests - actualRequests;
140
+ return {
141
+ activePendingRequests: actualRequests,
142
+ totalDeduplicationHits: savedRequests,
143
+ memoryUsage: `${Math.round(JSON.stringify(requests).length / 1024)}KB`,
144
+ efficiency: actualRequests > 0 ? `${Math.round((savedRequests / totalRequests) * 100)}% reduction` : '0%'
145
+ };
146
+ }
147
+ /**
148
+ * Force clear all pending requests (for testing)
149
+ */
150
+ clear() {
151
+ this.pendingRequests.clear();
152
+ }
153
+ async onShutdown() {
154
+ if (this.cleanupInterval) {
155
+ clearInterval(this.cleanupInterval);
156
+ }
157
+ const stats = this.getStats();
158
+ this.log(`Request deduplicator shutdown: ${stats.efficiency} efficiency achieved`);
159
+ this.pendingRequests.clear();
160
+ }
161
+ }
162
+ //# sourceMappingURL=requestDeduplicatorAugmentation.js.map
@@ -4,8 +4,8 @@
4
4
  * This file implements conduit and activation augmentations for browser-server search functionality.
5
5
  * It allows Brainy to search a server-hosted instance and store results locally.
6
6
  */
7
- import { AugmentationType, IActivationAugmentation, AugmentationResponse, WebSocketConnection } from '../types/augmentations.js';
8
- import { WebSocketConduitAugmentation } from './conduitAugmentations.js';
7
+ import { AugmentationResponse, WebSocketConnection } from '../types/augmentations.js';
8
+ import { BaseAugmentation } from '../augmentations/brainyAugmentation.js';
9
9
  import { BrainyDataInterface } from '../types/brainyDataInterface.js';
10
10
  /**
11
11
  * ServerSearchConduitAugmentation
@@ -13,23 +13,41 @@ import { BrainyDataInterface } from '../types/brainyDataInterface.js';
13
13
  * A specialized conduit augmentation that provides functionality for searching
14
14
  * a server-hosted Brainy instance and storing results locally.
15
15
  */
16
- export declare class ServerSearchConduitAugmentation extends WebSocketConduitAugmentation {
16
+ export declare class ServerSearchConduitAugmentation extends BaseAugmentation {
17
+ readonly name = "server-search-conduit";
18
+ readonly timing: "after";
19
+ operations: ("addNoun" | "delete" | "addVerb")[];
20
+ readonly priority = 20;
17
21
  private localDb;
18
22
  constructor(name?: string);
19
23
  /**
20
24
  * Initialize the augmentation
21
25
  */
22
- initialize(): Promise<void>;
26
+ protected onInitialize(): Promise<void>;
23
27
  /**
24
28
  * Set the local Brainy instance
25
29
  * @param db The Brainy instance to use for local storage
26
30
  */
27
31
  setLocalDb(db: BrainyDataInterface): void;
32
+ /**
33
+ * Stub method for performing search operations via WebSocket
34
+ * TODO: Implement proper WebSocket communication
35
+ */
36
+ private performSearch;
37
+ /**
38
+ * Stub method for performing write operations via WebSocket
39
+ * TODO: Implement proper WebSocket communication
40
+ */
41
+ private performWrite;
28
42
  /**
29
43
  * Get the local Brainy instance
30
44
  * @returns The local Brainy instance
31
45
  */
32
46
  getLocalDb(): BrainyDataInterface | null;
47
+ /**
48
+ * Execute method - required by BaseAugmentation
49
+ */
50
+ execute<T = any>(operation: string, params: any, next: () => Promise<T>): Promise<T>;
33
51
  /**
34
52
  * Search the server-hosted Brainy instance and store results locally
35
53
  * @param connectionId The ID of the established connection
@@ -61,33 +79,36 @@ export declare class ServerSearchConduitAugmentation extends WebSocketConduitAug
61
79
  * @returns ID of the added data
62
80
  */
63
81
  addToBoth(connectionId: string, data: string | any[], metadata?: any): Promise<AugmentationResponse<string>>;
82
+ /**
83
+ * Establish connection to remote server
84
+ * @param serverUrl Server URL to connect to
85
+ * @param options Connection options
86
+ * @returns Connection promise
87
+ */
88
+ establishConnection(serverUrl: string, options?: any): Promise<any>;
89
+ /**
90
+ * Close WebSocket connection
91
+ * @param connectionId Connection ID to close
92
+ * @returns Promise that resolves when connection is closed
93
+ */
94
+ closeWebSocket(connectionId: string): Promise<void>;
64
95
  }
65
96
  /**
66
97
  * ServerSearchActivationAugmentation
67
98
  *
68
99
  * An activation augmentation that provides actions for server search functionality.
69
100
  */
70
- export declare class ServerSearchActivationAugmentation implements IActivationAugmentation {
71
- readonly name: string;
72
- readonly description: string;
73
- enabled: boolean;
74
- private isInitialized;
101
+ export declare class ServerSearchActivationAugmentation extends BaseAugmentation {
102
+ readonly name = "server-search-activation";
103
+ readonly timing: "after";
104
+ operations: ("search" | "addNoun")[];
105
+ readonly priority = 20;
75
106
  private conduitAugmentation;
76
107
  private connections;
77
108
  constructor(name?: string);
78
- getType(): AugmentationType;
79
- /**
80
- * Initialize the augmentation
81
- */
82
- initialize(): Promise<void>;
83
- /**
84
- * Shut down the augmentation
85
- */
86
- shutDown(): Promise<void>;
87
- /**
88
- * Get the status of the augmentation
89
- */
90
- getStatus(): Promise<'active' | 'inactive' | 'error'>;
109
+ protected onInitialize(): Promise<void>;
110
+ protected onShutdown(): Promise<void>;
111
+ execute<T = any>(operation: string, params: any, next: () => Promise<T>): Promise<T>;
91
112
  /**
92
113
  * Set the conduit augmentation to use for server search
93
114
  * @param conduit The ServerSearchConduitAugmentation to use
@@ -4,40 +4,36 @@
4
4
  * This file implements conduit and activation augmentations for browser-server search functionality.
5
5
  * It allows Brainy to search a server-hosted instance and store results locally.
6
6
  */
7
- import { AugmentationType } from '../types/augmentations.js';
8
- import { WebSocketConduitAugmentation } from './conduitAugmentations.js';
7
+ import { BaseAugmentation } from '../augmentations/brainyAugmentation.js';
9
8
  /**
10
9
  * ServerSearchConduitAugmentation
11
10
  *
12
11
  * A specialized conduit augmentation that provides functionality for searching
13
12
  * a server-hosted Brainy instance and storing results locally.
14
13
  */
15
- export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentation {
16
- constructor(name = 'server-search-conduit') {
17
- super(name);
14
+ export class ServerSearchConduitAugmentation extends BaseAugmentation {
15
+ constructor(name) {
16
+ super();
17
+ this.name = 'server-search-conduit';
18
+ this.timing = 'after';
19
+ this.operations = ['addNoun', 'delete', 'addVerb'];
20
+ this.priority = 20;
18
21
  this.localDb = null;
19
- // this.description = 'Conduit augmentation for server-hosted Brainy search'
22
+ if (name) {
23
+ // Override name if provided (though it's readonly, this won't work)
24
+ // Keep constructor parameter for API compatibility but ignore it
25
+ }
20
26
  }
21
27
  /**
22
28
  * Initialize the augmentation
23
29
  */
24
- async initialize() {
25
- if (this.isInitialized) {
30
+ async onInitialize() {
31
+ // Local DB must be set before initialization
32
+ if (!this.localDb) {
33
+ this.log('Local database not set. Call setLocalDb before using server search.', 'warn');
26
34
  return;
27
35
  }
28
- try {
29
- // Initialize the base conduit
30
- await super.initialize();
31
- // Local DB must be set before initialization
32
- if (!this.localDb) {
33
- throw new Error('Local database not set. Call setLocalDb before initializing.');
34
- }
35
- this.isInitialized = true;
36
- }
37
- catch (error) {
38
- console.error(`Failed to initialize ${this.name}:`, error);
39
- throw new Error(`Failed to initialize ${this.name}: ${error}`);
40
- }
36
+ this.log('Server search conduit initialized');
41
37
  }
42
38
  /**
43
39
  * Set the local Brainy instance
@@ -46,6 +42,29 @@ export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentatio
46
42
  setLocalDb(db) {
47
43
  this.localDb = db;
48
44
  }
45
+ /**
46
+ * Stub method for performing search operations via WebSocket
47
+ * TODO: Implement proper WebSocket communication
48
+ */
49
+ async performSearch(params) {
50
+ this.log('Search operation not yet implemented - returning empty results', 'warn');
51
+ return {
52
+ success: true,
53
+ data: []
54
+ };
55
+ }
56
+ /**
57
+ * Stub method for performing write operations via WebSocket
58
+ * TODO: Implement proper WebSocket communication
59
+ */
60
+ async performWrite(params) {
61
+ this.log('Write operation not yet implemented', 'warn');
62
+ return {
63
+ success: false,
64
+ data: null,
65
+ error: 'Write operation not implemented'
66
+ };
67
+ }
49
68
  /**
50
69
  * Get the local Brainy instance
51
70
  * @returns The local Brainy instance
@@ -53,6 +72,13 @@ export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentatio
53
72
  getLocalDb() {
54
73
  return this.localDb;
55
74
  }
75
+ /**
76
+ * Execute method - required by BaseAugmentation
77
+ */
78
+ async execute(operation, params, next) {
79
+ // Just pass through for now - server search operations are handled by the activation augmentation
80
+ return next();
81
+ }
56
82
  /**
57
83
  * Search the server-hosted Brainy instance and store results locally
58
84
  * @param connectionId The ID of the established connection
@@ -61,10 +87,12 @@ export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentatio
61
87
  * @returns Search results
62
88
  */
63
89
  async searchServer(connectionId, query, limit = 10) {
64
- await this.ensureInitialized();
90
+ if (!this.isInitialized) {
91
+ throw new Error('ServerSearchConduitAugmentation not initialized');
92
+ }
65
93
  try {
66
- // Create a search request
67
- const readResult = await this.readData({
94
+ // Create a search request (TODO: Implement proper WebSocket communication)
95
+ const readResult = await this.performSearch({
68
96
  connectionId,
69
97
  query: {
70
98
  type: 'search',
@@ -78,10 +106,10 @@ export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentatio
78
106
  if (this.localDb) {
79
107
  for (const result of searchResults) {
80
108
  // Check if the noun already exists in the local database
81
- const existingNoun = await this.localDb.get(result.id);
109
+ const existingNoun = await this.localDb.getNoun(result.id);
82
110
  if (!existingNoun) {
83
111
  // Add the noun to the local database
84
- await this.localDb.add(result.vector, result.metadata);
112
+ await this.localDb.addNoun(result.vector, result.metadata);
85
113
  }
86
114
  }
87
115
  }
@@ -114,7 +142,9 @@ export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentatio
114
142
  * @returns Search results
115
143
  */
116
144
  async searchLocal(query, limit = 10) {
117
- await this.ensureInitialized();
145
+ if (!this.isInitialized) {
146
+ throw new Error('ServerSearchConduitAugmentation not initialized');
147
+ }
118
148
  try {
119
149
  if (!this.localDb) {
120
150
  return {
@@ -146,7 +176,9 @@ export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentatio
146
176
  * @returns Combined search results
147
177
  */
148
178
  async searchCombined(connectionId, query, limit = 10) {
149
- await this.ensureInitialized();
179
+ if (!this.isInitialized) {
180
+ throw new Error('ServerSearchConduitAugmentation not initialized');
181
+ }
150
182
  try {
151
183
  // Search local first
152
184
  const localSearchResult = await this.searchLocal(query, limit);
@@ -195,7 +227,9 @@ export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentatio
195
227
  * @returns ID of the added data
196
228
  */
197
229
  async addToBoth(connectionId, data, metadata = {}) {
198
- await this.ensureInitialized();
230
+ if (!this.isInitialized) {
231
+ throw new Error('ServerSearchConduitAugmentation not initialized');
232
+ }
199
233
  try {
200
234
  if (!this.localDb) {
201
235
  return {
@@ -204,10 +238,10 @@ export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentatio
204
238
  error: 'Local database not initialized'
205
239
  };
206
240
  }
207
- // Add to local first
208
- const id = await this.localDb.add(data, metadata);
241
+ // Add to local first - addNoun handles both strings and vectors automatically
242
+ const id = await this.localDb.addNoun(data, metadata);
209
243
  // Get the vector and metadata
210
- const noun = (await this.localDb.get(id));
244
+ const noun = (await this.localDb.getNoun(id));
211
245
  if (!noun) {
212
246
  return {
213
247
  success: false,
@@ -215,8 +249,8 @@ export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentatio
215
249
  error: 'Failed to retrieve newly created noun'
216
250
  };
217
251
  }
218
- // Add to server
219
- const writeResult = await this.writeData({
252
+ // Add to server (TODO: Implement proper WebSocket communication)
253
+ const writeResult = await this.performWrite({
220
254
  connectionId,
221
255
  data: {
222
256
  type: 'addNoun',
@@ -245,44 +279,64 @@ export class ServerSearchConduitAugmentation extends WebSocketConduitAugmentatio
245
279
  };
246
280
  }
247
281
  }
282
+ /**
283
+ * Establish connection to remote server
284
+ * @param serverUrl Server URL to connect to
285
+ * @param options Connection options
286
+ * @returns Connection promise
287
+ */
288
+ establishConnection(serverUrl, options) {
289
+ // Stub implementation - remote connection functionality not yet fully implemented in 2.0
290
+ console.warn('establishConnection: Remote server connections not yet fully implemented in Brainy 2.0');
291
+ return Promise.resolve({ connected: false, reason: 'Not implemented' });
292
+ }
293
+ /**
294
+ * Close WebSocket connection
295
+ * @param connectionId Connection ID to close
296
+ * @returns Promise that resolves when connection is closed
297
+ */
298
+ async closeWebSocket(connectionId) {
299
+ // Stub implementation - WebSocket functionality not yet fully implemented in 2.0
300
+ console.warn(`closeWebSocket: WebSocket functionality not yet fully implemented in Brainy 2.0 (connectionId: ${connectionId})`);
301
+ }
248
302
  }
249
303
  /**
250
304
  * ServerSearchActivationAugmentation
251
305
  *
252
306
  * An activation augmentation that provides actions for server search functionality.
253
307
  */
254
- export class ServerSearchActivationAugmentation {
255
- constructor(name = 'server-search-activation') {
256
- this.enabled = true;
257
- this.isInitialized = false;
308
+ export class ServerSearchActivationAugmentation extends BaseAugmentation {
309
+ constructor(name) {
310
+ super();
311
+ this.name = 'server-search-activation';
312
+ this.timing = 'after';
313
+ this.operations = ['search', 'addNoun'];
314
+ this.priority = 20;
258
315
  this.conduitAugmentation = null;
259
316
  this.connections = new Map();
260
- this.name = name;
261
- this.description = 'Activation augmentation for server-hosted Brainy search';
262
- }
263
- getType() {
264
- return AugmentationType.ACTIVATION;
265
- }
266
- /**
267
- * Initialize the augmentation
268
- */
269
- async initialize() {
270
- if (this.isInitialized) {
271
- return;
317
+ if (name) {
318
+ // Keep constructor parameter for API compatibility but ignore it
272
319
  }
273
- this.isInitialized = true;
274
320
  }
275
- /**
276
- * Shut down the augmentation
277
- */
278
- async shutDown() {
279
- this.isInitialized = false;
321
+ async onInitialize() {
322
+ // Initialization logic if needed
280
323
  }
281
- /**
282
- * Get the status of the augmentation
283
- */
284
- async getStatus() {
285
- return this.isInitialized ? 'active' : 'inactive';
324
+ async onShutdown() {
325
+ // Cleanup connections
326
+ this.connections.clear();
327
+ }
328
+ async execute(operation, params, next) {
329
+ // Execute the operation first
330
+ const result = await next();
331
+ // Handle server search operations
332
+ if (operation === 'search' && this.conduitAugmentation) {
333
+ // Trigger server search when local search happens
334
+ const connectionId = this.connections.keys().next().value;
335
+ if (connectionId && params.query) {
336
+ await this.conduitAugmentation.searchServer(connectionId, params.query, params.limit || 10);
337
+ }
338
+ }
339
+ return result;
286
340
  }
287
341
  /**
288
342
  * Set the conduit augmentation to use for server search
@@ -502,24 +556,23 @@ export class ServerSearchActivationAugmentation {
502
556
  export async function createServerSearchAugmentations(serverUrl, options = {}) {
503
557
  // Create the conduit augmentation
504
558
  const conduit = new ServerSearchConduitAugmentation(options.conduitName);
505
- await conduit.initialize();
506
559
  // Set the local database if provided
507
560
  if (options.localDb) {
508
561
  conduit.setLocalDb(options.localDb);
509
562
  }
510
- // Create the activation augmentation
563
+ // Create the activation augmentation
511
564
  const activation = new ServerSearchActivationAugmentation(options.activationName);
512
- await activation.initialize();
565
+ // Note: Augmentations will be initialized when added to BrainyData
513
566
  // Link the augmentations
514
567
  activation.setConduitAugmentation(conduit);
515
- // Connect to the server
516
- const connectionResult = await conduit.establishConnection(serverUrl, {
517
- protocols: options.protocols
518
- });
519
- if (!connectionResult.success || !connectionResult.data) {
520
- throw new Error(`Failed to connect to server: ${connectionResult.error}`);
521
- }
522
- const connection = connectionResult.data;
568
+ // TODO: Connect to the server (stub implementation for now)
569
+ const connection = {
570
+ connectionId: `stub-connection-${Date.now()}`,
571
+ url: serverUrl,
572
+ status: 'connected',
573
+ close: async () => { },
574
+ send: async (data) => { }
575
+ };
523
576
  // Store the connection in the activation augmentation
524
577
  activation.storeConnection(connection.connectionId, connection);
525
578
  return {