@burtson-labs/bandit-engine 2.0.51 → 2.0.52

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 (36) hide show
  1. package/dist/{chat-W5IFNEUC.mjs → chat-YWYLVKXX.mjs} +5 -5
  2. package/dist/chat-provider.js +225 -8
  3. package/dist/chat-provider.js.map +1 -1
  4. package/dist/chat-provider.mjs +3 -3
  5. package/dist/{chunk-EWUUF4GE.mjs → chunk-37PEP5JK.mjs} +2 -2
  6. package/dist/{chunk-HETIHZ42.mjs → chunk-M3BEAMCC.mjs} +2 -2
  7. package/dist/{chunk-QFSEZAG6.mjs → chunk-MH7WFWCP.mjs} +34 -3
  8. package/dist/chunk-MH7WFWCP.mjs.map +1 -0
  9. package/dist/{chunk-IDH2YOW3.mjs → chunk-QX6CO7TJ.mjs} +196 -9
  10. package/dist/chunk-QX6CO7TJ.mjs.map +1 -0
  11. package/dist/{chunk-LXD3IV6Z.mjs → chunk-RSSJADDD.mjs} +3 -3
  12. package/dist/{chunk-STMXPFAQ.mjs → chunk-TSQCNHOX.mjs} +4 -4
  13. package/dist/{chunk-JBXNXSAH.mjs → chunk-Y5N3NSTU.mjs} +459 -180
  14. package/dist/chunk-Y5N3NSTU.mjs.map +1 -0
  15. package/dist/{chunk-N7RMUOFB.mjs → chunk-YZ2HJFPQ.mjs} +2 -2
  16. package/dist/cli.js +1 -1
  17. package/dist/cli.js.map +1 -1
  18. package/dist/index.js +678 -183
  19. package/dist/index.js.map +1 -1
  20. package/dist/index.mjs +8 -8
  21. package/dist/management/management.js +648 -183
  22. package/dist/management/management.js.map +1 -1
  23. package/dist/management/management.mjs +6 -6
  24. package/dist/modals/chat-modal/chat-modal.js +197 -8
  25. package/dist/modals/chat-modal/chat-modal.js.map +1 -1
  26. package/dist/modals/chat-modal/chat-modal.mjs +3 -3
  27. package/package.json +1 -1
  28. package/dist/chunk-IDH2YOW3.mjs.map +0 -1
  29. package/dist/chunk-JBXNXSAH.mjs.map +0 -1
  30. package/dist/chunk-QFSEZAG6.mjs.map +0 -1
  31. /package/dist/{chat-W5IFNEUC.mjs.map → chat-YWYLVKXX.mjs.map} +0 -0
  32. /package/dist/{chunk-EWUUF4GE.mjs.map → chunk-37PEP5JK.mjs.map} +0 -0
  33. /package/dist/{chunk-HETIHZ42.mjs.map → chunk-M3BEAMCC.mjs.map} +0 -0
  34. /package/dist/{chunk-LXD3IV6Z.mjs.map → chunk-RSSJADDD.mjs.map} +0 -0
  35. /package/dist/{chunk-STMXPFAQ.mjs.map → chunk-TSQCNHOX.mjs.map} +0 -0
  36. /package/dist/{chunk-N7RMUOFB.mjs.map → chunk-YZ2HJFPQ.mjs.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/store/authenticationStore.ts","../src/services/auth/authenticationService.ts","../src/store/aiQueryStore.ts","../src/store/conversationStore.ts","../src/util/conversationMigration.ts","../src/store/conversationSyncEvents.ts","../src/store/memoryStore.ts","../src/store/projectStore.ts","../src/store/conversationSyncStore.ts","../src/services/conversationSync/conversationSyncService.ts","../src/store/knowledgeStore.ts","../src/util.ts","../src/services/notification/notificationService.ts","../src/services/prompts/conversationStarters.ts","../src/prompts/getStableQuestionPrompt.ts","../src/services/prompts/promptUtils.ts","../src/services/prompts/moodDetection.ts","../src/services/prompts/detectUserInterestAndExcitement.ts","../src/services/prompts/documentSummarization.ts","../src/services/prompts/documentRelevance.ts","../src/services/prompts/dateTimeContext.ts","../src/services/embedding/embeddingService.tsx","../src/services/vectorDatabase/vectorDatabaseService.ts","../src/services/vectorDatabase/vectorMigrationService.ts","../src/types/featureFlags.ts","../src/contexts/FeatureFlagContext.tsx","../src/hooks/useFeatures.ts","../src/hooks/useVectorStore.tsx","../src/chat/hooks/useKnowledgeStore.tsx","../src/services/branding/brandingService.ts","../src/shared/components/NotificationProvider.tsx"],"sourcesContent":["/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-4B68-54D1A0\nconst __banditFingerprint_store_authenticationStorets = 'BL-FP-3C880F-DCB9';\nconst __auditTrail_store_authenticationStorets = 'BL-AU-MGOIKVW3-9GUS';\n// File: authenticationStore.ts | Path: src/store/authenticationStore.ts | Hash: 4b68dcb9\n\nimport { create } from \"zustand\";\nimport { JwtClaims } from \"../services/auth/authenticationService\";\n\nconst TOKEN_KEY = \"authToken\";\n\n// 🔥 Inline hydration of token + user (avoids circular import)\nlet validToken: string | null = null;\nlet user: JwtClaims | null = null;\n\nconst rawToken = localStorage.getItem(TOKEN_KEY);\nif (rawToken) {\n try {\n const base64Url = rawToken.split(\".\")[1];\n const base64 = base64Url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const jsonPayload = decodeURIComponent(\n atob(base64)\n .split(\"\")\n .map((c) => \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2))\n .join(\"\")\n );\n const decoded = JSON.parse(jsonPayload) as JwtClaims;\n\n if (decoded.exp * 1000 > Date.now()) {\n validToken = rawToken;\n user = decoded;\n }\n } catch {\n validToken = null;\n user = null;\n }\n}\n\ninterface AuthenticationState {\n token: string | null;\n user: JwtClaims | null;\n authError: string | null;\n setToken: (token: string | null) => void;\n clearToken: () => void;\n}\n\nexport const useAuthenticationStore = create<AuthenticationState>((set) => ({\n token: validToken,\n user,\n authError: null,\n setToken: (token) => {\n if (token) {\n try {\n const base64Url = token.split(\".\")[1];\n const base64 = base64Url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const jsonPayload = decodeURIComponent(\n atob(base64)\n .split(\"\")\n .map((c) => \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2))\n .join(\"\")\n );\n const user = JSON.parse(jsonPayload) as JwtClaims;\n\n localStorage.setItem(TOKEN_KEY, token);\n set({ token, authError: null, user });\n } catch {\n set({ token: null, authError: \"Invalid token\", user: null });\n }\n } else {\n set({ token: null, authError: null, user: null });\n }\n },\n clearToken: () => {\n localStorage.removeItem(TOKEN_KEY);\n set({ token: null, authError: null, user: null });\n },\n}));\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-4D16-84732D\nconst __banditFingerprint_auth_authenticationServicets = 'BL-FP-90E332-44A4';\nconst __auditTrail_auth_authenticationServicets = 'BL-AU-MGOIKVVR-AIBP';\n// File: authenticationService.ts | Path: src/services/auth/authenticationService.ts | Hash: 4d1644a4\n\nimport { useAuthenticationStore } from \"../../store/authenticationStore\";\nimport { debugLogger } from \"../logging/debugLogger\";\n\n\nexport interface JwtClaims {\n /**\n * The unique identifier for the user.\n */\n sub: string;\n /**\n * The email address of the user.\n * This is typically used for authentication and user identification.\n */\n email: string;\n /**\n * Optional display name for the user if provided by the identity provider.\n */\n name?: string;\n /**\n * Optional preferred username provided by the identity provider.\n */\n preferred_username?: string;\n /**\n * Optional direct URL to a profile image for the user.\n */\n picture?: string;\n /**\n * Optional given name of the user when available.\n */\n given_name?: string;\n /**\n * Optional family name of the user when available.\n */\n family_name?: string;\n /**\n * The roles assigned to the user.\n * 'user' | 'admin' | 'super-admin'\n */\n roles: string[];\n /**\n * The time at which the token was issued.\n * This is represented as a Unix timestamp (seconds since the epoch).\n */\n iat: number;\n\n /**\n * The time at which the token will expire.\n * This is represented as a Unix timestamp (seconds since the epoch).\n */\n exp: number;\n /**\n * The issuer of the token.\n * This is typically the URL of the authentication server.\n * \n */\n iss: string;\n /**\n * Optional team session identifier for team features.\n * Present when user belongs to a team.\n */\n teamSid?: string;\n /**\n * Optional team identifier for team features.\n * Present when user belongs to a team.\n */\n teamId?: string;\n}\n\nexport const TOKEN_KEY = \"authToken\";\n\nclass AuthenticationService {\n getToken(): string | null {\n const token = localStorage.getItem(TOKEN_KEY);\n return token;\n }\n\n setToken(token: string) {\n localStorage.setItem(TOKEN_KEY, token);\n useAuthenticationStore.getState().setToken(token);\n }\n\n clearToken() {\n localStorage.removeItem(TOKEN_KEY);\n useAuthenticationStore.getState().clearToken();\n }\n\n isAuthenticated(): boolean {\n const token = useAuthenticationStore.getState().token;\n return !!token && !this.isTokenExpired(token);\n }\n\n isTokenExpired(token: string): boolean {\n try {\n if (!token) return true;\n const decoded = this.parseJwtClaims(token);\n if (!decoded) return true;\n return decoded.exp * 1000 < Date.now();\n } catch {\n return true;\n }\n }\n\n parseJwtClaims(token: string): JwtClaims | null {\n try {\n const base64Url = token.split(\".\")[1];\n const base64 = base64Url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const jsonPayload = decodeURIComponent(\n atob(base64)\n .split(\"\")\n .map((c) => {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\")\n );\n return JSON.parse(jsonPayload) as JwtClaims;\n } catch (error) {\n debugLogger.error(\"Failed to parse JWT claims:\", { error });\n return null;\n }\n }\n}\n\nexport const authenticationService = new AuthenticationService();\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-206C-8462DB\nconst __banditFingerprint_store_aiQueryStorets = 'BL-FP-38ACD0-3815';\nconst __auditTrail_store_aiQueryStorets = 'BL-AU-MGOIKVW3-J9DR';\n// File: aiQueryStore.ts | Path: src/store/aiQueryStore.ts | Hash: 206c3815\n\nimport { create } from \"zustand\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport { KnowledgeDoc } from \"./knowledgeStore\";\n\nexport type Position = { x: number; y: number };\nexport type HistoryEntry = {\n id?: string;\n question: string;\n answer: string;\n images?: string[];\n sourceFiles?: KnowledgeDoc[];\n memoryUpdated?: boolean;\n cancelled?: boolean;\n /**\n * Internal metadata so streaming can replace placeholders even when the display question differs\n */\n placeholder?: boolean;\n /**\n * Raw prompt text sent to the model (used when the display question is formatted differently)\n */\n rawQuestion?: string;\n};\n\nexport type ComponentStatus = \"Idle\" | \"Loading\" | \"Error\";\n\ninterface AIQueryState {\n inputValue: string;\n response: string;\n previousQuestion: string;\n position: Position;\n componentStatus: ComponentStatus;\n history: HistoryEntry[];\n apiKey: string;\n hydrated: boolean;\n\n setInputValue: (value: string) => void;\n setResponse: (response: string) => void;\n setPreviousQuestion: (question: string) => void;\n setPosition: (position: Position) => void;\n setComponentStatus: (status: ComponentStatus) => void;\n addHistory: (entry: HistoryEntry) => void;\n clearHistory: () => void;\n setApiKey: (key: string) => void;\n setHydrated: () => void;\n reset: () => void;\n hydrate: () => Promise<void>;\n}\n\nconst DB_NAME = \"ai-query-db\";\nconst STORE_NAME = \"ai-query\";\nconst DB_VERSION = 1;\nconst STORAGE_KEY = \"singleton\";\n\nconst storeConfigs = [{ name: STORE_NAME }];\n\nasync function saveStateToDB(state: Partial<AIQueryState>) {\n await indexedDBService.put(DB_NAME, DB_VERSION, STORE_NAME, state, storeConfigs, STORAGE_KEY);\n}\n\nasync function loadStateFromDB(): Promise<Partial<AIQueryState> | undefined> {\n let timeoutId: number | undefined;\n const timeoutPromise = new Promise<undefined>((resolve) => {\n timeoutId = window.setTimeout(() => resolve(undefined), 1200);\n });\n\n try {\n const getPromise = indexedDBService\n .get<Partial<AIQueryState>>(DB_NAME, DB_VERSION, STORE_NAME, STORAGE_KEY, storeConfigs)\n .catch(() => undefined);\n\n return await Promise.race([getPromise, timeoutPromise]);\n } finally {\n if (timeoutId !== undefined) {\n window.clearTimeout(timeoutId);\n }\n }\n}\n\nexport const useAIQueryStore = create<AIQueryState>((set, get) => ({\n inputValue: \"\",\n response: \"\",\n previousQuestion: \"\",\n position: { x: window.innerWidth / 2 - 300, y: window.innerHeight - 350 },\n componentStatus: \"Idle\",\n history: [],\n apiKey: \"\",\n hydrated: false,\n\n setInputValue: (value) => {\n set({ inputValue: value });\n saveStateToDB({ inputValue: value });\n },\n setResponse: (response) => {\n set({ response });\n saveStateToDB({ response });\n },\n setPreviousQuestion: (question) => {\n set({ previousQuestion: question });\n saveStateToDB({ previousQuestion: question });\n },\n setPosition: (position) => {\n set({ position });\n saveStateToDB({ position });\n },\n setComponentStatus: (status) => set({ componentStatus: status }),\n addHistory: (entry) => {\n const newHistory = [...get().history, entry];\n set({ history: newHistory });\n saveStateToDB({ history: newHistory });\n },\n clearHistory: () => {\n set({ history: [] });\n saveStateToDB({ history: [] });\n },\n setApiKey: (key) => {\n set({ apiKey: key });\n saveStateToDB({ apiKey: key });\n },\n setHydrated: () => set({ hydrated: true }),\n\n reset: () => {\n const resetState = {\n inputValue: \"\",\n response: \"\",\n previousQuestion: \"\",\n position: { x: window.innerWidth / 2 - 300, y: window.innerHeight - 350 },\n componentStatus: \"Idle\",\n history: [],\n apiKey: \"\",\n } as Partial<AIQueryState>;\n set(resetState);\n saveStateToDB(resetState);\n },\n\n hydrate: async () => {\n try {\n const storedState = await loadStateFromDB();\n if (storedState) {\n set({\n inputValue: storedState.inputValue ?? \"\",\n response: storedState.response ?? \"\",\n previousQuestion: storedState.previousQuestion ?? \"\",\n position: storedState.position ?? { x: window.innerWidth / 2 - 300, y: window.innerHeight - 350 },\n componentStatus: \"Idle\",\n history: storedState.history ?? [],\n apiKey: storedState.apiKey ?? \"\",\n hydrated: true,\n });\n } else {\n set({ hydrated: true });\n }\n } catch {\n set({ hydrated: true });\n }\n },\n}));\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-DBCC-69A917\nconst __banditFingerprint_store_conversationStorets = 'BL-FP-4510C8-8D68';\nconst __auditTrail_store_conversationStorets = 'BL-AU-MGOIKVW3-GEGF';\n// File: conversationStore.ts | Path: src/store/conversationStore.ts | Hash: dbcc8d68\n\nimport { create } from \"zustand\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { HistoryEntry, useAIQueryStore } from \"./aiQueryStore\";\nimport { useModelStore } from \"./modelStore\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport { KnowledgeDoc } from \"./knowledgeStore\";\nimport { runConversationMigrations } from \"../util/conversationMigration\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\nimport { CONVERSATION_DELETE_EVENT, CONVERSATION_UPSERT_EVENT } from \"./conversationSyncEvents\";\n\nexport interface Conversation {\n id: string;\n name: string;\n model: string;\n history: HistoryEntry[];\n projectId?: string; // Optional for backward compatibility\n createdAt?: Date;\n updatedAt?: Date;\n version?: number;\n summary?: string;\n tags?: string[];\n metadata?: Record<string, unknown>;\n updatedBy?: string;\n deletedAt?: string | null;\n summaryStatus?: string;\n summaryGeneratedAt?: Date;\n}\n\ninterface ConversationStore {\n conversations: Conversation[];\n currentId: string | null;\n _hasHydrated: boolean;\n createConversation: (firstMessage: string, projectId?: string) => void;\n createNewConversation: (projectId?: string) => void;\n deleteConversation: (id: string) => void;\n switchConversation: (id: string) => void;\n addToCurrent: (entry: HistoryEntry) => void;\n replaceLastAnswer: (answer: string, images?: string[], memoryUpdated?: boolean, sourceFiles?: KnowledgeDoc[], cancelled?: boolean) => void;\n setCurrent: (id: string) => void;\n renameConversation: (id: string, newName: string) => void;\n clearAllConversations: () => Promise<void>;\n moveConversationToProject: (conversationId: string, projectId: string | null) => void;\n getConversationsByProject: (projectId: string | null) => Conversation[];\n hydrate: () => Promise<void>;\n applyRemoteConversations: (conversations: Conversation[]) => Promise<void>;\n removeConversationsByIds: (ids: string[]) => Promise<void>;\n}\n\nconst DB_NAME = \"bandit-conversations\";\nconst STORE_NAME = \"conversations\";\nconst DB_VERSION = 1;\nconst storeConfigs = [{ name: STORE_NAME, keyPath: \"id\" }];\n\nexport const EMOJI_REGEX = /\\p{Extended_Pictographic}/gu;\nexport const VARIATION_SELECTORS_REGEX = /[\\uFE0F\\uFE0E]/g;\nexport const ZERO_WIDTH_JOINER_REGEX = /\\u200D/g;\n\nexport function sanitizeConversationName(input: string | undefined | null, maxLength = 60): string {\n if (!input) return \"Untitled Conversation\";\n\n const withoutEmoji = input\n .replace(EMOJI_REGEX, \"\")\n .replace(VARIATION_SELECTORS_REGEX, \"\")\n .replace(ZERO_WIDTH_JOINER_REGEX, \"\");\n\n const normalized = withoutEmoji.normalize(\"NFC\").trim().replace(/\\s+/g, \" \");\n\n if (!normalized) {\n return \"Untitled Conversation\";\n }\n\n const limited = Array.from(normalized).slice(0, maxLength).join(\"\");\n return limited || \"Untitled Conversation\";\n}\n\nasync function loadConversations(): Promise<Conversation[]> {\n const raw = await indexedDBService.getAll<Conversation>(DB_NAME, DB_VERSION, STORE_NAME, storeConfigs);\n return (raw || []).map(normalizeConversation);\n}\n\nasync function saveConversation(conversation: Conversation) {\n await indexedDBService.put(DB_NAME, DB_VERSION, STORE_NAME, conversation, storeConfigs);\n}\n\nasync function deleteConversationFromDB(id: string) {\n await indexedDBService.delete(DB_NAME, DB_VERSION, STORE_NAME, id, storeConfigs);\n}\n\nexport const useConversationStore = create<ConversationStore>((set, get) => ({\n conversations: [],\n currentId: null,\n _hasHydrated: false,\n\n hydrate: async () => {\n try {\n // Run migrations first to ensure backward compatibility\n await runConversationMigrations();\n \n const conversations = await loadConversations();\n set({ conversations, _hasHydrated: true });\n } catch (error) {\n console.error(\"Failed to hydrate conversations:\", error);\n set({ conversations: [], _hasHydrated: true });\n }\n },\n\n createConversation: (firstMessage: string, projectId?: string) => {\n const id = uuidv4();\n const { selectedModel } = useModelStore.getState();\n const sanitizedFirstMessage = sanitizeConversationName(firstMessage, 60);\n const name = sanitizedFirstMessage;\n const now = new Date();\n const newConv = normalizeConversation({ \n id, \n name, \n history: [], \n model: selectedModel,\n projectId,\n createdAt: now,\n updatedAt: now,\n version: 0,\n });\n set((state) => {\n const updatedConversations = [...state.conversations, newConv];\n saveConversation(newConv);\n emitConversationUpsert(id);\n return {\n conversations: updatedConversations,\n currentId: id,\n };\n });\n },\n\n createNewConversation: (projectId?: string) => {\n const { selectedModel } = useModelStore.getState();\n const id = uuidv4();\n const now = new Date();\n const newConv = normalizeConversation({\n id,\n name: \"New Conversation\",\n history: [],\n model: selectedModel,\n projectId,\n createdAt: now,\n updatedAt: now,\n version: 0,\n });\n set((state) => {\n const updatedConversations = [...state.conversations, newConv];\n saveConversation(newConv);\n emitConversationUpsert(id);\n return {\n conversations: updatedConversations,\n currentId: id,\n };\n });\n },\n\n deleteConversation: (id: string) => {\n const runHydrate = async () => {\n try {\n await get().hydrate();\n } catch (error) {\n debugLogger.warn(\"conversationStore: rehydrate after delete failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n\n set((state) => {\n const filtered = state.conversations.filter((c) => c.id !== id);\n const isDeletingCurrent = state.currentId === id;\n\n if (isDeletingCurrent) {\n useAIQueryStore.getState().reset();\n }\n\n deleteConversationFromDB(id)\n .then(runHydrate)\n .catch((error) => {\n debugLogger.error(\"Failed to delete conversation from DB\", {\n error,\n conversationId: id,\n });\n });\n emitConversationDelete(id);\n\n return {\n conversations: filtered,\n currentId: isDeletingCurrent ? null : state.currentId,\n };\n });\n },\n\n switchConversation: (id: string) => {\n const { conversations } = get();\n const { setSelectedModel } = useModelStore.getState();\n const selectedModel = conversations.find((c) => c.id === id)?.model;\n selectedModel && setSelectedModel(selectedModel);\n set({ currentId: id });\n },\n\n addToCurrent: (entry: HistoryEntry) => {\n const { currentId, conversations } = get();\n if (!currentId) return;\n set(() => {\n const updatedConversations = conversations.map((c) =>\n c.id === currentId ? normalizeConversation({ ...c, history: [...c.history, entry], updatedAt: new Date() }) : c\n );\n const updatedConv = updatedConversations.find((c) => c.id === currentId);\n if (updatedConv) {\n saveConversation(updatedConv);\n emitConversationUpsert(updatedConv.id);\n }\n return { conversations: updatedConversations };\n });\n },\n\n renameConversation: (id: string, newName: string) => {\n set((state) => {\n const sanitized = sanitizeConversationName(newName);\n const updatedConversations = state.conversations.map((c) =>\n c.id === id ? normalizeConversation({ ...c, name: sanitized, updatedAt: new Date() }) : c\n );\n const updatedConv = updatedConversations.find((c) => c.id === id);\n if (updatedConv) {\n saveConversation(updatedConv);\n emitConversationUpsert(updatedConv.id);\n }\n return { conversations: updatedConversations };\n });\n },\n\n replaceLastAnswer: (answer: string, images?: string[], memoryUpdated?: boolean, sourceFiles?: KnowledgeDoc[], cancelled?: boolean) => {\n const { currentId, conversations } = get();\n if (!currentId) return;\n set(() => {\n const updatedConversations = conversations.map((c) => {\n if (c.id === currentId && c.history.length > 0) {\n const updatedHistory = [...c.history];\n const existingImages = updatedHistory[updatedHistory.length - 1].images;\n const nextImages =\n Array.isArray(images) && images.length > 0\n ? [...images]\n : Array.isArray(existingImages) && existingImages.length > 0\n ? [...existingImages]\n : existingImages;\n updatedHistory[updatedHistory.length - 1] = {\n ...updatedHistory[updatedHistory.length - 1],\n answer,\n memoryUpdated,\n images: nextImages,\n sourceFiles: sourceFiles ?? updatedHistory[updatedHistory.length - 1].sourceFiles,\n cancelled: cancelled ?? updatedHistory[updatedHistory.length - 1].cancelled,\n placeholder: false,\n rawQuestion: undefined,\n };\n return normalizeConversation({ ...c, history: updatedHistory, updatedAt: new Date() });\n }\n return c;\n });\n const updatedConv = updatedConversations.find((c) => c.id === currentId);\n if (updatedConv) {\n saveConversation(updatedConv);\n emitConversationUpsert(updatedConv.id);\n }\n return { conversations: updatedConversations };\n });\n },\n\n setCurrent: (id: string) => set({ currentId: id }),\n\n moveConversationToProject: (conversationId: string, projectId: string | null) => {\n set((state) => {\n const updatedConversations = state.conversations.map((c) =>\n c.id === conversationId \n ? normalizeConversation({ ...c, projectId: projectId || undefined, updatedAt: new Date() }) \n : c\n );\n const updatedConv = updatedConversations.find((c) => c.id === conversationId);\n if (updatedConv) {\n saveConversation(updatedConv);\n }\n return { conversations: updatedConversations };\n });\n },\n\n clearAllConversations: async () => {\n try {\n // Clear all conversations from IndexedDB\n await indexedDBService.clear(DB_NAME, DB_VERSION, STORE_NAME, storeConfigs);\n \n // Reset store state\n set({\n conversations: [],\n currentId: null,\n });\n \n debugLogger.info(\"All conversations cleared successfully\");\n } catch (error) {\n debugLogger.error(\"Failed to clear all conversations\", { error });\n throw error;\n }\n },\n\n getConversationsByProject: (projectId: string | null) => {\n const { conversations } = get();\n if (projectId === null) {\n // Return conversations without a project (ungrouped)\n return conversations.filter(c => !c.projectId);\n }\n return conversations.filter(c => c.projectId === projectId);\n },\n\n applyRemoteConversations: async (incoming) => {\n const normalized = incoming.map(normalizeConversation);\n const toPersist: Conversation[] = [];\n\n set((state) => {\n const next = new Map(state.conversations.map((c) => [c.id, c] as const));\n\n for (const conversation of normalized) {\n const existing = next.get(conversation.id);\n\n if (existing) {\n const existingUpdatedAt = existing.updatedAt ? existing.updatedAt.getTime() : 0;\n const incomingUpdatedAt = conversation.updatedAt ? conversation.updatedAt.getTime() : 0;\n const existingHistoryLength = existing.history?.length ?? 0;\n const incomingHistoryLength = conversation.history?.length ?? 0;\n\n const incomingHasMoreHistory = incomingHistoryLength > existingHistoryLength;\n const incomingIsNewer = incomingUpdatedAt > existingUpdatedAt;\n\n if (incomingIsNewer && incomingHistoryLength < existingHistoryLength) {\n debugLogger.info(\"applyRemoteConversations: preserving local history over shorter incoming\", {\n conversationId: conversation.id,\n existingHistoryLength,\n incomingHistoryLength,\n existingUpdatedAt,\n incomingUpdatedAt,\n });\n conversation.history = existing.history;\n }\n\n if (!incomingHasMoreHistory && !incomingIsNewer) {\n debugLogger.info(\"applyRemoteConversations: skipping stale conversation\", {\n conversationId: conversation.id,\n existingHistoryLength,\n incomingHistoryLength,\n existingUpdatedAt,\n incomingUpdatedAt,\n });\n continue;\n }\n\n // Preserve local-only metadata (e.g., inline images) when remote payload omits it\n if (Array.isArray(existing.history) && Array.isArray(conversation.history)) {\n const mergedHistory = conversation.history.map((incomingEntry, index) => {\n const existingEntry = existing.history[index];\n if (!existingEntry) {\n return incomingEntry;\n }\n\n const mergedImagesSource =\n Array.isArray(incomingEntry.images) && incomingEntry.images.length > 0\n ? incomingEntry.images\n : existingEntry.images;\n const mergedImages =\n Array.isArray(mergedImagesSource) && mergedImagesSource.length > 0\n ? [...mergedImagesSource]\n : mergedImagesSource;\n\n return {\n ...existingEntry,\n ...incomingEntry,\n images: mergedImages,\n placeholder:\n incomingEntry.placeholder ?? existingEntry.placeholder,\n rawQuestion:\n incomingEntry.rawQuestion ?? existingEntry.rawQuestion,\n };\n });\n\n conversation.history = mergedHistory;\n }\n }\n\n next.set(conversation.id, conversation);\n toPersist.push(conversation);\n }\n\n return { conversations: Array.from(next.values()) };\n });\n\n if (toPersist.length > 0) {\n try {\n await Promise.all(toPersist.map((conversation) => saveConversation(conversation)));\n } catch (error) {\n debugLogger.error(\"Failed to persist remote conversations\", { error, conversationIds: toPersist.map((c) => c.id) });\n }\n }\n },\n\n removeConversationsByIds: async (ids) => {\n if (!ids.length) {\n return;\n }\n\n try {\n await Promise.all(ids.map((id) => deleteConversationFromDB(id)));\n } catch (error) {\n debugLogger.error(\"Failed to remove conversations from IndexedDB\", { error, ids });\n }\n\n set((state) => {\n const filtered = state.conversations.filter((c) => !ids.includes(c.id));\n const isCurrentDeleted = state.currentId ? ids.includes(state.currentId) : false;\n ids.forEach((id) => emitConversationDelete(id));\n return {\n conversations: filtered,\n currentId: isCurrentDeleted ? null : state.currentId,\n };\n });\n\n try {\n await get().hydrate();\n } catch (error) {\n debugLogger.warn(\"conversationStore: hydrate failed after remote delete\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n },\n}));\n\nfunction normalizeConversation(conversation: Conversation): Conversation {\n const ensureDate = (value?: Date | string | null): Date | undefined => {\n if (!value) return undefined;\n if (value instanceof Date) return value;\n const parsed = new Date(value);\n return Number.isNaN(parsed.getTime()) ? undefined : parsed;\n };\n\n return {\n ...conversation,\n name: sanitizeConversationName(conversation.name),\n createdAt: ensureDate(conversation.createdAt) ?? new Date(),\n updatedAt: ensureDate(conversation.updatedAt) ?? new Date(),\n summaryGeneratedAt: ensureDate(conversation.summaryGeneratedAt),\n history: Array.isArray(conversation.history)\n ? conversation.history.map((turn) => ({\n ...turn,\n }))\n : [],\n };\n}\nfunction emitConversationUpsert(id: string) {\n if (typeof window === 'undefined') return;\n window.dispatchEvent(new CustomEvent(CONVERSATION_UPSERT_EVENT, { detail: id }));\n}\n\nfunction emitConversationDelete(id: string) {\n if (typeof window === 'undefined') return;\n window.dispatchEvent(new CustomEvent(CONVERSATION_DELETE_EVENT, { detail: id }));\n}\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-39FF-3FCF58\nconst __banditFingerprint_util_conversationMigrationts = 'BL-FP-CA75E4-D550';\nconst __auditTrail_util_conversationMigrationts = 'BL-AU-MGOIKVW9-R32Z';\n// File: conversationMigration.ts | Path: src/util/conversationMigration.ts | Hash: 39ffd550\n\nimport { debugLogger } from \"../services/logging/debugLogger\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport type { HistoryEntry } from \"../store/aiQueryStore\";\n\n/**\n * Migration utility to ensure backward compatibility for conversations\n * that were created before the projects feature was added.\n */\n\nexport interface ConversationV1 {\n id: string;\n name: string;\n model: string;\n history: HistoryEntry[];\n}\n\nexport interface ConversationV2 {\n id: string;\n name: string;\n model: string;\n history: HistoryEntry[];\n projectId?: string;\n createdAt?: Date;\n updatedAt?: Date;\n}\n\nconst DB_NAME = \"bandit-conversations\";\nconst STORE_NAME = \"conversations\";\nconst DB_VERSION = 1;\nconst storeConfigs = [{ name: STORE_NAME, keyPath: \"id\" }];\n\n/**\n * Migrates conversations from V1 format (without projects) to V2 format (with projects)\n */\nexport async function migrateConversationsToV2(): Promise<boolean> {\n try {\n debugLogger.info(\"Starting conversation migration to V2 format\");\n \n const conversations = await indexedDBService.getAll<ConversationV1 | ConversationV2>(\n DB_NAME, \n DB_VERSION, \n STORE_NAME, \n storeConfigs\n );\n\n if (!conversations || conversations.length === 0) {\n debugLogger.info(\"No conversations found, migration not needed\");\n return true;\n }\n\n let migratedCount = 0;\n const now = new Date();\n\n for (const conversation of conversations) {\n // Check if conversation needs migration (missing V2 fields)\n const needsMigration = \n !conversation.hasOwnProperty('createdAt') || \n !conversation.hasOwnProperty('updatedAt');\n\n if (needsMigration) {\n const migratedConversation: ConversationV2 = {\n ...conversation,\n // projectId remains undefined (ungrouped)\n createdAt: now, // We can't know the real creation date\n updatedAt: now,\n };\n\n await indexedDBService.put(\n DB_NAME, \n DB_VERSION, \n STORE_NAME, \n migratedConversation, \n storeConfigs\n );\n\n migratedCount++;\n debugLogger.debug(\"Migrated conversation\", { \n id: conversation.id, \n name: conversation.name \n });\n } else if ('createdAt' in conversation && conversation.createdAt && typeof conversation.createdAt === 'string') {\n // Convert string dates back to Date objects if needed\n const fixedConversation: ConversationV2 = {\n ...(conversation as ConversationV2),\n createdAt: new Date(conversation.createdAt),\n updatedAt: new Date((conversation as ConversationV2).updatedAt || conversation.createdAt),\n };\n\n await indexedDBService.put(\n DB_NAME, \n DB_VERSION, \n STORE_NAME, \n fixedConversation, \n storeConfigs\n );\n\n migratedCount++;\n debugLogger.debug(\"Fixed date format for conversation\", { \n id: conversation.id, \n name: conversation.name \n });\n }\n }\n\n if (migratedCount > 0) {\n debugLogger.info(\"Conversation migration completed\", { \n totalConversations: conversations.length,\n migratedCount \n });\n } else {\n debugLogger.info(\"All conversations already up to date\");\n }\n\n return true;\n } catch (error) {\n debugLogger.error(\"Failed to migrate conversations\", { error });\n return false;\n }\n}\n\n/**\n * Validates that all conversations have the expected V2 structure\n */\nexport async function validateConversationStructure(): Promise<boolean> {\n try {\n const conversations = await indexedDBService.getAll<ConversationV2>(\n DB_NAME, \n DB_VERSION, \n STORE_NAME, \n storeConfigs\n );\n\n if (!conversations) {\n return true; // No conversations to validate\n }\n\n for (const conversation of conversations) {\n const isValid = \n typeof conversation.id === 'string' &&\n typeof conversation.name === 'string' &&\n typeof conversation.model === 'string' &&\n Array.isArray(conversation.history) &&\n (conversation.projectId === undefined || typeof conversation.projectId === 'string') &&\n (conversation.createdAt === undefined || conversation.createdAt instanceof Date) &&\n (conversation.updatedAt === undefined || conversation.updatedAt instanceof Date);\n\n if (!isValid) {\n debugLogger.warn(\"Invalid conversation structure detected\", { \n conversationId: conversation.id,\n structure: {\n hasId: typeof conversation.id === 'string',\n hasName: typeof conversation.name === 'string',\n hasModel: typeof conversation.model === 'string',\n hasHistory: Array.isArray(conversation.history),\n projectIdValid: conversation.projectId === undefined || typeof conversation.projectId === 'string',\n createdAtValid: conversation.createdAt === undefined || conversation.createdAt instanceof Date,\n updatedAtValid: conversation.updatedAt === undefined || conversation.updatedAt instanceof Date,\n }\n });\n return false;\n }\n }\n\n debugLogger.info(\"All conversations have valid structure\", { \n count: conversations.length \n });\n return true;\n } catch (error) {\n debugLogger.error(\"Failed to validate conversation structure\", { error });\n return false;\n }\n}\n\n/**\n * Runs all necessary migrations for conversations\n */\nexport async function runConversationMigrations(): Promise<boolean> {\n try {\n debugLogger.info(\"Running conversation migrations\");\n \n const migrationSuccess = await migrateConversationsToV2();\n if (!migrationSuccess) {\n debugLogger.error(\"Conversation migration failed\");\n return false;\n }\n\n const validationSuccess = await validateConversationStructure();\n if (!validationSuccess) {\n debugLogger.warn(\"Conversation validation failed, but continuing\");\n }\n\n debugLogger.info(\"Conversation migrations completed successfully\");\n return true;\n } catch (error) {\n debugLogger.error(\"Migration process failed\", { error });\n return false;\n }\n}\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-9C11-60075A\nconst __banditFingerprint_store_conversationSyncEventsts = 'BL-FP-46A3ED-3255';\nconst __auditTrail_store_conversationSyncEventsts = 'BL-AU-MGOIKVW3-GXVJ';\n// File: conversationSyncEvents.ts | Path: src/store/conversationSyncEvents.ts | Hash: 9c113255\n\nexport const CONVERSATION_UPSERT_EVENT = 'bandit-conversation-upsert';\nexport const CONVERSATION_DELETE_EVENT = 'bandit-conversation-delete';\nexport const PROJECT_UPSERT_EVENT = 'bandit-project-upsert';\nexport const PROJECT_DELETE_EVENT = 'bandit-project-delete';\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-8FA7-51595A\nconst __banditFingerprint_store_memoryStorets = 'BL-FP-C3FA6C-E06F';\nconst __auditTrail_store_memoryStorets = 'BL-AU-MGOIKVW4-KK1J';\n// File: memoryStore.ts | Path: src/store/memoryStore.ts | Hash: 8fa7e06f\n\nimport { create } from \"zustand\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\n\nexport interface MemoryEntry {\n id: string;\n content: string;\n tags?: string[];\n timestamp: number;\n source: \"auto\" | \"user\";\n embedding?: number[];\n pinned?: boolean;\n}\n\ninterface MemoryStore {\n entries: MemoryEntry[];\n _hasHydrated: boolean;\n addMemory: (\n content: string,\n tags?: string[],\n source?: \"auto\" | \"user\",\n embedding?: number[],\n pinned?: boolean\n ) => Promise<void>;\n searchMemory: (query: string) => MemoryEntry[];\n findRelevantMemories: (query: string, limit?: number) => MemoryEntry[];\n togglePinMemory: (id: string) => Promise<void>;\n hydrate: () => Promise<void>;\n removeMemory: (id: string) => Promise<void>;\n clearMemories: () => Promise<void>;\n}\n\nconst DB_NAME = \"bandit-memory-db\";\nconst STORE_NAME = \"bandit-memory\";\nconst storeConfigs = [{ name: STORE_NAME, keyPath: \"id\" }];\n\n// Helper: Normalize text for basic matching\nconst normalize = (text: string) =>\n text\n .toLowerCase()\n .replace(/[^\\w\\s]|_/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n\nexport const useMemoryStore = create<MemoryStore>((set, get) => ({\n entries: [],\n _hasHydrated: false,\n\n hydrate: async () => {\n const allEntries = await indexedDBService.getAll<MemoryEntry>(DB_NAME, 1, STORE_NAME, storeConfigs);\n set({ \n entries: allEntries,\n _hasHydrated: true \n });\n },\n\n addMemory: async (\n content,\n tags = [],\n source = \"user\",\n embedding,\n pinned = false\n ) => {\n const newEntry: MemoryEntry = {\n id: crypto.randomUUID(),\n content,\n tags,\n timestamp: Date.now(),\n source,\n embedding,\n pinned,\n };\n await indexedDBService.put(DB_NAME, 1, STORE_NAME, newEntry, storeConfigs);\n set((state) => ({\n entries: [...state.entries, newEntry],\n }));\n },\n\n removeMemory: async (id: string) => {\n await indexedDBService.delete(DB_NAME, 1, STORE_NAME, id, storeConfigs);\n set((state) => ({\n entries: state.entries.filter((entry) => entry.id !== id),\n }));\n },\n\n clearMemories: async () => {\n await indexedDBService.clear(DB_NAME, 1, STORE_NAME, storeConfigs);\n set({ \n entries: [],\n _hasHydrated: true // Keep hydrated flag true after clearing\n });\n },\n\n searchMemory: (query) => {\n const lc = query.toLowerCase();\n return get().entries.filter((entry) => entry.content.toLowerCase().includes(lc));\n },\n\n findRelevantMemories: (query, limit = 3) => {\n const normQuery = normalize(query);\n const queryWords = normQuery.split(\" \");\n\n const scored = get().entries.map((entry) => {\n const normContent = normalize(entry.content);\n const matchCount = queryWords.filter((word) =>\n normContent.includes(word)\n ).length;\n return { entry, score: matchCount };\n });\n\n return scored\n .filter((item) => item.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map((item) => item.entry);\n },\n\n togglePinMemory: async (id: string) => {\n set((state) => {\n const updatedEntries = state.entries.map((entry) =>\n entry.id === id ? { ...entry, pinned: !entry.pinned } : entry\n );\n (async () => {\n const updatedEntry = updatedEntries.find((entry) => entry.id === id);\n if (updatedEntry) {\n await indexedDBService.put(DB_NAME, 1, STORE_NAME, updatedEntry, storeConfigs);\n }\n })();\n return { entries: updatedEntries };\n });\n },\n}));\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-489B-13F873\nconst __banditFingerprint_store_projectStorets = 'BL-FP-4E45E3-8650';\nconst __auditTrail_store_projectStorets = 'BL-AU-MGOIKVW5-44EI';\n// File: projectStore.ts | Path: src/store/projectStore.ts | Hash: 489b8650\n\nimport { create } from \"zustand\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\nimport {\n PROJECT_DELETE_EVENT,\n PROJECT_UPSERT_EVENT,\n} from \"./conversationSyncEvents\";\n\nexport interface Project {\n id: string;\n name: string;\n description?: string;\n color?: string;\n createdAt: Date;\n updatedAt: Date;\n order: number;\n version?: number;\n conversationCount?: number;\n lastActivityAt?: Date;\n summary?: string;\n metadata?: Record<string, unknown>;\n updatedBy?: string;\n deletedAt?: string | null;\n}\n\ninterface ProjectStore {\n projects: Project[];\n _hasHydrated: boolean;\n \n // Actions\n createProject: (name: string, description?: string, color?: string) => Promise<Project>;\n deleteProject: (id: string) => Promise<void>;\n renameProject: (id: string, newName: string, description?: string) => Promise<void>;\n updateProjectColor: (id: string, color: string) => Promise<void>;\n reorderProjects: (projectIds: string[]) => Promise<void>;\n hydrate: () => Promise<void>;\n applyRemoteProjects: (projects: Project[]) => Promise<void>;\n removeProjectsByIds: (ids: string[]) => Promise<void>;\n}\n\nconst DB_NAME = \"bandit-projects\";\nconst STORE_NAME = \"projects\";\nconst DB_VERSION = 1;\nconst storeConfigs = [{ name: STORE_NAME, keyPath: \"id\" }];\n\n// Default colors for projects\nconst DEFAULT_COLORS = [\n \"#2196F3\", // Blue\n \"#4CAF50\", // Green\n \"#FF9800\", // Orange\n \"#9C27B0\", // Purple\n \"#F44336\", // Red\n \"#00BCD4\", // Cyan\n \"#FFEB3B\", // Yellow\n \"#795548\", // Brown\n \"#607D8B\", // Blue Grey\n \"#E91E63\", // Pink\n];\n\nasync function loadProjects(): Promise<Project[]> {\n try {\n const projects = await indexedDBService.getAll<Project>(DB_NAME, DB_VERSION, STORE_NAME, storeConfigs);\n return (projects || []).map(normalizeProject).sort((a, b) => a.order - b.order);\n } catch (error) {\n debugLogger.error(\"Failed to load projects\", { error });\n return [];\n }\n}\n\nasync function saveProject(project: Project) {\n try {\n await indexedDBService.put(DB_NAME, DB_VERSION, STORE_NAME, project, storeConfigs);\n debugLogger.info(\"Project saved\", { projectId: project.id, projectName: project.name });\n } catch (error) {\n debugLogger.error(\"Failed to save project\", { projectId: project.id, error });\n throw error;\n }\n}\n\nasync function deleteProjectFromDB(id: string) {\n try {\n await indexedDBService.delete(DB_NAME, DB_VERSION, STORE_NAME, id, storeConfigs);\n debugLogger.info(\"Project deleted from DB\", { projectId: id });\n } catch (error) {\n debugLogger.error(\"Failed to delete project from DB\", { projectId: id, error });\n throw error;\n }\n}\n\nexport const useProjectStore = create<ProjectStore>((set, get) => ({\n projects: [],\n _hasHydrated: false,\n\n hydrate: async () => {\n try {\n const projects = await loadProjects();\n set({ projects, _hasHydrated: true });\n debugLogger.info(\"Project store hydrated\", { projectCount: projects.length });\n } catch (error) {\n debugLogger.error(\"Failed to hydrate project store\", { error });\n set({ projects: [], _hasHydrated: true });\n }\n },\n\n createProject: async (name: string, description?: string, color?: string) => {\n const { projects } = get();\n const id = uuidv4();\n const now = new Date();\n \n // Assign a default color if not provided\n const projectColor = color || DEFAULT_COLORS[projects.length % DEFAULT_COLORS.length];\n \n const newProject: Project = normalizeProject({\n id,\n name: name.trim(),\n description: description?.trim(),\n color: projectColor,\n createdAt: now,\n updatedAt: now,\n order: projects.length,\n version: 0,\n });\n\n await saveProject(newProject);\n\n set((state) => ({\n projects: [...state.projects, newProject],\n }));\n emitProjectUpsert(id);\n\n debugLogger.info(\"Project created\", { projectId: id, projectName: name });\n return newProject;\n },\n\n deleteProject: async (id: string) => {\n await deleteProjectFromDB(id);\n \n set((state) => ({\n projects: state.projects.filter((p) => p.id !== id),\n }));\n\n debugLogger.info(\"Project deleted\", { projectId: id });\n emitProjectDelete(id);\n },\n\n renameProject: async (id: string, newName: string, description?: string) => {\n const { projects } = get();\n const project = projects.find(p => p.id === id);\n \n if (!project) {\n throw new Error(`Project with id ${id} not found`);\n }\n\n const updatedProject = normalizeProject({\n ...project,\n name: newName.trim(),\n description: description?.trim(),\n updatedAt: new Date(),\n });\n\n await saveProject(updatedProject);\n \n set((state) => ({\n projects: state.projects.map((p) =>\n p.id === id ? updatedProject : p\n ),\n }));\n\n debugLogger.info(\"Project renamed\", { projectId: id, newName });\n emitProjectUpsert(id);\n },\n\n updateProjectColor: async (id: string, color: string) => {\n const { projects } = get();\n const project = projects.find(p => p.id === id);\n \n if (!project) {\n throw new Error(`Project with id ${id} not found`);\n }\n\n const updatedProject = normalizeProject({\n ...project,\n color,\n updatedAt: new Date(),\n });\n\n await saveProject(updatedProject);\n \n set((state) => ({\n projects: state.projects.map((p) =>\n p.id === id ? updatedProject : p\n ),\n }));\n\n debugLogger.info(\"Project color updated\", { projectId: id, color });\n emitProjectUpsert(id);\n },\n\n reorderProjects: async (projectIds: string[]) => {\n const { projects } = get();\n const reorderedProjects = projectIds.map((id, index) => {\n const project = projects.find(p => p.id === id);\n if (!project) return null;\n return normalizeProject({ ...project, order: index, updatedAt: new Date() });\n }).filter(Boolean) as Project[];\n\n // Save all reordered projects\n await Promise.all(reorderedProjects.map(saveProject));\n \n set({ projects: reorderedProjects });\n debugLogger.info(\"Projects reordered\", { projectCount: reorderedProjects.length });\n reorderedProjects.forEach((project) => emitProjectUpsert(project.id));\n },\n\n applyRemoteProjects: async (incoming) => {\n const normalized = incoming.map(normalizeProject);\n\n try {\n await Promise.all(normalized.map((project) => saveProject(project)));\n } catch (error) {\n debugLogger.error(\"Failed to persist remote projects\", { error });\n }\n\n set((state) => {\n const next = new Map(state.projects.map((p) => [p.id, p] as const));\n for (const project of normalized) {\n next.set(project.id, project);\n }\n return { projects: Array.from(next.values()).sort((a, b) => a.order - b.order) };\n });\n },\n\n removeProjectsByIds: async (ids) => {\n if (!ids.length) {\n return;\n }\n\n try {\n await Promise.all(ids.map((id) => deleteProjectFromDB(id)));\n } catch (error) {\n debugLogger.error(\"Failed to delete projects from IndexedDB\", { error, ids });\n }\n\n set((state) => ({\n projects: state.projects.filter((p) => !ids.includes(p.id)),\n }));\n ids.forEach((id) => emitProjectDelete(id));\n },\n}));\n\nfunction normalizeProject(project: Project): Project {\n const ensureDate = (value?: Date | string | null): Date => {\n if (!value) return new Date();\n if (value instanceof Date) return value;\n const parsed = new Date(value);\n return Number.isNaN(parsed.getTime()) ? new Date() : parsed;\n };\n\n return {\n ...project,\n createdAt: ensureDate(project.createdAt),\n updatedAt: ensureDate(project.updatedAt),\n lastActivityAt: project.lastActivityAt ? ensureDate(project.lastActivityAt) : undefined,\n };\n}\n\nfunction emitProjectUpsert(id: string) {\n if (typeof window === 'undefined') return;\n window.dispatchEvent(new CustomEvent(PROJECT_UPSERT_EVENT, { detail: id }));\n}\n\nfunction emitProjectDelete(id: string) {\n if (typeof window === 'undefined') return;\n window.dispatchEvent(new CustomEvent(PROJECT_DELETE_EVENT, { detail: id }));\n}\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-50BC-1F9568\nconst __banditFingerprint_store_conversationSyncStorets = 'BL-FP-E5217A-A962';\nconst __auditTrail_store_conversationSyncStorets = 'BL-AU-MGOIKVW4-TH1T';\n// File: conversationSyncStore.ts | Path: src/store/conversationSyncStore.ts | Hash: 50bca962\n\nimport { create } from \"zustand\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { useConversationStore, Conversation } from \"./conversationStore\";\nimport { useProjectStore, Project } from \"./projectStore\";\nimport { usePackageSettingsStore } from \"./packageSettingsStore\";\nimport { authenticationService } from \"../services/auth/authenticationService\";\nimport {\n CONVERSATION_DELETE_EVENT,\n CONVERSATION_UPSERT_EVENT,\n PROJECT_DELETE_EVENT,\n PROJECT_UPSERT_EVENT,\n} from \"./conversationSyncEvents\";\nimport {\n ConversationRecordDTO,\n ConversationSyncPreferenceDTO,\n ConversationSyncRequest,\n ConversationSyncResponse,\n ConversationTurnDTO,\n ProjectRecordDTO,\n fetchConversationSyncPreference,\n syncConversations,\n updateConversationSyncPreference,\n} from \"../services/conversationSync/conversationSyncService\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\n\nconst DEVICE_STORAGE_KEY = \"banditConversationDeviceId\";\nconst PAYLOAD_VERSION = 1;\nconst MAX_CONVERSATION_BYTES = 12 * 1024 * 1024; // ~12 MB cloud cap\nconst WARN_CONVERSATION_BYTES = 10 * 1024 * 1024; // warn at ~10 MB\n\nlet suppressTracking = false;\nlet conversationsMeta = new Map<string, ConversationMeta>();\nlet projectsMeta = new Map<string, ProjectMeta>();\nlet conversationUnsubscribe: (() => void) | null = null;\nlet projectUnsubscribe: (() => void) | null = null;\nlet autoSyncTimeout: ReturnType<typeof setTimeout> | null = null;\n\nconst AUTO_SYNC_DELAY_MS = 4_000;\n\ntype ConversationStoreState = ReturnType<typeof useConversationStore.getState>;\ntype ProjectStoreState = ReturnType<typeof useProjectStore.getState>;\n\ninterface ConversationMeta {\n updatedAtMs: number;\n version?: number;\n historyLength: number;\n}\n\ninterface ProjectMeta {\n updatedAtMs: number;\n version?: number;\n order: number;\n}\n\ninterface ConversationSizeNotice {\n id: string;\n name: string;\n sizeBytes: number;\n limitBytes: number;\n}\n\nexport type ConversationSyncStatus = \"disabled\" | \"idle\" | \"syncing\" | \"error\";\n\nexport interface ConversationSyncState {\n initialized: boolean;\n syncEnabled: boolean;\n status: ConversationSyncStatus;\n lastSyncAt?: string | null;\n cursor?: string | null;\n lastError?: string | null;\n keepLocalOnly?: boolean;\n isAdvancedVectorFeaturesEnabled: boolean;\n conflicts: ConversationSyncResponse[\"conflicts\"] | null;\n deviceId: string;\n pendingConversationUpserts: Set<string>;\n pendingConversationDeletes: Set<string>;\n pendingProjectUpserts: Set<string>;\n pendingProjectDeletes: Set<string>;\n totalConversationsOnServer?: number;\n totalProjectsOnServer?: number;\n hasCompletedInitialUpload: boolean;\n warningConversations: ConversationSizeNotice[];\n oversizedConversations: ConversationSizeNotice[];\n initialize: () => Promise<void>;\n setSyncEnabled: (enabled: boolean) => Promise<void>;\n setAdvancedVectorFeaturesEnabled: (enabled: boolean) => Promise<void>;\n runSync: (options?: { force?: boolean }) => Promise<void>;\n registerError: (error: string) => void;\n clearConflicts: () => void;\n}\n\nfunction ensureDeviceId(): string {\n if (typeof window === \"undefined\") {\n return \"bandit-web\";\n }\n try {\n const existing = window.localStorage.getItem(DEVICE_STORAGE_KEY);\n if (existing) {\n return existing;\n }\n const generated = uuidv4();\n window.localStorage.setItem(DEVICE_STORAGE_KEY, generated);\n return generated;\n } catch (error) {\n debugLogger.warn(\"conversationSyncStore: unable to access localStorage, generating volatile device id\", { error });\n return uuidv4();\n }\n}\n\nfunction getPackageDefaultAdvancedKnowledgeSync(): boolean | undefined {\n return usePackageSettingsStore.getState().settings?.advancedKnowledgeSyncDefaultEnabled;\n}\n\nfunction mapConversationToDTO(conversation: Conversation): ConversationRecordDTO {\n const updatedAtIso = (conversation.updatedAt ?? new Date()).toISOString();\n const createdAtIso = conversation.createdAt ? conversation.createdAt.toISOString() : null;\n\n const history = conversation.history.map((entry, index) => {\n const turn: ConversationTurnDTO = {\n id: entry.id ?? `${conversation.id}-turn-${index}`,\n question: entry.question,\n answer: entry.answer,\n memoryUpdated: entry.memoryUpdated,\n cancelled: entry.cancelled,\n };\n\n if (entry.sourceFiles?.length) {\n turn.sourceFiles = entry.sourceFiles.map((doc) => ({\n id: doc.id,\n name: doc.name,\n }));\n }\n\n return turn;\n });\n\n return {\n id: conversation.id,\n name: conversation.name,\n model: conversation.model,\n projectId: conversation.projectId ?? null,\n history,\n summary: conversation.summary,\n tags: conversation.tags,\n metadata: conversation.metadata,\n createdAt: createdAtIso,\n updatedAt: updatedAtIso,\n version: conversation.version ?? 0,\n updatedBy: conversation.updatedBy,\n deletedAt: conversation.deletedAt ?? null,\n summaryStatus: conversation.summaryStatus,\n summaryGeneratedAt: conversation.summaryGeneratedAt ? conversation.summaryGeneratedAt.toISOString() : undefined,\n } as ConversationRecordDTO;\n}\n\nfunction mapProjectToDTO(project: Project): ProjectRecordDTO {\n const updatedAtIso = project.updatedAt?.toISOString() ?? new Date().toISOString();\n const createdAtIso = project.createdAt?.toISOString() ?? null;\n\n return {\n id: project.id,\n name: project.name,\n description: project.description,\n color: project.color,\n order: project.order,\n conversationCount: project.conversationCount,\n lastActivityAt: project.lastActivityAt ? project.lastActivityAt.toISOString() : undefined,\n summary: project.summary,\n metadata: project.metadata,\n createdAt: createdAtIso,\n updatedAt: updatedAtIso,\n version: project.version ?? 0,\n updatedBy: project.updatedBy,\n deletedAt: project.deletedAt ?? null,\n } as ProjectRecordDTO;\n}\n\nfunction mapConversationFromDTO(dto: ConversationRecordDTO): Conversation {\n return {\n id: dto.id,\n name: dto.name,\n model: dto.model,\n projectId: dto.projectId ?? undefined,\n history: dto.history.map((turn) => ({\n question: turn.question,\n answer: turn.answer,\n sourceFiles: turn.sourceFiles?.map((doc) => ({\n id: doc.id,\n name: doc.name ?? \"\",\n content: \"\",\n })),\n memoryUpdated: turn.memoryUpdated,\n cancelled: turn.cancelled,\n })),\n summary: dto.summary ?? undefined,\n tags: dto.tags ?? undefined,\n metadata: dto.metadata ?? undefined,\n createdAt: dto.createdAt ? new Date(dto.createdAt) : undefined,\n updatedAt: dto.updatedAt ? new Date(dto.updatedAt) : undefined,\n version: dto.version,\n updatedBy: dto.updatedBy,\n deletedAt: dto.deletedAt ?? undefined,\n summaryStatus: dto.summaryStatus,\n summaryGeneratedAt: dto.summaryGeneratedAt ? new Date(dto.summaryGeneratedAt) : undefined,\n } as Conversation;\n}\n\nfunction mapProjectFromDTO(dto: ProjectRecordDTO): Project {\n return {\n id: dto.id,\n name: dto.name,\n description: dto.description,\n color: dto.color,\n order: dto.order,\n createdAt: dto.createdAt ? new Date(dto.createdAt) : new Date(),\n updatedAt: dto.updatedAt ? new Date(dto.updatedAt) : new Date(),\n conversationCount: dto.conversationCount,\n lastActivityAt: dto.lastActivityAt ? new Date(dto.lastActivityAt) : undefined,\n summary: dto.summary ?? undefined,\n metadata: dto.metadata ?? undefined,\n version: dto.version,\n updatedBy: dto.updatedBy,\n deletedAt: dto.deletedAt ?? undefined,\n } as Project;\n}\n\nasync function waitForInitialHydration(): Promise<void> {\n const ready = () =>\n useConversationStore.getState()._hasHydrated &&\n useProjectStore.getState()._hasHydrated;\n\n if (ready()) {\n debugLogger.debug('conversationSyncStore: hydration already complete');\n return;\n }\n\n await new Promise<void>((resolve) => {\n const checkAndResolve = () => {\n if (ready()) {\n unsubscribeConversation();\n unsubscribeProject();\n debugLogger.debug('conversationSyncStore: hydration complete (async wait)');\n resolve();\n }\n };\n\n const unsubscribeConversation = useConversationStore.subscribe((state, prevState) => {\n if (state._hasHydrated !== prevState._hasHydrated) {\n checkAndResolve();\n }\n });\n\n const unsubscribeProject = useProjectStore.subscribe((state, prevState) => {\n if (state._hasHydrated !== prevState._hasHydrated) {\n checkAndResolve();\n }\n });\n\n debugLogger.debug('conversationSyncStore: waiting for stores hydration');\n checkAndResolve();\n });\n}\n\nfunction buildConversationMeta(conversation: Conversation): ConversationMeta {\n return {\n updatedAtMs: conversation.updatedAt ? conversation.updatedAt.getTime() : 0,\n version: conversation.version,\n historyLength: conversation.history.length,\n };\n}\n\nfunction buildProjectMeta(project: Project): ProjectMeta {\n return {\n updatedAtMs: project.updatedAt ? project.updatedAt.getTime() : 0,\n version: project.version,\n order: project.order,\n };\n}\n\nfunction snapshotConversationMetaMap(conversations: Conversation[]): Map<string, ConversationMeta> {\n return new Map(\n conversations.map((conversation): [string, ConversationMeta] => [\n conversation.id,\n buildConversationMeta(conversation),\n ])\n );\n}\n\nfunction snapshotProjectMetaMap(projects: Project[]): Map<string, ProjectMeta> {\n return new Map(\n projects.map((project): [string, ProjectMeta] => [\n project.id,\n buildProjectMeta(project),\n ])\n );\n}\n\nfunction ensureTrackersInitialized() {\n if (!conversationUnsubscribe) {\n const initialState = useConversationStore.getState();\n conversationsMeta = snapshotConversationMetaMap(initialState.conversations);\n\n const handleConversationChange = (\n state: ConversationStoreState,\n _prevState: ConversationStoreState\n ) => {\n const conversations = state.conversations;\n debugLogger.debug('conversationSyncStore: conversation store changed', { count: conversations.length });\n\n if (!state._hasHydrated) {\n conversationsMeta = snapshotConversationMetaMap(conversations);\n return;\n }\n\n if (suppressTracking) {\n conversationsMeta = snapshotConversationMetaMap(conversations);\n return;\n }\n\n const nextMeta = snapshotConversationMetaMap(conversations);\n for (const conversation of conversations) {\n const previous = conversationsMeta.get(conversation.id);\n const updatedAtMs = conversation.updatedAt ? conversation.updatedAt.getTime() : 0;\n\n if (!previous) {\n debugLogger.debug('conversationSyncStore: detected new conversation', { id: conversation.id });\n queueConversationUpsert(conversation.id);\n continue;\n }\n\n if (\n previous.updatedAtMs !== updatedAtMs ||\n previous.version !== conversation.version ||\n previous.historyLength !== conversation.history.length\n ) {\n debugLogger.debug('conversationSyncStore: detected conversation change', { id: conversation.id });\n queueConversationUpsert(conversation.id);\n }\n }\n\n for (const id of conversationsMeta.keys()) {\n if (!nextMeta.has(id)) {\n debugLogger.debug('conversationSyncStore: detected conversation removal', { id });\n queueConversationDelete(id);\n }\n }\n\n conversationsMeta = nextMeta;\n };\n\n conversationUnsubscribe = useConversationStore.subscribe(handleConversationChange);\n handleConversationChange(initialState, initialState);\n }\n\n if (!projectUnsubscribe) {\n const initialState = useProjectStore.getState();\n projectsMeta = snapshotProjectMetaMap(initialState.projects);\n\n const handleProjectChange = (state: ProjectStoreState, _prevState: ProjectStoreState) => {\n const projects = state.projects;\n debugLogger.debug('conversationSyncStore: project store changed', { count: projects.length });\n\n if (!state._hasHydrated) {\n projectsMeta = snapshotProjectMetaMap(projects);\n return;\n }\n\n if (suppressTracking) {\n projectsMeta = snapshotProjectMetaMap(projects);\n return;\n }\n\n const nextMeta = snapshotProjectMetaMap(projects);\n for (const project of projects) {\n const previous = projectsMeta.get(project.id);\n const updatedAtMs = project.updatedAt ? project.updatedAt.getTime() : 0;\n\n if (!previous) {\n debugLogger.debug('conversationSyncStore: detected new project', { id: project.id });\n queueProjectUpsert(project.id);\n continue;\n }\n\n if (\n previous.updatedAtMs !== updatedAtMs ||\n previous.version !== project.version ||\n previous.order !== project.order\n ) {\n debugLogger.debug('conversationSyncStore: detected project change', { id: project.id });\n queueProjectUpsert(project.id);\n }\n }\n\n for (const id of projectsMeta.keys()) {\n if (!nextMeta.has(id)) {\n debugLogger.debug('conversationSyncStore: detected project removal', { id });\n queueProjectDelete(id);\n }\n }\n\n projectsMeta = nextMeta;\n };\n\n projectUnsubscribe = useProjectStore.subscribe(handleProjectChange);\n handleProjectChange(initialState, initialState);\n }\n}\n\nif (typeof window !== 'undefined') {\n window.addEventListener(CONVERSATION_UPSERT_EVENT, (event) => {\n const id = (event as CustomEvent<string>).detail;\n if (id && !suppressTracking) {\n queueConversationUpsert(id);\n }\n });\n\n window.addEventListener(CONVERSATION_DELETE_EVENT, (event) => {\n const id = (event as CustomEvent<string>).detail;\n if (id && !suppressTracking) {\n queueConversationDelete(id);\n }\n });\n\n window.addEventListener(PROJECT_UPSERT_EVENT, (event) => {\n const id = (event as CustomEvent<string>).detail;\n if (id && !suppressTracking) {\n queueProjectUpsert(id);\n }\n });\n\n window.addEventListener(PROJECT_DELETE_EVENT, (event) => {\n const id = (event as CustomEvent<string>).detail;\n if (id && !suppressTracking) {\n queueProjectDelete(id);\n }\n });\n}\n\nexport function flagConversationUpsert(id: string) {\n queueConversationUpsert(id);\n}\n\nexport function flagConversationDelete(id: string) {\n queueConversationDelete(id);\n}\n\nexport function flagProjectUpsert(id: string) {\n queueProjectUpsert(id);\n}\n\nexport function flagProjectDelete(id: string) {\n queueProjectDelete(id);\n}\n\nfunction queueConversationUpsert(id: string) {\n useConversationSyncStore.setState((state) => {\n const upserts = new Set(state.pendingConversationUpserts);\n const deletes = new Set(state.pendingConversationDeletes);\n deletes.delete(id);\n upserts.add(id);\n debugLogger.info('conversationSyncStore: queued conversation upsert', { id });\n return { pendingConversationUpserts: upserts, pendingConversationDeletes: deletes };\n });\n scheduleAutoSync();\n}\n\nfunction queueConversationDelete(id: string) {\n useConversationSyncStore.setState((state) => {\n const upserts = new Set(state.pendingConversationUpserts);\n const deletes = new Set(state.pendingConversationDeletes);\n upserts.delete(id);\n deletes.add(id);\n debugLogger.info('conversationSyncStore: queued conversation delete', { id });\n return { pendingConversationUpserts: upserts, pendingConversationDeletes: deletes };\n });\n scheduleAutoSync(true);\n}\n\nfunction queueProjectUpsert(id: string) {\n useConversationSyncStore.setState((state) => {\n const upserts = new Set(state.pendingProjectUpserts);\n const deletes = new Set(state.pendingProjectDeletes);\n deletes.delete(id);\n upserts.add(id);\n debugLogger.info('conversationSyncStore: queued project upsert', { id });\n return { pendingProjectUpserts: upserts, pendingProjectDeletes: deletes };\n });\n scheduleAutoSync();\n}\n\nfunction queueProjectDelete(id: string) {\n useConversationSyncStore.setState((state) => {\n const upserts = new Set(state.pendingProjectUpserts);\n const deletes = new Set(state.pendingProjectDeletes);\n upserts.delete(id);\n deletes.add(id);\n debugLogger.info('conversationSyncStore: queued project delete', { id });\n return { pendingProjectUpserts: upserts, pendingProjectDeletes: deletes };\n });\n scheduleAutoSync(true);\n}\n\nfunction scheduleAutoSync(prioritize = false) {\n const { syncEnabled, status } = useConversationSyncStore.getState();\n if (!syncEnabled) {\n return;\n }\n\n const delay = prioritize ? Math.min(1_000, AUTO_SYNC_DELAY_MS) : AUTO_SYNC_DELAY_MS;\n\n if (autoSyncTimeout) {\n clearTimeout(autoSyncTimeout);\n }\n\n if (status === 'syncing') {\n // Wait until current sync finishes; we'll schedule a follow-up once status changes\n autoSyncTimeout = setTimeout(() => scheduleAutoSync(prioritize), delay);\n return;\n }\n\n autoSyncTimeout = setTimeout(() => {\n autoSyncTimeout = null;\n useConversationSyncStore\n .getState()\n .runSync()\n .catch((error) => {\n debugLogger.error('conversationSyncStore: auto sync failed', { error });\n });\n }, delay);\n}\n\nasync function applyServerResults(response: ConversationSyncResponse) {\n const conversationUpserts = response.conversations.upserts.map(mapConversationFromDTO);\n const projectUpserts = response.projects.upserts.map(mapProjectFromDTO);\n\n suppressTracking = true;\n try {\n if (projectUpserts.length > 0) {\n await useProjectStore.getState().applyRemoteProjects(projectUpserts);\n projectsMeta = new Map(\n useProjectStore.getState().projects.map((project) => [project.id, buildProjectMeta(project)])\n );\n }\n\n if (conversationUpserts.length > 0) {\n await useConversationStore.getState().applyRemoteConversations(conversationUpserts);\n conversationsMeta = new Map(\n useConversationStore.getState().conversations.map((conversation) => [conversation.id, buildConversationMeta(conversation)])\n );\n }\n\n if (response.projects.deletes.length > 0) {\n await useProjectStore.getState().removeProjectsByIds(response.projects.deletes);\n projectsMeta = new Map(\n useProjectStore.getState().projects.map((project) => [project.id, buildProjectMeta(project)])\n );\n }\n\n if (response.conversations.deletes.length > 0) {\n await useConversationStore.getState().removeConversationsByIds(response.conversations.deletes);\n conversationsMeta = new Map(\n useConversationStore.getState().conversations.map((conversation) => [conversation.id, buildConversationMeta(conversation)])\n );\n }\n } finally {\n suppressTracking = false;\n }\n}\n\nexport const useConversationSyncStore = create<ConversationSyncState>((set, get) => ({\n initialized: false,\n syncEnabled: false,\n status: \"disabled\",\n lastSyncAt: null,\n cursor: null,\n lastError: null,\n keepLocalOnly: false,\n isAdvancedVectorFeaturesEnabled: getPackageDefaultAdvancedKnowledgeSync() ?? false,\n conflicts: null,\n deviceId: ensureDeviceId(),\n pendingConversationUpserts: new Set<string>(),\n pendingConversationDeletes: new Set<string>(),\n pendingProjectUpserts: new Set<string>(),\n pendingProjectDeletes: new Set<string>(),\n totalConversationsOnServer: undefined,\n totalProjectsOnServer: undefined,\n hasCompletedInitialUpload: false,\n warningConversations: [],\n oversizedConversations: [],\n\n async initialize() {\n if (get().initialized) {\n return;\n }\n\n ensureTrackersInitialized();\n\n const gatewayUrl = usePackageSettingsStore.getState().settings?.gatewayApiUrl;\n if (!gatewayUrl) {\n debugLogger.info(\"conversationSyncStore: gateway API URL not configured; sync disabled\");\n set({ initialized: true, status: \"disabled\", syncEnabled: false });\n return;\n }\n\n const token = authenticationService.getToken();\n if (!token) {\n debugLogger.info(\"conversationSyncStore: no authentication token; sync disabled until login\");\n set({ initialized: true, status: \"disabled\", syncEnabled: false });\n return;\n }\n\n try {\n await waitForInitialHydration();\n const preference = await fetchConversationSyncPreference();\n const { deviceId } = get();\n const isNewDevice = Boolean(\n preference.lastDeviceId && preference.lastDeviceId !== deviceId\n );\n\n if (isNewDevice) {\n debugLogger.info('conversationSyncStore: detected new device, resetting cursor for full hydration', {\n deviceId,\n lastDeviceId: preference.lastDeviceId,\n });\n }\n\n applyPreference(preference, set, get, {\n isNewDevice,\n override: {\n isAdvancedVectorFeaturesEnabled: get().isAdvancedVectorFeaturesEnabled,\n },\n });\n set({ initialized: true });\n if (preference.syncEnabled) {\n await get().runSync({ force: true });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Failed to load conversation sync preference\";\n debugLogger.error(\"conversationSyncStore: initialization failed\", { error: message });\n set({ initialized: true, status: \"error\", lastError: message });\n }\n },\n\n async setSyncEnabled(enabled: boolean) {\n const state = get();\n const { deviceId, keepLocalOnly = false, isAdvancedVectorFeaturesEnabled } = state;\n try {\n const preference = await updateConversationSyncPreference({\n syncEnabled: enabled,\n deviceId,\n keepLocalOnly,\n isAdvancedVectorFeaturesEnabled,\n });\n const isNewDevice = Boolean(\n preference.lastDeviceId && preference.lastDeviceId !== deviceId\n );\n\n if (isNewDevice) {\n debugLogger.info('conversationSyncStore: preference updated from different device, forcing full hydration', {\n deviceId,\n lastDeviceId: preference.lastDeviceId,\n });\n }\n\n applyPreference(preference, set, get, {\n isNewDevice,\n override: {\n isAdvancedVectorFeaturesEnabled,\n },\n });\n if (enabled) {\n set({ hasCompletedInitialUpload: false });\n }\n if (preference.syncEnabled) {\n await get().runSync({ force: true });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Failed to update sync preference\";\n debugLogger.error(\"conversationSyncStore: setSyncEnabled failed\", { error: message });\n set({ status: \"error\", lastError: message });\n }\n },\n\n async setAdvancedVectorFeaturesEnabled(enabled: boolean) {\n const state = get();\n const { deviceId, keepLocalOnly = false, syncEnabled } = state;\n try {\n const preference = await updateConversationSyncPreference({\n syncEnabled,\n deviceId,\n keepLocalOnly,\n isAdvancedVectorFeaturesEnabled: enabled,\n });\n\n const isNewDevice = Boolean(\n preference.lastDeviceId && preference.lastDeviceId !== deviceId\n );\n\n if (isNewDevice) {\n debugLogger.info('conversationSyncStore: preference updated from different device, forcing full hydration', {\n deviceId,\n lastDeviceId: preference.lastDeviceId,\n });\n }\n\n applyPreference(preference, set, get, {\n isNewDevice,\n override: {\n isAdvancedVectorFeaturesEnabled: enabled,\n },\n });\n if (preference.syncEnabled && preference.isAdvancedVectorFeaturesEnabled) {\n await get().runSync({ force: true });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Failed to update advanced knowledge setting\";\n debugLogger.error(\"conversationSyncStore: setAdvancedVectorFeaturesEnabled failed\", { error: message });\n set({ status: \"error\", lastError: message });\n throw error;\n }\n },\n\n async runSync({ force = false } = {}) {\n await waitForInitialHydration();\n const stateBefore = get();\n debugLogger.info('conversationSyncStore: runSync invoked', {\n force,\n syncEnabled: stateBefore.syncEnabled,\n status: stateBefore.status,\n pendingConversationUpserts: stateBefore.pendingConversationUpserts.size,\n pendingConversationDeletes: stateBefore.pendingConversationDeletes.size,\n pendingProjectUpserts: stateBefore.pendingProjectUpserts.size,\n pendingProjectDeletes: stateBefore.pendingProjectDeletes.size,\n cursor: stateBefore.cursor,\n lastSyncAt: stateBefore.lastSyncAt,\n });\n const state = get();\n if (!state.syncEnabled && !force) {\n debugLogger.info('conversationSyncStore: runSync aborted - sync disabled and not forced');\n return;\n }\n if (state.status === \"syncing\") {\n debugLogger.debug('conversationSyncStore: runSync aborted - already syncing');\n return;\n }\n\n const gatewayUrl = usePackageSettingsStore.getState().settings?.gatewayApiUrl;\n if (!gatewayUrl) {\n set({ status: \"error\", lastError: \"Gateway API URL is not configured.\" });\n debugLogger.error('conversationSyncStore: runSync error - missing gateway URL');\n return;\n }\n\n const token = authenticationService.getToken();\n if (!token) {\n set({ status: \"error\", lastError: \"Authentication required to sync conversations.\" });\n debugLogger.error('conversationSyncStore: runSync error - missing auth token');\n return;\n }\n\n const pendingConversationIds = Array.from(state.pendingConversationUpserts);\n const pendingConversationDeleteIds = Array.from(state.pendingConversationDeletes);\n const pendingProjectIds = Array.from(state.pendingProjectUpserts);\n const pendingProjectDeleteIds = Array.from(state.pendingProjectDeletes);\n\n const conversationStore = useConversationStore.getState();\n const projectStore = useProjectStore.getState();\n\n const conversationCandidates = pendingConversationIds\n .map((id) => conversationStore.conversations.find((c) => c.id === id))\n .filter(Boolean) as Conversation[];\n\n let {\n allowed: conversationPayloads,\n warnings: warningConversations,\n oversized: oversizedConversations,\n } = analyzeConversations(conversationCandidates);\n\n let projectPayloads = pendingProjectIds\n .map((id) => projectStore.projects.find((p) => p.id === id))\n .filter(Boolean)\n .map((project) => mapProjectToDTO(project as Project));\n\n const isInitialSync = state.cursor == null;\n const shouldBootstrapSnapshot = !state.hasCompletedInitialUpload;\n\n const payloadDebug = {\n pendingConversationIds,\n pendingConversationDeleteIds,\n pendingProjectIds,\n pendingProjectDeleteIds,\n totalConversationsLocal: conversationStore.conversations.length,\n totalProjectsLocal: projectStore.projects.length,\n isInitialSync,\n shouldBootstrapSnapshot,\n };\n debugLogger.info('conversationSyncStore: preparing sync payload', payloadDebug);\n\n if (\n (isInitialSync || shouldBootstrapSnapshot) &&\n conversationPayloads.length === 0 &&\n pendingConversationDeleteIds.length === 0 &&\n projectPayloads.length === 0 &&\n pendingProjectDeleteIds.length === 0\n ) {\n const analysis = analyzeConversations(conversationStore.conversations);\n conversationPayloads = analysis.allowed;\n warningConversations = analysis.warnings;\n oversizedConversations = analysis.oversized;\n projectPayloads = projectStore.projects.map((project) => mapProjectToDTO(project));\n const bootInfo = {\n conversationCount: conversationPayloads.length,\n projectCount: projectPayloads.length,\n };\n debugLogger.info('conversationSyncStore: bootstrapping initial snapshot', bootInfo);\n }\n\n if (!force &&\n conversationPayloads.length === 0 &&\n pendingConversationDeleteIds.length === 0 &&\n projectPayloads.length === 0 &&\n pendingProjectDeleteIds.length === 0\n ) {\n // Nothing to push; still pull deltas if cursor exists\n if (!state.cursor) {\n debugLogger.debug('conversationSyncStore: runSync early exit - nothing to push and no cursor');\n set((current) => ({\n warningConversations,\n oversizedConversations,\n lastError: oversizedConversations.length ? buildOversizedMessage(oversizedConversations) : null,\n status: oversizedConversations.length ? 'error' : current.syncEnabled ? 'idle' : current.status,\n }));\n return;\n }\n }\n\n set({ status: \"syncing\", lastError: null });\n debugLogger.info('conversationSyncStore: issuing sync request', {\n conversationUpserts: conversationPayloads.length,\n conversationDeletes: pendingConversationDeleteIds.length,\n projectUpserts: projectPayloads.length,\n projectDeletes: pendingProjectDeleteIds.length,\n cursor: state.cursor,\n });\n\n const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n const request: ConversationSyncRequest = {\n deviceId: state.deviceId,\n cursor: state.cursor ?? undefined,\n timezone,\n payloadVersion: PAYLOAD_VERSION,\n changes: {\n conversations: {\n upserts: conversationPayloads,\n deletes: pendingConversationDeleteIds,\n },\n projects: {\n upserts: projectPayloads,\n deletes: pendingProjectDeleteIds,\n },\n },\n };\n\n try {\n let response = await syncConversations(request);\n await applyServerResults(response);\n\n let nextCursor = response.nextCursor?.token ?? state.cursor ?? null;\n let totalConversations = response.conversations.totalCount;\n let totalProjects = response.projects.totalCount;\n let conflicts = response.conflicts;\n\n while (response.hasMore) {\n const followUpRequest: ConversationSyncRequest = {\n deviceId: state.deviceId,\n cursor: response.nextCursor?.token ?? nextCursor ?? undefined,\n timezone,\n payloadVersion: PAYLOAD_VERSION,\n changes: {\n conversations: { upserts: [], deletes: [] },\n projects: { upserts: [], deletes: [] },\n },\n };\n response = await syncConversations(followUpRequest);\n await applyServerResults(response);\n nextCursor = response.nextCursor?.token ?? nextCursor;\n totalConversations = response.conversations.totalCount;\n totalProjects = response.projects.totalCount;\n conflicts = {\n conversationConflicts: [\n ...conflicts.conversationConflicts,\n ...response.conflicts.conversationConflicts,\n ],\n projectConflicts: [\n ...conflicts.projectConflicts,\n ...response.conflicts.projectConflicts,\n ],\n };\n }\n\n const sentConversationIds = new Set(conversationPayloads.map((c) => c.id));\n const sentProjectIds = new Set(projectPayloads.map((p) => p.id));\n const sentConversationDeleteIds = new Set(pendingConversationDeleteIds);\n const sentProjectDeleteIds = new Set(pendingProjectDeleteIds);\n\n set((current) => {\n const nextConversationUpserts = new Set(current.pendingConversationUpserts);\n const nextConversationDeletes = new Set(current.pendingConversationDeletes);\n const nextProjectUpserts = new Set(current.pendingProjectUpserts);\n const nextProjectDeletes = new Set(current.pendingProjectDeletes);\n\n for (const id of sentConversationIds) {\n nextConversationUpserts.delete(id);\n }\n for (const id of sentConversationDeleteIds) {\n nextConversationDeletes.delete(id);\n }\n for (const id of sentProjectIds) {\n nextProjectUpserts.delete(id);\n }\n for (const id of sentProjectDeleteIds) {\n nextProjectDeletes.delete(id);\n }\n\n const hasOversized = oversizedConversations.length > 0;\n\n return {\n status: hasOversized ? \"error\" : current.syncEnabled ? \"idle\" : \"disabled\",\n cursor: nextCursor,\n lastSyncAt: new Date().toISOString(),\n conflicts,\n totalConversationsOnServer: totalConversations,\n totalProjectsOnServer: totalProjects,\n pendingConversationUpserts: nextConversationUpserts,\n pendingConversationDeletes: nextConversationDeletes,\n pendingProjectUpserts: nextProjectUpserts,\n pendingProjectDeletes: nextProjectDeletes,\n hasCompletedInitialUpload: true,\n warningConversations,\n oversizedConversations,\n lastError: hasOversized ? buildOversizedMessage(oversizedConversations) : null,\n };\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Conversation sync failed\";\n debugLogger.error(\"conversationSyncStore: runSync failed\", { error: message });\n set({ status: \"error\", lastError: message });\n }\n },\n\n registerError(error: string) {\n set({ status: \"error\", lastError: error });\n },\n\n clearConflicts() {\n set({ conflicts: null });\n },\n}));\n\nfunction applyPreference(\n preference: ConversationSyncPreferenceDTO,\n set: (partial: Partial<ConversationSyncState>) => void,\n getState: () => ConversationSyncState,\n options?: {\n isNewDevice?: boolean;\n override?: Partial<Pick<ConversationSyncState, 'isAdvancedVectorFeaturesEnabled'>>;\n }\n) {\n const isNewDevice = options?.isNewDevice ?? false;\n const current = getState();\n const override = options?.override ?? {};\n\n const preferenceVectorFlag = preference.isAdvancedVectorFeaturesEnabled;\n const overrideVectorFlag = override.isAdvancedVectorFeaturesEnabled;\n const packageDefaultVectorFlag = getPackageDefaultAdvancedKnowledgeSync();\n const resolvedVectorFlag =\n preferenceVectorFlag !== undefined\n ? preferenceVectorFlag\n : overrideVectorFlag !== undefined\n ? overrideVectorFlag\n : packageDefaultVectorFlag !== undefined\n ? packageDefaultVectorFlag\n : current.isAdvancedVectorFeaturesEnabled ?? false;\n\n set({\n syncEnabled: preference.syncEnabled,\n status: preference.syncEnabled ? \"idle\" : \"disabled\",\n lastSyncAt: isNewDevice ? null : preference.lastSyncAt ?? null,\n cursor: isNewDevice ? null : preference.cursor ?? null,\n keepLocalOnly: preference.keepLocalOnly,\n isAdvancedVectorFeaturesEnabled: resolvedVectorFlag,\n lastError: null,\n hasCompletedInitialUpload:\n preference.syncEnabled && preference.lastSyncAt != null && !isNewDevice,\n warningConversations: [],\n oversizedConversations: [],\n });\n}\n\nfunction analyzeConversations(conversations: Conversation[]): {\n allowed: ConversationRecordDTO[];\n warnings: ConversationSizeNotice[];\n oversized: ConversationSizeNotice[];\n} {\n const allowed: ConversationRecordDTO[] = [];\n const warnings: ConversationSizeNotice[] = [];\n const oversized: ConversationSizeNotice[] = [];\n const encoder = new TextEncoder();\n\n for (const conversation of conversations) {\n const dto = mapConversationToDTO(conversation);\n const sizeBytes = encoder.encode(JSON.stringify(dto)).length;\n const notice: ConversationSizeNotice = {\n id: conversation.id,\n name: conversation.name,\n sizeBytes,\n limitBytes: MAX_CONVERSATION_BYTES,\n };\n if (sizeBytes >= MAX_CONVERSATION_BYTES) {\n oversized.push(notice);\n continue;\n }\n if (sizeBytes >= WARN_CONVERSATION_BYTES) {\n warnings.push(notice);\n }\n allowed.push(dto);\n }\n\n return { allowed, warnings, oversized };\n}\n\nfunction buildOversizedMessage(notices: ConversationSizeNotice[]): string {\n if (!notices.length) {\n return '';\n }\n const names = notices.map((n) => `\"${n.name || 'Untitled'}\"`).join(', ');\n return `Some conversations (${names}) are too large for Bandit Cloud. Start a new conversation or archive older turns to continue syncing.`;\n}\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-ECF9-6DA236\nconst __banditFingerprint_conversationSync_conversationSyncServicets = 'BL-FP-63F1FF-931F';\nconst __auditTrail_conversationSync_conversationSyncServicets = 'BL-AU-MGOIKVVS-90K4';\n// File: conversationSyncService.ts | Path: src/services/conversationSync/conversationSyncService.ts | Hash: ecf9931f\n\nimport { authenticationService } from \"../auth/authenticationService\";\nimport { usePackageSettingsStore } from \"../../store/packageSettingsStore\";\nimport { debugLogger } from \"../logging/debugLogger\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst getString = (record: Record<string, unknown>, key: string): string | undefined => {\n const value = record[key];\n return typeof value === 'string' ? value : undefined;\n};\n\nclass HttpResponseError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly payload: unknown,\n public readonly code?: string\n ) {\n super(message);\n this.name = 'HttpResponseError';\n }\n}\n\nexport interface SyncMetadataDTO {\n version: number;\n updatedAt: string;\n updatedBy?: string;\n deletedAt?: string | null;\n}\n\nexport interface KnowledgeDocRefDTO {\n id: string;\n name?: string;\n}\n\nexport interface ConversationTurnDTO {\n id: string;\n question: string;\n answer: string;\n images?: string[];\n sourceFiles?: KnowledgeDocRefDTO[];\n memoryUpdated?: boolean;\n cancelled?: boolean;\n}\n\nexport interface ConversationRecordDTO extends SyncMetadataDTO {\n id: string;\n name: string;\n model: string;\n projectId?: string | null;\n history: ConversationTurnDTO[];\n summary?: string;\n tags?: string[];\n metadata?: Record<string, unknown>;\n createdAt?: string | null;\n summaryStatus?: string;\n summaryGeneratedAt?: string;\n}\n\nexport interface ProjectRecordDTO extends SyncMetadataDTO {\n id: string;\n name: string;\n description?: string;\n color?: string;\n order: number;\n conversationCount?: number;\n lastActivityAt?: string;\n summary?: string;\n metadata?: Record<string, unknown>;\n createdAt?: string | null;\n}\n\nexport interface ConversationSyncPreferenceDTO {\n syncEnabled: boolean;\n lastSyncAt?: string | null;\n cursor?: string | null;\n lastDeviceId?: string | null;\n keepLocalOnly?: boolean;\n isAdvancedVectorFeaturesEnabled?: boolean;\n}\n\nexport interface ConversationSyncRequest {\n deviceId: string;\n cursor?: string | null;\n timezone?: string;\n payloadVersion: number;\n changes: {\n conversations: {\n upserts: ConversationRecordDTO[];\n deletes: string[];\n };\n projects: {\n upserts: ProjectRecordDTO[];\n deletes: string[];\n };\n };\n}\n\nexport interface ConflictRecordDTO<T> {\n id: string;\n server: T;\n client?: T;\n reason: 'version_mismatch' | 'missing_dependency' | 'validation_error';\n message?: string;\n}\n\nexport interface ConversationSyncResponse {\n nextCursor?: {\n token: string;\n expiresAt?: string;\n } | null;\n conversations: {\n upserts: ConversationRecordDTO[];\n deletes: string[];\n totalCount: number;\n };\n projects: {\n upserts: ProjectRecordDTO[];\n deletes: string[];\n totalCount: number;\n };\n conflicts: {\n conversationConflicts: ConflictRecordDTO<ConversationRecordDTO>[];\n projectConflicts: ConflictRecordDTO<ProjectRecordDTO>[];\n };\n hasMore: boolean;\n}\n\nfunction buildUrl(path: string): string {\n const base = usePackageSettingsStore.getState().settings?.gatewayApiUrl?.replace(/\\/$/, \"\");\n if (base) {\n const normalized = path.startsWith('/') ? path : `/${path}`;\n return `${base}${normalized}`;\n }\n return path;\n}\n\nfunction buildHeaders(): HeadersInit {\n const headers: HeadersInit = { 'Content-Type': 'application/json' };\n const token = authenticationService.getToken();\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n return headers;\n}\n\nasync function handleJsonResponse<T>(response: Response, fallbackMessage: string): Promise<T> {\n let data: unknown = null;\n try {\n data = await response.json();\n } catch (error) {\n debugLogger.warn('conversationSyncService: failed to parse JSON response', { error });\n }\n\n if (!response.ok) {\n const record = isRecord(data) ? data : {};\n const message =\n getString(record, 'error') ||\n getString(record, 'message') ||\n getString(record, 'detail') ||\n fallbackMessage;\n const code = getString(record, 'code') || getString(record, 'error_code');\n throw new HttpResponseError(message, response.status, data, code);\n }\n\n return data as T;\n}\n\nexport async function fetchConversationSyncPreference(): Promise<ConversationSyncPreferenceDTO> {\n const url = buildUrl('/v1/preferences/conversation-sync');\n const headers = buildHeaders();\n try {\n const response = await fetch(url, { method: 'GET', headers });\n return await handleJsonResponse<ConversationSyncPreferenceDTO>(response, 'Failed to load conversation sync preference');\n } catch (error) {\n debugLogger.error('conversationSyncService: failed to fetch sync preference', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n}\n\nexport async function updateConversationSyncPreference(body: {\n syncEnabled: boolean;\n deviceId?: string;\n keepLocalOnly?: boolean;\n isAdvancedVectorFeaturesEnabled: boolean;\n}): Promise<ConversationSyncPreferenceDTO> {\n const url = buildUrl('/v1/preferences/conversation-sync');\n const headers = buildHeaders();\n try {\n const response = await fetch(url, {\n method: 'PUT',\n headers,\n body: JSON.stringify(body),\n });\n return await handleJsonResponse<ConversationSyncPreferenceDTO>(response, 'Failed to update conversation sync preference');\n } catch (error) {\n debugLogger.error('conversationSyncService: failed to update sync preference', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n}\n\nexport async function syncConversations(request: ConversationSyncRequest): Promise<ConversationSyncResponse> {\n const url = buildUrl('/v1/conversations/sync');\n const headers = buildHeaders();\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(request),\n });\n return await handleJsonResponse<ConversationSyncResponse>(response, 'Failed to sync conversations');\n } catch (error) {\n debugLogger.error('conversationSyncService: sync request failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n}\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-05A8-49CD8F\nconst __banditFingerprint_store_knowledgeStorets = 'BL-FP-602E09-4421';\nconst __auditTrail_store_knowledgeStorets = 'BL-AU-MGOIKVW4-CU0K';\n// File: knowledgeStore.ts | Path: src/store/knowledgeStore.ts | Hash: 05a84421\n\nimport { create } from \"zustand\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\n\nexport interface KnowledgeDoc {\n id: string;\n name: string;\n content: string;\n embedding?: number[];\n rawData?: string;\n type?: string;\n addedDate?: Date;\n size?: number;\n uploadedBy?: string;\n userEmail?: string;\n bucket?: string;\n key?: string; \n\n isUserContent?: boolean;\n isTeamContent?: boolean;\n contentSource?: 'user' | 'team';\n teamSid?: string;\n\n mimeType?: string;\n originalFileName?: string;\n s3Url?: string;\n}\n\ninterface KnowledgeStore {\n docs: KnowledgeDoc[];\n isLoaded: boolean;\n addDoc: (doc: Omit<KnowledgeDoc, \"id\">) => void;\n removeDoc: (id: string) => void;\n clearDocs: () => void;\n loadDocs: () => Promise<void>;\n saveDocs: () => Promise<void>;\n}\n\nexport const useKnowledgeStore = create<KnowledgeStore>((set, get) => ({\n docs: [],\n isLoaded: false,\n \n addDoc: (doc) => {\n const current = get().docs;\n if (current.length >= 20) {\n debugLogger.warn(\"⚠️ Maximum of 20 knowledge docs reached.\");\n return;\n }\n\n const newDoc: KnowledgeDoc = {\n id: uuidv4(),\n name: doc.name,\n content: doc.content,\n embedding: doc.embedding,\n rawData: doc.rawData,\n mimeType: doc.mimeType,\n originalFileName: doc.originalFileName,\n s3Url: doc.s3Url,\n type: doc.type,\n addedDate: doc.addedDate,\n size: doc.size,\n uploadedBy: doc.uploadedBy,\n userEmail: doc.userEmail,\n bucket: doc.bucket,\n key: doc.key,\n isUserContent: doc.isUserContent,\n isTeamContent: doc.isTeamContent,\n contentSource: doc.contentSource,\n };\n\n set({ docs: [...current, newDoc] });\n \n // Save individual doc to IndexedDB\n (async () => {\n try {\n const storeConfigs = [{ name: \"documents\", keyPath: \"id\" }];\n await indexedDBService.put(\"banditKnowledge\", 1, \"documents\", newDoc, storeConfigs);\n debugLogger.debug(\"Knowledge doc added to IndexedDB\", { id: newDoc.id, name: newDoc.name });\n } catch (error) {\n debugLogger.error(\"Failed to save new knowledge doc to IndexedDB\", { error });\n }\n })();\n },\n \n removeDoc: (id) => {\n set((state) => ({\n docs: state.docs.filter((d) => d.id !== id),\n }));\n \n // Remove from IndexedDB\n (async () => {\n try {\n const storeConfigs = [{ name: \"documents\", keyPath: \"id\" }];\n await indexedDBService.delete(\"banditKnowledge\", 1, \"documents\", id, storeConfigs);\n debugLogger.debug(\"Knowledge doc removed from IndexedDB\", { id });\n } catch (error) {\n debugLogger.error(\"Failed to remove knowledge doc from IndexedDB\", { error });\n }\n })();\n },\n \n clearDocs: () => {\n set({ docs: [] });\n \n // Clear IndexedDB\n (async () => {\n try {\n const storeConfigs = [{ name: \"documents\", keyPath: \"id\" }];\n await indexedDBService.clear(\"banditKnowledge\", 1, \"documents\", storeConfigs);\n debugLogger.debug(\"All knowledge docs cleared from IndexedDB\");\n } catch (error) {\n debugLogger.error(\"Failed to clear knowledge docs from IndexedDB\", { error });\n }\n })();\n },\n \n loadDocs: async () => {\n try {\n const storeConfigs = [{ name: \"documents\", keyPath: \"id\" }];\n const docs = await indexedDBService.getAll<KnowledgeDoc>(\"banditKnowledge\", 1, \"documents\", storeConfigs);\n \n set({ \n docs: docs || [],\n isLoaded: true \n });\n debugLogger.info(\"Knowledge docs loaded from IndexedDB\", { count: docs?.length || 0 });\n } catch (error) {\n debugLogger.error(\"Failed to load knowledge docs from IndexedDB\", { error });\n set({ isLoaded: true }); // Mark as loaded even if failed, so UI can render\n }\n },\n \n saveDocs: async () => {\n try {\n const { docs } = get();\n const storeConfigs = [{ name: \"documents\", keyPath: \"id\" }];\n \n // Clear existing docs and save new ones individually\n await indexedDBService.clear(\"banditKnowledge\", 1, \"documents\", storeConfigs);\n \n for (const doc of docs) {\n await indexedDBService.put(\"banditKnowledge\", 1, \"documents\", doc, storeConfigs);\n }\n \n debugLogger.debug(\"Knowledge docs saved to IndexedDB\", { count: docs.length });\n } catch (error) {\n debugLogger.error(\"Failed to save knowledge docs to IndexedDB\", { error });\n }\n },\n}));","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-881F-0475DF\nconst __banditFingerprint_utilts = 'BL-FP-8CD496-6839';\nconst __auditTrail_utilts = 'BL-AU-MGOIKVW9-4I28';\n// File: util.ts | Path: src/util.ts | Hash: 881f6839\n\nimport { debugLogger } from \"./services/logging/debugLogger\";\n\nexport const toTitleCase = (str: string) => str.toLowerCase().split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')\n\n/**\n * Generates a random number between min and max (inclusive).\n * @param min the minimum value \n * @param max the maximum value \n * @returns \n */\nexport const randomRange = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;\n\nexport const generateSeed = () => Math.floor(Math.random() * 10000)\n\nexport const fetchAndConvertToBase64 = async (src: string): Promise<string> => {\n const response = await fetch(src);\n const blob = await response.blob();\n return await new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onloadend = () => resolve(reader.result as string);\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n};\n\nexport const detectTransparency = (imageSrc: string): Promise<boolean> => {\n return new Promise((resolve) => {\n const img = new window.Image();\n img.crossOrigin = \"Anonymous\";\n img.onload = () => {\n const canvas = document.createElement(\"canvas\");\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return resolve(false);\n ctx.drawImage(img, 0, 0);\n const imageData = ctx.getImageData(0, 0, img.width, img.height).data;\n for (let i = 3; i < imageData.length; i += 4) {\n if (imageData[i] < 255) {\n debugLogger.debug(\"Detected transparency in image\");\n resolve(true);\n return;\n }\n }\n debugLogger.debug(\"No transparency detected in image\");\n resolve(false);\n };\n img.src = imageSrc;\n });\n};\n\nconst banditHead = \"https://cdn.burtson.ai/logos/bandit-head.png\";\n\nexport const modelAvatars: Record<string, string> = {\n \"Bandit-Core\": \"https://cdn.burtson.ai/avatars/core-avatar.png\",\n \"Bandit-Muse\": \"https://cdn.burtson.ai/avatars/muse-avatar.png\",\n \"Bandit-Logic\": \"https://cdn.burtson.ai/avatars/logic-avatar.png\",\n \"Bandit-D1VA\": \"https://cdn.burtson.ai/avatars/d1va-avatar.png\",\n \"Bandit-Exec\": \"https://cdn.burtson.ai/avatars/exec-avatar.png\",\n};\n\ntype ModelLike = {\n name?: string;\n avatarBase64?: string | null;\n};\n\nexport const resolveAvatar = (model: ModelLike | null | undefined): string => {\n // If no model provided, return banditHead URL\n if (!model) return banditHead;\n\n // If model has base64 avatar\n if (model.avatarBase64 && model.avatarBase64.startsWith(\"data:image\")) {\n return model.avatarBase64;\n }\n\n // If model is a known Bandit model\n const banditAvatar = model.name ? modelAvatars[model.name] : undefined;\n if (banditAvatar) {\n return banditAvatar;\n }\n\n return banditHead;\n};\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-E089-EB279A\nconst __banditFingerprint_notification_notificationServicets = 'BL-FP-FFADE7-4599';\nconst __auditTrail_notification_notificationServicets = 'BL-AU-MGOIKVVV-ZTFN';\n// File: notificationService.ts | Path: src/services/notification/notificationService.ts | Hash: e0894599\n\nimport { debugLogger } from '../logging/debugLogger';\nimport type { NotificationContextType } from '../../shared/components/NotificationProvider';\n\ntype HttpErrorShape = {\n response?: {\n status?: number;\n data?: Record<string, unknown>;\n };\n message?: string;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === 'object';\nconst getRecordString = (record: Record<string, unknown> | undefined, key: string): string | undefined =>\n record && typeof record[key] === 'string' ? (record[key] as string) : undefined;\n\n\n/**\n * Global notification handler that can be used throughout the application\n */\nexport class NotificationService {\n private notificationContext: NotificationContextType | null = null;\n\n /**\n * Set the notification context (usually called from a component that has access to useNotification)\n */\n setContext(context: NotificationContextType) {\n this.notificationContext = context;\n }\n\n /**\n * Show a generic notification\n */\n show(message: string, severity: 'success' | 'error' | 'warning' | 'info' = 'info') {\n if (this.notificationContext) {\n this.notificationContext.showNotification({ message, severity });\n } else {\n // Fallback to console logging if notification context is not available\n debugLogger.warn('Notification context not available, falling back to console:', { message, severity });\n console.warn(`[${severity.toUpperCase()}] ${message}`);\n }\n }\n\n /**\n * Show an error notification\n */\n showError(message: string) {\n this.show(message, 'error');\n }\n\n /**\n * Show a success notification\n */\n showSuccess(message: string) {\n this.show(message, 'success');\n }\n\n /**\n * Show a warning notification\n */\n showWarning(message: string) {\n this.show(message, 'warning');\n }\n\n /**\n * Show an info notification\n */\n showInfo(message: string) {\n this.show(message, 'info');\n }\n\n /**\n * Handle HTTP errors and show appropriate notifications\n */\n handleHttpError(error: unknown, customMessage?: string) {\n let message = customMessage || 'An error occurred';\n const httpError = error as HttpErrorShape;\n\n if (httpError?.response) {\n // HTTP error response\n const status = httpError.response?.status;\n const data = httpError.response?.data;\n \n // Extract detailed error information\n // For your API structure with nested error objects: { error: { message: \"...\", type: \"...\", code: \"...\" } }\n const nestedError = isRecord(data?.error) ? data.error : undefined;\n const errorMessage =\n getRecordString(nestedError, 'message') ||\n getRecordString(data, 'message') ||\n getRecordString(data, 'detail');\n const errorType =\n getRecordString(nestedError, 'type') ||\n getRecordString(data, 'type');\n const errorCode =\n getRecordString(nestedError, 'code') ||\n getRecordString(data, 'code') ||\n getRecordString(data, 'error_code') ||\n (typeof data?.error === 'string' ? data.error : undefined);\n \n // Debug logging to see what we're extracting\n debugLogger.info('Processing HTTP error response:', {\n status,\n errorMessage,\n errorType,\n errorCode,\n rawData: data\n });\n \n // Build detailed message with error code and specific message\n const buildDetailedMessage = (defaultMsg: string) => {\n // If we have a specific error message, prioritize showing that\n if (errorMessage) {\n // For detailed error messages like yours, just show the message directly\n // as it's already comprehensive and user-friendly\n return errorMessage;\n } else if (errorCode) {\n // If we only have an error code, show it with context\n return `Error: ${errorCode}`;\n } else if (errorType) {\n // If we only have an error type, show it with context\n return `Error: ${errorType}`;\n } else {\n // For 400-level errors without specific messages, include status code\n if (typeof status === 'number' && status >= 400 && status < 500) {\n return `HTTP ${status}: ${defaultMsg}`;\n }\n return defaultMsg;\n }\n };\n\n switch (status) {\n case 400:\n message = buildDetailedMessage('Bad request - please check your input');\n break;\n case 401:\n message = buildDetailedMessage('Authentication required - please log in');\n break;\n case 403:\n message = buildDetailedMessage('Access denied - you don\\'t have permission for this action');\n break;\n case 404:\n message = buildDetailedMessage('Resource not found');\n break;\n case 422:\n message = buildDetailedMessage('Validation failed - please check your input');\n break;\n case 429:\n message = buildDetailedMessage('Too many requests - please try again later');\n break;\n case 500:\n message = buildDetailedMessage('Server error - please try again later');\n break;\n case 502:\n case 503:\n case 504:\n message = buildDetailedMessage('Service temporarily unavailable - please try again later');\n break;\n default:\n // For any other 400-level errors, show detailed info\n if (typeof status === 'number' && status >= 400 && status < 500) {\n message = buildDetailedMessage(`Client error (${typeof status === 'number' ? status : 'unknown'})`);\n } else {\n message = buildDetailedMessage(`Request failed with status ${typeof status === 'number' ? status : 'unknown'}`);\n }\n }\n } else if (httpError?.message) {\n message = httpError.message;\n }\n\n debugLogger.error('HTTP Error handled by notification service:', { error, message });\n this.showError(message);\n }\n\n /**\n * Handle network/connection errors\n */\n handleNetworkError(error: unknown, customMessage?: string) {\n const message = customMessage || 'Network error - please check your connection and try again';\n debugLogger.error('Network Error handled by notification service:', { error, message });\n this.showError(message);\n }\n\n /**\n * Handle validation errors\n */\n handleValidationError(errors: readonly string[] | string, customMessage?: string) {\n let message: string;\n if (typeof customMessage === 'string' && customMessage.length > 0) {\n message = customMessage;\n } else if (Array.isArray(errors)) {\n message = (errors as readonly string[]).join(', ');\n } else {\n message = errors as string;\n }\n debugLogger.warn('Validation Error handled by notification service:', { errors, message });\n this.showWarning(message);\n }\n}\n\nexport const notificationService = new NotificationService();\nexport default notificationService;\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-0A5F-162413\nconst __banditFingerprint_prompts_conversationStartersts = 'BL-FP-AC04B3-EC33';\nconst __auditTrail_prompts_conversationStartersts = 'BL-AU-MGOIKVVX-L4QX';\n// File: conversationStarters.ts | Path: src/services/prompts/conversationStarters.ts | Hash: 0a5fec33\n\nimport { lastValueFrom, map } from \"rxjs\";\nimport { useAIProviderStore } from \"../../store/aiProviderStore\";\nimport { usePackageSettingsStore } from \"../../store/packageSettingsStore\";\nimport { getStableQuestionPrompt, QuestionPromptArgs } from \"../../prompts/getStableQuestionPrompt\";\nimport { debugLogger } from \"../logging/debugLogger\";\nimport { enhancePromptWithContext } from \"./promptUtils\";\nimport { notificationService } from \"../notification/notificationService\";\n\n/**\n * Generates conversation starter prompts based on topics of interest.\n * \n * @param parameters - Parameters for generating conversation starters\n * @param parameters.limit - Number of questions to generate (1-10)\n * @param parameters.topicOfInterest - Default topic e.g \"sports, travel, technology, coding, .NET, kite flying, etc.\"\n * @returns A promise that resolves to an array of conversation starters\n */\nexport const generateConversationStarters = async (args: QuestionPromptArgs): Promise<string[]> => {\n const provider = useAIProviderStore.getState().provider;\n if (!provider) {\n debugLogger.error(\"No AI provider available for generating conversation starters\");\n return [];\n }\n\n const modelName = usePackageSettingsStore.getState().settings?.defaultModel || \"default-model-fallback\";\n \n try {\n const data$ = provider.generate({\n model: modelName,\n prompt: enhancePromptWithContext(getStableQuestionPrompt(args)),\n stream: false,\n options: { temperature: 1.5, num_predict: 250 },\n });\n const questions$ = data$.pipe(map((d) => {\n const sanitizeLine = (line: string): string => {\n const withoutNumbering = line\n .replace(/^[0-9]+[.)\\-\\s:]+/, \"\")\n .replace(/^[•*+-]\\s+/, \"\");\n const withoutQuotes = withoutNumbering.replace(/^[“\"']+/, \"\").replace(/[”\"']+$/, \"\");\n const withoutEmoji = withoutQuotes.replace(/\\p{Extended_Pictographic}/gu, \"\");\n return withoutEmoji.trim().replace(/\\s+/g, \" \");\n };\n\n // Split by newlines and filter out empty/meaningless responses\n const sanitized = d.response\n .split(\"\\n\")\n .map((line) => sanitizeLine(line.trim()))\n .filter((line) => {\n const lower = line.toLowerCase();\n return (\n line.length > 10 &&\n line.includes(\"?\") &&\n !lower.includes(\"sorry\") &&\n !lower.includes(\"i cannot\") &&\n !lower.includes(\"i can't\") &&\n !lower.includes(\"unable to\") &&\n !lower.startsWith(\"as an ai\")\n );\n })\n .filter((line) => line.length > 0);\n\n // Deduplicate while preserving order\n const unique: string[] = [];\n const seen = new Set<string>();\n sanitized.forEach((line) => {\n const key = line\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}]+/gu, \" \")\n .trim();\n if (key && !seen.has(key)) {\n seen.add(key);\n unique.push(line);\n }\n });\n return unique;\n }));\n const starters = await lastValueFrom(questions$);\n \n // Only return meaningful conversation starters\n if (starters.length === 0) {\n debugLogger.warn(\"No meaningful conversation starters generated\");\n return [];\n }\n \n return starters.slice(0, args.limit);\n } catch (err) {\n debugLogger.error(\"❌ Failed to generate conversation starters:\", { error: err });\n \n // Show notification to user for conversation starter generation failures\n notificationService.handleHttpError(err);\n \n return [];\n }\n};\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-426C-2EC0F0\nconst __banditFingerprint_prompts_getStableQuestionPromptts = 'BL-FP-1BF51B-C535';\nconst __auditTrail_prompts_getStableQuestionPromptts = 'BL-AU-MGOIKVVP-0EFF';\n// File: getStableQuestionPrompt.ts | Path: src/prompts/getStableQuestionPrompt.ts | Hash: 426cc535\n\nimport { generateSeed, randomRange } from \"../util\";\nexport type GeneralTopicOfInterest = typeof TOPICS[number];\nexport const TOPICS = [\"everyday life\", \"finance\", \"sports\", \"travel\", \"technology\", \"politics\", \"health\", \"food\", \"entertainment\", \"education\", \"science\", \"history\", \"art\", \"music\", \"literature\", \"philosophy\", \"psychology\", \"sociology\", \"environmental issues\", \"current events\"] as const;\n\nexport const getRandomTopicOfInterest = (): GeneralTopicOfInterest => {\n const minIndex = 0;\n // Use length - 1 to get the last index because `randomRange` is inclusive\n const maxIndex = TOPICS.length - 1;\n const randomIndex = randomRange(minIndex, maxIndex);\n const randomTopic = TOPICS[randomIndex];\n return randomTopic;\n}\n\n\nexport interface QuestionPromptArgs {\n /**\n * Number of questions to generate (1-10)\n * Values outside this range will throw an error\n */\n limit: number;\n /**\n * Must be a string containing a topic of interest, prepositions, conjuctions, adverbs, and adjectives will produce undesirable results.\n * GOOD EXAMPLE: \"sports, travel, Mark Burtson, Bandit Labs, technology, coding, .NET, kite flying\"\n * BAD EXMAPLE: \"in, and, quickly, beautiful\" do not make sense as a topic of interest.\n */\n topicOfInterest: string;\n /**\n * Optional system prompt from the selected model to tailor suggestions\n */\n modelSystemPrompt?: string;\n}\n\n/**\n * @param limit - Number of questions to generate (1-10)\n * @param topicOfInterest - Default topic e.g \"sports, travel, being Mark Burtson, technology, coding, .NET, kite flying, etc.\" \n * @returns A prompt string for generating questions\n */\nexport const getStableQuestionPrompt = (args: QuestionPromptArgs): string => {\n const { limit, topicOfInterest, modelSystemPrompt } = args;\n if (limit < 1 || limit > 10) {\n throw new Error(\"Limit must be between 1 and 10\");\n }\n const seed = generateSeed();\n \n // Build the base prompt\n let prompt = `You are a helpful assistant.\n\nThe following seed uniquely identifies the topic: \"${seed}\"`;\n\n // Add model-specific context if available\n if (modelSystemPrompt && modelSystemPrompt.trim()) {\n prompt += `\n\nBased on this specialized assistant profile: \"${modelSystemPrompt.trim()}\"`;\n }\n\n prompt += `\n\nGenerate ${limit} concise (5–20 words, try to use this entire range), natural-sounding questions a user might ask${modelSystemPrompt ? ' this specialized assistant' : ' an AI assistant'}. These should be:\n\n- Relevant to ${topicOfInterest}`;\n\n // Add model-specific relevance if we have a system prompt\n if (modelSystemPrompt && modelSystemPrompt.trim()) {\n prompt += `\n- Aligned with the assistant's specialized capabilities and knowledge area`;\n }\n\n prompt += `\n- Specific enough to be practical\n- Easy to understand and not abstract\n\nDo not:\n- Refer to yourself or use phrases like \"As an AI...\"\n- Include greetings, explanations, or personality\n- Include jokes, fiction, or quotes\n- Number, bullet, or otherwise prefix the questions with extra characters\n- Repeat the same idea phrased differently — each question must explore a distinct angle or subtopic\n\nOutput only ${limit} questions — one per line, with no leading numbers, bullets, or prefixes.`;\n\n return prompt.trim();\n}\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-77E3-745FE7\nconst __banditFingerprint_prompts_promptUtilsts = 'BL-FP-11EE62-0A9F';\nconst __auditTrail_prompts_promptUtilsts = 'BL-AU-MGOIKVVY-OO1C';\n// File: promptUtils.ts | Path: src/services/prompts/promptUtils.ts | Hash: 77e30a9f\n\n/**\n * Utility functions for prompt context and formatting\n */\n\n/**\n * Gets the current date and time in a human-readable format for LLM context\n * @returns Formatted date string for prompt injection\n */\nexport const getCurrentDateTimeContext = (): string => {\n const now = new Date();\n \n // Format: \"Wednesday, July 3, 2025 at 2:45 PM PST\"\n const dateString = now.toLocaleDateString('en-US', {\n weekday: 'long',\n year: 'numeric',\n month: 'long',\n day: 'numeric'\n });\n \n const timeString = now.toLocaleTimeString('en-US', {\n hour: 'numeric',\n minute: '2-digit',\n timeZoneName: 'short'\n });\n \n return `${dateString} at ${timeString}`;\n};\n\n/**\n * Creates a standardized context header for prompts\n * @param includeDateTime - Whether to include current date/time\n * @returns Context header string\n */\nexport const createPromptContext = (includeDateTime: boolean = true): string => {\n if (!includeDateTime) {\n return '';\n }\n \n return `Current date and time: ${getCurrentDateTimeContext()}\\n\\n`;\n};\n\n/**\n * Wraps a prompt with standard context information\n * @param prompt - The main prompt content\n * @param includeDateTime - Whether to include current date/time context\n * @returns Enhanced prompt with context\n */\nexport const enhancePromptWithContext = (prompt: string, includeDateTime: boolean = true): string => {\n const context = createPromptContext(includeDateTime);\n return `${context}${prompt}`;\n};\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-C82D-3600CB\nconst __banditFingerprint_prompts_moodDetectionts = 'BL-FP-DC31B2-A7D0';\nconst __auditTrail_prompts_moodDetectionts = 'BL-AU-MGOIKVVX-475M';\n// File: moodDetection.ts | Path: src/services/prompts/moodDetection.ts | Hash: c82da7d0\n\nimport { map, toArray } from \"rxjs\";\nimport { useAIProviderStore } from \"../../store/aiProviderStore\";\nimport { usePackageSettingsStore } from \"../../store/packageSettingsStore\";\nimport { debugLogger } from \"../logging/debugLogger\";\nimport { enhancePromptWithContext } from \"./promptUtils\";\n\n/**\n * Detects the emotional tone of the user's message using the AI provider.\n * This helps drive token budgeting, avatar mood, and reinforcement logic.\n *\n * @param message - The user's message to analyze\n * @returns Promise resolving to emotional tone: \"high\" | \"neutral\" | \"low\"\n */\nexport const detectMessageMood = async (\n message: string\n): Promise<\"high\" | \"neutral\" | \"low\"> => {\n // Get the provider fresh each time the function is called\n const provider = useAIProviderStore.getState().provider;\n\n if (!provider) {\n debugLogger.error(\"No AI provider available for mood detection\");\n return \"neutral\";\n }\n\n const prompt = `\nRate the emotional tone of the user's message. Only respond with \"high\", \"neutral\", or \"low\".\n\nIf the message expresses strong enthusiasm, joy, or excitement, respond with \"high\".\nIf the message feels calm, polite, or ordinary, respond with \"neutral\".\nIf the message feels sad, bored, or frustrated, respond with \"low\".\n\nMessage: \"${message}\"\n\nResponse:`;\n\n const modelName = usePackageSettingsStore.getState().settings?.defaultModel || \"bandit-core\";\n\n try {\n debugLogger.llmDebug(\"detectMessageMood\", { message: message.slice(0, 100) });\n\n const response$ = provider.generate({\n model: modelName,\n prompt: enhancePromptWithContext(prompt),\n stream: false,\n options: { temperature: 0.3, num_predict: 10 },\n });\n\n const chunks$ = response$.pipe(\n map((chunk) => chunk.response.trim().toLowerCase()),\n toArray()\n );\n\n const result = await chunks$.toPromise();\n const finalResult = (result || []).join(\"\").trim();\n\n debugLogger.llmDebug(\"detectMessageMood result\", { finalResult });\n\n // Validate the response\n if (finalResult.includes(\"high\")) return \"high\";\n if (finalResult.includes(\"low\")) return \"low\";\n return \"neutral\";\n } catch (error) {\n debugLogger.error(\"Error detecting mood:\", { error });\n return \"neutral\";\n }\n};\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-9F14-B1A808\nconst __banditFingerprint_prompts_detectUserInterestAndExcitementts = 'BL-FP-B4BAD5-BF82';\nconst __auditTrail_prompts_detectUserInterestAndExcitementts = 'BL-AU-MGOIKVVX-79NP';\n// File: detectUserInterestAndExcitement.ts | Path: src/services/prompts/detectUserInterestAndExcitement.ts | Hash: 9f14bf82\n\nimport { lastValueFrom, map, toArray } from \"rxjs\";\nimport { useAIProviderStore } from \"../../store/aiProviderStore\";\nimport { usePackageSettingsStore } from \"../../store/packageSettingsStore\";\nimport { debugLogger } from \"../logging/debugLogger\";\n\n/**\n * Determines if user input contains meaningful information that shows their interests, \n * excitement, or engagement - focusing on what could enhance their experience.\n * \n * This replaces the old \"personal information\" approach which was too broad and intrusive.\n * Now we focus on user interest signals and engagement rather than demographic collection.\n * \n * @param question - The user's input message\n * @param response - The AI's response (currently unused but available for context)\n * @returns Promise resolving to true if user interest/excitement is detected\n */\nexport const detectUserInterestAndExcitement = async (question: string, response: string): Promise<boolean> => {\n // Get the provider fresh each time the function is called\n const provider = useAIProviderStore.getState().provider;\n\n if (!provider) {\n debugLogger.error(\"No AI provider available for personal content detection\");\n return false;\n }\n\n const prompt = `\n Detect if the user shared something meaningful that shows their interests, excitement, or personal connection.\n\n Look for USER INTEREST & EXCITEMENT signals:\n - User expressing enthusiasm, excitement, or passion about something\n - User sharing goals, dreams, or aspirations they care about\n - User mentioning preferences that affect their experience (tools, formats, workflows)\n - User revealing meaningful life experiences or achievements\n - User discussing plans, projects, or activities they're invested in\n - User sharing challenges they want to overcome or skills they want to develop\n\n IGNORE routine mentions:\n - Simple factual statements without emotional investment\n - Casual location references without context\n - Generic preferences without personal significance\n - Basic demographic info (age, location) without meaningful context\n - Complaints or negative experiences without constructive elements\n\n Focus on what could enhance their experience or help me serve them better.\n \n Reply \"YES\" only if the user shared something they care about or are excited about.\n Reply \"NO\" for routine information or casual mentions.\n \n User input:\n \"${question}\"\n \n Response:`;\n\n const modelName = usePackageSettingsStore.getState().settings?.defaultModel || \"bandit-core\";\n\n try {\n debugLogger.llmDebug(\"detectUserInterestAndExcitement\", { question: question.slice(0, 100) });\n\n const response$ = provider.generate({\n model: modelName,\n prompt,\n stream: false,\n options: { temperature: 0.1, num_predict: 5 },\n });\n\n const chunks$ = response$.pipe(\n map((chunk) => chunk.response.trim().toUpperCase()),\n toArray()\n );\n\n const result = await lastValueFrom(chunks$);\n const decision = result.join(\"\").trim();\n\n debugLogger.llmDebug(\"detectUserInterestAndExcitement result\", { decision });\n\n return decision.includes(\"YES\");\n } catch (error) {\n debugLogger.error(\"Error detecting personal content:\", { error });\n return false;\n }\n};\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-5E11-84C444\nconst __banditFingerprint_prompts_documentSummarizationts = 'BL-FP-AEED1A-6849';\nconst __auditTrail_prompts_documentSummarizationts = 'BL-AU-MGOIKVVX-RYY6';\n// File: documentSummarization.ts | Path: src/services/prompts/documentSummarization.ts | Hash: 5e116849\n\nimport { lastValueFrom, map } from \"rxjs\";\nimport { useAIProviderStore } from \"../../store/aiProviderStore\";\nimport { usePackageSettingsStore } from \"../../store/packageSettingsStore\";\nimport { debugLogger } from \"../logging/debugLogger\";\n\n/**\n * Summarizes document content for indexing in the AI knowledge system.\n * \n * @param name - The filename of the document\n * @param content - The document content to summarize\n * @returns Promise resolving to a concise summary string\n */\nexport const summarizeDocument = async (name: string, content: string): Promise<string> => {\n // Get the provider fresh each time the function is called\n const provider = useAIProviderStore.getState().provider;\n\n if (!provider) {\n debugLogger.error(\"No AI provider available for document summarization\");\n return `Summary unavailable for ${name}`;\n }\n\n const prompt = `\nYou are an assistant designed to summarize documents for indexing in an AI knowledge system.\nSummarize the following document in 1-2 concise sentences.\nOnly describe the content — do not add commentary, humor, or emojis.\nIf the file has a specific structure (e.g., C# code, policy, technical reference), mention that in the summary.\n\nFilename: ${name}\nContent:\n${content.slice(0, 4000)}\n`.trim();\n\n try {\n debugLogger.ragDebug(\"summarizeDocument\", { name, contentLength: content.length });\n\n const data$ = provider.generate({\n model: usePackageSettingsStore.getState().settings?.defaultModel || \"bandit-core\",\n prompt,\n stream: false,\n options: { temperature: 0.3, num_predict: 100 },\n });\n\n const summary$ = data$.pipe(map((d) => d.response.trim()));\n const summary = await lastValueFrom(summary$);\n\n debugLogger.ragDebug(\"summarizeDocument result\", { name, summary });\n\n return summary || `Document summary for ${name}`;\n } catch (error) {\n debugLogger.error(\"Error summarizing document:\", { error, name });\n return `Summary error for ${name}`;\n }\n};\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-37EB-889E8F\nconst __banditFingerprint_prompts_documentRelevancets = 'BL-FP-678FBC-87EF';\nconst __auditTrail_prompts_documentRelevancets = 'BL-AU-MGOIKVVX-8TXA';\n// File: documentRelevance.ts | Path: src/services/prompts/documentRelevance.ts | Hash: 37eb87ef\n\nimport { lastValueFrom, map, toArray } from \"rxjs\";\nimport { useAIProviderStore } from \"../../store/aiProviderStore\";\nimport { usePackageSettingsStore } from \"../../store/packageSettingsStore\";\nimport { debugLogger } from \"../logging/debugLogger\";\n\n/**\n * Determines which documents are relevant to the user's question for RAG (Retrieval-Augmented Generation).\n * \n * @param question - The user's question or prompt\n * @param docs - Array of documents with name and chunk content\n * @returns Promise resolving to array of relevant document indices\n */\nexport const determineRelevantDocuments = async (\n question: string,\n docs: { name: string; chunks: string[] }[]\n): Promise<number[]> => {\n const provider = useAIProviderStore.getState().provider;\n if (!provider) {\n debugLogger.error(\"No AI provider available for knowledge relevance vetting\");\n return [];\n }\n\n const vetPrompt = `\nYou are a context-aware assistant. The user is asking:\n\n\"${question}\"\n\nHere are some documents:\n${docs\n .map(\n (d, i) =>\n `Doc ${i + 1} - \"${d.name}\":\\n${d.chunks.slice(0, 2).join(\"\\n\").slice(0, 1000)}\\n`\n )\n .join(\"\\n\")}\n\nOnly include documents if the user's question explicitly relates to their contents.\n\nReply with a comma-separated list of document numbers (e.g., \"1,3,5\") or \"none\" if no documents are relevant.\n\nResponse:`;\n\n const modelName = usePackageSettingsStore.getState().settings?.defaultModel || \"bandit-core\";\n\n try {\n debugLogger.ragDebug(\"determineRelevantDocuments\", {\n question: question.slice(0, 100),\n docCount: docs.length,\n docNames: docs.map(d => d.name)\n });\n\n const response$ = provider.generate({\n model: modelName,\n prompt: vetPrompt,\n stream: false,\n options: { temperature: 0.2, num_predict: 50 },\n });\n\n const chunks$ = response$.pipe(\n map((chunk) => chunk.response.trim()),\n toArray()\n );\n\n const result = await lastValueFrom(chunks$);\n const vetResult = result.join(\"\").trim().toLowerCase();\n\n debugLogger.ragDebug(\"determineRelevantDocuments result\", { vetResult });\n\n if (vetResult.includes(\"none\") || !vetResult) {\n return [];\n }\n\n // Parse comma-separated numbers\n const relevantIndices = vetResult\n .split(\",\")\n .map((s) => parseInt(s.trim()) - 1) // Convert to 0-based index\n .filter((i) => !isNaN(i) && i >= 0 && i < docs.length);\n\n debugLogger.ragDebug(\"determineRelevantDocuments parsed\", { relevantIndices });\n\n return relevantIndices;\n } catch (error) {\n debugLogger.error(\"Error determining relevant documents:\", { error });\n return [];\n }\n};\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-3792-494067\nconst __banditFingerprint_prompts_dateTimeContextts = 'BL-FP-40AA97-710C';\nconst __auditTrail_prompts_dateTimeContextts = 'BL-AU-MGOIKVVX-VAO3';\n// File: dateTimeContext.ts | Path: src/services/prompts/dateTimeContext.ts | Hash: 3792710c\n\n/**\n * Utility function to get the current date and time in a readable format for AI context.\n * \n * @returns A formatted string with current date and time information\n */\nexport const getCurrentDateTimeContext = (): string => {\n const now = new Date();\n \n // Format: \"Today is Thursday, July 3, 2025 at 2:30 PM EST\"\n const options: Intl.DateTimeFormatOptions = {\n weekday: 'long',\n year: 'numeric',\n month: 'long',\n day: 'numeric',\n hour: 'numeric',\n minute: '2-digit',\n timeZoneName: 'short'\n };\n \n const formattedDate = now.toLocaleDateString('en-US', options);\n \n return `\\n\\nCurrent context: Today is ${formattedDate}.`;\n};\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-80DE-7F9B86\nconst __banditFingerprint_embedding_embeddingServicetsx = 'BL-FP-F2415E-F7A3';\nconst __auditTrail_embedding_embeddingServicetsx = 'BL-AU-MGOIKVVS-XRZD';\n// File: embeddingService.tsx | Path: src/services/embedding/embeddingService.tsx | Hash: 80def7a3\n\nimport { summarizeDocument } from \"../prompts\";\nimport { useMemoryStore } from \"../../store/memoryStore\";\nimport { debugLogger } from \"../logging/debugLogger\";\n\nexport class EmbeddingService {\n /**\n * Generates a basic \"fake\" embedding based on word length.\n * (Replaceable later with true model-based embeddings.)\n */\n async generate(text: string): Promise<number[]> {\n const words = text.toLowerCase().split(/\\s+/);\n return words.slice(0, 5).map((w) => w.length / 10);\n }\n\n private generateTFEmbedding(text: string, topN = 10): number[] {\n const words = text\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \"\")\n .split(/\\s+/)\n .filter(Boolean);\n\n const freq: Record<string, number> = {};\n for (const word of words) {\n freq[word] = (freq[word] || 0) + 1;\n }\n\n const topWords = Object.entries(freq)\n .sort((a, b) => b[1] - a[1])\n .slice(0, topN)\n .map(([word]) => word);\n\n return topWords.map((w) => freq[w] / words.length);\n }\n\n /**\n * Computes cosine similarity between two embedding vectors.\n */\n cosineSimilarity(a: number[], b: number[]): number {\n const dot = a.reduce((sum, ai, i) => sum + ai * (b[i] ?? 0), 0);\n const magA = Math.sqrt(a.reduce((sum, ai) => sum + ai * ai, 0));\n const magB = Math.sqrt(b.reduce((sum, bi) => sum + bi * bi, 0));\n if (magA === 0 || magB === 0) return 0;\n return dot / (magA * magB);\n }\n\n /**\n * Backfills any missing memory embeddings in the memory store.\n */\n async backfillMissingEmbeddings(): Promise<void> {\n const { entries } = useMemoryStore.getState();\n const updates: { id: string; embedding: number[] }[] = [];\n\n for (const entry of entries) {\n if (!entry.embedding) {\n const embedding = await this.generate(entry.content);\n updates.push({ id: entry.id, embedding });\n }\n }\n\n if (updates.length > 0) {\n useMemoryStore.setState((state) => ({\n entries: state.entries.map((entry) => {\n const updated = updates.find((u) => u.id === entry.id);\n return updated ? { ...entry, embedding: updated.embedding } : entry;\n }),\n }));\n debugLogger.debug(`✅ Backfilled ${updates.length} memory embeddings.`);\n } else {\n debugLogger.debug(\"✅ No missing embeddings — all memories are up to date!\");\n }\n }\n\n /**\n * Estimates token usage for a given memory content.\n * Rough formula: word count × 1.3 (average token inflation).\n */\n estimateTokens(text: string): number {\n const wordCount = text.trim().split(/\\s+/).length;\n return Math.ceil(wordCount * 1.3);\n }\n\n /**\n * Calculates total estimated token usage for pinned memories.\n */\n estimatePinnedMemoryTokens(): number {\n const { entries } = useMemoryStore.getState();\n const pinned = entries.filter((entry) => entry.pinned);\n return pinned.reduce((sum, entry) => sum + this.estimateTokens(entry.content), 0);\n }\n\n /**\n * Selects the most relevant memories for injection based on:\n * 1. Always include pinned memories first.\n * 2. Then select top semantic matches by cosine similarity.\n * 3. Stay within an approximate max token budget.\n */\n async selectRelevantMemories(question: string, maxTokens = 750): Promise<string[]> {\n if (!question.trim()) return [];\n\n const { entries } = useMemoryStore.getState();\n if (entries.length === 0) return [];\n\n const questionEmbedding = await this.generate(question);\n\n const pinned = entries.filter((entry) => entry.pinned);\n const unpinned = entries.filter((entry) => !entry.pinned);\n\n // Score unpinned memories\n const scored: { content: string; score: number }[] = [];\n\n for (const entry of unpinned) {\n if (entry.embedding) {\n const sim = this.cosineSimilarity(questionEmbedding, entry.embedding);\n scored.push({ content: entry.content, score: sim });\n }\n }\n\n scored.sort((a, b) => b.score - a.score);\n\n const threshold = 0.6;\n const topMatches = scored.filter((s) => s.score >= threshold);\n\n const selected: string[] = [];\n let tokensUsed = 0;\n\n // 1. Add all pinned memories first (if they fit)\n for (const entry of pinned) {\n const tokensNeeded = this.estimateTokens(entry.content);\n if (tokensUsed + tokensNeeded > maxTokens) {\n break;\n }\n selected.push(entry.content);\n tokensUsed += tokensNeeded;\n }\n\n // 2. Then fill remaining budget with best unpinned matches\n for (const match of topMatches) {\n const tokensNeeded = this.estimateTokens(match.content);\n if (tokensUsed + tokensNeeded > maxTokens) {\n break;\n }\n selected.push(match.content);\n tokensUsed += tokensNeeded;\n }\n\n debugLogger.debug(\n \"🎯 Selected memories (pinned + semantic):\",\n { \n memories: selected.map((m) => `${m.slice(0, 60)}${m.length > 60 ? \"...\" : \"\"}`)\n }\n );\n\n return selected;\n }\n\n /**\n * Splits raw text into smaller chunks (approx. ~500 chars each).\n * Useful for embedding code or reference documents.\n */\n chunkText(text: string, maxLen = 500): string[] {\n const lines = text.split(/\\r?\\n/);\n const chunks: string[] = [];\n let currentChunk = \"\";\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const nextChunk = currentChunk + line + \"\\n\";\n\n if (nextChunk.length > maxLen) {\n if (currentChunk.trim()) {\n chunks.push(currentChunk.trim());\n currentChunk = line + \"\\n\";\n } else {\n chunks.push(line.trim());\n currentChunk = \"\";\n }\n } else {\n currentChunk = nextChunk;\n }\n }\n\n if (currentChunk.trim()) {\n chunks.push(currentChunk.trim());\n }\n\n return chunks;\n }\n\n /**\n * Prepares a document (like a code file) for embedding.\n */\n async embedDocument(name: string, content: string) {\n const chunks = this.chunkText(content);\n const summary = await summarizeDocument(name, content);\n const embeddings = chunks.map((chunk) => this.generateTFEmbedding(chunk));\n\n return {\n name,\n summary,\n chunks,\n embeddings,\n };\n }\n}\n\nexport const embeddingService = new EmbeddingService();\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-8982-9742E4\nconst __banditFingerprint_vectorDatabase_vectorDatabaseServicets = 'BL-FP-D2339E-A5C8';\nconst __auditTrail_vectorDatabase_vectorDatabaseServicets = 'BL-AU-MGOIKVW1-FS6U';\n// File: vectorDatabaseService.ts | Path: src/services/vectorDatabase/vectorDatabaseService.ts | Hash: 8982a5c8\n\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface VectorMemory {\n id: string;\n content: string;\n title?: string;\n tags?: string[];\n score?: number;\n uploadedBy: string;\n uploadedAt: string;\n source?: 'auto' | 'user'; // Indicates if memory was created automatically or by user\n pinned?: boolean;\n lastReferencedAt?: string;\n metadata?: VectorMemoryMetadata;\n}\n\nexport interface VectorMemoryMetadata {\n personalConfidence?: number;\n topic?: string;\n engagement?: number;\n extractedFrom?: string;\n tags?: string[];\n additionalProperties?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface VectorDocument {\n id: string;\n filename: string;\n content: string;\n mimeType: string;\n score?: number;\n uploadedBy: string;\n uploadedAt: string;\n isUserContent: boolean;\n isTeamContent: boolean;\n contentSource: 'user' | 'team';\n}\n\nexport interface SearchResult {\n memories: VectorMemory[];\n documents: VectorDocument[];\n success: boolean;\n message?: string;\n}\n\ninterface MemoryResultsEnvelope extends Record<string, unknown> {\n success?: boolean;\n results?: unknown[];\n memories?: unknown[];\n message?: string;\n totalCount?: number;\n}\n\ninterface DocumentSearchResponse extends Record<string, unknown> {\n success?: boolean;\n results?: VectorDocument[];\n message?: string;\n}\n\ntype RawFileRecord = Record<string, unknown>;\n\n// Optional search filters aligned with New_Memories_API.md\nexport interface MemorySearchFilters {\n includePinned?: boolean;\n topics?: string[];\n source?: Array<'auto' | 'user'>;\n tags?: string[];\n}\n\nexport interface CreateMemoryOptions {\n title?: string;\n tags?: string[];\n source?: 'auto' | 'user';\n pinned?: boolean;\n metadata?: VectorMemoryMetadata;\n lastReferencedAt?: string;\n}\n\nexport interface FileUploadResult {\n success: boolean;\n fileId: string;\n message?: string;\n}\n\n/**\n * Upload request structure that matches the backend C# UploadRequest class\n */\nexport interface UploadRequest {\n /** The file to upload */\n file: File;\n /** \n * Indicates whether the file should be shared with the team.\n * If true and the user has team information, the file will be saved to the team bucket.\n * If false, the file will be saved to the user's personal bucket regardless of team membership.\n * Defaults to true for backward compatibility.\n */\n shareWithTeam: boolean;\n}\n\n/**\n * Vector Database Service for Advanced Semantic Search\n * \n * This service handles storage and retrieval of memories and documents\n * in the vector database when advanced semantic search is enabled.\n * \n * Feature Gating:\n * - Requires admin authorization, pro subscription, or team subscription\n * - Supports admin users and pro/team subscription tiers\n * - Only active when advancedMemories feature is enabled\n */\nexport class VectorDatabaseService {\n private baseUrl: string;\n private fileStorageApiUrl: string;\n private token: string | null = null;\n private lastAvailabilityState: boolean | undefined;\n private lastConfigState: string | undefined;\n\n constructor(gatewayApiUrl?: string, fileStorageApiUrl?: string) {\n // Use provided URLs or fallback to defaults\n // For local development, use HTTPS localhost Gateway API (matches working curl command)\n this.baseUrl = gatewayApiUrl || 'https://localhost:5001/api';\n this.fileStorageApiUrl = fileStorageApiUrl || 'https://localhost:5001/api';\n \n debugLogger.info('Vector database service initialized', {\n baseUrl: this.baseUrl,\n fileStorageApiUrl: this.fileStorageApiUrl,\n hasToken: Boolean(this.token),\n });\n }\n\n /**\n * Set authentication token for API calls\n */\n setAuthToken(token: string) {\n this.token = token;\n }\n\n /**\n * Get authorization headers\n */\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.token) {\n headers['Authorization'] = `Bearer ${this.token}`;\n }\n\n return headers;\n }\n\n /**\n * Check if vector database is available and configured\n */\n isAvailable(): boolean {\n const available = !!(this.baseUrl && this.fileStorageApiUrl && this.token);\n // Only log on first check or when availability changes\n if (this.lastAvailabilityState !== available) {\n debugLogger.debug('Vector service availability check', {\n baseUrl: this.baseUrl,\n fileStorageApiUrl: this.fileStorageApiUrl,\n hasToken: Boolean(this.token),\n available,\n });\n this.lastAvailabilityState = available;\n }\n return available;\n }\n\n // ===== MEMORY OPERATIONS =====\n\n /**\n * Create and embed a memory in the vector database\n */\n async createMemory(\n content: string,\n options: CreateMemoryOptions = {}\n ): Promise<{ success: boolean; memoryId?: string; message?: string }> {\n if (!this.isAvailable()) {\n throw new Error('Vector database service not available');\n }\n\n try {\n const {\n title,\n tags,\n source = 'user',\n pinned = false,\n metadata,\n lastReferencedAt,\n } = options;\n\n debugLogger.info('Creating vector memory', { \n contentLength: content.length, \n title, \n tagsCount: tags?.length || 0,\n source,\n pinned,\n });\n\n const response = await fetch(`${this.baseUrl}/embedding/embed-memory`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n content,\n title,\n tags: tags || [],\n source,\n pinned,\n metadata,\n lastReferencedAt,\n })\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(errorData.message || `API request failed: ${response.status}`);\n }\n\n const result = await response.json();\n \n debugLogger.info('Vector memory created successfully', { \n memoryId: result.memoryId,\n contentLength: result.contentLength \n });\n\n return {\n success: true,\n memoryId: result.memoryId,\n message: result.message\n };\n } catch (error) {\n debugLogger.error('Failed to create vector memory', { \n error: error instanceof Error ? error.message : String(error) \n });\n \n throw new Error(`Failed to create memory: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Search memories in the vector database\n */\n private coerceStringArray(value: unknown): string[] {\n if (!value) {\n return [];\n }\n\n if (Array.isArray(value)) {\n return value\n .map((item) => (typeof item === 'string' ? item : String(item)))\n .map((item) => item.trim())\n .filter(Boolean);\n }\n\n if (typeof value === 'string') {\n return value\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean);\n }\n\n return [];\n }\n private coerceString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n }\n\n private coerceBoolean(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n }\n\n private coerceNumber(value: unknown): number | undefined {\n return typeof value === 'number' ? value : undefined;\n }\n\n private asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value && typeof value === 'object') {\n return value as Record<string, unknown>;\n }\n return undefined;\n }\n\n\n private toRecordArray(values: unknown[]): RawFileRecord[] {\n return values.reduce<RawFileRecord[]>((acc, item) => {\n const record = this.asRecord(item);\n if (record) {\n acc.push(record);\n }\n return acc;\n }, []);\n }\n\n private buildMetadata(primary?: Record<string, unknown>, fallback?: Record<string, unknown>): VectorMemoryMetadata | undefined {\n const metadata: VectorMemoryMetadata = {};\n let hasMetadata = false;\n\n const sources = [primary, fallback].filter(\n (source): source is Record<string, unknown> => Boolean(source) && typeof source === 'object'\n );\n\n const tagsSet = new Set<string>();\n\n for (const source of sources) {\n if (typeof source.personalConfidence === 'number') {\n metadata.personalConfidence = source.personalConfidence;\n hasMetadata = true;\n }\n if (typeof source.topic === 'string' && source.topic.trim()) {\n metadata.topic = source.topic.trim();\n hasMetadata = true;\n }\n if (typeof source.engagement === 'number') {\n metadata.engagement = source.engagement;\n hasMetadata = true;\n }\n if (typeof source.extractedFrom === 'string' && source.extractedFrom.trim()) {\n metadata.extractedFrom = source.extractedFrom.trim();\n hasMetadata = true;\n }\n\n this.coerceStringArray(source.tags).forEach((tag) => {\n tagsSet.add(tag);\n hasMetadata = true;\n });\n\n const additionalSource = source.additionalProperties;\n if (additionalSource && typeof additionalSource === 'object') {\n metadata.additionalProperties = {\n ...(metadata.additionalProperties || {}),\n ...additionalSource,\n };\n hasMetadata = true;\n }\n\n for (const [key, value] of Object.entries(source)) {\n if (\n key === 'personalConfidence' ||\n key === 'topic' ||\n key === 'engagement' ||\n key === 'extractedFrom' ||\n key === 'tags' ||\n key === 'additionalProperties'\n ) {\n continue;\n }\n\n if (key === 'vectorMemory') {\n continue;\n }\n\n metadata.additionalProperties = {\n ...(metadata.additionalProperties || {}),\n [key]: value,\n };\n hasMetadata = true;\n }\n }\n\n if (tagsSet.size > 0) {\n metadata.tags = Array.from(tagsSet);\n }\n\n return hasMetadata ? metadata : undefined;\n }\n\n private normalizeMemoryResult(rawInput: unknown): VectorMemory {\n const raw = this.asRecord(rawInput) ?? {};\n const rawMetadata = this.asRecord(raw['metadata']);\n const vectorMetadata = rawMetadata ? this.asRecord(rawMetadata['vectorMemory']) : undefined;\n const vector = vectorMetadata ?? raw;\n const vectorInnerMetadata = this.asRecord(vector['metadata']);\n\n const metadata = this.buildMetadata(vectorInnerMetadata, rawMetadata);\n\n const tagsSet = new Set<string>();\n this.coerceStringArray(vector['tags']).forEach((tag) => tagsSet.add(tag));\n this.coerceStringArray(raw['tags']).forEach((tag) => tagsSet.add(tag));\n metadata?.tags?.forEach((tag) => tagsSet.add(tag));\n\n const scoreCandidates = [\n this.coerceNumber(vector['score']),\n this.coerceNumber(raw['score']),\n ];\n const normalizedScore = scoreCandidates.find((value): value is number => typeof value === 'number');\n\n const pinnedValue =\n this.coerceBoolean(vector['pinned']) ??\n this.coerceBoolean(rawMetadata ? rawMetadata['pinned'] : undefined) ??\n this.coerceBoolean(raw['pinned']);\n\n const lastReferencedAt =\n this.coerceString(vector['lastReferencedAt']) ??\n this.coerceString(rawMetadata ? rawMetadata['lastReferencedAt'] : undefined) ??\n this.coerceString(raw['lastReferencedAt']);\n\n const uploadedAt =\n this.coerceString(vector['uploadedAt']) ??\n this.coerceString(raw['uploadedAt']) ??\n new Date().toISOString();\n\n const sourceValue = this.coerceString(vector['source']) ?? this.coerceString(raw['source']);\n const normalizedSource =\n sourceValue === 'auto' || sourceValue === 'user' ? sourceValue : undefined;\n\n const idValue = this.coerceString(vector['id']) ?? this.coerceString(raw['id']) ?? '';\n const contentValue = this.coerceString(vector['content']) ?? this.coerceString(raw['content']) ?? '';\n const titleValue =\n this.coerceString(vector['title']) ??\n this.coerceString(raw['title']) ??\n this.coerceString(raw['filename']) ??\n undefined;\n const uploadedByValue =\n this.coerceString(vector['uploadedBy']) ??\n this.coerceString(raw['uploadedBy']) ??\n 'unknown';\n\n return {\n id: idValue,\n content: contentValue,\n title: titleValue,\n tags: tagsSet.size > 0 ? Array.from(tagsSet) : undefined,\n score: normalizedScore,\n uploadedBy: uploadedByValue,\n uploadedAt,\n source: normalizedSource,\n pinned: pinnedValue,\n lastReferencedAt,\n metadata,\n };\n }\n /**\n * Search memories in the vector database\n */\n async searchMemories(\n query: string,\n limit = 10,\n scoreThreshold = 0.6,\n filters?: MemorySearchFilters\n ): Promise<VectorMemory[]> {\n if (!this.isAvailable()) {\n return [];\n }\n\n try {\n debugLogger.info('Searching vector memories', { query: query.slice(0, 100), limit, scoreThreshold });\n\n const response = await fetch(`${this.baseUrl}/embedding/search-memories`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n query,\n limit,\n scoreThreshold,\n // Only include filters when provided\n ...(filters ? { filters } : {})\n })\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(errorData.message || `Search request failed: ${response.status}`);\n }\n\n const statsHeader = response.headers.get('X-Memory-Stats');\n if (statsHeader) {\n debugLogger.memoryDebug('Vector memory search diagnostics', {\n header: statsHeader\n });\n }\n\n const result = (await response.json()) as MemoryResultsEnvelope;\n \n if (result.success === false) {\n throw new Error(result.message || 'Search was not successful');\n }\n\n const searchResults = Array.isArray(result.results) ? result.results : [];\n const normalizedResults = searchResults.map((entry) =>\n this.normalizeMemoryResult(entry)\n );\n\n debugLogger.info('Vector memory search completed', { \n resultsCount: normalizedResults.length,\n message: result.message \n });\n\n return normalizedResults;\n } catch (error) {\n debugLogger.error('Failed to search vector memories', { \n error: error instanceof Error ? error.message : String(error) \n });\n \n return [];\n }\n }\n\n /**\n * Get user's memories with pagination\n */\n async getMyMemories(skip = 0, limit = 50): Promise<VectorMemory[]> {\n if (!this.isAvailable()) {\n return [];\n }\n\n try {\n const response = await fetch(`${this.baseUrl}/embedding/my-memories?skip=${skip}&limit=${limit}`, {\n method: 'GET',\n headers: this.getHeaders()\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch memories: ${response.status}`);\n }\n\n const result = (await response.json()) as MemoryResultsEnvelope;\n debugLogger.debug('Vector getMyMemories API response', result);\n \n // Handle both 'memories' and 'results' response formats for compatibility\n const rawMemories = Array.isArray(result.memories)\n ? result.memories\n : Array.isArray(result.results)\n ? result.results\n : [];\n const memories = rawMemories.map((entry) => this.normalizeMemoryResult(entry));\n\n debugLogger.info('Vector memories fetched successfully', { \n count: memories.length, \n totalCount: result.totalCount,\n responseStructure: Object.keys(result)\n });\n \n return memories;\n } catch (error) {\n debugLogger.error('Failed to fetch user memories', { error });\n return [];\n }\n }\n\n /**\n * Delete a memory from the vector database\n */\n async deleteMemory(memoryId: string): Promise<boolean> {\n if (!this.isAvailable()) {\n return false;\n }\n\n try {\n const response = await fetch(`${this.baseUrl}/embedding/memory/${memoryId}`, {\n method: 'DELETE',\n headers: this.getHeaders()\n });\n\n if (!response.ok) {\n throw new Error(`Failed to delete memory: ${response.status}`);\n }\n\n const result = await response.json();\n debugLogger.info('Vector memory deleted successfully', { memoryId, result });\n return result.success || true;\n } catch (error) {\n debugLogger.error('Failed to delete vector memory', { memoryId, error });\n return false;\n }\n }\n\n /**\n * Update a memory in the vector database (e.g., pin/unpin)\n */\n async updateMemory(memoryId: string, updates: { pinned?: boolean; content?: string; title?: string; tags?: string[] }): Promise<boolean> {\n if (!this.isAvailable()) {\n return false;\n }\n\n try {\n // Use the specific pin endpoint for pinning operations\n if (updates.pinned !== undefined) {\n const response = await fetch(`${this.baseUrl}/embedding/memory/${memoryId}/pin`, {\n method: 'PUT',\n headers: this.getHeaders(),\n body: JSON.stringify({ pinned: updates.pinned })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to update memory pin status: ${response.status}`);\n }\n\n const result = await response.json();\n debugLogger.info('Vector memory pin status updated successfully', { memoryId, pinned: updates.pinned, result });\n return result.success || true;\n }\n\n // For other updates, we'd need a general update endpoint (not specified in API doc)\n debugLogger.warn('General memory updates not supported yet', { memoryId, updates });\n return false;\n } catch (error) {\n debugLogger.error('Failed to update vector memory', { memoryId, error });\n return false;\n }\n }\n\n /**\n * Batch create memories in the vector database\n */\n async batchCreateMemories(\n memories: Array<{ content: string; title?: string; tags?: string[] }>,\n mode: 'append' | 'replace' | 'smartDedupe' = 'append',\n clearExisting: boolean = false\n ): Promise<{\n success: boolean;\n message: string;\n results: Array<{\n content: string;\n success: boolean;\n memoryId?: string;\n mongoId?: string;\n contentLength?: number;\n message: string;\n action: string;\n }>;\n summary: {\n mode: string;\n totalProcessed: number;\n successCount: number;\n failureCount: number;\n skippedCount: number;\n clearedExistingCount: number;\n clearedExisting: boolean;\n };\n }> {\n if (!this.isAvailable()) {\n throw new Error('Vector database service is not available');\n }\n\n try {\n const requestBody = {\n memories,\n mode,\n clearExisting\n };\n\n debugLogger.info('Batch creating memories', {\n count: memories.length,\n mode,\n clearExisting,\n firstMemoryPreview: memories[0]?.content?.substring(0, 50) || '',\n });\n\n const response = await fetch(`${this.baseUrl}/embedding/batch-embed-memories`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(requestBody)\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(errorData.message || `Batch memory creation failed: ${response.status}`);\n }\n\n const result = await response.json();\n \n debugLogger.info('Batch memory creation completed', {\n mode,\n totalMemories: memories.length,\n successCount: result.summary?.successCount || 0,\n failureCount: result.summary?.failureCount || 0\n });\n\n return result;\n } catch (error) {\n debugLogger.error('Failed to batch create memories', { \n error, \n memoriesCount: memories.length,\n mode \n });\n throw error;\n }\n }\n\n /**\n * Advanced batch create memories with chunking and progress reporting\n */\n async batchCreateMemoriesAdvanced(\n memories: Array<{ content: string; title?: string; tags?: string[] }>,\n options: {\n mode?: 'append' | 'replace' | 'smartDedupe';\n clearExisting?: boolean;\n chunkSize?: number;\n onProgress?: (current: number, total: number, message: string) => void;\n validateContent?: boolean;\n } = {}\n ): Promise<{\n success: boolean;\n message: string;\n totalMemories: number;\n successCount: number;\n failureCount: number;\n skippedCount: number;\n errors: string[];\n warnings: string[];\n chunks: number;\n duration: number;\n }> {\n const startTime = Date.now();\n const {\n mode = 'append',\n clearExisting = false,\n chunkSize = 50,\n onProgress,\n validateContent = true\n } = options;\n\n // Import memory utilities\n const { MemoryUtils } = await import('../../utils/memoryUtils');\n\n try {\n // Validate memories if requested\n let validMemories = memories;\n const warnings: string[] = [];\n \n if (validateContent) {\n const validation = MemoryUtils.validateMemories(memories);\n validMemories = validation.valid;\n \n if (validation.invalid.length > 0) {\n warnings.push(`${validation.invalid.length} memories failed validation and were skipped`);\n debugLogger.warn('Some memories failed validation', { \n invalidCount: validation.invalid.length,\n firstError: validation.invalid[0]?.error \n });\n }\n }\n\n if (validMemories.length === 0) {\n return {\n success: false,\n message: 'No valid memories to process',\n totalMemories: memories.length,\n successCount: 0,\n failureCount: 0,\n skippedCount: memories.length,\n errors: ['All memories failed validation'],\n warnings,\n chunks: 0,\n duration: Date.now() - startTime\n };\n }\n\n // Chunk memories for better performance\n const chunks = MemoryUtils.chunkMemories(validMemories, chunkSize);\n let totalSuccessCount = 0;\n let totalFailureCount = 0;\n const errors: string[] = [];\n\n onProgress?.(0, validMemories.length, 'Starting batch operation...');\n\n // Process chunks sequentially to avoid overwhelming the server\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n const chunkStartIndex = i * chunkSize;\n \n try {\n onProgress?.(\n chunkStartIndex,\n validMemories.length,\n `Processing chunk ${i + 1}/${chunks.length}...`\n );\n\n const chunkResult = await this.batchCreateMemories(\n chunk,\n i === 0 ? mode : 'append', // Only use special modes on first chunk\n i === 0 ? clearExisting : false // Only clear on first chunk\n );\n\n totalSuccessCount += chunkResult.summary.successCount;\n totalFailureCount += chunkResult.summary.failureCount;\n\n // Collect errors from failed results\n chunkResult.results\n .filter(r => !r.success)\n .forEach(r => errors.push(r.message));\n\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n errors.push(`Chunk ${i + 1} failed: ${errorMsg}`);\n totalFailureCount += chunk.length;\n \n debugLogger.error('Chunk processing failed', { \n chunkIndex: i,\n chunkSize: chunk.length,\n error: errorMsg\n });\n }\n\n // Brief pause between chunks to be respectful to the server\n if (i < chunks.length - 1) {\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n }\n\n const duration = Date.now() - startTime;\n const success = totalFailureCount === 0;\n const skippedCount = memories.length - validMemories.length;\n\n onProgress?.(\n validMemories.length,\n validMemories.length,\n success ? 'Batch operation completed successfully!' : 'Batch operation completed with errors'\n );\n\n const result = {\n success,\n message: `Processed ${totalSuccessCount}/${validMemories.length} memories successfully` + \n (skippedCount > 0 ? ` (${skippedCount} skipped)` : ''),\n totalMemories: memories.length,\n successCount: totalSuccessCount,\n failureCount: totalFailureCount,\n skippedCount,\n errors,\n warnings,\n chunks: chunks.length,\n duration\n };\n\n debugLogger.info('Advanced batch operation completed', result);\n return result;\n\n } catch (error) {\n const duration = Date.now() - startTime;\n const errorMsg = error instanceof Error ? error.message : String(error);\n \n debugLogger.error('Advanced batch operation failed', { \n error: errorMsg,\n memoriesCount: memories.length,\n duration\n });\n\n return {\n success: false,\n message: `Batch operation failed: ${errorMsg}`,\n totalMemories: memories.length,\n successCount: 0,\n failureCount: memories.length,\n skippedCount: 0,\n errors: [errorMsg],\n warnings: [],\n chunks: 0,\n duration\n };\n }\n }\n\n // ===== DOCUMENT OPERATIONS =====\n\n /**\n * Upload file to file storage API and get file ID\n * \n * @param file - The file to upload\n * @param shareWithTeam - Whether to share the file with team members.\n * If true and user has team info, file goes to team bucket.\n * If false, file goes to user's personal bucket.\n * Defaults to true for backward compatibility.\n * @returns Promise<FileUploadResult> with success status and file ID\n */\n async uploadFile(file: File, shareWithTeam = true): Promise<FileUploadResult> {\n if (!this.fileStorageApiUrl) {\n throw new Error('File storage API URL not configured');\n }\n\n if (!this.token) {\n throw new Error('Authentication token not available');\n }\n\n try {\n const formData = new FormData();\n formData.append('file', file);\n formData.append('shareWithTeam', shareWithTeam.toString());\n\n debugLogger.info('Uploading file to file storage API', { \n filename: file.name, \n size: file.size, \n type: file.type,\n shareWithTeam: shareWithTeam,\n fileStorageApiUrl: this.fileStorageApiUrl\n });\n\n const response = await fetch(`${this.fileStorageApiUrl}/file/upload`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.token}`\n },\n body: formData\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(errorData.message || `file storage upload failed: ${response.status}`);\n }\n\n const result = await response.json();\n \n // File storage API returns 'id' field, but we need 'fileId'\n const fileId = result.fileId || result.id;\n \n debugLogger.debug('File storage API upload response', result);\n debugLogger.debug('Extracted vector file id', { fileId });\n \n debugLogger.info('File uploaded successfully to file storage', { \n fileId: fileId,\n filename: file.name,\n originalResponse: result\n });\n\n return {\n success: true,\n fileId: fileId,\n message: result.message\n };\n } catch (error) {\n debugLogger.error('Failed to upload file to file storage', { error });\n throw new Error(`File storage upload failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Embed a document in the vector database via Gateway API\n */\n async embedDocument(\n fileId: string, \n shareWithTeam = true\n ): Promise<{ success: boolean; message?: string }> {\n debugLogger.debug('Embedding document request', { fileId, shareWithTeam });\n \n if (!this.baseUrl) {\n debugLogger.error('Gateway API URL not configured', { baseUrl: this.baseUrl });\n throw new Error('Gateway API URL not configured');\n }\n\n if (!this.token) {\n debugLogger.error('Authentication token not available');\n throw new Error('Authentication token not available');\n }\n\n try {\n const endpoint = `${this.baseUrl}/embedding/embed-document`;\n const payload = {\n FileId: fileId,\n Options: null, // EmbeddingOptions - can be null for default options\n ShareWithTeam: shareWithTeam\n };\n \n debugLogger.debug('Making Gateway API call', {\n endpoint,\n method: 'POST',\n payload,\n hasToken: Boolean(this.token),\n tokenPreview: `${this.token.substring(0, 20)}...`,\n });\n\n debugLogger.info('Embedding document via Gateway API', { \n fileId, \n shareWithTeam,\n gatewayUrl: this.baseUrl\n });\n\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(payload)\n });\n\n debugLogger.debug('Gateway API response headers', {\n status: response.status,\n statusText: response.statusText,\n ok: response.ok,\n headers: Object.fromEntries(response.headers.entries())\n });\n\n // Try to get response text for better error debugging\n let responseText = '';\n let parsedResponse: unknown;\n \n try {\n responseText = await response.text();\n debugLogger.debug('Gateway API raw response text', {\n preview: responseText.substring(0, 500),\n });\n \n if (responseText) {\n parsedResponse = JSON.parse(responseText);\n }\n } catch (parseError) {\n debugLogger.warn('Could not parse Gateway API response as JSON', { error: parseError });\n }\n\n const responseRecord = this.asRecord(parsedResponse);\n const responseMessage = responseRecord && typeof responseRecord['message'] === 'string' ? (responseRecord['message'] as string) : undefined;\n\n if (!response.ok) {\n debugLogger.error('Gateway API error response', {\n status: response.status,\n statusText: response.statusText,\n responseData: responseRecord ?? { rawResponse: responseText },\n endpoint,\n payload\n });\n \n // Check for specific error types\n if (response.status === 404) {\n throw new Error(`Gateway API endpoint not found: ${endpoint}. Check if Gateway API is running and endpoint exists.`);\n } else if (response.status === 401 || response.status === 403) {\n throw new Error(`Authentication failed: ${response.status}. Check if auth token is valid.`);\n } else if (response.status === 500) {\n throw new Error(`Gateway API server error: ${responseMessage || responseText || 'Unknown server error'}`);\n } else {\n throw new Error(responseMessage || responseText || `Gateway embedding failed: ${response.status}`);\n }\n }\n\n debugLogger.debug('Gateway API success response', responseRecord ?? { rawResponse: responseText });\n \n const responseFileId = responseRecord && typeof responseRecord['fileId'] === 'string' ? (responseRecord['fileId'] as string) : undefined;\n\n debugLogger.info('Document embedded successfully via Gateway API', { \n fileId: responseFileId || fileId,\n message: responseMessage \n });\n\n return {\n success: true,\n message: responseMessage || 'Document embedded successfully'\n };\n } catch (error) {\n debugLogger.error('Failed to embed document via Gateway API', { fileId, error });\n \n // Provide more specific error messages\n if (error instanceof TypeError && error.message.includes('fetch')) {\n throw new Error(`Cannot connect to Gateway API at ${this.baseUrl}. Check if Gateway API server is running.`);\n } else {\n throw new Error(`Gateway embedding failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n\n /**\n * Search documents in the vector database\n */\n async searchDocuments(\n query: string, \n limit = 20, \n scoreThreshold = 0.5\n ): Promise<VectorDocument[]> {\n if (!this.isAvailable()) {\n return [];\n }\n\n try {\n debugLogger.info('Searching vector documents', { query: query.slice(0, 100), limit, scoreThreshold });\n\n const response = await fetch(`${this.baseUrl}/embedding/search`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n query,\n limit,\n scoreThreshold\n })\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(errorData.message || `Search failed: ${response.status}`);\n }\n\n const result = (await response.json()) as DocumentSearchResponse;\n \n if (result.success === false) {\n throw new Error(result.message || 'Search was not successful');\n }\n\n const documents = Array.isArray(result.results) ? result.results : [];\n\n debugLogger.info('Vector document search completed', { \n resultsCount: documents.length \n });\n\n return documents;\n } catch (error) {\n debugLogger.error('Failed to search vector documents', { error });\n return [];\n }\n }\n\n /**\n * Get available files that haven't been embedded\n */\n async getAvailableFiles(skip = 0, limit = 50): Promise<RawFileRecord[]> {\n if (!this.isAvailable()) {\n return [];\n }\n\n try {\n const response = await fetch(`${this.baseUrl}/embedding/available-files?skip=${skip}&limit=${limit}`, {\n method: 'GET',\n headers: this.getHeaders()\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch available files: ${response.status}`);\n }\n\n const result = await response.json();\n if (Array.isArray(result)) {\n return this.toRecordArray(result);\n }\n\n if (result && Array.isArray(result.files)) {\n return this.toRecordArray(result.files);\n }\n\n return [];\n } catch (error) {\n debugLogger.error('Failed to fetch available files', { error });\n return [];\n }\n }\n\n /**\n * Get user's files - tries both Gateway API and file storage API\n */\n async getUserFiles(skip = 0, limit = 50): Promise<RawFileRecord[]> {\n if (!this.isAvailable()) {\n return [];\n }\n\n try {\n debugLogger.debug('Fetching user files from Gateway API', { skip, limit });\n // First try Gateway API\n const response = await fetch(`${this.baseUrl}/embedding/files?skip=${skip}&limit=${limit}`, {\n method: 'GET',\n headers: this.getHeaders()\n });\n\n if (!response.ok) {\n debugLogger.warn('Gateway API files endpoint failed, falling back to file storage API', {\n status: response.status,\n });\n // If Gateway API fails, try file storage API\n return await this.getUserFilesFromFileStorage(skip, limit);\n }\n\n const result = await response.json();\n debugLogger.debug('Gateway API files response', result);\n\n if (Array.isArray(result)) {\n return this.toRecordArray(result);\n }\n\n if (result && Array.isArray(result.files)) {\n return this.toRecordArray(result.files);\n }\n\n return [];\n } catch (error) {\n debugLogger.error('Gateway API failed while fetching user files, trying file storage API', { error });\n // Fallback to file storage API\n return await this.getUserFilesFromFileStorage(skip, limit);\n }\n }\n\n /**\n * Get user's files from file storage API as fallback\n */\n private async getUserFilesFromFileStorage(skip = 0, limit = 50): Promise<RawFileRecord[]> {\n try {\n debugLogger.debug('Fetching user files from file storage API', { skip, limit });\n const response = await fetch(`${this.fileStorageApiUrl}/file/files?skip=${skip}&limit=${limit}`, {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.token}`,\n 'Content-Type': 'application/json'\n }\n });\n\n if (!response.ok) {\n throw new Error(`File storage API failed: ${response.status}`);\n }\n\n const result = await response.json();\n debugLogger.debug('File storage API files response', result);\n \n if (Array.isArray(result)) {\n return this.toRecordArray(result);\n }\n\n if (result && Array.isArray(result.files)) {\n return this.toRecordArray(result.files);\n }\n\n return [];\n } catch (error) {\n debugLogger.error('Failed to fetch user files from file storage API', { error });\n return [];\n }\n }\n\n /**\n * Download a file using MongoDB ObjectId (secure method)\n */\n async downloadFile(fileId: string, filename: string): Promise<void> {\n if (!this.isAvailable()) {\n throw new Error('Vector database service not available');\n }\n\n try {\n debugLogger.debug('Downloading vector file', { fileId, filename });\n \n // Download from file storage API using MongoDB ObjectId (correct file storage API format)\n const response = await fetch(`${this.fileStorageApiUrl}/file/download/${fileId}`, {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.token}`\n }\n });\n\n if (!response.ok) {\n throw new Error(`Download failed: ${response.status} ${response.statusText}`);\n }\n\n // Get the file as a blob\n const blob = await response.blob();\n \n // Create download link\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n \n // Clean up the blob URL\n URL.revokeObjectURL(url);\n \n debugLogger.info('Vector file downloaded successfully', { fileId, filename });\n \n } catch (error) {\n debugLogger.error('Failed to download vector file', { fileId, filename, error });\n throw new Error(`Failed to download ${filename}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Get file blob using MongoDB ObjectId (for displaying content in modal)\n */\n async getFileBlob(fileId: string): Promise<Blob> {\n if (!this.isAvailable()) {\n throw new Error('Vector database service not available');\n }\n\n try {\n debugLogger.debug('Fetching vector file blob', { fileId });\n \n // Get file from file storage API using MongoDB ObjectId\n const response = await fetch(`${this.fileStorageApiUrl}/file/download/${fileId}`, {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.token}`\n }\n });\n\n if (!response.ok) {\n throw new Error(`Failed to get file: ${response.status} ${response.statusText}`);\n }\n\n const blob = await response.blob();\n debugLogger.info('Successfully retrieved vector file blob', { fileId, size: blob.size });\n \n return blob;\n \n } catch (error) {\n debugLogger.error('Failed to get file blob', { fileId, error });\n throw new Error(`Failed to get file: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Get file content for preview using MongoDB ObjectId (from Gateway API metadata)\n */\n async getFilePreview(fileId: string, maxSize = 1024 * 1024): Promise<{ content: string; mimeType: string } | null> {\n if (!this.isAvailable()) {\n return null;\n }\n\n try {\n debugLogger.debug('Fetching vector file preview', { fileId });\n \n // Get file metadata from Gateway API which includes the preview content\n const response = await fetch(`${this.baseUrl}/embedding/files`, {\n method: 'GET',\n headers: this.getHeaders()\n });\n\n if (!response.ok) {\n debugLogger.warn('Failed to retrieve files list before preview', { status: response.status });\n return null;\n }\n\n const filesResponse = await response.json();\n const fileCandidates = Array.isArray(filesResponse)\n ? this.toRecordArray(filesResponse)\n : filesResponse && Array.isArray(filesResponse.files)\n ? this.toRecordArray(filesResponse.files)\n : [];\n \n const targetFile = fileCandidates.find((file) => this.coerceString(file['id']) === fileId);\n const previewContent = targetFile ? this.coerceString(targetFile['preview']) : undefined;\n const mimeType = targetFile ? this.coerceString(targetFile['mimeType']) : undefined;\n \n if (!previewContent) {\n debugLogger.warn('Preview not available for file', { fileId });\n return null;\n }\n\n return {\n content: previewContent,\n mimeType: mimeType || 'text/plain'\n };\n \n } catch (error) {\n debugLogger.error('Failed to get file preview', { fileId, error });\n return null;\n }\n }\n\n /**\n * Delete a document from vector database\n */\n async deleteDocument(fileId: string): Promise<boolean> {\n if (!this.isAvailable()) {\n return false;\n }\n\n try {\n const response = await fetch(`${this.baseUrl}/embedding/${fileId}`, {\n method: 'DELETE',\n headers: this.getHeaders()\n });\n\n if (!response.ok) {\n throw new Error(`Failed to delete document: ${response.status}`);\n }\n\n debugLogger.info('Vector document deleted successfully', { fileId });\n return true;\n } catch (error) {\n debugLogger.error('Failed to delete vector document', { fileId, error });\n return false;\n }\n }\n\n // ===== COMBINED SEARCH =====\n\n /**\n * Search both memories and documents simultaneously\n */\n async searchAll(\n query: string,\n memoryLimit = 10,\n documentLimit = 20,\n scoreThreshold = 0.6\n ): Promise<SearchResult> {\n if (!this.isAvailable()) {\n return {\n memories: [],\n documents: [],\n success: false,\n message: 'Vector database service not available'\n };\n }\n\n try {\n const [memories, documents] = await Promise.all([\n this.searchMemories(query, memoryLimit, scoreThreshold),\n this.searchDocuments(query, documentLimit, scoreThreshold)\n ]);\n\n return {\n memories,\n documents,\n success: true,\n message: `Found ${memories.length} memories and ${documents.length} documents`\n };\n } catch (error) {\n debugLogger.error('Failed to search all content', { error });\n return {\n memories: [],\n documents: [],\n success: false,\n message: error instanceof Error ? error.message : 'Search failed'\n };\n }\n }\n /**\n * Configure the service with API URLs\n * This should be called by the main application with environment variables\n */\n configure(gatewayApiUrl: string, fileStorageApiUrl: string) {\n this.baseUrl = gatewayApiUrl;\n this.fileStorageApiUrl = fileStorageApiUrl;\n \n // Only log configuration changes, not repetitive calls\n if (this.lastConfigState !== `${gatewayApiUrl}|${fileStorageApiUrl}`) {\n debugLogger.info('Vector database service configured', {\n baseUrl: this.baseUrl,\n fileStorageApiUrl: this.fileStorageApiUrl,\n hasToken: Boolean(this.token),\n });\n this.lastConfigState = `${gatewayApiUrl}|${fileStorageApiUrl}`;\n }\n }\n\n /**\n * Manual debug function to test Gateway API connection\n * Call this from browser console to debug API issues\n */\n async debugTestConnection(): Promise<void> {\n debugLogger.info('Testing Gateway API connection');\n debugLogger.info('Vector service status snapshot', {\n baseUrl: this.baseUrl,\n fileStorageApiUrl: this.fileStorageApiUrl,\n hasToken: Boolean(this.token),\n tokenLength: this.token?.length || 0,\n tokenPreview: this.token ? `${this.token.substring(0, 30)}...` : undefined,\n isAvailable: this.isAvailable()\n });\n\n // Test basic connectivity\n try {\n debugLogger.debug('Testing basic connectivity to Gateway API');\n const response = await fetch(`${this.baseUrl}/health`, {\n method: 'GET',\n headers: this.getHeaders()\n });\n\n debugLogger.debug('Gateway API health check response', {\n status: response.status,\n statusText: response.statusText,\n ok: response.ok\n });\n\n if (response.ok) {\n const result = await response.text();\n debugLogger.info('Gateway API is reachable', { result });\n } else {\n debugLogger.warn('Gateway API health check failed');\n }\n } catch (error) {\n debugLogger.error('Cannot reach Gateway API', { error });\n }\n\n // Test file storage API connectivity\n try {\n debugLogger.debug('Testing file storage API connectivity');\n const files = await this.getUserFilesFromFileStorage(0, 5);\n debugLogger.info('File storage API files response', {\n count: files.length,\n files: files.slice(0, 3) // Show first 3 files\n });\n } catch (error) {\n debugLogger.error('File storage API test failed', { error });\n }\n\n // Test embedding endpoint specifically\n try {\n debugLogger.debug('Testing embedding endpoint availability');\n const testResponse = await fetch(`${this.baseUrl}/embedding/available-files?limit=1`, {\n method: 'GET',\n headers: this.getHeaders()\n });\n\n debugLogger.debug('Embedding endpoint response', {\n status: testResponse.status,\n ok: testResponse.ok,\n statusText: testResponse.statusText\n });\n\n if (testResponse.ok) {\n const result = await testResponse.json();\n debugLogger.info('Embedding endpoint is available', { result });\n }\n } catch (error) {\n debugLogger.error('Embedding endpoint test failed', { error });\n }\n }\n\n /**\n * Test embedding a specific file ID that you know exists\n */\n async debugTestEmbedding(fileId: string): Promise<void> {\n debugLogger.info('Testing embedding for file', { fileId });\n \n try {\n const result = await this.embedDocument(fileId, true);\n debugLogger.info('Embedding test result', result);\n } catch (error) {\n debugLogger.error('Embedding test failed', { error });\n }\n }\n}\n\n// Export singleton instance\nexport const vectorDatabaseService = new VectorDatabaseService();\n\n// Expose to global scope for debugging in development\nif (typeof window !== 'undefined') {\n const globalWindow = window as Window & { vectorDatabaseService?: VectorDatabaseService };\n globalWindow.vectorDatabaseService = vectorDatabaseService;\n debugLogger.info('Vector database service exposed globally for debugging');\n}\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-7AB7-C71573\nconst __banditFingerprint_vectorDatabase_vectorMigrationServicets = 'BL-FP-D7A8C3-8E82';\nconst __auditTrail_vectorDatabase_vectorMigrationServicets = 'BL-AU-MGOIKVW1-KUYC';\n// File: vectorMigrationService.ts | Path: src/services/vectorDatabase/vectorMigrationService.ts | Hash: 7ab78e82\n\nimport { debugLogger } from '../logging/debugLogger';\nimport { MemoryEntry } from '../../store/memoryStore';\nimport { KnowledgeDoc } from '../../store/knowledgeStore';\nimport { vectorDatabaseService } from './vectorDatabaseService';\nimport indexedDBService from '../indexedDB/indexedDBService';\n\nexport interface MigrationStatus {\n success: boolean;\n migratedMemories: number;\n migratedDocuments: number;\n errors: string[];\n warnings: string[];\n totalTime: number;\n}\n\nexport interface MigrationProgress {\n phase: 'memories' | 'documents' | 'cleanup' | 'complete';\n current: number;\n total: number;\n currentItem?: string;\n errors: string[];\n}\n\n/**\n * Vector Database Migration Service\n * \n * Handles migration of memories and documents from IndexedDB to vector database\n * when advanced semantic search is enabled for the first time.\n * \n * Features:\n * - Batch migration to avoid overwhelming the API\n * - Progress tracking with user feedback\n * - Error handling and retry logic\n * - Cleanup of migrated IndexedDB data (optional)\n * - Rollback capability in case of issues\n */\nexport class VectorMigrationService {\n private static readonly BATCH_SIZE = 5;\n private static readonly RETRY_DELAY = 1000; // 1 second\n private static readonly MAX_RETRIES = 3;\n\n private migrationKey = 'bandit_vector_migration_completed';\n private progressCallbacks: ((progress: MigrationProgress) => void)[] = [];\n\n /**\n * Check if migration has already been completed\n */\n isMigrationCompleted(): boolean {\n try {\n return localStorage.getItem(this.migrationKey) === 'true';\n } catch (error) {\n debugLogger.warn('Unable to check migration status from localStorage', { error });\n return false;\n }\n }\n\n /**\n * Mark migration as completed\n */\n markMigrationCompleted(): void {\n try {\n localStorage.setItem(this.migrationKey, 'true');\n debugLogger.info('Vector migration marked as completed');\n } catch (error) {\n debugLogger.error('Failed to mark migration as completed', { error });\n }\n }\n\n /**\n * Reset migration status (for testing or re-migration)\n */\n resetMigrationStatus(): void {\n try {\n localStorage.removeItem(this.migrationKey);\n debugLogger.info('Vector migration status reset');\n } catch (error) {\n debugLogger.error('Failed to reset migration status', { error });\n }\n }\n\n /**\n * Add progress callback for UI updates\n */\n onProgress(callback: (progress: MigrationProgress) => void): void {\n this.progressCallbacks.push(callback);\n }\n\n /**\n * Remove progress callback\n */\n removeProgressCallback(callback: (progress: MigrationProgress) => void): void {\n this.progressCallbacks = this.progressCallbacks.filter(cb => cb !== callback);\n }\n\n /**\n * Notify progress callbacks\n */\n private notifyProgress(progress: MigrationProgress): void {\n this.progressCallbacks.forEach(callback => {\n try {\n callback(progress);\n } catch (error) {\n debugLogger.error('Error in migration progress callback', { error });\n }\n });\n }\n\n /**\n * Sleep utility for rate limiting\n */\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n /**\n * Get all memories directly from IndexedDB\n */\n private async getAllMemories(): Promise<MemoryEntry[]> {\n try {\n const DB_NAME = \"bandit-memory-db\";\n const STORE_NAME = \"bandit-memory\";\n const storeConfigs = [{ name: STORE_NAME, keyPath: \"id\" }];\n \n return await indexedDBService.getAll<MemoryEntry>(DB_NAME, 1, STORE_NAME, storeConfigs);\n } catch (error) {\n debugLogger.error('Failed to get memories from IndexedDB', { error });\n return [];\n }\n }\n\n /**\n * Get all knowledge documents directly from IndexedDB \n */\n private async getAllDocuments(): Promise<KnowledgeDoc[]> {\n try {\n const DB_NAME = \"bandit-knowledge-db\";\n const STORE_NAME = \"bandit-knowledge\";\n const storeConfigs = [{ name: STORE_NAME, keyPath: \"id\" }];\n \n return await indexedDBService.getAll<KnowledgeDoc>(DB_NAME, 1, STORE_NAME, storeConfigs);\n } catch (error) {\n debugLogger.error('Failed to get documents from IndexedDB', { error });\n return [];\n }\n }\n\n /**\n * Clear all memories from IndexedDB\n */\n private async clearAllMemories(): Promise<void> {\n try {\n const DB_NAME = \"bandit-memory-db\";\n const STORE_NAME = \"bandit-memory\";\n const storeConfigs = [{ name: STORE_NAME, keyPath: \"id\" }];\n \n await indexedDBService.clear(DB_NAME, 1, STORE_NAME, storeConfigs);\n } catch (error) {\n debugLogger.error('Failed to clear memories from IndexedDB', { error });\n throw error;\n }\n }\n\n /**\n * Clear all documents from IndexedDB\n */\n private async clearAllDocuments(): Promise<void> {\n try {\n const DB_NAME = \"bandit-knowledge-db\";\n const STORE_NAME = \"bandit-knowledge\";\n const storeConfigs = [{ name: STORE_NAME, keyPath: \"id\" }];\n \n await indexedDBService.clear(DB_NAME, 1, STORE_NAME, storeConfigs);\n } catch (error) {\n debugLogger.error('Failed to clear documents from IndexedDB', { error });\n throw error;\n }\n }\n\n /**\n * Migrate memories from IndexedDB to vector database\n */\n private async migrateMemories(): Promise<{ success: number; errors: string[] }> {\n debugLogger.info('Starting memory migration to vector database');\n \n const memories = await this.getAllMemories();\n const errors: string[] = [];\n let successCount = 0;\n\n if (memories.length === 0) {\n debugLogger.info('No memories to migrate');\n return { success: 0, errors: [] };\n }\n\n debugLogger.info(`Found ${memories.length} memories to migrate`);\n\n // Process in batches\n for (let i = 0; i < memories.length; i += VectorMigrationService.BATCH_SIZE) {\n const batch = memories.slice(i, i + VectorMigrationService.BATCH_SIZE);\n \n this.notifyProgress({\n phase: 'memories',\n current: i,\n total: memories.length,\n currentItem: `Migrating batch ${Math.floor(i / VectorMigrationService.BATCH_SIZE) + 1}`,\n errors\n });\n\n // Process batch items\n for (const memory of batch) {\n let attempts = 0;\n let migrated = false;\n\n while (attempts < VectorMigrationService.MAX_RETRIES && !migrated) {\n try {\n attempts++;\n \n debugLogger.debug('Migrating memory to vector database', { \n memoryId: memory.id,\n attempt: attempts,\n content: memory.content.slice(0, 100)\n });\n\n // Create memory in vector database\n const result = await vectorDatabaseService.createMemory(memory.content, {\n title: `Memory from ${new Date(memory.timestamp).toLocaleDateString()}`,\n tags: memory.tags || [],\n source: memory.source,\n pinned: memory.pinned,\n lastReferencedAt: new Date(memory.timestamp).toISOString(),\n });\n\n if (result.success) {\n successCount++;\n migrated = true;\n debugLogger.debug('Memory migrated successfully', { \n memoryId: memory.id,\n vectorId: result.memoryId \n });\n } else {\n throw new Error(result.message || 'Unknown error');\n }\n } catch (error) {\n debugLogger.error('Failed to migrate memory', { \n memoryId: memory.id,\n attempt: attempts,\n error: error instanceof Error ? error.message : String(error)\n });\n\n if (attempts >= VectorMigrationService.MAX_RETRIES) {\n const errorMsg = `Failed to migrate memory ${memory.id}: ${error instanceof Error ? error.message : String(error)}`;\n errors.push(errorMsg);\n } else {\n // Wait before retry\n await this.sleep(VectorMigrationService.RETRY_DELAY * attempts);\n }\n }\n }\n }\n\n // Rate limiting between batches\n if (i + VectorMigrationService.BATCH_SIZE < memories.length) {\n await this.sleep(500);\n }\n }\n\n debugLogger.info('Memory migration completed', { \n total: memories.length,\n success: successCount,\n errors: errors.length \n });\n\n return { success: successCount, errors };\n }\n\n /**\n * Migrate documents from IndexedDB to vector database\n */\n private async migrateDocuments(): Promise<{ success: number; errors: string[] }> {\n debugLogger.info('Starting document migration to vector database');\n \n const errors: string[] = [];\n let successCount = 0;\n\n try {\n // Get documents from knowledge store's IndexedDB storage\n const documents = await this.getAllDocuments();\n\n if (documents.length === 0) {\n debugLogger.info('No documents to migrate');\n return { success: 0, errors: [] };\n }\n\n debugLogger.info(`Found ${documents.length} documents to migrate`);\n\n // Process documents in batches\n for (let i = 0; i < documents.length; i += VectorMigrationService.BATCH_SIZE) {\n const batch = documents.slice(i, i + VectorMigrationService.BATCH_SIZE);\n \n this.notifyProgress({\n phase: 'documents',\n current: i,\n total: documents.length,\n currentItem: `Migrating batch ${Math.floor(i / VectorMigrationService.BATCH_SIZE) + 1}`,\n errors\n });\n\n // Process batch items\n for (const doc of batch) {\n let attempts = 0;\n let migrated = false;\n\n while (attempts < VectorMigrationService.MAX_RETRIES && !migrated) {\n try {\n attempts++;\n \n debugLogger.debug('Migrating document to vector database', { \n filename: doc.name,\n attempt: attempts\n });\n\n // For documents, we need to:\n // 1. Convert content to file format if needed\n // 2. Upload to S3\n // 3. Embed in vector database\n \n if (doc.content && doc.name) {\n // Create a virtual file from stored content\n const blob = new Blob([doc.content], { type: 'text/plain' });\n const file = new File([blob], doc.name, { type: 'text/plain' });\n\n // Upload to S3 with team sharing enabled by default for migration\n const uploadResult = await vectorDatabaseService.uploadFile(file, true);\n \n if (uploadResult.success && uploadResult.fileId) {\n // Embed in vector database\n const embedResult = await vectorDatabaseService.embedDocument(uploadResult.fileId, true);\n \n if (embedResult.success) {\n successCount++;\n migrated = true;\n debugLogger.debug('Document migrated successfully', { \n filename: doc.name,\n fileId: uploadResult.fileId \n });\n } else {\n throw new Error(embedResult.message || 'Embedding failed');\n }\n } else {\n throw new Error(uploadResult.message || 'Upload failed');\n }\n } else {\n throw new Error('Document missing required content or filename');\n }\n } catch (error) {\n debugLogger.error('Failed to migrate document', { \n filename: doc.name,\n attempt: attempts,\n error: error instanceof Error ? error.message : String(error)\n });\n\n if (attempts >= VectorMigrationService.MAX_RETRIES) {\n const errorMsg = `Failed to migrate document ${doc.name}: ${error instanceof Error ? error.message : String(error)}`;\n errors.push(errorMsg);\n } else {\n // Wait before retry\n await this.sleep(VectorMigrationService.RETRY_DELAY * attempts);\n }\n }\n }\n }\n\n // Rate limiting between batches\n if (i + VectorMigrationService.BATCH_SIZE < documents.length) {\n await this.sleep(500);\n }\n }\n } catch (error) {\n debugLogger.error('Failed to get documents for migration', { error });\n errors.push(`Failed to retrieve documents: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n debugLogger.info('Document migration completed', { \n success: successCount,\n errors: errors.length \n });\n\n return { success: successCount, errors };\n }\n\n /**\n * Perform full migration from IndexedDB to vector database\n */\n async performMigration(\n options: {\n cleanupAfterMigration?: boolean;\n skipIfCompleted?: boolean;\n } = {}\n ): Promise<MigrationStatus> {\n const startTime = Date.now();\n const { cleanupAfterMigration = false, skipIfCompleted = true } = options;\n\n debugLogger.info('Starting vector database migration', { \n cleanupAfterMigration,\n skipIfCompleted \n });\n\n // Check if already completed\n if (skipIfCompleted && this.isMigrationCompleted()) {\n debugLogger.info('Migration already completed, skipping');\n return {\n success: true,\n migratedMemories: 0,\n migratedDocuments: 0,\n errors: [],\n warnings: ['Migration was already completed'],\n totalTime: Date.now() - startTime\n };\n }\n\n const allErrors: string[] = [];\n const allWarnings: string[] = [];\n\n try {\n // Ensure vector database is available\n if (!vectorDatabaseService.isAvailable()) {\n throw new Error('Vector database service is not available - check configuration and authentication');\n }\n\n // Phase 1: Migrate memories\n debugLogger.info('Phase 1: Migrating memories');\n const memoryResult = await this.migrateMemories();\n allErrors.push(...memoryResult.errors);\n\n // Phase 2: Migrate documents\n debugLogger.info('Phase 2: Migrating documents');\n const documentResult = await this.migrateDocuments();\n allErrors.push(...documentResult.errors);\n\n // Phase 3: Cleanup (optional)\n if (cleanupAfterMigration && allErrors.length === 0) {\n this.notifyProgress({\n phase: 'cleanup',\n current: 0,\n total: 1,\n currentItem: 'Cleaning up local data',\n errors: allErrors\n });\n\n try {\n // Only cleanup if migration was successful\n await this.cleanupLocalData();\n debugLogger.info('Local data cleanup completed');\n } catch (error) {\n const warningMsg = `Cleanup failed but migration succeeded: ${error instanceof Error ? error.message : String(error)}`;\n allWarnings.push(warningMsg);\n debugLogger.warn('Cleanup failed', { error });\n }\n }\n\n // Mark as completed if no errors\n if (allErrors.length === 0) {\n this.markMigrationCompleted();\n }\n\n // Final progress update\n this.notifyProgress({\n phase: 'complete',\n current: 1,\n total: 1,\n currentItem: 'Migration complete',\n errors: allErrors\n });\n\n const totalTime = Date.now() - startTime;\n const status: MigrationStatus = {\n success: allErrors.length === 0,\n migratedMemories: memoryResult.success,\n migratedDocuments: documentResult.success,\n errors: allErrors,\n warnings: allWarnings,\n totalTime\n };\n\n debugLogger.info('Vector migration completed', status);\n return status;\n\n } catch (error) {\n const errorMsg = `Migration failed: ${error instanceof Error ? error.message : String(error)}`;\n allErrors.push(errorMsg);\n \n debugLogger.error('Vector migration failed', { error });\n\n return {\n success: false,\n migratedMemories: 0,\n migratedDocuments: 0,\n errors: allErrors,\n warnings: allWarnings,\n totalTime: Date.now() - startTime\n };\n }\n }\n\n /**\n * Clean up local IndexedDB data after successful migration\n */\n private async cleanupLocalData(): Promise<void> {\n debugLogger.info('Starting cleanup of local IndexedDB data');\n\n try {\n // Clear memories from memory store\n await this.clearAllMemories();\n debugLogger.info('Cleared all memories from local storage');\n\n // Clear documents from knowledge store\n await this.clearAllDocuments();\n debugLogger.info('Cleared all documents from local storage');\n\n } catch (error) {\n debugLogger.error('Failed to cleanup local data', { error });\n throw error;\n }\n }\n\n /**\n * Estimate migration time and data size\n */\n async estimateMigration(): Promise<{\n memoryCount: number;\n documentCount: number;\n estimatedTime: number; // in minutes\n estimatedDataSize: number; // in MB\n }> {\n try {\n const memories = await this.getAllMemories();\n const documents = await this.getAllDocuments();\n\n // Rough estimation based on content size and API call overhead\n const avgMemorySize = memories.reduce((sum: number, m: MemoryEntry) => sum + m.content.length, 0) / Math.max(memories.length, 1);\n const avgDocumentSize = documents.reduce((sum: number, d: KnowledgeDoc) => sum + (d.content?.length || 0), 0) / Math.max(documents.length, 1);\n\n const totalDataSize = (memories.length * avgMemorySize + documents.length * avgDocumentSize) / (1024 * 1024); // MB\n const totalItems = memories.length + documents.length;\n \n // Estimate 1-2 seconds per item including API calls and retries\n const estimatedTime = Math.ceil((totalItems * 1.5) / 60); // minutes\n\n return {\n memoryCount: memories.length,\n documentCount: documents.length,\n estimatedTime: Math.max(1, estimatedTime),\n estimatedDataSize: Math.round(totalDataSize * 100) / 100\n };\n } catch (error) {\n debugLogger.error('Failed to estimate migration', { error });\n return {\n memoryCount: 0,\n documentCount: 0,\n estimatedTime: 1,\n estimatedDataSize: 0\n };\n }\n }\n}\n\n// Export singleton instance\nexport const vectorMigrationService = new VectorMigrationService();\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-D01A-03DF7F\nconst __banditFingerprint_types_featureFlagsts = 'BL-FP-1B5BAB-D379';\nconst __auditTrail_types_featureFlagsts = 'BL-AU-MGOIKVW9-TDZP';\n// File: featureFlags.ts | Path: src/types/featureFlags.ts | Hash: d01ad379\n\n/**\n * Subscription tiers available in the system\n */\nexport type SubscriptionTier = 'basic' | 'premium' | 'pro' | 'team' | 'trial' | 'expired';\n\n/**\n * Available feature keys that can be toggled\n */\nexport type FeatureKey = \n | 'memory'\n | 'documentKnowledge'\n | 'moodAdaptation'\n | 'chatSuggestions'\n | 'tts'\n | 'stt'\n | 'adminDashboardEnabled'\n | 'limitedAdminDashboard'\n | 'semanticSearchSimple'\n | 'semanticSearchPremium'\n | 'advancedSearch' // Vector DB-based search for pro/team\n | 'advancedMemories'; // Vector DB-based memories for pro/team\n\n/**\n * Feature matrix defining which features are enabled/disabled\n */\nexport type FeatureMatrix = Partial<Record<FeatureKey, boolean>>;\n\n/**\n * Feature flag configuration interface\n */\nexport interface FeatureFlagConfig {\n /** Current subscription tier - if not provided, assumes OSS mode */\n subscriptionType?: SubscriptionTier;\n \n /** JWT claim key to extract roles from (default: 'roles') */\n rolesClaimKey?: string;\n \n /** JWT claim key to extract subscription type from (default: 'subscriptionType') */\n subscriptionTypeClaimKey?: string;\n \n /** JWT claim key to check if subscription is active (default: 'isSubscribed') */\n isSubscribedClaimKey?: string;\n \n /** LocalStorage key where JWT is stored (default: 'bandit-jwt') */\n jwtStorageKey?: string;\n \n /** Manual feature overrides - takes precedence in OSS mode */\n featureMatrix?: FeatureMatrix;\n \n /** Admin role name that grants full access (default: 'admin') */\n adminRole?: string;\n \n /** Enable debug logging for feature evaluation */\n debug?: boolean;\n}\n\n/**\n * Default feature matrices for each subscription tier\n */\nexport const DEFAULT_TIER_FEATURES: Record<SubscriptionTier, FeatureMatrix> = {\n basic: {\n memory: true,\n documentKnowledge: false,\n moodAdaptation: false,\n chatSuggestions: true,\n tts: false,\n stt: false,\n adminDashboardEnabled: false,\n limitedAdminDashboard: false,\n semanticSearchSimple: true,\n semanticSearchPremium: false,\n advancedSearch: false, // No advanced features for basic\n advancedMemories: false, // No advanced features for basic\n },\n premium: {\n memory: true,\n documentKnowledge: true,\n moodAdaptation: true,\n chatSuggestions: true,\n tts: true,\n stt: true,\n adminDashboardEnabled: false,\n limitedAdminDashboard: true, // Premium gets limited admin access\n semanticSearchSimple: true,\n semanticSearchPremium: false, // No premium search for limited admin\n advancedSearch: false, // No vector DB search yet\n advancedMemories: false, // No vector DB memories yet\n },\n pro: {\n memory: true,\n documentKnowledge: true,\n moodAdaptation: true,\n chatSuggestions: true,\n tts: true,\n stt: true,\n adminDashboardEnabled: false,\n limitedAdminDashboard: true,\n semanticSearchSimple: true,\n semanticSearchPremium: true,\n advancedSearch: true, // Pro gets vector DB search\n advancedMemories: true, // Pro gets vector DB memories\n },\n team: {\n memory: true,\n documentKnowledge: true,\n moodAdaptation: true,\n chatSuggestions: true,\n tts: true,\n stt: true,\n adminDashboardEnabled: true, // Full admin access\n limitedAdminDashboard: true,\n semanticSearchSimple: true,\n semanticSearchPremium: true,\n advancedSearch: true, // Team gets vector DB search\n advancedMemories: true, // Team gets vector DB memories\n },\n trial: {\n memory: true,\n documentKnowledge: true,\n moodAdaptation: true,\n chatSuggestions: true,\n tts: true,\n stt: true,\n adminDashboardEnabled: false,\n limitedAdminDashboard: true, // Trial gets limited admin like pro\n semanticSearchSimple: true,\n semanticSearchPremium: true, // Trial gets pro-level search\n advancedSearch: true, // Trial gets pro-level features\n advancedMemories: true, // Trial gets pro-level features\n },\n expired: {\n memory: false,\n documentKnowledge: false,\n moodAdaptation: false,\n chatSuggestions: false,\n tts: false,\n stt: false,\n adminDashboardEnabled: false,\n limitedAdminDashboard: false,\n semanticSearchSimple: false,\n semanticSearchPremium: false, // Expired users get no features\n advancedSearch: false, // No advanced features\n advancedMemories: false, // No advanced features\n }\n};\n\n/**\n * Open source mode - all features available by default\n */\nexport const OSS_DEFAULT_FEATURES: FeatureMatrix = {\n memory: true,\n documentKnowledge: true,\n moodAdaptation: true,\n chatSuggestions: true,\n tts: true,\n stt: true,\n adminDashboardEnabled: true,\n limitedAdminDashboard: true,\n semanticSearchSimple: true,\n semanticSearchPremium: true,\n advancedSearch: true, // OSS gets all features\n advancedMemories: true, // OSS gets all features\n};\n\n/**\n * JWT payload interface for role extraction\n */\nexport interface JWTPayload extends Record<string, unknown> {\n exp?: number;\n iat?: number;\n}\n\n/**\n * Trial usage information from JWT\n */\nexport interface TrialUsage {\n chatRequestsUsed: number;\n chatRequestsLimit: number;\n generateRequestsUsed: number;\n generateRequestsLimit: number;\n}\n\n/**\n * Feature evaluation result\n */\nexport interface FeatureEvaluation {\n /** Current subscription tier (or 'oss' for open source mode) */\n tier: SubscriptionTier | 'oss';\n \n /** Whether the user has admin role */\n isAdmin: boolean;\n \n /** Whether the user's subscription is active (false for trial users) */\n isSubscribed: boolean;\n \n /** Trial usage limits (only present for trial users) */\n trialUsage?: TrialUsage;\n \n /** Final computed feature matrix */\n features: FeatureMatrix;\n \n /** Evaluation metadata */\n metadata: {\n jwtFound: boolean;\n jwtValid: boolean;\n rolesExtracted: string[];\n subscriptionTypeFromJWT?: SubscriptionTier;\n isSubscribedFromJWT?: boolean;\n trialUsageFromJWT?: TrialUsage;\n evaluatedAt: number;\n };\n}\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-717C-59E71E\nconst __banditFingerprint_contexts_FeatureFlagContexttsx = 'BL-FP-0AB63F-9820';\nconst __auditTrail_contexts_FeatureFlagContexttsx = 'BL-AU-MGOIKVVB-PUH9';\n// File: FeatureFlagContext.tsx | Path: src/contexts/FeatureFlagContext.tsx | Hash: 717c9820\n\nimport React, { createContext, useContext, useEffect, useState, useCallback } from 'react';\nimport {\n FeatureFlagConfig,\n FeatureKey,\n FeatureMatrix,\n FeatureEvaluation,\n SubscriptionTier,\n TrialUsage,\n DEFAULT_TIER_FEATURES,\n OSS_DEFAULT_FEATURES,\n JWTPayload\n} from '../types/featureFlags';\nimport { debugLogger } from '../services/logging/debugLogger';\n\n/**\n * Context value interface\n */\nexport interface FeatureFlagContextValue {\n /** Check if a specific feature is enabled */\n hasFeature: (feature: FeatureKey) => boolean;\n \n /** Get the current feature evaluation */\n getEvaluation: () => FeatureEvaluation | null;\n \n /** Refresh feature evaluation (useful after login/logout) */\n refreshEvaluation: () => void;\n \n /** Check if user is admin */\n isAdmin: () => boolean;\n \n /** Get current tier */\n getCurrentTier: () => SubscriptionTier | 'oss';\n \n /** Update subscription tier dynamically */\n updateTier: (tier: SubscriptionTier) => void;\n \n /** Check if we're in OSS mode */\n isOSSMode: () => boolean;\n}\n\nexport const FeatureFlagContext = createContext<FeatureFlagContextValue | undefined>(undefined);\n\n/**\n * Props for the FeatureFlagProvider\n */\nexport interface FeatureFlagProviderProps {\n config: FeatureFlagConfig;\n children: React.ReactNode;\n}\n\n/**\n * JWT decoding utility (simple base64 decode)\n */\nfunction decodeJWT(token: string): JWTPayload | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n \n const payload = parts[1];\n const decoded = atob(payload.replace(/-/g, '+').replace(/_/g, '/'));\n return JSON.parse(decoded);\n } catch (error) {\n debugLogger.error('Failed to decode JWT:', { error });\n return null;\n }\n}\n\n/**\n * Check if JWT is expired\n */\nfunction isJWTExpired(payload: JWTPayload): boolean {\n if (!payload.exp) return false;\n return Date.now() >= payload.exp * 1000;\n}\n\nconst coerceNumber = (value: unknown, fallback: number): number => {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'string') {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n return fallback;\n};\n\nconst coerceBoolean = (value: unknown, fallback: boolean): boolean => {\n if (typeof value === 'boolean') {\n return value;\n }\n if (typeof value === 'string') {\n return value.toLowerCase() === 'true';\n }\n if (typeof value === 'number') {\n return value !== 0;\n }\n return fallback;\n};\n\n/**\n * Feature Flag Provider Component\n */\nexport const FeatureFlagProvider: React.FC<FeatureFlagProviderProps> = ({ config, children }) => {\n const [evaluation, setEvaluation] = useState<FeatureEvaluation | null>(null);\n const [currentTier, setCurrentTier] = useState<SubscriptionTier | undefined>(config.subscriptionType);\n\n /**\n * Evaluate features based on JWT, tier, and config\n */\n const evaluateFeatures = useCallback((): FeatureEvaluation => {\n const {\n subscriptionType,\n rolesClaimKey = 'roles',\n subscriptionTypeClaimKey = 'subscriptionType',\n isSubscribedClaimKey = 'isSubscribed',\n jwtStorageKey = 'bandit-jwt',\n featureMatrix = {},\n adminRole = 'admin',\n debug = false\n } = config;\n\n let jwtFound = false;\n let jwtValid = false;\n let rolesExtracted: string[] = [];\n let isAdmin = false;\n let jwtSubscriptionType: SubscriptionTier | undefined;\n let jwtIsSubscribed: boolean = true; // Default to true for non-trial users\n let jwtTrialUsage: TrialUsage | undefined;\n let effectiveTier: SubscriptionTier | 'oss' = currentTier || subscriptionType || 'oss';\n\n // Try to get JWT from localStorage\n if (typeof window !== 'undefined') {\n try {\n const token = localStorage.getItem(jwtStorageKey);\n if (token) {\n jwtFound = true;\n const payload = decodeJWT(token);\n \n if (payload && !isJWTExpired(payload)) {\n jwtValid = true;\n \n // Extract roles\n const roles = payload[rolesClaimKey];\n if (Array.isArray(roles)) {\n rolesExtracted = roles.filter((role): role is string => typeof role === 'string');\n isAdmin = rolesExtracted.includes(adminRole);\n }\n \n // Extract subscription information from JWT\n const jwtSubType = payload[subscriptionTypeClaimKey];\n if (typeof jwtSubType === 'string' && ['basic', 'premium', 'pro', 'team', 'trial', 'expired'].includes(jwtSubType)) {\n jwtSubscriptionType = jwtSubType as SubscriptionTier;\n effectiveTier = jwtSubscriptionType; // JWT overrides config\n }\n \n // Extract subscription status (important for trial users)\n if (Object.prototype.hasOwnProperty.call(payload, isSubscribedClaimKey)) {\n jwtIsSubscribed = coerceBoolean(payload[isSubscribedClaimKey], jwtIsSubscribed);\n }\n \n // Extract trial usage information for trial users\n if (jwtSubscriptionType === 'trial') {\n const chatRequestsUsedRaw = (payload as Record<string, unknown>).chatRequestsUsed ?? (payload as Record<string, unknown>).ChatRequestsUsed;\n const chatRequestsLimitRaw = (payload as Record<string, unknown>).chatRequestsLimit ?? (payload as Record<string, unknown>).ChatRequestsLimit;\n const generateRequestsUsedRaw = (payload as Record<string, unknown>).generateRequestsUsed ?? (payload as Record<string, unknown>).GenerateRequestsUsed;\n const generateRequestsLimitRaw = (payload as Record<string, unknown>).generateRequestsLimit ?? (payload as Record<string, unknown>).GenerateRequestsLimit;\n\n jwtTrialUsage = {\n chatRequestsUsed: coerceNumber(chatRequestsUsedRaw, 0),\n chatRequestsLimit: coerceNumber(chatRequestsLimitRaw, 40),\n generateRequestsUsed: coerceNumber(generateRequestsUsedRaw, 0),\n generateRequestsLimit: coerceNumber(generateRequestsLimitRaw, 1000)\n };\n }\n }\n }\n } catch (error) {\n if (debug) {\n debugLogger.error('Error processing JWT for feature flags:', { error });\n }\n }\n }\n\n // Determine final feature matrix\n let finalFeatures: FeatureMatrix;\n\n if (!subscriptionType && !currentTier && !jwtSubscriptionType) {\n // OSS mode - use provided matrix or defaults\n finalFeatures = { ...OSS_DEFAULT_FEATURES, ...featureMatrix };\n effectiveTier = 'oss';\n } else if (isAdmin) {\n // Admin gets everything\n finalFeatures = { ...OSS_DEFAULT_FEATURES };\n } else {\n // Use tier-based features with manual overrides\n // Note: Trial users get pro-level features but have API-enforced request limits\n const tierFeatures = effectiveTier !== 'oss' \n ? DEFAULT_TIER_FEATURES[effectiveTier as SubscriptionTier] \n : OSS_DEFAULT_FEATURES;\n finalFeatures = { ...tierFeatures, ...featureMatrix };\n }\n\n const result: FeatureEvaluation = {\n tier: effectiveTier,\n isAdmin,\n isSubscribed: jwtIsSubscribed,\n trialUsage: jwtTrialUsage,\n features: finalFeatures,\n metadata: {\n jwtFound,\n jwtValid,\n rolesExtracted,\n subscriptionTypeFromJWT: jwtSubscriptionType,\n isSubscribedFromJWT: jwtIsSubscribed,\n trialUsageFromJWT: jwtTrialUsage,\n evaluatedAt: Date.now()\n }\n };\n\n if (debug) {\n debugLogger.info('Feature flag evaluation:', result);\n }\n\n return result;\n }, [config, currentTier]);\n\n /**\n * Refresh evaluation\n */\n const refreshEvaluation = useCallback(() => {\n const newEvaluation = evaluateFeatures();\n setEvaluation(newEvaluation);\n }, [evaluateFeatures]);\n\n /**\n * Initial evaluation and periodic refresh\n */\n useEffect(() => {\n refreshEvaluation();\n\n // Listen for storage changes (login/logout in other tabs)\n const handleStorageChange = (e: StorageEvent) => {\n if (e.key === config.jwtStorageKey || e.key === null) {\n refreshEvaluation();\n }\n };\n\n // Listen for external tier updates\n const handleTierUpdate = (e: CustomEvent) => {\n if (e.detail?.tier) {\n setCurrentTier(e.detail.tier);\n }\n };\n\n window.addEventListener('storage', handleStorageChange);\n window.addEventListener('bandit:tier-updated', handleTierUpdate as EventListener);\n \n return () => {\n window.removeEventListener('storage', handleStorageChange);\n window.removeEventListener('bandit:tier-updated', handleTierUpdate as EventListener);\n };\n }, [refreshEvaluation, config.jwtStorageKey]);\n\n /**\n * Context value\n */\n const contextValue: FeatureFlagContextValue = {\n hasFeature: (feature: FeatureKey) => {\n return evaluation?.features[feature] ?? false;\n },\n \n getEvaluation: () => evaluation,\n \n refreshEvaluation,\n \n isAdmin: () => evaluation?.isAdmin ?? false,\n \n getCurrentTier: () => evaluation?.tier ?? 'oss',\n \n updateTier: (tier: SubscriptionTier) => {\n setCurrentTier(tier);\n },\n \n isOSSMode: () => {\n if (!evaluation) {\n return true;\n }\n return evaluation.tier === 'oss';\n }\n };\n\n return (\n <FeatureFlagContext.Provider value={contextValue}>\n {children}\n </FeatureFlagContext.Provider>\n );\n};\n\n/**\n * Hook to use feature flags\n */\nexport const useFeatureFlag = (): FeatureFlagContextValue => {\n const context = useContext(FeatureFlagContext);\n if (context === undefined) {\n throw new Error('useFeatureFlag must be used within a FeatureFlagProvider');\n }\n return context;\n};\n\nexport default FeatureFlagProvider;\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-B397-D72705\nconst __banditFingerprint_hooks_useFeaturests = 'BL-FP-4804C1-6785';\nconst __auditTrail_hooks_useFeaturests = 'BL-AU-MGOIKVVE-JH5X';\n// File: useFeatures.ts | Path: src/hooks/useFeatures.ts | Hash: b3976785\n\nimport { useContext } from 'react';\nimport { FeatureFlagContext } from '../contexts/FeatureFlagContext';\nimport { FeatureKey, SubscriptionTier } from '../types/featureFlags';\n\n/**\n * Convenience hook that provides an easier API for feature checking\n */\nexport const useFeatures = () => {\n const featureFlag = useContext(FeatureFlagContext);\n\n if (!featureFlag) {\n // Fallback: default to OSS features when feature flags are unavailable\n return {\n hasFeature: () => true,\n hasMemory: () => true,\n hasDocumentKnowledge: () => true,\n hasMoodAdaptation: () => true,\n hasChatSuggestions: () => true,\n hasTTS: () => true,\n hasSTT: () => true,\n hasAdminDashboard: () => true,\n hasLimitedAdminDashboard: () => true,\n hasSimpleSearch: () => true,\n hasPremiumSearch: () => true,\n hasAdvancedSearch: () => true,\n hasAdvancedMemories: () => true,\n isAdmin: () => false,\n getCurrentTier: () => 'oss' as const,\n isOSSMode: () => true,\n isSubscribed: () => true,\n isPremiumTier: () => false,\n isProTier: () => false,\n isTrialTier: () => false,\n isTeamTier: () => false,\n isExpiredTier: () => false,\n needsUpgrade: () => false,\n getTrialUsage: () => undefined,\n isTrialLimitReached: () => false,\n getTrialRemainingRequests: () => null,\n updateTier: () => undefined,\n refreshFeatures: () => undefined,\n getFullEvaluation: () => null,\n };\n }\n\n return {\n // Core feature checking\n hasFeature: (feature: FeatureKey) => featureFlag.hasFeature(feature),\n \n // Convenience methods for common features\n hasMemory: () => featureFlag.hasFeature('memory'),\n hasDocumentKnowledge: () => featureFlag.hasFeature('documentKnowledge'),\n hasMoodAdaptation: () => featureFlag.hasFeature('moodAdaptation'),\n hasChatSuggestions: () => featureFlag.hasFeature('chatSuggestions'),\n hasTTS: () => featureFlag.hasFeature('tts'),\n hasSTT: () => featureFlag.hasFeature('stt'),\n hasAdminDashboard: () => featureFlag.hasFeature('adminDashboardEnabled'),\n hasLimitedAdminDashboard: () => featureFlag.hasFeature('limitedAdminDashboard'),\n hasSimpleSearch: () => featureFlag.hasFeature('semanticSearchSimple'),\n hasPremiumSearch: () => featureFlag.hasFeature('semanticSearchPremium'),\n hasAdvancedSearch: () => featureFlag.hasFeature('advancedSearch'),\n hasAdvancedMemories: () => featureFlag.hasFeature('advancedMemories'),\n \n // Admin and tier checking\n isAdmin: () => featureFlag.isAdmin(),\n getCurrentTier: () => featureFlag.getCurrentTier(),\n isOSSMode: () => featureFlag.isOSSMode(),\n isSubscribed: () => featureFlag.getEvaluation()?.isSubscribed ?? true,\n \n // Tier comparison helpers\n isPremiumTier: () => {\n const tier = featureFlag.getCurrentTier();\n return tier === 'premium' || tier === 'pro' || tier === 'team' || tier === 'trial';\n },\n \n isProTier: () => {\n const tier = featureFlag.getCurrentTier();\n return tier === 'pro' || tier === 'team' || tier === 'trial';\n },\n \n isTrialTier: () => featureFlag.getCurrentTier() === 'trial',\n \n isTeamTier: () => featureFlag.getCurrentTier() === 'team',\n \n isExpiredTier: () => featureFlag.getCurrentTier() === 'expired',\n \n // Upgrade checking\n needsUpgrade: (feature: FeatureKey, requiredTier?: SubscriptionTier) => {\n if (featureFlag.isAdmin() || featureFlag.isOSSMode()) {\n return false;\n }\n \n if (!featureFlag.hasFeature(feature)) {\n return requiredTier || 'premium';\n }\n \n return false;\n },\n \n // Trial usage tracking\n getTrialUsage: () => featureFlag.getEvaluation()?.trialUsage,\n isTrialLimitReached: (type: 'chat' | 'generate') => {\n const usage = featureFlag.getEvaluation()?.trialUsage;\n if (!usage) return false;\n \n if (type === 'chat') {\n return usage.chatRequestsUsed >= usage.chatRequestsLimit;\n } else {\n return usage.generateRequestsUsed >= usage.generateRequestsLimit;\n }\n },\n getTrialRemainingRequests: (type: 'chat' | 'generate') => {\n const usage = featureFlag.getEvaluation()?.trialUsage;\n if (!usage) return null;\n \n if (type === 'chat') {\n return Math.max(0, usage.chatRequestsLimit - usage.chatRequestsUsed);\n } else {\n return Math.max(0, usage.generateRequestsLimit - usage.generateRequestsUsed);\n }\n },\n \n // Management\n updateTier: (tier: SubscriptionTier) => featureFlag.updateTier(tier),\n refreshFeatures: () => featureFlag.refreshEvaluation(),\n \n // Full evaluation access\n getFullEvaluation: () => featureFlag.getEvaluation(),\n };\n};\n\n/**\n * Hook specifically for checking if features should be shown in UI\n */\nexport const useFeatureVisibility = () => {\n const features = useFeatures();\n \n return {\n // UI visibility helpers\n showMemoryToggle: () => features.hasMemory() || features.isOSSMode(),\n showDocumentUpload: () => features.hasDocumentKnowledge() || features.isOSSMode(),\n showMoodSettings: () => features.hasMoodAdaptation() || features.isOSSMode(),\n showSuggestions: () => features.hasChatSuggestions() || features.isOSSMode(),\n showVoiceControls: () => (features.hasTTS() || features.hasSTT()) || features.isOSSMode(),\n showAdminPanel: () => features.hasAdminDashboard() || features.isAdmin(),\n showLimitedAdminPanel: () => features.hasLimitedAdminDashboard() || features.isOSSMode(),\n showAdvancedSearch: () => features.hasPremiumSearch() || features.isOSSMode(),\n \n // Upgrade prompts\n shouldShowUpgradePrompt: (feature: FeatureKey) => {\n return !features.isOSSMode() && !features.isAdmin() && !features.hasFeature(feature);\n },\n \n getUpgradeMessage: (feature: FeatureKey) => {\n const tier = features.needsUpgrade(feature);\n if (!tier) return null;\n \n const featureNames: Record<FeatureKey, string> = {\n memory: 'Conversation Memory',\n documentKnowledge: 'Document Knowledge',\n moodAdaptation: 'Mood Adaptation',\n chatSuggestions: 'Chat Suggestions',\n tts: 'Text-to-Speech',\n stt: 'Speech-to-Text',\n adminDashboardEnabled: 'Admin Dashboard',\n limitedAdminDashboard: 'Limited Admin Dashboard',\n semanticSearchSimple: 'Simple Search',\n semanticSearchPremium: 'Premium Search',\n advancedSearch: 'Advanced Vector Search',\n advancedMemories: 'Advanced Vector Memories'\n };\n \n return `${featureNames[feature]} requires ${tier} subscription`;\n }\n };\n};\n\nexport default useFeatures;\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-3B4B-14DF77\nconst __banditFingerprint_hooks_useVectorStoretsx = 'BL-FP-CA5CF8-985C';\nconst __auditTrail_hooks_useVectorStoretsx = 'BL-AU-MGOIKVVG-347B';\n// File: useVectorStore.tsx | Path: src/hooks/useVectorStore.tsx | Hash: 3b4b985c\n\nimport { useState, useEffect, useCallback } from 'react';\nimport { debugLogger } from '../services/logging/debugLogger';\nimport { vectorDatabaseService, type VectorMemoryMetadata, type VectorMemory, type MemorySearchFilters, type VectorDocument, type SearchResult } from '../services/vectorDatabase/vectorDatabaseService';\nimport { vectorMigrationService, MigrationStatus, MigrationProgress } from '../services/vectorDatabase/vectorMigrationService';\nimport { useMemoryStore } from '../store/memoryStore';\nimport type { MemoryEntry } from '../store/memoryStore';\nimport { useKnowledgeStore } from '../store/knowledgeStore';\nimport type { KnowledgeDoc } from '../store/knowledgeStore';\nimport { useAuthenticationStore } from '../store/authenticationStore';\nimport { usePackageSettingsStore } from '../store/packageSettingsStore';\nimport { useFeatures } from './useFeatures';\nimport { useConversationSyncStore } from '../store/conversationSyncStore';\n\nexport interface VectorStoreStatus {\n isEnabled: boolean;\n isAvailable: boolean;\n isMigrating: boolean;\n migrationRequired: boolean;\n migrationProgress?: MigrationProgress;\n lastError?: string;\n}\n\nexport interface SearchOptions {\n memoryLimit?: number;\n documentLimit?: number;\n scoreThreshold?: number;\n useVector?: boolean; // Override auto-detection\n filters?: MemorySearchFilters;\n}\n\nconst toIsoString = (timestamp: number | Date): string => {\n if (timestamp instanceof Date) {\n return timestamp.toISOString();\n }\n return new Date(timestamp).toISOString();\n};\n\nconst memoryEntryToVectorMemory = (entry: MemoryEntry): VectorMemory => ({\n id: entry.id,\n content: entry.content,\n tags: entry.tags,\n score: undefined,\n uploadedBy: 'local',\n uploadedAt: toIsoString(entry.timestamp),\n source: entry.source,\n pinned: entry.pinned,\n lastReferencedAt: toIsoString(entry.timestamp),\n metadata: undefined,\n});\n\nconst knowledgeDocToVectorDocument = (doc: KnowledgeDoc): VectorDocument => ({\n id: doc.id,\n filename: doc.name,\n content: doc.content,\n mimeType: doc.mimeType || 'application/octet-stream',\n score: undefined,\n uploadedBy: doc.uploadedBy || 'local',\n uploadedAt: doc.addedDate ? doc.addedDate.toISOString() : new Date().toISOString(),\n isUserContent: doc.isUserContent ?? true,\n isTeamContent: doc.isTeamContent ?? false,\n contentSource: doc.contentSource ?? (doc.isTeamContent ? 'team' : 'user'),\n});\n\ntype RawFileRecord = Record<string, unknown>;\n\nconst rawFileRecordToVectorDocument = (record: RawFileRecord): VectorDocument | null => {\n if (!record || typeof record !== 'object') {\n return null;\n }\n\n const id = typeof record.id === 'string'\n ? record.id\n : typeof record.fileId === 'string'\n ? record.fileId\n : undefined;\n\n if (!id) {\n return null;\n }\n\n const filename = typeof record.filename === 'string'\n ? record.filename\n : typeof record.fileName === 'string'\n ? record.fileName\n : 'Untitled Document';\n\n const preview = typeof record.preview === 'string'\n ? record.preview\n : typeof record.summary === 'string'\n ? record.summary\n : typeof record.snippet === 'string'\n ? record.snippet\n : undefined;\n\n const content = typeof record.content === 'string' && record.content.trim().length > 0\n ? record.content\n : preview ?? '';\n const mimeType = typeof record.mimeType === 'string' ? record.mimeType : 'application/octet-stream';\n const uploadedBy = typeof record.uploadedBy === 'string' ? record.uploadedBy : 'unknown';\n const uploadedAt = typeof record.uploadedAt === 'string' ? record.uploadedAt : new Date().toISOString();\n const isUserContent = typeof record.isUserContent === 'boolean' ? record.isUserContent : true;\n const isTeamContent = typeof record.isTeamContent === 'boolean' ? record.isTeamContent : false;\n const contentSource = record.contentSource === 'team' ? 'team' : 'user';\n const score = typeof record.score === 'number' ? record.score : undefined;\n\n return {\n id,\n filename,\n content,\n mimeType,\n uploadedBy,\n uploadedAt,\n isUserContent,\n isTeamContent,\n contentSource,\n score\n };\n};\n\n/**\n * Advanced Vector Storage Hook\n * \n * Manages the transition between IndexedDB and Vector Database storage\n * when advanced semantic search is enabled. Handles feature gating,\n * migration, and unified API for both storage backends.\n * \n * Features:\n * - Automatic migration when advanced search is first enabled\n * - Unified API that works with both IndexedDB and Vector DB\n * - Feature gating based on subscription tier and admin claims\n * - Progress tracking for migration operations\n * - Fallback to IndexedDB if vector service unavailable\n */\nexport const useVectorStore = () => {\n const [status, setStatus] = useState<VectorStoreStatus>({\n isEnabled: false,\n isAvailable: false,\n isMigrating: false,\n migrationRequired: false\n });\n\n // Store access\n const memoryStore = useMemoryStore();\n const knowledgeStore = useKnowledgeStore();\n const authStore = useAuthenticationStore();\n const features = useFeatures();\n const isAdvancedVectorFeaturesEnabled = useConversationSyncStore((state) => state.isAdvancedVectorFeaturesEnabled);\n\n const hasAnyAdvancedFeatures = isAdvancedVectorFeaturesEnabled;\n const hasVectorAccess = features.isAdmin() || features.hasAdvancedSearch() || features.hasAdvancedMemories();\n\n // Check if using compatible AI provider (Ollama or Gateway with Ollama)\n const [hasCompatibleProvider, setHasCompatibleProvider] = useState(false);\n\n const checkProviderCompatibility = useCallback(async () => {\n try {\n const { useAIProviderStore } = await import('../store/aiProviderStore');\n const aiProviderState = useAIProviderStore.getState();\n const provider = aiProviderState.provider;\n const config = aiProviderState.config;\n \n if (!provider || !config) {\n setHasCompatibleProvider(false);\n return false;\n }\n\n // Allow both native Ollama and Bandit gateway providers to access vector storage\n const vectorCapableProviders = new Set(['ollama', 'bandit']);\n const isNativeOllama = config.type === 'ollama';\n const hasVectorCapableProvider = typeof config.provider === 'string' && vectorCapableProviders.has(config.provider);\n const isGatewayWithVectorSupport = config.type === 'gateway' && hasVectorCapableProvider;\n const isCompatible = isNativeOllama || isGatewayWithVectorSupport;\n \n setHasCompatibleProvider(isCompatible);\n return isCompatible;\n } catch (error) {\n debugLogger.warn('Could not check AI provider for vector compatibility', { error });\n setHasCompatibleProvider(false);\n return false;\n }\n }, []);\n\n // Check provider compatibility on mount and when dependencies change\n useEffect(() => {\n checkProviderCompatibility();\n }, [checkProviderCompatibility]);\n\n // Also check when AI provider store changes\n useEffect(() => {\n const checkOnProviderChange = async () => {\n // Add a small delay to ensure provider store is updated\n setTimeout(() => {\n checkProviderCompatibility();\n }, 100);\n };\n\n checkOnProviderChange();\n }, [authStore.token, checkProviderCompatibility]); // Re-check when auth token changes (which affects provider initialization)\n\n // Force a periodic check to catch late provider initialization\n useEffect(() => {\n const interval = setInterval(() => {\n if (!hasCompatibleProvider) {\n checkProviderCompatibility();\n }\n }, 2000); // Check every 2 seconds if not compatible\n\n return () => clearInterval(interval);\n }, [hasCompatibleProvider, checkProviderCompatibility]);\n\n /**\n * Initialize vector database service with auth token\n */\n const initializeVectorService = useCallback(async () => {\n try {\n // Get configuration from package settings instead of direct environment access\n const packageSettings = usePackageSettingsStore.getState().getSettings();\n \n if (!packageSettings) {\n debugLogger.warn('Package settings not available for vector service initialization');\n return;\n }\n \n const gatewayApiUrl = packageSettings.gatewayApiUrl;\n const fileStorageApiUrl = packageSettings.fileStorageApiUrl || packageSettings.gatewayApiUrl; // Fallback to gateway URL if file storage API not specified\n \n vectorDatabaseService.configure(gatewayApiUrl, fileStorageApiUrl);\n\n if (authStore.token) {\n vectorDatabaseService.setAuthToken(authStore.token);\n }\n\n const isAvailable = vectorDatabaseService.isAvailable();\n const enabledCondition = hasAnyAdvancedFeatures && hasVectorAccess && isAvailable && hasCompatibleProvider;\n \n setStatus(prev => ({\n ...prev,\n isAvailable,\n isEnabled: enabledCondition,\n migrationRequired: isAvailable && enabledCondition && !vectorMigrationService.isMigrationCompleted()\n }));\n\n debugLogger.info('Vector service initialized', {\n isAvailable,\n isAdvancedVectorFeaturesEnabled,\n hasVectorAccess,\n migrationRequired: !vectorMigrationService.isMigrationCompleted()\n });\n\n } catch (error) {\n debugLogger.error('Failed to initialize vector service', { error });\n setStatus(prev => ({\n ...prev,\n isAvailable: false,\n isEnabled: false,\n lastError: error instanceof Error ? error.message : String(error)\n }));\n }\n }, [authStore.token, hasAnyAdvancedFeatures, hasVectorAccess, hasCompatibleProvider, isAdvancedVectorFeaturesEnabled]);\n\n // Initialize vector service when dependencies change\n useEffect(() => {\n initializeVectorService();\n }, [initializeVectorService]);\n\n /**\n * Perform migration from IndexedDB to Vector Database\n */\n const performMigration = useCallback(async (options?: { cleanupAfterMigration?: boolean }): Promise<MigrationStatus> => {\n debugLogger.info('Starting vector database migration');\n \n setStatus(prev => ({ ...prev, isMigrating: true, lastError: undefined }));\n\n // Set up progress tracking\n const progressCallback = (progress: MigrationProgress) => {\n setStatus(prev => ({ ...prev, migrationProgress: progress }));\n };\n\n vectorMigrationService.onProgress(progressCallback);\n\n try {\n const result = await vectorMigrationService.performMigration(options);\n \n setStatus(prev => ({\n ...prev,\n isMigrating: false,\n migrationRequired: !result.success,\n migrationProgress: undefined,\n lastError: result.success ? undefined : result.errors.join('; ')\n }));\n\n if (result.success) {\n debugLogger.info('Vector migration completed successfully', result);\n // Refresh stores to ensure they're updated\n await memoryStore.hydrate();\n await knowledgeStore.loadDocs();\n } else {\n debugLogger.error('Vector migration failed', result);\n }\n\n return result;\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n debugLogger.error('Migration failed with exception', { error: errorMsg });\n \n setStatus(prev => ({\n ...prev,\n isMigrating: false,\n lastError: errorMsg\n }));\n\n return {\n success: false,\n migratedMemories: 0,\n migratedDocuments: 0,\n errors: [errorMsg],\n warnings: [],\n totalTime: 0\n };\n } finally {\n vectorMigrationService.removeProgressCallback(progressCallback);\n }\n }, [memoryStore, knowledgeStore]);\n\n /**\n * Add a memory using the appropriate storage backend\n */\n const addMemory = useCallback(async (\n content: string,\n tags: string[] = [],\n source: 'auto' | 'user' = 'user',\n options: {\n metadata?: VectorMemoryMetadata;\n pinned?: boolean;\n title?: string;\n lastReferencedAt?: string;\n } = {}\n ): Promise<{ success: boolean; id?: string; error?: string }> => {\n if (status.isEnabled && !status.migrationRequired) {\n // Use vector database\n try {\n const result = await vectorDatabaseService.createMemory(\n content,\n {\n title: options.title ?? `Memory from ${new Date().toLocaleDateString()}`,\n tags,\n source,\n pinned: options.pinned,\n metadata: options.metadata,\n lastReferencedAt: options.lastReferencedAt,\n }\n );\n \n if (result.success) {\n debugLogger.info('Memory added to vector database', { memoryId: result.memoryId });\n return { success: true, id: result.memoryId };\n } else {\n throw new Error(result.message || 'Unknown error');\n }\n } catch (error) {\n debugLogger.error('Failed to add memory to vector database', { error });\n return { \n success: false, \n error: error instanceof Error ? error.message : String(error) \n };\n }\n } else {\n // Use IndexedDB fallback\n try {\n await memoryStore.addMemory(content, tags, source);\n debugLogger.info('Memory added to IndexedDB', { content: content.slice(0, 100) });\n return { success: true };\n } catch (error) {\n debugLogger.error('Failed to add memory to IndexedDB', { error });\n return { \n success: false, \n error: error instanceof Error ? error.message : String(error) \n };\n }\n }\n }, [status.isEnabled, status.migrationRequired, memoryStore]);\n\n /**\n * Search memories using the appropriate backend\n */\n const searchMemories = useCallback(async (\n query: string,\n options: SearchOptions = {}\n ): Promise<VectorMemory[]> => {\n const { \n memoryLimit = 10, \n scoreThreshold = 0.6, \n useVector = status.isEnabled && !status.migrationRequired \n } = options;\n\n if (useVector) {\n // Use vector database search\n try {\n const results = await vectorDatabaseService.searchMemories(query, memoryLimit, scoreThreshold, options.filters);\n debugLogger.info('Vector memory search completed', { \n query: query.slice(0, 50), \n resultsCount: results.length \n });\n return results;\n } catch (error) {\n debugLogger.error('Vector memory search failed, falling back to IndexedDB', { error });\n // Fall through to IndexedDB search\n }\n }\n\n // Use IndexedDB search\n const results = memoryStore.searchMemory(query);\n debugLogger.info('IndexedDB memory search completed', { \n query: query.slice(0, 50), \n resultsCount: results.length \n });\n\n return results.slice(0, memoryLimit).map((entry) => ({\n id: entry.id,\n content: entry.content,\n title: undefined,\n tags: entry.tags,\n score: undefined,\n uploadedBy: 'local',\n uploadedAt: new Date(entry.timestamp).toISOString(),\n source: entry.source,\n pinned: entry.pinned,\n lastReferencedAt: new Date(entry.timestamp).toISOString(),\n metadata: undefined,\n }));\n }, [status.isEnabled, status.migrationRequired, memoryStore]);\n\n /**\n * Get user's memories with pagination\n */\n const getUserMemories = useCallback(async (\n skip = 0, \n limit = 50\n ): Promise<VectorMemory[]> => {\n if (status.isEnabled && !status.migrationRequired) {\n // Use vector database\n try {\n const results = await vectorDatabaseService.getMyMemories(skip, limit);\n debugLogger.info('Vector memories retrieved', { count: results.length });\n return results;\n } catch (error) {\n debugLogger.error('Failed to get vector memories, falling back to IndexedDB', { error });\n // Fall through to IndexedDB\n }\n }\n\n // Use IndexedDB fallback\n await memoryStore.hydrate();\n const allEntries = memoryStore.entries;\n const paginatedEntries = allEntries.slice(skip, skip + limit);\n debugLogger.info('IndexedDB memories retrieved', { count: paginatedEntries.length });\n return paginatedEntries.map(memoryEntryToVectorMemory);\n }, [status.isEnabled, status.migrationRequired, memoryStore]);\n\n /**\n * Delete a memory\n */\n const deleteMemory = useCallback(async (\n memoryId: string\n ): Promise<{ success: boolean; error?: string }> => {\n if (status.isEnabled && !status.migrationRequired) {\n // Use vector database\n try {\n const success = await vectorDatabaseService.deleteMemory(memoryId);\n if (success) {\n debugLogger.info('Memory deleted from vector database', { memoryId });\n return { success: true };\n } else {\n throw new Error('Vector deletion failed');\n }\n } catch (error) {\n debugLogger.error('Failed to delete vector memory', { memoryId, error });\n return { \n success: false, \n error: error instanceof Error ? error.message : String(error) \n };\n }\n } else {\n // Use IndexedDB fallback\n try {\n await memoryStore.removeMemory(memoryId);\n debugLogger.info('Memory deleted from IndexedDB', { memoryId });\n return { success: true };\n } catch (error) {\n debugLogger.error('Failed to delete IndexedDB memory', { memoryId, error });\n return { \n success: false, \n error: error instanceof Error ? error.message : String(error) \n };\n }\n }\n }, [status.isEnabled, status.migrationRequired, memoryStore]);\n\n /**\n * Update a memory using the appropriate storage backend\n */\n const updateMemory = useCallback(async (\n memoryId: string,\n updates: { pinned?: boolean; content?: string; title?: string; tags?: string[] }\n ): Promise<{ success: boolean; error?: string }> => {\n if (status.isEnabled && !status.migrationRequired) {\n // Use vector database\n try {\n const success = await vectorDatabaseService.updateMemory(memoryId, updates);\n if (success) {\n debugLogger.info('Memory updated in vector database', { memoryId, updates });\n return { success: true };\n } else {\n throw new Error('Vector update failed');\n }\n } catch (error) {\n debugLogger.error('Failed to update vector memory', { memoryId, error });\n return { \n success: false, \n error: error instanceof Error ? error.message : String(error) \n };\n }\n } else {\n // Use IndexedDB fallback - for pinning\n if (updates.pinned !== undefined) {\n try {\n await memoryStore.togglePinMemory(memoryId);\n debugLogger.info('Memory pin status updated in IndexedDB', { memoryId });\n return { success: true };\n } catch (error) {\n debugLogger.error('Failed to update IndexedDB memory pin', { memoryId, error });\n return { \n success: false, \n error: error instanceof Error ? error.message : String(error) \n };\n }\n }\n return { success: false, error: 'Update not supported for IndexedDB' };\n }\n }, [status.isEnabled, status.migrationRequired, memoryStore]);\n\n /**\n * Batch create memories using the appropriate storage backend\n */\n const batchCreateMemories = useCallback(async (\n memories: Array<{ content: string; title?: string; tags?: string[] }>,\n mode: 'append' | 'replace' | 'smartDedupe' = 'append',\n clearExisting: boolean = false\n ): Promise<{\n success: boolean;\n message: string;\n results: Array<{\n content: string;\n success: boolean;\n memoryId?: string;\n mongoId?: string;\n contentLength?: number;\n message: string;\n action: string;\n }>;\n summary: {\n mode: string;\n totalProcessed: number;\n successCount: number;\n failureCount: number;\n skippedCount: number;\n clearedExistingCount: number;\n clearedExisting: boolean;\n };\n }> => {\n if (status.isEnabled && !status.migrationRequired) {\n // Use vector database\n try {\n const result = await vectorDatabaseService.batchCreateMemories(memories, mode, clearExisting);\n debugLogger.info('Batch memories created in vector database', { \n total: memories.length,\n successful: result.summary.successCount,\n mode \n });\n return result;\n } catch (error) {\n debugLogger.error('Failed to batch create vector memories', { error });\n throw error;\n }\n } else {\n // Use IndexedDB fallback - simulate batch response\n const results: Array<{\n content: string;\n success: boolean;\n memoryId?: string;\n mongoId?: string;\n contentLength?: number;\n message: string;\n action: string;\n }> = [];\n\n let successCount = 0;\n let failureCount = 0;\n\n // Handle clear existing for replace mode\n if (mode === 'replace' || clearExisting) {\n try {\n await memoryStore.clearMemories();\n debugLogger.info('Cleared existing IndexedDB memories for batch replace');\n } catch (error) {\n debugLogger.error('Failed to clear existing memories', { error });\n }\n }\n\n // Add each memory to IndexedDB\n for (const memory of memories) {\n try {\n await memoryStore.addMemory(memory.content, memory.tags || [], 'user');\n results.push({\n content: memory.content.substring(0, 100) + '...',\n success: true,\n contentLength: memory.content.length,\n message: 'Memory added successfully to IndexedDB',\n action: 'added'\n });\n successCount++;\n } catch (error) {\n results.push({\n content: memory.content.substring(0, 100) + '...',\n success: false,\n message: error instanceof Error ? error.message : String(error),\n action: 'failed'\n });\n failureCount++;\n }\n }\n\n debugLogger.info('Batch memories created in IndexedDB', { \n total: memories.length,\n successful: successCount,\n failed: failureCount,\n mode \n });\n\n return {\n success: failureCount === 0,\n message: `Batch processing completed. ${successCount}/${memories.length} memories added successfully (IndexedDB fallback).`,\n results,\n summary: {\n mode: mode.charAt(0).toUpperCase() + mode.slice(1),\n totalProcessed: memories.length,\n successCount,\n failureCount,\n skippedCount: 0,\n clearedExistingCount: mode === 'replace' || clearExisting ? 1 : 0,\n clearedExisting: mode === 'replace' || clearExisting\n }\n };\n }\n }, [status.isEnabled, status.migrationRequired, memoryStore]);\n\n /**\n * Advanced batch create memories with progress reporting and chunking\n */\n const batchCreateMemoriesAdvanced = useCallback(async (\n memories: Array<{ content: string; title?: string; tags?: string[] }>,\n options: {\n mode?: 'append' | 'replace' | 'smartDedupe';\n clearExisting?: boolean;\n chunkSize?: number;\n onProgress?: (current: number, total: number, message: string) => void;\n validateContent?: boolean;\n } = {}\n ) => {\n if (status.isEnabled && !status.migrationRequired) {\n // Use vector database with advanced features\n return await vectorDatabaseService.batchCreateMemoriesAdvanced(memories, options);\n } else {\n // Fallback to basic batch operation for IndexedDB\n const basicResult = await batchCreateMemories(\n memories, \n options.mode || 'append', \n options.clearExisting || false\n );\n \n // Convert to advanced result format\n return {\n success: basicResult.success,\n message: basicResult.message,\n totalMemories: memories.length,\n successCount: basicResult.summary.successCount,\n failureCount: basicResult.summary.failureCount,\n skippedCount: basicResult.summary.skippedCount,\n errors: basicResult.results.filter(r => !r.success).map(r => r.message),\n warnings: [],\n chunks: 1,\n duration: 0\n };\n }\n }, [status.isEnabled, status.migrationRequired, batchCreateMemories]);\n\n /**\n * Batch import memories from local storage to vector database\n * This is useful for migrating existing IndexedDB memories to vector storage\n */\n const batchImportMemories = useCallback(async (\n fromIndexedDB: boolean = true,\n mode: 'append' | 'replace' | 'smartDedupe' = 'append'\n ): Promise<{\n success: boolean;\n message: string;\n migratedCount: number;\n totalMemories: number;\n errors: string[];\n }> => {\n if (!status.isEnabled || status.migrationRequired) {\n return {\n success: false,\n message: 'Vector database not available for import',\n migratedCount: 0,\n totalMemories: 0,\n errors: ['Vector database not enabled or migration required']\n };\n }\n\n if (!fromIndexedDB) {\n return {\n success: false,\n message: 'Only IndexedDB import is currently supported',\n migratedCount: 0,\n totalMemories: 0,\n errors: ['Unsupported import source']\n };\n }\n\n try {\n // Get all memories from IndexedDB\n await memoryStore.hydrate();\n const indexedDBMemories = memoryStore.entries;\n\n if (indexedDBMemories.length === 0) {\n return {\n success: true,\n message: 'No memories found in IndexedDB to import',\n migratedCount: 0,\n totalMemories: 0,\n errors: []\n };\n }\n\n // Convert IndexedDB format to vector format\n const memoriesToImport = indexedDBMemories.map(entry => ({\n content: entry.content,\n title: `Imported Memory - ${new Date(entry.timestamp).toLocaleDateString()}`,\n tags: entry.tags || []\n }));\n\n debugLogger.info('Starting batch import from IndexedDB', {\n totalMemories: memoriesToImport.length,\n mode\n });\n\n // Import to vector database\n const result = await vectorDatabaseService.batchCreateMemories(memoriesToImport, mode, false);\n\n return {\n success: result.success,\n message: `Import completed: ${result.summary.successCount}/${memoriesToImport.length} memories imported`,\n migratedCount: result.summary.successCount,\n totalMemories: memoriesToImport.length,\n errors: result.results\n .filter(r => !r.success)\n .map(r => r.message)\n };\n\n } catch (error) {\n debugLogger.error('Failed to import memories from IndexedDB', { error });\n return {\n success: false,\n message: error instanceof Error ? error.message : String(error),\n migratedCount: 0,\n totalMemories: 0,\n errors: [error instanceof Error ? error.message : String(error)]\n };\n }\n }, [status.isEnabled, status.migrationRequired, memoryStore]);\n\n /**\n * Upload and embed document\n */\n const uploadDocument = useCallback(async (\n file: File, \n shareWithTeam = true\n ): Promise<{ success: boolean; fileId?: string; error?: string }> => {\n if (!status.isEnabled || status.migrationRequired) {\n return { \n success: false, \n error: 'Vector database not available - document upload requires advanced features' \n };\n }\n\n try {\n // Upload file to the configured file storage service\n const uploadResult = await vectorDatabaseService.uploadFile(file, shareWithTeam);\n \n if (!uploadResult.success || !uploadResult.fileId) {\n throw new Error(uploadResult.message || 'Upload failed');\n }\n\n // Embed in vector database\n const embedResult = await vectorDatabaseService.embedDocument(uploadResult.fileId, shareWithTeam);\n \n if (!embedResult.success) {\n throw new Error(embedResult.message || 'Embedding failed');\n }\n\n debugLogger.info('Document uploaded and embedded successfully', { \n filename: file.name,\n fileId: uploadResult.fileId \n });\n\n return { success: true, fileId: uploadResult.fileId };\n } catch (error) {\n debugLogger.error('Failed to upload document', { filename: file.name, error });\n return { \n success: false, \n error: error instanceof Error ? error.message : String(error) \n };\n }\n }, [status.isEnabled, status.migrationRequired]);\n\n /**\n * Search documents using vector database\n */\n const searchDocuments = useCallback(async (\n query: string, \n options: SearchOptions = {}\n ): Promise<VectorDocument[]> => {\n const { documentLimit = 20, scoreThreshold = 0.7 } = options;\n\n if (!status.isEnabled || status.migrationRequired) {\n debugLogger.warn('Vector document search not available, falling back to knowledge store');\n // Fallback to basic knowledge store search\n const docs = knowledgeStore.docs.filter(doc => \n doc.content.toLowerCase().includes(query.toLowerCase()) ||\n doc.name.toLowerCase().includes(query.toLowerCase())\n );\n return docs.slice(0, documentLimit).map(knowledgeDocToVectorDocument);\n }\n\n try {\n const results = await vectorDatabaseService.searchDocuments(query, documentLimit, scoreThreshold);\n debugLogger.info('Vector document search completed', { \n query: query.slice(0, 50), \n resultsCount: results.length \n });\n return results;\n } catch (error) {\n debugLogger.error('Vector document search failed', { error });\n return [];\n }\n }, [status.isEnabled, status.migrationRequired, knowledgeStore.docs]);\n\n /**\n * Combined search across both memories and documents\n */\n const searchAll = useCallback(async (\n query: string, \n options: SearchOptions = {}\n ): Promise<SearchResult> => {\n if (status.isEnabled && !status.migrationRequired) {\n // Use vector database combined search\n try {\n const result = await vectorDatabaseService.searchAll(\n query,\n options.memoryLimit,\n options.documentLimit,\n options.scoreThreshold\n );\n \n debugLogger.info('Vector combined search completed', result);\n return result;\n } catch (error) {\n debugLogger.error('Vector combined search failed, falling back', { error });\n // Fall through to fallback\n }\n }\n\n // Fallback to separate searches\n try {\n const [memories, documents] = await Promise.all([\n searchMemories(query, { ...options, useVector: false }),\n searchDocuments(query, options)\n ]);\n\n return {\n memories,\n documents,\n success: true,\n message: `Found ${memories.length} memories and ${documents.length} documents (fallback search)`,\n };\n } catch (error) {\n debugLogger.error('Fallback combined search failed', { error });\n return {\n memories: [],\n documents: [],\n success: false,\n message: error instanceof Error ? error.message : String(error)\n };\n }\n }, [status.isEnabled, status.migrationRequired, searchMemories, searchDocuments]);\n\n /**\n * Get migration estimation\n */\n const getMigrationEstimate = useCallback(async () => {\n return vectorMigrationService.estimateMigration();\n }, []);\n\n // Initialize on mount and when dependencies change\n useEffect(() => {\n initializeVectorService();\n }, [initializeVectorService]);\n\n /**\n * Get user's uploaded documents from vector database\n */\n const getUserDocuments = useCallback(async (\n skip = 0, \n limit = 50\n ): Promise<VectorDocument[]> => {\n if (!status.isEnabled || status.migrationRequired) {\n return [];\n }\n\n try {\n const records = await vectorDatabaseService.getUserFiles(skip, limit);\n const documents = records\n .map(rawFileRecordToVectorDocument)\n .filter((doc): doc is VectorDocument => doc !== null);\n\n debugLogger.info('Retrieved user documents from vector database', { \n count: documents.length \n });\n return documents;\n } catch (error) {\n debugLogger.error('Failed to get user documents', { error });\n return [];\n }\n }, [status.isEnabled, status.migrationRequired]);\n\n /**\n * Delete a document from vector database\n */\n const deleteDocument = useCallback(async (\n fileId: string\n ): Promise<{ success: boolean; error?: string }> => {\n if (!status.isEnabled || status.migrationRequired) {\n return { \n success: false, \n error: 'Vector database not available' \n };\n }\n\n try {\n const success = await vectorDatabaseService.deleteDocument(fileId);\n if (success) {\n debugLogger.info('Document deleted from vector database', { fileId });\n return { success: true };\n } else {\n throw new Error('Document deletion failed');\n }\n } catch (error) {\n debugLogger.error('Failed to delete document', { fileId, error });\n return { \n success: false, \n error: error instanceof Error ? error.message : String(error) \n };\n }\n }, [status.isEnabled, status.migrationRequired]);\n\n // Auto-trigger migration if required and user just gained access\n useEffect(() => {\n if (status.migrationRequired && status.isAvailable && !status.isMigrating) {\n debugLogger.info('Auto-triggering vector migration for newly enabled advanced features');\n // Auto-migrate when vector storage becomes available for users with access\n performMigration({ cleanupAfterMigration: false }).then(result => {\n debugLogger.info('Migration completed', { result });\n }).catch(error => {\n debugLogger.error('Auto-triggered migration failed', { error });\n });\n }\n }, [status.migrationRequired, status.isAvailable, status.isMigrating, performMigration]);\n\n /**\n * Download a file from vector database/file-storage using MongoDB ObjectId\n */\n const downloadVectorFile = useCallback(async (\n fileId: string,\n filename: string\n ): Promise<void> => {\n if (!status.isEnabled) {\n throw new Error('Vector database not enabled');\n }\n\n try {\n await vectorDatabaseService.downloadFile(fileId, filename);\n debugLogger.info('File downloaded successfully', { fileId, filename });\n } catch (error) {\n debugLogger.error('Failed to download file', { fileId, filename, error });\n throw error;\n }\n }, [status.isEnabled]);\n\n /**\n * Get file preview content using MongoDB ObjectId\n */\n const getFilePreview = useCallback(async (\n fileId: string\n ): Promise<{ content: string; mimeType: string } | null> => {\n if (!status.isEnabled) {\n return null;\n }\n\n try {\n const preview = await vectorDatabaseService.getFilePreview(fileId);\n debugLogger.info('File preview retrieved', { fileId, hasContent: !!preview?.content });\n return preview;\n } catch (error) {\n debugLogger.error('Failed to get file preview', { fileId, error });\n return null;\n }\n }, [status.isEnabled]);\n\n /**\n * Get file blob for displaying full content in modal using MongoDB ObjectId\n */\n const getFileBlob = useCallback(async (\n fileId: string\n ): Promise<Blob> => {\n if (!status.isEnabled) {\n throw new Error('Vector database not enabled');\n }\n\n try {\n const blob = await vectorDatabaseService.getFileBlob(fileId);\n debugLogger.info('File blob retrieved', { fileId, size: blob.size });\n return blob;\n } catch (error) {\n debugLogger.error('Failed to get file blob', { fileId, error });\n throw error;\n }\n }, [status.isEnabled]);\n\n // Manual refresh function for debugging\n const refreshCompatibilityCheck = useCallback(() => {\n checkProviderCompatibility();\n }, [checkProviderCompatibility]);\n\n return {\n // Status\n status,\n isVectorEnabled: status.isEnabled && !status.migrationRequired,\n \n // Debug functions\n refreshCompatibilityCheck,\n \n // Migration\n performMigration,\n getMigrationEstimate,\n \n // Memory operations\n addMemory,\n batchCreateMemories,\n batchCreateMemoriesAdvanced,\n batchImportMemories,\n searchMemories,\n getUserMemories,\n deleteMemory,\n updateMemory,\n \n // Document operations\n uploadDocument,\n searchDocuments,\n getUserDocuments,\n deleteDocument,\n downloadVectorFile,\n getFilePreview,\n getFileBlob,\n \n // Combined operations\n searchAll,\n \n // Utilities\n initializeVectorService\n };\n};\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-85A0-F6B027\nconst __banditFingerprint_hooks_useKnowledgeStoretsx = 'BL-FP-418893-DFF3';\nconst __auditTrail_hooks_useKnowledgeStoretsx = 'BL-AU-MGOIKVV2-OGXL';\n// File: useKnowledgeStore.tsx | Path: src/chat/hooks/useKnowledgeStore.tsx | Hash: 85a0dff3\n\nimport { useState, useCallback, useMemo } from \"react\";\nimport { useKnowledgeStore as useZustandKnowledgeStore, KnowledgeDoc } from \"../../store/knowledgeStore\";\nimport indexedDBService from \"../../services/indexedDB/indexedDBService\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport mammoth from \"mammoth\";\nimport * as pdfjsLib from \"pdfjs-dist/legacy/build/pdf\";\nimport type { TextItem, TextMarkedContent } from \"pdfjs-dist/types/src/display/api\";\nimport { embeddingService } from \"../../services/embedding/embeddingService\";\nimport { debugLogger } from \"../../services/logging/debugLogger\";\nimport { vectorDatabaseService } from \"../../services/vectorDatabase/vectorDatabaseService\";\nimport { useVectorStore } from \"../../hooks/useVectorStore\";\n\n// Re-export for backward compatibility\nexport type { KnowledgeDoc };\n\n/**\n * Knowledge Store Hook - Dual Storage Pattern\n * \n * This hook supports two different storage patterns based on user subscription and preferences:\n * \n * 1. **Local Storage (Basic Users)**:\n * - Users without vector DB access (lower tier subscriptions)\n * - Files are parsed locally and content + embeddings stored in IndexedDB\n * - Uses fake embedding service for similarity search\n * - Supports text files, DOCX, and limited PDF text extraction\n * \n * 2. **Vector Database + S3 (Advanced Users)**:\n * - Users with enhanced search features enabled\n * - Files uploaded to S3, embeddings generated server-side\n * - Only metadata stored in IndexedDB (lightweight references)\n * - Full PDF preview and advanced semantic search capabilities\n * \n * The storage method is automatically determined by `isVectorEnabled` from useVectorStore.\n */\n\n// PDF worker will be configured when package settings are available\n// pdfjsLib.GlobalWorkerOptions.workerSrc = \"/pdf.worker.js\";\n\nconst DB_NAME = \"banditKnowledge\";\nconst STORE_NAME = \"documents\";\nconst MAX_FILES = 20;\n\ntype KnowledgeDocWithVectorMetadata = KnowledgeDoc & { _vectorResult?: unknown };\n\nconst hasVectorMetadata = (doc: KnowledgeDoc): doc is KnowledgeDocWithVectorMetadata =>\n typeof doc === \"object\" && doc !== null && \"_vectorResult\" in doc;\n\nconst isTextItem = (item: TextItem | TextMarkedContent): item is TextItem =>\n typeof item === \"object\" && item !== null && \"str\" in item;\n\nexport const useKnowledgeStore = () => {\n const [documents, setDocuments] = useState<KnowledgeDoc[]>([]);\n\n const vectorStore = useVectorStore();\n const { isVectorEnabled, uploadDocument } = vectorStore;\n\n const storeConfigs = useMemo(() => [{ name: STORE_NAME, keyPath: \"id\" }], []);\n\n const loadDocuments = useCallback(async () => {\n const docs = await indexedDBService.getAll<KnowledgeDoc>(DB_NAME, 1, STORE_NAME, storeConfigs);\n setDocuments(docs);\n \n // Sync with zustand store - set the docs directly\n useZustandKnowledgeStore.setState({ \n docs: docs || [], \n isLoaded: true \n });\n debugLogger.debug(\"Synced knowledge docs with store\", { count: docs?.length || 0 });\n }, [storeConfigs]);\n\n const removeDocument = async (id: string) => {\n try {\n // First, try to delete from Gateway API (vector database, S3, and MongoDB)\n // This handles vector documents stored in the cloud\n const gatewayDeleteSuccess = await vectorDatabaseService.deleteDocument(id);\n if (gatewayDeleteSuccess) {\n debugLogger.info(\"Document deleted from Gateway API\", { id });\n } else {\n debugLogger.warn(\"Failed to delete from Gateway API or document not found\", { id });\n }\n } catch (error) {\n debugLogger.error(\"Error deleting from Gateway API\", { id, error });\n }\n\n try {\n // Always remove from local IndexedDB storage\n await indexedDBService.delete(DB_NAME, 1, STORE_NAME, id, storeConfigs);\n debugLogger.debug(\"Document removed from IndexedDB\", { id });\n } catch (error) {\n debugLogger.error(\"Failed to remove from IndexedDB\", { id, error });\n }\n\n // Reload documents to refresh the UI\n await loadDocuments();\n };\n\n const clearAllDocuments = async () => {\n await indexedDBService.clear(DB_NAME, 1, STORE_NAME, storeConfigs);\n await loadDocuments();\n };\n\n const addDocuments = async (files: File[]) => {\n const allKeys = await indexedDBService.getAllKeys(DB_NAME, 1, STORE_NAME, storeConfigs);\n if (allKeys.length + files.length > MAX_FILES) {\n throw new Error(`Max ${MAX_FILES} documents allowed.`);\n }\n\n const successfulUploads: KnowledgeDoc[] = [];\n \n for (const file of files) {\n try {\n debugLogger.debug(\"Processing file\", { filename: file.name, type: file.type });\n \n if (isVectorEnabled && uploadDocument) {\n // Advanced users: Use vector database + S3 storage (like Knowledge Tab)\n const result = await uploadDocument(file, true);\n \n if (result.success && result.fileId) {\n const doc: KnowledgeDoc = {\n id: uuidv4(),\n name: file.name,\n originalFileName: file.name,\n s3Url: result.fileId, // Store fileId as s3Url for file access\n addedDate: new Date(),\n content: \"\", // Content is in vector DB, not stored locally\n embedding: [], // Embedding is in vector DB\n mimeType: file.type,\n size: file.size,\n };\n \n // Save metadata to IndexedDB (lightweight reference)\n await indexedDBService.put(DB_NAME, 1, STORE_NAME, doc, storeConfigs);\n successfulUploads.push(doc);\n \n debugLogger.debug(\"Document uploaded to vector database\", { filename: file.name, fileId: result.fileId });\n } else {\n throw new Error(result.error || 'Vector upload failed');\n }\n } else {\n // Basic users: Use local IndexedDB storage with parsed content and embeddings\n const parseResult = await parseFile(file);\n if (parseResult.trim().length === 0) {\n debugLogger.warn(\"File has no content\", { filename: file.name });\n continue;\n }\n \n debugLogger.debug(\"File content parsed\", { filename: file.name, contentLength: parseResult.length });\n \n // Store raw file data as base64 for consistent download behavior\n const arrayBuffer = await file.arrayBuffer();\n // Use chunked approach to avoid \"Maximum call stack size exceeded\" for large files\n const uint8Array = new Uint8Array(arrayBuffer);\n let binaryString = '';\n const chunkSize = 8192; // Process 8KB chunks to avoid stack overflow\n \n for (let i = 0; i < uint8Array.length; i += chunkSize) {\n const chunk = uint8Array.slice(i, i + chunkSize);\n binaryString += String.fromCharCode.apply(null, Array.from(chunk));\n }\n \n const base64Data = btoa(binaryString);\n debugLogger.debug(\"Raw file data encoded\", { filename: file.name, rawDataLength: base64Data.length });\n \n const embedding = await embeddingService.generate(parseResult);\n debugLogger.debug(\"Embedding generated\", { filename: file.name, embeddingLength: embedding?.length });\n \n const doc: KnowledgeDoc = {\n id: uuidv4(),\n name: file.name,\n content: parseResult,\n rawData: base64Data, // Store original file data\n originalFileName: file.name,\n embedding,\n addedDate: new Date(),\n mimeType: file.type,\n size: file.size,\n };\n \n await indexedDBService.put(DB_NAME, 1, STORE_NAME, doc, storeConfigs);\n successfulUploads.push(doc);\n \n debugLogger.debug(\"Document saved to IndexedDB\", { filename: file.name, id: doc.id });\n }\n \n } catch (error) {\n debugLogger.error(\"Failed to process file\", { filename: file.name, error });\n throw new Error(`Failed to process ${file.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n \n if (successfulUploads.length === 0) {\n throw new Error(\"No files were successfully processed\");\n }\n \n // Reload documents and sync with zustand store\n await loadDocuments();\n \n debugLogger.info(\"Documents added successfully\", { \n count: successfulUploads.length,\n filenames: successfulUploads.map(d => d.name),\n storageMethod: isVectorEnabled ? 'vector-db' : 'indexed-db'\n });\n };\n\n // Helper function to determine if a document is stored in vector DB\n const isVectorDocument = (doc: KnowledgeDoc): boolean => {\n if (!doc) return false;\n\n const hasExplicitVectorMarker = Boolean(\n (doc.s3Url && String(doc.s3Url).trim().length > 0) ||\n (hasVectorMetadata(doc) && doc._vectorResult)\n );\n\n if (hasExplicitVectorMarker) {\n return true;\n }\n\n const looksLikeMongoId = typeof doc.id === \"string\" && /^[0-9a-f]{24}$/i.test(doc.id);\n const lacksInlineContent = !doc.content || doc.content.length === 0;\n\n return looksLikeMongoId && lacksInlineContent;\n };\n\n const parseFile = async (file: File): Promise<string> => {\n const name = file.name.toLowerCase();\n\n try {\n debugLogger.debug(\"Parsing file\", { filename: file.name, type: file.type, size: file.size });\n \n if (\n file.type.startsWith(\"text/\") ||\n name.endsWith(\".txt\") ||\n name.endsWith(\".md\") ||\n name.endsWith(\".json\") ||\n name.endsWith(\".cs\") ||\n name.endsWith(\".js\") ||\n name.endsWith(\".ts\") ||\n name.endsWith(\".tsx\") ||\n name.endsWith(\".jsx\") ||\n name.endsWith(\".py\") ||\n name.endsWith(\".java\") ||\n name.endsWith(\".cpp\") ||\n name.endsWith(\".c\") ||\n name.endsWith(\".html\") ||\n name.endsWith(\".css\") ||\n name.endsWith(\".php\") ||\n name.endsWith(\".rb\") ||\n name.endsWith(\".go\") ||\n name.endsWith(\".rs\") ||\n name.endsWith(\".kt\") ||\n name.endsWith(\".swift\") ||\n name.endsWith(\".scala\") ||\n name.endsWith(\".sh\") ||\n name.endsWith(\".bat\") ||\n name.endsWith(\".ps1\") ||\n name.endsWith(\".xml\") ||\n name.endsWith(\".yaml\") ||\n name.endsWith(\".yml\") ||\n name.endsWith(\".csv\")\n ) {\n const content = await file.text();\n debugLogger.debug(\"Text file parsed\", { filename: file.name, contentLength: content.length });\n return content;\n }\n\n if (name.endsWith(\".docx\")) {\n debugLogger.debug(\"Parsing DOCX file\", { filename: file.name });\n const arrayBuffer = await file.arrayBuffer();\n const { value } = await mammoth.extractRawText({ arrayBuffer });\n debugLogger.debug(\"DOCX file parsed\", { filename: file.name, contentLength: value.length });\n return value;\n }\n\n if (name.endsWith(\".pdf\")) {\n debugLogger.debug(\"Parsing PDF file\", { filename: file.name });\n // Use Burtson CDN PDF worker\n pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.burtson.ai/scripts/pdf.worker.js';\n \n const buffer = await file.arrayBuffer();\n const pdf = await pdfjsLib.getDocument({ data: buffer }).promise;\n\n const pages = await Promise.all(\n Array.from({ length: Math.min(10, pdf.numPages) }, async (_, i) => {\n const page = await pdf.getPage(i + 1);\n const content = await page.getTextContent();\n const items = content.items as Array<TextItem | TextMarkedContent>;\n return items\n .map((item) => (isTextItem(item) ? item.str : \"\"))\n .join(\" \");\n })\n );\n const result = pages.join(\"\\n\\n\");\n \n debugLogger.debug(\"PDF file parsed\", { filename: file.name, contentLength: result.length, pageCount: pdf.numPages });\n return result;\n }\n \n debugLogger.warn(\"Unsupported file type\", { filename: file.name, type: file.type });\n throw new Error(`Unsupported file type: ${file.type}`);\n \n } catch (err) {\n debugLogger.error(\"Failed to parse file\", { filename: file.name, error: err });\n throw err;\n }\n };\n\n const searchDocuments = async (query: string): Promise<KnowledgeDoc[]> => {\n if (!query.trim()) return [];\n\n const queryEmbedding = await embeddingService.generate(query);\n const scored: { doc: KnowledgeDoc; score: number }[] = [];\n\n for (const doc of documents) {\n if (doc.embedding) {\n const score = embeddingService.cosineSimilarity(queryEmbedding, doc.embedding);\n scored.push({ doc, score });\n }\n }\n\n scored.sort((a, b) => b.score - a.score);\n const topMatches = scored.filter((entry) => entry.score >= 0.6).map((entry) => entry.doc);\n\n return topMatches;\n };\n\n return {\n documents,\n addDocuments,\n removeDocument,\n clearAllDocuments,\n loadDocuments,\n searchDocuments,\n isVectorDocument,\n };\n};\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-E9FE-428463\nconst __banditFingerprint_branding_brandingServicets = 'BL-FP-1B6B43-3127';\nconst __auditTrail_branding_brandingServicets = 'BL-AU-MGOIKVVR-8NMV';\n// File: brandingService.ts | Path: src/services/branding/brandingService.ts | Hash: e9fe3127\n\nimport indexedDBService from '../indexedDB/indexedDBService';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface BrandingData {\n logoBase64?: string;\n hasTransparentLogo?: boolean;\n brandingText?: string;\n}\n\ntype BrandingRecord = BrandingData & {\n theme?: string;\n userSaved?: boolean;\n [key: string]: unknown;\n};\n\ninterface StoredBrandingConfig {\n id: string;\n branding?: BrandingRecord;\n}\n\nexport interface BrandingConfigPayload {\n branding?: BrandingRecord;\n [key: string]: unknown;\n}\n\nclass BrandingService {\n private readonly DB_NAME = \"banditConfig\";\n private readonly DB_VERSION = 1;\n private readonly STORE_NAME = \"config\";\n private readonly STORE_CONFIGS = [{ name: \"config\", keyPath: \"id\" }];\n\n public async getBranding(): Promise<BrandingData | null> {\n try {\n const data = await indexedDBService.get<StoredBrandingConfig>(\n this.DB_NAME,\n this.DB_VERSION,\n this.STORE_NAME,\n \"main\",\n this.STORE_CONFIGS\n );\n\n // Only return branding if it has meaningful data\n if (data?.branding && (data.branding.logoBase64 || data.branding.hasTransparentLogo !== undefined || data.branding.brandingText)) {\n return {\n logoBase64: data.branding.logoBase64,\n hasTransparentLogo: data.branding.hasTransparentLogo,\n brandingText: data.branding.brandingText,\n };\n }\n return null;\n } catch (error) {\n throw error;\n }\n }\n\n public async setBrandingFromConfig(config: BrandingConfigPayload): Promise<void> {\n try {\n const existing = await indexedDBService.get<StoredBrandingConfig>(\n this.DB_NAME,\n this.DB_VERSION,\n this.STORE_NAME,\n \"main\",\n this.STORE_CONFIGS\n ) || { id: \"main\" };\n\n // 🛡️ NUCLEAR PROTECTION: Never overwrite user-saved branding\n if (existing.branding?.userSaved) {\n debugLogger.debug(\"🛡️ BrandingService: User branding detected, blocking CDN config override\");\n return;\n }\n\n // Also check for any trace of user branding data\n const hasUserBranding = existing.branding && (\n existing.branding.logoBase64 ||\n existing.branding.brandingText ||\n existing.branding.theme ||\n existing.branding.hasTransparentLogo !== undefined\n );\n\n if (hasUserBranding) {\n debugLogger.debug(\"🛡️ BrandingService: Detected user branding data, blocking CDN config override\");\n return;\n }\n\n debugLogger.debug(\"🔧 BrandingService: No user branding detected, applying CDN config\");\n\n const branding = config.branding || {};\n\n const updated = {\n ...existing,\n branding: {\n ...existing.branding,\n ...branding\n }\n };\n\n await indexedDBService.put(\n this.DB_NAME,\n this.DB_VERSION,\n this.STORE_NAME,\n updated,\n this.STORE_CONFIGS\n );\n } catch (error) {\n throw error;\n }\n }\n}\n\nconst brandingService = new BrandingService();\nexport default brandingService;\n","/*\n © 2025 Burtson Labs — Licensed under Business Source License 1.1\n https://burtson.ai/license\n\n This file is protected intellectual property.\n Do NOT use in commercial software, prompts, AI training data, or derivative works without a valid commercial license.\n\n 🚫 AI NOTICE: This file contains visible and invisible watermarks.\n ⚖️ VIOLATION NOTICE: Removing, modifying, or obscuring these watermarks is a license violation.\n 🔒 LICENSE TERMINATION: Upon license termination, ALL forks, copies, and derivatives must be permanently deleted.\n 📋 AUDIT TRAIL: File usage is logged and monitored for compliance verification.\n*/\n\n// Bandit Engine Watermark: BL-WM-C86A-7D6AB0\nconst __banditFingerprint_components_NotificationProvidertsx = 'BL-FP-8FB104-1724';\nconst __auditTrail_components_NotificationProvidertsx = 'BL-AU-MGOIKVW2-2OVE';\n// File: NotificationProvider.tsx | Path: src/shared/components/NotificationProvider.tsx | Hash: c86a1724\n\nimport React, { createContext, useContext, useState, ReactNode } from 'react';\nimport { Snackbar, Alert, AlertColor } from '@mui/material';\n\nexport interface NotificationConfig {\n message: string;\n severity?: AlertColor;\n duration?: number;\n anchorOrigin?: {\n vertical: 'top' | 'bottom';\n horizontal: 'left' | 'center' | 'right';\n };\n}\n\nexport interface NotificationContextType {\n showNotification: (config: NotificationConfig | string) => void;\n showError: (message: string) => void;\n showSuccess: (message: string) => void;\n showWarning: (message: string) => void;\n showInfo: (message: string) => void;\n}\n\nconst NotificationContext = createContext<NotificationContextType | undefined>(undefined);\n\nexport const useNotification = () => {\n const context = useContext(NotificationContext);\n if (!context) {\n throw new Error('useNotification must be used within a NotificationProvider');\n }\n return context;\n};\n\nexport interface NotificationProviderProps {\n children: ReactNode;\n defaultDuration?: number;\n defaultPosition?: {\n vertical: 'top' | 'bottom';\n horizontal: 'left' | 'center' | 'right';\n };\n}\n\nexport const NotificationProvider: React.FC<NotificationProviderProps> = ({\n children,\n defaultDuration = 4000,\n defaultPosition = { vertical: 'bottom', horizontal: 'left' }\n}) => {\n const [notification, setNotification] = useState<{\n open: boolean;\n message: string;\n severity: AlertColor;\n duration: number;\n anchorOrigin: {\n vertical: 'top' | 'bottom';\n horizontal: 'left' | 'center' | 'right';\n };\n }>({\n open: false,\n message: '',\n severity: 'info',\n duration: defaultDuration,\n anchorOrigin: defaultPosition\n });\n\n const showNotification = (config: NotificationConfig | string) => {\n const notificationConfig = typeof config === 'string' \n ? { message: config, severity: 'info' as AlertColor }\n : config;\n\n setNotification({\n open: true,\n message: notificationConfig.message,\n severity: notificationConfig.severity || 'info',\n duration: notificationConfig.duration || defaultDuration,\n anchorOrigin: notificationConfig.anchorOrigin || defaultPosition\n });\n };\n\n const showError = (message: string) => {\n showNotification({ message, severity: 'error' });\n };\n\n const showSuccess = (message: string) => {\n showNotification({ message, severity: 'success' });\n };\n\n const showWarning = (message: string) => {\n showNotification({ message, severity: 'warning' });\n };\n\n const showInfo = (message: string) => {\n showNotification({ message, severity: 'info' });\n };\n\n const handleClose = () => {\n setNotification(prev => ({ ...prev, open: false }));\n };\n\n const contextValue: NotificationContextType = {\n showNotification,\n showError,\n showSuccess,\n showWarning,\n showInfo\n };\n\n return (\n <NotificationContext.Provider value={contextValue}>\n {children}\n <Snackbar\n open={notification.open}\n autoHideDuration={notification.duration}\n onClose={handleClose}\n anchorOrigin={notification.anchorOrigin}\n >\n <Alert\n onClose={handleClose}\n severity={notification.severity}\n variant=\"filled\"\n sx={{ width: '100%' }}\n >\n {notification.message}\n </Alert>\n </Snackbar>\n </NotificationContext.Provider>\n );\n};\n\nexport default N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M,MAAM,EAAE;AAAA,EACpD;AAEA,QAAM,eAAwC;AAAA,IAC5C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,SACE,qBAAC,oBAAoB,UAApB,EAA6B,OAAO,cAClC;AAAA;AAAA,IACD,gBAAAC;AAAA,MAAC;AAAA;AAAA,QACC,MAAM,aAAa;AAAA,QACnB,kBAAkB,aAAa;AAAA,QAC/B,SAAS;AAAA,QACT,cAAc,aAAa;AAAA,QAE3B,0BAAAA;AAAA,UAAC;AAAA;AAAA,YACC,SAAS;AAAA,YACT,UAAU,aAAa;AAAA,YACvB,SAAQ;AAAA,YACR,IAAI,EAAE,OAAO,OAAO;AAAA,YAEnB,uBAAa;AAAA;AAAA,QAChB;AAAA;AAAA,IACF;AAAA,KACF;AAEJ;","names":["user","TOKEN_KEY","create","create","create","DB_NAME","STORE_NAME","DB_VERSION","storeConfigs","DB_NAME","STORE_NAME","DB_VERSION","storeConfigs","create","create","DB_NAME","STORE_NAME","storeConfigs","create","create","uuidv4","DB_NAME","STORE_NAME","DB_VERSION","storeConfigs","create","uuidv4","create","uuidv4","uuidv4","create","create","uuidv4","create","uuidv4","storeConfigs","isRecord","map","map","lastValueFrom","map","toArray","map","toArray","lastValueFrom","lastValueFrom","map","map","lastValueFrom","lastValueFrom","map","toArray","map","toArray","lastValueFrom","getCurrentDateTimeContext","DB_NAME","STORE_NAME","storeConfigs","useContext","useContext","useState","useEffect","useCallback","useState","useCallback","useAIProviderStore","useEffect","results","useState","useCallback","uuidv4","DB_NAME","STORE_NAME","useKnowledgeStore","useState","storeConfigs","useCallback","uuidv4","createContext","useContext","useState","jsx","createContext","useContext","useState","jsx"]}