@soulcraft/brainy 3.0.0 → 3.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 (260) hide show
  1. package/CHANGELOG.md +53 -3
  2. package/README.md +353 -110
  3. package/bin/brainy.js +340 -62
  4. package/dist/api/ConfigAPI.d.ts +67 -0
  5. package/dist/api/ConfigAPI.js +166 -0
  6. package/dist/api/DataAPI.d.ts +123 -0
  7. package/dist/api/DataAPI.js +391 -0
  8. package/dist/api/SecurityAPI.d.ts +50 -0
  9. package/dist/api/SecurityAPI.js +139 -0
  10. package/dist/api/UniversalImportAPI.d.ts +134 -0
  11. package/dist/api/UniversalImportAPI.js +615 -0
  12. package/dist/augmentationManager.js +12 -7
  13. package/dist/augmentationPipeline.d.ts +0 -61
  14. package/dist/augmentationPipeline.js +0 -87
  15. package/dist/augmentationRegistry.d.ts +1 -1
  16. package/dist/augmentationRegistry.js +1 -1
  17. package/dist/augmentations/apiServerAugmentation.d.ts +27 -1
  18. package/dist/augmentations/apiServerAugmentation.js +290 -9
  19. package/dist/augmentations/auditLogAugmentation.d.ts +109 -0
  20. package/dist/augmentations/auditLogAugmentation.js +358 -0
  21. package/dist/augmentations/batchProcessingAugmentation.d.ts +3 -2
  22. package/dist/augmentations/batchProcessingAugmentation.js +123 -22
  23. package/dist/augmentations/brainyAugmentation.d.ts +142 -8
  24. package/dist/augmentations/brainyAugmentation.js +179 -2
  25. package/dist/augmentations/cacheAugmentation.d.ts +8 -5
  26. package/dist/augmentations/cacheAugmentation.js +116 -17
  27. package/dist/augmentations/conduitAugmentations.d.ts +2 -2
  28. package/dist/augmentations/conduitAugmentations.js +2 -2
  29. package/dist/augmentations/configResolver.d.ts +122 -0
  30. package/dist/augmentations/configResolver.js +440 -0
  31. package/dist/augmentations/connectionPoolAugmentation.d.ts +3 -1
  32. package/dist/augmentations/connectionPoolAugmentation.js +37 -12
  33. package/dist/augmentations/defaultAugmentations.d.ts +14 -10
  34. package/dist/augmentations/defaultAugmentations.js +16 -11
  35. package/dist/augmentations/discovery/catalogDiscovery.d.ts +142 -0
  36. package/dist/augmentations/discovery/catalogDiscovery.js +249 -0
  37. package/dist/augmentations/discovery/localDiscovery.d.ts +84 -0
  38. package/dist/augmentations/discovery/localDiscovery.js +246 -0
  39. package/dist/augmentations/discovery/runtimeLoader.d.ts +97 -0
  40. package/dist/augmentations/discovery/runtimeLoader.js +337 -0
  41. package/dist/augmentations/discovery.d.ts +152 -0
  42. package/dist/augmentations/discovery.js +441 -0
  43. package/dist/augmentations/display/cache.d.ts +130 -0
  44. package/dist/augmentations/display/cache.js +319 -0
  45. package/dist/augmentations/display/fieldPatterns.d.ts +52 -0
  46. package/dist/augmentations/display/fieldPatterns.js +393 -0
  47. package/dist/augmentations/display/iconMappings.d.ts +57 -0
  48. package/dist/augmentations/display/iconMappings.js +68 -0
  49. package/dist/augmentations/display/intelligentComputation.d.ts +109 -0
  50. package/dist/augmentations/display/intelligentComputation.js +462 -0
  51. package/dist/augmentations/display/types.d.ts +203 -0
  52. package/dist/augmentations/display/types.js +7 -0
  53. package/dist/augmentations/entityRegistryAugmentation.d.ts +3 -1
  54. package/dist/augmentations/entityRegistryAugmentation.js +5 -1
  55. package/dist/augmentations/indexAugmentation.d.ts +5 -3
  56. package/dist/augmentations/indexAugmentation.js +5 -2
  57. package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +24 -7
  58. package/dist/augmentations/intelligentVerbScoringAugmentation.js +111 -27
  59. package/dist/augmentations/manifest.d.ts +176 -0
  60. package/dist/augmentations/manifest.js +8 -0
  61. package/dist/augmentations/marketplace/AugmentationMarketplace.d.ts +168 -0
  62. package/dist/augmentations/marketplace/AugmentationMarketplace.js +329 -0
  63. package/dist/augmentations/marketplace/cli.d.ts +47 -0
  64. package/dist/augmentations/marketplace/cli.js +265 -0
  65. package/dist/augmentations/metricsAugmentation.d.ts +3 -3
  66. package/dist/augmentations/metricsAugmentation.js +2 -2
  67. package/dist/augmentations/monitoringAugmentation.d.ts +3 -3
  68. package/dist/augmentations/monitoringAugmentation.js +2 -2
  69. package/dist/augmentations/neuralImport.d.ts +1 -1
  70. package/dist/augmentations/neuralImport.js +4 -4
  71. package/dist/augmentations/rateLimitAugmentation.d.ts +82 -0
  72. package/dist/augmentations/rateLimitAugmentation.js +321 -0
  73. package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +2 -2
  74. package/dist/augmentations/requestDeduplicatorAugmentation.js +1 -1
  75. package/dist/augmentations/storageAugmentation.d.ts +1 -1
  76. package/dist/augmentations/storageAugmentation.js +2 -2
  77. package/dist/augmentations/storageAugmentations.d.ts +37 -8
  78. package/dist/augmentations/storageAugmentations.js +204 -15
  79. package/dist/augmentations/synapseAugmentation.d.ts +1 -1
  80. package/dist/augmentations/synapseAugmentation.js +35 -16
  81. package/dist/augmentations/typeMatching/brainyTypes.d.ts +83 -0
  82. package/dist/augmentations/typeMatching/brainyTypes.js +425 -0
  83. package/dist/augmentations/typeMatching/intelligentTypeMatcher.d.ts +39 -59
  84. package/dist/augmentations/typeMatching/intelligentTypeMatcher.js +103 -389
  85. package/dist/augmentations/universalDisplayAugmentation.d.ts +191 -0
  86. package/dist/augmentations/universalDisplayAugmentation.js +371 -0
  87. package/dist/brainy-unified.d.ts +106 -0
  88. package/dist/brainy-unified.js +327 -0
  89. package/dist/brainy.d.ts +273 -0
  90. package/dist/brainy.js +1181 -0
  91. package/dist/brainyData.d.ts +56 -111
  92. package/dist/brainyData.js +912 -756
  93. package/dist/brainyDataV3.d.ts +186 -0
  94. package/dist/brainyDataV3.js +337 -0
  95. package/dist/browserFramework.d.ts +6 -6
  96. package/dist/browserFramework.js +11 -8
  97. package/dist/browserFramework.minimal.d.ts +5 -5
  98. package/dist/browserFramework.minimal.js +11 -8
  99. package/dist/config/distributedPresets-new.d.ts +118 -0
  100. package/dist/config/distributedPresets-new.js +318 -0
  101. package/dist/config/distributedPresets.d.ts +118 -0
  102. package/dist/config/distributedPresets.js +318 -0
  103. package/dist/config/extensibleConfig.d.ts +99 -0
  104. package/dist/config/extensibleConfig.js +268 -0
  105. package/dist/config/index.d.ts +17 -0
  106. package/dist/config/index.js +35 -0
  107. package/dist/config/modelAutoConfig.d.ts +32 -0
  108. package/dist/config/modelAutoConfig.js +139 -0
  109. package/dist/config/modelPrecisionManager.d.ts +42 -0
  110. package/dist/config/modelPrecisionManager.js +98 -0
  111. package/dist/config/sharedConfigManager.d.ts +67 -0
  112. package/dist/config/sharedConfigManager.js +215 -0
  113. package/dist/config/storageAutoConfig.d.ts +41 -0
  114. package/dist/config/storageAutoConfig.js +328 -0
  115. package/dist/config/zeroConfig.d.ts +68 -0
  116. package/dist/config/zeroConfig.js +301 -0
  117. package/dist/cortex/backupRestore.d.ts +2 -2
  118. package/dist/cortex/backupRestore.js +85 -27
  119. package/dist/cortex/healthCheck.d.ts +2 -2
  120. package/dist/cortex/neuralImport.d.ts +2 -2
  121. package/dist/cortex/neuralImport.js +18 -13
  122. package/dist/cortex/performanceMonitor.d.ts +2 -2
  123. package/dist/critical/model-guardian.d.ts +4 -0
  124. package/dist/critical/model-guardian.js +31 -11
  125. package/dist/demo.d.ts +4 -4
  126. package/dist/demo.js +7 -7
  127. package/dist/distributed/cacheSync.d.ts +112 -0
  128. package/dist/distributed/cacheSync.js +265 -0
  129. package/dist/distributed/coordinator.d.ts +193 -0
  130. package/dist/distributed/coordinator.js +548 -0
  131. package/dist/distributed/httpTransport.d.ts +120 -0
  132. package/dist/distributed/httpTransport.js +446 -0
  133. package/dist/distributed/index.d.ts +8 -0
  134. package/dist/distributed/index.js +5 -0
  135. package/dist/distributed/networkTransport.d.ts +132 -0
  136. package/dist/distributed/networkTransport.js +633 -0
  137. package/dist/distributed/queryPlanner.d.ts +104 -0
  138. package/dist/distributed/queryPlanner.js +327 -0
  139. package/dist/distributed/readWriteSeparation.d.ts +134 -0
  140. package/dist/distributed/readWriteSeparation.js +350 -0
  141. package/dist/distributed/shardManager.d.ts +114 -0
  142. package/dist/distributed/shardManager.js +357 -0
  143. package/dist/distributed/shardMigration.d.ts +110 -0
  144. package/dist/distributed/shardMigration.js +289 -0
  145. package/dist/distributed/storageDiscovery.d.ts +160 -0
  146. package/dist/distributed/storageDiscovery.js +551 -0
  147. package/dist/embeddings/CachedEmbeddings.d.ts +40 -0
  148. package/dist/embeddings/CachedEmbeddings.js +146 -0
  149. package/dist/embeddings/EmbeddingManager.d.ts +102 -0
  150. package/dist/embeddings/EmbeddingManager.js +291 -0
  151. package/dist/embeddings/SingletonModelManager.d.ts +95 -0
  152. package/dist/embeddings/SingletonModelManager.js +220 -0
  153. package/dist/embeddings/index.d.ts +12 -0
  154. package/dist/embeddings/index.js +16 -0
  155. package/dist/embeddings/lightweight-embedder.d.ts +0 -1
  156. package/dist/embeddings/lightweight-embedder.js +4 -12
  157. package/dist/embeddings/model-manager.d.ts +11 -0
  158. package/dist/embeddings/model-manager.js +43 -7
  159. package/dist/embeddings/universal-memory-manager.d.ts +1 -1
  160. package/dist/embeddings/universal-memory-manager.js +27 -67
  161. package/dist/embeddings/worker-embedding.js +4 -8
  162. package/dist/errors/brainyError.d.ts +5 -1
  163. package/dist/errors/brainyError.js +12 -0
  164. package/dist/examples/basicUsage.js +7 -4
  165. package/dist/graph/graphAdjacencyIndex.d.ts +96 -0
  166. package/dist/graph/graphAdjacencyIndex.js +288 -0
  167. package/dist/graph/pathfinding.js +4 -2
  168. package/dist/hnsw/scaledHNSWSystem.js +11 -2
  169. package/dist/importManager.js +8 -5
  170. package/dist/index.d.ts +17 -22
  171. package/dist/index.js +37 -23
  172. package/dist/mcp/brainyMCPAdapter.d.ts +4 -4
  173. package/dist/mcp/brainyMCPAdapter.js +5 -5
  174. package/dist/mcp/brainyMCPService.d.ts +3 -3
  175. package/dist/mcp/brainyMCPService.js +3 -11
  176. package/dist/mcp/mcpAugmentationToolset.js +20 -30
  177. package/dist/neural/embeddedPatterns.d.ts +1 -1
  178. package/dist/neural/embeddedPatterns.js +2 -2
  179. package/dist/neural/entityExtractor.d.ts +65 -0
  180. package/dist/neural/entityExtractor.js +316 -0
  181. package/dist/neural/improvedNeuralAPI.d.ts +357 -0
  182. package/dist/neural/improvedNeuralAPI.js +2628 -0
  183. package/dist/neural/naturalLanguageProcessor.d.ts +155 -10
  184. package/dist/neural/naturalLanguageProcessor.js +941 -66
  185. package/dist/neural/naturalLanguageProcessorStatic.d.ts +2 -2
  186. package/dist/neural/naturalLanguageProcessorStatic.js +3 -3
  187. package/dist/neural/neuralAPI.js +8 -2
  188. package/dist/neural/patternLibrary.d.ts +57 -3
  189. package/dist/neural/patternLibrary.js +348 -13
  190. package/dist/neural/staticPatternMatcher.d.ts +2 -2
  191. package/dist/neural/staticPatternMatcher.js +2 -2
  192. package/dist/neural/types.d.ts +287 -0
  193. package/dist/neural/types.js +24 -0
  194. package/dist/shared/default-augmentations.d.ts +3 -3
  195. package/dist/shared/default-augmentations.js +5 -5
  196. package/dist/storage/adapters/baseStorageAdapter.d.ts +42 -0
  197. package/dist/storage/adapters/fileSystemStorage.d.ts +26 -2
  198. package/dist/storage/adapters/fileSystemStorage.js +218 -15
  199. package/dist/storage/adapters/memoryStorage.d.ts +4 -4
  200. package/dist/storage/adapters/memoryStorage.js +17 -12
  201. package/dist/storage/adapters/opfsStorage.d.ts +2 -2
  202. package/dist/storage/adapters/opfsStorage.js +2 -2
  203. package/dist/storage/adapters/s3CompatibleStorage.d.ts +2 -2
  204. package/dist/storage/adapters/s3CompatibleStorage.js +2 -2
  205. package/dist/storage/backwardCompatibility.d.ts +10 -78
  206. package/dist/storage/backwardCompatibility.js +17 -132
  207. package/dist/storage/baseStorage.d.ts +18 -2
  208. package/dist/storage/baseStorage.js +74 -3
  209. package/dist/storage/cacheManager.js +2 -2
  210. package/dist/storage/readOnlyOptimizations.js +8 -3
  211. package/dist/streaming/pipeline.d.ts +154 -0
  212. package/dist/streaming/pipeline.js +551 -0
  213. package/dist/triple/TripleIntelligence.d.ts +25 -110
  214. package/dist/triple/TripleIntelligence.js +4 -574
  215. package/dist/triple/TripleIntelligenceSystem.d.ts +159 -0
  216. package/dist/triple/TripleIntelligenceSystem.js +519 -0
  217. package/dist/types/apiTypes.d.ts +278 -0
  218. package/dist/types/apiTypes.js +33 -0
  219. package/dist/types/brainy.types.d.ts +308 -0
  220. package/dist/types/brainy.types.js +8 -0
  221. package/dist/types/brainyDataInterface.d.ts +5 -8
  222. package/dist/types/brainyDataInterface.js +2 -2
  223. package/dist/types/graphTypes.js +2 -2
  224. package/dist/utils/brainyTypes.d.ts +217 -0
  225. package/dist/utils/brainyTypes.js +261 -0
  226. package/dist/utils/cacheAutoConfig.d.ts +3 -3
  227. package/dist/utils/embedding.d.ts +9 -4
  228. package/dist/utils/embedding.js +89 -26
  229. package/dist/utils/enhancedLogger.d.ts +104 -0
  230. package/dist/utils/enhancedLogger.js +232 -0
  231. package/dist/utils/hybridModelManager.d.ts +19 -28
  232. package/dist/utils/hybridModelManager.js +36 -200
  233. package/dist/utils/index.d.ts +1 -1
  234. package/dist/utils/index.js +1 -1
  235. package/dist/utils/intelligentTypeMapper.d.ts +60 -0
  236. package/dist/utils/intelligentTypeMapper.js +349 -0
  237. package/dist/utils/metadataIndex.d.ts +118 -1
  238. package/dist/utils/metadataIndex.js +539 -16
  239. package/dist/utils/nodeVersionCheck.d.ts +24 -0
  240. package/dist/utils/nodeVersionCheck.js +65 -0
  241. package/dist/utils/paramValidation.d.ts +39 -0
  242. package/dist/utils/paramValidation.js +192 -0
  243. package/dist/utils/rateLimiter.d.ts +160 -0
  244. package/dist/utils/rateLimiter.js +271 -0
  245. package/dist/utils/statistics.d.ts +4 -4
  246. package/dist/utils/statistics.js +3 -3
  247. package/dist/utils/structuredLogger.d.ts +146 -0
  248. package/dist/utils/structuredLogger.js +394 -0
  249. package/dist/utils/textEncoding.js +2 -1
  250. package/dist/utils/typeValidation.d.ts +59 -0
  251. package/dist/utils/typeValidation.js +374 -0
  252. package/dist/utils/version.js +19 -3
  253. package/package.json +15 -4
  254. package/scripts/download-models.cjs +94 -20
  255. package/dist/augmentations/walAugmentation.d.ts +0 -109
  256. package/dist/augmentations/walAugmentation.js +0 -516
  257. package/dist/chat/BrainyChat.d.ts +0 -121
  258. package/dist/chat/BrainyChat.js +0 -396
  259. package/dist/chat/ChatCLI.d.ts +0 -61
  260. package/dist/chat/ChatCLI.js +0 -351
