@superatomai/sdk-node 0.0.2 → 0.0.3

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":["../node_modules/dotenv/package.json","../node_modules/dotenv/lib/main.js","../src/websocket.ts","../src/types.ts","../src/dashboards/types.ts","../src/reports/types.ts","../src/utils/logger.ts","../src/threads/uiblock.ts","../src/config/storage.ts","../src/threads/thread.ts","../src/threads/thread-manager.ts","../src/handlers/data-request.ts","../src/bundle.ts","../src/handlers/bundle-request.ts","../src/auth/utils.ts","../src/auth/user-storage.ts","../src/auth/validator.ts","../src/handlers/auth-login-requests.ts","../src/handlers/auth-verify-request.ts","../src/userResponse/groq.ts","../src/userResponse/utils.ts","../src/userResponse/schema.ts","../src/userResponse/prompt-loader.ts","../src/llm.ts","../src/userResponse/base-llm.ts","../src/userResponse/anthropic.ts","../src/userResponse/index.ts","../src/utils/log-collector.ts","../src/config/context.ts","../src/handlers/user-prompt-request.ts","../src/handlers/user-prompt-suggestions.ts","../src/userResponse/next-questions.ts","../src/handlers/actions-request.ts","../src/handlers/components-list-response.ts","../src/handlers/users.ts","../src/dashboards/dashboard-storage.ts","../src/handlers/dashboards.ts","../src/reports/report-storage.ts","../src/handlers/reports.ts","../src/auth/user-manager.ts","../src/dashboards/dashboard-manager.ts","../src/reports/report-manager.ts","../src/services/cleanup-service.ts","../src/index.ts"],"sourcesContent":["{\n \"name\": \"dotenv\",\n \"version\": \"17.2.3\",\n \"description\": \"Loads environment variables from .env file\",\n \"main\": \"lib/main.js\",\n \"types\": \"lib/main.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./lib/main.d.ts\",\n \"require\": \"./lib/main.js\",\n \"default\": \"./lib/main.js\"\n },\n \"./config\": \"./config.js\",\n \"./config.js\": \"./config.js\",\n \"./lib/env-options\": \"./lib/env-options.js\",\n \"./lib/env-options.js\": \"./lib/env-options.js\",\n \"./lib/cli-options\": \"./lib/cli-options.js\",\n \"./lib/cli-options.js\": \"./lib/cli-options.js\",\n \"./package.json\": \"./package.json\"\n },\n \"scripts\": {\n \"dts-check\": \"tsc --project tests/types/tsconfig.json\",\n \"lint\": \"standard\",\n \"pretest\": \"npm run lint && npm run dts-check\",\n \"test\": \"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000\",\n \"test:coverage\": \"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov\",\n \"prerelease\": \"npm test\",\n \"release\": \"standard-version\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git://github.com/motdotla/dotenv.git\"\n },\n \"homepage\": \"https://github.com/motdotla/dotenv#readme\",\n \"funding\": \"https://dotenvx.com\",\n \"keywords\": [\n \"dotenv\",\n \"env\",\n \".env\",\n \"environment\",\n \"variables\",\n \"config\",\n \"settings\"\n ],\n \"readmeFilename\": \"README.md\",\n \"license\": \"BSD-2-Clause\",\n \"devDependencies\": {\n \"@types/node\": \"^18.11.3\",\n \"decache\": \"^4.6.2\",\n \"sinon\": \"^14.0.1\",\n \"standard\": \"^17.0.0\",\n \"standard-version\": \"^9.5.0\",\n \"tap\": \"^19.2.0\",\n \"typescript\": \"^4.8.4\"\n },\n \"engines\": {\n \"node\": \">=12\"\n },\n \"browser\": {\n \"fs\": false\n }\n}\n","const fs = require('fs')\nconst path = require('path')\nconst os = require('os')\nconst crypto = require('crypto')\nconst packageJson = require('../package.json')\n\nconst version = packageJson.version\n\n// Array of tips to display randomly\nconst TIPS = [\n '🔐 encrypt with Dotenvx: https://dotenvx.com',\n '🔐 prevent committing .env to code: https://dotenvx.com/precommit',\n '🔐 prevent building .env in docker: https://dotenvx.com/prebuild',\n '📡 add observability to secrets: https://dotenvx.com/ops',\n '👥 sync secrets across teammates & machines: https://dotenvx.com/ops',\n '🗂️ backup and recover secrets: https://dotenvx.com/ops',\n '✅ audit secrets and track compliance: https://dotenvx.com/ops',\n '🔄 add secrets lifecycle management: https://dotenvx.com/ops',\n '🔑 add access controls to secrets: https://dotenvx.com/ops',\n '🛠️ run anywhere with `dotenvx run -- yourcommand`',\n '⚙️ specify custom .env file path with { path: \\'/custom/path/.env\\' }',\n '⚙️ enable debug logging with { debug: true }',\n '⚙️ override existing env vars with { override: true }',\n '⚙️ suppress all logs with { quiet: true }',\n '⚙️ write to custom object with { processEnv: myObject }',\n '⚙️ load multiple .env files with { path: [\\'.env.local\\', \\'.env\\'] }'\n]\n\n// Get a random tip from the tips array\nfunction _getRandomTip () {\n return TIPS[Math.floor(Math.random() * TIPS.length)]\n}\n\nfunction parseBoolean (value) {\n if (typeof value === 'string') {\n return !['false', '0', 'no', 'off', ''].includes(value.toLowerCase())\n }\n return Boolean(value)\n}\n\nfunction supportsAnsi () {\n return process.stdout.isTTY // && process.env.TERM !== 'dumb'\n}\n\nfunction dim (text) {\n return supportsAnsi() ? `\\x1b[2m${text}\\x1b[0m` : text\n}\n\nconst LINE = /(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/mg\n\n// Parse src into an Object\nfunction parse (src) {\n const obj = {}\n\n // Convert buffer to string\n let lines = src.toString()\n\n // Convert line breaks to same format\n lines = lines.replace(/\\r\\n?/mg, '\\n')\n\n let match\n while ((match = LINE.exec(lines)) != null) {\n const key = match[1]\n\n // Default undefined or null to empty string\n let value = (match[2] || '')\n\n // Remove whitespace\n value = value.trim()\n\n // Check if double quoted\n const maybeQuote = value[0]\n\n // Remove surrounding quotes\n value = value.replace(/^(['\"`])([\\s\\S]*)\\1$/mg, '$2')\n\n // Expand newlines if double quoted\n if (maybeQuote === '\"') {\n value = value.replace(/\\\\n/g, '\\n')\n value = value.replace(/\\\\r/g, '\\r')\n }\n\n // Add to object\n obj[key] = value\n }\n\n return obj\n}\n\nfunction _parseVault (options) {\n options = options || {}\n\n const vaultPath = _vaultPath(options)\n options.path = vaultPath // parse .env.vault\n const result = DotenvModule.configDotenv(options)\n if (!result.parsed) {\n const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)\n err.code = 'MISSING_DATA'\n throw err\n }\n\n // handle scenario for comma separated keys - for use with key rotation\n // example: DOTENV_KEY=\"dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod\"\n const keys = _dotenvKey(options).split(',')\n const length = keys.length\n\n let decrypted\n for (let i = 0; i < length; i++) {\n try {\n // Get full key\n const key = keys[i].trim()\n\n // Get instructions for decrypt\n const attrs = _instructions(result, key)\n\n // Decrypt\n decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)\n\n break\n } catch (error) {\n // last key\n if (i + 1 >= length) {\n throw error\n }\n // try next key\n }\n }\n\n // Parse decrypted .env string\n return DotenvModule.parse(decrypted)\n}\n\nfunction _warn (message) {\n console.error(`[dotenv@${version}][WARN] ${message}`)\n}\n\nfunction _debug (message) {\n console.log(`[dotenv@${version}][DEBUG] ${message}`)\n}\n\nfunction _log (message) {\n console.log(`[dotenv@${version}] ${message}`)\n}\n\nfunction _dotenvKey (options) {\n // prioritize developer directly setting options.DOTENV_KEY\n if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {\n return options.DOTENV_KEY\n }\n\n // secondary infra already contains a DOTENV_KEY environment variable\n if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {\n return process.env.DOTENV_KEY\n }\n\n // fallback to empty string\n return ''\n}\n\nfunction _instructions (result, dotenvKey) {\n // Parse DOTENV_KEY. Format is a URI\n let uri\n try {\n uri = new URL(dotenvKey)\n } catch (error) {\n if (error.code === 'ERR_INVALID_URL') {\n const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n throw error\n }\n\n // Get decrypt key\n const key = uri.password\n if (!key) {\n const err = new Error('INVALID_DOTENV_KEY: Missing key part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get environment\n const environment = uri.searchParams.get('environment')\n if (!environment) {\n const err = new Error('INVALID_DOTENV_KEY: Missing environment part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get ciphertext payload\n const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`\n const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION\n if (!ciphertext) {\n const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)\n err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'\n throw err\n }\n\n return { ciphertext, key }\n}\n\nfunction _vaultPath (options) {\n let possibleVaultPath = null\n\n if (options && options.path && options.path.length > 0) {\n if (Array.isArray(options.path)) {\n for (const filepath of options.path) {\n if (fs.existsSync(filepath)) {\n possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`\n }\n }\n } else {\n possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`\n }\n } else {\n possibleVaultPath = path.resolve(process.cwd(), '.env.vault')\n }\n\n if (fs.existsSync(possibleVaultPath)) {\n return possibleVaultPath\n }\n\n return null\n}\n\nfunction _resolveHome (envPath) {\n return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath\n}\n\nfunction _configVault (options) {\n const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || (options && options.debug))\n const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || (options && options.quiet))\n\n if (debug || !quiet) {\n _log('Loading env from encrypted .env.vault')\n }\n\n const parsed = DotenvModule._parseVault(options)\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsed, options)\n\n return { parsed }\n}\n\nfunction configDotenv (options) {\n const dotenvPath = path.resolve(process.cwd(), '.env')\n let encoding = 'utf8'\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || (options && options.debug))\n let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || (options && options.quiet))\n\n if (options && options.encoding) {\n encoding = options.encoding\n } else {\n if (debug) {\n _debug('No encoding is specified. UTF-8 is used by default')\n }\n }\n\n let optionPaths = [dotenvPath] // default, look for .env\n if (options && options.path) {\n if (!Array.isArray(options.path)) {\n optionPaths = [_resolveHome(options.path)]\n } else {\n optionPaths = [] // reset default\n for (const filepath of options.path) {\n optionPaths.push(_resolveHome(filepath))\n }\n }\n }\n\n // Build the parsed data in a temporary object (because we need to return it). Once we have the final\n // parsed data, we will combine it with process.env (or options.processEnv if provided).\n let lastError\n const parsedAll = {}\n for (const path of optionPaths) {\n try {\n // Specifying an encoding returns a string instead of a buffer\n const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))\n\n DotenvModule.populate(parsedAll, parsed, options)\n } catch (e) {\n if (debug) {\n _debug(`Failed to load ${path} ${e.message}`)\n }\n lastError = e\n }\n }\n\n const populated = DotenvModule.populate(processEnv, parsedAll, options)\n\n // handle user settings DOTENV_CONFIG_ options inside .env file(s)\n debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug)\n quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet)\n\n if (debug || !quiet) {\n const keysCount = Object.keys(populated).length\n const shortPaths = []\n for (const filePath of optionPaths) {\n try {\n const relative = path.relative(process.cwd(), filePath)\n shortPaths.push(relative)\n } catch (e) {\n if (debug) {\n _debug(`Failed to load ${filePath} ${e.message}`)\n }\n lastError = e\n }\n }\n\n _log(`injecting env (${keysCount}) from ${shortPaths.join(',')} ${dim(`-- tip: ${_getRandomTip()}`)}`)\n }\n\n if (lastError) {\n return { parsed: parsedAll, error: lastError }\n } else {\n return { parsed: parsedAll }\n }\n}\n\n// Populates process.env from .env file\nfunction config (options) {\n // fallback to original dotenv if DOTENV_KEY is not set\n if (_dotenvKey(options).length === 0) {\n return DotenvModule.configDotenv(options)\n }\n\n const vaultPath = _vaultPath(options)\n\n // dotenvKey exists but .env.vault file does not exist\n if (!vaultPath) {\n _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)\n\n return DotenvModule.configDotenv(options)\n }\n\n return DotenvModule._configVault(options)\n}\n\nfunction decrypt (encrypted, keyStr) {\n const key = Buffer.from(keyStr.slice(-64), 'hex')\n let ciphertext = Buffer.from(encrypted, 'base64')\n\n const nonce = ciphertext.subarray(0, 12)\n const authTag = ciphertext.subarray(-16)\n ciphertext = ciphertext.subarray(12, -16)\n\n try {\n const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)\n aesgcm.setAuthTag(authTag)\n return `${aesgcm.update(ciphertext)}${aesgcm.final()}`\n } catch (error) {\n const isRange = error instanceof RangeError\n const invalidKeyLength = error.message === 'Invalid key length'\n const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'\n\n if (isRange || invalidKeyLength) {\n const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n } else if (decryptionFailed) {\n const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')\n err.code = 'DECRYPTION_FAILED'\n throw err\n } else {\n throw error\n }\n }\n}\n\n// Populate process.env with parsed values\nfunction populate (processEnv, parsed, options = {}) {\n const debug = Boolean(options && options.debug)\n const override = Boolean(options && options.override)\n const populated = {}\n\n if (typeof parsed !== 'object') {\n const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')\n err.code = 'OBJECT_REQUIRED'\n throw err\n }\n\n // Set process.env\n for (const key of Object.keys(parsed)) {\n if (Object.prototype.hasOwnProperty.call(processEnv, key)) {\n if (override === true) {\n processEnv[key] = parsed[key]\n populated[key] = parsed[key]\n }\n\n if (debug) {\n if (override === true) {\n _debug(`\"${key}\" is already defined and WAS overwritten`)\n } else {\n _debug(`\"${key}\" is already defined and was NOT overwritten`)\n }\n }\n } else {\n processEnv[key] = parsed[key]\n populated[key] = parsed[key]\n }\n }\n\n return populated\n}\n\nconst DotenvModule = {\n configDotenv,\n _configVault,\n _parseVault,\n config,\n decrypt,\n parse,\n populate\n}\n\nmodule.exports.configDotenv = DotenvModule.configDotenv\nmodule.exports._configVault = DotenvModule._configVault\nmodule.exports._parseVault = DotenvModule._parseVault\nmodule.exports.config = DotenvModule.config\nmodule.exports.decrypt = DotenvModule.decrypt\nmodule.exports.parse = DotenvModule.parse\nmodule.exports.populate = DotenvModule.populate\n\nmodule.exports = DotenvModule\n","import WebSocket from 'ws';\nimport type { WebSocketLike } from './types';\n\n/**\n * Creates a WebSocket instance for Node.js using the ws package\n */\nexport function createWebSocket(url: string): WebSocketLike {\n return new WebSocket(url) as WebSocketLike;\n}\n","import { z } from 'zod';\n\n// From/To object schema for WebSocket messages\nexport const MessageParticipantSchema = z.object({\n id: z.string().optional(),\n type: z.string().optional(),\n});\n\nexport type MessageParticipant = z.infer<typeof MessageParticipantSchema>;\n\n// Message schemas for WebSocket communication\nexport const MessageSchema = z.object({\n id: z.string().optional(),\n type: z.string(),\n from: MessageParticipantSchema,\n to: MessageParticipantSchema.optional(),\n payload: z.unknown(),\n});\n\nexport type Message = z.infer<typeof MessageSchema>;\n\nexport const IncomingMessageSchema = z.object({\n id: z.string().optional(),\n type: z.string(),\n from: MessageParticipantSchema,\n to: MessageParticipantSchema.optional(),\n payload: z.unknown(),\n});\n\nexport type IncomingMessage = z.infer<typeof IncomingMessageSchema>;\n\n// Data request/response schemas\nexport const DataRequestPayloadSchema = z.object({\n collection: z.string(),\n op: z.string(),\n params: z.record(z.unknown()).optional(),\n SA_RUNTIME: z.record(z.unknown()).optional(),\n});\n\nexport type DataRequestPayload = z.infer<typeof DataRequestPayloadSchema>;\n\nexport const DataRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('DATA_REQ'),\n payload: DataRequestPayloadSchema,\n});\n\nexport type DataRequestMessage = z.infer<typeof DataRequestMessageSchema>;\n\nexport const AuthLoginRequestPayloadSchema = z.object({\n login_data: z.string(),\n});\n\nexport type AuthLoginRequestPayload = z.infer<typeof AuthLoginRequestPayloadSchema>;\n\nexport const AuthLoginRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('AUTH_LOGIN_REQ'),\n payload: AuthLoginRequestPayloadSchema,\n});\n\nexport type AuthLoginRequestMessage = z.infer<typeof AuthLoginRequestMessageSchema>;\n\nexport const AuthVerifyRequestPayloadSchema = z.object({\n token: z.string(),\n});\n\nexport type AuthVerifyRequestPayload = z.infer<typeof AuthVerifyRequestPayloadSchema>;\n\nexport const AuthVerifyRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('AUTH_VERIFY_REQ'),\n payload: AuthVerifyRequestPayloadSchema,\n});\n\nexport type AuthVerifyRequestMessage = z.infer<typeof AuthVerifyRequestMessageSchema>;\n\nexport const UserPromptRequestPayloadSchema = z.object({\n prompt: z.string(),\n SA_RUNTIME: z.object({\n threadId: z.string(),\n uiBlockId: z.string(),\n }).optional(),\n});\n\nexport type UserPromptRequestPayload = z.infer<typeof UserPromptRequestPayloadSchema>;\n\nexport const UserPromptRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('USER_PROMPT_REQ'),\n payload: UserPromptRequestPayloadSchema,\n});\n\nexport type UserPromptRequestMessage = z.infer<typeof UserPromptRequestMessageSchema>;\n\nexport const UserPromptSuggestionsPayloadSchema = z.object({\n prompt: z.string(),\n limit: z.number().int().positive().default(5),\n});\n\nexport type UserPromptSuggestionsPayload = z.infer<typeof UserPromptSuggestionsPayloadSchema>;\n\nexport const UserPromptSuggestionsMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('USER_PROMPT_SUGGESTIONS_REQ'),\n payload: UserPromptSuggestionsPayloadSchema,\n});\n\nexport type UserPromptSuggestionsMessage = z.infer<typeof UserPromptSuggestionsMessageSchema>;\n\n\nexport const ComponentPropsSchema = z.object({\n query: z.string().optional(),\n title: z.string().optional(),\n description: z.string().optional(),\n config: z.record(z.unknown()).optional(),\n});\n\nexport const ComponentSchema = z.object({\n id: z.string(),\n name: z.string(),\n type: z.string(),\n description: z.string(),\n props: ComponentPropsSchema,\n category: z.string().optional(),\n keywords: z.array(z.string()).optional(),\n});\n\nexport const ComponentsSchema = z.array(ComponentSchema);\n\nexport type Component = z.infer<typeof ComponentSchema>;\n\nexport const ComponentListResponsePayloadSchema = z.object({\n components: z.array(ComponentSchema),\n});\n\nexport type ComponentListResponsePayload = z.infer<typeof ComponentListResponsePayloadSchema>; \n\nexport const ComponentListResponseMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('COMPONENT_LIST_RES'),\n payload: ComponentListResponsePayloadSchema,\n});\n\nexport type ComponentListResponseMessage = z.infer<typeof ComponentListResponseMessageSchema>;\n\n// Admin User Management Request/Response schemas (Unified)\nexport const UsersRequestPayloadSchema = z.object({\n operation: z.enum(['create', 'update', 'delete', 'getAll', 'getOne']),\n data: z.object({\n username: z.string().optional(),\n password: z.string().optional(),\n }).optional(),\n});\n\nexport type UsersRequestPayload = z.infer<typeof UsersRequestPayloadSchema>;\n\nexport const UsersRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('USERS'),\n payload: UsersRequestPayloadSchema,\n});\n\nexport type UsersRequestMessage = z.infer<typeof UsersRequestMessageSchema>;\n\n// UI Logs schema for tracking user request execution\nexport const UILogsPayloadSchema = z.object({\n logs: z.array(z.object({\n timestamp: z.number(),\n level: z.enum(['info', 'error', 'warn', 'debug']),\n message: z.string(),\n type: z.enum(['explanation', 'query', 'general']).optional(),\n data: z.record(z.unknown()).optional(),\n })),\n});\n\nexport type UILogsPayload = z.infer<typeof UILogsPayloadSchema>;\n\nexport const UILogsMessageSchema = z.object({\n id: z.string(), // uiBlockId\n from: MessageParticipantSchema,\n type: z.literal('UI_LOGS'),\n payload: UILogsPayloadSchema,\n});\n\nexport type UILogsMessage = z.infer<typeof UILogsMessageSchema>;\n\n// Actions request schema - for runtime to send component actions and request next questions\nexport const ActionsRequestPayloadSchema = z.object({\n SA_RUNTIME: z.object({\n threadId: z.string(),\n uiBlockId: z.string(),\n }).optional(),\n});\n\nexport type ActionsRequestPayload = z.infer<typeof ActionsRequestPayloadSchema>;\n\nexport const ActionsRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('ACTIONS'),\n payload: ActionsRequestPayloadSchema,\n});\n\nexport type ActionsRequestMessage = z.infer<typeof ActionsRequestMessageSchema>;\n\n// Collection operation types\nexport type CollectionOperation =\n | 'getMany'\n | 'getOne'\n | 'query'\n | 'mutation'\n | 'updateOne'\n | 'deleteOne'\n | 'createOne';\n\nexport type CollectionHandler<TParams = any, TResult = any> = (\n params: TParams\n) => Promise<TResult> | TResult;\n\nexport interface CollectionRegistry {\n [collectionName: string]: {\n [operation: string]: CollectionHandler;\n };\n}\n\nexport type LLMProvider = 'anthropic' | 'groq';\n\nexport interface SuperatomSDKConfig {\n url?: string;\n apiKey: string;\n projectId: string;\n userId?: string;\n type?: string;\n bundleDir?: string;\n ANTHROPIC_API_KEY?: string;\n GROQ_API_KEY?: string;\n LLM_PROVIDERS?: LLMProvider[];\n}\n\n// ==================== Dashboard CRUD Message Schemas ====================\n\n// Import DSL types from dashboards module\nimport { DSLRendererPropsSchema } from './dashboards/types';\nexport type { DSLRendererProps } from './dashboards/types';\n\n// Dashboard CRUD request payload\n\nexport const DashboardsRequestPayloadSchema = z.object({\n operation: z.enum(['create', 'update', 'delete', 'getAll', 'getOne']),\n data: z.object({\n dashboardId: z.string().optional(),\n dashboard: DSLRendererPropsSchema.optional(),\n }).optional(),\n});\n\nexport type DashboardsRequestPayload = z.infer<typeof DashboardsRequestPayloadSchema>;\n\nexport const DashboardsRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('DASHBOARDS'),\n payload: DashboardsRequestPayloadSchema,\n});\n\nexport type DashboardsRequestMessage = z.infer<typeof DashboardsRequestMessageSchema>;\n\n// ==================== Report CRUD Message Schemas ====================\n\n// Import DSL types from reports module\nimport { DSLRendererPropsSchema as ReportDSLRendererPropsSchema } from './reports/types';\nexport type { DSLRendererProps as ReportDSLRendererProps } from './reports/types';\n\n// Report CRUD request payload\nexport const ReportsRequestPayloadSchema = z.object({\n operation: z.enum(['create', 'update', 'delete', 'getAll', 'getOne']),\n data: z.object({\n reportId: z.string().optional(),\n report: ReportDSLRendererPropsSchema.optional(),\n }).optional(),\n});\n\nexport type ReportsRequestPayload = z.infer<typeof ReportsRequestPayloadSchema>;\n\nexport const ReportsRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('REPORTS'),\n payload: ReportsRequestPayloadSchema,\n});\n\nexport type ReportsRequestMessage = z.infer<typeof ReportsRequestMessageSchema>;\n\nexport interface WebSocketLike {\n send(data: string): void;\n close(): void;\n addEventListener(event: string, listener: (event: any) => void): void;\n removeEventListener(event: string, listener: (event: any) => void): void;\n readyState: number;\n CONNECTING: number;\n OPEN: number;\n CLOSING: number;\n CLOSED: number;\n}\n\n","import { z } from 'zod';\n\n// ==================== Dashboard DSL Schemas ====================\n\n// Expression schema for dynamic values\nexport const ExpressionSchema = z.object({\n $exp: z.string(),\n $deps: z.array(z.string()).optional(),\n});\n\nexport type Expression = z.infer<typeof ExpressionSchema>;\n\n// Binding schema for data binding\nexport const BindingSchema = z.object({\n $bind: z.string(),\n $transform: z\n .array(\n z.object({\n name: z.string(),\n args: z.array(z.any()).optional(),\n }),\n )\n .optional(),\n});\n\nexport type Binding = z.infer<typeof BindingSchema>;\n\n// For directive schema\nexport const ForDirectiveSchema = z.object({\n in: z.union([ExpressionSchema, BindingSchema, z.string()]),\n as: z.string(),\n key: z.string().optional(),\n index: z.string().optional(),\n});\n\nexport type ForDirective = z.infer<typeof ForDirectiveSchema>;\n\n// Query specification schema\nexport const QuerySpecSchema = z.object({\n graphql: z.string().optional(),\n sql: z.string().optional(),\n variables: z.record(z.string(), z.any()).optional(),\n params: z.record(z.string(), z.any()).optional(),\n key: z.string().optional(),\n refetchPolicy: z\n .enum(['cache-first', 'network-only', 'cache-and-network'])\n .optional(),\n dependencies: z.array(z.string()).optional(),\n});\n\nexport type QuerySpec = z.infer<typeof QuerySpecSchema>;\n\n// UI Element schema\nexport const UIElementSchema: z.ZodType<any> = z.lazy(() =>\n z.object({\n id: z.string(),\n type: z.string(),\n key: z.union([z.string(), ExpressionSchema]).optional(),\n props: z.record(z.string(), z.any()).optional(),\n query: QuerySpecSchema.optional(),\n if: ExpressionSchema.optional(),\n elseIf: ExpressionSchema.optional(),\n for: ForDirectiveSchema.optional(),\n 'link-to': z\n .union([\n z.string(),\n ExpressionSchema,\n BindingSchema,\n z.object({\n ui: z.union([z.string(), ExpressionSchema, BindingSchema]),\n params: z.record(z.string(), z.any()).optional(),\n }),\n ])\n .optional(),\n _meta: z\n .object({\n id: z.string().optional(),\n version: z.string().optional(),\n created: z.string().optional(),\n lastModified: z.string().optional(),\n })\n .optional(),\n children: z.any().optional(),\n else: UIElementSchema.optional(),\n slots: z\n .record(z.string(), z.union([UIElementSchema, z.array(UIElementSchema)]))\n .optional(),\n platform: z\n .object({\n web: z.any().optional(),\n ios: z.any().optional(),\n android: z.any().optional(),\n })\n .optional(),\n })\n);\n\nexport type UIElement = z.infer<typeof UIElementSchema>;\n\n// UI Component schema\nexport const UIComponentSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n props: z.record(z.string(), z.any()).optional(),\n states: z.record(z.string(), z.any()).optional(),\n methods: z\n .record(\n z.string(),\n z.object({\n fn: z.string(),\n params: z.record(z.string(), z.any()).optional(),\n }),\n )\n .optional(),\n effects: z\n .array(\n z.object({\n fn: z.string(),\n deps: z.array(z.string()).optional(),\n }),\n )\n .optional(),\n data: z.record(z.string(), z.any()).optional(),\n render: UIElementSchema,\n query: QuerySpecSchema.optional(),\n});\n\nexport type UIComponent = z.infer<typeof UIComponentSchema>;\n\n// DSL Renderer Props schema\nexport const DSLRendererPropsSchema = z.object({\n dsl: UIComponentSchema,\n data: z.record(z.string(), z.any()).optional(),\n context: z.record(z.string(), z.any()).optional(),\n});\n\nexport type DSLRendererProps = z.infer<typeof DSLRendererPropsSchema>;\n","import { z } from 'zod';\n\n// ==================== Report DSL Schemas ====================\n\n// Expression schema for dynamic values\nexport const ExpressionSchema = z.object({\n $exp: z.string(),\n $deps: z.array(z.string()).optional(),\n});\n\nexport type Expression = z.infer<typeof ExpressionSchema>;\n\n// Binding schema for data binding\nexport const BindingSchema = z.object({\n $bind: z.string(),\n $transform: z\n .array(\n z.object({\n name: z.string(),\n args: z.array(z.any()).optional(),\n }),\n )\n .optional(),\n});\n\nexport type Binding = z.infer<typeof BindingSchema>;\n\n// For directive schema\nexport const ForDirectiveSchema = z.object({\n in: z.union([ExpressionSchema, BindingSchema, z.string()]),\n as: z.string(),\n key: z.string().optional(),\n index: z.string().optional(),\n});\n\nexport type ForDirective = z.infer<typeof ForDirectiveSchema>;\n\n// Query specification schema\nexport const QuerySpecSchema = z.object({\n graphql: z.string().optional(),\n sql: z.string().optional(),\n variables: z.record(z.string(), z.any()).optional(),\n params: z.record(z.string(), z.any()).optional(),\n key: z.string().optional(),\n refetchPolicy: z\n .enum(['cache-first', 'network-only', 'cache-and-network'])\n .optional(),\n dependencies: z.array(z.string()).optional(),\n});\n\nexport type QuerySpec = z.infer<typeof QuerySpecSchema>;\n\n// UI Element schema\nexport const UIElementSchema: z.ZodType<any> = z.lazy(() =>\n z.object({\n id: z.string(),\n type: z.string(),\n key: z.union([z.string(), ExpressionSchema]).optional(),\n props: z.record(z.string(), z.any()).optional(),\n query: QuerySpecSchema.optional(),\n if: ExpressionSchema.optional(),\n elseIf: ExpressionSchema.optional(),\n for: ForDirectiveSchema.optional(),\n 'link-to': z\n .union([\n z.string(),\n ExpressionSchema,\n BindingSchema,\n z.object({\n ui: z.union([z.string(), ExpressionSchema, BindingSchema]),\n params: z.record(z.string(), z.any()).optional(),\n }),\n ])\n .optional(),\n _meta: z\n .object({\n id: z.string().optional(),\n version: z.string().optional(),\n created: z.string().optional(),\n lastModified: z.string().optional(),\n })\n .optional(),\n children: z.any().optional(),\n else: UIElementSchema.optional(),\n slots: z\n .record(z.string(), z.union([UIElementSchema, z.array(UIElementSchema)]))\n .optional(),\n platform: z\n .object({\n web: z.any().optional(),\n ios: z.any().optional(),\n android: z.any().optional(),\n })\n .optional(),\n })\n);\n\nexport type UIElement = z.infer<typeof UIElementSchema>;\n\n// UI Component schema\nexport const UIComponentSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n props: z.record(z.string(), z.any()).optional(),\n states: z.record(z.string(), z.any()).optional(),\n methods: z\n .record(\n z.string(),\n z.object({\n fn: z.string(),\n params: z.record(z.string(), z.any()).optional(),\n }),\n )\n .optional(),\n effects: z\n .array(\n z.object({\n fn: z.string(),\n deps: z.array(z.string()).optional(),\n }),\n )\n .optional(),\n data: z.record(z.string(), z.any()).optional(),\n render: UIElementSchema,\n query: QuerySpecSchema.optional(),\n});\n\nexport type UIComponent = z.infer<typeof UIComponentSchema>;\n\n// DSL Renderer Props schema\nexport const DSLRendererPropsSchema = z.object({\n dsl: UIComponentSchema,\n data: z.record(z.string(), z.any()).optional(),\n context: z.record(z.string(), z.any()).optional(),\n});\n\nexport type DSLRendererProps = z.infer<typeof DSLRendererPropsSchema>;\n","const PREFIX = '[SuperatomSDK]';\n\nexport const logger = {\n info: (...args: any[]) => {\n console.log(PREFIX, ...args);\n },\n\n error: (...args: any[]) => {\n console.error(PREFIX, ...args);\n },\n\n warn: (...args: any[]) => {\n console.warn(PREFIX, ...args);\n },\n\n debug: (...args: any[]) => {\n console.log(PREFIX, '[DEBUG]', ...args);\n },\n};\n","import { randomUUID } from 'crypto';\nimport { logger } from '../utils/logger';\nimport { STORAGE_CONFIG } from '../config/storage';\nimport { Action } from './action';\n\n/**\n * UIBlock represents a single user and assistant message block in a thread\n * Contains user question, component metadata, component data, and available actions\n */\nexport class UIBlock {\n private id: string;\n private userQuestion: string;\n private generatedComponentMetadata: Record<string, any>;\n private componentData: Record<string, any>;\n private actions: Action[] | null | Promise<Action[]>;\n private createdAt: Date;\n\n /**\n * Creates a new UIBlock instance\n * @param userQuestion - The user's question or input\n * @param componentData - The component data object\n * @param generatedComponentMetadata - Optional metadata about the generated component\n * @param actions - Optional array of available actions\n * @param id - Optional custom ID, generates UUID if not provided\n */\n constructor(\n userQuestion: string,\n componentData: Record<string, any> = {},\n generatedComponentMetadata: Record<string, any> = {},\n actions: Action[] = [],\n id?: string\n ) {\n this.id = id || randomUUID();\n this.userQuestion = userQuestion;\n this.componentData = componentData;\n this.generatedComponentMetadata = generatedComponentMetadata;\n this.actions = actions;\n this.createdAt = new Date();\n }\n\n /**\n * Get the UIBlock ID\n */\n getId(): string {\n return this.id;\n }\n\n /**\n * Get the user question\n */\n getUserQuestion(): string {\n return this.userQuestion;\n }\n\n /**\n * Set or update the user question\n */\n setUserQuestion(question: string): void {\n this.userQuestion = question;\n }\n\n /**\n * Get component metadata\n */\n getComponentMetadata(): Record<string, any> {\n return this.generatedComponentMetadata;\n }\n\n /**\n * Set or update component metadata\n */\n setComponentMetadata(metadata: Record<string, any>): void {\n this.generatedComponentMetadata = { ...this.generatedComponentMetadata, ...metadata };\n }\n\n /**\n * Get component data\n */\n getComponentData(): Record<string, any> {\n return this.componentData;\n }\n\n /**\n * Calculate size of data in bytes\n */\n private getDataSizeInBytes(data: any): number {\n try {\n const jsonString = JSON.stringify(data);\n return Buffer.byteLength(jsonString, 'utf8');\n } catch (error) {\n logger.error('Error calculating data size:', error);\n return 0;\n }\n }\n\n /**\n * Limit array data to maximum rows\n */\n private limitArrayData(data: any[]): { data: any[]; metadata: any } {\n const totalRows = data.length;\n const limitedData = data.slice(0, STORAGE_CONFIG.MAX_ROWS_PER_BLOCK);\n\n return {\n data: limitedData,\n metadata: {\n totalRows,\n storedRows: limitedData.length,\n isTruncated: totalRows > STORAGE_CONFIG.MAX_ROWS_PER_BLOCK,\n },\n };\n }\n\n /**\n * Check if data exceeds size limit\n */\n private exceedsSizeLimit(data: any): boolean {\n const size = this.getDataSizeInBytes(data);\n return size > STORAGE_CONFIG.MAX_SIZE_PER_BLOCK_BYTES;\n }\n\n /**\n * Process and limit data before storing\n */\n private processDataForStorage(data: any): any {\n // If data is an array, limit rows\n if (Array.isArray(data)) {\n const { data: limitedData, metadata } = this.limitArrayData(data);\n\n // Check size after limiting rows\n const size = this.getDataSizeInBytes(limitedData);\n\n logger.info(\n `UIBlock ${this.id}: Storing ${metadata.storedRows}/${metadata.totalRows} rows (${(size / 1024).toFixed(2)} KB)`\n );\n\n // If still too large, store only metadata\n if (this.exceedsSizeLimit(limitedData)) {\n logger.warn(\n `UIBlock ${this.id}: Data too large (${(size / 1024 / 1024).toFixed(2)} MB), storing metadata only`\n );\n return {\n ...metadata,\n preview: limitedData.slice(0, 3), // Store only first 3 rows as preview\n dataTooLarge: true,\n };\n }\n\n return {\n data: limitedData,\n ...metadata,\n };\n }\n\n // For non-array data, check size\n const size = this.getDataSizeInBytes(data);\n\n if (this.exceedsSizeLimit(data)) {\n logger.warn(\n `UIBlock ${this.id}: Data too large (${(size / 1024 / 1024).toFixed(2)} MB), storing summary only`\n );\n return {\n dataTooLarge: true,\n dataType: typeof data,\n keys: typeof data === 'object' ? Object.keys(data) : undefined,\n };\n }\n\n return data;\n }\n\n /**\n * Set or update component data with size and row limits\n */\n setComponentData(data: Record<string, any>): void {\n const processedData = this.processDataForStorage(data);\n this.componentData = { ...this.componentData, ...processedData };\n }\n\n /**\n * Get all actions (only if they are resolved, not if fetching)\n */\n getActions(): Action[] | null | Promise<Action[]> {\n return this.actions;\n }\n\n /**\n * Get or fetch actions\n * If actions don't exist or are a Promise, calls the generateFn and stores the promise\n * If actions already exist, returns them\n * @param generateFn - Async function to generate actions\n * @returns Promise resolving to Action[]\n */\n async getOrFetchActions(generateFn: () => Promise<Action[]>): Promise<Action[]> {\n // If actions already exist and are not a Promise, return them\n\n if (this.actions && !(this.actions instanceof Promise) && Array.isArray(this.actions) && this.actions.length > 0) {\n return this.actions;\n }\n\n // If already fetching, cancel and start new fetch\n // Set new promise for fetching\n const fetchPromise = generateFn();\n this.actions = fetchPromise;\n\n try {\n // Wait for the promise to resolve\n const resolvedActions = await fetchPromise;\n // Store the resolved actions\n logger.info(`Fetched ${resolvedActions.length} actions for UIBlock: ${this.id}`);\n this.actions = resolvedActions;\n return resolvedActions;\n } catch (error) {\n // If generation fails, reset to null\n this.actions = null;\n throw error;\n }\n }\n\n /**\n * Add a single action (only if actions are resolved)\n */\n addAction(action: Action): void {\n if (this.actions && Array.isArray(this.actions)) {\n this.actions.push(action);\n }\n }\n\n /**\n * Add multiple actions (only if actions are resolved)\n */\n addActions(actions: Action[]): void {\n if (this.actions && Array.isArray(this.actions)) {\n this.actions.push(...actions);\n }\n }\n\n /**\n * Remove an action by ID (only if actions are resolved)\n */\n removeAction(actionId: string): boolean {\n if (this.actions && Array.isArray(this.actions)) {\n const index = this.actions.findIndex(a => a.id === actionId);\n if (index > -1) {\n this.actions.splice(index, 1);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Clear all actions\n */\n clearActions(): void {\n this.actions = null;\n }\n\n /**\n * Get creation timestamp\n */\n getCreatedAt(): Date {\n return this.createdAt;\n }\n\n /**\n * Convert UIBlock to JSON-serializable object\n */\n toJSON(): Record<string, any> {\n // Handle Promise case for serialization\n let actionsValue: Action[] | null = null;\n if (this.actions && !(this.actions instanceof Promise) && Array.isArray(this.actions)) {\n actionsValue = this.actions;\n }\n\n return {\n id: this.id,\n userQuestion: this.userQuestion,\n generatedComponentMetadata: this.generatedComponentMetadata,\n componentData: this.componentData,\n actions: actionsValue,\n isFetchingActions: this.actions instanceof Promise,\n createdAt: this.createdAt.toISOString(),\n };\n }\n}\n","/**\n * Configuration for data storage limits in UIBlocks\n */\nexport const STORAGE_CONFIG = {\n /**\n * Maximum number of rows to store in UIBlock data\n */\n MAX_ROWS_PER_BLOCK: 10,\n\n /**\n * Maximum size in bytes per UIBlock (1MB)\n */\n MAX_SIZE_PER_BLOCK_BYTES: 1 * 1024 * 1024, // 1MB\n\n /**\n * Number of days to keep threads before cleanup\n */\n THREAD_RETENTION_DAYS: 7,\n\n /**\n * Number of days to keep UIBlocks before cleanup\n */\n UIBLOCK_RETENTION_DAYS: 7,\n};\n","import { randomUUID } from 'crypto';\nimport { UIBlock } from './uiblock';\n\n/**\n * Thread represents a conversation thread containing multiple UIBlocks\n * Each UIBlock in a thread represents a user question and assistant response pair\n */\nexport class Thread {\n private id: string;\n private uiblocks: Map<string, UIBlock>;\n private createdAt: Date;\n\n /**\n * Creates a new Thread instance\n * @param id - Optional custom ID, generates UUID if not provided\n */\n constructor(id?: string) {\n this.id = id || randomUUID();\n this.uiblocks = new Map();\n this.createdAt = new Date();\n }\n\n /**\n * Get the thread ID\n */\n getId(): string {\n return this.id;\n }\n\n /**\n * Add a UIBlock to the thread\n */\n addUIBlock(uiblock: UIBlock): void {\n this.uiblocks.set(uiblock.getId(), uiblock);\n }\n\n /**\n * Get a UIBlock by ID\n */\n getUIBlock(id: string): UIBlock | undefined {\n return this.uiblocks.get(id);\n }\n\n /**\n * Get all UIBlocks in the thread\n */\n getUIBlocks(): UIBlock[] {\n return Array.from(this.uiblocks.values());\n }\n\n /**\n * Get UIBlocks as a Map\n */\n getUIBlocksMap(): Map<string, UIBlock> {\n return new Map(this.uiblocks);\n }\n\n /**\n * Remove a UIBlock by ID\n */\n removeUIBlock(id: string): boolean {\n return this.uiblocks.delete(id);\n }\n\n /**\n * Check if UIBlock exists\n */\n hasUIBlock(id: string): boolean {\n return this.uiblocks.has(id);\n }\n\n /**\n * Get number of UIBlocks in the thread\n */\n getUIBlockCount(): number {\n return this.uiblocks.size;\n }\n\n /**\n * Clear all UIBlocks from the thread\n */\n clear(): void {\n this.uiblocks.clear();\n }\n\n /**\n * Get creation timestamp\n */\n getCreatedAt(): Date {\n return this.createdAt;\n }\n\n /**\n * Get conversation context from recent UIBlocks (excluding current one)\n * Returns formatted string with previous questions and component summaries\n * @param limit - Maximum number of previous UIBlocks to include (default: 5)\n * @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)\n * @returns Formatted conversation history string\n */\n getConversationContext(limit: number = 5, currentUIBlockId?: string): string {\n if (limit === 0) {\n return '';\n }\n\n // Get all UIBlocks sorted by creation time (oldest first)\n const allBlocks = Array.from(this.uiblocks.values())\n .filter(block => !currentUIBlockId || block.getId() !== currentUIBlockId)\n .sort((a, b) => a.getCreatedAt().getTime() - b.getCreatedAt().getTime());\n\n if (allBlocks.length === 0) {\n return '';\n }\n\n // Take the last N blocks (most recent)\n const recentBlocks = allBlocks.slice(-limit);\n\n // Format as conversation history\n const contextLines: string[] = [];\n\n recentBlocks.forEach((block, index) => {\n const questionNum = index + 1;\n const question = block.getUserQuestion();\n const metadata = block.getComponentMetadata();\n\n // Build component summary\n let componentSummary = 'No component generated';\n if (metadata && Object.keys(metadata).length > 0) {\n const parts: string[] = [];\n\n if (metadata.type) {\n parts.push(`Component Type: ${metadata.type}`);\n }\n if (metadata.name) {\n parts.push(`Name: ${metadata.name}`);\n }\n if (metadata.props?.title) {\n parts.push(`Title: \"${metadata.props.title}\"`);\n }\n if (metadata.props?.query) {\n // Truncate long queries\n const query = metadata.props.query;\n const truncatedQuery = query.length > 200 ? query.substring(0, 200) + '...' : query;\n parts.push(`Query: ${truncatedQuery}`);\n }\n if (metadata.props?.config?.components && Array.isArray(metadata.props.config.components)) {\n // Multi-component container\n const componentTypes = metadata.props.config.components.map((c: any) => c.type).join(', ');\n parts.push(`Multi-component with: ${componentTypes}`);\n }\n\n componentSummary = parts.join(', ');\n }\n\n contextLines.push(`Q${questionNum}: ${question}`);\n contextLines.push(`A${questionNum}: ${componentSummary}`);\n contextLines.push(''); // Empty line for readability\n });\n\n return contextLines.join('\\n').trim();\n }\n\n /**\n * Convert Thread to JSON-serializable object\n */\n toJSON(): Record<string, any> {\n return {\n id: this.id,\n uiblocks: Array.from(this.uiblocks.values()).map(block => block.toJSON()),\n createdAt: this.createdAt.toISOString(),\n };\n }\n}\n","import { Thread } from './thread';\nimport { UIBlock } from './uiblock';\n\n/**\n * ThreadManager manages all threads globally\n * Provides methods to create, retrieve, and delete threads\n */\nexport class ThreadManager {\n private static instance: ThreadManager;\n private threads: Map<string, Thread>;\n\n private constructor() {\n this.threads = new Map();\n\n // Initialize cleanup service\n // new CleanupService(this.threads);\n }\n\n /**\n * Get singleton instance of ThreadManager\n */\n static getInstance(): ThreadManager {\n if (!ThreadManager.instance) {\n ThreadManager.instance = new ThreadManager();\n }\n return ThreadManager.instance;\n }\n\n /**\n * Create a new thread\n * @param id - Optional custom ID, generates UUID if not provided\n * @returns The created Thread instance\n */\n createThread(id?: string): Thread {\n const thread = new Thread(id);\n this.threads.set(thread.getId(), thread);\n return thread;\n }\n\n /**\n * Get a thread by ID\n */\n getThread(id: string): Thread | undefined {\n return this.threads.get(id);\n }\n\n /**\n * Get all threads\n */\n getAllThreads(): Thread[] {\n return Array.from(this.threads.values());\n }\n\n /**\n * Get threads as a Map\n */\n getThreadsMap(): Map<string, Thread> {\n return new Map(this.threads);\n }\n\n /**\n * Delete a thread by ID\n */\n deleteThread(id: string): boolean {\n return this.threads.delete(id);\n }\n\n /**\n * Check if thread exists\n */\n hasThread(id: string): boolean {\n return this.threads.has(id);\n }\n\n /**\n * Get number of threads\n */\n getThreadCount(): number {\n return this.threads.size;\n }\n\n /**\n * Clear all threads\n */\n clearAll(): void {\n this.threads.clear();\n }\n\n /**\n * Find a UIBlock by ID across all threads\n * @param uiBlockId - The UIBlock ID to search for\n * @returns Object with thread and uiBlock if found, undefined otherwise\n */\n findUIBlockById(uiBlockId: string): { thread: Thread; uiBlock: UIBlock } | undefined {\n for (const thread of this.threads.values()) {\n const uiBlock = thread.getUIBlock(uiBlockId);\n if (uiBlock) {\n return { thread, uiBlock };\n }\n }\n return undefined;\n }\n\n /**\n * Convert all threads to JSON-serializable object\n */\n toJSON(): Record<string, any> {\n return {\n threads: Array.from(this.threads.values()).map(thread => thread.toJSON()),\n count: this.threads.size,\n };\n }\n}\n","import { DataRequestMessageSchema, type CollectionRegistry, type Message } from '../types';\nimport { logger } from '../utils/logger';\nimport { ThreadManager } from '../threads';\n\n/**\n * Handle incoming data_req messages and execute collection handlers\n */\nexport async function handleDataRequest(\n data: any,\n collections: CollectionRegistry,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const dataRequest = DataRequestMessageSchema.parse(data);\n const { id, payload } = dataRequest;\n const { collection, op, params, SA_RUNTIME } = payload;\n\n // Check if collection and operation exist\n if (!collections[collection]) {\n sendDataResponse(id, collection, op, null, {\n error: `Collection '${collection}' not found`,\n }, sendMessage);\n return;\n }\n\n if (!collections[collection][op]) {\n sendDataResponse(id, collection, op, null, {\n error: `Operation '${op}' not found for collection '${collection}'`,\n }, sendMessage);\n return;\n }\n\n // Execute the handler and measure execution time\n const startTime = performance.now();\n const handler = collections[collection][op];\n const result = await handler(params || {});\n const executionMs = Math.round(performance.now() - startTime);\n\n logger.info(`Executed ${collection}.${op} in ${executionMs}ms`);\n\n // Update UIBlock with component data if SA_RUNTIME has uiBlockId\n if (SA_RUNTIME && typeof SA_RUNTIME === 'object' && 'uiBlockId' in SA_RUNTIME) {\n const uiBlockId = (SA_RUNTIME as any).uiBlockId;\n const threadId = (SA_RUNTIME as any).threadId;\n\n const threadManager = ThreadManager.getInstance();\n let uiBlock = null;\n let thread = null;\n\n // If threadId is provided, get the specific thread\n if (threadId) {\n thread = threadManager.getThread(threadId);\n if (thread) {\n uiBlock = thread.getUIBlock(uiBlockId);\n }\n } else {\n // Otherwise search across all threads\n const result = threadManager.findUIBlockById(uiBlockId);\n if (result) {\n thread = result.thread;\n uiBlock = result.uiBlock;\n }\n }\n\n // Update UIBlock's componentData with the response\n if (uiBlock) {\n uiBlock.setComponentData(result || {});\n logger.info(`Updated UIBlock ${uiBlockId} with component data from ${collection}.${op}`);\n } else {\n logger.warn(`UIBlock ${uiBlockId} not found in threads`);\n }\n }\n\n // Send response\n sendDataResponse(id, collection, op, result, { executionMs }, sendMessage);\n } catch (error) {\n logger.error('Failed to handle data request:', error);\n // Not a data_req message or invalid format\n }\n}\n\n/**\n * Send a data_res response message\n */\nfunction sendDataResponse(\n id: string,\n collection: string,\n op: string,\n data: any,\n meta: { executionMs?: number; error?: string },\n sendMessage: (message: Message) => void\n): void {\n const response: Message = {\n id,\n from: { type: 'data-agent' },\n type: 'DATA_RES',\n payload: {\n collection,\n op,\n data,\n ...meta,\n },\n };\n\n sendMessage(response);\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport { logger } from './utils/logger';\n\n/**\n * Get the bundle directory from config or environment variable\n */\nexport function getBundleDir(configDir?: string): string {\n const bundleDir = configDir || process.env.SA_BUNDLE_DIR;\n\n if (!bundleDir) {\n throw new Error(\n 'Bundle directory not configured. Please provide bundleDir in config or set SA_BUNDLE_DIR environment variable.'\n );\n }\n\n return bundleDir;\n}\n\n/**\n * Load the JavaScript bundle from the configured directory\n */\nexport function getJS(bundleDir: string): string {\n try {\n // Check if directory exists\n if (!fs.existsSync(bundleDir)) {\n throw new Error(`Bundle directory does not exist: ${bundleDir}`);\n }\n\n // Check if it's actually a directory\n const stats = fs.statSync(bundleDir);\n if (!stats.isDirectory()) {\n throw new Error(`Bundle path is not a directory: ${bundleDir}`);\n }\n\n // Read directory contents\n let files: string[];\n try {\n files = fs.readdirSync(bundleDir);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read bundle directory: ${errorMessage}`);\n }\n\n // Find the bundle file\n const indexFile = files.find((file) => file.startsWith('index-') && file.endsWith('.js'));\n\n if (!indexFile) {\n logger.warn(`Available files in ${bundleDir}:`, files);\n throw new Error(\n `Could not find index-*.js file in ${bundleDir}. ` +\n `Expected a file matching pattern: index-*.js`\n );\n }\n\n // Read the bundle file\n const filePath = path.join(bundleDir, indexFile);\n logger.info(`Loading bundle from ${filePath}`);\n\n try {\n return fs.readFileSync(filePath, 'utf8');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read bundle file: ${errorMessage}`);\n }\n } catch (error) {\n if (error instanceof Error) {\n logger.error('Failed to load bundle:', error.message);\n } else {\n logger.error('Failed to load bundle:', error);\n }\n throw error;\n }\n}\n","import { getJS, getBundleDir } from '../bundle';\nimport { logger } from '../utils/logger';\nimport type { Message } from '../types';\n\nconst CHUNK_SIZE = 900 * 1024; // 900 KB chunks (leaving room for metadata, max 1MB per message)\n\n/**\n * Handle incoming bundle_req messages and send chunked bundle response\n */\nexport async function handleBundleRequest(\n data: any,\n bundleDir: string | undefined,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const id = data.id || 'unknown';\n const fromId = data.from?.id;\n\n // Get bundle directory and load bundle\n const dir = getBundleDir(bundleDir);\n const js = getJS(dir);\n const bundleSize = Buffer.byteLength(js, 'utf8');\n\n logger.info(`Bundle size: ${(bundleSize / 1024).toFixed(2)} KB`);\n\n // Split bundle into chunks\n const totalChunks = Math.ceil(bundleSize / CHUNK_SIZE);\n logger.info(`Splitting bundle into ${totalChunks} chunks`);\n\n for (let i = 0; i < totalChunks; i++) {\n const start = i * CHUNK_SIZE;\n const end = Math.min(start + CHUNK_SIZE, js.length);\n const chunk = js.substring(start, end);\n const isComplete = i === totalChunks - 1;\n const progress = ((i + 1) / totalChunks) * 100;\n\n const chunkMessage: Message = {\n id: `${id}-chunk-${i}`,\n type: 'BUNDLE_CHUNK',\n from: { type: 'data-agent' },\n to: fromId ? { id: fromId } : undefined,\n payload: {\n chunk: chunk,\n chunkIndex: i,\n totalChunks: totalChunks,\n isComplete: isComplete,\n progress: parseFloat(progress.toFixed(2)),\n },\n };\n\n sendMessage(chunkMessage);\n logger.debug(`Sent chunk ${i + 1}/${totalChunks} (${progress.toFixed(2)}%)`);\n }\n\n logger.info('Bundle sending complete');\n } catch (error) {\n logger.error('Failed to handle bundle request:', error);\n\n // Send error response\n const errorMessage: Message = {\n id: data.id || 'unknown',\n type: 'BUNDLE_RES',\n from: { type: 'data-agent' },\n to: data.from?.id ? { id: data.from.id } : undefined,\n payload: {\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n };\n\n sendMessage(errorMessage);\n }\n}\n","import crypto from 'crypto';\n\n/**\n * Decode base64 encoded string and parse JSON\n * @param base64Data - Base64 encoded string\n * @returns Parsed JSON object\n */\nexport function decodeBase64ToJson(base64Data: string): any {\n try {\n const decodedString = Buffer.from(base64Data, 'base64').toString('utf-8');\n return JSON.parse(decodedString);\n } catch (error) {\n throw new Error(`Failed to decode base64 data: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n}\n\n/**\n * Hash password using SHA1\n * @param password - Plain text password\n * @returns SHA1 hashed password\n */\nexport function hashPassword(password: string): string {\n return crypto.createHash('sha1').update(password).digest('hex');\n}\n","import { UserManager, type User, type UsersData } from './user-manager';\nimport { logger } from '../utils/logger';\n\n// Global reference to the current SDK's UserManager instance\nlet currentUserManager: UserManager | null = null;\n\n/**\n * Set the UserManager instance (called by SuperatomSDK during initialization)\n * This should be called with the SDK's UserManager instance\n * @param userManager - UserManager instance from SuperatomSDK\n */\nexport function setUserManager(userManager: UserManager): void {\n if (!userManager) {\n throw new Error('userManager cannot be null');\n }\n currentUserManager = userManager;\n logger.debug('UserManager instance set');\n}\n\n/**\n * Get the current UserManager instance\n */\nexport function getUserManager(): UserManager {\n if (!currentUserManager) {\n throw new Error(\n 'UserManager not initialized. Make sure SuperatomSDK is initialized before using user storage.'\n );\n }\n return currentUserManager;\n}\n\n/**\n * Load users from memory (UserManager maintains the cache)\n * @returns UsersData object containing all users\n */\nexport function loadUsers(): UsersData {\n const manager = getUserManager();\n return {\n users: manager.getAllUsers()\n };\n}\n\n/**\n * Save users to file immediately (forces sync)\n * @param usersData - UsersData object to save\n */\nexport async function saveUsers(usersData: UsersData): Promise<void> {\n const manager = getUserManager();\n\n // Clear existing users and repopulate\n manager.deleteAllUsers();\n\n // Add all users from the provided data\n for (const user of usersData.users) {\n try {\n manager.createUser(user);\n } catch (error) {\n // User might already exist, update instead\n if (manager.userExists(user.username)) {\n manager.updateUser(user.username, user);\n }\n }\n }\n\n // Force immediate sync to file\n await manager.forceSync();\n}\n\n/**\n * Find a user by username\n * @param username - Username to search for\n * @returns User object if found, null otherwise\n */\nexport function findUserByUsername(username: string): User | null {\n const manager = getUserManager();\n const user = manager.getUser(username);\n return user || null;\n}\n\n/**\n * Add WebSocket ID to a user's wsIds array\n * @param username - Username to update\n * @param wsId - WebSocket ID to add\n * @returns true if successful, false otherwise\n */\nexport function addWsIdToUser(username: string, wsId: string): boolean {\n try {\n const manager = getUserManager();\n return manager.addWsId(username, wsId);\n } catch (error) {\n logger.error('Error adding WebSocket ID:', error);\n return false;\n }\n}\n\n/**\n * Remove WebSocket ID from a user's wsIds array\n * @param username - Username to update\n * @param wsId - WebSocket ID to remove\n * @returns true if successful, false otherwise\n */\nexport function removeWsIdFromUser(username: string, wsId: string): boolean {\n try {\n const manager = getUserManager();\n return manager.removeWsId(username, wsId);\n } catch (error) {\n logger.error('Error removing WebSocket ID:', error);\n return false;\n }\n}\n\n/**\n * Cleanup and destroy the UserManager\n */\nexport async function cleanupUserStorage(): Promise<void> {\n if (currentUserManager) {\n await currentUserManager.destroy();\n currentUserManager = null;\n logger.info('UserManager cleaned up');\n }\n}\n\n// Export types\nexport type { User, UsersData } from './user-manager';\n","import { findUserByUsername, addWsIdToUser } from \"./user-storage\";\nimport { hashPassword } from \"./utils\";\nimport { logger } from \"../utils/logger\";\n\nexport interface LoginCredentials {\n username: string;\n password: string;\n}\n\nexport interface ValidationResult {\n success: boolean;\n error?: string;\n data?: any;\n username?: string;\n}\n\n/**\n * Validate user credentials against stored user data\n * @param credentials - Login credentials with username and password\n * @returns ValidationResult indicating success or failure\n */\nexport function validateUser(credentials: LoginCredentials): ValidationResult {\n const { username, password } = credentials;\n\n // Check if username and password are provided\n if (!username || !password) {\n logger.warn('Validation failed: Username and password are required');\n return {\n success: false,\n error: 'Username and password are required'\n };\n }\n\n // Find user by username from in-memory cache\n const user = findUserByUsername(username);\n\n if (!user) {\n logger.warn(`Validation failed: User not found - ${username}`);\n return {\n success: false,\n error: 'Invalid username'\n };\n }\n\n // Hash the stored password and compare with provided password\n const hashedPassword = hashPassword(user.password);\n\n if (hashedPassword !== password) {\n logger.warn(`Validation failed: Invalid password for user - ${username}`);\n return {\n success: false,\n error: 'Invalid password'\n };\n }\n\n logger.debug(`User validated successfully: ${username}`);\n return {\n success: true,\n data: user.username\n };\n}\n\n/**\n * Authenticate user and store WebSocket ID\n * Uses UserManager's in-memory cache with automatic file sync\n * @param credentials - Login credentials\n * @param wsId - WebSocket ID to store\n * @returns ValidationResult with authentication status\n */\nexport function authenticateAndStoreWsId(credentials: LoginCredentials, wsId: string): ValidationResult {\n const validationResult = validateUser(credentials);\n\n if (!validationResult.success) {\n return validationResult;\n }\n\n // Store wsId in user's wsIds array using UserManager\n // Changes are automatically synced to file via setInterval\n const stored = addWsIdToUser(credentials.username, wsId);\n\n if (!stored) {\n logger.error(`Failed to store WebSocket ID for user: ${credentials.username}`);\n return {\n success: false,\n error: 'Failed to store user session'\n };\n }\n\n logger.info(`WebSocket ID stored for user: ${credentials.username}`);\n return validationResult;\n}\n\n/**\n * Verify authentication token\n * @param authToken - Base64 encoded auth token containing username and password\n * @returns ValidationResult indicating if token is valid\n */\nexport function verifyAuthToken(authToken: string): ValidationResult {\n try {\n // Decode base64 token\n const decodedString = Buffer.from(authToken, 'base64').toString('utf-8');\n const credentials = JSON.parse(decodedString);\n\n logger.debug('Token decoded and parsed successfully');\n // Validate credentials\n return validateUser(credentials);\n } catch (error) {\n logger.error('Failed to verify auth token:', error);\n return {\n success: false,\n error: 'Invalid token format'\n };\n }\n}\n","import { decodeBase64ToJson } from \"../auth/utils\";\nimport { authenticateAndStoreWsId } from \"../auth/validator\";\nimport { AuthLoginRequestMessageSchema, Message } from \"../types\";\nimport { logger } from \"../utils/logger\";\n\n\n\nexport async function handleAuthLoginRequest(\n data: any,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const authRequest = AuthLoginRequestMessageSchema.parse(data);\n const { id, payload } = authRequest;\n \n const login_data = payload.login_data;\n\n const wsId = authRequest.from.id ;\n\n if(!login_data){\n sendDataResponse(id, {\n success: false,\n error: 'Login data not found'\n }, sendMessage, wsId);\n return;\n }\n\n\n // Decode base64 data and parse JSON\n let loginData: any;\n try {\n loginData = decodeBase64ToJson(login_data);\n } catch (error) {\n sendDataResponse(id, {\n success: false,\n error: 'Invalid login data format'\n }, sendMessage, wsId);\n return;\n }\n\n // Extract username and password from decoded data\n const { username, password } = loginData;\n\n if (!username) {\n sendDataResponse(id, {\n success: false,\n error: 'Username not found in login data'\n }, sendMessage, wsId);\n return;\n }\n\n if (!password) {\n sendDataResponse(id, {\n success: false,\n error: 'Password not found in login data'\n }, sendMessage, wsId);\n return;\n }\n\n\n if(!wsId){\n sendDataResponse(id, {\n success: false,\n error: 'WebSocket ID not found'\n }, sendMessage, wsId);\n return;\n }\n\n // Authenticate user and store wsId\n const authResult = authenticateAndStoreWsId(\n { username, password },\n wsId\n );\n\n // Send response\n\n sendDataResponse(id, authResult, sendMessage, wsId);\n return ;\n }\n catch (error) {\n logger.error('Failed to handle auth login request:', error);\n }\n}\n\n\n/**\n * Send a data_res response message\n */\nfunction sendDataResponse(\n id: string,\n res: {success: boolean; error?: string; data?: any},\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id,\n type: 'AUTH_LOGIN_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: clientId\n },\n payload:{\n ...res,\n }\n };\n\n sendMessage(response);\n}\n\n","import { verifyAuthToken } from \"../auth/validator\";\nimport { AuthVerifyRequestMessageSchema, Message } from \"../types\";\nimport { logger } from \"../utils/logger\";\n\n\nexport async function handleAuthVerifyRequest(\n data: any,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const authRequest = AuthVerifyRequestMessageSchema.parse(data);\n const { id, payload } = authRequest;\n \n const token = payload.token;\n\n const wsId = authRequest.from.id ;\n\n if(!token){\n sendDataResponse(id, {\n success: false,\n error: 'Token not found'\n }, sendMessage, wsId);\n return;\n }\n\n\n if(!wsId){\n sendDataResponse(id, {\n success: false,\n error: 'WebSocket ID not found'\n }, sendMessage, wsId);\n return;\n }\n\n // Verify token\n const authResult = verifyAuthToken(token);\n\n // Send response\n sendDataResponse(id, authResult, sendMessage, wsId);\n return ;\n }\n catch (error) {\n logger.error('Failed to handle auth verify request:', error);\n }\n}\n\n/**\n * Send a data_res response message\n */\nfunction sendDataResponse(\n id: string,\n res: {success: boolean; error?: string; data?: any},\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void { \n const response: Message = {\n id,\n type: 'AUTH_VERIFY_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: clientId\n },\n payload:{\n ...res,\n }\n };\n\n sendMessage(response);\n} ","import dotenv from 'dotenv';\nimport { BaseLLM, BaseLLMConfig } from './base-llm';\n\ndotenv.config();\n\nexport interface GroqLLMConfig extends BaseLLMConfig {}\n\n/**\n * GroqLLM class for handling AI-powered component generation and matching using Groq\n */\nexport class GroqLLM extends BaseLLM {\n\tconstructor(config?: GroqLLMConfig) {\n\t\tsuper(config);\n\t}\n\n\tprotected getDefaultModel(): string {\n\t\treturn 'groq/openai/gpt-oss-120b';\n\t}\n\n\tprotected getDefaultApiKey(): string | undefined {\n\t\treturn process.env.GROQ_API_KEY;\n\t}\n\n\tprotected getProviderName(): string {\n\t\treturn 'Groq';\n\t}\n}\n\n// Export a singleton instance\nexport const groqLLM = new GroqLLM();\n","/**\n * Converts T-SQL TOP syntax to Snowflake LIMIT syntax\n * Snowflake doesn't support TOP keyword - it must use LIMIT\n * @param query - The SQL query to check\n * @returns The query with TOP converted to LIMIT\n */\nexport function convertTopToLimit(query: string): string {\n\tif (!query || query.trim().length === 0) {\n\t\treturn query;\n\t}\n\n\t// Replace \"TOP N\" with nothing (we'll add LIMIT at the end)\n\t// Pattern: SELECT TOP number or SELECT TOP (number)\n\tlet modifiedQuery = query.replace(/\\bSELECT\\s+TOP\\s+(\\d+)\\b/gi, 'SELECT');\n\n\tif (modifiedQuery !== query) {\n\t\tconsole.warn(`⚠️ Query had TOP syntax. Converting to LIMIT for Snowflake compatibility.`);\n\t}\n\n\treturn modifiedQuery;\n}\n\n/**\n * Ensures a SQL query has a LIMIT clause to prevent large result sets\n * Only applies to SELECT queries - leaves INSERT, UPDATE, DELETE, etc. unchanged\n * Also removes any duplicate LIMIT clauses to prevent SQL errors\n * Converts T-SQL TOP syntax to Snowflake LIMIT syntax\n * @param query - The SQL query to check\n * @param defaultLimit - Default limit to apply if none exists (default: 50)\n * @returns The query with a single LIMIT clause (if it's a SELECT query)\n */\nexport function ensureQueryLimit(query: string, defaultLimit: number = 50): string {\n\tif (!query || query.trim().length === 0) {\n\t\treturn query;\n\t}\n\n\tlet trimmedQuery = query.trim();\n\n\t// Only apply LIMIT to SELECT queries\n\t// Check if the query is a SELECT statement (not INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, etc.)\n\tconst isSelectQuery = /^\\s*SELECT\\b/i.test(trimmedQuery) ||\n\t\t/^\\s*WITH\\b.*\\bSELECT\\b/is.test(trimmedQuery); // Also handle CTEs (WITH clause)\n\n\tif (!isSelectQuery) {\n\t\t// Not a SELECT query, return as-is\n\t\treturn query;\n\t}\n\n\t// Step 1: Convert TOP syntax to standard format\n\ttrimmedQuery = convertTopToLimit(trimmedQuery);\n\n\t// Remove any trailing semicolon for processing\n\tconst hadSemicolon = trimmedQuery.endsWith(';');\n\tif (hadSemicolon) {\n\t\ttrimmedQuery = trimmedQuery.slice(0, -1).trim();\n\t}\n\n\t// Remove any duplicate LIMIT clauses (keep only the last one, or remove all to add a fresh one)\n\t// This regex matches LIMIT followed by a number, case-insensitive\n\tconst limitMatches = trimmedQuery.match(/\\bLIMIT\\s+\\d+\\b/gi);\n\n\tif (limitMatches && limitMatches.length > 0) {\n\t\t// If there are multiple LIMIT clauses, remove them all and add a fresh one\n\t\tif (limitMatches.length > 1) {\n\t\t\tconsole.warn(`⚠️ Query had ${limitMatches.length} LIMIT clauses. Removing duplicates...`);\n\t\t\ttrimmedQuery = trimmedQuery.replace(/\\s*\\bLIMIT\\s+\\d+\\b/gi, '').trim();\n\t\t} else {\n\t\t\t// Single LIMIT exists, keep it as-is\n\t\t\tif (hadSemicolon) {\n\t\t\t\ttrimmedQuery += ';';\n\t\t\t}\n\t\t\treturn trimmedQuery;\n\t\t}\n\t}\n\n\t// Add LIMIT clause at the end\n\ttrimmedQuery = `${trimmedQuery} LIMIT ${defaultLimit}`;\n\n\t// Add back the semicolon if it was there\n\tif (hadSemicolon) {\n\t\ttrimmedQuery += ';';\n\t}\n\n\treturn trimmedQuery;\n}\n\n/**\n * Calculates the size of a JSON object in bytes\n * @param obj - The object to measure\n * @returns Size in bytes\n */\nexport function getJsonSizeInBytes(obj: any): number {\n\tconst jsonString = JSON.stringify(obj);\n\treturn Buffer.byteLength(jsonString, 'utf8');\n}\n\n/**\n * Checks if a message exceeds the WebSocket size limit\n * @param message - The message object to check\n * @param maxSize - Maximum size in bytes (default: 1MB)\n * @returns Object with isValid flag and size information\n */\nexport function validateMessageSize(message: any, maxSize: number = 1048576): { isValid: boolean; size: number; maxSize: number } {\n\tconst size = getJsonSizeInBytes(message);\n\treturn {\n\t\tisValid: size <= maxSize,\n\t\tsize,\n\t\tmaxSize\n\t};\n}","import path from 'path';\nimport fs from 'fs';\nimport { logger } from '../utils/logger';\n\n/**\n * Schema class for managing database schema operations\n */\nexport class Schema {\n private schemaFilePath: string;\n private cachedSchema: any = null;\n\n constructor(schemaFilePath?: string) {\n this.schemaFilePath = schemaFilePath || path.join(process.cwd(), '../analysis/data/schema.json');\n }\n\n /**\n * Gets the database schema from the schema file\n * @returns Parsed schema object or null if error occurs\n */\n getDatabaseSchema(): any | null {\n logger.info(`SCHEMA_FILE_PATH: ${this.schemaFilePath}`);\n\n try {\n // Create directory structure if it doesn't exist\n const dir = path.dirname(this.schemaFilePath);\n if (!fs.existsSync(dir)) {\n logger.info(`Creating directory structure: ${dir}`);\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Create file with empty schema if it doesn't exist\n if (!fs.existsSync(this.schemaFilePath)) {\n logger.info(`Schema file does not exist at ${this.schemaFilePath}, creating with empty schema`);\n const initialSchema = {\n database: '',\n schema: '',\n description: '',\n tables: [],\n relationships: []\n };\n fs.writeFileSync(this.schemaFilePath, JSON.stringify(initialSchema, null, 4));\n this.cachedSchema = initialSchema;\n return initialSchema;\n }\n\n const fileContent = fs.readFileSync(this.schemaFilePath, 'utf-8');\n const schema = JSON.parse(fileContent);\n this.cachedSchema = schema;\n return schema;\n } catch (error) {\n logger.error('Error parsing schema file:', error);\n return null;\n }\n }\n\n /**\n * Gets the cached schema or loads it if not cached\n * @returns Cached schema or freshly loaded schema\n */\n getSchema(): any | null {\n if (this.cachedSchema) {\n return this.cachedSchema;\n }\n return this.getDatabaseSchema();\n }\n\n /**\n * Generates database schema documentation for LLM from Snowflake JSON schema\n * @returns Formatted schema documentation string\n */\n generateSchemaDocumentation(): string {\n const schema = this.getSchema();\n\n if (!schema) {\n logger.warn('No database schema found.');\n return 'No database schema available.';\n }\n\n const tables: string[] = [];\n\n // Header information\n tables.push(`Database: ${schema.database}`);\n tables.push(`Schema: ${schema.schema}`);\n tables.push(`Description: ${schema.description}`);\n tables.push('');\n tables.push('='.repeat(80));\n tables.push('');\n\n // Process each table\n for (const table of schema.tables) {\n const tableInfo: string[] = [];\n\n tableInfo.push(`TABLE: ${table.fullName}`);\n tableInfo.push(`Description: ${table.description}`);\n tableInfo.push(`Row Count: ~${table.rowCount.toLocaleString()}`);\n tableInfo.push('');\n tableInfo.push('Columns:');\n\n // Process columns\n for (const column of table.columns) {\n let columnLine = ` - ${column.name}: ${column.type}`;\n\n if ((column as any).isPrimaryKey) {\n columnLine += ' (PRIMARY KEY)';\n }\n\n if ((column as any).isForeignKey && (column as any).references) {\n columnLine += ` (FK -> ${(column as any).references.table}.${(column as any).references.column})`;\n }\n\n if (!column.nullable) {\n columnLine += ' NOT NULL';\n }\n\n if (column.description) {\n columnLine += ` - ${column.description}`;\n }\n\n tableInfo.push(columnLine);\n\n // Add value examples for categorical columns\n if ((column as any).sampleValues && (column as any).sampleValues.length > 0) {\n tableInfo.push(` Sample values: [${(column as any).sampleValues.join(', ')}]`);\n }\n\n // Add statistics if available\n if ((column as any).statistics) {\n const stats = (column as any).statistics;\n if (stats.min !== undefined && stats.max !== undefined) {\n tableInfo.push(` Range: ${stats.min} to ${stats.max}`);\n }\n if (stats.distinct !== undefined) {\n tableInfo.push(` Distinct values: ${stats.distinct.toLocaleString()}`);\n }\n }\n }\n\n tableInfo.push('');\n tables.push(tableInfo.join('\\n'));\n }\n\n // Add relationships section\n tables.push('='.repeat(80));\n tables.push('');\n tables.push('TABLE RELATIONSHIPS:');\n tables.push('');\n\n for (const rel of schema.relationships) {\n tables.push(`${rel.from} -> ${rel.to} (${rel.type}): ${rel.keys.join(' = ')}`);\n }\n\n return tables.join('\\n');\n }\n\n /**\n * Clears the cached schema, forcing a reload on next access\n */\n clearCache(): void {\n this.cachedSchema = null;\n }\n\n /**\n * Sets a custom schema file path\n * @param filePath - Path to the schema file\n */\n setSchemaPath(filePath: string): void {\n this.schemaFilePath = filePath;\n this.clearCache();\n }\n}\n\n// Export a singleton instance for use across the application\nexport const schema = new Schema();\n","import fs from 'fs';\nimport path from 'path';\nimport { logger } from '../utils/logger';\n\nexport interface PromptLoaderConfig {\n\tpromptsDir?: string;\n}\n\n/**\n * PromptLoader class for loading and processing prompt templates\n */\nexport class PromptLoader {\n\tprivate promptsDir: string;\n\n\tconstructor(config?: PromptLoaderConfig) {\n\t\tlogger.debug('Initializing PromptLoader...',process.cwd());\n\t\tthis.promptsDir = config?.promptsDir || path.join(process.cwd(), '.prompts');\n\t}\n\n\t/**\n\t * Load a single prompt file and replace variables using {{VARIABLE_NAME}} pattern\n\t * @param promptName - Name of the prompt folder\n\t * @param promptType - Type of prompt ('system' or 'user')\n\t * @param variables - Variables to replace in the template\n\t * @returns Processed prompt string\n\t */\n\tasync loadPrompt(\n\t\tpromptName: string,\n\t\tpromptType: 'system' | 'user',\n\t\tvariables: Record<string, string | number | boolean | any[]>\n\t): Promise<string> {\n\t\ttry {\n\t\t\tconst promptPath = path.join(\n\t\t\t\tthis.promptsDir,\n\t\t\t\tpromptName,\n\t\t\t\t`${promptType}.md`\n\t\t\t);\n\t\t\tlogger.debug(`Loading prompt '${promptName}/${promptType}.md' from ${promptPath} process path: ${process.cwd()}`);\n\t\t\tlet content = fs.readFileSync(promptPath, 'utf-8');\n\n\t\t\t// Replace all variables matching {{VARIABLE_NAME}} pattern\n\t\t\tfor (const [key, value] of Object.entries(variables)) {\n\t\t\t\tconst pattern = new RegExp(`{{${key}}}`, 'g');\n\t\t\t\tconst replacementValue = typeof value === 'string' ? value : JSON.stringify(value);\n\t\t\t\tcontent = content.replace(pattern, replacementValue);\n\t\t\t}\n\n\t\t\treturn content;\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error loading prompt '${promptName}/${promptType}.md':`, error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Load both system and user prompts and replace variables\n\t * @param promptName - Name of the prompt folder\n\t * @param variables - Variables to replace in the templates\n\t * @returns Object containing both system and user prompts\n\t */\n\tasync loadPrompts(\n\t\tpromptName: string,\n\t\tvariables: Record<string, string | number | boolean | any[]>\n\t): Promise<{ system: string; user: string }> {\n\t\tconst [system, user] = await Promise.all([\n\t\t\tthis.loadPrompt(promptName, 'system', variables),\n\t\t\tthis.loadPrompt(promptName, 'user', variables)\n\t\t]);\n\n\t\treturn { system, user };\n\t}\n\n\t/**\n\t * Set custom prompts directory\n\t * @param dir - Path to the prompts directory\n\t */\n\tsetPromptsDir(dir: string): void {\n\t\tthis.promptsDir = dir;\n\t}\n\n\t/**\n\t * Get current prompts directory\n\t * @returns Path to the prompts directory\n\t */\n\tgetPromptsDir(): string {\n\t\treturn this.promptsDir;\n\t}\n}\n\n// Export a singleton instance\nexport const promptLoader = new PromptLoader();\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport Groq from \"groq-sdk\";\n\ninterface LLMMessages {\n sys: string;\n user: string;\n}\n\ninterface LLMOptions {\n model?: string;\n maxTokens?: number;\n temperature?: number;\n topP?: number;\n apiKey?: string;\n partial?: (chunk: string) => void; // Callback for each chunk\n}\n\nexport class LLM {\n /* Get a complete text response from an LLM (Anthropic or Groq) */\n static async text(messages: LLMMessages, options: LLMOptions = {}): Promise<string> {\n const [provider, modelName] = this._parseModel(options.model);\n\n if (provider === 'anthropic') {\n return this._anthropicText(messages, modelName, options);\n } else if (provider === 'groq') {\n return this._groqText(messages, modelName, options);\n } else {\n throw new Error(`Unsupported provider: ${provider}. Use \"anthropic\" or \"groq\"`);\n }\n }\n\n /* Stream response from an LLM (Anthropic or Groq) */\n static async stream<T = string>(\n messages: LLMMessages,\n options: LLMOptions = {},\n json?: boolean\n ): Promise<T extends string ? string : any> {\n const [provider, modelName] = this._parseModel(options.model);\n\n if (provider === 'anthropic') {\n return this._anthropicStream(messages, modelName, options, json);\n } else if (provider === 'groq') {\n return this._groqStream(messages, modelName, options, json);\n } else {\n throw new Error(`Unsupported provider: ${provider}. Use \"anthropic\" or \"groq\"`);\n }\n }\n\n // ============================================================\n // PRIVATE HELPER METHODS\n // ============================================================\n\n /**\n * Parse model string to extract provider and model name\n * @param modelString - Format: \"provider/model-name\" or just \"model-name\"\n * @returns [provider, modelName]\n *\n * @example\n * \"anthropic/claude-sonnet-4-5\" → [\"anthropic\", \"claude-sonnet-4-5\"]\n * \"groq/openai/gpt-oss-120b\" → [\"groq\", \"openai/gpt-oss-120b\"]\n * \"claude-sonnet-4-5\" → [\"anthropic\", \"claude-sonnet-4-5\"] (default)\n */\n private static _parseModel(modelString?: string): [string, string] {\n if (!modelString) {\n // Default to Anthropic Claude\n return ['anthropic', 'claude-sonnet-4-5'];\n }\n\n // Check if model string has provider prefix\n if (modelString.includes('/')) {\n // Split only on the FIRST slash to handle models like \"groq/openai/gpt-oss-120b\"\n const firstSlashIndex = modelString.indexOf('/');\n const provider = modelString.substring(0, firstSlashIndex).toLowerCase().trim();\n const model = modelString.substring(firstSlashIndex + 1).trim();\n return [provider, model];\n }\n\n // No prefix, assume Anthropic\n return ['anthropic', modelString];\n }\n\n // ============================================================\n // ANTHROPIC IMPLEMENTATION\n // ============================================================\n\n private static async _anthropicText(\n messages: LLMMessages,\n modelName: string,\n options: LLMOptions\n ): Promise<string> {\n const apiKey = options.apiKey || process.env.ANTHROPIC_API_KEY || \"\";\n console.log('[LLM DEBUG] Anthropic Text - apiKey from options:', options.apiKey ? `${options.apiKey.substring(0, 10)}...` : 'NOT SET');\n console.log('[LLM DEBUG] Anthropic Text - final apiKey:', apiKey ? `${apiKey.substring(0, 10)}...` : 'EMPTY STRING');\n const client = new Anthropic({\n apiKey: apiKey,\n });\n\n const response = await client.messages.create({\n model: modelName,\n max_tokens: options.maxTokens || 1000,\n temperature: options.temperature,\n system: messages.sys,\n messages: [{\n role: \"user\",\n content: messages.user\n }]\n });\n\n const textBlock = response.content.find(block => block.type === 'text');\n return textBlock?.type === 'text' ? textBlock.text : '';\n }\n\n private static async _anthropicStream(\n messages: LLMMessages,\n modelName: string,\n options: LLMOptions,\n json?: boolean\n ): Promise<any> {\n const apiKey = options.apiKey || process.env.ANTHROPIC_API_KEY || \"\";\n console.log('[LLM DEBUG] Anthropic - apiKey from options:', options.apiKey ? `${options.apiKey.substring(0, 10)}...` : 'NOT SET');\n console.log('[LLM DEBUG] Anthropic - apiKey from env:', process.env.ANTHROPIC_API_KEY ? `${process.env.ANTHROPIC_API_KEY.substring(0, 10)}...` : 'NOT SET');\n console.log('[LLM DEBUG] Anthropic - final apiKey:', apiKey ? `${apiKey.substring(0, 10)}...` : 'EMPTY STRING');\n const client = new Anthropic({\n apiKey: apiKey,\n });\n\n const stream = await client.messages.create({\n model: modelName,\n max_tokens: options.maxTokens || 1000,\n temperature: options.temperature,\n system: messages.sys,\n messages: [{\n role: \"user\",\n content: messages.user\n }],\n stream: true,\n });\n\n let fullText = '';\n\n // Process stream\n for await (const chunk of stream) {\n if (chunk.type === 'content_block_delta' && chunk.delta.type === 'text_delta') {\n const text = chunk.delta.text;\n fullText += text;\n\n // Call partial callback if provided\n if (options.partial) {\n options.partial(text);\n }\n }\n }\n\n // Return parsed JSON or text\n if (json) {\n return this._parseJSON(fullText);\n }\n\n return fullText;\n }\n\n // ============================================================\n // GROQ IMPLEMENTATION\n // ============================================================\n\n private static async _groqText(\n messages: LLMMessages,\n modelName: string,\n options: LLMOptions\n ): Promise<string> {\n const client = new Groq({\n apiKey: options.apiKey || process.env.GROQ_API_KEY || \"\",\n });\n\n const response = await client.chat.completions.create({\n model: modelName,\n messages: [\n { role: 'system', content: messages.sys },\n { role: 'user', content: messages.user }\n ],\n temperature: options.temperature,\n max_tokens: options.maxTokens || 1000,\n });\n\n return response.choices[0]?.message?.content || '';\n }\n\n private static async _groqStream(\n messages: LLMMessages,\n modelName: string,\n options: LLMOptions,\n json?: boolean\n ): Promise<any> {\n const apiKey = options.apiKey || process.env.GROQ_API_KEY || \"\";\n console.log('[LLM DEBUG] Groq - apiKey from options:', options.apiKey ? `${options.apiKey.substring(0, 10)}...` : 'NOT SET');\n console.log('[LLM DEBUG] Groq - model:', modelName);\n console.log('[LLM DEBUG] Groq - final apiKey:', apiKey ? `${apiKey.substring(0, 10)}...` : 'EMPTY STRING');\n const client = new Groq({\n apiKey: apiKey,\n });\n\n const stream = await client.chat.completions.create({\n model: modelName,\n messages: [\n { role: 'system', content: messages.sys },\n { role: 'user', content: messages.user }\n ],\n temperature: options.temperature,\n max_tokens: options.maxTokens || 1000,\n stream: true,\n response_format: json ? { type: 'json_object' } : undefined\n });\n\n let fullText = '';\n\n // Process stream\n for await (const chunk of stream) {\n const text = chunk.choices[0]?.delta?.content || '';\n if (text) {\n fullText += text;\n\n // Call partial callback if provided\n if (options.partial) {\n options.partial(text);\n }\n }\n }\n\n // Return parsed JSON or text\n if (json) {\n return this._parseJSON(fullText);\n }\n\n return fullText;\n }\n\n // ============================================================\n // JSON PARSING HELPER\n // ============================================================\n\n /**\n * Parse JSON string, handling markdown code blocks and surrounding text\n * Enhanced version from anthropic.ts implementation\n * @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text\n * @returns Parsed JSON object\n */\n private static _parseJSON(text: string): any {\n let jsonText = text.trim();\n\n // Remove markdown code blocks\n if (jsonText.startsWith('```json')) {\n jsonText = jsonText.replace(/^```json\\s*\\n?/, '').replace(/\\n?```\\s*$/, '');\n } else if (jsonText.startsWith('```')) {\n jsonText = jsonText.replace(/^```\\s*\\n?/, '').replace(/\\n?```\\s*$/, '');\n }\n\n // Extract JSON if there's surrounding text - find the first { and last }\n const firstBrace = jsonText.indexOf('{');\n const lastBrace = jsonText.lastIndexOf('}');\n if (firstBrace !== -1 && lastBrace !== -1 && firstBrace < lastBrace) {\n jsonText = jsonText.substring(firstBrace, lastBrace + 1);\n }\n\n return JSON.parse(jsonText);\n }\n}","import { Component } from '../types';\nimport { ensureQueryLimit } from './utils';\nimport { schema } from './schema';\nimport { promptLoader } from './prompt-loader';\nimport { LLM } from '../llm';\nimport { logger } from '../utils/logger';\n\nexport interface BaseLLMConfig {\n\tmodel?: string;\n\tdefaultLimit?: number;\n\tapiKey?: string;\n}\n\n/**\n * BaseLLM abstract class for AI-powered component generation and matching\n * Provides common functionality for all LLM providers\n */\nexport abstract class BaseLLM {\n\tprotected model: string;\n\tprotected defaultLimit: number;\n\tprotected apiKey?: string;\n\n\tconstructor(config?: BaseLLMConfig) {\n\t\tthis.model = config?.model || this.getDefaultModel();\n\t\tthis.defaultLimit = config?.defaultLimit || 50;\n\t\tthis.apiKey = config?.apiKey;\n\t}\n\n\t/**\n\t * Get the default model for this provider\n\t */\n\tprotected abstract getDefaultModel(): string;\n\n\t/**\n\t * Get the default API key from environment\n\t */\n\tprotected abstract getDefaultApiKey(): string | undefined;\n\n\t/**\n\t * Get the provider name (for logging)\n\t */\n\tprotected abstract getProviderName(): string;\n\n\t/**\n\t * Get the API key (from instance, parameter, or environment)\n\t */\n\tprotected getApiKey(apiKey?: string): string | undefined {\n\t\treturn apiKey || this.apiKey || this.getDefaultApiKey();\n\t}\n\n\t/**\n\t * Classify user question to determine the type and required visualizations\n\t */\n\tasync classifyUserQuestion(\n\t\tuserPrompt: string,\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tquestionType: 'analytical' | 'data_modification' | 'general';\n\t\tvisualizations: string[];\n\t\treasoning: string;\n\t\tneedsMultipleComponents: boolean;\n\t}> {\n\t\tconst schemaDoc = schema.generateSchemaDocumentation();\n\t\tlogger.info('Generating prompts...', userPrompt, conversationHistory);\n\t\ttry {\n\t\t\tconst prompts = await promptLoader.loadPrompts('classify', {\n\t\t\t\tSCHEMA_DOC: schemaDoc || 'No schema available',\n\t\t\t\tUSER_PROMPT: userPrompt,\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 800,\n\t\t\t\t\ttemperature: 0.2,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\t// Log the LLM explanation with type\n\t\t\tlogCollector?.logExplanation(\n\t\t\t\t'User question classified',\n\t\t\t\tresult.reasoning || 'No reasoning provided',\n\t\t\t\t{\n\t\t\t\t\tquestionType: result.questionType || 'general',\n\t\t\t\t\tvisualizations: result.visualizations || [],\n\t\t\t\t\tneedsMultipleComponents: result.needsMultipleComponents || false\n\t\t\t\t}\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\tquestionType: result.questionType || 'general',\n\t\t\t\tvisualizations: result.visualizations || [],\n\t\t\t\treasoning: result.reasoning || 'No reasoning provided',\n\t\t\t\tneedsMultipleComponents: result.needsMultipleComponents || false\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error('Error classifying user question:', error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Enhanced function that validates and modifies the entire props object based on user request\n\t * This includes query, title, description, and config properties\n\t */\n\tasync validateAndModifyProps(\n\t\tuserPrompt: string,\n\t\toriginalProps: any,\n\t\tcomponentName: string,\n\t\tcomponentType: string,\n\t\tcomponentDescription?: string,\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{ props: any; isModified: boolean; reasoning: string; modifications: string[] }> {\n\n\t\tconst schemaDoc = schema.generateSchemaDocumentation();\n\t\ttry {\n\t\t\tconst prompts = await promptLoader.loadPrompts('modify-props', {\n\t\t\t\tCOMPONENT_NAME: componentName,\n\t\t\t\tCOMPONENT_TYPE: componentType,\n\t\t\t\tCOMPONENT_DESCRIPTION: componentDescription || 'No description',\n\t\t\t\tSCHEMA_DOC: schemaDoc || 'No schema available',\n\t\t\t\tDEFAULT_LIMIT: this.defaultLimit,\n\t\t\t\tUSER_PROMPT: userPrompt,\n\t\t\t\tCURRENT_PROPS: JSON.stringify(originalProps, null, 2),\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 2500,\n\t\t\t\t\ttemperature: 0.2,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\t// Ensure all queries have a LIMIT clause\n\t\t\tconst props = result.props || originalProps;\n\t\t\tif (props && props.query) {\n\t\t\t\tprops.query = ensureQueryLimit(props.query, this.defaultLimit);\n\t\t\t}\n\n\t\t\t// Log the generated query and explanation with types\n\t\t\tif (props && props.query) {\n\t\t\t\tlogCollector?.logQuery(\n\t\t\t\t\t'Props query modified',\n\t\t\t\t\tprops.query,\n\t\t\t\t\t{\n\t\t\t\t\t\tmodifications: result.modifications || [],\n\t\t\t\t\t\treasoning: result.reasoning || 'No modifications needed'\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (result.reasoning) {\n\t\t\t\tlogCollector?.logExplanation(\n\t\t\t\t\t'Props modification explanation',\n\t\t\t\t\tresult.reasoning,\n\t\t\t\t\t{ modifications: result.modifications || [] }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tprops: props,\n\t\t\t\tisModified: result.isModified || false,\n\t\t\t\treasoning: result.reasoning || 'No modifications needed',\n\t\t\t\tmodifications: result.modifications || []\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error validating/modifying props with ${this.getProviderName()}:`, error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Generate a dynamic component for analytical questions when no matching component exists\n\t * This creates a custom component with appropriate visualization and query\n\t */\n\tasync generateAnalyticalComponent(\n\t\tuserPrompt: string,\n\t\tpreferredVisualizationType?: string,\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tcomponent: Component | null;\n\t\treasoning: string;\n\t\tisGenerated: boolean;\n\t}> {\n\t\tconst schemaDoc = schema.generateSchemaDocumentation();\n\n\t\ttry {\n\t\t\tconst visualizationConstraint = preferredVisualizationType\n\t\t\t\t? `\\n**IMPORTANT: The user has specifically requested a ${preferredVisualizationType} visualization. You MUST use this type.**\\n`\n\t\t\t\t: '';\n\n\t\t\tconst prompts = await promptLoader.loadPrompts('single-component', {\n\t\t\t\tSCHEMA_DOC: schemaDoc || 'No schema available',\n\t\t\t\tVISUALIZATION_CONSTRAINT: visualizationConstraint,\n\t\t\t\tUSER_PROMPT: userPrompt,\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 2000,\n\t\t\t\t\ttemperature: 0.2,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\tif (!result.canGenerate) {\n\t\t\t\tlogCollector?.warn(\n\t\t\t\t\t'Cannot generate component',\n\t\t\t\t\t'explanation',\n\t\t\t\t\t{ reason: result.reasoning || 'Unable to generate component for this question' }\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tcomponent: null,\n\t\t\t\t\treasoning: result.reasoning || 'Unable to generate component for this question',\n\t\t\t\t\tisGenerated: false\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Ensure the generated query has a LIMIT clause\n\t\t\tconst query = ensureQueryLimit(result.query, this.defaultLimit);\n\n\t\t\t// Log the generated query and explanation with types\n\t\t\tlogCollector?.logQuery(\n\t\t\t\t'Analytical component query generated',\n\t\t\t\tquery,\n\t\t\t\t{\n\t\t\t\t\tcomponentType: result.componentType,\n\t\t\t\t\tvisualization: preferredVisualizationType || result.componentType,\n\t\t\t\t\ttitle: result.title\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tlogCollector?.logExplanation(\n\t\t\t\t'Analytical component generated',\n\t\t\t\tresult.reasoning || 'Generated dynamic component based on analytical question',\n\t\t\t\t{\n\t\t\t\t\tcomponentType: result.componentType,\n\t\t\t\t\tdescription: result.description\n\t\t\t\t}\n\t\t\t);\n\n\t\t\t// Create a dynamic component object\n\t\t\tconst dynamicComponent: Component = {\n\t\t\t\tid: `dynamic_${Date.now()}`,\n\t\t\t\tname: `Dynamic${result.componentType}`,\n\t\t\t\ttype: result.componentType,\n\t\t\t\tdescription: result.description,\n\t\t\t\tcategory: 'dynamic',\n\t\t\t\tkeywords: [],\n\t\t\t\tprops: {\n\t\t\t\t\tquery: query,\n\t\t\t\t\ttitle: result.title,\n\t\t\t\t\tdescription: result.description,\n\t\t\t\t\tconfig: result.config || {}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\treturn {\n\t\t\t\tcomponent: dynamicComponent,\n\t\t\t\treasoning: result.reasoning || 'Generated dynamic component based on analytical question',\n\t\t\t\tisGenerated: true\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error('Error generating analytical component:', error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Match component from a list with enhanced props modification\n\t */\n\tasync matchComponent(\n\t\tuserPrompt: string,\n\t\tcomponents: Component[],\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tcomponent: Component | null;\n\t\treasoning: string;\n\t\tqueryModified?: boolean;\n\t\tqueryReasoning?: string;\n\t\tpropsModified?: boolean;\n\t\tpropsModifications?: string[];\n\t\tmethod: string;\n\t\tconfidence?: number;\n\t}> {\n\t\ttry {\n\t\t\t// Step 1: Enhanced component matching with scoring and multiple candidates\n\t\t\tconst componentsText = components\n\t\t\t\t.map((comp, idx) => {\n\t\t\t\t\tconst keywords = comp.keywords ? comp.keywords.join(', ') : '';\n\t\t\t\t\tconst category = comp.category || 'general';\n\t\t\t\t\treturn `${idx + 1}. ID: ${comp.id}\n Name: ${comp.name}\n Type: ${comp.type}\n Category: ${category}\n Description: ${comp.description || 'No description'}\n Keywords: ${keywords}`;\n\t\t\t\t})\n\t\t\t\t.join('\\n\\n');\n\n\t\t\tconst prompts = await promptLoader.loadPrompts('match-component', {\n\t\t\t\tCOMPONENTS_TEXT: componentsText,\n\t\t\t\tUSER_PROMPT: userPrompt,\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 800,\n\t\t\t\t\ttemperature: 0.2,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\tconst componentIndex = result.componentIndex;\n\t\t\tconst componentId = result.componentId;\n\t\t\tconst confidence = result.confidence || 0;\n\n\t\t\t// Prefer componentId over componentIndex for accuracy\n\t\t\tlet component = null;\n\t\t\tif (componentId) {\n\t\t\t\tcomponent = components.find(c => c.id === componentId);\n\t\t\t}\n\n\t\t\t// Fallback to componentIndex if ID not found\n\t\t\tif (!component && componentIndex) {\n\t\t\t\tcomponent = components[componentIndex - 1];\n\t\t\t}\n\n\t\t\tconst matchedMsg = `${this.getProviderName()} matched component: ${component?.name || 'None'}`;\n\t\t\tconsole.log('✓', matchedMsg);\n\t\t\tlogCollector?.info(matchedMsg);\n\n\t\t\tif (result.alternativeMatches && result.alternativeMatches.length > 0) {\n\t\t\t\tconsole.log(' Alternative matches:');\n\t\t\t\tconst altMatches = result.alternativeMatches.map((alt: any) =>\n\t\t\t\t\t`${components[alt.index - 1]?.name} (${alt.score}%): ${alt.reason}`\n\t\t\t\t).join(' | ');\n\t\t\t\tlogCollector?.info(`Alternative matches: ${altMatches}`);\n\t\t\t\tresult.alternativeMatches.forEach((alt: any) => {\n\t\t\t\t\tconsole.log(` - ${components[alt.index - 1]?.name} (${alt.score}%): ${alt.reason}`);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!component) {\n\t\t\t\tconst noMatchMsg = `No matching component found (confidence: ${confidence}%)`;\n\t\t\t\tconsole.log('✗', noMatchMsg);\n\t\t\t\tlogCollector?.warn(noMatchMsg);\n\t\t\t\tconst genMsg = 'Attempting to generate dynamic component from analytical question...';\n\t\t\t\tconsole.log('✓', genMsg);\n\t\t\t\tlogCollector?.info(genMsg);\n\n\t\t\t\t// Try to generate a dynamic component for the analytical question\n\t\t\t\tconst generatedResult = await this.generateAnalyticalComponent(userPrompt, undefined, apiKey, logCollector, conversationHistory);\n\n\t\t\t\tif (generatedResult.component) {\n\t\t\t\t\tconst genSuccessMsg = `Successfully generated component: ${generatedResult.component.name}`;\n\t\t\t\t\tlogCollector?.info(genSuccessMsg);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcomponent: generatedResult.component,\n\t\t\t\t\t\treasoning: generatedResult.reasoning,\n\t\t\t\t\t\tmethod: `${this.getProviderName()}-generated`,\n\t\t\t\t\t\tconfidence: 100, // Generated components are considered 100% match to the question\n\t\t\t\t\t\tpropsModified: false,\n\t\t\t\t\t\tqueryModified: false\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// If generation also failed, return null\n\t\t\t\tlogCollector?.error('Failed to generate dynamic component');\n\t\t\t\treturn {\n\t\t\t\t\tcomponent: null,\n\t\t\t\t\treasoning: result.reasoning || 'No matching component found and unable to generate dynamic component',\n\t\t\t\t\tmethod: `${this.getProviderName()}-llm`,\n\t\t\t\t\tconfidence\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Step 2: Validate and modify the entire props object based on user request\n\t\t\tlet propsModified = false;\n\t\t\tlet propsModifications: string[] = [];\n\t\t\tlet queryModified = false;\n\t\t\tlet queryReasoning = '';\n\n\t\t\tif (component && component.props) {\n\n\t\t\t\tconst propsValidation = await this.validateAndModifyProps(\n\t\t\t\t\tuserPrompt,\n\t\t\t\t\tcomponent.props,\n\t\t\t\t\tcomponent.name,\n\t\t\t\t\tcomponent.type,\n\t\t\t\t\tcomponent.description,\n\t\t\t\t\tapiKey,\n\t\t\t\t\tlogCollector,\n\t\t\t\t\tconversationHistory\n\t\t\t\t);\n\n\t\t\t\t// Create a new component object with the modified props\n\t\t\t\tconst originalQuery = component.props.query;\n\t\t\t\tconst modifiedQuery = propsValidation.props.query;\n\n\t\t\t\tcomponent = {\n\t\t\t\t\t...component,\n\t\t\t\t\tprops: propsValidation.props\n\t\t\t\t};\n\n\t\t\t\tpropsModified = propsValidation.isModified;\n\t\t\t\tpropsModifications = propsValidation.modifications;\n\t\t\t\tqueryModified = originalQuery !== modifiedQuery;\n\t\t\t\tqueryReasoning = propsValidation.reasoning;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tcomponent,\n\t\t\t\treasoning: result.reasoning || 'No reasoning provided',\n\t\t\t\tqueryModified,\n\t\t\t\tqueryReasoning,\n\t\t\t\tpropsModified,\n\t\t\t\tpropsModifications,\n\t\t\t\tmethod: `${this.getProviderName()}-llm`,\n\t\t\t\tconfidence\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error matching component with ${this.getProviderName()}:`, error);\n\t\t\tlogCollector?.error(`Error matching component: ${(error as Error).message}`);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Generate multiple dynamic components for analytical questions\n\t * This is used when the user needs multiple visualizations\n\t */\n\tasync generateMultipleAnalyticalComponents(\n\t\tuserPrompt: string,\n\t\tvisualizationTypes: string[],\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tcomponents: Component[];\n\t\treasoning: string;\n\t\tisGenerated: boolean;\n\t}> {\n\t\ttry {\n\t\t\tconsole.log('✓ Generating multiple components:', visualizationTypes);\n\n\t\t\tconst components: Component[] = [];\n\n\t\t\t// Generate each component type requested\n\t\t\tfor (const vizType of visualizationTypes) {\n\t\t\t\tconst result = await this.generateAnalyticalComponent(userPrompt, vizType, apiKey, logCollector, conversationHistory);\n\n\t\t\t\tif (result.component) {\n\t\t\t\t\tcomponents.push(result.component);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (components.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcomponents: [],\n\t\t\t\t\treasoning: 'Failed to generate any components',\n\t\t\t\t\tisGenerated: false\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tcomponents,\n\t\t\t\treasoning: `Generated ${components.length} components: ${visualizationTypes.join(', ')}`,\n\t\t\t\tisGenerated: true\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error('Error generating multiple analytical components:', error);\n\t\t\treturn {\n\t\t\t\tcomponents: [],\n\t\t\t\treasoning: 'Error occurred while generating components',\n\t\t\t\tisGenerated: false\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Generate a complete multi-component response with intelligent container and component props\n\t */\n\tasync generateMultiComponentResponse(\n\t\tuserPrompt: string,\n\t\tvisualizationTypes: string[],\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tcontainerComponent: Component | null;\n\t\treasoning: string;\n\t\tisGenerated: boolean;\n\t}> {\n\t\tconst schemaDoc = schema.generateSchemaDocumentation();\n\n\t\ttry {\n\t\t\tconst prompts = await promptLoader.loadPrompts('mutli-component', {\n\t\t\t\tSCHEMA_DOC: schemaDoc || 'No schema available',\n\t\t\t\tDEFAULT_LIMIT: this.defaultLimit,\n\t\t\t\tUSER_PROMPT: userPrompt,\n\t\t\t\tVISUALIZATION_TYPES: visualizationTypes.join(', '),\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 3000,\n\t\t\t\t\ttemperature: 0.2,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\tif (!result.canGenerate || !result.components || result.components.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcontainerComponent: null,\n\t\t\t\t\treasoning: result.reasoning || 'Unable to generate multi-component dashboard',\n\t\t\t\t\tisGenerated: false\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Build the component array from the result\n\t\t\tconst generatedComponents: Component[] = result.components.map((compData: any, index: number) => {\n\t\t\t\t// Ensure query has LIMIT\n\t\t\t\tconst query = ensureQueryLimit(compData.query, this.defaultLimit);\n\n\t\t\t\treturn {\n\t\t\t\t\tid: `dynamic_${compData.componentType.toLowerCase()}_${Date.now()}_${index}`,\n\t\t\t\t\tname: `Dynamic${compData.componentType}`,\n\t\t\t\t\ttype: compData.componentType,\n\t\t\t\t\tdescription: compData.description,\n\t\t\t\t\tcategory: 'dynamic',\n\t\t\t\t\tkeywords: [],\n\t\t\t\t\tprops: {\n\t\t\t\t\t\tquery: query,\n\t\t\t\t\t\ttitle: compData.title,\n\t\t\t\t\t\tdescription: compData.description,\n\t\t\t\t\t\tconfig: compData.config || {}\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t});\n\n\t\t\t// Log each generated component's query\n\t\t\tgeneratedComponents.forEach((component, index) => {\n\t\t\t\tif (component.props.query) {\n\t\t\t\t\tlogCollector?.logQuery(\n\t\t\t\t\t\t`Multi-component query generated (${index + 1}/${generatedComponents.length})`,\n\t\t\t\t\t\tcomponent.props.query,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcomponentType: component.type,\n\t\t\t\t\t\t\ttitle: component.props.title,\n\t\t\t\t\t\t\tposition: index + 1,\n\t\t\t\t\t\t\ttotalComponents: generatedComponents.length\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Log the overall explanation for the multi-component dashboard\n\t\t\tlogCollector?.logExplanation(\n\t\t\t\t'Multi-component dashboard generated',\n\t\t\t\tresult.reasoning || `Generated ${generatedComponents.length} components for comprehensive analysis`,\n\t\t\t\t{\n\t\t\t\t\ttotalComponents: generatedComponents.length,\n\t\t\t\t\tcomponentTypes: generatedComponents.map(c => c.type),\n\t\t\t\t\tcontainerTitle: result.containerTitle,\n\t\t\t\t\tcontainerDescription: result.containerDescription\n\t\t\t\t}\n\t\t\t);\n\n\t\t\t// Create the MultiComponentContainer wrapper\n\t\t\tconst containerComponent: Component = {\n\t\t\t\tid: `multi_container_${Date.now()}`,\n\t\t\t\tname: 'MultiComponentContainer',\n\t\t\t\ttype: 'Container',\n\t\t\t\tdescription: result.containerDescription,\n\t\t\t\tcategory: 'dynamic',\n\t\t\t\tkeywords: ['multi', 'container', 'dashboard'],\n\t\t\t\tprops: {\n\t\t\t\t\tconfig: {\n\t\t\t\t\t\tcomponents: generatedComponents,\n\t\t\t\t\t\tlayout: 'grid',\n\t\t\t\t\t\tspacing: 24,\n\t\t\t\t\t\ttitle: result.containerTitle,\n\t\t\t\t\t\tdescription: result.containerDescription\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\treturn {\n\t\t\t\tcontainerComponent,\n\t\t\t\treasoning: result.reasoning || `Generated multi-component dashboard with ${generatedComponents.length} components`,\n\t\t\t\tisGenerated: true\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error('Error generating multi-component response:', error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Main orchestration function that classifies question and routes to appropriate handler\n\t * This is the NEW recommended entry point for handling user requests\n\t * ALWAYS returns a SINGLE component (wraps multiple in MultiComponentContainer)\n\t */\n\tasync handleUserRequest(\n\t\tuserPrompt: string,\n\t\tcomponents: Component[],\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tcomponent: Component | null;\n\t\treasoning: string;\n\t\tmethod: string;\n\t\tquestionType: string;\n\t\tneedsMultipleComponents: boolean;\n\t\tpropsModified?: boolean;\n\t\tqueryModified?: boolean;\n\t}> {\n\t\ttry {\n\t\t\t// Step 1: Classify the user's question\n\t\t\tconst classifyMsg = 'Classifying user question...';\n\t\t\tlogCollector?.info(classifyMsg);\n\t\t\tconst classification = await this.classifyUserQuestion(userPrompt, apiKey, logCollector, conversationHistory);\n\t\t\tconst classInfo = `Question type: ${classification.questionType}, Visualizations: ${classification.visualizations.join(', ') || 'None'}, Multiple components: ${classification.needsMultipleComponents}`;\n\t\t\tlogCollector?.info(classInfo);\n\n\t\t\t// Step 2: Route based on question type\n\t\t\tif (classification.questionType === 'analytical') {\n\t\t\t\t// For analytical questions with specific visualization types\n\t\t\t\tif (classification.visualizations.length > 0) {\n\t\t\t\t\tif (classification.needsMultipleComponents && classification.visualizations.length > 1) {\n\t\t\t\t\t\t// Generate multiple components wrapped in MultiComponentContainer\n\t\t\t\t\t\tconst multiMsg = 'Generating multi-component dashboard...';\n\t\t\t\t\t\tlogCollector?.info(multiMsg);\n\t\t\t\t\t\tconst result = await this.generateMultiComponentResponse(\n\t\t\t\t\t\t\tuserPrompt,\n\t\t\t\t\t\t\tclassification.visualizations,\n\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\tlogCollector,\n\t\t\t\t\t\t\tconversationHistory\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcomponent: result.containerComponent,\n\t\t\t\t\t\t\treasoning: result.reasoning,\n\t\t\t\t\t\t\tmethod: 'classification-multi-generated',\n\t\t\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\t\t\tneedsMultipleComponents: true,\n\t\t\t\t\t\t\tpropsModified: false,\n\t\t\t\t\t\t\tqueryModified: false\n\t\t\t\t\t\t};\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Generate single component with preferred type\n\t\t\t\t\t\tconst vizType = classification.visualizations[0];\n\t\t\t\t\t\tconst result = await this.generateAnalyticalComponent(userPrompt, vizType, apiKey, logCollector, conversationHistory);\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcomponent: result.component,\n\t\t\t\t\t\t\treasoning: result.reasoning,\n\t\t\t\t\t\t\tmethod: 'classification-generated',\n\t\t\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\t\t\tneedsMultipleComponents: false,\n\t\t\t\t\t\t\tpropsModified: false,\n\t\t\t\t\t\t\tqueryModified: false\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// No specific visualization type, let AI decide\n\t\t\t\t\tconst result = await this.generateAnalyticalComponent(userPrompt, undefined, apiKey, logCollector, conversationHistory);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcomponent: result.component,\n\t\t\t\t\t\treasoning: result.reasoning,\n\t\t\t\t\t\tmethod: 'classification-generated-auto',\n\t\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\t\tneedsMultipleComponents: false,\n\t\t\t\t\t\tpropsModified: false,\n\t\t\t\t\t\tqueryModified: false\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} else if (classification.questionType === 'data_modification') {\n\t\t\t\t// For data modification, use the old component matching flow\n\t\t\t\tconst matchMsg = 'Using component matching for data modification...';\n\t\t\t\tlogCollector?.info(matchMsg);\n\t\t\t\tconst matchResult = await this.matchComponent(userPrompt, components, apiKey, logCollector, conversationHistory);\n\n\t\t\t\treturn {\n\t\t\t\t\tcomponent: matchResult.component,\n\t\t\t\t\treasoning: matchResult.reasoning,\n\t\t\t\t\tmethod: 'classification-matched',\n\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\tneedsMultipleComponents: false,\n\t\t\t\t\tpropsModified: matchResult.propsModified,\n\t\t\t\t\tqueryModified: matchResult.queryModified\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\t// General questions - return empty\n\t\t\t\tlogCollector?.info('General question - no component needed');\n\t\t\t\treturn {\n\t\t\t\t\tcomponent: null,\n\t\t\t\t\treasoning: 'General question - no component needed',\n\t\t\t\t\tmethod: 'classification-general',\n\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\tneedsMultipleComponents: false\n\t\t\t\t};\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogCollector?.error(`Error handling user request: ${(error as Error).message}`);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Generate next questions that the user might ask based on the original prompt and generated component\n\t * This helps provide intelligent suggestions for follow-up queries\n\t */\n\tasync generateNextQuestions(\n\t\toriginalUserPrompt: string,\n\t\tcomponent: Component,\n\t\tcomponentData?: Record<string, unknown>,\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<string[]> {\n\t\ttry {\n\t\t\tconst component_info = `\n\t\t\t\tComponent Name: ${component.name}\n\t\t\t\tComponent Type: ${component.type}\n\t\t\t\tComponent Description: ${component.description || 'No description'}\n\t\t\t\tComponent Props: ${component.props ? JSON.stringify(component.props, null, 2) : 'No props'}\n\t\t\t`;\n\n\t\t\tconst component_data = componentData ? `Component Data: ${JSON.stringify(componentData, null, 2)}` : '';\n\n\t\t\tconst prompts = await promptLoader.loadPrompts('actions', {\n\t\t\t\tORIGINAL_USER_PROMPT: originalUserPrompt,\n\t\t\t\tCOMPONENT_INFO: component_info,\n\t\t\t\tCOMPONENT_DATA: component_data,\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 800,\n\t\t\t\t\ttemperature: 0.7,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\tconst nextQuestions = result.nextQuestions || [];\n\n\t\t\tlogCollector?.logExplanation(\n\t\t\t\t'Next questions generated',\n\t\t\t\t'Generated intelligent follow-up questions based on component',\n\t\t\t\t{\n\t\t\t\t\tcount: nextQuestions.length,\n\t\t\t\t\tquestions: nextQuestions\n\t\t\t\t}\n\t\t\t);\n\n\t\t\treturn nextQuestions;\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error generating next questions with ${this.getProviderName()}:`, error);\n\t\t\tlogCollector?.error(`Error generating next questions: ${(error as Error).message}`);\n\t\t\t// Return empty array on error instead of throwing\n\t\t\treturn [];\n\t\t}\n\t}\n}\n","import dotenv from 'dotenv';\nimport { BaseLLM, BaseLLMConfig } from './base-llm';\n\ndotenv.config();\n\nexport interface AnthropicLLMConfig extends BaseLLMConfig {}\n\n/**\n * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude\n */\nexport class AnthropicLLM extends BaseLLM {\n\tconstructor(config?: AnthropicLLMConfig) {\n\t\tsuper(config);\n\t}\n\n\tprotected getDefaultModel(): string {\n\t\treturn 'anthropic/claude-haiku-4-5-20251001';\n\t}\n\n\tprotected getDefaultApiKey(): string | undefined {\n\t\treturn process.env.ANTHROPIC_API_KEY;\n\t}\n\n\tprotected getProviderName(): string {\n\t\treturn 'Anthropic';\n\t}\n}\n\n// Export a singleton instance\nexport const anthropicLLM = new AnthropicLLM();\n","import { groqLLM } from \"./groq\";\nimport { anthropicLLM } from \"./anthropic\";\nimport { Component, LLMProvider } from \"../types\";\nimport dotenv from 'dotenv';\nimport { logger } from \"../utils/logger\";\n\ndotenv.config();\n\n\n\n/**\n * Parse LLM_PROVIDERS from environment variable\n * Expects a stringified JSON array like: '[\"anthropic\",\"groq\"]'\n */\nexport function getLLMProviders(): LLMProvider[] {\n const envProviders = process.env.LLM_PROVIDERS;\n\n const DEFAULT_PROVIDERS: LLMProvider[] = ['anthropic', 'groq'];\n if (!envProviders) {\n // Default to anthropic if not specified\n return DEFAULT_PROVIDERS;\n }\n\n try {\n const providers = JSON.parse(envProviders) as LLMProvider[];\n\n // Validate providers\n const validProviders = providers.filter(p => p === 'anthropic' || p === 'groq');\n\n if (validProviders.length === 0) {\n return DEFAULT_PROVIDERS;\n }\n\n return validProviders;\n } catch (error) {\n logger.error('Failed to parse LLM_PROVIDERS, defaulting to [\"anthropic\"]:', error);\n return DEFAULT_PROVIDERS;\n }\n}\n\n/**\n * Method 1: Use Anthropic Claude LLM\n */\nexport const useAnthropicMethod = async (prompt: string, components: Component[], apiKey?: string, logCollector?: any, conversationHistory?: string) => {\n const msg = 'Using Anthropic Claude matching method...';\n console.log(msg);\n logCollector?.info(msg);\n\n if (components.length === 0) {\n const emptyMsg = 'Components not loaded in memory. Please ensure components are fetched first.';\n logCollector?.error(emptyMsg);\n return { success: false, reason: emptyMsg };\n }\n\n try {\n const matchResult = await anthropicLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory);\n logger.debug(`Anthropic method success: ${matchResult}`);\n return { success: true, data: matchResult };\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n logCollector?.error(`Anthropic method failed: ${errorMsg}`);\n throw error; // Re-throw to be caught by the provider fallback mechanism\n }\n};\n\n/**\n * Method 2: Use Groq LLM\n */\nexport const useGroqMethod = async (prompt: string, components: Component[], apiKey?: string, logCollector?: any, conversationHistory?: string) => {\n const msg = 'Using Groq LLM matching method...';\n console.log(msg);\n logCollector?.info(msg);\n\n if (components.length === 0) {\n const emptyMsg = 'Components not loaded in memory. Please ensure components are fetched first.';\n logCollector?.error(emptyMsg);\n return { success: false, reason: emptyMsg };\n }\n\n try {\n const matchResult = await groqLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory);\n return { success: true, data: matchResult };\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n logCollector?.error(`Groq method failed: ${errorMsg}`);\n throw error; // Re-throw to be caught by the provider fallback mechanism\n }\n};\n\n//@to-do\nexport const getUserResponseFromCache = async (prompt: string) => {\n return false\n}\n\n/**\n * Get user response with automatic fallback between LLM providers\n * Tries providers in order specified by LLM_PROVIDERS or passed parameter\n */\nexport const get_user_response = async (\n prompt: string,\n components: Component[],\n anthropicApiKey?: string,\n groqApiKey?: string,\n llmProviders?: LLMProvider[],\n logCollector?: any,\n conversationHistory?: string\n) => {\n\n //first checking if he same prompt is already asked and we got successful response.\n const userResponse = await getUserResponseFromCache(prompt);\n if(userResponse){\n logCollector?.info('User response found in cache');\n return {\n success: true,\n data: userResponse\n };\n }\n\n const providers = llmProviders || getLLMProviders();\n const errors: { provider: LLMProvider; error: string }[] = [];\n\n const providerOrder = providers.join(', ');\n logCollector?.info(`LLM Provider order: [${providerOrder}]`);\n\n // Log conversation context info if available\n if (conversationHistory && conversationHistory.length > 0) {\n logCollector?.info(`Using conversation history with ${conversationHistory.split('\\n').filter((l: string) => l.startsWith('Q')).length} previous exchanges`);\n }\n\n for (let i = 0; i < providers.length; i++) {\n const provider = providers[i];\n const isLastProvider = i === providers.length - 1;\n\n try {\n const attemptMsg = `Attempting provider: ${provider} (${i + 1}/${providers.length})`;\n logCollector?.info(attemptMsg);\n\n let result;\n if (provider === 'anthropic') {\n result = await useAnthropicMethod(prompt, components, anthropicApiKey, logCollector, conversationHistory);\n logger.debug('Anthropic result:', result);\n } else if (provider === 'groq') {\n result = await useGroqMethod(prompt, components, groqApiKey, logCollector, conversationHistory);\n } else {\n continue; // Skip unknown providers\n }\n\n if (result.success) {\n const successMsg = `Success with provider: ${provider}`;\n logCollector?.info(successMsg);\n return result;\n } else {\n errors.push({ provider, error: result.reason || 'Unknown error' });\n const warnMsg = `Provider ${provider} returned unsuccessful result: ${result.reason}`;\n logCollector?.warn(warnMsg);\n }\n } catch (error) {\n const errorMessage = (error as Error).message;\n errors.push({ provider, error: errorMessage });\n\n const errorMsg = `Provider ${provider} failed: ${errorMessage}`;\n logCollector?.error(errorMsg);\n\n // If this is not the last provider, try the next one\n if (!isLastProvider) {\n const fallbackMsg = 'Falling back to next provider...';\n logCollector?.info(fallbackMsg);\n continue;\n }\n }\n }\n\n // All providers failed\n const errorSummary = errors\n .map(e => `${e.provider}: ${e.error}`)\n .join('; ');\n\n const failureMsg = `All LLM providers failed. Errors: ${errorSummary}`;\n logCollector?.error(failureMsg);\n\n return {\n success: false,\n reason: failureMsg\n };\n}","import { Message } from '../types';\n\nexport interface CapturedLog {\n timestamp: number;\n level: 'info' | 'error' | 'warn' | 'debug';\n message: string;\n type?: 'explanation' | 'query' | 'general';\n data?: Record<string, any>;\n}\n\n/**\n * UILogCollector captures logs during user prompt processing\n * and sends them to runtime via ui_logs message with uiBlockId as the message id\n * Logs are sent in real-time for streaming effect in the UI\n */\nexport class UILogCollector {\n private logs: CapturedLog[] = [];\n private uiBlockId: string | null;\n private clientId: string;\n private sendMessage: (message: Message) => void;\n\n constructor(\n clientId: string,\n sendMessage: (message: Message) => void,\n uiBlockId?: string\n ) {\n this.uiBlockId = uiBlockId || null;\n this.clientId = clientId;\n this.sendMessage = sendMessage;\n }\n\n /**\n * Check if logging is enabled (uiBlockId is provided)\n */\n isEnabled(): boolean {\n return this.uiBlockId !== null;\n }\n\n /**\n * Add a log entry with timestamp and immediately send to runtime\n */\n private addLog(\n level: 'info' | 'error' | 'warn' | 'debug',\n message: string,\n type?: 'explanation' | 'query' | 'general',\n data?: Record<string, any>\n ): void {\n const log: CapturedLog = {\n timestamp: Date.now(),\n level,\n message,\n ...(type && { type }),\n ...(data && { data }),\n };\n\n this.logs.push(log);\n\n // Send the log immediately to runtime for streaming effect\n this.sendLogImmediately(log);\n }\n\n /**\n * Send a single log to runtime immediately\n */\n private sendLogImmediately(log: CapturedLog): void {\n if (!this.isEnabled()) {\n return;\n }\n\n const response: Message = {\n id: this.uiBlockId!,\n type: 'UI_LOGS',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: this.clientId,\n },\n payload: {\n logs: [log], // Send single log in array\n },\n };\n\n this.sendMessage(response);\n }\n\n /**\n * Log info message\n */\n info(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('info', message, type, data);\n }\n }\n\n /**\n * Log error message\n */\n error(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('error', message, type, data);\n }\n }\n\n /**\n * Log warning message\n */\n warn(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('warn', message, type, data);\n }\n }\n\n /**\n * Log debug message\n */\n debug(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('debug', message, type, data);\n }\n }\n\n /**\n * Log LLM explanation with typed metadata\n */\n logExplanation(message: string, explanation: string, data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('info', message, 'explanation', {\n explanation,\n ...data,\n });\n }\n }\n\n /**\n * Log generated query with typed metadata\n */\n logQuery(message: string, query: string, data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('info', message, 'query', {\n query,\n ...data,\n });\n }\n }\n\n /**\n * Send all collected logs at once (optional, for final summary)\n */\n sendAllLogs(): void {\n if (!this.isEnabled() || this.logs.length === 0) {\n return;\n }\n\n const response: Message = {\n id: this.uiBlockId!,\n type: 'UI_LOGS',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: this.clientId,\n },\n payload: {\n logs: this.logs,\n },\n };\n\n this.sendMessage(response);\n }\n\n /**\n * Get all collected logs\n */\n getLogs(): CapturedLog[] {\n return [...this.logs];\n }\n\n /**\n * Clear all logs\n */\n clearLogs(): void {\n this.logs = [];\n }\n\n /**\n * Set uiBlockId (in case it's provided later)\n */\n setUIBlockId(uiBlockId: string): void {\n this.uiBlockId = uiBlockId;\n }\n}\n","/**\n * Configuration for conversation context and history management\n */\nexport const CONTEXT_CONFIG = {\n /**\n * Maximum number of previous UIBlocks to include as conversation context\n * Set to 0 to disable conversation history\n * Higher values provide more context but may increase token usage\n */\n MAX_CONVERSATION_CONTEXT_BLOCKS: 2,\n};\n","import { Component, LLMProvider, Message, UserPromptRequestMessageSchema } from \"../types\";\nimport { get_user_response } from \"../userResponse\";\nimport { logger } from \"../utils/logger\";\nimport { UILogCollector } from \"../utils/log-collector\";\nimport { ThreadManager, UIBlock } from \"../threads\";\nimport { CONTEXT_CONFIG } from \"../config/context\";\n\n// Track processed message IDs to prevent duplicates\nconst processedMessageIds = new Set<string>();\n\nexport async function handleUserPromptRequest(\n\tdata: any,\n\tcomponents: Component[],\n\tsendMessage: (message: Message) => void,\n\tanthropicApiKey?: string,\n\tgroqApiKey?: string,\n\tllmProviders?: LLMProvider[]\n): Promise<void> {\n\ttry {\n\t\tconst userPromptRequest = UserPromptRequestMessageSchema.parse(data);\n\t\tconst { id, payload } = userPromptRequest;\n\n\t\tconst prompt = payload.prompt;\n\t\tconst SA_RUNTIME = payload.SA_RUNTIME;\n\n\t\tconst wsId = userPromptRequest.from.id || 'unknown';\n\n\t\tlogger.info(`[REQUEST ${id}] Processing user prompt: \"${prompt.substring(0, 50)}...\"`);\n\t\tlogger.info(`[REQUEST ${id}] Providers: ${llmProviders?.join(', ')}, Anthropic key: ${anthropicApiKey ? 'SET' : 'NOT SET'}, Groq key: ${groqApiKey ? 'SET' : 'NOT SET'}`);\n\n\t\t// Check if this message ID has already been processed\n\t\tif (processedMessageIds.has(id)) {\n\t\t\tlogger.warn(`[REQUEST ${id}] Duplicate request detected - ignoring`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Mark this message ID as processed\n\t\tprocessedMessageIds.add(id);\n\n\t\t// Clean up old message IDs (keep only last 100)\n\t\tif (processedMessageIds.size > 100) {\n\t\t\tconst firstId = processedMessageIds.values().next().value;\n\t\t\tif (firstId) {\n\t\t\t\tprocessedMessageIds.delete(firstId);\n\t\t\t}\n\t\t}\n\n\t\t// Validate SA_RUNTIME and extract threadId and uiBlockId\n\t\tif (!SA_RUNTIME) {\n\t\t\tsendDataResponse(id, {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'SA_RUNTIME is required'\n\t\t\t}, sendMessage, wsId);\n\t\t\treturn;\n\t\t}\n\n\t\tconst threadId = SA_RUNTIME.threadId;\n\t\tconst existingUiBlockId = SA_RUNTIME.uiBlockId;\n\n\t\tif (!threadId) {\n\t\t\tsendDataResponse(id, {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'threadId in SA_RUNTIME is required'\n\t\t\t}, sendMessage, wsId);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!existingUiBlockId) {\n\t\t\tsendDataResponse(id, {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'uiBlockId in SA_RUNTIME is required'\n\t\t\t}, sendMessage, wsId);\n\t\t\treturn;\n\t\t}\n\n\t\t// Create log collector with uiBlockId\n\t\tconst logCollector = new UILogCollector(wsId, sendMessage, existingUiBlockId);\n\n\t\tif (!prompt) {\n\t\t\tsendDataResponse(id, {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Prompt not found'\n\t\t\t}, sendMessage, wsId);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!components || components.length === 0) {\n\t\t\tsendDataResponse(id, {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Components not found'\n\t\t\t}, sendMessage, wsId);\n\t\t\treturn;\n\t\t}\n\n\t\tlogCollector.info(`Starting user prompt request with ${components.length} components`);\n\t\tlogger.info(`components length: ${components.length}`);\n\n\t\t// Get or create thread BEFORE processing to enable conversation context\n\t\tconst threadManager = ThreadManager.getInstance();\n\t\tlet thread = threadManager.getThread(threadId);\n\t\tif (!thread) {\n\t\t\tthread = threadManager.createThread(threadId);\n\t\t\tlogger.info(`Created new thread: ${threadId}`);\n\t\t}\n\n\t\t// Extract conversation context from thread (excluding current UIBlock)\n\t\tconst conversationHistory = thread.getConversationContext(CONTEXT_CONFIG.MAX_CONVERSATION_CONTEXT_BLOCKS, existingUiBlockId);\n\n\t\t// Get user response with log collector and conversation context\n\t\tconst userResponse = await get_user_response(prompt, components, anthropicApiKey, groqApiKey, llmProviders, logCollector, conversationHistory);\n\n\t\t// Log completion (sent immediately if uiBlockId was provided)\n\t\tlogCollector.info('User prompt request completed');\n\t\tlogger.info(`[REQUEST ${id}] Response success: ${userResponse.success}, reason: ${userResponse.success ? 'N/A' : userResponse}`);\n\n\t\t// If response is successful, create UIBlock and add to Thread\n\t\tif (userResponse.success && userResponse.data && typeof userResponse.data === 'object' && 'component' in userResponse.data) {\n\t\t\tconst component = (userResponse.data as any).component;\n\n\t\t\t// Use the uiBlockId from SA_RUNTIME (already validated)\n\t\t\tconst uiBlockId = existingUiBlockId;\n\n\t\t\t// Create UIBlock with component metadata and empty component data (will fill later)\n\t\t\tconst uiBlock = new UIBlock(\n\t\t\t\tprompt,\n\t\t\t\t{}, // componentData: initially empty, will be filled later\n\t\t\t\tcomponent || {}, // generatedComponentMetadata: full component object (ComponentSchema)\n\t\t\t\t[], // actions: empty initially\n\t\t\t\tuiBlockId\n\t\t\t);\n\n\t\t\t// Add UIBlock to Thread\n\t\t\tthread.addUIBlock(uiBlock);\n\n\t\t\tlogger.info(`Created UIBlock: ${uiBlockId} in Thread: ${threadId}`);\n\n\t\t\t// Send response with uiBlockId and threadId\n\t\t\tsendDataResponse(id, {\n\t\t\t\t...userResponse,\n\t\t\t\tuiBlockId,\n\t\t\t\tthreadId\n\t\t\t}, sendMessage, wsId);\n\t\t} else {\n\t\t\t// If response failed, still send it but without UIBlock/Thread data\n\t\t\tsendDataResponse(id, userResponse, sendMessage, wsId);\n\t\t}\n\n\t\treturn;\n\t}\n\tcatch (error) {\n\t\tlogger.error('Failed to handle user prompt request:', error);\n\t}\n}\n\n/**\n * Send a data_res response message\n */\nfunction sendDataResponse(\n\tid: string,\n\tres: { success: boolean; error?: string; data?: any; uiBlockId?: string; threadId?: string },\n\tsendMessage: (message: Message) => void,\n\tclientId?: string,\n): void {\n\tconst response: Message = {\n\t\tid,\n\t\ttype: 'USER_PROMPT_RES',\n\t\tfrom: { type: 'data-agent' },\n\t\tto: {\n\t\t\ttype: 'runtime',\n\t\t\tid: clientId\n\t\t},\n\t\tpayload: {\n\t\t\t...res,\n\t\t}\n\t};\n\n\tlogger.info(`[REQUEST ${id}] Sending USER_PROMPT_RES with success=${res.success}`);\n\tif (!res.success && (res as any).reason) {\n\t\tlogger.info(`[REQUEST ${id}] Error reason: ${(res as any).reason}`);\n\t}\n\tsendMessage(response);\n} ","import { Component, Message, UserPromptSuggestionsMessageSchema } from '../types';\nimport { logger } from '../utils/logger';\n\n/**\n * Handle user prompt suggestions request\n * Searches components based on prompt keywords and returns top matches\n */\nexport async function handleUserPromptSuggestions(\n data: any,\n components: Component[],\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const request = UserPromptSuggestionsMessageSchema.parse(data);\n const { id, payload, from } = request;\n\n const { prompt, limit = 5 } = payload;\n const wsId = from.id;\n\n // Validate input\n if (!prompt || prompt.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Prompt is required and cannot be empty'\n }, sendMessage, wsId);\n return;\n }\n\n if (!components || components.length === 0) {\n sendResponse(id, {\n success: true,\n data: {\n prompt,\n suggestions: [],\n count: 0,\n message: 'No components available'\n }\n }, sendMessage, wsId);\n return;\n }\n\n // Search components based on prompt\n const suggestions = searchComponents(prompt, components, limit);\n\n\n sendResponse(id, {\n success: true,\n data: {\n prompt,\n suggestions,\n count: suggestions.length,\n message: `Found ${suggestions.length} matching components`\n }\n }, sendMessage, wsId);\n\n } catch (error) {\n logger.error('Failed to handle user prompt suggestions request:', error);\n sendResponse(null, {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n }, sendMessage);\n }\n}\n\n/**\n * Search components based on prompt keywords\n * Searches in component name, description, keywords, and category\n * @param prompt - Search prompt\n * @param components - List of components to search in\n * @param limit - Maximum number of results to return\n * @returns Matching components sorted by relevance\n */\nfunction searchComponents(prompt: string, components: Component[], limit: number): Component[] {\n const promptLower = prompt.toLowerCase();\n const promptTokens = promptLower.split(/\\s+/).filter(token => token.length > 0);\n\n // Score each component based on keyword matches\n const scoredComponents = components.map(component => {\n let score = 0;\n\n const componentName = component.name.toLowerCase();\n const componentDesc = component.description.toLowerCase();\n const componentKeywords = (component.keywords || []).map(k => k.toLowerCase());\n const componentCategory = (component.category || '').toLowerCase();\n\n // Search in each field with different weights\n for (const token of promptTokens) {\n // Exact name match (highest weight)\n if (componentName === token) {\n score += 10;\n }\n // Name contains token\n else if (componentName.includes(token)) {\n score += 5;\n }\n\n // Exact keyword match\n if (componentKeywords.includes(token)) {\n score += 8;\n }\n // Keywords contain token\n else if (componentKeywords.some(k => k.includes(token))) {\n score += 4;\n }\n\n // Description contains token\n if (componentDesc.includes(token)) {\n score += 2;\n }\n\n // Category contains token\n if (componentCategory.includes(token)) {\n score += 3;\n }\n }\n\n return { component, score };\n });\n\n // Filter out components with score 0, sort by score (descending), and take top results\n return scoredComponents\n .filter(({ score }) => score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map(({ component }) => component);\n}\n\n/**\n * Send user prompt suggestions response\n */\nfunction sendResponse(\n id: string | null,\n res: { success: boolean; error?: string; data?: any },\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id: id || 'unknown',\n type: 'USER_PROMPT_SUGGESTIONS_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: clientId\n },\n payload: {\n ...res,\n }\n };\n\n sendMessage(response);\n}\n","import { anthropicLLM } from './anthropic';\nimport { groqLLM } from './groq';\nimport { LLMProvider, Component } from '../types';\nimport { logger } from '../utils/logger';\n\n/**\n * Generate next questions based on the original user prompt and generated component\n * Routes to the appropriate LLM provider (Anthropic or Groq)\n * Falls back to next provider if current provider fails or returns empty results\n */\nexport async function generateNextQuestions(\n\toriginalUserPrompt: string,\n\tcomponent: Component,\n\tcomponentData?: Record<string, unknown>,\n\tanthropicApiKey?: string,\n\tgroqApiKey?: string,\n\tllmProviders?: LLMProvider[],\n\tlogCollector?: any,\n\tconversationHistory?: string\n): Promise<string[]> {\n\ttry {\n\t\t// Determine which providers to use\n\t\tconst providers = llmProviders || ['anthropic'];\n\n\t\t// Try each provider in order\n\t\tfor (const provider of providers) {\n\t\t\ttry {\n\t\t\t\tlogger.info(`Generating next questions using provider: ${provider}`);\n\n\t\t\t\tlet result: string[] = [];\n\n\t\t\t\tif (provider === 'groq') {\n\t\t\t\t\tresult = await groqLLM.generateNextQuestions(\n\t\t\t\t\t\toriginalUserPrompt,\n\t\t\t\t\t\tcomponent,\n\t\t\t\t\t\tcomponentData,\n\t\t\t\t\t\tgroqApiKey,\n\t\t\t\t\t\tlogCollector,\n\t\t\t\t\t\tconversationHistory\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\t// Default to Anthropic\n\t\t\t\t\tresult = await anthropicLLM.generateNextQuestions(\n\t\t\t\t\t\toriginalUserPrompt,\n\t\t\t\t\t\tcomponent,\n\t\t\t\t\t\tcomponentData,\n\t\t\t\t\t\tanthropicApiKey,\n\t\t\t\t\t\tlogCollector,\n\t\t\t\t\t\tconversationHistory\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// If we got results, return them\n\t\t\t\tif (result && result.length > 0) {\n\t\t\t\t\tlogger.info(`Successfully generated ${result.length} questions with ${provider}`);\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tlogger.warn(`No questions generated from ${provider}, trying next provider...`);\n\t\t\t} catch (providerError) {\n\t\t\t\tlogger.warn(`Provider ${provider} failed:`, providerError);\n\t\t\t\tlogCollector?.warn(`Provider ${provider} failed, trying next provider...`);\n\t\t\t\t// Continue to next provider\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// All providers failed or returned empty results\n\t\tlogger.warn('All providers failed or returned no questions');\n\t\treturn [];\n\t} catch (error) {\n\t\tlogger.error('Error generating next questions:', error);\n\t\tlogCollector?.error(`Error generating next questions: ${(error as Error).message}`);\n\t\t// Return empty array on error\n\t\treturn [];\n\t}\n}\n","import { ActionsRequestMessageSchema, type LLMProvider, type Message } from '../types';\nimport { generateNextQuestions } from '../userResponse/next-questions';\nimport { logger } from '../utils/logger';\nimport { UILogCollector } from '../utils/log-collector';\nimport { ThreadManager } from '../threads';\nimport { CONTEXT_CONFIG } from '../config/context';\n\n/**\n * Handle incoming actions messages from runtime\n * Generates suggested next questions based on the original user prompt and generated component\n */\nexport async function handleActionsRequest(\n data: any,\n sendMessage: (message: Message) => void,\n anthropicApiKey?: string,\n groqApiKey?: string,\n llmProviders?: LLMProvider[]\n): Promise<void> {\n try {\n const actionsRequest = ActionsRequestMessageSchema.parse(data);\n const { id, payload } = actionsRequest;\n const { SA_RUNTIME } = payload;\n\n const wsId = actionsRequest.from.id || 'unknown';\n\n // SA_RUNTIME is required to fetch actions from UIBlock\n if (!SA_RUNTIME) {\n sendResponse(id, {\n success: false,\n error: 'SA_RUNTIME with threadId and uiBlockId is required'\n }, sendMessage, wsId);\n return;\n }\n\n const uiBlockId = SA_RUNTIME.uiBlockId;\n const threadId = SA_RUNTIME.threadId;\n\n // Get UIBlock from ThreadManager\n const threadManager = ThreadManager.getInstance();\n const thread = threadManager.getThread(threadId);\n\n if (!thread) {\n sendResponse(id, {\n success: false,\n error: `Thread '${threadId}' not found`\n }, sendMessage, wsId);\n return;\n }\n\n const uiBlock = thread.getUIBlock(uiBlockId);\n if (!uiBlock) {\n sendResponse(id, {\n success: false,\n error: `UIBlock '${uiBlockId}' not found in thread '${threadId}'`\n }, sendMessage, wsId);\n return;\n }\n\n // Create log collector with uiBlockId\n const logCollector = new UILogCollector(wsId, sendMessage, uiBlockId);\n\n // Extract data from UIBlock\n const userQuestion = uiBlock.getUserQuestion();\n const component = uiBlock.getComponentMetadata();\n const componentData = uiBlock.getComponentData();\n\n // Extract conversation context from thread (excluding current UIBlock)\n const conversationHistory = thread.getConversationContext(CONTEXT_CONFIG.MAX_CONVERSATION_CONTEXT_BLOCKS, uiBlockId);\n\n logCollector.info(`Generating actions for UIBlock: ${uiBlockId}`);\n logger.info(`Generating actions for component: ${component?.name || 'unknown'}`);\n\n // Use getOrFetchActions to manage action state\n const actions = await uiBlock.getOrFetchActions(async () => {\n // Generate next questions using extracted data from UIBlock and conversation history\n const nextQuestions = await generateNextQuestions(\n userQuestion,\n component as any,\n componentData,\n anthropicApiKey,\n groqApiKey,\n llmProviders,\n logCollector,\n conversationHistory\n );\n\n // Convert questions to actions format\n return nextQuestions.map((question: string, index: number) => ({\n id: `action_${index}_${Date.now()}`,\n name: question,\n type: 'next_question',\n question\n }));\n });\n\n logCollector.info(`Generated ${actions.length} actions successfully`);\n\n sendResponse(id, {\n success: true,\n data: {\n actions,\n componentName: component?.name,\n componentId: component?.id,\n uiBlockId,\n threadId\n }\n }, sendMessage, wsId);\n\n } catch (error) {\n logger.error('Failed to handle actions request:', error);\n sendResponse(null, {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n }, sendMessage);\n }\n}\n\n/**\n * Send actions response\n */\nfunction sendResponse(\n id: string | null,\n res: { success: boolean; error?: string; data?: any },\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id: id || 'unknown',\n type: 'ACTIONS_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: clientId\n },\n payload: {\n ...res,\n }\n };\n\n sendMessage(response);\n}\n","import { Component, ComponentListResponseMessageSchema, ComponentSchema, ComponentsSchema, Message } from \"../types\";\nimport { logger } from \"../utils/logger\";\n\n\nexport async function handleComponentListResponse(\n data: any,\n storeComponents:(components: Component[])=>void\n ): Promise<void> {\n try {\n const componentListResponse = ComponentListResponseMessageSchema.parse(data);\n const { id, payload } = componentListResponse;\n \n const componentsList = payload.components;\n\n if(!componentsList){\n logger.error('Components list not found in the response');\n return;\n }\n\n const components = ComponentsSchema.parse(componentsList);\n storeComponents(components);\n\n return;\n } catch (error) {\n logger.error('Failed to handle user prompt request:', error);\n }\n } \n\n\n","import { UsersRequestMessageSchema, Message } from '../types';\nimport { getUserManager } from '../auth/user-storage';\nimport { logger } from '../utils/logger';\n\n/**\n * Handle unified users management request\n * Supports operations: create, update, delete, getAll, getOne\n * Only accepts requests from 'admin' type\n */\nexport async function handleUsersRequest(\n data: any,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const request = UsersRequestMessageSchema.parse(data);\n const { id, payload, from } = request;\n const { operation, data: requestData } = payload;\n const username = requestData?.username;\n const password = requestData?.password;\n\n // Verify request is from admin\n if (from.type !== 'admin') {\n sendResponse(id, {\n success: false,\n error: 'Unauthorized: Only admin can manage users'\n }, sendMessage, from.id);\n logger.warn(`Unauthorized user management attempt from: ${from.type}`);\n return;\n }\n\n const userManager = getUserManager();\n\n // Route to appropriate operation handler\n switch (operation) {\n case 'create':\n await handleCreate(id, username, password, userManager, sendMessage, from.id);\n break;\n\n case 'update':\n await handleUpdate(id, username, password, userManager, sendMessage, from.id);\n break;\n\n case 'delete':\n await handleDelete(id, username, userManager, sendMessage, from.id);\n break;\n\n case 'getAll':\n await handleGetAll(id, userManager, sendMessage, from.id);\n break;\n\n case 'getOne':\n await handleGetOne(id, username, userManager, sendMessage, from.id);\n break;\n\n default:\n sendResponse(id, {\n success: false,\n error: `Unknown operation: ${operation}`\n }, sendMessage, from.id);\n }\n\n } catch (error) {\n logger.error('Failed to handle users request:', error);\n sendResponse(null, {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n }, sendMessage);\n }\n}\n\n/**\n * Handle create user operation\n */\nasync function handleCreate(\n id: string,\n username: string | undefined,\n password: string | undefined,\n userManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!username || username.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Username is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n if (!password || password.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Password is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n // Check if user already exists\n if (userManager.userExists(username)) {\n sendResponse(id, {\n success: false,\n error: `User '${username}' already exists`\n }, sendMessage, clientId);\n return;\n }\n\n let wsIds: string[] = [];\n if (clientId) {\n wsIds.push(clientId);\n }\n\n // Create user\n const newUser = userManager.createUser({\n username,\n password: password,\n wsIds\n });\n\n logger.info(`User created by admin: ${username}`);\n\n sendResponse(id, {\n success: true,\n data: {\n username: newUser.username,\n message: `User '${username}' created successfully`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle update user operation\n */\nasync function handleUpdate(\n id: string,\n username: string | undefined,\n password: string | undefined,\n userManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!username || username.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Username is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n // Check if user exists\n if (!userManager.userExists(username)) {\n sendResponse(id, {\n success: false,\n error: `User '${username}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n // Build update object\n const updates: any = {};\n\n // Only update password if provided\n if (password && password.trim().length > 0) {\n updates.password = password;\n }\n\n // If nothing to update, return error\n if (Object.keys(updates).length === 0) {\n sendResponse(id, {\n success: false,\n error: 'No fields to update. Please provide password or other valid fields.'\n }, sendMessage, clientId);\n return;\n }\n\n // Update user\n const updatedUser = userManager.updateUser(username, updates);\n\n logger.info(`User updated by admin: ${username}`);\n\n sendResponse(id, {\n success: true,\n data: {\n username: updatedUser.username,\n message: `User '${username}' updated successfully`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle delete user operation\n */\nasync function handleDelete(\n id: string,\n username: string | undefined,\n userManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!username || username.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Username is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n // Check if user exists\n if (!userManager.userExists(username)) {\n sendResponse(id, {\n success: false,\n error: `User '${username}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n // Delete user\n const deleted = userManager.deleteUser(username);\n\n if (!deleted) {\n sendResponse(id, {\n success: false,\n error: `Failed to delete user '${username}'`\n }, sendMessage, clientId);\n return;\n }\n\n logger.info(`User deleted by admin: ${username}`);\n\n sendResponse(id, {\n success: true,\n data: {\n username: username,\n message: `User '${username}' deleted successfully`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get all users operation\n */\nasync function handleGetAll(\n id: string,\n userManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n const users = userManager.getAllUsers();\n\n // Remove sensitive information like passwords\n const sanitizedUsers = users.map((user: any) => ({\n username: user.username,\n wsIds: user.wsIds || []\n }));\n\n logger.info(`Admin retrieved all users (count: ${sanitizedUsers.length})`);\n\n sendResponse(id, {\n success: true,\n data: {\n users: sanitizedUsers,\n count: sanitizedUsers.length,\n message: `Retrieved ${sanitizedUsers.length} users`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get one user operation\n */\nasync function handleGetOne(\n id: string,\n username: string | undefined,\n userManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!username || username.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Username is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n // Check if user exists\n if (!userManager.userExists(username)) {\n sendResponse(id, {\n success: false,\n error: `User '${username}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n const user = userManager.getUser(username);\n\n // Remove sensitive information\n const sanitizedUser = {\n username: user.username,\n wsIds: user.wsIds || []\n };\n\n logger.info(`Admin retrieved user: ${username}`);\n\n sendResponse(id, {\n success: true,\n data: {\n user: sanitizedUser,\n message: `Retrieved user '${username}'`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Send users response\n */\nfunction sendResponse(\n id: string | null,\n res: { success: boolean; error?: string; data?: any },\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id: id || 'unknown',\n type: 'USERS_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'admin',\n id: clientId\n },\n payload: {\n ...res,\n }\n };\n\n sendMessage(response);\n}\n","import { DashboardManager } from './dashboard-manager';\nimport { logger } from '../utils/logger';\n\nlet dashboardManager: DashboardManager | null = null;\n\n/**\n * Set the dashboard manager instance\n * @param manager - DashboardManager instance to use\n */\nexport function setDashboardManager(manager: DashboardManager): void {\n dashboardManager = manager;\n logger.info('DashboardManager instance set');\n}\n\n/**\n * Get the dashboard manager instance\n * @throws Error if dashboard manager is not initialized\n * @returns DashboardManager instance\n */\nexport function getDashboardManager(): DashboardManager {\n if (!dashboardManager) {\n throw new Error('DashboardManager not initialized. Call setDashboardManager first.');\n }\n return dashboardManager;\n}\n","import { DashboardsRequestMessageSchema, Message } from '../types';\nimport { getDashboardManager } from '../dashboards/dashboard-storage';\nimport { logger } from '../utils/logger';\n\n/**\n * Handle unified dashboards management request\n * Supports operations: create, update, delete, getAll, getOne\n * Only accepts requests from 'admin' type\n */\nexport async function handleDashboardsRequest(\n data: any,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const request = DashboardsRequestMessageSchema.parse(data);\n const { id, payload, from } = request;\n const { operation, data: requestData } = payload;\n const dashboardId = requestData?.dashboardId;\n const dashboard = requestData?.dashboard;\n\n // Verify request is from admin\n if (from.type !== 'admin') {\n sendResponse(id, {\n success: false,\n error: 'Unauthorized: Only admin can manage dashboards'\n }, sendMessage, from.id);\n logger.warn(`Unauthorized dashboard management attempt from: ${from.type}`);\n return;\n }\n\n const dashboardManager = getDashboardManager();\n\n // Route to appropriate operation handler\n switch (operation) {\n case 'create':\n await handleCreate(id, dashboardId, dashboard, dashboardManager, sendMessage, from.id);\n break;\n\n case 'update':\n await handleUpdate(id, dashboardId, dashboard, dashboardManager, sendMessage, from.id);\n break;\n\n case 'delete':\n await handleDelete(id, dashboardId, dashboardManager, sendMessage, from.id);\n break;\n\n case 'getAll':\n await handleGetAll(id, dashboardManager, sendMessage, from.id);\n break;\n\n case 'getOne':\n await handleGetOne(id, dashboardId, dashboardManager, sendMessage, from.id);\n break;\n\n default:\n sendResponse(id, {\n success: false,\n error: `Unknown operation: ${operation}`\n }, sendMessage, from.id);\n }\n\n } catch (error) {\n logger.error('Failed to handle dashboards request:', error);\n sendResponse(null, {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n }, sendMessage);\n }\n}\n\n/**\n * Handle create dashboard operation\n */\nasync function handleCreate(\n id: string,\n dashboardId: string | undefined,\n dashboard: any,\n dashboardManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!dashboardId || dashboardId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n if (!dashboard) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard data is required'\n }, sendMessage, clientId);\n return;\n }\n\n try {\n const createdDashboard = dashboardManager.createDashboard(dashboardId, dashboard);\n\n sendResponse(id, {\n success: true,\n data: {\n dashboardId,\n dashboard: createdDashboard,\n message: `Dashboard '${dashboardId}' created successfully`\n }\n }, sendMessage, clientId);\n } catch (error) {\n sendResponse(id, {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create dashboard'\n }, sendMessage, clientId);\n }\n}\n\n/**\n * Handle update dashboard operation\n */\nasync function handleUpdate(\n id: string,\n dashboardId: string | undefined,\n dashboard: any,\n dashboardManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!dashboardId || dashboardId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n if (!dashboard) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard data is required'\n }, sendMessage, clientId);\n return;\n }\n\n try {\n const updatedDashboard = dashboardManager.updateDashboard(dashboardId, dashboard);\n\n if (!updatedDashboard) {\n sendResponse(id, {\n success: false,\n error: `Dashboard '${dashboardId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n sendResponse(id, {\n success: true,\n data: {\n dashboardId,\n dashboard: updatedDashboard,\n message: `Dashboard '${dashboardId}' updated successfully`\n }\n }, sendMessage, clientId);\n } catch (error) {\n sendResponse(id, {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to update dashboard'\n }, sendMessage, clientId);\n }\n}\n\n/**\n * Handle delete dashboard operation\n */\nasync function handleDelete(\n id: string,\n dashboardId: string | undefined,\n dashboardManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!dashboardId || dashboardId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n const deleted = dashboardManager.deleteDashboard(dashboardId);\n\n if (!deleted) {\n sendResponse(id, {\n success: false,\n error: `Dashboard '${dashboardId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n sendResponse(id, {\n success: true,\n data: {\n dashboardId,\n message: `Dashboard '${dashboardId}' deleted successfully`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get all dashboards operation\n */\nasync function handleGetAll(\n id: string,\n dashboardManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n const dashboards = dashboardManager.getAllDashboards();\n\n logger.info(`Admin retrieved all dashboards (count: ${dashboards.length})`);\n\n sendResponse(id, {\n success: true,\n data: {\n dashboards,\n count: dashboards.length,\n message: `Retrieved ${dashboards.length} dashboards`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get one dashboard operation\n */\nasync function handleGetOne(\n id: string,\n dashboardId: string | undefined,\n dashboardManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!dashboardId || dashboardId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n const dashboard = dashboardManager.getDashboard(dashboardId);\n\n if (!dashboard) {\n sendResponse(id, {\n success: false,\n error: `Dashboard '${dashboardId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n logger.info(`Admin retrieved dashboard: ${dashboardId}`);\n\n sendResponse(id, {\n success: true,\n data: {\n dashboardId,\n dashboard,\n message: `Retrieved dashboard '${dashboardId}'`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Send dashboards response\n */\nfunction sendResponse(\n id: string | null,\n res: { success: boolean; error?: string; data?: any },\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id: id || 'unknown',\n type: 'DASHBOARDS_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'admin',\n id: clientId\n },\n payload: {\n ...res,\n }\n };\n\n sendMessage(response);\n}\n","import { ReportManager } from './report-manager';\n\n/**\n * Global report manager instance\n */\nlet reportManager: ReportManager | null = null;\n\n/**\n * Get the global report manager instance\n * @returns ReportManager instance\n * @throws Error if report manager is not initialized\n */\nexport function getReportManager(): ReportManager {\n if (!reportManager) {\n throw new Error('Report manager not initialized. Call setReportManager first.');\n }\n return reportManager;\n}\n\n/**\n * Set the global report manager instance\n * @param manager - ReportManager instance to set\n */\nexport function setReportManager(manager: ReportManager): void {\n reportManager = manager;\n}\n","import { ReportsRequestMessageSchema, Message } from '../types';\nimport { getReportManager } from '../reports/report-storage';\nimport { logger } from '../utils/logger';\n\n/**\n * Handle unified reports management request\n * Supports operations: create, update, delete, getAll, getOne\n * Only accepts requests from 'admin' type\n */\nexport async function handleReportsRequest(\n data: any,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const request = ReportsRequestMessageSchema.parse(data);\n const { id, payload, from } = request;\n const { operation, data: requestData } = payload;\n const reportId = requestData?.reportId;\n const report = requestData?.report;\n\n // Verify request is from admin\n if (from.type !== 'admin') {\n sendResponse(id, {\n success: false,\n error: 'Unauthorized: Only admin can manage reports'\n }, sendMessage, from.id);\n logger.warn(`Unauthorized report management attempt from: ${from.type}`);\n return;\n }\n\n const reportManager = getReportManager();\n\n // Route to appropriate operation handler\n switch (operation) {\n case 'create':\n await handleCreate(id, reportId, report, reportManager, sendMessage, from.id);\n break;\n\n case 'update':\n await handleUpdate(id, reportId, report, reportManager, sendMessage, from.id);\n break;\n\n case 'delete':\n await handleDelete(id, reportId, reportManager, sendMessage, from.id);\n break;\n\n case 'getAll':\n await handleGetAll(id, reportManager, sendMessage, from.id);\n break;\n\n case 'getOne':\n await handleGetOne(id, reportId, reportManager, sendMessage, from.id);\n break;\n\n default:\n sendResponse(id, {\n success: false,\n error: `Unknown operation: ${operation}`\n }, sendMessage, from.id);\n }\n\n } catch (error) {\n logger.error('Failed to handle reports request:', error);\n sendResponse(null, {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n }, sendMessage);\n }\n}\n\n/**\n * Handle create report operation\n */\nasync function handleCreate(\n id: string,\n reportId: string | undefined,\n report: any,\n reportManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!reportId || reportId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Report ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n if (!report) {\n sendResponse(id, {\n success: false,\n error: 'Report data is required'\n }, sendMessage, clientId);\n return;\n }\n\n try {\n const createdReport = reportManager.createReport(reportId, report);\n\n sendResponse(id, {\n success: true,\n data: {\n reportId,\n report: createdReport,\n message: `Report '${reportId}' created successfully`\n }\n }, sendMessage, clientId);\n } catch (error) {\n sendResponse(id, {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create report'\n }, sendMessage, clientId);\n }\n}\n\n/**\n * Handle update report operation\n */\nasync function handleUpdate(\n id: string,\n reportId: string | undefined,\n report: any,\n reportManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!reportId || reportId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Report ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n if (!report) {\n sendResponse(id, {\n success: false,\n error: 'Report data is required'\n }, sendMessage, clientId);\n return;\n }\n\n try {\n const updatedReport = reportManager.updateReport(reportId, report);\n\n if (!updatedReport) {\n sendResponse(id, {\n success: false,\n error: `Report '${reportId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n sendResponse(id, {\n success: true,\n data: {\n reportId,\n report: updatedReport,\n message: `Report '${reportId}' updated successfully`\n }\n }, sendMessage, clientId);\n } catch (error) {\n sendResponse(id, {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to update report'\n }, sendMessage, clientId);\n }\n}\n\n/**\n * Handle delete report operation\n */\nasync function handleDelete(\n id: string,\n reportId: string | undefined,\n reportManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!reportId || reportId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Report ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n const deleted = reportManager.deleteReport(reportId);\n\n if (!deleted) {\n sendResponse(id, {\n success: false,\n error: `Report '${reportId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n sendResponse(id, {\n success: true,\n data: {\n reportId,\n message: `Report '${reportId}' deleted successfully`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get all reports operation\n */\nasync function handleGetAll(\n id: string,\n reportManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n const reports = reportManager.getAllReports();\n\n logger.info(`Admin retrieved all reports (count: ${reports.length})`);\n\n sendResponse(id, {\n success: true,\n data: {\n reports,\n count: reports.length,\n message: `Retrieved ${reports.length} reports`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get one report operation\n */\nasync function handleGetOne(\n id: string,\n reportId: string | undefined,\n reportManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!reportId || reportId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Report ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n const report = reportManager.getReport(reportId);\n\n if (!report) {\n sendResponse(id, {\n success: false,\n error: `Report '${reportId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n logger.info(`Admin retrieved report: ${reportId}`);\n\n sendResponse(id, {\n success: true,\n data: {\n reportId,\n report,\n message: `Retrieved report '${reportId}'`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Send reports response\n */\nfunction sendResponse(\n id: string | null,\n res: { success: boolean; error?: string; data?: any },\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id: id || 'unknown',\n type: 'REPORTS_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'admin',\n id: clientId\n },\n payload: {\n ...res,\n }\n };\n\n sendMessage(response);\n}\n","import fs from 'fs';\nimport path from 'path';\nimport os from 'os';\nimport { logger } from '../utils/logger';\n\nexport interface User {\n username: string;\n password: string;\n wsIds: string[];\n}\n\nexport interface UsersData {\n users: User[];\n}\n\n/**\n * UserManager class to handle CRUD operations on users with file persistence\n * and in-memory caching. Changes are synced to file periodically.\n */\nexport class UserManager {\n private users: User[] = [];\n private filePath: string;\n private hasChanged: boolean = false;\n private syncInterval: ReturnType<typeof setInterval> | null = null;\n private syncIntervalMs: number;\n private isInitialized: boolean = false;\n\n /**\n * Initialize UserManager with file path and sync interval\n * @param projectId - Project ID to use in file path (default: 'snowflake-dataset')\n * @param syncIntervalMs - Interval in milliseconds to sync changes to file (default: 5000ms)\n */\n constructor(projectId: string = 'snowflake-dataset', syncIntervalMs: number = 5000) {\n this.filePath = path.join(os.homedir(), '.superatom', 'projects', projectId, 'users.json');\n this.syncIntervalMs = syncIntervalMs;\n }\n\n /**\n * Initialize the UserManager by loading users from file and starting sync interval\n */\n async init(): Promise<void> {\n if (this.isInitialized) {\n return;\n }\n\n try {\n // Load users from file into memory\n await this.loadUsersFromFile();\n logger.info(`UserManager initialized with ${this.users.length} users`);\n\n // Start the sync interval\n this.startSyncInterval();\n this.isInitialized = true;\n } catch (error) {\n logger.error('Failed to initialize UserManager:', error);\n throw error;\n }\n }\n\n /**\n * Load users from the JSON file into memory\n */\n private async loadUsersFromFile(): Promise<void> {\n try {\n // Create directory structure if it doesn't exist\n const dir = path.dirname(this.filePath);\n if (!fs.existsSync(dir)) {\n logger.info(`Creating directory structure: ${dir}`);\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Create file with empty users array if it doesn't exist\n if (!fs.existsSync(this.filePath)) {\n logger.info(`Users file does not exist at ${this.filePath}, creating with empty users`);\n const initialData: UsersData = { users: [] };\n fs.writeFileSync(this.filePath, JSON.stringify(initialData, null, 4));\n this.users = [];\n this.hasChanged = false;\n return;\n }\n\n const fileContent = fs.readFileSync(this.filePath, 'utf-8');\n const data = JSON.parse(fileContent) as UsersData;\n\n this.users = Array.isArray(data.users) ? data.users : [];\n this.hasChanged = false;\n logger.debug(`Loaded ${this.users.length} users from file`);\n } catch (error) {\n logger.error('Failed to load users from file:', error);\n throw new Error(`Failed to load users from file: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n /**\n * Save users from memory to the JSON file\n */\n private async saveUsersToFile(): Promise<void> {\n if (!this.hasChanged) {\n return;\n }\n\n try {\n // Create directory if it doesn't exist\n const dir = path.dirname(this.filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n const data: UsersData = { users: this.users };\n fs.writeFileSync(this.filePath, JSON.stringify(data, null, 4));\n\n this.hasChanged = false;\n logger.debug(`Synced ${this.users.length} users to file`);\n } catch (error) {\n logger.error('Failed to save users to file:', error);\n throw new Error(`Failed to save users to file: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n /**\n * Start the periodic sync interval\n */\n private startSyncInterval(): void {\n if (this.syncInterval) {\n return;\n }\n\n this.syncInterval = setInterval(async () => {\n if (this.hasChanged) {\n try {\n await this.saveUsersToFile();\n logger.debug('Auto-sync: Users saved to file');\n } catch (error) {\n logger.error('Auto-sync failed:', error);\n }\n }\n }, this.syncIntervalMs);\n\n logger.debug(`Sync interval started (${this.syncIntervalMs}ms)`);\n }\n\n /**\n * Stop the periodic sync interval\n */\n public stopSyncInterval(): void {\n if (this.syncInterval) {\n clearInterval(this.syncInterval);\n this.syncInterval = null;\n logger.debug('Sync interval stopped');\n }\n }\n\n /**\n * Force sync users to file immediately\n */\n public async forceSync(): Promise<void> {\n await this.saveUsersToFile();\n }\n\n /**\n * Create a new user\n * @param user - User object to create\n * @returns The created user\n */\n public createUser(user: User): User {\n if (this.users.some(u => u.username === user.username)) {\n throw new Error(`User with username ${user.username} already exists`);\n }\n\n this.users.push(user);\n this.hasChanged = true;\n logger.debug(`User created: ${user.username}`);\n\n return user;\n }\n\n /**\n * Read a user by username\n * @param username - Username to retrieve\n * @returns The user if found, undefined otherwise\n */\n public getUser(username: string): User | undefined {\n return this.users.find(u => u.username === username);\n }\n\n /**\n * Read all users\n * @returns Array of all users\n */\n public getAllUsers(): User[] {\n return [...this.users];\n }\n\n /**\n * Find users by a predicate function\n * @param predicate - Function to filter users\n * @returns Array of matching users\n */\n public findUsers(predicate: (user: User) => boolean): User[] {\n return this.users.filter(predicate);\n }\n\n /**\n * Update an existing user by username\n * @param username - Username of user to update\n * @param updates - Partial user object with fields to update\n * @returns The updated user\n */\n public updateUser(username: string, updates: Partial<User>): User {\n const userIndex = this.users.findIndex(u => u.username === username);\n if (userIndex === -1) {\n throw new Error(`User with username ${username} not found`);\n }\n\n const updatedUser = { ...this.users[userIndex], ...updates };\n this.users[userIndex] = updatedUser;\n this.hasChanged = true;\n logger.debug(`User updated: ${username}`);\n\n return updatedUser;\n }\n\n /**\n * Delete a user by username\n * @param username - Username of user to delete\n * @returns true if user was deleted, false if not found\n */\n public deleteUser(username: string): boolean {\n const initialLength = this.users.length;\n this.users = this.users.filter(u => u.username !== username);\n\n if (this.users.length < initialLength) {\n this.hasChanged = true;\n logger.debug(`User deleted: ${username}`);\n return true;\n }\n return false;\n }\n\n /**\n * Delete all users\n */\n public deleteAllUsers(): void {\n if (this.users.length > 0) {\n this.users = [];\n this.hasChanged = true;\n logger.debug('All users deleted');\n }\n }\n\n /**\n * Get the count of users\n * @returns Number of users in memory\n */\n public getUserCount(): number {\n return this.users.length;\n }\n\n /**\n * Check if a user exists\n * @param username - Username to check\n * @returns true if user exists, false otherwise\n */\n public userExists(username: string): boolean {\n return this.users.some(u => u.username === username);\n }\n\n /**\n * Add a WebSocket ID to a user's wsIds array\n * @param username - Username to update\n * @param wsId - WebSocket ID to add\n * @returns true if successful, false if user not found\n */\n public addWsId(username: string, wsId: string): boolean {\n const user = this.getUser(username);\n if (!user) {\n return false;\n }\n\n if(!user.wsIds || !Array.isArray(user.wsIds)) {\n user.wsIds = [];\n }\n\n if (!user.wsIds.includes(wsId)) {\n user.wsIds.push(wsId);\n this.hasChanged = true;\n logger.debug(`WebSocket ID added to user ${username}: ${wsId}`);\n }\n\n return true;\n }\n\n /**\n * Remove a WebSocket ID from a user's wsIds array\n * @param username - Username to update\n * @param wsId - WebSocket ID to remove\n * @returns true if successful, false if user not found\n */\n public removeWsId(username: string, wsId: string): boolean {\n const user = this.getUser(username);\n if (!user) {\n return false;\n }\n\n if(!user.wsIds || !Array.isArray(user.wsIds)) {\n return false;\n }\n\n const initialLength = user.wsIds.length;\n user.wsIds = user.wsIds.filter(id => id !== wsId);\n\n if (user.wsIds.length < initialLength) {\n this.hasChanged = true;\n logger.debug(`WebSocket ID removed from user ${username}: ${wsId}`);\n }\n\n return true;\n }\n\n /**\n * Get the change status\n * @returns true if there are unsaved changes, false otherwise\n */\n public hasUnsavedChanges(): boolean {\n return this.hasChanged;\n }\n\n /**\n * Cleanup resources and stop sync interval\n */\n public async destroy(): Promise<void> {\n this.stopSyncInterval();\n // Final sync before cleanup\n if (this.hasChanged) {\n await this.saveUsersToFile();\n }\n logger.info('UserManager destroyed');\n }\n}\n","import fs from 'fs';\nimport path from 'path';\nimport os from 'os';\nimport { logger } from '../utils/logger';\nimport { DSLRendererProps, DSLRendererPropsSchema } from './types';\n\n/**\n * DashboardManager class to handle CRUD operations on dashboards\n * All operations read/write directly to files (no in-memory caching)\n */\nexport class DashboardManager {\n private dashboardsBasePath: string;\n private projectId: string;\n\n /**\n * Initialize DashboardManager with project ID\n * @param projectId - Project ID to use in file path\n */\n constructor(projectId: string = 'snowflake-dataset') {\n this.projectId = projectId;\n this.dashboardsBasePath = path.join(\n os.homedir(),\n '.superatom',\n 'projects',\n projectId,\n 'dashboards'\n );\n }\n\n /**\n * Get the file path for a specific dashboard\n * @param dashboardId - Dashboard ID\n * @returns Full path to dashboard data.json file\n */\n private getDashboardPath(dashboardId: string): string {\n return path.join(this.dashboardsBasePath, dashboardId, 'data.json');\n }\n\n /**\n * Create a new dashboard\n * @param dashboardId - Unique dashboard ID\n * @param dashboard - Dashboard data\n * @returns Created dashboard with metadata\n */\n createDashboard(dashboardId: string, dashboard: DSLRendererProps): DSLRendererProps {\n const dashboardPath = this.getDashboardPath(dashboardId);\n const dashboardDir = path.dirname(dashboardPath);\n\n // Check if dashboard already exists\n if (fs.existsSync(dashboardPath)) {\n throw new Error(`Dashboard '${dashboardId}' already exists`);\n }\n\n // Validate dashboard structure\n const validated = DSLRendererPropsSchema.parse(dashboard);\n\n // Create directory structure\n fs.mkdirSync(dashboardDir, { recursive: true });\n\n // Write dashboard to file\n fs.writeFileSync(dashboardPath, JSON.stringify(validated, null, 4));\n\n logger.info(`Dashboard created: ${dashboardId}`);\n return validated;\n }\n\n /**\n * Get a specific dashboard by ID\n * @param dashboardId - Dashboard ID\n * @returns Dashboard data or null if not found\n */\n getDashboard(dashboardId: string): DSLRendererProps | null {\n const dashboardPath = this.getDashboardPath(dashboardId);\n\n if (!fs.existsSync(dashboardPath)) {\n logger.warn(`Dashboard not found: ${dashboardId}`);\n return null;\n }\n\n try {\n const fileContent = fs.readFileSync(dashboardPath, 'utf-8');\n const dashboard = JSON.parse(fileContent) as DSLRendererProps;\n\n // Validate structure\n const validated = DSLRendererPropsSchema.parse(dashboard);\n return validated;\n } catch (error) {\n logger.error(`Failed to read dashboard ${dashboardId}:`, error);\n return null;\n }\n }\n\n /**\n * Get all dashboards\n * @returns Array of dashboard objects with their IDs\n */\n getAllDashboards(): Array<{ dashboardId: string; dashboard: DSLRendererProps }> {\n // Create base directory if it doesn't exist\n if (!fs.existsSync(this.dashboardsBasePath)) {\n fs.mkdirSync(this.dashboardsBasePath, { recursive: true });\n return [];\n }\n\n const dashboards: Array<{ dashboardId: string; dashboard: DSLRendererProps }> = [];\n\n try {\n const dashboardDirs = fs.readdirSync(this.dashboardsBasePath);\n\n for (const dashboardId of dashboardDirs) {\n const dashboardPath = this.getDashboardPath(dashboardId);\n\n if (fs.existsSync(dashboardPath)) {\n const dashboard = this.getDashboard(dashboardId);\n if (dashboard) {\n dashboards.push({ dashboardId, dashboard });\n }\n }\n }\n\n logger.debug(`Retrieved ${dashboards.length} dashboards`);\n return dashboards;\n } catch (error) {\n logger.error('Failed to get all dashboards:', error);\n return [];\n }\n }\n\n /**\n * Update an existing dashboard\n * @param dashboardId - Dashboard ID\n * @param dashboard - Updated dashboard data\n * @returns Updated dashboard or null if not found\n */\n updateDashboard(dashboardId: string, dashboard: DSLRendererProps): DSLRendererProps | null {\n const dashboardPath = this.getDashboardPath(dashboardId);\n\n if (!fs.existsSync(dashboardPath)) {\n logger.warn(`Dashboard not found for update: ${dashboardId}`);\n return null;\n }\n\n try {\n // Validate dashboard structure\n const validated = DSLRendererPropsSchema.parse(dashboard);\n\n // Write updated dashboard to file\n fs.writeFileSync(dashboardPath, JSON.stringify(validated, null, 4));\n\n logger.info(`Dashboard updated: ${dashboardId}`);\n return validated;\n } catch (error) {\n logger.error(`Failed to update dashboard ${dashboardId}:`, error);\n throw error;\n }\n }\n\n /**\n * Delete a dashboard\n * @param dashboardId - Dashboard ID\n * @returns True if deleted, false if not found\n */\n deleteDashboard(dashboardId: string): boolean {\n const dashboardPath = this.getDashboardPath(dashboardId);\n const dashboardDir = path.dirname(dashboardPath);\n\n if (!fs.existsSync(dashboardPath)) {\n logger.warn(`Dashboard not found for deletion: ${dashboardId}`);\n return false;\n }\n\n try {\n // Delete the entire dashboard directory\n fs.rmSync(dashboardDir, { recursive: true, force: true });\n\n logger.info(`Dashboard deleted: ${dashboardId}`);\n return true;\n } catch (error) {\n logger.error(`Failed to delete dashboard ${dashboardId}:`, error);\n return false;\n }\n }\n\n /**\n * Check if a dashboard exists\n * @param dashboardId - Dashboard ID\n * @returns True if dashboard exists, false otherwise\n */\n dashboardExists(dashboardId: string): boolean {\n const dashboardPath = this.getDashboardPath(dashboardId);\n return fs.existsSync(dashboardPath);\n }\n\n /**\n * Get dashboard count\n * @returns Number of dashboards\n */\n getDashboardCount(): number {\n if (!fs.existsSync(this.dashboardsBasePath)) {\n return 0;\n }\n\n try {\n const dashboardDirs = fs.readdirSync(this.dashboardsBasePath);\n return dashboardDirs.filter((dir) => {\n const dashboardPath = this.getDashboardPath(dir);\n return fs.existsSync(dashboardPath);\n }).length;\n } catch (error) {\n logger.error('Failed to get dashboard count:', error);\n return 0;\n }\n }\n}\n","import fs from 'fs';\nimport path from 'path';\nimport os from 'os';\nimport { logger } from '../utils/logger';\nimport { DSLRendererProps, DSLRendererPropsSchema } from './types';\n\n/**\n * ReportManager class to handle CRUD operations on reports\n * All operations read/write directly to files (no in-memory caching)\n */\nexport class ReportManager {\n private reportsBasePath: string;\n private projectId: string;\n\n /**\n * Initialize ReportManager with project ID\n * @param projectId - Project ID to use in file path\n */\n constructor(projectId: string = 'snowflake-dataset') {\n this.projectId = projectId;\n this.reportsBasePath = path.join(\n os.homedir(),\n '.superatom',\n 'projects',\n projectId,\n 'reports'\n );\n }\n\n /**\n * Get the file path for a specific report\n * @param reportId - Report ID\n * @returns Full path to report data.json file\n */\n private getReportPath(reportId: string): string {\n return path.join(this.reportsBasePath, reportId, 'data.json');\n }\n\n /**\n * Create a new report\n * @param reportId - Unique report ID\n * @param report - Report data\n * @returns Created report with metadata\n */\n createReport(reportId: string, report: DSLRendererProps): DSLRendererProps {\n const reportPath = this.getReportPath(reportId);\n const reportDir = path.dirname(reportPath);\n\n // Check if report already exists\n if (fs.existsSync(reportPath)) {\n throw new Error(`Report '${reportId}' already exists`);\n }\n\n // Validate report structure\n const validated = DSLRendererPropsSchema.parse(report);\n\n // Create directory structure\n fs.mkdirSync(reportDir, { recursive: true });\n\n // Write report to file\n fs.writeFileSync(reportPath, JSON.stringify(validated, null, 4));\n\n logger.info(`Report created: ${reportId}`);\n return validated;\n }\n\n /**\n * Get a specific report by ID\n * @param reportId - Report ID\n * @returns Report data or null if not found\n */\n getReport(reportId: string): DSLRendererProps | null {\n const reportPath = this.getReportPath(reportId);\n\n if (!fs.existsSync(reportPath)) {\n logger.warn(`Report not found: ${reportId}`);\n return null;\n }\n\n try {\n const fileContent = fs.readFileSync(reportPath, 'utf-8');\n const report = JSON.parse(fileContent) as DSLRendererProps;\n\n // Validate structure\n const validated = DSLRendererPropsSchema.parse(report);\n return validated;\n } catch (error) {\n logger.error(`Failed to read report ${reportId}:`, error);\n return null;\n }\n }\n\n /**\n * Get all reports\n * @returns Array of report objects with their IDs\n */\n getAllReports(): Array<{ reportId: string; report: DSLRendererProps }> {\n // Create base directory if it doesn't exist\n if (!fs.existsSync(this.reportsBasePath)) {\n fs.mkdirSync(this.reportsBasePath, { recursive: true });\n return [];\n }\n\n const reports: Array<{ reportId: string; report: DSLRendererProps }> = [];\n\n try {\n const reportDirs = fs.readdirSync(this.reportsBasePath);\n\n for (const reportId of reportDirs) {\n const reportPath = this.getReportPath(reportId);\n\n if (fs.existsSync(reportPath)) {\n const report = this.getReport(reportId);\n if (report) {\n reports.push({ reportId, report });\n }\n }\n }\n\n logger.debug(`Retrieved ${reports.length} reports`);\n return reports;\n } catch (error) {\n logger.error('Failed to get all reports:', error);\n return [];\n }\n }\n\n /**\n * Update an existing report\n * @param reportId - Report ID\n * @param report - Updated report data\n * @returns Updated report or null if not found\n */\n updateReport(reportId: string, report: DSLRendererProps): DSLRendererProps | null {\n const reportPath = this.getReportPath(reportId);\n\n if (!fs.existsSync(reportPath)) {\n logger.warn(`Report not found for update: ${reportId}`);\n return null;\n }\n\n try {\n // Validate report structure\n const validated = DSLRendererPropsSchema.parse(report);\n\n // Write updated report to file\n fs.writeFileSync(reportPath, JSON.stringify(validated, null, 4));\n\n logger.info(`Report updated: ${reportId}`);\n return validated;\n } catch (error) {\n logger.error(`Failed to update report ${reportId}:`, error);\n throw error;\n }\n }\n\n /**\n * Delete a report\n * @param reportId - Report ID\n * @returns True if deleted, false if not found\n */\n deleteReport(reportId: string): boolean {\n const reportPath = this.getReportPath(reportId);\n const reportDir = path.dirname(reportPath);\n\n if (!fs.existsSync(reportPath)) {\n logger.warn(`Report not found for deletion: ${reportId}`);\n return false;\n }\n\n try {\n // Delete the entire report directory\n fs.rmSync(reportDir, { recursive: true, force: true });\n\n logger.info(`Report deleted: ${reportId}`);\n return true;\n } catch (error) {\n logger.error(`Failed to delete report ${reportId}:`, error);\n return false;\n }\n }\n\n /**\n * Check if a report exists\n * @param reportId - Report ID\n * @returns True if report exists, false otherwise\n */\n reportExists(reportId: string): boolean {\n const reportPath = this.getReportPath(reportId);\n return fs.existsSync(reportPath);\n }\n\n /**\n * Get report count\n * @returns Number of reports\n */\n getReportCount(): number {\n if (!fs.existsSync(this.reportsBasePath)) {\n return 0;\n }\n\n try {\n const reportDirs = fs.readdirSync(this.reportsBasePath);\n return reportDirs.filter((dir) => {\n const reportPath = this.getReportPath(dir);\n return fs.existsSync(reportPath);\n }).length;\n } catch (error) {\n logger.error('Failed to get report count:', error);\n return 0;\n }\n }\n}\n","import { ThreadManager } from '../threads';\nimport { logger } from '../utils/logger';\nimport { STORAGE_CONFIG } from '../config/storage';\n\n/**\n * CleanupService handles cleanup of old threads and UIBlocks\n * to prevent memory bloat and maintain optimal performance\n */\nexport class CleanupService {\n private static instance: CleanupService;\n private cleanupInterval: NodeJS.Timeout | null = null;\n\n private constructor() {}\n\n /**\n * Get singleton instance of CleanupService\n */\n static getInstance(): CleanupService {\n if (!CleanupService.instance) {\n CleanupService.instance = new CleanupService();\n }\n return CleanupService.instance;\n }\n\n /**\n * Clean up old threads based on retention period\n * @param retentionDays - Number of days to keep threads (defaults to config)\n * @returns Number of threads deleted\n */\n cleanupOldThreads(retentionDays: number = STORAGE_CONFIG.THREAD_RETENTION_DAYS): number {\n const threadManager = ThreadManager.getInstance();\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - retentionDays);\n\n const threads = threadManager.getAllThreads();\n let deletedCount = 0;\n\n for (const thread of threads) {\n if (thread.getCreatedAt() < cutoffDate) {\n const threadId = thread.getId();\n if (threadManager.deleteThread(threadId)) {\n deletedCount++;\n logger.info(`Deleted old thread: ${threadId} (created: ${thread.getCreatedAt().toISOString()})`);\n }\n }\n }\n\n if (deletedCount > 0) {\n logger.info(`Cleanup: Deleted ${deletedCount} old threads (older than ${retentionDays} days)`);\n }\n\n return deletedCount;\n }\n\n /**\n * Clean up old UIBlocks within threads based on retention period\n * @param retentionDays - Number of days to keep UIBlocks (defaults to config)\n * @returns Object with number of UIBlocks deleted per thread\n */\n cleanupOldUIBlocks(retentionDays: number = STORAGE_CONFIG.UIBLOCK_RETENTION_DAYS): { [threadId: string]: number } {\n const threadManager = ThreadManager.getInstance();\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - retentionDays);\n\n const threads = threadManager.getAllThreads();\n const deletionStats: { [threadId: string]: number } = {};\n\n for (const thread of threads) {\n const uiblocks = thread.getUIBlocks();\n let deletedInThread = 0;\n\n for (const uiblock of uiblocks) {\n if (uiblock.getCreatedAt() < cutoffDate) {\n if (thread.removeUIBlock(uiblock.getId())) {\n deletedInThread++;\n }\n }\n }\n\n if (deletedInThread > 0) {\n deletionStats[thread.getId()] = deletedInThread;\n logger.info(\n `Deleted ${deletedInThread} old UIBlocks from thread ${thread.getId()} (older than ${retentionDays} days)`\n );\n }\n }\n\n const totalDeleted = Object.values(deletionStats).reduce((sum, count) => sum + count, 0);\n if (totalDeleted > 0) {\n logger.info(`Cleanup: Deleted ${totalDeleted} old UIBlocks across ${Object.keys(deletionStats).length} threads`);\n }\n\n return deletionStats;\n }\n\n /**\n * Clear all component data from UIBlocks to free memory\n * Keeps metadata but removes the actual data\n * @param retentionDays - Number of days to keep full data (defaults to config)\n * @returns Number of UIBlocks whose data was cleared\n */\n clearOldUIBlockData(retentionDays: number = STORAGE_CONFIG.UIBLOCK_RETENTION_DAYS): number {\n const threadManager = ThreadManager.getInstance();\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - retentionDays);\n\n const threads = threadManager.getAllThreads();\n let clearedCount = 0;\n\n for (const thread of threads) {\n const uiblocks = thread.getUIBlocks();\n\n for (const uiblock of uiblocks) {\n if (uiblock.getCreatedAt() < cutoffDate) {\n const componentData = uiblock.getComponentData();\n\n // Only clear if data exists\n if (componentData && Object.keys(componentData).length > 0) {\n // Keep metadata but clear actual data\n const metadata = {\n dataCleared: true,\n clearedAt: new Date().toISOString(),\n originalDataInfo: {\n totalRows: componentData.totalRows,\n storedRows: componentData.storedRows,\n isTruncated: componentData.isTruncated,\n },\n };\n\n uiblock.setComponentData({ ...metadata, data: null });\n clearedCount++;\n }\n }\n }\n }\n\n if (clearedCount > 0) {\n logger.info(`Cleanup: Cleared data from ${clearedCount} old UIBlocks (older than ${retentionDays} days)`);\n }\n\n return clearedCount;\n }\n\n /**\n * Run full cleanup (threads, UIBlocks, and data)\n * @returns Cleanup statistics\n */\n runFullCleanup(): {\n threadsDeleted: number;\n uiblocksDeleted: { [threadId: string]: number };\n dataCleared: number;\n } {\n logger.info('Starting full cleanup...');\n\n const stats = {\n threadsDeleted: this.cleanupOldThreads(),\n uiblocksDeleted: this.cleanupOldUIBlocks(),\n dataCleared: this.clearOldUIBlockData(),\n };\n\n const totalUIBlocksDeleted = Object.values(stats.uiblocksDeleted).reduce((sum, count) => sum + count, 0);\n\n logger.info(\n `Full cleanup completed: ${stats.threadsDeleted} threads, ${totalUIBlocksDeleted} UIBlocks deleted, ${stats.dataCleared} UIBlock data cleared`\n );\n\n return stats;\n }\n\n /**\n * Start automatic cleanup at regular intervals\n * @param intervalHours - Hours between cleanup runs (default: 24)\n */\n startAutoCleanup(intervalHours: number = 24): void {\n if (this.cleanupInterval) {\n logger.warn('Auto cleanup is already running');\n\n //stop this and run with new interval\n\n \n return;\n }\n\n const intervalMs = intervalHours * 60 * 60 * 1000;\n\n // Run initial cleanup\n this.runFullCleanup();\n\n // Schedule recurring cleanup\n this.cleanupInterval = setInterval(() => {\n this.runFullCleanup();\n }, intervalMs);\n\n logger.info(`Auto cleanup started: running every ${intervalHours} hours`);\n }\n\n /**\n * Stop automatic cleanup\n */\n stopAutoCleanup(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n logger.info('Auto cleanup stopped');\n }\n }\n\n /**\n * Check if auto cleanup is running\n */\n isAutoCleanupRunning(): boolean {\n return this.cleanupInterval !== null;\n }\n\n /**\n * Get current memory usage statistics\n */\n getMemoryStats(): {\n threadCount: number;\n totalUIBlocks: number;\n avgUIBlocksPerThread: number;\n } {\n const threadManager = ThreadManager.getInstance();\n const threads = threadManager.getAllThreads();\n const threadCount = threads.length;\n\n let totalUIBlocks = 0;\n for (const thread of threads) {\n totalUIBlocks += thread.getUIBlockCount();\n }\n\n return {\n threadCount,\n totalUIBlocks,\n avgUIBlocksPerThread: threadCount > 0 ? totalUIBlocks / threadCount : 0,\n };\n }\n}\n","import { createWebSocket } from './websocket';\nimport {\n IncomingMessageSchema,\n type Message,\n type IncomingMessage,\n type SuperatomSDKConfig,\n type CollectionRegistry,\n type CollectionHandler,\n type CollectionOperation,\n Component,\n LLMProvider,\n} from './types';\nimport { logger } from './utils/logger';\nimport { handleDataRequest } from './handlers/data-request';\nimport { handleBundleRequest } from './handlers/bundle-request';\nimport { handleAuthLoginRequest } from './handlers/auth-login-requests';\nimport { handleAuthVerifyRequest } from './handlers/auth-verify-request';\nimport { handleUserPromptRequest } from './handlers/user-prompt-request';\nimport { handleUserPromptSuggestions } from './handlers/user-prompt-suggestions';\nimport { handleActionsRequest } from './handlers/actions-request';\nimport { handleComponentListResponse } from './handlers/components-list-response';\nimport { handleUsersRequest } from './handlers/users';\nimport { handleDashboardsRequest } from './handlers/dashboards';\nimport { handleReportsRequest } from './handlers/reports';\nimport { getLLMProviders } from './userResponse';\nimport { setUserManager, cleanupUserStorage } from './auth/user-storage';\nimport { UserManager } from './auth/user-manager';\nimport { setDashboardManager } from './dashboards/dashboard-storage';\nimport { DashboardManager } from './dashboards/dashboard-manager';\nimport { setReportManager } from './reports/report-storage';\nimport { ReportManager } from './reports/report-manager';\n\nexport const SDK_VERSION = '0.0.8';\n\nconst DEFAULT_WS_URL = 'wss://ws.superatom.ai/websocket';\n\ntype MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;\n\nexport class SuperatomSDK {\n private ws: ReturnType<typeof createWebSocket> | null = null;\n private url: string;\n private apiKey: string;\n private projectId: string;\n private userId: string;\n private type: string;\n private bundleDir: string | undefined;\n private messageHandlers: Map<string, (message: IncomingMessage) => void> = new Map();\n private messageTypeHandlers: Map<string, MessageTypeHandler> = new Map();\n private connected: boolean = false;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = 5;\n private collections: CollectionRegistry = {};\n\tprivate components: Component[] = [];\n private anthropicApiKey: string;\n private groqApiKey: string;\n private llmProviders: LLMProvider[];\n private userManager: UserManager;\n private dashboardManager: DashboardManager;\n private reportManager: ReportManager;\n\n constructor(config: SuperatomSDKConfig) {\n this.apiKey = config.apiKey;\n this.projectId = config.projectId;\n this.userId = config.userId || 'anonymous';\n this.type = config.type || 'data-agent';\n this.bundleDir = config.bundleDir;\n this.url = config.url || process.env.SA_WEBSOCKET_URL || DEFAULT_WS_URL;\n this.anthropicApiKey = config.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || '';\n this.groqApiKey = config.GROQ_API_KEY || process.env.GROQ_API_KEY || '';\n this.llmProviders = config.LLM_PROVIDERS || getLLMProviders();\n\n // Initialize UserManager for this SDK instance\n this.userManager = new UserManager(this.projectId, 5000);\n\n // Initialize DashboardManager for this SDK instance\n this.dashboardManager = new DashboardManager(this.projectId);\n\n // Initialize ReportManager for this SDK instance\n this.reportManager = new ReportManager(this.projectId);\n\n // Initialize UserManager with projectId (startup)\n this.initializeUserManager().catch((error) => {\n logger.error('Failed to initialize UserManager:', error);\n });\n\n // Initialize DashboardManager\n this.initializeDashboardManager();\n\n // Initialize ReportManager\n this.initializeReportManager();\n\n // Automatically connect on instantiation\n this.connect().catch((error) => {\n logger.error('Failed to connect to Superatom:', error);\n });\n\n //\n }\n\n /**\n * Initialize UserManager for the project\n */\n private async initializeUserManager(): Promise<void> {\n try {\n await this.userManager.init();\n // Set the global reference for backward compatibility with existing auth code\n setUserManager(this.userManager);\n logger.info(`UserManager initialized for project: ${this.projectId}`);\n } catch (error) {\n logger.error('Failed to initialize UserManager:', error);\n throw error;\n }\n }\n\n /**\n * Get the UserManager instance for this SDK\n */\n public getUserManager(): UserManager {\n return this.userManager;\n }\n\n /**\n * Initialize DashboardManager for the project\n */\n private initializeDashboardManager(): void {\n // Set the global reference for dashboard operations\n setDashboardManager(this.dashboardManager);\n logger.info(`DashboardManager initialized for project: ${this.projectId}`);\n }\n\n /**\n * Get the DashboardManager instance for this SDK\n */\n public getDashboardManager(): DashboardManager {\n return this.dashboardManager;\n }\n\n /**\n * Initialize ReportManager for the project\n */\n private initializeReportManager(): void {\n // Set the global reference for report operations\n setReportManager(this.reportManager);\n logger.info(`ReportManager initialized for project: ${this.projectId}`);\n }\n\n /**\n * Get the ReportManager instance for this SDK\n */\n public getReportManager(): ReportManager {\n return this.reportManager;\n }\n\n /**\n * Connect to the Superatom WebSocket service\n */\n async connect(): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n // Add all required query parameters\n const url = new URL(this.url);\n url.searchParams.set('apiKey', this.apiKey);\n url.searchParams.set('projectId', this.projectId);\n url.searchParams.set('userId', this.userId);\n url.searchParams.set('type', this.type);\n\n logger.info(`Connecting to WebSocket: ${url.host}`);\n\n this.ws = createWebSocket(url.toString());\n\n this.ws.addEventListener('open', () => {\n this.connected = true;\n this.reconnectAttempts = 0;\n logger.info('WebSocket connected successfully');\n resolve();\n });\n\n this.ws.addEventListener('message', (event: any) => {\n this.handleMessage(event.data);\n });\n\n this.ws.addEventListener('error', (error: any) => {\n logger.error('WebSocket error:', error);\n reject(error);\n });\n\n this.ws.addEventListener('close', () => {\n this.connected = false;\n logger.warn('WebSocket closed');\n this.handleReconnect();\n });\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Handle incoming WebSocket messages\n */\n private handleMessage(data: string): void {\n try {\n const parsed = JSON.parse(data);\n const message = IncomingMessageSchema.parse(parsed);\n\n logger.debug('Received message:', message.type);\n\n // Route message by type\n switch (message.type) {\n case 'DATA_REQ':\n handleDataRequest(parsed, this.collections, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle data request:', error);\n });\n break;\n\n case 'BUNDLE_REQ':\n handleBundleRequest(parsed, this.bundleDir, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle bundle request:', error);\n });\n break;\n\n case 'AUTH_LOGIN_REQ':\n handleAuthLoginRequest(parsed, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle auth login request:', error);\n });\n break;\n\n case 'AUTH_VERIFY_REQ':\n handleAuthVerifyRequest(parsed, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle auth verify request:', error);\n });\n break;\n\n case 'USER_PROMPT_REQ':\n handleUserPromptRequest(parsed, this.components, (msg) => this.send(msg), this.anthropicApiKey, this.groqApiKey, this.llmProviders).catch((error) => {\n logger.error('Failed to handle user prompt request:', error);\n });\n break;\n\n case 'ACTIONS':\n handleActionsRequest(parsed, (msg) => this.send(msg), this.anthropicApiKey, this.groqApiKey, this.llmProviders).catch((error) => {\n logger.error('Failed to handle actions request:', error);\n });\n break;\n\n case 'USER_PROMPT_SUGGESTIONS_REQ':\n handleUserPromptSuggestions(parsed, this.components, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle user prompt suggestions request:', error);\n });\n break;\n\n case 'COMPONENT_LIST_RES':\n handleComponentListResponse(parsed, (com) => this.storeComponents(com)).catch((error) => {\n logger.error('Failed to handle component list request:', error);\n });\n break;\n\n case 'USERS':\n handleUsersRequest(parsed, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle users request:', error);\n });\n break;\n\n case 'DASHBOARDS':\n handleDashboardsRequest(parsed, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle dashboards request:', error);\n });\n break;\n\n case 'REPORTS':\n handleReportsRequest(parsed, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle reports request:', error);\n });\n break;\n\n default:\n // Check for custom message type handlers\n const handler = this.messageTypeHandlers.get(message.type);\n if (handler) {\n Promise.resolve(handler(message)).catch((error) => {\n logger.error(`Failed to handle ${message.type}:`, error);\n });\n }\n break;\n }\n\n // Call registered message handlers\n this.messageHandlers.forEach((handler) => {\n handler(message);\n });\n } catch (error) {\n logger.error('Failed to parse incoming message:', error);\n }\n }\n\n /**\n * Send a message to the Superatom service\n */\n send(message: Message): void {\n if (!this.ws || !this.connected) {\n throw new Error('WebSocket is not connected. Call connect() first.');\n }\n\n if (this.ws.readyState !== this.ws.OPEN) {\n throw new Error('WebSocket is not ready to send messages.');\n }\n\n const payload = JSON.stringify(message);\n this.ws.send(payload);\n }\n\n /**\n * Register a message handler to receive all messages\n */\n onMessage(handler: (message: IncomingMessage) => void): () => void {\n const id = Math.random().toString(36).substring(7);\n this.messageHandlers.set(id, handler);\n\n // Return unsubscribe function\n return () => {\n this.messageHandlers.delete(id);\n };\n }\n\n /**\n * Register a handler for a specific message type\n */\n onMessageType(type: string, handler: MessageTypeHandler): () => void {\n this.messageTypeHandlers.set(type, handler);\n\n // Return unsubscribe function\n return () => {\n this.messageTypeHandlers.delete(type);\n };\n }\n\n /**\n * Disconnect from the WebSocket service\n */\n disconnect(): void {\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n this.connected = false;\n }\n }\n\n /**\n * Cleanup and disconnect - stops reconnection attempts and closes the connection\n */\n async destroy(): Promise<void> {\n // Prevent further reconnection attempts\n this.maxReconnectAttempts = 0;\n this.reconnectAttempts = 0;\n\n // Clear all message handlers\n this.messageHandlers.clear();\n\n // Clear all collections\n this.collections = {};\n\n // Cleanup UserManager\n try {\n await cleanupUserStorage();\n logger.info('UserManager cleanup completed');\n } catch (error) {\n logger.error('Error during UserManager cleanup:', error);\n }\n\n // Disconnect\n this.disconnect();\n }\n\n /**\n * Check if the SDK is currently connected\n */\n isConnected(): boolean {\n return this.connected && this.ws !== null && this.ws.readyState === this.ws.OPEN;\n }\n\n /**\n * Register a collection handler for data operations\n */\n addCollection<TParams = any, TResult = any>(\n collectionName: string,\n operation: CollectionOperation | string,\n handler: CollectionHandler<TParams, TResult>\n ): void {\n if (!this.collections[collectionName]) {\n this.collections[collectionName] = {};\n }\n this.collections[collectionName][operation] = handler;\n }\n\n private handleReconnect(): void {\n if (this.reconnectAttempts < this.maxReconnectAttempts) {\n this.reconnectAttempts++;\n const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000);\n\n setTimeout(() => {\n logger.info(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);\n this.connect().catch((error) => {\n logger.error('Reconnection failed:', error);\n });\n }, delay);\n } else {\n logger.error('Max reconnection attempts reached');\n }\n }\n\n private storeComponents(components: Component[]){\n this.components = components;\n }\n \n}\n\n// Export types\nexport type { Message, IncomingMessage, SuperatomSDKConfig, CollectionHandler, CollectionOperation } from './types';\nexport {LLM} from './llm';\nexport { UserManager, type User, type UsersData } from './auth/user-manager';\nexport { UILogCollector, type CapturedLog } from './utils/log-collector';\nexport { Thread, UIBlock, ThreadManager, type Action } from './threads';\nexport { CleanupService } from './services/cleanup-service';\nexport { STORAGE_CONFIG } from './config/storage';\nexport { CONTEXT_CONFIG } from './config/context';"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,OAAS;AAAA,MACT,SAAW;AAAA,QACT,KAAK;AAAA,UACH,OAAS;AAAA,UACT,SAAW;AAAA,UACX,SAAW;AAAA,QACb;AAAA,QACA,YAAY;AAAA,QACZ,eAAe;AAAA,QACf,qBAAqB;AAAA,QACrB,wBAAwB;AAAA,QACxB,qBAAqB;AAAA,QACrB,wBAAwB;AAAA,QACxB,kBAAkB;AAAA,MACpB;AAAA,MACA,SAAW;AAAA,QACT,aAAa;AAAA,QACb,MAAQ;AAAA,QACR,SAAW;AAAA,QACX,MAAQ;AAAA,QACR,iBAAiB;AAAA,QACjB,YAAc;AAAA,QACd,SAAW;AAAA,MACb;AAAA,MACA,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,UAAY;AAAA,MACZ,SAAW;AAAA,MACX,UAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,gBAAkB;AAAA,MAClB,SAAW;AAAA,MACX,iBAAmB;AAAA,QACjB,eAAe;AAAA,QACf,SAAW;AAAA,QACX,OAAS;AAAA,QACT,UAAY;AAAA,QACZ,oBAAoB;AAAA,QACpB,KAAO;AAAA,QACP,YAAc;AAAA,MAChB;AAAA,MACA,SAAW;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA,SAAW;AAAA,QACT,IAAM;AAAA,MACR;AAAA,IACF;AAAA;AAAA;;;AC7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AAO,MAAM,qCAAqC,KAAK;AAAA,IACzD;AAGA,SAAK,WAAW;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA,EAKA,cAAuB;AACrB,WAAO,KAAK,aAAa,KAAK,OAAO,QAAQ,KAAK,GAAG,eAAe,KAAK,GAAG;AAAA,EAC9E;AAAA;AAAA;AAAA;AAAA,EAKA,cACE,gBACA,WACA,SACM;AACN,QAAI,CAAC,KAAK,YAAY,cAAc,GAAG;AACrC,WAAK,YAAY,cAAc,IAAI,CAAC;AAAA,IACtC;AACA,SAAK,YAAY,cAAc,EAAE,SAAS,IAAI;AAAA,EAChD;AAAA,EAEQ,kBAAwB;AAC9B,QAAI,KAAK,oBAAoB,KAAK,sBAAsB;AACtD,WAAK;AACL,YAAM,QAAQ,KAAK,IAAI,MAAO,KAAK,IAAI,GAAG,KAAK,iBAAiB,GAAG,GAAK;AAExE,iBAAW,MAAM;AACf,eAAO,KAAK,4BAA4B,KAAK,iBAAiB,IAAI,KAAK,oBAAoB,MAAM;AACjG,aAAK,QAAQ,EAAE,MAAM,CAAC,UAAU;AAC9B,iBAAO,MAAM,wBAAwB,KAAK;AAAA,QAC5C,CAAC;AAAA,MACH,GAAG,KAAK;AAAA,IACV,OAAO;AACL,aAAO,MAAM,mCAAmC;AAAA,IAClD;AAAA,EACF;AAAA,EAEQ,gBAAgB,YAAwB;AAC9C,SAAK,aAAa;AAAA,EACpB;AAEF;","names":["fs","path","os","crypto","z","z","ExpressionSchema","BindingSchema","ForDirectiveSchema","QuerySpecSchema","UIElementSchema","UIComponentSchema","DSLRendererPropsSchema","z","DSLRendererPropsSchema","size","randomUUID","result","sendDataResponse","sendDataResponse","path","fs","path","fs","schema","fs","path","path","fs","dotenv","import_dotenv","dotenv","import_dotenv","dotenv","sendDataResponse","sendResponse","sendResponse","sendResponse","dashboardManager","handleCreate","handleUpdate","handleDelete","handleGetAll","handleGetOne","sendResponse","reportManager","handleCreate","handleUpdate","handleDelete","handleGetAll","handleGetOne","fs","path","path","fs","fs","path","os","path","os","fs","fs","path","os","path","os","fs","DSLRendererPropsSchema"]}
1
+ {"version":3,"sources":["../node_modules/dotenv/package.json","../node_modules/dotenv/lib/main.js","../src/websocket.ts","../src/types.ts","../src/dashboards/types.ts","../src/reports/types.ts","../src/utils/logger.ts","../src/threads/uiblock.ts","../src/config/storage.ts","../src/threads/thread.ts","../src/threads/thread-manager.ts","../src/handlers/data-request.ts","../src/bundle.ts","../src/handlers/bundle-request.ts","../src/auth/utils.ts","../src/auth/user-storage.ts","../src/auth/validator.ts","../src/handlers/auth-login-requests.ts","../src/handlers/auth-verify-request.ts","../src/userResponse/groq.ts","../src/userResponse/utils.ts","../src/userResponse/schema.ts","../src/userResponse/prompt-loader.ts","../src/llm.ts","../src/userResponse/base-llm.ts","../src/userResponse/anthropic.ts","../src/userResponse/index.ts","../src/utils/log-collector.ts","../src/config/context.ts","../src/handlers/user-prompt-request.ts","../src/handlers/user-prompt-suggestions.ts","../src/userResponse/next-questions.ts","../src/handlers/actions-request.ts","../src/handlers/components-list-response.ts","../src/handlers/users.ts","../src/dashboards/dashboard-storage.ts","../src/handlers/dashboards.ts","../src/reports/report-storage.ts","../src/handlers/reports.ts","../src/auth/user-manager.ts","../src/dashboards/dashboard-manager.ts","../src/reports/report-manager.ts","../src/services/cleanup-service.ts","../src/index.ts"],"sourcesContent":["{\n \"name\": \"dotenv\",\n \"version\": \"17.2.3\",\n \"description\": \"Loads environment variables from .env file\",\n \"main\": \"lib/main.js\",\n \"types\": \"lib/main.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./lib/main.d.ts\",\n \"require\": \"./lib/main.js\",\n \"default\": \"./lib/main.js\"\n },\n \"./config\": \"./config.js\",\n \"./config.js\": \"./config.js\",\n \"./lib/env-options\": \"./lib/env-options.js\",\n \"./lib/env-options.js\": \"./lib/env-options.js\",\n \"./lib/cli-options\": \"./lib/cli-options.js\",\n \"./lib/cli-options.js\": \"./lib/cli-options.js\",\n \"./package.json\": \"./package.json\"\n },\n \"scripts\": {\n \"dts-check\": \"tsc --project tests/types/tsconfig.json\",\n \"lint\": \"standard\",\n \"pretest\": \"npm run lint && npm run dts-check\",\n \"test\": \"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000\",\n \"test:coverage\": \"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov\",\n \"prerelease\": \"npm test\",\n \"release\": \"standard-version\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git://github.com/motdotla/dotenv.git\"\n },\n \"homepage\": \"https://github.com/motdotla/dotenv#readme\",\n \"funding\": \"https://dotenvx.com\",\n \"keywords\": [\n \"dotenv\",\n \"env\",\n \".env\",\n \"environment\",\n \"variables\",\n \"config\",\n \"settings\"\n ],\n \"readmeFilename\": \"README.md\",\n \"license\": \"BSD-2-Clause\",\n \"devDependencies\": {\n \"@types/node\": \"^18.11.3\",\n \"decache\": \"^4.6.2\",\n \"sinon\": \"^14.0.1\",\n \"standard\": \"^17.0.0\",\n \"standard-version\": \"^9.5.0\",\n \"tap\": \"^19.2.0\",\n \"typescript\": \"^4.8.4\"\n },\n \"engines\": {\n \"node\": \">=12\"\n },\n \"browser\": {\n \"fs\": false\n }\n}\n","const fs = require('fs')\nconst path = require('path')\nconst os = require('os')\nconst crypto = require('crypto')\nconst packageJson = require('../package.json')\n\nconst version = packageJson.version\n\n// Array of tips to display randomly\nconst TIPS = [\n '🔐 encrypt with Dotenvx: https://dotenvx.com',\n '🔐 prevent committing .env to code: https://dotenvx.com/precommit',\n '🔐 prevent building .env in docker: https://dotenvx.com/prebuild',\n '📡 add observability to secrets: https://dotenvx.com/ops',\n '👥 sync secrets across teammates & machines: https://dotenvx.com/ops',\n '🗂️ backup and recover secrets: https://dotenvx.com/ops',\n '✅ audit secrets and track compliance: https://dotenvx.com/ops',\n '🔄 add secrets lifecycle management: https://dotenvx.com/ops',\n '🔑 add access controls to secrets: https://dotenvx.com/ops',\n '🛠️ run anywhere with `dotenvx run -- yourcommand`',\n '⚙️ specify custom .env file path with { path: \\'/custom/path/.env\\' }',\n '⚙️ enable debug logging with { debug: true }',\n '⚙️ override existing env vars with { override: true }',\n '⚙️ suppress all logs with { quiet: true }',\n '⚙️ write to custom object with { processEnv: myObject }',\n '⚙️ load multiple .env files with { path: [\\'.env.local\\', \\'.env\\'] }'\n]\n\n// Get a random tip from the tips array\nfunction _getRandomTip () {\n return TIPS[Math.floor(Math.random() * TIPS.length)]\n}\n\nfunction parseBoolean (value) {\n if (typeof value === 'string') {\n return !['false', '0', 'no', 'off', ''].includes(value.toLowerCase())\n }\n return Boolean(value)\n}\n\nfunction supportsAnsi () {\n return process.stdout.isTTY // && process.env.TERM !== 'dumb'\n}\n\nfunction dim (text) {\n return supportsAnsi() ? `\\x1b[2m${text}\\x1b[0m` : text\n}\n\nconst LINE = /(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/mg\n\n// Parse src into an Object\nfunction parse (src) {\n const obj = {}\n\n // Convert buffer to string\n let lines = src.toString()\n\n // Convert line breaks to same format\n lines = lines.replace(/\\r\\n?/mg, '\\n')\n\n let match\n while ((match = LINE.exec(lines)) != null) {\n const key = match[1]\n\n // Default undefined or null to empty string\n let value = (match[2] || '')\n\n // Remove whitespace\n value = value.trim()\n\n // Check if double quoted\n const maybeQuote = value[0]\n\n // Remove surrounding quotes\n value = value.replace(/^(['\"`])([\\s\\S]*)\\1$/mg, '$2')\n\n // Expand newlines if double quoted\n if (maybeQuote === '\"') {\n value = value.replace(/\\\\n/g, '\\n')\n value = value.replace(/\\\\r/g, '\\r')\n }\n\n // Add to object\n obj[key] = value\n }\n\n return obj\n}\n\nfunction _parseVault (options) {\n options = options || {}\n\n const vaultPath = _vaultPath(options)\n options.path = vaultPath // parse .env.vault\n const result = DotenvModule.configDotenv(options)\n if (!result.parsed) {\n const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)\n err.code = 'MISSING_DATA'\n throw err\n }\n\n // handle scenario for comma separated keys - for use with key rotation\n // example: DOTENV_KEY=\"dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod\"\n const keys = _dotenvKey(options).split(',')\n const length = keys.length\n\n let decrypted\n for (let i = 0; i < length; i++) {\n try {\n // Get full key\n const key = keys[i].trim()\n\n // Get instructions for decrypt\n const attrs = _instructions(result, key)\n\n // Decrypt\n decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)\n\n break\n } catch (error) {\n // last key\n if (i + 1 >= length) {\n throw error\n }\n // try next key\n }\n }\n\n // Parse decrypted .env string\n return DotenvModule.parse(decrypted)\n}\n\nfunction _warn (message) {\n console.error(`[dotenv@${version}][WARN] ${message}`)\n}\n\nfunction _debug (message) {\n console.log(`[dotenv@${version}][DEBUG] ${message}`)\n}\n\nfunction _log (message) {\n console.log(`[dotenv@${version}] ${message}`)\n}\n\nfunction _dotenvKey (options) {\n // prioritize developer directly setting options.DOTENV_KEY\n if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {\n return options.DOTENV_KEY\n }\n\n // secondary infra already contains a DOTENV_KEY environment variable\n if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {\n return process.env.DOTENV_KEY\n }\n\n // fallback to empty string\n return ''\n}\n\nfunction _instructions (result, dotenvKey) {\n // Parse DOTENV_KEY. Format is a URI\n let uri\n try {\n uri = new URL(dotenvKey)\n } catch (error) {\n if (error.code === 'ERR_INVALID_URL') {\n const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n throw error\n }\n\n // Get decrypt key\n const key = uri.password\n if (!key) {\n const err = new Error('INVALID_DOTENV_KEY: Missing key part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get environment\n const environment = uri.searchParams.get('environment')\n if (!environment) {\n const err = new Error('INVALID_DOTENV_KEY: Missing environment part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get ciphertext payload\n const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`\n const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION\n if (!ciphertext) {\n const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)\n err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'\n throw err\n }\n\n return { ciphertext, key }\n}\n\nfunction _vaultPath (options) {\n let possibleVaultPath = null\n\n if (options && options.path && options.path.length > 0) {\n if (Array.isArray(options.path)) {\n for (const filepath of options.path) {\n if (fs.existsSync(filepath)) {\n possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`\n }\n }\n } else {\n possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`\n }\n } else {\n possibleVaultPath = path.resolve(process.cwd(), '.env.vault')\n }\n\n if (fs.existsSync(possibleVaultPath)) {\n return possibleVaultPath\n }\n\n return null\n}\n\nfunction _resolveHome (envPath) {\n return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath\n}\n\nfunction _configVault (options) {\n const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || (options && options.debug))\n const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || (options && options.quiet))\n\n if (debug || !quiet) {\n _log('Loading env from encrypted .env.vault')\n }\n\n const parsed = DotenvModule._parseVault(options)\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsed, options)\n\n return { parsed }\n}\n\nfunction configDotenv (options) {\n const dotenvPath = path.resolve(process.cwd(), '.env')\n let encoding = 'utf8'\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || (options && options.debug))\n let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || (options && options.quiet))\n\n if (options && options.encoding) {\n encoding = options.encoding\n } else {\n if (debug) {\n _debug('No encoding is specified. UTF-8 is used by default')\n }\n }\n\n let optionPaths = [dotenvPath] // default, look for .env\n if (options && options.path) {\n if (!Array.isArray(options.path)) {\n optionPaths = [_resolveHome(options.path)]\n } else {\n optionPaths = [] // reset default\n for (const filepath of options.path) {\n optionPaths.push(_resolveHome(filepath))\n }\n }\n }\n\n // Build the parsed data in a temporary object (because we need to return it). Once we have the final\n // parsed data, we will combine it with process.env (or options.processEnv if provided).\n let lastError\n const parsedAll = {}\n for (const path of optionPaths) {\n try {\n // Specifying an encoding returns a string instead of a buffer\n const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))\n\n DotenvModule.populate(parsedAll, parsed, options)\n } catch (e) {\n if (debug) {\n _debug(`Failed to load ${path} ${e.message}`)\n }\n lastError = e\n }\n }\n\n const populated = DotenvModule.populate(processEnv, parsedAll, options)\n\n // handle user settings DOTENV_CONFIG_ options inside .env file(s)\n debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug)\n quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet)\n\n if (debug || !quiet) {\n const keysCount = Object.keys(populated).length\n const shortPaths = []\n for (const filePath of optionPaths) {\n try {\n const relative = path.relative(process.cwd(), filePath)\n shortPaths.push(relative)\n } catch (e) {\n if (debug) {\n _debug(`Failed to load ${filePath} ${e.message}`)\n }\n lastError = e\n }\n }\n\n _log(`injecting env (${keysCount}) from ${shortPaths.join(',')} ${dim(`-- tip: ${_getRandomTip()}`)}`)\n }\n\n if (lastError) {\n return { parsed: parsedAll, error: lastError }\n } else {\n return { parsed: parsedAll }\n }\n}\n\n// Populates process.env from .env file\nfunction config (options) {\n // fallback to original dotenv if DOTENV_KEY is not set\n if (_dotenvKey(options).length === 0) {\n return DotenvModule.configDotenv(options)\n }\n\n const vaultPath = _vaultPath(options)\n\n // dotenvKey exists but .env.vault file does not exist\n if (!vaultPath) {\n _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)\n\n return DotenvModule.configDotenv(options)\n }\n\n return DotenvModule._configVault(options)\n}\n\nfunction decrypt (encrypted, keyStr) {\n const key = Buffer.from(keyStr.slice(-64), 'hex')\n let ciphertext = Buffer.from(encrypted, 'base64')\n\n const nonce = ciphertext.subarray(0, 12)\n const authTag = ciphertext.subarray(-16)\n ciphertext = ciphertext.subarray(12, -16)\n\n try {\n const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)\n aesgcm.setAuthTag(authTag)\n return `${aesgcm.update(ciphertext)}${aesgcm.final()}`\n } catch (error) {\n const isRange = error instanceof RangeError\n const invalidKeyLength = error.message === 'Invalid key length'\n const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'\n\n if (isRange || invalidKeyLength) {\n const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n } else if (decryptionFailed) {\n const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')\n err.code = 'DECRYPTION_FAILED'\n throw err\n } else {\n throw error\n }\n }\n}\n\n// Populate process.env with parsed values\nfunction populate (processEnv, parsed, options = {}) {\n const debug = Boolean(options && options.debug)\n const override = Boolean(options && options.override)\n const populated = {}\n\n if (typeof parsed !== 'object') {\n const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')\n err.code = 'OBJECT_REQUIRED'\n throw err\n }\n\n // Set process.env\n for (const key of Object.keys(parsed)) {\n if (Object.prototype.hasOwnProperty.call(processEnv, key)) {\n if (override === true) {\n processEnv[key] = parsed[key]\n populated[key] = parsed[key]\n }\n\n if (debug) {\n if (override === true) {\n _debug(`\"${key}\" is already defined and WAS overwritten`)\n } else {\n _debug(`\"${key}\" is already defined and was NOT overwritten`)\n }\n }\n } else {\n processEnv[key] = parsed[key]\n populated[key] = parsed[key]\n }\n }\n\n return populated\n}\n\nconst DotenvModule = {\n configDotenv,\n _configVault,\n _parseVault,\n config,\n decrypt,\n parse,\n populate\n}\n\nmodule.exports.configDotenv = DotenvModule.configDotenv\nmodule.exports._configVault = DotenvModule._configVault\nmodule.exports._parseVault = DotenvModule._parseVault\nmodule.exports.config = DotenvModule.config\nmodule.exports.decrypt = DotenvModule.decrypt\nmodule.exports.parse = DotenvModule.parse\nmodule.exports.populate = DotenvModule.populate\n\nmodule.exports = DotenvModule\n","import WebSocket from 'ws';\nimport type { WebSocketLike } from './types';\n\n/**\n * Creates a WebSocket instance for Node.js using the ws package\n */\nexport function createWebSocket(url: string): WebSocketLike {\n return new WebSocket(url) as WebSocketLike;\n}\n","import { z } from 'zod';\n\n// From/To object schema for WebSocket messages\nexport const MessageParticipantSchema = z.object({\n id: z.string().optional(),\n type: z.string().optional(),\n});\n\nexport type MessageParticipant = z.infer<typeof MessageParticipantSchema>;\n\n// Message schemas for WebSocket communication\nexport const MessageSchema = z.object({\n id: z.string().optional(),\n type: z.string(),\n from: MessageParticipantSchema,\n to: MessageParticipantSchema.optional(),\n payload: z.unknown(),\n});\n\nexport type Message = z.infer<typeof MessageSchema>;\n\nexport const IncomingMessageSchema = z.object({\n id: z.string().optional(),\n type: z.string(),\n from: MessageParticipantSchema,\n to: MessageParticipantSchema.optional(),\n payload: z.unknown(),\n});\n\nexport type IncomingMessage = z.infer<typeof IncomingMessageSchema>;\n\n// Data request/response schemas\nexport const DataRequestPayloadSchema = z.object({\n collection: z.string(),\n op: z.string(),\n params: z.record(z.unknown()).optional(),\n SA_RUNTIME: z.record(z.unknown()).optional(),\n});\n\nexport type DataRequestPayload = z.infer<typeof DataRequestPayloadSchema>;\n\nexport const DataRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('DATA_REQ'),\n payload: DataRequestPayloadSchema,\n});\n\nexport type DataRequestMessage = z.infer<typeof DataRequestMessageSchema>;\n\nexport const AuthLoginRequestPayloadSchema = z.object({\n login_data: z.string(),\n});\n\nexport type AuthLoginRequestPayload = z.infer<typeof AuthLoginRequestPayloadSchema>;\n\nexport const AuthLoginRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('AUTH_LOGIN_REQ'),\n payload: AuthLoginRequestPayloadSchema,\n});\n\nexport type AuthLoginRequestMessage = z.infer<typeof AuthLoginRequestMessageSchema>;\n\nexport const AuthVerifyRequestPayloadSchema = z.object({\n token: z.string(),\n});\n\nexport type AuthVerifyRequestPayload = z.infer<typeof AuthVerifyRequestPayloadSchema>;\n\nexport const AuthVerifyRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('AUTH_VERIFY_REQ'),\n payload: AuthVerifyRequestPayloadSchema,\n});\n\nexport type AuthVerifyRequestMessage = z.infer<typeof AuthVerifyRequestMessageSchema>;\n\nexport const UserPromptRequestPayloadSchema = z.object({\n prompt: z.string(),\n SA_RUNTIME: z.object({\n threadId: z.string(),\n uiBlockId: z.string(),\n }).optional(),\n});\n\nexport type UserPromptRequestPayload = z.infer<typeof UserPromptRequestPayloadSchema>;\n\nexport const UserPromptRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('USER_PROMPT_REQ'),\n payload: UserPromptRequestPayloadSchema,\n});\n\nexport type UserPromptRequestMessage = z.infer<typeof UserPromptRequestMessageSchema>;\n\nexport const UserPromptSuggestionsPayloadSchema = z.object({\n prompt: z.string(),\n limit: z.number().int().positive().default(5),\n});\n\nexport type UserPromptSuggestionsPayload = z.infer<typeof UserPromptSuggestionsPayloadSchema>;\n\nexport const UserPromptSuggestionsMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('USER_PROMPT_SUGGESTIONS_REQ'),\n payload: UserPromptSuggestionsPayloadSchema,\n});\n\nexport type UserPromptSuggestionsMessage = z.infer<typeof UserPromptSuggestionsMessageSchema>;\n\n\nexport const ComponentPropsSchema = z.object({\n query: z.string().optional(),\n title: z.string().optional(),\n description: z.string().optional(),\n config: z.record(z.unknown()).optional(),\n});\n\nexport const ComponentSchema = z.object({\n id: z.string(),\n name: z.string(),\n type: z.string(),\n description: z.string(),\n props: ComponentPropsSchema,\n category: z.string().optional(),\n keywords: z.array(z.string()).optional(),\n});\n\nexport const ComponentsSchema = z.array(ComponentSchema);\n\nexport type Component = z.infer<typeof ComponentSchema>;\n\nexport const ComponentListResponsePayloadSchema = z.object({\n components: z.array(ComponentSchema),\n});\n\nexport type ComponentListResponsePayload = z.infer<typeof ComponentListResponsePayloadSchema>; \n\nexport const ComponentListResponseMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('COMPONENT_LIST_RES'),\n payload: ComponentListResponsePayloadSchema,\n});\n\nexport type ComponentListResponseMessage = z.infer<typeof ComponentListResponseMessageSchema>;\n\n// Admin User Management Request/Response schemas (Unified)\nexport const UsersRequestPayloadSchema = z.object({\n operation: z.enum(['create', 'update', 'delete', 'getAll', 'getOne']),\n data: z.object({\n username: z.string().optional(),\n password: z.string().optional(),\n }).optional(),\n});\n\nexport type UsersRequestPayload = z.infer<typeof UsersRequestPayloadSchema>;\n\nexport const UsersRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('USERS'),\n payload: UsersRequestPayloadSchema,\n});\n\nexport type UsersRequestMessage = z.infer<typeof UsersRequestMessageSchema>;\n\n// UI Logs schema for tracking user request execution\nexport const UILogsPayloadSchema = z.object({\n logs: z.array(z.object({\n timestamp: z.number(),\n level: z.enum(['info', 'error', 'warn', 'debug']),\n message: z.string(),\n type: z.enum(['explanation', 'query', 'general']).optional(),\n data: z.record(z.unknown()).optional(),\n })),\n});\n\nexport type UILogsPayload = z.infer<typeof UILogsPayloadSchema>;\n\nexport const UILogsMessageSchema = z.object({\n id: z.string(), // uiBlockId\n from: MessageParticipantSchema,\n type: z.literal('UI_LOGS'),\n payload: UILogsPayloadSchema,\n});\n\nexport type UILogsMessage = z.infer<typeof UILogsMessageSchema>;\n\n// Actions request schema - for runtime to send component actions and request next questions\nexport const ActionsRequestPayloadSchema = z.object({\n SA_RUNTIME: z.object({\n threadId: z.string(),\n uiBlockId: z.string(),\n }).optional(),\n});\n\nexport type ActionsRequestPayload = z.infer<typeof ActionsRequestPayloadSchema>;\n\nexport const ActionsRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('ACTIONS'),\n payload: ActionsRequestPayloadSchema,\n});\n\nexport type ActionsRequestMessage = z.infer<typeof ActionsRequestMessageSchema>;\n\n// Collection operation types\nexport type CollectionOperation =\n | 'getMany'\n | 'getOne'\n | 'query'\n | 'mutation'\n | 'updateOne'\n | 'deleteOne'\n | 'createOne';\n\nexport type CollectionHandler<TParams = any, TResult = any> = (\n params: TParams\n) => Promise<TResult> | TResult;\n\nexport interface CollectionRegistry {\n [collectionName: string]: {\n [operation: string]: CollectionHandler;\n };\n}\n\nexport type LLMProvider = 'anthropic' | 'groq';\n\nexport interface SuperatomSDKConfig {\n url?: string;\n apiKey: string;\n projectId: string;\n userId?: string;\n type?: string;\n bundleDir?: string;\n promptsDir?: string; // Path to custom prompts directory (defaults to .prompts in SDK)\n ANTHROPIC_API_KEY?: string;\n GROQ_API_KEY?: string;\n LLM_PROVIDERS?: LLMProvider[];\n}\n\n// ==================== Dashboard CRUD Message Schemas ====================\n\n// Import DSL types from dashboards module\nimport { DSLRendererPropsSchema } from './dashboards/types';\nexport type { DSLRendererProps } from './dashboards/types';\n\n// Dashboard CRUD request payload\n\nexport const DashboardsRequestPayloadSchema = z.object({\n operation: z.enum(['create', 'update', 'delete', 'getAll', 'getOne']),\n data: z.object({\n dashboardId: z.string().optional(),\n dashboard: DSLRendererPropsSchema.optional(),\n }).optional(),\n});\n\nexport type DashboardsRequestPayload = z.infer<typeof DashboardsRequestPayloadSchema>;\n\nexport const DashboardsRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('DASHBOARDS'),\n payload: DashboardsRequestPayloadSchema,\n});\n\nexport type DashboardsRequestMessage = z.infer<typeof DashboardsRequestMessageSchema>;\n\n// ==================== Report CRUD Message Schemas ====================\n\n// Import DSL types from reports module\nimport { DSLRendererPropsSchema as ReportDSLRendererPropsSchema } from './reports/types';\nexport type { DSLRendererProps as ReportDSLRendererProps } from './reports/types';\n\n// Report CRUD request payload\nexport const ReportsRequestPayloadSchema = z.object({\n operation: z.enum(['create', 'update', 'delete', 'getAll', 'getOne']),\n data: z.object({\n reportId: z.string().optional(),\n report: ReportDSLRendererPropsSchema.optional(),\n }).optional(),\n});\n\nexport type ReportsRequestPayload = z.infer<typeof ReportsRequestPayloadSchema>;\n\nexport const ReportsRequestMessageSchema = z.object({\n id: z.string(),\n from: MessageParticipantSchema,\n type: z.literal('REPORTS'),\n payload: ReportsRequestPayloadSchema,\n});\n\nexport type ReportsRequestMessage = z.infer<typeof ReportsRequestMessageSchema>;\n\nexport interface WebSocketLike {\n send(data: string): void;\n close(): void;\n addEventListener(event: string, listener: (event: any) => void): void;\n removeEventListener(event: string, listener: (event: any) => void): void;\n readyState: number;\n CONNECTING: number;\n OPEN: number;\n CLOSING: number;\n CLOSED: number;\n}\n\n","import { z } from 'zod';\n\n// ==================== Dashboard DSL Schemas ====================\n\n// Expression schema for dynamic values\nexport const ExpressionSchema = z.object({\n $exp: z.string(),\n $deps: z.array(z.string()).optional(),\n});\n\nexport type Expression = z.infer<typeof ExpressionSchema>;\n\n// Binding schema for data binding\nexport const BindingSchema = z.object({\n $bind: z.string(),\n $transform: z\n .array(\n z.object({\n name: z.string(),\n args: z.array(z.any()).optional(),\n }),\n )\n .optional(),\n});\n\nexport type Binding = z.infer<typeof BindingSchema>;\n\n// For directive schema\nexport const ForDirectiveSchema = z.object({\n in: z.union([ExpressionSchema, BindingSchema, z.string()]),\n as: z.string(),\n key: z.string().optional(),\n index: z.string().optional(),\n});\n\nexport type ForDirective = z.infer<typeof ForDirectiveSchema>;\n\n// Query specification schema\nexport const QuerySpecSchema = z.object({\n graphql: z.string().optional(),\n sql: z.string().optional(),\n variables: z.record(z.string(), z.any()).optional(),\n params: z.record(z.string(), z.any()).optional(),\n key: z.string().optional(),\n refetchPolicy: z\n .enum(['cache-first', 'network-only', 'cache-and-network'])\n .optional(),\n dependencies: z.array(z.string()).optional(),\n});\n\nexport type QuerySpec = z.infer<typeof QuerySpecSchema>;\n\n// UI Element schema\nexport const UIElementSchema: z.ZodType<any> = z.lazy(() =>\n z.object({\n id: z.string(),\n type: z.string(),\n key: z.union([z.string(), ExpressionSchema]).optional(),\n props: z.record(z.string(), z.any()).optional(),\n query: QuerySpecSchema.optional(),\n if: ExpressionSchema.optional(),\n elseIf: ExpressionSchema.optional(),\n for: ForDirectiveSchema.optional(),\n 'link-to': z\n .union([\n z.string(),\n ExpressionSchema,\n BindingSchema,\n z.object({\n ui: z.union([z.string(), ExpressionSchema, BindingSchema]),\n params: z.record(z.string(), z.any()).optional(),\n }),\n ])\n .optional(),\n _meta: z\n .object({\n id: z.string().optional(),\n version: z.string().optional(),\n created: z.string().optional(),\n lastModified: z.string().optional(),\n })\n .optional(),\n children: z.any().optional(),\n else: UIElementSchema.optional(),\n slots: z\n .record(z.string(), z.union([UIElementSchema, z.array(UIElementSchema)]))\n .optional(),\n platform: z\n .object({\n web: z.any().optional(),\n ios: z.any().optional(),\n android: z.any().optional(),\n })\n .optional(),\n })\n);\n\nexport type UIElement = z.infer<typeof UIElementSchema>;\n\n// UI Component schema\nexport const UIComponentSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n props: z.record(z.string(), z.any()).optional(),\n states: z.record(z.string(), z.any()).optional(),\n methods: z\n .record(\n z.string(),\n z.object({\n fn: z.string(),\n params: z.record(z.string(), z.any()).optional(),\n }),\n )\n .optional(),\n effects: z\n .array(\n z.object({\n fn: z.string(),\n deps: z.array(z.string()).optional(),\n }),\n )\n .optional(),\n data: z.record(z.string(), z.any()).optional(),\n render: UIElementSchema,\n query: QuerySpecSchema.optional(),\n});\n\nexport type UIComponent = z.infer<typeof UIComponentSchema>;\n\n// DSL Renderer Props schema\nexport const DSLRendererPropsSchema = z.object({\n dsl: UIComponentSchema,\n data: z.record(z.string(), z.any()).optional(),\n context: z.record(z.string(), z.any()).optional(),\n});\n\nexport type DSLRendererProps = z.infer<typeof DSLRendererPropsSchema>;\n","import { z } from 'zod';\n\n// ==================== Report DSL Schemas ====================\n\n// Expression schema for dynamic values\nexport const ExpressionSchema = z.object({\n $exp: z.string(),\n $deps: z.array(z.string()).optional(),\n});\n\nexport type Expression = z.infer<typeof ExpressionSchema>;\n\n// Binding schema for data binding\nexport const BindingSchema = z.object({\n $bind: z.string(),\n $transform: z\n .array(\n z.object({\n name: z.string(),\n args: z.array(z.any()).optional(),\n }),\n )\n .optional(),\n});\n\nexport type Binding = z.infer<typeof BindingSchema>;\n\n// For directive schema\nexport const ForDirectiveSchema = z.object({\n in: z.union([ExpressionSchema, BindingSchema, z.string()]),\n as: z.string(),\n key: z.string().optional(),\n index: z.string().optional(),\n});\n\nexport type ForDirective = z.infer<typeof ForDirectiveSchema>;\n\n// Query specification schema\nexport const QuerySpecSchema = z.object({\n graphql: z.string().optional(),\n sql: z.string().optional(),\n variables: z.record(z.string(), z.any()).optional(),\n params: z.record(z.string(), z.any()).optional(),\n key: z.string().optional(),\n refetchPolicy: z\n .enum(['cache-first', 'network-only', 'cache-and-network'])\n .optional(),\n dependencies: z.array(z.string()).optional(),\n});\n\nexport type QuerySpec = z.infer<typeof QuerySpecSchema>;\n\n// UI Element schema\nexport const UIElementSchema: z.ZodType<any> = z.lazy(() =>\n z.object({\n id: z.string(),\n type: z.string(),\n key: z.union([z.string(), ExpressionSchema]).optional(),\n props: z.record(z.string(), z.any()).optional(),\n query: QuerySpecSchema.optional(),\n if: ExpressionSchema.optional(),\n elseIf: ExpressionSchema.optional(),\n for: ForDirectiveSchema.optional(),\n 'link-to': z\n .union([\n z.string(),\n ExpressionSchema,\n BindingSchema,\n z.object({\n ui: z.union([z.string(), ExpressionSchema, BindingSchema]),\n params: z.record(z.string(), z.any()).optional(),\n }),\n ])\n .optional(),\n _meta: z\n .object({\n id: z.string().optional(),\n version: z.string().optional(),\n created: z.string().optional(),\n lastModified: z.string().optional(),\n })\n .optional(),\n children: z.any().optional(),\n else: UIElementSchema.optional(),\n slots: z\n .record(z.string(), z.union([UIElementSchema, z.array(UIElementSchema)]))\n .optional(),\n platform: z\n .object({\n web: z.any().optional(),\n ios: z.any().optional(),\n android: z.any().optional(),\n })\n .optional(),\n })\n);\n\nexport type UIElement = z.infer<typeof UIElementSchema>;\n\n// UI Component schema\nexport const UIComponentSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n props: z.record(z.string(), z.any()).optional(),\n states: z.record(z.string(), z.any()).optional(),\n methods: z\n .record(\n z.string(),\n z.object({\n fn: z.string(),\n params: z.record(z.string(), z.any()).optional(),\n }),\n )\n .optional(),\n effects: z\n .array(\n z.object({\n fn: z.string(),\n deps: z.array(z.string()).optional(),\n }),\n )\n .optional(),\n data: z.record(z.string(), z.any()).optional(),\n render: UIElementSchema,\n query: QuerySpecSchema.optional(),\n});\n\nexport type UIComponent = z.infer<typeof UIComponentSchema>;\n\n// DSL Renderer Props schema\nexport const DSLRendererPropsSchema = z.object({\n dsl: UIComponentSchema,\n data: z.record(z.string(), z.any()).optional(),\n context: z.record(z.string(), z.any()).optional(),\n});\n\nexport type DSLRendererProps = z.infer<typeof DSLRendererPropsSchema>;\n","const PREFIX = '[SuperatomSDK]';\n\nexport const logger = {\n info: (...args: any[]) => {\n console.log(PREFIX, ...args);\n },\n\n error: (...args: any[]) => {\n console.error(PREFIX, ...args);\n },\n\n warn: (...args: any[]) => {\n console.warn(PREFIX, ...args);\n },\n\n debug: (...args: any[]) => {\n console.log(PREFIX, '[DEBUG]', ...args);\n },\n};\n","import { randomUUID } from 'crypto';\nimport { logger } from '../utils/logger';\nimport { STORAGE_CONFIG } from '../config/storage';\nimport { Action } from './action';\n\n/**\n * UIBlock represents a single user and assistant message block in a thread\n * Contains user question, component metadata, component data, and available actions\n */\nexport class UIBlock {\n private id: string;\n private userQuestion: string;\n private generatedComponentMetadata: Record<string, any>;\n private componentData: Record<string, any>;\n private actions: Action[] | null | Promise<Action[]>;\n private createdAt: Date;\n\n /**\n * Creates a new UIBlock instance\n * @param userQuestion - The user's question or input\n * @param componentData - The component data object\n * @param generatedComponentMetadata - Optional metadata about the generated component\n * @param actions - Optional array of available actions\n * @param id - Optional custom ID, generates UUID if not provided\n */\n constructor(\n userQuestion: string,\n componentData: Record<string, any> = {},\n generatedComponentMetadata: Record<string, any> = {},\n actions: Action[] = [],\n id?: string\n ) {\n this.id = id || randomUUID();\n this.userQuestion = userQuestion;\n this.componentData = componentData;\n this.generatedComponentMetadata = generatedComponentMetadata;\n this.actions = actions;\n this.createdAt = new Date();\n }\n\n /**\n * Get the UIBlock ID\n */\n getId(): string {\n return this.id;\n }\n\n /**\n * Get the user question\n */\n getUserQuestion(): string {\n return this.userQuestion;\n }\n\n /**\n * Set or update the user question\n */\n setUserQuestion(question: string): void {\n this.userQuestion = question;\n }\n\n /**\n * Get component metadata\n */\n getComponentMetadata(): Record<string, any> {\n return this.generatedComponentMetadata;\n }\n\n /**\n * Set or update component metadata\n */\n setComponentMetadata(metadata: Record<string, any>): void {\n this.generatedComponentMetadata = { ...this.generatedComponentMetadata, ...metadata };\n }\n\n /**\n * Get component data\n */\n getComponentData(): Record<string, any> {\n return this.componentData;\n }\n\n /**\n * Calculate size of data in bytes\n */\n private getDataSizeInBytes(data: any): number {\n try {\n const jsonString = JSON.stringify(data);\n return Buffer.byteLength(jsonString, 'utf8');\n } catch (error) {\n logger.error('Error calculating data size:', error);\n return 0;\n }\n }\n\n /**\n * Limit array data to maximum rows\n */\n private limitArrayData(data: any[]): { data: any[]; metadata: any } {\n const totalRows = data.length;\n const limitedData = data.slice(0, STORAGE_CONFIG.MAX_ROWS_PER_BLOCK);\n\n return {\n data: limitedData,\n metadata: {\n totalRows,\n storedRows: limitedData.length,\n isTruncated: totalRows > STORAGE_CONFIG.MAX_ROWS_PER_BLOCK,\n },\n };\n }\n\n /**\n * Check if data exceeds size limit\n */\n private exceedsSizeLimit(data: any): boolean {\n const size = this.getDataSizeInBytes(data);\n return size > STORAGE_CONFIG.MAX_SIZE_PER_BLOCK_BYTES;\n }\n\n /**\n * Process and limit data before storing\n */\n private processDataForStorage(data: any): any {\n // If data is an array, limit rows\n if (Array.isArray(data)) {\n const { data: limitedData, metadata } = this.limitArrayData(data);\n\n // Check size after limiting rows\n const size = this.getDataSizeInBytes(limitedData);\n\n logger.info(\n `UIBlock ${this.id}: Storing ${metadata.storedRows}/${metadata.totalRows} rows (${(size / 1024).toFixed(2)} KB)`\n );\n\n // If still too large, store only metadata\n if (this.exceedsSizeLimit(limitedData)) {\n logger.warn(\n `UIBlock ${this.id}: Data too large (${(size / 1024 / 1024).toFixed(2)} MB), storing metadata only`\n );\n return {\n ...metadata,\n preview: limitedData.slice(0, 3), // Store only first 3 rows as preview\n dataTooLarge: true,\n };\n }\n\n return {\n data: limitedData,\n ...metadata,\n };\n }\n\n // For non-array data, check size\n const size = this.getDataSizeInBytes(data);\n\n if (this.exceedsSizeLimit(data)) {\n logger.warn(\n `UIBlock ${this.id}: Data too large (${(size / 1024 / 1024).toFixed(2)} MB), storing summary only`\n );\n return {\n dataTooLarge: true,\n dataType: typeof data,\n keys: typeof data === 'object' ? Object.keys(data) : undefined,\n };\n }\n\n return data;\n }\n\n /**\n * Set or update component data with size and row limits\n */\n setComponentData(data: Record<string, any>): void {\n const processedData = this.processDataForStorage(data);\n this.componentData = { ...this.componentData, ...processedData };\n }\n\n /**\n * Get all actions (only if they are resolved, not if fetching)\n */\n getActions(): Action[] | null | Promise<Action[]> {\n return this.actions;\n }\n\n /**\n * Get or fetch actions\n * If actions don't exist or are a Promise, calls the generateFn and stores the promise\n * If actions already exist, returns them\n * @param generateFn - Async function to generate actions\n * @returns Promise resolving to Action[]\n */\n async getOrFetchActions(generateFn: () => Promise<Action[]>): Promise<Action[]> {\n // If actions already exist and are not a Promise, return them\n\n if (this.actions && !(this.actions instanceof Promise) && Array.isArray(this.actions) && this.actions.length > 0) {\n return this.actions;\n }\n\n // If already fetching, cancel and start new fetch\n // Set new promise for fetching\n const fetchPromise = generateFn();\n this.actions = fetchPromise;\n\n try {\n // Wait for the promise to resolve\n const resolvedActions = await fetchPromise;\n // Store the resolved actions\n logger.info(`Fetched ${resolvedActions.length} actions for UIBlock: ${this.id}`);\n this.actions = resolvedActions;\n return resolvedActions;\n } catch (error) {\n // If generation fails, reset to null\n this.actions = null;\n throw error;\n }\n }\n\n /**\n * Add a single action (only if actions are resolved)\n */\n addAction(action: Action): void {\n if (this.actions && Array.isArray(this.actions)) {\n this.actions.push(action);\n }\n }\n\n /**\n * Add multiple actions (only if actions are resolved)\n */\n addActions(actions: Action[]): void {\n if (this.actions && Array.isArray(this.actions)) {\n this.actions.push(...actions);\n }\n }\n\n /**\n * Remove an action by ID (only if actions are resolved)\n */\n removeAction(actionId: string): boolean {\n if (this.actions && Array.isArray(this.actions)) {\n const index = this.actions.findIndex(a => a.id === actionId);\n if (index > -1) {\n this.actions.splice(index, 1);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Clear all actions\n */\n clearActions(): void {\n this.actions = null;\n }\n\n /**\n * Get creation timestamp\n */\n getCreatedAt(): Date {\n return this.createdAt;\n }\n\n /**\n * Convert UIBlock to JSON-serializable object\n */\n toJSON(): Record<string, any> {\n // Handle Promise case for serialization\n let actionsValue: Action[] | null = null;\n if (this.actions && !(this.actions instanceof Promise) && Array.isArray(this.actions)) {\n actionsValue = this.actions;\n }\n\n return {\n id: this.id,\n userQuestion: this.userQuestion,\n generatedComponentMetadata: this.generatedComponentMetadata,\n componentData: this.componentData,\n actions: actionsValue,\n isFetchingActions: this.actions instanceof Promise,\n createdAt: this.createdAt.toISOString(),\n };\n }\n}\n","/**\n * Configuration for data storage limits in UIBlocks\n */\nexport const STORAGE_CONFIG = {\n /**\n * Maximum number of rows to store in UIBlock data\n */\n MAX_ROWS_PER_BLOCK: 10,\n\n /**\n * Maximum size in bytes per UIBlock (1MB)\n */\n MAX_SIZE_PER_BLOCK_BYTES: 1 * 1024 * 1024, // 1MB\n\n /**\n * Number of days to keep threads before cleanup\n */\n THREAD_RETENTION_DAYS: 7,\n\n /**\n * Number of days to keep UIBlocks before cleanup\n */\n UIBLOCK_RETENTION_DAYS: 7,\n};\n","import { randomUUID } from 'crypto';\nimport { UIBlock } from './uiblock';\n\n/**\n * Thread represents a conversation thread containing multiple UIBlocks\n * Each UIBlock in a thread represents a user question and assistant response pair\n */\nexport class Thread {\n private id: string;\n private uiblocks: Map<string, UIBlock>;\n private createdAt: Date;\n\n /**\n * Creates a new Thread instance\n * @param id - Optional custom ID, generates UUID if not provided\n */\n constructor(id?: string) {\n this.id = id || randomUUID();\n this.uiblocks = new Map();\n this.createdAt = new Date();\n }\n\n /**\n * Get the thread ID\n */\n getId(): string {\n return this.id;\n }\n\n /**\n * Add a UIBlock to the thread\n */\n addUIBlock(uiblock: UIBlock): void {\n this.uiblocks.set(uiblock.getId(), uiblock);\n }\n\n /**\n * Get a UIBlock by ID\n */\n getUIBlock(id: string): UIBlock | undefined {\n return this.uiblocks.get(id);\n }\n\n /**\n * Get all UIBlocks in the thread\n */\n getUIBlocks(): UIBlock[] {\n return Array.from(this.uiblocks.values());\n }\n\n /**\n * Get UIBlocks as a Map\n */\n getUIBlocksMap(): Map<string, UIBlock> {\n return new Map(this.uiblocks);\n }\n\n /**\n * Remove a UIBlock by ID\n */\n removeUIBlock(id: string): boolean {\n return this.uiblocks.delete(id);\n }\n\n /**\n * Check if UIBlock exists\n */\n hasUIBlock(id: string): boolean {\n return this.uiblocks.has(id);\n }\n\n /**\n * Get number of UIBlocks in the thread\n */\n getUIBlockCount(): number {\n return this.uiblocks.size;\n }\n\n /**\n * Clear all UIBlocks from the thread\n */\n clear(): void {\n this.uiblocks.clear();\n }\n\n /**\n * Get creation timestamp\n */\n getCreatedAt(): Date {\n return this.createdAt;\n }\n\n /**\n * Get conversation context from recent UIBlocks (excluding current one)\n * Returns formatted string with previous questions and component summaries\n * @param limit - Maximum number of previous UIBlocks to include (default: 5)\n * @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)\n * @returns Formatted conversation history string\n */\n getConversationContext(limit: number = 5, currentUIBlockId?: string): string {\n if (limit === 0) {\n return '';\n }\n\n // Get all UIBlocks sorted by creation time (oldest first)\n const allBlocks = Array.from(this.uiblocks.values())\n .filter(block => !currentUIBlockId || block.getId() !== currentUIBlockId)\n .sort((a, b) => a.getCreatedAt().getTime() - b.getCreatedAt().getTime());\n\n if (allBlocks.length === 0) {\n return '';\n }\n\n // Take the last N blocks (most recent)\n const recentBlocks = allBlocks.slice(-limit);\n\n // Format as conversation history\n const contextLines: string[] = [];\n\n recentBlocks.forEach((block, index) => {\n const questionNum = index + 1;\n const question = block.getUserQuestion();\n const metadata = block.getComponentMetadata();\n\n // Build component summary\n let componentSummary = 'No component generated';\n if (metadata && Object.keys(metadata).length > 0) {\n const parts: string[] = [];\n\n if (metadata.type) {\n parts.push(`Component Type: ${metadata.type}`);\n }\n if (metadata.name) {\n parts.push(`Name: ${metadata.name}`);\n }\n if (metadata.props?.title) {\n parts.push(`Title: \"${metadata.props.title}\"`);\n }\n if (metadata.props?.query) {\n // Truncate long queries\n const query = metadata.props.query;\n const truncatedQuery = query.length > 200 ? query.substring(0, 200) + '...' : query;\n parts.push(`Query: ${truncatedQuery}`);\n }\n if (metadata.props?.config?.components && Array.isArray(metadata.props.config.components)) {\n // Multi-component container\n const componentTypes = metadata.props.config.components.map((c: any) => c.type).join(', ');\n parts.push(`Multi-component with: ${componentTypes}`);\n }\n\n componentSummary = parts.join(', ');\n }\n\n contextLines.push(`Q${questionNum}: ${question}`);\n contextLines.push(`A${questionNum}: ${componentSummary}`);\n contextLines.push(''); // Empty line for readability\n });\n\n return contextLines.join('\\n').trim();\n }\n\n /**\n * Convert Thread to JSON-serializable object\n */\n toJSON(): Record<string, any> {\n return {\n id: this.id,\n uiblocks: Array.from(this.uiblocks.values()).map(block => block.toJSON()),\n createdAt: this.createdAt.toISOString(),\n };\n }\n}\n","import { Thread } from './thread';\nimport { UIBlock } from './uiblock';\n\n/**\n * ThreadManager manages all threads globally\n * Provides methods to create, retrieve, and delete threads\n */\nexport class ThreadManager {\n private static instance: ThreadManager;\n private threads: Map<string, Thread>;\n\n private constructor() {\n this.threads = new Map();\n\n // Initialize cleanup service\n // new CleanupService(this.threads);\n }\n\n /**\n * Get singleton instance of ThreadManager\n */\n static getInstance(): ThreadManager {\n if (!ThreadManager.instance) {\n ThreadManager.instance = new ThreadManager();\n }\n return ThreadManager.instance;\n }\n\n /**\n * Create a new thread\n * @param id - Optional custom ID, generates UUID if not provided\n * @returns The created Thread instance\n */\n createThread(id?: string): Thread {\n const thread = new Thread(id);\n this.threads.set(thread.getId(), thread);\n return thread;\n }\n\n /**\n * Get a thread by ID\n */\n getThread(id: string): Thread | undefined {\n return this.threads.get(id);\n }\n\n /**\n * Get all threads\n */\n getAllThreads(): Thread[] {\n return Array.from(this.threads.values());\n }\n\n /**\n * Get threads as a Map\n */\n getThreadsMap(): Map<string, Thread> {\n return new Map(this.threads);\n }\n\n /**\n * Delete a thread by ID\n */\n deleteThread(id: string): boolean {\n return this.threads.delete(id);\n }\n\n /**\n * Check if thread exists\n */\n hasThread(id: string): boolean {\n return this.threads.has(id);\n }\n\n /**\n * Get number of threads\n */\n getThreadCount(): number {\n return this.threads.size;\n }\n\n /**\n * Clear all threads\n */\n clearAll(): void {\n this.threads.clear();\n }\n\n /**\n * Find a UIBlock by ID across all threads\n * @param uiBlockId - The UIBlock ID to search for\n * @returns Object with thread and uiBlock if found, undefined otherwise\n */\n findUIBlockById(uiBlockId: string): { thread: Thread; uiBlock: UIBlock } | undefined {\n for (const thread of this.threads.values()) {\n const uiBlock = thread.getUIBlock(uiBlockId);\n if (uiBlock) {\n return { thread, uiBlock };\n }\n }\n return undefined;\n }\n\n /**\n * Convert all threads to JSON-serializable object\n */\n toJSON(): Record<string, any> {\n return {\n threads: Array.from(this.threads.values()).map(thread => thread.toJSON()),\n count: this.threads.size,\n };\n }\n}\n","import { DataRequestMessageSchema, type CollectionRegistry, type Message } from '../types';\nimport { logger } from '../utils/logger';\nimport { ThreadManager } from '../threads';\n\n/**\n * Handle incoming data_req messages and execute collection handlers\n */\nexport async function handleDataRequest(\n data: any,\n collections: CollectionRegistry,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const dataRequest = DataRequestMessageSchema.parse(data);\n const { id, payload } = dataRequest;\n const { collection, op, params, SA_RUNTIME } = payload;\n\n // Check if collection and operation exist\n if (!collections[collection]) {\n sendDataResponse(id, collection, op, null, {\n error: `Collection '${collection}' not found`,\n }, sendMessage);\n return;\n }\n\n if (!collections[collection][op]) {\n sendDataResponse(id, collection, op, null, {\n error: `Operation '${op}' not found for collection '${collection}'`,\n }, sendMessage);\n return;\n }\n\n // Execute the handler and measure execution time\n const startTime = performance.now();\n const handler = collections[collection][op];\n const result = await handler(params || {});\n const executionMs = Math.round(performance.now() - startTime);\n\n logger.info(`Executed ${collection}.${op} in ${executionMs}ms`);\n\n // Update UIBlock with component data if SA_RUNTIME has uiBlockId\n if (SA_RUNTIME && typeof SA_RUNTIME === 'object' && 'uiBlockId' in SA_RUNTIME) {\n const uiBlockId = (SA_RUNTIME as any).uiBlockId;\n const threadId = (SA_RUNTIME as any).threadId;\n\n const threadManager = ThreadManager.getInstance();\n let uiBlock = null;\n let thread = null;\n\n // If threadId is provided, get the specific thread\n if (threadId) {\n thread = threadManager.getThread(threadId);\n if (thread) {\n uiBlock = thread.getUIBlock(uiBlockId);\n }\n } else {\n // Otherwise search across all threads\n const result = threadManager.findUIBlockById(uiBlockId);\n if (result) {\n thread = result.thread;\n uiBlock = result.uiBlock;\n }\n }\n\n // Update UIBlock's componentData with the response\n if (uiBlock) {\n uiBlock.setComponentData(result || {});\n logger.info(`Updated UIBlock ${uiBlockId} with component data from ${collection}.${op}`);\n } else {\n logger.warn(`UIBlock ${uiBlockId} not found in threads`);\n }\n }\n\n // Send response\n sendDataResponse(id, collection, op, result, { executionMs }, sendMessage);\n } catch (error) {\n logger.error('Failed to handle data request:', error);\n // Not a data_req message or invalid format\n }\n}\n\n/**\n * Send a data_res response message\n */\nfunction sendDataResponse(\n id: string,\n collection: string,\n op: string,\n data: any,\n meta: { executionMs?: number; error?: string },\n sendMessage: (message: Message) => void\n): void {\n const response: Message = {\n id,\n from: { type: 'data-agent' },\n type: 'DATA_RES',\n payload: {\n collection,\n op,\n data,\n ...meta,\n },\n };\n\n sendMessage(response);\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport { logger } from './utils/logger';\n\n/**\n * Get the bundle directory from config or environment variable\n */\nexport function getBundleDir(configDir?: string): string {\n const bundleDir = configDir || process.env.SA_BUNDLE_DIR;\n\n if (!bundleDir) {\n throw new Error(\n 'Bundle directory not configured. Please provide bundleDir in config or set SA_BUNDLE_DIR environment variable.'\n );\n }\n\n return bundleDir;\n}\n\n/**\n * Load the JavaScript bundle from the configured directory\n */\nexport function getJS(bundleDir: string): string {\n try {\n // Check if directory exists\n if (!fs.existsSync(bundleDir)) {\n throw new Error(`Bundle directory does not exist: ${bundleDir}`);\n }\n\n // Check if it's actually a directory\n const stats = fs.statSync(bundleDir);\n if (!stats.isDirectory()) {\n throw new Error(`Bundle path is not a directory: ${bundleDir}`);\n }\n\n // Read directory contents\n let files: string[];\n try {\n files = fs.readdirSync(bundleDir);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read bundle directory: ${errorMessage}`);\n }\n\n // Find the bundle file\n const indexFile = files.find((file) => file.startsWith('index-') && file.endsWith('.js'));\n\n if (!indexFile) {\n logger.warn(`Available files in ${bundleDir}:`, files);\n throw new Error(\n `Could not find index-*.js file in ${bundleDir}. ` +\n `Expected a file matching pattern: index-*.js`\n );\n }\n\n // Read the bundle file\n const filePath = path.join(bundleDir, indexFile);\n logger.info(`Loading bundle from ${filePath}`);\n\n try {\n return fs.readFileSync(filePath, 'utf8');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read bundle file: ${errorMessage}`);\n }\n } catch (error) {\n if (error instanceof Error) {\n logger.error('Failed to load bundle:', error.message);\n } else {\n logger.error('Failed to load bundle:', error);\n }\n throw error;\n }\n}\n","import { getJS, getBundleDir } from '../bundle';\nimport { logger } from '../utils/logger';\nimport type { Message } from '../types';\n\nconst CHUNK_SIZE = 900 * 1024; // 900 KB chunks (leaving room for metadata, max 1MB per message)\n\n/**\n * Handle incoming bundle_req messages and send chunked bundle response\n */\nexport async function handleBundleRequest(\n data: any,\n bundleDir: string | undefined,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const id = data.id || 'unknown';\n const fromId = data.from?.id;\n\n // Get bundle directory and load bundle\n const dir = getBundleDir(bundleDir);\n const js = getJS(dir);\n const bundleSize = Buffer.byteLength(js, 'utf8');\n\n logger.info(`Bundle size: ${(bundleSize / 1024).toFixed(2)} KB`);\n\n // Split bundle into chunks\n const totalChunks = Math.ceil(bundleSize / CHUNK_SIZE);\n logger.info(`Splitting bundle into ${totalChunks} chunks`);\n\n for (let i = 0; i < totalChunks; i++) {\n const start = i * CHUNK_SIZE;\n const end = Math.min(start + CHUNK_SIZE, js.length);\n const chunk = js.substring(start, end);\n const isComplete = i === totalChunks - 1;\n const progress = ((i + 1) / totalChunks) * 100;\n\n const chunkMessage: Message = {\n id: `${id}-chunk-${i}`,\n type: 'BUNDLE_CHUNK',\n from: { type: 'data-agent' },\n to: fromId ? { id: fromId } : undefined,\n payload: {\n chunk: chunk,\n chunkIndex: i,\n totalChunks: totalChunks,\n isComplete: isComplete,\n progress: parseFloat(progress.toFixed(2)),\n },\n };\n\n sendMessage(chunkMessage);\n logger.debug(`Sent chunk ${i + 1}/${totalChunks} (${progress.toFixed(2)}%)`);\n }\n\n logger.info('Bundle sending complete');\n } catch (error) {\n logger.error('Failed to handle bundle request:', error);\n\n // Send error response\n const errorMessage: Message = {\n id: data.id || 'unknown',\n type: 'BUNDLE_RES',\n from: { type: 'data-agent' },\n to: data.from?.id ? { id: data.from.id } : undefined,\n payload: {\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n };\n\n sendMessage(errorMessage);\n }\n}\n","import crypto from 'crypto';\n\n/**\n * Decode base64 encoded string and parse JSON\n * @param base64Data - Base64 encoded string\n * @returns Parsed JSON object\n */\nexport function decodeBase64ToJson(base64Data: string): any {\n try {\n const decodedString = Buffer.from(base64Data, 'base64').toString('utf-8');\n return JSON.parse(decodedString);\n } catch (error) {\n throw new Error(`Failed to decode base64 data: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n}\n\n/**\n * Hash password using SHA1\n * @param password - Plain text password\n * @returns SHA1 hashed password\n */\nexport function hashPassword(password: string): string {\n return crypto.createHash('sha1').update(password).digest('hex');\n}\n","import { UserManager, type User, type UsersData } from './user-manager';\nimport { logger } from '../utils/logger';\n\n// Global reference to the current SDK's UserManager instance\nlet currentUserManager: UserManager | null = null;\n\n/**\n * Set the UserManager instance (called by SuperatomSDK during initialization)\n * This should be called with the SDK's UserManager instance\n * @param userManager - UserManager instance from SuperatomSDK\n */\nexport function setUserManager(userManager: UserManager): void {\n if (!userManager) {\n throw new Error('userManager cannot be null');\n }\n currentUserManager = userManager;\n logger.debug('UserManager instance set');\n}\n\n/**\n * Get the current UserManager instance\n */\nexport function getUserManager(): UserManager {\n if (!currentUserManager) {\n throw new Error(\n 'UserManager not initialized. Make sure SuperatomSDK is initialized before using user storage.'\n );\n }\n return currentUserManager;\n}\n\n/**\n * Load users from memory (UserManager maintains the cache)\n * @returns UsersData object containing all users\n */\nexport function loadUsers(): UsersData {\n const manager = getUserManager();\n return {\n users: manager.getAllUsers()\n };\n}\n\n/**\n * Save users to file immediately (forces sync)\n * @param usersData - UsersData object to save\n */\nexport async function saveUsers(usersData: UsersData): Promise<void> {\n const manager = getUserManager();\n\n // Clear existing users and repopulate\n manager.deleteAllUsers();\n\n // Add all users from the provided data\n for (const user of usersData.users) {\n try {\n manager.createUser(user);\n } catch (error) {\n // User might already exist, update instead\n if (manager.userExists(user.username)) {\n manager.updateUser(user.username, user);\n }\n }\n }\n\n // Force immediate sync to file\n await manager.forceSync();\n}\n\n/**\n * Find a user by username\n * @param username - Username to search for\n * @returns User object if found, null otherwise\n */\nexport function findUserByUsername(username: string): User | null {\n const manager = getUserManager();\n const user = manager.getUser(username);\n return user || null;\n}\n\n/**\n * Add WebSocket ID to a user's wsIds array\n * @param username - Username to update\n * @param wsId - WebSocket ID to add\n * @returns true if successful, false otherwise\n */\nexport function addWsIdToUser(username: string, wsId: string): boolean {\n try {\n const manager = getUserManager();\n return manager.addWsId(username, wsId);\n } catch (error) {\n logger.error('Error adding WebSocket ID:', error);\n return false;\n }\n}\n\n/**\n * Remove WebSocket ID from a user's wsIds array\n * @param username - Username to update\n * @param wsId - WebSocket ID to remove\n * @returns true if successful, false otherwise\n */\nexport function removeWsIdFromUser(username: string, wsId: string): boolean {\n try {\n const manager = getUserManager();\n return manager.removeWsId(username, wsId);\n } catch (error) {\n logger.error('Error removing WebSocket ID:', error);\n return false;\n }\n}\n\n/**\n * Cleanup and destroy the UserManager\n */\nexport async function cleanupUserStorage(): Promise<void> {\n if (currentUserManager) {\n await currentUserManager.destroy();\n currentUserManager = null;\n logger.info('UserManager cleaned up');\n }\n}\n\n// Export types\nexport type { User, UsersData } from './user-manager';\n","import { findUserByUsername, addWsIdToUser } from \"./user-storage\";\nimport { hashPassword } from \"./utils\";\nimport { logger } from \"../utils/logger\";\n\nexport interface LoginCredentials {\n username: string;\n password: string;\n}\n\nexport interface ValidationResult {\n success: boolean;\n error?: string;\n data?: any;\n username?: string;\n}\n\n/**\n * Validate user credentials against stored user data\n * @param credentials - Login credentials with username and password\n * @returns ValidationResult indicating success or failure\n */\nexport function validateUser(credentials: LoginCredentials): ValidationResult {\n const { username, password } = credentials;\n\n // Check if username and password are provided\n if (!username || !password) {\n logger.warn('Validation failed: Username and password are required');\n return {\n success: false,\n error: 'Username and password are required'\n };\n }\n\n // Find user by username from in-memory cache\n const user = findUserByUsername(username);\n\n if (!user) {\n logger.warn(`Validation failed: User not found - ${username}`);\n return {\n success: false,\n error: 'Invalid username'\n };\n }\n\n // Hash the stored password and compare with provided password\n const hashedPassword = hashPassword(user.password);\n\n if (hashedPassword !== password) {\n logger.warn(`Validation failed: Invalid password for user - ${username}`);\n return {\n success: false,\n error: 'Invalid password'\n };\n }\n\n logger.debug(`User validated successfully: ${username}`);\n return {\n success: true,\n data: user.username\n };\n}\n\n/**\n * Authenticate user and store WebSocket ID\n * Uses UserManager's in-memory cache with automatic file sync\n * @param credentials - Login credentials\n * @param wsId - WebSocket ID to store\n * @returns ValidationResult with authentication status\n */\nexport function authenticateAndStoreWsId(credentials: LoginCredentials, wsId: string): ValidationResult {\n const validationResult = validateUser(credentials);\n\n if (!validationResult.success) {\n return validationResult;\n }\n\n // Store wsId in user's wsIds array using UserManager\n // Changes are automatically synced to file via setInterval\n const stored = addWsIdToUser(credentials.username, wsId);\n\n if (!stored) {\n logger.error(`Failed to store WebSocket ID for user: ${credentials.username}`);\n return {\n success: false,\n error: 'Failed to store user session'\n };\n }\n\n logger.info(`WebSocket ID stored for user: ${credentials.username}`);\n return validationResult;\n}\n\n/**\n * Verify authentication token\n * @param authToken - Base64 encoded auth token containing username and password\n * @returns ValidationResult indicating if token is valid\n */\nexport function verifyAuthToken(authToken: string): ValidationResult {\n try {\n // Decode base64 token\n const decodedString = Buffer.from(authToken, 'base64').toString('utf-8');\n const credentials = JSON.parse(decodedString);\n\n logger.debug('Token decoded and parsed successfully');\n // Validate credentials\n return validateUser(credentials);\n } catch (error) {\n logger.error('Failed to verify auth token:', error);\n return {\n success: false,\n error: 'Invalid token format'\n };\n }\n}\n","import { decodeBase64ToJson } from \"../auth/utils\";\nimport { authenticateAndStoreWsId } from \"../auth/validator\";\nimport { AuthLoginRequestMessageSchema, Message } from \"../types\";\nimport { logger } from \"../utils/logger\";\n\n\n\nexport async function handleAuthLoginRequest(\n data: any,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const authRequest = AuthLoginRequestMessageSchema.parse(data);\n const { id, payload } = authRequest;\n \n const login_data = payload.login_data;\n\n const wsId = authRequest.from.id ;\n\n if(!login_data){\n sendDataResponse(id, {\n success: false,\n error: 'Login data not found'\n }, sendMessage, wsId);\n return;\n }\n\n\n // Decode base64 data and parse JSON\n let loginData: any;\n try {\n loginData = decodeBase64ToJson(login_data);\n } catch (error) {\n sendDataResponse(id, {\n success: false,\n error: 'Invalid login data format'\n }, sendMessage, wsId);\n return;\n }\n\n // Extract username and password from decoded data\n const { username, password } = loginData;\n\n if (!username) {\n sendDataResponse(id, {\n success: false,\n error: 'Username not found in login data'\n }, sendMessage, wsId);\n return;\n }\n\n if (!password) {\n sendDataResponse(id, {\n success: false,\n error: 'Password not found in login data'\n }, sendMessage, wsId);\n return;\n }\n\n\n if(!wsId){\n sendDataResponse(id, {\n success: false,\n error: 'WebSocket ID not found'\n }, sendMessage, wsId);\n return;\n }\n\n // Authenticate user and store wsId\n const authResult = authenticateAndStoreWsId(\n { username, password },\n wsId\n );\n\n // Send response\n\n sendDataResponse(id, authResult, sendMessage, wsId);\n return ;\n }\n catch (error) {\n logger.error('Failed to handle auth login request:', error);\n }\n}\n\n\n/**\n * Send a data_res response message\n */\nfunction sendDataResponse(\n id: string,\n res: {success: boolean; error?: string; data?: any},\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id,\n type: 'AUTH_LOGIN_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: clientId\n },\n payload:{\n ...res,\n }\n };\n\n sendMessage(response);\n}\n\n","import { verifyAuthToken } from \"../auth/validator\";\nimport { AuthVerifyRequestMessageSchema, Message } from \"../types\";\nimport { logger } from \"../utils/logger\";\n\n\nexport async function handleAuthVerifyRequest(\n data: any,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const authRequest = AuthVerifyRequestMessageSchema.parse(data);\n const { id, payload } = authRequest;\n \n const token = payload.token;\n\n const wsId = authRequest.from.id ;\n\n if(!token){\n sendDataResponse(id, {\n success: false,\n error: 'Token not found'\n }, sendMessage, wsId);\n return;\n }\n\n\n if(!wsId){\n sendDataResponse(id, {\n success: false,\n error: 'WebSocket ID not found'\n }, sendMessage, wsId);\n return;\n }\n\n // Verify token\n const authResult = verifyAuthToken(token);\n\n // Send response\n sendDataResponse(id, authResult, sendMessage, wsId);\n return ;\n }\n catch (error) {\n logger.error('Failed to handle auth verify request:', error);\n }\n}\n\n/**\n * Send a data_res response message\n */\nfunction sendDataResponse(\n id: string,\n res: {success: boolean; error?: string; data?: any},\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void { \n const response: Message = {\n id,\n type: 'AUTH_VERIFY_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: clientId\n },\n payload:{\n ...res,\n }\n };\n\n sendMessage(response);\n} ","import dotenv from 'dotenv';\nimport { BaseLLM, BaseLLMConfig } from './base-llm';\n\ndotenv.config();\n\nexport interface GroqLLMConfig extends BaseLLMConfig {}\n\n/**\n * GroqLLM class for handling AI-powered component generation and matching using Groq\n */\nexport class GroqLLM extends BaseLLM {\n\tconstructor(config?: GroqLLMConfig) {\n\t\tsuper(config);\n\t}\n\n\tprotected getDefaultModel(): string {\n\t\treturn 'groq/openai/gpt-oss-120b';\n\t}\n\n\tprotected getDefaultApiKey(): string | undefined {\n\t\treturn process.env.GROQ_API_KEY;\n\t}\n\n\tprotected getProviderName(): string {\n\t\treturn 'Groq';\n\t}\n}\n\n// Export a singleton instance\nexport const groqLLM = new GroqLLM();\n","/**\n * Converts T-SQL TOP syntax to Snowflake LIMIT syntax\n * Snowflake doesn't support TOP keyword - it must use LIMIT\n * @param query - The SQL query to check\n * @returns The query with TOP converted to LIMIT\n */\nexport function convertTopToLimit(query: string): string {\n\tif (!query || query.trim().length === 0) {\n\t\treturn query;\n\t}\n\n\t// Replace \"TOP N\" with nothing (we'll add LIMIT at the end)\n\t// Pattern: SELECT TOP number or SELECT TOP (number)\n\tlet modifiedQuery = query.replace(/\\bSELECT\\s+TOP\\s+(\\d+)\\b/gi, 'SELECT');\n\n\tif (modifiedQuery !== query) {\n\t\tconsole.warn(`⚠️ Query had TOP syntax. Converting to LIMIT for Snowflake compatibility.`);\n\t}\n\n\treturn modifiedQuery;\n}\n\n/**\n * Ensures a SQL query has a LIMIT clause to prevent large result sets\n * Only applies to SELECT queries - leaves INSERT, UPDATE, DELETE, etc. unchanged\n * Also removes any duplicate LIMIT clauses to prevent SQL errors\n * Converts T-SQL TOP syntax to Snowflake LIMIT syntax\n * @param query - The SQL query to check\n * @param defaultLimit - Default limit to apply if none exists (default: 50)\n * @returns The query with a single LIMIT clause (if it's a SELECT query)\n */\nexport function ensureQueryLimit(query: string, defaultLimit: number = 50): string {\n\tif (!query || query.trim().length === 0) {\n\t\treturn query;\n\t}\n\n\tlet trimmedQuery = query.trim();\n\n\t// Only apply LIMIT to SELECT queries\n\t// Check if the query is a SELECT statement (not INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, etc.)\n\tconst isSelectQuery = /^\\s*SELECT\\b/i.test(trimmedQuery) ||\n\t\t/^\\s*WITH\\b.*\\bSELECT\\b/is.test(trimmedQuery); // Also handle CTEs (WITH clause)\n\n\tif (!isSelectQuery) {\n\t\t// Not a SELECT query, return as-is\n\t\treturn query;\n\t}\n\n\t// Step 1: Convert TOP syntax to standard format\n\ttrimmedQuery = convertTopToLimit(trimmedQuery);\n\n\t// Remove any trailing semicolon for processing\n\tconst hadSemicolon = trimmedQuery.endsWith(';');\n\tif (hadSemicolon) {\n\t\ttrimmedQuery = trimmedQuery.slice(0, -1).trim();\n\t}\n\n\t// Remove any duplicate LIMIT clauses (keep only the last one, or remove all to add a fresh one)\n\t// This regex matches LIMIT followed by a number, case-insensitive\n\tconst limitMatches = trimmedQuery.match(/\\bLIMIT\\s+\\d+\\b/gi);\n\n\tif (limitMatches && limitMatches.length > 0) {\n\t\t// If there are multiple LIMIT clauses, remove them all and add a fresh one\n\t\tif (limitMatches.length > 1) {\n\t\t\tconsole.warn(`⚠️ Query had ${limitMatches.length} LIMIT clauses. Removing duplicates...`);\n\t\t\ttrimmedQuery = trimmedQuery.replace(/\\s*\\bLIMIT\\s+\\d+\\b/gi, '').trim();\n\t\t} else {\n\t\t\t// Single LIMIT exists, keep it as-is\n\t\t\tif (hadSemicolon) {\n\t\t\t\ttrimmedQuery += ';';\n\t\t\t}\n\t\t\treturn trimmedQuery;\n\t\t}\n\t}\n\n\t// Add LIMIT clause at the end\n\ttrimmedQuery = `${trimmedQuery} LIMIT ${defaultLimit}`;\n\n\t// Add back the semicolon if it was there\n\tif (hadSemicolon) {\n\t\ttrimmedQuery += ';';\n\t}\n\n\treturn trimmedQuery;\n}\n\n/**\n * Calculates the size of a JSON object in bytes\n * @param obj - The object to measure\n * @returns Size in bytes\n */\nexport function getJsonSizeInBytes(obj: any): number {\n\tconst jsonString = JSON.stringify(obj);\n\treturn Buffer.byteLength(jsonString, 'utf8');\n}\n\n/**\n * Checks if a message exceeds the WebSocket size limit\n * @param message - The message object to check\n * @param maxSize - Maximum size in bytes (default: 1MB)\n * @returns Object with isValid flag and size information\n */\nexport function validateMessageSize(message: any, maxSize: number = 1048576): { isValid: boolean; size: number; maxSize: number } {\n\tconst size = getJsonSizeInBytes(message);\n\treturn {\n\t\tisValid: size <= maxSize,\n\t\tsize,\n\t\tmaxSize\n\t};\n}","import path from 'path';\nimport fs from 'fs';\nimport { logger } from '../utils/logger';\n\n/**\n * Schema class for managing database schema operations\n */\nexport class Schema {\n private schemaFilePath: string;\n private cachedSchema: any = null;\n\n constructor(schemaFilePath?: string) {\n this.schemaFilePath = schemaFilePath || path.join(process.cwd(), '../analysis/data/schema.json');\n }\n\n /**\n * Gets the database schema from the schema file\n * @returns Parsed schema object or null if error occurs\n */\n getDatabaseSchema(): any | null {\n logger.info(`SCHEMA_FILE_PATH: ${this.schemaFilePath}`);\n\n try {\n // Create directory structure if it doesn't exist\n const dir = path.dirname(this.schemaFilePath);\n if (!fs.existsSync(dir)) {\n logger.info(`Creating directory structure: ${dir}`);\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Create file with empty schema if it doesn't exist\n if (!fs.existsSync(this.schemaFilePath)) {\n logger.info(`Schema file does not exist at ${this.schemaFilePath}, creating with empty schema`);\n const initialSchema = {\n database: '',\n schema: '',\n description: '',\n tables: [],\n relationships: []\n };\n fs.writeFileSync(this.schemaFilePath, JSON.stringify(initialSchema, null, 4));\n this.cachedSchema = initialSchema;\n return initialSchema;\n }\n\n const fileContent = fs.readFileSync(this.schemaFilePath, 'utf-8');\n const schema = JSON.parse(fileContent);\n this.cachedSchema = schema;\n return schema;\n } catch (error) {\n logger.error('Error parsing schema file:', error);\n return null;\n }\n }\n\n /**\n * Gets the cached schema or loads it if not cached\n * @returns Cached schema or freshly loaded schema\n */\n getSchema(): any | null {\n if (this.cachedSchema) {\n return this.cachedSchema;\n }\n return this.getDatabaseSchema();\n }\n\n /**\n * Generates database schema documentation for LLM from Snowflake JSON schema\n * @returns Formatted schema documentation string\n */\n generateSchemaDocumentation(): string {\n const schema = this.getSchema();\n\n if (!schema) {\n logger.warn('No database schema found.');\n return 'No database schema available.';\n }\n\n const tables: string[] = [];\n\n // Header information\n tables.push(`Database: ${schema.database}`);\n tables.push(`Schema: ${schema.schema}`);\n tables.push(`Description: ${schema.description}`);\n tables.push('');\n tables.push('='.repeat(80));\n tables.push('');\n\n // Process each table\n for (const table of schema.tables) {\n const tableInfo: string[] = [];\n\n tableInfo.push(`TABLE: ${table.fullName}`);\n tableInfo.push(`Description: ${table.description}`);\n tableInfo.push(`Row Count: ~${table.rowCount.toLocaleString()}`);\n tableInfo.push('');\n tableInfo.push('Columns:');\n\n // Process columns\n for (const column of table.columns) {\n let columnLine = ` - ${column.name}: ${column.type}`;\n\n if ((column as any).isPrimaryKey) {\n columnLine += ' (PRIMARY KEY)';\n }\n\n if ((column as any).isForeignKey && (column as any).references) {\n columnLine += ` (FK -> ${(column as any).references.table}.${(column as any).references.column})`;\n }\n\n if (!column.nullable) {\n columnLine += ' NOT NULL';\n }\n\n if (column.description) {\n columnLine += ` - ${column.description}`;\n }\n\n tableInfo.push(columnLine);\n\n // Add value examples for categorical columns\n if ((column as any).sampleValues && (column as any).sampleValues.length > 0) {\n tableInfo.push(` Sample values: [${(column as any).sampleValues.join(', ')}]`);\n }\n\n // Add statistics if available\n if ((column as any).statistics) {\n const stats = (column as any).statistics;\n if (stats.min !== undefined && stats.max !== undefined) {\n tableInfo.push(` Range: ${stats.min} to ${stats.max}`);\n }\n if (stats.distinct !== undefined) {\n tableInfo.push(` Distinct values: ${stats.distinct.toLocaleString()}`);\n }\n }\n }\n\n tableInfo.push('');\n tables.push(tableInfo.join('\\n'));\n }\n\n // Add relationships section\n tables.push('='.repeat(80));\n tables.push('');\n tables.push('TABLE RELATIONSHIPS:');\n tables.push('');\n\n for (const rel of schema.relationships) {\n tables.push(`${rel.from} -> ${rel.to} (${rel.type}): ${rel.keys.join(' = ')}`);\n }\n\n return tables.join('\\n');\n }\n\n /**\n * Clears the cached schema, forcing a reload on next access\n */\n clearCache(): void {\n this.cachedSchema = null;\n }\n\n /**\n * Sets a custom schema file path\n * @param filePath - Path to the schema file\n */\n setSchemaPath(filePath: string): void {\n this.schemaFilePath = filePath;\n this.clearCache();\n }\n}\n\n// Export a singleton instance for use across the application\nexport const schema = new Schema();\n","import fs from 'fs';\nimport path from 'path';\nimport { logger } from '../utils/logger';\n\nexport interface PromptLoaderConfig {\n\tpromptsDir?: string;\n}\n\ninterface CachedPromptTemplate {\n\tsystem: string;\n\tuser: string;\n}\n\n/**\n * PromptLoader class for loading and processing prompt templates\n * Caches prompts in memory at initialization for better performance\n */\nexport class PromptLoader {\n\tprivate promptsDir: string;\n\tprivate defaultPromptsDir: string;\n\tprivate promptCache: Map<string, CachedPromptTemplate> = new Map();\n\tprivate isInitialized: boolean = false;\n\n\tconstructor(config?: PromptLoaderConfig) {\n\t\tlogger.debug('Initializing PromptLoader...', process.cwd());\n\t\tthis.promptsDir = config?.promptsDir || path.join(process.cwd(), '.prompts');\n\t\t// Default prompts directory within the SDK\n\t\tthis.defaultPromptsDir = path.join(__dirname, '..', '..', '.prompts');\n\t}\n\n\t/**\n\t * Initialize and cache all prompts into memory\n\t * This should be called once at SDK startup\n\t */\n\tasync initialize(): Promise<void> {\n\t\tif (this.isInitialized) {\n\t\t\tlogger.debug('PromptLoader already initialized, skipping...');\n\t\t\treturn;\n\t\t}\n\n\t\tlogger.info('Loading prompts into memory...');\n\n\t\tconst promptTypes = [\n\t\t\t'classify',\n\t\t\t'match-component',\n\t\t\t'modify-props',\n\t\t\t'single-component',\n\t\t\t'mutli-component',\n\t\t\t'actions',\n\t\t\t'container-metadata'\n\t\t];\n\n\t\tfor (const promptType of promptTypes) {\n\t\t\ttry {\n\t\t\t\tconst template = await this.loadPromptTemplate(promptType);\n\t\t\t\tthis.promptCache.set(promptType, template);\n\t\t\t\tlogger.debug(`Cached prompt: ${promptType}`);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`Failed to load prompt '${promptType}':`, error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\tthis.isInitialized = true;\n\t\tlogger.info(`Successfully loaded ${this.promptCache.size} prompt templates into memory`);\n\t}\n\n\t/**\n\t * Load a prompt template from file system (tries custom dir first, then defaults to SDK dir)\n\t * @param promptName - Name of the prompt folder\n\t * @returns Template with system and user prompts\n\t */\n\tprivate async loadPromptTemplate(promptName: string): Promise<CachedPromptTemplate> {\n\t\tconst tryLoadFromDir = (dir: string): CachedPromptTemplate | null => {\n\t\t\ttry {\n\t\t\t\tconst systemPath = path.join(dir, promptName, 'system.md');\n\t\t\t\tconst userPath = path.join(dir, promptName, 'user.md');\n\n\t\t\t\tif (fs.existsSync(systemPath) && fs.existsSync(userPath)) {\n\t\t\t\t\tconst system = fs.readFileSync(systemPath, 'utf-8');\n\t\t\t\t\tconst user = fs.readFileSync(userPath, 'utf-8');\n\t\t\t\t\tlogger.debug(`Loaded prompt '${promptName}' from ${dir}`);\n\t\t\t\t\treturn { system, user };\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t} catch (error) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t};\n\t\t// Try loading from custom directory first\n\t\tlet template = tryLoadFromDir(this.promptsDir);\n\n\t\t// If not found, try default SDK directory\n\t\tif (!template) {\n\t\t\tlogger.warn(`Prompt '${promptName}' not found in ${this.promptsDir}, trying default location...`);\n\t\t\ttemplate = tryLoadFromDir(this.defaultPromptsDir);\n\t\t}\n\n\t\tif (!template) {\n\t\t\tthrow new Error(`Prompt template '${promptName}' not found in either ${this.promptsDir} or ${this.defaultPromptsDir}`);\n\t\t}\n\n\t\treturn template;\n\t}\n\n\t/**\n\t * Replace variables in a template string using {{VARIABLE_NAME}} pattern\n\t * @param template - Template string with placeholders\n\t * @param variables - Variables to replace in the template\n\t * @returns Processed string\n\t */\n\tprivate replaceVariables(\n\t\ttemplate: string,\n\t\tvariables: Record<string, string | number | boolean | any[]>\n\t): string {\n\t\tlet content = template;\n\n\t\t// Replace all variables matching {{VARIABLE_NAME}} pattern\n\t\tfor (const [key, value] of Object.entries(variables)) {\n\t\t\tconst pattern = new RegExp(`{{${key}}}`, 'g');\n\t\t\tconst replacementValue = typeof value === 'string' ? value : JSON.stringify(value);\n\t\t\tcontent = content.replace(pattern, replacementValue);\n\t\t}\n\n\t\treturn content;\n\t}\n\n\t/**\n\t * Load both system and user prompts from cache and replace variables\n\t * @param promptName - Name of the prompt folder\n\t * @param variables - Variables to replace in the templates\n\t * @returns Object containing both system and user prompts\n\t */\n\tasync loadPrompts(\n\t\tpromptName: string,\n\t\tvariables: Record<string, string | number | boolean | any[]>\n\t): Promise<{ system: string; user: string }> {\n\t\tif (!this.isInitialized) {\n\t\t\tlogger.warn('PromptLoader not initialized, loading prompts on-demand (not recommended)');\n\t\t\tawait this.initialize();\n\t\t}\n\n\t\tconst template = this.promptCache.get(promptName);\n\n\t\tif (!template) {\n\t\t\tthrow new Error(`Prompt template '${promptName}' not found in cache. Available prompts: ${Array.from(this.promptCache.keys()).join(', ')}`);\n\t\t}\n\n\t\treturn {\n\t\t\tsystem: this.replaceVariables(template.system, variables),\n\t\t\tuser: this.replaceVariables(template.user, variables)\n\t\t};\n\t}\n\n\t/**\n\t * DEPRECATED: Use loadPrompts instead\n\t * Load a single prompt file and replace variables using {{VARIABLE_NAME}} pattern\n\t */\n\tasync loadPrompt(\n\t\tpromptName: string,\n\t\tpromptType: 'system' | 'user',\n\t\tvariables: Record<string, string | number | boolean | any[]>\n\t): Promise<string> {\n\t\tconst prompts = await this.loadPrompts(promptName, variables);\n\t\treturn promptType === 'system' ? prompts.system : prompts.user;\n\t}\n\n\t/**\n\t * Set custom prompts directory (requires re-initialization)\n\t * @param dir - Path to the prompts directory\n\t */\n\tsetPromptsDir(dir: string): void {\n\t\tthis.promptsDir = dir;\n\t\tthis.isInitialized = false;\n\t\tthis.promptCache.clear();\n\t}\n\n\t/**\n\t * Get current prompts directory\n\t * @returns Path to the prompts directory\n\t */\n\tgetPromptsDir(): string {\n\t\treturn this.promptsDir;\n\t}\n\n\t/**\n\t * Check if prompts are loaded in memory\n\t */\n\tisReady(): boolean {\n\t\treturn this.isInitialized;\n\t}\n\n\t/**\n\t * Get the number of cached prompts\n\t */\n\tgetCacheSize(): number {\n\t\treturn this.promptCache.size;\n\t}\n}\n\n// Export a singleton instance\n// Default to backend's .prompts directory (where the SDK is being used)\n// If prompts are not found there, the loader will fallback to SDK's built-in .prompts\nconst defaultPromptsPath = process.env.PROMPTS_DIR || path.join(process.cwd(), '.prompts');\n\nexport const promptLoader = new PromptLoader({\n\tpromptsDir: defaultPromptsPath\n});\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport Groq from \"groq-sdk\";\n\ninterface LLMMessages {\n sys: string;\n user: string;\n}\n\ninterface LLMOptions {\n model?: string;\n maxTokens?: number;\n temperature?: number;\n topP?: number;\n apiKey?: string;\n partial?: (chunk: string) => void; // Callback for each chunk\n}\n\nexport class LLM {\n /* Get a complete text response from an LLM (Anthropic or Groq) */\n static async text(messages: LLMMessages, options: LLMOptions = {}): Promise<string> {\n const [provider, modelName] = this._parseModel(options.model);\n\n if (provider === 'anthropic') {\n return this._anthropicText(messages, modelName, options);\n } else if (provider === 'groq') {\n return this._groqText(messages, modelName, options);\n } else {\n throw new Error(`Unsupported provider: ${provider}. Use \"anthropic\" or \"groq\"`);\n }\n }\n\n /* Stream response from an LLM (Anthropic or Groq) */\n static async stream<T = string>(\n messages: LLMMessages,\n options: LLMOptions = {},\n json?: boolean\n ): Promise<T extends string ? string : any> {\n const [provider, modelName] = this._parseModel(options.model);\n\n if (provider === 'anthropic') {\n return this._anthropicStream(messages, modelName, options, json);\n } else if (provider === 'groq') {\n return this._groqStream(messages, modelName, options, json);\n } else {\n throw new Error(`Unsupported provider: ${provider}. Use \"anthropic\" or \"groq\"`);\n }\n }\n\n // ============================================================\n // PRIVATE HELPER METHODS\n // ============================================================\n\n /**\n * Parse model string to extract provider and model name\n * @param modelString - Format: \"provider/model-name\" or just \"model-name\"\n * @returns [provider, modelName]\n *\n * @example\n * \"anthropic/claude-sonnet-4-5\" → [\"anthropic\", \"claude-sonnet-4-5\"]\n * \"groq/openai/gpt-oss-120b\" → [\"groq\", \"openai/gpt-oss-120b\"]\n * \"claude-sonnet-4-5\" → [\"anthropic\", \"claude-sonnet-4-5\"] (default)\n */\n private static _parseModel(modelString?: string): [string, string] {\n if (!modelString) {\n // Default to Anthropic Claude\n return ['anthropic', 'claude-sonnet-4-5'];\n }\n\n // Check if model string has provider prefix\n if (modelString.includes('/')) {\n // Split only on the FIRST slash to handle models like \"groq/openai/gpt-oss-120b\"\n const firstSlashIndex = modelString.indexOf('/');\n const provider = modelString.substring(0, firstSlashIndex).toLowerCase().trim();\n const model = modelString.substring(firstSlashIndex + 1).trim();\n return [provider, model];\n }\n\n // No prefix, assume Anthropic\n return ['anthropic', modelString];\n }\n\n // ============================================================\n // ANTHROPIC IMPLEMENTATION\n // ============================================================\n\n private static async _anthropicText(\n messages: LLMMessages,\n modelName: string,\n options: LLMOptions\n ): Promise<string> {\n const apiKey = options.apiKey || process.env.ANTHROPIC_API_KEY || \"\";\n const client = new Anthropic({\n apiKey: apiKey,\n });\n\n const response = await client.messages.create({\n model: modelName,\n max_tokens: options.maxTokens || 1000,\n temperature: options.temperature,\n system: messages.sys,\n messages: [{\n role: \"user\",\n content: messages.user\n }]\n });\n\n const textBlock = response.content.find(block => block.type === 'text');\n return textBlock?.type === 'text' ? textBlock.text : '';\n }\n\n private static async _anthropicStream(\n messages: LLMMessages,\n modelName: string,\n options: LLMOptions,\n json?: boolean\n ): Promise<any> {\n const apiKey = options.apiKey || process.env.ANTHROPIC_API_KEY || \"\";\n const client = new Anthropic({\n apiKey: apiKey,\n });\n\n const stream = await client.messages.create({\n model: modelName,\n max_tokens: options.maxTokens || 1000,\n temperature: options.temperature,\n system: messages.sys,\n messages: [{\n role: \"user\",\n content: messages.user\n }],\n stream: true,\n });\n\n let fullText = '';\n\n // Process stream\n for await (const chunk of stream) {\n if (chunk.type === 'content_block_delta' && chunk.delta.type === 'text_delta') {\n const text = chunk.delta.text;\n fullText += text;\n\n // Call partial callback if provided\n if (options.partial) {\n options.partial(text);\n }\n }\n }\n\n // Return parsed JSON or text\n if (json) {\n return this._parseJSON(fullText);\n }\n\n return fullText;\n }\n\n // ============================================================\n // GROQ IMPLEMENTATION\n // ============================================================\n\n private static async _groqText(\n messages: LLMMessages,\n modelName: string,\n options: LLMOptions\n ): Promise<string> {\n const client = new Groq({\n apiKey: options.apiKey || process.env.GROQ_API_KEY || \"\",\n });\n\n const response = await client.chat.completions.create({\n model: modelName,\n messages: [\n { role: 'system', content: messages.sys },\n { role: 'user', content: messages.user }\n ],\n temperature: options.temperature,\n max_tokens: options.maxTokens || 1000,\n });\n\n return response.choices[0]?.message?.content || '';\n }\n\n private static async _groqStream(\n messages: LLMMessages,\n modelName: string,\n options: LLMOptions,\n json?: boolean\n ): Promise<any> {\n const apiKey = options.apiKey || process.env.GROQ_API_KEY || \"\";\n const client = new Groq({\n apiKey: apiKey,\n });\n\n const stream = await client.chat.completions.create({\n model: modelName,\n messages: [\n { role: 'system', content: messages.sys },\n { role: 'user', content: messages.user }\n ],\n temperature: options.temperature,\n max_tokens: options.maxTokens || 1000,\n stream: true,\n response_format: json ? { type: 'json_object' } : undefined\n });\n\n let fullText = '';\n\n // Process stream\n for await (const chunk of stream) {\n const text = chunk.choices[0]?.delta?.content || '';\n if (text) {\n fullText += text;\n\n // Call partial callback if provided\n if (options.partial) {\n options.partial(text);\n }\n }\n }\n\n // Return parsed JSON or text\n if (json) {\n return this._parseJSON(fullText);\n }\n\n return fullText;\n }\n\n // ============================================================\n // JSON PARSING HELPER\n // ============================================================\n\n /**\n * Parse JSON string, handling markdown code blocks and surrounding text\n * Enhanced version from anthropic.ts implementation\n * @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text\n * @returns Parsed JSON object\n */\n private static _parseJSON(text: string): any {\n let jsonText = text.trim();\n\n // Remove markdown code blocks\n if (jsonText.startsWith('```json')) {\n jsonText = jsonText.replace(/^```json\\s*\\n?/, '').replace(/\\n?```\\s*$/, '');\n } else if (jsonText.startsWith('```')) {\n jsonText = jsonText.replace(/^```\\s*\\n?/, '').replace(/\\n?```\\s*$/, '');\n }\n\n // Extract JSON if there's surrounding text - find the first { and last }\n const firstBrace = jsonText.indexOf('{');\n const lastBrace = jsonText.lastIndexOf('}');\n if (firstBrace !== -1 && lastBrace !== -1 && firstBrace < lastBrace) {\n jsonText = jsonText.substring(firstBrace, lastBrace + 1);\n }\n\n return JSON.parse(jsonText);\n }\n}","import { Component } from '../types';\nimport { ensureQueryLimit } from './utils';\nimport { schema } from './schema';\nimport { promptLoader } from './prompt-loader';\nimport { LLM } from '../llm';\nimport { logger } from '../utils/logger';\n\nexport interface BaseLLMConfig {\n\tmodel?: string;\n\tdefaultLimit?: number;\n\tapiKey?: string;\n}\n\n/**\n * BaseLLM abstract class for AI-powered component generation and matching\n * Provides common functionality for all LLM providers\n */\nexport abstract class BaseLLM {\n\tprotected model: string;\n\tprotected defaultLimit: number;\n\tprotected apiKey?: string;\n\n\tconstructor(config?: BaseLLMConfig) {\n\t\tthis.model = config?.model || this.getDefaultModel();\n\t\tthis.defaultLimit = config?.defaultLimit || 50;\n\t\tthis.apiKey = config?.apiKey;\n\t}\n\n\t/**\n\t * Get the default model for this provider\n\t */\n\tprotected abstract getDefaultModel(): string;\n\n\t/**\n\t * Get the default API key from environment\n\t */\n\tprotected abstract getDefaultApiKey(): string | undefined;\n\n\t/**\n\t * Get the provider name (for logging)\n\t */\n\tprotected abstract getProviderName(): string;\n\n\t/**\n\t * Get the API key (from instance, parameter, or environment)\n\t */\n\tprotected getApiKey(apiKey?: string): string | undefined {\n\t\treturn apiKey || this.apiKey || this.getDefaultApiKey();\n\t}\n\n\t/**\n\t * Classify user question to determine the type and required visualizations\n\t */\n\tasync classifyUserQuestion(\n\t\tuserPrompt: string,\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tquestionType: 'analytical' | 'data_modification' | 'general';\n\t\tvisualizations: string[];\n\t\treasoning: string;\n\t\tneedsMultipleComponents: boolean;\n\t}> {\n\t\t\n\t\ttry {\n\t\t\tconst prompts = await promptLoader.loadPrompts('classify', {\n\t\t\t\tUSER_PROMPT: userPrompt,\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 800,\n\t\t\t\t\ttemperature: 0.2,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\t// Log the LLM explanation with type\n\t\t\tlogCollector?.logExplanation(\n\t\t\t\t'User question classified',\n\t\t\t\tresult.reasoning || 'No reasoning provided',\n\t\t\t\t{\n\t\t\t\t\tquestionType: result.questionType || 'general',\n\t\t\t\t\tvisualizations: result.visualizations || [],\n\t\t\t\t\tneedsMultipleComponents: result.needsMultipleComponents || false\n\t\t\t\t}\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\tquestionType: result.questionType || 'general',\n\t\t\t\tvisualizations: result.visualizations || [],\n\t\t\t\treasoning: result.reasoning || 'No reasoning provided',\n\t\t\t\tneedsMultipleComponents: result.needsMultipleComponents || false\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error('Error classifying user question:', error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Enhanced function that validates and modifies the entire props object based on user request\n\t * This includes query, title, description, and config properties\n\t */\n\tasync validateAndModifyProps(\n\t\tuserPrompt: string,\n\t\toriginalProps: any,\n\t\tcomponentName: string,\n\t\tcomponentType: string,\n\t\tcomponentDescription?: string,\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{ props: any; isModified: boolean; reasoning: string; modifications: string[] }> {\n\n\t\tconst schemaDoc = schema.generateSchemaDocumentation();\n\t\ttry {\n\t\t\tconst prompts = await promptLoader.loadPrompts('modify-props', {\n\t\t\t\tCOMPONENT_NAME: componentName,\n\t\t\t\tCOMPONENT_TYPE: componentType,\n\t\t\t\tCOMPONENT_DESCRIPTION: componentDescription || 'No description',\n\t\t\t\tSCHEMA_DOC: schemaDoc || 'No schema available',\n\t\t\t\tDEFAULT_LIMIT: this.defaultLimit,\n\t\t\t\tUSER_PROMPT: userPrompt,\n\t\t\t\tCURRENT_PROPS: JSON.stringify(originalProps, null, 2),\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tlogger.debug('props-modification: System prompt\\n',prompts.system.substring(0, 100), '\\n\\n\\n', 'User prompt:', prompts.user.substring(0, 50));\t\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 2500,\n\t\t\t\t\ttemperature: 0.2,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\t// Ensure all queries have a LIMIT clause\n\t\t\tconst props = result.props || originalProps;\n\t\t\tif (props && props.query) {\n\t\t\t\tprops.query = ensureQueryLimit(props.query, this.defaultLimit);\n\t\t\t}\n\n\t\t\t// Log the generated query and explanation with types\n\t\t\tif (props && props.query) {\n\t\t\t\tlogCollector?.logQuery(\n\t\t\t\t\t'Props query modified',\n\t\t\t\t\tprops.query,\n\t\t\t\t\t{\n\t\t\t\t\t\tmodifications: result.modifications || [],\n\t\t\t\t\t\treasoning: result.reasoning || 'No modifications needed'\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (result.reasoning) {\n\t\t\t\tlogCollector?.logExplanation(\n\t\t\t\t\t'Props modification explanation',\n\t\t\t\t\tresult.reasoning,\n\t\t\t\t\t{ modifications: result.modifications || [] }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tprops: props,\n\t\t\t\tisModified: result.isModified || false,\n\t\t\t\treasoning: result.reasoning || 'No modifications needed',\n\t\t\t\tmodifications: result.modifications || []\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error validating/modifying props with ${this.getProviderName()}:`, error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Match and select a component from available components filtered by type\n\t * This picks the best matching component based on user prompt and modifies its props\n\t */\n\tasync generateAnalyticalComponent(\n\t\tuserPrompt: string,\n\t\tcomponents: Component[],\n\t\tpreferredVisualizationType?: string,\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tcomponent: Component | null;\n\t\treasoning: string;\n\t\tisGenerated: boolean;\n\t}> {\n\t\ttry {\n\t\t\t// Filter components by the preferred visualization type\n\t\t\tconst filteredComponents = preferredVisualizationType\n\t\t\t\t? components.filter(c => c.type === preferredVisualizationType)\n\t\t\t\t: components;\n\n\t\t\tif (filteredComponents.length === 0) {\n\t\t\t\tlogCollector?.warn(\n\t\t\t\t\t`No components found of type ${preferredVisualizationType}`,\n\t\t\t\t\t'explanation',\n\t\t\t\t\t{ reason: 'No matching components available for this visualization type' }\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tcomponent: null,\n\t\t\t\t\treasoning: `No components available of type ${preferredVisualizationType}`,\n\t\t\t\t\tisGenerated: false\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Format filtered components for the prompt\n\t\t\tconst componentsText = filteredComponents\n\t\t\t\t.map((comp, idx) => {\n\t\t\t\t\tconst keywords = comp.keywords ? comp.keywords.join(', ') : '';\n\t\t\t\t\tconst category = comp.category || 'general';\n\t\t\t\t\tconst propsPreview = comp.props ? JSON.stringify(comp.props, null, 2) : 'No props';\n\t\t\t\t\treturn `${idx + 1}. ID: ${comp.id}\n Name: ${comp.name}\n Type: ${comp.type}\n Category: ${category}\n Description: ${comp.description || 'No description'}\n Keywords: ${keywords}\n Props Preview: ${propsPreview}`;\n\t\t\t\t})\n\t\t\t\t.join('\\n\\n');\n\n\t\t\tconst visualizationConstraint = preferredVisualizationType\n\t\t\t\t? `\\n**IMPORTANT: Components are filtered to type ${preferredVisualizationType}. Select the best match.**\\n`\n\t\t\t\t: '';\n\n\t\t\tconst prompts = await promptLoader.loadPrompts('single-component', {\n\t\t\t\tCOMPONENT_TYPE: preferredVisualizationType || 'any',\n\t\t\t\tCOMPONENTS_LIST: componentsText,\n\t\t\t\tVISUALIZATION_CONSTRAINT: visualizationConstraint,\n\t\t\t\tUSER_PROMPT: userPrompt,\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tlogger.debug('single-component: System prompt\\n',prompts.system.substring(0, 100), '\\n\\n\\n', 'User prompt:', prompts.user.substring(0, 50));\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 2000,\n\t\t\t\t\ttemperature: 0.2,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\tif (!result.canGenerate || result.confidence < 50) {\n\t\t\t\tlogCollector?.warn(\n\t\t\t\t\t'Cannot match component',\n\t\t\t\t\t'explanation',\n\t\t\t\t\t{ reason: result.reasoning || 'Unable to find matching component for this question' }\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tcomponent: null,\n\t\t\t\t\treasoning: result.reasoning || 'Unable to find matching component for this question',\n\t\t\t\t\tisGenerated: false\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Get the matched component\n\t\t\tconst componentIndex = result.componentIndex;\n\t\t\tconst componentId = result.componentId;\n\t\t\tlet matchedComponent = null;\n\n\t\t\t// Prefer componentId over componentIndex\n\t\t\tif (componentId) {\n\t\t\t\tmatchedComponent = filteredComponents.find(c => c.id === componentId);\n\t\t\t}\n\n\t\t\t// Fallback to componentIndex\n\t\t\tif (!matchedComponent && componentIndex) {\n\t\t\t\tmatchedComponent = filteredComponents[componentIndex - 1];\n\t\t\t}\n\n\t\t\tif (!matchedComponent) {\n\t\t\t\tlogCollector?.warn('Component not found in filtered list');\n\t\t\t\treturn {\n\t\t\t\t\tcomponent: null,\n\t\t\t\t\treasoning: 'Component not found in filtered list',\n\t\t\t\t\tisGenerated: false\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlogCollector?.info(`Matched component: ${matchedComponent.name} (confidence: ${result.confidence}%)`);\n\n\t\t\t// Now modify the component's props based on user prompt\n\t\t\tconst propsValidation = await this.validateAndModifyProps(\n\t\t\t\tuserPrompt,\n\t\t\t\tmatchedComponent.props,\n\t\t\t\tmatchedComponent.name,\n\t\t\t\tmatchedComponent.type,\n\t\t\t\tmatchedComponent.description,\n\t\t\t\tapiKey,\n\t\t\t\tlogCollector,\n\t\t\t\tconversationHistory\n\t\t\t);\n\n\t\t\t// Create modified component\n\t\t\tconst modifiedComponent: Component = {\n\t\t\t\t...matchedComponent,\n\t\t\t\tprops: propsValidation.props\n\t\t\t};\n\n\t\t\tlogCollector?.logExplanation(\n\t\t\t\t'Analytical component selected and modified',\n\t\t\t\tresult.reasoning || 'Selected component based on analytical question',\n\t\t\t\t{\n\t\t\t\t\tcomponentName: matchedComponent.name,\n\t\t\t\t\tcomponentType: matchedComponent.type,\n\t\t\t\t\tconfidence: result.confidence,\n\t\t\t\t\tpropsModified: propsValidation.isModified\n\t\t\t\t}\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\tcomponent: modifiedComponent,\n\t\t\t\treasoning: result.reasoning || 'Selected and modified component based on analytical question',\n\t\t\t\tisGenerated: true\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error('Error generating analytical component:', error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Generate container metadata (title and description) for multi-component dashboard\n\t */\n\tasync generateContainerMetadata(\n\t\tuserPrompt: string,\n\t\tvisualizationTypes: string[],\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\ttitle: string;\n\t\tdescription: string;\n\t}> {\n\t\ttry {\n\t\t\tconst prompts = await promptLoader.loadPrompts('container-metadata', {\n\t\t\t\tUSER_PROMPT: userPrompt,\n\t\t\t\tVISUALIZATION_TYPES: visualizationTypes.join(', '),\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 500,\n\t\t\t\t\ttemperature: 0.3,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\tlogCollector?.logExplanation(\n\t\t\t\t'Container metadata generated',\n\t\t\t\t`Generated title and description for multi-component dashboard`,\n\t\t\t\t{\n\t\t\t\t\ttitle: result.title,\n\t\t\t\t\tdescription: result.description,\n\t\t\t\t\tvisualizationTypes\n\t\t\t\t}\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\ttitle: result.title || `${userPrompt} - Dashboard`,\n\t\t\t\tdescription: result.description || `Multi-component dashboard showing ${visualizationTypes.join(', ')}`\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error('Error generating container metadata:', error);\n\t\t\t// Return fallback values\n\t\t\treturn {\n\t\t\t\ttitle: `${userPrompt} - Dashboard`,\n\t\t\t\tdescription: `Multi-component dashboard showing ${visualizationTypes.join(', ')}`\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Match component from a list with enhanced props modification\n\t */\n\tasync matchComponent(\n\t\tuserPrompt: string,\n\t\tcomponents: Component[],\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tcomponent: Component | null;\n\t\treasoning: string;\n\t\tqueryModified?: boolean;\n\t\tqueryReasoning?: string;\n\t\tpropsModified?: boolean;\n\t\tpropsModifications?: string[];\n\t\tmethod: string;\n\t\tconfidence?: number;\n\t}> {\n\t\ttry {\n\t\t\t// Step 1: Enhanced component matching with scoring and multiple candidates\n\t\t\tconst componentsText = components\n\t\t\t\t.map((comp, idx) => {\n\t\t\t\t\tconst keywords = comp.keywords ? comp.keywords.join(', ') : '';\n\t\t\t\t\tconst category = comp.category || 'general';\n\t\t\t\t\treturn `${idx + 1}. ID: ${comp.id}\n Name: ${comp.name}\n Type: ${comp.type}\n Category: ${category}\n Description: ${comp.description || 'No description'}\n Keywords: ${keywords}`;\n\t\t\t\t})\n\t\t\t\t.join('\\n\\n');\n\n\t\t\tconst prompts = await promptLoader.loadPrompts('match-component', {\n\t\t\t\tCOMPONENTS_TEXT: componentsText,\n\t\t\t\tUSER_PROMPT: userPrompt,\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 800,\n\t\t\t\t\ttemperature: 0.2,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\tconst componentIndex = result.componentIndex;\n\t\t\tconst componentId = result.componentId;\n\t\t\tconst confidence = result.confidence || 0;\n\n\t\t\t// Prefer componentId over componentIndex for accuracy\n\t\t\tlet component = null;\n\t\t\tif (componentId) {\n\t\t\t\tcomponent = components.find(c => c.id === componentId);\n\t\t\t}\n\n\t\t\t// Fallback to componentIndex if ID not found\n\t\t\tif (!component && componentIndex) {\n\t\t\t\tcomponent = components[componentIndex - 1];\n\t\t\t}\n\n\t\t\tconst matchedMsg = `${this.getProviderName()} matched component: ${component?.name || 'None'}`;\n\t\t\tconsole.log('✓', matchedMsg);\n\t\t\tlogCollector?.info(matchedMsg);\n\n\t\t\tif (result.alternativeMatches && result.alternativeMatches.length > 0) {\n\t\t\t\tconsole.log(' Alternative matches:');\n\t\t\t\tconst altMatches = result.alternativeMatches.map((alt: any) =>\n\t\t\t\t\t`${components[alt.index - 1]?.name} (${alt.score}%): ${alt.reason}`\n\t\t\t\t).join(' | ');\n\t\t\t\tlogCollector?.info(`Alternative matches: ${altMatches}`);\n\t\t\t\tresult.alternativeMatches.forEach((alt: any) => {\n\t\t\t\t\tconsole.log(` - ${components[alt.index - 1]?.name} (${alt.score}%): ${alt.reason}`);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!component) {\n\t\t\t\tconst noMatchMsg = `No matching component found (confidence: ${confidence}%)`;\n\t\t\t\tconsole.log('✗', noMatchMsg);\n\t\t\t\tlogCollector?.warn(noMatchMsg);\n\t\t\t\tconst genMsg = 'Attempting to match component from analytical question...';\n\t\t\t\tconsole.log('✓', genMsg);\n\t\t\t\tlogCollector?.info(genMsg);\n\n\t\t\t\t// Try to match a component for the analytical question\n\t\t\t\tconst generatedResult = await this.generateAnalyticalComponent(userPrompt, components, undefined, apiKey, logCollector, conversationHistory);\n\n\t\t\t\tif (generatedResult.component) {\n\t\t\t\t\tconst genSuccessMsg = `Successfully matched component: ${generatedResult.component.name}`;\n\t\t\t\t\tlogCollector?.info(genSuccessMsg);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcomponent: generatedResult.component,\n\t\t\t\t\t\treasoning: generatedResult.reasoning,\n\t\t\t\t\t\tmethod: `${this.getProviderName()}-generated`,\n\t\t\t\t\t\tconfidence: 100, // Generated components are considered 100% match to the question\n\t\t\t\t\t\tpropsModified: false,\n\t\t\t\t\t\tqueryModified: false\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// If matching also failed, return null\n\t\t\t\tlogCollector?.error('Failed to match component');\n\t\t\t\treturn {\n\t\t\t\t\tcomponent: null,\n\t\t\t\t\treasoning: result.reasoning || 'No matching component found and unable to match component',\n\t\t\t\t\tmethod: `${this.getProviderName()}-llm`,\n\t\t\t\t\tconfidence\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Step 2: Validate and modify the entire props object based on user request\n\t\t\tlet propsModified = false;\n\t\t\tlet propsModifications: string[] = [];\n\t\t\tlet queryModified = false;\n\t\t\tlet queryReasoning = '';\n\n\t\t\tif (component && component.props) {\n\n\t\t\t\tconst propsValidation = await this.validateAndModifyProps(\n\t\t\t\t\tuserPrompt,\n\t\t\t\t\tcomponent.props,\n\t\t\t\t\tcomponent.name,\n\t\t\t\t\tcomponent.type,\n\t\t\t\t\tcomponent.description,\n\t\t\t\t\tapiKey,\n\t\t\t\t\tlogCollector,\n\t\t\t\t\tconversationHistory\n\t\t\t\t);\n\n\t\t\t\t// Create a new component object with the modified props\n\t\t\t\tconst originalQuery = component.props.query;\n\t\t\t\tconst modifiedQuery = propsValidation.props.query;\n\n\t\t\t\tcomponent = {\n\t\t\t\t\t...component,\n\t\t\t\t\tprops: propsValidation.props\n\t\t\t\t};\n\n\t\t\t\tpropsModified = propsValidation.isModified;\n\t\t\t\tpropsModifications = propsValidation.modifications;\n\t\t\t\tqueryModified = originalQuery !== modifiedQuery;\n\t\t\t\tqueryReasoning = propsValidation.reasoning;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tcomponent,\n\t\t\t\treasoning: result.reasoning || 'No reasoning provided',\n\t\t\t\tqueryModified,\n\t\t\t\tqueryReasoning,\n\t\t\t\tpropsModified,\n\t\t\t\tpropsModifications,\n\t\t\t\tmethod: `${this.getProviderName()}-llm`,\n\t\t\t\tconfidence\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error matching component with ${this.getProviderName()}:`, error);\n\t\t\tlogCollector?.error(`Error matching component: ${(error as Error).message}`);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Match multiple components for analytical questions by visualization types\n\t * This is used when the user needs multiple visualizations\n\t */\n\tasync generateMultipleAnalyticalComponents(\n\t\tuserPrompt: string,\n\t\tavailableComponents: Component[],\n\t\tvisualizationTypes: string[],\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tcomponents: Component[];\n\t\treasoning: string;\n\t\tisGenerated: boolean;\n\t}> {\n\t\ttry {\n\t\t\tconsole.log('✓ Matching multiple components:', visualizationTypes);\n\n\t\t\tconst components: Component[] = [];\n\n\t\t\t// Match each component type requested\n\t\t\tfor (const vizType of visualizationTypes) {\n\t\t\t\tconst result = await this.generateAnalyticalComponent(userPrompt, availableComponents, vizType, apiKey, logCollector, conversationHistory);\n\n\t\t\t\tif (result.component) {\n\t\t\t\t\tcomponents.push(result.component);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (components.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcomponents: [],\n\t\t\t\t\treasoning: 'Failed to match any components',\n\t\t\t\t\tisGenerated: false\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tcomponents,\n\t\t\t\treasoning: `Matched ${components.length} components: ${visualizationTypes.join(', ')}`,\n\t\t\t\tisGenerated: true\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error('Error matching multiple analytical components:', error);\n\t\t\treturn {\n\t\t\t\tcomponents: [],\n\t\t\t\treasoning: 'Error occurred while matching components',\n\t\t\t\tisGenerated: false\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Match multiple components and wrap them in a container\n\t */\n\tasync generateMultiComponentResponse(\n\t\tuserPrompt: string,\n\t\tavailableComponents: Component[],\n\t\tvisualizationTypes: string[],\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tcontainerComponent: Component | null;\n\t\treasoning: string;\n\t\tisGenerated: boolean;\n\t}> {\n\t\ttry {\n\t\t\t// Match multiple components for each visualization type\n\t\t\tconst matchResult = await this.generateMultipleAnalyticalComponents(\n\t\t\t\tuserPrompt,\n\t\t\t\tavailableComponents,\n\t\t\t\tvisualizationTypes,\n\t\t\t\tapiKey,\n\t\t\t\tlogCollector,\n\t\t\t\tconversationHistory\n\t\t\t);\n\n\t\t\tif (!matchResult.isGenerated || matchResult.components.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcontainerComponent: null,\n\t\t\t\t\treasoning: matchResult.reasoning || 'Unable to match multi-component dashboard',\n\t\t\t\t\tisGenerated: false\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst generatedComponents = matchResult.components;\n\n\t\t\t// Log each generated component's query\n\t\t\tgeneratedComponents.forEach((component, index) => {\n\t\t\t\tif (component.props.query) {\n\t\t\t\t\tlogCollector?.logQuery(\n\t\t\t\t\t\t`Multi-component query generated (${index + 1}/${generatedComponents.length})`,\n\t\t\t\t\t\tcomponent.props.query,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcomponentType: component.type,\n\t\t\t\t\t\t\ttitle: component.props.title,\n\t\t\t\t\t\t\tposition: index + 1,\n\t\t\t\t\t\t\ttotalComponents: generatedComponents.length\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Generate container title and description\n\t\t\tconst containerTitle = `${userPrompt} - Dashboard`;\n\t\t\tconst containerDescription = `Multi-component dashboard showing ${visualizationTypes.join(', ')}`;\n\n\t\t\t// Log the overall explanation for the multi-component dashboard\n\t\t\tlogCollector?.logExplanation(\n\t\t\t\t'Multi-component dashboard matched',\n\t\t\t\tmatchResult.reasoning || `Matched ${generatedComponents.length} components for comprehensive analysis`,\n\t\t\t\t{\n\t\t\t\t\ttotalComponents: generatedComponents.length,\n\t\t\t\t\tcomponentTypes: generatedComponents.map(c => c.type),\n\t\t\t\t\tcomponentNames: generatedComponents.map(c => c.name),\n\t\t\t\t\tcontainerTitle,\n\t\t\t\t\tcontainerDescription\n\t\t\t\t}\n\t\t\t);\n\n\t\t\t// Create the MultiComponentContainer wrapper\n\t\t\tconst containerComponent: Component = {\n\t\t\t\tid: `multi_container_${Date.now()}`,\n\t\t\t\tname: 'MultiComponentContainer',\n\t\t\t\ttype: 'Container',\n\t\t\t\tdescription: containerDescription,\n\t\t\t\tcategory: 'dynamic',\n\t\t\t\tkeywords: ['multi', 'container', 'dashboard'],\n\t\t\t\tprops: {\n\t\t\t\t\tconfig: {\n\t\t\t\t\t\tcomponents: generatedComponents,\n\t\t\t\t\t\tlayout: 'grid',\n\t\t\t\t\t\tspacing: 24,\n\t\t\t\t\t\ttitle: containerTitle,\n\t\t\t\t\t\tdescription: containerDescription\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\treturn {\n\t\t\t\tcontainerComponent,\n\t\t\t\treasoning: matchResult.reasoning || `Matched multi-component dashboard with ${generatedComponents.length} components`,\n\t\t\t\tisGenerated: true\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error('Error generating multi-component response:', error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Main orchestration function that classifies question and routes to appropriate handler\n\t * This is the NEW recommended entry point for handling user requests\n\t * ALWAYS returns a SINGLE component (wraps multiple in MultiComponentContainer)\n\t */\n\tasync handleUserRequest(\n\t\tuserPrompt: string,\n\t\tcomponents: Component[],\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<{\n\t\tcomponent: Component | null;\n\t\treasoning: string;\n\t\tmethod: string;\n\t\tquestionType: string;\n\t\tneedsMultipleComponents: boolean;\n\t\tpropsModified?: boolean;\n\t\tqueryModified?: boolean;\n\t}> {\n\t\ttry {\n\t\t\t// Step 1: Classify the user's question\n\t\t\tconst classifyMsg = 'Classifying user question...';\n\t\t\tlogCollector?.info(classifyMsg);\n\t\t\tconst classification = await this.classifyUserQuestion(userPrompt, apiKey, logCollector, conversationHistory);\n\t\t\tconst classInfo = `Question type: ${classification.questionType}, Visualizations: ${classification.visualizations.join(', ') || 'None'}, Multiple components: ${classification.needsMultipleComponents}`;\n\t\t\tlogCollector?.info(classInfo);\n\n\t\t\t// Step 2: Route based on question type\n\t\t\tif (classification.questionType === 'analytical') {\n\t\t\t\t// For analytical questions with specific visualization types\n\t\t\t\tif (classification.visualizations.length > 1) {\n\t\t\t\t\t// Multiple visualization types - match component for each type\n\t\t\t\t\tconst multiMsg = `Matching ${classification.visualizations.length} components for types: ${classification.visualizations.join(', ')}`;\n\t\t\t\t\tlogCollector?.info(multiMsg);\n\n\t\t\t\t\tconst matchedComponents: Component[] = [];\n\n\t\t\t\t\t// Loop through each visualization type and match a component\n\t\t\t\t\tfor (const vizType of classification.visualizations) {\n\t\t\t\t\t\tlogCollector?.info(`Matching component for type: ${vizType}`);\n\t\t\t\t\t\tconst result = await this.generateAnalyticalComponent(\n\t\t\t\t\t\t\tuserPrompt,\n\t\t\t\t\t\t\tcomponents,\n\t\t\t\t\t\t\tvizType,\n\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\tlogCollector,\n\t\t\t\t\t\t\tconversationHistory\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (result.component) {\n\t\t\t\t\t\t\tmatchedComponents.push(result.component);\n\t\t\t\t\t\t\tlogCollector?.info(`Matched: ${result.component.name}`);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlogCollector?.warn(`Failed to match component for type: ${vizType}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (matchedComponents.length === 0) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcomponent: null,\n\t\t\t\t\t\t\treasoning: 'Failed to match any components for the requested visualization types',\n\t\t\t\t\t\t\tmethod: 'classification-multi-failed',\n\t\t\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\t\t\tneedsMultipleComponents: true,\n\t\t\t\t\t\t\tpropsModified: false,\n\t\t\t\t\t\t\tqueryModified: false\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\t// Generate container metadata from user request\n\t\t\t\t\tlogCollector?.info('Generating container metadata...');\n\t\t\t\t\tconst containerMetadata = await this.generateContainerMetadata(\n\t\t\t\t\t\tuserPrompt,\n\t\t\t\t\t\tclassification.visualizations,\n\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\tlogCollector,\n\t\t\t\t\t\tconversationHistory\n\t\t\t\t\t);\n\n\n\t\t\t\t\tconst containerComponent: Component = {\n\t\t\t\t\t\tid: `multi_container_${Date.now()}`,\n\t\t\t\t\t\tname: 'MultiComponentContainer',\n\t\t\t\t\t\ttype: 'Container',\n\t\t\t\t\t\tdescription: containerMetadata.description,\n\t\t\t\t\t\tcategory: 'dynamic',\n\t\t\t\t\t\tkeywords: ['multi', 'container', 'dashboard'],\n\t\t\t\t\t\tprops: {\n\t\t\t\t\t\t\tconfig: {\n\t\t\t\t\t\t\t\tcomponents: matchedComponents,\n\t\t\t\t\t\t\t\tlayout: 'grid',\n\t\t\t\t\t\t\t\tspacing: 24,\n\t\t\t\t\t\t\t\ttitle: containerMetadata.title,\n\t\t\t\t\t\t\t\tdescription: containerMetadata.description\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tlogCollector?.info(`Created multi-component container with ${matchedComponents.length} components: \"${containerMetadata.title}\"`);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcomponent: containerComponent,\n\t\t\t\t\t\treasoning: `Matched ${matchedComponents.length} components for visualization types: ${classification.visualizations.join(', ')}`,\n\t\t\t\t\t\tmethod: 'classification-multi-generated',\n\t\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\t\tneedsMultipleComponents: true,\n\t\t\t\t\t\tpropsModified: false,\n\t\t\t\t\t\tqueryModified: false\n\t\t\t\t\t};\n\t\t\t\t} else if (classification.visualizations.length === 1) {\n\t\t\t\t\t// Single visualization type - match one component\n\t\t\t\t\tconst vizType = classification.visualizations[0];\n\t\t\t\t\tlogCollector?.info(`Matching single component for type: ${vizType}`);\n\t\t\t\t\tconst result = await this.generateAnalyticalComponent(userPrompt, components, vizType, apiKey, logCollector, conversationHistory);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcomponent: result.component,\n\t\t\t\t\t\treasoning: result.reasoning,\n\t\t\t\t\t\tmethod: 'classification-generated',\n\t\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\t\tneedsMultipleComponents: false,\n\t\t\t\t\t\tpropsModified: false,\n\t\t\t\t\t\tqueryModified: false\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\t// No specific visualization type, match from all components\n\t\t\t\t\tlogCollector?.info('No specific visualization type - matching from all components');\n\t\t\t\t\tconst result = await this.generateAnalyticalComponent(userPrompt, components, undefined, apiKey, logCollector, conversationHistory);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcomponent: result.component,\n\t\t\t\t\t\treasoning: result.reasoning,\n\t\t\t\t\t\tmethod: 'classification-generated-auto',\n\t\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\t\tneedsMultipleComponents: false,\n\t\t\t\t\t\tpropsModified: false,\n\t\t\t\t\t\tqueryModified: false\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} else if (classification.questionType === 'data_modification' || classification.questionType === 'general') {\n\t\t\t\t// For data modification, use the old component matching flow\n\t\t\t\tconst matchMsg = 'Using component matching for data modification...';\n\t\t\t\tlogCollector?.info(matchMsg);\n\t\t\t\tconst matchResult = await this.matchComponent(userPrompt, components, apiKey, logCollector, conversationHistory);\n\n\t\t\t\treturn {\n\t\t\t\t\tcomponent: matchResult.component,\n\t\t\t\t\treasoning: matchResult.reasoning,\n\t\t\t\t\tmethod: 'classification-matched',\n\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\tneedsMultipleComponents: false,\n\t\t\t\t\tpropsModified: matchResult.propsModified,\n\t\t\t\t\tqueryModified: matchResult.queryModified\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tlogCollector?.info('General question - no component needed');\n\t\t\t\treturn {\n\t\t\t\t\tcomponent: null,\n\t\t\t\t\treasoning: 'General question - no component needed',\n\t\t\t\t\tmethod: 'classification-general',\n\t\t\t\t\tquestionType: classification.questionType,\n\t\t\t\t\tneedsMultipleComponents: false\n\t\t\t\t};\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogCollector?.error(`Error handling user request: ${(error as Error).message}`);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Generate next questions that the user might ask based on the original prompt and generated component\n\t * This helps provide intelligent suggestions for follow-up queries\n\t */\n\tasync generateNextQuestions(\n\t\toriginalUserPrompt: string,\n\t\tcomponent: Component,\n\t\tcomponentData?: Record<string, unknown>,\n\t\tapiKey?: string,\n\t\tlogCollector?: any,\n\t\tconversationHistory?: string\n\t): Promise<string[]> {\n\t\ttry {\n\t\t\tconst component_info = `\n\t\t\t\tComponent Name: ${component.name}\n\t\t\t\tComponent Type: ${component.type}\n\t\t\t\tComponent Description: ${component.description || 'No description'}\n\t\t\t\tComponent Props: ${component.props ? JSON.stringify(component.props, null, 2) : 'No props'}\n\t\t\t`;\n\n\t\t\tconst component_data = componentData ? `Component Data: ${JSON.stringify(componentData, null, 2)}` : '';\n\n\t\t\tconst prompts = await promptLoader.loadPrompts('actions', {\n\t\t\t\tORIGINAL_USER_PROMPT: originalUserPrompt,\n\t\t\t\tCOMPONENT_INFO: component_info,\n\t\t\t\tCOMPONENT_DATA: component_data,\n\t\t\t\tCONVERSATION_HISTORY: conversationHistory || 'No previous conversation'\n\t\t\t});\n\n\t\t\tconst result = await LLM.stream<any>(\n\t\t\t\t{\n\t\t\t\t\tsys: prompts.system,\n\t\t\t\t\tuser: prompts.user\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmaxTokens: 800,\n\t\t\t\t\ttemperature: 0.7,\n\t\t\t\t\tapiKey: this.getApiKey(apiKey)\n\t\t\t\t},\n\t\t\t\ttrue // Parse as JSON\n\t\t\t) as any;\n\n\t\t\tconst nextQuestions = result.nextQuestions || [];\n\n\t\t\tlogCollector?.logExplanation(\n\t\t\t\t'Next questions generated',\n\t\t\t\t'Generated intelligent follow-up questions based on component',\n\t\t\t\t{\n\t\t\t\t\tcount: nextQuestions.length,\n\t\t\t\t\tquestions: nextQuestions\n\t\t\t\t}\n\t\t\t);\n\n\t\t\treturn nextQuestions;\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error generating next questions with ${this.getProviderName()}:`, error);\n\t\t\tlogCollector?.error(`Error generating next questions: ${(error as Error).message}`);\n\t\t\t// Return empty array on error instead of throwing\n\t\t\treturn [];\n\t\t}\n\t}\n}\n","import dotenv from 'dotenv';\nimport { BaseLLM, BaseLLMConfig } from './base-llm';\n\ndotenv.config();\n\nexport interface AnthropicLLMConfig extends BaseLLMConfig {}\n\n/**\n * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude\n */\nexport class AnthropicLLM extends BaseLLM {\n\tconstructor(config?: AnthropicLLMConfig) {\n\t\tsuper(config);\n\t}\n\n\tprotected getDefaultModel(): string {\n\t\treturn 'anthropic/claude-haiku-4-5-20251001';\n\t}\n\n\tprotected getDefaultApiKey(): string | undefined {\n\t\treturn process.env.ANTHROPIC_API_KEY;\n\t}\n\n\tprotected getProviderName(): string {\n\t\treturn 'Anthropic';\n\t}\n}\n\n// Export a singleton instance\nexport const anthropicLLM = new AnthropicLLM();\n","import { groqLLM } from \"./groq\";\nimport { anthropicLLM } from \"./anthropic\";\nimport { Component, LLMProvider } from \"../types\";\nimport dotenv from 'dotenv';\nimport { logger } from \"../utils/logger\";\n\ndotenv.config();\n\n\n\n/**\n * Parse LLM_PROVIDERS from environment variable\n * Expects a stringified JSON array like: '[\"anthropic\",\"groq\"]'\n */\nexport function getLLMProviders(): LLMProvider[] {\n const envProviders = process.env.LLM_PROVIDERS;\n\n const DEFAULT_PROVIDERS: LLMProvider[] = ['anthropic', 'groq'];\n if (!envProviders) {\n // Default to anthropic if not specified\n return DEFAULT_PROVIDERS;\n }\n\n try {\n const providers = JSON.parse(envProviders) as LLMProvider[];\n\n // Validate providers\n const validProviders = providers.filter(p => p === 'anthropic' || p === 'groq');\n\n if (validProviders.length === 0) {\n return DEFAULT_PROVIDERS;\n }\n\n return validProviders;\n } catch (error) {\n logger.error('Failed to parse LLM_PROVIDERS, defaulting to [\"anthropic\"]:', error);\n return DEFAULT_PROVIDERS;\n }\n}\n\n/**\n * Method 1: Use Anthropic Claude LLM\n */\nexport const useAnthropicMethod = async (prompt: string, components: Component[], apiKey?: string, logCollector?: any, conversationHistory?: string) => {\n const msg = 'Using Anthropic Claude matching method...';\n console.log(msg);\n logCollector?.info(msg);\n\n if (components.length === 0) {\n const emptyMsg = 'Components not loaded in memory. Please ensure components are fetched first.';\n logCollector?.error(emptyMsg);\n return { success: false, reason: emptyMsg };\n }\n\n try {\n const matchResult = await anthropicLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory);\n return { success: true, data: matchResult };\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n logCollector?.error(`Anthropic method failed: ${errorMsg}`);\n throw error; // Re-throw to be caught by the provider fallback mechanism\n }\n};\n\n/**\n * Method 2: Use Groq LLM\n */\nexport const useGroqMethod = async (prompt: string, components: Component[], apiKey?: string, logCollector?: any, conversationHistory?: string) => {\n const msg = 'Using Groq LLM matching method...';\n console.log(msg);\n logCollector?.info(msg);\n\n if (components.length === 0) {\n const emptyMsg = 'Components not loaded in memory. Please ensure components are fetched first.';\n logCollector?.error(emptyMsg);\n return { success: false, reason: emptyMsg };\n }\n\n try {\n const matchResult = await groqLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory);\n return { success: true, data: matchResult };\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n logCollector?.error(`Groq method failed: ${errorMsg}`);\n throw error; // Re-throw to be caught by the provider fallback mechanism\n }\n};\n\n//@to-do\nexport const getUserResponseFromCache = async (prompt: string) => {\n return false\n}\n\n/**\n * Get user response with automatic fallback between LLM providers\n * Tries providers in order specified by LLM_PROVIDERS or passed parameter\n */\nexport const get_user_response = async (\n prompt: string,\n components: Component[],\n anthropicApiKey?: string,\n groqApiKey?: string,\n llmProviders?: LLMProvider[],\n logCollector?: any,\n conversationHistory?: string\n) => {\n\n //first checking if he same prompt is already asked and we got successful response.\n const userResponse = await getUserResponseFromCache(prompt);\n if(userResponse){\n logCollector?.info('User response found in cache');\n return {\n success: true,\n data: userResponse\n };\n }\n\n const providers = llmProviders || getLLMProviders();\n const errors: { provider: LLMProvider; error: string }[] = [];\n\n const providerOrder = providers.join(', ');\n logCollector?.info(`LLM Provider order: [${providerOrder}]`);\n\n // Log conversation context info if available\n if (conversationHistory && conversationHistory.length > 0) {\n logCollector?.info(`Using conversation history with ${conversationHistory.split('\\n').filter((l: string) => l.startsWith('Q')).length} previous exchanges`);\n }\n\n for (let i = 0; i < providers.length; i++) {\n const provider = providers[i];\n const isLastProvider = i === providers.length - 1;\n\n try {\n const attemptMsg = `Attempting provider: ${provider} (${i + 1}/${providers.length})`;\n logCollector?.info(attemptMsg);\n\n let result;\n if (provider === 'anthropic') {\n result = await useAnthropicMethod(prompt, components, anthropicApiKey, logCollector, conversationHistory);\n } else if (provider === 'groq') {\n result = await useGroqMethod(prompt, components, groqApiKey, logCollector, conversationHistory);\n } else {\n continue; // Skip unknown providers\n }\n\n if (result.success) {\n const successMsg = `Success with provider: ${provider}`;\n logCollector?.info(successMsg);\n return result;\n } else {\n errors.push({ provider, error: result.reason || 'Unknown error' });\n const warnMsg = `Provider ${provider} returned unsuccessful result: ${result.reason}`;\n logCollector?.warn(warnMsg);\n }\n } catch (error) {\n const errorMessage = (error as Error).message;\n errors.push({ provider, error: errorMessage });\n\n const errorMsg = `Provider ${provider} failed: ${errorMessage}`;\n logCollector?.error(errorMsg);\n\n // If this is not the last provider, try the next one\n if (!isLastProvider) {\n const fallbackMsg = 'Falling back to next provider...';\n logCollector?.info(fallbackMsg);\n continue;\n }\n }\n }\n\n // All providers failed\n const errorSummary = errors\n .map(e => `${e.provider}: ${e.error}`)\n .join('; ');\n\n const failureMsg = `All LLM providers failed. Errors: ${errorSummary}`;\n logCollector?.error(failureMsg);\n\n return {\n success: false,\n reason: failureMsg\n };\n}","import { Message } from '../types';\n\nexport interface CapturedLog {\n timestamp: number;\n level: 'info' | 'error' | 'warn' | 'debug';\n message: string;\n type?: 'explanation' | 'query' | 'general';\n data?: Record<string, any>;\n}\n\n/**\n * UILogCollector captures logs during user prompt processing\n * and sends them to runtime via ui_logs message with uiBlockId as the message id\n * Logs are sent in real-time for streaming effect in the UI\n */\nexport class UILogCollector {\n private logs: CapturedLog[] = [];\n private uiBlockId: string | null;\n private clientId: string;\n private sendMessage: (message: Message) => void;\n\n constructor(\n clientId: string,\n sendMessage: (message: Message) => void,\n uiBlockId?: string\n ) {\n this.uiBlockId = uiBlockId || null;\n this.clientId = clientId;\n this.sendMessage = sendMessage;\n }\n\n /**\n * Check if logging is enabled (uiBlockId is provided)\n */\n isEnabled(): boolean {\n return this.uiBlockId !== null;\n }\n\n /**\n * Add a log entry with timestamp and immediately send to runtime\n */\n private addLog(\n level: 'info' | 'error' | 'warn' | 'debug',\n message: string,\n type?: 'explanation' | 'query' | 'general',\n data?: Record<string, any>\n ): void {\n const log: CapturedLog = {\n timestamp: Date.now(),\n level,\n message,\n ...(type && { type }),\n ...(data && { data }),\n };\n\n this.logs.push(log);\n\n // Send the log immediately to runtime for streaming effect\n this.sendLogImmediately(log);\n }\n\n /**\n * Send a single log to runtime immediately\n */\n private sendLogImmediately(log: CapturedLog): void {\n if (!this.isEnabled()) {\n return;\n }\n\n const response: Message = {\n id: this.uiBlockId!,\n type: 'UI_LOGS',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: this.clientId,\n },\n payload: {\n logs: [log], // Send single log in array\n },\n };\n\n this.sendMessage(response);\n }\n\n /**\n * Log info message\n */\n info(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('info', message, type, data);\n }\n }\n\n /**\n * Log error message\n */\n error(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('error', message, type, data);\n }\n }\n\n /**\n * Log warning message\n */\n warn(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('warn', message, type, data);\n }\n }\n\n /**\n * Log debug message\n */\n debug(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('debug', message, type, data);\n }\n }\n\n /**\n * Log LLM explanation with typed metadata\n */\n logExplanation(message: string, explanation: string, data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('info', message, 'explanation', {\n explanation,\n ...data,\n });\n }\n }\n\n /**\n * Log generated query with typed metadata\n */\n logQuery(message: string, query: string, data?: Record<string, any>): void {\n if (this.isEnabled()) {\n this.addLog('info', message, 'query', {\n query,\n ...data,\n });\n }\n }\n\n /**\n * Send all collected logs at once (optional, for final summary)\n */\n sendAllLogs(): void {\n if (!this.isEnabled() || this.logs.length === 0) {\n return;\n }\n\n const response: Message = {\n id: this.uiBlockId!,\n type: 'UI_LOGS',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: this.clientId,\n },\n payload: {\n logs: this.logs,\n },\n };\n\n this.sendMessage(response);\n }\n\n /**\n * Get all collected logs\n */\n getLogs(): CapturedLog[] {\n return [...this.logs];\n }\n\n /**\n * Clear all logs\n */\n clearLogs(): void {\n this.logs = [];\n }\n\n /**\n * Set uiBlockId (in case it's provided later)\n */\n setUIBlockId(uiBlockId: string): void {\n this.uiBlockId = uiBlockId;\n }\n}\n","/**\n * Configuration for conversation context and history management\n */\nexport const CONTEXT_CONFIG = {\n /**\n * Maximum number of previous UIBlocks to include as conversation context\n * Set to 0 to disable conversation history\n * Higher values provide more context but may increase token usage\n */\n MAX_CONVERSATION_CONTEXT_BLOCKS: 2,\n};\n","import { Component, LLMProvider, Message, UserPromptRequestMessageSchema } from \"../types\";\nimport { get_user_response } from \"../userResponse\";\nimport { logger } from \"../utils/logger\";\nimport { UILogCollector } from \"../utils/log-collector\";\nimport { ThreadManager, UIBlock } from \"../threads\";\nimport { CONTEXT_CONFIG } from \"../config/context\";\n\n// Track processed message IDs to prevent duplicates\nconst processedMessageIds = new Set<string>();\n\nexport async function handleUserPromptRequest(\n\tdata: any,\n\tcomponents: Component[],\n\tsendMessage: (message: Message) => void,\n\tanthropicApiKey?: string,\n\tgroqApiKey?: string,\n\tllmProviders?: LLMProvider[]\n): Promise<void> {\n\ttry {\n\t\tconst userPromptRequest = UserPromptRequestMessageSchema.parse(data);\n\t\tconst { id, payload } = userPromptRequest;\n\n\t\tconst prompt = payload.prompt;\n\t\tconst SA_RUNTIME = payload.SA_RUNTIME;\n\n\t\tconst wsId = userPromptRequest.from.id || 'unknown';\n\n\t\tlogger.info(`[REQUEST ${id}] Processing user prompt: \"${prompt.substring(0, 50)}...\"`);\n\n\t\t// Check if this message ID has already been processed\n\t\tif (processedMessageIds.has(id)) {\n\t\t\tlogger.warn(`[REQUEST ${id}] Duplicate request detected - ignoring`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Mark this message ID as processed\n\t\tprocessedMessageIds.add(id);\n\n\t\t// Clean up old message IDs (keep only last 100)\n\t\tif (processedMessageIds.size > 100) {\n\t\t\tconst firstId = processedMessageIds.values().next().value;\n\t\t\tif (firstId) {\n\t\t\t\tprocessedMessageIds.delete(firstId);\n\t\t\t}\n\t\t}\n\n\t\t// Validate SA_RUNTIME and extract threadId and uiBlockId\n\t\tif (!SA_RUNTIME) {\n\t\t\tsendDataResponse(id, {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'SA_RUNTIME is required'\n\t\t\t}, sendMessage, wsId);\n\t\t\treturn;\n\t\t}\n\n\t\tconst threadId = SA_RUNTIME.threadId;\n\t\tconst existingUiBlockId = SA_RUNTIME.uiBlockId;\n\n\t\tif (!threadId) {\n\t\t\tsendDataResponse(id, {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'threadId in SA_RUNTIME is required'\n\t\t\t}, sendMessage, wsId);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!existingUiBlockId) {\n\t\t\tsendDataResponse(id, {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'uiBlockId in SA_RUNTIME is required'\n\t\t\t}, sendMessage, wsId);\n\t\t\treturn;\n\t\t}\n\n\t\t// Create log collector with uiBlockId\n\t\tconst logCollector = new UILogCollector(wsId, sendMessage, existingUiBlockId);\n\n\t\tif (!prompt) {\n\t\t\tsendDataResponse(id, {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Prompt not found'\n\t\t\t}, sendMessage, wsId);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!components || components.length === 0) {\n\t\t\tsendDataResponse(id, {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Components not found'\n\t\t\t}, sendMessage, wsId);\n\t\t\treturn;\n\t\t}\n\n\t\tlogCollector.info(`Starting user prompt request with ${components.length} components`);\n\n\t\t// Get or create thread BEFORE processing to enable conversation context\n\t\tconst threadManager = ThreadManager.getInstance();\n\t\tlet thread = threadManager.getThread(threadId);\n\t\tif (!thread) {\n\t\t\tthread = threadManager.createThread(threadId);\n\t\t\tlogger.info(`Created new thread: ${threadId}`);\n\t\t}\n\n\t\t// Extract conversation context from thread (excluding current UIBlock)\n\t\tconst conversationHistory = thread.getConversationContext(CONTEXT_CONFIG.MAX_CONVERSATION_CONTEXT_BLOCKS, existingUiBlockId);\n\n\t\t// Get user response with log collector and conversation context\n\t\tconst userResponse = await get_user_response(prompt, components, anthropicApiKey, groqApiKey, llmProviders, logCollector, conversationHistory);\n\n\t\t// Log completion (sent immediately if uiBlockId was provided)\n\t\tlogCollector.info('User prompt request completed');\n\n\t\t// If response is successful, create UIBlock and add to Thread\n\t\tif (userResponse.success && userResponse.data && typeof userResponse.data === 'object' && 'component' in userResponse.data) {\n\t\t\tconst component = (userResponse.data as any).component;\n\n\t\t\t// Use the uiBlockId from SA_RUNTIME (already validated)\n\t\t\tconst uiBlockId = existingUiBlockId;\n\n\t\t\t// Create UIBlock with component metadata and empty component data (will fill later)\n\t\t\tconst uiBlock = new UIBlock(\n\t\t\t\tprompt,\n\t\t\t\t{}, // componentData: initially empty, will be filled later\n\t\t\t\tcomponent || {}, // generatedComponentMetadata: full component object (ComponentSchema)\n\t\t\t\t[], // actions: empty initially\n\t\t\t\tuiBlockId\n\t\t\t);\n\n\t\t\t// Add UIBlock to Thread\n\t\t\tthread.addUIBlock(uiBlock);\n\n\t\t\tlogger.info(`Created UIBlock: ${uiBlockId} in Thread: ${threadId}`);\n\n\t\t\t// Send response with uiBlockId and threadId\n\t\t\tsendDataResponse(id, {\n\t\t\t\t...userResponse,\n\t\t\t\tuiBlockId,\n\t\t\t\tthreadId\n\t\t\t}, sendMessage, wsId);\n\t\t} else {\n\t\t\t// If response failed, still send it but without UIBlock/Thread data\n\t\t\tsendDataResponse(id, userResponse, sendMessage, wsId);\n\t\t}\n\n\t\treturn;\n\t}\n\tcatch (error) {\n\t\tlogger.error('Failed to handle user prompt request:', error);\n\t}\n}\n\n/**\n * Send a data_res response message\n */\nfunction sendDataResponse(\n\tid: string,\n\tres: { success: boolean; error?: string; data?: any; uiBlockId?: string; threadId?: string },\n\tsendMessage: (message: Message) => void,\n\tclientId?: string,\n): void {\n\tconst response: Message = {\n\t\tid,\n\t\ttype: 'USER_PROMPT_RES',\n\t\tfrom: { type: 'data-agent' },\n\t\tto: {\n\t\t\ttype: 'runtime',\n\t\t\tid: clientId\n\t\t},\n\t\tpayload: {\n\t\t\t...res,\n\t\t}\n\t};\n\tsendMessage(response);\n} ","import { Component, Message, UserPromptSuggestionsMessageSchema } from '../types';\nimport { logger } from '../utils/logger';\n\n/**\n * Handle user prompt suggestions request\n * Searches components based on prompt keywords and returns top matches\n */\nexport async function handleUserPromptSuggestions(\n data: any,\n components: Component[],\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const request = UserPromptSuggestionsMessageSchema.parse(data);\n const { id, payload, from } = request;\n\n const { prompt, limit = 5 } = payload;\n const wsId = from.id;\n\n // Validate input\n if (!prompt || prompt.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Prompt is required and cannot be empty'\n }, sendMessage, wsId);\n return;\n }\n\n if (!components || components.length === 0) {\n sendResponse(id, {\n success: true,\n data: {\n prompt,\n suggestions: [],\n count: 0,\n message: 'No components available'\n }\n }, sendMessage, wsId);\n return;\n }\n\n // Search components based on prompt\n const suggestions = searchComponents(prompt, components, limit);\n\n\n sendResponse(id, {\n success: true,\n data: {\n prompt,\n suggestions,\n count: suggestions.length,\n message: `Found ${suggestions.length} matching components`\n }\n }, sendMessage, wsId);\n\n } catch (error) {\n logger.error('Failed to handle user prompt suggestions request:', error);\n sendResponse(null, {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n }, sendMessage);\n }\n}\n\n/**\n * Search components based on prompt keywords\n * Searches in component name, description, keywords, and category\n * @param prompt - Search prompt\n * @param components - List of components to search in\n * @param limit - Maximum number of results to return\n * @returns Matching components sorted by relevance\n */\nfunction searchComponents(prompt: string, components: Component[], limit: number): Component[] {\n const promptLower = prompt.toLowerCase();\n const promptTokens = promptLower.split(/\\s+/).filter(token => token.length > 0);\n\n // Score each component based on keyword matches\n const scoredComponents = components.map(component => {\n let score = 0;\n\n const componentName = component.name.toLowerCase();\n const componentDesc = component.description.toLowerCase();\n const componentKeywords = (component.keywords || []).map(k => k.toLowerCase());\n const componentCategory = (component.category || '').toLowerCase();\n\n // Search in each field with different weights\n for (const token of promptTokens) {\n // Exact name match (highest weight)\n if (componentName === token) {\n score += 10;\n }\n // Name contains token\n else if (componentName.includes(token)) {\n score += 5;\n }\n\n // Exact keyword match\n if (componentKeywords.includes(token)) {\n score += 8;\n }\n // Keywords contain token\n else if (componentKeywords.some(k => k.includes(token))) {\n score += 4;\n }\n\n // Description contains token\n if (componentDesc.includes(token)) {\n score += 2;\n }\n\n // Category contains token\n if (componentCategory.includes(token)) {\n score += 3;\n }\n }\n\n return { component, score };\n });\n\n // Filter out components with score 0, sort by score (descending), and take top results\n return scoredComponents\n .filter(({ score }) => score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map(({ component }) => component);\n}\n\n/**\n * Send user prompt suggestions response\n */\nfunction sendResponse(\n id: string | null,\n res: { success: boolean; error?: string; data?: any },\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id: id || 'unknown',\n type: 'USER_PROMPT_SUGGESTIONS_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: clientId\n },\n payload: {\n ...res,\n }\n };\n\n sendMessage(response);\n}\n","import { anthropicLLM } from './anthropic';\nimport { groqLLM } from './groq';\nimport { LLMProvider, Component } from '../types';\nimport { logger } from '../utils/logger';\n\n/**\n * Generate next questions based on the original user prompt and generated component\n * Routes to the appropriate LLM provider (Anthropic or Groq)\n * Falls back to next provider if current provider fails or returns empty results\n */\nexport async function generateNextQuestions(\n\toriginalUserPrompt: string,\n\tcomponent: Component,\n\tcomponentData?: Record<string, unknown>,\n\tanthropicApiKey?: string,\n\tgroqApiKey?: string,\n\tllmProviders?: LLMProvider[],\n\tlogCollector?: any,\n\tconversationHistory?: string\n): Promise<string[]> {\n\ttry {\n\t\t// Determine which providers to use\n\t\tconst providers = llmProviders || ['anthropic'];\n\n\t\t// Try each provider in order\n\t\tfor (const provider of providers) {\n\t\t\ttry {\n\t\t\t\tlogger.info(`Generating next questions using provider: ${provider}`);\n\n\t\t\t\tlet result: string[] = [];\n\n\t\t\t\tif (provider === 'groq') {\n\t\t\t\t\tresult = await groqLLM.generateNextQuestions(\n\t\t\t\t\t\toriginalUserPrompt,\n\t\t\t\t\t\tcomponent,\n\t\t\t\t\t\tcomponentData,\n\t\t\t\t\t\tgroqApiKey,\n\t\t\t\t\t\tlogCollector,\n\t\t\t\t\t\tconversationHistory\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\t// Default to Anthropic\n\t\t\t\t\tresult = await anthropicLLM.generateNextQuestions(\n\t\t\t\t\t\toriginalUserPrompt,\n\t\t\t\t\t\tcomponent,\n\t\t\t\t\t\tcomponentData,\n\t\t\t\t\t\tanthropicApiKey,\n\t\t\t\t\t\tlogCollector,\n\t\t\t\t\t\tconversationHistory\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// If we got results, return them\n\t\t\t\tif (result && result.length > 0) {\n\t\t\t\t\tlogger.info(`Successfully generated ${result.length} questions with ${provider}`);\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tlogger.warn(`No questions generated from ${provider}, trying next provider...`);\n\t\t\t} catch (providerError) {\n\t\t\t\tlogger.warn(`Provider ${provider} failed:`, providerError);\n\t\t\t\tlogCollector?.warn(`Provider ${provider} failed, trying next provider...`);\n\t\t\t\t// Continue to next provider\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// All providers failed or returned empty results\n\t\tlogger.warn('All providers failed or returned no questions');\n\t\treturn [];\n\t} catch (error) {\n\t\tlogger.error('Error generating next questions:', error);\n\t\tlogCollector?.error(`Error generating next questions: ${(error as Error).message}`);\n\t\t// Return empty array on error\n\t\treturn [];\n\t}\n}\n","import { ActionsRequestMessageSchema, type LLMProvider, type Message } from '../types';\nimport { generateNextQuestions } from '../userResponse/next-questions';\nimport { logger } from '../utils/logger';\nimport { UILogCollector } from '../utils/log-collector';\nimport { ThreadManager } from '../threads';\nimport { CONTEXT_CONFIG } from '../config/context';\n\n/**\n * Handle incoming actions messages from runtime\n * Generates suggested next questions based on the original user prompt and generated component\n */\nexport async function handleActionsRequest(\n data: any,\n sendMessage: (message: Message) => void,\n anthropicApiKey?: string,\n groqApiKey?: string,\n llmProviders?: LLMProvider[]\n): Promise<void> {\n try {\n const actionsRequest = ActionsRequestMessageSchema.parse(data);\n const { id, payload } = actionsRequest;\n const { SA_RUNTIME } = payload;\n\n const wsId = actionsRequest.from.id || 'unknown';\n\n // SA_RUNTIME is required to fetch actions from UIBlock\n if (!SA_RUNTIME) {\n sendResponse(id, {\n success: false,\n error: 'SA_RUNTIME with threadId and uiBlockId is required'\n }, sendMessage, wsId);\n return;\n }\n\n const uiBlockId = SA_RUNTIME.uiBlockId;\n const threadId = SA_RUNTIME.threadId;\n\n // Get UIBlock from ThreadManager\n const threadManager = ThreadManager.getInstance();\n const thread = threadManager.getThread(threadId);\n\n if (!thread) {\n sendResponse(id, {\n success: false,\n error: `Thread '${threadId}' not found`\n }, sendMessage, wsId);\n return;\n }\n\n const uiBlock = thread.getUIBlock(uiBlockId);\n if (!uiBlock) {\n sendResponse(id, {\n success: false,\n error: `UIBlock '${uiBlockId}' not found in thread '${threadId}'`\n }, sendMessage, wsId);\n return;\n }\n\n // Create log collector with uiBlockId\n const logCollector = new UILogCollector(wsId, sendMessage, uiBlockId);\n\n // Extract data from UIBlock\n const userQuestion = uiBlock.getUserQuestion();\n const component = uiBlock.getComponentMetadata();\n const componentData = uiBlock.getComponentData();\n\n // Extract conversation context from thread (excluding current UIBlock)\n const conversationHistory = thread.getConversationContext(CONTEXT_CONFIG.MAX_CONVERSATION_CONTEXT_BLOCKS, uiBlockId);\n\n logCollector.info(`Generating actions for UIBlock: ${uiBlockId}`);\n logger.info(`Generating actions for component: ${component?.name || 'unknown'}`);\n\n // Use getOrFetchActions to manage action state\n const actions = await uiBlock.getOrFetchActions(async () => {\n // Generate next questions using extracted data from UIBlock and conversation history\n const nextQuestions = await generateNextQuestions(\n userQuestion,\n component as any,\n componentData,\n anthropicApiKey,\n groqApiKey,\n llmProviders,\n logCollector,\n conversationHistory\n );\n\n // Convert questions to actions format\n return nextQuestions.map((question: string, index: number) => ({\n id: `action_${index}_${Date.now()}`,\n name: question,\n type: 'next_question',\n question\n }));\n });\n\n logCollector.info(`Generated ${actions.length} actions successfully`);\n\n sendResponse(id, {\n success: true,\n data: {\n actions,\n componentName: component?.name,\n componentId: component?.id,\n uiBlockId,\n threadId\n }\n }, sendMessage, wsId);\n\n } catch (error) {\n logger.error('Failed to handle actions request:', error);\n sendResponse(null, {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n }, sendMessage);\n }\n}\n\n/**\n * Send actions response\n */\nfunction sendResponse(\n id: string | null,\n res: { success: boolean; error?: string; data?: any },\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id: id || 'unknown',\n type: 'ACTIONS_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'runtime',\n id: clientId\n },\n payload: {\n ...res,\n }\n };\n\n sendMessage(response);\n}\n","import { Component, ComponentListResponseMessageSchema, ComponentSchema, ComponentsSchema, Message } from \"../types\";\nimport { logger } from \"../utils/logger\";\n\n\nexport async function handleComponentListResponse(\n data: any,\n storeComponents:(components: Component[])=>void\n ): Promise<void> {\n try {\n const componentListResponse = ComponentListResponseMessageSchema.parse(data);\n const { id, payload } = componentListResponse;\n \n const componentsList = payload.components;\n\n if(!componentsList){\n logger.error('Components list not found in the response');\n return;\n }\n\n const components = ComponentsSchema.parse(componentsList);\n storeComponents(components);\n\n return;\n } catch (error) {\n logger.error('Failed to handle user prompt request:', error);\n }\n } \n\n\n","import { UsersRequestMessageSchema, Message } from '../types';\nimport { getUserManager } from '../auth/user-storage';\nimport { logger } from '../utils/logger';\n\n/**\n * Handle unified users management request\n * Supports operations: create, update, delete, getAll, getOne\n * Only accepts requests from 'admin' type\n */\nexport async function handleUsersRequest(\n data: any,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const request = UsersRequestMessageSchema.parse(data);\n const { id, payload, from } = request;\n const { operation, data: requestData } = payload;\n const username = requestData?.username;\n const password = requestData?.password;\n\n // Verify request is from admin\n if (from.type !== 'admin') {\n sendResponse(id, {\n success: false,\n error: 'Unauthorized: Only admin can manage users'\n }, sendMessage, from.id);\n logger.warn(`Unauthorized user management attempt from: ${from.type}`);\n return;\n }\n\n const userManager = getUserManager();\n\n // Route to appropriate operation handler\n switch (operation) {\n case 'create':\n await handleCreate(id, username, password, userManager, sendMessage, from.id);\n break;\n\n case 'update':\n await handleUpdate(id, username, password, userManager, sendMessage, from.id);\n break;\n\n case 'delete':\n await handleDelete(id, username, userManager, sendMessage, from.id);\n break;\n\n case 'getAll':\n await handleGetAll(id, userManager, sendMessage, from.id);\n break;\n\n case 'getOne':\n await handleGetOne(id, username, userManager, sendMessage, from.id);\n break;\n\n default:\n sendResponse(id, {\n success: false,\n error: `Unknown operation: ${operation}`\n }, sendMessage, from.id);\n }\n\n } catch (error) {\n logger.error('Failed to handle users request:', error);\n sendResponse(null, {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n }, sendMessage);\n }\n}\n\n/**\n * Handle create user operation\n */\nasync function handleCreate(\n id: string,\n username: string | undefined,\n password: string | undefined,\n userManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!username || username.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Username is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n if (!password || password.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Password is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n // Check if user already exists\n if (userManager.userExists(username)) {\n sendResponse(id, {\n success: false,\n error: `User '${username}' already exists`\n }, sendMessage, clientId);\n return;\n }\n\n let wsIds: string[] = [];\n if (clientId) {\n wsIds.push(clientId);\n }\n\n // Create user\n const newUser = userManager.createUser({\n username,\n password: password,\n wsIds\n });\n\n logger.info(`User created by admin: ${username}`);\n\n sendResponse(id, {\n success: true,\n data: {\n username: newUser.username,\n message: `User '${username}' created successfully`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle update user operation\n */\nasync function handleUpdate(\n id: string,\n username: string | undefined,\n password: string | undefined,\n userManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!username || username.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Username is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n // Check if user exists\n if (!userManager.userExists(username)) {\n sendResponse(id, {\n success: false,\n error: `User '${username}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n // Build update object\n const updates: any = {};\n\n // Only update password if provided\n if (password && password.trim().length > 0) {\n updates.password = password;\n }\n\n // If nothing to update, return error\n if (Object.keys(updates).length === 0) {\n sendResponse(id, {\n success: false,\n error: 'No fields to update. Please provide password or other valid fields.'\n }, sendMessage, clientId);\n return;\n }\n\n // Update user\n const updatedUser = userManager.updateUser(username, updates);\n\n logger.info(`User updated by admin: ${username}`);\n\n sendResponse(id, {\n success: true,\n data: {\n username: updatedUser.username,\n message: `User '${username}' updated successfully`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle delete user operation\n */\nasync function handleDelete(\n id: string,\n username: string | undefined,\n userManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!username || username.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Username is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n // Check if user exists\n if (!userManager.userExists(username)) {\n sendResponse(id, {\n success: false,\n error: `User '${username}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n // Delete user\n const deleted = userManager.deleteUser(username);\n\n if (!deleted) {\n sendResponse(id, {\n success: false,\n error: `Failed to delete user '${username}'`\n }, sendMessage, clientId);\n return;\n }\n\n logger.info(`User deleted by admin: ${username}`);\n\n sendResponse(id, {\n success: true,\n data: {\n username: username,\n message: `User '${username}' deleted successfully`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get all users operation\n */\nasync function handleGetAll(\n id: string,\n userManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n const users = userManager.getAllUsers();\n\n // Remove sensitive information like passwords\n const sanitizedUsers = users.map((user: any) => ({\n username: user.username,\n wsIds: user.wsIds || []\n }));\n\n logger.info(`Admin retrieved all users (count: ${sanitizedUsers.length})`);\n\n sendResponse(id, {\n success: true,\n data: {\n users: sanitizedUsers,\n count: sanitizedUsers.length,\n message: `Retrieved ${sanitizedUsers.length} users`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get one user operation\n */\nasync function handleGetOne(\n id: string,\n username: string | undefined,\n userManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!username || username.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Username is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n // Check if user exists\n if (!userManager.userExists(username)) {\n sendResponse(id, {\n success: false,\n error: `User '${username}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n const user = userManager.getUser(username);\n\n // Remove sensitive information\n const sanitizedUser = {\n username: user.username,\n wsIds: user.wsIds || []\n };\n\n logger.info(`Admin retrieved user: ${username}`);\n\n sendResponse(id, {\n success: true,\n data: {\n user: sanitizedUser,\n message: `Retrieved user '${username}'`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Send users response\n */\nfunction sendResponse(\n id: string | null,\n res: { success: boolean; error?: string; data?: any },\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id: id || 'unknown',\n type: 'USERS_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'admin',\n id: clientId\n },\n payload: {\n ...res,\n }\n };\n\n sendMessage(response);\n}\n","import { DashboardManager } from './dashboard-manager';\nimport { logger } from '../utils/logger';\n\nlet dashboardManager: DashboardManager | null = null;\n\n/**\n * Set the dashboard manager instance\n * @param manager - DashboardManager instance to use\n */\nexport function setDashboardManager(manager: DashboardManager): void {\n dashboardManager = manager;\n logger.info('DashboardManager instance set');\n}\n\n/**\n * Get the dashboard manager instance\n * @throws Error if dashboard manager is not initialized\n * @returns DashboardManager instance\n */\nexport function getDashboardManager(): DashboardManager {\n if (!dashboardManager) {\n throw new Error('DashboardManager not initialized. Call setDashboardManager first.');\n }\n return dashboardManager;\n}\n","import { DashboardsRequestMessageSchema, Message } from '../types';\nimport { getDashboardManager } from '../dashboards/dashboard-storage';\nimport { logger } from '../utils/logger';\n\n/**\n * Handle unified dashboards management request\n * Supports operations: create, update, delete, getAll, getOne\n * Only accepts requests from 'admin' type\n */\nexport async function handleDashboardsRequest(\n data: any,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const request = DashboardsRequestMessageSchema.parse(data);\n const { id, payload, from } = request;\n const { operation, data: requestData } = payload;\n const dashboardId = requestData?.dashboardId;\n const dashboard = requestData?.dashboard;\n\n // Verify request is from admin\n if (from.type !== 'admin') {\n sendResponse(id, {\n success: false,\n error: 'Unauthorized: Only admin can manage dashboards'\n }, sendMessage, from.id);\n logger.warn(`Unauthorized dashboard management attempt from: ${from.type}`);\n return;\n }\n\n const dashboardManager = getDashboardManager();\n\n // Route to appropriate operation handler\n switch (operation) {\n case 'create':\n await handleCreate(id, dashboardId, dashboard, dashboardManager, sendMessage, from.id);\n break;\n\n case 'update':\n await handleUpdate(id, dashboardId, dashboard, dashboardManager, sendMessage, from.id);\n break;\n\n case 'delete':\n await handleDelete(id, dashboardId, dashboardManager, sendMessage, from.id);\n break;\n\n case 'getAll':\n await handleGetAll(id, dashboardManager, sendMessage, from.id);\n break;\n\n case 'getOne':\n await handleGetOne(id, dashboardId, dashboardManager, sendMessage, from.id);\n break;\n\n default:\n sendResponse(id, {\n success: false,\n error: `Unknown operation: ${operation}`\n }, sendMessage, from.id);\n }\n\n } catch (error) {\n logger.error('Failed to handle dashboards request:', error);\n sendResponse(null, {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n }, sendMessage);\n }\n}\n\n/**\n * Handle create dashboard operation\n */\nasync function handleCreate(\n id: string,\n dashboardId: string | undefined,\n dashboard: any,\n dashboardManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!dashboardId || dashboardId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n if (!dashboard) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard data is required'\n }, sendMessage, clientId);\n return;\n }\n\n try {\n const createdDashboard = dashboardManager.createDashboard(dashboardId, dashboard);\n\n sendResponse(id, {\n success: true,\n data: {\n dashboardId,\n dashboard: createdDashboard,\n message: `Dashboard '${dashboardId}' created successfully`\n }\n }, sendMessage, clientId);\n } catch (error) {\n sendResponse(id, {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create dashboard'\n }, sendMessage, clientId);\n }\n}\n\n/**\n * Handle update dashboard operation\n */\nasync function handleUpdate(\n id: string,\n dashboardId: string | undefined,\n dashboard: any,\n dashboardManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!dashboardId || dashboardId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n if (!dashboard) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard data is required'\n }, sendMessage, clientId);\n return;\n }\n\n try {\n const updatedDashboard = dashboardManager.updateDashboard(dashboardId, dashboard);\n\n if (!updatedDashboard) {\n sendResponse(id, {\n success: false,\n error: `Dashboard '${dashboardId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n sendResponse(id, {\n success: true,\n data: {\n dashboardId,\n dashboard: updatedDashboard,\n message: `Dashboard '${dashboardId}' updated successfully`\n }\n }, sendMessage, clientId);\n } catch (error) {\n sendResponse(id, {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to update dashboard'\n }, sendMessage, clientId);\n }\n}\n\n/**\n * Handle delete dashboard operation\n */\nasync function handleDelete(\n id: string,\n dashboardId: string | undefined,\n dashboardManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!dashboardId || dashboardId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n const deleted = dashboardManager.deleteDashboard(dashboardId);\n\n if (!deleted) {\n sendResponse(id, {\n success: false,\n error: `Dashboard '${dashboardId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n sendResponse(id, {\n success: true,\n data: {\n dashboardId,\n message: `Dashboard '${dashboardId}' deleted successfully`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get all dashboards operation\n */\nasync function handleGetAll(\n id: string,\n dashboardManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n const dashboards = dashboardManager.getAllDashboards();\n\n logger.info(`Admin retrieved all dashboards (count: ${dashboards.length})`);\n\n sendResponse(id, {\n success: true,\n data: {\n dashboards,\n count: dashboards.length,\n message: `Retrieved ${dashboards.length} dashboards`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get one dashboard operation\n */\nasync function handleGetOne(\n id: string,\n dashboardId: string | undefined,\n dashboardManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!dashboardId || dashboardId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Dashboard ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n const dashboard = dashboardManager.getDashboard(dashboardId);\n\n if (!dashboard) {\n sendResponse(id, {\n success: false,\n error: `Dashboard '${dashboardId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n logger.info(`Admin retrieved dashboard: ${dashboardId}`);\n\n sendResponse(id, {\n success: true,\n data: {\n dashboardId,\n dashboard,\n message: `Retrieved dashboard '${dashboardId}'`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Send dashboards response\n */\nfunction sendResponse(\n id: string | null,\n res: { success: boolean; error?: string; data?: any },\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id: id || 'unknown',\n type: 'DASHBOARDS_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'admin',\n id: clientId\n },\n payload: {\n ...res,\n }\n };\n\n sendMessage(response);\n}\n","import { ReportManager } from './report-manager';\n\n/**\n * Global report manager instance\n */\nlet reportManager: ReportManager | null = null;\n\n/**\n * Get the global report manager instance\n * @returns ReportManager instance\n * @throws Error if report manager is not initialized\n */\nexport function getReportManager(): ReportManager {\n if (!reportManager) {\n throw new Error('Report manager not initialized. Call setReportManager first.');\n }\n return reportManager;\n}\n\n/**\n * Set the global report manager instance\n * @param manager - ReportManager instance to set\n */\nexport function setReportManager(manager: ReportManager): void {\n reportManager = manager;\n}\n","import { ReportsRequestMessageSchema, Message } from '../types';\nimport { getReportManager } from '../reports/report-storage';\nimport { logger } from '../utils/logger';\n\n/**\n * Handle unified reports management request\n * Supports operations: create, update, delete, getAll, getOne\n * Only accepts requests from 'admin' type\n */\nexport async function handleReportsRequest(\n data: any,\n sendMessage: (message: Message) => void\n): Promise<void> {\n try {\n const request = ReportsRequestMessageSchema.parse(data);\n const { id, payload, from } = request;\n const { operation, data: requestData } = payload;\n const reportId = requestData?.reportId;\n const report = requestData?.report;\n\n // Verify request is from admin\n if (from.type !== 'admin') {\n sendResponse(id, {\n success: false,\n error: 'Unauthorized: Only admin can manage reports'\n }, sendMessage, from.id);\n logger.warn(`Unauthorized report management attempt from: ${from.type}`);\n return;\n }\n\n const reportManager = getReportManager();\n\n // Route to appropriate operation handler\n switch (operation) {\n case 'create':\n await handleCreate(id, reportId, report, reportManager, sendMessage, from.id);\n break;\n\n case 'update':\n await handleUpdate(id, reportId, report, reportManager, sendMessage, from.id);\n break;\n\n case 'delete':\n await handleDelete(id, reportId, reportManager, sendMessage, from.id);\n break;\n\n case 'getAll':\n await handleGetAll(id, reportManager, sendMessage, from.id);\n break;\n\n case 'getOne':\n await handleGetOne(id, reportId, reportManager, sendMessage, from.id);\n break;\n\n default:\n sendResponse(id, {\n success: false,\n error: `Unknown operation: ${operation}`\n }, sendMessage, from.id);\n }\n\n } catch (error) {\n logger.error('Failed to handle reports request:', error);\n sendResponse(null, {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n }, sendMessage);\n }\n}\n\n/**\n * Handle create report operation\n */\nasync function handleCreate(\n id: string,\n reportId: string | undefined,\n report: any,\n reportManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!reportId || reportId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Report ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n if (!report) {\n sendResponse(id, {\n success: false,\n error: 'Report data is required'\n }, sendMessage, clientId);\n return;\n }\n\n try {\n const createdReport = reportManager.createReport(reportId, report);\n\n sendResponse(id, {\n success: true,\n data: {\n reportId,\n report: createdReport,\n message: `Report '${reportId}' created successfully`\n }\n }, sendMessage, clientId);\n } catch (error) {\n sendResponse(id, {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create report'\n }, sendMessage, clientId);\n }\n}\n\n/**\n * Handle update report operation\n */\nasync function handleUpdate(\n id: string,\n reportId: string | undefined,\n report: any,\n reportManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!reportId || reportId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Report ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n if (!report) {\n sendResponse(id, {\n success: false,\n error: 'Report data is required'\n }, sendMessage, clientId);\n return;\n }\n\n try {\n const updatedReport = reportManager.updateReport(reportId, report);\n\n if (!updatedReport) {\n sendResponse(id, {\n success: false,\n error: `Report '${reportId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n sendResponse(id, {\n success: true,\n data: {\n reportId,\n report: updatedReport,\n message: `Report '${reportId}' updated successfully`\n }\n }, sendMessage, clientId);\n } catch (error) {\n sendResponse(id, {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to update report'\n }, sendMessage, clientId);\n }\n}\n\n/**\n * Handle delete report operation\n */\nasync function handleDelete(\n id: string,\n reportId: string | undefined,\n reportManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!reportId || reportId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Report ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n const deleted = reportManager.deleteReport(reportId);\n\n if (!deleted) {\n sendResponse(id, {\n success: false,\n error: `Report '${reportId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n sendResponse(id, {\n success: true,\n data: {\n reportId,\n message: `Report '${reportId}' deleted successfully`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get all reports operation\n */\nasync function handleGetAll(\n id: string,\n reportManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n const reports = reportManager.getAllReports();\n\n logger.info(`Admin retrieved all reports (count: ${reports.length})`);\n\n sendResponse(id, {\n success: true,\n data: {\n reports,\n count: reports.length,\n message: `Retrieved ${reports.length} reports`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Handle get one report operation\n */\nasync function handleGetOne(\n id: string,\n reportId: string | undefined,\n reportManager: any,\n sendMessage: (message: Message) => void,\n clientId?: string\n): Promise<void> {\n // Validate input\n if (!reportId || reportId.trim().length === 0) {\n sendResponse(id, {\n success: false,\n error: 'Report ID is required and cannot be empty'\n }, sendMessage, clientId);\n return;\n }\n\n const report = reportManager.getReport(reportId);\n\n if (!report) {\n sendResponse(id, {\n success: false,\n error: `Report '${reportId}' not found`\n }, sendMessage, clientId);\n return;\n }\n\n logger.info(`Admin retrieved report: ${reportId}`);\n\n sendResponse(id, {\n success: true,\n data: {\n reportId,\n report,\n message: `Retrieved report '${reportId}'`\n }\n }, sendMessage, clientId);\n}\n\n/**\n * Send reports response\n */\nfunction sendResponse(\n id: string | null,\n res: { success: boolean; error?: string; data?: any },\n sendMessage: (message: Message) => void,\n clientId?: string,\n): void {\n const response: Message = {\n id: id || 'unknown',\n type: 'REPORTS_RES',\n from: { type: 'data-agent' },\n to: {\n type: 'admin',\n id: clientId\n },\n payload: {\n ...res,\n }\n };\n\n sendMessage(response);\n}\n","import fs from 'fs';\nimport path from 'path';\nimport os from 'os';\nimport { logger } from '../utils/logger';\n\nexport interface User {\n username: string;\n password: string;\n wsIds: string[];\n}\n\nexport interface UsersData {\n users: User[];\n}\n\n/**\n * UserManager class to handle CRUD operations on users with file persistence\n * and in-memory caching. Changes are synced to file periodically.\n */\nexport class UserManager {\n private users: User[] = [];\n private filePath: string;\n private hasChanged: boolean = false;\n private syncInterval: ReturnType<typeof setInterval> | null = null;\n private syncIntervalMs: number;\n private isInitialized: boolean = false;\n\n /**\n * Initialize UserManager with file path and sync interval\n * @param projectId - Project ID to use in file path (default: 'snowflake-dataset')\n * @param syncIntervalMs - Interval in milliseconds to sync changes to file (default: 5000ms)\n */\n constructor(projectId: string = 'snowflake-dataset', syncIntervalMs: number = 5000) {\n this.filePath = path.join(os.homedir(), '.superatom', 'projects', projectId, 'users.json');\n this.syncIntervalMs = syncIntervalMs;\n }\n\n /**\n * Initialize the UserManager by loading users from file and starting sync interval\n */\n async init(): Promise<void> {\n if (this.isInitialized) {\n return;\n }\n\n try {\n // Load users from file into memory\n await this.loadUsersFromFile();\n logger.info(`UserManager initialized with ${this.users.length} users`);\n\n // Start the sync interval\n this.startSyncInterval();\n this.isInitialized = true;\n } catch (error) {\n logger.error('Failed to initialize UserManager:', error);\n throw error;\n }\n }\n\n /**\n * Load users from the JSON file into memory\n */\n private async loadUsersFromFile(): Promise<void> {\n try {\n // Create directory structure if it doesn't exist\n const dir = path.dirname(this.filePath);\n if (!fs.existsSync(dir)) {\n logger.info(`Creating directory structure: ${dir}`);\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Create file with empty users array if it doesn't exist\n if (!fs.existsSync(this.filePath)) {\n logger.info(`Users file does not exist at ${this.filePath}, creating with empty users`);\n const initialData: UsersData = { users: [] };\n fs.writeFileSync(this.filePath, JSON.stringify(initialData, null, 4));\n this.users = [];\n this.hasChanged = false;\n return;\n }\n\n const fileContent = fs.readFileSync(this.filePath, 'utf-8');\n const data = JSON.parse(fileContent) as UsersData;\n\n this.users = Array.isArray(data.users) ? data.users : [];\n this.hasChanged = false;\n logger.debug(`Loaded ${this.users.length} users from file`);\n } catch (error) {\n logger.error('Failed to load users from file:', error);\n throw new Error(`Failed to load users from file: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n /**\n * Save users from memory to the JSON file\n */\n private async saveUsersToFile(): Promise<void> {\n if (!this.hasChanged) {\n return;\n }\n\n try {\n // Create directory if it doesn't exist\n const dir = path.dirname(this.filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n const data: UsersData = { users: this.users };\n fs.writeFileSync(this.filePath, JSON.stringify(data, null, 4));\n\n this.hasChanged = false;\n logger.debug(`Synced ${this.users.length} users to file`);\n } catch (error) {\n logger.error('Failed to save users to file:', error);\n throw new Error(`Failed to save users to file: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n /**\n * Start the periodic sync interval\n */\n private startSyncInterval(): void {\n if (this.syncInterval) {\n return;\n }\n\n this.syncInterval = setInterval(async () => {\n if (this.hasChanged) {\n try {\n await this.saveUsersToFile();\n logger.debug('Auto-sync: Users saved to file');\n } catch (error) {\n logger.error('Auto-sync failed:', error);\n }\n }\n }, this.syncIntervalMs);\n\n logger.debug(`Sync interval started (${this.syncIntervalMs}ms)`);\n }\n\n /**\n * Stop the periodic sync interval\n */\n public stopSyncInterval(): void {\n if (this.syncInterval) {\n clearInterval(this.syncInterval);\n this.syncInterval = null;\n logger.debug('Sync interval stopped');\n }\n }\n\n /**\n * Force sync users to file immediately\n */\n public async forceSync(): Promise<void> {\n await this.saveUsersToFile();\n }\n\n /**\n * Create a new user\n * @param user - User object to create\n * @returns The created user\n */\n public createUser(user: User): User {\n if (this.users.some(u => u.username === user.username)) {\n throw new Error(`User with username ${user.username} already exists`);\n }\n\n this.users.push(user);\n this.hasChanged = true;\n logger.debug(`User created: ${user.username}`);\n\n return user;\n }\n\n /**\n * Read a user by username\n * @param username - Username to retrieve\n * @returns The user if found, undefined otherwise\n */\n public getUser(username: string): User | undefined {\n return this.users.find(u => u.username === username);\n }\n\n /**\n * Read all users\n * @returns Array of all users\n */\n public getAllUsers(): User[] {\n return [...this.users];\n }\n\n /**\n * Find users by a predicate function\n * @param predicate - Function to filter users\n * @returns Array of matching users\n */\n public findUsers(predicate: (user: User) => boolean): User[] {\n return this.users.filter(predicate);\n }\n\n /**\n * Update an existing user by username\n * @param username - Username of user to update\n * @param updates - Partial user object with fields to update\n * @returns The updated user\n */\n public updateUser(username: string, updates: Partial<User>): User {\n const userIndex = this.users.findIndex(u => u.username === username);\n if (userIndex === -1) {\n throw new Error(`User with username ${username} not found`);\n }\n\n const updatedUser = { ...this.users[userIndex], ...updates };\n this.users[userIndex] = updatedUser;\n this.hasChanged = true;\n logger.debug(`User updated: ${username}`);\n\n return updatedUser;\n }\n\n /**\n * Delete a user by username\n * @param username - Username of user to delete\n * @returns true if user was deleted, false if not found\n */\n public deleteUser(username: string): boolean {\n const initialLength = this.users.length;\n this.users = this.users.filter(u => u.username !== username);\n\n if (this.users.length < initialLength) {\n this.hasChanged = true;\n logger.debug(`User deleted: ${username}`);\n return true;\n }\n return false;\n }\n\n /**\n * Delete all users\n */\n public deleteAllUsers(): void {\n if (this.users.length > 0) {\n this.users = [];\n this.hasChanged = true;\n logger.debug('All users deleted');\n }\n }\n\n /**\n * Get the count of users\n * @returns Number of users in memory\n */\n public getUserCount(): number {\n return this.users.length;\n }\n\n /**\n * Check if a user exists\n * @param username - Username to check\n * @returns true if user exists, false otherwise\n */\n public userExists(username: string): boolean {\n return this.users.some(u => u.username === username);\n }\n\n /**\n * Add a WebSocket ID to a user's wsIds array\n * @param username - Username to update\n * @param wsId - WebSocket ID to add\n * @returns true if successful, false if user not found\n */\n public addWsId(username: string, wsId: string): boolean {\n const user = this.getUser(username);\n if (!user) {\n return false;\n }\n\n if(!user.wsIds || !Array.isArray(user.wsIds)) {\n user.wsIds = [];\n }\n\n if (!user.wsIds.includes(wsId)) {\n user.wsIds.push(wsId);\n this.hasChanged = true;\n logger.debug(`WebSocket ID added to user ${username}: ${wsId}`);\n }\n\n return true;\n }\n\n /**\n * Remove a WebSocket ID from a user's wsIds array\n * @param username - Username to update\n * @param wsId - WebSocket ID to remove\n * @returns true if successful, false if user not found\n */\n public removeWsId(username: string, wsId: string): boolean {\n const user = this.getUser(username);\n if (!user) {\n return false;\n }\n\n if(!user.wsIds || !Array.isArray(user.wsIds)) {\n return false;\n }\n\n const initialLength = user.wsIds.length;\n user.wsIds = user.wsIds.filter(id => id !== wsId);\n\n if (user.wsIds.length < initialLength) {\n this.hasChanged = true;\n logger.debug(`WebSocket ID removed from user ${username}: ${wsId}`);\n }\n\n return true;\n }\n\n /**\n * Get the change status\n * @returns true if there are unsaved changes, false otherwise\n */\n public hasUnsavedChanges(): boolean {\n return this.hasChanged;\n }\n\n /**\n * Cleanup resources and stop sync interval\n */\n public async destroy(): Promise<void> {\n this.stopSyncInterval();\n // Final sync before cleanup\n if (this.hasChanged) {\n await this.saveUsersToFile();\n }\n logger.info('UserManager destroyed');\n }\n}\n","import fs from 'fs';\nimport path from 'path';\nimport os from 'os';\nimport { logger } from '../utils/logger';\nimport { DSLRendererProps, DSLRendererPropsSchema } from './types';\n\n/**\n * DashboardManager class to handle CRUD operations on dashboards\n * All operations read/write directly to files (no in-memory caching)\n */\nexport class DashboardManager {\n private dashboardsBasePath: string;\n private projectId: string;\n\n /**\n * Initialize DashboardManager with project ID\n * @param projectId - Project ID to use in file path\n */\n constructor(projectId: string = 'snowflake-dataset') {\n this.projectId = projectId;\n this.dashboardsBasePath = path.join(\n os.homedir(),\n '.superatom',\n 'projects',\n projectId,\n 'dashboards'\n );\n }\n\n /**\n * Get the file path for a specific dashboard\n * @param dashboardId - Dashboard ID\n * @returns Full path to dashboard data.json file\n */\n private getDashboardPath(dashboardId: string): string {\n return path.join(this.dashboardsBasePath, dashboardId, 'data.json');\n }\n\n /**\n * Create a new dashboard\n * @param dashboardId - Unique dashboard ID\n * @param dashboard - Dashboard data\n * @returns Created dashboard with metadata\n */\n createDashboard(dashboardId: string, dashboard: DSLRendererProps): DSLRendererProps {\n const dashboardPath = this.getDashboardPath(dashboardId);\n const dashboardDir = path.dirname(dashboardPath);\n\n // Check if dashboard already exists\n if (fs.existsSync(dashboardPath)) {\n throw new Error(`Dashboard '${dashboardId}' already exists`);\n }\n\n // Validate dashboard structure\n const validated = DSLRendererPropsSchema.parse(dashboard);\n\n // Create directory structure\n fs.mkdirSync(dashboardDir, { recursive: true });\n\n // Write dashboard to file\n fs.writeFileSync(dashboardPath, JSON.stringify(validated, null, 4));\n\n logger.info(`Dashboard created: ${dashboardId}`);\n return validated;\n }\n\n /**\n * Get a specific dashboard by ID\n * @param dashboardId - Dashboard ID\n * @returns Dashboard data or null if not found\n */\n getDashboard(dashboardId: string): DSLRendererProps | null {\n const dashboardPath = this.getDashboardPath(dashboardId);\n\n if (!fs.existsSync(dashboardPath)) {\n logger.warn(`Dashboard not found: ${dashboardId}`);\n return null;\n }\n\n try {\n const fileContent = fs.readFileSync(dashboardPath, 'utf-8');\n const dashboard = JSON.parse(fileContent) as DSLRendererProps;\n\n // Validate structure\n const validated = DSLRendererPropsSchema.parse(dashboard);\n return validated;\n } catch (error) {\n logger.error(`Failed to read dashboard ${dashboardId}:`, error);\n return null;\n }\n }\n\n /**\n * Get all dashboards\n * @returns Array of dashboard objects with their IDs\n */\n getAllDashboards(): Array<{ dashboardId: string; dashboard: DSLRendererProps }> {\n // Create base directory if it doesn't exist\n if (!fs.existsSync(this.dashboardsBasePath)) {\n fs.mkdirSync(this.dashboardsBasePath, { recursive: true });\n return [];\n }\n\n const dashboards: Array<{ dashboardId: string; dashboard: DSLRendererProps }> = [];\n\n try {\n const dashboardDirs = fs.readdirSync(this.dashboardsBasePath);\n\n for (const dashboardId of dashboardDirs) {\n const dashboardPath = this.getDashboardPath(dashboardId);\n\n if (fs.existsSync(dashboardPath)) {\n const dashboard = this.getDashboard(dashboardId);\n if (dashboard) {\n dashboards.push({ dashboardId, dashboard });\n }\n }\n }\n\n logger.debug(`Retrieved ${dashboards.length} dashboards`);\n return dashboards;\n } catch (error) {\n logger.error('Failed to get all dashboards:', error);\n return [];\n }\n }\n\n /**\n * Update an existing dashboard\n * @param dashboardId - Dashboard ID\n * @param dashboard - Updated dashboard data\n * @returns Updated dashboard or null if not found\n */\n updateDashboard(dashboardId: string, dashboard: DSLRendererProps): DSLRendererProps | null {\n const dashboardPath = this.getDashboardPath(dashboardId);\n\n if (!fs.existsSync(dashboardPath)) {\n logger.warn(`Dashboard not found for update: ${dashboardId}`);\n return null;\n }\n\n try {\n // Validate dashboard structure\n const validated = DSLRendererPropsSchema.parse(dashboard);\n\n // Write updated dashboard to file\n fs.writeFileSync(dashboardPath, JSON.stringify(validated, null, 4));\n\n logger.info(`Dashboard updated: ${dashboardId}`);\n return validated;\n } catch (error) {\n logger.error(`Failed to update dashboard ${dashboardId}:`, error);\n throw error;\n }\n }\n\n /**\n * Delete a dashboard\n * @param dashboardId - Dashboard ID\n * @returns True if deleted, false if not found\n */\n deleteDashboard(dashboardId: string): boolean {\n const dashboardPath = this.getDashboardPath(dashboardId);\n const dashboardDir = path.dirname(dashboardPath);\n\n if (!fs.existsSync(dashboardPath)) {\n logger.warn(`Dashboard not found for deletion: ${dashboardId}`);\n return false;\n }\n\n try {\n // Delete the entire dashboard directory\n fs.rmSync(dashboardDir, { recursive: true, force: true });\n\n logger.info(`Dashboard deleted: ${dashboardId}`);\n return true;\n } catch (error) {\n logger.error(`Failed to delete dashboard ${dashboardId}:`, error);\n return false;\n }\n }\n\n /**\n * Check if a dashboard exists\n * @param dashboardId - Dashboard ID\n * @returns True if dashboard exists, false otherwise\n */\n dashboardExists(dashboardId: string): boolean {\n const dashboardPath = this.getDashboardPath(dashboardId);\n return fs.existsSync(dashboardPath);\n }\n\n /**\n * Get dashboard count\n * @returns Number of dashboards\n */\n getDashboardCount(): number {\n if (!fs.existsSync(this.dashboardsBasePath)) {\n return 0;\n }\n\n try {\n const dashboardDirs = fs.readdirSync(this.dashboardsBasePath);\n return dashboardDirs.filter((dir) => {\n const dashboardPath = this.getDashboardPath(dir);\n return fs.existsSync(dashboardPath);\n }).length;\n } catch (error) {\n logger.error('Failed to get dashboard count:', error);\n return 0;\n }\n }\n}\n","import fs from 'fs';\nimport path from 'path';\nimport os from 'os';\nimport { logger } from '../utils/logger';\nimport { DSLRendererProps, DSLRendererPropsSchema } from './types';\n\n/**\n * ReportManager class to handle CRUD operations on reports\n * All operations read/write directly to files (no in-memory caching)\n */\nexport class ReportManager {\n private reportsBasePath: string;\n private projectId: string;\n\n /**\n * Initialize ReportManager with project ID\n * @param projectId - Project ID to use in file path\n */\n constructor(projectId: string = 'snowflake-dataset') {\n this.projectId = projectId;\n this.reportsBasePath = path.join(\n os.homedir(),\n '.superatom',\n 'projects',\n projectId,\n 'reports'\n );\n }\n\n /**\n * Get the file path for a specific report\n * @param reportId - Report ID\n * @returns Full path to report data.json file\n */\n private getReportPath(reportId: string): string {\n return path.join(this.reportsBasePath, reportId, 'data.json');\n }\n\n /**\n * Create a new report\n * @param reportId - Unique report ID\n * @param report - Report data\n * @returns Created report with metadata\n */\n createReport(reportId: string, report: DSLRendererProps): DSLRendererProps {\n const reportPath = this.getReportPath(reportId);\n const reportDir = path.dirname(reportPath);\n\n // Check if report already exists\n if (fs.existsSync(reportPath)) {\n throw new Error(`Report '${reportId}' already exists`);\n }\n\n // Validate report structure\n const validated = DSLRendererPropsSchema.parse(report);\n\n // Create directory structure\n fs.mkdirSync(reportDir, { recursive: true });\n\n // Write report to file\n fs.writeFileSync(reportPath, JSON.stringify(validated, null, 4));\n\n logger.info(`Report created: ${reportId}`);\n return validated;\n }\n\n /**\n * Get a specific report by ID\n * @param reportId - Report ID\n * @returns Report data or null if not found\n */\n getReport(reportId: string): DSLRendererProps | null {\n const reportPath = this.getReportPath(reportId);\n\n if (!fs.existsSync(reportPath)) {\n logger.warn(`Report not found: ${reportId}`);\n return null;\n }\n\n try {\n const fileContent = fs.readFileSync(reportPath, 'utf-8');\n const report = JSON.parse(fileContent) as DSLRendererProps;\n\n // Validate structure\n const validated = DSLRendererPropsSchema.parse(report);\n return validated;\n } catch (error) {\n logger.error(`Failed to read report ${reportId}:`, error);\n return null;\n }\n }\n\n /**\n * Get all reports\n * @returns Array of report objects with their IDs\n */\n getAllReports(): Array<{ reportId: string; report: DSLRendererProps }> {\n // Create base directory if it doesn't exist\n if (!fs.existsSync(this.reportsBasePath)) {\n fs.mkdirSync(this.reportsBasePath, { recursive: true });\n return [];\n }\n\n const reports: Array<{ reportId: string; report: DSLRendererProps }> = [];\n\n try {\n const reportDirs = fs.readdirSync(this.reportsBasePath);\n\n for (const reportId of reportDirs) {\n const reportPath = this.getReportPath(reportId);\n\n if (fs.existsSync(reportPath)) {\n const report = this.getReport(reportId);\n if (report) {\n reports.push({ reportId, report });\n }\n }\n }\n\n logger.debug(`Retrieved ${reports.length} reports`);\n return reports;\n } catch (error) {\n logger.error('Failed to get all reports:', error);\n return [];\n }\n }\n\n /**\n * Update an existing report\n * @param reportId - Report ID\n * @param report - Updated report data\n * @returns Updated report or null if not found\n */\n updateReport(reportId: string, report: DSLRendererProps): DSLRendererProps | null {\n const reportPath = this.getReportPath(reportId);\n\n if (!fs.existsSync(reportPath)) {\n logger.warn(`Report not found for update: ${reportId}`);\n return null;\n }\n\n try {\n // Validate report structure\n const validated = DSLRendererPropsSchema.parse(report);\n\n // Write updated report to file\n fs.writeFileSync(reportPath, JSON.stringify(validated, null, 4));\n\n logger.info(`Report updated: ${reportId}`);\n return validated;\n } catch (error) {\n logger.error(`Failed to update report ${reportId}:`, error);\n throw error;\n }\n }\n\n /**\n * Delete a report\n * @param reportId - Report ID\n * @returns True if deleted, false if not found\n */\n deleteReport(reportId: string): boolean {\n const reportPath = this.getReportPath(reportId);\n const reportDir = path.dirname(reportPath);\n\n if (!fs.existsSync(reportPath)) {\n logger.warn(`Report not found for deletion: ${reportId}`);\n return false;\n }\n\n try {\n // Delete the entire report directory\n fs.rmSync(reportDir, { recursive: true, force: true });\n\n logger.info(`Report deleted: ${reportId}`);\n return true;\n } catch (error) {\n logger.error(`Failed to delete report ${reportId}:`, error);\n return false;\n }\n }\n\n /**\n * Check if a report exists\n * @param reportId - Report ID\n * @returns True if report exists, false otherwise\n */\n reportExists(reportId: string): boolean {\n const reportPath = this.getReportPath(reportId);\n return fs.existsSync(reportPath);\n }\n\n /**\n * Get report count\n * @returns Number of reports\n */\n getReportCount(): number {\n if (!fs.existsSync(this.reportsBasePath)) {\n return 0;\n }\n\n try {\n const reportDirs = fs.readdirSync(this.reportsBasePath);\n return reportDirs.filter((dir) => {\n const reportPath = this.getReportPath(dir);\n return fs.existsSync(reportPath);\n }).length;\n } catch (error) {\n logger.error('Failed to get report count:', error);\n return 0;\n }\n }\n}\n","import { ThreadManager } from '../threads';\nimport { logger } from '../utils/logger';\nimport { STORAGE_CONFIG } from '../config/storage';\n\n/**\n * CleanupService handles cleanup of old threads and UIBlocks\n * to prevent memory bloat and maintain optimal performance\n */\nexport class CleanupService {\n private static instance: CleanupService;\n private cleanupInterval: NodeJS.Timeout | null = null;\n\n private constructor() {}\n\n /**\n * Get singleton instance of CleanupService\n */\n static getInstance(): CleanupService {\n if (!CleanupService.instance) {\n CleanupService.instance = new CleanupService();\n }\n return CleanupService.instance;\n }\n\n /**\n * Clean up old threads based on retention period\n * @param retentionDays - Number of days to keep threads (defaults to config)\n * @returns Number of threads deleted\n */\n cleanupOldThreads(retentionDays: number = STORAGE_CONFIG.THREAD_RETENTION_DAYS): number {\n const threadManager = ThreadManager.getInstance();\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - retentionDays);\n\n const threads = threadManager.getAllThreads();\n let deletedCount = 0;\n\n for (const thread of threads) {\n if (thread.getCreatedAt() < cutoffDate) {\n const threadId = thread.getId();\n if (threadManager.deleteThread(threadId)) {\n deletedCount++;\n logger.info(`Deleted old thread: ${threadId} (created: ${thread.getCreatedAt().toISOString()})`);\n }\n }\n }\n\n if (deletedCount > 0) {\n logger.info(`Cleanup: Deleted ${deletedCount} old threads (older than ${retentionDays} days)`);\n }\n\n return deletedCount;\n }\n\n /**\n * Clean up old UIBlocks within threads based on retention period\n * @param retentionDays - Number of days to keep UIBlocks (defaults to config)\n * @returns Object with number of UIBlocks deleted per thread\n */\n cleanupOldUIBlocks(retentionDays: number = STORAGE_CONFIG.UIBLOCK_RETENTION_DAYS): { [threadId: string]: number } {\n const threadManager = ThreadManager.getInstance();\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - retentionDays);\n\n const threads = threadManager.getAllThreads();\n const deletionStats: { [threadId: string]: number } = {};\n\n for (const thread of threads) {\n const uiblocks = thread.getUIBlocks();\n let deletedInThread = 0;\n\n for (const uiblock of uiblocks) {\n if (uiblock.getCreatedAt() < cutoffDate) {\n if (thread.removeUIBlock(uiblock.getId())) {\n deletedInThread++;\n }\n }\n }\n\n if (deletedInThread > 0) {\n deletionStats[thread.getId()] = deletedInThread;\n logger.info(\n `Deleted ${deletedInThread} old UIBlocks from thread ${thread.getId()} (older than ${retentionDays} days)`\n );\n }\n }\n\n const totalDeleted = Object.values(deletionStats).reduce((sum, count) => sum + count, 0);\n if (totalDeleted > 0) {\n logger.info(`Cleanup: Deleted ${totalDeleted} old UIBlocks across ${Object.keys(deletionStats).length} threads`);\n }\n\n return deletionStats;\n }\n\n /**\n * Clear all component data from UIBlocks to free memory\n * Keeps metadata but removes the actual data\n * @param retentionDays - Number of days to keep full data (defaults to config)\n * @returns Number of UIBlocks whose data was cleared\n */\n clearOldUIBlockData(retentionDays: number = STORAGE_CONFIG.UIBLOCK_RETENTION_DAYS): number {\n const threadManager = ThreadManager.getInstance();\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - retentionDays);\n\n const threads = threadManager.getAllThreads();\n let clearedCount = 0;\n\n for (const thread of threads) {\n const uiblocks = thread.getUIBlocks();\n\n for (const uiblock of uiblocks) {\n if (uiblock.getCreatedAt() < cutoffDate) {\n const componentData = uiblock.getComponentData();\n\n // Only clear if data exists\n if (componentData && Object.keys(componentData).length > 0) {\n // Keep metadata but clear actual data\n const metadata = {\n dataCleared: true,\n clearedAt: new Date().toISOString(),\n originalDataInfo: {\n totalRows: componentData.totalRows,\n storedRows: componentData.storedRows,\n isTruncated: componentData.isTruncated,\n },\n };\n\n uiblock.setComponentData({ ...metadata, data: null });\n clearedCount++;\n }\n }\n }\n }\n\n if (clearedCount > 0) {\n logger.info(`Cleanup: Cleared data from ${clearedCount} old UIBlocks (older than ${retentionDays} days)`);\n }\n\n return clearedCount;\n }\n\n /**\n * Run full cleanup (threads, UIBlocks, and data)\n * @returns Cleanup statistics\n */\n runFullCleanup(): {\n threadsDeleted: number;\n uiblocksDeleted: { [threadId: string]: number };\n dataCleared: number;\n } {\n logger.info('Starting full cleanup...');\n\n const stats = {\n threadsDeleted: this.cleanupOldThreads(),\n uiblocksDeleted: this.cleanupOldUIBlocks(),\n dataCleared: this.clearOldUIBlockData(),\n };\n\n const totalUIBlocksDeleted = Object.values(stats.uiblocksDeleted).reduce((sum, count) => sum + count, 0);\n\n logger.info(\n `Full cleanup completed: ${stats.threadsDeleted} threads, ${totalUIBlocksDeleted} UIBlocks deleted, ${stats.dataCleared} UIBlock data cleared`\n );\n\n return stats;\n }\n\n /**\n * Start automatic cleanup at regular intervals\n * @param intervalHours - Hours between cleanup runs (default: 24)\n */\n startAutoCleanup(intervalHours: number = 24): void {\n if (this.cleanupInterval) {\n logger.warn('Auto cleanup is already running');\n\n //stop this and run with new interval\n\n \n return;\n }\n\n const intervalMs = intervalHours * 60 * 60 * 1000;\n\n // Run initial cleanup\n this.runFullCleanup();\n\n // Schedule recurring cleanup\n this.cleanupInterval = setInterval(() => {\n this.runFullCleanup();\n }, intervalMs);\n\n logger.info(`Auto cleanup started: running every ${intervalHours} hours`);\n }\n\n /**\n * Stop automatic cleanup\n */\n stopAutoCleanup(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n logger.info('Auto cleanup stopped');\n }\n }\n\n /**\n * Check if auto cleanup is running\n */\n isAutoCleanupRunning(): boolean {\n return this.cleanupInterval !== null;\n }\n\n /**\n * Get current memory usage statistics\n */\n getMemoryStats(): {\n threadCount: number;\n totalUIBlocks: number;\n avgUIBlocksPerThread: number;\n } {\n const threadManager = ThreadManager.getInstance();\n const threads = threadManager.getAllThreads();\n const threadCount = threads.length;\n\n let totalUIBlocks = 0;\n for (const thread of threads) {\n totalUIBlocks += thread.getUIBlockCount();\n }\n\n return {\n threadCount,\n totalUIBlocks,\n avgUIBlocksPerThread: threadCount > 0 ? totalUIBlocks / threadCount : 0,\n };\n }\n}\n","import { createWebSocket } from './websocket';\nimport {\n IncomingMessageSchema,\n type Message,\n type IncomingMessage,\n type SuperatomSDKConfig,\n type CollectionRegistry,\n type CollectionHandler,\n type CollectionOperation,\n Component,\n LLMProvider,\n} from './types';\nimport { logger } from './utils/logger';\nimport { handleDataRequest } from './handlers/data-request';\nimport { handleBundleRequest } from './handlers/bundle-request';\nimport { handleAuthLoginRequest } from './handlers/auth-login-requests';\nimport { handleAuthVerifyRequest } from './handlers/auth-verify-request';\nimport { handleUserPromptRequest } from './handlers/user-prompt-request';\nimport { handleUserPromptSuggestions } from './handlers/user-prompt-suggestions';\nimport { handleActionsRequest } from './handlers/actions-request';\nimport { handleComponentListResponse } from './handlers/components-list-response';\nimport { handleUsersRequest } from './handlers/users';\nimport { handleDashboardsRequest } from './handlers/dashboards';\nimport { handleReportsRequest } from './handlers/reports';\nimport { getLLMProviders } from './userResponse';\nimport { setUserManager, cleanupUserStorage } from './auth/user-storage';\nimport { UserManager } from './auth/user-manager';\nimport { setDashboardManager } from './dashboards/dashboard-storage';\nimport { DashboardManager } from './dashboards/dashboard-manager';\nimport { setReportManager } from './reports/report-storage';\nimport { ReportManager } from './reports/report-manager';\nimport { promptLoader } from './userResponse/prompt-loader';\n\nexport const SDK_VERSION = '0.0.8';\n\nconst DEFAULT_WS_URL = 'wss://ws.superatom.ai/websocket';\n\ntype MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;\n\nexport class SuperatomSDK {\n private ws: ReturnType<typeof createWebSocket> | null = null;\n private url: string;\n private apiKey: string;\n private projectId: string;\n private userId: string;\n private type: string;\n private bundleDir: string | undefined;\n private messageHandlers: Map<string, (message: IncomingMessage) => void> = new Map();\n private messageTypeHandlers: Map<string, MessageTypeHandler> = new Map();\n private connected: boolean = false;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = 5;\n private collections: CollectionRegistry = {};\n\tprivate components: Component[] = [];\n private anthropicApiKey: string;\n private groqApiKey: string;\n private llmProviders: LLMProvider[];\n private userManager: UserManager;\n private dashboardManager: DashboardManager;\n private reportManager: ReportManager;\n\n constructor(config: SuperatomSDKConfig) {\n this.apiKey = config.apiKey;\n this.projectId = config.projectId;\n this.userId = config.userId || 'anonymous';\n this.type = config.type || 'data-agent';\n this.bundleDir = config.bundleDir;\n this.url = config.url || process.env.SA_WEBSOCKET_URL || DEFAULT_WS_URL;\n this.anthropicApiKey = config.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || '';\n this.groqApiKey = config.GROQ_API_KEY || process.env.GROQ_API_KEY || '';\n this.llmProviders = config.LLM_PROVIDERS || getLLMProviders();\n\n // Initialize UserManager for this SDK instance\n this.userManager = new UserManager(this.projectId, 5000);\n\n // Initialize DashboardManager for this SDK instance\n this.dashboardManager = new DashboardManager(this.projectId);\n\n // Initialize ReportManager for this SDK instance\n this.reportManager = new ReportManager(this.projectId);\n\n // Initialize PromptLoader (load prompts into memory)\n this.initializePromptLoader(config.promptsDir).catch((error) => {\n logger.error('Failed to initialize PromptLoader:', error);\n });\n\n // Initialize UserManager with projectId (startup)\n this.initializeUserManager().catch((error) => {\n logger.error('Failed to initialize UserManager:', error);\n });\n\n // Initialize DashboardManager\n this.initializeDashboardManager();\n\n // Initialize ReportManager\n this.initializeReportManager();\n\n // Automatically connect on instantiation\n this.connect().catch((error) => {\n logger.error('Failed to connect to Superatom:', error);\n });\n\n //\n }\n\n /**\n * Initialize PromptLoader and load prompts into memory\n */\n private async initializePromptLoader(promptsDir?: string): Promise<void> {\n try {\n // Set custom prompts directory if provided\n if (promptsDir) {\n promptLoader.setPromptsDir(promptsDir);\n }\n\n await promptLoader.initialize();\n logger.info(`PromptLoader initialized with ${promptLoader.getCacheSize()} prompts from ${promptLoader.getPromptsDir()}`);\n } catch (error) {\n logger.error('Failed to initialize PromptLoader:', error);\n throw error;\n }\n }\n\n /**\n * Initialize UserManager for the project\n */\n private async initializeUserManager(): Promise<void> {\n try {\n await this.userManager.init();\n // Set the global reference for backward compatibility with existing auth code\n setUserManager(this.userManager);\n logger.info(`UserManager initialized for project: ${this.projectId}`);\n } catch (error) {\n logger.error('Failed to initialize UserManager:', error);\n throw error;\n }\n }\n\n /**\n * Get the UserManager instance for this SDK\n */\n public getUserManager(): UserManager {\n return this.userManager;\n }\n\n /**\n * Initialize DashboardManager for the project\n */\n private initializeDashboardManager(): void {\n // Set the global reference for dashboard operations\n setDashboardManager(this.dashboardManager);\n logger.info(`DashboardManager initialized for project: ${this.projectId}`);\n }\n\n /**\n * Get the DashboardManager instance for this SDK\n */\n public getDashboardManager(): DashboardManager {\n return this.dashboardManager;\n }\n\n /**\n * Initialize ReportManager for the project\n */\n private initializeReportManager(): void {\n // Set the global reference for report operations\n setReportManager(this.reportManager);\n logger.info(`ReportManager initialized for project: ${this.projectId}`);\n }\n\n /**\n * Get the ReportManager instance for this SDK\n */\n public getReportManager(): ReportManager {\n return this.reportManager;\n }\n\n /**\n * Connect to the Superatom WebSocket service\n */\n async connect(): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n // Add all required query parameters\n const url = new URL(this.url);\n url.searchParams.set('apiKey', this.apiKey);\n url.searchParams.set('projectId', this.projectId);\n url.searchParams.set('userId', this.userId);\n url.searchParams.set('type', this.type);\n\n logger.info(`Connecting to WebSocket: ${url.host}`);\n\n this.ws = createWebSocket(url.toString());\n\n this.ws.addEventListener('open', () => {\n this.connected = true;\n this.reconnectAttempts = 0;\n logger.info('WebSocket connected successfully');\n resolve();\n });\n\n this.ws.addEventListener('message', (event: any) => {\n this.handleMessage(event.data);\n });\n\n this.ws.addEventListener('error', (error: any) => {\n logger.error('WebSocket error:', error);\n reject(error);\n });\n\n this.ws.addEventListener('close', () => {\n this.connected = false;\n logger.warn('WebSocket closed');\n this.handleReconnect();\n });\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Handle incoming WebSocket messages\n */\n private handleMessage(data: string): void {\n try {\n const parsed = JSON.parse(data);\n const message = IncomingMessageSchema.parse(parsed);\n\n logger.debug('Received message:', message.type);\n\n // Route message by type\n switch (message.type) {\n case 'DATA_REQ':\n handleDataRequest(parsed, this.collections, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle data request:', error);\n });\n break;\n\n case 'BUNDLE_REQ':\n handleBundleRequest(parsed, this.bundleDir, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle bundle request:', error);\n });\n break;\n\n case 'AUTH_LOGIN_REQ':\n handleAuthLoginRequest(parsed, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle auth login request:', error);\n });\n break;\n\n case 'AUTH_VERIFY_REQ':\n handleAuthVerifyRequest(parsed, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle auth verify request:', error);\n });\n break;\n\n case 'USER_PROMPT_REQ':\n handleUserPromptRequest(parsed, this.components, (msg) => this.send(msg), this.anthropicApiKey, this.groqApiKey, this.llmProviders).catch((error) => {\n logger.error('Failed to handle user prompt request:', error);\n });\n break;\n\n case 'ACTIONS':\n handleActionsRequest(parsed, (msg) => this.send(msg), this.anthropicApiKey, this.groqApiKey, this.llmProviders).catch((error) => {\n logger.error('Failed to handle actions request:', error);\n });\n break;\n\n case 'USER_PROMPT_SUGGESTIONS_REQ':\n handleUserPromptSuggestions(parsed, this.components, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle user prompt suggestions request:', error);\n });\n break;\n\n case 'COMPONENT_LIST_RES':\n handleComponentListResponse(parsed, (com) => this.storeComponents(com)).catch((error) => {\n logger.error('Failed to handle component list request:', error);\n });\n break;\n\n case 'USERS':\n handleUsersRequest(parsed, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle users request:', error);\n });\n break;\n\n case 'DASHBOARDS':\n handleDashboardsRequest(parsed, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle dashboards request:', error);\n });\n break;\n\n case 'REPORTS':\n handleReportsRequest(parsed, (msg) => this.send(msg)).catch((error) => {\n logger.error('Failed to handle reports request:', error);\n });\n break;\n\n default:\n // Check for custom message type handlers\n const handler = this.messageTypeHandlers.get(message.type);\n if (handler) {\n Promise.resolve(handler(message)).catch((error) => {\n logger.error(`Failed to handle ${message.type}:`, error);\n });\n }\n break;\n }\n\n // Call registered message handlers\n this.messageHandlers.forEach((handler) => {\n handler(message);\n });\n } catch (error) {\n logger.error('Failed to parse incoming message:', error);\n }\n }\n\n /**\n * Send a message to the Superatom service\n */\n send(message: Message): void {\n if (!this.ws || !this.connected) {\n throw new Error('WebSocket is not connected. Call connect() first.');\n }\n\n if (this.ws.readyState !== this.ws.OPEN) {\n throw new Error('WebSocket is not ready to send messages.');\n }\n\n const payload = JSON.stringify(message);\n this.ws.send(payload);\n }\n\n /**\n * Register a message handler to receive all messages\n */\n onMessage(handler: (message: IncomingMessage) => void): () => void {\n const id = Math.random().toString(36).substring(7);\n this.messageHandlers.set(id, handler);\n\n // Return unsubscribe function\n return () => {\n this.messageHandlers.delete(id);\n };\n }\n\n /**\n * Register a handler for a specific message type\n */\n onMessageType(type: string, handler: MessageTypeHandler): () => void {\n this.messageTypeHandlers.set(type, handler);\n\n // Return unsubscribe function\n return () => {\n this.messageTypeHandlers.delete(type);\n };\n }\n\n /**\n * Disconnect from the WebSocket service\n */\n disconnect(): void {\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n this.connected = false;\n }\n }\n\n /**\n * Cleanup and disconnect - stops reconnection attempts and closes the connection\n */\n async destroy(): Promise<void> {\n // Prevent further reconnection attempts\n this.maxReconnectAttempts = 0;\n this.reconnectAttempts = 0;\n\n // Clear all message handlers\n this.messageHandlers.clear();\n\n // Clear all collections\n this.collections = {};\n\n // Cleanup UserManager\n try {\n await cleanupUserStorage();\n logger.info('UserManager cleanup completed');\n } catch (error) {\n logger.error('Error during UserManager cleanup:', error);\n }\n\n // Disconnect\n this.disconnect();\n }\n\n /**\n * Check if the SDK is currently connected\n */\n isConnected(): boolean {\n return this.connected && this.ws !== null && this.ws.readyState === this.ws.OPEN;\n }\n\n /**\n * Register a collection handler for data operations\n */\n addCollection<TParams = any, TResult = any>(\n collectionName: string,\n operation: CollectionOperation | string,\n handler: CollectionHandler<TParams, TResult>\n ): void {\n if (!this.collections[collectionName]) {\n this.collections[collectionName] = {};\n }\n this.collections[collectionName][operation] = handler;\n }\n\n private handleReconnect(): void {\n if (this.reconnectAttempts < this.maxReconnectAttempts) {\n this.reconnectAttempts++;\n const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000);\n\n setTimeout(() => {\n logger.info(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);\n this.connect().catch((error) => {\n logger.error('Reconnection failed:', error);\n });\n }, delay);\n } else {\n logger.error('Max reconnection attempts reached');\n }\n }\n\n private storeComponents(components: Component[]){\n this.components = components;\n }\n \n}\n\n// Export types\nexport type { Message, IncomingMessage, SuperatomSDKConfig, CollectionHandler, CollectionOperation } from './types';\nexport {LLM} from './llm';\nexport { UserManager, type User, type UsersData } from './auth/user-manager';\nexport { UILogCollector, type CapturedLog } from './utils/log-collector';\nexport { Thread, UIBlock, ThreadManager, type Action } from './threads';\nexport { CleanupService } from './services/cleanup-service';\nexport { STORAGE_CONFIG } from './config/storage';\nexport { CONTEXT_CONFIG } from './config/context';"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,OAAS;AAAA,MACT,SAAW;AAAA,QACT,KAAK;AAAA,UACH,OAAS;AAAA,UACT,SAAW;AAAA,UACX,SAAW;AAAA,QACb;AAAA,QACA,YAAY;AAAA,QACZ,eAAe;AAAA,QACf,qBAAqB;AAAA,QACrB,wBAAwB;AAAA,QACxB,qBAAqB;AAAA,QACrB,wBAAwB;AAAA,QACxB,kBAAkB;AAAA,MACpB;AAAA,MACA,SAAW;AAAA,QACT,aAAa;AAAA,QACb,MAAQ;AAAA,QACR,SAAW;AAAA,QACX,MAAQ;AAAA,QACR,iBAAiB;AAAA,QACjB,YAAc;AAAA,QACd,SAAW;AAAA,MACb;AAAA,MACA,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,UAAY;AAAA,MACZ,SAAW;AAAA,MACX,UAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,gBAAkB;AAAA,MAClB,SAAW;AAAA,MACX,iBAAmB;AAAA,QACjB,eAAe;AAAA,QACf,SAAW;AAAA,QACX,OAAS;AAAA,QACT,UAAY;AAAA,QACZ,oBAAoB;AAAA,QACpB,KAAO;AAAA,QACP,YAAc;AAAA,MAChB;AAAA,MACA,SAAW;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA,SAAW;AAAA,QACT,IAAM;AAAA,MACR;AAAA,IACF;AAAA;AAAA;;;AC7DA;AAAA;AAAA;AAAA,QAAMA,MAAK,UAAQ,IAAI;AACvB,QAAMC,QAAO,UAAQ,MAAM;AAC3B,QAAMC,MA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AAa,KAAK,OAAO,QAAQ,KAAK,GAAG,eAAe,KAAK,GAAG;AAAA,EAC9E;AAAA;AAAA;AAAA;AAAA,EAKA,cACE,gBACA,WACA,SACM;AACN,QAAI,CAAC,KAAK,YAAY,cAAc,GAAG;AACrC,WAAK,YAAY,cAAc,IAAI,CAAC;AAAA,IACtC;AACA,SAAK,YAAY,cAAc,EAAE,SAAS,IAAI;AAAA,EAChD;AAAA,EAEQ,kBAAwB;AAC9B,QAAI,KAAK,oBAAoB,KAAK,sBAAsB;AACtD,WAAK;AACL,YAAM,QAAQ,KAAK,IAAI,MAAO,KAAK,IAAI,GAAG,KAAK,iBAAiB,GAAG,GAAK;AAExE,iBAAW,MAAM;AACf,eAAO,KAAK,4BAA4B,KAAK,iBAAiB,IAAI,KAAK,oBAAoB,MAAM;AACjG,aAAK,QAAQ,EAAE,MAAM,CAAC,UAAU;AAC9B,iBAAO,MAAM,wBAAwB,KAAK;AAAA,QAC5C,CAAC;AAAA,MACH,GAAG,KAAK;AAAA,IACV,OAAO;AACL,aAAO,MAAM,mCAAmC;AAAA,IAClD;AAAA,EACF;AAAA,EAEQ,gBAAgB,YAAwB;AAC9C,SAAK,aAAa;AAAA,EACpB;AAEF;","names":["fs","path","os","crypto","z","z","ExpressionSchema","BindingSchema","ForDirectiveSchema","QuerySpecSchema","UIElementSchema","UIComponentSchema","DSLRendererPropsSchema","z","DSLRendererPropsSchema","size","randomUUID","result","sendDataResponse","sendDataResponse","path","fs","path","fs","schema","fs","path","path","fs","dotenv","import_dotenv","dotenv","import_dotenv","dotenv","sendDataResponse","sendResponse","sendResponse","sendResponse","dashboardManager","handleCreate","handleUpdate","handleDelete","handleGetAll","handleGetOne","sendResponse","reportManager","handleCreate","handleUpdate","handleDelete","handleGetAll","handleGetOne","fs","path","path","fs","fs","path","os","path","os","fs","fs","path","os","path","os","fs","DSLRendererPropsSchema"]}