@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
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Zero-Configuration System
3
+ * Main entry point for all auto-configuration features
4
+ */
5
+ // Model configuration
6
+ export { autoSelectModelPrecision, shouldAutoDownloadModels, getModelPath, logModelConfig } from './modelAutoConfig.js';
7
+ // Model precision - Always Q8 now (99% accuracy, 75% smaller)
8
+ export const getModelPrecision = () => 'q8';
9
+ // Storage configuration
10
+ export { autoDetectStorage, StorageType, StoragePreset, logStorageConfig } from './storageAutoConfig.js';
11
+ // Shared configuration for multi-instance
12
+ export { SharedConfigManager } from './sharedConfigManager.js';
13
+ // Main zero-config processor
14
+ export { processZeroConfig, createEmbeddingFunctionWithPrecision } from './zeroConfig.js';
15
+ // Strongly-typed presets and enums
16
+ export { PresetName, PresetCategory, ModelPrecision, StorageOption, FeatureSet, DistributedRole, PRESET_CONFIGS, getPreset, isValidPreset, getPresetsByCategory, getAllPresetNames, getPresetDescription, presetToBrainyConfig } from './distributedPresets.js';
17
+ // Extensible configuration
18
+ export { registerStorageAugmentation, registerPresetAugmentation, getConfigRegistry } from './extensibleConfig.js';
19
+ /**
20
+ * Main zero-config processor
21
+ * This is what Brainy will call
22
+ */
23
+ export async function applyZeroConfig(input) {
24
+ // Handle legacy config (full object) by detecting known legacy properties
25
+ if (input && typeof input === 'object' &&
26
+ (input.storage?.forceMemoryStorage || input.storage?.forceFileSystemStorage || input.storage?.s3Storage)) {
27
+ // This is a legacy config object - pass through unchanged
28
+ console.log('📦 Using legacy configuration format');
29
+ return input;
30
+ }
31
+ // Process as zero-config (includes new object format)
32
+ const { processZeroConfig } = await import('./zeroConfig.js');
33
+ return processZeroConfig(input);
34
+ }
35
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Model Configuration Auto-Selection
3
+ * Always uses Q8 for optimal size/performance balance (99% accuracy, 75% smaller)
4
+ */
5
+ export type ModelPrecision = 'q8';
6
+ export type ModelPreset = 'small' | 'auto';
7
+ interface ModelConfigResult {
8
+ precision: ModelPrecision;
9
+ reason: string;
10
+ autoSelected: boolean;
11
+ }
12
+ /**
13
+ * Auto-select model precision - Always returns Q8
14
+ * Q8 provides 99% accuracy with 75% smaller size
15
+ * @param override - For backward compatibility, ignored
16
+ */
17
+ export declare function autoSelectModelPrecision(override?: ModelPrecision | ModelPreset): ModelConfigResult;
18
+ /**
19
+ * Convenience function to check if models need to be downloaded
20
+ * This replaces the need for BRAINY_ALLOW_REMOTE_MODELS
21
+ */
22
+ export declare function shouldAutoDownloadModels(): boolean;
23
+ /**
24
+ * Get the model path with intelligent defaults
25
+ * This replaces the need for BRAINY_MODELS_PATH env var
26
+ */
27
+ export declare function getModelPath(): string;
28
+ /**
29
+ * Log model configuration decision (only in verbose mode)
30
+ */
31
+ export declare function logModelConfig(config: ModelConfigResult, verbose?: boolean): void;
32
+ export {};
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Model Configuration Auto-Selection
3
+ * Always uses Q8 for optimal size/performance balance (99% accuracy, 75% smaller)
4
+ */
5
+ import { isBrowser, isNode } from '../utils/environment.js';
6
+ /**
7
+ * Auto-select model precision - Always returns Q8
8
+ * Q8 provides 99% accuracy with 75% smaller size
9
+ * @param override - For backward compatibility, ignored
10
+ */
11
+ export function autoSelectModelPrecision(override) {
12
+ // Always use Q8 regardless of override for simplicity
13
+ // Q8 is optimal: 33MB vs 130MB, 99% accuracy retained
14
+ // Log deprecation notice if FP32 was requested
15
+ if (typeof override === 'string' && override.toLowerCase().includes('fp32')) {
16
+ console.log('Note: FP32 precision is deprecated. Using Q8 (99% accuracy, 75% smaller).');
17
+ }
18
+ return {
19
+ precision: 'q8',
20
+ reason: 'Q8 precision (99% accuracy, 75% smaller)',
21
+ autoSelected: true
22
+ };
23
+ }
24
+ /**
25
+ * Automatically detect the best model precision for the environment
26
+ * DEPRECATED: Always returns Q8 now
27
+ */
28
+ function autoDetectBestPrecision() {
29
+ // Always return Q8 - deprecated function kept for backward compatibility
30
+ return {
31
+ precision: 'q8',
32
+ reason: 'Q8 precision (99% accuracy, 75% smaller)',
33
+ autoSelected: true
34
+ };
35
+ }
36
+ /**
37
+ * Check if running in a serverless environment
38
+ */
39
+ function isServerlessEnvironment() {
40
+ if (!isNode())
41
+ return false;
42
+ return !!(process.env.AWS_LAMBDA_FUNCTION_NAME ||
43
+ process.env.VERCEL ||
44
+ process.env.NETLIFY ||
45
+ process.env.CLOUDFLARE_WORKERS ||
46
+ process.env.FUNCTIONS_WORKER_RUNTIME ||
47
+ process.env.K_SERVICE // Google Cloud Run
48
+ );
49
+ }
50
+ /**
51
+ * Get available memory in MB
52
+ */
53
+ function getAvailableMemoryMB() {
54
+ if (isBrowser()) {
55
+ // @ts-ignore - navigator.deviceMemory is experimental
56
+ if (navigator.deviceMemory) {
57
+ // @ts-ignore
58
+ return navigator.deviceMemory * 1024; // Device memory in GB
59
+ }
60
+ return 256; // Conservative default for browsers
61
+ }
62
+ if (isNode()) {
63
+ try {
64
+ // Try to get memory info synchronously for Node.js
65
+ // This will be available in Node.js environments
66
+ if (typeof process !== 'undefined' && process.memoryUsage) {
67
+ // Use RSS (Resident Set Size) as a proxy for available memory
68
+ const rss = process.memoryUsage().rss;
69
+ // Assume we can use up to 4GB or 50% more than current usage
70
+ return Math.min(4096, Math.floor(rss / (1024 * 1024) * 1.5));
71
+ }
72
+ }
73
+ catch {
74
+ // Fall through to default
75
+ }
76
+ return 1024; // Default 1GB for Node.js
77
+ }
78
+ return 512; // Conservative default
79
+ }
80
+ /**
81
+ * Convenience function to check if models need to be downloaded
82
+ * This replaces the need for BRAINY_ALLOW_REMOTE_MODELS
83
+ */
84
+ export function shouldAutoDownloadModels() {
85
+ // Always allow downloads unless explicitly disabled
86
+ // This eliminates the need for BRAINY_ALLOW_REMOTE_MODELS
87
+ const explicitlyDisabled = process.env.BRAINY_ALLOW_REMOTE_MODELS === 'false';
88
+ if (explicitlyDisabled) {
89
+ console.warn('Model downloads disabled via BRAINY_ALLOW_REMOTE_MODELS=false');
90
+ return false;
91
+ }
92
+ // In production, always allow downloads for seamless operation
93
+ if (process.env.NODE_ENV === 'production') {
94
+ return true;
95
+ }
96
+ // In development, allow downloads with a one-time notice
97
+ if (process.env.NODE_ENV === 'development') {
98
+ return true;
99
+ }
100
+ // Default: allow downloads
101
+ return true;
102
+ }
103
+ /**
104
+ * Get the model path with intelligent defaults
105
+ * This replaces the need for BRAINY_MODELS_PATH env var
106
+ */
107
+ export function getModelPath() {
108
+ // Check if user explicitly set a path (keeping this for advanced users)
109
+ if (process.env.BRAINY_MODELS_PATH) {
110
+ return process.env.BRAINY_MODELS_PATH;
111
+ }
112
+ // Browser - use cache API or IndexedDB (handled by transformers.js)
113
+ if (isBrowser()) {
114
+ return 'browser-cache';
115
+ }
116
+ // Serverless - use /tmp for ephemeral storage
117
+ if (isServerlessEnvironment()) {
118
+ return '/tmp/.brainy/models';
119
+ }
120
+ // Node.js - use home directory for persistent storage
121
+ if (isNode()) {
122
+ // Use process.env.HOME as a fallback
123
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '~';
124
+ return `${homeDir}/.brainy/models`;
125
+ }
126
+ // Fallback
127
+ return './.brainy/models';
128
+ }
129
+ /**
130
+ * Log model configuration decision (only in verbose mode)
131
+ */
132
+ export function logModelConfig(config, verbose = false) {
133
+ if (!verbose && process.env.NODE_ENV === 'production') {
134
+ return; // Silent in production unless verbose
135
+ }
136
+ const icon = config.autoSelected ? '🤖' : '👤';
137
+ console.log(`${icon} Model: ${config.precision.toUpperCase()} - ${config.reason}`);
138
+ }
139
+ //# sourceMappingURL=modelAutoConfig.js.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Central Model Precision Manager
3
+ *
4
+ * Single source of truth for model precision configuration.
5
+ * Ensures consistent usage of Q8 or FP32 models throughout the system.
6
+ */
7
+ import { ModelPrecision } from './modelAutoConfig.js';
8
+ export declare class ModelPrecisionManager {
9
+ private static instance;
10
+ private precision;
11
+ private isLocked;
12
+ private constructor();
13
+ static getInstance(): ModelPrecisionManager;
14
+ /**
15
+ * Get the current model precision
16
+ */
17
+ getPrecision(): ModelPrecision;
18
+ /**
19
+ * Set the model precision (can only be done before first model load)
20
+ */
21
+ setPrecision(precision: ModelPrecision): void;
22
+ /**
23
+ * Lock the precision (called after first model load)
24
+ */
25
+ lock(): void;
26
+ /**
27
+ * Check if precision is locked
28
+ */
29
+ isConfigLocked(): boolean;
30
+ /**
31
+ * Get precision info for logging
32
+ */
33
+ getInfo(): string;
34
+ /**
35
+ * Validate that a given precision matches the configured one
36
+ */
37
+ validatePrecision(precision: ModelPrecision): boolean;
38
+ }
39
+ export declare const getModelPrecision: () => ModelPrecision;
40
+ export declare const setModelPrecision: (precision: ModelPrecision) => void;
41
+ export declare const lockModelPrecision: () => void;
42
+ export declare const validateModelPrecision: (precision: ModelPrecision) => boolean;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Central Model Precision Manager
3
+ *
4
+ * Single source of truth for model precision configuration.
5
+ * Ensures consistent usage of Q8 or FP32 models throughout the system.
6
+ */
7
+ export class ModelPrecisionManager {
8
+ constructor() {
9
+ this.precision = 'q8'; // DEFAULT TO Q8
10
+ this.isLocked = false;
11
+ // Check environment variable override
12
+ const envPrecision = process.env.BRAINY_MODEL_PRECISION;
13
+ if (envPrecision === 'fp32' || envPrecision === 'q8') {
14
+ this.precision = envPrecision;
15
+ console.log(`Model precision set from environment: ${envPrecision.toUpperCase()}`);
16
+ }
17
+ else {
18
+ console.log('Using default model precision: Q8 (75% smaller, 99% accuracy)');
19
+ }
20
+ }
21
+ static getInstance() {
22
+ if (!ModelPrecisionManager.instance) {
23
+ ModelPrecisionManager.instance = new ModelPrecisionManager();
24
+ }
25
+ return ModelPrecisionManager.instance;
26
+ }
27
+ /**
28
+ * Get the current model precision
29
+ */
30
+ getPrecision() {
31
+ return this.precision;
32
+ }
33
+ /**
34
+ * Set the model precision (can only be done before first model load)
35
+ */
36
+ setPrecision(precision) {
37
+ if (this.isLocked) {
38
+ console.warn(`⚠️ Cannot change precision after model initialization. Current: ${this.precision.toUpperCase()}`);
39
+ return;
40
+ }
41
+ if (precision !== this.precision) {
42
+ console.log(`Model precision changed: ${this.precision.toUpperCase()} → ${precision.toUpperCase()}`);
43
+ this.precision = precision;
44
+ }
45
+ }
46
+ /**
47
+ * Lock the precision (called after first model load)
48
+ */
49
+ lock() {
50
+ if (!this.isLocked) {
51
+ this.isLocked = true;
52
+ console.log(`Model precision locked: ${this.precision.toUpperCase()}`);
53
+ }
54
+ }
55
+ /**
56
+ * Check if precision is locked
57
+ */
58
+ isConfigLocked() {
59
+ return this.isLocked;
60
+ }
61
+ /**
62
+ * Get precision info for logging
63
+ */
64
+ getInfo() {
65
+ const info = this.precision === 'q8'
66
+ ? 'Q8 (quantized, 23MB, 99% accuracy)'
67
+ : 'FP32 (full precision, 90MB, 100% accuracy)';
68
+ return `${info}${this.isLocked ? ' [LOCKED]' : ''}`;
69
+ }
70
+ /**
71
+ * Validate that a given precision matches the configured one
72
+ */
73
+ validatePrecision(precision) {
74
+ if (precision !== this.precision) {
75
+ console.error(`❌ Precision mismatch! Expected: ${this.precision.toUpperCase()}, Got: ${precision.toUpperCase()}`);
76
+ console.error('This will cause incompatible embeddings!');
77
+ return false;
78
+ }
79
+ return true;
80
+ }
81
+ }
82
+ // Export singleton instance getter
83
+ export const getModelPrecision = () => {
84
+ return ModelPrecisionManager.getInstance().getPrecision();
85
+ };
86
+ // Export setter (for configuration phase)
87
+ export const setModelPrecision = (precision) => {
88
+ ModelPrecisionManager.getInstance().setPrecision(precision);
89
+ };
90
+ // Export lock function (for after model initialization)
91
+ export const lockModelPrecision = () => {
92
+ ModelPrecisionManager.getInstance().lock();
93
+ };
94
+ // Export validation function
95
+ export const validateModelPrecision = (precision) => {
96
+ return ModelPrecisionManager.getInstance().validatePrecision(precision);
97
+ };
98
+ //# sourceMappingURL=modelPrecisionManager.js.map
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Shared Configuration Manager
3
+ * Ensures configuration consistency across multiple instances using shared storage
4
+ */
5
+ import { ModelPrecision } from './modelAutoConfig.js';
6
+ export interface SharedConfig {
7
+ version: string;
8
+ precision: ModelPrecision;
9
+ dimensions: number;
10
+ hnswM: number;
11
+ hnswEfConstruction: number;
12
+ distanceFunction: string;
13
+ createdAt: string;
14
+ lastUpdated: string;
15
+ instanceCount?: number;
16
+ lastAccessedBy?: string;
17
+ }
18
+ /**
19
+ * Manages configuration consistency for shared storage
20
+ */
21
+ export declare class SharedConfigManager {
22
+ private static CONFIG_FILE;
23
+ /**
24
+ * Load or create shared configuration
25
+ * When connecting to existing data, this OVERRIDES auto-configuration!
26
+ */
27
+ static loadOrCreateSharedConfig(storage: any, localConfig: any): Promise<{
28
+ config: any;
29
+ warnings: string[];
30
+ }>;
31
+ /**
32
+ * Check if storage type is shared (multi-instance)
33
+ */
34
+ private static isSharedStorage;
35
+ /**
36
+ * Load configuration from shared storage
37
+ */
38
+ private static loadConfigFromStorage;
39
+ /**
40
+ * Save configuration to shared storage
41
+ */
42
+ private static saveConfigToStorage;
43
+ /**
44
+ * Create shared configuration from local config
45
+ */
46
+ private static createSharedConfig;
47
+ /**
48
+ * Check for critical configuration mismatches
49
+ */
50
+ private static checkCriticalMismatches;
51
+ /**
52
+ * Merge local config with shared config (shared takes precedence for critical params)
53
+ */
54
+ private static mergeWithSharedConfig;
55
+ /**
56
+ * Update access information in shared config
57
+ */
58
+ private static updateAccessInfo;
59
+ /**
60
+ * Get unique identifier for this instance
61
+ */
62
+ private static getInstanceIdentifier;
63
+ /**
64
+ * Validate that a configuration is compatible with shared data
65
+ */
66
+ static validateCompatibility(config1: SharedConfig, config2: SharedConfig): boolean;
67
+ }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Shared Configuration Manager
3
+ * Ensures configuration consistency across multiple instances using shared storage
4
+ */
5
+ /**
6
+ * Manages configuration consistency for shared storage
7
+ */
8
+ export class SharedConfigManager {
9
+ /**
10
+ * Load or create shared configuration
11
+ * When connecting to existing data, this OVERRIDES auto-configuration!
12
+ */
13
+ static async loadOrCreateSharedConfig(storage, localConfig) {
14
+ const warnings = [];
15
+ try {
16
+ // Check if we're using shared storage
17
+ if (!this.isSharedStorage(localConfig.storageType)) {
18
+ // Local storage - use local config
19
+ return { config: localConfig, warnings: [] };
20
+ }
21
+ // Try to load existing configuration from shared storage
22
+ const existingConfig = await this.loadConfigFromStorage(storage);
23
+ if (existingConfig) {
24
+ // EXISTING SHARED DATA - Must use its configuration!
25
+ console.log('📁 Found existing shared data configuration');
26
+ // Check for critical mismatches
27
+ const mismatches = this.checkCriticalMismatches(localConfig, existingConfig);
28
+ if (mismatches.length > 0) {
29
+ console.warn('⚠️ Configuration override required for shared storage:');
30
+ mismatches.forEach(m => {
31
+ console.warn(` - ${m.param}: ${m.local} → ${m.shared} (using shared)`);
32
+ warnings.push(`${m.param} overridden: ${m.local} → ${m.shared}`);
33
+ });
34
+ }
35
+ // Override critical parameters with shared values
36
+ const mergedConfig = this.mergeWithSharedConfig(localConfig, existingConfig);
37
+ // Update last accessed
38
+ await this.updateAccessInfo(storage, existingConfig);
39
+ return { config: mergedConfig, warnings };
40
+ }
41
+ else {
42
+ // NEW SHARED STORAGE - Save our configuration
43
+ console.log('📝 Initializing new shared storage with configuration');
44
+ const sharedConfig = this.createSharedConfig(localConfig);
45
+ await this.saveConfigToStorage(storage, sharedConfig);
46
+ return { config: localConfig, warnings: [] };
47
+ }
48
+ }
49
+ catch (error) {
50
+ console.error('Failed to manage shared configuration:', error);
51
+ warnings.push('Could not verify shared configuration - proceeding with caution');
52
+ return { config: localConfig, warnings };
53
+ }
54
+ }
55
+ /**
56
+ * Check if storage type is shared (multi-instance)
57
+ */
58
+ static isSharedStorage(storageType) {
59
+ return ['s3', 'gcs', 'r2'].includes(storageType);
60
+ }
61
+ /**
62
+ * Load configuration from shared storage
63
+ */
64
+ static async loadConfigFromStorage(storage) {
65
+ try {
66
+ const configData = await storage.get(this.CONFIG_FILE);
67
+ if (!configData)
68
+ return null;
69
+ const config = JSON.parse(configData);
70
+ return config;
71
+ }
72
+ catch (error) {
73
+ // Config doesn't exist yet
74
+ return null;
75
+ }
76
+ }
77
+ /**
78
+ * Save configuration to shared storage
79
+ */
80
+ static async saveConfigToStorage(storage, config) {
81
+ try {
82
+ await storage.set(this.CONFIG_FILE, JSON.stringify(config, null, 2));
83
+ }
84
+ catch (error) {
85
+ console.error('Failed to save shared configuration:', error);
86
+ throw new Error('Cannot initialize shared storage without saving configuration');
87
+ }
88
+ }
89
+ /**
90
+ * Create shared configuration from local config
91
+ */
92
+ static createSharedConfig(localConfig) {
93
+ return {
94
+ version: '2.10.0', // Brainy version
95
+ precision: localConfig.embeddingOptions?.precision || 'fp32',
96
+ dimensions: 384, // Fixed for all-MiniLM-L6-v2
97
+ hnswM: localConfig.hnsw?.M || 16,
98
+ hnswEfConstruction: localConfig.hnsw?.efConstruction || 200,
99
+ distanceFunction: localConfig.distanceFunction || 'cosine',
100
+ createdAt: new Date().toISOString(),
101
+ lastUpdated: new Date().toISOString(),
102
+ instanceCount: 1,
103
+ lastAccessedBy: this.getInstanceIdentifier()
104
+ };
105
+ }
106
+ /**
107
+ * Check for critical configuration mismatches
108
+ */
109
+ static checkCriticalMismatches(localConfig, sharedConfig) {
110
+ const mismatches = [];
111
+ // Model precision - CRITICAL!
112
+ const localPrecision = localConfig.embeddingOptions?.precision || 'fp32';
113
+ if (localPrecision !== sharedConfig.precision) {
114
+ mismatches.push({
115
+ param: 'Model Precision',
116
+ local: localPrecision,
117
+ shared: sharedConfig.precision
118
+ });
119
+ }
120
+ // HNSW parameters - Important for index consistency
121
+ const localM = localConfig.hnsw?.M || 16;
122
+ if (localM !== sharedConfig.hnswM) {
123
+ mismatches.push({
124
+ param: 'HNSW M',
125
+ local: localM,
126
+ shared: sharedConfig.hnswM
127
+ });
128
+ }
129
+ const localEf = localConfig.hnsw?.efConstruction || 200;
130
+ if (localEf !== sharedConfig.hnswEfConstruction) {
131
+ mismatches.push({
132
+ param: 'HNSW efConstruction',
133
+ local: localEf,
134
+ shared: sharedConfig.hnswEfConstruction
135
+ });
136
+ }
137
+ // Distance function
138
+ const localDistance = localConfig.distanceFunction || 'cosine';
139
+ if (localDistance !== sharedConfig.distanceFunction) {
140
+ mismatches.push({
141
+ param: 'Distance Function',
142
+ local: localDistance,
143
+ shared: sharedConfig.distanceFunction
144
+ });
145
+ }
146
+ return mismatches;
147
+ }
148
+ /**
149
+ * Merge local config with shared config (shared takes precedence for critical params)
150
+ */
151
+ static mergeWithSharedConfig(localConfig, sharedConfig) {
152
+ return {
153
+ ...localConfig,
154
+ // Override critical parameters with shared values
155
+ embeddingOptions: {
156
+ ...localConfig.embeddingOptions,
157
+ precision: sharedConfig.precision // MUST use shared precision!
158
+ },
159
+ hnsw: {
160
+ ...localConfig.hnsw,
161
+ M: sharedConfig.hnswM,
162
+ efConstruction: sharedConfig.hnswEfConstruction
163
+ },
164
+ distanceFunction: sharedConfig.distanceFunction,
165
+ // Add metadata about shared configuration
166
+ _sharedConfig: {
167
+ loaded: true,
168
+ version: sharedConfig.version,
169
+ createdAt: sharedConfig.createdAt,
170
+ precision: sharedConfig.precision
171
+ }
172
+ };
173
+ }
174
+ /**
175
+ * Update access information in shared config
176
+ */
177
+ static async updateAccessInfo(storage, config) {
178
+ try {
179
+ config.lastUpdated = new Date().toISOString();
180
+ config.instanceCount = (config.instanceCount || 0) + 1;
181
+ config.lastAccessedBy = this.getInstanceIdentifier();
182
+ await this.saveConfigToStorage(storage, config);
183
+ }
184
+ catch {
185
+ // Non-critical - don't fail if we can't update access info
186
+ }
187
+ }
188
+ /**
189
+ * Get unique identifier for this instance
190
+ */
191
+ static getInstanceIdentifier() {
192
+ if (process.env.HOSTNAME)
193
+ return process.env.HOSTNAME;
194
+ if (process.env.CONTAINER_ID)
195
+ return process.env.CONTAINER_ID;
196
+ if (process.env.K_SERVICE)
197
+ return process.env.K_SERVICE;
198
+ if (process.env.AWS_LAMBDA_FUNCTION_NAME)
199
+ return process.env.AWS_LAMBDA_FUNCTION_NAME;
200
+ // Generate a random identifier
201
+ return `instance-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
202
+ }
203
+ /**
204
+ * Validate that a configuration is compatible with shared data
205
+ */
206
+ static validateCompatibility(config1, config2) {
207
+ return (config1.precision === config2.precision &&
208
+ config1.dimensions === config2.dimensions &&
209
+ config1.hnswM === config2.hnswM &&
210
+ config1.hnswEfConstruction === config2.hnswEfConstruction &&
211
+ config1.distanceFunction === config2.distanceFunction);
212
+ }
213
+ }
214
+ SharedConfigManager.CONFIG_FILE = '.brainy/config.json';
215
+ //# sourceMappingURL=sharedConfigManager.js.map
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Storage Configuration Auto-Detection
3
+ * Intelligently selects storage based on environment and available services
4
+ */
5
+ /**
6
+ * Low-level storage implementation types
7
+ */
8
+ export declare enum StorageType {
9
+ MEMORY = "memory",
10
+ FILESYSTEM = "filesystem",
11
+ OPFS = "opfs",
12
+ S3 = "s3",
13
+ GCS = "gcs",
14
+ R2 = "r2"
15
+ }
16
+ /**
17
+ * High-level storage presets (maps to StorageType)
18
+ */
19
+ export declare enum StoragePreset {
20
+ AUTO = "auto",
21
+ MEMORY = "memory",
22
+ DISK = "disk",
23
+ CLOUD = "cloud"
24
+ }
25
+ export type StorageTypeString = 'memory' | 'filesystem' | 'opfs' | 's3' | 'gcs' | 'r2';
26
+ export type StoragePresetString = 'auto' | 'memory' | 'disk' | 'cloud';
27
+ export interface StorageConfigResult {
28
+ type: StorageType | StorageTypeString;
29
+ config: any;
30
+ reason: string;
31
+ autoSelected: boolean;
32
+ }
33
+ /**
34
+ * Auto-detect the best storage configuration
35
+ * @param override - Manual override: specific type or preset
36
+ */
37
+ export declare function autoDetectStorage(override?: StorageType | StoragePreset | StorageTypeString | StoragePresetString | any): Promise<StorageConfigResult>;
38
+ /**
39
+ * Log storage configuration decision
40
+ */
41
+ export declare function logStorageConfig(config: StorageConfigResult, verbose?: boolean): void;