@@ -6,7 +6,6 @@
6
6
  *
7
7
  * This minimal implementation redirects to the new AugmentationRegistry system.
8
8
  */
9
- import { BrainyAugmentation } from './types/augmentations.js';
10
9
  /**
11
10
  * Execution mode for pipeline operations
12
11
  */
@@ -33,66 +32,6 @@ export interface PipelineOptions {
33
32
  export declare class Cortex {
34
33
  private static instance?;
35
34
  constructor();
36
- /**
37
- * Get all available augmentation types (returns empty for compatibility)
38
- * @deprecated Use brain.augmentations instead
39
- */
40
- getAvailableAugmentationTypes(): string[];
41
- /**
42
- * Get augmentations by type (returns empty for compatibility)
43
- * @deprecated Use brain.augmentations instead
44
- */
45
- getAugmentationsByType(type: string): BrainyAugmentation[];
46
- /**
47
- * Check if augmentation is enabled (returns false for compatibility)
48
- * @deprecated Use brain.augmentations instead
49
- */
50
- isAugmentationEnabled(name: string): boolean;
51
- /**
52
- * List augmentations with status (returns empty for compatibility)
53
- * @deprecated Use brain.augmentations instead
54
- */
55
- listAugmentationsWithStatus(): Array<{
56
- name: string;
57
- type: string;
58
- enabled: boolean;
59
- description: string;
60
- }>;
61
- /**
62
- * Execute augmentations (compatibility method)
63
- * @deprecated Use brain.augmentations.execute instead
64
- */
65
- executeAugmentations<T>(operation: string, data: any, options?: PipelineOptions): Promise<T>;
66
- /**
67
- * Enable augmentation (compatibility method)
68
- * @deprecated Use brain.augmentations instead
69
- */
70
- enableAugmentation(name: string): boolean;
71
- /**
72
- * Disable augmentation (compatibility method)
73
- * @deprecated Use brain.augmentations instead
74
- */
75
- disableAugmentation(name: string): boolean;
76
- /**
77
- * Register augmentation (compatibility method)
78
- * @deprecated Use brain.augmentations.register instead
79
- */
80
- register(augmentation: BrainyAugmentation): void;
81
- /**
82
- * Unregister augmentation (compatibility method)
83
- * @deprecated Use brain.augmentations instead
84
- */
85
- unregister(name: string): boolean;
86
- /**
87
- * Enable augmentation type (compatibility method)
88
- * @deprecated Use brain.augmentations instead
89
- */
90
- enableAugmentationType(type: string): number;
91
- /**
92
- * Disable augmentation type (compatibility method)
93
- * @deprecated Use brain.augmentations instead
94
- */
95
- disableAugmentationType(type: string): number;
96
35
  }
97
36
  export declare const cortex: Cortex;
98
37
  export declare const AugmentationPipeline: typeof Cortex;
@@ -28,93 +28,6 @@ export class Cortex {
28
28
  }
29
29
  Cortex.instance = this;
30
30
  }
