@burtson-labs/bandit-engine 2.0.161 → 2.0.163

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 (213) hide show
  1. package/README.md +7 -22
  2. package/dist/aiProviderStore-PEGSX4PK.mjs +9 -0
  3. package/dist/chat-MRDQ2WRJ.mjs +16 -0
  4. package/dist/chat-provider.js +86 -31
  5. package/dist/chat-provider.js.map +1 -1
  6. package/dist/chat-provider.mjs +7 -7
  7. package/dist/{chunk-QXITTH2X.mjs → chunk-5KBTOCQZ.mjs} +4 -4
  8. package/dist/chunk-5KBTOCQZ.mjs.map +1 -0
  9. package/dist/{chunk-B3HAQC6F.mjs → chunk-CQJGUYRW.mjs} +69 -26
  10. package/dist/chunk-CQJGUYRW.mjs.map +1 -0
  11. package/dist/{chunk-TTAORNWI.mjs → chunk-F32P7Q5O.mjs} +122 -232
  12. package/dist/chunk-F32P7Q5O.mjs.map +1 -0
  13. package/dist/{chunk-XC7HDKFW.mjs → chunk-HSGQXL4N.mjs} +11 -11
  14. package/dist/chunk-HSGQXL4N.mjs.map +1 -0
  15. package/dist/{chunk-QPXG4A5C.mjs → chunk-IZX2J65Q.mjs} +2 -2
  16. package/dist/chunk-IZX2J65Q.mjs.map +1 -0
  17. package/dist/{chunk-MIDYEQOS.mjs → chunk-J6SWNO7Z.mjs} +20 -35
  18. package/dist/chunk-J6SWNO7Z.mjs.map +1 -0
  19. package/dist/{chunk-PFKKGJAQ.mjs → chunk-O6P37PFR.mjs} +4 -4
  20. package/dist/chunk-O6P37PFR.mjs.map +1 -0
  21. package/dist/{chunk-KCI46M23.mjs → chunk-OCVZVBQQ.mjs} +1 -1
  22. package/dist/chunk-OCVZVBQQ.mjs.map +1 -0
  23. package/dist/{chunk-IXIM7BNO.mjs → chunk-P4C5IRM5.mjs} +1 -1
  24. package/dist/chunk-P4C5IRM5.mjs.map +1 -0
  25. package/dist/{chunk-WQEBTH2R.mjs → chunk-TY5VL3SG.mjs} +3 -3
  26. package/dist/chunk-TY5VL3SG.mjs.map +1 -0
  27. package/dist/{chunk-X65A3NED.mjs → chunk-URZSIL7X.mjs} +7 -7
  28. package/dist/chunk-URZSIL7X.mjs.map +1 -0
  29. package/dist/{chunk-FSRMNQRN.mjs → chunk-VBHI4TJC.mjs} +6 -6
  30. package/dist/chunk-VBHI4TJC.mjs.map +1 -0
  31. package/dist/{chunk-EOMOOMUC.mjs → chunk-WLNZL6SP.mjs} +5 -16
  32. package/dist/chunk-WLNZL6SP.mjs.map +1 -0
  33. package/dist/index.d.mts +6 -0
  34. package/dist/index.d.ts +6 -0
  35. package/dist/index.js +660 -759
  36. package/dist/index.js.map +1 -1
  37. package/dist/index.mjs +15 -31
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/management/management.js +300 -383
  40. package/dist/management/management.js.map +1 -1
  41. package/dist/management/management.mjs +10 -10
  42. package/dist/{memoryUtils-33TZKHSQ.mjs → memoryUtils-2FVXDSS6.mjs} +1 -1
  43. package/dist/memoryUtils-2FVXDSS6.mjs.map +1 -0
  44. package/dist/modals/chat-modal/chat-modal.js +86 -31
  45. package/dist/modals/chat-modal/chat-modal.js.map +1 -1
  46. package/dist/modals/chat-modal/chat-modal.mjs +6 -6
  47. package/dist/modelStore-7XYYDCNC.mjs +9 -0
  48. package/dist/shared/custom-element.js.map +1 -1
  49. package/dist/shared/custom-element.mjs +1 -1
  50. package/docs/05_contributing.md +1 -1
  51. package/docs/api_reference/assets/navigation.js +1 -1
  52. package/docs/api_reference/assets/search.js +1 -1
  53. package/docs/api_reference/classes/DebugLogger.html +11 -11
  54. package/docs/api_reference/classes/FeatureFlagService.html +13 -13
  55. package/docs/api_reference/classes/NotificationService.html +10 -10
  56. package/docs/api_reference/classes/StreamingTTSClient.html +9 -9
  57. package/docs/api_reference/classes/VectorDatabaseService.html +24 -24
  58. package/docs/api_reference/classes/VectorMigrationService.html +8 -8
  59. package/docs/api_reference/classes/VoiceService.html +2 -2
  60. package/docs/api_reference/enums/TTSState.html +2 -2
  61. package/docs/api_reference/functions/Chat.html +1 -1
  62. package/docs/api_reference/functions/ChatModal.html +1 -1
  63. package/docs/api_reference/functions/ChatProvider.html +1 -1
  64. package/docs/api_reference/functions/FeatureFlagProvider.html +1 -1
  65. package/docs/api_reference/functions/FeedbackButton.html +1 -1
  66. package/docs/api_reference/functions/FeedbackModal.html +1 -1
  67. package/docs/api_reference/functions/InterestsEditor.html +5 -0
  68. package/docs/api_reference/functions/Management.html +1 -1
  69. package/docs/api_reference/functions/NotificationProvider.html +1 -1
  70. package/docs/api_reference/functions/SubscriptionExpiredGuard.html +1 -1
  71. package/docs/api_reference/functions/SubscriptionExpiredModal.html +1 -1
  72. package/docs/api_reference/functions/defineCustomElement.html +1 -1
  73. package/docs/api_reference/functions/getCriticalConfig.html +2 -1
  74. package/docs/api_reference/functions/getFeatureMatrix.html +1 -1
  75. package/docs/api_reference/functions/getStreamingTTSClient.html +1 -1
  76. package/docs/api_reference/functions/getSystemConstants.html +2 -1
  77. package/docs/api_reference/functions/getTTSState.html +1 -1
  78. package/docs/api_reference/functions/handleHttpError.html +1 -1
  79. package/docs/api_reference/functions/handleSubscriptionUpgrade.html +1 -1
  80. package/docs/api_reference/functions/handleValidationError.html +1 -1
  81. package/docs/api_reference/functions/initializeCoreSystem.html +2 -1
  82. package/docs/api_reference/functions/isWorkspaceAdminRole.html +6 -0
  83. package/docs/api_reference/functions/pauseTTS.html +1 -1
  84. package/docs/api_reference/functions/previewTierUpgrade.html +1 -1
  85. package/docs/api_reference/functions/resolveManagementSections.html +2 -0
  86. package/docs/api_reference/functions/resumeTTS.html +1 -1
  87. package/docs/api_reference/functions/showInfoNotification.html +1 -1
  88. package/docs/api_reference/functions/showSuccessNotification.html +1 -1
  89. package/docs/api_reference/functions/speakWithStreaming.html +1 -1
  90. package/docs/api_reference/functions/stopTTS.html +1 -1
  91. package/docs/api_reference/functions/syncSubscriptionWithAPI.html +1 -1
  92. package/docs/api_reference/functions/updateSubscriptionTier.html +1 -1
  93. package/docs/api_reference/functions/useFeatureFlag.html +1 -1
  94. package/docs/api_reference/functions/useFeatureVisibility.html +1 -1
  95. package/docs/api_reference/functions/useFeatures.html +1 -1
  96. package/docs/api_reference/functions/useGatewayHealth.html +1 -1
  97. package/docs/api_reference/functions/useGatewayMemory.html +1 -1
  98. package/docs/api_reference/functions/useGatewayModels.html +1 -1
  99. package/docs/api_reference/functions/useGlobalTTS.html +1 -1
  100. package/docs/api_reference/functions/useManagementAccess.html +2 -0
  101. package/docs/api_reference/functions/useNotification.html +1 -1
  102. package/docs/api_reference/functions/useNotificationService.html +1 -1
  103. package/docs/api_reference/functions/useTTS.html +1 -1
  104. package/docs/api_reference/functions/useVectorStore.html +1 -1
  105. package/docs/api_reference/functions/useVoiceStore.html +2 -2
  106. package/docs/api_reference/functions/useVoices.html +1 -1
  107. package/docs/api_reference/functions/validateEnvironment.html +2 -1
  108. package/docs/api_reference/functions/validateSystemIntegrity.html +2 -1
  109. package/docs/api_reference/index.html +219 -155
  110. package/docs/api_reference/interfaces/AIChatRequest.html +2 -2
  111. package/docs/api_reference/interfaces/AIChatResponse.html +2 -2
  112. package/docs/api_reference/interfaces/AIGenerateRequest.html +2 -2
  113. package/docs/api_reference/interfaces/AIGenerateResponse.html +2 -2
  114. package/docs/api_reference/interfaces/AIMessage.html +2 -2
  115. package/docs/api_reference/interfaces/AIModel.html +2 -2
  116. package/docs/api_reference/interfaces/AIProviderConfig.html +5 -2
  117. package/docs/api_reference/interfaces/ChatConfig.html +3 -3
  118. package/docs/api_reference/interfaces/ChatModalProps.html +3 -3
  119. package/docs/api_reference/interfaces/CreateMemoryOptions.html +2 -2
  120. package/docs/api_reference/interfaces/FeatureEvaluation.html +7 -7
  121. package/docs/api_reference/interfaces/FeatureFlagConfig.html +9 -9
  122. package/docs/api_reference/interfaces/FeatureFlagContextValue.html +8 -8
  123. package/docs/api_reference/interfaces/FeatureFlagProviderProps.html +2 -2
  124. package/docs/api_reference/interfaces/FeedbackButtonProps.html +10 -10
  125. package/docs/api_reference/interfaces/FeedbackCategories.html +2 -2
  126. package/docs/api_reference/interfaces/FeedbackModalProps.html +2 -2
  127. package/docs/api_reference/interfaces/FeedbackPriorities.html +2 -2
  128. package/docs/api_reference/interfaces/FeedbackRequest.html +2 -2
  129. package/docs/api_reference/interfaces/FeedbackResponse.html +2 -2
  130. package/docs/api_reference/interfaces/FileUploadResult.html +2 -2
  131. package/docs/api_reference/interfaces/GatewayChatRequest.html +3 -2
  132. package/docs/api_reference/interfaces/GatewayChatResponse.html +2 -2
  133. package/docs/api_reference/interfaces/GatewayContract.html +2 -2
  134. package/docs/api_reference/interfaces/GatewayGenerateRequest.html +2 -2
  135. package/docs/api_reference/interfaces/GatewayGenerateResponse.html +2 -2
  136. package/docs/api_reference/interfaces/GatewayHealthResponse.html +2 -2
  137. package/docs/api_reference/interfaces/GatewayMemoryRecord.html +2 -2
  138. package/docs/api_reference/interfaces/GatewayMemoryResponse.html +2 -2
  139. package/docs/api_reference/interfaces/GatewayMessage.html +2 -2
  140. package/docs/api_reference/interfaces/GatewayMessageContent.html +2 -2
  141. package/docs/api_reference/interfaces/GatewayModel.html +2 -2
  142. package/docs/api_reference/interfaces/GatewayModelsResponse.html +2 -2
  143. package/docs/api_reference/interfaces/ManagementAccess.html +5 -0
  144. package/docs/api_reference/interfaces/ManagementAccessInput.html +5 -0
  145. package/docs/api_reference/interfaces/ManagementLink.html +7 -0
  146. package/docs/api_reference/interfaces/ManagementProps.html +22 -0
  147. package/docs/api_reference/interfaces/ManagementSectionDef.html +10 -0
  148. package/docs/api_reference/interfaces/MemorySearchFilters.html +2 -2
  149. package/docs/api_reference/interfaces/MigrationProgress.html +2 -2
  150. package/docs/api_reference/interfaces/MigrationStatus.html +2 -2
  151. package/docs/api_reference/interfaces/NotificationConfig.html +2 -2
  152. package/docs/api_reference/interfaces/NotificationContextType.html +2 -2
  153. package/docs/api_reference/interfaces/NotificationProviderProps.html +2 -2
  154. package/docs/api_reference/interfaces/PackageSettings.html +11 -2
  155. package/docs/api_reference/interfaces/SearchOptions.html +2 -2
  156. package/docs/api_reference/interfaces/SearchResult.html +2 -2
  157. package/docs/api_reference/interfaces/SubscriptionExpiredGuardProps.html +2 -2
  158. package/docs/api_reference/interfaces/SubscriptionExpiredModalProps.html +2 -2
  159. package/docs/api_reference/interfaces/TTSOptions.html +2 -2
  160. package/docs/api_reference/interfaces/TTSProgress.html +2 -2
  161. package/docs/api_reference/interfaces/TrialUsage.html +2 -2
  162. package/docs/api_reference/interfaces/UploadRequest.html +3 -3
  163. package/docs/api_reference/interfaces/UseTTSReturn.html +2 -2
  164. package/docs/api_reference/interfaces/VectorDocument.html +2 -2
  165. package/docs/api_reference/interfaces/VectorMemory.html +2 -2
  166. package/docs/api_reference/interfaces/VectorMemoryMetadata.html +2 -2
  167. package/docs/api_reference/interfaces/VectorStoreStatus.html +2 -2
  168. package/docs/api_reference/interfaces/VoiceModelsResponse.html +2 -2
  169. package/docs/api_reference/interfaces/VoiceState.html +2 -2
  170. package/docs/api_reference/media/PROTECTION-NOTICE.md +6 -55
  171. package/docs/api_reference/media/README.md +20 -1
  172. package/docs/api_reference/modules.html +18 -6
  173. package/docs/api_reference/types/FeatureKey.html +1 -1
  174. package/docs/api_reference/types/FeatureMatrix.html +1 -1
  175. package/docs/api_reference/types/GatewayQueryOptions.html +1 -1
  176. package/docs/api_reference/types/LogContext.html +1 -1
  177. package/docs/api_reference/types/ManagementRequest.html +1 -0
  178. package/docs/api_reference/types/ManagementSectionId.html +2 -0
  179. package/docs/api_reference/types/SubscriptionTier.html +1 -1
  180. package/docs/api_reference/variables/DEFAULT_TIER_FEATURES.html +1 -1
  181. package/docs/api_reference/variables/FeatureFlagContext.html +1 -1
  182. package/docs/api_reference/variables/MANAGEMENT_SECTIONS.html +1 -0
  183. package/docs/api_reference/variables/OSS_DEFAULT_FEATURES.html +1 -1
  184. package/docs/api_reference/variables/SYSTEM_FLAGS.html +2 -1
  185. package/docs/api_reference/variables/authenticationService.html +1 -1
  186. package/docs/api_reference/variables/debugLogger-1.html +1 -1
  187. package/docs/api_reference/variables/featureFlagService-1.html +1 -1
  188. package/docs/api_reference/variables/notificationService-1.html +1 -1
  189. package/docs/api_reference/variables/vectorDatabaseService-1.html +1 -1
  190. package/docs/api_reference/variables/vectorMigrationService-1.html +1 -1
  191. package/docs/api_reference/variables/voiceService-1.html +1 -1
  192. package/package.json +1 -1
  193. package/dist/aiProviderStore-BNZGM6QU.mjs +0 -9
  194. package/dist/chat-3JAV77HO.mjs +0 -16
  195. package/dist/chunk-B3HAQC6F.mjs.map +0 -1
  196. package/dist/chunk-EOMOOMUC.mjs.map +0 -1
  197. package/dist/chunk-FSRMNQRN.mjs.map +0 -1
  198. package/dist/chunk-IXIM7BNO.mjs.map +0 -1
  199. package/dist/chunk-KCI46M23.mjs.map +0 -1
  200. package/dist/chunk-MIDYEQOS.mjs.map +0 -1
  201. package/dist/chunk-PFKKGJAQ.mjs.map +0 -1
  202. package/dist/chunk-QPXG4A5C.mjs.map +0 -1
  203. package/dist/chunk-QXITTH2X.mjs.map +0 -1
  204. package/dist/chunk-TTAORNWI.mjs.map +0 -1
  205. package/dist/chunk-WQEBTH2R.mjs.map +0 -1
  206. package/dist/chunk-X65A3NED.mjs.map +0 -1
  207. package/dist/chunk-XC7HDKFW.mjs.map +0 -1
  208. package/dist/memoryUtils-33TZKHSQ.mjs.map +0 -1
  209. package/dist/modelStore-FGUGOWTL.mjs +0 -9
  210. package/docs/api_reference/media/PROTECTION-README.md +0 -39
  211. /package/dist/{aiProviderStore-BNZGM6QU.mjs.map → aiProviderStore-PEGSX4PK.mjs.map} +0 -0
  212. /package/dist/{chat-3JAV77HO.mjs.map → chat-MRDQ2WRJ.mjs.map} +0 -0
  213. /package/dist/{modelStore-FGUGOWTL.mjs.map → modelStore-7XYYDCNC.mjs.map} +0 -0
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  ChatProvider,
3
3
  chat_provider_default
