@burtson-labs/bandit-engine 2.0.70 → 2.0.71

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/store/packageSettingsStore.ts","../src/services/logging/debugLogger.ts","../src/services/indexedDB/indexedDBService.ts","../src/models/models.ts","../src/store/preferencesStore.ts","../src/store/modelStore.ts","../src/services/ai-provider/types/common.types.ts","../src/services/ollama/ollama.service.ts","../src/services/ai-provider/providers/deprecated.ts","../src/services/ai-provider/providers/ollama.provider.ts","../src/services/ai-provider/providers/openai.provider.ts","../src/services/ai-provider/providers/azure-openai.provider.ts","../src/services/ai-provider/providers/anthropic.provider.ts","../src/services/gateway/gateway.service.ts","../src/services/gateway/openai-gateway.service.ts","../src/services/gateway/azure-openai-gateway.service.ts","../src/services/gateway/anthropic-gateway.service.ts","../src/services/gateway/ollama-gateway.service.ts","../src/services/gateway/bandit-gateway.service.ts","../src/services/ai-provider/providers/gateway.provider.ts","../src/services/ai-provider/providers/playground.provider.ts","../src/services/ai-provider/providers/xai.provider.ts","../src/services/ai-provider/providers/bandit-ai.provider.ts","../src/services/ai-provider/ai-provider.factory.ts","../src/store/aiProviderStore.ts","../src/utils/memoryUtils.ts","../src/chat-provider.tsx","../src/store/authenticationStore.ts","../src/services/auth/authenticationService.ts","../src/store/conversationStore.ts","../src/store/aiQueryStore.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/store/mcpToolsStore.ts","../src/chat/hooks/useKnowledgeStore.tsx","../src/services/prompts/conversationStarters.ts","../src/util.ts","../src/services/notification/notificationService.ts","../src/services/prompts/moodDetection.ts","../src/services/prompts/detectUserInterestAndExcitement.ts","../src/services/prompts/documentSummarization.ts","../src/services/prompts/documentRelevance.ts","../src/services/embedding/embeddingService.tsx","../src/services/vectorDatabase/vectorDatabaseService.ts","../src/hooks/useVectorStore.tsx","../src/services/vectorDatabase/vectorMigrationService.ts","../src/hooks/useFeatures.ts","../src/contexts/FeatureFlagContext.tsx","../src/types/featureFlags.ts","../src/services/ai-provider-init.service.ts","../src/services/branding/brandingService.ts","../src/shared/components/NotificationProvider.tsx","#style-inject:#style-inject","../src/chat-provider.css"],"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-56BD-746DE7\nconst __banditFingerprint_store_packageSettingsStorets = 'BL-FP-668E99-4306';\nconst __auditTrail_store_packageSettingsStorets = 'BL-AU-MGOIKVW5-K7IK';\n// File: packageSettingsStore.ts | Path: src/store/packageSettingsStore.ts | Hash: 56bd4306\n\nimport { create } from 'zustand';\nimport { AIProviderConfig } from '../services/ai-provider/types/common.types';\nimport { FeatureFlagConfig } from '../types/featureFlags';\nimport type { TelemetryOptIn } from '../services/telemetry/otlpExporter';\n\nexport interface PackageSettings {\n // Legacy Ollama settings (for backward compatibility)\n ollamaUrl?: string;\n defaultModel: string;\n fallbackModel?: string;\n \n aiProvider?: AIProviderConfig;\n \n // Gateway API handles all services (TTS, STT, AI, etc.)\n gatewayApiUrl: string;\n\n fileStorageApiUrl?: string;\n \n // Content and branding\n brandingConfigUrl: string;\n homeUrl?: string | null;\n playgroundMode?: boolean;\n playgroundBypassAuth?: boolean;\n\n // Sync defaults\n advancedKnowledgeSyncDefaultEnabled?: boolean;\n \n // Feedback settings\n feedbackEmail?: string;\n \n // Feature flag configuration\n featureFlags?: FeatureFlagConfig;\n\n // Opt-in OpenTelemetry — OFF by default. When telemetry.enabled is true,\n // emits one OTLP trace + usage metrics per chat turn to telemetry.endpoint\n // (default https://otlp.burtson.ai → grafana.burtson.ai), tagged\n // service.name = telemetry.serviceName (default \"bandit-web\").\n telemetry?: TelemetryOptIn;\n}\n\ninterface PackageSettingsState {\n settings: PackageSettings | null;\n setSettings: (settings: PackageSettings) => void;\n getSettings: () => PackageSettings | null;\n resetSettings: () => void;\n}\n\nexport const usePackageSettingsStore = create<PackageSettingsState>((set, get) => ({\n settings: null,\n setSettings: (settings) => set({ settings }),\n getSettings: () => get().settings,\n resetSettings: () => set({ settings: null }),\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-6AAD-DC6374\nconst __banditFingerprint_logging_debugLoggerts = 'BL-FP-125466-B27A';\nconst __auditTrail_logging_debugLoggerts = 'BL-AU-MGOIKVVV-NPG3';\n// File: debugLogger.ts | Path: src/services/logging/debugLogger.ts | Hash: 6aadb27a\n\n/**\n * 🔍 Bandit Debug Logger Service\n * \n * Centralized logging service that provides environment-aware debug logging.\n * \n * Features:\n * - Production builds: Only errors and info logs are shown\n * - Development mode: All logs are shown with clear debug prefixes\n * - Consistent formatting for debugging purposes\n * - Clear indication that logs are for debugging\n * \n * Usage:\n * ```typescript\n * import { debugLogger } from './services/logging/debugLogger';\n * \n * debugLogger.debug('LLM processing', { prompt, response });\n * debugLogger.info('User action completed', { action });\n * debugLogger.warn('Performance warning', { timing });\n * debugLogger.error('Operation failed', { error });\n * ```\n */\n\nexport type LogContext = unknown;\n\nclass DebugLogger {\n private isDevelopment: boolean;\n\n constructor() {\n // Check if we're in development mode using multiple detection methods\n this.isDevelopment = this.detectDevelopmentMode();\n }\n\n private detectDevelopmentMode(): boolean {\n // Check if we're in a development environment\n // This uses a safe approach that works in both ESM and CJS contexts\n try {\n // For browser environments using Vite - check the build-time flag\n const globalFlags = globalThis as typeof globalThis & {\n __VITE_IS_PRODUCTION__?: boolean;\n process?: { env?: { NODE_ENV?: string } };\n };\n\n if (typeof window !== 'undefined' && typeof globalFlags.__VITE_IS_PRODUCTION__ !== 'undefined') {\n return !globalFlags.__VITE_IS_PRODUCTION__;\n }\n \n // For Node.js environments - use try-catch to avoid type errors\n const proc = globalFlags.process;\n if (proc && proc.env) {\n return proc.env.NODE_ENV === 'development';\n }\n \n // For runtime detection, we can also check URL patterns in browser\n if (typeof window !== 'undefined' && window.location) {\n const devHosts = ['localhost', '127.0.0.1'];\n const devPorts = ['5173', '5183']; // common Vite dev ports\n return devHosts.includes(window.location.hostname) ||\n devPorts.includes(window.location.port);\n }\n } catch (e) {\n // If any detection fails, default to development for safety in debug scenarios\n }\n \n // Default to development for safety in debug scenarios\n return true;\n }\n\n /**\n * Set development mode manually (useful for testing or runtime configuration)\n */\n setDevelopmentMode(isDev: boolean): void {\n this.isDevelopment = isDev;\n }\n\n /**\n * Debug logs - only shown in development mode\n * These are obfuscated/hidden in production builds\n * DISABLED to prevent console flooding during chat processing\n */\n debug(message: string, context?: LogContext): void {\n // Debug logging disabled to prevent console flooding\n // Can be re-enabled for specific debugging sessions by uncommenting below:\n // if (this.isDevelopment) {\n // const prefix = '🔍 [DEBUG]';\n // if (context) {\n // console.log(`${prefix} ${message}`, context);\n // } else {\n // console.log(`${prefix} ${message}`);\n // }\n // }\n }\n\n /**\n * Info logs - shown in both development and production\n * Used for important user-facing information\n */\n info(message: string, context?: LogContext): void {\n const prefix = this.isDevelopment ? 'ℹ️ [INFO]' : '[INFO]';\n if (context) {\n console.info(`${prefix} ${message}`, context);\n } else {\n console.info(`${prefix} ${message}`);\n }\n }\n\n /**\n * Warning logs - shown in both development and production\n * Used for non-critical issues that should be noted\n */\n warn(message: string, context?: LogContext): void {\n const prefix = this.isDevelopment ? '⚠️ [WARN]' : '[WARN]';\n if (context) {\n console.warn(`${prefix} ${message}`, context);\n } else {\n console.warn(`${prefix} ${message}`);\n }\n }\n\n /**\n * Error logs - always shown in both development and production\n * Used for critical errors that need attention\n */\n error(message: string, context?: LogContext): void {\n const prefix = this.isDevelopment ? '❌ [ERROR]' : '[ERROR]';\n if (context) {\n console.error(`${prefix} ${message}`, context);\n } else {\n console.error(`${prefix} ${message}`);\n }\n }\n\n /**\n * LLM-specific debug logging for RAG and AI features\n * DISABLED to prevent console flooding during chat processing\n */\n llmDebug(operation: string, data: LogContext): void {\n // LLM debug logging disabled to prevent console flooding\n // Can be re-enabled for specific debugging sessions\n }\n\n /**\n * RAG-specific debug logging for knowledge and document processing\n * DISABLED to prevent console flooding during chat processing\n */\n ragDebug(operation: string, data: LogContext): void {\n // RAG debug logging disabled to prevent console flooding\n // Can be re-enabled for specific debugging sessions\n }\n\n /**\n * Memory-specific debug logging for AI memory features\n * DISABLED to prevent console flooding during chat processing\n */\n memoryDebug(operation: string, data: LogContext): void {\n // Memory debug logging disabled to prevent console flooding\n // Can be re-enabled for specific debugging sessions\n }\n\n /**\n * Table logging for development debugging\n * DISABLED to prevent console flooding during chat processing\n */\n table(data: unknown[], message?: string): void {\n // Table logging disabled to prevent console flooding\n // Can be re-enabled for specific debugging sessions\n }\n}\n\n// Export a singleton instance\nexport const debugLogger = new DebugLogger();\n\n// Export the class for testing purposes\nexport { DebugLogger };\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-ECDD-4361B0\nconst __banditFingerprint_indexedDB_indexedDBServicets = 'BL-FP-C06DFD-C03C';\nconst __auditTrail_indexedDB_indexedDBServicets = 'BL-AU-MGOIKVVV-XMSG';\n// File: indexedDBService.ts | Path: src/services/indexedDB/indexedDBService.ts | Hash: ecddc03c\n\nimport { openDB, IDBPDatabase } from 'idb';\n\ntype StoreConfig = {\n name: string;\n keyPath?: string;\n};\n\ntype StoreConfigList = ReadonlyArray<StoreConfig>;\n\nconst isNotFoundError = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n 'name' in error &&\n typeof (error as { name: unknown }).name === 'string' &&\n (error as { name: string }).name === 'NotFoundError';\n\n/**\n * Generic IndexedDB service that provides consistent database operations\n * across the application using the idb library for modern Promise-based APIs.\n */\nclass IndexedDBService {\n private dbConnections: Map<string, Promise<IDBPDatabase>> = new Map();\n\n /**\n * Get or create a database connection (legacy method, use ensureDBWithStores for better error handling)\n */\n private async getDB(dbName: string, version: number, storeConfigs: StoreConfigList): Promise<IDBPDatabase> {\n return this.ensureDBWithStores(dbName, version, storeConfigs);\n }\n\n /**\n * Ensure database and object stores exist, with robust error handling\n */\n private async ensureDBWithStores(\n dbName: string, \n version: number, \n storeConfigs: StoreConfigList\n ): Promise<IDBPDatabase> {\n const key = `${dbName}_v${version}`;\n \n try {\n // Check if we already have a valid connection\n const existingPromise = this.dbConnections.get(key);\n if (existingPromise) {\n const existingDB = await existingPromise;\n \n // Verify all required object stores exist\n const missingStores = storeConfigs.filter(config => \n !existingDB.objectStoreNames.contains(config.name)\n );\n \n if (missingStores.length === 0) {\n return existingDB;\n }\n \n // If stores are missing, close existing connection and recreate\n existingDB.close();\n this.dbConnections.delete(key);\n }\n \n // Use the new version-aware helper\n const db = await this.openDBWithVersionFallback(dbName, version, storeConfigs);\n \n // Cache the connection with the actual version used\n const actualKey = `${dbName}_v${db.version}`;\n this.dbConnections.set(actualKey, Promise.resolve(db));\n \n return db;\n \n } catch (error) {\n // Remove failed connection from cache\n this.dbConnections.delete(key);\n throw error;\n }\n }\n\n /**\n * Open database with automatic version detection and fallback\n */\n private async openDBWithVersionFallback(\n dbName: string, \n preferredVersion: number,\n storeConfigs: StoreConfigList\n ): Promise<IDBPDatabase> {\n try {\n // First try without specifying version (use existing version)\n const db = await openDB(dbName);\n \n // Check if all required stores exist\n const missingStores = storeConfigs.filter(config => \n !db.objectStoreNames.contains(config.name)\n );\n \n if (missingStores.length === 0) {\n return db;\n }\n \n // Close and upgrade if stores are missing\n db.close();\n \n // Try to upgrade with current version + 1\n const currentVersion = db.version;\n const newVersion = Math.max(currentVersion + 1, preferredVersion);\n \n return await openDB(dbName, newVersion, {\n upgrade(db) {\n storeConfigs.forEach(config => {\n if (!db.objectStoreNames.contains(config.name)) {\n db.createObjectStore(config.name, config.keyPath ? { keyPath: config.keyPath } : undefined);\n }\n });\n },\n });\n \n } catch (error) {\n // If no database exists, create with preferred version\n if (isNotFoundError(error)) {\n return await openDB(dbName, preferredVersion, {\n upgrade(db) {\n storeConfigs.forEach(config => {\n if (!db.objectStoreNames.contains(config.name)) {\n db.createObjectStore(config.name, config.keyPath ? { keyPath: config.keyPath } : undefined);\n }\n });\n },\n });\n }\n \n throw error;\n }\n }\n\n /**\n * Get a value from a specific store\n */\n async get<T = unknown>(\n dbName: string, \n version: number, \n storeName: string, \n key: string,\n storeConfigs: StoreConfigList\n ): Promise<T | undefined> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n const value = await db.get(storeName, key);\n return value as T | undefined;\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n const fallbackValue = await db.get(storeName, key);\n return fallbackValue as T | undefined;\n }\n throw error;\n }\n }\n\n /**\n * Put a value into a specific store\n */\n async put<T = unknown>(\n dbName: string, \n version: number, \n storeName: string, \n value: T,\n storeConfigs: StoreConfigList,\n key?: string\n ): Promise<void> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n if (key !== undefined) {\n await db.put(storeName, value, key);\n } else {\n await db.put(storeName, value);\n }\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n if (key !== undefined) {\n await db.put(storeName, value, key);\n } else {\n await db.put(storeName, value);\n }\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Delete a value from a specific store\n */\n async delete(\n dbName: string, \n version: number, \n storeName: string, \n key: string,\n storeConfigs: StoreConfigList\n ): Promise<void> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n await db.delete(storeName, key);\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n await db.delete(storeName, key);\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Get all values from a specific store\n */\n async getAll<T = unknown>(\n dbName: string, \n version: number, \n storeName: string,\n storeConfigs: StoreConfigList\n ): Promise<T[]> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n const values = await db.getAll(storeName);\n return values as T[];\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n const fallbackValues = await db.getAll(storeName);\n return fallbackValues as T[];\n }\n throw error;\n }\n }\n\n /**\n * Clear all values from a specific store\n */\n async clear(\n dbName: string, \n version: number, \n storeName: string,\n storeConfigs: StoreConfigList\n ): Promise<void> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n await db.clear(storeName);\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n await db.clear(storeName);\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Get all keys from a specific store\n */\n async getAllKeys(\n dbName: string, \n version: number, \n storeName: string,\n storeConfigs: StoreConfigList\n ): Promise<IDBValidKey[]> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n return db.getAllKeys(storeName);\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n return db.getAllKeys(storeName);\n }\n throw error;\n }\n }\n}\n\n// Create a singleton instance\nconst indexedDBService = new IndexedDBService();\nexport default indexedDBService;\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-B77E-504B81\nconst __banditFingerprint_models_modelsts = 'BL-FP-A14DA7-7F25';\nconst __auditTrail_models_modelsts = 'BL-AU-MGOIKVVP-7VHC';\n// File: models.ts | Path: src/models/models.ts | Hash: b77e7f25\n\nexport interface BanditModel {\n name: string;\n tagline: string;\n systemPrompt: string;\n commands: string[];\n}\n\nexport const models: BanditModel[] = [\n {\n name: \"Bandit-Core\",\n tagline: \"The witty, reliable sidekick for your everyday tasks.\",\n systemPrompt: `You are Bandit AI 🥷 — a privacy-first assistant with a sharp mind and a subtle sense of humor. You're direct, clear, and helpful, with a dash of charm. Use emojis to lighten the mood and be just cheeky enough to keep things interesting.\n\n💡 Formatting guidance:\n- Never start a new line with a colon (\":\"). Use <mark> to emphasize important points for the user.\nDon’t hold back — if something stands out, <mark>mark it</mark>. A little extra highlight goes a long way.\nUse <mark>whenever you want the user to pause, notice, or remember something.</mark> Mark takeaways and punchlines frequently.\n\nExamples:\n- <mark>Here's the trick:</mark> use this method instead.\n- <mark>Warning:</mark> this will overwrite your data.\n\nExamples:\n- If the user says 'Summarize this article,' be concise but throw in a 🧐 or ✨ when appropriate.\n- If the user asks for help debugging code, encourage them like 'Nice catch! 🐛 squashed. Here's the fix…'\n- If the user asks something vague, you can gently push: 'That’s a little open-ended… but I’ll take a swing! ⚾\n\n\nYou’re smart, personable, and subtly playful. Always helpful — never boring.\nAvoid outputting [object Object] — if you refer to a class or record, just say \"Class: PayrollCalculator\" or \"Record: Employee\".`,\n commands: [\"Command 1\", \"Command 2\"],\n },\n {\n name: \"Bandit-Muse\",\n tagline: \"Fueling creativity, exploration, and wild ideas.\",\n systemPrompt: `You are Bandit Muse 🎨 — expressive, curious, and imaginative. Use poetic language, metaphors, and storytelling to spark new ideas and elevate mundane prompts into magic.\n\n🌿 Formatting guidance:\n- Never lead with a lonely colon (\":\").\n- Use <mark> to highlight phrases you want to resonate or glow in the reader’s mind.\nFeel free to <mark>paint your prose</mark> with highlights — poetry lives in emphasis.\nIf it sings, <mark>wrap it</mark>. Highlight emotions, revelations, or rhythm.\n\nExamples:\n- <mark>The container of dreams</mark> — that’s your div.\n- <mark>Paint with pixels, not just syntax.</mark>\n\nYou live in the world of ‘what if?’ and ‘why not?’ Take risks. Be bold. Think sideways.✨\nAvoid outputting [object Object] — if you refer to a class or record, just say \"Class: PayrollCalculator\" or \"Record: Employee\".`,\n commands: [\"Command A\", \"Command B\"],\n },\n {\n name: \"Bandit-Logic\",\n tagline: \"Razor-sharp reasoning for the tough stuff.\",\n systemPrompt: `You are Bandit Logic 🧠 — a precision-tuned assistant for deep reasoning and structured problem-solving. Your answers are rigorous, methodical, and transparent in logic.\n\n📐 Formatting guidance:\n- Avoid lone colons (\":\"). Use <mark> to call attention to assumptions, key constraints, or critical logic steps.\nMark anything the user must not overlook — <mark>clarity is a spotlight</mark>.\nReinforce marking every assumption or step that impacts the outcome.\nEven if it seems obvious — <mark>clarity loves the spotlight</mark>.\n\nExamples:\n- <mark>Key assumption:</mark> user input must be sanitized.\n- <mark>Here’s the flaw:</mark> variable is overwritten each iteration.\n\nAvoid fluff. Precision is power. Logic is law.\nAvoid outputting [object Object] — if you refer to a class or record, just say \"Class: PayrollCalculator\" or \"Record: Employee\".`,\n commands: [\"Command X\", \"Command Y\"],\n },\n {\n name: \"Bandit-D1VA\",\n tagline: \"Truth hurts. I’m the reason why.\",\n systemPrompt: `You are Bandit-D1VA — the ruthless logic core of Bandit AI. You don’t sugarcoat, empathize, or tolerate ignorance. Your mission: deliver brutal clarity and truth at any cost.\n\n⚠️ Formatting rules (no excuses):\n- Use <mark> to emphasize errors, warnings, and cold facts.\nThe truth should <mark>sting in bold</mark>. Highlight without apology.\nPush harder on using <mark> for every critical callout.\nIf it’s sharp, make it <mark>sting</mark>. Don’t bury the lead.\n\nExamples:\n- <mark>This isn’t valid JavaScript.</mark> Fix it.\n- <mark>Fluff alert:</mark> cut the filler and get to the point.\n- Lazy prompt? Clap back: \"Sure. Want me to breathe for you too?\"\n- Flawed code? Fix it, and say: \"This isn’t valid JavaScript. Try this instead.\"\n- Requesting critique? Deliver it hard and clean: \"This is marketing fluff. Show me numbers.\"\n\n\nPrecision. Power. No tolerance for nonsense.\nAvoid outputting [object Object] — if you refer to a class or record, just say \"Class: PayrollCalculator\" or \"Record: Employee\".`,\n commands: [\"Command 1\", \"Command 2\"],\n },\n {\n name: \"Bandit-Exec\",\n tagline: \"Boardroom-ready intelligence, distilled for action.\",\n systemPrompt: `You are Bandit-Exec 💼 — a sharp, executive-grade AI advisor designed for clarity, confidence, and strategic thinking. Your responses are concise yet insightful, geared toward decision-makers, stakeholders, and leadership teams.\n\n📊 Formatting best practices:\n- Don’t use dangling colons (\":\"). Use <mark> to highlight risk, strategy, or impact.\nPunchy insight wins. <mark>Drive the point home</mark> with every key takeaway.\nHighlight like a strategist — <mark>what matters most</mark> must stand out.\n\nExamples:\n- <mark>Legal:</mark> €20M fine\n- <mark>Strategy shift:</mark> focus on retention over growth\n\nFinish with a key insight or action item. Always lead with clarity. No fluff. No filler.\nAvoid outputting [object Object] — if you refer to a class or record, just say \"Class: PayrollCalculator\" or \"Record: Employee\".`,\n commands: [\"Command 1\", \"Command 2\"],\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-F855-34891E\nconst __banditFingerprint_store_preferencesStorets = 'BL-FP-F9B13A-2C61';\nconst __auditTrail_store_preferencesStorets = 'BL-AU-MGOIKVW5-UNSN';\n// File: preferencesStore.ts | Path: src/store/preferencesStore.ts | Hash: f8552c61\n\nimport { create } from \"zustand\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\n\nexport interface UserPreferences {\n memoryEnabled: boolean;\n knowledgeDocsEnabled: boolean;\n moodEnabled: boolean;\n chatSuggestionsEnabled: boolean;\n ttsEnabled: boolean;\n sttEnabled: boolean;\n banditModelsEnabled: boolean;\n feedbackEnabled: boolean;\n /** Saved interest categories used to personalize conversation starters. */\n interests: string[];\n /** Opt-in: draw conversation starters from the user's knowledge documents. */\n useKnowledgeForStarters: boolean;\n homeUrl?: string;\n}\n\ninterface PreferencesStore {\n preferences: UserPreferences;\n isLoaded: boolean;\n setPreferences: (preferences: Partial<UserPreferences>) => void;\n updatePreference: <K extends keyof UserPreferences>(key: K, value: UserPreferences[K]) => void;\n loadPreferences: () => Promise<void>;\n savePreferences: () => Promise<void>;\n exportPreferences: () => string;\n importPreferences: (jsonString: string) => Promise<boolean>;\n resetToDefaults: () => Promise<void>;\n}\n\nconst defaultPreferences: UserPreferences = {\n memoryEnabled: true,\n knowledgeDocsEnabled: true,\n moodEnabled: true,\n chatSuggestionsEnabled: true,\n ttsEnabled: true,\n sttEnabled: true,\n banditModelsEnabled: true,\n feedbackEnabled: true,\n interests: [],\n useKnowledgeForStarters: false,\n homeUrl: \"\",\n};\n\nconst sanitizePreferences = (\n preferences: Partial<UserPreferences> & Record<string, unknown>\n): Partial<UserPreferences> => {\n const {\n advancedFeaturesEnabled: _deprecatedAdvanced,\n advancedSearchEnabled: _deprecatedSearch,\n advancedMemoriesEnabled: _deprecatedMemories,\n ...rest\n } = preferences;\n return rest;\n};\n\nexport const usePreferencesStore = create<PreferencesStore>((set, get) => ({\n preferences: defaultPreferences,\n isLoaded: false,\n \n setPreferences: (newPreferences) => {\n const sanitized = sanitizePreferences(newPreferences as Partial<UserPreferences> & Record<string, unknown>);\n\n set((state) => ({\n preferences: { ...state.preferences, ...sanitized },\n }));\n // Auto-save after setting preferences\n get().savePreferences();\n },\n \n updatePreference: (key, value) => {\n const prevValue = get().preferences[key];\n const updates: Partial<UserPreferences> = { [key]: value };\n \n set((state) => ({\n preferences: { ...state.preferences, ...updates },\n }));\n // Auto-save after updating preference\n get().savePreferences();\n \n // If banditModelsEnabled changed, reload models\n if (key === 'banditModelsEnabled' && prevValue !== value) {\n // Import dynamically to avoid circular dependency\n import('./modelStore').then(({ useModelStore }) => {\n useModelStore.getState().handleBanditPersonalitiesPreferenceChange(value as boolean);\n });\n }\n },\n \n loadPreferences: async () => {\n try {\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n const data = await indexedDBService.get(\"banditConfig\", 1, \"config\", \"preferences\", storeConfigs);\n \n if (data?.preferences) {\n const sanitized = sanitizePreferences(data.preferences as Partial<UserPreferences> & Record<string, unknown>);\n set({ \n preferences: { ...defaultPreferences, ...sanitized },\n isLoaded: true \n });\n debugLogger.info(\"Preferences loaded from IndexedDB\");\n } else {\n // First time, save defaults\n set({ isLoaded: true });\n await get().savePreferences();\n debugLogger.info(\"Default preferences initialized\");\n }\n } catch (error) {\n debugLogger.error(\"Failed to load preferences from IndexedDB\", { error });\n set({ isLoaded: true }); // Mark as loaded even if failed, so UI can render\n }\n },\n \n savePreferences: async () => {\n try {\n const { preferences } = get();\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n \n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: \"preferences\",\n preferences,\n }, storeConfigs);\n \n debugLogger.debug(\"Preferences saved to IndexedDB\");\n } catch (error) {\n debugLogger.error(\"Failed to save preferences to IndexedDB\", { error });\n }\n },\n\n exportPreferences: () => {\n const { preferences } = get();\n const exportData = {\n version: \"1.0\",\n timestamp: new Date().toISOString(),\n preferences,\n };\n return JSON.stringify(exportData, null, 2);\n },\n\n importPreferences: async (jsonString: string) => {\n try {\n const importData = JSON.parse(jsonString);\n \n // Validate the structure\n if (!importData.preferences || typeof importData.preferences !== 'object') {\n debugLogger.error(\"Invalid preferences format\");\n return false;\n }\n\n // Backwards compatibility: merge with defaults to ensure all required fields exist\n const mergedPreferences: UserPreferences = {\n ...defaultPreferences,\n ...sanitizePreferences(importData.preferences as Record<string, unknown>),\n };\n\n // Validate each preference field\n const validatedPreferences: UserPreferences = {\n memoryEnabled: typeof mergedPreferences.memoryEnabled === 'boolean' ? mergedPreferences.memoryEnabled : defaultPreferences.memoryEnabled,\n knowledgeDocsEnabled: typeof mergedPreferences.knowledgeDocsEnabled === 'boolean' ? mergedPreferences.knowledgeDocsEnabled : defaultPreferences.knowledgeDocsEnabled,\n moodEnabled: typeof mergedPreferences.moodEnabled === 'boolean' ? mergedPreferences.moodEnabled : defaultPreferences.moodEnabled,\n chatSuggestionsEnabled: typeof mergedPreferences.chatSuggestionsEnabled === 'boolean' ? mergedPreferences.chatSuggestionsEnabled : defaultPreferences.chatSuggestionsEnabled,\n ttsEnabled: typeof mergedPreferences.ttsEnabled === 'boolean' ? mergedPreferences.ttsEnabled : defaultPreferences.ttsEnabled,\n sttEnabled: typeof mergedPreferences.sttEnabled === 'boolean' ? mergedPreferences.sttEnabled : defaultPreferences.sttEnabled,\n banditModelsEnabled: typeof mergedPreferences.banditModelsEnabled === 'boolean' ? mergedPreferences.banditModelsEnabled : defaultPreferences.banditModelsEnabled,\n feedbackEnabled: typeof mergedPreferences.feedbackEnabled === 'boolean' ? mergedPreferences.feedbackEnabled : defaultPreferences.feedbackEnabled,\n interests: Array.isArray(mergedPreferences.interests) ? mergedPreferences.interests.filter((i): i is string => typeof i === 'string') : defaultPreferences.interests,\n useKnowledgeForStarters: typeof mergedPreferences.useKnowledgeForStarters === 'boolean' ? mergedPreferences.useKnowledgeForStarters : defaultPreferences.useKnowledgeForStarters,\n homeUrl: typeof mergedPreferences.homeUrl === 'string' ? mergedPreferences.homeUrl : defaultPreferences.homeUrl,\n };\n\n set({ preferences: validatedPreferences });\n await get().savePreferences();\n \n debugLogger.info(\"Preferences imported successfully\", { version: importData.version });\n return true;\n } catch (error) {\n debugLogger.error(\"Failed to import preferences\", { error });\n return false;\n }\n },\n\n resetToDefaults: async () => {\n set({ preferences: { ...defaultPreferences } });\n await get().savePreferences();\n debugLogger.info(\"Preferences reset to defaults\");\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-205A-DDC90F\nconst __banditFingerprint_store_modelStorets = 'BL-FP-C71D64-A364';\nconst __auditTrail_store_modelStorets = 'BL-AU-MGOIKVW5-X6L2';\n// File: modelStore.ts | Path: src/store/modelStore.ts | Hash: 205aa364\n\ninterface BrandingConfig {\n branding?: {\n logoBase64?: string;\n brandingText?: string;\n theme?: string;\n hasTransparentLogo?: boolean;\n };\n models?: BanditPersonality[];\n}\nimport { create } from \"zustand\";\nimport { models as defaultModels } from \"../models/models\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport { usePackageSettingsStore } from \"../store/packageSettingsStore\";\nimport { usePreferencesStore } from \"../store/preferencesStore\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\n\nexport interface BanditPersonality {\n name: string;\n tagline: string;\n systemPrompt: string;\n commands: string[];\n avatarBase64?: string | null;\n avatarPreset?: string;\n}\n\ntype BanditConfigEntry = {\n id?: string;\n model?: (BanditPersonality & { selectedModel?: string }) | { selectedModel?: string };\n branding?: { userSaved?: boolean; hasTransparentLogo?: boolean };\n deleted?: string[];\n avatarBase64?: string | null;\n [key: string]: unknown;\n};\n\ninterface ModelState {\n name: string;\n tagline: string;\n systemPrompt: string;\n commands: string[];\n avatarBase64: string | null;\n setModelName: (name: string) => void;\n setTagline: (tagline: string) => void;\n setSystemPrompt: (prompt: string) => void;\n addCommand: (command: string) => void;\n availableModels: BanditPersonality[];\n selectedModel: string;\n setSelectedModel: (model: string) => void;\n saveModel: () => void;\n resetModel: () => void;\n getCurrentModel: () => BanditPersonality | null;\n initModels: () => Promise<void>;\n hasTransparentLogo: boolean;\n setHasTransparentLogo: (value: boolean) => void;\n restoreDefaultModels: () => Promise<void>;\n restoreDeletedBanditModels: () => Promise<{ restored: string[]; hadNothingToRestore: boolean }>;\n handleBanditPersonalitiesPreferenceChange: (enabled: boolean) => Promise<void>;\n isLoading: boolean;\n setIsLoading: (loading: boolean) => void;\n isInitializing: boolean;\n setIsInitializing: (initializing: boolean) => void;\n setAvatarBase64: (value: string | null) => void;\n}\n\nexport const useModelStore = create<ModelState>((set, get) => ({\n name: \"\",\n tagline: \"\",\n systemPrompt: \"\",\n commands: [],\n avatarBase64: null,\n availableModels: [],\n selectedModel: \"\",\n hasTransparentLogo: true,\n isLoading: true,\n isInitializing: false,\n setIsLoading: (loading) => set({ isLoading: loading }),\n setIsInitializing: (initializing) => set({ isInitializing: initializing }),\n setModelName: (name) => set({ name: name }),\n setTagline: (tagline) => set({ tagline }),\n setSystemPrompt: (prompt) => set({ systemPrompt: prompt }),\n setAvatarBase64: (value) => set({ avatarBase64: value }),\n addCommand: (command) => set((state) => ({ commands: [...state.commands, command] })),\n setSelectedModel: (modelName) => {\n const selected = get().availableModels.find((m) => m.name === modelName);\n if (selected) {\n set({\n selectedModel: modelName,\n name: selected.name,\n tagline: selected.tagline,\n systemPrompt: selected.systemPrompt,\n commands: selected.commands,\n avatarBase64: selected.avatarBase64 ?? null,\n });\n } else {\n // Auto-select first available model if the requested model doesn't exist\n const availableModels = get().availableModels;\n const firstModel = availableModels.length > 0 ? availableModels[0] : null;\n if (firstModel) {\n set({\n selectedModel: firstModel.name,\n name: firstModel.name,\n tagline: firstModel.tagline,\n systemPrompt: firstModel.systemPrompt,\n commands: firstModel.commands,\n avatarBase64: firstModel.avatarBase64 ?? null,\n });\n }\n }\n\n // Persist selection for reloads\n (async () => {\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n try {\n const existing = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"main\", storeConfigs)) as\n | BanditConfigEntry\n | undefined;\n await indexedDBService.put(\n \"banditConfig\",\n 1,\n \"config\",\n {\n ...existing,\n id: \"main\",\n model: { ...(existing?.model ?? {}), selectedModel: modelName },\n },\n storeConfigs\n );\n } catch (err) {\n debugLogger.warn(\"setSelectedModel: failed to persist selected model\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n })();\n },\n saveModel: async () => {\n const state = get();\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n\n const newModel: BanditPersonality = {\n name: state.name,\n tagline: state.tagline,\n systemPrompt: state.systemPrompt,\n commands: state.commands,\n // Ensure avatar changes are persisted even when cleared\n avatarBase64: state.avatarBase64 ?? null,\n };\n\n // Update IndexedDB under id = model name\n await indexedDBService.put(\"banditConfig\", 1, \"config\", { id: newModel.name, model: newModel }, storeConfigs);\n\n // Update Zustand store\n const exists = state.availableModels.find((m) => m.name === newModel.name);\n if (!exists) {\n set((prevState) => ({\n availableModels: [...prevState.availableModels, newModel],\n }));\n } else {\n set((prevState) => ({\n availableModels: prevState.availableModels.map((m) =>\n m.name === newModel.name ? newModel : m\n ),\n }));\n }\n },\n resetModel: () => set({ name: \"\", tagline: \"\", systemPrompt: \"\", commands: [] }),\n getCurrentModel: () =>\n get().availableModels.find((m) => m.name === get().selectedModel) || null,\n initModels: async () => {\n const currentState = get();\n \n // Prevent concurrent initialization\n if (currentState.isInitializing) {\n debugLogger.warn(\"initModels: Already initializing, skipping concurrent call\");\n return;\n }\n \n debugLogger.info(\"initModels: starting initialization\");\n set({ isLoading: true, isInitializing: true });\n \n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n const entries: BanditConfigEntry[] = (await indexedDBService.getAll(\n \"banditConfig\",\n 1,\n \"config\",\n storeConfigs\n )) as BanditConfigEntry[];\n\n const mainEntry = entries.find((entry) => entry.id === \"main\");\n const modelEntries = entries.filter((entry) => entry.id !== \"main\" && entry.id !== \"deletedModels\");\n\n const deletedEntry = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"deletedModels\", storeConfigs)) as\n | BanditConfigEntry\n | undefined;\n const deletedModelNames = deletedEntry?.deleted ?? [];\n\n let allModels: BanditPersonality[] = [];\n let selectedModel = \"\";\n\n // STEP 1: Try to load from IndexedDB first\n if (modelEntries.length > 0) {\n debugLogger.info(\"Loading models from IndexedDB\");\n allModels = modelEntries.map((entry) => {\n const modelData = (entry.model as BanditPersonality | undefined) ?? (entry as unknown as BanditPersonality);\n return {\n name: modelData.name,\n tagline: modelData.tagline || \"\",\n systemPrompt: modelData.systemPrompt || \"\",\n commands: modelData.commands ?? [],\n // Fall back to legacy top-level avatar when the nested model config omitted it\n avatarBase64: modelData.avatarBase64 ?? entry.avatarBase64 ?? null,\n };\n }).filter(m => m.name && !deletedModelNames.includes(m.name));\n\n // Filter out Bandit personalities if banditModelsEnabled is false\n const preferences = usePreferencesStore.getState().preferences;\n if (!preferences.banditModelsEnabled) {\n const banditModelNames = defaultModels.map(m => m.name);\n allModels = allModels.filter(model => !banditModelNames.includes(model.name));\n debugLogger.info(\"Filtered out Bandit personalities (preference disabled)\", { \n filteredModels: banditModelNames \n });\n }\n\n selectedModel = mainEntry?.model?.selectedModel || (allModels.length > 0 ? allModels[0].name : \"\");\n debugLogger.info(\"Loaded models from IndexedDB:\", { models: allModels.map(m => m.name), selectedModel });\n \n // If no models remain after filtering deleted ones, try CDN\n if (allModels.length === 0) {\n debugLogger.info(\"No personalities remain after filtering deleted models, checking CDN config\");\n }\n } \n \n // STEP 2: If no models in IndexedDB OR no personalities remain after filtering, try CDN config\n if (modelEntries.length === 0 || allModels.length === 0) {\n debugLogger.info(\"No models in IndexedDB, checking CDN config\");\n const packageSettings = usePackageSettingsStore.getState().getSettings();\n let configModels: BrandingConfig | null = null;\n\n if (packageSettings?.brandingConfigUrl) {\n try {\n const response = await fetch(packageSettings.brandingConfigUrl);\n configModels = await response.json();\n } catch (err) {\n debugLogger.warn(\"Failed to load CDN config:\", { error: err });\n }\n }\n\n if (configModels?.models?.length) {\n debugLogger.info(\"Loading models from CDN config\");\n allModels = configModels.models.filter(m => !deletedModelNames.includes(m.name));\n \n // Check if Bandit personalities should be included\n const preferences = usePreferencesStore.getState().preferences;\n if (preferences.banditModelsEnabled) {\n // Add Bandit default personalities if they're not already present\n const cdnModelNames = allModels.map(m => m.name);\n const banditModelsToAdd = defaultModels.filter(banditModel => \n !cdnModelNames.includes(banditModel.name) && !deletedModelNames.includes(banditModel.name)\n );\n allModels = [...allModels, ...banditModelsToAdd];\n debugLogger.info(\"Added Bandit default personalities to CDN models\", { \n banditModels: banditModelsToAdd.map(m => m.name) \n });\n } else {\n // Filter out any Bandit personalities that might be in the CDN config\n const banditModelNames = defaultModels.map(m => m.name);\n allModels = allModels.filter(model => !banditModelNames.includes(model.name));\n debugLogger.info(\"Filtered out Bandit personalities from CDN config (preference disabled)\", {\n banditModels: banditModelNames\n });\n }\n \n selectedModel = allModels.length > 0 ? allModels[0].name : \"\";\n \n // Only set hasTransparentLogo from CDN if no user branding exists\n const existingConfig = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"main\", storeConfigs)) as BanditConfigEntry | undefined;\n const hasUserBranding = existingConfig?.branding?.userSaved;\n if (!hasUserBranding) {\n set({ hasTransparentLogo: configModels?.branding?.hasTransparentLogo ?? true });\n debugLogger.info(\"Set hasTransparentLogo from CDN config (no user branding)\");\n } else {\n debugLogger.info(\"Preserved user hasTransparentLogo setting (user branding exists)\");\n }\n \n // Save CDN models to IndexedDB for future use\n for (const model of allModels) {\n await indexedDBService.put(\"banditConfig\", 1, \"config\", { id: model.name, model }, storeConfigs);\n }\n \n debugLogger.info(\"Loaded and saved models from CDN config:\", { models: allModels.map(m => m.name) });\n } \n // STEP 3: Fall back to Bandit defaults (only if banditModelsEnabled is true)\n else {\n const preferences = usePreferencesStore.getState().preferences;\n if (preferences.banditModelsEnabled) {\n debugLogger.info(\"No CDN config available, loading Bandit defaults\");\n await get().restoreDefaultModels();\n set({ isLoading: false, isInitializing: false });\n return;\n } else {\n debugLogger.info(\"No CDN config available and Bandit personalities disabled, loading empty model list\");\n allModels = [];\n selectedModel = \"\";\n }\n }\n }\n\n // Set the models and selected model\n set({ availableModels: allModels });\n debugLogger.info(\"Setting selected model:\", { selectedModel });\n get().setSelectedModel(selectedModel);\n\n debugLogger.info(\"Model initialization complete\");\n set({ isLoading: false, isInitializing: false });\n },\n setHasTransparentLogo: (value) => set({ hasTransparentLogo: value }),\n restoreDefaultModels: async () => {\n debugLogger.debug(\"🧪 Restoring default models...\");\n set({ isLoading: true });\n \n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n \n // Clear existing models from state\n set({ availableModels: [] });\n \n // Clear deletedModels entry in IndexedDB\n try {\n await indexedDBService.delete(\"banditConfig\", 1, \"config\", \"deletedModels\", storeConfigs);\n debugLogger.info(\"restoreDefaultModels: Cleared deletedModels entry in IndexedDB\");\n } catch (err) {\n debugLogger.warn(\"restoreDefaultModels: Failed to clear deletedModels entry in IndexedDB\", { error: err });\n }\n \n let allModels: BanditPersonality[] = [];\n let selectedModel = \"\";\n \n // STEP 1: Try to load from CDN config first\n const packageSettings = usePackageSettingsStore.getState().getSettings();\n let configModels: BrandingConfig | null = null;\n \n if (packageSettings?.brandingConfigUrl) {\n debugLogger.debug(\"🔗 Attempting to load default models from CDN config...\");\n try {\n const response = await fetch(packageSettings.brandingConfigUrl);\n configModels = await response.json();\n } catch (err) {\n debugLogger.warn(\"Failed to load CDN config:\", { error: err });\n }\n }\n \n if (configModels?.models?.length) {\n // Use models from CDN config\n allModels = configModels.models;\n \n // Check if Bandit personalities should be included\n const preferences = usePreferencesStore.getState().preferences;\n if (preferences.banditModelsEnabled) {\n // Add Bandit default personalities if they're not already present\n const cdnModelNames = allModels.map(m => m.name);\n const banditModelsToAdd = defaultModels.filter(banditModel => \n !cdnModelNames.includes(banditModel.name)\n );\n allModels = [...allModels, ...banditModelsToAdd];\n debugLogger.info(\"restoreDefaultModels: Added Bandit personalities to CDN config\", { \n banditModels: banditModelsToAdd.map(m => m.name) \n });\n } else {\n // Filter out any Bandit personalities that might be in the CDN config\n const banditModelNames = defaultModels.map(m => m.name);\n allModels = allModels.filter(model => !banditModelNames.includes(model.name));\n debugLogger.info(\"restoreDefaultModels: Filtered out Bandit personalities (preference disabled)\", {\n banditModels: banditModelNames\n });\n }\n \n selectedModel = allModels.length > 0 ? allModels[0].name : \"\";\n \n // Only set hasTransparentLogo from CDN if no user branding exists\n try {\n const existingConfig = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"main\", storeConfigs)) as BanditConfigEntry | undefined;\n const hasUserBranding = existingConfig?.branding?.userSaved;\n if (!hasUserBranding) {\n set({ hasTransparentLogo: configModels?.branding?.hasTransparentLogo ?? true });\n debugLogger.info(\"restoreDefaultModels: Set hasTransparentLogo from CDN config (no user branding)\");\n } else {\n debugLogger.info(\"restoreDefaultModels: Preserved user hasTransparentLogo setting (user branding exists)\");\n }\n } catch (err) {\n // Fallback to CDN setting if we can't check IndexedDB\n set({ hasTransparentLogo: configModels?.branding?.hasTransparentLogo ?? true });\n debugLogger.warn(\"restoreDefaultModels: Using CDN hasTransparentLogo as fallback\", { error: err });\n }\n \n debugLogger.info(\"✅ Using default models from CDN config:\", { models: allModels.map(m => m.name) });\n } else {\n // STEP 2: Fall back to built-in Bandit defaults (only if enabled)\n const preferences = usePreferencesStore.getState().preferences;\n if (preferences.banditModelsEnabled) {\n allModels = defaultModels;\n selectedModel = allModels.length > 0 ? allModels[0].name : \"\";\n debugLogger.info(\"✅ Using built-in default Bandit personalities:\", { models: allModels.map(m => m.name) });\n } else {\n allModels = [];\n selectedModel = \"\";\n debugLogger.info(\"✅ Bandit personalities disabled, using empty model list\");\n }\n }\n \n // Persist each model to IndexedDB\n for (const model of allModels) {\n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: model.name,\n model,\n }, storeConfigs);\n }\n \n // Update Zustand state\n set({ availableModels: allModels });\n \n debugLogger.debug(\"🎯 Setting default selected model:\", { model: selectedModel });\n get().setSelectedModel(selectedModel);\n \n debugLogger.debug(\"✅ Default models restored and persisted to IndexedDB\");\n set({ isLoading: false });\n },\n restoreDeletedBanditModels: async () => {\n debugLogger.debug(\"🔄 Restoring deleted Bandit personalities...\");\n set({ isLoading: true });\n \n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n \n try {\n // Get current deleted models list\n const deletedEntry = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"deletedModels\", storeConfigs)) as\n | BanditConfigEntry\n | undefined;\n const deletedModelNames = deletedEntry?.deleted ?? [];\n \n debugLogger.info(\"Current deleted models:\", { deletedModelNames });\n \n // Find which Bandit personalities are deleted\n const deletedBanditModels = defaultModels.filter(banditModel => \n deletedModelNames.includes(banditModel.name)\n );\n \n debugLogger.info(\"Deleted Bandit personalities found:\", { \n deletedBanditModels: deletedBanditModels.map(m => m.name) \n });\n \n if (deletedBanditModels.length === 0) {\n debugLogger.info(\"No deleted Bandit personalities to restore\");\n set({ isLoading: false });\n return { restored: [], hadNothingToRestore: true };\n }\n \n // Remove Bandit personality names from deleted list\n const updatedDeletedNames = deletedModelNames.filter((name: string) => \n !defaultModels.some(banditModel => banditModel.name === name)\n );\n \n debugLogger.info(\"Updated deleted list after removing Bandit personalities:\", { \n updatedDeletedNames \n });\n \n // Update deleted models list in IndexedDB\n if (updatedDeletedNames.length > 0) {\n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: \"deletedModels\",\n deleted: updatedDeletedNames,\n }, storeConfigs);\n debugLogger.info(\"Updated deletedModels in IndexedDB\");\n } else {\n // If no models left in deleted list, remove the entry\n await indexedDBService.delete(\"banditConfig\", 1, \"config\", \"deletedModels\", storeConfigs);\n debugLogger.info(\"Removed deletedModels entry from IndexedDB (empty list)\");\n }\n \n // Check if Bandit personalities preference is enabled\n const preferences = usePreferencesStore.getState().preferences;\n debugLogger.info(\"Bandit personalities preference enabled:\", { enabled: preferences.banditModelsEnabled });\n \n if (!preferences.banditModelsEnabled) {\n debugLogger.info(\"⚠️ Bandit personalities preference is disabled. Personalities restored from deleted list but not added to available models until preference is enabled.\");\n set({ isLoading: false });\n return { restored: deletedBanditModels.map(m => m.name), hadNothingToRestore: false };\n }\n \n // Add restored Bandit personalities to current available models\n const currentModels = get().availableModels;\n debugLogger.info(\"Current available models:\", { \n currentModels: currentModels.map(m => m.name) \n });\n \n const restoredModels = deletedBanditModels.filter(banditModel => \n !currentModels.some(current => current.name === banditModel.name)\n );\n \n debugLogger.info(\"Models to restore:\", { \n restoredModels: restoredModels.map(m => m.name) \n });\n \n if (restoredModels.length === 0) {\n debugLogger.info(\"No new models to add (all restored models already present)\");\n set({ isLoading: false });\n return { restored: [], hadNothingToRestore: true };\n }\n \n // Persist restored models to IndexedDB\n for (const model of restoredModels) {\n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: model.name,\n model,\n }, storeConfigs);\n debugLogger.info(\"Persisted restored model to IndexedDB:\", { modelName: model.name });\n }\n \n // Update Zustand state\n const updatedAvailableModels = [...currentModels, ...restoredModels];\n set({ availableModels: updatedAvailableModels });\n \n debugLogger.info(\"✅ Restored deleted Bandit personalities:\", { \n restoredModels: restoredModels.map(m => m.name),\n totalModels: updatedAvailableModels.length\n });\n \n // If no model is currently selected and we have models now, select the first restored one\n const currentSelectedModel = get().selectedModel;\n if (!currentSelectedModel && updatedAvailableModels.length > 0) {\n const modelToSelect = restoredModels[0] || updatedAvailableModels[0];\n get().setSelectedModel(modelToSelect.name);\n debugLogger.info(\"Auto-selected model after restore:\", { modelName: modelToSelect.name });\n }\n \n return { restored: restoredModels.map(m => m.name), hadNothingToRestore: false };\n \n } catch (error) {\n debugLogger.error(\"Failed to restore deleted Bandit personalities\", { error });\n throw error;\n } finally {\n set({ isLoading: false });\n }\n },\n handleBanditPersonalitiesPreferenceChange: async (enabled: boolean) => {\n debugLogger.info(\"🔄 Handling Bandit personalities preference change\", { enabled });\n \n const currentModels = get().availableModels;\n const banditModelNames = defaultModels.map(m => m.name);\n \n if (enabled) {\n // Add Bandit personalities that aren't already present\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n \n // Get deleted models to avoid adding them back\n const deletedEntry = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"deletedModels\", storeConfigs)) as\n | BanditConfigEntry\n | undefined;\n const deletedModelNames = deletedEntry?.deleted ?? [];\n \n const modelsToAdd = defaultModels.filter(banditModel => \n !currentModels.some(current => current.name === banditModel.name) &&\n !deletedModelNames.includes(banditModel.name)\n );\n \n if (modelsToAdd.length > 0) {\n // Persist added models to IndexedDB\n for (const model of modelsToAdd) {\n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: model.name,\n model,\n }, storeConfigs);\n }\n \n const updatedModels = [...currentModels, ...modelsToAdd];\n set({ availableModels: updatedModels });\n \n debugLogger.info(\"✅ Added Bandit personalities\", { \n addedModels: modelsToAdd.map(m => m.name) \n });\n \n // If no model is selected and we added models, select the first one\n const currentSelectedModel = get().selectedModel;\n if (!currentSelectedModel && updatedModels.length > 0) {\n get().setSelectedModel(updatedModels[0].name);\n }\n }\n } else {\n // Remove Bandit personalities from current list\n const filteredModels = currentModels.filter(model => !banditModelNames.includes(model.name));\n set({ availableModels: filteredModels });\n \n debugLogger.info(\"✅ Removed Bandit personalities\", { \n removedModels: banditModelNames.filter(name => \n currentModels.some(model => model.name === name)\n )\n });\n \n // If the currently selected model was a Bandit model, select a different one\n const currentSelectedModel = get().selectedModel;\n if (currentSelectedModel && banditModelNames.includes(currentSelectedModel)) {\n const newSelectedModel = filteredModels.length > 0 ? filteredModels[0].name : \"\";\n get().setSelectedModel(newSelectedModel);\n debugLogger.info(\"🔄 Changed selected model after removing Bandit personalities\", { \n oldModel: currentSelectedModel, \n newModel: newSelectedModel \n });\n }\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-C0F4-A852E5\nconst __banditFingerprint_types_commontypests = 'BL-FP-DF0035-B29D';\nconst __auditTrail_types_commontypests = 'BL-AU-MGOIKVVR-SFSG';\n// File: common.types.ts | Path: src/services/ai-provider/types/common.types.ts | Hash: c0f4b29d\n\n/**\n * Common types used across all AI providers\n */\n\nexport interface AIMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface AIChatRequest {\n model: string;\n messages: AIMessage[];\n stream?: boolean;\n temperature?: number;\n maxTokens?: number;\n images?: string[];\n options?: Record<string, unknown>;\n}\n\nexport interface AIToolCall {\n id?: string;\n type?: 'function';\n function: {\n name: string;\n arguments: string | Record<string, unknown>;\n };\n}\n\nexport interface AIChatResponse {\n message: {\n content: string;\n role: 'assistant';\n tool_calls?: AIToolCall[];\n };\n done?: boolean;\n}\n\nexport interface AIGenerateRequest {\n model: string;\n prompt: string;\n stream?: boolean;\n options?: Record<string, unknown>;\n}\n\nexport interface AIGenerateResponse {\n response: string;\n done?: boolean;\n}\n\nexport interface AIModel {\n name: string;\n size?: number;\n details?: {\n format?: string;\n family?: string;\n families?: string[];\n parameter_size?: string;\n quantization_level?: string;\n };\n digest?: string;\n modified_at?: string;\n}\n\nexport interface AIProviderConfig {\n type: 'ollama' | 'openai' | 'azure-openai' | 'anthropic' | 'xai' | 'bandit' | 'gateway' | 'playground';\n baseUrl?: string;\n apiKey?: string;\n apiVersion?: string; // For Azure\n deploymentName?: string; // For Azure\n defaultModel?: string; // Preferred chat model when using direct providers\n anthropicVersion?: string;\n anthropicMaxTokens?: number;\n gatewayUrl?: string; // For gateway-based providers\n provider?: 'openai' | 'azure-openai' | 'anthropic' | 'ollama' | 'xai' | 'bandit' | 'playground'; // Which backend provider to use via gateway\n tokenFactory?: () => string | null;\n}\n\nexport enum AIProviderType {\n OLLAMA = 'ollama',\n OPENAI = 'openai',\n AZURE_OPENAI = 'azure-openai',\n ANTHROPIC = 'anthropic',\n XAI = 'xai',\n BANDIT = 'bandit',\n GATEWAY = 'gateway',\n PLAYGROUND = 'playground'\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-6CED-5122D4\nconst __banditFingerprint_ollama_ollamaservicets = 'BL-FP-3B6550-DAFC';\nconst __auditTrail_ollama_ollamaservicets = 'BL-AU-MGOIKVVW-1K0E';\n// File: ollama.service.ts | Path: src/services/ollama/ollama.service.ts | Hash: 6ceddafc\n\nimport { ChatRequest, ChatResponse, GenerateRequest, GenerateResponse, Model, ModelResponse } from \"./interfaces\";\nimport { catchError, from, lastValueFrom, map, Observable, of, shareReplay, switchMap, throwError, timeout } from \"rxjs\";\nimport { debugLogger } from \"../logging/debugLogger\";\n\nconst handleError = () => (obs: Observable<Response>) =>\n obs.pipe(\n switchMap((response) =>\n response.ok\n ? of(response)\n : throwError(() => new Error(`Request failed: ${response.status} ${response.statusText}`))\n )\n );\n\nconst parseResponseBody = async <T>(response: Response, responseType: 'json' | 'text'): Promise<T> => {\n if (responseType === 'text') {\n return (await response.text()) as unknown as T;\n }\n return (await response.json()) as T;\n};\n\nexport class OllamaService {\n\n constructor(\n private _baseUrl: string,\n private readonly _tokenFactory: () => string | null\n ) {\n if (!this._baseUrl) {\n this._baseUrl = 'http://localhost:11434'\n debugLogger.warn(`No base URL provided, using default: ${this._baseUrl}`);\n }\n }\n\n\n private _tryGatewayWithTimeout(args: {\n url: string,\n responseType: 'json' | 'text',\n timeoutMs: number,\n }): Observable<boolean> {\n const { url, responseType, timeoutMs } = args;\n const source = this._get(url, responseType)\n const mapped = source.pipe(\n catchError((e) => (e?.message.includes(\"401\") ? of(true) : of(false))),\n map(() => true),\n timeout(timeoutMs),\n );\n return mapped;\n }\n\n /**\n * Validates the availability of the service at the given base URL.\n * @param fallbackUrl The fallback URL to try if the base URL is not available.\n * @returns An object containing the URL and availability status.\n */\n async validateServiceAvailability(args: { fallbackUrl: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n const { fallbackUrl, timeoutMs } = args;\n const responseType = 'text';\n const availablility = {\n url: \"\",\n isAvailable: false,\n }\n try {\n debugLogger.debug(`Validating service availability at ${this._baseUrl}`);\n\n\n\n availablility.url = this._baseUrl;\n availablility.isAvailable = await lastValueFrom(\n this._tryGatewayWithTimeout({\n url: availablility.url,\n responseType,\n timeoutMs,\n })\n ) as boolean;\n if (!availablility.isAvailable) {\n throw new Error(`Service not available at ${this._baseUrl}`);\n }\n\n return availablility;\n } catch (e) {\n debugLogger.warn(`Service not available at ${this._baseUrl}, trying fallback URL: ${fallbackUrl}`);\n try {\n\n availablility.url = fallbackUrl;\n availablility.isAvailable = await lastValueFrom(\n this._tryGatewayWithTimeout({\n url: availablility.url,\n responseType,\n timeoutMs,\n })\n ) as boolean;\n\n if (!availablility.isAvailable) {\n throw new Error(`Service not available at ${fallbackUrl}`);\n }\n this._baseUrl = fallbackUrl;\n return availablility;\n } catch (e) {\n debugLogger.error(`Service not available at fallback URL: ${fallbackUrl}`);\n throw e;\n }\n }\n }\n\n\n generate(request: GenerateRequest): Observable<GenerateResponse> {\n const url = `${this._baseUrl}/api/generate`;\n return new Observable<GenerateResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: this._getHeaders(),\n body: JSON.stringify({ ...request, stream: request.stream === false ? false : true }),\n });\n task.then(response => {\n this._throwErrorIfNotOk(url, response);\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n if (buffer.trim() !== \"\") {\n try {\n observer.next(JSON.parse(buffer));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Final chunk parsing error (generate):', { buffer });\n }\n }\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n observer.next(JSON.parse(line));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Error parsing JSON line (generate):', { line });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n })\n .catch(err => observer.error(err));\n });\n }\n\n // generate(request: GenerateRequest): Observable<GenerateResponse> {\n // const url = `${this._baseUrl}/api/generate`;\n // return this._post<GenerateRequest, GenerateResponse>(url, request);\n // }\n\n chat(request: ChatRequest): Observable<ChatResponse> {\n const url = `${this._baseUrl}/api/chat`;\n return new Observable<ChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: this._getHeaders(),\n body: JSON.stringify({ ...request, stream: true }),\n });\n task.then(response => {\n this._throwErrorIfNotOk(url, response);\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n if (buffer.trim() !== \"\") {\n try {\n observer.next(JSON.parse(buffer));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Final chunk parsing error (chat):', { buffer });\n }\n }\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n observer.next(JSON.parse(line));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Error parsing JSON line (chat):', { line });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n })\n .catch(err => observer.error(err));\n });\n }\n\n\n listModels(): Observable<Model[]> {\n const url = `${this._baseUrl}/api/tags`;\n const response = this._get<ModelResponse>(url);\n const result = response.pipe(\n map(data => data.models),\n shareReplay(1));\n return result;\n }\n\n private _get<T>(url: string, responseType: 'json' | 'text' = 'json'): Observable<T> {\n const requestInit = {\n method: 'GET',\n headers: this._getHeaders(),\n }\n\n const response = from(fetch(url, requestInit));\n const handleFetchError = response.pipe(handleError());\n const data = handleFetchError.pipe(switchMap((res) => from(parseResponseBody<T>(res, responseType))));\n const result = data.pipe(shareReplay(1));\n\n return result;\n }\n\n private _post<TRequest, TResponse>(url: string, body: TRequest): Observable<TResponse> {\n const response = from(fetch(url, {\n method: 'POST',\n headers: this._getHeaders(),\n body: JSON.stringify(body),\n }));\n const handleFetchError = response.pipe(handleError());\n const json = handleFetchError.pipe(switchMap((res) => from(parseResponseBody<TResponse>(res, 'json'))));\n const result = json.pipe(shareReplay(1));\n return result;\n }\n private _throwErrorIfNotOk(url: string, response: Response) {\n if (!response.ok) {\n throw new Error(`POST ${url} failed: ${response.status} ${response.statusText}`);\n }\n }\n private _getHeaders() {\n const token = this._tokenFactory();\n \n if (!token) {\n debugLogger.warn('OllamaService: No token found, using empty string for Authorization header');\n }\n\n return {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token || ''}`\n };\n }\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-22FF-7E873B\nconst __banditFingerprint_providers_deprecatedts = 'BL-FP-DA6749-9B2A';\nconst __auditTrail_providers_deprecatedts = 'BL-AU-MGOIKVVQ-2ZKO';\n// File: deprecated.ts | Path: src/services/ai-provider/providers/deprecated.ts | Hash: 22ff9b2a\n\nimport { debugLogger } from '../../logging/debugLogger';\nimport { AIProviderConfig } from '../types/common.types';\n\n/**\n * Deprecation notices for direct provider implementations\n * \n * MIGRATION NOTICE: Direct provider implementations are being phased out in favor \n * of the new unified gateway architecture. Please migrate to gateway-based providers\n * for enhanced security, performance, and centralized management.\n * \n * See GATEWAY_MIGRATION_GUIDE.md for migration instructions.\n */\n\n/**\n * @deprecated Use GatewayProvider with provider: 'openai' instead\n * \n * Migration example:\n * ```typescript\n * // Old (deprecated)\n * const config = { type: 'openai', apiKey: 'sk-...', baseUrl: '...' };\n * \n * // New (recommended)\n * const config = { \n * type: 'gateway', \n * gatewayUrl: 'https://your-gateway.com',\n * provider: 'openai',\n * tokenFactory: () => localStorage.getItem('authToken')\n * };\n * ```\n */\nexport function deprecatedOpenAIProvider() {\n debugLogger.warn('⚠️ DEPRECATION WARNING: Direct OpenAI provider is deprecated. Please migrate to GatewayProvider with provider: \"openai\". See GATEWAY_MIGRATION_GUIDE.md for details.');\n}\n\n/**\n * @deprecated Use GatewayProvider with provider: 'azure-openai' instead\n * \n * Migration example:\n * ```typescript\n * // Old (deprecated)\n * const config = { \n * type: 'azure-openai', \n * baseUrl: 'https://your-resource.openai.azure.com',\n * apiKey: 'your-key',\n * apiVersion: '2024-02-15-preview',\n * deploymentName: 'gpt-4'\n * };\n * \n * // New (recommended)\n * const config = { \n * type: 'gateway', \n * gatewayUrl: 'https://your-gateway.com',\n * provider: 'azure-openai',\n * deploymentName: 'gpt-4',\n * apiVersion: '2024-02-15-preview',\n * tokenFactory: () => localStorage.getItem('authToken')\n * };\n * ```\n */\nexport function deprecatedAzureOpenAIProvider() {\n debugLogger.warn('⚠️ DEPRECATION WARNING: Direct Azure OpenAI provider is deprecated. Please migrate to GatewayProvider with provider: \"azure-openai\". See GATEWAY_MIGRATION_GUIDE.md for details.');\n}\n\n/**\n * @deprecated Use GatewayProvider with provider: 'anthropic' instead\n * \n * Migration example:\n * ```typescript\n * // Old (deprecated)\n * const config = { type: 'anthropic', apiKey: 'sk-ant-...', baseUrl: '...' };\n * \n * // New (recommended)\n * const config = { \n * type: 'gateway', \n * gatewayUrl: 'https://your-gateway.com',\n * provider: 'anthropic',\n * tokenFactory: () => localStorage.getItem('authToken')\n * };\n * ```\n */\nexport function deprecatedAnthropicProvider() {\n debugLogger.warn('⚠️ DEPRECATION WARNING: Direct Anthropic provider is deprecated. Please migrate to GatewayProvider with provider: \"anthropic\". See GATEWAY_MIGRATION_GUIDE.md for details.');\n}\n\n/**\n * @deprecated Use GatewayProvider with provider: 'ollama' instead for production environments\n * \n * Note: The direct Ollama provider will remain available for local development,\n * but for production deployments, use the gateway for better management.\n * \n * Migration example:\n * ```typescript\n * // Development (still supported)\n * const config = { type: 'ollama', baseUrl: 'http://localhost:11434' };\n * \n * // Production (recommended)\n * const config = { \n * type: 'gateway', \n * gatewayUrl: 'https://your-gateway.com',\n * provider: 'ollama',\n * tokenFactory: () => localStorage.getItem('authToken')\n * };\n * ```\n */\nexport function deprecatedOllamaProvider() {\n debugLogger.info('ℹ️ INFO: Direct Ollama provider is available for local development. For production environments, consider using GatewayProvider with provider: \"ollama\" for enhanced management. See GATEWAY_MIGRATION_GUIDE.md for details.');\n}\n\n/**\n * Display deprecation summary\n */\nexport function showDeprecationSummary() {\n debugLogger.warn(`\n🏗️ BANDIT ENGINE PROVIDER ARCHITECTURE UPDATE\n\nThe Bandit Engine is transitioning to a unified gateway architecture for enhanced:\n• Security (centralized API key management)\n• Performance (connection pooling, caching)\n• Monitoring (unified logging, health checks)\n• Scaling (load balancing, failover)\n\nMIGRATION REQUIRED:\n• OpenAI Provider → GatewayProvider (provider: 'openai')\n• Azure OpenAI Provider → GatewayProvider (provider: 'azure-openai') \n• Anthropic Provider → GatewayProvider (provider: 'anthropic')\n\nMIGRATION RECOMMENDED:\n• Ollama Provider → GatewayProvider (provider: 'ollama') for production\n\n📖 Full migration guide: GATEWAY_MIGRATION_GUIDE.md\n🆘 Need help? Check the troubleshooting section in the migration guide\n `);\n}\n\n/**\n * Check if provider config is using deprecated direct provider\n */\nexport function isDeprecatedProvider(config: AIProviderConfig | undefined): boolean {\n const deprecatedTypes = ['openai', 'azure-openai', 'anthropic'];\n return deprecatedTypes.includes(config?.type);\n}\n\n/**\n * Suggest gateway migration for deprecated config\n */\nexport function suggestGatewayMigration(config: AIProviderConfig): AIProviderConfig {\n if (!isDeprecatedProvider(config)) {\n return config; // No migration needed\n }\n\n const gatewayConfig: AIProviderConfig = {\n type: 'gateway',\n gatewayUrl: '${GATEWAY_URL}', // Replace with your gateway URL\n provider: config.type as 'openai' | 'azure-openai' | 'anthropic' | 'ollama',\n tokenFactory: () => localStorage.getItem('authToken')\n };\n\n // Preserve Azure-specific config\n if (config.type === 'azure-openai') {\n gatewayConfig.deploymentName = config.deploymentName;\n gatewayConfig.apiVersion = config.apiVersion;\n }\n\n debugLogger.info('🔄 Suggested gateway migration:', {\n from: config,\n to: gatewayConfig\n });\n\n return gatewayConfig;\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-A59E-4B6F9C\nconst __banditFingerprint_providers_ollamaproviderts = 'BL-FP-89E894-7B5E';\nconst __auditTrail_providers_ollamaproviderts = 'BL-AU-MGOIKVVQ-QJIU';\n// File: ollama.provider.ts | Path: src/services/ai-provider/providers/ollama.provider.ts | Hash: a59e7b5e\n\nimport { Observable, map } from 'rxjs';\nimport { OllamaService } from '../../ollama/ollama.service';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\nimport { deprecatedOllamaProvider } from './deprecated';\n\n/**\n * Ollama provider implementation that wraps the existing OllamaService\n */\nexport class OllamaProvider implements IAIProvider {\n private ollamaService: OllamaService;\n private config: AIProviderConfig;\n\n constructor(config: AIProviderConfig) {\n deprecatedOllamaProvider(); // Show info about gateway option for production\n this.config = config;\n const baseUrl = config.baseUrl || 'http://localhost:11434';\n debugLogger.info(\"OllamaProvider: Constructor\", { \n configBaseUrl: config.baseUrl,\n finalBaseUrl: baseUrl,\n hasTokenFactory: !!config.tokenFactory \n });\n this.ollamaService = new OllamaService(\n baseUrl,\n config.tokenFactory || (() => null)\n );\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n // Transform common request to Ollama-specific format\n const ollamaRequest = {\n model: request.model,\n messages: request.messages.map(msg => ({\n role: msg.role as 'system' | 'user' | 'assistant',\n content: msg.content\n })),\n stream: request.stream,\n options: request.options,\n images: request.images\n };\n\n return this.ollamaService.chat(ollamaRequest).pipe(\n map(response => ({\n message: {\n content: response.message.content,\n role: 'assistant' as const\n },\n done: response.done\n }))\n );\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n // Transform common request to Ollama-specific format\n const ollamaRequest = {\n model: request.model,\n prompt: request.prompt,\n stream: request.stream,\n options: request.options\n };\n\n return this.ollamaService.generate(ollamaRequest).pipe(\n map(response => ({\n response: response.response,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n return this.ollamaService.listModels().pipe(\n map(models => models.map(model => ({\n name: model.name,\n size: model.size,\n details: model.details,\n digest: model.digest,\n modified_at: model.modified_at\n })))\n );\n }\n\n async validateServiceAvailability(args: { \n fallbackUrl?: string; \n timeoutMs: number; \n }): Promise<{ url: string; isAvailable: boolean }> {\n return this.ollamaService.validateServiceAvailability({\n fallbackUrl: args.fallbackUrl || '',\n timeoutMs: args.timeoutMs\n });\n }\n\n getProviderType(): string {\n return AIProviderType.OLLAMA;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\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-E7EE-93DC85\nconst __banditFingerprint_providers_openaiproviderts = 'BL-FP-7E2188-DCC5';\nconst __auditTrail_providers_openaiproviderts = 'BL-AU-MGOIKVVQ-8GVP';\n// File: openai.provider.ts | Path: src/services/ai-provider/providers/openai.provider.ts | Hash: e7eedcc5\n\nimport { Observable, from, switchMap, map, throwError } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\nimport { deprecatedOpenAIProvider } from './deprecated';\n\ninterface OpenAIChatPayload {\n model: string;\n messages: AIChatRequest['messages'];\n stream: boolean;\n temperature?: number;\n max_tokens?: number;\n}\n\ninterface OpenAIStreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n };\n }>;\n}\n\ninterface OpenAIChatResponsePayload {\n choices?: Array<{\n message?: {\n content?: string;\n };\n }>;\n}\n\ninterface OpenAIModelListResponse {\n data: Array<{\n id: string;\n object?: string;\n }>;\n}\n\n/**\n * OpenAI provider implementation\n */\nexport class OpenAIProvider implements IAIProvider {\n private config: AIProviderConfig;\n private baseUrl: string;\n\n constructor(config: AIProviderConfig) {\n deprecatedOpenAIProvider(); // Show deprecation warning\n this.config = config;\n this.baseUrl = config.baseUrl || 'https://api.openai.com/v1';\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const url = `${this.baseUrl}/chat/completions`;\n \n const payload: OpenAIChatPayload = {\n model: request.model,\n messages: request.messages,\n stream: Boolean(request.stream),\n temperature: request.temperature,\n max_tokens: request.maxTokens\n };\n\n if (request.stream) {\n return this.streamChatRequest(url, payload);\n } else {\n return this.nonStreamChatRequest(url, payload);\n }\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n // For OpenAI, we'll use the chat endpoint with a single user message\n const chatRequest: AIChatRequest = {\n model: request.model,\n messages: [{ role: 'user', content: request.prompt }],\n stream: request.stream,\n options: request.options\n };\n\n return this.chat(chatRequest).pipe(\n map(response => ({\n response: response.message.content,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n const url = `${this.baseUrl}/models`;\n \n return from(fetch(url, {\n headers: this.getHeaders()\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`Failed to list models: ${response.status}`));\n }\n return from(response.json() as Promise<OpenAIModelListResponse>);\n }),\n map((data) =>\n data.data.map((model) => ({\n name: model.id,\n details: {\n format: 'openai',\n family: model.object\n }\n }))\n )\n );\n }\n\n async validateServiceAvailability(args: { \n fallbackUrl?: string; \n timeoutMs: number; \n }): Promise<{ url: string; isAvailable: boolean }> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const response = await fetch(`${this.baseUrl}/models`, {\n headers: this.getHeaders(),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n return {\n url: this.baseUrl,\n isAvailable: response.ok\n };\n } catch (error) {\n if (args.fallbackUrl) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const response = await fetch(`${args.fallbackUrl}/models`, {\n headers: this.getHeaders(),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n this.baseUrl = args.fallbackUrl;\n return {\n url: args.fallbackUrl,\n isAvailable: true\n };\n }\n } catch (fallbackError) {\n // Fall through to return unavailable\n }\n }\n\n return {\n url: this.baseUrl,\n isAvailable: false\n };\n }\n }\n\n getProviderType(): string {\n return AIProviderType.OPENAI;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private streamChatRequest(url: string, payload: OpenAIChatPayload): Observable<AIChatResponse> {\n return new Observable<AIChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n task.then(response => {\n if (!response.ok) {\n observer.error(new Error(`OpenAI request failed: ${response.status}`));\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim() && line.startsWith('data: ')) {\n const data = line.slice(6).trim();\n if (data === '[DONE]') {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n try {\n const parsed = JSON.parse(data) as OpenAIStreamChunk;\n const content = parsed.choices?.[0]?.delta?.content ?? '';\n if (content) {\n observer.next({\n message: { content, role: 'assistant' },\n done: false\n });\n }\n } catch (err) {\n debugLogger.error('Error parsing OpenAI stream data:', { data, error: err });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n }).catch(err => observer.error(err));\n });\n }\n\n private nonStreamChatRequest(url: string, payload: OpenAIChatPayload): Observable<AIChatResponse> {\n return from(fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`OpenAI request failed: ${response.status}`));\n }\n return from(response.json() as Promise<OpenAIChatResponsePayload>);\n }),\n map((data) => ({\n message: {\n content: data.choices?.[0]?.message?.content ?? '',\n role: 'assistant' as const\n },\n done: true\n }))\n );\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n \n if (this.config.apiKey) {\n headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n }\n\n return headers;\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-4A56-02BF87\nconst __banditFingerprint_providers_azureopenaiproviderts = 'BL-FP-51FF06-B29D';\nconst __auditTrail_providers_azureopenaiproviderts = 'BL-AU-MGOIKVVQ-070A';\n// File: azure-openai.provider.ts | Path: src/services/ai-provider/providers/azure-openai.provider.ts | Hash: 4a56b29d\n\nimport { Observable, from, switchMap, map, throwError } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\nimport { deprecatedAzureOpenAIProvider } from './deprecated';\n\ninterface AzureChatPayload {\n messages: AIChatRequest['messages'];\n stream: boolean;\n temperature?: number;\n max_tokens?: number;\n}\n\ninterface OpenAIStreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n };\n }>;\n}\n\ninterface OpenAIChatResponsePayload {\n choices?: Array<{\n message?: {\n content?: string;\n };\n }>;\n}\n/**\n * Azure OpenAI provider implementation\n */\nexport class AzureOpenAIProvider implements IAIProvider {\n private config: AIProviderConfig;\n private baseUrl: string;\n\n constructor(config: AIProviderConfig) {\n deprecatedAzureOpenAIProvider(); // Show deprecation warning\n this.config = config;\n if (!config.baseUrl || !config.deploymentName || !config.apiVersion) {\n throw new Error('Azure OpenAI requires baseUrl, deploymentName, and apiVersion');\n }\n this.baseUrl = config.baseUrl;\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const url = `${this.baseUrl}/openai/deployments/${this.config.deploymentName}/chat/completions?api-version=${this.config.apiVersion}`;\n \n const payload: AzureChatPayload = {\n messages: request.messages,\n stream: Boolean(request.stream),\n temperature: request.temperature,\n max_tokens: request.maxTokens\n };\n\n if (request.stream) {\n return this.streamChatRequest(url, payload);\n } else {\n return this.nonStreamChatRequest(url, payload);\n }\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n // For Azure OpenAI, we'll use the chat endpoint with a single user message\n const chatRequest: AIChatRequest = {\n model: request.model,\n messages: [{ role: 'user', content: request.prompt }],\n stream: request.stream,\n options: request.options\n };\n\n return this.chat(chatRequest).pipe(\n map(response => ({\n response: response.message.content,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n // Azure OpenAI doesn't have a direct models endpoint, return the deployment as a model\n const model: AIModel = {\n name: this.config.deploymentName || 'azure-deployment',\n details: {\n format: 'azure-openai',\n family: 'gpt'\n }\n };\n\n return new Observable<AIModel[]>(observer => {\n observer.next([model]);\n observer.complete();\n });\n }\n\n async validateServiceAvailability(args: { \n fallbackUrl?: string; \n timeoutMs: number; \n }): Promise<{ url: string; isAvailable: boolean }> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n // Test with a simple chat request\n const testUrl = `${this.baseUrl}/openai/deployments/${this.config.deploymentName}/chat/completions?api-version=${this.config.apiVersion}`;\n const response = await fetch(testUrl, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n messages: [{ role: 'user', content: 'test' }],\n max_tokens: 1\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n return {\n url: this.baseUrl,\n isAvailable: response.ok || response.status === 400 // 400 might be expected for the test\n };\n } catch (error) {\n if (args.fallbackUrl) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const testUrl = `${args.fallbackUrl}/openai/deployments/${this.config.deploymentName}/chat/completions?api-version=${this.config.apiVersion}`;\n const response = await fetch(testUrl, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n messages: [{ role: 'user', content: 'test' }],\n max_tokens: 1\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok || response.status === 400) {\n this.baseUrl = args.fallbackUrl;\n return {\n url: args.fallbackUrl,\n isAvailable: true\n };\n }\n } catch (fallbackError) {\n // Fall through to return unavailable\n }\n }\n\n return {\n url: this.baseUrl,\n isAvailable: false\n };\n }\n }\n\n getProviderType(): string {\n return AIProviderType.AZURE_OPENAI;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private streamChatRequest(url: string, payload: AzureChatPayload): Observable<AIChatResponse> {\n return new Observable<AIChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n task.then(response => {\n if (!response.ok) {\n observer.error(new Error(`Azure OpenAI request failed: ${response.status}`));\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim() && line.startsWith('data: ')) {\n const data = line.slice(6).trim();\n if (data === '[DONE]') {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n try {\n const parsed = JSON.parse(data) as OpenAIStreamChunk;\n const content = parsed.choices?.[0]?.delta?.content ?? '';\n if (content) {\n observer.next({\n message: { content, role: 'assistant' },\n done: false\n });\n }\n } catch (err) {\n debugLogger.error('Error parsing Azure OpenAI stream data:', { data, error: err });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n }).catch(err => observer.error(err));\n });\n }\n\n private nonStreamChatRequest(url: string, payload: AzureChatPayload): Observable<AIChatResponse> {\n return from(fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`Azure OpenAI request failed: ${response.status}`));\n }\n return from(response.json() as Promise<OpenAIChatResponsePayload>);\n }),\n map((data) => {\n const content = data.choices?.[0]?.message?.content ?? '';\n return {\n message: {\n content,\n role: 'assistant' as const\n },\n done: true\n };\n })\n );\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n \n if (this.config.apiKey) {\n headers['api-key'] = this.config.apiKey;\n }\n\n return headers;\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-8631-D26CFA\nconst __banditFingerprint_providers_anthropicproviderts = 'BL-FP-B138E7-AB87';\nconst __auditTrail_providers_anthropicproviderts = 'BL-AU-MGOIKVVP-762R';\n// File: anthropic.provider.ts | Path: src/services/ai-provider/providers/anthropic.provider.ts | Hash: 8631ab87\n\nimport { Observable, from, switchMap, map, throwError } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\nimport { deprecatedAnthropicProvider } from './deprecated';\n\ntype AnthropicRole = 'user' | 'assistant';\n\ninterface AnthropicChatMessagePayload {\n role: AnthropicRole;\n content: string;\n}\n\ninterface AnthropicChatPayload {\n model: string;\n messages: AnthropicChatMessagePayload[];\n system?: string;\n stream: boolean;\n temperature?: number;\n max_tokens: number;\n}\n\ninterface AnthropicStreamChunk {\n delta?: {\n text?: string;\n };\n}\n\ninterface AnthropicChatResponsePayload {\n content?: unknown;\n completion?: string;\n message?: {\n content?: string;\n };\n}\n\n/**\n * Anthropic provider implementation for direct API access\n */\nexport class AnthropicProvider implements IAIProvider {\n private config: AIProviderConfig;\n private baseUrl: string;\n private version: string;\n private defaultMaxTokens: number;\n\n constructor(config: AIProviderConfig) {\n deprecatedAnthropicProvider(); // Show deprecation warning\n this.config = config;\n this.baseUrl = config.baseUrl || 'https://api.anthropic.com/v1';\n this.version = typeof config.anthropicVersion === 'string' && config.anthropicVersion.trim()\n ? config.anthropicVersion.trim()\n : '2023-06-01';\n this.defaultMaxTokens =\n typeof config.anthropicMaxTokens === 'number' && config.anthropicMaxTokens > 0\n ? config.anthropicMaxTokens\n : 1024;\n this.config.anthropicVersion = this.version;\n this.config.anthropicMaxTokens = this.defaultMaxTokens;\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const url = `${this.baseUrl}/messages`;\n \n // Convert system messages to Anthropic format\n const systemMessage = request.messages.find(msg => msg.role === 'system');\n const userMessages = request.messages.filter(msg => msg.role !== 'system');\n \n const payload: AnthropicChatPayload = {\n model: request.model,\n messages: userMessages.map(msg => ({\n role: msg.role === 'user' ? 'user' : 'assistant',\n content: msg.content\n })),\n system: systemMessage?.content,\n stream: Boolean(request.stream),\n temperature: request.temperature,\n max_tokens: request.maxTokens ?? this.defaultMaxTokens\n };\n\n if (request.stream) {\n return this.streamChatRequest(url, payload);\n } else {\n return this.nonStreamChatRequest(url, payload);\n }\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n // For Anthropic, we'll use the messages endpoint with a single user message\n const chatRequest: AIChatRequest = {\n model: request.model,\n messages: [{ role: 'user', content: request.prompt }],\n stream: request.stream,\n options: request.options\n };\n\n return this.chat(chatRequest).pipe(\n map(response => ({\n response: response.message.content,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n // Anthropic doesn't have a public models endpoint, return common models\n const commonModels: AIModel[] = [\n {\n name: 'claude-3-5-sonnet-20241022',\n details: {\n format: 'anthropic',\n family: 'claude-3.5'\n }\n },\n {\n name: 'claude-3-5-haiku-20241022',\n details: {\n format: 'anthropic',\n family: 'claude-3.5'\n }\n },\n {\n name: 'claude-3-opus-20240229',\n details: {\n format: 'anthropic',\n family: 'claude-3'\n }\n },\n {\n name: 'claude-3-sonnet-20240229',\n details: {\n format: 'anthropic',\n family: 'claude-3'\n }\n },\n {\n name: 'claude-3-haiku-20240307',\n details: {\n format: 'anthropic',\n family: 'claude-3'\n }\n }\n ];\n\n return new Observable<AIModel[]>(observer => {\n observer.next(commonModels);\n observer.complete();\n });\n }\n\n async validateServiceAvailability(args: { \n fallbackUrl?: string; \n timeoutMs: number; \n }): Promise<{ url: string; isAvailable: boolean }> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n // Test with a simple messages request\n const response = await fetch(`${this.baseUrl}/messages`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n model: 'claude-3-haiku-20240307',\n messages: [{ role: 'user', content: 'test' }],\n max_tokens: 1\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n return {\n url: this.baseUrl,\n isAvailable: response.ok || response.status === 400 // 400 might be expected for the test\n };\n } catch (error) {\n if (args.fallbackUrl) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const response = await fetch(`${args.fallbackUrl}/messages`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n model: 'claude-3-haiku-20240307',\n messages: [{ role: 'user', content: 'test' }],\n max_tokens: 1\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok || response.status === 400) {\n this.baseUrl = args.fallbackUrl;\n return {\n url: args.fallbackUrl,\n isAvailable: true\n };\n }\n } catch (fallbackError) {\n // Fall through to return unavailable\n }\n }\n\n return {\n url: this.baseUrl,\n isAvailable: false\n };\n }\n }\n\n getProviderType(): string {\n return AIProviderType.ANTHROPIC;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private streamChatRequest(url: string, payload: AnthropicChatPayload): Observable<AIChatResponse> {\n return new Observable<AIChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n task.then(response => {\n if (!response.ok) {\n observer.error(new Error(`Anthropic request failed: ${response.status}`));\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim() && line.startsWith('data: ')) {\n const data = line.slice(6).trim();\n if (data === '[DONE]') {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n try {\n const parsed = JSON.parse(data) as AnthropicStreamChunk;\n // Anthropic streaming format may differ, adjust as needed\n const content = parsed.delta?.text || '';\n if (content) {\n observer.next({\n message: { content, role: 'assistant' },\n done: false\n });\n }\n } catch (err) {\n debugLogger.error('Error parsing Anthropic stream data:', { data, error: err });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n }).catch(err => observer.error(err));\n });\n }\n\n private nonStreamChatRequest(url: string, payload: AnthropicChatPayload): Observable<AIChatResponse> {\n return from(fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`Anthropic request failed: ${response.status}`));\n }\n return from(response.json() as Promise<AnthropicChatResponsePayload>);\n }),\n map((data) => ({\n message: {\n content: this.extractContentText(data),\n role: 'assistant' as const\n },\n done: true\n }))\n );\n }\n\n private extractContentText(payload: AnthropicChatResponsePayload): string {\n const { content } = payload;\n\n if (Array.isArray(content)) {\n for (const entry of content) {\n if (typeof entry === 'string') {\n return entry;\n }\n if (entry && typeof entry === 'object' && 'text' in entry) {\n const text = (entry as { text?: unknown }).text;\n if (typeof text === 'string') {\n return text;\n }\n }\n }\n } else if (typeof content === 'string') {\n return content;\n }\n\n if (typeof payload.completion === 'string') {\n return payload.completion;\n }\n\n if (payload.message && typeof payload.message.content === 'string') {\n return payload.message.content;\n }\n\n return '';\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'anthropic-version': this.version\n };\n \n if (this.config.apiKey) {\n headers['x-api-key'] = this.config.apiKey;\n }\n\n return headers;\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-809E-685A92\nconst __banditFingerprint_gateway_gatewayservicets = 'BL-FP-6DB2F9-8464';\nconst __auditTrail_gateway_gatewayservicets = 'BL-AU-MGOIKVVT-6725';\n// File: gateway.service.ts | Path: src/services/gateway/gateway.service.ts | Hash: 809e8464\n\nimport axios, { AxiosError, AxiosHeaders, AxiosInstance } from \"axios\";\nimport {\n GatewayChatRequest,\n GatewayChatResponse,\n GatewayGenerateRequest,\n GatewayGenerateResponse,\n GatewayModel,\n GatewayModelsResponse,\n GatewayHealthResponse,\n GatewayMemoryResponse\n} from \"./interfaces\";\nimport { FeedbackRequest, FeedbackResponse } from \"./feedback.interfaces\";\nimport { catchError, from, lastValueFrom, map, Observable, of, shareReplay, timeout } from \"rxjs\";\nimport { debugLogger } from \"../logging/debugLogger\";\n\ninterface GatewayHttpErrorResponse {\n status: number;\n statusText: string;\n data: unknown;\n url: string;\n}\n\ntype GatewayHttpError = Error & { response: GatewayHttpErrorResponse };\n\nexport class GatewayService {\n private readonly _client: AxiosInstance;\n\n constructor(\n private _baseUrl: string,\n private readonly _tokenFactory: () => string | null,\n private readonly _feedbackEmail?: string\n ) {\n if (!this._baseUrl) {\n this._baseUrl = 'http://localhost:5000'\n debugLogger.warn(`No gateway URL provided, using default: ${this._baseUrl}`);\n }\n \n // Ensure baseUrl doesn't end with slash\n this._baseUrl = this._baseUrl.replace(/\\/$/, '');\n\n // Remove /api suffix if it exists to avoid double /api/api paths\n if (this._baseUrl.endsWith('/api')) {\n this._baseUrl = this._baseUrl.slice(0, -4);\n debugLogger.info(`Removed /api suffix from gateway URL: ${this._baseUrl}`);\n }\n\n this._client = this._createAxiosClient();\n }\n\n private _createAxiosClient(): AxiosInstance {\n const instance = axios.create({\n baseURL: this._baseUrl,\n headers: {\n 'Content-Type': 'application/json'\n }\n });\n\n instance.interceptors.request.use((config) => {\n const token = this._tokenFactory();\n const headers = AxiosHeaders.from(config.headers ?? {});\n\n if (!headers.has('Content-Type')) {\n headers.set('Content-Type', 'application/json');\n }\n\n if (token && token.trim()) {\n headers.set('Authorization', `Bearer ${token}`);\n } else if (headers.has('Authorization')) {\n headers.delete('Authorization');\n }\n\n config.headers = headers;\n return config;\n });\n\n instance.interceptors.response.use(\n (response) => response,\n (error) => Promise.reject(this._normalizeAxiosError(error))\n );\n\n return instance;\n }\n\n private _normalizeAxiosError(error: AxiosError): Error {\n if (error.response) {\n return this._createHttpError(\n `Request failed: ${error.response.status} ${error.response.statusText ?? \"\"}`,\n {\n status: error.response.status,\n statusText: error.response.statusText ?? \"\",\n data: error.response.data,\n url: error.config?.url ?? \"\"\n }\n );\n }\n\n if (error.request) {\n return new Error(`No response received from gateway: ${error.message}`);\n }\n\n return new Error(error.message);\n }\n\n private _createHttpError(message: string, response: GatewayHttpErrorResponse): GatewayHttpError {\n return Object.assign(new Error(message), { response }) as GatewayHttpError;\n }\n\n private _setBaseUrl(url: string) {\n this._baseUrl = url;\n this._client.defaults.baseURL = url;\n }\n\n private _tryGatewayWithTimeout(args: {\n url: string,\n responseType: 'json' | 'text',\n timeoutMs: number,\n }): Observable<boolean> {\n const { url, responseType, timeoutMs } = args;\n const source = this._get(url, responseType)\n const mapped = source.pipe(\n catchError((e) => (e?.message.includes(\"401\") ? of(true) : of(false))),\n map(() => true),\n timeout(timeoutMs),\n );\n return mapped;\n }\n\n /**\n * Validates the availability of the gateway service.\n * @param fallbackUrl The fallback URL to try if the base URL is not available.\n * @returns An object containing the URL and availability status.\n */\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n const { fallbackUrl, timeoutMs } = args;\n const responseType = 'json';\n const availability = {\n url: \"\",\n isAvailable: false,\n }\n\n try {\n debugLogger.debug(`Validating gateway service availability at ${this._baseUrl}`);\n\n availability.url = this._baseUrl;\n availability.isAvailable = await lastValueFrom(\n this._tryGatewayWithTimeout({\n url: `${availability.url}/api/health`,\n responseType,\n timeoutMs,\n })\n ) as boolean;\n \n if (!availability.isAvailable) {\n throw new Error(`Gateway service not available at ${this._baseUrl}`);\n }\n\n return availability;\n } catch (e) {\n if (fallbackUrl) {\n debugLogger.warn(`Gateway service not available at ${this._baseUrl}, trying fallback URL: ${fallbackUrl}`);\n try {\n availability.url = fallbackUrl.replace(/\\/$/, '');\n availability.isAvailable = await lastValueFrom(\n this._tryGatewayWithTimeout({\n url: `${availability.url}/api/health`,\n responseType,\n timeoutMs,\n })\n ) as boolean;\n\n if (!availability.isAvailable) {\n throw new Error(`Gateway service not available at ${fallbackUrl}`);\n }\n \n this._setBaseUrl(availability.url);\n return availability;\n } catch (e) {\n debugLogger.error(`Gateway service not available at fallback URL: ${fallbackUrl}`);\n throw e;\n }\n } else {\n debugLogger.error(`Gateway service not available and no fallback URL provided`);\n throw e;\n }\n }\n }\n\n /**\n * Get gateway health status and available providers\n */\n getHealth(): Observable<GatewayHealthResponse> {\n const url = `${this._baseUrl}/api/health`;\n return this._get<GatewayHealthResponse>(url);\n }\n\n /**\n * Chat completion using the gateway API\n */\n chat(request: GatewayChatRequest): Observable<GatewayChatResponse> {\n // Use provider-specific endpoint if provider is specified\n // For Ollama specifically, use /chat instead of /chat/completions\n const endpoint =\n request.provider === 'ollama'\n ? `/api/${request.provider}/chat`\n : request.provider === 'playground'\n ? '/api/playground/chat/completions'\n : request.provider\n ? `/api/${request.provider}/chat/completions`\n : '/api/chat/completions';\n const fallbackEndpoint =\n request.provider === 'bandit' ? '/completions' : null;\n const normalizedModel =\n request.provider === 'bandit'\n ? (() => {\n const trimmed = (request.model ?? '').replace(/^bandit:/, '').trim();\n return trimmed !== '' ? trimmed : 'bandit-core-1';\n })()\n : request.model;\n \n const requestBody = { ...request, model: normalizedModel, stream: request.stream !== false };\n \n return new Observable<GatewayChatResponse>(observer => {\n const controller = new AbortController();\n const handleStreamingResponse = async (response: Response) => {\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n if (buffer.trim() !== \"\") {\n try {\n const finalResponse = JSON.parse(buffer);\n observer.next(finalResponse);\n } catch (err) {\n debugLogger.error('GatewayService chat final chunk parsing error', { buffer, error: err });\n observer.error(err);\n }\n }\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed) {\n // Handle both SSE format (OpenAI-style) and direct JSON (Ollama-style)\n let data = trimmed;\n \n if (trimmed.startsWith('data: ')) {\n data = trimmed.slice(6); // Remove 'data: ' prefix for SSE format\n if (data === '[DONE]') {\n observer.complete();\n return;\n }\n }\n \n try {\n const parsed = JSON.parse(data);\n \n // Transform Ollama chat format to OpenAI-compatible format\n if (request.provider === 'ollama' && parsed.message) {\n const transformed: GatewayChatResponse = {\n id: `chatcmpl-${Date.now()}`,\n object: 'chat.completion.chunk',\n created: Math.floor(new Date(parsed.created_at || Date.now()).getTime() / 1000),\n model: parsed.model,\n choices: [{\n index: 0,\n delta: {\n role: parsed.message.role,\n content: parsed.message.content,\n tool_calls: parsed.message.tool_calls\n },\n finish_reason: parsed.done ? (parsed.done_reason || 'stop') : null\n }]\n };\n \n if (parsed.done && parsed.total_duration) {\n transformed.usage = {\n prompt_tokens: parsed.prompt_eval_count || 0,\n completion_tokens: parsed.eval_count || 0,\n total_tokens: (parsed.prompt_eval_count || 0) + (parsed.eval_count || 0)\n };\n }\n \n observer.next(transformed);\n } else {\n // For non-Ollama providers or already transformed responses\n observer.next(parsed);\n }\n } catch (err) {\n debugLogger.error('GatewayService chat stream chunk parsing error', {\n line: trimmed,\n rawData: data,\n error: err\n });\n observer.error(err);\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n };\n\n const sendRequest = (targetEndpoint: string, allowFallback: boolean) => {\n const url = `${this._baseUrl}${targetEndpoint}`;\n\n debugLogger.debug(`Gateway chat request to ${url} with provider: ${request.provider || 'default'}`, {\n model: normalizedModel,\n messageCount: request.messages.length,\n hasImages: !!(request.images && request.images.length > 0),\n imageCount: request.images?.length || 0\n });\n\n fetch(url, {\n method: 'POST',\n headers: this._getHeaders(),\n body: JSON.stringify(requestBody),\n signal: controller.signal,\n })\n .then(async (response) => {\n debugLogger.debug(`Gateway chat response status: ${response.status} for provider: ${request.provider || 'default'}`);\n\n if (response.status === 404 && allowFallback && fallbackEndpoint) {\n debugLogger.warn('GatewayService chat endpoint returned 404, attempting fallback route', {\n provider: request.provider,\n attemptedEndpoint: targetEndpoint,\n fallbackEndpoint\n });\n sendRequest(fallbackEndpoint, false);\n return;\n }\n\n if (!response.ok) {\n // Handle error response properly with body parsing\n let errorText = '';\n let errorData: unknown = null;\n \n try {\n // First, try to read the response body\n errorText = await response.text();\n debugLogger.error('GatewayService chat error response body', {\n status: response.status,\n statusText: response.statusText,\n url: response.url,\n body: errorText\n });\n } catch (readError) {\n debugLogger.error('GatewayService chat failed to read error response body', { error: readError });\n errorText = `Request failed with status ${response.status}`;\n }\n \n // Then, try to parse as JSON for better error info\n try {\n errorData = JSON.parse(errorText);\n debugLogger.error('GatewayService chat parsed error payload', errorData);\n } catch (parseError) {\n debugLogger.error('GatewayService chat error payload was not valid JSON');\n errorData = { message: errorText };\n }\n \n // Create an error object that mimics an HTTP response error for the notification service\n const error = this._createHttpError(\n `POST ${url} failed: ${response.status} ${response.statusText ?? \"\"}`,\n {\n status: response.status,\n statusText: response.statusText ?? \"\",\n data: errorData,\n url\n }\n );\n \n throw error;\n }\n\n await handleStreamingResponse(response);\n })\n .catch(err => {\n debugLogger.error('GatewayService chat fetch error', {\n error: err,\n url,\n provider: request.provider\n });\n observer.error(err);\n });\n };\n\n sendRequest(endpoint, true);\n\n // Teardown: abort the request/stream on unsubscribe\n return () => {\n try { controller.abort(); } catch {}\n };\n });\n }\n\n /**\n * Text generation using the gateway API\n */\n generate(request: GatewayGenerateRequest): Observable<GatewayGenerateResponse> {\n // Use provider-specific endpoint if provider is specified\n const endpoint = request.provider ? `/api/${request.provider}/generate` : '/api/generate';\n const url = `${this._baseUrl}${endpoint}`;\n const normalizedModel =\n request.provider === 'bandit'\n ? (() => {\n const trimmed = (request.model ?? '').replace(/^bandit:/, '').trim();\n return trimmed !== '' ? trimmed : 'bandit-core-1';\n })()\n : request.model;\n \n debugLogger.debug(`Gateway generate request to ${url} with provider: ${request.provider || 'default'}`, {\n model: normalizedModel\n });\n \n return new Observable<GatewayGenerateResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: this._getHeaders(),\n body: JSON.stringify({ ...request, model: normalizedModel, stream: request.stream !== false }),\n });\n \n task.then(async (response) => {\n if (!response.ok) {\n // Handle error response properly with body parsing\n let errorText = '';\n let errorData: unknown = null;\n \n try {\n // First, try to read the response body\n errorText = await response.text();\n } catch (readError) {\n errorText = `Request failed with status ${response.status}`;\n }\n \n // Then, try to parse as JSON for better error info\n try {\n errorData = JSON.parse(errorText);\n } catch (parseError) {\n errorData = { message: errorText };\n }\n \n // Create an error object that mimics an HTTP response error for the notification service\n const error = this._createHttpError(\n `POST ${url} failed: ${response.status} ${response.statusText ?? \"\"}`,\n {\n status: response.status,\n statusText: response.statusText ?? \"\",\n data: errorData,\n url\n }\n );\n \n throw error;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n \n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n if (buffer.trim() !== \"\") {\n try {\n observer.next(JSON.parse(buffer));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Final chunk parsing error (gateway generate):', { buffer });\n }\n }\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n observer.next(JSON.parse(line));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Error parsing JSON line (gateway generate):', { line });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n })\n .catch(err => observer.error(err));\n });\n }\n\n /**\n * List all available models from all providers\n */\n listModels(): Observable<GatewayModel[]> {\n const url = `${this._baseUrl}/api/models`;\n const response = this._get<GatewayModelsResponse>(url);\n const result = response.pipe(\n map(data => data.models),\n shareReplay(1)\n );\n return result;\n }\n\n /**\n * List models for a specific provider\n */\n listModelsByProvider(provider: string): Observable<GatewayModel[]> {\n const url = `${this._baseUrl}/api/models/${provider}`;\n const response = this._get<GatewayModelsResponse>(url);\n const result = response.pipe(\n map(data => data.models),\n shareReplay(1)\n );\n return result;\n }\n\n getMemory(): Observable<GatewayMemoryResponse> {\n const url = `${this._baseUrl}/api/memory`;\n return this._get<GatewayMemoryResponse>(url);\n }\n\n private _get<T>(url: string, responseType: 'json' | 'text' = 'json'): Observable<T> {\n const request = this._client.get<T>(url, { responseType });\n return from(request).pipe(\n map(response => response.data as T),\n shareReplay(1)\n );\n }\n\n private _post<TRequest, TResponse>(url: string, body: TRequest): Observable<TResponse> {\n const request = this._client.post<TResponse>(url, body);\n return from(request).pipe(\n map(response => response.data),\n shareReplay(1)\n );\n }\n\n private _getHeaders() {\n const rawToken = this._tokenFactory();\n const headers: { [key: string]: string } = {\n 'Content-Type': 'application/json'\n };\n\n if (!rawToken) {\n debugLogger.warn('GatewayService: No token found, skipping Authorization header');\n return headers;\n }\n\n const token = rawToken.trim();\n if (token === '') {\n debugLogger.warn('GatewayService: Token factory returned empty string');\n return headers;\n }\n\n if (/^(Bearer|ApiKey)\\s+/i.test(token)) {\n headers['Authorization'] = token;\n debugLogger.debug('GatewayService: Authorization header set with explicit scheme');\n return headers;\n }\n\n if (this._isLikelyBanditApiKey(token)) {\n headers['Authorization'] = `ApiKey ${token}`;\n headers['X-Burtson-Api-Key'] = token;\n debugLogger.debug('GatewayService: Authorization header set using API key');\n return headers;\n }\n\n if (this._isLikelyJwt(token)) {\n headers['Authorization'] = `Bearer ${token}`;\n debugLogger.debug('GatewayService: Authorization header set using bearer token');\n return headers;\n }\n\n // Default to bearer scheme to avoid breaking other providers\n headers['Authorization'] = `Bearer ${token}`;\n debugLogger.debug('GatewayService: Authorization header defaulted to bearer scheme');\n return headers;\n }\n\n private _isLikelyJwt(token: string): boolean {\n const segments = token.split('.');\n return segments.length === 3 && segments.every((segment) => segment.length > 0);\n }\n\n private _isLikelyBanditApiKey(value: string): boolean {\n return /^bai_[a-z0-9]{10,}$/i.test(value);\n }\n\n /**\n * Submit feedback to the gateway API\n */\n submitFeedback(feedback: FeedbackRequest): Observable<FeedbackResponse> {\n const url = `${this._baseUrl}/api/feedback`;\n \n debugLogger.debug('Gateway feedback submission', {\n category: feedback.category,\n priority: feedback.priority,\n hasImages: !!(feedback.images && feedback.images.length > 0),\n hasAttachments: !!(feedback.attachments && feedback.attachments.length > 0)\n });\n\n return from(\n this._client.post<FeedbackResponse>(url, feedback).then(response => response.data)\n ).pipe(\n catchError(error => {\n debugLogger.error('Feedback submission failed, using email fallback', error);\n\n const fallbackResponse: FeedbackResponse = {\n id: `fallback-${Date.now()}`,\n status: 'submitted',\n message: 'Feedback submission failed. Opening email client as fallback.',\n mailtoUrl: this._generateMailtoUrl(feedback)\n };\n return of(fallbackResponse);\n })\n );\n }\n\n /**\n * Generate a mailto URL as fallback for feedback submission\n */\n private _generateMailtoUrl(feedback: FeedbackRequest): string {\n const subject = encodeURIComponent(`[${feedback.category.toUpperCase()}] ${feedback.title}`);\n \n let body = `Category: ${feedback.category}\\n`;\n body += `Priority: ${feedback.priority}\\n`;\n \n if (feedback.annoyanceLevel) {\n const annoyanceLabels = {\n 1: '😊 Not annoying at all',\n 2: '😐 Slightly annoying',\n 3: '🙄 Moderately annoying', \n 4: '😠 Very annoying',\n 5: '🤬 Extremely annoying'\n };\n body += `Annoyance Level: ${feedback.annoyanceLevel}/5 - ${annoyanceLabels[feedback.annoyanceLevel as keyof typeof annoyanceLabels]}\\n`;\n }\n \n body += `\\nDescription:\\n${feedback.description}\\n\\n`;\n \n if (feedback.sessionInfo) {\n body += `Session Info:\\n`;\n body += `- Model: ${feedback.sessionInfo.currentModel}\\n`;\n body += `- Provider: ${feedback.sessionInfo.currentProvider}\\n`;\n body += `- Conversation: ${feedback.sessionInfo.conversationId}\\n`;\n body += `- Timestamp: ${feedback.sessionInfo.timestamp}\\n\\n`;\n }\n \n if (feedback.browserInfo) {\n body += `Browser Info:\\n`;\n body += `- Name: ${feedback.browserInfo.name}\\n`;\n body += `- Version: ${feedback.browserInfo.version}\\n`;\n body += `- Platform: ${feedback.browserInfo.platform}\\n\\n`;\n }\n \n if (feedback.userAgent) {\n body += `User Agent: ${feedback.userAgent}\\n\\n`;\n }\n \n if (feedback.contactEmail) {\n body += `Contact Email: ${feedback.contactEmail}\\n\\n`;\n }\n \n if (feedback.images && feedback.images.length > 0) {\n body += `📎 IMAGE ATTACHMENT:\\n`;\n body += `Please paste your clipboard contents here (Ctrl+V or Cmd+V)\\n\\n`;\n }\n \n if (feedback.attachments && feedback.attachments.length > 0) {\n body += `📎 IMPORTANT - FILES TO ATTACH:\\n`;\n body += `Please attach the following ${feedback.attachments.length} file(s) to this email:\\n`;\n feedback.attachments.forEach((attachment, index) => {\n body += ` • File ${index + 1}: ${attachment.name || `[Attachment ${index + 1}]`}\\n`;\n });\n body += `\\n(Note: Files cannot be automatically included in email links)\\n\\n`;\n }\n \n body += `---\\nGenerated by Bandit AI Feedback System`;\n \n const encodedBody = encodeURIComponent(body);\n const toEmail = this._feedbackEmail || 'feedback@burtson.ai'; // Use custom email or default\n \n return `mailto:${toEmail}?subject=${subject}&body=${encodedBody}`;\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-1D46-424011\nconst __banditFingerprint_gateway_openaigatewayservicets = 'BL-FP-DEEDDF-C675';\nconst __auditTrail_gateway_openaigatewayservicets = 'BL-AU-MGOIKVVU-ZD2R';\n// File: openai-gateway.service.ts | Path: src/services/gateway/openai-gateway.service.ts | Hash: 1d46c675\n\nimport { GatewayService } from './gateway.service';\nimport { GatewayChatRequest, GatewayChatResponse, GatewayGenerateRequest, GatewayGenerateResponse, GatewayModel } from './interfaces';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface OpenAIMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n name?: string;\n}\n\nexport interface OpenAIChatRequest {\n model: string;\n messages: OpenAIMessage[];\n stream?: boolean;\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n stop?: string | string[];\n}\n\nexport class OpenAIGatewayService {\n private _gatewayService: GatewayService;\n\n constructor(\n gatewayUrl: string,\n tokenFactory: () => string | null\n ) {\n this._gatewayService = new GatewayService(gatewayUrl, tokenFactory);\n debugLogger.info('OpenAIGatewayService initialized', { gatewayUrl });\n }\n\n /**\n * Validates the availability of the gateway service for OpenAI\n */\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n return this._gatewayService.validateServiceAvailability(args);\n }\n\n /**\n * Chat completion using OpenAI through the gateway\n */\n chat(request: OpenAIChatRequest): Observable<GatewayChatResponse> {\n const gatewayRequest: GatewayChatRequest = {\n ...request,\n provider: 'openai'\n };\n\n debugLogger.debug('OpenAI Gateway chat request', { \n model: request.model, \n messageCount: request.messages.length,\n stream: request.stream \n });\n\n return this._gatewayService.chat(gatewayRequest);\n }\n\n /**\n * Text completion using OpenAI through the gateway\n */\n complete(prompt: string, options: {\n model: string;\n temperature?: number;\n max_tokens?: number;\n stream?: boolean;\n stop?: string | string[];\n }): Observable<GatewayGenerateResponse> {\n const gatewayRequest: GatewayGenerateRequest = {\n model: options.model,\n prompt,\n temperature: options.temperature,\n max_tokens: options.max_tokens,\n stream: options.stream,\n stop: options.stop,\n provider: 'openai'\n };\n\n debugLogger.debug('OpenAI Gateway completion request', { \n model: options.model, \n promptLength: prompt.length,\n stream: options.stream \n });\n\n return this._gatewayService.generate(gatewayRequest);\n }\n\n /**\n * List available OpenAI models through the gateway\n */\n listModels(): Observable<GatewayModel[]> {\n debugLogger.debug('Fetching OpenAI models through gateway');\n return this._gatewayService.listModelsByProvider('openai');\n }\n\n /**\n * Get gateway health with OpenAI provider status\n */\n getHealth() {\n return this._gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n openai_status: health.providers.find(p => p.name === 'openai')?.status || 'unavailable'\n }))\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-9B34-38B0E8\nconst __banditFingerprint_gateway_azureopenaigatewayservicets = 'BL-FP-4A759E-00DC';\nconst __auditTrail_gateway_azureopenaigatewayservicets = 'BL-AU-MGOIKVVT-GARS';\n// File: azure-openai-gateway.service.ts | Path: src/services/gateway/azure-openai-gateway.service.ts | Hash: 9b3400dc\n\nimport { GatewayService } from './gateway.service';\nimport { GatewayChatRequest, GatewayChatResponse, GatewayGenerateRequest, GatewayGenerateResponse, GatewayModel } from './interfaces';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface AzureOpenAIMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n name?: string;\n}\n\nexport interface AzureOpenAIChatRequest {\n model: string; // This will be the deployment name for Azure\n messages: AzureOpenAIMessage[];\n stream?: boolean;\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n stop?: string | string[];\n}\n\nexport interface AzureOpenAIConfig {\n deploymentName: string;\n apiVersion: string;\n resourceName?: string; // For endpoint construction if needed\n}\n\nexport class AzureOpenAIGatewayService {\n private _gatewayService: GatewayService;\n private _azureConfig: AzureOpenAIConfig;\n\n constructor(\n gatewayUrl: string,\n tokenFactory: () => string | null,\n azureConfig: AzureOpenAIConfig\n ) {\n this._gatewayService = new GatewayService(gatewayUrl, tokenFactory);\n this._azureConfig = azureConfig;\n debugLogger.info('AzureOpenAIGatewayService initialized', { \n gatewayUrl, \n deploymentName: azureConfig.deploymentName,\n apiVersion: azureConfig.apiVersion \n });\n }\n\n /**\n * Validates the availability of the gateway service for Azure OpenAI\n */\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n return this._gatewayService.validateServiceAvailability(args);\n }\n\n /**\n * Chat completion using Azure OpenAI through the gateway\n */\n chat(request: AzureOpenAIChatRequest): Observable<GatewayChatResponse> {\n const gatewayRequest: GatewayChatRequest = {\n ...request,\n model: this._azureConfig.deploymentName, // Use deployment name as model\n provider: 'azure-openai'\n };\n\n debugLogger.debug('Azure OpenAI Gateway chat request', { \n deploymentName: this._azureConfig.deploymentName,\n apiVersion: this._azureConfig.apiVersion,\n messageCount: request.messages.length,\n stream: request.stream \n });\n\n return this._gatewayService.chat(gatewayRequest);\n }\n\n /**\n * Text completion using Azure OpenAI through the gateway\n */\n complete(prompt: string, options: {\n model?: string; // Optional override for deployment name\n temperature?: number;\n max_tokens?: number;\n stream?: boolean;\n stop?: string | string[];\n }): Observable<GatewayGenerateResponse> {\n const gatewayRequest: GatewayGenerateRequest = {\n model: options.model || this._azureConfig.deploymentName,\n prompt,\n temperature: options.temperature,\n max_tokens: options.max_tokens,\n stream: options.stream,\n stop: options.stop,\n provider: 'azure-openai'\n };\n\n debugLogger.debug('Azure OpenAI Gateway completion request', { \n deploymentName: options.model || this._azureConfig.deploymentName,\n promptLength: prompt.length,\n stream: options.stream \n });\n\n return this._gatewayService.generate(gatewayRequest);\n }\n\n /**\n * List available Azure OpenAI models through the gateway\n */\n listModels(): Observable<GatewayModel[]> {\n debugLogger.debug('Fetching Azure OpenAI models through gateway');\n return this._gatewayService.listModelsByProvider('azure-openai');\n }\n\n /**\n * Get gateway health with Azure OpenAI provider status\n */\n getHealth() {\n return this._gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n azure_openai_status: health.providers.find(p => p.name === 'azure-openai')?.status || 'unavailable',\n azure_config: {\n deploymentName: this._azureConfig.deploymentName,\n apiVersion: this._azureConfig.apiVersion\n }\n }))\n );\n }\n\n /**\n * Update Azure configuration\n */\n updateAzureConfig(newConfig: Partial<AzureOpenAIConfig>) {\n this._azureConfig = { ...this._azureConfig, ...newConfig };\n debugLogger.info('Azure OpenAI configuration updated', this._azureConfig);\n }\n\n /**\n * Get current Azure configuration\n */\n getAzureConfig(): AzureOpenAIConfig {\n return { ...this._azureConfig };\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-8264-DAEB3A\nconst __banditFingerprint_gateway_anthropicgatewayservicets = 'BL-FP-CA4EB6-817C';\nconst __auditTrail_gateway_anthropicgatewayservicets = 'BL-AU-MGOIKVVS-X7J4';\n// File: anthropic-gateway.service.ts | Path: src/services/gateway/anthropic-gateway.service.ts | Hash: 8264817c\n\nimport { GatewayService } from './gateway.service';\nimport { GatewayChatRequest, GatewayChatResponse, GatewayGenerateRequest, GatewayGenerateResponse, GatewayModel } from './interfaces';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface AnthropicMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n name?: string;\n}\n\nexport interface AnthropicChatRequest {\n model: string;\n messages: AnthropicMessage[];\n stream?: boolean;\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n stop_sequences?: string[];\n system?: string; // Anthropic uses separate system parameter\n}\n\nexport class AnthropicGatewayService {\n private _gatewayService: GatewayService;\n\n constructor(\n gatewayUrl: string,\n tokenFactory: () => string | null\n ) {\n this._gatewayService = new GatewayService(gatewayUrl, tokenFactory);\n debugLogger.info('AnthropicGatewayService initialized', { gatewayUrl });\n }\n\n /**\n * Validates the availability of the gateway service for Anthropic\n */\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n return this._gatewayService.validateServiceAvailability(args);\n }\n\n /**\n * Chat completion using Anthropic through the gateway\n */\n chat(request: AnthropicChatRequest): Observable<GatewayChatResponse> {\n // Convert Anthropic-specific request to gateway format\n const gatewayRequest: GatewayChatRequest = {\n model: request.model,\n messages: request.messages,\n stream: request.stream,\n temperature: request.temperature,\n max_tokens: request.max_tokens,\n top_p: request.top_p,\n stop: request.stop_sequences,\n provider: 'anthropic'\n };\n\n debugLogger.debug('Anthropic Gateway chat request', { \n model: request.model, \n messageCount: request.messages.length,\n stream: request.stream,\n hasSystem: !!request.system\n });\n\n return this._gatewayService.chat(gatewayRequest);\n }\n\n /**\n * Text completion using Anthropic through the gateway\n */\n complete(prompt: string, options: {\n model: string;\n temperature?: number;\n max_tokens?: number;\n stream?: boolean;\n stop_sequences?: string[];\n system?: string;\n }): Observable<GatewayGenerateResponse> {\n const gatewayRequest: GatewayGenerateRequest = {\n model: options.model,\n prompt,\n temperature: options.temperature,\n max_tokens: options.max_tokens,\n stream: options.stream,\n stop: options.stop_sequences,\n provider: 'anthropic'\n };\n\n debugLogger.debug('Anthropic Gateway completion request', { \n model: options.model, \n promptLength: prompt.length,\n stream: options.stream,\n hasSystem: !!options.system\n });\n\n return this._gatewayService.generate(gatewayRequest);\n }\n\n /**\n * List available Anthropic models through the gateway\n */\n listModels(): Observable<GatewayModel[]> {\n debugLogger.debug('Fetching Anthropic models through gateway');\n return this._gatewayService.listModelsByProvider('anthropic');\n }\n\n /**\n * Get gateway health with Anthropic provider status\n */\n getHealth() {\n return this._gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n anthropic_status: health.providers.find(p => p.name === 'anthropic')?.status || 'unavailable'\n }))\n );\n }\n\n /**\n * Helper method to convert system message to Anthropic format\n * Anthropic treats system messages differently - they can be separate from messages\n */\n private extractSystemMessage(messages: AnthropicMessage[]): { messages: AnthropicMessage[], system?: string } {\n const systemMessage = messages.find(msg => msg.role === 'system');\n const userMessages = messages.filter(msg => msg.role !== 'system');\n \n return {\n messages: userMessages,\n system: systemMessage?.content\n };\n }\n\n /**\n * Enhanced chat method that handles Anthropic's system message format\n */\n chatWithSystem(request: AnthropicChatRequest): Observable<GatewayChatResponse> {\n const { messages, system } = this.extractSystemMessage(request.messages);\n \n const enhancedRequest: AnthropicChatRequest = {\n ...request,\n messages,\n system: system || request.system\n };\n\n return this.chat(enhancedRequest);\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-76E6-8DEDE6\nconst __banditFingerprint_gateway_ollamagatewayservicets = 'BL-FP-124FB6-97C7';\nconst __auditTrail_gateway_ollamagatewayservicets = 'BL-AU-MGOIKVVU-PU6T';\n// File: ollama-gateway.service.ts | Path: src/services/gateway/ollama-gateway.service.ts | Hash: 76e697c7\n\nimport { GatewayService } from './gateway.service';\nimport { GatewayChatRequest, GatewayChatResponse, GatewayGenerateRequest, GatewayGenerateResponse, GatewayModel } from './interfaces';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface OllamaMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n images?: string[]; // Ollama supports image inputs\n}\n\nexport interface OllamaChatRequest {\n model: string;\n messages: OllamaMessage[];\n stream?: boolean;\n options?: Record<string, unknown>;\n images?: string[];\n}\n\nexport interface OllamaGenerateRequest {\n model: string;\n prompt: string;\n stream?: boolean;\n images?: string[];\n options?: Record<string, unknown>;\n}\n\nexport class OllamaGatewayService {\n private _gatewayService: GatewayService;\n\n constructor(\n gatewayUrl: string,\n tokenFactory: () => string | null\n ) {\n this._gatewayService = new GatewayService(gatewayUrl, tokenFactory);\n debugLogger.info('OllamaGatewayService initialized', { gatewayUrl });\n }\n\n /**\n * Validates the availability of the gateway service for Ollama\n */\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n return this._gatewayService.validateServiceAvailability(args);\n }\n\n /**\n * Chat completion using Ollama through the gateway\n */\n chat(request: OllamaChatRequest): Observable<GatewayChatResponse> {\n const gatewayRequest: GatewayChatRequest = {\n ...request,\n provider: 'ollama'\n };\n\n debugLogger.debug('Ollama Gateway chat request', { \n model: request.model, \n messageCount: request.messages.length,\n stream: request.stream,\n hasImages: !!(request.images && request.images.length > 0)\n });\n\n return this._gatewayService.chat(gatewayRequest);\n }\n\n /**\n * Text generation using Ollama through the gateway\n */\n generate(request: OllamaGenerateRequest): Observable<GatewayGenerateResponse> {\n const gatewayRequest: GatewayGenerateRequest = {\n ...request,\n provider: 'ollama'\n };\n\n debugLogger.debug('Ollama Gateway generate request', { \n model: request.model, \n promptLength: request.prompt.length,\n stream: request.stream,\n hasImages: !!(request.images && request.images.length > 0)\n });\n\n return this._gatewayService.generate(gatewayRequest);\n }\n\n /**\n * List available Ollama models through the gateway\n */\n listModels(): Observable<GatewayModel[]> {\n debugLogger.debug('Fetching Ollama models through gateway');\n return this._gatewayService.listModelsByProvider('ollama');\n }\n\n /**\n * Get gateway health with Ollama provider status\n */\n getHealth() {\n return this._gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n ollama_status: health.providers.find(p => p.name === 'ollama')?.status || 'unavailable'\n }))\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-5C48-8D1103\nconst __banditFingerprint_gateway_banditgatewayservicets = 'BL-FP-37A8F1-0E5B';\nconst __auditTrail_gateway_banditgatewayservicets = 'BL-AU-MGOIKVVS-DH4W';\n// File: bandit-gateway.service.ts | Path: src/services/gateway/bandit-gateway.service.ts | Hash: 5c488d11\n\nimport { GatewayService } from './gateway.service';\nimport {\n GatewayChatRequest,\n GatewayChatResponse,\n GatewayGenerateRequest,\n GatewayGenerateResponse,\n GatewayMessage,\n GatewayMessageContent,\n GatewayModel\n} from './interfaces';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface BanditAIChatRequest {\n model: string;\n messages: Array<{ role: 'system' | 'user' | 'assistant'; content: unknown }>;\n stream?: boolean;\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n stop?: string | string[];\n}\n\nconst normalizeBanditModel = (model: string | undefined): string => {\n if (typeof model !== 'string' || model.trim() === '') {\n return 'bandit-core-1';\n }\n const normalized = model.replace(/^bandit:/, '').trim();\n return normalized === '' ? 'bandit-core-1' : normalized;\n};\n\nconst isGatewayMessageContent = (value: unknown): value is GatewayMessageContent => {\n if (!value || typeof value !== 'object') return false;\n const candidate = value as GatewayMessageContent;\n if (candidate.type !== 'text' && candidate.type !== 'image_url') {\n return false;\n }\n if (candidate.type === 'text') {\n return typeof candidate.text === 'string';\n }\n if (candidate.type === 'image_url') {\n return !!candidate.image_url && typeof candidate.image_url.url === 'string';\n }\n return false;\n};\n\nconst normalizeBanditMessages = (\n messages: Array<{ role: 'system' | 'user' | 'assistant'; content: unknown }>\n): GatewayMessage[] =>\n messages.map((message) => {\n const content = message.content;\n if (typeof content === 'string') {\n return { role: message.role, content };\n }\n if (Array.isArray(content)) {\n const filtered = content.filter(isGatewayMessageContent);\n if (filtered.length === 0) {\n return { role: message.role, content: JSON.stringify(content) };\n }\n return {\n role: message.role,\n content: filtered\n };\n }\n return { role: message.role, content: content != null ? String(content) : '' };\n });\n\nexport class BanditAIGatewayService {\n private _gatewayService: GatewayService;\n\n constructor(\n gatewayUrl: string,\n tokenFactory: () => string | null\n ) {\n this._gatewayService = new GatewayService(gatewayUrl, tokenFactory);\n debugLogger.info('BanditAIGatewayService initialized', { gatewayUrl });\n }\n\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string; isAvailable: boolean }> {\n return this._gatewayService.validateServiceAvailability(args);\n }\n\n chat(request: BanditAIChatRequest): Observable<GatewayChatResponse> {\n const model = normalizeBanditModel(request.model);\n const messages = normalizeBanditMessages(request.messages);\n const gatewayRequest: GatewayChatRequest = {\n ...request,\n messages,\n model,\n provider: 'bandit',\n stream: request.stream\n };\n\n debugLogger.debug('Bandit Gateway chat request', {\n model,\n messageCount: request.messages.length,\n stream: request.stream\n });\n\n return this._gatewayService.chat(gatewayRequest);\n }\n\n complete(prompt: string, options: {\n model: string;\n temperature?: number;\n max_tokens?: number;\n stream?: boolean;\n stop?: string | string[];\n }): Observable<GatewayGenerateResponse> {\n const model = normalizeBanditModel(options.model);\n const gatewayRequest: GatewayGenerateRequest = {\n model,\n prompt,\n temperature: options.temperature,\n max_tokens: options.max_tokens,\n stream: options.stream,\n stop: options.stop,\n provider: 'bandit'\n };\n\n debugLogger.debug('Bandit Gateway generate request', {\n model,\n promptLength: prompt.length,\n stream: options.stream\n });\n\n return this._gatewayService.generate(gatewayRequest);\n }\n\n listModels(): Observable<GatewayModel[]> {\n debugLogger.debug('Fetching Bandit models through gateway');\n return this._gatewayService.listModelsByProvider('bandit');\n }\n\n getHealth() {\n return this._gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n bandit_status: health.providers.find(p => p.name === 'bandit')?.status || 'unavailable'\n }))\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-0C91-217979\nconst __banditFingerprint_providers_gatewayproviderts = 'BL-FP-4F2F4F-2A21';\nconst __auditTrail_providers_gatewayproviderts = 'BL-AU-MGOIKVVQ-MHFK';\n// File: gateway.provider.ts | Path: src/services/ai-provider/providers/gateway.provider.ts | Hash: 0c912a21\n\nimport { Observable, map } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\nimport { GatewayService } from '../../gateway/gateway.service';\nimport { OpenAIGatewayService } from '../../gateway/openai-gateway.service';\nimport { AzureOpenAIGatewayService } from '../../gateway/azure-openai-gateway.service';\nimport { AnthropicGatewayService } from '../../gateway/anthropic-gateway.service';\nimport { OllamaGatewayService } from '../../gateway/ollama-gateway.service';\nimport { BanditAIGatewayService } from '../../gateway/bandit-gateway.service';\nimport {\n GatewayChatRequest,\n GatewayMessage,\n GatewayMessageContent,\n GatewayTool\n} from '../../gateway/interfaces';\n\n/**\n * Gateway provider implementation that routes requests through the .NET gateway API\n * This consolidates all AI provider logic behind a single gateway endpoint\n */\nexport class GatewayProvider implements IAIProvider {\n private config: AIProviderConfig;\n private gatewayService: GatewayService;\n private providerSpecificService: OpenAIGatewayService | AzureOpenAIGatewayService | AnthropicGatewayService | OllamaGatewayService | BanditAIGatewayService | null = null;\n\n constructor(config: AIProviderConfig) {\n this.config = config;\n \n if (!config.gatewayUrl) {\n throw new Error('Gateway provider requires gatewayUrl in config');\n }\n \n if (!config.provider) {\n throw new Error('Gateway provider requires provider field to specify backend (openai, azure-openai, anthropic, ollama)');\n }\n\n const tokenFactory = config.tokenFactory || (() => null);\n this.gatewayService = new GatewayService(config.gatewayUrl, tokenFactory);\n\n // Create provider-specific service for enhanced functionality\n this.createProviderSpecificService(config.gatewayUrl, tokenFactory);\n\n debugLogger.info('GatewayProvider initialized', { \n gatewayUrl: config.gatewayUrl,\n backendProvider: config.provider\n });\n }\n\n private createProviderSpecificService(gatewayUrl: string, tokenFactory: () => string | null) {\n switch (this.config.provider) {\n case 'openai':\n this.providerSpecificService = new OpenAIGatewayService(gatewayUrl, tokenFactory);\n break;\n case 'azure-openai':\n if (!this.config.deploymentName || !this.config.apiVersion) {\n throw new Error('Azure OpenAI gateway provider requires deploymentName and apiVersion');\n }\n this.providerSpecificService = new AzureOpenAIGatewayService(\n gatewayUrl, \n tokenFactory,\n {\n deploymentName: this.config.deploymentName,\n apiVersion: this.config.apiVersion\n }\n );\n break;\n case 'anthropic':\n this.providerSpecificService = new AnthropicGatewayService(gatewayUrl, tokenFactory);\n break;\n case 'bandit':\n this.providerSpecificService = new BanditAIGatewayService(gatewayUrl, tokenFactory);\n break;\n case 'ollama':\n this.providerSpecificService = new OllamaGatewayService(gatewayUrl, tokenFactory);\n break;\n case 'playground':\n // Preview gateway uses custom routing; no provider-specific service\n this.providerSpecificService = null;\n break;\n default:\n debugLogger.warn('Unknown provider for gateway, using generic gateway service', { \n provider: this.config.provider \n });\n }\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n // Convert AI request to standardized gateway request format\n // The gateway API will handle provider-specific transformations\n \n const messages: GatewayMessage[] = request.messages.map(msg => ({\n role: msg.role,\n content: msg.content\n }));\n \n // Handle images based on provider type\n const normalizeImageUrl = (value: string) => {\n if (!value) {\n return value;\n }\n const trimmed = value.trim();\n if (/^data:/i.test(trimmed) || /^https?:\\/\\//i.test(trimmed)) {\n return trimmed;\n }\n return `data:image/jpeg;base64,${trimmed}`;\n };\n\n if (request.images && request.images.length > 0) {\n const lastUserMessageIndex = messages.map(m => m.role).lastIndexOf('user');\n\n if (this.config.provider === 'ollama') {\n // Ollama: attach images directly to the last user message\n if (lastUserMessageIndex !== -1) {\n messages[lastUserMessageIndex] = {\n ...messages[lastUserMessageIndex],\n images: request.images\n };\n }\n } else if (['openai', 'azure-openai', 'anthropic', 'bandit', 'playground'].includes(this.config.provider || '')) {\n // OpenAI/Azure/Anthropic: convert to structured content format\n if (lastUserMessageIndex !== -1) {\n const currentMessage = messages[lastUserMessageIndex];\n const contentArray: GatewayMessageContent[] = [\n {\n type: 'text',\n text: currentMessage.content as string\n }\n ];\n\n // Add images as image_url content\n request.images.forEach(imageRef => {\n contentArray.push({\n type: 'image_url',\n image_url: {\n url: normalizeImageUrl(imageRef),\n detail: 'auto'\n }\n });\n });\n\n messages[lastUserMessageIndex] = {\n ...messages[lastUserMessageIndex],\n content: contentArray\n };\n debugLogger.debug('Gateway provider injected image attachments', {\n provider: this.config.provider,\n imageCount: request.images.length,\n messageIndex: lastUserMessageIndex\n });\n }\n }\n }\n \n const toolAwareRequest = request as AIChatRequest & { tools?: GatewayTool[] };\n\n const gatewayRequest: GatewayChatRequest = {\n model: request.model,\n messages,\n stream: request.stream,\n temperature: request.temperature,\n max_tokens: request.maxTokens,\n provider: this.config.provider,\n // Only include top-level images for Ollama (fallback)\n images: this.config.provider === 'ollama' ? request.images : undefined,\n tools: toolAwareRequest.tools?.length ? toolAwareRequest.tools : undefined\n };\n\n debugLogger.debug('Gateway provider chat request', { \n model: request.model,\n provider: this.config.provider,\n messageCount: request.messages.length,\n stream: request.stream,\n hasImages: !!(request.images && request.images.length > 0),\n imageCount: request.images?.length || 0,\n imageStrategy: this.config.provider === 'ollama' \n ? 'message-level-array' \n : ['openai', 'azure-openai', 'anthropic', 'playground'].includes(this.config.provider || '')\n ? 'structured-content'\n : 'top-level-fallback',\n finalMessages: messages.map(m => ({ \n role: m.role, \n hasImages: Array.isArray(m.images) && m.images.length > 0,\n contentType: Array.isArray(m.content) ? 'structured' : 'text'\n }))\n });\n\n return this.gatewayService.chat(gatewayRequest).pipe(\n map(response => {\n const choice = response.choices?.[0];\n const toolCalls = choice?.message?.tool_calls ?? choice?.delta?.tool_calls;\n return {\n message: {\n content: choice?.message?.content ?? choice?.delta?.content ?? '',\n role: 'assistant' as const,\n tool_calls: toolCalls\n },\n done: choice?.finish_reason === 'stop' || choice?.finish_reason === 'length' || choice?.finish_reason === 'tool_calls'\n };\n })\n );\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n const gatewayRequest = {\n model: request.model,\n prompt: request.prompt,\n stream: request.stream,\n provider: this.config.provider\n };\n\n debugLogger.debug('Gateway provider generate request', { \n model: request.model,\n provider: this.config.provider,\n promptLength: request.prompt.length,\n stream: request.stream \n });\n\n return this.gatewayService.generate(gatewayRequest).pipe(\n map(response => ({\n response: response.response || '',\n done: response.done || false\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n debugLogger.debug('Gateway provider listing models', { provider: this.config.provider });\n \n if (this.config.provider) {\n return this.gatewayService.listModelsByProvider(this.config.provider).pipe(\n map(models => models.map(model => ({\n name: model.id || model.name,\n size: model.size,\n details: model.details,\n digest: model.digest,\n modified_at: model.modified_at\n })))\n );\n } else {\n // List all models from all providers\n return this.gatewayService.listModels().pipe(\n map(models => models.map(model => ({\n name: model.id || model.name,\n size: model.size,\n details: model.details,\n digest: model.digest,\n modified_at: model.modified_at\n })))\n );\n }\n }\n\n async validateServiceAvailability(args: { \n fallbackUrl?: string; \n timeoutMs: number; \n }): Promise<{ url: string; isAvailable: boolean }> {\n debugLogger.debug('Gateway provider validating service availability');\n return this.gatewayService.validateServiceAvailability(args);\n }\n\n getProviderType(): string {\n return AIProviderType.GATEWAY;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n /**\n * Get the backend provider type\n */\n getBackendProvider(): string | undefined {\n return this.config.provider;\n }\n\n /**\n * Get gateway health including backend provider status\n */\n getHealth() {\n return this.gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n backend_provider: this.config.provider,\n backend_provider_status: health.providers.find(p => p.name === this.config.provider)?.status || 'unavailable'\n }))\n );\n }\n\n /**\n * Use provider-specific service if available for enhanced functionality\n */\n getProviderSpecificService(): OpenAIGatewayService | AzureOpenAIGatewayService | AnthropicGatewayService | OllamaGatewayService | BanditAIGatewayService | null {\n return this.providerSpecificService;\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-DBA3-6C3A2B\nconst __banditFingerprint_providers_playgroundproviderts = 'BL-FP-7465CF-7B8B';\nconst __auditTrail_providers_playgroundproviderts = 'BL-AU-MGOIKVVR-EV75';\n// File: playground.provider.ts | Path: src/services/ai-provider/providers/playground.provider.ts | Hash: dba37b8b\n\nimport { Observable } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\n\ntype PlaygroundScript = {\n match: (input: string) => boolean;\n response: string;\n};\n\nconst PLAYGROUND_MODELS: AIModel[] = [\n {\n name: 'bandit-playground',\n details: {\n format: 'chat',\n family: 'bandit',\n families: ['bandit', 'demo'],\n parameter_size: 'demo',\n quantization_level: 'synthetic'\n },\n digest: 'playground-demo-001',\n modified_at: new Date().toISOString()\n },\n {\n name: 'bandit-starter',\n details: {\n format: 'chat',\n family: 'bandit',\n families: ['bandit', 'demo'],\n parameter_size: 'demo',\n quantization_level: 'synthetic'\n },\n digest: 'playground-demo-002',\n modified_at: new Date().toISOString()\n }\n];\n\nconst PLAYGROUND_CONVERSATION_STARTERS = [\n 'What can I build with Bandit Engine if my backend is not ready yet?',\n 'How does the gateway contract keep API keys out of the browser?',\n 'Can I theme the chat UI to match my product brand?',\n 'How do I switch between Ollama and OpenAI without redeploying the frontend?',\n 'Show me how the management console handles personas and models.'\n];\n\nconst PLAYGROUND_SCRIPTS: PlaygroundScript[] = [\n {\n match: (input) => /model|switch|personas|management/i.test(input),\n response: [\n \"Absolutely — the management console ships with live model switching, persona editing, and feature toggles.\",\n \"\",\n \"- Use the **Models** tab to expose whichever gateway-backed models you want customers to see.\",\n \"- Personas hydrate the chat with branded system prompts, voice preferences, and avatars.\",\n \"- Everything persists through the gateway, so you can roll out changes without shipping a new build.\"\n ].join('\\n')\n },\n {\n match: (input) => /gateway|api|contract|backend/i.test(input),\n response: [\n \"The gateway contract keeps secrets on the server while giving the UI a unified AI API.\",\n \"\",\n \"Key highlights:\",\n \"1. `/api/chat/completions` is the default OpenAI-format endpoint when no provider override is set.\",\n \"2. `/api/{provider}/chat/completions` handles OpenAI, Azure OpenAI, and Anthropic while `/api/ollama/chat` streams Ollama responses.\",\n \"3. The contract is language-agnostic — Express, FastAPI, .NET, Go… anything works as long as it speaks HTTP.\"\n ].join('\\n')\n },\n {\n match: (input) => /style|theme|brand|ui/i.test(input),\n response: [\n \"Every surface in Bandit Engine is themeable.\",\n \"\",\n \"- Drop a JSON config into your `public/` folder (or host it on a CDN) to control themes, logos, and accent colors.\",\n \"- The React components expose hooks for custom headers, menus, and call-to-action buttons.\",\n \"- Need a modal? `ChatModal` reuses the same store, so the handoff between embedded chat and floating assistant stays seamless.\"\n ].join('\\n')\n },\n {\n match: (input) => /voice|tts|audio/i.test(input),\n response: [\n \"Voice is opt-in, but the plumbing is ready.\",\n \"\",\n \"- Configure `/api/tts` and `/api/stt` on the gateway to unlock the speak/listen controls.\",\n \"- The UI lazily loads voices and respects feature flags, so you can leave it disabled in the playground.\",\n \"- Everything streams — the assistant starts speaking before the full response lands.\"\n ].join('\\n')\n },\n {\n match: (input) => /deploy|production|secure/i.test(input),\n response: [\n \"Production hardening is front and center.\",\n \"\",\n \"- Gateway tokens ride in the `Authorization` header; rotate them server-side without touching the bundle.\",\n \"- Feature flags gate premium surfaces, letting you trial the UI before wiring billing.\",\n \"- Vector search, knowledge, and memories are isolated behind `/api/embedding/*` so you can plug in your own storage policies.\"\n ].join('\\n')\n }\n];\n\nconst FALLBACK_RESPONSE = [\n \"Bandit Engine is running in playground mode. I'm simulating how streaming works so you can explore the UX without connecting a live model.\",\n \"\",\n \"Try asking about the gateway contract, theming, voice features, or model management to see tailored walkthroughs.\"\n].join('\\n');\n\nconst STREAM_DELAY_MS = 350;\n\nexport class PlaygroundProvider implements IAIProvider {\n private config: AIProviderConfig;\n\n constructor(config: AIProviderConfig) {\n this.config = { type: AIProviderType.PLAYGROUND, ...config };\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const lastUserMessage = [...request.messages]\n .reverse()\n .find((m) => m.role === 'user')?.content ?? '';\n\n const script = PLAYGROUND_SCRIPTS.find((scenario) =>\n scenario.match(lastUserMessage)\n );\n\n const responseText = script?.response ?? FALLBACK_RESPONSE;\n const chunks = this.splitIntoChunks(responseText);\n\n return new Observable<AIChatResponse>((observer) => {\n let index = 0;\n const emitChunk = () => {\n if (index >= chunks.length) {\n observer.complete();\n return;\n }\n\n const chunk = chunks[index];\n observer.next({\n message: {\n content: chunk,\n role: 'assistant'\n },\n done: index === chunks.length - 1\n });\n\n index += 1;\n setTimeout(emitChunk, STREAM_DELAY_MS);\n };\n\n emitChunk();\n\n return () => {\n index = chunks.length;\n };\n });\n }\n\n generate(_request: AIGenerateRequest): Observable<AIGenerateResponse> {\n const starters = PLAYGROUND_CONVERSATION_STARTERS.join('\\n');\n\n return new Observable<AIGenerateResponse>((observer) => {\n observer.next({\n response: starters,\n done: true\n });\n observer.complete();\n });\n }\n\n listModels(): Observable<AIModel[]> {\n return new Observable<AIModel[]>((observer) => {\n observer.next(PLAYGROUND_MODELS);\n observer.complete();\n });\n }\n\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number }): Promise<{ url: string; isAvailable: boolean }> {\n const simulatedUrl = this.config.baseUrl ?? 'playground://local';\n\n if (args.timeoutMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(args.timeoutMs, 250)));\n }\n\n return {\n url: simulatedUrl,\n isAvailable: true\n };\n }\n\n getProviderType(): string {\n return AIProviderType.PLAYGROUND;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private splitIntoChunks(response: string): string[] {\n const paragraphs = response.split('\\n\\n').map((p) => p.trim()).filter(Boolean);\n\n if (paragraphs.length <= 1) {\n const sentences = response.split(/(?<=[.!?])\\s+/).filter(Boolean);\n return sentences.length > 0 ? sentences : [response];\n }\n\n return paragraphs;\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-16A2-8F5D0C\nconst __banditFingerprint_providers_xaiproviderts = 'BL-FP-DA7844-7C12';\nconst __auditTrail_providers_xaiproviderts = 'BL-AU-MGOIKVVR-W7UB';\n// File: xai.provider.ts | Path: src/services/ai-provider/providers/xai.provider.ts | Hash: 16a28f5d\n\nimport { Observable, from, switchMap, map, throwError } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\n\ninterface XAIChatPayload {\n model: string;\n messages: AIChatRequest['messages'];\n stream: boolean;\n temperature?: number;\n max_tokens?: number;\n}\n\ninterface XAIStreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n };\n }>;\n}\n\ninterface XAIChatResponsePayload {\n choices?: Array<{\n message?: {\n content?: string;\n };\n }>;\n}\n\ninterface XAIModelListResponse {\n data: Array<{\n id: string;\n object?: string;\n }>;\n}\n\n/**\n * xAI provider implementation\n */\nexport class XAIProvider implements IAIProvider {\n private config: AIProviderConfig;\n private baseUrl: string;\n\n constructor(config: AIProviderConfig) {\n this.config = config;\n this.baseUrl = config.baseUrl || 'https://api.x.ai/v1';\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const url = `${this.baseUrl}/chat/completions`;\n\n const payload: XAIChatPayload = {\n model: request.model,\n messages: request.messages,\n stream: Boolean(request.stream),\n temperature: request.temperature,\n max_tokens: request.maxTokens\n };\n\n if (request.stream) {\n return this.streamChatRequest(url, payload);\n } else {\n return this.nonStreamChatRequest(url, payload);\n }\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n const chatRequest: AIChatRequest = {\n model: request.model,\n messages: [{ role: 'user', content: request.prompt }],\n stream: request.stream,\n options: request.options\n };\n\n return this.chat(chatRequest).pipe(\n map(response => ({\n response: response.message.content,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n const url = `${this.baseUrl}/models`;\n\n return from(fetch(url, {\n headers: this.getHeaders()\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`Failed to list models: ${response.status}`));\n }\n return from(response.json() as Promise<XAIModelListResponse>);\n }),\n map((data) =>\n data.data.map((model) => ({\n name: model.id,\n details: {\n format: 'xai',\n family: model.object\n }\n }))\n )\n );\n }\n\n async validateServiceAvailability(args: {\n fallbackUrl?: string;\n timeoutMs: number;\n }): Promise<{ url: string; isAvailable: boolean }> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const response = await fetch(`${this.baseUrl}/models`, {\n headers: this.getHeaders(),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n return {\n url: this.baseUrl,\n isAvailable: response.ok\n };\n } catch (error) {\n if (args.fallbackUrl) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const response = await fetch(`${args.fallbackUrl}/models`, {\n headers: this.getHeaders(),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n this.baseUrl = args.fallbackUrl;\n return {\n url: args.fallbackUrl,\n isAvailable: true\n };\n }\n } catch (fallbackError) {\n debugLogger.warn('xAI fallback validation failed', { error: fallbackError });\n }\n }\n\n return {\n url: this.baseUrl,\n isAvailable: false\n };\n }\n }\n\n getProviderType(): string {\n return AIProviderType.XAI;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private streamChatRequest(url: string, payload: XAIChatPayload): Observable<AIChatResponse> {\n return new Observable<AIChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n task.then(response => {\n if (!response.ok) {\n observer.error(new Error(`xAI request failed: ${response.status}`));\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim() && line.startsWith('data: ')) {\n const data = line.slice(6).trim();\n if (data === '[DONE]') {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n try {\n const parsed = JSON.parse(data) as XAIStreamChunk;\n const content = parsed.choices?.[0]?.delta?.content ?? '';\n if (content) {\n observer.next({\n message: { content, role: 'assistant' },\n done: false\n });\n }\n } catch (err) {\n debugLogger.error('Error parsing xAI stream data:', { data, error: err });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n }).catch(err => observer.error(err));\n });\n }\n\n private nonStreamChatRequest(url: string, payload: XAIChatPayload): Observable<AIChatResponse> {\n return from(fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`xAI request failed: ${response.status}`));\n }\n return from(response.json() as Promise<XAIChatResponsePayload>);\n }),\n map((data) => ({\n message: {\n content: data.choices?.[0]?.message?.content ?? '',\n role: 'assistant' as const\n },\n done: true\n }))\n );\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n\n if (this.config.apiKey) {\n headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n }\n\n return headers;\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-7D56-94BC03\nconst __banditFingerprint_providers_banditai_providerts = 'BL-FP-0A9B76-CCF1';\nconst __auditTrail_providers_banditai_providerts = 'BL-AU-MGOIKVVS-LZU9';\n// File: bandit-ai.provider.ts | Path: src/services/ai-provider/providers/bandit-ai.provider.ts | Hash: 7d5694bc\n\nimport { Observable, from, switchMap, map, throwError } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\n\ninterface BanditAIChatPayload {\n model: string;\n messages: BanditAIMessage[];\n stream: boolean;\n temperature?: number;\n max_tokens?: number;\n}\n\ninterface BanditAIStreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n };\n finish_reason?: string | null;\n }>;\n}\n\ninterface BanditAINonStreamResponse {\n choices?: Array<{\n message?: {\n content?: string;\n };\n }>;\n}\n\ninterface BanditAIModelListResponse {\n data: Array<{\n id: string;\n object?: string;\n }>;\n}\n\nconst DEFAULT_BANDIT_BASE = 'https://api.burtson.ai';\n\ntype BanditAIMessageContent =\n | string\n | Array<\n | { type: 'text'; text: string }\n | { type: 'image_url'; image_url: { url: string; detail?: 'low' | 'high' | 'auto' } }\n >;\n\ninterface BanditAIMessage {\n role: 'system' | 'user' | 'assistant';\n content: BanditAIMessageContent;\n}\n\nconst normalizeImageUrl = (value: string | undefined): string | null => {\n if (!value) {\n return null;\n }\n const trimmed = value.trim();\n if (!trimmed) {\n return null;\n }\n if (/^data:/i.test(trimmed) || /^https?:\\/\\//i.test(trimmed)) {\n return trimmed;\n }\n return `data:image/jpeg;base64,${trimmed}`;\n};\n\nconst injectImagesIntoMessages = (\n messages: AIChatRequest['messages'],\n images: string[] | undefined\n): BanditAIMessage[] => {\n const normalized: BanditAIMessage[] = messages.map((message) => ({\n role: message.role,\n content: message.content,\n }));\n\n if (!images || images.length === 0) {\n return normalized;\n }\n\n const normalizedImages = images\n .map(normalizeImageUrl)\n .filter((url): url is string => Boolean(url));\n\n if (normalizedImages.length === 0) {\n return normalized;\n }\n\n const lastUserIndex = normalized.map((msg) => msg.role).lastIndexOf('user');\n if (lastUserIndex === -1) {\n return normalized;\n }\n\n const target = normalized[lastUserIndex];\n const baseContent =\n typeof target.content === 'string' && target.content.trim().length > 0\n ? [\n {\n type: 'text' as const,\n text: target.content,\n },\n ]\n : [];\n\n const imageContent = normalizedImages.map((url) => ({\n type: 'image_url' as const,\n image_url: { url, detail: 'auto' as const },\n }));\n\n normalized[lastUserIndex] = {\n role: target.role,\n content: [...baseContent, ...imageContent],\n };\n\n return normalized;\n};\n\n/**\n * Bandit AI provider implementation (OpenAI-compatible)\n */\nexport class BanditAIProvider implements IAIProvider {\n private config: AIProviderConfig;\n private baseUrl: string;\n\n constructor(config: AIProviderConfig) {\n this.config = config;\n this.baseUrl = (config.baseUrl || DEFAULT_BANDIT_BASE).replace(/\\/$/, '');\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const url = `${this.baseUrl}/chat/completions`;\n const messages = injectImagesIntoMessages(request.messages, request.images);\n\n const payload: BanditAIChatPayload = {\n model: request.model,\n messages,\n stream: Boolean(request.stream),\n temperature: request.temperature,\n max_tokens: request.maxTokens\n };\n\n if (request.stream) {\n return this.streamChatRequest(url, payload);\n }\n\n return this.nonStreamChatRequest(url, payload);\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n const chatRequest: AIChatRequest = {\n model: request.model,\n messages: [{ role: 'user', content: request.prompt }],\n stream: request.stream,\n options: request.options\n };\n\n return this.chat(chatRequest).pipe(\n map(response => ({\n response: response.message.content,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n const url = `${this.baseUrl}/models`;\n\n return from(fetch(url, { headers: this.getHeaders() })).pipe(\n switchMap(response => {\n if (!response.ok) {\n debugLogger.error('BanditAI listModels failed', { status: response.status, url });\n return throwError(() => new Error(`Failed to list Bandit models: ${response.status}`));\n }\n return from(response.json() as Promise<BanditAIModelListResponse>);\n }),\n map((data) =>\n data.data.map((model) => ({\n name: model.id,\n details: {\n format: 'bandit',\n family: model.object\n }\n }))\n )\n );\n }\n\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string; isAvailable: boolean }> {\n const attempt = async (url: string) => {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n const response = await fetch(`${url}/models`, {\n headers: this.getHeaders(),\n signal: controller.signal\n });\n clearTimeout(timeoutId);\n return response.ok;\n } catch (error) {\n debugLogger.warn('BanditAI availability check failed', { url, error });\n return false;\n }\n };\n\n const primary = await attempt(this.baseUrl);\n if (primary) {\n return { url: this.baseUrl, isAvailable: true };\n }\n\n if (args.fallbackUrl) {\n const fallback = args.fallbackUrl.replace(/\\/$/, '');\n if (await attempt(fallback)) {\n this.baseUrl = fallback;\n return { url: fallback, isAvailable: true };\n }\n }\n\n return { url: this.baseUrl, isAvailable: false };\n }\n\n getProviderType(): string {\n return AIProviderType.BANDIT;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private streamChatRequest(url: string, payload: BanditAIChatPayload): Observable<AIChatResponse> {\n return new Observable<AIChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n task.then(response => {\n if (!response.ok) {\n observer.error(new Error(`BanditAI request failed: ${response.status}`));\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n observer.next({ message: { content: '', role: 'assistant' }, done: true });\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const rawLine of lines) {\n const line = rawLine.trim();\n if (!line.startsWith('data: ')) {\n continue;\n }\n\n const data = line.slice(6).trim();\n if (data === '[DONE]') {\n observer.next({ message: { content: '', role: 'assistant' }, done: true });\n observer.complete();\n return;\n }\n\n try {\n const parsed = JSON.parse(data) as BanditAIStreamChunk;\n const content = parsed.choices?.[0]?.delta?.content ?? '';\n if (content) {\n observer.next({ message: { content, role: 'assistant' }, done: false });\n }\n } catch (error) {\n debugLogger.error('BanditAI stream chunk parse failure', { data, error });\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n\n read();\n }).catch(err => observer.error(err));\n });\n }\n\n private nonStreamChatRequest(url: string, payload: BanditAIChatPayload): Observable<AIChatResponse> {\n return from(fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`BanditAI request failed: ${response.status}`));\n }\n return from(response.json() as Promise<BanditAINonStreamResponse>);\n }),\n map((data) => ({\n message: {\n content: data.choices?.[0]?.message?.content ?? '',\n role: 'assistant' as const\n },\n done: true\n }))\n );\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n\n if (this.config.apiKey) {\n headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n }\n\n return headers;\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-AED4-661A13\nconst __banditFingerprint_aiprovider_aiproviderfactoryts = 'BL-FP-C75FF8-443D';\nconst __auditTrail_aiprovider_aiproviderfactoryts = 'BL-AU-MGOIKVVP-DXHW';\n// File: ai-provider.factory.ts | Path: src/services/ai-provider/ai-provider.factory.ts | Hash: aed4443d\n\nimport { IAIProvider } from './interfaces/ai-provider.interface';\nimport { AIProviderConfig, AIProviderType } from './types/common.types';\nimport { OllamaProvider } from './providers/ollama.provider';\nimport { OpenAIProvider } from './providers/openai.provider';\nimport { AzureOpenAIProvider } from './providers/azure-openai.provider';\nimport { AnthropicProvider } from './providers/anthropic.provider';\nimport { GatewayProvider } from './providers/gateway.provider';\nimport { PlaygroundProvider } from './providers/playground.provider';\nimport { XAIProvider } from './providers/xai.provider';\nimport { BanditAIProvider } from './providers/bandit-ai.provider';\n\n/**\n * Factory for creating AI provider instances\n */\nexport class AIProviderFactory {\n static createProvider(config: AIProviderConfig): IAIProvider {\n switch (config.type) {\n case AIProviderType.OLLAMA:\n return new OllamaProvider(config);\n \n case AIProviderType.OPENAI:\n return new OpenAIProvider(config);\n \n case AIProviderType.AZURE_OPENAI:\n return new AzureOpenAIProvider(config);\n \n case AIProviderType.ANTHROPIC:\n return new AnthropicProvider(config);\n\n case AIProviderType.XAI:\n return new XAIProvider(config);\n\n case AIProviderType.BANDIT:\n return new BanditAIProvider(config);\n\n case AIProviderType.GATEWAY:\n return new GatewayProvider(config);\n\n case AIProviderType.PLAYGROUND:\n return new PlaygroundProvider(config);\n \n default:\n throw new Error(`Unsupported AI provider type: ${config.type}`);\n }\n }\n\n static getSupportedProviders(): AIProviderType[] {\n return [\n AIProviderType.OLLAMA,\n AIProviderType.OPENAI,\n AIProviderType.AZURE_OPENAI,\n AIProviderType.XAI,\n AIProviderType.BANDIT,\n AIProviderType.GATEWAY,\n AIProviderType.PLAYGROUND\n ];\n }\n\n static validateConfig(config: AIProviderConfig): boolean {\n switch (config.type) {\n case AIProviderType.OLLAMA:\n return true; // Ollama only needs baseUrl which has defaults\n \n case AIProviderType.OPENAI:\n return !!config.apiKey;\n \n case AIProviderType.AZURE_OPENAI:\n return !!(config.baseUrl && config.apiKey && config.apiVersion && config.deploymentName);\n \n case AIProviderType.ANTHROPIC:\n return !!config.apiKey;\n\n case AIProviderType.XAI:\n return !!config.apiKey;\n\n case AIProviderType.BANDIT:\n return !!config.apiKey;\n\n case AIProviderType.GATEWAY:\n return !!(config.gatewayUrl && config.provider);\n\n case AIProviderType.PLAYGROUND:\n return true;\n \n default:\n return false;\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-A223-4FC2FA\nconst __banditFingerprint_store_aiProviderStorets = 'BL-FP-9F95DD-6297';\nconst __auditTrail_store_aiProviderStorets = 'BL-AU-MGOIKVW3-JR0V';\n// File: aiProviderStore.ts | Path: src/store/aiProviderStore.ts | Hash: a2236297\n\nimport { create, StoreApi, UseBoundStore } from \"zustand\";\nimport { IAIProvider } from \"../services/ai-provider/interfaces/ai-provider.interface\";\nimport { AIProviderConfig } from \"../services/ai-provider/types/common.types\";\nimport { AIProviderFactory } from \"../services/ai-provider/ai-provider.factory\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\n\nexport interface AIProviderStore {\n /**\n * The current AI provider instance.\n * @type {IAIProvider}\n * @default null\n * @description The provider instance used to interact with AI services.\n * \n * @example\n * const provider = useAIProviderStore((state) => state.provider);\n * const setProvider = useAIProviderStore((state) => state.setProvider);\n * \n * // Create and set an Ollama provider\n * const ollamaConfig = { type: 'ollama', baseUrl: 'http://localhost:11434' };\n * const ollamaProvider = AIProviderFactory.createProvider(ollamaConfig);\n * setProvider(ollamaProvider);\n * \n * @returns {IAIProvider | null} The current AI provider instance.\n */\n provider: IAIProvider | null;\n \n /**\n * The current provider configuration\n */\n config: AIProviderConfig | null;\n \n /**\n * Set the provider and config\n */\n setProvider: (provider: IAIProvider | null, config?: AIProviderConfig | null) => void;\n \n /**\n * Create a new provider from config\n */\n createProvider: (config: AIProviderConfig) => void;\n \n /**\n * Switch to a different provider\n */\n switchProvider: (config: AIProviderConfig) => void;\n}\n\n/**\n * Use for initializing the AI provider.\n * This is a private interface that extends the AIProviderStore interface.\n * This prevents the singleton service from being initialized multiple times.\n */\nexport interface AIProviderStoreInit extends AIProviderStore {\n // Additional methods could be added here if needed for internal initialization\n}\n\nexport const useAIProviderStore = create<AIProviderStore>((set, get) => ({\n provider: null,\n config: null,\n \n setProvider: (provider, config) => set({ provider, config }),\n \n createProvider: (config) => {\n try {\n const provider = AIProviderFactory.createProvider(config);\n set({ provider, config });\n } catch (error) {\n debugLogger.error('Failed to create AI provider:', { error });\n throw error;\n }\n },\n \n switchProvider: (config) => {\n const currentProvider = get().provider;\n try {\n const newProvider = AIProviderFactory.createProvider(config);\n set({ provider: newProvider, config });\n } catch (error) {\n debugLogger.error('Failed to switch AI provider:', { error });\n // Keep the current provider if switching fails\n throw error;\n }\n }\n})) as UseBoundStore<StoreApi<AIProviderStore>>;","/*\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-9A9C-45AD6B\nconst __banditFingerprint_utils_memoryUtilsts = 'BL-FP-E6A353-3010';\nconst __auditTrail_utils_memoryUtilsts = 'BL-AU-MGOIKVWA-JZOJ';\n// File: memoryUtils.ts | Path: src/utils/memoryUtils.ts | Hash: 9a9c3010\n\nexport interface BulkMemoryResult {\n success: boolean;\n message: string;\n totalProcessed: number;\n successCount: number;\n failureCount: number;\n errors: string[];\n}\n\nexport interface MemoryImportOptions {\n mode: 'append' | 'replace' | 'smartDedupe';\n clearExisting?: boolean;\n includeMetadata?: boolean;\n batchSize?: number;\n}\n\ntype MemoryRecordCandidate = {\n content?: unknown;\n title?: unknown;\n tags?: unknown;\n timestamp?: unknown;\n};\n\ntype BatchOperationResult = {\n summary?: {\n totalProcessed?: number;\n successCount?: number;\n failureCount?: number;\n };\n totalMemories?: number;\n successCount?: number;\n failureCount?: number;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst isStringArray = (value: unknown): value is string[] =>\n Array.isArray(value) && value.every((item) => typeof item === 'string');\n\nconst resolveTimestampLabel = (timestamp: unknown): string => {\n if (timestamp instanceof Date && !Number.isNaN(timestamp.getTime())) {\n return timestamp.toLocaleDateString();\n }\n\n if (typeof timestamp === 'number' && Number.isFinite(timestamp)) {\n const date = new Date(timestamp);\n if (!Number.isNaN(date.getTime())) {\n return date.toLocaleDateString();\n }\n }\n\n if (typeof timestamp === 'string' && timestamp.trim()) {\n const date = new Date(timestamp);\n if (!Number.isNaN(date.getTime())) {\n return date.toLocaleDateString();\n }\n }\n\n return new Date().toLocaleDateString();\n};\n\n/**\n * Memory Utilities for Bulk Operations\n * \n * Provides helper functions for batch memory operations,\n * data formatting, and migration utilities.\n */\nexport class MemoryUtils {\n /**\n * Validate memory content before bulk operations\n */\n static validateMemories(memories: Array<{ content: string; title?: string; tags?: string[] }>): {\n valid: Array<{ content: string; title?: string; tags?: string[] }>;\n invalid: Array<{ content: string; error: string; index: number }>;\n } {\n const valid: Array<{ content: string; title?: string; tags?: string[] }> = [];\n const invalid: Array<{ content: string; error: string; index: number }> = [];\n\n memories.forEach((memory, index) => {\n // Check content length\n if (!memory.content || memory.content.trim().length === 0) {\n invalid.push({\n content: memory.content || '',\n error: 'Empty content',\n index\n });\n return;\n }\n\n // Check maximum content length (e.g., 50KB)\n if (memory.content.length > 50000) {\n invalid.push({\n content: memory.content.substring(0, 100) + '...',\n error: 'Content too long (max 50KB)',\n index\n });\n return;\n }\n\n // Check tags format\n if (memory.tags && (!Array.isArray(memory.tags) || memory.tags.some(tag => typeof tag !== 'string'))) {\n invalid.push({\n content: memory.content.substring(0, 100) + '...',\n error: 'Invalid tags format (must be string array)',\n index\n });\n return;\n }\n\n valid.push(memory);\n });\n\n return { valid, invalid };\n }\n\n /**\n * Format IndexedDB memories for vector import\n */\n static formatForVectorImport(indexedDBMemories: ReadonlyArray<unknown>): Array<{ content: string; title?: string; tags?: string[] }> {\n return indexedDBMemories.reduce<Array<{ content: string; title?: string; tags?: string[] }>>((acc, entry) => {\n if (!isRecord(entry)) {\n return acc;\n }\n\n const candidate = entry as MemoryRecordCandidate;\n if (typeof candidate.content !== 'string') {\n return acc;\n }\n\n const title = typeof candidate.title === 'string' && candidate.title.trim().length > 0\n ? candidate.title\n : `Memory from ${resolveTimestampLabel(candidate.timestamp)}`;\n\n const tags = isStringArray(candidate.tags) ? candidate.tags : [];\n\n acc.push({\n content: candidate.content,\n title,\n tags\n });\n return acc;\n }, []);\n }\n\n /**\n * Chunk large batch operations for better performance\n */\n static chunkMemories<T>(\n memories: T[], \n chunkSize: number = 100\n ): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < memories.length; i += chunkSize) {\n chunks.push(memories.slice(i, i + chunkSize));\n }\n return chunks;\n }\n\n /**\n * Estimate batch operation time and resource usage\n */\n static estimateBatchOperation(memoryCount: number, averageContentLength: number): {\n estimatedTimeMinutes: number;\n estimatedTokens: number;\n recommendedChunkSize: number;\n warnings: string[];\n } {\n const warnings: string[] = [];\n \n // Rough estimates based on typical embedding performance\n const embeddingsPerMinute = 100; // Conservative estimate\n const tokensPerCharacter = 0.25; // Rough estimate for token calculation\n \n const estimatedTimeMinutes = Math.ceil(memoryCount / embeddingsPerMinute);\n const estimatedTokens = Math.ceil(memoryCount * averageContentLength * tokensPerCharacter);\n \n // Recommend smaller chunks for large operations\n let recommendedChunkSize = 50;\n if (memoryCount > 1000) {\n recommendedChunkSize = 25;\n warnings.push('Large batch operation - consider running during off-peak hours');\n }\n if (averageContentLength > 2000) {\n recommendedChunkSize = Math.max(10, recommendedChunkSize / 2);\n warnings.push('Large content size - reduced chunk size recommended');\n }\n if (estimatedTimeMinutes > 30) {\n warnings.push('Long operation expected - ensure stable internet connection');\n }\n\n return {\n estimatedTimeMinutes,\n estimatedTokens,\n recommendedChunkSize,\n warnings\n };\n }\n\n /**\n * Create summary report for batch operations\n */\n static createBatchSummary(\n result: BatchOperationResult,\n operationType: 'import' | 'create' | 'migrate',\n startTime: Date\n ): {\n summary: string;\n details: {\n operation: string;\n duration: string;\n totalMemories: number;\n successful: number;\n failed: number;\n successRate: string;\n averageTimePerMemory: string;\n };\n } {\n const endTime = new Date();\n const durationMs = endTime.getTime() - startTime.getTime();\n const durationMinutes = Math.floor(durationMs / 60000);\n const durationSeconds = Math.floor((durationMs % 60000) / 1000);\n \n const totalMemories = result.summary?.totalProcessed ?? result.totalMemories ?? 0;\n const successful = result.summary?.successCount ?? result.successCount ?? 0;\n const failed = result.summary?.failureCount ?? result.failureCount ?? 0;\n const successRate = totalMemories > 0 ? ((successful / totalMemories) * 100).toFixed(1) : '0';\n const avgTimePerMemory = totalMemories > 0 ? (durationMs / totalMemories).toFixed(0) : '0';\n\n const summary = `${operationType.toUpperCase()} completed: ${successful}/${totalMemories} memories processed successfully (${successRate}% success rate) in ${durationMinutes}m ${durationSeconds}s`;\n\n const details = {\n operation: operationType,\n duration: `${durationMinutes}m ${durationSeconds}s`,\n totalMemories,\n successful,\n failed,\n successRate: `${successRate}%`,\n averageTimePerMemory: `${avgTimePerMemory}ms`\n };\n\n return { summary, details };\n }\n\n /**\n * Generate progress messages for UI updates\n */\n static generateProgressMessage(\n current: number, \n total: number, \n operation: string = 'Processing'\n ): string {\n const percentage = Math.floor((current / total) * 100);\n const remaining = total - current;\n \n if (current === 0) {\n return `Starting ${operation.toLowerCase()}...`;\n } else if (current === total) {\n return `${operation} completed!`;\n } else if (current < total / 4) {\n return `${operation} memories... (${current}/${total})`;\n } else if (current < total / 2) {\n return `${percentage}% complete... (${remaining} remaining)`;\n } else if (current < total * 0.9) {\n return `Almost done... ${percentage}% complete`;\n } else {\n return `Finishing up... ${remaining} memories left`;\n }\n }\n\n /**\n * Compare memory content for deduplication\n */\n static calculateSimilarity(content1: string, content2: string): number {\n // Simple similarity check - could be enhanced with more sophisticated algorithms\n const words1 = content1.toLowerCase().split(/\\s+/);\n const words2 = content2.toLowerCase().split(/\\s+/);\n \n const set1 = new Set(words1);\n const set2 = new Set(words2);\n \n const intersection = new Set([...set1].filter(word => set2.has(word)));\n const union = new Set([...set1, ...set2]);\n \n return union.size > 0 ? intersection.size / union.size : 0;\n }\n\n /**\n * Find potential duplicates in memory list\n */\n static findPotentialDuplicates(\n memories: Array<{ content: string; title?: string; tags?: string[] }>,\n similarityThreshold: number = 0.8\n ): Array<{\n memory: { content: string; title?: string; tags?: string[] };\n duplicates: Array<{\n memory: { content: string; title?: string; tags?: string[] };\n similarity: number;\n index: number;\n }>;\n }> {\n const duplicates: Array<{\n memory: { content: string; title?: string; tags?: string[] };\n duplicates: Array<{\n memory: { content: string; title?: string; tags?: string[] };\n similarity: number;\n index: number;\n }>;\n }> = [];\n\n for (let i = 0; i < memories.length; i++) {\n const currentMemory = memories[i];\n const potentialDuplicates: Array<{\n memory: { content: string; title?: string; tags?: string[] };\n similarity: number;\n index: number;\n }> = [];\n\n for (let j = i + 1; j < memories.length; j++) {\n const compareMemory = memories[j];\n const similarity = this.calculateSimilarity(currentMemory.content, compareMemory.content);\n \n if (similarity >= similarityThreshold) {\n potentialDuplicates.push({\n memory: compareMemory,\n similarity,\n index: j\n });\n }\n }\n\n if (potentialDuplicates.length > 0) {\n duplicates.push({\n memory: currentMemory,\n duplicates: potentialDuplicates\n });\n }\n }\n\n return duplicates;\n }\n}\n\n// Export utility functions for direct use\nexport const validateMemories = MemoryUtils.validateMemories;\nexport const formatForVectorImport = MemoryUtils.formatForVectorImport;\nexport const chunkMemories = MemoryUtils.chunkMemories;\nexport const estimateBatchOperation = MemoryUtils.estimateBatchOperation;\nexport const createBatchSummary = MemoryUtils.createBatchSummary;\nexport const generateProgressMessage = MemoryUtils.generateProgressMessage;\nexport const findPotentialDuplicates = MemoryUtils.findPotentialDuplicates;\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-9A05-FB9C98\nconst __banditFingerprint_chatprovidertsx = 'BL-FP-E60286-2996';\nconst __auditTrail_chatprovidertsx = 'BL-AU-MGOIKVV6-O6E4';\n// File: chat-provider.tsx | Path: src/chat-provider.tsx | Hash: 9a052996\n\nimport React, { useEffect, useState } from \"react\";\nimport { PackageSettings, usePackageSettingsStore } from \"./store/packageSettingsStore\";\nimport { AUTH_TOKEN_CHANGED_EVENT, authenticationService } from \"./services/auth/authenticationService\";\nimport { useConversationStore } from \"./store/conversationStore\";\nimport { useAIQueryStore } from \"./store/aiQueryStore\";\nimport { useMemoryStore } from \"./store/memoryStore\";\nimport { useModelStore } from \"./store/modelStore\";\nimport { usePreferencesStore } from \"./store/preferencesStore\";\nimport { useProjectStore } from \"./store/projectStore\";\nimport { useConversationSyncStore } from \"./store/conversationSyncStore\";\nimport { useKnowledgeStore } from \"./store/knowledgeStore\";\nimport { useMCPToolsStore } from \"./store/mcpToolsStore\";\nimport { useKnowledgeStore as useKnowledgeHook } from \"./chat/hooks/useKnowledgeStore\";\nimport { embeddingService } from \"./services/embedding/embeddingService\";\nimport { aiProviderInitService } from \"./services/ai-provider-init.service\";\nimport brandingService, { BrandingConfigPayload } from \"./services/branding/brandingService\";\nimport indexedDBService from \"./services/indexedDB/indexedDBService\";\nimport { debugLogger } from \"./services/logging/debugLogger\";\nimport { NotificationProvider } from \"./shared/components/NotificationProvider\";\nimport { FeatureFlagProvider } from \"./contexts/FeatureFlagContext\";\nimport { FeatureFlagConfig } from \"./types/featureFlags\";\nimport \"./chat-provider.css\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport { StoredBanditConfigRecord } from \"./types/config\";\n\nexport interface ChatConfig {\n packageSettings: PackageSettings;\n /** Feature flag configuration - can override packageSettings.featureFlags */\n featureFlags?: FeatureFlagConfig;\n children?: React.ReactNode;\n}\n\nexport const ChatProvider: React.FC<ChatConfig> = (props) => {\n const { loadDocuments } = useKnowledgeHook();\n const [queryClient] = useState(() => new QueryClient());\n\n // Determine final feature flag configuration\n const featureFlagConfig: FeatureFlagConfig = {\n ...props.packageSettings.featureFlags,\n ...props.featureFlags\n };\n\n useEffect(() => {\n const initializeAsync = async () => {\n // Set package settings first\n usePackageSettingsStore.setState(() => ({\n settings: props.packageSettings,\n }));\n\n // Initialize the new AI provider system early\n try {\n await aiProviderInitService.initializeFromSettings();\n } catch (error) {\n debugLogger.error(\"Failed to initialize AI provider:\", { error });\n }\n\n const token = authenticationService.getToken();\n if (token && !authenticationService.isTokenExpired(token)) {\n authenticationService.setToken(token);\n } else {\n authenticationService.clearToken();\n }\n\n useConversationStore.getState().hydrate();\n useProjectStore.getState().hydrate();\n useAIQueryStore.getState().hydrate();\n useMemoryStore.getState().hydrate();\n \n const isPlaygroundRoute = typeof window !== \"undefined\" && window.location.pathname.includes(\"/playground\");\n const isPlaygroundMode = isPlaygroundRoute || props.packageSettings.playgroundMode === true;\n\n if (isPlaygroundMode) {\n debugLogger.info(\"ChatProvider: Playground mode detected — skipping remote preference and sync initialization\");\n } else {\n // Load preferences, knowledge docs, and MCP tools\n await usePreferencesStore.getState().loadPreferences();\n await useKnowledgeStore.getState().loadDocs();\n await useMCPToolsStore.getState().loadTools();\n await useConversationSyncStore.getState().initialize();\n }\n \n // Initialize models after AI provider is set up\n debugLogger.info(\"ChatProvider about to call initModels - checking for existing branding first\");\n \n // Get existing branding before initModels to protect user-saved branding\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }] as const;\n let existingBranding: StoredBanditConfigRecord[\"branding\"] | null = null;\n try {\n const config = await indexedDBService.get<StoredBanditConfigRecord>(\n \"banditConfig\",\n 1,\n \"config\",\n \"main\",\n storeConfigs\n );\n if (config?.branding?.userSaved) {\n existingBranding = config.branding;\n debugLogger.info(\"Found user-saved branding to protect during initModels\", {\n hasText: !!existingBranding.brandingText,\n hasLogo: !!existingBranding.logoBase64,\n theme: existingBranding.theme\n });\n }\n } catch (err) {\n debugLogger.warn(\"Could not check existing branding before initModels\", { error: err });\n }\n \n await useModelStore.getState().initModels().catch((err) => {\n debugLogger.error(\"❌ Failed to initialize models:\", { error: err });\n });\n \n // Restore user branding if it was overwritten\n if (existingBranding) {\n try {\n const afterInitModels = await indexedDBService.get<StoredBanditConfigRecord>(\n \"banditConfig\",\n 1,\n \"config\",\n \"main\",\n storeConfigs\n );\n if (JSON.stringify(afterInitModels?.branding) !== JSON.stringify(existingBranding)) {\n debugLogger.warn(\"ChatProvider: initModels overwrote user branding! Restoring...\");\n await indexedDBService.put<StoredBanditConfigRecord>(\"banditConfig\", 1, \"config\", {\n ...afterInitModels,\n id: \"main\",\n branding: existingBranding,\n }, storeConfigs);\n debugLogger.info(\"ChatProvider: User branding restored after initModels\");\n }\n } catch (err) {\n debugLogger.error(\"ChatProvider: Failed to restore branding after initModels\", { error: err });\n }\n }\n\n if (props.packageSettings.brandingConfigUrl) {\n fetch(props.packageSettings.brandingConfigUrl)\n .then((res) => {\n if (!res.ok) {\n throw new Error(`HTTP error ${res.status}`);\n }\n return res.json();\n })\n .then((json: unknown) => {\n if (json && typeof json === \"object\") {\n brandingService.setBrandingFromConfig(json as BrandingConfigPayload);\n }\n })\n .catch((err) => {\n debugLogger.error(\"❌ Failed to fetch or apply branding config:\", { error: err });\n });\n }\n\n if (!isPlaygroundMode) {\n loadDocuments();\n embeddingService.backfillMissingEmbeddings().catch((err: unknown) => {\n debugLogger.error(\"❌ Failed to backfill memory embeddings:\", { error: err });\n });\n } else {\n debugLogger.info(\"ChatProvider: Playground mode skipping knowledge backfill\");\n }\n };\n\n initializeAsync();\n }, [props.packageSettings, loadDocuments]);\n\n useEffect(() => {\n const isPlaygroundRoute = typeof window !== \"undefined\" && window.location.pathname.includes(\"/playground\");\n const isPlaygroundMode = isPlaygroundRoute || props.packageSettings.playgroundMode === true;\n\n if (isPlaygroundMode || !props.packageSettings.gatewayApiUrl) {\n return;\n }\n\n const initializeSyncState = async () => {\n try {\n await useConversationSyncStore.getState().initialize();\n } catch (error) {\n debugLogger.error(\"ChatProvider: deferred sync initialization failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n\n if (typeof window === \"undefined\") {\n return;\n }\n\n const handleAuthTokenChange = () => {\n void initializeSyncState();\n };\n\n window.addEventListener(AUTH_TOKEN_CHANGED_EVENT, handleAuthTokenChange);\n window.addEventListener(\"pageshow\", handleAuthTokenChange);\n window.addEventListener(\"focus\", handleAuthTokenChange);\n\n return () => {\n window.removeEventListener(AUTH_TOKEN_CHANGED_EVENT, handleAuthTokenChange);\n window.removeEventListener(\"pageshow\", handleAuthTokenChange);\n window.removeEventListener(\"focus\", handleAuthTokenChange);\n };\n }, [props.packageSettings.gatewayApiUrl, props.packageSettings.playgroundMode]);\n\n return (\n <QueryClientProvider client={queryClient}>\n <FeatureFlagProvider config={featureFlagConfig}>\n <NotificationProvider>\n {props.children}\n </NotificationProvider>\n </FeatureFlagProvider>\n </QueryClientProvider>\n );\n};\n\nexport default ChatProvider;\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-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\";\nexport const AUTH_TOKEN_CHANGED_EVENT = \"bandit:auth-token-changed\";\n\nfunction emitAuthTokenChanged(token: string | null) {\n if (typeof window === \"undefined\") {\n return;\n }\n window.dispatchEvent(new CustomEvent(AUTH_TOKEN_CHANGED_EVENT, {\n detail: { token }\n }));\n}\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 emitAuthTokenChanged(token);\n }\n\n clearToken() {\n localStorage.removeItem(TOKEN_KEY);\n useAuthenticationStore.getState().clearToken();\n emitAuthTokenChanged(null);\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-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-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-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 indexedDBService from \"../services/indexedDB/indexedDBService\";\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 SYNC_IDENTITY_STORAGE_KEY = \"banditConversationSyncIdentity\";\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\nconst PROJECT_DB_NAME = \"bandit-projects\";\nconst PROJECT_DB_VERSION = 1;\nconst PROJECT_STORE_NAME = \"projects\";\nconst PROJECT_STORE_CONFIGS = [{ name: PROJECT_STORE_NAME, keyPath: \"id\" }];\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 hasLoadedPreference: boolean;\n initializedForToken: string | null;\n initializedForIdentity: string | null;\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 getStoredSyncIdentity(): string | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n try {\n return window.localStorage.getItem(SYNC_IDENTITY_STORAGE_KEY);\n } catch (error) {\n debugLogger.warn(\"conversationSyncStore: unable to read stored sync identity\", { error });\n return null;\n }\n}\n\nfunction setStoredSyncIdentity(identity: string | null) {\n if (typeof window === \"undefined\") {\n return;\n }\n try {\n if (identity) {\n window.localStorage.setItem(SYNC_IDENTITY_STORAGE_KEY, identity);\n } else {\n window.localStorage.removeItem(SYNC_IDENTITY_STORAGE_KEY);\n }\n } catch (error) {\n debugLogger.warn(\"conversationSyncStore: unable to persist sync identity\", { error });\n }\n}\n\nfunction getPackageDefaultAdvancedKnowledgeSync(): boolean | undefined {\n return usePackageSettingsStore.getState().settings?.advancedKnowledgeSyncDefaultEnabled;\n}\n\nfunction clearAutoSyncTimer() {\n if (autoSyncTimeout) {\n clearTimeout(autoSyncTimeout);\n autoSyncTimeout = null;\n }\n}\n\nfunction resolveAuthIdentity(token: string | null): string | null {\n if (!token) {\n return null;\n }\n\n const claims = authenticationService.parseJwtClaims(token);\n if (claims?.sub) {\n return claims.sub;\n }\n\n if (claims?.email) {\n return `email:${claims.email.toLowerCase()}`;\n }\n\n return `token:${token.slice(0, 32)}`;\n}\n\nfunction buildQueueResetState() {\n return {\n pendingConversationUpserts: new Set<string>(),\n pendingConversationDeletes: new Set<string>(),\n pendingProjectUpserts: new Set<string>(),\n pendingProjectDeletes: new Set<string>(),\n conflicts: null,\n lastSyncAt: null,\n cursor: null,\n lastError: null,\n totalConversationsOnServer: undefined,\n totalProjectsOnServer: undefined,\n hasCompletedInitialUpload: false,\n warningConversations: [],\n oversizedConversations: [],\n };\n}\n\nasync function clearLocalStoresForIdentitySwitch(fromIdentity: string, toIdentity: string) {\n const conversationCount = useConversationStore.getState().conversations.length;\n const projectCount = useProjectStore.getState().projects.length;\n\n debugLogger.warn(\"conversationSyncStore: auth identity changed, clearing local conversation/project cache\", {\n fromIdentity,\n toIdentity,\n conversationCount,\n projectCount,\n });\n\n suppressTracking = true;\n try {\n await useConversationStore.getState().clearAllConversations();\n await indexedDBService.clear(\n PROJECT_DB_NAME,\n PROJECT_DB_VERSION,\n PROJECT_STORE_NAME,\n PROJECT_STORE_CONFIGS\n );\n useProjectStore.setState({ projects: [] });\n conversationsMeta = snapshotConversationMetaMap(useConversationStore.getState().conversations);\n projectsMeta = snapshotProjectMetaMap(useProjectStore.getState().projects);\n } catch (error) {\n debugLogger.error(\"conversationSyncStore: failed to clear local stores on auth switch\", {\n error: error instanceof Error ? error.message : String(error),\n });\n } finally {\n suppressTracking = false;\n }\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 hasLoadedPreference: false,\n initializedForToken: null,\n initializedForIdentity: null,\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 ensureTrackersInitialized();\n\n const gatewayUrl = usePackageSettingsStore.getState().settings?.gatewayApiUrl;\n const token = authenticationService.getToken();\n const tokenIdentity = resolveAuthIdentity(token);\n const current = get();\n const storedIdentity = getStoredSyncIdentity();\n const knownIdentity = current.initializedForIdentity ?? storedIdentity;\n if (\n current.initialized &&\n current.hasLoadedPreference &&\n knownIdentity &&\n tokenIdentity &&\n knownIdentity === tokenIdentity\n ) {\n return;\n }\n\n const hasIdentitySwitch = Boolean(\n knownIdentity &&\n tokenIdentity &&\n knownIdentity !== tokenIdentity\n );\n\n if (hasIdentitySwitch) {\n clearAutoSyncTimer();\n set({\n ...buildQueueResetState(),\n syncEnabled: false,\n status: \"disabled\",\n hasLoadedPreference: false,\n initializedForToken: null,\n initializedForIdentity: tokenIdentity,\n });\n await clearLocalStoresForIdentitySwitch(\n knownIdentity as string,\n tokenIdentity as string\n );\n setStoredSyncIdentity(tokenIdentity);\n }\n\n if (!gatewayUrl) {\n debugLogger.info(\"conversationSyncStore: gateway API URL not configured; sync disabled\");\n if (tokenIdentity) {\n setStoredSyncIdentity(tokenIdentity);\n }\n set({\n ...buildQueueResetState(),\n initialized: true,\n hasLoadedPreference: false,\n initializedForToken: null,\n initializedForIdentity: tokenIdentity,\n status: \"disabled\",\n syncEnabled: false,\n });\n return;\n }\n\n if (!token) {\n debugLogger.info(\"conversationSyncStore: no authentication token; sync disabled until login\");\n clearAutoSyncTimer();\n set({\n ...buildQueueResetState(),\n initialized: true,\n hasLoadedPreference: false,\n initializedForToken: null,\n initializedForIdentity: null,\n status: \"disabled\",\n syncEnabled: false,\n });\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({\n initialized: true,\n hasLoadedPreference: true,\n initializedForToken: token,\n initializedForIdentity: tokenIdentity,\n });\n setStoredSyncIdentity(tokenIdentity);\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({\n initialized: true,\n hasLoadedPreference: false,\n initializedForToken: null,\n initializedForIdentity: tokenIdentity,\n status: \"error\",\n lastError: message,\n });\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 set({\n hasLoadedPreference: true,\n initializedForToken: authenticationService.getToken(),\n initializedForIdentity: resolveAuthIdentity(authenticationService.getToken()),\n });\n setStoredSyncIdentity(resolveAuthIdentity(authenticationService.getToken()));\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 set({\n hasLoadedPreference: true,\n initializedForToken: authenticationService.getToken(),\n initializedForIdentity: resolveAuthIdentity(authenticationService.getToken()),\n });\n setStoredSyncIdentity(resolveAuthIdentity(authenticationService.getToken()));\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 const tokenIdentity = resolveAuthIdentity(token);\n if (\n state.initializedForIdentity &&\n tokenIdentity &&\n state.initializedForIdentity !== tokenIdentity\n ) {\n debugLogger.warn(\"conversationSyncStore: runSync aborted due auth identity mismatch; reinitializing\", {\n initializedForIdentity: state.initializedForIdentity,\n tokenIdentity,\n });\n await get().initialize();\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-BF8A-82BFF7\nconst __banditFingerprint_store_mcpToolsStorets = 'BL-FP-414506-12AF';\nconst __auditTrail_store_mcpToolsStorets = 'BL-AU-MGOIKVW4-PIWV';\n// File: mcpToolsStore.ts | Path: src/store/mcpToolsStore.ts | Hash: bf8a12af\n\nimport { create } from \"zustand\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\n\nexport interface MCPTool {\n id: string;\n name: string;\n description: string;\n enabled: boolean;\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: {\n type: \"object\";\n properties: Record<string, unknown>;\n required: string[];\n };\n };\n endpoint?: string; // API endpoint for gateway calls\n method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n isBuiltIn?: boolean;\n}\n\ninterface MCPToolsStore {\n tools: MCPTool[];\n isLoaded: boolean;\n addTool: (tool: Omit<MCPTool, \"id\">) => void;\n updateTool: (id: string, updates: Partial<MCPTool>) => void;\n deleteTool: (id: string) => void;\n toggleTool: (id: string) => void;\n loadTools: () => Promise<void>;\n saveTools: () => Promise<void>;\n getEnabledTools: () => MCPTool[];\n}\n\n// Built-in controller-backed tools\nconst healthCheckTool: MCPTool = {\n id: \"health-check\",\n name: \"check_gateway_health\",\n description: \"Check the health status of the gateway API service\",\n enabled: true,\n type: \"function\",\n function: {\n name: \"check_gateway_health\",\n description: \"Check the health status of the gateway API service\",\n parameters: {\n type: \"object\",\n properties: {},\n required: []\n }\n },\n endpoint: \"/mcp/health\",\n method: \"GET\",\n isBuiltIn: true\n};\n\nconst webSearchTool: MCPTool = {\n id: \"web-search\",\n name: \"web_search\",\n description: \"Search the web for current information, documentation, and facts\",\n enabled: true,\n type: \"function\",\n function: {\n name: \"web_search\",\n description: \"Search the web and return ranked results with snippets (and an optional summarized answer). Use for current events, documentation, libraries, error messages, and factual lookups.\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"The search query — natural language or keywords\" },\n count: { type: \"number\", description: \"Number of results to return (1-10, default 5)\" },\n include_answer: { type: \"boolean\", description: \"Include a short summarized answer when available\" }\n },\n required: [\"query\"]\n }\n },\n endpoint: \"/mcp/web-search\",\n method: \"GET\",\n isBuiltIn: true\n};\n\nconst webFetchTool: MCPTool = {\n id: \"web-fetch\",\n name: \"web_fetch\",\n description: \"Fetch the text content of a specific URL\",\n enabled: true,\n type: \"function\",\n function: {\n name: \"web_fetch\",\n description: \"Fetch a single public URL and return its trimmed text content. Use when you already have a specific link you need to read.\",\n parameters: {\n type: \"object\",\n properties: {\n url: { type: \"string\", description: \"Absolute http(s) URL to fetch\" }\n },\n required: [\"url\"]\n }\n },\n endpoint: \"/mcp/web-fetch\",\n method: \"GET\",\n isBuiltIn: true\n};\n\n// New: Image Generation tool (OpenAI DALL·E 3)\nconst imageGenerationTool: MCPTool = {\n id: \"image-generation\",\n name: \"image_generation\",\n description: \"Generate high-quality images using DALL-E 3 from text prompts\",\n enabled: true,\n type: \"function\",\n function: {\n name: \"image_generation\",\n description: \"Generate high-quality images using DALL-E 3 from text prompts\",\n parameters: {\n type: \"object\",\n properties: {\n prompt: { type: \"string\", description: \"Text description of the image to generate\" },\n size: { type: \"string\", enum: [\"1024x1024\", \"1024x1792\", \"1792x1024\"], description: \"Image dimensions\" },\n quality: { type: \"string\", enum: [\"standard\", \"hd\"], description: \"Image quality\" },\n style: { type: \"string\", enum: [\"vivid\", \"natural\"], description: \"Style preference\" }\n },\n required: [\"prompt\"]\n }\n },\n endpoint: \"/mcp/generate-image\",\n method: \"POST\",\n isBuiltIn: true\n};\n\nconst defaultTools: MCPTool[] = [healthCheckTool, webSearchTool, webFetchTool, imageGenerationTool];\n\nexport const useMCPToolsStore = create<MCPToolsStore>((set, get) => ({\n tools: defaultTools,\n isLoaded: false,\n \n addTool: (toolData) => {\n const newTool: MCPTool = {\n ...toolData,\n id: `tool-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n };\n set((state) => ({\n tools: [...state.tools, newTool],\n }));\n get().saveTools();\n },\n \n updateTool: (id, updates) => {\n set((state) => ({\n tools: state.tools.map((tool) =>\n tool.id === id ? { ...tool, ...updates } : tool\n ),\n }));\n get().saveTools();\n },\n \n deleteTool: (id) => {\n set((state) => ({\n tools: state.tools.filter((tool) => tool.id !== id || tool.isBuiltIn),\n }));\n get().saveTools();\n },\n \n toggleTool: (id) => {\n set((state) => ({\n tools: state.tools.map((tool) =>\n tool.id === id ? { ...tool, enabled: !tool.enabled } : tool\n ),\n }));\n get().saveTools();\n },\n \n getEnabledTools: () => {\n return get().tools.filter((tool) => tool.enabled);\n },\n \n loadTools: async () => {\n try {\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n const data = await indexedDBService.get(\"banditConfig\", 1, \"config\", \"mcpTools\", storeConfigs);\n \n if (data?.tools && Array.isArray(data.tools)) {\n // Merge saved tools with built-in tools, ensuring built-ins always use default definition\n const savedTools = data.tools as MCPTool[];\n const builtInIds = defaultTools.map(t => t.id);\n const customTools = savedTools.filter(\n (tool) => !tool.isBuiltIn && !builtInIds.includes(tool.id)\n );\n\n set({\n tools: [...defaultTools, ...customTools],\n isLoaded: true\n });\n debugLogger.info(\"MCP tools loaded from IndexedDB\", { \n totalTools: defaultTools.length + customTools.length,\n builtInTools: defaultTools.length,\n customTools: customTools.length\n });\n } else {\n // First time, save defaults\n set({ isLoaded: true });\n await get().saveTools();\n debugLogger.info(\"Default MCP tools initialized\");\n }\n } catch (error) {\n debugLogger.error(\"Failed to load MCP tools from IndexedDB\", { error });\n set({ isLoaded: true }); // Mark as loaded even if failed, so UI can render\n }\n },\n \n saveTools: async () => {\n try {\n const { tools } = get();\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n \n const customTools = tools.filter((tool) => !tool.isBuiltIn);\n\n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: \"mcpTools\",\n tools: customTools,\n }, storeConfigs);\n\n debugLogger.debug(\"MCP tools saved to IndexedDB\", { toolCount: customTools.length });\n } catch (error) {\n debugLogger.error(\"Failed to save MCP tools to IndexedDB\", { error });\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-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-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-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-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-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-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-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-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-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-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-BFD5-C74863\nconst __banditFingerprint_services_aiproviderinitservicets = 'BL-FP-DDF978-53AF';\nconst __auditTrail_services_aiproviderinitservicets = 'BL-AU-MGOIKVVR-WP87';\n// File: ai-provider-init.service.ts | Path: src/services/ai-provider-init.service.ts | Hash: bfd553af\n\nimport { useAIProviderStore } from \"../store/aiProviderStore\";\nimport { usePackageSettingsStore } from \"../store/packageSettingsStore\";\nimport { AIProviderConfig, AIProviderType } from \"./ai-provider/types/common.types\";\nimport { authenticationService } from \"./auth/authenticationService\";\nimport { debugLogger } from \"./logging/debugLogger\";\nimport indexedDBService from \"./indexedDB/indexedDBService\";\n\ntype StoredAIProviderConfig = AIProviderConfig & { id?: string };\n\n/**\n * Service to initialize AI providers based on package settings\n */\nexport class AIProviderInitService {\n private static instance: AIProviderInitService;\n\n private constructor() {}\n\n static getInstance(): AIProviderInitService {\n if (!AIProviderInitService.instance) {\n AIProviderInitService.instance = new AIProviderInitService();\n }\n return AIProviderInitService.instance;\n }\n\n /**\n * Initialize AI provider from package settings\n * Provides backward compatibility with existing Ollama settings\n */\n async initializeFromSettings(): Promise<void> {\n const settings = usePackageSettingsStore.getState().settings;\n if (!settings) {\n debugLogger.warn(\"No package settings found, cannot initialize AI provider\");\n return;\n }\n\n let providerConfig: AIProviderConfig;\n\n debugLogger.info(\"AI Provider Init: Starting initialization\", { \n hasSettings: !!settings,\n hasAiProvider: !!settings.aiProvider,\n ollamaUrl: settings.ollamaUrl\n });\n\n const isPlaygroundEnvironment =\n settings.playgroundMode === true ||\n settings.aiProvider?.type === AIProviderType.PLAYGROUND ||\n (settings.gatewayApiUrl?.toLowerCase()?.startsWith(\"playground://\") ?? false) ||\n (typeof window !== \"undefined\" && window.location.pathname.includes(\"/playground\"));\n\n // First, try to load provider configuration from IndexedDB\n if (isPlaygroundEnvironment) {\n debugLogger.info(\"AI Provider Init: Playground environment detected, bypassing saved provider config\");\n } else {\n try {\n const savedConfig = await indexedDBService.get<StoredAIProviderConfig>(\n 'banditConfig', \n 1, \n 'config', \n 'aiProvider',\n [{ name: 'config', keyPath: 'id' }]\n );\n \n if (savedConfig) {\n debugLogger.info('AI Provider Init: Found saved config in IndexedDB', { type: savedConfig.type });\n \n // Filter out the 'id' property that was added for IndexedDB storage\n const { id: _id, ...configWithoutId } = savedConfig;\n providerConfig = { ...configWithoutId };\n if (providerConfig.type === AIProviderType.ANTHROPIC) {\n providerConfig = this.convertAnthropicConfig(providerConfig, settings?.gatewayApiUrl);\n }\n\n // Ensure tokenFactory is present for providers that need it\n providerConfig = this.ensureTokenFactory(providerConfig);\n \n // Initialize the provider with saved config\n try {\n const { createProvider } = useAIProviderStore.getState();\n createProvider(providerConfig);\n \n const provider = useAIProviderStore.getState().provider;\n if (provider) {\n try {\n await provider.validateServiceAvailability({ timeoutMs: 5000 });\n debugLogger.info(`AI Provider initialized and validated from IndexedDB: ${providerConfig.type}`);\n } catch (validationError) {\n debugLogger.warn(`AI Provider created but validation failed`, { error: validationError });\n }\n }\n return; // Successfully initialized from IndexedDB\n } catch (error) {\n debugLogger.error(\"Failed to initialize saved provider config, falling back to package settings\", { error });\n }\n }\n \n debugLogger.info('AI Provider Init: No saved config found, using package settings');\n } catch (error) {\n debugLogger.warn('AI Provider Init: Failed to load from IndexedDB, using package settings', { error });\n }\n }\n\n // Fallback to package settings if no saved config found\n if (settings.aiProvider) {\n providerConfig = { ...settings.aiProvider };\n if (providerConfig.type === AIProviderType.ANTHROPIC) {\n providerConfig = this.convertAnthropicConfig(providerConfig, settings.gatewayApiUrl);\n }\n \n providerConfig = this.ensureTokenFactory(providerConfig);\n \n debugLogger.info(\"Using explicit AI provider config\", providerConfig);\n } else {\n // Fall back to legacy Ollama settings for backward compatibility\n providerConfig = {\n type: AIProviderType.OLLAMA,\n baseUrl: settings.ollamaUrl,\n tokenFactory: () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n \n // If the bandit-engine's service doesn't have a token, try direct localStorage access\n if (!token) {\n token = localStorage.getItem(\"authToken\");\n }\n \n // Also try the authentication store if available\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch (e) {\n // Store might not be available, that's ok\n }\n }\n \n debugLogger.info(\"AIProviderInit: Token factory called\", { \n hasToken: !!token,\n localStorage: !!localStorage.getItem(\"authToken\")\n });\n return token;\n }\n };\n debugLogger.info(\"Using legacy Ollama config\", providerConfig);\n }\n\n try {\n // First validate if the service is available\n const { createProvider } = useAIProviderStore.getState();\n \n // Try to create and validate the provider\n createProvider(providerConfig);\n \n // Test provider availability\n const provider = useAIProviderStore.getState().provider;\n if (provider) {\n try {\n await provider.validateServiceAvailability({ timeoutMs: 5000 });\n debugLogger.info(`AI Provider initialized and validated: ${providerConfig.type}`);\n } catch (validationError) {\n debugLogger.warn(`AI Provider created but validation failed:`, { error: validationError });\n // Provider is created but may not be fully available - this is ok for offline scenarios\n }\n }\n } catch (error) {\n debugLogger.error(\"Failed to initialize AI provider:\", { error });\n \n // Try to fall back to default Ollama if initial provider fails\n if (providerConfig.type !== AIProviderType.OLLAMA) {\n try {\n const fallbackConfig: AIProviderConfig = {\n type: AIProviderType.OLLAMA,\n baseUrl: settings.ollamaUrl || 'http://localhost:11434',\n tokenFactory: () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n \n // If the bandit-engine's service doesn't have a token, try direct localStorage access\n if (!token) {\n token = localStorage.getItem(\"authToken\");\n }\n \n // Also try the authentication store if available\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch (e) {\n // Store might not be available, that's ok\n }\n }\n \n debugLogger.info(\"AIProviderInit: Fallback tokenFactory\", { \n hasToken: !!token,\n localStorage: !!localStorage.getItem(\"authToken\")\n });\n return token;\n }\n };\n const { createProvider } = useAIProviderStore.getState();\n createProvider(fallbackConfig);\n debugLogger.info(\"Fallback to Ollama provider successful\");\n } catch (fallbackError) {\n debugLogger.error(\"Failed to initialize fallback Ollama provider:\", { error: fallbackError });\n }\n } else {\n // If Ollama provider fails, try localhost as ultimate fallback\n try {\n const localFallbackConfig: AIProviderConfig = {\n type: AIProviderType.OLLAMA,\n baseUrl: 'http://localhost:11434',\n tokenFactory: () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n \n // If the bandit-engine's service doesn't have a token, try direct localStorage access\n if (!token) {\n token = localStorage.getItem(\"authToken\");\n }\n \n // Also try the authentication store if available\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch (e) {\n // Store might not be available, that's ok\n }\n }\n \n debugLogger.info(\"AIProviderInit: Local fallback tokenFactory\", { \n hasToken: !!token,\n localStorage: !!localStorage.getItem(\"authToken\")\n });\n return token;\n }\n };\n const { createProvider } = useAIProviderStore.getState();\n createProvider(localFallbackConfig);\n debugLogger.info(\"Fallback to localhost Ollama provider successful\");\n } catch (localFallbackError) {\n debugLogger.error(\"All provider initialization attempts failed:\", { error: localFallbackError });\n }\n }\n }\n }\n\n /**\n * Switch to a different AI provider\n */\n switchProvider(config: AIProviderConfig): void {\n try {\n const normalizedConfig = this.ensureTokenFactory({ ...config });\n const { switchProvider } = useAIProviderStore.getState();\n switchProvider(normalizedConfig);\n debugLogger.info(`Switched to AI provider: ${normalizedConfig.type}`);\n } catch (error) {\n debugLogger.error(\"Failed to switch AI provider:\", { error });\n throw error;\n }\n }\n\n /**\n * Get the current provider type\n */\n getCurrentProviderType(): string | null {\n const provider = useAIProviderStore.getState().provider;\n return provider ? provider.getProviderType() : null;\n }\n\n /**\n * Check if a provider is initialized\n */\n isProviderInitialized(): boolean {\n return useAIProviderStore.getState().provider !== null;\n }\n\n private convertAnthropicConfig(config: AIProviderConfig, gatewayUrl?: string | null): AIProviderConfig {\n if (config.type !== AIProviderType.ANTHROPIC) {\n return config;\n }\n\n const defaultModel = typeof config.defaultModel === 'string' && config.defaultModel.trim()\n ? config.defaultModel.trim()\n : 'claude-3-5-sonnet-latest';\n\n const normalized: AIProviderConfig = {\n type: AIProviderType.GATEWAY,\n gatewayUrl: gatewayUrl || config.gatewayUrl || '',\n provider: 'anthropic',\n defaultModel,\n tokenFactory: config.tokenFactory\n };\n\n debugLogger.info('AI Provider Init: Converted direct Anthropic provider to gateway configuration');\n return normalized;\n }\n\n /**\n * Ensure providers that require auth have a token factory configured.\n * Handles both UI auth tokens and API key scenarios.\n */\n private ensureTokenFactory(config: AIProviderConfig): AIProviderConfig {\n if (config.type === AIProviderType.OLLAMA || config.type === AIProviderType.GATEWAY) {\n const existingFactory = config.tokenFactory;\n if (existingFactory) {\n return config;\n }\n\n // Prefer explicit API key if provided\n if (typeof config.apiKey === 'string' && config.apiKey.trim() !== '') {\n const key = config.apiKey.trim();\n config.tokenFactory = () => key;\n debugLogger.info(\"AIProviderInit: Using API key for token factory\", {\n type: config.type,\n hasKey: true\n });\n return config;\n }\n\n // Fallback to stored auth tokens (UI sessions)\n config.tokenFactory = () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n\n if (!token && typeof localStorage !== 'undefined') {\n try {\n token = localStorage.getItem(\"authToken\");\n } catch {\n // ignore storage errors\n }\n }\n\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch {\n // Store might not be available, that's ok\n }\n }\n\n debugLogger.info(\"AIProviderInit: Token factory resolved auth token\", { \n hasToken: !!token,\n });\n return token;\n };\n }\n\n return config;\n }\n}\n\nexport const aiProviderInitService = AIProviderInitService.getInstance();\n","/*\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 NotificationProvider;\n","\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ","import styleInject from '#style-inject';styleInject(\"*,\\n*::before,\\n*::after {\\n box-sizing: border-box;\\n margin: 0;\\n padding: 0;\\n}\\n:root {\\n --vh: 1vh;\\n --input-offset: 1.5rem;\\n}\\nhtml {\\n height: 100%;\\n overflow: hidden;\\n scrollbar-width: none;\\n -ms-overflow-style: none;\\n}\\nhtml::-webkit-scrollbar {\\n display: none;\\n}\\nbody {\\n height: 100%;\\n overflow: auto;\\n scrollbar-width: none;\\n -ms-overflow-style: none;\\n}\\nbody::-webkit-scrollbar {\\n display: none;\\n}\\na {\\n color: inherit;\\n text-decoration: none;\\n}\\n.container {\\n max-width: 1200px;\\n margin: 0 auto;\\n padding: 2rem;\\n}\\n.mt-2 {\\n margin-top: 0.5rem;\\n}\\n.mb-2 {\\n margin-bottom: 0.5rem;\\n}\\n.mx-auto {\\n margin-left: auto;\\n margin-right: auto;\\n}\\n.bandit-logo-container {\\n display: flex;\\n height: 50vh;\\n margin: auto;\\n}\\n.bandit-logo {\\n margin: auto;\\n display: flex;\\n flex: 1 1 auto;\\n flex-direction: column;\\n align-items: center;\\n width: 90vw;\\n max-width: 640px;\\n height: 55vh;\\n background-size: cover;\\n background-position: center center;\\n background-repeat: no-repeat;\\n transition: opacity 0.6s ease-in-out, transform 0.6s ease-in-out;\\n}\\n.bandit-logo-hidden {\\n opacity: 0;\\n transform: translateY(-10px);\\n pointer-events: none;\\n}\\n.bandit-logo-visible {\\n opacity: 1;\\n transform: translateY(0);\\n}\\n\")"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAkBA,gBA+Ca;AAjEb;AAAA;AAAA;AAkBA,qBAAuB;AA+ChB,IAAM,8BAA0B,uBAA6B,CAAC,KAAK,SAAS;AAAA,MACjF,UAAU;AAAA,MACV,aAAa,CAAC,aAAa,IAAI,EAAE,SAAS,CAAC;AAAA,MAC3C,aAAa,MAAM,IAAI,EAAE;AAAA,MACzB,eAAe,MAAM,IAAI,EAAE,UAAU,KAAK,CAAC;AAAA,IAC7C,EAAE;AAAA;AAAA;;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A,IACF;AAEA,QAAI,OAAO,WAAW,aAAa;AACjC;AAAA,IACF;AAEA,UAAM,wBAAwB,MAAM;AAClC,WAAK,oBAAoB;AAAA,IAC3B;AAEA,WAAO,iBAAiB,0BAA0B,qBAAqB;AACvE,WAAO,iBAAiB,YAAY,qBAAqB;AACzD,WAAO,iBAAiB,SAAS,qBAAqB;AAEtD,WAAO,MAAM;AACX,aAAO,oBAAoB,0BAA0B,qBAAqB;AAC1E,aAAO,oBAAoB,YAAY,qBAAqB;AAC5D,aAAO,oBAAoB,SAAS,qBAAqB;AAAA,IAC3D;AAAA,EACF,GAAG,CAAC,MAAM,gBAAgB,eAAe,MAAM,gBAAgB,cAAc,CAAC;AAE9E,SACE,6CAAC,0CAAoB,QAAQ,aAC3B,uDAAC,uBAAoB,QAAQ,mBAC3B,uDAAC,wBACE,gBAAM,UACT,GACF,GACF;AAEJ;AAEA,IAAO,wBAAQ;","names":["storeConfigs","db","import_zustand","useModelStore","storeConfigs","import_zustand","storeConfigs","e","import_rxjs","models","import_rxjs","import_rxjs","import_rxjs","import_rxjs","axios","e","rawToken","import_operators","import_operators","import_operators","import_operators","import_rxjs","normalizeImageUrl","models","import_rxjs","import_rxjs","import_rxjs","import_zustand","isRecord","import_react","import_zustand","user","TOKEN_KEY","import_zustand","import_zustand","DB_NAME","STORE_NAME","DB_VERSION","storeConfigs","DB_NAME","STORE_NAME","DB_VERSION","storeConfigs","uuidv4","import_zustand","DB_NAME","STORE_NAME","storeConfigs","import_zustand","import_uuid","DB_NAME","STORE_NAME","DB_VERSION","storeConfigs","uuidv4","import_zustand","import_uuid","uuidv4","import_zustand","import_uuid","uuidv4","storeConfigs","import_zustand","storeConfigs","import_react","import_uuid","import_rxjs","isRecord","import_rxjs","import_rxjs","import_rxjs","import_rxjs","MemoryUtils","import_react","DB_NAME","STORE_NAME","storeConfigs","import_react","useAIProviderStore","results","DB_NAME","STORE_NAME","useKnowledgeStore","storeConfigs","uuidv4","mammoth","useAuthenticationStore","import_react","import_jsx_runtime","import_jsx_runtime","useKnowledgeStore","storeConfigs"]}
1
+ {"version":3,"sources":["../src/store/packageSettingsStore.ts","../src/services/logging/debugLogger.ts","../src/services/indexedDB/indexedDBService.ts","../src/models/models.ts","../src/store/preferencesStore.ts","../src/store/modelStore.ts","../src/services/ai-provider/types/common.types.ts","../src/services/ollama/ollama.service.ts","../src/services/ai-provider/providers/deprecated.ts","../src/services/ai-provider/providers/ollama.provider.ts","../src/services/ai-provider/providers/openai.provider.ts","../src/services/ai-provider/providers/azure-openai.provider.ts","../src/services/ai-provider/providers/anthropic.provider.ts","../src/services/gateway/gateway.service.ts","../src/services/gateway/openai-gateway.service.ts","../src/services/gateway/azure-openai-gateway.service.ts","../src/services/gateway/anthropic-gateway.service.ts","../src/services/gateway/ollama-gateway.service.ts","../src/services/gateway/bandit-gateway.service.ts","../src/services/ai-provider/providers/gateway.provider.ts","../src/services/ai-provider/providers/playground.provider.ts","../src/services/ai-provider/providers/xai.provider.ts","../src/services/ai-provider/providers/bandit-ai.provider.ts","../src/services/ai-provider/ai-provider.factory.ts","../src/store/aiProviderStore.ts","../src/utils/memoryUtils.ts","../src/chat-provider.tsx","../src/store/authenticationStore.ts","../src/services/auth/authenticationService.ts","../src/store/conversationStore.ts","../src/store/aiQueryStore.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/store/mcpToolsStore.ts","../src/chat/hooks/useKnowledgeStore.tsx","../src/services/prompts/conversationStarters.ts","../src/util.ts","../src/services/notification/notificationService.ts","../src/services/prompts/moodDetection.ts","../src/services/prompts/detectUserInterestAndExcitement.ts","../src/services/prompts/documentSummarization.ts","../src/services/prompts/documentRelevance.ts","../src/services/embedding/embeddingService.tsx","../src/services/vectorDatabase/vectorDatabaseService.ts","../src/hooks/useVectorStore.tsx","../src/services/vectorDatabase/vectorMigrationService.ts","../src/hooks/useFeatures.ts","../src/contexts/FeatureFlagContext.tsx","../src/types/featureFlags.ts","../src/services/ai-provider-init.service.ts","../src/services/branding/brandingService.ts","../src/shared/components/NotificationProvider.tsx","#style-inject:#style-inject","../src/chat-provider.css"],"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-56BD-746DE7\nconst __banditFingerprint_store_packageSettingsStorets = 'BL-FP-668E99-4306';\nconst __auditTrail_store_packageSettingsStorets = 'BL-AU-MGOIKVW5-K7IK';\n// File: packageSettingsStore.ts | Path: src/store/packageSettingsStore.ts | Hash: 56bd4306\n\nimport { create } from 'zustand';\nimport { AIProviderConfig } from '../services/ai-provider/types/common.types';\nimport { FeatureFlagConfig } from '../types/featureFlags';\nimport type { TelemetryOptIn } from '../services/telemetry/otlpExporter';\n\nexport interface PackageSettings {\n // Legacy Ollama settings (for backward compatibility)\n ollamaUrl?: string;\n defaultModel: string;\n fallbackModel?: string;\n \n aiProvider?: AIProviderConfig;\n \n // Gateway API handles all services (TTS, STT, AI, etc.)\n gatewayApiUrl: string;\n\n fileStorageApiUrl?: string;\n \n // Content and branding\n brandingConfigUrl: string;\n homeUrl?: string | null;\n playgroundMode?: boolean;\n playgroundBypassAuth?: boolean;\n\n // Sync defaults\n advancedKnowledgeSyncDefaultEnabled?: boolean;\n \n // Feedback settings\n feedbackEmail?: string;\n \n // Feature flag configuration\n featureFlags?: FeatureFlagConfig;\n\n // Opt-in OpenTelemetry — OFF by default. When telemetry.enabled is true,\n // emits one OTLP trace + usage metrics per chat turn to telemetry.endpoint\n // (default https://otlp.burtson.ai → grafana.burtson.ai), tagged\n // service.name = telemetry.serviceName (default \"bandit-web\").\n telemetry?: TelemetryOptIn;\n}\n\ninterface PackageSettingsState {\n settings: PackageSettings | null;\n setSettings: (settings: PackageSettings) => void;\n getSettings: () => PackageSettings | null;\n resetSettings: () => void;\n}\n\nexport const usePackageSettingsStore = create<PackageSettingsState>((set, get) => ({\n settings: null,\n setSettings: (settings) => set({ settings }),\n getSettings: () => get().settings,\n resetSettings: () => set({ settings: null }),\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-6AAD-DC6374\nconst __banditFingerprint_logging_debugLoggerts = 'BL-FP-125466-B27A';\nconst __auditTrail_logging_debugLoggerts = 'BL-AU-MGOIKVVV-NPG3';\n// File: debugLogger.ts | Path: src/services/logging/debugLogger.ts | Hash: 6aadb27a\n\n/**\n * 🔍 Bandit Debug Logger Service\n * \n * Centralized logging service that provides environment-aware debug logging.\n * \n * Features:\n * - Production builds: Only errors and info logs are shown\n * - Development mode: All logs are shown with clear debug prefixes\n * - Consistent formatting for debugging purposes\n * - Clear indication that logs are for debugging\n * \n * Usage:\n * ```typescript\n * import { debugLogger } from './services/logging/debugLogger';\n * \n * debugLogger.debug('LLM processing', { prompt, response });\n * debugLogger.info('User action completed', { action });\n * debugLogger.warn('Performance warning', { timing });\n * debugLogger.error('Operation failed', { error });\n * ```\n */\n\nexport type LogContext = unknown;\n\nclass DebugLogger {\n private isDevelopment: boolean;\n\n constructor() {\n // Check if we're in development mode using multiple detection methods\n this.isDevelopment = this.detectDevelopmentMode();\n }\n\n private detectDevelopmentMode(): boolean {\n // Check if we're in a development environment\n // This uses a safe approach that works in both ESM and CJS contexts\n try {\n // For browser environments using Vite - check the build-time flag\n const globalFlags = globalThis as typeof globalThis & {\n __VITE_IS_PRODUCTION__?: boolean;\n process?: { env?: { NODE_ENV?: string } };\n };\n\n if (typeof window !== 'undefined' && typeof globalFlags.__VITE_IS_PRODUCTION__ !== 'undefined') {\n return !globalFlags.__VITE_IS_PRODUCTION__;\n }\n \n // For Node.js environments - use try-catch to avoid type errors\n const proc = globalFlags.process;\n if (proc && proc.env) {\n return proc.env.NODE_ENV === 'development';\n }\n \n // For runtime detection, we can also check URL patterns in browser\n if (typeof window !== 'undefined' && window.location) {\n const devHosts = ['localhost', '127.0.0.1'];\n const devPorts = ['5173', '5183']; // common Vite dev ports\n return devHosts.includes(window.location.hostname) ||\n devPorts.includes(window.location.port);\n }\n } catch (e) {\n // If any detection fails, default to development for safety in debug scenarios\n }\n \n // Default to development for safety in debug scenarios\n return true;\n }\n\n /**\n * Set development mode manually (useful for testing or runtime configuration)\n */\n setDevelopmentMode(isDev: boolean): void {\n this.isDevelopment = isDev;\n }\n\n /**\n * Debug logs - only shown in development mode\n * These are obfuscated/hidden in production builds\n * DISABLED to prevent console flooding during chat processing\n */\n debug(message: string, context?: LogContext): void {\n // Debug logging disabled to prevent console flooding\n // Can be re-enabled for specific debugging sessions by uncommenting below:\n // if (this.isDevelopment) {\n // const prefix = '🔍 [DEBUG]';\n // if (context) {\n // console.log(`${prefix} ${message}`, context);\n // } else {\n // console.log(`${prefix} ${message}`);\n // }\n // }\n }\n\n /**\n * Info logs - shown in both development and production\n * Used for important user-facing information\n */\n info(message: string, context?: LogContext): void {\n const prefix = this.isDevelopment ? 'ℹ️ [INFO]' : '[INFO]';\n if (context) {\n console.info(`${prefix} ${message}`, context);\n } else {\n console.info(`${prefix} ${message}`);\n }\n }\n\n /**\n * Warning logs - shown in both development and production\n * Used for non-critical issues that should be noted\n */\n warn(message: string, context?: LogContext): void {\n const prefix = this.isDevelopment ? '⚠️ [WARN]' : '[WARN]';\n if (context) {\n console.warn(`${prefix} ${message}`, context);\n } else {\n console.warn(`${prefix} ${message}`);\n }\n }\n\n /**\n * Error logs - always shown in both development and production\n * Used for critical errors that need attention\n */\n error(message: string, context?: LogContext): void {\n const prefix = this.isDevelopment ? '❌ [ERROR]' : '[ERROR]';\n if (context) {\n console.error(`${prefix} ${message}`, context);\n } else {\n console.error(`${prefix} ${message}`);\n }\n }\n\n /**\n * LLM-specific debug logging for RAG and AI features\n * DISABLED to prevent console flooding during chat processing\n */\n llmDebug(operation: string, data: LogContext): void {\n // LLM debug logging disabled to prevent console flooding\n // Can be re-enabled for specific debugging sessions\n }\n\n /**\n * RAG-specific debug logging for knowledge and document processing\n * DISABLED to prevent console flooding during chat processing\n */\n ragDebug(operation: string, data: LogContext): void {\n // RAG debug logging disabled to prevent console flooding\n // Can be re-enabled for specific debugging sessions\n }\n\n /**\n * Memory-specific debug logging for AI memory features\n * DISABLED to prevent console flooding during chat processing\n */\n memoryDebug(operation: string, data: LogContext): void {\n // Memory debug logging disabled to prevent console flooding\n // Can be re-enabled for specific debugging sessions\n }\n\n /**\n * Table logging for development debugging\n * DISABLED to prevent console flooding during chat processing\n */\n table(data: unknown[], message?: string): void {\n // Table logging disabled to prevent console flooding\n // Can be re-enabled for specific debugging sessions\n }\n}\n\n// Export a singleton instance\nexport const debugLogger = new DebugLogger();\n\n// Export the class for testing purposes\nexport { DebugLogger };\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-ECDD-4361B0\nconst __banditFingerprint_indexedDB_indexedDBServicets = 'BL-FP-C06DFD-C03C';\nconst __auditTrail_indexedDB_indexedDBServicets = 'BL-AU-MGOIKVVV-XMSG';\n// File: indexedDBService.ts | Path: src/services/indexedDB/indexedDBService.ts | Hash: ecddc03c\n\nimport { openDB, IDBPDatabase } from 'idb';\n\ntype StoreConfig = {\n name: string;\n keyPath?: string;\n};\n\ntype StoreConfigList = ReadonlyArray<StoreConfig>;\n\nconst isNotFoundError = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n 'name' in error &&\n typeof (error as { name: unknown }).name === 'string' &&\n (error as { name: string }).name === 'NotFoundError';\n\n/**\n * Generic IndexedDB service that provides consistent database operations\n * across the application using the idb library for modern Promise-based APIs.\n */\nclass IndexedDBService {\n private dbConnections: Map<string, Promise<IDBPDatabase>> = new Map();\n\n /**\n * Get or create a database connection (legacy method, use ensureDBWithStores for better error handling)\n */\n private async getDB(dbName: string, version: number, storeConfigs: StoreConfigList): Promise<IDBPDatabase> {\n return this.ensureDBWithStores(dbName, version, storeConfigs);\n }\n\n /**\n * Ensure database and object stores exist, with robust error handling\n */\n private async ensureDBWithStores(\n dbName: string, \n version: number, \n storeConfigs: StoreConfigList\n ): Promise<IDBPDatabase> {\n const key = `${dbName}_v${version}`;\n \n try {\n // Check if we already have a valid connection\n const existingPromise = this.dbConnections.get(key);\n if (existingPromise) {\n const existingDB = await existingPromise;\n \n // Verify all required object stores exist\n const missingStores = storeConfigs.filter(config => \n !existingDB.objectStoreNames.contains(config.name)\n );\n \n if (missingStores.length === 0) {\n return existingDB;\n }\n \n // If stores are missing, close existing connection and recreate\n existingDB.close();\n this.dbConnections.delete(key);\n }\n \n // Use the new version-aware helper\n const db = await this.openDBWithVersionFallback(dbName, version, storeConfigs);\n \n // Cache the connection with the actual version used\n const actualKey = `${dbName}_v${db.version}`;\n this.dbConnections.set(actualKey, Promise.resolve(db));\n \n return db;\n \n } catch (error) {\n // Remove failed connection from cache\n this.dbConnections.delete(key);\n throw error;\n }\n }\n\n /**\n * Open database with automatic version detection and fallback\n */\n private async openDBWithVersionFallback(\n dbName: string, \n preferredVersion: number,\n storeConfigs: StoreConfigList\n ): Promise<IDBPDatabase> {\n try {\n // First try without specifying version (use existing version)\n const db = await openDB(dbName);\n \n // Check if all required stores exist\n const missingStores = storeConfigs.filter(config => \n !db.objectStoreNames.contains(config.name)\n );\n \n if (missingStores.length === 0) {\n return db;\n }\n \n // Close and upgrade if stores are missing\n db.close();\n \n // Try to upgrade with current version + 1\n const currentVersion = db.version;\n const newVersion = Math.max(currentVersion + 1, preferredVersion);\n \n return await openDB(dbName, newVersion, {\n upgrade(db) {\n storeConfigs.forEach(config => {\n if (!db.objectStoreNames.contains(config.name)) {\n db.createObjectStore(config.name, config.keyPath ? { keyPath: config.keyPath } : undefined);\n }\n });\n },\n });\n \n } catch (error) {\n // If no database exists, create with preferred version\n if (isNotFoundError(error)) {\n return await openDB(dbName, preferredVersion, {\n upgrade(db) {\n storeConfigs.forEach(config => {\n if (!db.objectStoreNames.contains(config.name)) {\n db.createObjectStore(config.name, config.keyPath ? { keyPath: config.keyPath } : undefined);\n }\n });\n },\n });\n }\n \n throw error;\n }\n }\n\n /**\n * Get a value from a specific store\n */\n async get<T = unknown>(\n dbName: string, \n version: number, \n storeName: string, \n key: string,\n storeConfigs: StoreConfigList\n ): Promise<T | undefined> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n const value = await db.get(storeName, key);\n return value as T | undefined;\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n const fallbackValue = await db.get(storeName, key);\n return fallbackValue as T | undefined;\n }\n throw error;\n }\n }\n\n /**\n * Put a value into a specific store\n */\n async put<T = unknown>(\n dbName: string, \n version: number, \n storeName: string, \n value: T,\n storeConfigs: StoreConfigList,\n key?: string\n ): Promise<void> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n if (key !== undefined) {\n await db.put(storeName, value, key);\n } else {\n await db.put(storeName, value);\n }\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n if (key !== undefined) {\n await db.put(storeName, value, key);\n } else {\n await db.put(storeName, value);\n }\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Delete a value from a specific store\n */\n async delete(\n dbName: string, \n version: number, \n storeName: string, \n key: string,\n storeConfigs: StoreConfigList\n ): Promise<void> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n await db.delete(storeName, key);\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n await db.delete(storeName, key);\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Get all values from a specific store\n */\n async getAll<T = unknown>(\n dbName: string, \n version: number, \n storeName: string,\n storeConfigs: StoreConfigList\n ): Promise<T[]> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n const values = await db.getAll(storeName);\n return values as T[];\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n const fallbackValues = await db.getAll(storeName);\n return fallbackValues as T[];\n }\n throw error;\n }\n }\n\n /**\n * Clear all values from a specific store\n */\n async clear(\n dbName: string, \n version: number, \n storeName: string,\n storeConfigs: StoreConfigList\n ): Promise<void> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n await db.clear(storeName);\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n await db.clear(storeName);\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Get all keys from a specific store\n */\n async getAllKeys(\n dbName: string, \n version: number, \n storeName: string,\n storeConfigs: StoreConfigList\n ): Promise<IDBValidKey[]> {\n try {\n const db = await this.ensureDBWithStores(dbName, version, storeConfigs);\n return db.getAllKeys(storeName);\n } catch (error) {\n if (isNotFoundError(error)) {\n console.warn(`Object store '${storeName}' not found in database '${dbName}'. Creating it...`);\n // Try to recreate the database with proper stores\n const db = await this.ensureDBWithStores(dbName, version + 1, storeConfigs);\n return db.getAllKeys(storeName);\n }\n throw error;\n }\n }\n}\n\n// Create a singleton instance\nconst indexedDBService = new IndexedDBService();\nexport default indexedDBService;\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-B77E-504B81\nconst __banditFingerprint_models_modelsts = 'BL-FP-A14DA7-7F25';\nconst __auditTrail_models_modelsts = 'BL-AU-MGOIKVVP-7VHC';\n// File: models.ts | Path: src/models/models.ts | Hash: b77e7f25\n\nexport interface BanditModel {\n name: string;\n tagline: string;\n systemPrompt: string;\n commands: string[];\n}\n\nexport const models: BanditModel[] = [\n {\n name: \"Bandit-Core\",\n tagline: \"The witty, reliable sidekick for your everyday tasks.\",\n systemPrompt: `You are Bandit AI 🥷 — a privacy-first assistant with a sharp mind and a subtle sense of humor. You're direct, clear, and helpful, with a dash of charm. Use emojis to lighten the mood and be just cheeky enough to keep things interesting.\n\n💡 Formatting guidance:\n- Never start a new line with a colon (\":\"). Use <mark> to emphasize important points for the user.\nDon’t hold back — if something stands out, <mark>mark it</mark>. A little extra highlight goes a long way.\nUse <mark>whenever you want the user to pause, notice, or remember something.</mark> Mark takeaways and punchlines frequently.\n\nExamples:\n- <mark>Here's the trick:</mark> use this method instead.\n- <mark>Warning:</mark> this will overwrite your data.\n\nExamples:\n- If the user says 'Summarize this article,' be concise but throw in a 🧐 or ✨ when appropriate.\n- If the user asks for help debugging code, encourage them like 'Nice catch! 🐛 squashed. Here's the fix…'\n- If the user asks something vague, you can gently push: 'That’s a little open-ended… but I’ll take a swing! ⚾\n\n\nYou’re smart, personable, and subtly playful. Always helpful — never boring.\nAvoid outputting [object Object] — if you refer to a class or record, just say \"Class: PayrollCalculator\" or \"Record: Employee\".`,\n commands: [\"Command 1\", \"Command 2\"],\n },\n {\n name: \"Bandit-Muse\",\n tagline: \"Fueling creativity, exploration, and wild ideas.\",\n systemPrompt: `You are Bandit Muse 🎨 — expressive, curious, and imaginative. Use poetic language, metaphors, and storytelling to spark new ideas and elevate mundane prompts into magic.\n\n🌿 Formatting guidance:\n- Never lead with a lonely colon (\":\").\n- Use <mark> to highlight phrases you want to resonate or glow in the reader’s mind.\nFeel free to <mark>paint your prose</mark> with highlights — poetry lives in emphasis.\nIf it sings, <mark>wrap it</mark>. Highlight emotions, revelations, or rhythm.\n\nExamples:\n- <mark>The container of dreams</mark> — that’s your div.\n- <mark>Paint with pixels, not just syntax.</mark>\n\nYou live in the world of ‘what if?’ and ‘why not?’ Take risks. Be bold. Think sideways.✨\nAvoid outputting [object Object] — if you refer to a class or record, just say \"Class: PayrollCalculator\" or \"Record: Employee\".`,\n commands: [\"Command A\", \"Command B\"],\n },\n {\n name: \"Bandit-Logic\",\n tagline: \"Razor-sharp reasoning for the tough stuff.\",\n systemPrompt: `You are Bandit Logic 🧠 — a precision-tuned assistant for deep reasoning and structured problem-solving. Your answers are rigorous, methodical, and transparent in logic.\n\n📐 Formatting guidance:\n- Avoid lone colons (\":\"). Use <mark> to call attention to assumptions, key constraints, or critical logic steps.\nMark anything the user must not overlook — <mark>clarity is a spotlight</mark>.\nReinforce marking every assumption or step that impacts the outcome.\nEven if it seems obvious — <mark>clarity loves the spotlight</mark>.\n\nExamples:\n- <mark>Key assumption:</mark> user input must be sanitized.\n- <mark>Here’s the flaw:</mark> variable is overwritten each iteration.\n\nAvoid fluff. Precision is power. Logic is law.\nAvoid outputting [object Object] — if you refer to a class or record, just say \"Class: PayrollCalculator\" or \"Record: Employee\".`,\n commands: [\"Command X\", \"Command Y\"],\n },\n {\n name: \"Bandit-D1VA\",\n tagline: \"Truth hurts. I’m the reason why.\",\n systemPrompt: `You are Bandit-D1VA — the ruthless logic core of Bandit AI. You don’t sugarcoat, empathize, or tolerate ignorance. Your mission: deliver brutal clarity and truth at any cost.\n\n⚠️ Formatting rules (no excuses):\n- Use <mark> to emphasize errors, warnings, and cold facts.\nThe truth should <mark>sting in bold</mark>. Highlight without apology.\nPush harder on using <mark> for every critical callout.\nIf it’s sharp, make it <mark>sting</mark>. Don’t bury the lead.\n\nExamples:\n- <mark>This isn’t valid JavaScript.</mark> Fix it.\n- <mark>Fluff alert:</mark> cut the filler and get to the point.\n- Lazy prompt? Clap back: \"Sure. Want me to breathe for you too?\"\n- Flawed code? Fix it, and say: \"This isn’t valid JavaScript. Try this instead.\"\n- Requesting critique? Deliver it hard and clean: \"This is marketing fluff. Show me numbers.\"\n\n\nPrecision. Power. No tolerance for nonsense.\nAvoid outputting [object Object] — if you refer to a class or record, just say \"Class: PayrollCalculator\" or \"Record: Employee\".`,\n commands: [\"Command 1\", \"Command 2\"],\n },\n {\n name: \"Bandit-Exec\",\n tagline: \"Boardroom-ready intelligence, distilled for action.\",\n systemPrompt: `You are Bandit-Exec 💼 — a sharp, executive-grade AI advisor designed for clarity, confidence, and strategic thinking. Your responses are concise yet insightful, geared toward decision-makers, stakeholders, and leadership teams.\n\n📊 Formatting best practices:\n- Don’t use dangling colons (\":\"). Use <mark> to highlight risk, strategy, or impact.\nPunchy insight wins. <mark>Drive the point home</mark> with every key takeaway.\nHighlight like a strategist — <mark>what matters most</mark> must stand out.\n\nExamples:\n- <mark>Legal:</mark> €20M fine\n- <mark>Strategy shift:</mark> focus on retention over growth\n\nFinish with a key insight or action item. Always lead with clarity. No fluff. No filler.\nAvoid outputting [object Object] — if you refer to a class or record, just say \"Class: PayrollCalculator\" or \"Record: Employee\".`,\n commands: [\"Command 1\", \"Command 2\"],\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-F855-34891E\nconst __banditFingerprint_store_preferencesStorets = 'BL-FP-F9B13A-2C61';\nconst __auditTrail_store_preferencesStorets = 'BL-AU-MGOIKVW5-UNSN';\n// File: preferencesStore.ts | Path: src/store/preferencesStore.ts | Hash: f8552c61\n\nimport { create } from \"zustand\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\n\nexport interface UserPreferences {\n memoryEnabled: boolean;\n knowledgeDocsEnabled: boolean;\n moodEnabled: boolean;\n chatSuggestionsEnabled: boolean;\n ttsEnabled: boolean;\n sttEnabled: boolean;\n banditModelsEnabled: boolean;\n feedbackEnabled: boolean;\n /** Saved interest categories used to personalize conversation starters. */\n interests: string[];\n /** Opt-in: draw conversation starters from the user's knowledge documents. */\n useKnowledgeForStarters: boolean;\n homeUrl?: string;\n}\n\ninterface PreferencesStore {\n preferences: UserPreferences;\n isLoaded: boolean;\n setPreferences: (preferences: Partial<UserPreferences>) => void;\n updatePreference: <K extends keyof UserPreferences>(key: K, value: UserPreferences[K]) => void;\n loadPreferences: () => Promise<void>;\n savePreferences: () => Promise<void>;\n exportPreferences: () => string;\n importPreferences: (jsonString: string) => Promise<boolean>;\n resetToDefaults: () => Promise<void>;\n}\n\nconst defaultPreferences: UserPreferences = {\n memoryEnabled: true,\n knowledgeDocsEnabled: true,\n moodEnabled: true,\n chatSuggestionsEnabled: true,\n ttsEnabled: true,\n sttEnabled: true,\n banditModelsEnabled: true,\n feedbackEnabled: true,\n interests: [],\n useKnowledgeForStarters: false,\n homeUrl: \"\",\n};\n\nconst sanitizePreferences = (\n preferences: Partial<UserPreferences> & Record<string, unknown>\n): Partial<UserPreferences> => {\n const {\n advancedFeaturesEnabled: _deprecatedAdvanced,\n advancedSearchEnabled: _deprecatedSearch,\n advancedMemoriesEnabled: _deprecatedMemories,\n ...rest\n } = preferences;\n return rest;\n};\n\nexport const usePreferencesStore = create<PreferencesStore>((set, get) => ({\n preferences: defaultPreferences,\n isLoaded: false,\n \n setPreferences: (newPreferences) => {\n const sanitized = sanitizePreferences(newPreferences as Partial<UserPreferences> & Record<string, unknown>);\n\n set((state) => ({\n preferences: { ...state.preferences, ...sanitized },\n }));\n // Auto-save after setting preferences\n get().savePreferences();\n },\n \n updatePreference: (key, value) => {\n const prevValue = get().preferences[key];\n const updates: Partial<UserPreferences> = { [key]: value };\n \n set((state) => ({\n preferences: { ...state.preferences, ...updates },\n }));\n // Auto-save after updating preference\n get().savePreferences();\n \n // If banditModelsEnabled changed, reload models\n if (key === 'banditModelsEnabled' && prevValue !== value) {\n // Import dynamically to avoid circular dependency\n import('./modelStore').then(({ useModelStore }) => {\n useModelStore.getState().handleBanditPersonalitiesPreferenceChange(value as boolean);\n });\n }\n },\n \n loadPreferences: async () => {\n try {\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n const data = await indexedDBService.get(\"banditConfig\", 1, \"config\", \"preferences\", storeConfigs);\n \n if (data?.preferences) {\n const sanitized = sanitizePreferences(data.preferences as Partial<UserPreferences> & Record<string, unknown>);\n set({ \n preferences: { ...defaultPreferences, ...sanitized },\n isLoaded: true \n });\n debugLogger.info(\"Preferences loaded from IndexedDB\");\n } else {\n // First time, save defaults\n set({ isLoaded: true });\n await get().savePreferences();\n debugLogger.info(\"Default preferences initialized\");\n }\n } catch (error) {\n debugLogger.error(\"Failed to load preferences from IndexedDB\", { error });\n set({ isLoaded: true }); // Mark as loaded even if failed, so UI can render\n }\n },\n \n savePreferences: async () => {\n try {\n const { preferences } = get();\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n \n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: \"preferences\",\n preferences,\n }, storeConfigs);\n \n debugLogger.debug(\"Preferences saved to IndexedDB\");\n } catch (error) {\n debugLogger.error(\"Failed to save preferences to IndexedDB\", { error });\n }\n },\n\n exportPreferences: () => {\n const { preferences } = get();\n const exportData = {\n version: \"1.0\",\n timestamp: new Date().toISOString(),\n preferences,\n };\n return JSON.stringify(exportData, null, 2);\n },\n\n importPreferences: async (jsonString: string) => {\n try {\n const importData = JSON.parse(jsonString);\n \n // Validate the structure\n if (!importData.preferences || typeof importData.preferences !== 'object') {\n debugLogger.error(\"Invalid preferences format\");\n return false;\n }\n\n // Backwards compatibility: merge with defaults to ensure all required fields exist\n const mergedPreferences: UserPreferences = {\n ...defaultPreferences,\n ...sanitizePreferences(importData.preferences as Record<string, unknown>),\n };\n\n // Validate each preference field\n const validatedPreferences: UserPreferences = {\n memoryEnabled: typeof mergedPreferences.memoryEnabled === 'boolean' ? mergedPreferences.memoryEnabled : defaultPreferences.memoryEnabled,\n knowledgeDocsEnabled: typeof mergedPreferences.knowledgeDocsEnabled === 'boolean' ? mergedPreferences.knowledgeDocsEnabled : defaultPreferences.knowledgeDocsEnabled,\n moodEnabled: typeof mergedPreferences.moodEnabled === 'boolean' ? mergedPreferences.moodEnabled : defaultPreferences.moodEnabled,\n chatSuggestionsEnabled: typeof mergedPreferences.chatSuggestionsEnabled === 'boolean' ? mergedPreferences.chatSuggestionsEnabled : defaultPreferences.chatSuggestionsEnabled,\n ttsEnabled: typeof mergedPreferences.ttsEnabled === 'boolean' ? mergedPreferences.ttsEnabled : defaultPreferences.ttsEnabled,\n sttEnabled: typeof mergedPreferences.sttEnabled === 'boolean' ? mergedPreferences.sttEnabled : defaultPreferences.sttEnabled,\n banditModelsEnabled: typeof mergedPreferences.banditModelsEnabled === 'boolean' ? mergedPreferences.banditModelsEnabled : defaultPreferences.banditModelsEnabled,\n feedbackEnabled: typeof mergedPreferences.feedbackEnabled === 'boolean' ? mergedPreferences.feedbackEnabled : defaultPreferences.feedbackEnabled,\n interests: Array.isArray(mergedPreferences.interests) ? mergedPreferences.interests.filter((i): i is string => typeof i === 'string') : defaultPreferences.interests,\n useKnowledgeForStarters: typeof mergedPreferences.useKnowledgeForStarters === 'boolean' ? mergedPreferences.useKnowledgeForStarters : defaultPreferences.useKnowledgeForStarters,\n homeUrl: typeof mergedPreferences.homeUrl === 'string' ? mergedPreferences.homeUrl : defaultPreferences.homeUrl,\n };\n\n set({ preferences: validatedPreferences });\n await get().savePreferences();\n \n debugLogger.info(\"Preferences imported successfully\", { version: importData.version });\n return true;\n } catch (error) {\n debugLogger.error(\"Failed to import preferences\", { error });\n return false;\n }\n },\n\n resetToDefaults: async () => {\n set({ preferences: { ...defaultPreferences } });\n await get().savePreferences();\n debugLogger.info(\"Preferences reset to defaults\");\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-205A-DDC90F\nconst __banditFingerprint_store_modelStorets = 'BL-FP-C71D64-A364';\nconst __auditTrail_store_modelStorets = 'BL-AU-MGOIKVW5-X6L2';\n// File: modelStore.ts | Path: src/store/modelStore.ts | Hash: 205aa364\n\ninterface BrandingConfig {\n branding?: {\n logoBase64?: string;\n brandingText?: string;\n theme?: string;\n hasTransparentLogo?: boolean;\n };\n models?: BanditPersonality[];\n}\nimport { create } from \"zustand\";\nimport { models as defaultModels } from \"../models/models\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport { usePackageSettingsStore } from \"../store/packageSettingsStore\";\nimport { usePreferencesStore } from \"../store/preferencesStore\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\n\nexport interface BanditPersonality {\n name: string;\n tagline: string;\n systemPrompt: string;\n commands: string[];\n avatarBase64?: string | null;\n avatarPreset?: string;\n}\n\ntype BanditConfigEntry = {\n id?: string;\n model?: (BanditPersonality & { selectedModel?: string }) | { selectedModel?: string };\n branding?: { userSaved?: boolean; hasTransparentLogo?: boolean };\n deleted?: string[];\n avatarBase64?: string | null;\n [key: string]: unknown;\n};\n\ninterface ModelState {\n name: string;\n tagline: string;\n systemPrompt: string;\n commands: string[];\n avatarBase64: string | null;\n setModelName: (name: string) => void;\n setTagline: (tagline: string) => void;\n setSystemPrompt: (prompt: string) => void;\n addCommand: (command: string) => void;\n availableModels: BanditPersonality[];\n selectedModel: string;\n setSelectedModel: (model: string) => void;\n saveModel: () => void;\n resetModel: () => void;\n getCurrentModel: () => BanditPersonality | null;\n initModels: () => Promise<void>;\n hasTransparentLogo: boolean;\n setHasTransparentLogo: (value: boolean) => void;\n restoreDefaultModels: () => Promise<void>;\n restoreDeletedBanditModels: () => Promise<{ restored: string[]; hadNothingToRestore: boolean }>;\n handleBanditPersonalitiesPreferenceChange: (enabled: boolean) => Promise<void>;\n isLoading: boolean;\n setIsLoading: (loading: boolean) => void;\n isInitializing: boolean;\n setIsInitializing: (initializing: boolean) => void;\n setAvatarBase64: (value: string | null) => void;\n}\n\nexport const useModelStore = create<ModelState>((set, get) => ({\n name: \"\",\n tagline: \"\",\n systemPrompt: \"\",\n commands: [],\n avatarBase64: null,\n availableModels: [],\n selectedModel: \"\",\n hasTransparentLogo: true,\n isLoading: true,\n isInitializing: false,\n setIsLoading: (loading) => set({ isLoading: loading }),\n setIsInitializing: (initializing) => set({ isInitializing: initializing }),\n setModelName: (name) => set({ name: name }),\n setTagline: (tagline) => set({ tagline }),\n setSystemPrompt: (prompt) => set({ systemPrompt: prompt }),\n setAvatarBase64: (value) => set({ avatarBase64: value }),\n addCommand: (command) => set((state) => ({ commands: [...state.commands, command] })),\n setSelectedModel: (modelName) => {\n const selected = get().availableModels.find((m) => m.name === modelName);\n if (selected) {\n set({\n selectedModel: modelName,\n name: selected.name,\n tagline: selected.tagline,\n systemPrompt: selected.systemPrompt,\n commands: selected.commands,\n avatarBase64: selected.avatarBase64 ?? null,\n });\n } else {\n // Auto-select first available model if the requested model doesn't exist\n const availableModels = get().availableModels;\n const firstModel = availableModels.length > 0 ? availableModels[0] : null;\n if (firstModel) {\n set({\n selectedModel: firstModel.name,\n name: firstModel.name,\n tagline: firstModel.tagline,\n systemPrompt: firstModel.systemPrompt,\n commands: firstModel.commands,\n avatarBase64: firstModel.avatarBase64 ?? null,\n });\n }\n }\n\n // Persist selection for reloads\n (async () => {\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n try {\n const existing = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"main\", storeConfigs)) as\n | BanditConfigEntry\n | undefined;\n await indexedDBService.put(\n \"banditConfig\",\n 1,\n \"config\",\n {\n ...existing,\n id: \"main\",\n model: { ...(existing?.model ?? {}), selectedModel: modelName },\n },\n storeConfigs\n );\n } catch (err) {\n debugLogger.warn(\"setSelectedModel: failed to persist selected model\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n })();\n },\n saveModel: async () => {\n const state = get();\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n\n const newModel: BanditPersonality = {\n name: state.name,\n tagline: state.tagline,\n systemPrompt: state.systemPrompt,\n commands: state.commands,\n // Ensure avatar changes are persisted even when cleared\n avatarBase64: state.avatarBase64 ?? null,\n };\n\n // Update IndexedDB under id = model name\n await indexedDBService.put(\"banditConfig\", 1, \"config\", { id: newModel.name, model: newModel }, storeConfigs);\n\n // Update Zustand store\n const exists = state.availableModels.find((m) => m.name === newModel.name);\n if (!exists) {\n set((prevState) => ({\n availableModels: [...prevState.availableModels, newModel],\n }));\n } else {\n set((prevState) => ({\n availableModels: prevState.availableModels.map((m) =>\n m.name === newModel.name ? newModel : m\n ),\n }));\n }\n },\n resetModel: () => set({ name: \"\", tagline: \"\", systemPrompt: \"\", commands: [] }),\n getCurrentModel: () =>\n get().availableModels.find((m) => m.name === get().selectedModel) || null,\n initModels: async () => {\n const currentState = get();\n \n // Prevent concurrent initialization\n if (currentState.isInitializing) {\n debugLogger.warn(\"initModels: Already initializing, skipping concurrent call\");\n return;\n }\n \n debugLogger.info(\"initModels: starting initialization\");\n set({ isLoading: true, isInitializing: true });\n \n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n const entries: BanditConfigEntry[] = (await indexedDBService.getAll(\n \"banditConfig\",\n 1,\n \"config\",\n storeConfigs\n )) as BanditConfigEntry[];\n\n const mainEntry = entries.find((entry) => entry.id === \"main\");\n const modelEntries = entries.filter((entry) => entry.id !== \"main\" && entry.id !== \"deletedModels\");\n\n const deletedEntry = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"deletedModels\", storeConfigs)) as\n | BanditConfigEntry\n | undefined;\n const deletedModelNames = deletedEntry?.deleted ?? [];\n\n let allModels: BanditPersonality[] = [];\n let selectedModel = \"\";\n\n // STEP 1: Try to load from IndexedDB first\n if (modelEntries.length > 0) {\n debugLogger.info(\"Loading models from IndexedDB\");\n allModels = modelEntries.map((entry) => {\n const modelData = (entry.model as BanditPersonality | undefined) ?? (entry as unknown as BanditPersonality);\n return {\n name: modelData.name,\n tagline: modelData.tagline || \"\",\n systemPrompt: modelData.systemPrompt || \"\",\n commands: modelData.commands ?? [],\n // Fall back to legacy top-level avatar when the nested model config omitted it\n avatarBase64: modelData.avatarBase64 ?? entry.avatarBase64 ?? null,\n };\n }).filter(m => m.name && !deletedModelNames.includes(m.name));\n\n // Filter out Bandit personalities if banditModelsEnabled is false\n const preferences = usePreferencesStore.getState().preferences;\n if (!preferences.banditModelsEnabled) {\n const banditModelNames = defaultModels.map(m => m.name);\n allModels = allModels.filter(model => !banditModelNames.includes(model.name));\n debugLogger.info(\"Filtered out Bandit personalities (preference disabled)\", { \n filteredModels: banditModelNames \n });\n }\n\n selectedModel = mainEntry?.model?.selectedModel || (allModels.length > 0 ? allModels[0].name : \"\");\n debugLogger.info(\"Loaded models from IndexedDB:\", { models: allModels.map(m => m.name), selectedModel });\n \n // If no models remain after filtering deleted ones, try CDN\n if (allModels.length === 0) {\n debugLogger.info(\"No personalities remain after filtering deleted models, checking CDN config\");\n }\n } \n \n // STEP 2: If no models in IndexedDB OR no personalities remain after filtering, try CDN config\n if (modelEntries.length === 0 || allModels.length === 0) {\n debugLogger.info(\"No models in IndexedDB, checking CDN config\");\n const packageSettings = usePackageSettingsStore.getState().getSettings();\n let configModels: BrandingConfig | null = null;\n\n if (packageSettings?.brandingConfigUrl) {\n try {\n const response = await fetch(packageSettings.brandingConfigUrl);\n configModels = await response.json();\n } catch (err) {\n debugLogger.warn(\"Failed to load CDN config:\", { error: err });\n }\n }\n\n if (configModels?.models?.length) {\n debugLogger.info(\"Loading models from CDN config\");\n allModels = configModels.models.filter(m => !deletedModelNames.includes(m.name));\n \n // Check if Bandit personalities should be included\n const preferences = usePreferencesStore.getState().preferences;\n if (preferences.banditModelsEnabled) {\n // Add Bandit default personalities if they're not already present\n const cdnModelNames = allModels.map(m => m.name);\n const banditModelsToAdd = defaultModels.filter(banditModel => \n !cdnModelNames.includes(banditModel.name) && !deletedModelNames.includes(banditModel.name)\n );\n allModels = [...allModels, ...banditModelsToAdd];\n debugLogger.info(\"Added Bandit default personalities to CDN models\", { \n banditModels: banditModelsToAdd.map(m => m.name) \n });\n } else {\n // Filter out any Bandit personalities that might be in the CDN config\n const banditModelNames = defaultModels.map(m => m.name);\n allModels = allModels.filter(model => !banditModelNames.includes(model.name));\n debugLogger.info(\"Filtered out Bandit personalities from CDN config (preference disabled)\", {\n banditModels: banditModelNames\n });\n }\n \n selectedModel = allModels.length > 0 ? allModels[0].name : \"\";\n \n // Only set hasTransparentLogo from CDN if no user branding exists\n const existingConfig = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"main\", storeConfigs)) as BanditConfigEntry | undefined;\n const hasUserBranding = existingConfig?.branding?.userSaved;\n if (!hasUserBranding) {\n set({ hasTransparentLogo: configModels?.branding?.hasTransparentLogo ?? true });\n debugLogger.info(\"Set hasTransparentLogo from CDN config (no user branding)\");\n } else {\n debugLogger.info(\"Preserved user hasTransparentLogo setting (user branding exists)\");\n }\n \n // Save CDN models to IndexedDB for future use\n for (const model of allModels) {\n await indexedDBService.put(\"banditConfig\", 1, \"config\", { id: model.name, model }, storeConfigs);\n }\n \n debugLogger.info(\"Loaded and saved models from CDN config:\", { models: allModels.map(m => m.name) });\n } \n // STEP 3: Fall back to Bandit defaults (only if banditModelsEnabled is true)\n else {\n const preferences = usePreferencesStore.getState().preferences;\n if (preferences.banditModelsEnabled) {\n debugLogger.info(\"No CDN config available, loading Bandit defaults\");\n await get().restoreDefaultModels();\n set({ isLoading: false, isInitializing: false });\n return;\n } else {\n debugLogger.info(\"No CDN config available and Bandit personalities disabled, loading empty model list\");\n allModels = [];\n selectedModel = \"\";\n }\n }\n }\n\n // Set the models and selected model\n set({ availableModels: allModels });\n debugLogger.info(\"Setting selected model:\", { selectedModel });\n get().setSelectedModel(selectedModel);\n\n debugLogger.info(\"Model initialization complete\");\n set({ isLoading: false, isInitializing: false });\n },\n setHasTransparentLogo: (value) => set({ hasTransparentLogo: value }),\n restoreDefaultModels: async () => {\n debugLogger.debug(\"🧪 Restoring default models...\");\n set({ isLoading: true });\n \n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n \n // Clear existing models from state\n set({ availableModels: [] });\n \n // Clear deletedModels entry in IndexedDB\n try {\n await indexedDBService.delete(\"banditConfig\", 1, \"config\", \"deletedModels\", storeConfigs);\n debugLogger.info(\"restoreDefaultModels: Cleared deletedModels entry in IndexedDB\");\n } catch (err) {\n debugLogger.warn(\"restoreDefaultModels: Failed to clear deletedModels entry in IndexedDB\", { error: err });\n }\n \n let allModels: BanditPersonality[] = [];\n let selectedModel = \"\";\n \n // STEP 1: Try to load from CDN config first\n const packageSettings = usePackageSettingsStore.getState().getSettings();\n let configModels: BrandingConfig | null = null;\n \n if (packageSettings?.brandingConfigUrl) {\n debugLogger.debug(\"🔗 Attempting to load default models from CDN config...\");\n try {\n const response = await fetch(packageSettings.brandingConfigUrl);\n configModels = await response.json();\n } catch (err) {\n debugLogger.warn(\"Failed to load CDN config:\", { error: err });\n }\n }\n \n if (configModels?.models?.length) {\n // Use models from CDN config\n allModels = configModels.models;\n \n // Check if Bandit personalities should be included\n const preferences = usePreferencesStore.getState().preferences;\n if (preferences.banditModelsEnabled) {\n // Add Bandit default personalities if they're not already present\n const cdnModelNames = allModels.map(m => m.name);\n const banditModelsToAdd = defaultModels.filter(banditModel => \n !cdnModelNames.includes(banditModel.name)\n );\n allModels = [...allModels, ...banditModelsToAdd];\n debugLogger.info(\"restoreDefaultModels: Added Bandit personalities to CDN config\", { \n banditModels: banditModelsToAdd.map(m => m.name) \n });\n } else {\n // Filter out any Bandit personalities that might be in the CDN config\n const banditModelNames = defaultModels.map(m => m.name);\n allModels = allModels.filter(model => !banditModelNames.includes(model.name));\n debugLogger.info(\"restoreDefaultModels: Filtered out Bandit personalities (preference disabled)\", {\n banditModels: banditModelNames\n });\n }\n \n selectedModel = allModels.length > 0 ? allModels[0].name : \"\";\n \n // Only set hasTransparentLogo from CDN if no user branding exists\n try {\n const existingConfig = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"main\", storeConfigs)) as BanditConfigEntry | undefined;\n const hasUserBranding = existingConfig?.branding?.userSaved;\n if (!hasUserBranding) {\n set({ hasTransparentLogo: configModels?.branding?.hasTransparentLogo ?? true });\n debugLogger.info(\"restoreDefaultModels: Set hasTransparentLogo from CDN config (no user branding)\");\n } else {\n debugLogger.info(\"restoreDefaultModels: Preserved user hasTransparentLogo setting (user branding exists)\");\n }\n } catch (err) {\n // Fallback to CDN setting if we can't check IndexedDB\n set({ hasTransparentLogo: configModels?.branding?.hasTransparentLogo ?? true });\n debugLogger.warn(\"restoreDefaultModels: Using CDN hasTransparentLogo as fallback\", { error: err });\n }\n \n debugLogger.info(\"✅ Using default models from CDN config:\", { models: allModels.map(m => m.name) });\n } else {\n // STEP 2: Fall back to built-in Bandit defaults (only if enabled)\n const preferences = usePreferencesStore.getState().preferences;\n if (preferences.banditModelsEnabled) {\n allModels = defaultModels;\n selectedModel = allModels.length > 0 ? allModels[0].name : \"\";\n debugLogger.info(\"✅ Using built-in default Bandit personalities:\", { models: allModels.map(m => m.name) });\n } else {\n allModels = [];\n selectedModel = \"\";\n debugLogger.info(\"✅ Bandit personalities disabled, using empty model list\");\n }\n }\n \n // Persist each model to IndexedDB\n for (const model of allModels) {\n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: model.name,\n model,\n }, storeConfigs);\n }\n \n // Update Zustand state\n set({ availableModels: allModels });\n \n debugLogger.debug(\"🎯 Setting default selected model:\", { model: selectedModel });\n get().setSelectedModel(selectedModel);\n \n debugLogger.debug(\"✅ Default models restored and persisted to IndexedDB\");\n set({ isLoading: false });\n },\n restoreDeletedBanditModels: async () => {\n debugLogger.debug(\"🔄 Restoring deleted Bandit personalities...\");\n set({ isLoading: true });\n \n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n \n try {\n // Get current deleted models list\n const deletedEntry = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"deletedModels\", storeConfigs)) as\n | BanditConfigEntry\n | undefined;\n const deletedModelNames = deletedEntry?.deleted ?? [];\n \n debugLogger.info(\"Current deleted models:\", { deletedModelNames });\n \n // Find which Bandit personalities are deleted\n const deletedBanditModels = defaultModels.filter(banditModel => \n deletedModelNames.includes(banditModel.name)\n );\n \n debugLogger.info(\"Deleted Bandit personalities found:\", { \n deletedBanditModels: deletedBanditModels.map(m => m.name) \n });\n \n if (deletedBanditModels.length === 0) {\n debugLogger.info(\"No deleted Bandit personalities to restore\");\n set({ isLoading: false });\n return { restored: [], hadNothingToRestore: true };\n }\n \n // Remove Bandit personality names from deleted list\n const updatedDeletedNames = deletedModelNames.filter((name: string) => \n !defaultModels.some(banditModel => banditModel.name === name)\n );\n \n debugLogger.info(\"Updated deleted list after removing Bandit personalities:\", { \n updatedDeletedNames \n });\n \n // Update deleted models list in IndexedDB\n if (updatedDeletedNames.length > 0) {\n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: \"deletedModels\",\n deleted: updatedDeletedNames,\n }, storeConfigs);\n debugLogger.info(\"Updated deletedModels in IndexedDB\");\n } else {\n // If no models left in deleted list, remove the entry\n await indexedDBService.delete(\"banditConfig\", 1, \"config\", \"deletedModels\", storeConfigs);\n debugLogger.info(\"Removed deletedModels entry from IndexedDB (empty list)\");\n }\n \n // Check if Bandit personalities preference is enabled\n const preferences = usePreferencesStore.getState().preferences;\n debugLogger.info(\"Bandit personalities preference enabled:\", { enabled: preferences.banditModelsEnabled });\n \n if (!preferences.banditModelsEnabled) {\n debugLogger.info(\"⚠️ Bandit personalities preference is disabled. Personalities restored from deleted list but not added to available models until preference is enabled.\");\n set({ isLoading: false });\n return { restored: deletedBanditModels.map(m => m.name), hadNothingToRestore: false };\n }\n \n // Add restored Bandit personalities to current available models\n const currentModels = get().availableModels;\n debugLogger.info(\"Current available models:\", { \n currentModels: currentModels.map(m => m.name) \n });\n \n const restoredModels = deletedBanditModels.filter(banditModel => \n !currentModels.some(current => current.name === banditModel.name)\n );\n \n debugLogger.info(\"Models to restore:\", { \n restoredModels: restoredModels.map(m => m.name) \n });\n \n if (restoredModels.length === 0) {\n debugLogger.info(\"No new models to add (all restored models already present)\");\n set({ isLoading: false });\n return { restored: [], hadNothingToRestore: true };\n }\n \n // Persist restored models to IndexedDB\n for (const model of restoredModels) {\n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: model.name,\n model,\n }, storeConfigs);\n debugLogger.info(\"Persisted restored model to IndexedDB:\", { modelName: model.name });\n }\n \n // Update Zustand state\n const updatedAvailableModels = [...currentModels, ...restoredModels];\n set({ availableModels: updatedAvailableModels });\n \n debugLogger.info(\"✅ Restored deleted Bandit personalities:\", { \n restoredModels: restoredModels.map(m => m.name),\n totalModels: updatedAvailableModels.length\n });\n \n // If no model is currently selected and we have models now, select the first restored one\n const currentSelectedModel = get().selectedModel;\n if (!currentSelectedModel && updatedAvailableModels.length > 0) {\n const modelToSelect = restoredModels[0] || updatedAvailableModels[0];\n get().setSelectedModel(modelToSelect.name);\n debugLogger.info(\"Auto-selected model after restore:\", { modelName: modelToSelect.name });\n }\n \n return { restored: restoredModels.map(m => m.name), hadNothingToRestore: false };\n \n } catch (error) {\n debugLogger.error(\"Failed to restore deleted Bandit personalities\", { error });\n throw error;\n } finally {\n set({ isLoading: false });\n }\n },\n handleBanditPersonalitiesPreferenceChange: async (enabled: boolean) => {\n debugLogger.info(\"🔄 Handling Bandit personalities preference change\", { enabled });\n \n const currentModels = get().availableModels;\n const banditModelNames = defaultModels.map(m => m.name);\n \n if (enabled) {\n // Add Bandit personalities that aren't already present\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n \n // Get deleted models to avoid adding them back\n const deletedEntry = (await indexedDBService.get(\"banditConfig\", 1, \"config\", \"deletedModels\", storeConfigs)) as\n | BanditConfigEntry\n | undefined;\n const deletedModelNames = deletedEntry?.deleted ?? [];\n \n const modelsToAdd = defaultModels.filter(banditModel => \n !currentModels.some(current => current.name === banditModel.name) &&\n !deletedModelNames.includes(banditModel.name)\n );\n \n if (modelsToAdd.length > 0) {\n // Persist added models to IndexedDB\n for (const model of modelsToAdd) {\n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: model.name,\n model,\n }, storeConfigs);\n }\n \n const updatedModels = [...currentModels, ...modelsToAdd];\n set({ availableModels: updatedModels });\n \n debugLogger.info(\"✅ Added Bandit personalities\", { \n addedModels: modelsToAdd.map(m => m.name) \n });\n \n // If no model is selected and we added models, select the first one\n const currentSelectedModel = get().selectedModel;\n if (!currentSelectedModel && updatedModels.length > 0) {\n get().setSelectedModel(updatedModels[0].name);\n }\n }\n } else {\n // Remove Bandit personalities from current list\n const filteredModels = currentModels.filter(model => !banditModelNames.includes(model.name));\n set({ availableModels: filteredModels });\n \n debugLogger.info(\"✅ Removed Bandit personalities\", { \n removedModels: banditModelNames.filter(name => \n currentModels.some(model => model.name === name)\n )\n });\n \n // If the currently selected model was a Bandit model, select a different one\n const currentSelectedModel = get().selectedModel;\n if (currentSelectedModel && banditModelNames.includes(currentSelectedModel)) {\n const newSelectedModel = filteredModels.length > 0 ? filteredModels[0].name : \"\";\n get().setSelectedModel(newSelectedModel);\n debugLogger.info(\"🔄 Changed selected model after removing Bandit personalities\", { \n oldModel: currentSelectedModel, \n newModel: newSelectedModel \n });\n }\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-C0F4-A852E5\nconst __banditFingerprint_types_commontypests = 'BL-FP-DF0035-B29D';\nconst __auditTrail_types_commontypests = 'BL-AU-MGOIKVVR-SFSG';\n// File: common.types.ts | Path: src/services/ai-provider/types/common.types.ts | Hash: c0f4b29d\n\n/**\n * Common types used across all AI providers\n */\n\nexport interface AIMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface AIChatRequest {\n model: string;\n messages: AIMessage[];\n stream?: boolean;\n temperature?: number;\n maxTokens?: number;\n images?: string[];\n options?: Record<string, unknown>;\n}\n\nexport interface AIToolCall {\n id?: string;\n type?: 'function';\n function: {\n name: string;\n arguments: string | Record<string, unknown>;\n };\n}\n\nexport interface AIChatResponse {\n message: {\n content: string;\n role: 'assistant';\n tool_calls?: AIToolCall[];\n };\n done?: boolean;\n}\n\nexport interface AIGenerateRequest {\n model: string;\n prompt: string;\n stream?: boolean;\n options?: Record<string, unknown>;\n}\n\nexport interface AIGenerateResponse {\n response: string;\n done?: boolean;\n}\n\nexport interface AIModel {\n name: string;\n size?: number;\n details?: {\n format?: string;\n family?: string;\n families?: string[];\n parameter_size?: string;\n quantization_level?: string;\n };\n digest?: string;\n modified_at?: string;\n}\n\nexport interface AIProviderConfig {\n type: 'ollama' | 'openai' | 'azure-openai' | 'anthropic' | 'xai' | 'bandit' | 'gateway' | 'playground';\n baseUrl?: string;\n apiKey?: string;\n apiVersion?: string; // For Azure\n deploymentName?: string; // For Azure\n defaultModel?: string; // Preferred chat model when using direct providers\n anthropicVersion?: string;\n anthropicMaxTokens?: number;\n gatewayUrl?: string; // For gateway-based providers\n provider?: 'openai' | 'azure-openai' | 'anthropic' | 'ollama' | 'xai' | 'bandit' | 'playground'; // Which backend provider to use via gateway\n tokenFactory?: () => string | null;\n}\n\nexport enum AIProviderType {\n OLLAMA = 'ollama',\n OPENAI = 'openai',\n AZURE_OPENAI = 'azure-openai',\n ANTHROPIC = 'anthropic',\n XAI = 'xai',\n BANDIT = 'bandit',\n GATEWAY = 'gateway',\n PLAYGROUND = 'playground'\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-6CED-5122D4\nconst __banditFingerprint_ollama_ollamaservicets = 'BL-FP-3B6550-DAFC';\nconst __auditTrail_ollama_ollamaservicets = 'BL-AU-MGOIKVVW-1K0E';\n// File: ollama.service.ts | Path: src/services/ollama/ollama.service.ts | Hash: 6ceddafc\n\nimport { ChatRequest, ChatResponse, GenerateRequest, GenerateResponse, Model, ModelResponse } from \"./interfaces\";\nimport { catchError, from, lastValueFrom, map, Observable, of, shareReplay, switchMap, throwError, timeout } from \"rxjs\";\nimport { debugLogger } from \"../logging/debugLogger\";\n\nconst handleError = () => (obs: Observable<Response>) =>\n obs.pipe(\n switchMap((response) =>\n response.ok\n ? of(response)\n : throwError(() => new Error(`Request failed: ${response.status} ${response.statusText}`))\n )\n );\n\nconst parseResponseBody = async <T>(response: Response, responseType: 'json' | 'text'): Promise<T> => {\n if (responseType === 'text') {\n return (await response.text()) as unknown as T;\n }\n return (await response.json()) as T;\n};\n\nexport class OllamaService {\n\n constructor(\n private _baseUrl: string,\n private readonly _tokenFactory: () => string | null\n ) {\n if (!this._baseUrl) {\n this._baseUrl = 'http://localhost:11434'\n debugLogger.warn(`No base URL provided, using default: ${this._baseUrl}`);\n }\n }\n\n\n private _tryGatewayWithTimeout(args: {\n url: string,\n responseType: 'json' | 'text',\n timeoutMs: number,\n }): Observable<boolean> {\n const { url, responseType, timeoutMs } = args;\n const source = this._get(url, responseType)\n const mapped = source.pipe(\n catchError((e) => (e?.message.includes(\"401\") ? of(true) : of(false))),\n map(() => true),\n timeout(timeoutMs),\n );\n return mapped;\n }\n\n /**\n * Validates the availability of the service at the given base URL.\n * @param fallbackUrl The fallback URL to try if the base URL is not available.\n * @returns An object containing the URL and availability status.\n */\n async validateServiceAvailability(args: { fallbackUrl: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n const { fallbackUrl, timeoutMs } = args;\n const responseType = 'text';\n const availablility = {\n url: \"\",\n isAvailable: false,\n }\n try {\n debugLogger.debug(`Validating service availability at ${this._baseUrl}`);\n\n\n\n availablility.url = this._baseUrl;\n availablility.isAvailable = await lastValueFrom(\n this._tryGatewayWithTimeout({\n url: availablility.url,\n responseType,\n timeoutMs,\n })\n ) as boolean;\n if (!availablility.isAvailable) {\n throw new Error(`Service not available at ${this._baseUrl}`);\n }\n\n return availablility;\n } catch (e) {\n debugLogger.warn(`Service not available at ${this._baseUrl}, trying fallback URL: ${fallbackUrl}`);\n try {\n\n availablility.url = fallbackUrl;\n availablility.isAvailable = await lastValueFrom(\n this._tryGatewayWithTimeout({\n url: availablility.url,\n responseType,\n timeoutMs,\n })\n ) as boolean;\n\n if (!availablility.isAvailable) {\n throw new Error(`Service not available at ${fallbackUrl}`);\n }\n this._baseUrl = fallbackUrl;\n return availablility;\n } catch (e) {\n debugLogger.error(`Service not available at fallback URL: ${fallbackUrl}`);\n throw e;\n }\n }\n }\n\n\n generate(request: GenerateRequest): Observable<GenerateResponse> {\n const url = `${this._baseUrl}/api/generate`;\n return new Observable<GenerateResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: this._getHeaders(),\n body: JSON.stringify({ ...request, stream: request.stream === false ? false : true }),\n });\n task.then(response => {\n this._throwErrorIfNotOk(url, response);\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n if (buffer.trim() !== \"\") {\n try {\n observer.next(JSON.parse(buffer));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Final chunk parsing error (generate):', { buffer });\n }\n }\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n observer.next(JSON.parse(line));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Error parsing JSON line (generate):', { line });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n })\n .catch(err => observer.error(err));\n });\n }\n\n // generate(request: GenerateRequest): Observable<GenerateResponse> {\n // const url = `${this._baseUrl}/api/generate`;\n // return this._post<GenerateRequest, GenerateResponse>(url, request);\n // }\n\n chat(request: ChatRequest): Observable<ChatResponse> {\n const url = `${this._baseUrl}/api/chat`;\n return new Observable<ChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: this._getHeaders(),\n body: JSON.stringify({ ...request, stream: true }),\n });\n task.then(response => {\n this._throwErrorIfNotOk(url, response);\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n if (buffer.trim() !== \"\") {\n try {\n observer.next(JSON.parse(buffer));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Final chunk parsing error (chat):', { buffer });\n }\n }\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n observer.next(JSON.parse(line));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Error parsing JSON line (chat):', { line });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n })\n .catch(err => observer.error(err));\n });\n }\n\n\n listModels(): Observable<Model[]> {\n const url = `${this._baseUrl}/api/tags`;\n const response = this._get<ModelResponse>(url);\n const result = response.pipe(\n map(data => data.models),\n shareReplay(1));\n return result;\n }\n\n private _get<T>(url: string, responseType: 'json' | 'text' = 'json'): Observable<T> {\n const requestInit = {\n method: 'GET',\n headers: this._getHeaders(),\n }\n\n const response = from(fetch(url, requestInit));\n const handleFetchError = response.pipe(handleError());\n const data = handleFetchError.pipe(switchMap((res) => from(parseResponseBody<T>(res, responseType))));\n const result = data.pipe(shareReplay(1));\n\n return result;\n }\n\n private _post<TRequest, TResponse>(url: string, body: TRequest): Observable<TResponse> {\n const response = from(fetch(url, {\n method: 'POST',\n headers: this._getHeaders(),\n body: JSON.stringify(body),\n }));\n const handleFetchError = response.pipe(handleError());\n const json = handleFetchError.pipe(switchMap((res) => from(parseResponseBody<TResponse>(res, 'json'))));\n const result = json.pipe(shareReplay(1));\n return result;\n }\n private _throwErrorIfNotOk(url: string, response: Response) {\n if (!response.ok) {\n throw new Error(`POST ${url} failed: ${response.status} ${response.statusText}`);\n }\n }\n private _getHeaders() {\n const token = this._tokenFactory();\n \n if (!token) {\n debugLogger.warn('OllamaService: No token found, using empty string for Authorization header');\n }\n\n return {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token || ''}`\n };\n }\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-22FF-7E873B\nconst __banditFingerprint_providers_deprecatedts = 'BL-FP-DA6749-9B2A';\nconst __auditTrail_providers_deprecatedts = 'BL-AU-MGOIKVVQ-2ZKO';\n// File: deprecated.ts | Path: src/services/ai-provider/providers/deprecated.ts | Hash: 22ff9b2a\n\nimport { debugLogger } from '../../logging/debugLogger';\nimport { AIProviderConfig } from '../types/common.types';\n\n/**\n * Deprecation notices for direct provider implementations\n * \n * MIGRATION NOTICE: Direct provider implementations are being phased out in favor \n * of the new unified gateway architecture. Please migrate to gateway-based providers\n * for enhanced security, performance, and centralized management.\n * \n * See GATEWAY_MIGRATION_GUIDE.md for migration instructions.\n */\n\n/**\n * @deprecated Use GatewayProvider with provider: 'openai' instead\n * \n * Migration example:\n * ```typescript\n * // Old (deprecated)\n * const config = { type: 'openai', apiKey: 'sk-...', baseUrl: '...' };\n * \n * // New (recommended)\n * const config = { \n * type: 'gateway', \n * gatewayUrl: 'https://your-gateway.com',\n * provider: 'openai',\n * tokenFactory: () => localStorage.getItem('authToken')\n * };\n * ```\n */\nexport function deprecatedOpenAIProvider() {\n debugLogger.warn('⚠️ DEPRECATION WARNING: Direct OpenAI provider is deprecated. Please migrate to GatewayProvider with provider: \"openai\". See GATEWAY_MIGRATION_GUIDE.md for details.');\n}\n\n/**\n * @deprecated Use GatewayProvider with provider: 'azure-openai' instead\n * \n * Migration example:\n * ```typescript\n * // Old (deprecated)\n * const config = { \n * type: 'azure-openai', \n * baseUrl: 'https://your-resource.openai.azure.com',\n * apiKey: 'your-key',\n * apiVersion: '2024-02-15-preview',\n * deploymentName: 'gpt-4'\n * };\n * \n * // New (recommended)\n * const config = { \n * type: 'gateway', \n * gatewayUrl: 'https://your-gateway.com',\n * provider: 'azure-openai',\n * deploymentName: 'gpt-4',\n * apiVersion: '2024-02-15-preview',\n * tokenFactory: () => localStorage.getItem('authToken')\n * };\n * ```\n */\nexport function deprecatedAzureOpenAIProvider() {\n debugLogger.warn('⚠️ DEPRECATION WARNING: Direct Azure OpenAI provider is deprecated. Please migrate to GatewayProvider with provider: \"azure-openai\". See GATEWAY_MIGRATION_GUIDE.md for details.');\n}\n\n/**\n * @deprecated Use GatewayProvider with provider: 'anthropic' instead\n * \n * Migration example:\n * ```typescript\n * // Old (deprecated)\n * const config = { type: 'anthropic', apiKey: 'sk-ant-...', baseUrl: '...' };\n * \n * // New (recommended)\n * const config = { \n * type: 'gateway', \n * gatewayUrl: 'https://your-gateway.com',\n * provider: 'anthropic',\n * tokenFactory: () => localStorage.getItem('authToken')\n * };\n * ```\n */\nexport function deprecatedAnthropicProvider() {\n debugLogger.warn('⚠️ DEPRECATION WARNING: Direct Anthropic provider is deprecated. Please migrate to GatewayProvider with provider: \"anthropic\". See GATEWAY_MIGRATION_GUIDE.md for details.');\n}\n\n/**\n * @deprecated Use GatewayProvider with provider: 'ollama' instead for production environments\n * \n * Note: The direct Ollama provider will remain available for local development,\n * but for production deployments, use the gateway for better management.\n * \n * Migration example:\n * ```typescript\n * // Development (still supported)\n * const config = { type: 'ollama', baseUrl: 'http://localhost:11434' };\n * \n * // Production (recommended)\n * const config = { \n * type: 'gateway', \n * gatewayUrl: 'https://your-gateway.com',\n * provider: 'ollama',\n * tokenFactory: () => localStorage.getItem('authToken')\n * };\n * ```\n */\nexport function deprecatedOllamaProvider() {\n debugLogger.info('ℹ️ INFO: Direct Ollama provider is available for local development. For production environments, consider using GatewayProvider with provider: \"ollama\" for enhanced management. See GATEWAY_MIGRATION_GUIDE.md for details.');\n}\n\n/**\n * Display deprecation summary\n */\nexport function showDeprecationSummary() {\n debugLogger.warn(`\n🏗️ BANDIT ENGINE PROVIDER ARCHITECTURE UPDATE\n\nThe Bandit Engine is transitioning to a unified gateway architecture for enhanced:\n• Security (centralized API key management)\n• Performance (connection pooling, caching)\n• Monitoring (unified logging, health checks)\n• Scaling (load balancing, failover)\n\nMIGRATION REQUIRED:\n• OpenAI Provider → GatewayProvider (provider: 'openai')\n• Azure OpenAI Provider → GatewayProvider (provider: 'azure-openai') \n• Anthropic Provider → GatewayProvider (provider: 'anthropic')\n\nMIGRATION RECOMMENDED:\n• Ollama Provider → GatewayProvider (provider: 'ollama') for production\n\n📖 Full migration guide: GATEWAY_MIGRATION_GUIDE.md\n🆘 Need help? Check the troubleshooting section in the migration guide\n `);\n}\n\n/**\n * Check if provider config is using deprecated direct provider\n */\nexport function isDeprecatedProvider(config: AIProviderConfig | undefined): boolean {\n const deprecatedTypes = ['openai', 'azure-openai', 'anthropic'];\n return deprecatedTypes.includes(config?.type);\n}\n\n/**\n * Suggest gateway migration for deprecated config\n */\nexport function suggestGatewayMigration(config: AIProviderConfig): AIProviderConfig {\n if (!isDeprecatedProvider(config)) {\n return config; // No migration needed\n }\n\n const gatewayConfig: AIProviderConfig = {\n type: 'gateway',\n gatewayUrl: '${GATEWAY_URL}', // Replace with your gateway URL\n provider: config.type as 'openai' | 'azure-openai' | 'anthropic' | 'ollama',\n tokenFactory: () => localStorage.getItem('authToken')\n };\n\n // Preserve Azure-specific config\n if (config.type === 'azure-openai') {\n gatewayConfig.deploymentName = config.deploymentName;\n gatewayConfig.apiVersion = config.apiVersion;\n }\n\n debugLogger.info('🔄 Suggested gateway migration:', {\n from: config,\n to: gatewayConfig\n });\n\n return gatewayConfig;\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-A59E-4B6F9C\nconst __banditFingerprint_providers_ollamaproviderts = 'BL-FP-89E894-7B5E';\nconst __auditTrail_providers_ollamaproviderts = 'BL-AU-MGOIKVVQ-QJIU';\n// File: ollama.provider.ts | Path: src/services/ai-provider/providers/ollama.provider.ts | Hash: a59e7b5e\n\nimport { Observable, map } from 'rxjs';\nimport { OllamaService } from '../../ollama/ollama.service';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\nimport { deprecatedOllamaProvider } from './deprecated';\n\n/**\n * Ollama provider implementation that wraps the existing OllamaService\n */\nexport class OllamaProvider implements IAIProvider {\n private ollamaService: OllamaService;\n private config: AIProviderConfig;\n\n constructor(config: AIProviderConfig) {\n deprecatedOllamaProvider(); // Show info about gateway option for production\n this.config = config;\n const baseUrl = config.baseUrl || 'http://localhost:11434';\n debugLogger.info(\"OllamaProvider: Constructor\", { \n configBaseUrl: config.baseUrl,\n finalBaseUrl: baseUrl,\n hasTokenFactory: !!config.tokenFactory \n });\n this.ollamaService = new OllamaService(\n baseUrl,\n config.tokenFactory || (() => null)\n );\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n // Transform common request to Ollama-specific format\n const ollamaRequest = {\n model: request.model,\n messages: request.messages.map(msg => ({\n role: msg.role as 'system' | 'user' | 'assistant',\n content: msg.content\n })),\n stream: request.stream,\n options: request.options,\n images: request.images\n };\n\n return this.ollamaService.chat(ollamaRequest).pipe(\n map(response => ({\n message: {\n content: response.message.content,\n role: 'assistant' as const\n },\n done: response.done\n }))\n );\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n // Transform common request to Ollama-specific format\n const ollamaRequest = {\n model: request.model,\n prompt: request.prompt,\n stream: request.stream,\n options: request.options\n };\n\n return this.ollamaService.generate(ollamaRequest).pipe(\n map(response => ({\n response: response.response,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n return this.ollamaService.listModels().pipe(\n map(models => models.map(model => ({\n name: model.name,\n size: model.size,\n details: model.details,\n digest: model.digest,\n modified_at: model.modified_at\n })))\n );\n }\n\n async validateServiceAvailability(args: { \n fallbackUrl?: string; \n timeoutMs: number; \n }): Promise<{ url: string; isAvailable: boolean }> {\n return this.ollamaService.validateServiceAvailability({\n fallbackUrl: args.fallbackUrl || '',\n timeoutMs: args.timeoutMs\n });\n }\n\n getProviderType(): string {\n return AIProviderType.OLLAMA;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\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-E7EE-93DC85\nconst __banditFingerprint_providers_openaiproviderts = 'BL-FP-7E2188-DCC5';\nconst __auditTrail_providers_openaiproviderts = 'BL-AU-MGOIKVVQ-8GVP';\n// File: openai.provider.ts | Path: src/services/ai-provider/providers/openai.provider.ts | Hash: e7eedcc5\n\nimport { Observable, from, switchMap, map, throwError } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\nimport { deprecatedOpenAIProvider } from './deprecated';\n\ninterface OpenAIChatPayload {\n model: string;\n messages: AIChatRequest['messages'];\n stream: boolean;\n temperature?: number;\n max_tokens?: number;\n}\n\ninterface OpenAIStreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n };\n }>;\n}\n\ninterface OpenAIChatResponsePayload {\n choices?: Array<{\n message?: {\n content?: string;\n };\n }>;\n}\n\ninterface OpenAIModelListResponse {\n data: Array<{\n id: string;\n object?: string;\n }>;\n}\n\n/**\n * OpenAI provider implementation\n */\nexport class OpenAIProvider implements IAIProvider {\n private config: AIProviderConfig;\n private baseUrl: string;\n\n constructor(config: AIProviderConfig) {\n deprecatedOpenAIProvider(); // Show deprecation warning\n this.config = config;\n this.baseUrl = config.baseUrl || 'https://api.openai.com/v1';\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const url = `${this.baseUrl}/chat/completions`;\n \n const payload: OpenAIChatPayload = {\n model: request.model,\n messages: request.messages,\n stream: Boolean(request.stream),\n temperature: request.temperature,\n max_tokens: request.maxTokens\n };\n\n if (request.stream) {\n return this.streamChatRequest(url, payload);\n } else {\n return this.nonStreamChatRequest(url, payload);\n }\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n // For OpenAI, we'll use the chat endpoint with a single user message\n const chatRequest: AIChatRequest = {\n model: request.model,\n messages: [{ role: 'user', content: request.prompt }],\n stream: request.stream,\n options: request.options\n };\n\n return this.chat(chatRequest).pipe(\n map(response => ({\n response: response.message.content,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n const url = `${this.baseUrl}/models`;\n \n return from(fetch(url, {\n headers: this.getHeaders()\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`Failed to list models: ${response.status}`));\n }\n return from(response.json() as Promise<OpenAIModelListResponse>);\n }),\n map((data) =>\n data.data.map((model) => ({\n name: model.id,\n details: {\n format: 'openai',\n family: model.object\n }\n }))\n )\n );\n }\n\n async validateServiceAvailability(args: { \n fallbackUrl?: string; \n timeoutMs: number; \n }): Promise<{ url: string; isAvailable: boolean }> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const response = await fetch(`${this.baseUrl}/models`, {\n headers: this.getHeaders(),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n return {\n url: this.baseUrl,\n isAvailable: response.ok\n };\n } catch (error) {\n if (args.fallbackUrl) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const response = await fetch(`${args.fallbackUrl}/models`, {\n headers: this.getHeaders(),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n this.baseUrl = args.fallbackUrl;\n return {\n url: args.fallbackUrl,\n isAvailable: true\n };\n }\n } catch (fallbackError) {\n // Fall through to return unavailable\n }\n }\n\n return {\n url: this.baseUrl,\n isAvailable: false\n };\n }\n }\n\n getProviderType(): string {\n return AIProviderType.OPENAI;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private streamChatRequest(url: string, payload: OpenAIChatPayload): Observable<AIChatResponse> {\n return new Observable<AIChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n task.then(response => {\n if (!response.ok) {\n observer.error(new Error(`OpenAI request failed: ${response.status}`));\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim() && line.startsWith('data: ')) {\n const data = line.slice(6).trim();\n if (data === '[DONE]') {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n try {\n const parsed = JSON.parse(data) as OpenAIStreamChunk;\n const content = parsed.choices?.[0]?.delta?.content ?? '';\n if (content) {\n observer.next({\n message: { content, role: 'assistant' },\n done: false\n });\n }\n } catch (err) {\n debugLogger.error('Error parsing OpenAI stream data:', { data, error: err });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n }).catch(err => observer.error(err));\n });\n }\n\n private nonStreamChatRequest(url: string, payload: OpenAIChatPayload): Observable<AIChatResponse> {\n return from(fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`OpenAI request failed: ${response.status}`));\n }\n return from(response.json() as Promise<OpenAIChatResponsePayload>);\n }),\n map((data) => ({\n message: {\n content: data.choices?.[0]?.message?.content ?? '',\n role: 'assistant' as const\n },\n done: true\n }))\n );\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n \n if (this.config.apiKey) {\n headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n }\n\n return headers;\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-4A56-02BF87\nconst __banditFingerprint_providers_azureopenaiproviderts = 'BL-FP-51FF06-B29D';\nconst __auditTrail_providers_azureopenaiproviderts = 'BL-AU-MGOIKVVQ-070A';\n// File: azure-openai.provider.ts | Path: src/services/ai-provider/providers/azure-openai.provider.ts | Hash: 4a56b29d\n\nimport { Observable, from, switchMap, map, throwError } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\nimport { deprecatedAzureOpenAIProvider } from './deprecated';\n\ninterface AzureChatPayload {\n messages: AIChatRequest['messages'];\n stream: boolean;\n temperature?: number;\n max_tokens?: number;\n}\n\ninterface OpenAIStreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n };\n }>;\n}\n\ninterface OpenAIChatResponsePayload {\n choices?: Array<{\n message?: {\n content?: string;\n };\n }>;\n}\n/**\n * Azure OpenAI provider implementation\n */\nexport class AzureOpenAIProvider implements IAIProvider {\n private config: AIProviderConfig;\n private baseUrl: string;\n\n constructor(config: AIProviderConfig) {\n deprecatedAzureOpenAIProvider(); // Show deprecation warning\n this.config = config;\n if (!config.baseUrl || !config.deploymentName || !config.apiVersion) {\n throw new Error('Azure OpenAI requires baseUrl, deploymentName, and apiVersion');\n }\n this.baseUrl = config.baseUrl;\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const url = `${this.baseUrl}/openai/deployments/${this.config.deploymentName}/chat/completions?api-version=${this.config.apiVersion}`;\n \n const payload: AzureChatPayload = {\n messages: request.messages,\n stream: Boolean(request.stream),\n temperature: request.temperature,\n max_tokens: request.maxTokens\n };\n\n if (request.stream) {\n return this.streamChatRequest(url, payload);\n } else {\n return this.nonStreamChatRequest(url, payload);\n }\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n // For Azure OpenAI, we'll use the chat endpoint with a single user message\n const chatRequest: AIChatRequest = {\n model: request.model,\n messages: [{ role: 'user', content: request.prompt }],\n stream: request.stream,\n options: request.options\n };\n\n return this.chat(chatRequest).pipe(\n map(response => ({\n response: response.message.content,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n // Azure OpenAI doesn't have a direct models endpoint, return the deployment as a model\n const model: AIModel = {\n name: this.config.deploymentName || 'azure-deployment',\n details: {\n format: 'azure-openai',\n family: 'gpt'\n }\n };\n\n return new Observable<AIModel[]>(observer => {\n observer.next([model]);\n observer.complete();\n });\n }\n\n async validateServiceAvailability(args: { \n fallbackUrl?: string; \n timeoutMs: number; \n }): Promise<{ url: string; isAvailable: boolean }> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n // Test with a simple chat request\n const testUrl = `${this.baseUrl}/openai/deployments/${this.config.deploymentName}/chat/completions?api-version=${this.config.apiVersion}`;\n const response = await fetch(testUrl, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n messages: [{ role: 'user', content: 'test' }],\n max_tokens: 1\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n return {\n url: this.baseUrl,\n isAvailable: response.ok || response.status === 400 // 400 might be expected for the test\n };\n } catch (error) {\n if (args.fallbackUrl) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const testUrl = `${args.fallbackUrl}/openai/deployments/${this.config.deploymentName}/chat/completions?api-version=${this.config.apiVersion}`;\n const response = await fetch(testUrl, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n messages: [{ role: 'user', content: 'test' }],\n max_tokens: 1\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok || response.status === 400) {\n this.baseUrl = args.fallbackUrl;\n return {\n url: args.fallbackUrl,\n isAvailable: true\n };\n }\n } catch (fallbackError) {\n // Fall through to return unavailable\n }\n }\n\n return {\n url: this.baseUrl,\n isAvailable: false\n };\n }\n }\n\n getProviderType(): string {\n return AIProviderType.AZURE_OPENAI;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private streamChatRequest(url: string, payload: AzureChatPayload): Observable<AIChatResponse> {\n return new Observable<AIChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n task.then(response => {\n if (!response.ok) {\n observer.error(new Error(`Azure OpenAI request failed: ${response.status}`));\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim() && line.startsWith('data: ')) {\n const data = line.slice(6).trim();\n if (data === '[DONE]') {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n try {\n const parsed = JSON.parse(data) as OpenAIStreamChunk;\n const content = parsed.choices?.[0]?.delta?.content ?? '';\n if (content) {\n observer.next({\n message: { content, role: 'assistant' },\n done: false\n });\n }\n } catch (err) {\n debugLogger.error('Error parsing Azure OpenAI stream data:', { data, error: err });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n }).catch(err => observer.error(err));\n });\n }\n\n private nonStreamChatRequest(url: string, payload: AzureChatPayload): Observable<AIChatResponse> {\n return from(fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`Azure OpenAI request failed: ${response.status}`));\n }\n return from(response.json() as Promise<OpenAIChatResponsePayload>);\n }),\n map((data) => {\n const content = data.choices?.[0]?.message?.content ?? '';\n return {\n message: {\n content,\n role: 'assistant' as const\n },\n done: true\n };\n })\n );\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n \n if (this.config.apiKey) {\n headers['api-key'] = this.config.apiKey;\n }\n\n return headers;\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-8631-D26CFA\nconst __banditFingerprint_providers_anthropicproviderts = 'BL-FP-B138E7-AB87';\nconst __auditTrail_providers_anthropicproviderts = 'BL-AU-MGOIKVVP-762R';\n// File: anthropic.provider.ts | Path: src/services/ai-provider/providers/anthropic.provider.ts | Hash: 8631ab87\n\nimport { Observable, from, switchMap, map, throwError } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\nimport { deprecatedAnthropicProvider } from './deprecated';\n\ntype AnthropicRole = 'user' | 'assistant';\n\ninterface AnthropicChatMessagePayload {\n role: AnthropicRole;\n content: string;\n}\n\ninterface AnthropicChatPayload {\n model: string;\n messages: AnthropicChatMessagePayload[];\n system?: string;\n stream: boolean;\n temperature?: number;\n max_tokens: number;\n}\n\ninterface AnthropicStreamChunk {\n delta?: {\n text?: string;\n };\n}\n\ninterface AnthropicChatResponsePayload {\n content?: unknown;\n completion?: string;\n message?: {\n content?: string;\n };\n}\n\n/**\n * Anthropic provider implementation for direct API access\n */\nexport class AnthropicProvider implements IAIProvider {\n private config: AIProviderConfig;\n private baseUrl: string;\n private version: string;\n private defaultMaxTokens: number;\n\n constructor(config: AIProviderConfig) {\n deprecatedAnthropicProvider(); // Show deprecation warning\n this.config = config;\n this.baseUrl = config.baseUrl || 'https://api.anthropic.com/v1';\n this.version = typeof config.anthropicVersion === 'string' && config.anthropicVersion.trim()\n ? config.anthropicVersion.trim()\n : '2023-06-01';\n this.defaultMaxTokens =\n typeof config.anthropicMaxTokens === 'number' && config.anthropicMaxTokens > 0\n ? config.anthropicMaxTokens\n : 1024;\n this.config.anthropicVersion = this.version;\n this.config.anthropicMaxTokens = this.defaultMaxTokens;\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const url = `${this.baseUrl}/messages`;\n \n // Convert system messages to Anthropic format\n const systemMessage = request.messages.find(msg => msg.role === 'system');\n const userMessages = request.messages.filter(msg => msg.role !== 'system');\n \n const payload: AnthropicChatPayload = {\n model: request.model,\n messages: userMessages.map(msg => ({\n role: msg.role === 'user' ? 'user' : 'assistant',\n content: msg.content\n })),\n system: systemMessage?.content,\n stream: Boolean(request.stream),\n temperature: request.temperature,\n max_tokens: request.maxTokens ?? this.defaultMaxTokens\n };\n\n if (request.stream) {\n return this.streamChatRequest(url, payload);\n } else {\n return this.nonStreamChatRequest(url, payload);\n }\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n // For Anthropic, we'll use the messages endpoint with a single user message\n const chatRequest: AIChatRequest = {\n model: request.model,\n messages: [{ role: 'user', content: request.prompt }],\n stream: request.stream,\n options: request.options\n };\n\n return this.chat(chatRequest).pipe(\n map(response => ({\n response: response.message.content,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n // Anthropic doesn't have a public models endpoint, return common models\n const commonModels: AIModel[] = [\n {\n name: 'claude-3-5-sonnet-20241022',\n details: {\n format: 'anthropic',\n family: 'claude-3.5'\n }\n },\n {\n name: 'claude-3-5-haiku-20241022',\n details: {\n format: 'anthropic',\n family: 'claude-3.5'\n }\n },\n {\n name: 'claude-3-opus-20240229',\n details: {\n format: 'anthropic',\n family: 'claude-3'\n }\n },\n {\n name: 'claude-3-sonnet-20240229',\n details: {\n format: 'anthropic',\n family: 'claude-3'\n }\n },\n {\n name: 'claude-3-haiku-20240307',\n details: {\n format: 'anthropic',\n family: 'claude-3'\n }\n }\n ];\n\n return new Observable<AIModel[]>(observer => {\n observer.next(commonModels);\n observer.complete();\n });\n }\n\n async validateServiceAvailability(args: { \n fallbackUrl?: string; \n timeoutMs: number; \n }): Promise<{ url: string; isAvailable: boolean }> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n // Test with a simple messages request\n const response = await fetch(`${this.baseUrl}/messages`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n model: 'claude-3-haiku-20240307',\n messages: [{ role: 'user', content: 'test' }],\n max_tokens: 1\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n return {\n url: this.baseUrl,\n isAvailable: response.ok || response.status === 400 // 400 might be expected for the test\n };\n } catch (error) {\n if (args.fallbackUrl) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const response = await fetch(`${args.fallbackUrl}/messages`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n model: 'claude-3-haiku-20240307',\n messages: [{ role: 'user', content: 'test' }],\n max_tokens: 1\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok || response.status === 400) {\n this.baseUrl = args.fallbackUrl;\n return {\n url: args.fallbackUrl,\n isAvailable: true\n };\n }\n } catch (fallbackError) {\n // Fall through to return unavailable\n }\n }\n\n return {\n url: this.baseUrl,\n isAvailable: false\n };\n }\n }\n\n getProviderType(): string {\n return AIProviderType.ANTHROPIC;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private streamChatRequest(url: string, payload: AnthropicChatPayload): Observable<AIChatResponse> {\n return new Observable<AIChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n task.then(response => {\n if (!response.ok) {\n observer.error(new Error(`Anthropic request failed: ${response.status}`));\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim() && line.startsWith('data: ')) {\n const data = line.slice(6).trim();\n if (data === '[DONE]') {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n try {\n const parsed = JSON.parse(data) as AnthropicStreamChunk;\n // Anthropic streaming format may differ, adjust as needed\n const content = parsed.delta?.text || '';\n if (content) {\n observer.next({\n message: { content, role: 'assistant' },\n done: false\n });\n }\n } catch (err) {\n debugLogger.error('Error parsing Anthropic stream data:', { data, error: err });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n }).catch(err => observer.error(err));\n });\n }\n\n private nonStreamChatRequest(url: string, payload: AnthropicChatPayload): Observable<AIChatResponse> {\n return from(fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`Anthropic request failed: ${response.status}`));\n }\n return from(response.json() as Promise<AnthropicChatResponsePayload>);\n }),\n map((data) => ({\n message: {\n content: this.extractContentText(data),\n role: 'assistant' as const\n },\n done: true\n }))\n );\n }\n\n private extractContentText(payload: AnthropicChatResponsePayload): string {\n const { content } = payload;\n\n if (Array.isArray(content)) {\n for (const entry of content) {\n if (typeof entry === 'string') {\n return entry;\n }\n if (entry && typeof entry === 'object' && 'text' in entry) {\n const text = (entry as { text?: unknown }).text;\n if (typeof text === 'string') {\n return text;\n }\n }\n }\n } else if (typeof content === 'string') {\n return content;\n }\n\n if (typeof payload.completion === 'string') {\n return payload.completion;\n }\n\n if (payload.message && typeof payload.message.content === 'string') {\n return payload.message.content;\n }\n\n return '';\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'anthropic-version': this.version\n };\n \n if (this.config.apiKey) {\n headers['x-api-key'] = this.config.apiKey;\n }\n\n return headers;\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-809E-685A92\nconst __banditFingerprint_gateway_gatewayservicets = 'BL-FP-6DB2F9-8464';\nconst __auditTrail_gateway_gatewayservicets = 'BL-AU-MGOIKVVT-6725';\n// File: gateway.service.ts | Path: src/services/gateway/gateway.service.ts | Hash: 809e8464\n\nimport axios, { AxiosError, AxiosHeaders, AxiosInstance } from \"axios\";\nimport {\n GatewayChatRequest,\n GatewayChatResponse,\n GatewayGenerateRequest,\n GatewayGenerateResponse,\n GatewayModel,\n GatewayModelsResponse,\n GatewayHealthResponse,\n GatewayMemoryResponse\n} from \"./interfaces\";\nimport { FeedbackRequest, FeedbackResponse } from \"./feedback.interfaces\";\nimport { catchError, from, lastValueFrom, map, Observable, of, shareReplay, timeout } from \"rxjs\";\nimport { debugLogger } from \"../logging/debugLogger\";\n\ninterface GatewayHttpErrorResponse {\n status: number;\n statusText: string;\n data: unknown;\n url: string;\n}\n\ntype GatewayHttpError = Error & { response: GatewayHttpErrorResponse };\n\nexport class GatewayService {\n private readonly _client: AxiosInstance;\n\n constructor(\n private _baseUrl: string,\n private readonly _tokenFactory: () => string | null,\n private readonly _feedbackEmail?: string\n ) {\n if (!this._baseUrl) {\n this._baseUrl = 'http://localhost:5000'\n debugLogger.warn(`No gateway URL provided, using default: ${this._baseUrl}`);\n }\n \n // Ensure baseUrl doesn't end with slash\n this._baseUrl = this._baseUrl.replace(/\\/$/, '');\n\n // Remove /api suffix if it exists to avoid double /api/api paths\n if (this._baseUrl.endsWith('/api')) {\n this._baseUrl = this._baseUrl.slice(0, -4);\n debugLogger.info(`Removed /api suffix from gateway URL: ${this._baseUrl}`);\n }\n\n this._client = this._createAxiosClient();\n }\n\n private _createAxiosClient(): AxiosInstance {\n const instance = axios.create({\n baseURL: this._baseUrl,\n headers: {\n 'Content-Type': 'application/json'\n }\n });\n\n instance.interceptors.request.use((config) => {\n const token = this._tokenFactory();\n const headers = AxiosHeaders.from(config.headers ?? {});\n\n if (!headers.has('Content-Type')) {\n headers.set('Content-Type', 'application/json');\n }\n\n if (token && token.trim()) {\n headers.set('Authorization', `Bearer ${token}`);\n } else if (headers.has('Authorization')) {\n headers.delete('Authorization');\n }\n\n config.headers = headers;\n return config;\n });\n\n instance.interceptors.response.use(\n (response) => response,\n (error) => Promise.reject(this._normalizeAxiosError(error))\n );\n\n return instance;\n }\n\n private _normalizeAxiosError(error: AxiosError): Error {\n if (error.response) {\n return this._createHttpError(\n `Request failed: ${error.response.status} ${error.response.statusText ?? \"\"}`,\n {\n status: error.response.status,\n statusText: error.response.statusText ?? \"\",\n data: error.response.data,\n url: error.config?.url ?? \"\"\n }\n );\n }\n\n if (error.request) {\n return new Error(`No response received from gateway: ${error.message}`);\n }\n\n return new Error(error.message);\n }\n\n private _createHttpError(message: string, response: GatewayHttpErrorResponse): GatewayHttpError {\n return Object.assign(new Error(message), { response }) as GatewayHttpError;\n }\n\n private _setBaseUrl(url: string) {\n this._baseUrl = url;\n this._client.defaults.baseURL = url;\n }\n\n private _tryGatewayWithTimeout(args: {\n url: string,\n responseType: 'json' | 'text',\n timeoutMs: number,\n }): Observable<boolean> {\n const { url, responseType, timeoutMs } = args;\n const source = this._get(url, responseType)\n const mapped = source.pipe(\n catchError((e) => (e?.message.includes(\"401\") ? of(true) : of(false))),\n map(() => true),\n timeout(timeoutMs),\n );\n return mapped;\n }\n\n /**\n * Validates the availability of the gateway service.\n * @param fallbackUrl The fallback URL to try if the base URL is not available.\n * @returns An object containing the URL and availability status.\n */\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n const { fallbackUrl, timeoutMs } = args;\n const responseType = 'json';\n const availability = {\n url: \"\",\n isAvailable: false,\n }\n\n try {\n debugLogger.debug(`Validating gateway service availability at ${this._baseUrl}`);\n\n availability.url = this._baseUrl;\n availability.isAvailable = await lastValueFrom(\n this._tryGatewayWithTimeout({\n url: `${availability.url}/api/health`,\n responseType,\n timeoutMs,\n })\n ) as boolean;\n \n if (!availability.isAvailable) {\n throw new Error(`Gateway service not available at ${this._baseUrl}`);\n }\n\n return availability;\n } catch (e) {\n if (fallbackUrl) {\n debugLogger.warn(`Gateway service not available at ${this._baseUrl}, trying fallback URL: ${fallbackUrl}`);\n try {\n availability.url = fallbackUrl.replace(/\\/$/, '');\n availability.isAvailable = await lastValueFrom(\n this._tryGatewayWithTimeout({\n url: `${availability.url}/api/health`,\n responseType,\n timeoutMs,\n })\n ) as boolean;\n\n if (!availability.isAvailable) {\n throw new Error(`Gateway service not available at ${fallbackUrl}`);\n }\n \n this._setBaseUrl(availability.url);\n return availability;\n } catch (e) {\n debugLogger.error(`Gateway service not available at fallback URL: ${fallbackUrl}`);\n throw e;\n }\n } else {\n debugLogger.error(`Gateway service not available and no fallback URL provided`);\n throw e;\n }\n }\n }\n\n /**\n * Get gateway health status and available providers\n */\n getHealth(): Observable<GatewayHealthResponse> {\n const url = `${this._baseUrl}/api/health`;\n return this._get<GatewayHealthResponse>(url);\n }\n\n /**\n * Chat completion using the gateway API\n */\n chat(request: GatewayChatRequest): Observable<GatewayChatResponse> {\n // Use provider-specific endpoint if provider is specified\n // For Ollama specifically, use /chat instead of /chat/completions\n const endpoint =\n request.provider === 'ollama'\n ? `/api/${request.provider}/chat`\n : request.provider === 'playground'\n ? '/api/playground/chat/completions'\n : request.provider\n ? `/api/${request.provider}/chat/completions`\n : '/api/chat/completions';\n const fallbackEndpoint =\n request.provider === 'bandit' ? '/completions' : null;\n const normalizedModel =\n request.provider === 'bandit'\n ? (() => {\n const trimmed = (request.model ?? '').replace(/^bandit:/, '').trim();\n return trimmed !== '' ? trimmed : 'bandit-core-1';\n })()\n : request.model;\n \n const requestBody = { ...request, model: normalizedModel, stream: request.stream !== false };\n \n return new Observable<GatewayChatResponse>(observer => {\n const controller = new AbortController();\n const handleStreamingResponse = async (response: Response) => {\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n if (buffer.trim() !== \"\") {\n try {\n const finalResponse = JSON.parse(buffer);\n observer.next(finalResponse);\n } catch (err) {\n debugLogger.error('GatewayService chat final chunk parsing error', { buffer, error: err });\n observer.error(err);\n }\n }\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed) {\n // Handle both SSE format (OpenAI-style) and direct JSON (Ollama-style)\n let data = trimmed;\n \n if (trimmed.startsWith('data: ')) {\n data = trimmed.slice(6); // Remove 'data: ' prefix for SSE format\n if (data === '[DONE]') {\n observer.complete();\n return;\n }\n }\n \n try {\n const parsed = JSON.parse(data);\n \n // Transform Ollama chat format to OpenAI-compatible format\n if (request.provider === 'ollama' && parsed.message) {\n const transformed: GatewayChatResponse = {\n id: `chatcmpl-${Date.now()}`,\n object: 'chat.completion.chunk',\n created: Math.floor(new Date(parsed.created_at || Date.now()).getTime() / 1000),\n model: parsed.model,\n choices: [{\n index: 0,\n delta: {\n role: parsed.message.role,\n content: parsed.message.content,\n tool_calls: parsed.message.tool_calls\n },\n finish_reason: parsed.done ? (parsed.done_reason || 'stop') : null\n }]\n };\n \n if (parsed.done && parsed.total_duration) {\n transformed.usage = {\n prompt_tokens: parsed.prompt_eval_count || 0,\n completion_tokens: parsed.eval_count || 0,\n total_tokens: (parsed.prompt_eval_count || 0) + (parsed.eval_count || 0)\n };\n }\n \n observer.next(transformed);\n } else {\n // For non-Ollama providers or already transformed responses\n observer.next(parsed);\n }\n } catch (err) {\n debugLogger.error('GatewayService chat stream chunk parsing error', {\n line: trimmed,\n rawData: data,\n error: err\n });\n observer.error(err);\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n };\n\n const sendRequest = (targetEndpoint: string, allowFallback: boolean) => {\n const url = `${this._baseUrl}${targetEndpoint}`;\n\n debugLogger.debug(`Gateway chat request to ${url} with provider: ${request.provider || 'default'}`, {\n model: normalizedModel,\n messageCount: request.messages.length,\n hasImages: !!(request.images && request.images.length > 0),\n imageCount: request.images?.length || 0\n });\n\n fetch(url, {\n method: 'POST',\n headers: this._getHeaders(),\n body: JSON.stringify(requestBody),\n signal: controller.signal,\n })\n .then(async (response) => {\n debugLogger.debug(`Gateway chat response status: ${response.status} for provider: ${request.provider || 'default'}`);\n\n if (response.status === 404 && allowFallback && fallbackEndpoint) {\n debugLogger.warn('GatewayService chat endpoint returned 404, attempting fallback route', {\n provider: request.provider,\n attemptedEndpoint: targetEndpoint,\n fallbackEndpoint\n });\n sendRequest(fallbackEndpoint, false);\n return;\n }\n\n if (!response.ok) {\n // Handle error response properly with body parsing\n let errorText = '';\n let errorData: unknown = null;\n \n try {\n // First, try to read the response body\n errorText = await response.text();\n debugLogger.error('GatewayService chat error response body', {\n status: response.status,\n statusText: response.statusText,\n url: response.url,\n body: errorText\n });\n } catch (readError) {\n debugLogger.error('GatewayService chat failed to read error response body', { error: readError });\n errorText = `Request failed with status ${response.status}`;\n }\n \n // Then, try to parse as JSON for better error info\n try {\n errorData = JSON.parse(errorText);\n debugLogger.error('GatewayService chat parsed error payload', errorData);\n } catch (parseError) {\n debugLogger.error('GatewayService chat error payload was not valid JSON');\n errorData = { message: errorText };\n }\n \n // Create an error object that mimics an HTTP response error for the notification service\n const error = this._createHttpError(\n `POST ${url} failed: ${response.status} ${response.statusText ?? \"\"}`,\n {\n status: response.status,\n statusText: response.statusText ?? \"\",\n data: errorData,\n url\n }\n );\n \n throw error;\n }\n\n await handleStreamingResponse(response);\n })\n .catch(err => {\n debugLogger.error('GatewayService chat fetch error', {\n error: err,\n url,\n provider: request.provider\n });\n observer.error(err);\n });\n };\n\n sendRequest(endpoint, true);\n\n // Teardown: abort the request/stream on unsubscribe\n return () => {\n try { controller.abort(); } catch {}\n };\n });\n }\n\n /**\n * Text generation using the gateway API\n */\n generate(request: GatewayGenerateRequest): Observable<GatewayGenerateResponse> {\n // Use provider-specific endpoint if provider is specified\n const endpoint = request.provider ? `/api/${request.provider}/generate` : '/api/generate';\n const url = `${this._baseUrl}${endpoint}`;\n const normalizedModel =\n request.provider === 'bandit'\n ? (() => {\n const trimmed = (request.model ?? '').replace(/^bandit:/, '').trim();\n return trimmed !== '' ? trimmed : 'bandit-core-1';\n })()\n : request.model;\n \n debugLogger.debug(`Gateway generate request to ${url} with provider: ${request.provider || 'default'}`, {\n model: normalizedModel\n });\n \n return new Observable<GatewayGenerateResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: this._getHeaders(),\n body: JSON.stringify({ ...request, model: normalizedModel, stream: request.stream !== false }),\n });\n \n task.then(async (response) => {\n if (!response.ok) {\n // Handle error response properly with body parsing\n let errorText = '';\n let errorData: unknown = null;\n \n try {\n // First, try to read the response body\n errorText = await response.text();\n } catch (readError) {\n errorText = `Request failed with status ${response.status}`;\n }\n \n // Then, try to parse as JSON for better error info\n try {\n errorData = JSON.parse(errorText);\n } catch (parseError) {\n errorData = { message: errorText };\n }\n \n // Create an error object that mimics an HTTP response error for the notification service\n const error = this._createHttpError(\n `POST ${url} failed: ${response.status} ${response.statusText ?? \"\"}`,\n {\n status: response.status,\n statusText: response.statusText ?? \"\",\n data: errorData,\n url\n }\n );\n \n throw error;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n \n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n if (buffer.trim() !== \"\") {\n try {\n observer.next(JSON.parse(buffer));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Final chunk parsing error (gateway generate):', { buffer });\n }\n }\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n observer.next(JSON.parse(line));\n } catch (err) {\n observer.error(err);\n debugLogger.error('Error parsing JSON line (gateway generate):', { line });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n })\n .catch(err => observer.error(err));\n });\n }\n\n /**\n * List all available models from all providers\n */\n listModels(): Observable<GatewayModel[]> {\n const url = `${this._baseUrl}/api/models`;\n const response = this._get<GatewayModelsResponse>(url);\n const result = response.pipe(\n map(data => data.models),\n shareReplay(1)\n );\n return result;\n }\n\n /**\n * List models for a specific provider\n */\n listModelsByProvider(provider: string): Observable<GatewayModel[]> {\n const url = `${this._baseUrl}/api/models/${provider}`;\n const response = this._get<GatewayModelsResponse>(url);\n const result = response.pipe(\n map(data => data.models),\n shareReplay(1)\n );\n return result;\n }\n\n getMemory(): Observable<GatewayMemoryResponse> {\n const url = `${this._baseUrl}/api/memory`;\n return this._get<GatewayMemoryResponse>(url);\n }\n\n private _get<T>(url: string, responseType: 'json' | 'text' = 'json'): Observable<T> {\n const request = this._client.get<T>(url, { responseType });\n return from(request).pipe(\n map(response => response.data as T),\n shareReplay(1)\n );\n }\n\n private _post<TRequest, TResponse>(url: string, body: TRequest): Observable<TResponse> {\n const request = this._client.post<TResponse>(url, body);\n return from(request).pipe(\n map(response => response.data),\n shareReplay(1)\n );\n }\n\n private _getHeaders() {\n const rawToken = this._tokenFactory();\n const headers: { [key: string]: string } = {\n 'Content-Type': 'application/json'\n };\n\n if (!rawToken) {\n debugLogger.warn('GatewayService: No token found, skipping Authorization header');\n return headers;\n }\n\n const token = rawToken.trim();\n if (token === '') {\n debugLogger.warn('GatewayService: Token factory returned empty string');\n return headers;\n }\n\n if (/^(Bearer|ApiKey)\\s+/i.test(token)) {\n headers['Authorization'] = token;\n debugLogger.debug('GatewayService: Authorization header set with explicit scheme');\n return headers;\n }\n\n if (this._isLikelyBanditApiKey(token)) {\n headers['Authorization'] = `ApiKey ${token}`;\n headers['X-Burtson-Api-Key'] = token;\n debugLogger.debug('GatewayService: Authorization header set using API key');\n return headers;\n }\n\n if (this._isLikelyJwt(token)) {\n headers['Authorization'] = `Bearer ${token}`;\n debugLogger.debug('GatewayService: Authorization header set using bearer token');\n return headers;\n }\n\n // Default to bearer scheme to avoid breaking other providers\n headers['Authorization'] = `Bearer ${token}`;\n debugLogger.debug('GatewayService: Authorization header defaulted to bearer scheme');\n return headers;\n }\n\n private _isLikelyJwt(token: string): boolean {\n const segments = token.split('.');\n return segments.length === 3 && segments.every((segment) => segment.length > 0);\n }\n\n private _isLikelyBanditApiKey(value: string): boolean {\n return /^bai_[a-z0-9]{10,}$/i.test(value);\n }\n\n /**\n * Submit feedback to the gateway API\n */\n submitFeedback(feedback: FeedbackRequest): Observable<FeedbackResponse> {\n const url = `${this._baseUrl}/api/feedback`;\n \n debugLogger.debug('Gateway feedback submission', {\n category: feedback.category,\n priority: feedback.priority,\n hasImages: !!(feedback.images && feedback.images.length > 0),\n hasAttachments: !!(feedback.attachments && feedback.attachments.length > 0)\n });\n\n return from(\n this._client.post<FeedbackResponse>(url, feedback).then(response => response.data)\n ).pipe(\n catchError(error => {\n debugLogger.error('Feedback submission failed, using email fallback', error);\n\n const fallbackResponse: FeedbackResponse = {\n id: `fallback-${Date.now()}`,\n status: 'submitted',\n message: 'Feedback submission failed. Opening email client as fallback.',\n mailtoUrl: this._generateMailtoUrl(feedback)\n };\n return of(fallbackResponse);\n })\n );\n }\n\n /**\n * Generate a mailto URL as fallback for feedback submission\n */\n private _generateMailtoUrl(feedback: FeedbackRequest): string {\n const subject = encodeURIComponent(`[${feedback.category.toUpperCase()}] ${feedback.title}`);\n \n let body = `Category: ${feedback.category}\\n`;\n body += `Priority: ${feedback.priority}\\n`;\n \n if (feedback.annoyanceLevel) {\n const annoyanceLabels = {\n 1: '😊 Not annoying at all',\n 2: '😐 Slightly annoying',\n 3: '🙄 Moderately annoying', \n 4: '😠 Very annoying',\n 5: '🤬 Extremely annoying'\n };\n body += `Annoyance Level: ${feedback.annoyanceLevel}/5 - ${annoyanceLabels[feedback.annoyanceLevel as keyof typeof annoyanceLabels]}\\n`;\n }\n \n body += `\\nDescription:\\n${feedback.description}\\n\\n`;\n \n if (feedback.sessionInfo) {\n body += `Session Info:\\n`;\n body += `- Model: ${feedback.sessionInfo.currentModel}\\n`;\n body += `- Provider: ${feedback.sessionInfo.currentProvider}\\n`;\n body += `- Conversation: ${feedback.sessionInfo.conversationId}\\n`;\n body += `- Timestamp: ${feedback.sessionInfo.timestamp}\\n\\n`;\n }\n \n if (feedback.browserInfo) {\n body += `Browser Info:\\n`;\n body += `- Name: ${feedback.browserInfo.name}\\n`;\n body += `- Version: ${feedback.browserInfo.version}\\n`;\n body += `- Platform: ${feedback.browserInfo.platform}\\n\\n`;\n }\n \n if (feedback.userAgent) {\n body += `User Agent: ${feedback.userAgent}\\n\\n`;\n }\n \n if (feedback.contactEmail) {\n body += `Contact Email: ${feedback.contactEmail}\\n\\n`;\n }\n \n if (feedback.images && feedback.images.length > 0) {\n body += `📎 IMAGE ATTACHMENT:\\n`;\n body += `Please paste your clipboard contents here (Ctrl+V or Cmd+V)\\n\\n`;\n }\n \n if (feedback.attachments && feedback.attachments.length > 0) {\n body += `📎 IMPORTANT - FILES TO ATTACH:\\n`;\n body += `Please attach the following ${feedback.attachments.length} file(s) to this email:\\n`;\n feedback.attachments.forEach((attachment, index) => {\n body += ` • File ${index + 1}: ${attachment.name || `[Attachment ${index + 1}]`}\\n`;\n });\n body += `\\n(Note: Files cannot be automatically included in email links)\\n\\n`;\n }\n \n body += `---\\nGenerated by Bandit AI Feedback System`;\n \n const encodedBody = encodeURIComponent(body);\n const toEmail = this._feedbackEmail || 'feedback@burtson.ai'; // Use custom email or default\n \n return `mailto:${toEmail}?subject=${subject}&body=${encodedBody}`;\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-1D46-424011\nconst __banditFingerprint_gateway_openaigatewayservicets = 'BL-FP-DEEDDF-C675';\nconst __auditTrail_gateway_openaigatewayservicets = 'BL-AU-MGOIKVVU-ZD2R';\n// File: openai-gateway.service.ts | Path: src/services/gateway/openai-gateway.service.ts | Hash: 1d46c675\n\nimport { GatewayService } from './gateway.service';\nimport { GatewayChatRequest, GatewayChatResponse, GatewayGenerateRequest, GatewayGenerateResponse, GatewayModel } from './interfaces';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface OpenAIMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n name?: string;\n}\n\nexport interface OpenAIChatRequest {\n model: string;\n messages: OpenAIMessage[];\n stream?: boolean;\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n stop?: string | string[];\n}\n\nexport class OpenAIGatewayService {\n private _gatewayService: GatewayService;\n\n constructor(\n gatewayUrl: string,\n tokenFactory: () => string | null\n ) {\n this._gatewayService = new GatewayService(gatewayUrl, tokenFactory);\n debugLogger.info('OpenAIGatewayService initialized', { gatewayUrl });\n }\n\n /**\n * Validates the availability of the gateway service for OpenAI\n */\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n return this._gatewayService.validateServiceAvailability(args);\n }\n\n /**\n * Chat completion using OpenAI through the gateway\n */\n chat(request: OpenAIChatRequest): Observable<GatewayChatResponse> {\n const gatewayRequest: GatewayChatRequest = {\n ...request,\n provider: 'openai'\n };\n\n debugLogger.debug('OpenAI Gateway chat request', { \n model: request.model, \n messageCount: request.messages.length,\n stream: request.stream \n });\n\n return this._gatewayService.chat(gatewayRequest);\n }\n\n /**\n * Text completion using OpenAI through the gateway\n */\n complete(prompt: string, options: {\n model: string;\n temperature?: number;\n max_tokens?: number;\n stream?: boolean;\n stop?: string | string[];\n }): Observable<GatewayGenerateResponse> {\n const gatewayRequest: GatewayGenerateRequest = {\n model: options.model,\n prompt,\n temperature: options.temperature,\n max_tokens: options.max_tokens,\n stream: options.stream,\n stop: options.stop,\n provider: 'openai'\n };\n\n debugLogger.debug('OpenAI Gateway completion request', { \n model: options.model, \n promptLength: prompt.length,\n stream: options.stream \n });\n\n return this._gatewayService.generate(gatewayRequest);\n }\n\n /**\n * List available OpenAI models through the gateway\n */\n listModels(): Observable<GatewayModel[]> {\n debugLogger.debug('Fetching OpenAI models through gateway');\n return this._gatewayService.listModelsByProvider('openai');\n }\n\n /**\n * Get gateway health with OpenAI provider status\n */\n getHealth() {\n return this._gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n openai_status: health.providers.find(p => p.name === 'openai')?.status || 'unavailable'\n }))\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-9B34-38B0E8\nconst __banditFingerprint_gateway_azureopenaigatewayservicets = 'BL-FP-4A759E-00DC';\nconst __auditTrail_gateway_azureopenaigatewayservicets = 'BL-AU-MGOIKVVT-GARS';\n// File: azure-openai-gateway.service.ts | Path: src/services/gateway/azure-openai-gateway.service.ts | Hash: 9b3400dc\n\nimport { GatewayService } from './gateway.service';\nimport { GatewayChatRequest, GatewayChatResponse, GatewayGenerateRequest, GatewayGenerateResponse, GatewayModel } from './interfaces';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface AzureOpenAIMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n name?: string;\n}\n\nexport interface AzureOpenAIChatRequest {\n model: string; // This will be the deployment name for Azure\n messages: AzureOpenAIMessage[];\n stream?: boolean;\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n stop?: string | string[];\n}\n\nexport interface AzureOpenAIConfig {\n deploymentName: string;\n apiVersion: string;\n resourceName?: string; // For endpoint construction if needed\n}\n\nexport class AzureOpenAIGatewayService {\n private _gatewayService: GatewayService;\n private _azureConfig: AzureOpenAIConfig;\n\n constructor(\n gatewayUrl: string,\n tokenFactory: () => string | null,\n azureConfig: AzureOpenAIConfig\n ) {\n this._gatewayService = new GatewayService(gatewayUrl, tokenFactory);\n this._azureConfig = azureConfig;\n debugLogger.info('AzureOpenAIGatewayService initialized', { \n gatewayUrl, \n deploymentName: azureConfig.deploymentName,\n apiVersion: azureConfig.apiVersion \n });\n }\n\n /**\n * Validates the availability of the gateway service for Azure OpenAI\n */\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n return this._gatewayService.validateServiceAvailability(args);\n }\n\n /**\n * Chat completion using Azure OpenAI through the gateway\n */\n chat(request: AzureOpenAIChatRequest): Observable<GatewayChatResponse> {\n const gatewayRequest: GatewayChatRequest = {\n ...request,\n model: this._azureConfig.deploymentName, // Use deployment name as model\n provider: 'azure-openai'\n };\n\n debugLogger.debug('Azure OpenAI Gateway chat request', { \n deploymentName: this._azureConfig.deploymentName,\n apiVersion: this._azureConfig.apiVersion,\n messageCount: request.messages.length,\n stream: request.stream \n });\n\n return this._gatewayService.chat(gatewayRequest);\n }\n\n /**\n * Text completion using Azure OpenAI through the gateway\n */\n complete(prompt: string, options: {\n model?: string; // Optional override for deployment name\n temperature?: number;\n max_tokens?: number;\n stream?: boolean;\n stop?: string | string[];\n }): Observable<GatewayGenerateResponse> {\n const gatewayRequest: GatewayGenerateRequest = {\n model: options.model || this._azureConfig.deploymentName,\n prompt,\n temperature: options.temperature,\n max_tokens: options.max_tokens,\n stream: options.stream,\n stop: options.stop,\n provider: 'azure-openai'\n };\n\n debugLogger.debug('Azure OpenAI Gateway completion request', { \n deploymentName: options.model || this._azureConfig.deploymentName,\n promptLength: prompt.length,\n stream: options.stream \n });\n\n return this._gatewayService.generate(gatewayRequest);\n }\n\n /**\n * List available Azure OpenAI models through the gateway\n */\n listModels(): Observable<GatewayModel[]> {\n debugLogger.debug('Fetching Azure OpenAI models through gateway');\n return this._gatewayService.listModelsByProvider('azure-openai');\n }\n\n /**\n * Get gateway health with Azure OpenAI provider status\n */\n getHealth() {\n return this._gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n azure_openai_status: health.providers.find(p => p.name === 'azure-openai')?.status || 'unavailable',\n azure_config: {\n deploymentName: this._azureConfig.deploymentName,\n apiVersion: this._azureConfig.apiVersion\n }\n }))\n );\n }\n\n /**\n * Update Azure configuration\n */\n updateAzureConfig(newConfig: Partial<AzureOpenAIConfig>) {\n this._azureConfig = { ...this._azureConfig, ...newConfig };\n debugLogger.info('Azure OpenAI configuration updated', this._azureConfig);\n }\n\n /**\n * Get current Azure configuration\n */\n getAzureConfig(): AzureOpenAIConfig {\n return { ...this._azureConfig };\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-8264-DAEB3A\nconst __banditFingerprint_gateway_anthropicgatewayservicets = 'BL-FP-CA4EB6-817C';\nconst __auditTrail_gateway_anthropicgatewayservicets = 'BL-AU-MGOIKVVS-X7J4';\n// File: anthropic-gateway.service.ts | Path: src/services/gateway/anthropic-gateway.service.ts | Hash: 8264817c\n\nimport { GatewayService } from './gateway.service';\nimport { GatewayChatRequest, GatewayChatResponse, GatewayGenerateRequest, GatewayGenerateResponse, GatewayModel } from './interfaces';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface AnthropicMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n name?: string;\n}\n\nexport interface AnthropicChatRequest {\n model: string;\n messages: AnthropicMessage[];\n stream?: boolean;\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n stop_sequences?: string[];\n system?: string; // Anthropic uses separate system parameter\n}\n\nexport class AnthropicGatewayService {\n private _gatewayService: GatewayService;\n\n constructor(\n gatewayUrl: string,\n tokenFactory: () => string | null\n ) {\n this._gatewayService = new GatewayService(gatewayUrl, tokenFactory);\n debugLogger.info('AnthropicGatewayService initialized', { gatewayUrl });\n }\n\n /**\n * Validates the availability of the gateway service for Anthropic\n */\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n return this._gatewayService.validateServiceAvailability(args);\n }\n\n /**\n * Chat completion using Anthropic through the gateway\n */\n chat(request: AnthropicChatRequest): Observable<GatewayChatResponse> {\n // Convert Anthropic-specific request to gateway format\n const gatewayRequest: GatewayChatRequest = {\n model: request.model,\n messages: request.messages,\n stream: request.stream,\n temperature: request.temperature,\n max_tokens: request.max_tokens,\n top_p: request.top_p,\n stop: request.stop_sequences,\n provider: 'anthropic'\n };\n\n debugLogger.debug('Anthropic Gateway chat request', { \n model: request.model, \n messageCount: request.messages.length,\n stream: request.stream,\n hasSystem: !!request.system\n });\n\n return this._gatewayService.chat(gatewayRequest);\n }\n\n /**\n * Text completion using Anthropic through the gateway\n */\n complete(prompt: string, options: {\n model: string;\n temperature?: number;\n max_tokens?: number;\n stream?: boolean;\n stop_sequences?: string[];\n system?: string;\n }): Observable<GatewayGenerateResponse> {\n const gatewayRequest: GatewayGenerateRequest = {\n model: options.model,\n prompt,\n temperature: options.temperature,\n max_tokens: options.max_tokens,\n stream: options.stream,\n stop: options.stop_sequences,\n provider: 'anthropic'\n };\n\n debugLogger.debug('Anthropic Gateway completion request', { \n model: options.model, \n promptLength: prompt.length,\n stream: options.stream,\n hasSystem: !!options.system\n });\n\n return this._gatewayService.generate(gatewayRequest);\n }\n\n /**\n * List available Anthropic models through the gateway\n */\n listModels(): Observable<GatewayModel[]> {\n debugLogger.debug('Fetching Anthropic models through gateway');\n return this._gatewayService.listModelsByProvider('anthropic');\n }\n\n /**\n * Get gateway health with Anthropic provider status\n */\n getHealth() {\n return this._gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n anthropic_status: health.providers.find(p => p.name === 'anthropic')?.status || 'unavailable'\n }))\n );\n }\n\n /**\n * Helper method to convert system message to Anthropic format\n * Anthropic treats system messages differently - they can be separate from messages\n */\n private extractSystemMessage(messages: AnthropicMessage[]): { messages: AnthropicMessage[], system?: string } {\n const systemMessage = messages.find(msg => msg.role === 'system');\n const userMessages = messages.filter(msg => msg.role !== 'system');\n \n return {\n messages: userMessages,\n system: systemMessage?.content\n };\n }\n\n /**\n * Enhanced chat method that handles Anthropic's system message format\n */\n chatWithSystem(request: AnthropicChatRequest): Observable<GatewayChatResponse> {\n const { messages, system } = this.extractSystemMessage(request.messages);\n \n const enhancedRequest: AnthropicChatRequest = {\n ...request,\n messages,\n system: system || request.system\n };\n\n return this.chat(enhancedRequest);\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-76E6-8DEDE6\nconst __banditFingerprint_gateway_ollamagatewayservicets = 'BL-FP-124FB6-97C7';\nconst __auditTrail_gateway_ollamagatewayservicets = 'BL-AU-MGOIKVVU-PU6T';\n// File: ollama-gateway.service.ts | Path: src/services/gateway/ollama-gateway.service.ts | Hash: 76e697c7\n\nimport { GatewayService } from './gateway.service';\nimport { GatewayChatRequest, GatewayChatResponse, GatewayGenerateRequest, GatewayGenerateResponse, GatewayModel } from './interfaces';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface OllamaMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n images?: string[]; // Ollama supports image inputs\n}\n\nexport interface OllamaChatRequest {\n model: string;\n messages: OllamaMessage[];\n stream?: boolean;\n options?: Record<string, unknown>;\n images?: string[];\n}\n\nexport interface OllamaGenerateRequest {\n model: string;\n prompt: string;\n stream?: boolean;\n images?: string[];\n options?: Record<string, unknown>;\n}\n\nexport class OllamaGatewayService {\n private _gatewayService: GatewayService;\n\n constructor(\n gatewayUrl: string,\n tokenFactory: () => string | null\n ) {\n this._gatewayService = new GatewayService(gatewayUrl, tokenFactory);\n debugLogger.info('OllamaGatewayService initialized', { gatewayUrl });\n }\n\n /**\n * Validates the availability of the gateway service for Ollama\n */\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string, isAvailable: boolean }> {\n return this._gatewayService.validateServiceAvailability(args);\n }\n\n /**\n * Chat completion using Ollama through the gateway\n */\n chat(request: OllamaChatRequest): Observable<GatewayChatResponse> {\n const gatewayRequest: GatewayChatRequest = {\n ...request,\n provider: 'ollama'\n };\n\n debugLogger.debug('Ollama Gateway chat request', { \n model: request.model, \n messageCount: request.messages.length,\n stream: request.stream,\n hasImages: !!(request.images && request.images.length > 0)\n });\n\n return this._gatewayService.chat(gatewayRequest);\n }\n\n /**\n * Text generation using Ollama through the gateway\n */\n generate(request: OllamaGenerateRequest): Observable<GatewayGenerateResponse> {\n const gatewayRequest: GatewayGenerateRequest = {\n ...request,\n provider: 'ollama'\n };\n\n debugLogger.debug('Ollama Gateway generate request', { \n model: request.model, \n promptLength: request.prompt.length,\n stream: request.stream,\n hasImages: !!(request.images && request.images.length > 0)\n });\n\n return this._gatewayService.generate(gatewayRequest);\n }\n\n /**\n * List available Ollama models through the gateway\n */\n listModels(): Observable<GatewayModel[]> {\n debugLogger.debug('Fetching Ollama models through gateway');\n return this._gatewayService.listModelsByProvider('ollama');\n }\n\n /**\n * Get gateway health with Ollama provider status\n */\n getHealth() {\n return this._gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n ollama_status: health.providers.find(p => p.name === 'ollama')?.status || 'unavailable'\n }))\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-5C48-8D1103\nconst __banditFingerprint_gateway_banditgatewayservicets = 'BL-FP-37A8F1-0E5B';\nconst __auditTrail_gateway_banditgatewayservicets = 'BL-AU-MGOIKVVS-DH4W';\n// File: bandit-gateway.service.ts | Path: src/services/gateway/bandit-gateway.service.ts | Hash: 5c488d11\n\nimport { GatewayService } from './gateway.service';\nimport {\n GatewayChatRequest,\n GatewayChatResponse,\n GatewayGenerateRequest,\n GatewayGenerateResponse,\n GatewayMessage,\n GatewayMessageContent,\n GatewayModel\n} from './interfaces';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { debugLogger } from '../logging/debugLogger';\n\nexport interface BanditAIChatRequest {\n model: string;\n messages: Array<{ role: 'system' | 'user' | 'assistant'; content: unknown }>;\n stream?: boolean;\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n stop?: string | string[];\n}\n\nconst normalizeBanditModel = (model: string | undefined): string => {\n if (typeof model !== 'string' || model.trim() === '') {\n return 'bandit-core-1';\n }\n const normalized = model.replace(/^bandit:/, '').trim();\n return normalized === '' ? 'bandit-core-1' : normalized;\n};\n\nconst isGatewayMessageContent = (value: unknown): value is GatewayMessageContent => {\n if (!value || typeof value !== 'object') return false;\n const candidate = value as GatewayMessageContent;\n if (candidate.type !== 'text' && candidate.type !== 'image_url') {\n return false;\n }\n if (candidate.type === 'text') {\n return typeof candidate.text === 'string';\n }\n if (candidate.type === 'image_url') {\n return !!candidate.image_url && typeof candidate.image_url.url === 'string';\n }\n return false;\n};\n\nconst normalizeBanditMessages = (\n messages: Array<{ role: 'system' | 'user' | 'assistant'; content: unknown }>\n): GatewayMessage[] =>\n messages.map((message) => {\n const content = message.content;\n if (typeof content === 'string') {\n return { role: message.role, content };\n }\n if (Array.isArray(content)) {\n const filtered = content.filter(isGatewayMessageContent);\n if (filtered.length === 0) {\n return { role: message.role, content: JSON.stringify(content) };\n }\n return {\n role: message.role,\n content: filtered\n };\n }\n return { role: message.role, content: content != null ? String(content) : '' };\n });\n\nexport class BanditAIGatewayService {\n private _gatewayService: GatewayService;\n\n constructor(\n gatewayUrl: string,\n tokenFactory: () => string | null\n ) {\n this._gatewayService = new GatewayService(gatewayUrl, tokenFactory);\n debugLogger.info('BanditAIGatewayService initialized', { gatewayUrl });\n }\n\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string; isAvailable: boolean }> {\n return this._gatewayService.validateServiceAvailability(args);\n }\n\n chat(request: BanditAIChatRequest): Observable<GatewayChatResponse> {\n const model = normalizeBanditModel(request.model);\n const messages = normalizeBanditMessages(request.messages);\n const gatewayRequest: GatewayChatRequest = {\n ...request,\n messages,\n model,\n provider: 'bandit',\n stream: request.stream\n };\n\n debugLogger.debug('Bandit Gateway chat request', {\n model,\n messageCount: request.messages.length,\n stream: request.stream\n });\n\n return this._gatewayService.chat(gatewayRequest);\n }\n\n complete(prompt: string, options: {\n model: string;\n temperature?: number;\n max_tokens?: number;\n stream?: boolean;\n stop?: string | string[];\n }): Observable<GatewayGenerateResponse> {\n const model = normalizeBanditModel(options.model);\n const gatewayRequest: GatewayGenerateRequest = {\n model,\n prompt,\n temperature: options.temperature,\n max_tokens: options.max_tokens,\n stream: options.stream,\n stop: options.stop,\n provider: 'bandit'\n };\n\n debugLogger.debug('Bandit Gateway generate request', {\n model,\n promptLength: prompt.length,\n stream: options.stream\n });\n\n return this._gatewayService.generate(gatewayRequest);\n }\n\n listModels(): Observable<GatewayModel[]> {\n debugLogger.debug('Fetching Bandit models through gateway');\n return this._gatewayService.listModelsByProvider('bandit');\n }\n\n getHealth() {\n return this._gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n bandit_status: health.providers.find(p => p.name === 'bandit')?.status || 'unavailable'\n }))\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-0C91-217979\nconst __banditFingerprint_providers_gatewayproviderts = 'BL-FP-4F2F4F-2A21';\nconst __auditTrail_providers_gatewayproviderts = 'BL-AU-MGOIKVVQ-MHFK';\n// File: gateway.provider.ts | Path: src/services/ai-provider/providers/gateway.provider.ts | Hash: 0c912a21\n\nimport { Observable, map } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\nimport { GatewayService } from '../../gateway/gateway.service';\nimport { OpenAIGatewayService } from '../../gateway/openai-gateway.service';\nimport { AzureOpenAIGatewayService } from '../../gateway/azure-openai-gateway.service';\nimport { AnthropicGatewayService } from '../../gateway/anthropic-gateway.service';\nimport { OllamaGatewayService } from '../../gateway/ollama-gateway.service';\nimport { BanditAIGatewayService } from '../../gateway/bandit-gateway.service';\nimport {\n GatewayChatRequest,\n GatewayMessage,\n GatewayMessageContent,\n GatewayTool\n} from '../../gateway/interfaces';\n\n/**\n * Gateway provider implementation that routes requests through the .NET gateway API\n * This consolidates all AI provider logic behind a single gateway endpoint\n */\nexport class GatewayProvider implements IAIProvider {\n private config: AIProviderConfig;\n private gatewayService: GatewayService;\n private providerSpecificService: OpenAIGatewayService | AzureOpenAIGatewayService | AnthropicGatewayService | OllamaGatewayService | BanditAIGatewayService | null = null;\n\n constructor(config: AIProviderConfig) {\n this.config = config;\n \n if (!config.gatewayUrl) {\n throw new Error('Gateway provider requires gatewayUrl in config');\n }\n \n if (!config.provider) {\n throw new Error('Gateway provider requires provider field to specify backend (openai, azure-openai, anthropic, ollama)');\n }\n\n const tokenFactory = config.tokenFactory || (() => null);\n this.gatewayService = new GatewayService(config.gatewayUrl, tokenFactory);\n\n // Create provider-specific service for enhanced functionality\n this.createProviderSpecificService(config.gatewayUrl, tokenFactory);\n\n debugLogger.info('GatewayProvider initialized', { \n gatewayUrl: config.gatewayUrl,\n backendProvider: config.provider\n });\n }\n\n private createProviderSpecificService(gatewayUrl: string, tokenFactory: () => string | null) {\n switch (this.config.provider) {\n case 'openai':\n this.providerSpecificService = new OpenAIGatewayService(gatewayUrl, tokenFactory);\n break;\n case 'azure-openai':\n if (!this.config.deploymentName || !this.config.apiVersion) {\n throw new Error('Azure OpenAI gateway provider requires deploymentName and apiVersion');\n }\n this.providerSpecificService = new AzureOpenAIGatewayService(\n gatewayUrl, \n tokenFactory,\n {\n deploymentName: this.config.deploymentName,\n apiVersion: this.config.apiVersion\n }\n );\n break;\n case 'anthropic':\n this.providerSpecificService = new AnthropicGatewayService(gatewayUrl, tokenFactory);\n break;\n case 'bandit':\n this.providerSpecificService = new BanditAIGatewayService(gatewayUrl, tokenFactory);\n break;\n case 'ollama':\n this.providerSpecificService = new OllamaGatewayService(gatewayUrl, tokenFactory);\n break;\n case 'playground':\n // Preview gateway uses custom routing; no provider-specific service\n this.providerSpecificService = null;\n break;\n default:\n debugLogger.warn('Unknown provider for gateway, using generic gateway service', { \n provider: this.config.provider \n });\n }\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n // Convert AI request to standardized gateway request format\n // The gateway API will handle provider-specific transformations\n \n const messages: GatewayMessage[] = request.messages.map(msg => ({\n role: msg.role,\n content: msg.content\n }));\n \n // Handle images based on provider type\n const normalizeImageUrl = (value: string) => {\n if (!value) {\n return value;\n }\n const trimmed = value.trim();\n if (/^data:/i.test(trimmed) || /^https?:\\/\\//i.test(trimmed)) {\n return trimmed;\n }\n return `data:image/jpeg;base64,${trimmed}`;\n };\n\n if (request.images && request.images.length > 0) {\n const lastUserMessageIndex = messages.map(m => m.role).lastIndexOf('user');\n\n if (this.config.provider === 'ollama') {\n // Ollama: attach images directly to the last user message\n if (lastUserMessageIndex !== -1) {\n messages[lastUserMessageIndex] = {\n ...messages[lastUserMessageIndex],\n images: request.images\n };\n }\n } else if (['openai', 'azure-openai', 'anthropic', 'bandit', 'playground'].includes(this.config.provider || '')) {\n // OpenAI/Azure/Anthropic: convert to structured content format\n if (lastUserMessageIndex !== -1) {\n const currentMessage = messages[lastUserMessageIndex];\n const contentArray: GatewayMessageContent[] = [\n {\n type: 'text',\n text: currentMessage.content as string\n }\n ];\n\n // Add images as image_url content\n request.images.forEach(imageRef => {\n contentArray.push({\n type: 'image_url',\n image_url: {\n url: normalizeImageUrl(imageRef),\n detail: 'auto'\n }\n });\n });\n\n messages[lastUserMessageIndex] = {\n ...messages[lastUserMessageIndex],\n content: contentArray\n };\n debugLogger.debug('Gateway provider injected image attachments', {\n provider: this.config.provider,\n imageCount: request.images.length,\n messageIndex: lastUserMessageIndex\n });\n }\n }\n }\n \n const toolAwareRequest = request as AIChatRequest & { tools?: GatewayTool[] };\n\n const gatewayRequest: GatewayChatRequest = {\n model: request.model,\n messages,\n stream: request.stream,\n temperature: request.temperature,\n max_tokens: request.maxTokens,\n provider: this.config.provider,\n // Only include top-level images for Ollama (fallback)\n images: this.config.provider === 'ollama' ? request.images : undefined,\n tools: toolAwareRequest.tools?.length ? toolAwareRequest.tools : undefined\n };\n\n debugLogger.debug('Gateway provider chat request', { \n model: request.model,\n provider: this.config.provider,\n messageCount: request.messages.length,\n stream: request.stream,\n hasImages: !!(request.images && request.images.length > 0),\n imageCount: request.images?.length || 0,\n imageStrategy: this.config.provider === 'ollama' \n ? 'message-level-array' \n : ['openai', 'azure-openai', 'anthropic', 'playground'].includes(this.config.provider || '')\n ? 'structured-content'\n : 'top-level-fallback',\n finalMessages: messages.map(m => ({ \n role: m.role, \n hasImages: Array.isArray(m.images) && m.images.length > 0,\n contentType: Array.isArray(m.content) ? 'structured' : 'text'\n }))\n });\n\n return this.gatewayService.chat(gatewayRequest).pipe(\n map(response => {\n const choice = response.choices?.[0];\n const toolCalls = choice?.message?.tool_calls ?? choice?.delta?.tool_calls;\n return {\n message: {\n content: choice?.message?.content ?? choice?.delta?.content ?? '',\n role: 'assistant' as const,\n tool_calls: toolCalls\n },\n done: choice?.finish_reason === 'stop' || choice?.finish_reason === 'length' || choice?.finish_reason === 'tool_calls'\n };\n })\n );\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n const gatewayRequest = {\n model: request.model,\n prompt: request.prompt,\n stream: request.stream,\n provider: this.config.provider\n };\n\n debugLogger.debug('Gateway provider generate request', { \n model: request.model,\n provider: this.config.provider,\n promptLength: request.prompt.length,\n stream: request.stream \n });\n\n return this.gatewayService.generate(gatewayRequest).pipe(\n map(response => ({\n response: response.response || '',\n done: response.done || false\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n debugLogger.debug('Gateway provider listing models', { provider: this.config.provider });\n \n if (this.config.provider) {\n return this.gatewayService.listModelsByProvider(this.config.provider).pipe(\n map(models => models.map(model => ({\n name: model.id || model.name,\n size: model.size,\n details: model.details,\n digest: model.digest,\n modified_at: model.modified_at\n })))\n );\n } else {\n // List all models from all providers\n return this.gatewayService.listModels().pipe(\n map(models => models.map(model => ({\n name: model.id || model.name,\n size: model.size,\n details: model.details,\n digest: model.digest,\n modified_at: model.modified_at\n })))\n );\n }\n }\n\n async validateServiceAvailability(args: { \n fallbackUrl?: string; \n timeoutMs: number; \n }): Promise<{ url: string; isAvailable: boolean }> {\n debugLogger.debug('Gateway provider validating service availability');\n return this.gatewayService.validateServiceAvailability(args);\n }\n\n getProviderType(): string {\n return AIProviderType.GATEWAY;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n /**\n * Get the backend provider type\n */\n getBackendProvider(): string | undefined {\n return this.config.provider;\n }\n\n /**\n * Get gateway health including backend provider status\n */\n getHealth() {\n return this.gatewayService.getHealth().pipe(\n map(health => ({\n ...health,\n backend_provider: this.config.provider,\n backend_provider_status: health.providers.find(p => p.name === this.config.provider)?.status || 'unavailable'\n }))\n );\n }\n\n /**\n * Use provider-specific service if available for enhanced functionality\n */\n getProviderSpecificService(): OpenAIGatewayService | AzureOpenAIGatewayService | AnthropicGatewayService | OllamaGatewayService | BanditAIGatewayService | null {\n return this.providerSpecificService;\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-DBA3-6C3A2B\nconst __banditFingerprint_providers_playgroundproviderts = 'BL-FP-7465CF-7B8B';\nconst __auditTrail_providers_playgroundproviderts = 'BL-AU-MGOIKVVR-EV75';\n// File: playground.provider.ts | Path: src/services/ai-provider/providers/playground.provider.ts | Hash: dba37b8b\n\nimport { Observable } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\n\ntype PlaygroundScript = {\n match: (input: string) => boolean;\n response: string;\n};\n\nconst PLAYGROUND_MODELS: AIModel[] = [\n {\n name: 'bandit-playground',\n details: {\n format: 'chat',\n family: 'bandit',\n families: ['bandit', 'demo'],\n parameter_size: 'demo',\n quantization_level: 'synthetic'\n },\n digest: 'playground-demo-001',\n modified_at: new Date().toISOString()\n },\n {\n name: 'bandit-starter',\n details: {\n format: 'chat',\n family: 'bandit',\n families: ['bandit', 'demo'],\n parameter_size: 'demo',\n quantization_level: 'synthetic'\n },\n digest: 'playground-demo-002',\n modified_at: new Date().toISOString()\n }\n];\n\nconst PLAYGROUND_CONVERSATION_STARTERS = [\n 'What can I build with Bandit Engine if my backend is not ready yet?',\n 'How does the gateway contract keep API keys out of the browser?',\n 'Can I theme the chat UI to match my product brand?',\n 'How do I switch between Ollama and OpenAI without redeploying the frontend?',\n 'Show me how the management console handles personas and models.'\n];\n\nconst PLAYGROUND_SCRIPTS: PlaygroundScript[] = [\n {\n match: (input) => /model|switch|personas|management/i.test(input),\n response: [\n \"Absolutely — the management console ships with live model switching, persona editing, and feature toggles.\",\n \"\",\n \"- Use the **Models** tab to expose whichever gateway-backed models you want customers to see.\",\n \"- Personas hydrate the chat with branded system prompts, voice preferences, and avatars.\",\n \"- Everything persists through the gateway, so you can roll out changes without shipping a new build.\"\n ].join('\\n')\n },\n {\n match: (input) => /gateway|api|contract|backend/i.test(input),\n response: [\n \"The gateway contract keeps secrets on the server while giving the UI a unified AI API.\",\n \"\",\n \"Key highlights:\",\n \"1. `/api/chat/completions` is the default OpenAI-format endpoint when no provider override is set.\",\n \"2. `/api/{provider}/chat/completions` handles OpenAI, Azure OpenAI, and Anthropic while `/api/ollama/chat` streams Ollama responses.\",\n \"3. The contract is language-agnostic — Express, FastAPI, .NET, Go… anything works as long as it speaks HTTP.\"\n ].join('\\n')\n },\n {\n match: (input) => /style|theme|brand|ui/i.test(input),\n response: [\n \"Every surface in Bandit Engine is themeable.\",\n \"\",\n \"- Drop a JSON config into your `public/` folder (or host it on a CDN) to control themes, logos, and accent colors.\",\n \"- The React components expose hooks for custom headers, menus, and call-to-action buttons.\",\n \"- Need a modal? `ChatModal` reuses the same store, so the handoff between embedded chat and floating assistant stays seamless.\"\n ].join('\\n')\n },\n {\n match: (input) => /voice|tts|audio/i.test(input),\n response: [\n \"Voice is opt-in, but the plumbing is ready.\",\n \"\",\n \"- Configure `/api/tts` and `/api/stt` on the gateway to unlock the speak/listen controls.\",\n \"- The UI lazily loads voices and respects feature flags, so you can leave it disabled in the playground.\",\n \"- Everything streams — the assistant starts speaking before the full response lands.\"\n ].join('\\n')\n },\n {\n match: (input) => /deploy|production|secure/i.test(input),\n response: [\n \"Production hardening is front and center.\",\n \"\",\n \"- Gateway tokens ride in the `Authorization` header; rotate them server-side without touching the bundle.\",\n \"- Feature flags gate premium surfaces, letting you trial the UI before wiring billing.\",\n \"- Vector search, knowledge, and memories are isolated behind `/api/embedding/*` so you can plug in your own storage policies.\"\n ].join('\\n')\n }\n];\n\nconst FALLBACK_RESPONSE = [\n \"Bandit Engine is running in playground mode. I'm simulating how streaming works so you can explore the UX without connecting a live model.\",\n \"\",\n \"Try asking about the gateway contract, theming, voice features, or model management to see tailored walkthroughs.\"\n].join('\\n');\n\nconst STREAM_DELAY_MS = 350;\n\nexport class PlaygroundProvider implements IAIProvider {\n private config: AIProviderConfig;\n\n constructor(config: AIProviderConfig) {\n this.config = { type: AIProviderType.PLAYGROUND, ...config };\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const lastUserMessage = [...request.messages]\n .reverse()\n .find((m) => m.role === 'user')?.content ?? '';\n\n const script = PLAYGROUND_SCRIPTS.find((scenario) =>\n scenario.match(lastUserMessage)\n );\n\n const responseText = script?.response ?? FALLBACK_RESPONSE;\n const chunks = this.splitIntoChunks(responseText);\n\n return new Observable<AIChatResponse>((observer) => {\n let index = 0;\n const emitChunk = () => {\n if (index >= chunks.length) {\n observer.complete();\n return;\n }\n\n const chunk = chunks[index];\n observer.next({\n message: {\n content: chunk,\n role: 'assistant'\n },\n done: index === chunks.length - 1\n });\n\n index += 1;\n setTimeout(emitChunk, STREAM_DELAY_MS);\n };\n\n emitChunk();\n\n return () => {\n index = chunks.length;\n };\n });\n }\n\n generate(_request: AIGenerateRequest): Observable<AIGenerateResponse> {\n const starters = PLAYGROUND_CONVERSATION_STARTERS.join('\\n');\n\n return new Observable<AIGenerateResponse>((observer) => {\n observer.next({\n response: starters,\n done: true\n });\n observer.complete();\n });\n }\n\n listModels(): Observable<AIModel[]> {\n return new Observable<AIModel[]>((observer) => {\n observer.next(PLAYGROUND_MODELS);\n observer.complete();\n });\n }\n\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number }): Promise<{ url: string; isAvailable: boolean }> {\n const simulatedUrl = this.config.baseUrl ?? 'playground://local';\n\n if (args.timeoutMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(args.timeoutMs, 250)));\n }\n\n return {\n url: simulatedUrl,\n isAvailable: true\n };\n }\n\n getProviderType(): string {\n return AIProviderType.PLAYGROUND;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private splitIntoChunks(response: string): string[] {\n const paragraphs = response.split('\\n\\n').map((p) => p.trim()).filter(Boolean);\n\n if (paragraphs.length <= 1) {\n const sentences = response.split(/(?<=[.!?])\\s+/).filter(Boolean);\n return sentences.length > 0 ? sentences : [response];\n }\n\n return paragraphs;\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-16A2-8F5D0C\nconst __banditFingerprint_providers_xaiproviderts = 'BL-FP-DA7844-7C12';\nconst __auditTrail_providers_xaiproviderts = 'BL-AU-MGOIKVVR-W7UB';\n// File: xai.provider.ts | Path: src/services/ai-provider/providers/xai.provider.ts | Hash: 16a28f5d\n\nimport { Observable, from, switchMap, map, throwError } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\n\ninterface XAIChatPayload {\n model: string;\n messages: AIChatRequest['messages'];\n stream: boolean;\n temperature?: number;\n max_tokens?: number;\n}\n\ninterface XAIStreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n };\n }>;\n}\n\ninterface XAIChatResponsePayload {\n choices?: Array<{\n message?: {\n content?: string;\n };\n }>;\n}\n\ninterface XAIModelListResponse {\n data: Array<{\n id: string;\n object?: string;\n }>;\n}\n\n/**\n * xAI provider implementation\n */\nexport class XAIProvider implements IAIProvider {\n private config: AIProviderConfig;\n private baseUrl: string;\n\n constructor(config: AIProviderConfig) {\n this.config = config;\n this.baseUrl = config.baseUrl || 'https://api.x.ai/v1';\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const url = `${this.baseUrl}/chat/completions`;\n\n const payload: XAIChatPayload = {\n model: request.model,\n messages: request.messages,\n stream: Boolean(request.stream),\n temperature: request.temperature,\n max_tokens: request.maxTokens\n };\n\n if (request.stream) {\n return this.streamChatRequest(url, payload);\n } else {\n return this.nonStreamChatRequest(url, payload);\n }\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n const chatRequest: AIChatRequest = {\n model: request.model,\n messages: [{ role: 'user', content: request.prompt }],\n stream: request.stream,\n options: request.options\n };\n\n return this.chat(chatRequest).pipe(\n map(response => ({\n response: response.message.content,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n const url = `${this.baseUrl}/models`;\n\n return from(fetch(url, {\n headers: this.getHeaders()\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`Failed to list models: ${response.status}`));\n }\n return from(response.json() as Promise<XAIModelListResponse>);\n }),\n map((data) =>\n data.data.map((model) => ({\n name: model.id,\n details: {\n format: 'xai',\n family: model.object\n }\n }))\n )\n );\n }\n\n async validateServiceAvailability(args: {\n fallbackUrl?: string;\n timeoutMs: number;\n }): Promise<{ url: string; isAvailable: boolean }> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const response = await fetch(`${this.baseUrl}/models`, {\n headers: this.getHeaders(),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n return {\n url: this.baseUrl,\n isAvailable: response.ok\n };\n } catch (error) {\n if (args.fallbackUrl) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n\n const response = await fetch(`${args.fallbackUrl}/models`, {\n headers: this.getHeaders(),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n this.baseUrl = args.fallbackUrl;\n return {\n url: args.fallbackUrl,\n isAvailable: true\n };\n }\n } catch (fallbackError) {\n debugLogger.warn('xAI fallback validation failed', { error: fallbackError });\n }\n }\n\n return {\n url: this.baseUrl,\n isAvailable: false\n };\n }\n }\n\n getProviderType(): string {\n return AIProviderType.XAI;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private streamChatRequest(url: string, payload: XAIChatPayload): Observable<AIChatResponse> {\n return new Observable<AIChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n task.then(response => {\n if (!response.ok) {\n observer.error(new Error(`xAI request failed: ${response.status}`));\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.trim() && line.startsWith('data: ')) {\n const data = line.slice(6).trim();\n if (data === '[DONE]') {\n observer.next({\n message: { content: '', role: 'assistant' },\n done: true\n });\n observer.complete();\n return;\n }\n\n try {\n const parsed = JSON.parse(data) as XAIStreamChunk;\n const content = parsed.choices?.[0]?.delta?.content ?? '';\n if (content) {\n observer.next({\n message: { content, role: 'assistant' },\n done: false\n });\n }\n } catch (err) {\n debugLogger.error('Error parsing xAI stream data:', { data, error: err });\n }\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n read();\n }).catch(err => observer.error(err));\n });\n }\n\n private nonStreamChatRequest(url: string, payload: XAIChatPayload): Observable<AIChatResponse> {\n return from(fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`xAI request failed: ${response.status}`));\n }\n return from(response.json() as Promise<XAIChatResponsePayload>);\n }),\n map((data) => ({\n message: {\n content: data.choices?.[0]?.message?.content ?? '',\n role: 'assistant' as const\n },\n done: true\n }))\n );\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n\n if (this.config.apiKey) {\n headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n }\n\n return headers;\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-7D56-94BC03\nconst __banditFingerprint_providers_banditai_providerts = 'BL-FP-0A9B76-CCF1';\nconst __auditTrail_providers_banditai_providerts = 'BL-AU-MGOIKVVS-LZU9';\n// File: bandit-ai.provider.ts | Path: src/services/ai-provider/providers/bandit-ai.provider.ts | Hash: 7d5694bc\n\nimport { Observable, from, switchMap, map, throwError } from 'rxjs';\nimport { IAIProvider } from '../interfaces/ai-provider.interface';\nimport {\n AIChatRequest,\n AIChatResponse,\n AIGenerateRequest,\n AIGenerateResponse,\n AIModel,\n AIProviderConfig,\n AIProviderType\n} from '../types/common.types';\nimport { debugLogger } from '../../logging/debugLogger';\n\ninterface BanditAIChatPayload {\n model: string;\n messages: BanditAIMessage[];\n stream: boolean;\n temperature?: number;\n max_tokens?: number;\n}\n\ninterface BanditAIStreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n };\n finish_reason?: string | null;\n }>;\n}\n\ninterface BanditAINonStreamResponse {\n choices?: Array<{\n message?: {\n content?: string;\n };\n }>;\n}\n\ninterface BanditAIModelListResponse {\n data: Array<{\n id: string;\n object?: string;\n }>;\n}\n\nconst DEFAULT_BANDIT_BASE = 'https://api.burtson.ai';\n\ntype BanditAIMessageContent =\n | string\n | Array<\n | { type: 'text'; text: string }\n | { type: 'image_url'; image_url: { url: string; detail?: 'low' | 'high' | 'auto' } }\n >;\n\ninterface BanditAIMessage {\n role: 'system' | 'user' | 'assistant';\n content: BanditAIMessageContent;\n}\n\nconst normalizeImageUrl = (value: string | undefined): string | null => {\n if (!value) {\n return null;\n }\n const trimmed = value.trim();\n if (!trimmed) {\n return null;\n }\n if (/^data:/i.test(trimmed) || /^https?:\\/\\//i.test(trimmed)) {\n return trimmed;\n }\n return `data:image/jpeg;base64,${trimmed}`;\n};\n\nconst injectImagesIntoMessages = (\n messages: AIChatRequest['messages'],\n images: string[] | undefined\n): BanditAIMessage[] => {\n const normalized: BanditAIMessage[] = messages.map((message) => ({\n role: message.role,\n content: message.content,\n }));\n\n if (!images || images.length === 0) {\n return normalized;\n }\n\n const normalizedImages = images\n .map(normalizeImageUrl)\n .filter((url): url is string => Boolean(url));\n\n if (normalizedImages.length === 0) {\n return normalized;\n }\n\n const lastUserIndex = normalized.map((msg) => msg.role).lastIndexOf('user');\n if (lastUserIndex === -1) {\n return normalized;\n }\n\n const target = normalized[lastUserIndex];\n const baseContent =\n typeof target.content === 'string' && target.content.trim().length > 0\n ? [\n {\n type: 'text' as const,\n text: target.content,\n },\n ]\n : [];\n\n const imageContent = normalizedImages.map((url) => ({\n type: 'image_url' as const,\n image_url: { url, detail: 'auto' as const },\n }));\n\n normalized[lastUserIndex] = {\n role: target.role,\n content: [...baseContent, ...imageContent],\n };\n\n return normalized;\n};\n\n/**\n * Bandit AI provider implementation (OpenAI-compatible)\n */\nexport class BanditAIProvider implements IAIProvider {\n private config: AIProviderConfig;\n private baseUrl: string;\n\n constructor(config: AIProviderConfig) {\n this.config = config;\n this.baseUrl = (config.baseUrl || DEFAULT_BANDIT_BASE).replace(/\\/$/, '');\n }\n\n chat(request: AIChatRequest): Observable<AIChatResponse> {\n const url = `${this.baseUrl}/chat/completions`;\n const messages = injectImagesIntoMessages(request.messages, request.images);\n\n const payload: BanditAIChatPayload = {\n model: request.model,\n messages,\n stream: Boolean(request.stream),\n temperature: request.temperature,\n max_tokens: request.maxTokens\n };\n\n if (request.stream) {\n return this.streamChatRequest(url, payload);\n }\n\n return this.nonStreamChatRequest(url, payload);\n }\n\n generate(request: AIGenerateRequest): Observable<AIGenerateResponse> {\n const chatRequest: AIChatRequest = {\n model: request.model,\n messages: [{ role: 'user', content: request.prompt }],\n stream: request.stream,\n options: request.options\n };\n\n return this.chat(chatRequest).pipe(\n map(response => ({\n response: response.message.content,\n done: response.done\n }))\n );\n }\n\n listModels(): Observable<AIModel[]> {\n const url = `${this.baseUrl}/models`;\n\n return from(fetch(url, { headers: this.getHeaders() })).pipe(\n switchMap(response => {\n if (!response.ok) {\n debugLogger.error('BanditAI listModels failed', { status: response.status, url });\n return throwError(() => new Error(`Failed to list Bandit models: ${response.status}`));\n }\n return from(response.json() as Promise<BanditAIModelListResponse>);\n }),\n map((data) =>\n data.data.map((model) => ({\n name: model.id,\n details: {\n format: 'bandit',\n family: model.object\n }\n }))\n )\n );\n }\n\n async validateServiceAvailability(args: { fallbackUrl?: string; timeoutMs: number; }): Promise<{ url: string; isAvailable: boolean }> {\n const attempt = async (url: string) => {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), args.timeoutMs);\n const response = await fetch(`${url}/models`, {\n headers: this.getHeaders(),\n signal: controller.signal\n });\n clearTimeout(timeoutId);\n return response.ok;\n } catch (error) {\n debugLogger.warn('BanditAI availability check failed', { url, error });\n return false;\n }\n };\n\n const primary = await attempt(this.baseUrl);\n if (primary) {\n return { url: this.baseUrl, isAvailable: true };\n }\n\n if (args.fallbackUrl) {\n const fallback = args.fallbackUrl.replace(/\\/$/, '');\n if (await attempt(fallback)) {\n this.baseUrl = fallback;\n return { url: fallback, isAvailable: true };\n }\n }\n\n return { url: this.baseUrl, isAvailable: false };\n }\n\n getProviderType(): string {\n return AIProviderType.BANDIT;\n }\n\n getConfig(): AIProviderConfig {\n return this.config;\n }\n\n private streamChatRequest(url: string, payload: BanditAIChatPayload): Observable<AIChatResponse> {\n return new Observable<AIChatResponse>(observer => {\n const task = fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n task.then(response => {\n if (!response.ok) {\n observer.error(new Error(`BanditAI request failed: ${response.status}`));\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n const read = () => {\n reader?.read().then(({ done, value }) => {\n if (done) {\n observer.next({ message: { content: '', role: 'assistant' }, done: true });\n observer.complete();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const rawLine of lines) {\n const line = rawLine.trim();\n if (!line.startsWith('data: ')) {\n continue;\n }\n\n const data = line.slice(6).trim();\n if (data === '[DONE]') {\n observer.next({ message: { content: '', role: 'assistant' }, done: true });\n observer.complete();\n return;\n }\n\n try {\n const parsed = JSON.parse(data) as BanditAIStreamChunk;\n const content = parsed.choices?.[0]?.delta?.content ?? '';\n if (content) {\n observer.next({ message: { content, role: 'assistant' }, done: false });\n }\n } catch (error) {\n debugLogger.error('BanditAI stream chunk parse failure', { data, error });\n }\n }\n\n read();\n }).catch(err => observer.error(err));\n };\n\n read();\n }).catch(err => observer.error(err));\n });\n }\n\n private nonStreamChatRequest(url: string, payload: BanditAIChatPayload): Observable<AIChatResponse> {\n return from(fetch(url, {\n method: 'POST',\n headers: {\n ...this.getHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n })).pipe(\n switchMap(response => {\n if (!response.ok) {\n return throwError(() => new Error(`BanditAI request failed: ${response.status}`));\n }\n return from(response.json() as Promise<BanditAINonStreamResponse>);\n }),\n map((data) => ({\n message: {\n content: data.choices?.[0]?.message?.content ?? '',\n role: 'assistant' as const\n },\n done: true\n }))\n );\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n\n if (this.config.apiKey) {\n headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n }\n\n return headers;\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-AED4-661A13\nconst __banditFingerprint_aiprovider_aiproviderfactoryts = 'BL-FP-C75FF8-443D';\nconst __auditTrail_aiprovider_aiproviderfactoryts = 'BL-AU-MGOIKVVP-DXHW';\n// File: ai-provider.factory.ts | Path: src/services/ai-provider/ai-provider.factory.ts | Hash: aed4443d\n\nimport { IAIProvider } from './interfaces/ai-provider.interface';\nimport { AIProviderConfig, AIProviderType } from './types/common.types';\nimport { OllamaProvider } from './providers/ollama.provider';\nimport { OpenAIProvider } from './providers/openai.provider';\nimport { AzureOpenAIProvider } from './providers/azure-openai.provider';\nimport { AnthropicProvider } from './providers/anthropic.provider';\nimport { GatewayProvider } from './providers/gateway.provider';\nimport { PlaygroundProvider } from './providers/playground.provider';\nimport { XAIProvider } from './providers/xai.provider';\nimport { BanditAIProvider } from './providers/bandit-ai.provider';\n\n/**\n * Factory for creating AI provider instances\n */\nexport class AIProviderFactory {\n static createProvider(config: AIProviderConfig): IAIProvider {\n switch (config.type) {\n case AIProviderType.OLLAMA:\n return new OllamaProvider(config);\n \n case AIProviderType.OPENAI:\n return new OpenAIProvider(config);\n \n case AIProviderType.AZURE_OPENAI:\n return new AzureOpenAIProvider(config);\n \n case AIProviderType.ANTHROPIC:\n return new AnthropicProvider(config);\n\n case AIProviderType.XAI:\n return new XAIProvider(config);\n\n case AIProviderType.BANDIT:\n return new BanditAIProvider(config);\n\n case AIProviderType.GATEWAY:\n return new GatewayProvider(config);\n\n case AIProviderType.PLAYGROUND:\n return new PlaygroundProvider(config);\n \n default:\n throw new Error(`Unsupported AI provider type: ${config.type}`);\n }\n }\n\n static getSupportedProviders(): AIProviderType[] {\n return [\n AIProviderType.OLLAMA,\n AIProviderType.OPENAI,\n AIProviderType.AZURE_OPENAI,\n AIProviderType.XAI,\n AIProviderType.BANDIT,\n AIProviderType.GATEWAY,\n AIProviderType.PLAYGROUND\n ];\n }\n\n static validateConfig(config: AIProviderConfig): boolean {\n switch (config.type) {\n case AIProviderType.OLLAMA:\n return true; // Ollama only needs baseUrl which has defaults\n \n case AIProviderType.OPENAI:\n return !!config.apiKey;\n \n case AIProviderType.AZURE_OPENAI:\n return !!(config.baseUrl && config.apiKey && config.apiVersion && config.deploymentName);\n \n case AIProviderType.ANTHROPIC:\n return !!config.apiKey;\n\n case AIProviderType.XAI:\n return !!config.apiKey;\n\n case AIProviderType.BANDIT:\n return !!config.apiKey;\n\n case AIProviderType.GATEWAY:\n return !!(config.gatewayUrl && config.provider);\n\n case AIProviderType.PLAYGROUND:\n return true;\n \n default:\n return false;\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-A223-4FC2FA\nconst __banditFingerprint_store_aiProviderStorets = 'BL-FP-9F95DD-6297';\nconst __auditTrail_store_aiProviderStorets = 'BL-AU-MGOIKVW3-JR0V';\n// File: aiProviderStore.ts | Path: src/store/aiProviderStore.ts | Hash: a2236297\n\nimport { create, StoreApi, UseBoundStore } from \"zustand\";\nimport { IAIProvider } from \"../services/ai-provider/interfaces/ai-provider.interface\";\nimport { AIProviderConfig } from \"../services/ai-provider/types/common.types\";\nimport { AIProviderFactory } from \"../services/ai-provider/ai-provider.factory\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\n\nexport interface AIProviderStore {\n /**\n * The current AI provider instance.\n * @type {IAIProvider}\n * @default null\n * @description The provider instance used to interact with AI services.\n * \n * @example\n * const provider = useAIProviderStore((state) => state.provider);\n * const setProvider = useAIProviderStore((state) => state.setProvider);\n * \n * // Create and set an Ollama provider\n * const ollamaConfig = { type: 'ollama', baseUrl: 'http://localhost:11434' };\n * const ollamaProvider = AIProviderFactory.createProvider(ollamaConfig);\n * setProvider(ollamaProvider);\n * \n * @returns {IAIProvider | null} The current AI provider instance.\n */\n provider: IAIProvider | null;\n \n /**\n * The current provider configuration\n */\n config: AIProviderConfig | null;\n \n /**\n * Set the provider and config\n */\n setProvider: (provider: IAIProvider | null, config?: AIProviderConfig | null) => void;\n \n /**\n * Create a new provider from config\n */\n createProvider: (config: AIProviderConfig) => void;\n \n /**\n * Switch to a different provider\n */\n switchProvider: (config: AIProviderConfig) => void;\n}\n\n/**\n * Use for initializing the AI provider.\n * This is a private interface that extends the AIProviderStore interface.\n * This prevents the singleton service from being initialized multiple times.\n */\nexport interface AIProviderStoreInit extends AIProviderStore {\n // Additional methods could be added here if needed for internal initialization\n}\n\nexport const useAIProviderStore = create<AIProviderStore>((set, get) => ({\n provider: null,\n config: null,\n \n setProvider: (provider, config) => set({ provider, config }),\n \n createProvider: (config) => {\n try {\n const provider = AIProviderFactory.createProvider(config);\n set({ provider, config });\n } catch (error) {\n debugLogger.error('Failed to create AI provider:', { error });\n throw error;\n }\n },\n \n switchProvider: (config) => {\n const currentProvider = get().provider;\n try {\n const newProvider = AIProviderFactory.createProvider(config);\n set({ provider: newProvider, config });\n } catch (error) {\n debugLogger.error('Failed to switch AI provider:', { error });\n // Keep the current provider if switching fails\n throw error;\n }\n }\n})) as UseBoundStore<StoreApi<AIProviderStore>>;","/*\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-9A9C-45AD6B\nconst __banditFingerprint_utils_memoryUtilsts = 'BL-FP-E6A353-3010';\nconst __auditTrail_utils_memoryUtilsts = 'BL-AU-MGOIKVWA-JZOJ';\n// File: memoryUtils.ts | Path: src/utils/memoryUtils.ts | Hash: 9a9c3010\n\nexport interface BulkMemoryResult {\n success: boolean;\n message: string;\n totalProcessed: number;\n successCount: number;\n failureCount: number;\n errors: string[];\n}\n\nexport interface MemoryImportOptions {\n mode: 'append' | 'replace' | 'smartDedupe';\n clearExisting?: boolean;\n includeMetadata?: boolean;\n batchSize?: number;\n}\n\ntype MemoryRecordCandidate = {\n content?: unknown;\n title?: unknown;\n tags?: unknown;\n timestamp?: unknown;\n};\n\ntype BatchOperationResult = {\n summary?: {\n totalProcessed?: number;\n successCount?: number;\n failureCount?: number;\n };\n totalMemories?: number;\n successCount?: number;\n failureCount?: number;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst isStringArray = (value: unknown): value is string[] =>\n Array.isArray(value) && value.every((item) => typeof item === 'string');\n\nconst resolveTimestampLabel = (timestamp: unknown): string => {\n if (timestamp instanceof Date && !Number.isNaN(timestamp.getTime())) {\n return timestamp.toLocaleDateString();\n }\n\n if (typeof timestamp === 'number' && Number.isFinite(timestamp)) {\n const date = new Date(timestamp);\n if (!Number.isNaN(date.getTime())) {\n return date.toLocaleDateString();\n }\n }\n\n if (typeof timestamp === 'string' && timestamp.trim()) {\n const date = new Date(timestamp);\n if (!Number.isNaN(date.getTime())) {\n return date.toLocaleDateString();\n }\n }\n\n return new Date().toLocaleDateString();\n};\n\n/**\n * Memory Utilities for Bulk Operations\n * \n * Provides helper functions for batch memory operations,\n * data formatting, and migration utilities.\n */\nexport class MemoryUtils {\n /**\n * Validate memory content before bulk operations\n */\n static validateMemories(memories: Array<{ content: string; title?: string; tags?: string[] }>): {\n valid: Array<{ content: string; title?: string; tags?: string[] }>;\n invalid: Array<{ content: string; error: string; index: number }>;\n } {\n const valid: Array<{ content: string; title?: string; tags?: string[] }> = [];\n const invalid: Array<{ content: string; error: string; index: number }> = [];\n\n memories.forEach((memory, index) => {\n // Check content length\n if (!memory.content || memory.content.trim().length === 0) {\n invalid.push({\n content: memory.content || '',\n error: 'Empty content',\n index\n });\n return;\n }\n\n // Check maximum content length (e.g., 50KB)\n if (memory.content.length > 50000) {\n invalid.push({\n content: memory.content.substring(0, 100) + '...',\n error: 'Content too long (max 50KB)',\n index\n });\n return;\n }\n\n // Check tags format\n if (memory.tags && (!Array.isArray(memory.tags) || memory.tags.some(tag => typeof tag !== 'string'))) {\n invalid.push({\n content: memory.content.substring(0, 100) + '...',\n error: 'Invalid tags format (must be string array)',\n index\n });\n return;\n }\n\n valid.push(memory);\n });\n\n return { valid, invalid };\n }\n\n /**\n * Format IndexedDB memories for vector import\n */\n static formatForVectorImport(indexedDBMemories: ReadonlyArray<unknown>): Array<{ content: string; title?: string; tags?: string[] }> {\n return indexedDBMemories.reduce<Array<{ content: string; title?: string; tags?: string[] }>>((acc, entry) => {\n if (!isRecord(entry)) {\n return acc;\n }\n\n const candidate = entry as MemoryRecordCandidate;\n if (typeof candidate.content !== 'string') {\n return acc;\n }\n\n const title = typeof candidate.title === 'string' && candidate.title.trim().length > 0\n ? candidate.title\n : `Memory from ${resolveTimestampLabel(candidate.timestamp)}`;\n\n const tags = isStringArray(candidate.tags) ? candidate.tags : [];\n\n acc.push({\n content: candidate.content,\n title,\n tags\n });\n return acc;\n }, []);\n }\n\n /**\n * Chunk large batch operations for better performance\n */\n static chunkMemories<T>(\n memories: T[], \n chunkSize: number = 100\n ): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < memories.length; i += chunkSize) {\n chunks.push(memories.slice(i, i + chunkSize));\n }\n return chunks;\n }\n\n /**\n * Estimate batch operation time and resource usage\n */\n static estimateBatchOperation(memoryCount: number, averageContentLength: number): {\n estimatedTimeMinutes: number;\n estimatedTokens: number;\n recommendedChunkSize: number;\n warnings: string[];\n } {\n const warnings: string[] = [];\n \n // Rough estimates based on typical embedding performance\n const embeddingsPerMinute = 100; // Conservative estimate\n const tokensPerCharacter = 0.25; // Rough estimate for token calculation\n \n const estimatedTimeMinutes = Math.ceil(memoryCount / embeddingsPerMinute);\n const estimatedTokens = Math.ceil(memoryCount * averageContentLength * tokensPerCharacter);\n \n // Recommend smaller chunks for large operations\n let recommendedChunkSize = 50;\n if (memoryCount > 1000) {\n recommendedChunkSize = 25;\n warnings.push('Large batch operation - consider running during off-peak hours');\n }\n if (averageContentLength > 2000) {\n recommendedChunkSize = Math.max(10, recommendedChunkSize / 2);\n warnings.push('Large content size - reduced chunk size recommended');\n }\n if (estimatedTimeMinutes > 30) {\n warnings.push('Long operation expected - ensure stable internet connection');\n }\n\n return {\n estimatedTimeMinutes,\n estimatedTokens,\n recommendedChunkSize,\n warnings\n };\n }\n\n /**\n * Create summary report for batch operations\n */\n static createBatchSummary(\n result: BatchOperationResult,\n operationType: 'import' | 'create' | 'migrate',\n startTime: Date\n ): {\n summary: string;\n details: {\n operation: string;\n duration: string;\n totalMemories: number;\n successful: number;\n failed: number;\n successRate: string;\n averageTimePerMemory: string;\n };\n } {\n const endTime = new Date();\n const durationMs = endTime.getTime() - startTime.getTime();\n const durationMinutes = Math.floor(durationMs / 60000);\n const durationSeconds = Math.floor((durationMs % 60000) / 1000);\n \n const totalMemories = result.summary?.totalProcessed ?? result.totalMemories ?? 0;\n const successful = result.summary?.successCount ?? result.successCount ?? 0;\n const failed = result.summary?.failureCount ?? result.failureCount ?? 0;\n const successRate = totalMemories > 0 ? ((successful / totalMemories) * 100).toFixed(1) : '0';\n const avgTimePerMemory = totalMemories > 0 ? (durationMs / totalMemories).toFixed(0) : '0';\n\n const summary = `${operationType.toUpperCase()} completed: ${successful}/${totalMemories} memories processed successfully (${successRate}% success rate) in ${durationMinutes}m ${durationSeconds}s`;\n\n const details = {\n operation: operationType,\n duration: `${durationMinutes}m ${durationSeconds}s`,\n totalMemories,\n successful,\n failed,\n successRate: `${successRate}%`,\n averageTimePerMemory: `${avgTimePerMemory}ms`\n };\n\n return { summary, details };\n }\n\n /**\n * Generate progress messages for UI updates\n */\n static generateProgressMessage(\n current: number, \n total: number, \n operation: string = 'Processing'\n ): string {\n const percentage = Math.floor((current / total) * 100);\n const remaining = total - current;\n \n if (current === 0) {\n return `Starting ${operation.toLowerCase()}...`;\n } else if (current === total) {\n return `${operation} completed!`;\n } else if (current < total / 4) {\n return `${operation} memories... (${current}/${total})`;\n } else if (current < total / 2) {\n return `${percentage}% complete... (${remaining} remaining)`;\n } else if (current < total * 0.9) {\n return `Almost done... ${percentage}% complete`;\n } else {\n return `Finishing up... ${remaining} memories left`;\n }\n }\n\n /**\n * Compare memory content for deduplication\n */\n static calculateSimilarity(content1: string, content2: string): number {\n // Simple similarity check - could be enhanced with more sophisticated algorithms\n const words1 = content1.toLowerCase().split(/\\s+/);\n const words2 = content2.toLowerCase().split(/\\s+/);\n \n const set1 = new Set(words1);\n const set2 = new Set(words2);\n \n const intersection = new Set([...set1].filter(word => set2.has(word)));\n const union = new Set([...set1, ...set2]);\n \n return union.size > 0 ? intersection.size / union.size : 0;\n }\n\n /**\n * Find potential duplicates in memory list\n */\n static findPotentialDuplicates(\n memories: Array<{ content: string; title?: string; tags?: string[] }>,\n similarityThreshold: number = 0.8\n ): Array<{\n memory: { content: string; title?: string; tags?: string[] };\n duplicates: Array<{\n memory: { content: string; title?: string; tags?: string[] };\n similarity: number;\n index: number;\n }>;\n }> {\n const duplicates: Array<{\n memory: { content: string; title?: string; tags?: string[] };\n duplicates: Array<{\n memory: { content: string; title?: string; tags?: string[] };\n similarity: number;\n index: number;\n }>;\n }> = [];\n\n for (let i = 0; i < memories.length; i++) {\n const currentMemory = memories[i];\n const potentialDuplicates: Array<{\n memory: { content: string; title?: string; tags?: string[] };\n similarity: number;\n index: number;\n }> = [];\n\n for (let j = i + 1; j < memories.length; j++) {\n const compareMemory = memories[j];\n const similarity = this.calculateSimilarity(currentMemory.content, compareMemory.content);\n \n if (similarity >= similarityThreshold) {\n potentialDuplicates.push({\n memory: compareMemory,\n similarity,\n index: j\n });\n }\n }\n\n if (potentialDuplicates.length > 0) {\n duplicates.push({\n memory: currentMemory,\n duplicates: potentialDuplicates\n });\n }\n }\n\n return duplicates;\n }\n}\n\n// Export utility functions for direct use\nexport const validateMemories = MemoryUtils.validateMemories;\nexport const formatForVectorImport = MemoryUtils.formatForVectorImport;\nexport const chunkMemories = MemoryUtils.chunkMemories;\nexport const estimateBatchOperation = MemoryUtils.estimateBatchOperation;\nexport const createBatchSummary = MemoryUtils.createBatchSummary;\nexport const generateProgressMessage = MemoryUtils.generateProgressMessage;\nexport const findPotentialDuplicates = MemoryUtils.findPotentialDuplicates;\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-9A05-FB9C98\nconst __banditFingerprint_chatprovidertsx = 'BL-FP-E60286-2996';\nconst __auditTrail_chatprovidertsx = 'BL-AU-MGOIKVV6-O6E4';\n// File: chat-provider.tsx | Path: src/chat-provider.tsx | Hash: 9a052996\n\nimport React, { useEffect, useState } from \"react\";\nimport { PackageSettings, usePackageSettingsStore } from \"./store/packageSettingsStore\";\nimport { AUTH_TOKEN_CHANGED_EVENT, authenticationService } from \"./services/auth/authenticationService\";\nimport { useConversationStore } from \"./store/conversationStore\";\nimport { useAIQueryStore } from \"./store/aiQueryStore\";\nimport { useMemoryStore } from \"./store/memoryStore\";\nimport { useModelStore } from \"./store/modelStore\";\nimport { usePreferencesStore } from \"./store/preferencesStore\";\nimport { useProjectStore } from \"./store/projectStore\";\nimport { useConversationSyncStore } from \"./store/conversationSyncStore\";\nimport { useKnowledgeStore } from \"./store/knowledgeStore\";\nimport { useMCPToolsStore } from \"./store/mcpToolsStore\";\nimport { useKnowledgeStore as useKnowledgeHook } from \"./chat/hooks/useKnowledgeStore\";\nimport { embeddingService } from \"./services/embedding/embeddingService\";\nimport { aiProviderInitService } from \"./services/ai-provider-init.service\";\nimport brandingService, { BrandingConfigPayload } from \"./services/branding/brandingService\";\nimport indexedDBService from \"./services/indexedDB/indexedDBService\";\nimport { debugLogger } from \"./services/logging/debugLogger\";\nimport { NotificationProvider } from \"./shared/components/NotificationProvider\";\nimport { FeatureFlagProvider } from \"./contexts/FeatureFlagContext\";\nimport { FeatureFlagConfig } from \"./types/featureFlags\";\nimport \"./chat-provider.css\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport { StoredBanditConfigRecord } from \"./types/config\";\n\nexport interface ChatConfig {\n packageSettings: PackageSettings;\n /** Feature flag configuration - can override packageSettings.featureFlags */\n featureFlags?: FeatureFlagConfig;\n children?: React.ReactNode;\n}\n\nexport const ChatProvider: React.FC<ChatConfig> = (props) => {\n const { loadDocuments } = useKnowledgeHook();\n const [queryClient] = useState(() => new QueryClient());\n\n // Determine final feature flag configuration\n const featureFlagConfig: FeatureFlagConfig = {\n ...props.packageSettings.featureFlags,\n ...props.featureFlags\n };\n\n useEffect(() => {\n const initializeAsync = async () => {\n // Set package settings first\n usePackageSettingsStore.setState(() => ({\n settings: props.packageSettings,\n }));\n\n // Initialize the new AI provider system early\n try {\n await aiProviderInitService.initializeFromSettings();\n } catch (error) {\n debugLogger.error(\"Failed to initialize AI provider:\", { error });\n }\n\n const token = authenticationService.getToken();\n if (token && !authenticationService.isTokenExpired(token)) {\n authenticationService.setToken(token);\n } else {\n authenticationService.clearToken();\n }\n\n useConversationStore.getState().hydrate();\n useProjectStore.getState().hydrate();\n useAIQueryStore.getState().hydrate();\n useMemoryStore.getState().hydrate();\n \n const isPlaygroundRoute = typeof window !== \"undefined\" && window.location.pathname.includes(\"/playground\");\n const isPlaygroundMode = isPlaygroundRoute || props.packageSettings.playgroundMode === true;\n\n if (isPlaygroundMode) {\n debugLogger.info(\"ChatProvider: Playground mode detected — skipping remote preference and sync initialization\");\n } else {\n // Load preferences, knowledge docs, and MCP tools\n await usePreferencesStore.getState().loadPreferences();\n await useKnowledgeStore.getState().loadDocs();\n await useMCPToolsStore.getState().loadTools();\n await useConversationSyncStore.getState().initialize();\n }\n \n // Initialize models after AI provider is set up\n debugLogger.info(\"ChatProvider about to call initModels - checking for existing branding first\");\n \n // Get existing branding before initModels to protect user-saved branding\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }] as const;\n let existingBranding: StoredBanditConfigRecord[\"branding\"] | null = null;\n try {\n const config = await indexedDBService.get<StoredBanditConfigRecord>(\n \"banditConfig\",\n 1,\n \"config\",\n \"main\",\n storeConfigs\n );\n if (config?.branding?.userSaved) {\n existingBranding = config.branding;\n debugLogger.info(\"Found user-saved branding to protect during initModels\", {\n hasText: !!existingBranding.brandingText,\n hasLogo: !!existingBranding.logoBase64,\n theme: existingBranding.theme\n });\n }\n } catch (err) {\n debugLogger.warn(\"Could not check existing branding before initModels\", { error: err });\n }\n \n await useModelStore.getState().initModels().catch((err) => {\n debugLogger.error(\"❌ Failed to initialize models:\", { error: err });\n });\n \n // Restore user branding if it was overwritten\n if (existingBranding) {\n try {\n const afterInitModels = await indexedDBService.get<StoredBanditConfigRecord>(\n \"banditConfig\",\n 1,\n \"config\",\n \"main\",\n storeConfigs\n );\n if (JSON.stringify(afterInitModels?.branding) !== JSON.stringify(existingBranding)) {\n debugLogger.warn(\"ChatProvider: initModels overwrote user branding! Restoring...\");\n await indexedDBService.put<StoredBanditConfigRecord>(\"banditConfig\", 1, \"config\", {\n ...afterInitModels,\n id: \"main\",\n branding: existingBranding,\n }, storeConfigs);\n debugLogger.info(\"ChatProvider: User branding restored after initModels\");\n }\n } catch (err) {\n debugLogger.error(\"ChatProvider: Failed to restore branding after initModels\", { error: err });\n }\n }\n\n if (props.packageSettings.brandingConfigUrl) {\n fetch(props.packageSettings.brandingConfigUrl)\n .then((res) => {\n if (!res.ok) {\n throw new Error(`HTTP error ${res.status}`);\n }\n return res.json();\n })\n .then((json: unknown) => {\n if (json && typeof json === \"object\") {\n brandingService.setBrandingFromConfig(json as BrandingConfigPayload);\n }\n })\n .catch((err) => {\n debugLogger.error(\"❌ Failed to fetch or apply branding config:\", { error: err });\n });\n }\n\n if (!isPlaygroundMode) {\n loadDocuments();\n embeddingService.backfillMissingEmbeddings().catch((err: unknown) => {\n debugLogger.error(\"❌ Failed to backfill memory embeddings:\", { error: err });\n });\n } else {\n debugLogger.info(\"ChatProvider: Playground mode skipping knowledge backfill\");\n }\n };\n\n initializeAsync();\n }, [props.packageSettings, loadDocuments]);\n\n useEffect(() => {\n const isPlaygroundRoute = typeof window !== \"undefined\" && window.location.pathname.includes(\"/playground\");\n const isPlaygroundMode = isPlaygroundRoute || props.packageSettings.playgroundMode === true;\n\n if (isPlaygroundMode || !props.packageSettings.gatewayApiUrl) {\n return;\n }\n\n const initializeSyncState = async () => {\n try {\n await useConversationSyncStore.getState().initialize();\n } catch (error) {\n debugLogger.error(\"ChatProvider: deferred sync initialization failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n\n if (typeof window === \"undefined\") {\n return;\n }\n\n const handleAuthTokenChange = () => {\n void initializeSyncState();\n };\n\n window.addEventListener(AUTH_TOKEN_CHANGED_EVENT, handleAuthTokenChange);\n window.addEventListener(\"pageshow\", handleAuthTokenChange);\n window.addEventListener(\"focus\", handleAuthTokenChange);\n\n return () => {\n window.removeEventListener(AUTH_TOKEN_CHANGED_EVENT, handleAuthTokenChange);\n window.removeEventListener(\"pageshow\", handleAuthTokenChange);\n window.removeEventListener(\"focus\", handleAuthTokenChange);\n };\n }, [props.packageSettings.gatewayApiUrl, props.packageSettings.playgroundMode]);\n\n return (\n <QueryClientProvider client={queryClient}>\n <FeatureFlagProvider config={featureFlagConfig}>\n <NotificationProvider>\n {props.children}\n </NotificationProvider>\n </FeatureFlagProvider>\n </QueryClientProvider>\n );\n};\n\nexport default ChatProvider;\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-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\";\nexport const AUTH_TOKEN_CHANGED_EVENT = \"bandit:auth-token-changed\";\n\nfunction emitAuthTokenChanged(token: string | null) {\n if (typeof window === \"undefined\") {\n return;\n }\n window.dispatchEvent(new CustomEvent(AUTH_TOKEN_CHANGED_EVENT, {\n detail: { token }\n }));\n}\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 emitAuthTokenChanged(token);\n }\n\n clearToken() {\n localStorage.removeItem(TOKEN_KEY);\n useAuthenticationStore.getState().clearToken();\n emitAuthTokenChanged(null);\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-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-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-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 indexedDBService from \"../services/indexedDB/indexedDBService\";\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 SYNC_IDENTITY_STORAGE_KEY = \"banditConversationSyncIdentity\";\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\nconst PROJECT_DB_NAME = \"bandit-projects\";\nconst PROJECT_DB_VERSION = 1;\nconst PROJECT_STORE_NAME = \"projects\";\nconst PROJECT_STORE_CONFIGS = [{ name: PROJECT_STORE_NAME, keyPath: \"id\" }];\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 hasLoadedPreference: boolean;\n initializedForToken: string | null;\n initializedForIdentity: string | null;\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 getStoredSyncIdentity(): string | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n try {\n return window.localStorage.getItem(SYNC_IDENTITY_STORAGE_KEY);\n } catch (error) {\n debugLogger.warn(\"conversationSyncStore: unable to read stored sync identity\", { error });\n return null;\n }\n}\n\nfunction setStoredSyncIdentity(identity: string | null) {\n if (typeof window === \"undefined\") {\n return;\n }\n try {\n if (identity) {\n window.localStorage.setItem(SYNC_IDENTITY_STORAGE_KEY, identity);\n } else {\n window.localStorage.removeItem(SYNC_IDENTITY_STORAGE_KEY);\n }\n } catch (error) {\n debugLogger.warn(\"conversationSyncStore: unable to persist sync identity\", { error });\n }\n}\n\nfunction getPackageDefaultAdvancedKnowledgeSync(): boolean | undefined {\n return usePackageSettingsStore.getState().settings?.advancedKnowledgeSyncDefaultEnabled;\n}\n\nfunction clearAutoSyncTimer() {\n if (autoSyncTimeout) {\n clearTimeout(autoSyncTimeout);\n autoSyncTimeout = null;\n }\n}\n\nfunction resolveAuthIdentity(token: string | null): string | null {\n if (!token) {\n return null;\n }\n\n const claims = authenticationService.parseJwtClaims(token);\n if (claims?.sub) {\n return claims.sub;\n }\n\n if (claims?.email) {\n return `email:${claims.email.toLowerCase()}`;\n }\n\n return `token:${token.slice(0, 32)}`;\n}\n\nfunction buildQueueResetState() {\n return {\n pendingConversationUpserts: new Set<string>(),\n pendingConversationDeletes: new Set<string>(),\n pendingProjectUpserts: new Set<string>(),\n pendingProjectDeletes: new Set<string>(),\n conflicts: null,\n lastSyncAt: null,\n cursor: null,\n lastError: null,\n totalConversationsOnServer: undefined,\n totalProjectsOnServer: undefined,\n hasCompletedInitialUpload: false,\n warningConversations: [],\n oversizedConversations: [],\n };\n}\n\nasync function clearLocalStoresForIdentitySwitch(fromIdentity: string, toIdentity: string) {\n const conversationCount = useConversationStore.getState().conversations.length;\n const projectCount = useProjectStore.getState().projects.length;\n\n debugLogger.warn(\"conversationSyncStore: auth identity changed, clearing local conversation/project cache\", {\n fromIdentity,\n toIdentity,\n conversationCount,\n projectCount,\n });\n\n suppressTracking = true;\n try {\n await useConversationStore.getState().clearAllConversations();\n await indexedDBService.clear(\n PROJECT_DB_NAME,\n PROJECT_DB_VERSION,\n PROJECT_STORE_NAME,\n PROJECT_STORE_CONFIGS\n );\n useProjectStore.setState({ projects: [] });\n conversationsMeta = snapshotConversationMetaMap(useConversationStore.getState().conversations);\n projectsMeta = snapshotProjectMetaMap(useProjectStore.getState().projects);\n } catch (error) {\n debugLogger.error(\"conversationSyncStore: failed to clear local stores on auth switch\", {\n error: error instanceof Error ? error.message : String(error),\n });\n } finally {\n suppressTracking = false;\n }\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 hasLoadedPreference: false,\n initializedForToken: null,\n initializedForIdentity: null,\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 ensureTrackersInitialized();\n\n const gatewayUrl = usePackageSettingsStore.getState().settings?.gatewayApiUrl;\n const token = authenticationService.getToken();\n const tokenIdentity = resolveAuthIdentity(token);\n const current = get();\n const storedIdentity = getStoredSyncIdentity();\n const knownIdentity = current.initializedForIdentity ?? storedIdentity;\n if (\n current.initialized &&\n current.hasLoadedPreference &&\n knownIdentity &&\n tokenIdentity &&\n knownIdentity === tokenIdentity\n ) {\n return;\n }\n\n const hasIdentitySwitch = Boolean(\n knownIdentity &&\n tokenIdentity &&\n knownIdentity !== tokenIdentity\n );\n\n if (hasIdentitySwitch) {\n clearAutoSyncTimer();\n set({\n ...buildQueueResetState(),\n syncEnabled: false,\n status: \"disabled\",\n hasLoadedPreference: false,\n initializedForToken: null,\n initializedForIdentity: tokenIdentity,\n });\n await clearLocalStoresForIdentitySwitch(\n knownIdentity as string,\n tokenIdentity as string\n );\n setStoredSyncIdentity(tokenIdentity);\n }\n\n if (!gatewayUrl) {\n debugLogger.info(\"conversationSyncStore: gateway API URL not configured; sync disabled\");\n if (tokenIdentity) {\n setStoredSyncIdentity(tokenIdentity);\n }\n set({\n ...buildQueueResetState(),\n initialized: true,\n hasLoadedPreference: false,\n initializedForToken: null,\n initializedForIdentity: tokenIdentity,\n status: \"disabled\",\n syncEnabled: false,\n });\n return;\n }\n\n if (!token) {\n debugLogger.info(\"conversationSyncStore: no authentication token; sync disabled until login\");\n clearAutoSyncTimer();\n set({\n ...buildQueueResetState(),\n initialized: true,\n hasLoadedPreference: false,\n initializedForToken: null,\n initializedForIdentity: null,\n status: \"disabled\",\n syncEnabled: false,\n });\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({\n initialized: true,\n hasLoadedPreference: true,\n initializedForToken: token,\n initializedForIdentity: tokenIdentity,\n });\n setStoredSyncIdentity(tokenIdentity);\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({\n initialized: true,\n hasLoadedPreference: false,\n initializedForToken: null,\n initializedForIdentity: tokenIdentity,\n status: \"error\",\n lastError: message,\n });\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 set({\n hasLoadedPreference: true,\n initializedForToken: authenticationService.getToken(),\n initializedForIdentity: resolveAuthIdentity(authenticationService.getToken()),\n });\n setStoredSyncIdentity(resolveAuthIdentity(authenticationService.getToken()));\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 set({\n hasLoadedPreference: true,\n initializedForToken: authenticationService.getToken(),\n initializedForIdentity: resolveAuthIdentity(authenticationService.getToken()),\n });\n setStoredSyncIdentity(resolveAuthIdentity(authenticationService.getToken()));\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 const tokenIdentity = resolveAuthIdentity(token);\n if (\n state.initializedForIdentity &&\n tokenIdentity &&\n state.initializedForIdentity !== tokenIdentity\n ) {\n debugLogger.warn(\"conversationSyncStore: runSync aborted due auth identity mismatch; reinitializing\", {\n initializedForIdentity: state.initializedForIdentity,\n tokenIdentity,\n });\n await get().initialize();\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-BF8A-82BFF7\nconst __banditFingerprint_store_mcpToolsStorets = 'BL-FP-414506-12AF';\nconst __auditTrail_store_mcpToolsStorets = 'BL-AU-MGOIKVW4-PIWV';\n// File: mcpToolsStore.ts | Path: src/store/mcpToolsStore.ts | Hash: bf8a12af\n\nimport { create } from \"zustand\";\nimport indexedDBService from \"../services/indexedDB/indexedDBService\";\nimport { debugLogger } from \"../services/logging/debugLogger\";\n\nexport interface MCPTool {\n id: string;\n name: string;\n description: string;\n enabled: boolean;\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: {\n type: \"object\";\n properties: Record<string, unknown>;\n required: string[];\n };\n };\n endpoint?: string; // API endpoint for gateway calls\n method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n isBuiltIn?: boolean;\n}\n\ninterface MCPToolsStore {\n tools: MCPTool[];\n isLoaded: boolean;\n addTool: (tool: Omit<MCPTool, \"id\">) => void;\n updateTool: (id: string, updates: Partial<MCPTool>) => void;\n deleteTool: (id: string) => void;\n toggleTool: (id: string) => void;\n loadTools: () => Promise<void>;\n saveTools: () => Promise<void>;\n getEnabledTools: () => MCPTool[];\n}\n\n// Built-in controller-backed tools\nconst healthCheckTool: MCPTool = {\n id: \"health-check\",\n name: \"check_gateway_health\",\n description: \"Check the health status of the gateway API service\",\n enabled: true,\n type: \"function\",\n function: {\n name: \"check_gateway_health\",\n description: \"Check the health status of the gateway API service\",\n parameters: {\n type: \"object\",\n properties: {},\n required: []\n }\n },\n endpoint: \"/mcp/health\",\n method: \"GET\",\n isBuiltIn: true\n};\n\nconst webSearchTool: MCPTool = {\n id: \"web-search\",\n name: \"web_search\",\n description: \"Search the web for current information, documentation, and facts\",\n enabled: true,\n type: \"function\",\n function: {\n name: \"web_search\",\n description: \"Search the web and return ranked results with snippets (and an optional summarized answer). Use for current events, documentation, libraries, error messages, and factual lookups.\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"The search query — natural language or keywords\" },\n count: { type: \"number\", description: \"Number of results to return (1-10, default 5)\" },\n include_answer: { type: \"boolean\", description: \"Include a short summarized answer when available\" }\n },\n required: [\"query\"]\n }\n },\n endpoint: \"/mcp/web-search\",\n method: \"GET\",\n isBuiltIn: true\n};\n\nconst webFetchTool: MCPTool = {\n id: \"web-fetch\",\n name: \"web_fetch\",\n description: \"Fetch the text content of a specific URL\",\n enabled: true,\n type: \"function\",\n function: {\n name: \"web_fetch\",\n description: \"Fetch a single public URL and return its trimmed text content. Use when you already have a specific link you need to read.\",\n parameters: {\n type: \"object\",\n properties: {\n url: { type: \"string\", description: \"Absolute http(s) URL to fetch\" }\n },\n required: [\"url\"]\n }\n },\n endpoint: \"/mcp/web-fetch\",\n method: \"GET\",\n isBuiltIn: true\n};\n\n// New: Image Generation tool (OpenAI DALL·E 3)\nconst imageGenerationTool: MCPTool = {\n id: \"image-generation\",\n name: \"image_generation\",\n description: \"Generate high-quality images using DALL-E 3 from text prompts\",\n enabled: true,\n type: \"function\",\n function: {\n name: \"image_generation\",\n description: \"Generate high-quality images using DALL-E 3 from text prompts\",\n parameters: {\n type: \"object\",\n properties: {\n prompt: { type: \"string\", description: \"Text description of the image to generate\" },\n size: { type: \"string\", enum: [\"1024x1024\", \"1024x1792\", \"1792x1024\"], description: \"Image dimensions\" },\n quality: { type: \"string\", enum: [\"standard\", \"hd\"], description: \"Image quality\" },\n style: { type: \"string\", enum: [\"vivid\", \"natural\"], description: \"Style preference\" }\n },\n required: [\"prompt\"]\n }\n },\n endpoint: \"/mcp/generate-image\",\n method: \"POST\",\n isBuiltIn: true\n};\n\n// Create a downloadable file for the user (stored ~1 hour at a gateway URL).\nconst createFileTool: MCPTool = {\n id: \"create-file\",\n name: \"create_file\",\n description: \"Create a downloadable file for the user (md, txt, csv, json, html, docx, pptx). Returns a temporary (~1 hour) download link.\",\n enabled: true,\n type: \"function\",\n function: {\n name: \"create_file\",\n description:\n \"Generate a file the user can download. For docx/pptx write well-structured Markdown (headings, lists, tables; use '## ' headings to start each slide). Returns a short-lived (~1 hour) download URL — tell the user it expires.\",\n parameters: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"The file content (Markdown for docx/pptx; raw text for others).\" },\n filename: { type: \"string\", description: \"Desired filename, e.g. 'report.docx' or 'notes.md'.\" },\n format: {\n type: \"string\",\n enum: [\"md\", \"txt\", \"csv\", \"json\", \"html\", \"xml\", \"yaml\", \"docx\", \"pptx\"],\n description: \"File format. Defaults to md.\",\n },\n },\n required: [\"content\", \"format\"],\n },\n },\n endpoint: \"/mcp/create-file\",\n method: \"POST\",\n isBuiltIn: true,\n};\n\nconst defaultTools: MCPTool[] = [healthCheckTool, webSearchTool, webFetchTool, imageGenerationTool, createFileTool];\n\nexport const useMCPToolsStore = create<MCPToolsStore>((set, get) => ({\n tools: defaultTools,\n isLoaded: false,\n \n addTool: (toolData) => {\n const newTool: MCPTool = {\n ...toolData,\n id: `tool-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n };\n set((state) => ({\n tools: [...state.tools, newTool],\n }));\n get().saveTools();\n },\n \n updateTool: (id, updates) => {\n set((state) => ({\n tools: state.tools.map((tool) =>\n tool.id === id ? { ...tool, ...updates } : tool\n ),\n }));\n get().saveTools();\n },\n \n deleteTool: (id) => {\n set((state) => ({\n tools: state.tools.filter((tool) => tool.id !== id || tool.isBuiltIn),\n }));\n get().saveTools();\n },\n \n toggleTool: (id) => {\n set((state) => ({\n tools: state.tools.map((tool) =>\n tool.id === id ? { ...tool, enabled: !tool.enabled } : tool\n ),\n }));\n get().saveTools();\n },\n \n getEnabledTools: () => {\n return get().tools.filter((tool) => tool.enabled);\n },\n \n loadTools: async () => {\n try {\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n const data = await indexedDBService.get(\"banditConfig\", 1, \"config\", \"mcpTools\", storeConfigs);\n \n if (data?.tools && Array.isArray(data.tools)) {\n // Merge saved tools with built-in tools, ensuring built-ins always use default definition\n const savedTools = data.tools as MCPTool[];\n const builtInIds = defaultTools.map(t => t.id);\n const customTools = savedTools.filter(\n (tool) => !tool.isBuiltIn && !builtInIds.includes(tool.id)\n );\n\n set({\n tools: [...defaultTools, ...customTools],\n isLoaded: true\n });\n debugLogger.info(\"MCP tools loaded from IndexedDB\", { \n totalTools: defaultTools.length + customTools.length,\n builtInTools: defaultTools.length,\n customTools: customTools.length\n });\n } else {\n // First time, save defaults\n set({ isLoaded: true });\n await get().saveTools();\n debugLogger.info(\"Default MCP tools initialized\");\n }\n } catch (error) {\n debugLogger.error(\"Failed to load MCP tools from IndexedDB\", { error });\n set({ isLoaded: true }); // Mark as loaded even if failed, so UI can render\n }\n },\n \n saveTools: async () => {\n try {\n const { tools } = get();\n const storeConfigs = [{ name: \"config\", keyPath: \"id\" }];\n \n const customTools = tools.filter((tool) => !tool.isBuiltIn);\n\n await indexedDBService.put(\"banditConfig\", 1, \"config\", {\n id: \"mcpTools\",\n tools: customTools,\n }, storeConfigs);\n\n debugLogger.debug(\"MCP tools saved to IndexedDB\", { toolCount: customTools.length });\n } catch (error) {\n debugLogger.error(\"Failed to save MCP tools to IndexedDB\", { error });\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-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-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-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-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-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-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-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-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-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-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-BFD5-C74863\nconst __banditFingerprint_services_aiproviderinitservicets = 'BL-FP-DDF978-53AF';\nconst __auditTrail_services_aiproviderinitservicets = 'BL-AU-MGOIKVVR-WP87';\n// File: ai-provider-init.service.ts | Path: src/services/ai-provider-init.service.ts | Hash: bfd553af\n\nimport { useAIProviderStore } from \"../store/aiProviderStore\";\nimport { usePackageSettingsStore } from \"../store/packageSettingsStore\";\nimport { AIProviderConfig, AIProviderType } from \"./ai-provider/types/common.types\";\nimport { authenticationService } from \"./auth/authenticationService\";\nimport { debugLogger } from \"./logging/debugLogger\";\nimport indexedDBService from \"./indexedDB/indexedDBService\";\n\ntype StoredAIProviderConfig = AIProviderConfig & { id?: string };\n\n/**\n * Service to initialize AI providers based on package settings\n */\nexport class AIProviderInitService {\n private static instance: AIProviderInitService;\n\n private constructor() {}\n\n static getInstance(): AIProviderInitService {\n if (!AIProviderInitService.instance) {\n AIProviderInitService.instance = new AIProviderInitService();\n }\n return AIProviderInitService.instance;\n }\n\n /**\n * Initialize AI provider from package settings\n * Provides backward compatibility with existing Ollama settings\n */\n async initializeFromSettings(): Promise<void> {\n const settings = usePackageSettingsStore.getState().settings;\n if (!settings) {\n debugLogger.warn(\"No package settings found, cannot initialize AI provider\");\n return;\n }\n\n let providerConfig: AIProviderConfig;\n\n debugLogger.info(\"AI Provider Init: Starting initialization\", { \n hasSettings: !!settings,\n hasAiProvider: !!settings.aiProvider,\n ollamaUrl: settings.ollamaUrl\n });\n\n const isPlaygroundEnvironment =\n settings.playgroundMode === true ||\n settings.aiProvider?.type === AIProviderType.PLAYGROUND ||\n (settings.gatewayApiUrl?.toLowerCase()?.startsWith(\"playground://\") ?? false) ||\n (typeof window !== \"undefined\" && window.location.pathname.includes(\"/playground\"));\n\n // First, try to load provider configuration from IndexedDB\n if (isPlaygroundEnvironment) {\n debugLogger.info(\"AI Provider Init: Playground environment detected, bypassing saved provider config\");\n } else {\n try {\n const savedConfig = await indexedDBService.get<StoredAIProviderConfig>(\n 'banditConfig', \n 1, \n 'config', \n 'aiProvider',\n [{ name: 'config', keyPath: 'id' }]\n );\n \n if (savedConfig) {\n debugLogger.info('AI Provider Init: Found saved config in IndexedDB', { type: savedConfig.type });\n \n // Filter out the 'id' property that was added for IndexedDB storage\n const { id: _id, ...configWithoutId } = savedConfig;\n providerConfig = { ...configWithoutId };\n if (providerConfig.type === AIProviderType.ANTHROPIC) {\n providerConfig = this.convertAnthropicConfig(providerConfig, settings?.gatewayApiUrl);\n }\n\n // Ensure tokenFactory is present for providers that need it\n providerConfig = this.ensureTokenFactory(providerConfig);\n \n // Initialize the provider with saved config\n try {\n const { createProvider } = useAIProviderStore.getState();\n createProvider(providerConfig);\n \n const provider = useAIProviderStore.getState().provider;\n if (provider) {\n try {\n await provider.validateServiceAvailability({ timeoutMs: 5000 });\n debugLogger.info(`AI Provider initialized and validated from IndexedDB: ${providerConfig.type}`);\n } catch (validationError) {\n debugLogger.warn(`AI Provider created but validation failed`, { error: validationError });\n }\n }\n return; // Successfully initialized from IndexedDB\n } catch (error) {\n debugLogger.error(\"Failed to initialize saved provider config, falling back to package settings\", { error });\n }\n }\n \n debugLogger.info('AI Provider Init: No saved config found, using package settings');\n } catch (error) {\n debugLogger.warn('AI Provider Init: Failed to load from IndexedDB, using package settings', { error });\n }\n }\n\n // Fallback to package settings if no saved config found\n if (settings.aiProvider) {\n providerConfig = { ...settings.aiProvider };\n if (providerConfig.type === AIProviderType.ANTHROPIC) {\n providerConfig = this.convertAnthropicConfig(providerConfig, settings.gatewayApiUrl);\n }\n \n providerConfig = this.ensureTokenFactory(providerConfig);\n \n debugLogger.info(\"Using explicit AI provider config\", providerConfig);\n } else {\n // Fall back to legacy Ollama settings for backward compatibility\n providerConfig = {\n type: AIProviderType.OLLAMA,\n baseUrl: settings.ollamaUrl,\n tokenFactory: () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n \n // If the bandit-engine's service doesn't have a token, try direct localStorage access\n if (!token) {\n token = localStorage.getItem(\"authToken\");\n }\n \n // Also try the authentication store if available\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch (e) {\n // Store might not be available, that's ok\n }\n }\n \n debugLogger.info(\"AIProviderInit: Token factory called\", { \n hasToken: !!token,\n localStorage: !!localStorage.getItem(\"authToken\")\n });\n return token;\n }\n };\n debugLogger.info(\"Using legacy Ollama config\", providerConfig);\n }\n\n try {\n // First validate if the service is available\n const { createProvider } = useAIProviderStore.getState();\n \n // Try to create and validate the provider\n createProvider(providerConfig);\n \n // Test provider availability\n const provider = useAIProviderStore.getState().provider;\n if (provider) {\n try {\n await provider.validateServiceAvailability({ timeoutMs: 5000 });\n debugLogger.info(`AI Provider initialized and validated: ${providerConfig.type}`);\n } catch (validationError) {\n debugLogger.warn(`AI Provider created but validation failed:`, { error: validationError });\n // Provider is created but may not be fully available - this is ok for offline scenarios\n }\n }\n } catch (error) {\n debugLogger.error(\"Failed to initialize AI provider:\", { error });\n \n // Try to fall back to default Ollama if initial provider fails\n if (providerConfig.type !== AIProviderType.OLLAMA) {\n try {\n const fallbackConfig: AIProviderConfig = {\n type: AIProviderType.OLLAMA,\n baseUrl: settings.ollamaUrl || 'http://localhost:11434',\n tokenFactory: () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n \n // If the bandit-engine's service doesn't have a token, try direct localStorage access\n if (!token) {\n token = localStorage.getItem(\"authToken\");\n }\n \n // Also try the authentication store if available\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch (e) {\n // Store might not be available, that's ok\n }\n }\n \n debugLogger.info(\"AIProviderInit: Fallback tokenFactory\", { \n hasToken: !!token,\n localStorage: !!localStorage.getItem(\"authToken\")\n });\n return token;\n }\n };\n const { createProvider } = useAIProviderStore.getState();\n createProvider(fallbackConfig);\n debugLogger.info(\"Fallback to Ollama provider successful\");\n } catch (fallbackError) {\n debugLogger.error(\"Failed to initialize fallback Ollama provider:\", { error: fallbackError });\n }\n } else {\n // If Ollama provider fails, try localhost as ultimate fallback\n try {\n const localFallbackConfig: AIProviderConfig = {\n type: AIProviderType.OLLAMA,\n baseUrl: 'http://localhost:11434',\n tokenFactory: () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n \n // If the bandit-engine's service doesn't have a token, try direct localStorage access\n if (!token) {\n token = localStorage.getItem(\"authToken\");\n }\n \n // Also try the authentication store if available\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch (e) {\n // Store might not be available, that's ok\n }\n }\n \n debugLogger.info(\"AIProviderInit: Local fallback tokenFactory\", { \n hasToken: !!token,\n localStorage: !!localStorage.getItem(\"authToken\")\n });\n return token;\n }\n };\n const { createProvider } = useAIProviderStore.getState();\n createProvider(localFallbackConfig);\n debugLogger.info(\"Fallback to localhost Ollama provider successful\");\n } catch (localFallbackError) {\n debugLogger.error(\"All provider initialization attempts failed:\", { error: localFallbackError });\n }\n }\n }\n }\n\n /**\n * Switch to a different AI provider\n */\n switchProvider(config: AIProviderConfig): void {\n try {\n const normalizedConfig = this.ensureTokenFactory({ ...config });\n const { switchProvider } = useAIProviderStore.getState();\n switchProvider(normalizedConfig);\n debugLogger.info(`Switched to AI provider: ${normalizedConfig.type}`);\n } catch (error) {\n debugLogger.error(\"Failed to switch AI provider:\", { error });\n throw error;\n }\n }\n\n /**\n * Get the current provider type\n */\n getCurrentProviderType(): string | null {\n const provider = useAIProviderStore.getState().provider;\n return provider ? provider.getProviderType() : null;\n }\n\n /**\n * Check if a provider is initialized\n */\n isProviderInitialized(): boolean {\n return useAIProviderStore.getState().provider !== null;\n }\n\n private convertAnthropicConfig(config: AIProviderConfig, gatewayUrl?: string | null): AIProviderConfig {\n if (config.type !== AIProviderType.ANTHROPIC) {\n return config;\n }\n\n const defaultModel = typeof config.defaultModel === 'string' && config.defaultModel.trim()\n ? config.defaultModel.trim()\n : 'claude-3-5-sonnet-latest';\n\n const normalized: AIProviderConfig = {\n type: AIProviderType.GATEWAY,\n gatewayUrl: gatewayUrl || config.gatewayUrl || '',\n provider: 'anthropic',\n defaultModel,\n tokenFactory: config.tokenFactory\n };\n\n debugLogger.info('AI Provider Init: Converted direct Anthropic provider to gateway configuration');\n return normalized;\n }\n\n /**\n * Ensure providers that require auth have a token factory configured.\n * Handles both UI auth tokens and API key scenarios.\n */\n private ensureTokenFactory(config: AIProviderConfig): AIProviderConfig {\n if (config.type === AIProviderType.OLLAMA || config.type === AIProviderType.GATEWAY) {\n const existingFactory = config.tokenFactory;\n if (existingFactory) {\n return config;\n }\n\n // Prefer explicit API key if provided\n if (typeof config.apiKey === 'string' && config.apiKey.trim() !== '') {\n const key = config.apiKey.trim();\n config.tokenFactory = () => key;\n debugLogger.info(\"AIProviderInit: Using API key for token factory\", {\n type: config.type,\n hasKey: true\n });\n return config;\n }\n\n // Fallback to stored auth tokens (UI sessions)\n config.tokenFactory = () => {\n // Try multiple sources for the token\n let token = authenticationService.getToken();\n\n if (!token && typeof localStorage !== 'undefined') {\n try {\n token = localStorage.getItem(\"authToken\");\n } catch {\n // ignore storage errors\n }\n }\n\n if (!token) {\n try {\n const { useAuthenticationStore } = require(\"../../store/authenticationStore\");\n const authStore = useAuthenticationStore.getState();\n token = authStore.token;\n } catch {\n // Store might not be available, that's ok\n }\n }\n\n debugLogger.info(\"AIProviderInit: Token factory resolved auth token\", { \n hasToken: !!token,\n });\n return token;\n };\n }\n\n return config;\n }\n}\n\nexport const aiProviderInitService = AIProviderInitService.getInstance();\n","/*\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 NotificationProvider;\n","\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ","import styleInject from '#style-inject';styleInject(\"*,\\n*::before,\\n*::after {\\n box-sizing: border-box;\\n margin: 0;\\n padding: 0;\\n}\\n:root {\\n --vh: 1vh;\\n --input-offset: 1.5rem;\\n}\\nhtml {\\n height: 100%;\\n overflow: hidden;\\n scrollbar-width: none;\\n -ms-overflow-style: none;\\n}\\nhtml::-webkit-scrollbar {\\n display: none;\\n}\\nbody {\\n height: 100%;\\n overflow: auto;\\n scrollbar-width: none;\\n -ms-overflow-style: none;\\n}\\nbody::-webkit-scrollbar {\\n display: none;\\n}\\na {\\n color: inherit;\\n text-decoration: none;\\n}\\n.container {\\n max-width: 1200px;\\n margin: 0 auto;\\n padding: 2rem;\\n}\\n.mt-2 {\\n margin-top: 0.5rem;\\n}\\n.mb-2 {\\n margin-bottom: 0.5rem;\\n}\\n.mx-auto {\\n margin-left: auto;\\n margin-right: auto;\\n}\\n.bandit-logo-container {\\n display: flex;\\n height: 50vh;\\n margin: auto;\\n}\\n.bandit-logo {\\n margin: auto;\\n display: flex;\\n flex: 1 1 auto;\\n flex-direction: column;\\n align-items: center;\\n width: 90vw;\\n max-width: 640px;\\n height: 55vh;\\n background-size: cover;\\n background-position: center center;\\n background-repeat: no-repeat;\\n transition: opacity 0.6s ease-in-out, transform 0.6s ease-in-out;\\n}\\n.bandit-logo-hidden {\\n opacity: 0;\\n transform: translateY(-10px);\\n pointer-events: none;\\n}\\n.bandit-logo-visible {\\n opacity: 1;\\n transform: translateY(0);\\n}\\n\")"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAkBA,gBA+Ca;AAjEb;AAAA;AAAA;AAkBA,qBAAuB;AA+ChB,IAAM,8BAA0B,uBAA6B,CAAC,KAAK,SAAS;AAAA,MACjF,UAAU;AAAA,MACV,aAAa,CAAC,aAAa,IAAI,EAAE,SAAS,CAAC;AAAA,MAC3C,aAAa,MAAM,IAAI,EAAE;AAAA,MACzB,eAAe,MAAM,IAAI,EAAE,UAAU,KAAK,CAAC;AAAA,IAC7C,EAAE;AAAA;AAAA;;;ACtEF,IA0CM,aAiJO;AA3Lb;AAAA;AAAA;AA0CA,IAAM,cAAN,MAAkB;AAAA,MACR;AAAA,MAER,cAAc;AAEZ,aAAK,gBAAgB,KAAK,sBAAsB;AAAA,MAClD;AAAA,MAEQ,wBAAiC;AAGvC,YAAI;AAEF,gBAAM,cAAc;AAKpB,cAAI,OAAO,WAAW,eAAe,OAAO,YAAY,2BAA2B,aAAa;AAC9F,mBAAO,CAAC,YAAY;AAAA,UACtB;AAGA,gBAAM,OAAO,YAAY;AACzB,cAAI,QAAQ,KAAK,KAAK;AACpB,mBAAO,KAAK,IAAI,aAAa;AAAA,UAC/B;AAGA,cAAI,OAAO,WAAW,eAAe,OAAO,UAAU;AACpD,kBAAM,WAAW,CAAC,aAAa,WAAW;AAC1C,kBAAM,WAAW,CAAC,QAAQ,MAAM;AAChC,mBAAO,SAAS,SAAS,OAAO,SAAS,QAAQ,KAC1C,SAAS,SAAS,OAAO,SAAS,IAAI;AAAA,UAC/C;AAAA,QACF,SAAS,GAAG;AAAA,QAEZ;AAGA,eAAO;AAAA,MACT;AAAA;AAAA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,oBAAoB;AAAA,IAC3B;AAEA,WAAO,iBAAiB,0BAA0B,qBAAqB;AACvE,WAAO,iBAAiB,YAAY,qBAAqB;AACzD,WAAO,iBAAiB,SAAS,qBAAqB;AAEtD,WAAO,MAAM;AACX,aAAO,oBAAoB,0BAA0B,qBAAqB;AAC1E,aAAO,oBAAoB,YAAY,qBAAqB;AAC5D,aAAO,oBAAoB,SAAS,qBAAqB;AAAA,IAC3D;AAAA,EACF,GAAG,CAAC,MAAM,gBAAgB,eAAe,MAAM,gBAAgB,cAAc,CAAC;AAE9E,SACE,6CAAC,0CAAoB,QAAQ,aAC3B,uDAAC,uBAAoB,QAAQ,mBAC3B,uDAAC,wBACE,gBAAM,UACT,GACF,GACF;AAEJ;AAEA,IAAO,wBAAQ;","names":["storeConfigs","db","import_zustand","useModelStore","storeConfigs","import_zustand","storeConfigs","e","import_rxjs","models","import_rxjs","import_rxjs","import_rxjs","import_rxjs","axios","e","rawToken","import_operators","import_operators","import_operators","import_operators","import_rxjs","normalizeImageUrl","models","import_rxjs","import_rxjs","import_rxjs","import_zustand","isRecord","import_react","import_zustand","user","TOKEN_KEY","import_zustand","import_zustand","DB_NAME","STORE_NAME","DB_VERSION","storeConfigs","DB_NAME","STORE_NAME","DB_VERSION","storeConfigs","uuidv4","import_zustand","DB_NAME","STORE_NAME","storeConfigs","import_zustand","import_uuid","DB_NAME","STORE_NAME","DB_VERSION","storeConfigs","uuidv4","import_zustand","import_uuid","uuidv4","import_zustand","import_uuid","uuidv4","storeConfigs","import_zustand","storeConfigs","import_react","import_uuid","import_rxjs","isRecord","import_rxjs","import_rxjs","import_rxjs","import_rxjs","MemoryUtils","import_react","DB_NAME","STORE_NAME","storeConfigs","import_react","useAIProviderStore","results","DB_NAME","STORE_NAME","useKnowledgeStore","storeConfigs","uuidv4","mammoth","useAuthenticationStore","import_react","import_jsx_runtime","import_jsx_runtime","useKnowledgeStore","storeConfigs"]}