31
- /**
32
- * Get all available augmentation types (returns empty for compatibility)
33
- * @deprecated Use brain.augmentations instead
34
- */
35
- getAvailableAugmentationTypes() {
36
- console.warn('getAvailableAugmentationTypes is deprecated. Use brain.augmentations instead.');
37
- return [];
38
- }
39
- /**
40
- * Get augmentations by type (returns empty for compatibility)
41
- * @deprecated Use brain.augmentations instead
42
- */
43
- getAugmentationsByType(type) {
44
- console.warn('getAugmentationsByType is deprecated. Use brain.augmentations instead.');
45
- return [];
46
- }
47
- /**
48
- * Check if augmentation is enabled (returns false for compatibility)
49
- * @deprecated Use brain.augmentations instead
50
- */
51
- isAugmentationEnabled(name) {
52
- console.warn('isAugmentationEnabled is deprecated. Use brain.augmentations instead.');
53
- return false;
54
- }
55
- /**
56
- * List augmentations with status (returns empty for compatibility)
57
- * @deprecated Use brain.augmentations instead
58
- */
59
- listAugmentationsWithStatus() {
60
- console.warn('listAugmentationsWithStatus is deprecated. Use brain.augmentations instead.');
61
- return [];
62
- }
63
- /**
64
- * Execute augmentations (compatibility method)
65
- * @deprecated Use brain.augmentations.execute instead
66
- */
67
- async executeAugmentations(operation, data, options) {
68
- console.warn('executeAugmentations is deprecated. Use brain.augmentations.execute instead.');
69
- return data;
70
- }
71
- /**
72
- * Enable augmentation (compatibility method)
73
- * @deprecated Use brain.augmentations instead
74
- */
75
- enableAugmentation(name) {
76
- console.warn('enableAugmentation is deprecated. Use brain.augmentations instead.');
77
- return false;
78
- }
79
- /**
80
- * Disable augmentation (compatibility method)
81
- * @deprecated Use brain.augmentations instead
82
- */
83
- disableAugmentation(name) {
84
- console.warn('disableAugmentation is deprecated. Use brain.augmentations instead.');
85
- return false;
86
- }
87
- /**
88
- * Register augmentation (compatibility method)
89
- * @deprecated Use brain.augmentations.register instead
90
- */
91
- register(augmentation) {
92
- console.warn('register is deprecated. Use brain.augmentations.register instead.');
93
- }
94
- /**
95
- * Unregister augmentation (compatibility method)
96
- * @deprecated Use brain.augmentations instead
97
- */
98
- unregister(name) {
99
- console.warn('unregister is deprecated. Use brain.augmentations instead.');
100
- return false;
101
- }
102
- /**
103
- * Enable augmentation type (compatibility method)
104
- * @deprecated Use brain.augmentations instead
105
- */
106
- enableAugmentationType(type) {
107
- console.warn('enableAugmentationType is deprecated. Use brain.augmentations instead.');
108
- return 0;
109
- }
110
- /**
111
- * Disable augmentation type (compatibility method)
112
- * @deprecated Use brain.augmentations instead
113
- */
114
- disableAugmentationType(type) {
115
- console.warn('disableAugmentationType is deprecated. Use brain.augmentations instead.');
116
- return 0;
117
- }
118
31
  }