4
- } from "./chunk-X65A3NED.mjs";
4
+ } from "./chunk-URZSIL7X.mjs";
5
5
  import "./chunk-ONQMRE2G.mjs";
6
- import "./chunk-QXITTH2X.mjs";
7
- import "./chunk-PFKKGJAQ.mjs";
8
- import "./chunk-MIDYEQOS.mjs";
9
- import "./chunk-WQEBTH2R.mjs";
10
- import "./chunk-B3HAQC6F.mjs";
11
- import "./chunk-KCI46M23.mjs";
6
+ import "./chunk-5KBTOCQZ.mjs";
7
+ import "./chunk-O6P37PFR.mjs";
8
+ import "./chunk-J6SWNO7Z.mjs";
9
+ import "./chunk-TY5VL3SG.mjs";
10
+ import "./chunk-CQJGUYRW.mjs";
11
+ import "./chunk-OCVZVBQQ.mjs";
12
12
  import "./chunk-BJTO5JO5.mjs";
13
13
  export {
14
14
  ChatProvider,
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  indexedDBService_default,
3
3
  usePackageSettingsStore
4
- } from "./chunk-WQEBTH2R.mjs";
4
+ } from "./chunk-TY5VL3SG.mjs";
5
5
  import {
6
6
  authenticationService,
7
7
  useAIProviderStore
8
- } from "./chunk-B3HAQC6F.mjs";
8
+ } from "./chunk-CQJGUYRW.mjs";
9
9
  import {
10
10
  debugLogger
11
- } from "./chunk-KCI46M23.mjs";
11
+ } from "./chunk-OCVZVBQQ.mjs";
12
12
  import {
13
13
  __require
14
14
  } from "./chunk-BJTO5JO5.mjs";
