@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
@@ -1,121 +0,0 @@
1
- /**
2
- * BrainyChat - Magical Chat Command Center
3
- *
4
- * A smart chat system that leverages Brainy's standard noun/verb types
5
- * to create intelligent, persistent conversations with automatic context loading.
6
- *
7
- * Key Features:
8
- * - Uses standard NounType.Message for all chat messages
9
- * - Employs VerbType.Communicates and VerbType.Precedes for conversation flow
10
- * - Auto-discovery of previous sessions using Brainy's search capabilities
11
- * - Full-featured chat with memory and context management
12
- */
13
- import { BrainyData } from '../brainyData.js';
14
- export interface ChatMessage {
15
- id: string;
16
- content: string;
17
- speaker: 'user' | 'assistant' | string;
18
- sessionId: string;
19
- timestamp: Date;
20
- metadata?: {
21
- model?: string;
22
- usage?: {
23
- prompt_tokens?: number;
24
- completion_tokens?: number;
25
- };
26
- context?: Record<string, any>;
27
- };
28
- }
29
- export interface ChatSession {
30
- id: string;
31
- title?: string;
32
- createdAt: Date;
33
- lastMessageAt: Date;
34
- messageCount: number;
35
- participants: string[];
36
- metadata?: {
37
- tags?: string[];
38
- summary?: string;
39
- archived?: boolean;
40
- };
41
- }
42
- /**
43
- * BrainyChat with automatic context loading and intelligent memory
44
- *
45
- * Full-featured chat functionality with conversation persistence
46
- */
47
- export declare class BrainyChat {
48
- private brainy;
49
- private currentSessionId;
50
- private sessionCache;
51
- constructor(brainy: BrainyData);
52
- /**
53
- * Initialize chat system and auto-discover last session
54
- * Uses Brainy's advanced search to find the most recent conversation
55
- */
56
- initialize(): Promise<ChatSession | null>;
57
- /**
58
- * Start a new chat session
59
- * Automatically generates a session ID and stores session metadata
60
- */
61
- startNewSession(title?: string, participants?: string[]): Promise<ChatSession>;
62
- /**
63
- * Add a message to the current session
64
- * Stores using standard NounType.Message and creates conversation flow relationships
65
- */
66
- addMessage(content: string, speaker?: string, metadata?: ChatMessage['metadata']): Promise<ChatMessage>;
67
- /**
68
- * Ask a question and get a template-based response
69
- * This provides basic functionality without requiring an LLM
70
- */
71
- ask(question: string, options?: {
72
- includeSources?: boolean;
73
- maxSources?: number;
74
- sessionId?: string;
75
- }): Promise<string>;
76
- /**
77
- * Get conversation history for current session
78
- * Uses Brainy's graph traversal to get messages in chronological order
79
- */
80
- getHistory(limit?: number): Promise<ChatMessage[]>;
81
- /**
82
- * Search across all chat sessions and messages
83
- * Leverages Brainy's powerful vector and semantic search
84
- */
85
- searchMessages(query: string, options?: {
86
- sessionId?: string;
87
- speaker?: string;
88
- limit?: number;
89
- semanticSearch?: boolean;
90
- }): Promise<ChatMessage[]>;
91
- /**
92
- * Get all chat sessions
93
- * Uses Brainy's search to find all conversation sessions
94
- */
95
- getSessions(limit?: number): Promise<ChatSession[]>;
96
- /**
97
- * Switch to a different session
98
- * Automatically loads context and history
99
- */
100
- switchToSession(sessionId: string): Promise<ChatSession | null>;
101
- /**
102
- * Archive a session
103
- * Maintains full searchability while organizing conversations
104
- */
105
- archiveSession(sessionId: string): Promise<boolean>;
106
- /**
107
- * Generate session summary
108
- * Creates a simple summary of the conversation
109
- * For AI summaries, users can integrate their own LLM
110
- */
111
- generateSessionSummary(sessionId: string): Promise<string | null>;
112
- private createMessageRelationships;
113
- private loadSession;
114
- private getHistoryForSession;
115
- private updateSessionMetadata;
116
- private nounToChatMessage;
117
- private nounToChatSession;
118
- private toTimestamp;
119
- getCurrentSessionId(): string | null;
120
- getCurrentSession(): ChatSession | null;
121
- }
@@ -1,396 +0,0 @@
1
- /**
2
- * BrainyChat - Magical Chat Command Center
3
- *
4
- * A smart chat system that leverages Brainy's standard noun/verb types
5
- * to create intelligent, persistent conversations with automatic context loading.
6
- *
7
- * Key Features:
8
- * - Uses standard NounType.Message for all chat messages
9
- * - Employs VerbType.Communicates and VerbType.Precedes for conversation flow
10
- * - Auto-discovery of previous sessions using Brainy's search capabilities
11
- * - Full-featured chat with memory and context management
12
- */
13
- import { NounType, VerbType } from '../types/graphTypes.js';
14
- /**
15
- * BrainyChat with automatic context loading and intelligent memory
16
- *
17
- * Full-featured chat functionality with conversation persistence
18
- */
19
- export class BrainyChat {
20
- constructor(brainy) {
21
- this.currentSessionId = null;
22
- this.sessionCache = new Map();
23
- this.brainy = brainy;
24
- }
25
- /**
26
- * Initialize chat system and auto-discover last session
27
- * Uses Brainy's advanced search to find the most recent conversation
28
- */
29
- async initialize() {
30
- try {
31
- // Search for the most recent chat message using Brainy's search
32
- const recentMessages = await this.brainy.search('recent chat conversation', {
33
- limit: 1,
34
- nounTypes: [NounType.Message],
35
- metadata: {
36
- messageType: 'chat'
37
- }
38
- });
39
- if (recentMessages.length > 0) {
40
- const lastMessage = recentMessages[0];
41
- const sessionId = lastMessage.metadata?.sessionId;
42
- if (sessionId) {
43
- this.currentSessionId = sessionId;
44
- return await this.loadSession(sessionId);
45
- }
46
- }
47
- }
48
- catch (error) {
49
- console.debug('No previous session found, starting fresh:', error?.message);
50
- }
51
- return null;
52
- }
53
- /**
54
- * Start a new chat session
55
- * Automatically generates a session ID and stores session metadata
56
- */
57
- async startNewSession(title, participants = ['user', 'assistant']) {
58
- const sessionId = `chat-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
59
- const session = {
60
- id: sessionId,
61
- title,
62
- createdAt: new Date(),
63
- lastMessageAt: new Date(),
64
- messageCount: 0,
65
- participants,
66
- metadata: {
67
- tags: ['active']
68
- }
69
- };
70
- // Store session using BrainyData add() method
71
- await this.brainy.add({
72
- sessionType: 'chat',
73
- title: title || `Chat Session ${new Date().toLocaleDateString()}`,
74
- createdAt: session.createdAt.toISOString(),
75
- lastMessageAt: session.lastMessageAt.toISOString(),
76
- messageCount: session.messageCount,
77
- participants: session.participants
78
- }, {
79
- id: sessionId,
80
- nounType: NounType.Concept,
81
- sessionType: 'chat'
82
- });
83
- this.currentSessionId = sessionId;
84
- this.sessionCache.set(sessionId, session);
85
- return session;
86
- }
87
- /**
88
- * Add a message to the current session
89
- * Stores using standard NounType.Message and creates conversation flow relationships
90
- */
91
- async addMessage(content, speaker = 'user', metadata) {
92
- if (!this.currentSessionId) {
93
- await this.startNewSession();
94
- }
95
- const messageId = `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
96
- const timestamp = new Date();
97
- const message = {
98
- id: messageId,
99
- content,
100
- speaker,
101
- sessionId: this.currentSessionId,
102
- timestamp,
103
- metadata
104
- };
105
- // Store message using BrainyData add() method
106
- await this.brainy.add({
107
- messageType: 'chat',
108
- content,
109
- speaker,
110
- sessionId: this.currentSessionId,
111
- timestamp: timestamp.toISOString(),
112
- ...metadata
113
- }, {
114
- id: messageId,
115
- nounType: NounType.Message,
116
- messageType: 'chat',
117
- sessionId: this.currentSessionId,
118
- speaker
119
- });
120
- // Create relationships using standard verb types
121
- await this.createMessageRelationships(messageId);
122
- // Update session metadata
123
- await this.updateSessionMetadata();
124
- return message;
125
- }
126
- /**
127
- * Ask a question and get a template-based response
128
- * This provides basic functionality without requiring an LLM
129
- */
130
- async ask(question, options) {
131
- // Add the user's question to the chat
132
- await this.addMessage(question, 'user');
133
- // Search for relevant content using Brainy's search
134
- const searchResults = await this.brainy.search(question, {
135
- limit: options?.maxSources || 5
136
- });
137
- // Generate a template-based response
138
- let response = '';
139
- if (searchResults.length === 0) {
140
- response = "I don't have enough information to answer that question based on the current data.";
141
- }
142
- else {
143
- // Check if this is a count question
144
- if (question.toLowerCase().includes('how many') || question.toLowerCase().includes('count')) {
145
- response = `Based on the search results, I found ${searchResults.length} relevant items.`;
146
- }
147
- // Check if this is a list question
148
- else if (question.toLowerCase().includes('list') || question.toLowerCase().includes('show me')) {
149
- response = `Here are the relevant items I found:\n${searchResults.map((r, i) => `${i + 1}. ${r.metadata?.title || r.metadata?.content || r.id}`).join('\n')}`;
150
- }
151
- // General question
152
- else {
153
- response = `Based on the available data, I found information related to your question. The most relevant content includes: ${searchResults[0].metadata?.title || searchResults[0].metadata?.content || searchResults[0].id}`;
154
- }
155
- // Add sources if requested
156
- if (options?.includeSources && searchResults.length > 0) {
157
- response += '\n\nSources: ' + searchResults.map(r => r.id).join(', ');
158
- }
159
- }
160
- // Add the assistant's response to the chat
161
- await this.addMessage(response, 'assistant');
162
- return response;
163
- }
164
- /**
165
- * Get conversation history for current session
166
- * Uses Brainy's graph traversal to get messages in chronological order
167
- */
168
- async getHistory(limit = 50) {
169
- if (!this.currentSessionId)
170
- return [];
171
- try {
172
- // Search for messages in this session using Brainy's search
173
- const messageNouns = await this.brainy.search('', // Empty query to get all messages
174
- {
175
- limit: limit,
176
- nounTypes: [NounType.Message],
177
- metadata: {
178
- sessionId: this.currentSessionId,
179
- messageType: 'chat'
180
- }
181
- });
182
- return messageNouns.map((noun) => this.nounToChatMessage(noun));
183
- }
184
- catch (error) {
185
- console.error('Error retrieving chat history:', error);
186
- return [];
187
- }
188
- }
189
- /**
190
- * Search across all chat sessions and messages
191
- * Leverages Brainy's powerful vector and semantic search
192
- */
193
- async searchMessages(query, options) {
194
- const metadata = {
195
- messageType: 'chat'
196
- };
197
- if (options?.sessionId) {
198
- metadata.sessionId = options.sessionId;
199
- }
200
- if (options?.speaker) {
201
- metadata.speaker = options.speaker;
202
- }
203
- try {
204
- const results = await this.brainy.search(options?.semanticSearch !== false ? query : '', {
205
- limit: options?.limit || 20,
206
- nounTypes: [NounType.Message],
207
- metadata
208
- });
209
- return results.map((noun) => this.nounToChatMessage(noun));
210
- }
211
- catch (error) {
212
- console.error('Error searching messages:', error);
213
- return [];
214
- }
215
- }
216
- /**
217
- * Get all chat sessions
218
- * Uses Brainy's search to find all conversation sessions
219
- */
220
- async getSessions(limit = 20) {
221
- try {
222
- const sessionNouns = await this.brainy.search('', {
223
- limit: limit,
224
- nounTypes: [NounType.Concept],
225
- metadata: {
226
- sessionType: 'chat'
227
- }
228
- });
229
- return sessionNouns.map((noun) => this.nounToChatSession(noun));
230
- }
231
- catch (error) {
232
- console.error('Error retrieving sessions:', error);
233
- return [];
234
- }
235
- }
236
- /**
237
- * Switch to a different session
238
- * Automatically loads context and history
239
- */
240
- async switchToSession(sessionId) {
241
- try {
242
- const session = await this.loadSession(sessionId);
243
- if (session) {
244
- this.currentSessionId = sessionId;
245
- this.sessionCache.set(sessionId, session);
246
- }
247
- return session;
248
- }
249
- catch (error) {
250
- console.error('Error switching to session:', error);
251
- return null;
252
- }
253
- }
254
- /**
255
- * Archive a session
256
- * Maintains full searchability while organizing conversations
257
- */
258
- async archiveSession(sessionId) {
259
- try {
260
- // Since BrainyData doesn't have update, add an archive marker
261
- await this.brainy.add({
262
- archivedSessionId: sessionId,
263
- archivedAt: new Date().toISOString(),
264
- action: 'archive'
265
- }, {
266
- nounType: NounType.State,
267
- sessionId,
268
- archived: true
269
- });
270
- return true;
271
- }
272
- catch (error) {
273
- console.error('Error archiving session:', error);
274
- }
275
- return false;
276
- }
277
- /**
278
- * Generate session summary
279
- * Creates a simple summary of the conversation
280
- * For AI summaries, users can integrate their own LLM
281
- */
282
- async generateSessionSummary(sessionId) {
283
- try {
284
- const messages = await this.getHistoryForSession(sessionId, 100);
285
- const content = messages
286
- .map(msg => `${msg.speaker}: ${msg.content}`)
287
- .join('\n');
288
- // Use Brainy's AI to generate summary (placeholder - would need actual AI integration)
289
- const summaryResponse = `Summary of ${messages.length} messages discussing various topics in ${sessionId}`;
290
- return summaryResponse || null;
291
- }
292
- catch (error) {
293
- console.error('Error generating session summary:', error);
294
- return null;
295
- }
296
- }
297
- // Private helper methods
298
- async createMessageRelationships(messageId) {
299
- // Link message to session using unified addVerb API
300
- await this.brainy.addVerb(messageId, this.currentSessionId, VerbType.PartOf, {
301
- relationship: 'message-in-session'
302
- });
303
- // Find previous message to create conversation flow using VerbType.Precedes
304
- const previousMessages = await this.brainy.search('', {
305
- limit: 1,
306
- nounTypes: [NounType.Message],
307
- metadata: {
308
- sessionId: this.currentSessionId,
309
- messageType: 'chat'
310
- }
311
- });
312
- if (previousMessages.length > 0 && previousMessages[0].id !== messageId) {
313
- await this.brainy.addVerb(previousMessages[0].id, messageId, VerbType.Precedes, {
314
- relationship: 'message-sequence'
315
- });
316
- }
317
- }
318
- async loadSession(sessionId) {
319
- try {
320
- const sessionNouns = await this.brainy.search('', {
321
- limit: 1,
322
- nounTypes: [NounType.Concept],
323
- metadata: {
324
- sessionType: 'chat'
325
- }
326
- });
327
- // Filter by session ID manually since BrainyData search may not support ID filtering
328
- const matchingSession = sessionNouns.find(noun => noun.id === sessionId);
329
- if (matchingSession) {
330
- return this.nounToChatSession(matchingSession);
331
- }
332
- }
333
- catch (error) {
334
- console.error('Error loading session:', error);
335
- }
336
- return null;
337
- }
338
- async getHistoryForSession(sessionId, limit = 50) {
339
- try {
340
- const messageNouns = await this.brainy.search('', {
341
- limit: limit,
342
- nounTypes: [NounType.Message],
343
- metadata: {
344
- sessionId: sessionId,
345
- messageType: 'chat'
346
- }
347
- });
348
- return messageNouns.map((noun) => this.nounToChatMessage(noun));
349
- }
350
- catch (error) {
351
- console.error('Error retrieving session history:', error);
352
- return [];
353
- }
354
- }
355
- async updateSessionMetadata() {
356
- if (!this.currentSessionId)
357
- return;
358
- // Since BrainyData doesn't have update functionality, we'll skip this
359
- // In a real implementation, you'd need update capabilities
360
- console.debug('Session metadata update skipped - BrainyData lacks update API');
361
- }
362
- nounToChatMessage(noun) {
363
- return {
364
- id: noun.id,
365
- content: noun.metadata?.content || noun.data?.content || '',
366
- speaker: noun.metadata?.speaker || noun.data?.speaker || 'unknown',
367
- sessionId: noun.metadata?.sessionId || noun.data?.sessionId || '',
368
- timestamp: new Date(noun.metadata?.timestamp || noun.data?.timestamp || Date.now()),
369
- metadata: noun.metadata
370
- };
371
- }
372
- nounToChatSession(noun) {
373
- return {
374
- id: noun.id,
375
- title: noun.metadata?.title || noun.data?.title || 'Untitled Session',
376
- createdAt: new Date(noun.metadata?.createdAt || noun.data?.createdAt || Date.now()),
377
- lastMessageAt: new Date(noun.metadata?.lastMessageAt || noun.data?.lastMessageAt || Date.now()),
378
- messageCount: noun.metadata?.messageCount || noun.data?.messageCount || 0,
379
- participants: noun.metadata?.participants || noun.data?.participants || ['user', 'assistant'],
380
- metadata: noun.metadata
381
- };
382
- }
383
- toTimestamp(date) {
384
- const seconds = Math.floor(date.getTime() / 1000);
385
- const nanoseconds = (date.getTime() % 1000) * 1000000;
386
- return { seconds, nanoseconds };
387
- }
388
- // Public API methods for CLI integration
389
- getCurrentSessionId() {
390
- return this.currentSessionId;
391
- }
392
- getCurrentSession() {
393
- return this.currentSessionId ? this.sessionCache.get(this.currentSessionId) || null : null;
394
- }
395
- }
396
- //# sourceMappingURL=BrainyChat.js.map
@@ -1,61 +0,0 @@
1
- /**
2
- * ChatCLI - Command Line Interface for BrainyChat
3
- *
4
- * Provides a magical chat experience through the Brainy CLI with:
5
- * - Auto-discovery of previous sessions
6
- * - Intelligent context loading
7
- * - Multi-agent coordination support
8
- * - Full conversation history and context
9
- */
10
- import { type ChatMessage } from './BrainyChat.js';
11
- import { BrainyData } from '../brainyData.js';
12
- export declare class ChatCLI {
13
- private brainyChat;
14
- private brainy;
15
- constructor(brainy: BrainyData);
16
- /**
17
- * Start an interactive chat session
18
- * Automatically discovers and loads previous context
19
- */
20
- startInteractiveChat(options?: {
21
- sessionId?: string;
22
- speaker?: string;
23
- memory?: boolean;
24
- newSession?: boolean;
25
- }): Promise<void>;
26
- /**
27
- * Send a single message and get response
28
- */
29
- sendMessage(message: string, options?: {
30
- sessionId?: string;
31
- speaker?: string;
32
- noResponse?: boolean;
33
- }): Promise<ChatMessage[]>;
34
- /**
35
- * Show conversation history
36
- */
37
- showHistory(limit?: number): Promise<void>;
38
- /**
39
- * Search across all conversations
40
- */
41
- searchConversations(query: string, options?: {
42
- limit?: number;
43
- sessionId?: string;
44
- semantic?: boolean;
45
- }): Promise<void>;
46
- /**
47
- * List all chat sessions
48
- */
49
- listSessions(): Promise<void>;
50
- /**
51
- * Switch to a different session
52
- */
53
- switchSession(sessionId: string): Promise<void>;
54
- /**
55
- * Show help for chat commands
56
- */
57
- showHelp(): void;
58
- private interactiveLoop;
59
- private showRecentContext;
60
- private generateResponse;
61
- }