119
32
  // Create and export a default instance of the cortex
120
33
  export const cortex = new Cortex();
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @deprecated This module provides backward compatibility for old augmentation
5
5
  * loading code. All new code should use the AugmentationRegistry class directly
6
- * on BrainyData instances.
6
+ * on Brainy instances.
7
7
  */
8
8
  import { BrainyAugmentation } from './types/augmentations.js';
9
9
  /**
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @deprecated This module provides backward compatibility for old augmentation
5
5
  * loading code. All new code should use the AugmentationRegistry class directly
6
- * on BrainyData instances.
6
+ * on Brainy instances.
7
7
  */
8
8
  /**
9
9
  * Registry of all available augmentations (for compatibility)
@@ -45,13 +45,14 @@ export declare class APIServerAugmentation extends BaseAugmentation {
45
45
  readonly metadata: "readonly";
46
46
  readonly operations: ("all")[];
47
47
  readonly priority = 5;
48
- private config;
48
+ protected config: APIServerConfig;
49
49
  private mcpService?;
50
50
  private httpServer?;
51
51
  private wsServer?;
52
52
  private clients;
53
53
  private operationHistory;
54
54
  private maxHistorySize;
55
+ private rateLimitStore;
55
56
  constructor(config?: APIServerConfig);
56
57
  protected onInitialize(): Promise<void>;
57
58
  /**
@@ -98,6 +99,31 @@ export declare class APIServerAugmentation extends BaseAugmentation {
98
99
  * Start Service Worker (for browser)
99
100
  */