@@ -285,4 +285,4 @@ var aiProviderInitService = AIProviderInitService.getInstance();
285
285
  export {
286
286
  aiProviderInitService
287
287
  };
288
- //# sourceMappingURL=chunk-QXITTH2X.mjs.map
288
+ //# sourceMappingURL=chunk-5KBTOCQZ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/services/ai-provider-init.service.ts"],"sourcesContent":["/*\n * Copyright (c) 2025 Burtson Labs LLC.\n * SPDX-License-Identifier: BUSL-1.1\n * See LICENSE for the applicable terms.\n */\n\n\nimport { useAIProviderStore } from \"../store/aiProviderStore\";\nimport { usePackageSettingsStore } from \"../store/packageSettingsStore\";\nimport { AIProviderConfig, AIProviderType } from \"./ai-provider/types/common.types\";\nimport { authenticationService } from \"./auth/authenticationService\";\nimport { debugLogger } from \"./logging/debugLogger\";\nimport indexedDBService from \"./indexedDB/indexedDBService\";\n\ntype StoredAIProviderConfig = AIProviderConfig & { id?: string };\n\n/**\n * Service to initialize AI providers based on package settings\n */\nexport class AIProviderInitService {\n private static instance: AIProviderInitService;\n\n private constructor() {}\n\n static getInstance(): AIProviderInitService {\n if (!AIProviderInitService.instance) {\n AIProviderInitService.instance = new AIProviderInitService();\n }\n return AIProviderInitService.instance;\n }\n\n /**\n * Initialize AI provider from package settings\n * Provides backward compatibility with existing Ollama settings\n */\n async initializeFromSettings(): Promise<void> {\n const settings = usePackageSettingsStore.getState().settings;\n if (!settings) {\n debugLogger.warn(\"No package settings found, cannot initialize AI provider\");\n return;\n }\n\n let providerConfig: AIProviderConfig;\n\n debugLogger.info(\"AI Provider Init: Starting initialization\", { \n hasSettings: !!settings,\n hasAiProvider: !!settings.aiProvider,\n ollamaUrl: settings.ollamaUrl\n });\n\n const isPlaygroundEnvironment =\n settings.playgroundMode === true ||\n settings.aiProvider?.type === AIProviderType.PLAYGROUND ||\n (settings.gatewayApiUrl?.toLowerCase()?.startsWith(\"playground://\") ?? false) ||\n (typeof window !== \"undefined\" && window.location.pathname.includes(\"/playground\"));\n\n // First, try to load provider configuration from IndexedDB\n if (isPlaygroundEnvironment) {\n debugLogger.info(\"AI Provider Init: Playground environment detected, bypassing saved provider config\");\n } else {\n try {\n const savedConfig = await indexedDBService.get<StoredAIProviderConfig>(\n 'banditConfig', \n 1, \n 'config', \n 'aiProvider',\n [{ name: 'config', keyPath: 'id' }]\n );\n \n if (savedConfig) {\n debugLogger.info('AI Provider Init: Found saved config in IndexedDB', { type: savedConfig.type });\n \n // Filter out the 'id' property that was added for IndexedDB storage\n const { id: _id, ...configWithoutId } = savedConfig;\n providerConfig = { ...configWithoutId };\n if (providerConfig.type === AIProviderType.ANTHROPIC) {\n providerConfig = this.convertAnthropicConfig(providerConfig, settings?.gatewayApiUrl);\n }\n\n // Ensure tokenFactory is present for providers that need it\n providerConfig = this.ensureTokenFactory(providerConfig);\n \n // Initialize the provider with saved config\n try {\n const { createProvider } = useAIProviderStore.getState();\n createProvider(providerConfig);\n \n const provider = useAIProviderStore.getState().provider;\n if (provider) {\n try {\n await provider.validateServiceAvailability({ timeoutMs: 5000 });\n debugLogger.info(`AI Provider initialized and validated from IndexedDB: ${providerConfig.type}`);\n } catch (validationError) {\n debugLogger.warn(`AI Provider created but validation failed`, { error: validationError });\n }\n }\n return; // Successfully initialized from IndexedDB\n } catch (error) {\n debugLogger.error(\"Failed to initialize saved provider config, falling back to package settings\", { error });\n }\n }\n \n debugLogger.info('AI Provider Init: No saved config found, using package settings');\n } catch (error) {\n debugLogger.warn('AI Provider Init: Failed to load from IndexedDB, using package settings', { error });\n }\n }\n\n // Fallback to package settings if no saved config found\n if (settings.aiProvider) {\n providerConfig = { ...settings.aiProvider };\n if (providerConfig.type === AIProviderType.ANTHROPIC) {\n providerConfig = this.convertAnthropicConfig(providerConfig, settings.gatewayApiUrl);\n }\n \n providerConfig = this.ensureTokenFactory(providerConfig);\n \n debugLogger.info(\"Using explicit AI provider config\", providerConfig);\n } else {\n // Fall back to legacy Ollama settings for backward compatibility\n providerConfig = {\n type: AIProviderType.OLLAMA,\n baseUrl: settings.ollamaUrl,\n tokenFactory: () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n \n // If the bandit-engine's service doesn't have a token, try direct localStorage access\n if (!token) {\n token = localStorage.getItem(\"authToken\");\n }\n \n // Also try the authentication store if available\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch (e) {\n // Store might not be available, that's ok\n }\n }\n \n debugLogger.info(\"AIProviderInit: Token factory called\", { \n hasToken: !!token,\n localStorage: !!localStorage.getItem(\"authToken\")\n });\n return token;\n }\n };\n debugLogger.info(\"Using legacy Ollama config\", providerConfig);\n }\n\n try {\n // First validate if the service is available\n const { createProvider } = useAIProviderStore.getState();\n \n // Try to create and validate the provider\n createProvider(providerConfig);\n \n // Test provider availability\n const provider = useAIProviderStore.getState().provider;\n if (provider) {\n try {\n await provider.validateServiceAvailability({ timeoutMs: 5000 });\n debugLogger.info(`AI Provider initialized and validated: ${providerConfig.type}`);\n } catch (validationError) {\n debugLogger.warn(`AI Provider created but validation failed:`, { error: validationError });\n // Provider is created but may not be fully available - this is ok for offline scenarios\n }\n }\n } catch (error) {\n debugLogger.error(\"Failed to initialize AI provider:\", { error });\n \n // Try to fall back to default Ollama if initial provider fails\n if (providerConfig.type !== AIProviderType.OLLAMA) {\n try {\n const fallbackConfig: AIProviderConfig = {\n type: AIProviderType.OLLAMA,\n baseUrl: settings.ollamaUrl || 'http://localhost:11434',\n tokenFactory: () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n \n // If the bandit-engine's service doesn't have a token, try direct localStorage access\n if (!token) {\n token = localStorage.getItem(\"authToken\");\n }\n \n // Also try the authentication store if available\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch (e) {\n // Store might not be available, that's ok\n }\n }\n \n debugLogger.info(\"AIProviderInit: Fallback tokenFactory\", { \n hasToken: !!token,\n localStorage: !!localStorage.getItem(\"authToken\")\n });\n return token;\n }\n };\n const { createProvider } = useAIProviderStore.getState();\n createProvider(fallbackConfig);\n debugLogger.info(\"Fallback to Ollama provider successful\");\n } catch (fallbackError) {\n debugLogger.error(\"Failed to initialize fallback Ollama provider:\", { error: fallbackError });\n }\n } else {\n // If Ollama provider fails, try localhost as ultimate fallback\n try {\n const localFallbackConfig: AIProviderConfig = {\n type: AIProviderType.OLLAMA,\n baseUrl: 'http://localhost:11434',\n tokenFactory: () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n \n // If the bandit-engine's service doesn't have a token, try direct localStorage access\n if (!token) {\n token = localStorage.getItem(\"authToken\");\n }\n \n // Also try the authentication store if available\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch (e) {\n // Store might not be available, that's ok\n }\n }\n \n debugLogger.info(\"AIProviderInit: Local fallback tokenFactory\", { \n hasToken: !!token,\n localStorage: !!localStorage.getItem(\"authToken\")\n });\n return token;\n }\n };\n const { createProvider } = useAIProviderStore.getState();\n createProvider(localFallbackConfig);\n debugLogger.info(\"Fallback to localhost Ollama provider successful\");\n } catch (localFallbackError) {\n debugLogger.error(\"All provider initialization attempts failed:\", { error: localFallbackError });\n }\n }\n }\n }\n\n /**\n * Switch to a different AI provider\n */\n switchProvider(config: AIProviderConfig): void {\n try {\n const normalizedConfig = this.ensureTokenFactory({ ...config });\n const { switchProvider } = useAIProviderStore.getState();\n switchProvider(normalizedConfig);\n debugLogger.info(`Switched to AI provider: ${normalizedConfig.type}`);\n } catch (error) {\n debugLogger.error(\"Failed to switch AI provider:\", { error });\n throw error;\n }\n }\n\n /**\n * Get the current provider type\n */\n getCurrentProviderType(): string | null {\n const provider = useAIProviderStore.getState().provider;\n return provider ? provider.getProviderType() : null;\n }\n\n /**\n * Check if a provider is initialized\n */\n isProviderInitialized(): boolean {\n return useAIProviderStore.getState().provider !== null;\n }\n\n private convertAnthropicConfig(config: AIProviderConfig, gatewayUrl?: string | null): AIProviderConfig {\n if (config.type !== AIProviderType.ANTHROPIC) {\n return config;\n }\n\n const defaultModel = typeof config.defaultModel === 'string' && config.defaultModel.trim()\n ? config.defaultModel.trim()\n : 'claude-3-5-sonnet-latest';\n\n const normalized: AIProviderConfig = {\n type: AIProviderType.GATEWAY,\n gatewayUrl: gatewayUrl || config.gatewayUrl || '',\n provider: 'anthropic',\n defaultModel,\n tokenFactory: config.tokenFactory\n };\n\n debugLogger.info('AI Provider Init: Converted direct Anthropic provider to gateway configuration');\n return normalized;\n }\n\n /**\n * Ensure providers that require auth have a token factory configured.\n * Handles both UI auth tokens and API key scenarios.\n */\n private ensureTokenFactory(config: AIProviderConfig): AIProviderConfig {\n if (config.type === AIProviderType.OLLAMA || config.type === AIProviderType.GATEWAY) {\n const existingFactory = config.tokenFactory;\n if (existingFactory) {\n return config;\n }\n\n // Prefer explicit API key if provided\n if (typeof config.apiKey === 'string' && config.apiKey.trim() !== '') {\n const key = config.apiKey.trim();\n config.tokenFactory = () => key;\n debugLogger.info(\"AIProviderInit: Using API key for token factory\", {\n type: config.type,\n hasKey: true\n });\n return config;\n }\n\n // Fallback to stored auth tokens (UI sessions)\n config.tokenFactory = () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n\n if (!token && typeof localStorage !== 'undefined') {\n try {\n token = localStorage.getItem(\"authToken\");\n } catch {\n // ignore storage errors\n }\n }\n\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch {\n // Store might not be available, that's ok\n }\n }\n\n debugLogger.info(\"AIProviderInit: Token factory resolved auth token\", { \n hasToken: !!token,\n });\n return token;\n };\n }\n\n return config;\n }\n}\n\nexport const aiProviderInitService = AIProviderInitService.getInstance();\n"],"mappings":";;;;;;;;;;;;;;;;AAmBO,IAAM,wBAAN,MAAM,uBAAsB;AAAA,EACjC,OAAe;AAAA,EAEP,cAAc;AAAA,EAAC;AAAA,EAEvB,OAAO,cAAqC;AAC1C,QAAI,CAAC,uBAAsB,UAAU;AACnC,6BAAsB,WAAW,IAAI,uBAAsB;AAAA,IAC7D;AACA,WAAO,uBAAsB;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,yBAAwC;AAC5C,UAAM,WAAW,wBAAwB,SAAS,EAAE;AACpD,QAAI,CAAC,UAAU;AACb,kBAAY,KAAK,0DAA0D;AAC3E;AAAA,IACF;AAEA,QAAI;AAEJ,gBAAY,KAAK,6CAA6C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/C,UAAU;AAAA,MACV;AAAA,MACA,cAAc,OAAO;AAAA,IACvB;AAEA,gBAAY,KAAK,gFAAgF;AACjG,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,mBAAmB,QAA4C;AACrE,QAAI,OAAO,kCAAkC,OAAO,kCAAiC;AACnF,YAAM,kBAAkB,OAAO;AAC/B,UAAI,iBAAiB;AACnB,eAAO;AAAA,MACT;AAGA,UAAI,OAAO,OAAO,WAAW,YAAY,OAAO,OAAO,KAAK,MAAM,IAAI;AACpE,cAAM,MAAM,OAAO,OAAO,KAAK;AAC/B,eAAO,eAAe,MAAM;AAC5B,oBAAY,KAAK,mDAAmD;AAAA,UAClE,MAAM,OAAO;AAAA,UACb,QAAQ;AAAA,QACV,CAAC;AACD,eAAO;AAAA,MACT;AAGA,aAAO,eAAe,MAAM;AAE1B,YAAI,QAAQ,sBAAsB,SAAS;AAE3C,YAAI,CAAC,SAAS,OAAO,iBAAiB,aAAa;AACjD,cAAI;AACF,oBAAQ,aAAa,QAAQ,WAAW;AAAA,UAC1C,QAAQ;AAAA,UAER;AAAA,QACF;AAEA,YAAI,CAAC,OAAO;AACV,cAAI;AACF,kBAAM,EAAE,uBAAuB,IAAI,UAAQ,iCAAiC;AAC5E,kBAAM,YAAY,uBAAuB,SAAS;AAClD,oBAAQ,UAAU;AAAA,UACpB,QAAQ;AAAA,UAER;AAAA,QACF;AAEA,oBAAY,KAAK,qDAAqD;AAAA,UACpE,UAAU,CAAC,CAAC;AAAA,QACd,CAAC;AACD,eAAO;AAAA,MACT;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;AAEO,IAAM,wBAAwB,sBAAsB,YAAY;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  debugLogger
3
- } from "./chunk-KCI46M23.mjs";
3
+ } from "./chunk-OCVZVBQQ.mjs";
4
4
 