100
101
  private startServiceWorker;
102
+ /**
103
+ * Create universal handler using Web Standards (works in Node, Deno, Service Workers)
104
+ */
105
+ private createUniversalHandler;
106
+ /**
107
+ * Handle Brainy API requests using universal Request/Response
108
+ */
109
+ private handleBrainyAPI;
110
+ /**
111
+ * Handle MCP API requests
112
+ */
113
+ private handleMCPAPI;
114
+ /**
115
+ * Universal WebSocket setup (works in Node, Deno)
116
+ */
117
+ private setupUniversalWebSocket;
118
+ /**
119
+ * Service Worker messaging for WebSocket-like communication
120
+ */
121
+ private setupServiceWorkerMessaging;
122
+ /**
123
+ * Universal authentication using Web Standards
124
+ */
125
+ private authenticateRequest;
126
+ private checkRateLimit;
101
127
  /**
102
128
  * Shutdown the server
103
129
  */
@@ -29,6 +29,7 @@ export class APIServerAugmentation extends BaseAugmentation {
29
29
  this.clients = new Map();
30
30
  this.operationHistory = [];
31
31
  this.maxHistorySize = 1000;
32
+ this.rateLimitStore = new Map();
32
33
  this.config = {
33
34
  enabled: true,
34
35
  port: 3000,
@@ -138,7 +139,7 @@ export class APIServerAugmentation extends BaseAugmentation {
138
139
  app.post('/api/add', async (req, res) => {
139
140
  try {
140
141
  const { content, metadata } = req.body;
141
- const id = await this.context.brain.add(content, metadata);
142
+ const id = await this.context.brain.addNoun(content, 'Content', metadata);
142
143
  res.json({ success: true, id });
143
144
  }
144
145
  catch (error) {
@@ -300,7 +301,7 @@ export class APIServerAugmentation extends BaseAugmentation {
300
301
  }));
301
302
  break;
302
303
  case 'add':
303
- const id = await this.context.brain.add(msg.content, msg.metadata);
304
+ const id = await this.context.brain.addNoun(msg.content, 'Content', msg.metadata);
304
305
  socket.send(JSON.stringify({
305
306
  type: 'addResult',
306
307
  requestId: msg.requestId,
@@ -456,17 +457,294 @@ export class APIServerAugmentation extends BaseAugmentation {
456
457
  * Start Deno server
457
458
  */
458
459
  async startDenoServer() {
459
- // Deno implementation would go here
460
- // Using Deno.serve() or oak framework
461
- this.log('Deno server not yet implemented', 'warn');
460
+ try {
461
+ // Check if Deno.serve is available (Deno 1.35+)
462
+ const DenoGlobal = globalThis.Deno;
463
+ if (DenoGlobal && 'serve' in DenoGlobal) {
464
+ const handler = this.createUniversalHandler();
465
+ this.httpServer = DenoGlobal.serve({
466
+ port: this.config.port,
467
+ hostname: this.config.host || '0.0.0.0',
468
+ handler: handler
469
+ });
470
+ this.log(`Deno server started on ${this.config.host || '0.0.0.0'}:${this.config.port}`);
471
+ // Setup WebSocket handling for Deno
472
+ this.setupUniversalWebSocket();
473
+ }
474
+ else {
475
+ throw new Error('Deno.serve not available - requires Deno 1.35+');
476
+ }
477
+ }
478
+ catch (error) {
479
+ this.log(`Failed to start Deno server: ${error.message}`, 'error');
480
+ throw error;
481
+ }
462
482
  }
463
483
  /**
464
484
  * Start Service Worker (for browser)
465
485
  */
466
486
  async startServiceWorker() {
467
- // Service Worker implementation would go here
468
- // Intercepts fetch() calls and handles them locally
469
- this.log('Service Worker API not yet implemented', 'warn');
487
+ try {
488
+ if (typeof self !== 'undefined' && 'addEventListener' in self) {
489
+ // Service Worker environment - intercept fetch events
490
+ const handler = this.createUniversalHandler();
491
+ self.addEventListener('fetch', async (event) => {
492
+ const url = new URL(event.request.url);
493
+ // Only handle API requests
494
+ if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/ws') || url.pathname.startsWith('/mcp/')) {
495
+ event.respondWith(handler(event.request));
496
+ }
497
+ });
498
+ this.log('Service Worker API server registered for /api/, /ws, and /mcp paths');
499
+ // Setup message handling for WebSocket-like communication
500
+ this.setupServiceWorkerMessaging();
501
+ }
502
+ else if (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) {
503
+ // Browser main thread - service worker registration should be handled by the application
504
+ this.log('Service Worker environment detected. Registration should be handled by your application.', 'info');
505
+ // Return early - the app will handle service worker registration
506
+ return;
507
+ }
508
+ else {
509
+ this.log('Service Worker environment not available', 'warn');
510
+ return;
511
+ }
512
+ }
513
+ catch (error) {
514
+ this.log(`Failed to start Service Worker server: ${error.message}`, 'error');
515
+ throw error;
516
+ }
517
+ }
518
+ /**
519
+ * Create universal handler using Web Standards (works in Node, Deno, Service Workers)
520
+ */
521
+ createUniversalHandler() {
522
+ return async (request) => {
523
+ try {
524
+ const url = new URL(request.url);
525
+ const method = request.method.toUpperCase();
526
+ const path = url.pathname;
527
+ // Add CORS headers
528
+ const corsOrigin = Array.isArray(this.config.cors?.origin)
529
+ ? this.config.cors.origin[0]
530
+ : this.config.cors?.origin || '*';
531
+ const headers = new Headers({
532
+ 'Access-Control-Allow-Origin': corsOrigin,
533
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
534
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
535
+ 'Content-Type': 'application/json'
536
+ });
537
+ // Handle preflight requests
538
+ if (method === 'OPTIONS') {
539
+ return new Response(null, { status: 200, headers });
540
+ }
541
+ // Authentication
542
+ if (!this.authenticateRequest(request)) {
543
+ return new Response(JSON.stringify({ error: 'Unauthorized' }), {
544
+ status: 401,
545
+ headers
546
+ });
547
+ }
548
+ // Rate limiting
549
+ if (!this.checkRateLimit(request)) {
550
+ return new Response(JSON.stringify({ error: 'Rate limit exceeded' }), {
551
+ status: 429,
552
+ headers
553
+ });
554
+ }
555
+ // Route handling
556
+ if (path.startsWith('/api/brainy/')) {
557
+ return this.handleBrainyAPI(request, path.replace('/api/brainy/', ''), headers);
558
+ }
559
+ else if (path.startsWith('/mcp/')) {
560
+ return this.handleMCPAPI(request, path.replace('/mcp/', ''), headers);
561
+ }
562
+ else if (path === '/health') {
563
+ return new Response(JSON.stringify({ status: 'ok', timestamp: Date.now() }), {
564
+ status: 200,
565
+ headers
566
+ });
567
+ }
568
+ return new Response(JSON.stringify({ error: 'Not found' }), {
569
+ status: 404,
570
+ headers
571
+ });
572
+ }
573
+ catch (error) {
574
+ return new Response(JSON.stringify({
575
+ error: 'Internal server error',
576
+ message: error.message
577
+ }), {
578
+ status: 500,
579
+ headers: new Headers({ 'Content-Type': 'application/json' })
580
+ });
581
+ }
582
+ };
583
+ }
584
+ /**
585
+ * Handle Brainy API requests using universal Request/Response
586
+ */
587
+ async handleBrainyAPI(request, path, headers) {
588
+ const method = request.method.toUpperCase();
589
+ const body = method !== 'GET' ? await request.json().catch(() => ({})) : {};
590
+ try {
591
+ let result;
592
+ switch (`${method} ${path}`) {
593
+ case 'POST add':
594
+ result = { id: await this.context.brain.add(body) };
595
+ break;
596
+ case 'GET get':
597
+ const id = new URL(request.url).searchParams.get('id');
598
+ result = await this.context.brain.get(id);
599
+ break;
600
+ case 'PUT update':
601
+ await this.context.brain.update(body);
602
+ result = { success: true };
603
+ break;
604
+ case 'DELETE delete':
605
+ const deleteId = new URL(request.url).searchParams.get('id');
606
+ await this.context.brain.delete(deleteId);
607
+ result = { success: true };
608
+ break;
609
+ case 'POST find':
610
+ result = await this.context.brain.find(body);
611
+ break;
612
+ case 'POST relate':
613
+ result = { id: await this.context.brain.relate(body) };
614
+ break;
615
+ case 'GET insights':
616
+ result = await this.context.brain.insights();
617
+ break;
618
+ default:
619
+ return new Response(JSON.stringify({ error: `Unknown endpoint: ${method} ${path}` }), {
620
+ status: 404,
621
+ headers
622
+ });
623
+ }
624
+ return new Response(JSON.stringify(result), { status: 200, headers });
625
+ }
626
+ catch (error) {
627
+ return new Response(JSON.stringify({
628
+ error: error.message
629
+ }), { status: 400, headers });
630
+ }
631
+ }
632
+ /**
633
+ * Handle MCP API requests
634
+ */
635
+ async handleMCPAPI(request, path, headers) {
636
+ try {
637
+ if (!this.mcpService) {
638
+ return new Response(JSON.stringify({ error: 'MCP service not available' }), {
639
+ status: 503,
640
+ headers
641
+ });
642
+ }
643
+ const body = await request.json().catch(() => ({}));
644
+ // Convert to MCP request format
645
+ const mcpRequest = {
646
+ type: path.includes('data') ? 'data_access' : 'tool_execution',
647
+ ...body
648
+ };
649
+ const result = await this.mcpService.handleRequest(mcpRequest);
650
+ return new Response(JSON.stringify(result), { status: 200, headers });
651
+ }
652
+ catch (error) {
653
+ return new Response(JSON.stringify({
654
+ error: error.message
655
+ }), { status: 400, headers });
656
+ }
657
+ }
658
+ /**
659
+ * Universal WebSocket setup (works in Node, Deno)
660
+ */
661
+ setupUniversalWebSocket() {
662
+ // WebSocket handling varies by platform but uses same interface
663
+ this.log('WebSocket support enabled for real-time updates');
664
+ }
665
+ /**
666
+ * Service Worker messaging for WebSocket-like communication
667
+ */
668
+ setupServiceWorkerMessaging() {
669
+ if (typeof self !== 'undefined') {
670
+ self.addEventListener('message', async (event) => {
671
+ if (event.data.type === 'brainy-api') {
672
+ try {
673
+ const response = await this.handleBrainyAPI(new Request('http://localhost/api/brainy/' + event.data.endpoint, {
674
+ method: event.data.method || 'POST',
675
+ body: JSON.stringify(event.data.data)
676
+ }), event.data.endpoint, new Headers({ 'Content-Type': 'application/json' }));
677
+ const result = await response.json();
678
+ event.ports[0]?.postMessage({
679
+ id: event.data.id,
680
+ success: response.ok,
681
+ data: result
682
+ });
683
+ }
684
+ catch (error) {
685
+ event.ports[0]?.postMessage({
686
+ id: event.data.id,
687
+ success: false,
688
+ error: error.message
689
+ });
690
+ }
691
+ }
692
+ });
693
+ }
694
+ }
695
+ /**
696
+ * Universal authentication using Web Standards
697
+ */
698
+ authenticateRequest(request) {
699
+ if (!this.config.auth?.required)
700
+ return true;
701
+ const authHeader = request.headers.get('authorization');
702
+ if (!authHeader)
703
+ return false;
704
+ if (this.config.auth.apiKeys?.length) {
705
+ const apiKey = authHeader.replace('Bearer ', '');
706
+ return this.config.auth.apiKeys.includes(apiKey);
707
+ }
708
+ return true;
709
+ }
710
+ checkRateLimit(request) {
711
+ if (!this.config.rateLimit)
712
+ return true;
713
+ // Get client identifier from headers or use a default
714
+ const clientId = request.headers.get('x-forwarded-for') ||
715
+ request.headers.get('x-real-ip') ||
716
+ request.headers.get('cf-connecting-ip') || // Cloudflare
717
+ request.headers.get('x-vercel-forwarded-for') || // Vercel
718
+ 'unknown';
719
+ const now = Date.now();
720
+ const windowMs = this.config.rateLimit.windowMs || 60000;
721
+ const maxRequests = this.config.rateLimit.max || 100;
722
+ const windowStart = now - windowMs;
723
+ // Get or create request timestamps for this client
724
+ let timestamps = this.rateLimitStore.get(clientId) || [];
725
+ // Remove old timestamps outside the window
726
+ timestamps = timestamps.filter(t => t > windowStart);
727
+ // Check if limit exceeded
728
+ if (timestamps.length >= maxRequests) {
729
+ this.log(`Rate limit exceeded for client ${clientId}: ${timestamps.length}/${maxRequests} requests`, 'warn');
730
+ return false;
731
+ }
732
+ // Add current request timestamp
733
+ timestamps.push(now);
734
+ this.rateLimitStore.set(clientId, timestamps);
735
+ // Periodic cleanup of old entries to prevent memory leak
736
+ if (this.rateLimitStore.size > 1000) {
737
+ for (const [id, times] of this.rateLimitStore.entries()) {
738
+ const validTimes = times.filter(t => t > windowStart);
739
+ if (validTimes.length === 0) {
740
+ this.rateLimitStore.delete(id);
741
+ }
742
+ else {
743
+ this.rateLimitStore.set(id, validTimes);
744
+ }
745
+ }
746
+ }
747
+ return true;
470
748
  }
471
749
  /**
472
750
  * Shutdown the server
@@ -478,7 +756,10 @@ export class APIServerAugmentation extends BaseAugmentation {
478
756
  try {
479
757
  client.socket.close();
480
758
  }
481
- catch { }
759
+ catch (error) {
760
+ // Socket already closed or errored
761
+ console.debug('Error closing WebSocket:', error);
762
+ }
482
763
  }
483
764
  }
484
765
  this.clients.clear();
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Audit Logging Augmentation
3
+ * Provides comprehensive audit trail for all Brainy operations
4
+ */
5
+ import { BaseAugmentation } from './brainyAugmentation.js';
6
+ import { AugmentationManifest } from './manifest.js';
7
+ export interface AuditLogConfig {
8
+ enabled?: boolean;
9
+ logLevel?: 'minimal' | 'standard' | 'detailed';
10
+ includeData?: boolean;
11
+ includeMetadata?: boolean;
12
+ retention?: number;
13
+ storage?: 'memory' | 'file' | 'database';
14
+ filePath?: string;
15
+ maxMemoryLogs?: number;
16
+ }
17
+ export interface AuditLogEntry {
18
+ id: string;
19
+ timestamp: number;
20
+ operation: string;
21
+ params: any;
22
+ result?: any;
23
+ error?: any;
24
+ duration: number;
25
+ userId?: string;
26
+ sessionId?: string;
27
+ metadata?: Record<string, any>;
28
+ }
29
+ /**
30
+ * Audit Log Augmentation
31
+ */
32
+ export declare class AuditLogAugmentation extends BaseAugmentation {
33
+ readonly name = "auditLogger";
34
+ readonly timing: "around";
35
+ readonly metadata: "readonly";
36
+ operations: any;
37
+ readonly priority = 90;
38
+ readonly category: "core";
39
+ readonly description = "Comprehensive audit logging for compliance and debugging";
40
+ private logs;
41
+ private sessionId;
42
+ constructor(config?: AuditLogConfig);
43
+ getManifest(): AugmentationManifest;
44
+ protected onInitialize(): Promise<void>;
45
+ protected onShutdown(): Promise<void>;
46
+ /**
47
+ * Execute augmentation - log operations
48
+ */
49
+ execute<T = any>(operation: string, params: any, next: () => Promise<T>): Promise<T>;
50
+ /**
51
+ * Sanitize parameters to remove sensitive data
52
+ */
53
+ private sanitizeParams;
54
+ /**
55
+ * Sanitize result data
56
+ */
57
+ private sanitizeResult;
58
+ /**
59
+ * Sanitize error information
60
+ */
61
+ private sanitizeError;
62
+ /**
63
+ * Write log entry
64
+ */
65
+ private writeLog;
66
+ /**
67
+ * Flush logs to persistent storage
68
+ */
69
+ private flushLogs;
70
+ /**
71
+ * Clean up old logs based on retention
72
+ */
73
+ private cleanupOldLogs;
74
+ /**
75
+ * Generate unique ID
76
+ */
77
+ private generateId;
78
+ /**
79
+ * Query audit logs
80
+ */
81
+ queryLogs(filter?: {
82
+ operation?: string;
83
+ startTime?: number;
84
+ endTime?: number;
85
+ sessionId?: string;
86
+ hasError?: boolean;
87
+ }): AuditLogEntry[];
88
+ /**
89
+ * Get audit statistics
90
+ */
91
+ getStats(): {
92
+ totalLogs: number;
93
+ operations: Record<string, number>;
94
+ averageDuration: number;
95
+ errorRate: number;
96
+ };
97
+ /**
98
+ * Export logs for analysis
99
+ */
100
+ exportLogs(): AuditLogEntry[];
101
+ /**
102
+ * Clear all logs
103
+ */
104
+ clearLogs(): void;
105
+ }
106
+ /**
107
+ * Create audit log augmentation
108
+ */
109
+ export declare function createAuditLogAugmentation(config?: AuditLogConfig): AuditLogAugmentation;