5
5
  // src/store/aiProviderStore.ts
6
6
  import { create as create2 } from "zustand";
@@ -10,6 +10,36 @@ import { map as map2 } from "rxjs";
10
10
 
11
11
  // src/services/ollama/ollama.service.ts
12
12
  import { catchError, from, lastValueFrom, map, Observable, of, shareReplay, switchMap, throwError, timeout } from "rxjs";
13
+
14
+ // src/services/stream/streamLineParser.ts
15
+ var SKIP = { kind: "skip" };
16
+ var StreamLineParser = class {
17
+ /** Set by `event: ping` until the frame's blank-line terminator. */
18
+ inHeartbeatFrame = false;
19
+ next(rawLine) {
20
+ const line = rawLine.trim();
21
+ if (!line) {
22
+ this.inHeartbeatFrame = false;
23
+ return SKIP;
24
+ }
25
+ if (line.startsWith(":")) return SKIP;
26
+ if (line.startsWith("event:")) {
27
+ this.inHeartbeatFrame = line.slice(6).trim().toLowerCase() === "ping";
28
+ return SKIP;
29
+ }
30
+ if (line.startsWith("id:") || line.startsWith("retry:")) return SKIP;
31
+ if (line.startsWith("data:")) {
32
+ if (this.inHeartbeatFrame) return SKIP;
33
+ const data = line.slice(5).trim();
34
+ if (!data) return SKIP;
35
+ if (data === "[DONE]") return { kind: "done" };
36
+ return { kind: "json", text: data };
37
+ }
38
+ return { kind: "json", text: line };
39
+ }
40
+ };
41
+
42
+ // src/services/ollama/ollama.service.ts
13
43
  var handleError = () => (obs) => obs.pipe(
14
44
  switchMap(
15
45
  (response) => response.ok ? of(response) : throwError(() => new Error(`Request failed: ${response.status} ${response.statusText}`))
@@ -100,13 +130,15 @@ var OllamaService = class {
100
130
  this._throwErrorIfNotOk(url, response);
101
131
  const reader = response.body?.getReader();
102
132
  const decoder = new TextDecoder();
133
+ const lineParser = new StreamLineParser();
103
134
  let buffer = "";
104
135
  const read = () => {
105
136
  reader?.read().then(({ done, value }) => {
106
137
  if (done) {
107
- if (buffer.trim() !== "") {
138
+ const tail = lineParser.next(buffer);
139
+ if (tail.kind === "json") {
108
140
  try {
109
- observer.next(JSON.parse(buffer));
141
+ observer.next(JSON.parse(tail.text));
110
142
  } catch (err) {
111
143
  observer.error(err);
112
144
  debugLogger.error("Final chunk parsing error (generate):", { buffer });
@@ -119,9 +151,10 @@ var OllamaService = class {
119
151
  const lines = buffer.split("\n");
120
152
  buffer = lines.pop() ?? "";
121
153
  for (const line of lines) {
122
- if (line.trim()) {
154
+ const classified = lineParser.next(line);
155
+ if (classified.kind === "json") {
123
156
  try {
124
- observer.next(JSON.parse(line));
157
+ observer.next(JSON.parse(classified.text));
125
158
  } catch (err) {
126
159
  observer.error(err);
127
160
  debugLogger.error("Error parsing JSON line (generate):", { line });
@@ -151,13 +184,15 @@ var OllamaService = class {
151
184
  this._throwErrorIfNotOk(url, response);
152
185
  const reader = response.body?.getReader();
153
186
  const decoder = new TextDecoder();
187
+ const lineParser = new StreamLineParser();
154
188
  let buffer = "";
155
189
  const read = () => {
156
190
  reader?.read().then(({ done, value }) => {
157
191
  if (done) {
158
- if (buffer.trim() !== "") {
192
+ const tail = lineParser.next(buffer);
193
+ if (tail.kind === "json") {
159
194
  try {
160
- observer.next(JSON.parse(buffer));
195
+ observer.next(JSON.parse(tail.text));
161
196
  } catch (err) {
162
197
  observer.error(err);
163
198
  debugLogger.error("Final chunk parsing error (chat):", { buffer });
@@ -170,9 +205,10 @@ var OllamaService = class {
170
205
  const lines = buffer.split("\n");
171
206
  buffer = lines.pop() ?? "";
172
207
  for (const line of lines) {
173
- if (line.trim()) {
208
+ const classified = lineParser.next(line);
209
+ if (classified.kind === "json") {
174
210
  try {
175
- observer.next(JSON.parse(line));
211
+ observer.next(JSON.parse(classified.text));
176
212
  } catch (err) {
177
213
  observer.error(err);
178
214
  debugLogger.error("Error parsing JSON line (chat):", { line });
@@ -1323,13 +1359,15 @@ var GatewayService = class {
1323
1359
  const handleStreamingResponse = async (response) => {
1324
1360
  const reader = response.body?.getReader();
1325
1361
  const decoder = new TextDecoder();
1362
+ const lineParser = new StreamLineParser();
1326
1363
  let buffer = "";
1327
1364
  const read = () => {
1328
1365
  reader?.read().then(({ done, value }) => {
1329
1366
  if (done) {
1330
- if (buffer.trim() !== "") {
1367
+ const tail = lineParser.next(buffer);
1368
+ if (tail.kind === "json") {
1331
1369
  try {
1332
- const finalResponse = JSON.parse(buffer);
1370
+ const finalResponse = JSON.parse(tail.text);
1333
1371
  observer.next(finalResponse);
1334
1372
  } catch (err) {
1335
1373
  debugLogger.error("GatewayService chat final chunk parsing error", { buffer, error: err });
@@ -1343,16 +1381,14 @@ var GatewayService = class {
1343
1381
  const lines = buffer.split("\n");
1344
1382
  buffer = lines.pop() ?? "";
1345
1383
  for (const line of lines) {
1346
- const trimmed = line.trim();
1347
- if (trimmed) {
1348
- let data = trimmed;
1349
- if (trimmed.startsWith("data: ")) {
1350
- data = trimmed.slice(6);
1351
- if (data === "[DONE]") {
1352
- observer.complete();
1353
- return;
1354
- }
1355
- }
1384
+ const classified = lineParser.next(line);
1385
+ if (classified.kind === "done") {
1386
+ observer.complete();
1387
+ return;
1388
+ }
1389
+ if (classified.kind === "json") {
1390
+ const trimmed = line.trim();
1391
+ const data = classified.text;
1356
1392
  try {
1357
1393
  const parsed = JSON.parse(data);
1358
1394
  if (request.provider === "ollama" && parsed.message) {
@@ -1519,13 +1555,15 @@ var GatewayService = class {
1519
1555
  }
1520
1556
  const reader = response.body?.getReader();
1521
1557
  const decoder = new TextDecoder();
1558
+ const lineParser = new StreamLineParser();
1522
1559
  let buffer = "";
1523
1560
  const read = () => {
1524
1561
  reader?.read().then(({ done, value }) => {
1525
1562
  if (done) {
1526
- if (buffer.trim() !== "") {
1563
+ const tail = lineParser.next(buffer);
1564
+ if (tail.kind === "json") {
1527
1565
  try {
1528
- observer.next(JSON.parse(buffer));
1566
+ observer.next(JSON.parse(tail.text));
1529
1567
  } catch (err) {
1530
1568
  observer.error(err);
1531
1569
  debugLogger.error("Final chunk parsing error (gateway generate):", { buffer });
@@ -1538,9 +1576,14 @@ var GatewayService = class {
1538
1576
  const lines = buffer.split("\n");
1539
1577
  buffer = lines.pop() ?? "";
1540
1578
  for (const line of lines) {
1541
- if (line.trim()) {
1579
+ const classified = lineParser.next(line);
1580
+ if (classified.kind === "done") {
1581
+ observer.complete();
1582
+ return;
1583
+ }
1584
+ if (classified.kind === "json") {
1542
1585
  try {
1543
- observer.next(JSON.parse(line));
1586
+ observer.next(JSON.parse(classified.text));
1544
1587
  } catch (err) {
1545
1588
  observer.error(err);
1546
1589
  debugLogger.error("Error parsing JSON line (gateway generate):", { line });
@@ -3111,4 +3154,4 @@ export {
3111
3154
  AIProviderFactory,
3112
3155
  useAIProviderStore
3113
3156
  };
3114
- //# sourceMappingURL=chunk-B3HAQC6F.mjs.map
3157
+ //# sourceMappingURL=chunk-CQJGUYRW.mjs.map